@cloudflare/ai-chat 0.5.4 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -102,7 +102,7 @@ Tools with an `execute` function run on the server automatically:
102
102
 
103
103
  ```typescript
104
104
  import { createWorkersAI } from "workers-ai-provider";
105
- import { streamText, convertToModelMessages, tool } from "ai";
105
+ import { streamText, convertToModelMessages, stepCountIs, tool } from "ai";
106
106
  import { z } from "zod";
107
107
 
108
108
  export class ChatAgent extends AIChatAgent {
@@ -122,7 +122,7 @@ export class ChatAgent extends AIChatAgent {
122
122
  }
123
123
  })
124
124
  },
125
- maxSteps: 5
125
+ stopWhen: stepCountIs(5)
126
126
  });
127
127
 
128
128
  return result.toUIMessageStreamResponse();
@@ -188,6 +188,60 @@ const { messages, addToolApprovalResponse } = useAgentChat({ agent });
188
188
  </button>
189
189
  ```
190
190
 
191
+ ### Agent tools
192
+
193
+ `AIChatAgent` subclasses can be used as retained, streaming agent tools from a
194
+ parent agent through `runAgentTool()` or `agentTool()`:
195
+
196
+ ```typescript
197
+ import { AIChatAgent } from "@cloudflare/ai-chat";
198
+ import { agentTool } from "agents/agent-tools";
199
+ import { convertToModelMessages, streamText } from "ai";
200
+ import { z } from "zod";
201
+
202
+ export class Summarizer extends AIChatAgent<Env> {
203
+ protected override formatAgentToolInput(input: { text: string }, request) {
204
+ return {
205
+ id: `agent-tool-${request.runId}-input`,
206
+ role: "user",
207
+ parts: [{ type: "text", text: `Summarize:\n\n${input.text}` }]
208
+ };
209
+ }
210
+
211
+ async onChatMessage() {
212
+ const result = streamText({
213
+ model: this.env.MODEL,
214
+ messages: await convertToModelMessages(this.messages)
215
+ });
216
+
217
+ return result.toUIMessageStreamResponse();
218
+ }
219
+ }
220
+
221
+ export class ChatAgent extends AIChatAgent<Env> {
222
+ async onChatMessage() {
223
+ const result = streamText({
224
+ model: this.env.MODEL,
225
+ messages: await convertToModelMessages(this.messages),
226
+ tools: {
227
+ summarize: agentTool(Summarizer, {
228
+ description: "Summarize long text in a separate retained agent.",
229
+ inputSchema: z.object({ text: z.string() })
230
+ })
231
+ }
232
+ });
233
+
234
+ return result.toUIMessageStreamResponse();
235
+ }
236
+ }
237
+ ```
238
+
239
+ Agent-tool turns are headless. Server-side tools work normally, but
240
+ browser-provided client tools are not available unless you design a separate
241
+ server-side or parent-mediated handoff. Override `formatAgentToolInput()`,
242
+ `getAgentToolOutput()`, and `getAgentToolSummary()` when you need structured
243
+ inputs or outputs.
244
+
191
245
  ## Resumable Streaming
192
246
 
193
247
  Streams automatically resume on disconnect/reconnect. No configuration needed.
