@@ -58,9 +58,20 @@ interface AgentRun extends AgentOptions {
5858 onEvent: (event: AgentEvent) => void;
5959 }
6060
61+/** The concatenated text blocks of an assistant message, ignoring the rest. */
62+export function assistantText(message: AssistantMessage): string {
63+ return message.content
64+ .filter((block) => block.type === "text")
65+ .map((block) => block.text)
66+ .join("");
67+}
68+
6169 export async function runAgentTurn(run: AgentRun): Promise<void> {
6270 const { messages, session, signal, interaction, onEvent } = run;
6371
72+ const cancelled = (): void => onEvent({ type: "cancelled" });
73+ const failed = (message: string): void => onEvent({ type: "error", message });
74+
6475 /** Appends a user message the model reads at the next step boundary. */
6576 const steer = (content: string): void => {
6677 if (content === "") return;
@@ -91,7 +102,7 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
91102 for (;;) {
92103 const steering = await pauseStep();
93104 if (steering === null) {
94- onEvent({ type: "cancelled" });
105+ cancelled();
95106 return;
96107 }
97108 steer(steering);
@@ -116,7 +127,7 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
116127 sessionId: session.id ?? undefined,
117128 });
118129 } catch (error) {
119- onEvent({ type: "error", message: (error as Error).message });
130+ failed((error as Error).message);
120131 return;
121132 }
122133
@@ -138,7 +149,7 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
138149 }
139150 }
140151 } catch (error) {
141- onEvent({ type: "error", message: (error as Error).message });
152+ failed((error as Error).message);
142153 return;
143154 }
144155
@@ -148,11 +159,11 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
148159 onEvent({ type: "message", message: assistant });
149160
150161 if (assistant.stopReason === "aborted") {
151- onEvent({ type: "cancelled" });
162+ cancelled();
152163 return;
153164 }
154165 if (assistant.stopReason === "error") {
155- onEvent({ type: "error", message: assistant.errorMessage ?? "provider error" });
166+ failed(assistant.errorMessage ?? "provider error");
156167 return;
157168 }
158169
@@ -169,7 +180,7 @@ export async function runAgentTurn(run: AgentRun): Promise<void> {
169180 for (const call of toolCalls) {
170181 const steering = await pauseStep();
171182 if (steering === null) {
172- onEvent({ type: "cancelled" });
183+ cancelled();
173184 return;
174185 }
175186 if (steering !== "") held.push(steering);