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: ACP elicitation — agents ask the user, and Macro's user tools are reviewed in the turn (#6196)

Wolf Mermelsteinf9ddf64f0a02
diff --git a/Cargo.lock b/Cargo.lock
index e9ce4179e2..fa68973a6c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -364,6 +364,9 @@ dependencies = [
"ai_tools",
"ai_toolset",
"ai_usage",
+ "anyhow",
+ "async-trait",
+ "axum",
"bot_id",
"bytes",
"dashmap",
@@ -378,6 +381,7 @@ dependencies = [
"prompt",
"rig-agent",
"rmcp",
+ "schemars 1.2.1",
"serde",
"serde_json",
"sqlx",
@@ -682,6 +686,7 @@ dependencies = [
"sync_service_client",
"system_properties",
"teams",
+ "thiserror 2.0.18",
"tokio",
"tokio-util",
"tracing",
diff --git a/Cargo.toml b/Cargo.toml
index 58698c7db5..33b683159f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -140,7 +140,9 @@ apollo-parser = "0.8"
# main but not yet in a tagged release):
# https://github.com/agentclientprotocol/rust-sdk/pull/294
# Swap back to a plain version once upstream cuts a release containing it.
-agent-client-protocol = { git = "https://github.com/agentclientprotocol/rust-sdk", rev = "8769d16d10e0c9fa7e662ee18424a4313b06ea88" }
+agent-client-protocol = { git = "https://github.com/agentclientprotocol/rust-sdk", rev = "8769d16d10e0c9fa7e662ee18424a4313b06ea88", features = [
+ "unstable_elicitation",
+] }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
askama = "0.14"
async-graphql = "7.2.1"
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index f63edbcf7e..fcef8bf070 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -24,7 +24,9 @@ export function AgentComposer(props: {
autofocus?: boolean;
}) {
const {
+ blockedOnUser,
composer,
+ elicitation,
loadFailed,
metadata,
pending,
@@ -73,6 +75,15 @@ export function AgentComposer(props: {
<Show when={resuming()}>
<ComposerNotice text="Waking the agent's sandbox…" active />
</Show>
+ <Show when={blockedOnUser()}>
+ <ComposerNotice
+ text={
+ elicitation.canAnswer()
+ ? 'The agent is waiting for your answer above. Messages sent now are queued.'
+ : `The agent is waiting for ${elicitation.ownerName()} to answer above. Messages sent now are queued.`
+ }
+ />
+ </Show>
<AgentInput
placeholder="Message the agent, @mention anything"
autofocus={props.autofocus}
diff --git a/apps/web/src/features/block-agent/component/AgentMessage.tsx b/apps/web/src/features/block-agent/component/AgentMessage.tsx
index 358fc2349c..d95a9c2449 100644
--- a/apps/web/src/features/block-agent/component/AgentMessage.tsx
+++ b/apps/web/src/features/block-agent/component/AgentMessage.tsx
@@ -14,6 +14,7 @@ import { match } from 'ts-pattern';
import { isControlMessage } from '../state/control-message';
import { ActionLine, Thought } from '../ui';
import { ControlPart } from './parts/ControlPart';
+import { ElicitationPart } from './parts/ElicitationPart';
import { PermissionPart } from './parts/PermissionPart';
import { PlanPart } from './parts/PlanPart';
import { TextPart } from './parts/TextPart';
@@ -50,6 +51,7 @@ function AgentMessagePart(props: {
.with({ kind: 'permission' }, (part) => <PermissionPart part={part} />)
.with({ kind: 'plan' }, (part) => <PlanPart part={part} />)
.with({ kind: 'control' }, (part) => <ControlPart part={part} />)
+ .with({ kind: 'elicitation' }, (part) => <ElicitationPart part={part} />)
.exhaustive();
}
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
new file mode 100644
index 0000000000..e29e92d9cb
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.test.tsx
@@ -0,0 +1,522 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * What this part must get right: a form is offered only while the fold says
+ * the agent is still waiting on it, an answer sends exactly one key, and a
+ * URL is never opened without the user pressing Open.
+ */
+
+import type {
+ MessagePart,
+ PendingElicitation,
+} from '@service-agent-fold/generated/types';
+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
+import { fireEvent, render } from '@solidjs/testing-library';
+import type { JSX } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();
+let pending: PendingElicitation | undefined;
+let canAnswer = true;
+
+vi.mock('../../context/AgentSessionContext', () => ({
+ useAgentSession: () => ({
+ bot: () => ({ name: 'Macro Coder' }),
+ elicitation: {
+ pending: () => pending,
+ canAnswer: () => canAnswer,
+ ownerName: () => 'Alice Owner',
+ answering: () => false,
+ respond,
+ },
+ }),
+}));
+
+// The ui barrel reaches kobalte and svg sprites; the layer under test is the
+// part's gating and what it sends, so the card and form are stubs that expose
+// their props. `ElicitationForm` is a real component with its own file, but
+// its inputs are plain HTML so the stub hands back a text box for the first
+// property and an "Other" box when the field allows one.
+vi.mock('../../ui', () => ({
+ ToolCard: (props: {
+ title: JSX.Element;
+ subtitle?: string;
+ trailing?: JSX.Element;
+ status: string;
+ children?: JSX.Element;
+ }) => (
+ <div data-testid="tool-card" data-status={props.status}>
+ <span data-testid="title">{props.title}</span>
+ <span data-testid="subtitle">{props.subtitle}</span>
+ <span data-testid="trailing">{props.trailing}</span>
+ <div data-testid="body">{props.children}</div>
+ </div>
+ ),
+ ElicitationForm: (props: {
+ schema: { properties: { name: string; schema: { type: string } }[] };
+ onChange: (name: string, value: unknown) => void;
+ }) => {
+ const first = props.schema.properties[0]!;
+ return (
+ <div data-testid="form">
+ <button
+ type="button"
+ data-testid="pick-red"
+ onClick={() =>
+ props.onChange(first.name, {
+ kind: 'single_select',
+ selection: { kind: 'option', value: 'Red' },
+ })
+ }
+ />
+ <button
+ type="button"
+ data-testid="type-other"
+ onClick={() =>
+ props.onChange(first.name, {
+ kind: 'single_select',
+ selection: { kind: 'custom', text: 'blue' },
+ })
+ }
+ />
+ </div>
+ );
+ },
+}));
+
+// The composers are the chat block's real editors over calendar and email
+// queries; the part's job is to pick one for the tool under review and wire
+// its sink, so each stub exposes the sink through two buttons and its notice.
+type StubSink = {
+ canAct: () => boolean;
+ lockedNotice: () => string | undefined;
+ onExecute: (args: unknown) => Promise<boolean>;
+ onReject: () => Promise<boolean>;
+};
+function composerStub(kind: string) {
+ return (props: { initialData: unknown; sink: StubSink }) => (
+ <div data-testid={`${kind}-composer`} data-can-act={props.sink.canAct()}>
+ <span data-testid="locked-notice">{props.sink.lockedNotice()}</span>
+ <button
+ type="button"
+ data-testid="composer-execute"
+ onClick={() => void props.sink.onExecute(props.initialData)}
+ />
+ <button
+ type="button"
+ data-testid="composer-reject"
+ onClick={() => void props.sink.onReject()}
+ />
+ </div>
+ );
+}
+vi.mock('@core/component/AI/component/tool/calendar/DraftComposer', () => ({
+ CalendarDraftComposer: composerStub('calendar'),
+}));
+vi.mock('@core/component/AI/component/tool/email/DraftComposer', () => ({
+ EmailDraftComposer: composerStub('email'),
+}));
+vi.mock('./UserToolCall', () => ({
+ UserToolCall: (props: {
+ detail: { outcome: { kind: string } };
+ common: { label: string; status: string };
+ }) => (
+ <div
+ data-testid="user-tool"
+ data-label={props.common.label}
+ data-status={props.common.status}
+ data-outcome={props.detail.outcome.kind}
+ />
+ ),
+}));
+
+import { ElicitationPart } from './ElicitationPart';
+
+type Elicitation = Extract<MessagePart, { kind: 'elicitation' }>;
+
+const colourForm: Elicitation['request'] = {
+ kind: 'form',
+ schema: {
+ title: null,
+ description: null,
+ required: ['question_0'],
+ properties: [
+ {
+ name: 'question_0',
+ title: 'Best colour',
+ description: null,
+ schema: {
+ type: 'string',
+ minLength: null,
+ maxLength: null,
+ pattern: null,
+ format: null,
+ default: null,
+ options: [
+ { value: 'Red', title: 'Red', description: null },
+ { value: 'Blue', title: 'Blue', description: null },
+ ],
+ customField: 'question_0_custom',
+ },
+ },
+ ],
+ },
+};
+
+function part(overrides: Partial<Elicitation> = {}): Elicitation {
+ return {
+ kind: 'elicitation',
+ requestId: 0,
+ toolCall: 'toolu_1',
+ message: 'What is the best colour?',
+ request: colourForm,
+ outcome: { kind: 'pending' },
+ reported: null,
+ toolOutcome: null,
+ ...overrides,
+ };
+}
+
+function live(): PendingElicitation {
+ return {
+ requestId: 0,
+ turn: 0,
+ toolCall: 'toolu_1',
+ message: 'What is the best colour?',
+ request: colourForm,
+ };
+}
+
+beforeEach(() => {
+ respond.mockReset();
+ respond.mockResolvedValue(true);
+ pending = undefined;
+ canAnswer = true;
+});
+
+describe('ElicitationPart', () => {
+ it('offers the form only while the metadata names this question', () => {
+ pending = live();
+ const { queryByTestId, getByTestId } = render(() => (
+ <ElicitationPart part={part()} />
+ ));
+ expect(queryByTestId('form')).not.toBeNull();
+ expect(getByTestId('title').textContent).toContain('Macro Coder is asking');
+ expect(getByTestId('trailing').textContent).toBe('Waiting for you');
+ });
+
+ it('a viewer who is not the owner sees the question locked and named for the owner', () => {
+ pending = live();
+ canAnswer = false;
+ const { getByTestId, getByText } = render(() => (
+ <ElicitationPart part={part()} />
+ ));
+ expect(getByTestId('trailing').textContent).toBe('Waiting for Alice Owner');
+ expect(getByTestId('body').textContent).toContain(
+ 'Only Alice Owner can answer this.'
+ );
+ for (const label of ['Submit', 'Decline', 'Cancel']) {
+ const button = getByText(label).closest('button');
+ expect(button?.disabled).toBe(true);
+ fireEvent.click(getByText(label));
+ }
+ expect(respond).not.toHaveBeenCalled();
+ });
+
+ it('reads as not answered once the agent has moved on', () => {
+ pending = undefined;
+ const { queryByTestId, getByTestId } = render(() => (
+ <ElicitationPart part={part()} />
+ ));
+ expect(queryByTestId('form')).toBeNull();
+ expect(getByTestId('trailing').textContent).toBe('Not answered');
+ });
+
+ it('a different pending question does not make this one live', () => {
+ pending = { ...live(), requestId: 7 };
+ const { queryByTestId } = render(() => <ElicitationPart part={part()} />);
+ expect(queryByTestId('form')).toBeNull();
+ });
+
+ it('submits the chosen option under the property name', () => {
+ pending = live();
+ const { getByTestId, getByText } = render(() => (
+ <ElicitationPart part={part()} />
+ ));
+ fireEvent.click(getByTestId('pick-red'));
+ fireEvent.click(getByText('Submit'));
+ expect(respond).toHaveBeenCalledWith({
+ action: 'accept',
+ content: { question_0: 'Red' },
+ });
+ });
+
+ it('submits custom text under the custom key, and never both', () => {
+ pending = live();
+ const { getByTestId, getByText } = render(() => (
+ <ElicitationPart part={part()} />
+ ));
+ fireEvent.click(getByTestId('type-other'));
+ fireEvent.click(getByText('Submit'));
+ expect(respond).toHaveBeenCalledWith({
+ action: 'accept',
+ content: { question_0_custom: 'blue' },
+ });
+ });
+
+ it('refuses to submit an empty required form', () => {
+ pending = live();
+ const { getByText } = render(() => <ElicitationPart part={part()} />);
+ fireEvent.click(getByText('Submit'));
+ expect(respond).not.toHaveBeenCalled();
+ });
+
+ it('decline and cancel send their actions', () => {
+ pending = live();
+ const { getByText } = render(() => <ElicitationPart part={part()} />);
+ fireEvent.click(getByText('Decline'));
+ expect(respond).toHaveBeenCalledWith({ action: 'decline' });
+ fireEvent.click(getByText('Cancel'));
+ expect(respond).toHaveBeenCalledWith({ action: 'cancel' });
+ });
+
+ it('shows the harness-reported answer over what was sent', () => {
+ const { getByTestId } = render(() => (
+ <ElicitationPart
+ part={part({
+ outcome: {
+ kind: 'accepted',
+ answers: [
+ {
+ name: 'question_0',
+ label: 'Best colour',
+ value: {
+ kind: 'choice',
+ choice: { value: 'Red', title: 'Red' },
+ },
+ },
+ ],
+ },
+ reported: [
+ {
+ name: 'What is the best colour?',
+ label: 'What is the best colour?',
+ value: { kind: 'text', text: 'blue' },
+ },
+ ],
+ })}
+ />
+ ));
+ expect(getByTestId('trailing').textContent).toBe('Answered');
+ expect(getByTestId('body').textContent).toContain('blue');
+ expect(getByTestId('body').textContent).not.toContain('Red');
+ });
+
+ it('a url request shows the host and opens only after consent', async () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ pending = {
+ ...live(),
+ request: {
+ kind: 'url',
+ elicitationId: 'gh-1',
+ url: 'https://agent.example.com/connect?e=gh-1',
+ },
+ };
+ const { getByText } = render(() => (
+ <ElicitationPart
+ part={part({
+ request: {
+ kind: 'url',
+ elicitationId: 'gh-1',
+ url: 'https://agent.example.com/connect?e=gh-1',
+ },
+ })}
+ />
+ ));
+ expect(getByText('agent.example.com')).not.toBeNull();
+ expect(open).not.toHaveBeenCalled();
+ fireEvent.click(getByText('Open'));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(respond).toHaveBeenCalledWith({ action: 'accept' });
+ expect(open).toHaveBeenCalledWith(
+ 'https://agent.example.com/connect?e=gh-1',
+ '_blank',
+ 'noopener,noreferrer'
+ );
+ open.mockRestore();
+ });
+
+ describe('a user tool under review', () => {
+ const eventDraft = {
+ title: 'Q3 sync',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-08-20T17:00:00Z',
+ endsAt: '2026-08-20T17:30:00Z',
+ timeZone: 'UTC',
+ },
+ attendees: [],
+ recurrenceLines: [],
+ addGoogleMeet: false,
+ eventType: 'default',
+ };
+ const emptySchema = {
+ title: null,
+ description: null,
+ properties: [],
+ required: [],
+ };
+ const review = (
+ tool: string,
+ draft: unknown
+ ): Extract<Elicitation['request'], { kind: 'user_tool' }> => ({
+ kind: 'user_tool',
+ tool,
+ draft,
+ schema: emptySchema,
+ });
+
+ it("opens the tool's own composer, and Create answers with the whole draft", () => {
+ const request = review('CreateCalendarEvent', eventDraft);
+ pending = { ...live(), request };
+ const { getByTestId, queryByTestId } = render(() => (
+ <ElicitationPart
+ part={part({ request, message: 'Create calendar event?' })}
+ />
+ ));
+ expect(queryByTestId('form')).toBeNull();
+ const composer = getByTestId('calendar-composer');
+ expect(composer.dataset.canAct).toBe('true');
+ expect(getByTestId('locked-notice').textContent).toBe('');
+ fireEvent.click(getByTestId('composer-execute'));
+ expect(respond).toHaveBeenCalledWith({
+ action: 'accept',
+ content: { draft: JSON.stringify(eventDraft) },
+ });
+ fireEvent.click(getByTestId('composer-reject'));
+ expect(respond).toHaveBeenLastCalledWith({ action: 'decline' });
+ });
+
+ it('routes SendEmail to the email composer', () => {
+ const request = review('SendEmail', {
+ to: [{ email: '[email protected]' }],
+ cc: [],
+ bcc: [],
+ subject: 'Q3 plan',
+ body: 'Hi Alice',
+ });
+ pending = { ...live(), request };
+ const { queryByTestId } = render(() => (
+ <ElicitationPart part={part({ request })} />
+ ));
+ expect(queryByTestId('email-composer')).not.toBeNull();
+ });
+
+ // The email composer offers only Send, so the card carries the decline the
+ // calendar composer answers through its own Cancel.
+ it('an email review can be declined from the card', () => {
+ const request = review('SendEmail', {
+ to: [{ email: '[email protected]' }],
+ cc: [],
+ bcc: [],
+ subject: 'Q3 plan',
+ body: 'Hi Alice',
+ });
+ pending = { ...live(), request };
+ const { getByText } = render(() => (
+ <ElicitationPart part={part({ request })} />
+ ));
+ fireEvent.click(getByText('Cancel'));
+ expect(respond).toHaveBeenCalledWith({ action: 'decline' });
+ });
+
+ it('a viewer who is not the owner gets the composer locked and told who can act', () => {
+ canAnswer = false;
+ const request = review('CreateCalendarEvent', eventDraft);
+ pending = { ...live(), request };
+ const { getByTestId } = render(() => (
+ <ElicitationPart part={part({ request })} />
+ ));
+ expect(getByTestId('calendar-composer').dataset.canAct).toBe('false');
+ expect(getByTestId('locked-notice').textContent).toBe(
+ 'Waiting for Alice Owner to answer.'
+ );
+ fireEvent.click(getByTestId('composer-execute'));
+ expect(respond).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the flat form for a draft the tool's schema rejects", () => {
+ const request = {
+ ...review('CreateCalendarEvent', { nonsense: true }),
+ schema: colourForm.schema,
+ };
+ pending = { ...live(), request };
+ const { queryByTestId } = render(() => (
+ <ElicitationPart part={part({ request })} />
+ ));
+ expect(queryByTestId('calendar-composer')).toBeNull();
+ expect(queryByTestId('form')).not.toBeNull();
+ });
+
+ it('once the tool has reported, the question reads as the tool it finished', () => {
+ const request = review('CreateCalendarEvent', eventDraft);
+ const { getByTestId } = render(() => (
+ <ElicitationPart
+ part={part({
+ request,
+ outcome: { kind: 'accepted', answers: [] },
+ toolOutcome: {
+ kind: 'completed',
+ result: { eventId: 'evt-1', title: 'Q3 sync' },
+ },
+ })}
+ />
+ ));
+ const tool = getByTestId('user-tool');
+ expect(tool.dataset.label).toBe('CreateCalendarEvent');
+ expect(tool.dataset.outcome).toBe('completed');
+ expect(tool.dataset.status).toBe('completed');
+ });
+
+ it('a declined review with no tool report reads as a declined question', () => {
+ const request = review('CreateCalendarEvent', eventDraft);
+ const { getByTestId, queryByTestId } = render(() => (
+ <ElicitationPart
+ part={part({ request, outcome: { kind: 'declined' } })}
+ />
+ ));
+ expect(queryByTestId('user-tool')).toBeNull();
+ expect(getByTestId('trailing').textContent).toBe('Declined');
+ });
+ });
+
+ it('a refused url consent does not open the tab', async () => {
+ const open = vi.spyOn(window, 'open').mockImplementation(() => null);
+ respond.mockResolvedValue(false);
+ pending = {
+ ...live(),
+ request: {
+ kind: 'url',
+ elicitationId: 'gh-1',
+ url: 'https://x.example/y',
+ },
+ };
+ const { getByText } = render(() => (
+ <ElicitationPart
+ part={part({
+ request: {
+ kind: 'url',
+ elicitationId: 'gh-1',
+ url: 'https://x.example/y',
+ },
+ })}
+ />
+ ));
+ fireEvent.click(getByText('Open'));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(open).not.toHaveBeenCalled();
+ open.mockRestore();
+ });
+});
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
new file mode 100644
index 0000000000..5394b4ce1f
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx
@@ -0,0 +1,424 @@
+/**
+ * The agent asking the user a question.
+ *
+ * Interactive only while the fold's metadata still names this question as the
+ * one to answer: a `pending` part on a turn that has ended, or on a dead
+ * connection, reads as "not answered" rather than offering a form the agent
+ * is no longer waiting on. Resolved parts read back what was chosen.
+ *
+ * Only the session's owner can answer (the service refuses anyone else), so
+ * another viewer sees the same live card with its controls disabled and the
+ * owner named as the one it waits on.
+ *
+ * URL mode never opens anything on its own. The card shows the full URL and
+ * its host, and only after the user presses Open does it send the consent and
+ * open a new tab - never an iframe, never a prefetch.
+ */
+
+import { CalendarDraftComposer } from '@core/component/AI/component/tool/calendar/DraftComposer';
+import { EmailDraftComposer } from '@core/component/AI/component/tool/email/DraftComposer';
+import type {
+ AnsweredField,
+ AnsweredValue,
+ MessagePart,
+} from '@service-agent-fold/generated/types';
+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
+import { deserializeToolCall } from '@service-cognition/generated/tools/tool';
+import type {
+ CreateCalendarEvent,
+ SendEmail,
+} from '@service-cognition/generated/tools/types';
+import { Button } from '@ui';
+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import { match } from 'ts-pattern';
+import { useAgentSession } from '../../context/AgentSessionContext';
+import {
+ type FieldValue,
+ initialValues,
+ toContent,
+ validate,
+} from '../../state/elicitation-form';
+import { createElicitationReviewSink } from '../../state/elicitation-review-sink';
+import { ElicitationForm, ToolCard } from '../../ui';
+import { UserToolCall } from './UserToolCall';
+
+type ElicitationPartData = Extract<MessagePart, { kind: 'elicitation' }>;
+type UserToolRequest = Extract<
+ ElicitationPartData['request'],
+ { kind: 'user_tool' }
+>;
+
+function outcomeLabel(part: ElicitationPartData): string {
+ return match(part.outcome)
+ .with({ kind: 'pending' }, () => 'Not answered')
+ .with({ kind: 'accepted' }, () =>
+ match(part.request.kind)
+ .with('url', () => 'Opened')
+ .with('user_tool', () => 'Confirmed')
+ .otherwise(() => 'Answered')
+ )
+ .with({ kind: 'declined' }, () => 'Declined')
+ .with({ kind: 'cancelled' }, () => 'Cancelled')
+ .with({ kind: 'completed' }, () => 'Finished')
+ .with({ kind: 'errored' }, () => 'Refused')
+ .with({ kind: 'unrecognized' }, () => 'Answered')
+ .exhaustive();
+}
+
+export function ElicitationPart(props: { part: ElicitationPartData }) {
+ const { elicitation, bot } = useAgentSession();
+
+ // Live only while the metadata slot names this exact request.
+ const live = () =>
+ props.part.outcome.kind === 'pending' &&
+ elicitation.pending()?.requestId === props.part.requestId;
+
+ const agentName = () => bot()?.name ?? 'The agent';
+ // Controls are inert while an answer is on the wire and for anyone who is
+ // not the owner.
+ const locked = () => elicitation.answering() || !elicitation.canAnswer();
+ const waitingFor = () =>
+ elicitation.canAnswer()
+ ? 'Waiting for you'
+ : `Waiting for ${elicitation.ownerName()}`;
+
+ return (
+ <Show when={live()} fallback={<ResolvedElicitation part={props.part} />}>
+ <ToolCard
+ title={`${agentName()} is asking`}
+ status="running"
+ defaultOpen
+ trailing={<span class="text-ink-muted">{waitingFor()}</span>}
+ >
+ <div class="flex flex-col gap-3 py-1">
+ <div class="text-sm text-ink">{props.part.message}</div>
+ <Show when={!elicitation.canAnswer()}>
+ <div class="text-xs text-ink-extra-muted">
+ Only {elicitation.ownerName()} can answer this.
+ </div>
+ </Show>
+ {match(props.part.request)
+ .with({ kind: 'form' }, (request) => (
+ <LiveForm
+ schema={request.schema}
+ locked={locked()}
+ onRespond={elicitation.respond}
+ />
+ ))
+ .with({ kind: 'user_tool' }, (request) => (
+ <LiveUserTool
+ request={request}
+ toolCall={props.part.toolCall ?? String(props.part.requestId)}
+ locked={locked()}
+ onRespond={elicitation.respond}
+ />
+ ))
+ .with({ kind: 'url' }, (request) => (
+ <LiveUrl
+ url={request.url}
+ locked={locked()}
+ onRespond={elicitation.respond}
+ />
+ ))
+ .with({ kind: 'unrecognized' }, (request) => (
+ <div class="flex flex-col gap-2">
+ <div class="text-xs text-ink-extra-muted italic">
+ This client cannot display a "{request.mode}" request.
+ </div>
+ <DeclineCancel
+ locked={locked()}
+ onRespond={elicitation.respond}
+ />
+ </div>
+ ))
+ .exhaustive()}
+ </div>
+ </ToolCard>
+ </Show>
+ );
+}
+
+function DeclineCancel(props: {
+ locked: boolean;
+ onRespond: (answer: { action: 'decline' } | { action: 'cancel' }) => unknown;
+}) {
+ return (
+ <>
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={props.locked}
+ onClick={() => props.onRespond({ action: 'decline' })}
+ >
+ Decline
+ </Button>
+ <Button
+ variant="ghost"
+ size="xs"
+ disabled={props.locked}
+ onClick={() => props.onRespond({ action: 'cancel' })}
+ >
+ Cancel
+ </Button>
+ </>
+ );
+}
+
+function LiveForm(props: {
+ schema: Extract<ElicitationPartData['request'], { kind: 'form' }>['schema'];
+ locked: boolean;
+ onRespond: (answer: ElicitationAnswer) => unknown;
+}) {
+ const [values, setValues] = createStore(initialValues(props.schema));
+ const [touched, setTouched] = createSignal(false);
+ const errors = createMemo(() => validate(props.schema, values));
+ const shownErrors = () => (touched() ? errors() : {});
+
+ const submit = () => {
+ if (props.locked) return;
+ setTouched(true);
+ if (Object.keys(errors()).length > 0) return;
+ props.onRespond({
+ action: 'accept',
+ content: toContent(props.schema, values),
+ });
+ };
+
+ return (
+ <div class="flex flex-col gap-3">
+ <ElicitationForm
+ schema={props.schema}
+ values={values}
+ errors={shownErrors()}
+ disabled={props.locked}
+ onChange={(name: string, value: FieldValue) => setValues(name, value)}
+ />
+ <div class="flex items-center gap-2">
+ <Button
+ variant="cta"
+ size="xs"
+ disabled={props.locked}
+ onClick={submit}
+ >
+ Submit
+ </Button>
+ <DeclineCancel locked={props.locked} onRespond={props.onRespond} />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * A Macro user tool under review, in the tool's own composer: the calendar
+ * event form for `CreateCalendarEvent`, the email compose for `SendEmail`.
+ * The composer's Create/Send accepts the review with the whole edited draft;
+ * Cancel declines it. A draft the tool's schema rejects, or a tool with no
+ * composer here, falls back to the flat form the agent also sent.
+ */
+function LiveUserTool(props: {
+ request: UserToolRequest;
+ toolCall: string;
+ locked: boolean;
+ onRespond: (answer: ElicitationAnswer) => Promise<boolean>;
+}) {
+ const { elicitation } = useAgentSession();
+ const typed = createMemo(() => {
+ const call = deserializeToolCall({
+ id: props.toolCall,
+ name: props.request.tool,
+ json: props.request.draft,
+ });
+ return call.isOk() ? call.value : undefined;
+ });
+ const sink = <T,>() =>
+ createElicitationReviewSink<T>({
+ canAnswer: elicitation.canAnswer,
+ ownerName: elicitation.ownerName,
+ answering: elicitation.answering,
+ respond: props.onRespond,
+ });
+
+ return (
+ <Switch
+ fallback={
+ <LiveForm
+ schema={props.request.schema}
+ locked={props.locked}
+ onRespond={props.onRespond}
+ />
+ }
+ >
+ <Match when={typed()?.name === 'CreateCalendarEvent' && typed()}>
+ {(tool) => (
+ <CalendarDraftComposer
+ initialData={tool().data as CreateCalendarEvent}
+ sink={sink<CreateCalendarEvent>()}
+ previewKey={props.toolCall}
+ />
+ )}
+ </Match>
+ <Match when={typed()?.name === 'SendEmail' && typed()}>
+ {(tool) => (
+ <div class="flex flex-col gap-2">
+ <EmailDraftComposer
+ initialData={tool().data as SendEmail}
+ sink={sink<SendEmail>()}
+ debugName={`agent-review:${props.toolCall}`}
+ />
+ {/* The email composer has only Send; the calendar one answers a
+ decline through the sink's `onReject`. Without this the turn
+ could only be refused from the chip, or by stopping it. */}
+ <div class="flex items-center gap-2">
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={props.locked}
+ onClick={() => void props.onRespond({ action: 'decline' })}
+ >
+ Cancel
+ </Button>
+ </div>
+ </div>
+ )}
+ </Match>
+ </Switch>
+ );
+}
+
+function LiveUrl(props: {
+ url: string;
+ locked: boolean;
+ onRespond: (answer: {
+ action: 'accept' | 'decline' | 'cancel';
+ }) => Promise<boolean> | unknown;
+}) {
+ const host = () => urlHost(props.url);
+ const open = async () => {
+ if (props.locked) return;
+ // Consent goes to the agent first so it learns the user agreed even if
+ // the popup is blocked; the link below stays as the fallback.
+ const accepted = await props.onRespond({ action: 'accept' });
+ if (accepted === false) return;
+ window.open(props.url, '_blank', 'noopener,noreferrer');
+ };
+ return (
+ <div class="flex flex-col gap-2">
+ <div class="text-xs text-ink-muted">
+ Opens <span class="font-medium text-ink">{host()}</span> in a new tab.
+ </div>
+ <div class="rounded-md border border-edge-muted bg-surface px-2 py-1 font-mono text-xs text-ink-muted break-all">
+ {props.url}
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="cta" size="xs" disabled={props.locked} onClick={open}>
+ Open
+ </Button>
+ <DeclineCancel locked={props.locked} onRespond={props.onRespond} />
+ </div>
+ </div>
+ );
+}
+
+function ResolvedElicitation(props: { part: ElicitationPartData }) {
+ // A reviewed user tool that has reported back reads as the tool: the draft
+ // it ran with and what it did - the same card the chat block's user tools
+ // settle into.
+ const reviewedTool = () => {
+ const { request, toolOutcome } = props.part;
+ return request.kind === 'user_tool' && toolOutcome
+ ? { request, toolOutcome }
+ : undefined;
+ };
+ return (
+ <Show
+ when={reviewedTool()}
+ fallback={<ResolvedQuestion part={props.part} />}
+ >
+ {(reviewed) => (
+ <UserToolCall
+ detail={{
+ kind: 'user_tool',
+ input: reviewed().request.draft,
+ outcome: reviewed().toolOutcome,
+ }}
+ common={{
+ id: props.part.toolCall ?? String(props.part.requestId),
+ label: reviewed().request.tool,
+ status:
+ reviewed().toolOutcome.kind === 'failed' ? 'failed' : 'completed',
+ muted: reviewed().toolOutcome.kind === 'failed',
+ trailing: undefined,
+ }}
+ />
+ )}
+ </Show>
+ );
+}
+
+/** The host of a URL-mode request, for the consent card, or the raw text. */
+function urlHost(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+/** One answer as a line of text. The fold has already resolved the values. */
+function answerText(value: AnsweredValue): string {
+ return match(value)
+ .with(
+ { kind: 'text' },
+ { kind: 'custom' },
+ { kind: 'number' },
+ (v) => v.text
+ )
+ .with({ kind: 'boolean' }, (v) => (v.checked ? 'Yes' : 'No'))
+ .with({ kind: 'choice' }, (v) => v.choice.title ?? v.choice.value)
+ .with({ kind: 'choices' }, (v) =>
+ v.choices.map((choice) => choice.title ?? choice.value).join(', ')
+ )
+ .with({ kind: 'unrecognized' }, (v) => JSON.stringify(v.raw))
+ .exhaustive();
+}
+
+function ResolvedQuestion(props: { part: ElicitationPartData }) {
+ const refusal = () =>
+ props.part.outcome.kind === 'errored'
+ ? props.part.outcome.message
+ : undefined;
+ // The harness's own reading outranks what we sent: it is what the agent
+ // actually acted on. Both arrive from the fold in the same shape.
+ const shown = (): AnsweredField[] =>
+ props.part.reported ??
+ (props.part.outcome.kind === 'accepted' ? props.part.outcome.answers : []);
+
+ return (
+ <ToolCard
+ title="Question"
+ subtitle={props.part.message}
+ status={props.part.outcome.kind === 'errored' ? 'failed' : 'completed'}
+ muted={props.part.outcome.kind === 'errored'}
+ trailing={<span class="text-ink">{outcomeLabel(props.part)}</span>}
+ >
+ <Show when={shown().length > 0 || refusal()}>
+ <div class="flex flex-col gap-2 py-1">
+ <For each={shown()}>
+ {(answer) => (
+ <div class="flex min-w-0 flex-col gap-0.5">
+ <div class="text-xs text-ink-muted">{answer.label}</div>
+ <div class="text-sm text-ink wrap-break-word">
+ {answerText(answer.value)}
+ </div>
+ </div>
+ )}
+ </For>
+ <Show when={refusal()}>
+ {(message) => <div class="text-xs text-failure">{message()}</div>}
+ </Show>
+ </div>
+ </Show>
+ </ToolCard>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
index d735d49b1a..301e1c8756 100644
--- a/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
+++ b/apps/web/src/features/block-agent/component/parts/UserToolCall.tsx
@@ -181,7 +181,8 @@ function htmlText(html: string): string {
);
}
-function EmailDraft(props: { email: SendEmail; inFlight: boolean }) {
+/** The email as drafted, read-only: recipients, subject, body. */
+export function EmailDraft(props: { email: SendEmail; inFlight: boolean }) {
const body = createMemo(() => emailBody(props.email.body));
const recipients = () =>
[
@@ -251,7 +252,8 @@ function attendeeLabel(attendee: AttendeeInput): string {
return attendee.isOptional ? `${attendee.email} (optional)` : attendee.email;
}
-function EventDraft(props: { event: CreateCalendarEvent }) {
+/** The event as drafted, read-only: when, where, who, repeats, notes. */
+export function EventDraft(props: { event: CreateCalendarEvent }) {
const rows = () =>
[
['When', eventWhen(props.event.time)],
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index 7dc5cfe604..aa050204de 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -10,6 +10,7 @@
*/
import { isCursorBotId } from '@core/constant/cursorAgent';
+import { useUserId } from '@core/context/user';
import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
import type {
FoldedMessage,
@@ -34,6 +35,10 @@ import {
type ComposerController,
createComposerController,
} from './create-composer-controller';
+import {
+ createElicitationController,
+ type ElicitationController,
+} from './create-elicitation-controller';
import {
createQueueController,
type QueueController,
@@ -90,7 +95,15 @@ export type AgentSessionState = {
* runtime was disconnected, and a request it must wait on is outstanding.
*/
resuming: Accessor<boolean>;
+ /**
+ * The agent is mid-turn but waiting on the user, not generating: the
+ * fold's metadata names a question to answer. Presentational only -
+ * `working` stays true so queued prompts keep waiting behind the question.
+ */
+ blockedOnUser: Accessor<boolean>;
composer: ComposerController;
+ /** The live question, and the one POST that answers it. */
+ elicitation: ElicitationController;
/**
* The session's server-side action queue: prompts sent mid-turn wait
* there and dispatch one per turn end. The server is the only truth —
@@ -142,6 +155,18 @@ export function AgentSessionProvider(
model: () => feed.metadata()?.model,
controlOutcome: (requestId) => controlOutcome(feed.messages(), requestId),
});
+ const pendingElicitation = () =>
+ isDisconnected(status.status())
+ ? undefined
+ : (feed.metadata()?.pendingElicitation ?? undefined);
+ const viewerId = useUserId();
+ const elicitation = createElicitationController({
+ sessionId,
+ pending: pendingElicitation,
+ ownerId: () => feed.session()?.ownerId,
+ viewerId,
+ });
+ const blockedOnUser = () => working() && pendingElicitation() !== undefined;
// The transcript's "Reply to this" chip hands selected text to the
// composer through here. A plain variable, not a signal: it is only read
@@ -187,7 +212,9 @@ export function AgentSessionProvider(
working,
status: status.status,
resuming,
+ blockedOnUser,
composer,
+ elicitation,
queue,
quoteSelection,
registerQuoteInsert,
diff --git a/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts b/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts
new file mode 100644
index 0000000000..a7a0505be1
--- /dev/null
+++ b/apps/web/src/features/block-agent/context/create-elicitation-controller.test.ts
@@ -0,0 +1,152 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * The controller against a mocked harness client: an answer is one POST on
+ * the agent's request id, only the owner may send it, a 409 is said once,
+ * and the owner is named for everyone else.
+ */
+
+import type { PendingElicitation } from '@service-agent-fold/generated/types';
+import { createRoot, createSignal } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createElicitationController } from './create-elicitation-controller';
+
+const control = vi.hoisted(() => ({
+ calls: [] as { sessionId: string; action: unknown }[],
+ outcome: 'ok' as 'ok' | 'conflict' | 'err' | 'reject',
+}));
+
+vi.mock('@service-agent-harness/client', () => ({
+ agentHarnessServiceClient: {
+ control: vi.fn(async (sessionId: string, action: unknown) => {
+ control.calls.push({ sessionId, action });
+ if (control.outcome === 'reject') throw new Error('network');
+ return {
+ isErr: () => control.outcome !== 'ok',
+ error:
+ control.outcome === 'conflict'
+ ? [{ code: 'CONFLICT' }]
+ : [{ code: 'INTERNAL' }],
+ value: { actionId: 'unused', status: 'sent' },
+ };
+ }),
+ },
+}));
+
+const toast = vi.hoisted(() => ({ failure: vi.fn(), success: vi.fn() }));
+vi.mock('@core/component/Toast/Toast', () => ({ toast }));
+
+vi.mock('@core/user', () => ({
+ tryMacroId: (id: string) => (id.startsWith('macro|') ? id : undefined),
+ getDisplayName: (id: string) =>
+ id === 'macro|[email protected]' ? 'Alice Owner' : '',
+}));
+
+const question: PendingElicitation = {
+ requestId: 43,
+ turn: 0,
+ toolCall: null,
+ message: 'Which colour?',
+ request: {
+ kind: 'form',
+ schema: { title: null, description: null, properties: [], required: [] },
+ },
+};
+
+function setup(options?: { ownerId?: string; viewerId?: string }) {
+ const [pending, setPending] = createSignal<PendingElicitation | undefined>(
+ question
+ );
+ const [ownerId] = createSignal<string | undefined>(
+ 'ownerId' in (options ?? {}) ? options?.ownerId : 'macro|[email protected]'
+ );
+ const [viewerId] = createSignal<string | undefined>(
+ 'viewerId' in (options ?? {}) ? options?.viewerId : 'macro|[email protected]'
+ );
+ const { controller, dispose } = createRoot((dispose) => ({
+ controller: createElicitationController({
+ sessionId: () => 'session-1',
+ pending,
+ ownerId,
+ viewerId,
+ }),
+ dispose,
+ }));
+ return { controller, setPending, dispose };
+}
+
+beforeEach(() => {
+ control.calls = [];
+ control.outcome = 'ok';
+ toast.failure.mockReset();
+});
+
+describe('createElicitationController', () => {
+ it('answers on the agent request id with the action spread into the body', async () => {
+ const { controller, dispose } = setup();
+ expect(controller.canAnswer()).toBe(true);
+ const accepted = await controller.respond({
+ action: 'accept',
+ content: { colour: 'teal' },
+ });
+ expect(accepted).toBe(true);
+ expect(control.calls).toEqual([
+ {
+ sessionId: 'session-1',
+ action: {
+ type: 'respondElicitation',
+ requestId: 43,
+ action: 'accept',
+ content: { colour: 'teal' },
+ },
+ },
+ ]);
+ dispose();
+ });
+
+ it('a viewer who is not the owner cannot answer, and knows who can', async () => {
+ const { controller, dispose } = setup({ viewerId: 'macro|[email protected]' });
+ expect(controller.canAnswer()).toBe(false);
+ expect(controller.ownerName()).toBe('Alice Owner');
+ const sent = await controller.respond({ action: 'decline' });
+ expect(sent).toBe(false);
+ expect(control.calls).toEqual([]);
+ dispose();
+ });
+
+ it('nobody can answer before the session has loaded', () => {
+ const { controller, dispose } = setup({ ownerId: undefined });
+ expect(controller.canAnswer()).toBe(false);
+ expect(controller.ownerName()).toBe('the session owner');
+ dispose();
+ });
+
+ it('a 409 means the agent moved on: said once, nothing else', async () => {
+ control.outcome = 'conflict';
+ const { controller, dispose } = setup();
+ expect(await controller.respond({ action: 'cancel' })).toBe(false);
+ expect(toast.failure).toHaveBeenCalledWith(
+ 'The agent is no longer waiting on that question'
+ );
+ dispose();
+ });
+
+ it('other failures and thrown errors read as a failed send', async () => {
+ control.outcome = 'err';
+ const { controller, dispose } = setup();
+ expect(await controller.respond({ action: 'decline' })).toBe(false);
+ control.outcome = 'reject';
+ expect(await controller.respond({ action: 'decline' })).toBe(false);
+ expect(toast.failure).toHaveBeenCalledTimes(2);
+ expect(toast.failure).toHaveBeenCalledWith("Couldn't send your answer");
+ dispose();
+ });
+
+ it('nothing is sent once the question is gone', async () => {
+ const { controller, setPending, dispose } = setup();
+ setPending(undefined);
+ expect(await controller.respond({ action: 'decline' })).toBe(false);
+ expect(control.calls).toEqual([]);
+ dispose();
+ });
+});
diff --git a/apps/web/src/features/block-agent/context/create-elicitation-controller.ts b/apps/web/src/features/block-agent/context/create-elicitation-controller.ts
new file mode 100644
index 0000000000..b876b03961
--- /dev/null
+++ b/apps/web/src/features/block-agent/context/create-elicitation-controller.ts
@@ -0,0 +1,104 @@
+/**
+ * The block's half of answering an elicitation: which question is live (the
+ * fold's metadata slot), who may answer it, and the one POST that does.
+ *
+ * Not a queue. An answer is a response to a request the agent is blocked on,
+ * so it goes straight out rather than behind queued prompts - and a second
+ * answer to the same question is refused by the server (409), not merged.
+ *
+ * Only the session's owner may answer - the same `OwnerAccessLevel` gate
+ * every other control action has - so a surface shared with other viewers
+ * (the session split, a channel thread) reads {@link ElicitationController.canAnswer}
+ * before offering a form, and names the owner it is waiting on otherwise.
+ */
+
+import { toast } from '@core/component/Toast/Toast';
+import { getDisplayName, tryMacroId } from '@core/user';
+import type { PendingElicitation } from '@service-agent-fold/generated/types';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
+import { type Accessor, createSignal } from 'solid-js';
+
+export type ElicitationController = {
+ /** The question the owner can answer right now, if any. */
+ pending: Accessor<PendingElicitation | undefined>;
+ /**
+ * Whether the viewer is the session's owner, the one user the service
+ * accepts an answer from. `false` until the session has loaded.
+ */
+ canAnswer: Accessor<boolean>;
+ /** The owner's display name, for "waiting for …" when the viewer is not them. */
+ ownerName: Accessor<string>;
+ /** An answer is on the wire. */
+ answering: Accessor<boolean>;
+ /**
+ * Answer the pending question. Resolves `true` when the service accepted
+ * the answer; the fold then shows the outcome. A `409` means the agent is
+ * no longer waiting (someone else answered, a stop cancelled it, or the
+ * connection that asked is gone) - said once, and the metadata refresh
+ * removes the form. A viewer who is not the owner gets `false` without a
+ * request.
+ */
+ respond: (answer: ElicitationAnswer) => Promise<boolean>;
+};
+
+export function createElicitationController(options: {
+ sessionId: Accessor<string | undefined>;
+ pending: Accessor<PendingElicitation | undefined>;
+ /** The session's owner, once the session has loaded. */
+ ownerId: Accessor<string | undefined>;
+ /** The signed-in user looking at the surface. */
+ viewerId: Accessor<string | undefined>;
+}): ElicitationController {
+ const [answering, setAnswering] = createSignal(false);
+
+ const canAnswer = () => {
+ const owner = options.ownerId();
+ return owner !== undefined && owner === options.viewerId();
+ };
+ const ownerName = () => {
+ const owner = options.ownerId();
+ const id = owner === undefined ? undefined : tryMacroId(owner);
+ const name = id ? getDisplayName(id) : '';
+ return name === '' ? 'the session owner' : name;
+ };
+
+ const respond = async (answer: ElicitationAnswer): Promise<boolean> => {
+ const sessionId = options.sessionId();
+ const pending = options.pending();
+ if (!sessionId || !pending || answering() || !canAnswer()) return false;
+ setAnswering(true);
+ try {
+ const result = await agentHarnessServiceClient.control(sessionId, {
+ type: 'respondElicitation',
+ requestId: pending.requestId,
+ ...answer,
+ });
+ if (result.isErr()) {
+ const conflict = result.error.some(
+ (error) => error.code === 'CONFLICT'
+ );
+ toast.failure(
+ conflict
+ ? 'The agent is no longer waiting on that question'
+ : "Couldn't send your answer"
+ );
+ return false;
+ }
+ return true;
+ } catch {
+ toast.failure("Couldn't send your answer");
+ return false;
+ } finally {
+ setAnswering(false);
+ }
+ };
+
+ return {
+ pending: options.pending,
+ canAnswer,
+ ownerName,
+ answering,
+ respond,
+ };
+}
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index ef603a7dfd..1aefc32a49 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -6,13 +6,16 @@
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import type {
+ ElicitationSchema,
FoldedMessage,
ModelOption,
ToolStatus,
} from '@service-agent-fold/generated/types';
import { createSignal, type JSX, onCleanup } from 'solid-js';
+import { createStore } from 'solid-js/store';
import { Message } from '../component/AgentMessage';
import { ReplyToSelection } from '../component/ReplyToSelection';
+import { initialValues, validate } from '../state/elicitation-form';
import {
ActionLine,
AgentInput,
@@ -21,6 +24,7 @@ import {
ComposerNotice,
CountSummary,
DiffChanges,
+ ElicitationForm,
PierreDiff,
QuestionAnswers,
type QuoteInsert,
@@ -355,6 +359,102 @@ const FIXTURE_MESSAGE: FoldedMessage = {
],
};
+/**
+ * The Claude Code colour question after the fold collapsed its custom pair,
+ * plus one of every other field type, so the form's controls can be eyeballed.
+ */
+const FIXTURE_ELICITATION: ElicitationSchema = {
+ title: 'Deployment',
+ description: 'A few details before the agent continues.',
+ required: ['question_0', 'name'],
+ properties: [
+ {
+ name: 'question_0',
+ title: 'Best colour',
+ description: null,
+ schema: {
+ type: 'string',
+ minLength: null,
+ maxLength: null,
+ pattern: null,
+ format: null,
+ default: null,
+ options: [
+ { value: 'Red', title: 'Red', description: 'Warm' },
+ { value: 'Blue', title: 'Blue', description: 'Cool' },
+ { value: 'Green', title: 'Green', description: null },
+ ],
+ customField: 'question_0_custom',
+ },
+ },
+ {
+ name: 'name',
+ title: 'Service name',
+ description: 'Lowercase letters only',
+ schema: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 32,
+ pattern: '^[a-z]+$',
+ format: null,
+ default: 'api',
+ options: [],
+ customField: null,
+ },
+ },
+ {
+ name: 'port',
+ title: 'Port',
+ description: null,
+ schema: { type: 'integer', minimum: 1024, maximum: 65535, default: 3000 },
+ },
+ {
+ name: 'logging',
+ title: 'Enable logging',
+ description: null,
+ schema: { type: 'boolean', default: true },
+ },
+ {
+ name: 'regions',
+ title: 'Regions',
+ description: null,
+ schema: {
+ type: 'multi_select',
+ minItems: 1,
+ maxItems: 2,
+ options: [
+ { value: 'us', title: 'US', description: null },
+ { value: 'eu', title: 'EU', description: null },
+ { value: 'ap', title: 'APAC', description: null },
+ ],
+ default: ['us'],
+ customField: 'regions_custom',
+ },
+ },
+ {
+ name: 'weird',
+ title: 'Hologram',
+ description: null,
+ schema: { type: 'unrecognized', typeName: '_hologram', raw: {} },
+ },
+ ],
+};
+
+function ElicitationFormDemo() {
+ const [values, setValues] = createStore(initialValues(FIXTURE_ELICITATION));
+ const errors = () => validate(FIXTURE_ELICITATION, values);
+ return (
+ <ToolCard title="Macro Coder is asking" status="running" defaultOpen>
+ <ElicitationForm
+ schema={FIXTURE_ELICITATION}
+ values={values}
+ errors={errors()}
+ onChange={(name, value) => setValues(name, value)}
+ />
+ </ToolCard>
+ );
+}
+
export default function AgentUiGallery() {
const pulse = usePulse();
const status = (): ToolStatus => (pulse() ? 'running' : 'completed');
@@ -364,6 +464,10 @@ export default function AgentUiGallery() {
<StaticMarkdownContext>
<div class="size-full overflow-auto">
<div class="mx-auto flex max-w-3xl flex-col gap-8 px-6 py-8">
+ <Item label="ElicitationForm (live validation)">
+ <ElicitationFormDemo />
+ </Item>
+
<Item label="ComposerNotice">
<ComposerNotice text="Waking the agent's sandbox…" active />
</Item>
diff --git a/apps/web/src/features/block-agent/state/elicitation-form.test.ts b/apps/web/src/features/block-agent/state/elicitation-form.test.ts
new file mode 100644
index 0000000000..3e43ef0e14
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/elicitation-form.test.ts
@@ -0,0 +1,283 @@
+import type { ElicitationSchema } from '@service-agent-fold/generated/types';
+import { describe, expect, it } from 'vitest';
+import { initialValues, toContent, validate } from './elicitation-form';
+
+/** The Claude Code single-select question after the fold collapsed its pair. */
+const colour: ElicitationSchema = {
+ title: null,
+ description: null,
+ required: ['question_0'],
+ properties: [
+ {
+ name: 'question_0',
+ title: 'Best colour',
+ description: null,
+ schema: {
+ type: 'string',
+ minLength: null,
+ maxLength: null,
+ pattern: null,
+ format: null,
+ default: null,
+ options: [
+ { value: 'Red', title: 'Red', description: 'Red' },
+ { value: 'Blue', title: 'Blue', description: 'Blue' },
+ ],
+ customField: 'question_0_custom',
+ },
+ },
+ ],
+};
+
+const config: ElicitationSchema = {
+ title: 'Config',
+ description: null,
+ required: ['name', 'port'],
+ properties: [
+ {
+ name: 'name',
+ title: 'Name',
+ description: null,
+ schema: {
+ type: 'string',
+ minLength: 2,
+ maxLength: 5,
+ pattern: '^[a-z]+$',
+ format: null,
+ default: 'svc',
+ options: [],
+ customField: null,
+ },
+ },
+ {
+ name: 'port',
+ title: 'Port',
+ description: null,
+ schema: { type: 'integer', minimum: 1024, maximum: 65535, default: 3000 },
+ },
+ {
+ name: 'ratio',
+ title: null,
+ description: null,
+ schema: { type: 'number', minimum: 0, maximum: 1, default: null },
+ },
+ {
+ name: 'logging',
+ title: 'Logging',
+ description: null,
+ schema: { type: 'boolean', default: true },
+ },
+ {
+ name: 'colours',
+ title: 'Colours',
+ description: null,
+ schema: {
+ type: 'multi_select',
+ minItems: 1,
+ maxItems: 2,
+ options: [
+ { value: 'r', title: 'Red', description: null },
+ { value: 'g', title: 'Green', description: null },
+ { value: 'b', title: null, description: null },
+ ],
+ default: ['r'],
+ customField: null,
+ },
+ },
+ {
+ name: 'weird',
+ title: 'Weird',
+ description: null,
+ schema: { type: 'unrecognized', typeName: '_hologram', raw: {} },
+ },
+ ],
+};
+
+describe('initialValues', () => {
+ it('pre-fills from defaults and picks the right draft shape per field', () => {
+ expect(initialValues(config)).toEqual({
+ name: { kind: 'text', text: 'svc' },
+ port: { kind: 'text', text: '3000' },
+ ratio: { kind: 'text', text: '' },
+ logging: { kind: 'boolean', checked: true },
+ colours: { kind: 'multi_select', values: ['r'], custom: undefined },
+ weird: { kind: 'unsupported' },
+ });
+ expect(initialValues(colour)).toEqual({
+ question_0: { kind: 'single_select', selection: { kind: 'none' } },
+ });
+ });
+});
+
+describe('validate', () => {
+ it('keeps an unselected question and an empty custom answer unanswered', () => {
+ for (const selection of [
+ { kind: 'none' as const },
+ { kind: 'custom' as const, text: '' },
+ { kind: 'custom' as const, text: ' ' },
+ ]) {
+ const values = {
+ question_0: { kind: 'single_select' as const, selection },
+ };
+ expect(validate(colour, values)).toEqual({ question_0: 'Required' });
+ expect(toContent(colour, values)).toEqual({});
+ expect(validate({ ...colour, required: [] }, values)).toEqual({});
+ }
+ });
+
+ it('refuses custom text when the question only allows offered options', () => {
+ const plain = structuredClone(colour);
+ const field = plain.properties[0]!.schema;
+ if (field.type !== 'string') throw new Error('expected a single choice');
+ field.customField = null;
+ const values = {
+ question_0: {
+ kind: 'single_select' as const,
+ selection: { kind: 'custom' as const, text: 'teal' },
+ },
+ };
+ expect(validate(plain, values)).toEqual({
+ question_0: 'Choose one of the offered choices',
+ });
+ expect(toContent(plain, values)).toEqual({});
+ });
+
+ it('passes a defaulted form', () => {
+ expect(validate(config, initialValues(config))).toEqual({});
+ });
+
+ it('requires required fields but not optional or unrecognized ones', () => {
+ const values = initialValues(config);
+ values.name = { kind: 'text', text: '' };
+ expect(validate(config, values)).toEqual({ name: 'Required' });
+ });
+
+ it('checks string length, and leaves pattern and format to the agent', () => {
+ const values = initialValues(config);
+ values.name = { kind: 'text', text: 'a' };
+ expect(validate(config, values).name).toBe('At least 2 characters');
+ values.name = { kind: 'text', text: 'toolong' };
+ expect(validate(config, values).name).toBe('At most 5 characters');
+ // `AB` fails the schema's `^[a-z]+$`, and `nope` is not an email. Neither
+ // is this client's business: the agent enforces both, and an unbounded
+ // agent-supplied regex has no place on the main thread.
+ values.name = { kind: 'text', text: 'AB' };
+ expect(validate(config, values)).toEqual({});
+ });
+
+ it('checks numbers, integers, and multi-select counts', () => {
+ const values = initialValues(config);
+ values.port = { kind: 'text', text: '80' };
+ expect(validate(config, values).port).toBe('At least 1024');
+ values.port = { kind: 'text', text: '3000.5' };
+ expect(validate(config, values).port).toBe('Must be a whole number');
+ values.port = { kind: 'text', text: 'x' };
+ expect(validate(config, values).port).toBe('Not a number');
+ values.port = { kind: 'text', text: '3000' };
+ values.ratio = { kind: 'text', text: '2' };
+ expect(validate(config, values).ratio).toBe('At most 1');
+ values.ratio = { kind: 'text', text: '' };
+ values.colours = {
+ kind: 'multi_select',
+ values: ['r', 'g', 'b'],
+ custom: undefined,
+ };
+ expect(validate(config, values).colours).toBe('Choose at most 2');
+ // Empty is "not answered": fine for an optional field, required otherwise.
+ values.colours = { kind: 'multi_select', values: [], custom: undefined };
+ expect(validate(config, values).colours).toBeUndefined();
+ expect(validate({ ...config, required: ['colours'] }, values).colours).toBe(
+ 'Required'
+ );
+ });
+
+ it('a select with a custom escape counts its custom text as an answer', () => {
+ expect(
+ validate(colour, {
+ question_0: { kind: 'single_select', selection: { kind: 'none' } },
+ })
+ ).toEqual({ question_0: 'Required' });
+ // Typing an answer instead of picking one satisfies the question, and -
+ // for a multi-select - counts towards `minItems`.
+ expect(
+ validate(colour, {
+ question_0: {
+ kind: 'single_select',
+ selection: { kind: 'custom', text: 'blue' },
+ },
+ })
+ ).toEqual({});
+ expect(
+ validate(colour, {
+ question_0: {
+ kind: 'single_select',
+ selection: { kind: 'option', value: 'Red' },
+ },
+ })
+ ).toEqual({});
+ const oneColour: ElicitationSchema = {
+ ...config,
+ required: [],
+ properties: [
+ {
+ ...config.properties[4]!,
+ schema: {
+ ...(config.properties[4]!.schema as Extract<
+ ElicitationSchema['properties'][number]['schema'],
+ { type: 'multi_select' }
+ >),
+ minItems: 1,
+ customField: 'colours_custom',
+ },
+ },
+ ],
+ };
+ expect(
+ validate(oneColour, {
+ colours: { kind: 'multi_select', values: [], custom: 'teal' },
+ })
+ ).toEqual({});
+ });
+
+ it('refuses a value no option offered', () => {
+ expect(
+ validate(colour, {
+ question_0: {
+ kind: 'single_select',
+ selection: { kind: 'option', value: 'Mauve' },
+ },
+ })
+ ).toEqual({ question_0: 'Not one of the offered choices' });
+ });
+});
+
+describe('toContent', () => {
+ it('sends the choice under the property or the custom text under its key', () => {
+ expect(
+ toContent(colour, {
+ question_0: {
+ kind: 'single_select',
+ selection: { kind: 'option', value: 'Red' },
+ },
+ })
+ ).toEqual({ question_0: 'Red' });
+ expect(
+ toContent(colour, {
+ question_0: {
+ kind: 'single_select',
+ selection: { kind: 'custom', text: 'blue' },
+ },
+ })
+ ).toEqual({ question_0_custom: 'blue' });
+ });
+
+ it('types values and omits blanks and unsupported fields', () => {
+ const values = initialValues(config);
+ expect(toContent(config, values)).toEqual({
+ name: 'svc',
+ port: 3000,
+ logging: true,
+ colours: ['r'],
+ });
+ });
+});
diff --git a/apps/web/src/features/block-agent/state/elicitation-form.ts b/apps/web/src/features/block-agent/state/elicitation-form.ts
new file mode 100644
index 0000000000..c3f4612c0c
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/elicitation-form.ts
@@ -0,0 +1,313 @@
+/**
+ * The elicitation form's pure model: what the user has typed, whether it
+ * satisfies the agent's schema, and what goes back on the wire.
+ *
+ * The fold has already normalized the schema (`ElicitationSchema` in the
+ * fold's generated types): one field per question, declaration order kept,
+ * harness idioms collapsed. This file only knows that vocabulary. Decisions
+ * are functions over present values so the component stays a thin shell.
+ *
+ * Draft values are deliberately *not* the answer's shape: a number is held as
+ * the text being typed, and a single choice is either unselected, an offered
+ * option, or custom text. Picking Other with an empty text box is distinct
+ * from not selecting anything. Every match is `.exhaustive()`, so a new
+ * variant must be handled explicitly.
+ *
+ * What this does not validate: `pattern` and `format`. Both are the agent's
+ * to enforce and it does, on every answer, before acting. Re-implementing
+ * them here bought an early hint and cost an unbounded, agent-supplied regex
+ * on the browser's main thread. The client checks what it can check cheaply
+ * and totally - required, lengths, bounds, membership, item counts - and
+ * nothing else.
+ */
+
+import type {
+ ElicitationPropertySchema,
+ ElicitationSchema,
+} from '@service-agent-fold/generated/types';
+import { match, P } from 'ts-pattern';
+
+/** A single-choice draft cannot hold an option and custom text together. */
+export type SingleSelection =
+ | { kind: 'none' }
+ | { kind: 'option'; value: string }
+ | { kind: 'custom'; text: string };
+
+/** One field's draft value, keyed by property name. */
+export type FieldValue =
+ /** Free text, and the raw text of a number while it is being typed. */
+ | { kind: 'text'; text: string }
+ | { kind: 'single_select'; selection: SingleSelection }
+ /** Multiple choices, or the free-text escape when the schema allows one. */
+ | { kind: 'multi_select'; values: string[]; custom: string | undefined }
+ | { kind: 'boolean'; checked: boolean }
+ /** A property type this client cannot render. */
+ | { kind: 'unsupported' };
+
+export type FormValues = Record<string, FieldValue>;
+
+/** A multi-select and its options. */
+type MultiSelectSchema = Extract<
+ ElicitationPropertySchema,
+ { type: 'multi_select' }
+>;
+type MultiSelectValue = Extract<FieldValue, { kind: 'multi_select' }>;
+
+/** Draft values pre-filled from the schema's defaults. */
+export function initialValues(schema: ElicitationSchema): FormValues {
+ const values: FormValues = {};
+ for (const property of schema.properties) {
+ values[property.name] = initialValue(property.schema);
+ }
+ return values;
+}
+
+function initialValue(field: ElicitationPropertySchema): FieldValue {
+ return match(field)
+ .with(
+ { type: 'string', options: P.when((options) => options.length > 0) },
+ (select): FieldValue => ({
+ kind: 'single_select',
+ selection:
+ select.default == null
+ ? { kind: 'none' }
+ : { kind: 'option', value: select.default },
+ })
+ )
+ .with(
+ { type: 'string' },
+ (text): FieldValue => ({
+ kind: 'text',
+ text: text.default ?? '',
+ })
+ )
+ .with(
+ { type: 'number' },
+ { type: 'integer' },
+ (number): FieldValue => ({
+ kind: 'text',
+ text: number.default == null ? '' : String(number.default),
+ })
+ )
+ .with(
+ { type: 'boolean' },
+ (flag): FieldValue => ({
+ kind: 'boolean',
+ checked: flag.default ?? false,
+ })
+ )
+ .with(
+ { type: 'multi_select' },
+ (multi): FieldValue => ({
+ kind: 'multi_select',
+ values: [...multi.default],
+ custom: undefined,
+ })
+ )
+ .with({ type: 'unrecognized' }, (): FieldValue => ({ kind: 'unsupported' }))
+ .exhaustive();
+}
+
+/**
+ * How many answers a select holds: its checked values, plus the custom text
+ * when one was typed. Custom text is an answer, which is what `minItems` and
+ * `maxItems` are counting.
+ */
+function selected(value: MultiSelectValue): number {
+ return value.values.length + (value.custom?.trim() ? 1 : 0);
+}
+
+function isBlank(value: FieldValue | undefined): boolean {
+ if (!value) return true;
+ return match(value)
+ .with({ kind: 'text' }, (text) => text.text.trim().length === 0)
+ .with({ kind: 'single_select' }, ({ selection }) =>
+ match(selection)
+ .with({ kind: 'none' }, () => true)
+ .with({ kind: 'option' }, () => false)
+ .with({ kind: 'custom' }, ({ text }) => text.trim().length === 0)
+ .exhaustive()
+ )
+ .with({ kind: 'multi_select' }, (select) => selected(select) === 0)
+ .with({ kind: 'boolean' }, () => false)
+ .with({ kind: 'unsupported' }, () => true)
+ .exhaustive();
+}
+
+/**
+ * Every field's problem, keyed by property name. Empty when the form can be
+ * submitted.
+ */
+export function validate(
+ schema: ElicitationSchema,
+ values: FormValues
+): Record<string, string> {
+ const errors: Record<string, string> = {};
+ for (const property of schema.properties) {
+ const problem = validateField(
+ property.schema,
+ values[property.name],
+ schema.required.includes(property.name)
+ );
+ if (problem) errors[property.name] = problem;
+ }
+ return errors;
+}
+
+function validateField(
+ field: ElicitationPropertySchema,
+ value: FieldValue | undefined,
+ required: boolean
+): string | undefined {
+ // A field this client cannot render can never be filled in, so a required
+ // one has no valid answer: the user's move is decline, not submit.
+ if (field.type === 'unrecognized') {
+ return required
+ ? `This client cannot answer a ${field.typeName} field`
+ : undefined;
+ }
+ if (isBlank(value)) return required ? 'Required' : undefined;
+ if (!value) return undefined;
+
+ return match(field)
+ .with({ type: 'string' }, (text) =>
+ value.kind === 'single_select'
+ ? match(value.selection)
+ .with({ kind: 'none' }, () => undefined)
+ .with({ kind: 'option' }, ({ value }) =>
+ text.options.some((option) => option.value === value)
+ ? undefined
+ : 'Not one of the offered choices'
+ )
+ .with({ kind: 'custom' }, () =>
+ text.customField ? undefined : 'Choose one of the offered choices'
+ )
+ .exhaustive()
+ : value.kind === 'text'
+ ? length(text, value.text)
+ : undefined
+ )
+ .with({ type: 'number' }, { type: 'integer' }, (number) =>
+ value.kind === 'text'
+ ? bounds(number, value.text, field.type === 'integer')
+ : undefined
+ )
+ .with({ type: 'multi_select' }, (multi) =>
+ value.kind === 'multi_select' ? count(multi, value) : undefined
+ )
+ .with({ type: 'boolean' }, () => undefined)
+ .exhaustive();
+}
+
+function length(
+ field: Extract<ElicitationPropertySchema, { type: 'string' }>,
+ text: string
+): string | undefined {
+ if (field.minLength != null && text.length < field.minLength) {
+ return `At least ${field.minLength} characters`;
+ }
+ if (field.maxLength != null && text.length > field.maxLength) {
+ return `At most ${field.maxLength} characters`;
+ }
+ return undefined;
+}
+
+function bounds(
+ field: Extract<ElicitationPropertySchema, { type: 'number' | 'integer' }>,
+ text: string,
+ whole: boolean
+): string | undefined {
+ const parsed = Number(text);
+ if (!Number.isFinite(parsed)) return 'Not a number';
+ if (whole && !Number.isInteger(parsed)) return 'Must be a whole number';
+ if (field.minimum != null && parsed < field.minimum) {
+ return `At least ${field.minimum}`;
+ }
+ if (field.maximum != null && parsed > field.maximum) {
+ return `At most ${field.maximum}`;
+ }
+ return undefined;
+}
+
+function count(
+ field: Extract<ElicitationPropertySchema, { type: 'multi_select' }>,
+ value: MultiSelectValue
+): string | undefined {
+ const chosen = selected(value);
+ if (field.minItems != null && chosen < field.minItems) {
+ return `Choose at least ${field.minItems}`;
+ }
+ if (field.maxItems != null && chosen > field.maxItems) {
+ return `Choose at most ${field.maxItems}`;
+ }
+ return membership(field, value);
+}
+
+/** A select's values must be offered, and its custom text must be allowed. */
+function membership(
+ field: MultiSelectSchema,
+ value: MultiSelectValue
+): string | undefined {
+ if (value.custom?.trim() && !field.customField) {
+ return 'Choose one of the offered choices';
+ }
+ const stray = value.values.some(
+ (chosen) => !field.options.some((option) => option.value === chosen)
+ );
+ return stray ? 'Not one of the offered choices' : undefined;
+}
+
+/**
+ * The `content` for an `accept`: one key per answered field. A select with a
+ * custom escape sends the choice under the property's name *or* the typed
+ * text under `customField` - never both, which is the one thing the Claude
+ * Code recording showed a naive client getting wrong. Blank optional fields
+ * are omitted rather than sent empty.
+ */
+export function toContent(
+ schema: ElicitationSchema,
+ values: FormValues
+): Record<string, string | number | boolean | string[]> {
+ const content: Record<string, string | number | boolean | string[]> = {};
+ for (const property of schema.properties) {
+ const value = values[property.name];
+ const field = property.schema;
+ if (!value || isBlank(value) || field.type === 'unrecognized') continue;
+ match(value)
+ .with({ kind: 'text' }, (text) => {
+ content[property.name] =
+ field.type === 'number' || field.type === 'integer'
+ ? Number(text.text)
+ : text.text;
+ })
+ .with({ kind: 'boolean' }, (flag) => {
+ content[property.name] = flag.checked;
+ })
+ .with({ kind: 'single_select' }, ({ selection }) => {
+ match(selection)
+ .with({ kind: 'none' }, () => {})
+ .with({ kind: 'option' }, ({ value }) => {
+ content[property.name] = value;
+ })
+ .with({ kind: 'custom' }, ({ text }) => {
+ if (field.type === 'string' && field.customField) {
+ content[field.customField] = text.trim();
+ }
+ })
+ .exhaustive();
+ })
+ .with({ kind: 'multi_select' }, (select) => {
+ const custom = select.custom?.trim();
+ const customField =
+ field.type === 'multi_select' ? field.customField : null;
+ if (custom && customField) {
+ content[customField] = custom;
+ } else if (select.values.length > 0) {
+ content[property.name] = select.values;
+ }
+ })
+ .with({ kind: 'unsupported' }, () => {})
+ .exhaustive();
+ }
+ return content;
+}
diff --git a/apps/web/src/features/block-agent/state/elicitation-review-sink.ts b/apps/web/src/features/block-agent/state/elicitation-review-sink.ts
new file mode 100644
index 0000000000..e03ea94805
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/elicitation-review-sink.ts
@@ -0,0 +1,43 @@
+/**
+ * The agent session's half of a user tool's composer: answering the review
+ * elicitation the agent is blocked on.
+ *
+ * Accept sends the whole edited draft under the `draft` field (Macro's
+ * `_macro/json` extension); the agent's finisher runs the tool with it.
+ * Reject declines. There is nothing to persist between edits - the draft
+ * lives in the form until the user decides - so `onEdit` is left out.
+ */
+
+import type { UserToolReviewSink } from '@core/component/AI/component/tool/user-tool-review';
+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
+import type { Accessor } from 'solid-js';
+
+/** The form field a Macro client sends the whole edited draft under. */
+export const DRAFT_FIELD = 'draft';
+
+export function createElicitationReviewSink<T>(options: {
+ canAnswer: Accessor<boolean>;
+ ownerName: Accessor<string>;
+ answering: Accessor<boolean>;
+ respond: (answer: ElicitationAnswer) => Promise<boolean>;
+}): UserToolReviewSink<T> {
+ const canAct = () => options.canAnswer() && !options.answering();
+ return {
+ canAct,
+ lockedNotice: () =>
+ options.canAnswer()
+ ? undefined
+ : `Waiting for ${options.ownerName()} to answer.`,
+ onExecute: (args) =>
+ canAct()
+ ? options.respond({
+ action: 'accept',
+ content: { [DRAFT_FIELD]: JSON.stringify(args) },
+ })
+ : Promise.resolve(false),
+ onReject: () =>
+ canAct()
+ ? options.respond({ action: 'decline' })
+ : Promise.resolve(false),
+ };
+}
diff --git a/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx b/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx
new file mode 100644
index 0000000000..5ed20ff179
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/ElicitationForm.test.tsx
@@ -0,0 +1,119 @@
+/** @vitest-environment jsdom */
+
+import type { ElicitationSchema } from '@service-agent-fold/generated/types';
+import { cleanup, fireEvent, render } from '@solidjs/testing-library';
+import { createStore } from 'solid-js/store';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { initialValues, toContent, validate } from '../state/elicitation-form';
+import { ElicitationForm } from './ElicitationForm';
+
+// These cases exercise the real radio and text inputs, without loading the
+// unrelated checkbox's UI dependencies.
+vi.mock('@ui', () => ({ Checkbox: () => null }));
+
+afterEach(cleanup);
+
+function question(customField: string | null): ElicitationSchema {
+ return {
+ title: null,
+ description: null,
+ required: ['colour'],
+ properties: [
+ {
+ name: 'colour',
+ title: 'Colour',
+ description: null,
+ schema: {
+ type: 'string',
+ minLength: null,
+ maxLength: null,
+ pattern: null,
+ format: null,
+ default: 'red',
+ options: [
+ { value: 'red', title: 'Red', description: null },
+ { value: '__custom', title: 'A literal option', description: null },
+ ],
+ customField,
+ },
+ },
+ ],
+ };
+}
+
+function form(schema: ElicitationSchema) {
+ return render(() => {
+ const [values, setValues] = createStore(initialValues(schema));
+ return (
+ <>
+ <ElicitationForm
+ schema={schema}
+ values={values}
+ errors={validate(schema, values)}
+ onChange={(name, value) => setValues(name, value)}
+ />
+ <output data-testid="answer">
+ {JSON.stringify(toContent(schema, values))}
+ </output>
+ </>
+ );
+ });
+}
+
+describe('single-choice elicitation', () => {
+ it('switches from the default option to empty Other, custom text, and back', () => {
+ const view = form(question('colour_custom'));
+ const red = view.getByRole('radio', { name: 'Red' }) as HTMLInputElement;
+ const other = view.getByRole('radio', {
+ name: 'Other',
+ }) as HTMLInputElement;
+ const text = view.getByPlaceholderText(
+ 'Type your own answer'
+ ) as HTMLInputElement;
+ const answer = () => JSON.parse(view.getByTestId('answer').textContent!);
+
+ expect(red.checked).toBe(true);
+ expect(answer()).toEqual({ colour: 'red' });
+
+ fireEvent.click(other);
+ expect(other.checked).toBe(true);
+ expect(red.checked).toBe(false);
+ expect(view.getByText('Required')).toBeTruthy();
+ expect(answer()).toEqual({});
+
+ fireEvent.input(text, { target: { value: 'teal' } });
+ expect(other.checked).toBe(true);
+ expect(view.queryByText('Required')).toBeNull();
+ expect(answer()).toEqual({ colour_custom: 'teal' });
+
+ fireEvent.click(red);
+ expect(red.checked).toBe(true);
+ expect(other.checked).toBe(false);
+ expect(text.value).toBe('');
+ expect(answer()).toEqual({ colour: 'red' });
+ });
+
+ it('typing directly selects Other and keeps an empty Other selected', () => {
+ const view = form(question('colour_custom'));
+ const text = view.getByPlaceholderText('Type your own answer');
+ const other = view.getByRole('radio', {
+ name: 'Other',
+ }) as HTMLInputElement;
+ fireEvent.input(text, { target: { value: 'teal' } });
+ expect(other.checked).toBe(true);
+ fireEvent.input(text, { target: { value: '' } });
+ expect(other.checked).toBe(true);
+ expect(view.getByText('Required')).toBeTruthy();
+ expect(view.getByTestId('answer').textContent).toBe('{}');
+ });
+
+ it('only renders Other when allowed, and treats __custom as an ordinary option value', () => {
+ const view = form(question(null));
+ expect(view.queryByRole('radio', { name: 'Other' })).toBeNull();
+ expect(view.queryByPlaceholderText('Type your own answer')).toBeNull();
+ fireEvent.click(view.getByRole('radio', { name: 'A literal option' }));
+ expect(JSON.parse(view.getByTestId('answer').textContent!)).toEqual({
+ colour: '__custom',
+ });
+ });
+});
diff --git a/apps/web/src/features/block-agent/ui/ElicitationForm.tsx b/apps/web/src/features/block-agent/ui/ElicitationForm.tsx
new file mode 100644
index 0000000000..8dfffac875
--- /dev/null
+++ b/apps/web/src/features/block-agent/ui/ElicitationForm.tsx
@@ -0,0 +1,292 @@
+/**
+ * The fields of an elicitation form, props-in JSX-out. The caller owns the
+ * draft values and validation (`state/elicitation-form.ts`) and the card
+ * chrome; this renders one control per property and reports edits.
+ */
+
+import type {
+ ElicitationProperty,
+ ElicitationSchema,
+} from '@service-agent-fold/generated/types';
+import { Checkbox } from '@ui';
+import { For, Show } from 'solid-js';
+import type {
+ FieldValue,
+ FormValues,
+ SingleSelection,
+} from '../state/elicitation-form';
+
+export interface ElicitationFormProps {
+ schema: ElicitationSchema;
+ values: FormValues;
+ errors: Record<string, string>;
+ disabled?: boolean;
+ onChange: (name: string, value: FieldValue) => void;
+}
+
+/** The text a free-text or number field is showing. */
+function textOf(value: FieldValue | undefined): string {
+ return value?.kind === 'text' ? value.text : '';
+}
+
+const INPUT_CLASS =
+ 'w-full rounded-md border border-edge-muted bg-surface px-2 py-1 text-sm text-ink placeholder:text-ink-placeholder focus:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50';
+
+function Field(props: {
+ property: ElicitationProperty;
+ required: boolean;
+ error?: string;
+ children: unknown;
+}) {
+ return (
+ <div class="flex flex-col gap-1">
+ <div class="flex items-baseline gap-1 text-xs text-ink-muted">
+ <span>{props.property.title ?? props.property.name}</span>
+ <Show when={props.required}>
+ <span aria-hidden="true" class="text-failure">
+ *
+ </span>
+ </Show>
+ </div>
+ <Show when={props.property.description}>
+ {(description) => (
+ <div class="text-xs text-ink-extra-muted">{description()}</div>
+ )}
+ </Show>
+ {props.children as never}
+ <Show when={props.error}>
+ {(error) => <div class="text-xs text-failure">{error()}</div>}
+ </Show>
+ </div>
+ );
+}
+
+export function ElicitationForm(props: ElicitationFormProps) {
+ const required = (name: string) => props.schema.required.includes(name);
+
+ return (
+ <div class="flex flex-col gap-3 py-1">
+ <Show when={props.schema.description}>
+ {(description) => (
+ <div class="text-xs text-ink-muted">{description()}</div>
+ )}
+ </Show>
+ <For each={props.schema.properties}>
+ {(property) => {
+ const value = () => props.values[property.name];
+ const selection = (): SingleSelection => {
+ const current = value();
+ return current?.kind === 'single_select'
+ ? current.selection
+ : { kind: 'none' };
+ };
+ const field = property.schema;
+ const set = (next: FieldValue) => props.onChange(property.name, next);
+ return (
+ <Field
+ property={property}
+ required={required(property.name)}
+ error={props.errors[property.name]}
+ >
+ {field.type === 'string' && field.options.length > 0 ? (
+ <div class="flex flex-col gap-1" role="radiogroup">
+ <For each={field.options}>
+ {(option) => {
+ const checked = () => {
+ const current = selection();
+ return (
+ current.kind === 'option' &&
+ current.value === option.value
+ );
+ };
+ return (
+ <label class="flex items-start gap-2 text-sm text-ink">
+ <input
+ type="radio"
+ class="mt-1 accent-accent"
+ name={`elicitation-${property.name}`}
+ value={option.value}
+ checked={checked()}
+ disabled={props.disabled}
+ onChange={() =>
+ set({
+ kind: 'single_select',
+ selection: {
+ kind: 'option',
+ value: option.value,
+ },
+ })
+ }
+ />
+ <span class="flex flex-col">
+ <span>{option.title ?? option.value}</span>
+ <Show when={option.description}>
+ {(description) => (
+ <span class="text-xs text-ink-extra-muted">
+ {description()}
+ </span>
+ )}
+ </Show>
+ </span>
+ </label>
+ );
+ }}
+ </For>
+ <Show when={field.customField}>
+ <label class="flex items-start gap-2 text-sm text-ink">
+ <input
+ type="radio"
+ class="mt-1 accent-accent"
+ name={`elicitation-${property.name}`}
+ checked={selection().kind === 'custom'}
+ disabled={props.disabled}
+ onChange={() =>
+ set({
+ kind: 'single_select',
+ selection: { kind: 'custom', text: '' },
+ })
+ }
+ />
+ <span class="flex min-w-0 flex-1 flex-col gap-1">
+ <span>Other</span>
+ <input
+ type="text"
+ class={INPUT_CLASS}
+ placeholder="Type your own answer"
+ disabled={props.disabled}
+ value={(() => {
+ const current = selection();
+ return current.kind === 'custom'
+ ? current.text
+ : '';
+ })()}
+ onInput={(event) =>
+ set({
+ kind: 'single_select',
+ selection: {
+ kind: 'custom',
+ text: event.currentTarget.value,
+ },
+ })
+ }
+ />
+ </span>
+ </label>
+ </Show>
+ </div>
+ ) : field.type === 'string' ? (
+ <input
+ type={
+ field.format === 'email'
+ ? 'email'
+ : field.format === 'uri'
+ ? 'url'
+ : 'text'
+ }
+ class={INPUT_CLASS}
+ disabled={props.disabled}
+ value={textOf(value())}
+ onInput={(event) =>
+ set({ kind: 'text', text: event.currentTarget.value })
+ }
+ />
+ ) : field.type === 'number' || field.type === 'integer' ? (
+ <input
+ type="number"
+ class={INPUT_CLASS}
+ disabled={props.disabled}
+ step={field.type === 'integer' ? 1 : 'any'}
+ min={field.minimum ?? undefined}
+ max={field.maximum ?? undefined}
+ value={textOf(value())}
+ onInput={(event) =>
+ set({ kind: 'text', text: event.currentTarget.value })
+ }
+ />
+ ) : field.type === 'boolean' ? (
+ <Checkbox
+ checked={(() => {
+ const current = value();
+ return current?.kind === 'boolean' && current.checked;
+ })()}
+ disabled={props.disabled}
+ onChange={(checked) => set({ kind: 'boolean', checked })}
+ >
+ <Checkbox.Control />
+ <Checkbox.Label class="text-sm text-ink">Yes</Checkbox.Label>
+ </Checkbox>
+ ) : field.type === 'multi_select' ? (
+ <div class="flex flex-col gap-1">
+ <For each={field.options}>
+ {(option) => {
+ const selected = () => {
+ const current = value();
+ return current?.kind === 'multi_select'
+ ? current.values
+ : [];
+ };
+ return (
+ <Checkbox
+ checked={selected().includes(option.value)}
+ disabled={props.disabled}
+ onChange={(checked) =>
+ set({
+ kind: 'multi_select',
+ values: checked
+ ? [...selected(), option.value]
+ : selected().filter(
+ (item) => item !== option.value
+ ),
+ custom: undefined,
+ })
+ }
+ >
+ <Checkbox.Control />
+ <Checkbox.Label class="flex flex-col text-sm text-ink">
+ <span>{option.title ?? option.value}</span>
+ <Show when={option.description}>
+ {(description) => (
+ <span class="text-xs text-ink-extra-muted">
+ {description()}
+ </span>
+ )}
+ </Show>
+ </Checkbox.Label>
+ </Checkbox>
+ );
+ }}
+ </For>
+ <Show when={field.customField}>
+ <input
+ type="text"
+ class={INPUT_CLASS}
+ placeholder="Or type your own answer"
+ disabled={props.disabled}
+ value={(() => {
+ const current = value();
+ return current?.kind === 'multi_select'
+ ? (current.custom ?? '')
+ : '';
+ })()}
+ onInput={(event) =>
+ set({
+ kind: 'multi_select',
+ values: [],
+ custom: event.currentTarget.value,
+ })
+ }
+ />
+ </Show>
+ </div>
+ ) : (
+ <div class="text-xs text-ink-extra-muted italic">
+ This client cannot display a {field.typeName} field.
+ </div>
+ )}
+ </Field>
+ );
+ }}
+ </For>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index bdc2a239a6..1285d6ad05 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -21,6 +21,10 @@ export {
} from './ComposerNotice';
export { type CountItem, CountSummary } from './CountSummary';
export { DiffChanges, type DiffChangesProps } from './DiffChanges';
+export {
+ ElicitationForm,
+ type ElicitationFormProps,
+} from './ElicitationForm';
export { FoldedAnsiText } from './FoldedAnsiText';
export { FoldedOutput } from './FoldedOutput';
export { FoldedPathList } from './FoldedPathList';
diff --git a/apps/web/src/lib/core/agent-fold/client.ts b/apps/web/src/lib/core/agent-fold/client.ts
index d4f767ec3a..d74f576b19 100644
--- a/apps/web/src/lib/core/agent-fold/client.ts
+++ b/apps/web/src/lib/core/agent-fold/client.ts
@@ -28,6 +28,7 @@ const EMPTY_METADATA: SessionMetadata = {
title: null,
availableCommands: [],
status: null,
+ pendingElicitation: null,
};
interface Pending {
diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx
index ef29195187..361fdf0cb2 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/ChatCompose.tsx
@@ -1,36 +1,24 @@
-import { createCalendarEventFormController } from '@app/features/calendar/components/composer/create-calendar-event-form-controller';
-import { EventForm } from '@app/features/calendar/components/composer/EventForm';
-import type { EventEditorSubmitValues } from '@app/features/calendar/components/composer/event-form-model';
-import { DEFAULT_CALENDAR_SOURCE } from '@app/features/calendar/types';
-import {
- calendarDisplayLabel,
- spansMultipleInboxes,
-} from '@app/features/calendar/utils/calendar-label';
+/**
+ * Chat's half of a deferred `CreateCalendarEvent`: the composer over the
+ * pending call, finished through the cognition tool endpoints.
+ *
+ * Edits are persisted as they happen (`updateToolCall`) so a reload keeps
+ * them; Create runs the call (`callTool`) and Cancel rejects it
+ * (`rejectToolCall`), and either writes the outcome back into the chat's
+ * message so the card re-renders as the finished tool.
+ */
+
import { useChatContext } from '@core/component/AI/context';
import type { AssistantMessagePart } from '@core/component/AI/types';
import { toast } from '@core/component/Toast/Toast';
-import { recipientEntityMapper, useContacts } from '@core/user';
-import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
import { invalidateCalendarOccurrences } from '@queries/calendar/occurrences';
import { useChatQuery } from '@queries/chat';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { NamedTool } from '@service-cognition/generated/tools/tool';
import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';
import { debounce } from '@solid-primitives/scheduled';
-import { Layer } from '@ui';
-import {
- createMemo,
- createSignal,
- ErrorBoundary,
- onCleanup,
- Show,
- Suspense,
-} from 'solid-js';
-import { CalendarToolEventPreview } from './EventPreview';
-import {
- createCalendarEventToEditorInitialValues,
- editorSubmitValuesToCreateCalendarEvent,
-} from './event-form-adapter';
+import type { UserToolReviewSink } from '../user-tool-review';
+import { CalendarDraftComposer } from './DraftComposer';
import { openToolCalendarEvent } from './open-tool-event';
type CreateCalendarEventResponse = NamedTool<
@@ -98,117 +86,41 @@ function updateToolParts(
return changed ? nextParts : parts;
}
-function CalendarChatComposeFallback() {
- return (
- <Layer depth={2}>
- <div
- role="status"
- aria-label="Loading calendar editor"
- aria-busy="true"
- class="flex min-h-64 animate-pulse flex-col gap-6 rounded-xl border border-edge-muted bg-surface p-4 shadow-sm"
- >
- <span class="sr-only">Loading calendar editor</span>
-
- <div class="flex flex-col gap-4">
- <div class="flex items-center gap-2">
- <div class="h-7 w-28 rounded-lg bg-skeleton" />
- <div class="h-7 w-28 rounded-lg bg-skeleton" />
- <div class="h-7 w-16 rounded-lg bg-skeleton" />
- </div>
- <div class="h-6 w-2/5 rounded-md bg-skeleton" />
- <div class="h-3 w-3/4 rounded-full bg-skeleton" />
- </div>
-
- <div class="flex flex-wrap gap-2">
- <div class="h-7 w-24 rounded-full bg-skeleton" />
- <div class="h-7 w-28 rounded-full bg-skeleton" />
- <div class="h-7 w-20 rounded-full bg-skeleton" />
- <div class="h-7 w-24 rounded-full bg-skeleton" />
- </div>
-
- <div class="mt-auto flex justify-end gap-3">
- <div class="h-8 w-16 rounded-lg bg-skeleton" />
- <div class="h-8 w-28 rounded-lg bg-skeleton" />
- </div>
- </div>
- </Layer>
- );
-}
-
-/** Inline editor for a deferred CreateCalendarEvent tool call. */
-function CalendarChatComposeContent(props: CalendarChatComposeProps) {
+/** Inline editor for a deferred CreateCalendarEvent tool call in a chat. */
+export function CalendarChatCompose(props: CalendarChatComposeProps) {
const chat = useChatContext();
const chatQuery = useChatQuery(() => props.chatId);
- const calendarsQuery = useVisibleCalendarsQuery();
- const contacts = useContacts();
- const [operation, setOperation] = createSignal<'create' | 'reject'>();
const isOwner = () => chatQuery.data?.userAccessLevel === 'owner';
- const ownerGateDisabled = () => !chatQuery.isSuccess || !isOwner();
- const showOwnerDisabledMessage = () => chatQuery.isSuccess && !isOwner();
- const interactionLocked = () =>
- toolFinalized ||
- ownerGateDisabled() ||
- props.streamLocked === true ||
- operation() !== undefined;
-
- const guestOptions = createMemo(() =>
- contacts().map(recipientEntityMapper('user'))
- );
- const writableCalendars = createMemo(
- () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []
- );
- const calendarsSpanInboxes = () => spansMultipleInboxes(writableCalendars());
- const calendarOptions = createMemo(() =>
- writableCalendars().map((calendar) => ({
- id: calendar.id,
- label: calendarDisplayLabel(calendar, calendarsSpanInboxes()),
- color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,
- defaultReminders: calendar.defaultReminders,
- isPrimary: calendar.isPrimary,
- }))
- );
+ const ownerKnown = () => chatQuery.isSuccess;
+ const canAct = () => ownerKnown() && isOwner() && props.streamLocked !== true;
+ const lockedNotice = () => {
+ if (ownerKnown() && !isOwner()) {
+ return 'Only the chat owner can create or edit this calendar event.';
+ }
+ if (props.streamLocked) {
+ return 'Waiting for the response to finish before this event can be edited.';
+ }
+ return undefined;
+ };
- let toolFinalized = false;
+ // Edits go to the server debounced and in order, so the stored call is what
+ // the user last saw even if they reload before confirming.
let lastPersistedSnapshot = JSON.stringify(props.initialData);
let lastEnqueuedSnapshot = lastPersistedSnapshot;
+ let latestArgs: CreateCalendarEvent | undefined;
let persistenceQueue = Promise.resolve();
-
- const controller = createCalendarEventFormController({
- initialValue: createCalendarEventToEditorInitialValues(props.initialData),
- calendarOptions,
- guestOptions,
- recurrenceTimeZone:
- props.initialData.time.kind === 'timed'
- ? (props.initialData.time.timeZone ?? undefined)
- : undefined,
- onChange: scheduleUpdate,
- });
-
- function currentArgs(values = controller.submitValues()) {
- return values
- ? editorSubmitValuesToCreateCalendarEvent(values, props.initialData)
- : undefined;
- }
-
- const debouncedUpdate = debounce(() => void enqueueUpdate(), 150);
-
- function scheduleUpdate() {
- if (toolFinalized || interactionLocked()) return;
- debouncedUpdate();
- }
+ let finalized = false;
function enqueueUpdate() {
- if (toolFinalized || operation() !== undefined) return persistenceQueue;
- const args = currentArgs();
- if (!args) return persistenceQueue;
-
+ const args = latestArgs;
+ if (finalized || !args) return persistenceQueue;
const snapshot = JSON.stringify(args);
if (snapshot === lastEnqueuedSnapshot) return persistenceQueue;
lastEnqueuedSnapshot = snapshot;
persistenceQueue = persistenceQueue.then(async () => {
- if (toolFinalized) return;
+ if (finalized) return;
try {
const result =
await cognitionApiServiceClient.updateToolCall<'CreateCalendarEvent'>(
@@ -231,9 +143,9 @@ function CalendarChatComposeContent(props: CalendarChatComposeProps) {
}
toast.failure('Failed to save calendar event changes');
});
-
return persistenceQueue;
}
+ const debouncedUpdate = debounce(() => void enqueueUpdate(), 150);
function updateLocalResponse(
response: CreateCalendarEventResponse,
@@ -255,135 +167,68 @@ function CalendarChatComposeContent(props: CalendarChatComposeProps) {
);
}
- async function handleCreate(values: EventEditorSubmitValues) {
- if (interactionLocked()) return;
- setOperation('create');
- debouncedUpdate.clear();
- await persistenceQueue;
-
- const args = currentArgs(values);
- if (!args) {
- setOperation(undefined);
- return;
- }
- const result =
- await cognitionApiServiceClient.callTool<'CreateCalendarEvent'>({
+ const sink: UserToolReviewSink<CreateCalendarEvent> = {
+ canAct,
+ lockedNotice,
+ onEdit: (args) => {
+ latestArgs = args;
+ debouncedUpdate();
+ },
+ onExecute: async (args) => {
+ debouncedUpdate.clear();
+ await persistenceQueue;
+ const result =
+ await cognitionApiServiceClient.callTool<'CreateCalendarEvent'>({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ args,
+ });
+ if (result.isErr()) {
+ toast.failure('Failed to create calendar event');
+ return false;
+ }
+ const event = createdEvent(result.value);
+ if (!event) {
+ toast.failure('Failed to create calendar event', {
+ subtext: toolError(result.value),
+ });
+ return false;
+ }
+ finalized = true;
+ updateLocalResponse(result.value as CreateCalendarEventResponse, args);
+ void invalidateCalendarOccurrences();
+ toast.success('Calendar event created', {
+ actions: [
+ { label: 'Open', onClick: () => openToolCalendarEvent(event) },
+ ],
+ });
+ return true;
+ },
+ onReject: async () => {
+ debouncedUpdate.clear();
+ await persistenceQueue;
+ const result = await cognitionApiServiceClient.rejectToolCall({
chat_id: props.chatId,
messageId: props.messageId,
toolCallId: props.toolCallId,
- args,
- });
-
- if (result.isErr()) {
- setOperation(undefined);
- toast.failure('Failed to create calendar event');
- return;
- }
-
- const event = createdEvent(result.value);
- if (!event) {
- setOperation(undefined);
- toast.failure('Failed to create calendar event', {
- subtext: toolError(result.value),
});
- return;
- }
-
- toolFinalized = true;
- setOperation(undefined);
- updateLocalResponse(result.value as CreateCalendarEventResponse, args);
- void invalidateCalendarOccurrences();
- toast.success('Calendar event created', {
- actions: [{ label: 'Open', onClick: () => openToolCalendarEvent(event) }],
- });
- }
-
- async function handleCancel() {
- if (interactionLocked()) return;
- setOperation('reject');
- debouncedUpdate.clear();
- await persistenceQueue;
-
- const result = await cognitionApiServiceClient.rejectToolCall({
- chat_id: props.chatId,
- messageId: props.messageId,
- toolCallId: props.toolCallId,
- });
- if (result.isErr()) {
- setOperation(undefined);
- toast.failure('Failed to cancel calendar event');
- return;
- }
-
- toolFinalized = true;
- setOperation(undefined);
- updateLocalResponse('Rejected');
- }
-
- onCleanup(() => debouncedUpdate.clear());
-
- return (
- <Layer depth={2}>
- <div class="flex min-h-0 w-full flex-col gap-4">
- <div
- data-calendar-tool-composer
- class="flex min-h-80 max-h-128 min-w-0 flex-col gap-3 rounded-xl border border-edge-muted bg-surface p-4 text-ink shadow-sm"
- >
- <Show when={showOwnerDisabledMessage()}>
- <p class="text-xs text-ink-extra-muted/60">
- Only the chat owner can create or edit this calendar event.
- </p>
- </Show>
- <Show when={props.streamLocked && !showOwnerDisabledMessage()}>
- <p class="text-xs text-ink-extra-muted/60">
- Waiting for the response to finish before this event can be
- edited.
- </p>
- </Show>
- <EventForm
- controller={controller}
- class="min-w-0"
- disabled={
- toolFinalized ||
- ownerGateDisabled() ||
- props.streamLocked === true ||
- operation() === 'reject'
- }
- pending={operation() === 'create'}
- onCancel={() => void handleCancel()}
- onSubmit={(values) => void handleCreate(values)}
- />
- </div>
- <ErrorBoundary
- fallback={
- <div class="flex h-96 items-center justify-center rounded-xl border border-edge-muted bg-surface p-4 text-center text-xs text-ink-muted shadow-sm">
- Calendar preview unavailable.
- </div>
- }
- >
- <CalendarToolEventPreview
- controller={controller}
- eventId={`calendar-tool-preview:${props.toolCallId}`}
- showPeriodLabel
- showNavigationControls
- timeZone={
- props.initialData.time.kind === 'timed'
- ? (props.initialData.time.timeZone ?? undefined)
- : undefined
- }
- class="h-96 shrink-0"
- />
- </ErrorBoundary>
- </div>
- </Layer>
- );
-}
+ if (result.isErr()) {
+ toast.failure('Failed to cancel calendar event');
+ return false;
+ }
+ finalized = true;
+ updateLocalResponse('Rejected');
+ return true;
+ },
+ onDispose: () => debouncedUpdate.clear(),
+ };
-/** Query-scoped boundary for the deferred calendar editor. */
-export function CalendarChatCompose(props: CalendarChatComposeProps) {
return (
- <Suspense fallback={<CalendarChatComposeFallback />}>
- <CalendarChatComposeContent {...props} />
- </Suspense>
+ <CalendarDraftComposer
+ initialData={props.initialData}
+ sink={sink}
+ previewKey={props.toolCallId}
+ />
);
}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx
new file mode 100644
index 0000000000..a498337b83
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/calendar/DraftComposer.tsx
@@ -0,0 +1,210 @@
+/**
+ * The calendar event composer for a drafted `CreateCalendarEvent` call, with
+ * no opinion about where the draft came from or where the decision goes.
+ *
+ * Chat mounts it over a pending user tool and finishes the call through the
+ * cognition endpoints; an agent session mounts it over a review elicitation
+ * and answers the agent. Both hand in a {@link UserToolReviewSink}; the
+ * composer only knows how to edit the draft and what the two buttons mean.
+ */
+
+import { createCalendarEventFormController } from '@app/features/calendar/components/composer/create-calendar-event-form-controller';
+import { EventForm } from '@app/features/calendar/components/composer/EventForm';
+import type { EventEditorSubmitValues } from '@app/features/calendar/components/composer/event-form-model';
+import { DEFAULT_CALENDAR_SOURCE } from '@app/features/calendar/types';
+import {
+ calendarDisplayLabel,
+ spansMultipleInboxes,
+} from '@app/features/calendar/utils/calendar-label';
+import { recipientEntityMapper, useContacts } from '@core/user';
+import { useVisibleCalendarsQuery } from '@queries/calendar/calendars';
+import type { CreateCalendarEvent } from '@service-cognition/generated/tools/types';
+import { Layer } from '@ui';
+import {
+ createMemo,
+ createSignal,
+ ErrorBoundary,
+ onCleanup,
+ Show,
+ Suspense,
+} from 'solid-js';
+import type { UserToolReviewSink } from '../user-tool-review';
+import { CalendarToolEventPreview } from './EventPreview';
+import {
+ createCalendarEventToEditorInitialValues,
+ editorSubmitValuesToCreateCalendarEvent,
+} from './event-form-adapter';
+
+export type CalendarDraftComposerProps = {
+ /** The draft as the agent wrote it. */
+ initialData: CreateCalendarEvent;
+ /** Where edits, the confirmation and the rejection go. */
+ sink: UserToolReviewSink<CreateCalendarEvent>;
+ /** A key for the preview's synthetic event; the call's id in practice. */
+ previewKey: string;
+ /** Show the calendar preview under the form. On by default. */
+ showPreview?: boolean;
+};
+
+function CalendarDraftComposerFallback() {
+ return (
+ <Layer depth={2}>
+ <div
+ role="status"
+ aria-label="Loading calendar editor"
+ aria-busy="true"
+ class="flex min-h-64 animate-pulse flex-col gap-6 rounded-xl border border-edge-muted bg-surface p-4 shadow-sm"
+ >
+ <span class="sr-only">Loading calendar editor</span>
+
+ <div class="flex flex-col gap-4">
+ <div class="flex items-center gap-2">
+ <div class="h-7 w-28 rounded-lg bg-skeleton" />
+ <div class="h-7 w-28 rounded-lg bg-skeleton" />
+ <div class="h-7 w-16 rounded-lg bg-skeleton" />
+ </div>
+ <div class="h-6 w-2/5 rounded-md bg-skeleton" />
+ <div class="h-3 w-3/4 rounded-full bg-skeleton" />
+ </div>
+
+ <div class="flex flex-wrap gap-2">
+ <div class="h-7 w-24 rounded-full bg-skeleton" />
+ <div class="h-7 w-28 rounded-full bg-skeleton" />
+ <div class="h-7 w-20 rounded-full bg-skeleton" />
+ <div class="h-7 w-24 rounded-full bg-skeleton" />
+ </div>
+
+ <div class="mt-auto flex justify-end gap-3">
+ <div class="h-8 w-16 rounded-lg bg-skeleton" />
+ <div class="h-8 w-28 rounded-lg bg-skeleton" />
+ </div>
+ </div>
+ </Layer>
+ );
+}
+
+function CalendarDraftComposerContent(props: CalendarDraftComposerProps) {
+ const calendarsQuery = useVisibleCalendarsQuery();
+ const contacts = useContacts();
+ const [operation, setOperation] = createSignal<'create' | 'reject'>();
+ let finalized = false;
+
+ const interactionLocked = () =>
+ finalized || !props.sink.canAct() || operation() !== undefined;
+
+ const guestOptions = createMemo(() =>
+ contacts().map(recipientEntityMapper('user'))
+ );
+ const writableCalendars = createMemo(
+ () => calendarsQuery.data?.filter((calendar) => calendar.isWritable) ?? []
+ );
+ const calendarsSpanInboxes = () => spansMultipleInboxes(writableCalendars());
+ const calendarOptions = createMemo(() =>
+ writableCalendars().map((calendar) => ({
+ id: calendar.id,
+ label: calendarDisplayLabel(calendar, calendarsSpanInboxes()),
+ color: calendar.color ?? DEFAULT_CALENDAR_SOURCE.color,
+ defaultReminders: calendar.defaultReminders,
+ isPrimary: calendar.isPrimary,
+ }))
+ );
+
+ const controller = createCalendarEventFormController({
+ initialValue: createCalendarEventToEditorInitialValues(props.initialData),
+ calendarOptions,
+ guestOptions,
+ recurrenceTimeZone:
+ props.initialData.time.kind === 'timed'
+ ? (props.initialData.time.timeZone ?? undefined)
+ : undefined,
+ onChange: () => {
+ if (interactionLocked()) return;
+ const args = currentArgs();
+ if (args) props.sink.onEdit?.(args);
+ },
+ });
+
+ function currentArgs(values = controller.submitValues()) {
+ return values
+ ? editorSubmitValuesToCreateCalendarEvent(values, props.initialData)
+ : undefined;
+ }
+
+ async function handleCreate(values: EventEditorSubmitValues) {
+ if (interactionLocked()) return;
+ const args = currentArgs(values);
+ if (!args) return;
+ setOperation('create');
+ const done = await props.sink.onExecute(args);
+ setOperation(undefined);
+ if (done) finalized = true;
+ }
+
+ async function handleCancel() {
+ if (interactionLocked()) return;
+ setOperation('reject');
+ const done = await props.sink.onReject();
+ setOperation(undefined);
+ if (done) finalized = true;
+ }
+
+ onCleanup(() => props.sink.onDispose?.());
+
+ return (
+ <Layer depth={2}>
+ <div class="flex min-h-0 w-full flex-col gap-4">
+ <div
+ data-calendar-tool-composer
+ class="flex min-h-80 max-h-128 min-w-0 flex-col gap-3 rounded-xl border border-edge-muted bg-surface p-4 text-ink shadow-sm"
+ >
+ <Show when={props.sink.lockedNotice()}>
+ {(notice) => (
+ <p class="text-xs text-ink-extra-muted/60">{notice()}</p>
+ )}
+ </Show>
+ <EventForm
+ controller={controller}
+ class="min-w-0"
+ disabled={
+ finalized || !props.sink.canAct() || operation() === 'reject'
+ }
+ pending={operation() === 'create'}
+ onCancel={() => void handleCancel()}
+ onSubmit={(values) => void handleCreate(values)}
+ />
+ </div>
+ <Show when={props.showPreview !== false}>
+ <ErrorBoundary
+ fallback={
+ <div class="flex h-96 items-center justify-center rounded-xl border border-edge-muted bg-surface p-4 text-center text-xs text-ink-muted shadow-sm">
+ Calendar preview unavailable.
+ </div>
+ }
+ >
+ <CalendarToolEventPreview
+ controller={controller}
+ eventId={`calendar-tool-preview:${props.previewKey}`}
+ showPeriodLabel
+ showNavigationControls
+ timeZone={
+ props.initialData.time.kind === 'timed'
+ ? (props.initialData.time.timeZone ?? undefined)
+ : undefined
+ }
+ class="h-96 shrink-0"
+ />
+ </ErrorBoundary>
+ </Show>
+ </div>
+ </Layer>
+ );
+}
+
+/** Query-scoped boundary for the calendar draft composer. */
+export function CalendarDraftComposer(props: CalendarDraftComposerProps) {
+ return (
+ <Suspense fallback={<CalendarDraftComposerFallback />}>
+ <CalendarDraftComposerContent {...props} />
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx
index 41b9c7a29d..c037bd9f39 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/ChatCompose.tsx
@@ -1,32 +1,22 @@
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
-import {
- ComposeLayout,
- EmailComposeToolbar,
-} from '@block-email/component/compose';
-import {
- type ComposeContextValue,
- ComposeProvider,
- type ComposeValidationError,
-} from '@block-email/component/compose/ComposeContext';
-import { SignaturePreview } from '@block-email/component/compose/SignaturePreview';
-import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';
+/**
+ * Chat's half of a deferred `SendEmail`: the composer over the pending call,
+ * finished through the cognition tool endpoints.
+ *
+ * Edits are persisted as they settle (`updateToolCall`, then a `userEdited`
+ * response so the card keeps rendering as a composer); Send runs the call
+ * (`callTool`) and writes the sent outcome back into the chat's message.
+ */
+
import type { EmailRecipient } from '@block-email/component/EmailContext';
-import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';
-import { prepareEmailBody } from '@block-email/util/prepareEmailBody';
-import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';
import { useChatContext } from '@core/component/AI/context';
import type { AssistantMessagePart } from '@core/component/AI/types';
import { toast } from '@core/component/Toast/Toast';
-import { enableEmailSignatures } from '@core/constant/featureFlags';
-
import { useChatQuery } from '@queries/chat';
-import { useEmailLinksQuery, useEmailSignature } from '@queries/email/link';
import { cognitionApiServiceClient } from '@service-cognition/client';
import type { SendEmail } from '@service-cognition/generated/tools/types';
-import { debounce } from '@solid-primitives/scheduled';
-import { cn } from '@ui';
-import type { LexicalEditor } from 'lexical';
-import { createMemo, createSignal, type JSX, Show } from 'solid-js';
+import type { JSX } from 'solid-js';
+import type { UserToolReviewSink } from '../user-tool-review';
+import { EmailDraftComposer } from './DraftComposer';
type ComposeToolProps = {
chatId: string;
@@ -48,23 +38,6 @@ type SendEmailSnapshot = {
to: Array<{ email: string; name: string | null }>;
};
-function toEmailRecipients(
- items: Array<{ email: string; name?: string | null }>
-): EmailRecipient[] {
- return items.map(convertContactInfoToEmailRecipient);
-}
-
-function fromEmailRecipients(
- items: EmailRecipient[]
-): Array<{ email: string; name: string | null }> {
- return items.map((recipient) => {
- const email = 'email' in recipient.data ? recipient.data.email : '';
- const name =
- 'name' in recipient.data ? (recipient.data.name ?? null) : null;
- return { email, name };
- });
-}
-
function createSendEmailSnapshot(data: SendEmail): SendEmailSnapshot {
return {
to: (data.to ?? []).map((item) => ({
@@ -159,116 +132,27 @@ export function ComposeTool(props: ComposeToolProps) {
const chat = useChatContext();
const chatQuery = useChatQuery(() => props.chatId);
const isOwner = () => chatQuery.data?.userAccessLevel === 'owner';
- const ownerGateDisabled = () => !chatQuery.isSuccess || !isOwner();
- const showOwnerDisabledMessage = () =>
- chatQuery.isSuccess && !isOwner() && props.readOnly !== true;
- const uiDisabled = () =>
- ownerGateDisabled() ||
- props.readOnly === true ||
- props.streamLocked === true;
- const emailLinksQuery = useEmailLinksQuery();
- // The inbox this card sends from — always the first linked inbox (shown as
- // "from"); the backend resolves the same default at send time.
- const sendingLink = createMemo(() => emailLinksQuery.data?.links?.[0]);
- const fromAddress = () => sendingLink()?.email_address;
- const signature = useEmailSignature(() => sendingLink()?.id);
- const emailSignaturesFlag = useFeatureFlag(enableEmailSignatures);
- // Whether this email includes the signature. Defaults on; the preview's ✕
- // drops it for this one message. Mirrors the normal composer.
- // Initialize from the persisted tool args so a dismiss survives re-render /
- // reload; only an explicit false counts as dismissed.
- const [includeSignature, setIncludeSignature] = createSignal(
- props.initialData.includeSignature !== false
- );
- const isReplyOrForward = () => Boolean(props.initialData.replyingToId);
- // Signature to preview (and inject on send): a new compose always shows it; a
- // reply/forward only when the inbox's "add to replies & forwards" setting is
- // on. Hidden once dismissed and in the read-only (sent) state. Shown during
- // streaming too — the composer's overlay blocks interaction until it ends.
- const previewSignatureHtml = (): string | undefined => {
- if (!emailSignaturesFlag().enabled) return undefined;
+ const ownerKnown = () => chatQuery.isSuccess;
+ const canAct = () =>
+ ownerKnown() &&
+ isOwner() &&
+ props.readOnly !== true &&
+ props.streamLocked !== true;
+ const lockedNotice = () => {
if (props.readOnly) return undefined;
- if (!includeSignature()) return undefined;
- const sig = signature();
- if (!sig) return undefined;
- if (isReplyOrForward()) {
- return sendingLink()?.settings.signature_on_replies_forwards
- ? sig
- : undefined;
+ if (ownerKnown() && !isOwner()) {
+ return 'Only the chat owner can send or edit this email.';
}
- return sig;
+ return undefined;
};
- const [recipients, setRecipients] = createSignal({
- to: toEmailRecipients(
- (props.initialData.to ?? []).map((r) => ({ ...r, name: r.name ?? null }))
- ),
- cc: toEmailRecipients(
- (props.initialData.cc ?? []).map((r) => ({ ...r, name: r.name ?? null }))
- ),
- bcc: toEmailRecipients(
- (props.initialData.bcc ?? []).map((r) => ({
- ...r,
- name: r.name ?? null,
- }))
- ),
- });
- const [subject, setSubject] = createSignal(props.initialData.subject ?? '');
- const [isSending, setIsSending] = createSignal(false);
- const [editor, setEditor] = createSignal<LexicalEditor>();
- const [validationErrors, setValidationErrors] = createSignal<
- ComposeValidationError[]
- >([]);
- let toolFinalized = false;
let lastPersistedSnapshot = createSendEmailSnapshot(props.initialData);
+ let finalized = false;
- function collectArgs(): SendEmail {
- return {
- to: fromEmailRecipients(recipients().to),
- cc: fromEmailRecipients(recipients().cc),
- bcc: fromEmailRecipients(recipients().bcc),
- subject: subject(),
- body: prepareEmailBody(editor())?.bodyHtml ?? '',
- replyingToId: props.initialData.replyingToId,
- // Omit to use the backend default policy; false only when dismissed.
- includeSignature: includeSignature() ? undefined : false,
- };
- }
-
- function validate(): boolean {
- const errors: ComposeValidationError[] = [];
-
- if (recipients().to.length === 0) {
- errors.push({
- type: 'no_recipient',
- message: 'Add at least one recipient',
- });
- }
-
- if (!prepareEmailBody(editor())?.bodyText.trim()) {
- errors.push({ type: 'no_message', message: 'Write a message' });
- }
-
- setValidationErrors(errors);
- return errors.length === 0;
- }
-
- const debouncedUpdate = debounce(flushUpdate, 150);
-
- function scheduleUpdate() {
- if (toolFinalized) return;
- debouncedUpdate();
- }
-
- async function flushUpdate() {
- if (toolFinalized) return;
-
- const args = collectArgs();
+ async function persistEdit(args: SendEmail) {
+ if (finalized) return;
const nextSnapshot = createSendEmailSnapshot(args);
-
- if (sameSendEmailSnapshot(nextSnapshot, lastPersistedSnapshot)) {
- return;
- }
+ if (sameSendEmailSnapshot(nextSnapshot, lastPersistedSnapshot)) return;
const updateCallResult =
await cognitionApiServiceClient.updateToolCall<'SendEmail'>({
@@ -277,7 +161,6 @@ export function ComposeTool(props: ComposeToolProps) {
toolCallId: props.toolCallId,
args,
});
-
if (updateCallResult.isErr()) {
toast.failure('Failed to save changes');
return;
@@ -290,7 +173,6 @@ export function ComposeTool(props: ComposeToolProps) {
toolCallId: props.toolCallId,
response: { UserAction: 'userEdited' },
});
-
if (updateResponseResult.isErr()) {
toast.failure('Failed to save changes');
return;
@@ -299,156 +181,58 @@ export function ComposeTool(props: ComposeToolProps) {
lastPersistedSnapshot = nextSnapshot;
}
- async function handleSend() {
- if (ownerGateDisabled()) return;
-
- if (!validate()) return;
-
- setIsSending(true);
- const args = collectArgs();
-
- const result = await cognitionApiServiceClient.callTool<'SendEmail'>({
- chat_id: props.chatId,
- messageId: props.messageId,
- toolCallId: props.toolCallId,
- args,
- });
-
- setIsSending(false);
-
- if (result.isErr()) {
- toast.failure('Failed to send email');
- return;
- }
-
- const sentResponse = getSentToolResponse(result.value);
- if (sentResponse) {
- toolFinalized = true;
- chat.setMessages((messages) =>
- messages.map((message) => {
- if (
- message.id !== props.messageId ||
- !Array.isArray(message.content)
- ) {
- return message;
- }
-
- const content = updateToolParts(
- message.content,
- args,
- toSentResponse(sentResponse.message_id, sentResponse.thread_id),
- props.toolCallId
- );
-
- if (content === message.content) return message;
- return { ...message, content };
- })
- );
- }
-
- toast.success('Email sent');
- }
-
- // `body` is markdown while the AI is drafting, but every persist path
- // (flushUpdate, handleSend) replaces it with the base64url-encoded HTML
- // that the SendEmail tool contract requires at send time. Decode and route
- // to the editor slot that matches what the field actually holds.
- const initialBody = (): { html?: string; markdown?: string } => {
- const body = props.initialData.body;
- if (!body) return {};
- const decoded = decodeBase64Utf8(body);
- if (decoded.startsWith('<body')) return { html: decoded };
- return { markdown: body };
- };
-
- const ctx: ComposeContextValue = {
- subject,
- attachments: () => [],
- sendTime: () => undefined,
- initialHtml: () => initialBody().html,
- initialMarkdown: () => initialBody().markdown,
- setRecipients: (field, value) => {
- setRecipients((prev) => ({ ...prev, [field]: value }));
- scheduleUpdate();
- },
- setSubject: (value) => {
- setSubject(value);
- scheduleUpdate();
- },
- onContentChange: () => {
- scheduleUpdate();
+ const sink: UserToolReviewSink<SendEmail> = {
+ canAct,
+ lockedNotice,
+ onEdit: (args) => void persistEdit(args),
+ onExecute: async (args) => {
+ const result = await cognitionApiServiceClient.callTool<'SendEmail'>({
+ chat_id: props.chatId,
+ messageId: props.messageId,
+ toolCallId: props.toolCallId,
+ args,
+ });
+ if (result.isErr()) {
+ toast.failure('Failed to send email');
+ return false;
+ }
+ const sentResponse = getSentToolResponse(result.value);
+ if (sentResponse) {
+ finalized = true;
+ chat.setMessages((messages) =>
+ messages.map((message) => {
+ if (
+ message.id !== props.messageId ||
+ !Array.isArray(message.content)
+ ) {
+ return message;
+ }
+ const content = updateToolParts(
+ message.content,
+ args,
+ toSentResponse(sentResponse.message_id, sentResponse.thread_id),
+ props.toolCallId
+ );
+ if (content === message.content) return message;
+ return { ...message, content };
+ })
+ );
+ }
+ toast.success('Email sent');
+ return sentResponse !== null;
},
- onAddAttachments: (_: DraftFormAttachment[]) => {},
- onRemoveAttachment: (_: DraftFormAttachment) => {},
- captureEditor: setEditor,
- onSend: handleSend,
- disabled: () =>
- isSending() ||
- ownerGateDisabled() ||
- props.readOnly === true ||
- props.streamLocked === true,
- isSending,
- isSavingDraft: () => false,
- hasDraft: () => false,
- hasPaidAccess: () => true,
- focusRecipientsOnMount: false,
- includeSelf: true,
- hideAttachments: true,
- recipientOptions: () => [
- ...recipients().to,
- ...recipients().cc,
- ...recipients().bcc,
- ...(props.recipientOptions ?? []),
- ],
- validationError: (type) => validationErrors().find((e) => e.type === type),
- fromAddress,
- recipients,
- // Read-only preview of the signature the backend appends on send, with a ✕
- // to drop it for this one email (persisted via the userEdited update).
- signaturePreview: () => (
- <Show when={previewSignatureHtml()}>
- {(html) => (
- <SignaturePreview
- html={html()}
- onDismiss={() => {
- setIncludeSignature(false);
- scheduleUpdate();
- }}
- />
- )}
- </Show>
- ),
+ // Chat's email card has no reject control; the composer never calls this.
+ onReject: async () => false,
};
return (
- <ComposeProvider value={ctx}>
- <div class="relative">
- <ComposeLayout
- bodyDebugName={`chat-compose:${props.chatId}:${props.messageId}:${props.toolCallId}`}
- class={cn(
- 'flex flex-col w-full text-xs rounded-lg p-4 bg-surface',
- uiDisabled() &&
- '[&_button:disabled]:opacity-50 [&_button:disabled]:text-ink-disabled [&_input:disabled]:text-ink-muted'
- )}
- header={
- showOwnerDisabledMessage() ? (
- <div class="text-xs text-ink-extra-muted/60">
- Only the chat owner can send or edit this email.
- </div>
- ) : (
- props.header
- )
- }
- toolbar={
- props.readOnly === true ? undefined : (
- <EmailComposeToolbar editor={editor} />
- )
- }
- />
- <Show when={uiDisabled()}>
- <div aria-hidden="true" class="absolute inset-0 z-10 rounded-lg" />
- </Show>
- </div>
- </ComposeProvider>
+ <EmailDraftComposer
+ initialData={props.initialData}
+ sink={sink}
+ recipientOptions={props.recipientOptions}
+ header={props.header}
+ readOnly={props.readOnly}
+ debugName={`${props.chatId}:${props.messageId}:${props.toolCallId}`}
+ />
);
}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
new file mode 100644
index 0000000000..aecc49118b
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/email/DraftComposer.tsx
@@ -0,0 +1,280 @@
+/**
+ * The email composer for a drafted `SendEmail` call, with no opinion about
+ * where the draft came from or where the decision goes.
+ *
+ * Chat mounts it over a pending user tool and sends through the cognition
+ * endpoints; an agent session mounts it over a review elicitation and answers
+ * the agent. Both hand in a {@link UserToolReviewSink}; the composer only
+ * knows how to edit the draft and what Send means.
+ */
+
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import {
+ ComposeLayout,
+ EmailComposeToolbar,
+} from '@block-email/component/compose';
+import {
+ type ComposeContextValue,
+ ComposeProvider,
+ type ComposeValidationError,
+} from '@block-email/component/compose/ComposeContext';
+import { SignaturePreview } from '@block-email/component/compose/SignaturePreview';
+import type { DraftFormAttachment } from '@block-email/component/createEmailFormState';
+import type { EmailRecipient } from '@block-email/component/EmailContext';
+import { decodeBase64Utf8 } from '@block-email/util/decodeBase64';
+import { prepareEmailBody } from '@block-email/util/prepareEmailBody';
+import { convertContactInfoToEmailRecipient } from '@block-email/util/recipientConversion';
+import { enableEmailSignatures } from '@core/constant/featureFlags';
+import { useEmailLinksQuery, useEmailSignature } from '@queries/email/link';
+import type { SendEmail } from '@service-cognition/generated/tools/types';
+import { debounce } from '@solid-primitives/scheduled';
+import { cn } from '@ui';
+import type { LexicalEditor } from 'lexical';
+import { createMemo, createSignal, type JSX, onCleanup, Show } from 'solid-js';
+import type { UserToolReviewSink } from '../user-tool-review';
+
+export type EmailDraftComposerProps = {
+ /** The draft as the agent wrote it, or as the user last saved it. */
+ initialData: SendEmail;
+ /** Where edits, the send and the rejection go. */
+ sink: UserToolReviewSink<SendEmail>;
+ /** Extra recipients to offer in the pickers. */
+ recipientOptions?: EmailRecipient[];
+ /** Shown above the form; the sink's locked notice takes precedence. */
+ header?: JSX.Element;
+ /** A finished email, shown as it was sent: no toolbar, nothing editable. */
+ readOnly?: boolean;
+ /** Suffix for the body editor's debug name, unique per draft. */
+ debugName: string;
+};
+
+function toEmailRecipients(
+ items: Array<{ email: string; name?: string | null }>
+): EmailRecipient[] {
+ return items.map(convertContactInfoToEmailRecipient);
+}
+
+function fromEmailRecipients(
+ items: EmailRecipient[]
+): Array<{ email: string; name: string | null }> {
+ return items.map((recipient) => {
+ const email = 'email' in recipient.data ? recipient.data.email : '';
+ const name =
+ 'name' in recipient.data ? (recipient.data.name ?? null) : null;
+ return { email, name };
+ });
+}
+
+export function EmailDraftComposer(props: EmailDraftComposerProps) {
+ const uiDisabled = () => !props.sink.canAct() || props.readOnly === true;
+ const emailLinksQuery = useEmailLinksQuery();
+ // The inbox this card sends from — always the first linked inbox (shown as
+ // "from"); the backend resolves the same default at send time.
+ const sendingLink = createMemo(() => emailLinksQuery.data?.links?.[0]);
+ const fromAddress = () => sendingLink()?.email_address;
+ const signature = useEmailSignature(() => sendingLink()?.id);
+ const emailSignaturesFlag = useFeatureFlag(enableEmailSignatures);
+ // Whether this email includes the signature. Defaults on; the preview's ✕
+ // drops it for this one message. Mirrors the normal composer.
+ // Initialize from the persisted tool args so a dismiss survives re-render /
+ // reload; only an explicit false counts as dismissed.
+ const [includeSignature, setIncludeSignature] = createSignal(
+ props.initialData.includeSignature !== false
+ );
+ const isReplyOrForward = () => Boolean(props.initialData.replyingToId);
+ // Signature to preview (and inject on send): a new compose always shows it; a
+ // reply/forward only when the inbox's "add to replies & forwards" setting is
+ // on. Hidden once dismissed and in the read-only (sent) state. Shown while
+ // locked too — the overlay blocks interaction until the lock lifts.
+ const previewSignatureHtml = (): string | undefined => {
+ if (!emailSignaturesFlag().enabled) return undefined;
+ if (props.readOnly) return undefined;
+ if (!includeSignature()) return undefined;
+ const sig = signature();
+ if (!sig) return undefined;
+ if (isReplyOrForward()) {
+ return sendingLink()?.settings.signature_on_replies_forwards
+ ? sig
+ : undefined;
+ }
+ return sig;
+ };
+
+ const [recipients, setRecipients] = createSignal({
+ to: toEmailRecipients(
+ (props.initialData.to ?? []).map((r) => ({ ...r, name: r.name ?? null }))
+ ),
+ cc: toEmailRecipients(
+ (props.initialData.cc ?? []).map((r) => ({ ...r, name: r.name ?? null }))
+ ),
+ bcc: toEmailRecipients(
+ (props.initialData.bcc ?? []).map((r) => ({
+ ...r,
+ name: r.name ?? null,
+ }))
+ ),
+ });
+ const [subject, setSubject] = createSignal(props.initialData.subject ?? '');
+ const [isSending, setIsSending] = createSignal(false);
+ const [editor, setEditor] = createSignal<LexicalEditor>();
+ const [validationErrors, setValidationErrors] = createSignal<
+ ComposeValidationError[]
+ >([]);
+ let finalized = false;
+
+ function collectArgs(): SendEmail {
+ return {
+ to: fromEmailRecipients(recipients().to),
+ cc: fromEmailRecipients(recipients().cc),
+ bcc: fromEmailRecipients(recipients().bcc),
+ subject: subject(),
+ body: prepareEmailBody(editor())?.bodyHtml ?? '',
+ replyingToId: props.initialData.replyingToId,
+ // Omit to use the backend default policy; false only when dismissed.
+ includeSignature: includeSignature() ? undefined : false,
+ };
+ }
+
+ function validate(): boolean {
+ const errors: ComposeValidationError[] = [];
+
+ if (recipients().to.length === 0) {
+ errors.push({
+ type: 'no_recipient',
+ message: 'Add at least one recipient',
+ });
+ }
+
+ if (!prepareEmailBody(editor())?.bodyText.trim()) {
+ errors.push({ type: 'no_message', message: 'Write a message' });
+ }
+
+ setValidationErrors(errors);
+ return errors.length === 0;
+ }
+
+ // Reading the body out of the editor is not free, so edits reach the sink
+ // settled, not per keystroke.
+ const debouncedEdit = debounce(() => {
+ if (finalized || uiDisabled()) return;
+ props.sink.onEdit?.(collectArgs());
+ }, 150);
+ function scheduleUpdate() {
+ if (finalized || !props.sink.onEdit) return;
+ debouncedEdit();
+ }
+ onCleanup(() => {
+ debouncedEdit.clear();
+ props.sink.onDispose?.();
+ });
+
+ async function handleSend() {
+ if (finalized || uiDisabled() || isSending()) return;
+ if (!validate()) return;
+ debouncedEdit.clear();
+ setIsSending(true);
+ const done = await props.sink.onExecute(collectArgs());
+ setIsSending(false);
+ if (done) finalized = true;
+ }
+
+ // `body` is markdown while the AI is drafting, but every persist path
+ // replaces it with the base64url-encoded HTML that the SendEmail tool
+ // contract requires at send time. Decode and route to the editor slot that
+ // matches what the field actually holds.
+ const initialBody = (): { html?: string; markdown?: string } => {
+ const body = props.initialData.body;
+ if (!body) return {};
+ const decoded = decodeBase64Utf8(body);
+ if (decoded.startsWith('<body')) return { html: decoded };
+ return { markdown: body };
+ };
+
+ const ctx: ComposeContextValue = {
+ subject,
+ attachments: () => [],
+ sendTime: () => undefined,
+ initialHtml: () => initialBody().html,
+ initialMarkdown: () => initialBody().markdown,
+ setRecipients: (field, value) => {
+ setRecipients((prev) => ({ ...prev, [field]: value }));
+ scheduleUpdate();
+ },
+ setSubject: (value) => {
+ setSubject(value);
+ scheduleUpdate();
+ },
+ onContentChange: () => {
+ scheduleUpdate();
+ },
+ onAddAttachments: (_: DraftFormAttachment[]) => {},
+ onRemoveAttachment: (_: DraftFormAttachment) => {},
+ captureEditor: setEditor,
+ onSend: handleSend,
+ disabled: () => isSending() || uiDisabled(),
+ isSending,
+ isSavingDraft: () => false,
+ hasDraft: () => false,
+ hasPaidAccess: () => true,
+ focusRecipientsOnMount: false,
+ includeSelf: true,
+ hideAttachments: true,
+ recipientOptions: () => [
+ ...recipients().to,
+ ...recipients().cc,
+ ...recipients().bcc,
+ ...(props.recipientOptions ?? []),
+ ],
+ validationError: (type) => validationErrors().find((e) => e.type === type),
+ fromAddress,
+ recipients,
+ // Read-only preview of the signature the backend appends on send, with a ✕
+ // to drop it for this one email (persisted through the sink's edit).
+ signaturePreview: () => (
+ <Show when={previewSignatureHtml()}>
+ {(html) => (
+ <SignaturePreview
+ html={html()}
+ onDismiss={() => {
+ setIncludeSignature(false);
+ scheduleUpdate();
+ }}
+ />
+ )}
+ </Show>
+ ),
+ };
+
+ const header = () => {
+ const notice = props.readOnly ? undefined : props.sink.lockedNotice();
+ return notice ? (
+ <div class="text-xs text-ink-extra-muted/60">{notice}</div>
+ ) : (
+ props.header
+ );
+ };
+
+ return (
+ <ComposeProvider value={ctx}>
+ <div class="relative">
+ <ComposeLayout
+ bodyDebugName={`chat-compose:${props.debugName}`}
+ class={cn(
+ 'flex flex-col w-full text-xs rounded-lg p-4 bg-surface',
+ uiDisabled() &&
+ '[&_button:disabled]:opacity-50 [&_button:disabled]:text-ink-disabled [&_input:disabled]:text-ink-muted'
+ )}
+ header={header()}
+ toolbar={
+ props.readOnly === true ? undefined : (
+ <EmailComposeToolbar editor={editor} />
+ )
+ }
+ />
+ <Show when={uiDisabled()}>
+ <div aria-hidden="true" class="absolute inset-0 z-10 rounded-lg" />
+ </Show>
+ </div>
+ </ComposeProvider>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/user-tool-review.ts b/apps/web/src/lib/core/component/AI/component/tool/user-tool-review.ts
new file mode 100644
index 0000000000..b852aa302e
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/user-tool-review.ts
@@ -0,0 +1,38 @@
+/**
+ * What a user tool's composer does with the user's decisions.
+ *
+ * A user tool (`SendEmail`, `CreateCalendarEvent`) is drafted by the agent
+ * and finished by the user. The composer that edits the draft is the same
+ * wherever it shows; what differs is who finishes the call: chat posts to the
+ * cognition tool endpoints after the turn, an agent session answers the
+ * agent's review elicitation mid-turn. Each surface builds one of these and
+ * the composer calls it.
+ */
+
+import type { Accessor } from 'solid-js';
+
+export type UserToolReviewSink<T> = {
+ /** Whether this viewer may act: the chat's or session's owner. */
+ canAct: Accessor<boolean>;
+ /**
+ * Why the composer is read-only when it is, in a sentence for the user -
+ * "Only the chat owner can…", "Waiting for Alice to answer." - or nothing
+ * when it is live.
+ */
+ lockedNotice: Accessor<string | undefined>;
+ /**
+ * An edit in progress. Chat persists these so a reload keeps them; a
+ * session has nowhere to put them until submit, so it leaves this out.
+ */
+ onEdit?: (args: T) => void;
+ /**
+ * Execute the call with the edited arguments. Resolves `true` when the call
+ * is finished (executed, or refused for good), `false` when the composer
+ * should stay open for another try.
+ */
+ onExecute: (args: T) => Promise<boolean>;
+ /** Reject the call. Same contract as {@link onExecute}. */
+ onReject: () => Promise<boolean>;
+ /** The composer is going away; flush or drop whatever is pending. */
+ onDispose?: () => void;
+};
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
index bdb78ca11d..8b4ab4a55d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChip.tsx
@@ -4,7 +4,7 @@ import type { Component } from 'solid-js';
import { createMagicChipModel } from './create-magic-chip-model';
import { MagicChipView } from './MagicChipView';
-/** Connect the Magic Chip's live model to its pure visual surface. */
+/** Lexical decorator for a `<m-magic-chip>` node in a channel message. */
export const MagicChip: Component<MagicChipDecoratorProps> = (props) => {
const { insertSplit } = useSplitLayout();
const model = createMagicChipModel(props);
@@ -13,6 +13,10 @@ export const MagicChip: Component<MagicChipDecoratorProps> = (props) => {
<MagicChipView
agentSessionId={props.agentSessionId}
presentation={model.presentation()}
+ answer={{
+ answering: model.elicitation.answering(),
+ respond: model.elicitation.respond,
+ }}
onOpen={() => insertSplit({ type: 'agent', id: props.agentSessionId })}
/>
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
index 2cdc68c536..72331a8d6a 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.test.tsx
@@ -1,10 +1,10 @@
-/**
- * @vitest-environment jsdom
- */
-
+/** @vitest-environment jsdom */
+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createSignal } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MagicChipView } from './MagicChipView';
+import type { MagicChipPresentation } from './presentation';
vi.mock(
'@core/component/LexicalMarkdown/component/core/StaticMarkdown',
@@ -183,3 +183,150 @@ describe('MagicChipView', () => {
expect(screen.getByText(LONG_PATH).className).toContain('truncate');
});
});
+
+vi.mock('@app/features/block-agent/component/parts/UserToolCall', () => ({
+ EventDraft: (props: { event: { title: string } }) => (
+ <div data-testid="event-draft">{props.event.title}</div>
+ ),
+ EmailDraft: (props: { email: { subject: string } }) => (
+ <div data-testid="email-draft">{props.email.subject}</div>
+ ),
+}));
+
+const draft = {
+ title: 'Q3 sync',
+ time: {
+ kind: 'timed',
+ startsAt: '2026-08-20T17:00:00Z',
+ endsAt: '2026-08-20T17:30:00Z',
+ timeZone: 'UTC',
+ },
+};
+
+function asking(canAnswer: boolean, markdown = ''): MagicChipPresentation {
+ return {
+ kind: 'asking',
+ markdown,
+ asking: {
+ question: {
+ requestId: 9,
+ turn: 0,
+ toolCall: 'toolu_evt',
+ message: 'Create calendar event?',
+ request: {
+ kind: 'user_tool',
+ tool: 'CreateCalendarEvent',
+ draft,
+ schema: {
+ title: null,
+ description: null,
+ properties: [],
+ required: [],
+ },
+ },
+ },
+ canAnswer,
+ ownerName: 'Alice Owner',
+ },
+ };
+}
+
+const respond = vi.fn<(answer: ElicitationAnswer) => Promise<boolean>>();
+const onOpen = vi.fn();
+
+beforeEach(() => {
+ respond.mockReset();
+ respond.mockResolvedValue(true);
+ onOpen.mockReset();
+});
+
+describe('MagicChipView asking', () => {
+ it('summarizes the draft and sends it whole on Create, declines on Cancel', () => {
+ const { getByTestId, getByText } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={asking(true, 'Setting that up.')}
+ answer={{ answering: false, respond }}
+ onOpen={onOpen}
+ />
+ ));
+ expect(getByTestId('chip-markdown').textContent).toBe('Setting that up.');
+ expect(getByTestId('event-draft').textContent).toBe('Q3 sync');
+ expect(getByText('Waiting for you')).not.toBeNull();
+
+ fireEvent.click(getByText('Create event'));
+ expect(respond).toHaveBeenCalledWith({
+ action: 'accept',
+ content: { draft: JSON.stringify(draft) },
+ });
+ fireEvent.click(getByText('Cancel'));
+ expect(respond).toHaveBeenLastCalledWith({ action: 'decline' });
+ fireEvent.click(getByText('Edit in session'));
+ expect(onOpen).toHaveBeenCalled();
+ });
+
+ it('a viewer who is not the owner sees who is being waited on and can only open the session', () => {
+ const { queryByText, getByText } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={asking(false)}
+ answer={{ answering: false, respond }}
+ onOpen={onOpen}
+ />
+ ));
+ expect(getByText('Waiting for Alice Owner')).not.toBeNull();
+ expect(queryByText('Create event')).toBeNull();
+ expect(queryByText('Cancel')).toBeNull();
+ fireEvent.click(getByText('Open session'));
+ expect(onOpen).toHaveBeenCalled();
+ expect(respond).not.toHaveBeenCalled();
+ });
+
+ it('holds the buttons while an answer is on the wire', () => {
+ const { getByText } = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={asking(true)}
+ answer={{ answering: true, respond }}
+ />
+ ));
+ fireEvent.click(getByText('Create event'));
+ expect(respond).not.toHaveBeenCalled();
+ });
+});
+
+describe('MagicChipView review transition', () => {
+ it('keeps the expanded answer while a review appears and the agent continues', () => {
+ const [presentation, setPresentation] = createSignal<MagicChipPresentation>(
+ {
+ kind: 'answering',
+ markdown: 'Setting that up.',
+ activity: { label: 'Writing response', busy: false },
+ }
+ );
+ const view = render(() => (
+ <MagicChipView
+ agentSessionId="session"
+ presentation={presentation()}
+ answer={{ answering: false, respond }}
+ onOpen={onOpen}
+ />
+ ));
+ const area = answerArea(view.container)!;
+ fireEvent.click(area);
+ expect(area.getAttribute('aria-expanded')).toBe('true');
+
+ setPresentation(asking(true, 'Setting that up.'));
+ expect(view.getByText('Create event')).toBeTruthy();
+ expect(answerArea(view.container)).toBe(area);
+ expect(area.getAttribute('aria-expanded')).toBe('true');
+
+ setPresentation({ kind: 'settled', markdown: 'Created the event.' });
+ expect(view.queryByText('Create event')).toBeNull();
+ expect(view.getByText('Created the event.')).toBeTruthy();
+ expect(answerArea(view.container)).toBe(area);
+ expect(area.getAttribute('aria-expanded')).toBe('true');
+ fireEvent.click(view.getByText('Open session'));
+ expect(onOpen).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
index 238a0e4f60..57e82a0147 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
@@ -1,3 +1,8 @@
+import {
+ EmailDraft,
+ EventDraft,
+} from '@app/features/block-agent/component/parts/UserToolCall';
+import { DRAFT_FIELD } from '@app/features/block-agent/state/elicitation-review-sink';
import {
StaticMarkdown,
StaticMarkdownContext,
@@ -6,16 +11,36 @@ import { channelTheme } from '@core/component/LexicalMarkdown/theme';
import { PulsingStar } from '@entity/components/PulsingStar';
import ArrowUpRight from '@phosphor/arrow-up-right.svg';
import CaretRight from '@phosphor/caret-right.svg';
-import { Layer } from '@ui';
-import { type Component, createSignal, Show } from 'solid-js';
-import type { MagicChipActivity, MagicChipPresentation } from './presentation';
+import type { ElicitationAnswer } from '@service-agent-harness/generated/schemas';
+import { deserializeToolCall } from '@service-cognition/generated/tools/tool';
+import type {
+ CreateCalendarEvent,
+ SendEmail,
+} from '@service-cognition/generated/tools/types';
+import { Button, Layer } from '@ui';
+import {
+ type Component,
+ createMemo,
+ createSignal,
+ Match,
+ Show,
+ Switch,
+} from 'solid-js';
+import { match } from 'ts-pattern';
+import type {
+ MagicChipActivity,
+ MagicChipPresentation,
+ MagicChipQuestion,
+} from './presentation';
function answerMarkdown(presentation: MagicChipPresentation) {
return presentation.kind === 'working' ? undefined : presentation.markdown;
}
function currentActivity(presentation: MagicChipPresentation) {
- return presentation.kind === 'settled' ? undefined : presentation.activity;
+ return presentation.kind === 'working' || presentation.kind === 'answering'
+ ? presentation.activity
+ : undefined;
}
function replyPreview(activity: MagicChipActivity | undefined) {
@@ -23,6 +48,138 @@ function replyPreview(activity: MagicChipActivity | undefined) {
return `${activity.label}${activity.detail ? ` ${activity.detail}` : ''}`;
}
+/** What the chip's answer to a question does. */
+export type MagicChipAnswer = {
+ /** An answer is on the wire; the buttons wait. */
+ answering: boolean;
+ respond: (answer: ElicitationAnswer) => Promise<boolean>;
+};
+
+/**
+ * A question the agent stopped to ask, kept small for a channel thread: what
+ * is being asked, a read-only summary of a user tool's draft, and the two
+ * decisions. Editing the draft, or answering a form field by field, happens
+ * in the session - "Edit in session" opens it. Anyone but the session's
+ * owner sees the summary and who is being waited on.
+ */
+const AskingCard: Component<{
+ agentSessionId: string;
+ asking: MagicChipQuestion;
+ answer?: MagicChipAnswer;
+ onOpen?: () => void;
+}> = (props) => {
+ const request = () => props.asking.question.request;
+ const userTool = createMemo(() => {
+ const current = request();
+ if (current.kind !== 'user_tool') return undefined;
+ const call = deserializeToolCall({
+ id:
+ props.asking.question.toolCall ??
+ String(props.asking.question.requestId),
+ name: current.tool,
+ json: current.draft,
+ });
+ return call.isOk() ? { tool: call.value, draft: current.draft } : undefined;
+ });
+ const locked = () =>
+ !props.asking.canAnswer || props.answer?.answering === true;
+ const waitingFor = () =>
+ props.asking.canAnswer
+ ? 'Waiting for you'
+ : `Waiting for ${props.asking.ownerName}`;
+ const confirmLabel = () =>
+ match(userTool()?.tool.name)
+ .with('CreateCalendarEvent', () => 'Create event')
+ .with('SendEmail', () => 'Send email')
+ .otherwise(() => 'Confirm');
+ const respond = (answer: ElicitationAnswer) => {
+ if (locked()) return;
+ void props.answer?.respond(answer);
+ };
+ // The chip sends the draft as the agent wrote it; edits need the session's
+ // composer.
+ const accept = () =>
+ respond({
+ action: 'accept',
+ content:
+ request().kind === 'user_tool'
+ ? { [DRAFT_FIELD]: JSON.stringify(userTool()?.draft ?? {}) }
+ : {},
+ });
+
+ return (
+ <div
+ class="flex w-full min-w-0 flex-col gap-2 rounded-lg border border-edge-muted bg-surface p-3"
+ data-magic-chip={props.agentSessionId}
+ data-magic-chip-asking
+ data-message-reply-preview={`${waitingFor()} · ${props.asking.question.message}`}
+ >
+ <div class="flex items-center gap-2 text-xs">
+ <span class="shrink-0 font-semibold text-ink-muted" aria-live="polite">
+ {waitingFor()}
+ </span>
+ <span class="min-w-0 truncate text-ink">
+ {props.asking.question.message}
+ </span>
+ </div>
+ <Switch>
+ <Match
+ when={userTool()?.tool.name === 'CreateCalendarEvent' && userTool()}
+ >
+ {(reviewed) => (
+ <EventDraft event={reviewed().tool.data as CreateCalendarEvent} />
+ )}
+ </Match>
+ <Match when={userTool()?.tool.name === 'SendEmail' && userTool()}>
+ {(reviewed) => (
+ <EmailDraft
+ email={reviewed().tool.data as SendEmail}
+ inFlight={false}
+ />
+ )}
+ </Match>
+ </Switch>
+ <div class="flex flex-wrap items-center gap-2">
+ <Show when={props.asking.canAnswer}>
+ <Show when={userTool()}>
+ <Button
+ variant="cta"
+ size="xs"
+ disabled={locked()}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={accept}
+ >
+ {confirmLabel()}
+ </Button>
+ </Show>
+ <Button
+ variant="outline"
+ size="xs"
+ disabled={locked()}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => respond({ action: 'decline' })}
+ >
+ {userTool() ? 'Cancel' : 'Decline'}
+ </Button>
+ </Show>
+ <Button
+ variant="ghost"
+ size="xs"
+ disabled={!props.onOpen}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={props.onOpen}
+ >
+ {props.asking.canAnswer
+ ? userTool()
+ ? 'Edit in session'
+ : 'Answer in session'
+ : 'Open session'}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
/** The shimmering label plus its muted detail. */
const ActivityText: Component<{ activity: MagicChipActivity }> = (props) => (
<>
@@ -139,8 +296,14 @@ const ExpandHint: Component<{ expanded: boolean }> = (props) => (
export const MagicChipView: Component<{
agentSessionId: string;
presentation: MagicChipPresentation;
+ /** How the chip answers a question; absent renders it read-only. */
+ answer?: MagicChipAnswer;
onOpen?: () => void;
}> = (props) => {
+ const asking = () =>
+ props.presentation.kind === 'asking'
+ ? props.presentation.asking
+ : undefined;
const markdown = () => answerMarkdown(props.presentation);
const activity = () => currentActivity(props.presentation);
const [expanded, setExpanded] = createSignal(false);
@@ -183,25 +346,39 @@ export const MagicChipView: Component<{
)}
</Show>
</div>
- <button
- type="button"
- class="flex min-h-9 w-full items-center gap-1.5 border-t border-edge-muted px-3 py-2 text-left text-xs leading-5 text-ink-extra-muted hover:bg-hover"
- data-message-reply-preview={
- markdown() ? undefined : replyPreview(activity())
+ <Show
+ when={asking()}
+ fallback={
+ <button
+ type="button"
+ class="flex min-h-9 w-full items-center gap-1.5 border-t border-edge-muted px-3 py-2 text-left text-xs leading-5 text-ink-extra-muted hover:bg-hover"
+ data-message-reply-preview={
+ markdown() ? undefined : replyPreview(activity())
+ }
+ disabled={!props.onOpen}
+ onClick={props.onOpen}
+ >
+ <span class="flex min-w-0 flex-1 items-center gap-1.5">
+ <Show
+ when={activity()}
+ fallback={<span class="text-ink-muted">Open session</span>}
+ >
+ {(current) => <ActivityText activity={current()} />}
+ </Show>
+ </span>
+ <ArrowUpRight aria-hidden="true" class="size-3 shrink-0" />
+ </button>
}
- disabled={!props.onOpen}
- onClick={props.onOpen}
>
- <span class="flex min-w-0 flex-1 items-center gap-1.5">
- <Show
- when={activity()}
- fallback={<span class="text-ink-muted">Open session</span>}
- >
- {(current) => <ActivityText activity={current()} />}
- </Show>
- </span>
- <ArrowUpRight aria-hidden="true" class="size-3 shrink-0" />
- </button>
+ {(question) => (
+ <AskingCard
+ agentSessionId={props.agentSessionId}
+ asking={question()}
+ answer={props.answer}
+ onOpen={props.onOpen}
+ />
+ )}
+ </Show>
</div>
</Layer>
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
index d21550d8f4..04ea1c9d40 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.test.ts
@@ -1,5 +1,9 @@
import type { MagicChipDecoratorProps } from '@macro-inc/lexical-core';
-import type { FoldedMessage } from '@service-agent-fold/generated/types';
+import type {
+ FoldedMessage,
+ PendingElicitation,
+ SessionMetadata,
+} from '@service-agent-fold/generated/types';
import { createRoot } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -7,12 +11,22 @@ const sessionFold = vi.hoisted(() => ({
acquireAgentSessionFold: vi.fn(),
subscribeAgentSessionLog: vi.fn(),
}));
-const serviceClient = vi.hoisted(() => ({ get: vi.fn() }));
+const serviceClient = vi.hoisted(() => ({ get: vi.fn(), control: vi.fn() }));
+const viewer = vi.hoisted(() => ({ id: 'macro|[email protected]' }));
vi.mock('@queries/agent-session/session-fold', () => sessionFold);
vi.mock('@service-agent-harness/client', () => ({
agentHarnessServiceClient: serviceClient,
}));
+vi.mock('@core/context/user', () => ({ useUserId: () => () => viewer.id }));
+vi.mock('@core/user', () => ({
+ tryMacroId: (id: string) => (id.startsWith('macro|') ? id : undefined),
+ getDisplayName: (id: string) =>
+ id === 'macro|[email protected]' ? 'Alice Owner' : '',
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { failure: vi.fn(), success: vi.fn() },
+}));
import { createMagicChipModel } from './create-magic-chip-model';
@@ -34,24 +48,60 @@ const response: FoldedMessage = {
stop: { kind: 'end_turn' },
};
+const openResponse: FoldedMessage = {
+ ...response,
+ parts: [{ kind: 'text', text: 'Setting that up.' }],
+ stop: null,
+};
+
+const question: PendingElicitation = {
+ requestId: 9,
+ turn: 0,
+ toolCall: 'toolu_evt',
+ message: 'Create calendar event?',
+ request: {
+ kind: 'user_tool',
+ tool: 'CreateCalendarEvent',
+ draft: { title: 'Q3 sync' },
+ schema: { title: null, description: null, properties: [], required: [] },
+ },
+};
+
+const metadata = (
+ pendingElicitation: PendingElicitation | null
+): SessionMetadata => ({ pendingElicitation }) as unknown as SessionMetadata;
+
const props = {
agentSessionId: 'session',
promptedMessage: { turn: 0, author: 'user' },
status: 'acp_ready',
} as MagicChipDecoratorProps;
+/** Let the fold acquisition and the status fetch settle. */
+const settle = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+};
+
describe('createMagicChipModel', () => {
beforeEach(() => {
vi.clearAllMocks();
+ viewer.id = 'macro|[email protected]';
sessionFold.subscribeAgentSessionLog.mockReturnValue(vi.fn());
sessionFold.acquireAgentSessionFold.mockResolvedValue({
messages: [prompt, response],
+ metadata: metadata(null),
release: vi.fn(),
});
serviceClient.get.mockResolvedValue({
isOk: () => true,
- value: { status: { kind: 'disconnected' } },
+ value: {
+ status: { kind: 'disconnected' },
+ ownerId: 'macro|[email protected]',
+ },
});
+ serviceClient.control.mockResolvedValue({ isErr: () => false });
});
it('settles after the attached turn completes despite stale acp_ready status', async () => {
@@ -61,13 +111,14 @@ describe('createMagicChipModel', () => {
return rootDispose;
});
- await Promise.resolve();
+ await settle();
expect(presentation()).toEqual({ kind: 'settled', markdown: 'Hi!' });
expect(sessionFold.acquireAgentSessionFold).toHaveBeenCalledWith({
agentSessionId: 'session',
onChange: expect.any(Function),
onReplace: expect.any(Function),
+ onMetadata: expect.any(Function),
});
dispose();
@@ -100,6 +151,7 @@ describe('createMagicChipModel', () => {
it('hydrates a disconnected status from the session', async () => {
sessionFold.acquireAgentSessionFold.mockResolvedValue({
messages: [],
+ metadata: metadata(null),
release: vi.fn(),
});
let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];
@@ -108,8 +160,7 @@ describe('createMagicChipModel', () => {
return rootDispose;
});
- await Promise.resolve();
- await Promise.resolve();
+ await settle();
expect(presentation()).toEqual({
kind: 'working',
@@ -118,4 +169,90 @@ describe('createMagicChipModel', () => {
dispose();
});
+
+ it('offers a question asked in its turn, to the owner, and answers on the request id', async () => {
+ viewer.id = 'macro|[email protected]';
+ sessionFold.acquireAgentSessionFold.mockResolvedValue({
+ messages: [prompt, openResponse],
+ metadata: metadata(question),
+ release: vi.fn(),
+ });
+ let model!: ReturnType<typeof createMagicChipModel>;
+ const dispose = createRoot((rootDispose) => {
+ model = createMagicChipModel(props);
+ return rootDispose;
+ });
+
+ await settle();
+
+ expect(model.presentation()).toEqual({
+ kind: 'asking',
+ markdown: 'Setting that up.',
+ asking: { question, canAnswer: true, ownerName: 'Alice Owner' },
+ });
+ expect(await model.elicitation.respond({ action: 'decline' })).toBe(true);
+ expect(serviceClient.control).toHaveBeenCalledWith('session', {
+ type: 'respondElicitation',
+ requestId: 9,
+ action: 'decline',
+ });
+
+ dispose();
+ });
+
+ it('shows another viewer who is being waited on, and sends nothing for them', async () => {
+ sessionFold.acquireAgentSessionFold.mockResolvedValue({
+ messages: [prompt, openResponse],
+ metadata: metadata(question),
+ release: vi.fn(),
+ });
+ let model!: ReturnType<typeof createMagicChipModel>;
+ const dispose = createRoot((rootDispose) => {
+ model = createMagicChipModel(props);
+ return rootDispose;
+ });
+
+ await settle();
+
+ const presentation = model.presentation();
+ expect(presentation.kind).toBe('asking');
+ if (presentation.kind === 'asking') {
+ expect(presentation.asking.canAnswer).toBe(false);
+ expect(presentation.asking.ownerName).toBe('Alice Owner');
+ }
+ expect(await model.elicitation.respond({ action: 'decline' })).toBe(false);
+ expect(serviceClient.control).not.toHaveBeenCalled();
+
+ dispose();
+ });
+
+ it("a question from a later turn is not this chip's, and the live metadata moves it", async () => {
+ let onMetadata: ((metadata: SessionMetadata) => void) | undefined;
+ sessionFold.acquireAgentSessionFold.mockImplementation(
+ (args: { onMetadata?: (metadata: SessionMetadata) => void }) => {
+ onMetadata = args.onMetadata;
+ return Promise.resolve({
+ messages: [prompt, openResponse],
+ metadata: metadata({ ...question, turn: 3 }),
+ release: vi.fn(),
+ });
+ }
+ );
+ let presentation!: ReturnType<typeof createMagicChipModel>['presentation'];
+ const dispose = createRoot((rootDispose) => {
+ presentation = createMagicChipModel(props).presentation;
+ return rootDispose;
+ });
+
+ await settle();
+ expect(presentation().kind).toBe('answering');
+
+ onMetadata?.(metadata(question));
+ expect(presentation().kind).toBe('asking');
+
+ onMetadata?.(metadata(null));
+ expect(presentation().kind).toBe('answering');
+
+ dispose();
+ });
});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
index fd534fd488..b1f4601ec2 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
@@ -1,3 +1,8 @@
+import {
+ createElicitationController,
+ type ElicitationController,
+} from '@app/features/block-agent/context/create-elicitation-controller';
+import { useUserId } from '@core/context/user';
import {
MAGIC_CHIP_STATUSES,
type MagicChipDecoratorProps,
@@ -7,7 +12,10 @@ import {
acquireAgentSessionFold,
subscribeAgentSessionLog,
} from '@queries/agent-session/session-fold';
-import type { FoldedMessage } from '@service-agent-fold/generated/types';
+import type {
+ FoldedMessage,
+ PendingElicitation,
+} from '@service-agent-fold/generated/types';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
import type {
AgentSessionLogEntryDto,
@@ -17,6 +25,7 @@ import { type Accessor, createSignal, onCleanup } from 'solid-js';
import {
deriveMagicChipPresentation,
type MagicChipPresentation,
+ type MagicChipQuestion,
} from './presentation';
const STATUS_POLL_INTERVAL_MS = 5_000;
@@ -36,13 +45,24 @@ function magicChipStatus(
return MAGIC_CHIP_STATUSES.find((candidate) => candidate === value);
}
-/** Observe the session lifecycle and the chip's anchored folded turn. */
+/**
+ * Observe the session lifecycle and the chip's anchored folded turn.
+ *
+ * Also the chip's half of answering a question the agent stops to ask in
+ * that turn: the session's metadata names the live question, the session
+ * row names its owner, and {@link ElicitationController} sends the answer.
+ */
export function createMagicChipModel(props: MagicChipDecoratorProps): {
presentation: Accessor<MagicChipPresentation>;
+ elicitation: ElicitationController;
} {
const [latestEvent, setLatestEvent] = createSignal<string>();
const [messages, setMessages] = createSignal<FoldedMessage[]>([]);
const [persistedStatus, setPersistedStatus] = createSignal(props.status);
+ const [ownerId, setOwnerId] = createSignal<string>();
+ const [pendingElicitation, setPendingElicitation] =
+ createSignal<PendingElicitation>();
+ const viewerId = useUserId();
let active = true;
let release: (() => void) | undefined;
let statusTimer: ReturnType<typeof setTimeout> | undefined;
@@ -61,6 +81,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
.get(props.agentSessionId)
.catch(() => undefined);
if (!active) return;
+ if (result?.isOk()) setOwnerId(result.value.ownerId);
const status = result?.isOk()
? magicChipStatus(result.value.status)
: undefined;
@@ -91,6 +112,9 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
)
);
},
+ onMetadata: (metadata) => {
+ setPendingElicitation(metadata.pendingElicitation ?? undefined);
+ },
})
.then((acquired) => {
if (!active) {
@@ -99,6 +123,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
}
release = acquired.release;
setMessages(acquired.messages);
+ setPendingElicitation(acquired.metadata.pendingElicitation ?? undefined);
})
.catch((error: unknown) => {
console.error('[magic-chip] session log could not be folded', error);
@@ -111,6 +136,28 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
release?.();
});
+ // This chip is one turn's surface; only a question asked in that turn is
+ // its to offer.
+ const questionForTurn = () => {
+ const question = pendingElicitation();
+ return question?.turn === props.promptedMessage.turn ? question : undefined;
+ };
+ const elicitation = createElicitationController({
+ sessionId: () => props.agentSessionId,
+ pending: questionForTurn,
+ ownerId,
+ viewerId,
+ });
+ const asking = (): MagicChipQuestion | undefined => {
+ const question = questionForTurn();
+ if (!question) return undefined;
+ return {
+ question,
+ canAnswer: elicitation.canAnswer(),
+ ownerName: elicitation.ownerName(),
+ };
+ };
+
const presentation = () => {
const turn = props.promptedMessage.turn;
const messagesForTurn = messages().filter(
@@ -119,6 +166,7 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
return deriveMagicChipPresentation({
persistedStatus: persistedStatus(),
latestEvent: latestEvent(),
+ asking: asking(),
prompt: messagesForTurn.find((message) => message.author.kind === 'user'),
response: messagesForTurn.find(
(message) => message.author.kind === 'agent'
@@ -126,5 +174,5 @@ export function createMagicChipModel(props: MagicChipDecoratorProps): {
});
};
- return { presentation };
+ return { presentation, elicitation };
}
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 cf600b3f51..8587d11572 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
@@ -213,6 +213,46 @@ describe('deriveMagicChipPresentation', () => {
}
);
+ it('prioritizes an unanswered question over a running tool', () => {
+ const presentation = deriveMagicChipPresentation({
+ persistedStatus: 'acp_ready',
+ response: response({
+ parts: [
+ {
+ kind: 'elicitation',
+ requestId: 0,
+ toolCall: 'tool',
+ message: 'Which approach?',
+ request: {
+ kind: 'form',
+ schema: {
+ title: null,
+ description: null,
+ properties: [],
+ required: [],
+ },
+ },
+ outcome: { kind: 'pending' },
+ reported: null,
+ toolOutcome: null,
+ },
+ {
+ kind: 'tool_use',
+ id: 'other',
+ name: { kind: 'native', name: 'Read' },
+ status: 'running',
+ detail: { kind: 'read', paths: [] },
+ },
+ ],
+ }),
+ });
+
+ expect(presentation).toMatchObject({
+ kind: 'working',
+ activity: { label: 'Waiting for your input', busy: false },
+ });
+ });
+
it('shows the answer as it is written, before the turn ends', () => {
const presentation = deriveMagicChipPresentation({
persistedStatus: 'acp_ready',
@@ -291,4 +331,71 @@ describe('deriveMagicChipPresentation', () => {
expect(presentation).toEqual({ kind: 'settled', markdown: '**Fixed.**' });
});
+
+ describe('a question the agent is waiting on', () => {
+ const asking = {
+ question: {
+ requestId: 9,
+ turn: 0,
+ toolCall: 'toolu_evt',
+ message: 'Create calendar event?',
+ request: {
+ kind: 'user_tool' as const,
+ tool: 'CreateCalendarEvent',
+ draft: { title: 'Q3 sync' },
+ schema: {
+ title: null,
+ description: null,
+ properties: [],
+ required: [],
+ },
+ },
+ },
+ canAnswer: true,
+ ownerName: 'Alice Owner',
+ };
+
+ it('outranks whatever else the open turn is doing, keeping the answer so far', () => {
+ const presentation = deriveMagicChipPresentation({
+ persistedStatus: 'acp_ready',
+ asking,
+ response: response({
+ parts: [
+ { kind: 'text', text: 'Setting that up.' },
+ {
+ kind: 'tool_use',
+ id: 'tool',
+ name: { kind: 'native', name: 'ListCalendars' },
+ status: 'running',
+ detail: { kind: 'macro', input: {}, output: null, error: null },
+ },
+ ],
+ }),
+ });
+ expect(presentation).toEqual({
+ kind: 'asking',
+ markdown: 'Setting that up.',
+ asking,
+ });
+ });
+
+ it('is offered even before the agent has written anything', () => {
+ expect(
+ deriveMagicChipPresentation({ persistedStatus: 'acp_ready', asking })
+ ).toEqual({ kind: 'asking', markdown: '', asking });
+ });
+
+ it('never outranks a settled answer', () => {
+ expect(
+ deriveMagicChipPresentation({
+ persistedStatus: 'acp_ready',
+ asking,
+ response: response({
+ parts: [{ kind: 'text', text: 'Done.' }],
+ stop: { kind: 'end_turn' },
+ }),
+ })
+ ).toEqual({ kind: 'settled', markdown: 'Done.' });
+ });
+ });
});
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 9e65c234fd..67e5a77965 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,6 +2,7 @@ import type { MagicChipStatus } from '@macro-inc/lexical-core';
import type {
FoldedMessage,
MessagePart,
+ PendingElicitation,
ToolName,
} from '@service-agent-fold/generated/types';
import { match } from 'ts-pattern';
@@ -17,20 +18,40 @@ export type MagicChipActivity = {
busy: boolean;
};
+/**
+ * A question the agent is waiting on, as the chip offers it: the live slot
+ * from the session's metadata, and whether this viewer is the one who may
+ * answer (the session's owner) or is watching someone else be asked.
+ */
+export type MagicChipQuestion = {
+ question: PendingElicitation;
+ canAnswer: boolean;
+ /** Who the chip is waiting on when it is not the viewer. */
+ ownerName: string;
+};
+
/**
* The one state the chip renders.
*
- * Three, in the order a turn passes through them: an activity line while the
- * agent works with nothing to show, the answer as it is written with the
- * activity line still under it, and the answer alone once the turn ends.
+ * Four: an activity line while the agent works with nothing to show, the
+ * answer as it is written with the activity line still under it, a question
+ * the agent has stopped to ask (with whatever answer it had written so far
+ * above it), and the answer alone once the turn ends.
*/
export type MagicChipPresentation =
| { kind: 'working'; activity: MagicChipActivity }
| { kind: 'answering'; markdown: string; activity: MagicChipActivity }
+ | { kind: 'asking'; markdown: string; asking: MagicChipQuestion }
| { kind: 'settled'; markdown: string };
export type MagicChipPresentationInput = {
persistedStatus: MagicChipStatus;
+ /**
+ * The question the session is blocked on, when it belongs to this chip's
+ * turn. The chip is a turn's surface, so a question asked in a later turn
+ * is that turn's chip's to show.
+ */
+ asking?: MagicChipQuestion;
/**
* Freshest lifecycle event seen on the live log stream, as its wire string.
* A stopgap for {@link persistedStatus} being a snapshot from when the chip
@@ -160,6 +181,34 @@ function partActivity(part: MessagePart): MagicChipActivity {
label: 'Stop requested',
busy: false,
}))
+ .with({ kind: 'elicitation', outcome: { kind: 'pending' } }, () => ({
+ label: 'Waiting for your input',
+ busy: false,
+ }))
+ .with({ kind: 'elicitation', outcome: { kind: 'accepted' } }, () => ({
+ label: 'Resuming work',
+ busy: true,
+ }))
+ .with({ kind: 'elicitation', outcome: { kind: 'completed' } }, () => ({
+ label: 'Resuming work',
+ busy: true,
+ }))
+ .with({ kind: 'elicitation', outcome: { kind: 'declined' } }, () => ({
+ label: 'Question declined',
+ busy: true,
+ }))
+ .with({ kind: 'elicitation', outcome: { kind: 'cancelled' } }, () => ({
+ label: 'Question cancelled',
+ busy: false,
+ }))
+ .with({ kind: 'elicitation', outcome: { kind: 'errored' } }, () => ({
+ label: 'Question refused',
+ busy: false,
+ }))
+ .with({ kind: 'elicitation', outcome: { kind: 'unrecognized' } }, () => ({
+ label: 'Question answered',
+ busy: true,
+ }))
.with({ kind: 'plan' }, ({ entries }) => {
const completed = entries.filter(
(entry) => entry.status === 'completed'
@@ -214,8 +263,8 @@ function turnEndedActivity(
/**
* What the agent is doing right now, from the parts of an open turn: an
- * unanswered permission request outranks a running tool, which outranks
- * whatever arrived last.
+ * unanswered permission request or question outranks a running tool, which
+ * outranks whatever arrived last.
*/
function turnInFlightActivity(
response: FoldedMessage | undefined
@@ -223,10 +272,11 @@ function turnInFlightActivity(
if (!response) return undefined;
const blocked = response.parts.findLast(
(part) =>
- part.kind === 'permission' &&
- (part.outcome.kind === 'pending' ||
- part.outcome.kind === 'errored' ||
- part.outcome.kind === 'unrecognized')
+ (part.kind === 'permission' &&
+ (part.outcome.kind === 'pending' ||
+ part.outcome.kind === 'errored' ||
+ part.outcome.kind === 'unrecognized')) ||
+ (part.kind === 'elicitation' && part.outcome.kind === 'pending')
);
const runningTool = response.parts.findLast(
(part) =>
@@ -287,12 +337,17 @@ function answerMarkdown(response: FoldedMessage | undefined): string {
export function deriveMagicChipPresentation(
input: MagicChipPresentationInput
): MagicChipPresentation {
- const { response, prompt, latestEvent, persistedStatus } = input;
+ const { response, prompt, latestEvent, persistedStatus, asking } = input;
const markdown = answerMarkdown(response);
if (response?.stop?.kind === 'end_turn' && markdown) {
return { kind: 'settled', markdown };
}
+ // A question the agent is waiting on outranks whatever else the turn is
+ // doing: nothing moves until it is answered.
+ if (asking) {
+ return { kind: 'asking', markdown, asking };
+ }
// Best available answer first: how the turn ended, then what it is doing,
// then that it exists at all, then the session's lifecycle — live before
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 a077e55c89..a7bd7ad1b1 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
@@ -8,6 +8,97 @@
*/
export type AnsiText = string;
+/**
+ * A chosen option, with the title it was offered under when the schema gave
+ * one. `title` is `None` for a value no option declared.
+ */
+export type AnsweredChoice = {
+ /** The value submitted. */
+ value: string;
+ /** The label it was offered under. */
+ title: string | null;
+};
+
+/**
+ * One property's answer, resolved against the schema that asked for it.
+ *
+ * The correlation happens here so that no client repeats it: an option's
+ * title is looked up where the options live, and the harness "Other" idiom -
+ * a free-text answer arriving under a *different* key than the property it
+ * replaces, sometimes alongside the choice it replaces (see the
+ * `elicitation_claude_single_select` fixture, which carries both) - collapses
+ * to a single [`AnsweredValue::Custom`].
+ */
+export type AnsweredField = {
+ /**
+ * The property this answers, or the key it arrived under when no
+ * property claimed it.
+ */
+ name: string;
+ /** What to show as the label: the property's title, else its name. */
+ label: string;
+ /** The answer. */
+ value: AnsweredValue;
+};
+
+/** An answer's value, in the vocabulary the property declared. */
+export type AnsweredValue =
+ /** Free text. */
+ | {
+ kind: 'text';
+ /** The text as submitted. */
+ text: string;
+ }
+ /**
+ * A number, whole or not, exactly as it was submitted.
+ *
+ * Text rather than `f64`: a JSON integer can outrun `f64`'s exact range,
+ * and `f64` has a `number | null` TypeScript face because a non-finite
+ * float serializes as null. Nothing computes with an answer - it is
+ * rendered - so the digits are what matter.
+ */
+ | {
+ kind: 'number';
+ /** The number as written. */
+ text: string;
+ }
+ /** A yes/no. */
+ | {
+ kind: 'boolean';
+ /** Whether it was checked. */
+ checked: boolean;
+ }
+ /** One of the offered options. */
+ | {
+ kind: 'choice';
+ /** The option chosen, with the title it was offered under. */
+ choice: AnsweredChoice;
+ }
+ /** Several of the offered options. */
+ | {
+ kind: 'choices';
+ /** The options chosen, in the order they were submitted. */
+ choices: AnsweredChoice[];
+ }
+ /**
+ * The free-text escape: the user typed their own answer instead of
+ * picking, and it arrived under the property's `customField`.
+ */
+ | {
+ kind: 'custom';
+ /** What they typed. */
+ text: string;
+ }
+ /**
+ * A value this fold could not read as any of the above - a nested
+ * object, or an array of something other than strings.
+ */
+ | {
+ kind: 'unrecognized';
+ /** The value, verbatim. */
+ raw: unknown;
+ };
+
/** Who produced a [`FoldedMessage`]. */
export type Author =
/**
@@ -73,6 +164,240 @@ export type ControlOutcome =
message: string;
};
+/** One choice in a select. */
+export type ElicitationOption = {
+ /** The value sent back when chosen. */
+ value: string;
+ /**
+ * Label to show; absent for an untitled `enum`, where the value is the
+ * label.
+ */
+ title: string | null;
+ /** Help text, when the agent gave one. */
+ description: string | null;
+};
+
+/**
+ * How an elicitation has resolved so far.
+ *
+ * [`Self::Pending`] is a legitimate final state on a dead session, like an
+ * unanswered permission.
+ */
+export type ElicitationOutcome =
+ /** No response has gone out yet. */
+ | { kind: 'pending' }
+ /** The user submitted the form, or consented to open the URL. */
+ | {
+ kind: 'accepted';
+ /**
+ * What they answered: one entry per property the schema declared and
+ * the content answered, in declaration order, then any key no
+ * property claimed. Empty for a URL consent, which carries no
+ * content.
+ */
+ answers: AnsweredField[];
+ }
+ /** The user explicitly said no. */
+ | { kind: 'declined' }
+ /** The user dismissed it, or a stop cancelled it. */
+ | { kind: 'cancelled' }
+ /** URL only: the agent reported the external interaction finished. */
+ | { kind: 'completed' }
+ /**
+ * The response was a JSON-RPC error - including this client's own
+ * refusal of a request it could not hold.
+ */
+ | {
+ kind: 'errored';
+ /** The error's message, verbatim. */
+ message: string;
+ }
+ /** A result arrived that this fold could not read as an ACP action. */
+ | { kind: 'unrecognized' };
+
+/** One form field. */
+export type ElicitationProperty = {
+ /** The key the answer is sent back under. */
+ name: string;
+ /** Label to show, when the agent gave one. */
+ title: string | null;
+ /** Help text, when the agent gave one. */
+ description: string | null;
+ /** The field's type and constraints. */
+ schema: ElicitationPropertySchema;
+};
+
+/**
+ * A field's type and constraints, mirroring ACP's restricted property
+ * schemas.
+ */
+export type ElicitationPropertySchema =
+ /** Free text, or a single choice when `options` is non-empty. */
+ | {
+ type: 'string';
+ /** Minimum length, when constrained. */
+ minLength: number | null;
+ /** Maximum length, when constrained. */
+ maxLength: number | null;
+ /**
+ * A regular expression the value must match. Agent-supplied, so a
+ * renderer must bound its evaluation.
+ */
+ pattern: string | null;
+ /**
+ * ACP's format hint as its wire string (`email`, `uri`, `date`,
+ * `date-time`, or something this fold does not know).
+ */
+ format: string | null;
+ /** Pre-filled value. */
+ default: string | null;
+ /** The choices, when this is a single select. Empty for free text. */
+ options: ElicitationOption[];
+ /**
+ * The key a free-text answer is sent under when one is accepted
+ * alongside `options` - the user picks a choice *or* types their
+ * own. A harness idiom (Claude Code's and Codex's "Other" field),
+ * never ACP's own; `None` for a plain select.
+ */
+ customField: string | null;
+ }
+ /** A floating-point number. */
+ | {
+ type: 'number';
+ /** Lower bound, when constrained. */
+ minimum: number | null;
+ /** Upper bound, when constrained. */
+ maximum: number | null;
+ /** Pre-filled value. */
+ default: number | null;
+ }
+ /** A whole number. */
+ | {
+ type: 'integer';
+ /** Lower bound, when constrained. */
+ minimum: number | null;
+ /** Upper bound, when constrained. */
+ maximum: number | null;
+ /** Pre-filled value. */
+ default: number | null;
+ }
+ /** A yes/no. */
+ | {
+ type: 'boolean';
+ /** Pre-filled value. */
+ default: boolean | null;
+ }
+ /** Several choices from a list. */
+ | {
+ type: 'multi_select';
+ /** Fewest selections allowed, when constrained. */
+ minItems: number | null;
+ /** Most selections allowed, when constrained. */
+ maxItems: number | null;
+ /** The choices. */
+ options: ElicitationOption[];
+ /** Pre-selected values. */
+ default: string[];
+ /**
+ * The key a free-text answer is sent under when one is accepted
+ * instead of the choices. Harness idiom, `None` for a plain
+ * multi-select. See the `String` variant.
+ */
+ customField: string | null;
+ }
+ /**
+ * A property type this fold does not know. A renderer shows that it
+ * cannot display the field; decline and cancel still work.
+ */
+ | {
+ type: 'unrecognized';
+ /** The wire `type`. */
+ typeName: string;
+ /** The property schema, verbatim. */
+ raw: unknown;
+ };
+
+/** What the agent asked for. */
+export type ElicitationRequest =
+ /** Structured data through a form the client renders. */
+ | {
+ kind: 'form';
+ /** The restricted schema describing the form. */
+ schema: ElicitationSchema;
+ }
+ /** An out-of-band interaction the user consents to open. */
+ | {
+ kind: 'url';
+ /**
+ * The agent's handle for this interaction; `elicitation/complete`
+ * names it.
+ */
+ elicitationId: string;
+ /** Where the user is sent. */
+ url: string;
+ }
+ /**
+ * A Macro user tool (`SendEmail`, `CreateCalendarEvent`) paused for the
+ * user's review: the agent drafted the call and asks before it runs.
+ *
+ * Recognized from the call the form is scoped to - a tool this fold
+ * already knows as a user tool - or from `_meta.macro.userTool`, which
+ * Macro's own agent stamps. The draft is the call's arguments whole,
+ * so a client with the tool's own composer renders that and answers
+ * with the whole edited draft; `schema` is the flat form the agent also
+ * sent, for a client without one.
+ */
+ | {
+ kind: 'user_tool';
+ /** The tool, by Macro's name. */
+ tool: string;
+ /** The call's arguments - the tool's own JSON. */
+ draft: unknown;
+ /** The restricted form describing the draft's flat fields. */
+ schema: ElicitationSchema;
+ }
+ /**
+ * A mode this fold does not know. Kept raw so nothing is lost; a
+ * renderer must not treat it as form or url.
+ */
+ | {
+ kind: 'unrecognized';
+ /** The wire mode. */
+ mode: string;
+ /** The request params, verbatim. */
+ raw: unknown;
+ };
+
+/**
+ * The JSON-RPC id of an agent's `elicitation/create` request, carried whole
+ * so the answer echoes exactly what the agent sent.
+ *
+ * Agents pick these, not us: Claude Code counts from `0`, others use
+ * strings. `null` is not a legal id for a request that expects a response,
+ * so it is not representable here.
+ */
+export type ElicitationRequestId =
+ /**
+ * A numeric JSON-RPC id. Specta refuses `i64` (it does not fit a JS
+ * number); agents count their requests from zero, so `i32` is the
+ * honest TypeScript face.
+ */
+ | number
+ /** A string JSON-RPC id. */
+ | string;
+
+/** ACP's restricted form schema: a flat object of primitive properties. */
+export type ElicitationSchema = {
+ /** Schema-level title, when the agent gave one. */
+ title: string | null;
+ /** Schema-level description, when the agent gave one. */
+ description: string | null;
+ /** The fields, in the order the agent declared them. */
+ properties: ElicitationProperty[];
+ /** Property names the agent requires an answer for. */
+ required: string[];
+};
+
/** A file modification a tool reported. */
export type FileDiff = {
/** The file that changed. */
@@ -218,6 +543,49 @@ export type MessagePart =
kind: 'plan';
/** The tasks, in the order the agent listed them. */
entries: PlanEntry[];
+ }
+ /**
+ * The agent asking the user a question.
+ *
+ * When the question was asked on behalf of a tool call this fold had
+ * already opened (Claude Code's `AskUserQuestion`), this part *replaces*
+ * that tool's part in place: the question is the call, and rendering
+ * both would show one thing twice.
+ */
+ | {
+ kind: 'elicitation';
+ /**
+ * The agent's `elicitation/create` request id - what an answer must
+ * echo.
+ */
+ requestId: ElicitationRequestId;
+ /** The tool call the question belongs to, when the agent said. */
+ toolCall: ToolUseId | null;
+ /** What the agent is asking, in prose. */
+ message: string;
+ /** The form or URL. */
+ request: ElicitationRequest;
+ /** How it has resolved so far. */
+ outcome: ElicitationOutcome;
+ /**
+ * The harness's own reading of the answer, when it reported one
+ * after the response went back (Claude Code echoes the chosen
+ * option through its tool result). Absent otherwise.
+ *
+ * Shaped like [`ElicitationOutcome::Accepted`]'s answers so a reader
+ * renders one vocabulary either way, though a harness keys these by
+ * question prose rather than by property, so each `name` is that
+ * prose rather than a schema property.
+ */
+ reported: AnsweredField[] | null;
+ /**
+ * For a user tool's review ([`ElicitationRequest::UserTool`]): how
+ * the tool itself ended once the user answered - run with the
+ * reviewed draft, rejected, or failed - read from the absorbed
+ * call's later updates. Absent until the tool reports, and for
+ * every other kind of question.
+ */
+ toolOutcome: UserToolOutcome | null;
};
/** One model the runtime offers. */
@@ -237,6 +605,24 @@ export type ModelOption = {
group: string | null;
};
+/**
+ * The one elicitation the user can answer right now, surfaced on
+ * [`SessionMetadata`](super::SessionMetadata) so a reader need not scan the
+ * transcript for it.
+ */
+export type PendingElicitation = {
+ /** The agent's request id; what an answer must name. */
+ requestId: ElicitationRequestId;
+ /** The turn whose agent message holds the matching part. */
+ turn: number;
+ /** The tool call it was asked on behalf of, when any. */
+ toolCall: ToolUseId | null;
+ /** What the agent is asking, in prose. */
+ message: string;
+ /** The form or URL. */
+ request: ElicitationRequest;
+};
+
/** One choice offered for a permission request. */
export type PermissionOption = {
/** The id to report back when this option is chosen. */
@@ -335,6 +721,8 @@ export type PlanEntryStatus =
/**
* Session-level state derived from the log, latest-wins and carried whole.
* Fields start absent and fill in as the log reveals them.
+ *
+ * `PartialEq` only: a pending form's numeric bounds are `f64`.
*/
export type SessionMetadata = {
/** The agent that produced the log. See [`Harness`]. */
@@ -359,6 +747,12 @@ export type SessionMetadata = {
* `None` until the runtime reports one.
*/
status: string | null;
+ /**
+ * The one elicitation the user can answer right now. `None` when
+ * nothing is pending, when the turn that asked has ended, or when the
+ * connection that asked is gone - the request id dies with it.
+ */
+ pendingElicitation: PendingElicitation | null;
};
/**
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts
index cf477039b4..04ac108cb0 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentAction.ts
@@ -7,6 +7,7 @@
import type { AgentActionOneOf } from './agentActionOneOf';
import type { AgentActionOneOfFour } from './agentActionOneOfFour';
import type { AgentActionOneOfNine } from './agentActionOneOfNine';
+import type { AgentActionOneOfOneone } from './agentActionOneOfOneone';
import type { AgentActionOneOfSeven } from './agentActionOneOfSeven';
/**
@@ -16,4 +17,5 @@ export type AgentAction =
| AgentActionOneOf
| AgentActionOneOfFour
| AgentActionOneOfSeven
- | AgentActionOneOfNine;
+ | AgentActionOneOfNine
+ | AgentActionOneOfOneone;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneone.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneone.ts
new file mode 100644
index 0000000000..ede5f06edc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneone.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { AgentActionOneOfOneoneAllOf } from './agentActionOneOfOneoneAllOf';
+import type { AgentRespondElicitationAction } from './agentRespondElicitationAction';
+
+/**
+ * Answer an `elicitation/create` the agent sent.
+
+The one action whose wire form is a JSON-RPC *response* rather than a
+request or notification: the agent asked, we answer on its id. The
+minted [`AgentActionId`] therefore never reaches the wire for this
+action; the fold correlates on the agent's id instead.
+ */
+export type AgentActionOneOfOneone = AgentRespondElicitationAction &
+ AgentActionOneOfOneoneAllOf;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneoneAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneoneAllOf.ts
new file mode 100644
index 0000000000..64de5f769a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneoneAllOf.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentActionOneOfOneoneAllOfType } from './agentActionOneOfOneoneAllOfType';
+
+export type AgentActionOneOfOneoneAllOf = {
+ type: AgentActionOneOfOneoneAllOfType;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneoneAllOfType.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneoneAllOfType.ts
new file mode 100644
index 0000000000..ce4ec2fb10
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentActionOneOfOneoneAllOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentActionOneOfOneoneAllOfType =
+ (typeof AgentActionOneOfOneoneAllOfType)[keyof typeof AgentActionOneOfOneoneAllOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const AgentActionOneOfOneoneAllOfType = {
+ respondElicitation: 'respondElicitation',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRespondElicitationAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRespondElicitationAction.ts
new file mode 100644
index 0000000000..5c6cbf9613
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRespondElicitationAction.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { AgentRespondElicitationActionAllOf } from './agentRespondElicitationActionAllOf';
+import type { ElicitationAnswer } from './elicitationAnswer';
+
+/**
+ * Answer an elicitation the agent is waiting on.
+ */
+export type AgentRespondElicitationAction = ElicitationAnswer &
+ AgentRespondElicitationActionAllOf;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRespondElicitationActionAllOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRespondElicitationActionAllOf.ts
new file mode 100644
index 0000000000..c245ffffa5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentRespondElicitationActionAllOf.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationRequestId } from './elicitationRequestId';
+
+export type AgentRespondElicitationActionAllOf = {
+ /** The agent's `elicitation/create` request id - not an
+[`AgentActionId`], because the agent minted it. */
+ requestId: ElicitationRequestId;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswer.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswer.ts
new file mode 100644
index 0000000000..3d9e305adb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswer.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationAnswerOneOf } from './elicitationAnswerOneOf';
+import type { ElicitationAnswerOneOfFive } from './elicitationAnswerOneOfFive';
+import type { ElicitationAnswerOneOfSeven } from './elicitationAnswerOneOfSeven';
+
+/**
+ * What the user decided about an elicitation. Mirrors ACP's three actions;
+there is no `Other` because we never originate an action we do not know.
+ */
+export type ElicitationAnswer =
+ | ElicitationAnswerOneOf
+ | ElicitationAnswerOneOfFive
+ | ElicitationAnswerOneOfSeven;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOf.ts
new file mode 100644
index 0000000000..479d82e008
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOf.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationAnswerOneOfAction } from './elicitationAnswerOneOfAction';
+import type { ElicitationAnswerOneOfContent } from './elicitationAnswerOneOfContent';
+
+/**
+ * The user submitted the form, or consented to open the URL.
+ */
+export type ElicitationAnswerOneOf = {
+ action: ElicitationAnswerOneOfAction;
+ /** Form: the submitted values keyed by property. URL: omitted. */
+ content?: ElicitationAnswerOneOfContent;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfAction.ts
new file mode 100644
index 0000000000..cfce9837f4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfAction.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ElicitationAnswerOneOfAction =
+ (typeof ElicitationAnswerOneOfAction)[keyof typeof ElicitationAnswerOneOfAction];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ElicitationAnswerOneOfAction = {
+ accept: 'accept',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfContent.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfContent.ts
new file mode 100644
index 0000000000..9ae6d7fa4d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfContent.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationAnswerOneOfContentAnyOf } from './elicitationAnswerOneOfContentAnyOf';
+
+/**
+ * Form: the submitted values keyed by property. URL: omitted.
+ */
+export type ElicitationAnswerOneOfContent =
+ ElicitationAnswerOneOfContentAnyOf | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfContentAnyOf.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfContentAnyOf.ts
new file mode 100644
index 0000000000..f20f0687a0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfContentAnyOf.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationContentValue } from './elicitationContentValue';
+
+/**
+ * Form: the submitted values keyed by property. URL: omitted.
+ */
+export type ElicitationAnswerOneOfContentAnyOf = {
+ [key: string]: ElicitationContentValue;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfFive.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfFive.ts
new file mode 100644
index 0000000000..74d1d80b0e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfFive.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationAnswerOneOfFiveAction } from './elicitationAnswerOneOfFiveAction';
+
+/**
+ * The user explicitly said no.
+ */
+export type ElicitationAnswerOneOfFive = {
+ action: ElicitationAnswerOneOfFiveAction;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfFiveAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfFiveAction.ts
new file mode 100644
index 0000000000..02c66dbdc3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfFiveAction.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ElicitationAnswerOneOfFiveAction =
+ (typeof ElicitationAnswerOneOfFiveAction)[keyof typeof ElicitationAnswerOneOfFiveAction];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ElicitationAnswerOneOfFiveAction = {
+ decline: 'decline',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfSeven.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfSeven.ts
new file mode 100644
index 0000000000..1f49582192
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfSeven.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ElicitationAnswerOneOfSevenAction } from './elicitationAnswerOneOfSevenAction';
+
+/**
+ * The user dismissed the request without choosing.
+ */
+export type ElicitationAnswerOneOfSeven = {
+ action: ElicitationAnswerOneOfSevenAction;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfSevenAction.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfSevenAction.ts
new file mode 100644
index 0000000000..91405be814
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationAnswerOneOfSevenAction.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ElicitationAnswerOneOfSevenAction =
+ (typeof ElicitationAnswerOneOfSevenAction)[keyof typeof ElicitationAnswerOneOfSevenAction];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ElicitationAnswerOneOfSevenAction = {
+ cancel: 'cancel',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationContentValue.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationContentValue.ts
new file mode 100644
index 0000000000..aacf1526a1
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationContentValue.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A value ACP accepts in an elicitation answer.
+
+Mirrors ACP's `ElicitationContentValue` so that the contract a caller
+answers against is the closed union ACP will accept, rather than arbitrary
+JSON narrowed on the way out. An object, a null, or a mixed array is
+refused when the request is deserialized - where the caller learns of it -
+instead of at send time, when the elicitation slot has already been
+released.
+ */
+export type ElicitationContentValue =
+ | string
+ | boolean
+ | number
+ | number
+ | string[];
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationRequestId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationRequestId.ts
new file mode 100644
index 0000000000..559caeafdc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/elicitationRequestId.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The JSON-RPC id of an agent's `elicitation/create` request, carried whole
+so the answer echoes exactly what the agent sent.
+
+Agents pick these, not us: Claude Code counts from `0`, others use
+strings. `null` is not a legal id for a request that expects a response,
+so it is not representable here.
+ */
+export type ElicitationRequestId = number | string;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 7a4feaf8ad..31444fdfb1 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -15,9 +15,14 @@ export * from './agentActionOneOfFourAllOf';
export * from './agentActionOneOfFourAllOfType';
export * from './agentActionOneOfNine';
export * from './agentActionOneOfNineType';
+export * from './agentActionOneOfOneone';
+export * from './agentActionOneOfOneoneAllOf';
+export * from './agentActionOneOfOneoneAllOfType';
export * from './agentActionOneOfSeven';
export * from './agentActionOneOfSevenType';
export * from './agentPromptAction';
+export * from './agentRespondElicitationAction';
+export * from './agentRespondElicitationActionAllOf';
export * from './agentSessionLogEntryDto';
export * from './agentSessionLogEntryDtoAllOf';
export * from './agentSessionLogEntryDtoAllOfUserId';
@@ -48,6 +53,17 @@ export * from './createAgentSessionResponse';
export * from './createSessionThread';
export * from './createSessionThreadThreadId';
export * from './editQueuedActionRequest';
+export * from './elicitationAnswer';
+export * from './elicitationAnswerOneOf';
+export * from './elicitationAnswerOneOfAction';
+export * from './elicitationAnswerOneOfContent';
+export * from './elicitationAnswerOneOfContentAnyOf';
+export * from './elicitationAnswerOneOfFive';
+export * from './elicitationAnswerOneOfFiveAction';
+export * from './elicitationAnswerOneOfSeven';
+export * from './elicitationAnswerOneOfSevenAction';
+export * from './elicitationContentValue';
+export * from './elicitationRequestId';
export * from './externalSessionResponse';
export * from './externalSessionResponseName';
export * from './externalSessionResponseUrl';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 5609adc0c9..9b337e6f15 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -869,6 +869,25 @@
"enum": ["stop"]
}
}
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AgentRespondElicitationAction",
+ "description": "Answer an `elicitation/create` the agent sent.\n\nThe one action whose wire form is a JSON-RPC *response* rather than a\nrequest or notification: the agent asked, we answer on its id. The\nminted [`AgentActionId`] therefore never reaches the wire for this\naction; the fold correlates on the agent's id instead."
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["respondElicitation"]
+ }
+ }
+ }
+ ],
+ "description": "Answer an `elicitation/create` the agent sent.\n\nThe one action whose wire form is a JSON-RPC *response* rather than a\nrequest or notification: the agent asked, we answer on its id. The\nminted [`AgentActionId`] therefore never reaches the wire for this\naction; the fold correlates on the agent's id instead."
}
],
"description": "One thing a caller wants an agent to do."
@@ -889,6 +908,25 @@
}
}
},
+ "AgentRespondElicitationAction": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ElicitationAnswer",
+ "description": "The decision."
+ },
+ {
+ "type": "object",
+ "required": ["requestId"],
+ "properties": {
+ "requestId": {
+ "$ref": "#/components/schemas/ElicitationRequestId",
+ "description": "The agent's `elicitation/create` request id - not an\n[`AgentActionId`], because the agent minted it."
+ }
+ }
+ }
+ ],
+ "description": "Answer an elicitation the agent is waiting on."
+ },
"AgentSessionLogEntryDto": {
"allOf": [
{
@@ -1189,6 +1227,98 @@
}
}
},
+ "ElicitationAnswer": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "The user submitted the form, or consented to open the URL.",
+ "required": ["action"],
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["accept"]
+ },
+ "content": {
+ "type": ["object", "null"],
+ "description": "Form: the submitted values keyed by property. URL: omitted.",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/ElicitationContentValue"
+ },
+ "propertyNames": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The user explicitly said no.",
+ "required": ["action"],
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["decline"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The user dismissed the request without choosing.",
+ "required": ["action"],
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["cancel"]
+ }
+ }
+ }
+ ],
+ "description": "What the user decided about an elicitation. Mirrors ACP's three actions;\nthere is no `Other` because we never originate an action we do not know."
+ },
+ "ElicitationContentValue": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "A string, and the shape a whole draft rides in as JSON text."
+ },
+ {
+ "type": "boolean",
+ "description": "A yes/no."
+ },
+ {
+ "type": "integer",
+ "format": "int64",
+ "description": "A whole number."
+ },
+ {
+ "type": "number",
+ "format": "double",
+ "description": "A number that is not whole."
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "A multi-select's chosen values."
+ }
+ ],
+ "description": "A value ACP accepts in an elicitation answer.\n\nMirrors ACP's `ElicitationContentValue` so that the contract a caller\nanswers against is the closed union ACP will accept, rather than arbitrary\nJSON narrowed on the way out. An object, a null, or a mixed array is\nrefused when the request is deserialized - where the caller learns of it -\ninstead of at send time, when the elicitation slot has already been\nreleased."
+ },
+ "ElicitationRequestId": {
+ "oneOf": [
+ {
+ "type": "integer",
+ "format": "int64",
+ "description": "A numeric JSON-RPC id. Specta refuses `i64` (it does not fit a JS\nnumber); agents count their requests from zero, so `i32` is the\nhonest TypeScript face."
+ },
+ {
+ "type": "string",
+ "description": "A string JSON-RPC id."
+ }
+ ],
+ "description": "The JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here."
+ },
"ExternalSessionResponse": {
"type": "object",
"description": "The provider-side identity of an externally-served session.",
diff --git a/crates/agent/src/agent_loop.rs b/crates/agent/src/agent_loop.rs
index d0fd718557..406c9175b4 100644
--- a/crates/agent/src/agent_loop.rs
+++ b/crates/agent/src/agent_loop.rs
@@ -1,6 +1,6 @@
/// The main entry point: [`AgentLoop`] and [`Session`].
use crate::error::AgentError;
-use crate::hook::{RegisterFn, ToolRouter};
+use crate::hook::{BridgeInputs, RegisterFn, ToolRouter, UserToolFinisher};
use crate::model::PredefinedModel;
use crate::model::router::{ModelRouter, ProviderAgent};
use crate::stream::ChatCompletionStream;
@@ -30,6 +30,7 @@ pub struct AgentLoop {
max_turns: usize,
max_tokens: u64,
recorder: Arc<dyn UsageRecorder>,
+ user_tool_finisher: Option<UserToolFinisher>,
}
impl AgentLoop {
@@ -46,9 +47,24 @@ impl AgentLoop {
max_turns: DEFAULT_MAX_TURNS,
max_tokens: DEFAULT_MAX_TOKENS,
recorder,
+ user_tool_finisher: None,
}
}
+ /// Finish user tools inside the turn.
+ ///
+ /// A user tool (`ai_toolset::UserTool`) answers `"PendingUserExecution"`
+ /// and leaves the call for the host to finish. Without a finisher that
+ /// answer reaches the model as-is and the host finishes the call later,
+ /// as chat does over HTTP. With one, the bridge hands each pending call
+ /// to `finisher` before the model reads it, and the model sees what the
+ /// user decided instead - the shape a host that can reach its user
+ /// mid-turn wants.
+ pub fn with_user_tool_finisher(mut self, finisher: UserToolFinisher) -> Self {
+ self.user_tool_finisher = Some(finisher);
+ self
+ }
+
/// Override the model.
///
/// Accepts any stringifiable id — an [`AgentModel`] (backend) or a raw
@@ -228,9 +244,12 @@ impl AgentLoop {
agent,
history: Vec::new(),
max_turns: self.max_turns,
- routing,
- loaded_buffer,
- register_loaded,
+ bridge_inputs: BridgeInputs {
+ routing,
+ loaded_buffer,
+ register_loaded,
+ user_tool_finisher: self.user_tool_finisher.clone(),
+ },
recorder: self.recorder.clone(),
usage_ctx,
model: self.model.clone(),
@@ -273,11 +292,9 @@ pub struct Session {
agent: ProviderAgent,
history: Vec<Message>,
max_turns: usize,
- routing: ToolRouter,
- /// Tools `SearchTools` asked to load, shared with the stream bridge.
- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
- /// Registers loaded tools with the live tool server (see [`RegisterFn`]).
- register_loaded: RegisterFn,
+ /// What every turn's stream bridge is built from: tool routing, the
+ /// on-demand tool loading pair, and the user-tool finisher if any.
+ bridge_inputs: BridgeInputs,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -313,9 +330,7 @@ impl Session {
prompt.clone(),
history.to_vec(),
self.max_turns,
- self.routing.clone(),
- self.loaded_buffer.clone(),
- self.register_loaded.clone(),
+ self.bridge_inputs.clone(),
self.recorder.clone(),
self.usage_ctx.clone(),
self.model.clone(),
diff --git a/crates/agent/src/hook.rs b/crates/agent/src/hook.rs
index 1c195f932f..68cb08d9a4 100644
--- a/crates/agent/src/hook.rs
+++ b/crates/agent/src/hook.rs
@@ -30,6 +30,60 @@ pub type ToolRouter = Arc<dyn Fn(&str) -> Option<ToolInfo> + Send + Sync>;
pub type RegisterFn =
Arc<dyn Fn(Vec<SearchableTool>) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;
+/// A user tool the model called, as the host's [`UserToolFinisher`] sees it.
+///
+/// A user tool (`ai_toolset::UserTool`) answers `"PendingUserExecution"` and
+/// does nothing: the host is meant to finish it - let the user review the
+/// call, then execute or reject it. Chat does that after the turn, over HTTP;
+/// a host that can reach its user mid-turn does it here, before the model
+/// reads the result.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PendingUserTool {
+ /// The tool's name as the toolset knows it.
+ pub tool_name: String,
+ /// The call's id as the stream reported it ([`ToolCall::id`]): the
+ /// provider's, or rig's correlation id when the provider gave none. The
+ /// id the host's transcript shows the call under.
+ pub tool_call_id: String,
+ /// The arguments the model called the tool with.
+ pub args: serde_json::Value,
+}
+
+/// What a finished user tool comes back as, in place of the pending answer.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum FinishedUserTool {
+ /// The tool's own result (`UserToolResponse<T>` as JSON: the user's
+ /// action, or their rejection).
+ Result(serde_json::Value),
+ /// Finishing failed; the description is what the model reads.
+ Error(String),
+}
+
+/// Finishes a user tool inside the turn. Returns `None` to leave the pending
+/// answer as it is - the host will finish the call some other way, or not at
+/// all. Context-erased for the same reason as [`RegisterFn`].
+pub type UserToolFinisher = Arc<
+ dyn Fn(PendingUserTool) -> Pin<Box<dyn Future<Output = Option<FinishedUserTool>> + Send>>
+ + Send
+ + Sync,
+>;
+
+/// Everything the session hands the stream bridge besides the request context.
+#[derive(Clone)]
+pub struct BridgeInputs {
+ /// Resolves tool names to their MCP routing info.
+ pub routing: ToolRouter,
+ /// Tools `SearchTools` asked to load, awaiting registration.
+ pub loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
+ /// Registers loaded tools with the live tool server.
+ pub register_loaded: RegisterFn,
+ /// Finishes user tools mid-turn, when the host can.
+ pub user_tool_finisher: Option<UserToolFinisher>,
+}
+
+/// The answer a user tool gives when it has not been finished.
+const PENDING_USER_EXECUTION: &str = "PendingUserExecution";
+
static CANCELLED_REASON: &str = "user cancelled";
/// Retry budget for invalid tool calls recovered via
@@ -56,6 +110,9 @@ pub struct StreamBridge {
/// [`Self::on_invalid_tool_call`] to recover calls to tools the model
/// discovered but never loaded.
searchable_catalog: Arc<Vec<SearchableTool>>,
+ /// Finishes a user tool's pending answer before the model reads it, on
+ /// hosts that can reach the user mid-turn (see [`UserToolFinisher`]).
+ user_tool_finisher: Option<UserToolFinisher>,
/// the user has requested the stream stop
cancel: CancellationToken,
}
@@ -63,21 +120,25 @@ pub struct StreamBridge {
impl StreamBridge {
/// Create a bridge and its receiving half.
///
- /// `routing` resolves tool names to [`ToolInfo`] so MCP calls can be
+ /// `inputs.routing` resolves tool names to [`ToolInfo`] so MCP calls can be
/// tagged as such (see [`ToolRouter`]). `loaded_buffer` / `register_loaded`
/// power on-demand tool loading: `SearchTools` pushes matches into the
/// buffer, and the bridge registers them after the tool result, before the
/// next turn (see [`Self::on_tool_result`]).
pub fn channel(
- routing: ToolRouter,
- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
- register_loaded: RegisterFn,
+ inputs: BridgeInputs,
searchable_catalog: Arc<Vec<SearchableTool>>,
cancel: CancellationToken,
) -> (
Self,
mpsc::UnboundedReceiver<Result<StreamPart, AgentError>>,
) {
+ let BridgeInputs {
+ routing,
+ loaded_buffer,
+ register_loaded,
+ user_tool_finisher,
+ } = inputs;
let (tx, rx) = mpsc::unbounded_channel();
(
Self {
@@ -86,6 +147,7 @@ impl StreamBridge {
loaded_buffer,
register_loaded,
searchable_catalog,
+ user_tool_finisher,
cancel,
},
rx,
@@ -115,6 +177,11 @@ fn presentation_json(presentation: &ToolOutput) -> Option<serde_json::Value> {
.and_then(|text| serde_json::from_str(text).ok())
}
+/// Whether a tool's JSON result is a user tool's unfinished answer.
+fn is_pending_user_execution(json: &serde_json::Value) -> bool {
+ json.as_str() == Some(PENDING_USER_EXECUTION)
+}
+
/// The hook bodies, as inherent methods so tests can exercise them directly:
/// rig's [`HookContext`] has no public constructor, so the [`AgentHook`] impl
/// below is a thin delegation layer over these.
@@ -207,6 +274,7 @@ impl StreamBridge {
tool_name: &str,
tool_call_id: Option<&str>,
internal_call_id: &str,
+ args: &str,
presentation: &ToolOutput,
is_success: bool,
) -> ToolResultAction {
@@ -223,7 +291,47 @@ impl StreamBridge {
}
let id = tool_call_id.unwrap_or(internal_call_id).to_owned();
- let response = if is_success && let Some(json) = presentation_json(presentation) {
+ let json = if is_success {
+ presentation_json(presentation)
+ } else {
+ None
+ };
+
+ // A user tool's pending answer is finished here when the host can:
+ // the user reviews the call while the turn waits, and the model reads
+ // what they decided instead of a "pending" it would take for success.
+ if let Some(finisher) = &self.user_tool_finisher
+ && json.as_ref().is_some_and(is_pending_user_execution)
+ {
+ let call = PendingUserTool {
+ tool_name: tool_name.to_owned(),
+ tool_call_id: id.clone(),
+ args: serde_json::from_str(args).unwrap_or(serde_json::Value::Null),
+ };
+ match finisher(call).await {
+ Some(FinishedUserTool::Result(result)) => {
+ let _ = self
+ .tx
+ .send(Ok(StreamPart::ToolResponse(ToolResponse::Json {
+ id,
+ json: result.clone(),
+ name: tool_name.to_owned(),
+ })));
+ return ToolResultAction::Rewrite(ToolOutput::json(result));
+ }
+ Some(FinishedUserTool::Error(description)) => {
+ let _ = self.tx.send(Ok(StreamPart::ToolResponse(ToolResponse::Err {
+ id,
+ name: tool_name.to_owned(),
+ description: description.clone(),
+ })));
+ return ToolResultAction::rewrite(description);
+ }
+ None => {}
+ }
+ }
+
+ let response = if let Some(json) = json {
ToolResponse::Json {
id,
json,
@@ -284,6 +392,7 @@ impl AgentHook for StreamBridge {
event.tool_name,
event.tool_call_id,
event.internal_call_id,
+ event.args,
event.presentation,
event.raw_result.is_success(),
)
diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs
index c0732f6d90..99154451b2 100644
--- a/crates/agent/src/lib.rs
+++ b/crates/agent/src/lib.rs
@@ -23,6 +23,7 @@ pub use agent_loop::{AgentLoop, Session};
pub use completion::{complete, complete_with_history};
pub use convert::{merge_consecutive_parts, to_rig_messages};
pub use error::AgentError;
+pub use hook::{FinishedUserTool, PendingUserTool, UserToolFinisher};
pub use model::PredefinedModel;
pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};
pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter, normalize_request_schema};
diff --git a/crates/agent/src/model/router.rs b/crates/agent/src/model/router.rs
index 88413189bb..ddc856fbe7 100644
--- a/crates/agent/src/model/router.rs
+++ b/crates/agent/src/model/router.rs
@@ -16,9 +16,9 @@
//! sniffing the id. Unroutable ids fall back to the default model.
use std::collections::HashMap;
-use std::sync::{Arc, Mutex, OnceLock};
+use std::sync::{Arc, OnceLock};
-use ai_toolset::{RequestContext, SearchableTool};
+use ai_toolset::RequestContext;
use ai_usage::{UsageContext, UsageRecorder};
use futures::StreamExt;
use macro_env_var::env_var;
@@ -35,7 +35,7 @@ use super::anthropic::AnthropicModel;
use super::openai::{OpenAiChatCompletionsModel, OpenAiResponsesModel};
use super::types::Model;
use crate::error::AgentError;
-use crate::hook::{RegisterFn, StreamBridge, ToolRouter};
+use crate::hook::{BridgeInputs, StreamBridge};
use crate::stream::{ChatCompletionStream, StreamPart};
env_var! {
@@ -142,9 +142,7 @@ impl ProviderAgent {
prompt: Message,
history: Vec<Message>,
max_turns: usize,
- routing: ToolRouter,
- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
- register_loaded: RegisterFn,
+ inputs: BridgeInputs,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -157,9 +155,7 @@ impl ProviderAgent {
prompt,
history,
max_turns,
- routing,
- loaded_buffer,
- register_loaded,
+ inputs,
recorder,
usage_ctx,
model,
@@ -173,9 +169,7 @@ impl ProviderAgent {
prompt,
history,
max_turns,
- routing,
- loaded_buffer,
- register_loaded,
+ inputs,
recorder,
usage_ctx,
model,
@@ -189,9 +183,7 @@ impl ProviderAgent {
prompt,
history,
max_turns,
- routing,
- loaded_buffer,
- register_loaded,
+ inputs,
recorder,
usage_ctx,
model,
@@ -206,9 +198,7 @@ impl ProviderAgent {
prompt,
history,
max_turns,
- routing,
- loaded_buffer,
- register_loaded,
+ inputs,
recorder,
usage_ctx,
model,
@@ -403,9 +393,7 @@ async fn drive_stream<M>(
prompt: Message,
history: Vec<Message>,
max_turns: usize,
- routing: ToolRouter,
- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
- register_loaded: RegisterFn,
+ inputs: BridgeInputs,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -416,9 +404,7 @@ where
M::StreamingResponse: GetTokenUsage + Send + Sync,
{
let (bridge, mut rx) = StreamBridge::channel(
- routing,
- loaded_buffer,
- register_loaded,
+ inputs,
request_context.searchable_tools.clone(),
request_context.cancel.clone(),
);
@@ -520,9 +506,7 @@ pub(crate) trait DynStreamAgent: Send + Sync {
prompt: Message,
history: Vec<Message>,
max_turns: usize,
- routing: ToolRouter,
- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
- register_loaded: RegisterFn,
+ inputs: BridgeInputs,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -543,9 +527,7 @@ where
prompt: Message,
history: Vec<Message>,
max_turns: usize,
- routing: ToolRouter,
- loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
- register_loaded: RegisterFn,
+ inputs: BridgeInputs,
recorder: Arc<dyn UsageRecorder>,
usage_ctx: UsageContext,
model: String,
@@ -558,9 +540,7 @@ where
prompt,
history,
max_turns,
- routing,
- loaded_buffer,
- register_loaded,
+ inputs,
recorder,
usage_ctx,
model,
diff --git a/crates/agent/src/test/agent_loop/mod.rs b/crates/agent/src/test/agent_loop/mod.rs
index 3ac84396f4..cf5a1931d4 100644
--- a/crates/agent/src/test/agent_loop/mod.rs
+++ b/crates/agent/src/test/agent_loop/mod.rs
@@ -9,3 +9,4 @@ mod test_cooperative_cancellation;
mod test_eager_tools;
mod test_tool;
mod test_tool_search;
+mod test_user_tools;
diff --git a/crates/agent/src/test/agent_loop/test_user_tools.rs b/crates/agent/src/test/agent_loop/test_user_tools.rs
new file mode 100644
index 0000000000..c692d8286c
--- /dev/null
+++ b/crates/agent/src/test/agent_loop/test_user_tools.rs
@@ -0,0 +1,174 @@
+//! User tools through the whole loop: the tool answers pending, the session's
+//! finisher (when it has one) settles the call before the model reads it, and
+//! the model's next request carries what the user decided.
+
+use super::util;
+use crate::hook::{FinishedUserTool, PendingUserTool, UserToolFinisher};
+use crate::stream::ToolResponse;
+use ai_toolset::{
+ AsyncTool, AsyncToolCollection, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations,
+ ToolResult,
+};
+use async_trait::async_trait;
+use rig_core::completion::CompletionRequest;
+use rig_core::message::{Message, UserContent};
+use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::pin::Pin;
+use std::sync::{Arc, Mutex};
+
+#[derive(Deserialize, JsonSchema)]
+#[schemars(
+ title = "SendNote",
+ description = "Sends a note the user must confirm."
+)]
+struct SendNote {
+ text: String,
+}
+
+#[derive(Serialize, JsonSchema)]
+struct Sent {
+ delivered: String,
+}
+
+impl ToolAnnotated for SendNote {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Send note");
+}
+
+#[async_trait]
+impl AsyncTool<()> for SendNote {
+ type Output = Sent;
+
+ async fn call(
+ &self,
+ _service_context: ServiceContext<()>,
+ _request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ Ok(Sent {
+ delivered: self.text.clone(),
+ })
+ }
+}
+
+/// The model calls the user tool once, then reads its result and says "done".
+fn call_then_done() -> MockCompletionModel {
+ MockCompletionModel::from_stream_turns([
+ vec![
+ MockStreamEvent::tool_call(
+ "call-1",
+ "SendNote",
+ serde_json::json!({ "text": "hello" }),
+ ),
+ MockStreamEvent::final_response_with_default_usage(),
+ ],
+ vec![
+ MockStreamEvent::text("done"),
+ MockStreamEvent::final_response_with_default_usage(),
+ ],
+ ])
+}
+
+/// The tool result text the model was shown in its second request.
+fn tool_result_shown(requests: &[CompletionRequest]) -> String {
+ let second = requests
+ .get(1)
+ .expect("the model was asked again after the tool");
+ second
+ .chat_history
+ .iter()
+ .filter_map(|message| match message {
+ Message::User { content } => Some(content.iter()),
+ _ => None,
+ })
+ .flatten()
+ .filter_map(|content| match content {
+ UserContent::ToolResult(result) => Some(format!("{result:?}")),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+#[tokio::test]
+async fn without_a_finisher_the_model_reads_the_pending_answer() {
+ let model = call_then_done();
+ let toolset = util::tool_set(AsyncToolCollection::<()>::new().add_user_tool::<SendNote, ()>());
+ let mut session = util::session(toolset, Arc::new(()), model.clone()).await;
+
+ let result = util::drive(&mut session, "send hello").await;
+
+ let call = result.tool_calls()[0].clone();
+ let response = result
+ .tool_response(&call.id)
+ .expect("the call was answered");
+ assert!(
+ matches!(response, ToolResponse::Json { json, .. } if json == "PendingUserExecution"),
+ "chat's flow: the pending answer is recorded as-is, got {response:?}"
+ );
+ assert!(tool_result_shown(&model.requests()).contains("PendingUserExecution"));
+ assert_eq!(result.content(), "done");
+}
+
+#[tokio::test]
+async fn with_a_finisher_the_model_reads_what_the_user_decided() {
+ let model = call_then_done();
+ let seen: Arc<Mutex<Vec<PendingUserTool>>> = Arc::new(Mutex::new(Vec::new()));
+ let finisher: UserToolFinisher = {
+ let seen = Arc::clone(&seen);
+ Arc::new(move |call: PendingUserTool| {
+ let seen = Arc::clone(&seen);
+ Box::pin(async move {
+ seen.lock().unwrap().push(call);
+ Some(FinishedUserTool::Result(
+ serde_json::json!({"UserAction": {"delivered": "hello, edited"}}),
+ ))
+ }) as Pin<Box<dyn Future<Output = Option<FinishedUserTool>> + Send>>
+ })
+ };
+ let toolset = util::tool_set(AsyncToolCollection::<()>::new().add_user_tool::<SendNote, ()>());
+ let mut session = util::test_loop()
+ .with_user_tool_finisher(finisher)
+ .test_session(
+ toolset,
+ Arc::new(()),
+ "test preamble",
+ util::usage_ctx(),
+ model.clone(),
+ )
+ .await;
+
+ let result = util::drive(&mut session, "send hello").await;
+
+ let call = result.tool_calls()[0].clone();
+ assert_eq!(
+ &*seen.lock().unwrap(),
+ &[PendingUserTool {
+ tool_name: "SendNote".to_owned(),
+ tool_call_id: call.id.clone(),
+ args: serde_json::json!({ "text": "hello" }),
+ }],
+ "the finisher saw the call as the model made it, under the id the stream gave it"
+ );
+ let response = result
+ .tool_response(&call.id)
+ .expect("the call was answered");
+ assert!(
+ matches!(
+ response,
+ ToolResponse::Json { json, .. }
+ if json == &serde_json::json!({"UserAction": {"delivered": "hello, edited"}})
+ ),
+ "the stream records the finished result, got {response:?}"
+ );
+ let shown = tool_result_shown(&model.requests());
+ assert!(
+ shown.contains("hello, edited"),
+ "the model read the finished result: {shown}"
+ );
+ assert!(
+ !shown.contains("PendingUserExecution"),
+ "the pending answer never reached the model: {shown}"
+ );
+ assert_eq!(result.content(), "done");
+}
diff --git a/crates/agent/src/test/test_hook.rs b/crates/agent/src/test/test_hook.rs
index 74a5c5e80e..3852d366ec 100644
--- a/crates/agent/src/test/test_hook.rs
+++ b/crates/agent/src/test/test_hook.rs
@@ -1,7 +1,7 @@
use crate::hook::*;
-use crate::stream::StreamPart;
+use crate::stream::{StreamPart, ToolResponse};
use ai_toolset::SearchableTool;
-use rig_agent::agent::{InvalidToolCallAction, ToolCallAction};
+use rig_agent::agent::{InvalidToolCallAction, ToolCallAction, ToolResultAction};
use rig_agent::tool::ToolOutput;
use schemars::Schema;
use std::pin::Pin;
@@ -32,6 +32,38 @@ fn recording_register() -> (RegisterFn, Arc<Mutex<Vec<String>>>) {
(register, recorded)
}
+/// Bridge inputs with no routing and `register` as the registrar; the caller
+/// supplies the loaded-tool buffer and, optionally, a user-tool finisher.
+fn inputs(
+ loaded_buffer: Arc<Mutex<Vec<SearchableTool>>>,
+ register: RegisterFn,
+ user_tool_finisher: Option<UserToolFinisher>,
+) -> BridgeInputs {
+ BridgeInputs {
+ routing: Arc::new(|_| None),
+ loaded_buffer,
+ register_loaded: register,
+ user_tool_finisher,
+ }
+}
+
+/// A finisher that records what it was handed and answers with `answer`.
+fn recording_finisher(
+ answer: Option<FinishedUserTool>,
+) -> (UserToolFinisher, Arc<Mutex<Vec<PendingUserTool>>>) {
+ let recorded = Arc::new(Mutex::new(Vec::new()));
+ let sink = recorded.clone();
+ let finisher: UserToolFinisher = Arc::new(move |call: PendingUserTool| {
+ let sink = sink.clone();
+ let answer = answer.clone();
+ Box::pin(async move {
+ sink.lock().unwrap().push(call);
+ answer
+ }) as Pin<Box<dyn Future<Output = Option<FinishedUserTool>> + Send>>
+ });
+ (finisher, recorded)
+}
+
#[tokio::test]
async fn on_tool_result_drains_buffer_and_registers_loaded_tools() {
let buffer = Arc::new(Mutex::new(vec![
@@ -39,16 +71,19 @@ async fn on_tool_result_drains_buffer_and_registers_loaded_tools() {
searchable("mcp__linear__create_issue"),
]));
let (register, registered) = recording_register();
- let routing: ToolRouter = Arc::new(|_| None);
let token = CancellationToken::new();
- let (bridge, _rx) =
- StreamBridge::channel(routing, buffer.clone(), register, Arc::new(vec![]), token);
+ let (bridge, _rx) = StreamBridge::channel(
+ inputs(buffer.clone(), register, None),
+ Arc::new(vec![]),
+ token,
+ );
bridge
.handle_tool_result(
"SearchTools",
None,
"call-1",
+ "{}",
&ToolOutput::json(serde_json::json!({"loaded": []})),
true,
)
@@ -71,15 +106,16 @@ async fn on_tool_result_drains_buffer_and_registers_loaded_tools() {
async fn on_tool_result_registers_nothing_when_buffer_empty() {
let buffer = Arc::new(Mutex::new(Vec::new()));
let (register, registered) = recording_register();
- let routing: ToolRouter = Arc::new(|_| None);
let token = CancellationToken::new();
- let (bridge, _rx) = StreamBridge::channel(routing, buffer, register, Arc::new(vec![]), token);
+ let (bridge, _rx) =
+ StreamBridge::channel(inputs(buffer, register, None), Arc::new(vec![]), token);
bridge
.handle_tool_result(
"WebSearch",
None,
"call-2",
+ "{}",
&ToolOutput::json(serde_json::json!({})),
true,
)
@@ -97,9 +133,22 @@ fn bare_bridge() -> (
) {
let (register, _registered) = recording_register();
StreamBridge::channel(
- Arc::new(|_| None),
- Arc::new(Mutex::new(Vec::new())),
- register,
+ inputs(Arc::new(Mutex::new(Vec::new())), register, None),
+ Arc::new(vec![]),
+ CancellationToken::new(),
+ )
+}
+
+/// A bare bridge whose user tools `finisher` finishes.
+fn finishing_bridge(
+ finisher: UserToolFinisher,
+) -> (
+ StreamBridge,
+ tokio::sync::mpsc::UnboundedReceiver<Result<StreamPart, crate::AgentError>>,
+) {
+ let (register, _registered) = recording_register();
+ StreamBridge::channel(
+ inputs(Arc::new(Mutex::new(Vec::new())), register, Some(finisher)),
Arc::new(vec![]),
CancellationToken::new(),
)
@@ -145,12 +194,9 @@ async fn on_tool_call_coerces_non_object_args_to_empty_object() {
#[tokio::test]
async fn invalid_call_to_searchable_tool_loads_it_and_retries() {
let (register, registered) = recording_register();
- let routing: ToolRouter = Arc::new(|_| None);
let catalog = Arc::new(vec![searchable("mcp__linear__create_issue")]);
let (bridge, _rx) = StreamBridge::channel(
- routing,
- Arc::new(Mutex::new(Vec::new())),
- register,
+ inputs(Arc::new(Mutex::new(Vec::new())), register, None),
catalog,
CancellationToken::new(),
);
@@ -170,12 +216,9 @@ async fn invalid_call_to_searchable_tool_loads_it_and_retries() {
#[tokio::test]
async fn invalid_call_to_unknown_tool_retries_with_feedback_without_loading() {
let (register, registered) = recording_register();
- let routing: ToolRouter = Arc::new(|_| None);
let catalog = Arc::new(vec![searchable("mcp__linear__create_issue")]);
let (bridge, _rx) = StreamBridge::channel(
- routing,
- Arc::new(Mutex::new(Vec::new())),
- register,
+ inputs(Arc::new(Mutex::new(Vec::new())), register, None),
catalog,
CancellationToken::new(),
);
@@ -192,3 +235,154 @@ async fn invalid_call_to_unknown_tool_retries_with_feedback_without_loading() {
};
assert!(feedback.contains("mcp__nope__hallucinated"));
}
+
+// --- user tools ---
+
+const PENDING: &str = "\"PendingUserExecution\"";
+
+/// The finisher gets the call as the model made it, and what it returns is
+/// what the model reads and what the stream records - the pending answer
+/// never leaves the bridge.
+#[tokio::test]
+async fn a_pending_user_tool_is_finished_before_the_model_reads_it() {
+ let created = serde_json::json!({"UserAction": {"eventId": "evt-1", "title": "Sync"}});
+ let (finisher, seen) = recording_finisher(Some(FinishedUserTool::Result(created.clone())));
+ let (bridge, mut rx) = finishing_bridge(finisher);
+
+ let action = bridge
+ .handle_tool_result(
+ "CreateCalendarEvent",
+ Some("toolu_1"),
+ "internal-1",
+ "{\"title\":\"Sync\"}",
+ &ToolOutput::json(serde_json::Value::String("PendingUserExecution".into())),
+ true,
+ )
+ .await;
+
+ assert_eq!(
+ &*seen.lock().unwrap(),
+ &[PendingUserTool {
+ tool_name: "CreateCalendarEvent".to_owned(),
+ tool_call_id: "toolu_1".to_owned(),
+ args: serde_json::json!({"title": "Sync"}),
+ }]
+ );
+ let ToolResultAction::Rewrite(shown) = action else {
+ panic!("the model's view is rewritten, got {action:?}");
+ };
+ assert_eq!(shown.as_json(), Some(&created));
+ let Ok(StreamPart::ToolResponse(ToolResponse::Json { id, json, name })) =
+ rx.try_recv().unwrap()
+ else {
+ panic!("the stream records the finished result");
+ };
+ assert_eq!(
+ (id.as_str(), name.as_str()),
+ ("toolu_1", "CreateCalendarEvent")
+ );
+ assert_eq!(json, created);
+}
+
+#[tokio::test]
+async fn a_user_tool_the_finisher_fails_reads_as_a_tool_error() {
+ let (finisher, _seen) = recording_finisher(Some(FinishedUserTool::Error(
+ "the user is already being asked something".to_owned(),
+ )));
+ let (bridge, mut rx) = finishing_bridge(finisher);
+
+ let action = bridge
+ .handle_tool_result(
+ "SendEmail",
+ Some("toolu_2"),
+ "internal-2",
+ "{}",
+ &ToolOutput::text(PENDING),
+ true,
+ )
+ .await;
+
+ let ToolResultAction::Rewrite(shown) = action else {
+ panic!("the model's view is rewritten, got {action:?}");
+ };
+ assert_eq!(
+ shown.as_text(),
+ Some("the user is already being asked something")
+ );
+ let Ok(StreamPart::ToolResponse(ToolResponse::Err { description, .. })) =
+ rx.try_recv().unwrap()
+ else {
+ panic!("the stream records the failure");
+ };
+ assert_eq!(description, "the user is already being asked something");
+}
+
+/// A finisher that declines to act, and a bridge with no finisher at all,
+/// both leave the pending answer for the host to finish later - chat's flow.
+#[tokio::test]
+async fn an_unfinished_user_tool_keeps_its_pending_answer() {
+ let (finisher, seen) = recording_finisher(None);
+ for (bridge, mut rx) in [finishing_bridge(finisher), bare_bridge()] {
+ let action = bridge
+ .handle_tool_result(
+ "SendEmail",
+ None,
+ "internal-3",
+ "{}",
+ &ToolOutput::text(PENDING),
+ true,
+ )
+ .await;
+ assert!(matches!(action, ToolResultAction::Keep), "got {action:?}");
+ let Ok(StreamPart::ToolResponse(ToolResponse::Json { json, .. })) = rx.try_recv().unwrap()
+ else {
+ panic!("the stream records the pending answer");
+ };
+ assert_eq!(json, serde_json::json!("PendingUserExecution"));
+ }
+ assert_eq!(
+ seen.lock().unwrap().len(),
+ 1,
+ "the declining finisher was asked once"
+ );
+}
+
+/// Only the pending answer is a user tool's: every other result, and every
+/// failure, passes the finisher by.
+#[tokio::test]
+async fn results_other_than_pending_never_reach_the_finisher() {
+ let (finisher, seen) =
+ recording_finisher(Some(FinishedUserTool::Result(serde_json::json!("never"))));
+ let (bridge, mut rx) = finishing_bridge(finisher);
+
+ bridge
+ .handle_tool_result(
+ "ListCalendars",
+ None,
+ "internal-4",
+ "{}",
+ &ToolOutput::json(serde_json::json!({"calendars": []})),
+ true,
+ )
+ .await;
+ bridge
+ .handle_tool_result(
+ "CreateCalendarEvent",
+ None,
+ "internal-5",
+ "{}",
+ &ToolOutput::text(PENDING),
+ false,
+ )
+ .await;
+
+ assert!(seen.lock().unwrap().is_empty());
+ assert!(matches!(
+ rx.try_recv().unwrap(),
+ Ok(StreamPart::ToolResponse(ToolResponse::Json { .. }))
+ ));
+ assert!(matches!(
+ rx.try_recv().unwrap(),
+ Ok(StreamPart::ToolResponse(ToolResponse::Err { .. }))
+ ));
+}
diff --git a/crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl b/crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl
new file mode 100644
index 0000000000..109d876365
--- /dev/null
+++ b/crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl
@@ -0,0 +1,40 @@
+{"ts":"2026-09-02T22:43:35.761Z","direction":"to_server","content":{"type":"event","event":"acp_ready"}}
+{"ts":"2026-09-02T22:43:35.761Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"093a62ba-61d6-4c31-914d-a03cffa4b5b0","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{"fs":{"readTextFile":false,"writeTextFile":false},"terminal":false,"elicitation":{"form":{},"url":{}}}}}}
+{"ts":"2026-09-02T22:43:37.045Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"093a62ba-61d6-4c31-914d-a03cffa4b5b0","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":[],"_meta":{"steering":{"supported":true}}}}}
+{"ts":"2026-09-02T22:43:37.046Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"42059514-0bef-4d64-b44e-798af3c77880","method":"session/new","params":{"cwd":"/workspace","mcpServers":[]}}}
+{"ts":"2026-09-02T22:43:37.710Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"42059514-0bef-4d64-b44e-798af3c77880","result":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","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":"Opus 5 with 1M context \u00b7 Best for everyday, complex tasks"},{"value":"opus[1m]","name":"Opus (1M context)","description":"Opus 5 with 1M context \u00b7 Best for everyday, complex tasks"},{"value":"claude-fable-5[1m]","name":"Fable","description":"Fable 5 \u00b7 Most capable for your hardest and longest-running tasks"},{"value":"sonnet","name":"Sonnet","description":"Sonnet 5 \u00b7 Efficient for routine tasks"},{"value":"haiku","name":"Haiku","description":"Haiku 4.5 \u00b7 Fastest for quick answers"}]},{"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-02T22:43:37.711Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"c4f086b1-8f75-4cdd-a772-f1ed41286d61","method":"session/prompt","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","prompt":[{"type":"text","text":"Please use your elicitation capability (elicitation/create, form mode) to ask me what the best colour is, with options: 1. red 2. blue 3. green"}]}}}
+{"ts":"2026-09-02T22:43:37.712Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"add-sdk-endpoint","description":"Wrap a new backend endpoint in the TypeScript SDK (packages/sdk), or record it as skipped. Use when `just coverage` fails, or after adding an endpoint to a Rust service. (project)","input":null},{"name":"qc","description":"Quality gate. 5 parallel agents review changes. All must pass. (project)","input":null},{"name":"compact","description":"Free up context by summarizing the conversation so far","input":{"hint":"<optional custom summarization instructions>"}}]}}}}
+{"ts":"2026-09-02T22:43:40.153Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"usage_update","used":47248,"size":200000}}}}
+{"ts":"2026-09-02T22:43:40.154Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.203Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" don"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.261Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"'t have an"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" el"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"icitation/form"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" cap"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ability to"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" present"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" inter"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"active U"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.651Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"I wid"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.675Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"gets \u2014 I can only re"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.722Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ply in"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.766Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" text or"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:40.816Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" use the AskU"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:41.182Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"serQuestion tool."},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:41.182Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" I"},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:41.182Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"'ll use that instead."},"messageId":"msg_011CefRQjJSyDELfT2ExPeCA"}}}}
+{"ts":"2026-09-02T22:43:41.186Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"_meta":{"claudeCode":{"toolName":"AskUserQuestion"}},"toolCallId":"toolu_01JYzP4A82LetDUgqvnRXguU","sessionUpdate":"tool_call","rawInput":{},"status":"pending","title":"Asking for your input","kind":"other","content":[]}}}}
+{"ts":"2026-09-02T22:43:41.900Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"_meta":{"claudeCode":{"toolName":"AskUserQuestion"}},"toolCallId":"toolu_01JYzP4A82LetDUgqvnRXguU","sessionUpdate":"tool_call_update","rawInput":{"questions":[{"question":"What is the best colour?","header":"Best colour","options":[{"label":"Red","description":"Red"},{"label":"Blue","description":"Blue"},{"label":"Green","description":"Green"}],"multiSelect":false}]},"title":"What is the best colour?","kind":"other","content":[{"type":"content","content":{"type":"text","text":"What is the best colour?"}}]}}}}
+{"ts":"2026-09-02T22:43:41.905Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":0,"method":"elicitation/create","params":{"mode":"form","sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","toolCallId":"toolu_01JYzP4A82LetDUgqvnRXguU","message":"What is the best colour?","requestedSchema":{"type":"object","properties":{"question_0":{"type":"string","title":"Best colour","oneOf":[{"const":"Red","title":"Red","description":"Red"},{"const":"Blue","title":"Blue","description":"Blue"},{"const":"Green","title":"Green","description":"Green"}]},"question_0_custom":{"type":"string","title":"Other","description":"Type your own answer instead of choosing an option above (optional).","_meta":{"_askUserQuestionCustomAnswer":{"questionId":"question_0","isCustomAnswer":true}}}}}}}}
+{"ts":"2026-09-02T22:43:41.906Z","direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":0,"result":{"action":"accept","content":{"question_0":"Red","question_0_custom":"blue"}}}}
+{"ts":"2026-09-02T22:43:41.908Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"usage_update","used":47443,"size":200000}}}}
+{"ts":"2026-09-02T22:43:41.913Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"_meta":{"claudeCode":{"toolResponse":{"questions":[{"question":"What is the best colour?","header":"Best colour","options":[{"label":"Red","description":"Red"},{"label":"Blue","description":"Blue"},{"label":"Green","description":"Green"}],"multiSelect":false}],"answers":{"What is the best colour?":"blue"}},"toolName":"AskUserQuestion"}},"toolCallId":"toolu_01JYzP4A82LetDUgqvnRXguU","sessionUpdate":"tool_call_update"}}}}
+{"ts":"2026-09-02T22:43:41.922Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"_meta":{"claudeCode":{"toolName":"AskUserQuestion"}},"toolCallId":"toolu_01JYzP4A82LetDUgqvnRXguU","sessionUpdate":"tool_call_update","status":"completed","rawOutput":"The user answered: \"What is the best colour?\"=\"blue\". Read the answers carefully \u2014 they may request clarification, changes, or that you not proceed \u2014 and follow what they actually say.","content":[{"type":"content","content":{"type":"text","text":"The user answered: \"What is the best colour?\"=\"blue\". Read the answers carefully \u2014 they may request clarification, changes, or that you not proceed \u2014 and follow what they actually say."}}]}}}}
+{"ts":"2026-09-02T22:43:43.056Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"usage_update","used":47504,"size":200000}}}}
+{"ts":"2026-09-02T22:43:43.066Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Bl"},"messageId":"msg_011CefRR32oCr1jqyjUH7i7T"}}}}
+{"ts":"2026-09-02T22:43:43.105Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"ue it"},"messageId":"msg_011CefRR32oCr1jqyjUH7i7T"}}}}
+{"ts":"2026-09-02T22:43:43.134Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" is."},"messageId":"msg_011CefRR32oCr1jqyjUH7i7T"}}}}
+{"ts":"2026-09-02T22:43:43.147Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"usage_update","used":47510,"size":200000}}}}
+{"ts":"2026-09-02T22:43:43.158Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"43358ad3-3d47-4ea3-925c-8d27ee90bbc2","update":{"sessionUpdate":"usage_update","used":47510,"size":1000000,"cost":{"amount":0.3028725,"currency":"USD"},"_meta":{"_claude/origin":{"kind":"human"}}}}}}
+{"ts":"2026-09-02T22:43:43.159Z","direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"c4f086b1-8f75-4cdd-a772-f1ed41286d61","result":{"stopReason":"end_turn","usage":{"inputTokens":4,"outputTokens":204,"cachedReadTokens":47245,"cachedWriteTokens":47500,"totalTokens":94953}}}}
diff --git a/crates/agent_fold/scripts/convert_stdio_recording.py b/crates/agent_fold/scripts/convert_stdio_recording.py
new file mode 100644
index 0000000000..d037dc5056
--- /dev/null
+++ b/crates/agent_fold/scripts/convert_stdio_recording.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""Turn a stdio ACP recording into the fold's fixture format.
+
+A local recorder wrapping an ACP agent's stdin/stdout writes lines like
+
+ {"ts": "...", "direction": "stdin", "line": {"jsonrpc": "2.0", ...}}
+ {"ts": "...", "direction": "stdout", "line": {"jsonrpc": "2.0", ...}}
+ {"ts": "...", "direction": "stderr", "line": "some log text"}
+
+The fold reads `agent_session_log` rows, which the fixtures mirror:
+
+ {"ts": "...", "direction": "to_server", "content": {"type": "event", "event": "acp_ready"}}
+ {"ts": "...", "direction": "to_runtime", "content": {"type": "acp", "jsonrpc": "2.0", ...}}
+ {"ts": "...", "direction": "to_server", "content": {"type": "acp", "jsonrpc": "2.0", ...}}
+
+`stdin` is what the client (us) sent the agent, so it is `to_runtime`;
+`stdout` is what the agent sent back, `to_server`. `stderr` is dropped. An
+`acp_ready` event is prepended, stamped with the first frame's time, since a
+real session's log starts with the runtime announcing itself.
+
+Optional rewrites for fixtures: `--cwd FROM TO` replaces a workspace path
+everywhere it appears as a JSON string; `--trim-commands N` keeps only the
+first N entries of each `available_commands_update` (those lists run to
+hundreds of lines of skill descriptions that prove nothing about the fold).
+
+Run the sanitizer afterwards if the recording came from a real session.
+
+Usage:
+ ./convert_stdio_recording.py input.jsonl output.jsonl [--cwd FROM TO] [--trim-commands N]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+DIRECTION = {"stdin": "to_runtime", "stdout": "to_server"}
+
+
+def rewrite_strings(value, old: str, new: str):
+ if isinstance(value, str):
+ return value.replace(old, new)
+ if isinstance(value, list):
+ return [rewrite_strings(item, old, new) for item in value]
+ if isinstance(value, dict):
+ return {key: rewrite_strings(item, old, new) for key, item in value.items()}
+ return value
+
+
+def trim_commands(frame: dict, keep: int) -> dict:
+ update = frame.get("params", {}).get("update")
+ if isinstance(update, dict) and update.get("sessionUpdate") == "available_commands_update":
+ commands = update.get("availableCommands")
+ if isinstance(commands, list):
+ update["availableCommands"] = commands[:keep]
+ return frame
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("input", type=Path)
+ parser.add_argument("output", type=Path)
+ parser.add_argument("--cwd", nargs=2, metavar=("FROM", "TO"))
+ parser.add_argument("--trim-commands", type=int, metavar="N")
+ args = parser.parse_args()
+
+ out_lines: list[str] = []
+ first_ts: str | None = None
+ for raw in args.input.read_text().splitlines():
+ raw = raw.strip()
+ if not raw:
+ continue
+ entry = json.loads(raw)
+ direction = DIRECTION.get(entry.get("direction"))
+ if direction is None:
+ continue
+ frame = entry["line"]
+ if not isinstance(frame, dict):
+ continue
+ if args.cwd:
+ frame = rewrite_strings(frame, args.cwd[0], args.cwd[1])
+ if args.trim_commands is not None:
+ frame = trim_commands(frame, args.trim_commands)
+ ts = entry["ts"]
+ if first_ts is None:
+ first_ts = ts
+ out_lines.append(
+ json.dumps(
+ {"ts": ts, "direction": "to_server", "content": {"type": "event", "event": "acp_ready"}},
+ separators=(",", ":"),
+ )
+ )
+ content = {"type": "acp", **frame}
+ out_lines.append(json.dumps({"ts": ts, "direction": direction, "content": content}, separators=(",", ":")))
+
+ if not out_lines:
+ print("no ACP frames found", file=sys.stderr)
+ return 1
+ args.output.write_text("\n".join(out_lines) + "\n")
+ print(f"wrote {len(out_lines)} frames to {args.output}", file=sys.stderr)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/crates/agent_fold/src/bin/fold_jsonl.rs b/crates/agent_fold/src/bin/fold_jsonl.rs
index a5e0f2e897..f642404d00 100644
--- a/crates/agent_fold/src/bin/fold_jsonl.rs
+++ b/crates/agent_fold/src/bin/fold_jsonl.rs
@@ -12,8 +12,10 @@
use agent_fold::domain::fold::FoldMachineImpl;
use agent_fold::domain::log::{AgentSessionId, AgentSessionLog, Message};
use agent_fold::domain::model::{
- Author, Control, ControlOutcome, FoldedMessage, MessagePart, PermissionOption,
- PermissionOutcome, PlanEntryStatus, StopReason, ToolDetail, ToolStatus, ToolUseId,
+ AnsweredField, AnsweredValue, Author, Control, ControlOutcome, ElicitationOutcome,
+ ElicitationPropertySchema, ElicitationRequest, ElicitationSchema, FoldedMessage, MessagePart,
+ PermissionOption, PermissionOutcome, PlanEntryStatus, StopReason, ToolDetail, ToolStatus,
+ ToolUseId,
};
use agent_fold::domain::ports::FoldMachine;
use agent_fold::domain::ports::LogRepo;
@@ -272,11 +274,147 @@ fn render_part(part: &MessagePart) -> String {
let _ = writeln!(out, "{}", indent(&format!("[{mark}] {}", entry.content)));
}
}
+ MessagePart::Elicitation {
+ message: question,
+ request,
+ outcome,
+ reported,
+ ..
+ } => out.push_str(&render_elicitation(
+ question,
+ request,
+ outcome,
+ reported.as_deref(),
+ )),
+ }
+ }
+ out
+}
+
+/// A question: `[question · outcome]`, the message, then each field or the URL.
+fn render_elicitation(
+ question: &str,
+ request: &ElicitationRequest,
+ outcome: &ElicitationOutcome,
+ reported: Option<&[AnsweredField]>,
+) -> String {
+ let mut out = String::new();
+ let state = match outcome {
+ ElicitationOutcome::Pending => "pending".to_owned(),
+ ElicitationOutcome::Accepted { answers } if answers.is_empty() => "accepted".to_owned(),
+ ElicitationOutcome::Accepted { answers } => format!("accepted {}", render_answers(answers)),
+ ElicitationOutcome::Declined => "declined".to_owned(),
+ ElicitationOutcome::Cancelled => "cancelled".to_owned(),
+ ElicitationOutcome::Completed => "completed".to_owned(),
+ ElicitationOutcome::Errored { message } => format!("error: {message}"),
+ ElicitationOutcome::Unrecognized => "unrecognized".to_owned(),
+ };
+ let _ = writeln!(out, "[question · {state}]");
+ let _ = writeln!(out, "{}", indent(question.trim_end()));
+ match request {
+ ElicitationRequest::UserTool {
+ tool,
+ draft,
+ schema,
+ } => {
+ let _ = writeln!(out, "{}", indent(&format!("review {tool}: {draft}")));
+ render_form_fields(&mut out, schema);
+ }
+ ElicitationRequest::Form { schema } => render_form_fields(&mut out, schema),
+ ElicitationRequest::Url { url, .. } => {
+ let _ = writeln!(out, "{}", indent(&format!("open {url}")));
+ }
+ ElicitationRequest::Unrecognized { mode, .. } => {
+ let _ = writeln!(out, "{}", indent(&format!("unrecognized mode {mode}")));
}
}
+ if let Some(reported) = reported {
+ let _ = writeln!(
+ out,
+ "{}",
+ indent(&format!("agent read: {}", render_answers(reported)))
+ );
+ }
out
}
+/// Answers as `label=value`, comma separated.
+fn render_answers(answers: &[AnsweredField]) -> String {
+ answers
+ .iter()
+ .map(|answer| {
+ let value = match &answer.value {
+ AnsweredValue::Text { text } | AnsweredValue::Custom { text } => text.clone(),
+ AnsweredValue::Number { text } => text.clone(),
+ AnsweredValue::Boolean { checked } => checked.to_string(),
+ AnsweredValue::Choice { choice } => choice.value.clone(),
+ AnsweredValue::Choices { choices } => choices
+ .iter()
+ .map(|choice| choice.value.as_str())
+ .collect::<Vec<_>>()
+ .join("+"),
+ AnsweredValue::Unrecognized { raw } => raw.to_string(),
+ };
+ format!("{}={value}", answer.label)
+ })
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+/// One line per form field: `label* (shape)`.
+fn render_form_fields(out: &mut String, schema: &ElicitationSchema) {
+ for property in &schema.properties {
+ let label = property.title.as_deref().unwrap_or(&property.name);
+ let required = if schema.required.contains(&property.name) {
+ "*"
+ } else {
+ ""
+ };
+ let shape = match &property.schema {
+ ElicitationPropertySchema::String {
+ options,
+ custom_field,
+ ..
+ } if !options.is_empty() => {
+ let choices: Vec<&str> = options
+ .iter()
+ .map(|option| option.title.as_deref().unwrap_or(&option.value))
+ .collect();
+ let other = if custom_field.is_some() {
+ " | other…"
+ } else {
+ ""
+ };
+ format!("select: {}{other}", choices.join(" | "))
+ }
+ ElicitationPropertySchema::String { .. } => "text".to_owned(),
+ ElicitationPropertySchema::Number { .. } => "number".to_owned(),
+ ElicitationPropertySchema::Integer { .. } => "integer".to_owned(),
+ ElicitationPropertySchema::Boolean { .. } => "boolean".to_owned(),
+ ElicitationPropertySchema::MultiSelect {
+ options,
+ custom_field,
+ ..
+ } => {
+ let choices: Vec<&str> = options
+ .iter()
+ .map(|option| option.title.as_deref().unwrap_or(&option.value))
+ .collect();
+ let other = if custom_field.is_some() {
+ " | other…"
+ } else {
+ ""
+ };
+ format!("multi-select: {}{other}", choices.join(" | "))
+ }
+ ElicitationPropertySchema::Unrecognized { type_name, .. } => {
+ format!("unrecognized type {type_name}")
+ }
+ };
+ let _ = writeln!(out, "{}", indent(&format!("{label}{required} ({shape})")));
+ }
+}
+
/// A tool call: `[label · status]` then whatever detail the fold recovered.
fn render_tool(label: &str, status: ToolStatus, detail: &ToolDetail) -> String {
let mut out = String::new();
diff --git a/crates/agent_fold/src/domain/fold.rs b/crates/agent_fold/src/domain/fold.rs
index 7adc8dec01..aa32e2019c 100644
--- a/crates/agent_fold/src/domain/fold.rs
+++ b/crates/agent_fold/src/domain/fold.rs
@@ -12,6 +12,8 @@
//! - A tool call whose opening frame carried no useful fields gets them from
//! later patches. Until then it renders as a bare tool row.
//! - A permission request with no answer is outstanding.
+//! - A question the agent asked with no answer is outstanding too - in the
+//! transcript forever, on the metadata only while its turn is open.
//!
//! What is left over - a patch for a tool call that was never opened, an
//! update variant this fold does not model - is logged through [`FoldError`]
@@ -63,6 +65,8 @@ mod content;
mod control;
/// ACP-to-vocabulary conversions shared by the handlers.
mod convert;
+/// Questions the agent asks the user, their answers, and their completion.
+mod elicitation;
/// Permission requests and their answers.
mod permission;
/// The agent's plan (todo list).
diff --git a/crates/agent_fold/src/domain/fold/content.rs b/crates/agent_fold/src/domain/fold/content.rs
index fff9bc6ae5..ddb12a9cf5 100644
--- a/crates/agent_fold/src/domain/fold/content.rs
+++ b/crates/agent_fold/src/domain/fold/content.rs
@@ -17,6 +17,16 @@ impl FoldState {
Some(part)
}
+ /// [`Self::part_at_mut`], read-only.
+ pub(super) fn part_at(&self, at: &ToolPath) -> Option<&MessagePart> {
+ let (first, rest) = at.path.split_first()?;
+ let mut part = self.messages.get(at.message)?.parts.get(*first)?;
+ for &index in rest {
+ part = part.children().get(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 text.is_empty() {
diff --git a/crates/agent_fold/src/domain/fold/elicitation.rs b/crates/agent_fold/src/domain/fold/elicitation.rs
new file mode 100644
index 0000000000..a602882321
--- /dev/null
+++ b/crates/agent_fold/src/domain/fold/elicitation.rs
@@ -0,0 +1,815 @@
+//! Folding `elicitation/create`, its answer, and `elicitation/complete`.
+//!
+//! A question is a part in the transcript (history) and, while it is open,
+//! the one [`PendingElicitation`] on the metadata (the live pointer a surface
+//! answers from). The two diverge on purpose: the part stays `Pending` forever
+//! on a session that died mid-question, while the metadata slot clears the
+//! moment the turn that asked ends - the agent has moved on and nothing
+//! should still offer the form.
+//!
+//! Only ACP is read here. What a harness adds to it - a select's free-text
+//! "Other" companion, the answer it reports afterwards - comes through the
+//! [`HarnessReader`] like every other harness convention.
+
+use std::collections::{BTreeMap, HashSet};
+
+use agent_client_protocol::RawJsonRpcParams;
+use agent_client_protocol::schema::v1::{
+ CompleteElicitationNotification, CreateElicitationRequest, CreateElicitationResponse,
+ ElicitationAction, ElicitationContentValue, ElicitationMode,
+ ElicitationPropertySchema as AcpPropertySchema, ElicitationSchema as AcpSchema,
+ ElicitationScope, EnumOption, MultiSelectItems, RequestId,
+};
+use serde_json::Value;
+
+use super::convert::{deserialize_params, param};
+use super::state::{Changed, FoldState, ToolPath};
+use crate::domain::error::FoldError;
+use crate::domain::harness::{HarnessReader, ToolFrame};
+use crate::domain::model::{
+ AnsweredChoice, AnsweredField, AnsweredValue, ElicitationOption, ElicitationOutcome,
+ ElicitationProperty, ElicitationPropertySchema, ElicitationRequest, ElicitationRequestId,
+ ElicitationSchema, MessagePart, PendingElicitation, ToolUseId,
+};
+
+impl FoldState {
+ /// Handle an `elicitation/create`: add (or absorb into) a part, record
+ /// the request id so its response can be matched, and point the metadata
+ /// at it when nothing else is pending.
+ ///
+ /// Returns the message change and whether the metadata moved; `None` when
+ /// the frame derived nothing (a null id, params that do not parse, or a
+ /// question with no message to attach to).
+ pub(super) fn request_elicitation(
+ &mut self,
+ request_id: &RequestId,
+ params: Option<&RawJsonRpcParams>,
+ ) -> Option<(Changed, bool)> {
+ let Some(id) = ElicitationRequestId::from_request_id(request_id) else {
+ self.warn(FoldError::Unknown {
+ kind: "elicitation/create with a null id".to_owned(),
+ });
+ return None;
+ };
+ let Some(request) = deserialize_params::<CreateElicitationRequest>(params) else {
+ self.warn(FoldError::Unknown {
+ kind: "elicitation/create".to_owned(),
+ });
+ return None;
+ };
+
+ let (tool_call, elicitation_request) = decode_request(self.reader(), &request, params);
+ let message_text = request.message.clone();
+
+ // Absorb the tool call the question was asked for, when this fold has
+ // it open: the part takes the tool's place so the question renders
+ // once, in the position the tool row already had - nested under a
+ // subagent if that is where the call sat - and later updates for that
+ // tool id land on the question (see `patch_tool_call`).
+ let absorbed = tool_call
+ .as_ref()
+ .and_then(|tool| self.tool_positions.get(tool).cloned())
+ .filter(|at| matches!(self.part_at_mut(at), Some(MessagePart::ToolUse { .. })));
+
+ // A form asked on behalf of one of Macro's user tools is that tool's
+ // review: the call is what is being decided, and a client with the
+ // tool's composer renders the draft rather than the form.
+ let elicitation_request = match elicitation_request {
+ ElicitationRequest::Form { schema } => {
+ let absorbed_user_tool = absorbed.as_ref().and_then(|at| self.user_tool_at(at));
+ match absorbed_user_tool.or_else(|| user_tool_from_meta(&request)) {
+ Some((tool, draft)) => ElicitationRequest::UserTool {
+ tool,
+ draft: Box::new(draft),
+ schema: Box::new(schema),
+ },
+ None => ElicitationRequest::Form { schema },
+ }
+ }
+ other => other,
+ };
+
+ let part = MessagePart::Elicitation {
+ request_id: id.clone(),
+ tool_call: tool_call.clone(),
+ message: message_text.clone(),
+ request: elicitation_request.clone(),
+ outcome: ElicitationOutcome::Pending,
+ reported: None,
+ tool_outcome: None,
+ };
+ let (changed, at) = match absorbed {
+ Some(at) => {
+ *self.part_at_mut(&at)? = part;
+ (Changed::updated(at.message), at)
+ }
+ None => {
+ let (changed, position) = self.push_agent_part(part)?;
+ let at = ToolPath {
+ message: changed.message,
+ path: vec![position],
+ };
+ (changed, at)
+ }
+ };
+
+ self.pending_elicitations
+ .insert(request_id.clone(), at.clone());
+
+ // One question at a time is a Macro rule the session machine enforces
+ // by refusing a second create; the fold mirrors it by never letting a
+ // second one take the slot, so a refused request still gets its part
+ // (and its `Errored` outcome) without ever being offered to the user.
+ let metadata_changed = if self.metadata.pending_elicitation.is_none() {
+ self.metadata.pending_elicitation = Some(PendingElicitation {
+ request_id: id,
+ turn: self.messages[at.message].id.0,
+ tool_call,
+ message: message_text,
+ request: elicitation_request,
+ });
+ true
+ } else {
+ false
+ };
+
+ Some((changed, metadata_changed))
+ }
+
+ /// Handle the response to an `elicitation/create`. `None` when the id
+ /// matches no outstanding elicitation, so the caller can try the
+ /// permission map instead.
+ pub(super) fn resolve_elicitation(
+ &mut self,
+ response_id: &RequestId,
+ value: Option<&Value>,
+ error: Option<&str>,
+ ) -> Option<(Changed, bool)> {
+ let at = self.pending_elicitations.remove(response_id)?;
+
+ // The schema the question was asked with: what the submitted content
+ // is shaped against, so a reader never re-correlates the two.
+ let schema = match self.part_at(&at) {
+ Some(MessagePart::Elicitation { request, .. }) => schema_of(request).cloned(),
+ _ => None,
+ };
+
+ let outcome = match (value, error) {
+ (_, Some(message)) => ElicitationOutcome::Errored {
+ message: message.to_owned(),
+ },
+ (None, None) => ElicitationOutcome::Errored {
+ message: String::new(),
+ },
+ (Some(value), None) => {
+ match serde_json::from_value::<CreateElicitationResponse>(value.clone()) {
+ Ok(response) => match response.action {
+ ElicitationAction::Accept(accept) => ElicitationOutcome::Accepted {
+ answers: accept
+ .content
+ .map(|content| shape_answers(schema.as_ref(), &content))
+ .unwrap_or_default(),
+ },
+ ElicitationAction::Decline => ElicitationOutcome::Declined,
+ ElicitationAction::Cancel => ElicitationOutcome::Cancelled,
+ // `#[non_exhaustive]`, and `Other` is untagged.
+ _ => ElicitationOutcome::Unrecognized,
+ },
+ Err(_) => ElicitationOutcome::Unrecognized,
+ }
+ }
+ };
+ let accepted = matches!(outcome, ElicitationOutcome::Accepted { .. });
+
+ let Some(MessagePart::Elicitation {
+ outcome: existing,
+ request,
+ request_id,
+ ..
+ }) = self.part_at_mut(&at)
+ else {
+ return None;
+ };
+ *existing = outcome;
+ let answered_id = request_id.clone();
+
+ // A URL consent may still be completed by the agent later.
+ if accepted && let ElicitationRequest::Url { elicitation_id, .. } = request {
+ let elicitation_id = elicitation_id.clone();
+ self.completable_elicitations
+ .insert(elicitation_id, at.clone());
+ }
+
+ let metadata_changed =
+ self.clear_pending_elicitation_if(|pending| pending.request_id == answered_id);
+
+ Some((Changed::updated(at.message), metadata_changed))
+ }
+
+ /// Handle an `elicitation/complete`: a URL interaction the user accepted
+ /// has finished. Unknown and already-completed ids are ignored, as the
+ /// protocol requires.
+ pub(super) fn complete_elicitation(
+ &mut self,
+ params: Option<&RawJsonRpcParams>,
+ ) -> Option<Changed> {
+ let notification = deserialize_params::<CompleteElicitationNotification>(params)?;
+ let at = self
+ .completable_elicitations
+ .remove(notification.elicitation_id.0.as_ref())?;
+ let Some(MessagePart::Elicitation { outcome, .. }) = self.part_at_mut(&at) else {
+ return None;
+ };
+ if !matches!(outcome, ElicitationOutcome::Accepted { .. }) {
+ return None;
+ }
+ *outcome = ElicitationOutcome::Completed;
+ Some(Changed::updated(at.message))
+ }
+
+ /// A `tool_call_update` for a tool id whose part is now an elicitation:
+ /// the harness telling us what it made of the answer, or - for a user
+ /// tool's review - the tool reporting how it ended once the user
+ /// answered. Returns `None` when the update carries nothing this fold
+ /// reads.
+ pub(super) fn patch_absorbed_elicitation(
+ &mut self,
+ at: &ToolPath,
+ frame: &ToolFrame<'_>,
+ ) -> Option<Changed> {
+ let reader = self.reader();
+ let answer = reader.reported_elicitation_answer(frame);
+ let Some(MessagePart::Elicitation {
+ request,
+ reported,
+ tool_outcome,
+ ..
+ }) = self.part_at_mut(at)
+ else {
+ return None;
+ };
+ let mut changed = false;
+ if let Some(answer) = answer.as_ref().and_then(shape_reported) {
+ *reported = Some(answer);
+ changed = true;
+ }
+ if let (ElicitationRequest::UserTool { tool, .. }, Some(raw)) =
+ (&*request, frame.raw_output)
+ {
+ *tool_outcome = Some(crate::domain::harness::user_tool_outcome(reader, tool, raw));
+ changed = true;
+ }
+ changed.then(|| Changed::updated(at.message))
+ }
+
+ /// A `tool_call` for an id a pending question already names: the question
+ /// asked on the call's behalf arrived first. The question keeps its row
+ /// and becomes the call's position, so the call's later updates land on
+ /// it, and a user tool's draft fills from the call's input when the
+ /// question came without one. `None` when no question names the call.
+ pub(super) fn absorb_late_tool_call(
+ &mut self,
+ id: &ToolUseId,
+ frame: &ToolFrame<'_>,
+ ) -> Option<Changed> {
+ if self.tool_positions.contains_key(id) {
+ return None;
+ }
+ let at = self
+ .pending_elicitations
+ .values()
+ .find(|at| {
+ matches!(
+ self.part_at(at),
+ Some(MessagePart::Elicitation { tool_call: Some(named), .. }) if named == id
+ )
+ })
+ .cloned()?;
+ if let Some(MessagePart::Elicitation {
+ request: ElicitationRequest::UserTool { draft, .. },
+ ..
+ }) = self.part_at_mut(&at)
+ && draft.is_null()
+ && let Some(input) = frame.raw_input
+ {
+ **draft = input.clone();
+ }
+ self.tool_positions.insert(id.clone(), at.clone());
+ Some(Changed::updated(at.message))
+ }
+
+ /// The Macro user tool at `at`, with its draft, when the part there is a
+ /// tool call this fold classified as one.
+ fn user_tool_at(&mut self, at: &ToolPath) -> Option<(String, Value)> {
+ match self.part_at_mut(at) {
+ Some(MessagePart::ToolUse {
+ name,
+ detail: crate::domain::model::ToolDetail::UserTool { input, .. },
+ ..
+ }) => Some((name.display().to_owned(), input.clone())),
+ _ => None,
+ }
+ }
+
+ /// Drop the metadata's pending elicitation when `matches` says so.
+ /// Returns whether the metadata moved.
+ pub(super) fn clear_pending_elicitation_if(
+ &mut self,
+ matches: impl FnOnce(&PendingElicitation) -> bool,
+ ) -> bool {
+ match &self.metadata.pending_elicitation {
+ Some(pending) if matches(pending) => {
+ self.metadata.pending_elicitation = None;
+ true
+ }
+ _ => false,
+ }
+ }
+
+ /// After a prompt response: if no turn is open any more, the agent has
+ /// moved past whatever it asked, and nothing should still offer the form.
+ /// The part keeps its `Pending` outcome; only the live pointer clears.
+ pub(super) fn turn_ended_clears_elicitation(&mut self) -> bool {
+ if self.turn.is_some() {
+ return false;
+ }
+ self.clear_pending_elicitation_if(|_| true)
+ }
+
+ /// Forget everything about outstanding elicitations: the connection that
+ /// asked is gone and its request ids with it.
+ pub(super) fn forget_elicitations(&mut self) -> bool {
+ self.pending_elicitations.clear();
+ self.completable_elicitations.clear();
+ self.clear_pending_elicitation_if(|_| true)
+ }
+}
+
+/// The tool call (if any) and the renderable request, decoded from ACP's
+/// typed request plus the raw params for what the typed form loses.
+fn decode_request(
+ reader: &dyn HarnessReader,
+ request: &CreateElicitationRequest,
+ params: Option<&RawJsonRpcParams>,
+) -> (Option<ToolUseId>, ElicitationRequest) {
+ let raw_schema = param(params, "requestedSchema");
+ match &request.mode {
+ ElicitationMode::Form(form) => (
+ scope_tool_call(&form.scope),
+ ElicitationRequest::Form {
+ schema: collapse_custom_answers(
+ reader,
+ decode_schema(&form.requested_schema, raw_schema),
+ raw_schema,
+ ),
+ },
+ ),
+ ElicitationMode::Url(url) => (
+ scope_tool_call(&url.scope),
+ ElicitationRequest::Url {
+ elicitation_id: url.elicitation_id.0.to_string(),
+ url: url.url.clone(),
+ },
+ ),
+ // `Other`, or a mode ACP adds later. The raw params are the payload.
+ _ => {
+ let raw = match params {
+ Some(RawJsonRpcParams::Object(map)) => Value::Object(map.clone()),
+ _ => Value::Null,
+ };
+ let mode = raw
+ .get("mode")
+ .and_then(Value::as_str)
+ .unwrap_or("<missing>")
+ .to_owned();
+ let tool_call = raw
+ .get("toolCallId")
+ .and_then(Value::as_str)
+ .map(|id| ToolUseId(id.to_owned()));
+ (tool_call, ElicitationRequest::Unrecognized { mode, raw })
+ }
+ }
+}
+
+/// The user tool a request names under `_meta.macro.userTool`, with the
+/// draft it carries there - how Macro's own agent labels a review, so the
+/// fold reads it even when the call it is scoped to is not open here. The
+/// name is required; the draft defaults to nothing.
+fn user_tool_from_meta(request: &CreateElicitationRequest) -> Option<(String, Value)> {
+ let user_tool = request
+ .meta
+ .as_ref()?
+ .get(crate::domain::harness::macro_inmem::NAMESPACE)?
+ .get("userTool")?;
+ let name = user_tool.get("name")?.as_str()?.to_owned();
+ let draft = user_tool.get("draft").cloned().unwrap_or(Value::Null);
+ Some((name, draft))
+}
+
+fn scope_tool_call(scope: &ElicitationScope) -> Option<ToolUseId> {
+ match scope {
+ ElicitationScope::Session(scope) => scope
+ .tool_call_id
+ .as_ref()
+ .map(|id| ToolUseId(id.0.to_string())),
+ _ => None,
+ }
+}
+
+/// Mirror ACP's schema, keeping the agent's property order.
+///
+/// The SDK decodes `properties` into a `BTreeMap`, which sorts keys; the raw
+/// object (insertion-ordered - `serde_json/preserve_order` is on workspace
+/// wide) says what order the agent actually declared. Keys the raw object
+/// lacks, or that fail to decode, are skipped: a partially typed schema is
+/// still a form.
+fn decode_schema(schema: &AcpSchema, raw: Option<&Value>) -> ElicitationSchema {
+ let raw_properties = raw
+ .and_then(|raw| raw.get("properties"))
+ .and_then(Value::as_object);
+ let order: Vec<&str> = match raw_properties {
+ Some(map) => map.keys().map(String::as_str).collect(),
+ None => schema.properties.keys().map(String::as_str).collect(),
+ };
+
+ let properties = order
+ .into_iter()
+ .filter_map(|name| {
+ let typed = schema.properties.get(name)?;
+ let raw = raw_properties.and_then(|map| map.get(name));
+ Some(decode_property(name, typed, raw))
+ })
+ .collect();
+
+ ElicitationSchema {
+ title: schema.title.clone(),
+ description: schema.description.clone(),
+ properties,
+ required: schema.required.clone().unwrap_or_default(),
+ }
+}
+
+/// Collapse each select + free-text "Other" companion pair the harness
+/// declared into one property whose `custom_field` names the companion key.
+///
+/// Both single (`String` with options) and multi (`MultiSelect`) selects take
+/// a companion. The pair arrives with no `required` from Claude Code (Codex
+/// requires the select only when it has no companion), but an empty
+/// submission is useless to the agent, so the collapsed field is marked
+/// required: the user must pick or type.
+fn collapse_custom_answers(
+ reader: &dyn HarnessReader,
+ mut schema: ElicitationSchema,
+ raw: Option<&Value>,
+) -> ElicitationSchema {
+ let raw_properties = raw
+ .and_then(|raw| raw.get("properties"))
+ .and_then(Value::as_object);
+ let companions: Vec<(String, String)> = schema
+ .properties
+ .iter()
+ .filter(|property| {
+ // Only a free-text string can be a companion; a select never is.
+ matches!(
+ &property.schema,
+ ElicitationPropertySchema::String { options, .. } if options.is_empty()
+ )
+ })
+ .filter_map(|property| {
+ let raw_property = raw_properties?.get(&property.name)?;
+ let target = reader.custom_answer_for(&property.name, raw_property)?;
+ Some((property.name.clone(), target))
+ })
+ .collect();
+
+ for (companion, target) in &companions {
+ let Some(select) = schema
+ .properties
+ .iter_mut()
+ .find(|property| property.name == *target)
+ else {
+ continue;
+ };
+ let attached = match &mut select.schema {
+ ElicitationPropertySchema::String {
+ options,
+ custom_field,
+ ..
+ } if !options.is_empty() => {
+ *custom_field = Some(companion.clone());
+ true
+ }
+ ElicitationPropertySchema::MultiSelect { custom_field, .. } => {
+ *custom_field = Some(companion.clone());
+ true
+ }
+ _ => false,
+ };
+ if !attached {
+ continue;
+ }
+ schema
+ .properties
+ .retain(|property| property.name != *companion);
+ if !schema.required.iter().any(|name| name == target) {
+ schema.required.push(target.clone());
+ }
+ schema.required.retain(|name| name != companion);
+ }
+ schema
+}
+
+fn decode_property(
+ name: &str,
+ typed: &AcpPropertySchema,
+ raw: Option<&Value>,
+) -> ElicitationProperty {
+ let (title, description, schema) = match typed {
+ AcpPropertySchema::String(string) => (
+ string.title.clone(),
+ string.description.clone(),
+ ElicitationPropertySchema::String {
+ min_length: string.min_length,
+ max_length: string.max_length,
+ pattern: string.pattern.clone(),
+ format: string
+ .format
+ .and_then(|format| serde_json::to_value(format).ok())
+ .and_then(|format| format.as_str().map(str::to_owned)),
+ default: string.default.clone(),
+ options: match (&string.one_of, &string.enum_values) {
+ (Some(titled), _) => titled.iter().map(titled_option).collect(),
+ (None, Some(values)) => {
+ values.iter().map(|value| untitled_option(value)).collect()
+ }
+ (None, None) => Vec::new(),
+ },
+ custom_field: None,
+ },
+ ),
+ AcpPropertySchema::Number(number) => (
+ number.title.clone(),
+ number.description.clone(),
+ ElicitationPropertySchema::Number {
+ minimum: number.minimum,
+ maximum: number.maximum,
+ default: number.default,
+ },
+ ),
+ AcpPropertySchema::Integer(integer) => (
+ integer.title.clone(),
+ integer.description.clone(),
+ ElicitationPropertySchema::Integer {
+ minimum: integer.minimum,
+ maximum: integer.maximum,
+ default: integer.default,
+ },
+ ),
+ AcpPropertySchema::Boolean(boolean) => (
+ boolean.title.clone(),
+ boolean.description.clone(),
+ ElicitationPropertySchema::Boolean {
+ default: boolean.default,
+ },
+ ),
+ AcpPropertySchema::Array(multi) => (
+ multi.title.clone(),
+ multi.description.clone(),
+ ElicitationPropertySchema::MultiSelect {
+ min_items: multi.min_items,
+ max_items: multi.max_items,
+ options: match &multi.items {
+ MultiSelectItems::String(items) => items
+ .values
+ .iter()
+ .map(|value| untitled_option(value))
+ .collect(),
+ MultiSelectItems::Titled(items) => {
+ items.options.iter().map(titled_option).collect()
+ }
+ // `Other`, or an item type ACP adds later: no choices this
+ // fold can offer.
+ _ => Vec::new(),
+ },
+ default: multi.default.clone().unwrap_or_default(),
+ custom_field: None,
+ },
+ ),
+ // `Other`, or a property type ACP adds later.
+ _ => {
+ let raw = raw.cloned().unwrap_or(Value::Null);
+ let type_name = raw
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("<missing>")
+ .to_owned();
+ (
+ raw.get("title").and_then(Value::as_str).map(str::to_owned),
+ raw.get("description")
+ .and_then(Value::as_str)
+ .map(str::to_owned),
+ ElicitationPropertySchema::Unrecognized { type_name, raw },
+ )
+ }
+ };
+ ElicitationProperty {
+ name: name.to_owned(),
+ title,
+ description,
+ schema,
+ }
+}
+
+fn titled_option(option: &EnumOption) -> ElicitationOption {
+ ElicitationOption {
+ value: option.value.clone(),
+ title: Some(option.title.clone()),
+ description: option.description.clone(),
+ }
+}
+
+fn untitled_option(value: &str) -> ElicitationOption {
+ ElicitationOption {
+ value: value.to_owned(),
+ title: None,
+ description: None,
+ }
+}
+
+/// The form schema a request was asked with, when it has one.
+fn schema_of(request: &ElicitationRequest) -> Option<&ElicitationSchema> {
+ match request {
+ ElicitationRequest::Form { schema } => Some(schema),
+ ElicitationRequest::UserTool { schema, .. } => Some(schema),
+ ElicitationRequest::Url { .. } | ElicitationRequest::Unrecognized { .. } => None,
+ }
+}
+
+/// Shape submitted content against the schema that asked for it.
+///
+/// The schema's properties come first, in the order the agent declared them,
+/// so a transcript reads in the order the form was filled; then any key no
+/// property claimed, labelled by the key it arrived under. Properties the
+/// content did not answer are skipped rather than rendered empty.
+///
+/// The "Other" idiom is resolved here: a non-blank value under a property's
+/// `custom_field` wins over a choice under the property's own name, and
+/// claims both keys. Real harnesses send both (see the
+/// `elicitation_claude_single_select` fixture, where `question_0` is `"Red"`
+/// and `question_0_custom` is `"blue"`, and Claude Code itself reports the
+/// answer as `"blue"`).
+fn shape_answers(
+ schema: Option<&ElicitationSchema>,
+ content: &BTreeMap<String, ElicitationContentValue>,
+) -> Vec<AnsweredField> {
+ let mut answers = Vec::new();
+ let mut claimed: HashSet<&str> = HashSet::new();
+
+ for property in schema
+ .map(|schema| schema.properties.as_slice())
+ .unwrap_or_default()
+ {
+ let label = property
+ .title
+ .clone()
+ .unwrap_or_else(|| property.name.clone());
+ claimed.insert(property.name.as_str());
+
+ if let Some(key) = custom_field_of(&property.schema) {
+ claimed.insert(key);
+ if let Some(ElicitationContentValue::String(text)) = content.get(key)
+ && !text.trim().is_empty()
+ {
+ answers.push(AnsweredField {
+ name: property.name.clone(),
+ label,
+ value: AnsweredValue::Custom { text: text.clone() },
+ });
+ continue;
+ }
+ }
+
+ let Some(value) = content.get(&property.name) else {
+ continue;
+ };
+ answers.push(AnsweredField {
+ name: property.name.clone(),
+ label,
+ value: answered_value(Some(&property.schema), value),
+ });
+ }
+
+ for (key, value) in content {
+ if claimed.contains(key.as_str()) {
+ continue;
+ }
+ answers.push(AnsweredField {
+ name: key.clone(),
+ label: key.clone(),
+ value: answered_value(None, value),
+ });
+ }
+
+ answers
+}
+
+/// The key a property's free-text escape arrives under, when it has one.
+fn custom_field_of(schema: &ElicitationPropertySchema) -> Option<&str> {
+ match schema {
+ ElicitationPropertySchema::String { custom_field, .. }
+ | ElicitationPropertySchema::MultiSelect { custom_field, .. } => custom_field.as_deref(),
+ _ => None,
+ }
+}
+
+/// One value, read through the property that asked for it when there is one:
+/// that is what resolves a string to the option it names, and its title.
+fn answered_value(
+ schema: Option<&ElicitationPropertySchema>,
+ value: &ElicitationContentValue,
+) -> AnsweredValue {
+ let options = match schema {
+ Some(
+ ElicitationPropertySchema::String { options, .. }
+ | ElicitationPropertySchema::MultiSelect { options, .. },
+ ) => options.as_slice(),
+ _ => &[],
+ };
+ match value {
+ ElicitationContentValue::String(text) if !options.is_empty() => AnsweredValue::Choice {
+ choice: choice_for(options, text),
+ },
+ ElicitationContentValue::String(text) => AnsweredValue::Text { text: text.clone() },
+ ElicitationContentValue::Integer(number) => AnsweredValue::Number {
+ text: number.to_string(),
+ },
+ ElicitationContentValue::Number(number) => AnsweredValue::Number {
+ text: number.to_string(),
+ },
+ ElicitationContentValue::Boolean(checked) => AnsweredValue::Boolean { checked: *checked },
+ ElicitationContentValue::StringArray(values) => AnsweredValue::Choices {
+ choices: values
+ .iter()
+ .map(|value| choice_for(options, value))
+ .collect(),
+ },
+ // `#[non_exhaustive]`: a value kind ACP adds later.
+ _ => AnsweredValue::Unrecognized {
+ raw: serde_json::to_value(value).unwrap_or_default(),
+ },
+ }
+}
+
+/// A chosen value with the title it was offered under, or untitled when no
+/// option declared it.
+fn choice_for(options: &[ElicitationOption], value: &str) -> AnsweredChoice {
+ AnsweredChoice {
+ value: value.to_owned(),
+ title: options
+ .iter()
+ .find(|option| option.value == value)
+ .and_then(|option| option.title.clone()),
+ }
+}
+
+/// Shape a harness's reported answer, which is keyed by question prose rather
+/// than by schema property - so every entry is its own label, and the values
+/// are read as plain JSON rather than through ACP's typed content.
+fn shape_reported(reported: &Value) -> Option<Vec<AnsweredField>> {
+ let object = reported.as_object()?;
+ Some(
+ object
+ .iter()
+ .map(|(key, value)| AnsweredField {
+ name: key.clone(),
+ label: key.clone(),
+ value: reported_value(value),
+ })
+ .collect(),
+ )
+}
+
+/// A reported value, narrowed to the shared vocabulary where it fits.
+fn reported_value(value: &Value) -> AnsweredValue {
+ match value {
+ Value::String(text) => AnsweredValue::Text { text: text.clone() },
+ Value::Bool(checked) => AnsweredValue::Boolean { checked: *checked },
+ Value::Number(number) => AnsweredValue::Number {
+ text: number.to_string(),
+ },
+ Value::Array(items) => items
+ .iter()
+ .map(|item| item.as_str().map(str::to_owned))
+ .collect::<Option<Vec<_>>>()
+ .map_or_else(
+ || AnsweredValue::Unrecognized { raw: value.clone() },
+ |values| AnsweredValue::Choices {
+ choices: values
+ .into_iter()
+ .map(|value| AnsweredChoice { value, title: None })
+ .collect(),
+ },
+ ),
+ Value::Null | Value::Object(_) => AnsweredValue::Unrecognized { raw: value.clone() },
+ }
+}
diff --git a/crates/agent_fold/src/domain/fold/state.rs b/crates/agent_fold/src/domain/fold/state.rs
index 3d6ee5d700..260030d386 100644
--- a/crates/agent_fold/src/domain/fold/state.rs
+++ b/crates/agent_fold/src/domain/fold/state.rs
@@ -7,8 +7,8 @@ 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,
+ CompleteElicitationNotification, CreateElicitationRequest, PromptRequest, RequestId,
+ RequestPermissionRequest, Response, SessionNotification, SessionUpdate,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage, RawJsonRpcParams};
use agent_runtime_protocol::domain::action::AgentAction;
@@ -71,6 +71,16 @@ impl StepChange {
}
}
+impl FoldState {
+ /// The changes for a handler that touched one message and reported
+ /// whether the metadata moved, message first.
+ fn message_and_metadata(changed: Changed, metadata: bool) -> Vec<StepChange> {
+ let mut changes = vec![StepChange::Message(changed)];
+ changes.extend(StepChange::metadata(metadata));
+ changes
+ }
+}
+
/// The fold's state, advanced one log entry at a time by [`State::step`] and
/// owned by [`FoldMachineImpl`].
#[derive(Debug, Default)]
@@ -97,6 +107,14 @@ pub(super) struct FoldState {
pub(super) turns_opened: u32,
/// Outstanding permission requests, by the id of the request that asked.
pub(super) pending_permissions: HashMap<RequestId, ToolUseId>,
+ /// Outstanding `elicitation/create`s, by the id of the request that
+ /// asked: where the question's part sits, so its answer can find it.
+ /// Session-wide like [`Self::tool_positions`], since the part may have
+ /// taken a tool call's place under a subagent.
+ pub(super) pending_elicitations: HashMap<RequestId, ToolPath>,
+ /// Accepted URL elicitations the agent may still report complete, by the
+ /// agent's `elicitationId`.
+ pub(super) completable_elicitations: HashMap<String, ToolPath>,
/// Session-level state derived so far. Handlers mutate it freely; the
/// machine diffs it against what it last reported.
pub(super) metadata: SessionMetadata,
@@ -210,7 +228,10 @@ impl FoldState {
AgentAction::Stop => {
self.record_control(Control::Stop, None, entry.user_id.clone())
}
- AgentAction::Prompt(_) => None,
+ // `control_from_runtime` never yields these: a prompt
+ // is folded below, and an elicitation answer is a
+ // response frame, correlated by the agent's id.
+ AgentAction::Prompt(_) | AgentAction::RespondElicitation(_) => None,
});
}
StepChange::message(match &acp.0 {
@@ -220,11 +241,27 @@ impl FoldState {
{
self.begin_turn(&request.id, request.params.as_ref(), entry.user_id.clone())
}
- // The user's answer to a permission request.
+ // The user's answer to a question or a permission
+ // request. Each map holds only the ids of its own
+ // requests, so trying the elicitations first is order,
+ // not precedence.
RawJsonRpcMessage::Response(Response::Result { id, result }) => {
+ if let Some((changed, metadata)) =
+ self.resolve_elicitation(id, Some(result), None)
+ {
+ return Self::message_and_metadata(changed, metadata);
+ }
self.resolve_permission(id, Some(result))
}
- RawJsonRpcMessage::Response(Response::Error { id, .. }) => {
+ // An error response is this client refusing a request it
+ // could not hold - a second question, an unknown mode -
+ // or failing to answer a permission.
+ RawJsonRpcMessage::Response(Response::Error { id, error }) => {
+ if let Some((changed, metadata)) =
+ self.resolve_elicitation(id, None, Some(&error.message))
+ {
+ return Self::message_and_metadata(changed, metadata);
+ }
self.resolve_permission(id, None)
}
// Handshake and configuration traffic: nothing to render.
@@ -276,6 +313,21 @@ impl FoldState {
self.request_permission(&request.id, request.params.as_ref()),
)
}
+ // The agent asking the user a question.
+ RawJsonRpcMessage::Request(request)
+ if CreateElicitationRequest::matches_method(&request.method) =>
+ {
+ match self.request_elicitation(&request.id, request.params.as_ref()) {
+ Some((changed, metadata)) => Self::message_and_metadata(changed, metadata),
+ None => Vec::new(),
+ }
+ }
+ // The agent reporting that a URL interaction finished.
+ RawJsonRpcMessage::Notification(notification)
+ if CompleteElicitationNotification::matches_method(&notification.method) =>
+ {
+ StepChange::message(self.complete_elicitation(notification.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
@@ -293,7 +345,9 @@ impl FoldState {
} else if control.is_some() {
StepChange::message(control)
} else {
- StepChange::message(self.end_turn(id, Some(result)))
+ let mut changes = StepChange::message(self.end_turn(id, Some(result)));
+ changes.extend(StepChange::metadata(self.turn_ended_clears_elicitation()));
+ changes
}
}
RawJsonRpcMessage::Response(Response::Error { id, error }) => {
@@ -303,7 +357,9 @@ impl FoldState {
if self.pending_config_requests.remove(id) || control.is_some() {
StepChange::message(control)
} else {
- StepChange::message(self.fail_turn(id, &error.message))
+ let mut changes = StepChange::message(self.fail_turn(id, &error.message));
+ changes.extend(StepChange::metadata(self.turn_ended_clears_elicitation()));
+ changes
}
}
RawJsonRpcMessage::Request(_) | RawJsonRpcMessage::Notification(_) => Vec::new(),
@@ -315,16 +371,18 @@ impl FoldState {
// nothing pending can be answered past one - a stale entry would
// misattribute a new connection's reused id.
Message::ToServer(ToServerMessage::Event { event }) => {
+ let mut changed = false;
if matches!(event, SystemEvent::AcpReady) {
self.pending_initialize = None;
self.pending_config_requests.clear();
self.pending_permissions.clear();
self.pending_controls.clear();
+ changed |= self.forget_elicitations();
}
let status = Some(event.as_str().to_owned());
- let changed = self.metadata.status != status;
- if changed {
+ if self.metadata.status != status {
self.metadata.status = status;
+ changed = true;
}
StepChange::metadata(changed)
}
diff --git a/crates/agent_fold/src/domain/fold/tool_call.rs b/crates/agent_fold/src/domain/fold/tool_call.rs
index c133ba86a9..6fb50d27ea 100644
--- a/crates/agent_fold/src/domain/fold/tool_call.rs
+++ b/crates/agent_fold/src/domain/fold/tool_call.rs
@@ -23,6 +23,16 @@ impl FoldState {
let id = ToolUseId(call.tool_call_id.0.to_string());
let reader = self.reader();
let frame = ToolFrame::of_call(&call);
+
+ // A question already asked on this call's behalf - its
+ // `elicitation/create` is a request the agent sends directly, and can
+ // overtake the `tool_call` notification on the wire - takes the call
+ // in now, the way an open call is absorbed when the question follows
+ // it. Either order shows one row.
+ if let Some(changed) = self.absorb_late_tool_call(&id, &frame) {
+ return Some(changed);
+ }
+
let name = harness::tool_name(reader, &frame);
// Whose shape the call is in is decided here, once; a patch finds the
@@ -92,6 +102,14 @@ impl FoldState {
return None;
};
let message = at.message;
+
+ // A call a question absorbed (see `request_elicitation`) is patched
+ // as the question: the only thing a later update can add is the
+ // harness's own reading of the answer.
+ if matches!(self.part_at_mut(&at), Some(MessagePart::Elicitation { .. })) {
+ return self.patch_absorbed_elicitation(&at, &ToolFrame::of_update(&update));
+ }
+
let Some(MessagePart::ToolUse {
name,
status,
diff --git a/crates/agent_fold/src/domain/harness.rs b/crates/agent_fold/src/domain/harness.rs
index 83da9d8ad3..da9d90d6d5 100644
--- a/crates/agent_fold/src/domain/harness.rs
+++ b/crates/agent_fold/src/domain/harness.rs
@@ -19,6 +19,11 @@
//! 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.
+//! - How an ask-the-user question is spelled in an `elicitation/create`
+//! form. ACP fixes the wire shape; the harness decides that a select comes
+//! with a free-text "Other" companion property, marks the companion in its
+//! `_meta`, and later reports which of the two it took on the asking
+//! tool's frame.
//!
//! So each harness gets a [`HarnessReader`] in its own file, and every reader
//! method takes the whole frame - a [`ToolFrame`] - rather than the fields
@@ -283,6 +288,32 @@ pub trait HarnessReader: Sync {
let _ = frame;
Vec::new()
}
+
+ /// The select that `property` - one property of an `elicitation/create`
+ /// form schema, as the wire carried it, declared under `name` - is the
+ /// free-text "Other" companion of, when it is one.
+ ///
+ /// The ask-the-user idiom: the agent offers choices *and* a place to type
+ /// an answer of one's own, as two properties. The fold collapses the pair
+ /// into one field, so a renderer never shows a stray text box under a
+ /// select. The neutral reading is the un-namespaced marker Claude Code
+ /// chose so other bridges could share it,
+ /// `_meta._askUserQuestionCustomAnswer`; a harness with a marker of its
+ /// own, or a bare naming convention for recordings that lost their
+ /// `_meta`, reads that too. `None` means an ordinary property.
+ fn custom_answer_for(&self, name: &str, property: &Value) -> Option<String> {
+ generic::custom_answer_for(name, property)
+ }
+
+ /// The harness's own reading of the answer to a question it asked through
+ /// `elicitation/create`, when a frame for the asking tool call carries
+ /// one - the value it settled on when the user both chose and typed, in
+ /// whatever shape the harness reports it. `None` when the frame says
+ /// nothing about it, which is every harness but Claude Code today.
+ fn reported_elicitation_answer(&self, frame: &ToolFrame<'_>) -> Option<Value> {
+ let _ = frame;
+ None
+ }
}
/// What a subagent was asked, as one frame reports it. Every field is
diff --git a/crates/agent_fold/src/domain/harness/claude_code.rs b/crates/agent_fold/src/domain/harness/claude_code.rs
index e64e6d3151..eca605068a 100644
--- a/crates/agent_fold/src/domain/harness/claude_code.rs
+++ b/crates/agent_fold/src/domain/harness/claude_code.rs
@@ -10,7 +10,14 @@
//! - `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.
+//! count and per-tool statistics. For `AskUserQuestion` it carries
+//! `answers`, the answer the adapter settled on per question.
+//!
+//! `AskUserQuestion` is asked through `elicitation/create` (adapter ≥ 0.64,
+//! gated on the client advertising `elicitation.form`): one form per call,
+//! `toolCallId` naming the tool call, and per question a `question_N` select
+//! plus a `question_N_custom` free-text companion marked with the shared
+//! [`generic::MARKER`]. Custom text wins over the choice when both are sent.
use agent_client_protocol::schema::v1::{ContentBlock, Meta};
use lazy_regex::regex_is_match;
@@ -23,6 +30,9 @@ use crate::domain::model::{SubagentResult, ToolName, ToolStats, ToolUseId};
/// The `_meta` namespace Claude Code writes under.
pub const NAMESPACE: &str = "claudeCode";
+/// What the adapter appends to a question's name for its "Other" companion.
+const CUSTOM_ANSWER_SUFFIX: &str = "_custom";
+
/// Reader for Claude Code's conventions.
pub struct ClaudeCode;
@@ -167,6 +177,17 @@ impl HarnessReader for ClaudeCode {
None => generic::subagent_result(frame),
}
}
+
+ fn custom_answer_for(&self, name: &str, property: &Value) -> Option<String> {
+ generic::custom_answer_for(name, property)
+ .or_else(|| generic::custom_answer_by_suffix(name, property, CUSTOM_ANSWER_SUFFIX))
+ }
+
+ /// `_meta.claudeCode.toolResponse.answers`: an object keyed by question
+ /// text, holding the answer the adapter took for each.
+ fn reported_elicitation_answer(&self, frame: &ToolFrame<'_>) -> Option<Value> {
+ meta_of(frame.meta).tool_response?.get("answers").cloned()
+ }
}
/// The harness's own name for the tool behind a `tool_call`, verbatim.
diff --git a/crates/agent_fold/src/domain/harness/codex.rs b/crates/agent_fold/src/domain/harness/codex.rs
index 6a11a8143d..e6bba5b47b 100644
--- a/crates/agent_fold/src/domain/harness/codex.rs
+++ b/crates/agent_fold/src/domain/harness/codex.rs
@@ -10,6 +10,11 @@
//! on the collaboration tools. `tool: "spawnAgent"` is the delegation; the
//! others (`sendInput`, `wait`, `closeAgent`, …) steer an existing one.
//!
+//! Its `request_user_input` asks through `elicitation/create` (adapter ≥
+//! 1.8): per question an `<id>` select and an `<id>__other` free-text
+//! companion marked `_meta.codex = { questionId, isOtherAnswer: true }`. No
+//! tool call goes over the wire for it, so nothing reports the answer back.
+//!
//! 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
@@ -44,6 +49,18 @@ struct Collaboration {
tool: String,
}
+/// `_meta.codex` on an elicitation form's "Other" property.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OtherAnswerMarker {
+ question_id: String,
+ #[serde(default)]
+ is_other_answer: bool,
+}
+
+/// What the adapter appends to a question's id for its "Other" companion.
+const OTHER_ANSWER_SUFFIX: &str = "__other";
+
/// `_meta` flags codex-acp writes at the top level.
#[derive(Debug, Default, Deserialize)]
struct CodexFlags {
@@ -129,4 +146,15 @@ impl HarnessReader for Codex {
};
(!result.is_empty()).then_some(result)
}
+
+ fn custom_answer_for(&self, name: &str, property: &Value) -> Option<String> {
+ let own_marker = || {
+ let marker: OtherAnswerMarker =
+ serde_json::from_value(property.get("_meta")?.get(NAMESPACE)?.clone()).ok()?;
+ marker.is_other_answer.then_some(marker.question_id)
+ };
+ own_marker()
+ .or_else(|| generic::custom_answer_for(name, property))
+ .or_else(|| generic::custom_answer_by_suffix(name, property, OTHER_ANSWER_SUFFIX))
+ }
}
diff --git a/crates/agent_fold/src/domain/harness/generic.rs b/crates/agent_fold/src/domain/harness/generic.rs
index ac17ff68f7..83bef0a577 100644
--- a/crates/agent_fold/src/domain/harness/generic.rs
+++ b/crates/agent_fold/src/domain/harness/generic.rs
@@ -10,6 +10,9 @@
//! - 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.
+//! - The `_meta._askUserQuestionCustomAnswer` marker on an elicitation
+//! form's free-text "Other" property, which Claude Code left un-namespaced
+//! on purpose so other bridges could write the same one.
use agent_client_protocol::schema::v1::ToolKind;
use serde::Deserialize;
@@ -90,6 +93,50 @@ pub fn subagent_input(frame: &ToolFrame<'_>) -> SubagentInput {
}
}
+/// The shared marker on an elicitation form's "Other" property.
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct CustomAnswerMarker {
+ question_id: String,
+ #[serde(default)]
+ is_custom_answer: bool,
+}
+
+/// The select an elicitation form property is the free-text companion of,
+/// by the shared marker: `_meta._askUserQuestionCustomAnswer = { questionId,
+/// isCustomAnswer: true }` on the property's own schema.
+#[must_use]
+pub fn custom_answer_for(name: &str, property: &Value) -> Option<String> {
+ let _ = name;
+ let marker: CustomAnswerMarker =
+ serde_json::from_value(property.get("_meta")?.get(MARKER)?.clone()).ok()?;
+ marker.is_custom_answer.then_some(marker.question_id)
+}
+
+/// The `_meta` key of the shared companion marker.
+pub const MARKER: &str = "_askUserQuestionCustomAnswer";
+
+/// Whether an elicitation form property looks like a free-text "Other" box
+/// by naming convention alone: a free-text string titled `Other` whose name
+/// is a select's name plus `suffix`. The fallback for a recording that lost
+/// its `_meta` - so a property that still carries one, whatever it says, is
+/// read from that alone. Returns the select's name.
+#[must_use]
+pub fn custom_answer_by_suffix(name: &str, property: &Value, suffix: &str) -> Option<String> {
+ if property.get("_meta").is_some() {
+ return None;
+ }
+ let titled_other = property.get("title").and_then(Value::as_str) == Some("Other");
+ let free_text = property.get("type").and_then(Value::as_str) == Some("string")
+ && property.get("oneOf").is_none()
+ && property.get("enum").is_none();
+ (titled_other && free_text)
+ .then(|| name.strip_suffix(suffix))
+ .flatten()
+ .filter(|target| !target.is_empty())
+ .map(str::to_owned)
+}
+
/// A bare `{ "error": … }` result, how several harnesses report a failed
/// call's output.
#[derive(Deserialize)]
diff --git a/crates/agent_fold/src/domain/model.rs b/crates/agent_fold/src/domain/model.rs
index 36b34a217f..e28a014bee 100644
--- a/crates/agent_fold/src/domain/model.rs
+++ b/crates/agent_fold/src/domain/model.rs
@@ -18,6 +18,8 @@ use non_empty::NonEmpty;
use serde::Serialize;
use specta::Type;
+/// Questions the agent asks the user, and their answers.
+mod elicitation;
/// Per-push change reports.
mod event;
/// Session-level metadata.
@@ -35,6 +37,11 @@ mod tool;
/// Macro user tools.
mod user_tool;
+pub use elicitation::{
+ AnsweredChoice, AnsweredField, AnsweredValue, ElicitationOption, ElicitationOutcome,
+ ElicitationProperty, ElicitationPropertySchema, ElicitationRequest, ElicitationRequestId,
+ ElicitationSchema, PendingElicitation,
+};
pub use event::{FoldEvent, OwnedFoldEvent};
pub use metadata::{AvailableCommand, Harness, ModelOption, SessionMetadata};
pub use part::{Control, ControlOutcome, MessagePart, StopReason};
diff --git a/crates/agent_fold/src/domain/model/elicitation.rs b/crates/agent_fold/src/domain/model/elicitation.rs
new file mode 100644
index 0000000000..fe5a16043a
--- /dev/null
+++ b/crates/agent_fold/src/domain/model/elicitation.rs
@@ -0,0 +1,322 @@
+//! The elicitation vocabulary: what an agent asked the user, and how it
+//! resolved.
+//!
+//! ACP's `elicitation/create` is mirrored here rather than carried raw so the
+//! browser gets a typed union to render forms from. The mirror is lossy where
+//! it should be - unknown modes and unknown property types keep their raw
+//! payload and nothing else - and harness idioms (a select paired with a
+//! free-text "Other" companion, see
+//! [`HarnessReader::custom_answer_for`](crate::domain::harness::HarnessReader::custom_answer_for))
+//! are collapsed before they reach these types, so a renderer sees one field
+//! per question.
+
+pub use agent_runtime_protocol::domain::action::ElicitationRequestId;
+use serde::Serialize;
+use specta::Type;
+
+/// What the agent asked for.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ElicitationRequest {
+ /// Structured data through a form the client renders.
+ Form {
+ /// The restricted schema describing the form.
+ schema: ElicitationSchema,
+ },
+ /// An out-of-band interaction the user consents to open.
+ Url {
+ /// The agent's handle for this interaction; `elicitation/complete`
+ /// names it.
+ #[serde(rename = "elicitationId")]
+ elicitation_id: String,
+ /// Where the user is sent.
+ url: String,
+ },
+ /// A Macro user tool (`SendEmail`, `CreateCalendarEvent`) paused for the
+ /// user's review: the agent drafted the call and asks before it runs.
+ ///
+ /// Recognized from the call the form is scoped to - a tool this fold
+ /// already knows as a user tool - or from `_meta.macro.userTool`, which
+ /// Macro's own agent stamps. The draft is the call's arguments whole,
+ /// so a client with the tool's own composer renders that and answers
+ /// with the whole edited draft; `schema` is the flat form the agent also
+ /// sent, for a client without one.
+ UserTool {
+ /// The tool, by Macro's name.
+ tool: String,
+ /// The call's arguments - the tool's own JSON.
+ #[specta(type = specta_typescript::Unknown)]
+ draft: Box<serde_json::Value>,
+ /// The restricted form describing the draft's flat fields.
+ schema: Box<ElicitationSchema>,
+ },
+ /// A mode this fold does not know. Kept raw so nothing is lost; a
+ /// renderer must not treat it as form or url.
+ Unrecognized {
+ /// The wire mode.
+ mode: String,
+ /// The request params, verbatim.
+ #[specta(type = specta_typescript::Unknown)]
+ raw: serde_json::Value,
+ },
+}
+
+/// ACP's restricted form schema: a flat object of primitive properties.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ElicitationSchema {
+ /// Schema-level title, when the agent gave one.
+ pub title: Option<String>,
+ /// Schema-level description, when the agent gave one.
+ pub description: Option<String>,
+ /// The fields, in the order the agent declared them.
+ pub properties: Vec<ElicitationProperty>,
+ /// Property names the agent requires an answer for.
+ pub required: Vec<String>,
+}
+
+/// One form field.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ElicitationProperty {
+ /// The key the answer is sent back under.
+ pub name: String,
+ /// Label to show, when the agent gave one.
+ pub title: Option<String>,
+ /// Help text, when the agent gave one.
+ pub description: Option<String>,
+ /// The field's type and constraints.
+ pub schema: ElicitationPropertySchema,
+}
+
+/// A field's type and constraints, mirroring ACP's restricted property
+/// schemas.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ElicitationPropertySchema {
+ /// Free text, or a single choice when `options` is non-empty.
+ String {
+ /// Minimum length, when constrained.
+ #[serde(rename = "minLength")]
+ min_length: Option<u32>,
+ /// Maximum length, when constrained.
+ #[serde(rename = "maxLength")]
+ max_length: Option<u32>,
+ /// A regular expression the value must match. Agent-supplied, so a
+ /// renderer must bound its evaluation.
+ pattern: Option<String>,
+ /// ACP's format hint as its wire string (`email`, `uri`, `date`,
+ /// `date-time`, or something this fold does not know).
+ format: Option<String>,
+ /// Pre-filled value.
+ default: Option<String>,
+ /// The choices, when this is a single select. Empty for free text.
+ options: Vec<ElicitationOption>,
+ /// The key a free-text answer is sent under when one is accepted
+ /// alongside `options` - the user picks a choice *or* types their
+ /// own. A harness idiom (Claude Code's and Codex's "Other" field),
+ /// never ACP's own; `None` for a plain select.
+ #[serde(rename = "customField")]
+ custom_field: Option<String>,
+ },
+ /// A floating-point number.
+ Number {
+ /// Lower bound, when constrained.
+ minimum: Option<f64>,
+ /// Upper bound, when constrained.
+ maximum: Option<f64>,
+ /// Pre-filled value.
+ default: Option<f64>,
+ },
+ /// A whole number.
+ Integer {
+ /// Lower bound, when constrained.
+ #[specta(type = Option<f64>)]
+ minimum: Option<i64>,
+ /// Upper bound, when constrained.
+ #[specta(type = Option<f64>)]
+ maximum: Option<i64>,
+ /// Pre-filled value.
+ #[specta(type = Option<f64>)]
+ default: Option<i64>,
+ },
+ /// A yes/no.
+ Boolean {
+ /// Pre-filled value.
+ default: Option<bool>,
+ },
+ /// Several choices from a list.
+ MultiSelect {
+ /// Fewest selections allowed, when constrained.
+ #[serde(rename = "minItems")]
+ #[specta(type = Option<f64>)]
+ min_items: Option<u64>,
+ /// Most selections allowed, when constrained.
+ #[serde(rename = "maxItems")]
+ #[specta(type = Option<f64>)]
+ max_items: Option<u64>,
+ /// The choices.
+ options: Vec<ElicitationOption>,
+ /// Pre-selected values.
+ default: Vec<String>,
+ /// The key a free-text answer is sent under when one is accepted
+ /// instead of the choices. Harness idiom, `None` for a plain
+ /// multi-select. See the `String` variant.
+ #[serde(rename = "customField")]
+ custom_field: Option<String>,
+ },
+ /// A property type this fold does not know. A renderer shows that it
+ /// cannot display the field; decline and cancel still work.
+ Unrecognized {
+ /// The wire `type`.
+ #[serde(rename = "typeName")]
+ type_name: String,
+ /// The property schema, verbatim.
+ #[specta(type = specta_typescript::Unknown)]
+ raw: serde_json::Value,
+ },
+}
+
+/// One choice in a select.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct ElicitationOption {
+ /// The value sent back when chosen.
+ pub value: String,
+ /// Label to show; absent for an untitled `enum`, where the value is the
+ /// label.
+ pub title: Option<String>,
+ /// Help text, when the agent gave one.
+ pub description: Option<String>,
+}
+
+/// One property's answer, resolved against the schema that asked for it.
+///
+/// The correlation happens here so that no client repeats it: an option's
+/// title is looked up where the options live, and the harness "Other" idiom -
+/// a free-text answer arriving under a *different* key than the property it
+/// replaces, sometimes alongside the choice it replaces (see the
+/// `elicitation_claude_single_select` fixture, which carries both) - collapses
+/// to a single [`AnsweredValue::Custom`].
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct AnsweredField {
+ /// The property this answers, or the key it arrived under when no
+ /// property claimed it.
+ pub name: String,
+ /// What to show as the label: the property's title, else its name.
+ pub label: String,
+ /// The answer.
+ pub value: AnsweredValue,
+}
+
+/// An answer's value, in the vocabulary the property declared.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum AnsweredValue {
+ /// Free text.
+ Text {
+ /// The text as submitted.
+ text: String,
+ },
+ /// A number, whole or not, exactly as it was submitted.
+ ///
+ /// Text rather than `f64`: a JSON integer can outrun `f64`'s exact range,
+ /// and `f64` has a `number | null` TypeScript face because a non-finite
+ /// float serializes as null. Nothing computes with an answer - it is
+ /// rendered - so the digits are what matter.
+ Number {
+ /// The number as written.
+ text: String,
+ },
+ /// A yes/no.
+ Boolean {
+ /// Whether it was checked.
+ checked: bool,
+ },
+ /// One of the offered options.
+ Choice {
+ /// The option chosen, with the title it was offered under.
+ choice: AnsweredChoice,
+ },
+ /// Several of the offered options.
+ Choices {
+ /// The options chosen, in the order they were submitted.
+ choices: Vec<AnsweredChoice>,
+ },
+ /// The free-text escape: the user typed their own answer instead of
+ /// picking, and it arrived under the property's `customField`.
+ Custom {
+ /// What they typed.
+ text: String,
+ },
+ /// A value this fold could not read as any of the above - a nested
+ /// object, or an array of something other than strings.
+ Unrecognized {
+ /// The value, verbatim.
+ #[specta(type = specta_typescript::Unknown)]
+ raw: serde_json::Value,
+ },
+}
+
+/// A chosen option, with the title it was offered under when the schema gave
+/// one. `title` is `None` for a value no option declared.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct AnsweredChoice {
+ /// The value submitted.
+ pub value: String,
+ /// The label it was offered under.
+ pub title: Option<String>,
+}
+
+/// How an elicitation has resolved so far.
+///
+/// [`Self::Pending`] is a legitimate final state on a dead session, like an
+/// unanswered permission.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ElicitationOutcome {
+ /// No response has gone out yet.
+ Pending,
+ /// The user submitted the form, or consented to open the URL.
+ Accepted {
+ /// What they answered: one entry per property the schema declared and
+ /// the content answered, in declaration order, then any key no
+ /// property claimed. Empty for a URL consent, which carries no
+ /// content.
+ answers: Vec<AnsweredField>,
+ },
+ /// The user explicitly said no.
+ Declined,
+ /// The user dismissed it, or a stop cancelled it.
+ Cancelled,
+ /// URL only: the agent reported the external interaction finished.
+ Completed,
+ /// The response was a JSON-RPC error - including this client's own
+ /// refusal of a request it could not hold.
+ Errored {
+ /// The error's message, verbatim.
+ message: String,
+ },
+ /// A result arrived that this fold could not read as an ACP action.
+ Unrecognized,
+}
+
+/// The one elicitation the user can answer right now, surfaced on
+/// [`SessionMetadata`](super::SessionMetadata) so a reader need not scan the
+/// transcript for it.
+#[derive(Debug, Clone, PartialEq, Serialize, Type)]
+#[serde(rename_all = "camelCase")]
+pub struct PendingElicitation {
+ /// The agent's request id; what an answer must name.
+ pub request_id: ElicitationRequestId,
+ /// The turn whose agent message holds the matching part.
+ pub turn: u32,
+ /// The tool call it was asked on behalf of, when any.
+ pub tool_call: Option<super::ToolUseId>,
+ /// What the agent is asking, in prose.
+ pub message: String,
+ /// The form or URL.
+ pub request: ElicitationRequest,
+}
diff --git a/crates/agent_fold/src/domain/model/metadata.rs b/crates/agent_fold/src/domain/model/metadata.rs
index edd5d5fe64..a6af4dcf32 100644
--- a/crates/agent_fold/src/domain/model/metadata.rs
+++ b/crates/agent_fold/src/domain/model/metadata.rs
@@ -3,6 +3,8 @@
use serde::Serialize;
use specta::Type;
+use super::elicitation::PendingElicitation;
+
/// Which ACP agent produced a session's log.
///
/// ACP names none of a harness's conventions - which `_meta` keys it writes,
@@ -40,7 +42,9 @@ pub enum Harness {
/// 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)]
+///
+/// `PartialEq` only: a pending form's numeric bounds are `f64`.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionMetadata {
/// The agent that produced the log. See [`Harness`].
@@ -59,6 +63,10 @@ pub struct SessionMetadata {
/// The last system event's wire name (`"acp_ready"`, `"disconnected"`),
/// `None` until the runtime reports one.
pub status: Option<String>,
+ /// The one elicitation the user can answer right now. `None` when
+ /// nothing is pending, when the turn that asked has ended, or when the
+ /// connection that asked is gone - the request id dies with it.
+ pub pending_elicitation: Option<PendingElicitation>,
}
/// One slash command the harness advertises.
diff --git a/crates/agent_fold/src/domain/model/part.rs b/crates/agent_fold/src/domain/model/part.rs
index 7e9c958653..802e7dda2c 100644
--- a/crates/agent_fold/src/domain/model/part.rs
+++ b/crates/agent_fold/src/domain/model/part.rs
@@ -6,9 +6,13 @@ use serde::Serialize;
use specta::Type;
use super::ToolUseId;
+use super::elicitation::{
+ AnsweredField, ElicitationOutcome, ElicitationRequest, ElicitationRequestId,
+};
use super::permission::{PermissionOption, PermissionOutcome};
use super::plan::PlanEntry;
use super::tool::{ToolDetail, ToolName, ToolStatus};
+use super::user_tool::UserToolOutcome;
/// A unit of renderable content.
#[derive(Debug, Clone, PartialEq, Serialize, Type)]
@@ -57,6 +61,43 @@ pub enum MessagePart {
/// The tasks, in the order the agent listed them.
entries: Vec<PlanEntry>,
},
+ /// The agent asking the user a question.
+ ///
+ /// When the question was asked on behalf of a tool call this fold had
+ /// already opened (Claude Code's `AskUserQuestion`), this part *replaces*
+ /// that tool's part in place: the question is the call, and rendering
+ /// both would show one thing twice.
+ Elicitation {
+ /// The agent's `elicitation/create` request id - what an answer must
+ /// echo.
+ #[serde(rename = "requestId")]
+ request_id: ElicitationRequestId,
+ /// The tool call the question belongs to, when the agent said.
+ #[serde(rename = "toolCall")]
+ tool_call: Option<ToolUseId>,
+ /// What the agent is asking, in prose.
+ message: String,
+ /// The form or URL.
+ request: ElicitationRequest,
+ /// How it has resolved so far.
+ outcome: ElicitationOutcome,
+ /// The harness's own reading of the answer, when it reported one
+ /// after the response went back (Claude Code echoes the chosen
+ /// option through its tool result). Absent otherwise.
+ ///
+ /// Shaped like [`ElicitationOutcome::Accepted`]'s answers so a reader
+ /// renders one vocabulary either way, though a harness keys these by
+ /// question prose rather than by property, so each `name` is that
+ /// prose rather than a schema property.
+ reported: Option<Vec<AnsweredField>>,
+ /// For a user tool's review ([`ElicitationRequest::UserTool`]): how
+ /// the tool itself ended once the user answered - run with the
+ /// reviewed draft, rejected, or failed - read from the absorbed
+ /// call's later updates. Absent until the tool reports, and for
+ /// every other kind of question.
+ #[serde(rename = "toolOutcome")]
+ tool_outcome: Option<UserToolOutcome>,
+ },
}
impl MessagePart {
diff --git a/crates/agent_fold/src/domain/test.rs b/crates/agent_fold/src/domain/test.rs
index 4661bc36c1..230269eb93 100644
--- a/crates/agent_fold/src/domain/test.rs
+++ b/crates/agent_fold/src/domain/test.rs
@@ -1,6 +1,7 @@
//! Unit tests for the domain layer, one file per module under test, plus
//! [`util`] for what they share.
+mod elicitation;
mod fold;
mod harness;
mod harness_readers;
diff --git a/crates/agent_fold/src/domain/test/elicitation.rs b/crates/agent_fold/src/domain/test/elicitation.rs
new file mode 100644
index 0000000000..3ecf953345
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/elicitation.rs
@@ -0,0 +1,1080 @@
+//! Elicitation: the agent asking the user a question, and the answer.
+//!
+//! The harness idioms - which property is a select's "Other" companion, what
+//! the harness reported it took - are the readers' business and are pinned
+//! per reader in [`harness_readers`](super::harness_readers). These tests
+//! drive the fold with the harness announced, the way a real log has it, and
+//! check what the collapsed form and the transcript look like.
+
+use super::util::{capturing_warnings, parse_log};
+use crate::domain::fold::{FoldMachineImpl, fold};
+use crate::domain::model::{
+ AnsweredChoice, AnsweredField, AnsweredValue, ElicitationOutcome, ElicitationPropertySchema,
+ ElicitationRequest, ElicitationRequestId, FoldEvent, MessagePart, ToolDetail, ToolUseId,
+};
+use crate::domain::ports::FoldMachine;
+use crate::testing::fixtures::ELICITATION_CLAUDE_SINGLE_SELECT;
+
+const PROMPT: &str = r#"{"direction":"to_runtime","user_id":"macro|[email protected]","content":{"type":"acp","jsonrpc":"2.0","id":"agent_session:p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"go"}]}}}"#;
+const END_TURN: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"agent_session:p","result":{"stopReason":"end_turn"}}}"#;
+const ACP_READY: &str =
+ r#"{"direction":"to_server","content":{"type":"event","event":"acp_ready"}}"#;
+
+/// A session-scoped form with one of every property type, declared in an
+/// order the SDK's `BTreeMap` would not preserve.
+const FORM: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":7,"method":"elicitation/create","params":{"sessionId":"s","mode":"form","message":"Configure the service","requestedSchema":{"type":"object","title":"Config","description":"A few details","properties":{"zeta":{"type":"string","title":"Name","minLength":1,"maxLength":64,"pattern":"^[a-z]+$","format":"email","default":"svc"},"port":{"type":"integer","title":"Port","minimum":1024,"maximum":65535,"default":3000},"ratio":{"type":"number","minimum":0,"maximum":1},"logging":{"type":"boolean","title":"Logging","default":true},"colours":{"type":"array","title":"Colours","minItems":1,"maxItems":2,"items":{"anyOf":[{"const":"r","title":"Red"},{"const":"g","title":"Green","description":"go"}]},"default":["r"]},"plain":{"type":"array","items":{"type":"string","enum":["a","b"]}},"alpha":{"type":"string","enum":["x","y"]},"weird":{"type":"_hologram","title":"Weird","projector":"left"}},"required":["zeta","port"]}}}}"#;
+
+fn accept(id: u64, content: &str) -> String {
+ format!(
+ r#"{{"direction":"to_runtime","user_id":"macro|[email protected]","content":{{"type":"acp","jsonrpc":"2.0","id":{id},"result":{{"action":"accept","content":{content}}}}}}}"#
+ )
+}
+
+fn answer(id: u64, action: &str) -> String {
+ format!(
+ r#"{{"direction":"to_runtime","user_id":"macro|[email protected]","content":{{"type":"acp","jsonrpc":"2.0","id":{id},"result":{{"action":"{action}"}}}}}}"#
+ )
+}
+
+fn error(id: u64) -> String {
+ format!(
+ r#"{{"direction":"to_runtime","content":{{"type":"acp","jsonrpc":"2.0","id":{id},"error":{{"code":-32602,"message":"one elicitation at a time"}}}}}}"#
+ )
+}
+
+fn url(id: u64, elicitation_id: &str) -> String {
+ format!(
+ r#"{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","id":{id},"method":"elicitation/create","params":{{"sessionId":"s","mode":"url","elicitationId":"{elicitation_id}","url":"https://agent.example.com/connect?e={elicitation_id}","message":"Authorize GitHub"}}}}}}"#
+ )
+}
+
+fn complete(elicitation_id: &str) -> String {
+ format!(
+ r#"{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","method":"elicitation/complete","params":{{"elicitationId":"{elicitation_id}"}}}}}}"#
+ )
+}
+
+/// The `initialize` exchange that names the harness, so the fold reads the
+/// frames that follow with that harness's reader.
+fn announce(agent_name: &str) -> String {
+ format!(
+ r#"{{"direction":"to_runtime","content":{{"type":"acp","jsonrpc":"2.0","id":"i","method":"initialize","params":{{"protocolVersion":1,"clientCapabilities":{{}}}}}}}}
+{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","id":"i","result":{{"protocolVersion":1,"agentCapabilities":{{}},"agentInfo":{{"name":"{agent_name}","version":"0"}}}}}}}}"#
+ )
+}
+
+fn lines(parts: &[&str]) -> String {
+ parts.join("\n")
+}
+
+/// Push a log, returning the machine and how many metadata events it reported.
+fn drive(jsonl: &str) -> (FoldMachineImpl, usize) {
+ let mut machine = FoldMachineImpl::new();
+ let mut metadata_events = 0;
+ for entry in parse_log(jsonl) {
+ for event in machine.push(entry) {
+ if matches!(event, FoldEvent::MetadataUpdated(_)) {
+ metadata_events += 1;
+ }
+ }
+ }
+ (machine, metadata_events)
+}
+
+fn elicitations(machine: &FoldMachineImpl) -> Vec<&MessagePart> {
+ machine
+ .messages()
+ .iter()
+ .flat_map(|message| message.parts.iter())
+ .filter(|part| matches!(part, MessagePart::Elicitation { .. }))
+ .collect()
+}
+
+#[test]
+fn a_form_request_becomes_a_pending_part_and_the_live_slot() {
+ let (machine, metadata_events) = drive(&lines(&[PROMPT, FORM]));
+
+ assert_eq!(metadata_events, 1, "the slot filling is a metadata change");
+ let parts = elicitations(&machine);
+ assert_eq!(parts.len(), 1);
+ let MessagePart::Elicitation {
+ request_id,
+ tool_call,
+ message,
+ request,
+ outcome,
+ reported,
+ tool_outcome,
+ } = parts[0]
+ else {
+ unreachable!()
+ };
+ assert_eq!(*request_id, ElicitationRequestId::Number(7));
+ assert_eq!(*tool_call, None);
+ assert_eq!(message, "Configure the service");
+ assert_eq!(*outcome, ElicitationOutcome::Pending);
+ assert_eq!(*reported, None);
+ assert_eq!(*tool_outcome, None, "no tool is under review");
+
+ let pending = machine
+ .metadata()
+ .pending_elicitation
+ .as_ref()
+ .expect("the slot is filled");
+ assert_eq!(pending.request_id, ElicitationRequestId::Number(7));
+ assert_eq!(pending.turn, 0);
+ assert_eq!(pending.message, "Configure the service");
+ assert_eq!(pending.request, *request);
+}
+
+#[test]
+fn the_schema_mirror_keeps_declaration_order_and_every_property_type() {
+ let (machine, _) = drive(&lines(&[PROMPT, FORM]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request: ElicitationRequest::Form { schema },
+ ..
+ } = parts[0]
+ else {
+ panic!("a form: {:?}", parts[0]);
+ };
+
+ assert_eq!(schema.title.as_deref(), Some("Config"));
+ assert_eq!(schema.description.as_deref(), Some("A few details"));
+ assert_eq!(schema.required, ["zeta", "port"]);
+ // The agent's order, not the BTreeMap's alphabetical one.
+ assert_eq!(
+ schema
+ .properties
+ .iter()
+ .map(|property| property.name.as_str())
+ .collect::<Vec<_>>(),
+ [
+ "zeta", "port", "ratio", "logging", "colours", "plain", "alpha", "weird"
+ ]
+ );
+
+ let by_name = |name: &str| {
+ schema
+ .properties
+ .iter()
+ .find(|property| property.name == name)
+ .unwrap_or_else(|| panic!("{name} is present"))
+ };
+
+ let zeta = by_name("zeta");
+ assert_eq!(zeta.title.as_deref(), Some("Name"));
+ assert_eq!(
+ zeta.schema,
+ ElicitationPropertySchema::String {
+ min_length: Some(1),
+ max_length: Some(64),
+ pattern: Some("^[a-z]+$".to_owned()),
+ format: Some("email".to_owned()),
+ default: Some("svc".to_owned()),
+ options: Vec::new(),
+ custom_field: None,
+ }
+ );
+ assert_eq!(
+ by_name("port").schema,
+ ElicitationPropertySchema::Integer {
+ minimum: Some(1024),
+ maximum: Some(65535),
+ default: Some(3000),
+ }
+ );
+ assert_eq!(
+ by_name("ratio").schema,
+ ElicitationPropertySchema::Number {
+ minimum: Some(0.0),
+ maximum: Some(1.0),
+ default: None,
+ }
+ );
+ assert_eq!(
+ by_name("logging").schema,
+ ElicitationPropertySchema::Boolean {
+ default: Some(true)
+ }
+ );
+ let ElicitationPropertySchema::MultiSelect {
+ min_items,
+ max_items,
+ options,
+ default,
+ custom_field,
+ } = &by_name("colours").schema
+ else {
+ panic!("an anyOf array is a multi-select");
+ };
+ assert_eq!((*min_items, *max_items), (Some(1), Some(2)));
+ assert_eq!(
+ options
+ .iter()
+ .map(|option| (option.value.as_str(), option.title.as_deref()))
+ .collect::<Vec<_>>(),
+ [("r", Some("Red")), ("g", Some("Green"))]
+ );
+ assert_eq!(options[1].description.as_deref(), Some("go"));
+ assert_eq!(default, &["r"]);
+ assert_eq!(*custom_field, None);
+ let ElicitationPropertySchema::MultiSelect { options, .. } = &by_name("plain").schema else {
+ panic!("an enum array is a multi-select");
+ };
+ assert_eq!(
+ options
+ .iter()
+ .map(|option| (option.value.as_str(), option.title.is_none()))
+ .collect::<Vec<_>>(),
+ [("a", true), ("b", true)]
+ );
+ let ElicitationPropertySchema::String { options, .. } = &by_name("alpha").schema else {
+ panic!("an enum string is a single select");
+ };
+ assert_eq!(options.len(), 2);
+ let ElicitationPropertySchema::Unrecognized { type_name, raw } = &by_name("weird").schema
+ else {
+ panic!("an unknown type is preserved raw");
+ };
+ assert_eq!(type_name, "_hologram");
+ assert_eq!(raw["projector"], "left");
+ assert_eq!(by_name("weird").title.as_deref(), Some("Weird"));
+}
+
+#[test]
+fn accept_resolves_the_part_with_its_content_and_frees_the_slot() {
+ let (machine, metadata_events) = drive(&lines(&[
+ PROMPT,
+ FORM,
+ &accept(7, r#"{"zeta":"svc","port":8080}"#),
+ ]));
+
+ assert_eq!(metadata_events, 2, "filled, then cleared");
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ // Shaped against the schema that asked: the property's title becomes the
+ // label, declaration order is kept, and properties the content did not
+ // answer are absent rather than empty.
+ assert_eq!(
+ *outcome,
+ ElicitationOutcome::Accepted {
+ answers: vec![
+ AnsweredField {
+ name: "zeta".to_owned(),
+ label: "Name".to_owned(),
+ value: AnsweredValue::Text {
+ text: "svc".to_owned()
+ },
+ },
+ AnsweredField {
+ name: "port".to_owned(),
+ label: "Port".to_owned(),
+ value: AnsweredValue::Number {
+ text: "8080".to_owned()
+ },
+ },
+ ],
+ }
+ );
+ assert_eq!(machine.metadata().pending_elicitation, None);
+}
+
+/// Multi-select answers resolve to the titles they were offered under, and a
+/// key no property declared still surfaces - labelled by the key itself, after
+/// the schema's own fields - rather than being dropped.
+#[test]
+fn accept_titles_the_choices_and_keeps_a_key_no_property_claimed() {
+ let (machine, _) = drive(&lines(&[
+ PROMPT,
+ FORM,
+ &accept(7, r#"{"colours":["r","g"],"alpha":"x","surprise":true}"#),
+ ]));
+
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ let ElicitationOutcome::Accepted { answers } = outcome else {
+ unreachable!("{outcome:?}")
+ };
+ assert_eq!(
+ *answers,
+ vec![
+ AnsweredField {
+ name: "colours".to_owned(),
+ label: "Colours".to_owned(),
+ value: AnsweredValue::Choices {
+ choices: vec![
+ AnsweredChoice {
+ value: "r".to_owned(),
+ title: Some("Red".to_owned()),
+ },
+ AnsweredChoice {
+ value: "g".to_owned(),
+ title: Some("Green".to_owned()),
+ },
+ ],
+ },
+ },
+ // An untitled `enum`: the value is its own label, so no title.
+ AnsweredField {
+ name: "alpha".to_owned(),
+ label: "alpha".to_owned(),
+ value: AnsweredValue::Choice {
+ choice: AnsweredChoice {
+ value: "x".to_owned(),
+ title: None,
+ },
+ },
+ },
+ AnsweredField {
+ name: "surprise".to_owned(),
+ label: "surprise".to_owned(),
+ value: AnsweredValue::Boolean { checked: true },
+ },
+ ]
+ );
+}
+
+#[test]
+fn decline_cancel_and_error_each_resolve_and_free_the_slot() {
+ for (log, expected) in [
+ (answer(7, "decline"), ElicitationOutcome::Declined),
+ (answer(7, "cancel"), ElicitationOutcome::Cancelled),
+ (
+ error(7),
+ ElicitationOutcome::Errored {
+ message: "one elicitation at a time".to_owned(),
+ },
+ ),
+ (answer(7, "_shrug"), ElicitationOutcome::Unrecognized),
+ ] {
+ let (machine, _) = drive(&lines(&[PROMPT, FORM, &log]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ assert_eq!(*outcome, expected);
+ assert_eq!(machine.metadata().pending_elicitation, None);
+ }
+}
+
+#[test]
+fn a_second_request_gets_a_part_but_never_the_slot() {
+ let second = FORM.replace(r#""id":7"#, r#""id":8"#);
+ let (machine, _) = drive(&lines(&[PROMPT, FORM, &second, &error(8)]));
+
+ let parts = elicitations(&machine);
+ assert_eq!(parts.len(), 2, "both requests are in the transcript");
+ let MessagePart::Elicitation { outcome, .. } = parts[1] else {
+ unreachable!()
+ };
+ assert!(matches!(outcome, ElicitationOutcome::Errored { .. }));
+ assert_eq!(
+ machine
+ .metadata()
+ .pending_elicitation
+ .as_ref()
+ .map(|pending| pending.request_id.clone()),
+ Some(ElicitationRequestId::Number(7)),
+ "the first question still owns the slot"
+ );
+}
+
+#[test]
+fn the_turn_ending_clears_the_slot_but_leaves_the_part_pending() {
+ let (machine, metadata_events) = drive(&lines(&[PROMPT, FORM, END_TURN]));
+
+ assert_eq!(metadata_events, 2);
+ assert_eq!(machine.metadata().pending_elicitation, None);
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ assert_eq!(*outcome, ElicitationOutcome::Pending);
+}
+
+#[test]
+fn a_late_answer_after_the_turn_ended_still_resolves_the_part() {
+ let (machine, _) = drive(&lines(&[PROMPT, FORM, END_TURN, &answer(7, "decline")]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ assert_eq!(*outcome, ElicitationOutcome::Declined);
+}
+
+#[test]
+fn a_reconnect_forgets_the_question_because_its_id_died_with_the_connection() {
+ let (machine, _) = drive(&lines(&[PROMPT, FORM, ACP_READY, &answer(7, "decline")]));
+
+ assert_eq!(machine.metadata().pending_elicitation, None);
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ assert_eq!(
+ *outcome,
+ ElicitationOutcome::Pending,
+ "an answer on a dead connection's id correlates with nothing"
+ );
+}
+
+#[test]
+fn a_url_consent_then_completion_walks_accepted_to_completed() {
+ let (machine, _) = drive(&lines(&[
+ PROMPT,
+ &url(3, "gh-1"),
+ &answer(3, "accept"),
+ &complete("gh-1"),
+ &complete("gh-1"),
+ &complete("unknown"),
+ ]));
+
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request, outcome, ..
+ } = parts[0]
+ else {
+ unreachable!()
+ };
+ assert_eq!(
+ *request,
+ ElicitationRequest::Url {
+ elicitation_id: "gh-1".to_owned(),
+ url: "https://agent.example.com/connect?e=gh-1".to_owned(),
+ }
+ );
+ assert_eq!(*outcome, ElicitationOutcome::Completed);
+}
+
+#[test]
+fn a_declined_url_is_never_completed() {
+ let (machine, _) = drive(&lines(&[
+ PROMPT,
+ &url(3, "gh-1"),
+ &answer(3, "decline"),
+ &complete("gh-1"),
+ ]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { outcome, .. } = parts[0] else {
+ unreachable!()
+ };
+ assert_eq!(*outcome, ElicitationOutcome::Declined);
+}
+
+#[test]
+fn an_unknown_mode_is_kept_raw() {
+ let raw = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"sessionId":"s","mode":"_hologram","message":"Look","projector":"left"}}}"#;
+ let (machine, _) = drive(&lines(&[PROMPT, raw]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation { request, .. } = parts[0] else {
+ unreachable!()
+ };
+ let ElicitationRequest::Unrecognized { mode, raw } = request else {
+ panic!("unknown modes are preserved: {request:?}");
+ };
+ assert_eq!(mode, "_hologram");
+ assert_eq!(raw["projector"], "left");
+}
+
+/// The real Claude Code recording: `AskUserQuestion` opens a tool call, the
+/// elicitation names it, and the adapter reports which answer it took.
+#[test]
+fn claude_code_absorbs_the_ask_user_question_tool_call() {
+ let (messages, warnings) =
+ capturing_warnings(|| fold(parse_log(ELICITATION_CLAUDE_SINGLE_SELECT)));
+ assert_eq!(warnings, vec![], "the recording folds cleanly");
+
+ let agent = &messages[1];
+ let kinds: Vec<&str> = agent
+ .parts
+ .iter()
+ .map(|part| match part {
+ MessagePart::Text { .. } => "text",
+ MessagePart::Elicitation { .. } => "elicitation",
+ MessagePart::ToolUse { .. } => "tool_use",
+ _ => "other",
+ })
+ .collect();
+ assert_eq!(
+ kinds,
+ ["text", "elicitation", "text"],
+ "the question took the tool row's place; no separate tool card: {:#?}",
+ agent.parts
+ );
+
+ let MessagePart::Elicitation {
+ request_id,
+ tool_call,
+ message,
+ request,
+ outcome,
+ reported,
+ ..
+ } = &agent.parts[1]
+ else {
+ unreachable!()
+ };
+ assert_eq!(*request_id, ElicitationRequestId::Number(0));
+ assert_eq!(
+ *tool_call,
+ Some(ToolUseId("toolu_01JYzP4A82LetDUgqvnRXguU".to_owned()))
+ );
+ assert_eq!(message, "What is the best colour?");
+
+ // The `question_0` / `question_0_custom` pair collapsed to one required
+ // select that allows a custom answer.
+ let ElicitationRequest::Form { schema } = request else {
+ panic!("a form");
+ };
+ assert_eq!(schema.properties.len(), 1);
+ assert_eq!(schema.properties[0].name, "question_0");
+ assert_eq!(schema.properties[0].title.as_deref(), Some("Best colour"));
+ assert_eq!(schema.required, ["question_0"]);
+ let ElicitationPropertySchema::String {
+ options,
+ custom_field,
+ ..
+ } = &schema.properties[0].schema
+ else {
+ panic!("a select");
+ };
+ assert_eq!(custom_field.as_deref(), Some("question_0_custom"));
+ assert_eq!(
+ options
+ .iter()
+ .map(|option| option.value.as_str())
+ .collect::<Vec<_>>(),
+ ["Red", "Blue", "Green"]
+ );
+
+ // The recording's client sent both keys - the choice *and* the custom
+ // text. The fold resolves that once, the way the adapter did: the custom
+ // text wins, and it claims the choice's key rather than leaving it to
+ // surface as a second answer.
+ assert_eq!(
+ *outcome,
+ ElicitationOutcome::Accepted {
+ answers: vec![AnsweredField {
+ name: "question_0".to_owned(),
+ label: "Best colour".to_owned(),
+ value: AnsweredValue::Custom {
+ text: "blue".to_owned()
+ },
+ }],
+ }
+ );
+ // The harness keys its own reading by the question's prose, so that prose
+ // is the label - the same shape, a different source.
+ assert_eq!(
+ *reported,
+ Some(vec![AnsweredField {
+ name: "What is the best colour?".to_owned(),
+ label: "What is the best colour?".to_owned(),
+ value: AnsweredValue::Text {
+ text: "blue".to_owned()
+ },
+ }])
+ );
+}
+
+#[test]
+fn claude_code_recording_streams_the_slot_open_then_closed() {
+ let (machine, metadata_events) = drive(ELICITATION_CLAUDE_SINGLE_SELECT);
+ assert!(
+ metadata_events >= 2,
+ "the slot filled and cleared: {metadata_events}"
+ );
+ assert_eq!(machine.metadata().pending_elicitation, None);
+}
+
+/// Hand-shaped from `claude-agent-acp` 0.64's `askUserQuestionsToCreateRequest`:
+/// two questions, the second multi-select, each with its `_custom` companion.
+const CLAUDE_TWO_QUESTIONS: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":1,"method":"elicitation/create","params":{"mode":"form","sessionId":"s","toolCallId":"toolu_ask","message":"Please answer the following questions.","requestedSchema":{"type":"object","properties":{"question_0":{"type":"string","title":"Approach","description":"Which approach?","oneOf":[{"const":"A","title":"A"},{"const":"B","title":"B"}]},"question_0_custom":{"type":"string","title":"Other","description":"Type your own answer instead of choosing an option above (optional).","_meta":{"_askUserQuestionCustomAnswer":{"questionId":"question_0","isCustomAnswer":true}}},"question_1":{"type":"array","description":"Which features?","items":{"anyOf":[{"const":"auth","title":"auth"},{"const":"logging","title":"logging"}]}},"question_1_custom":{"type":"string","title":"Other","description":"Type your own answer instead of choosing an option above (optional).","_meta":{"_askUserQuestionCustomAnswer":{"questionId":"question_1","isCustomAnswer":true}}}}}}}}"#;
+
+/// Hand-shaped from `codex-acp` 1.8's `buildUserInputRequest`: Codex's own
+/// marker namespace and `__other` suffix, `required` naming only the question
+/// without a companion.
+const CODEX_REQUEST_USER_INPUT: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"c-1","method":"elicitation/create","params":{"sessionId":"s","toolCallId":"item_9","mode":"form","message":"Input requested","requestedSchema":{"type":"object","properties":{"target":{"type":"string","title":"Target","description":"Where should this deploy?","oneOf":[{"const":"staging","title":"staging"},{"const":"prod","title":"prod","description":"Careful"}],"_meta":{"codex":{"isOther":true,"isSecret":false}}},"target__other":{"type":"string","title":"Other","description":"Type your own answer instead of choosing an option above.","_meta":{"codex":{"questionId":"target","isOtherAnswer":true,"isSecret":false}}},"region":{"type":"string","title":"Region","description":"Which region?","oneOf":[{"const":"us","title":"us"},{"const":"eu","title":"eu"}],"_meta":{"codex":{"isOther":false,"isSecret":false}}}},"required":["region"]},"_meta":{"codex":{"autoResolutionMs":null}}}}}"#;
+
+#[test]
+fn claude_code_collapses_every_question_including_multi_select() {
+ let (machine, _) = drive(&lines(&[
+ &announce("@agentclientprotocol/claude-agent-acp"),
+ PROMPT,
+ CLAUDE_TWO_QUESTIONS,
+ ]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request: ElicitationRequest::Form { schema },
+ ..
+ } = parts[0]
+ else {
+ panic!("a form");
+ };
+ assert_eq!(
+ schema
+ .properties
+ .iter()
+ .map(|property| property.name.as_str())
+ .collect::<Vec<_>>(),
+ ["question_0", "question_1"],
+ "both companions folded away"
+ );
+ assert_eq!(schema.required, ["question_0", "question_1"]);
+ let ElicitationPropertySchema::String { custom_field, .. } = &schema.properties[0].schema
+ else {
+ panic!("a select");
+ };
+ assert_eq!(custom_field.as_deref(), Some("question_0_custom"));
+ assert_eq!(
+ schema.properties[1].description.as_deref(),
+ Some("Which features?")
+ );
+ let ElicitationPropertySchema::MultiSelect {
+ options,
+ custom_field,
+ ..
+ } = &schema.properties[1].schema
+ else {
+ panic!("a multi-select: {:?}", schema.properties[1].schema);
+ };
+ assert_eq!(options.len(), 2);
+ assert_eq!(custom_field.as_deref(), Some("question_1_custom"));
+}
+
+#[test]
+fn codex_companions_are_recognized_by_their_own_marker() {
+ let (machine, _) = drive(&lines(&[
+ &announce("@agentclientprotocol/codex-acp"),
+ PROMPT,
+ CODEX_REQUEST_USER_INPUT,
+ ]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request_id,
+ tool_call,
+ request: ElicitationRequest::Form { schema },
+ ..
+ } = parts[0]
+ else {
+ panic!("a form");
+ };
+ assert_eq!(*request_id, ElicitationRequestId::Str("c-1".to_owned()));
+ // Codex never opened a tool_call for this id; the part still records it.
+ assert_eq!(*tool_call, Some(ToolUseId("item_9".to_owned())));
+ assert_eq!(
+ schema
+ .properties
+ .iter()
+ .map(|property| property.name.as_str())
+ .collect::<Vec<_>>(),
+ ["target", "region"]
+ );
+ // Codex required only `region`; the collapsed `target` joins it.
+ assert_eq!(schema.required, ["region", "target"]);
+ let ElicitationPropertySchema::String { custom_field, .. } = &schema.properties[0].schema
+ else {
+ panic!("a select");
+ };
+ assert_eq!(custom_field.as_deref(), Some("target__other"));
+ let ElicitationPropertySchema::String { custom_field, .. } = &schema.properties[1].schema
+ else {
+ panic!("a select");
+ };
+ assert_eq!(
+ *custom_field, None,
+ "a question without a companion stays plain"
+ );
+}
+
+#[test]
+fn the_shared_marker_collapses_a_companion_whoever_the_harness_is() {
+ // No `initialize`: an unknown harness, read generically. The marker
+ // Claude Code left un-namespaced is enough.
+ let (machine, _) = drive(&lines(&[PROMPT, CLAUDE_TWO_QUESTIONS]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request: ElicitationRequest::Form { schema },
+ ..
+ } = parts[0]
+ else {
+ panic!("a form");
+ };
+ assert_eq!(schema.properties.len(), 2, "both companions folded away");
+}
+
+#[test]
+fn an_unknown_harness_does_not_guess_companions_from_names_alone() {
+ // Codex's frames without Codex announced: its namespaced marker and its
+ // `__other` suffix are its own conventions, not the neutral reading.
+ let (machine, _) = drive(&lines(&[PROMPT, CODEX_REQUEST_USER_INPUT]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request: ElicitationRequest::Form { schema },
+ ..
+ } = parts[0]
+ else {
+ panic!("a form");
+ };
+ assert_eq!(
+ schema
+ .properties
+ .iter()
+ .map(|property| property.name.as_str())
+ .collect::<Vec<_>>(),
+ ["target", "target__other", "region"],
+ "every property is kept as declared"
+ );
+}
+
+#[test]
+fn a_question_asked_under_a_subagent_takes_the_nested_calls_place() {
+ // Claude Code attributes the subagent's `AskUserQuestion` to the `Agent`
+ // call through `parentToolUseId`; the elicitation names that nested id.
+ let agent_call = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"toolu_agent","title":"Agent","kind":"think","status":"in_progress","rawInput":{"prompt":"decide"},"_meta":{"claudeCode":{"toolName":"Agent","subagent":true}}}}}}"#;
+ let nested_ask = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"toolu_ask","title":"AskUserQuestion","kind":"other","status":"in_progress","_meta":{"claudeCode":{"toolName":"AskUserQuestion","parentToolUseId":"toolu_agent"}}}}}}"#;
+ let (machine, _) = drive(&lines(&[
+ &announce("@agentclientprotocol/claude-agent-acp"),
+ PROMPT,
+ agent_call,
+ nested_ask,
+ CLAUDE_TWO_QUESTIONS,
+ ]));
+
+ let agent = &machine.messages()[1];
+ assert_eq!(agent.parts.len(), 1, "one subagent row: {:#?}", agent.parts);
+ let MessagePart::ToolUse {
+ detail: ToolDetail::Subagent { children, .. },
+ ..
+ } = &agent.parts[0]
+ else {
+ panic!("the Agent call: {:?}", agent.parts[0]);
+ };
+ assert_eq!(children.len(), 1);
+ let MessagePart::Elicitation { tool_call, .. } = &children[0] else {
+ panic!("the question replaced the nested call: {:?}", children[0]);
+ };
+ assert_eq!(*tool_call, Some(ToolUseId("toolu_ask".to_owned())));
+ assert_eq!(
+ machine
+ .metadata()
+ .pending_elicitation
+ .as_ref()
+ .map(|pending| pending.turn),
+ Some(0)
+ );
+}
+
+#[test]
+fn a_bare_text_field_titled_other_without_a_select_is_left_alone() {
+ let lone = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":2,"method":"elicitation/create","params":{"mode":"form","sessionId":"s","message":"Name?","requestedSchema":{"type":"object","properties":{"name_custom":{"type":"string","title":"Other"}}}}}}"#;
+ let (machine, _) = drive(&lines(&[
+ &announce("@agentclientprotocol/claude-agent-acp"),
+ PROMPT,
+ lone,
+ ]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ request: ElicitationRequest::Form { schema },
+ ..
+ } = parts[0]
+ else {
+ panic!("a form");
+ };
+ assert_eq!(schema.properties.len(), 1, "nothing to collapse onto");
+ assert_eq!(schema.properties[0].name, "name_custom");
+}
+
+// --- a Macro user tool's review ---
+
+/// Macro's in-process agent calling `CreateCalendarEvent` natively: the
+/// call opens as a user tool, answered pending until the review lands.
+const CREATE_EVENT_CALL: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"macro":{"toolName":"CreateCalendarEvent"}},"toolCallId":"toolu_evt","sessionUpdate":"tool_call","title":"CreateCalendarEvent","kind":"edit","status":"in_progress","rawInput":{"title":"Q3 sync","time":{"kind":"allDay","startDate":"2026-08-20","endDate":"2026-08-21"}}}}}}"#;
+
+/// The review the finisher asks for that call: a form scoped to it, with
+/// the flat fields, the `_macro/json` draft field, and `_meta.macro.userTool`
+/// naming the tool and carrying the draft.
+const CREATE_EVENT_REVIEW: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"sessionId":"s","toolCallId":"toolu_evt","mode":"form","message":"Create calendar event?","requestedSchema":{"type":"object","title":"Create calendar event","properties":{"title":{"type":"string","title":"title","default":"Q3 sync"},"draft":{"type":"_macro/json","title":"draft"}},"required":["title"]},"_meta":{"macro":{"userTool":{"name":"CreateCalendarEvent","draft":{"title":"Q3 sync","time":{"kind":"allDay","startDate":"2026-08-20","endDate":"2026-08-21"}}}}}}}}"#;
+
+/// The same review with no call open for it to absorb.
+const ORPHAN_REVIEW: &str = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"sessionId":"s","toolCallId":"toolu_gone","mode":"form","message":"Create calendar event?","requestedSchema":{"type":"object","properties":{"title":{"type":"string","default":"Q3 sync"}}},"_meta":{"macro":{"userTool":{"name":"CreateCalendarEvent","draft":{"title":"Q3 sync"}}}}}}}"#;
+
+fn tool_update(id: &str, status: &str, raw_output: &str) -> String {
+ format!(
+ r#"{{"direction":"to_server","content":{{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{{"sessionId":"s","update":{{"_meta":{{"macro":{{"toolName":"CreateCalendarEvent"}}}},"toolCallId":"{id}","sessionUpdate":"tool_call_update","status":"{status}","rawOutput":{raw_output}}}}}}}}}"#
+ )
+}
+
+fn draft() -> serde_json::Value {
+ serde_json::json!({"title": "Q3 sync", "time": {"kind": "allDay", "startDate": "2026-08-20", "endDate": "2026-08-21"}})
+}
+
+#[test]
+fn a_form_scoped_to_a_user_tool_call_is_that_tools_review() {
+ let (machine, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ CREATE_EVENT_CALL,
+ CREATE_EVENT_REVIEW,
+ ]));
+
+ let agent = &machine.messages()[1];
+ assert_eq!(
+ agent.parts.len(),
+ 1,
+ "the review took the call's row: {:#?}",
+ agent.parts
+ );
+ let MessagePart::Elicitation {
+ tool_call,
+ request,
+ outcome,
+ tool_outcome,
+ ..
+ } = &agent.parts[0]
+ else {
+ panic!("a question: {:?}", agent.parts[0]);
+ };
+ assert_eq!(*tool_call, Some(ToolUseId("toolu_evt".to_owned())));
+ assert_eq!(*outcome, ElicitationOutcome::Pending);
+ assert_eq!(*tool_outcome, None, "the tool has not run yet");
+ let ElicitationRequest::UserTool {
+ tool,
+ draft: reviewed,
+ schema,
+ } = request
+ else {
+ panic!("a user tool review: {request:?}");
+ };
+ assert_eq!(tool, "CreateCalendarEvent");
+ assert_eq!(**reviewed, draft(), "the draft is the call's own arguments");
+ assert_eq!(schema.title.as_deref(), Some("Create calendar event"));
+ let names: Vec<&str> = schema
+ .properties
+ .iter()
+ .map(|property| property.name.as_str())
+ .collect();
+ assert_eq!(
+ names,
+ ["title", "draft"],
+ "the flat form is kept for a client without a composer"
+ );
+ assert!(
+ matches!(
+ schema.properties[1].schema,
+ ElicitationPropertySchema::Unrecognized { ref type_name, .. } if type_name == "_macro/json"
+ ),
+ "the draft field is Macro's extension type: {:?}",
+ schema.properties[1].schema
+ );
+
+ let pending = machine
+ .metadata()
+ .pending_elicitation
+ .as_ref()
+ .expect("the review is the live question");
+ assert_eq!(
+ pending.request, *request,
+ "the slot carries the same typed request"
+ );
+}
+
+#[test]
+fn a_reviewed_tools_own_result_lands_on_the_question() {
+ let accepted = accept(
+ 9,
+ r#"{"title":"Q3 planning","draft":"{\"title\":\"Q3 planning\"}"}"#,
+ );
+ let created = r#"{"UserAction":{"eventId":"evt-1","title":"Q3 planning"}}"#;
+ let (machine, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ CREATE_EVENT_CALL,
+ CREATE_EVENT_REVIEW,
+ &accepted,
+ &tool_update("toolu_evt", "completed", created),
+ END_TURN,
+ ]));
+
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ outcome,
+ tool_outcome,
+ ..
+ } = parts[0]
+ else {
+ unreachable!()
+ };
+ assert!(
+ matches!(outcome, ElicitationOutcome::Accepted { answers } if !answers.is_empty()),
+ "the user's answer: {outcome:?}"
+ );
+ assert_eq!(
+ *tool_outcome,
+ Some(crate::domain::model::UserToolOutcome::Completed {
+ result: serde_json::json!({"eventId": "evt-1", "title": "Q3 planning"}),
+ }),
+ "the created event, read as the tool's user-tool response"
+ );
+ assert!(
+ machine.metadata().pending_elicitation.is_none(),
+ "answered and the turn over: nothing to offer"
+ );
+}
+
+#[test]
+fn a_declined_review_and_a_failed_tool_read_as_such() {
+ let (declined, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ CREATE_EVENT_CALL,
+ CREATE_EVENT_REVIEW,
+ &answer(9, "decline"),
+ &tool_update("toolu_evt", "completed", r#""Rejected""#),
+ ]));
+ let MessagePart::Elicitation {
+ outcome,
+ tool_outcome,
+ ..
+ } = elicitations(&declined)[0]
+ else {
+ unreachable!()
+ };
+ assert_eq!(*outcome, ElicitationOutcome::Declined);
+ assert_eq!(
+ *tool_outcome,
+ Some(crate::domain::model::UserToolOutcome::Rejected)
+ );
+
+ let (failed, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ CREATE_EVENT_CALL,
+ CREATE_EVENT_REVIEW,
+ &accept(9, "{}"),
+ &tool_update(
+ "toolu_evt",
+ "failed",
+ r#"{"error":"Failed to create the calendar event: no writable calendar"}"#,
+ ),
+ ]));
+ let MessagePart::Elicitation { tool_outcome, .. } = elicitations(&failed)[0] else {
+ unreachable!()
+ };
+ assert_eq!(
+ *tool_outcome,
+ Some(crate::domain::model::UserToolOutcome::Failed {
+ message: "Failed to create the calendar event: no writable calendar".to_owned(),
+ })
+ );
+}
+
+/// The review is a request the agent sends directly from the tool's task,
+/// while the `tool_call` notification queues through the turn loop, so the
+/// question can reach the log first. The call still folds into the question:
+/// one row, and the call's result lands on it.
+#[test]
+fn a_tool_call_arriving_after_its_review_is_absorbed_into_the_question() {
+ let created = r#"{"UserAction":{"eventId":"evt-1","title":"Q3 sync"}}"#;
+ let (machine, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ CREATE_EVENT_REVIEW,
+ CREATE_EVENT_CALL,
+ &accept(9, "{}"),
+ &tool_update("toolu_evt", "completed", created),
+ ]));
+
+ let agent = &machine.messages()[1];
+ assert_eq!(
+ agent.parts.len(),
+ 1,
+ "the late call took the question's row, not its own: {:#?}",
+ agent.parts
+ );
+ let MessagePart::Elicitation {
+ tool_call,
+ request,
+ outcome,
+ tool_outcome,
+ ..
+ } = &agent.parts[0]
+ else {
+ panic!("a question: {:?}", agent.parts[0]);
+ };
+ assert_eq!(*tool_call, Some(ToolUseId("toolu_evt".to_owned())));
+ assert!(matches!(request, ElicitationRequest::UserTool { .. }));
+ assert!(matches!(outcome, ElicitationOutcome::Accepted { .. }));
+ assert_eq!(
+ *tool_outcome,
+ Some(crate::domain::model::UserToolOutcome::Completed {
+ result: serde_json::json!({"eventId": "evt-1", "title": "Q3 sync"}),
+ }),
+ "the call's updates reach the question it was absorbed into"
+ );
+}
+
+/// A review that came without its draft takes it from the late call.
+#[test]
+fn a_late_call_fills_a_review_that_came_without_a_draft() {
+ let bare_review = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"sessionId":"s","toolCallId":"toolu_evt","mode":"form","message":"Create calendar event?","requestedSchema":{"type":"object","properties":{"title":{"type":"string"}}},"_meta":{"macro":{"userTool":{"name":"CreateCalendarEvent"}}}}}}"#;
+ let (machine, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ bare_review,
+ CREATE_EVENT_CALL,
+ ]));
+ let MessagePart::Elicitation { request, .. } = elicitations(&machine)[0] else {
+ unreachable!()
+ };
+ let ElicitationRequest::UserTool {
+ draft: reviewed, ..
+ } = request
+ else {
+ panic!("a user tool review: {request:?}");
+ };
+ assert_eq!(**reviewed, draft());
+}
+
+#[test]
+fn a_review_with_no_call_to_absorb_is_still_a_review_from_its_meta() {
+ let (machine, _) = drive(&lines(&[&announce("macro-inmem"), PROMPT, ORPHAN_REVIEW]));
+ let parts = elicitations(&machine);
+ let MessagePart::Elicitation {
+ tool_call, request, ..
+ } = parts[0]
+ else {
+ unreachable!()
+ };
+ assert_eq!(*tool_call, Some(ToolUseId("toolu_gone".to_owned())));
+ let ElicitationRequest::UserTool { tool, draft, .. } = request else {
+ panic!("a user tool review: {request:?}");
+ };
+ assert_eq!(tool, "CreateCalendarEvent");
+ assert_eq!(**draft, serde_json::json!({"title": "Q3 sync"}));
+}
+
+#[test]
+fn a_form_scoped_to_an_ordinary_tool_call_stays_a_form() {
+ // A Macro tool that is not a user tool, asked about with no `_meta.macro.userTool`.
+ let read_call = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"macro":{"toolName":"ReadContent"}},"toolCallId":"toolu_read","sessionUpdate":"tool_call","title":"ReadContent","kind":"read","status":"in_progress","rawInput":{"documentId":"d"}}}}}"#;
+ let question = r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":3,"method":"elicitation/create","params":{"sessionId":"s","toolCallId":"toolu_read","mode":"form","message":"Which section?","requestedSchema":{"type":"object","properties":{"section":{"type":"string"}}}}}}"#;
+ let (machine, _) = drive(&lines(&[
+ &announce("macro-inmem"),
+ PROMPT,
+ read_call,
+ question,
+ ]));
+ let MessagePart::Elicitation { request, .. } = elicitations(&machine)[0] else {
+ unreachable!()
+ };
+ assert!(
+ matches!(request, ElicitationRequest::Form { .. }),
+ "not a user tool: {request:?}"
+ );
+}
diff --git a/crates/agent_fold/src/domain/test/harness_readers.rs b/crates/agent_fold/src/domain/test/harness_readers.rs
index 520a079773..a66f188611 100644
--- a/crates/agent_fold/src/domain/test/harness_readers.rs
+++ b/crates/agent_fold/src/domain/test/harness_readers.rs
@@ -14,6 +14,71 @@ fn native(name: &str) -> ToolName {
ToolName::native(name)
}
+// --- Claude Code (@agentclientprotocol/claude-agent-acp) ---
+
+/// `AskUserQuestion` through `elicitation/create`: the `question_N_custom`
+/// companion carries the shared marker; without one its name and title say.
+#[test]
+fn claude_code_recognizes_its_custom_answer_companion() {
+ let reader = Harness::ClaudeCode.reader();
+ let marked = json!({"type": "string", "title": "Other", "description": "Type your own answer instead of choosing an option above (optional).", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "question_0", "isCustomAnswer": true}}});
+ assert_eq!(
+ reader.custom_answer_for("question_0_custom", &marked),
+ Some("question_0".to_owned())
+ );
+ let unset = json!({"type": "string", "title": "Other", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "question_0", "isCustomAnswer": false}}});
+ assert_eq!(reader.custom_answer_for("question_0_custom", &unset), None);
+ let bare = json!({"type": "string", "title": "Other"});
+ assert_eq!(
+ reader.custom_answer_for("question_0_custom", &bare),
+ Some("question_0".to_owned())
+ );
+ let select =
+ json!({"type": "string", "title": "Other", "oneOf": [{"const": "a", "title": "a"}]});
+ assert_eq!(
+ reader.custom_answer_for("question_0_custom", &select),
+ None,
+ "a select titled Other is a question, not a companion"
+ );
+ let retitled = json!({"type": "string", "title": "Notes"});
+ assert_eq!(
+ reader.custom_answer_for("question_0_custom", &retitled),
+ None
+ );
+ assert_eq!(reader.custom_answer_for("_custom", &bare), None);
+}
+
+/// The adapter reports the answer it settled on through the asking tool's
+/// `toolResponse`, keyed by question text.
+#[test]
+fn claude_code_reports_the_answer_it_took_on_the_tool_frame() {
+ let reader = Harness::ClaudeCode.reader();
+ let reported = Frame::new().meta(json!({"claudeCode": {"toolName": "AskUserQuestion", "toolResponse": {"questions": [], "answers": {"What is the best colour?": "blue"}}}}));
+ assert_eq!(
+ reader.reported_elicitation_answer(&reported.view()),
+ Some(json!({"What is the best colour?": "blue"}))
+ );
+ let streaming = Frame::new().meta(json!({"claudeCode": {"toolName": "AskUserQuestion"}}));
+ assert_eq!(reader.reported_elicitation_answer(&streaming.view()), None);
+ let other_tool = Frame::new()
+ .meta(json!({"claudeCode": {"toolName": "Bash", "toolResponse": {"stdout": "x"}}}));
+ assert_eq!(reader.reported_elicitation_answer(&other_tool.view()), None);
+}
+
+/// The neutral reading knows the shared marker and nothing else: no
+/// namespace, no naming convention.
+#[test]
+fn the_generic_reader_knows_only_the_shared_marker() {
+ let reader = Harness::Unknown.reader();
+ let shared = json!({"type": "string", "title": "Other", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "q", "isCustomAnswer": true}}});
+ assert_eq!(reader.custom_answer_for("x", &shared), Some("q".to_owned()));
+ let bare = json!({"type": "string", "title": "Other"});
+ assert_eq!(reader.custom_answer_for("q_custom", &bare), None);
+ assert_eq!(reader.custom_answer_for("q__other", &bare), None);
+ let codex = json!({"type": "string", "title": "Other", "_meta": {"codex": {"questionId": "q", "isOtherAnswer": true}}});
+ assert_eq!(reader.custom_answer_for("q__other", &codex), None);
+}
+
// --- Codex (@agentclientprotocol/codex-acp, legacy collaboration mode) ---
#[test]
@@ -109,6 +174,51 @@ fn codex_is_sniffed_from_either_of_its_meta_signals() {
assert_eq!(Harness::sniff(&unflagged.view()), None);
}
+/// `request_user_input` through `elicitation/create`: the `__other`
+/// companion carries Codex's own marker, and is recognized by it first, by
+/// the shared marker second, and by its name and title last.
+#[test]
+fn codex_recognizes_its_other_answer_companion() {
+ let reader = Harness::Codex.reader();
+ let marked = json!({"type": "string", "title": "Other", "_meta": {"codex": {"questionId": "target", "isOtherAnswer": true, "isSecret": false}}});
+ assert_eq!(
+ reader.custom_answer_for("target__other", &marked),
+ Some("target".to_owned())
+ );
+ // The marker names the question; the property's own name need not.
+ assert_eq!(
+ reader.custom_answer_for("anything", &marked),
+ Some("target".to_owned())
+ );
+ let select = json!({"type": "string", "title": "Target", "oneOf": [{"const": "a", "title": "a"}], "_meta": {"codex": {"isOther": true, "isSecret": false}}});
+ assert_eq!(
+ reader.custom_answer_for("target", &select),
+ None,
+ "the select itself is not a companion"
+ );
+ let shared = json!({"type": "string", "title": "Other", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "q", "isCustomAnswer": true}}});
+ assert_eq!(
+ reader.custom_answer_for("q__other", &shared),
+ Some("q".to_owned())
+ );
+ let bare = json!({"type": "string", "title": "Other"});
+ assert_eq!(
+ reader.custom_answer_for("target__other", &bare),
+ Some("target".to_owned()),
+ "a recording that lost its _meta still collapses by name"
+ );
+ assert_eq!(
+ reader.custom_answer_for("target_custom", &bare),
+ None,
+ "Claude Code's suffix is not Codex's"
+ );
+ assert_eq!(
+ reader.reported_elicitation_answer(&Frame::new().view()),
+ None,
+ "Codex sends no tool call for a question, so nothing reports back"
+ );
+}
+
// --- Cursor (cursor_cloud_agents) ---
#[test]
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 f1b72a87cb..98f7a351f1 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
@@ -395,4 +395,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap
new file mode 100644
index 0000000000..33bb439dfc
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_derive_their_pinned_metadata@elicitation_claude_single_select.jsonl.snap
@@ -0,0 +1,77 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: machine.metadata()
+input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl
+---
+SessionMetadata {
+ harness: ClaudeCode,
+ model: Some(
+ "sonnet",
+ ),
+ supported_models: [
+ ModelOption {
+ id: "default",
+ name: "Default (recommended)",
+ description: Some(
+ "Opus 5 with 1M context · Best for everyday, complex tasks",
+ ),
+ group: None,
+ },
+ ModelOption {
+ id: "opus[1m]",
+ name: "Opus (1M context)",
+ description: Some(
+ "Opus 5 with 1M context · Best for everyday, complex tasks",
+ ),
+ group: None,
+ },
+ ModelOption {
+ id: "claude-fable-5[1m]",
+ name: "Fable",
+ description: Some(
+ "Fable 5 · Most capable for your hardest and longest-running tasks",
+ ),
+ group: None,
+ },
+ ModelOption {
+ id: "sonnet",
+ name: "Sonnet",
+ description: Some(
+ "Sonnet 5 · Efficient for routine tasks",
+ ),
+ group: None,
+ },
+ ModelOption {
+ id: "haiku",
+ name: "Haiku",
+ description: Some(
+ "Haiku 4.5 · Fastest for quick answers",
+ ),
+ group: None,
+ },
+ ],
+ title: None,
+ available_commands: [
+ AvailableCommand {
+ name: "add-sdk-endpoint",
+ description: "Wrap a new backend endpoint in the TypeScript SDK (packages/sdk), or record it as skipped. Use when `just coverage` fails, or after adding an endpoint to a Rust service. (project)",
+ input_hint: None,
+ },
+ AvailableCommand {
+ name: "qc",
+ description: "Quality gate. 5 parallel agents review changes. All must pass. (project)",
+ input_hint: None,
+ },
+ AvailableCommand {
+ name: "compact",
+ description: "Free up context by summarizing the conversation so far",
+ input_hint: Some(
+ "<optional custom summarization instructions>",
+ ),
+ },
+ ],
+ status: Some(
+ "acp_ready",
+ ),
+ pending_elicitation: None,
+}
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 bc795cc0af..de9a448c4d 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
@@ -390,4 +390,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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 8446fe84db..dee87985f1 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
@@ -395,4 +395,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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 583215cdcb..a8468de61f 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
@@ -430,4 +430,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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 8358e2c986..c5e5cc513b 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
@@ -430,4 +430,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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 ee6c7c9285..376ade08c3 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
@@ -430,4 +430,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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 0accd3b040..b3d5b413dc 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
@@ -428,4 +428,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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
index ff0914a890..fa90f9c836 100644
--- 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
@@ -57,4 +57,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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
index 525b54e7d5..d4e10b8a16 100644
--- 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
@@ -243,4 +243,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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
index b366a4c848..85bfede3c9 100644
--- 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
@@ -12,4 +12,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
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
index bfe200d37e..f9d46d3b9c 100644
--- 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
@@ -60,4 +60,5 @@ SessionMetadata {
status: Some(
"acp_ready",
),
+ pending_elicitation: None,
}
diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap
new file mode 100644
index 0000000000..8223ab6026
--- /dev/null
+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@elicitation_claude_single_select.jsonl.snap
@@ -0,0 +1,141 @@
+---
+source: crates/agent_fold/src/domain/test/real_recordings.rs
+expression: messages
+input_file: crates/agent_fold/fixtures/real/elicitation_claude_single_select.jsonl
+---
+[
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: User {
+ user_id: Some(
+ ),
+ },
+ request_id: Some(
+ AgentActionId(
+ c4f086b1-8f75-4cdd-a772-f1ed41286d61,
+ ),
+ ),
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "Please use your elicitation capability (elicitation/create, form mode) to ask me what the best colour is, with options: 1. red 2. blue 3. green",
+ },
+ ],
+ },
+ stop: None,
+ },
+ FoldedMessage {
+ id: TurnId(
+ 0,
+ ),
+ author: Agent,
+ request_id: None,
+ parts: NonEmpty {
+ inner: [
+ Text {
+ text: "I don't have an elicitation/form capability to present interactive UI widgets — I can only reply in text or use the AskUserQuestion tool. I'll use that instead.",
+ },
+ Elicitation {
+ request_id: Number(
+ 0,
+ ),
+ tool_call: Some(
+ ToolUseId(
+ "toolu_01JYzP4A82LetDUgqvnRXguU",
+ ),
+ ),
+ message: "What is the best colour?",
+ request: Form {
+ schema: ElicitationSchema {
+ title: None,
+ description: None,
+ properties: [
+ ElicitationProperty {
+ name: "question_0",
+ title: Some(
+ "Best colour",
+ ),
+ description: None,
+ schema: String {
+ min_length: None,
+ max_length: None,
+ pattern: None,
+ format: None,
+ default: None,
+ options: [
+ ElicitationOption {
+ value: "Red",
+ title: Some(
+ "Red",
+ ),
+ description: Some(
+ "Red",
+ ),
+ },
+ ElicitationOption {
+ value: "Blue",
+ title: Some(
+ "Blue",
+ ),
+ description: Some(
+ "Blue",
+ ),
+ },
+ ElicitationOption {
+ value: "Green",
+ title: Some(
+ "Green",
+ ),
+ description: Some(
+ "Green",
+ ),
+ },
+ ],
+ custom_field: Some(
+ "question_0_custom",
+ ),
+ },
+ },
+ ],
+ required: [
+ "question_0",
+ ],
+ },
+ },
+ outcome: Accepted {
+ answers: [
+ AnsweredField {
+ name: "question_0",
+ label: "Best colour",
+ value: Custom {
+ text: "blue",
+ },
+ },
+ ],
+ },
+ reported: Some(
+ [
+ AnsweredField {
+ name: "What is the best colour?",
+ label: "What is the best colour?",
+ value: Text {
+ text: "blue",
+ },
+ },
+ ],
+ ),
+ tool_outcome: None,
+ },
+ Text {
+ text: "Blue it is.",
+ },
+ ],
+ },
+ stop: Some(
+ EndTurn,
+ ),
+ },
+]
diff --git a/crates/agent_fold/src/testing/fixtures.rs b/crates/agent_fold/src/testing/fixtures.rs
index 4815bceb3a..e061791a73 100644
--- a/crates/agent_fold/src/testing/fixtures.rs
+++ b/crates/agent_fold/src/testing/fixtures.rs
@@ -47,3 +47,9 @@ pub const SUBAGENT_CURSOR: &str = include_str!("../../fixtures/real/subagent_cur
/// streamed.
pub const SUBAGENT_MACRO_INMEM: &str =
include_str!("../../fixtures/real/subagent_macro_inmem.jsonl");
+
+/// A real Claude Code turn where `AskUserQuestion` asks a single-select
+/// question through `elicitation/create`, the client answers with both the
+/// choice and a custom text, and the adapter reports the custom text won.
+pub const ELICITATION_CLAUDE_SINGLE_SELECT: &str =
+ include_str!("../../fixtures/real/elicitation_claude_single_select.jsonl");
diff --git a/crates/agent_harness/src/domain/queue.rs b/crates/agent_harness/src/domain/queue.rs
index efa903fb06..c396354737 100644
--- a/crates/agent_harness/src/domain/queue.rs
+++ b/crates/agent_harness/src/domain/queue.rs
@@ -162,9 +162,10 @@ impl SessionQueues {
entry.actor = actor;
Ok(())
}
- AgentAction::SetModel(_) | AgentAction::Compact | AgentAction::Stop => {
- Err(QueueError::NotEditable)
- }
+ AgentAction::SetModel(_)
+ | AgentAction::Compact
+ | AgentAction::Stop
+ | AgentAction::RespondElicitation(_) => Err(QueueError::NotEditable),
}
}
diff --git a/crates/agent_inmem/Cargo.toml b/crates/agent_inmem/Cargo.toml
index 3ed8f55ccb..ce7bb90f9b 100644
--- a/crates/agent_inmem/Cargo.toml
+++ b/crates/agent_inmem/Cargo.toml
@@ -12,10 +12,13 @@ agent_egress = { path = "../agent_egress" }
agent-client-protocol = { workspace = true }
agent_runtime_protocol = { path = "../agent_runtime_protocol" }
agent_session = { path = "../agent_session" }
+anyhow = { workspace = true }
ai_tools = { path = "../ai_tools" }
ai_toolset = { path = "../ai_toolset" }
ai_usage = { path = "../ai_usage" }
bytes = { workspace = true }
+async-trait = { workspace = true }
+axum = { workspace = true }
dashmap = { workspace = true }
futures = { workspace = true }
macro_user_id = { path = "../macro_user_id" }
@@ -27,6 +30,7 @@ mcp_toolset = { path = "../mcp_toolset" }
memory = { path = "../memory" }
prompt = { path = "../prompt" }
rmcp = { workspace = true, features = ["client", "transport-streamable-http-client"] }
+schemars = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index 8f2e7d6d45..0b1a695c3c 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -9,30 +9,43 @@
//! [`RuntimeAttachment::solo`]: agent_session::domain::connection::RuntimeAttachment::solo
use std::collections::HashSet;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use agent::types::{AssistantMessagePart, ChatMessage};
use agent::{StreamAccumulator, StreamPart, ToolResponse};
use agent_client_protocol::schema::v1::{
- 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,
+ AgentCapabilities, BooleanPropertySchema, CancelNotification, ContentBlock, ContentChunk,
+ CreateElicitationRequest, ElicitationAction, ElicitationFormMode, ElicitationPropertySchema,
+ ElicitationSchema, ElicitationSessionScope, EnumOption, Implementation, InitializeRequest,
+ InitializeResponse, IntegerPropertySchema, Meta, NewSessionRequest, NewSessionResponse,
+ NumberPropertySchema, OtherElicitationPropertySchema, PromptRequest, PromptResponse,
+ ResumeSessionRequest, ResumeSessionResponse, SessionCapabilities, SessionId,
+ SessionNotification, SessionResumeCapabilities, SessionUpdate, SetSessionConfigOptionRequest,
+ SetSessionConfigOptionResponse, StopReason, StringFormat, StringPropertySchema,
+ ToolCall as AcpToolCall, ToolCallId, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields,
+ ToolKind,
};
use agent_client_protocol::{
Agent, Channel as AcpChannel, Client, ConnectionTo, Error as AcpError,
};
use agent_runtime_protocol::domain::action::{COMPACT_COMMAND, MODEL_CONFIG_ID};
use agent_session::domain::model::AgentSessionId;
+use ai_tools::user_tool_review::{
+ ReviewError, ReviewFieldKind, ReviewForm, ReviewOutcome, ReviewRequest, UserToolReviewer,
+};
+use async_trait::async_trait;
use macro_user_id::user_id::MacroUserIdStr;
use tokio_util::sync::CancellationToken;
use crate::domain::engine::{TurnEngine, TurnRequest};
use crate::domain::mcp::{DynMcpToolConnector, dialable_servers};
use crate::domain::session::{HistoryEntry, SessionStore, messages_for_turn};
+use crate::domain::user_input::{
+ SharedUserInputRequester, UserInputError, UserInputOutcome, UserInputRequest,
+ UserInputRequester,
+};
use agent_client_protocol::schema::v1::McpServer as AcpMcpServer;
use mcp_toolset::RemoteMcpToolSet;
@@ -41,6 +54,11 @@ mod test;
/// A turn that produces nothing for this long is treated as hung and
/// cancelled, so it cannot wedge the session's turn lock forever.
+///
+/// Time spent waiting on the user is not idleness: while a question the turn
+/// asked is outstanding ([`AwaitingUser`]), the timeout re-arms instead of
+/// cancelling, however long the user takes. The question ends with an answer,
+/// a stop, or the connection going away.
const TURN_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
/// What this agent calls itself in the `initialize` response. The fold
@@ -54,6 +72,19 @@ pub const META_NAMESPACE: &str = "macro";
/// The one tool in the Macro toolset that delegates to another agent.
const SUBAGENT_TOOL: &str = "Subagent";
+/// Slash command that asks the user a question through `elicitation/create`
+/// instead of running the model: `/ask <question>` for free text, or
+/// `/ask <question> | option | option` for a single select.
+///
+/// A test rig, deliberately: the fastest way to drive the whole elicitation
+/// path (hold, render, answer, fold) end to end without an external agent or
+/// a model. Only handled when the host enables development commands; the
+/// model-callable `AskUser` tool does not depend on that setting.
+pub const ASK_COMMAND: &str = "/ask";
+
+/// The property the `/ask` form's one field is sent back under.
+const ASK_FIELD: &str = "answer";
+
/// What one turn reads out of its session's state before running.
struct TurnInput {
/// The conversation so far plus the prompt being answered.
@@ -85,6 +116,12 @@ pub struct AgentState {
/// The tools of those servers, once dialed; `None` until then or when
/// there were none.
pub mcp_tools: Mutex<Option<RemoteMcpToolSet>>,
+ /// Whether the client advertised `elicitation.form` on `initialize`. The
+ /// protocol forbids asking a mode the client did not advertise.
+ pub client_renders_forms: AtomicBool,
+ /// Whether the host enables manual development commands such as `/ask`.
+ /// When disabled, their text is passed to the model as an ordinary prompt.
+ pub enable_dev_commands: bool,
}
impl AgentState {
@@ -191,20 +228,271 @@ impl AgentState {
}
}
+/// How many questions a turn currently has out to the user. Shared between
+/// the turn's requester, which counts each question it is waiting on, and the
+/// turn loop, which reads it to tell "waiting on the user" from "hung".
+#[derive(Default)]
+struct AwaitingUser(AtomicUsize);
+
+impl AwaitingUser {
+ fn is_waiting(&self) -> bool {
+ self.0.load(Ordering::Acquire) > 0
+ }
+
+ /// Count one outstanding question until the guard drops - on an answer,
+ /// an error, or the asking future being cancelled.
+ fn begin(&self) -> AwaitingGuard<'_> {
+ self.0.fetch_add(1, Ordering::AcqRel);
+ AwaitingGuard(self)
+ }
+}
+
+struct AwaitingGuard<'a>(&'a AwaitingUser);
+
+impl Drop for AwaitingGuard<'_> {
+ fn drop(&mut self) {
+ self.0.0.fetch_sub(1, Ordering::AcqRel);
+ }
+}
+
+/// ACP-backed user-input port for one connected session: the one place this
+/// agent sends `elicitation/create`, whether a tool is asking a question
+/// (`AskUser`, [`UserInputRequester`]) or a user tool wants its call reviewed
+/// ([`UserToolReviewer`]).
+struct AcpUserInputRequester {
+ connection: ConnectionTo<Client>,
+ session_id: SessionId,
+ awaiting: Arc<AwaitingUser>,
+}
+
+/// The key under `_meta.macro` naming the user tool an elicitation reviews,
+/// so a Macro client can render the tool's own composer instead of the form.
+const USER_TOOL_META_KEY: &str = "userTool";
+
+/// The custom property type carrying the whole edited draft as a JSON string
+/// (`_`-prefixed, as ACP reserves for implementation-specific extensions).
+const JSON_PROPERTY_TYPE: &str = "_macro/json";
+
+#[async_trait]
+impl UserToolReviewer for AcpUserInputRequester {
+ async fn review(&self, request: ReviewRequest) -> Result<ReviewOutcome, ReviewError> {
+ let _waiting = self.awaiting.begin();
+ let scope = ElicitationSessionScope::new(self.session_id.clone())
+ .tool_call_id(ToolCallId::new(request.tool_call_id.as_str()));
+ // The name lets a Macro client pick the tool's composer; the draft
+ // rides along so the fold has it even when the call the review is
+ // scoped to is not one it opened.
+ let mut ours = serde_json::Map::new();
+ ours.insert(
+ USER_TOOL_META_KEY.to_owned(),
+ serde_json::json!({ "name": request.tool_name, "draft": request.draft }),
+ );
+ let mut meta = Meta::new();
+ meta.insert(META_NAMESPACE.to_owned(), serde_json::Value::Object(ours));
+ let elicitation = CreateElicitationRequest::new(
+ ElicitationFormMode::new(scope, review_form_schema(&request.form)),
+ request.message,
+ )
+ .meta(meta);
+
+ let response = self
+ .connection
+ .send_request(elicitation)
+ .block_task()
+ .await
+ .map_err(|error| ReviewError::Unavailable(error.to_string()))?;
+ Ok(match response.action {
+ ElicitationAction::Accept(accept) => ReviewOutcome::Accepted(
+ accept
+ .content
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|(name, value)| {
+ serde_json::to_value(value).ok().map(|value| (name, value))
+ })
+ .collect(),
+ ),
+ ElicitationAction::Decline => ReviewOutcome::Declined,
+ ElicitationAction::Cancel => ReviewOutcome::Cancelled,
+ _ => {
+ return Err(ReviewError::Failed(
+ "the client returned an unknown elicitation action".to_owned(),
+ ));
+ }
+ })
+ }
+}
+
+/// A review form as ACP's restricted schema. Fields are the draft's flat
+/// arguments with their current values as defaults; the draft field is the
+/// `_macro/json` extension a Macro client fills from its own composer.
+fn review_form_schema(form: &ReviewForm) -> ElicitationSchema {
+ let mut schema = ElicitationSchema::new().title(form.title.clone());
+ for field in &form.fields {
+ let required = form.required.contains(&field.name);
+ let property: ElicitationPropertySchema = match &field.kind {
+ ReviewFieldKind::Text { default, format } => StringPropertySchema::new()
+ .title(field.name.clone())
+ .description(field.description.clone())
+ .default_value(default.clone())
+ .format(format.as_deref().and_then(string_format))
+ .into(),
+ ReviewFieldKind::Boolean { default } => BooleanPropertySchema::new()
+ .title(field.name.clone())
+ .description(field.description.clone())
+ .default_value(*default)
+ .into(),
+ ReviewFieldKind::Number { default } => NumberPropertySchema::new()
+ .title(field.name.clone())
+ .description(field.description.clone())
+ .default_value(*default)
+ .into(),
+ ReviewFieldKind::Integer { default } => IntegerPropertySchema::new()
+ .title(field.name.clone())
+ .description(field.description.clone())
+ .default_value(*default)
+ .into(),
+ ReviewFieldKind::Choice { options, default } => StringPropertySchema::new()
+ .title(field.name.clone())
+ .description(field.description.clone())
+ .enum_values(options.clone())
+ .default_value(default.clone())
+ .into(),
+ ReviewFieldKind::Json => {
+ let mut fields = std::collections::BTreeMap::new();
+ fields.insert(
+ "title".to_owned(),
+ serde_json::Value::String(field.name.clone()),
+ );
+ if let Some(description) = &field.description {
+ fields.insert(
+ "description".to_owned(),
+ serde_json::Value::String(description.clone()),
+ );
+ }
+ ElicitationPropertySchema::Other(OtherElicitationPropertySchema::new(
+ JSON_PROPERTY_TYPE,
+ fields,
+ ))
+ }
+ };
+ schema = schema.property(field.name.clone(), property, required);
+ }
+ schema
+}
+
+/// ACP's string format for a JSON Schema `format`, for the ones it names.
+fn string_format(format: &str) -> Option<StringFormat> {
+ match format {
+ "email" => Some(StringFormat::Email),
+ "uri" => Some(StringFormat::Uri),
+ "date" => Some(StringFormat::Date),
+ "date-time" => Some(StringFormat::DateTime),
+ _ => None,
+ }
+}
+
+#[async_trait]
+impl UserInputRequester for AcpUserInputRequester {
+ async fn ask(&self, request: UserInputRequest) -> Result<UserInputOutcome, UserInputError> {
+ let _waiting = self.awaiting.begin();
+ let options = request.options;
+ let mut field = StringPropertySchema::new().title("Answer");
+ if !options.is_empty() {
+ field = field.one_of(
+ options
+ .iter()
+ .map(|option| EnumOption::new(option.clone(), option.clone()))
+ .collect::<Vec<_>>(),
+ );
+ }
+ let schema = ElicitationSchema::new().property(ASK_FIELD, field, true);
+ let request = CreateElicitationRequest::new(
+ ElicitationFormMode::new(
+ ElicitationSessionScope::new(self.session_id.clone()),
+ schema,
+ ),
+ request.question,
+ );
+
+ let response = self
+ .connection
+ .send_request(request)
+ .block_task()
+ .await
+ .map_err(|error| UserInputError::RequestFailed(error.to_string()))?;
+ match response.action {
+ ElicitationAction::Accept(accept) => {
+ let answer = accept
+ .content
+ .as_ref()
+ .and_then(|content| content.get(ASK_FIELD))
+ .and_then(|value| serde_json::to_value(value).ok())
+ .ok_or(UserInputError::MissingAnswer)?;
+ let serde_json::Value::String(answer) = answer else {
+ return Err(UserInputError::InvalidAnswer(
+ "the answer was not a string".to_owned(),
+ ));
+ };
+ if !options.is_empty() && !options.contains(&answer) {
+ return Err(UserInputError::InvalidAnswer(format!(
+ "{answer:?} was not one of the offered options"
+ )));
+ }
+ Ok(UserInputOutcome::Answered(answer))
+ }
+ ElicitationAction::Decline => Ok(UserInputOutcome::Declined),
+ ElicitationAction::Cancel => Ok(UserInputOutcome::Cancelled),
+ _ => Err(UserInputError::RequestFailed(
+ "the client returned an unknown elicitation action".to_owned(),
+ )),
+ }
+ }
+}
+
+/// The turn's way of reaching the user, when the client can show a form.
+/// `None` means no question and no review can be asked this turn: `AskUser`
+/// is not offered, and a user tool's pending answer stays pending.
+fn user_input_requester(
+ state: &AgentState,
+ connection: &ConnectionTo<Client>,
+ session_id: SessionId,
+ awaiting: &Arc<AwaitingUser>,
+) -> Option<Arc<AcpUserInputRequester>> {
+ state.client_renders_forms.load(Ordering::Relaxed).then(|| {
+ Arc::new(AcpUserInputRequester {
+ connection: connection.clone(),
+ session_id,
+ awaiting: Arc::clone(awaiting),
+ })
+ })
+}
+
/// Serve this session's agent on `acp` until the connection closes.
pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpError> {
Agent
.builder()
.name("macro-inmem")
.on_receive_request(
- async move |request: InitializeRequest, responder, _connection| {
- responder.respond(
- 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"))),
- )
+ {
+ let state = Arc::clone(&state);
+ async move |request: InitializeRequest, responder, _connection| {
+ let renders_forms = request
+ .client_capabilities
+ .elicitation
+ .as_ref()
+ .is_some_and(|elicitation| elicitation.form.is_some());
+ state
+ .client_renders_forms
+ .store(renders_forms, Ordering::Relaxed);
+ responder.respond(
+ 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!(),
)
@@ -258,6 +546,29 @@ pub async fn serve(state: Arc<AgentState>, acp: AcpChannel) -> Result<(), AcpErr
));
return responder.respond(PromptResponse::new(StopReason::EndTurn));
}
+ if state.enable_dev_commands
+ && let Some(question) = prompt.trim().strip_prefix(ASK_COMMAND)
+ {
+ let question = question.trim().to_owned();
+ let cancel = state.begin_turn();
+ connection.spawn({
+ let connection = connection.clone();
+ async move {
+ let stop = run_ask(
+ &state,
+ &connection,
+ request.session_id,
+ prompt,
+ question,
+ cancel,
+ )
+ .await;
+ let _ = responder.respond(PromptResponse::new(stop));
+ Ok(())
+ }
+ })?;
+ return Ok(());
+ }
let cancel = state.begin_turn();
connection.spawn({
@@ -334,6 +645,8 @@ async fn run_turn(
model,
instructions,
} = state.turn_input(&prompt);
+ let awaiting = Arc::new(AwaitingUser::default());
+ let requester = user_input_requester(state, connection, acp_session_id.clone(), &awaiting);
let mut parts = state.engine.run_turn(TurnRequest {
owner: state.owner.clone(),
model,
@@ -341,6 +654,10 @@ async fn run_turn(
messages,
mcp_tools: state.current_mcp_tools(),
cancel: cancel.clone(),
+ user_input: requester
+ .clone()
+ .map(|requester| requester as SharedUserInputRequester),
+ reviewer: requester.map(|requester| requester as Arc<dyn UserToolReviewer>),
});
let mut accumulator = StreamAccumulator::new();
@@ -368,6 +685,10 @@ async fn run_turn(
break;
}
Ok(None) => break,
+ // Silence while a question is out is the user thinking, not the
+ // turn hanging; the tool that asked resumes the stream when they
+ // answer.
+ Err(_) if awaiting.is_waiting() => continue,
Err(_) => {
failure = Some(format!(
"the turn produced nothing for {} seconds and was stopped",
@@ -406,6 +727,79 @@ async fn run_turn(
}
}
+/// Run an `/ask` turn: send the question as a form elicitation, wait for the
+/// client's answer, and say back what it was.
+///
+/// Runs inside a spawned connection task, outside the dispatch loop, which is
+/// what makes `block_task` safe here - the loop stays free to deliver the
+/// answer (and a `session/cancel`, which the session machine turns into a
+/// `cancel` answer before the notification arrives).
+async fn run_ask(
+ state: &AgentState,
+ connection: &ConnectionTo<Client>,
+ acp_session_id: SessionId,
+ prompt: String,
+ question: String,
+ cancel: CancellationToken,
+) -> StopReason {
+ let _turn = state.turn_lock.lock().await;
+
+ let say = |text: String| {
+ let _ = connection.send_notification(SessionNotification::new(
+ acp_session_id.clone(),
+ SessionUpdate::AgentMessageChunk(ContentChunk::new(ContentBlock::from(text.clone()))),
+ ));
+ text
+ };
+
+ if !state.client_renders_forms.load(Ordering::Relaxed) {
+ let text = say(
+ "This client did not advertise form elicitation, so there is no way to ask.".to_owned(),
+ );
+ state.push_turn(prompt, vec![AssistantMessagePart::Text { text }]);
+ return StopReason::EndTurn;
+ }
+
+ let (question, options) = parse_ask(&question);
+ let requester = AcpUserInputRequester {
+ connection: connection.clone(),
+ session_id: acp_session_id.clone(),
+ // `/ask` has no idle timeout to hold off: it waits on the answer
+ // directly rather than through the turn loop.
+ awaiting: Arc::new(AwaitingUser::default()),
+ };
+ let text = match requester.ask(UserInputRequest { question, options }).await {
+ Ok(UserInputOutcome::Answered(value)) => format!("You answered: {value}"),
+ Ok(UserInputOutcome::Declined) => "You declined to answer.".to_owned(),
+ Ok(UserInputOutcome::Cancelled) => "The question was cancelled.".to_owned(),
+ Err(error) => error.to_string(),
+ };
+ let text = say(text);
+ state.push_turn(prompt, vec![AssistantMessagePart::Text { text }]);
+
+ if cancel.is_cancelled() {
+ StopReason::Cancelled
+ } else {
+ StopReason::EndTurn
+ }
+}
+
+/// Split `/ask`'s argument into the question and its options: everything
+/// before the first `|` is the question, each `|`-separated piece after it
+/// an option. No `|` means free text.
+fn parse_ask(question: &str) -> (String, Vec<String>) {
+ let mut pieces = question
+ .split('|')
+ .map(str::trim)
+ .filter(|piece| !piece.is_empty());
+ let message = pieces
+ .next()
+ .map(str::to_owned)
+ .unwrap_or_else(|| "What would you like?".to_owned());
+ let options = pieces.map(str::to_owned).collect();
+ (message, options)
+}
+
/// The `session/update` a stream part renders as, if any.
fn update_for_part(part: &StreamPart) -> Option<SessionUpdate> {
match part {
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index 26e43cd66e..f0bd38a021 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -63,6 +63,8 @@ where
turn_lock: tokio::sync::Mutex::new(()),
mcp: Arc::new(crate::domain::mcp::NoMcpServers),
mcp_tools: std::sync::Mutex::new(None),
+ client_renders_forms: AtomicBool::new(false),
+ enable_dev_commands: true,
});
let (client_channel, agent_channel) = AcpChannel::duplex();
@@ -396,8 +398,10 @@ async fn session_new_dials_the_advertised_servers_except_macros_own() {
store,
active_cancel: std::sync::Mutex::new(Vec::new()),
turn_lock: tokio::sync::Mutex::new(()),
+ enable_dev_commands: false,
mcp: Arc::new(Arc::clone(&spy)),
mcp_tools: std::sync::Mutex::new(None),
+ client_renders_forms: AtomicBool::new(false),
});
let (client_channel, agent_channel) = AcpChannel::duplex();
let agent = tokio::spawn(serve(state, agent_channel));
@@ -437,3 +441,551 @@ async fn session_new_dials_the_advertised_servers_except_macros_own() {
vec![vec!["linear".to_owned(), "notion".to_owned()]]
);
}
+
+/// Like [`with_agent`], but the client advertises form elicitation and
+/// answers every `elicitation/create` with `answer`, recording what it was
+/// asked.
+async fn with_asking_agent<Out>(
+ answer: agent_client_protocol::schema::v1::ElicitationAction,
+ scenario: impl AsyncFnOnce(ConnectionTo<Agent>, SessionId) -> Out,
+) -> (Vec<SessionNotification>, Vec<CreateElicitationRequest>, Out) {
+ with_asking_engine(
+ Arc::new(ScriptedEngine::new(vec![])),
+ true,
+ answer,
+ Duration::ZERO,
+ scenario,
+ )
+ .await
+}
+
+/// [`with_asking_agent`] over `engine`, with the client taking `delay` to
+/// answer each question - the user's think time.
+async fn with_asking_engine<Engine, Out>(
+ engine: Arc<Engine>,
+ enable_dev_commands: bool,
+ answer: agent_client_protocol::schema::v1::ElicitationAction,
+ delay: Duration,
+ scenario: impl AsyncFnOnce(ConnectionTo<Agent>, SessionId) -> Out,
+) -> (Vec<SessionNotification>, Vec<CreateElicitationRequest>, Out)
+where
+ Engine: TurnEngine,
+{
+ use agent_client_protocol::schema::v1::{
+ ClientCapabilities, CreateElicitationResponse, ElicitationCapabilities,
+ ElicitationFormCapabilities,
+ };
+
+ let store = Arc::new(SessionStore::new());
+ let session_id = AgentSessionId::new();
+ store.insert(
+ session_id,
+ crate::domain::session::SessionState::new("test-model".into()),
+ );
+ let state = Arc::new(AgentState {
+ session_id,
+ owner: MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
+ engine,
+ store,
+ active_cancel: std::sync::Mutex::new(Vec::new()),
+ turn_lock: tokio::sync::Mutex::new(()),
+ client_renders_forms: AtomicBool::new(false),
+ mcp: Arc::new(crate::domain::mcp::NoMcpServers),
+ mcp_tools: std::sync::Mutex::new(None),
+ enable_dev_commands,
+ });
+
+ let (client_channel, agent_channel) = AcpChannel::duplex();
+ let agent = tokio::spawn(serve(state, agent_channel));
+
+ let notifications = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let asked = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let out = Client
+ .builder()
+ .on_receive_notification(
+ {
+ let notifications = Arc::clone(&notifications);
+ async move |notification: SessionNotification, _connection| {
+ notifications.lock().unwrap().push(notification);
+ Ok(())
+ }
+ },
+ agent_client_protocol::on_receive_notification!(),
+ )
+ .on_receive_request(
+ {
+ let asked = Arc::clone(&asked);
+ async move |request: CreateElicitationRequest, responder, connection| {
+ asked.lock().unwrap().push(request);
+ if delay.is_zero() {
+ return responder.respond(CreateElicitationResponse::new(answer.clone()));
+ }
+ // Answer off the dispatch loop so the delay does not hold
+ // up the notifications the agent keeps sending meanwhile.
+ let answer = answer.clone();
+ connection.spawn(async move {
+ tokio::time::sleep(delay).await;
+ let _ = responder.respond(CreateElicitationResponse::new(answer));
+ Ok(())
+ })?;
+ Ok(())
+ }
+ },
+ agent_client_protocol::on_receive_request!(),
+ )
+ .connect_with(
+ client_channel,
+ async move |connection: ConnectionTo<Agent>| {
+ connection
+ .send_request(
+ InitializeRequest::new(ProtocolVersion::V1).client_capabilities(
+ ClientCapabilities::new().elicitation(
+ ElicitationCapabilities::new()
+ .form(ElicitationFormCapabilities::new()),
+ ),
+ ),
+ )
+ .block_task()
+ .await?;
+ let session = connection
+ .send_request(NewSessionRequest::new("/"))
+ .block_task()
+ .await?;
+ Ok(scenario(connection, session.session_id).await)
+ },
+ )
+ .await
+ .expect("the scripted client should run clean");
+ agent.abort();
+
+ let notifications = notifications.lock().unwrap().clone();
+ let asked = asked.lock().unwrap().clone();
+ (notifications, asked, out)
+}
+
+fn spoken(notifications: &[SessionNotification]) -> String {
+ notifications
+ .iter()
+ .filter_map(|notification| match &notification.update {
+ SessionUpdate::AgentMessageChunk(chunk) => match &chunk.content {
+ ContentBlock::Text(text) => Some(text.text.clone()),
+ _ => None,
+ },
+ _ => None,
+ })
+ .collect()
+}
+
+#[tokio::test]
+async fn ask_is_an_ordinary_prompt_when_dev_commands_are_disabled() {
+ use agent_client_protocol::schema::v1::ElicitationAction;
+
+ let prompt = "/ask Which colour? | red | blue";
+ let engine = Arc::new(ScriptedEngine::new(vec![StreamPart::Content(
+ "An ordinary model response".to_owned(),
+ )]));
+ let (notifications, asked, response) = with_asking_engine(
+ Arc::clone(&engine),
+ false,
+ ElicitationAction::Decline,
+ Duration::ZERO,
+ async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, prompt))
+ .block_task()
+ .await
+ .expect("the ordinary turn should complete")
+ },
+ )
+ .await;
+
+ assert!(
+ asked.is_empty(),
+ "the manual command must not ask a question"
+ );
+ assert_eq!(engine.requests().len(), 1);
+ assert_eq!(engine.requests()[0].messages, vec![prompt]);
+ assert_eq!(spoken(&notifications), "An ordinary model response");
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+}
+
+#[tokio::test]
+async fn ask_sends_a_form_elicitation_and_echoes_the_accepted_answer() {
+ use agent_client_protocol::schema::v1::{
+ ElicitationAcceptAction, ElicitationAction, ElicitationContentValue, ElicitationMode,
+ };
+ use std::collections::BTreeMap;
+
+ let answer =
+ ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from([(
+ ASK_FIELD.to_owned(),
+ ElicitationContentValue::String("blue".to_owned()),
+ )])));
+ let (notifications, asked, response) =
+ with_asking_agent(answer, async |connection, session| {
+ connection
+ .send_request(text_prompt(
+ &session,
+ "/ask What is the best colour? | red | blue | green",
+ ))
+ .block_task()
+ .await
+ .expect("the ask should complete")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ assert_eq!(asked.len(), 1, "exactly one question was asked");
+ assert_eq!(asked[0].message, "What is the best colour?");
+ let ElicitationMode::Form(form) = &asked[0].mode else {
+ panic!("a form was asked");
+ };
+ let field = form
+ .requested_schema
+ .properties
+ .get(ASK_FIELD)
+ .expect("the one field");
+ let agent_client_protocol::schema::v1::ElicitationPropertySchema::String(field) = field else {
+ panic!("a string field");
+ };
+ assert_eq!(
+ field.one_of.as_ref().map(|options| options
+ .iter()
+ .map(|option| option.value.as_str())
+ .collect::<Vec<_>>()),
+ Some(vec!["red", "blue", "green"])
+ );
+ assert_eq!(
+ form.requested_schema.required.as_deref(),
+ Some(&[ASK_FIELD.to_owned()][..])
+ );
+ assert_eq!(spoken(&notifications), "You answered: blue");
+}
+
+#[tokio::test]
+async fn ask_rejects_an_answer_outside_the_offered_options() {
+ use std::collections::BTreeMap;
+
+ use agent_client_protocol::schema::v1::{
+ ElicitationAcceptAction, ElicitationAction, ElicitationContentValue,
+ };
+
+ let answer =
+ ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from([(
+ ASK_FIELD.to_owned(),
+ ElicitationContentValue::String("yellow".to_owned()),
+ )])));
+ let (notifications, _, response) = with_asking_agent(answer, async |connection, session| {
+ connection
+ .send_request(text_prompt(
+ &session,
+ "/ask What is the best colour? | red | blue | green",
+ ))
+ .block_task()
+ .await
+ .expect("the ask turn should complete with a validation message")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ assert!(
+ spoken(&notifications).contains("was not one of the offered options"),
+ "got {:?}",
+ spoken(&notifications)
+ );
+}
+
+#[tokio::test]
+async fn ask_reports_a_decline_and_a_free_text_question_has_no_options() {
+ use agent_client_protocol::schema::v1::{ElicitationAction, ElicitationMode};
+
+ let (notifications, asked, response) =
+ with_asking_agent(ElicitationAction::Decline, async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "/ask Name the service"))
+ .block_task()
+ .await
+ .expect("the ask should complete")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ let ElicitationMode::Form(form) = &asked[0].mode else {
+ panic!("a form was asked");
+ };
+ let agent_client_protocol::schema::v1::ElicitationPropertySchema::String(field) =
+ &form.requested_schema.properties[ASK_FIELD]
+ else {
+ panic!("a string field");
+ };
+ assert!(field.one_of.is_none(), "free text has no options");
+ assert_eq!(spoken(&notifications), "You declined to answer.");
+}
+
+/// An engine whose one tool asks the user a question through the turn's
+/// user-input port and then says the answer - `AskUser` reduced to the part
+/// the ACP surface cares about.
+struct AskingEngine;
+
+impl TurnEngine for AskingEngine {
+ fn run_turn(
+ &self,
+ request: TurnRequest,
+ ) -> tokio::sync::mpsc::Receiver<Result<StreamPart, agent::AgentError>> {
+ let (parts, receiver) = tokio::sync::mpsc::channel(4);
+ tokio::spawn(async move {
+ let requester = request
+ .user_input
+ .expect("the client advertised forms, so the turn can ask");
+ let outcome = requester
+ .ask(UserInputRequest {
+ question: "Which colour?".to_owned(),
+ options: Vec::new(),
+ })
+ .await;
+ let text = match outcome {
+ Ok(UserInputOutcome::Answered(answer)) => format!("You said {answer}."),
+ Ok(other) => format!("{other:?}"),
+ Err(error) => error.to_string(),
+ };
+ let _ = parts.send(Ok(StreamPart::Content(text))).await;
+ });
+ receiver
+ }
+}
+
+/// A user who takes longer than the idle timeout to answer is not a hung
+/// turn: the question holds the timeout off, and the turn finishes on the
+/// answer rather than being stopped for producing nothing meanwhile.
+#[tokio::test(start_paused = true)]
+async fn a_turn_waiting_on_the_user_outlasts_the_idle_timeout() {
+ use agent_client_protocol::schema::v1::{
+ ElicitationAcceptAction, ElicitationAction, ElicitationContentValue,
+ };
+ use std::collections::BTreeMap;
+
+ let answer =
+ ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from([(
+ ASK_FIELD.to_owned(),
+ ElicitationContentValue::String("teal".to_owned()),
+ )])));
+ let (notifications, asked, response) = with_asking_engine(
+ Arc::new(AskingEngine),
+ false,
+ answer,
+ TURN_IDLE_TIMEOUT * 3,
+ async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "pick a colour for me"))
+ .block_task()
+ .await
+ .expect("the turn should complete")
+ },
+ )
+ .await;
+
+ assert_eq!(asked.len(), 1, "the tool asked once");
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ assert_eq!(spoken(&notifications), "You said teal.");
+}
+
+/// An engine whose turn puts one user tool call to the reviewer and says what
+/// came back - the agent loop's finisher reduced to the ACP surface.
+struct ReviewingEngine;
+
+impl TurnEngine for ReviewingEngine {
+ fn run_turn(
+ &self,
+ request: TurnRequest,
+ ) -> tokio::sync::mpsc::Receiver<Result<StreamPart, agent::AgentError>> {
+ let (parts, receiver) = tokio::sync::mpsc::channel(4);
+ tokio::spawn(async move {
+ let reviewer = request
+ .reviewer
+ .expect("the client advertised forms, so the turn can ask for a review");
+ let outcome = reviewer
+ .review(ReviewRequest {
+ tool_name: "CreateCalendarEvent".to_owned(),
+ tool_call_id: "toolu_7".to_owned(),
+ message: "Create calendar event?".to_owned(),
+ draft: serde_json::json!({"title": "Q3 sync", "addGoogleMeet": false}),
+ form: ReviewForm {
+ title: Some("Create calendar event".to_owned()),
+ fields: vec![
+ ai_tools::user_tool_review::ReviewField {
+ name: "title".to_owned(),
+ description: Some("The event title.".to_owned()),
+ kind: ReviewFieldKind::Text {
+ default: Some("Q3 sync".to_owned()),
+ format: None,
+ },
+ },
+ ai_tools::user_tool_review::ReviewField {
+ name: "addGoogleMeet".to_owned(),
+ description: None,
+ kind: ReviewFieldKind::Boolean {
+ default: Some(false),
+ },
+ },
+ ai_tools::user_tool_review::ReviewField {
+ name: "draft".to_owned(),
+ description: None,
+ kind: ReviewFieldKind::Json,
+ },
+ ],
+ required: vec!["title".to_owned()],
+ },
+ })
+ .await;
+ let text = match outcome {
+ Ok(ReviewOutcome::Accepted(content)) => format!(
+ "accepted {}",
+ serde_json::to_string(&content).expect("content serializes")
+ ),
+ Ok(other) => format!("{other:?}"),
+ Err(error) => error.to_string(),
+ };
+ let _ = parts.send(Ok(StreamPart::Content(text))).await;
+ });
+ receiver
+ }
+}
+
+/// A user tool's review goes out as a tool-call-scoped form elicitation the
+/// fold and a Macro client can recognize: the draft's flat fields with their
+/// values as defaults, the `_macro/json` draft field, and `_meta.macro.userTool`
+/// naming the tool. The accepted content comes back as submitted.
+#[tokio::test]
+async fn a_user_tool_review_is_a_tool_scoped_form_elicitation_naming_the_tool() {
+ use agent_client_protocol::schema::v1::{
+ ElicitationAcceptAction, ElicitationAction, ElicitationContentValue, ElicitationMode,
+ ElicitationPropertySchema, ElicitationScope,
+ };
+ use std::collections::BTreeMap;
+
+ let answer =
+ ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from([
+ (
+ "title".to_owned(),
+ ElicitationContentValue::String("Q3 planning".to_owned()),
+ ),
+ (
+ "addGoogleMeet".to_owned(),
+ ElicitationContentValue::Boolean(true),
+ ),
+ ])));
+ let (notifications, asked, response) = with_asking_engine(
+ Arc::new(ReviewingEngine),
+ false,
+ answer,
+ Duration::ZERO,
+ async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "create the event"))
+ .block_task()
+ .await
+ .expect("the turn should complete")
+ },
+ )
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ assert_eq!(asked.len(), 1, "one review was asked");
+ let request = &asked[0];
+ assert_eq!(request.message, "Create calendar event?");
+ let ElicitationMode::Form(form) = &request.mode else {
+ panic!("a form was asked");
+ };
+ let ElicitationScope::Session(scope) = &form.scope else {
+ panic!("session scoped");
+ };
+ assert_eq!(
+ scope.tool_call_id.as_ref().map(|id| id.0.as_ref()),
+ Some("toolu_7"),
+ "the elicitation names the call it reviews"
+ );
+ let user_tool = request
+ .meta
+ .as_ref()
+ .and_then(|meta| meta.get(META_NAMESPACE))
+ .and_then(|ours| ours.get(USER_TOOL_META_KEY))
+ .expect("_meta.macro.userTool names the tool under review");
+ assert_eq!(
+ user_tool.get("name").and_then(|name| name.as_str()),
+ Some("CreateCalendarEvent"),
+ "a Macro client learns which tool's composer to show"
+ );
+ assert_eq!(
+ user_tool.get("draft"),
+ Some(&serde_json::json!({"title": "Q3 sync", "addGoogleMeet": false})),
+ "and has the draft whether or not it opened the call"
+ );
+ let schema = &form.requested_schema;
+ assert_eq!(schema.title.as_deref(), Some("Create calendar event"));
+ let ElicitationPropertySchema::String(title) = &schema.properties["title"] else {
+ panic!("title is a string field");
+ };
+ assert_eq!(title.default.as_deref(), Some("Q3 sync"));
+ assert_eq!(title.description.as_deref(), Some("The event title."));
+ let ElicitationPropertySchema::Boolean(meet) = &schema.properties["addGoogleMeet"] else {
+ panic!("addGoogleMeet is a boolean field");
+ };
+ assert_eq!(meet.default, Some(false));
+ let ElicitationPropertySchema::Other(draft) = &schema.properties["draft"] else {
+ panic!(
+ "the draft is a custom field, got {:?}",
+ schema.properties["draft"]
+ );
+ };
+ assert_eq!(draft.type_, JSON_PROPERTY_TYPE);
+ assert_eq!(
+ schema.required.as_deref(),
+ Some(&["title".to_owned()][..]),
+ "the draft field is never required"
+ );
+ assert_eq!(
+ spoken(&notifications),
+ r#"accepted {"addGoogleMeet":true,"title":"Q3 planning"}"#
+ );
+}
+
+/// The timeout still guards a turn that is silent with nothing asked.
+#[tokio::test(start_paused = true)]
+async fn a_silent_turn_with_no_question_out_is_stopped_by_the_idle_timeout() {
+ let (notifications, response) =
+ with_agent(Arc::new(HangingEngine), async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "hang"))
+ .block_task()
+ .await
+ .expect("the turn should complete")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::Cancelled);
+ assert!(
+ spoken(&notifications).contains("produced nothing"),
+ "got {:?}",
+ spoken(&notifications)
+ );
+}
+
+#[tokio::test]
+async fn ask_without_form_support_explains_instead_of_asking() {
+ let engine = Arc::new(ScriptedEngine::new(vec![]));
+ let (notifications, response) = with_agent(engine, async |connection, session| {
+ connection
+ .send_request(text_prompt(&session, "/ask anything?"))
+ .block_task()
+ .await
+ .expect("the ask should complete")
+ })
+ .await;
+
+ assert_eq!(response.stop_reason, StopReason::EndTurn);
+ assert!(
+ spoken(&notifications).contains("did not advertise form elicitation"),
+ "got {:?}",
+ spoken(&notifications)
+ );
+}
diff --git a/crates/agent_inmem/src/domain/engine.rs b/crates/agent_inmem/src/domain/engine.rs
index 698c7bd8b5..3f1997917e 100644
--- a/crates/agent_inmem/src/domain/engine.rs
+++ b/crates/agent_inmem/src/domain/engine.rs
@@ -1,12 +1,17 @@
//! The seam between the ACP surface and the agentic loop that serves it.
+use std::sync::Arc;
+
use agent::types::ChatMessage;
use agent::{AgentError, StreamPart};
+use ai_tools::user_tool_review::UserToolReviewer;
use macro_user_id::user_id::MacroUserIdStr;
use mcp_toolset::RemoteMcpToolSet;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
+use super::user_input::SharedUserInputRequester;
+
/// Everything one conversational turn needs.
pub struct TurnRequest {
/// The user the turn acts on behalf of. Tools run with their identity and
@@ -27,13 +32,21 @@ pub struct TurnRequest {
/// Cancelling this token stops the turn; the stream ends after the
/// engine has drained cooperatively.
pub cancel: CancellationToken,
+ /// User-input capability for model-callable tools. Absent when the ACP
+ /// client did not advertise form elicitation.
+ pub user_input: Option<SharedUserInputRequester>,
+ /// Puts a user tool's call (`SendEmail`, `CreateCalendarEvent`) to the
+ /// user for review mid-turn, so the tool is finished - run as edited, or
+ /// rejected - before the model reads its result. Absent for the same
+ /// reason as `user_input`; a pending call then stays pending.
+ pub reviewer: Option<Arc<dyn UserToolReviewer>>,
}
/// Runs one conversational turn and streams its parts back.
///
/// The trait is the testing seam: the ACP surface is exercised against a
/// scripted engine, and production plugs in
-/// [`crate::outbound::rig_engine::RigTurnEngine`].
+/// [`crate::rig_engine::RigTurnEngine`].
pub trait TurnEngine: Send + Sync + 'static {
/// Start the turn. Parts arrive on the returned receiver; the stream
/// ending is the turn ending, and an `Err` item is a turn-fatal failure.
diff --git a/crates/agent_inmem/src/domain/mod.rs b/crates/agent_inmem/src/domain/mod.rs
index 47d98673dd..4864334f33 100644
--- a/crates/agent_inmem/src/domain/mod.rs
+++ b/crates/agent_inmem/src/domain/mod.rs
@@ -6,3 +6,4 @@ pub mod engine;
pub mod mcp;
pub mod replay;
pub mod session;
+pub mod user_input;
diff --git a/crates/agent_inmem/src/domain/user_input.rs b/crates/agent_inmem/src/domain/user_input.rs
new file mode 100644
index 0000000000..a0b64ece7d
--- /dev/null
+++ b/crates/agent_inmem/src/domain/user_input.rs
@@ -0,0 +1,63 @@
+//! Port for asking the user for information during an agent turn.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+
+/// A single question the agent needs the user to answer.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UserInputRequest {
+ /// The question shown to the user.
+ pub question: String,
+ /// Allowed answers. An empty list requests free text.
+ pub options: Vec<String>,
+}
+
+/// How the user resolved a question.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum UserInputOutcome {
+ /// The user supplied an answer.
+ Answered(String),
+ /// The user explicitly declined to answer.
+ Declined,
+ /// The question was dismissed or the turn was stopped.
+ Cancelled,
+}
+
+/// Failure to ask or decode a user-input request.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum UserInputError {
+ /// The connected ACP client did not advertise form elicitation.
+ Unsupported,
+ /// The client or transport refused the request.
+ RequestFailed(String),
+ /// The client accepted the form without returning its answer.
+ MissingAnswer,
+ /// The client returned a value outside the requested field schema.
+ InvalidAnswer(String),
+}
+
+impl std::fmt::Display for UserInputError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Unsupported => f.write_str("the client does not support form elicitation"),
+ Self::RequestFailed(message) => write!(f, "the client refused the question: {message}"),
+ Self::MissingAnswer => f.write_str("the client accepted without returning an answer"),
+ Self::InvalidAnswer(message) => {
+ write!(f, "the client returned an invalid answer: {message}")
+ }
+ }
+ }
+}
+
+impl std::error::Error for UserInputError {}
+
+/// Capability used by a turn to ask its connected user a question.
+#[async_trait]
+pub trait UserInputRequester: Send + Sync {
+ /// Ask one question and wait for the user's decision.
+ async fn ask(&self, request: UserInputRequest) -> Result<UserInputOutcome, UserInputError>;
+}
+
+/// Shared requester carried into model-callable tools.
+pub type SharedUserInputRequester = Arc<dyn UserInputRequester>;
diff --git a/crates/agent_inmem/src/inbound/ask_user.rs b/crates/agent_inmem/src/inbound/ask_user.rs
new file mode 100644
index 0000000000..f6b76e679b
--- /dev/null
+++ b/crates/agent_inmem/src/inbound/ask_user.rs
@@ -0,0 +1,115 @@
+//! Model-callable adapter for ACP elicitation.
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use tokio::select;
+
+use crate::domain::user_input::{SharedUserInputRequester, UserInputOutcome, UserInputRequest};
+
+/// Context required by [`AskUser`].
+#[derive(Clone)]
+pub struct AskUserContext {
+ /// The active session's user-input port.
+ pub requester: Option<SharedUserInputRequester>,
+}
+
+/// Ask the user one blocking question.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(
+ title = "AskUser",
+ description = "Ask the user for information or a decision that is required before continuing. Use this only when the answer cannot be inferred safely. Pass options for a single-choice question, or omit them for free text. Never request passwords, API keys, authentication codes, payment details, or other secrets."
+)]
+pub struct AskUser {
+ /// The complete, concise question shown to the user.
+ #[schemars(description = "The complete, concise question shown to the user.")]
+ pub question: String,
+ /// Allowed answers for a single-choice question. Empty requests free text.
+ #[serde(default)]
+ #[schemars(
+ description = "Allowed answers for a single-choice question. Omit or pass an empty list to request free text."
+ )]
+ pub options: Vec<String>,
+}
+
+/// Result returned to the model after the user resolves the question.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
+#[serde(tag = "action", rename_all = "snake_case")]
+pub enum AskUserResponse {
+ /// The user supplied an answer.
+ Answered {
+ /// The selected option or entered text.
+ answer: String,
+ },
+ /// The user explicitly declined to answer.
+ Declined,
+ /// The user dismissed the question or stopped the turn.
+ Cancelled,
+}
+
+impl ToolAnnotated for AskUser {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::read_only("Ask user").without_idempotent();
+}
+
+#[async_trait]
+impl AsyncTool<AskUserContext> for AskUser {
+ type Output = AskUserResponse;
+
+ #[tracing::instrument(skip_all, err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<AskUserContext>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let requester = service_context
+ .requester
+ .as_ref()
+ .ok_or_else(|| ToolCallError {
+ description: "This client cannot show an interactive question.".to_owned(),
+ internal_error: anyhow::anyhow!("form elicitation was not advertised"),
+ })?;
+ let question = self.question.trim();
+ if question.is_empty() {
+ return Err(ToolCallError {
+ description: "AskUser requires a non-empty question.".to_owned(),
+ internal_error: anyhow::anyhow!("empty AskUser question"),
+ });
+ }
+ let mut options = Vec::with_capacity(self.options.len());
+ for option in &self.options {
+ let option = option.trim();
+ if !option.is_empty() && !options.iter().any(|existing| existing == option) {
+ options.push(option.to_owned());
+ }
+ }
+
+ let answer = select! {
+ biased;
+ _ = request_context.cancel.cancelled() => {
+ return Ok(AskUserResponse::Cancelled);
+ }
+ answer = requester.ask(UserInputRequest {
+ question: question.to_owned(),
+ options,
+ }) => answer,
+ }
+ .map_err(|error| ToolCallError {
+ description: error.to_string(),
+ internal_error: anyhow::Error::new(error),
+ })?;
+
+ Ok(match answer {
+ UserInputOutcome::Answered(answer) => AskUserResponse::Answered { answer },
+ UserInputOutcome::Declined => AskUserResponse::Declined,
+ UserInputOutcome::Cancelled => AskUserResponse::Cancelled,
+ })
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/agent_inmem/src/inbound/ask_user/test.rs b/crates/agent_inmem/src/inbound/ask_user/test.rs
new file mode 100644
index 0000000000..02684d1e7a
--- /dev/null
+++ b/crates/agent_inmem/src/inbound/ask_user/test.rs
@@ -0,0 +1,178 @@
+use std::sync::{Arc, Mutex};
+
+use ai_toolset::{AsyncTool as _, RequestContext, ServiceContext};
+use async_trait::async_trait;
+use macro_user_id::user_id::MacroUserIdStr;
+
+use super::*;
+use crate::domain::user_input::{UserInputError, UserInputRequester};
+
+struct FakeRequester {
+ requests: Mutex<Vec<UserInputRequest>>,
+ response: UserInputOutcome,
+}
+
+#[async_trait]
+impl UserInputRequester for FakeRequester {
+ async fn ask(&self, request: UserInputRequest) -> Result<UserInputOutcome, UserInputError> {
+ self.requests
+ .lock()
+ .expect("request lock should not be poisoned")
+ .push(request);
+ Ok(self.response.clone())
+ }
+}
+
+fn request_context() -> RequestContext {
+ RequestContext::new(
+ MacroUserIdStr::try_from("macro|[email protected]".to_owned())
+ .expect("test user id should be valid"),
+ )
+}
+
+#[tokio::test]
+async fn asks_through_the_port_and_returns_the_answer() {
+ let requester = Arc::new(FakeRequester {
+ requests: Mutex::new(Vec::new()),
+ response: UserInputOutcome::Answered("blue".to_owned()),
+ });
+ let response = AskUser {
+ question: " What is the best colour? ".to_owned(),
+ options: vec![
+ "red".to_owned(),
+ " blue ".to_owned(),
+ "red".to_owned(),
+ String::new(),
+ ],
+ }
+ .call(
+ ServiceContext(AskUserContext {
+ requester: Some(requester.clone()),
+ }),
+ request_context(),
+ )
+ .await
+ .expect("the question should succeed");
+
+ assert_eq!(
+ response,
+ AskUserResponse::Answered {
+ answer: "blue".to_owned()
+ }
+ );
+ assert_eq!(
+ *requester
+ .requests
+ .lock()
+ .expect("request lock should not be poisoned"),
+ vec![UserInputRequest {
+ question: "What is the best colour?".to_owned(),
+ options: vec!["red".to_owned(), "blue".to_owned()],
+ }]
+ );
+}
+
+#[tokio::test]
+async fn preserves_decline_and_cancel_as_successful_tool_results() {
+ for (outcome, expected) in [
+ (UserInputOutcome::Declined, AskUserResponse::Declined),
+ (UserInputOutcome::Cancelled, AskUserResponse::Cancelled),
+ ] {
+ let response = AskUser {
+ question: "Continue?".to_owned(),
+ options: vec!["yes".to_owned(), "no".to_owned()],
+ }
+ .call(
+ ServiceContext(AskUserContext {
+ requester: Some(Arc::new(FakeRequester {
+ requests: Mutex::new(Vec::new()),
+ response: outcome,
+ })),
+ }),
+ request_context(),
+ )
+ .await
+ .expect("decline and cancel are user decisions, not tool failures");
+ assert_eq!(response, expected);
+ }
+}
+
+#[tokio::test]
+async fn fails_clearly_without_client_support() {
+ let error = AskUser {
+ question: "Continue?".to_owned(),
+ options: Vec::new(),
+ }
+ .call(
+ ServiceContext(AskUserContext { requester: None }),
+ request_context(),
+ )
+ .await
+ .expect_err("an unsupported client cannot be asked");
+
+ assert_eq!(
+ error.description,
+ "This client cannot show an interactive question."
+ );
+}
+
+#[tokio::test]
+async fn rejects_an_empty_question_without_calling_the_port() {
+ let requester = Arc::new(FakeRequester {
+ requests: Mutex::new(Vec::new()),
+ response: UserInputOutcome::Answered("unused".to_owned()),
+ });
+ let error = AskUser {
+ question: " ".to_owned(),
+ options: Vec::new(),
+ }
+ .call(
+ ServiceContext(AskUserContext {
+ requester: Some(requester.clone()),
+ }),
+ request_context(),
+ )
+ .await
+ .expect_err("an empty question should be rejected");
+
+ assert_eq!(error.description, "AskUser requires a non-empty question.");
+ assert!(
+ requester
+ .requests
+ .lock()
+ .expect("request lock should not be poisoned")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn a_cancelled_turn_does_not_start_a_question() {
+ let requester = Arc::new(FakeRequester {
+ requests: Mutex::new(Vec::new()),
+ response: UserInputOutcome::Answered("unused".to_owned()),
+ });
+ let request_context = request_context();
+ request_context.cancel.cancel();
+
+ let response = AskUser {
+ question: "Continue?".to_owned(),
+ options: Vec::new(),
+ }
+ .call(
+ ServiceContext(AskUserContext {
+ requester: Some(requester.clone()),
+ }),
+ request_context,
+ )
+ .await
+ .expect("turn cancellation is a successful cancelled tool result");
+
+ assert_eq!(response, AskUserResponse::Cancelled);
+ assert!(
+ requester
+ .requests
+ .lock()
+ .expect("request lock should not be poisoned")
+ .is_empty()
+ );
+}
diff --git a/crates/agent_inmem/src/inbound/mod.rs b/crates/agent_inmem/src/inbound/mod.rs
new file mode 100644
index 0000000000..a713dff331
--- /dev/null
+++ b/crates/agent_inmem/src/inbound/mod.rs
@@ -0,0 +1,3 @@
+//! Inbound adapters exposed to the in-memory agent's model.
+
+pub mod ask_user;
diff --git a/crates/agent_inmem/src/lib.rs b/crates/agent_inmem/src/lib.rs
index 9d7f0183e1..02c580d194 100644
--- a/crates/agent_inmem/src/lib.rs
+++ b/crates/agent_inmem/src/lib.rs
@@ -12,14 +12,16 @@
//! The seams:
//!
//! - [`domain::engine::TurnEngine`] runs one conversational turn and streams
-//! [`agent::StreamPart`]s back; [`outbound::rig_engine::RigTurnEngine`] is
-//! the production implementation.
+//! [`agent::StreamPart`]s back; [`rig_engine::RigTurnEngine`] is the
+//! production composition root.
//! - [`outbound::manager::InMemAgentManager`] provisions per-session agent
//! tasks and hands the harness the [`agent_runtime_protocol`] transport it
//! expects from any container manager.
#![deny(missing_docs)]
pub mod domain;
+pub mod inbound;
pub mod outbound;
+pub mod rig_engine;
#[cfg(test)]
pub(crate) mod testing;
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index 29251e9335..31cc07a857 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -6,6 +6,7 @@
//! and the conversation store those tasks read.
use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::channel::Channel;
@@ -64,6 +65,7 @@ pub struct InMemAgentManager {
engine: Arc<dyn TurnEngine>,
frames: Arc<dyn FrameSource>,
mcp: Arc<dyn DynMcpToolConnector>,
+ enable_dev_commands: bool,
store: Arc<SessionStore>,
live: DashMap<AgentSessionId, LiveAgent>,
/// Each live session's egress token. An in-process session has no
@@ -88,6 +90,7 @@ impl InMemAgentManager {
engine,
frames,
mcp,
+ enable_dev_commands: false,
store: Arc::new(SessionStore::new()),
live: DashMap::new(),
tokens: DashMap::new(),
@@ -101,6 +104,14 @@ impl InMemAgentManager {
self.tokens.get(&session).map(|token| token.clone())
}
+ /// Enable manual development commands such as `/ask`. Disabled by default;
+ /// the host opts in for its local and development environments.
+ #[must_use]
+ pub fn with_dev_commands(mut self, enabled: bool) -> Self {
+ self.enable_dev_commands = enabled;
+ self
+ }
+
/// Start (or restart) the session's agent and return the transport the
/// harness attaches. Spawn and resume are the same operation here: the
/// conversation store is what persists across reattachment, not the
@@ -144,6 +155,8 @@ impl InMemAgentManager {
turn_lock: tokio::sync::Mutex::new(()),
mcp: Arc::clone(&self.mcp),
mcp_tools: std::sync::Mutex::new(None),
+ client_renders_forms: AtomicBool::new(false),
+ enable_dev_commands: self.enable_dev_commands,
});
let session_id = facts.id;
let task = tokio::spawn(async move {
diff --git a/crates/agent_inmem/src/outbound/mod.rs b/crates/agent_inmem/src/outbound/mod.rs
index 30039024bf..2449f6e45c 100644
--- a/crates/agent_inmem/src/outbound/mod.rs
+++ b/crates/agent_inmem/src/outbound/mod.rs
@@ -1,8 +1,6 @@
-//! Outbound adapters: the production turn engine and the per-session agent
-//! manager.
+//! Outbound adapters for session logging and agent management.
pub mod acp_mcp;
pub mod egress_mcp;
pub mod log_frames;
pub mod manager;
-pub mod rig_engine;
diff --git a/crates/agent_inmem/src/outbound/rig_engine/test.rs b/crates/agent_inmem/src/outbound/rig_engine/test.rs
index d32d525d7f..867d8aef49 100644
--- a/crates/agent_inmem/src/outbound/rig_engine/test.rs
+++ b/crates/agent_inmem/src/outbound/rig_engine/test.rs
@@ -3,6 +3,23 @@ use super::*;
/// A stand-in for the toolset prompt, short enough to assert on positionally.
const TOOLS: &str = "TOOLS";
+fn has_ask_user(supports_user_input: bool) -> bool {
+ let tools = tools_for(AiHost::AgentSession);
+ let base_tools = Arc::into_inner(tools.toolset)
+ .expect("tools_for should return a fresh, uniquely owned collection");
+ tools_for_turn(base_tools, supports_user_input)
+ .request_schemas()
+ .expect("tool schemas should be valid")
+ .iter()
+ .any(|schema| schema.name == "AskUser")
+}
+
+#[test]
+fn ask_user_is_only_advertised_when_the_client_supports_it() {
+ assert!(has_ask_user(true));
+ assert!(!has_ask_user(false));
+}
+
#[test]
fn instructions_are_a_delimited_section_after_the_standing_prompt() {
let prompt = system_prompt(&TOOLS, Some("be terse"), None);
diff --git a/crates/agent_inmem/src/outbound/rig_engine.rs b/crates/agent_inmem/src/rig_engine.rs
similarity index 67%
rename from crates/agent_inmem/src/outbound/rig_engine.rs
rename to crates/agent_inmem/src/rig_engine.rs
index e70d504add..917b81b53b 100644
--- a/crates/agent_inmem/src/outbound/rig_engine.rs
+++ b/crates/agent_inmem/src/rig_engine.rs
@@ -1,5 +1,5 @@
-//! The production turn engine: the shared rig agent loop over the Macro
-//! product toolset.
+//! Composition root for the production turn engine: the shared rig agent loop
+//! over the Macro product toolset.
//!
//! Consumption mirrors the scheduled-action executor
//! (`services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs`):
@@ -7,6 +7,14 @@
//! prompt (immediately before any session instructions), and the owner's
//! memory, with usage recorded per turn against the session owner.
//!
+//! User tools (`SendEmail`, `CreateCalendarEvent`) are the chat host's
+//! deferring ones, finished inside the turn: the turn's [`TurnRequest`]
+//! carries a reviewer over the ACP connection, and the agent loop's
+//! user-tool finisher puts each pending call to it - the session renders the
+//! elicitation - then runs or rejects the tool before the model reads the
+//! result. Without a reviewer (a client with no form support) a pending call
+//! stays pending, as in chat.
+//!
//! This is also where a session's own instructions become a system prompt.
//! Nothing has to be transported for it - the loop runs in this process - which
//! is why the in-memory runtime is the one provider that needs no wire format
@@ -15,8 +23,10 @@
use std::sync::Arc;
use agent::{AgentError, AgentLoop, StreamPart};
+use ai_tools::user_tool_review::user_tool_finisher;
use ai_tools::{AiHost, ToolServiceContext, ToolSetWithPrompt, tools_for};
-use ai_toolset::ToolSet as AiToolSet;
+use ai_toolset::{AsyncToolCollection, ToolSet as AiToolSet};
+use axum::extract::FromRef;
use futures::StreamExt as _;
use macro_user_id::user_id::MacroUserIdStr;
use memory::domain::MemoryService as _;
@@ -26,8 +36,10 @@ use sqlx::PgPool;
use tokio::sync::mpsc;
use crate::domain::engine::{TurnEngine, TurnRequest};
+use crate::inbound::ask_user::{AskUser, AskUserContext};
#[cfg(test)]
+#[path = "outbound/rig_engine/test.rs"]
mod test;
/// How many stream parts may sit unread before the engine pauses; keeps a
@@ -35,7 +47,7 @@ mod test;
const PART_BUFFER: usize = 256;
/// [`TurnEngine`] backed by [`agent::AgentLoop`] and
-/// [`ai_tools::all_tools`].
+/// [`ai_tools::tools_for`].
pub struct RigTurnEngine {
db: PgPool,
tool_context: ToolServiceContext,
@@ -50,6 +62,36 @@ impl RigTurnEngine {
}
}
+#[derive(Clone)]
+struct InMemToolContext {
+ base: ToolServiceContext,
+ ask_user: AskUserContext,
+}
+
+impl FromRef<InMemToolContext> for ToolServiceContext {
+ fn from_ref(context: &InMemToolContext) -> Self {
+ context.base.clone()
+ }
+}
+
+impl FromRef<InMemToolContext> for AskUserContext {
+ fn from_ref(context: &InMemToolContext) -> Self {
+ context.ask_user.clone()
+ }
+}
+
+fn tools_for_turn(
+ base_tools: ai_tools::AiToolSet,
+ supports_user_input: bool,
+) -> AsyncToolCollection<InMemToolContext> {
+ let tools = AsyncToolCollection::<InMemToolContext>::new().add_subtoolset(base_tools);
+ if supports_user_input {
+ tools.add_tool::<AskUser, AskUserContext>()
+ } else {
+ tools
+ }
+}
+
impl TurnEngine for RigTurnEngine {
fn run_turn(&self, request: TurnRequest) -> mpsc::Receiver<Result<StreamPart, AgentError>> {
let (parts, receiver) = mpsc::channel(PART_BUFFER);
@@ -77,9 +119,14 @@ async fn drive_turn(
messages,
mcp_tools,
cancel,
+ user_input,
+ reviewer,
} = request;
- let tools = tools_for(AiHost::Chat);
+ // Chat's tools with the session's prompt: the user tools (`SendEmail`,
+ // `CreateCalendarEvent`) defer to the user, and this runtime finishes
+ // them in the turn through `reviewer`.
+ let tools = tools_for(AiHost::AgentSession);
let user_memory = fetch_user_memory(&db, &base_context, &owner).await;
let system_prompt = system_prompt(
&tools.prompt,
@@ -87,18 +134,39 @@ async fn drive_turn(
user_memory.as_deref(),
);
- // The MCP servers the session was handed sit next to the native tools
- // the way they do in chat: static tools on every request, MCP tools in
- // the searchable catalog behind `SearchTools`.
- let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = match mcp_tools {
- Some(mcp) => Arc::new(mcp_select::CombinedToolSet::new(tools.toolset, mcp)),
- None => tools.toolset,
- };
- let agent_loop = AgentLoop::new(base_context.recorder.clone()).with_model(&model);
- let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::AgentSession, owner);
+ // `tools_for` returns a fresh Arc. Take its collection back so the
+ // in-memory runtime can widen it onto the session-specific context and
+ // add the one tool that needs the active ACP connection.
+ let base_tools = Arc::into_inner(tools.toolset)
+ .expect("tools_for should return a fresh, uniquely owned collection");
+ let toolset = Arc::new(tools_for_turn(base_tools, user_input.is_some()));
+ let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::AgentSession, owner.clone());
// Carry the feature on the context so tool-spawned subagents attribute to it.
- let mut tool_context = base_context;
+ let mut tool_context = base_context.clone();
tool_context.usage_context = usage_ctx.clone();
+ let tool_context = InMemToolContext {
+ base: tool_context,
+ ask_user: AskUserContext {
+ requester: user_input,
+ },
+ };
+
+ let mut agent_loop = AgentLoop::new(base_context.recorder.clone()).with_model(&model);
+ if let Some(reviewer) = reviewer {
+ agent_loop = agent_loop.with_user_tool_finisher(user_tool_finisher(
+ Arc::clone(&toolset),
+ tool_context.clone(),
+ owner,
+ reviewer,
+ cancel.clone(),
+ ));
+ }
+ // Keep remote MCP tools alongside the native and AskUser tools. The
+ // finisher above reviews only Macro's native user tools.
+ let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = match mcp_tools {
+ Some(mcp) => Arc::new(mcp_select::CombinedToolSet::new(toolset, mcp)),
+ None => toolset,
+ };
let session = agent_loop
.session(toolset, Arc::new(tool_context), &system_prompt, usage_ctx)
.await;
diff --git a/crates/agent_runtime_protocol/src/domain/action.rs b/crates/agent_runtime_protocol/src/domain/action.rs
index 2d5ef94f51..40c3fdc03d 100644
--- a/crates/agent_runtime_protocol/src/domain/action.rs
+++ b/crates/agent_runtime_protocol/src/domain/action.rs
@@ -3,9 +3,12 @@
//! An action can be accepted and queued before there is any way to express it
//! as ACP, since that needs the [`SessionId`] the handshake produces.
+use std::collections::BTreeMap;
+
use agent_client_protocol::schema::v1::{
- CancelNotification, ClientRequest, PromptRequest, RequestId, SessionId,
- SetSessionConfigOptionRequest,
+ CancelNotification, ClientRequest, CreateElicitationResponse, ElicitationAcceptAction,
+ ElicitationAction, ElicitationContentValue as AcpContentValue, PromptRequest, RequestId,
+ SessionId, SetSessionConfigOptionRequest,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
use macro_uuid::Uuid;
@@ -144,8 +147,124 @@ impl AgentSetModelAction {
}
}
+/// The JSON-RPC id of an agent's `elicitation/create` request, carried whole
+/// so the answer echoes exactly what the agent sent.
+///
+/// Agents pick these, not us: Claude Code counts from `0`, others use
+/// strings. `null` is not a legal id for a request that expects a response,
+/// so it is not representable here.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, specta::Type)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(untagged)]
+pub enum ElicitationRequestId {
+ /// A numeric JSON-RPC id. Specta refuses `i64` (it does not fit a JS
+ /// number); agents count their requests from zero, so `i32` is the
+ /// honest TypeScript face.
+ Number(#[specta(type = i32)] i64),
+ /// A string JSON-RPC id.
+ Str(String),
+}
+
+impl ElicitationRequestId {
+ /// The id as the agent sent it. `None` for `null`, which cannot be
+ /// answered.
+ #[must_use]
+ pub fn from_request_id(id: &RequestId) -> Option<Self> {
+ match id {
+ RequestId::Number(number) => Some(Self::Number(*number)),
+ RequestId::Str(id) => Some(Self::Str(id.clone())),
+ RequestId::Null => None,
+ }
+ }
+
+ /// The same id as the transport's request id type.
+ #[must_use]
+ pub fn to_request_id(&self) -> RequestId {
+ match self {
+ Self::Number(number) => RequestId::Number(*number),
+ Self::Str(id) => RequestId::Str(id.clone()),
+ }
+ }
+}
+
+impl std::fmt::Display for ElicitationRequestId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Number(number) => write!(f, "{number}"),
+ Self::Str(id) => f.write_str(id),
+ }
+ }
+}
+
+/// A value ACP accepts in an elicitation answer.
+///
+/// Mirrors ACP's `ElicitationContentValue` so that the contract a caller
+/// answers against is the closed union ACP will accept, rather than arbitrary
+/// JSON narrowed on the way out. An object, a null, or a mixed array is
+/// refused when the request is deserialized - where the caller learns of it -
+/// instead of at send time, when the elicitation slot has already been
+/// released.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(untagged)]
+pub enum ElicitationContentValue {
+ /// A string, and the shape a whole draft rides in as JSON text.
+ Text(String),
+ /// A yes/no.
+ Boolean(bool),
+ /// A whole number.
+ Integer(i64),
+ /// A number that is not whole.
+ Number(f64),
+ /// A multi-select's chosen values.
+ Strings(Vec<String>),
+}
+
+impl From<&ElicitationContentValue> for AcpContentValue {
+ fn from(value: &ElicitationContentValue) -> Self {
+ match value {
+ ElicitationContentValue::Text(text) => Self::String(text.clone()),
+ ElicitationContentValue::Boolean(flag) => Self::Boolean(*flag),
+ ElicitationContentValue::Integer(number) => Self::Integer(*number),
+ ElicitationContentValue::Number(number) => Self::Number(*number),
+ ElicitationContentValue::Strings(values) => Self::StringArray(values.clone()),
+ }
+ }
+}
+
+/// What the user decided about an elicitation. Mirrors ACP's three actions;
+/// there is no `Other` because we never originate an action we do not know.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(tag = "action", rename_all = "snake_case")]
+pub enum ElicitationAnswer {
+ /// The user submitted the form, or consented to open the URL.
+ Accept {
+ /// Form: the submitted values keyed by property. URL: omitted.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ content: Option<BTreeMap<String, ElicitationContentValue>>,
+ },
+ /// The user explicitly said no.
+ Decline,
+ /// The user dismissed the request without choosing.
+ Cancel,
+}
+
+/// Answer an elicitation the agent is waiting on.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct AgentRespondElicitationAction {
+ /// The agent's `elicitation/create` request id - not an
+ /// [`AgentActionId`], because the agent minted it.
+ pub request_id: ElicitationRequestId,
+ /// The decision.
+ #[serde(flatten)]
+ pub answer: ElicitationAnswer,
+}
+
/// One thing a caller wants an agent to do.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::AsRefStr)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, strum::AsRefStr)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde(tag = "type", rename_all = "camelCase")]
#[strum(serialize_all = "snake_case")]
@@ -158,6 +277,13 @@ pub enum AgentAction {
Compact,
/// Interrupt whatever the agent is doing.
Stop,
+ /// Answer an `elicitation/create` the agent sent.
+ ///
+ /// The one action whose wire form is a JSON-RPC *response* rather than a
+ /// request or notification: the agent asked, we answer on its id. The
+ /// minted [`AgentActionId`] therefore never reaches the wire for this
+ /// action; the fold correlates on the agent's id instead.
+ RespondElicitation(AgentRespondElicitationAction),
}
impl AgentAction {
@@ -176,6 +302,14 @@ impl AgentAction {
})
}
+ /// Answer the elicitation the agent asked with `request_id`.
+ pub fn respond_elicitation(
+ request_id: ElicitationRequestId,
+ answer: ElicitationAnswer,
+ ) -> Self {
+ Self::RespondElicitation(AgentRespondElicitationAction { request_id, answer })
+ }
+
/// Recognize a control action from its translated runtime frame.
///
/// Ordinary prompts are deliberately excluded: callers need their full
@@ -223,7 +357,9 @@ impl AgentAction {
pub fn occupies_turn(&self) -> bool {
match self {
Self::Prompt(_) | Self::Compact => true,
- Self::SetModel(_) | Self::Stop => false,
+ // An elicitation answer is the running turn's own business: the
+ // agent is blocked on it mid-turn, so it must ride alongside.
+ Self::SetModel(_) | Self::Stop | Self::RespondElicitation(_) => false,
}
}
@@ -279,6 +415,43 @@ impl AgentAction {
.map_err(|error| ActionError::Acp(error.to_string()))?;
Ok(ToRuntimeMessage::Acp(AcpMessage(frame)))
}
+ // A response to the agent's own request: `request_id` is the
+ // minted action id and is deliberately unused - the frame must
+ // carry the id the agent asked with, or nothing answers it.
+ Self::RespondElicitation(action) => {
+ let response = action.to_acp_response();
+ let result = serde_json::to_value(&response)
+ .map_err(|error| ActionError::Acp(error.to_string()))?;
+ let frame =
+ RawJsonRpcMessage::response(action.request_id.to_request_id(), Ok(result));
+ Ok(ToRuntimeMessage::Acp(AcpMessage(frame)))
+ }
}
}
}
+
+impl AgentRespondElicitationAction {
+ /// The ACP response body for this answer.
+ ///
+ /// Total: every value the type can hold is one ACP accepts, so answering
+ /// cannot fail here. That matters because the session machine releases the
+ /// elicitation slot before this runs - a failure would leave the agent
+ /// blocked on a request nothing can answer any more.
+ #[must_use]
+ pub fn to_acp_response(&self) -> CreateElicitationResponse {
+ let action = match &self.answer {
+ ElicitationAnswer::Accept { content } => {
+ let content = content.as_ref().map(|content| {
+ content
+ .iter()
+ .map(|(key, value)| (key.clone(), AcpContentValue::from(value)))
+ .collect::<BTreeMap<_, _>>()
+ });
+ ElicitationAction::Accept(ElicitationAcceptAction::new().content(content))
+ }
+ ElicitationAnswer::Decline => ElicitationAction::Decline,
+ ElicitationAnswer::Cancel => ElicitationAction::Cancel,
+ };
+ CreateElicitationResponse::new(action)
+ }
+}
diff --git a/crates/agent_runtime_protocol/src/domain/action/test.rs b/crates/agent_runtime_protocol/src/domain/action/test.rs
index a0afffda40..b1f54cfb12 100644
--- a/crates/agent_runtime_protocol/src/domain/action/test.rs
+++ b/crates/agent_runtime_protocol/src/domain/action/test.rs
@@ -1,3 +1,4 @@
+use super::ElicitationContentValue as ContentValue;
use agent_client_protocol::schema::v1::{ClientRequest, ContentBlock, SessionId};
use super::*;
@@ -144,4 +145,182 @@ fn only_prompt_shaped_actions_occupy_a_turn() {
assert!(AgentAction::Compact.occupies_turn());
assert!(!AgentAction::set_model("opus").occupies_turn());
assert!(!AgentAction::Stop.occupies_turn());
+ assert!(
+ !AgentAction::respond_elicitation(
+ ElicitationRequestId::Number(0),
+ ElicitationAnswer::Cancel
+ )
+ .occupies_turn(),
+ "an answer rides alongside the turn that is waiting on it"
+ );
+}
+
+#[test]
+fn an_elicitation_answer_is_a_response_on_the_agents_own_id() {
+ use agent_client_protocol::schema::v1::{
+ CreateElicitationResponse, ElicitationAction, ElicitationContentValue, Response,
+ };
+
+ let session_id = SessionId::new("acp-abc");
+ let content = BTreeMap::from([
+ (
+ "strategy".to_owned(),
+ ContentValue::Text("balanced".to_owned()),
+ ),
+ ("port".to_owned(), ContentValue::Integer(3000)),
+ ("ratio".to_owned(), ContentValue::Number(0.5)),
+ ("logging".to_owned(), ContentValue::Boolean(true)),
+ (
+ "colours".to_owned(),
+ ContentValue::Strings(vec!["red".to_owned(), "blue".to_owned()]),
+ ),
+ ]);
+ let translated = AgentAction::respond_elicitation(
+ ElicitationRequestId::Number(0),
+ ElicitationAnswer::Accept {
+ content: Some(content),
+ },
+ )
+ .to_runtime(
+ &session_id,
+ RequestId::Str("agent_session:ignored".to_owned()),
+ )
+ .unwrap();
+
+ // Claude Code numbers its elicitations from 0; the answer must echo that
+ // id exactly, not the minted action id.
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(Response::Result {
+ id,
+ result,
+ }))) = translated
+ else {
+ panic!("an elicitation answer translates to a JSON-RPC result");
+ };
+ assert_eq!(id, RequestId::Number(0));
+
+ let response: CreateElicitationResponse = serde_json::from_value(result).unwrap();
+ let ElicitationAction::Accept(accept) = response.action else {
+ panic!("accept round-trips as accept, got {:?}", response.action);
+ };
+ let content = accept.content.unwrap();
+ assert_eq!(
+ content["strategy"],
+ ElicitationContentValue::String("balanced".to_owned())
+ );
+ assert_eq!(content["port"], ElicitationContentValue::Integer(3000));
+ assert_eq!(content["ratio"], ElicitationContentValue::Number(0.5));
+ assert_eq!(content["logging"], ElicitationContentValue::Boolean(true));
+ assert_eq!(
+ content["colours"],
+ ElicitationContentValue::StringArray(vec!["red".to_owned(), "blue".to_owned()])
+ );
+}
+
+#[test]
+fn decline_and_cancel_carry_no_content_and_string_ids_survive() {
+ use agent_client_protocol::schema::v1::Response;
+
+ for (answer, action) in [
+ (ElicitationAnswer::Decline, "decline"),
+ (ElicitationAnswer::Cancel, "cancel"),
+ ] {
+ let translated =
+ AgentAction::respond_elicitation(ElicitationRequestId::Str("el-7".to_owned()), answer)
+ .to_runtime(
+ &SessionId::new("acp-abc"),
+ RequestId::Str("unused".to_owned()),
+ )
+ .unwrap();
+ let ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(Response::Result {
+ id,
+ result,
+ }))) = translated
+ else {
+ panic!("an elicitation answer translates to a JSON-RPC result");
+ };
+ assert_eq!(id, RequestId::Str("el-7".to_owned()));
+ assert_eq!(result, serde_json::json!({ "action": action }));
+ }
+}
+
+/// A value ACP cannot express is refused where the caller finds out about it -
+/// reading the control request - rather than on the way to the wire, by which
+/// point the session has already released the elicitation slot and the agent
+/// would wait on a request nothing can answer.
+#[test]
+fn content_acp_cannot_express_is_refused_when_the_request_is_read() {
+ for unrepresentable in [
+ serde_json::json!({ "a": 1 }),
+ serde_json::json!(null),
+ serde_json::json!(["a", 1]),
+ ] {
+ let body = serde_json::json!({
+ "type": "respondElicitation",
+ "requestId": 1,
+ "action": "accept",
+ "content": { "field": unrepresentable },
+ });
+ assert!(
+ serde_json::from_value::<AgentAction>(body).is_err(),
+ "{unrepresentable} is not an ACP content value"
+ );
+ }
+}
+
+#[test]
+fn the_control_body_for_an_answer_reads_as_documented() {
+ let action: AgentAction = serde_json::from_value(serde_json::json!({
+ "type": "respondElicitation",
+ "requestId": 43,
+ "action": "accept",
+ "content": { "strategy": "balanced" }
+ }))
+ .unwrap();
+ assert_eq!(
+ action,
+ AgentAction::respond_elicitation(
+ ElicitationRequestId::Number(43),
+ ElicitationAnswer::Accept {
+ content: Some(BTreeMap::from([(
+ "strategy".to_owned(),
+ ContentValue::Text("balanced".to_owned())
+ )])),
+ },
+ )
+ );
+
+ let action: AgentAction = serde_json::from_value(serde_json::json!({
+ "type": "respondElicitation",
+ "requestId": "el-7",
+ "action": "decline"
+ }))
+ .unwrap();
+ assert_eq!(
+ action,
+ AgentAction::respond_elicitation(
+ ElicitationRequestId::Str("el-7".to_owned()),
+ ElicitationAnswer::Decline,
+ )
+ );
+ assert_eq!(
+ serde_json::to_value(&action).unwrap(),
+ serde_json::json!({ "type": "respondElicitation", "requestId": "el-7", "action": "decline" })
+ );
+}
+
+#[test]
+fn elicitation_ids_round_trip_and_null_is_unanswerable() {
+ assert_eq!(
+ ElicitationRequestId::from_request_id(&RequestId::Number(0)),
+ Some(ElicitationRequestId::Number(0))
+ );
+ assert_eq!(
+ ElicitationRequestId::from_request_id(&RequestId::Str("x".to_owned()))
+ .map(|id| id.to_request_id()),
+ Some(RequestId::Str("x".to_owned()))
+ );
+ assert_eq!(
+ ElicitationRequestId::from_request_id(&RequestId::Null),
+ None
+ );
}
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index 07f8674f69..a0a1d6e84f 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -36,6 +36,11 @@ pub enum AgentSessionError {
"agent session {0} cannot be restored because the agent supports neither session/resume nor session/load"
)]
ResumeUnsupported(AgentSessionId),
+ /// The answer names an elicitation the live connection is not holding:
+ /// already answered, cancelled by a stop, lost with the connection, or
+ /// never asked.
+ #[error("agent session {0} has no pending elicitation matching that request id")]
+ ElicitationNotPending(AgentSessionId),
#[error("agent session {0} action delivery timed out")]
DeliveryTimedOut(AgentSessionId),
#[error("agent session {0} log persistence timed out")]
diff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rs
index 20643b4290..dba63a6c19 100644
--- a/crates/agent_session/src/domain/session/session.rs
+++ b/crates/agent_session/src/domain/session/session.rs
@@ -3,10 +3,12 @@
use std::collections::VecDeque;
use agent_client_protocol::schema::v1::{
- InitializeRequest, InitializeResponse, LoadSessionRequest, LoadSessionResponse, McpServer,
- NewSessionRequest, NewSessionResponse, PermissionOptionKind, RequestId,
- RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse, Response,
- ResumeSessionRequest, ResumeSessionResponse, SelectedPermissionOutcome, SessionId,
+ ClientCapabilities, CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
+ ElicitationCapabilities, ElicitationFormCapabilities, ElicitationMode, ElicitationScope,
+ ElicitationUrlCapabilities, InitializeRequest, InitializeResponse, LoadSessionRequest,
+ LoadSessionResponse, McpServer, NewSessionRequest, NewSessionResponse, PermissionOptionKind,
+ RequestId, RequestPermissionOutcome, RequestPermissionRequest, RequestPermissionResponse,
+ Response, ResumeSessionRequest, ResumeSessionResponse, SelectedPermissionOutcome, SessionId,
};
use agent_client_protocol::{JsonRpcMessage, RawJsonRpcMessage};
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
@@ -20,8 +22,8 @@ use crate::domain::error::AgentSessionError;
use crate::domain::model::AgentSessionId;
use super::types::{
- CloseReason, Effect, Input, PendingAction, RuntimeStatus, SessionOpening, SessionPhase,
- SessionRestoreSupport, StopReason,
+ CloseReason, Effect, Input, PendingAction, PendingElicitation, RuntimeStatus, SessionOpening,
+ SessionPhase, SessionRestoreSupport, StopReason,
};
const INITIAL_REQUEST_NUM: u64 = 0;
@@ -122,7 +124,7 @@ impl<Token> SessionMachine<Token> {
SessionPhase::Initializing { .. } | SessionPhase::Opening { .. } => {
RuntimeStatus::Handshaking
}
- SessionPhase::Live { session_id } => RuntimeStatus::Live {
+ SessionPhase::Live { session_id, .. } => RuntimeStatus::Live {
session_id: session_id.clone(),
},
SessionPhase::Dead => RuntimeStatus::Dead,
@@ -134,6 +136,18 @@ impl<Token> SessionMachine<Token> {
self.pending.len()
}
+ /// The id of the elicitation this connection is holding for the user, if
+ /// any.
+ pub fn pending_elicitation(&self) -> Option<&RequestId> {
+ match &self.phase {
+ SessionPhase::Live {
+ elicitation: Some(pending),
+ ..
+ } => Some(&pending.request_id),
+ _ => None,
+ }
+ }
+
/// Advance the machine by one input, returning the effects it implies.
pub fn handle(&mut self, input: Input<Token>) -> Vec<Effect<Token>> {
match input {
@@ -179,10 +193,27 @@ impl<Token> SessionMachine<Token> {
) -> Vec<Effect<Token>> {
let mut effects = Vec::new();
+ // A stop cancels the question the agent is waiting on, and does so
+ // before the cancel notification goes out, so the agent hears the
+ // answer to its request before it hears that the turn is over.
+ if matches!(action, AgentAction::Stop) {
+ self.cancel_pending_elicitation(from.clone(), &mut effects);
+ }
+
let session_id = match &self.phase {
SessionPhase::Booting
| SessionPhase::Initializing { .. }
| SessionPhase::Opening { .. } => {
+ // An answer cannot be queued: it names a request id that only
+ // a live connection could have received, and any connection
+ // that opens from here is a fresh one.
+ if let AgentAction::RespondElicitation(_) = &action {
+ effects.push(Effect::Complete {
+ token,
+ result: Err(AgentSessionError::ElicitationNotPending(self.id)),
+ });
+ return effects;
+ }
self.pending.push_back(PendingAction {
from,
action,
@@ -191,7 +222,7 @@ impl<Token> SessionMachine<Token> {
});
return effects;
}
- SessionPhase::Live { session_id } => session_id.clone(),
+ SessionPhase::Live { session_id, .. } => session_id.clone(),
SessionPhase::Dead => {
effects.push(Effect::Complete {
token,
@@ -201,6 +232,26 @@ impl<Token> SessionMachine<Token> {
}
};
+ // An answer must match the one elicitation being held, and answering
+ // it releases the slot before the response goes out.
+ if let AgentAction::RespondElicitation(answer) = &action {
+ let matches = matches!(
+ &self.phase,
+ SessionPhase::Live { elicitation: Some(pending), .. }
+ if pending.request_id == answer.request_id.to_request_id()
+ );
+ if !matches {
+ effects.push(Effect::Complete {
+ token,
+ result: Err(AgentSessionError::ElicitationNotPending(self.id)),
+ });
+ return effects;
+ }
+ if let SessionPhase::Live { elicitation, .. } = &mut self.phase {
+ *elicitation = None;
+ }
+ }
+
// Through the queue even when live, so an action can never overtake
// one accepted earlier. (A completed flush leaves the queue empty, so
// the flush below sends exactly this action.)
@@ -260,7 +311,7 @@ impl<Token> SessionMachine<Token> {
}
fn begin_reload(&mut self, effects: &mut Vec<Effect<Token>>) {
- let SessionPhase::Live { session_id } = &self.phase else {
+ let SessionPhase::Live { session_id, .. } = &self.phase else {
return;
};
self.resume_session_id = Some(session_id.clone());
@@ -309,6 +360,7 @@ impl<Token> SessionMachine<Token> {
return;
}
self.respond_to_permission_request(&frame, effects);
+ self.hold_or_refuse_elicitation(&frame, effects);
return;
}
@@ -445,6 +497,7 @@ impl<Token> SessionMachine<Token> {
self.phase = SessionPhase::Live {
session_id: session_id.clone(),
+ elicitation: None,
};
if persist {
effects.push(Effect::PersistAcpSession {
@@ -503,7 +556,18 @@ impl<Token> SessionMachine<Token> {
fn build_initialize_request(
&mut self,
) -> std::result::Result<(RawJsonRpcMessage, RequestId), agent_client_protocol::Error> {
+ // Both elicitation modes are advertised: the session page renders
+ // forms and opens URLs after consent. Agents that check (they must)
+ // will only ask once this says they may - so this line must never
+ // ship ahead of `hold_or_refuse_elicitation`, or every agent that
+ // asks hangs on a request nothing answers.
+ let capabilities = ClientCapabilities::new().elicitation(
+ ElicitationCapabilities::new()
+ .form(ElicitationFormCapabilities::new())
+ .url(ElicitationUrlCapabilities::new()),
+ );
let (method, params) = InitializeRequest::new(PROTOCOL_VERSION)
+ .client_capabilities(capabilities)
.to_untyped_message()?
.into_parts();
let request_id = self.next_id();
@@ -574,6 +638,114 @@ impl<Token> SessionMachine<Token> {
});
}
+ /// An `elicitation/create` is held for the user rather than answered - the
+ /// one agent request this machine does not resolve on its own. What
+ /// cannot be held is refused on the spot with `-32602`, the code the
+ /// protocol names for a mode the client did not advertise: a request
+ /// this machine cannot parse, a mode it does not render, a request
+ /// scoped outside any session, one for another session on the same
+ /// connection, or a second question while the first is still open.
+ fn hold_or_refuse_elicitation(
+ &mut self,
+ frame: &RawJsonRpcMessage,
+ effects: &mut Vec<Effect<Token>>,
+ ) {
+ let RawJsonRpcMessage::Request(request) = frame else {
+ return;
+ };
+ if !CreateElicitationRequest::matches_method(&request.method) {
+ return;
+ }
+ let SessionPhase::Live {
+ session_id,
+ elicitation,
+ } = &mut self.phase
+ else {
+ return;
+ };
+
+ let parsed = request
+ .params
+ .clone()
+ .ok_or("an elicitation needs params")
+ .and_then(|params| {
+ serde_json::from_value::<CreateElicitationRequest>(params.into_value())
+ .map_err(|_| "the elicitation did not parse")
+ });
+ let refusal = match parsed {
+ Err(reason) => Some(reason),
+ Ok(elicitation_request) => {
+ let scope = match &elicitation_request.mode {
+ ElicitationMode::Form(form) => Some(&form.scope),
+ ElicitationMode::Url(url) => Some(&url.scope),
+ // `#[non_exhaustive]`: an `Other` mode, or one ACP adds later.
+ _ => None,
+ };
+ match scope {
+ None => Some("this client renders only form and url elicitations"),
+ Some(ElicitationScope::Request(_)) => {
+ Some("request-scoped elicitation is not supported")
+ }
+ Some(ElicitationScope::Session(scope)) if &scope.session_id != session_id => {
+ Some("the elicitation names another session")
+ }
+ Some(ElicitationScope::Session(_)) if elicitation.is_some() => {
+ Some("one elicitation at a time")
+ }
+ Some(ElicitationScope::Session(_)) => None,
+ // `#[non_exhaustive]` scope.
+ Some(_) => Some("unrecognized elicitation scope"),
+ }
+ }
+ };
+
+ match refusal {
+ None => {
+ *elicitation = Some(PendingElicitation {
+ request_id: request.id.clone(),
+ });
+ }
+ Some(reason) => {
+ let error = agent_client_protocol::Error::invalid_params().data(reason);
+ effects.push(Effect::Send {
+ from: None,
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
+ request.id.clone(),
+ Err(error),
+ ))),
+ });
+ }
+ }
+ }
+
+ /// Answer the held elicitation with `cancel` and release the slot. What a
+ /// stop does before its cancel notification, so the agent's request is
+ /// resolved rather than left dangling on a turn that is ending anyway.
+ fn cancel_pending_elicitation(
+ &mut self,
+ from: Option<MacroUserIdStr<'static>>,
+ effects: &mut Vec<Effect<Token>>,
+ ) {
+ let SessionPhase::Live { elicitation, .. } = &mut self.phase else {
+ return;
+ };
+ let Some(pending) = elicitation.take() else {
+ return;
+ };
+ let Ok(result) =
+ serde_json::to_value(CreateElicitationResponse::new(ElicitationAction::Cancel))
+ else {
+ return;
+ };
+ effects.push(Effect::Send {
+ from,
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
+ pending.request_id,
+ Ok(result),
+ ))),
+ });
+ }
+
/// Send everything queued, oldest first. Each action's [`Effect::Complete`]
/// directly follows its [`Effect::Send`], so the shell aborting a batch
/// mid-way strands no false completions - and an action that cannot be
diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rs
index 74f0232054..9ed18b7f38 100644
--- a/crates/agent_session/src/domain/session/tests.rs
+++ b/crates/agent_session/src/domain/session/tests.rs
@@ -1192,3 +1192,348 @@ fn late_load_response_from_a_previous_actor_cannot_select_history() {
matches!(completed[0], Effect::Log { boundary: Some(crate::domain::model::HistoryBoundary { initialization_log_id: id }), .. } if id == initialization_log_id)
);
}
+
+// ---------------------------------------------------------------------------
+// Elicitation: held for the user, never answered by the machine itself.
+// ---------------------------------------------------------------------------
+
+mod elicitation {
+ use super::*;
+ use agent_client_protocol::schema::v1::{
+ ClientRequest, CreateElicitationRequest, CreateElicitationResponse, ElicitationAction,
+ ElicitationFormMode, ElicitationRequestScope, ElicitationSchema, ElicitationSessionScope,
+ ElicitationUrlMode, InitializeRequest, SessionId,
+ };
+ use agent_runtime_protocol::domain::action::{ElicitationAnswer, ElicitationRequestId};
+ use std::collections::BTreeMap;
+
+ fn live_machine() -> SessionMachine<u32> {
+ let mut machine = machine();
+ begin_opening(&mut machine);
+ machine.handle(session_opened("acp-42"));
+ machine
+ }
+
+ fn create(id: RequestId, request: CreateElicitationRequest) -> Input<u32> {
+ let (method, params) = request.to_untyped_message().unwrap().into_parts();
+ frame(RawJsonRpcMessage::request(method, params, id).unwrap())
+ }
+
+ fn form_for(session: &'static str) -> CreateElicitationRequest {
+ CreateElicitationRequest::new(
+ ElicitationFormMode::new(
+ ElicitationSessionScope::new(SessionId::new(session)),
+ ElicitationSchema::new(),
+ ),
+ "Which approach?",
+ )
+ }
+
+ fn answer(id: ElicitationRequestId, answer: ElicitationAnswer, token: u32) -> Input<u32> {
+ Input::Command {
+ from: Some(
+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id"),
+ ),
+ action: AgentAction::respond_elicitation(id, answer),
+ action_id: AgentActionId::mint(),
+ token,
+ }
+ }
+
+ /// Every JSON-RPC response the machine sent, as `(id, result)`.
+ fn sent_responses(
+ effects: &[Effect<u32>],
+ ) -> Vec<(
+ RequestId,
+ Result<serde_json::Value, agent_client_protocol::Error>,
+ )> {
+ effects
+ .iter()
+ .filter_map(|effect| match effect {
+ Effect::Send {
+ message:
+ ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(
+ Response::Result { id, result },
+ ))),
+ ..
+ } => Some((id.clone(), Ok(result.clone()))),
+ Effect::Send {
+ message:
+ ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(
+ Response::Error { id, error },
+ ))),
+ ..
+ } => Some((id.clone(), Err(error.clone()))),
+ _ => None,
+ })
+ .collect()
+ }
+
+ fn refusals(effects: &[Effect<u32>]) -> Vec<RequestId> {
+ sent_responses(effects)
+ .into_iter()
+ .filter_map(|(id, result)| match result {
+ Err(error) if error.code == agent_client_protocol::ErrorCode::InvalidParams => {
+ Some(id)
+ }
+ _ => None,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn initialize_advertises_both_elicitation_modes() {
+ let mut machine = machine();
+ let effects = machine.handle(acp_ready());
+ let Effect::Send {
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))),
+ ..
+ } = &effects[1]
+ else {
+ panic!("initialize is sent");
+ };
+ let ClientRequest::InitializeRequest(initialize) =
+ ClientRequest::parse_message(&request.method, &request.params).unwrap()
+ else {
+ panic!("the first request is initialize");
+ };
+ let _: &InitializeRequest = &initialize;
+ let elicitation = initialize
+ .client_capabilities
+ .elicitation
+ .expect("elicitation is advertised");
+ assert!(elicitation.form.is_some(), "form mode is advertised");
+ assert!(elicitation.url.is_some(), "url mode is advertised");
+
+ // And on the wire, exactly the shape the protocol documents.
+ let params = serde_json::to_value(&request.params).unwrap();
+ assert_eq!(
+ params["clientCapabilities"]["elicitation"],
+ serde_json::json!({ "form": {}, "url": {} })
+ );
+ }
+
+ #[test]
+ fn a_form_elicitation_is_held_not_answered() {
+ let mut machine = live_machine();
+
+ let effects = machine.handle(create(RequestId::Number(0), form_for("acp-42")));
+
+ assert!(
+ matches!(effects[..], [Effect::Log { .. }]),
+ "held: {effects:?}"
+ );
+ assert_eq!(machine.pending_elicitation(), Some(&RequestId::Number(0)));
+ assert!(matches!(machine.status(), RuntimeStatus::Live { .. }));
+ }
+
+ #[test]
+ fn a_url_elicitation_is_held_too() {
+ let mut machine = live_machine();
+ let request = CreateElicitationRequest::new(
+ ElicitationUrlMode::new(
+ ElicitationSessionScope::new(SessionId::new("acp-42")),
+ "github-oauth-1",
+ "https://agent.example.com/connect?elicitationId=github-oauth-1",
+ ),
+ "Authorize GitHub",
+ );
+
+ let effects = machine.handle(create(RequestId::Str("el-1".to_owned()), request));
+
+ assert!(matches!(effects[..], [Effect::Log { .. }]));
+ assert_eq!(
+ machine.pending_elicitation(),
+ Some(&RequestId::Str("el-1".to_owned()))
+ );
+ }
+
+ #[test]
+ fn a_second_elicitation_while_one_is_held_is_refused_and_the_first_kept() {
+ let mut machine = live_machine();
+ machine.handle(create(RequestId::Number(0), form_for("acp-42")));
+
+ let effects = machine.handle(create(RequestId::Number(1), form_for("acp-42")));
+
+ assert_eq!(refusals(&effects), [RequestId::Number(1)]);
+ assert_eq!(machine.pending_elicitation(), Some(&RequestId::Number(0)));
+ }
+
+ #[test]
+ fn request_scoped_and_foreign_session_elicitations_are_refused() {
+ let mut machine = live_machine();
+
+ let request_scoped = CreateElicitationRequest::new(
+ ElicitationFormMode::new(
+ ElicitationRequestScope::new(RequestId::Number(12)),
+ ElicitationSchema::new(),
+ ),
+ "Workspace name?",
+ );
+ let effects = machine.handle(create(RequestId::Number(0), request_scoped));
+ assert_eq!(refusals(&effects), [RequestId::Number(0)]);
+
+ let effects = machine.handle(create(RequestId::Number(1), form_for("acp-other")));
+ assert_eq!(refusals(&effects), [RequestId::Number(1)]);
+
+ assert_eq!(machine.pending_elicitation(), None);
+ }
+
+ #[test]
+ fn an_unknown_mode_is_refused() {
+ let mut machine = live_machine();
+ let params = serde_json::json!({
+ "sessionId": "acp-42",
+ "mode": "_hologram",
+ "message": "Look here",
+ "projector": "left"
+ });
+ let effects = machine.handle(frame(
+ RawJsonRpcMessage::request(
+ "elicitation/create".to_owned(),
+ params,
+ RequestId::Number(7),
+ )
+ .unwrap(),
+ ));
+
+ assert_eq!(refusals(&effects), [RequestId::Number(7)]);
+ assert_eq!(machine.pending_elicitation(), None);
+ }
+
+ #[test]
+ fn an_answer_with_the_held_id_goes_out_as_a_response_and_frees_the_slot() {
+ let mut machine = live_machine();
+ machine.handle(create(RequestId::Number(0), form_for("acp-42")));
+
+ let content = BTreeMap::from([(
+ "strategy".to_owned(),
+ agent_runtime_protocol::domain::action::ElicitationContentValue::Text(
+ "balanced".to_owned(),
+ ),
+ )]);
+ let effects = machine.handle(answer(
+ ElicitationRequestId::Number(0),
+ ElicitationAnswer::Accept {
+ content: Some(content),
+ },
+ 1,
+ ));
+
+ let responses = sent_responses(&effects);
+ assert_eq!(responses.len(), 1, "exactly one response: {effects:?}");
+ let (id, result) = &responses[0];
+ assert_eq!(*id, RequestId::Number(0));
+ let response: CreateElicitationResponse =
+ serde_json::from_value(result.clone().unwrap()).unwrap();
+ assert!(matches!(response.action, ElicitationAction::Accept(_)));
+ assert!(matches!(
+ effects.last(),
+ Some(Effect::Complete {
+ token: 1,
+ result: Ok(())
+ })
+ ));
+ assert_eq!(machine.pending_elicitation(), None);
+
+ // Answering again is a conflict: nothing is held any more.
+ let effects = machine.handle(answer(
+ ElicitationRequestId::Number(0),
+ ElicitationAnswer::Decline,
+ 2,
+ ));
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 2,
+ result: Err(AgentSessionError::ElicitationNotPending(_))
+ }]
+ ));
+ }
+
+ #[test]
+ fn an_answer_with_the_wrong_id_is_refused_and_the_slot_kept() {
+ let mut machine = live_machine();
+ machine.handle(create(RequestId::Number(0), form_for("acp-42")));
+
+ let effects = machine.handle(answer(
+ ElicitationRequestId::Number(99),
+ ElicitationAnswer::Decline,
+ 1,
+ ));
+
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 1,
+ result: Err(AgentSessionError::ElicitationNotPending(_))
+ }]
+ ));
+ assert_eq!(machine.pending_elicitation(), Some(&RequestId::Number(0)));
+ }
+
+ #[test]
+ fn an_answer_before_the_session_is_live_is_refused_not_queued() {
+ let mut machine = machine();
+
+ let effects = machine.handle(answer(
+ ElicitationRequestId::Number(0),
+ ElicitationAnswer::Cancel,
+ 1,
+ ));
+
+ assert!(matches!(
+ effects[..],
+ [Effect::Complete {
+ token: 1,
+ result: Err(AgentSessionError::ElicitationNotPending(_))
+ }]
+ ));
+ assert_eq!(machine.pending_count(), 0);
+ }
+
+ #[test]
+ fn a_stop_cancels_the_held_elicitation_before_cancelling_the_turn() {
+ let mut machine = live_machine();
+ machine.handle(create(RequestId::Number(0), form_for("acp-42")));
+
+ let effects = machine.handle(stop(1));
+
+ let responses = sent_responses(&effects);
+ assert_eq!(responses.len(), 1);
+ assert_eq!(responses[0].0, RequestId::Number(0));
+ let response: CreateElicitationResponse =
+ serde_json::from_value(responses[0].1.clone().unwrap()).unwrap();
+ assert!(matches!(response.action, ElicitationAction::Cancel));
+
+ // The cancel answer precedes the cancel notification.
+ let order: Vec<&str> = effects
+ .iter()
+ .filter_map(|effect| match effect {
+ Effect::Send {
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Response(_))),
+ ..
+ } => Some("answer"),
+ Effect::Send {
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Notification(n))),
+ ..
+ } if n.method.as_ref() == "session/cancel" => Some("cancel"),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(order, ["answer", "cancel"]);
+ assert_eq!(machine.pending_elicitation(), None);
+ }
+
+ #[test]
+ fn a_closed_connection_drops_the_held_elicitation_without_answering() {
+ let mut machine = live_machine();
+ machine.handle(create(RequestId::Number(0), form_for("acp-42")));
+
+ let effects = machine.handle(Input::Closed(CloseReason::TransportClosed));
+
+ assert!(sent_responses(&effects).is_empty());
+ assert_eq!(machine.pending_elicitation(), None);
+ assert_eq!(machine.status(), RuntimeStatus::Dead);
+ }
+}
diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rs
index 0074b92551..cd089e7675 100644
--- a/crates/agent_session/src/domain/session/types.rs
+++ b/crates/agent_session/src/domain/session/types.rs
@@ -34,10 +34,22 @@ pub(super) enum SessionPhase {
},
Live {
session_id: SessionId,
+ /// The one `elicitation/create` this connection is holding for the
+ /// user to answer. Macro allows one at a time; a second is refused
+ /// while this is `Some`.
+ elicitation: Option<PendingElicitation>,
},
Dead,
}
+/// An `elicitation/create` the agent is waiting on. Only the id is held:
+/// message, schema and mode are in the log for the fold to render, and the
+/// machine's one job is to know which id it may answer.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) struct PendingElicitation {
+ pub(super) request_id: RequestId,
+}
+
#[derive(Clone)]
pub(super) enum SessionOpening {
New,
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 2d4d36968c..f95920ba67 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -275,6 +275,18 @@ impl IntoResponse for AgentSessionApiError {
)
.into_response()
}
+ // Same class as a disconnected runtime: nothing is wrong, and
+ // repeating the request will not land. The form the caller is
+ // answering has already resolved (someone else answered, a stop
+ // cancelled it, or the connection that asked is gone).
+ Self::Domain(AgentSessionError::ElicitationNotPending(session_id)) => {
+ tracing::info!(%session_id, "elicitation answer refused: nothing pending under that id");
+ (
+ StatusCode::CONFLICT,
+ "the agent is not waiting on that question any more",
+ )
+ .into_response()
+ }
Self::Domain(AgentSessionError::Forbidden) => {
(StatusCode::FORBIDDEN, "forbidden").into_response()
}
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 6ac91929fb..54905e4b87 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -88,6 +88,7 @@ sqlx.workspace = true
strum.workspace = true
sync_service_client = { path = "../sync_service_client" }
system_properties = { path = "../system_properties" }
+thiserror.workspace = true
tokio.workspace = true
tokio-util = { workspace = true, features = ["rt"] }
tracing.workspace = true
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 81ef1dd7fd..f82cb21160 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -16,6 +16,7 @@ mod self_knowledge;
pub mod serde_utils;
mod subagent;
mod tool_context;
+pub mod user_tool_review;
pub use anthropic::toolset::AnthropicToolContext;
use anthropic::toolset::anthropic_toolset;
@@ -110,19 +111,25 @@ pub(crate) fn subagent_toolset() -> AiToolSet {
/// The host a toolset is assembled for.
///
-/// Hosts differ on two axes. First, whether their surface can render the
-/// composer card that finishes a chat-deferred user tool: only
-/// [`AiHost::Chat`] can, so it alone registers `SendEmail` and the deferring
-/// `CreateCalendarEvent` — on any other host those registrations would
-/// return `PendingUserExecution` forever while reading to the model as
-/// success. Second, whether the host runs the chat frontend's tool
-/// discovery and display tools.
+/// Hosts differ on two axes. First, whether something finishes a deferred
+/// user tool for them: [`AiHost::Chat`] has the composer card after the
+/// turn and [`AiHost::AgentSession`] the review elicitation in it, so those
+/// two register `SendEmail` and the deferring `CreateCalendarEvent` — on any
+/// other host those registrations would return `PendingUserExecution`
+/// forever while reading to the model as success. Second, whether the host
+/// runs the chat frontend's tool discovery and display tools.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AiHost {
/// The AI chat, and any host whose conversation is stored as a chat the
- /// frontend can render (scheduled agents, agent sessions, memory
- /// generation): composer cards finish deferred user tools there.
+ /// frontend can render (scheduled agents, memory generation): composer
+ /// cards finish deferred user tools there, after the turn.
Chat,
+ /// Macro's in-process agent serving an agent session: the same toolset
+ /// as [`AiHost::Chat`], but its user tools are reviewed in the turn - the
+ /// agent loop's finisher puts the call to the user over ACP and the tool
+ /// returns the outcome - so the prompt describes a review card the agent
+ /// waits on, never a pending composer.
+ AgentSession,
/// The channel-mention bot: no composer, so `CreateCalendarEvent`
/// executes directly in the agent loop and `SendEmail` is omitted.
ChannelBot,
@@ -139,7 +146,7 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
.add_subtoolset::<ToolNotificationToolContext>(notification_toolset())
.add_subtoolset::<ToolRemindersToolContext>(reminders_toolset());
let toolset = match host {
- AiHost::Chat => toolset
+ AiHost::Chat | AiHost::AgentSession => toolset
.add_subtoolset::<ToolEmailToolContext>(email_toolset())
.add_subtoolset::<ToolCalendarToolContext>(calendar_toolset()),
AiHost::ChannelBot | AiHost::Mcp => toolset
@@ -150,7 +157,7 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
.add_subtoolset::<ToolImportToolContext>(import_toolset())
.add_tool::<Subagent, ToolServiceContext>();
let toolset = match host {
- AiHost::Chat | AiHost::ChannelBot => toolset
+ AiHost::Chat | AiHost::AgentSession | AiHost::ChannelBot => toolset
.add_tool::<SearchTools, ToolServiceContext>()
.add_tool::<LoadTools, ToolServiceContext>()
.add_tool::<DisplayResults, ToolServiceContext>(),
@@ -158,6 +165,7 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
};
let prompt: Box<dyn std::fmt::Display + Send + Sync> = match host {
AiHost::Chat => Box::new(&prompt::TOOL_USE_PROMPT),
+ AiHost::AgentSession => Box::new(&prompt::SESSION_TOOL_USE_PROMPT),
AiHost::ChannelBot | AiHost::Mcp => Box::new(&prompt::DIRECT_TOOL_USE_PROMPT),
};
ToolSetWithPrompt {
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index 5dbbccc55e..5b7e062c0a 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -13,6 +13,7 @@
//! turning that runtime failure into a test-time failure.
use super::*;
+use ai_toolset::ToolSet as _;
#[test]
fn subagent_toolset_passes_schema_validation() {
@@ -21,11 +22,45 @@ fn subagent_toolset_passes_schema_validation() {
#[test]
fn every_host_toolset_passes_schema_validation() {
- for host in [AiHost::Chat, AiHost::ChannelBot, AiHost::Mcp] {
+ for host in [
+ AiHost::Chat,
+ AiHost::AgentSession,
+ AiHost::ChannelBot,
+ AiHost::Mcp,
+ ] {
let _ = tools_for(host);
}
}
+/// An agent session finishes user tools in the turn, so it keeps chat's
+/// deferring registrations - and gets the prompt that says a review card,
+/// not a pending composer, is what follows the call.
+#[test]
+fn the_agent_session_host_keeps_chats_user_tools_with_the_review_prompt() {
+ let session = tools_for(AiHost::AgentSession);
+ assert!(
+ session
+ .toolset
+ .user_tools
+ .contains_key("CreateCalendarEvent")
+ );
+ assert!(session.toolset.user_tools.contains_key("SendEmail"));
+ let prompt = session.prompt.to_string();
+ assert!(prompt.contains("review card"));
+ assert!(!prompt.contains("PendingUserExecution"));
+ assert_eq!(
+ session
+ .toolset
+ .request_schemas()
+ .map(|schemas| schemas.len()),
+ tools_for(AiHost::Chat)
+ .toolset
+ .request_schemas()
+ .map(|schemas| schemas.len()),
+ "the same tools as chat"
+ );
+}
+
/// Hosts without a composer cannot finish a deferred user tool, so their
/// toolsets must execute calendar creation directly and omit SendEmail
/// entirely — a `UserToolResponse` output there would mean a call that
diff --git a/crates/ai_tools/src/user_tool_review.rs b/crates/ai_tools/src/user_tool_review.rs
new file mode 100644
index 0000000000..58d2d0c248
--- /dev/null
+++ b/crates/ai_tools/src/user_tool_review.rs
@@ -0,0 +1,424 @@
+//! Finishing a user tool inside the turn: the user reviews the call the model
+//! made, then the host executes or rejects it.
+//!
+//! A user tool (`ai_toolset::UserTool`, registered with `add_user_tool`)
+//! answers `"PendingUserExecution"` and does nothing. The host finishes it
+//! with the pieces `ai_toolset` exposes for exactly that: `is_valid_tool` to
+//! check edited arguments and `try_user_tool_call` to run the wrapped tool.
+//! Chat does so after the turn, over HTTP, from its composer. A host that can
+//! reach its user *during* the turn - Macro's in-process agent, whose ACP
+//! client renders elicitations - does it here, through the
+//! [`UserToolReviewer`] port, before the model reads the result.
+//!
+//! The port speaks in the restricted form vocabulary elicitation shares
+//! across ACP and MCP (flat primitives with defaults), stated in this crate's
+//! own types so neither protocol leaks in. A [`ReviewForm`] is projected from
+//! the tool's input schema and the call's arguments, so every user tool is
+//! reviewable without per-tool code; the whole edited draft can come back in
+//! one `Json` field for a client that has a composer of its own.
+
+use std::collections::BTreeMap;
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::Arc;
+
+use agent::{FinishedUserTool, PendingUserTool, UserToolFinisher};
+use ai_toolset::tool_object::UserToolResponse;
+use ai_toolset::{AsyncToolCollection, RequestContext};
+use async_trait::async_trait;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde_json::{Map, Value};
+use tokio_util::sync::CancellationToken;
+
+#[cfg(test)]
+mod test;
+
+/// The name of the form field that carries the whole edited draft as JSON.
+/// A client with its own composer for the tool fills this in; a client that
+/// renders the form generically leaves it out and edits the flat fields.
+pub const DRAFT_FIELD: &str = "draft";
+
+/// A user tool's call, put to the user for review.
+#[derive(Debug, Clone, PartialEq)]
+pub struct ReviewRequest {
+ /// The tool's name as the toolset knows it.
+ pub tool_name: String,
+ /// The call's id as the transcript shows it.
+ pub tool_call_id: String,
+ /// What the user is asked, in one line: "Create calendar event?".
+ pub message: String,
+ /// The arguments the model called the tool with, whole.
+ pub draft: Value,
+ /// The flat form a client renders to edit the draft.
+ pub form: ReviewForm,
+}
+
+/// A flat form: the restricted schema elicitation allows, in neutral terms.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct ReviewForm {
+ /// The tool's human title, for the form's heading.
+ pub title: Option<String>,
+ /// The fields, in the schema's order.
+ pub fields: Vec<ReviewField>,
+ /// Names of the fields an answer must fill.
+ pub required: Vec<String>,
+}
+
+/// One form field.
+#[derive(Debug, Clone, PartialEq)]
+pub struct ReviewField {
+ /// The key the answer is sent back under; the argument it edits.
+ pub name: String,
+ /// The argument's description from the tool's schema, when it has one.
+ pub description: Option<String>,
+ /// The field's type and pre-filled value.
+ pub kind: ReviewFieldKind,
+}
+
+/// A field's type, with the value the draft holds as its default.
+#[derive(Debug, Clone, PartialEq)]
+pub enum ReviewFieldKind {
+ /// Free text; `format` is the schema's (`date-time`, `email`, ...) when given.
+ Text {
+ /// The draft's value.
+ default: Option<String>,
+ /// The schema's format hint.
+ format: Option<String>,
+ },
+ /// A yes/no.
+ Boolean {
+ /// The draft's value.
+ default: Option<bool>,
+ },
+ /// A number.
+ Number {
+ /// The draft's value.
+ default: Option<f64>,
+ },
+ /// A whole number.
+ Integer {
+ /// The draft's value.
+ default: Option<i64>,
+ },
+ /// One of a fixed set of strings.
+ Choice {
+ /// The allowed values.
+ options: Vec<String>,
+ /// The draft's value.
+ default: Option<String>,
+ },
+ /// The whole edited draft as a JSON string - see [`DRAFT_FIELD`].
+ Json,
+}
+
+/// What the user decided.
+#[derive(Debug, Clone, PartialEq)]
+pub enum ReviewOutcome {
+ /// The user confirmed, with the form's values as submitted. Absent
+ /// fields keep the draft's values.
+ Accepted(BTreeMap<String, Value>),
+ /// The user said no.
+ Declined,
+ /// The question was dismissed, or the turn stopped.
+ Cancelled,
+}
+
+/// Why a review could not happen.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum ReviewError {
+ /// The user cannot be asked right now: the client has no way to show the
+ /// form, or is already holding another question.
+ #[error("the user cannot be asked to review this call right now: {0}")]
+ Unavailable(String),
+ /// Asking failed on the way.
+ #[error("asking the user to review this call failed: {0}")]
+ Failed(String),
+}
+
+/// A host's way of putting a call to its user and waiting for the answer.
+#[async_trait]
+pub trait UserToolReviewer: Send + Sync {
+ /// Ask the user to review `request` and wait for their decision.
+ async fn review(&self, request: ReviewRequest) -> Result<ReviewOutcome, ReviewError>;
+}
+
+/// A [`UserToolFinisher`] for `tools`: puts each pending user tool to
+/// `reviewer`, and on acceptance runs the tool with the reviewed arguments
+/// as `user`, against `context`.
+///
+/// The tool's answer is a `UserToolResponse` as JSON, the same shape chat
+/// writes when its composer finishes the call: the user's action with the
+/// tool's result, or `"Rejected"`. A tool this toolset does not know as a
+/// user tool is left alone (`None`) for the host to finish some other way.
+pub fn user_tool_finisher<Context>(
+ tools: Arc<AsyncToolCollection<Context>>,
+ context: Context,
+ user: MacroUserIdStr<'static>,
+ reviewer: Arc<dyn UserToolReviewer>,
+ cancel: CancellationToken,
+) -> UserToolFinisher
+where
+ Context: Clone + Send + Sync + 'static,
+{
+ Arc::new(move |call: PendingUserTool| {
+ let tools = Arc::clone(&tools);
+ let context = context.clone();
+ let user = user.clone();
+ let reviewer = Arc::clone(&reviewer);
+ let cancel = cancel.clone();
+ Box::pin(async move { finish(&tools, context, user, &*reviewer, cancel, call).await })
+ as Pin<Box<dyn Future<Output = Option<FinishedUserTool>> + Send>>
+ })
+}
+
+async fn finish<Context>(
+ tools: &AsyncToolCollection<Context>,
+ context: Context,
+ user: MacroUserIdStr<'static>,
+ reviewer: &dyn UserToolReviewer,
+ cancel: CancellationToken,
+ call: PendingUserTool,
+) -> Option<FinishedUserTool>
+where
+ Context: Clone + Send + Sync + 'static,
+{
+ let tool = tools.user_tools.get(&call.tool_name)?;
+ let request = ReviewRequest {
+ tool_name: call.tool_name.clone(),
+ tool_call_id: call.tool_call_id.clone(),
+ message: format!("{}?", tool.annotations.title),
+ draft: call.args.clone(),
+ form: project_form(
+ Some(tool.annotations.title.to_owned()),
+ &tool.input_schema,
+ &call.args,
+ ),
+ };
+
+ let outcome = match reviewer.review(request).await {
+ Ok(outcome) => outcome,
+ Err(error) => return Some(FinishedUserTool::Error(error.to_string())),
+ };
+ let content = match outcome {
+ ReviewOutcome::Accepted(content) => content,
+ ReviewOutcome::Declined => {
+ return Some(FinishedUserTool::Result(rejected()));
+ }
+ ReviewOutcome::Cancelled => {
+ return Some(FinishedUserTool::Error(
+ "the user cancelled the review; the call was not made".to_owned(),
+ ));
+ }
+ };
+
+ let args = apply_review(&call.args, &content);
+ if !tools.is_valid_tool(&call.tool_name, &args) {
+ return Some(FinishedUserTool::Error(format!(
+ "the reviewed arguments are not valid for {}; nothing was done",
+ call.tool_name
+ )));
+ }
+ let mut request_context = RequestContext::new(user);
+ request_context.cancel = cancel;
+ match tools
+ .try_user_tool_call(context, request_context, &call.tool_name, &args)
+ .await
+ {
+ Ok(Ok(response)) => Some(match serde_json::to_value(response) {
+ Ok(json) => FinishedUserTool::Result(json),
+ Err(error) => {
+ FinishedUserTool::Error(format!("the result could not be encoded: {error}"))
+ }
+ }),
+ Ok(Err(error)) => Some(FinishedUserTool::Error(error.description)),
+ Err(error) => Some(FinishedUserTool::Error(error.to_string())),
+ }
+}
+
+/// `UserToolResponse::Rejected` as the JSON chat writes for it.
+fn rejected() -> Value {
+ serde_json::to_value(UserToolResponse::<Value>::Rejected).unwrap_or(Value::Null)
+}
+
+/// The arguments to run with: the draft, overwritten by what the user
+/// submitted. A whole draft under [`DRAFT_FIELD`] (a JSON string, or the
+/// object itself) replaces everything; otherwise each flat field replaces
+/// the argument of the same name.
+pub fn apply_review(draft: &Value, content: &BTreeMap<String, Value>) -> Value {
+ if let Some(whole) = content.get(DRAFT_FIELD) {
+ let parsed = match whole {
+ Value::String(text) => serde_json::from_str::<Value>(text).ok(),
+ Value::Object(_) => Some(whole.clone()),
+ _ => None,
+ };
+ if let Some(object @ Value::Object(_)) = parsed {
+ return object;
+ }
+ }
+ let mut args = match draft {
+ Value::Object(map) => map.clone(),
+ _ => Map::new(),
+ };
+ for (name, value) in content {
+ if name != DRAFT_FIELD {
+ args.insert(name.clone(), value.clone());
+ }
+ }
+ Value::Object(args)
+}
+
+/// The flat form for a tool: one field per top-level primitive argument in
+/// `schema`, pre-filled from `args`, plus the [`DRAFT_FIELD`]. Arguments the
+/// restricted form cannot show - objects, arrays, unions - are left to the
+/// draft field.
+pub fn project_form(
+ title: Option<String>,
+ schema: &Map<String, Value>,
+ args: &Value,
+) -> ReviewForm {
+ let properties = schema
+ .get("properties")
+ .and_then(Value::as_object)
+ .cloned()
+ .unwrap_or_default();
+ let schema_required: Vec<&str> = schema
+ .get("required")
+ .and_then(Value::as_array)
+ .map(|names| names.iter().filter_map(Value::as_str).collect())
+ .unwrap_or_default();
+
+ let mut fields = Vec::new();
+ let mut required = Vec::new();
+ for (name, property) in &properties {
+ let Some(kind) = field_kind(property, args.get(name)) else {
+ continue;
+ };
+ if schema_required.contains(&name.as_str()) {
+ required.push(name.clone());
+ }
+ fields.push(ReviewField {
+ name: name.clone(),
+ description: property
+ .get("description")
+ .and_then(Value::as_str)
+ .map(str::to_owned),
+ kind,
+ });
+ }
+ fields.push(ReviewField {
+ name: DRAFT_FIELD.to_owned(),
+ description: Some(
+ "The complete edited arguments as JSON, for a client with its own editor. \
+ When present it replaces every other field."
+ .to_owned(),
+ ),
+ kind: ReviewFieldKind::Json,
+ });
+ ReviewForm {
+ title,
+ fields,
+ required,
+ }
+}
+
+/// The field a property renders as, or `None` when the restricted form has
+/// no shape for it.
+fn field_kind(property: &Value, current: Option<&Value>) -> Option<ReviewFieldKind> {
+ // `Option<T>` fields come out as `{"type": ["string", "null"]}` or
+ // `anyOf: [T, null]`; read through to the one non-null type.
+ let property = non_null(property);
+ if let Some(options) = choice_options(property) {
+ return Some(ReviewFieldKind::Choice {
+ options,
+ default: current.and_then(Value::as_str).map(str::to_owned),
+ });
+ }
+ match json_type(property)? {
+ "string" => Some(ReviewFieldKind::Text {
+ default: current.and_then(Value::as_str).map(str::to_owned),
+ format: property
+ .get("format")
+ .and_then(Value::as_str)
+ .map(str::to_owned),
+ }),
+ "boolean" => Some(ReviewFieldKind::Boolean {
+ default: current.and_then(Value::as_bool),
+ }),
+ "integer" => Some(ReviewFieldKind::Integer {
+ default: current.and_then(Value::as_i64),
+ }),
+ "number" => Some(ReviewFieldKind::Number {
+ default: current.and_then(Value::as_f64),
+ }),
+ _ => None,
+ }
+}
+
+/// The string values a property allows, when it is a choice among fixed
+/// strings: a plain `enum`, or - how a documented Rust enum comes out - an
+/// `anyOf`/`oneOf` whose every real variant is one `const` string (or a
+/// one-value `enum`).
+fn choice_options(property: &Value) -> Option<Vec<String>> {
+ if let Some(options) = property.get("enum").and_then(Value::as_array) {
+ let options: Vec<String> = options
+ .iter()
+ .filter_map(Value::as_str)
+ .map(str::to_owned)
+ .collect();
+ return (!options.is_empty()).then_some(options);
+ }
+ let variants = ["anyOf", "oneOf"]
+ .into_iter()
+ .find_map(|key| property.get(key).and_then(Value::as_array))?;
+ let mut options = Vec::new();
+ for variant in variants {
+ if json_type(variant) == Some("null") {
+ continue;
+ }
+ let value = variant.get("const").and_then(Value::as_str).or_else(|| {
+ match variant.get("enum").and_then(Value::as_array)?.as_slice() {
+ [only] => only.as_str(),
+ _ => None,
+ }
+ })?;
+ options.push(value.to_owned());
+ }
+ (!options.is_empty()).then_some(options)
+}
+
+/// The property with a nullable wrapper removed: `anyOf`/`oneOf` of one real
+/// schema and `null` reads as that schema.
+fn non_null(property: &Value) -> &Value {
+ for key in ["anyOf", "oneOf"] {
+ if let Some(variants) = property.get(key).and_then(Value::as_array) {
+ let real: Vec<&Value> = variants
+ .iter()
+ .filter(|variant| json_type(variant) != Some("null"))
+ .collect();
+ if let [only] = real[..] {
+ return only;
+ }
+ }
+ }
+ property
+}
+
+/// The one JSON type a property declares, reading `["string", "null"]` as
+/// `string`. `None` for a property with several real types or none.
+fn json_type(property: &Value) -> Option<&str> {
+ match property.get("type")? {
+ Value::String(name) => Some(name.as_str()),
+ Value::Array(names) => {
+ let real: Vec<&str> = names
+ .iter()
+ .filter_map(Value::as_str)
+ .filter(|name| *name != "null")
+ .collect();
+ match real[..] {
+ [only] => Some(only),
+ _ => None,
+ }
+ }
+ _ => None,
+ }
+}
diff --git a/crates/ai_tools/src/user_tool_review/test.rs b/crates/ai_tools/src/user_tool_review/test.rs
new file mode 100644
index 0000000000..01a40fa4f5
--- /dev/null
+++ b/crates/ai_tools/src/user_tool_review/test.rs
@@ -0,0 +1,338 @@
+//! The review form is projected from a tool's own schema, the user's answer
+//! is applied over the draft, and the finisher runs the wrapped tool with
+//! what came back - or reports what stopped it.
+
+use std::sync::Mutex;
+
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+
+use super::*;
+use crate::{AiHost, tools_for};
+
+fn owner() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
+}
+
+fn field<'form>(form: &'form ReviewForm, name: &str) -> &'form ReviewField {
+ form.fields
+ .iter()
+ .find(|field| field.name == name)
+ .unwrap_or_else(|| panic!("the form has a {name} field: {form:#?}"))
+}
+
+/// The real `CreateCalendarEvent` schema, from the chat toolset that
+/// registers it as a user tool.
+fn create_calendar_event_schema() -> Map<String, Value> {
+ let tools = tools_for(AiHost::Chat);
+ tools
+ .toolset
+ .user_tools
+ .get("CreateCalendarEvent")
+ .expect("chat registers CreateCalendarEvent as a user tool")
+ .input_schema
+ .clone()
+}
+
+#[test]
+fn the_form_shows_a_tools_flat_arguments_prefilled_and_leaves_the_rest_to_the_draft() {
+ let schema = create_calendar_event_schema();
+ let draft = json!({
+ "title": "Q3 sync",
+ "time": {"kind": "timed", "startsAt": "2026-08-20T17:00:00Z", "endsAt": "2026-08-20T17:30:00Z"},
+ "location": "Room 4",
+ "attendees": [{"email": "[email protected]"}],
+ "addGoogleMeet": true,
+ });
+ let form = project_form(Some("Create calendar event".to_owned()), &schema, &draft);
+
+ assert_eq!(form.title.as_deref(), Some("Create calendar event"));
+ assert_eq!(
+ field(&form, "title").kind,
+ ReviewFieldKind::Text {
+ default: Some("Q3 sync".to_owned()),
+ format: None,
+ }
+ );
+ assert_eq!(
+ field(&form, "location").kind,
+ ReviewFieldKind::Text {
+ default: Some("Room 4".to_owned()),
+ format: None,
+ },
+ "an optional string reads through its nullable wrapper"
+ );
+ assert_eq!(
+ field(&form, "addGoogleMeet").kind,
+ ReviewFieldKind::Boolean {
+ default: Some(true)
+ }
+ );
+ assert!(
+ field(&form, "description").description.is_some(),
+ "field help comes from the schema"
+ );
+ assert_eq!(
+ field(&form, "eventType").kind,
+ ReviewFieldKind::Choice {
+ options: vec!["default".to_owned(), "out_of_office".to_owned()],
+ default: None,
+ },
+ "an enum is a choice, unset when the draft omits it"
+ );
+ // Objects and arrays have no flat shape: they ride in the draft field.
+ for nested in [
+ "time",
+ "attendees",
+ "reminders",
+ "outOfOffice",
+ "recurrenceLines",
+ ] {
+ assert!(
+ form.fields.iter().all(|field| field.name != nested),
+ "{nested} is not a flat field"
+ );
+ }
+ assert_eq!(field(&form, DRAFT_FIELD).kind, ReviewFieldKind::Json);
+ assert_eq!(
+ form.required,
+ vec!["title".to_owned()],
+ "the schema's requirements, flat ones only"
+ );
+}
+
+#[test]
+fn the_answer_is_applied_over_the_draft_and_a_whole_draft_wins() {
+ let draft = json!({"title": "Q3 sync", "location": "Room 4", "time": {"kind": "allDay"}});
+
+ // Flat fields replace the arguments of the same name; the rest stays.
+ let flat = BTreeMap::from([
+ ("title".to_owned(), json!("Q3 planning")),
+ ("addGoogleMeet".to_owned(), json!(true)),
+ ]);
+ assert_eq!(
+ apply_review(&draft, &flat),
+ json!({"title": "Q3 planning", "location": "Room 4", "time": {"kind": "allDay"}, "addGoogleMeet": true})
+ );
+
+ // A whole draft, as the JSON string a composer sends, replaces everything.
+ let whole = BTreeMap::from([
+ ("title".to_owned(), json!("ignored")),
+ (
+ DRAFT_FIELD.to_owned(),
+ json!(r#"{"title":"From the composer","time":{"kind":"allDay"}}"#),
+ ),
+ ]);
+ assert_eq!(
+ apply_review(&draft, &whole),
+ json!({"title": "From the composer", "time": {"kind": "allDay"}})
+ );
+
+ // A draft field that is not an object is ignored, not applied.
+ let broken = BTreeMap::from([
+ ("title".to_owned(), json!("Kept")),
+ (DRAFT_FIELD.to_owned(), json!("not json")),
+ ]);
+ assert_eq!(apply_review(&draft, &broken)["title"], "Kept");
+ assert!(apply_review(&draft, &broken).get(DRAFT_FIELD).is_none());
+
+ // Nothing submitted: the draft as it was.
+ assert_eq!(apply_review(&draft, &BTreeMap::new()), draft);
+}
+
+// --- the finisher, over a toolset with one user tool ---
+
+#[derive(Debug, Clone, PartialEq, Deserialize, JsonSchema)]
+#[schemars(title = "Greet", description = "Greets someone.")]
+struct Greet {
+ /// Who to greet.
+ name: String,
+ /// Whether to shout.
+ #[serde(default)]
+ loud: bool,
+}
+
+#[derive(Debug, Serialize, JsonSchema)]
+struct Greeting {
+ text: String,
+}
+
+impl ToolAnnotated for Greet {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Greet someone");
+}
+
+/// Records every call it runs.
+#[derive(Clone, Default)]
+struct Ran(Arc<Mutex<Vec<Greet>>>);
+
+#[async_trait]
+impl AsyncTool<Ran> for Greet {
+ type Output = Greeting;
+
+ async fn call(
+ &self,
+ context: ServiceContext<Ran>,
+ _request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ if self.name == "nobody" {
+ return Err(ToolCallError {
+ description: "nobody is not a person".to_owned(),
+ internal_error: anyhow::anyhow!("nobody"),
+ });
+ }
+ context.0.0.lock().unwrap().push(self.clone());
+ let text = format!("Hello, {}{}", self.name, if self.loud { "!" } else { "." });
+ Ok(Greeting { text })
+ }
+}
+
+/// A reviewer that records what it was asked and answers as scripted.
+struct Scripted {
+ asked: Mutex<Vec<ReviewRequest>>,
+ answer: Result<ReviewOutcome, ReviewError>,
+}
+
+#[async_trait]
+impl UserToolReviewer for Scripted {
+ async fn review(&self, request: ReviewRequest) -> Result<ReviewOutcome, ReviewError> {
+ self.asked.lock().unwrap().push(request);
+ self.answer.clone()
+ }
+}
+
+fn finisher_over_greet(
+ answer: Result<ReviewOutcome, ReviewError>,
+) -> (UserToolFinisher, Arc<Scripted>, Ran) {
+ let tools = Arc::new(AsyncToolCollection::<Ran>::new().add_user_tool::<Greet, Ran>());
+ let ran = Ran::default();
+ let reviewer = Arc::new(Scripted {
+ asked: Mutex::new(Vec::new()),
+ answer,
+ });
+ let finisher = user_tool_finisher(
+ tools,
+ ran.clone(),
+ owner(),
+ Arc::clone(&reviewer) as Arc<dyn UserToolReviewer>,
+ CancellationToken::new(),
+ );
+ (finisher, reviewer, ran)
+}
+
+fn pending(args: Value) -> PendingUserTool {
+ PendingUserTool {
+ tool_name: "Greet".to_owned(),
+ tool_call_id: "toolu_1".to_owned(),
+ args,
+ }
+}
+
+#[tokio::test]
+async fn an_accepted_review_runs_the_tool_with_the_edited_arguments() {
+ let (finisher, reviewer, ran) = finisher_over_greet(Ok(ReviewOutcome::Accepted(
+ BTreeMap::from([("loud".to_owned(), json!(true))]),
+ )));
+
+ let finished = finisher(pending(json!({"name": "Alice", "loud": false}))).await;
+
+ let asked = reviewer.asked.lock().unwrap();
+ assert_eq!(asked.len(), 1);
+ assert_eq!(asked[0].tool_name, "Greet");
+ assert_eq!(asked[0].tool_call_id, "toolu_1");
+ assert_eq!(asked[0].message, "Greet someone?");
+ assert_eq!(asked[0].draft, json!({"name": "Alice", "loud": false}));
+ assert_eq!(
+ field(&asked[0].form, "name").kind,
+ ReviewFieldKind::Text {
+ default: Some("Alice".to_owned()),
+ format: None,
+ }
+ );
+ assert_eq!(asked[0].form.required, vec!["name".to_owned()]);
+
+ assert_eq!(
+ &*ran.0.lock().unwrap(),
+ &[Greet {
+ name: "Alice".to_owned(),
+ loud: true,
+ }]
+ );
+ assert_eq!(
+ finished,
+ Some(FinishedUserTool::Result(
+ json!({"UserAction": {"text": "Hello, Alice!"}})
+ )),
+ "the answer is the user tool response chat writes"
+ );
+}
+
+#[tokio::test]
+async fn a_declined_review_rejects_without_running() {
+ let (finisher, _reviewer, ran) = finisher_over_greet(Ok(ReviewOutcome::Declined));
+ let finished = finisher(pending(json!({"name": "Alice"}))).await;
+ assert!(ran.0.lock().unwrap().is_empty());
+ assert_eq!(finished, Some(FinishedUserTool::Result(json!("Rejected"))));
+}
+
+#[tokio::test]
+async fn a_cancelled_review_and_an_unavailable_reviewer_fail_the_call_closed() {
+ let (finisher, _reviewer, ran) = finisher_over_greet(Ok(ReviewOutcome::Cancelled));
+ let Some(FinishedUserTool::Error(message)) = finisher(pending(json!({"name": "Alice"}))).await
+ else {
+ panic!("a cancelled review is an error the model reads");
+ };
+ assert!(message.contains("cancelled"), "{message}");
+ assert!(ran.0.lock().unwrap().is_empty());
+
+ let (finisher, _reviewer, ran) = finisher_over_greet(Err(ReviewError::Unavailable(
+ "another question is pending".to_owned(),
+ )));
+ let Some(FinishedUserTool::Error(message)) = finisher(pending(json!({"name": "Alice"}))).await
+ else {
+ panic!("an unavailable reviewer is an error the model reads");
+ };
+ assert!(message.contains("another question is pending"), "{message}");
+ assert!(ran.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn edited_arguments_the_tool_rejects_never_run() {
+ let (finisher, _reviewer, ran) = finisher_over_greet(Ok(ReviewOutcome::Accepted(
+ BTreeMap::from([("name".to_owned(), json!(42))]),
+ )));
+ let Some(FinishedUserTool::Error(message)) = finisher(pending(json!({"name": "Alice"}))).await
+ else {
+ panic!("invalid arguments are an error the model reads");
+ };
+ assert!(message.contains("not valid"), "{message}");
+ assert!(ran.0.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_tool_failure_after_acceptance_is_the_tools_own_error() {
+ let (finisher, _reviewer, _ran) =
+ finisher_over_greet(Ok(ReviewOutcome::Accepted(BTreeMap::new())));
+ assert_eq!(
+ finisher(pending(json!({"name": "nobody"}))).await,
+ Some(FinishedUserTool::Error("nobody is not a person".to_owned()))
+ );
+}
+
+#[tokio::test]
+async fn a_tool_the_toolset_does_not_know_as_a_user_tool_is_left_alone() {
+ let (finisher, reviewer, _ran) =
+ finisher_over_greet(Ok(ReviewOutcome::Accepted(BTreeMap::new())));
+ let finished = finisher(PendingUserTool {
+ tool_name: "SomethingElse".to_owned(),
+ tool_call_id: "toolu_2".to_owned(),
+ args: json!({}),
+ })
+ .await;
+ assert_eq!(finished, None);
+ assert!(reviewer.asked.lock().unwrap().is_empty());
+}
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index 3bebe235cb..b422e9e4d2 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -56,6 +56,17 @@ pub static TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT
.compose(&document_content_links::PROMPT)
.compose(&email::PROMPT);
+/// The agent-session tool-enabled prompt: [`TOOL_USE_PROMPT`] with the user
+/// tool rules restated for a host that reviews those calls in the turn - a
+/// review card the user answers while the agent waits, not a composer left
+/// pending after it.
+pub static SESSION_TOOL_USE_PROMPT: ComposedPrompt = BASE_PROMPT
+ .compose(&tool_usage::PROMPT)
+ .compose(&user_tools::SESSION_PROMPT)
+ .compose(&skills::PROMPT)
+ .compose(&document_content_links::PROMPT)
+ .compose(&email::PROMPT);
+
/// Citation, do-not, Macro-terms, and document-content-linking rules surfaced
/// to external MCP clients, composed together. These are static; the
/// item-linking rules for the model's own replies are not, because they
@@ -168,6 +179,18 @@ mod tests {
assert!(chat.contains("MUST use the `SendEmail` tool"));
}
+ #[test]
+ fn session_tool_use_prompt_describes_a_review_in_the_turn_not_a_pending_composer() {
+ // An agent session finishes user tools in the turn: the model never
+ // sees "PendingUserExecution" there, and telling it about a composer
+ // to confirm in later would have it say so to the user.
+ let session = SESSION_TOOL_USE_PROMPT.to_string();
+ assert!(!session.contains("PendingUserExecution"));
+ assert!(session.contains("review card"));
+ assert!(session.contains("MUST use the `SendEmail` tool"));
+ assert!(session.contains("do not ask for confirmation in prose"));
+ }
+
#[test]
fn tool_use_prompt_also_carries_document_content_link_rules() {
// The in-app prompt should keep the same guidance so behavior doesn't
diff --git a/crates/prompt/src/user_tools.rs b/crates/prompt/src/user_tools.rs
index f317480766..9ef626da12 100644
--- a/crates/prompt/src/user_tools.rs
+++ b/crates/prompt/src/user_tools.rs
@@ -1,11 +1,12 @@
-//! Chat-only rules for user tools — tools the user finishes in a composer.
+//! Rules for user tools — tools the user finishes rather than the agent.
//!
-//! Only compose this section into prompts for hosts whose toolset registers
-//! deferred user tools (`SendEmail`, `CreateCalendarEvent`) and whose surface
-//! can render the composer card that executes them. Hosts without that
-//! surface (the channel-mention bot, MCP) get toolsets where those tools
-//! execute directly or are absent, and this section would describe the
-//! opposite of what their tools do.
+//! Two flavours for the two hosts that register deferred user tools
+//! (`SendEmail`, `CreateCalendarEvent`): chat, where the call stays pending
+//! until the user finishes it in a composer after the turn ([`PROMPT`]), and
+//! an agent session, where the call is reviewed in the turn and the tool
+//! returns the outcome ([`SESSION_PROMPT`]). Hosts without either surface
+//! (the channel-mention bot, MCP) get toolsets where those tools execute
+//! directly or are absent, and neither section applies.
use crate::types::StaticPrompt;
@@ -29,3 +30,22 @@ through the SendEmail tool rather than inline text in the chat.";
/// The user-tools prompt section for composer-capable chat hosts.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
+
+static SESSION_INSTRUCTIONS: &str = r##"- `SendEmail` and `CreateCalendarEvent` are reviewed by the user before they run. Calling one opens a review card in the session, the turn waits while the user edits, confirms or declines, and the tool then returns what happened: the sent email or created event, or "Rejected". Nothing is pending afterwards and there is no chat composer; do not tell the user to confirm anything, and do not ask for confirmation in prose before calling the tool - the review card is the confirmation.
+
+- IMPORTANT: When the user asks you to draft, write, compose, or send an email (or reply to one),
+ you MUST use the `SendEmail` tool to produce it. NEVER write the email body as plain text in your
+ reply. The review card is a real email composer the user can edit before it sends; inline text
+ does none of that and is wrong. Drafting and sending are the same tool: the user decides in the
+ card whether it goes out.
+"##;
+
+static SESSION_INTENT: &str = "The model treats user tools as reviewed in the turn: the call \
+opens a review card, waits for the user, and returns the outcome - so it never describes a \
+pending composer, never asks for confirmation in prose first, and drafts or sends email through \
+SendEmail rather than inline text.";
+
+/// The user-tools prompt section for an agent session, whose in-process
+/// agent finishes user tools in the turn through a review elicitation.
+pub static SESSION_PROMPT: StaticPrompt<'static> =
+ StaticPrompt::borrowed(TITLE, SESSION_INSTRUCTIONS, SESSION_INTENT);
diff --git a/docs/ACP_ELICITATION.md b/docs/ACP_ELICITATION.md
new file mode 100644
index 0000000000..e3f56bbee7
--- /dev/null
+++ b/docs/ACP_ELICITATION.md
@@ -0,0 +1,1108 @@
+# ACP Elicitation
+
+Status: implementation plan. No protocol or product code has changed as part
+of this document.
+
+Sources:
+
+- [Elicitation RFD](https://agentclientprotocol.com/rfds/elicitation) (Completed, 2026-07-22)
+- [Protocol: Elicitation](https://agentclientprotocol.com/protocol/v2/elicitation) (stable)
+- [Announcement](https://agentclientprotocol.com/announcements/elicitation-stabilized) (2026-07-24)
+- [Schema reference](https://agentclientprotocol.com/protocol/schema)
+
+The RFD is done. The remaining work is ours: Macro is an ACP client today and
+does not advertise, hold, render, or answer `elicitation/create`.
+
+## Elevator pitch
+
+Let a coding agent pause a turn and ask the user a structured question (form)
+or send them through a safe out-of-band flow (URL, typically OAuth). The user
+answers in the session page. The agent gets a typed `accept` / `decline` /
+`cancel` and continues. This is not a permission prompt and not a session
+config option.
+
+## Why this exists
+
+ACP agents already have two limited ways to get input:
+
+1. **Session config options** — persistent, pre-declared at session open
+ (model, mode). Defaults required. Wrong tool for a one-off decision.
+2. **Unstructured turn text** — the agent writes "which approach?" in prose
+ and hopes the next `session/prompt` is the answer. No validation, no
+ cancel/decline distinction, no safe place for secrets.
+
+Elicitation is the missing transient request/response. The community rejected
+a one-off `session/select` (PR #340) in favor of the MCP elicitation data
+model, adapted to ACP's persistent bidirectional connection.
+
+## Protocol, compressed
+
+Agents send `elicitation/create` **directly** to the Client. MCP instead
+embeds the same payload in an `InputRequiredResult` and waits for the Client
+to retry the originating request. That is the main ACP/MCP split.
+
+### Modes
+
+- **Form** — restricted JSON Schema, in-band. Non-sensitive data only.
+- **URL** — out-of-band browser flow. Credentials never transit ACP or enter
+ Client / model context.
+
+`mode` is required. An omitted mode is not form. Unknown modes (and
+implementation-specific modes starting with `_`) must be preserved when
+stored or forwarded, and must not be rendered as form or URL.
+
+### Scope (flattened on the request)
+
+- **Session** — `sessionId` set. Optional `toolCallId` when the elicitation
+ was forwarded from an MCP server during a tool call.
+- **Request** — `requestId` set. Pre-session (auth / setup). No `sessionId`.
+
+Every elicitation and its state binds to the **Client connection** and, when
+auth exists, the **verified user**. A `sessionId` alone is not enough.
+
+### Capability negotiation
+
+Advertised on `initialize` under `clientCapabilities.elicitation`:
+
+```json
+{ "elicitation": { "form": {}, "url": {} } }
+```
+
+| Wire | Meaning |
+| --- | --- |
+| omitted / `null` | elicitation unsupported |
+| `{ "form": {} }` | form only |
+| `{ "url": {} }` | URL only |
+| `{ "form": {}, "url": {} }` | both |
+| `{}` or `{ "form": null, "url": null }` | no modes (not "form by default") |
+
+This is a deliberate ACP/MCP split: MCP still treats an empty object as
+form-only. Agents **MUST NOT** send a mode the Client did not advertise.
+Unsupported mode → JSON-RPC `-32602`.
+
+### Restricted form schema
+
+Senders must send `type: "object"` and `properties`. Flat primitives only:
+
+- `string` (`minLength`, `maxLength`, `pattern`, `format`: `email` / `uri` /
+ `date` / `date-time`, plus unknown formats preserved)
+- `number` / `integer` (`minimum`, `maximum`)
+- `boolean`
+- single-select: `enum` or titled `oneOf` + `const`
+- multi-select: array of string `enum` or titled `anyOf` + `const`
+ (`minItems` / `maxItems`)
+
+ACP additions over MCP: `pattern`, schema-level `title` / `description`,
+titled-enum descriptions, `_meta`. No `$schema`, no deprecated `enumNames`.
+
+Not supported: nested objects, arrays of objects, conditionals.
+
+`pattern` is agent-supplied. Evaluating it requires a time-bounded regex
+engine. A pathological pattern must not block the UI.
+
+### Response actions
+
+| Action | Meaning | `content` |
+| --- | --- | --- |
+| `accept` | user submitted (form) or consented to open (URL) | form: SHOULD match schema; URL: usually omitted |
+| `decline` | explicit no | ignored |
+| `cancel` | dismissed (Escape, close, navigate away) | ignored |
+
+Unknown actions starting with `_` are preserved, never treated as the three
+known ones. Agents must handle every action and every failure; they must not
+assume success.
+
+URL `accept` is **consent to open**, not completion. Completion is a later
+optional `elicitation/complete` notification carrying the original
+`elicitationId`.
+
+### URL security (normative)
+
+Agents:
+
+- MUST NOT put credentials, PII, or pre-authenticated access in the URL
+- SHOULD use HTTPS outside development
+- SHOULD NOT put clickable URLs in form fields
+- MUST NOT send tokens obtained through URL mode back over ACP
+- MUST verify the user who started the flow is the user who finishes it
+
+Clients:
+
+- MUST NOT prefetch the URL or its metadata
+- MUST show the full URL and obtain consent before navigating
+- MUST highlight the host; SHOULD warn on Punycode / suspicious URIs
+ (Macro shows the full URL and highlights the host - the MUST. It does not
+ warn on Punycode: a `xn--` test is a poor proxy for a hostile host, and it
+ read as a security guarantee the client cannot make. Deliberately unmet.)
+- MUST open in a context the Client and the model cannot inspect
+ (new browser tab, not an embedded webview we control)
+- MUST identify the requesting Agent and offer decline + cancel
+
+### Not a permission request
+
+The RFD is explicit: keep elicitation and `session/request_permission`
+separate. Permission is "may this tool run?". Elicitation is "what should I
+do next?". Different UX, different policy, different defaults.
+
+## What Macro does today
+
+Macro is an ACP **Client**. The harness does not care which agent is on the
+other end of the pipe (`docs/CURSOR_AGENT_TRANSPORT.md`). The pieces that
+matter:
+
+```text
+web (block-agent)
+ └─ POST /agent-sessions/{id}/control AgentAction
+ └─ agent_session SessionMachine ACP Client
+ ├─ initialize / session/new|load|resume / session/prompt
+ ├─ auto-answers session/request_permission
+ └─ logs every frame
+ └─ agent_fold MessagePart vocabulary
+ └─ MagicChip + AgentMessage
+```
+
+### Handshake
+
+`SessionMachine::build_initialize_request` sends
+`InitializeRequest::new(PROTOCOL_VERSION)` with default
+`ClientCapabilities`. That default does **not** advertise `elicitation`.
+Agents that check capabilities (they must) will never send
+`elicitation/create` to us.
+
+We speak `ProtocolVersion::V1` (`crates/agent_session/src/lib.rs`).
+Elicitation is in the stable schema; it does not require a version bump.
+
+### Incoming agent requests
+
+Once `Live`, `on_frame` only special-cases `session/request_permission`. It
+picks `AllowAlways`, else `AllowOnce`, else `Cancelled`, and replies
+immediately. Comment on the machine: "this autonomous agent has no approval
+UI." Everything else is ignored.
+
+If an agent sent `elicitation/create` today, the request would be logged
+and then hang until the agent timed out.
+
+### Fold
+
+`agent_fold` already understands permission as a first-class part
+(`MessagePart::Permission`) and matches the later JSON-RPC response to
+resolve `pending` → `selected` / `cancelled` / `errored` / `unrecognized`.
+`acp_ready` clears `pending_permissions` because request ids restart per
+connection.
+
+Elicitation is not in the vocabulary. Incoming `elicitation/create` falls
+through to "handshake and configuration traffic: nothing to render."
+
+### Control plane
+
+`AgentAction` is `Prompt | SetModel | Compact | Stop`. Those mint a new
+`AgentActionId` (`agent_session:{uuid}`) used as the JSON-RPC **request**
+id. Control requires `OwnerAccessLevel`.
+
+An elicitation answer is a JSON-RPC **response** to the agent's request id,
+the same shape as the permission auto-reply. It does not mint a new ACP
+request.
+
+### Frontend
+
+- `PermissionPart` is a read-only `ToolCard` ("Permission requested" +
+ trailing outcome). No buttons. By the time the fold shows it, the machine
+ has usually already answered.
+- MagicChip treats a pending permission as the in-flight activity
+ ("Permission needed") and ranks it above a running tool.
+- Composer drain keys off `working` (open turn, no stop). A hung
+ elicitation would leave `working` true and hold the prompt queue — unless
+ we teach both the fold and the composer that "waiting on the user" is
+ not "the agent is busy."
+
+### The other ACP role
+
+`cursor_cloud_agents` is an ACP **Agent** (`AgentCapabilities::default()`).
+It never sends `session/request_permission` and would not send elicitation
+either. Out of scope for v1. When we want Macro-as-agent to ask Zed / Cursor
+a question, that is a later slice against this same protocol.
+
+Cognition chat (`POST /cognition/stream/chat/message`) is not ACP. Do not
+extend `AssistantMessagePart` for this.
+
+### SDK pin
+
+Workspace `agent-client-protocol` is git-pinned at
+`8769d16d10e0c9fa7e662ee18424a4313b06ea88`. That pin resolves
+`agent-client-protocol-schema 1.6.0`, which **already has every elicitation
+type** in `src/v1/elicitation.rs` — but behind a cargo feature:
+
+```text
+agent-client-protocol feature unstable_elicitation
+ └─ agent-client-protocol-schema feature unstable_elicitation
+```
+
+Without the feature there is no `ClientCapabilities::elicitation`, no
+`CreateElicitationRequest`, and no `matches_method` impl for
+`elicitation/create`. No pin bump is needed. One line in the workspace
+`Cargo.toml` turns it on.
+
+Zed-as-client recordings in `crates/agent_fold/fixtures/real/` already
+advertise `"elicitation":{"form":{},"url":{}}` on `initialize`. That is
+Zed's capability object, not ours.
+
+## Harness matrix (research 2026-09-02)
+
+What each popular ACP agent actually does when it wants to ask the user
+something, from reading adapter source. The shared idiom (a select plus an
+"Other" free-text companion, and the answer the harness settled on) is read
+through two `HarnessReader` methods in `crates/agent_fold/src/domain/harness/`
+- `custom_answer_for` and `reported_elicitation_answer` - with the shared
+marker as the neutral reading (`generic.rs`) and each harness's own marker
+and naming fallback in its file (`claude_code.rs`, `codex.rs`). The fold
+collapses each pair in `fold/elicitation.rs`; everything else is plain ACP.
+
+| Harness | `agentInfo.name` | Sends `elicitation/create` | Idiom | Client answers by |
+| --- | --- | --- | --- | --- |
+| Claude Code (`claude-agent-acp` ≥ 0.64) | `@agentclientprotocol/claude-agent-acp` | yes — form for `AskUserQuestion` (gated on `elicitation.form`, tool removed otherwise); url + `elicitation/complete` for MCP servers | `question_N` (`oneOf`, or `array`+`anyOf` for multi) + `question_N_custom` marked `_meta._askUserQuestionCustomAnswer`; `toolCallId` = the `AskUserQuestion` tool call; custom text wins; adapter reports the answer in `_meta.claudeCode.toolResponse.answers`; decline → empty answers, cancel → tool aborted; numeric ids; may have several in flight | JSON-RPC response |
+| Codex (`codex-acp` ≥ 1.8) | `@agentclientprotocol/codex-acp` | yes, only in `collaboration_mode: plan` (or a Codex feature flag) and only if `elicitation.form`; MCP url → url mode + complete | `<id>` + `<id>__other` marked `_meta.codex.{questionId,isOtherAnswer}`; `required` names only questions without a companion; `toolCallId` names an id never opened as a `tool_call`; `_meta.codex.autoResolutionMs` may time the request out | JSON-RPC response |
+| OpenCode 1.18 | `OpenCode` | no; `clientCapabilities.elicitation` ignored | `question` tool exists but is off under `opencode acp`; if forced on, it blocks forever — nothing on ACP can answer it | new `session/prompt` (agent asks in prose) |
+| Hermes Agent | `hermes-agent` | no (PR #30089 unmerged would add `answer` + `other_answer`) | `clarify` excluded from the ACP toolset | n/a |
+| OpenClaw bridge | `openclaw-acp` | no | `ask_user` shows as `tool_call` `title:"ask_user: …"`, blocks the Gateway run; cannot be answered over ACP | n/a (times out → `no_answer`) |
+| Goose | — | yes, form, MCP-originated | plain ACP | JSON-RPC response |
+| Macro in-memory agent | `macro-inmem` | yes — form, when the client advertises it | model-callable `AskUser` asks one required free-text or single-choice question; `/ask` remains the deterministic end-to-end rig | JSON-RPC response |
+| Gemini CLI, Kimi, Cursor cloud | — | no | — | — |
+
+Consequences already built in:
+
+- The custom-answer collapse keys on the harness's marker, then the shared
+ one, then - only for a property with no `_meta` at all - the harness's
+ suffix; it applies to single and multi selects (`customField` on the
+ property). An unknown harness collapses on the shared marker alone.
+- A collapsed question is required even when the wire says optional: an
+ empty submission is useless to the agent.
+- Claude Code's tool call is absorbed by the question part; Codex's
+ `toolCallId` matches nothing, so the part is simply appended.
+- Claude Code may run several elicitations concurrently (parallel
+ subagents). This client holds one; the second is refused `-32602`, which
+ the adapter turns into a denied tool. Acceptable for v1; revisit if seen.
+- OpenCode / OpenClaw questions are not synthesized into elicitation parts:
+ nothing could answer them, and a form nobody can submit is worse than a
+ tool card.
+
+## What shipped on this branch
+
+The first pass, end to end, on the `cursor/acp-elicitation-spec-caf3`
+branch:
+
+- `agent-client-protocol` with `unstable_elicitation` (the pinned rev
+ already had every type).
+- `AgentAction::RespondElicitation` — a JSON-RPC response on the agent's
+ own id, numeric or string.
+- `SessionMachine` advertises `{form:{}, url:{}}`, holds one
+ session-scoped elicitation, refuses the rest with `-32602`, answers
+ through control, cancels the held question on Stop, and 409s a stale
+ answer.
+- `agent_fold`: `MessagePart::Elicitation`, `SessionMetadata.pending_elicitation`,
+ absorption of the asking tool call (by `ToolPath`, so a question a
+ subagent asked replaces the nested call), id-routed responses,
+ `elicitation/complete`, and the two `HarnessReader` methods above. Real
+ Claude Code fixture pinned; Claude multi-question and Codex shapes tested
+ from the adapters' documented output; each reader's idiom pinned in
+ `test/harness_readers.rs`.
+- `agent_inmem`: model-callable `AskUser` sends a real `elicitation/create`
+ through a domain user-input port; `/ask <question> | option | option`
+ remains the deterministic end-to-end rig in local and deployed development
+ environments. The host passes an explicit development-command setting into
+ the in-memory manager; it defaults off, and production treats `/ask` as
+ ordinary prompt text. Model-callable `AskUser` and user-tool review do not
+ depend on this setting.
+- Web: `ElicitationPart` (form with select / "Other" / text / number /
+ boolean / multi-select, URL consent), `blockedOnUser` composer notice,
+ MagicChip ranking, gallery demo, form-model tests.
+- `scripts/convert_stdio_recording.py` turns a stdio recorder's log into a
+ fold fixture.
+
+Second pass, same branch — Macro's own user tools reviewed through
+elicitation (see [User tools reviewed in the turn](#user-tools-reviewed-in-the-turn)):
+
+- `agent`: `AgentLoop::with_user_tool_finisher`. The stream bridge's
+ `on_tool_result` hands a `"PendingUserExecution"` answer to the finisher
+ and rewrites what the model reads (and the stream records) to what the
+ user decided.
+- `ai_tools::user_tool_review`: the `UserToolReviewer` port in a neutral
+ form vocabulary, the schema→form projection, and `user_tool_finisher`
+ over `is_valid_tool` / `try_user_tool_call` — the same pair chat's
+ `/tool/call` uses.
+- `agent_inmem`: the ACP requester implements the port; a review is a
+ form elicitation scoped to the call with `_meta.macro.userTool`. The idle
+ timeout re-arms while any question is out. `AiHost::AgentSession` pairs
+ chat's toolset with a prompt that describes the review card.
+- `agent_fold`: `ElicitationRequest::UserTool { tool, draft, schema }`,
+ recognized from the absorbed user-tool call or `_meta.macro.userTool`;
+ `MessagePart::Elicitation.tool_outcome` from the absorbed call's later
+ updates.
+- Web: the calendar and email composers split from their chat bindings
+ behind `UserToolReviewSink`; `ElicitationPart` mounts them for a review
+ and settles into the finished user tool; the owner gate lives in the
+ controller; the MagicChip gets an `asking` state with a compact card.
+
+Third pass, same branch - the answer surface typed end to end (see [Answers
+are shapes, not values](#answers-are-shapes-not-values)):
+
+- `agent_fold`: `ElicitationOutcome::Accepted { answers: Vec<AnsweredField> }`
+ and `reported: Option<Vec<AnsweredField>>` replace two raw-JSON fields. The
+ schema correlation, option titles, and the "Other" idiom resolve in the
+ fold, pinned by the Claude Code fixture that carries both keys.
+- `agent_runtime_protocol`: `ElicitationContentValue` closes the outbound
+ content type, `to_acp_response` becomes total, and the OpenAPI stops saying
+ `additionalProperties: {}`.
+- Web: `describeContent` and `optionTitle` deleted - the part renders the
+ fold's answers. `FieldValue` distinguishes single-choice and multi-choice
+ drafts. A single choice explicitly represents no selection, an offered
+ option, or custom text; `customField` controls whether Other is available.
+ The radio needs no synthetic `__custom` value. Decisions use exhaustive
+ matches, and `pattern` / `format` / `looksSuspicious` are gone.
+
+Still to do: request scope, more than one outstanding question per session
+(Claude Code's parallel subagents), the MCP server reviewing user tools for
+sandboxed harnesses.
+
+## User tools reviewed in the turn
+
+Macro's user tools (`SendEmail`, `CreateCalendarEvent`) are registered with
+`add_user_tool`: calling one returns `"PendingUserExecution"` and does
+nothing, and the *host* finishes the call with the pieces `ai_toolset`
+exposes for that — `is_valid_tool` for edited arguments,
+`try_user_tool_call` to run the wrapped tool, `UserToolResponse<T>` as the
+answer. Chat is one host: it finishes after the turn, over HTTP, from its
+composer. An agent session is another: it finishes *inside* the turn,
+through elicitation, before the model reads the result.
+
+```text
+model calls CreateCalendarEvent(draft)
+ └─ UserTool::call → "PendingUserExecution"
+ └─ StreamBridge::on_tool_result (agent)
+ └─ UserToolFinisher (ai_tools)
+ ├─ form = project(tool input schema, draft) + `draft` (_macro/json)
+ ├─ reviewer.review(..) → elicitation/create (agent_inmem)
+ │ sessionId, toolCallId, mode: form, requestedSchema,
+ │ _meta.macro.userTool = { name, draft }
+ │ ← accept {content} | decline | cancel
+ ├─ accept: args = apply(draft, content); is_valid_tool; try_user_tool_call
+ │ → Rewrite(UserToolResponse::UserAction(result))
+ ├─ decline → Rewrite("Rejected")
+ └─ cancel / unreachable client → tool error, nothing runs
+```
+
+Why this shape rather than a second, "reviewing" tool wrapper:
+
+- One contract. `PendingUserExecution` already means "the host finishes
+ this"; the session just finishes sooner. Toolset, schemas, descriptions
+ and the `UserToolResponse` output type are identical across chat and
+ sessions, so the fold's `user_tool_outcome` reader and the generated
+ frontend types need nothing new.
+- `toolCallId` for free. The hook has the call's id, so the elicitation is
+ properly tool-call-scoped and the fold's absorption replaces the tool row
+ with the question.
+- Generic forms. The flat elicitation form is projected from the tool's
+ input schema (top-level string / boolean / number / enum arguments,
+ pre-filled from the call); anything nested rides in one `draft` field of
+ Macro's `_macro/json` type. Any user tool is reviewable with no per-tool
+ code; a client without a composer edits the flat fields, Macro's client
+ renders the tool's composer and sends the whole edited draft.
+- Fail closed. No form capability, a slot already taken, or a cancelled
+ turn all read to the model as an error; nothing is created silently.
+
+The fold types the review — `ElicitationRequest::UserTool` — so the web
+`match`es on it exhaustively: the session block mounts the calendar or
+email composer over the draft (through `UserToolReviewSink`, the same
+components chat uses) and the MagicChip shows a compact summary with
+Create/Cancel and "Edit in session". Once the tool reports, the part's
+`tool_outcome` carries its result and the question renders as the finished
+user tool.
+
+Hosts (`ai_tools::AiHost`): `Chat` keeps the deferring registrations and the
+composer prompt; `AgentSession` keeps the same tools with the review prompt;
+`ChannelBot` and `Mcp` are unchanged — direct `CreateCalendarEvent`, no
+`SendEmail` — until the MCP server reviews through `rmcp`'s elicitation.
+
+## Answers are shapes, not values
+
+The first pass carried an accepted answer as raw JSON - ACP's content map,
+verbatim, `unknown` in TypeScript. That pushed one job onto every client:
+re-correlating the content with the schema that asked for it.
+
+The pinned Claude Code recording shows why that is the fold's job. Its
+accepted content is:
+
+```json
+{ "question_0": "Red", "question_0_custom": "blue" }
+```
+
+Both the choice *and* the free-text escape, because the harness sends both.
+The answer is "blue" - Claude Code says so itself in the tool result it
+reports afterwards. Resolving that took the same rule written three times: in
+the harness reader that produced `reported`, in the browser's `describeContent`
+(`custom ?? record[name]`), and inverted in `toContent`'s "never send both".
+Two languages, one rule, no shared test.
+
+It now folds once, against the schema:
+
+```rust
+Accepted { answers: vec![AnsweredField {
+ name: "question_0", label: "Best colour",
+ value: AnsweredValue::Custom { text: "blue" },
+}] }
+```
+
+Properties in declaration order, `label` resolved from the property's title,
+options resolved to the titles they were offered under, unanswered properties
+absent, and any key no property claimed kept as its own field. `reported`
+folds to the same type, labelled by the question prose a harness keys it with,
+so a surface renders one vocabulary either way. The fixture pins all of it.
+
+Two `#[specta(type = Unknown)]` escapes go away with it. `AnsweredValue::Number`
+carries the number as text: a JSON integer can outrun `f64`'s exact range, and
+`f64` has a `number | null` TypeScript face because a non-finite float
+serializes as null.
+
+The outbound direction is the mirror image and stays flat, because the
+session machine holds only a request id - it never sees the schema, so the
+`customField` key mapping has to stay client-side. What it gained instead is
+a closed type: `ElicitationContentValue` (string, boolean, integer, number,
+string array) replaces `serde_json::Value` on `ElicitationAnswer::Accept`, so
+`to_acp_response` is total. An object or a mixed array is now refused when the
+control request is *read*, where the caller learns of it, rather than at send
+time - after the machine has already released the elicitation slot, which
+would leave the agent blocked on a request nothing could answer.
+
+## Product decisions
+
+1. **Client first.** The product path is Macro receiving elicitation from
+ coding agents. `agent_inmem` also sends it through `AskUser`, both as a
+ native harness feature and as the local integration path. Sending from
+ `cursor_cloud_agents` remains a later slice.
+2. **Do not auto-answer.** Permissions stay auto-approved. Elicitation
+ waits for the session owner.
+3. **Advertise both modes.** `{ form: {}, url: {} }`.
+4. **Owner answers.** Same `OwnerAccessLevel` gate as every other control.
+5. **Session-scoped only.** Request-scoped (`requestId`, no `sessionId`)
+ is answered `-32602`. Those fire before `session/new`; the session
+ machine is the wrong place for them.
+6. **One outstanding elicitation per session.** The protocol allows many.
+ Macro holds one. A second `elicitation/create` while one is pending is
+ answered `-32602` and never rendered. The first is not disturbed.
+7. **Permission and elicitation stay separate** parts, separate UX.
+8. **Stop cancels the pending elicitation** (`action: "cancel"`) before
+ `session/cancel`. Disconnect / `acp_ready` drops it — the JSON-RPC id
+ is dead across connections and cannot be answered.
+9. **Form answers are conversation content.** Logged as ACP frames, folded
+ into the transcript. No password widget; the user's tool is Decline.
+10. **URL opens in a new tab** after consent. No iframe, no prefetch.
+11. **No new table, no new gateway message type.** The log is the record;
+ the fold derives the pending slot into `SessionMetadata`; the existing
+ `agent_session_log` realtime stream carries every frame the web needs.
+12. **Waiting on the user is not idle.** The in-process agent's turn idle
+ timeout re-arms while a question is out; a review waits as long as the
+ user takes, until an answer, a Stop, or the connection going away. No
+ cap for now.
+13. **Only the owner answers, everywhere it shows.** The controller knows
+ the owner and the viewer; the session block and the chip render the
+ question locked for anyone else and name who is being waited on.
+14. **The fold shapes answers, it does not forward values.** An accepted
+ answer folds to `Vec<AnsweredField>` - correlated with the schema that
+ asked, option titles resolved, the harness "Other" idiom collapsed - and
+ the harness's own reported reading folds to the same shape. The
+ correlation happens where the schema and the content are both in hand, so
+ no client repeats it. See [Answers are shapes, not
+ values](#answers-are-shapes-not-values).
+15. **A client validates only what it can check totally.** Required, lengths,
+ bounds, membership, item counts. Not `pattern`, not `format`: the agent
+ enforces both on every answer, and an agent-supplied regex has no place
+ on the browser's main thread.
+
+## What changes
+
+Five layers, inner to outer. Each has a type-surface diff and a behavior
+diff.
+
+```text
+Cargo.toml feature flag
+agent_runtime_protocol AgentAction::RespondElicitation
+agent_session advertise · hold one slot · answer · stop-cancel
+agent_fold MessagePart::Elicitation · SessionMetadata.pending_elicitation
+apps/web ElicitationPart · composer blockedOnUser · MagicChip
+```
+
+### 0. Cargo
+
+```toml
+# Cargo.toml [workspace.dependencies]
+agent-client-protocol = { git = "…", rev = "8769d16…", features = ["unstable_elicitation"] }
+```
+
+Unlocks, all in `agent_client_protocol::schema::v1`:
+
+| Type | Shape (fields that matter) |
+| --- | --- |
+| `ElicitationCapabilities` | `form: Option<ElicitationFormCapabilities>`, `url: Option<ElicitationUrlCapabilities>` |
+| `ClientCapabilities::elicitation(..)` | builder |
+| `CreateElicitationRequest` | `mode: ElicitationMode` (flattened), `message: String` |
+| `ElicitationMode` | `Form(ElicitationFormMode)` \| `Url(ElicitationUrlMode)` \| `Other(..)` — tagged `mode` |
+| `ElicitationFormMode` | `scope: ElicitationScope`, `requested_schema: ElicitationSchema` |
+| `ElicitationUrlMode` | `scope`, `elicitation_id: ElicitationId`, `url: String` |
+| `ElicitationScope` | `Session { session_id, tool_call_id: Option }` \| `Request { request_id }` |
+| `ElicitationSchema` | `properties: BTreeMap<String, ElicitationPropertySchema>`, `required: Option<Vec<String>>`, `title`, `description` |
+| `ElicitationPropertySchema` | `String` \| `Number` \| `Integer` \| `Boolean` \| `Array(MultiSelect)` \| `Other { type_, fields }` — tagged `type` |
+| `CreateElicitationResponse` | `action: ElicitationAction` (flattened) |
+| `ElicitationAction` | `Accept(ElicitationAcceptAction { content: Option<BTreeMap<String, ElicitationContentValue>> })` \| `Decline` \| `Cancel` \| `Other` — tagged `action` |
+| `ElicitationContentValue` | untagged `String` \| `Integer(i64)` \| `Number(f64)` \| `Boolean` \| `StringArray` |
+| `CompleteElicitationNotification` | `elicitation_id: ElicitationId` |
+| `CreateElicitationRequest::matches_method` / `CompleteElicitationNotification::matches_method` | from the SDK's `impl_jsonrpc_*` macros |
+
+Everything is `#[non_exhaustive]`, so every `match` in our code needs a
+wildcard arm, same as `PermissionOutcome` today.
+
+Wasm: `agent_fold` builds for wasm32. The schema crate is pure serde; the
+feature adds no native deps. `just ensure-agent-fold-wasm` in `apps/web`
+is the check.
+
+### 1. `agent_runtime_protocol` — the action
+
+`crates/agent_runtime_protocol/src/domain/action.rs`.
+
+```rust
+/// A JSON-RPC request id as the agent sent it, carried whole so the answer
+/// echoes the exact id back. `null` is not a valid id for a request that
+/// expects a response, so it is not representable here.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(untagged)]
+pub enum ElicitationRequestId {
+ Number(i64),
+ Str(String),
+}
+impl ElicitationRequestId {
+ pub fn from_request_id(id: &RequestId) -> Option<Self>; // Null → None
+ pub fn to_request_id(&self) -> RequestId;
+}
+
+/// What the user decided. Mirrors ACP's three actions; there is no
+/// `Other` because we never originate an unknown action.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(tag = "action", rename_all = "snake_case")]
+pub enum ElicitationAnswer {
+ Accept {
+ /// Form: the submitted values, keyed by property. URL: omitted.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ content: Option<BTreeMap<String, serde_json::Value>>,
+ },
+ Decline,
+ Cancel,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct AgentRespondElicitationAction {
+ /// The agent's `elicitation/create` request id, not an AgentActionId.
+ pub request_id: ElicitationRequestId,
+ #[serde(flatten)]
+ pub answer: ElicitationAnswer,
+}
+
+pub enum AgentAction {
+ Prompt(AgentPromptAction),
+ SetModel(AgentSetModelAction),
+ Compact,
+ Stop,
+ RespondElicitation(AgentRespondElicitationAction), // new
+}
+```
+
+Wire body on `POST /agent-sessions/{id}/control`:
+
+```json
+{ "type": "respondElicitation", "requestId": 43, "action": "accept",
+ "content": { "strategy": "balanced" } }
+{ "type": "respondElicitation", "requestId": "el-7", "action": "decline" }
+```
+
+Behavior:
+
+- `supersedes_queued()` → `false`.
+- `to_runtime(session_id, minted_id)` → **ignores `minted_id`** and builds
+ `RawJsonRpcMessage::response(request_id.to_request_id(), Ok(CreateElicitationResponse))`.
+ `content` values are converted `serde_json::Value → ElicitationContentValue`;
+ a value that is not string / integer / number / boolean / string-array is
+ `ActionError::Acp(..)`. This is the only `AgentAction` that emits a
+ Response frame rather than a Request or Notification; the doc comment on
+ the variant says so.
+- `control_from_runtime` → recognizes a `to_runtime` Response whose id is
+ in the fold's pending-elicitation map. The fold does this itself (see §3);
+ `control_from_runtime` returns `None` for responses, unchanged.
+
+Tests (`action/test.rs`): serde round trip for all three answers; `to_runtime`
+emits a Response with the echoed id and a body that deserializes as
+`CreateElicitationResponse`; non-primitive content is rejected.
+
+### 2. `agent_session` — advertise, hold, answer
+
+#### Types (`domain/session/types.rs`)
+
+```rust
+/// The one elicitation this connection is holding for the user.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) struct PendingElicitation {
+ pub(super) request_id: RequestId,
+}
+```
+
+Nothing else. Message, schema and mode live in the log; the machine only
+needs to know *which* id it may answer.
+
+`SessionPhase::Live` grows the slot:
+
+```rust
+Live { session_id: SessionId, elicitation: Option<PendingElicitation> }
+```
+
+`Effect` is unchanged. Answers go out as `Effect::Send`.
+
+#### Error (`domain/error.rs`)
+
+```rust
+#[error("agent session {0} has no pending elicitation matching that request id")]
+ElicitationNotPending(AgentSessionId),
+```
+
+HTTP mapping in `inbound/axum_router.rs`: `409 CONFLICT` (a stale or
+double answer, same class as "runtime not attached").
+
+#### Machine (`domain/session/session.rs`)
+
+`build_initialize_request`:
+
+```rust
+InitializeRequest::new(PROTOCOL_VERSION).client_capabilities(
+ ClientCapabilities::new().elicitation(
+ ElicitationCapabilities::new()
+ .form(ElicitationFormCapabilities::new())
+ .url(ElicitationUrlCapabilities::new()),
+ ),
+)
+```
+
+`on_frame` while `Live` — today only `respond_to_permission_request`. Add
+`hold_or_refuse_elicitation`:
+
+```text
+Request with method elicitation/create
+ parse CreateElicitationRequest
+ parse fails → JSON-RPC -32602 "invalid elicitation"
+ mode is Other → -32602 "unsupported elicitation mode"
+ scope is Request → -32602 "request-scoped elicitation unsupported"
+ slot already Some → -32602 "one elicitation at a time"
+ scope.session_id != live session_id → -32602 "elicitation for another session"
+ otherwise → slot = Some(request.id); no Send
+Notification elicitation/complete → nothing (fold handles it)
+```
+
+Every refusal is an `Effect::Send` of `RawJsonRpcMessage::response(id, Err(Error::invalid_params()))`,
+which the actor logs before sending like any other outbound frame — so the
+refusal is in the transcript too.
+
+`on_command` while `Live`, new arm before the generic enqueue:
+
+```text
+RespondElicitation(action)
+ slot is None or slot.request_id != action.request_id
+ → Effect::Complete { Err(ElicitationNotPending) } (nothing sent, nothing logged)
+ else
+ → slot = None; enqueue + flush as usual (to_runtime builds the Response)
+```
+
+`Stop` (already `supersedes_queued`): before `drop_pending`, if the slot
+is `Some`, push `Effect::Send { from: <stopper>, Response(id, Ok(Cancel)) }`
+and clear the slot. Then the existing cancel notification.
+
+Slot lifetime: set on hold; cleared on answer, on stop, and on `die`. A
+new `acp_ready` builds a fresh machine, so there is nothing to clear
+there. **The machine keeps the slot across a `session/prompt` response**
+(the agent may still be waiting). The fold, not the machine, decides
+whether to keep offering the form once the turn has ended — see §3.
+
+Tests (`session/tests.rs`), in the style of the permission tests:
+
+- initialize frame carries `"elicitation":{"form":{},"url":{}}`
+- form create is held (no Send), status stays Live
+- url create is held
+- second create while held → `-32602`, first slot intact
+- request-scoped → `-32602`; `Other` mode → `-32602`
+- respond with matching id → Response frame with `action: accept` and content; slot empty; a repeat → `ElicitationNotPending`
+- respond with wrong id → `ElicitationNotPending`, slot intact
+- stop with a slot → cancel Response then `session/cancel`, in that order
+- close with a slot → no frame, no panic
+
+Actor (`actors.rs`): no change. `deliver` already logs then sends;
+`acp_method` returns `None` for a Response, so the span simply lacks
+`rpc.method` for an answer. Acceptable; note it.
+
+Harness test agent (`agent_harness/src/testing/helpers/agent.rs`): the
+`ClientRequest::parse_message` match is over client→agent requests and is
+unaffected. Add a helper `sends_elicitation(request) -> RequestId` and
+`elicitation_response(id) -> Option<CreateElicitationResponse>` so
+service-level tests can drive the loop end-to-end.
+
+### 3. `agent_fold` — the type surface
+
+`crates/agent_fold/src/domain/model.rs`. Everything here is
+`Serialize + specta::Type` and lands in
+`apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts`
+via `just gen-agent-fold-types`.
+
+#### New: the elicitation vocabulary
+
+```rust
+/// The agent's JSON-RPC id for an elicitation, as the answer must echo it.
+/// Re-exported from agent_runtime_protocol so the control body and the
+/// fold agree byte-for-byte.
+pub use agent_runtime_protocol::domain::action::ElicitationRequestId;
+// TS: string | number
+
+/// What the agent asked for.
+#[serde(tag = "mode", rename_all = "snake_case")]
+pub enum ElicitationRequest {
+ Form { schema: ElicitationSchema },
+ Url { elicitation_id: String, url: String },
+ /// A mode this fold does not know. Kept raw so nothing is lost; never
+ /// rendered as form or url.
+ Unrecognized { mode: String, #[specta(type = Unknown)] raw: serde_json::Value },
+}
+
+/// ACP's restricted form schema, mirrored so the browser gets a typed
+/// union instead of `unknown`.
+#[serde(rename_all = "camelCase")]
+pub struct ElicitationSchema {
+ pub title: Option<String>,
+ pub description: Option<String>,
+ /// In the agent's order. BTreeMap on the wire is alphabetical; the fold
+ /// re-reads the raw `properties` object to keep declaration order.
+ pub properties: Vec<ElicitationProperty>,
+ pub required: Vec<String>,
+}
+
+#[serde(rename_all = "camelCase")]
+pub struct ElicitationProperty {
+ pub name: String,
+ pub title: Option<String>,
+ pub description: Option<String>,
+ pub schema: ElicitationPropertySchema,
+}
+
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum ElicitationPropertySchema {
+ String {
+ min_length: Option<u32>, max_length: Option<u32>,
+ pattern: Option<String>, format: Option<ElicitationStringFormat>,
+ default: Option<String>,
+ /// Single-select: `enum` (untitled) or `oneOf` (titled). Empty when free text.
+ options: Vec<ElicitationOption>,
+ },
+ Number { minimum: Option<f64>, maximum: Option<f64>, default: Option<f64> },
+ Integer { minimum: Option<i64>, maximum: Option<i64>, default: Option<i64> },
+ Boolean { default: Option<bool> },
+ /// Multi-select. `anyOf` (titled) and `items.enum` (untitled) both land here.
+ MultiSelect {
+ min_items: Option<u64>, max_items: Option<u64>,
+ options: Vec<ElicitationOption>, default: Vec<String>,
+ },
+ /// A property type this fold does not know. The browser renders a
+ /// "cannot display" row; Decline / Cancel still work.
+ Unrecognized { #[serde(rename = "type")] type_name: String, #[specta(type = Unknown)] raw: serde_json::Value },
+}
+
+#[serde(rename_all = "snake_case")]
+pub enum ElicitationStringFormat { Email, Uri, Date, DateTime, Other(String) }
+
+#[serde(rename_all = "camelCase")]
+pub struct ElicitationOption { pub value: String, pub title: Option<String>, pub description: Option<String> }
+
+/// How the request has resolved so far. `Pending` is a legitimate final
+/// state on a dead session, like an unanswered permission.
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ElicitationOutcome {
+ Pending,
+ Accepted {
+ /// The submitted form values (absent for URL accept).
+ #[specta(type = Unknown)] content: Option<serde_json::Value>,
+ },
+ Declined,
+ Cancelled,
+ /// URL only: `elicitation/complete` arrived after Accepted.
+ Completed,
+ /// Answered with a JSON-RPC error — including our own -32602 refusals.
+ Errored { message: String },
+ Unrecognized,
+}
+```
+
+#### Changed: `MessagePart`
+
+```rust
+pub enum MessagePart {
+ Text { .. }, Thought { .. }, ToolUse { .. }, Permission { .. }, Control { .. }, Plan { .. },
+ /// The agent asking the user a question. // new
+ Elicitation {
+ #[serde(rename = "requestId")] request_id: ElicitationRequestId,
+ #[serde(rename = "toolCall")] tool_call: Option<ToolUseId>,
+ message: String,
+ request: ElicitationRequest,
+ outcome: ElicitationOutcome,
+ },
+}
+```
+
+#### Changed: `SessionMetadata`
+
+```rust
+pub struct SessionMetadata {
+ pub model, supported_models, title, available_commands, status, // unchanged
+ /// The one elicitation the user can answer right now. `None` when
+ /// nothing is pending, the turn that asked has ended, or the
+ /// connection that asked is gone.
+ pub pending_elicitation: Option<PendingElicitation>, // new
+}
+
+#[serde(rename_all = "camelCase")]
+pub struct PendingElicitation {
+ pub request_id: ElicitationRequestId,
+ /// Where the matching `MessagePart::Elicitation` lives, so a surface
+ /// can scroll to it or dedupe against the transcript.
+ pub turn: u32,
+ pub tool_call: Option<ToolUseId>,
+ pub message: String,
+ pub request: ElicitationRequest,
+}
+```
+
+The part is the history; the metadata is the live pointer. The web reads
+`metadata.pendingElicitation` to decide *whether to show a form*, and the
+part to render the transcript row. The channel MagicChip already receives
+metadata and can say "Waiting for your input" without folding parts.
+
+#### Fold state (`domain/fold.rs`)
+
+```rust
+struct FoldState {
+ ..,
+ /// Outstanding elicitations by the agent's request id: where the part
+ /// sits (message, part), so a response can resolve it.
+ pending_elicitations: HashMap<RequestId, (usize, usize)>, // new
+ /// URL elicitations that were accepted and may still `complete`.
+ completable_elicitations: HashMap<String /* elicitationId */, (usize, usize)>, // new
+}
+```
+
+Dispatch additions, each one arm in `step`:
+
+| Frame | Handler | Effect |
+| --- | --- | --- |
+| `to_server` Request `elicitation/create` | `request_elicitation` | push part `Pending`; record in `pending_elicitations`; set `metadata.pending_elicitation` (only if none set — a second one, which the machine refuses, still gets a part so the refusal is visible, but never the slot) |
+| `to_runtime` Response `Result` whose id ∈ `pending_elicitations` | `resolve_elicitation` | outcome ← Accepted / Declined / Cancelled / Unrecognized; clear slot if it was this id; if URL + Accepted, record in `completable_elicitations` |
+| `to_runtime` Response `Error` whose id ∈ `pending_elicitations` | `resolve_elicitation` | outcome ← `Errored { message }`; clear slot |
+| `to_server` Notification `elicitation/complete` | `complete_elicitation` | if id ∈ `completable_elicitations` and part is Accepted → Completed; else ignore |
+| `session/prompt` Response (turn end) | existing `end_turn` | additionally: `metadata.pending_elicitation = None` if set. The part stays `Pending`. |
+| `acp_ready` event | existing | additionally clear `pending_elicitations`, `completable_elicitations`, and the metadata slot |
+
+Dispatch ordering caveat: today a `to_runtime` `Response::Result` is
+routed to `resolve_permission`. Route by id: try `pending_elicitations`
+first, then `pending_permissions`. Both maps are keyed by the *agent's*
+request ids, which the agent keeps unique, so there is no ambiguity.
+
+`request_elicitation` decoding rules, so the TS side never sees a
+half-typed schema:
+
+- `ElicitationMode::Form` → `ElicitationRequest::Form`, mapping each
+ `ElicitationPropertySchema` variant 1:1; `Other` → `Unrecognized`.
+- Declaration order: the SDK's `properties` is a `BTreeMap`, which sorts
+ keys. Re-read `params.requestedSchema.properties` as a
+ `serde_json::Map` to recover the agent's order — `workspace-hack`
+ enables `serde_json/preserve_order`, so that map is insertion-ordered
+ everywhere in this workspace, wasm included.
+- `ElicitationMode::Url` → `ElicitationRequest::Url`.
+- `ElicitationMode::Other` → `ElicitationRequest::Unrecognized`.
+- `scope` Request → still folded (the part exists, the machine will have
+ refused it, the Error response resolves it to `Errored`). The metadata
+ slot is never set for it.
+
+`Turn` gains nothing: positions are held in `FoldState` maps like
+`pending_controls`, not per turn, because an answer can legally arrive
+after the turn that asked has ended.
+
+Tests (`domain/test/fold.rs`, plus a fixture in `testing/fixtures.rs`):
+
+- form create → part Pending, metadata slot set with same id
+- accept with content → part Accepted{content}, slot None
+- decline / cancel → part, slot None
+- error response → Errored, slot None
+- url accept then complete → Completed; complete for unknown id ignored
+- second create while pending → second part exists, slot still first id
+- turn ends with pending → part Pending, slot None
+- `acp_ready` → maps cleared, slot None
+- `Other` mode and `Other` property type → Unrecognized, raw preserved
+- interrupted log → Pending is a legal final state
+- `export_types` output diff is reviewed by hand once
+
+#### Wire (`inbound/wire.rs`)
+
+No change. `FoldedStreamEvent::Metadata` already carries the whole
+`SessionMetadata`, so the new field streams for free.
+
+### 4. `apps/web`
+
+Regenerate first, then code against the types:
+
+```sh
+just gen-agent-fold-types # fold model → service-agent-fold/generated/types.ts
+bun run gen-api # harness openapi → AgentAction incl. respondElicitation
+```
+
+#### Service client
+
+`agentHarnessServiceClient.control(sessionId, request)` already takes the
+generated `ControlRequest = AgentAction`. Nothing to add; the union grows.
+
+#### Feed / context (`features/block-agent`)
+
+`create-agent-session-feed.ts` already exposes `metadata`. Add one
+derived accessor on `AgentSessionContext`:
+
+```ts
+pendingElicitation: Accessor<PendingElicitation | undefined> // metadata()?.pendingElicitation ?? undefined
+```
+
+#### Composer (`state/composer-state.ts`, `context/create-composer-controller.ts`)
+
+`ComposerFacts` is **unchanged**. `agentWorking` stays "newest turn has no
+stop"; a pending elicitation happens mid-turn, so the drain already holds
+and queued prompts already wait. That is correct.
+
+Add to the controller's return, read off metadata:
+
+```ts
+/** The agent is waiting on the user, not generating. Stop still works;
+ * the send button must not spin. */
+blockedOnUser: Accessor<boolean>
+```
+
+`AgentInput` uses it to swap the spinner for a static "Waiting for your
+answer" state while keeping the stop square. No change to `isBusy`.
+
+Add:
+
+```ts
+respondElicitation: (answer: ElicitationAnswer) => Promise<void>
+```
+
+which POSTs `{ type: 'respondElicitation', requestId, ...answer }` with
+`requestId` from `pendingElicitation()`. A `409` means the slot is gone
+(someone else answered, or the agent moved on): toast and let the
+metadata refresh clear the form. No queueing — the answer is not a
+prompt and must not sit behind one.
+
+`stop()` is unchanged on the client; the server cancels the slot.
+
+#### Rendering
+
+`component/parts/ElicitationPart.tsx`, routed from `AgentMessage.tsx`'s
+`match(...).exhaustive()` (a new arm is mandatory or tsc fails):
+
+- `outcome.kind === 'pending'` **and** `pendingElicitation()?.requestId === part.requestId`
+ → interactive card (this is the only place a form is live).
+- `pending` but not the slot (turn ended, or a refused second request that
+ has not resolved yet) → read-only "Not answered".
+- `accepted` → read-only key/value of `content`, or "Opened" for URL.
+- `declined` / `cancelled` / `completed` / `errored` / `unrecognized` →
+ read-only label.
+
+Form renderer, one component per `ElicitationPropertySchema` variant:
+string (text / select when `options` non-empty), number, integer,
+boolean, multi_select (checkbox group), unrecognized (disabled row).
+Client validation before POST: required, min/max length, min/max, item
+count, `format` for email/uri/date/date-time, `pattern` via `new RegExp`
+wrapped in a try and a 50 ms budget check (fail closed to "invalid").
+
+URL card: `message`, full URL monospace, host highlighted, warning when
+host starts with `xn--`, buttons Open / Decline / Cancel. Open →
+`respondElicitation({ action: 'accept' })` **then**
+`window.open(url, '_blank', 'noopener,noreferrer')`. Never fetch the URL.
+
+`ui/index.ts` gets `ElicitationCard` next to `ToolCard`.
+
+#### MagicChip (`LexicalMarkdown/.../MagicChip/presentation.ts`)
+
+`partActivity` gets `elicitation` arms (`.exhaustive()` forces it):
+pending → `{ label: 'Waiting for your input', busy: false }`; resolved →
+`'Resuming work'` busy. `turnInFlightActivity` ranks a pending
+elicitation with pending permission, above a running tool.
+
+`create-magic-chip-model.ts` already subscribes to metadata; no change.
+
+#### Debug gallery
+
+`debug/Gallery.tsx` gets one form and one URL fixture so the card can be
+eyeballed without an agent.
+
+#### Agent guide
+
+`docs/AGENT_GUIDE/ai-chat.md`: one paragraph — an agent session may show
+a form or a link-consent card; answer it or press Stop; queued messages
+send after the agent finishes.
+
+### 5. Out of scope, restated
+
+No Postgres table. No new connection-gateway message type. No
+request-scoped elicitation. No Macro-as-Agent sending. No change to
+permissions or `session/request_permission`.
+
+## Order of work
+
+Each step compiles and passes on its own. 0–3 are backend and can be one
+PR; 4 is the web PR against the regenerated types.
+
+| # | Step | Gate |
+| --- | --- | --- |
+| 0 | Cargo feature | `cargo check -p agent_session -p agent_fold -p agent_runtime_protocol`; `just ensure-agent-fold-wasm` |
+| 1 | `AgentAction::RespondElicitation` + tests | `cargo test -p agent_runtime_protocol` |
+| 2 | Machine: advertise, hold, answer, stop-cancel, error, HTTP 409 + tests | `cargo test -p agent_session` (`bash .cursor/infra.sh` first — postgres tests) |
+| 3 | Fold: model, state, dispatch, tests; regenerate TS | `cargo test -p agent_fold`; `just gen-agent-fold-types`; diff review |
+| 4 | Web: context accessor, composer, part, chip, gallery, guide | `bun run check`, `bun run test`, `bun run lint` |
+| 5 | End-to-end: `agent_inmem` or a mock agent sends `elicitation/create` mid-turn; answer from the session page; agent continues | manual, recorded |
+
+Steps 0–2 must ship together. Advertising a capability with nothing
+holding the request wedges every agent that uses it.
+
+## Risks
+
+- **Advertise without hold.** Covered by shipping 0–2 as one unit.
+- **Wrong response routing in the fold.** Elicitation and permission
+ responses both arrive as `to_runtime` Results. Route by id map, test the
+ interleaving (permission pending, elicitation pending, answer both).
+- **Property order.** Recovered from the raw `properties` object;
+ `preserve_order` is already on via `workspace-hack`. A test pins that a
+ schema declared `b, a` folds as `b, a`.
+- **Regex from the agent.** Bounded on the client; the server never
+ evaluates `pattern`.
+- **Stale answer after failover.** The slot lives in the machine on the
+ owning replica. A replica change means a new connection → new machine →
+ no slot → `409`. The fold's metadata slot clears on the next `acp_ready`.
+- **Composer confusion.** `agentWorking` must stay true while blocked, or
+ queued prompts would fire into the agent's question. `blockedOnUser` is
+ presentational only.
+
+## Open questions (decide before step 4)
+
+1. Should Stop cancel the elicitation, or only the model? Plan says both.
+2. Should a viewer (non-owner) see the form disabled, or hidden? Plan says
+ disabled with "Only the session owner can answer".
+3. URL accept: fire the POST before or after `window.open`? Plan says
+ before, so the agent learns consent even if the popup is blocked; the
+ card then shows the link as a fallback.
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 47619f83c0..cffccd664d 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -62,6 +62,25 @@ The agent has workspace tools (it can list your documents, read channels, create
render `displayResults` views). Requests go to `POST /cognition/stream/chat/message`; results
stream over the app's websocket, not the HTTP response.
+## Agent sessions asking a question
+
+For manual testing on local or deployed development environments, send
+`/ask <question>` for free text or `/ask <question> | option | option` for a
+single choice. This shortcut bypasses the model. It is disabled in production,
+where the text is an ordinary prompt; the model's `AskUser` tool and user-tool
+review remain independent of this development setting.
+
+An agent session (the `/app/channel/<channel>/agent/<session>` pane) can pause its turn to
+ask you something. A card titled `<bot> is asking` with trailing text `Waiting for you`
+appears in the transcript, and the notice `The agent is waiting for your answer above` sits
+over the composer. Forms have one control per field (radios for a choice, an `Other` text
+box when the agent allows a custom answer, checkboxes for multi-select, text/number inputs)
+plus `Submit` / `Decline` / `Cancel`; a link request shows the target host and URL with an
+`Open` button that only opens a new tab after you click it. Once answered the card collapses
+to `Question · <text>` with `Answered` / `Declined` / `Cancelled` on the right and the agent
+continues. Messages typed while a question is open queue behind it; the composer's `Stop`
+square cancels the question and the turn.
+
## In channels
Mention `@Macro` in any channel message for the classic in-channel reply. Mention
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 58f6717c71..ce9a2581bb 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AgentAction, AgentActionId, AgentPromptAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, ClientOptions, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, LogDirectionDto, LogFrameDto, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto } from './types.gen';
+export type { AgentAction, AgentActionId, AgentPromptAction, AgentRespondElicitationAction, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionQueueResponse, AgentSessionResponse, AgentSetModelAction, BotId, ClientOptions, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateSessionThread, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, ExternalSessionResponse, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, LogDirectionDto, LogFrameDto, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, SandboxSize, SandboxSizeBody, SessionBot, SessionStatusDto } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 28628e5eac..5f1ede72c7 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -15,7 +15,9 @@ export type AgentAction = (AgentPromptAction & {
type: 'compact';
} | {
type: 'stop';
-};
+} | (AgentRespondElicitationAction & {
+ type: 'respondElicitation';
+});
/**
* Identifies one accepted [`AgentAction`] end to end: returned by the
@@ -41,6 +43,17 @@ export type AgentPromptAction = {
prompt: string;
};
+/**
+ * Answer an elicitation the agent is waiting on.
+ */
+export type AgentRespondElicitationAction = ElicitationAnswer & {
+ /**
+ * The agent's `elicitation/create` request id - not an
+ * [`AgentActionId`], because the agent minted it.
+ */
+ requestId: ElicitationRequestId;
+};
+
/**
* One entry of a session's protocol log.
*
@@ -347,6 +360,46 @@ export type EditQueuedActionRequest = {
prompt: string;
};
+/**
+ * What the user decided about an elicitation. Mirrors ACP's three actions;
+ * there is no `Other` because we never originate an action we do not know.
+ */
+export type ElicitationAnswer = {
+ action: 'accept';
+ /**
+ * Form: the submitted values keyed by property. URL: omitted.
+ */
+ content?: {
+ [key: string]: ElicitationContentValue;
+ } | null;
+} | {
+ action: 'decline';
+} | {
+ action: 'cancel';
+};
+
+/**
+ * A value ACP accepts in an elicitation answer.
+ *
+ * Mirrors ACP's `ElicitationContentValue` so that the contract a caller
+ * answers against is the closed union ACP will accept, rather than arbitrary
+ * JSON narrowed on the way out. An object, a null, or a mixed array is
+ * refused when the request is deserialized - where the caller learns of it -
+ * instead of at send time, when the elicitation slot has already been
+ * released.
+ */
+export type ElicitationContentValue = string | boolean | number | number | Array<string>;
+
+/**
+ * The JSON-RPC id of an agent's `elicitation/create` request, carried whole
+ * so the answer echoes exactly what the agent sent.
+ *
+ * Agents pick these, not us: Claude Code counts from `0`, others use
+ * strings. `null` is not a legal id for a request that expects a response,
+ * so it is not representable here.
+ */
+export type ElicitationRequestId = number | string;
+
/**
* The provider-side identity of an externally-served session.
*/
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 5609adc0c9..9b337e6f15 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -869,6 +869,25 @@
"enum": ["stop"]
}
}
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AgentRespondElicitationAction",
+ "description": "Answer an `elicitation/create` the agent sent.\n\nThe one action whose wire form is a JSON-RPC *response* rather than a\nrequest or notification: the agent asked, we answer on its id. The\nminted [`AgentActionId`] therefore never reaches the wire for this\naction; the fold correlates on the agent's id instead."
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["respondElicitation"]
+ }
+ }
+ }
+ ],
+ "description": "Answer an `elicitation/create` the agent sent.\n\nThe one action whose wire form is a JSON-RPC *response* rather than a\nrequest or notification: the agent asked, we answer on its id. The\nminted [`AgentActionId`] therefore never reaches the wire for this\naction; the fold correlates on the agent's id instead."
}
],
"description": "One thing a caller wants an agent to do."
@@ -889,6 +908,25 @@
}
}
},
+ "AgentRespondElicitationAction": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/ElicitationAnswer",
+ "description": "The decision."
+ },
+ {
+ "type": "object",
+ "required": ["requestId"],
+ "properties": {
+ "requestId": {
+ "$ref": "#/components/schemas/ElicitationRequestId",
+ "description": "The agent's `elicitation/create` request id - not an\n[`AgentActionId`], because the agent minted it."
+ }
+ }
+ }
+ ],
+ "description": "Answer an elicitation the agent is waiting on."
+ },
"AgentSessionLogEntryDto": {
"allOf": [
{
@@ -1189,6 +1227,98 @@
}
}
},
+ "ElicitationAnswer": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "The user submitted the form, or consented to open the URL.",
+ "required": ["action"],
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["accept"]
+ },
+ "content": {
+ "type": ["object", "null"],
+ "description": "Form: the submitted values keyed by property. URL: omitted.",
+ "additionalProperties": {
+ "$ref": "#/components/schemas/ElicitationContentValue"
+ },
+ "propertyNames": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The user explicitly said no.",
+ "required": ["action"],
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["decline"]
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "The user dismissed the request without choosing.",
+ "required": ["action"],
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": ["cancel"]
+ }
+ }
+ }
+ ],
+ "description": "What the user decided about an elicitation. Mirrors ACP's three actions;\nthere is no `Other` because we never originate an action we do not know."
+ },
+ "ElicitationContentValue": {
+ "oneOf": [
+ {
+ "type": "string",
+ "description": "A string, and the shape a whole draft rides in as JSON text."
+ },
+ {
+ "type": "boolean",
+ "description": "A yes/no."
+ },
+ {
+ "type": "integer",
+ "format": "int64",
+ "description": "A whole number."
+ },
+ {
+ "type": "number",
+ "format": "double",
+ "description": "A number that is not whole."
+ },
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "A multi-select's chosen values."
+ }
+ ],
+ "description": "A value ACP accepts in an elicitation answer.\n\nMirrors ACP's `ElicitationContentValue` so that the contract a caller\nanswers against is the closed union ACP will accept, rather than arbitrary\nJSON narrowed on the way out. An object, a null, or a mixed array is\nrefused when the request is deserialized - where the caller learns of it -\ninstead of at send time, when the elicitation slot has already been\nreleased."
+ },
+ "ElicitationRequestId": {
+ "oneOf": [
+ {
+ "type": "integer",
+ "format": "int64",
+ "description": "A numeric JSON-RPC id. Specta refuses `i64` (it does not fit a JS\nnumber); agents count their requests from zero, so `i32` is the\nhonest TypeScript face."
+ },
+ {
+ "type": "string",
+ "description": "A string JSON-RPC id."
+ }
+ ],
+ "description": "The JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here."
+ },
"ExternalSessionResponse": {
"type": "object",
"description": "The provider-side identity of an externally-served session.",
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 70331f4276..ee94ad1395 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -52,7 +52,7 @@ use agent_inmem::outbound::acp_mcp::AcpMcpConnector;
use agent_inmem::outbound::egress_mcp::EgressMcpClient;
use agent_inmem::outbound::log_frames::LogFrameSource;
use agent_inmem::outbound::manager::InMemAgentManager;
-use agent_inmem::outbound::rig_engine::RigTurnEngine;
+use agent_inmem::rig_engine::RigTurnEngine;
use agent_runtime_directory::PgAgentRuntimeDirectory;
use agent_session::domain::model::{AgentMcpServers, ReplicaId};
use agent_session::domain::ports::{NoOpRealtime, SessionOwnership as _};
@@ -164,6 +164,10 @@ async fn run() -> anyhow::Result<()> {
.await
.context("failed to resolve agent harness service secrets")?;
let bot_id = BotId::new_from_uuid(config.harness_bot_id);
+ let enable_dev_commands = matches!(
+ config.environment,
+ Environment::Local | Environment::Develop
+ );
// The in-process "macro(new)" bot is a compile-time identity, not
// configuration: it is always `bot_id::MACRO_NEW_BOT_ID`, so the only real
// question is whether this environment serves it. Production stays off
@@ -342,7 +346,8 @@ async fn run() -> anyhow::Result<()> {
Arc::new(AcpMcpConnector::new(EgressMcpClient::new(Arc::clone(
&egress,
)))),
- ),
+ )
+ .with_dev_commands(enable_dev_commands),
})
}
None => None,