@@ -271,7 +325,9 @@ if (result.status === "aborted") {
271
325
 
272
326
  This is the same shape `Think.saveMessages` uses — see
273
327
  [`cloudflare/agents#1406`](https://github.com/cloudflare/agents/issues/1406)
274
- for the helper-as-sub-agent pattern that motivated the API.
328
+ for the agent-tool orchestration pattern that motivated the API. The shipped
329
+ agent-tool API is documented in
330
+ [`docs/agent-tools.md`](../../docs/agent-tools.md).
275
331
 
276
332
  ## Storage Management
277
333
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,10 @@
1
- import { Agent, AgentContext, FiberRecoveryContext } from "agents";
1
+ import {
2
+ Agent,
3
+ AgentContext,
4
+ AgentToolRunInspection,
5
+ AgentToolStoredChunk,
6
+ FiberRecoveryContext
7
+ } from "agents";
2
8
  import {
3
9
  ChatRecoveryContext,
4
10
  ChatRecoveryContext as ChatRecoveryContext$1,
@@ -148,6 +154,13 @@ declare class AIChatAgent<
148
154
  * connections awaiting a continuation stream to start.
149
155
  */
150
156
  private _continuation;
157
+ private _agentToolForwarders;
158
+ private _agentToolClosers;
159
+ private _agentToolAbortControllers;
160
+ private _agentToolLastErrors;
161
+ private _agentToolPreTurnAssistantIds;
162
+ private _agentToolLiveSequences;
163
+ private _agentToolActiveRunId;
151
164
  /**
152
165
  * Client tool schemas from the most recent chat request.
153
166
  * Stored so they can be passed to onChatMessage during tool continuations.
@@ -250,7 +263,12 @@ declare class AIChatAgent<
250
263
  * mutate the array directly.
251
264
  */
252
265
  messages: UIMessage[];
266
+ broadcast(
267
+ msg: string | ArrayBuffer | ArrayBufferView,
268
+ without?: string[]
269
+ ): void;
253
270
  constructor(ctx: AgentContext, env: Env);
271
+ private _ensureAgentToolTables;
254
272
  private _flushAwaitingStreamStartConnections;
255
273
  private _mergeAutoContinuationPrerequisite;
256
274
  private _storeDeferredAutoContinuation;
@@ -470,6 +488,68 @@ declare class AIChatAgent<
470
488
  * ```
471
489
  */
472
490
  protected sanitizeMessageForPersistence(message: UIMessage): UIMessage;
491
+ /**
492
+ * Convert an agent-tool input payload into the synthetic user message that
493
+ * starts a headless `AIChatAgent` turn.
494
+ */
495
+ protected formatAgentToolInput(
496
+ input: unknown,
497
+ request: {
498
+ runId: string;
499
+ }
500
+ ): UIMessage;
501
+ /**
502
+ * Override to return structured agent-tool output instead of the default
503
+ * final assistant text.
504
+ */
505
+ protected getAgentToolOutput(
506
+ _request: {
507
+ runId: string;
508
+ input: unknown;
509
+ },
510
+ messagesAfterStart: readonly UIMessage[]
511
+ ): unknown;
512
+ /**
513
+ * Override to customize the concise summary stored on the parent run.
514
+ */
515
+ protected getAgentToolSummary(
516
+ _request: {
517
+ runId: string;
518
+ input: unknown;
519
+ },
520
+ output: unknown,
521
+ messagesAfterStart: readonly UIMessage[]
522
+ ): string;
523
+ startAgentToolRun(
524
+ input: unknown,
525
+ options: {
526
+ runId: string;
527
+ signal?: AbortSignal;
528
+ }
529
+ ): Promise<AgentToolRunInspection>;
530
+ cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
531
+ inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
532
+ getAgentToolChunks(
533
+ runId: string,
534
+ options?: {
535
+ afterSequence?: number;
536
+ }
537
+ ): Promise<AgentToolStoredChunk[]>;
538
+ tailAgentToolRun(
539
+ runId: string,
540
+ options?: {
541
+ afterSequence?: number;
542
+ signal?: AbortSignal;
543
+ }
544
+ ): Promise<ReadableStream<AgentToolStoredChunk>>;
545
+ private _getAgentToolRunRow;
546
+ private _getAgentToolStreamId;
547
+ private _getAgentToolStoredChunks;
548
+ private _getAgentToolMessagesAfterStart;
549
+ private _closeAgentToolTailers;
550
+ private static _stringifyAgentToolValue;
551
+ private static _parseAgentToolValue;
552
+ private static _extractLatestAssistantText;
473
553
  /**
474
554
  * Persist messages and trigger `onChatMessage()` for a new response.
475
555
  *
package/dist/index.js CHANGED
@@ -36,6 +36,7 @@ function isValidMessageStructure(msg) {
36
36
  return true;
37
37
  }
38
38
  const decoder = new TextDecoder();
39
+ const agentToolChunkEncoder = new TextEncoder();
39
40
  /**
40
41
  * Extension of Agent with built-in chat capabilities
41
42
  * @template Env Environment type containing bindings
@@ -47,6 +48,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
47
48
  static {
48
49
  this.MESSAGE_DEBOUNCE_MS = 750;
49
50
  }
51
+ broadcast(msg, without) {
52
+ if (this._agentToolForwarders.size > 0 && typeof msg === "string") try {
53
+ const parsed = JSON.parse(msg);
54
+ if (parsed.type === "cf_agent_use_chat_response") {
55
+ if (parsed.error === true && typeof parsed.body === "string") {
56
+ const runIds = this._agentToolActiveRunId !== null ? [this._agentToolActiveRunId] : [...this._agentToolForwarders.keys()];
57
+ for (const runId of runIds) this._agentToolLastErrors.set(runId, parsed.body);
58
+ } else if (typeof parsed.body === "string" && parsed.body.length > 0) {
59
+ const entries = this._agentToolActiveRunId !== null ? [[this._agentToolActiveRunId, this._agentToolForwarders.get(this._agentToolActiveRunId) ?? /* @__PURE__ */ new Set()]] : [...this._agentToolForwarders.entries()];
60
+ for (const [runId, forwarders] of entries) {
61
+ const sequence = this._agentToolLiveSequences.get(runId) ?? 0;
62
+ this._agentToolLiveSequences.set(runId, sequence + 1);
63
+ const chunk = {
64
+ sequence,
65
+ body: parsed.body
66
+ };
67
+ for (const forward of forwarders) forward(chunk);
68
+ }
69
+ }
70
+ }
71
+ } catch {}
72
+ super.broadcast(msg, without);
73
+ }
50
74
  constructor(ctx, env) {
51
75
  super(ctx, env);
52
76
  this._streamingMessage = null;
@@ -60,6 +84,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
60
84
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: AIChatAgent.MESSAGE_DEBOUNCE_MS });
61
85
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
62
86
  this._continuation = new ContinuationState();
87
+ this._agentToolForwarders = /* @__PURE__ */ new Map();
88
+ this._agentToolClosers = /* @__PURE__ */ new Map();
89
+ this._agentToolAbortControllers = /* @__PURE__ */ new Map();
90
+ this._agentToolLastErrors = /* @__PURE__ */ new Map();
91
+ this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
92
+ this._agentToolLiveSequences = /* @__PURE__ */ new Map();
93
+ this._agentToolActiveRunId = null;
63
94
  this._persistedMessageCache = /* @__PURE__ */ new Map();
64
95
  this.maxPersistedMessages = void 0;
65
96
  this.messageConcurrency = "queue";
@@ -74,6 +105,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
74
105
  key text primary key,
75
106
  value text not null
76
107
  )`;
108
+ this._ensureAgentToolTables();
77
109
  this._restoreRequestContext();
78
110
  this._resumableStream = new ResumableStream(this.sql.bind(this));
79
111
  const rawMessages = this._loadMessagesFromDb();
@@ -81,6 +113,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
81
113
  this._abortRegistry = new AbortRegistry();
82
114
  const _onConnect = this.onConnect.bind(this);
83
115
  this.onConnect = async (connection, ctx) => {
116
+ if (this._cf_requestTargetsSubAgent(ctx.request)) return _onConnect(connection, ctx);
84
117
  if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
85
118
  return _onConnect(connection, ctx);
86
119
  };
@@ -94,6 +127,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
94
127
  };
95
128
  const _onMessage = this.onMessage.bind(this);
96
129
  this.onMessage = async (connection, message) => {
130
+ if (this._cf_connectionTargetsSubAgent(connection)) return _onMessage(connection, message);
97
131
  if (typeof message === "string") {
98
132
  let data;
99
133
  try {
@@ -249,7 +283,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
249
283
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
250
284
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
251
285
  if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
252
- }
286
+ } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, data.id)) connection.send(JSON.stringify({
287
+ body: "",
288
+ done: true,
289
+ id: data.id,
290
+ type: "cf_agent_use_chat_response",
291
+ replay: true
292
+ }));
253
293
  return;
254
294
  }
