@cloudflare/ai-chat 0.5.3 → 0.6.0

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/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, reconcileMessages, resolveToolMergeId, sanitizeMessage } from "agents/chat";
4
+ import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, SubmitConcurrencyController, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, isReplayChunk, reconcileMessages, resolveToolMergeId, sanitizeMessage } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
6
  //#region src/index.ts
7
7
  const TIMED_OUT = Symbol("timed-out");
@@ -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();
@@ -296,6 +328,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
296
328
  });
297
329
  };
298
330
  }
331
+ _ensureAgentToolTables() {
332
+ this.sql`create table if not exists cf_ai_chat_agent_tool_runs (
333
+ run_id text primary key,
334
+ request_id text,
335
+ status text not null,
336
+ input_json text,
337
+ output_json text,
338
+ summary text,
339
+ error_message text,
340
+ started_at integer not null,
341
+ completed_at integer
342
+ )`;
343
+ const addColumnIfNotExists = (sql) => {
344
+ try {
345
+ this.ctx.storage.sql.exec(sql);
346
+ } catch (error) {
347
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
348
+ }
349
+ };
350
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column input_json text");
351
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column output_json text");
352
+ addColumnIfNotExists("alter table cf_ai_chat_agent_tool_runs add column summary text");
353
+ this.sql`create index if not exists idx_ai_chat_agent_tool_request_id
354
+ on cf_ai_chat_agent_tool_runs(request_id)`;
355
+ }
299
356
  _flushAwaitingStreamStartConnections() {
300
357
  if (!this._resumableStream.hasActiveStream()) return;
301
358
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
@@ -988,6 +1045,306 @@ var AIChatAgent = class AIChatAgent extends Agent {
988
1045
  return message;
989
1046
  }
990
1047
  /**
1048
+ * Convert an agent-tool input payload into the synthetic user message that
1049
+ * starts a headless `AIChatAgent` turn.
1050
+ */
1051
+ formatAgentToolInput(input, request) {
1052
+ let text;
1053
+ try {
1054
+ text = typeof input === "string" ? input : JSON.stringify(input, null, 2);
1055
+ } catch {
1056
+ text = String(input);
1057
+ }
1058
+ return {
1059
+ id: `agent-tool-${request.runId}-input`,
1060
+ role: "user",
1061
+ parts: [{
1062
+ type: "text",
1063
+ text
1064
+ }]
1065
+ };
1066
+ }
1067
+ /**
1068
+ * Override to return structured agent-tool output instead of the default
1069
+ * final assistant text.
1070
+ */
1071
+ getAgentToolOutput(_request, messagesAfterStart) {
1072
+ return AIChatAgent._extractLatestAssistantText(messagesAfterStart);
1073
+ }
1074
+ /**
1075
+ * Override to customize the concise summary stored on the parent run.
1076
+ */
1077
+ getAgentToolSummary(_request, output, messagesAfterStart) {
1078
+ if (typeof output === "string") return output;
1079
+ if (output === void 0) return AIChatAgent._extractLatestAssistantText(messagesAfterStart) ?? "";
1080
+ try {
1081
+ return JSON.stringify(output);
1082
+ } catch {
1083
+ return String(output);
1084
+ }
1085
+ }
1086
+ async startAgentToolRun(input, options) {
1087
+ const existing = await this.inspectAgentToolRun(options.runId);
1088
+ if (existing) return existing;
1089
+ const startedAt = Date.now();
1090
+ const controller = new AbortController();
1091
+ const assistantIdsBeforeStart = new Set(this.messages.filter((message) => message.role === "assistant").map((message) => message.id));
1092
+ this.sql`
1093
+ insert into cf_ai_chat_agent_tool_runs
1094
+ (run_id, request_id, status, input_json, started_at)
1095
+ values (${options.runId}, null, 'running', ${AIChatAgent._stringifyAgentToolValue(input)}, ${startedAt})
1096
+ `;
1097
+ this._agentToolAbortControllers.set(options.runId, controller);
1098
+ this._agentToolPreTurnAssistantIds.set(options.runId, assistantIdsBeforeStart);
1099
+ this._agentToolLiveSequences.set(options.runId, 0);
1100
+ const abortFromParent = () => controller.abort(options.signal?.reason);
1101
+ if (options.signal?.aborted) abortFromParent();
1102
+ else options.signal?.addEventListener("abort", abortFromParent, { once: true });
1103
+ const lifecycle = async () => {
1104
+ let requestId;
1105
+ try {
1106
+ const previousClientTools = this._lastClientTools;
1107
+ const previousBody = this._lastBody;
1108
+ this._setRequestContext(void 0, { agentToolInput: input });
1109
+ const result = await this.saveMessages(async (messages) => {
1110
+ this._agentToolActiveRunId = options.runId;
1111
+ return [...messages, this.formatAgentToolInput(input, { runId: options.runId })];
1112
+ }, { signal: controller.signal }).finally(() => {
1113
+ this._setRequestContext(previousClientTools, previousBody);
1114
+ });
1115
+ requestId = result.requestId;
1116
+ if (result.status === "aborted") {
1117
+ this.sql`
1118
+ update cf_ai_chat_agent_tool_runs
1119
+ set request_id = ${requestId}, status = 'aborted',
1120
+ completed_at = ${Date.now()}
1121
+ where run_id = ${options.runId}
1122
+ `;
1123
+ return;
1124
+ }
1125
+ if (result.status === "skipped") {
1126
+ this.sql`
1127
+ update cf_ai_chat_agent_tool_runs
1128
+ set request_id = ${requestId}, status = 'error',
1129
+ error_message = 'Agent tool run was skipped because the chat was cleared.',
1130
+ completed_at = ${Date.now()}
1131
+ where run_id = ${options.runId}
1132
+ `;
1133
+ return;
1134
+ }
1135
+ const streamError = this._agentToolLastErrors.get(options.runId);
1136
+ if (streamError) {
1137
+ this.sql`
1138
+ update cf_ai_chat_agent_tool_runs
1139
+ set request_id = ${requestId}, status = 'error',
1140
+ error_message = ${streamError}, completed_at = ${Date.now()}
1141
+ where run_id = ${options.runId}
1142
+ `;
1143
+ return;
1144
+ }
1145
+ const messagesAfterStart = this._getAgentToolMessagesAfterStart(options.runId);
1146
+ const output = this.getAgentToolOutput({
1147
+ runId: options.runId,
1148
+ input
1149
+ }, messagesAfterStart);
1150
+ const summary = this.getAgentToolSummary({
1151
+ runId: options.runId,
1152
+ input
1153
+ }, output, messagesAfterStart);
1154
+ this.sql`
1155
+ update cf_ai_chat_agent_tool_runs
1156
+ set request_id = ${requestId}, status = 'completed',
1157
+ output_json = ${AIChatAgent._stringifyAgentToolValue(output)},
1158
+ summary = ${summary}, error_message = null,
1159
+ completed_at = ${Date.now()}
1160
+ where run_id = ${options.runId}
1161
+ `;
1162
+ } catch (error) {
1163
+ if (controller.signal.aborted) {
1164
+ this.sql`
1165
+ update cf_ai_chat_agent_tool_runs
1166
+ set request_id = ${requestId ?? null}, status = 'aborted',
1167
+ completed_at = ${Date.now()}
1168
+ where run_id = ${options.runId}
1169
+ `;
1170
+ return;
1171
+ }
1172
+ const message = error instanceof Error ? error.message : String(error);
1173
+ this._agentToolLastErrors.set(options.runId, message);
1174
+ this.sql`
1175
+ update cf_ai_chat_agent_tool_runs
1176
+ set request_id = ${requestId ?? null}, status = 'error',
1177
+ error_message = ${message}, completed_at = ${Date.now()}
1178
+ where run_id = ${options.runId}
1179
+ `;
1180
+ } finally {
1181
+ options.signal?.removeEventListener("abort", abortFromParent);
1182
+ this._agentToolAbortControllers.delete(options.runId);
1183
+ this._agentToolLiveSequences.delete(options.runId);
1184
+ if (this._agentToolActiveRunId === options.runId) this._agentToolActiveRunId = null;
1185
+ this._agentToolLastErrors.delete(options.runId);
1186
+ this._agentToolPreTurnAssistantIds.delete(options.runId);
1187
+ this._closeAgentToolTailers(options.runId);
1188
+ }
1189
+ };
1190
+ this.keepAliveWhile(lifecycle);
1191
+ return {
1192
+ runId: options.runId,
1193
+ status: "running",
1194
+ startedAt
1195
+ };
1196
+ }
1197
+ async cancelAgentToolRun(runId, reason) {
1198
+ this._agentToolAbortControllers.get(runId)?.abort(reason);
1199
+ this.sql`
1200
+ update cf_ai_chat_agent_tool_runs
1201
+ set status = 'aborted', completed_at = coalesce(completed_at, ${Date.now()})
1202
+ where run_id = ${runId} and status = 'running'
1203
+ `;
1204
+ this._closeAgentToolTailers(runId);
1205
+ }
1206
+ async inspectAgentToolRun(runId) {
1207
+ const row = this._getAgentToolRunRow(runId);
1208
+ if (!row) return null;
1209
+ if (row.status === "running" && !this._agentToolAbortControllers.has(runId)) {
1210
+ const error = "Agent tool run was interrupted before the child could finish.";
1211
+ this.sql`
1212
+ update cf_ai_chat_agent_tool_runs
1213
+ set status = 'error', error_message = ${error}, completed_at = ${Date.now()}
1214
+ where run_id = ${runId}
1215
+ `;
1216
+ row.status = "error";
1217
+ row.error_message = error;
1218
+ row.completed_at = Date.now();
1219
+ }
1220
+ const streamId = row.request_id ? this._getAgentToolStreamId(row.request_id) : void 0;
1221
+ const messagesAfterStart = this._getAgentToolMessagesAfterStart(runId);
1222
+ const input = AIChatAgent._parseAgentToolValue(row.input_json);
1223
+ const output = row.status === "completed" ? AIChatAgent._parseAgentToolValue(row.output_json) ?? this.getAgentToolOutput({
1224
+ runId,
1225
+ input
1226
+ }, messagesAfterStart) : void 0;
1227
+ return {
1228
+ runId,
1229
+ status: row.status,
1230
+ requestId: row.request_id ?? void 0,
1231
+ streamId,
1232
+ output,
1233
+ summary: row.status === "completed" ? row.summary ?? "" : void 0,
1234
+ error: row.status === "error" ? row.error_message ?? void 0 : void 0,
1235
+ startedAt: row.started_at,
1236
+ completedAt: row.completed_at ?? void 0
1237
+ };
1238
+ }
1239
+ async getAgentToolChunks(runId, options) {
1240
+ this._flushChunkBuffer();
1241
+ const row = this._getAgentToolRunRow(runId);
1242
+ if (!row?.request_id) return [];
1243
+ return this._getAgentToolStoredChunks(row.request_id, options?.afterSequence);
1244
+ }
1245
+ async tailAgentToolRun(runId, options) {
1246
+ return new ReadableStream({
1247
+ start: async (controller) => {
1248
+ let closed = false;
1249
+ const close = () => {
1250
+ if (closed) return;
1251
+ closed = true;
1252
+ controller.close();
1253
+ };
1254
+ const onAbort = () => close();
1255
+ try {
1256
+ if (options?.signal?.aborted) {
1257
+ close();
1258
+ return;
1259
+ }
1260
+ options?.signal?.addEventListener("abort", onAbort, { once: true });
1261
+ for (const chunk of await this.getAgentToolChunks(runId, options)) {
1262
+ if (closed) return;
1263
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1264
+ }
1265
+ const inspection = await this.inspectAgentToolRun(runId);
1266
+ if (!inspection || inspection.status !== "running") {
1267
+ close();
1268
+ return;
1269
+ }
1270
+ const forwarders = this._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1271
+ const forward = (chunk) => {
1272
+ if (!closed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1273
+ };
1274
+ forwarders.add(forward);
1275
+ this._agentToolForwarders.set(runId, forwarders);
1276
+ const closers = this._agentToolClosers.get(runId) ?? /* @__PURE__ */ new Set();
1277
+ closers.add(close);
1278
+ this._agentToolClosers.set(runId, closers);
1279
+ } catch (error) {
1280
+ controller.error(error);
1281
+ }
1282
+ },
1283
+ cancel: () => {}
1284
+ });
1285
+ }
1286
+ _getAgentToolRunRow(runId) {
1287
+ return this.sql`
1288
+ select run_id, request_id, status, input_json, output_json, summary,
1289
+ error_message, started_at, completed_at
1290
+ from cf_ai_chat_agent_tool_runs
1291
+ where run_id = ${runId}
1292
+ `[0] ?? null;
1293
+ }
1294
+ _getAgentToolStreamId(requestId) {
1295
+ return this.sql`
1296
+ select id, status, request_id
1297
+ from cf_ai_chat_stream_metadata
1298
+ where request_id = ${requestId}
1299
+ order by rowid desc
1300
+ limit 1
1301
+ `[0]?.id;
1302
+ }
1303
+ _getAgentToolStoredChunks(requestId, afterSequence = -1) {
1304
+ const streamId = this._getAgentToolStreamId(requestId);
1305
+ if (!streamId) return [];
1306
+ return this.sql`
1307
+ select body, chunk_index
1308
+ from cf_ai_chat_stream_chunks
1309
+ where stream_id = ${streamId} and chunk_index > ${afterSequence}
1310
+ order by chunk_index asc
1311
+ `.map((row) => ({
1312
+ sequence: row.chunk_index,
1313
+ body: row.body
1314
+ }));
1315
+ }
1316
+ _getAgentToolMessagesAfterStart(runId) {
1317
+ const previousAssistantIds = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
1318
+ return this.messages.filter((message) => message.role !== "assistant" || !previousAssistantIds.has(message.id));
1319
+ }
1320
+ _closeAgentToolTailers(runId) {
1321
+ const closers = this._agentToolClosers.get(runId);
1322
+ if (closers) {
1323
+ for (const close of closers) close();
1324
+ this._agentToolClosers.delete(runId);
1325
+ }
1326
+ this._agentToolForwarders.delete(runId);
1327
+ }
1328
+ static _stringifyAgentToolValue(value) {
1329
+ if (value === void 0) return null;
1330
+ const json = JSON.stringify(value);
1331
+ return json === void 0 ? null : json;
1332
+ }
1333
+ static _parseAgentToolValue(value) {
1334
+ if (value === null) return void 0;
1335
+ try {
1336
+ return JSON.parse(value);
1337
+ } catch {
1338
+ return value;
1339
+ }
1340
+ }
1341
+ static _extractLatestAssistantText(messages) {
1342
+ const message = [...messages].reverse().find((candidate) => candidate.role === "assistant");
1343
+ if (!message) return void 0;
1344
+ const text = message.parts.filter((part) => part.type === "text").map((part) => part.text).join("");
1345
+ return text.length > 0 ? text : void 0;
1346
+ }
1347
+ /**
991
1348
  * Persist messages and trigger `onChatMessage()` for a new response.
992
1349
  *
993
1350
  * Waits for any active chat turn to finish before starting, so scheduled
@@ -1470,11 +1827,17 @@ var AIChatAgent = class AIChatAgent extends Agent {
1470
1827
  * the AI is still streaming), then retries persisted messages with backoff
1471
1828
  * in case streaming completes between attempts.
1472
1829
  *
1830
+ * `applyUpdate` may return its argument by reference (or `{ ...part }`
1831
+ * with no semantic changes) to signal an idempotent no-op — this is
1832
+ * detected via `_isToolPartUnchanged` and short-circuits the SQLite
1833
+ * write and `MESSAGE_UPDATED` broadcast.
1834
+ *
1473
1835
  * @param toolCallId - The tool call ID to find
1474
1836
  * @param callerName - Name for log messages (e.g. "_applyToolResult")
1475
1837
  * @param matchStates - Which tool part states to match
1476
1838
  * @param applyUpdate - Mutation to apply to the matched part (streaming: in-place, persisted: spread)
1477
- * @returns true if the update was applied, false if not found or state didn't match
1839
+ * @returns true if the update was applied (or matched as an idempotent
1840
+ * no-op), false if no matching part was found
1478
1841
  */
1479
1842
  async _findAndUpdateToolPart(toolCallId, callerName, matchStates, applyUpdate) {
1480
1843
  let message;
@@ -1494,23 +1857,30 @@ var AIChatAgent = class AIChatAgent extends Agent {
1494
1857
  return false;
1495
1858
  }
1496
1859
  const isStreamingMessage = message === this._streamingMessage;
1497
- let updated = false;
1860
+ let wasFound = false;
1861
+ let hasRealChange = false;
1498
1862
  if (isStreamingMessage) {
1499
1863
  for (const part of message.parts) if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
1864
+ wasFound = true;
1500
1865
  const applied = applyUpdate(part);
1501
- Object.assign(part, applied);
1502
- updated = true;
1866
+ if (!AIChatAgent._isToolPartUnchanged(part, applied)) {
1867
+ Object.assign(part, applied);
1868
+ hasRealChange = true;
1869
+ }
1503
1870
  break;
1504
1871
  }
1505
1872
  } else {
1506
1873
  const updatedParts = message.parts.map((part) => {
1507
1874
  if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && matchStates.includes(part.state)) {
1508
- updated = true;
1509
- return applyUpdate(part);
1875
+ wasFound = true;
1876
+ const applied = applyUpdate(part);
1877
+ if (AIChatAgent._isToolPartUnchanged(part, applied)) return part;
1878
+ hasRealChange = true;
1879
+ return applied;
1510
1880
  }
1511
1881
  return part;
1512
1882
  });
1513
- if (updated) {
1883
+ if (hasRealChange) {
1514
1884
  const updatedMessage = this._sanitizeMessageForPersistence({
1515
1885
  ...message,
1516
1886
  parts: updatedParts
@@ -1527,10 +1897,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1527
1897
  this.messages = autoTransformMessages(persisted);
1528
1898
  }
1529
1899
  }
1530
- if (!updated) {
1900
+ if (!wasFound) {
1531
1901
  console.warn(`[AIChatAgent] ${callerName}: Tool part with toolCallId ${toolCallId} not in expected state (expected: ${matchStates.join("|")})`);
1532
1902
  return false;
1533
1903
  }
1904
+ if (!hasRealChange) return true;
1534
1905
  if (isStreamingMessage) this._broadcastChatMessage({
1535
1906
  type: "cf_agent_message_updated",
1536
1907
  message
@@ -1545,11 +1916,34 @@ var AIChatAgent = class AIChatAgent extends Agent {
1545
1916
  return true;
1546
1917
  }
1547
1918
  /**
1919
+ * Returns true if `applied` is the same reference as `original`, or if
1920
+ * the two have identical state-relevant fields. Used by
1921
+ * `_findAndUpdateToolPart` to detect idempotent re-applies and skip
1922
+ * SQLite writes plus `MESSAGE_UPDATED` broadcasts.
1923
+ */
1924
+ static _isToolPartUnchanged(original, applied) {
1925
+ if (applied === original) return true;
1926
+ if (applied.state !== original.state) return false;
1927
+ if (applied.state === "output-available" || applied.state === "output-error") return JSON.stringify(applied.output) === JSON.stringify(original.output) && applied.errorText === original.errorText && applied.preliminary === original.preliminary;
1928
+ if (applied.state === "output-denied") return true;
1929
+ if (applied.state === "approval-responded" || applied.state === "approval-requested") return JSON.stringify(applied.approval) === JSON.stringify(original.approval);
1930
+ return false;
1931
+ }
1932
+ /**
1548
1933
  * Applies a tool result to an existing assistant message.
1549
1934
  * This is used when the client sends CF_AGENT_TOOL_RESULT for client-side tools.
1550
1935
  * The server is the source of truth, so we update the message here and broadcast
1551
1936
  * the update to all clients.
1552
1937
  *
1938
+ * `output-available` and `output-error` are accepted as valid starting
1939
+ * states for *idempotent* re-application — duplicate WS frames, second
1940
+ * tabs re-running the same tool, and provider-replay round-trips all
1941
+ * become silent no-ops rather than a warn + skipped update. The first
1942
+ * applied terminal result wins; subsequent results carrying *different*
1943
+ * data are also dropped (preserving the existing "first write wins"
1944
+ * contract — see `client-tool-duplicate-message.test.ts`). See issue
1945
+ * #1404.
1946
+ *
1553
1947
  * @param toolCallId - The tool call ID this result is for
1554
1948
  * @param _toolName - The name of the tool (unused, kept for API compat)
1555
1949
  * @param output - The output from the tool execution
@@ -1561,18 +1955,24 @@ var AIChatAgent = class AIChatAgent extends Agent {
1561
1955
  return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", [
1562
1956
  "input-available",
1563
1957
  "approval-requested",
1564
- "approval-responded"
1565
- ], (part) => ({
1566
- ...part,
1567
- ...overrideState === "output-error" ? {
1958
+ "approval-responded",
1959
+ "output-available",
1960
+ "output-error",
1961
+ "output-denied"
1962
+ ], (part) => {
1963
+ if (part.state === "output-available" || part.state === "output-error" || part.state === "output-denied") return part;
1964
+ if (overrideState === "output-error") return {
1965
+ ...part,
1568
1966
  state: "output-error",
1569
1967
  errorText: errorText ?? "Tool execution denied by user"
1570
- } : {
1968
+ };
1969
+ return {
1970
+ ...part,
1571
1971
  state: "output-available",
1572
1972
  output,
1573
1973
  preliminary: false
1574
- }
1575
- }));
1974
+ };
1975
+ });
1576
1976
  }
1577
1977
  async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1578
1978
  streamCompleted.value = false;
@@ -1626,6 +2026,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1626
2026
  if (continuationReasoningResumed) continue;
1627
2027
  }
1628
2028
  }
2029
+ if (isReplayChunk(message.parts, data)) continue;
1629
2030
  const handled = applyChunkToParts(message.parts, data);
1630
2031
  if (data.type === "tool-approval-request" && this._streamingMessage) {
1631
2032
  const snapshot = {
@@ -1646,23 +2047,35 @@ var AIChatAgent = class AIChatAgent extends Agent {
1646
2047
  "input-available",
1647
2048
  "input-streaming",
1648
2049
  "approval-responded",
1649
- "approval-requested"
1650
- ], (part) => ({
1651
- ...part,
1652
- state: "output-available",
1653
- output: data.output,
1654
- ...data.preliminary !== void 0 && { preliminary: data.preliminary }
1655
- }));
2050
+ "approval-requested",
2051
+ "output-available",
2052
+ "output-error",
2053
+ "output-denied"
2054
+ ], (part) => {
2055
+ if (part.state === "output-available" || part.state === "output-error" || part.state === "output-denied") return part;
2056
+ return {
2057
+ ...part,
2058
+ state: "output-available",
2059
+ output: data.output,
2060
+ ...data.preliminary !== void 0 && { preliminary: data.preliminary }
2061
+ };
2062
+ });
1656
2063
  else this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
1657
2064
  "input-available",
1658
2065
  "input-streaming",
1659
2066
  "approval-responded",
1660
- "approval-requested"
1661
- ], (part) => ({
1662
- ...part,
1663
- state: "output-error",
1664
- errorText: data.errorText
1665
- }));
2067
+ "approval-requested",
2068
+ "output-available",
2069
+ "output-error",
2070
+ "output-denied"
2071
+ ], (part) => {
2072
+ if (part.state === "output-available" || part.state === "output-error" || part.state === "output-denied") return part;
2073
+ return {
2074
+ ...part,
2075
+ state: "output-error",
2076
+ errorText: data.errorText
2077
+ };
2078
+ });
1666
2079
  }
1667
2080
  if (!handled) switch (data.type) {
1668
2081
  case "start":