@cloudflare/ai-chat 0.5.4 → 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/README.md +59 -3
- package/dist/index.d.ts +81 -1
- package/dist/index.js +357 -0
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
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
|
-
|
|
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
|
|
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 {
|
|
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();
|
|
@@ -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
|