Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: custom Macro MCP via ACP --> inferred tools (#6154)

Wolf Mermelsteinb03d31e5c92c
diff --git a/Cargo.lock b/Cargo.lock
index ff12f7a957..d2e4f6fe51 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -212,6 +212,7 @@ dependencies = [
"agent_runtime_protocol",
"clap",
"insta",
+ "lazy-regex",
"macro_user_id",
"macro_uuid",
"non_empty",
@@ -8994,6 +8995,29 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "lazy-regex"
+version = "3.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4994ba703f78b083e2f7946dac9251abd83fd43a0365f030e99b69be5b4b9ef9"
+dependencies = [
+ "lazy-regex-proc_macros",
+ "once_cell",
+ "regex",
+]
+
+[[package]]
+name = "lazy-regex-proc_macros"
+version = "3.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd97232314824e6dbef1918a871bb93f51070455e3715bf26e19a6d01aa977a0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "regex",
+ "syn 2.0.117",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -13377,9 +13401,9 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.12.3"
+version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
@@ -13389,9 +13413,9 @@ dependencies = [
[[package]]
name = "regex-automata"
-version = "0.4.14"
+version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
@@ -13406,9 +13430,9 @@ checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
[[package]]
name = "regex-syntax"
-version = "0.8.10"
+version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "reminders"
diff --git a/Cargo.toml b/Cargo.toml
index f6174016bc..c59674a54a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -209,6 +209,7 @@ jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features
"rust_crypto",
] }
lambda_runtime = "0.13.0"
+lazy-regex = "3.6.1"
lazy_static = "1.5.0"
livekit-api = { version = "0.4.16", default-features = false, features = [
"access-token",
diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
new file mode 100644
index 0000000000..21c5cedda1
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx
@@ -0,0 +1,108 @@
+/**
+ * A Macro tool the fold recognized by name — reached over Macro's MCP
+ * server, or called natively by Macro's own agent.
+ *
+ * The fold has already named the tool and removed any MCP envelope, so
+ * `detail.input` / `detail.output` are the tool's own JSON. When the chat
+ * block has a component for that tool, it renders here with that JSON — the
+ * same chip a chat shows for `ReadContent`, `ListEntities`, `CreateDocument`
+ * and the rest. The chat renderer validates the JSON against the tool's
+ * schema and shows nothing for a shape it does not know; then, or when a
+ * chat component assumes chat context it does not have here, the card falls
+ * back to a labelled row with the JSON.
+ */
+
+import { RenderTool } from '@core/component/AI/component/tool/handler';
+import type { ToolDetail } from '@service-agent-fold/generated/types';
+import {
+ deserializeToolCall,
+ deserializeToolResponse,
+} from '@service-cognition/generated/tools/tool';
+import { createMemo, ErrorBoundary, type JSX, Show } from 'solid-js';
+import { FoldedOutput, ToolCard } from '../../ui';
+import type { ToolCallCommon, ToolCallContext } from './shared';
+
+type MacroDetail = Extract<ToolDetail, { kind: 'macro' }>;
+
+export function MacroToolCall(props: {
+ detail: MacroDetail;
+ common: ToolCallCommon;
+ context?: ToolCallContext;
+}): JSX.Element {
+ const finished = () =>
+ props.common.status === 'completed' || props.common.status === 'failed';
+ // The chat renderer renders nothing for a tool it has no component for or
+ // arguments that do not fit the tool's schema, and it shows a *completed*
+ // call whose response it cannot read as failed. A call it would drop or
+ // misreport keeps the generic card, so no row vanishes or lies.
+ const chatRenders = createMemo(() => {
+ if (props.detail.error != null) return false;
+ const call = deserializeToolCall({
+ id: props.common.id,
+ name: props.common.label,
+ json: props.detail.input,
+ });
+ if (call.isErr()) return false;
+ if (props.common.status !== 'completed') return true;
+ return deserializeToolResponse({
+ id: props.common.id,
+ name: props.common.label,
+ json: props.detail.output,
+ }).isOk();
+ });
+
+ return (
+ <Show when={chatRenders()} fallback={<GenericMacroToolCall {...props} />}>
+ <ErrorBoundary fallback={<GenericMacroToolCall {...props} />}>
+ <RenderTool
+ tool_id={props.common.id}
+ name={props.common.label}
+ json={props.detail.input}
+ response={
+ props.detail.output == null
+ ? undefined
+ : { json: props.detail.output, name: props.common.label }
+ }
+ chat_id={props.context?.sessionId ?? ''}
+ message_id={props.context?.messageId ?? ''}
+ part_index={props.context?.partIndex ?? 0}
+ isComplete={finished()}
+ renderContext={{
+ renderContext: { isStreaming: !finished(), grouped: false },
+ }}
+ />
+ </ErrorBoundary>
+ </Show>
+ );
+}
+
+/** The labelled row with the tool's own JSON, for a tool the chat has no component for. */
+function GenericMacroToolCall(props: {
+ detail: MacroDetail;
+ common: ToolCallCommon;
+}): JSX.Element {
+ const body = () => {
+ const sections: string[] = [];
+ if (props.detail.input != null) {
+ sections.push(JSON.stringify(props.detail.input, null, 2));
+ }
+ if (props.detail.error != null) {
+ sections.push(props.detail.error);
+ } else if (props.detail.output != null) {
+ sections.push(JSON.stringify(props.detail.output, null, 2));
+ }
+ return sections.join('\n\n');
+ };
+
+ return (
+ <ToolCard
+ title={props.common.label}
+ subtitle={props.detail.error ?? undefined}
+ status={props.common.status}
+ muted={props.common.muted}
+ trailing={props.common.trailing}
+ >
+ <Show when={body()}>{(text) => <FoldedOutput text={text()} />}</Show>
+ </ToolCard>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
new file mode 100644
index 0000000000..8274c544d7
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/SubagentToolCall.tsx
@@ -0,0 +1,158 @@
+/**
+ * Work the agent delegated to another agent: the brief, whatever of the
+ * subagent's own activity the harness attributed to it (nested through the
+ * same part components), and what it reported back.
+ */
+
+import type {
+ MessagePart,
+ SubagentResult,
+ ToolDetail,
+} from '@service-agent-fold/generated/types';
+import { For, type JSX, Show } from 'solid-js';
+import { match } from 'ts-pattern';
+import { FoldedOutput, Thought, ToolCard } from '../../ui';
+import type { ToolCallCommon, ToolCallContext } from './shared';
+import { TextPart } from './TextPart';
+import { ToolCallPart } from './ToolCallPart';
+
+type SubagentDetail = Extract<ToolDetail, { kind: 'subagent' }>;
+
+/** `1 tool · 3.5s · 26k tokens`, from whatever the harness reported. */
+function resultSummary(result: SubagentResult): string | undefined {
+ const facts: string[] = [];
+ if (result.toolUses != null) {
+ facts.push(result.toolUses === 1 ? '1 tool' : `${result.toolUses} tools`);
+ }
+ if (result.durationMs != null) {
+ facts.push(
+ result.durationMs >= 1000
+ ? `${(result.durationMs / 1000).toFixed(1)}s`
+ : `${result.durationMs}ms`
+ );
+ }
+ if (result.tokens != null) {
+ facts.push(
+ result.tokens >= 1000
+ ? `${Math.round(result.tokens / 1000)}k tokens`
+ : `${result.tokens} tokens`
+ );
+ }
+ return facts.length > 0 ? facts.join(' · ') : undefined;
+}
+
+/** A subagent's nested part: prose, reasoning, or one of its tool calls. */
+function ChildPart(props: {
+ part: MessagePart;
+ index: number;
+ context?: ToolCallContext;
+}) {
+ const inFlight = () => props.context?.inFlight ?? false;
+ return (
+ match(props.part)
+ .with({ kind: 'text' }, (part) => <TextPart text={part.text} />)
+ .with({ kind: 'thought' }, (part) => (
+ <Thought text={part.text} active={inFlight()} />
+ ))
+ .with({ kind: 'tool_use' }, (part) => (
+ <ToolCallPart
+ part={part}
+ context={
+ props.context && {
+ ...props.context,
+ // A child's slot is its own; the parent's index is not it.
+ partIndex: props.index,
+ }
+ }
+ />
+ ))
+ // A subagent's permission, plan, or control has nowhere to nest today;
+ // the harnesses that attribute children only attribute tool calls.
+ .otherwise(() => null)
+ );
+}
+
+export function SubagentToolCall(props: {
+ detail: SubagentDetail;
+ common: ToolCallCommon;
+ context?: ToolCallContext;
+}): JSX.Element {
+ const working = () =>
+ props.common.status === 'pending' || props.common.status === 'running';
+ // Children only shimmer while both the subagent and the turn are live.
+ const childContext = () =>
+ props.context && {
+ ...props.context,
+ inFlight: working() && props.context.inFlight,
+ };
+ const subtitle = () =>
+ [props.detail.agentType, props.detail.background ? 'background' : undefined]
+ .filter(Boolean)
+ .join(' · ') || undefined;
+ const trailing = () =>
+ props.common.trailing ??
+ (props.detail.result?.error != null ? (
+ <span class="text-ink">Failed</span>
+ ) : props.detail.result ? (
+ <Show when={resultSummary(props.detail.result)}>
+ {(summary) => <span>{summary()}</span>}
+ </Show>
+ ) : undefined);
+ const hasBody = () =>
+ props.detail.prompt != null ||
+ props.detail.children.length > 0 ||
+ props.detail.result != null;
+
+ return (
+ <ToolCard
+ title={props.detail.title}
+ subtitle={subtitle()}
+ status={props.common.status}
+ muted={props.common.muted || props.detail.result?.error != null}
+ trailing={trailing()}
+ defaultOpen={props.detail.children.length > 0}
+ >
+ <Show when={hasBody()}>
+ <div class="flex flex-col gap-2">
+ <Show when={props.detail.prompt}>
+ {(prompt) => (
+ <blockquote class="border-l-2 border-edge-muted pl-2 text-xs text-ink-muted whitespace-pre-wrap wrap-break-word">
+ {prompt()}
+ </blockquote>
+ )}
+ </Show>
+ <Show when={props.detail.children.length > 0}>
+ <div class="flex flex-col gap-1 border-l-2 border-edge-muted pl-2">
+ <For each={props.detail.children}>
+ {(child, index) => (
+ <ChildPart
+ part={child}
+ index={index()}
+ context={childContext()}
+ />
+ )}
+ </For>
+ </div>
+ </Show>
+ <Show when={props.detail.result}>
+ {(result) => (
+ <div class="flex flex-col gap-1">
+ <Show when={result().error}>
+ {(error) => <FoldedOutput text={error()} />}
+ </Show>
+ <Show when={result().text}>
+ {(text) => <TextPart text={text()} />}
+ </Show>
+ <Show when={result().model}>
+ {(model) => (
+ <span class="text-xs text-ink-extra-muted">{model()}</span>
+ )}
+ </Show>
+ </div>
+ )}
+ </Show>
+ </div>
+ </Show>
+ </ToolCard>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
index 583a9bebae..f6fa6c55c3 100644
--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx
@@ -22,6 +22,11 @@ vi.mock('@core/component/AI/component/tool/handler', () => ({
<div
data-complete={String(props.isComplete)}
data-has-response={String(props.response !== undefined)}
+ data-response={
+ props.response === undefined
+ ? undefined
+ : JSON.stringify(props.response.json)
+ }
data-testid="macro-tool"
>
{props.name}
@@ -29,6 +34,26 @@ vi.mock('@core/component/AI/component/tool/handler', () => ({
),
}));
+// The entity link a finished email's outcome carries needs the query client
+// and the split layout; a marker carrying the id is enough here.
+vi.mock('@core/component/ItemPreview', () => ({
+ ItemPreview: (props: { id: string; type: string }) => (
+ <span
+ data-id={props.id}
+ data-testid="item-preview"
+ data-type={props.type}
+ />
+ ),
+}));
+
+// Markdown rendering pulls in the Lexical editor; the nested transcript's
+// prose is a marker here.
+vi.mock('./TextPart', () => ({
+ TextPart: (props: { text: string }) => (
+ <p data-testid="text-part">{props.text}</p>
+ ),
+}));
+
// The ui primitives are mocked (the AssistantMessageParts.test.tsx idiom):
// ToolCard pulls in kobalte + svg sprites and PierreDiff pulls in the diff
// engine — the layer under test here is the per-kind card components and the
@@ -67,23 +92,25 @@ vi.mock('../../ui', () => ({
FoldedPathList: (props: { paths: string[] }) => (
<div data-testid="path-list">{props.paths.join(',')}</div>
),
+ Thought: (props: { text: string }) => (
+ <div data-testid="thought">{props.text}</div>
+ ),
}));
type ToolUsePart = Extract<MessagePart, { kind: 'tool_use' }>;
function toolUse(
detail: ToolUsePart['detail'],
- overrides?: Partial<ToolUsePart>
+ overrides?: Partial<Omit<ToolUsePart, 'name'>> & { name?: string }
): ToolUsePart {
+ const { name, ...rest } = overrides ?? {};
return {
kind: 'tool_use',
id: 'call-1',
- label: 'Tool',
+ name: { kind: 'native', name: name ?? 'Tool' },
status: 'completed',
detail,
- rawInput: null,
- rawOutput: null,
- ...overrides,
+ ...rest,
};
}
@@ -98,7 +125,7 @@ describe('ToolCallPart routing', () => {
output: 'running 14 tests',
exitCode: 0,
},
- { label: 'Bash' }
+ { name: 'Bash' }
)}
/>
));
@@ -111,6 +138,23 @@ describe('ToolCallPart routing', () => {
);
});
+ it('shows an MCP tool by its own name, without the server namespace', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={{
+ ...toolUse({
+ kind: 'other',
+ acpKind: 'other',
+ output: null,
+ input: null,
+ }),
+ name: { kind: 'mcp', server: 'deepwiki', tool: 'ask' },
+ }}
+ />
+ ));
+ expect(rendered.getByTestId('title').textContent).toBe('ask');
+ });
+
it('renders an edit with computed +/− counts and the diff body', () => {
const rendered = render(() => (
<ToolCallPart
@@ -154,33 +198,37 @@ describe('ToolCallPart routing', () => {
});
});
-describe('ToolCallPart Macro tool routing', () => {
- // A ReadContent call still in flight: name and arguments parse, no
- // response required yet.
- const macroPart = (overrides?: Partial<ToolUsePart>) =>
+describe('ToolCallPart Macro tools', () => {
+ // A ReadContent call the fold already named and unwrapped.
+ const readContent = (overrides?: Partial<Omit<ToolUsePart, 'name'>>) =>
toolUse(
- { kind: 'read', paths: [] },
{
- label: 'ReadContent',
- status: 'running',
- rawInput: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
- ...overrides,
- }
+ kind: 'macro',
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ output: null,
+ error: null,
+ },
+ { name: 'ReadContent', status: 'running', ...overrides }
);
- it('routes an in-flight call with parseable input to the chat renderer', () => {
- const rendered = render(() => <ToolCallPart part={macroPart()} />);
+ it('renders a known Macro tool with the chat component', () => {
+ const rendered = render(() => <ToolCallPart part={readContent()} />);
expect(rendered.getByTestId('macro-tool').textContent).toBe('ReadContent');
expect(rendered.getByTestId('macro-tool').dataset.complete).toBe('false');
expect(rendered.queryByTestId('tool-card')).toBeNull();
});
- it('routes a completed call whose raw output parses, as the response', () => {
+ it('passes the unwrapped output as the chat response once complete', () => {
const rendered = render(() => (
<ToolCallPart
- part={macroPart({
+ part={readContent({
status: 'completed',
- rawOutput: { content: { text: 'hi' }, comments: [] },
+ detail: {
+ kind: 'macro',
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ output: { content: { text: 'hi' }, comments: [] },
+ error: null,
+ },
})}
/>
));
@@ -188,61 +236,363 @@ describe('ToolCallPart Macro tool routing', () => {
expect(rendered.getByTestId('macro-tool').dataset.hasResponse).toBe('true');
});
- it('strips an mcp__<server>__ prefix when resolving the tool name', () => {
+ it('keeps a Macro tool the chat has no component for on a labelled card', () => {
const rendered = render(() => (
- <ToolCallPart part={macroPart({ label: 'mcp__macro__ReadContent' })} />
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'macro',
+ input: { anything: 1 },
+ output: { result: 'ok' },
+ error: null,
+ },
+ { name: 'BrandNewTool' }
+ )}
+ />
));
- expect(rendered.getByTestId('macro-tool').textContent).toBe('ReadContent');
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ expect(rendered.getByTestId('title').textContent).toBe('BrandNewTool');
+ expect(rendered.getByTestId('body').textContent).toContain(
+ '"result": "ok"'
+ );
});
- it('keeps a completed call with no parseable response on the generic cards', () => {
- // The chat renderer shows complete-without-response as failed, which
- // would be wrong for a call that succeeded.
+ it('keeps a completed call whose output the chat cannot read on the card', () => {
+ // The chat renderer would show this as failed; the call succeeded.
const rendered = render(() => (
- <ToolCallPart part={macroPart({ status: 'completed' })} />
+ <ToolCallPart
+ part={readContent({
+ status: 'completed',
+ detail: {
+ kind: 'macro',
+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },
+ output: { unexpected: true },
+ error: null,
+ },
+ })}
+ />
));
expect(rendered.queryByTestId('macro-tool')).toBeNull();
- expect(rendered.getByTestId('tool-card')).not.toBeNull();
+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('false');
+ expect(rendered.getByTestId('trailing').textContent).toBe('');
});
- it('routes a failed call — the chat renderer owns the failed treatment', () => {
+ it('keeps a known tool whose arguments do not fit its schema on the card', () => {
const rendered = render(() => (
<ToolCallPart
- part={macroPart({ status: 'failed', rawOutput: { error: 'nope' } })}
+ part={readContent({
+ detail: {
+ kind: 'macro',
+ input: { documentId: 'not-a-uuid' },
+ output: null,
+ error: null,
+ },
+ })}
/>
));
- expect(rendered.getByTestId('macro-tool').dataset.complete).toBe('true');
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ expect(rendered.getByTestId('tool-card')).not.toBeNull();
});
- it('keeps an unknown tool name on the generic cards', () => {
+ it('shows a failed Macro tool with its error, faded', () => {
const rendered = render(() => (
<ToolCallPart
part={toolUse(
- { kind: 'read', paths: ['a.rs'] },
- { label: 'Read', rawInput: { filePath: 'a.rs' } }
+ {
+ kind: 'macro',
+ input: { limit: 5 },
+ output: null,
+ error: 'permission denied',
+ },
+ { name: 'ListEntities', status: 'failed' }
)}
/>
));
expect(rendered.queryByTestId('macro-tool')).toBeNull();
- expect(rendered.getByTestId('tool-card')).not.toBeNull();
+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
+ expect(rendered.getByTestId('subtitle').textContent).toBe(
+ 'permission denied'
+ );
+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
+ });
+});
+
+describe('ToolCallPart user tools', () => {
+ const email = (
+ outcome: Extract<ToolUsePart['detail'], { kind: 'user_tool' }>['outcome']
+ ) =>
+ toolUse(
+ {
+ kind: 'user_tool',
+ input: {
+ subject: 'Q3 plan',
+ body: 'Hi Alice',
+ to: [{ email: '[email protected]', name: 'Alice' }],
+ },
+ outcome,
+ },
+ { name: 'SendEmail' }
+ );
+
+ it('renders a pending email draft read-only on its own card, never through the chat', () => {
+ const rendered = render(() => (
+ <ToolCallPart part={email({ kind: 'pending' })} />
+ ));
+ expect(rendered.queryByTestId('macro-tool')).toBeNull();
+ expect(rendered.getByTestId('title').textContent).toBe('SendEmail');
+ expect(rendered.getByTestId('subtitle').textContent).toBe('Q3 plan');
+ expect(rendered.getByTestId('trailing').textContent).toBe('Awaiting you');
+ const body = rendered.getByTestId('body');
+ expect(body.textContent).toContain('Alice <[email protected]>');
+ expect(body.textContent).toContain('Q3 plan');
+ expect(rendered.getByTestId('text-part').textContent).toBe('Hi Alice');
+ });
+
+ it('labels every outcome, and links the thread an email went to', () => {
+ const cases: [
+ Extract<ToolUsePart['detail'], { kind: 'user_tool' }>['outcome'],
+ string,
+ string | undefined,
+ ][] = [
+ [{ kind: 'edited' }, 'Edited', undefined],
+ [
+ {
+ kind: 'sent',
+ messageId: '9c4d2c6e-2f3a-4d1e-8b0a-5e6f7a8b9c0d',
+ threadId: '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
+ },
+ 'Sent',
+ '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
+ ],
+ [
+ {
+ kind: 'draft',
+ draftId: '7e8f9a0b-1c2d-4e3f-8a9b-0c1d2e3f4a5b',
+ threadId: null,
+ },
+ 'Saved as draft',
+ undefined,
+ ],
+ [
+ {
+ kind: 'draft',
+ draftId: '7e8f9a0b-1c2d-4e3f-8a9b-0c1d2e3f4a5b',
+ threadId: '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
+ },
+ 'Saved as draft',
+ '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
+ ],
+ [{ kind: 'rejected' }, 'Rejected', undefined],
+ [{ kind: 'completed', result: { id: 'evt' } }, 'Done', undefined],
+ ];
+ for (const [outcome, label, thread] of cases) {
+ const rendered = render(() => <ToolCallPart part={email(outcome)} />);
+ const trailing = rendered.getByTestId('trailing');
+ expect(trailing.textContent).toContain(label);
+ const link = rendered.queryByTestId('item-preview');
+ expect(link?.dataset.id).toBe(thread);
+ rendered.unmount();
+ }
});
- it('keeps a known name whose input does not parse on the generic cards', () => {
+ it('shows an edited body, which arrives as base64url HTML, as its text', () => {
+ const html = btoa('<body><p>Hi <b>Alice</b>,</p><p>see plan</p></body>')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_');
const rendered = render(() => (
<ToolCallPart
- part={macroPart({ rawInput: { documentId: 'not-a-uuid' } })}
+ part={toolUse(
+ {
+ kind: 'user_tool',
+ input: {
+ subject: 'Q3 plan',
+ body: html,
+ to: [{ email: '[email protected]' }],
+ },
+ outcome: { kind: 'edited' },
+ },
+ { name: 'SendEmail' }
+ )}
/>
));
+ expect(rendered.queryByTestId('text-part')).toBeNull();
+ expect(rendered.getByTestId('output').textContent).toBe(
+ 'Hi Alice,see plan'
+ );
+ });
+
+ it('renders a calendar event draft with when, where and attendees', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'user_tool',
+ input: {
+ title: 'Q3 sync',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-08-20T17:00:00Z',
+ endsAt: '2026-08-20T17:30:00Z',
+ timeZone: 'UTC',
+ },
+ location: 'Room 4',
+ attendees: [
+ { email: '[email protected]' },
+ { email: '[email protected]', isOptional: true },
+ ],
+ description: 'Agenda in the doc.',
+ },
+ outcome: { kind: 'pending' },
+ },
+ { name: 'CreateCalendarEvent' }
+ )}
+ />
+ ));
+ expect(rendered.getByTestId('title').textContent).toBe(
+ 'CreateCalendarEvent'
+ );
+ expect(rendered.getByTestId('subtitle').textContent).toBe('Q3 sync');
+ const body = rendered.getByTestId('body').textContent ?? '';
+ expect(body).toContain('Aug 20, 2026');
+ expect(body).toContain('Room 4');
+ expect(body).toContain('[email protected], [email protected] (optional)');
+ expect(rendered.getByTestId('text-part').textContent).toBe(
+ 'Agenda in the doc.'
+ );
+ });
+
+ it('keeps a failed user tool on a faded card with the error as body', () => {
+ const rendered = render(() => (
+ <ToolCallPart part={email({ kind: 'failed', message: 'no inbox' })} />
+ ));
expect(rendered.queryByTestId('macro-tool')).toBeNull();
- expect(rendered.getByTestId('tool-card')).not.toBeNull();
+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
+ expect(rendered.getByTestId('body').textContent).toBe('no inbox');
+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
});
- it('keeps a known name with no raw input on the generic cards', () => {
+ it('shows a draft the schema rejects as JSON, with the outcome still labelled', () => {
const rendered = render(() => (
- <ToolCallPart part={macroPart({ rawInput: null })} />
+ <ToolCallPart
+ part={toolUse(
+ {
+ kind: 'user_tool',
+ input: { subject: 'no recipients or body' },
+ outcome: { kind: 'unrecognized' },
+ },
+ { name: 'SendEmail' }
+ )}
+ />
));
expect(rendered.queryByTestId('macro-tool')).toBeNull();
- expect(rendered.getByTestId('tool-card')).not.toBeNull();
+ expect(rendered.getByTestId('trailing').textContent).toBe('Answered');
+ expect(rendered.getByTestId('body').textContent).toContain(
+ '"subject": "no recipients or body"'
+ );
+ });
+});
+
+describe('ToolCallPart subagents', () => {
+ const subagent = (
+ overrides?: Partial<Extract<ToolUsePart['detail'], { kind: 'subagent' }>>
+ ) =>
+ toolUse(
+ {
+ kind: 'subagent',
+ title: 'Add 5+5 with Python',
+ agentType: 'general-purpose',
+ description: 'Add 5+5 with Python',
+ prompt: 'Run python and report the output.',
+ background: false,
+ children: [
+ toolUse(
+ {
+ kind: 'terminal',
+ command: 'python3 -c "print(5+5)"',
+ output: '10',
+ exitCode: 0,
+ },
+ { id: 'child', name: 'Bash' }
+ ),
+ ],
+ result: {
+ text: 'Output: `10`',
+ error: null,
+ agentId: 'a1',
+ model: 'claude-opus-5[1m]',
+ durationMs: 3485,
+ tokens: 26077,
+ toolUses: 1,
+ stats: null,
+ },
+ ...overrides,
+ },
+ { name: 'Agent' }
+ );
+
+ it('titles the card with the description and nests the children', () => {
+ const rendered = render(() => <ToolCallPart part={subagent()} />);
+ const titles = rendered.getAllByTestId('title').map((el) => el.textContent);
+ expect(titles).toEqual(['Add 5+5 with Python', 'Bash']);
+ expect(rendered.getAllByTestId('subtitle')[0]?.textContent).toBe(
+ 'general-purpose'
+ );
+ expect(rendered.getByTestId('terminal').textContent).toBe('10');
+ expect(rendered.getByTestId('text-part').textContent).toBe('Output: `10`');
+ });
+
+ it('summarizes the result in the trailing slot', () => {
+ const rendered = render(() => <ToolCallPart part={subagent()} />);
+ expect(rendered.getAllByTestId('trailing')[0]?.textContent).toBe(
+ '1 tool · 3.5s · 26k tokens'
+ );
+ });
+
+ it('shows the title the fold chose, whatever the harness gave', () => {
+ // The fold has already decided the title - description, else the brief's
+ // first line, else the tool name - so the card shows it as is.
+ const rendered = render(() => (
+ <ToolCallPart
+ part={subagent({
+ title: 'Run python and report the output.',
+ description: null,
+ agentType: null,
+ children: [],
+ result: null,
+ })}
+ />
+ ));
+ expect(rendered.getByTestId('title').textContent).toBe(
+ 'Run python and report the output.'
+ );
+ expect(rendered.getByTestId('body').textContent).toContain(
+ 'Run python and report the output.'
+ );
+ });
+
+ it('shows a failed subagent faded with its error', () => {
+ const rendered = render(() => (
+ <ToolCallPart
+ part={subagent({
+ children: [],
+ result: {
+ text: null,
+ error: 'Subagent failed: boom',
+ agentId: null,
+ model: null,
+ durationMs: null,
+ tokens: null,
+ toolUses: null,
+ stats: null,
+ },
+ })}
+ />
+ ));
+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');
+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');
+ expect(rendered.getByTestId('output').textContent).toBe(
+ 'Subagent failed: boom'
+ );
});
});
diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx
index 7a7876a3ff..d82664af00 100644
--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx
+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx
@@ -2,168 +2,39 @@
* Routes a folded tool call to its detail component — the chat block's
* `RenderTool`/handler-map analog (`tool/handler.tsx`).
*
- * Macro tools route to the chat block's own per-tool components: the agent
- * runs the same `ai_tools` toolset the chat does, so a call whose label is a
- * known tool name and whose raw input parses as that tool's arguments renders
- * with the exact component the chat block would use. Everything else — the
- * coding harness's Bash/Read/Edit, unrecognized tools, calls whose input
- * never arrived — falls back to the fold's kind-based cards, each in its own
- * file.
+ * The fold has already decided what every call is: a coding-harness tool by
+ * kind (terminal, edit, read, ...), a Macro tool by name, a user tool the
+ * user finishes, or a delegated subagent. This is a pure match over that
+ * closed vocabulary — nothing here reads ACP, parses raw JSON, or guesses a
+ * tool from its title.
*/
-import { RenderTool } from '@core/component/AI/component/tool/handler';
import type { MessagePart } from '@service-agent-fold/generated/types';
-import {
- deserializeToolCall,
- deserializeToolResponse,
-} from '@service-cognition/generated/tools/tool';
-import { createMemo, ErrorBoundary, type JSX, Show } from 'solid-js';
+import type { JSX } from 'solid-js';
import { match } from 'ts-pattern';
import { EditToolCall } from './EditToolCall';
+import { MacroToolCall } from './MacroToolCall';
import { OutputToolCall } from './OutputToolCall';
import { PathsToolCall } from './PathsToolCall';
import { SearchToolCall } from './SearchToolCall';
-import type { ToolCallCommon } from './shared';
+import { SubagentToolCall } from './SubagentToolCall';
+import { type ToolCallCommon, type ToolCallContext, toolLabel } from './shared';
import { TerminalToolCall } from './TerminalToolCall';
+import { UserToolCall } from './UserToolCall';
type ToolUsePart = Extract<MessagePart, { kind: 'tool_use' }>;
-/**
- * Where the part sits in its transcript, for the chat components' render
- * context. The chat block keys its tool components by chat/message/part;
- * the agent block's equivalents are the session, the turn's message, and
- * the part's index. Absent in fixtures and unit tests, where the generic
- * cards (which need none of this) are the layer under test.
- */
-export type ToolCallContext = {
- /** The agent session id, standing in for the chat block's chat id. */
- sessionId: string;
- /** A stable per-turn id, standing in for the chat block's message id. */
- messageId: string;
- /** The part's index within its message. */
- partIndex: number;
- /** The turn is still in flight — the chat block's `isStreaming`. */
- inFlight: boolean;
-};
-
-/**
- * The Macro tool name a label resolves to, when the call is one the chat
- * renderer can faithfully show. Undefined keeps the part on the generic
- * cards.
- *
- * A call is recognized by evidence, not just its label: the raw input must
- * parse as the named tool's arguments (a coincidental name with different
- * arguments stays generic), and a call that already completed must carry a
- * parseable response — the chat renderer shows a complete call with no
- * parseable response as failed, which would slander a call that succeeded
- * but whose result the log carried in another shape.
- *
- * The label is tried as-is (Macro's own agent names its tools plainly:
- * `ReadContent`) and, failing that, as an `mcp__<server>__<tool>` suffix —
- * how a Claude Code harness names the same tools when it reaches them over
- * MCP.
- */
-function resolveMacroTool(part: ToolUsePart): string | undefined {
- if (part.rawInput == null) return undefined;
-
- const candidates = [part.label];
- const mcp = part.label.match(/^mcp__.+?__(.+)$/);
- if (mcp) candidates.push(mcp[1]);
-
- for (const name of candidates) {
- const call = deserializeToolCall({
- id: part.id,
- name,
- json: part.rawInput,
- });
- if (call.isErr()) continue;
- if (part.status === 'completed') {
- const response = deserializeToolResponse({
- id: part.id,
- name,
- json: part.rawOutput,
- });
- if (response.isErr()) continue;
- }
- return name;
- }
- return undefined;
-}
-
export function ToolCallPart(props: {
part: ToolUsePart;
+ /** Where the part sits, for the chat components Macro tools render with. */
context?: ToolCallContext;
}): JSX.Element {
- const macroTool = createMemo(() => resolveMacroTool(props.part));
-
- return (
- <Show
- when={macroTool()}
- fallback={<GenericToolCall part={props.part} />}
- keyed
- >
- {(name) => (
- // A handful of chat tool components assume chat-only context (the
- // email/calendar compose flows resume a chat stream); if one throws
- // here, fall back to the generic card rather than losing the row.
- <ErrorBoundary fallback={<GenericToolCall part={props.part} />}>
- <MacroToolCall
- name={name}
- part={props.part}
- context={props.context}
- />
- </ErrorBoundary>
- )}
- </Show>
- );
-}
-
-/**
- * The chat block's tool renderer, fed from the fold: label is the tool name,
- * `rawInput` the call arguments, `rawOutput` the response. A failed call or
- * a response that never parsed renders exactly as it does in the chat —
- * `RenderTool` treats a complete call with no parseable response as failed.
- */
-function MacroToolCall(props: {
- /** The resolved Macro tool name — the label, MCP prefix stripped. */
- name: string;
- part: ToolUsePart;
- context?: ToolCallContext;
-}): JSX.Element {
- const response = () =>
- props.part.rawOutput == null
- ? undefined
- : { json: props.part.rawOutput, name: props.name };
-
- return (
- <RenderTool
- tool_id={props.part.id}
- name={props.name}
- json={props.part.rawInput}
- response={response()}
- chat_id={props.context?.sessionId ?? ''}
- message_id={props.context?.messageId ?? ''}
- part_index={props.context?.partIndex ?? 0}
- isComplete={
- props.part.status === 'completed' || props.part.status === 'failed'
- }
- renderContext={{
- renderContext: {
- isStreaming: props.context?.inFlight ?? false,
- grouped: false,
- },
- }}
- />
- );
-}
-
-/** The fold's kind-based cards, keyed off the closed `ToolDetail` union. */
-function GenericToolCall(props: { part: ToolUsePart }): JSX.Element {
const failed = () => props.part.status === 'failed';
// The chat block's failed-tool treatment: the same row, faded, with a quiet
// trailing label — not a separate error card.
const common = (): ToolCallCommon => ({
- label: props.part.label,
+ id: props.part.id,
+ label: toolLabel(props.part.name),
status: props.part.status,
muted: failed(),
trailing: failed() ? <span class="text-ink">Failed</span> : undefined,
@@ -185,5 +56,22 @@ function GenericToolCall(props: { part: ToolUsePart }): JSX.Element {
.with({ kind: 'fetch' }, { kind: 'think' }, { kind: 'other' }, (detail) => (
<OutputToolCall detail={detail} common={common()} />
))
+ .with({ kind: 'macro' }, (detail) => (
+ <MacroToolCall
+ detail={detail}
+ common={common()}
+ context={props.context}
+ />
+ ))
+ .with({ kind: 'user_tool' }, (detail) => (
+ <UserToolCall detail={detail} common={common()} context={props.context} />
+ ))
+ .with({ kind: 'subagent' }, (detail) => (
+ <SubagentToolCall
+ detail={detail}
+ common={common()}
+ context={props.context}
+ />
+ ))
.exhaustive();
}
diff --git a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
new file mode 100644
index 0000000000..d735d49b1a
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
@@ -0,0 +1,293 @@
+/**
+ * A Macro user tool: the agent drafted it, the user finishes it after the
+ * turn - `SendEmail`, `CreateCalendarEvent`.
+ *
+ * A transcript is a record of the session, not a place to act from, so this
+ * renders the draft read-only in its own card: what the agent wrote, and
+ * where the user got to with it. The chat block's composers are not reused
+ * here - they are editors wired to a chat's owner gate, message list and
+ * tool-call endpoints, none of which an agent session has - so nothing in
+ * this file depends on chat context.
+ */
+
+import { ItemPreview } from '@core/component/ItemPreview';
+import type {
+ ToolDetail,
+ UserToolOutcome,
+} from '@service-agent-fold/generated/types';
+import {
+ deserializeToolCall,
+ type NamedTool,
+} from '@service-cognition/generated/tools/tool';
+import type {
+ AttendeeInput,
+ CreateCalendarEvent,
+ EmailRecipient,
+ EventTimeInput,
+ SendEmail,
+} from '@service-cognition/generated/tools/types';
+import { createMemo, For, type JSX, Match, Show, Switch } from 'solid-js';
+import { match } from 'ts-pattern';
+import { FoldedOutput, ToolCard } from '../../ui';
+import type { ToolCallCommon, ToolCallContext } from './shared';
+import { TextPart } from './TextPart';
+
+type UserToolDetail = Extract<ToolDetail, { kind: 'user_tool' }>;
+
+/** The one-line reading of an outcome, for the card's trailing slot. */
+function outcomeLabel(outcome: UserToolOutcome): string {
+ return match(outcome)
+ .with({ kind: 'pending' }, () => 'Awaiting you')
+ .with({ kind: 'edited' }, () => 'Edited')
+ .with({ kind: 'sent' }, () => 'Sent')
+ .with({ kind: 'draft' }, () => 'Saved as draft')
+ .with({ kind: 'completed' }, () => 'Done')
+ .with({ kind: 'rejected' }, () => 'Rejected')
+ .with({ kind: 'failed' }, () => 'Failed')
+ .with({ kind: 'unrecognized' }, () => 'Answered')
+ .exhaustive();
+}
+
+/**
+ * The draft, typed by the tool's own schema, when the input fits it. A
+ * draft that does not - a tool this block has no view for, or arguments the
+ * schema rejects - shows as JSON instead.
+ */
+function typedDraft(
+ common: ToolCallCommon,
+ input: unknown
+): NamedTool<'SendEmail' | 'CreateCalendarEvent', 'call'> | undefined {
+ const call = deserializeToolCall({
+ id: common.id,
+ name: common.label,
+ json: input,
+ });
+ if (call.isErr()) return undefined;
+ const tool = call.value;
+ return tool.name === 'SendEmail' || tool.name === 'CreateCalendarEvent'
+ ? (tool as NamedTool<'SendEmail' | 'CreateCalendarEvent', 'call'>)
+ : undefined;
+}
+
+export function UserToolCall(props: {
+ detail: UserToolDetail;
+ common: ToolCallCommon;
+ context?: ToolCallContext;
+}): JSX.Element {
+ const draft = createMemo(() => typedDraft(props.common, props.detail.input));
+ const outcome = () => props.detail.outcome;
+ const failure = () => {
+ const current = outcome();
+ return current.kind === 'failed' ? current.message : undefined;
+ };
+
+ return (
+ <ToolCard
+ title={props.common.label}
+ status={props.common.status}
+ subtitle={draft() && draftSubtitle(draft()!)}
+ muted={props.common.muted || failure() !== undefined}
+ trailing={
+ props.common.trailing ?? <OutcomeTrailing outcome={outcome()} />
+ }
+ >
+ <Switch
+ fallback={
+ <FoldedOutput text={JSON.stringify(props.detail.input, null, 2)} />
+ }
+ >
+ <Match when={failure()}>
+ {(message) => <FoldedOutput text={message()} />}
+ </Match>
+ <Match when={draft()?.name === 'SendEmail' && draft()}>
+ {(tool) => (
+ <EmailDraft
+ email={tool().data as SendEmail}
+ inFlight={props.context?.inFlight ?? false}
+ />
+ )}
+ </Match>
+ <Match when={draft()?.name === 'CreateCalendarEvent' && draft()}>
+ {(tool) => <EventDraft event={tool().data as CreateCalendarEvent} />}
+ </Match>
+ </Switch>
+ </ToolCard>
+ );
+}
+
+/** The one thing to say beside the tool's name: the subject, or the title. */
+function draftSubtitle(
+ tool: NamedTool<'SendEmail' | 'CreateCalendarEvent', 'call'>
+): string | undefined {
+ const text =
+ tool.name === 'SendEmail'
+ ? (tool.data as SendEmail).subject
+ : (tool.data as CreateCalendarEvent).title;
+ return text.trim() === '' ? undefined : text;
+}
+
+/**
+ * The outcome, and for an email that went somewhere, a link to where: the
+ * thread it was sent into, or the thread its draft belongs to.
+ */
+function OutcomeTrailing(props: { outcome: UserToolOutcome }): JSX.Element {
+ const threadId = () =>
+ match(props.outcome)
+ .with({ kind: 'sent' }, (sent) => sent.threadId)
+ .with({ kind: 'draft' }, (draft) => draft.threadId ?? undefined)
+ .otherwise(() => undefined);
+ return (
+ <span class="flex items-center gap-2">
+ <span class="text-ink">{outcomeLabel(props.outcome)}</span>
+ <Show when={threadId()}>
+ {(id) => <ItemPreview id={id()} type="email" class="ring-0" />}
+ </Show>
+ </span>
+ );
+}
+
+// --- SendEmail ---
+
+function recipientLabel(recipient: EmailRecipient): string {
+ const name = recipient.name?.trim();
+ return name ? `${name} <${recipient.email}>` : recipient.email;
+}
+
+/**
+ * The body as the draft holds it. The agent writes markdown; once the user
+ * has edited in the chat's composer it is the base64url-encoded HTML the
+ * tool sends, which reads here as its text.
+ */
+function emailBody(body: string): { markdown?: string; text?: string } {
+ if (body === '') return {};
+ const decoded = decodeBase64Url(body);
+ if (decoded?.startsWith('<body')) return { text: htmlText(decoded) };
+ return { markdown: body };
+}
+
+function decodeBase64Url(input: string): string | undefined {
+ try {
+ const base64 = input.replace(/-/g, '+').replace(/_/g, '/');
+ const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
+ return new TextDecoder('utf-8').decode(bytes);
+ } catch {
+ return undefined;
+ }
+}
+
+function htmlText(html: string): string {
+ return (
+ new DOMParser().parseFromString(html, 'text/html').body.textContent ?? ''
+ );
+}
+
+function EmailDraft(props: { email: SendEmail; inFlight: boolean }) {
+ const body = createMemo(() => emailBody(props.email.body));
+ const recipients = () =>
+ [
+ ['To', props.email.to],
+ ['Cc', props.email.cc ?? []],
+ ['Bcc', props.email.bcc ?? []],
+ ] as const;
+ return (
+ <div class="flex flex-col gap-2">
+ <dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
+ <For each={recipients()}>
+ {([field, list]) => (
+ <Show when={list.length > 0}>
+ <dt class="text-ink-muted">{field}</dt>
+ <dd class="text-ink wrap-break-word">
+ {list.map(recipientLabel).join(', ')}
+ </dd>
+ </Show>
+ )}
+ </For>
+ <Show when={props.email.subject.trim() !== ''}>
+ <dt class="text-ink-muted">Subject</dt>
+ <dd class="text-ink wrap-break-word">{props.email.subject}</dd>
+ </Show>
+ </dl>
+ <Show when={body().markdown}>
+ {(markdown) => <TextPart text={markdown()} inFlight={props.inFlight} />}
+ </Show>
+ <Show when={body().text}>{(text) => <FoldedOutput text={text()} />}</Show>
+ </div>
+ );
+}
+
+// --- CreateCalendarEvent ---
+
+/** When the event is, in the reader's locale, minding the zone it was set in. */
+function eventWhen(time: EventTimeInput): string {
+ if (time.kind === 'allDay') {
+ const start = localDate(time.startDate);
+ // `endDate` is exclusive: a one-day event ends the next date.
+ const lastDay = localDate(time.endDate);
+ lastDay.setDate(lastDay.getDate() - 1);
+ const day = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium' });
+ return lastDay > start
+ ? `${day.format(start)} – ${day.format(lastDay)}`
+ : day.format(start);
+ }
+ const options: Intl.DateTimeFormatOptions = {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ };
+ if (time.timeZone) options.timeZone = time.timeZone;
+ const format = new Intl.DateTimeFormat(undefined, options);
+ const start = new Date(time.startsAt);
+ const end = new Date(time.endsAt);
+ return Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())
+ ? `${time.startsAt} – ${time.endsAt}`
+ : format.formatRange(start, end);
+}
+
+function localDate(date: string): Date {
+ const [year, month, day] = date.split('-').map(Number);
+ return new Date(year ?? 0, (month ?? 1) - 1, day ?? 1);
+}
+
+function attendeeLabel(attendee: AttendeeInput): string {
+ return attendee.isOptional ? `${attendee.email} (optional)` : attendee.email;
+}
+
+function EventDraft(props: { event: CreateCalendarEvent }) {
+ const rows = () =>
+ [
+ ['When', eventWhen(props.event.time)],
+ ['Where', props.event.location?.trim() || undefined],
+ [
+ 'Attendees',
+ props.event.attendees?.length
+ ? props.event.attendees.map(attendeeLabel).join(', ')
+ : undefined,
+ ],
+ [
+ 'Repeats',
+ props.event.recurrenceLines?.length
+ ? props.event.recurrenceLines.join('; ')
+ : undefined,
+ ],
+ ] as const;
+ return (
+ <div class="flex flex-col gap-2">
+ <dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
+ <For each={rows()}>
+ {([field, value]) => (
+ <Show when={value}>
+ {(text) => (
+ <>
+ <dt class="text-ink-muted">{field}</dt>
+ <dd class="text-ink wrap-break-word">{text()}</dd>
+ </>
+ )}
+ </Show>
+ )}
+ </For>
+ </dl>
+ <Show when={props.event.description?.trim()}>
+ {(description) => <TextPart text={description()} />}
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/shared.ts b/apps/web/src/features/block-agent/component/parts/shared.ts
index d4a03bdfcf..7dd2452ff4 100644
--- a/apps/web/src/features/block-agent/component/parts/shared.ts
+++ b/apps/web/src/features/block-agent/component/parts/shared.ts
@@ -5,11 +5,31 @@
* row-level facts every card shares.
*/
+import type { ToolName } from '@service-agent-fold/generated/types';
import type { JSX } from 'solid-js';
import type { ToolStatus } from '../../ui';
+/**
+ * Where a part sits in its transcript, for the chat components a Macro tool
+ * renders with: they key per-call state by chat, message, and part, and the
+ * agent block's equivalents are the session, the turn's message, and the
+ * part's index.
+ */
+export type ToolCallContext = {
+ /** The agent session id, standing in for the chat block's chat id. */
+ sessionId: string;
+ /** A stable per-turn id, standing in for the chat block's message id. */
+ messageId: string;
+ /** The part's index within its message. */
+ partIndex: number;
+ /** The turn is still in flight — the chat block's `isStreaming`. */
+ inFlight: boolean;
+};
+
/** Row-level facts common to every tool card, derived once by the dispatcher. */
export type ToolCallCommon = {
+ /** The ACP tool call id. */
+ id: string;
label: string;
status: ToolStatus;
/** The chat block's failed treatment: faded row, quiet trailing label. */
@@ -17,6 +37,14 @@ export type ToolCallCommon = {
trailing: JSX.Element | undefined;
};
+/**
+ * The short name to show for a tool: its own name, without the MCP server
+ * namespace the fold already separated out.
+ */
+export function toolLabel(name: ToolName): string {
+ return name.kind === 'mcp' ? name.tool : name.name;
+}
+
/** Subtitle for a call that touched paths: the path, or how many. */
export function pathsSubtitle(paths: string[]): string | undefined {
if (paths.length === 0) return undefined;
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index 7872f513c9..7eb140edba 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -115,19 +115,15 @@ const FIXTURE_MESSAGE: FoldedMessage = {
},
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'demo-read',
- label: 'Read',
+ name: { kind: 'native', name: 'Read' },
status: 'completed',
detail: { kind: 'read', paths: ['crates/agent_fold/src/domain/fold.rs'] },
},
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'demo-search',
- label: 'Search',
+ name: { kind: 'native', name: 'Search' },
status: 'completed',
detail: {
kind: 'search',
@@ -137,19 +133,15 @@ const FIXTURE_MESSAGE: FoldedMessage = {
},
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'demo-edit',
- label: 'Edit',
+ name: { kind: 'native', name: 'Edit' },
status: 'completed',
detail: { kind: 'edit', diffs: [FIXTURE_DIFF] },
},
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'demo-terminal',
- label: 'Bash',
+ name: { kind: 'native', name: 'Bash' },
status: 'running',
detail: {
kind: 'terminal',
@@ -167,6 +159,116 @@ const FIXTURE_MESSAGE: FoldedMessage = {
],
outcome: { kind: 'selected', optionId: 'allow' },
},
+ {
+ kind: 'tool_use',
+ id: 'demo-subagent',
+ name: { kind: 'native', name: 'Agent' },
+ status: 'completed',
+ detail: {
+ kind: 'subagent',
+ title: 'Check the arithmetic',
+ agentType: 'general-purpose',
+ description: 'Check the arithmetic',
+ prompt: 'Run `python3 -c "print(5+5)"` and report the output.',
+ background: false,
+ children: [
+ {
+ kind: 'tool_use',
+ id: 'demo-subagent-bash',
+ name: { kind: 'native', name: 'Bash' },
+ status: 'completed',
+ detail: {
+ kind: 'terminal',
+ command: 'python3 -c "print(5+5)"',
+ output: '10',
+ exitCode: 0,
+ },
+ },
+ ],
+ result: {
+ text: 'Output: `10`',
+ error: null,
+ agentId: 'af2647314187b6bf1',
+ model: 'claude-opus-5[1m]',
+ durationMs: 3485,
+ tokens: 26077,
+ toolUses: 1,
+ stats: null,
+ },
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'demo-macro',
+ name: { kind: 'mcp', server: 'macro', tool: 'BrandNewTool' },
+ status: 'completed',
+ detail: {
+ kind: 'macro',
+ input: { query: 'fold' },
+ output: { hits: 3 },
+ error: null,
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'demo-email',
+ name: { kind: 'mcp', server: 'macro', tool: 'SendEmail' },
+ status: 'completed',
+ detail: {
+ kind: 'user_tool',
+ input: {
+ subject: 'Fold status',
+ body: 'Hi Alice,\n\nThe fold now knows which harness it is reading.',
+ to: [{ email: '[email protected]', name: 'Alice' }],
+ },
+ outcome: { kind: 'pending' },
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'demo-email-sent',
+ name: { kind: 'mcp', server: 'macro', tool: 'SendEmail' },
+ status: 'completed',
+ detail: {
+ kind: 'user_tool',
+ input: {
+ subject: 'Re: fold status',
+ body: 'Thanks Alice - shipping it.',
+ to: [{ email: '[email protected]', name: 'Alice' }],
+ cc: [{ email: '[email protected]' }],
+ },
+ outcome: {
+ kind: 'sent',
+ messageId: '9c4d2c6e-2f3a-4d1e-8b0a-5e6f7a8b9c0d',
+ threadId: '1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d',
+ },
+ },
+ },
+ {
+ kind: 'tool_use',
+ id: 'demo-event',
+ name: { kind: 'mcp', server: 'macro', tool: 'CreateCalendarEvent' },
+ status: 'completed',
+ detail: {
+ kind: 'user_tool',
+ input: {
+ title: 'Fold review',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-09-04T16:00:00Z',
+ endsAt: '2026-09-04T16:30:00Z',
+ timeZone: 'America/New_York',
+ },
+ location: 'Room 4',
+ attendees: [
+ { email: '[email protected]' },
+ { email: '[email protected]', isOptional: true },
+ ],
+ description: 'Walk through the harness readers.',
+ },
+ outcome: { kind: 'rejected' },
+ },
+ },
],
};
diff --git a/apps/web/src/features/block-agent/state/session-summary.test.ts b/apps/web/src/features/block-agent/state/session-summary.test.ts
index 02f4ddb89e..2fd66362f2 100644
--- a/apps/web/src/features/block-agent/state/session-summary.test.ts
+++ b/apps/web/src/features/block-agent/state/session-summary.test.ts
@@ -27,11 +27,9 @@ function edit(
return {
kind: 'tool_use',
id: `edit-${diffs[0]?.path}`,
- label: 'Edit',
+ name: { kind: 'native', name: 'Edit' },
status: 'completed',
detail: { kind: 'edit', diffs },
- rawInput: null,
- rawOutput: null,
};
}
@@ -39,11 +37,9 @@ function tool(detail: Extract<MessagePart, { kind: 'tool_use' }>['detail']) {
return {
kind: 'tool_use' as const,
id: 'tool',
- label: 'Tool',
+ name: { kind: 'native' as const, name: 'Tool' },
status: 'completed' as const,
detail,
- rawInput: null,
- rawOutput: null,
};
}
@@ -100,6 +96,35 @@ describe('changedFiles', () => {
});
});
+describe('subagent descent', () => {
+ it("counts a subagent's edits and tool calls as the session's", () => {
+ const nested = edit([{ path: 'b.rs', oldText: 'x\n', newText: 'y\n' }]);
+ const subagent: MessagePart = {
+ kind: 'tool_use',
+ id: 'agent',
+ name: { kind: 'native', name: 'Agent' },
+ status: 'completed',
+ detail: {
+ kind: 'subagent',
+ title: 'Fix b',
+ agentType: 'general-purpose',
+ description: 'Fix b',
+ prompt: 'Fix b.rs',
+ background: false,
+ children: [nested, tool({ kind: 'read', paths: ['b.rs'] })],
+ result: null,
+ },
+ };
+ const messages = [message(0, [subagent])];
+ expect(changedFiles(messages).map((file) => file.path)).toEqual(['b.rs']);
+ const counts = Object.fromEntries(
+ activityCounts(messages).map((item) => [item.key, item.count])
+ );
+ expect(counts.edit).toBe(1);
+ expect(counts.read).toBe(1);
+ });
+});
+
describe('activityCounts', () => {
it('counts tool calls by kind, keeping zero-count items', () => {
const messages = [
diff --git a/apps/web/src/features/block-agent/state/session-summary.ts b/apps/web/src/features/block-agent/state/session-summary.ts
index e944331fef..d3f57ea8c5 100644
--- a/apps/web/src/features/block-agent/state/session-summary.ts
+++ b/apps/web/src/features/block-agent/state/session-summary.ts
@@ -6,6 +6,7 @@
import type {
FoldedMessage,
+ MessagePart,
PlanEntry,
} from '@service-agent-fold/generated/types';
import { diffLines } from 'diff';
@@ -47,6 +48,22 @@ export type ChangedFile = {
deletions: number;
};
+/**
+ * Every tool call in the transcript, in order, descending into the calls a
+ * subagent made: a file the subagent edited is a file the session edited.
+ */
+function* toolCalls(
+ parts: readonly MessagePart[]
+): Generator<Extract<MessagePart, { kind: 'tool_use' }>> {
+ for (const part of parts) {
+ if (part.kind !== 'tool_use') continue;
+ yield part;
+ if (part.detail.kind === 'subagent') {
+ yield* toolCalls(part.detail.children);
+ }
+ }
+}
+
/**
* Every file the session's edit tools touched, in first-touched order, with
* line stats summed across all edits of that file.
@@ -54,8 +71,8 @@ export type ChangedFile = {
export function changedFiles(messages: FoldedMessage[]): ChangedFile[] {
const byPath = new Map<string, ChangedFile>();
for (const message of messages) {
- for (const part of message.parts) {
- if (part.kind !== 'tool_use' || part.detail.kind !== 'edit') continue;
+ for (const part of toolCalls(message.parts)) {
+ if (part.detail.kind !== 'edit') continue;
for (const diff of part.detail.diffs) {
const changes = countDiffChanges([diff]);
const existing = byPath.get(diff.path);
@@ -79,8 +96,7 @@ export function changedFiles(messages: FoldedMessage[]): ChangedFile[] {
export function activityCounts(messages: FoldedMessage[]): CountItem[] {
const counts = { edit: 0, read: 0, search: 0, terminal: 0, fetch: 0 };
for (const message of messages) {
- for (const part of message.parts) {
- if (part.kind !== 'tool_use') continue;
+ for (const part of toolCalls(message.parts)) {
const kind = part.detail.kind;
if (kind in counts) counts[kind as keyof typeof counts] += 1;
}
diff --git a/apps/web/src/lib/core/agent-fold/client.ts b/apps/web/src/lib/core/agent-fold/client.ts
index d9784f1388..d4f767ec3a 100644
--- a/apps/web/src/lib/core/agent-fold/client.ts
+++ b/apps/web/src/lib/core/agent-fold/client.ts
@@ -22,6 +22,7 @@ export type SessionFoldSnapshot = {
/** What a machine that has folded nothing knows — every field still absent. */
const EMPTY_METADATA: SessionMetadata = {
+ harness: 'unknown',
model: null,
supportedModels: [],
title: null,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
index 73dc2cfe33..cf600b3f51 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.test.ts
@@ -22,6 +22,103 @@ describe('deriveMagicChipPresentation', () => {
});
});
+ it('describes a working subagent by what its child call is doing', () => {
+ expect(
+ deriveMagicChipPresentation({
+ persistedStatus: 'booting',
+ response: response({
+ parts: [
+ {
+ kind: 'tool_use',
+ id: 'agent',
+ name: { kind: 'native', name: 'Agent' },
+ status: 'running',
+ detail: {
+ kind: 'subagent',
+ title: 'Add 5+5',
+ agentType: 'general-purpose',
+ description: 'Add 5+5',
+ prompt: 'Run python',
+ background: false,
+ children: [
+ {
+ kind: 'tool_use',
+ id: 'child',
+ name: { kind: 'native', name: 'Bash' },
+ status: 'running',
+ detail: {
+ kind: 'terminal',
+ command: 'python3 -c "print(5+5)"',
+ output: null,
+ exitCode: null,
+ },
+ },
+ ],
+ result: null,
+ },
+ },
+ ],
+ }),
+ })
+ ).toMatchObject({
+ kind: 'working',
+ activity: {
+ label: 'Running command',
+ detail: 'python3 -c "print(5+5)"',
+ busy: true,
+ },
+ });
+ });
+
+ it('names a Macro tool and a drafted user tool by their tools', () => {
+ const macro = deriveMagicChipPresentation({
+ persistedStatus: 'booting',
+ response: response({
+ parts: [
+ {
+ kind: 'tool_use',
+ id: 'read',
+ name: { kind: 'mcp', server: 'macro', tool: 'ReadContent' },
+ status: 'running',
+ detail: {
+ kind: 'macro',
+ input: { documentId: 'd' },
+ output: null,
+ error: null,
+ },
+ },
+ ],
+ }),
+ });
+ expect(macro).toMatchObject({
+ kind: 'working',
+ activity: { label: 'Using ReadContent', busy: true },
+ });
+
+ const drafted = deriveMagicChipPresentation({
+ persistedStatus: 'booting',
+ response: response({
+ parts: [
+ {
+ kind: 'tool_use',
+ id: 'email',
+ name: { kind: 'mcp', server: 'macro', tool: 'SendEmail' },
+ status: 'completed',
+ detail: {
+ kind: 'user_tool',
+ input: { subject: 'Hi' },
+ outcome: { kind: 'pending' },
+ },
+ },
+ ],
+ }),
+ });
+ expect(drafted).toMatchObject({
+ kind: 'working',
+ activity: { label: 'SendEmail drafted', busy: false },
+ });
+ });
+
it('shows thought activity before answer text exists', () => {
expect(
deriveMagicChipPresentation({
@@ -45,10 +142,8 @@ describe('deriveMagicChipPresentation', () => {
parts: [
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'running',
- label: 'Terminal',
+ name: { kind: 'native', name: 'Terminal' },
status: 'running',
detail: {
kind: 'terminal',
@@ -59,10 +154,8 @@ describe('deriveMagicChipPresentation', () => {
},
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'done',
- label: 'Read',
+ name: { kind: 'native', name: 'Read' },
status: 'completed',
detail: { kind: 'read', paths: ['README.md'] },
},
@@ -93,10 +186,8 @@ describe('deriveMagicChipPresentation', () => {
parts: [
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'tool',
- label: 'Terminal',
+ name: { kind: 'native', name: 'Terminal' },
status: 'pending',
detail: {
kind: 'terminal',
@@ -131,7 +222,10 @@ describe('deriveMagicChipPresentation', () => {
expect(presentation).toEqual({
kind: 'answering',
markdown: 'Looking at t',
- activity: { label: 'Writing response', busy: false },
+ activity: {
+ label: 'Writing response',
+ busy: false,
+ },
});
});
@@ -145,10 +239,8 @@ describe('deriveMagicChipPresentation', () => {
{ kind: 'text', text: 'Let me check the tests.' },
{
kind: 'tool_use',
- rawInput: null,
- rawOutput: null,
id: 'running',
- label: 'Terminal',
+ name: { kind: 'native', name: 'Terminal' },
status: 'running',
detail: {
kind: 'terminal',
@@ -164,7 +256,11 @@ describe('deriveMagicChipPresentation', () => {
expect(presentation).toEqual({
kind: 'answering',
markdown: 'Let me check the tests.',
- activity: { label: 'Running command', detail: 'cargo test', busy: true },
+ activity: {
+ label: 'Running command',
+ detail: 'cargo test',
+ busy: true,
+ },
});
});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
index a2032ec92f..9e65c234fd 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/presentation.ts
@@ -2,9 +2,15 @@ import type { MagicChipStatus } from '@macro-inc/lexical-core';
import type {
FoldedMessage,
MessagePart,
+ ToolName,
} from '@service-agent-fold/generated/types';
import { match } from 'ts-pattern';
+/** The tool's own name, without its MCP server namespace. */
+function toolLabel(name: ToolName): string {
+ return name.kind === 'mcp' ? name.tool : name.name;
+}
+
export type MagicChipActivity = {
label: string;
detail?: string;
@@ -41,6 +47,7 @@ function toolActivity(
): MagicChipActivity {
const busy = part.status === 'pending' || part.status === 'running';
const failed = part.status === 'failed';
+ const label = toolLabel(part.name);
return match(part.detail)
.with({ kind: 'terminal' }, (detail) => ({
label: failed
@@ -48,12 +55,12 @@ function toolActivity(
: busy
? 'Running command'
: 'Command finished',
- detail: detail.command ?? part.label,
+ detail: detail.command ?? label,
busy,
}))
.with({ kind: 'edit' }, (detail) => ({
label: failed ? 'Edit failed' : busy ? 'Editing files' : 'Files updated',
- detail: detail.diffs.at(-1)?.path ?? part.label,
+ detail: detail.diffs.at(-1)?.path ?? label,
busy,
}))
.with({ kind: 'read' }, (detail) => ({
@@ -62,7 +69,7 @@ function toolActivity(
: busy
? 'Reading files'
: 'Finished reading',
- detail: detail.paths.at(-1) ?? part.label,
+ detail: detail.paths.at(-1) ?? label,
busy,
}))
.with(
@@ -70,15 +77,44 @@ function toolActivity(
{ kind: 'move' },
{ kind: 'search' },
(detail) => ({
- label: failed ? `${part.label} failed` : part.label,
- detail: detail.paths.at(-1) ?? part.label,
+ label: failed ? `${label} failed` : label,
+ detail: detail.paths.at(-1) ?? label,
busy,
})
)
.with({ kind: 'fetch' }, { kind: 'think' }, { kind: 'other' }, () => ({
- label: failed ? `${part.label} failed` : part.label,
+ label: failed ? `${label} failed` : label,
busy,
}))
+ .with({ kind: 'macro' }, () => ({
+ label: failed ? `${label} failed` : busy ? `Using ${label}` : label,
+ busy,
+ }))
+ .with({ kind: 'user_tool' }, (detail) => ({
+ label:
+ detail.outcome.kind === 'pending'
+ ? `${label} drafted`
+ : `${label} ${detail.outcome.kind.replace('_', ' ')}`,
+ busy: false,
+ }))
+ .with({ kind: 'subagent' }, (detail) => {
+ // What the subagent is doing right now says more than that it exists.
+ const child = detail.children.findLast(
+ (child) =>
+ child.kind === 'tool_use' &&
+ (child.status === 'pending' || child.status === 'running')
+ );
+ if (busy && child?.kind === 'tool_use') return toolActivity(child);
+ return {
+ label: failed
+ ? 'Subagent failed'
+ : busy
+ ? 'Delegating work'
+ : 'Subagent finished',
+ detail: detail.title,
+ busy,
+ };
+ })
.exhaustive();
}
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index 7ee084e69b..9813000f07 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -130,6 +130,39 @@ export type FoldedStreamEvent =
metadata: SessionMetadata;
};
+/**
+ * Which ACP agent produced a session's log.
+ *
+ * ACP names none of a harness's conventions - which `_meta` keys it writes,
+ * what it calls its tools, how it reports a subagent - so the fold has to
+ * know who it is reading in order to read those. The agent announces itself
+ * in the `initialize` response's `agentInfo.name`; a log that starts
+ * mid-session (a resume) is recognized from the `_meta` namespaces its
+ * first tool frames carry instead. Carried on the metadata so a reader can
+ * show it and never has to infer it.
+ *
+ * [`Self::Unknown`] is a real state, not a failure: every reader falls back
+ * to the harness-neutral conventions, and a harness this fold has not met
+ * still folds to the generic vocabulary.
+ */
+export type Harness =
+ /** `@agentclientprotocol/claude-agent-acp`. */
+ | 'claude_code'
+ /** `OpenCode`, whose ACP server is built in. */
+ | 'open_code'
+ /** OpenAI Codex, through `codex-acp`. */
+ | 'codex'
+ /** Cursor cloud agents, through this repository's `cursor_cloud_agents`. */
+ | 'cursor'
+ /** Macro's own in-process agent, `agent_inmem`. */
+ | 'macro'
+ /** Nous Research's Hermes agent. */
+ | 'hermes'
+ /** OpenClaw. */
+ | 'open_claw'
+ /** Not announced, or an agent this fold does not know. */
+ | 'unknown';
+
/** A unit of renderable content. */
export type MessagePart =
/** Prose from the user or the agent. */
@@ -149,29 +182,12 @@ export type MessagePart =
kind: 'tool_use';
/** The ACP `toolCallId`. */
id: ToolUseId;
- /** What to show as the tool's name. */
- label: string;
+ /** What the harness called the tool. */
+ name: ToolName;
/** Where the call got to. */
status: ToolStatus;
/** What the tool did, as far as the log reveals. */
detail: ToolDetail;
- /**
- * The call's input, verbatim from ACP's `rawInput`, when reported.
- *
- * Carried on every call - not just [`ToolDetail::Other`] - so a
- * reader that knows a tool by name (the Macro toolset renders each
- * tool with its own component) can parse the real arguments instead
- * of settling for the coarse detail.
- */
- rawInput: unknown;
- /**
- * The call's result, verbatim from ACP's `rawOutput`, when reported.
- *
- * The structured counterpart to the text a detail may carry: Macro's
- * agent reports each tool response as JSON here, and named-tool
- * rendering needs that JSON whole.
- */
- rawOutput: unknown;
}
/** The agent asking to proceed. */
| {
@@ -308,6 +324,8 @@ export type PlanEntryStatus =
* Fields start absent and fill in as the log reveals them.
*/
export type SessionMetadata = {
+ /** The agent that produced the log. See [`Harness`]. */
+ harness: Harness;
/**
* Current model per the runtime's own `configOptions` responses, so a
* rejected model change never moves it.
@@ -373,6 +391,40 @@ export type StopReason =
message: string;
};
+/**
+ * What a subagent reported back, as far as its harness told us.
+ *
+ * Every field is optional because every harness tells us a different
+ * subset: Claude Code reports timings, token counts and a per-tool
+ * breakdown; OpenCode names the child session and its model; Cursor and
+ * Hermes give back little more than the text. A reader shows what is
+ * there.
+ */
+export type SubagentResult = {
+ /** The subagent's answer, as text. */
+ text: string | null;
+ /** Why the subagent failed, when it did. */
+ error: string | null;
+ /**
+ * The harness's id for the subagent or its session, for anyone who
+ * wants to find it again.
+ */
+ agentId: string | null;
+ /** The model the subagent ran on. */
+ model: string | null;
+ /**
+ * Wall-clock time the subagent took. `u32` because the browser
+ * contract forbids 64-bit integers; 49 days of milliseconds is plenty.
+ */
+ durationMs: number | null;
+ /** Tokens the subagent consumed. `u32` for the same reason. */
+ tokens: number | null;
+ /** How many tools the subagent called. */
+ toolUses: number | null;
+ /** What kinds of tools the subagent called. */
+ stats: ToolStats | null;
+};
+
/**
* What a tool call actually did.
*
@@ -384,6 +436,11 @@ export type StopReason =
* has a variant here, so the fold never falls back to [`Self::Other`] for a
* kind ACP defines - only for `switch_mode` (nothing a reader would want
* rendered) and a kind this fold does not yet know about.
+ *
+ * Two variants are chosen by *name* rather than kind: Macro's own tools
+ * ([`Self::Macro`], [`Self::UserTool`]) arrive as ACP `other`, and what a
+ * reader wants for them is the tool's own JSON, not a generic card. The
+ * harness reader decides which names are Macro's.
*/
export type ToolDetail =
/** A shell command. ACP's `execute`. */
@@ -464,8 +521,144 @@ export type ToolDetail =
output: string | null;
/** The tool's input, when reported. */
input: unknown;
+ }
+ /**
+ * A Macro tool the fold knows by name - reached over Macro's MCP
+ * server, or called in-process by Macro's own agent. Input and output
+ * are the tool's own JSON, any MCP envelope already removed, so a
+ * reader that knows the tool renders it without parsing the wire.
+ */
+ | {
+ kind: 'macro';
+ /** The tool's arguments, as it defines them. */
+ input: unknown;
+ /**
+ * The tool's result, as it defines it; absent until the call
+ * completes.
+ */
+ output: unknown;
+ /** The error text, when the call failed. */
+ error: string | null;
+ }
+ /**
+ * A Macro user tool: the agent drafted it, the user finishes it after
+ * the turn. See [`UserToolOutcome`].
+ */
+ | {
+ kind: 'user_tool';
+ /**
+ * The draft, as the tool defines its arguments; patched as the
+ * user edits.
+ */
+ input: unknown;
+ /** Where the user got to with it. */
+ outcome: UserToolOutcome;
+ }
+ /**
+ * Work the agent delegated to another agent.
+ *
+ * ACP has no notion of this; every harness spells it as a tool call by
+ * its own conventions (Claude Code's `Agent`, OpenCode's and Cursor's
+ * `task`, Codex's `spawnAgent`, Hermes's `delegate_task`), and the
+ * harness reader recognizes it. What the subagent itself did nests in
+ * `children` when the harness attributes its calls to the parent -
+ * only Claude Code does today - and is otherwise summarized in
+ * `result`.
+ */
+ | {
+ kind: 'subagent';
+ /**
+ * What to call the delegation: the harness's description when it
+ * gave one, else the first line of the brief, else the tool's own
+ * name. Always present, so a reader never has to pick a fallback
+ * itself; `description` and `prompt` stay exactly what the harness
+ * said.
+ */
+ title: string;
+ /**
+ * Which kind of agent was delegated to (`general-purpose`,
+ * `explore`), when the harness names one.
+ */
+ agentType: string | null;
+ /** A short description of the task, when given. */
+ description: string | null;
+ /** The brief the subagent was given. */
+ prompt: string | null;
+ /**
+ * Whether the subagent was started in the background: its call
+ * completes at once and its answer, if any, arrives some other way.
+ */
+ background: boolean;
+ /**
+ * The subagent's own parts, in arrival order, for a harness that
+ * attributes them to the parent call.
+ */
+ children: MessagePart[];
+ /**
+ * What the subagent reported back, once it has.
+ *
+ * Boxed: this is by far the widest thing a part can hold, and every
+ * part pays for the widest variant.
+ */
+ result: SubagentResult | null;
};
+/**
+ * What a harness called a tool.
+ *
+ * ACP has no tool-name field - a call carries a human-readable `title` and a
+ * coarse `kind`, nothing more. The name a reader wants (`Bash`, `ReadContent`)
+ * is a harness convention: Claude Code writes it to `_meta`, others put it
+ * in the title, and tools reached over MCP arrive namespaced as
+ * `mcp__<server>__<tool>`. This type is the one place that namespacing is
+ * understood, so no reader downstream ever splits a string.
+ *
+ * Parsing is infallible: a string that is not an MCP name is a native one,
+ * however odd it looks. Nothing is dropped for being unrecognized.
+ */
+export type ToolName =
+ /**
+ * A tool the harness owns: `Bash`, `Read`, `Write`, or a Macro tool
+ * called in-process by Macro's own agent.
+ */
+ | {
+ kind: 'native';
+ /** The name as the harness reported it. */
+ name: string;
+ }
+ /**
+ * A tool reached over MCP, from the server the harness registered it
+ * under.
+ */
+ | {
+ kind: 'mcp';
+ /** The MCP server's name, as the harness registered it. */
+ server: string;
+ /** The tool's name on that server. */
+ tool: string;
+ };
+
+/**
+ * A subagent's tool use, by kind. Claude Code's `toolStats`, in the fold's
+ * vocabulary.
+ */
+export type ToolStats = {
+ /** Files read. */
+ reads: number;
+ /** Searches run. */
+ searches: number;
+ /** Shell commands run. */
+ commands: number;
+ /** Files edited. */
+ edits: number;
+ /** Lines added across those edits. */
+ linesAdded: number;
+ /** Lines removed across those edits. */
+ linesRemoved: number;
+ /** Anything else. */
+ other: number;
+};
+
/**
* How far a tool call progressed.
*
@@ -485,3 +678,61 @@ export type ToolStatus =
/** A tool call within a turn, identified by its ACP `toolCallId`. */
export type ToolUseId = string;
+
+/**
+ * How far a user tool has got - the fold's reading of the backend's
+ * `UserToolResponse`, restated each time the call is patched.
+ *
+ * A user tool's call completes, from ACP's point of view, the moment the
+ * agent invokes it: the backend answers `"PendingUserExecution"` and does
+ * nothing. What happens next - the user editing, sending, or rejecting the
+ * draft - reaches the log as later patches to the same call, so
+ * [`Self::Pending`] is where every user tool starts and where one the user
+ * never touched stays.
+ */
+export type UserToolOutcome =
+ /** Awaiting the user. The draft is whatever the input currently holds. */
+ | { kind: 'pending' }
+ /**
+ * The user edited the draft without finishing it; the input holds
+ * their edits.
+ */
+ | { kind: 'edited' }
+ /** `SendEmail`: the email went out. */
+ | {
+ kind: 'sent';
+ /** The sent message's id. */
+ messageId: string;
+ /** The thread the message landed in. */
+ threadId: string;
+ }
+ /** `SendEmail`: the user saved the draft instead of sending it. */
+ | {
+ kind: 'draft';
+ /** The saved draft's id. */
+ draftId: string;
+ /** The thread the draft belongs to, when it is a reply. */
+ threadId: string | null;
+ }
+ /**
+ * The user executed the tool; this is what the tool returned. The shape
+ * is the tool's own - a calendar event for `CreateCalendarEvent`.
+ */
+ | {
+ kind: 'completed';
+ /** The tool's result, verbatim. */
+ result: unknown;
+ }
+ /** The user declined. */
+ | { kind: 'rejected' }
+ /** The call itself failed before the user could act. */
+ | {
+ kind: 'failed';
+ /** The error, as reported. */
+ message: string;
+ }
+ /**
+ * A result arrived that this fold could not read as a user tool
+ * response - a shape the backend added after this was written.
+ */
+ | { kind: 'unrecognized' };
diff --git a/crates/agent_fold/Cargo.toml b/crates/agent_fold/Cargo.toml
index 269dc6f1e1..4c64287dba 100644
--- a/crates/agent_fold/Cargo.toml
+++ b/crates/agent_fold/Cargo.toml
@@ -43,6 +43,7 @@ agent-client-protocol = { workspace = true }
# whoever else needs the transport turns it back on, and cargo unifies.
agent_runtime_protocol = { path = "../agent_runtime_protocol", default-features = false }
clap = { workspace = true, optional = true }
+lazy-regex = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
non_empty = { path = "../non_empty" }
diff --git a/crates/agent_fold/fixtures/macro_mcp.jsonl b/crates/agent_fold/fixtures/macro_mcp.jsonl
new file mode 100644
index 0000000000..7fee5d1811
--- /dev/null
+++ b/crates/agent_fold/fixtures/macro_mcp.jsonl
@@ -0,0 +1,16 @@
+{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"init-1","method":"initialize","params":{"protocolVersion":1}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"init-1","result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","version":"0.64.2"}}}}
+{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"prompt-1","method":"session/prompt","params":{"sessionId":"s1","prompt":[{"type":"text","text":"read the plan and draft an email to alice about it"}]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__ReadContent"}},"toolCallId":"tc-read","sessionUpdate":"tool_call","rawInput":{},"status":"pending","title":"mcp__macro__ReadContent","kind":"other","content":[]}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__ReadContent"}},"toolCallId":"tc-read","sessionUpdate":"tool_call_update","rawInput":{"documentId":"4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"},"title":"mcp__macro__ReadContent","kind":"other"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__ReadContent"}},"toolCallId":"tc-read","sessionUpdate":"tool_call_update","status":"completed","rawOutput":{"content":[{"type":"text","text":"{\"content\":{\"text\":\"Q3 plan: ship the fold.\"},\"comments\":[]}"}],"structuredContent":{"content":{"text":"Q3 plan: ship the fold."},"comments":[]},"isError":false},"content":[{"type":"content","content":{"type":"text","text":"{\"content\":{\"text\":\"Q3 plan: ship the fold.\"},\"comments\":[]}"}}]}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__SendEmail"}},"toolCallId":"tc-email","sessionUpdate":"tool_call","rawInput":{},"status":"pending","title":"mcp__macro__SendEmail","kind":"other","content":[]}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__SendEmail"}},"toolCallId":"tc-email","sessionUpdate":"tool_call_update","rawInput":{"subject":"Q3 plan","body":"Hi Alice,\n\nThe plan is to ship the fold.","to":[{"email":"[email protected]","name":"Alice"}]},"title":"mcp__macro__SendEmail","kind":"other"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__SendEmail"}},"toolCallId":"tc-email","sessionUpdate":"tool_call_update","status":"completed","rawOutput":{"content":[{"type":"text","text":"\"PendingUserExecution\""}],"structuredContent":"PendingUserExecution","isError":false},"content":[{"type":"content","content":{"type":"text","text":"\"PendingUserExecution\""}}]}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__ListEntities"}},"toolCallId":"tc-list","sessionUpdate":"tool_call","rawInput":{"limit":5},"status":"pending","title":"mcp__macro__ListEntities","kind":"other","content":[]}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__ListEntities"}},"toolCallId":"tc-list","sessionUpdate":"tool_call_update","status":"failed","rawOutput":{"content":[{"type":"text","text":"Failed to list entities: permission denied"}],"isError":true},"content":[{"type":"content","content":{"type":"text","text":"Failed to list entities: permission denied"}}]}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I drafted the email; review and send when ready."}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"prompt-1","result":{"stopReason":"end_turn"}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-email","rawInput":{"subject":"Q3 plan (updated)","body":"Hi Alice,\n\nThe plan is to ship the fold this week.","to":[{"email":"[email protected]","name":"Alice"}]},"rawOutput":{"UserAction":"userEdited"}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s1","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-email","rawOutput":{"UserAction":{"sent":{"message_id":"9c4d2c6e-2f3a-4d1e-8b0a-5e6f7a8b9c0d","thread_id":"1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"}}}}}}}
diff --git a/crates/agent_fold/fixtures/real/subagent_claude_code.jsonl b/crates/agent_fold/fixtures/real/subagent_claude_code.jsonl
new file mode 100644
index 0000000000..62faed2d88
--- /dev/null
+++ b/crates/agent_fold/fixtures/real/subagent_claude_code.jsonl
@@ -0,0 +1,28 @@
+{"ts":"2026-09-02T21:55:36.703Z","direction":"to_server","content":{"type":"event","event":"acp_ready"}}
+{"ts":"2026-09-02T21:55:36.706Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"ab3ce3a4-657c-485f-a417-d08abf607212","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":true,"writeTextFile":true},"terminal":true,"session":{"configOptions":{"boolean":{}}},"auth":{"terminal":true},"_meta":{"terminal_output":true,"terminal-auth":true}},"clientInfo":{"name":"zed","title":"Zed","version":"1.11.3+stable"}}}}
+{"ts":"2026-09-02T21:55:41.551Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"ab3ce3a4-657c-485f-a417-d08abf607212","result":{"protocolVersion":1,"agentCapabilities":{"_meta":{"claudeCode":{"promptQueueing":true}},"promptCapabilities":{"image":true,"embeddedContext":true},"mcpCapabilities":{"http":true,"sse":true},"auth":{"logout":{}},"providers":{},"loadSession":true,"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"resume":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"0.64.2"},"authMethods":[{"description":"Run `claude /login` in the terminal","name":"Log in with Claude","id":"claude-login","type":"terminal","args":["--cli"],"_meta":{"terminal-auth":{"command":"/nix/store/0nbp03038s33ck712yx9219gcj3a2sqm-nodejs-slim-24.18.0/bin/node","args":["/home/user/.npm/_npx/539edbc7afd0f13d/node_modules/.bin/claude-agent-acp","--cli"],"label":"Claude Login"}}}],"_meta":{"steering":{"supported":true}}}}}
+{"ts":"2026-09-02T21:57:03.660Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"d048cbc6-104e-4785-bac4-f71716865ce0","method":"session/new","params":{"cwd":"/home/user/repos/macro","mcpServers":[]}}}
+{"ts":"2026-09-02T21:57:04.194Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"d048cbc6-104e-4785-bac4-f71716865ce0","result":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","modes":{"currentModeId":"bypassPermissions","availableModes":[{"id":"auto","name":"Auto","description":"Use a model classifier to approve/deny permission prompts"},{"id":"default","name":"Manual","description":"Standard behavior, prompts for dangerous operations"},{"id":"acceptEdits","name":"Accept Edits","description":"Auto-accept file edit operations"},{"id":"plan","name":"Plan Mode","description":"Planning mode, no actual tool execution"},{"id":"dontAsk","name":"Don't Ask","description":"Don't prompt for permissions, deny if not pre-approved"},{"id":"bypassPermissions","name":"Bypass Permissions","description":"Bypass all permission checks"}]},"configOptions":[{"id":"mode","name":"Mode","description":"Session permission mode","category":"mode","type":"select","currentValue":"bypassPermissions","options":[{"value":"auto","name":"Auto","description":"Use a model classifier to approve/deny permission prompts"},{"value":"default","name":"Manual","description":"Standard behavior, prompts for dangerous operations"},{"value":"acceptEdits","name":"Accept Edits","description":"Auto-accept file edit operations"},{"value":"plan","name":"Plan Mode","description":"Planning mode, no actual tool execution"},{"value":"dontAsk","name":"Don't Ask","description":"Don't prompt for permissions, deny if not pre-approved"},{"value":"bypassPermissions","name":"Bypass Permissions","description":"Bypass all permission checks"}]},{"id":"model","name":"Model","description":"AI model to use","category":"model","type":"select","currentValue":"sonnet","options":[{"value":"default","name":"Default (recommended)","description":"Use the default model (currently Opus 5 (1M context)) · $5/$25 per Mtok"},{"value":"opus[1m]","name":"Opus (1M context)","description":"Opus 5 with 1M context · Best for everyday, complex tasks · $5/$25 per Mtok"},{"value":"claude-fable-5[1m]","name":"Fable","description":"Fable 5 · Most capable for your hardest and longest-running tasks · $10/$50 per Mtok"},{"value":"sonnet","name":"Sonnet","description":"Sonnet 5 · Efficient for routine tasks · $2/$10 per Mtok · promo through Aug 31"},{"value":"haiku","name":"Haiku","description":"Haiku 4.5 · Fastest for quick answers · $1/$5 per Mtok"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"medium","options":[{"value":"default","name":"Default"},{"value":"low","name":"Low"},{"value":"medium","name":"Medium"},{"value":"high","name":"High"},{"value":"xhigh","name":"Xhigh"},{"value":"max","name":"Max"}]},{"id":"agent","name":"Agent","description":"Main-thread agent persona","type":"select","currentValue":"default","options":[{"value":"default","name":"Default","description":"Standard Claude Code agent"}]}]}}}
+{"ts":"2026-09-02T21:57:04.226Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"56062802-48df-4dca-b98d-966c762ee74c","method":"session/set_config_option","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","configId":"model","value":"opus[1m]"}}}
+{"ts":"2026-09-02T21:57:04.228Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"56062802-48df-4dca-b98d-966c762ee74c","result":{"configOptions":[{"id":"mode","name":"Mode","description":"Session permission mode","category":"mode","type":"select","currentValue":"bypassPermissions","options":[{"value":"auto","name":"Auto","description":"Use a model classifier to approve/deny permission prompts"},{"value":"default","name":"Manual","description":"Standard behavior, prompts for dangerous operations"},{"value":"acceptEdits","name":"Accept Edits","description":"Auto-accept file edit operations"},{"value":"plan","name":"Plan Mode","description":"Planning mode, no actual tool execution"},{"value":"dontAsk","name":"Don't Ask","description":"Don't prompt for permissions, deny if not pre-approved"},{"value":"bypassPermissions","name":"Bypass Permissions","description":"Bypass all permission checks"}]},{"id":"model","name":"Model","description":"AI model to use","category":"model","type":"select","currentValue":"opus[1m]","options":[{"value":"default","name":"Default (recommended)","description":"Use the default model (currently Opus 5 (1M context)) · $5/$25 per Mtok"},{"value":"opus[1m]","name":"Opus (1M context)","description":"Opus 5 with 1M context · Best for everyday, complex tasks · $5/$25 per Mtok"},{"value":"claude-fable-5[1m]","name":"Fable","description":"Fable 5 · Most capable for your hardest and longest-running tasks · $10/$50 per Mtok"},{"value":"sonnet","name":"Sonnet","description":"Sonnet 5 · Efficient for routine tasks · $2/$10 per Mtok · promo through Aug 31"},{"value":"haiku","name":"Haiku","description":"Haiku 4.5 · Fastest for quick answers · $1/$5 per Mtok"}]},{"id":"effort","name":"Effort","description":"Available effort levels for this model","category":"thought_level","type":"select","currentValue":"medium","options":[{"value":"default","name":"Default"},{"value":"low","name":"Low"},{"value":"medium","name":"Medium"},{"value":"high","name":"High"},{"value":"xhigh","name":"Xhigh"},{"value":"max","name":"Max"}]},{"id":"fast","name":"Fast mode","description":"Faster responses on supported models","category":"model_config","type":"boolean","currentValue":false},{"id":"agent","name":"Agent","description":"Main-thread agent persona","type":"select","currentValue":"default","options":[{"value":"default","name":"Default","description":"Standard Claude Code agent"}]}]}}}
+{"ts":"2026-09-02T21:57:08.877Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"b63bb736-1022-4b01-abcf-d00c2b6adf90","method":"session/prompt","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","prompt":[{"type":"text","text":"spwan a subagent to use python to add 5+5"}]}}}
+{"ts":"2026-09-02T21:57:10.293Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"usage_update","used":37879,"size":1000000}}}}
+{"ts":"2026-09-02T21:57:10.335Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call","rawInput":{},"status":"pending","title":"Task","kind":"think","content":[]}}}}
+{"ts":"2026-09-02T21:57:11.047Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call_update","rawInput":{"subagent_type":"general-purpose"},"title":"Task","kind":"think"}}}}
+{"ts":"2026-09-02T21:57:11.047Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call_update","rawInput":{"subagent_type":"general-purpose","description":"Add 5+5 with Python"},"title":"Add 5+5 with Python","kind":"think"}}}}
+{"ts":"2026-09-02T21:57:11.550Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call_update","rawInput":{"subagent_type":"general-purpose","description":"Add 5+5 with Python","prompt":"Run `python3 -c \"print(5+5)\"` in bash and report the output."},"title":"Add 5+5 with Python","kind":"think"}}}}
+{"ts":"2026-09-02T21:57:11.552Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call_update","rawInput":{"subagent_type":"general-purpose","description":"Add 5+5 with Python","prompt":"Run `python3 -c \"print(5+5)\"` in bash and report the output.","run_in_background":false},"title":"Add 5+5 with Python","kind":"think","content":[{"type":"content","content":{"type":"text","text":"Run `python3 -c \"print(5+5)\"` in bash and report the output."}}]}}}}
+{"ts":"2026-09-02T21:57:11.566Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"usage_update","used":38019,"size":1000000}}}}
+{"ts":"2026-09-02T21:57:13.547Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Bash","title":"Run python addition","parentToolUseId":"toolu_0134fqTfrmNcuarHkdgLtffW"},"terminal_info":{"terminal_id":"toolu_01CCNovB4Fe1yRrJNhJjx3ah"}},"toolCallId":"toolu_01CCNovB4Fe1yRrJNhJjx3ah","sessionUpdate":"tool_call","rawInput":{"command":"python3 -c \"print(5+5)\"","description":"Run python addition"},"status":"pending","title":"python3 -c \"print(5+5)\"","kind":"execute","content":[{"type":"terminal","terminalId":"toolu_01CCNovB4Fe1yRrJNhJjx3ah"}]}}}}
+{"ts":"2026-09-02T21:57:13.829Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolResponse":{"stdout":"10","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false},"toolName":"Bash"}},"toolCallId":"toolu_01CCNovB4Fe1yRrJNhJjx3ah","sessionUpdate":"tool_call_update"}}}}
+{"ts":"2026-09-02T21:57:13.840Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"terminal_output":{"terminal_id":"toolu_01CCNovB4Fe1yRrJNhJjx3ah","data":"10"},"claudeCode":{"parentToolUseId":"toolu_0134fqTfrmNcuarHkdgLtffW"}},"toolCallId":"toolu_01CCNovB4Fe1yRrJNhJjx3ah","sessionUpdate":"tool_call_update"}}}}
+{"ts":"2026-09-02T21:57:13.840Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Bash","parentToolUseId":"toolu_0134fqTfrmNcuarHkdgLtffW"},"terminal_exit":{"terminal_id":"toolu_01CCNovB4Fe1yRrJNhJjx3ah","exit_code":0,"signal":null}},"toolCallId":"toolu_01CCNovB4Fe1yRrJNhJjx3ah","sessionUpdate":"tool_call_update","status":"completed","rawOutput":"10","content":[{"type":"terminal","terminalId":"toolu_01CCNovB4Fe1yRrJNhJjx3ah"}]}}}}
+{"ts":"2026-09-02T21:57:15.042Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolResponse":{"status":"completed","prompt":"Run `python3 -c \"print(5+5)\"` in bash and report the output.","agentId":"af2647314187b6bf1","agentType":"general-purpose","content":[{"type":"text","text":"Output: `10`"}],"resolvedModel":"claude-opus-5[1m]","totalDurationMs":3485,"totalTokens":26077,"totalToolUseCount":1,"usage":{"input_tokens":1,"cache_creation_input_tokens":4247,"cache_read_input_tokens":21821,"output_tokens":8,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":4247},"inference_geo":"global","iterations":[{"input_tokens":1,"output_tokens":8,"cache_read_input_tokens":21821,"cache_creation_input_tokens":4247,"cache_creation":{"ephemeral_5m_input_tokens":4247,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"toolStats":{"readCount":0,"searchCount":0,"bashCount":1,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}},"toolName":"Agent"}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call_update"}}}}
+{"ts":"2026-09-02T21:57:15.083Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"_meta":{"claudeCode":{"toolName":"Agent"}},"toolCallId":"toolu_0134fqTfrmNcuarHkdgLtffW","sessionUpdate":"tool_call_update","status":"completed","rawOutput":[{"type":"text","text":"Output: `10`"},{"type":"text","text":"agentId: af2647314187b6bf1 (use SendMessage with to: 'af2647314187b6bf1', summary: '<5-10 word recap>' to continue this agent)\n<usage>subagent_tokens: 26077\ntool_uses: 1\nduration_ms: 3485</usage>"}],"content":[{"type":"content","content":{"type":"text","text":"Output: `10`"}}]}}}}
+{"ts":"2026-09-02T21:57:16.114Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"usage_update","used":38129,"size":1000000}}}}
+{"ts":"2026-09-02T21:57:16.119Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"The"},"messageId":"msg_011CefMsbqGgtkieZ72ncGAU"}}}}
+{"ts":"2026-09-02T21:57:16.412Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" subagent ran `python3 -c \"print(5+5)\"` → **10**."},"messageId":"msg_011CefMsbqGgtkieZ72ncGAU"}}}}
+{"ts":"2026-09-02T21:57:16.424Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"usage_update","used":38156,"size":1000000}}}}
+{"ts":"2026-09-02T21:57:16.444Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"usage_update","used":38156,"size":1000000,"cost":{"amount":0.40005725,"currency":"USD"},"_meta":{"_claude/origin":{"kind":"human"}}}}}}
+{"ts":"2026-09-02T21:57:16.444Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"b63bb736-1022-4b01-abcf-d00c2b6adf90","result":{"stopReason":"end_turn","usage":{"inputTokens":4,"outputTokens":185,"cachedReadTokens":37860,"cachedWriteTokens":38126,"totalTokens":76175}}}}
+{"ts":"2026-09-02T21:57:16.449Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"1952daad-a0e9-4c68-aceb-373c9a9f0c7a","update":{"sessionUpdate":"session_info_update","title":"Spawn subagent to add numbers with Python","updatedAt":"2026-09-02T21:57:15.099Z"}}}}
diff --git a/crates/agent_fold/fixtures/real/subagent_cursor.jsonl b/crates/agent_fold/fixtures/real/subagent_cursor.jsonl
new file mode 100644
index 0000000000..050f5bf856
--- /dev/null
+++ b/crates/agent_fold/fixtures/real/subagent_cursor.jsonl
@@ -0,0 +1,184 @@
+{"ts": "2026-09-03T15:52:27.885Z", "direction": "to_server", "content": {"type": "event", "event": "acp_ready"}}
+{"ts": "2026-09-03T15:52:27.896Z", "direction": "to_runtime", "content": {"id": "agent_session:01a067f8-b552-7fce-b231-b04e17a4de25:0", "type": "acp", "method": "initialize", "params": {"protocolVersion": 1, "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false}}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:27.916Z", "direction": "to_server", "content": {"id": "agent_session:01a067f8-b552-7fce-b231-b04e17a4de25:0", "type": "acp", "result": {"agentInfo": {"name": "cursor-acp", "version": "0.1.0"}, "authMethods": [], "protocolVersion": 1, "agentCapabilities": {"auth": {}, "loadSession": true, "mcpCapabilities": {"sse": true, "http": true}, "promptCapabilities": {"audio": false, "image": false, "embeddedContext": true}, "sessionCapabilities": {}}}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:27.936Z", "direction": "to_runtime", "content": {"id": "agent_session:01a067f8-b552-7fce-b231-b04e17a4de25:1", "type": "acp", "method": "session/new", "params": {"cwd": "/workspace", "mcpServers": [{"url": "https://beans-willow-arg-wright.trycloudflare.com/mcp-macro", "name": "macro", "type": "http", "headers": [{"name": "Authorization", "value": "Bearer DUMMY-SECRET-dacaf015-bearer_token"}]}]}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:28.148Z", "direction": "to_server", "content": {"id": "agent_session:01a067f8-b552-7fce-b231-b04e17a4de25:1", "type": "acp", "result": {"sessionId": "cursor-acp-1", "configOptions": [{"id": "model", "name": "Model", "type": "select", "options": [{"name": "Auto", "value": "auto-smart"}, {"name": "Auto", "value": "default"}, {"name": "Cursor Grok 4.6", "value": "grok-4.6"}, {"name": "Composer 2.5", "value": "composer-2.5"}, {"name": "Claude Opus 5", "value": "claude-opus-5"}, {"name": "Claude Opus 4.8", "value": "claude-opus-4-8"}, {"name": "GPT-5.6 Sol", "value": "gpt-5.6-sol"}, {"name": "GPT-5.5", "value": "gpt-5.5"}, {"name": "Claude Fable 5.1", "value": "claude-fable-5-1"}, {"name": "Claude Fable 5", "value": "claude-fable-5"}, {"name": "Cursor Grok 4.5", "value": "grok-4.5"}, {"name": "Gemini 3.8 Flash", "value": "gemini-3.8-flash"}, {"name": "Gemini 3.7 Flash", "value": "gemini-3.7-flash"}, {"name": "GPT-5.6 Terra", "value": "gpt-5.6-terra"}, {"name": "Claude Sonnet 5", "value": "claude-sonnet-5"}, {"name": "Claude Sonnet 4.6", "value": "claude-sonnet-4-6"}, {"name": "Codex 5.3", "value": "gpt-5.3-codex"}, {"name": "Claude Opus 4.7", "value": "claude-opus-4-7"}, {"name": "GPT-5.4", "value": "gpt-5.4"}, {"name": "Claude Opus 4.6", "value": "claude-opus-4-6"}, {"name": "Claude Opus 4.5", "value": "claude-opus-4-5"}, {"name": "GPT-5.2", "value": "gpt-5.2"}, {"name": "GPT-5.6 Luna", "value": "gpt-5.6-luna"}, {"name": "Gemini 3.6 Flash", "value": "gemini-3.6-flash"}, {"name": "Gemini 3.1 Pro", "value": "gemini-3.1-pro"}, {"name": "GPT-5.4 Mini", "value": "gpt-5.4-mini"}, {"name": "GPT-5.4 Nano", "value": "gpt-5.4-nano"}, {"name": "Claude Haiku 4.5", "value": "claude-haiku-4-5"}, {"name": "Claude Sonnet 4.5", "value": "claude-sonnet-4-5"}, {"name": "GPT-5.1", "value": "gpt-5.1"}, {"name": "Gemini 3 Flash", "value": "gemini-3-flash"}, {"name": "Gemini 3.5 Flash", "value": "gemini-3.5-flash"}, {"name": "Claude Sonnet 4", "value": "claude-sonnet-4"}, {"name": "GPT-5 Mini", "value": "gpt-5-mini"}, {"name": "Gemini 2.5 Flash", "value": "gemini-2.5-flash"}, {"name": "Kimi K3", "value": "kimi-k3"}, {"name": "Kimi K2.7 Code", "value": "kimi-k2.7-code"}, {"name": "GLM 5.2", "value": "glm-5.2"}], "currentValue": "default"}]}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:28.166Z", "direction": "to_runtime", "content": {"id": "agent_session:01a067f8-b5ec-743f-a96a-3a05709b0a26", "type": "acp", "method": "session/prompt", "params": {"prompt": [{"text": "<m-agent-context>{\"version\":1,\"text\":\"Prior message 1:\\nSender: macro|[email protected]\\nContent: Hey \\u003cm-user-mention>{\\\"userId\\\":\\\"macro|[email protected]\\\",\\\"email\\\":\\\"[email protected]\\\"}\\u003c/m-user-mention>,\\n\\nWelcome to Macro, we're excited for you to try it out.\\n\\nThis is your own personal support Channel, with \\u003cm-user-mention>{\\\"userId\\\":\\\"macro|[email protected]\\\",\\\"email\\\":\\\"[email protected]\\\"}\\u003c/m-user-mention> (ceo) and \\u003cm-user-mention>{\\\"userId\\\":\\\"macro|[email protected]\\\",\\\"email\\\":\\\"[email protected]\\\"}\\u003c/m-user-mention> (cto) and me (julia).\\n\\nIf you have any feedback or find any bugs let us know here.\"}</m-agent-context>\n\n<m-user-mention>{\"userId\":\"bot|00000000-0000-0000-0000-00000000c5c5\",\"email\":\"Cursor\",\"displayName\":\"Cursor\"}</m-user-mention> spawn a subagent to use python to take the integral of x^2 dx between 1 and 5", "type": "text"}], "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:34.664Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "**Implementing subagent use**\n\nI", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:34.723Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " need", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:34.776Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " to", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:34.839Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " use", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:34.918Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.000Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " sub", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.081Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "agent", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.185Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " because", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.252Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.348Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " user", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.424Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " specifically", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.518Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " asked", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.589Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " for", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.682Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " it", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.740Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.753Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " I'm", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.788Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " considering", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.836Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " whether", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.846Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " to", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.854Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " choose", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.969Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.982Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " general", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:35.993Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " purpose", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.014Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " or", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.023Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " a", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.045Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " simpler", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.055Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " option", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.063Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ",", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.100Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " but", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.108Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " that's", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.118Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " alright", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.126Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.135Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " First", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.144Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ",", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.152Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " I", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.162Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " should", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.171Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " update", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.181Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.190Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " commentary", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.198Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.206Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " It", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.215Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " looks", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.224Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " like", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.232Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " there", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.241Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " might", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.249Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " not", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.257Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " be", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.265Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " any", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.273Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " repo", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.281Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " work", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.289Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " required", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.307Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ",", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.319Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " and", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.328Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " perhaps", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.337Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " no", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.346Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " testing", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.355Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " is", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.366Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " necessary", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.374Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " since", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.383Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " it", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.391Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " seems", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.399Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " simple", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.408Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " to", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.416Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " handle", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.474Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.483Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " I'll", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.491Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " proceed", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.499Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " with", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.508Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.516Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " sub", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.524Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "agent", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.532Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " using", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.541Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " Python", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.549Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " and", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.558Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " return", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.566Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.575Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " result", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.583Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.591Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "I", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.599Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "’m", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.608Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " spawning", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.617Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " a", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.624Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " sub", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.633Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "agent", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.642Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " to", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.664Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " compute", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.672Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.680Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " definite", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.688Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " integral", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.697Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " in", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.704Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " Python", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.713Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " and", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.721Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " return", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.751Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.760Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " result", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.767Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " directly", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:36.775Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:38.244Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"title": "task", "status": "in_progress", "rawInput": {"model": "default", "prompt": "Use Python to compute the definite integral of x^2 dx from 1 to 5. Return the exact value and a brief note of the method used.", "agentId": "bc-b723d011-d87a-5f5e-a0b0-bf3ffddc2693", "machine": {"sameMachine": {}}, "description": "Compute integral in Python", "subagentType": {"unspecified": {}}}, "toolCallId": "call_WDdIO2oFNumfaB7SNHinSgRM fc_084f7006b4bfb13e016a9997c35c8087d2b209ca20dbbd2613", "sessionUpdate": "tool_call"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:50.914Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"kind": "other", "title": "task", "status": "completed", "rawInput": {"model": "default", "prompt": "Use Python to compute the definite integral of x^2 dx from 1 to 5. Return the exact value and a brief note of the method used.", "agentId": "bc-b723d011-d87a-5f5e-a0b0-bf3ffddc2693", "machine": {"sameMachine": {}}, "description": "Compute integral in Python", "subagentType": {"unspecified": {}}}, "rawOutput": {"result": {"success": {"agentId": "bc-b723d011-d87a-5f5e-a0b0-bf3ffddc2693", "durationMs": "12978", "conversationSteps": [{"thinkingMessage": {"text": "**Executing terminal command**\n\nI see that I need an answer via a terminal command. I could compute this mentally, but since the request is labeled as simple, using a terminal command seems more appropriate. I should make sure to provide a commentary update first. So, I'll opt to use the Python shell to get this done. I just need to make sure that I'm following the correct steps to get the answer efficiently!", "durationMs": 1168, "startedAtMs": "1788450761262", "completedAtMs": "1788450762430"}}, {"assistantMessage": {"text": "I’m computing the definite integral in Python and will return the exact result with a short note on the method.", "startedAtMs": "1788450762437", "completedAtMs": "1788450762708"}}, {"toolCall": {"toolCallId": "call_njT7kCrh8vMAKfDvXg3DmkAJ\nfc_04cef57509d465f7016a9997c9d3f887d28128fd586814459d", "startedAtMs": "1788450763197", "completedAtMs": "1788450763496", "shellToolCall": {"args": {"command": "python3 - <<'PY'\nimport sympy as sp\nx = sp.symbols('x')\nexpr = sp.integrate(x**2, (x, 1, 5))\nprint(expr)\nPY", "timeout": 30000, "requestId": "0c781aed-147d-487b-9f85-5b3ea2842976", "closeStdin": true, "toolCallId": "call_njT7kCrh8vMAKfDvXg3DmkAJ\nfc_04cef57509d465f7016a9997c9d3f887d28128fd586814459d", "description": "Compute exact integral with SymPy", "hardTimeout": 86400000, "parsingResult": {"redirects": [{"operator": "<<", "targetText": "python3", "destinationFds": [0], "targetNodeType": "heredoc_redirect"}], "hasRedirects": true, "executableCommands": [{"name": "python3", "fullText": "python3"}], "allRedirectsAreDevNull": true}, "conversationId": "bc-b723d011-d87a-5f5e-a0b0-bf3ffddc2693", "simpleCommands": ["python3"], "timeoutBehavior": "TIMEOUT_BEHAVIOR_BACKGROUND", "hasInputRedirect": true, "workingDirectory": "/workspace"}, "result": {"failure": {"stderr": "Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nModuleNotFoundError: No module named 'sympy'\n", "command": "python3 - <<'PY'\nimport sympy as sp\nx = sp.symbols('x')\nexpr = sp.integrate(x**2, (x, 1, 5))\nprint(expr)\nPY", "exitCode": 1, "executionTime": 296, "workingDirectory": "/workspace", "interleavedOutput": "Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nModuleNotFoundError: No module named 'sympy'\n", "localExecutionTimeMs": 247}, "isBackground": false}, "description": "Compute exact integral with SymPy"}}}, {"thinkingMessage": {"text": "**Considering fallback options**\n\nI'm thinking about maybe using a plain Python formula as a fallback. It seems like a simple way to handle things if my first approach isn't working out. I wonder if I'll need to adjust any parameters or structure it differently. Let's see if this gives me the results I want. It's always good to have these alternatives ready, just in case!", "durationMs": 966, "startedAtMs": "1788450764724", "completedAtMs": "1788450765690"}}, {"assistantMessage": {"text": "SymPy isn’t installed here, so I’m using a short Python evaluation of the antiderivative directly to keep the result exact.", "startedAtMs": "1788450765697", "completedAtMs": "1788450766063"}}, {"toolCall": {"toolCallId": "call_a6FRCO5T7CJ0kFmetndLRJhj\nfc_04cef57509d465f7016a9997cd322087d28a06be214c6849d1", "startedAtMs": "1788450766491", "completedAtMs": "1788450766693", "shellToolCall": {"args": {"command": "python3 - <<'PY'\nfrom fractions import Fraction\nresult = Fraction(5**3 - 1**3, 3)\nprint(result)\nPY", "timeout": 30000, "requestId": "0c781aed-147d-487b-9f85-5b3ea2842976", "closeStdin": true, "toolCallId": "call_a6FRCO5T7CJ0kFmetndLRJhj\nfc_04cef57509d465f7016a9997cd322087d28a06be214c6849d1", "description": "Compute exact antiderivative value", "hardTimeout": 86400000, "parsingResult": {"redirects": [{"operator": "<<", "targetText": "python3", "destinationFds": [0], "targetNodeType": "heredoc_redirect"}], "hasRedirects": true, "executableCommands": [{"name": "python3", "fullText": "python3"}], "allRedirectsAreDevNull": true}, "conversationId": "bc-b723d011-d87a-5f5e-a0b0-bf3ffddc2693", "simpleCommands": ["python3"], "timeoutBehavior": "TIMEOUT_BEHAVIOR_BACKGROUND", "hasInputRedirect": true, "workingDirectory": "/workspace"}, "result": {"success": {"stdout": "124/3\n", "command": "python3 - <<'PY'\nfrom fractions import Fraction\nresult = Fraction(5**3 - 1**3, 3)\nprint(result)\nPY", "executionTime": 201, "workingDirectory": "/workspace", "interleavedOutput": "124/3\n", "localExecutionTimeMs": 139}, "isBackground": false}, "description": "Compute exact antiderivative value"}}}, {"assistantMessage": {"text": "The exact value is **124/3**.\n\nMethod: I used Python to evaluate the antiderivative of \\(x^2\\), which is \\(x^3/3\\), and then applied the bounds:\n\\[\n\\int_1^5 x^2\\,dx = \\left[\\frac{x^3}{3}\\right]_1^5 = \\frac{125 - 1}{3} = \\frac{124}{3}.\n\\]", "startedAtMs": "1788450768263", "completedAtMs": "1788450769760"}}]}}}, "toolCallId": "call_WDdIO2oFNumfaB7SNHinSgRM fc_084f7006b4bfb13e016a9997c35c8087d2b209ca20dbbd2613", "sessionUpdate": "tool_call_update"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:52.982Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "I", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:52.995Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " spawned", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.061Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " a", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.072Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " sub", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.081Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "agent", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.090Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " and", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.099Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " it", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.107Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " computed", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.116Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " the", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.124Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " integral", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.133Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " as", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.141Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " **", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.149Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "124", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.157Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "/", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.165Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "3", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.173Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "**", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.181Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".\n\n", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.190Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "\\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.198Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "[\n", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.206Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "\\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.215Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "int", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.224Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "_", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.232Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "1", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.241Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "^", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.249Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "5", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.258Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " x", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.266Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "^", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.274Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "2", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.282Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " \\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.290Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ",", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.299Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " dx", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.307Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " =", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.315Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " \\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.323Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "left", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.331Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "[\\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.339Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "frac", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.385Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "{x", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.409Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "^", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.419Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "3", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.428Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "}{", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.436Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "3", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.445Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "}\\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.453Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "right", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.461Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "]_", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.468Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "1", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.476Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "^", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.484Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "5", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.492Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " =", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.500Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " \\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.509Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "frac", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.517Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "{", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.526Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "125", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.534Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " -", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.542Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " ", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.551Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "1", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.559Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "}{", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.567Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "3", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.574Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "}", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.582Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " =", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.590Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " \\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.598Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "frac", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.607Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "{", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.614Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "124", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.622Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "}{", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.629Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "3", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.638Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "}\n", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.646Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "\\", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.654Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "]\n\n", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.661Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "That", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.669Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "’s", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.677Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " approximately", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.685Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " **", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.692Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "41", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.700Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.708Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "333", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.716Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "3", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.724Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "**", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:53.732Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": ".", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "cursor-acp-1"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T15:52:55.189Z", "direction": "to_server", "content": {"id": "agent_session:01a067f8-b5ec-743f-a96a-3a05709b0a26", "type": "acp", "result": {"stopReason": "end_turn"}, "jsonrpc": "2.0"}}
diff --git a/crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl b/crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl
new file mode 100644
index 0000000000..8edd7b0d80
--- /dev/null
+++ b/crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl
@@ -0,0 +1,17 @@
+{"ts": "2026-09-03T16:31:52.342Z", "direction": "to_server", "content": {"type": "event", "event": "acp_ready"}}
+{"ts": "2026-09-03T16:31:52.357Z", "direction": "to_runtime", "content": {"id": "agent_session:01a0681c-ca0b-7359-8eee-e5bf25598a82:0", "type": "acp", "method": "initialize", "params": {"protocolVersion": 1, "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false}}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:31:52.368Z", "direction": "to_server", "content": {"id": "agent_session:01a0681c-ca0b-7359-8eee-e5bf25598a82:0", "type": "acp", "result": {"agentInfo": {"name": "macro-inmem", "version": "0.1.0"}, "authMethods": [], "protocolVersion": 1, "agentCapabilities": {"auth": {}, "loadSession": false, "mcpCapabilities": {"sse": false, "http": false}, "promptCapabilities": {"audio": false, "image": false, "embeddedContext": false}, "sessionCapabilities": {"resume": {}}}}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:31:52.378Z", "direction": "to_runtime", "content": {"id": "agent_session:01a0681c-ca0b-7359-8eee-e5bf25598a82:1", "type": "acp", "method": "session/new", "params": {"cwd": "/workspace", "mcpServers": [{"url": "https://beans-willow-arg-wright.trycloudflare.com/mcp-macro", "name": "macro", "type": "http", "headers": [{"name": "Authorization", "value": "Bearer DUMMY-SECRET-6f811fd1-bearer_token"}]}]}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:31:52.387Z", "direction": "to_server", "content": {"id": "agent_session:01a0681c-ca0b-7359-8eee-e5bf25598a82:1", "type": "acp", "result": {"sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:31:57.238Z", "direction": "to_runtime", "content": {"id": "agent_session:01a0681c-dd2f-7cf9-90b8-32198e5cf8b0", "type": "acp", "method": "session/prompt", "params": {"prompt": [{"text": "spawn a subagent to add 5+5 ini python, then reason that it's right, and then write a frog poem, and then give me the last line of the frog poem and the nunber", "type": "text"}], "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:08.404Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "The user wants me to spawn a subagent for a simple task—adding 5+5 in Python—then follow up with reasoning, a frog poem, and a final answer. I'll go ahead and delegate that small task to the subagent as instructed, even though it's a trivial computation.", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:08.428Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"_meta": {"macro": {"subagent": true, "toolName": "Subagent"}}, "title": "Subagent", "status": "in_progress", "rawInput": {"task": "Compute 5 + 5 in Python by executing the code, and report the exact numeric result that Python outputs."}, "toolCallId": "QHiaeI_bhc1dMjpBo_Un0", "sessionUpdate": "tool_call"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:10.482Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"status": "completed", "rawOutput": {"result": "I'll execute the Python code to compute 5 + 5.\n\nBased on executing the Python code `5 + 5`, the exact numeric result that Python outputs is:\n\n**10**\n\nThe computation `5 + 5` in Python returns the integer value `10`."}, "toolCallId": "QHiaeI_bhc1dMjpBo_Un0", "sessionUpdate": "tool_call_update"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.487Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "I'm confirming the answer makes sense, then I'll craft a short frog-themed poem before finishing with the final line and the number.", "type": "text"}, "sessionUpdate": "agent_thought_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.498Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "The subagent ran it and Python returned $$ 5 + 5 = 10 $$.\n\nThat", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.507Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " checks out: adding two groups of five gives ten, same as $$ 2 \\times 5 = 10 $$, so the result is right.\n\nHere's the frog po", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.515Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "em:\n\n*Ode to a Frog*\n\nA little frog sat on a log,\nhalf-hidden in the morning fog.\nHe blinked his eyes, he puffed his thro", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.524Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "at,\nthen sang a low and croaking note.\nHe leapt across the lily pads,\nignoring all the passing g", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.552Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": "nats,\nand dove into the cool green deep,\nwhere quiet frogs go off to sleep.\n\nLast line:", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.782Z", "direction": "to_server", "content": {"type": "acp", "method": "session/update", "params": {"update": {"content": {"text": " **where quiet frogs go off to sleep.**\nNumber: **10**", "type": "text"}, "sessionUpdate": "agent_message_chunk"}, "sessionId": "01a0681c-ca43-77ff-b336-3d52af217a8e"}, "jsonrpc": "2.0"}}
+{"ts": "2026-09-03T16:32:16.796Z", "direction": "to_server", "content": {"id": "agent_session:01a0681c-dd2f-7cf9-90b8-32198e5cf8b0", "type": "acp", "result": {"stopReason": "end_turn"}, "jsonrpc": "2.0"}}
diff --git a/crates/agent_fold/fixtures/real/subagent_opencode.jsonl b/crates/agent_fold/fixtures/real/subagent_opencode.jsonl
new file mode 100644
index 0000000000..51b62bc948
--- /dev/null
+++ b/crates/agent_fold/fixtures/real/subagent_opencode.jsonl
@@ -0,0 +1,14 @@
+{"ts": "2026-09-02T22:05:36.400Z", "direction": "to_server", "content": {"type": "event", "event": "acp_ready"}}
+{"ts": "2026-09-02T22:05:36.452Z", "direction": "to_runtime", "content": {"type": "acp", "jsonrpc": "2.0", "id": "cb3d7181-5dc6-4251-9b8c-bc092f68be89", "method": "initialize", "params": {"protocolVersion": 1, "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false}}}}
+{"ts": "2026-09-02T22:05:37.825Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "id": "cb3d7181-5dc6-4251-9b8c-bc092f68be89", "result": {"protocolVersion": 1, "agentCapabilities": {"loadSession": true, "mcpCapabilities": {"http": true, "sse": true}, "promptCapabilities": {"embeddedContext": true, "image": true}, "sessionCapabilities": {"close": {}, "fork": {}, "list": {}, "resume": {}}}, "authMethods": [{"description": "Run `opencode auth login` in the terminal", "name": "Login with opencode", "id": "opencode-login"}], "agentInfo": {"name": "OpenCode", "version": "1.18.26+b046973"}}}}
+{"ts": "2026-09-02T22:05:37.826Z", "direction": "to_runtime", "content": {"type": "acp", "jsonrpc": "2.0", "id": "48cb6a22-d2bc-4d09-8da9-c3dcb797f0d4", "method": "session/new", "params": {"cwd": "/home/user/repos/macro", "mcpServers": []}}}
+{"ts": "2026-09-02T22:05:39.953Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "id": "48cb6a22-d2bc-4d09-8da9-c3dcb797f0d4", "result": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "configOptions": [{"id": "model", "name": "Model", "category": "model", "type": "select", "currentValue": "openai/gpt-5.6-terra", "options": [{"value": "openai/gpt-5.4", "name": "OpenAI/GPT-5.4"}, {"value": "openai/gpt-5.5", "name": "OpenAI/GPT-5.5"}, {"value": "openai/gpt-5.6-terra", "name": "OpenAI/GPT-5.6 Terra"}, {"value": "openai/gpt-5.6-terra-fast", "name": "OpenAI/GPT-5.6 Terra Fast"}]}, {"id": "effort", "name": "Effort", "description": "Available effort levels for this model", "category": "thought_level", "type": "select", "currentValue": "none", "options": [{"value": "none", "name": "None"}, {"value": "low", "name": "Low"}, {"value": "medium", "name": "Medium"}, {"value": "high", "name": "High"}, {"value": "xhigh", "name": "Xhigh"}, {"value": "max", "name": "Max"}]}, {"id": "mode", "name": "Session Mode", "category": "mode", "type": "select", "currentValue": "build", "options": [{"value": "build", "name": "build", "description": "Everyday primary agent for implementation, debugging, and moderate refactors."}, {"value": "fast", "name": "fast", "description": "Performs small, well-specified, mechanical code changes quickly."}, {"value": "hard", "name": "hard", "description": "Architecture, difficult bugs, large refactors, and reviewing complex plans."}, {"value": "plan", "name": "plan", "description": "Plan mode. Disallows all edit tools."}]}]}}}
+{"ts": "2026-09-02T22:05:39.953Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "available_commands_update", "availableCommands": [{"name": "dump-schema", "description": "Dump clean Postgres schema to a file and copy path to clipboard."}, {"name": "init", "description": "guided AGENTS.md setup"}, {"name": "qc", "description": "Quality gate. 5 parallel agents review changes. All must pass."}, {"name": "review", "description": "review changes [commit|branch|pr], defaults to uncommitted"}]}}}}
+{"ts": "2026-09-02T22:05:39.955Z", "direction": "to_runtime", "content": {"type": "acp", "jsonrpc": "2.0", "id": "219d3ba0-a6bf-4104-a273-51b8bf4409c7", "method": "session/prompt", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "prompt": [{"type": "text", "text": "please spawn a subagent to use python to add 5+5"}]}}}
+{"ts": "2026-09-02T22:05:41.887Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "tool_call", "toolCallId": "call_jD0TDWivCCvEOTvAR47QMvJG", "title": "task", "kind": "think", "status": "pending", "locations": [], "rawInput": {}}}}}
+{"ts": "2026-09-02T22:05:42.693Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "tool_call_update", "toolCallId": "call_jD0TDWivCCvEOTvAR47QMvJG", "status": "in_progress", "kind": "think", "title": "task", "locations": [], "rawInput": {"description": "Add numbers with Python", "prompt": "Use Python to calculate 5 + 5. Return only the numeric result. Do not modify files.", "subagent_type": "general"}}}}}
+{"ts": "2026-09-02T22:05:42.694Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "tool_call_update", "toolCallId": "call_jD0TDWivCCvEOTvAR47QMvJG", "status": "in_progress", "kind": "think", "title": "Add numbers with Python", "locations": [], "rawInput": {"description": "Add numbers with Python", "prompt": "Use Python to calculate 5 + 5. Return only the numeric result. Do not modify files.", "subagent_type": "general"}}}}}
+{"ts": "2026-09-02T22:05:48.742Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "tool_call_update", "toolCallId": "call_jD0TDWivCCvEOTvAR47QMvJG", "status": "completed", "title": "Add numbers with Python", "content": [{"type": "content", "content": {"type": "text", "text": "<task id=\"ses_f9bd7ee76ffeshjLOLx06ArVK7\" state=\"completed\">\n<task_result>\n10\n</task_result>\n</task>"}}], "rawOutput": {"output": "<task id=\"ses_f9bd7ee76ffeshjLOLx06ArVK7\" state=\"completed\">\n<task_result>\n10\n</task_result>\n</task>", "metadata": {"parentSessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "sessionId": "ses_f9bd7ee76ffeshjLOLx06ArVK7", "model": {"modelID": "gpt-5.6-terra", "providerID": "openai"}, "truncated": false}}}}}}
+{"ts": "2026-09-02T22:05:49.926Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "agent_message_chunk", "messageId": "msg_064282935001FEv6kHZhFeOt1d", "content": {"type": "text", "text": "10"}}}}}
+{"ts": "2026-09-02T22:05:50.315Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "ses_f9bd7f919ffeGXugGN25V3vYGR", "update": {"sessionUpdate": "usage_update", "used": 15126, "size": 400000, "cost": {"amount": 0, "currency": "USD"}}}}}
+{"ts": "2026-09-02T22:05:50.315Z", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", "id": "219d3ba0-a6bf-4104-a273-51b8bf4409c7", "result": {"stopReason": "end_turn", "usage": {"inputTokens": 278, "outputTokens": 5, "totalTokens": 15131, "cachedReadTokens": 14848}, "_meta": {}}}}
diff --git a/crates/agent_fold/src/bin/fold_jsonl.rs b/crates/agent_fold/src/bin/fold_jsonl.rs
index fdf0897526..a5e0f2e897 100644
--- a/crates/agent_fold/src/bin/fold_jsonl.rs
+++ b/crates/agent_fold/src/bin/fold_jsonl.rs
@@ -173,6 +173,7 @@ async fn main() -> ExitCode {
print!("{}", render_message(message));
}
println!("── metadata ──");
+ println!("harness: {:?}", metadata.harness);
println!("model: {}", metadata.model.as_deref().unwrap_or("-"));
println!("title: {}", metadata.title.as_deref().unwrap_or("-"));
println!(
@@ -219,6 +220,16 @@ fn render_message(message: &FoldedMessage) -> String {
.unwrap_or_default();
let _ = writeln!(out, "── turn {} · {author}{stop} ──", message.id.0);
for part in message.parts.iter() {
+ out.push_str(&render_part(part));
+ out.push('\n');
+ }
+ out
+}
+
+/// One part as terminal text.
+fn render_part(part: &MessagePart) -> String {
+ let mut out = String::new();
+ {
match part {
MessagePart::Text { text } => {
let _ = writeln!(out, "{}", text.trim_end());
@@ -227,11 +238,11 @@ fn render_message(message: &FoldedMessage) -> String {
let _ = writeln!(out, "[thought]\n{}", indent(text.trim_end()));
}
MessagePart::ToolUse {
- label,
+ name,
status,
detail,
..
- } => out.push_str(&render_tool(label, *status, detail)),
+ } => out.push_str(&render_tool(name.display(), *status, detail)),
MessagePart::Permission {
tool_call,
options,
@@ -262,7 +273,6 @@ fn render_message(message: &FoldedMessage) -> String {
}
}
}
- out.push('\n');
}
out
}
@@ -331,15 +341,88 @@ fn render_tool(label: &str, status: ToolStatus, detail: &ToolDetail) -> String {
let _ = writeln!(out, "{}", indent(output.trim_end()));
}
if let Some(input) = input {
- let json =
- serde_json::to_string_pretty(input).unwrap_or_else(|_| input.to_string());
- let _ = writeln!(out, "{}", indent(&json));
+ let _ = writeln!(out, "{}", indent(&pretty(input)));
+ }
+ }
+ ToolDetail::Macro {
+ input,
+ output,
+ error,
+ } => {
+ let _ = writeln!(out, "{}", indent(&format!("input: {}", pretty(input))));
+ if let Some(output) = output {
+ let _ = writeln!(out, "{}", indent(&format!("output: {}", pretty(output))));
+ }
+ if let Some(error) = error {
+ let _ = writeln!(out, "{}", indent(&format!("error: {error}")));
+ }
+ }
+ ToolDetail::UserTool { input, outcome } => {
+ let _ = writeln!(out, "{}", indent(&format!("draft: {}", pretty(input))));
+ let _ = writeln!(out, "{}", indent(&format!("outcome: {outcome:?}")));
+ }
+ ToolDetail::Subagent {
+ title,
+ agent_type,
+ description,
+ prompt,
+ background,
+ children,
+ result,
+ } => {
+ let mut head = vec![format!("title: {title}")];
+ if let Some(agent_type) = agent_type {
+ head.push(format!("type: {agent_type}"));
+ }
+ if let Some(description) = description {
+ head.push(format!("description: {description}"));
+ }
+ if *background {
+ head.push("background".to_owned());
+ }
+ if !head.is_empty() {
+ let _ = writeln!(out, "{}", indent(&head.join(" · ")));
+ }
+ if let Some(prompt) = prompt {
+ let _ = writeln!(out, "{}", indent(&format!("> {}", prompt.trim_end())));
+ }
+ for child in children {
+ let _ = writeln!(out, "{}", indent(render_part(child).trim_end()));
+ }
+ if let Some(result) = result {
+ if let Some(text) = &result.text {
+ let _ = writeln!(out, "{}", indent(&format!("result: {}", text.trim_end())));
+ }
+ if let Some(error) = &result.error {
+ let _ = writeln!(out, "{}", indent(&format!("error: {error}")));
+ }
+ let mut facts = Vec::new();
+ if let Some(model) = &result.model {
+ facts.push(model.clone());
+ }
+ if let Some(tool_uses) = result.tool_uses {
+ facts.push(format!("{tool_uses} tool uses"));
+ }
+ if let Some(ms) = result.duration_ms {
+ facts.push(format!("{ms}ms"));
+ }
+ if let Some(tokens) = result.tokens {
+ facts.push(format!("{tokens} tokens"));
+ }
+ if !facts.is_empty() {
+ let _ = writeln!(out, "{}", indent(&facts.join(" · ")));
+ }
}
}
}
out
}
+/// JSON, pretty-printed, or its compact form if that somehow fails.
+fn pretty(value: &serde_json::Value) -> String {
+ serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string())
+}
+
/// A permission request: what was asked, what was offered, what was chosen.
fn render_permission(
tool_call: &ToolUseId,
diff --git a/crates/agent_fold/src/domain/error.rs b/crates/agent_fold/src/domain/error.rs
index 42ad1bb0d4..eac30533e4 100644
--- a/crates/agent_fold/src/domain/error.rs
+++ b/crates/agent_fold/src/domain/error.rs
@@ -20,6 +20,15 @@ pub(crate) enum FoldError {
/// The unopened tool call.
tool_call: ToolUseId,
},
+ /// A `tool_call` named a parent call the fold has not seen, or one that
+ /// is not a subagent. The call is folded at top level instead.
+ #[error("tool call {tool_call:?} names an unknown parent {parent:?}")]
+ UnknownParent {
+ /// The call that named a parent.
+ tool_call: ToolUseId,
+ /// The parent it named.
+ parent: ToolUseId,
+ },
/// A response arrived for a request id the fold was not tracking.
#[error("response arrived for a request id the fold was not tracking")]
UncorrelatedResponse,
diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rs
index 7fa8678ed2..365795dabf 100644
--- a/crates/agent_fold/src/domain/fold.rs
+++ b/crates/agent_fold/src/domain/fold.rs
@@ -51,34 +51,32 @@
use std::borrow::Cow;
-use crate::domain::error::FoldError;
-use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};
-use crate::domain::meta::{claude_code, command_from_raw_input, file_edit_from_raw_input};
-use crate::domain::model::{
- AnsiText, Author, AvailableCommand, Control, ControlOutcome, FileDiff, FoldEvent,
- FoldedMessage, MessagePart, ModelOption, PermissionOption, PermissionOptionKind,
- PermissionOutcome, PlanEntry, PlanEntryPriority, PlanEntryStatus, SessionMetadata, StopReason,
- ToolDetail, ToolStatus, ToolUseId, TurnId,
-};
+use crate::domain::log::{AgentSessionId, AgentSessionLog};
+use crate::domain::model::{FoldEvent, FoldedMessage, SessionMetadata, TurnId};
use crate::domain::ports::{FoldMachine, FoldSession, LogRepo};
-use agent_client_protocol::schema::MaybeUndefined;
-use agent_client_protocol::schema::v1::{
- AvailableCommandInput, AvailableCommandsUpdate as AcpAvailableCommandsUpdate, Content,
- ContentBlock, LoadSessionRequest, Meta, NewSessionRequest, Plan as AcpPlan, PromptRequest,
- RequestId, RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,
- Response, ResumeSessionRequest, SessionConfigKind, SessionConfigOption,
- SessionConfigSelectOptions, SessionInfoUpdate, SessionNotification, SessionUpdate,
- SetSessionConfigOptionRequest, ToolCall, ToolCallContent, ToolCallLocation, ToolCallStatus,
- ToolCallUpdate, ToolKind,
-};
-use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage, RawJsonRpcParams};
-use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId, MODEL_CONFIG_ID};
-use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
-use macro_user_id::user_id::MacroUserIdStr;
-use non_empty::NonEmpty;
-use serde::Deserialize;
-use std::collections::{HashMap, HashSet};
-use std::path::PathBuf;
+
+/// Config-option and session-info bookkeeping.
+mod config;
+/// Prose and reasoning chunks, and adding parts to the agent message.
+mod content;
+/// Control operations: set-model, compact, stop.
+mod control;
+/// ACP-to-vocabulary conversions shared by the handlers.
+mod convert;
+/// Permission requests and their answers.
+mod permission;
+/// The agent's plan (todo list).
+mod plan;
+/// The fold's state and the per-frame dispatch.
+mod state;
+/// Delegated agents and the calls nested under them.
+mod subagent;
+/// Tool calls and their patches.
+mod tool_call;
+/// Opening, closing, and failing turns.
+mod turn;
+
+use state::{Change, FoldState, StepChange};
/// Collapse a session's protocol log into renderable messages.
///
@@ -178,60 +176,6 @@ impl FoldMachine for FoldMachineImpl {
}
}
-/// How one push changed [`State::messages`].
-#[derive(Debug, Clone, Copy)]
-struct Changed {
- kind: Change,
- /// The changed message's index in [`State::messages`].
- message: usize,
-}
-
-impl Changed {
- /// A message that did not exist before this push.
- fn new(message: usize) -> Self {
- Self {
- kind: Change::New,
- message,
- }
- }
-
- /// A message already reported, now carrying more.
- fn updated(message: usize) -> Self {
- Self {
- kind: Change::Updated,
- message,
- }
- }
-}
-
-/// Whether a changed message is one the caller has seen before.
-#[derive(Debug, Clone, Copy)]
-enum Change {
- New,
- Updated,
-}
-
-/// One change a step implied. A step returns however many it implied, in
-/// emission order - most frames imply none, and the set-model response
-/// implies two (its control's outcome, and the config it restates).
-#[derive(Debug, Clone, Copy)]
-enum StepChange {
- Message(Changed),
- Metadata,
-}
-
-impl StepChange {
- /// The changes for a handler that touched at most one message.
- fn message(changed: Option<Changed>) -> Vec<Self> {
- changed.map(Self::Message).into_iter().collect()
- }
-
- /// The changes for a handler that reported whether the metadata moved.
- fn metadata(changed: bool) -> Vec<Self> {
- changed.then_some(Self::Metadata).into_iter().collect()
- }
-}
-
impl<T: LogRepo + Sync> FoldSession for T {
/// Read the session's log through [`LogRepo`] and fold it.
///
@@ -250,1268 +194,3 @@ impl<T: LogRepo + Sync> FoldSession for T {
Ok(fold_machine(log).next_turn_id())
}
}
-
-/// The fold's state, advanced one log entry at a time by [`State::step`] and
-/// owned by [`FoldMachineImpl`].
-#[derive(Debug, Default)]
-struct FoldState {
- /// Every message derived so far, oldest first - including the open turn's
- /// agent message, which is appended to in place as the agent talks.
- messages: Vec<FoldedMessage>,
- /// The session the entry currently being folded belongs to, for
- /// [`State::warn`]. Set fresh from each log entry, so it is always
- /// current even though it rarely changes within one fold.
- session: Option<AgentSessionId>,
- /// The turn currently being built, if any.
- turn: Option<Turn>,
- /// How many turns have been opened, which is also the next [`TurnId`].
- turns_opened: u32,
- /// Outstanding permission requests, by the id of the request that asked.
- pending_permissions: HashMap<RequestId, ToolUseId>,
- /// Session-level state derived so far. Handlers mutate it freely; the
- /// machine diffs it against what it last reported.
- metadata: SessionMetadata,
- /// Requests whose responses carry config options. The response body is
- /// authoritative - a rejected change answers with an error and moves
- /// nothing.
- pending_config_requests: HashSet<RequestId>,
- /// Controls awaiting a response, by request id: where the control part
- /// sits (message, part), so the response can resolve its outcome.
- pending_controls: HashMap<RequestId, (usize, usize)>,
-}
-
-/// A turn under construction.
-///
-/// Holds no content of its own. The turn's agent message lives in
-/// [`State::messages`] as soon as there is one, and everything here is a way
-/// back into it.
-#[derive(Debug)]
-struct Turn {
- id: TurnId,
- /// The `session/prompt` request whose response will close this turn.
- ///
- /// `None` for a turn opened without one - see
- /// [`State::begin_turn_without_prompt`]. Such a turn has no id to
- /// correlate against, so [`State::end_turn`] closes it on the first
- /// response that reports a stop reason instead.
- prompt_id: Option<RequestId>,
- /// Where this turn's agent message sits in [`State::messages`].
- ///
- /// `None` until the agent produces its first part, because a
- /// [`FoldedMessage`] cannot hold an empty part list - which is also what
- /// makes a turn the agent never answered derive no agent message at all.
- agent: Option<usize>,
- /// Where each tool call sits in the agent message's parts, so patches can
- /// find it.
- tool_positions: HashMap<ToolUseId, usize>,
- /// Where each permission sits in the agent message's parts, so outcomes
- /// can find it.
- permission_positions: HashMap<ToolUseId, usize>,
- /// Where this turn's plan sits in the agent message's parts, so later
- /// plan updates can replace it.
- plan_position: Option<usize>,
- /// Whether closing this turn needs an agent message to record its stop
- /// reason on, minting one if the agent never produced a part.
- ///
- /// True for a turn a prompt opened: the user's bubble is then the
- /// transcript's newest turn message, and readers take one without a stop
- /// reason to mean the agent is still working. False for a turn a control
- /// opened (`/compact`), whose own message readers skip.
- expects_reply: bool,
-}
-
-impl FoldState {
- /// Advance by one log entry, returning what it changed in emission order.
- ///
- /// One entry changes at most one message today - see [`FoldEvent`]
- /// for why the prompt-interrupts-a-turn case is not an exception.
- fn step(&mut self, entry: AgentSessionLog) -> Vec<StepChange> {
- self.session = Some(entry.agent_session_id);
-
- // The one place the protocol is dispatched. Each arm names a frame
- // this fold understands; the rest are ignored on purpose.
- match &entry.content {
- Message::ToRuntime(message @ ToRuntimeMessage::Acp(acp)) => {
- // Before the control dispatch, which returns early for the
- // set-model request whose response this correlates.
- self.note_config_request(&acp.0);
- if let Some(action) = AgentAction::control_from_runtime(message) {
- return StepChange::message(match action {
- AgentAction::SetModel(action) => {
- let request_id = match &acp.0 {
- RawJsonRpcMessage::Request(request) => Some(&request.id),
- _ => None,
- };
- self.record_control(
- Control::SetModel {
- model: action.model,
- },
- request_id,
- entry.user_id.clone(),
- )
- }
- AgentAction::Compact => match &acp.0 {
- RawJsonRpcMessage::Request(request) => {
- self.begin_compact(&request.id, entry.user_id.clone())
- }
- _ => None,
- },
- // A stop is a notification: nothing can answer it, so
- // it is accepted the moment it is sent.
- AgentAction::Stop => {
- self.record_control(Control::Stop, None, entry.user_id.clone())
- }
- AgentAction::Prompt(_) => None,
- });
- }
- StepChange::message(match &acp.0 {
- // A user's prompt opens a turn.
- RawJsonRpcMessage::Request(request)
- if PromptRequest::matches_method(&request.method) =>
- {
- self.begin_turn(&request.id, request.params.as_ref(), entry.user_id.clone())
- }
- // The user's answer to a permission request.
- RawJsonRpcMessage::Response(Response::Result { id, result }) => {
- self.resolve_permission(id, Some(result))
- }
- RawJsonRpcMessage::Response(Response::Error { id, .. }) => {
- self.resolve_permission(id, None)
- }
- // Handshake and configuration traffic: nothing to render.
- RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => None,
- })
- }
-
- Message::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {
- // The bulk of the log: streamed content and tool activity.
- RawJsonRpcMessage::Notification(notification)
- if SessionNotification::matches_method(&notification.method) =>
- {
- self.apply_session_update(notification.params.as_ref())
- }
- // The agent asking to proceed.
- RawJsonRpcMessage::Request(request)
- if RequestPermissionRequest::matches_method(&request.method) =>
- {
- StepChange::message(
- self.request_permission(&request.id, request.params.as_ref()),
- )
- }
- // The response to `session/prompt` closes the turn; a
- // config-bearing response updates the metadata; a control's
- // response resolves its outcome. Set-model is both of the
- // latter at once.
- RawJsonRpcMessage::Response(Response::Result { id, result }) => {
- let control = self.resolve_control(id, None);
- if self.pending_config_requests.remove(id) {
- let mut changes = StepChange::message(control);
- changes.extend(StepChange::metadata(self.apply_config_response(result)));
- changes
- } else if control.is_some() {
- StepChange::message(control)
- } else {
- StepChange::message(self.end_turn(id, Some(result)))
- }
- }
- RawJsonRpcMessage::Response(Response::Error { id, error }) => {
- let control = self.resolve_control(id, Some(&error.message));
- // An error response moves no metadata, so a config-bearing
- // request's failure changes at most its control part.
- if self.pending_config_requests.remove(id) || control.is_some() {
- StepChange::message(control)
- } else {
- StepChange::message(self.fail_turn(id, &error.message))
- }
- }
- RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => Vec::new(),
- },
-
- // Runtime lifecycle events carry no conversation content, but
- // they are the session's status, and `acp_ready` marks a
- // connection boundary: request ids restart per connection, so
- // nothing pending can be answered past one - a stale entry would
- // misattribute a new connection's reused id.
- Message::ToServer(ToServerMessage::Event { event }) => {
- if matches!(event, SystemEvent::AcpReady) {
- self.pending_config_requests.clear();
- self.pending_permissions.clear();
- self.pending_controls.clear();
- }
- let status = Some(event.as_str().to_owned());
- let changed = self.metadata.status != status;
- if changed {
- self.metadata.status = status;
- }
- StepChange::metadata(changed)
- }
-
- // The wrapped protocol enums are `#[non_exhaustive]`.
- Message::ToServer(_) | Message::ToRuntime(_) => Vec::new(),
- }
- }
-
- /// Handle a `session/prompt`: emit the user's message, open a turn.
- fn begin_turn(
- &mut self,
- prompt_id: &RequestId,
- params: Option<&RawJsonRpcParams>,
- user_id: Option<MacroUserIdStr<'static>>,
- ) -> Option<Changed> {
- // A second prompt without an intervening response means the previous
- // turn never got one. Its agent message is already in `messages` and
- // already reads `stop: None`, so there is nothing left to report -
- // which is what keeps a push to one changed message.
- let closed = self.close_turn(None);
- debug_assert!(
- closed.is_none(),
- "closing a turn without a stop reason changes nothing"
- );
-
- let id = TurnId(self.turns_opened);
- self.turns_opened += 1;
-
- // A params shape this fold does not recognize derives no text, same
- // as an empty prompt - see the module docs on why a mismatch here
- // degrades rather than warns: `PromptRequest`'s own fields (a session
- // id, an optional `_meta`) carry nothing this fold renders, so there
- // is nothing to warn *about* beyond "no text," which showing no user
- // message already says.
- let text = deserialize_params::<PromptRequest>(params)
- .map(|request| {
- request
- .prompt
- .into_iter()
- .filter_map(content_block_text)
- .collect::<Vec<_>>()
- .join("")
- })
- .unwrap_or_default();
-
- // A prompt carrying no text derives no user message, but still opens
- // the turn the agent will answer into.
- let changed = (!text.is_empty()).then(|| {
- let message = self.messages.len();
- self.messages.push(FoldedMessage {
- id,
- author: Author::User { user_id },
- request_id: AgentActionId::from_request_id(prompt_id),
- parts: NonEmpty::one(MessagePart::Text { text }),
- stop: None,
- });
- Changed::new(message)
- });
-
- self.turn = Some(Turn {
- id,
- prompt_id: Some(prompt_id.clone()),
- agent: None,
- tool_positions: HashMap::new(),
- permission_positions: HashMap::new(),
- plan_position: None,
- expects_reply: true,
- });
-
- changed
- }
-
- /// Open a turn for a compact: the invocation renders as a control part,
- /// and how it went is the turn's own reply and stop reason, not an
- /// outcome to track separately.
- fn begin_compact(
- &mut self,
- prompt_id: &RequestId,
- user_id: Option<MacroUserIdStr<'static>>,
- ) -> Option<Changed> {
- let closed = self.close_turn(None);
- debug_assert!(closed.is_none());
- let id = TurnId(self.turns_opened);
- self.turns_opened += 1;
- let message = self.messages.len();
- self.messages.push(FoldedMessage {
- id,
- author: Author::User { user_id },
- request_id: AgentActionId::from_request_id(prompt_id),
- parts: NonEmpty::one(MessagePart::Control {
- control: Control::Compact,
- outcome: ControlOutcome::Accepted,
- }),
- stop: None,
- });
- self.turn = Some(Turn {
- id,
- prompt_id: Some(prompt_id.clone()),
- agent: None,
- tool_positions: HashMap::new(),
- permission_positions: HashMap::new(),
- plan_position: None,
- expects_reply: false,
- });
- Some(Changed::new(message))
- }
-
- /// Emit a standalone control message. A request-backed control starts
- /// pending and is resolved by its response; one with no request to answer
- /// (a stop notification) is accepted outright.
- fn record_control(
- &mut self,
- control: Control,
- request_id: Option<&RequestId>,
- user_id: Option<MacroUserIdStr<'static>>,
- ) -> Option<Changed> {
- let id = TurnId(self.turns_opened);
- self.turns_opened += 1;
- let message = self.messages.len();
- let outcome = match request_id {
- Some(_) => ControlOutcome::Pending,
- None => ControlOutcome::Accepted,
- };
- if let Some(request_id) = request_id {
- self.pending_controls
- .insert(request_id.clone(), (message, 0));
- }
- self.messages.push(FoldedMessage {
- id,
- author: Author::User { user_id },
- request_id: request_id.and_then(AgentActionId::from_request_id),
- parts: NonEmpty::one(MessagePart::Control { control, outcome }),
- stop: None,
- });
- Some(Changed::new(message))
- }
-
- /// Resolve a pending control from its response. `None` when the id
- /// matches no control.
- fn resolve_control(&mut self, response_id: &RequestId, error: Option<&str>) -> Option<Changed> {
- let (message, part) = self.pending_controls.remove(response_id)?;
- let Some(MessagePart::Control { outcome, .. }) =
- self.messages.get_mut(message)?.parts.get_mut(part)
- else {
- return None;
- };
- *outcome = match error {
- Some(message) => ControlOutcome::Rejected {
- message: message.to_owned(),
- },
- None => ControlOutcome::Accepted,
- };
- Some(Changed::updated(message))
- }
-
- /// Handle the response to `session/prompt`: close the turn.
- fn end_turn(
- &mut self,
- response_id: &RequestId,
- value: Option<&serde_json::Value>,
- ) -> Option<Changed> {
- let stop = value
- .and_then(|value| value.get("stopReason"))
- .and_then(|reason| reason.as_str())
- // Infallible: `StopReason`'s unmodelled variant is strum's default.
- .and_then(|reason| reason.parse().ok());
-
- let closes_the_open_turn = match self.turn.as_ref() {
- Some(turn) => match &turn.prompt_id {
- // The ordinary case: the response to the prompt that opened it.
- Some(prompt_id) => prompt_id == response_id,
- // A turn nothing prompted has no id to match against, so the
- // first response reporting a stop reason is taken as its
- // answer - the prompt it belongs to is in an earlier log.
- None => stop.is_some(),
- },
- None => false,
- };
-
- if !closes_the_open_turn {
- // Responses to `initialize`, `session/new` and `session/load`
- // land here. Only flag one that looks like a turn ending.
- if stop.is_some() {
- self.warn(FoldError::UncorrelatedResponse);
- }
- return None;
- }
-
- self.close_turn(stop)
- }
-
- /// End the open turn because its prompt was answered with an error.
- ///
- /// The turn has to end even when the agent produced nothing at all -
- /// which is the common case, since a runtime that rejects a prompt
- /// rejects it before writing anything. That is why this cannot go
- /// through [`Self::close_turn`], whose job is to stamp a stop reason on
- /// an agent message that exists: here the agent message is created if
- /// need be, so the failure has somewhere to live and the turn is
- /// unambiguously over.
- fn fail_turn(&mut self, response_id: &RequestId, message: &str) -> Option<Changed> {
- let closes_the_open_turn = self
- .turn
- .as_ref()
- .and_then(|turn| turn.prompt_id.as_ref())
- .is_some_and(|prompt_id| prompt_id == response_id);
- if !closes_the_open_turn {
- return None;
- }
-
- // An error is worth showing under any turn, control's included, so
- // this mints unconditionally where a clean close does not.
- let turn = self.turn.take()?;
- let (agent, changed) = match turn.agent {
- Some(agent) => (agent, Changed::updated(agent)),
- None => self.mint_agent_message(turn.id),
- };
- self.messages[agent].stop = Some(StopReason::Failed {
- message: message.to_owned(),
- });
- Some(changed)
- }
-
- /// Handle a `session/update`.
- fn apply_session_update(&mut self, params: Option<&RawJsonRpcParams>) -> Vec<StepChange> {
- // Only the `update` field is folded; the rest of the notification
- // (session id, meta) carries nothing renderable. Borrowed out of the
- // params rather than cloning them - `session/update` is the bulk of
- // any log, so this is the fold's hot path.
- let Some(update_value) = param(params, "update") else {
- self.warn(FoldError::Unknown {
- kind: "<missing params>".to_owned(),
- });
- return Vec::new();
- };
-
- // Keep the wire name before decoding, so an unmodelled variant can be
- // named in the anomaly even though `SessionUpdate` is non-exhaustive.
- let wire_kind = update_value
- .get("sessionUpdate")
- .and_then(|kind| kind.as_str())
- .unwrap_or("<missing>")
- .to_owned();
-
- let Ok(update) = SessionUpdate::deserialize(update_value) else {
- self.warn(FoldError::Unknown { kind: wire_kind });
- return Vec::new();
- };
-
- match update {
- // Prose from the agent. Chunks are appended to the open text part
- // rather than each becoming a part of its own.
- SessionUpdate::AgentMessageChunk(chunk) => StepChange::message(
- content_block_text(chunk.content).and_then(|text| self.append_text(text)),
- ),
- // Reasoning, kept separate so a reader can collapse it.
- SessionUpdate::AgentThoughtChunk(chunk) => StepChange::message(
- content_block_text(chunk.content).and_then(|text| self.append_thought(text)),
- ),
- // The agent replaying the user's own message. The prompt frame is
- // the authoritative copy, so this is dropped.
- SessionUpdate::UserMessageChunk(_) => Vec::new(),
- SessionUpdate::ToolCall(call) => StepChange::message(self.open_tool_call(call)),
- SessionUpdate::ToolCallUpdate(update) => {
- StepChange::message(self.patch_tool_call(update))
- }
- SessionUpdate::SessionInfoUpdate(update) => {
- StepChange::metadata(self.apply_session_info(&update))
- }
- SessionUpdate::ConfigOptionUpdate(update) => {
- StepChange::metadata(self.apply_config_options(update.config_options))
- }
- SessionUpdate::AvailableCommandsUpdate(update) => {
- StepChange::metadata(self.apply_available_commands(update))
- }
- // Deliberately dropped: token accounting and session bookkeeping,
- // none of which a reader wants in a channel. `usage_update` alone
- // is 81 of ~450 frames in a recorded session.
- SessionUpdate::UsageUpdate(_) | SessionUpdate::CurrentModeUpdate(_) => Vec::new(),
- // The agent's todo list, carried whole each time.
- SessionUpdate::Plan(plan) => StepChange::message(self.apply_plan(plan)),
- _ => {
- self.warn(FoldError::Unknown { kind: wire_kind });
- Vec::new()
- }
- }
- }
-
- /// Handle a `tool_call`: add a new tool part.
- fn open_tool_call(&mut self, call: ToolCall) -> Option<Changed> {
- let id = ToolUseId(call.tool_call_id.0.to_string());
- let label =
- claude_code::tool_name(call.meta.as_ref()).unwrap_or_else(|| call.title.clone());
-
- let tool = MessagePart::ToolUse {
- id: id.clone(),
- label,
- status: tool_status(call.status),
- detail: tool_detail(
- call.kind,
- call.raw_input.as_ref(),
- &call.content,
- &call.locations,
- call.meta.as_ref(),
- ),
- raw_input: call.raw_input.clone().map(Box::new),
- raw_output: call.raw_output.clone().map(Box::new),
- };
-
- // A repeated open for the same id patches in place rather than
- // duplicating the row. Looked up without `?` so that a call arriving
- // with no turn open falls through to `push_agent_part`, which opens
- // one, rather than being dropped.
- let opened = self
- .turn
- .as_ref()
- .and_then(|turn| turn.tool_positions.get(&id).copied());
- if let Some(position) = opened {
- let (message, parts) = self.agent_parts_mut()?;
- if let Some(existing @ MessagePart::ToolUse { .. }) = parts.get_mut(position) {
- *existing = tool;
- }
- return Some(Changed::updated(message));
- }
-
- let (changed, position) = self.push_agent_part(tool)?;
- self.open_turn().tool_positions.insert(id, position);
- Some(changed)
- }
-
- /// Handle a `tool_call_update`: patch an existing tool part.
- ///
- /// Only fields the update actually carries are written, since
- /// `ToolCallUpdateFields` is entirely optional and a typical call is
- /// patched several times - the recordings average about four updates per
- /// call.
- fn patch_tool_call(&mut self, update: ToolCallUpdate) -> Option<Changed> {
- let id = ToolUseId(update.tool_call_id.0.to_string());
-
- let Some(&position) = self.turn.as_ref()?.tool_positions.get(&id) else {
- self.warn(FoldError::PatchBeforeOpen { tool_call: id });
- return None;
- };
- let (message, parts) = self.agent_parts_mut()?;
- let Some(MessagePart::ToolUse {
- label,
- status,
- detail,
- raw_input,
- raw_output,
- ..
- }) = parts.get_mut(position)
- else {
- return None;
- };
-
- let fields = update.fields;
-
- if let Some(new_status) = fields.status {
- *status = tool_status(new_status);
- }
- if let Some(title) = fields.title {
- // A harness-supplied name outranks any ACP title, so only take
- // the title when nothing better is already set.
- if claude_code::tool_name(update.meta.as_ref()).is_none() && label.is_empty() {
- *label = title;
- }
- }
- if let Some(name) = claude_code::tool_name(update.meta.as_ref()) {
- *label = name;
- }
-
- patch_detail(
- detail,
- fields.raw_input.as_ref(),
- fields.content.as_deref(),
- fields.locations.as_deref(),
- update.meta.as_ref(),
- );
-
- if let Some(found) = fields.raw_input {
- *raw_input = Some(Box::new(found));
- }
- if let Some(found) = fields.raw_output {
- *raw_output = Some(Box::new(found));
- }
-
- Some(Changed::updated(message))
- }
-
- /// Handle a `plan` update: the agent's todo list, carried whole each time.
- ///
- /// The first update pushes a plan part onto the turn's agent message;
- /// every later one replaces that part wholesale, which is ACP's own
- /// contract ("the client replaces the entire plan with each update"). An
- /// update identical to what the part already holds changes nothing - the
- /// harness re-emits the list more often than it changes it.
- fn apply_plan(&mut self, update: AcpPlan) -> Option<Changed> {
- let entries: Vec<PlanEntry> = update.entries.into_iter().map(plan_entry).collect();
-
- if let Some(position) = self.turn.as_ref().and_then(|turn| turn.plan_position) {
- let (message, parts) = self.agent_parts_mut()?;
- if let Some(MessagePart::Plan { entries: existing }) = parts.get_mut(position) {
- if *existing == entries {
- return None;
- }
- *existing = entries;
- }
- return Some(Changed::updated(message));
- }
-
- // An empty list derives nothing to render, so no part is created for
- // one; the turn's first non-empty update creates it. A list that
- // *becomes* empty is a replacement like any other, handled above.
- if entries.is_empty() {
- return None;
- }
-
- let (changed, position) = self.push_agent_part(MessagePart::Plan { entries })?;
- self.open_turn().plan_position = Some(position);
- Some(changed)
- }
-
- /// Remember a request whose response will carry config options.
- fn note_config_request(&mut self, frame: &RawJsonRpcMessage) {
- let RawJsonRpcMessage::Request(request) = frame else {
- return;
- };
- let method = &request.method;
- if NewSessionRequest::matches_method(method)
- || LoadSessionRequest::matches_method(method)
- || ResumeSessionRequest::matches_method(method)
- || SetSessionConfigOptionRequest::matches_method(method)
- {
- self.pending_config_requests.insert(request.id.clone());
- }
- }
-
- /// Read the config options out of a correlated response, whichever
- /// response shape carried them.
- fn apply_config_response(&mut self, result: &serde_json::Value) -> bool {
- #[derive(Deserialize)]
- #[serde(rename_all = "camelCase")]
- struct ConfigCarrier {
- #[serde(default)]
- config_options: Vec<SessionConfigOption>,
- }
- match serde_json::from_value::<ConfigCarrier>(result.clone()) {
- Ok(carrier) => self.apply_config_options(carrier.config_options),
- Err(_) => false,
- }
- }
-
- /// Update the metadata's model fields from a fresh config-options list.
- fn apply_config_options(&mut self, options: Vec<SessionConfigOption>) -> bool {
- let model = options
- .into_iter()
- .find(|option| option.id.to_string() == MODEL_CONFIG_ID);
- let Some(SessionConfigOption {
- kind: SessionConfigKind::Select(select),
- ..
- }) = model
- else {
- return false;
- };
-
- let model = Some(select.current_value.to_string());
- let supported: Vec<ModelOption> = match select.options {
- SessionConfigSelectOptions::Ungrouped(options) => options,
- SessionConfigSelectOptions::Grouped(groups) => {
- groups.into_iter().flat_map(|group| group.options).collect()
- }
- _ => return false,
- }
- .into_iter()
- .map(|option| ModelOption {
- id: option.value.to_string(),
- name: option.name,
- description: option.description,
- })
- .collect();
-
- let changed = self.metadata.model != model || self.metadata.supported_models != supported;
- self.metadata.model = model;
- self.metadata.supported_models = supported;
- changed
- }
-
- /// Handle an `available_commands_update`: the advertised slash commands,
- /// carried whole each time, latest wins.
- fn apply_available_commands(&mut self, update: AcpAvailableCommandsUpdate) -> bool {
- let commands: Vec<AvailableCommand> = update
- .available_commands
- .into_iter()
- .map(|command| AvailableCommand {
- name: command.name,
- description: command.description,
- input_hint: command.input.and_then(|input| match input {
- AvailableCommandInput::Unstructured(input) => Some(input.hint),
- // `#[non_exhaustive]`; unstructured text is the only
- // input ACP defines, so an unknown shape carries no hint
- // this fold can show.
- _ => None,
- }),
- })
- .collect();
- let changed = self.metadata.available_commands != commands;
- self.metadata.available_commands = commands;
- changed
- }
-
- /// Handle a `session_info_update`: take the title, minding the
- /// absent/null/value distinction - absent means unchanged.
- fn apply_session_info(&mut self, update: &SessionInfoUpdate) -> bool {
- let title = match &update.title {
- MaybeUndefined::Undefined => return false,
- MaybeUndefined::Null => None,
- MaybeUndefined::Value(title) => Some(title.clone()),
- };
- let changed = self.metadata.title != title;
- self.metadata.title = title;
- changed
- }
-
- /// Handle a `session/request_permission`: add a permission part and record
- /// the request id so its response can be matched.
- fn request_permission(
- &mut self,
- request_id: &RequestId,
- params: Option<&RawJsonRpcParams>,
- ) -> Option<Changed> {
- let request = deserialize_params::<RequestPermissionRequest>(params)?;
- let tool_call = ToolUseId(request.tool_call.tool_call_id.0.to_string());
- let options = request
- .options
- .into_iter()
- .map(|option| PermissionOption {
- id: option.option_id.0.to_string(),
- name: option.name,
- kind: permission_option_kind(option.kind),
- })
- .collect();
-
- // Recorded even with no turn open, so a late response is still
- // recognized as an answer rather than an uncorrelated frame.
- self.pending_permissions
- .insert(request_id.clone(), tool_call.clone());
-
- let (changed, position) = self.push_agent_part(MessagePart::Permission {
- tool_call: tool_call.clone(),
- options,
- outcome: PermissionOutcome::Pending,
- })?;
- self.open_turn()
- .permission_positions
- .insert(tool_call, position);
- Some(changed)
- }
-
- /// Handle the response to a permission request.
- fn resolve_permission(
- &mut self,
- response_id: &RequestId,
- value: Option<&serde_json::Value>,
- ) -> Option<Changed> {
- let tool_call = self.pending_permissions.remove(response_id)?;
-
- let outcome = match value {
- // A JSON-RPC error, not a result: the harness failed to answer
- // rather than resolving the request.
- None => PermissionOutcome::Errored,
- Some(value) => {
- match serde_json::from_value::<RequestPermissionResponse>(value.clone()) {
- Ok(response) => match response.outcome {
- RequestPermissionOutcome::Selected(selected) => {
- PermissionOutcome::Selected {
- option_id: selected.option_id.0.to_string(),
- }
- }
- RequestPermissionOutcome::Cancelled => PermissionOutcome::Cancelled,
- // `#[non_exhaustive]`; reaching this means ACP added
- // an outcome after this was written.
- _ => PermissionOutcome::Unrecognized,
- },
- // The result did not match ACP's response shape.
- Err(_) => PermissionOutcome::Unrecognized,
- }
- }
- };
-
- let position = *self.turn.as_ref()?.permission_positions.get(&tool_call)?;
- let (message, parts) = self.agent_parts_mut()?;
- if let Some(MessagePart::Permission {
- outcome: existing, ..
- }) = parts.get_mut(position)
- {
- *existing = outcome;
- }
- Some(Changed::updated(message))
- }
-
- /// Append agent prose, extending the trailing text part when there is one.
- fn append_text(&mut self, text: String) -> Option<Changed> {
- if let Some((message, parts)) = self.agent_parts_mut()
- && let MessagePart::Text { text: existing } = parts.last_mut()
- {
- existing.push_str(&text);
- return Some(Changed::updated(message));
- }
- self.push_agent_part(MessagePart::Text { text })
- .map(|(changed, _)| changed)
- }
-
- /// Append agent reasoning, extending the trailing thought part when there
- /// is one.
- fn append_thought(&mut self, text: String) -> Option<Changed> {
- if let Some((message, parts)) = self.agent_parts_mut()
- && let MessagePart::Thought { text: existing } = parts.last_mut()
- {
- existing.push_str(&text);
- return Some(Changed::updated(message));
- }
- self.push_agent_part(MessagePart::Thought { text })
- .map(|(changed, _)| changed)
- }
-
- /// Close the open turn, recording on its agent message how it stopped.
- ///
- /// Usually the agent message has been in [`State::messages`] since the
- /// agent's first part, and all that is left is the stop reason. When the
- /// agent produced nothing at all, one is minted to carry it: readers ask
- /// whether a turn is running by looking for a stop reason on the
- /// transcript's tail, so recording none anywhere reads as working
- /// forever. That is a stop pressed before the first chunk - a first
- /// prompt spends ~10s creating the Cursor agent - which answers
- /// `session/prompt` with `cancelled` and nothing to stamp it on.
- fn close_turn(&mut self, stop: Option<StopReason>) -> Option<Changed> {
- let Some(stop) = stop else {
- // Nothing to record, so nothing to mint a message for.
- self.turn = None;
- return None;
- };
- let turn = self.turn.take()?;
- let (message, changed) = match turn.agent {
- Some(message) => (message, Changed::updated(message)),
- // A turn a control opened is skipped by those readers, so an
- // empty agent bubble under its line would be noise, not a fix.
- None if !turn.expects_reply => return None,
- None => self.mint_agent_message(turn.id),
- };
- self.messages[message].stop = Some(stop);
- Some(changed)
- }
-
- /// Mint the agent message a turn never opened, so a stop reason has
- /// somewhere to sit. Reported as new: the client has not seen it.
- fn mint_agent_message(&mut self, turn: TurnId) -> (usize, Changed) {
- let message = self.messages.len();
- self.messages.push(FoldedMessage {
- id: turn,
- author: Author::Agent,
- request_id: None,
- parts: NonEmpty::one(MessagePart::Text {
- text: String::new(),
- }),
- stop: None,
- });
- (message, Changed::new(message))
- }
-
- /// Add a part to the open turn's agent message, creating that message if
- /// this is the first part the agent has produced in the turn - and the
- /// turn itself if the agent is talking without one.
- ///
- /// Every way the agent contributes content comes through here, which is
- /// why opening the turn belongs here rather than in each caller.
- fn push_agent_part(&mut self, part: MessagePart) -> Option<(Changed, usize)> {
- if self.turn.is_none() {
- self.begin_turn_without_prompt();
- }
- let turn = self.turn.as_ref()?;
- let turn_id = turn.id;
- let agent = turn.agent;
-
- let Some(message) = agent else {
- let message = self.messages.len();
- self.messages.push(FoldedMessage {
- id: turn_id,
- author: Author::Agent,
- request_id: None,
- parts: NonEmpty::one(part),
- stop: None,
- });
- self.open_turn().agent = Some(message);
- return Some((Changed::new(message), 0));
- };
-
- let parts = &mut self.messages[message].parts;
- let position = parts.len();
- parts.push(part);
- Some((Changed::updated(message), position))
- }
-
- /// The open turn's agent message: where it sits in [`State::messages`],
- /// and its parts. `None` until the agent has produced a part.
- fn agent_parts_mut(&mut self) -> Option<(usize, &mut NonEmpty<Vec<MessagePart>>)> {
- let message = self.turn.as_ref()?.agent?;
- Some((message, &mut self.messages[message].parts))
- }
-
- /// Open a turn for agent content that arrived without a prompt.
- ///
- /// A session resumed through `session/load` picks up mid-conversation: the
- /// prompt the agent is answering is in the log of the session it resumed,
- /// not this one. Dropping the content for want of a prompt folded such a
- /// session to nothing at all - hundreds of frames of real work rendering
- /// as an empty channel - and showing the reply without the question is
- /// plainly better than showing neither.
- ///
- /// The turn is numbered like any other and produces no user message, since
- /// there is no prompt to attribute one to. It is closed by the first
- /// response carrying a stop reason; see [`State::end_turn`].
- fn begin_turn_without_prompt(&mut self) {
- let id = TurnId(self.turns_opened);
- self.turns_opened += 1;
-
- self.turn = Some(Turn {
- id,
- prompt_id: None,
- agent: None,
- tool_positions: HashMap::new(),
- permission_positions: HashMap::new(),
- plan_position: None,
- expects_reply: true,
- });
- }
-
- /// The open turn, for the handlers that have already established there is
- /// one.
- fn open_turn(&mut self) -> &mut Turn {
- self.turn.as_mut().expect("a turn is open")
- }
-
- /// Log a frame the fold could not account for. Not fatal - see the
- /// module docs - so this only ever logs and never returns an error.
- fn warn(&self, error: FoldError) {
- tracing::warn!(
- session = ?self.session,
- error = ?error,
- "agent session log frame could not be folded"
- );
- }
-}
-
-/// The text carried by a content block, if it carries any.
-fn content_block_text(block: ContentBlock) -> Option<String> {
- match block {
- ContentBlock::Text(text) => Some(text.text),
- // Images, audio, resource links and embedded resources have no text
- // to fold. Rendering them is a separate problem from this one.
- _ => None,
- }
-}
-
-/// Build a [`ToolDetail`] from a tool call's opening frame.
-fn tool_detail(
- kind: ToolKind,
- raw_input: Option<&serde_json::Value>,
- content: &[ToolCallContent],
- locations: &[ToolCallLocation],
- meta: Option<&Meta>,
-) -> ToolDetail {
- match kind {
- ToolKind::Execute => ToolDetail::Terminal {
- command: command_from_raw_input(raw_input),
- output: claude_code::terminal_output(meta).map(AnsiText),
- exit_code: claude_code::terminal_exit_code(meta),
- },
- ToolKind::Edit => ToolDetail::Edit {
- diffs: edit_diffs(content, raw_input),
- },
- ToolKind::Read => ToolDetail::Read {
- paths: location_paths(locations),
- },
- ToolKind::Delete => ToolDetail::Delete {
- paths: location_paths(locations),
- },
- ToolKind::Move => ToolDetail::Move {
- paths: location_paths(locations),
- },
- ToolKind::Search => ToolDetail::Search {
- paths: location_paths(locations),
- output: generic_output(content),
- },
- ToolKind::Fetch => ToolDetail::Fetch {
- output: generic_output(content),
- },
- ToolKind::Think => ToolDetail::Think {
- output: generic_output(content),
- },
- other => ToolDetail::Other {
- kind: tool_kind_name(other).to_owned(),
- output: generic_output(content),
- input: raw_input.cloned(),
- },
- }
-}
-
-/// Write an update's fields into an existing detail, leaving what it does not
-/// carry untouched.
-fn patch_detail(
- detail: &mut ToolDetail,
- raw_input: Option<&serde_json::Value>,
- content: Option<&[ToolCallContent]>,
- locations: Option<&[ToolCallLocation]>,
- meta: Option<&Meta>,
-) {
- match detail {
- ToolDetail::Terminal {
- command,
- output,
- exit_code,
- } => {
- if let Some(found) = command_from_raw_input(raw_input) {
- *command = Some(found);
- }
- // Each update carries the output accumulated so far, so replace.
- if let Some(found) = claude_code::terminal_output(meta) {
- *output = Some(AnsiText(found));
- }
- if let Some(found) = claude_code::terminal_exit_code(meta) {
- *exit_code = Some(found);
- }
- }
- ToolDetail::Edit { diffs: existing } => {
- if let Some(content) = content {
- let found = diffs(content);
- if !found.is_empty() {
- *existing = found;
- }
- }
- // A call that never reports a diff block (Claude Code's `Write`)
- // may still deliver its raw input on a later update.
- if existing.is_empty()
- && let Some(found) = synthesized_edit_diff(raw_input)
- {
- *existing = vec![found];
- }
- }
- ToolDetail::Read { paths } | ToolDetail::Delete { paths } | ToolDetail::Move { paths } => {
- if let Some(found) = locations.map(location_paths)
- && !found.is_empty()
- {
- *paths = found;
- }
- }
- ToolDetail::Search { paths, output } => {
- if let Some(found) = locations.map(location_paths)
- && !found.is_empty()
- {
- *paths = found;
- }
- if let Some(found) = content.and_then(generic_output) {
- *output = Some(found);
- }
- }
- ToolDetail::Fetch { output } | ToolDetail::Think { output } => {
- if let Some(found) = content.and_then(generic_output) {
- *output = Some(found);
- }
- }
- ToolDetail::Other { input, output, .. } => {
- if let Some(found) = raw_input {
- *input = Some(found.clone());
- }
- if let Some(found) = content.and_then(generic_output) {
- *output = Some(found);
- }
- }
- }
-}
-
-/// An edit call's diffs: the reported diff blocks, or — for calls that never
-/// report one, like Claude Code's `Write` — a whole-file diff synthesized
-/// from the raw input.
-fn edit_diffs(content: &[ToolCallContent], raw_input: Option<&serde_json::Value>) -> Vec<FileDiff> {
- let found = diffs(content);
- if !found.is_empty() {
- return found;
- }
- synthesized_edit_diff(raw_input).into_iter().collect()
-}
-
-/// A whole-file diff from `{filePath, content}` raw input. The prior contents
-/// are not on the wire, so the file reads as new.
-fn synthesized_edit_diff(raw_input: Option<&serde_json::Value>) -> Option<FileDiff> {
- let (path, content) = file_edit_from_raw_input(raw_input)?;
- Some(FileDiff {
- path: path.into(),
- old_text: None,
- new_text: content,
- })
-}
-
-/// The diffs among a tool call's content blocks.
-fn diffs(content: &[ToolCallContent]) -> Vec<FileDiff> {
- content
- .iter()
- .filter_map(|block| match block {
- ToolCallContent::Diff(diff) => Some(FileDiff {
- path: diff.path.clone(),
- old_text: diff.old_text.clone(),
- new_text: diff.new_text.clone(),
- }),
- _ => None,
- })
- .collect()
-}
-
-/// The paths among a tool call's reported locations.
-///
-/// The one source this fold trusts for "what path did this call touch" -
-/// `locations` is ACP's own field, meant for exactly this, unlike `rawInput`,
-/// whose keys are a harness's own convention with no fixed shape to read.
-fn location_paths(locations: &[ToolCallLocation]) -> Vec<PathBuf> {
- locations
- .iter()
- .map(|location| location.path.clone())
- .collect()
-}
-
-/// The text among a tool call's content blocks - e.g. search matches or a
-/// fetched page's text - joined in order.
-///
-/// `None` when none of the blocks carry text, same as an empty result: there
-/// is nothing useful to distinguish "reported nothing" from "reported an
-/// empty string."
-fn generic_output(content: &[ToolCallContent]) -> Option<String> {
- let text = content
- .iter()
- .filter_map(|block| match block {
- ToolCallContent::Content(Content {
- content: block_content,
- ..
- }) => content_block_text(block_content.clone()),
- _ => None,
- })
- .collect::<Vec<_>>()
- .join("");
- (!text.is_empty()).then_some(text)
-}
-
-/// An ACP plan entry in the fold's own vocabulary.
-fn plan_entry(entry: agent_client_protocol::schema::v1::PlanEntry) -> PlanEntry {
- PlanEntry {
- content: entry.content,
- priority: plan_entry_priority(entry.priority),
- status: plan_entry_status(entry.status),
- }
-}
-
-fn plan_entry_priority(
- priority: agent_client_protocol::schema::v1::PlanEntryPriority,
-) -> PlanEntryPriority {
- use agent_client_protocol::schema::v1::PlanEntryPriority as Acp;
- match priority {
- Acp::High => PlanEntryPriority::High,
- Acp::Medium => PlanEntryPriority::Medium,
- Acp::Low => PlanEntryPriority::Low,
- // `#[non_exhaustive]`; a priority ACP adds later is not demonstrably
- // more or less important than the middle.
- _ => PlanEntryPriority::Medium,
- }
-}
-
-fn plan_entry_status(
- status: agent_client_protocol::schema::v1::PlanEntryStatus,
-) -> PlanEntryStatus {
- use agent_client_protocol::schema::v1::PlanEntryStatus as Acp;
- match status {
- Acp::Pending => PlanEntryStatus::Pending,
- Acp::InProgress => PlanEntryStatus::InProgress,
- Acp::Completed => PlanEntryStatus::Completed,
- // `#[non_exhaustive]`; an unknown status has not demonstrably
- // finished, same as `ToolStatus`.
- _ => PlanEntryStatus::Pending,
- }
-}
-
-fn permission_option_kind(
- kind: agent_client_protocol::schema::v1::PermissionOptionKind,
-) -> PermissionOptionKind {
- use agent_client_protocol::schema::v1::PermissionOptionKind as Acp;
- match kind {
- Acp::AllowOnce => PermissionOptionKind::AllowOnce,
- Acp::AllowAlways => PermissionOptionKind::AllowAlways,
- Acp::RejectOnce => PermissionOptionKind::RejectOnce,
- Acp::RejectAlways => PermissionOptionKind::RejectAlways,
- // `#[non_exhaustive]`, and unreachable in practice: this only ever
- // runs on a `kind` that already deserialized successfully, and a
- // wire value ACP added after this was written would have failed
- // that deserialize instead of reaching here - see the type's docs.
- _ => PermissionOptionKind::RejectOnce,
- }
-}
-
-fn tool_status(status: ToolCallStatus) -> ToolStatus {
- match status {
- ToolCallStatus::Pending => ToolStatus::Pending,
- ToolCallStatus::InProgress => ToolStatus::Running,
- ToolCallStatus::Completed => ToolStatus::Completed,
- ToolCallStatus::Failed => ToolStatus::Failed,
- // `ToolCallStatus` is `#[non_exhaustive]`; an unknown status has not
- // demonstrably finished.
- _ => ToolStatus::Pending,
- }
-}
-
-fn tool_kind_name(kind: ToolKind) -> &'static str {
- match kind {
- ToolKind::Read => "read",
- ToolKind::Edit => "edit",
- ToolKind::Delete => "delete",
- ToolKind::Move => "move",
- ToolKind::Search => "search",
- ToolKind::Execute => "execute",
- ToolKind::Think => "think",
- ToolKind::Fetch => "fetch",
- ToolKind::SwitchMode => "switch_mode",
- ToolKind::Other => "other",
- _ => "unknown",
- }
-}
-
-/// A named JSON-RPC param, borrowed. `None` for positional params - every
-/// frame this fold reads carries an object.
-///
-/// Only [`State::apply_session_update`] still uses this, to reach the one
-/// field it wants (`update`) without paying to deserialize the rest of the
-/// notification - `session/update` is most of any log, so that is the
-/// difference between one clone per log and one clone per frame. Everywhere
-/// else, [`deserialize_params`] reads the whole params object as ACP's own
-/// type, because those frames are rare enough that the clone is free and the
-/// typed struct is far harder to get wrong than a chain of `.get(key)`s.
-fn param<'params>(
- params: Option<&'params RawJsonRpcParams>,
- key: &str,
-) -> Option<&'params serde_json::Value> {
- match params? {
- RawJsonRpcParams::Object(map) => map.get(key),
- RawJsonRpcParams::Array(_) => None,
- }
-}
-
-/// Deserialize a request's or notification's params as a specific ACP type.
-///
-/// `None` for positional params (nothing this fold reads uses those) or when
-/// the object does not match `T`'s shape - the crate's total-by-construction
-/// design point: a mismatch here is a state to render around, not a reason
-/// to fail. Callers that want that mismatch to warn do so themselves; most
-/// do not, because the alternative to a malformed prompt or permission
-/// request is simply deriving less from it, same as any other partial frame.
-fn deserialize_params<T: serde::de::DeserializeOwned>(
- params: Option<&RawJsonRpcParams>,
-) -> Option<T> {
- match params? {
- RawJsonRpcParams::Object(map) => {
- serde_json::from_value(serde_json::Value::Object(map.clone())).ok()
- }
- RawJsonRpcParams::Array(_) => None,
- }
-}
diff --git a/crates/agent_fold/src/domain/fold/config.rs b/crates/agent_fold/src/domain/fold/config.rs
new file mode 100644
index 0000000000..896217aa9f
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/config.rs
@@ -0,0 +1,163 @@
+//! Config options, available commands, and session info: the metadata.
+
+use crate::domain::harness::ToolFrame;
+use crate::domain::model::{AvailableCommand, Harness, ModelOption};
+use agent_client_protocol::schema::MaybeUndefined;
+use agent_client_protocol::schema::v1::{
+ AvailableCommandInput, AvailableCommandsUpdate as AcpAvailableCommandsUpdate,
+ InitializeRequest, InitializeResponse, LoadSessionRequest, NewSessionRequest,
+ ResumeSessionRequest, SessionConfigKind, SessionConfigOption, SessionConfigSelectOptions,
+ SessionInfoUpdate, SetSessionConfigOptionRequest,
+};
+use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
+use agent_runtime_protocol::domain::action::MODEL_CONFIG_ID;
+use serde::Deserialize;
+
+use super::state::FoldState;
+
+impl FoldState {
+ /// Remember the `initialize` request, whose response names the harness.
+ pub(super) fn note_initialize_request(&mut self, frame: &RawJsonRpcMessage) {
+ if let RawJsonRpcMessage::Request(request) = frame
+ && InitializeRequest::matches_method(&request.method)
+ {
+ self.pending_initialize = Some(request.id.clone());
+ }
+ }
+
+ /// Read the harness off the `initialize` response's `agentInfo`.
+ ///
+ /// An announcement outranks a sniff: a response that names an agent
+ /// replaces whatever a tool frame's `_meta` suggested. One that names
+ /// nothing changes nothing, so a sniffed harness survives it.
+ pub(super) fn apply_initialize_response(&mut self, result: &serde_json::Value) -> bool {
+ let Ok(response) = serde_json::from_value::<InitializeResponse>(result.clone()) else {
+ return false;
+ };
+ let Some(info) = response.agent_info else {
+ return false;
+ };
+ self.set_harness(Harness::from_agent_info(&info.name))
+ }
+
+ /// Recognize the harness from a tool frame when the log never showed an
+ /// `initialize` - a resumed session, or a recording that starts mid-turn.
+ /// Only ever fills in an unknown; an announced harness is never
+ /// second-guessed by a frame.
+ pub(super) fn sniff_harness(&mut self, frame: &ToolFrame<'_>) -> bool {
+ if self.metadata.harness != Harness::Unknown {
+ return false;
+ }
+ match Harness::sniff(frame) {
+ Some(harness) => self.set_harness(harness),
+ None => false,
+ }
+ }
+
+ fn set_harness(&mut self, harness: Harness) -> bool {
+ let changed = self.metadata.harness != harness;
+ self.metadata.harness = harness;
+ changed
+ }
+
+ /// Remember a request whose response will carry config options.
+ pub(super) fn note_config_request(&mut self, frame: &RawJsonRpcMessage) {
+ let RawJsonRpcMessage::Request(request) = frame else {
+ return;
+ };
+ let method = &request.method;
+ if NewSessionRequest::matches_method(method)
+ || LoadSessionRequest::matches_method(method)
+ || ResumeSessionRequest::matches_method(method)
+ || SetSessionConfigOptionRequest::matches_method(method)
+ {
+ self.pending_config_requests.insert(request.id.clone());
+ }
+ }
+
+ /// Read the config options out of a correlated response, whichever
+ /// response shape carried them.
+ pub(super) fn apply_config_response(&mut self, result: &serde_json::Value) -> bool {
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct ConfigCarrier {
+ #[serde(default)]
+ config_options: Vec<SessionConfigOption>,
+ }
+ match serde_json::from_value::<ConfigCarrier>(result.clone()) {
+ Ok(carrier) => self.apply_config_options(carrier.config_options),
+ Err(_) => false,
+ }
+ }
+
+ /// Update the metadata's model fields from a fresh config-options list.
+ pub(super) fn apply_config_options(&mut self, options: Vec<SessionConfigOption>) -> bool {
+ let model = options
+ .into_iter()
+ .find(|option| option.id.to_string() == MODEL_CONFIG_ID);
+ let Some(SessionConfigOption {
+ kind: SessionConfigKind::Select(select),
+ ..
+ }) = model
+ else {
+ return false;
+ };
+
+ let model = Some(select.current_value.to_string());
+ let supported: Vec<ModelOption> = match select.options {
+ SessionConfigSelectOptions::Ungrouped(options) => options,
+ SessionConfigSelectOptions::Grouped(groups) => {
+ groups.into_iter().flat_map(|group| group.options).collect()
+ }
+ _ => return false,
+ }
+ .into_iter()
+ .map(|option| ModelOption {
+ id: option.value.to_string(),
+ name: option.name,
+ description: option.description,
+ })
+ .collect();
+
+ let changed = self.metadata.model != model || self.metadata.supported_models != supported;
+ self.metadata.model = model;
+ self.metadata.supported_models = supported;
+ changed
+ }
+
+ /// Handle an `available_commands_update`: the advertised slash commands,
+ /// carried whole each time, latest wins.
+ pub(super) fn apply_available_commands(&mut self, update: AcpAvailableCommandsUpdate) -> bool {
+ let commands: Vec<AvailableCommand> = update
+ .available_commands
+ .into_iter()
+ .map(|command| AvailableCommand {
+ name: command.name,
+ description: command.description,
+ input_hint: command.input.and_then(|input| match input {
+ AvailableCommandInput::Unstructured(input) => Some(input.hint),
+ // `#[non_exhaustive]`; unstructured text is the only
+ // input ACP defines, so an unknown shape carries no hint
+ // this fold can show.
+ _ => None,
+ }),
+ })
+ .collect();
+ let changed = self.metadata.available_commands != commands;
+ self.metadata.available_commands = commands;
+ changed
+ }
+
+ /// Handle a `session_info_update`: take the title, minding the
+ /// absent/null/value distinction - absent means unchanged.
+ pub(super) fn apply_session_info(&mut self, update: &SessionInfoUpdate) -> bool {
+ let title = match &update.title {
+ MaybeUndefined::Undefined => return false,
+ MaybeUndefined::Null => None,
+ MaybeUndefined::Value(title) => Some(title.clone()),
+ };
+ let changed = self.metadata.title != title;
+ self.metadata.title = title;
+ changed
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/content.rs b/crates/agent_fold/src/domain/fold/content.rs
new file mode 100644
index 0000000000..49c7ccc1bb
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/content.rs
@@ -0,0 +1,84 @@
+//! Prose and reasoning chunks, and adding parts to the agent message.
+
+use crate::domain::model::{Author, FoldedMessage, MessagePart};
+use non_empty::NonEmpty;
+
+use super::state::{Changed, FoldState, ToolPath};
+
+impl FoldState {
+ /// The part at `at`, wherever in the transcript it sits. `None` if the
+ /// path no longer resolves, which a well-formed log never produces.
+ pub(super) fn part_at_mut(&mut self, at: &ToolPath) -> Option<&mut MessagePart> {
+ let (first, rest) = at.path.split_first()?;
+ let mut part = self.messages.get_mut(at.message)?.parts.get_mut(*first)?;
+ for &index in rest {
+ part = part.children_mut()?.get_mut(index)?;
+ }
+ Some(part)
+ }
+
+ /// Append agent prose, extending the trailing text part when there is one.
+ pub(super) fn append_text(&mut self, text: String) -> Option<Changed> {
+ if let Some((message, parts)) = self.agent_parts_mut()
+ && let MessagePart::Text { text: existing } = parts.last_mut()
+ {
+ existing.push_str(&text);
+ return Some(Changed::updated(message));
+ }
+ self.push_agent_part(MessagePart::Text { text })
+ .map(|(changed, _)| changed)
+ }
+
+ /// Append agent reasoning, extending the trailing thought part when there
+ /// is one.
+ pub(super) fn append_thought(&mut self, text: String) -> Option<Changed> {
+ if let Some((message, parts)) = self.agent_parts_mut()
+ && let MessagePart::Thought { text: existing } = parts.last_mut()
+ {
+ existing.push_str(&text);
+ return Some(Changed::updated(message));
+ }
+ self.push_agent_part(MessagePart::Thought { text })
+ .map(|(changed, _)| changed)
+ }
+
+ /// Add a part to the open turn's agent message, creating that message if
+ /// this is the first part the agent has produced in the turn - and the
+ /// turn itself if the agent is talking without one.
+ ///
+ /// Every way the agent contributes content comes through here, which is
+ /// why opening the turn belongs here rather than in each caller.
+ pub(super) fn push_agent_part(&mut self, part: MessagePart) -> Option<(Changed, usize)> {
+ if self.turn.is_none() {
+ self.begin_turn_without_prompt();
+ }
+ let turn = self.turn.as_ref()?;
+ let turn_id = turn.id;
+ let agent = turn.agent;
+
+ let Some(message) = agent else {
+ let message = self.messages.len();
+ self.messages.push(FoldedMessage {
+ id: turn_id,
+ author: Author::Agent,
+ request_id: None,
+ parts: NonEmpty::one(part),
+ stop: None,
+ });
+ self.open_turn().agent = Some(message);
+ return Some((Changed::new(message), 0));
+ };
+
+ let parts = &mut self.messages[message].parts;
+ let position = parts.len();
+ parts.push(part);
+ Some((Changed::updated(message), position))
+ }
+
+ /// The open turn's agent message: where it sits in [`State::messages`],
+ /// and its parts. `None` until the agent has produced a part.
+ pub(super) fn agent_parts_mut(&mut self) -> Option<(usize, &mut NonEmpty<Vec<MessagePart>>)> {
+ let message = self.turn.as_ref()?.agent?;
+ Some((message, &mut self.messages[message].parts))
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/control.rs b/crates/agent_fold/src/domain/fold/control.rs
new file mode 100644
index 0000000000..0f0cd73e26
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/control.rs
@@ -0,0 +1,99 @@
+//! Control operations the user issues on the session.
+
+use std::collections::HashMap;
+
+use crate::domain::model::{Author, Control, ControlOutcome, FoldedMessage, MessagePart, TurnId};
+use agent_client_protocol::schema::v1::RequestId;
+use agent_runtime_protocol::domain::action::AgentActionId;
+use macro_user_id::user_id::MacroUserIdStr;
+use non_empty::NonEmpty;
+
+use super::state::{Changed, FoldState, Turn};
+
+impl FoldState {
+ /// Open a turn for a compact: the invocation renders as a control part,
+ /// and how it went is the turn's own reply and stop reason, not an
+ /// outcome to track separately.
+ pub(super) fn begin_compact(
+ &mut self,
+ prompt_id: &RequestId,
+ user_id: Option<MacroUserIdStr<'static>>,
+ ) -> Option<Changed> {
+ let closed = self.close_turn(None);
+ debug_assert!(closed.is_none());
+ let id = TurnId(self.turns_opened);
+ self.turns_opened += 1;
+ let message = self.messages.len();
+ self.messages.push(FoldedMessage {
+ id,
+ author: Author::User { user_id },
+ request_id: AgentActionId::from_request_id(prompt_id),
+ parts: NonEmpty::one(MessagePart::Control {
+ control: Control::Compact,
+ outcome: ControlOutcome::Accepted,
+ }),
+ stop: None,
+ });
+ self.turn = Some(Turn {
+ id,
+ prompt_id: Some(prompt_id.clone()),
+ agent: None,
+ permission_positions: HashMap::new(),
+ plan_position: None,
+ expects_reply: false,
+ });
+ Some(Changed::new(message))
+ }
+
+ /// Emit a standalone control message. A request-backed control starts
+ /// pending and is resolved by its response; one with no request to answer
+ /// (a stop notification) is accepted outright.
+ pub(super) fn record_control(
+ &mut self,
+ control: Control,
+ request_id: Option<&RequestId>,
+ user_id: Option<MacroUserIdStr<'static>>,
+ ) -> Option<Changed> {
+ let id = TurnId(self.turns_opened);
+ self.turns_opened += 1;
+ let message = self.messages.len();
+ let outcome = match request_id {
+ Some(_) => ControlOutcome::Pending,
+ None => ControlOutcome::Accepted,
+ };
+ if let Some(request_id) = request_id {
+ self.pending_controls
+ .insert(request_id.clone(), (message, 0));
+ }
+ self.messages.push(FoldedMessage {
+ id,
+ author: Author::User { user_id },
+ request_id: request_id.and_then(AgentActionId::from_request_id),
+ parts: NonEmpty::one(MessagePart::Control { control, outcome }),
+ stop: None,
+ });
+ Some(Changed::new(message))
+ }
+
+ /// Resolve a pending control from its response. `None` when the id
+ /// matches no control.
+ pub(super) fn resolve_control(
+ &mut self,
+ response_id: &RequestId,
+ error: Option<&str>,
+ ) -> Option<Changed> {
+ let (message, part) = self.pending_controls.remove(response_id)?;
+ let Some(MessagePart::Control { outcome, .. }) =
+ self.messages.get_mut(message)?.parts.get_mut(part)
+ else {
+ return None;
+ };
+ *outcome = match error {
+ Some(message) => ControlOutcome::Rejected {
+ message: message.to_owned(),
+ },
+ None => ControlOutcome::Accepted,
+ };
+ Some(Changed::updated(message))
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/convert.rs b/crates/agent_fold/src/domain/fold/convert.rs
new file mode 100644
index 0000000000..224e92a3a2
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/convert.rs
@@ -0,0 +1,69 @@
+//! ACP-to-vocabulary conversions and params access shared by the handlers.
+
+use agent_client_protocol::RawJsonRpcParams;
+use agent_client_protocol::schema::v1::{ContentBlock, ToolKind};
+
+/// The text carried by a content block, if it carries any.
+pub(super) fn content_block_text(block: ContentBlock) -> Option<String> {
+ match block {
+ ContentBlock::Text(text) => Some(text.text),
+ // Images, audio, resource links and embedded resources have no text
+ // to fold. Rendering them is a separate problem from this one.
+ _ => None,
+ }
+}
+
+pub(super) fn tool_kind_name(kind: ToolKind) -> &'static str {
+ match kind {
+ ToolKind::Read => "read",
+ ToolKind::Edit => "edit",
+ ToolKind::Delete => "delete",
+ ToolKind::Move => "move",
+ ToolKind::Search => "search",
+ ToolKind::Execute => "execute",
+ ToolKind::Think => "think",
+ ToolKind::Fetch => "fetch",
+ ToolKind::SwitchMode => "switch_mode",
+ ToolKind::Other => "other",
+ _ => "unknown",
+ }
+}
+
+/// A named JSON-RPC param, borrowed. `None` for positional params - every
+/// frame this fold reads carries an object.
+///
+/// Only [`State::apply_session_update`] still uses this, to reach the one
+/// field it wants (`update`) without paying to deserialize the rest of the
+/// notification - `session/update` is most of any log, so that is the
+/// difference between one clone per log and one clone per frame. Everywhere
+/// else, [`deserialize_params`] reads the whole params object as ACP's own
+/// type, because those frames are rare enough that the clone is free and the
+/// typed struct is far harder to get wrong than a chain of `.get(key)`s.
+pub(super) fn param<'params>(
+ params: Option<&'params RawJsonRpcParams>,
+ key: &str,
+) -> Option<&'params serde_json::Value> {
+ match params? {
+ RawJsonRpcParams::Object(map) => map.get(key),
+ RawJsonRpcParams::Array(_) => None,
+ }
+}
+
+/// Deserialize a request's or notification's params as a specific ACP type.
+///
+/// `None` for positional params (nothing this fold reads uses those) or when
+/// the object does not match `T`'s shape - the crate's total-by-construction
+/// design point: a mismatch here is a state to render around, not a reason
+/// to fail. Callers that want that mismatch to warn do so themselves; most
+/// do not, because the alternative to a malformed prompt or permission
+/// request is simply deriving less from it, same as any other partial frame.
+pub(super) fn deserialize_params<T: serde::de::DeserializeOwned>(
+ params: Option<&RawJsonRpcParams>,
+) -> Option<T> {
+ match params? {
+ RawJsonRpcParams::Object(map) => {
+ serde_json::from_value(serde_json::Value::Object(map.clone())).ok()
+ }
+ RawJsonRpcParams::Array(_) => None,
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/permission.rs b/crates/agent_fold/src/domain/fold/permission.rs
new file mode 100644
index 0000000000..99e1f1da42
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/permission.rs
@@ -0,0 +1,108 @@
+//! Permission requests and their answers.
+
+use crate::domain::model::{
+ MessagePart, PermissionOption, PermissionOptionKind, PermissionOutcome, ToolUseId,
+};
+use agent_client_protocol::RawJsonRpcParams;
+use agent_client_protocol::schema::v1::{
+ RequestId, RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,
+};
+
+use super::convert::deserialize_params;
+use super::state::{Changed, FoldState};
+
+impl FoldState {
+ /// Handle a `session/request_permission`: add a permission part and record
+ /// the request id so its response can be matched.
+ pub(super) fn request_permission(
+ &mut self,
+ request_id: &RequestId,
+ params: Option<&RawJsonRpcParams>,
+ ) -> Option<Changed> {
+ let request = deserialize_params::<RequestPermissionRequest>(params)?;
+ let tool_call = ToolUseId(request.tool_call.tool_call_id.0.to_string());
+ let options = request
+ .options
+ .into_iter()
+ .map(|option| PermissionOption {
+ id: option.option_id.0.to_string(),
+ name: option.name,
+ kind: permission_option_kind(option.kind),
+ })
+ .collect();
+
+ // Recorded even with no turn open, so a late response is still
+ // recognized as an answer rather than an uncorrelated frame.
+ self.pending_permissions
+ .insert(request_id.clone(), tool_call.clone());
+
+ let (changed, position) = self.push_agent_part(MessagePart::Permission {
+ tool_call: tool_call.clone(),
+ options,
+ outcome: PermissionOutcome::Pending,
+ })?;
+ self.open_turn()
+ .permission_positions
+ .insert(tool_call, position);
+ Some(changed)
+ }
+
+ /// Handle the response to a permission request.
+ pub(super) fn resolve_permission(
+ &mut self,
+ response_id: &RequestId,
+ value: Option<&serde_json::Value>,
+ ) -> Option<Changed> {
+ let tool_call = self.pending_permissions.remove(response_id)?;
+
+ let outcome = match value {
+ // A JSON-RPC error, not a result: the harness failed to answer
+ // rather than resolving the request.
+ None => PermissionOutcome::Errored,
+ Some(value) => {
+ match serde_json::from_value::<RequestPermissionResponse>(value.clone()) {
+ Ok(response) => match response.outcome {
+ RequestPermissionOutcome::Selected(selected) => {
+ PermissionOutcome::Selected {
+ option_id: selected.option_id.0.to_string(),
+ }
+ }
+ RequestPermissionOutcome::Cancelled => PermissionOutcome::Cancelled,
+ // `#[non_exhaustive]`; reaching this means ACP added
+ // an outcome after this was written.
+ _ => PermissionOutcome::Unrecognized,
+ },
+ // The result did not match ACP's response shape.
+ Err(_) => PermissionOutcome::Unrecognized,
+ }
+ }
+ };
+
+ let position = *self.turn.as_ref()?.permission_positions.get(&tool_call)?;
+ let (message, parts) = self.agent_parts_mut()?;
+ if let Some(MessagePart::Permission {
+ outcome: existing, ..
+ }) = parts.get_mut(position)
+ {
+ *existing = outcome;
+ }
+ Some(Changed::updated(message))
+ }
+}
+
+pub(super) fn permission_option_kind(
+ kind: agent_client_protocol::schema::v1::PermissionOptionKind,
+) -> PermissionOptionKind {
+ use agent_client_protocol::schema::v1::PermissionOptionKind as Acp;
+ match kind {
+ Acp::AllowOnce => PermissionOptionKind::AllowOnce,
+ Acp::AllowAlways => PermissionOptionKind::AllowAlways,
+ Acp::RejectOnce => PermissionOptionKind::RejectOnce,
+ Acp::RejectAlways => PermissionOptionKind::RejectAlways,
+ // `#[non_exhaustive]`, and unreachable in practice: this only ever
+ // runs on a `kind` that already deserialized successfully, and a
+ // wire value ACP added after this was written would have failed
+ // that deserialize instead of reaching here - see the type's docs.
+ _ => PermissionOptionKind::RejectOnce,
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/plan.rs b/crates/agent_fold/src/domain/fold/plan.rs
new file mode 100644
index 0000000000..191845df4b
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/plan.rs
@@ -0,0 +1,78 @@
+//! The agent's plan: its todo list, carried whole on every update.
+
+use crate::domain::model::{MessagePart, PlanEntry, PlanEntryPriority, PlanEntryStatus};
+use agent_client_protocol::schema::v1::Plan as AcpPlan;
+
+use super::state::{Changed, FoldState};
+
+impl FoldState {
+ /// Handle a `plan` update: the agent's todo list, carried whole each time.
+ ///
+ /// The first update pushes a plan part onto the turn's agent message;
+ /// every later one replaces that part wholesale, which is ACP's own
+ /// contract ("the client replaces the entire plan with each update"). An
+ /// update identical to what the part already holds changes nothing - the
+ /// harness re-emits the list more often than it changes it.
+ pub(super) fn apply_plan(&mut self, update: AcpPlan) -> Option<Changed> {
+ let entries: Vec<PlanEntry> = update.entries.into_iter().map(plan_entry).collect();
+
+ if let Some(position) = self.turn.as_ref().and_then(|turn| turn.plan_position) {
+ let (message, parts) = self.agent_parts_mut()?;
+ if let Some(MessagePart::Plan { entries: existing }) = parts.get_mut(position) {
+ if *existing == entries {
+ return None;
+ }
+ *existing = entries;
+ }
+ return Some(Changed::updated(message));
+ }
+
+ // An empty list derives nothing to render, so no part is created for
+ // one; the turn's first non-empty update creates it. A list that
+ // *becomes* empty is a replacement like any other, handled above.
+ if entries.is_empty() {
+ return None;
+ }
+
+ let (changed, position) = self.push_agent_part(MessagePart::Plan { entries })?;
+ self.open_turn().plan_position = Some(position);
+ Some(changed)
+ }
+}
+
+/// An ACP plan entry in the fold's own vocabulary.
+pub(super) fn plan_entry(entry: agent_client_protocol::schema::v1::PlanEntry) -> PlanEntry {
+ PlanEntry {
+ content: entry.content,
+ priority: plan_entry_priority(entry.priority),
+ status: plan_entry_status(entry.status),
+ }
+}
+
+pub(super) fn plan_entry_priority(
+ priority: agent_client_protocol::schema::v1::PlanEntryPriority,
+) -> PlanEntryPriority {
+ use agent_client_protocol::schema::v1::PlanEntryPriority as Acp;
+ match priority {
+ Acp::High => PlanEntryPriority::High,
+ Acp::Medium => PlanEntryPriority::Medium,
+ Acp::Low => PlanEntryPriority::Low,
+ // `#[non_exhaustive]`; a priority ACP adds later is not demonstrably
+ // more or less important than the middle.
+ _ => PlanEntryPriority::Medium,
+ }
+}
+
+pub(super) fn plan_entry_status(
+ status: agent_client_protocol::schema::v1::PlanEntryStatus,
+) -> PlanEntryStatus {
+ use agent_client_protocol::schema::v1::PlanEntryStatus as Acp;
+ match status {
+ Acp::Pending => PlanEntryStatus::Pending,
+ Acp::InProgress => PlanEntryStatus::InProgress,
+ Acp::Completed => PlanEntryStatus::Completed,
+ // `#[non_exhaustive]`; an unknown status has not demonstrably
+ // finished, same as `ToolStatus`.
+ _ => PlanEntryStatus::Pending,
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/state.rs b/crates/agent_fold/src/domain/fold/state.rs
new file mode 100644
index 0000000000..490d717b02
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/state.rs
@@ -0,0 +1,393 @@
+//! The fold's state and the one place the protocol is dispatched.
+
+use std::collections::{HashMap, HashSet};
+
+use crate::domain::error::FoldError;
+use crate::domain::harness::{HarnessReader, ToolFrame};
+use crate::domain::log::{AgentSessionId, AgentSessionLog, Message};
+use crate::domain::model::{Control, FoldedMessage, SessionMetadata, ToolUseId, TurnId};
+use agent_client_protocol::schema::v1::{
+ PromptRequest, RequestId, RequestPermissionRequest, Response, SessionNotification,
+ SessionUpdate,
+};
+use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage, RawJsonRpcParams};
+use agent_runtime_protocol::domain::action::AgentAction;
+use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
+use serde::Deserialize;
+
+use super::convert::{content_block_text, param};
+
+/// How one push changed [`State::messages`].
+#[derive(Debug, Clone, Copy)]
+pub(super) struct Changed {
+ pub(super) kind: Change,
+ /// The changed message's index in [`State::messages`].
+ pub(super) message: usize,
+}
+
+impl Changed {
+ /// A message that did not exist before this push.
+ pub(super) fn new(message: usize) -> Self {
+ Self {
+ kind: Change::New,
+ message,
+ }
+ }
+
+ /// A message already reported, now carrying more.
+ pub(super) fn updated(message: usize) -> Self {
+ Self {
+ kind: Change::Updated,
+ message,
+ }
+ }
+}
+
+/// Whether a changed message is one the caller has seen before.
+#[derive(Debug, Clone, Copy)]
+pub(super) enum Change {
+ New,
+ Updated,
+}
+
+/// One change a step implied. A step returns however many it implied, in
+/// emission order - most frames imply none, and the set-model response
+/// implies two (its control's outcome, and the config it restates).
+#[derive(Debug, Clone, Copy)]
+pub(super) enum StepChange {
+ Message(Changed),
+ Metadata,
+}
+
+impl StepChange {
+ /// The changes for a handler that touched at most one message.
+ pub(super) fn message(changed: Option<Changed>) -> Vec<Self> {
+ changed.map(Self::Message).into_iter().collect()
+ }
+
+ /// The changes for a handler that reported whether the metadata moved.
+ pub(super) fn metadata(changed: bool) -> Vec<Self> {
+ changed.then_some(Self::Metadata).into_iter().collect()
+ }
+}
+
+/// The fold's state, advanced one log entry at a time by [`State::step`] and
+/// owned by [`FoldMachineImpl`].
+#[derive(Debug, Default)]
+pub(super) struct FoldState {
+ /// Every message derived so far, oldest first - including the open turn's
+ /// agent message, which is appended to in place as the agent talks.
+ pub(super) messages: Vec<FoldedMessage>,
+ /// The session the entry currently being folded belongs to, for
+ /// [`State::warn`]. Set fresh from each log entry, so it is always
+ /// current even though it rarely changes within one fold.
+ pub(super) session: Option<AgentSessionId>,
+ /// The turn currently being built, if any.
+ pub(super) turn: Option<Turn>,
+ /// Where every tool call so far sits, so a patch can find it.
+ ///
+ /// Session-wide, not per turn: a user tool is patched *after* its turn
+ /// ended, when the user edits or sends the draft, and a subagent's calls
+ /// nest inside their parent. ACP tool call ids are unique within a
+ /// session, which is what makes one map sound.
+ pub(super) tool_positions: HashMap<ToolUseId, ToolPath>,
+ /// How many turns have been opened, which is also the next [`TurnId`].
+ pub(super) turns_opened: u32,
+ /// Outstanding permission requests, by the id of the request that asked.
+ pub(super) pending_permissions: HashMap<RequestId, ToolUseId>,
+ /// Session-level state derived so far. Handlers mutate it freely; the
+ /// machine diffs it against what it last reported.
+ pub(super) metadata: SessionMetadata,
+ /// The `initialize` request whose response will name the harness.
+ pub(super) pending_initialize: Option<RequestId>,
+ /// Requests whose responses carry config options. The response body is
+ /// authoritative - a rejected change answers with an error and moves
+ /// nothing.
+ pub(super) pending_config_requests: HashSet<RequestId>,
+ /// Controls awaiting a response, by request id: where the control part
+ /// sits (message, part), so the response can resolve its outcome.
+ pub(super) pending_controls: HashMap<RequestId, (usize, usize)>,
+}
+
+/// Where a tool call's part sits: which message, and the path of part
+/// indices to it - one index for a top-level part, more for one nested
+/// inside another part's children.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) struct ToolPath {
+ /// Index into [`FoldState::messages`].
+ pub(super) message: usize,
+ /// Part indices from the message's parts down to the tool's part.
+ pub(super) path: Vec<usize>,
+}
+
+/// A turn under construction.
+///
+/// Holds no content of its own. The turn's agent message lives in
+/// [`State::messages`] as soon as there is one, and everything here is a way
+/// back into it.
+#[derive(Debug)]
+pub(super) struct Turn {
+ pub(super) id: TurnId,
+ /// The `session/prompt` request whose response will close this turn.
+ ///
+ /// `None` for a turn opened without one - see
+ /// [`State::begin_turn_without_prompt`]. Such a turn has no id to
+ /// correlate against, so [`State::end_turn`] closes it on the first
+ /// response that reports a stop reason instead.
+ pub(super) prompt_id: Option<RequestId>,
+ /// Where this turn's agent message sits in [`State::messages`].
+ ///
+ /// `None` until the agent produces its first part, because a
+ /// [`FoldedMessage`] cannot hold an empty part list - which is also what
+ /// makes a turn the agent never answered derive no agent message at all.
+ pub(super) agent: Option<usize>,
+ /// Where each permission sits in the agent message's parts, so outcomes
+ /// can find it.
+ pub(super) permission_positions: HashMap<ToolUseId, usize>,
+ /// Where this turn's plan sits in the agent message's parts, so later
+ /// plan updates can replace it.
+ pub(super) plan_position: Option<usize>,
+ /// Whether closing this turn needs an agent message to record its stop
+ /// reason on, minting one if the agent never produced a part.
+ ///
+ /// True for a turn a prompt opened: the user's bubble is then the
+ /// transcript's newest turn message, and readers take one without a stop
+ /// reason to mean the agent is still working. False for a turn a control
+ /// opened (`/compact`), whose own message readers skip.
+ pub(super) expects_reply: bool,
+}
+
+impl FoldState {
+ /// Advance by one log entry, returning what it changed in emission order.
+ ///
+ /// One entry changes at most one message today - see [`FoldEvent`]
+ /// for why the prompt-interrupts-a-turn case is not an exception.
+ pub(super) fn step(&mut self, entry: AgentSessionLog) -> Vec<StepChange> {
+ self.session = Some(entry.agent_session_id);
+
+ // The one place the protocol is dispatched. Each arm names a frame
+ // this fold understands; the rest are ignored on purpose.
+ match &entry.content {
+ Message::ToRuntime(message @ ToRuntimeMessage::Acp(acp)) => {
+ // Before the control dispatch, which returns early for the
+ // set-model request whose response this correlates.
+ self.note_config_request(&acp.0);
+ self.note_initialize_request(&acp.0);
+ if let Some(action) = AgentAction::control_from_runtime(message) {
+ return StepChange::message(match action {
+ AgentAction::SetModel(action) => {
+ let request_id = match &acp.0 {
+ RawJsonRpcMessage::Request(request) => Some(&request.id),
+ _ => None,
+ };
+ self.record_control(
+ Control::SetModel {
+ model: action.model,
+ },
+ request_id,
+ entry.user_id.clone(),
+ )
+ }
+ AgentAction::Compact => match &acp.0 {
+ RawJsonRpcMessage::Request(request) => {
+ self.begin_compact(&request.id, entry.user_id.clone())
+ }
+ _ => None,
+ },
+ // A stop is a notification: nothing can answer it, so
+ // it is accepted the moment it is sent.
+ AgentAction::Stop => {
+ self.record_control(Control::Stop, None, entry.user_id.clone())
+ }
+ AgentAction::Prompt(_) => None,
+ });
+ }
+ StepChange::message(match &acp.0 {
+ // A user's prompt opens a turn.
+ RawJsonRpcMessage::Request(request)
+ if PromptRequest::matches_method(&request.method) =>
+ {
+ self.begin_turn(&request.id, request.params.as_ref(), entry.user_id.clone())
+ }
+ // The user's answer to a permission request.
+ RawJsonRpcMessage::Response(Response::Result { id, result }) => {
+ self.resolve_permission(id, Some(result))
+ }
+ RawJsonRpcMessage::Response(Response::Error { id, .. }) => {
+ self.resolve_permission(id, None)
+ }
+ // Handshake and configuration traffic: nothing to render.
+ RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => None,
+ })
+ }
+
+ Message::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {
+ // The bulk of the log: streamed content and tool activity.
+ RawJsonRpcMessage::Notification(notification)
+ if SessionNotification::matches_method(&notification.method) =>
+ {
+ self.apply_session_update(notification.params.as_ref())
+ }
+ // The agent asking to proceed.
+ RawJsonRpcMessage::Request(request)
+ if RequestPermissionRequest::matches_method(&request.method) =>
+ {
+ StepChange::message(
+ self.request_permission(&request.id, request.params.as_ref()),
+ )
+ }
+ // The response to `session/prompt` closes the turn; a
+ // config-bearing response updates the metadata; a control's
+ // response resolves its outcome. Set-model is both of the
+ // latter at once.
+ RawJsonRpcMessage::Response(Response::Result { id, result }) => {
+ if self.pending_initialize.as_ref() == Some(id) {
+ self.pending_initialize = None;
+ return StepChange::metadata(self.apply_initialize_response(result));
+ }
+ let control = self.resolve_control(id, None);
+ if self.pending_config_requests.remove(id) {
+ let mut changes = StepChange::message(control);
+ changes.extend(StepChange::metadata(self.apply_config_response(result)));
+ changes
+ } else if control.is_some() {
+ StepChange::message(control)
+ } else {
+ StepChange::message(self.end_turn(id, Some(result)))
+ }
+ }
+ RawJsonRpcMessage::Response(Response::Error { id, error }) => {
+ let control = self.resolve_control(id, Some(&error.message));
+ // An error response moves no metadata, so a config-bearing
+ // request's failure changes at most its control part.
+ if self.pending_config_requests.remove(id) || control.is_some() {
+ StepChange::message(control)
+ } else {
+ StepChange::message(self.fail_turn(id, &error.message))
+ }
+ }
+ RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => Vec::new(),
+ },
+
+ // Runtime lifecycle events carry no conversation content, but
+ // they are the session's status, and `acp_ready` marks a
+ // connection boundary: request ids restart per connection, so
+ // nothing pending can be answered past one - a stale entry would
+ // misattribute a new connection's reused id.
+ Message::ToServer(ToServerMessage::Event { event }) => {
+ if matches!(event, SystemEvent::AcpReady) {
+ self.pending_initialize = None;
+ self.pending_config_requests.clear();
+ self.pending_permissions.clear();
+ self.pending_controls.clear();
+ }
+ let status = Some(event.as_str().to_owned());
+ let changed = self.metadata.status != status;
+ if changed {
+ self.metadata.status = status;
+ }
+ StepChange::metadata(changed)
+ }
+
+ // The wrapped protocol enums are `#[non_exhaustive]`.
+ Message::ToServer(_) | Message::ToRuntime(_) => Vec::new(),
+ }
+ }
+
+ /// Handle a `session/update`.
+ pub(super) fn apply_session_update(
+ &mut self,
+ params: Option<&RawJsonRpcParams>,
+ ) -> Vec<StepChange> {
+ // Only the `update` field is folded; the rest of the notification
+ // (session id, meta) carries nothing renderable. Borrowed out of the
+ // params rather than cloning them - `session/update` is the bulk of
+ // any log, so this is the fold's hot path.
+ let Some(update_value) = param(params, "update") else {
+ self.warn(FoldError::Unknown {
+ kind: "<missing params>".to_owned(),
+ });
+ return Vec::new();
+ };
+
+ // Keep the wire name before decoding, so an unmodelled variant can be
+ // named in the anomaly even though `SessionUpdate` is non-exhaustive.
+ let wire_kind = update_value
+ .get("sessionUpdate")
+ .and_then(|kind| kind.as_str())
+ .unwrap_or("<missing>")
+ .to_owned();
+
+ let Ok(update) = SessionUpdate::deserialize(update_value) else {
+ self.warn(FoldError::Unknown { kind: wire_kind });
+ return Vec::new();
+ };
+
+ match update {
+ // Prose from the agent. Chunks are appended to the open text part
+ // rather than each becoming a part of its own.
+ SessionUpdate::AgentMessageChunk(chunk) => StepChange::message(
+ content_block_text(chunk.content).and_then(|text| self.append_text(text)),
+ ),
+ // Reasoning, kept separate so a reader can collapse it.
+ SessionUpdate::AgentThoughtChunk(chunk) => StepChange::message(
+ content_block_text(chunk.content).and_then(|text| self.append_thought(text)),
+ ),
+ // The agent replaying the user's own message. The prompt frame is
+ // the authoritative copy, so this is dropped.
+ SessionUpdate::UserMessageChunk(_) => Vec::new(),
+ SessionUpdate::ToolCall(call) => {
+ let mut changes =
+ StepChange::metadata(self.sniff_harness(&ToolFrame::of_call(&call)));
+ changes.extend(StepChange::message(self.open_tool_call(call)));
+ changes
+ }
+ SessionUpdate::ToolCallUpdate(update) => {
+ let mut changes =
+ StepChange::metadata(self.sniff_harness(&ToolFrame::of_update(&update)));
+ changes.extend(StepChange::message(self.patch_tool_call(update)));
+ changes
+ }
+ SessionUpdate::SessionInfoUpdate(update) => {
+ StepChange::metadata(self.apply_session_info(&update))
+ }
+ SessionUpdate::ConfigOptionUpdate(update) => {
+ StepChange::metadata(self.apply_config_options(update.config_options))
+ }
+ SessionUpdate::AvailableCommandsUpdate(update) => {
+ StepChange::metadata(self.apply_available_commands(update))
+ }
+ // Deliberately dropped: token accounting and session bookkeeping,
+ // none of which a reader wants in a channel. `usage_update` alone
+ // is 81 of ~450 frames in a recorded session.
+ SessionUpdate::UsageUpdate(_) | SessionUpdate::CurrentModeUpdate(_) => Vec::new(),
+ // The agent's todo list, carried whole each time.
+ SessionUpdate::Plan(plan) => StepChange::message(self.apply_plan(plan)),
+ _ => {
+ self.warn(FoldError::Unknown { kind: wire_kind });
+ Vec::new()
+ }
+ }
+ }
+
+ /// How to read the frames of whichever harness produced this log.
+ pub(super) fn reader(&self) -> &'static dyn HarnessReader {
+ self.metadata.harness.reader()
+ }
+
+ /// The open turn, for the handlers that have already established there is
+ /// one.
+ pub(super) fn open_turn(&mut self) -> &mut Turn {
+ self.turn.as_mut().expect("a turn is open")
+ }
+
+ /// Log a frame the fold could not account for. Not fatal - see the
+ /// module docs - so this only ever logs and never returns an error.
+ pub(super) fn warn(&self, error: FoldError) {
+ tracing::warn!(
+ session = ?self.session,
+ error = ?error,
+ "agent session log frame could not be folded"
+ );
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/subagent.rs b/crates/agent_fold/src/domain/fold/subagent.rs
new file mode 100644
index 0000000000..46273ab9b3
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/subagent.rs
@@ -0,0 +1,142 @@
+//! Delegated agents: building a subagent's detail, patching it, and nesting
+//! the calls it made under it.
+
+use crate::domain::error::FoldError;
+use crate::domain::harness::{self, HarnessReader, ToolFrame};
+use crate::domain::model::{MessagePart, ToolDetail, ToolName, ToolUseId};
+
+use super::state::{Changed, FoldState, ToolPath};
+
+impl FoldState {
+ /// Where a call the harness attributes to a parent should go: into the
+ /// parent's children, if the parent is a subagent this fold has seen.
+ /// A parent it has not seen is warned about and the call lands at top
+ /// level rather than being dropped.
+ pub(super) fn parent_path(
+ &mut self,
+ reader: &dyn HarnessReader,
+ frame: &ToolFrame<'_>,
+ child: &ToolUseId,
+ ) -> Option<ToolPath> {
+ let parent = reader.parent_tool_call(frame)?;
+ let Some(path) = self.tool_positions.get(&parent).cloned() else {
+ self.warn(FoldError::UnknownParent {
+ tool_call: child.clone(),
+ parent,
+ });
+ return None;
+ };
+ let is_subagent = self
+ .part_at_mut(&path)
+ .is_some_and(|part| part.children_mut().is_some());
+ if is_subagent {
+ return Some(path);
+ }
+ self.warn(FoldError::UnknownParent {
+ tool_call: child.clone(),
+ parent,
+ });
+ None
+ }
+
+ /// Add `part` under the subagent at `parent`, returning where it landed.
+ /// `None` only if the path no longer resolves to a subagent, which
+ /// [`Self::parent_path`] has just checked.
+ pub(super) fn push_child_part(
+ &mut self,
+ parent: &ToolPath,
+ part: MessagePart,
+ ) -> Option<(Changed, ToolPath)> {
+ let children = self.part_at_mut(parent)?.children_mut()?;
+ let index = children.len();
+ children.push(part);
+ let mut path = parent.path.clone();
+ path.push(index);
+ Some((
+ Changed::updated(parent.message),
+ ToolPath {
+ message: parent.message,
+ path,
+ },
+ ))
+ }
+}
+
+/// What to call a delegation: the harness's description, else the first
+/// non-empty line of the brief, else the tool's own name. Decided here, once,
+/// so every reader shows the same thing and none has to fall back itself.
+fn subagent_title(description: Option<&str>, prompt: Option<&str>, name: &ToolName) -> String {
+ description
+ .map(str::trim)
+ .filter(|description| !description.is_empty())
+ .or_else(|| prompt?.lines().map(str::trim).find(|line| !line.is_empty()))
+ .unwrap_or_else(|| name.display())
+ .to_owned()
+}
+
+/// The detail for a subagent call, from its opening frame.
+pub(super) fn subagent_detail(
+ reader: &dyn HarnessReader,
+ name: &ToolName,
+ frame: &ToolFrame<'_>,
+) -> ToolDetail {
+ let input = reader.subagent_input(frame);
+ ToolDetail::Subagent {
+ title: subagent_title(input.description.as_deref(), input.prompt.as_deref(), name),
+ agent_type: input.agent_type,
+ description: input.description,
+ prompt: input.prompt,
+ background: input.background.unwrap_or(false),
+ children: reader.subagent_transcript(frame),
+ result: harness::subagent_result(reader, name, frame).map(Box::new),
+ }
+}
+
+/// Write an update's fields into a subagent's detail: input fields the
+/// update names, whatever result it reports merged over what is held, and
+/// the child's transcript when the harness delivers one whole.
+pub(super) fn patch_subagent_detail(
+ reader: &dyn HarnessReader,
+ name: &ToolName,
+ detail: &mut ToolDetail,
+ frame: &ToolFrame<'_>,
+) {
+ let ToolDetail::Subagent {
+ title,
+ agent_type,
+ description,
+ prompt,
+ background,
+ children,
+ result,
+ } = detail
+ else {
+ return;
+ };
+ let transcript = reader.subagent_transcript(frame);
+ if !transcript.is_empty() {
+ *children = transcript;
+ }
+ if frame.raw_input.is_some() || frame.title.is_some() {
+ let input = reader.subagent_input(frame);
+ if input.agent_type.is_some() {
+ *agent_type = input.agent_type;
+ }
+ if input.description.is_some() {
+ *description = input.description;
+ }
+ if input.prompt.is_some() {
+ *prompt = input.prompt;
+ }
+ if let Some(found) = input.background {
+ *background = found;
+ }
+ *title = subagent_title(description.as_deref(), prompt.as_deref(), name);
+ }
+ if let Some(reported) = harness::subagent_result(reader, name, frame) {
+ match result {
+ Some(existing) => existing.merge(reported),
+ None => *result = Some(Box::new(reported)),
+ }
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/tool_call.rs b/crates/agent_fold/src/domain/fold/tool_call.rs
new file mode 100644
index 0000000000..c133ba86a9
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/tool_call.rs
@@ -0,0 +1,374 @@
+//! Tool calls: opening a part for one and patching it as updates arrive.
+
+use std::path::PathBuf;
+
+use crate::domain::error::FoldError;
+use crate::domain::harness::{
+ self, HarnessReader, ToolFrame, ToolShape, command_from_raw_input, file_edit_from_raw_input,
+};
+use crate::domain::model::{
+ AnsiText, FileDiff, MessagePart, ToolDetail, ToolName, ToolUseId, UserToolOutcome,
+};
+use agent_client_protocol::schema::v1::{
+ ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdate, ToolKind,
+};
+
+use super::convert::tool_kind_name;
+use super::state::{Changed, FoldState, ToolPath};
+use super::subagent::{patch_subagent_detail, subagent_detail};
+
+impl FoldState {
+ /// Handle a `tool_call`: add a new tool part.
+ pub(super) fn open_tool_call(&mut self, call: ToolCall) -> Option<Changed> {
+ let id = ToolUseId(call.tool_call_id.0.to_string());
+ let reader = self.reader();
+ let frame = ToolFrame::of_call(&call);
+ let name = harness::tool_name(reader, &frame);
+
+ // Whose shape the call is in is decided here, once; a patch finds the
+ // detail it opened with and reads into that.
+ let detail = match harness::tool_shape(reader, &name, &frame) {
+ ToolShape::Harness => tool_detail(reader, &frame),
+ ToolShape::Macro(_) => macro_detail(reader, &frame),
+ ToolShape::UserTool(tool) => user_tool_detail(reader, tool, &frame),
+ ToolShape::Subagent => subagent_detail(reader, &name, &frame),
+ };
+ let tool = MessagePart::ToolUse {
+ id: id.clone(),
+ name,
+ status: call.status.into(),
+ detail,
+ };
+
+ // A repeated open for the same id patches in place rather than
+ // duplicating the row. A subagent's children were pushed by their own
+ // frames, which a re-announcement of the parent does not carry, so
+ // they are kept - unless the re-announcement carries the child's
+ // whole transcript itself, which is then the newer copy.
+ if let Some(at) = self.tool_positions.get(&id).cloned() {
+ let message = at.message;
+ if let Some(existing @ MessagePart::ToolUse { .. }) = self.part_at_mut(&at) {
+ let mut tool = tool;
+ if let (Some(kept), Some(children)) = (existing.children_mut(), tool.children_mut())
+ && children.is_empty()
+ {
+ children.append(kept);
+ }
+ *existing = tool;
+ }
+ return Some(Changed::updated(message));
+ }
+
+ // A call the harness attributes to a subagent nests under it.
+ let (changed, at) = match self.parent_path(reader, &frame, &id) {
+ Some(parent) => self.push_child_part(&parent, tool)?,
+ None => {
+ let (changed, position) = self.push_agent_part(tool)?;
+ (
+ changed,
+ ToolPath {
+ message: changed.message,
+ path: vec![position],
+ },
+ )
+ }
+ };
+ self.tool_positions.insert(id, at);
+ Some(changed)
+ }
+
+ /// Handle a `tool_call_update`: patch an existing tool part.
+ ///
+ /// Only fields the update actually carries are written, since
+ /// `ToolCallUpdateFields` is entirely optional and a typical call is
+ /// patched several times - the recordings average about four updates per
+ /// call.
+ pub(super) fn patch_tool_call(&mut self, update: ToolCallUpdate) -> Option<Changed> {
+ let id = ToolUseId(update.tool_call_id.0.to_string());
+ let reader = self.reader();
+
+ let Some(at) = self.tool_positions.get(&id).cloned() else {
+ self.warn(FoldError::PatchBeforeOpen { tool_call: id });
+ return None;
+ };
+ let message = at.message;
+ let Some(MessagePart::ToolUse {
+ name,
+ status,
+ detail,
+ ..
+ }) = self.part_at_mut(&at)
+ else {
+ return None;
+ };
+
+ let frame = ToolFrame::of_update(&update);
+ if let Some(new_status) = frame.status {
+ *status = new_status;
+ }
+ // Readers see the status the call is in once this update lands, so
+ // "has it finished" is answered the same on a patch that carries a
+ // status and on one that follows it.
+ let frame = frame.with_status(*status);
+
+ // A harness-supplied name outranks any ACP title, so a title alone
+ // only fills a name nothing better has set.
+ if let Some(found) = reader.reported_tool_name(&frame) {
+ *name = found;
+ } else if let Some(title) = frame.title
+ && name.is_empty()
+ {
+ *name = title.parse().unwrap_or_else(|never| match never {});
+ }
+
+ match detail {
+ ToolDetail::Macro { .. } | ToolDetail::UserTool { .. } => {
+ patch_macro_detail(reader, name, detail, &frame);
+ }
+ ToolDetail::Subagent { .. } => patch_subagent_detail(reader, name, detail, &frame),
+ _ => patch_detail(reader, detail, &frame),
+ }
+
+ Some(Changed::updated(message))
+ }
+}
+
+/// Build a [`ToolDetail`] from a tool call's opening frame.
+pub(super) fn tool_detail(reader: &dyn HarnessReader, frame: &ToolFrame<'_>) -> ToolDetail {
+ let content = frame.content.unwrap_or_default();
+ let locations = frame.locations.unwrap_or_default();
+ match frame.kind.unwrap_or_default() {
+ ToolKind::Execute => ToolDetail::Terminal {
+ command: command_from_raw_input(frame.raw_input),
+ output: reader.terminal_output(frame).map(AnsiText),
+ exit_code: reader.terminal_exit_code(frame),
+ },
+ ToolKind::Edit => ToolDetail::Edit {
+ diffs: edit_diffs(content, frame.raw_input),
+ },
+ ToolKind::Read => ToolDetail::Read {
+ paths: location_paths(locations),
+ },
+ ToolKind::Delete => ToolDetail::Delete {
+ paths: location_paths(locations),
+ },
+ ToolKind::Move => ToolDetail::Move {
+ paths: location_paths(locations),
+ },
+ ToolKind::Search => ToolDetail::Search {
+ paths: location_paths(locations),
+ output: frame.content_text(),
+ },
+ ToolKind::Fetch => ToolDetail::Fetch {
+ output: frame.content_text(),
+ },
+ ToolKind::Think => ToolDetail::Think {
+ output: frame.content_text(),
+ },
+ other => ToolDetail::Other {
+ kind: tool_kind_name(other).to_owned(),
+ output: frame.content_text(),
+ input: frame.raw_input.cloned(),
+ },
+ }
+}
+
+/// Build the detail for a Macro tool from its opening frame: its input as
+/// given, its output out of the harness's wrapper.
+pub(super) fn macro_detail(reader: &dyn HarnessReader, frame: &ToolFrame<'_>) -> ToolDetail {
+ let (output, error) = match frame.raw_output.map(|raw| reader.unwrap_tool_output(raw)) {
+ None => (None, None),
+ Some((value, error)) => (Some(value), error),
+ };
+ ToolDetail::Macro {
+ input: frame.raw_input.cloned().unwrap_or(serde_json::Value::Null),
+ output,
+ error,
+ }
+}
+
+/// Build the detail for a Macro user tool from its opening frame.
+///
+/// A user tool starts [`UserToolOutcome::Pending`] whether or not the frame
+/// carried output: the backend's `"PendingUserExecution"` reads as pending
+/// too, and a frame with nothing yet is a call still being made.
+pub(super) fn user_tool_detail(
+ reader: &dyn HarnessReader,
+ tool: &str,
+ frame: &ToolFrame<'_>,
+) -> ToolDetail {
+ ToolDetail::UserTool {
+ input: frame.raw_input.cloned().unwrap_or(serde_json::Value::Null),
+ outcome: frame.raw_output.map_or(UserToolOutcome::Pending, |raw| {
+ harness::user_tool_outcome(reader, tool, raw)
+ }),
+ }
+}
+
+/// Write an update's raw input and output into a Macro tool's detail.
+///
+/// Both replace rather than merge: a harness sends the arguments whole each
+/// time, and so does the session API that later records what the user did
+/// with a user tool.
+pub(super) fn patch_macro_detail(
+ reader: &dyn HarnessReader,
+ name: &ToolName,
+ detail: &mut ToolDetail,
+ frame: &ToolFrame<'_>,
+) {
+ match detail {
+ ToolDetail::Macro {
+ input,
+ output,
+ error,
+ } => {
+ if let Some(found) = frame.raw_input {
+ *input = found.clone();
+ }
+ if let Some(raw) = frame.raw_output {
+ let (value, failure) = reader.unwrap_tool_output(raw);
+ *output = Some(value);
+ *error = failure;
+ }
+ }
+ ToolDetail::UserTool { input, outcome } => {
+ if let Some(found) = frame.raw_input {
+ *input = found.clone();
+ }
+ if let Some(raw) = frame.raw_output {
+ // The detail says this is a user tool, so the name's short
+ // form is the tool's: `SendEmail` whether the harness wrote it
+ // bare or as `mcp__macro__SendEmail`.
+ *outcome = harness::user_tool_outcome(reader, name.display(), raw);
+ }
+ }
+ _ => {}
+ }
+}
+
+/// Write an update's fields into an existing detail, leaving what it does not
+/// carry untouched.
+pub(super) fn patch_detail(
+ reader: &dyn HarnessReader,
+ detail: &mut ToolDetail,
+ frame: &ToolFrame<'_>,
+) {
+ match detail {
+ ToolDetail::Terminal {
+ command,
+ output,
+ exit_code,
+ } => {
+ if let Some(found) = command_from_raw_input(frame.raw_input) {
+ *command = Some(found);
+ }
+ // Each update carries the output accumulated so far, so replace.
+ if let Some(found) = reader.terminal_output(frame) {
+ *output = Some(AnsiText(found));
+ }
+ if let Some(found) = reader.terminal_exit_code(frame) {
+ *exit_code = Some(found);
+ }
+ }
+ ToolDetail::Edit { diffs: existing } => {
+ if let Some(content) = frame.content {
+ let found = diffs(content);
+ if !found.is_empty() {
+ *existing = found;
+ }
+ }
+ // A call that never reports a diff block (Claude Code's `Write`)
+ // may still deliver its raw input on a later update.
+ if existing.is_empty()
+ && let Some(found) = synthesized_edit_diff(frame.raw_input)
+ {
+ *existing = vec![found];
+ }
+ }
+ ToolDetail::Read { paths } | ToolDetail::Delete { paths } | ToolDetail::Move { paths } => {
+ if let Some(found) = frame.locations.map(location_paths)
+ && !found.is_empty()
+ {
+ *paths = found;
+ }
+ }
+ ToolDetail::Search { paths, output } => {
+ if let Some(found) = frame.locations.map(location_paths)
+ && !found.is_empty()
+ {
+ *paths = found;
+ }
+ if let Some(found) = frame.content_text() {
+ *output = Some(found);
+ }
+ }
+ ToolDetail::Fetch { output } | ToolDetail::Think { output } => {
+ if let Some(found) = frame.content_text() {
+ *output = Some(found);
+ }
+ }
+ ToolDetail::Other { input, output, .. } => {
+ if let Some(found) = frame.raw_input {
+ *input = Some(found.clone());
+ }
+ if let Some(found) = frame.content_text() {
+ *output = Some(found);
+ }
+ }
+ // Patched by `patch_macro_detail` / `patch_subagent_detail`, which
+ // have the name and the harness's result shapes to hand.
+ ToolDetail::Macro { .. } | ToolDetail::UserTool { .. } | ToolDetail::Subagent { .. } => {}
+ }
+}
+
+/// An edit call's diffs: the reported diff blocks, or — for calls that never
+/// report one, like Claude Code's `Write` — a whole-file diff synthesized
+/// from the raw input.
+pub(super) fn edit_diffs(
+ content: &[ToolCallContent],
+ raw_input: Option<&serde_json::Value>,
+) -> Vec<FileDiff> {
+ let found = diffs(content);
+ if !found.is_empty() {
+ return found;
+ }
+ synthesized_edit_diff(raw_input).into_iter().collect()
+}
+
+/// A whole-file diff from `{filePath, content}` raw input. The prior contents
+/// are not on the wire, so the file reads as new.
+pub(super) fn synthesized_edit_diff(raw_input: Option<&serde_json::Value>) -> Option<FileDiff> {
+ let (path, content) = file_edit_from_raw_input(raw_input)?;
+ Some(FileDiff {
+ path: path.into(),
+ old_text: None,
+ new_text: content,
+ })
+}
+
+/// The diffs among a tool call's content blocks.
+pub(super) fn diffs(content: &[ToolCallContent]) -> Vec<FileDiff> {
+ content
+ .iter()
+ .filter_map(|block| match block {
+ ToolCallContent::Diff(diff) => Some(FileDiff {
+ path: diff.path.clone(),
+ old_text: diff.old_text.clone(),
+ new_text: diff.new_text.clone(),
+ }),
+ _ => None,
+ })
+ .collect()
+}
+
+/// The paths among a tool call's reported locations.
+///
+/// The one source this fold trusts for "what path did this call touch" -
+/// `locations` is ACP's own field, meant for exactly this, unlike `rawInput`,
+/// whose keys are a harness's own convention with no fixed shape to read.
+pub(super) fn location_paths(locations: &[ToolCallLocation]) -> Vec<PathBuf> {
+ locations
+ .iter()
+ .map(|location| location.path.clone())
+ .collect()
+}
diff --git a/crates/agent_fold/src/domain/fold/turn.rs b/crates/agent_fold/src/domain/fold/turn.rs
new file mode 100644
index 0000000000..cc2a150fd9
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/turn.rs
@@ -0,0 +1,217 @@
+//! Opening, closing, and failing turns.
+
+use std::collections::HashMap;
+
+use crate::domain::error::FoldError;
+use crate::domain::model::{Author, FoldedMessage, MessagePart, StopReason, TurnId};
+use agent_client_protocol::RawJsonRpcParams;
+use agent_client_protocol::schema::v1::{PromptRequest, RequestId};
+use agent_runtime_protocol::domain::action::AgentActionId;
+use macro_user_id::user_id::MacroUserIdStr;
+use non_empty::NonEmpty;
+
+use super::convert::{content_block_text, deserialize_params};
+use super::state::{Changed, FoldState, Turn};
+
+impl FoldState {
+ /// Handle a `session/prompt`: emit the user's message, open a turn.
+ pub(super) fn begin_turn(
+ &mut self,
+ prompt_id: &RequestId,
+ params: Option<&RawJsonRpcParams>,
+ user_id: Option<MacroUserIdStr<'static>>,
+ ) -> Option<Changed> {
+ // A second prompt without an intervening response means the previous
+ // turn never got one. Its agent message is already in `messages` and
+ // already reads `stop: None`, so there is nothing left to report -
+ // which is what keeps a push to one changed message.
+ let closed = self.close_turn(None);
+ debug_assert!(
+ closed.is_none(),
+ "closing a turn without a stop reason changes nothing"
+ );
+
+ let id = TurnId(self.turns_opened);
+ self.turns_opened += 1;
+
+ // A params shape this fold does not recognize derives no text, same
+ // as an empty prompt - see the module docs on why a mismatch here
+ // degrades rather than warns: `PromptRequest`'s own fields (a session
+ // id, an optional `_meta`) carry nothing this fold renders, so there
+ // is nothing to warn *about* beyond "no text," which showing no user
+ // message already says.
+ let text = deserialize_params::<PromptRequest>(params)
+ .map(|request| {
+ request
+ .prompt
+ .into_iter()
+ .filter_map(content_block_text)
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .unwrap_or_default();
+
+ // A prompt carrying no text derives no user message, but still opens
+ // the turn the agent will answer into.
+ let changed = (!text.is_empty()).then(|| {
+ let message = self.messages.len();
+ self.messages.push(FoldedMessage {
+ id,
+ author: Author::User { user_id },
+ request_id: AgentActionId::from_request_id(prompt_id),
+ parts: NonEmpty::one(MessagePart::Text { text }),
+ stop: None,
+ });
+ Changed::new(message)
+ });
+
+ self.turn = Some(Turn {
+ id,
+ prompt_id: Some(prompt_id.clone()),
+ agent: None,
+ permission_positions: HashMap::new(),
+ plan_position: None,
+ expects_reply: true,
+ });
+
+ changed
+ }
+
+ /// Handle the response to `session/prompt`: close the turn.
+ pub(super) fn end_turn(
+ &mut self,
+ response_id: &RequestId,
+ value: Option<&serde_json::Value>,
+ ) -> Option<Changed> {
+ let stop = value
+ .and_then(|value| value.get("stopReason"))
+ .and_then(|reason| reason.as_str())
+ // Infallible: `StopReason`'s unmodelled variant is strum's default.
+ .and_then(|reason| reason.parse().ok());
+
+ let closes_the_open_turn = match self.turn.as_ref() {
+ Some(turn) => match &turn.prompt_id {
+ // The ordinary case: the response to the prompt that opened it.
+ Some(prompt_id) => prompt_id == response_id,
+ // A turn nothing prompted has no id to match against, so the
+ // first response reporting a stop reason is taken as its
+ // answer - the prompt it belongs to is in an earlier log.
+ None => stop.is_some(),
+ },
+ None => false,
+ };
+
+ if !closes_the_open_turn {
+ // Responses to `initialize`, `session/new` and `session/load`
+ // land here. Only flag one that looks like a turn ending.
+ if stop.is_some() {
+ self.warn(FoldError::UncorrelatedResponse);
+ }
+ return None;
+ }
+
+ self.close_turn(stop)
+ }
+
+ /// End the open turn because its prompt was answered with an error.
+ ///
+ /// The turn has to end even when the agent produced nothing at all -
+ /// which is the common case, since a runtime that rejects a prompt
+ /// rejects it before writing anything. That is why this cannot go
+ /// through [`Self::close_turn`], whose job is to stamp a stop reason on
+ /// an agent message that exists: here the agent message is created if
+ /// need be, so the failure has somewhere to live and the turn is
+ /// unambiguously over.
+ pub(super) fn fail_turn(&mut self, response_id: &RequestId, message: &str) -> Option<Changed> {
+ let closes_the_open_turn = self
+ .turn
+ .as_ref()
+ .and_then(|turn| turn.prompt_id.as_ref())
+ .is_some_and(|prompt_id| prompt_id == response_id);
+ if !closes_the_open_turn {
+ return None;
+ }
+
+ // An error is worth showing under any turn, control's included, so
+ // this mints unconditionally where a clean close does not.
+ let turn = self.turn.take()?;
+ let (agent, changed) = match turn.agent {
+ Some(agent) => (agent, Changed::updated(agent)),
+ None => self.mint_agent_message(turn.id),
+ };
+ self.messages[agent].stop = Some(StopReason::Failed {
+ message: message.to_owned(),
+ });
+ Some(changed)
+ }
+
+ /// Close the open turn, recording on its agent message how it stopped.
+ ///
+ /// Usually the agent message has been in [`State::messages`] since the
+ /// agent's first part, and all that is left is the stop reason. When the
+ /// agent produced nothing at all, one is minted to carry it: readers ask
+ /// whether a turn is running by looking for a stop reason on the
+ /// transcript's tail, so recording none anywhere reads as working
+ /// forever. That is a stop pressed before the first chunk - a first
+ /// prompt spends ~10s creating the Cursor agent - which answers
+ /// `session/prompt` with `cancelled` and nothing to stamp it on.
+ pub(super) fn close_turn(&mut self, stop: Option<StopReason>) -> Option<Changed> {
+ let Some(stop) = stop else {
+ // Nothing to record, so nothing to mint a message for.
+ self.turn = None;
+ return None;
+ };
+ let turn = self.turn.take()?;
+ let (message, changed) = match turn.agent {
+ Some(message) => (message, Changed::updated(message)),
+ // A turn a control opened is skipped by those readers, so an
+ // empty agent bubble under its line would be noise, not a fix.
+ None if !turn.expects_reply => return None,
+ None => self.mint_agent_message(turn.id),
+ };
+ self.messages[message].stop = Some(stop);
+ Some(changed)
+ }
+
+ /// Mint the agent message a turn never opened, so a stop reason has
+ /// somewhere to sit. Reported as new: the client has not seen it.
+ pub(super) fn mint_agent_message(&mut self, turn: TurnId) -> (usize, Changed) {
+ let message = self.messages.len();
+ self.messages.push(FoldedMessage {
+ id: turn,
+ author: Author::Agent,
+ request_id: None,
+ parts: NonEmpty::one(MessagePart::Text {
+ text: String::new(),
+ }),
+ stop: None,
+ });
+ (message, Changed::new(message))
+ }
+
+ /// Open a turn for agent content that arrived without a prompt.
+ ///
+ /// A session resumed through `session/load` picks up mid-conversation: the
+ /// prompt the agent is answering is in the log of the session it resumed,
+ /// not this one. Dropping the content for want of a prompt folded such a
+ /// session to nothing at all - hundreds of frames of real work rendering
+ /// as an empty channel - and showing the reply without the question is
+ /// plainly better than showing neither.
+ ///
+ /// The turn is numbered like any other and produces no user message, since
+ /// there is no prompt to attribute one to. It is closed by the first
+ /// response carrying a stop reason; see [`State::end_turn`].
+ pub(super) fn begin_turn_without_prompt(&mut self) {
+ let id = TurnId(self.turns_opened);
+ self.turns_opened += 1;
+
+ self.turn = Some(Turn {
+ id,
+ prompt_id: None,
+ agent: None,
+ permission_positions: HashMap::new(),
+ plan_position: None,
+ expects_reply: true,
+ });
+ }
+}
diff --git a/crates/agent_fold/src/domain/harness.rs b/crates/agent_fold/src/domain/harness.rs
new file mode 100644
index 0000000000..83da9d8ad3
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness.rs
@@ -0,0 +1,503 @@
+//! Harness-specific conventions: who produced the log, and how to read what
+//! they wrote beyond the ACP schema.
+//!
+//! ACP gives a tool call a human-readable `title`, a coarse
+//! [`ToolKind`](agent_client_protocol::ToolKind), typed content blocks, and
+//! three fields it deliberately leaves open: `rawInput`, `rawOutput`, and
+//! `_meta`. The material a reader most wants lives in those open fields, by
+//! each harness's own convention:
+//!
+//! - The real tool name (`Bash`, `Read`, `Write`). Claude Code writes it to
+//! `_meta`; Codex spells MCP tools into the title; OpenClaw prefixes the
+//! title with it.
+//! - Terminal output and exit codes. ACP's own
+//! [`Terminal`](agent_client_protocol::Terminal) content block carries only
+//! a `terminalId` pointing at a terminal the client is expected to have
+//! created itself. A fold reading a historical log never created one, so the
+//! only output it will ever see is the copy in `_meta`.
+//! - Whether a call delegates to another agent, and what that agent said.
+//! Every harness spells this differently: a `_meta` flag, a tool name, a
+//! title prefix; the answer in `_meta`, in `rawInput`, in `rawOutput`, or
+//! in the content text.
+//!
+//! So each harness gets a [`HarnessReader`] in its own file, and every reader
+//! method takes the whole frame - a [`ToolFrame`] - rather than the fields
+//! some earlier harness happened to need. A harness that answers a question
+//! from a field no other harness uses reads it off the frame; the trait does
+//! not change. Every method has a harness-neutral default in [`generic`], so
+//! an unknown harness still folds; a known one overrides only what it can
+//! answer from its own conventions. Every reader treats a missing or
+//! misshapen field as "no information".
+//!
+//! Two things a tool call carries are not the harness's to define, and have
+//! modules of their own rather than a reader:
+//!
+//! - [`mcp`] - the envelope MCP wraps every external tool's result in, which
+//! a harness may copy into `rawOutput` whole.
+//! - [`macro_tools`] - Macro's own tools, which any harness may call (over
+//! Macro's MCP server, or natively when the harness *is* Macro's agent).
+//! Their names and result shapes are Macro's whichever harness relayed
+//! them.
+//!
+//! The fold reads a call through the functions at the bottom of this file -
+//! [`tool_name`], [`tool_shape`], [`subagent_result`], [`user_tool_outcome`]
+//! - which decide whose shape a call is in and read it accordingly, so the
+//! fold itself never names a harness, MCP, or a Macro tool.
+//!
+//! Supporting a new harness is one file here and one arm in
+//! [`Harness::reader`]. The reader says how to recognize itself
+//! ([`HarnessReader::announces`], [`HarnessReader::wrote`]) as well as how
+//! to read its frames.
+
+/// The Claude Code harness (`claude-agent-acp`).
+pub mod claude_code;
+/// OpenAI Codex through `codex-acp`.
+pub mod codex;
+/// Cursor cloud agents through `cursor_cloud_agents`.
+pub mod cursor;
+/// Harness-neutral defaults.
+pub mod generic;
+/// Nous Research's Hermes agent.
+pub mod hermes;
+/// Macro's own in-process agent (`agent_inmem`).
+pub mod macro_inmem;
+/// Macro's tools: their names and what they return.
+pub mod macro_tools;
+/// MCP's result envelope.
+pub mod mcp;
+/// OpenClaw's ACP gateway.
+pub mod openclaw;
+/// OpenCode's built-in ACP server.
+pub mod opencode;
+
+use crate::domain::model::{
+ Harness, MessagePart, SubagentResult, ToolName, ToolStatus, ToolUseId, UserToolOutcome,
+};
+use agent_client_protocol::schema::v1::{
+ Content, ContentBlock, Meta, ToolCall, ToolCallContent, ToolCallLocation, ToolCallUpdate,
+ ToolKind,
+};
+use macro_tools::MacroTool;
+use serde::Deserialize;
+use serde::de::DeserializeOwned;
+use serde_json::Value;
+
+/// One tool frame, as a harness reads it: everything a `tool_call` or a
+/// `tool_call_update` carries, borrowed.
+///
+/// A `tool_call` fills every field it has; an update fills only what it
+/// patches, so every field is optional and a reader treats an absent one as
+/// "not on this frame". Readers take this whole rather than a hand-picked
+/// subset of it, so a harness that answers a question from a field no other
+/// harness uses needs no change to the trait.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct ToolFrame<'frame> {
+ /// ACP's implementation-defined `_meta`.
+ pub meta: Option<&'frame Meta>,
+ /// The human-readable title.
+ pub title: Option<&'frame str>,
+ /// ACP's coarse kind.
+ pub kind: Option<ToolKind>,
+ /// How far the call has got. On an update, the status the call is in
+ /// once the update is applied - the update's own when it carries one,
+ /// else the status held before it (see [`Self::with_status`]).
+ pub status: Option<ToolStatus>,
+ /// The tool's arguments, in the harness's shape.
+ pub raw_input: Option<&'frame Value>,
+ /// The tool's result, in the harness's shape.
+ pub raw_output: Option<&'frame Value>,
+ /// The typed content blocks.
+ pub content: Option<&'frame [ToolCallContent]>,
+ /// The paths the call touched.
+ pub locations: Option<&'frame [ToolCallLocation]>,
+}
+
+impl<'frame> ToolFrame<'frame> {
+ /// The view of an opening `tool_call`.
+ #[must_use]
+ pub fn of_call(call: &'frame ToolCall) -> Self {
+ Self {
+ meta: call.meta.as_ref(),
+ title: Some(&call.title),
+ kind: Some(call.kind),
+ status: Some(call.status.into()),
+ raw_input: call.raw_input.as_ref(),
+ raw_output: call.raw_output.as_ref(),
+ content: Some(&call.content),
+ locations: Some(&call.locations),
+ }
+ }
+
+ /// The view of a `tool_call_update`: only what it carries.
+ #[must_use]
+ pub fn of_update(update: &'frame ToolCallUpdate) -> Self {
+ let fields = &update.fields;
+ Self {
+ meta: update.meta.as_ref(),
+ title: fields.title.as_deref(),
+ kind: fields.kind,
+ status: fields.status.map(Into::into),
+ raw_input: fields.raw_input.as_ref(),
+ raw_output: fields.raw_output.as_ref(),
+ content: fields.content.as_deref(),
+ locations: fields.locations.as_deref(),
+ }
+ }
+
+ /// The same frame with the status the call is in once it is applied,
+ /// for an update that carried none of its own.
+ #[must_use]
+ pub fn with_status(self, status: ToolStatus) -> Self {
+ Self {
+ status: Some(status),
+ ..self
+ }
+ }
+
+ /// Whether the call is over, as far as this frame says.
+ #[must_use]
+ pub fn finished(&self) -> bool {
+ self.status.is_some_and(ToolStatus::is_finished)
+ }
+
+ /// The text among the content blocks - e.g. search matches or a fetched
+ /// page's text - joined in order. `None` when no block carries text,
+ /// same as an empty result: nothing useful distinguishes "reported
+ /// nothing" from "reported an empty string".
+ #[must_use]
+ pub fn content_text(&self) -> Option<String> {
+ let text = self
+ .content?
+ .iter()
+ .filter_map(|block| match block {
+ ToolCallContent::Content(Content {
+ content: ContentBlock::Text(text),
+ ..
+ }) => Some(text.text.as_str()),
+ _ => None,
+ })
+ .collect::<String>();
+ (!text.is_empty()).then_some(text)
+ }
+}
+
+/// What a harness's conventions let the fold read off a tool frame, and how
+/// the fold tells which harness it is reading.
+///
+/// Every method has a default a harness can leave alone. Defaults are the
+/// neutral readings in [`generic`], never `None`-for-everything: a frame
+/// from an unrecognized harness still folds to the same vocabulary as one
+/// from a known harness, only with less filled in.
+pub trait HarnessReader: Sync {
+ /// Whether `name` - the `agentInfo.name` an `initialize` response
+ /// announced - is this harness. Matching should be loose: a harness's
+ /// package name, title and version format all change more often than
+ /// the word that identifies it.
+ fn announces(&self, name: &str) -> bool {
+ let _ = name;
+ false
+ }
+
+ /// Whether this harness wrote `frame` - for a log with no `initialize`
+ /// to read (a resumed session, a recording that starts mid-turn). Only a
+ /// harness that leaves something distinctive on its tool frames, like a
+ /// `_meta` namespace of its own, can say yes.
+ fn wrote(&self, frame: &ToolFrame<'_>) -> bool {
+ let _ = frame;
+ false
+ }
+
+ /// The tool's own name, when the harness reported one beyond the bare
+ /// ACP title - in `_meta`, or by a naming convention in the title.
+ ///
+ /// Outranks the plain title, which is human-readable copy and may change
+ /// over a call's life. `None` means the title is all there is. Returns a
+ /// [`ToolName`] rather than a string because splitting an MCP tool's
+ /// server from its name is itself a harness convention.
+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {
+ let _ = frame;
+ None
+ }
+
+ /// Terminal output accumulated so far.
+ fn terminal_output(&self, frame: &ToolFrame<'_>) -> Option<String> {
+ generic::terminal_output(frame)
+ }
+
+ /// The exit code a terminal-backed call finished with.
+ fn terminal_exit_code(&self, frame: &ToolFrame<'_>) -> Option<i32> {
+ generic::terminal_exit_code(frame)
+ }
+
+ /// The Macro tool `name` refers to, if it is one of Macro's.
+ ///
+ /// For most harnesses that means a tool reached over Macro's own MCP
+ /// server; Macro's in-process agent calls the same tools natively and
+ /// says so by being the harness it is.
+ fn macro_tool<'name>(&self, name: &'name ToolName) -> Option<&'name str> {
+ macro_tools::mcp_tool(name)
+ }
+
+ /// An external tool's own result, out of whatever this harness wrapped it
+ /// in when it wrote `rawOutput`, plus the error text when the wrapper
+ /// reported failure. The neutral reading is MCP's envelope.
+ fn unwrap_tool_output(&self, raw: &Value) -> (Value, Option<String>) {
+ mcp::unwrap_call_result(raw)
+ }
+
+ /// Whether a call, as its opening frame describes it, delegates work to
+ /// another agent.
+ ///
+ /// Decided at open and never revisited, so a subagent never changes
+ /// shape mid-flight. The neutral rule is the Claude Code "Task tool"
+ /// convention that OpenCode and Cursor copied: a tool called `task` or
+ /// `agent` whose kind is `think` or `other`.
+ fn is_subagent(&self, name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ generic::is_subagent(name, frame)
+ }
+
+ /// The subagent call this frame's call belongs to, when the harness
+ /// attributes calls to a parent. Only Claude Code does today.
+ fn parent_tool_call(&self, frame: &ToolFrame<'_>) -> Option<ToolUseId> {
+ let _ = frame;
+ None
+ }
+
+ /// What a subagent was asked.
+ fn subagent_input(&self, frame: &ToolFrame<'_>) -> SubagentInput {
+ generic::subagent_input(frame)
+ }
+
+ /// What a subagent reported on this frame, wherever the harness puts it.
+ /// `None` when the frame carries no result at all.
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ generic::subagent_result(frame)
+ }
+
+ /// The subagent's own activity, when the harness reports it wholesale in
+ /// the call's result rather than streaming the child's frames and
+ /// attributing them to the parent (see [`Self::parent_tool_call`]).
+ /// Only Cursor does today. Empty means the frame carries none; a
+ /// non-empty transcript replaces whatever children the call held.
+ fn subagent_transcript(&self, frame: &ToolFrame<'_>) -> Vec<MessagePart> {
+ let _ = frame;
+ Vec::new()
+ }
+}
+
+/// What a subagent was asked, as one frame reports it. Every field is
+/// optional because the input arrives in pieces - Claude Code streams the
+/// arguments over several patches - and a patch only says what it carries.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct SubagentInput {
+ /// Which kind of agent was delegated to.
+ pub agent_type: Option<String>,
+ /// A short description of the task.
+ pub description: Option<String>,
+ /// The brief.
+ pub prompt: Option<String>,
+ /// Whether the subagent runs in the background.
+ pub background: Option<bool>,
+}
+
+impl Harness {
+ /// Recognize a harness from the `agentInfo.name` it announced in its
+ /// `initialize` response: the first known harness that claims the name.
+ #[must_use]
+ pub fn from_agent_info(name: &str) -> Self {
+ Self::KNOWN
+ .iter()
+ .copied()
+ .find(|harness| harness.reader().announces(name))
+ .unwrap_or(Self::Unknown)
+ }
+
+ /// Recognize a harness from a tool frame, for a log with no `initialize`
+ /// to read. `None` when no known harness claims the frame.
+ #[must_use]
+ pub fn sniff(frame: &ToolFrame<'_>) -> Option<Self> {
+ Self::KNOWN
+ .iter()
+ .copied()
+ .find(|harness| harness.reader().wrote(frame))
+ }
+
+ /// Every harness with a reader of its own, in the order recognition
+ /// tries them.
+ const KNOWN: &'static [Self] = &[
+ Self::ClaudeCode,
+ Self::Macro,
+ Self::Codex,
+ Self::OpenCode,
+ Self::Cursor,
+ Self::Hermes,
+ Self::OpenClaw,
+ ];
+
+ /// How to read this harness's frames.
+ #[must_use]
+ pub fn reader(self) -> &'static dyn HarnessReader {
+ match self {
+ Self::ClaudeCode => &claude_code::ClaudeCode,
+ Self::Macro => &macro_inmem::MacroInmem,
+ Self::OpenCode => &opencode::OpenCode,
+ Self::Codex => &codex::Codex,
+ Self::Cursor => &cursor::Cursor,
+ Self::Hermes => &hermes::Hermes,
+ Self::OpenClaw => &openclaw::OpenClaw,
+ Self::Unknown => &generic::Generic,
+ }
+ }
+}
+
+/// The name of the tool behind a frame: the harness's own name when it
+/// reported one, else the ACP title, else empty - a name a later patch may
+/// fill.
+#[must_use]
+pub fn tool_name(reader: &dyn HarnessReader, frame: &ToolFrame<'_>) -> ToolName {
+ reader.reported_tool_name(frame).unwrap_or_else(|| {
+ frame
+ .title
+ .unwrap_or_default()
+ .parse()
+ .unwrap_or_else(|never| match never {})
+ })
+}
+
+/// Whose shape a tool call is in, and so how the fold reads it.
+///
+/// Decided once, from the opening frame, and never revisited: the detail a
+/// call opens with is the detail it keeps, so a subagent never turns into a
+/// Macro tool mid-flight or the other way round.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ToolShape<'name> {
+ /// One of the harness's own tools, read by its ACP kind: `Bash`, `Read`,
+ /// `Write`, or a tool from an MCP server the fold knows nothing about.
+ Harness,
+ /// A Macro tool, by the name Macro gives it. Its input and output are the
+ /// tool's own JSON once the harness's wrapper is off.
+ Macro(&'name str),
+ /// A Macro user tool, by name: the agent drafts it, the user finishes it.
+ UserTool(&'name str),
+ /// Work delegated to another agent - the harness's own delegation tool
+ /// (Claude Code's `Agent`, Cursor's `task`) or Macro's `Subagent`. Which
+ /// of the two it is stays out of the fold's way: [`subagent_result`]
+ /// reads either by the tool's name.
+ Subagent,
+}
+
+/// Classify a tool call from its opening frame.
+///
+/// Macro's tools are recognized by name before anything else, since the
+/// kind ACP gives them is `other` and says nothing; among them, `Subagent`
+/// is a delegation like the harness's own. Everything else is the harness's,
+/// and whether it delegates is the reader's call.
+#[must_use]
+pub fn tool_shape<'name>(
+ reader: &dyn HarnessReader,
+ name: &'name ToolName,
+ frame: &ToolFrame<'_>,
+) -> ToolShape<'name> {
+ match reader.macro_tool(name).map(MacroTool::of) {
+ Some(MacroTool::User(tool)) => ToolShape::UserTool(tool),
+ Some(MacroTool::Subagent) => ToolShape::Subagent,
+ Some(MacroTool::Other(tool)) => ToolShape::Macro(tool),
+ None if reader.is_subagent(name, frame) => ToolShape::Subagent,
+ None => ToolShape::Harness,
+ }
+}
+
+/// What a subagent reported on one frame, read in whichever shape the
+/// delegation tool named by `name` answers in: Macro's `Subagent` returns
+/// Macro's response inside the harness's wrapper, whoever the harness is;
+/// any other delegation tool is the harness's own, and its reader knows it.
+/// `None` when the frame carries no result.
+#[must_use]
+pub fn subagent_result(
+ reader: &dyn HarnessReader,
+ name: &ToolName,
+ frame: &ToolFrame<'_>,
+) -> Option<SubagentResult> {
+ if reader.macro_tool(name).map(MacroTool::of) == Some(MacroTool::Subagent) {
+ let (value, error) = reader.unwrap_tool_output(frame.raw_output?);
+ return macro_tools::subagent_result(&value, error);
+ }
+ reader.subagent_result(frame)
+}
+
+/// Where a Macro user tool got to, from a frame's `rawOutput`: the harness's
+/// wrapper reporting failure is [`UserToolOutcome::Failed`]; otherwise the
+/// response inside it says.
+#[must_use]
+pub fn user_tool_outcome(
+ reader: &dyn HarnessReader,
+ tool: &str,
+ raw_output: &Value,
+) -> UserToolOutcome {
+ match reader.unwrap_tool_output(raw_output) {
+ (_, Some(error)) => UserToolOutcome::Failed { message: error },
+ (value, None) => macro_tools::user_tool_outcome(tool, &value),
+ }
+}
+
+/// The object at `_meta.<namespace>`, read as `T`.
+///
+/// The shape every namespaced harness shares: its keys live under one
+/// top-level object named for the harness. `None` when the key is absent,
+/// not an object, or does not deserialize - all "no information".
+#[must_use]
+pub(crate) fn namespaced<T: DeserializeOwned>(meta: Option<&Meta>, namespace: &str) -> Option<T> {
+ let value = meta?.get(namespace)?;
+ value
+ .is_object()
+ .then(|| serde_json::from_value(value.clone()).ok())
+ .flatten()
+}
+
+/// Whether `_meta` has a key called `namespace` at all - how a harness that
+/// writes one recognizes its own frames.
+#[must_use]
+pub(crate) fn has_namespace(meta: Option<&Meta>, namespace: &str) -> bool {
+ meta.is_some_and(|meta| meta.contains_key(namespace))
+}
+
+/// `raw_input` or `raw_output`, read as `T`. `None` when absent or not that
+/// shape.
+#[must_use]
+pub(crate) fn raw<T: DeserializeOwned>(value: Option<&Value>) -> Option<T> {
+ serde_json::from_value(value?.clone()).ok()
+}
+
+/// The command line behind an `execute` tool call.
+///
+/// This one reads ACP's own `rawInput` rather than `_meta`, but lives here
+/// because the key it looks for (`command`) is a harness convention that ACP
+/// does not specify.
+#[must_use]
+pub fn command_from_raw_input(raw_input: Option<&Value>) -> Option<String> {
+ #[derive(Deserialize)]
+ struct Input {
+ command: Option<String>,
+ }
+ raw::<Input>(raw_input)?.command
+}
+
+/// The whole-file edit an edit tool's raw input describes, as
+/// `(path, new contents)`.
+///
+/// Claude Code's `Write` (and whole-file `Edit`) calls carry
+/// `{"filePath", "content"}` in `rawInput` and never report an ACP diff
+/// content block, so this is the only material a fold has for their diff. The
+/// prior contents are not on the wire at all — a reader treats the file as
+/// new.
+#[must_use]
+pub fn file_edit_from_raw_input(raw_input: Option<&Value>) -> Option<(String, String)> {
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct Input {
+ file_path: String,
+ content: String,
+ }
+ let input: Input = raw(raw_input)?;
+ Some((input.file_path, input.content))
+}
diff --git a/crates/agent_fold/src/domain/harness/claude_code.rs b/crates/agent_fold/src/domain/harness/claude_code.rs
new file mode 100644
index 0000000000..e64e6d3151
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/claude_code.rs
@@ -0,0 +1,178 @@
+//! The Claude Code harness, `@agentclientprotocol/claude-agent-acp`.
+//!
+//! Writes its own keys under `_meta.claudeCode`, read as [`ClaudeCodeMeta`]:
+//!
+//! - `toolName` - the harness's name for the tool (`Bash`, `Read`, `Write`,
+//! or `mcp__<server>__<tool>` for an MCP tool).
+//! - `subagent: true` - on the `Agent` tool call that delegates work.
+//! - `parentToolUseId` - on a call the subagent made, naming the `Agent`
+//! call it belongs to. Present on the opening frame; not on every patch.
+//! - `toolResponse` - the tool's own result object, richer than the text
+//! blocks `rawOutput` later carries. For `Agent` it is an
+//! [`AgentResponse`]: the subagent's answer, id, model, timings, token
+//! count and per-tool statistics.
+
+use agent_client_protocol::schema::v1::{ContentBlock, Meta};
+use lazy_regex::regex_is_match;
+use serde::Deserialize;
+use serde_json::Value;
+
+use super::{HarnessReader, ToolFrame, generic, has_namespace, namespaced, raw};
+use crate::domain::model::{SubagentResult, ToolName, ToolStats, ToolUseId};
+
+/// The `_meta` namespace Claude Code writes under.
+pub const NAMESPACE: &str = "claudeCode";
+
+/// Reader for Claude Code's conventions.
+pub struct ClaudeCode;
+
+/// `_meta.claudeCode`, as far as the fold reads it.
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ClaudeCodeMeta {
+ tool_name: Option<String>,
+ #[serde(default)]
+ subagent: bool,
+ parent_tool_use_id: Option<String>,
+ tool_response: Option<Value>,
+}
+
+fn meta_of(meta: Option<&Meta>) -> ClaudeCodeMeta {
+ namespaced(meta, NAMESPACE).unwrap_or_default()
+}
+
+/// The `Agent` tool's `toolResponse`.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AgentResponse {
+ status: Option<String>,
+ error: Option<String>,
+ #[serde(default)]
+ content: Vec<ContentBlock>,
+ agent_id: Option<String>,
+ resolved_model: Option<String>,
+ total_duration_ms: Option<u32>,
+ total_tokens: Option<u32>,
+ total_tool_use_count: Option<u32>,
+ tool_stats: Option<AgentToolStats>,
+}
+
+/// The `Agent` tool's `toolStats`, in Claude Code's names.
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AgentToolStats {
+ #[serde(default)]
+ read_count: u32,
+ #[serde(default)]
+ search_count: u32,
+ #[serde(default)]
+ bash_count: u32,
+ #[serde(default)]
+ edit_file_count: u32,
+ #[serde(default)]
+ lines_added: u32,
+ #[serde(default)]
+ lines_removed: u32,
+ #[serde(default)]
+ other_tool_count: u32,
+}
+
+impl From<AgentToolStats> for ToolStats {
+ fn from(stats: AgentToolStats) -> Self {
+ Self {
+ reads: stats.read_count,
+ searches: stats.search_count,
+ commands: stats.bash_count,
+ edits: stats.edit_file_count,
+ lines_added: stats.lines_added,
+ lines_removed: stats.lines_removed,
+ other: stats.other_tool_count,
+ }
+ }
+}
+
+impl From<AgentResponse> for SubagentResult {
+ fn from(response: AgentResponse) -> Self {
+ let text = response
+ .content
+ .iter()
+ .filter_map(|block| match block {
+ ContentBlock::Text(text) => Some(text.text.as_str()),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ let failed = response.status.as_deref() == Some("failed");
+ Self {
+ text: (!text.is_empty()).then_some(text),
+ error: failed.then(|| {
+ response
+ .error
+ .unwrap_or_else(|| "subagent failed".to_owned())
+ }),
+ agent_id: response.agent_id,
+ model: response.resolved_model,
+ duration_ms: response.total_duration_ms,
+ tokens: response.total_tokens,
+ tool_uses: response.total_tool_use_count,
+ stats: response.tool_stats.map(ToolStats::from),
+ }
+ }
+}
+
+impl HarnessReader for ClaudeCode {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)claude", name)
+ }
+
+ fn wrote(&self, frame: &ToolFrame<'_>) -> bool {
+ has_namespace(frame.meta, NAMESPACE)
+ }
+
+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {
+ tool_name(frame.meta).map(|name| name.parse().unwrap_or_else(|never| match never {}))
+ }
+
+ fn is_subagent(&self, name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ meta_of(frame.meta).subagent || generic::is_subagent(name, frame)
+ }
+
+ fn parent_tool_call(&self, frame: &ToolFrame<'_>) -> Option<ToolUseId> {
+ meta_of(frame.meta).parent_tool_use_id.map(ToolUseId)
+ }
+
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ if let Some(response) = meta_of(frame.meta).tool_response {
+ // The response object is what the harness says about the run;
+ // one that does not read as an `AgentResponse` still says nothing
+ // the generic path would not.
+ if let Ok(response) = serde_json::from_value::<AgentResponse>(response) {
+ return Some(response.into());
+ }
+ }
+ // The final frame copies the answer into `rawOutput` as content
+ // blocks, the second of which is an "agentId: ... <usage>" boilerplate
+ // the response object already said better. Keep the first.
+ let first_text = raw::<Vec<ContentBlock>>(frame.raw_output).and_then(|blocks| {
+ blocks.into_iter().find_map(|block| match block {
+ ContentBlock::Text(text) => Some(text.text),
+ _ => None,
+ })
+ });
+ match first_text {
+ Some(text) => Some(SubagentResult {
+ text: Some(text),
+ ..SubagentResult::default()
+ }),
+ None => generic::subagent_result(frame),
+ }
+ }
+}
+
+/// The harness's own name for the tool behind a `tool_call`, verbatim.
+///
+/// Reads `_meta.claudeCode.toolName`.
+#[must_use]
+pub fn tool_name(meta: Option<&Meta>) -> Option<String> {
+ meta_of(meta).tool_name
+}
diff --git a/crates/agent_fold/src/domain/harness/codex.rs b/crates/agent_fold/src/domain/harness/codex.rs
new file mode 100644
index 0000000000..6a11a8143d
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/codex.rs
@@ -0,0 +1,132 @@
+//! OpenAI Codex through the `@agentclientprotocol/codex-acp` adapter
+//! (`agentInfo.name = "@agentclientprotocol/codex-acp"`; the deprecated Rust
+//! adapter announced `codex-acp` and emitted nothing for subagents).
+//!
+//! Writes its own keys under `_meta.codex` ([`CodexMeta`]), and two flat flags:
+//!
+//! - `_meta.is_mcp_tool_call: true` with the title `mcp.<server>.<tool>` -
+//! how it names an MCP tool, where Claude Code uses `mcp__<server>__<tool>`.
+//! - `_meta.codex.collaboration = { tool, senderThreadId, receiverThreadIds }`
+//! on the collaboration tools. `tool: "spawnAgent"` is the delegation; the
+//! others (`sendInput`, `wait`, `closeAgent`, …) steer an existing one.
+//!
+//! A `spawnAgent` call is `kind: other`, titled `spawnAgent` for its whole
+//! life, and carries its state in `rawInput` ([`SpawnAgentInput`]) - there is
+//! no `rawOutput`. The child's own activity is not streamed into the parent
+//! session by this (legacy) mode; the adapter's native-subagent mode uses
+//! `sessionUpdate` variants ACP has not standardized, which this fold does
+//! not read yet.
+
+use std::collections::BTreeMap;
+
+use agent_client_protocol::schema::v1::Meta;
+use lazy_regex::{regex_captures, regex_is_match};
+use serde::Deserialize;
+use serde_json::Value;
+
+use super::{HarnessReader, SubagentInput, ToolFrame, generic, has_namespace, namespaced, raw};
+use crate::domain::model::{SubagentResult, ToolName};
+
+/// The `_meta` namespace codex-acp writes under.
+pub const NAMESPACE: &str = "codex";
+
+/// Reader for codex-acp's conventions.
+pub struct Codex;
+
+/// `_meta.codex`, as far as the fold reads it.
+#[derive(Debug, Default, Deserialize)]
+struct CodexMeta {
+ collaboration: Option<Collaboration>,
+}
+
+#[derive(Debug, Deserialize)]
+struct Collaboration {
+ tool: String,
+}
+
+/// `_meta` flags codex-acp writes at the top level.
+#[derive(Debug, Default, Deserialize)]
+struct CodexFlags {
+ #[serde(default)]
+ is_mcp_tool_call: bool,
+}
+
+/// `spawnAgent`'s `rawInput`, which is also where its result lives.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SpawnAgentInput {
+ prompt: Option<String>,
+ #[serde(default)]
+ receiver_thread_ids: Vec<String>,
+ #[serde(default)]
+ agents_states: BTreeMap<String, AgentState>,
+ model: Option<String>,
+ status: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct AgentState {
+ message: Option<String>,
+}
+
+fn flags_of(meta: Option<&Meta>) -> CodexFlags {
+ meta.and_then(|meta| serde_json::from_value(Value::Object(meta.clone())).ok())
+ .unwrap_or_default()
+}
+
+impl HarnessReader for Codex {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)codex", name)
+ }
+
+ /// Either of its `_meta` signals: the namespace, or the flat MCP flag it
+ /// writes on MCP calls whether or not the namespace is present.
+ fn wrote(&self, frame: &ToolFrame<'_>) -> bool {
+ has_namespace(frame.meta, NAMESPACE) || flags_of(frame.meta).is_mcp_tool_call
+ }
+
+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {
+ if !flags_of(frame.meta).is_mcp_tool_call {
+ return None;
+ }
+ regex_captures!(r"^mcp\.([^.]+)\.(.+)$", frame.title?).map(|(_, server, tool)| {
+ ToolName::Mcp {
+ server: server.to_owned(),
+ tool: tool.to_owned(),
+ }
+ })
+ }
+
+ fn is_subagent(&self, _name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ namespaced::<CodexMeta>(frame.meta, NAMESPACE)
+ .and_then(|meta| meta.collaboration)
+ .is_some_and(|collaboration| collaboration.tool == "spawnAgent")
+ }
+
+ fn subagent_input(&self, frame: &ToolFrame<'_>) -> SubagentInput {
+ SubagentInput {
+ prompt: raw::<SpawnAgentInput>(frame.raw_input).and_then(|input| input.prompt),
+ ..SubagentInput::default()
+ }
+ }
+
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ let Some(input) = raw::<SpawnAgentInput>(frame.raw_input) else {
+ return generic::subagent_result(frame);
+ };
+ let child = input.receiver_thread_ids.first().cloned();
+ let message = child
+ .as_ref()
+ .and_then(|child| input.agents_states.get(child))
+ .and_then(|state| state.message.clone());
+ let failed = input.status.as_deref() == Some("failed");
+ let result = SubagentResult {
+ text: if failed { None } else { message.clone() },
+ error: failed.then(|| message.unwrap_or_else(|| "subagent failed".to_owned())),
+ agent_id: child,
+ model: input.model.filter(|model| !model.is_empty()),
+ ..SubagentResult::default()
+ };
+ (!result.is_empty()).then_some(result)
+ }
+}
diff --git a/crates/agent_fold/src/domain/harness/cursor.rs b/crates/agent_fold/src/domain/harness/cursor.rs
new file mode 100644
index 0000000000..41e6b253e6
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/cursor.rs
@@ -0,0 +1,622 @@
+//! Cursor cloud agents, through this repository's `cursor_cloud_agents`
+//! translator (`agentInfo.name = "cursor-acp"`).
+//!
+//! The translator writes no `_meta`. Cursor's subagent tool is `task`, kind
+//! `other`, with the Task-tool arguments in Cursor's own spelling:
+//!
+//! ```json
+//! { "description": "…", "prompt": "…", "subagentType": { "explore": {} },
+//! "model": "composer-2.5-fast", "agentId": "bc-…" }
+//! ```
+//!
+//! `subagentType` is a proto-oneof: sometimes `{ "explore": {} }`, sometimes
+//! `{ "kind": "explore" }` or `{ "kind": "custom", "name": "…" }`, and
+//! `{ "unspecified": {} }` (with `"model": "default"`) when the agent left
+//! both to Cursor - proto defaults, not information.
+//!
+//! The child's activity is never streamed as frames of its own. Instead the
+//! finished call carries the child's whole transcript, wrapped by the
+//! translator under `rawOutput.result`:
+//!
+//! ```json
+//! { "result": { "success": {
+//! "agentId": "bc-…", "durationMs": "12978",
+//! "conversationSteps": [
+//! { "thinkingMessage": { "text": "…", "durationMs": 1168 } },
+//! { "assistantMessage": { "text": "…" } },
+//! { "toolCall": { "toolCallId": "call_…\nfc_…",
+//! "shellToolCall": { "args": { "command": "…" },
+//! "result": { "success": { "stdout": "…" },
+//! "isBackground": false } } } },
+//! { "assistantMessage": { "text": "the answer" } }
+//! ] } } }
+//! ```
+//!
+//! or `{ "result": { "error": … } }`. Numbers Cursor declares as 64-bit
+//! arrive as JSON strings, proto's encoding for them. The reader folds the
+//! steps into the subagent's children and takes the closing prose as its
+//! answer, so the transcript reads like the child had streamed.
+//!
+//! Every shape is a serde type below and read by deserializing, never by
+//! walking `Value`s. A field the types do not name is ignored; a frame they
+//! cannot read is "no information", same as every reader. Proto oneofs are
+//! enums keyed by their variant, and proto envelopes that may carry a flag
+//! beside the payload (`isBackground`) are structs of optionals.
+
+use std::collections::BTreeMap;
+
+use lazy_regex::regex_is_match;
+use serde::Deserialize;
+use serde::de::IgnoredAny;
+use serde_json::Value;
+
+use super::{HarnessReader, SubagentInput, ToolFrame, generic, raw};
+use crate::domain::model::{
+ AnsiText, FileDiff, MessagePart, SubagentResult, ToolDetail, ToolName, ToolStatus, ToolUseId,
+};
+
+/// Reader for Cursor's conventions.
+pub struct Cursor;
+
+impl HarnessReader for Cursor {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)cursor", name)
+ }
+
+ fn subagent_input(&self, frame: &ToolFrame<'_>) -> SubagentInput {
+ let mut input = generic::subagent_input(frame);
+ if input.agent_type.is_none() {
+ input.agent_type = TaskArguments::read(frame.raw_input)
+ .and_then(|arguments| arguments.subagent_type)
+ .and_then(SubagentType::name);
+ }
+ input
+ }
+
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ let mut result = match TaskOutput::read(frame.raw_output) {
+ Some(output) => output.result.into_subagent_result(),
+ None => generic::subagent_result(frame).unwrap_or_default(),
+ };
+ if let Some(arguments) = TaskArguments::read(frame.raw_input) {
+ result.agent_id = arguments.agent_id.or(result.agent_id);
+ result.model = arguments.model.or(result.model);
+ }
+ (!result.is_empty()).then_some(result)
+ }
+
+ fn subagent_transcript(&self, frame: &ToolFrame<'_>) -> Vec<MessagePart> {
+ TaskOutput::read(frame.raw_output)
+ .and_then(|output| output.result.success)
+ .map(Transcript::into_parts)
+ .unwrap_or_default()
+ }
+}
+
+/// A string that says something, else `None`. Cursor writes `""` for a field
+/// it has nothing for, and `"default"` for a model it chose itself.
+fn informative(text: Option<String>) -> Option<String> {
+ text.filter(|text| !text.is_empty() && text != "default")
+}
+
+/// A count Cursor may encode as a number or, for its 64-bit fields, a
+/// string. Saturates rather than drops a count past `u32`: the browser
+/// contract forbids 64-bit integers, and a clamped 49 days beats a vanished
+/// duration.
+fn lenient_u32<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<u32>, D::Error> {
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum Count {
+ Number(u64),
+ Text(String),
+ Other(IgnoredAny),
+ }
+ let saturate = |count: u64| u32::try_from(count).unwrap_or(u32::MAX);
+ Ok(match Option::<Count>::deserialize(deserializer)? {
+ Some(Count::Number(count)) => Some(saturate(count)),
+ Some(Count::Text(text)) => text.parse().ok().map(saturate),
+ Some(Count::Other(_)) | None => None,
+ })
+}
+
+/// Cursor call ids embed a literal newline (`call_…\nfc_…`); the translator
+/// collapses it for top-level ids, and nested ids get the same treatment.
+fn collapse_whitespace(id: &str) -> String {
+ id.split_whitespace().collect::<Vec<_>>().join(" ")
+}
+
+// --- The `task` call's arguments ---
+
+/// The `task` tool's arguments, as far as this reader wants them. The
+/// Task-tool fields (`description`, `prompt`) are read by [`generic`].
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TaskArguments {
+ subagent_type: Option<SubagentType>,
+ #[serde(default)]
+ model: Option<String>,
+ #[serde(default)]
+ agent_id: Option<String>,
+}
+
+impl TaskArguments {
+ fn read(raw_input: Option<&Value>) -> Option<Self> {
+ let mut arguments: Self = raw(raw_input)?;
+ arguments.model = informative(arguments.model);
+ arguments.agent_id = informative(arguments.agent_id);
+ Some(arguments)
+ }
+}
+
+/// Cursor's `subagentType` oneof, in each spelling it has been seen in.
+#[derive(Deserialize)]
+#[serde(untagged)]
+enum SubagentType {
+ /// `{ "kind": "explore" }` or `{ "kind": "custom", "name": "reviewer" }`.
+ Kinded {
+ kind: String,
+ #[serde(default)]
+ name: Option<String>,
+ },
+ /// `{ "explore": {} }` - the variant is the key.
+ Keyed(BTreeMap<String, IgnoredAny>),
+}
+
+impl SubagentType {
+ /// The agent type's name; `None` for the proto default `unspecified`.
+ fn name(self) -> Option<String> {
+ let name = match self {
+ Self::Kinded { kind, name } => name.unwrap_or(kind),
+ Self::Keyed(variants) => variants.into_keys().next()?,
+ };
+ (name != "unspecified").then_some(name)
+ }
+}
+
+// --- The `task` call's result ---
+
+/// `rawOutput` of a finished `task` call: Cursor's result under the
+/// translator's `result` key.
+#[derive(Deserialize)]
+struct TaskOutput {
+ result: Envelope<Transcript>,
+}
+
+impl TaskOutput {
+ /// `None` for a `rawOutput` that is not a `task` result at all - one
+ /// with neither `success` nor `error` under `result`.
+ fn read(raw_output: Option<&Value>) -> Option<Self> {
+ let output: Self = raw(raw_output)?;
+ output.result.is_reported().then_some(output)
+ }
+}
+
+/// Cursor's result envelope, shared by the `task` call and every call the
+/// child made: `success` with the payload, or `error` (`failure` for the
+/// shell tool), and sometimes a flag beside them (`isBackground`) - hence a
+/// struct of optionals rather than a one-key enum.
+#[derive(Deserialize)]
+struct Envelope<Payload> {
+ success: Option<Payload>,
+ failure: Option<Payload>,
+ error: Option<Value>,
+}
+
+/// By hand rather than derived: the derive would demand `Payload: Default`,
+/// and an empty envelope needs no payload.
+impl<Payload> Default for Envelope<Payload> {
+ fn default() -> Self {
+ Self {
+ success: None,
+ failure: None,
+ error: None,
+ }
+ }
+}
+
+impl<Payload> Envelope<Payload> {
+ fn is_reported(&self) -> bool {
+ self.success.is_some() || self.failure.is_some() || self.error.is_some()
+ }
+
+ fn status(&self) -> ToolStatus {
+ if self.success.is_some() {
+ ToolStatus::Completed
+ } else if self.failure.is_some() || self.error.is_some() {
+ ToolStatus::Failed
+ } else {
+ // Nothing recorded: not evidence either way.
+ ToolStatus::Pending
+ }
+ }
+
+ /// Whichever payload was written, successful or not.
+ fn payload(&self) -> Option<&Payload> {
+ self.success.as_ref().or(self.failure.as_ref())
+ }
+
+ fn error_text(&self) -> Option<String> {
+ Some(match self.error.as_ref()? {
+ Value::String(text) => text.clone(),
+ other => other.to_string(),
+ })
+ }
+}
+
+impl Envelope<Transcript> {
+ fn into_subagent_result(self) -> SubagentResult {
+ if let Some(error) = self.error_text() {
+ return SubagentResult {
+ error: Some(error),
+ ..SubagentResult::default()
+ };
+ }
+ self.success
+ .or(self.failure)
+ .map(Transcript::into_subagent_result)
+ .unwrap_or_default()
+ }
+}
+
+/// What a finished child reports: who it was, how long it took, and every
+/// step it took.
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct Transcript {
+ #[serde(default)]
+ agent_id: Option<String>,
+ #[serde(default, deserialize_with = "lenient_u32")]
+ duration_ms: Option<u32>,
+ #[serde(default)]
+ conversation_steps: Vec<Step>,
+}
+
+impl Transcript {
+ /// The child's answer: its final step, when that is prose.
+ fn answer(&self) -> Option<&str> {
+ match self.conversation_steps.last()? {
+ Step::AssistantMessage(message) if !message.text.is_empty() => Some(&message.text),
+ _ => None,
+ }
+ }
+
+ fn into_subagent_result(self) -> SubagentResult {
+ SubagentResult {
+ text: self.answer().map(ToOwned::to_owned),
+ agent_id: informative(self.agent_id.clone()),
+ duration_ms: self.duration_ms,
+ tool_uses: u32::try_from(
+ self.conversation_steps
+ .iter()
+ .filter(|step| matches!(step, Step::ToolCall(_)))
+ .count(),
+ )
+ .ok(),
+ ..SubagentResult::default()
+ }
+ }
+
+ /// The child's work as parts: every step but the closing prose, which
+ /// is the answer and reported in the result instead.
+ fn into_parts(mut self) -> Vec<MessagePart> {
+ if self.answer().is_some() {
+ self.conversation_steps.pop();
+ }
+ self.conversation_steps
+ .into_iter()
+ .filter_map(Step::into_part)
+ .collect()
+ }
+}
+
+/// One step of the child's transcript: a proto oneof keyed by step kind.
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+enum Step {
+ ThinkingMessage(StepText),
+ AssistantMessage(StepText),
+ ToolCall(Box<ToolCallStep>),
+ /// A step kind this reader does not know; kept so one unknown step does
+ /// not fail the whole transcript.
+ #[serde(untagged)]
+ Unrecognized(IgnoredAny),
+}
+
+impl Step {
+ fn into_part(self) -> Option<MessagePart> {
+ match self {
+ Self::ThinkingMessage(StepText { text }) if !text.is_empty() => {
+ Some(MessagePart::Thought { text })
+ }
+ Self::AssistantMessage(StepText { text }) if !text.is_empty() => {
+ Some(MessagePart::Text { text })
+ }
+ Self::ToolCall(call) => Some(call.into_part()),
+ Self::ThinkingMessage(_) | Self::AssistantMessage(_) | Self::Unrecognized(_) => None,
+ }
+ }
+}
+
+#[derive(Deserialize)]
+struct StepText {
+ #[serde(default)]
+ text: String,
+}
+
+// --- The calls the child made ---
+
+/// A `toolCall` step: the call's id beside a descriptor oneof keyed by tool.
+/// A descriptor this reader knows is read typed; one it does not is kept by
+/// name alone, so a new Cursor tool still shows up as a call rather than
+/// vanishing from the transcript.
+#[derive(Deserialize)]
+#[serde(untagged)]
+enum ToolCallStep {
+ Known(Box<KnownToolCall>),
+ Unknown(UnknownToolCall),
+}
+
+impl ToolCallStep {
+ fn into_part(self) -> MessagePart {
+ match self {
+ Self::Known(call) => call.into_part(),
+ Self::Unknown(call) => call.into_part(),
+ }
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct KnownToolCall {
+ #[serde(default)]
+ tool_call_id: String,
+ #[serde(flatten)]
+ descriptor: Descriptor,
+}
+
+impl KnownToolCall {
+ fn into_part(self) -> MessagePart {
+ let (name, status, detail) = self.descriptor.into_detail();
+ MessagePart::ToolUse {
+ id: ToolUseId(collapse_whitespace(&self.tool_call_id)),
+ name: ToolName::native(name),
+ status,
+ detail,
+ }
+ }
+}
+
+/// Cursor's tool descriptor oneof. The variants mirror the typed
+/// descriptors the translator maps at top level (`kind_from_cursor_type`),
+/// so a nested call renders like the same call would there. Each holds the
+/// tool's own arguments and result payload.
+#[derive(Deserialize)]
+enum Descriptor {
+ #[serde(rename = "shellToolCall")]
+ Shell(ToolBody<ShellArguments, ShellOutcome>),
+ #[serde(rename = "readToolCall")]
+ Read(ToolBody<PathArguments, PathOutcome>),
+ #[serde(rename = "editToolCall")]
+ Edit(ToolBody<PathArguments, EditOutcome>),
+ #[serde(rename = "deleteToolCall")]
+ Delete(ToolBody<PathArguments, PathOutcome>),
+ #[serde(rename = "grepToolCall")]
+ Grep(ToolBody<PathArguments, PathOutcome>),
+ #[serde(rename = "globToolCall")]
+ Glob(ToolBody<PathArguments, PathOutcome>),
+ #[serde(rename = "updateTodosToolCall")]
+ UpdateTodos(ToolBody<Value, IgnoredAny>),
+ #[serde(rename = "taskToolCall")]
+ Task(ToolBody<Value, IgnoredAny>),
+ #[serde(rename = "mcpToolCall")]
+ Mcp(ToolBody<Value, IgnoredAny>),
+}
+
+impl Descriptor {
+ /// The tool's name in Cursor's own vocabulary (the descriptor key's
+ /// stem), how far it got, and what it did.
+ fn into_detail(self) -> (&'static str, ToolStatus, ToolDetail) {
+ match self {
+ Self::Shell(body) => {
+ let status = body.result.status();
+ let outcome = body.result.payload();
+ let detail = ToolDetail::Terminal {
+ command: body.args.and_then(|args| args.command),
+ output: outcome.and_then(ShellOutcome::output).map(AnsiText),
+ exit_code: match (&body.result.success, &body.result.failure) {
+ (Some(_), _) => Some(0),
+ (None, Some(failure)) => failure.exit_code,
+ (None, None) => None,
+ },
+ };
+ ("shell", status, detail)
+ }
+ Self::Read(body) => {
+ let (status, paths) = body.status_and_paths();
+ ("read", status, ToolDetail::Read { paths })
+ }
+ Self::Delete(body) => {
+ let (status, paths) = body.status_and_paths();
+ ("delete", status, ToolDetail::Delete { paths })
+ }
+ Self::Grep(body) => {
+ let (status, paths) = body.status_and_paths();
+ (
+ "grep",
+ status,
+ ToolDetail::Search {
+ paths,
+ output: None,
+ },
+ )
+ }
+ Self::Glob(body) => {
+ let (status, paths) = body.status_and_paths();
+ (
+ "glob",
+ status,
+ ToolDetail::Search {
+ paths,
+ output: None,
+ },
+ )
+ }
+ Self::Edit(body) => {
+ let status = body.result.status();
+ let diffs = body
+ .result
+ .success
+ .and_then(EditOutcome::into_diff)
+ .into_iter()
+ .collect();
+ ("edit", status, ToolDetail::Edit { diffs })
+ }
+ Self::UpdateTodos(body) => (
+ "updateTodos",
+ body.result.status(),
+ ToolDetail::Think { output: None },
+ ),
+ Self::Task(body) => ("task", body.result.status(), body.into_other()),
+ Self::Mcp(body) => ("mcp", body.result.status(), body.into_other()),
+ }
+ }
+}
+
+/// A descriptor's body: what the child asked for and what it got.
+#[derive(Deserialize)]
+// Spelled out because the derive would otherwise infer `Default` bounds on
+// both parameters from the `default` below, which the payload types lack.
+#[serde(bound(deserialize = "Arguments: Deserialize<'de>, Outcome: Deserialize<'de>"))]
+struct ToolBody<Arguments, Outcome> {
+ args: Option<Arguments>,
+ #[serde(default)]
+ result: Envelope<Outcome>,
+}
+
+impl<Arguments, Outcome> ToolBody<Arguments, Outcome> {
+ fn status(&self) -> ToolStatus {
+ self.result.status()
+ }
+}
+
+impl<Outcome> ToolBody<Value, Outcome> {
+ /// A tool with no rendering of its own: its arguments, verbatim.
+ fn into_other(self) -> ToolDetail {
+ ToolDetail::Other {
+ kind: "other".to_owned(),
+ output: None,
+ input: self.args,
+ }
+ }
+}
+
+impl ToolBody<PathArguments, PathOutcome> {
+ /// The path the call touched - from its result once finished, from its
+ /// arguments before.
+ fn status_and_paths(self) -> (ToolStatus, Vec<std::path::PathBuf>) {
+ let status = self.status();
+ let path = self
+ .result
+ .payload()
+ .and_then(|outcome| outcome.path.clone())
+ .or(self.args.and_then(|args| args.path));
+ (status, path.map(Into::into).into_iter().collect())
+ }
+}
+
+#[derive(Deserialize)]
+struct ShellArguments {
+ #[serde(default)]
+ command: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct ShellOutcome {
+ #[serde(default)]
+ stdout: Option<String>,
+ #[serde(default)]
+ stderr: Option<String>,
+ #[serde(default)]
+ interleaved_output: Option<String>,
+ #[serde(default)]
+ exit_code: Option<i32>,
+}
+
+impl ShellOutcome {
+ /// The output as the terminal showed it, else whichever stream it wrote.
+ fn output(&self) -> Option<String> {
+ self.interleaved_output
+ .clone()
+ .or_else(|| self.stdout.clone())
+ .or_else(|| self.stderr.clone())
+ }
+}
+
+#[derive(Deserialize)]
+struct PathArguments {
+ #[serde(default)]
+ path: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct PathOutcome {
+ #[serde(default)]
+ path: Option<String>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct EditOutcome {
+ #[serde(default)]
+ path: Option<String>,
+ #[serde(default)]
+ before_full_file_content: Option<String>,
+ #[serde(default)]
+ after_full_file_content: Option<String>,
+}
+
+impl EditOutcome {
+ /// A finished edit's whole-file diff. `beforeFullFileContent` is absent
+ /// exactly when the file is new, which is what `old_text: None` means.
+ fn into_diff(self) -> Option<FileDiff> {
+ Some(FileDiff {
+ path: self.path?.into(),
+ old_text: self.before_full_file_content,
+ new_text: self.after_full_file_content?,
+ })
+ }
+}
+
+/// A `toolCall` step whose descriptor this reader has no type for. Only
+/// the variant's name is read - the key ending in `ToolCall` - so the call
+/// still appears, as an `other` with nothing inside.
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct UnknownToolCall {
+ #[serde(default)]
+ tool_call_id: String,
+ #[serde(flatten)]
+ rest: BTreeMap<String, IgnoredAny>,
+}
+
+impl UnknownToolCall {
+ fn into_part(self) -> MessagePart {
+ let name = self
+ .rest
+ .into_keys()
+ .find(|key| key.ends_with("ToolCall"))
+ .map(|key| key.trim_end_matches("ToolCall").to_owned())
+ .unwrap_or_default();
+ MessagePart::ToolUse {
+ id: ToolUseId(collapse_whitespace(&self.tool_call_id)),
+ name: ToolName::native(name),
+ status: ToolStatus::Pending,
+ detail: ToolDetail::Other {
+ kind: "other".to_owned(),
+ output: None,
+ input: None,
+ },
+ }
+ }
+}
diff --git a/crates/agent_fold/src/domain/harness/generic.rs b/crates/agent_fold/src/domain/harness/generic.rs
new file mode 100644
index 0000000000..ac17ff68f7
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/generic.rs
@@ -0,0 +1,127 @@
+//! The harness-neutral readings every [`HarnessReader`] starts from.
+//!
+//! These read conventions that are not any one harness's:
+//!
+//! - The ACP title as the tool's name.
+//! - The `_meta.terminal_output` / `_meta.terminal_exit` keys, an ACP
+//! *client* extension (Zed's - a client advertises
+//! `clientCapabilities._meta.terminal_output`) that any agent serving that
+//! client writes, whichever harness it is.
+//! - The "Task tool" convention for subagents that Claude Code set and
+//! OpenCode and Cursor copied: a tool named `task`/`agent` with
+//! `{ description, prompt, subagent_type }` arguments.
+
+use agent_client_protocol::schema::v1::ToolKind;
+use serde::Deserialize;
+use serde_json::Value;
+
+use super::{HarnessReader, SubagentInput, ToolFrame, mcp, namespaced, raw};
+use crate::domain::model::{SubagentResult, ToolName};
+
+/// A harness this fold knows nothing specific about.
+pub struct Generic;
+
+impl HarnessReader for Generic {}
+
+/// `_meta.terminal_output`: the output accumulated so far.
+#[derive(Deserialize)]
+struct TerminalOutput {
+ data: String,
+}
+
+/// `_meta.terminal_exit`: how the command ended.
+#[derive(Deserialize)]
+struct TerminalExit {
+ exit_code: Option<i64>,
+}
+
+/// A chunk of terminal output carried on a `tool_call_update`.
+///
+/// Reads `_meta.terminal_output.data`. Each update carries the output
+/// accumulated so far rather than only the new bytes, so callers should
+/// replace rather than append.
+#[must_use]
+pub fn terminal_output(frame: &ToolFrame<'_>) -> Option<String> {
+ namespaced::<TerminalOutput>(frame.meta, "terminal_output").map(|output| output.data)
+}
+
+/// The exit code reported when a terminal-backed tool call finished.
+///
+/// Reads `_meta.terminal_exit.exit_code`.
+#[must_use]
+pub fn terminal_exit_code(frame: &ToolFrame<'_>) -> Option<i32> {
+ let code = namespaced::<TerminalExit>(frame.meta, "terminal_exit")?.exit_code?;
+ i32::try_from(code).ok()
+}
+
+/// The Task-tool convention: a tool named `task` or `agent` whose kind is
+/// `think` (Claude Code, OpenCode) or `other` (Cursor).
+#[must_use]
+pub fn is_subagent(name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ matches!(frame.kind, Some(ToolKind::Think | ToolKind::Other))
+ && matches!(
+ name.display().to_ascii_lowercase().as_str(),
+ "task" | "agent"
+ )
+}
+
+/// The Task-tool arguments, plus the aliases the harnesses that copied the
+/// convention use: `task` for the prompt (Macro's own `Subagent`),
+/// `background` for `run_in_background` (OpenCode).
+#[derive(Deserialize, Default)]
+struct TaskInput {
+ subagent_type: Option<String>,
+ description: Option<String>,
+ prompt: Option<String>,
+ task: Option<String>,
+ run_in_background: Option<bool>,
+ background: Option<bool>,
+}
+
+/// The Task-tool argument shape, read off a call's raw input.
+#[must_use]
+pub fn subagent_input(frame: &ToolFrame<'_>) -> SubagentInput {
+ let input: TaskInput = raw(frame.raw_input).unwrap_or_default();
+ SubagentInput {
+ agent_type: input.subagent_type,
+ description: input.description,
+ prompt: input.prompt.or(input.task),
+ background: input.run_in_background.or(input.background),
+ }
+}
+
+/// A bare `{ "error": … }` result, how several harnesses report a failed
+/// call's output.
+#[derive(Deserialize)]
+struct ErrorOutput {
+ error: String,
+}
+
+/// A subagent's result when the harness reports nothing structured: the
+/// raw output as text, else the content blocks' text; an `{ "error" }`
+/// object is a failure.
+///
+/// Content text counts only once the call has finished: while a delegation
+/// streams, Claude Code echoes the brief there, and an echo of the question
+/// is not an answer.
+#[must_use]
+pub fn subagent_result(frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ let mut result = SubagentResult::default();
+ if let Some(raw_value) = frame.raw_output {
+ if let Some(ErrorOutput { error }) = raw(Some(raw_value)) {
+ result.error = Some(error);
+ } else {
+ let (value, error) = mcp::unwrap_call_result(raw_value);
+ result.error = error;
+ result.text = match value {
+ Value::String(text) => Some(text),
+ Value::Null => None,
+ other => Some(other.to_string()),
+ };
+ }
+ }
+ if result.text.is_none() && result.error.is_none() && frame.finished() {
+ result.text = frame.content_text();
+ }
+ (!result.is_empty()).then_some(result)
+}
diff --git a/crates/agent_fold/src/domain/harness/hermes.rs b/crates/agent_fold/src/domain/harness/hermes.rs
new file mode 100644
index 0000000000..c7026bf728
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/hermes.rs
@@ -0,0 +1,68 @@
+//! Nous Research's Hermes agent (`agentInfo.name = "hermes-agent"`).
+//!
+//! Writes no `_meta` on tool frames (only `_meta.hermes.*` on session-info
+//! and replayed message chunks). Its delegation tool is `delegate_task`,
+//! which its ACP adapter reports as kind `execute` - not `think` - with no
+//! `rawInput` and no `rawOutput`; everything is in the title and the content
+//! text:
+//!
+//! - title: `delegate: <goal…>`, `delegate batch (N tasks)`, or
+//! `delegate task`
+//! - opening content: `Delegating task:\n<goal>`
+//! - completion content: the dispatch JSON, a `Delegation results: …` block,
+//! or `Delegation failed: <error>`
+//!
+//! The subagent's own calls are not streamed to the parent.
+
+use lazy_regex::{regex_captures, regex_is_match};
+
+use super::{HarnessReader, SubagentInput, ToolFrame, generic};
+use crate::domain::model::{SubagentResult, ToolName};
+
+/// Reader for Hermes's conventions.
+pub struct Hermes;
+
+impl HarnessReader for Hermes {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)hermes", name)
+ }
+
+ /// The title is the only name there is; strip the goal off it so the
+ /// call reads as the tool it is.
+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {
+ is_delegation_title(frame.title?).then(|| ToolName::native("delegate_task"))
+ }
+
+ fn is_subagent(&self, name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ name.display() == "delegate_task" || generic::is_subagent(name, frame)
+ }
+
+ fn subagent_input(&self, frame: &ToolFrame<'_>) -> SubagentInput {
+ let mut input = generic::subagent_input(frame);
+ let title = frame.title.unwrap_or_default();
+ if input.prompt.is_none()
+ && let Some((_, goal)) = regex_captures!(r"^delegate:\s*(.+)$", title)
+ {
+ input.prompt = Some(goal.to_owned());
+ }
+ if input.description.is_none() && is_delegation_title(title) {
+ input.description = Some(title.to_owned());
+ }
+ input
+ }
+
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ let mut result = generic::subagent_result(frame)?;
+ if let Some(text) = result.text.as_deref()
+ && let Some((_, error)) = regex_captures!(r"^Delegation failed:\s*(.+)$", text)
+ {
+ result.error = Some(error.to_owned());
+ result.text = None;
+ }
+ Some(result)
+ }
+}
+
+fn is_delegation_title(title: &str) -> bool {
+ regex_is_match!(r"^delegate(:| batch \(\d+ tasks?\)| task$)", title)
+}
diff --git a/crates/agent_fold/src/domain/harness/macro_inmem.rs b/crates/agent_fold/src/domain/harness/macro_inmem.rs
new file mode 100644
index 0000000000..ef4a9a016a
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/macro_inmem.rs
@@ -0,0 +1,86 @@
+//! Macro's own in-process agent, `agent_inmem`.
+//!
+//! The one harness this repository writes as well as reads, so it labels its
+//! frames rather than leaving the fold to guess from titles. It mirrors
+//! Claude Code's key layout under its own namespace, `_meta.macro`:
+//!
+//! - `toolName` - the Macro tool's name (`ReadContent`, `SendEmail`), or
+//! `mcp__<server>__<tool>` for a connected app's tool it reached over MCP.
+//! - `subagent: true` - on its `Subagent` delegation.
+//!
+//! Its own tools run in-process, not over MCP, so their output is the tool's
+//! own JSON with no envelope around it.
+
+use agent_client_protocol::schema::v1::Meta;
+use lazy_regex::regex_is_match;
+use serde::Deserialize;
+
+use super::{HarnessReader, ToolFrame, generic, has_namespace, macro_tools, namespaced, raw};
+use crate::domain::model::ToolName;
+
+/// The `_meta` namespace `agent_inmem` writes under.
+pub const NAMESPACE: &str = "macro";
+
+/// Reader for the in-process agent's conventions.
+pub struct MacroInmem;
+
+/// `_meta.macro`, as far as the fold reads it.
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct MacroMeta {
+ tool_name: Option<String>,
+ #[serde(default)]
+ subagent: bool,
+}
+
+fn meta_of(meta: Option<&Meta>) -> MacroMeta {
+ namespaced(meta, NAMESPACE).unwrap_or_default()
+}
+
+/// How a failed in-process tool reports: `{ "error": <description> }` and
+/// nothing else.
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct ErrorOutput {
+ error: String,
+}
+
+impl HarnessReader for MacroInmem {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)^macro", name)
+ }
+
+ fn wrote(&self, frame: &ToolFrame<'_>) -> bool {
+ has_namespace(frame.meta, NAMESPACE)
+ }
+
+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {
+ meta_of(frame.meta)
+ .tool_name
+ .map(|name| name.parse().unwrap_or_else(|never| match never {}))
+ }
+
+ /// Every native tool this agent calls is a Macro tool; the ones it
+ /// reaches over MCP belong to whichever server it named.
+ fn macro_tool<'name>(&self, name: &'name ToolName) -> Option<&'name str> {
+ match name {
+ ToolName::Native { name } => Some(name),
+ ToolName::Mcp { .. } => macro_tools::mcp_tool(name),
+ }
+ }
+
+ /// Tool output arrives bare.
+ fn unwrap_tool_output(
+ &self,
+ raw_output: &serde_json::Value,
+ ) -> (serde_json::Value, Option<String>) {
+ match raw::<ErrorOutput>(Some(raw_output)) {
+ Some(ErrorOutput { error }) => (serde_json::Value::Null, Some(error)),
+ None => (raw_output.clone(), None),
+ }
+ }
+
+ fn is_subagent(&self, name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ meta_of(frame.meta).subagent || generic::is_subagent(name, frame)
+ }
+}
diff --git a/crates/agent_fold/src/domain/harness/macro_tools.rs b/crates/agent_fold/src/domain/harness/macro_tools.rs
new file mode 100644
index 0000000000..6dddff6acd
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/macro_tools.rs
@@ -0,0 +1,172 @@
+//! Macro as a tool provider: which tool names are Macro's, and what those
+//! tools return.
+//!
+//! Not a harness either. Macro's tools reach the fold through whichever
+//! harness called them - natively from Macro's own in-process agent, or over
+//! Macro's MCP server from any other - and the harness decides how the result
+//! is wrapped ([`HarnessReader::unwrap_tool_output`]). What is *inside* the
+//! wrapper is Macro's whichever harness relayed it, and that is what this
+//! module reads:
+//!
+//! - Which Macro tools are *user tools* - drafted by the agent, finished by
+//! the user - and the [`UserToolResponse`] they return. Mirrors
+//! `ai_toolset::UserToolResponse`, restated here so the wasm fold does not
+//! depend on the toolset crate.
+//! - Macro's own delegation tool, `Subagent`, and its [`SubagentResponse`].
+//! Mirrors `ai_tools::subagent::SubagentResponse`.
+//!
+//! Every other Macro tool's result is the tool's own JSON, handed to a reader
+//! as it is.
+//!
+//! [`HarnessReader::unwrap_tool_output`]: super::HarnessReader::unwrap_tool_output
+
+use serde::Deserialize;
+use serde_json::Value;
+
+use crate::domain::model::{SubagentResult, ToolName, UserToolOutcome};
+
+/// The name every session's server list gives Macro's own MCP server.
+/// Mirrors `agent_harness::MACRO_MCP_NAME`; restated here rather than
+/// imported so the wasm fold does not pull in the harness crate.
+pub const MCP_SERVER: &str = "macro";
+
+/// The Macro tool `name` reaches over Macro's own MCP server, if it is one.
+/// A native name is never a Macro tool by this rule - Macro's in-process
+/// agent is recognized by the harness it runs under, not by its tool names.
+#[must_use]
+pub fn mcp_tool(name: &ToolName) -> Option<&str> {
+ match name {
+ ToolName::Mcp { server, tool } if server == MCP_SERVER => Some(tool),
+ ToolName::Native { .. } | ToolName::Mcp { .. } => None,
+ }
+}
+
+/// Macro tools the agent drafts and the user finishes.
+///
+/// Registered with `add_user_tool` on the backend: calling one returns
+/// `"PendingUserExecution"` and performs nothing until the user acts through
+/// the session's own API.
+pub const USER_TOOLS: &[&str] = &["SendEmail", "CreateCalendarEvent"];
+
+/// Macro's own delegation tool. Mirrors `agent_inmem`'s `SUBAGENT_TOOL`.
+pub const SUBAGENT_TOOL: &str = "Subagent";
+
+/// What the fold does with a Macro tool, by its name.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MacroTool<'name> {
+ /// A user tool: folds to a draft the user finishes.
+ User(&'name str),
+ /// The `Subagent` tool: folds to a delegation, like a harness's own.
+ Subagent,
+ /// Any other Macro tool: folds to its own input and output.
+ Other(&'name str),
+}
+
+impl<'name> MacroTool<'name> {
+ /// Classify a Macro tool by name.
+ #[must_use]
+ pub fn of(tool: &'name str) -> Self {
+ if USER_TOOLS.contains(&tool) {
+ Self::User(tool)
+ } else if tool == SUBAGENT_TOOL {
+ Self::Subagent
+ } else {
+ Self::Other(tool)
+ }
+ }
+}
+
+/// What the `Subagent` tool returns: the child's answer as prose.
+#[derive(Deserialize)]
+struct SubagentResponse {
+ result: String,
+}
+
+/// A `Subagent` call's result, from its own response (`value`, already
+/// unwrapped) and the error its wrapper reported, if any. `None` when there
+/// is neither.
+#[must_use]
+pub fn subagent_result(value: &Value, error: Option<String>) -> Option<SubagentResult> {
+ let response: Option<SubagentResponse> = serde_json::from_value(value.clone()).ok();
+ let result = SubagentResult {
+ text: response
+ .map(|response| response.result)
+ .filter(|text| !text.is_empty()),
+ error,
+ ..SubagentResult::default()
+ };
+ (!result.is_empty()).then_some(result)
+}
+
+/// The backend's `UserToolResponse<T>`, with the action left as JSON: each
+/// user tool defines its own.
+#[derive(Debug, Deserialize)]
+enum UserToolResponse {
+ PendingUserExecution,
+ Rejected,
+ UserAction(Value),
+}
+
+/// `SendEmail`'s action, mirroring `email::SendEmailResponse`.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+enum SendEmailAction {
+ Sent {
+ message_id: String,
+ thread_id: String,
+ },
+ ConvertedToDraft {
+ draft_id: String,
+ #[serde(default)]
+ thread_id: Option<String>,
+ },
+ UserEdited,
+}
+
+/// Read a `UserToolResponse<T>` value into an outcome.
+///
+/// `value` is the tool's own result, already unwrapped. `tool` picks the
+/// `UserAction` shape: `SendEmail` distinguishes sent from saved-as-draft,
+/// anything else reports the action's payload whole.
+#[must_use]
+pub fn user_tool_outcome(tool: &str, value: &Value) -> UserToolOutcome {
+ if value.is_null() {
+ return UserToolOutcome::Pending;
+ }
+ let Ok(response) = serde_json::from_value::<UserToolResponse>(value.clone()) else {
+ return UserToolOutcome::Unrecognized;
+ };
+ match response {
+ UserToolResponse::PendingUserExecution => UserToolOutcome::Pending,
+ UserToolResponse::Rejected => UserToolOutcome::Rejected,
+ UserToolResponse::UserAction(action) => user_action_outcome(tool, action),
+ }
+}
+
+fn user_action_outcome(tool: &str, action: Value) -> UserToolOutcome {
+ // Every user tool's composer reports an edit the same way.
+ if action.as_str() == Some("userEdited") {
+ return UserToolOutcome::Edited;
+ }
+ if tool == "SendEmail" {
+ return match serde_json::from_value::<SendEmailAction>(action) {
+ Ok(SendEmailAction::Sent {
+ message_id,
+ thread_id,
+ }) => UserToolOutcome::Sent {
+ message_id,
+ thread_id,
+ },
+ Ok(SendEmailAction::ConvertedToDraft {
+ draft_id,
+ thread_id,
+ }) => UserToolOutcome::Draft {
+ draft_id,
+ thread_id,
+ },
+ Ok(SendEmailAction::UserEdited) => UserToolOutcome::Edited,
+ Err(_) => UserToolOutcome::Unrecognized,
+ };
+ }
+ UserToolOutcome::Completed { result: action }
+}
diff --git a/crates/agent_fold/src/domain/harness/mcp.rs b/crates/agent_fold/src/domain/harness/mcp.rs
new file mode 100644
index 0000000000..6e2b0eac50
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/mcp.rs
@@ -0,0 +1,96 @@
+//! MCP's result envelope, as it reaches the fold through any harness.
+//!
+//! Not a harness: MCP is the protocol a harness reaches an external tool
+//! server over, and it wraps every result the same way whoever the harness
+//! is - [`CallToolResult`], `{ content: [blocks], structuredContent?,
+//! isError? }`. A harness may copy that whole envelope into ACP's `rawOutput`
+//! rather than the tool's own JSON, so the fold unwraps it before reading.
+//! Its content blocks are the same shape as ACP's [`ContentBlock`], which is
+//! what they deserialize as.
+//!
+//! What is inside the envelope belongs to whoever serves the tool; this
+//! module does not read it. A value that is not an envelope is left alone.
+
+use agent_client_protocol::schema::v1::ContentBlock;
+use serde::Deserialize;
+use serde_json::Value;
+
+/// MCP's `CallToolResult`, as far as the fold reads it.
+///
+/// Deserializing an object into this is how an envelope is recognized: a
+/// tool's own JSON may well have a `content` field (Macro's `ReadContent`
+/// returns `{ content: { text }, comments }`), but only an array of typed
+/// blocks deserializes as one, and an object with neither `content` nor
+/// `structuredContent` is no envelope at all.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct CallToolResult {
+ content: Option<Vec<ContentBlock>>,
+ structured_content: Option<Value>,
+ #[serde(default)]
+ is_error: bool,
+}
+
+impl CallToolResult {
+ /// The envelope `raw` is, if it is one.
+ fn recognize(raw: &Value) -> Option<Self> {
+ match raw {
+ Value::Object(_) => {
+ let result: Self = serde_json::from_value(raw.clone()).ok()?;
+ (result.content.is_some() || result.structured_content.is_some()).then_some(result)
+ }
+ // How Claude Code copies `content` into `rawOutput`: the blocks
+ // alone, no envelope around them.
+ Value::Array(items) if !items.is_empty() => {
+ let content: Vec<ContentBlock> = serde_json::from_value(raw.clone()).ok()?;
+ Some(Self {
+ content: Some(content),
+ structured_content: None,
+ is_error: false,
+ })
+ }
+ _ => None,
+ }
+ }
+
+ /// The text blocks' text, in order.
+ fn texts(&self) -> Vec<&str> {
+ self.content
+ .iter()
+ .flatten()
+ .filter_map(|block| match block {
+ ContentBlock::Text(text) => Some(text.text.as_str()),
+ _ => None,
+ })
+ .collect()
+ }
+}
+
+/// A tool's own result, with any MCP [`CallToolResult`] envelope removed,
+/// and the error text when the envelope marked the call failed.
+///
+/// Preference order for the payload: `structuredContent`; else the first
+/// text block that parses as JSON; else the text blocks joined as a string;
+/// else `null`. A value that is not an envelope is returned untouched.
+#[must_use]
+pub fn unwrap_call_result(raw: &Value) -> (Value, Option<String>) {
+ let Some(result) = CallToolResult::recognize(raw) else {
+ return (raw.clone(), None);
+ };
+ let texts = result.texts();
+ let error = result.is_error.then(|| texts.join("\n"));
+
+ if let Some(structured) = result.structured_content {
+ return (structured, error);
+ }
+ if let Some(parsed) = texts
+ .iter()
+ .find_map(|text| serde_json::from_str::<Value>(text).ok())
+ {
+ return (parsed, error);
+ }
+ if texts.is_empty() {
+ return (Value::Null, error);
+ }
+ (Value::String(texts.join("\n")), error)
+}
diff --git a/crates/agent_fold/src/domain/harness/openclaw.rs b/crates/agent_fold/src/domain/harness/openclaw.rs
new file mode 100644
index 0000000000..56ceb4031c
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/openclaw.rs
@@ -0,0 +1,104 @@
+//! OpenClaw's ACP gateway (`agentInfo.name = "openclaw-acp"`).
+//!
+//! Writes no `_meta` on tool frames. Every tool call is titled
+//! `<tool>: key: value, key: value…` with the arguments in `rawInput`. Its
+//! delegation tool is `sessions_spawn`, kind `other` ([`SpawnArgs`]):
+//!
+//! ```json
+//! { "task": "…", "label": "…", "agentId": "…", "runtime": "subagent" }
+//! ```
+//!
+//! Completion means the spawn was *accepted*, not that the subagent
+//! finished; the answer arrives later as a message. The result names the
+//! child session ([`SpawnDetails`]):
+//!
+//! ```json
+//! { "content": [{ "type": "text", "text": "{…}" }],
+//! "details": { "status": "accepted", "childSessionKey": "agent:main:subagent:…", "runId": "…" } }
+//! ```
+
+use lazy_regex::{regex_captures, regex_is_match};
+use serde::Deserialize;
+use serde_json::Value;
+
+use super::{HarnessReader, SubagentInput, ToolFrame, generic, mcp, raw};
+use crate::domain::model::{SubagentResult, ToolName};
+
+/// Reader for OpenClaw's conventions.
+pub struct OpenClaw;
+
+/// `sessions_spawn`'s arguments, beyond the Task-tool ones the generic
+/// reader takes (`task` as the prompt).
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SpawnArgs {
+ label: Option<String>,
+ agent_id: Option<String>,
+ runtime: Option<String>,
+}
+
+/// `sessions_spawn`'s result, wherever it sits: the `details` object, or the
+/// same JSON as the text block's content.
+#[derive(Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct SpawnDetails {
+ child_session_key: Option<String>,
+ run_id: Option<String>,
+ error: Option<String>,
+}
+
+/// A `rawOutput` that carries `details` beside its content blocks.
+#[derive(Debug, Deserialize)]
+struct DetailedOutput {
+ details: SpawnDetails,
+}
+
+impl HarnessReader for OpenClaw {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)openclaw", name)
+ }
+
+ /// `<tool>: key: value…` - the tool is what comes before the first colon.
+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {
+ regex_captures!(r"^([a-z][a-z0-9_]*):\s", frame.title?)
+ .map(|(_, tool)| ToolName::native(tool))
+ }
+
+ fn is_subagent(&self, name: &ToolName, frame: &ToolFrame<'_>) -> bool {
+ name.display() == "sessions_spawn" || generic::is_subagent(name, frame)
+ }
+
+ fn subagent_input(&self, frame: &ToolFrame<'_>) -> SubagentInput {
+ let mut input = generic::subagent_input(frame);
+ let args: SpawnArgs = raw(frame.raw_input).unwrap_or_default();
+ if input.description.is_none() {
+ input.description = args.label;
+ }
+ if input.agent_type.is_none() {
+ input.agent_type = args.agent_id.or(args.runtime);
+ }
+ input
+ }
+
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ let Some(raw_output) = frame.raw_output else {
+ return generic::subagent_result(frame);
+ };
+ let details = match raw::<DetailedOutput>(Some(raw_output)) {
+ Some(output) => output.details,
+ // Without `details`, the text block's JSON says the same.
+ None => match mcp::unwrap_call_result(raw_output).0 {
+ Value::String(text) => serde_json::from_str(&text).unwrap_or_default(),
+ value => serde_json::from_value(value).unwrap_or_default(),
+ },
+ };
+ let result = SubagentResult {
+ agent_id: details.child_session_key.or(details.run_id),
+ error: details.error,
+ // An accepted spawn has no answer yet; that arrives as a message.
+ text: None,
+ ..SubagentResult::default()
+ };
+ (!result.is_empty()).then_some(result)
+ }
+}
diff --git a/crates/agent_fold/src/domain/harness/opencode.rs b/crates/agent_fold/src/domain/harness/opencode.rs
new file mode 100644
index 0000000000..a2f4c6a2eb
--- /dev/null
+++ b/crates/agent_fold/src/domain/harness/opencode.rs
@@ -0,0 +1,86 @@
+//! OpenCode, whose ACP server is built in (`agentInfo.name = "OpenCode"`).
+//!
+//! Writes no `_meta` on tool frames. Its subagent tool is `task`, kind
+//! `think`, with the Task-tool arguments; the child runs as a separate
+//! OpenCode session whose activity is never streamed into the parent. What
+//! the parent sees is the completion, read as [`TaskOutput`]:
+//!
+//! ```json
+//! { "output": "<task id=\"ses_…\" state=\"completed\">\n<task_result>\n…\n</task_result>\n</task>",
+//! "metadata": { "parentSessionId": "ses_…", "sessionId": "ses_…",
+//! "model": { "modelID": "…", "providerID": "…" }, "truncated": false } }
+//! ```
+//!
+//! or, on failure, `{ "error": "…", "metadata": { … } }`.
+
+use lazy_regex::{regex_captures, regex_is_match};
+use serde::Deserialize;
+use serde_json::Value;
+
+use super::{HarnessReader, ToolFrame, generic, raw};
+use crate::domain::model::SubagentResult;
+
+/// Reader for OpenCode's conventions.
+pub struct OpenCode;
+
+/// The `task` tool's `rawOutput`.
+#[derive(Debug, Deserialize)]
+struct TaskOutput {
+ output: Option<String>,
+ error: Option<String>,
+ metadata: Option<TaskMetadata>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TaskMetadata {
+ session_id: Option<String>,
+ model: Option<TaskModel>,
+}
+
+#[derive(Debug, Deserialize)]
+struct TaskModel {
+ #[serde(rename = "providerID")]
+ provider_id: String,
+ #[serde(rename = "modelID")]
+ model_id: String,
+}
+
+impl HarnessReader for OpenCode {
+ fn announces(&self, name: &str) -> bool {
+ regex_is_match!(r"(?i)^opencode", name)
+ }
+
+ fn subagent_result(&self, frame: &ToolFrame<'_>) -> Option<SubagentResult> {
+ let raw_output = frame.raw_output;
+ let Some(output) =
+ raw::<TaskOutput>(raw_output).filter(|_| raw_output.is_some_and(Value::is_object))
+ else {
+ return generic::subagent_result(frame);
+ };
+ let metadata = output.metadata;
+ let result = SubagentResult {
+ text: output.output.as_deref().map(task_result_text),
+ error: output.error,
+ agent_id: metadata.as_ref().and_then(|meta| meta.session_id.clone()),
+ model: metadata
+ .and_then(|meta| meta.model)
+ .map(|model| format!("{}/{}", model.provider_id, model.model_id)),
+ ..SubagentResult::default()
+ };
+ (!result.is_empty()).then_some(result)
+ }
+}
+
+/// The answer inside OpenCode's `<task …><task_result>…</task_result></task>`
+/// wrapper, or the text untouched when it is not wrapped.
+#[must_use]
+pub fn task_result_text(output: &str) -> String {
+ match regex_captures!(
+ r"(?s)<task_(?:result|error)>\s*(.*?)\s*</task_(?:result|error)>",
+ output
+ ) {
+ Some((_, inner)) => inner.to_owned(),
+ None => output.to_owned(),
+ }
+}
diff --git a/crates/agent_fold/src/domain/meta.rs b/crates/agent_fold/src/domain/meta.rs
deleted file mode 100644
index ce525adb74..0000000000
--- a/crates/agent_fold/src/domain/meta.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-//! Harness-specific `_meta` extraction.
-//!
-//! ACP reserves `_meta` for implementation-defined data and tells clients to
-//! make no assumptions about it. A faithful fold nevertheless has to read it,
-//! because the material a reader most wants is only there:
-//!
-//! - The real tool name (`Bash`, `Read`, `Write`). ACP normalizes tools to a
-//! coarse [`ToolKind`](agent_client_protocol::ToolKind), so `execute` is all
-//! the spec gives us.
-//! - Terminal output and exit codes. ACP's own
-//! [`Terminal`](agent_client_protocol::Terminal) content block carries only
-//! a `terminalId` pointing at a terminal the client is expected to have
-//! created itself. A fold reading a historical log never created one, so the
-//! only output it will ever see is the copy in `_meta`.
-//!
-//! Everything that depends on a specific harness lives in this module, so
-//! supporting a second one means adding a sibling reader rather than editing
-//! the fold. Every function here treats a missing or misshapen key as "no
-//! information" and returns `None`.
-
-use agent_client_protocol::schema::v1::Meta;
-
-/// The `_meta` keys written by the Claude Code harness.
-pub mod claude_code {
- use super::Meta;
-
- /// The harness's own name for the tool behind a `tool_call`.
- ///
- /// Reads `_meta.claudeCode.toolName`.
- #[must_use]
- pub fn tool_name(meta: Option<&Meta>) -> Option<String> {
- meta?
- .get("claudeCode")?
- .get("toolName")?
- .as_str()
- .map(ToOwned::to_owned)
- }
-
- /// A chunk of terminal output carried on a `tool_call_update`.
- ///
- /// Reads `_meta.terminal_output.data`. Each update carries the output
- /// accumulated so far rather than only the new bytes, so callers should
- /// replace rather than append.
- #[must_use]
- pub fn terminal_output(meta: Option<&Meta>) -> Option<String> {
- meta?
- .get("terminal_output")?
- .get("data")?
- .as_str()
- .map(ToOwned::to_owned)
- }
-
- /// The exit code reported when a terminal-backed tool call finished.
- ///
- /// Reads `_meta.terminal_exit.exit_code`.
- #[must_use]
- pub fn terminal_exit_code(meta: Option<&Meta>) -> Option<i32> {
- let code = meta?.get("terminal_exit")?.get("exit_code")?.as_i64()?;
- i32::try_from(code).ok()
- }
-}
-
-/// The command line behind an `execute` tool call.
-///
-/// This one reads ACP's own `rawInput` rather than `_meta`, but lives here
-/// because the key it looks for (`command`) is a harness convention that ACP
-/// does not specify.
-#[must_use]
-pub fn command_from_raw_input(raw_input: Option<&serde_json::Value>) -> Option<String> {
- raw_input?.get("command")?.as_str().map(ToOwned::to_owned)
-}
-
-/// The whole-file edit an edit tool's raw input describes, as
-/// `(path, new contents)`.
-///
-/// Claude Code's `Write` (and whole-file `Edit`) calls carry
-/// `{"filePath", "content"}` in `rawInput` and never report an ACP diff
-/// content block, so this is the only material a fold has for their diff. The
-/// prior contents are not on the wire at all — a reader treats the file as
-/// new.
-#[must_use]
-pub fn file_edit_from_raw_input(raw_input: Option<&serde_json::Value>) -> Option<(String, String)> {
- let input = raw_input?;
- let path = input.get("filePath")?.as_str()?;
- let content = input.get("content")?.as_str()?;
- Some((path.to_owned(), content.to_owned()))
-}
diff --git a/crates/agent_fold/src/domain/mod.rs b/crates/agent_fold/src/domain/mod.rs
index cb09840022..5ab4a88a27 100644
--- a/crates/agent_fold/src/domain/mod.rs
+++ b/crates/agent_fold/src/domain/mod.rs
@@ -5,10 +5,10 @@
mod error;
/// Collapsing a protocol log into messages.
pub mod fold;
+/// Harness-specific `_meta` and raw-input extraction.
+pub mod harness;
/// The raw log vocabulary the fold consumes.
pub mod log;
-/// Harness-specific `_meta` extraction.
-pub mod meta;
/// The renderable message vocabulary.
pub mod model;
/// The driving query port and the driven log-source port.
diff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rs
index 62102d137f..36b34a217f 100644
--- a/crates/agent_fold/src/domain/model.rs
+++ b/crates/agent_fold/src/domain/model.rs
@@ -17,7 +17,32 @@ use macro_user_id::user_id::MacroUserIdStr;
use non_empty::NonEmpty;
use serde::Serialize;
use specta::Type;
-use std::{borrow::Cow, path::PathBuf, str::FromStr};
+
+/// Per-push change reports.
+mod event;
+/// Session-level metadata.
+mod metadata;
+/// The parts a message is made of.
+mod part;
+/// Permission requests and outcomes.
+mod permission;
+/// The agent's plan.
+mod plan;
+/// Delegated agents.
+mod subagent;
+/// Tool calls.
+mod tool;
+/// Macro user tools.
+mod user_tool;
+
+pub use event::{FoldEvent, OwnedFoldEvent};
+pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata};
+pub use part::{Control, ControlOutcome, MessagePart, StopReason};
+pub use permission::{PermissionOption, PermissionOptionKind, PermissionOutcome};
+pub use plan::{PlanEntry, PlanEntryPriority, PlanEntryStatus};
+pub use subagent::{SubagentResult, ToolStats};
+pub use tool::{AnsiText, FileDiff, ToolDetail, ToolName, ToolStatus};
+pub use user_tool::UserToolOutcome;
/// One prompt-to-stop cycle within a session.
///
@@ -192,498 +217,3 @@ impl Author {
}
}
}
-
-/// A unit of renderable content.
-#[derive(Debug, Clone, PartialEq, Serialize, Type)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum MessagePart {
- /// Prose from the user or the agent.
- Text {
- /// The prose.
- text: String,
- },
- /// The agent's reasoning, which a reader may want to hide by default.
- Thought {
- /// The reasoning.
- text: String,
- },
- /// A tool the agent invoked.
- ToolUse {
- /// The ACP `toolCallId`.
- id: ToolUseId,
- /// What to show as the tool's name.
- label: String,
- /// Where the call got to.
- status: ToolStatus,
- /// What the tool did, as far as the log reveals.
- detail: ToolDetail,
- /// The call's input, verbatim from ACP's `rawInput`, when reported.
- ///
- /// Carried on every call - not just [`ToolDetail::Other`] - so a
- /// reader that knows a tool by name (the Macro toolset renders each
- /// tool with its own component) can parse the real arguments instead
- /// of settling for the coarse detail.
- #[serde(rename = "rawInput")]
- #[specta(type = specta_typescript::Unknown)]
- raw_input: Option<Box<serde_json::Value>>,
- /// The call's result, verbatim from ACP's `rawOutput`, when reported.
- ///
- /// The structured counterpart to the text a detail may carry: Macro's
- /// agent reports each tool response as JSON here, and named-tool
- /// rendering needs that JSON whole.
- #[serde(rename = "rawOutput")]
- #[specta(type = specta_typescript::Unknown)]
- raw_output: Option<Box<serde_json::Value>>,
- },
- /// The agent asking to proceed.
- Permission {
- /// The tool call permission was requested for.
- #[serde(rename = "toolCall")]
- tool_call: ToolUseId,
- /// The choices offered, in the order ACP listed them.
- options: Vec<PermissionOption>,
- /// How the request has resolved so far.
- outcome: PermissionOutcome,
- },
- /// A user-issued control operation on the session.
- Control {
- /// The requested operation.
- control: Control,
- /// How the runtime disposed of it so far.
- outcome: ControlOutcome,
- },
- /// The agent's working todo list for the turn.
- Plan {
- /// The tasks, in the order the agent listed them.
- entries: Vec<PlanEntry>,
- },
-}
-
-/// One task on an agent plan.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "camelCase")]
-pub struct PlanEntry {
- /// What this task aims to accomplish.
- pub content: String,
- /// The task's relative importance.
- pub priority: PlanEntryPriority,
- /// Where the task got to.
- pub status: PlanEntryStatus,
-}
-
-/// A [`PlanEntry`]'s relative importance, mirroring ACP's
-/// `PlanEntryPriority`.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "snake_case")]
-pub enum PlanEntryPriority {
- /// Critical to the overall goal.
- High,
- /// Important but not critical.
- Medium,
- /// Nice to have but not essential.
- Low,
-}
-
-/// Where a [`PlanEntry`] got to, mirroring ACP's `PlanEntryStatus`.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "snake_case")]
-pub enum PlanEntryStatus {
- /// Not started yet.
- Pending,
- /// Currently being worked on.
- InProgress,
- /// Successfully completed.
- Completed,
-}
-
-/// A session control operation shown in the conversation timeline.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum Control {
- /// The runtime was asked to switch models.
- SetModel {
- /// The model slug requested by the caller.
- model: String,
- },
- /// The runtime was asked to compact its context.
- Compact,
- /// The runtime was asked to stop its current work.
- Stop,
-}
-
-/// How the runtime disposed of a [`Control`], like [`PermissionOutcome`] for
-/// permission requests. Pending is a legitimate final state: a control the
-/// session died before answering stays pending.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum ControlOutcome {
- /// No response yet.
- Pending,
- /// Acknowledged - immediately so for a stop, which nothing can answer.
- Accepted,
- /// Answered with a JSON-RPC error.
- Rejected {
- /// The error's message, verbatim.
- message: String,
- },
-}
-
-/// How far a tool call progressed.
-///
-/// [`ToolStatus::Pending`] and [`ToolStatus::Running`] are legitimate final
-/// states, not errors: a live session's newest calls have not finished, and a
-/// session that dies mid-call leaves one behind permanently.
-#[derive(
- Debug,
- Clone,
- Copy,
- Default,
- PartialEq,
- Eq,
- strum::Display,
- strum::IntoStaticStr,
- Serialize,
- Type,
-)]
-#[strum(serialize_all = "snake_case")]
-#[serde(rename_all = "snake_case")]
-pub enum ToolStatus {
- /// Not started - either still streaming input or awaiting permission.
- #[default]
- Pending,
- /// Currently running.
- Running,
- /// Finished successfully.
- Completed,
- /// Finished unsuccessfully.
- Failed,
-}
-
-/// What a tool call actually did.
-///
-/// Discriminated by what a reader needs in order to render it, not by ACP's
-/// [`ToolKind`](agent_client_protocol::ToolKind). A terminal wants command and
-/// output; an edit wants a diff; a handful of others want the paths they
-/// touched or whatever text they reported; everything else wants its raw
-/// input shown as JSON. Every named [`ToolKind`](agent_client_protocol::ToolKind)
-/// has a variant here, so the fold never falls back to [`Self::Other`] for a
-/// kind ACP defines - only for `switch_mode` (nothing a reader would want
-/// rendered) and a kind this fold does not yet know about.
-#[derive(Debug, Clone, PartialEq, Serialize, Type)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum ToolDetail {
- /// A shell command. ACP's `execute`.
- Terminal {
- /// The command line, when the harness reported one.
- command: Option<String>,
- /// Captured output, ANSI escapes intact. See [`AnsiText`].
- output: Option<AnsiText>,
- /// Process exit code, when the harness reported one.
- #[serde(rename = "exitCode")]
- exit_code: Option<i32>,
- },
- /// One or more file modifications. ACP's `edit`.
- Edit {
- /// The diffs ACP reported for this call.
- diffs: Vec<FileDiff>,
- },
- /// A file read. ACP's `read`.
- Read {
- /// Paths this call touched.
- paths: Vec<PathBuf>,
- },
- /// One or more files removed. ACP's `delete`.
- Delete {
- /// Paths this call touched.
- paths: Vec<PathBuf>,
- },
- /// One or more files moved or renamed. ACP's `move`.
- ///
- /// Only the paths a reader can be sure of. ACP has no standard field for
- /// "from" versus "to" - a call's `locations` is just the set of paths it
- /// touched - so this does not guess at a direction.
- Move {
- /// Paths this call touched.
- paths: Vec<PathBuf>,
- },
- /// A search. ACP's `search`.
- Search {
- /// Paths this call touched.
- paths: Vec<PathBuf>,
- /// Text the call reported - e.g. matched lines - when any.
- output: Option<String>,
- },
- /// Retrieving external data. ACP's `fetch`.
- Fetch {
- /// Text the call reported, when any.
- output: Option<String>,
- },
- /// Explicit reasoning surfaced as its own tool call, as distinct from
- /// [`MessagePart::Thought`], which is reasoning streamed inline. ACP's
- /// `think`.
- Think {
- /// Text the call reported, when any.
- output: Option<String>,
- },
- /// Anything else: ACP's `switch_mode`, and any kind - including `other`
- /// itself, [`ToolKind`](agent_client_protocol::ToolKind)'s default for a
- /// call that names no kind at all - this fold has no special rendering
- /// for.
- Other {
- /// ACP's tool kind, as its wire string.
- #[serde(rename = "acpKind")]
- kind: String,
- /// Text the call reported, when any.
- output: Option<String>,
- /// The tool's input, when reported.
- #[specta(type = specta_typescript::Unknown)]
- input: Option<serde_json::Value>,
- },
-}
-
-/// A file modification a tool reported.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "camelCase")]
-pub struct FileDiff {
- /// The file that changed.
- pub path: PathBuf,
- /// Prior contents, absent when the file is new.
- pub old_text: Option<String>,
- /// New contents.
- pub new_text: String,
-}
-
-/// Terminal output with ANSI escape sequences left in place.
-///
-/// Stripping here would be lossy and irreversible, and the escapes carry real
-/// information - the recordings are full of colorized `ls` and `grep` output.
-/// Rendering decides whether to interpret, strip, or ignore them.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(transparent)]
-#[specta(transparent)]
-pub struct AnsiText(pub String);
-
-impl AnsiText {
- /// The raw text, escapes included.
- #[must_use]
- pub fn as_str(&self) -> &str {
- &self.0
- }
-}
-
-/// One choice offered for a permission request.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "camelCase")]
-pub struct PermissionOption {
- /// The id to report back when this option is chosen.
- pub id: String,
- /// Label to show.
- pub name: String,
- /// What kind of choice this is.
- pub kind: PermissionOptionKind,
-}
-
-/// What kind of choice a [`PermissionOption`] offers, mirroring ACP's
-/// `PermissionOptionKind`.
-///
-/// ACP's enum is `#[non_exhaustive]`, but unlike [`StopReason`] there is no
-/// wire string worth preserving for a variant this fold does not model: the
-/// fold only ever sees one of these once the whole permission request has
-/// already deserialized successfully, and a wire value ACP added after this
-/// was written would have failed that deserialize already - so an unmatched
-/// kind here cannot happen in practice, not "happens and is rendered
-/// unlabeled."
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "snake_case")]
-pub enum PermissionOptionKind {
- /// Allow this operation only this time.
- AllowOnce,
- /// Allow this operation and remember the choice.
- AllowAlways,
- /// Reject this operation only this time.
- RejectOnce,
- /// Reject this operation and remember the choice.
- RejectAlways,
-}
-
-/// How a permission request has resolved so far.
-///
-/// Not just "chosen or not": nothing chosen has more than one cause, and a
-/// reader deciding whether to still show the options needs to tell them
-/// apart. [`Self::Pending`] may still resolve; [`Self::Errored`] and
-/// [`Self::Unrecognized`] have already resolved, just not into anything this
-/// fold can show as a choice.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum PermissionOutcome {
- /// No response has arrived yet - the request is still outstanding.
- Pending,
- /// An option was chosen.
- Selected {
- /// The chosen option's id.
- #[serde(rename = "optionId")]
- option_id: String,
- },
- /// The request was cancelled without a choice.
- Cancelled,
- /// The response was a JSON-RPC error rather than a result: the harness
- /// failed to answer the request rather than resolving it.
- Errored,
- /// A result arrived, but this fold could not make sense of it - a
- /// payload that did not match ACP's response shape, or an outcome ACP
- /// added after this was written.
- Unrecognized,
-}
-
-/// Why a turn stopped.
-///
-/// All but one variant is parsed straight off ACP's `stopReason` wire string
-/// by [`FromStr`]: the `snake_case` variant names are the wire names, and
-/// anything unmodelled falls through to [`Self::Other`], so parsing never
-/// fails. [`Self::Failed`] is the exception - no wire string produces it,
-/// because it is what a turn that got no `stopReason` at all stopped for.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(tag = "kind", rename_all = "snake_case")]
-pub enum StopReason {
- /// The agent finished its turn.
- EndTurn,
- /// The model hit its token limit.
- MaxTokens,
- /// The agent hit its turn-request limit.
- MaxTurnRequests,
- /// The agent declined.
- Refusal,
- /// The turn was cancelled.
- Cancelled,
- /// A stop reason this fold does not model, as its wire string.
- Other {
- /// The unrecognized wire value.
- reason: String,
- },
- /// The runtime answered the prompt with a JSON-RPC error, so the turn
- /// produced no reply and never will.
- ///
- /// Constructed by the fold, never parsed: an error response carries no
- /// `stopReason` to read. Modelled as a stop reason rather than as
- /// something alongside one because that is what it is - a turn that
- /// ended - and because every reader already asks `stop` whether a turn
- /// is still running. A turn left with no stop reason reads as forever in
- /// flight, which is how a failed prompt used to wedge a session.
- Failed {
- /// The runtime's error message, verbatim.
- message: String,
- },
-}
-
-impl FromStr for StopReason {
- type Err = std::convert::Infallible;
-
- fn from_str(reason: &str) -> Result<Self, Self::Err> {
- Ok(match reason {
- "end_turn" => Self::EndTurn,
- "max_tokens" => Self::MaxTokens,
- "max_turn_requests" => Self::MaxTurnRequests,
- "refusal" => Self::Refusal,
- "cancelled" => Self::Cancelled,
- reason => Self::Other {
- reason: reason.to_owned(),
- },
- })
- }
-}
-
-/// Session-level state derived from the log, latest-wins and carried whole.
-/// Fields start absent and fill in as the log reveals them.
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "camelCase")]
-pub struct SessionMetadata {
- /// Current model per the runtime's own `configOptions` responses, so a
- /// rejected model change never moves it.
- pub model: Option<String>,
- /// The models the runtime offers, in the order it listed them.
- pub supported_models: Vec<ModelOption>,
- /// Session title, when the harness reports one.
- pub title: Option<String>,
- /// The slash commands the harness most recently advertised, in the order
- /// it listed them. Empty until the first `available_commands_update`,
- /// which arrives right after session setup, before any turn.
- pub available_commands: Vec<AvailableCommand>,
- /// The last system event's wire name (`"acp_ready"`, `"disconnected"`),
- /// `None` until the runtime reports one.
- pub status: Option<String>,
-}
-
-/// One slash command the harness advertises.
-///
-/// Mirrors ACP's `AvailableCommand`, flattened: the only input shape ACP
-/// defines today is "unstructured text after the name," so the hint is
-/// carried directly rather than through a nested enum.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "camelCase")]
-pub struct AvailableCommand {
- /// Bare name as advertised (`"qc"`, `"honeycomb:query-patterns"`) - no
- /// leading slash, which is client syntax rather than part of the name.
- pub name: String,
- /// Human-readable description, verbatim from the harness.
- pub description: String,
- /// Placeholder text for the command's input, when it takes any.
- pub input_hint: Option<String>,
-}
-
-/// One model the runtime offers.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
-#[serde(rename_all = "camelCase")]
-pub struct ModelOption {
- /// The value to send back to select this model.
- pub id: String,
- /// Human-readable label.
- pub name: String,
- /// Descriptive copy - pricing, context size, and the like.
- pub description: Option<String>,
-}
-
-/// One change a pushed log frame implied. A push reports every change in
-/// order; most frames report none.
-///
-/// Payloads are borrowed from the machine and carried whole rather than as
-/// deltas: a consumer replaces what it holds under the same
-/// [`FoldedMessage::id`], or replaces its metadata outright.
-#[derive(Debug, Clone, PartialEq)]
-pub enum FoldEvent<'a> {
- /// A message the machine had not derived before. Reported exactly once
- /// per message, before any update to it.
- NewMessage(Cow<'a, FoldedMessage>),
- /// A message the machine had already reported, whose content changed.
- MessageUpdate(Cow<'a, FoldedMessage>),
- /// The metadata changed - restating identical metadata reports nothing.
- MetadataUpdated(Cow<'a, SessionMetadata>),
-}
-
-/// A fold event that owns whatever it carries.
-pub type OwnedFoldEvent = FoldEvent<'static>;
-
-impl FoldEvent<'_> {
- /// The message that changed, or `None` when this event is not about a
- /// message.
- #[must_use]
- pub fn message(&self) -> Option<&FoldedMessage> {
- match self {
- Self::NewMessage(message) | Self::MessageUpdate(message) => Some(message.as_ref()),
- Self::MetadataUpdated(_) => None,
- }
- }
-
- /// Own the payload so this event can cross a task boundary.
- #[must_use]
- pub fn into_owned(self) -> OwnedFoldEvent {
- match self {
- Self::NewMessage(message) => FoldEvent::NewMessage(Cow::Owned(message.into_owned())),
- Self::MessageUpdate(message) => {
- FoldEvent::MessageUpdate(Cow::Owned(message.into_owned()))
- }
- Self::MetadataUpdated(metadata) => {
- FoldEvent::MetadataUpdated(Cow::Owned(metadata.into_owned()))
- }
- }
- }
-}
diff --git a/crates/agent_fold/src/domain/model/event.rs b/crates/agent_fold/src/domain/model/event.rs
new file mode 100644
index 0000000000..83bd99079c
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/event.rs
@@ -0,0 +1,52 @@
+//! What one pushed frame changed.
+
+use std::borrow::Cow;
+
+use super::FoldedMessage;
+use super::metadata::SessionMetadata;
+
+/// One change a pushed log frame implied. A push reports every change in
+/// order; most frames report none.
+///
+/// Payloads are borrowed from the machine and carried whole rather than as
+/// deltas: a consumer replaces what it holds under the same
+/// [`FoldedMessage::id`], or replaces its metadata outright.
+#[derive(Debug, Clone, PartialEq)]
+pub enum FoldEvent<'a> {
+ /// A message the machine had not derived before. Reported exactly once
+ /// per message, before any update to it.
+ NewMessage(Cow<'a, FoldedMessage>),
+ /// A message the machine had already reported, whose content changed.
+ MessageUpdate(Cow<'a, FoldedMessage>),
+ /// The metadata changed - restating identical metadata reports nothing.
+ MetadataUpdated(Cow<'a, SessionMetadata>),
+}
+
+/// A fold event that owns whatever it carries.
+pub type OwnedFoldEvent = FoldEvent<'static>;
+
+impl FoldEvent<'_> {
+ /// The message that changed, or `None` when this event is not about a
+ /// message.
+ #[must_use]
+ pub fn message(&self) -> Option<&FoldedMessage> {
+ match self {
+ Self::NewMessage(message) | Self::MessageUpdate(message) => Some(message.as_ref()),
+ Self::MetadataUpdated(_) => None,
+ }
+ }
+
+ /// Own the payload so this event can cross a task boundary.
+ #[must_use]
+ pub fn into_owned(self) -> OwnedFoldEvent {
+ match self {
+ Self::NewMessage(message) => FoldEvent::NewMessage(Cow::Owned(message.into_owned())),
+ Self::MessageUpdate(message) => {
+ FoldEvent::MessageUpdate(Cow::Owned(message.into_owned()))
+ }
+ Self::MetadataUpdated(metadata) => {
+ FoldEvent::MetadataUpdated(Cow::Owned(metadata.into_owned()))
+ }
+ }
+ }
+}
diff --git a/crates/agent_fold/src/domain/model/metadata.rs b/crates/agent_fold/src/domain/model/metadata.rs
new file mode 100644
index 0000000000..9961a21fc7
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/metadata.rs
@@ -0,0 +1,91 @@
+//! Session-level state derived from the log.
+
+use serde::Serialize;
+use specta::Type;
+
+/// Which ACP agent produced a session's log.
+///
+/// ACP names none of a harness's conventions - which `_meta` keys it writes,
+/// what it calls its tools, how it reports a subagent - so the fold has to
+/// know who it is reading in order to read those. The agent announces itself
+/// in the `initialize` response's `agentInfo.name`; a log that starts
+/// mid-session (a resume) is recognized from the `_meta` namespaces its
+/// first tool frames carry instead. Carried on the metadata so a reader can
+/// show it and never has to infer it.
+///
+/// [`Self::Unknown`] is a real state, not a failure: every reader falls back
+/// to the harness-neutral conventions, and a harness this fold has not met
+/// still folds to the generic vocabulary.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum Harness {
+ /// `@agentclientprotocol/claude-agent-acp`.
+ ClaudeCode,
+ /// `OpenCode`, whose ACP server is built in.
+ OpenCode,
+ /// OpenAI Codex, through `codex-acp`.
+ Codex,
+ /// Cursor cloud agents, through this repository's `cursor_cloud_agents`.
+ Cursor,
+ /// Macro's own in-process agent, `agent_inmem`.
+ Macro,
+ /// Nous Research's Hermes agent.
+ Hermes,
+ /// OpenClaw.
+ OpenClaw,
+ /// Not announced, or an agent this fold does not know.
+ #[default]
+ Unknown,
+}
+
+/// Session-level state derived from the log, latest-wins and carried whole.
+/// Fields start absent and fill in as the log reveals them.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct SessionMetadata {
+ /// The agent that produced the log. See [`Harness`].
+ pub harness: Harness,
+ /// Current model per the runtime's own `configOptions` responses, so a
+ /// rejected model change never moves it.
+ pub model: Option<String>,
+ /// The models the runtime offers, in the order it listed them.
+ pub supported_models: Vec<ModelOption>,
+ /// Session title, when the harness reports one.
+ pub title: Option<String>,
+ /// The slash commands the harness most recently advertised, in the order
+ /// it listed them. Empty until the first `available_commands_update`,
+ /// which arrives right after session setup, before any turn.
+ pub available_commands: Vec<AvailableCommand>,
+ /// The last system event's wire name (`"acp_ready"`, `"disconnected"`),
+ /// `None` until the runtime reports one.
+ pub status: Option<String>,
+}
+
+/// One slash command the harness advertises.
+///
+/// Mirrors ACP's `AvailableCommand`, flattened: the only input shape ACP
+/// defines today is "unstructured text after the name," so the hint is
+/// carried directly rather than through a nested enum.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct AvailableCommand {
+ /// Bare name as advertised (`"qc"`, `"honeycomb:query-patterns"`) - no
+ /// leading slash, which is client syntax rather than part of the name.
+ pub name: String,
+ /// Human-readable description, verbatim from the harness.
+ pub description: String,
+ /// Placeholder text for the command's input, when it takes any.
+ pub input_hint: Option<String>,
+}
+
+/// One model the runtime offers.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ModelOption {
+ /// The value to send back to select this model.
+ pub id: String,
+ /// Human-readable label.
+ pub name: String,
+ /// Descriptive copy - pricing, context size, and the like.
+ pub description: Option<String>,
+}
diff --git a/crates/agent_fold/src/domain/model/part.rs b/crates/agent_fold/src/domain/model/part.rs
new file mode 100644
index 0000000000..7e9c958653
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/part.rs
@@ -0,0 +1,176 @@
+//! The parts a message is made of, and why a turn stopped.
+
+use std::str::FromStr;
+
+use serde::Serialize;
+use specta::Type;
+
+use super::ToolUseId;
+use super::permission::{PermissionOption, PermissionOutcome};
+use super::plan::PlanEntry;
+use super::tool::{ToolDetail, ToolName, ToolStatus};
+
+/// A unit of renderable content.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum MessagePart {
+ /// Prose from the user or the agent.
+ Text {
+ /// The prose.
+ text: String,
+ },
+ /// The agent's reasoning, which a reader may want to hide by default.
+ Thought {
+ /// The reasoning.
+ text: String,
+ },
+ /// A tool the agent invoked.
+ ToolUse {
+ /// The ACP `toolCallId`.
+ id: ToolUseId,
+ /// What the harness called the tool.
+ name: ToolName,
+ /// Where the call got to.
+ status: ToolStatus,
+ /// What the tool did, as far as the log reveals.
+ detail: ToolDetail,
+ },
+ /// The agent asking to proceed.
+ Permission {
+ /// The tool call permission was requested for.
+ #[serde(rename = "toolCall")]
+ tool_call: ToolUseId,
+ /// The choices offered, in the order ACP listed them.
+ options: Vec<PermissionOption>,
+ /// How the request has resolved so far.
+ outcome: PermissionOutcome,
+ },
+ /// A user-issued control operation on the session.
+ Control {
+ /// The requested operation.
+ control: Control,
+ /// How the runtime disposed of it so far.
+ outcome: ControlOutcome,
+ },
+ /// The agent's working todo list for the turn.
+ Plan {
+ /// The tasks, in the order the agent listed them.
+ entries: Vec<PlanEntry>,
+ },
+}
+
+impl MessagePart {
+ /// The parts nested inside this one: a subagent's own parts. `None` for
+ /// every other kind.
+ #[must_use]
+ pub fn children_mut(&mut self) -> Option<&mut Vec<MessagePart>> {
+ match self {
+ Self::ToolUse {
+ detail: ToolDetail::Subagent { children, .. },
+ ..
+ } => Some(children),
+ _ => None,
+ }
+ }
+
+ /// The parts nested inside this one, read-only. See [`Self::children_mut`].
+ #[must_use]
+ pub fn children(&self) -> &[MessagePart] {
+ match self {
+ Self::ToolUse {
+ detail: ToolDetail::Subagent { children, .. },
+ ..
+ } => children,
+ _ => &[],
+ }
+ }
+}
+
+/// A session control operation shown in the conversation timeline.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum Control {
+ /// The runtime was asked to switch models.
+ SetModel {
+ /// The model slug requested by the caller.
+ model: String,
+ },
+ /// The runtime was asked to compact its context.
+ Compact,
+ /// The runtime was asked to stop its current work.
+ Stop,
+}
+
+/// How the runtime disposed of a [`Control`], like [`PermissionOutcome`] for
+/// permission requests. Pending is a legitimate final state: a control the
+/// session died before answering stays pending.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ControlOutcome {
+ /// No response yet.
+ Pending,
+ /// Acknowledged - immediately so for a stop, which nothing can answer.
+ Accepted,
+ /// Answered with a JSON-RPC error.
+ Rejected {
+ /// The error's message, verbatim.
+ message: String,
+ },
+}
+
+/// Why a turn stopped.
+///
+/// All but one variant is parsed straight off ACP's `stopReason` wire string
+/// by [`FromStr`]: the `snake_case` variant names are the wire names, and
+/// anything unmodelled falls through to [`Self::Other`], so parsing never
+/// fails. [`Self::Failed`] is the exception - no wire string produces it,
+/// because it is what a turn that got no `stopReason` at all stopped for.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum StopReason {
+ /// The agent finished its turn.
+ EndTurn,
+ /// The model hit its token limit.
+ MaxTokens,
+ /// The agent hit its turn-request limit.
+ MaxTurnRequests,
+ /// The agent declined.
+ Refusal,
+ /// The turn was cancelled.
+ Cancelled,
+ /// A stop reason this fold does not model, as its wire string.
+ Other {
+ /// The unrecognized wire value.
+ reason: String,
+ },
+ /// The runtime answered the prompt with a JSON-RPC error, so the turn
+ /// produced no reply and never will.
+ ///
+ /// Constructed by the fold, never parsed: an error response carries no
+ /// `stopReason` to read. Modelled as a stop reason rather than as
+ /// something alongside one because that is what it is - a turn that
+ /// ended - and because every reader already asks `stop` whether a turn
+ /// is still running. A turn left with no stop reason reads as forever in
+ /// flight, which is how a failed prompt used to wedge a session.
+ Failed {
+ /// The runtime's error message, verbatim.
+ message: String,
+ },
+}
+
+impl FromStr for StopReason {
+ type Err = std::convert::Infallible;
+
+ fn from_str(reason: &str) -> Result<Self, Self::Err> {
+ Ok(match reason {
+ "end_turn" => Self::EndTurn,
+ "max_tokens" => Self::MaxTokens,
+ "max_turn_requests" => Self::MaxTurnRequests,
+ "refusal" => Self::Refusal,
+ "cancelled" => Self::Cancelled,
+ reason => Self::Other {
+ reason: reason.to_owned(),
+ },
+ })
+ }
+}
diff --git a/crates/agent_fold/src/domain/model/permission.rs b/crates/agent_fold/src/domain/model/permission.rs
new file mode 100644
index 0000000000..8b7cdf28d7
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/permission.rs
@@ -0,0 +1,68 @@
+//! Permission requests: the options offered and how the request resolved.
+
+use serde::Serialize;
+use specta::Type;
+
+/// One choice offered for a permission request.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PermissionOption {
+ /// The id to report back when this option is chosen.
+ pub id: String,
+ /// Label to show.
+ pub name: String,
+ /// What kind of choice this is.
+ pub kind: PermissionOptionKind,
+}
+
+/// What kind of choice a [`PermissionOption`] offers, mirroring ACP's
+/// `PermissionOptionKind`.
+///
+/// ACP's enum is `#[non_exhaustive]`, but unlike [`StopReason`] there is no
+/// wire string worth preserving for a variant this fold does not model: the
+/// fold only ever sees one of these once the whole permission request has
+/// already deserialized successfully, and a wire value ACP added after this
+/// was written would have failed that deserialize already - so an unmatched
+/// kind here cannot happen in practice, not "happens and is rendered
+/// unlabeled."
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum PermissionOptionKind {
+ /// Allow this operation only this time.
+ AllowOnce,
+ /// Allow this operation and remember the choice.
+ AllowAlways,
+ /// Reject this operation only this time.
+ RejectOnce,
+ /// Reject this operation and remember the choice.
+ RejectAlways,
+}
+
+/// How a permission request has resolved so far.
+///
+/// Not just "chosen or not": nothing chosen has more than one cause, and a
+/// reader deciding whether to still show the options needs to tell them
+/// apart. [`Self::Pending`] may still resolve; [`Self::Errored`] and
+/// [`Self::Unrecognized`] have already resolved, just not into anything this
+/// fold can show as a choice.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum PermissionOutcome {
+ /// No response has arrived yet - the request is still outstanding.
+ Pending,
+ /// An option was chosen.
+ Selected {
+ /// The chosen option's id.
+ #[serde(rename = "optionId")]
+ option_id: String,
+ },
+ /// The request was cancelled without a choice.
+ Cancelled,
+ /// The response was a JSON-RPC error rather than a result: the harness
+ /// failed to answer the request rather than resolving it.
+ Errored,
+ /// A result arrived, but this fold could not make sense of it - a
+ /// payload that did not match ACP's response shape, or an outcome ACP
+ /// added after this was written.
+ Unrecognized,
+}
diff --git a/crates/agent_fold/src/domain/model/plan.rs b/crates/agent_fold/src/domain/model/plan.rs
new file mode 100644
index 0000000000..97319a076d
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/plan.rs
@@ -0,0 +1,41 @@
+//! The agent's plan: a todo list carried whole on every update.
+
+use serde::Serialize;
+use specta::Type;
+
+/// One task on an agent plan.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PlanEntry {
+ /// What this task aims to accomplish.
+ pub content: String,
+ /// The task's relative importance.
+ pub priority: PlanEntryPriority,
+ /// Where the task got to.
+ pub status: PlanEntryStatus,
+}
+
+/// A [`PlanEntry`]'s relative importance, mirroring ACP's
+/// `PlanEntryPriority`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum PlanEntryPriority {
+ /// Critical to the overall goal.
+ High,
+ /// Important but not critical.
+ Medium,
+ /// Nice to have but not essential.
+ Low,
+}
+
+/// Where a [`PlanEntry`] got to, mirroring ACP's `PlanEntryStatus`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "snake_case")]
+pub enum PlanEntryStatus {
+ /// Not started yet.
+ Pending,
+ /// Currently being worked on.
+ InProgress,
+ /// Successfully completed.
+ Completed,
+}
diff --git a/crates/agent_fold/src/domain/model/subagent.rs b/crates/agent_fold/src/domain/model/subagent.rs
new file mode 100644
index 0000000000..1c63fe9288
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/subagent.rs
@@ -0,0 +1,96 @@
+//! Delegated agents: what a subagent was asked, what it did, what it said.
+
+use serde::Serialize;
+use specta::Type;
+
+/// What a subagent reported back, as far as its harness told us.
+///
+/// Every field is optional because every harness tells us a different
+/// subset: Claude Code reports timings, token counts and a per-tool
+/// breakdown; OpenCode names the child session and its model; Cursor and
+/// Hermes give back little more than the text. A reader shows what is
+/// there.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct SubagentResult {
+ /// The subagent's answer, as text.
+ pub text: Option<String>,
+ /// Why the subagent failed, when it did.
+ pub error: Option<String>,
+ /// The harness's id for the subagent or its session, for anyone who
+ /// wants to find it again.
+ pub agent_id: Option<String>,
+ /// The model the subagent ran on.
+ pub model: Option<String>,
+ /// Wall-clock time the subagent took. `u32` because the browser
+ /// contract forbids 64-bit integers; 49 days of milliseconds is plenty.
+ pub duration_ms: Option<u32>,
+ /// Tokens the subagent consumed. `u32` for the same reason.
+ pub tokens: Option<u32>,
+ /// How many tools the subagent called.
+ pub tool_uses: Option<u32>,
+ /// What kinds of tools the subagent called.
+ pub stats: Option<ToolStats>,
+}
+
+impl SubagentResult {
+ /// Whether nothing at all was reported.
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ *self == Self::default()
+ }
+
+ /// Take what `later` reports over what this holds, field by field - except
+ /// the answer text, which the first report of keeps. A harness that
+ /// reports its result twice (Claude Code: a rich `toolResponse`, then the
+ /// bare `rawOutput`) says the important part first.
+ pub fn merge(&mut self, later: Self) {
+ if self.text.is_none() {
+ self.text = later.text;
+ }
+ for (mine, theirs) in [
+ (&mut self.error, later.error),
+ (&mut self.agent_id, later.agent_id),
+ (&mut self.model, later.model),
+ ] {
+ if theirs.is_some() {
+ *mine = theirs;
+ }
+ }
+ for (mine, theirs) in [
+ (&mut self.duration_ms, later.duration_ms),
+ (&mut self.tokens, later.tokens),
+ ] {
+ if theirs.is_some() {
+ *mine = theirs;
+ }
+ }
+ if later.tool_uses.is_some() {
+ self.tool_uses = later.tool_uses;
+ }
+ if later.stats.is_some() {
+ self.stats = later.stats;
+ }
+ }
+}
+
+/// A subagent's tool use, by kind. Claude Code's `toolStats`, in the fold's
+/// vocabulary.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ToolStats {
+ /// Files read.
+ pub reads: u32,
+ /// Searches run.
+ pub searches: u32,
+ /// Shell commands run.
+ pub commands: u32,
+ /// Files edited.
+ pub edits: u32,
+ /// Lines added across those edits.
+ pub lines_added: u32,
+ /// Lines removed across those edits.
+ pub lines_removed: u32,
+ /// Anything else.
+ pub other: u32,
+}
diff --git a/crates/agent_fold/src/domain/model/tool.rs b/crates/agent_fold/src/domain/model/tool.rs
new file mode 100644
index 0000000000..3f6b3e15d0
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/tool.rs
@@ -0,0 +1,323 @@
+//! Tool calls: what one was called, how far it got, and what it did.
+
+use std::convert::Infallible;
+use std::path::PathBuf;
+use std::str::FromStr;
+
+use agent_client_protocol::schema::v1::ToolCallStatus;
+use lazy_regex::regex_captures;
+use serde::Serialize;
+use specta::Type;
+
+use super::part::MessagePart;
+use super::subagent::SubagentResult;
+use super::user_tool::UserToolOutcome;
+
+/// What a harness called a tool.
+///
+/// ACP has no tool-name field - a call carries a human-readable `title` and a
+/// coarse `kind`, nothing more. The name a reader wants (`Bash`, `ReadContent`)
+/// is a harness convention: Claude Code writes it to `_meta`, others put it
+/// in the title, and tools reached over MCP arrive namespaced as
+/// `mcp__<server>__<tool>`. This type is the one place that namespacing is
+/// understood, so no reader downstream ever splits a string.
+///
+/// Parsing is infallible: a string that is not an MCP name is a native one,
+/// however odd it looks. Nothing is dropped for being unrecognized.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ToolName {
+ /// A tool the harness owns: `Bash`, `Read`, `Write`, or a Macro tool
+ /// called in-process by Macro's own agent.
+ Native {
+ /// The name as the harness reported it.
+ name: String,
+ },
+ /// A tool reached over MCP, from the server the harness registered it
+ /// under.
+ Mcp {
+ /// The MCP server's name, as the harness registered it.
+ server: String,
+ /// The tool's name on that server.
+ tool: String,
+ },
+}
+
+impl ToolName {
+ /// A native name, as reported.
+ #[must_use]
+ pub fn native(name: impl Into<String>) -> Self {
+ Self::Native { name: name.into() }
+ }
+
+ /// The short name to show: the tool's own name, without any server
+ /// namespacing.
+ #[must_use]
+ pub fn display(&self) -> &str {
+ match self {
+ Self::Native { name } => name,
+ Self::Mcp { tool, .. } => tool,
+ }
+ }
+
+ /// Whether this name is empty - a call whose harness reported nothing
+ /// useful yet, which a later patch may fill in.
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ self.display().is_empty()
+ }
+}
+
+impl FromStr for ToolName {
+ type Err = Infallible;
+
+ /// `mcp__<server>__<tool>` splits at the first `__` after the prefix
+ /// whose left side does not start or end in an underscore, so a server
+ /// or tool name containing single underscores survives intact. Anything
+ /// else is a native name.
+ fn from_str(name: &str) -> Result<Self, Self::Err> {
+ Ok(
+ match regex_captures!(r"^mcp__([^_](?:.*?[^_])?)__(.+)$", name) {
+ Some((_, server, tool)) => Self::Mcp {
+ server: server.to_owned(),
+ tool: tool.to_owned(),
+ },
+ None => Self::Native {
+ name: name.to_owned(),
+ },
+ },
+ )
+ }
+}
+
+/// How far a tool call progressed.
+///
+/// [`ToolStatus::Pending`] and [`ToolStatus::Running`] are legitimate final
+/// states, not errors: a live session's newest calls have not finished, and a
+/// session that dies mid-call leaves one behind permanently.
+#[derive(
+ Debug,
+ Clone,
+ Copy,
+ Default,
+ PartialEq,
+ Eq,
+ strum::Display,
+ strum::IntoStaticStr,
+ Serialize,
+ Type,
+)]
+#[strum(serialize_all = "snake_case")]
+#[serde(rename_all = "snake_case")]
+pub enum ToolStatus {
+ /// Not started - either still streaming input or awaiting permission.
+ #[default]
+ Pending,
+ /// Currently running.
+ Running,
+ /// Finished successfully.
+ Completed,
+ /// Finished unsuccessfully.
+ Failed,
+}
+
+impl ToolStatus {
+ /// Whether the call is over, either way.
+ #[must_use]
+ pub const fn is_finished(self) -> bool {
+ matches!(self, Self::Completed | Self::Failed)
+ }
+}
+
+impl From<ToolCallStatus> for ToolStatus {
+ fn from(status: ToolCallStatus) -> Self {
+ match status {
+ ToolCallStatus::Pending => Self::Pending,
+ ToolCallStatus::InProgress => Self::Running,
+ ToolCallStatus::Completed => Self::Completed,
+ ToolCallStatus::Failed => Self::Failed,
+ // `ToolCallStatus` is `#[non_exhaustive]`; an unknown status has
+ // not demonstrably finished.
+ _ => Self::Pending,
+ }
+ }
+}
+
+/// What a tool call actually did.
+///
+/// Discriminated by what a reader needs in order to render it, not by ACP's
+/// [`ToolKind`](agent_client_protocol::ToolKind). A terminal wants command and
+/// output; an edit wants a diff; a handful of others want the paths they
+/// touched or whatever text they reported; everything else wants its raw
+/// input shown as JSON. Every named [`ToolKind`](agent_client_protocol::ToolKind)
+/// has a variant here, so the fold never falls back to [`Self::Other`] for a
+/// kind ACP defines - only for `switch_mode` (nothing a reader would want
+/// rendered) and a kind this fold does not yet know about.
+///
+/// Three variants are chosen by *name* rather than kind: Macro's own tools
+/// ([`Self::Macro`], [`Self::UserTool`]) arrive as ACP `other`, and what a
+/// reader wants for them is the tool's own JSON, not a generic card; a
+/// delegation ([`Self::Subagent`]) is a tool call by whatever name its
+/// harness gives it. The harness layer decides which names are which.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ToolDetail {
+ /// A shell command. ACP's `execute`.
+ Terminal {
+ /// The command line, when the harness reported one.
+ command: Option<String>,
+ /// Captured output, ANSI escapes intact. See [`AnsiText`].
+ output: Option<AnsiText>,
+ /// Process exit code, when the harness reported one.
+ #[serde(rename = "exitCode")]
+ exit_code: Option<i32>,
+ },
+ /// One or more file modifications. ACP's `edit`.
+ Edit {
+ /// The diffs ACP reported for this call.
+ diffs: Vec<FileDiff>,
+ },
+ /// A file read. ACP's `read`.
+ Read {
+ /// Paths this call touched.
+ paths: Vec<PathBuf>,
+ },
+ /// One or more files removed. ACP's `delete`.
+ Delete {
+ /// Paths this call touched.
+ paths: Vec<PathBuf>,
+ },
+ /// One or more files moved or renamed. ACP's `move`.
+ ///
+ /// Only the paths a reader can be sure of. ACP has no standard field for
+ /// "from" versus "to" - a call's `locations` is just the set of paths it
+ /// touched - so this does not guess at a direction.
+ Move {
+ /// Paths this call touched.
+ paths: Vec<PathBuf>,
+ },
+ /// A search. ACP's `search`.
+ Search {
+ /// Paths this call touched.
+ paths: Vec<PathBuf>,
+ /// Text the call reported - e.g. matched lines - when any.
+ output: Option<String>,
+ },
+ /// Retrieving external data. ACP's `fetch`.
+ Fetch {
+ /// Text the call reported, when any.
+ output: Option<String>,
+ },
+ /// Explicit reasoning surfaced as its own tool call, as distinct from
+ /// [`MessagePart::Thought`], which is reasoning streamed inline. ACP's
+ /// `think`.
+ Think {
+ /// Text the call reported, when any.
+ output: Option<String>,
+ },
+ /// Anything else: ACP's `switch_mode`, and any kind - including `other`
+ /// itself, [`ToolKind`](agent_client_protocol::ToolKind)'s default for a
+ /// call that names no kind at all - this fold has no special rendering
+ /// for.
+ Other {
+ /// ACP's tool kind, as its wire string.
+ #[serde(rename = "acpKind")]
+ kind: String,
+ /// Text the call reported, when any.
+ output: Option<String>,
+ /// The tool's input, when reported.
+ #[specta(type = specta_typescript::Unknown)]
+ input: Option<serde_json::Value>,
+ },
+ /// A Macro tool the fold knows by name - reached over Macro's MCP
+ /// server, or called in-process by Macro's own agent. Input and output
+ /// are the tool's own JSON, any MCP envelope already removed, so a
+ /// reader that knows the tool renders it without parsing the wire.
+ Macro {
+ /// The tool's arguments, as it defines them.
+ #[specta(type = specta_typescript::Unknown)]
+ input: serde_json::Value,
+ /// The tool's result, as it defines it; absent until the call
+ /// completes.
+ #[specta(type = specta_typescript::Unknown)]
+ output: Option<serde_json::Value>,
+ /// The error text, when the call failed.
+ error: Option<String>,
+ },
+ /// A Macro user tool: the agent drafted it, the user finishes it after
+ /// the turn. See [`UserToolOutcome`].
+ UserTool {
+ /// The draft, as the tool defines its arguments; patched as the
+ /// user edits.
+ #[specta(type = specta_typescript::Unknown)]
+ input: serde_json::Value,
+ /// Where the user got to with it.
+ outcome: UserToolOutcome,
+ },
+ /// Work the agent delegated to another agent.
+ ///
+ /// ACP has no notion of this; every harness spells it as a tool call by
+ /// its own conventions (Claude Code's `Agent`, OpenCode's and Cursor's
+ /// `task`, Codex's `spawnAgent`, Hermes's `delegate_task`), and the
+ /// harness reader recognizes it. What the subagent itself did nests in
+ /// `children` when the harness attributes its calls to the parent -
+ /// only Claude Code does today - and is otherwise summarized in
+ /// `result`.
+ Subagent {
+ /// What to call the delegation: the harness's description when it
+ /// gave one, else the first line of the brief, else the tool's own
+ /// name. Always present, so a reader never has to pick a fallback
+ /// itself; `description` and `prompt` stay exactly what the harness
+ /// said.
+ title: String,
+ /// Which kind of agent was delegated to (`general-purpose`,
+ /// `explore`), when the harness names one.
+ #[serde(rename = "agentType")]
+ agent_type: Option<String>,
+ /// A short description of the task, when given.
+ description: Option<String>,
+ /// The brief the subagent was given.
+ prompt: Option<String>,
+ /// Whether the subagent was started in the background: its call
+ /// completes at once and its answer, if any, arrives some other way.
+ background: bool,
+ /// The subagent's own parts, in arrival order, for a harness that
+ /// attributes them to the parent call.
+ children: Vec<MessagePart>,
+ /// What the subagent reported back, once it has.
+ ///
+ /// Boxed: this is by far the widest thing a part can hold, and every
+ /// part pays for the widest variant.
+ result: Option<Box<SubagentResult>>,
+ },
+}
+
+/// A file modification a tool reported.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct FileDiff {
+ /// The file that changed.
+ pub path: PathBuf,
+ /// Prior contents, absent when the file is new.
+ pub old_text: Option<String>,
+ /// New contents.
+ pub new_text: String,
+}
+
+/// Terminal output with ANSI escape sequences left in place.
+///
+/// Stripping here would be lossy and irreversible, and the escapes carry real
+/// information - the recordings are full of colorized `ls` and `grep` output.
+/// Rendering decides whether to interpret, strip, or ignore them.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(transparent)]
+#[specta(transparent)]
+pub struct AnsiText(pub String);
+
+impl AnsiText {
+ /// The raw text, escapes included.
+ #[must_use]
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
diff --git a/crates/agent_fold/src/domain/model/user_tool.rs b/crates/agent_fold/src/domain/model/user_tool.rs
new file mode 100644
index 0000000000..69ec29eb0d
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/user_tool.rs
@@ -0,0 +1,58 @@
+//! Macro user tools: drafted by the agent, finished by the user.
+
+use serde::Serialize;
+use specta::Type;
+
+/// How far a user tool has got - the fold's reading of the backend's
+/// `UserToolResponse`, restated each time the call is patched.
+///
+/// A user tool's call completes, from ACP's point of view, the moment the
+/// agent invokes it: the backend answers `"PendingUserExecution"` and does
+/// nothing. What happens next - the user editing, sending, or rejecting the
+/// draft - reaches the log as later patches to the same call, so
+/// [`Self::Pending`] is where every user tool starts and where one the user
+/// never touched stays.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum UserToolOutcome {
+ /// Awaiting the user. The draft is whatever the input currently holds.
+ Pending,
+ /// The user edited the draft without finishing it; the input holds
+ /// their edits.
+ Edited,
+ /// `SendEmail`: the email went out.
+ Sent {
+ /// The sent message's id.
+ #[serde(rename = "messageId")]
+ message_id: String,
+ /// The thread the message landed in.
+ #[serde(rename = "threadId")]
+ thread_id: String,
+ },
+ /// `SendEmail`: the user saved the draft instead of sending it.
+ Draft {
+ /// The saved draft's id.
+ #[serde(rename = "draftId")]
+ draft_id: String,
+ /// The thread the draft belongs to, when it is a reply.
+ #[serde(rename = "threadId")]
+ thread_id: Option<String>,
+ },
+ /// The user executed the tool; this is what the tool returned. The shape
+ /// is the tool's own - a calendar event for `CreateCalendarEvent`.
+ Completed {
+ /// The tool's result, verbatim.
+ #[specta(type = specta_typescript::Unknown)]
+ result: serde_json::Value,
+ },
+ /// The user declined.
+ Rejected,
+ /// The call itself failed before the user could act.
+ Failed {
+ /// The error, as reported.
+ message: String,
+ },
+ /// A result arrived that this fold could not read as a user tool
+ /// response - a shape the backend added after this was written.
+ Unrecognized,
+}
diff --git a/crates/agent_fold/src/domain/test.rs b/crates/agent_fold/src/domain/test.rs
index 8c77e86479..7a4bb7ef9c 100644
--- a/crates/agent_fold/src/domain/test.rs
+++ b/crates/agent_fold/src/domain/test.rs
@@ -2,9 +2,13 @@
//! [`util`] for what they share.
mod fold;
+mod harness;
+mod harness_readers;
mod machine;
-mod meta;
+mod macro_tools;
mod metadata;
mod real_recordings;
mod service;
+mod subagent;
+mod tool_name;
mod util;
diff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rs
index 26b823cf9d..a70a0a6ae2 100644
--- a/crates/agent_fold/src/domain/test/fold.rs
+++ b/crates/agent_fold/src/domain/test/fold.rs
@@ -57,7 +57,7 @@ fn folds_a_complete_turn() {
let MessagePart::ToolUse {
id: run_id,
- label: run_label,
+ name: run_name,
status: run_status,
detail: run_detail,
..
@@ -65,7 +65,11 @@ fn folds_a_complete_turn() {
else {
panic!("second part is the terminal call: {:?}", parts[1]);
};
- assert_eq!(run_label, "Bash", "harness tool name outranks ACP title");
+ assert_eq!(
+ run_name.display(),
+ "Bash",
+ "harness tool name outranks ACP title"
+ );
assert_eq!(*run_status, ToolStatus::Completed);
let ToolDetail::Terminal {
command,
@@ -106,7 +110,7 @@ fn folds_a_complete_turn() {
);
let MessagePart::ToolUse {
- label,
+ name,
status,
detail,
..
@@ -114,7 +118,7 @@ fn folds_a_complete_turn() {
else {
panic!("fourth part is the edit: {:?}", parts[3]);
};
- assert_eq!(label, "Write");
+ assert_eq!(name.display(), "Write");
assert_eq!(*status, ToolStatus::Completed);
let ToolDetail::Edit { diffs } = detail else {
panic!("edit folds to diffs: {detail:?}");
diff --git a/crates/agent_fold/src/domain/test/harness.rs b/crates/agent_fold/src/domain/test/harness.rs
new file mode 100644
index 0000000000..72856c0ea8
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/harness.rs
@@ -0,0 +1,161 @@
+use crate::domain::harness::{HarnessReader, claude_code, command_from_raw_input, generic};
+use crate::domain::model::{Harness, ToolName};
+use crate::domain::test::util::Frame;
+use agent_client_protocol::schema::v1::Meta;
+use serde_json::json;
+
+fn meta_of(value: serde_json::Value) -> Meta {
+ match value {
+ serde_json::Value::Object(map) => map,
+ other => panic!("meta must be an object, got {other}"),
+ }
+}
+
+#[test]
+fn claude_code_reads_its_namespaced_tool_name() {
+ let meta = meta_of(json!({"claudeCode": {"toolName": "Bash"}}));
+ assert_eq!(claude_code::tool_name(Some(&meta)), Some("Bash".to_owned()));
+ let frame = Frame::new().meta(json!({"claudeCode": {"toolName": "Bash"}}));
+ assert_eq!(
+ claude_code::ClaudeCode.reported_tool_name(&frame.view()),
+ Some(ToolName::native("Bash"))
+ );
+
+ let mcp = Frame::new().meta(json!({"claudeCode": {"toolName": "mcp__macro__ReadContent"}}));
+ assert_eq!(
+ claude_code::ClaudeCode.reported_tool_name(&mcp.view()),
+ Some(ToolName::Mcp {
+ server: "macro".to_owned(),
+ tool: "ReadContent".to_owned(),
+ })
+ );
+}
+
+#[test]
+fn macro_inmem_reads_its_namespaced_tool_name() {
+ let frame = Frame::new().meta(json!({"macro": {"toolName": "ReadContent"}}));
+ assert_eq!(
+ Harness::Macro.reader().reported_tool_name(&frame.view()),
+ Some(ToolName::native("ReadContent"))
+ );
+ // Another harness's namespace is not this one's.
+ let other = Frame::new().meta(json!({"claudeCode": {"toolName": "Bash"}}));
+ assert_eq!(
+ Harness::Macro.reader().reported_tool_name(&other.view()),
+ None
+ );
+}
+
+/// Terminal output is a client extension every harness writes the same way,
+/// so the generic reader answers it for a harness the fold does not know.
+#[test]
+fn terminal_output_and_exit_are_read_for_any_harness() {
+ let frame = Frame::new().meta(json!({
+ "terminal_output": {"terminal_id": "t1", "data": "\u{1b}[0mhello"},
+ "terminal_exit": {"terminal_id": "t1", "exit_code": 2, "signal": null},
+ }));
+ for harness in [Harness::Unknown, Harness::ClaudeCode, Harness::Macro] {
+ let reader = harness.reader();
+ assert_eq!(
+ reader.terminal_output(&frame.view()),
+ Some("\u{1b}[0mhello".to_owned()),
+ "{harness:?}"
+ );
+ assert_eq!(
+ reader.terminal_exit_code(&frame.view()),
+ Some(2),
+ "{harness:?}"
+ );
+ }
+}
+
+/// Missing keys, misshapen values, and absent meta all mean "no information".
+#[test]
+fn tolerates_absence_and_noise() {
+ let reader = Harness::ClaudeCode.reader();
+ let empty = Frame::new();
+ assert_eq!(reader.reported_tool_name(&empty.view()), None);
+ assert_eq!(generic::terminal_output(&empty.view()), None);
+ assert_eq!(generic::terminal_exit_code(&empty.view()), None);
+
+ let noise = Frame::new().meta(json!({
+ "claudeCode": "not an object",
+ "terminal_output": {"data": 7},
+ "terminal_exit": {"exit_code": "zero"},
+ }));
+ assert_eq!(reader.reported_tool_name(&noise.view()), None);
+ assert_eq!(generic::terminal_output(&noise.view()), None);
+ assert_eq!(generic::terminal_exit_code(&noise.view()), None);
+}
+
+#[test]
+fn reads_a_command_from_raw_input() {
+ let input = json!({"command": "ls -la", "description": "list"});
+ assert_eq!(
+ command_from_raw_input(Some(&input)),
+ Some("ls -la".to_owned())
+ );
+ assert_eq!(command_from_raw_input(Some(&json!({}))), None);
+ assert_eq!(command_from_raw_input(None), None);
+}
+
+#[test]
+fn recognizes_harnesses_from_their_announced_names() {
+ let cases = [
+ ("@agentclientprotocol/claude-agent-acp", Harness::ClaudeCode),
+ ("Claude Agent", Harness::ClaudeCode),
+ ("OpenCode", Harness::OpenCode),
+ ("codex-acp", Harness::Codex),
+ ("cursor-acp", Harness::Cursor),
+ ("macro-inmem", Harness::Macro),
+ ("hermes-agent", Harness::Hermes),
+ ("openclaw", Harness::OpenClaw),
+ ("zed", Harness::Unknown),
+ ("", Harness::Unknown),
+ ];
+ for (name, expected) in cases {
+ assert_eq!(Harness::from_agent_info(name), expected, "{name:?}");
+ if expected != Harness::Unknown {
+ assert!(
+ expected.reader().announces(name),
+ "{expected:?} claims {name:?}"
+ );
+ }
+ assert!(
+ !Harness::Unknown.reader().announces(name),
+ "Unknown is what is left, never a match"
+ );
+ }
+}
+
+#[test]
+fn sniffs_a_harness_from_the_frames_it_wrote() {
+ let claude =
+ Frame::new().meta(json!({"claudeCode": {"toolName": "Bash"}, "terminal_output": {}}));
+ assert_eq!(Harness::sniff(&claude.view()), Some(Harness::ClaudeCode));
+ let macro_ = Frame::new().meta(json!({"macro": {"toolName": "ReadContent"}}));
+ assert_eq!(Harness::sniff(&macro_.view()), Some(Harness::Macro));
+ let anonymous = Frame::new().meta(json!({"terminal_output": {"data": "x"}}));
+ assert_eq!(Harness::sniff(&anonymous.view()), None);
+ assert_eq!(Harness::sniff(&Frame::new().view()), None);
+}
+
+/// Every harness resolves to a reader, and the unknown one reads generically
+/// and claims nothing.
+#[test]
+fn every_harness_has_a_reader() {
+ for harness in [
+ Harness::ClaudeCode,
+ Harness::OpenCode,
+ Harness::Codex,
+ Harness::Cursor,
+ Harness::Macro,
+ Harness::Hermes,
+ Harness::OpenClaw,
+ Harness::Unknown,
+ ] {
+ let _ = harness.reader();
+ }
+ let frame = Frame::new().meta(json!({"claudeCode": {}, "macro": {}, "codex": {}}));
+ assert!(!Harness::Unknown.reader().wrote(&frame.view()));
+}
diff --git a/crates/agent_fold/src/domain/test/harness_readers.rs b/crates/agent_fold/src/domain/test/harness_readers.rs
new file mode 100644
index 0000000000..520a079773
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/harness_readers.rs
@@ -0,0 +1,404 @@
+//! The per-harness readers, against the frame shapes each harness's source
+//! confirms (see the research notes in the PR that added them). Where a real
+//! recording exists it is pinned in `real_recordings`; these pin the readers
+//! for harnesses we have read but not yet recorded.
+
+use crate::domain::model::{
+ AnsiText, Harness, MessagePart, SubagentResult, ToolDetail, ToolName, ToolStatus, ToolUseId,
+};
+use crate::domain::test::util::Frame;
+use agent_client_protocol::schema::v1::ToolKind;
+use serde_json::json;
+
+fn native(name: &str) -> ToolName {
+ ToolName::native(name)
+}
+
+// --- Codex (@agentclientprotocol/codex-acp, legacy collaboration mode) ---
+
+#[test]
+fn codex_names_mcp_tools_from_its_dotted_title_and_flag() {
+ let reader = Harness::Codex.reader();
+ let flagged = Frame::new()
+ .meta(json!({"is_mcp_tool_call": true}))
+ .title("mcp.macro.ReadContent");
+ assert_eq!(
+ reader.reported_tool_name(&flagged.view()),
+ Some(ToolName::Mcp {
+ server: "macro".to_owned(),
+ tool: "ReadContent".to_owned()
+ })
+ );
+ // Without the flag a dotted title is just a title.
+ let unflagged = Frame::new().title("mcp.macro.ReadContent");
+ assert_eq!(reader.reported_tool_name(&unflagged.view()), None);
+ let prose = Frame::new()
+ .meta(json!({"is_mcp_tool_call": true}))
+ .title("Editing files");
+ assert_eq!(reader.reported_tool_name(&prose.view()), None);
+}
+
+#[test]
+fn codex_spawn_agent_is_a_subagent_and_carries_its_result_in_raw_input() {
+ let reader = Harness::Codex.reader();
+ let collaboration =
+ |tool: &str| {
+ Frame::new().kind(ToolKind::Other).meta(json!({"codex": {"collaboration": {
+ "tool": tool, "senderThreadId": "thread-main", "receiverThreadIds": ["thread-paris"]
+ }}}))
+ };
+ assert!(reader.is_subagent(&native("spawnAgent"), &collaboration("spawnAgent").view()));
+ assert!(
+ !reader.is_subagent(&native("wait"), &collaboration("wait").view()),
+ "steering an existing subagent is not a delegation"
+ );
+ assert!(!reader.is_subagent(
+ &native("spawnAgent"),
+ &Frame::new().kind(ToolKind::Other).view()
+ ));
+
+ let frame = Frame::new().title("spawnAgent").raw_input(json!({
+ "prompt": "Find the current weather in Paris.",
+ "senderThreadId": "thread-main",
+ "receiverThreadIds": ["thread-paris"],
+ "agentsStates": {"thread-paris": {"status": "completed", "message": "Sunny, 24C"}},
+ "model": "gpt-5.4",
+ "reasoningEffort": null,
+ "status": "completed"
+ }));
+ let input = reader.subagent_input(&frame.view());
+ assert_eq!(
+ input.prompt.as_deref(),
+ Some("Find the current weather in Paris.")
+ );
+ let result = reader.subagent_result(&frame.view()).expect("reported");
+ assert_eq!(
+ result,
+ SubagentResult {
+ text: Some("Sunny, 24C".to_owned()),
+ agent_id: Some("thread-paris".to_owned()),
+ model: Some("gpt-5.4".to_owned()),
+ ..SubagentResult::default()
+ }
+ );
+
+ // The opening frame: no child yet, an empty model string means none.
+ let opening = Frame::new().raw_input(json!({
+ "prompt": "…", "senderThreadId": "thread-main", "receiverThreadIds": [],
+ "agentsStates": {}, "model": "", "status": "inProgress"
+ }));
+ assert_eq!(reader.subagent_result(&opening.view()), None);
+
+ let failed = Frame::new().raw_input(json!({
+ "receiverThreadIds": ["t"], "agentsStates": {"t": {"status": "errored", "message": "boom"}},
+ "status": "failed"
+ }));
+ let result = reader.subagent_result(&failed.view()).unwrap();
+ assert_eq!(result.error.as_deref(), Some("boom"));
+ assert_eq!(result.text, None);
+}
+
+/// Codex leaves two marks on its frames; either is enough to recognize it.
+#[test]
+fn codex_is_sniffed_from_either_of_its_meta_signals() {
+ let namespaced = Frame::new().meta(json!({"codex": {"collaboration": {"tool": "wait"}}}));
+ assert_eq!(Harness::sniff(&namespaced.view()), Some(Harness::Codex));
+ let flagged = Frame::new().meta(json!({"is_mcp_tool_call": true}));
+ assert_eq!(Harness::sniff(&flagged.view()), Some(Harness::Codex));
+ let unflagged = Frame::new().meta(json!({"is_mcp_tool_call": false}));
+ assert_eq!(Harness::sniff(&unflagged.view()), None);
+}
+
+// --- Cursor (cursor_cloud_agents) ---
+
+#[test]
+fn cursor_task_reads_its_oneof_subagent_type_and_ids() {
+ let reader = Harness::Cursor.reader();
+ assert!(reader.is_subagent(&native("task"), &Frame::new().kind(ToolKind::Other).view()));
+
+ let frame = Frame::new().title("task").raw_input(json!({
+ "description": "Find SSE decoding",
+ "prompt": "Find where SSE decoding happens.",
+ "subagentType": {"explore": {}},
+ "model": "composer-2.5-fast",
+ "agentId": "bc-f6167deb"
+ }));
+ let input = reader.subagent_input(&frame.view());
+ assert_eq!(input.agent_type.as_deref(), Some("explore"));
+ assert_eq!(input.description.as_deref(), Some("Find SSE decoding"));
+ assert_eq!(
+ input.prompt.as_deref(),
+ Some("Find where SSE decoding happens.")
+ );
+
+ let result = reader
+ .subagent_result(&frame.view())
+ .expect("ids are a result even before the answer");
+ assert_eq!(result.agent_id.as_deref(), Some("bc-f6167deb"));
+ assert_eq!(result.model.as_deref(), Some("composer-2.5-fast"));
+ assert_eq!(result.text, None);
+
+ // The other spellings of the oneof.
+ let agent_type = |raw_input: serde_json::Value| {
+ reader
+ .subagent_input(&Frame::new().raw_input(raw_input).view())
+ .agent_type
+ };
+ assert_eq!(
+ agent_type(json!({"subagentType": {"kind": "custom", "name": "reviewer"}})).as_deref(),
+ Some("reviewer")
+ );
+ assert_eq!(
+ agent_type(json!({"subagentType": {"kind": "explore"}})).as_deref(),
+ Some("explore")
+ );
+
+ // Proto defaults say nothing: no agent type, no model.
+ let defaults = Frame::new().raw_input(
+ json!({"subagentType": {"unspecified": {}}, "model": "default", "agentId": "bc-1"}),
+ );
+ assert_eq!(reader.subagent_input(&defaults.view()).agent_type, None);
+ let result = reader.subagent_result(&defaults.view()).unwrap();
+ assert_eq!(result.model, None);
+ assert_eq!(result.agent_id.as_deref(), Some("bc-1"));
+}
+
+/// The finished `task` call carries the child's transcript whole; it folds to
+/// nested parts, and the closing prose is the answer rather than a child.
+#[test]
+fn cursor_task_result_unfolds_the_childs_transcript() {
+ let reader = Harness::Cursor.reader();
+ let frame = Frame::new().raw_output(json!({"result": {"success": {
+ "agentId": "bc-child",
+ "durationMs": "12978",
+ "conversationSteps": [
+ {"thinkingMessage": {"text": "Use the shell.", "durationMs": 1168}},
+ {"assistantMessage": {"text": "Computing."}},
+ {"toolCall": {
+ "toolCallId": "call_1\nfc_1",
+ "shellToolCall": {
+ "args": {"command": "python3 -c 'import sympy'"},
+ "result": {"failure": {"stderr": "No module named 'sympy'\n", "exitCode": 1}, "isBackground": false}
+ }
+ }},
+ {"toolCall": {
+ "toolCallId": "call_2\nfc_2",
+ "shellToolCall": {
+ "args": {"command": "python3 -c 'print(124/3)'"},
+ "result": {"success": {"stdout": "41.3\n", "interleavedOutput": "41.3\n"}}
+ }
+ }},
+ {"toolCall": {
+ "toolCallId": "call_3",
+ "readToolCall": {"args": {"path": "/workspace/README.md"}, "result": {"success": {"path": "/workspace/README.md"}}}
+ }},
+ {"toolCall": {
+ "toolCallId": "call_4",
+ "brandNewToolCall": {"args": {"anything": 1}, "result": {"success": {}}}
+ }},
+ {"somethingElse": {"text": "a step kind this reader has never seen"}},
+ {"assistantMessage": {"text": "The exact value is **124/3**."}}
+ ]
+ }}}));
+
+ let result = reader.subagent_result(&frame.view()).unwrap();
+ assert_eq!(
+ result,
+ SubagentResult {
+ text: Some("The exact value is **124/3**.".to_owned()),
+ agent_id: Some("bc-child".to_owned()),
+ duration_ms: Some(12978),
+ tool_uses: Some(4),
+ ..SubagentResult::default()
+ }
+ );
+
+ let children = reader.subagent_transcript(&frame.view());
+ assert_eq!(
+ children,
+ vec![
+ MessagePart::Thought {
+ text: "Use the shell.".to_owned()
+ },
+ MessagePart::Text {
+ text: "Computing.".to_owned()
+ },
+ MessagePart::ToolUse {
+ id: ToolUseId("call_1 fc_1".to_owned()),
+ name: native("shell"),
+ status: ToolStatus::Failed,
+ detail: ToolDetail::Terminal {
+ command: Some("python3 -c 'import sympy'".to_owned()),
+ output: Some(AnsiText("No module named 'sympy'\n".to_owned())),
+ exit_code: Some(1),
+ },
+ },
+ MessagePart::ToolUse {
+ id: ToolUseId("call_2 fc_2".to_owned()),
+ name: native("shell"),
+ status: ToolStatus::Completed,
+ detail: ToolDetail::Terminal {
+ command: Some("python3 -c 'print(124/3)'".to_owned()),
+ output: Some(AnsiText("41.3\n".to_owned())),
+ exit_code: Some(0),
+ },
+ },
+ MessagePart::ToolUse {
+ id: ToolUseId("call_3".to_owned()),
+ name: native("read"),
+ status: ToolStatus::Completed,
+ detail: ToolDetail::Read {
+ paths: vec!["/workspace/README.md".into()],
+ },
+ },
+ // An unknown tool is kept by name; an unknown step kind is skipped.
+ MessagePart::ToolUse {
+ id: ToolUseId("call_4".to_owned()),
+ name: native("brandNew"),
+ status: ToolStatus::Pending,
+ detail: ToolDetail::Other {
+ kind: "other".to_owned(),
+ output: None,
+ input: None,
+ },
+ },
+ ]
+ );
+
+ // A failed task is an error, with nothing to nest.
+ let failed = Frame::new().raw_output(json!({"result": {"error": "agent crashed"}}));
+ let result = reader.subagent_result(&failed.view()).unwrap();
+ assert_eq!(result.error.as_deref(), Some("agent crashed"));
+ assert_eq!(result.text, None);
+ assert_eq!(reader.subagent_transcript(&failed.view()), vec![]);
+
+ // The opening frame carries no result and so no transcript.
+ assert_eq!(reader.subagent_transcript(&Frame::new().view()), vec![]);
+}
+
+// --- Hermes (hermes-agent) ---
+
+#[test]
+fn hermes_delegations_are_recognized_from_their_titles() {
+ let reader = Harness::Hermes.reader();
+ for title in [
+ "delegate: Find the flaky test",
+ "delegate batch (3 tasks)",
+ "delegate task",
+ ] {
+ let frame = Frame::new().title(title).kind(ToolKind::Execute);
+ let name = reader
+ .reported_tool_name(&frame.view())
+ .unwrap_or_else(|| panic!("{title:?} names delegate_task"));
+ assert_eq!(name, native("delegate_task"));
+ assert!(
+ reader.is_subagent(&name, &frame.view()),
+ "{title:?} is a delegation despite kind execute"
+ );
+ }
+ let shell = Frame::new().title("ls -la").kind(ToolKind::Execute);
+ assert_eq!(reader.reported_tool_name(&shell.view()), None);
+ assert!(!reader.is_subagent(&native("ls -la"), &shell.view()));
+
+ let input = reader.subagent_input(&Frame::new().title("delegate: Find the flaky test").view());
+ assert_eq!(input.prompt.as_deref(), Some("Find the flaky test"));
+ assert_eq!(
+ input.description.as_deref(),
+ Some("delegate: Find the flaky test")
+ );
+
+ let ok = reader
+ .subagent_result(
+ &Frame::new()
+ .text("Delegation results: 1 task(s) in 4s")
+ .view(),
+ )
+ .unwrap();
+ assert_eq!(
+ ok.text.as_deref(),
+ Some("Delegation results: 1 task(s) in 4s")
+ );
+ let failed = reader
+ .subagent_result(
+ &Frame::new()
+ .text("Delegation failed: pool exhausted")
+ .view(),
+ )
+ .unwrap();
+ assert_eq!(failed.error.as_deref(), Some("pool exhausted"));
+ assert_eq!(failed.text, None);
+}
+
+// --- OpenClaw (openclaw-acp) ---
+
+#[test]
+fn openclaw_names_tools_from_its_titles_and_reads_spawns() {
+ let reader = Harness::OpenClaw.reader();
+ let title =
+ "sessions_spawn: task: Investigate flaky test, label: flaky-test, runtime: subagent";
+ assert_eq!(
+ reader.reported_tool_name(&Frame::new().title(title).view()),
+ Some(native("sessions_spawn"))
+ );
+ assert_eq!(
+ reader.reported_tool_name(&Frame::new().title("read: path: /etc/hosts").view()),
+ Some(native("read"))
+ );
+ assert_eq!(
+ reader.reported_tool_name(&Frame::new().title("Plain title").view()),
+ None
+ );
+ let other = Frame::new().kind(ToolKind::Other);
+ assert!(reader.is_subagent(&native("sessions_spawn"), &other.view()));
+ assert!(!reader.is_subagent(&native("sessions_send"), &other.view()));
+
+ let frame = Frame::new().title(title).raw_input(json!({
+ "task": "Investigate flaky test",
+ "label": "flaky-test",
+ "runtime": "subagent"
+ }));
+ let input = reader.subagent_input(&frame.view());
+ assert_eq!(input.prompt.as_deref(), Some("Investigate flaky test"));
+ assert_eq!(input.description.as_deref(), Some("flaky-test"));
+ assert_eq!(input.agent_type.as_deref(), Some("subagent"));
+
+ let frame = frame.raw_output(json!({
+ "content": [{"type": "text", "text": "{\"status\":\"accepted\",\"childSessionKey\":\"agent:main:subagent:1f2e\",\"runId\":\"r1\"}"}],
+ "details": {"status": "accepted", "childSessionKey": "agent:main:subagent:1f2e", "runId": "r1"}
+ }));
+ let result = reader.subagent_result(&frame.view()).unwrap();
+ assert_eq!(result.agent_id.as_deref(), Some("agent:main:subagent:1f2e"));
+ assert_eq!(result.text, None, "an accepted spawn has no answer yet");
+
+ // Without `details`, the text block's JSON is read instead.
+ let text_only = Frame::new()
+ .raw_output(json!({"content": [{"type": "text", "text": "{\"childSessionKey\":\"k\"}"}]}));
+ assert_eq!(
+ reader
+ .subagent_result(&text_only.view())
+ .unwrap()
+ .agent_id
+ .as_deref(),
+ Some("k")
+ );
+}
+
+/// The harnesses that leave nothing distinctive on their tool frames cannot
+/// be sniffed; they are recognized from `initialize` alone.
+#[test]
+fn title_only_harnesses_are_not_sniffed() {
+ let anonymous = Frame::new()
+ .meta(json!({"terminal_output": {"data": "x"}}))
+ .title("task")
+ .kind(ToolKind::Other)
+ .raw_input(json!({"description": "d", "prompt": "p"}));
+ assert_eq!(Harness::sniff(&anonymous.view()), None);
+ for harness in [
+ Harness::OpenCode,
+ Harness::Cursor,
+ Harness::Hermes,
+ Harness::OpenClaw,
+ ] {
+ assert!(!harness.reader().wrote(&anonymous.view()), "{harness:?}");
+ }
+}
diff --git a/crates/agent_fold/src/domain/test/machine.rs b/crates/agent_fold/src/domain/test/machine.rs
index 0c7e471c17..47baf8c13e 100644
--- a/crates/agent_fold/src/domain/test/machine.rs
+++ b/crates/agent_fold/src/domain/test/machine.rs
@@ -318,7 +318,7 @@ fn a_tool_call_without_a_prompt_opens_a_turn() {
let agent = &consumer.messages[0];
assert_eq!(agent.id, TurnId(0));
assert!(
- matches!(&agent.parts[0], MessagePart::ToolUse { label, .. } if label == "Bash"),
+ matches!(&agent.parts[0], MessagePart::ToolUse { name, .. } if name.display() == "Bash"),
"and the call is its first part: {:?}",
agent.parts[0]
);
diff --git a/crates/agent_fold/src/domain/test/macro_tools.rs b/crates/agent_fold/src/domain/test/macro_tools.rs
new file mode 100644
index 0000000000..bbb7d19bfc
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/macro_tools.rs
@@ -0,0 +1,395 @@
+//! Macro tools reached over MCP, and the user tools among them, fold to
+//! their own details with the MCP envelope removed.
+
+use crate::domain::fold::{FoldMachineImpl, fold};
+use crate::domain::harness::{self, ToolShape, macro_tools, mcp};
+use crate::domain::model::{
+ Harness, MessagePart, SubagentResult, ToolDetail, ToolName, ToolStatus, UserToolOutcome,
+};
+use crate::domain::ports::FoldMachine;
+use crate::domain::test::util::Frame;
+use crate::testing::fixtures::MACRO_MCP;
+use crate::testing::parse_log;
+use agent_client_protocol::schema::v1::ToolKind;
+use serde_json::{Value, json};
+
+#[test]
+fn macro_mcp_calls_fold_to_macro_and_user_tool_details() {
+ let messages = fold(parse_log(MACRO_MCP));
+ let agent = messages
+ .iter()
+ .find(|message| message.author == crate::domain::model::Author::Agent)
+ .expect("the agent answered");
+ let tools: Vec<_> = agent
+ .parts
+ .iter()
+ .filter_map(|part| match part {
+ MessagePart::ToolUse {
+ name,
+ status,
+ detail,
+ ..
+ } => Some((name.display(), *status, detail)),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(tools.len(), 3, "three Macro calls: {tools:#?}");
+
+ let (name, status, detail) = tools[0];
+ assert_eq!(name, "ReadContent");
+ assert_eq!(status, ToolStatus::Completed);
+ let ToolDetail::Macro {
+ input,
+ output,
+ error,
+ } = detail
+ else {
+ panic!("ReadContent folds to a Macro detail: {detail:?}");
+ };
+ assert_eq!(
+ input,
+ &json!({"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}),
+ "input is the tool's own arguments, filled by the patch"
+ );
+ assert_eq!(
+ output.as_ref(),
+ Some(&json!({"content": {"text": "Q3 plan: ship the fold."}, "comments": []})),
+ "structuredContent wins over the text block"
+ );
+ assert_eq!(*error, None);
+
+ let (name, status, detail) = tools[1];
+ assert_eq!(name, "SendEmail");
+ assert_eq!(status, ToolStatus::Completed);
+ let ToolDetail::UserTool { input, outcome } = detail else {
+ panic!("SendEmail folds to a user tool: {detail:?}");
+ };
+ assert_eq!(
+ input["subject"], "Q3 plan (updated)",
+ "the user's edits patch the draft after the turn ended"
+ );
+ assert_eq!(
+ *outcome,
+ UserToolOutcome::Sent {
+ message_id: "9c4d2c6e-2f3a-4d1e-8b0a-5e6f7a8b9c0d".to_owned(),
+ thread_id: "1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d".to_owned(),
+ },
+ "the last synthetic update records what the user did"
+ );
+
+ let (name, status, detail) = tools[2];
+ assert_eq!(name, "ListEntities");
+ assert_eq!(status, ToolStatus::Failed);
+ let ToolDetail::Macro { output, error, .. } = detail else {
+ panic!("ListEntities folds to a Macro detail: {detail:?}");
+ };
+ assert_eq!(
+ error.as_deref(),
+ Some("Failed to list entities: permission denied"),
+ "isError text is the error"
+ );
+ assert_eq!(
+ output.as_ref(),
+ Some(&Value::String(
+ "Failed to list entities: permission denied".to_owned()
+ )),
+ "non-JSON text is kept as the output string"
+ );
+}
+
+/// A user tool's outcome walks pending → edited → sent as patches arrive,
+/// each restating the whole outcome.
+#[test]
+fn a_user_tool_outcome_follows_the_patches() {
+ let frames = parse_log(MACRO_MCP);
+ // Fold up to (not including) the two post-turn patches.
+ let before_user: Vec<_> = frames.iter().take(frames.len() - 2).cloned().collect();
+ let pending = user_tool_outcome(&fold(before_user));
+ assert_eq!(pending, UserToolOutcome::Pending);
+
+ let edited: Vec<_> = frames.iter().take(frames.len() - 1).cloned().collect();
+ assert_eq!(user_tool_outcome(&fold(edited)), UserToolOutcome::Edited);
+}
+
+fn user_tool_outcome(messages: &[crate::domain::model::FoldedMessage]) -> UserToolOutcome {
+ messages
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .find_map(|part| match part {
+ MessagePart::ToolUse {
+ detail: ToolDetail::UserTool { outcome, .. },
+ ..
+ } => Some(outcome.clone()),
+ _ => None,
+ })
+ .expect("a user tool part")
+}
+
+#[test]
+fn the_fixture_names_its_harness() {
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(MACRO_MCP) {
+ let _ = machine.push(entry);
+ }
+ assert_eq!(machine.metadata().harness, Harness::ClaudeCode);
+}
+
+#[test]
+fn unwraps_call_tool_results() {
+ // structuredContent wins.
+ let enveloped = json!({
+ "content": [{"type": "text", "text": "{\"a\":1}"}],
+ "structuredContent": {"a": 2},
+ "isError": false
+ });
+ assert_eq!(mcp::unwrap_call_result(&enveloped), (json!({"a": 2}), None));
+
+ // Else the first JSON-parsable text block.
+ let text_json = json!({"content": [{"type": "text", "text": "\"PendingUserExecution\""}]});
+ assert_eq!(
+ mcp::unwrap_call_result(&text_json),
+ (json!("PendingUserExecution"), None)
+ );
+
+ // Else the text, joined; an error envelope reports it as the error too.
+ let plain = json!({"content": [{"type": "text", "text": "nope"}, {"type": "text", "text": "really"}], "isError": true});
+ assert_eq!(
+ mcp::unwrap_call_result(&plain),
+ (json!("nope\nreally"), Some("nope\nreally".to_owned()))
+ );
+
+ // A bare array of blocks (how Claude Code copies `content`) reads the same.
+ let blocks = json!([{"type": "text", "text": "{\"ok\":true}"}]);
+ assert_eq!(
+ mcp::unwrap_call_result(&blocks),
+ (json!({"ok": true}), None)
+ );
+
+ // A tool's own JSON with a `content` field is not an envelope: only an
+ // array of typed blocks is. `ReadContent` returns exactly this shape.
+ let read_content = json!({"content": {"text": "Q3 plan"}, "comments": []});
+ assert_eq!(
+ mcp::unwrap_call_result(&read_content),
+ (read_content.clone(), None)
+ );
+ let string_content = json!({"content": "document text"});
+ assert_eq!(
+ mcp::unwrap_call_result(&string_content),
+ (string_content.clone(), None)
+ );
+ let untyped_items = json!({"content": [{"text": "no type"}]});
+ assert_eq!(
+ mcp::unwrap_call_result(&untyped_items),
+ (untyped_items.clone(), None)
+ );
+
+ // Anything else is already bare.
+ let bare = json!({"result": "done"});
+ assert_eq!(mcp::unwrap_call_result(&bare), (bare.clone(), None));
+ assert_eq!(mcp::unwrap_call_result(&json!("10")), (json!("10"), None));
+ // An empty content array carries nothing.
+ assert_eq!(
+ mcp::unwrap_call_result(&json!({"content": []})),
+ (Value::Null, None)
+ );
+}
+
+#[test]
+fn reads_user_tool_responses() {
+ let email = "SendEmail";
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &json!("PendingUserExecution")),
+ UserToolOutcome::Pending
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &json!("Rejected")),
+ UserToolOutcome::Rejected
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &json!({"UserAction": "userEdited"})),
+ UserToolOutcome::Edited
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(
+ email,
+ &json!({"UserAction": {"sent": {"message_id": "m", "thread_id": "t"}}})
+ ),
+ UserToolOutcome::Sent {
+ message_id: "m".to_owned(),
+ thread_id: "t".to_owned()
+ }
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(
+ email,
+ &json!({"UserAction": {"convertedToDraft": {"draft_id": "d"}}})
+ ),
+ UserToolOutcome::Draft {
+ draft_id: "d".to_owned(),
+ thread_id: None
+ }
+ );
+ // Another user tool's action is carried whole.
+ let event = json!({"id": "evt", "title": "Sync"});
+ assert_eq!(
+ macro_tools::user_tool_outcome("CreateCalendarEvent", &json!({"UserAction": event})),
+ UserToolOutcome::Completed {
+ result: event.clone()
+ }
+ );
+ // Shapes this fold does not know are named as such, never dropped.
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &json!({"UserAction": {"teleported": true}})),
+ UserToolOutcome::Unrecognized
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &json!({"other": 1})),
+ UserToolOutcome::Unrecognized
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &json!(42)),
+ UserToolOutcome::Unrecognized
+ );
+ assert_eq!(
+ macro_tools::user_tool_outcome(email, &Value::Null),
+ UserToolOutcome::Pending
+ );
+}
+
+/// Whose shape a call is in is decided by name first, then by the harness.
+#[test]
+fn tool_shape_puts_macro_tools_first_and_leaves_the_rest_to_the_harness() {
+ let parse = |name: &str| -> ToolName { name.parse().unwrap_or_else(|never| match never {}) };
+ let other = Frame::new().kind(ToolKind::Other);
+ let claude = Harness::ClaudeCode.reader();
+ assert_eq!(
+ harness::tool_shape(claude, &parse("mcp__macro__ReadContent"), &other.view()),
+ ToolShape::Macro("ReadContent")
+ );
+ assert_eq!(
+ harness::tool_shape(claude, &parse("mcp__macro__SendEmail"), &other.view()),
+ ToolShape::UserTool("SendEmail")
+ );
+ assert_eq!(
+ harness::tool_shape(claude, &parse("mcp__macro__Subagent"), &other.view()),
+ ToolShape::Subagent
+ );
+ // Another server's tool, whatever it is called, is the harness's to read.
+ assert_eq!(
+ harness::tool_shape(claude, &parse("mcp__deepwiki__Subagent"), &other.view()),
+ ToolShape::Harness
+ );
+ assert_eq!(
+ harness::tool_shape(
+ claude,
+ &parse("Bash"),
+ &Frame::new().kind(ToolKind::Execute).view()
+ ),
+ ToolShape::Harness
+ );
+ // The harness's own delegation tool is a subagent by its rule.
+ assert_eq!(
+ harness::tool_shape(
+ claude,
+ &parse("Task"),
+ &Frame::new().kind(ToolKind::Think).view()
+ ),
+ ToolShape::Subagent
+ );
+ // Macro's own agent calls its tools by bare name.
+ let inmem = Harness::Macro.reader();
+ assert_eq!(
+ harness::tool_shape(inmem, &parse("SendEmail"), &other.view()),
+ ToolShape::UserTool("SendEmail")
+ );
+ assert_eq!(
+ harness::tool_shape(inmem, &parse("Subagent"), &other.view()),
+ ToolShape::Subagent
+ );
+ // Any other harness only knows a bare `SendEmail` as its own.
+ assert_eq!(
+ harness::tool_shape(claude, &parse("SendEmail"), &other.view()),
+ ToolShape::Harness
+ );
+}
+
+/// Macro's `Subagent` answers in Macro's shape through every harness's
+/// wrapper; a harness's own delegation tool is read by its reader.
+#[test]
+fn subagent_result_reads_macro_subagent_through_the_harness_wrapper() {
+ let parse = |name: &str| -> ToolName { name.parse().unwrap_or_else(|never| match never {}) };
+ let answer = |text: &str| {
+ Some(SubagentResult {
+ text: Some(text.to_owned()),
+ ..SubagentResult::default()
+ })
+ };
+ // Over MCP: the response is a JSON text block inside the envelope.
+ let claude = Harness::ClaudeCode.reader();
+ let enveloped = Frame::new()
+ .raw_output(json!({"content": [{"type": "text", "text": "{\"result\":\"ten\"}"}]}));
+ assert_eq!(
+ harness::subagent_result(claude, &parse("mcp__macro__Subagent"), &enveloped.view()),
+ answer("ten")
+ );
+ // Natively: bare.
+ let inmem = Harness::Macro.reader();
+ let bare = Frame::new().raw_output(json!({"result": "ten"}));
+ assert_eq!(
+ harness::subagent_result(inmem, &parse("Subagent"), &bare.view()),
+ answer("ten")
+ );
+ // An in-process failure is the wrapper's error, not an answer.
+ let failed = Frame::new().raw_output(json!({"error": "pool exhausted"}));
+ assert_eq!(
+ harness::subagent_result(inmem, &parse("Subagent"), &failed.view()),
+ Some(SubagentResult {
+ error: Some("pool exhausted".to_owned()),
+ ..SubagentResult::default()
+ })
+ );
+ // No output yet, nothing reported - not even the streamed echo.
+ let streaming = Frame::new().text("echo").status(ToolStatus::Running);
+ assert_eq!(
+ harness::subagent_result(inmem, &parse("Subagent"), &streaming.view()),
+ None
+ );
+ // The same `{ "result" }` from the harness's own tool is not Macro's
+ // shape: the generic reading shows it as JSON text.
+ assert_eq!(
+ harness::subagent_result(claude, &parse("Task"), &bare.view()),
+ answer(r#"{"result":"ten"}"#)
+ );
+}
+
+/// Macro's in-process agent calls the same tools natively, with bare output.
+#[test]
+fn the_inmem_harness_reads_native_names_as_macro_tools_with_bare_output() {
+ let reader = Harness::Macro.reader();
+ assert_eq!(
+ reader.macro_tool(&ToolName::native("SendEmail")),
+ Some("SendEmail")
+ );
+ assert_eq!(
+ reader.macro_tool(&ToolName::Mcp {
+ server: "deepwiki".to_owned(),
+ tool: "ask".to_owned()
+ }),
+ None
+ );
+ assert_eq!(
+ reader.unwrap_tool_output(&json!({"result": "done"})),
+ (json!({"result": "done"}), None)
+ );
+ assert_eq!(
+ reader.unwrap_tool_output(&json!({"error": "boom"})),
+ (Value::Null, Some("boom".to_owned()))
+ );
+ // Other harnesses only know Macro's tools through its MCP server.
+ assert_eq!(
+ Harness::ClaudeCode
+ .reader()
+ .macro_tool(&ToolName::native("SendEmail")),
+ None
+ );
+}
diff --git a/crates/agent_fold/src/domain/test/meta.rs b/crates/agent_fold/src/domain/test/meta.rs
deleted file mode 100644
index 42c85ec451..0000000000
--- a/crates/agent_fold/src/domain/test/meta.rs
+++ /dev/null
@@ -1,57 +0,0 @@
-use crate::domain::meta::{claude_code, command_from_raw_input};
-use agent_client_protocol::schema::v1::Meta;
-use serde_json::json;
-
-fn meta_of(value: serde_json::Value) -> Meta {
- match value {
- serde_json::Value::Object(map) => map,
- other => panic!("meta must be an object, got {other}"),
- }
-}
-
-#[test]
-fn reads_the_harness_tool_name() {
- let meta = meta_of(json!({"claudeCode": {"toolName": "Bash"}}));
- assert_eq!(claude_code::tool_name(Some(&meta)), Some("Bash".to_owned()));
-}
-
-#[test]
-fn reads_terminal_output_and_exit() {
- let meta = meta_of(json!({
- "terminal_output": {"terminal_id": "t1", "data": "\u{1b}[0mhello"},
- "terminal_exit": {"terminal_id": "t1", "exit_code": 2, "signal": null},
- }));
- assert_eq!(
- claude_code::terminal_output(Some(&meta)),
- Some("\u{1b}[0mhello".to_owned())
- );
- assert_eq!(claude_code::terminal_exit_code(Some(&meta)), Some(2));
-}
-
-/// Missing keys, misshapen values, and absent meta all mean "no information".
-#[test]
-fn tolerates_absence_and_noise() {
- assert_eq!(claude_code::tool_name(None), None);
- assert_eq!(claude_code::terminal_output(None), None);
- assert_eq!(claude_code::terminal_exit_code(None), None);
-
- let noise = meta_of(json!({
- "claudeCode": "not an object",
- "terminal_output": {"data": 7},
- "terminal_exit": {"exit_code": "zero"},
- }));
- assert_eq!(claude_code::tool_name(Some(&noise)), None);
- assert_eq!(claude_code::terminal_output(Some(&noise)), None);
- assert_eq!(claude_code::terminal_exit_code(Some(&noise)), None);
-}
-
-#[test]
-fn reads_a_command_from_raw_input() {
- let input = json!({"command": "ls -la", "description": "list"});
- assert_eq!(
- command_from_raw_input(Some(&input)),
- Some("ls -la".to_owned())
- );
- assert_eq!(command_from_raw_input(Some(&json!({}))), None);
- assert_eq!(command_from_raw_input(None), None);
-}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap
index bd8372326f..6b3507dac5 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap
@@ -1,6 +1,6 @@
---
source: crates/agent_fold/src/domain/test/fold.rs
-assertion_line: 314
+assertion_line: 381
expression: agent.parts
---
NonEmpty {
@@ -9,21 +9,23 @@ NonEmpty {
id: ToolUseId(
"del",
),
- label: "del",
+ name: Native {
+ name: "del",
+ },
status: Completed,
detail: Delete {
paths: [
"/repo/dead.rs",
],
},
- raw_input: None,
- raw_output: None,
},
ToolUse {
id: ToolUseId(
"mv",
),
- label: "mv",
+ name: Native {
+ name: "mv",
+ },
status: Completed,
detail: Move {
paths: [
@@ -31,14 +33,14 @@ NonEmpty {
"/repo/to.rs",
],
},
- raw_input: None,
- raw_output: None,
},
ToolUse {
id: ToolUseId(
"search",
),
- label: "search",
+ name: Native {
+ name: "search",
+ },
status: Completed,
detail: Search {
paths: [
@@ -48,42 +50,42 @@ NonEmpty {
"1 match",
),
},
- raw_input: None,
- raw_output: None,
},
ToolUse {
id: ToolUseId(
"fetch",
),
- label: "fetch",
+ name: Native {
+ name: "fetch",
+ },
status: Completed,
detail: Fetch {
output: Some(
"page body",
),
},
- raw_input: None,
- raw_output: None,
},
ToolUse {
id: ToolUseId(
"think",
),
- label: "think",
+ name: Native {
+ name: "think",
+ },
status: Completed,
detail: Think {
output: Some(
"reasoning aloud",
),
},
- raw_input: None,
- raw_output: None,
},
ToolUse {
id: ToolUseId(
"mystery",
),
- label: "mystery",
+ name: Native {
+ name: "mystery",
+ },
status: Completed,
detail: Other {
kind: "other",
@@ -96,12 +98,6 @@ NonEmpty {
},
),
},
- raw_input: Some(
- Object {
- "foo": String("bar"),
- },
- ),
- raw_output: None,
},
],
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap
index 03cd51ebc2..91ffaf1503 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@command_invocation.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/command_invocation.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"opus[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap
index 7feeb71c06..a0b8c17e19 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@long_multi_resume.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/long_multi_resume.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"opus[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap
index 1b00b2aae9..9847c1902f 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@plan_todo.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"opus[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap
index 938db437ea..9f6bd24da0 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_multi_turn.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"opus[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap
index b36f3487ee..57eaf438dc 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@real_single_turn.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/real_single_turn.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"claude-fable-5[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap
index 03b7b26137..5568ff1f2f 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_and_continued.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"claude-fable-5[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap
index 509d6cef13..4226e6ce9b 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@resumed_no_prompt.jsonl.snap
@@ -5,6 +5,7 @@ expression: machine.metadata()
input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
---
SessionMetadata {
+ harness: ClaudeCode,
model: Some(
"opus[1m]",
),
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap
new file mode 100644
index 0000000000..54980839c3
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_claude_code.jsonl.snap
@@ -0,0 +1,56 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+assertion_line: 270
+expression: machine.metadata()
+input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl
+---
+SessionMetadata {
+ harness: ClaudeCode,
+ model: Some(
+ "opus[1m]",
+ ),
+ supported_models: [
+ ModelOption {
+ id: "default",
+ name: "Default (recommended)",
+ description: Some(
+ "Use the default model (currently Opus 5 (1M context)) · $5/$25 per Mtok",
+ ),
+ },
+ ModelOption {
+ id: "opus[1m]",
+ name: "Opus (1M context)",
+ description: Some(
+ "Opus 5 with 1M context · Best for everyday, complex tasks · $5/$25 per Mtok",
+ ),
+ },
+ ModelOption {
+ id: "claude-fable-5[1m]",
+ name: "Fable",
+ description: Some(
+ "Fable 5 · Most capable for your hardest and longest-running tasks · $10/$50 per Mtok",
+ ),
+ },
+ ModelOption {
+ id: "sonnet",
+ name: "Sonnet",
+ description: Some(
+ "Sonnet 5 · Efficient for routine tasks · $2/$10 per Mtok · promo through Aug 31",
+ ),
+ },
+ ModelOption {
+ id: "haiku",
+ name: "Haiku",
+ description: Some(
+ "Haiku 4.5 · Fastest for quick answers · $1/$5 per Mtok",
+ ),
+ },
+ ],
+ title: Some(
+ "Spawn subagent to add numbers with Python",
+ ),
+ available_commands: [],
+ status: Some(
+ "acp_ready",
+ ),
+}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap
new file mode 100644
index 0000000000..b777f2142b
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_cursor.jsonl.snap
@@ -0,0 +1,208 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: machine.metadata()
+input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonl
+---
+SessionMetadata {
+ harness: Cursor,
+ model: Some(
+ "default",
+ ),
+ supported_models: [
+ ModelOption {
+ id: "auto-smart",
+ name: "Auto",
+ description: None,
+ },
+ ModelOption {
+ id: "default",
+ name: "Auto",
+ description: None,
+ },
+ ModelOption {
+ id: "grok-4.6",
+ name: "Cursor Grok 4.6",
+ description: None,
+ },
+ ModelOption {
+ id: "composer-2.5",
+ name: "Composer 2.5",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-opus-5",
+ name: "Claude Opus 5",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-opus-4-8",
+ name: "Claude Opus 4.8",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.6-sol",
+ name: "GPT-5.6 Sol",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.5",
+ name: "GPT-5.5",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-fable-5-1",
+ name: "Claude Fable 5.1",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-fable-5",
+ name: "Claude Fable 5",
+ description: None,
+ },
+ ModelOption {
+ id: "grok-4.5",
+ name: "Cursor Grok 4.5",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-3.8-flash",
+ name: "Gemini 3.8 Flash",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-3.7-flash",
+ name: "Gemini 3.7 Flash",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.6-terra",
+ name: "GPT-5.6 Terra",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-sonnet-5",
+ name: "Claude Sonnet 5",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-sonnet-4-6",
+ name: "Claude Sonnet 4.6",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.3-codex",
+ name: "Codex 5.3",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-opus-4-7",
+ name: "Claude Opus 4.7",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.4",
+ name: "GPT-5.4",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-opus-4-6",
+ name: "Claude Opus 4.6",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-opus-4-5",
+ name: "Claude Opus 4.5",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.2",
+ name: "GPT-5.2",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.6-luna",
+ name: "GPT-5.6 Luna",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-3.6-flash",
+ name: "Gemini 3.6 Flash",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-3.1-pro",
+ name: "Gemini 3.1 Pro",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.4-mini",
+ name: "GPT-5.4 Mini",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.4-nano",
+ name: "GPT-5.4 Nano",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-haiku-4-5",
+ name: "Claude Haiku 4.5",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-sonnet-4-5",
+ name: "Claude Sonnet 4.5",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5.1",
+ name: "GPT-5.1",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-3-flash",
+ name: "Gemini 3 Flash",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-3.5-flash",
+ name: "Gemini 3.5 Flash",
+ description: None,
+ },
+ ModelOption {
+ id: "claude-sonnet-4",
+ name: "Claude Sonnet 4",
+ description: None,
+ },
+ ModelOption {
+ id: "gpt-5-mini",
+ name: "GPT-5 Mini",
+ description: None,
+ },
+ ModelOption {
+ id: "gemini-2.5-flash",
+ name: "Gemini 2.5 Flash",
+ description: None,
+ },
+ ModelOption {
+ id: "kimi-k3",
+ name: "Kimi K3",
+ description: None,
+ },
+ ModelOption {
+ id: "kimi-k2.7-code",
+ name: "Kimi K2.7 Code",
+ description: None,
+ },
+ ModelOption {
+ id: "glm-5.2",
+ name: "GLM 5.2",
+ description: None,
+ },
+ ],
+ title: None,
+ available_commands: [],
+ status: Some(
+ "acp_ready",
+ ),
+}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap
new file mode 100644
index 0000000000..b366a4c848
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_macro_inmem.jsonl.snap
@@ -0,0 +1,15 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: machine.metadata()
+input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl
+---
+SessionMetadata {
+ harness: Macro,
+ model: None,
+ supported_models: [],
+ title: None,
+ available_commands: [],
+ status: Some(
+ "acp_ready",
+ ),
+}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap
new file mode 100644
index 0000000000..90a19996c5
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@subagent_opencode.jsonl.snap
@@ -0,0 +1,60 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+assertion_line: 270
+expression: machine.metadata()
+input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonl
+---
+SessionMetadata {
+ harness: OpenCode,
+ model: Some(
+ "openai/gpt-5.6-terra",
+ ),
+ supported_models: [
+ ModelOption {
+ id: "openai/gpt-5.4",
+ name: "OpenAI/GPT-5.4",
+ description: None,
+ },
+ ModelOption {
+ id: "openai/gpt-5.5",
+ name: "OpenAI/GPT-5.5",
+ description: None,
+ },
+ ModelOption {
+ id: "openai/gpt-5.6-terra",
+ name: "OpenAI/GPT-5.6 Terra",
+ description: None,
+ },
+ ModelOption {
+ id: "openai/gpt-5.6-terra-fast",
+ name: "OpenAI/GPT-5.6 Terra Fast",
+ description: None,
+ },
+ ],
+ title: None,
+ available_commands: [
+ AvailableCommand {
+ name: "dump-schema",
+ description: "Dump clean Postgres schema to a file and copy path to clipboard.",
+ input_hint: None,
+ },
+ AvailableCommand {
+ name: "init",
+ description: "guided AGENTS.md setup",
+ input_hint: None,
+ },
+ AvailableCommand {
+ name: "qc",
+ description: "Quality gate. 5 parallel agents review changes. All must pass.",
+ input_hint: None,
+ },
+ AvailableCommand {
+ name: "review",
+ description: "review changes [commit|branch|pr], defaults to uncommitted",
+ input_hint: None,
+ },
+ ],
+ status: Some(
+ "acp_ready",
+ ),
+}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap
index 66cb3a878b..3ace8fd73c 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap
@@ -63,7 +63,9 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
id: ToolUseId(
"toolu_01VWRTvryJTnQLFGHiTsBXYT",
),
- label: "ToolSearch",
+ name: Native {
+ name: "ToolSearch",
+ },
status: Completed,
detail: Other {
kind: "other",
@@ -77,42 +79,14 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
},
),
},
- raw_input: Some(
- Object {
- "query": String("todo list write tasks"),
- "max_results": Number(5),
- },
- ),
- raw_output: Some(
- Array [
- Object {
- "type": String("tool_reference"),
- "tool_name": String("TaskList"),
- },
- Object {
- "type": String("tool_reference"),
- "tool_name": String("CronList"),
- },
- Object {
- "type": String("tool_reference"),
- "tool_name": String("ListMcpResourcesTool"),
- },
- Object {
- "type": String("tool_reference"),
- "tool_name": String("mcp__macro__ListEntities"),
- },
- Object {
- "type": String("tool_reference"),
- "tool_name": String("mcp__macro__ListCompanies"),
- },
- ],
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01DCbqRyKnRaqmDNHoFB7MNi",
),
- label: "ToolSearch",
+ name: Native {
+ name: "ToolSearch",
+ },
status: Completed,
detail: Other {
kind: "other",
@@ -126,24 +100,6 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl
},
),
},
- raw_input: Some(
- Object {
- "query": String("select:TaskCreate,TaskUpdate"),
- "max_results": Number(3),
- },
- ),
- raw_output: Some(
- Array [
- Object {
- "type": String("tool_reference"),
- "tool_name": String("TaskCreate"),
- },
- Object {
- "type": String("tool_reference"),
- "tool_name": String("TaskUpdate"),
- },
- ],
- ),
},
Plan {
entries: [
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
index f5894fa269..0a374116a7 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@real_multi_turn.jsonl.snap
@@ -42,7 +42,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_01F5V288iQ8iArGM4B3ayCFm",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -57,15 +59,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls -la ~/.agent_runtime_sessions/ 2>/dev/null && echo \"---\" && for f in ~/.agent_runtime_sessions/*.jsonl; do echo \"$f: $(wc -l < \"$f\") lines, modified $(stat -f '%Sm' \"$f\")\"; done"),
- "description": String("List session recording files with line counts and mtimes"),
- },
- ),
- raw_output: Some(
- String("total 196\ndrwxr-xr-x 4 eric staff 128 Aug 3 16:08 \u{1b}[0m\u{1b}[01;34m.\u{1b}[0m\ndrwxr-x--- 131 eric staff 4192 Aug 3 16:21 \u{1b}[01;34m..\u{1b}[0m\n-rw-r--r-- 1 eric staff 181929 Aug 3 16:23 2026-08-03T20-08-59Z.jsonl\ndrwxr-xr-x 9 eric staff 288 Aug 3 11:12 \u{1b}[01;34mclaude_config\u{1b}[0m\n---\nstat: cannot read file system information for '%Sm': No such file or directory\n/Users/eric/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl: 166 lines, modified File: \"/Users/eric/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl\"\n ID: 100000e0000001a Namelen: ? Type: apfs\nBlock size: 4096 Fundamental block size: 4096\nBlocks: Total: 242837545 Free: 44364140 Available: 44364140\nInodes: Total: 1781145734 Free: 1774565600"),
- ),
},
Permission {
tool_call: ToolUseId(
@@ -99,7 +92,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_01T6GAjr5YEZpBifkp3vj1N9",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -114,15 +109,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -o '\"method\":\"[^\"]*\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort | uniq -c | sort -rn; echo \"---\"; grep -c 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo \"--- sessionIds:\"; grep -o '\"sessionId\":\"[^\"]*\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort -u; echo \"--- first/last ts:\"; head -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\"ts\":\"[^\"]*\"'; tail -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\"ts\":\"[^\"]*\"'"),
- "description": String("Count methods, session/new calls, and distinct sessionIds in the recording"),
- },
- ),
- raw_output: Some(
- String(" 144 \"method\":\"session/update\"\n 6 \"method\":\"session/request_permission\"\n 5 \"method\":\"session/prompt\"\n 2 \"method\":\"session/new\"\n 1 \"method\":\"session/set_config_option\"\n 1 \"method\":\"session/load\"\n 1 \"method\":\"initialize\"\n---\n4\n--- sessionIds:\n\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\"\n\"sessionId\":\"ab25cf29-d876-4ec6-9c30-dac24f13bcfe\"\n\"sessionId\":\"cdf15e0e-c8b7-486e-93de-f596f547e641\"\n--- first/last ts:\n\"ts\":\"2026-08-03T20:08:59.828Z\"\n\"ts\":\"2026-08-03T20:23:55.404Z\""),
- ),
},
Text {
text: "Found it — the recorder isn't broken, but it records **one file per process**, not per session, and Zed keeps the agent-server process alive across sessions.\n\n**What the data shows:** There's exactly one file, `2026-08-03T20-08-59Z.jsonl`, created at 16:08 local and still growing at 16:23. Inside it there are 2 `session/new` calls, 1 `session/load`, and **3 distinct sessionIds** — all of your \"new sessions\" from the last 15 minutes are in that one file.\n\n**Why:** In `main()` the recording path is computed once from `Utc::now()` at process startup, and there's one writer task for the lifetime of the process. Zed spawns your agent-server binary once and then multiplexes: each new session in the Zed UI is just a `session/new` (or `session/load`) JSON-RPC call over the same stdio connection to the same process. The recorder never sees a \"new session\" as an event worth rotating on — it just taps the channel and appends everything to the file named at spawn time. You'll only get a new file when Zed restarts the agent process (e.g. Zed restart, or the agent server gets killed).\n\n**Your other two theories:**\n- **Buffering** — not the issue. `run_writer` flushes after every line, and the mtime confirms lines are landing in real time.\n- **Timestamp overwriting** — not what's happening here, but it *is* a latent bug: `File::create` truncates, and the name only has second precision, so two processes spawned within the same second would clobber each other. Using `OpenOptions::create_new` (or appending) would make that fail loudly instead.\n\nIf you want one JSONL per session, the fix is to key recordings off the ACP session rather than the process: watch the tapped messages in `record_channel` for `session/new` / `session/load` responses, and route each line to a per-sessionId file (named e.g. `<timestamp>-<sessionId>.jsonl`). Pre-session traffic (`initialize`) could go to the first session's file or a shared prelude. Want me to make that change?",
@@ -171,7 +157,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_0166v7nKJaZsGG5TUqPcomaa",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -186,21 +174,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("head -c 2000 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo; echo \"=== session/new lines ===\"; grep -n 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | head -20"),
- "description": String("Inspect recorded line structure and session/new occurrences"),
- },
- ),
- raw_output: Some(
- String("{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"event\",\"event\":\"acp_ready\"}}\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"dcb750c2-712b-4aa0-a41a-414b7af61bc9\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":1,\"clientCapabilities\":{\"fs\":{\"readTextFile\":true,\"writeTextFile\":true},\"terminal\":true,\"session\":{\"configOptions\":{\"boolean\":{}}},\"auth\":{\"terminal\":true},\"elicitation\":{\"form\":{},\"url\":{}},\"_meta\":{\"terminal_output\":true,\"terminal-auth\":true}},\"clientInfo\":{\"name\":\"zed\",\"title\":\"Zed\",\"version\":\"1.13.2+stable.335.5cdb7ab9d9546db683132cfa78e68acec3064cac\"}}}}\n{\"ts\":\"2026-08-03T20:09:02.777Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"dcb750c2-712b-4aa0-a41a-414b7af61bc9\",\"result\":{\"protocolVersion\":1,\"agentCapabilities\":{\"_meta\":{\"claudeCode\":{\"promptQueueing\":true}},\"promptCapabilities\":{\"image\":true,\"embeddedContext\":true},\"mcpCapabilities\":{\"http\":true,\"sse\":true},\"auth\":{\"logout\":{}},\"providers\":{},\"loadSession\":true,\"sessionCapabilities\":{\"additionalDirectories\":{},\"close\":{},\"delete\":{},\"fork\":{},\"list\":{},\"resume\":{}}},\"agentInfo\":{\"name\":\"@agentclientprotocol/claude-agent-acp\",\"title\":\"Claude Agent\",\"version\":\"0.64.2\"},\"authMethods\":[{\"description\":\"Use Claude subscription \",\"name\":\"Claude Subscription\",\"id\":\"claude-ai-login\",\"type\":\"terminal\",\"args\":[\"--cli\",\"auth\",\"login\",\"--claudeai\"],\"_meta\":{\"terminal-auth\":{\"command\":\"/opt/homebrew/Cellar/node/25.8.0/bin/node\",\"args\":[\"/Users/eric/.npm/_npx/539edbc7afd0f13d/node_modules/.bin/claude-agent-acp\",\"--cli\",\"auth\",\"login\",\"--claudeai\"],\"label\":\"Claude Login\"}}},{\"description\":\"Use Anthropic Console (API usage billing)\",\"name\":\"Anthropic Console\",\"id\":\"console-login\",\"type\":\"terminal\",\"args\":[\"--cli\",\"auth\",\"login\",\"--console\"],\"_meta\":{\"terminal-auth\":{\"command\":\"/opt/homebrew/Cellar/node/25.8.0/bin/node\",\"args\":[\"/Users/eric/.npm/_npx/539edbc7afd0f13d/node_modules/.bin/claude-agent-acp\",\"--\n=== session/new lines ===\n45:{\"ts\":\"2026-08-03T20:09:06.609Z\",\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"51de871c-e1c8-4c6a-b215-c4e748f49222\",\"method\":\"session/new\",\"params\":{\"cwd\":\"/Users/eric/Code/macro\",\"mcpServers\":[]}}}\n151:{\"ts\":\"2026-08-03T20:21:47.595Z\",\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"e50a70c1-02c2-4e30-958d-5414acb302bb\",\"method\":\"session/new\",\"params\":{\"cwd\":\"/Users/eric/Code/macro\",\"mcpServers\":[]}}}\n174:{\"ts\":\"2026-08-03T20:23:55.019Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\"}},\"toolCallId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"sessionUpdate\":\"tool_call_update\",\"rawInput\":{\"command\":\"grep -o '\\\"method\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort | uniq -c | sort -rn; echo \\\"---\\\"; grep -c 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo \\\"--- sessionIds:\\\"; grep -o '\\\"sessionId\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort -u; echo \\\"--- first/last ts:\\\"; head -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'; tail -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'\"},\"title\":\"grep -o '\\\"method\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort | uniq -c | sort -rn; echo \\\"---\\\"; grep -c 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo \\\"--- sessionIds:\\\"; grep -o '\\\"sessionId\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort -u; echo \\\"--- first/last ts:\\\"; head -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'; tail -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'\",\"kind\":\"execute\"}}}}\n175:{\"ts\":\"2026-08-03T20:23:55.380Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\",\"title\":\"Count methods, session/new calls, and distinct sessionIds in the recording\"}},\"toolCallId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"sessionUpdate\":\"tool_call_update\",\"rawInput\":{\"command\":\"grep -o '\\\"method\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort | uniq -c | sort -rn; echo \\\"---\\\"; grep -c 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo \\\"--- sessionIds:\\\"; grep -o '\\\"sessionId\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort -u; echo \\\"--- first/last ts:\\\"; head -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'; tail -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'\",\"description\":\"Count methods, session/new calls, and distinct sessionIds in the recording\"},\"title\":\"grep -o '\\\"method\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort | uniq -c | sort -rn; echo \\\"---\\\"; grep -c 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo \\\"--- sessionIds:\\\"; grep -o '\\\"sessionId\\\":\\\"[^\\\"]*\\\"' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | sort -u; echo \\\"--- first/last ts:\\\"; head -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'; tail -1 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | grep -o '\\\"ts\\\":\\\"[^\\\"]*\\\"'\",\"kind\":\"execute\",\"content\":[{\"type\":\"terminal\",\"terminalId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\"}]}}}}\n177:{\"ts\":\"2026-08-03T20:23:55.490Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"claudeCode\":{\"toolResponse\":{\"stdout\":\" 144 \\\"method\\\":\\\"session/update\\\"\\n 6 \\\"method\\\":\\\"session/request_permission\\\"\\n 5 \\\"method\\\":\\\"session/prompt\\\"\\n 2 \\\"method\\\":\\\"session/new\\\"\\n 1 \\\"method\\\":\\\"session/set_config_option\\\"\\n 1 \\\"method\\\":\\\"session/load\\\"\\n 1 \\\"method\\\":\\\"initialize\\\"\\n---\\n4\\n--- sessionIds:\\n\\\"sessionId\\\":\\\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\\\"\\n\\\"sessionId\\\":\\\"ab25cf29-d876-4ec6-9c30-dac24f13bcfe\\\"\\n\\\"sessionId\\\":\\\"cdf15e0e-c8b7-486e-93de-f596f547e641\\\"\\n--- first/last ts:\\n\\\"ts\\\":\\\"2026-08-03T20:08:59.828Z\\\"\\n\\\"ts\\\":\\\"2026-08-03T20:23:55.404Z\\\"\",\"stderr\":\"\",\"interrupted\":false,\"isImage\":false,\"noOutputExpected\":false},\"toolName\":\"Bash\"}},\"toolCallId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"sessionUpdate\":\"tool_call_update\"}}}}\n178:{\"ts\":\"2026-08-03T20:23:55.490Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"terminal_output\":{\"terminal_id\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"data\":\" 144 \\\"method\\\":\\\"session/update\\\"\\n 6 \\\"method\\\":\\\"session/request_permission\\\"\\n 5 \\\"method\\\":\\\"session/prompt\\\"\\n 2 \\\"method\\\":\\\"session/new\\\"\\n 1 \\\"method\\\":\\\"session/set_config_option\\\"\\n 1 \\\"method\\\":\\\"session/load\\\"\\n 1 \\\"method\\\":\\\"initialize\\\"\\n---\\n4\\n--- sessionIds:\\n\\\"sessionId\\\":\\\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\\\"\\n\\\"sessionId\\\":\\\"ab25cf29-d876-4ec6-9c30-dac24f13bcfe\\\"\\n\\\"sessionId\\\":\\\"cdf15e0e-c8b7-486e-93de-f596f547e641\\\"\\n--- first/last ts:\\n\\\"ts\\\":\\\"2026-08-03T20:08:59.828Z\\\"\\n\\\"ts\\\":\\\"2026-08-03T20:23:55.404Z\\\"\"}},\"toolCallId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"sessionUpdate\":\"tool_call_update\"}}}}\n179:{\"ts\":\"2026-08-03T20:23:55.490Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\"},\"terminal_exit\":{\"terminal_id\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"exit_code\":0,\"signal\":null}},\"toolCallId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\",\"sessionUpdate\":\"tool_call_update\",\"status\":\"completed\",\"rawOutput\":\" 144 \\\"method\\\":\\\"session/update\\\"\\n 6 \\\"method\\\":\\\"session/request_permission\\\"\\n 5 \\\"method\\\":\\\"session/prompt\\\"\\n 2 \\\"method\\\":\\\"session/new\\\"\\n 1 \\\"method\\\":\\\"session/set_config_option\\\"\\n 1 \\\"method\\\":\\\"session/load\\\"\\n 1 \\\"method\\\":\\\"initialize\\\"\\n---\\n4\\n--- sessionIds:\\n\\\"sessionId\\\":\\\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\\\"\\n\\\"sessionId\\\":\\\"ab25cf29-d876-4ec6-9c30-dac24f13bcfe\\\"\\n\\\"sessionId\\\":\\\"cdf15e0e-c8b7-486e-93de-f596f547e641\\\"\\n--- first/last ts:\\n\\\"ts\\\":\\\"2026-08-03T20:08:59.828Z\\\"\\n\\\"ts\\\":\\\"2026-08-03T20:23:55.404Z\\\"\",\"content\":[{\"type\":\"terminal\",\"terminalId\":\"toolu_01T6GAjr5YEZpBifkp3vj1N9\"}]}}}}\n184:{\"ts\":\"2026-08-03T20:24:14.147Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\":23. Inside it there are 2 `session/new` calls, 1 `session/load`, and **3 distinct sessionIds** — all of your \\\"new sessions\\\" from the last\"},\"messageId\":\"msg_011CdgSVP7J2iCeSj8d6Apw3\"}}}}\n187:{\"ts\":\"2026-08-03T20:24:14.147Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\" agent-server binary once and then multiplexes: each new session in the Zed UI is just a `session/new` (or `session/load`) JSON-RPC call\"},\"messageId\":\"msg_011CdgSVP7J2iCeSj8d6Apw3\"}}}}\n197:{\"ts\":\"2026-08-03T20:24:14.179Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"session/new` / `session/load` responses, and route each line to a per-sessionId file (named\"},\"messageId\":\"msg_011CdgSVP7J2iCeSj8d6Apw3\"}}}}\n209:{\"ts\":\"2026-08-03T20:25:49.678Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\"}},\"toolCallId\":\"toolu_0166v7nKJaZsGG5TUqPcomaa\",\"sessionUpdate\":\"tool_call_update\",\"rawInput\":{\"command\":\"head -c 2000 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo; echo \\\"=== session/new lines ===\\\"; grep -n 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | head -20\"},\"title\":\"head -c 2000 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo; echo \\\"=== session/new lines ===\\\"; grep -n 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | head -20\",\"kind\":\"execute\"}}}}\n210:{\"ts\":\"2026-08-03T20:25:50.207Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\",\"title\":\"Inspect recorded line structure and session/new occurrences\"}},\"toolCallId\":\"toolu_0166v7nKJaZsGG5TUqPcomaa\",\"sessionUpdate\":\"tool_call_update\",\"rawInput\":{\"command\":\"head -c 2000 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo; echo \\\"=== session/new lines ===\\\"; grep -n 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | head -20\",\"description\":\"Inspect recorded line structure and session/new occurrences\"},\"title\":\"head -c 2000 ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl; echo; echo \\\"=== session/new lines ===\\\"; grep -n 'session/new' ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl | head -20\",\"kind\":\"execute\",\"content\":[{\"type\":\"terminal\",\"terminalId\":\"toolu_0166v7nKJaZsGG5TUqPcomaa\"}]}}}}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01BSkUBhuv3VSJMmEXidfKDZ",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -215,15 +196,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("find /Users/eric/Code/macro/crates/agent_session /Users/eric/Code/macro/crates/agent_runtime_protocol -name '*.rs' | head -50"),
- "description": String("List source files in agent_session and agent_runtime_protocol crates"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs\n/Users/eric/Code/macro/crates/agent_session/src/lib.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/events.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/mock_container.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/websocket.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/acp.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/lib.rs\n/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs\n/Users/eric/Code/macro/crates/agent_session/src/outbound/mod.rs\n/Users/eric/Code/macro/crates/agent_session/src/domain/ports.rs\n/Users/eric/Code/macro/crates/agent_session/src/domain/error.rs\n/Users/eric/Code/macro/crates/agent_session/src/domain/mod.rs\n/Users/eric/Code/macro/crates/agent_session/src/domain/model.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/mock_container/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/bin/export_types.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/fake_wire.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/wire_conformance.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/ports.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/channel.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/mod.rs\n/Users/eric/Code/macro/crates/agent_session/src/outbound/postgres/test.rs\n/Users/eric/Code/macro/crates/agent_session/src/outbound/postgres/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/fake_wire/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/websocket/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/websocket/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/mod.rs"),
- ),
},
Text {
text: "Let me look at the protocol types, the recorder's test file, and how these fixtures get consumed, so the routing matches the real message shapes.",
@@ -232,47 +204,37 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_015cPCzRzsgaeC5T4RKwfcqt",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/src/domain/model.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/src/domain/model.rs"),
- },
- ),
- raw_output: Some(
- String("1\tuse agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};\n2\tuse bots::domain::models::BotId;\n3\tuse chrono::{DateTime, Utc};\n4\tuse macro_user_id::user_id::MacroUserIdStr;\n5\tuse macro_uuid::Uuid;\n6\tuse serde::{Deserialize, Serialize};\n7\t\n8\tpub struct UninitializedSession;\n9\t\n10\t#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n11\tpub struct AgentSessionId(Uuid);\n12\t\n13\timpl AgentSessionId {\n14\t /// Wrap an existing UUID as an agent session id.\n15\t pub fn new_from_uuid(id: Uuid) -> Self {\n16\t Self(id)\n17\t }\n18\t\n19\t /// The underlying UUID.\n20\t pub fn as_uuid(&self) -> Uuid {\n21\t self.0\n22\t }\n23\t}\n24\t\n25\t#[derive(Debug, Clone, Default)]\n26\tpub enum SessionStatus {\n27\t /// No status updates received\n28\t #[default]\n29\t NoMessages,\n30\t /// EventRecieved from container\n31\t Event(SystemEvent),\n32\t /// A session disconnected without sending a clsoed event\n33\t Disconnected,\n34\t}\n35\t\n36\t/// A running or historical agent coding session.\n37\t#[derive(Debug, Clone)]\n38\tpub struct AgentSession<SessionId> {\n39\t /// id of the agent session\n40\t pub id: SessionId,\n41\t /// if this was created by `@` in a thread\n42\t pub created_from_thread_id: Option<Uuid>,\n43\t /// the thread id of the comms thread\n44\t pub thread_id: Uuid,\n45\t /// the bot id of the bot running the agent\n46\t pub bot_id: BotId,\n47\t /// model slug - TODO: probably a better type here\n48\t pub model: String,\n49\t /// harness slug - TODO: probably a better type here\n50\t pub harness: String,\n51\t /// repo we are working with\n52\t pub repo_url: String,\n53\t /// ACP session if we have one\n54\t pub acp_session_id: Option<String>,\n55\t pub status: SessionStatus,\n56\t pub created_at: DateTime<Utc>,\n57\t pub modified_at: DateTime<Utc>,\n58\t}\n59\t\n60\t/// One logical protocol message with its direction.\n61\t///\n62\t/// Serializes as `{\"direction\": \"to_server\" | \"to_runtime\", \"content\": <envelope>}`,\n63\t/// the same vocabulary the Postgres log storage uses for its `direction` and\n64\t/// `content` columns, so recorded fixtures and stored rows share one wire\n65\t/// format.\n66\t#[derive(Debug, Clone, Serialize, Deserialize)]\n67\t#[serde(tag = \"direction\", content = \"content\", rename_all = \"snake_case\")]\n68\tpub enum Message {\n69\t ToServer(ToServerMessage),\n70\t ToRuntime(ToRuntimeMessage),\n71\t}\n72\t\n73\t#[derive(Debug, Clone)]\n74\tpub struct AgentSessionLog {\n75\t pub agent_session_id: AgentSessionId,\n76\t /// if this is ACP sent by a user this will be Some\n77\t pub user_id: Option<MacroUserIdStr<'static>>,\n78\t pub content: Message,\n79\t}\n80\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01ULC7SdcZW6QpLwibk2SdF9",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs"),
- },
- ),
- raw_output: Some(
- String("1\tuse serde_json::{Value, json};\n2\tuse tokio::time::{Duration, timeout};\n3\t\n4\tuse super::*;\n5\t\n6\t#[test]\n7\tfn recording_path_is_timestamped_jsonl_under_home() {\n8\t let now = DateTime::parse_from_rfc3339(\"2026-08-03T14:22:07Z\")\n9\t .expect(\"timestamp should parse\")\n10\t .with_timezone(&Utc);\n11\t\n12\t assert_eq!(\n13\t recording_path(Path::new(\"/home/user\"), now),\n14\t PathBuf::from(\"/home/user/.agent_runtime_sessions/2026-08-03T14-22-07Z.jsonl\"),\n15\t );\n16\t}\n17\t\n18\t#[tokio::test]\n19\tasync fn tap_records_and_forwards_both_directions() {\n20\t let (inner, mut runtime_side) = Channel::duplex();\n21\t let (sink, mut lines) = mpsc::unbounded_channel();\n22\t let mut tapped = record_channel(inner, sink);\n23\t\n24\t // Runtime -> service traffic is forwarded and recorded as to_server.\n25\t runtime_side\n26\t .tx\n27\t .send(ToServerMessage::Event {\n28\t event: SystemEvent::AcpReady,\n29\t })\n30\t .expect(\"tap should be listening\");\n31\t let forwarded = timeout(Duration::from_secs(1), tapped.rx.recv())\n32\t .await\n33\t .expect(\"runtime message should be forwarded promptly\")\n34\t .expect(\"tapped channel should stay open\");\n35\t assert!(matches!(\n36\t forwarded,\n37\t ToServerMessage::Event {\n38\t event: SystemEvent::AcpReady\n39\t }\n40\t ));\n41\t\n42\t // Service -> runtime traffic is forwarded and recorded as to_runtime.\n43\t let prompt: ToRuntimeMessage = serde_json::from_value(json!({\n44\t \"type\": \"acp\",\n45\t \"jsonrpc\": \"2.0\",\n46\t \"id\": 1,\n47\t \"method\": \"session/prompt\",\n48\t \"params\": { \"sessionId\": \"sess-1\", \"prompt\": [] },\n49\t }))\n50\t .expect(\"envelope should deserialize\");\n51\t tapped.tx.send(prompt).expect(\"tap should be listening\");\n52\t let forwarded = timeout(Duration::from_secs(1), runtime_side.rx.recv())\n53\t .await\n54\t .expect(\"service message should be forwarded promptly\")\n55\t .expect(\"runtime channel should stay open\");\n56\t assert!(matches!(forwarded, ToRuntimeMessage::Acp(_)));\n57\t\n58\t // Each direction was recorded before it was forwarded, so by the time\n59\t // the forwards above were observed both lines are already in the sink,\n60\t // in send order. Each line is Message's own serialization plus `ts`, so\n61\t // it parses straight back into Message.\n62\t let event_line = lines.recv().await.expect(\"event line\");\n63\t let event_value: Value =\n64\t serde_json::from_str(&event_line).expect(\"recorded line should be JSON\");\n65\t assert_eq!(event_value[\"direction\"], \"to_server\");\n66\t assert_eq!(\n67\t event_value[\"content\"],\n68\t json!({\"type\": \"event\", \"event\": \"acp_ready\"})\n69\t );\n70\t DateTime::parse_from_rfc3339(event_value[\"ts\"].as_str().expect(\"ts should be a string\"))\n71\t .expect(\"ts should be RFC 3339\");\n72\t let event_message: Message =\n73\t serde_json::from_str(&event_line).expect(\"line should parse as Message\");\n74\t assert!(matches!(\n75\t event_message,\n76\t Message::ToServer(ToServerMessage::Event {\n77\t event: SystemEvent::AcpReady\n78\t })\n79\t ));\n80\t\n81\t let prompt_line = lines.recv().await.expect(\"prompt line\");\n82\t let prompt_value: Value =\n83\t serde_json::from_str(&prompt_line).expect(\"recorded line should be JSON\");\n84\t assert_eq!(prompt_value[\"direction\"], \"to_runtime\");\n85\t assert_eq!(prompt_value[\"content\"][\"type\"], \"acp\");\n86\t assert_eq!(prompt_value[\"content\"][\"method\"], \"session/prompt\");\n87\t assert_eq!(prompt_value[\"content\"][\"params\"][\"sessionId\"], \"sess-1\");\n88\t let prompt_message: Message =\n89\t serde_json::from_str(&prompt_line).expect(\"line should parse as Message\");\n90\t assert!(matches!(\n91\t prompt_message,\n92\t Message::ToRuntime(ToRuntimeMessage::Acp(_))\n93\t ));\n94\t}\n95\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018WB6FehVLcrszUvj598DeC",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -287,21 +249,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n 'Acp\\|acp' /Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/mod.rs | head -40"),
- "description": String("Find ACP message variants in protocol schema"),
- },
- ),
- raw_output: Some(
- String("11://! needs an agent or agent-instance identifier: [`AcpMessage`] simply carries\n26:/// through [`SystemEvent::Unknown`]. [`SystemEvent::AcpReady`] is the one\n44: AcpReady,\n54: Self::AcpReady => \"acp_ready\",\n75: \"acp_ready\" => Self::AcpReady,\n89:/// tagged `Acp` variant, which requires its payload provably serialize as an\n94:/// it looks through to the map type below instead of treating `AcpMessage`\n98:pub struct AcpMessage(\n108: Acp(AcpMessage),\n117: Acp(AcpMessage),"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01FMZq9Myj3VrRZScNV2vx4o",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -316,21 +271,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("sed -n '80,130p' /Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/mod.rs"),
- "description": String("Read AcpMessage and message enum definitions"),
- },
- ),
- raw_output: Some(
- String("/// One complete ACP JSON-RPC message routed between the Agent Service and the\n/// single agent execution hosted by this connection.\n///\n/// Its own JSON-RPC fields are opaque to TypeScript consumers here (typed as\n/// an arbitrary object of unknown values): they already have a proper ACP SDK\n/// on the TypeScript side, so this crate only needs to guarantee the message\n/// round-trips unchanged. This is typed as a map rather than plain `unknown`\n/// because [`ToRuntimeMessage`]/[`ToServerMessage`] carry it in an internally\n/// tagged `Acp` variant, which requires its payload provably serialize as an\n/// object so the `\"type\"` tag can be merged into it. `#[serde(transparent)]`\n/// changes nothing about the actual wire format here - a single-field tuple\n/// struct already serializes transparently by default - but it does tell\n/// specta's serde-compatibility checker that this newtype is transparent, so\n/// it looks through to the map type below instead of treating `AcpMessage`\n/// itself as an opaque, non-mergeable struct.\n#[derive(Debug, Clone, Serialize, Deserialize, Type)]\n#[serde(transparent)]\npub struct AcpMessage(\n #[specta(type = std::collections::HashMap<String, Unknown>)] pub RawJsonRpcMessage,\n);\n\n/// Agent Service to Agent Runtime traffic on the logical protocol stream.\n#[derive(Debug, Clone, Serialize, Deserialize, Type)]\n#[serde(tag = \"type\", rename_all = \"camelCase\")]\n#[non_exhaustive]\npub enum ToRuntimeMessage {\n /// An ACP message routed to the hosted agent.\n Acp(AcpMessage),\n}\n\n/// Agent Runtime to Agent Service traffic on the logical protocol stream.\n#[derive(Debug, Clone, Serialize, Deserialize, Type)]\n#[serde(tag = \"type\", rename_all = \"camelCase\")]\n#[non_exhaustive]\npub enum ToServerMessage {\n /// An ACP message routed from the hosted agent.\n Acp(AcpMessage),\n /// A runtime or agent lifecycle event.\n Event {\n /// The event name.\n #[specta(type = String)]\n event: SystemEvent,\n },\n}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01352etHpBLWV1h8TL9UTmdc",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -345,21 +293,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn 'RawJsonRpcMessage' /Users/eric/Code/macro/crates/agent_runtime_protocol/src/ | head; grep -rn 'home_dir\\|edition' /Users/eric/Code/macro/crates/agent_session/Cargo.toml"),
- "description": String("Find RawJsonRpcMessage definition and crate edition"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/websocket/test.rs:1:use agent_client_protocol::RawJsonRpcMessage;\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/websocket/test.rs:18: RawJsonRpcMessage::notification(\"session/update\".to_owned(), json!({ \"foo\": \"bar\" }))\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/test.rs:1:use agent_client_protocol::RawJsonRpcMessage;\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/test.rs:66: let nested = RawJsonRpcMessage::request(\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/test.rs:4:use agent_client_protocol::RawJsonRpcMessage;\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/test.rs:80: let initialize = RawJsonRpcMessage::request(\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/test.rs:105: .unbounded_send(Ok(RawJsonRpcMessage::response(\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/mod.rs:14:use agent_client_protocol::RawJsonRpcMessage;\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/mod.rs:99: #[specta(type = std::collections::HashMap<String, Unknown>)] pub RawJsonRpcMessage,\n/Users/eric/Code/macro/crates/agent_session/Cargo.toml:4:edition = \"2024\""),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01V4uph7ZkZKaPpgF6UE4Nop",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -374,21 +315,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n 'agent_client_protocol\\|agent-client-protocol' /Users/eric/Code/macro/Cargo.toml /Users/eric/Code/macro/crates/agent_session/Cargo.toml; find ~/.cargo/registry/src -maxdepth 2 -name 'agent-client-protocol*' -o -maxdepth 2 -name 'agent_client_protocol*' 2>/dev/null | head"),
- "description": String("Locate agent_client_protocol dependency source"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/Code/macro/crates/agent_session/Cargo.toml:21:agent-client-protocol = { workspace = true }\n/Users/eric/Code/macro/Cargo.toml:106:agent-client-protocol = \"1.2.0\"\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-derive-1.2.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.5.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-2.0.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-derive-2.0.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.3.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-derive-1.3.0"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_019iCEBqeqsXYMJQdJhvGZzE",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -403,21 +337,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn 'pub struct RawJsonRpcMessage\\|impl RawJsonRpcMessage' ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/rust/ 2>/dev/null | head; find ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0 -name '*.rs' | xargs grep -ln 'RawJsonRpcMessage' | head"),
- "description": String("Find RawJsonRpcMessage struct definition in ACP crate"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/tests/jsonrpc_edge_cases.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/tests/protocol_v2.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/lib.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc/transport_actor.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc/incoming_actor.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc/outgoing_actor.rs"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_019NXxCRZdm2cgJ4haDXmfRn",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -432,21 +359,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n 'pub struct RawJsonRpcMessage' -A 40 ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs | head -80; grep -n 'impl RawJsonRpcMessage' -A 60 ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs | head -120"),
- "description": String("Read RawJsonRpcMessage fields and methods"),
- },
- ),
- raw_output: Some(
- String("127:impl RawJsonRpcMessage {\n128- /// Build a raw JSON-RPC request message.\n129- pub fn request(\n130- method: String,\n131- params: serde_json::Value,\n132- id: RequestId,\n133- ) -> Result<Self, crate::Error> {\n134- Ok(Self::Request(RpcRequest {\n135- id,\n136- method: Arc::from(method),\n137- params: RawJsonRpcParams::from_value(params)?,\n138- }))\n139- }\n140-\n141- /// Build a raw JSON-RPC notification message.\n142- pub fn notification(method: String, params: serde_json::Value) -> Result<Self, crate::Error> {\n143- Ok(Self::Notification(RpcNotification {\n144- method: Arc::from(method),\n145- params: RawJsonRpcParams::from_value(params)?,\n146- }))\n147- }\n148-\n149- /// Build a raw JSON-RPC response message.\n150- #[must_use]\n151- pub fn response(id: RequestId, response: Result<serde_json::Value, crate::Error>) -> Self {\n152- Self::Response(RpcResponse::new(id, response))\n153- }\n154-\n155- /// The response id, if this is a response.\n156- #[must_use]\n157- pub fn response_id(&self) -> Option<&RequestId> {\n158- match self {\n159- Self::Response(RpcResponse::Result { id, .. } | RpcResponse::Error { id, .. }) => {\n160- Some(id)\n161- }\n162- Self::Request(_) | Self::Notification(_) => None,\n163- }\n164- }\n165-}\n166-\n167-impl Serialize for RawJsonRpcMessage {\n168- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n169- where\n170- S: serde::Serializer,\n171- {\n172- match self {\n173- Self::Request(request) => {\n174- VersionedJsonRpcMessage::wrap(request.clone()).serialize(serializer)\n175- }\n176- Self::Notification(notification) => {\n177- VersionedJsonRpcMessage::wrap(notification.clone()).serialize(serializer)\n178- }\n179- Self::Response(response) => {\n180- VersionedJsonRpcMessage::wrap(response.clone()).serialize(serializer)\n181- }\n182- }\n183- }\n184-}\n185-\n186-impl<'de> Deserialize<'de> for RawJsonRpcMessage {\n187- fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018ArD4ZmaWuxEXW1KVfWxWi",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -461,41 +381,28 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("sed -n '1,126p' ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs"),
- "description": String("Read RawJsonRpcMessage enum and RpcRequest/RpcResponse types"),
- },
- ),
- raw_output: Some(
- String("//! Core JSON-RPC server support.\n\nuse agent_client_protocol_schema::v1::{\n JsonRpcMessage as VersionedJsonRpcMessage, Notification as RpcNotification,\n Request as RpcRequest, RequestId, Response as RpcResponse, SessionId,\n};\n\n// Types re-exported from crate root\nuse serde::{Deserialize, Serialize};\nuse std::any::TypeId;\nuse std::collections::HashMap;\nuse std::fmt::Debug;\nuse std::panic::Location;\nuse std::pin::pin;\nuse std::sync::Arc;\nuse std::sync::{\n Mutex,\n atomic::{AtomicBool, Ordering},\n};\nuse uuid::Uuid;\n\nuse futures::FutureExt;\nuse futures::channel::{mpsc, oneshot};\nuse futures::future::{self, BoxFuture, Either};\nuse futures::{AsyncRead, AsyncWrite, StreamExt};\n\nmod dynamic_handler;\npub(crate) mod handlers;\nmod incoming_actor;\nmod outgoing_actor;\nmod protocol_compat;\npub(crate) mod run;\nmod task_actor;\nmod transport_actor;\n\nuse crate::jsonrpc::dynamic_handler::DynamicHandlerMessage;\npub use crate::jsonrpc::handlers::NullHandler;\nuse crate::jsonrpc::handlers::{ChainedHandler, NamedHandler};\nuse crate::jsonrpc::handlers::{MessageHandler, NotificationHandler, RequestHandler};\nuse crate::jsonrpc::outgoing_actor::{OutgoingMessageTx, send_raw_message};\nuse crate::jsonrpc::protocol_compat::{ProtocolCompat, ProtocolMode};\nuse crate::jsonrpc::run::SpawnedRun;\nuse crate::jsonrpc::run::{ChainRun, NullRun, RunWithConnectionTo};\nuse crate::jsonrpc::task_actor::{Task, TaskTx};\nuse crate::mcp_server::McpServer;\nuse crate::role::HasPeer;\nuse crate::role::Role;\nuse crate::{Agent, Client, ConnectTo, RoleId};\n\n/// Raw JSON-RPC message transported by [`Channel`].\n///\n/// This uses the JSON-RPC envelope types from `agent-client-protocol-schema`\n/// while keeping method params as raw, JSON-RPC-valid params at the transport boundary.\n#[derive(Debug, Clone)]\npub enum RawJsonRpcMessage {\n /// A JSON-RPC request with an id and expected response.\n Request(RpcRequest<RawJsonRpcParams>),\n /// A JSON-RPC notification without a response.\n Notification(RpcNotification<RawJsonRpcParams>),\n /// A JSON-RPC response to a prior request.\n Response(RpcResponse<serde_json::Value>),\n}\n\n/// Raw JSON-RPC request or notification parameters.\n///\n/// JSON-RPC params, when present, must be either an array or an object.\n#[derive(Debug, Clone, PartialEq)]\npub enum RawJsonRpcParams {\n /// Positional JSON-RPC params.\n Array(Vec<serde_json::Value>),\n /// Named JSON-RPC params.\n Object(serde_json::Map<String, serde_json::Value>),\n}\n\nimpl RawJsonRpcParams {\n /// Convert a JSON value into JSON-RPC params.\n pub fn from_value(value: serde_json::Value) -> Result<Option<Self>, crate::Error> {\n match value {\n serde_json::Value::Null => Ok(None),\n serde_json::Value::Array(array) => Ok(Some(Self::Array(array))),\n serde_json::Value::Object(object) => Ok(Some(Self::Object(object))),\n _ => {\n Err(crate::Error::invalid_params()\n .data(\"JSON-RPC params must be an object or array\"))\n }\n }\n }\n\n /// Convert params back into a JSON value.\n #[must_use]\n pub fn into_value(self) -> serde_json::Value {\n match self {\n Self::Array(array) => serde_json::Value::Array(array),\n Self::Object(object) => serde_json::Value::Object(object),\n }\n }\n}\n\nimpl Serialize for RawJsonRpcParams {\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n where\n S: serde::Serializer,\n {\n match self {\n Self::Array(array) => array.serialize(serializer),\n Self::Object(object) => object.serialize(serializer),\n }\n }\n}\n\nimpl<'de> Deserialize<'de> for RawJsonRpcParams {\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n where\n D: serde::Deserializer<'de>,\n {\n let value = serde_json::Value::deserialize(deserializer)?;\n match value {\n serde_json::Value::Array(array) => Ok(Self::Array(array)),\n serde_json::Value::Object(object) => Ok(Self::Object(object)),\n _ => Err(serde::de::Error::custom(\n \"JSON-RPC params must be an object or array\",\n )),\n }\n }\n}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Ex1sHJeme9xM23T9tuUtvW",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/Cargo.toml",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/Cargo.toml"),
- },
- ),
- raw_output: Some(
- String("1\t[package]\n2\tname = \"agent_session\"\n3\tversion = \"0.1.0\"\n4\tedition = \"2024\"\n5\t\n6\t[dependencies]\n7\t\n8\tmacro_uuid = { path = \"../macro_uuid\" }\n9\tagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\n10\tbots = { path = \"../bots\"}\n11\tmacro_user_id = { path = \"../macro_user_id\", features = [\"sqlx\"] }\n12\tsqlx = { workspace = true }\n13\tchrono = { workspace = true }\n14\tthiserror = { workspace = true }\n15\tanyhow = { workspace = true }\n16\tserde = { workspace = true }\n17\tserde_json = { workspace = true }\n18\tworkspace-hack = { version = \"0.1\", path = \"../workspace-hack\" }\n19\t\n20\t[dev-dependencies]\n21\tagent-client-protocol = { workspace = true }\n22\taxum = { workspace = true, features = [\"ws\"] }\n23\tmacro_db_migrator = { path = \"../macro_db_migrator\" }\n24\ttokio = { workspace = true, features = [\"fs\", \"io-std\", \"io-util\", \"macros\", \"net\", \"rt-multi-thread\", \"time\"] }\n25\ttokio-tungstenite = { workspace = true }\n26\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01NuY6RvJBEwhYApLPbV3QfA",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -510,21 +417,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n '^tempfile' /Users/eric/Code/macro/Cargo.toml"),
- "description": String("Check if tempfile is a workspace dependency"),
- },
- ),
- raw_output: Some(
- String("(Bash completed with no output)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01ATR61Vo1sUBC4sDTb9hgkQ",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -539,21 +439,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn 'tempfile' /Users/eric/Code/macro/Cargo.toml /Users/eric/Code/macro/Cargo.lock | head -5"),
- "description": String("Check tempfile presence in workspace"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/Code/macro/Cargo.lock:836: \"tempfile\",\n/Users/eric/Code/macro/Cargo.lock:1155: \"tempfile\",\n/Users/eric/Code/macro/Cargo.lock:2541: \"tempfile\",\n/Users/eric/Code/macro/Cargo.lock:11689: \"tempfile\",\n/Users/eric/Code/macro/Cargo.lock:13242: \"tempfile\","),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_014E1teRuKvFVz3kXjjkS9Ah",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -568,21 +461,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn 'tempfile' /Users/eric/Code/macro/crates/*/Cargo.toml /Users/eric/Code/macro/rust/**/Cargo.toml 2>/dev/null | head"),
- "description": String("See how other crates declare tempfile"),
- },
- ),
- raw_output: Some(
- String("(eval):1: no matches found: /Users/eric/Code/macro/rust/**/Cargo.toml"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01HocEetuSapsmVgT3isZYfw",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Failed,
detail: Edit {
diffs: [
@@ -593,42 +479,28 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs"),
- "content": String("//! Record a live agent session as [`Message`]-per-line JSONL fixtures.\n//!\n//! An ACP client (e.g. Zed) spawns this example as its agent server and\n//! speaks ACP over stdio. Internally the process is both sides of an\n//! Agent Runtime Protocol connection over a loopback WebSocket:\n//!\n//! - the service side accepts the runtime connection, records every logical\n//! protocol message crossing the wire, and bridges the connection's ACP\n//! channel to stdio;\n//! - a Tokio task stands in for a container, connects its runtime to the\n//! service, announces `acp_ready`, and starts the official Claude Code ACP\n//! adapter (`@agentclientprotocol/claude-agent-acp`) with `npx`.\n//!\n//! Each ACP session on the connection is recorded to its own file,\n//! `~/.agent_runtime_sessions/<session-id>.jsonl`, one JSON object per line:\n//! a timestamp flattened together with this crate's own [`Message`]\n//! serialization, so each line parses straight back into [`Message`]:\n//!\n//! ```text\n//! {\"ts\": \"2026-08-03T14:22:07.123Z\", \"direction\": \"to_server\" | \"to_runtime\", \"content\": <envelope>}\n//! ```\n//!\n//! One connection multiplexes many sessions (an ACP client like Zed spawns\n//! the agent server once and opens every session over it), so lines are\n//! routed by the session they belong to: `params.sessionId` where present,\n//! and JSON-RPC request ids otherwise — a response is attributed to the\n//! session of the request it answers, and `session/new` only reveals its\n//! session in the response. Connection-level traffic that belongs to no\n//! session (the `acp_ready` event, the `initialize` handshake) is copied\n//! into every session file so each recording stands alone. A connection that\n//! never opens a session records nothing; a session resumed by a later\n//! process appends to its existing file.\n//!\n//! Prerequisites:\n//!\n//! - Node.js and `npx` must be installed;\n//! - Claude Code credentials: either a subscription login (`claude /login`)\n//! or `ANTHROPIC_API_KEY` in the environment. The API key takes precedence\n//! over the subscription login when both are present.\n//!\n//! Install the recorder to `~/.cargo/bin` (`--locked` keeps the workspace\n//! lockfile's dependency versions, which the pinned toolchain requires), then\n//! point an ACP client at the installed binary:\n//!\n//! ```text\n//! cargo install --locked --path crates/agent_session --example agent_session_recorder\n//! ```\n//!\n//! Zed `settings.json` (the shell resolves the binary from `$HOME`, so no\n//! hardcoded paths; the `env -u` strips a stray API key from the environment\n//! so the session uses the subscription login):\n//!\n//! ```text\n//! \"agent_servers\": {\n//! \"Recorded Claude\": {\n//! \"type\": \"custom\",\n//! \"command\": \"/bin/bash\",\n//! \"args\": [\n//! \"-c\",\n//! \"exec env -u ANTHROPIC_API_KEY \\\"$HOME/.cargo/bin/agent_session_recorder\\\"\"\n//! ]\n//! }\n//! }\n//! ```\n//!\n//! All diagnostics go to stderr: stdout carries the ACP stream.\n\nuse std::collections::HashMap;\nuse std::collections::hash_map::Entry;\nuse std::error::Error;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse agent_client_protocol::{AcpAgent, Agent, Client, ConnectTo, Stdio};\nuse agent_runtime_protocol::domain::channel::Channel;\nuse agent_runtime_protocol::domain::connection::{\n RuntimeConnection, ServerChannel, ServerConnection,\n};\nuse agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};\nuse agent_runtime_protocol::outbound::websocket::{ServerTransport, connect_runtime};\nuse agent_session::domain::model::Message;\nuse chrono::{SecondsFormat, Utc};\nuse serde::Serialize;\nuse tokio::io::AsyncWriteExt;\nuse tokio::sync::mpsc;\n\n#[cfg(test)]\n#[path = \"agent_session_recorder/test.rs\"]\nmod test;\n\ntype AnyError = Box<dyn Error + Send + Sync>;\n\nconst CLAUDE_AGENT_ACP: &str = \"@agentclientprotocol/[email protected]\";\n\n#[tokio::main]\nasync fn main() -> Result<(), AnyError> {\n let dir = recordings_dir(&std::env::home_dir().ok_or(\"cannot determine home directory\")?);\n let (sink, lines) = mpsc::unbounded_channel();\n let writer = tokio::spawn(run_writer(dir.clone(), lines));\n\n let carrier: Arc<ServerTransport<ToRuntimeMessage, ToServerMessage>> =\n Arc::new(ServerTransport::new());\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:0\").await?;\n let address = listener.local_addr()?;\n let app = Arc::clone(&carrier).into_router();\n let websocket_handle = tokio::spawn(async move { axum::serve(listener, app).await });\n eprintln!(\"recorder: service listening on ws://{address}\");\n\n let mut container = tokio::spawn(run_container(format!(\"ws://{address}\")));\n let incoming = accept_runtime(&carrier, &mut container).await?;\n eprintln!(\n \"recorder: runtime connected, recording sessions under {}\",\n dir.display()\n );\n\n let (service, acp) = ServerConnection::connect(record_channel(incoming, sink), ());\n\n // Bridge the ACP client on stdio to this connection's agent. The client\n // drives the whole session; this future completes when it closes stdio.\n let bridge = ConnectTo::<Agent>::connect_to(Stdio::new(), acp);\n tokio::pin!(bridge);\n let result: Result<(), AnyError> = tokio::select! {\n result = &mut bridge => {\n container.abort();\n let _ = container.await;\n result.map_err(Into::into)\n }\n container_result = &mut container => Err(container_error(container_result)),\n };\n\n // Tear the connection down, then let the writer drain what was recorded.\n drop(service);\n websocket_handle.abort();\n match writer.await {\n Ok(Ok(())) => eprintln!(\n \"recorder: session recordings saved under {}\",\n dir.display()\n ),\n Ok(Err(error)) => eprintln!(\"recorder: writing the recordings failed: {error}\"),\n Err(error) => eprintln!(\"recorder: recording writer panicked: {error}\"),\n }\n result\n}\n\n/// The directory holding per-session recordings for the user whose home\n/// directory is `home`.\nfn recordings_dir(home: &Path) -> PathBuf {\n home.join(\".agent_runtime_sessions\")\n}\n\n/// Where the session identified by `session_id` is recorded under `dir`.\n///\n/// The id is minted by the agent (a UUID in practice); anything outside a\n/// conservative filename alphabet maps to `_` so an exotic id cannot name a\n/// path outside `dir`.\nfn session_recording_path(dir: &Path, session_id: &str) -> PathBuf {\n let safe: String = session_id\n .chars()\n .map(|c| {\n if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {\n c\n } else {\n '_'\n }\n })\n .collect();\n dir.join(format!(\"{safe}.jsonl\"))\n}\n\n/// One recorded line's destination.\n#[derive(Debug, PartialEq)]\nenum Append {\n /// A connection-level line: appended to every open recording and copied\n /// to the front of any recording opened later, so each file stands alone.\n Shared(String),\n /// A line belonging to one session's recording.\n Session { session_id: String, line: String },\n}\n\n/// Where the response to an in-flight request belongs.\nenum Pending {\n /// The request named its session; the response follows it there.\n Session(String),\n /// The request named no session (`initialize`, `session/new`, ...); its\n /// line is held back until the response shows whether it minted one.\n Unattributed { request_line: String },\n}\n\n/// Routes recorded JSONL lines to per-session recordings.\n///\n/// Most ACP traffic names its session in `params.sessionId`. Responses never\n/// do, so requests register their JSON-RPC id and responses are attributed\n/// by looking that id back up. Ids are scoped by the direction of the\n/// request: the two peers' id spaces are independent, so an id alone is\n/// ambiguous.\n#[derive(Default)]\nstruct SessionRouter {\n /// `\"<issuer direction>:<id>\"` of each in-flight request, mapped to\n /// where its response belongs.\n pending: HashMap<String, Pending>,\n}\n\nimpl SessionRouter {\n /// Decide where `line` (one serialized [`RecordedLine`]) is appended.\n ///\n /// A request that names no session yields nothing until its response\n /// arrives; the pair is then routed together.\n fn route(&mut self, line: String) -> Vec<Append> {\n let value: serde_json::Value = match serde_json::from_str(&line) {\n Ok(value) => value,\n // Lines come from record_line, so this cannot happen; shared is\n // the destination that never loses data.\n Err(_) => return vec![Append::Shared(line)],\n };\n let direction = value[\"direction\"].as_str().unwrap_or_default().to_owned();\n let content = &value[\"content\"];\n let method = content[\"method\"].as_str();\n let id = match &content[\"id\"] {\n serde_json::Value::Null => None,\n id => Some(id.to_string()),\n };\n let session_id = content[\"params\"][\"sessionId\"].as_str().map(str::to_owned);\n\n match (method, id) {\n // A request: remember where its response belongs.\n (Some(_), Some(id)) => match session_id {\n Some(session_id) => {\n self.pending\n .insert(format!(\"{direction}:{id}\"), Pending::Session(session_id.clone()));\n vec![Append::Session { session_id, line }]\n }\n None => {\n self.pending\n .insert(format!(\"{direction}:{id}\"), Pending::Unattributed {\n request_line: line,\n });\n vec![]\n }\n },\n // A notification.\n (Some(_), None) => match session_id {\n Some(session_id) => vec![Append::Session { session_id, line }],\n None => vec![Append::Shared(line)],\n },\n // A response: attribute it via the request that caused it, which\n // traveled in the opposite direction.\n (None, Some(id)) => {\n let issuer = opposite(&direction);\n match self.pending.remove(&format!(\"{issuer}:{id}\")) {\n Some(Pending::Session(session_id)) => {\n vec![Append::Session { session_id, line }]\n }\n Some(Pending::Unattributed { request_line }) => {\n match content[\"result\"][\"sessionId\"].as_str() {\n // The request minted a session (session/new);\n // both lines open its recording.\n Some(minted) => vec![\n Append::Session {\n session_id: minted.to_owned(),\n line: request_line,\n },\n Append::Session {\n session_id: minted.to_owned(),\n line,\n },\n ],\n None => vec![Append::Shared(request_line), Append::Shared(line)],\n }\n }\n None => vec![Append::Shared(line)],\n }\n }\n // Not JSON-RPC at all, e.g. the acp_ready system event.\n (None, None) => vec![Append::Shared(line)],\n }\n }\n\n /// Give back request lines still waiting on a response — e.g. when the\n /// connection closes mid-request — so they are not lost. Sorted by\n /// pending key for determinism.\n fn drain(&mut self) -> Vec<Append> {\n let mut pending: Vec<_> = std::mem::take(&mut self.pending).into_iter().collect();\n pending.sort_by(|(a, _), (b, _)| a.cmp(b));\n pending\n .into_iter()\n .filter_map(|(_, entry)| match entry {\n Pending::Session(_) => None,\n Pending::Unattributed { request_line } => Some(Append::Shared(request_line)),\n })\n .collect()\n }\n}\n\n/// The opposite of a recorded `direction` value.\nfn opposite(direction: &str) -> &'static str {\n match direction {\n \"to_server\" => \"to_runtime\",\n _ => \"to_server\",\n }\n}\n\n/// Route recorded lines to per-session files until every sink handle drops.\n///\n/// Flushes after every line so a session killed mid-run keeps its data.\nasync fn run_writer(\n dir: PathBuf,\n mut lines: mpsc::UnboundedReceiver<String>,\n) -> std::io::Result<()> {\n tokio::fs::create_dir_all(&dir).await?;\n let mut router = SessionRouter::default();\n // Connection-level lines recorded so far, copied into each new recording.\n let mut shared: Vec<String> = Vec::new();\n let mut recordings: HashMap<String, tokio::fs::File> = HashMap::new();\n\n while let Some(line) = lines.recv().await {\n let appends = router.route(line);\n append_lines(&dir, appends, &mut shared, &mut recordings).await?;\n }\n let leftovers = router.drain();\n append_lines(&dir, leftovers, &mut shared, &mut recordings).await\n}\n\n/// Apply routed appends, opening a session's recording on its first line.\n///\n/// A recording opens in append mode: a session resumed by a later process\n/// continues its existing file. Each newly opened recording starts with a\n/// copy of the connection-level lines seen so far.\nasync fn append_lines(\n dir: &Path,\n appends: Vec<Append>,\n shared: &mut Vec<String>,\n recordings: &mut HashMap<String, tokio::fs::File>,\n) -> std::io::Result<()> {\n for append in appends {\n match append {\n Append::Shared(line) => {\n for file in recordings.values_mut() {\n write_line(file, &line).await?;\n }\n shared.push(line);\n }\n Append::Session { session_id, line } => {\n let file = match recordings.entry(session_id) {\n Entry::Occupied(entry) => entry.into_mut(),\n Entry::Vacant(entry) => {\n let path = session_recording_path(dir, entry.key());\n let mut file = tokio::fs::OpenOptions::new()\n .create(true)\n .append(true)\n .open(&path)\n .await?;\n for line in shared.iter() {\n write_line(&mut file, line).await?;\n }\n eprintln!(\n \"recorder: session {} recording to {}\",\n entry.key(),\n path.display()\n );\n entry.insert(file)\n }\n };\n write_line(file, &line).await?;\n }\n }\n }\n Ok(())\n}\n\n/// Append one line to `file` and flush it.\nasync fn write_line(file: &mut tokio::fs::File, line: &str) -> std::io::Result<()> {\n file.write_all(line.as_bytes()).await?;\n file.write_all(b\"\\n\").await?;\n file.flush().await\n}\n\n/// Interpose a recording tap on the service side of a logical connection.\n///\n/// Every message crossing the channel is appended to `sink` as one JSONL\n/// line before being forwarded unchanged. Recording is best-effort: a\n/// message that fails to serialize is reported on stderr and forwarded\n/// anyway, and a closed sink never tears down the session.\nfn record_channel(inner: ServerChannel, sink: mpsc::UnboundedSender<String>) -> ServerChannel {\n let (outer, bridge) = Channel::duplex();\n let Channel {\n tx: inner_tx,\n rx: mut inner_rx,\n } = inner;\n let Channel {\n tx: bridge_tx,\n rx: mut bridge_rx,\n }: Channel<ToServerMessage, ToRuntimeMessage> = bridge;\n\n let to_runtime_sink = sink.clone();\n tokio::spawn(async move {\n while let Some(message) = bridge_rx.recv().await {\n record(&to_runtime_sink, &Message::ToRuntime(message.clone()));\n if inner_tx.send(message).is_err() {\n break;\n }\n }\n });\n tokio::spawn(async move {\n while let Some(message) = inner_rx.recv().await {\n record(&sink, &Message::ToServer(message.clone()));\n if bridge_tx.send(message).is_err() {\n break;\n }\n }\n });\n\n outer\n}\n\n/// One recorded JSONL line: a timestamp flattened alongside [`Message`]'s\n/// own `direction`/`content` serialization.\n#[derive(Serialize)]\nstruct RecordedLine<'a> {\n ts: String,\n #[serde(flatten)]\n message: &'a Message,\n}\n\nfn record(sink: &mpsc::UnboundedSender<String>, message: &Message) {\n match record_line(message) {\n Ok(line) => {\n let _ = sink.send(line);\n }\n Err(error) => eprintln!(\"recorder: dropping unserializable message: {error}\"),\n }\n}\n\nfn record_line(message: &Message) -> serde_json::Result<String> {\n serde_json::to_string(&RecordedLine {\n ts: Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),\n message,\n })\n}\n\nasync fn accept_runtime(\n carrier: &ServerTransport<ToRuntimeMessage, ToServerMessage>,\n container: &mut tokio::task::JoinHandle<Result<(), AnyError>>,\n) -> Result<ServerChannel, AnyError> {\n tokio::select! {\n incoming = carrier.accept() => incoming\n .ok_or_else(|| \"container disconnected before connecting\".into()),\n result = &mut *container => Err(container_error(result)),\n }\n}\n\nfn container_error(result: Result<Result<(), AnyError>, tokio::task::JoinError>) -> AnyError {\n match result {\n Ok(Ok(())) => \"container exited unexpectedly\".into(),\n Ok(Err(error)) => error,\n Err(error) => Box::new(error),\n }\n}\n\nasync fn run_container(websocket_url: String) -> Result<(), AnyError> {\n let (stream, _response) = tokio_tungstenite::connect_async(websocket_url).await?;\n let channel = connect_runtime::<ToServerMessage, ToRuntimeMessage, _>(stream);\n let (runtime, acp) = RuntimeConnection::connect(channel);\n // Announce readiness over the wire like a real Agent Runtime would, so\n // the recording contains the acp_ready event that production logs carry.\n runtime.system_event(SystemEvent::AcpReady)?;\n\n let claude_code = AcpAgent::from_args([\"npx\", \"-y\", CLAUDE_AGENT_ACP])?;\n ConnectTo::<Client>::connect_to(claude_code, acp)\n .await\n .map_err(Into::into)\n}\n"),
- },
- ),
- raw_output: Some(
- String("<tool_use_error>File has not been read yet. Read it first before writing to it.</tool_use_error>"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_017CKQR5Ypi2BbXyyEWi9epq",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs"),
- "limit": Number(10),
- },
- ),
- raw_output: Some(
- String("1\t//! Record a live agent session as [`Message`]-per-line JSONL fixtures.\n2\t//!\n3\t//! An ACP client (e.g. Zed) spawns this example as its agent server and\n4\t//! speaks ACP over stdio. Internally the process is both sides of an\n5\t//! Agent Runtime Protocol connection over a loopback WebSocket:\n6\t//!\n7\t//! - the service side accepts the runtime connection, records every logical\n8\t//! protocol message crossing the wire, and bridges the connection's ACP\n9\t//! channel to stdio;\n10\t//! - a Tokio task stands in for a container, connects its runtime to the"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01B21mvnKULwrxijSpbU4hgU",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -676,15 +548,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs"),
- "content": String("//! Record a live agent session as [`Message`]-per-line JSONL fixtures.\n//!\n//! An ACP client (e.g. Zed) spawns this example as its agent server and\n//! speaks ACP over stdio. Internally the process is both sides of an\n//! Agent Runtime Protocol connection over a loopback WebSocket:\n//!\n//! - the service side accepts the runtime connection, records every logical\n//! protocol message crossing the wire, and bridges the connection's ACP\n//! channel to stdio;\n//! - a Tokio task stands in for a container, connects its runtime to the\n//! service, announces `acp_ready`, and starts the official Claude Code ACP\n//! adapter (`@agentclientprotocol/claude-agent-acp`) with `npx`.\n//!\n//! Each ACP session on the connection is recorded to its own file,\n//! `~/.agent_runtime_sessions/<session-id>.jsonl`, one JSON object per line:\n//! a timestamp flattened together with this crate's own [`Message`]\n//! serialization, so each line parses straight back into [`Message`]:\n//!\n//! ```text\n//! {\"ts\": \"2026-08-03T14:22:07.123Z\", \"direction\": \"to_server\" | \"to_runtime\", \"content\": <envelope>}\n//! ```\n//!\n//! One connection multiplexes many sessions (an ACP client like Zed spawns\n//! the agent server once and opens every session over it), so lines are\n//! routed by the session they belong to: `params.sessionId` where present,\n//! and JSON-RPC request ids otherwise — a response is attributed to the\n//! session of the request it answers, and `session/new` only reveals its\n//! session in the response. Connection-level traffic that belongs to no\n//! session (the `acp_ready` event, the `initialize` handshake) is copied\n//! into every session file so each recording stands alone. A connection that\n//! never opens a session records nothing; a session resumed by a later\n//! process appends to its existing file.\n//!\n//! Prerequisites:\n//!\n//! - Node.js and `npx` must be installed;\n//! - Claude Code credentials: either a subscription login (`claude /login`)\n//! or `ANTHROPIC_API_KEY` in the environment. The API key takes precedence\n//! over the subscription login when both are present.\n//!\n//! Install the recorder to `~/.cargo/bin` (`--locked` keeps the workspace\n//! lockfile's dependency versions, which the pinned toolchain requires), then\n//! point an ACP client at the installed binary:\n//!\n//! ```text\n//! cargo install --locked --path crates/agent_session --example agent_session_recorder\n//! ```\n//!\n//! Zed `settings.json` (the shell resolves the binary from `$HOME`, so no\n//! hardcoded paths; the `env -u` strips a stray API key from the environment\n//! so the session uses the subscription login):\n//!\n//! ```text\n//! \"agent_servers\": {\n//! \"Recorded Claude\": {\n//! \"type\": \"custom\",\n//! \"command\": \"/bin/bash\",\n//! \"args\": [\n//! \"-c\",\n//! \"exec env -u ANTHROPIC_API_KEY \\\"$HOME/.cargo/bin/agent_session_recorder\\\"\"\n//! ]\n//! }\n//! }\n//! ```\n//!\n//! All diagnostics go to stderr: stdout carries the ACP stream.\n\nuse std::collections::HashMap;\nuse std::collections::hash_map::Entry;\nuse std::error::Error;\nuse std::path::{Path, PathBuf};\nuse std::sync::Arc;\n\nuse agent_client_protocol::{AcpAgent, Agent, Client, ConnectTo, Stdio};\nuse agent_runtime_protocol::domain::channel::Channel;\nuse agent_runtime_protocol::domain::connection::{\n RuntimeConnection, ServerChannel, ServerConnection,\n};\nuse agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};\nuse agent_runtime_protocol::outbound::websocket::{ServerTransport, connect_runtime};\nuse agent_session::domain::model::Message;\nuse chrono::{SecondsFormat, Utc};\nuse serde::Serialize;\nuse tokio::io::AsyncWriteExt;\nuse tokio::sync::mpsc;\n\n#[cfg(test)]\n#[path = \"agent_session_recorder/test.rs\"]\nmod test;\n\ntype AnyError = Box<dyn Error + Send + Sync>;\n\nconst CLAUDE_AGENT_ACP: &str = \"@agentclientprotocol/[email protected]\";\n\n#[tokio::main]\nasync fn main() -> Result<(), AnyError> {\n let dir = recordings_dir(&std::env::home_dir().ok_or(\"cannot determine home directory\")?);\n let (sink, lines) = mpsc::unbounded_channel();\n let writer = tokio::spawn(run_writer(dir.clone(), lines));\n\n let carrier: Arc<ServerTransport<ToRuntimeMessage, ToServerMessage>> =\n Arc::new(ServerTransport::new());\n let listener = tokio::net::TcpListener::bind(\"127.0.0.1:0\").await?;\n let address = listener.local_addr()?;\n let app = Arc::clone(&carrier).into_router();\n let websocket_handle = tokio::spawn(async move { axum::serve(listener, app).await });\n eprintln!(\"recorder: service listening on ws://{address}\");\n\n let mut container = tokio::spawn(run_container(format!(\"ws://{address}\")));\n let incoming = accept_runtime(&carrier, &mut container).await?;\n eprintln!(\n \"recorder: runtime connected, recording sessions under {}\",\n dir.display()\n );\n\n let (service, acp) = ServerConnection::connect(record_channel(incoming, sink), ());\n\n // Bridge the ACP client on stdio to this connection's agent. The client\n // drives the whole session; this future completes when it closes stdio.\n let bridge = ConnectTo::<Agent>::connect_to(Stdio::new(), acp);\n tokio::pin!(bridge);\n let result: Result<(), AnyError> = tokio::select! {\n result = &mut bridge => {\n container.abort();\n let _ = container.await;\n result.map_err(Into::into)\n }\n container_result = &mut container => Err(container_error(container_result)),\n };\n\n // Tear the connection down, then let the writer drain what was recorded.\n drop(service);\n websocket_handle.abort();\n match writer.await {\n Ok(Ok(())) => eprintln!(\n \"recorder: session recordings saved under {}\",\n dir.display()\n ),\n Ok(Err(error)) => eprintln!(\"recorder: writing the recordings failed: {error}\"),\n Err(error) => eprintln!(\"recorder: recording writer panicked: {error}\"),\n }\n result\n}\n\n/// The directory holding per-session recordings for the user whose home\n/// directory is `home`.\nfn recordings_dir(home: &Path) -> PathBuf {\n home.join(\".agent_runtime_sessions\")\n}\n\n/// Where the session identified by `session_id` is recorded under `dir`.\n///\n/// The id is minted by the agent (a UUID in practice); anything outside a\n/// conservative filename alphabet maps to `_` so an exotic id cannot name a\n/// path outside `dir`.\nfn session_recording_path(dir: &Path, session_id: &str) -> PathBuf {\n let safe: String = session_id\n .chars()\n .map(|c| {\n if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {\n c\n } else {\n '_'\n }\n })\n .collect();\n dir.join(format!(\"{safe}.jsonl\"))\n}\n\n/// One recorded line's destination.\n#[derive(Debug, PartialEq)]\nenum Append {\n /// A connection-level line: appended to every open recording and copied\n /// to the front of any recording opened later, so each file stands alone.\n Shared(String),\n /// A line belonging to one session's recording.\n Session { session_id: String, line: String },\n}\n\n/// Where the response to an in-flight request belongs.\nenum Pending {\n /// The request named its session; the response follows it there.\n Session(String),\n /// The request named no session (`initialize`, `session/new`, ...); its\n /// line is held back until the response shows whether it minted one.\n Unattributed { request_line: String },\n}\n\n/// Routes recorded JSONL lines to per-session recordings.\n///\n/// Most ACP traffic names its session in `params.sessionId`. Responses never\n/// do, so requests register their JSON-RPC id and responses are attributed\n/// by looking that id back up. Ids are scoped by the direction of the\n/// request: the two peers' id spaces are independent, so an id alone is\n/// ambiguous.\n#[derive(Default)]\nstruct SessionRouter {\n /// `\"<issuer direction>:<id>\"` of each in-flight request, mapped to\n /// where its response belongs.\n pending: HashMap<String, Pending>,\n}\n\nimpl SessionRouter {\n /// Decide where `line` (one serialized [`RecordedLine`]) is appended.\n ///\n /// A request that names no session yields nothing until its response\n /// arrives; the pair is then routed together.\n fn route(&mut self, line: String) -> Vec<Append> {\n let value: serde_json::Value = match serde_json::from_str(&line) {\n Ok(value) => value,\n // Lines come from record_line, so this cannot happen; shared is\n // the destination that never loses data.\n Err(_) => return vec![Append::Shared(line)],\n };\n let direction = value[\"direction\"].as_str().unwrap_or_default().to_owned();\n let content = &value[\"content\"];\n let method = content[\"method\"].as_str();\n let id = match &content[\"id\"] {\n serde_json::Value::Null => None,\n id => Some(id.to_string()),\n };\n let session_id = content[\"params\"][\"sessionId\"].as_str().map(str::to_owned);\n\n match (method, id) {\n // A request: remember where its response belongs.\n (Some(_), Some(id)) => match session_id {\n Some(session_id) => {\n self.pending.insert(\n format!(\"{direction}:{id}\"),\n Pending::Session(session_id.clone()),\n );\n vec![Append::Session { session_id, line }]\n }\n None => {\n self.pending.insert(\n format!(\"{direction}:{id}\"),\n Pending::Unattributed { request_line: line },\n );\n vec![]\n }\n },\n // A notification.\n (Some(_), None) => match session_id {\n Some(session_id) => vec![Append::Session { session_id, line }],\n None => vec![Append::Shared(line)],\n },\n // A response: attribute it via the request that caused it, which\n // traveled in the opposite direction.\n (None, Some(id)) => {\n let issuer = opposite(&direction);\n match self.pending.remove(&format!(\"{issuer}:{id}\")) {\n Some(Pending::Session(session_id)) => {\n vec![Append::Session { session_id, line }]\n }\n Some(Pending::Unattributed { request_line }) => {\n match content[\"result\"][\"sessionId\"].as_str() {\n // The request minted a session (session/new);\n // both lines open its recording.\n Some(minted) => vec![\n Append::Session {\n session_id: minted.to_owned(),\n line: request_line,\n },\n Append::Session {\n session_id: minted.to_owned(),\n line,\n },\n ],\n None => vec![Append::Shared(request_line), Append::Shared(line)],\n }\n }\n None => vec![Append::Shared(line)],\n }\n }\n // Not JSON-RPC at all, e.g. the acp_ready system event.\n (None, None) => vec![Append::Shared(line)],\n }\n }\n\n /// Give back request lines still waiting on a response — e.g. when the\n /// connection closes mid-request — so they are not lost. Sorted by\n /// pending key for determinism.\n fn drain(&mut self) -> Vec<Append> {\n let mut pending: Vec<_> = std::mem::take(&mut self.pending).into_iter().collect();\n pending.sort_by(|(a, _), (b, _)| a.cmp(b));\n pending\n .into_iter()\n .filter_map(|(_, entry)| match entry {\n Pending::Session(_) => None,\n Pending::Unattributed { request_line } => Some(Append::Shared(request_line)),\n })\n .collect()\n }\n}\n\n/// The opposite of a recorded `direction` value.\nfn opposite(direction: &str) -> &'static str {\n match direction {\n \"to_server\" => \"to_runtime\",\n _ => \"to_server\",\n }\n}\n\n/// Route recorded lines to per-session files until every sink handle drops.\n///\n/// Flushes after every line so a session killed mid-run keeps its data.\nasync fn run_writer(\n dir: PathBuf,\n mut lines: mpsc::UnboundedReceiver<String>,\n) -> std::io::Result<()> {\n tokio::fs::create_dir_all(&dir).await?;\n let mut router = SessionRouter::default();\n // Connection-level lines recorded so far, copied into each new recording.\n let mut shared: Vec<String> = Vec::new();\n let mut recordings: HashMap<String, tokio::fs::File> = HashMap::new();\n\n while let Some(line) = lines.recv().await {\n let appends = router.route(line);\n append_lines(&dir, appends, &mut shared, &mut recordings).await?;\n }\n let leftovers = router.drain();\n append_lines(&dir, leftovers, &mut shared, &mut recordings).await\n}\n\n/// Apply routed appends, opening a session's recording on its first line.\n///\n/// A recording opens in append mode: a session resumed by a later process\n/// continues its existing file. Each newly opened recording starts with a\n/// copy of the connection-level lines seen so far.\nasync fn append_lines(\n dir: &Path,\n appends: Vec<Append>,\n shared: &mut Vec<String>,\n recordings: &mut HashMap<String, tokio::fs::File>,\n) -> std::io::Result<()> {\n for append in appends {\n match append {\n Append::Shared(line) => {\n for file in recordings.values_mut() {\n write_line(file, &line).await?;\n }\n shared.push(line);\n }\n Append::Session { session_id, line } => {\n let file = match recordings.entry(session_id) {\n Entry::Occupied(entry) => entry.into_mut(),\n Entry::Vacant(entry) => {\n let path = session_recording_path(dir, entry.key());\n let mut file = tokio::fs::OpenOptions::new()\n .create(true)\n .append(true)\n .open(&path)\n .await?;\n for line in shared.iter() {\n write_line(&mut file, line).await?;\n }\n eprintln!(\n \"recorder: session {} recording to {}\",\n entry.key(),\n path.display()\n );\n entry.insert(file)\n }\n };\n write_line(file, &line).await?;\n }\n }\n }\n Ok(())\n}\n\n/// Append one line to `file` and flush it.\nasync fn write_line(file: &mut tokio::fs::File, line: &str) -> std::io::Result<()> {\n file.write_all(line.as_bytes()).await?;\n file.write_all(b\"\\n\").await?;\n file.flush().await\n}\n\n/// Interpose a recording tap on the service side of a logical connection.\n///\n/// Every message crossing the channel is appended to `sink` as one JSONL\n/// line before being forwarded unchanged. Recording is best-effort: a\n/// message that fails to serialize is reported on stderr and forwarded\n/// anyway, and a closed sink never tears down the session.\nfn record_channel(inner: ServerChannel, sink: mpsc::UnboundedSender<String>) -> ServerChannel {\n let (outer, bridge) = Channel::duplex();\n let Channel {\n tx: inner_tx,\n rx: mut inner_rx,\n } = inner;\n let Channel {\n tx: bridge_tx,\n rx: mut bridge_rx,\n }: Channel<ToServerMessage, ToRuntimeMessage> = bridge;\n\n let to_runtime_sink = sink.clone();\n tokio::spawn(async move {\n while let Some(message) = bridge_rx.recv().await {\n record(&to_runtime_sink, &Message::ToRuntime(message.clone()));\n if inner_tx.send(message).is_err() {\n break;\n }\n }\n });\n tokio::spawn(async move {\n while let Some(message) = inner_rx.recv().await {\n record(&sink, &Message::ToServer(message.clone()));\n if bridge_tx.send(message).is_err() {\n break;\n }\n }\n });\n\n outer\n}\n\n/// One recorded JSONL line: a timestamp flattened alongside [`Message`]'s\n/// own `direction`/`content` serialization.\n#[derive(Serialize)]\nstruct RecordedLine<'a> {\n ts: String,\n #[serde(flatten)]\n message: &'a Message,\n}\n\nfn record(sink: &mpsc::UnboundedSender<String>, message: &Message) {\n match record_line(message) {\n Ok(line) => {\n let _ = sink.send(line);\n }\n Err(error) => eprintln!(\"recorder: dropping unserializable message: {error}\"),\n }\n}\n\nfn record_line(message: &Message) -> serde_json::Result<String> {\n serde_json::to_string(&RecordedLine {\n ts: Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true),\n message,\n })\n}\n\nasync fn accept_runtime(\n carrier: &ServerTransport<ToRuntimeMessage, ToServerMessage>,\n container: &mut tokio::task::JoinHandle<Result<(), AnyError>>,\n) -> Result<ServerChannel, AnyError> {\n tokio::select! {\n incoming = carrier.accept() => incoming\n .ok_or_else(|| \"container disconnected before connecting\".into()),\n result = &mut *container => Err(container_error(result)),\n }\n}\n\nfn container_error(result: Result<Result<(), AnyError>, tokio::task::JoinError>) -> AnyError {\n match result {\n Ok(Ok(())) => \"container exited unexpectedly\".into(),\n Ok(Err(error)) => error,\n Err(error) => Box::new(error),\n }\n}\n\nasync fn run_container(websocket_url: String) -> Result<(), AnyError> {\n let (stream, _response) = tokio_tungstenite::connect_async(websocket_url).await?;\n let channel = connect_runtime::<ToServerMessage, ToRuntimeMessage, _>(stream);\n let (runtime, acp) = RuntimeConnection::connect(channel);\n // Announce readiness over the wire like a real Agent Runtime would, so\n // the recording contains the acp_ready event that production logs carry.\n runtime.system_event(SystemEvent::AcpReady)?;\n\n let claude_code = AcpAgent::from_args([\"npx\", \"-y\", CLAUDE_AGENT_ACP])?;\n ConnectTo::<Client>::connect_to(claude_code, acp)\n .await\n .map_err(Into::into)\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the tests:",
@@ -693,7 +556,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_01Y6KvTMTESF9qJwnVDWLMMh",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -706,15 +571,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs"),
- "content": String("use serde_json::{Value, json};\nuse tokio::time::{Duration, timeout};\n\nuse super::*;\n\n/// A recorded line the way `record_line` would serialize it.\nfn line(direction: &str, content: Value) -> String {\n json!({\n \"ts\": \"2026-08-03T14:22:07.123Z\",\n \"direction\": direction,\n \"content\": content,\n })\n .to_string()\n}\n\nfn shared(line: &str) -> Append {\n Append::Shared(line.to_owned())\n}\n\nfn session(session_id: &str, line: &str) -> Append {\n Append::Session {\n session_id: session_id.to_owned(),\n line: line.to_owned(),\n }\n}\n\n#[test]\nfn session_recording_path_is_sanitized_jsonl_under_dir() {\n assert_eq!(\n session_recording_path(Path::new(\"/tmp/recordings\"), \"sess-1\"),\n PathBuf::from(\"/tmp/recordings/sess-1.jsonl\"),\n );\n // Path separators in an exotic id cannot escape the directory.\n assert_eq!(\n session_recording_path(Path::new(\"/tmp/recordings\"), \"../evil/id\"),\n PathBuf::from(\"/tmp/recordings/.._evil_id.jsonl\"),\n );\n}\n\n#[test]\nfn router_attributes_session_new_to_its_minted_session() {\n let mut router = SessionRouter::default();\n\n // Connection-level traffic is shared: the readiness event immediately,\n // the initialize pair once its response shows no session was minted.\n let ready = line(\"to_server\", json!({\"type\": \"event\", \"event\": \"acp_ready\"}));\n assert_eq!(router.route(ready.clone()), vec![shared(&ready)]);\n let init_request = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 0, \"method\": \"initialize\", \"params\": {}}),\n );\n assert_eq!(router.route(init_request.clone()), vec![]);\n let init_response = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 0, \"result\": {\"protocolVersion\": 1}}),\n );\n assert_eq!(\n router.route(init_response.clone()),\n vec![shared(&init_request), shared(&init_response)],\n );\n\n // session/new is buffered until the response mints the session id, then\n // both lines land in that session.\n let new_request = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"session/new\", \"params\": {\"cwd\": \"/\"}}),\n );\n assert_eq!(router.route(new_request.clone()), vec![]);\n let new_response = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": {\"sessionId\": \"sess-1\"}}),\n );\n assert_eq!(\n router.route(new_response.clone()),\n vec![\n session(\"sess-1\", &new_request),\n session(\"sess-1\", &new_response),\n ],\n );\n\n // Traffic naming the session follows it directly.\n let update = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"method\": \"session/update\", \"params\": {\"sessionId\": \"sess-1\", \"update\": {}}}),\n );\n assert_eq!(router.route(update.clone()), vec![session(\"sess-1\", &update)]);\n}\n\n#[test]\nfn router_scopes_request_ids_by_direction() {\n let mut router = SessionRouter::default();\n\n // Both peers use id 7 concurrently: the client prompts sess-a while the\n // agent asks sess-b for permission.\n let prompt = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 7, \"method\": \"session/prompt\", \"params\": {\"sessionId\": \"sess-a\", \"prompt\": []}}),\n );\n assert_eq!(router.route(prompt.clone()), vec![session(\"sess-a\", &prompt)]);\n let permission = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 7, \"method\": \"session/request_permission\", \"params\": {\"sessionId\": \"sess-b\"}}),\n );\n assert_eq!(\n router.route(permission.clone()),\n vec![session(\"sess-b\", &permission)],\n );\n\n // Each response routes to the session of the request it answers.\n let permission_reply = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 7, \"result\": {\"outcome\": {\"outcome\": \"cancelled\"}}}),\n );\n assert_eq!(\n router.route(permission_reply.clone()),\n vec![session(\"sess-b\", &permission_reply)],\n );\n let prompt_reply = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 7, \"result\": {\"stopReason\": \"end_turn\"}}),\n );\n assert_eq!(\n router.route(prompt_reply.clone()),\n vec![session(\"sess-a\", &prompt_reply)],\n );\n}\n\n#[test]\nfn router_falls_back_to_shared_for_unattributable_lines() {\n let mut router = SessionRouter::default();\n\n // A notification naming no session, and a response to a request the\n // router never saw, both stay at connection level.\n let notification = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"method\": \"connection/ping\", \"params\": {}}),\n );\n assert_eq!(\n router.route(notification.clone()),\n vec![shared(&notification)],\n );\n let orphan_response = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 99, \"result\": {}}),\n );\n assert_eq!(\n router.route(orphan_response.clone()),\n vec![shared(&orphan_response)],\n );\n}\n\n#[test]\nfn router_drain_recovers_unanswered_requests() {\n let mut router = SessionRouter::default();\n\n let unanswered = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 3, \"method\": \"session/new\", \"params\": {\"cwd\": \"/\"}}),\n );\n assert_eq!(router.route(unanswered.clone()), vec![]);\n assert_eq!(router.drain(), vec![shared(&unanswered)]);\n assert_eq!(router.drain(), vec![]);\n}\n\n#[tokio::test]\nasync fn writer_splits_sessions_into_standalone_files() {\n let dir = std::env::temp_dir().join(format!(\n \"agent_session_recorder_writer_test_{}\",\n std::process::id()\n ));\n let _ = tokio::fs::remove_dir_all(&dir).await;\n\n let ready = line(\"to_server\", json!({\"type\": \"event\", \"event\": \"acp_ready\"}));\n let new_a_request = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"session/new\", \"params\": {\"cwd\": \"/\"}}),\n );\n let new_a_response = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 1, \"result\": {\"sessionId\": \"sess-a\"}}),\n );\n let update_a = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"method\": \"session/update\", \"params\": {\"sessionId\": \"sess-a\", \"update\": {}}}),\n );\n let ping = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"method\": \"connection/ping\", \"params\": {}}),\n );\n let new_b_request = line(\n \"to_runtime\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 2, \"method\": \"session/new\", \"params\": {\"cwd\": \"/\"}}),\n );\n let new_b_response = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"id\": 2, \"result\": {\"sessionId\": \"sess-b\"}}),\n );\n let update_b = line(\n \"to_server\",\n json!({\"type\": \"acp\", \"jsonrpc\": \"2.0\", \"method\": \"session/update\", \"params\": {\"sessionId\": \"sess-b\", \"update\": {}}}),\n );\n\n let (sink, lines) = mpsc::unbounded_channel();\n let writer = tokio::spawn(run_writer(dir.clone(), lines));\n for recorded in [\n &ready,\n &new_a_request,\n &new_a_response,\n &update_a,\n &ping,\n &new_b_request,\n &new_b_response,\n &update_b,\n ] {\n sink.send(recorded.clone()).expect(\"writer should be listening\");\n }\n drop(sink);\n timeout(Duration::from_secs(5), writer)\n .await\n .expect(\"writer should stop once the sink drops\")\n .expect(\"writer should not panic\")\n .expect(\"writer should not fail\");\n\n // sess-a was open when the shared ping arrived, so it appears in stream\n // order; sess-b opened later and gets it as part of its shared prefix.\n let recording_a = tokio::fs::read_to_string(session_recording_path(&dir, \"sess-a\"))\n .await\n .expect(\"sess-a recording should exist\");\n assert_eq!(\n recording_a.lines().collect::<Vec<_>>(),\n vec![&ready, &new_a_request, &new_a_response, &update_a, &ping],\n );\n let recording_b = tokio::fs::read_to_string(session_recording_path(&dir, \"sess-b\"))\n .await\n .expect(\"sess-b recording should exist\");\n assert_eq!(\n recording_b.lines().collect::<Vec<_>>(),\n vec![&ready, &ping, &new_b_request, &new_b_response, &update_b],\n );\n\n tokio::fs::remove_dir_all(&dir)\n .await\n .expect(\"test directory should be removable\");\n}\n\n#[tokio::test]\nasync fn tap_records_and_forwards_both_directions() {\n let (inner, mut runtime_side) = Channel::duplex();\n let (sink, mut lines) = mpsc::unbounded_channel();\n let mut tapped = record_channel(inner, sink);\n\n // Runtime -> service traffic is forwarded and recorded as to_server.\n runtime_side\n .tx\n .send(ToServerMessage::Event {\n event: SystemEvent::AcpReady,\n })\n .expect(\"tap should be listening\");\n let forwarded = timeout(Duration::from_secs(1), tapped.rx.recv())\n .await\n .expect(\"runtime message should be forwarded promptly\")\n .expect(\"tapped channel should stay open\");\n assert!(matches!(\n forwarded,\n ToServerMessage::Event {\n event: SystemEvent::AcpReady\n }\n ));\n\n // Service -> runtime traffic is forwarded and recorded as to_runtime.\n let prompt: ToRuntimeMessage = serde_json::from_value(json!({\n \"type\": \"acp\",\n \"jsonrpc\": \"2.0\",\n \"id\": 1,\n \"method\": \"session/prompt\",\n \"params\": { \"sessionId\": \"sess-1\", \"prompt\": [] },\n }))\n .expect(\"envelope should deserialize\");\n tapped.tx.send(prompt).expect(\"tap should be listening\");\n let forwarded = timeout(Duration::from_secs(1), runtime_side.rx.recv())\n .await\n .expect(\"service message should be forwarded promptly\")\n .expect(\"runtime channel should stay open\");\n assert!(matches!(forwarded, ToRuntimeMessage::Acp(_)));\n\n // Each direction was recorded before it was forwarded, so by the time\n // the forwards above were observed both lines are already in the sink,\n // in send order. Each line is Message's own serialization plus `ts`, so\n // it parses straight back into Message.\n let event_line = lines.recv().await.expect(\"event line\");\n let event_value: Value =\n serde_json::from_str(&event_line).expect(\"recorded line should be JSON\");\n assert_eq!(event_value[\"direction\"], \"to_server\");\n assert_eq!(\n event_value[\"content\"],\n json!({\"type\": \"event\", \"event\": \"acp_ready\"})\n );\n DateTime::parse_from_rfc3339(event_value[\"ts\"].as_str().expect(\"ts should be a string\"))\n .expect(\"ts should be RFC 3339\");\n let event_message: Message =\n serde_json::from_str(&event_line).expect(\"line should parse as Message\");\n assert!(matches!(\n event_message,\n Message::ToServer(ToServerMessage::Event {\n event: SystemEvent::AcpReady\n })\n ));\n\n let prompt_line = lines.recv().await.expect(\"prompt line\");\n let prompt_value: Value =\n serde_json::from_str(&prompt_line).expect(\"recorded line should be JSON\");\n assert_eq!(prompt_value[\"direction\"], \"to_runtime\");\n assert_eq!(prompt_value[\"content\"][\"type\"], \"acp\");\n assert_eq!(prompt_value[\"content\"][\"method\"], \"session/prompt\");\n assert_eq!(prompt_value[\"content\"][\"params\"][\"sessionId\"], \"sess-1\");\n let prompt_message: Message =\n serde_json::from_str(&prompt_line).expect(\"line should parse as Message\");\n assert!(matches!(\n prompt_message,\n Message::ToRuntime(ToRuntimeMessage::Acp(_))\n ));\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "The tap test uses `DateTime` which I removed from the main file's imports — add it to the test module:",
@@ -723,7 +579,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_01XiuBq9trG9cXnZA3wDu7Gp",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -736,23 +594,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs"),
- "old_string": String("use serde_json::{Value, json};\nuse tokio::time::{Duration, timeout};"),
- "new_string": String("use chrono::DateTime;\nuse serde_json::{Value, json};\nuse tokio::time::{Duration, timeout};"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01MohDMjaUKCtkLJXFwjMqVY",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -767,22 +616,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo test -p agent_session --example agent_session_recorder 2>&1 | tail -25"),
- "description": String("Run recorder example tests"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String(" Compiling agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)\n Finished `test` profile [unoptimized + debuginfo] target(s) in 3.46s\n Running unittests examples/agent_session_recorder.rs (target/debug/examples/agent_session_recorder-ab700388d3dda52c)\n\nrunning 7 tests\ntest test::session_recording_path_is_sanitized_jsonl_under_dir ... ok\ntest test::router_falls_back_to_shared_for_unattributable_lines ... ok\ntest test::router_drain_recovers_unanswered_requests ... ok\ntest test::router_attributes_session_new_to_its_minted_session ... ok\ntest test::router_scopes_request_ids_by_direction ... ok\ntest test::tap_records_and_forwards_both_directions ... ok\ntest test::writer_splits_sessions_into_standalone_files ... ok\n\ntest result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01MRKTuvyiKzhsv37MTRfvmQ",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -797,22 +638,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo fmt -p agent_session && SQLX_OFFLINE=true cargo clippy -p agent_session --examples --tests 2>&1 | tail -10"),
- "description": String("Format and lint the agent_session crate"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String(" Checking attachment v0.1.0 (/Users/eric/Code/macro/crates/attachment)\n Checking models_permissions v0.1.0 (/Users/eric/Code/macro/crates/models_permissions)\n Checking ai_usage v0.1.0 (/Users/eric/Code/macro/crates/ai_usage)\n Checking agent v0.1.0 (/Users/eric/Code/macro/crates/agent)\n Checking model v0.1.0 (/Users/eric/Code/macro/crates/model)\n Checking entity_access v0.1.0 (/Users/eric/Code/macro/crates/entity_access)\n Checking channels v0.1.0 (/Users/eric/Code/macro/crates/channels)\n Checking bots v0.1.0 (/Users/eric/Code/macro/crates/bots)\n Checking agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 7.81s\n[This command modified 2 files you've previously read: crates/agent_session/examples/agent_session_recorder.rs, crates/agent_session/examples/agent_session_recorder/test.rs. Call Read before editing.]"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LPjM3sh7fjLME6aNNvbYtu",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -823,21 +656,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/.agent_runtime_sessions/split_recording.py"),
- "content": String("#!/usr/bin/env python3\n\"\"\"Split per-process agent_session_recorder JSONL files into per-session files.\n\nMirrors the routing in crates/agent_session/examples/agent_session_recorder.rs:\n\n- lines naming `params.sessionId` go to that session's file;\n- responses are attributed via the JSON-RPC id of the request they answer\n (ids are scoped by the direction of the request);\n- a request naming no session is held until its response shows whether it\n minted a session (`session/new`);\n- connection-level lines (acp_ready, the initialize pair) are copied into\n every session file so each recording stands alone.\n\nUsage: python3 split_recording.py <recording.jsonl> [...]\n\nOutput files land next to each source as <session-id>.jsonl. Files are\nOVERWRITTEN on the first touch of a run (re-running is idempotent for the\nsame sources), so re-run this only on the old per-process files — not after\nthe new per-session recorder has appended to a session file this would clobber.\nThe source files are left untouched.\n\"\"\"\n\nimport json\nimport sys\nfrom pathlib import Path\n\n\ndef opposite(direction):\n return \"to_runtime\" if direction == \"to_server\" else \"to_server\"\n\n\ndef sanitize(session_id):\n return \"\".join(\n c if c.isascii() and (c.isalnum() or c in \"-_.\") else \"_\" for c in session_id\n )\n\n\ndef split(source: Path):\n \"\"\"Return ({session_id: [lines]}, [unattributable lines]).\"\"\"\n shared = [] # connection-level lines, copied into every session file\n sessions = {}\n\n # (issuer direction, id json) -> (\"session\", sid) | (\"unattributed\", line)\n pending = {}\n\n def to_session(sid, line):\n if sid not in sessions:\n sessions[sid] = list(shared)\n sessions[sid].append(line)\n\n def to_shared(line):\n shared.append(line)\n for lines in sessions.values():\n lines.append(line)\n\n for raw in source.read_text().splitlines():\n if not raw.strip():\n continue\n value = json.loads(raw)\n direction = value.get(\"direction\")\n content = value.get(\"content\") or {}\n method = content.get(\"method\")\n rpc_id = json.dumps(content[\"id\"]) if content.get(\"id\") is not None else None\n params = content.get(\"params\")\n sid = params.get(\"sessionId\") if isinstance(params, dict) else None\n\n if method is not None and rpc_id is not None: # request\n if sid is not None:\n pending[(direction, rpc_id)] = (\"session\", sid)\n to_session(sid, raw)\n else:\n pending[(direction, rpc_id)] = (\"unattributed\", raw)\n elif method is not None: # notification\n to_session(sid, raw) if sid is not None else to_shared(raw)\n elif rpc_id is not None: # response\n kind, val = pending.pop((opposite(direction), rpc_id), (None, None))\n if kind == \"session\":\n to_session(val, raw)\n elif kind == \"unattributed\":\n result = content.get(\"result\")\n minted = result.get(\"sessionId\") if isinstance(result, dict) else None\n if minted is not None:\n to_session(minted, val)\n to_session(minted, raw)\n else:\n to_shared(val)\n to_shared(raw)\n else:\n to_shared(raw)\n else: # not JSON-RPC, e.g. the acp_ready event\n to_shared(raw)\n\n # Requests that never got a response (connection died mid-request).\n for key in sorted(pending):\n kind, val = pending[key]\n if kind == \"unattributed\":\n to_shared(val)\n\n return sessions\n\n\ndef main():\n sources = [Path(arg).expanduser() for arg in sys.argv[1:]]\n if not sources:\n sys.exit(__doc__)\n\n touched = set()\n for source in sources:\n sessions = split(source)\n if not sessions:\n print(f\"{source}: no sessions found\")\n continue\n for sid, lines in sessions.items():\n target = source.parent / f\"{sanitize(sid)}.jsonl\"\n if target.resolve() == source.resolve():\n sys.exit(f\"refusing to overwrite source {source}\")\n mode = \"a\" if target in touched else \"w\"\n with open(target, mode) as f:\n f.write(\"\\n\".join(lines) + \"\\n\")\n touched.add(target)\n print(f\"{source.name}: {len(lines):4} lines -> {target.name}\")\n\n\nif __name__ == \"__main__\":\n main()\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/.agent_runtime_sessions/split_recording.py (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018xbq9fhqGHb88EBgsfVisi",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -852,15 +678,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("python3 ~/.agent_runtime_sessions/split_recording.py ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl"),
- "description": String("Split the per-process recording into per-session files"),
- },
- ),
- raw_output: Some(
- String("2026-08-03T20-08-59Z.jsonl: 139 lines -> cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl\n2026-08-03T20-08-59Z.jsonl: 14 lines -> ab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl\n2026-08-03T20-08-59Z.jsonl: 238 lines -> 1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl"),
- ),
},
Text {
text: "Split done. Now verify nothing was lost and no session file contains another session's traffic:",
@@ -869,7 +686,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_013ZZhkrMVi1WUobYm5iLFBp",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -884,21 +703,14 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("python3 - <<'EOF'\nimport json\nfrom pathlib import Path\n\nd = Path.home() / \".agent_runtime_sessions\"\nsource = (d / \"2026-08-03T20-08-59Z.jsonl\").read_text().splitlines()\noutputs = {p.name: p.read_text().splitlines() for p in d.glob(\"*.jsonl\") if len(p.stem) == 36}\n\nunion = set()\nfor name, lines in outputs.items():\n sids = set()\n for l in lines:\n json.loads(l) # every line parses\n c = json.loads(l).get(\"content\", {})\n p = c.get(\"params\")\n if isinstance(p, dict) and \"sessionId\" in p:\n sids.add(p[\"sessionId\"])\n r = c.get(\"result\")\n if isinstance(r, dict) and \"sessionId\" in r:\n sids.add(r[\"sessionId\"])\n union.update(lines)\n print(f\"{name}: {len(lines)} lines, sessionIds referenced: {sids}\")\n\nmissing = [l for l in source if l not in union]\nprint(f\"\\nsource lines: {len(source)}, missing from all outputs: {len(missing)}\")\nfor l in missing[:5]:\n print(\"MISSING:\", l[:200])\nEOF"),
- "description": String("Verify split coverage and per-file session purity"),
- },
- ),
- raw_output: Some(
- String("ab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl: 14 lines, sessionIds referenced: {'ab25cf29-d876-4ec6-9c30-dac24f13bcfe'}\n1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl: 238 lines, sessionIds referenced: {'1c6f5dbc-0fa8-4558-8ebb-3165a1daea56'}\ncdf15e0e-c8b7-486e-93de-f596f547e641.jsonl: 139 lines, sessionIds referenced: {'cdf15e0e-c8b7-486e-93de-f596f547e641'}\n\nsource lines: 395, missing from all outputs: 10\nMISSING: {\"ts\":\"2026-08-03T20:36:03.763Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\nMISSING: {\"ts\":\"2026-08-03T20:36:03.764Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\nMISSING: {\"ts\":\"2026-08-03T20:36:03.764Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"_meta\nMISSING: {\"ts\":\"2026-08-03T20:36:07.713Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"sessi\nMISSING: {\"ts\":\"2026-08-03T20:36:09.553Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"update\":{\"sessi"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_011jsLuU3pdvMBZ5UQuv87Mz",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -913,16 +725,6 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo install --locked --path /Users/eric/Code/macro/crates/agent_session --example agent_session_recorder 2>&1 | tail -5"),
- "description": String("Install the updated recorder binary to ~/.cargo/bin"),
- "timeout": Number(600000),
- },
- ),
- raw_output: Some(
- String("warning: package `spin v0.10.0` in Cargo.lock is yanked in registry `crates-io`, consider running without --locked\n Compiling agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)\n Finished `release` profile [optimized] target(s) in 4.72s\n Replacing /Users/eric/.cargo/bin/agent_session_recorder\n Replaced package `agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)` with `agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)` (executable `agent_session_recorder`)"),
- ),
},
Text {
text: "Done — new recorder installed, tests passing, and your existing recording is backfilled into per-session files.\n\n**Recorder changes** (`crates/agent_session/examples/agent_session_recorder.rs`): recordings are now one file per ACP session, named `~/.agent_runtime_sessions/<session-id>.jsonl`. Since one process multiplexes many sessions, a `SessionRouter` attributes each recorded line: lines carrying `params.sessionId` route directly; responses (which never name a session) are matched to their request by JSON-RPC id, scoped by direction since the two peers' id spaces are independent; a `session/new` request is held until its response mints the id, then both lines open that session's file. Connection-level traffic (`acp_ready`, the `initialize` handshake) is copied into every session file so each recording replays standalone, and files open in append mode so a session resumed by a later process continues its existing file. Also, still flushed per line — buffering was never the issue. 7 tests pass (router attribution, direction-scoped ids, drain on disconnect, and an end-to-end writer test), fmt and clippy are clean.\n\n**Backfill**: your single `2026-08-03T20-08-59Z.jsonl` split into three session files (139, 14, and 238 lines). I verified every line parses, each file references only its own sessionId, and every source line landed in a file — except 10 lines timestamped seconds after the split ran, which is this very conversation: **you're talking to me through the old recorder process right now**, and it's still appending to the timestamp file.\n\nSo one manual step remains, in this order:\n\n1. When you're done with this session, restart the agent server in Zed (the new binary is already installed at `~/.cargo/bin/agent_session_recorder`).\n2. Re-run `python3 ~/.agent_runtime_sessions/split_recording.py ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl` to pick up the tail — it rewrites the session files from scratch, so run it **before** starting new recorded sessions (a resumed session would otherwise get clobbered).\n3. Delete the old timestamp file once you're happy.\n\nThe changes are uncommitted in your working copy; let me know if you want a jj commit/PR for them.",
@@ -995,7 +797,9 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
id: ToolUseId(
"toolu_01VdTdh7sXMuLbz5B7D35poo",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Pending,
detail: Terminal {
command: Some(
@@ -1004,29 +808,20 @@ input_file: crates/agent_fold/fixtures/real/real_multi_turn.jsonl
output: None,
exit_code: None,
},
- raw_input: Some(
- Object {
- "command": String("python3 ~/.agent_runtime_sessions/split_recording.py ~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl"),
- "description": String("Re-split to capture the recording tail before deleting"),
- },
- ),
- raw_output: None,
},
ToolUse {
id: ToolUseId(
"toolu_01JnxGKMHWwnZCHCc7RWuBxk",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Pending,
detail: Terminal {
command: None,
output: None,
exit_code: None,
},
- raw_input: Some(
- Object {},
- ),
- raw_output: None,
},
],
},
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
index 0b10a2b6bc..c3d9891af7 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_and_continued.jsonl.snap
@@ -19,7 +19,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_01JmdVCbwRjVNdCaXZAy6rL8",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -34,41 +36,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls /Users/eric/Code/macro/crates/agent_session/examples/ 2>/dev/null; ls /Users/eric/Code/macro/crates/agent_runtime_protocol/examples/ 2>/dev/null"),
- "description": String("Locate the example file's actual crate"),
- },
- ),
- raw_output: Some(
- String("\u{1b}[0m\u{1b}[01;34magent_session_recorder\u{1b}[0m\n\u{1b}[00magent_session_recorder.rs\u{1b}[0m\n\u{1b}[0m\u{1b}[00macp.rs\u{1b}[0m\n\u{1b}[00mevents.rs\u{1b}[0m\n\u{1b}[01;34mmock_container\u{1b}[0m\n\u{1b}[00mmock_container.rs\u{1b}[0m\n\u{1b}[00mwebsocket.rs\u{1b}[0m"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01JzF7TRdp8Hua7s8ogcF8bK",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/.zed/settings.json",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/.zed/settings.json"),
- },
- ),
- raw_output: Some(
- String("1\t{\n2\t \"disable_ai\": false,\n3\t \"show_edit_predictions\": false,\n4\t \"lsp\": {\n5\t \"biome\": {\n6\t \"settings\": {\n7\t \"config_path\": \"app/biome.jsonc\",\n8\t \"require_config_file\": true,\n9\t }\n10\t }\n11\t },\n12\t \"languages\": {\n13\t \"CSS\": {\n14\t \"language_servers\": [\"tailwindcss-language-server\", \"!vscode-css-language-server\"]\n15\t }\n16\t },\n17\t \"use_on_type_format\": false\n18\t}\n19\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01V3ua93NVQMzvw1UuSyz5Ds",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -83,21 +72,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n -A 12 'agent_servers' ~/.config/zed/settings.json 2>/dev/null || echo \"not found in user settings\""),
- "description": String("Look for agent_servers in user Zed settings"),
- },
- ),
- raw_output: Some(
- String("127:\t\"agent_servers\": {\n128- \"Recorded Claude\": {\n129- \"type\": \"custom\",\n130- \"command\": \"/bin/bash\",\n131- \"args\": [\n132- \"-c\",\n133- \"exec env -u ANTHROPIC_API_KEY /Users/eric/Code/macro/target/debug/examples/agent_session_recorder\"\n134- ]\n135-\t }\n136-\t}\n137-}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_014z9EgjHhbpdT4oiKKbKVoi",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -110,45 +92,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs"),
- "old_string": String("//! Build the recorder, then point an ACP client at the binary:\n//!\n//! ```text\n//! cargo build -p agent_session --example agent_session_recorder\n//! ```\n//!\n//! Zed `settings.json` (use an absolute path - Zed does not expand `~`; the\n//! `env -u` strips a stray API key from the environment so the session uses\n//! the subscription login):\n//!\n//! ```text\n//! \"agent_servers\": {\n//! \"Recorded Claude\": {\n//! \"type\": \"custom\",\n//! \"command\": \"/bin/bash\",\n//! \"args\": [\n//! \"-c\",\n//! \"exec env -u ANTHROPIC_API_KEY <repo>/target/debug/examples/agent_session_recorder\"\n//! ]\n//! }\n//! }\n//! ```"),
- "new_string": String("//! Install the recorder to `~/.cargo/bin`, then point an ACP client at the\n//! installed binary:\n//!\n//! ```text\n//! cargo install --path crates/agent_session --example agent_session_recorder\n//! ```\n//!\n//! Zed `settings.json` (the shell resolves the binary from `$HOME`, so no\n//! hardcoded paths; the `env -u` strips a stray API key from the environment\n//! so the session uses the subscription login):\n//!\n//! ```text\n//! \"agent_servers\": {\n//! \"Recorded Claude\": {\n//! \"type\": \"custom\",\n//! \"command\": \"/bin/bash\",\n//! \"args\": [\n//! \"-c\",\n//! \"exec env -u ANTHROPIC_API_KEY \\\"$HOME/.cargo/bin/agent_session_recorder\\\"\"\n//! ]\n//! }\n//! }\n//! ```"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01RDnLaxGffMSSDvnHToEarF",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/.config/zed/settings.json",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/.config/zed/settings.json"),
- "offset": Number(120),
- "limit": Number(20),
- },
- ),
- raw_output: Some(
- String("120\t\t\"lsp\": {\n121\t\t\t\"biome\": {\n122\t\t\t\t\"settings\": {\n123\t\t\t\t\t\"config_path\": \"biome.jsonc\"\n124\t\t\t\t}\n125\t\t\t}\n126\t\t},\n127\t\t\"agent_servers\": {\n128\t \"Recorded Claude\": {\n129\t \"type\": \"custom\",\n130\t \"command\": \"/bin/bash\",\n131\t \"args\": [\n132\t \"-c\",\n133\t \"exec env -u ANTHROPIC_API_KEY /Users/eric/Code/macro/target/debug/examples/agent_session_recorder\"\n134\t ]\n135\t\t }\n136\t\t}\n137\t}\n138\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_017vXvd3YJFsTDHjuqH1pm9J",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -161,17 +126,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/.config/zed/settings.json"),
- "old_string": String(" \"exec env -u ANTHROPIC_API_KEY /Users/eric/Code/macro/target/debug/examples/agent_session_recorder\""),
- "new_string": String(" \"exec env -u ANTHROPIC_API_KEY \\\"$HOME/.cargo/bin/agent_session_recorder\\\"\""),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/.config/zed/settings.json has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now installing the binary (release build, may take a few minutes):",
@@ -180,7 +134,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_01VScDhwjTxikVfbmwUoxaok",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -195,22 +151,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo install --path crates/agent_session --example agent_session_recorder 2>&1 | tail -5"),
- "description": String("Install agent_session_recorder example to ~/.cargo/bin"),
- "timeout": Number(600000),
- },
- ),
- raw_output: Some(
- String(" [email protected] requires rustc 1.94.1\n [email protected] requires rustc 1.94.1\n Either upgrade rustc or select compatible dependency versions with\n `cargo update <name>@<current-ver> --precise <compatible-ver>`\n where `<compatible-ver>` is the latest version supporting rustc 1.94.0"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01ETt3DxUVQNopgU44xbSc69",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -225,21 +173,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat /Users/eric/Code/macro/rust-toolchain.toml 2>/dev/null; rustup show active-toolchain; rustc --version"),
- "description": String("Check pinned rust toolchain versions"),
- },
- ),
- raw_output: Some(
- String("[toolchain]\nchannel = \"1.94.0\"\ncomponents = [\"clippy\", \"rustfmt\", \"rust-analyzer\", \"rust-src\"]\n# The linux-gnu targets are required by `cargo x zigbuild` (the local\n# orchestrator cross-compiles service binaries for the runtime image). They\n# don't affect the fenix channel-manifest hash in nix/cloud-storage.nix (targets\n# are selected after the manifest is fetched), so adding one needs no hash bump.\ntargets = [\n \"wasm32-unknown-unknown\",\n \"aarch64-unknown-linux-gnu\",\n \"x86_64-unknown-linux-gnu\",\n]\nrustup shim only supports commands used by cross\nrustc 1.94.0 (4a4ef493e 2026-03-02)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01GSaPYdcfh8YP2kDfjgb3v9",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -254,16 +195,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo install --locked --path crates/agent_session --example agent_session_recorder 2>&1 | tail -5"),
- "description": String("Install recorder with workspace lockfile"),
- "timeout": Number(600000),
- },
- ),
- raw_output: Some(
- String(" Compiling bots v0.1.0 (/Users/eric/Code/macro/crates/bots)\n Compiling agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)\n Finished `release` profile [optimized] target(s) in 1m 38s\n Installing /Users/eric/.cargo/bin/agent_session_recorder\n Installed package `agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)` (executable `agent_session_recorder`)"),
- ),
},
Text {
text: "The install needed `--locked`, so I'll add that to the documented command too:",
@@ -272,7 +203,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_01KsnUYkdiXpsCnKiLAaBwEC",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -285,23 +218,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs"),
- "old_string": String("//! Install the recorder to `~/.cargo/bin`, then point an ACP client at the\n//! installed binary:\n//!\n//! ```text\n//! cargo install --path crates/agent_session --example agent_session_recorder\n//! ```"),
- "new_string": String("//! Install the recorder to `~/.cargo/bin` (`--locked` keeps the workspace\n//! lockfile's dependency versions, which the pinned toolchain requires), then\n//! point an ACP client at the installed binary:\n//!\n//! ```text\n//! cargo install --locked --path crates/agent_session --example agent_session_recorder\n//! ```"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/examples/agent_session_recorder.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01C7ZWnHKJy4TwzpXiReZgcz",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -316,15 +240,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls -la ~/.cargo/bin/agent_session_recorder"),
- "description": String("Verify installed binary exists"),
- },
- ),
- raw_output: Some(
- String("-rwxr-xr-x 1 eric staff 6109552 Aug 3 16:07 \u{1b}[0m\u{1b}[00;32m/Users/eric/.cargo/bin/agent_session_recorder\u{1b}[0m"),
- ),
},
Text {
text: "Done. The recorder is now installed at `~/.cargo/bin/agent_session_recorder` and Zed points at it instead of the debug build in `target/`.\n\nThree changes:\n\n1. **Doc comment** in `crates/agent_session/examples/agent_session_recorder.rs` — the build command is now `cargo install --locked --path crates/agent_session --example agent_session_recorder`, and the sample Zed config uses `\"$HOME/.cargo/bin/agent_session_recorder\"` (bash expands `$HOME`, so no hardcoded repo path).\n2. **`~/.config/zed/settings.json`** — the \"Recorded Claude\" agent server now execs the installed binary via `$HOME/.cargo/bin` instead of `/Users/eric/Code/macro/target/debug/examples/...`.\n3. **Ran the install** — it succeeded and the binary is in place. One wrinkle worth knowing: plain `cargo install` failed because it ignores `Cargo.lock` and resolved an `aws-types` that needs rustc 1.94.1 (the repo pins 1.94.0). `--locked` fixes that, which is why it's in the documented command.\n\nAfter future changes to the recorder, re-run the install command to refresh the binary — Zed no longer picks up `cargo build` output automatically.Yes — in your user-level Zed settings at `~/.config/zed/settings.json` (the `agent_servers` block wasn't in the project's `.zed/settings.json`). The \"Recorded Claude\" entry's command changed from:\n\n```\nexec env -u ANTHROPIC_API_KEY /Users/eric/Code/macro/target/debug/examples/agent_session_recorder\n```\n\nto:\n\n```\nexec env -u ANTHROPIC_API_KEY \"$HOME/.cargo/bin/agent_session_recorder\"\n```\n\nEverything else in the file is untouched. You may need to restart the agent server in Zed (or reopen the panel) for it to pick up the new command.",
@@ -411,7 +326,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_015c1NGtLCDbzzN6gLsNek6c",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -426,15 +343,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls -la ~/.agent_runtime_sessions/ 2>&1"),
- "description": String("Check for session recordings directory"),
- },
- ),
- raw_output: Some(
- String("total 132\ndrwxr-xr-x 4 eric staff 128 Aug 3 16:08 \u{1b}[0m\u{1b}[01;34m.\u{1b}[0m\ndrwxr-x--- 131 eric staff 4192 Aug 3 16:12 \u{1b}[01;34m..\u{1b}[0m\n-rw-r--r-- 1 eric staff 99509 Aug 3 16:12 2026-08-03T20-08-59Z.jsonl\ndrwxr-xr-x 9 eric staff 288 Aug 3 11:12 \u{1b}[01;34mclaude_config\u{1b}[0m"),
- ),
},
Permission {
tool_call: ToolUseId(
@@ -508,7 +416,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_01SfjW3NaG4UD6znQMU23cyf",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -523,15 +433,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("jj log -r 'claude-recorder | @ | @-' --no-pager -T 'change_id.short() ++ \" \" ++ bookmarks ++ \" \" ++ description.first_line() ++ \"\\n\"' && jj st --no-pager"),
- "description": String("Show jj log around claude-recorder bookmark and working copy status"),
- },
- ),
- raw_output: Some(
- String("@ szwwkmusnqwv fold\n○ zyrwruupsoys claude-recorder feat: claude recorder\n│\n~\nWorking copy changes:\nM .zed/settings.json\nM Cargo.lock\nM Cargo.toml\nA crates/agent_fold/Cargo.toml\nA crates/agent_fold/src/domain/error.rs\nA crates/agent_fold/src/domain/mod.rs\nA crates/agent_fold/src/domain/ports.rs\nA crates/agent_fold/src/inbound/comms_message.rs\nA crates/agent_fold/src/inbound/mod.rs\nA crates/agent_fold/src/lib.rs\nM crates/agent_session/examples/agent_session_recorder.rs\nWorking copy (@) : szwwkmus 432cbf81 fold\nParent commit (@-): zyrwruup e5adf6d1 claude-recorder | feat: claude recorder\nWarning: These bookmarks have conflicts:\n attachment-rework-integration\n auto-deploy-lexical-service-paths\n ci/gitlab-ci-migration\n eric.hayes/macro-1558-duplicate-task-detection\n fix-ai-stream-logging\n fix-sfs-log-acl\n improve-tracing\n litellm\n mcp-auth-fix\n mcp-notion\n remove-dps\n scheduled-agents\n sfs-monitoring\n wolf/acp-cleanup\nHint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve."),
- ),
},
Permission {
tool_call: ToolUseId(
@@ -562,7 +463,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_01CtXAUSJxvsbs2FD7QmMqDu",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -577,15 +480,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("jj squash --from @ --into claude-recorder --use-destination-message crates/agent_session/examples/agent_session_recorder.rs && jj st --no-pager"),
- "description": String("Squash example file change into claude-recorder commit"),
- },
- ),
- raw_output: Some(
- String("Rebased 1 descendant commits\nWorking copy (@) now at: szwwkmus 3612559a fold\nParent commit (@-) : zyrwruup 42fc9eef claude-recorder* | feat: claude recorder\nWorking copy changes:\nM .zed/settings.json\nM Cargo.lock\nM Cargo.toml\nA crates/agent_fold/Cargo.toml\nA crates/agent_fold/src/domain/error.rs\nA crates/agent_fold/src/domain/mod.rs\nA crates/agent_fold/src/domain/ports.rs\nA crates/agent_fold/src/inbound/comms_message.rs\nA crates/agent_fold/src/inbound/mod.rs\nA crates/agent_fold/src/lib.rs\nWorking copy (@) : szwwkmus 3612559a fold\nParent commit (@-): zyrwruup 42fc9eef claude-recorder* | feat: claude recorder\nWarning: These bookmarks have conflicts:\n attachment-rework-integration\n auto-deploy-lexical-service-paths\n ci/gitlab-ci-migration\n eric.hayes/macro-1558-duplicate-task-detection\n fix-ai-stream-logging\n fix-sfs-log-acl\n improve-tracing\n litellm\n mcp-auth-fix\n mcp-notion\n remove-dps\n scheduled-agents\n sfs-monitoring\n wolf/acp-cleanup\nHint: Use `jj bookmark list` to see details. Use `jj bookmark set <name> -r <rev>` to resolve."),
- ),
},
Permission {
tool_call: ToolUseId(
@@ -619,7 +513,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_01C3WXuHqyYExW1fkiSdhQBm",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -634,15 +530,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("jj git push -b claude-recorder 2>&1"),
- "description": String("Push claude-recorder bookmark to remote"),
- },
- ),
- raw_output: Some(
- String("Changes to push to origin:\n Move sideways bookmark claude-recorder from e5adf6d16c51 to 42fc9eef52a7\nremote: \nremote: GitHub found 21 vulnerabilities on macro-inc/macro's default branch (8 high, 8 moderate, 5 low). To find out more, visit: \nremote: https://github.com/macro-inc/macro/security/dependabot \nremote:"),
- ),
},
Permission {
tool_call: ToolUseId(
@@ -673,7 +560,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
id: ToolUseId(
"toolu_011EjWXxbBUL3LeeWdhwZzVE",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -688,15 +577,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_and_continued.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("gh pr view claude-recorder --json number,title,url,state -q '\"\\(.number) \\(.title) \\(.state) \\(.url)\"' 2>&1"),
- "description": String("Confirm the PR picked up the push"),
- },
- ),
- raw_output: Some(
- String("5373 feat: claude recorder OPEN https://github.com/macro-inc/macro/pull/5373"),
- ),
},
Permission {
tool_call: ToolUseId(
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
index e11451718b..787942d4a5 100644
--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap
@@ -19,7 +19,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_016KvA9QfpBcmLNajBmQNpSV",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -34,21 +36,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("find /Users/eric/Code/macro/crates/agent_fold /Users/eric/Code/macro/crates/agent_runtime_protocol -type f | head -50"),
- "description": String("List files in both crates"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/Code/macro/crates/agent_fold/Cargo.toml\n/Users/eric/Code/macro/crates/agent_runtime_protocol/Cargo.toml\n/Users/eric/Code/macro/crates/agent_fold/src/lib.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/events.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/mock_container.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/websocket.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/acp.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/lib.rs\n/Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs\n/Users/eric/Code/macro/crates/agent_fold/src/inbound/mod.rs\n/Users/eric/Code/macro/crates/agent_fold/src/domain/ports.rs\n/Users/eric/Code/macro/crates/agent_fold/src/domain/error.rs\n/Users/eric/Code/macro/crates/agent_fold/src/domain/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/examples/mock_container/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/bin/export_types.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/fake_wire.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/wire_conformance.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/ports.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/channel.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/connection/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/testing/fake_wire/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/websocket/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/outbound/websocket/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/mod.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/test.rs\n/Users/eric/Code/macro/crates/agent_runtime_protocol/src/domain/schema/v0/mod.rs"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_015HGRRG8ibnJVuZ3s4TupsE",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -63,21 +58,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls ~/.agent_session_recordings/ 2>/dev/null | head -20"),
- "description": String("List session recordings"),
- },
- ),
- raw_output: Some(
- String("(Bash completed with no output)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01GLwvbuuYzjinKZv1Kwpbu4",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -92,21 +80,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd /Users/eric/Code/macro/crates/agent_fold && for f in Cargo.toml src/lib.rs src/domain/mod.rs src/domain/ports.rs src/domain/error.rs src/inbound/mod.rs src/inbound/comms_message.rs; do echo \"===== $f =====\"; cat -n \"$f\"; done"),
- "description": String("Read agent_fold crate"),
- },
- ),
- raw_output: Some(
- String("===== Cargo.toml =====\n 1\t[package]\n 2\tname = \"agent_fold\"\n 3\tversion = \"0.1.0\"\n 4\tedition = \"2024\"\n 5\t\n 6\t[dependencies]\n 7\tthiserror = { workspace = true }\n 8\tnon_empty = { path = \"../non_empty\" }\n===== src/lib.rs =====\n 1\tmod domain;\n===== src/domain/mod.rs =====\n 1\tmod error;\n 2\tmod ports;\n===== src/domain/ports.rs =====\n 1\t\n===== src/domain/error.rs =====\n 1\tuse thiserror::Error;\n 2\t\n 3\tpub type Result<T, E = Error> = std::result::Result<T, E>;\n 4\t\n 5\t#[derive(Debug, Clone, Error)]\n 6\t#[error(\"fold error\")]\n 7\tpub enum Error {}\n===== src/inbound/mod.rs =====\n 1\t\n===== src/inbound/comms_message.rs ====="),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01DB7JxnjAW9FCjSdAYhapYw",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -121,15 +102,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd /Users/eric/Code/macro/crates/agent_runtime_protocol && wc -l src/domain/schema/v0/mod.rs src/domain/mod.rs src/lib.rs && echo ---- && ls ~/.agent_session_recordings 2>&1; ls -la ~/ | grep -i agent"),
- "description": String("Check protocol sizes"),
- },
- ),
- raw_output: Some(
- String(" 124 src/domain/schema/v0/mod.rs\n 10 src/domain/mod.rs\n 15 src/lib.rs\n 149 total\n----\nls: cannot access '/Users/eric/.agent_session_recordings': No such file or directory\ndrwxr-xr-x 6 eric staff 192 Aug 3 16:40 \u{1b}[01;34m.agent_runtime_sessions\u{1b}[0m"),
- ),
},
Text {
text: "The crate is essentially empty stubs. Let me read the protocol schema and find the comms message models.",
@@ -138,7 +110,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01FkFADbJ7W3WdgvzpGWnTji",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -153,21 +127,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("for f in src/lib.rs src/domain/mod.rs src/domain/schema/mod.rs src/domain/schema/v0/mod.rs; do echo \"===== $f =====\"; cat -n \"$f\"; done"),
- "description": String("Read protocol schema"),
- },
- ),
- raw_output: Some(
- String("===== src/lib.rs =====\n 1\t#![deny(missing_docs)]\n 2\t//! Agent Runtime Protocol wire types.\n 3\t//!\n 4\t//! The Agent Runtime Protocol is the outer protocol used to communicate with\n 5\t//! an agent runtime. It carries Agent Client Protocol (ACP) messages alongside\n 6\t//! runtime control messages without interpreting the wrapped ACP payloads.\n 7\t\n 8\t/// Protocol schema, role-oriented connections, and the runtime wire port.\n 9\tpub mod domain;\n 10\t/// Adapters implementing the domain wire port over physical transports.\n 11\tpub mod outbound;\n 12\t\n 13\t/// Utilities for asserting direction-labelled JSON messages at the wire boundary.\n 14\t#[cfg(any(test, feature = \"test-utils\"))]\n 15\tpub mod testing;\n===== src/domain/mod.rs =====\n 1\t//! Domain layer: protocol schema, role-oriented connections, and the physical transport port.\n 2\t\n 3\t/// A typed duplex channel over the logical protocol stream.\n 4\tpub mod channel;\n 5\t/// Role-oriented connections over a logical Agent Runtime Protocol stream.\n 6\tpub mod connection;\n 7\t/// The physical transport port.\n 8\tpub mod ports;\n 9\t/// Versioned protocol message types.\n 10\tpub mod schema;\n===== src/domain/schema/mod.rs =====\n 1\t//! Agent Runtime Protocol schema types.\n 2\t\n 3\t/// Draft `agent-runtime.v0` schema types.\n 4\tpub mod v0;\n===== src/domain/schema/v0/mod.rs =====\n 1\t//! Draft `agent-runtime.v0` message types.\n 2\t//!\n 3\t//! The logical protocol multiplexes two kinds of traffic over one stream:\n 4\t//! runtime/agent lifecycle events and ACP conversation traffic. Each\n 5\t//! direction has its own envelope - [`ToRuntimeMessage`] for Agent Service to\n 6\t//! Agent Runtime traffic and [`ToServerMessage`] for the reverse -\n 7\t//! discriminated by a `\"type\"` field. Only the wrapped ACP payload is itself\n 8\t//! a JSON-RPC message; the outer envelope is not.\n 9\t//!\n 10\t//! A connection hosts exactly one agent execution, so nothing on this schema\n 11\t//! needs an agent or agent-instance identifier: [`AcpMessage`] simply carries\n 12\t//! the agent's raw ACP traffic.\n 13\t\n 14\tuse agent_client_protocol::RawJsonRpcMessage;\n 15\tuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n 16\tuse specta::Type;\n 17\tuse specta_typescript::Unknown;\n 18\t\n 19\t#[cfg(test)]\n 20\tmod test;\n 21\t\n 22\t/// The kind of runtime or agent state transition reported to the Agent Service.\n 23\t///\n 24\t/// The protocol does not define a full event-name catalog yet, so this enum\n 25\t/// is non-exhaustive: unrecognized wire strings still round-trip losslessly\n 26\t/// through [`SystemEvent::Unknown`]. [`SystemEvent::AcpReady`] is the one\n 27\t/// name the Agent Service actually acts on (see\n 28\t/// `agent_proxy::inbound::runtime::RuntimeConnectionDriver`, which waits for\n 29\t/// it before starting the ACP `initialize`/`session/new` handshake) rather\n 30\t/// than merely forwarding it for observability.\n 31\t///\n 32\t/// This has a hand-written [`Serialize`]/[`Deserialize`] impl rather than a\n 33\t/// derive, so it cannot derive [`specta::Type`] either: nothing here\n 34\t/// introspects its shape for TypeScript. Every field that carries a\n 35\t/// `SystemEvent` is instead given a `#[specta(type = String)]` override at\n 36\t/// the field, matching the plain string it actually serializes as.\n 37\t#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n 38\t#[non_exhaustive]\n 39\tpub enum SystemEvent {\n 40\t /// The Agent Runtime's hosted agent process is up and its ACP channel is\n 41\t /// wired end-to-end: the Agent Service may now start the ACP\n 42\t /// `initialize`/`session/new` handshake. Sent at most once per\n 43\t /// connection, before any ACP traffic.\n 44\t AcpReady,\n 45\t /// An application-defined event name with no protocol-level meaning yet.\n 46\t Unknown(String),\n 47\t}\n 48\t\n 49\timpl SystemEvent {\n 50\t /// Borrow the wire string for this event name.\n 51\t #[must_use]\n 52\t pub fn as_str(&self) -> &str {\n 53\t match self {\n 54\t Self::AcpReady => \"acp_ready\",\n 55\t Self::Unknown(name) => name,\n 56\t }\n 57\t }\n 58\t}\n 59\t\n 60\timpl Serialize for SystemEvent {\n 61\t fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n 62\t where\n 63\t S: Serializer,\n 64\t {\n 65\t serializer.serialize_str(self.as_str())\n 66\t }\n 67\t}\n 68\t\n 69\timpl<'de> Deserialize<'de> for SystemEvent {\n 70\t fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n 71\t where\n 72\t D: Deserializer<'de>,\n 73\t {\n 74\t Ok(match String::deserialize(deserializer)?.as_str() {\n 75\t \"acp_ready\" => Self::AcpReady,\n 76\t name => Self::Unknown(name.to_owned()),\n 77\t })\n 78\t }\n 79\t}\n 80\t\n 81\t/// One complete ACP JSON-RPC message routed between the Agent Service and the\n 82\t/// single agent execution hosted by this connection.\n 83\t///\n 84\t/// Its own JSON-RPC fields are opaque to TypeScript consumers here (typed as\n 85\t/// an arbitrary object of unknown values): they already have a proper ACP SDK\n 86\t/// on the TypeScript side, so this crate only needs to guarantee the message\n 87\t/// round-trips unchanged. This is typed as a map rather than plain `unknown`\n 88\t/// because [`ToRuntimeMessage`]/[`ToServerMessage`] carry it in an internally\n 89\t/// tagged `Acp` variant, which requires its payload provably serialize as an\n 90\t/// object so the `\"type\"` tag can be merged into it. `#[serde(transparent)]`\n 91\t/// changes nothing about the actual wire format here - a single-field tuple\n 92\t/// struct already serializes transparently by default - but it does tell\n 93\t/// specta's serde-compatibility checker that this newtype is transparent, so\n 94\t/// it looks through to the map type below instead of treating `AcpMessage`\n 95\t/// itself as an opaque, non-mergeable struct.\n 96\t#[derive(Debug, Clone, Serialize, Deserialize, Type)]\n 97\t#[serde(transparent)]\n 98\tpub struct AcpMessage(\n 99\t #[specta(type = std::collections::HashMap<String, Unknown>)] pub RawJsonRpcMessage,\n 100\t);\n 101\t\n 102\t/// Agent Service to Agent Runtime traffic on the logical protocol stream.\n 103\t#[derive(Debug, Clone, Serialize, Deserialize, Type)]\n 104\t#[serde(tag = \"type\", rename_all = \"camelCase\")]\n 105\t#[non_exhaustive]\n 106\tpub enum ToRuntimeMessage {\n 107\t /// An ACP message routed to the hosted agent.\n 108\t Acp(AcpMessage),\n 109\t}\n 110\t\n 111\t/// Agent Runtime to Agent Service traffic on the logical protocol stream.\n 112\t#[derive(Debug, Clone, Serialize, Deserialize, Type)]\n 113\t#[serde(tag = \"type\", rename_all = \"camelCase\")]\n 114\t#[non_exhaustive]\n 115\tpub enum ToServerMessage {\n 116\t /// An ACP message routed from the hosted agent.\n 117\t Acp(AcpMessage),\n 118\t /// A runtime or agent lifecycle event.\n 119\t Event {\n 120\t /// The event name.\n 121\t #[specta(type = String)]\n 122\t event: SystemEvent,\n 123\t },\n 124\t}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01SeJKBY6azjALY8kj4uq27Y",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -182,15 +149,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls -R ~/.agent_runtime_sessions | head -40"),
- "description": String("List runtime sessions dir"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.agent_runtime_sessions:\n1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl\nab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl\ncdf15e0e-c8b7-486e-93de-f596f547e641.jsonl\n\u{1b}[0m\u{1b}[01;34mclaude_config\u{1b}[0m\n\n/Users/eric/.agent_runtime_sessions/claude_config:\n\u{1b}[01;34mbackups\u{1b}[0m\npolicy-limits.json\n\u{1b}[01;34mprojects\u{1b}[0m\nremote-settings.json\n\u{1b}[01;34msessions\u{1b}[0m\nsettings.json\n\n/Users/eric/.agent_runtime_sessions/claude_config/backups:\n\n/Users/eric/.agent_runtime_sessions/claude_config/projects:\n\u{1b}[01;34m-Users-eric-Code-macro\u{1b}[0m\n\u{1b}[01;34m-Users-eric-Code-macro-crates\u{1b}[0m\n\n/Users/eric/.agent_runtime_sessions/claude_config/projects/-Users-eric-Code-macro:\n\u{1b}[01;34mmemory\u{1b}[0m\n\n/Users/eric/.agent_runtime_sessions/claude_config/projects/-Users-eric-Code-macro/memory:\n\n/Users/eric/.agent_runtime_sessions/claude_config/projects/-Users-eric-Code-macro-crates:\nfe461773-871c-41e8-8b10-8b5abce9dc55.jsonl\n\n/Users/eric/.agent_runtime_sessions/claude_config/sessions:"),
- ),
},
Text {
text: "Recordings are actually at `~/.agent_runtime_sessions/` (not `.agent_session_recordings`). Now let me find the comms message models.",
@@ -199,29 +157,38 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01PXukMqRZDXuKbPTVafaGGx",
),
- label: "Agent",
+ name: Native {
+ name: "Agent",
+ },
status: Completed,
- detail: Think {
- output: Some(
- "Here is the complete map.\n\n## 1. Channel message structs (Rust)\n\n**Domain (canonical) — `crates/channels/src/domain/models.rs`**\n\n- `ChannelMessage` (top-level timeline message) — **line 140**\n```rust\n/// A top-level message with thread info, reactions, and attachments.\n#[derive(Debug, Clone)]\npub struct ChannelMessage {\n pub id: Uuid,\n pub channel_id: Uuid,\n pub sender_id: String,\n /// For an agent (bot) message, the id of the user who triggered it.\n pub triggered_by: Option<String>,\n /// Bot profile when the sender is a bot.\n pub bot_profile: Option<BotSenderProfile>,\n pub content: String,\n pub created_at: DateTime<Utc>,\n pub updated_at: DateTime<Utc>,\n pub edited_at: Option<DateTime<Utc>>,\n pub deleted_at: Option<DateTime<Utc>>,\n pub thread: ThreadInfo,\n pub reactions: Vec<CountedReaction>,\n pub attachments: Vec<MessageAttachment>,\n}\n```\n- `ThreadInfo` (line 200), `ThreadReply` (line 212 — same shape, no `thread`/`deleted_at`), `CountedReaction` (line 240), `MessageAttachment` (line 249)\n- `ChannelContextMessage` (line 366) — flat shape used by the message-context endpoint (has `thread_id`)\n- `RecentChannelMessage` (line 175) — lightweight shape used for AI attachments / search indexing, adds `mentions: Vec<String>` formatted `{ENTITY_TYPE}:{ENTITY_ID}`\n- `MutatedMessage` (line 1028) — what mutations return / what gets broadcast over realtime; `sender_id: ChannelSender<'static>`\n- Raw DB row types: `TopLevelMessageRow` (line 431), `ThreadReplyRow` (line 465), `ThreadData` (line 452)\n- Requests: `PostMessageRequest` (line 913 — `content: String`, `mentions: Vec<SimpleMention>`, `thread_id`, `attachments`, `nonce`, internal-only `triggered_by`), `PatchMessageRequest` (line 946), `PostMessageResponse` (line 939)\n- `SimpleMention` (line 797) = `{ entity_type: String, entity_id: String }`\n\n**DB row / SQL** — `crates/channels/src/outbound/pg_channels_repo.rs` (row structs at lines 72–290: `TopLevelRow`, `ThreadDataRow`, `ContextMessageRow` at 165, `MutatedMessageRow` at 209).\nTable DDL: `crates/macro_db_client/migrations/20251104101012_comms_db_schema.sql:93`\n```sql\nCREATE TABLE public.comms_messages\n(\n id uuid NOT NULL, channel_id uuid NOT NULL, thread_id uuid,\n sender_id text NOT NULL, content text NOT NULL,\n created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,\n edited_at timestamp, deleted_at timestamp\n);\n```\nplus `crates/macro_db_client/migrations/20260629171949_add_comms_messages_triggered_by.sql:11` → `ADD COLUMN IF NOT EXISTS triggered_by_user_id text;`\nContent is a single `text` column. There is **no** content-type/kind column, no jsonb.\n\n**API/response types — `crates/channels/src/inbound/axum_router.rs`** (mounted by `services/document_storage_service/src/main.rs:1072`)\n- `ApiChannelMessage` — **line 1911**, `ApiChannelMessagesPage` — 1817, `ApiThreadInfo` — 2107, `ApiThreadReply` — 2137, `ApiChannelContextMessage` — 1978, `ApiMessageSender` — 1829, `ApiMessageSenderType` — 1849\n```rust\npub struct ApiChannelMessage {\n id: Uuid, channel_id: Uuid,\n sender_id: String,\n sender: ApiMessageSender,\n content: String,\n created_at/updated_at/edited_at/deleted_at,\n thread: ApiThreadInfo,\n reactions: Vec<ApiCountedReaction>,\n attachments: Vec<ApiMessageAttachment>,\n}\n```\n\n**Other parallel copies of the same shape:**\n- Soup/inbox: `crates/models_soup/src/comms.rs:78` `ChannelMessage`, `:120` `SoupChannelThread`, `:155` `SoupMessageSender`, `:167` `SoupMessageSenderType`\n- MCP toolset: `crates/channels/src/inbound/toolset/types.rs` (`ToolMessageKind` at 33, message types ~263)\n- Search indexing: `crates/comms_db_client/src/messages/get_channel_message.rs:6` `ChannelMessageInfo`; `crates/models_search/src/channel.rs:129`; `crates/opensearch_client/src/search/channels.rs:23`\n- Realtime websocket payload: `crates/channels/src/outbound/connection_gateway_realtime.rs:159` `MessageRealtimeData` (flattens `MutatedMessage` + `MessageRealtimeSender` at 166)\n\n## 2. How content is represented\n\n**Plain `String`.** Markdown text, rendered client-side. No content blocks, no enum of part types, no structured/rich parts anywhere in the channel path — every layer (`ChannelMessage`, `ThreadReply`, `ApiChannelMessage`, `MutatedMessage`, `TopLevelMessageRow`, soup, search, DB column) carries `content: String`.\n\nThe only structure adjacent to content:\n- Inline mention markup embedded *inside* the markdown string, extracted by the lexical service into `SimpleMention` rows (`crates/lexical_mention_extractor/src/lib.rs:27`, table `comms_entity_mentions`).\n- `MessageAttachment` / `comms_attachments` as a sibling list (entity_type/entity_id + width/height), not part of content.\n\nFrontend rendering: `apps/web/src/features/channel/Message/Content.tsx:14` — takes `message().content` and passes it whole to `StaticMarkdown` with `channelTheme`. `isEmojiOnly` bumps to big-emoji styling. That's the entire content rendering model.\n\n## 3. Non-human / bot / AI author — yes, this exists\n\n- `crates/channel_sender/src/lib.rs:18` — `ChannelSender<'a>(Either<BotIdStr, MacroUserIdStr>)`; `sender_id` in the DB is a namespaced principal string, parsed via `parse_from_str` (tries `BotIdStr` first, i.e. `bot|<uuid>`, else macro user id).\n- `crates/channels/src/domain/models.rs:25` — `BotSenderProfile { name: String, avatar_url: Option<String> }`\n- API discriminator: `crates/channels/src/inbound/axum_router.rs:1829-1853`\n```rust\npub struct ApiMessageSender {\n #[serde(rename = \"type\")] sender_type: ApiMessageSenderType,\n id: String, // bot uuid or user id, namespace stripped\n name: Option<String>, // bot display name\n avatar_url: Option<String>, // bot avatar\n triggered_by: Option<String>, // user who triggered the agent message\n}\npub enum ApiMessageSenderType { User, Bot } // snake_case on the wire\n```\nbuilt by `ApiMessageSender::from_message_sender` (line 1893) — bot profile + `triggered_by` only attached when the sender is a bot.\n- `triggered_by` is set internally, never from the wire (`PostMessageRequest.triggered_by`, `#[serde(skip)]`).\n- Bot model: `crates/bots/src/domain/models.rs:104` `Bot { id: BotId, kind: BotKind, owner: Option<BotOwner>, name, handle, description, avatar_url, ... }`; `BotKind { Owned, System }` at line 14; `BotOwner { User{user_id}, Team{team_id} }` at line 87. Related crates: `crates/bot_id`, `crates/channel_bots`.\n- Frontend: `apps/web/src/lib/queries/channel/message-sender.ts` (`isBotSenderId`, `senderFromStorageId`, `normalizeChannelMessageSender`), `apps/web/src/features/channel/Message/AgentBadge.tsx` (renders an \"Agent\" pill when `isBotSenderId(sender_id)`), `apps/web/src/features/channel/macroAi.ts` + `@core/constant/macroAgent` (the first-party Macro agent bot identity, `MACRO_AGENT_PRINCIPAL_ID` = `bot|<uuid>`).\n\n## 4. Message \"kind\"/\"type\" discriminator — none for content\n\nThe only `kind` that exists is **position**, not content type: `ChannelMessageKind { TopLevelMessage, ThreadReply }` at `crates/channels/src/domain/models.rs:104`, surfaced as `ApiChannelMessageKind` (`axum_router.rs:2198`) and `ToolMessageKind` (`toolset/types.rs:33`).\n\nThere is **no** system-message / join-leave / call-event variant on `comms_messages`. Non-plain-text UI is modeled *outside* the message stream:\n- Active call banner: `apps/web/src/features/channel/Channel/ActiveCallMessage.tsx` — a separate component driven by `useActiveCallQuery`, not a message row.\n- Channel-created marker: `apps/web/src/features/channel/Message/ChannelCreatedIndicator.tsx` — list decoration.\n- Date/new dividers: `DateDivider.tsx`, `NewDivider.tsx` — list decorations keyed off `ChannelMessageListMeta` (`Message/list-meta.ts`).\n- Deleted state: branch on `message.deleted_at != null` (`ChannelMessage.tsx:227` → `DeletedMessageLayout`).\n- Call transcripts fake a message: `apps/web/src/features/block-call/component/CallTranscript.tsx:79` `segmentToApiChannelMessage(...)` synthesizes an `ApiChannelMessage` from a transcript segment. Same trick for doc comments: `apps/web/src/lib/core/comments/discussion/Discussion.tsx:182` `discussionCommentToApiChannelMessage`.\n\nSo today the only way to render anything non-plain-text is to either synthesize a fake `ApiChannelMessage` or add a sibling component to the list.\n\n## 5. TypeScript types + renderer\n\n**Not specta.** utoipa → OpenAPI JSON → **orval** codegen.\n- Config: `apps/web/src/lib/service-clients/orval.config.ts` (channels live in the `document_storage_service` spec → `service-storage`).\n- Generated: `apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelMessage.ts`, `apiMessageSender.ts`, `apiMessageSenderType.ts` (`{ user: 'user', bot: 'bot' }`), `apiThreadInfo.ts`, `apiThreadReply.ts`, `apiCountedReaction.ts`, `apiMessageAttachment.ts`, `apiChannelMessagesPage.ts`, `apiChannelMessageKind.ts`, plus `soupMessageSender*.ts`. Imported as `@service-storage/generated/schemas/...` or `@service-storage/client` (tsconfig path at `apps/web/tsconfig.json:92`).\n\n**Renderer:**\n- `apps/web/src/features/channel/Message/ChannelMessage.tsx:198` — `ChannelMessage()`, the row component (Switch over deleted / grouped / regular layouts).\n- Compound namespace: `apps/web/src/features/channel/Message/Message.ts` — `Message.{Root, Layout, Slot, SenderName, AgentBadge, FromPill, SenderIcon, Timestamp, Content, Attachments, Reactions, EditedIndicator, HoverActions, ActionMenu, MediaPreview, ...}`\n- Frontend view model (deliberately looser than the API type): `apps/web/src/features/channel/Message/types.ts` — `MessageData { id, content, sender_id, sender?: ApiMessageSender, created_at, updated_at, deleted_at?, edited_at?, thread_id?, attachments, reactions }`. This is what the whole Message tree consumes via `useMessage()` (`Message/context.ts`).\n- Consumers: `apps/web/src/features/channel/Thread/ChannelThread.tsx:308`, `Thread/ThreadReplyList.tsx:85`, `Channel/ThreadList.tsx` (virtua virtualizer), `apps/web/src/features/entity/composed/list-entity/channel.tsx:171`.\n- Queries/cache: `apps/web/src/lib/queries/channel/channel-messages.ts`, `reconcile.ts`, `message-sender.ts`.\n\n## 6. AI chat message model (for comparison)\n\n**Content parts enum — `crates/agent/src/types.rs`**\n- `Role` — line 32: `{ User, Assistant, System }` (lowercase)\n- `AssistantMessagePart` — **line 52**, `#[serde(tag = \"type\", rename_all = \"camelCase\")]`:\n```rust\npub enum AssistantMessagePart {\n Text { text: String },\n ToolCall { name: String, json: serde_json::Value, id: String },\n McpToolCall { name: String, service: String, display_name: Option<String>, json: serde_json::Value, id: String },\n ToolCallResponseJson { name: String, json: serde_json::Value, id: String },\n ToolCallErr { name: String, description: String, id: String },\n Thinking { thinking: String },\n}\n```\n- `ChatMessageContent` — **line 136**:\n```rust\n#[serde(untagged)]\npub enum ChatMessageContent {\n Text(String),\n AssistantMessageParts(Vec<AssistantMessagePart>),\n}\n```\nwith helpers `user_message_text`, `assistant_message_text`, `assistant_message_text_with_tools`, `message_text`, `message_text_with_tools` (lines 148–232). `ChatMessage { content, role, attachments }` at line 240; `ChatMessages(Vec<ChatMessage>)` at 255.\n\n**Persisted / API types — `crates/model/src/chat/message.rs`**\n- `ChatMessage` (line 10): `{ id: String, content: ChatMessageContent, role: Role, model: Option<String> }`, `#[serde(rename_all = \"camelCase\")]`, `sqlx::FromRow`\n- `ChatMessageWithAttachments` (line 23): same + `attachments: Vec<Entity<'static>>`\n- `NewChatMessage` (line 35)\n- DB: `public.\"ChatMessage\"` with **`content jsonb NOT NULL`** and `role text` — see `services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sql:343`\n- Chat crate: `crates/chat/src/domain/models/chat.rs:83` `ChatResponse { messages: Vec<ChatMessageWithAttachments>, ... }`; `crates/chat/src/domain/models/message.rs:8` `PatchChatMessageArgs { message_id, content: ChatMessageContent }`, `WebCitation` (line 17), `ResolvedMessageContent` (line 34); `crates/chat/src/domain/events.rs:104` `ChatMessageRole`.\n\n**Frontend AI renderer** (the analogue of `Message/Content.tsx`): `apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx` — switches on `part.type` (`toolCall` / `mcpToolCall` / `toolCallErr` / `thinking` / `text`) into `RenderTool`, `McpToolCall`, `ThinkingBlock`, `ChatMessageMarkdown`, grouping tool activity into `AssistantActivityGroup`. Types come from `@service-cognition/generated/schemas/assistantMessagePart` (orval, cognition service spec).\n\n**Key contrast:** AI chat already has a tagged, extensible part enum persisted as jsonb with a per-part-type frontend renderer registry; channel messages are a flat `text` column with a single markdown renderer, and the only author/kind discriminators are `ApiMessageSenderType { user, bot }` (author) and `ChannelMessageKind { TopLevelMessage, ThreadReply }` (position). There is no content-kind discriminator on channel messages at all.",
+ detail: Subagent {
+ title: "Find comms message models",
+ agent_type: Some(
+ "Explore",
),
- },
- raw_input: Some(
- Object {
- "subagent_type": String("Explore"),
- "description": String("Find comms message models"),
- "run_in_background": Bool(false),
- "prompt": String("In /Users/eric/Code/macro, find the canonical Rust models for **channel messages** (comms messages) — the type that gets rendered in a channel in the frontend, plus its content/body representation.\n\nBe very thorough. I need to know:\n1. Where the channel message struct(s) live (crate + file paths + line numbers) — both the DB row type and the API/response type if they differ.\n2. How message *content* is represented — plain text? rich content blocks? an enum of block types? Is there any existing notion of structured/rich content parts?\n3. Whether there's any existing notion of a non-human / bot / AI author on a channel message (author type enum, bot user, sender kind, etc.).\n4. Any existing message \"kind\"/\"type\" discriminator on channel messages (e.g. system messages, join/leave, call events) — how are non-plain-text messages modeled today?\n5. Where the TypeScript types for these come from (specta export? generated swagger types?) and the frontend component that renders a channel message.\n6. Also check for the `chat` crate's AI message model (assistant messages, tool calls, content blocks) since AI chat messages already exist somewhere in this repo — I want to compare how AI content is modeled there vs channel messages.\n\nReport concrete file:line references and paste the key struct/enum definitions verbatim. Do not modify any files."),
- },
- ),
- raw_output: Some(
- Array [
- Object {
- "type": String("text"),
- "text": String("Here is the complete map.\n\n## 1. Channel message structs (Rust)\n\n**Domain (canonical) — `crates/channels/src/domain/models.rs`**\n\n- `ChannelMessage` (top-level timeline message) — **line 140**\n```rust\n/// A top-level message with thread info, reactions, and attachments.\n#[derive(Debug, Clone)]\npub struct ChannelMessage {\n pub id: Uuid,\n pub channel_id: Uuid,\n pub sender_id: String,\n /// For an agent (bot) message, the id of the user who triggered it.\n pub triggered_by: Option<String>,\n /// Bot profile when the sender is a bot.\n pub bot_profile: Option<BotSenderProfile>,\n pub content: String,\n pub created_at: DateTime<Utc>,\n pub updated_at: DateTime<Utc>,\n pub edited_at: Option<DateTime<Utc>>,\n pub deleted_at: Option<DateTime<Utc>>,\n pub thread: ThreadInfo,\n pub reactions: Vec<CountedReaction>,\n pub attachments: Vec<MessageAttachment>,\n}\n```\n- `ThreadInfo` (line 200), `ThreadReply` (line 212 — same shape, no `thread`/`deleted_at`), `CountedReaction` (line 240), `MessageAttachment` (line 249)\n- `ChannelContextMessage` (line 366) — flat shape used by the message-context endpoint (has `thread_id`)\n- `RecentChannelMessage` (line 175) — lightweight shape used for AI attachments / search indexing, adds `mentions: Vec<String>` formatted `{ENTITY_TYPE}:{ENTITY_ID}`\n- `MutatedMessage` (line 1028) — what mutations return / what gets broadcast over realtime; `sender_id: ChannelSender<'static>`\n- Raw DB row types: `TopLevelMessageRow` (line 431), `ThreadReplyRow` (line 465), `ThreadData` (line 452)\n- Requests: `PostMessageRequest` (line 913 — `content: String`, `mentions: Vec<SimpleMention>`, `thread_id`, `attachments`, `nonce`, internal-only `triggered_by`), `PatchMessageRequest` (line 946), `PostMessageResponse` (line 939)\n- `SimpleMention` (line 797) = `{ entity_type: String, entity_id: String }`\n\n**DB row / SQL** — `crates/channels/src/outbound/pg_channels_repo.rs` (row structs at lines 72–290: `TopLevelRow`, `ThreadDataRow`, `ContextMessageRow` at 165, `MutatedMessageRow` at 209).\nTable DDL: `crates/macro_db_client/migrations/20251104101012_comms_db_schema.sql:93`\n```sql\nCREATE TABLE public.comms_messages\n(\n id uuid NOT NULL, channel_id uuid NOT NULL, thread_id uuid,\n sender_id text NOT NULL, content text NOT NULL,\n created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,\n edited_at timestamp, deleted_at timestamp\n);\n```\nplus `crates/macro_db_client/migrations/20260629171949_add_comms_messages_triggered_by.sql:11` → `ADD COLUMN IF NOT EXISTS triggered_by_user_id text;`\nContent is a single `text` column. There is **no** content-type/kind column, no jsonb.\n\n**API/response types — `crates/channels/src/inbound/axum_router.rs`** (mounted by `services/document_storage_service/src/main.rs:1072`)\n- `ApiChannelMessage` — **line 1911**, `ApiChannelMessagesPage` — 1817, `ApiThreadInfo` — 2107, `ApiThreadReply` — 2137, `ApiChannelContextMessage` — 1978, `ApiMessageSender` — 1829, `ApiMessageSenderType` — 1849\n```rust\npub struct ApiChannelMessage {\n id: Uuid, channel_id: Uuid,\n sender_id: String,\n sender: ApiMessageSender,\n content: String,\n created_at/updated_at/edited_at/deleted_at,\n thread: ApiThreadInfo,\n reactions: Vec<ApiCountedReaction>,\n attachments: Vec<ApiMessageAttachment>,\n}\n```\n\n**Other parallel copies of the same shape:**\n- Soup/inbox: `crates/models_soup/src/comms.rs:78` `ChannelMessage`, `:120` `SoupChannelThread`, `:155` `SoupMessageSender`, `:167` `SoupMessageSenderType`\n- MCP toolset: `crates/channels/src/inbound/toolset/types.rs` (`ToolMessageKind` at 33, message types ~263)\n- Search indexing: `crates/comms_db_client/src/messages/get_channel_message.rs:6` `ChannelMessageInfo`; `crates/models_search/src/channel.rs:129`; `crates/opensearch_client/src/search/channels.rs:23`\n- Realtime websocket payload: `crates/channels/src/outbound/connection_gateway_realtime.rs:159` `MessageRealtimeData` (flattens `MutatedMessage` + `MessageRealtimeSender` at 166)\n\n## 2. How content is represented\n\n**Plain `String`.** Markdown text, rendered client-side. No content blocks, no enum of part types, no structured/rich parts anywhere in the channel path — every layer (`ChannelMessage`, `ThreadReply`, `ApiChannelMessage`, `MutatedMessage`, `TopLevelMessageRow`, soup, search, DB column) carries `content: String`.\n\nThe only structure adjacent to content:\n- Inline mention markup embedded *inside* the markdown string, extracted by the lexical service into `SimpleMention` rows (`crates/lexical_mention_extractor/src/lib.rs:27`, table `comms_entity_mentions`).\n- `MessageAttachment` / `comms_attachments` as a sibling list (entity_type/entity_id + width/height), not part of content.\n\nFrontend rendering: `apps/web/src/features/channel/Message/Content.tsx:14` — takes `message().content` and passes it whole to `StaticMarkdown` with `channelTheme`. `isEmojiOnly` bumps to big-emoji styling. That's the entire content rendering model.\n\n## 3. Non-human / bot / AI author — yes, this exists\n\n- `crates/channel_sender/src/lib.rs:18` — `ChannelSender<'a>(Either<BotIdStr, MacroUserIdStr>)`; `sender_id` in the DB is a namespaced principal string, parsed via `parse_from_str` (tries `BotIdStr` first, i.e. `bot|<uuid>`, else macro user id).\n- `crates/channels/src/domain/models.rs:25` — `BotSenderProfile { name: String, avatar_url: Option<String> }`\n- API discriminator: `crates/channels/src/inbound/axum_router.rs:1829-1853`\n```rust\npub struct ApiMessageSender {\n #[serde(rename = \"type\")] sender_type: ApiMessageSenderType,\n id: String, // bot uuid or user id, namespace stripped\n name: Option<String>, // bot display name\n avatar_url: Option<String>, // bot avatar\n triggered_by: Option<String>, // user who triggered the agent message\n}\npub enum ApiMessageSenderType { User, Bot } // snake_case on the wire\n```\nbuilt by `ApiMessageSender::from_message_sender` (line 1893) — bot profile + `triggered_by` only attached when the sender is a bot.\n- `triggered_by` is set internally, never from the wire (`PostMessageRequest.triggered_by`, `#[serde(skip)]`).\n- Bot model: `crates/bots/src/domain/models.rs:104` `Bot { id: BotId, kind: BotKind, owner: Option<BotOwner>, name, handle, description, avatar_url, ... }`; `BotKind { Owned, System }` at line 14; `BotOwner { User{user_id}, Team{team_id} }` at line 87. Related crates: `crates/bot_id`, `crates/channel_bots`.\n- Frontend: `apps/web/src/lib/queries/channel/message-sender.ts` (`isBotSenderId`, `senderFromStorageId`, `normalizeChannelMessageSender`), `apps/web/src/features/channel/Message/AgentBadge.tsx` (renders an \"Agent\" pill when `isBotSenderId(sender_id)`), `apps/web/src/features/channel/macroAi.ts` + `@core/constant/macroAgent` (the first-party Macro agent bot identity, `MACRO_AGENT_PRINCIPAL_ID` = `bot|<uuid>`).\n\n## 4. Message \"kind\"/\"type\" discriminator — none for content\n\nThe only `kind` that exists is **position**, not content type: `ChannelMessageKind { TopLevelMessage, ThreadReply }` at `crates/channels/src/domain/models.rs:104`, surfaced as `ApiChannelMessageKind` (`axum_router.rs:2198`) and `ToolMessageKind` (`toolset/types.rs:33`).\n\nThere is **no** system-message / join-leave / call-event variant on `comms_messages`. Non-plain-text UI is modeled *outside* the message stream:\n- Active call banner: `apps/web/src/features/channel/Channel/ActiveCallMessage.tsx` — a separate component driven by `useActiveCallQuery`, not a message row.\n- Channel-created marker: `apps/web/src/features/channel/Message/ChannelCreatedIndicator.tsx` — list decoration.\n- Date/new dividers: `DateDivider.tsx`, `NewDivider.tsx` — list decorations keyed off `ChannelMessageListMeta` (`Message/list-meta.ts`).\n- Deleted state: branch on `message.deleted_at != null` (`ChannelMessage.tsx:227` → `DeletedMessageLayout`).\n- Call transcripts fake a message: `apps/web/src/features/block-call/component/CallTranscript.tsx:79` `segmentToApiChannelMessage(...)` synthesizes an `ApiChannelMessage` from a transcript segment. Same trick for doc comments: `apps/web/src/lib/core/comments/discussion/Discussion.tsx:182` `discussionCommentToApiChannelMessage`.\n\nSo today the only way to render anything non-plain-text is to either synthesize a fake `ApiChannelMessage` or add a sibling component to the list.\n\n## 5. TypeScript types + renderer\n\n**Not specta.** utoipa → OpenAPI JSON → **orval** codegen.\n- Config: `apps/web/src/lib/service-clients/orval.config.ts` (channels live in the `document_storage_service` spec → `service-storage`).\n- Generated: `apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelMessage.ts`, `apiMessageSender.ts`, `apiMessageSenderType.ts` (`{ user: 'user', bot: 'bot' }`), `apiThreadInfo.ts`, `apiThreadReply.ts`, `apiCountedReaction.ts`, `apiMessageAttachment.ts`, `apiChannelMessagesPage.ts`, `apiChannelMessageKind.ts`, plus `soupMessageSender*.ts`. Imported as `@service-storage/generated/schemas/...` or `@service-storage/client` (tsconfig path at `apps/web/tsconfig.json:92`).\n\n**Renderer:**\n- `apps/web/src/features/channel/Message/ChannelMessage.tsx:198` — `ChannelMessage()`, the row component (Switch over deleted / grouped / regular layouts).\n- Compound namespace: `apps/web/src/features/channel/Message/Message.ts` — `Message.{Root, Layout, Slot, SenderName, AgentBadge, FromPill, SenderIcon, Timestamp, Content, Attachments, Reactions, EditedIndicator, HoverActions, ActionMenu, MediaPreview, ...}`\n- Frontend view model (deliberately looser than the API type): `apps/web/src/features/channel/Message/types.ts` — `MessageData { id, content, sender_id, sender?: ApiMessageSender, created_at, updated_at, deleted_at?, edited_at?, thread_id?, attachments, reactions }`. This is what the whole Message tree consumes via `useMessage()` (`Message/context.ts`).\n- Consumers: `apps/web/src/features/channel/Thread/ChannelThread.tsx:308`, `Thread/ThreadReplyList.tsx:85`, `Channel/ThreadList.tsx` (virtua virtualizer), `apps/web/src/features/entity/composed/list-entity/channel.tsx:171`.\n- Queries/cache: `apps/web/src/lib/queries/channel/channel-messages.ts`, `reconcile.ts`, `message-sender.ts`.\n\n## 6. AI chat message model (for comparison)\n\n**Content parts enum — `crates/agent/src/types.rs`**\n- `Role` — line 32: `{ User, Assistant, System }` (lowercase)\n- `AssistantMessagePart` — **line 52**, `#[serde(tag = \"type\", rename_all = \"camelCase\")]`:\n```rust\npub enum AssistantMessagePart {\n Text { text: String },\n ToolCall { name: String, json: serde_json::Value, id: String },\n McpToolCall { name: String, service: String, display_name: Option<String>, json: serde_json::Value, id: String },\n ToolCallResponseJson { name: String, json: serde_json::Value, id: String },\n ToolCallErr { name: String, description: String, id: String },\n Thinking { thinking: String },\n}\n```\n- `ChatMessageContent` — **line 136**:\n```rust\n#[serde(untagged)]\npub enum ChatMessageContent {\n Text(String),\n AssistantMessageParts(Vec<AssistantMessagePart>),\n}\n```\nwith helpers `user_message_text`, `assistant_message_text`, `assistant_message_text_with_tools`, `message_text`, `message_text_with_tools` (lines 148–232). `ChatMessage { content, role, attachments }` at line 240; `ChatMessages(Vec<ChatMessage>)` at 255.\n\n**Persisted / API types — `crates/model/src/chat/message.rs`**\n- `ChatMessage` (line 10): `{ id: String, content: ChatMessageContent, role: Role, model: Option<String> }`, `#[serde(rename_all = \"camelCase\")]`, `sqlx::FromRow`\n- `ChatMessageWithAttachments` (line 23): same + `attachments: Vec<Entity<'static>>`\n- `NewChatMessage` (line 35)\n- DB: `public.\"ChatMessage\"` with **`content jsonb NOT NULL`** and `role text` — see `services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sql:343`\n- Chat crate: `crates/chat/src/domain/models/chat.rs:83` `ChatResponse { messages: Vec<ChatMessageWithAttachments>, ... }`; `crates/chat/src/domain/models/message.rs:8` `PatchChatMessageArgs { message_id, content: ChatMessageContent }`, `WebCitation` (line 17), `ResolvedMessageContent` (line 34); `crates/chat/src/domain/events.rs:104` `ChatMessageRole`.\n\n**Frontend AI renderer** (the analogue of `Message/Content.tsx`): `apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx` — switches on `part.type` (`toolCall` / `mcpToolCall` / `toolCallErr` / `thinking` / `text`) into `RenderTool`, `McpToolCall`, `ThinkingBlock`, `ChatMessageMarkdown`, grouping tool activity into `AssistantActivityGroup`. Types come from `@service-cognition/generated/schemas/assistantMessagePart` (orval, cognition service spec).\n\n**Key contrast:** AI chat already has a tagged, extensible part enum persisted as jsonb with a per-part-type frontend renderer registry; channel messages are a flat `text` column with a single markdown renderer, and the only author/kind discriminators are `ApiMessageSenderType { user, bot }` (author) and `ChannelMessageKind { TopLevelMessage, ThreadReply }` (position). There is no content-kind discriminator on channel messages at all."),
+ description: Some(
+ "Find comms message models",
+ ),
+ prompt: Some(
+ "In /Users/eric/Code/macro, find the canonical Rust models for **channel messages** (comms messages) — the type that gets rendered in a channel in the frontend, plus its content/body representation.\n\nBe very thorough. I need to know:\n1. Where the channel message struct(s) live (crate + file paths + line numbers) — both the DB row type and the API/response type if they differ.\n2. How message *content* is represented — plain text? rich content blocks? an enum of block types? Is there any existing notion of structured/rich content parts?\n3. Whether there's any existing notion of a non-human / bot / AI author on a channel message (author type enum, bot user, sender kind, etc.).\n4. Any existing message \"kind\"/\"type\" discriminator on channel messages (e.g. system messages, join/leave, call events) — how are non-plain-text messages modeled today?\n5. Where the TypeScript types for these come from (specta export? generated swagger types?) and the frontend component that renders a channel message.\n6. Also check for the `chat` crate's AI message model (assistant messages, tool calls, content blocks) since AI chat messages already exist somewhere in this repo — I want to compare how AI content is modeled there vs channel messages.\n\nReport concrete file:line references and paste the key struct/enum definitions verbatim. Do not modify any files.",
+ ),
+ background: false,
+ children: [],
+ result: Some(
+ SubagentResult {
+ text: Some(
+ "Here is the complete map.\n\n## 1. Channel message structs (Rust)\n\n**Domain (canonical) — `crates/channels/src/domain/models.rs`**\n\n- `ChannelMessage` (top-level timeline message) — **line 140**\n```rust\n/// A top-level message with thread info, reactions, and attachments.\n#[derive(Debug, Clone)]\npub struct ChannelMessage {\n pub id: Uuid,\n pub channel_id: Uuid,\n pub sender_id: String,\n /// For an agent (bot) message, the id of the user who triggered it.\n pub triggered_by: Option<String>,\n /// Bot profile when the sender is a bot.\n pub bot_profile: Option<BotSenderProfile>,\n pub content: String,\n pub created_at: DateTime<Utc>,\n pub updated_at: DateTime<Utc>,\n pub edited_at: Option<DateTime<Utc>>,\n pub deleted_at: Option<DateTime<Utc>>,\n pub thread: ThreadInfo,\n pub reactions: Vec<CountedReaction>,\n pub attachments: Vec<MessageAttachment>,\n}\n```\n- `ThreadInfo` (line 200), `ThreadReply` (line 212 — same shape, no `thread`/`deleted_at`), `CountedReaction` (line 240), `MessageAttachment` (line 249)\n- `ChannelContextMessage` (line 366) — flat shape used by the message-context endpoint (has `thread_id`)\n- `RecentChannelMessage` (line 175) — lightweight shape used for AI attachments / search indexing, adds `mentions: Vec<String>` formatted `{ENTITY_TYPE}:{ENTITY_ID}`\n- `MutatedMessage` (line 1028) — what mutations return / what gets broadcast over realtime; `sender_id: ChannelSender<'static>`\n- Raw DB row types: `TopLevelMessageRow` (line 431), `ThreadReplyRow` (line 465), `ThreadData` (line 452)\n- Requests: `PostMessageRequest` (line 913 — `content: String`, `mentions: Vec<SimpleMention>`, `thread_id`, `attachments`, `nonce`, internal-only `triggered_by`), `PatchMessageRequest` (line 946), `PostMessageResponse` (line 939)\n- `SimpleMention` (line 797) = `{ entity_type: String, entity_id: String }`\n\n**DB row / SQL** — `crates/channels/src/outbound/pg_channels_repo.rs` (row structs at lines 72–290: `TopLevelRow`, `ThreadDataRow`, `ContextMessageRow` at 165, `MutatedMessageRow` at 209).\nTable DDL: `crates/macro_db_client/migrations/20251104101012_comms_db_schema.sql:93`\n```sql\nCREATE TABLE public.comms_messages\n(\n id uuid NOT NULL, channel_id uuid NOT NULL, thread_id uuid,\n sender_id text NOT NULL, content text NOT NULL,\n created_at timestamptz NOT NULL, updated_at timestamptz NOT NULL,\n edited_at timestamp, deleted_at timestamp\n);\n```\nplus `crates/macro_db_client/migrations/20260629171949_add_comms_messages_triggered_by.sql:11` → `ADD COLUMN IF NOT EXISTS triggered_by_user_id text;`\nContent is a single `text` column. There is **no** content-type/kind column, no jsonb.\n\n**API/response types — `crates/channels/src/inbound/axum_router.rs`** (mounted by `services/document_storage_service/src/main.rs:1072`)\n- `ApiChannelMessage` — **line 1911**, `ApiChannelMessagesPage` — 1817, `ApiThreadInfo` — 2107, `ApiThreadReply` — 2137, `ApiChannelContextMessage` — 1978, `ApiMessageSender` — 1829, `ApiMessageSenderType` — 1849\n```rust\npub struct ApiChannelMessage {\n id: Uuid, channel_id: Uuid,\n sender_id: String,\n sender: ApiMessageSender,\n content: String,\n created_at/updated_at/edited_at/deleted_at,\n thread: ApiThreadInfo,\n reactions: Vec<ApiCountedReaction>,\n attachments: Vec<ApiMessageAttachment>,\n}\n```\n\n**Other parallel copies of the same shape:**\n- Soup/inbox: `crates/models_soup/src/comms.rs:78` `ChannelMessage`, `:120` `SoupChannelThread`, `:155` `SoupMessageSender`, `:167` `SoupMessageSenderType`\n- MCP toolset: `crates/channels/src/inbound/toolset/types.rs` (`ToolMessageKind` at 33, message types ~263)\n- Search indexing: `crates/comms_db_client/src/messages/get_channel_message.rs:6` `ChannelMessageInfo`; `crates/models_search/src/channel.rs:129`; `crates/opensearch_client/src/search/channels.rs:23`\n- Realtime websocket payload: `crates/channels/src/outbound/connection_gateway_realtime.rs:159` `MessageRealtimeData` (flattens `MutatedMessage` + `MessageRealtimeSender` at 166)\n\n## 2. How content is represented\n\n**Plain `String`.** Markdown text, rendered client-side. No content blocks, no enum of part types, no structured/rich parts anywhere in the channel path — every layer (`ChannelMessage`, `ThreadReply`, `ApiChannelMessage`, `MutatedMessage`, `TopLevelMessageRow`, soup, search, DB column) carries `content: String`.\n\nThe only structure adjacent to content:\n- Inline mention markup embedded *inside* the markdown string, extracted by the lexical service into `SimpleMention` rows (`crates/lexical_mention_extractor/src/lib.rs:27`, table `comms_entity_mentions`).\n- `MessageAttachment` / `comms_attachments` as a sibling list (entity_type/entity_id + width/height), not part of content.\n\nFrontend rendering: `apps/web/src/features/channel/Message/Content.tsx:14` — takes `message().content` and passes it whole to `StaticMarkdown` with `channelTheme`. `isEmojiOnly` bumps to big-emoji styling. That's the entire content rendering model.\n\n## 3. Non-human / bot / AI author — yes, this exists\n\n- `crates/channel_sender/src/lib.rs:18` — `ChannelSender<'a>(Either<BotIdStr, MacroUserIdStr>)`; `sender_id` in the DB is a namespaced principal string, parsed via `parse_from_str` (tries `BotIdStr` first, i.e. `bot|<uuid>`, else macro user id).\n- `crates/channels/src/domain/models.rs:25` — `BotSenderProfile { name: String, avatar_url: Option<String> }`\n- API discriminator: `crates/channels/src/inbound/axum_router.rs:1829-1853`\n```rust\npub struct ApiMessageSender {\n #[serde(rename = \"type\")] sender_type: ApiMessageSenderType,\n id: String, // bot uuid or user id, namespace stripped\n name: Option<String>, // bot display name\n avatar_url: Option<String>, // bot avatar\n triggered_by: Option<String>, // user who triggered the agent message\n}\npub enum ApiMessageSenderType { User, Bot } // snake_case on the wire\n```\nbuilt by `ApiMessageSender::from_message_sender` (line 1893) — bot profile + `triggered_by` only attached when the sender is a bot.\n- `triggered_by` is set internally, never from the wire (`PostMessageRequest.triggered_by`, `#[serde(skip)]`).\n- Bot model: `crates/bots/src/domain/models.rs:104` `Bot { id: BotId, kind: BotKind, owner: Option<BotOwner>, name, handle, description, avatar_url, ... }`; `BotKind { Owned, System }` at line 14; `BotOwner { User{user_id}, Team{team_id} }` at line 87. Related crates: `crates/bot_id`, `crates/channel_bots`.\n- Frontend: `apps/web/src/lib/queries/channel/message-sender.ts` (`isBotSenderId`, `senderFromStorageId`, `normalizeChannelMessageSender`), `apps/web/src/features/channel/Message/AgentBadge.tsx` (renders an \"Agent\" pill when `isBotSenderId(sender_id)`), `apps/web/src/features/channel/macroAi.ts` + `@core/constant/macroAgent` (the first-party Macro agent bot identity, `MACRO_AGENT_PRINCIPAL_ID` = `bot|<uuid>`).\n\n## 4. Message \"kind\"/\"type\" discriminator — none for content\n\nThe only `kind` that exists is **position**, not content type: `ChannelMessageKind { TopLevelMessage, ThreadReply }` at `crates/channels/src/domain/models.rs:104`, surfaced as `ApiChannelMessageKind` (`axum_router.rs:2198`) and `ToolMessageKind` (`toolset/types.rs:33`).\n\nThere is **no** system-message / join-leave / call-event variant on `comms_messages`. Non-plain-text UI is modeled *outside* the message stream:\n- Active call banner: `apps/web/src/features/channel/Channel/ActiveCallMessage.tsx` — a separate component driven by `useActiveCallQuery`, not a message row.\n- Channel-created marker: `apps/web/src/features/channel/Message/ChannelCreatedIndicator.tsx` — list decoration.\n- Date/new dividers: `DateDivider.tsx`, `NewDivider.tsx` — list decorations keyed off `ChannelMessageListMeta` (`Message/list-meta.ts`).\n- Deleted state: branch on `message.deleted_at != null` (`ChannelMessage.tsx:227` → `DeletedMessageLayout`).\n- Call transcripts fake a message: `apps/web/src/features/block-call/component/CallTranscript.tsx:79` `segmentToApiChannelMessage(...)` synthesizes an `ApiChannelMessage` from a transcript segment. Same trick for doc comments: `apps/web/src/lib/core/comments/discussion/Discussion.tsx:182` `discussionCommentToApiChannelMessage`.\n\nSo today the only way to render anything non-plain-text is to either synthesize a fake `ApiChannelMessage` or add a sibling component to the list.\n\n## 5. TypeScript types + renderer\n\n**Not specta.** utoipa → OpenAPI JSON → **orval** codegen.\n- Config: `apps/web/src/lib/service-clients/orval.config.ts` (channels live in the `document_storage_service` spec → `service-storage`).\n- Generated: `apps/web/src/lib/service-clients/service-storage/generated/schemas/apiChannelMessage.ts`, `apiMessageSender.ts`, `apiMessageSenderType.ts` (`{ user: 'user', bot: 'bot' }`), `apiThreadInfo.ts`, `apiThreadReply.ts`, `apiCountedReaction.ts`, `apiMessageAttachment.ts`, `apiChannelMessagesPage.ts`, `apiChannelMessageKind.ts`, plus `soupMessageSender*.ts`. Imported as `@service-storage/generated/schemas/...` or `@service-storage/client` (tsconfig path at `apps/web/tsconfig.json:92`).\n\n**Renderer:**\n- `apps/web/src/features/channel/Message/ChannelMessage.tsx:198` — `ChannelMessage()`, the row component (Switch over deleted / grouped / regular layouts).\n- Compound namespace: `apps/web/src/features/channel/Message/Message.ts` — `Message.{Root, Layout, Slot, SenderName, AgentBadge, FromPill, SenderIcon, Timestamp, Content, Attachments, Reactions, EditedIndicator, HoverActions, ActionMenu, MediaPreview, ...}`\n- Frontend view model (deliberately looser than the API type): `apps/web/src/features/channel/Message/types.ts` — `MessageData { id, content, sender_id, sender?: ApiMessageSender, created_at, updated_at, deleted_at?, edited_at?, thread_id?, attachments, reactions }`. This is what the whole Message tree consumes via `useMessage()` (`Message/context.ts`).\n- Consumers: `apps/web/src/features/channel/Thread/ChannelThread.tsx:308`, `Thread/ThreadReplyList.tsx:85`, `Channel/ThreadList.tsx` (virtua virtualizer), `apps/web/src/features/entity/composed/list-entity/channel.tsx:171`.\n- Queries/cache: `apps/web/src/lib/queries/channel/channel-messages.ts`, `reconcile.ts`, `message-sender.ts`.\n\n## 6. AI chat message model (for comparison)\n\n**Content parts enum — `crates/agent/src/types.rs`**\n- `Role` — line 32: `{ User, Assistant, System }` (lowercase)\n- `AssistantMessagePart` — **line 52**, `#[serde(tag = \"type\", rename_all = \"camelCase\")]`:\n```rust\npub enum AssistantMessagePart {\n Text { text: String },\n ToolCall { name: String, json: serde_json::Value, id: String },\n McpToolCall { name: String, service: String, display_name: Option<String>, json: serde_json::Value, id: String },\n ToolCallResponseJson { name: String, json: serde_json::Value, id: String },\n ToolCallErr { name: String, description: String, id: String },\n Thinking { thinking: String },\n}\n```\n- `ChatMessageContent` — **line 136**:\n```rust\n#[serde(untagged)]\npub enum ChatMessageContent {\n Text(String),\n AssistantMessageParts(Vec<AssistantMessagePart>),\n}\n```\nwith helpers `user_message_text`, `assistant_message_text`, `assistant_message_text_with_tools`, `message_text`, `message_text_with_tools` (lines 148–232). `ChatMessage { content, role, attachments }` at line 240; `ChatMessages(Vec<ChatMessage>)` at 255.\n\n**Persisted / API types — `crates/model/src/chat/message.rs`**\n- `ChatMessage` (line 10): `{ id: String, content: ChatMessageContent, role: Role, model: Option<String> }`, `#[serde(rename_all = \"camelCase\")]`, `sqlx::FromRow`\n- `ChatMessageWithAttachments` (line 23): same + `attachments: Vec<Entity<'static>>`\n- `NewChatMessage` (line 35)\n- DB: `public.\"ChatMessage\"` with **`content jsonb NOT NULL`** and `role text` — see `services/delete_chat_handler/migrations/20240325143515_basic_schema_for_testing.sql:343`\n- Chat crate: `crates/chat/src/domain/models/chat.rs:83` `ChatResponse { messages: Vec<ChatMessageWithAttachments>, ... }`; `crates/chat/src/domain/models/message.rs:8` `PatchChatMessageArgs { message_id, content: ChatMessageContent }`, `WebCitation` (line 17), `ResolvedMessageContent` (line 34); `crates/chat/src/domain/events.rs:104` `ChatMessageRole`.\n\n**Frontend AI renderer** (the analogue of `Message/Content.tsx`): `apps/web/src/lib/core/component/AI/component/message/AssistantMessageParts.tsx` — switches on `part.type` (`toolCall` / `mcpToolCall` / `toolCallErr` / `thinking` / `text`) into `RenderTool`, `McpToolCall`, `ThinkingBlock`, `ChatMessageMarkdown`, grouping tool activity into `AssistantActivityGroup`. Types come from `@service-cognition/generated/schemas/assistantMessagePart` (orval, cognition service spec).\n\n**Key contrast:** AI chat already has a tagged, extensible part enum persisted as jsonb with a per-part-type frontend renderer registry; channel messages are a flat `text` column with a single markdown renderer, and the only author/kind discriminators are `ApiMessageSenderType { user, bot }` (author) and `ChannelMessageKind { TopLevelMessage, ThreadReply }` (position). There is no content-kind discriminator on channel messages at all.",
+ ),
+ error: None,
+ agent_id: None,
+ model: None,
+ duration_ms: None,
+ tokens: None,
+ tool_uses: None,
+ stats: None,
},
- ],
- ),
+ ),
+ },
},
Text {
text: "Let me check what the ACP payloads actually look like, since that's the fold's input.",
@@ -230,7 +197,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01KsJWsNt9AEMNxGvH9kdzFW",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Failed,
detail: Terminal {
command: Some(
@@ -245,21 +214,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
1,
),
},
- raw_input: Some(
- Object {
- "command": String("cd /Users/eric/Code/macro && grep -rn \"agent_client_protocol\" Cargo.toml crates/agent_runtime_protocol/Cargo.toml && echo \"=== SessionUpdate variants ===\" && find ~/.cargo/registry/src -type d -name \"agent-client-protocol-*\" 2>/dev/null | head -3"),
- "description": String("Find ACP crate version"),
- },
- ),
- raw_output: Some(
- String("Exit code 1"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01A6mS8XN4ZXEnxhJyWiEGMH",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -274,21 +236,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd /Users/eric/Code/macro && grep -rn \"agent.client.protocol\" Cargo.toml crates/agent_runtime_protocol/Cargo.toml; echo \"---\"; find ~/.cargo/registry/src -maxdepth 2 -type d -name \"agent-client-protocol*\" 2>/dev/null | head"),
- "description": String("Find ACP dep and source"),
- },
- ),
- raw_output: Some(
- String("crates/agent_runtime_protocol/Cargo.toml:11:agent-client-protocol = { workspace = true }\nCargo.toml:106:agent-client-protocol = \"1.2.0\"\n---\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-derive-1.2.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.5.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-2.0.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-derive-2.0.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.3.0\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-derive-1.3.0"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01NmGaWpJhjrn48N9FJENixC",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -303,21 +258,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0 && grep -n \"pub enum SessionUpdate\" -A 80 src/*.rs | head -120"),
- "description": String("Read SessionUpdate enum"),
- },
- ),
- raw_output: Some(
- String("Shell cwd was reset to /Users/eric/Code/macro"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01VQBg93GPRV7YetjxNSqNpV",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -332,21 +280,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn \"pub enum SessionUpdate\" -A 70 ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/ | head -100"),
- "description": String("Read SessionUpdate enum"),
- },
- ),
- raw_output: Some(
- String("(Bash completed with no output)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LSir1M6JhmFeiHNYs1T6Ly",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -361,21 +302,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/; grep -rln \"SessionUpdate\" ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/"),
- "description": String("Locate SessionUpdate"),
- },
- ),
- raw_output: Some(
- String("acp_agent.rs\ncapabilities.rs\ncomponent.rs\n\u{1b}[0m\u{1b}[01;34mconcepts\u{1b}[0m\n\u{1b}[01;34mjsonrpc\u{1b}[0m\njsonrpc.rs\nlib.rs\n\u{1b}[01;34mmcp_server\u{1b}[0m\n\u{1b}[01;34mrole\u{1b}[0m\nrole.rs\n\u{1b}[01;34mschema\u{1b}[0m\nsession.rs\nstdio.rs\n\u{1b}[01;34mutil\u{1b}[0m\nutil.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc/protocol_compat.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/session.rs"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_014pZDiX2zcymaRYNFibN4tw",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -390,21 +324,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0; ls $D/src; grep -rn \"pub enum SessionUpdate\" -A 60 $D/src/ | head -90"),
- "description": String("Read SessionUpdate from schema crate"),
- },
- ),
- raw_output: Some(
- String("lib.rs\nrpc.rs\nserde_util.rs\n\u{1b}[0m\u{1b}[01;34mv1\u{1b}[0m\n\u{1b}[01;34mv2\u{1b}[0m\nversion.rs\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs:99:pub enum SessionUpdate {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-100- /// A chunk of the user's message being streamed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-101- UserMessageChunk(ContentChunk),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-102- /// A chunk of the agent's response being streamed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-103- AgentMessageChunk(ContentChunk),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-104- /// A chunk of the agent's internal reasoning being streamed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-105- AgentThoughtChunk(ContentChunk),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-106- /// Notification that a new tool call has been initiated.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-107- ToolCall(ToolCall),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-108- /// Update on the status or results of a tool call.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-109- ToolCallUpdate(ToolCallUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-110- /// The agent's execution plan for complex tasks.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-111- /// See protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-112- Plan(Plan),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-113- /// **UNSTABLE**\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-114- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-115- /// This capability is not part of the spec yet, and may be removed or changed at any point.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-116- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-117- /// A content update for a plan identified by ID.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-118- #[cfg(feature = \"unstable_plan_operations\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-119- PlanUpdate(PlanUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-120- /// **UNSTABLE**\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-121- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-122- /// This capability is not part of the spec yet, and may be removed or changed at any point.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-123- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-124- /// Removal notice for a plan identified by ID.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-125- #[cfg(feature = \"unstable_plan_operations\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-126- PlanRemoved(PlanRemoved),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-127- /// Available commands are ready or have changed\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-128- AvailableCommandsUpdate(AvailableCommandsUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-129- /// The current mode of the session has changed\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-130- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-131- /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-132- CurrentModeUpdate(CurrentModeUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-133- /// Session configuration options have been updated.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-134- ConfigOptionUpdate(ConfigOptionUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-135- /// Session metadata has been updated (title, timestamps, custom metadata)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-136- SessionInfoUpdate(SessionInfoUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-137- /// Context window and cost update for the session.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-138- UsageUpdate(UsageUpdate),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-139-}\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-140-\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-141-/// The current mode of the session has changed\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-142-///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-143-/// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-144-#[serde_as]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-145-#[skip_serializing_none]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-146-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-147-#[serde(rename_all = \"camelCase\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-148-#[non_exhaustive]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-149-pub struct CurrentModeUpdate {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-150- /// The ID of the current mode\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-151- pub current_mode_id: SessionModeId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-152- /// The _meta property is reserved by ACP to allow clients and agents to attach additional\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-153- /// metadata to their interactions. Implementations MUST NOT make assumptions about values at\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-154- /// these keys.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-155- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-156- /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-157- #[serde_as(deserialize_as = \"DefaultOnError\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-158- #[schemars(extend(\"x-deserialize-default-on-error\" = true))]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-159- #[serde(default)]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs:100:pub enum SessionUpdate {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-101- /// A chunk of the user's message being streamed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-102- UserMessageChunk(ContentChunk),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-103- /// A user message has been created or updated.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-104- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-105- /// Agents can send this when they accept or replay a user message. When a\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-106- /// client receives another `user_message` update with the same `messageId`,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-107- /// fields in the new update patch the previous fields for that message.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-108- UserMessage(UserMessage),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-109- /// A chunk of the agent's response being streamed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-110- AgentMessageChunk(ContentChunk),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-111- /// An agent message has been created or updated.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-112- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-113- /// Agents can send this in addition to streamed chunks. When a client\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-114- /// receives another `agent_message` update with the same `messageId`,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-115- /// fields in the new update patch the previous fields for that message.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-116- AgentMessage(AgentMessage),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-117- /// A chunk of the agent's internal reasoning being streamed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-118- AgentThoughtChunk(ContentChunk),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-119- /// An agent thought or reasoning message has been created or updated.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-120- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-121- /// Agents can send this in addition to streamed chunks. When a client\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-122- /// receives another `agent_thought` update with the same `messageId`,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-123- /// fields in the new update patch the previous fields for that message.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-124- AgentThought(AgentThought),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-125- /// The agent's session state has changed.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-126- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-127- /// Agents send this to report when work starts, completes, or pauses while\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/client.rs-128- /// waiting for user action. Completion of active work is reported here instead"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01H7txCGcKsCxMmCNw3tpmdK",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -419,21 +346,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("sed -n '135,175p' crates/channels/src/domain/models.rs && echo \"===== api =====\" && sed -n '1905,1945p' crates/channels/src/inbound/axum_router.rs"),
- "description": String("Spot-check channel message models"),
- },
- ),
- raw_output: Some(
- String(" Newer,\n}\n\n/// A top-level message with thread info, reactions, and attachments.\n#[derive(Debug, Clone)]\npub struct ChannelMessage {\n /// Message id.\n pub id: Uuid,\n /// Channel this message belongs to.\n pub channel_id: Uuid,\n /// User who sent the message.\n pub sender_id: String,\n /// For an agent (bot) message, the id of the user who triggered it.\n pub triggered_by: Option<String>,\n /// Bot profile when the sender is a bot.\n pub bot_profile: Option<BotSenderProfile>,\n /// Message body.\n pub content: String,\n /// When the message was created.\n pub created_at: DateTime<Utc>,\n /// When the message was last updated.\n pub updated_at: DateTime<Utc>,\n /// When the message was edited (if ever).\n pub edited_at: Option<DateTime<Utc>>,\n /// When the message was soft-deleted (if ever).\n pub deleted_at: Option<DateTime<Utc>>,\n /// Thread metadata and preview replies.\n pub thread: ThreadInfo,\n /// Aggregated reactions on this message.\n pub reactions: Vec<CountedReaction>,\n /// Attachments on this message.\n pub attachments: Vec<MessageAttachment>,\n}\n\nimpl Identify for ChannelMessage {\n type Id = Uuid;\n\n fn id(&self) -> Self::Id {\n self.id\n }\n}\n===== api =====\n sender.name = Some(profile.name);\n sender.avatar_url = profile.avatar_url;\n }\n sender.triggered_by = triggered_by;\n }\n sender\n }\n}\n\n/// A top-level channel message with thread info.\n#[derive(Debug, Serialize, utoipa::ToSchema)]\npub struct ApiChannelMessage {\n /// Message id.\n id: Uuid,\n /// Channel id.\n channel_id: Uuid,\n /// Sender user id.\n sender_id: String,\n /// Structured sender identity.\n sender: ApiMessageSender,\n /// Message content.\n content: String,\n /// When the message was created.\n created_at: DateTime<Utc>,\n /// When the message was last updated.\n updated_at: DateTime<Utc>,\n /// When the message was edited.\n edited_at: Option<DateTime<Utc>>,\n /// When the message was soft-deleted.\n deleted_at: Option<DateTime<Utc>>,\n /// Thread metadata and preview.\n thread: ApiThreadInfo,\n /// Reactions on this message.\n reactions: Vec<ApiCountedReaction>,\n /// Attachments on this message.\n attachments: Vec<ApiMessageAttachment>,\n}\n\nimpl From<ChannelMessage> for ApiChannelMessage {\n fn from(m: ChannelMessage) -> Self {\n Self {"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01MkAkz5N8nTLSrwXLQCJQA6",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -448,15 +368,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions && for f in *.jsonl; do echo \"== $f ($(wc -l < $f) lines)\"; head -c 400 $f; echo; done"),
- "description": String("Peek at recording shape"),
- },
- ),
- raw_output: Some(
- String("== 1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl (299 lines)\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"event\",\"event\":\"acp_ready\"}}\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"dcb750c2-712b-4aa0-a41a-414b7af61bc9\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":1,\"clientCapabilities\":{\"fs\":{\"readTextFile\":true,\"writeTextFile\":true},\"terminal\":true,\"session\":{\"con\n== ab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl (14 lines)\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"event\",\"event\":\"acp_ready\"}}\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"dcb750c2-712b-4aa0-a41a-414b7af61bc9\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":1,\"clientCapabilities\":{\"fs\":{\"readTextFile\":true,\"writeTextFile\":true},\"terminal\":true,\"session\":{\"con\n== cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl (139 lines)\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"event\",\"event\":\"acp_ready\"}}\n{\"ts\":\"2026-08-03T20:08:59.828Z\",\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"dcb750c2-712b-4aa0-a41a-414b7af61bc9\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":1,\"clientCapabilities\":{\"fs\":{\"readTextFile\":true,\"writeTextFile\":true},\"terminal\":true,\"session\":{\"con\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
Text {
text: "Found them. Here's the picture.\n\n## Channel messages: flat text, no content structure\n\n`crates/channels/src/domain/models.rs:140` — `ChannelMessage` carries **`content: String`**. Same at every layer: `ApiChannelMessage` (`channels/src/inbound/axum_router.rs:1911`), `MutatedMessage`, the realtime websocket payload, soup/inbox (`models_soup/src/comms.rs:78`), search indexing, MCP toolset. The DB column is plain `text` (`macro_db_client/migrations/20251104101012_comms_db_schema.sql:93`) — no jsonb, no content-kind column.\n\nThere is **no content-kind discriminator at all**. The only `kind` is positional (`TopLevelMessage` / `ThreadReply`). Everything non-plain-text today is either a sibling component in the list (active call banner, dividers) or a **synthesized fake message** — `segmentToApiChannelMessage` for call transcripts, `discussionCommentToApiChannelMessage` for doc comments.\n\nRendering is one component: `apps/web/src/features/channel/Message/Content.tsx:14` → `StaticMarkdown`.\n\n## Bot authorship already exists — that part's done\n\n`crates/channel_sender/src/lib.rs:18` — `ChannelSender(Either<BotIdStr, MacroUserIdStr>)`, `sender_id` is a namespaced principal (`bot|<uuid>`). `ApiMessageSender { type: user|bot, id, name, avatar_url, triggered_by }`. Frontend already renders an \"Agent\" pill (`AgentBadge.tsx`). So *who* sent it is solved; only *what* it contains isn't.\n\n## AI content is already modeled — elsewhere\n\n`crates/agent/src/types.rs:52` — `AssistantMessagePart`, tagged enum: `Text | ToolCall | McpToolCall | ToolCallResponseJson | ToolCallErr | Thinking`, persisted as **jsonb** on `ChatMessage.content`, with a per-type frontend renderer registry at `AI/component/message/AssistantMessageParts.tsx`.\n\nSo the repo has two parallel worlds: AI chat has extensible jsonb parts + a renderer registry; channels have a text column + a markdown renderer.\n\n## Your input is a delta stream\n\nACP `SessionUpdate` (v1, `agent-client-protocol-schema`) is: `UserMessageChunk | AgentMessageChunk | AgentThoughtChunk | ToolCall | ToolCallUpdate | Plan | AvailableCommandsUpdate | CurrentModeUpdate | UsageUpdate`. That's genuinely a fold — chunks accumulate, `ToolCallUpdate` patches a prior `ToolCall` by id, `Plan` replaces.\n\nAnd the recordings are ideal fixtures — they're at `~/.agent_runtime_sessions/` (not `.agent_session_recordings/`), 3 sessions, direction-labelled ARP wire frames:\n```json\n{\"ts\":\"...\",\"direction\":\"to_server\",\"content\":{\"type\":\"event\",\"event\":\"acp_ready\"}}\n```\nThat's exactly `ToServerMessage`/`ToRuntimeMessage` JSON, so they replay straight through the fold.\n\n## The two decisions that gate everything\n\nNote ACP is richer than `AssistantMessagePart`: it has tool-call **status** (pending/in_progress/completed/failed), `ToolCallContent` with diffs and terminal output, plans, and permission requests. The DCS enum has none of that — it was shaped by Anthropic streaming, not ACP. My lean is a fresh vocabulary in `agent_fold` shaped after ACP, and an additive nullable `parts` column so every existing `content: String` consumer (search, soup, notifications, toolset) keeps working untouched.",
@@ -465,7 +376,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01GFxjB6ojJiQfBfho1by61y",
),
- label: "AskUserQuestion",
+ name: Native {
+ name: "AskUserQuestion",
+ },
status: Failed,
detail: Other {
kind: "other",
@@ -540,76 +453,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
),
},
- raw_input: Some(
- Object {
- "questions": Array [
- Object {
- "question": String("How should comms messages carry AI content?"),
- "header": String("Storage"),
- "multiSelect": Bool(false),
- "options": Array [
- Object {
- "label": String("Additive nullable parts jsonb (Recommended)"),
- "description": String("Add `parts jsonb NULL` to comms_messages; `content: String` stays as plain-text fallback for search/soup/notifications. ApiChannelMessage gains `parts: Option<Vec<AgentMessagePart>>`. Content.tsx branches: parts → part registry, else markdown. Every existing consumer keeps working unchanged."),
- },
- Object {
- "label": String("content_kind discriminator + payload"),
- "description": String("Add a real content-kind enum column to comms_messages with a jsonb payload. More general (system messages, call events could migrate too), but touches every read path and forces all consumers to handle the new kinds."),
- },
- Object {
- "label": String("Fold to markdown only, no schema change"),
- "description": String("agent_fold emits a markdown string; bot sender already exists so zero DB/frontend work. Loses collapsible tool calls, diffs, plan UI, and live streaming state — everything becomes prose."),
- },
- Object {
- "label": String("Sibling table joined by message id"),
- "description": String("comms_messages untouched; agent parts live in a new table joined in at read time. Keeps the hot table clean but adds a join to every channel message fetch."),
- },
- ],
- },
- Object {
- "question": String("What part vocabulary should agent_fold's output use?"),
- "header": String("Part types"),
- "multiSelect": Bool(false),
- "options": Array [
- Object {
- "label": String("New ACP-shaped vocabulary (Recommended)"),
- "description": String("Define `AgentMessagePart` in agent_fold modeled on what ACP actually emits: text, thought, tool call with status + ToolCallContent (diffs, terminals), plan. Honest to the input; frontend renderer is new but can borrow from AssistantMessageParts.tsx."),
- },
- Object {
- "label": String("Reuse agent::types::AssistantMessagePart"),
- "description": String("Fold ACP down into the existing DCS enum. Free frontend renderer reuse, but it has no tool-call status, no diffs, no plans — you'd lose that fidelity or smuggle it through the json blob."),
- },
- Object {
- "label": String("New vocabulary, superset of both"),
- "description": String("One part enum that serves both the AI chat surface and channels, replacing AssistantMessagePart over time. Best long-term, but couples this work to migrating DCS chat."),
- },
- ],
- },
- Object {
- "question": String("What's the message granularity as a turn streams?"),
- "header": String("Granularity"),
- "multiSelect": Bool(false),
- "options": Array [
- Object {
- "label": String("One message per turn, patched (Recommended)"),
- "description": String("A single channel message row per agent turn; the fold accumulates parts and the row is updated as chunks arrive. Matches how a Claude Code turn reads as one unit; needs a realtime patch path for the growing parts list."),
- },
- Object {
- "label": String("One message per block"),
- "description": String("Each text block / tool call becomes its own channel message. Fits the existing append-only realtime path with no patching, but a single turn floods the channel with many rows."),
- },
- Object {
- "label": String("Buffer, emit once on turn end"),
- "description": String("Fold in memory, write one complete message when the turn finishes. Simplest storage and realtime story, but nothing renders while the agent works — no live progress."),
- },
- ],
- },
- ],
- },
- ),
- raw_output: Some(
- String("The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.\n\nNote: The user's next message may contain a correction or preference. Pay close attention — if they explain what went wrong or how they'd prefer you to work, consider saving that to memory for future sessions."),
- ),
},
Text {
text: "Right — pure derivation. Let me ground the design in what's actually in the log.",
@@ -618,7 +461,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_015NiiSX3ES4fmbWphw92e4w",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -633,21 +478,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("find crates/agent_session -type f -name \"*.rs\" | head -20 && echo \"=== model ===\" && cat -n crates/agent_session/src/domain/model.rs 2>/dev/null | head -80"),
- "description": String("Find agent_session Message model"),
- },
- ),
- raw_output: Some(
- String("crates/agent_session/src/lib.rs\ncrates/agent_session/src/outbound/mod.rs\ncrates/agent_session/src/domain/ports.rs\ncrates/agent_session/src/domain/error.rs\ncrates/agent_session/src/domain/mod.rs\ncrates/agent_session/src/domain/model.rs\ncrates/agent_session/src/outbound/postgres/test.rs\ncrates/agent_session/src/outbound/postgres/mod.rs\n=== model ===\n 1\tuse agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};\n 2\tuse bots::domain::models::BotId;\n 3\tuse chrono::{DateTime, Utc};\n 4\tuse macro_user_id::user_id::MacroUserIdStr;\n 5\tuse macro_uuid::Uuid;\n 6\t\n 7\tpub struct UninitializedSession;\n 8\t\n 9\t#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n 10\tpub struct AgentSessionId(Uuid);\n 11\t\n 12\timpl AgentSessionId {\n 13\t /// Wrap an existing UUID as an agent session id.\n 14\t pub fn new_from_uuid(id: Uuid) -> Self {\n 15\t Self(id)\n 16\t }\n 17\t\n 18\t /// The underlying UUID.\n 19\t pub fn as_uuid(&self) -> Uuid {\n 20\t self.0\n 21\t }\n 22\t}\n 23\t\n 24\t#[derive(Debug, Clone, Default)]\n 25\tpub enum SessionStatus {\n 26\t /// No status updates received\n 27\t #[default]\n 28\t NoMessages,\n 29\t /// EventRecieved from container\n 30\t Event(SystemEvent),\n 31\t /// A session disconnected without sending a clsoed event\n 32\t Disconnected,\n 33\t}\n 34\t\n 35\t/// A running or historical agent coding session.\n 36\t#[derive(Debug, Clone)]\n 37\tpub struct AgentSession<SessionId> {\n 38\t /// id of the agent session\n 39\t pub id: SessionId,\n 40\t /// if this was created by `@` in a thread\n 41\t pub created_from_thread_id: Option<Uuid>,\n 42\t /// the thread id of the comms thread\n 43\t pub thread_id: Uuid,\n 44\t /// the bot id of the bot running the agent\n 45\t pub bot_id: BotId,\n 46\t /// model slug - TODO: probably a better type here\n 47\t pub model: String,\n 48\t /// harness slug - TODO: probably a better type here\n 49\t pub harness: String,\n 50\t /// repo we are working with\n 51\t pub repo_url: String,\n 52\t /// ACP session if we have one\n 53\t pub acp_session_id: Option<String>,\n 54\t pub status: SessionStatus,\n 55\t pub created_at: DateTime<Utc>,\n 56\t pub modified_at: DateTime<Utc>,\n 57\t}\n 58\t\n 59\t#[derive(Debug, Clone)]\n 60\tpub enum Message {\n 61\t ToServer(ToServerMessage),\n 62\t ToRuntime(ToRuntimeMessage),\n 63\t}\n 64\t\n 65\t#[derive(Debug, Clone)]\n 66\tpub struct AgentSessionLog {\n 67\t pub agent_session_id: AgentSessionId,\n 68\t /// if this is ACP sent by a user this will be Some\n 69\t pub user_id: Option<MacroUserIdStr<'static>>,\n 70\t pub content: Message,\n 71\t}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_013NK6fa5hBQpYgvTui7X7ji",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -662,21 +500,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions && cat *.jsonl | jq -r 'select(.content.type==\"acp\") | .direction + \" \" + (.content.method // (\"result/\" + ((.content.result|keys|join(\",\")) // \"err\")))' | sort | uniq -c | sort -rn"),
- "description": String("Survey ACP methods in recordings"),
- },
- ),
- raw_output: Some(
- String(" 406 to_server session/update\n 7 to_runtime session/prompt\n 6 to_server session/request_permission\n 6 to_server result/stopReason,usage\n 6 to_runtime result/outcome\n 3 to_server result/configOptions,modes,sessionId\n 3 to_server result/configOptions\n 3 to_server result/_meta,agentCapabilities,agentInfo,authMethods,protocolVersion\n 3 to_runtime session/set_config_option\n 3 to_runtime initialize\n 2 to_runtime session/new\n 1 to_runtime session/load\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01QuLErooobxKmiBx7PBuUhp",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -691,21 +522,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions && echo \"=== sessionUpdate types ===\" && cat *.jsonl | jq -r 'select(.content.method==\"session/update\") | .content.params.update.sessionUpdate' | sort | uniq -c | sort -rn && echo \"=== tool_call kind/status ===\" && cat *.jsonl | jq -r 'select(.content.params.update.sessionUpdate==\"tool_call\") | \"\\(.content.params.update.kind) \\(.content.params.update.status) title=\\(.content.params.update.title|tostring[0:40])\"' | sort | uniq -c | sort -rn"),
- "description": String("Survey session update types"),
- },
- ),
- raw_output: Some(
- String("=== sessionUpdate types ===\n 175 tool_call_update\n 92 agent_message_chunk\n 81 usage_update\n 46 tool_call\n 5 user_message_chunk\n 3 session_info_update\n 3 available_commands_update\n 1 current_mode_update\n=== tool_call kind/status ===\n 26 execute pending title=Terminal\n 4 read pending title=Read File\n 4 edit pending title=Write\n 2 edit pending title=Edit crates/agent_session/examples/agent\n 1 read pending title=Read /Users/eric/.config/zed/settings.js\n 1 read pending title=Read .zed/settings.json\n 1 execute pending title=ls /Users/eric/Code/macro/crates/agent_s\n 1 execute pending title=ls -la ~/.cargo/bin/agent_session_record\n 1 execute pending title=grep -n -A 12 'agent_servers' ~/.config/\n 1 execute pending title=cat /Users/eric/Code/macro/rust-toolchai\n 1 execute pending title=SQLX_OFFLINE=true cargo install --path c\n 1 execute pending title=SQLX_OFFLINE=true cargo install --locked\n 1 edit pending title=Edit /Users/eric/.config/zed/settings.js\n 1 edit pending title=Edit\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_016onb2tTHYUN1xFGMHxqn4c",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -720,21 +544,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions && ID=$(cat cdf15e0e*.jsonl | jq -r 'select(.content.params.update.sessionUpdate==\"tool_call\" and .content.params.update.kind==\"execute\") | .content.params.update.toolCallId' | head -1) && echo \"toolCallId=$ID\" && cat cdf15e0e*.jsonl | jq -c \"select(.content.params.update.toolCallId==\\\"$ID\\\") | .content.params.update\" | head -8"),
- "description": String("Trace one tool call lifecycle"),
- },
- ),
- raw_output: Some(
- String("toolCallId=toolu_01JmdVCbwRjVNdCaXZAy6rL8\n{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\",\"title\":\"Locate the example file's actual crate\"},\"terminal_info\":{\"terminal_id\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\"}},\"toolCallId\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\",\"sessionUpdate\":\"tool_call\",\"rawInput\":{\"command\":\"ls /Users/eric/Code/macro/crates/agent_session/examples/ 2>/dev/null; ls /Users/eric/Code/macro/crates/agent_runtime_protocol/examples/ 2>/dev/null\",\"description\":\"Locate the example file's actual crate\"},\"status\":\"pending\",\"title\":\"ls /Users/eric/Code/macro/crates/agent_session/examples/ 2>/dev/null; ls /Users/eric/Code/macro/crates/agent_runtime_protocol/examples/ 2>/dev/null\",\"kind\":\"execute\",\"content\":[{\"type\":\"terminal\",\"terminalId\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\"}]}\n{\"_meta\":{\"terminal_output\":{\"terminal_id\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\",\"data\":\"\\u001b[0m\\u001b[01;34magent_session_recorder\\u001b[0m\\n\\u001b[00magent_session_recorder.rs\\u001b[0m\\n\\u001b[0m\\u001b[00macp.rs\\u001b[0m\\n\\u001b[00mevents.rs\\u001b[0m\\n\\u001b[01;34mmock_container\\u001b[0m\\n\\u001b[00mmock_container.rs\\u001b[0m\\n\\u001b[00mwebsocket.rs\\u001b[0m\"}},\"toolCallId\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\",\"sessionUpdate\":\"tool_call_update\"}\n{\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\"},\"terminal_exit\":{\"terminal_id\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\",\"exit_code\":0,\"signal\":null}},\"toolCallId\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\",\"sessionUpdate\":\"tool_call_update\",\"status\":\"completed\",\"rawOutput\":\"\\u001b[0m\\u001b[01;34magent_session_recorder\\u001b[0m\\n\\u001b[00magent_session_recorder.rs\\u001b[0m\\n\\u001b[0m\\u001b[00macp.rs\\u001b[0m\\n\\u001b[00mevents.rs\\u001b[0m\\n\\u001b[01;34mmock_container\\u001b[0m\\n\\u001b[00mmock_container.rs\\u001b[0m\\n\\u001b[00mwebsocket.rs\\u001b[0m\",\"content\":[{\"type\":\"terminal\",\"terminalId\":\"toolu_01JmdVCbwRjVNdCaXZAy6rL8\"}]}\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01YHq57i7vBC5MCSso8v9K3o",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -749,15 +566,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions && echo \"=== an edit tool_call ===\" && cat *.jsonl | jq -c 'select(.content.params.update.sessionUpdate==\"tool_call\" and .content.params.update.kind==\"edit\") | .content.params.update' | head -1 | cut -c1-900 && echo && echo \"=== permission request ===\" && cat *.jsonl | jq -c 'select(.content.method==\"session/request_permission\") | .content.params' | head -1 | cut -c1-700"),
- "description": String("Inspect edit tool call and permission request"),
- },
- ),
- raw_output: Some(
- String("=== an edit tool_call ===\n{\"_meta\":{\"claudeCode\":{\"toolName\":\"Write\"}},\"toolCallId\":\"toolu_01HocEetuSapsmVgT3isZYfw\",\"sessionUpdate\":\"tool_call\",\"rawInput\":{},\"status\":\"pending\",\"title\":\"Write\",\"kind\":\"edit\",\"content\":[],\"locations\":[]}\n\n=== permission request ===\n{\"options\":[{\"kind\":\"reject_once\",\"name\":\"Deny\",\"optionId\":\"reject\"},{\"kind\":\"allow_once\",\"name\":\"Allow Once\",\"optionId\":\"allow\"},{\"kind\":\"allow_always\",\"name\":\"Always Allow\",\"optionId\":\"allow_always\",\"_meta\":{\"permission\":{\"version\":1,\"changes\":[{\"type\":\"policy_rule\",\"operation\":\"add\",\"ruleBehavior\":\"allow\",\"description\":\"Allow all Bash calls\",\"lifetime\":{\"scope\":\"session\"},\"targets\":[{\"type\":\"tool\",\"toolName\":\"Bash\"}]}]}}}],\"sessionId\":\"1c6f5dbc-0fa8-4558-8ebb-3165a1daea56\",\"toolCall\":{\"toolCallId\":\"toolu_01F5V288iQ8iArGM4B3ayCFm\",\"rawInput\":{\"command\":\"ls -la ~/.agent_runtime_sessions/ 2>/dev/null && echo \\\"---\\\" && for f in ~/.agent_runtime_sessions/*.jsonl; do echo \\\"$f: $(wc -l < \\\"$f\\\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
Text {
text: "Now I have what I need. The recordings are the real spec here, and they surfaced four things that change the design:\n\n**1. Tool calls dominate.** 406 of ~450 ACP frames are `session/update`; within those, 175 `tool_call_update` vs 46 `tool_call` — ~4 patches per call. The fold is mostly a correlate-and-patch loop keyed on `toolCallId`, not a text accumulator.\n\n**2. `usage_update` is 81 frames of noise.** Nothing renderable. Drop, or aggregate once per turn.\n\n**3. The interesting data is in `_meta`, not in ACP.** ACP normalizes tools to a coarse `kind` (`execute`/`read`/`edit`). The actual tool name lives at `_meta.claudeCode.toolName` (`Bash`, `Write`, `Read`). Terminal output streams via `_meta.terminal_output` — **with raw ANSI escapes** — and the exit code via `_meta.terminal_exit`. None of that is standard ACP.\n\nSo a faithful fold **cannot be pure ACP**. It needs a harness-specific extension layer. I'd quarantine that explicitly rather than let `_meta` reads leak through the whole fold — one `ClaudeCodeMeta` extraction step, so a future harness slots in beside it instead of rewriting the core.\n\n**4. Frames arrive underspecified and get patched.** The `Write` tool call opens as `{\"rawInput\":{},\"status\":\"pending\",\"content\":[],\"locations\":[]}` — title is literally just `\"Write\"`. Everything useful arrives later. And `session/request_permission` is a request/response pair correlated by JSON-RPC **id**, not `toolCallId` — a pending permission is a renderable state that later resolves.\n\n## Proposed vocabulary\n\n```rust\n/// One renderable message. Derived, never stored.\npub struct AgentMessage {\n pub turn: TurnId, // prompt → stopReason\n pub parts: NonEmpty<AgentMessagePart>,\n}\n\npub enum AgentMessagePart {\n Text(Markdown),\n Thought(Markdown),\n ToolUse(ToolUse),\n Permission(PermissionPrompt), // pending | resolved(outcome)\n}\n\npub struct ToolUse {\n pub id: ToolUseId, // ACP toolCallId\n pub label: String, // _meta tool name, else title\n pub status: ToolStatus, // Pending | Running | Completed | Failed\n pub detail: ToolDetail,\n}\n\npub enum ToolDetail {\n Terminal { command: String, output: AnsiText, exit_code: Option<i32> },\n FileEdit { path: PathBuf, diff: Option<Diff> },\n FileRead { path: PathBuf },\n Other { kind: String, input: serde_json::Value },\n}\n```\n\n`AnsiText` as its own type because that decision has to land somewhere — strip at fold time or preserve and render client-side. I'd preserve; stripping is lossy and the frontend can decide.\n\n## Two consequences for what you stubbed\n\n**The fold is pure and infallible.** The log's `content` jsonb is already deserialized into `agent_session::domain::model::Message` by the repo (`crates/agent_session/src/domain/model.rs:60`), so the fold's input is typed on arrival. Unknown/irrelevant frames are skipped, not errored. That makes `domain/error.rs` dead — signature is just:\n\n```rust\nfn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Vec<AgentMessage>\n```\n\n**There's no port to define.** A pure fold does no I/O; the log source is already `agent_session`'s repo. So `agent_fold` wants to be a plain library with a free function and a `test.rs` replaying those three `.jsonl` files — not a hex crate with `domain/ports.rs`. Your trait stub is probably worth deleting rather than filling in.\n\nOne thing I'd want your call on before writing types: **granularity within a turn.** One `AgentMessage` per turn with parts in order (frontend collapses runs of `ToolUse` into an activity group) reads best as a channel message and is what I'd default to — but it means a turn is one big message that grows. The alternative is splitting a new message each time text follows tool activity, which gives a more conversational channel feel at the cost of a fuzzier boundary rule.Empirically answerable — let me check whether the log actually produces orphans.",
@@ -766,7 +574,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01AYc17jWRchH926P73NPt6L",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -781,15 +591,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions && for f in *.jsonl; do echo \"=== $f\"; \nopened=$(jq -r 'select(.content.params.update.sessionUpdate==\"tool_call\") | .content.params.update.toolCallId' $f | sort -u)\nupdated=$(jq -r 'select(.content.params.update.sessionUpdate==\"tool_call_update\") | .content.params.update.toolCallId' $f | sort -u)\necho \"opened=$(echo \"$opened\" | grep -c . ) updated=$(echo \"$updated\" | grep -c .)\"\necho \"orphan updates (patch w/ no open):\"; comm -13 <(echo \"$opened\") <(echo \"$updated\") | sed 's/^/ /'\necho \"never reached terminal status:\"\nfor id in $opened; do\n last=$(jq -r \"select(.content.params.update.toolCallId==\\\"$id\\\") | .content.params.update.status // empty\" $f | tail -1)\n case \"$last\" in completed|failed) ;; *) echo \" $id last_status=${last:-none}\";; esac\ndone\ndone"),
- "description": String("Check for orphan tool call updates and unterminated calls"),
- },
- ),
- raw_output: Some(
- String("=== 1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl\nopened=30 updated=29\norphan updates (patch w/ no open):\nnever reached terminal status:\n toolu_011jsLuU3pdvMBZ5UQuv87Mz\ntoolu_01352etHpBLWV1h8TL9UTmdc\ntoolu_013ZZhkrMVi1WUobYm5iLFBp\ntoolu_014E1teRuKvFVz3kXjjkS9Ah\ntoolu_015cPCzRzsgaeC5T4RKwfcqt\ntoolu_0166v7nKJaZsGG5TUqPcomaa\ntoolu_017CKQR5Ypi2BbXyyEWi9epq\ntoolu_018ArD4ZmaWuxEXW1KVfWxWi\ntoolu_018WB6FehVLcrszUvj598DeC\ntoolu_018xbq9fhqGHb88EBgsfVisi\ntoolu_019NXxCRZdm2cgJ4haDXmfRn\ntoolu_019iCEBqeqsXYMJQdJhvGZzE\ntoolu_01ATR61Vo1sUBC4sDTb9hgkQ\ntoolu_01B21mvnKULwrxijSpbU4hgU\ntoolu_01BSkUBhuv3VSJMmEXidfKDZ\ntoolu_01Ex1sHJeme9xM23T9tuUtvW\ntoolu_01F5V288iQ8iArGM4B3ayCFm\ntoolu_01FMZq9Myj3VrRZScNV2vx4o\ntoolu_01HocEetuSapsmVgT3isZYfw\ntoolu_01JnxGKMHWwnZCHCc7RWuBxk\ntoolu_01LPjM3sh7fjLME6aNNvbYtu\ntoolu_01MRKTuvyiKzhsv37MTRfvmQ\ntoolu_01MohDMjaUKCtkLJXFwjMqVY\ntoolu_01NuY6RvJBEwhYApLPbV3QfA\ntoolu_01T6GAjr5YEZpBifkp3vj1N9\ntoolu_01ULC7SdcZW6QpLwibk2SdF9\ntoolu_01V4uph7ZkZKaPpgF6UE4Nop\ntoolu_01VdTdh7sXMuLbz5B7D35poo\ntoolu_01XiuBq9trG9cXnZA3wDu7Gp\ntoolu_01Y6KvTMTESF9qJwnVDWLMMh last_status=none\n=== ab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl\nopened=0 updated=0\norphan updates (patch w/ no open):\nnever reached terminal status:\n=== cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl\nopened=16 updated=16\norphan updates (patch w/ no open):\nnever reached terminal status:\n toolu_011EjWXxbBUL3LeeWdhwZzVE\ntoolu_014z9EgjHhbpdT4oiKKbKVoi\ntoolu_015c1NGtLCDbzzN6gLsNek6c\ntoolu_017vXvd3YJFsTDHjuqH1pm9J\ntoolu_01C3WXuHqyYExW1fkiSdhQBm\ntoolu_01C7ZWnHKJy4TwzpXiReZgcz\ntoolu_01CtXAUSJxvsbs2FD7QmMqDu\ntoolu_01ETt3DxUVQNopgU44xbSc69\ntoolu_01GSaPYdcfh8YP2kDfjgb3v9\ntoolu_01JmdVCbwRjVNdCaXZAy6rL8\ntoolu_01JzF7TRdp8Hua7s8ogcF8bK\ntoolu_01KsnUYkdiXpsCnKiLAaBwEC\ntoolu_01RDnLaxGffMSSDvnHToEarF\ntoolu_01SfjW3NaG4UD6znQMU23cyf\ntoolu_01V3ua93NVQMzvw1UuSyz5Ds\ntoolu_01VScDhwjTxikVfbmwUoxaok last_status=none\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
Text {
text: "My loop was mangled by fish — redoing it as a single jq pass.",
@@ -798,7 +599,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_019Z1Rgt7583ZiypZa7sgjJX",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Failed,
detail: Terminal {
command: Some(
@@ -813,21 +616,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
1,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions; for f in *.jsonl; do echo \"=== $f\"; jq -s '\n[.[] | select(.content.params.update != null) | .content.params.update] as $u\n| ([$u[] | select(.sessionUpdate==\"tool_call\") | .toolCallId] | unique) as $o\n| ([$u[] | select(.sessionUpdate==\"tool_call_update\") | .toolCallId] | unique) as $p\n| { opened: ($o|length), patched: ($p|length),\n orphan_patches: ($p - $o),\n unterminated: [ $o[] as $id\n | ([$u[] | select(.toolCallId==$id) | .status // empty] | last // \"none\") as $l\n | select($l != \"completed\" and $l != \"failed\") | {id:$id, last:$l} ] }' $f; end"),
- "description": String("Correctly analyze tool call completeness"),
- },
- ),
- raw_output: Some(
- String("Exit code 1\n(eval):9: parse error near `end'"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01VbU2LJR4jYLDREztQ6RHJ5",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -842,21 +638,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions; for f in *.jsonl; do echo \"=== $f\"; jq -s '\n[.[] | select(.content.params.update != null) | .content.params.update] as $u\n| ([$u[] | select(.sessionUpdate==\"tool_call\") | .toolCallId] | unique) as $o\n| ([$u[] | select(.sessionUpdate==\"tool_call_update\") | .toolCallId] | unique) as $p\n| { opened: ($o|length), patched: ($p|length),\n orphan_patches: ($p - $o),\n unterminated: [ $o[] as $id\n | ([$u[] | select(.toolCallId==$id) | .status // empty] | last // \"none\") as $l\n | select($l != \"completed\" and $l != \"failed\") | {id:$id, last:$l} ] }' \"$f\"; done"),
- "description": String("Analyze tool call completeness with jq"),
- },
- ),
- raw_output: Some(
- String("=== 1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl\n{\n \"opened\": 30,\n \"patched\": 29,\n \"orphan_patches\": [],\n \"unterminated\": [\n {\n \"id\": \"toolu_01JnxGKMHWwnZCHCc7RWuBxk\",\n \"last\": \"pending\"\n },\n {\n \"id\": \"toolu_01VdTdh7sXMuLbz5B7D35poo\",\n \"last\": \"pending\"\n }\n ]\n}\n=== ab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl\n{\n \"opened\": 0,\n \"patched\": 0,\n \"orphan_patches\": [],\n \"unterminated\": []\n}\n=== cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl\n{\n \"opened\": 16,\n \"patched\": 16,\n \"orphan_patches\": [],\n \"unterminated\": []\n}\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01RYj6NV18X5Lt1eEaaGqmdQ",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -871,15 +660,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions; echo \"== total lines: $(wc -l < 1c6f5dbc*.jsonl)\"; grep -n -e toolu_01JnxGKMHWwnZCHCc7RWuBxk -e toolu_01VdTdh7sXMuLbz5B7D35poo 1c6f5dbc*.jsonl | cut -c1-160; echo \"== permission req ids vs result ids ==\"; jq -r 'select(.content.method==\"session/request_permission\") | \"req \" + (.content.id|tostring)' 1c6f5dbc*.jsonl; jq -r 'select(.content.result.outcome != null) | \"res \" + (.content.id|tostring) + \" \" + (.content.result.outcome.outcome // \"?\")' 1c6f5dbc*.jsonl"),
- "description": String("Locate unterminated calls and check permission pairing"),
- },
- ),
- raw_output: Some(
- String("== total lines: 299\n296:{\"ts\":\"2026-08-03T20:39:26.425Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0\n297:{\"ts\":\"2026-08-03T20:39:26.831Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0\n298:{\"ts\":\"2026-08-03T20:39:27.615Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0\n299:{\"ts\":\"2026-08-03T20:39:27.628Z\",\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"1c6f5dbc-0\n== permission req ids vs result ids ==\nreq 5\nres 5 selected\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
Text {
text: "Both unterminated calls are at lines 296–299 of a 299-line log — that's this live session mid-flight, not corruption. And permission pairing is clean (`req id 5` → `res id 5 selected`).\n\nSo: **zero orphan patches in 45 tool calls across 3 sessions.** Let me check the one thing that could manufacture them.",
@@ -888,7 +668,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01Ln6wSwGcnpNJh4rX2uhoPb",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -903,15 +685,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd ~/.agent_runtime_sessions; for f in *.jsonl; do echo \"=== $f\"; jq -r '.ts' \"$f\" | sort | uniq -d | wc -l | sed 's/^/ duplicate timestamps: /'; jq -r '.ts' \"$f\" | sort | uniq -c | sort -rn | head -3 | sed 's/^/ worst: /'; done"),
- "description": String("Check timestamp collisions in recordings"),
- },
- ),
- raw_output: Some(
- String("=== 1c6f5dbc-0fa8-4558-8ebb-3165a1daea56.jsonl\n duplicate timestamps: 44\n worst: 9 2026-08-03T20:24:14.147Z\n worst: 6 2026-08-03T20:24:14.179Z\n worst: 4 2026-08-03T20:36:48.149Z\n=== ab25cf29-d876-4ec6-9c30-dac24f13bcfe.jsonl\n duplicate timestamps: 2\n worst: 2 2026-08-03T20:09:15.973Z\n worst: 2 2026-08-03T20:08:59.828Z\n worst: 1 2026-08-03T20:09:15.999Z\n=== cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl\n duplicate timestamps: 20\n worst: 19 2026-08-03T20:09:03.277Z\n worst: 9 2026-08-03T20:09:03.275Z\n worst: 6 2026-08-03T20:09:03.276Z\nShell cwd was reset to /Users/eric/Code/macro"),
- ),
},
Text {
text: "That's the real finding. Let me check one thing that decides whether it matters.",
@@ -920,7 +693,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_016jwFFdrSR1LJ8cGfsDaEBY",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -935,21 +710,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("ls crates/macro_uuid/src/ && grep -rn \"fn new\\|now_v7\\|new_v4\\|uuid::Uuid\" crates/macro_uuid/src/*.rs | head -20"),
- "description": String("Check if macro_uuid is v7 time-ordered"),
- },
- ),
- raw_output: Some(
- String("lib.rs\ntest.rs\ncrates/macro_uuid/src/lib.rs:2:pub use uuid::Uuid;"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_019ks1zbBSkDLjzdWz71FFrn",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -964,15 +732,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat -n crates/macro_uuid/src/lib.rs; echo \"=== how log rows get ids ===\"; grep -rn \"agent_session_log\" -A 12 crates/agent_session/src/outbound/postgres/mod.rs | grep -i -e \"INSERT\" -e \"v7\\|v4\\|new(\" -e \"id\" | head -20"),
- "description": String("Check uuid generation for log rows"),
- },
- ),
- raw_output: Some(
- String(" 1\tuse anyhow::{Result, anyhow};\n 2\tpub use uuid::Uuid;\n 3\tuse uuid::{NoContext, Timestamp};\n 4\t\n 5\tpub fn generate_uuid_v7() -> Uuid {\n 6\t Uuid::new_v7(Timestamp::now(NoContext))\n 7\t}\n 8\t\n 9\tpub fn string_to_uuid(s: &str) -> Result<Uuid> {\n 10\t Uuid::parse_str(s).map_err(|e| anyhow!(e))\n 11\t}\n 12\t\n 13\t// Flickr's base58 alphabet as used in short-uuid\n 14\tconst FLICKR_BASE58: &str = \"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\";\n 15\t\n 16\t#[derive(Clone)]\n 17\tpub struct ShortUuidConverter {\n 18\t alphabet: String,\n 19\t base: u128,\n 20\t char_map: std::collections::HashMap<char, u128>,\n 21\t}\n 22\t\n 23\timpl Default for ShortUuidConverter {\n 24\t fn default() -> Self {\n 25\t let alphabet = FLICKR_BASE58.to_string();\n 26\t let base = alphabet.chars().count() as u128;\n 27\t let char_map = alphabet\n 28\t .chars()\n 29\t .enumerate()\n 30\t .map(|(i, c)| (c, i as u128))\n 31\t .collect();\n 32\t\n 33\t Self {\n 34\t alphabet,\n 35\t base,\n 36\t char_map,\n 37\t }\n 38\t }\n 39\t}\n 40\t\n 41\timpl ShortUuidConverter {\n 42\t /// checks if a string is a valid short UUID\n 43\t pub fn is_short_uuid(&self, s: &str) -> bool {\n 44\t // Short UUIDs using Flickr's base58:\n 45\t // 1. Must not be empty\n 46\t // 2. Must only contain characters from the Flickr base58 alphabet\n 47\t // 3. Typically shorter than standard UUID (which is 36 chars)\n 48\t // 4. Must not be longer than maximum possible length for a UUID in base58\n 49\t\n 50\t if s.is_empty() || s.len() >= 25 {\n 51\t // 25 is a safe upper bound for base58 UUID\n 52\t return false;\n 53\t }\n 54\t\n 55\t s.chars().all(|c| self.char_map.contains_key(&c))\n 56\t }\n 57\t\n 58\t /// checks if a string is a standard UUID\n 59\t pub fn is_standard_uuid(s: &str) -> bool {\n 60\t Uuid::parse_str(s).is_ok()\n 61\t }\n 62\t\n 63\t /// converts short uuid to uuid\n 64\t pub fn to_uuid(&self, short_uuid: &str) -> Result<Uuid> {\n 65\t if !self.is_short_uuid(short_uuid) {\n 66\t anyhow::bail!(\"Invalid short UUID format\");\n 67\t }\n 68\t\n 69\t // Convert from base58 to number\n 70\t let mut num: u128 = 0;\n 71\t for c in short_uuid.chars() {\n 72\t let digit = self\n 73\t .char_map\n 74\t .get(&c)\n 75\t .ok_or_else(|| anyhow!(\"Invalid character in short UUID: {}\", c))?;\n 76\t num = num * self.base + digit;\n 77\t }\n 78\t\n 79\t // Convert number to bytes (16 bytes for UUID)\n 80\t let bytes: [u8; 16] = num.to_be_bytes();\n 81\t Ok(Uuid::from_bytes(bytes))\n 82\t }\n 83\t\n 84\t /// converts uuid to short form\n 85\t pub fn from_uuid(&self, uuid: &Uuid) -> String {\n 86\t let mut num = u128::from_be_bytes(*uuid.as_bytes());\n 87\t let mut short = String::new();\n 88\t\n 89\t // Convert to base58\n 90\t while num > 0 {\n 91\t let rem = (num % self.base) as usize;\n 92\t short.push(self.alphabet.chars().nth(rem).unwrap());\n 93\t num /= self.base;\n 94\t }\n 95\t\n 96\t // Reverse the string\n 97\t short.chars().rev().collect()\n 98\t }\n 99\t}\n 100\t\n 101\t#[cfg(test)]\n 102\tmod test;\n=== how log rows get ids ===\ncrates/agent_session/src/outbound/postgres/mod.rs-83- id: Uuid,\ncrates/agent_session/src/outbound/postgres/mod.rs-84- created_from_thread_id: Option<Uuid>,\ncrates/agent_session/src/outbound/postgres/mod.rs-85- thread_id: Uuid,\ncrates/agent_session/src/outbound/postgres/mod.rs-86- bot_id: Uuid,\ncrates/agent_session/src/outbound/postgres/mod.rs-90- acp_session_id: Option<String>,\ncrates/agent_session/src/outbound/postgres/mod.rs:244: INSERT INTO agent_session_log (id, agent_session_id, user_id, direction, content)\ncrates/agent_session/src/outbound/postgres/mod.rs-247- macro_uuid::generate_uuid_v7(),\ncrates/agent_session/src/outbound/postgres/mod.rs-248- log.agent_session_id.as_uuid(),\ncrates/agent_session/src/outbound/postgres/mod.rs-249- log.user_id.as_ref().map(|user_id| user_id.as_ref()),\ncrates/agent_session/src/outbound/postgres/mod.rs-269- WHERE agent_session_id = $1\ncrates/agent_session/src/outbound/postgres/mod.rs-270- ORDER BY created_at ASC, id ASC\ncrates/agent_session/src/outbound/postgres/mod.rs-272- agent_session_id.as_uuid(),"),
- ),
},
Text {
text: "Checked the ordering hazard: log ids are `generate_uuid_v7()` (`crates/agent_session/src/outbound/postgres/mod.rs:247`) and the read is `ORDER BY created_at ASC, id ASC` (line 270). v7 is time-ordered, so the tie-break is chronological, and `created_at` comes from per-statement `now()` at microsecond resolution. Ordering is sound — frames can't reorder. Good, because the recordings pack up to 19 frames into a single millisecond.\n\nThat means your \"missing parts\" case is a small enumerable set, not chaos. Here's what the data says about each:\n\n**Tool call with no response — real, 2 of 46.** Both at lines 296–299 of a 299-line log: the live session. So this isn't corruption, it's the *in-flight* state. It also becomes permanent when a session dies (`SessionStatus::Disconnected` already exists at `agent_session/src/domain/model.rs:32`). Not an error — `ToolStatus::Pending` with no output is a thing you want to render, as a spinner or \"interrupted\".\n\n**Orphan patch (update before open) — 0 of 45.** Only reachable through `session/load` resume, where the log legitimately starts mid-stream. There's one `session/load` in the recordings.\n\n**Unpaired permission request — 0 of 1.** Same story: in-flight, not error.\n\n**Partial open frame — common, and this is the one that actually bites.** The `Write` call opens as `{\"rawInput\":{},\"title\":\"Write\",\"content\":[],\"locations\":[]}`. Every renderable field is absent and arrives later. If the type demands them at construction, this frame fails — and it's *normal traffic*.\n\n## So I'd argue against `Result` here\n\nBecause these messages are derived on every read, a fold error means **the channel renders blank**. Failing is the worst available outcome for a render path — a partially-known tool call is strictly better than nothing. Every case above is legitimately representable:\n\n```rust\nfn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Fold;\n\npub struct Fold {\n pub messages: Vec<AgentMessage>,\n pub anomalies: Vec<Anomaly>, // observability, not failure\n}\n\npub enum Anomaly {\n PatchBeforeOpen { tool_call: ToolUseId },\n UnknownSessionUpdate { kind: String },\n UnknownToolKind { kind: String },\n}\n```\n\nPush \"missing parts\" into the *type* — optionals inside `ToolUse`, so a call with nothing known still renders as a bare \"used a tool\" row — and surface the weirdness through `anomalies` instead of `Err`.\n\nThe payoff is in testing: your replay tests assert `anomalies.is_empty()` against the recorded fixtures, so protocol drift fails CI loudly, while production degrades gracefully instead of showing an empty channel. You get strictness where it's cheap and leniency where it's expensive.\n\nWant me to write the vocabulary into the crate now, with a `test.rs` that replays the three `.jsonl` files? I'd need your call on the turn-granularity question from before — one `AgentMessage` per turn is still my default.No `Result`, one explicit match. That kills the ports trait too. Let me check the one thing that decides the match's shape — how we get from a log row to typed ACP.",
@@ -981,7 +740,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01B8qQLpqdnLgGTvjEsvWHet",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -996,15 +757,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; grep -rn \"RawJsonRpcMessage\" $D/src/jsonrpc.rs | head -20; echo \"=== def ===\"; grep -rn \"pub struct RawJsonRpcMessage\\|pub enum RawJsonRpcMessage\" -A 25 $D/src/jsonrpc/*.rs $D/src/jsonrpc.rs 2>/dev/null | head -40"),
- "description": String("Inspect RawJsonRpcMessage"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:55:pub enum RawJsonRpcMessage {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:127:impl RawJsonRpcMessage {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:167:impl Serialize for RawJsonRpcMessage {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:186:impl<'de> Deserialize<'de> for RawJsonRpcMessage {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1298: /// The transport is responsible for serializing and deserializing [`RawJsonRpcMessage`]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1446: // Protocol layer: OutgoingMessage -> RawJsonRpcMessage\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1453: // Protocol layer: RawJsonRpcMessage -> handler/reply routing\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:3385: ) -> Result<RawJsonRpcMessage, crate::Error> {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:3388: Some(id) => RawJsonRpcMessage::request(method, params, id),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:3389: None => RawJsonRpcMessage::notification(method, params),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:4395: pub rx: mpsc::UnboundedReceiver<Result<RawJsonRpcMessage, crate::Error>>,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:4397: pub tx: mpsc::UnboundedSender<Result<RawJsonRpcMessage, crate::Error>>,\n=== def ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:55:pub enum RawJsonRpcMessage {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-56- /// A JSON-RPC request with an id and expected response.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-57- Request(RpcRequest<RawJsonRpcParams>),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-58- /// A JSON-RPC notification without a response.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-59- Notification(RpcNotification<RawJsonRpcParams>),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-60- /// A JSON-RPC response to a prior request.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-61- Response(RpcResponse<serde_json::Value>),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-62-}\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-63-\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-64-/// Raw JSON-RPC request or notification parameters.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-65-///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-66-/// JSON-RPC params, when present, must be either an array or an object.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-67-#[derive(Debug, Clone, PartialEq)]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-68-pub enum RawJsonRpcParams {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-69- /// Positional JSON-RPC params.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-70- Array(Vec<serde_json::Value>),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-71- /// Named JSON-RPC params.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-72- Object(serde_json::Map<String, serde_json::Value>),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-73-}\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-74-\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-75-impl RawJsonRpcParams {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-76- /// Convert a JSON value into JSON-RPC params.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-77- pub fn from_value(value: serde_json::Value) -> Result<Option<Self>, crate::Error> {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-78- match value {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-79- serde_json::Value::Null => Ok(None),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs-80- serde_json::Value::Array(array) => Ok(Some(Self::Array(array))),"),
- ),
},
Text {
text: "`RawJsonRpcMessage` is untyped — raw params. So the fold has to decode. Let me see if ACP gives us a typed envelope enum so the match can be genuinely exhaustive rather than string-dispatched.",
@@ -1013,7 +765,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01V7xp9geWVr3oeA1UAeCX8m",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1028,21 +782,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; grep -rn \"^pub enum \\(Client\\|Agent\\)\\(Notification\\|Request\\|Response\\)\\|pub enum ClientNotification\\|pub enum AgentNotification\" $D/src/ | head; echo \"=== SessionNotification ===\"; grep -rn \"pub struct SessionNotification\" -A 20 ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs | head -30"),
- "description": String("Look for typed ACP envelope enums"),
- },
- ),
- raw_output: Some(
- String("=== SessionNotification ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs:50:pub struct SessionNotification {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-51- /// The ID of the session this update pertains to.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-52- pub session_id: SessionId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-53- /// The actual update content.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-54- pub update: SessionUpdate,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-55- /// The _meta property is reserved by ACP to allow clients and agents to attach additional\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-56- /// metadata to their interactions. Implementations MUST NOT make assumptions about values at\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-57- /// these keys.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-58- ///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-59- /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-60- #[serde_as(deserialize_as = \"DefaultOnError\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-61- #[schemars(extend(\"x-deserialize-default-on-error\" = true))]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-62- #[serde(default)]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-63- #[serde(rename = \"_meta\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-64- pub meta: Option<Meta>,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-65-}\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-66-\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-67-impl SessionNotification {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-68- /// Builds [`SessionNotification`] with the required notification fields set; optional fields start unset or empty.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-69- #[must_use]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-70- pub fn new(session_id: impl Into<SessionId>, update: SessionUpdate) -> Self {"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LBs9wCxaeXcKkyKQDYw53q",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1057,21 +804,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; echo \"=== re-exports in lib.rs ===\"; grep -n \"pub use\" $D/src/lib.rs | head -20; echo \"=== Meta ===\"; grep -rn \"pub struct Meta\\|pub type Meta\" -A 6 ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/ | head -12"),
- "description": String("Check ACP re-exports and Meta type"),
- },
- ),
- raw_output: Some(
- String("=== re-exports in lib.rs ===\n95:pub use capabilities::*;\n97:pub use jsonrpc::{\n104:pub use jsonrpc::{RequestCancellation, is_cancel_request_notification};\n106:pub use role::{\n111:pub use component::{ConnectTo, DynConnectTo};\n114:pub use futures::future::BoxFuture;\n117:pub use schema::v1::{Error, ErrorCode, Result};\n120:pub use agent_client_protocol_derive::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};\n123:pub use session::*;\n126:pub use acp_agent::{AcpAgent, LineDirection};\n129:pub use stdio::Stdio;\n=== Meta ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs:15:pub type Meta = serde_json::Map<String, serde_json::Value>;\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs-16-\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs-17-/// Allows for sending an arbitrary request that is not part of the ACP spec.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs-18-/// Extension methods provide a way to add custom functionality while maintaining\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs-19-/// protocol compatibility.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs-20-///\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/ext.rs-21-/// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/ext.rs:15:pub type Meta = serde_json::Map<String, serde_json::Value>;\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/ext.rs-16-\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/ext.rs-17-/// Allows for sending an arbitrary request that is not part of the ACP spec.\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/ext.rs-18-/// Extension methods provide a way to add custom functionality while maintaining\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v2/ext.rs-19-/// protocol compatibility."),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01JKXbVLmzWzxmsRexjuJmjc",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1086,15 +826,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat crates/agent_session/Cargo.toml"),
- "description": String("Check agent_session deps"),
- },
- ),
- raw_output: Some(
- String("[package]\nname = \"agent_session\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n\nmacro_uuid = { path = \"../macro_uuid\" }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nbots = { path = \"../bots\"}\nmacro_user_id = { path = \"../macro_user_id\", features = [\"sqlx\"] }\nsqlx = { workspace = true }\nchrono = { workspace = true }\nthiserror = { workspace = true }\nanyhow = { workspace = true }\nserde_json = { workspace = true }\nworkspace-hack = { version = \"0.1\", path = \"../workspace-hack\" }\n\n[dev-dependencies]\nagent-client-protocol = { workspace = true }\nmacro_db_migrator = { path = \"../macro_db_migrator\" }\ntokio = { workspace = true, features = [\"macros\", \"rt-multi-thread\"] }"),
- ),
},
Text {
text: "No typed envelope enum and `SessionUpdate` is `#[non_exhaustive]`, so it's method-string dispatch → typed params → match on the update. That's exactly the explicit shape you want. Last details before I write:",
@@ -1103,7 +834,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01TDnpwNc7wRVoM1dNNpwL5E",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1118,21 +851,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("S=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1; echo \"=== ToolCall ===\"; grep -n \"pub struct ToolCall {\" -A 45 $S/client.rs | grep -v \"^\\s*[0-9]*-\\s*///\" | grep -v \"serde\\|schemars\\|serde_as\" | head -30; echo \"=== ToolCallUpdate ===\"; grep -n \"pub struct ToolCallUpdate {\" -A 40 $S/client.rs | grep -v \"^\\s*[0-9]*-\\s*///\" | grep -v \"serde\\|schemars\\|serde_as\" | head -25"),
- "description": String("Read ToolCall and ToolCallUpdate shapes"),
- },
- ),
- raw_output: Some(
- String("=== ToolCall ===\n=== ToolCallUpdate ==="),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01R8T1Wn8GZuAUejP5HBmX66",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1147,21 +873,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat crates/non_empty/src/lib.rs 2>/dev/null | head -60; ls crates/non_empty/src/"),
- "description": String("Check non_empty API"),
- },
- ),
- raw_output: Some(
- String("//! Wrapper around types that implement IsEmpty trait to ensure they are non-empty.\n\nuse serde::de::Error as _;\nuse serde::{Deserialize, Serialize};\nuse std::fmt;\nuse std::ops::Deref;\n\n#[cfg(test)]\nmod test;\n\n/// Error type for when attempting to create an NonEmpty with an empty collection\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct EmptyError;\n\nimpl fmt::Display for EmptyError {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"Cannot create NonEmpty from an empty collection\")\n }\n}\n\nimpl std::error::Error for EmptyError {}\n\n/// A wrapper type that ensures the wrapped value is not empty.\n///\n/// This type can wrap any type that implements the `IsEmpty` trait (or has an `is_empty()` method).\n/// It validates at construction time that the value is non-empty, returning an error if it is empty.\n///\n/// # Examples\n///\n/// ```\n/// use non_empty::NonEmpty;\n///\n/// // Success case with Vec\n/// let vec = vec![1, 2, 3];\n/// let non_empty = NonEmpty::new(vec).unwrap();\n/// assert_eq!(non_empty.len(), 3);\n///\n/// // Error case with empty Vec\n/// let empty_vec: Vec<i32> = vec![];\n/// assert!(NonEmpty::new(empty_vec).is_err());\n///\n/// // Works with HashMap\n/// use std::collections::HashMap;\n/// let mut map = HashMap::new();\n/// map.insert(\"key\", \"value\");\n/// let non_empty_map = NonEmpty::new(map).unwrap();\n/// // Can use HashMap methods directly via Deref\n/// assert_eq!(non_empty_map[\"key\"], \"value\");\n/// ```\n#[derive(Debug, Clone, PartialEq, Eq, Serialize)]\n#[serde(transparent)]\npub struct NonEmpty<T> {\n inner: T,\n}\n\nimpl<'de, T> Deserialize<'de> for NonEmpty<T>\nwhere\n T: Deserialize<'de> + IsEmpty,\n{\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\nlib.rs\ntest.rs"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01SRXCzzj8Qwsvq9ivymuC1E",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1176,21 +895,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n \"agent-client-protocol-schema\" -A 3 /Users/eric/Code/macro/Cargo.lock | head -12; echo \"=== find ToolCall struct ===\"; grep -rn \"pub struct ToolCall\\b\" ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-*/src/v1/*.rs | head"),
- "description": String("Find resolved schema version and ToolCall"),
- },
- ),
- raw_output: Some(
- String("90: \"agent-client-protocol-schema\",\n91- \"async-process\",\n92- \"blocking\",\n93- \"futures\",\n--\n116:name = \"agent-client-protocol-schema\"\n117-version = \"1.4.0\"\n118-source = \"registry+https://github.com/rust-lang/crates.io-index\"\n119-checksum = \"06679e1542356341f4550ccfb16338b64f37f6af70de2105446ef6fbb078234c\"\n=== find ToolCall struct ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/tool_call.rs:29:pub struct ToolCall {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.5.0/src/v1/tool_call.rs:29:pub struct ToolCall {"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LLrSGm3o4HeXjtL22kg1KC",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1205,21 +917,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("F=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/tool_call.rs; grep -n \"^pub \\(struct\\|enum\\)\\|^ pub [a-z_]*:\" $F | head -70"),
- "description": String("Read tool_call.rs shapes"),
- },
- ),
- raw_output: Some(
- String("29:pub struct ToolCall {\n31: pub tool_call_id: ToolCallId,\n33: pub title: String,\n39: pub kind: ToolKind,\n44: pub status: ToolCallStatus,\n49: pub content: Vec<ToolCallContent>,\n55: pub locations: Vec<ToolCallLocation>,\n60: pub raw_input: Option<serde_json::Value>,\n65: pub raw_output: Option<serde_json::Value>,\n75: pub meta: Option<Meta>,\n188:pub struct ToolCallUpdate {\n190: pub tool_call_id: ToolCallId,\n193: pub fields: ToolCallUpdateFields,\n203: pub meta: Option<Meta>,\n240:pub struct ToolCallUpdateFields {\n245: pub kind: Option<ToolKind>,\n250: pub status: Option<ToolCallStatus>,\n255: pub title: Option<String>,\n260: pub content: Option<Vec<ToolCallContent>>,\n265: pub locations: Option<Vec<ToolCallLocation>>,\n270: pub raw_input: Option<serde_json::Value>,\n275: pub raw_output: Option<serde_json::Value>,\n406:pub struct ToolCallId(pub Arc<str>);\n431:pub enum ToolKind {\n471:pub enum ToolCallStatus {\n502:pub enum ToolCallContent {\n533:pub struct Content {\n535: pub content: ContentBlock,\n545: pub meta: Option<Meta>,\n580:pub struct Terminal {\n582: pub terminal_id: TerminalId,\n592: pub meta: Option<Meta>,\n627:pub struct Diff {\n629: pub path: PathBuf,\n634: pub old_text: Option<String>,\n636: pub new_text: String,\n646: pub meta: Option<Meta>,\n691:pub struct ToolCallLocation {\n693: pub path: PathBuf,\n698: pub line: Option<u32>,\n708: pub meta: Option<Meta>,"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01WTbBesTaXiVdkiquSzSgm1",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1234,15 +939,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("F=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/tool_call.rs; sed -n '425,445p;465,510p' $F"),
- "description": String("Read ToolKind, ToolCallStatus, ToolCallContent variants"),
- },
- ),
- raw_output: Some(
- String("/// display tool execution progress.\n///\n/// See protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\n#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]\n#[serde(rename_all = \"snake_case\")]\n#[non_exhaustive]\npub enum ToolKind {\n /// Reading files or data.\n Read,\n /// Modifying files or content.\n Edit,\n /// Removing files or data.\n Delete,\n /// Moving or renaming files.\n Move,\n /// Searching for information.\n Search,\n /// Running commands or code.\n Execute,\n /// Internal reasoning or planning.\n Think,\n/// Tool calls progress through different statuses during their lifecycle.\n///\n/// See protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\n#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]\n#[serde(rename_all = \"snake_case\")]\n#[non_exhaustive]\npub enum ToolCallStatus {\n /// The tool call hasn't started running yet because the input is either\n /// streaming or we're awaiting approval.\n #[default]\n Pending,\n /// The tool call is currently running.\n InProgress,\n /// The tool call completed successfully.\n Completed,\n /// The tool call failed with an error.\n Failed,\n}\n\nimpl ToolCallStatus {\n #[expect(clippy::trivially_copy_pass_by_ref, reason = \"Required by serde\")]\n fn is_default(&self) -> bool {\n matches!(self, ToolCallStatus::Pending)\n }\n}\n\n/// Content produced by a tool call.\n///\n/// Tool calls can produce different types of content including\n/// standard content blocks (text, images) or file diffs.\n///\n/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\n#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]\n#[serde(tag = \"type\", rename_all = \"snake_case\")]\n#[schemars(extend(\"discriminator\" = {\"propertyName\": \"type\"}))]\n#[non_exhaustive]\n#[expect(clippy::large_enum_variant)]\npub enum ToolCallContent {\n /// Standard content block (text, images, resources).\n Content(Content),\n /// File modification shown as a diff.\n Diff(Diff),\n /// Embed a terminal created with `terminal/create` by its id.\n ///\n /// The terminal must be added before calling `terminal/release`.\n ///"),
- ),
},
Text {
text: "Everything checks out. One detail: the recordings show **mixed JSON-RPC id types** (`\"id\":\"dcb750c2-...\"` and `\"id\":5`), so correlation needs care.",
@@ -1251,7 +947,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01N6BLgjAoGAhxgh5vSVFX1p",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1266,21 +964,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; grep -n \"pub struct RpcRequest\\|pub struct RpcNotification\\|pub struct RpcResponse\\|pub enum RequestId\\|pub struct RequestId\" -A 14 $D/src/jsonrpc.rs | grep -v \"///\" | head -45"),
- "description": String("Read RpcRequest/Response id types"),
- },
- ),
- raw_output: Some(
- String("(Bash completed with no output)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01T5EFmheabRG2iikUtqkK36",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1295,21 +986,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; grep -rn \"struct RpcRequest\\|struct RpcResponse\\|struct RpcNotification\\|RequestId\" $D/src/*.rs $D/src/jsonrpc/*.rs | head -12"),
- "description": String("Locate Rpc types"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:5: Request as RpcRequest, RequestId, Response as RpcResponse, SessionId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:132: id: RequestId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:151: pub fn response(id: RequestId, response: Result<serde_json::Value, crate::Error>) -> Self {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:157: pub fn response_id(&self) -> Option<&RequestId> {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1525: id: RequestId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1682: slots: HashMap<RequestId, RequestCancellationSlot>,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1693: id: RequestId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1703: fn register(&self, id: &RequestId) -> ResponderCancellation {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1744: fn marker(&self, id: &RequestId, generation: u64) -> RequestCancellation {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1790: fn cancel(&self, request_id: &RequestId) -> bool {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1818: fn remove(&self, request_id: &RequestId, generation: u64) {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:1845:fn cancellation_request_id(dispatch: &Dispatch) -> Result<Option<RequestId>, crate::Error> {"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01NevBStmCFksbhVaXa7PFyh",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1324,15 +1008,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("S=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1; grep -rn \"pub enum ContentBlock\" -A 20 $S/content.rs | grep -v \"///\" | head -22; echo \"=== ContentChunk ===\"; grep -rn \"pub struct ContentChunk\" -A 12 $S/*.rs | grep -v \"///\" | head -14; echo \"=== PromptRequest / StopReason ===\"; grep -rn \"pub struct PromptRequest\" -A 12 $S/agent.rs | grep -v \"///\" | head -12; grep -rn \"pub enum StopReason\" -A 18 $S/agent.rs | grep -v \"///\" | head -20"),
- "description": String("Read ContentBlock, ContentChunk, PromptRequest, StopReason"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/content.rs:38:pub enum ContentBlock {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/content.rs-43- Text(TextContent),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/content.rs-47- Image(ImageContent),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/content.rs-51- Audio(AudioContent),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/content.rs-55- ResourceLink(ResourceLink),\n=== ContentChunk ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs:407:pub struct ContentChunk {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-409- pub content: ContentBlock,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-414- #[serde_as(deserialize_as = \"DefaultOnError\")]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-415- #[schemars(extend(\"x-deserialize-default-on-error\" = true))]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-416- #[serde(default)]\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/client.rs-417- pub message_id: Option<MessageId>,\n=== PromptRequest / StopReason ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs:3207:pub struct PromptRequest {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs-3209- pub session_id: SessionId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs:3335:pub enum StopReason {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs-3337- EndTurn,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs-3339- MaxTokens,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs-3342- MaxTurnRequests,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs-3346- Refusal,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/agent.rs-3353- Cancelled,"),
- ),
},
Text {
text: "Now I have the full picture. Writing it.",
@@ -1341,7 +1016,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01RWuiUWaScgdt5rf1KLBv6V",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1356,15 +1033,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat crates/agent_runtime_protocol/Cargo.toml; echo \"=== workspace members mentioning agent_fold ===\"; grep -n \"agent_fold\\|agent_session\\|agent_runtime_protocol\" Cargo.toml"),
- "description": String("Check dep patterns and workspace membership"),
- },
- ),
- raw_output: Some(
- String("[package]\nedition = \"2024\"\nname = \"agent_runtime_protocol\"\npublish = false\nversion = \"0.1.0\"\n\n[features]\ntest-utils = []\n\n[dependencies]\nagent-client-protocol = { workspace = true }\naxum = { workspace = true, features = [\"ws\"] }\nfutures = { workspace = true }\nserde = { workspace = true }\nserde_json = { workspace = true }\nspecta = { workspace = true }\nspecta-serde = { workspace = true }\nspecta-typescript = { workspace = true }\nthiserror = { workspace = true }\ntokio = { workspace = true, features = [\"rt\", \"sync\"] }\ntokio-tungstenite = { workspace = true }\ntracing = { workspace = true }\n\n[dev-dependencies]\ntokio = { workspace = true, features = [\"io-std\", \"io-util\", \"macros\", \"net\", \"rt\", \"rt-multi-thread\", \"time\"] }\n=== workspace members mentioning agent_fold ===\n5: \"crates/agent\", \"crates/agent_fold\",\n7: \"crates/agent_runtime_protocol\", \"crates/agent_session\","),
- ),
},
Text {
text: "Already a workspace member. Writing the crate now.",
@@ -1373,7 +1041,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01T2H17efiw2RWxccX8yZmqN",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Failed,
detail: Edit {
diffs: [
@@ -1384,41 +1054,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/Cargo.toml"),
- "content": String("[package]\nedition = \"2024\"\nname = \"agent_fold\"\npublish = false\nversion = \"0.1.0\"\n\n[dependencies]\nagent-client-protocol = { workspace = true }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nmacro_user_id = { path = \"../macro_user_id\" }\nnon_empty = { path = \"../non_empty\" }\nserde = { workspace = true }\nserde_json = { workspace = true }\n\n[dev-dependencies]\nserde_json = { workspace = true }\n"),
- },
- ),
- raw_output: Some(
- String("<tool_use_error>File has not been read yet. Read it first before writing to it.</tool_use_error>"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_015VCTRFM2kjYc3uX2U8qYPL",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_fold/Cargo.toml",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/Cargo.toml"),
- },
- ),
- raw_output: Some(
- String("1\t[package]\n2\tname = \"agent_fold\"\n3\tversion = \"0.1.0\"\n4\tedition = \"2024\"\n5\t\n6\t[dependencies]\n7\tthiserror = { workspace = true }\n8\tnon_empty = { path = \"../non_empty\" }\n9\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01QXMwDjKGFcFRsh4J4HNiWg",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1429,15 +1086,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/Cargo.toml"),
- "content": String("[package]\nedition = \"2024\"\nname = \"agent_fold\"\npublish = false\nversion = \"0.1.0\"\n\n[dependencies]\nagent-client-protocol = { workspace = true }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nmacro_user_id = { path = \"../macro_user_id\" }\nnon_empty = { path = \"../non_empty\" }\nserde = { workspace = true }\nserde_json = { workspace = true }\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/Cargo.toml has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the message vocabulary:",
@@ -1446,7 +1094,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01PkqPtUVwaQs3NDjektXfJT",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1457,21 +1107,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/message.rs"),
- "content": String("//! The renderable message vocabulary.\n//!\n//! These types are the fold's output: what an agent session looks like once\n//! its protocol log has been collapsed into something a channel can display.\n//! Nothing here is persisted - a [`FoldedMessage`] is derived from\n//! `agent_session_log` on every read, so the vocabulary is free to change\n//! without a migration.\n//!\n//! The shapes are deliberately lossy. ACP carries plenty that no reader wants\n//! to see (token usage, mode changes, capability handshakes); those frames are\n//! dropped rather than modelled. What survives is the material a person would\n//! recognize as the story of the session: what they asked, what the agent\n//! said, what it ran, and what it wanted permission to do.\n\nuse non_empty::NonEmpty;\nuse std::path::PathBuf;\n\n/// One prompt-to-stop cycle within a session.\n///\n/// Assigned by the fold in log order starting at zero, so the same log always\n/// yields the same ids. This is not the ACP request id - that correlation is\n/// internal to the fold.\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\npub struct TurnId(pub u32);\n\n/// A tool call within a turn, identified by its ACP `toolCallId`.\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\npub struct ToolUseId(pub String);\n\n/// One renderable message folded out of a session's protocol log.\n///\n/// A turn produces at most two of these: the user's prompt and the agent's\n/// reply. Both carry their content as an ordered part list, so a reader can\n/// collapse runs of tool activity or interleave text and tools however it\n/// likes.\n#[derive(Debug, Clone, PartialEq)]\npub struct FoldedMessage {\n /// The turn this message belongs to.\n pub turn: TurnId,\n /// Who produced it.\n pub author: Author,\n /// Ordered content. Never empty - the fold drops messages with no parts.\n pub parts: NonEmpty<Vec<MessagePart>>,\n /// How the turn ended, on the agent message that closed it.\n ///\n /// `None` while a turn is still in flight, or when the session died\n /// without a response to the prompt.\n pub stop: Option<StopReason>,\n}\n\n/// Who produced a [`FoldedMessage`].\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum Author {\n /// A person, via `session/prompt`.\n ///\n /// The id comes from the log row rather than the ACP payload, and is\n /// absent when the prompt was not attributed to a user.\n User(Option<String>),\n /// The agent.\n Agent,\n}\n\n/// A unit of renderable content.\n#[derive(Debug, Clone, PartialEq)]\npub enum MessagePart {\n /// Prose from the user or the agent.\n Text(String),\n /// The agent's reasoning, which a reader may want to hide by default.\n Thought(String),\n /// A tool the agent invoked.\n ToolUse(ToolUse),\n /// The agent asking to proceed.\n Permission(Permission),\n}\n\n/// A tool invocation and whatever is known about it so far.\n///\n/// Every field past the id is optional or defaulted, because ACP opens a tool\n/// call before it knows much: the `Write` tool arrives as\n/// `{\"rawInput\":{},\"title\":\"Write\",\"content\":[],\"locations\":[]}` and is filled\n/// in by later patches. A partially-known call still renders.\n#[derive(Debug, Clone, PartialEq)]\npub struct ToolUse {\n /// The ACP `toolCallId`.\n pub id: ToolUseId,\n /// What to show as the tool's name.\n ///\n /// Prefers the harness's own tool name (`Bash`, `Read`, `Write`) over\n /// ACP's coarse `kind`, since that is what a reader recognizes. Falls\n /// back to the ACP title when the harness reports nothing.\n pub label: String,\n /// Where the call got to.\n pub status: ToolStatus,\n /// What the tool did, as far as the log reveals.\n pub detail: ToolDetail,\n}\n\n/// How far a tool call progressed.\n///\n/// [`ToolStatus::Pending`] and [`ToolStatus::Running`] are legitimate final\n/// states, not errors: a live session's newest calls have not finished, and a\n/// session that dies mid-call leaves one behind permanently.\n#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]\npub enum ToolStatus {\n /// Not started - either still streaming input or awaiting permission.\n #[default]\n Pending,\n /// Currently running.\n Running,\n /// Finished successfully.\n Completed,\n /// Finished unsuccessfully.\n Failed,\n}\n\n/// What a tool call actually did.\n///\n/// Discriminated by what a reader needs in order to render it, not by ACP's\n/// [`ToolKind`](agent_client_protocol::ToolKind). A terminal wants command and\n/// output; an edit wants a diff; everything else wants its raw input shown as\n/// JSON.\n#[derive(Debug, Clone, PartialEq)]\npub enum ToolDetail {\n /// A shell command.\n Terminal {\n /// The command line, when the harness reported one.\n command: Option<String>,\n /// Captured output, ANSI escapes intact. See [`AnsiText`].\n output: Option<AnsiText>,\n /// Process exit code, when the harness reported one.\n exit_code: Option<i32>,\n },\n /// One or more file modifications.\n Edit {\n /// The diffs ACP reported for this call.\n diffs: Vec<FileDiff>,\n },\n /// A file read.\n Read {\n /// Paths this call touched.\n paths: Vec<PathBuf>,\n },\n /// Anything else, including tools the fold has no special rendering for.\n Other {\n /// ACP's tool kind, as its wire string.\n kind: String,\n /// The tool's input, when reported.\n input: Option<serde_json::Value>,\n },\n}\n\n/// A file modification a tool reported.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct FileDiff {\n /// The file that changed.\n pub path: PathBuf,\n /// Prior contents, absent when the file is new.\n pub old_text: Option<String>,\n /// New contents.\n pub new_text: String,\n}\n\n/// Terminal output with ANSI escape sequences left in place.\n///\n/// Stripping here would be lossy and irreversible, and the escapes carry real\n/// information - the recordings are full of colorized `ls` and `grep` output.\n/// Rendering decides whether to interpret, strip, or ignore them.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct AnsiText(pub String);\n\nimpl AnsiText {\n /// The raw text, escapes included.\n #[must_use]\n pub fn as_str(&self) -> &str {\n &self.0\n }\n}\n\n/// The agent asking permission to proceed with a tool call.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct Permission {\n /// The tool call permission was requested for.\n pub tool_call: ToolUseId,\n /// The choices offered, in the order ACP listed them.\n pub options: Vec<PermissionOption>,\n /// What the user chose.\n ///\n /// `None` while the request is outstanding, or when the session ended\n /// before anyone answered.\n pub outcome: Option<PermissionOutcome>,\n}\n\n/// One choice offered for a [`Permission`] request.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub struct PermissionOption {\n /// The id to report back when this option is chosen.\n pub id: String,\n /// Label to show.\n pub name: String,\n /// ACP's option kind, as its wire string - `allow_once`, `reject_once`,\n /// `allow_always`, `reject_always`.\n pub kind: String,\n}\n\n/// How a [`Permission`] request resolved.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum PermissionOutcome {\n /// An option was chosen.\n Selected {\n /// The chosen option's id.\n option_id: String,\n },\n /// The request was cancelled without a choice.\n Cancelled,\n}\n\n/// Why a turn stopped.\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum StopReason {\n /// The agent finished its turn.\n EndTurn,\n /// The model hit its token limit.\n MaxTokens,\n /// The agent hit its turn-request limit.\n MaxTurnRequests,\n /// The agent declined.\n Refusal,\n /// The turn was cancelled.\n Cancelled,\n /// A stop reason this fold does not model, as its wire string.\n Other(&'static str),\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/message.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01QuD8zhMyp3jCNHMLMEdccb",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1486,21 +1129,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n \"pub struct MacroUserIdStr\\|pub fn new\\|impl.*MacroUserIdStr\\|pub enum\" crates/macro_user_id/src/user_id.rs | head -20; echo \"=== features ===\"; grep -n \"\\[features\\]\" -A 6 crates/macro_user_id/Cargo.toml"),
- "description": String("Check MacroUserIdStr API"),
- },
- ),
- raw_output: Some(
- String("76:pub struct MacroUserIdStr<'a>(pub MacroUserId<Lowercase<'a>>);\n79:impl<'a> utoipa::ToSchema for MacroUserIdStr<'a> {\n86:impl<'a> utoipa::PartialSchema for MacroUserIdStr<'a> {\n92:impl<'a> std::fmt::Debug for MacroUserIdStr<'a> {\n109:impl<'a> doppleganger::Primitive for MacroUserIdStr<'a> {}\n111:impl<'a> std::fmt::Display for MacroUserIdStr<'a> {\n117:impl<'a> Deref for MacroUserIdStr<'a> {\n125:impl<'a> MacroUserIdStr<'a> {\n134:impl<'a> From<MacroUserIdStr<'a>> for MacroUserId<String> {\n144:impl MacroUserIdStr<'static> {\n151:impl TryFrom<String> for MacroUserIdStr<'static> {\n160:impl<'a> TryFrom<&'a str> for MacroUserIdStr<'a> {\n176:impl<'a> From<MacroUserIdStr<'a>> for String {\n183:impl<'a> sqlx::Type<sqlx::Postgres> for MacroUserIdStr<'a> {\n194:impl<'a> sqlx::postgres::PgHasArrayType for MacroUserIdStr<'a> {\n201:impl<'q> sqlx::Encode<'q, sqlx::Postgres> for MacroUserIdStr<'q> {\n215:impl<'r> sqlx::Decode<'r, sqlx::Postgres> for MacroUserIdStr<'static> {\n222:impl<'a> CowLike<'a> for MacroUserIdStr<'a> {\n=== features ===\n7:[features]\n8-schema = [\"dep:utoipa\"]\n9-sqlx = [\"dep:sqlx\"]\n10-\n11-[dependencies]\n12-cowlike = { path = \"../cowlike\" }\n13-doppleganger = { workspace = true }"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01CaR4g64cMXfdpwDosqALzP",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1515,21 +1151,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("sed -n '68,78p;125,150p' crates/macro_user_id/src/user_id.rs"),
- "description": String("Check MacroUserIdStr derives"),
- },
- ),
- raw_output: Some(
- String(" self.user_id.hash(state);\n }\n}\n\n/// The standard inner type for a [MacroUserId]\n/// This is a value which is guaranteed to be unmodified from its original input\n#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]\n#[serde(try_from = \"String\", into = \"String\")]\npub struct MacroUserIdStr<'a>(pub MacroUserId<Lowercase<'a>>);\n\n#[cfg(feature = \"schema\")]\nimpl<'a> MacroUserIdStr<'a> {\n /// parse the inner value from the input string\n pub fn parse_from_str(s: &'a str) -> Result<Self, ParseErr> {\n MacroUserId::parse_from_str(s)\n .map(|id| id.lowercase())\n .map(MacroUserIdStr)\n }\n}\n\nimpl<'a> From<MacroUserIdStr<'a>> for MacroUserId<String> {\n fn from(value: MacroUserIdStr<'a>) -> Self {\n MacroUserId {\n email_part: value.email_part,\n email_part_offset: value.email_part_offset,\n user_id: value.0.user_id.as_ref().into(),\n }\n }\n}\n\nimpl MacroUserIdStr<'static> {\n /// Create a MacroUserIdStr from an email address by prepending \"macro|\"\n pub fn try_from_email(email: &str) -> Result<Self, ParseErr> {\n Self::try_from(format!(\"{}|{}\", MACRO_PREFIX, email))\n }\n}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018MmsGdVRKGcXBLTexY6icm",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1542,23 +1171,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/message.rs"),
- "old_string": String("use non_empty::NonEmpty;\nuse std::path::PathBuf;"),
- "new_string": String("use macro_user_id::user_id::MacroUserIdStr;\nuse non_empty::NonEmpty;\nuse std::path::PathBuf;"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_016bMWEGPYrPdQR5dK18C6t6",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1571,23 +1191,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/message.rs"),
- "old_string": String(" /// A person, via `session/prompt`.\n ///\n /// The id comes from the log row rather than the ACP payload, and is\n /// absent when the prompt was not attributed to a user.\n User(Option<String>),"),
- "new_string": String(" /// A person, via `session/prompt`.\n ///\n /// The id comes from the log row rather than the ACP payload, and is\n /// absent when the prompt was not attributed to a user.\n User(Option<MacroUserIdStr<'static>>),"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_012q1xtZk5Ur7JNvVqQLbBQZ",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1600,23 +1211,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/message.rs"),
- "old_string": String("/// Why a turn stopped.\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\npub enum StopReason {"),
- "new_string": String("/// Why a turn stopped.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum StopReason {"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_014kDAJJqKsQvum7wiW9BFRx",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1629,17 +1231,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/message.rs"),
- "old_string": String(" /// A stop reason this fold does not model, as its wire string.\n Other(&'static str),"),
- "new_string": String(" /// A stop reason this fold does not model, as its wire string.\n Other(String),"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the harness `_meta` layer — quarantined, since this is the one place we read non-ACP data:",
@@ -1648,7 +1239,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01WcPGzVB8WquF1rUAv8w4Gu",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1659,15 +1252,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/meta.rs"),
- "content": String("//! Harness-specific `_meta` extraction.\n//!\n//! ACP reserves `_meta` for implementation-defined data and tells clients to\n//! make no assumptions about it. A faithful fold nevertheless has to read it,\n//! because the material a reader most wants is only there:\n//!\n//! - The real tool name (`Bash`, `Read`, `Write`). ACP normalizes tools to a\n//! coarse [`ToolKind`](agent_client_protocol::ToolKind), so `execute` is all\n//! the spec gives us.\n//! - Terminal output and exit codes. ACP's own\n//! [`Terminal`](agent_client_protocol::Terminal) content block carries only\n//! a `terminalId` pointing at a terminal the client is expected to have\n//! created itself. A fold reading a historical log never created one, so the\n//! only output it will ever see is the copy in `_meta`.\n//!\n//! Everything that depends on a specific harness lives in this module, so\n//! supporting a second one means adding a sibling reader rather than editing\n//! the fold. Every function here treats a missing or misshapen key as \"no\n//! information\" and returns `None`.\n\nuse agent_client_protocol::Meta;\n\n/// The `_meta` keys written by the Claude Code harness.\npub mod claude_code {\n use super::Meta;\n\n /// The harness's own name for the tool behind a `tool_call`.\n ///\n /// Reads `_meta.claudeCode.toolName`.\n #[must_use]\n pub fn tool_name(meta: Option<&Meta>) -> Option<String> {\n meta?\n .get(\"claudeCode\")?\n .get(\"toolName\")?\n .as_str()\n .map(ToOwned::to_owned)\n }\n\n /// A chunk of terminal output carried on a `tool_call_update`.\n ///\n /// Reads `_meta.terminal_output.data`. Each update carries the output\n /// accumulated so far rather than only the new bytes, so callers should\n /// replace rather than append.\n #[must_use]\n pub fn terminal_output(meta: Option<&Meta>) -> Option<String> {\n meta?\n .get(\"terminal_output\")?\n .get(\"data\")?\n .as_str()\n .map(ToOwned::to_owned)\n }\n\n /// The exit code reported when a terminal-backed tool call finished.\n ///\n /// Reads `_meta.terminal_exit.exit_code`.\n #[must_use]\n pub fn terminal_exit_code(meta: Option<&Meta>) -> Option<i32> {\n let code = meta?.get(\"terminal_exit\")?.get(\"exit_code\")?.as_i64()?;\n i32::try_from(code).ok()\n }\n}\n\n/// The command line behind an `execute` tool call.\n///\n/// This one reads ACP's own `rawInput` rather than `_meta`, but lives here\n/// because the key it looks for (`command`) is a harness convention that ACP\n/// does not specify.\n#[must_use]\npub fn command_from_raw_input(raw_input: Option<&serde_json::Value>) -> Option<String> {\n raw_input?\n .get(\"command\")?\n .as_str()\n .map(ToOwned::to_owned)\n}\n\n#[cfg(test)]\nmod test;\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/meta.rs (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the fold itself — one explicit match:",
@@ -1676,7 +1260,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01Qc86PFeEm9GLk2rah6m9nz",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1687,15 +1273,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "content": String("//! Collapsing a session's protocol log into renderable messages.\n//!\n//! # Why this cannot fail\n//!\n//! [`fold`] is total. Messages are derived on every read, so returning an\n//! error would mean rendering an empty channel - strictly worse than rendering\n//! a partially-understood session. Every case that looks like a failure is\n//! instead a state worth showing:\n//!\n//! - A tool call with no result is in flight, or was interrupted when the\n//! session died. Its status stays [`ToolStatus::Pending`].\n//! - A tool call whose opening frame carried no useful fields gets them from\n//! later patches. Until then it renders as a bare tool row.\n//! - A permission request with no answer is outstanding.\n//!\n//! What is left over - a patch for a tool call that was never opened, an\n//! update variant this fold does not model - is reported through\n//! [`Fold::anomalies`] instead. That keeps the render path lenient while\n//! letting tests be strict: a replay test asserts `anomalies.is_empty()`, so\n//! protocol drift fails loudly in CI rather than silently degrading in\n//! production.\n//!\n//! # Why one match rather than a registry\n//!\n//! Dispatch is a single explicit `match` over the protocol, in [`fold`] and\n//! the handlers it calls. A registry of self-describing handlers would move\n//! the decision of what matches what into data, where it is invisible; here\n//! every frame this fold understands is named in one place you can read\n//! top-to-bottom, and every frame it ignores is an explicit arm.\n\nuse crate::meta::{claude_code, command_from_raw_input};\nuse crate::message::{\n AnsiText, Author, FileDiff, FoldedMessage, MessagePart, Permission, PermissionOption,\n PermissionOutcome, StopReason, ToolDetail, ToolStatus, ToolUse, ToolUseId, TurnId,\n};\nuse agent_client_protocol::{\n ContentBlock, RawJsonRpcMessage, RawJsonRpcParams, RequestId, SessionNotification,\n SessionUpdate, ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,\n};\nuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};\nuse macro_user_id::user_id::MacroUserIdStr;\nuse non_empty::NonEmpty;\nuse std::collections::HashMap;\n\n#[cfg(test)]\nmod test;\n\n/// One row of a session's protocol log.\n///\n/// Mirrors `agent_session_log`, but is defined here so the fold depends only\n/// on the protocol schema rather than on the crate that persists it.\n#[derive(Debug, Clone)]\npub struct LogEntry {\n /// Set when this frame is ACP traffic that originated from a user.\n pub user_id: Option<MacroUserIdStr<'static>>,\n /// The frame, in its original direction.\n pub message: LogMessage,\n}\n\n/// A logged frame, tagged with the direction it travelled.\n#[derive(Debug, Clone)]\npub enum LogMessage {\n /// Agent Runtime to Agent Service.\n ToServer(ToServerMessage),\n /// Agent Service to Agent Runtime.\n ToRuntime(ToRuntimeMessage),\n}\n\n/// The result of folding a log.\n#[derive(Debug, Clone, Default)]\npub struct Fold {\n /// Renderable messages, in log order.\n pub messages: Vec<FoldedMessage>,\n /// Frames the fold could not place. Not failures - see the module docs.\n pub anomalies: Vec<Anomaly>,\n}\n\n/// Something in the log the fold could not account for.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum Anomaly {\n /// A `tool_call_update` arrived for an id no `tool_call` had opened.\n ///\n /// Unobserved in practice: log rows are ordered by `created_at` then by a\n /// v7 uuid, which is itself time-ordered, so frames cannot be reordered.\n /// It is still reachable through `session/load`, where a resumed session's\n /// log legitimately begins mid-stream.\n PatchBeforeOpen {\n /// The unopened tool call.\n tool_call: ToolUseId,\n },\n /// A `session/update` whose variant this fold does not model.\n UnmodelledSessionUpdate {\n /// The variant's wire name, when it could be read.\n kind: String,\n },\n /// A `session/update` frame whose params would not deserialize.\n UndecodableSessionUpdate,\n /// A response arrived for a request id the fold was not tracking.\n UncorrelatedResponse,\n}\n\n/// Collapse a session's protocol log into renderable messages.\n///\n/// Total by construction: unrecognized and incomplete frames land in\n/// [`Fold::anomalies`] rather than aborting the fold. See the module docs for\n/// why.\n#[must_use]\npub fn fold(log: impl IntoIterator<Item = LogEntry>) -> Fold {\n let mut state = State::default();\n\n for entry in log {\n // The one place the protocol is dispatched. Each arm names a frame\n // this fold understands; the rest are ignored on purpose.\n match &entry.message {\n LogMessage::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {\n // A user's prompt opens a turn.\n RawJsonRpcMessage::Request(request) if request.method == \"session/prompt\" => {\n state.begin_turn(&request.id, params_value(request.params.as_ref()), entry.user_id);\n }\n // The user's answer to a permission request.\n RawJsonRpcMessage::Response(response) => {\n state.resolve_permission(&response.id, response_value(response));\n }\n // Handshake and configuration traffic: nothing to render.\n RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => {}\n },\n\n LogMessage::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {\n // The bulk of the log: streamed content and tool activity.\n RawJsonRpcMessage::Notification(notification)\n if notification.method == \"session/update\" =>\n {\n state.apply_session_update(params_value(notification.params.as_ref()));\n }\n // The agent asking to proceed.\n RawJsonRpcMessage::Request(request)\n if request.method == \"session/request_permission\" =>\n {\n state.request_permission(&request.id, params_value(request.params.as_ref()));\n }\n // The response to `session/prompt` closes the turn.\n RawJsonRpcMessage::Response(response) => {\n state.end_turn(&response.id, response_value(response));\n }\n RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => {}\n },\n\n // Runtime lifecycle events carry no conversation content. The one\n // the service acts on, `acp_ready`, is a handshake signal.\n LogMessage::ToServer(ToServerMessage::Event { .. }) => {}\n\n // Both message enums are `#[non_exhaustive]`.\n _ => {}\n }\n }\n\n state.finish()\n}\n\n/// Accumulated fold state.\n#[derive(Default)]\nstruct State {\n messages: Vec<FoldedMessage>,\n anomalies: Vec<Anomaly>,\n /// The turn currently being built, if any.\n turn: Option<Turn>,\n /// How many turns have been opened, which is also the next [`TurnId`].\n turns_opened: u32,\n /// Outstanding permission requests, by the id of the request that asked.\n pending_permissions: HashMap<RequestId, ToolUseId>,\n}\n\n/// A turn under construction.\nstruct Turn {\n id: TurnId,\n /// The `session/prompt` request whose response will close this turn.\n prompt_id: RequestId,\n /// Parts of the agent's reply, in arrival order.\n parts: Vec<MessagePart>,\n /// Where each tool call sits in `parts`, so patches can find it.\n tool_positions: HashMap<ToolUseId, usize>,\n /// Where each permission sits in `parts`, so outcomes can find it.\n permission_positions: HashMap<ToolUseId, usize>,\n}\n\nimpl State {\n /// Handle a `session/prompt`: emit the user's message, open a turn.\n fn begin_turn(\n &mut self,\n prompt_id: &RequestId,\n params: Option<serde_json::Value>,\n user_id: Option<MacroUserIdStr<'static>>,\n ) {\n // A second prompt without an intervening response means the previous\n // turn never got one. Close it out so its content is not lost.\n self.close_turn(None);\n\n let id = TurnId(self.turns_opened);\n self.turns_opened += 1;\n\n let text = params\n .as_ref()\n .and_then(|params| params.get(\"prompt\"))\n .and_then(|prompt| prompt.as_array())\n .map(|blocks| {\n blocks\n .iter()\n .filter_map(|block| {\n serde_json::from_value::<ContentBlock>(block.clone()).ok()\n })\n .filter_map(content_block_text)\n .collect::<Vec<_>>()\n .join(\"\")\n })\n .unwrap_or_default();\n\n if !text.is_empty() {\n self.push_message(FoldedMessage {\n turn: id,\n author: Author::User(user_id),\n parts: NonEmpty::new(vec![MessagePart::Text(text)])\n .expect(\"checked non-empty above\"),\n stop: None,\n });\n }\n\n self.turn = Some(Turn {\n id,\n prompt_id: prompt_id.clone(),\n parts: Vec::new(),\n tool_positions: HashMap::new(),\n permission_positions: HashMap::new(),\n });\n }\n\n /// Handle the response to `session/prompt`: close the turn.\n fn end_turn(&mut self, response_id: &RequestId, value: Option<serde_json::Value>) {\n let is_current_turn = self\n .turn\n .as_ref()\n .is_some_and(|turn| &turn.prompt_id == response_id);\n\n if !is_current_turn {\n // Responses to `initialize`, `session/new` and `session/load`\n // land here. Only flag one that looks like a turn ending.\n if value\n .as_ref()\n .is_some_and(|value| value.get(\"stopReason\").is_some())\n {\n self.anomalies.push(Anomaly::UncorrelatedResponse);\n }\n return;\n }\n\n let stop = value\n .as_ref()\n .and_then(|value| value.get(\"stopReason\"))\n .and_then(|reason| reason.as_str())\n .map(stop_reason);\n\n self.close_turn(stop);\n }\n\n /// Handle a `session/update`.\n fn apply_session_update(&mut self, params: Option<serde_json::Value>) {\n let Some(params) = params else {\n self.anomalies.push(Anomaly::UndecodableSessionUpdate);\n return;\n };\n\n // Keep the wire name before decoding, so an unmodelled variant can be\n // named in the anomaly even though `SessionUpdate` is non-exhaustive.\n let wire_kind = params\n .get(\"update\")\n .and_then(|update| update.get(\"sessionUpdate\"))\n .and_then(|kind| kind.as_str())\n .unwrap_or(\"<missing>\")\n .to_owned();\n\n let Ok(notification) = serde_json::from_value::<SessionNotification>(params) else {\n self.anomalies.push(Anomaly::UndecodableSessionUpdate);\n return;\n };\n\n match notification.update {\n // Prose from the agent. Chunks are appended to the open text part\n // rather than each becoming a part of its own.\n SessionUpdate::AgentMessageChunk(chunk) => {\n if let Some(text) = content_block_text(chunk.content) {\n self.append_text(text);\n }\n }\n // Reasoning, kept separate so a reader can collapse it.\n SessionUpdate::AgentThoughtChunk(chunk) => {\n if let Some(text) = content_block_text(chunk.content) {\n self.append_thought(text);\n }\n }\n // The agent replaying the user's own message. The prompt frame is\n // the authoritative copy, so this is dropped.\n SessionUpdate::UserMessageChunk(_) => {}\n SessionUpdate::ToolCall(call) => self.open_tool_call(*Box::new(call)),\n SessionUpdate::ToolCallUpdate(update) => self.patch_tool_call(update),\n // Deliberately dropped: token accounting and session bookkeeping,\n // none of which a reader wants in a channel. `usage_update` alone\n // is 81 of ~450 frames in a recorded session.\n SessionUpdate::UsageUpdate(_)\n | SessionUpdate::SessionInfoUpdate(_)\n | SessionUpdate::AvailableCommandsUpdate(_)\n | SessionUpdate::CurrentModeUpdate(_)\n | SessionUpdate::ConfigOptionUpdate(_) => {}\n // Plans are renderable and worth folding, but no recorded session\n // has produced one yet, so there is nothing to verify a shape\n // against. Reported rather than guessed at.\n SessionUpdate::Plan(_) => self\n .anomalies\n .push(Anomaly::UnmodelledSessionUpdate { kind: wire_kind }),\n _ => self\n .anomalies\n .push(Anomaly::UnmodelledSessionUpdate { kind: wire_kind }),\n }\n }\n\n /// Handle a `tool_call`: add a new tool part.\n fn open_tool_call(&mut self, call: ToolCall) {\n let id = ToolUseId(call.tool_call_id.0.to_string());\n let label = claude_code::tool_name(call.meta.as_ref()).unwrap_or_else(|| call.title.clone());\n\n let tool = ToolUse {\n id: id.clone(),\n label,\n status: tool_status(call.status),\n detail: tool_detail(call.kind, call.raw_input.as_ref(), &call.content, call.meta.as_ref()),\n };\n\n let Some(turn) = self.turn.as_mut() else {\n return;\n };\n\n // A repeated open for the same id patches in place rather than\n // duplicating the row.\n if let Some(&position) = turn.tool_positions.get(&id) {\n if let Some(MessagePart::ToolUse(existing)) = turn.parts.get_mut(position) {\n *existing = tool;\n }\n return;\n }\n\n turn.tool_positions.insert(id, turn.parts.len());\n turn.parts.push(MessagePart::ToolUse(tool));\n }\n\n /// Handle a `tool_call_update`: patch an existing tool part.\n ///\n /// Only fields the update actually carries are written, since\n /// `ToolCallUpdateFields` is entirely optional and a typical call is\n /// patched several times - the recordings average about four updates per\n /// call.\n fn patch_tool_call(&mut self, update: ToolCallUpdate) {\n let id = ToolUseId(update.tool_call_id.0.to_string());\n\n let Some(turn) = self.turn.as_mut() else {\n return;\n };\n let Some(&position) = turn.tool_positions.get(&id) else {\n self.anomalies\n .push(Anomaly::PatchBeforeOpen { tool_call: id });\n return;\n };\n let Some(MessagePart::ToolUse(tool)) = turn.parts.get_mut(position) else {\n return;\n };\n\n let fields = update.fields;\n\n if let Some(status) = fields.status {\n tool.status = tool_status(status);\n }\n if let Some(title) = fields.title {\n // A harness-supplied name outranks any ACP title, so only take\n // the title when nothing better is already set.\n if claude_code::tool_name(update.meta.as_ref()).is_none() && tool.label.is_empty() {\n tool.label = title;\n }\n }\n if let Some(name) = claude_code::tool_name(update.meta.as_ref()) {\n tool.label = name;\n }\n\n patch_detail(\n &mut tool.detail,\n fields.raw_input.as_ref(),\n fields.content.as_deref(),\n update.meta.as_ref(),\n );\n }\n\n /// Handle a `session/request_permission`: add a permission part and record\n /// the request id so its response can be matched.\n fn request_permission(&mut self, request_id: &RequestId, params: Option<serde_json::Value>) {\n let Some(params) = params else { return };\n\n let Some(tool_call) = params\n .get(\"toolCall\")\n .and_then(|call| call.get(\"toolCallId\"))\n .and_then(|id| id.as_str())\n .map(|id| ToolUseId(id.to_owned()))\n else {\n return;\n };\n\n let options = params\n .get(\"options\")\n .and_then(|options| options.as_array())\n .map(|options| {\n options\n .iter()\n .filter_map(|option| {\n Some(PermissionOption {\n id: option.get(\"optionId\")?.as_str()?.to_owned(),\n name: option.get(\"name\")?.as_str()?.to_owned(),\n kind: option.get(\"kind\")?.as_str()?.to_owned(),\n })\n })\n .collect()\n })\n .unwrap_or_default();\n\n self.pending_permissions\n .insert(request_id.clone(), tool_call.clone());\n\n let Some(turn) = self.turn.as_mut() else {\n return;\n };\n turn.permission_positions\n .insert(tool_call.clone(), turn.parts.len());\n turn.parts.push(MessagePart::Permission(Permission {\n tool_call,\n options,\n outcome: None,\n }));\n }\n\n /// Handle the response to a permission request.\n fn resolve_permission(&mut self, response_id: &RequestId, value: Option<serde_json::Value>) {\n let Some(tool_call) = self.pending_permissions.remove(response_id) else {\n return;\n };\n\n // `{\"outcome\": {\"outcome\": \"selected\", \"optionId\": \"...\"}}`\n let outcome = value\n .as_ref()\n .and_then(|value| value.get(\"outcome\"))\n .and_then(|outcome| {\n match outcome.get(\"outcome\").and_then(|kind| kind.as_str())? {\n \"selected\" => Some(PermissionOutcome::Selected {\n option_id: outcome.get(\"optionId\")?.as_str()?.to_owned(),\n }),\n \"cancelled\" => Some(PermissionOutcome::Cancelled),\n _ => None,\n }\n });\n\n let Some(turn) = self.turn.as_mut() else {\n return;\n };\n let Some(&position) = turn.permission_positions.get(&tool_call) else {\n return;\n };\n if let Some(MessagePart::Permission(permission)) = turn.parts.get_mut(position) {\n permission.outcome = outcome;\n }\n }\n\n /// Append agent prose, extending the trailing text part when there is one.\n fn append_text(&mut self, text: String) {\n let Some(turn) = self.turn.as_mut() else {\n return;\n };\n match turn.parts.last_mut() {\n Some(MessagePart::Text(existing)) => existing.push_str(&text),\n _ => turn.parts.push(MessagePart::Text(text)),\n }\n }\n\n /// Append agent reasoning, extending the trailing thought part when there\n /// is one.\n fn append_thought(&mut self, text: String) {\n let Some(turn) = self.turn.as_mut() else {\n return;\n };\n match turn.parts.last_mut() {\n Some(MessagePart::Thought(existing)) => existing.push_str(&text),\n _ => turn.parts.push(MessagePart::Thought(text)),\n }\n }\n\n /// Emit the open turn's agent message, if it produced anything.\n fn close_turn(&mut self, stop: Option<StopReason>) {\n let Some(turn) = self.turn.take() else { return };\n\n if let Ok(parts) = NonEmpty::new(turn.parts) {\n self.push_message(FoldedMessage {\n turn: turn.id,\n author: Author::Agent,\n parts,\n stop,\n });\n }\n }\n\n fn push_message(&mut self, message: FoldedMessage) {\n self.messages.push(message);\n }\n\n /// Close any turn still open - a live or abandoned session - and return.\n fn finish(mut self) -> Fold {\n self.close_turn(None);\n Fold {\n messages: self.messages,\n anomalies: self.anomalies,\n }\n }\n}\n\n/// The text carried by a content block, if it carries any.\nfn content_block_text(block: ContentBlock) -> Option<String> {\n match block {\n ContentBlock::Text(text) => Some(text.text),\n // Images, audio, resource links and embedded resources have no text\n // to fold. Rendering them is a separate problem from this one.\n _ => None,\n }\n}\n\n/// Build a [`ToolDetail`] from a tool call's opening frame.\nfn tool_detail(\n kind: ToolKind,\n raw_input: Option<&serde_json::Value>,\n content: &[ToolCallContent],\n meta: Option<&agent_client_protocol::Meta>,\n) -> ToolDetail {\n match kind {\n ToolKind::Execute => ToolDetail::Terminal {\n command: command_from_raw_input(raw_input),\n output: claude_code::terminal_output(meta).map(AnsiText),\n exit_code: claude_code::terminal_exit_code(meta),\n },\n ToolKind::Edit => ToolDetail::Edit {\n diffs: diffs(content),\n },\n ToolKind::Read => ToolDetail::Read {\n paths: read_paths(raw_input),\n },\n other => ToolDetail::Other {\n kind: tool_kind_name(other).to_owned(),\n input: raw_input.cloned(),\n },\n }\n}\n\n/// Write an update's fields into an existing detail, leaving what it does not\n/// carry untouched.\nfn patch_detail(\n detail: &mut ToolDetail,\n raw_input: Option<&serde_json::Value>,\n content: Option<&[ToolCallContent]>,\n meta: Option<&agent_client_protocol::Meta>,\n) {\n match detail {\n ToolDetail::Terminal {\n command,\n output,\n exit_code,\n } => {\n if let Some(found) = command_from_raw_input(raw_input) {\n *command = Some(found);\n }\n // Each update carries the output accumulated so far, so replace.\n if let Some(found) = claude_code::terminal_output(meta) {\n *output = Some(AnsiText(found));\n }\n if let Some(found) = claude_code::terminal_exit_code(meta) {\n *exit_code = Some(found);\n }\n }\n ToolDetail::Edit { diffs: existing } => {\n if let Some(content) = content {\n let found = diffs(content);\n if !found.is_empty() {\n *existing = found;\n }\n }\n }\n ToolDetail::Read { paths } => {\n let found = read_paths(raw_input);\n if !found.is_empty() {\n *paths = found;\n }\n }\n ToolDetail::Other { input, .. } => {\n if let Some(found) = raw_input {\n *input = Some(found.clone());\n }\n }\n }\n}\n\n/// The diffs among a tool call's content blocks.\nfn diffs(content: &[ToolCallContent]) -> Vec<FileDiff> {\n content\n .iter()\n .filter_map(|block| match block {\n ToolCallContent::Diff(diff) => Some(FileDiff {\n path: diff.path.clone(),\n old_text: diff.old_text.clone(),\n new_text: diff.new_text.clone(),\n }),\n _ => None,\n })\n .collect()\n}\n\n/// The paths a read tool was pointed at.\nfn read_paths(raw_input: Option<&serde_json::Value>) -> Vec<PathBufList> {\n raw_input\n .and_then(|input| input.get(\"file_path\"))\n .and_then(|path| path.as_str())\n .map(|path| vec![std::path::PathBuf::from(path)])\n .unwrap_or_default()\n}\n\n/// Alias kept local so the signature above reads as a list of paths.\ntype PathBufList = std::path::PathBuf;\n\nfn tool_status(status: ToolCallStatus) -> ToolStatus {\n match status {\n ToolCallStatus::Pending => ToolStatus::Pending,\n ToolCallStatus::InProgress => ToolStatus::Running,\n ToolCallStatus::Completed => ToolStatus::Completed,\n ToolCallStatus::Failed => ToolStatus::Failed,\n // `ToolCallStatus` is `#[non_exhaustive]`; an unknown status has not\n // demonstrably finished.\n _ => ToolStatus::Pending,\n }\n}\n\nfn tool_kind_name(kind: ToolKind) -> &'static str {\n match kind {\n ToolKind::Read => \"read\",\n ToolKind::Edit => \"edit\",\n ToolKind::Delete => \"delete\",\n ToolKind::Move => \"move\",\n ToolKind::Search => \"search\",\n ToolKind::Execute => \"execute\",\n ToolKind::Think => \"think\",\n ToolKind::Fetch => \"fetch\",\n ToolKind::SwitchMode => \"switch_mode\",\n ToolKind::Other => \"other\",\n _ => \"unknown\",\n }\n}\n\nfn stop_reason(wire: &str) -> StopReason {\n match wire {\n \"end_turn\" => StopReason::EndTurn,\n \"max_tokens\" => StopReason::MaxTokens,\n \"max_turn_requests\" => StopReason::MaxTurnRequests,\n \"refusal\" => StopReason::Refusal,\n \"cancelled\" => StopReason::Cancelled,\n other => StopReason::Other(other.to_owned()),\n }\n}\n\n/// JSON-RPC params as a plain value, so handlers can decode selectively.\nfn params_value(params: Option<&RawJsonRpcParams>) -> Option<serde_json::Value> {\n match params? {\n RawJsonRpcParams::Object(map) => Some(serde_json::Value::Object(map.clone())),\n RawJsonRpcParams::Array(values) => Some(serde_json::Value::Array(values.clone())),\n }\n}\n\n/// A response's success payload, if it succeeded.\nfn response_value(\n response: &agent_client_protocol::RpcResponse<serde_json::Value>,\n) -> Option<serde_json::Value> {\n serde_json::to_value(response).ok()?.get(\"result\").cloned()\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/fold.rs (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Let me fix a couple of rough edges and verify the shapes I guessed at:",
@@ -1704,7 +1281,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01RiE5apYRropfoqsYGHabpw",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1719,21 +1298,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("F=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1; sed -n '444,465p' $F/tool_call.rs; echo \"=== Response struct ===\"; grep -rn \"pub struct Response\" -A 22 $F/rpc.rs 2>/dev/null | grep -v \"///\" | head -26; ls $F"),
- "description": String("Verify ToolKind variants and Response shape"),
- },
- ),
- raw_output: Some(
- String(" /// Internal reasoning or planning.\n Think,\n /// Retrieving external data.\n Fetch,\n /// Switching the current session mode.\n SwitchMode,\n /// Other tool types (default).\n #[default]\n #[serde(other)]\n Other,\n}\n\nimpl ToolKind {\n #[expect(clippy::trivially_copy_pass_by_ref, reason = \"Required by serde\")]\n fn is_default(&self) -> bool {\n matches!(self, ToolKind::Other)\n }\n}\n\n/// Execution status of a tool call.\n///\n/// Tool calls progress through different statuses during their lifecycle.\n=== Response struct ===\nagent.rs\nclient.rs\ncontent.rs\nelicitation.rs\nerror.rs\next.rs\nmcp.rs\nmod.rs\nnes.rs\nplan.rs\nprotocol_level.rs\ntool_call.rs"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01TjvXdjMBemxw37v82KJVt3",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1748,21 +1320,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; sed -n '1,12p' $D/src/jsonrpc.rs; echo \"=== Response def ===\"; grep -rn \"pub struct Response\" -A 20 ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/rpc.rs | grep -v \"^\\s*[0-9-]*\\s*///\" | head -26"),
- "description": String("Find Response struct definition"),
- },
- ),
- raw_output: Some(
- String("//! Core JSON-RPC server support.\n\nuse agent_client_protocol_schema::v1::{\n JsonRpcMessage as VersionedJsonRpcMessage, Notification as RpcNotification,\n Request as RpcRequest, RequestId, Response as RpcResponse, SessionId,\n};\n\n// Types re-exported from crate root\nuse serde::{Deserialize, Serialize};\nuse std::any::TypeId;\nuse std::collections::HashMap;\nuse std::fmt::Debug;\n=== Response def ==="),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01SAzhLQbhr3L7S1KFUxohSa",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1777,21 +1342,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("S=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src; grep -rn \"pub struct Response<\" -A 24 $S/ | grep -v \"^\\S*[0-9-]*\\s*///\" | head -30"),
- "description": String("Locate generic Response struct"),
- },
- ),
- raw_output: Some(
- String("(Bash completed with no output)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Gk2jb4SFVnZqJhybpX3pb3",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1806,21 +1364,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("S=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src; grep -rn \"struct Response\\|enum Response\" $S/ | head; echo \"--- rpc.rs pub items ---\"; grep -n \"^pub \\|^ pub \" $S/rpc.rs | head -30"),
- "description": String("Find Response in schema crate"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/rpc.rs:77:pub enum Response<Result, Error> {\n--- rpc.rs pub items ---\n42:pub enum RequestId {\n60:pub struct Request<Params> {\n62: pub id: RequestId,\n64: pub method: Arc<str>,\n66: pub params: Option<Params>,\n77:pub enum Response<Result, Error> {\n97: pub fn new(id: impl Into<RequestId>, result: std::result::Result<R, E>) -> Self {\n119:pub struct Notification<Params> {\n121: pub method: Arc<str>,\n123: pub params: Option<Params>,\n139:pub struct JsonRpcMessage<M> {\n148: pub fn wrap(message: M) -> Self {\n157: pub fn inner(&self) -> &M {\n163: pub fn into_inner(self) -> M {\n172:pub struct EmptyJsonRpcBatch;\n184:pub struct JsonRpcBatch<M>(#[schemars(length(min = 1))] Vec<JsonRpcMessage<M>>);\n195: pub fn new(messages: Vec<JsonRpcMessage<M>>) -> Result<Self, EmptyJsonRpcBatch> {\n205: pub fn as_slice(&self) -> &[JsonRpcMessage<M>] {\n211: pub fn into_vec(self) -> Vec<JsonRpcMessage<M>> {"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_014cLczzExDZjr3nu7kw2PFH",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1835,21 +1386,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("sed -n '70,100p' ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/rpc.rs"),
- "description": String("Read Response enum variants"),
- },
- ),
- raw_output: Some(
- String("#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]\n#[allow(\n clippy::exhaustive_enums,\n reason = \"This comes from the JSON-RPC specification itself\"\n)]\n#[serde(untagged)]\n#[schemars(rename = \"{Result}\", extend(\"x-docs-ignore\" = true))]\npub enum Response<Result, Error> {\n /// A successful JSON-RPC response.\n Result {\n /// The id of the request this response answers.\n id: RequestId,\n /// Method-specific response data.\n result: Result,\n },\n /// A failed JSON-RPC response.\n Error {\n /// The id of the request this response answers.\n id: RequestId,\n /// Method-specific error data.\n error: Error,\n },\n}\n\nimpl<R, E> Response<R, E> {\n /// Creates a JSON-RPC response from a Rust [`Result`].\n #[must_use]\n pub fn new(id: impl Into<RequestId>, result: std::result::Result<R, E>) -> Self {\n match result {\n Ok(result) => Self::Result {\n id: id.into(),"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01YWP9Mr3s51smkm2PZKJvFz",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1864,21 +1408,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; grep -rn \"RpcResponse\" $D/src/jsonrpc.rs | head -8; echo \"=== alias? ===\"; grep -rn \"type RpcResponse\\|Response as RpcResponse\" $D/src/*.rs; echo \"=== v1 alias ===\"; grep -rn \"pub type Response\\|Response<\" ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/mod.rs | head"),
- "description": String("Resolve RpcResponse alias"),
- },
- ),
- raw_output: Some(
- String("/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:5: Request as RpcRequest, RequestId, Response as RpcResponse, SessionId,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:61: Response(RpcResponse<serde_json::Value>),\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:152: Self::Response(RpcResponse::new(id, response))\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:159: Self::Response(RpcResponse::Result { id, .. } | RpcResponse::Error { id, .. }) => {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:210: VersionedJsonRpcMessage<RpcResponse<serde_json::Value>>,\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:2576:pub struct Responder<T: JsonRpcResponse = serde_json::Value> {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:2593:impl<T: JsonRpcResponse> std::fmt::Debug for Responder<T> {\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:2636: pub fn cast<T: JsonRpcResponse>(self) -> Responder<T> {\n=== alias? ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0/src/jsonrpc.rs:5: Request as RpcRequest, RequestId, Response as RpcResponse, SessionId,\n=== v1 alias ===\n/Users/eric/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/mod.rs:37:pub type Response<Result> = crate::rpc::Response<Result, Error>;"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Sth7ajAnwikWsFGZUizoFU",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1893,15 +1430,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; sed -n '95,130p' $D/src/lib.rs"),
- "description": String("Read crate root re-exports"),
- },
- ),
- raw_output: Some(
- String("pub use capabilities::*;\n\npub use jsonrpc::{\n Builder, ByteStreams, Channel, ConnectionTo, Dispatch, HandleDispatchFrom, Handled,\n IntoHandled, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, Lines,\n NullHandler, RawJsonRpcMessage, RawJsonRpcParams, Responder, ResponseRouter, SentRequest,\n UntypedMessage,\n run::{ChainRun, NullRun, RunWithConnectionTo},\n};\npub use jsonrpc::{RequestCancellation, is_cancel_request_notification};\n\npub use role::{\n Role, RoleId, UntypedRole,\n acp::{Agent, Client, Conductor, Proxy},\n};\n\npub use component::{ConnectTo, DynConnectTo};\n\n// Re-export BoxFuture for implementing Component traits\npub use futures::future::BoxFuture;\n\n// Re-export commonly used infrastructure types for convenience\npub use schema::v1::{Error, ErrorCode, Result};\n\n// Re-export derive macros for custom JSON-RPC types\npub use agent_client_protocol_derive::{JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};\n\nmod session;\npub use session::*;\n\nmod acp_agent;\npub use acp_agent::{AcpAgent, LineDirection};\n\nmod stdio;\npub use stdio::Stdio;"),
- ),
},
Text {
text: "`RpcResponse` isn't re-exported at the root. Let me check what paths are reachable, then compile-iterate.",
@@ -1910,7 +1438,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_016TzwRDT93LPFd2WmByWsgx",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -1925,15 +1455,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("D=~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-1.2.0; grep -n \"^pub mod\\|^mod \\|pub use schema\" $D/src/lib.rs | head -20; echo \"=== v1 re-exports (session etc) ===\"; grep -n \"pub use\" ~/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/agent-client-protocol-schema-1.4.0/src/v1/mod.rs | head"),
- "description": String("Check module visibility in ACP crate"),
- },
- ),
- raw_output: Some(
- String("79:mod capabilities;\n81:pub mod component;\n83:pub mod concepts;\n85:mod jsonrpc;\n87:pub mod mcp_server;\n89:pub mod role;\n91:pub mod schema;\n93:pub mod util;\n117:pub use schema::v1::{Error, ErrorCode, Result};\n122:mod session;\n125:mod acp_agent;\n128:mod stdio;\n=== v1 re-exports (session etc) ===\n18:pub use crate::rpc::{JsonRpcBatch, JsonRpcMessage, Notification, Request, RequestId};\n19:pub use agent::*;\n20:pub use client::*;\n21:pub use content::*;\n24:pub use elicitation::*;\n25:pub use error::*;\n26:pub use ext::*;\n28:pub use mcp::*;\n30:pub use nes::*;\n31:pub use plan::*;"),
- ),
},
Text {
text: "`pub mod schema` is reachable. Fixing the imports and response handling:",
@@ -1942,7 +1463,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01MQwo3p8Jbo1MvEZeLAreAh",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1955,23 +1478,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String("use agent_client_protocol::{\n ContentBlock, RawJsonRpcMessage, RawJsonRpcParams, RequestId, SessionNotification,\n SessionUpdate, ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,\n};\nuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};\nuse macro_user_id::user_id::MacroUserIdStr;\nuse non_empty::NonEmpty;\nuse std::collections::HashMap;"),
- "new_string": String("use agent_client_protocol::schema::v1::{\n ContentBlock, Meta, RequestId, Response, SessionNotification, SessionUpdate, ToolCall,\n ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,\n};\nuse agent_client_protocol::{RawJsonRpcMessage, RawJsonRpcParams};\nuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};\nuse macro_user_id::user_id::MacroUserIdStr;\nuse non_empty::NonEmpty;\nuse std::collections::HashMap;\nuse std::path::PathBuf;"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01KitVhUe1VzMioHL1HS4cdz",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -1984,23 +1498,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" // The user's answer to a permission request.\n RawJsonRpcMessage::Response(response) => {\n state.resolve_permission(&response.id, response_value(response));\n }"),
- "new_string": String(" // The user's answer to a permission request.\n RawJsonRpcMessage::Response(Response::Result { id, result }) => {\n state.resolve_permission(id, Some(result));\n }\n RawJsonRpcMessage::Response(Response::Error { id, .. }) => {\n state.resolve_permission(id, None);\n }"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01UX6CxpBaaAJDqqQXKTQYda",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2013,23 +1518,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" // The response to `session/prompt` closes the turn.\n RawJsonRpcMessage::Response(response) => {\n state.end_turn(&response.id, response_value(response));\n }"),
- "new_string": String(" // The response to `session/prompt` closes the turn.\n RawJsonRpcMessage::Response(Response::Result { id, result }) => {\n state.end_turn(id, Some(result));\n }\n RawJsonRpcMessage::Response(Response::Error { id, .. }) => {\n state.end_turn(id, None);\n }"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_015i8GDcUt9U8v4guH7kK4de",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2042,23 +1538,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" fn end_turn(&mut self, response_id: &RequestId, value: Option<serde_json::Value>) {"),
- "new_string": String(" fn end_turn(&mut self, response_id: &RequestId, value: Option<&serde_json::Value>) {"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LgYVEM887shZWUC221pENP",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2071,23 +1558,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" if !is_current_turn {\n // Responses to `initialize`, `session/new` and `session/load`\n // land here. Only flag one that looks like a turn ending.\n if value\n .as_ref()\n .is_some_and(|value| value.get(\"stopReason\").is_some())\n {\n self.anomalies.push(Anomaly::UncorrelatedResponse);\n }\n return;\n }\n\n let stop = value\n .as_ref()\n .and_then(|value| value.get(\"stopReason\"))\n .and_then(|reason| reason.as_str())\n .map(stop_reason);"),
- "new_string": String(" if !is_current_turn {\n // Responses to `initialize`, `session/new` and `session/load`\n // land here. Only flag one that looks like a turn ending.\n if value.is_some_and(|value| value.get(\"stopReason\").is_some()) {\n self.anomalies.push(Anomaly::UncorrelatedResponse);\n }\n return;\n }\n\n let stop = value\n .and_then(|value| value.get(\"stopReason\"))\n .and_then(|reason| reason.as_str())\n .map(stop_reason);"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01YWuFhjpoU6xBVApLNMGNrR",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2100,17 +1578,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" fn resolve_permission(&mut self, response_id: &RequestId, value: Option<serde_json::Value>) {\n let Some(tool_call) = self.pending_permissions.remove(response_id) else {\n return;\n };\n\n // `{\"outcome\": {\"outcome\": \"selected\", \"optionId\": \"...\"}}`\n let outcome = value\n .as_ref()\n .and_then(|value| value.get(\"outcome\"))"),
- "new_string": String(" fn resolve_permission(&mut self, response_id: &RequestId, value: Option<&serde_json::Value>) {\n let Some(tool_call) = self.pending_permissions.remove(response_id) else {\n return;\n };\n\n // `{\"outcome\": {\"outcome\": \"selected\", \"optionId\": \"...\"}}`\n let outcome = value\n .and_then(|value| value.get(\"outcome\"))"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the remaining rough edges — the `Box` slip, the path alias, and the dead helper:",
@@ -2119,7 +1586,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_012kkzYC8t6uTYrmkUZTNQMA",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2132,23 +1601,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" SessionUpdate::ToolCall(call) => self.open_tool_call(*Box::new(call)),"),
- "new_string": String(" SessionUpdate::ToolCall(call) => self.open_tool_call(call),"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01TRWwTP4i26fJYCohQUFEeP",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2161,23 +1621,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String("/// The paths a read tool was pointed at.\nfn read_paths(raw_input: Option<&serde_json::Value>) -> Vec<PathBufList> {\n raw_input\n .and_then(|input| input.get(\"file_path\"))\n .and_then(|path| path.as_str())\n .map(|path| vec![std::path::PathBuf::from(path)])\n .unwrap_or_default()\n}\n\n/// Alias kept local so the signature above reads as a list of paths.\ntype PathBufList = std::path::PathBuf;"),
- "new_string": String("/// The paths a read tool was pointed at.\nfn read_paths(raw_input: Option<&serde_json::Value>) -> Vec<PathBuf> {\n raw_input\n .and_then(|input| input.get(\"file_path\"))\n .and_then(|path| path.as_str())\n .map(|path| vec![PathBuf::from(path)])\n .unwrap_or_default()\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Pv8aPePeM8Fcm4o2K63pJ6",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2190,23 +1641,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/fold.rs"),
- "old_string": String(" RawJsonRpcParams::Array(values) => Some(serde_json::Value::Array(values.clone())),\n }\n}\n\n/// A response's success payload, if it succeeded.\nfn response_value(\n response: &agent_client_protocol::RpcResponse<serde_json::Value>,\n) -> Option<serde_json::Value> {\n serde_json::to_value(response).ok()?.get(\"result\").cloned()\n}"),
- "new_string": String(" RawJsonRpcParams::Array(values) => Some(serde_json::Value::Array(values.clone())),\n }\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01UuQP3vFtHykhVVEW1UNdnz",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Failed,
detail: Terminal {
command: Some(
@@ -2221,21 +1663,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
1,
),
},
- raw_input: Some(
- Object {
- "command": String("sed -i '' 's|meta: Option<&agent_client_protocol::Meta>|meta: Option<\\&Meta>|g' crates/agent_fold/src/fold.rs && grep -n \"Option<&Meta>\" crates/agent_fold/src/fold.rs"),
- "description": String("Fix Meta paths in fold.rs"),
- },
- ),
- raw_output: Some(
- String("Exit code 2\nsed: can't read s|meta: Option<&agent_client_protocol::Meta>|meta: Option<\\&Meta>|g: No such file or directory"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Weisa7bDsWPF7ZnTtdXcdP",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2250,15 +1685,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("perl -pi -e 's/Option<&agent_client_protocol::Meta>/Option<&Meta>/g' crates/agent_fold/src/fold.rs && grep -n \"Option<&Meta>\" crates/agent_fold/src/fold.rs"),
- "description": String("Fix Meta paths with perl"),
- },
- ),
- raw_output: Some(
- String("544: meta: Option<&Meta>,\n571: meta: Option<&Meta>,"),
- ),
},
Text {
text: "Now `lib.rs` and the tests. First let me write a hermetic fixture covering the tricky cases:",
@@ -2267,7 +1693,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01VHjufyUubZ1jBhzQCnemLD",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Failed,
detail: Edit {
diffs: [
@@ -2278,41 +1706,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/lib.rs"),
- "content": String("#![deny(missing_docs)]\n//! Folds an agent session's protocol log into renderable messages.\n//!\n//! An agent session is recorded as a flat log of Agent Runtime Protocol\n//! frames - see `agent_session_log` and\n//! [`agent_runtime_protocol::domain::schema::v0`]. That log is faithful but\n//! unreadable: a single session is hundreds of streamed chunks, tool-call\n//! patches and token-usage reports. This crate collapses it into the handful\n//! of messages a person would recognize as the story of the session.\n//!\n//! Nothing here is persisted. [`fold`] is a pure function from log to\n//! messages, so its output vocabulary can change without a migration - the\n//! messages are re-derived on every read.\n//!\n//! ```no_run\n//! use agent_fold::{fold, LogEntry};\n//!\n//! # fn run(log: Vec<LogEntry>) {\n//! let folded = fold(log);\n//! for message in &folded.messages {\n//! println!(\"{:?} said {} part(s)\", message.author, message.parts.len());\n//! }\n//! # }\n//! ```\n\n/// Collapsing a protocol log into messages.\npub mod fold;\n/// Harness-specific `_meta` extraction.\npub mod meta;\n/// The renderable message vocabulary.\npub mod message;\n\npub use fold::{Anomaly, Fold, LogEntry, LogMessage, fold};\npub use message::{\n AnsiText, Author, FileDiff, FoldedMessage, MessagePart, Permission, PermissionOption,\n PermissionOutcome, StopReason, ToolDetail, ToolStatus, ToolUse, ToolUseId, TurnId,\n};\n"),
- },
- ),
- raw_output: Some(
- String("<tool_use_error>File has not been read yet. Read it first before writing to it.</tool_use_error>"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018wDJSEfs9FyqEeHi1HNdHD",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_fold/src/lib.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/lib.rs"),
- },
- ),
- raw_output: Some(
- String("1\tmod domain;\n2\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_014w6RmXtn2vVEJPA6ZMiwA1",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2323,15 +1738,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/lib.rs"),
- "content": String("#![deny(missing_docs)]\n//! Folds an agent session's protocol log into renderable messages.\n//!\n//! An agent session is recorded as a flat log of Agent Runtime Protocol\n//! frames - see `agent_session_log` and\n//! [`agent_runtime_protocol::domain::schema::v0`]. That log is faithful but\n//! unreadable: a single session is hundreds of streamed chunks, tool-call\n//! patches and token-usage reports. This crate collapses it into the handful\n//! of messages a person would recognize as the story of the session.\n//!\n//! Nothing here is persisted. [`fold`] is a pure function from log to\n//! messages, so its output vocabulary can change without a migration - the\n//! messages are re-derived on every read.\n//!\n//! ```no_run\n//! use agent_fold::{LogEntry, fold};\n//!\n//! # fn run(log: Vec<LogEntry>) {\n//! let folded = fold(log);\n//! for message in &folded.messages {\n//! println!(\"{:?} said {} part(s)\", message.author, message.parts.len());\n//! }\n//! # }\n//! ```\n\n/// Collapsing a protocol log into messages.\npub mod fold;\n/// Harness-specific `_meta` extraction.\npub mod meta;\n/// The renderable message vocabulary.\npub mod message;\n\npub use fold::{Anomaly, Fold, LogEntry, LogMessage, fold};\npub use message::{\n AnsiText, Author, FileDiff, FoldedMessage, MessagePart, Permission, PermissionOption,\n PermissionOutcome, StopReason, ToolDetail, ToolStatus, ToolUse, ToolUseId, TurnId,\n};\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/lib.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now remove the stubs the new design replaces:",
@@ -2340,7 +1746,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_0171Un3aQHfB4AdqNNLq53zR",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2355,15 +1763,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd /Users/eric/Code/macro/crates/agent_fold && rm -rf src/domain src/inbound && find . -type f | sort"),
- "description": String("Remove hex stubs, list remaining files"),
- },
- ),
- raw_output: Some(
- String("./Cargo.toml\n./src/fold.rs\n./src/lib.rs\n./src/message.rs\n./src/meta.rs"),
- ),
},
Text {
text: "Now the tests. A hermetic fixture that encodes the tricky cases the recordings revealed, plus an opt-in replay of the real recordings:",
@@ -2372,7 +1771,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01GNJ1dqehPY33GVVnwhNGr4",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2383,21 +1784,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/fixtures/turn.jsonl"),
- "content": String("{\"direction\":\"to_server\",\"content\":{\"type\":\"event\",\"event\":\"acp_ready\"}}\n{\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"init-1\",\"method\":\"initialize\",\"params\":{\"protocolVersion\":1}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"init-1\",\"result\":{\"protocolVersion\":1,\"agentCapabilities\":{}}}}\n{\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"prompt-1\",\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s1\",\"prompt\":[{\"type\":\"text\",\"text\":\"list the examples and write a file\"}]}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"Sure, \"}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"one moment.\"}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"usage_update\",\"usage\":{\"inputTokens\":10,\"outputTokens\":2}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"tool_call\",\"toolCallId\":\"tc-run\",\"kind\":\"execute\",\"status\":\"pending\",\"title\":\"ls examples\",\"rawInput\":{\"command\":\"ls examples\"},\"content\":[{\"type\":\"terminal\",\"terminalId\":\"tc-run\"}],\"_meta\":{\"claudeCode\":{\"toolName\":\"Bash\"}}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"perm-1\",\"method\":\"session/request_permission\",\"params\":{\"sessionId\":\"s1\",\"toolCall\":{\"toolCallId\":\"tc-run\"},\"options\":[{\"kind\":\"reject_once\",\"name\":\"Deny\",\"optionId\":\"reject\"},{\"kind\":\"allow_once\",\"name\":\"Allow Once\",\"optionId\":\"allow\"}]}}}\n{\"direction\":\"to_runtime\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"perm-1\",\"result\":{\"outcome\":{\"outcome\":\"selected\",\"optionId\":\"allow\"}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"tc-run\",\"_meta\":{\"terminal_output\":{\"terminal_id\":\"tc-run\",\"data\":\"\u{1b}[01;34macp.rs\u{1b}[0m\"}}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"tc-run\",\"status\":\"completed\",\"_meta\":{\"terminal_output\":{\"terminal_id\":\"tc-run\",\"data\":\"\u{1b}[01;34macp.rs\u{1b}[0m\\nevents.rs\"},\"terminal_exit\":{\"terminal_id\":\"tc-run\",\"exit_code\":0}}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"tool_call\",\"toolCallId\":\"tc-write\",\"kind\":\"edit\",\"status\":\"pending\",\"title\":\"Write\",\"rawInput\":{},\"content\":[],\"locations\":[],\"_meta\":{\"claudeCode\":{\"toolName\":\"Write\"}}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"tc-write\",\"status\":\"completed\",\"content\":[{\"type\":\"diff\",\"path\":\"/repo/new.rs\",\"oldText\":null,\"newText\":\"fn main() {}\"}]}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"method\":\"session/update\",\"params\":{\"sessionId\":\"s1\",\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"Done.\"}}}}}\n{\"direction\":\"to_server\",\"content\":{\"type\":\"acp\",\"jsonrpc\":\"2.0\",\"id\":\"prompt-1\",\"result\":{\"stopReason\":\"end_turn\",\"usage\":{\"inputTokens\":10,\"outputTokens\":8}}}}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/fixtures/turn.jsonl (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01KKDkPymKKwqZRd1qmfEHEk",
),
- label: "Skill",
+ name: Native {
+ name: "Skill",
+ },
status: Completed,
detail: Other {
kind: "other",
@@ -2410,20 +1804,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
),
},
- raw_input: Some(
- Object {
- "skill": String("cloud-storage-hexagonal-architecture"),
- },
- ),
- raw_output: Some(
- String("Launching skill: cloud-storage-hexagonal-architecture"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01RsHdoDUdYXHPLfCa3DpmmP",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2438,21 +1826,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat crates/agent_session/src/domain/ports.rs; echo \"===== error =====\"; cat crates/agent_session/src/domain/error.rs; echo \"===== lib/mod =====\"; cat crates/agent_session/src/lib.rs crates/agent_session/src/domain/mod.rs crates/agent_session/src/outbound/mod.rs"),
- "description": String("Read agent_session hex conventions"),
- },
- ),
- raw_output: Some(
- String("use super::error::Result;\nuse super::model::*;\n\npub trait AgentSessionRepo {\n /// Create a new agent session, returning its id.\n fn create(\n &self,\n session: AgentSession<UninitializedSession>,\n ) -> impl Future<Output = Result<AgentSessionId>>;\n\n /// Get an agent session by id.\n fn get(&self, id: AgentSessionId)\n -> impl Future<Output = Result<AgentSession<AgentSessionId>>>;\n\n /// Update an existing agent session.\n fn update(&self, session: AgentSession<AgentSessionId>) -> impl Future<Output = Result<()>>;\n\n /// Delete an agent session by id.\n fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>>;\n}\n\npub trait AgentSessionLogRepo {\n /// Append a new log entry to a session's history.\n fn create(&self, log: AgentSessionLog) -> impl Future<Output = Result<()>>;\n\n /// List all log entries for a session, in chronological order.\n fn list_by_session(\n &self,\n agent_session_id: AgentSessionId,\n ) -> impl Future<Output = Result<Vec<AgentSessionLog>>>;\n}\n===== error =====\nuse thiserror::Error;\npub type Result<T, E = AgentSessionError> = std::result::Result<T, E>;\n\n#[derive(Error, Debug)]\npub enum AgentSessionError {\n #[error(\"{0}\")]\n Unknown(#[from] anyhow::Error),\n}\n===== lib/mod =====\npub mod domain;\npub mod outbound;\npub mod error;\npub mod model;\npub mod ports;\n//! Adapters implementing the domain ports for external systems.\n\npub mod postgres;"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Qz45eqP4VcGMTWfeATHyda",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2467,21 +1848,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n \"CS-46\" -A 25 docs/STYLE_GUIDE.md | head -45; echo \"=== rootcause users ===\"; grep -rln \"rootcause\" crates/*/Cargo.toml | head -5"),
- "description": String("Read CS-46 rootcause guidance"),
- },
- ),
- raw_output: Some(
- String("133:- **CS-46** `[rust]` Use `rootcause` for error handling in new code — it's preferred\n134- over `anyhow` these days. In code that's still on anyhow, prefer `bail!` for early\n135- error returns. (also: CLAUDE.md)\n136-- **CS-47** `[perf]` Keep latency-critical services thin: push bytes directly instead of\n137- round-tripping through presigned URLs or extra services; dispatch non-blocking\n138- background work with `wait_until`. (#3781)\n139-- **CS-48** `[perf]` Don't do per-message work on hot websocket paths — accumulate and\n140- flush on a timer/alarm. (#3961)\n141-- **CS-49** `[test]` Tests live in a sibling `test.rs`, not inline `#[cfg(test)]` blocks\n142- in the implementation file. (#4647 · also: CLAUDE.md)\n143-- **CS-50** `[test]` Update tests and run `just prepare_db` with any db-crate change.\n144- (also: CLAUDE.md)\n145-\n146-## Frontend and shared TypeScript (`apps/web`, `packages/`)\n147-\n148-- **FE-01** `[data]` Never call a service client outside the `queries` package — UI code\n149- calling an endpoint directly is usually re-fetching data an existing query already\n150- caches. (#3750, #3961 · also: AGENTS.md)\n151-- **FE-02** `[data]` Every query module has a `keys.ts` structured like the existing\n152- ones. (#3710)\n153-- **FE-03** `[data]` Conditional fetching uses a debounced signal passed to TanStack\n154- Query's `enabled`, not a custom resource. (#3961)\n155-- **FE-04** `[data]` Pre-populating data means exposing a cache-seeding method on the\n156- query, not an ad hoc manual cache. (#4020)\n157-- **FE-05** `[data]` Data-dependent UI that must not suspend uses `queryReadyGate`.\n158- (#4077)\n=== rootcause users ===\ncrates/ai_tools/Cargo.toml\ncrates/ai_projections/Cargo.toml\ncrates/cal/Cargo.toml\ncrates/bots/Cargo.toml\ncrates/channels/Cargo.toml"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_0118qP7HovvgD4BkeFY1BMn8",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2496,21 +1870,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn \"rootcause\" crates/bots/src/domain/*.rs | head -8; echo \"=== bots error style ===\"; sed -n '1,40p' crates/bots/src/domain/error.rs 2>/dev/null || find crates/bots/src -name \"*.rs\" | head"),
- "description": String("See rootcause usage in bots domain"),
- },
- ),
- raw_output: Some(
- String("=== bots error style ===\ncrates/bots/src/lib.rs\ncrates/bots/src/inbound/axum_router.rs\ncrates/bots/src/inbound/mod.rs\ncrates/bots/src/inbound/channel_webhook_router.rs\ncrates/bots/src/outbound/mod.rs\ncrates/bots/src/outbound/pg_bots_repo.rs\ncrates/bots/src/domain/tokens.rs\ncrates/bots/src/domain/events.rs\ncrates/bots/src/domain/ports.rs\ncrates/bots/src/domain/models.rs"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01R4QYGgJfpQiQS1VxqWjDZ9",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2525,21 +1892,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn \"rootcause\" crates/bots/src/domain/ports.rs crates/bots/src/domain/models.rs | head -6; echo \"===\"; grep -rn \"Report\\|rootcause\" crates/channels/src/domain/ports.rs | head -8; grep -n \"enum ChannelsError\\|#\\[error\" -A 2 crates/channels/src/domain/models.rs | head -20"),
- "description": String("Check rootcause in ports/errors"),
- },
- ),
- raw_output: Some(
- String("===\ncrates/channels/src/domain/ports.rs:42: ) -> impl Future<Output = Result<Vec<ChannelWithParticipants>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:48: ) -> impl Future<Output = Result<HashMap<Uuid, LatestMessage>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:54: ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:60: ) -> impl Future<Output = Result<Vec<ChannelMessage>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:70: ) -> impl Future<Output = Result<Vec<UserName>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:80: ) -> impl Future<Output = Result<Vec<ChannelWithLatest>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:86: ) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send;\ncrates/channels/src/domain/ports.rs:92: ) -> impl Future<Output = Result<Vec<ChannelMessage>, rootcause::Report>> + Send;"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_017VydSZzYozARKNeGLFrLL4",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2554,21 +1914,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n \"rootcause\" Cargo.toml | head -3; grep -n \"impl ChannelsRepo\\|async fn list_channels\\|Report\" -A 6 crates/channels/src/outbound/pg_channels_repo.rs | head -30; echo \"=== service impl style ===\"; ls crates/channels/src/domain/; grep -rn \"tracing::instrument\" crates/channels/src/domain/*.rs | head -4"),
- "description": String("Check rootcause construction and service style"),
- },
- ),
- raw_output: Some(
- String("217:rootcause = { version = \"0.12\" }\n218:rootcause-tracing = \"0.12.1\"\n1174: ) -> Result<Vec<ChannelWithParticipants>, rootcause::Report> {\n1175- let user_id = params.user();\n1176- let query_limit = params.limit().map(i64::from);\n1177- let cursor = params.query();\n1178- let sort_method_str = cursor.sort_method().to_string();\n1179- let (cursor_id, cursor_timestamp) = cursor.vals();\n1180- let cursor_id_str = cursor_id.as_ref().map(|u| u.to_string());\n--\n1212: ) -> Result<HashMap<Uuid, LatestMessage>, rootcause::Report> {\n1213- if channel_ids.is_empty() {\n1214- return Ok(HashMap::new());\n1215- }\n1216-\n1217- let rows = sqlx::query!(\n1218- r#\"\n--\n1364: ) -> Result<Vec<Activity>, rootcause::Report> {\n1365- Ok(sqlx::query!(\n1366- r#\"\n1367- SELECT\n1368- a.id as \"id!: Uuid\",\n1369- a.user_id as \"user_id!: String\",\n1370- a.channel_id as \"channel_id!: Uuid\",\n--\n1403: ) -> Result<Vec<ChannelMessage>, rootcause::Report> {\n1404- use bot_id::BotIdStr;\n1405-\n1406- let parents: Vec<TopLevelMessageRow> = build_channel_thread_rows_query(&params)\n1407- .build()\n1408- .try_map(|row: PgRow| {\n=== service impl style ===\n\u{1b}[0m\u{1b}[01;34mbroker_events\u{1b}[0m\nbroker_events.rs\nentity_mutation.rs\nevents.rs\n\u{1b}[01;34mlist_service\u{1b}[0m\nlist_service.rs\n\u{1b}[01;34mmention_events\u{1b}[0m\nmention_events.rs\nmod.rs\nmodels.rs\nports.rs\n\u{1b}[01;34mservice\u{1b}[0m\nservice.rs\n\u{1b}[01;34mside_effects\u{1b}[0m\nside_effects.rs\ncrates/channels/src/domain/list_service.rs:65: #[tracing::instrument(err, skip(self))]\ncrates/channels/src/domain/service.rs:327: #[tracing::instrument(err, skip(self, req))]\ncrates/channels/src/domain/service.rs:389: #[tracing::instrument(err, skip(self, recipient_id))]\ncrates/channels/src/domain/service.rs:424: #[tracing::instrument(err, skip(self, req))]"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_013P87uybRY1M6bmfZLgdixN",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2583,21 +1936,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -rn \"rootcause::\\(bail\\|report\\)\\|\\.attach\\|IntoReport\\|report!\\|Report::\" crates/channels/src/outbound/pg_channels_repo.rs crates/channels/src/domain/service.rs | head -8; echo \"=== how sqlx errors become Report ===\"; grep -n \"await?\" crates/channels/src/outbound/pg_channels_repo.rs | head -3; sed -n '60,80p' crates/channels/src/domain/list_service.rs"),
- "description": String("Check Report construction idioms"),
- },
- ),
- raw_output: Some(
- String("crates/channels/src/domain/service.rs:623: let items = extract_share_items(&req.attachments, &req.mentions);\ncrates/channels/src/domain/service.rs:668: let has_attachments = !req.attachments.is_empty();\ncrates/channels/src/domain/service.rs:671: .add_attachments(message.id, channel_id, req.attachments.clone())\ncrates/channels/src/outbound/pg_channels_repo.rs:1432: .map_err(|error| rootcause::report!(error))?;\ncrates/channels/src/outbound/pg_channels_repo.rs:1460: let reactions = reactions.map_err(|error| rootcause::report!(error))?;\ncrates/channels/src/outbound/pg_channels_repo.rs:1461: let attachments = attachments.map_err(|error| rootcause::report!(error))?;\ncrates/channels/src/outbound/pg_channels_repo.rs:1462: let bot_profiles = bot_profiles.map_err(|error| rootcause::report!(error))?;\ncrates/channels/src/outbound/pg_channels_repo.rs:2400: AttachmentEntityReference::Channel(c) => c.attachment_created_at,\n=== how sqlx errors become Report ===\n358: .await?;\n428: .await?;\n448: .await?;\nwhere\n Channels: ChannelListRepo,\n Users: ChannelListUserRepo,\n Frec: AggregateFrecencyStorage,\n{\n #[tracing::instrument(err, skip(self))]\n async fn get_channels(\n &self,\n req: GetChannelsRequest,\n ) -> Result<Vec<ChannelWithLatest>, rootcause::Report> {\n let include_frecency = req.include_frecency;\n let params = req.into_params();\n let user = params.user().clone();\n\n let channels = self\n .channels\n .get_user_channels_with_participants(params)\n .await?;\n\n let channel_entities: Vec<_> = channels\n .iter()"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01FE69AgtngAnUCmqgxnr5bP",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2612,21 +1958,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd crates/agent_fold && mkdir -p src/domain src/outbound && mv src/meta.rs src/domain/meta.rs && mv src/meta src/domain/meta && ls -R src"),
- "description": String("Move meta module into domain"),
- },
- ),
- raw_output: Some(
- String("src:\n\u{1b}[0m\u{1b}[01;34mdomain\u{1b}[0m\n\u{1b}[01;34mfold\u{1b}[0m\nfold.rs\nlib.rs\nmessage.rs\n\u{1b}[01;34moutbound\u{1b}[0m\n\nsrc/domain:\n\u{1b}[01;34mmeta\u{1b}[0m\nmeta.rs\n\nsrc/domain/meta:\ntest.rs\n\nsrc/fold:\ntest.rs\n\nsrc/outbound:"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01XWbArSuRgoMnLaePyVtkWb",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -2641,15 +1980,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("mv src/message.rs src/domain/message.rs && mv src/fold.rs src/domain/fold.rs && mv src/fold src/domain/fold && ls -R src"),
- "description": String("Move message and fold into domain"),
- },
- ),
- raw_output: Some(
- String("src:\n\u{1b}[0m\u{1b}[01;34mdomain\u{1b}[0m\nlib.rs\n\u{1b}[01;34moutbound\u{1b}[0m\n\nsrc/domain:\n\u{1b}[01;34mfold\u{1b}[0m\nfold.rs\nmessage.rs\n\u{1b}[01;34mmeta\u{1b}[0m\nmeta.rs\n\nsrc/domain/fold:\ntest.rs\n\nsrc/domain/meta:\ntest.rs\n\nsrc/outbound:"),
- ),
},
Text {
text: "Now update `Cargo.toml`, then the moved files:",
@@ -2658,7 +1988,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01NYowSTpdShAk3oAqyK6dTv",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2671,44 +2003,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/Cargo.toml"),
- "old_string": String("[dependencies]\nagent-client-protocol = { workspace = true }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nmacro_user_id = { path = \"../macro_user_id\" }\nnon_empty = { path = \"../non_empty\" }\nserde_json = { workspace = true }"),
- "new_string": String("[dependencies]\nagent-client-protocol = { workspace = true }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nagent_session = { path = \"../agent_session\" }\nmacro_user_id = { path = \"../macro_user_id\" }\nnon_empty = { path = \"../non_empty\" }\nrootcause = { workspace = true }\nserde_json = { workspace = true }\ntracing = { workspace = true }\n\n[dev-dependencies]\nmacro_uuid = { path = \"../macro_uuid\" }\ntokio = { workspace = true, features = [\"macros\", \"rt-multi-thread\"] }"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/Cargo.toml has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LbUahv1rowfscwRgxRcjtE",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs"),
- "limit": Number(175),
- },
- ),
- raw_output: Some(
- String("1\t//! Collapsing a session's protocol log into renderable messages.\n2\t//!\n3\t//! # Why this cannot fail\n4\t//!\n5\t//! [`fold`] is total. Messages are derived on every read, so returning an\n6\t//! error would mean rendering an empty channel - strictly worse than rendering\n7\t//! a partially-understood session. Every case that looks like a failure is\n8\t//! instead a state worth showing:\n9\t//!\n10\t//! - A tool call with no result is in flight, or was interrupted when the\n11\t//! session died. Its status stays [`ToolStatus::Pending`].\n12\t//! - A tool call whose opening frame carried no useful fields gets them from\n13\t//! later patches. Until then it renders as a bare tool row.\n14\t//! - A permission request with no answer is outstanding.\n15\t//!\n16\t//! What is left over - a patch for a tool call that was never opened, an\n17\t//! update variant this fold does not model - is reported through\n18\t//! [`Fold::anomalies`] instead. That keeps the render path lenient while\n19\t//! letting tests be strict: a replay test asserts `anomalies.is_empty()`, so\n20\t//! protocol drift fails loudly in CI rather than silently degrading in\n21\t//! production.\n22\t//!\n23\t//! # Why one match rather than a registry\n24\t//!\n25\t//! Dispatch is a single explicit `match` over the protocol, in [`fold`] and\n26\t//! the handlers it calls. A registry of self-describing handlers would move\n27\t//! the decision of what matches what into data, where it is invisible; here\n28\t//! every frame this fold understands is named in one place you can read\n29\t//! top-to-bottom, and every frame it ignores is an explicit arm.\n30\t\n31\tuse crate::message::{\n32\t AnsiText, Author, FileDiff, FoldedMessage, MessagePart, Permission, PermissionOption,\n33\t PermissionOutcome, StopReason, ToolDetail, ToolStatus, ToolUse, ToolUseId, TurnId,\n34\t};\n35\tuse crate::meta::{claude_code, command_from_raw_input};\n36\tuse agent_client_protocol::schema::v1::{\n37\t ContentBlock, Meta, RequestId, Response, SessionNotification, SessionUpdate, ToolCall,\n38\t ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,\n39\t};\n40\tuse agent_client_protocol::{RawJsonRpcMessage, RawJsonRpcParams};\n41\tuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};\n42\tuse macro_user_id::user_id::MacroUserIdStr;\n43\tuse non_empty::NonEmpty;\n44\tuse std::collections::HashMap;\n45\tuse std::path::PathBuf;\n46\t\n47\t#[cfg(test)]\n48\tmod test;\n49\t\n50\t/// One row of a session's protocol log.\n51\t///\n52\t/// Mirrors `agent_session_log`, but is defined here so the fold depends only\n53\t/// on the protocol schema rather than on the crate that persists it.\n54\t#[derive(Debug, Clone)]\n55\tpub struct LogEntry {\n56\t /// Set when this frame is ACP traffic that originated from a user.\n57\t pub user_id: Option<MacroUserIdStr<'static>>,\n58\t /// The frame, in its original direction.\n59\t pub message: LogMessage,\n60\t}\n61\t\n62\t/// A logged frame, tagged with the direction it travelled.\n63\t#[derive(Debug, Clone)]\n64\tpub enum LogMessage {\n65\t /// Agent Runtime to Agent Service.\n66\t ToServer(ToServerMessage),\n67\t /// Agent Service to Agent Runtime.\n68\t ToRuntime(ToRuntimeMessage),\n69\t}\n70\t\n71\t/// The result of folding a log.\n72\t#[derive(Debug, Clone, Default)]\n73\tpub struct Fold {\n74\t /// Renderable messages, in log order.\n75\t pub messages: Vec<FoldedMessage>,\n76\t /// Frames the fold could not place. Not failures - see the module docs.\n77\t pub anomalies: Vec<Anomaly>,\n78\t}\n79\t\n80\t/// Something in the log the fold could not account for.\n81\t#[derive(Debug, Clone, PartialEq, Eq)]\n82\tpub enum Anomaly {\n83\t /// A `tool_call_update` arrived for an id no `tool_call` had opened.\n84\t ///\n85\t /// Unobserved in practice: log rows are ordered by `created_at` then by a\n86\t /// v7 uuid, which is itself time-ordered, so frames cannot be reordered.\n87\t /// It is still reachable through `session/load`, where a resumed session's\n88\t /// log legitimately begins mid-stream.\n89\t PatchBeforeOpen {\n90\t /// The unopened tool call.\n91\t tool_call: ToolUseId,\n92\t },\n93\t /// A `session/update` whose variant this fold does not model.\n94\t UnmodelledSessionUpdate {\n95\t /// The variant's wire name, when it could be read.\n96\t kind: String,\n97\t },\n98\t /// A `session/update` frame whose params would not deserialize.\n99\t UndecodableSessionUpdate,\n100\t /// A response arrived for a request id the fold was not tracking.\n101\t UncorrelatedResponse,\n102\t}\n103\t\n104\t/// Collapse a session's protocol log into renderable messages.\n105\t///\n106\t/// Total by construction: unrecognized and incomplete frames land in\n107\t/// [`Fold::anomalies`] rather than aborting the fold. See the module docs for\n108\t/// why.\n109\t#[must_use]\n110\tpub fn fold(log: impl IntoIterator<Item = LogEntry>) -> Fold {\n111\t let mut state = State::default();\n112\t\n113\t for entry in log {\n114\t // The one place the protocol is dispatched. Each arm names a frame\n115\t // this fold understands; the rest are ignored on purpose.\n116\t match &entry.message {\n117\t LogMessage::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {\n118\t // A user's prompt opens a turn.\n119\t RawJsonRpcMessage::Request(request) if &*request.method == \"session/prompt\" => {\n120\t state.begin_turn(\n121\t &request.id,\n122\t params_value(request.params.as_ref()),\n123\t entry.user_id,\n124\t );\n125\t }\n126\t // The user's answer to a permission request.\n127\t RawJsonRpcMessage::Response(Response::Result { id, result }) => {\n128\t state.resolve_permission(id, Some(result));\n129\t }\n130\t RawJsonRpcMessage::Response(Response::Error { id, .. }) => {\n131\t state.resolve_permission(id, None);\n132\t }\n133\t // Handshake and configuration traffic: nothing to render.\n134\t RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => {}\n135\t },\n136\t\n137\t LogMessage::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {\n138\t // The bulk of the log: streamed content and tool activity.\n139\t RawJsonRpcMessage::Notification(notification)\n140\t if &*notification.method == \"session/update\" =>\n141\t {\n142\t state.apply_session_update(params_value(notification.params.as_ref()));\n143\t }\n144\t // The agent asking to proceed.\n145\t RawJsonRpcMessage::Request(request)\n146\t if &*request.method == \"session/request_permission\" =>\n147\t {\n148\t state.request_permission(&request.id, params_value(request.params.as_ref()));\n149\t }\n150\t // The response to `session/prompt` closes the turn.\n151\t RawJsonRpcMessage::Response(Response::Result { id, result }) => {\n152\t state.end_turn(id, Some(result));\n153\t }\n154\t RawJsonRpcMessage::Response(Response::Error { id, .. }) => {\n155\t state.end_turn(id, None);\n156\t }\n157\t RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => {}\n158\t },\n159\t\n160\t // Runtime lifecycle events carry no conversation content. The one\n161\t // the service acts on, `acp_ready`, is a handshake signal.\n162\t LogMessage::ToServer(ToServerMessage::Event { .. }) => {}\n163\t\n164\t // Both message enums are `#[non_exhaustive]`.\n165\t _ => {}\n166\t }\n167\t }\n168\t\n169\t state.finish()\n170\t}\n171\t\n172\t/// Accumulated fold state.\n173\t#[derive(Default)]\n174\tstruct State {\n175\t messages: Vec<FoldedMessage>,"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Dvw8FiPMEqdtL4XDjktdfQ",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2721,23 +2037,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs"),
- "old_string": String("use crate::message::{\n AnsiText, Author, FileDiff, FoldedMessage, MessagePart, Permission, PermissionOption,\n PermissionOutcome, StopReason, ToolDetail, ToolStatus, ToolUse, ToolUseId, TurnId,\n};\nuse crate::meta::{claude_code, command_from_raw_input};\nuse agent_client_protocol::schema::v1::{\n ContentBlock, Meta, RequestId, Response, SessionNotification, SessionUpdate, ToolCall,\n ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,\n};\nuse agent_client_protocol::{RawJsonRpcMessage, RawJsonRpcParams};\nuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};\nuse macro_user_id::user_id::MacroUserIdStr;\nuse non_empty::NonEmpty;\nuse std::collections::HashMap;\nuse std::path::PathBuf;\n\n#[cfg(test)]\nmod test;\n\n/// One row of a session's protocol log.\n///\n/// Mirrors `agent_session_log`, but is defined here so the fold depends only\n/// on the protocol schema rather than on the crate that persists it.\n#[derive(Debug, Clone)]\npub struct LogEntry {\n /// Set when this frame is ACP traffic that originated from a user.\n pub user_id: Option<MacroUserIdStr<'static>>,\n /// The frame, in its original direction.\n pub message: LogMessage,\n}\n\n/// A logged frame, tagged with the direction it travelled.\n#[derive(Debug, Clone)]\npub enum LogMessage {\n /// Agent Runtime to Agent Service.\n ToServer(ToServerMessage),\n /// Agent Service to Agent Runtime.\n ToRuntime(ToRuntimeMessage),\n}\n\n/// The result of folding a log."),
- "new_string": String("use crate::domain::message::{\n AnsiText, Author, FileDiff, FoldedMessage, MessagePart, Permission, PermissionOption,\n PermissionOutcome, StopReason, ToolDetail, ToolStatus, ToolUse, ToolUseId, TurnId,\n};\nuse crate::domain::meta::{claude_code, command_from_raw_input};\nuse agent_client_protocol::schema::v1::{\n ContentBlock, Meta, RequestId, Response, SessionNotification, SessionUpdate, ToolCall,\n ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,\n};\nuse agent_client_protocol::{RawJsonRpcMessage, RawJsonRpcParams};\nuse agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};\nuse agent_session::domain::model::{AgentSessionLog, Message};\nuse macro_user_id::user_id::MacroUserIdStr;\nuse non_empty::NonEmpty;\nuse std::collections::HashMap;\nuse std::path::PathBuf;\n\n#[cfg(test)]\nmod test;\n\n/// The result of folding a log."),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018eJ4a56yi6dA4ACkP83bJb",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2750,23 +2057,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs"),
- "old_string": String("#[must_use]\npub fn fold(log: impl IntoIterator<Item = LogEntry>) -> Fold {\n let mut state = State::default();\n\n for entry in log {\n // The one place the protocol is dispatched. Each arm names a frame\n // this fold understands; the rest are ignored on purpose.\n match &entry.message {\n LogMessage::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {\n // A user's prompt opens a turn.\n RawJsonRpcMessage::Request(request) if &*request.method == \"session/prompt\" => {\n state.begin_turn(\n &request.id,\n params_value(request.params.as_ref()),\n entry.user_id,\n );\n }"),
- "new_string": String("#[must_use]\npub fn fold(log: impl IntoIterator<Item = AgentSessionLog>) -> Fold {\n let mut state = State::default();\n\n for entry in log {\n // The one place the protocol is dispatched. Each arm names a frame\n // this fold understands; the rest are ignored on purpose.\n match &entry.content {\n Message::ToRuntime(ToRuntimeMessage::Acp(acp)) => match &acp.0 {\n // A user's prompt opens a turn.\n RawJsonRpcMessage::Request(request) if &*request.method == \"session/prompt\" => {\n state.begin_turn(\n &request.id,\n params_value(request.params.as_ref()),\n entry.user_id.clone(),\n );\n }"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01V9HqUkM7YX6mBu1Hne6SoT",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2779,23 +2077,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs"),
- "old_string": String(" // Handshake and configuration traffic: nothing to render.\n RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => {}\n },\n\n LogMessage::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {"),
- "new_string": String(" // Handshake and configuration traffic: nothing to render.\n RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => {}\n },\n\n Message::ToServer(ToServerMessage::Acp(acp)) => match &acp.0 {"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Q6d8KScTNVZGChbDWwuioD",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2808,17 +2097,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs"),
- "old_string": String(" // Runtime lifecycle events carry no conversation content. The one\n // the service acts on, `acp_ready`, is a handshake signal.\n LogMessage::ToServer(ToServerMessage::Event { .. }) => {}\n\n // Both message enums are `#[non_exhaustive]`.\n _ => {}\n }\n }"),
- "new_string": String(" // Runtime lifecycle events carry no conversation content. The one\n // the service acts on, `acp_ready`, is a handshake signal.\n Message::ToServer(ToServerMessage::Event { .. }) => {}\n\n // The wrapped protocol enums are `#[non_exhaustive]`.\n Message::ToServer(_) | Message::ToRuntime(_) => {}\n }\n }"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now add the natural key to `message.rs` — the pretend-DB needs a stable id:",
@@ -2827,7 +2105,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01DQJhgDzAGsapYG5sCQvnBG",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2840,23 +2120,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/message.rs"),
- "old_string": String("/// A tool call within a turn, identified by its ACP `toolCallId`.\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\npub struct ToolUseId(pub String);"),
- "new_string": String("/// A tool call within a turn, identified by its ACP `toolCallId`.\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\npub struct ToolUseId(pub String);\n\n/// The natural key of a [`FoldedMessage`] within its session.\n///\n/// Nothing here is stored, so there is no surrogate row id to hand out.\n/// Instead the key falls out of the fold's shape: a turn yields at most one\n/// message per side of the conversation, so `(turn, author side)` identifies\n/// a message - and because [`TurnId`]s are assigned in log order, the same\n/// log always derives the same keys. Queries that pretend the messages are\n/// stored address them by this.\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub struct MessageId {\n /// The turn the message belongs to.\n pub turn: TurnId,\n /// Which side of the conversation produced it.\n pub author: AuthorKind,\n}\n\n/// Which side of the conversation produced a message.\n///\n/// The identity-free discriminant of [`Author`], usable in a key where\n/// [`Author`] itself carries a payload.\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub enum AuthorKind {\n /// A person.\n User,\n /// The agent.\n Agent,\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01CosbbVKFBxAW6aFoVjyMFY",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2869,23 +2140,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/message.rs"),
- "old_string": String(" /// How the turn ended, on the agent message that closed it.\n ///\n /// `None` while a turn is still in flight, or when the session died\n /// without a response to the prompt.\n pub stop: Option<StopReason>,\n}"),
- "new_string": String(" /// How the turn ended, on the agent message that closed it.\n ///\n /// `None` while a turn is still in flight, or when the session died\n /// without a response to the prompt.\n pub stop: Option<StopReason>,\n}\n\nimpl FoldedMessage {\n /// This message's natural key within its session.\n #[must_use]\n pub fn id(&self) -> MessageId {\n MessageId {\n turn: self.turn,\n author: self.author.kind(),\n }\n }\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01EgKh8Ae871CWUaaJZ6FREe",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2898,17 +2160,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/message.rs"),
- "old_string": String(" User(Option<MacroUserIdStr<'static>>),\n /// The agent.\n Agent,\n}"),
- "new_string": String(" User(Option<MacroUserIdStr<'static>>),\n /// The agent.\n Agent,\n}\n\nimpl Author {\n /// Which side of the conversation this author is, identity dropped.\n #[must_use]\n pub fn kind(&self) -> AuthorKind {\n match self {\n Self::User(_) => AuthorKind::User,\n Self::Agent => AuthorKind::Agent,\n }\n }\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the ports — the two boundaries of the hexagon:",
@@ -2917,7 +2168,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01KLVU5FN37NVukDAVgYXf4G",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2928,21 +2181,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/ports.rs"),
- "content": String("//! The crate's ports.\n//!\n//! [`FoldedMessageRepo`] is the driving port: the query API the rest of the\n//! system calls. It is deliberately shaped like a repository over stored\n//! rows - list a session's messages, get one by id - even though nothing is\n//! stored: the service behind it derives every answer from the protocol log\n//! on each call. Callers should not be able to tell, and the day the\n//! messages *are* materialized somewhere, only the implementation moves.\n//!\n//! [`SessionLogStore`] is the driven port: where the log comes from. Its one\n//! method mirrors `agent_session::domain::ports::AgentSessionLogRepo::\n//! list_by_session`, but is declared here so this domain names exactly the\n//! capability it needs - reading a session's log, chronologically - and so\n//! tests can supply one without a database.\n\nuse crate::domain::message::{FoldedMessage, MessageId};\nuse agent_session::domain::model::{AgentSessionId, AgentSessionLog};\n\n/// Read access to a session's protocol log, in chronological order.\npub trait SessionLogStore {\n /// Every logged frame for the session, oldest first. A session with no\n /// log - including one that does not exist - is an empty list.\n fn list_by_session(\n &self,\n session: AgentSessionId,\n ) -> impl Future<Output = Result<Vec<AgentSessionLog>, rootcause::Report>> + Send;\n}\n\n/// Query a session's messages as if they were stored.\npub trait FoldedMessageRepo {\n /// A session's messages, oldest first. A session with no log folds to no\n /// messages.\n fn list_by_session(\n &self,\n session: AgentSessionId,\n ) -> impl Future<Output = Result<Vec<FoldedMessage>, rootcause::Report>> + Send;\n\n /// One message by its natural key, or `None` when the session's log\n /// derives no such message.\n fn get(\n &self,\n session: AgentSessionId,\n id: MessageId,\n ) -> impl Future<Output = Result<Option<FoldedMessage>, rootcause::Report>> + Send;\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/domain/ports.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01VvtRhZuKi3qGQzEz9vs5ri",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2953,21 +2199,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service.rs"),
- "content": String("//! The domain service implementing the query port.\n//!\n//! [`FoldedMessageService`] is the \"database engine\" of the pretend store:\n//! every query loads the session's log through [`SessionLogStore`] and runs\n//! the fold. Anomalies the fold reports are logged as warnings rather than\n//! surfaced to callers - a query against a store should not fail because one\n//! frame was strange - so the only error a query can return is a failure to\n//! load the log itself.\n\nuse crate::domain::fold;\nuse crate::domain::message::{FoldedMessage, MessageId};\nuse crate::domain::ports::{FoldedMessageRepo, SessionLogStore};\nuse agent_session::domain::model::AgentSessionId;\n\n#[cfg(test)]\nmod test;\n\n/// Serves [`FoldedMessageRepo`] queries by folding the session log on read.\n#[derive(Debug, Clone)]\npub struct FoldedMessageService<Logs> {\n logs: Logs,\n}\n\nimpl<Logs> FoldedMessageService<Logs> {\n /// A service answering queries from the given log store.\n pub fn new(logs: Logs) -> Self {\n Self { logs }\n }\n}\n\nimpl<Logs> FoldedMessageService<Logs>\nwhere\n Logs: SessionLogStore + Sync,\n{\n /// Load and fold a session's log, reporting anomalies as warnings.\n async fn fold_session(\n &self,\n session: AgentSessionId,\n ) -> Result<Vec<FoldedMessage>, rootcause::Report> {\n let log = self.logs.list_by_session(session).await?;\n let folded = fold::fold(log);\n for anomaly in &folded.anomalies {\n tracing::warn!(\n anomaly = ?anomaly,\n session = ?session,\n \"agent session log frame could not be folded\"\n );\n }\n Ok(folded.messages)\n }\n}\n\nimpl<Logs> FoldedMessageRepo for FoldedMessageService<Logs>\nwhere\n Logs: SessionLogStore + Sync,\n{\n #[tracing::instrument(err, skip(self))]\n async fn list_by_session(\n &self,\n session: AgentSessionId,\n ) -> Result<Vec<FoldedMessage>, rootcause::Report> {\n self.fold_session(session).await\n }\n\n #[tracing::instrument(err, skip(self))]\n async fn get(\n &self,\n session: AgentSessionId,\n id: MessageId,\n ) -> Result<Option<FoldedMessage>, rootcause::Report> {\n let messages = self.fold_session(session).await?;\n Ok(messages.into_iter().find(|message| message.id() == id))\n }\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/domain/service.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01JmETWUewVzK4J65BumEd6J",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -2978,15 +2217,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/mod.rs"),
- "content": String("//! Domain layer: the message vocabulary, the fold that derives it, and the\n//! ports through which it is queried and fed.\n\n/// Collapsing a protocol log into messages.\npub mod fold;\n/// The renderable message vocabulary.\npub mod message;\n/// Harness-specific `_meta` extraction.\npub mod meta;\n/// The driving query port and the driven log-source port.\npub mod ports;\n/// The domain service answering queries by folding on read.\npub mod service;\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/domain/mod.rs (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the outbound side — an in-memory log store, which is what \"make-believe\" runs on until the Postgres adapter exists:",
@@ -2995,7 +2225,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_018fCCvxm72CU4kX2nhRnH8n",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3006,21 +2238,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/outbound/mod.rs"),
- "content": String("//! Adapters implementing the domain ports.\n//!\n//! The production log source is `agent_session`'s Postgres-backed repo; an\n//! adapter for it belongs to whichever composition root wires this crate\n//! into a service, where the concrete repo type is known. What lives here is\n//! the in-memory store that tests, examples, and make-believe run on.\n\n/// An in-memory [`SessionLogStore`](crate::domain::ports::SessionLogStore).\npub mod memory;\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/outbound/mod.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01FHp7bM44DiyczQWeRbzAud",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3031,21 +2256,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/outbound/memory.rs"),
- "content": String("//! An in-memory session log store.\n\nuse crate::domain::ports::SessionLogStore;\nuse agent_session::domain::model::{AgentSessionId, AgentSessionLog};\nuse std::collections::HashMap;\n\n/// A [`SessionLogStore`] over logs held in memory, keyed by session.\n///\n/// The backing store for tests and examples: load recorded frames in, then\n/// query them through the domain service exactly as a database-backed store\n/// would be queried.\n#[derive(Debug, Clone, Default)]\npub struct InMemoryLogStore {\n logs: HashMap<AgentSessionId, Vec<AgentSessionLog>>,\n}\n\nimpl InMemoryLogStore {\n /// An empty store.\n #[must_use]\n pub fn new() -> Self {\n Self::default()\n }\n\n /// Append an entry to its session's log. Insertion order is chronology.\n pub fn push(&mut self, entry: AgentSessionLog) {\n self.logs\n .entry(entry.agent_session_id)\n .or_default()\n .push(entry);\n }\n}\n\nimpl FromIterator<AgentSessionLog> for InMemoryLogStore {\n fn from_iter<I: IntoIterator<Item = AgentSessionLog>>(entries: I) -> Self {\n let mut store = Self::new();\n for entry in entries {\n store.push(entry);\n }\n store\n }\n}\n\nimpl SessionLogStore for InMemoryLogStore {\n async fn list_by_session(\n &self,\n session: AgentSessionId,\n ) -> Result<Vec<AgentSessionLog>, rootcause::Report> {\n Ok(self.logs.get(&session).cloned().unwrap_or_default())\n }\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/outbound/memory.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_017wesMmZoBU6Qg5DzScBKFd",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3056,15 +2274,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/lib.rs"),
- "content": String("#![deny(missing_docs)]\n//! Folds an agent session's protocol log into renderable messages, and\n//! serves them as if they were stored.\n//!\n//! An agent session is recorded as a flat log of Agent Runtime Protocol\n//! frames - `agent_session_log`, modelled by\n//! [`agent_session::domain::model::AgentSessionLog`]. That log is faithful\n//! but unreadable: a single session is hundreds of streamed chunks,\n//! tool-call patches and token-usage reports. This crate collapses it into\n//! the handful of messages a person would recognize as the story of the\n//! session.\n//!\n//! Nothing here is persisted. The fiction of the crate is that folded\n//! messages live in a database: [`domain::ports::FoldedMessageRepo`] is a\n//! repository-shaped query API, and\n//! [`domain::service::FoldedMessageService`] answers it by loading the log\n//! through [`domain::ports::SessionLogStore`] and folding on every read.\n//! Because the messages are re-derived each time, the vocabulary in\n//! [`domain::message`] can change without a migration.\n//!\n//! ```no_run\n//! use agent_fold::domain::ports::FoldedMessageRepo;\n//! use agent_fold::domain::service::FoldedMessageService;\n//! use agent_fold::outbound::memory::InMemoryLogStore;\n//! use agent_session::domain::model::AgentSessionId;\n//!\n//! # async fn run(store: InMemoryLogStore, session: AgentSessionId) {\n//! let messages = FoldedMessageService::new(store)\n//! .list_by_session(session)\n//! .await\n//! .expect(\"log store is in memory\");\n//! for message in &messages {\n//! println!(\"{:?} said {} part(s)\", message.author, message.parts.len());\n//! }\n//! # }\n//! ```\n\n/// Domain models, the fold, and the crate's ports.\npub mod domain;\n/// Adapters implementing the domain ports.\npub mod outbound;\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/lib.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now update the fold tests to build `AgentSessionLog` rows:",
@@ -3073,7 +2282,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01U1n75uqikwJQNhkocKhm9x",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3086,17 +2297,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold/test.rs"),
- "old_string": String("use super::*;\nuse crate::message::{Author, MessagePart, PermissionOutcome, StopReason, ToolDetail, ToolStatus};\n\n/// Parse one recorded line - the agent_session_recorder / fixture format:\n/// `{\"ts\": ..., \"direction\": \"to_server\" | \"to_runtime\", \"content\": {...}}`.\n///\n/// Prompts get a user id attached, mirroring what the agent service stamps\n/// onto `agent_session_log.user_id` for user-originated ACP traffic.\nfn parse_line(line: &str) -> LogEntry {\n let value: serde_json::Value = serde_json::from_str(line).expect(\"recorded line is JSON\");\n let direction = value\n .get(\"direction\")\n .and_then(|direction| direction.as_str())\n .expect(\"recorded line has a direction\");\n let content = value.get(\"content\").expect(\"recorded line has content\");\n\n let message = match direction {\n \"to_server\" => LogMessage::ToServer(\n serde_json::from_value(content.clone()).expect(\"to_server frame deserializes\"),\n ),\n \"to_runtime\" => LogMessage::ToRuntime(\n serde_json::from_value(content.clone()).expect(\"to_runtime frame deserializes\"),\n ),\n other => panic!(\"unknown direction {other}\"),\n };\n\n let is_prompt = content\n .get(\"method\")\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n\n LogEntry {\n user_id: is_prompt.then(|| {\n MacroUserIdStr::try_from_email(\"[email protected]\").expect(\"test email parses\")\n }),\n message,\n }\n}\n\nfn parse_log(jsonl: &str) -> Vec<LogEntry> {\n jsonl\n .lines()\n .filter(|line| !line.trim().is_empty())\n .map(parse_line)\n .collect()\n}"),
- "new_string": String("use super::*;\nuse crate::domain::message::{\n Author, MessagePart, PermissionOutcome, StopReason, ToolDetail, ToolStatus,\n};\nuse agent_session::domain::model::AgentSessionId;\n\nfn test_session() -> AgentSessionId {\n AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(1))\n}\n\n/// Parse one recorded line - the agent_session_recorder / fixture format:\n/// `{\"ts\": ..., \"direction\": \"to_server\" | \"to_runtime\", \"content\": {...}}` -\n/// into the log row the fold consumes.\n///\n/// Prompts get a user id attached, mirroring what the agent service stamps\n/// onto `agent_session_log.user_id` for user-originated ACP traffic.\nfn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {\n let value: serde_json::Value = serde_json::from_str(line).expect(\"recorded line is JSON\");\n let direction = value\n .get(\"direction\")\n .and_then(|direction| direction.as_str())\n .expect(\"recorded line has a direction\");\n let content = value.get(\"content\").expect(\"recorded line has content\");\n\n let content = match direction {\n \"to_server\" => Message::ToServer(\n serde_json::from_value(content.clone()).expect(\"to_server frame deserializes\"),\n ),\n \"to_runtime\" => {\n let is_prompt = content\n .get(\"method\")\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n let _ = is_prompt;\n Message::ToRuntime(\n serde_json::from_value(content.clone()).expect(\"to_runtime frame deserializes\"),\n )\n }\n other => panic!(\"unknown direction {other}\"),\n };\n\n let is_prompt = value\n .get(\"content\")\n .and_then(|content| content.get(\"method\"))\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n\n AgentSessionLog {\n agent_session_id: session,\n user_id: is_prompt.then(|| {\n MacroUserIdStr::try_from_email(\"[email protected]\").expect(\"test email parses\")\n }),\n content,\n }\n}\n\nfn parse_log(jsonl: &str) -> Vec<AgentSessionLog> {\n jsonl\n .lines()\n .filter(|line| !line.trim().is_empty())\n .map(|line| parse_line(test_session(), line))\n .collect()\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "I left a clumsy duplicate in that edit — cleaning it:",
@@ -3105,7 +2305,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01T2PhF57e3XSotKV48kgBeh",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3118,17 +2320,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold/test.rs"),
- "old_string": String(" let content = match direction {\n \"to_server\" => Message::ToServer(\n serde_json::from_value(content.clone()).expect(\"to_server frame deserializes\"),\n ),\n \"to_runtime\" => {\n let is_prompt = content\n .get(\"method\")\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n let _ = is_prompt;\n Message::ToRuntime(\n serde_json::from_value(content.clone()).expect(\"to_runtime frame deserializes\"),\n )\n }\n other => panic!(\"unknown direction {other}\"),\n };\n\n let is_prompt = value\n .get(\"content\")\n .and_then(|content| content.get(\"method\"))\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n\n AgentSessionLog {"),
- "new_string": String(" let is_prompt = content\n .get(\"method\")\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n\n let content = match direction {\n \"to_server\" => Message::ToServer(\n serde_json::from_value(content.clone()).expect(\"to_server frame deserializes\"),\n ),\n \"to_runtime\" => Message::ToRuntime(\n serde_json::from_value(content.clone()).expect(\"to_runtime frame deserializes\"),\n ),\n other => panic!(\"unknown direction {other}\"),\n };\n\n AgentSessionLog {"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Both fold tests and service tests need the same parsing helpers — promoting them to a shared `test_support` module:",
@@ -3137,7 +2328,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_011ryaCQw7sFhbjFuH38gYcQ",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3148,21 +2341,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs"),
- "content": String("//! Shared helpers for tests: parsing recorded protocol frames into log rows.\n\nuse agent_session::domain::model::{AgentSessionId, AgentSessionLog, Message};\nuse macro_user_id::user_id::MacroUserIdStr;\n\n/// The hermetic fixture: one complete turn with prose, a permission-gated\n/// terminal command, a patched-in edit, and a clean stop.\npub const TURN: &str = include_str!(\"../../fixtures/turn.jsonl\");\n\n/// The session id fixture logs are parsed into by default.\npub fn test_session() -> AgentSessionId {\n AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(1))\n}\n\n/// Parse one recorded line - the agent_session_recorder / fixture format:\n/// `{\"ts\": ..., \"direction\": \"to_server\" | \"to_runtime\", \"content\": {...}}` -\n/// into the log row the fold consumes.\n///\n/// Prompts get a user id attached, mirroring what the agent service stamps\n/// onto `agent_session_log.user_id` for user-originated ACP traffic.\npub fn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {\n let value: serde_json::Value = serde_json::from_str(line).expect(\"recorded line is JSON\");\n let direction = value\n .get(\"direction\")\n .and_then(|direction| direction.as_str())\n .expect(\"recorded line has a direction\");\n let content = value.get(\"content\").expect(\"recorded line has content\");\n\n let is_prompt = content\n .get(\"method\")\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n\n let content = match direction {\n \"to_server\" => Message::ToServer(\n serde_json::from_value(content.clone()).expect(\"to_server frame deserializes\"),\n ),\n \"to_runtime\" => Message::ToRuntime(\n serde_json::from_value(content.clone()).expect(\"to_runtime frame deserializes\"),\n ),\n other => panic!(\"unknown direction {other}\"),\n };\n\n AgentSessionLog {\n agent_session_id: session,\n user_id: is_prompt.then(|| {\n MacroUserIdStr::try_from_email(\"[email protected]\").expect(\"test email parses\")\n }),\n content,\n }\n}\n\n/// Parse a whole recording into the given session's log.\npub fn parse_log_as(session: AgentSessionId, jsonl: &str) -> Vec<AgentSessionLog> {\n jsonl\n .lines()\n .filter(|line| !line.trim().is_empty())\n .map(|line| parse_line(session, line))\n .collect()\n}\n\n/// Parse a whole recording into [`test_session`]'s log.\npub fn parse_log(jsonl: &str) -> Vec<AgentSessionLog> {\n parse_log_as(test_session(), jsonl)\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018nUaDSs117XXUdHBH8i5L5",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3175,17 +2361,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/mod.rs"),
- "old_string": String("/// The domain service answering queries by folding on read.\npub mod service;"),
- "new_string": String("/// The domain service answering queries by folding on read.\npub mod service;\n\n#[cfg(test)]\npub(crate) mod test_support;"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/mod.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now slim `fold/test.rs` down to use the shared helpers:",
@@ -3194,7 +2369,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01HeSAMG6QFhTYYRWtA3qn79",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3207,23 +2384,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/fold/test.rs"),
- "old_string": String("use super::*;\nuse crate::domain::message::{\n Author, MessagePart, PermissionOutcome, StopReason, ToolDetail, ToolStatus,\n};\nuse agent_session::domain::model::AgentSessionId;\n\nfn test_session() -> AgentSessionId {\n AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(1))\n}\n\n/// Parse one recorded line - the agent_session_recorder / fixture format:\n/// `{\"ts\": ..., \"direction\": \"to_server\" | \"to_runtime\", \"content\": {...}}` -\n/// into the log row the fold consumes.\n///\n/// Prompts get a user id attached, mirroring what the agent service stamps\n/// onto `agent_session_log.user_id` for user-originated ACP traffic.\nfn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {\n let value: serde_json::Value = serde_json::from_str(line).expect(\"recorded line is JSON\");\n let direction = value\n .get(\"direction\")\n .and_then(|direction| direction.as_str())\n .expect(\"recorded line has a direction\");\n let content = value.get(\"content\").expect(\"recorded line has content\");\n\n let is_prompt = content\n .get(\"method\")\n .and_then(|method| method.as_str())\n .is_some_and(|method| method == \"session/prompt\");\n\n let content = match direction {\n \"to_server\" => Message::ToServer(\n serde_json::from_value(content.clone()).expect(\"to_server frame deserializes\"),\n ),\n \"to_runtime\" => Message::ToRuntime(\n serde_json::from_value(content.clone()).expect(\"to_runtime frame deserializes\"),\n ),\n other => panic!(\"unknown direction {other}\"),\n };\n\n AgentSessionLog {\n agent_session_id: session,\n user_id: is_prompt.then(|| {\n MacroUserIdStr::try_from_email(\"[email protected]\").expect(\"test email parses\")\n }),\n content,\n }\n}\n\nfn parse_log(jsonl: &str) -> Vec<AgentSessionLog> {\n jsonl\n .lines()\n .filter(|line| !line.trim().is_empty())\n .map(|line| parse_line(test_session(), line))\n .collect()\n}\n\nconst TURN: &str = include_str!(\"../../fixtures/turn.jsonl\");"),
- "new_string": String("use super::*;\nuse crate::domain::message::{\n Author, MessagePart, PermissionOutcome, StopReason, ToolDetail, ToolStatus,\n};\nuse crate::domain::test_support::{TURN, parse_log};"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/fold/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_017g4c2PmRqCXehTvjCUqgHQ",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3234,21 +2402,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "content": String("use super::*;\nuse crate::domain::message::{AuthorKind, MessagePart, TurnId};\nuse crate::domain::ports::SessionLogStore;\nuse crate::domain::test_support::{TURN, parse_log_as, test_session};\nuse crate::outbound::memory::InMemoryLogStore;\nuse agent_session::domain::model::AgentSessionId;\n\nfn other_session() -> AgentSessionId {\n AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(2))\n}\n\n/// A store holding two sessions: the full fixture, and a second session cut\n/// off mid-turn.\nfn two_session_store() -> InMemoryLogStore {\n let mut second = parse_log_as(other_session(), TURN);\n second.truncate(9);\n\n parse_log_as(test_session(), TURN)\n .into_iter()\n .chain(second)\n .collect()\n}\n\n/// Queries answer per session: each session's log folds independently, and\n/// a session nothing was logged for is simply empty - the same answer a\n/// database would give.\n#[tokio::test]\nasync fn queries_are_scoped_to_a_session() {\n let service = FoldedMessageService::new(two_session_store());\n\n let full = service\n .list_by_session(test_session())\n .await\n .expect(\"in-memory store cannot fail\");\n assert_eq!(full.len(), 2);\n assert_eq!(full[1].stop.as_ref().map(|_| ()), Some(()), \"full session closed its turn\");\n\n let interrupted = service\n .list_by_session(other_session())\n .await\n .expect(\"in-memory store cannot fail\");\n assert_eq!(interrupted.len(), 2);\n assert_eq!(interrupted[1].stop, None, \"cut session never closed\");\n\n let unknown = service\n .list_by_session(AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(9)))\n .await\n .expect(\"in-memory store cannot fail\");\n assert_eq!(unknown, vec![], \"an unlogged session has no messages\");\n}\n\n/// `get` addresses one message by its natural key.\n#[tokio::test]\nasync fn gets_a_message_by_id() {\n let service = FoldedMessageService::new(two_session_store());\n\n let listed = service\n .list_by_session(test_session())\n .await\n .expect(\"in-memory store cannot fail\");\n let agent_reply = listed[1].clone();\n\n let fetched = service\n .get(test_session(), agent_reply.id())\n .await\n .expect(\"in-memory store cannot fail\");\n assert_eq!(fetched, Some(agent_reply), \"get returns the listed message\");\n\n let missing = service\n .get(\n test_session(),\n MessageId {\n turn: TurnId(7),\n author: AuthorKind::Agent,\n },\n )\n .await\n .expect(\"in-memory store cannot fail\");\n assert_eq!(missing, None, \"a key no turn produced is absent\");\n}\n\n/// The service is a read model over whatever the log store returns; folding\n/// through the service matches folding the log directly.\n#[tokio::test]\nasync fn service_matches_the_bare_fold() {\n let store = two_session_store();\n let service = FoldedMessageService::new(store.clone());\n\n let via_service = service\n .list_by_session(test_session())\n .await\n .expect(\"in-memory store cannot fail\");\n let via_fold = fold::fold(\n store\n .list_by_session(test_session())\n .await\n .expect(\"in-memory store cannot fail\"),\n );\n\n assert_eq!(via_service, via_fold.messages);\n\n // Every derived message is addressable by the key it reports.\n for message in &via_service {\n let fetched = service\n .get(test_session(), message.id())\n .await\n .expect(\"in-memory store cannot fail\");\n assert_eq!(fetched.as_ref(), Some(message));\n }\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01QN37aZBTmATxnPgkiGCfck",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3261,17 +2422,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "old_string": String(" assert_eq!(full.len(), 2);\n assert_eq!(full[1].stop.as_ref().map(|_| ()), Some(()), \"full session closed its turn\");"),
- "new_string": String(" assert_eq!(full.len(), 2);\n assert!(full[1].stop.is_some(), \"full session closed its turn\");"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the example — rewritten to run the whole hexagon (recording → in-memory store → service → query):",
@@ -3280,7 +2430,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_013kEDYGtNadUSqxn8a4e7jZ",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3291,21 +2443,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/examples/fold_recording.rs"),
- "content": String("//! Fold a recorded session and print what a channel would render.\n//!\n//! Loads a recording into the in-memory log store and queries it through the\n//! domain service - the same path a real caller takes, with Postgres swapped\n//! out.\n//!\n//! ```sh\n//! cargo run -p agent_fold --example fold_recording -- ~/.agent_runtime_sessions/<id>.jsonl\n//! ```\n\nuse agent_fold::domain::message::{Author, MessagePart, ToolDetail};\nuse agent_fold::domain::ports::FoldedMessageRepo;\nuse agent_fold::domain::service::FoldedMessageService;\nuse agent_fold::outbound::memory::InMemoryLogStore;\nuse agent_session::domain::model::{AgentSessionId, AgentSessionLog, Message};\n\n#[tokio::main(flavor = \"current_thread\")]\nasync fn main() {\n let path = std::env::args()\n .nth(1)\n .expect(\"usage: fold_recording <recording.jsonl>\");\n let jsonl = std::fs::read_to_string(&path).expect(\"recording is readable\");\n\n let session = AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(1));\n let store: InMemoryLogStore = jsonl\n .lines()\n .filter(|line| !line.trim().is_empty())\n .map(|line| parse_line(session, line))\n .collect();\n\n let messages = FoldedMessageService::new(store)\n .list_by_session(session)\n .await\n .expect(\"in-memory store cannot fail\");\n\n for message in &messages {\n let author = match &message.author {\n Author::User(id) => format!(\n \"user({})\",\n id.as_ref()\n .map_or_else(|| \"?\".to_owned(), ToString::to_string)\n ),\n Author::Agent => \"agent\".to_owned(),\n };\n println!(\n \"── turn {} · {author} · stop {:?}\",\n message.turn.0, message.stop\n );\n for part in message.parts.iter() {\n match part {\n MessagePart::Text(text) => {\n println!(\" text ({} chars) {:?}\", text.len(), preview(text))\n }\n MessagePart::Thought(text) => println!(\" thought ({} chars)\", text.len()),\n MessagePart::ToolUse(tool) => {\n let detail = match &tool.detail {\n ToolDetail::Terminal {\n command, exit_code, ..\n } => format!(\n \"terminal {:?} exit={exit_code:?}\",\n command.as_deref().map(preview)\n ),\n ToolDetail::Edit { diffs } => format!(\"edit {} diff(s)\", diffs.len()),\n ToolDetail::Read { paths } => format!(\"read {paths:?}\"),\n ToolDetail::Other { kind, .. } => format!(\"other kind={kind}\"),\n };\n println!(\" tool {} [{:?}] {detail}\", tool.label, tool.status);\n }\n MessagePart::Permission(permission) => println!(\n \" permission for {} -> {:?}\",\n permission.tool_call.0, permission.outcome\n ),\n }\n }\n }\n}\n\n/// Parse one recorded line into a log row for the given session.\nfn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {\n let value: serde_json::Value = serde_json::from_str(line).expect(\"line is JSON\");\n let content = value.get(\"content\").expect(\"line has content\").clone();\n let content = match value.get(\"direction\").and_then(|d| d.as_str()) {\n Some(\"to_server\") => {\n Message::ToServer(serde_json::from_value(content).expect(\"to_server frame\"))\n }\n Some(\"to_runtime\") => {\n Message::ToRuntime(serde_json::from_value(content).expect(\"to_runtime frame\"))\n }\n other => panic!(\"unknown direction {other:?}\"),\n };\n AgentSessionLog {\n agent_session_id: session,\n user_id: None,\n content,\n }\n}\n\nfn preview(text: &str) -> String {\n let line = text.lines().next().unwrap_or_default();\n let mut preview: String = line.chars().take(60).collect();\n if preview.len() < text.len() {\n preview.push('…');\n }\n preview\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/examples/fold_recording.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_015iMmr6odhKRipdzks5KqM2",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3320,22 +2465,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo check -p agent_fold --all-targets 2>&1 | grep -E \"^error|^warning: unused|-->\" | head -30; echo \"---done---\""),
- "description": String("Type-check restructured crate"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String("warning: unused import: `MessagePart`\n --> crates/agent_fold/src/domain/service/test.rs:2:42\n---done---"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_012DvLbqFv7vpUoakxBMZiMe",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3348,23 +2485,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "old_string": String("use crate::domain::message::{AuthorKind, MessagePart, TurnId};"),
- "new_string": String("use crate::domain::message::{AuthorKind, TurnId};"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01MPA4MBU4n2CjXBuUgJZSNE",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3379,22 +2507,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo test -p agent_fold 2>&1 | grep -E \"^test |test result|^error\" | head -20"),
- "description": String("Run all agent_fold tests"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String("test domain::fold::test::folds_nothing ... ok\ntest domain::meta::test::reads_the_harness_tool_name ... ok\ntest domain::meta::test::reads_a_command_from_raw_input ... ok\ntest domain::meta::test::tolerates_absence_and_noise ... ok\ntest domain::meta::test::reads_terminal_output_and_exit ... ok\ntest domain::fold::test::reports_a_patch_before_open ... ok\ntest domain::fold::test::folds_a_complete_turn ... ok\ntest domain::fold::test::folds_an_interrupted_turn ... ok\ntest domain::service::test::queries_are_scoped_to_a_session ... ok\ntest domain::service::test::gets_a_message_by_id ... ok\ntest domain::service::test::service_matches_the_bare_fold ... ok\ntest domain::fold::test::replays_local_recordings ... ok\ntest result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s\ntest crates/agent_fold/src/lib.rs - (line 21) - compile ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Le2eyQK2JbXXbfrzM1WCjg",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3409,22 +2529,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo fmt -p agent_fold && RUSTFLAGS=\"-Dwarnings -Dclippy::disallowed_methods\" RUSTDOCFLAGS=-Dwarnings SQLX_OFFLINE=true cargo clippy -p agent_fold --all-targets --all-features 2>&1 | tail -3 && cargo run -p agent_fold --example fold_recording -- ~/.agent_runtime_sessions/cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl 2>/dev/null | head -8"),
- "description": String("Format, strict clippy, and run example through service"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String(" Checking agent_session v0.1.0 (/Users/eric/Code/macro/crates/agent_session)\n Checking agent_fold v0.1.0 (/Users/eric/Code/macro/crates/agent_fold)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 16.95s\n── turn 0 · user(?) · stop None\n text (35 chars) \"where are session recordings saved?\"\n── turn 0 · agent · stop Some(EndTurn)\n text (452 chars) \"They're saved to `~/.agent_runtime_sessions/`, one file per …\"\n── turn 1 · user(?) · stop None\n text (20 chars) \"I don't see that dir\"\n── turn 1 · agent · stop Some(EndTurn)\n text (115 chars) \"Let me check whether it exists — it's a dotfile directory, s…\"\n[This command modified 1 file you've previously read: src/domain/service/test.rs. Call Read before editing.]"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_013qFo2rqGHZJHK7BjeN7ctf",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3437,23 +2549,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/.claude/projects/-Users-eric-Code-macro/memory/project_agent_fold.md"),
- "old_string": String("Design decisions (Eric's calls):\n- **Parallel system** — ignore existing AI chat models (`AssistantMessagePart` etc.); nothing persisted, messages derived from the log on every read (\"type land\")\n- **Plain lib, no hex** — deleted domain/ports stubs; pure fn `fold(impl IntoIterator<Item = LogEntry>) -> Fold`\n- **No Result** — fold is total; renderable-partial beats failing (pending tool call = in-flight state, not error). Weirdness goes to `Fold::anomalies` (tests assert empty; prod degrades gracefully)\n- **One explicit match** in `fold()`, not a handler registry — every understood/ignored frame named in one place\n\nStructure: `src/message.rs` (FoldedMessage/MessagePart/ToolUse/ToolDetail/Permission vocabulary, TurnId per prompt→stop cycle), `src/fold.rs` (State machine: turns, toolCallId patch correlation, JSON-RPC id permission correlation), `src/meta.rs` (quarantined Claude-Code `_meta` readers: toolName, terminal_output — snapshots not deltas — terminal_exit)."),
- "new_string": String("Design decisions (Eric's calls):\n- **Parallel system** — ignore existing AI chat models (`AssistantMessagePart` etc.); nothing persisted, messages derived from the log on every read (\"type land\")\n- **Hex crate with a pretend DB** — Eric reversed the earlier plain-lib call: messages are queried *as if stored*. Driving port `FoldedMessageRepo` (list_by_session / get by natural key `MessageId{turn, AuthorKind}`), driven port `SessionLogStore` (mirrors AgentSessionLogRepo::list_by_session), `FoldedMessageService` folds on every read; anomalies → tracing::warn, never errors\n- **No Result on the fold** — fold is total; renderable-partial beats failing (pending tool call = in-flight state, not error). Weirdness goes to `Fold::anomalies` (tests assert empty; prod degrades gracefully)\n- **One explicit match** in `fold()`, not a handler registry — every understood/ignored frame named in one place\n- Fold consumes `agent_session::domain::model::{AgentSessionLog, Message}` directly (no duplicate LogEntry type)\n\nStructure: `domain/message.rs` (FoldedMessage/MessagePart/ToolUse/ToolDetail/Permission vocabulary, TurnId per prompt→stop cycle, MessageId natural key), `domain/fold.rs` (State machine: turns, toolCallId patch correlation, JSON-RPC id permission correlation), `domain/meta.rs` (quarantined Claude-Code `_meta` readers: toolName, terminal_output — snapshots not deltas — terminal_exit), `domain/{ports,service}.rs`, `outbound/memory.rs` (InMemoryLogStore; pg adapter deferred to composition root), `domain/test_support.rs` (shared recording parser). Ports follow channels style: RPITIT `+ Send`, `rootcause::Report` errors, `#[tracing::instrument(err, skip(self))]`."),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/.claude/projects/-Users-eric-Code-macro/memory/project_agent_fold.md has been updated successfully."),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01BynA9q2Rig8kASZ25XBG2N",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3466,17 +2569,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/.claude/projects/-Users-eric-Code-macro/memory/MEMORY.md"),
- "old_string": String("- [agent_fold crate](project_agent_fold.md) — pure total fold (no Result, one explicit match, anomalies channel) from agent_session_log → FoldedMessage vocabulary; recordings at ~/.agent_runtime_sessions; iterate via fold_recording example"),
- "new_string": String("- [agent_fold crate](project_agent_fold.md) — hex crate, pretend-DB: FoldedMessageRepo query port answered by folding agent_session_log on read (fold itself total: no Result, one explicit match, anomalies channel); recordings at ~/.agent_runtime_sessions; iterate via fold_recording example"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/.claude/projects/-Users-eric-Code-macro/memory/MEMORY.md has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Restructured into a hex crate with the pretend-DB made explicit. **Hexagonal boundary checked** (via the architecture skill): domain imports only other domain models (`agent_session::domain::model`), protocol schema, and `tracing` — no axum/sqlx/transport anywhere; the one adapter lives in `outbound/`. There's no authz or business policy in this crate yet — queries are scoped by `AgentSessionId`, and access control (who may read a session's messages) stays with whatever inbound surface eventually calls the repo, minting its receipt against the session's thread/channel.\n\n**The shape now:**\n\n```\nsrc/domain/\n message.rs FoldedMessage vocabulary + MessageId natural key (turn, AuthorKind)\n fold.rs the pure total fold — unchanged semantics, now eats AgentSessionLog directly\n meta.rs quarantined Claude-Code _meta readers\n ports.rs SessionLogStore (driven) · FoldedMessageRepo (driving)\n service.rs FoldedMessageService: folds on every read, warns anomalies\nsrc/outbound/\n memory.rs InMemoryLogStore — what make-believe runs on\n```\n\n**Key decisions in the restructure:**\n- **The duplication went away.** My `LogEntry`/`LogMessage` were `agent_session::domain::model::{AgentSessionLog, Message}` re-invented — the fold now consumes the real model, so the eventual Postgres adapter is `AgentSessionLogRepo::list_by_session` output passed straight through.\n- **`FoldedMessageRepo` is the fiction.** Repo-shaped API (`list_by_session`, `get(session, id)`), styled after the channels crate: RPITIT `+ Send`, `rootcause::Report`, `#[tracing::instrument(err, skip(self))]`. Callers can't tell nothing is stored; if messages ever materialize, only the implementation moves.\n- **Messages got a natural key.** No rows means no surrogate ids, but the fold's shape gives one for free: `(turn, author side)` — deterministic across re-derivation, so `get` and future streaming reconciliation have something stable to address.\n- **Anomalies stay out of the query API.** A DB read doesn't fail because one row is odd — the service `tracing::warn!`s them; tests still assert-empty via the bare fold.\n- **Deferred:** the real Postgres adapter (belongs at the composition root — a generic wrapper over `AgentSessionLogRepo` can't prove `Send` since that trait doesn't bound its futures) and the `inbound/` comms adapter, per your earlier hold-off.\n\n12 tests + doctest green (fold suite, new service suite covering session scoping / get-by-id / service≡fold equivalence, recordings replay), strict clippy (`-Dwarnings`) clean, and `fold_recording` now exercises the full hexagon: recording → `InMemoryLogStore` → service → rendered turns.Two clear changes. Let me check what I need for both.",
@@ -3485,7 +2577,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01ViMoKt3zuuKcFvNgP3DzYR",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3500,21 +2594,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("echo \"=== channels deps (cycle check) ===\"; grep -n \"agent\\|^\\[\" crates/channels/Cargo.toml | head -20; echo \"=== ThreadInfo / CountedReaction / MessageAttachment pub? ===\"; sed -n '195,265p' crates/channels/src/domain/models.rs"),
- "description": String("Check channels deps and model constructibility"),
- },
- ),
- raw_output: Some(
- String("=== channels deps (cycle check) ===\n1:[package]\n7:[features]\n77:[dependencies]\n128:[dev-dependencies]\n=== ThreadInfo / CountedReaction / MessageAttachment pub? ===\n pub mentions: Vec<String>,\n}\n\nimpl SortOn<CreatedAt> for ChannelMessage {\n fn sort_on(sort_type: CreatedAt) -> impl FnMut(&Self) -> CursorVal<CreatedAt> {\n move |msg| CursorVal {\n sort_type,\n last_val: msg.created_at,\n }\n }\n}\n\n/// Thread metadata + preview replies for a top-level message.\n#[derive(Debug, Clone)]\npub struct ThreadInfo {\n /// Total number of replies in the thread.\n pub reply_count: i64,\n /// Timestamp of the most recent reply.\n pub latest_reply_at: Option<DateTime<Utc>>,\n /// Oldest N replies for the collapsed thread preview.\n pub preview: Vec<ThreadReply>,\n}\n\n/// A reply shown in a thread preview.\n#[derive(Debug, Clone)]\npub struct ThreadReply {\n /// Reply id.\n pub id: Uuid,\n /// User who sent the reply.\n pub sender_id: String,\n /// For an agent (bot) reply, the id of the user who triggered it.\n pub triggered_by: Option<String>,\n /// Bot profile when the sender is a bot.\n pub bot_profile: Option<BotSenderProfile>,\n /// Reply body.\n pub content: String,\n /// When the reply was created.\n pub created_at: DateTime<Utc>,\n /// When the reply was last updated.\n pub updated_at: DateTime<Utc>,\n /// When the reply was edited (if ever).\n pub edited_at: Option<DateTime<Utc>>,\n /// Aggregated reactions on this reply.\n pub reactions: Vec<CountedReaction>,\n /// Attachments on this reply.\n pub attachments: Vec<MessageAttachment>,\n}\n\n/// A reaction emoji with the list of users who reacted.\n#[derive(Debug, Clone, Serialize)]\npub struct CountedReaction {\n /// The emoji string.\n pub emoji: String,\n /// User ids who added this reaction.\n pub users: Vec<String>,\n}\n\n/// An attachment on a message.\n#[derive(Debug, Clone)]\npub struct MessageAttachment {\n /// Attachment id.\n pub id: Uuid,\n /// Type of attached entity (e.g. \"document\").\n pub entity_type: String,\n /// Id of the attached entity.\n pub entity_id: String,\n /// Optional width (for images).\n pub width: Option<i32>,\n /// Optional height (for images).\n pub height: Option<i32>,\n /// When the attachment was created."),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01V6p2sN3PN7mzJqbM5F4JSn",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3529,15 +2616,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("echo \"=== BotIdStr / ChannelSender ===\"; sed -n '1,60p' crates/channel_sender/src/lib.rs; echo \"=== bot_id ===\"; grep -n \"pub struct BotIdStr\\|pub fn\\|PREFIX\" crates/bot_id/src/lib.rs | head -15"),
- "description": String("Read channel_sender and bot_id APIs"),
- },
- ),
- raw_output: Some(
- String("=== BotIdStr / ChannelSender ===\n#![deny(missing_docs)]\n//! This crate defines the [ChannelSender] which is a wrapper type which denotes either a first party macro user, OR, a bot user\n\nuse bot_id::{BotId, BotIdStr, cowlike::CowLike};\nuse either::Either;\nuse macro_user_id::{error::ParseErr, user_id::MacroUserIdStr};\nuse serde::{Deserialize, Serialize};\n\n#[cfg(test)]\nmod test;\n\ntype InnerVal<'a> = Either<BotIdStr<'a>, MacroUserIdStr<'a>>;\n\n/// Actor identity for channel mutations.\n#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]\n#[serde(try_from = \"String\", into = \"String\")]\npub struct ChannelSender<'a>(pub InnerVal<'a>);\n\n#[cfg(feature = \"schema\")]\nimpl<'a> utoipa::ToSchema for ChannelSender<'a> {\n fn name() -> std::borrow::Cow<'static, str> {\n std::borrow::Cow::Borrowed(\"ChannelSender\")\n }\n}\n\n#[cfg(feature = \"schema\")]\nimpl<'a> utoipa::PartialSchema for ChannelSender<'a> {\n fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {\n String::schema()\n }\n}\n\nimpl<'a> TryFrom<&'a str> for ChannelSender<'a> {\n type Error = ParseErr;\n\n fn try_from(value: &'a str) -> Result<Self, Self::Error> {\n Self::parse_from_str(value)\n }\n}\n\nimpl TryFrom<String> for ChannelSender<'static> {\n type Error = ParseErr;\n\n fn try_from(value: String) -> Result<Self, Self::Error> {\n ChannelSender::parse_from_str(&value).map(CowLike::into_owned)\n }\n}\n\nimpl From<ChannelSender<'_>> for String {\n fn from(value: ChannelSender<'_>) -> Self {\n value.as_ref().to_string()\n }\n}\n\nimpl<'a> CowLike<'a> for ChannelSender<'a> {\n type Owned<'b> = ChannelSender<'b>;\n\n fn into_owned(self) -> Self::Owned<'static> {\n ChannelSender(self.0.into_owned())\n }\n=== bot_id ===\n20:const BOT_STORAGE_PREFIX: &str = \"bot\";\n36: let (rest, (((prefix, pipe), bot_id), _eof)) = tag(BOT_STORAGE_PREFIX)\n80: pub fn parse_uuid_str(value: &str) -> Result<Self, BotIdParseError> {\n87: pub fn into_storage_id(self) -> BotIdStr<'static> {\n88: let storage_id = format!(\"{BOT_STORAGE_PREFIX}|{}\", self.0);\n91: bot_id_part_offset: BOT_STORAGE_PREFIX.len() + 1,\n180: pub fn uuid_str(&self) -> &str {\n207: pub fn parse_from_str(input: &'a str) -> Result<Self, BotIdParseError> {\n218:pub struct BotIdStr<'a>(pub BotIdStorage<ArcCowStr<'a>>);\n240: pub fn parse_from_str(s: &'a str) -> Result<Self, BotIdParseError> {"),
- ),
},
Text {
text: "All pub and no cycle. Key discovery: `AgentSession` already carries `thread_id` and `bot_id` — that's the projection context.",
@@ -3546,7 +2624,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01MjmaSEP7KT1kHQ6hGUp3Ht",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3561,15 +2641,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n '^uuid' Cargo.toml; echo \"=== pg log repo impl ===\"; sed -n '235,290p' crates/agent_session/src/outbound/postgres/mod.rs; echo \"=== agent_session testing? ===\"; ls crates/agent_session/src/"),
- "description": String("Check uuid features and agent_session log repo impl"),
- },
- ),
- raw_output: Some(
- String("270:uuid = { version = \"1.15.1\", features = [\"fast-rng\", \"serde\", \"v4\", \"v5\", \"v7\"] }\n=== pg log repo impl ===\n })\n }\n}\n\nimpl AgentSessionLogRepo for PgAgentSessionRepo {\n async fn create(&self, log: AgentSessionLog) -> Result<()> {\n let (direction, content) = message_columns(&log.content)?;\n sqlx::query!(\n r#\"\n INSERT INTO agent_session_log (id, agent_session_id, user_id, direction, content)\n VALUES ($1, $2, $3, $4, $5)\n \"#,\n macro_uuid::generate_uuid_v7(),\n log.agent_session_id.as_uuid(),\n log.user_id.as_ref().map(|user_id| user_id.as_ref()),\n direction,\n content,\n )\n .execute(&self.pool)\n .await\n .context(\"failed to create agent session log entry\")?;\n\n Ok(())\n }\n\n async fn list_by_session(\n &self,\n agent_session_id: AgentSessionId,\n ) -> Result<Vec<AgentSessionLog>> {\n let rows = sqlx::query_as!(\n AgentSessionLogRow,\n r#\"\n SELECT agent_session_id, user_id AS \"user_id: MacroUserIdStr\", direction, content\n FROM agent_session_log\n WHERE agent_session_id = $1\n ORDER BY created_at ASC, id ASC\n \"#,\n agent_session_id.as_uuid(),\n )\n .fetch_all(&self.pool)\n .await\n .context(\"failed to list agent session log entries\")?;\n\n Ok(rows\n .into_iter()\n .map(TryInto::try_into)\n .collect::<anyhow::Result<Vec<_>>>()?)\n }\n}\n=== agent_session testing? ===\n\u{1b}[0m\u{1b}[01;34mdomain\u{1b}[0m\nlib.rs\n\u{1b}[01;34moutbound\u{1b}[0m"),
- ),
},
Text {
text: "Starting with `agent_session` — adding `Send` bounds so `agent_fold` can be generic over the port, plus an in-memory double for tests:",
@@ -3578,27 +2649,23 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01WUijwLfisYxcDCwUNk5bJe",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/src/domain/ports.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/src/domain/ports.rs"),
- },
- ),
- raw_output: Some(
- String("1\tuse super::error::Result;\n2\tuse super::model::*;\n3\t\n4\tpub trait AgentSessionRepo {\n5\t /// Create a new agent session, returning its id.\n6\t fn create(\n7\t &self,\n8\t session: AgentSession<UninitializedSession>,\n9\t ) -> impl Future<Output = Result<AgentSessionId>>;\n10\t\n11\t /// Get an agent session by id.\n12\t fn get(&self, id: AgentSessionId)\n13\t -> impl Future<Output = Result<AgentSession<AgentSessionId>>>;\n14\t\n15\t /// Update an existing agent session.\n16\t fn update(&self, session: AgentSession<AgentSessionId>) -> impl Future<Output = Result<()>>;\n17\t\n18\t /// Delete an agent session by id.\n19\t fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>>;\n20\t}\n21\t\n22\tpub trait AgentSessionLogRepo {\n23\t /// Append a new log entry to a session's history.\n24\t fn create(&self, log: AgentSessionLog) -> impl Future<Output = Result<()>>;\n25\t\n26\t /// List all log entries for a session, in chronological order.\n27\t fn list_by_session(\n28\t &self,\n29\t agent_session_id: AgentSessionId,\n30\t ) -> impl Future<Output = Result<Vec<AgentSessionLog>>>;\n31\t}\n32\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01G2v4zZ3pQjxgV9qhs1Xkwx",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3609,21 +2676,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/src/domain/ports.rs"),
- "content": String("use super::error::Result;\nuse super::model::*;\n\npub trait AgentSessionRepo {\n /// Create a new agent session, returning its id.\n fn create(\n &self,\n session: AgentSession<UninitializedSession>,\n ) -> impl Future<Output = Result<AgentSessionId>> + Send;\n\n /// Get an agent session by id.\n fn get(\n &self,\n id: AgentSessionId,\n ) -> impl Future<Output = Result<AgentSession<AgentSessionId>>> + Send;\n\n /// Update an existing agent session.\n fn update(\n &self,\n session: AgentSession<AgentSessionId>,\n ) -> impl Future<Output = Result<()>> + Send;\n\n /// Delete an agent session by id.\n fn delete(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;\n}\n\npub trait AgentSessionLogRepo {\n /// Append a new log entry to a session's history.\n fn create(&self, log: AgentSessionLog) -> impl Future<Output = Result<()>> + Send;\n\n /// List all log entries for a session, in chronological order.\n fn list_by_session(\n &self,\n agent_session_id: AgentSessionId,\n ) -> impl Future<Output = Result<Vec<AgentSessionLog>>> + Send;\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/src/domain/ports.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_017LSgehp1mrEeQpPyqunths",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3634,41 +2694,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/src/testing.rs"),
- "content": String("//! In-memory port implementations for tests.\n//!\n//! Lets crates that consume this one - the agent service, `agent_fold` -\n//! exercise their own logic against a real [`AgentSessionRepo`] /\n//! [`AgentSessionLogRepo`] contract without a database.\n\nuse crate::domain::error::{AgentSessionError, Result};\nuse crate::domain::model::{AgentSession, AgentSessionId, AgentSessionLog, UninitializedSession};\nuse crate::domain::ports::{AgentSessionLogRepo, AgentSessionRepo};\nuse std::collections::HashMap;\nuse std::sync::{Arc, Mutex};\n\n/// An in-memory [`AgentSessionRepo`] and [`AgentSessionLogRepo`].\n///\n/// Cheap to clone - clones share one store, so a handle kept for assertions\n/// sees writes made through the copy under test. Log entries are returned in\n/// insertion order, which is the chronology the real repo gets from\n/// `ORDER BY created_at, id`.\n#[derive(Debug, Clone, Default)]\npub struct InMemoryAgentSessionRepo {\n sessions: Arc<Mutex<HashMap<AgentSessionId, AgentSession<AgentSessionId>>>>,\n logs: Arc<Mutex<HashMap<AgentSessionId, Vec<AgentSessionLog>>>>,\n}\n\nimpl InMemoryAgentSessionRepo {\n /// An empty store.\n #[must_use]\n pub fn new() -> Self {\n Self::default()\n }\n\n /// Seed a session, bypassing [`AgentSessionRepo::create`] so a test can\n /// choose the id it will query by.\n pub fn insert_session(&self, session: AgentSession<AgentSessionId>) {\n self.sessions\n .lock()\n .expect(\"in-memory session store is not poisoned\")\n .insert(session.id, session);\n }\n\n /// Seed log entries, in the order they should be read back.\n pub fn extend_log(&self, entries: impl IntoIterator<Item = AgentSessionLog>) {\n let mut logs = self\n .logs\n .lock()\n .expect(\"in-memory log store is not poisoned\");\n for entry in entries {\n logs.entry(entry.agent_session_id).or_default().push(entry);\n }\n }\n}\n\nimpl FromIterator<AgentSessionLog> for InMemoryAgentSessionRepo {\n fn from_iter<I: IntoIterator<Item = AgentSessionLog>>(entries: I) -> Self {\n let repo = Self::new();\n repo.extend_log(entries);\n repo\n }\n}\n\nimpl AgentSessionRepo for InMemoryAgentSessionRepo {\n async fn create(\n &self,\n session: AgentSession<UninitializedSession>,\n ) -> Result<AgentSessionId> {\n let id = AgentSessionId::new_from_uuid(macro_uuid::generate_uuid_v7());\n self.insert_session(AgentSession {\n id,\n created_from_thread_id: session.created_from_thread_id,\n thread_id: session.thread_id,\n bot_id: session.bot_id,\n model: session.model,\n harness: session.harness,\n repo_url: session.repo_url,\n acp_session_id: session.acp_session_id,\n status: session.status,\n created_at: session.created_at,\n modified_at: session.modified_at,\n });\n Ok(id)\n }\n\n async fn get(&self, id: AgentSessionId) -> Result<AgentSession<AgentSessionId>> {\n self.sessions\n .lock()\n .expect(\"in-memory session store is not poisoned\")\n .get(&id)\n .cloned()\n .ok_or_else(|| {\n AgentSessionError::Unknown(anyhow::anyhow!(\"no agent session {}\", id.as_uuid()))\n })\n }\n\n async fn update(&self, session: AgentSession<AgentSessionId>) -> Result<()> {\n self.insert_session(session);\n Ok(())\n }\n\n async fn delete(&self, id: AgentSessionId) -> Result<()> {\n self.sessions\n .lock()\n .expect(\"in-memory session store is not poisoned\")\n .remove(&id);\n self.logs\n .lock()\n .expect(\"in-memory log store is not poisoned\")\n .remove(&id);\n Ok(())\n }\n}\n\nimpl AgentSessionLogRepo for InMemoryAgentSessionRepo {\n async fn create(&self, log: AgentSessionLog) -> Result<()> {\n self.extend_log([log]);\n Ok(())\n }\n\n async fn list_by_session(\n &self,\n agent_session_id: AgentSessionId,\n ) -> Result<Vec<AgentSessionLog>> {\n Ok(self\n .logs\n .lock()\n .expect(\"in-memory log store is not poisoned\")\n .get(&agent_session_id)\n .cloned()\n .unwrap_or_default())\n }\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_session/src/testing.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01BpevjmhnXXC1vjLTfjVYhi",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/src/lib.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/src/lib.rs"),
- },
- ),
- raw_output: Some(
- String("1\tpub mod domain;\n2\tpub mod outbound;\n3\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_0162xMTspmR7TWbjaVwiPtnA",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3679,41 +2726,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/src/lib.rs"),
- "content": String("pub mod domain;\npub mod outbound;\n\n/// In-memory port implementations for tests.\n#[cfg(any(test, feature = \"test-utils\"))]\npub mod testing;\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/src/lib.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01KN8bsa7eqWdQg8VgPK9bLM",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_session/Cargo.toml",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/Cargo.toml"),
- },
- ),
- raw_output: Some(
- String("1\t[package]\n2\tname = \"agent_session\"\n3\tversion = \"0.1.0\"\n4\tedition = \"2024\"\n5\t\n6\t[dependencies]\n7\t\n8\tmacro_uuid = { path = \"../macro_uuid\" }\n9\tagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\n10\tbots = { path = \"../bots\"}\n11\tmacro_user_id = { path = \"../macro_user_id\", features = [\"sqlx\"] }\n12\tsqlx = { workspace = true }\n13\tchrono = { workspace = true }\n14\tthiserror = { workspace = true }\n15\tanyhow = { workspace = true }\n16\tserde_json = { workspace = true }\n17\tworkspace-hack = { version = \"0.1\", path = \"../workspace-hack\" }\n18\t\n19\t[dev-dependencies]\n20\tagent-client-protocol = { workspace = true }\n21\tmacro_db_migrator = { path = \"../macro_db_migrator\" }\n22\ttokio = { workspace = true, features = [\"macros\", \"rt-multi-thread\"] }\n23\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01EhNCTkY3nVcQebEeDHV67s",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3726,23 +2760,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_session/Cargo.toml"),
- "old_string": String("edition = \"2024\"\n\n[dependencies]\n"),
- "new_string": String("edition = \"2024\"\n\n[features]\n# In-memory port implementations, for crates that test against this one.\ntest-utils = []\n\n[dependencies]\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_session/Cargo.toml has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01P67JqV5GnJHzy3JCWGXkkM",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3757,16 +2782,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo check -p agent_session --all-features 2>&1 | grep -E \"^error|^warning|-->\" | head -20; echo \"--- done ---\""),
- "description": String("Check agent_session with new Send bounds and testing module"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String("--- done ---"),
- ),
},
Text {
text: "`agent_session` compiles with `Send` bounds. Now `agent_fold`'s domain — drop the redundant port and the outbound store:",
@@ -3775,7 +2790,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01H5oHnUt1DJMkWRhNX3XWTk",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3786,21 +2803,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/ports.rs"),
- "content": String("//! The crate's driving port.\n//!\n//! [`FoldedMessageRepo`] is the query API the rest of the system calls. It is\n//! deliberately shaped like a repository over stored rows - list a session's\n//! messages, get one by id - even though nothing is stored: the service\n//! behind it derives every answer from the protocol log on each call.\n//! Callers should not be able to tell, and the day the messages *are*\n//! materialized somewhere, only the implementation moves.\n//!\n//! There is no driven port here. The one capability this domain needs from\n//! the outside - reading a session's log - is already a port on the crate\n//! that owns that log: [`agent_session::domain::ports::AgentSessionLogRepo`].\n//! Re-declaring it would be a second name for one contract.\n\nuse crate::domain::message::{FoldedMessage, MessageId};\nuse agent_session::domain::model::AgentSessionId;\n\n/// Query a session's messages as if they were stored.\npub trait FoldedMessageRepo {\n /// A session's messages, oldest first. A session with no log folds to no\n /// messages.\n fn list_by_session(\n &self,\n session: AgentSessionId,\n ) -> impl Future<Output = Result<Vec<FoldedMessage>, rootcause::Report>> + Send;\n\n /// One message by its natural key, or `None` when the session's log\n /// derives no such message.\n fn get(\n &self,\n session: AgentSessionId,\n id: MessageId,\n ) -> impl Future<Output = Result<Option<FoldedMessage>, rootcause::Report>> + Send;\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/ports.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Wy46G7qjy4czVSD94ficqs",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3811,15 +2821,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service.rs"),
- "content": String("//! The domain service implementing the query port.\n//!\n//! [`FoldedMessageService`] is the \"query engine\" of the pretend store: every\n//! query loads the session's log through\n//! [`AgentSessionLogRepo`](agent_session::domain::ports::AgentSessionLogRepo)\n//! and runs the fold. Anomalies the fold reports are logged as warnings\n//! rather than surfaced to callers - a query against a store should not fail\n//! because one frame was strange - so the only error a query can return is a\n//! failure to load the log itself.\n\nuse crate::domain::fold;\nuse crate::domain::message::{FoldedMessage, MessageId};\nuse crate::domain::ports::FoldedMessageRepo;\nuse agent_session::domain::model::AgentSessionId;\nuse agent_session::domain::ports::AgentSessionLogRepo;\n\n#[cfg(test)]\nmod test;\n\n/// Serves [`FoldedMessageRepo`] queries by folding the session log on read.\n#[derive(Debug, Clone)]\npub struct FoldedMessageService<Logs> {\n logs: Logs,\n}\n\nimpl<Logs> FoldedMessageService<Logs> {\n /// A service answering queries from the given log repo.\n pub fn new(logs: Logs) -> Self {\n Self { logs }\n }\n}\n\nimpl<Logs> FoldedMessageService<Logs>\nwhere\n Logs: AgentSessionLogRepo + Sync,\n{\n /// Load and fold a session's log, reporting anomalies as warnings.\n async fn fold_session(\n &self,\n session: AgentSessionId,\n ) -> Result<Vec<FoldedMessage>, rootcause::Report> {\n let log = self\n .logs\n .list_by_session(session)\n .await\n .map_err(|error| rootcause::report!(error))?;\n\n let folded = fold::fold(log);\n for anomaly in &folded.anomalies {\n tracing::warn!(\n anomaly = ?anomaly,\n session = ?session,\n \"agent session log frame could not be folded\"\n );\n }\n Ok(folded.messages)\n }\n}\n\nimpl<Logs> FoldedMessageRepo for FoldedMessageService<Logs>\nwhere\n Logs: AgentSessionLogRepo + Sync,\n{\n #[tracing::instrument(err, skip(self))]\n async fn list_by_session(\n &self,\n session: AgentSessionId,\n ) -> Result<Vec<FoldedMessage>, rootcause::Report> {\n self.fold_session(session).await\n }\n\n #[tracing::instrument(err, skip(self))]\n async fn get(\n &self,\n session: AgentSessionId,\n id: MessageId,\n ) -> Result<Option<FoldedMessage>, rootcause::Report> {\n let messages = self.fold_session(session).await?;\n Ok(messages.into_iter().find(|message| message.id() == id))\n }\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/service.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the inbound comms adapter — the concrete fold to channel messages:",
@@ -3828,7 +2829,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01AuAyJPSM8diHAMvejhMks6",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3839,21 +2842,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/inbound/mod.rs"),
- "content": String("//! Adapters that drive the domain and render its messages outward.\n//!\n//! The domain's [`FoldedMessage`](crate::domain::message::FoldedMessage) is\n//! deliberately its own vocabulary: it knows about turns, tool calls and\n//! permissions, and nothing about how any particular surface displays them.\n//! Adapters here convert it into the representation their surface speaks.\n\n/// Rendering folded messages as comms channel messages.\npub mod comms_message;\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/inbound/mod.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01XXo9AEBcVSza4qjTAfqzN3",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3868,21 +2864,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("grep -n \"pub struct BotSenderProfile\" -A 8 crates/channels/src/domain/models.rs; echo \"=== BotId api ===\"; grep -n \"impl BotId\\b\" -A 20 crates/bot_id/src/lib.rs | grep -n \"pub fn\" ; sed -n '70,95p' crates/bot_id/src/lib.rs"),
- "description": String("Check BotSenderProfile and BotId storage id API"),
- },
- ),
- raw_output: Some(
- String("25:pub struct BotSenderProfile {\n26- /// Bot display name.\n27- pub name: String,\n28- /// Bot avatar URL.\n29- pub avatar_url: Option<String>,\n30-}\n31-\n32-/// Request to fetch a page of channel messages.\n33-#[derive(Debug)]\n=== BotId api ===\n13:80- pub fn parse_uuid_str(value: &str) -> Result<Self, BotIdParseError> {\n20:87- pub fn into_storage_id(self) -> BotIdStr<'static> {\n pub const fn new_from_uuid(id: Uuid) -> Self {\n Self(id)\n }\n\n /// Return the underlying UUID.\n pub const fn as_uuid(self) -> Uuid {\n self.0\n }\n\n /// Parse a bot id from its UUID string representation.\n pub fn parse_uuid_str(value: &str) -> Result<Self, BotIdParseError> {\n Uuid::parse_str(value)\n .map(Self)\n .map_err(|_| BotIdParseError::invalid(value))\n }\n\n /// Canonical storage representation as a parsed [`BotIdStr`].\n pub fn into_storage_id(self) -> BotIdStr<'static> {\n let storage_id = format!(\"{BOT_STORAGE_PREFIX}|{}\", self.0);\n BotIdStr(BotIdStorage {\n bot_id: self,\n bot_id_part_offset: BOT_STORAGE_PREFIX.len() + 1,\n storage_id: ArcCowStr::Owned(storage_id.into()),\n })\n }\n}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Bh7uu1nLRfo8xoMyGFcKSx",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3893,21 +2882,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs"),
- "content": String("//! The fold from Agent Runtime Protocol traffic to comms channel messages.\n//!\n//! This is where the two halves meet. The domain folds a protocol log into\n//! its own vocabulary; this adapter renders that vocabulary as\n//! [`ChannelMessage`], the shape a channel already knows how to display. The\n//! domain never names a comms type, so the coupling lives here and only here.\n//!\n//! # The lossy part\n//!\n//! `comms_messages.content` is a single `text` column and\n//! [`ChannelMessage::content`] is a `String`, so structure has to be flattened\n//! into markdown: tool calls become fenced blocks, thoughts a blockquote,\n//! permissions a one-line note. That loses the collapsible tool rows, diff\n//! rendering and live status a reader would want.\n//!\n//! It is the right lossy choice *for now*, because it renders today with no\n//! schema change and no frontend work. When a comms message can carry\n//! structured parts, this module is the only thing that changes - swap\n//! [`render_markdown`] for a mapping onto that representation and the domain,\n//! the fold and every test above it stay put.\n\nuse crate::domain::message::{\n AuthorKind, FoldedMessage, MessagePart, Permission, PermissionOutcome, StopReason, ToolDetail,\n ToolStatus, ToolUse,\n};\nuse crate::domain::ports::FoldedMessageRepo;\nuse agent_session::domain::model::{AgentSession, AgentSessionId};\nuse agent_session::domain::ports::AgentSessionRepo;\nuse bot_id::BotId;\nuse channels::domain::models::{BotSenderProfile, ChannelMessage, ThreadInfo};\nuse chrono::{DateTime, Utc};\nuse macro_uuid::Uuid;\n\n#[cfg(test)]\nmod test;\n\n/// The namespace for deriving stable message ids.\n///\n/// A folded message has no stored row and therefore no id of its own, but a\n/// channel message needs one - and needs the *same* one on every read, or\n/// clients would treat each poll as a batch of new messages. Deriving it as a\n/// v5 (name-based) uuid from the session and the message's natural key makes\n/// the id a pure function of the log, exactly like the messages themselves.\nconst MESSAGE_ID_NAMESPACE: Uuid = Uuid::from_bytes([\n 0x6a, 0x67, 0x65, 0x6e, 0x74, 0x2d, 0x66, 0x6f, 0x6c, 0x64, 0x2d, 0x6d, 0x73, 0x67, 0x00, 0x01,\n]);\n\n/// What a folded message needs in order to look like a channel message.\n///\n/// Everything here comes off the [`AgentSession`] itself, which already knows\n/// the comms thread it belongs to and the bot running it - see\n/// [`context_for_session`].\n#[derive(Debug, Clone)]\npub struct CommsContext {\n /// The session being rendered.\n pub session: AgentSessionId,\n /// The channel the session's thread lives in.\n pub channel_id: Uuid,\n /// The bot posting the agent's side of the conversation.\n pub bot: BotId,\n /// Display name and avatar for that bot.\n pub bot_profile: Option<BotSenderProfile>,\n /// Storage id of the user whose prompts opened the turns, used when a\n /// prompt was logged without one.\n pub fallback_user_id: Option<String>,\n}\n\n/// Read the rendering context off a session record.\n///\n/// The session is the source of truth for both the thread it posts into and\n/// the bot it speaks as, so callers should not have to supply either.\npub async fn context_for_session<Sessions>(\n sessions: &Sessions,\n session: AgentSessionId,\n) -> Result<CommsContext, rootcause::Report>\nwhere\n Sessions: AgentSessionRepo + Sync,\n{\n let record: AgentSession<AgentSessionId> = sessions\n .get(session)\n .await\n .map_err(|error| rootcause::report!(error))?;\n\n Ok(CommsContext {\n session,\n channel_id: record.thread_id,\n bot: record.bot_id,\n bot_profile: None,\n fallback_user_id: None,\n })\n}\n\n/// Render a session's folded messages as channel messages.\n///\n/// The composed fold: protocol log in, comms messages out.\n#[tracing::instrument(err, skip(messages))]\npub async fn list_as_channel_messages<Messages>(\n messages: &Messages,\n context: &CommsContext,\n) -> Result<Vec<ChannelMessage>, rootcause::Report>\nwhere\n Messages: FoldedMessageRepo + Sync,\n{\n let folded = messages.list_by_session(context.session).await?;\n Ok(folded\n .into_iter()\n .map(|message| to_channel_message(context, message))\n .collect())\n}\n\n/// Render one folded message as a channel message.\n///\n/// Timestamps are the one thing the fold cannot supply: `agent_session_log`\n/// has a `created_at` per frame, but\n/// [`AgentSessionLog`](agent_session::domain::model::AgentSessionLog) does not\n/// carry it, so there is nothing truthful to put here. Both stamps are left\n/// at the epoch rather than invented from the wall clock, which would make\n/// every read report a different time. Threading a frame timestamp through the\n/// log model is the fix.\n#[must_use]\npub fn to_channel_message(context: &CommsContext, message: FoldedMessage) -> ChannelMessage {\n let id = derive_message_id(context.session, &message);\n let is_agent = message.author.kind() == AuthorKind::Agent;\n\n let sender_id = match &message.author {\n crate::domain::message::Author::User(user) => user\n .as_ref()\n .map(ToString::to_string)\n .or_else(|| context.fallback_user_id.clone())\n .unwrap_or_default(),\n crate::domain::message::Author::Agent => {\n context.bot.into_storage_id().as_ref().to_string()\n }\n };\n\n ChannelMessage {\n id,\n channel_id: context.channel_id,\n sender_id,\n // The user who prompted the turn is what a reader wants attributed\n // here, and only the agent's own messages carry that relationship.\n triggered_by: is_agent.then(|| context.fallback_user_id.clone()).flatten(),\n bot_profile: is_agent.then(|| context.bot_profile.clone()).flatten(),\n content: render_markdown(&message),\n created_at: DateTime::<Utc>::UNIX_EPOCH,\n updated_at: DateTime::<Utc>::UNIX_EPOCH,\n edited_at: None,\n deleted_at: None,\n thread: ThreadInfo {\n reply_count: 0,\n latest_reply_at: None,\n preview: Vec::new(),\n },\n reactions: Vec::new(),\n attachments: Vec::new(),\n }\n}\n\n/// The stable id for a folded message within its session.\nfn derive_message_id(session: AgentSessionId, message: &FoldedMessage) -> Uuid {\n let key = message.id();\n let author = match key.author {\n AuthorKind::User => \"user\",\n AuthorKind::Agent => \"agent\",\n };\n let name = format!(\"{}:{}:{author}\", session.as_uuid(), key.turn.0);\n Uuid::new_v5(&MESSAGE_ID_NAMESPACE, name.as_bytes())\n}\n\n/// Flatten a folded message's parts into markdown.\n#[must_use]\npub fn render_markdown(message: &FoldedMessage) -> String {\n let mut blocks: Vec<String> = Vec::new();\n\n for part in message.parts.iter() {\n match part {\n MessagePart::Text(text) => blocks.push(text.trim().to_owned()),\n MessagePart::Thought(text) => blocks.push(render_thought(text)),\n MessagePart::ToolUse(tool) => blocks.push(render_tool(tool)),\n MessagePart::Permission(permission) => blocks.push(render_permission(permission)),\n }\n }\n\n if let Some(note) = stop_note(message.stop.as_ref()) {\n blocks.push(note);\n }\n\n blocks.retain(|block| !block.is_empty());\n blocks.join(\"\\n\\n\")\n}\n\n/// Reasoning as a blockquote, so it reads as an aside.\nfn render_thought(text: &str) -> String {\n text.trim()\n .lines()\n .map(|line| format!(\"> {line}\"))\n .collect::<Vec<_>>()\n .join(\"\\n\")\n}\n\n/// A tool call as a status line plus whatever detail it produced.\nfn render_tool(tool: &ToolUse) -> String {\n let mut out = format!(\"{} **{}**\", status_marker(tool.status), tool.label);\n\n match &tool.detail {\n ToolDetail::Terminal {\n command,\n output,\n exit_code,\n } => {\n if let Some(command) = command {\n out.push_str(&format!(\"\\n\\n```sh\\n{}\\n```\", command.trim()));\n }\n if let Some(output) = output {\n let text = strip_ansi(output.as_str());\n if !text.trim().is_empty() {\n out.push_str(&format!(\"\\n\\n```\\n{}\\n```\", text.trim_end()));\n }\n }\n // A zero exit is the unremarkable case; only note failures.\n if let Some(code) = exit_code.filter(|code| *code != 0) {\n out.push_str(&format!(\"\\n\\nexited with {code}\"));\n }\n }\n ToolDetail::Edit { diffs } => {\n for diff in diffs {\n out.push_str(&format!(\"\\n\\n`{}`\", diff.path.display()));\n out.push_str(&format!(\"\\n\\n```diff\\n{}\\n```\", render_diff_body(diff)));\n }\n }\n ToolDetail::Read { paths } => {\n for path in paths {\n out.push_str(&format!(\"\\n\\n`{}`\", path.display()));\n }\n }\n ToolDetail::Other { kind, input } => {\n out.push_str(&format!(\" _({kind})_\"));\n if let Some(input) = input {\n if let Ok(pretty) = serde_json::to_string_pretty(input) {\n if pretty != \"{}\" {\n out.push_str(&format!(\"\\n\\n```json\\n{pretty}\\n```\"));\n }\n }\n }\n }\n }\n\n out\n}\n\n/// A diff as `-`/`+` lines. Not a real unified diff - there are no hunk\n/// headers to compute from old/new text alone - but it renders in a `diff`\n/// fence and reads correctly.\nfn render_diff_body(diff: &crate::domain::message::FileDiff) -> String {\n let mut body = String::new();\n if let Some(old) = &diff.old_text {\n for line in old.lines() {\n body.push_str(&format!(\"-{line}\\n\"));\n }\n }\n for line in diff.new_text.lines() {\n body.push_str(&format!(\"+{line}\\n\"));\n }\n body.trim_end().to_owned()\n}\n\n/// A permission request and how it went.\nfn render_permission(permission: &Permission) -> String {\n match &permission.outcome {\n Some(PermissionOutcome::Selected { option_id }) => {\n let name = permission\n .options\n .iter()\n .find(|option| &option.id == option_id)\n .map_or(option_id.as_str(), |option| option.name.as_str());\n format!(\"_Permission requested — {name}._\")\n }\n Some(PermissionOutcome::Cancelled) => \"_Permission request cancelled._\".to_owned(),\n None => \"_Waiting for permission…_\".to_owned(),\n }\n}\n\n/// A note for turns that ended in something other than a clean finish.\nfn stop_note(stop: Option<&StopReason>) -> Option<String> {\n match stop? {\n // The ordinary ending needs no annotation.\n StopReason::EndTurn => None,\n StopReason::MaxTokens => Some(\"_Stopped: token limit reached._\".to_owned()),\n StopReason::MaxTurnRequests => Some(\"_Stopped: turn limit reached._\".to_owned()),\n StopReason::Refusal => Some(\"_The agent declined to continue._\".to_owned()),\n StopReason::Cancelled => Some(\"_Cancelled._\".to_owned()),\n StopReason::Other(reason) => Some(format!(\"_Stopped: {reason}._\")),\n }\n}\n\nfn status_marker(status: ToolStatus) -> &'static str {\n match status {\n ToolStatus::Pending => \"◦\",\n ToolStatus::Running => \"◍\",\n ToolStatus::Completed => \"●\",\n ToolStatus::Failed => \"✕\",\n }\n}\n\n/// Drop ANSI escape sequences.\n///\n/// The domain preserves them deliberately - stripping is lossy and\n/// irreversible - but markdown has no way to render them, so the flattening\n/// adapter is where they go. A structured representation would keep them and\n/// let the client decide.\n#[must_use]\npub fn strip_ansi(text: &str) -> String {\n let mut out = String::with_capacity(text.len());\n let mut chars = text.chars();\n\n while let Some(character) = chars.next() {\n if character != '\\u{1b}' {\n out.push(character);\n continue;\n }\n // CSI sequences (`ESC [ … final`) are all that terminal output uses\n // here; a final byte in `@`..=`~` ends one.\n match chars.next() {\n Some('[') => {\n for parameter in chars.by_ref() {\n if ('@'..='~').contains(&parameter) {\n break;\n }\n }\n }\n // A bare or unrecognized escape: drop the escape itself and keep\n // whatever followed.\n Some(other) => out.push(other),\n None => break,\n }\n }\n\n out\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01PMRbR5KWC4FYDKXNoz4GRT",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3918,21 +2900,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/lib.rs"),
- "content": String("#![deny(missing_docs)]\n//! Folds an agent session's protocol log into renderable messages, and\n//! serves them as if they were stored.\n//!\n//! An agent session is recorded as a flat log of Agent Runtime Protocol\n//! frames - `agent_session_log`, modelled by\n//! [`agent_session::domain::model::AgentSessionLog`]. That log is faithful\n//! but unreadable: a single session is hundreds of streamed chunks,\n//! tool-call patches and token-usage reports. This crate collapses it into\n//! the handful of messages a person would recognize as the story of the\n//! session.\n//!\n//! Nothing here is persisted. The fiction of the crate is that folded\n//! messages live in a database: [`domain::ports::FoldedMessageRepo`] is a\n//! repository-shaped query API, and\n//! [`domain::service::FoldedMessageService`] answers it by loading the log\n//! through [`agent_session::domain::ports::AgentSessionLogRepo`] and folding\n//! on every read. Because the messages are re-derived each time, the\n//! vocabulary in [`domain::message`] can change without a migration.\n//!\n//! The domain speaks only its own vocabulary - turns, tool calls,\n//! permissions - and names no display type. Rendering it as something a\n//! surface can show is an adapter's job: [`inbound::comms_message`] is the\n//! fold from protocol traffic to comms channel messages.\n//!\n//! ```no_run\n//! use agent_fold::domain::ports::FoldedMessageRepo;\n//! use agent_fold::domain::service::FoldedMessageService;\n//! use agent_fold::inbound::comms_message::{context_for_session, list_as_channel_messages};\n//! use agent_session::domain::model::AgentSessionId;\n//! use agent_session::domain::ports::{AgentSessionLogRepo, AgentSessionRepo};\n//!\n//! # async fn run<R>(repo: R, session: AgentSessionId) -> Result<(), rootcause::Report>\n//! # where R: AgentSessionRepo + AgentSessionLogRepo + Clone + Sync {\n//! // Query the domain's own messages...\n//! let messages = FoldedMessageService::new(repo.clone());\n//! for message in messages.list_by_session(session).await? {\n//! println!(\"{:?} said {} part(s)\", message.author, message.parts.len());\n//! }\n//!\n//! // ...or render them as channel messages.\n//! let context = context_for_session(&repo, session).await?;\n//! let channel_messages = list_as_channel_messages(&messages, &context).await?;\n//! # let _ = channel_messages;\n//! # Ok(())\n//! # }\n//! ```\n\n/// Domain models, the fold, and the query port.\npub mod domain;\n/// Adapters that drive the domain and render its messages outward.\npub mod inbound;\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/lib.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_018LWRjGQsDrxskD5U9BHKzP",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -3947,15 +2922,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd crates/agent_fold && rm -rf src/outbound && cat > /tmp/cargo_agent_fold.toml <<'EOF'\n[package]\nedition = \"2024\"\nname = \"agent_fold\"\npublish = false\nversion = \"0.1.0\"\n\n[dependencies]\nagent-client-protocol = { workspace = true }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nagent_session = { path = \"../agent_session\" }\nbot_id = { path = \"../bot_id\" }\nchannels = { path = \"../channels\" }\nchrono = { workspace = true }\nmacro_user_id = { path = \"../macro_user_id\" }\nmacro_uuid = { path = \"../macro_uuid\" }\nnon_empty = { path = \"../non_empty\" }\nrootcause = { workspace = true }\nserde_json = { workspace = true }\ntracing = { workspace = true }\n\n[dev-dependencies]\nagent_session = { path = \"../agent_session\", features = [\"test-utils\"] }\ntokio = { workspace = true, features = [\"macros\", \"rt-multi-thread\"] }\nEOF\ncp /tmp/cargo_agent_fold.toml Cargo.toml && cat Cargo.toml"),
- "description": String("Remove outbound, update Cargo.toml deps"),
- },
- ),
- raw_output: Some(
- String("[package]\nedition = \"2024\"\nname = \"agent_fold\"\npublish = false\nversion = \"0.1.0\"\n\n[dependencies]\nagent-client-protocol = { workspace = true }\nagent_runtime_protocol = { path = \"../agent_runtime_protocol\" }\nagent_session = { path = \"../agent_session\" }\nbot_id = { path = \"../bot_id\" }\nchannels = { path = \"../channels\" }\nchrono = { workspace = true }\nmacro_user_id = { path = \"../macro_user_id\" }\nmacro_uuid = { path = \"../macro_uuid\" }\nnon_empty = { path = \"../non_empty\" }\nrootcause = { workspace = true }\nserde_json = { workspace = true }\ntracing = { workspace = true }\n\n[dev-dependencies]\nagent_session = { path = \"../agent_session\", features = [\"test-utils\"] }\ntokio = { workspace = true, features = [\"macros\", \"rt-multi-thread\"] }"),
- ),
},
Text {
text: "Now update the tests to use `agent_session`'s in-memory repo, and add tests for the comms adapter:",
@@ -3964,7 +2930,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01UEdswQzxRbnKYNpVkXJw1j",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -3977,23 +2945,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs"),
- "old_string": String("//! Shared helpers for tests: parsing recorded protocol frames into log rows.\n\nuse agent_session::domain::model::{AgentSessionId, AgentSessionLog, Message};\nuse macro_user_id::user_id::MacroUserIdStr;"),
- "new_string": String("//! Shared helpers for tests: parsing recorded protocol frames into log rows.\n\nuse agent_session::domain::model::{\n AgentSession, AgentSessionId, AgentSessionLog, Message, SessionStatus,\n};\nuse agent_session::testing::InMemoryAgentSessionRepo;\nuse bot_id::BotId;\nuse chrono::{DateTime, Utc};\nuse macro_user_id::user_id::MacroUserIdStr;\nuse macro_uuid::Uuid;"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01R9Jjdxeuv6xS8p6A9wgovX",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4006,44 +2965,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs"),
- "old_string": String("/// Parse a whole recording into [`test_session`]'s log.\npub fn parse_log(jsonl: &str) -> Vec<AgentSessionLog> {\n parse_log_as(test_session(), jsonl)\n}"),
- "new_string": String("/// Parse a whole recording into [`test_session`]'s log.\npub fn parse_log(jsonl: &str) -> Vec<AgentSessionLog> {\n parse_log_as(test_session(), jsonl)\n}\n\n/// The bot the test session runs as.\npub fn test_bot() -> BotId {\n BotId::new_from_uuid(Uuid::from_u128(0xb0t))\n}\n\n/// The comms thread the test session posts into.\npub fn test_thread() -> Uuid {\n Uuid::from_u128(0xf00d)\n}\n\n/// A session record for [`test_session`], as\n/// [`AgentSessionRepo`](agent_session::domain::ports::AgentSessionRepo) would\n/// return it.\npub fn test_session_record(id: AgentSessionId) -> AgentSession<AgentSessionId> {\n AgentSession {\n id,\n created_from_thread_id: None,\n thread_id: test_thread(),\n bot_id: test_bot(),\n model: \"claude-opus-5\".to_owned(),\n harness: \"claude-code\".to_owned(),\n repo_url: \"https://github.com/example/repo\".to_owned(),\n acp_session_id: None,\n status: SessionStatus::NoMessages,\n created_at: DateTime::<Utc>::UNIX_EPOCH,\n modified_at: DateTime::<Utc>::UNIX_EPOCH,\n }\n}\n\n/// A repo seeded with the given sessions' logs and session records.\npub fn seeded_repo(\n logs: impl IntoIterator<Item = AgentSessionLog>,\n) -> InMemoryAgentSessionRepo {\n let repo: InMemoryAgentSessionRepo = logs.into_iter().collect();\n repo\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_013eZ4p21vhq6MtS54fXnYp9",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "limit": Number(30),
- },
- ),
- raw_output: Some(
- String("1\tuse super::*;\n2\tuse crate::domain::message::{AuthorKind, TurnId};\n3\tuse crate::domain::ports::SessionLogStore;\n4\tuse crate::domain::test_support::{TURN, parse_log_as, test_session};\n5\tuse crate::outbound::memory::InMemoryLogStore;\n6\tuse agent_session::domain::model::AgentSessionId;\n7\t\n8\tfn other_session() -> AgentSessionId {\n9\t AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(2))\n10\t}\n11\t\n12\t/// A store holding two sessions: the full fixture, and a second session cut\n13\t/// off mid-turn.\n14\tfn two_session_store() -> InMemoryLogStore {\n15\t let mut second = parse_log_as(other_session(), TURN);\n16\t second.truncate(9);\n17\t\n18\t parse_log_as(test_session(), TURN)\n19\t .into_iter()\n20\t .chain(second)\n21\t .collect()\n22\t}\n23\t\n24\t/// Queries answer per session: each session's log folds independently, and\n25\t/// a session nothing was logged for is simply empty - the same answer a\n26\t/// database would give.\n27\t#[tokio::test]\n28\tasync fn queries_are_scoped_to_a_session() {\n29\t let service = FoldedMessageService::new(two_session_store());\n30\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01As3awcCaWRFSbEeQoe4jUo",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4056,44 +2999,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "old_string": String("use super::*;\nuse crate::domain::message::{AuthorKind, TurnId};\nuse crate::domain::ports::SessionLogStore;\nuse crate::domain::test_support::{TURN, parse_log_as, test_session};\nuse crate::outbound::memory::InMemoryLogStore;\nuse agent_session::domain::model::AgentSessionId;\n\nfn other_session() -> AgentSessionId {\n AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(2))\n}\n\n/// A store holding two sessions: the full fixture, and a second session cut\n/// off mid-turn.\nfn two_session_store() -> InMemoryLogStore {\n let mut second = parse_log_as(other_session(), TURN);\n second.truncate(9);\n\n parse_log_as(test_session(), TURN)\n .into_iter()\n .chain(second)\n .collect()\n}"),
- "new_string": String("use super::*;\nuse crate::domain::message::{AuthorKind, TurnId};\nuse crate::domain::test_support::{TURN, parse_log_as, test_session};\nuse agent_session::testing::InMemoryAgentSessionRepo;\n\nfn other_session() -> AgentSessionId {\n AgentSessionId::new_from_uuid(macro_uuid::Uuid::from_u128(2))\n}\n\n/// A repo holding two sessions: the full fixture, and a second session cut\n/// off mid-turn.\nfn two_session_store() -> InMemoryAgentSessionRepo {\n let mut second = parse_log_as(other_session(), TURN);\n second.truncate(9);\n\n parse_log_as(test_session(), TURN)\n .into_iter()\n .chain(second)\n .collect()\n}"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01HBHsfxYJydGiK8kYqbtaVG",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "offset": Number(84),
- },
- ),
- raw_output: Some(
- String("84\t#[tokio::test]\n85\tasync fn service_matches_the_bare_fold() {\n86\t let store = two_session_store();\n87\t let service = FoldedMessageService::new(store.clone());\n88\t\n89\t let via_service = service\n90\t .list_by_session(test_session())\n91\t .await\n92\t .expect(\"in-memory store cannot fail\");\n93\t let via_fold = fold::fold(\n94\t store\n95\t .list_by_session(test_session())\n96\t .await\n97\t .expect(\"in-memory store cannot fail\"),\n98\t );\n99\t\n100\t assert_eq!(via_service, via_fold.messages);\n101\t\n102\t // Every derived message is addressable by the key it reports.\n103\t for message in &via_service {\n104\t let fetched = service\n105\t .get(test_session(), message.id())\n106\t .await\n107\t .expect(\"in-memory store cannot fail\");\n108\t assert_eq!(fetched.as_ref(), Some(message));\n109\t }\n110\t}\n111\t"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01Eq6eiBaSNCybxRoa1zuRap",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4106,17 +3033,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs"),
- "old_string": String(" let via_fold = fold::fold(\n store\n .list_by_session(test_session())\n .await\n .expect(\"in-memory store cannot fail\"),\n );"),
- "new_string": String(" let via_fold = fold::fold(\n AgentSessionLogRepo::list_by_session(&store, test_session())\n .await\n .expect(\"in-memory store cannot fail\"),\n );"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/service/test.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now tests for the comms adapter:",
@@ -4125,7 +3041,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01XVVyZTJkSLkuSAmRNobNc8",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4136,21 +3054,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message/test.rs"),
- "content": String("use super::*;\nuse crate::domain::service::FoldedMessageService;\nuse crate::domain::test_support::{\n TURN, parse_log_as, test_bot, test_session, test_session_record, test_thread,\n};\nuse agent_session::testing::InMemoryAgentSessionRepo;\n\n/// A repo holding the fixture session plus its session record.\nfn seeded() -> InMemoryAgentSessionRepo {\n let repo: InMemoryAgentSessionRepo = parse_log_as(test_session(), TURN).into_iter().collect();\n repo.insert_session(test_session_record(test_session()));\n repo\n}\n\n/// The context comes off the session record, so callers need not know the\n/// thread or the bot.\n#[tokio::test]\nasync fn reads_context_from_the_session() {\n let context = context_for_session(&seeded(), test_session())\n .await\n .expect(\"session was seeded\");\n\n assert_eq!(context.session, test_session());\n assert_eq!(context.channel_id, test_thread());\n assert_eq!(context.bot, test_bot());\n}\n\n/// A missing session is an error, not an empty context - unlike a missing\n/// *log*, which legitimately folds to nothing.\n#[tokio::test]\nasync fn missing_session_is_an_error() {\n let unknown = AgentSessionId::new_from_uuid(Uuid::from_u128(99));\n assert!(\n context_for_session(&seeded(), unknown).await.is_err(),\n \"no session record to read a thread and bot from\"\n );\n}\n\n/// The composed fold: protocol log in, channel messages out.\n#[tokio::test]\nasync fn renders_a_session_as_channel_messages() {\n let repo = seeded();\n let context = context_for_session(&repo, test_session())\n .await\n .expect(\"session was seeded\");\n let messages = FoldedMessageService::new(repo);\n\n let rendered = list_as_channel_messages(&messages, &context)\n .await\n .expect(\"in-memory repo cannot fail\");\n\n assert_eq!(rendered.len(), 2, \"one user message, one agent message\");\n\n let user = &rendered[0];\n assert_eq!(user.channel_id, test_thread());\n assert!(\n user.sender_id.contains(\"eric\"),\n \"user message keeps its author: {}\",\n user.sender_id\n );\n assert_eq!(user.bot_profile, None);\n assert_eq!(user.content, \"list the examples and write a file\");\n\n let agent = &rendered[1];\n assert_eq!(\n agent.sender_id,\n format!(\"bot|{}\", test_bot().as_uuid()),\n \"agent messages are sent by the session's bot\"\n );\n\n // Prose, the terminal call with its command and stripped output, the\n // permission note, the diff, and the closing prose.\n let content = &agent.content;\n assert!(content.starts_with(\"Sure, one moment.\"), \"{content}\");\n assert!(content.contains(\"**Bash**\"), \"{content}\");\n assert!(content.contains(\"```sh\\nls examples\\n```\"), \"{content}\");\n assert!(content.contains(\"events.rs\"), \"{content}\");\n assert!(\n !content.contains('\\u{1b}'),\n \"ANSI escapes are stripped for markdown: {content:?}\"\n );\n assert!(content.contains(\"Permission requested\"), \"{content}\");\n assert!(content.contains(\"**Write**\"), \"{content}\");\n assert!(content.contains(\"+fn main() {}\"), \"{content}\");\n assert!(content.trim_end().ends_with(\"Done.\"), \"{content}\");\n assert!(\n !content.contains(\"Stopped\"),\n \"a clean end_turn needs no note: {content}\"\n );\n}\n\n/// Ids are a pure function of the log, so re-reading a session yields the\n/// same message ids - otherwise every poll would look like new messages.\n#[tokio::test]\nasync fn message_ids_are_stable_and_distinct() {\n let repo = seeded();\n let context = context_for_session(&repo, test_session())\n .await\n .expect(\"session was seeded\");\n let messages = FoldedMessageService::new(repo);\n\n let first = list_as_channel_messages(&messages, &context)\n .await\n .expect(\"in-memory repo cannot fail\");\n let second = list_as_channel_messages(&messages, &context)\n .await\n .expect(\"in-memory repo cannot fail\");\n\n let ids: Vec<_> = first.iter().map(|message| message.id).collect();\n let again: Vec<_> = second.iter().map(|message| message.id).collect();\n assert_eq!(ids, again, \"ids are derived, not generated\");\n assert_ne!(ids[0], ids[1], \"user and agent messages differ\");\n\n // A different session derives different ids for the same turn shape.\n let other = AgentSessionId::new_from_uuid(Uuid::from_u128(2));\n let other_repo: InMemoryAgentSessionRepo = parse_log_as(other, TURN).into_iter().collect();\n other_repo.insert_session(test_session_record(other));\n let other_context = context_for_session(&other_repo, other)\n .await\n .expect(\"session was seeded\");\n let other_rendered = list_as_channel_messages(&FoldedMessageService::new(other_repo), &other_context)\n .await\n .expect(\"in-memory repo cannot fail\");\n assert_ne!(\n ids[0], other_rendered[0].id,\n \"ids are scoped to their session\"\n );\n}\n\n/// In-flight state renders as text rather than vanishing.\n#[tokio::test]\nasync fn renders_an_interrupted_turn() {\n let mut log = parse_log_as(test_session(), TURN);\n log.truncate(9);\n let repo: InMemoryAgentSessionRepo = log.into_iter().collect();\n repo.insert_session(test_session_record(test_session()));\n\n let context = context_for_session(&repo, test_session())\n .await\n .expect(\"session was seeded\");\n let rendered = list_as_channel_messages(&FoldedMessageService::new(repo), &context)\n .await\n .expect(\"in-memory repo cannot fail\");\n\n let content = &rendered[1].content;\n assert!(content.contains(\"◦ **Bash**\"), \"pending marker: {content}\");\n assert!(\n content.contains(\"Waiting for permission\"),\n \"unanswered request: {content}\"\n );\n}\n\n#[test]\nfn strips_ansi_sequences() {\n assert_eq!(\n strip_ansi(\"\\u{1b}[01;34macp.rs\\u{1b}[0m\\nevents.rs\"),\n \"acp.rs\\nevents.rs\"\n );\n assert_eq!(strip_ansi(\"plain\"), \"plain\");\n // A truncated escape at the end of a captured buffer must not panic.\n assert_eq!(strip_ansi(\"tail\\u{1b}\"), \"tail\");\n assert_eq!(strip_ansi(\"tail\\u{1b}[\"), \"tail\");\n}\n"),
- },
- ),
- raw_output: Some(
- String("File created successfully at: /Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message/test.rs (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01YGi2fkdeEMfQt8waKgkq5p",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4165,16 +3076,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo check -p agent_fold --all-targets 2>&1 | grep -E \"^error|^warning\" -A 4 | head -50; echo \"--- done ---\""),
- "description": String("Type-check restructured agent_fold"),
- "timeout": Number(400000),
- },
- ),
- raw_output: Some(
- String("error: invalid suffix `t` for number literal\n --> crates/agent_fold/src/domain/test_support.rs:75:42\n |\n75 | BotId::new_from_uuid(Uuid::from_u128(0xb0t))\n | ^^^^^ invalid suffix `t`\n--\nerror: could not compile `agent_fold` (lib test) due to 1 previous error\nwarning: build failed, waiting for other jobs to finish...\nerror[E0433]: failed to resolve: could not find `outbound` in `agent_fold`\n --> crates/agent_fold/examples/fold_recording.rs:14:17\n |\n14 | use agent_fold::outbound::memory::InMemoryLogStore;\n | ^^^^^^^^ could not find `outbound` in `agent_fold`\n--\nerror[E0282]: type annotations needed\n --> crates/agent_fold/examples/fold_recording.rs:31:20\n |\n31 | let messages = FoldedMessageService::new(store)\n | ____________________^\n--\nerror[E0308]: mismatched types\n --> crates/agent_fold/examples/fold_recording.rs:52:77\n |\n52 | println!(\" text ({} chars) {:?}\", text.len(), preview(text))\n | ------- ^^^^ expected `&str`, found `String`\n--\nerror: could not compile `agent_fold` (example \"fold_recording\") due to 3 previous errors\n--- done ---"),
- ),
},
Text {
text: "Fixing the invalid hex literal and rewriting the example for the new structure:",
@@ -4183,7 +3084,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_018C5QEs32b3cM9PhtW6MUrV",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4196,23 +3099,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs"),
- "old_string": String(" BotId::new_from_uuid(Uuid::from_u128(0xb0t))"),
- "new_string": String(" BotId::new_from_uuid(Uuid::from_u128(0xb07))"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_019jfNCyVfzrLGp18DqS8ynr",
),
- label: "Write",
+ name: Native {
+ name: "Write",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4223,21 +3117,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/examples/fold_recording.rs"),
- "content": String("//! Fold a recorded session and print it both ways.\n//!\n//! Loads a recording into `agent_session`'s in-memory repo and queries it\n//! through the domain service - the same path a real caller takes, with\n//! Postgres swapped out - then renders the result as comms channel messages.\n//!\n//! ```sh\n//! cargo run -p agent_fold --example fold_recording -- ~/.agent_runtime_sessions/<id>.jsonl\n//! ```\n\nuse agent_fold::domain::message::{Author, MessagePart, ToolDetail};\nuse agent_fold::domain::ports::FoldedMessageRepo;\nuse agent_fold::domain::service::FoldedMessageService;\nuse agent_fold::inbound::comms_message::{CommsContext, list_as_channel_messages};\nuse agent_session::domain::model::{AgentSessionId, AgentSessionLog, Message};\nuse agent_session::testing::InMemoryAgentSessionRepo;\nuse bot_id::BotId;\nuse macro_uuid::Uuid;\n\n#[tokio::main(flavor = \"current_thread\")]\nasync fn main() {\n let path = std::env::args()\n .nth(1)\n .expect(\"usage: fold_recording <recording.jsonl>\");\n let jsonl = std::fs::read_to_string(&path).expect(\"recording is readable\");\n\n let session = AgentSessionId::new_from_uuid(Uuid::from_u128(1));\n let repo: InMemoryAgentSessionRepo = jsonl\n .lines()\n .filter(|line| !line.trim().is_empty())\n .map(|line| parse_line(session, line))\n .collect();\n\n let messages = FoldedMessageService::new(repo);\n let folded = messages\n .list_by_session(session)\n .await\n .expect(\"in-memory repo cannot fail\");\n\n println!(\"══ domain messages ══\\n\");\n for message in &folded {\n let author = match &message.author {\n Author::User(id) => format!(\n \"user({})\",\n id.as_ref()\n .map_or_else(|| \"?\".to_owned(), ToString::to_string)\n ),\n Author::Agent => \"agent\".to_owned(),\n };\n println!(\n \"── turn {} · {author} · stop {:?}\",\n message.turn.0, message.stop\n );\n for part in message.parts.iter() {\n match part {\n MessagePart::Text(text) => {\n println!(\" text ({} chars) {:?}\", text.len(), preview(text))\n }\n MessagePart::Thought(text) => println!(\" thought ({} chars)\", text.len()),\n MessagePart::ToolUse(tool) => {\n let detail = match &tool.detail {\n ToolDetail::Terminal {\n command, exit_code, ..\n } => format!(\n \"terminal {:?} exit={exit_code:?}\",\n command.as_deref().map(preview)\n ),\n ToolDetail::Edit { diffs } => format!(\"edit {} diff(s)\", diffs.len()),\n ToolDetail::Read { paths } => format!(\"read {paths:?}\"),\n ToolDetail::Other { kind, .. } => format!(\"other kind={kind}\"),\n };\n println!(\" tool {} [{:?}] {detail}\", tool.label, tool.status);\n }\n MessagePart::Permission(permission) => println!(\n \" permission for {} -> {:?}\",\n permission.tool_call.0, permission.outcome\n ),\n }\n }\n }\n\n // Rendered for a channel. A recording carries no session record, so the\n // context is supplied directly rather than read off one.\n let context = CommsContext {\n session,\n channel_id: Uuid::from_u128(0xf00d),\n bot: BotId::new_from_uuid(Uuid::from_u128(0xb07)),\n bot_profile: None,\n fallback_user_id: None,\n };\n let rendered = list_as_channel_messages(&messages, &context)\n .await\n .expect(\"in-memory repo cannot fail\");\n\n println!(\"\\n══ as channel messages ══\");\n for message in &rendered {\n println!(\"\\n── {} · {}\\n\", message.id, message.sender_id);\n println!(\"{}\", message.content);\n }\n}\n\n/// Parse one recorded line into a log row for the given session.\nfn parse_line(session: AgentSessionId, line: &str) -> AgentSessionLog {\n let value: serde_json::Value = serde_json::from_str(line).expect(\"line is JSON\");\n let content = value.get(\"content\").expect(\"line has content\").clone();\n let content = match value.get(\"direction\").and_then(|d| d.as_str()) {\n Some(\"to_server\") => {\n Message::ToServer(serde_json::from_value(content).expect(\"to_server frame\"))\n }\n Some(\"to_runtime\") => {\n Message::ToRuntime(serde_json::from_value(content).expect(\"to_runtime frame\"))\n }\n other => panic!(\"unknown direction {other:?}\"),\n };\n AgentSessionLog {\n agent_session_id: session,\n user_id: None,\n content,\n }\n}\n\nfn preview(text: &str) -> String {\n let line = text.lines().next().unwrap_or_default();\n let mut preview: String = line.chars().take(60).collect();\n if preview.len() < text.len() {\n preview.push('…');\n }\n preview\n}\n"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/examples/fold_recording.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_015mJuH5F4nVfyag7i2tzNB2",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4252,22 +3139,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo check -p agent_fold --all-targets 2>&1 | grep -E \"^error\" -A 8 | head -60; echo \"--- done ---\""),
- "description": String("Re-check agent_fold"),
- "timeout": Number(400000),
- },
- ),
- raw_output: Some(
- String("--- done ---"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01VyFEbbVaCEma32FdDNsJgh",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4282,16 +3161,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("SQLX_OFFLINE=true cargo check -p agent_fold --all-targets 2>&1 | grep -E \"warning\" -A 6 | head -30; cargo test -p agent_fold 2>&1 | grep -E \"^test |test result|^error|panicked|assertion\" | head -30"),
- "description": String("Check warnings and run tests"),
- "timeout": Number(400000),
- },
- ),
- raw_output: Some(
- String("warning: function `seeded_repo` is never used\n --> crates/agent_fold/src/domain/test_support.rs:103:8\n |\n103 | pub fn seeded_repo(\n | ^^^^^^^^^^^\n |\n = note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default\n--\nwarning: `agent_fold` (lib test) generated 1 warning\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.46s\ntest domain::fold::test::folds_nothing ... ok\ntest domain::meta::test::reads_a_command_from_raw_input ... ok\ntest domain::meta::test::tolerates_absence_and_noise ... ok\ntest domain::meta::test::reads_the_harness_tool_name ... ok\ntest domain::meta::test::reads_terminal_output_and_exit ... ok\ntest inbound::comms_message::test::strips_ansi_sequences ... ok\ntest domain::fold::test::reports_a_patch_before_open ... ok\ntest inbound::comms_message::test::renders_an_interrupted_turn ... ok\ntest inbound::comms_message::test::renders_a_session_as_channel_messages ... ok\ntest domain::fold::test::folds_a_complete_turn ... ok\ntest inbound::comms_message::test::reads_context_from_the_session ... ok\ntest inbound::comms_message::test::missing_session_is_an_error ... ok\ntest domain::service::test::gets_a_message_by_id ... ok\ntest domain::service::test::service_matches_the_bare_fold ... ok\ntest inbound::comms_message::test::message_ids_are_stable_and_distinct ... ok\ntest domain::service::test::queries_are_scoped_to_a_session ... ok\ntest domain::fold::test::folds_an_interrupted_turn ... ok\ntest domain::fold::test::replays_local_recordings ... ok\ntest result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s\ntest crates/agent_fold/src/lib.rs - (line 26) - compile ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"),
- ),
},
Text {
text: "All 18 pass. Removing the unused helper I left behind:",
@@ -4300,7 +3169,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_013avoaixmfTiMhq2cT69ZQ5",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4313,23 +3184,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs"),
- "old_string": String("\n/// A repo seeded with the given sessions' logs and session records.\npub fn seeded_repo(\n logs: impl IntoIterator<Item = AgentSessionLog>,\n) -> InMemoryAgentSessionRepo {\n let repo: InMemoryAgentSessionRepo = logs.into_iter().collect();\n repo\n}"),
- "new_string": String(""),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_015sGhsKemJsQy9hxwd62JPD",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4344,22 +3206,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("perl -pi -e 's/^use agent_session::testing::InMemoryAgentSessionRepo;\\n$//' crates/agent_fold/src/domain/test_support.rs; SQLX_OFFLINE=true cargo check -p agent_fold --all-targets 2>&1 | grep -E \"^error|^warning\" -A 5 | head -20; echo \"--- done ---\""),
- "description": String("Drop now-unused import and recheck"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String("Can't open crates/agent_fold/src/domain/test_support.rs: No such file or directory.\nwarning: unused import: `agent_session::testing::InMemoryAgentSessionRepo`\n --> crates/agent_fold/src/domain/test_support.rs:6:5\n |\n6 | use agent_session::testing::InMemoryAgentSessionRepo;\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n |\n--\nwarning: `agent_fold` (lib test) generated 1 warning (run `cargo fix --lib -p agent_fold --tests` to apply 1 suggestion)\n Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.57s\n--- done ---"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_011utVtULLtsCwD2q5uT7nWV",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4372,17 +3226,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs"),
- "old_string": String("use agent_session::testing::InMemoryAgentSessionRepo;\nuse bot_id::BotId;"),
- "new_string": String("use bot_id::BotId;"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/domain/test_support.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
Text {
text: "Now the boundary audit the architecture skill prescribes:",
@@ -4391,7 +3234,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_017Ho44av5PzXQvbpUWXPJes",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4406,21 +3251,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("CRATE=crates/agent_fold; echo \"=== domain must not know transport/infra ===\"; rg -n \"use (axum|http::StatusCode)|IntoResponse|Json<|Router|HeaderMap|Request<|sqlx::|PgPool|aws_sdk|redis::|reqwest|crate::inbound|crate::outbound|channels::\" \"$CRATE/src/domain\" --glob '*.rs' || echo \" (clean)\"; echo; echo \"=== inbound must not do persistence/infra ===\"; rg -n \"sqlx::|query!|query_as!|PgPool|Transaction|aws_sdk|redis::|opensearch|reqwest|S3|Sqs|Dynamo\" \"$CRATE/src/inbound\" --glob '*.rs' || echo \" (clean)\"; echo; echo \"=== inbound authz/policy hits ===\"; rg -n \"entity_access|EntityAccessReceipt|AccessLevel|authorize|authz|can_|Forbidden|Unauthorized|permission\" \"$CRATE/src/inbound\" --glob '*.rs' | grep -v \"^.*comms_message.rs:.*[Pp]ermission\" | head || echo \" (no authz decisions)\""),
- "description": String("Run hexagonal boundary audit"),
- },
- ),
- raw_output: Some(
- String("=== domain must not know transport/infra ===\nrg: crates/agent_fold/src/domain: IO error for operation on crates/agent_fold/src/domain: No such file or directory (os error 2)\n (clean)\n\n=== inbound must not do persistence/infra ===\nrg: crates/agent_fold/src/inbound: IO error for operation on crates/agent_fold/src/inbound: No such file or directory (os error 2)\n (clean)\n\n=== inbound authz/policy hits ===\nrg: crates/agent_fold/src/inbound: IO error for operation on crates/agent_fold/src/inbound: No such file or directory (os error 2)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01FmmuiHZb3fQA2mTp8abdES",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4435,21 +3273,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cd /Users/eric/Code/macro && CRATE=crates/agent_fold; echo \"=== domain must not know transport/infra/comms ===\"; rg -n \"use (axum|http::StatusCode)|IntoResponse|Json<|Router|HeaderMap|sqlx::|PgPool|aws_sdk|redis::|reqwest|crate::inbound|channels::\" \"$CRATE/src/domain\" --glob '*.rs' || echo \" (clean)\"; echo; echo \"=== inbound must not do persistence/infra ===\"; rg -n \"sqlx::|query!|query_as!|PgPool|Transaction|aws_sdk|redis::|opensearch|reqwest\" \"$CRATE/src/inbound\" --glob '*.rs' || echo \" (clean)\"; echo; echo \"=== domain deps on channels crate anywhere ===\"; rg -c \"channels\" \"$CRATE/src/domain\" -g '*.rs' || echo \" (none)\""),
- "description": String("Run boundary audit from repo root"),
- },
- ),
- raw_output: Some(
- String("=== domain must not know transport/infra/comms ===\n (clean)\n\n=== inbound must not do persistence/infra ===\n (clean)\n\n=== domain deps on channels crate anywhere ===\n (none)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01LL75Hr3YA9RMM9v7BbqPUi",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4464,44 +3295,28 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo fmt -p agent_fold -p agent_session && RUSTFLAGS=\"-Dwarnings -Dclippy::disallowed_methods\" RUSTDOCFLAGS=-Dwarnings SQLX_OFFLINE=true cargo clippy -p agent_fold -p agent_session --all-targets --all-features 2>&1 | grep -E \"^error|^warning\" -A 6 | head -40; echo \"--- clippy done ---\""),
- "description": String("Format and strict clippy both crates"),
- "timeout": Number(400000),
- },
- ),
- raw_output: Some(
- String("error: this `if` statement can be collapsed\n --> crates/agent_fold/src/inbound/comms_message.rs:236:13\n |\n236 | / if let Some(input) = input {\n237 | | if let Ok(pretty) = serde_json::to_string_pretty(input) {\n238 | | if pretty != \"{}\" {\n239 | | out.push_str(&format!(\"\\n\\n```json\\n{pretty}\\n```\"));\n--\nerror: this `if` statement can be collapsed\n --> crates/agent_fold/src/inbound/comms_message.rs:237:17\n |\n237 | / if let Ok(pretty) = serde_json::to_string_pretty(input) {\n238 | | if pretty != \"{}\" {\n239 | | out.push_str(&format!(\"\\n\\n```json\\n{pretty}\\n```\"));\n240 | | }\n--\nerror: could not compile `agent_fold` (lib) due to 2 previous errors\nwarning: build failed, waiting for other jobs to finish...\nerror: could not compile `agent_fold` (lib test) due to 2 previous errors\n--- clippy done ---\n[This command modified 3 files you've previously read: crates/agent_fold/src/inbound/comms_message.rs, crates/agent_session/src/testing.rs, crates/agent_fold/src/inbound/comms_message/test.rs. Call Read before editing.]"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01QhDMea41zuGuzDmZRpUHdk",
),
- label: "Read",
+ name: Native {
+ name: "Read",
+ },
status: Completed,
detail: Read {
paths: [
"/Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs",
],
},
- raw_input: Some(
- Object {
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs"),
- "offset": Number(228),
- "limit": Number(20),
- },
- ),
- raw_output: Some(
- String("228\t }\n229\t ToolDetail::Read { paths } => {\n230\t for path in paths {\n231\t out.push_str(&format!(\"\\n\\n`{}`\", path.display()));\n232\t }\n233\t }\n234\t ToolDetail::Other { kind, input } => {\n235\t out.push_str(&format!(\" _({kind})_\"));\n236\t if let Some(input) = input {\n237\t if let Ok(pretty) = serde_json::to_string_pretty(input) {\n238\t if pretty != \"{}\" {\n239\t out.push_str(&format!(\"\\n\\n```json\\n{pretty}\\n```\"));\n240\t }\n241\t }\n242\t }\n243\t }\n244\t }\n245\t\n246\t out\n247\t}"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01AEErEMbFRSAmhDqFVhEafU",
),
- label: "Edit",
+ name: Native {
+ name: "Edit",
+ },
status: Completed,
detail: Edit {
diffs: [
@@ -4514,23 +3329,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
},
],
},
- raw_input: Some(
- Object {
- "replace_all": Bool(false),
- "file_path": String("/Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs"),
- "old_string": String(" ToolDetail::Other { kind, input } => {\n out.push_str(&format!(\" _({kind})_\"));\n if let Some(input) = input {\n if let Ok(pretty) = serde_json::to_string_pretty(input) {\n if pretty != \"{}\" {\n out.push_str(&format!(\"\\n\\n```json\\n{pretty}\\n```\"));\n }\n }\n }\n }"),
- "new_string": String(" ToolDetail::Other { kind, input } => {\n out.push_str(&format!(\" _({kind})_\"));\n // An empty input object says nothing worth a code fence.\n if let Some(pretty) = input\n .as_ref()\n .and_then(|input| serde_json::to_string_pretty(input).ok())\n .filter(|pretty| pretty != \"{}\")\n {\n out.push_str(&format!(\"\\n\\n```json\\n{pretty}\\n```\"));\n }\n }"),
- },
- ),
- raw_output: Some(
- String("The file /Users/eric/Code/macro/crates/agent_fold/src/inbound/comms_message.rs has been updated successfully. (file state is current in your context — no need to Read it back)"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01H1h38nZaVDtDLhUiCGBG6X",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4545,22 +3351,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo fmt -p agent_fold -p agent_session && RUSTFLAGS=\"-Dwarnings -Dclippy::disallowed_methods\" RUSTDOCFLAGS=-Dwarnings SQLX_OFFLINE=true cargo clippy -p agent_fold -p agent_session --all-targets --all-features 2>&1 | grep -E \"^error|^warning\" -A 6 | head -30; echo \"--- clippy done ---\""),
- "description": String("Re-run strict clippy"),
- "timeout": Number(400000),
- },
- ),
- raw_output: Some(
- String("--- clippy done ---"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01QgiihrkQ3YA9UsC42QMXKc",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4575,16 +3373,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo test -p agent_fold 2>&1 | grep -E \"test result|^error|FAILED\" | head; echo \"=== agent_session tests (needs db) ===\"; cargo test -p agent_session 2>&1 | grep -E \"test result|^error|FAILED|running\" | head"),
- "description": String("Run both crates' tests"),
- "timeout": Number(400000),
- },
- ),
- raw_output: Some(
- String("test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s\n=== agent_session tests (needs db) ===\nrunning 5 tests\ntest result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.17s\nrunning 0 tests\ntest result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"),
- ),
},
Text {
text: "`agent_session`'s own 5 DB-backed tests still pass with the `Send` bounds added. Let me see the composed fold on real data:",
@@ -4593,7 +3381,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_018xWfu38d71cFTKh75qAP1R",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4608,16 +3398,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cargo run -p agent_fold --example fold_recording -- ~/.agent_runtime_sessions/cdf15e0e-c8b7-486e-93de-f596f547e641.jsonl 2>/dev/null | sed -n '/as channel messages/,$p' | head -55"),
- "description": String("Show channel-message rendering of real session"),
- "timeout": Number(300000),
- },
- ),
- raw_output: Some(
- String("══ as channel messages ══\n\n── 20297da6-e699-509f-bd4a-ad737b54a0d7 · \n\nwhere are session recordings saved?\n\n── c1db4d10-461c-51b4-aa99-34dce3eb5418 · bot|00000000-0000-0000-0000-000000000b07\n\nThey're saved to `~/.agent_runtime_sessions/`, one file per run named with the session's UTC start time — e.g. `~/.agent_runtime_sessions/2026-08-03T14-22-07Z.jsonl`. Each line is a JSON object with a `ts` timestamp plus the `direction`/`content` fields of a `Message`, so every line parses straight back into the crate's `Message` type. The recorder also prints the exact path to stderr when the runtime connects and again when the session is saved.\n\n── 1f912c38-023e-58c8-a74d-32724f6e57b2 · \n\nI don't see that dir\n\n── 78edc7d5-b9ff-5696-af77-efade450dfa3 · bot|00000000-0000-0000-0000-000000000b07\n\nLet me check whether it exists — it's a dotfile directory, so plain `ls` in Finder or without `-a` would hide it.\n\n● **Bash**\n\n```sh\nls -la ~/.agent_runtime_sessions/ 2>&1\n```\n\n```\ntotal 132\ndrwxr-xr-x 4 eric staff 128 Aug 3 16:08 .\ndrwxr-x--- 131 eric staff 4192 Aug 3 16:12 ..\n-rw-r--r-- 1 eric staff 99509 Aug 3 16:12 2026-08-03T20-08-59Z.jsonl\ndrwxr-xr-x 9 eric staff 288 Aug 3 11:12 claude_config\n```\n\n_Permission requested — Always Allow._\n\nThe directory exists — it's just hidden because the name starts with a dot, so Finder and plain `ls` won't show it (use `ls -a`, or press `Cmd+Shift+.` in Finder).\n\nThere's already one recording in it from a session you started a few minutes ago: `~/.agent_runtime_sessions/2026-08-03T20-08-59Z.jsonl` (~100 KB and growing as of a moment ago — note the filename is the UTC start time, so 4 hours ahead of your local clock). There's also a `claude_config/` subdirectory in there from earlier today.\n\n── 4cc7fc49-f39a-58a3-aa02-ee92c0ac3fcf · \n\ngood catch. I had a PR for the example can u push to that PR. it should only include the changes for the example / bin and not any other changes. It's in bookmark \"claude-recorder\"\n\n── bf2c2c68-d0d8-552d-a08a-583c02960631 · bot|00000000-0000-0000-0000-000000000b07\n\nI'll look at the jj state first to see where the `claude-recorder` bookmark sits relative to the working copy.\n\n● **Bash**\n\n```sh\njj log -r 'claude-recorder | @ | @-' --no-pager -T 'change_id.short() ++ \" \" ++ bookmarks ++ \" \" ++ description.first_line() ++ \"\\n\"' && jj st --no-pager\n```\n\n```\n@ szwwkmusnqwv fold\n○ zyrwruupsoys claude-recorder feat: claude recorder"),
- ),
},
Text {
text: "Let me verify the `Send` bound change didn't break other implementors across the workspace:",
@@ -4626,7 +3406,9 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
id: ToolUseId(
"toolu_01NoHPiPMMJm2KsZdZy3gMHn",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4641,21 +3423,14 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("echo \"=== crates depending on agent_session ===\"; rg -l 'agent_session = ' --glob 'Cargo.toml' | head; echo \"=== other impls of the ports ===\"; rg -n \"impl.*AgentSession(Log)?Repo for\" --glob '*.rs' | head"),
- "description": String("Find all dependents and port implementors"),
- },
- ),
- raw_output: Some(
- String("=== crates depending on agent_session ===\ncrates/agent_fold/Cargo.toml\n=== other impls of the ports ===\ncrates/agent_session/src/outbound/postgres/mod.rs:118:impl AgentSessionRepo for PgAgentSessionRepo {\ncrates/agent_session/src/outbound/postgres/mod.rs:239:impl AgentSessionLogRepo for PgAgentSessionRepo {\ncrates/agent_session/src/testing.rs:61:impl AgentSessionRepo for InMemoryAgentSessionRepo {\ncrates/agent_session/src/testing.rs:109:impl AgentSessionLogRepo for InMemoryAgentSessionRepo {"),
- ),
},
ToolUse {
id: ToolUseId(
"toolu_01NAdCwZqSfWjRUHgxz5R1wC",
),
- label: "Bash",
+ name: Native {
+ name: "Bash",
+ },
status: Completed,
detail: Terminal {
command: Some(
@@ -4670,15 +3445,6 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl
0,
),
},
- raw_input: Some(
- Object {
- "command": String("cat > /tmp/mem_fold.md <<'EOF'\n---\nname: project-agent-fold\ndescription: agent_fold crate — hex crate folding agent_session_log ACP frames into messages queried as if stored; comms rendering in inbound\nmetadata:\n type: project\n---\n\n`crates/agent_fold` (started 2026-08-03) folds the `agent_session_log` protocol log (ARP v0 frames wrapping ACP) into renderable messages. Related: [[project-agent-container-integration]].\n\nDesign decisions (Eric's calls, in order given):\n- **Parallel system** — ignore existing AI chat models (`AssistantMessagePart` etc.); nothing persisted, derived on every read (\"type land\")\n- **No Result on the fold** — total by construction; renderable-partial beats failing (pending tool call = in-flight state, not error). Weirdness → `Fold::anomalies` (tests assert empty; prod degrades gracefully). A fold error would mean a blank channel.\n- **One explicit match**, not a handler registry — every understood/ignored frame named in one place\n- **Hex crate with a pretend DB** — reversed an earlier plain-lib decision. Messages queried *as if stored*: `FoldedMessageRepo` (list_by_session / get by natural key `MessageId{turn, AuthorKind}`), `FoldedMessageService` folds on read, anomalies → `tracing::warn`\n- **Domain names no display type** — comms coupling lives only in `inbound/comms_message.rs` (Eric: \"beautiful / abstract way that doesn't inject / depend on comms messages at all in the domain\")\n- **Reuse agent_session's log store** — no duplicate `SessionLogStore` port, no `outbound/` module; expand agent_session instead (added `+ Send` to both port traits + `testing::InMemoryAgentSessionRepo` behind `test-utils`)\n\nLayout: `domain/{message,fold,meta,ports,service,test_support}.rs`, `inbound/comms_message.rs`. Ports follow channels style: RPITIT `+ Send`, `rootcause::Report`, `#[tracing::instrument(err, skip(self))]`.\n\n`inbound/comms_message.rs`: renders `FoldedMessage` → `channels::domain::models::ChannelMessage`. **Lossy on purpose** — `content` is a `String` today so parts flatten to markdown (tool calls → fenced blocks w/ status markers ●◦◍✕, thoughts → blockquote, ANSI stripped here since domain preserves it). Swap `render_markdown` when comms carries structured parts. `CommsContext` comes off the `AgentSession` record itself (it already has `thread_id` + `bot_id`). Message ids = UUIDv5 from (session, turn, author) so re-reads are stable — otherwise every poll looks like new messages.\n\nEmpirics from recordings (`~/.agent_runtime_sessions/*.jsonl`, NOT .agent_session_recordings): ~4 tool_call_update per tool_call; usage_update is noise (81/450 frames); tool opens arrive underspecified (`Write` opens with empty rawInput); real tool name + terminal output ONLY in `_meta` (ACP normalizes to coarse `kind`) — hence quarantined `domain/meta.rs`; log order sound (uuid v7 + created_at tiebreak) so orphan patches need a `session/load` resume.\n\nIterate: `cargo run -p agent_fold --example fold_recording -- <recording.jsonl>` prints domain messages AND channel-message markdown. Test `replays_local_recordings` folds all local recordings asserting zero anomalies (no-op in CI where dir absent).\n\nKnown gaps: `AgentSessionLog` carries no `created_at`, so rendered timestamps are epoch (thread a frame timestamp through the model to fix); `SessionUpdate::Plan` deliberately unmodelled → anomaly until a recording produces one; no inbound axum router yet; no authz (queries scoped by AgentSessionId only).\nEOF\ncp /tmp/mem_fold.md /Users/eric/.claude/projects/-Users-eric-Code-macro/memory/project_agent_fold.md && echo written"),
- "description": String("Update agent_fold memory"),
- },
- ),
- raw_output: Some(
- String("written"),
- ),
},
Text {
text: "Both changes done. **Hexagonal boundary checked** — audit greps come back clean: `domain/` has zero references to `channels`, axum, sqlx, or `crate::inbound`; `inbound/` does no persistence or infrastructure work. No authz or business policy exists in this crate yet — queries are scoped by `AgentSessionId` only, so access control belongs to whichever inbound surface eventually exposes this, minting a receipt against the session's thread.\n\n**1. The domain no longer knows comms exists.** `inbound/comms_message.rs` is the concrete fold — protocol log in, `channels::domain::models::ChannelMessage` out — and it's the only file in the crate that names a comms type. The domain keeps its own vocabulary (turns, tool calls, permissions) and the coupling sits at the edge.\n\nTwo things worth flagging about that adapter:\n- **It's lossy on purpose.** `ChannelMessage.content` is a `String`, so parts flatten to markdown: tool calls become fenced blocks with status markers, thoughts a blockquote, diffs a `diff` fence. That's the reason the layering pays off — when comms carries structured parts, `render_markdown` is the only thing that changes. It also means ANSI stripping lives *here*, not in the domain, which still preserves the escapes.\n- **Message ids are derived, not generated.** UUIDv5 over `(session, turn, author)`, so re-reading a session yields identical ids. Without that, every poll would look like a fresh batch of messages. There's a test pinning it.\n\n**2. `agent_session` owns the log store.** Deleted my duplicate `SessionLogStore` port and the whole `outbound/` module; the service is now generic over `AgentSessionLogRepo` directly. To make that work I expanded `agent_session` as you authorized:\n- Added `+ Send` to both port traits' futures — without it a generic consumer can't hold them across an await. Its 5 DB-backed tests still pass, and it's the only implementor besides the new double.\n- Added `testing::InMemoryAgentSessionRepo` behind a `test-utils` feature (mirroring `agent_runtime_protocol`'s pattern), implementing both traits. That's what `agent_fold`'s tests and the example run on.\n\nA nice consequence of dropping the duplicate port: `CommsContext` reads straight off the `AgentSession` record, which already carries `thread_id` and `bot_id` — so callers don't supply the channel or the bot.\n\n18 tests + doctest green, strict clippy clean on both crates. The example now prints both representations; on your real jj-push session the channel side reads as an actual conversation — prose, a `● **Bash**` block with the command and its output, `_Permission requested — Always Allow._`, then the reply.\n\n**One gap I couldn't close honestly:** `AgentSessionLog` carries no `created_at`, even though the table has one. I left rendered timestamps at the epoch rather than invent wall-clock values that would change every read. Threading a frame timestamp through the log model is the fix — small change to `agent_session`, but it touches the row mapping, so I left it for your call.",
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap
new file mode 100644
index 0000000000..4edf0ed574
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_claude_code.jsonl.snap
@@ -0,0 +1,151 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: messages
+input_file: crates/agent_fold/fixtures/real/subagent_claude_code.jsonl
+---
+[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: None,
+ },
+ request_id: Some(
+ AgentActionId(
+ 56062802-48df-4dca-b98d-966c762ee74c,
+ ),
+ ),
+ parts: NonEmpty {
+ inner: [
+ Control {
+ control: SetModel {
+ model: "opus[1m]",
+ },
+ outcome: Accepted,
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 1,
+ ),
+ author: User {
+ user_id: Some(
+ ),
+ },
+ request_id: Some(
+ AgentActionId(
+ b63bb736-1022-4b01-abcf-d00c2b6adf90,
+ ),
+ ),
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "spwan a subagent to use python to add 5+5",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 1,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ ToolUse {
+ id: ToolUseId(
+ "toolu_0134fqTfrmNcuarHkdgLtffW",
+ ),
+ name: Native {
+ name: "Agent",
+ },
+ status: Completed,
+ detail: Subagent {
+ title: "Add 5+5 with Python",
+ agent_type: Some(
+ "general-purpose",
+ ),
+ description: Some(
+ "Add 5+5 with Python",
+ ),
+ prompt: Some(
+ "Run `python3 -c \"print(5+5)\"` in bash and report the output.",
+ ),
+ background: false,
+ children: [
+ ToolUse {
+ id: ToolUseId(
+ "toolu_01CCNovB4Fe1yRrJNhJjx3ah",
+ ),
+ name: Native {
+ name: "Bash",
+ },
+ status: Completed,
+ detail: Terminal {
+ command: Some(
+ "python3 -c \"print(5+5)\"",
+ ),
+ output: Some(
+ AnsiText(
+ "10",
+ ),
+ ),
+ exit_code: Some(
+ 0,
+ ),
+ },
+ },
+ ],
+ result: Some(
+ SubagentResult {
+ text: Some(
+ "Output: `10`",
+ ),
+ error: None,
+ agent_id: Some(
+ "af2647314187b6bf1",
+ ),
+ model: Some(
+ "claude-opus-5[1m]",
+ ),
+ duration_ms: Some(
+ 3485,
+ ),
+ tokens: Some(
+ 26077,
+ ),
+ tool_uses: Some(
+ 1,
+ ),
+ stats: Some(
+ ToolStats {
+ reads: 0,
+ searches: 0,
+ commands: 1,
+ edits: 0,
+ lines_added: 0,
+ lines_removed: 0,
+ other: 0,
+ },
+ ),
+ },
+ ),
+ },
+ },
+ Text {
+ text: "The subagent ran `python3 -c \"print(5+5)\"` → **10**.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+]
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap
new file mode 100644
index 0000000000..b2abb0c7ec
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_cursor.jsonl.snap
@@ -0,0 +1,147 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: messages
+input_file: crates/agent_fold/fixtures/real/subagent_cursor.jsonl
+---
+[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: Some(
+ ),
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "<m-agent-context>{\"version\":1,\"text\":\"Prior message 1:\\nSender: macro|[email protected]\\nContent: Hey \\u003cm-user-mention>{\\\"userId\\\":\\\"macro|[email protected]\\\",\\\"email\\\":\\\"[email protected]\\\"}\\u003c/m-user-mention>,\\n\\nWelcome to Macro, we're excited for you to try it out.\\n\\nThis is your own personal support Channel, with \\u003cm-user-mention>{\\\"userId\\\":\\\"macro|[email protected]\\\",\\\"email\\\":\\\"[email protected]\\\"}\\u003c/m-user-mention> (ceo) and \\u003cm-user-mention>{\\\"userId\\\":\\\"macro|[email protected]\\\",\\\"email\\\":\\\"[email protected]\\\"}\\u003c/m-user-mention> (cto) and me (julia).\\n\\nIf you have any feedback or find any bugs let us know here.\"}</m-agent-context>\n\n<m-user-mention>{\"userId\":\"bot|00000000-0000-0000-0000-00000000c5c5\",\"email\":\"Cursor\",\"displayName\":\"Cursor\"}</m-user-mention> spawn a subagent to use python to take the integral of x^2 dx between 1 and 5",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Thought {
+ text: "**Implementing subagent use**\n\nI need to use the subagent because the user specifically asked for it. I'm considering whether to choose the general purpose or a simpler option, but that's alright. First, I should update the commentary. It looks like there might not be any repo work required, and perhaps no testing is necessary since it seems simple to handle. I'll proceed with the subagent using Python and return the result.",
+ },
+ Text {
+ text: "I’m spawning a subagent to compute the definite integral in Python and return the result directly.",
+ },
+ ToolUse {
+ id: ToolUseId(
+ "call_WDdIO2oFNumfaB7SNHinSgRM fc_084f7006b4bfb13e016a9997c35c8087d2b209ca20dbbd2613",
+ ),
+ name: Native {
+ name: "task",
+ },
+ status: Completed,
+ detail: Subagent {
+ title: "Compute integral in Python",
+ agent_type: None,
+ description: Some(
+ "Compute integral in Python",
+ ),
+ prompt: Some(
+ "Use Python to compute the definite integral of x^2 dx from 1 to 5. Return the exact value and a brief note of the method used.",
+ ),
+ background: false,
+ children: [
+ Thought {
+ text: "**Executing terminal command**\n\nI see that I need an answer via a terminal command. I could compute this mentally, but since the request is labeled as simple, using a terminal command seems more appropriate. I should make sure to provide a commentary update first. So, I'll opt to use the Python shell to get this done. I just need to make sure that I'm following the correct steps to get the answer efficiently!",
+ },
+ Text {
+ text: "I’m computing the definite integral in Python and will return the exact result with a short note on the method.",
+ },
+ ToolUse {
+ id: ToolUseId(
+ "call_njT7kCrh8vMAKfDvXg3DmkAJ fc_04cef57509d465f7016a9997c9d3f887d28128fd586814459d",
+ ),
+ name: Native {
+ name: "shell",
+ },
+ status: Failed,
+ detail: Terminal {
+ command: Some(
+ "python3 - <<'PY'\nimport sympy as sp\nx = sp.symbols('x')\nexpr = sp.integrate(x**2, (x, 1, 5))\nprint(expr)\nPY",
+ ),
+ output: Some(
+ AnsiText(
+ "Traceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nModuleNotFoundError: No module named 'sympy'\n",
+ ),
+ ),
+ exit_code: Some(
+ 1,
+ ),
+ },
+ },
+ Thought {
+ text: "**Considering fallback options**\n\nI'm thinking about maybe using a plain Python formula as a fallback. It seems like a simple way to handle things if my first approach isn't working out. I wonder if I'll need to adjust any parameters or structure it differently. Let's see if this gives me the results I want. It's always good to have these alternatives ready, just in case!",
+ },
+ Text {
+ text: "SymPy isn’t installed here, so I’m using a short Python evaluation of the antiderivative directly to keep the result exact.",
+ },
+ ToolUse {
+ id: ToolUseId(
+ "call_a6FRCO5T7CJ0kFmetndLRJhj fc_04cef57509d465f7016a9997cd322087d28a06be214c6849d1",
+ ),
+ name: Native {
+ name: "shell",
+ },
+ status: Completed,
+ detail: Terminal {
+ command: Some(
+ "python3 - <<'PY'\nfrom fractions import Fraction\nresult = Fraction(5**3 - 1**3, 3)\nprint(result)\nPY",
+ ),
+ output: Some(
+ AnsiText(
+ "124/3\n",
+ ),
+ ),
+ exit_code: Some(
+ 0,
+ ),
+ },
+ },
+ ],
+ result: Some(
+ SubagentResult {
+ text: Some(
+ "The exact value is **124/3**.\n\nMethod: I used Python to evaluate the antiderivative of \\(x^2\\), which is \\(x^3/3\\), and then applied the bounds:\n\\[\n\\int_1^5 x^2\\,dx = \\left[\\frac{x^3}{3}\\right]_1^5 = \\frac{125 - 1}{3} = \\frac{124}{3}.\n\\]",
+ ),
+ error: None,
+ agent_id: Some(
+ "bc-b723d011-d87a-5f5e-a0b0-bf3ffddc2693",
+ ),
+ model: None,
+ duration_ms: Some(
+ 12978,
+ ),
+ tokens: None,
+ tool_uses: Some(
+ 2,
+ ),
+ stats: None,
+ },
+ ),
+ },
+ },
+ Text {
+ text: "I spawned a subagent and it computed the integral as **124/3**.\n\n\\[\n\\int_1^5 x^2 \\, dx = \\left[\\frac{x^3}{3}\\right]_1^5 = \\frac{125 - 1}{3} = \\frac{124}{3}\n\\]\n\nThat’s approximately **41.3333**.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+]
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap
new file mode 100644
index 0000000000..48f880080d
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_macro_inmem.jsonl.snap
@@ -0,0 +1,82 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: messages
+input_file: crates/agent_fold/fixtures/real/subagent_macro_inmem.jsonl
+---
+[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: Some(
+ ),
+ },
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "spawn a subagent to add 5+5 ini python, then reason that it's right, and then write a frog poem, and then give me the last line of the frog poem and the nunber",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Thought {
+ text: "The user wants me to spawn a subagent for a simple task—adding 5+5 in Python—then follow up with reasoning, a frog poem, and a final answer. I'll go ahead and delegate that small task to the subagent as instructed, even though it's a trivial computation.",
+ },
+ ToolUse {
+ id: ToolUseId(
+ "QHiaeI_bhc1dMjpBo_Un0",
+ ),
+ name: Native {
+ name: "Subagent",
+ },
+ status: Completed,
+ detail: Subagent {
+ title: "Compute 5 + 5 in Python by executing the code, and report the exact numeric result that Python outputs.",
+ agent_type: None,
+ description: None,
+ prompt: Some(
+ "Compute 5 + 5 in Python by executing the code, and report the exact numeric result that Python outputs.",
+ ),
+ background: false,
+ children: [],
+ result: Some(
+ SubagentResult {
+ text: Some(
+ "I'll execute the Python code to compute 5 + 5.\n\nBased on executing the Python code `5 + 5`, the exact numeric result that Python outputs is:\n\n**10**\n\nThe computation `5 + 5` in Python returns the integer value `10`.",
+ ),
+ error: None,
+ agent_id: None,
+ model: None,
+ duration_ms: None,
+ tokens: None,
+ tool_uses: None,
+ stats: None,
+ },
+ ),
+ },
+ },
+ Thought {
+ text: "I'm confirming the answer makes sense, then I'll craft a short frog-themed poem before finishing with the final line and the number.",
+ },
+ Text {
+ text: "The subagent ran it and Python returned $$ 5 + 5 = 10 $$.\n\nThat checks out: adding two groups of five gives ten, same as $$ 2 \\times 5 = 10 $$, so the result is right.\n\nHere's the frog poem:\n\n*Ode to a Frog*\n\nA little frog sat on a log,\nhalf-hidden in the morning fog.\nHe blinked his eyes, he puffed his throat,\nthen sang a low and croaking note.\nHe leapt across the lily pads,\nignoring all the passing gnats,\nand dove into the cool green deep,\nwhere quiet frogs go off to sleep.\n\nLast line: **where quiet frogs go off to sleep.**\nNumber: **10**",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+]
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap
new file mode 100644
index 0000000000..2edbb060d1
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@subagent_opencode.jsonl.snap
@@ -0,0 +1,88 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: messages
+input_file: crates/agent_fold/fixtures/real/subagent_opencode.jsonl
+---
+[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: Some(
+ ),
+ },
+ request_id: Some(
+ AgentActionId(
+ 219d3ba0-a6bf-4104-a273-51b8bf4409c7,
+ ),
+ ),
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "please spawn a subagent to use python to add 5+5",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ ToolUse {
+ id: ToolUseId(
+ "call_jD0TDWivCCvEOTvAR47QMvJG",
+ ),
+ name: Native {
+ name: "task",
+ },
+ status: Completed,
+ detail: Subagent {
+ title: "Add numbers with Python",
+ agent_type: Some(
+ "general",
+ ),
+ description: Some(
+ "Add numbers with Python",
+ ),
+ prompt: Some(
+ "Use Python to calculate 5 + 5. Return only the numeric result. Do not modify files.",
+ ),
+ background: false,
+ children: [],
+ result: Some(
+ SubagentResult {
+ text: Some(
+ "10",
+ ),
+ error: None,
+ agent_id: Some(
+ "ses_f9bd7ee76ffeshjLOLx06ArVK7",
+ ),
+ model: Some(
+ "openai/gpt-5.6-terra",
+ ),
+ duration_ms: None,
+ tokens: None,
+ tool_uses: None,
+ stats: None,
+ },
+ ),
+ },
+ },
+ Text {
+ text: "10",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+]
diff --git a/crates/agent_fold/src/domain/test/subagent.rs b/crates/agent_fold/src/domain/test/subagent.rs
new file mode 100644
index 0000000000..a4b5451712
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/subagent.rs
@@ -0,0 +1,498 @@
+//! Delegated agents fold to one `Subagent` detail whichever harness reported
+//! them, with the subagent's own calls nested when the harness attributes
+//! them.
+
+use crate::domain::fold::{FoldMachineImpl, fold};
+use crate::domain::harness::opencode::task_result_text;
+use crate::domain::model::{
+ Author, FoldedMessage, Harness, MessagePart, SubagentResult, ToolDetail, ToolName, ToolStats,
+ ToolStatus,
+};
+use crate::domain::ports::FoldMachine;
+use crate::domain::test::util::{Frame, capturing_warnings};
+use crate::testing::fixtures::{
+ SUBAGENT_CLAUDE_CODE, SUBAGENT_CURSOR, SUBAGENT_MACRO_INMEM, SUBAGENT_OPENCODE,
+};
+use crate::testing::parse_log;
+use agent_client_protocol::schema::v1::ToolKind;
+use serde_json::json;
+
+fn agent_message(messages: &[FoldedMessage]) -> &FoldedMessage {
+ messages
+ .iter()
+ .find(|message| message.author == Author::Agent)
+ .expect("the agent answered")
+}
+
+fn subagent_parts(message: &FoldedMessage) -> Vec<&MessagePart> {
+ message
+ .parts
+ .iter()
+ .filter(|part| {
+ matches!(
+ part,
+ MessagePart::ToolUse {
+ detail: ToolDetail::Subagent { .. },
+ ..
+ }
+ )
+ })
+ .collect()
+}
+
+#[test]
+fn claude_code_nests_the_subagents_calls_and_reports_its_stats() {
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(SUBAGENT_CLAUDE_CODE)));
+ assert_eq!(warnings, vec![], "a clean recording should not warn");
+ let agent = agent_message(&messages);
+
+ // The Bash call the subagent made is nested, not a sibling.
+ let top_level_terminals = agent
+ .parts
+ .iter()
+ .filter(|part| {
+ matches!(
+ part,
+ MessagePart::ToolUse {
+ detail: ToolDetail::Terminal { .. },
+ ..
+ }
+ )
+ })
+ .count();
+ assert_eq!(top_level_terminals, 0, "the child's Bash is not top level");
+
+ let [part] = subagent_parts(agent)[..] else {
+ panic!("exactly one subagent: {:#?}", agent.parts);
+ };
+ let MessagePart::ToolUse {
+ name,
+ status,
+ detail:
+ ToolDetail::Subagent {
+ title,
+ agent_type,
+ description,
+ prompt,
+ background,
+ children,
+ result,
+ },
+ ..
+ } = part
+ else {
+ unreachable!()
+ };
+ assert_eq!(*name, ToolName::native("Agent"));
+ assert_eq!(title, "Add 5+5 with Python", "the description is the title");
+ assert_eq!(*status, ToolStatus::Completed);
+ assert_eq!(agent_type.as_deref(), Some("general-purpose"));
+ assert_eq!(description.as_deref(), Some("Add 5+5 with Python"));
+ assert_eq!(
+ prompt.as_deref(),
+ Some("Run `python3 -c \"print(5+5)\"` in bash and report the output.")
+ );
+ assert!(!background);
+
+ let [child] = &children[..] else {
+ panic!("one child call: {children:#?}");
+ };
+ let MessagePart::ToolUse {
+ name,
+ status,
+ detail:
+ ToolDetail::Terminal {
+ command,
+ output,
+ exit_code,
+ },
+ ..
+ } = child
+ else {
+ panic!("the child is the Bash terminal: {child:?}");
+ };
+ assert_eq!(*name, ToolName::native("Bash"));
+ assert_eq!(*status, ToolStatus::Completed);
+ assert_eq!(command.as_deref(), Some("python3 -c \"print(5+5)\""));
+ assert_eq!(output.as_ref().map(|o| o.as_str()), Some("10"));
+ assert_eq!(*exit_code, Some(0));
+
+ let result = result.as_deref().expect("the subagent reported back");
+ assert_eq!(
+ *result,
+ SubagentResult {
+ text: Some("Output: `10`".to_owned()),
+ error: None,
+ agent_id: Some("af2647314187b6bf1".to_owned()),
+ model: Some("claude-opus-5[1m]".to_owned()),
+ duration_ms: Some(3485),
+ tokens: Some(26077),
+ tool_uses: Some(1),
+ stats: Some(ToolStats {
+ commands: 1,
+ ..ToolStats::default()
+ }),
+ },
+ "the rich toolResponse is kept; the later rawOutput text does not replace its answer"
+ );
+}
+
+#[test]
+fn opencode_reports_the_child_session_and_strips_the_task_wrapper() {
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(SUBAGENT_OPENCODE)));
+ assert_eq!(warnings, vec![]);
+ let agent = agent_message(&messages);
+ let [part] = subagent_parts(agent)[..] else {
+ panic!("exactly one subagent: {:#?}", agent.parts);
+ };
+ let MessagePart::ToolUse {
+ name,
+ detail:
+ ToolDetail::Subagent {
+ agent_type,
+ description,
+ prompt,
+ children,
+ result,
+ ..
+ },
+ ..
+ } = part
+ else {
+ unreachable!()
+ };
+ assert_eq!(*name, ToolName::native("task"));
+ assert_eq!(agent_type.as_deref(), Some("general"));
+ assert_eq!(description.as_deref(), Some("Add numbers with Python"));
+ assert!(prompt.as_deref().unwrap().starts_with("Use Python"));
+ assert!(children.is_empty(), "OpenCode never streams the child");
+ let result = result.as_deref().expect("reported");
+ assert_eq!(result.text.as_deref(), Some("10"));
+ assert_eq!(
+ result.agent_id.as_deref(),
+ Some("ses_f9bd7ee76ffeshjLOLx06ArVK7")
+ );
+ assert_eq!(result.model.as_deref(), Some("openai/gpt-5.6-terra"));
+ assert_eq!(result.error, None);
+}
+
+/// Macro's own agent delegates through its `Subagent` tool, which by name is
+/// a Macro tool; the fold still folds it to the subagent detail, with the
+/// tool's `{ "result" }` response read as the answer rather than shown as
+/// JSON.
+#[test]
+fn the_inmem_agents_subagent_tool_folds_to_a_subagent_not_a_macro_tool() {
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(SUBAGENT_MACRO_INMEM)));
+ assert_eq!(warnings, vec![]);
+ let agent = agent_message(&messages);
+ let [part] = subagent_parts(agent)[..] else {
+ panic!("exactly one subagent: {:#?}", agent.parts);
+ };
+ let MessagePart::ToolUse {
+ name,
+ status,
+ detail:
+ ToolDetail::Subagent {
+ title,
+ agent_type,
+ description,
+ prompt,
+ children,
+ result,
+ ..
+ },
+ ..
+ } = part
+ else {
+ unreachable!()
+ };
+ assert_eq!(*name, ToolName::native("Subagent"));
+ assert_eq!(*status, ToolStatus::Completed);
+ assert_eq!(*agent_type, None);
+ assert_eq!(*description, None);
+ assert!(prompt.as_deref().unwrap().starts_with("Compute 5 + 5"));
+ assert_eq!(
+ title,
+ "Compute 5 + 5 in Python by executing the code, and report the exact numeric result that Python outputs.",
+ "with no description, the brief's first line is the title"
+ );
+ assert!(children.is_empty(), "the child is not streamed");
+ let result = result.as_deref().expect("reported");
+ assert!(result.text.as_deref().unwrap().contains("**10**"));
+ assert_eq!(result.error, None);
+ assert!(
+ !agent.parts.iter().any(|part| matches!(
+ part,
+ MessagePart::ToolUse {
+ detail: ToolDetail::Macro { .. },
+ ..
+ }
+ )),
+ "the delegation must not also fold as a Macro tool"
+ );
+}
+
+/// Any other harness reaches the same tool over Macro's MCP server, with the
+/// response inside MCP's envelope; it is a delegation there too.
+#[test]
+fn the_subagent_tool_over_mcp_folds_to_a_subagent() {
+ let log = r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"go"}]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"claudeCode":{"toolName":"mcp__macro__Subagent"}},"toolCallId":"a","sessionUpdate":"tool_call","rawInput":{"task":"Find the frog poem"},"status":"in_progress","title":"Subagent","kind":"other"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"toolCallId":"a","sessionUpdate":"tool_call_update","status":"completed","rawOutput":{"content":[{"type":"text","text":"{\"result\":\"where quiet frogs go off to sleep.\"}"}]}}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#;
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(log)));
+ assert_eq!(warnings, vec![]);
+ let agent = agent_message(&messages);
+ let [part] = subagent_parts(agent)[..] else {
+ panic!("exactly one subagent: {:#?}", agent.parts);
+ };
+ let MessagePart::ToolUse {
+ name,
+ detail: ToolDetail::Subagent { prompt, result, .. },
+ ..
+ } = part
+ else {
+ unreachable!()
+ };
+ assert_eq!(
+ *name,
+ ToolName::Mcp {
+ server: "macro".to_owned(),
+ tool: "Subagent".to_owned()
+ }
+ );
+ assert_eq!(prompt.as_deref(), Some("Find the frog poem"));
+ assert_eq!(
+ result.as_deref().and_then(|result| result.text.as_deref()),
+ Some("where quiet frogs go off to sleep.")
+ );
+}
+
+#[test]
+fn the_fixtures_name_their_harnesses() {
+ for (fixture, expected) in [
+ (SUBAGENT_CLAUDE_CODE, Harness::ClaudeCode),
+ (SUBAGENT_OPENCODE, Harness::OpenCode),
+ (SUBAGENT_CURSOR, Harness::Cursor),
+ (SUBAGENT_MACRO_INMEM, Harness::Macro),
+ ] {
+ let mut machine = FoldMachineImpl::new();
+ for entry in parse_log(fixture) {
+ let _ = machine.push(entry);
+ }
+ assert_eq!(machine.metadata().harness, expected);
+ }
+}
+
+/// A harness that delivers the child's transcript whole and re-announces the
+/// call with it (Cursor sends the same `tool_call` event for every progress
+/// report) replaces the children rather than doubling them.
+#[test]
+fn a_reannounced_transcript_replaces_the_children() {
+ let announce = |status: &str| {
+ format!(
+ r#"{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{{"sessionId":"s","update":{{"toolCallId":"t","sessionUpdate":"tool_call","rawInput":{{"prompt":"add"}},"status":"{status}","title":"task","kind":"other","rawOutput":{{"result":{{"success":{{"agentId":"bc-1","conversationSteps":[{{"toolCall":{{"toolCallId":"c","shellToolCall":{{"args":{{"command":"echo 10"}},"result":{{"success":{{"stdout":"10\n"}}}}}}}}}},{{"assistantMessage":{{"text":"10"}}}}]}}}}}}}}}}}}}}"#
+ )
+ };
+ let log = [
+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"i","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}}"#.to_owned(),
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"i","result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"cursor-acp","version":"0"}}}}"#.to_owned(),
+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"go"}]}}}"#.to_owned(),
+ announce("in_progress"),
+ announce("completed"),
+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#.to_owned(),
+ ]
+ .join("\n");
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(&log)));
+ assert_eq!(warnings, vec![]);
+ let agent = agent_message(&messages);
+ let [part] = subagent_parts(agent)[..] else {
+ panic!("exactly one subagent: {:#?}", agent.parts);
+ };
+ let MessagePart::ToolUse {
+ detail: ToolDetail::Subagent {
+ children, result, ..
+ },
+ ..
+ } = part
+ else {
+ unreachable!()
+ };
+ assert_eq!(children.len(), 1, "one shell call, not two: {children:#?}");
+ assert_eq!(
+ result.as_deref().and_then(|result| result.text.as_deref()),
+ Some("10")
+ );
+}
+
+/// A harness that re-announces a subagent call (a repeated `tool_call` for the
+/// same id) does not re-send the children's frames, so they are kept.
+#[test]
+fn a_reannounced_subagent_keeps_its_children() {
+ let log = r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"go"}]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"a","sessionUpdate":"tool_call","rawInput":{"prompt":"do it"},"status":"in_progress","title":"Task","kind":"think"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"claudeCode":{"toolName":"Bash","parentToolUseId":"a"}},"toolCallId":"c","sessionUpdate":"tool_call","rawInput":{"command":"ls"},"status":"completed","title":"ls","kind":"execute"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}},"toolCallId":"a","sessionUpdate":"tool_call","rawInput":{"prompt":"do it","description":"Do it"},"status":"completed","title":"Do it","kind":"think"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#;
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(log)));
+ assert_eq!(warnings, vec![]);
+ let agent = agent_message(&messages);
+ let [part] = subagent_parts(agent)[..] else {
+ panic!("one subagent: {:#?}", agent.parts);
+ };
+ let MessagePart::ToolUse {
+ status,
+ detail:
+ ToolDetail::Subagent {
+ description,
+ children,
+ ..
+ },
+ ..
+ } = part
+ else {
+ unreachable!()
+ };
+ assert_eq!(*status, ToolStatus::Completed);
+ assert_eq!(description.as_deref(), Some("Do it"));
+ assert_eq!(children.len(), 1, "the child survived the re-announcement");
+}
+
+/// A child whose parent the fold never saw lands at top level, with a
+/// warning, rather than vanishing.
+#[test]
+fn an_orphaned_child_folds_at_top_level_and_warns() {
+ let log = r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"go"}]}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"claudeCode":{"toolName":"Bash","parentToolUseId":"never-opened"}},"toolCallId":"c","sessionUpdate":"tool_call","rawInput":{"command":"ls"},"status":"completed","title":"ls","kind":"execute"}}}}
+{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"p","result":{"stopReason":"end_turn"}}}"#;
+ let (messages, warnings) = capturing_warnings(|| fold(parse_log(log)));
+ assert_eq!(warnings.len(), 1, "{warnings:?}");
+ let agent = agent_message(&messages);
+ assert!(matches!(
+ &agent.parts[0],
+ MessagePart::ToolUse {
+ detail: ToolDetail::Terminal { .. },
+ ..
+ }
+ ));
+}
+
+#[test]
+fn the_generic_reader_recognizes_the_task_tool_convention() {
+ let generic = Harness::Unknown.reader();
+ let kinded = |kind: ToolKind| Frame::new().kind(kind);
+ for name in ["task", "Task", "Agent"] {
+ assert!(generic.is_subagent(&ToolName::native(name), &kinded(ToolKind::Think).view()));
+ assert!(generic.is_subagent(&ToolName::native(name), &kinded(ToolKind::Other).view()));
+ assert!(
+ !generic.is_subagent(&ToolName::native(name), &kinded(ToolKind::Execute).view()),
+ "a shell command called task is a shell command"
+ );
+ }
+ assert!(!generic.is_subagent(&ToolName::native("Bash"), &kinded(ToolKind::Think).view()));
+
+ let frame = Frame::new().raw_input(json!({
+ "subagent_type": "explore",
+ "description": "Find it",
+ "task": "Look everywhere",
+ "background": true
+ }));
+ let input = generic.subagent_input(&frame.view());
+ assert_eq!(input.agent_type.as_deref(), Some("explore"));
+ assert_eq!(input.description.as_deref(), Some("Find it"));
+ assert_eq!(input.prompt.as_deref(), Some("Look everywhere"));
+ assert_eq!(input.background, Some(true));
+ assert_eq!(
+ generic.subagent_input(&Frame::new().title("anything").view()),
+ Default::default()
+ );
+
+ // Without a structured result the text is whatever the call reported.
+ let text_of = |frame: Frame| generic.subagent_result(&frame.view()).unwrap().text;
+ assert_eq!(
+ text_of(Frame::new().raw_output(json!("done"))).as_deref(),
+ Some("done")
+ );
+ assert_eq!(
+ generic
+ .subagent_result(&Frame::new().raw_output(json!({"error": "nope"})).view())
+ .unwrap()
+ .error
+ .as_deref(),
+ Some("nope")
+ );
+ assert_eq!(
+ text_of(Frame::new().text("from content")).as_deref(),
+ Some("from content")
+ );
+ assert_eq!(generic.subagent_result(&Frame::new().view()), None);
+}
+
+/// While a delegation streams, Claude Code echoes the brief into the content
+/// blocks; that text is the question, not the answer, until the call ends.
+#[test]
+fn content_text_is_an_answer_only_once_the_call_has_finished() {
+ let generic = Harness::Unknown.reader();
+ let streaming = Frame::new()
+ .text("Find the frog poem")
+ .status(ToolStatus::Running);
+ assert_eq!(generic.subagent_result(&streaming.view()), None);
+ let finished = Frame::new()
+ .text("Find the frog poem")
+ .status(ToolStatus::Completed);
+ assert_eq!(
+ generic
+ .subagent_result(&finished.view())
+ .unwrap()
+ .text
+ .as_deref(),
+ Some("Find the frog poem")
+ );
+}
+
+#[test]
+fn claude_code_marks_a_subagent_by_meta_even_under_another_name() {
+ let claude = Harness::ClaudeCode.reader();
+ let flagged = Frame::new()
+ .kind(ToolKind::Other)
+ .meta(json!({"claudeCode": {"toolName": "Agent", "subagent": true}}));
+ assert!(claude.is_subagent(&ToolName::native("Whatever"), &flagged.view()));
+ let unflagged = Frame::new().kind(ToolKind::Other);
+ assert!(!claude.is_subagent(&ToolName::native("Whatever"), &unflagged.view()));
+}
+
+#[test]
+fn opencode_task_wrapper_is_stripped() {
+ assert_eq!(
+ task_result_text(
+ "<task id=\"ses_1\" state=\"completed\">\n<task_result>\n10\n</task_result>\n</task>"
+ ),
+ "10"
+ );
+ assert_eq!(
+ task_result_text(
+ "<task id=\"ses_1\" state=\"error\">\n<task_error>\nboom\n</task_error>\n</task>"
+ ),
+ "boom"
+ );
+ assert_eq!(task_result_text("plain"), "plain");
+}
+
+#[test]
+fn a_subagent_result_merges_later_reports_without_losing_its_answer() {
+ let mut first = SubagentResult {
+ text: Some("answer".to_owned()),
+ agent_id: Some("a".to_owned()),
+ ..SubagentResult::default()
+ };
+ first.merge(SubagentResult {
+ text: Some("boilerplate".to_owned()),
+ model: Some("m".to_owned()),
+ tool_uses: Some(2),
+ ..SubagentResult::default()
+ });
+ assert_eq!(first.text.as_deref(), Some("answer"));
+ assert_eq!(first.agent_id.as_deref(), Some("a"));
+ assert_eq!(first.model.as_deref(), Some("m"));
+ assert_eq!(first.tool_uses, Some(2));
+}
diff --git a/crates/agent_fold/src/domain/test/tool_name.rs b/crates/agent_fold/src/domain/test/tool_name.rs
new file mode 100644
index 0000000000..4645a7ee68
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/tool_name.rs
@@ -0,0 +1,104 @@
+use crate::domain::harness::{self, macro_tools};
+use crate::domain::model::{Harness, ToolName};
+use crate::domain::test::util::Frame;
+use serde_json::json;
+
+fn parse(name: &str) -> ToolName {
+ name.parse().unwrap_or_else(|never| match never {})
+}
+
+fn mcp(server: &str, tool: &str) -> ToolName {
+ ToolName::Mcp {
+ server: server.to_owned(),
+ tool: tool.to_owned(),
+ }
+}
+
+#[test]
+fn splits_claude_code_mcp_names_at_the_server_boundary() {
+ assert_eq!(parse("mcp__macro__SendEmail"), mcp("macro", "SendEmail"));
+ assert_eq!(parse("mcp__deepwiki__ask"), mcp("deepwiki", "ask"));
+ // Single underscores inside either half are part of the name.
+ assert_eq!(
+ parse("mcp__macro__Bulk_Set_Options"),
+ mcp("macro", "Bulk_Set_Options")
+ );
+ assert_eq!(parse("mcp__my_server__Tool"), mcp("my_server", "Tool"));
+}
+
+#[test]
+fn everything_else_is_a_native_name() {
+ for name in [
+ "Bash", "Read", "Task", "mcp", "mcp__", "mcp__x", "mcp____x", "",
+ ] {
+ assert_eq!(parse(name), ToolName::native(name), "{name:?}");
+ }
+}
+
+#[test]
+fn display_drops_the_server_namespace() {
+ assert_eq!(parse("mcp__macro__ReadContent").display(), "ReadContent");
+ assert_eq!(parse("Bash").display(), "Bash");
+}
+
+#[test]
+fn only_macro_mcp_names_are_macro_tools() {
+ assert_eq!(
+ macro_tools::mcp_tool(&parse("mcp__macro__ReadContent")),
+ Some("ReadContent")
+ );
+ assert_eq!(
+ macro_tools::mcp_tool(&parse("mcp__deepwiki__ReadContent")),
+ None
+ );
+ assert_eq!(macro_tools::mcp_tool(&parse("ReadContent")), None);
+}
+
+#[test]
+fn empty_is_the_name_of_a_call_that_named_nothing_yet() {
+ assert!(parse("").is_empty());
+ assert!(!parse("Bash").is_empty());
+}
+
+#[test]
+fn a_harness_name_in_meta_outranks_the_title() {
+ let named = Frame::new()
+ .meta(json!({"claudeCode": {"toolName": "Bash"}}))
+ .title("ls examples");
+ let claude = Harness::ClaudeCode.reader();
+ assert_eq!(
+ harness::tool_name(claude, &named.view()),
+ ToolName::native("Bash")
+ );
+ assert_eq!(
+ harness::tool_name(claude, &Frame::new().title("ls examples").view()),
+ parse("ls examples")
+ );
+ assert_eq!(
+ harness::tool_name(
+ claude,
+ &Frame::new().title("mcp__macro__ReadContent").view()
+ ),
+ mcp("macro", "ReadContent")
+ );
+ // A harness that does not write that namespace reads only the title.
+ let unknown = Harness::Unknown.reader();
+ assert_eq!(
+ harness::tool_name(unknown, &named.view()),
+ parse("ls examples")
+ );
+ // A frame with neither names nothing, which a later patch may fill.
+ assert!(harness::tool_name(claude, &Frame::new().view()).is_empty());
+}
+
+#[test]
+fn wire_form_is_a_tagged_union() {
+ assert_eq!(
+ serde_json::to_value(parse("Bash")).unwrap(),
+ json!({"kind": "native", "name": "Bash"})
+ );
+ assert_eq!(
+ serde_json::to_value(parse("mcp__macro__SendEmail")).unwrap(),
+ json!({"kind": "mcp", "server": "macro", "tool": "SendEmail"})
+ );
+}
diff --git a/crates/agent_fold/src/domain/test/util.rs b/crates/agent_fold/src/domain/test/util.rs
index 6d4fab45a6..85ff13ee16 100644
--- a/crates/agent_fold/src/domain/test/util.rs
+++ b/crates/agent_fold/src/domain/test/util.rs
@@ -5,9 +5,96 @@ pub use crate::testing::{InMemoryLog, TURN, parse_log, parse_log_as, test_sessio
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
+
+use agent_client_protocol::schema::v1::{Meta, ToolCallContent, ToolKind};
+use serde_json::{Value, json};
use tracing::Level;
use tracing::field::{Field, Visit};
+use crate::domain::harness::ToolFrame;
+use crate::domain::model::ToolStatus;
+
+/// An owned tool frame for tests to build a [`ToolFrame`] over: the fields
+/// a reader might look at, each set by a builder method, nothing else.
+#[derive(Debug, Default)]
+pub struct Frame {
+ meta: Option<Meta>,
+ title: Option<String>,
+ kind: Option<ToolKind>,
+ status: Option<ToolStatus>,
+ raw_input: Option<Value>,
+ raw_output: Option<Value>,
+ content: Option<Vec<ToolCallContent>>,
+}
+
+impl Frame {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// `_meta`, from a JSON object.
+ pub fn meta(mut self, meta: Value) -> Self {
+ self.meta = Some(match meta {
+ Value::Object(map) => map,
+ other => panic!("meta must be an object, got {other}"),
+ });
+ self
+ }
+
+ pub fn title(mut self, title: &str) -> Self {
+ self.title = Some(title.to_owned());
+ self
+ }
+
+ pub fn kind(mut self, kind: ToolKind) -> Self {
+ self.kind = Some(kind);
+ self
+ }
+
+ pub fn status(mut self, status: ToolStatus) -> Self {
+ self.status = Some(status);
+ self
+ }
+
+ pub fn raw_input(mut self, raw_input: Value) -> Self {
+ self.raw_input = Some(raw_input);
+ self
+ }
+
+ pub fn raw_output(mut self, raw_output: Value) -> Self {
+ self.raw_output = Some(raw_output);
+ self
+ }
+
+ /// One text content block - what a harness's completion prose arrives
+ /// as. Marks the frame completed too, since that is when readers take
+ /// content text as an answer.
+ pub fn text(mut self, text: &str) -> Self {
+ let block = json!({"type": "content", "content": {"type": "text", "text": text}});
+ self.content
+ .get_or_insert_with(Vec::new)
+ .push(serde_json::from_value(block).expect("a text content block"));
+ if self.status.is_none() {
+ self.status = Some(ToolStatus::Completed);
+ }
+ self
+ }
+
+ /// The borrowed view a reader takes.
+ pub fn view(&self) -> ToolFrame<'_> {
+ ToolFrame {
+ meta: self.meta.as_ref(),
+ title: self.title.as_deref(),
+ kind: self.kind,
+ status: self.status,
+ raw_input: self.raw_input.as_ref(),
+ raw_output: self.raw_output.as_ref(),
+ content: self.content.as_deref(),
+ locations: None,
+ }
+ }
+}
+
/// Everything a captured `WARN` event carried, by field name.
pub type CapturedFields = HashMap<String, String>;
diff --git a/crates/agent_fold/src/inbound/wasm.rs b/crates/agent_fold/src/inbound/wasm.rs
index 1dfa17296b..13fa024319 100644
--- a/crates/agent_fold/src/inbound/wasm.rs
+++ b/crates/agent_fold/src/inbound/wasm.rs
@@ -120,7 +120,7 @@ impl FoldStream {
.map(|event| FoldedStreamEvent::new(self.session, event))
.collect();
- serde_wasm_bindgen::to_value(&events)
+ encode(&events)
.map_err(|error| JsValue::from_str(&format!("fold events are not encodable: {error}")))
}
@@ -133,7 +133,7 @@ impl FoldStream {
/// Returns a JS string describing what could not be encoded.
pub fn metadata(&self) -> Result<JsValue, JsValue> {
let metadata: SessionMetadata = self.machine.metadata().clone().into();
- serde_wasm_bindgen::to_value(&metadata).map_err(|error| {
+ encode(&metadata).map_err(|error| {
JsValue::from_str(&format!("session metadata is not encodable: {error}"))
})
}
@@ -156,7 +156,7 @@ impl FoldStream {
.map(|message| FoldedMessage::new(self.session, message))
.collect();
- serde_wasm_bindgen::to_value(&messages).map_err(|error| {
+ encode(&messages).map_err(|error| {
JsValue::from_str(&format!("folded messages are not encodable: {error}"))
})
}
@@ -191,10 +191,20 @@ fn encode_messages(
.map(|message| FoldedMessage::new(session, message))
.collect();
- serde_wasm_bindgen::to_value(&messages)
+ encode(&messages)
.map_err(|error| JsValue::from_str(&format!("folded messages are not encodable: {error}")))
}
+/// Encode a value for the browser as plain JSON-shaped data.
+///
+/// `serde_wasm_bindgen`'s default turns a `serde_json::Value` object into an
+/// ES `Map`, which `JSON.stringify` renders as `{}` and no reader expects. The
+/// generated TypeScript contract types these fields as plain objects, so the
+/// JSON-compatible serializer is the one that honors it.
+fn encode<T: serde::Serialize>(value: &T) -> Result<JsValue, serde_wasm_bindgen::Error> {
+ serde::Serialize::serialize(value, &serde_wasm_bindgen::Serializer::json_compatible())
+}
+
/// One entry of a session's protocol log, as the endpoint serves it.
#[derive(Deserialize)]
struct LogEntry {
diff --git a/crates/agent_fold/src/inbound/wire/test.rs b/crates/agent_fold/src/inbound/wire/test.rs
index 8b7cb25ebc..f3b410fec2 100644
--- a/crates/agent_fold/src/inbound/wire/test.rs
+++ b/crates/agent_fold/src/inbound/wire/test.rs
@@ -1,5 +1,7 @@
use super::*;
-use crate::domain::model::{Author, PermissionOutcome, ToolDetail, ToolStatus, ToolUseId, TurnId};
+use crate::domain::model::{
+ Author, PermissionOutcome, ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId, UserToolOutcome,
+};
use non_empty::NonEmpty;
use serde_json::json;
@@ -11,15 +13,13 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
request_id: None,
parts: NonEmpty::one(MessagePart::ToolUse {
id: ToolUseId("tool-1".to_owned()),
- label: "Bash".to_owned(),
+ name: ToolName::native("Bash"),
status: ToolStatus::Running,
detail: ToolDetail::Terminal {
command: Some("ls".to_owned()),
output: None,
exit_code: None,
},
- raw_input: Some(Box::new(json!({ "command": "ls" }))),
- raw_output: None,
}),
stop: None,
};
@@ -35,21 +35,49 @@ fn domain_parts_serialize_directly_into_the_browser_contract() {
"parts": [{
"kind": "tool_use",
"id": "tool-1",
- "label": "Bash",
+ "name": { "kind": "native", "name": "Bash" },
"status": "running",
"detail": {
"kind": "terminal",
"command": "ls",
"output": null,
"exitCode": null
- },
- "rawInput": { "command": "ls" },
- "rawOutput": null
+ }
}],
"stop": null
})
);
+ assert_eq!(
+ serde_json::to_value(ToolDetail::UserTool {
+ input: json!({ "subject": "Hi" }),
+ outcome: UserToolOutcome::Draft {
+ draft_id: "d1".to_owned(),
+ thread_id: None,
+ },
+ })
+ .unwrap(),
+ json!({
+ "kind": "user_tool",
+ "input": { "subject": "Hi" },
+ "outcome": { "kind": "draft", "draftId": "d1", "threadId": null }
+ })
+ );
+ assert_eq!(
+ serde_json::to_value(ToolDetail::Macro {
+ input: json!({ "documentId": "x" }),
+ output: None,
+ error: None,
+ })
+ .unwrap(),
+ json!({
+ "kind": "macro",
+ "input": { "documentId": "x" },
+ "output": null,
+ "error": null
+ })
+ );
+
assert_eq!(
serde_json::to_value(MessagePart::Permission {
tool_call: ToolUseId("tool-1".to_owned()),
diff --git a/crates/agent_fold/src/testing/fixtures.rs b/crates/agent_fold/src/testing/fixtures.rs
index 87ee13e75e..4815bceb3a 100644
--- a/crates/agent_fold/src/testing/fixtures.rs
+++ b/crates/agent_fold/src/testing/fixtures.rs
@@ -3,6 +3,11 @@
/// A hand-shaped complete turn with prose, tools, permission, and a clean stop.
pub const TURN: &str = include_str!("../../fixtures/turn.jsonl");
+/// A hand-shaped Claude Code turn calling Macro tools over MCP - a read, a
+/// user tool (`SendEmail`) the user later edits and sends, and a failed call -
+/// with the MCP `CallToolResult` envelope around every output.
+pub const MACRO_MCP: &str = include_str!("../../fixtures/macro_mcp.jsonl");
+
/// A sanitized real resumed session followed by fresh prompts.
pub const RESUMED_AND_CONTINUED: &str =
include_str!("../../fixtures/real/resumed_and_continued.jsonl");
@@ -15,3 +20,30 @@ pub const LONG_MULTI_RESUME: &str = include_str!("../../fixtures/real/long_multi
/// A sanitized real turn containing repeated plan updates.
pub const PLAN_TODO: &str = include_str!("../../fixtures/real/plan_todo.jsonl");
+
+/// A sanitized real Claude Code turn delegating to a subagent: the `Agent`
+/// call, the subagent's own `Bash` call attributed to it, and the rich
+/// `toolResponse` with the subagent's answer and statistics.
+pub const SUBAGENT_CLAUDE_CODE: &str =
+ include_str!("../../fixtures/real/subagent_claude_code.jsonl");
+
+/// A sanitized real OpenCode turn delegating to a subagent: the `task` call
+/// whose completion names the child session and wraps the answer in
+/// `<task_result>`, with nothing of the child streamed.
+pub const SUBAGENT_OPENCODE: &str = include_str!("../../fixtures/real/subagent_opencode.jsonl");
+
+/// A sanitized real Cursor (`cursor-acp`) turn delegating to a subagent: the
+/// `task` call with `subagentType: { unspecified: {} }` and `model:
+/// "default"`, whose completion carries the child's whole transcript in
+/// `rawOutput.result.success.conversationSteps` - thoughts, prose, and two
+/// `shellToolCall`s with their results - plus `agentId` and a `durationMs`
+/// string. Nothing of the child is streamed as its own frames.
+pub const SUBAGENT_CURSOR: &str = include_str!("../../fixtures/real/subagent_cursor.jsonl");
+
+/// A sanitized real turn of Macro's in-process agent (`macro-inmem`)
+/// delegating to a subagent: its native `Subagent` call, flagged
+/// `_meta.macro.subagent: true`, with `{ "task" }` as input and the bare
+/// `{ "result": "<answer>" }` response on completion. Nothing of the child is
+/// streamed.
+pub const SUBAGENT_MACRO_INMEM: &str =
+ include_str!("../../fixtures/real/subagent_macro_inmem.jsonl");
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index 0ad028634a..db64a28587 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -15,12 +15,12 @@ use std::time::Duration;
use agent::types::{AssistantMessagePart, ChatMessage};
use agent::{StreamAccumulator, StreamPart, ToolResponse};
use agent_client_protocol::schema::v1::{
- AgentCapabilities, CancelNotification, ContentBlock, ContentChunk, InitializeRequest,
- InitializeResponse, NewSessionRequest, NewSessionResponse, PromptRequest, PromptResponse,
- ResumeSessionRequest, ResumeSessionResponse, SessionCapabilities, SessionId,
- SessionNotification, SessionResumeCapabilities, SessionUpdate, SetSessionConfigOptionRequest,
- SetSessionConfigOptionResponse, StopReason, ToolCall as AcpToolCall, ToolCallStatus,
- ToolCallUpdate, ToolCallUpdateFields, ToolKind,
+ AgentCapabilities, CancelNotification, ContentBlock, ContentChunk, Implementation,
+ InitializeRequest, InitializeResponse, Meta, NewSessionRequest, NewSessionResponse,
+ PromptRequest, PromptResponse, ResumeSessionRequest, ResumeSessionResponse,
+ SessionCapabilities, SessionId, SessionNotification, SessionResumeCapabilities, SessionUpdate,
+ SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, StopReason,
+ ToolCall as AcpToolCall, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields, ToolKind,
};
use agent_client_protocol::{
Agent, Channel as AcpChannel, Client, ConnectionTo, Error as AcpError,
@@ -40,6 +40,17 @@ mod test;
/// cancelled, so it cannot wedge the session's turn lock forever.
const TURN_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
+/// What this agent calls itself in the `initialize` response. The fold
+/// recognizes the harness by this name, so it is a contract, not a label.
+pub const AGENT_NAME: &str = "macro-inmem";
+
+/// The `_meta` namespace this agent writes its own keys under, mirroring
+/// Claude Code's `claudeCode` layout so the fold reads both the same way.
+pub const META_NAMESPACE: &str = "macro";
+
+/// The one tool in the Macro toolset that delegates to another agent.
+const SUBAGENT_TOOL: &str = "Subagent";
+
/// What one turn reads out of its session's state before running.
struct TurnInput {
/// The conversation so far plus the prompt being answered.
@@ -161,11 +172,11 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
.on_receive_request(
async move |request: InitializeRequest, responder, _connection| {
responder.respond(
- InitializeResponse::new(request.protocol_version).agent_capabilities(
- AgentCapabilities::new().session_capabilities(
+ InitializeResponse::new(request.protocol_version)
+ .agent_capabilities(AgentCapabilities::new().session_capabilities(
SessionCapabilities::new().resume(SessionResumeCapabilities::new()),
- ),
- ),
+ ))
+ .agent_info(Implementation::new(AGENT_NAME, env!("CARGO_PKG_VERSION"))),
)
},
agent_client_protocol::on_receive_request!(),
@@ -384,7 +395,8 @@ fn update_for_part(part: &StreamPart) -> Option<SessionUpdate> {
AcpToolCall::new(call.id.clone(), title)
.kind(tool_kind(&call.name))
.status(ToolCallStatus::InProgress)
- .raw_input(call.json.clone()),
+ .raw_input(call.json.clone())
+ .meta(tool_call_meta(call)),
))
}
StreamPart::ToolResponse(ToolResponse::Json { id, json, .. }) => {
@@ -408,6 +420,25 @@ fn update_for_part(part: &StreamPart) -> Option<SessionUpdate> {
}
}
+/// The `_meta` this agent stamps on a tool call so the fold can read it by
+/// name rather than guess from the title: `macro.toolName` (an MCP tool as
+/// `mcp__<server>__<tool>`, the convention Claude Code set) and
+/// `macro.subagent` on a delegation.
+fn tool_call_meta(call: &agent::ToolCall) -> Meta {
+ let tool_name = match &call.mcp {
+ Some(mcp) => format!("mcp__{}__{}", mcp.service, mcp.tool_name),
+ None => call.name.clone(),
+ };
+ let mut ours = serde_json::Map::new();
+ ours.insert("toolName".to_owned(), serde_json::Value::String(tool_name));
+ if call.mcp.is_none() && call.name == SUBAGENT_TOOL {
+ ours.insert("subagent".to_owned(), serde_json::Value::Bool(true));
+ }
+ let mut meta = Meta::new();
+ meta.insert(META_NAMESPACE.to_owned(), serde_json::Value::Object(ours));
+ meta
+}
+
/// A coarse [`ToolKind`] for a Macro tool name, for client iconography only.
fn tool_kind(name: &str) -> ToolKind {
let name = name.to_ascii_lowercase();
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 8f64075914..24338058f3 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -98,6 +98,14 @@ where
.is_some(),
"the agent must declare resume support or reattachment dies"
);
+ assert_eq!(
+ initialized
+ .agent_info
+ .as_ref()
+ .map(|info| info.name.as_str()),
+ Some(AGENT_NAME),
+ "the fold recognizes this harness by its announced name"
+ );
let session = connection
.send_request(NewSessionRequest::new("/"))
.block_task()
@@ -175,6 +183,64 @@ async fn a_prompt_streams_updates_and_ends_the_turn() {
);
}
+/// Every tool call is stamped with the tool's name under `_meta.macro`, the
+/// way Claude Code stamps `_meta.claudeCode.toolName`: an MCP tool as
+/// `mcp__<server>__<tool>`, a delegation flagged `subagent`.
+#[tokio::test]
+async fn tool_calls_are_stamped_with_their_names_and_subagent_flag() {
+ let engine = Arc::new(ScriptedEngine::new(vec![
+ StreamPart::ToolCall(agent::ToolCall {
+ id: "call-1".into(),
+ name: "ReadContent".into(),
+ json: serde_json::json!({"documentId": "d"}),
+ mcp: None,
+ }),
+ StreamPart::ToolCall(agent::ToolCall {
+ id: "call-2".into(),
+ name: "Subagent".into(),
+ json: serde_json::json!({"task": "count the beans"}),
+ mcp: None,
+ }),
+ StreamPart::ToolCall(agent::ToolCall {
+ id: "call-3".into(),
+ name: "slack__search".into(),
+ json: serde_json::json!({"query": "standup"}),
+ mcp: Some(agent::McpInfo {
+ service: "slack".into(),
+ tool_name: "search".into(),
+ display_name: Some("Search Slack".into()),
+ }),
+ }),
+ ]));
+
+ let (notifications, _) = with_agent(Arc::clone(&engine), async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "go"))
+ .block_task()
+ .await
+ .expect("the prompt should complete")
+ })
+ .await;
+
+ let metas: Vec<serde_json::Value> = notifications
+ .iter()
+ .filter_map(|notification| match &notification.update {
+ SessionUpdate::ToolCall(call) => Some(serde_json::Value::Object(
+ call.meta.clone().expect("meta is stamped"),
+ )),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(
+ metas,
+ vec![
+ serde_json::json!({"macro": {"toolName": "ReadContent"}}),
+ serde_json::json!({"macro": {"toolName": "Subagent", "subagent": true}}),
+ serde_json::json!({"macro": {"toolName": "mcp__slack__search"}}),
+ ]
+ );
+}
+
#[tokio::test]
async fn turns_accumulate_history_and_send_the_model() {
let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content("ok".into())]));