255
295
  if (data.type === "cf_agent_tool_result") {
@@ -296,6 +336,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
296
336
  });
297
337
  };
298
338
  }
339
+ _ensureAgentToolTables() {
340
+ this.sql`create table if not exists cf_ai_chat_agent_tool_runs (
341
+ run_id text primary key,
342
+ request_id text,
343
+ status text not null,
344
+ input_json text,
345
+ output_json text,
346
+ summary text,
347
+ error_message text,
348
+ started_at integer not null,
349
+ completed_at integer
350
+ )`;
351
+ const addColumnIfNotExists = (sql) => {
352
+ try {
353
+ this.ctx.storage.sql.exec(sql);
354
+ } catch (error) {
355
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
356
+ }
357
+ };
358
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column input_json text");
359
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column output_json text");
360
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column summary text");
361
+ this.sql`create index if not exists idx_ai_chat_agent_tool_request_id
362
+ on cf_ai_chat_agent_tool_runs(request_id)`;
363
+ }
299
364
  _flushAwaitingStreamStartConnections() {
300
365
  if (!this._resumableStream.hasActiveStream()) return;
301
366
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
@@ -988,6 +1053,306 @@ var AIChatAgent = class AIChatAgent extends Agent {
988
1053
  return message;
989
1054
  }
990
1055
  /**
1056
+ * Convert an agent-tool input payload into the synthetic user message that
1057
+ * starts a headless `AIChatAgent` turn.
1058
+ */
1059
+ formatAgentToolInput(input, request) {
1060
+ let text;
1061
+ try {
1062
+ text = typeof input === "string" ? input : JSON.stringify(input, null, 2);
1063
+ } catch {
1064
+ text = String(input);
1065
+ }
1066
+ return {
1067
+ id: `agent-tool-${request.runId}-input`,
1068
+ role: "user",
1069
+ parts: [{
1070
+ type: "text",
1071
+ text
1072
+ }]
1073
+ };
1074
+ }
1075
+ /**
1076
+ * Override to return structured agent-tool output instead of the default
1077
+ * final assistant text.
1078
+ */
1079
+ getAgentToolOutput(_request, messagesAfterStart) {
1080
+ return AIChatAgent._extractLatestAssistantText(messagesAfterStart);
1081
+ }
1082
+ /**
1083
+ * Override to customize the concise summary stored on the parent run.
1084
+ */
1085
+ getAgentToolSummary(_request, output, messagesAfterStart) {
1086
+ if (typeof output === "string") return output;
1087
+ if (output === void 0) return AIChatAgent._extractLatestAssistantText(messagesAfterStart) ?? "";
1088
+ try {
1089
+ return JSON.stringify(output);
1090
+ } catch {
1091
+ return String(output);
1092
+ }
1093
+ }
1094
+ async startAgentToolRun(input, options) {
1095
+ const existing = await this.inspectAgentToolRun(options.runId);
1096
+ if (existing) return existing;
1097
+ const startedAt = Date.now();
1098
+ const controller = new AbortController();
1099
+ const assistantIdsBeforeStart = new Set(this.messages.filter((message) => message.role === "assistant").map((message) => message.id));
1100
+ this.sql`
1101
+ insert into cf_ai_chat_agent_tool_runs
1102
+ (run_id, request_id, status, input_json, started_at)
1103
+ values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt})
1104
+ `;
1105
+ this._agentToolAbortControllers.set(options.runId, controller);
1106
+ this._agentToolPreTurnAssistantIds.set(options.runId, assistantIdsBeforeStart);
1107
+ this._agentToolLiveSequences.set(options.runId, 0);
1108
+ const abortFromParent = () => controller.abort(options.signal?.reason);
1109
+ if (options.signal?.aborted) abortFromParent();
1110
+ else options.signal?.addEventListener("abort", abortFromParent, { once: true });
1111
+ const lifecycle = async () => {
1112
+ let requestId;
1113
+ try {
1114
+ const previousClientTools = this._lastClientTools;
1115
+ const previousBody = this._lastBody;
1116
+ this._setRequestContext(void 0, { agentToolInput: input });
1117
+ const result = await this.saveMessages(async (messages) => {
1118
+ this._agentToolActiveRunId = options.runId;
1119
+ return [...messages, this.formatAgentToolInput(input, { runId: options.runId })];
1120
+ }, { signal: controller.signal }).finally(() => {
1121
+ this._setRequestContext(previousClientTools, previousBody);
1122
+ });
1123
+ requestId = result.requestId;
1124
+ if (result.status === "aborted") {
1125
+ this.sql`
1126
+ update cf_ai_chat_agent_tool_runs
1127
+ set request_id = ${requestId}, status = 'aborted',
1128
+ completed_at = ${Date.now()}
1129
+ where run_id = ${options.runId}
1130
+ `;
1131
+ return;
1132
+ }
1133
+ if (result.status === "skipped") {
1134
+ this.sql`
1135
+ update cf_ai_chat_agent_tool_runs
1136
+ set request_id = ${requestId}, status = 'error',
1137
+ error_message = 'Agent tool run was skipped because the chat was cleared.',
1138
+ completed_at = ${Date.now()}
1139
+ where run_id = ${options.runId}
1140
+ `;
1141
+ return;
1142
+ }
1143
+ const streamError = this._agentToolLastErrors.get(options.runId);
1144
+ if (streamError) {
1145
+ this.sql`
1146
+ update cf_ai_chat_agent_tool_runs
1147
+ set request_id = ${requestId}, status = 'error',
1148
+ error_message = ${streamError}, completed_at = ${Date.now()}
1149
+ where run_id = ${options.runId}
1150
+ `;
1151
+ return;
1152
+ }
1153
+ const messagesAfterStart = this._getAgentToolMessagesAfterStart(options.runId);
1154
+ const output = this.getAgentToolOutput({
1155
+ runId: options.runId,
1156
+ input
1157
+ }, messagesAfterStart);
1158
+ const summary = this.getAgentToolSummary({
1159
+ runId: options.runId,
1160
+ input
1161
+ }, output, messagesAfterStart);
1162
+ this.sql`
1163
+ update cf_ai_chat_agent_tool_runs
1164
+ set request_id = ${requestId}, status = 'completed',
1165
+ output_json = ${AIChatAgent._stringifyAgentToolValue(output)},
1166
+ summary = ${summary}, error_message = null,
1167
+ completed_at = ${Date.now()}
1168
+ where run_id = ${options.runId}
1169
+ `;
1170
+ } catch (error) {
1171
+ if (controller.signal.aborted) {
1172
+ this.sql`
1173
+ update cf_ai_chat_agent_tool_runs
1174
+ set request_id = ${requestId ?? null}, status = 'aborted',
1175
+ completed_at = ${Date.now()}
1176
+ where run_id = ${options.runId}
1177
+ `;
1178
+ return;
1179
+ }
1180
+ const message = error instanceof Error ? error.message : String(error);
1181
+ this._agentToolLastErrors.set(options.runId, message);
1182
+ this.sql`
1183
+ update cf_ai_chat_agent_tool_runs
1184
+ set request_id = ${requestId ?? null}, status = 'error',
1185
+ error_message = ${message}, completed_at = ${Date.now()}
1186
+ where run_id = ${options.runId}
1187
+ `;
1188
+ } finally {
1189
+ options.signal?.removeEventListener("abort", abortFromParent);
1190
+ this._agentToolAbortControllers.delete(options.runId);
1191
+ this._agentToolLiveSequences.delete(options.runId);
1192
+ if (this._agentToolActiveRunId === options.runId) this._agentToolActiveRunId = null;
1193
+ this._agentToolLastErrors.delete(options.runId);
1194
+ this._agentToolPreTurnAssistantIds.delete(options.runId);
1195
+ this._closeAgentToolTailers(options.runId);
1196
+ }
1197
+ };
1198
+ this.keepAliveWhile(lifecycle);
1199
+ return {
1200
+ runId: options.runId,
1201
+ status: "running",
1202
+ startedAt
1203
+ };
1204
+ }
1205
+ async cancelAgentToolRun(runId, reason) {
1206
+ this._agentToolAbortControllers.get(runId)?.abort(reason);
1207
+ this.sql`
1208
+ update cf_ai_chat_agent_tool_runs
1209
+ set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})
1210
+ where run_id = ${runId} and status = 'running'
1211
+ `;
1212
+ this._closeAgentToolTailers(runId);
1213
+ }
1214
+ async inspectAgentToolRun(runId) {
1215
+ const row = this._getAgentToolRunRow(runId);
1216
+ if (!row) return null;
1217
+ if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) {
1218
+ const error = "Agent tool run was interrupted before the child could finish.";
1219
+ this.sql`
1220
+ update cf_ai_chat_agent_tool_runs
1221
+ set status = 'error', error_message = ${error}, completed_at = ${Date.now()}
1222
+ where run_id = ${runId}
1223
+ `;
1224
+ row.status = "error";
1225
+ row.error_message = error;
1226
+ row.completed_at = Date.now();
1227
+ }
1228
+ const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
1229
+ const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1230
+ const input = AIChatAgent._parseAgentToolValue(row.input_json);
1231
+ const output = row.status === "completed" ? AIChatAgent._parseAgentToolValue(row.output_json) ?? this.getAgentToolOutput({
1232
+ runId,
1233
+ input
1234
+ }, messagesAfterStart) : void 0;
1235
+ return {
1236
+ runId,
1237
+ status: row.status,
1238
+ requestId: row.request_id ?? void 0,
1239
+ streamId,
1240
+ output,
1241
+ summary: row.status === "completed" ? row.summary ?? "" : void 0,
1242
+ error: row.status === "error" ? row.error_message ?? void 0 : void 0,
1243
+ startedAt: row.started_at,
1244
+ completedAt: row.completed_at ?? void 0
1245
+ };
1246
+ }
1247
+ async getAgentToolChunks(runId, options) {
1248
+ this._flushChunkBuffer();
1249
+ const row = this._getAgentToolRunRow(runId);
1250
+ if (!row?.request_id) return [];
1251
+ return this._getAgentToolStoredChunks(row.request_id, options?.afterSequence);
1252
+ }
1253
+ async tailAgentToolRun(runId, options) {
1254
+ return new ReadableStream({
1255
+ start: async (controller) => {
1256
+ let closed = false;
1257
+ const close = () => {
1258
+ if (closed) return;
1259
+ closed = true;
1260
+ controller.close();
1261
+ };
1262
+ const onAbort = () => close();
1263
+ try {
1264
+ if (options?.signal?.aborted) {
1265
+ close();
1266
+ return;
1267
+ }
1268
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
1269
+ for (const chunk of await this.getAgentToolChunks(runId, options)) {
1270
+ if (closed) return;
1271
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1272
+ }
1273
+ const inspection = await this.inspectAgentToolRun(runId);
1274
+ if (!inspection || inspection.status !== "running") {
1275
+ close();
1276
+ return;
1277
+ }
1278
+ const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1279
+ const forward = (chunk) => {
1280
+ if (!closed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1281
+ };
1282
+ forwarders.add(forward);
1283
+ this._agentToolForwarders.set(runId, forwarders);
1284
+ const closers = this._agentToolClosers.get(runId) ?? /* @__PURE__ */ new Set();
1285
+ closers.add(close);
1286
+ this._agentToolClosers.set(runId, closers);
1287
+ } catch (error) {
1288
+ controller.error(error);
1289
+ }
1290
+ },
1291
+ cancel: () => {}
1292
+ });
1293
+ }
1294
+ _getAgentToolRunRow(runId) {
1295
+ return this.sql`
1296
+ select run_id, request_id, status, input_json, output_json, summary,
1297
+ error_message, started_at, completed_at
1298
+ from cf_ai_chat_agent_tool_runs
1299
+ where run_id = ${runId}
1300
+ `[0] ?? null;
1301
+ }
1302
+ _getAgentToolStreamId(requestId) {
1303
+ return this.sql`
1304
+ select id, status, request_id
1305
+ from cf_ai_chat_stream_metadata
1306
+ where request_id = ${requestId}
1307
+ order by rowid desc
1308
+ limit 1
1309
+ `[0]?.id;
1310
+ }
1311
+ _getAgentToolStoredChunks(requestId, afterSequence = -1) {
1312
+ const streamId = this._getAgentToolStreamId(requestId);
1313
+ if (!streamId) return [];
1314
+ return this.sql`
1315
+ select body, chunk_index
1316
+ from cf_ai_chat_stream_chunks
1317
+ where stream_id = ${streamId} and chunk_index > ${afterSequence}
1318
+ order by chunk_index asc
1319
+ `.map((row) => ({
1320
+ sequence: row.chunk_index,
1321
+ body: row.body
1322
+ }));
1323
+ }
1324
+ _getAgentToolMessagesAfterStart(runId) {
1325
+ const previousAssistantIds = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
1326
+ return this.messages.filter((message) => message.role !== "assistant" || !previousAssistantIds.has(message.id));
1327
+ }
1328
+ _closeAgentToolTailers(runId) {
1329
+ const closers = this._agentToolClosers.get(runId);
1330
+ if (closers) {
1331
+ for (const close of closers) close();
1332
+ this._agentToolClosers.delete(runId);
1333
+ }
1334
+ this._agentToolForwarders.delete(runId);
1335
+ }
1336
+ static _stringifyAgentToolValue(value) {
1337
+ if (value === void 0) return null;
1338
+ const json = JSON.stringify(value);
1339
+ return json === void 0 ? null : json;
1340
+ }
1341
+ static _parseAgentToolValue(value) {
1342
+ if (value === null) return void 0;
1343
+ try {
1344
+ return JSON.parse(value);
1345
+ } catch {
1346
+ return value;
1347
+ }
1348
+ }
1349
+ static _extractLatestAssistantText(messages) {
1350
+ const message = [...messages].reverse().find((candidate) => candidate.role === "assistant");
1351
+ if (!message) return void 0;
1352
+ const text = message.parts.filter((part) => part.type === "text").map((part) => part.text).join("");
1353
+ return text.length > 0 ? text : void 0;
1354
+ }
1355
+ /**
991
1356
  * Persist messages and trigger `onChatMessage()` for a new response.
992
1357
  *
993
1358
  * Waits for any active chat turn to finish before starting, so scheduled