@cloudflare/think 0.7.3 → 0.8.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 +420 -43
- package/dist/chat-sdk-Bb93yaZh.js +669 -0
- package/dist/chat-sdk-Bb93yaZh.js.map +1 -0
- package/dist/{classPrivateFieldGet2-BP1jgEfY.js → classPrivateFieldGet2-D_obpP6O.js} +5 -5
- package/dist/extensions/index.d.ts +2 -2
- package/dist/extensions/index.js +2 -2
- package/dist/{hook-proxy-5248W-ea.js → hook-proxy-CkF0EhRO.js} +1 -1
- package/dist/{hook-proxy-5248W-ea.js.map → hook-proxy-CkF0EhRO.js.map} +1 -1
- package/dist/{index-BsB4GUsL.d.ts → index-B-zgBVj2.d.ts} +2 -2
- package/dist/index-DpPdyY46.d.ts +2309 -0
- package/dist/{manager-px912SoZ.js → manager-DnCkoyVo.js} +3 -3
- package/dist/{manager-px912SoZ.js.map → manager-DnCkoyVo.js.map} +1 -1
- package/dist/{manager-DCbSiSWT.d.ts → manager-dOcdCX4u.d.ts} +1 -1
- package/dist/messengers/index.d.ts +110 -0
- package/dist/messengers/index.js +2 -0
- package/dist/messengers/telegram.d.ts +62 -0
- package/dist/messengers/telegram.js +84 -0
- package/dist/messengers/telegram.js.map +1 -0
- package/dist/think.d.ts +73 -1160
- package/dist/think.js +2391 -204
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +35 -334
- package/dist/tools/workspace.js +283 -3
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +78 -0
- package/dist/workflows.js +119 -0
- package/dist/workflows.js.map +1 -0
- package/dist/workspace-BZXdZcuw.d.ts +342 -0
- package/package.json +25 -8
|
@@ -0,0 +1,2309 @@
|
|
|
1
|
+
import {
|
|
2
|
+
i as ExtensionManifest,
|
|
3
|
+
t as ExtensionManager
|
|
4
|
+
} from "./manager-dOcdCX4u.js";
|
|
5
|
+
import {
|
|
6
|
+
D as createWorkspaceTools,
|
|
7
|
+
h as WorkspaceLike
|
|
8
|
+
} from "./workspace-BZXdZcuw.js";
|
|
9
|
+
import {
|
|
10
|
+
LanguageModel,
|
|
11
|
+
ModelMessage,
|
|
12
|
+
PrepareStepFunction,
|
|
13
|
+
PrepareStepFunction as PrepareStepFunction$1,
|
|
14
|
+
PrepareStepResult,
|
|
15
|
+
PrepareStepResult as PrepareStepResult$1,
|
|
16
|
+
StepResult,
|
|
17
|
+
StopCondition,
|
|
18
|
+
StopCondition as StopCondition$1,
|
|
19
|
+
StreamTextOnChunkCallback,
|
|
20
|
+
StreamTextOnStepFinishCallback,
|
|
21
|
+
TextStreamPart,
|
|
22
|
+
ToolSet,
|
|
23
|
+
TypedToolCall,
|
|
24
|
+
TypedToolCall as TypedToolCall$1,
|
|
25
|
+
TypedToolResult,
|
|
26
|
+
UIMessage,
|
|
27
|
+
streamText
|
|
28
|
+
} from "ai";
|
|
29
|
+
import * as skills from "agents/skills";
|
|
30
|
+
import {
|
|
31
|
+
SkillRunContext,
|
|
32
|
+
SkillScriptRunner,
|
|
33
|
+
SkillSource,
|
|
34
|
+
SkillSource as SkillSource$1
|
|
35
|
+
} from "agents/skills";
|
|
36
|
+
import {
|
|
37
|
+
Agent,
|
|
38
|
+
FiberContext,
|
|
39
|
+
FiberContext as FiberContext$1,
|
|
40
|
+
FiberRecoveryContext,
|
|
41
|
+
FiberRecoveryContext as FiberRecoveryContext$1,
|
|
42
|
+
FiberRecoveryResult,
|
|
43
|
+
RetryOptions,
|
|
44
|
+
StartFiberOptions,
|
|
45
|
+
SubAgentClass,
|
|
46
|
+
SubAgentStub
|
|
47
|
+
} from "agents";
|
|
48
|
+
import {
|
|
49
|
+
ChatRecoveryConfig,
|
|
50
|
+
ChatRecoveryConfig as ChatRecoveryConfig$1,
|
|
51
|
+
ChatRecoveryContext,
|
|
52
|
+
ChatRecoveryContext as ChatRecoveryContext$1,
|
|
53
|
+
ChatRecoveryExhaustedContext,
|
|
54
|
+
ChatRecoveryOptions,
|
|
55
|
+
ChatRecoveryOptions as ChatRecoveryOptions$1,
|
|
56
|
+
ChatResponseResult,
|
|
57
|
+
ChatResponseResult as ChatResponseResult$1,
|
|
58
|
+
ClientToolSchema,
|
|
59
|
+
MessageConcurrency,
|
|
60
|
+
MessageConcurrency as MessageConcurrency$1,
|
|
61
|
+
ResolvedChatRecoveryConfig,
|
|
62
|
+
ResumableStream,
|
|
63
|
+
SaveMessagesOptions,
|
|
64
|
+
SaveMessagesOptions as SaveMessagesOptions$1,
|
|
65
|
+
SaveMessagesResult,
|
|
66
|
+
SaveMessagesResult as SaveMessagesResult$1
|
|
67
|
+
} from "agents/chat";
|
|
68
|
+
import {
|
|
69
|
+
Session,
|
|
70
|
+
Session as Session$1
|
|
71
|
+
} from "agents/experimental/memory/session";
|
|
72
|
+
import { Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
73
|
+
import {
|
|
74
|
+
ActionEvent,
|
|
75
|
+
Adapter,
|
|
76
|
+
Attachment,
|
|
77
|
+
Author,
|
|
78
|
+
Message,
|
|
79
|
+
Thread
|
|
80
|
+
} from "chat";
|
|
81
|
+
import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
|
|
82
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
83
|
+
|
|
84
|
+
//#region src/think.d.ts
|
|
85
|
+
type ChatRecoveryRetryData = {
|
|
86
|
+
targetUserId?: string;
|
|
87
|
+
originalRequestId?: string;
|
|
88
|
+
incidentId?: string;
|
|
89
|
+
lastBody?: Record<string, unknown> | null;
|
|
90
|
+
lastClientTools?: ClientToolSchema[] | null;
|
|
91
|
+
recoveredRequestId?: string;
|
|
92
|
+
};
|
|
93
|
+
type ChatRecoveryContinueData = {
|
|
94
|
+
targetAssistantId?: string;
|
|
95
|
+
originalRequestId?: string;
|
|
96
|
+
incidentId?: string;
|
|
97
|
+
lastBody?: Record<string, unknown> | null;
|
|
98
|
+
lastClientTools?: ClientToolSchema[] | null;
|
|
99
|
+
recoveredRequestId?: string;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Callback interface for streaming chat events from a Think sub-agent.
|
|
103
|
+
*
|
|
104
|
+
* Designed to work across the sub-agent RPC boundary — implement as
|
|
105
|
+
* an RpcTarget in the parent agent and pass to `chat()`.
|
|
106
|
+
*/
|
|
107
|
+
interface ChatStartEvent {
|
|
108
|
+
requestId: string;
|
|
109
|
+
}
|
|
110
|
+
interface StreamCallback {
|
|
111
|
+
onStart(event: ChatStartEvent): void | Promise<void>;
|
|
112
|
+
onEvent(json: string): void | Promise<void>;
|
|
113
|
+
onDone(): void | Promise<void>;
|
|
114
|
+
onError(error: string): void | Promise<void>;
|
|
115
|
+
/**
|
|
116
|
+
* The current attempt was interrupted (a stream-stall watchdog abort routed
|
|
117
|
+
* into bounded recovery, #1626) and its final outcome will NOT arrive through
|
|
118
|
+
* this callback. One of two things is true:
|
|
119
|
+
* - a scheduled continuation — running in a LATER isolate invocation, without
|
|
120
|
+
* this callback — will produce the answer (delivered to other channels,
|
|
121
|
+
* e.g. WebSocket connections), OR
|
|
122
|
+
* - the recovery budget was exhausted, so the turn was already terminalized
|
|
123
|
+
* out-of-band (the configured `terminalMessage` + `onExhausted`) and is
|
|
124
|
+
* terminally over — there is NO continuation to come.
|
|
125
|
+
*
|
|
126
|
+
* This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
|
|
127
|
+
* raw stall is not surfaced as a terminal error here); without it the contract
|
|
128
|
+
* `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
|
|
129
|
+
* consumer that treats the clean resolve as success finalizes a truncated
|
|
130
|
+
* partial.
|
|
131
|
+
*
|
|
132
|
+
* Consumers should AVOID finalizing the partial on this signal — surface a
|
|
133
|
+
* "recovering…" / "interrupted, please retry" state, or re-attach via a
|
|
134
|
+
* durable channel — but must ALSO NOT block indefinitely waiting for a
|
|
135
|
+
* continuation: per the exhausted case above, one may never come. Optional →
|
|
136
|
+
* defaults to a no-op, so this is fully backward-compatible.
|
|
137
|
+
*
|
|
138
|
+
* Note: a deploy/eviction interruption kills the isolate (and this callback)
|
|
139
|
+
* before this can fire — the caller observes a transport break instead. This
|
|
140
|
+
* fires only for an in-isolate interruption (the stall→recovery path).
|
|
141
|
+
*/
|
|
142
|
+
onInterrupted?(): void | Promise<void>;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Minimal interface for the result of the inference loop.
|
|
146
|
+
* The AI SDK's `streamText()` result satisfies this interface.
|
|
147
|
+
*/
|
|
148
|
+
interface StreamableResult {
|
|
149
|
+
toUIMessageStream(options?: {
|
|
150
|
+
sendReasoning?: boolean;
|
|
151
|
+
}): AsyncIterable<unknown>;
|
|
152
|
+
output?: PromiseLike<unknown>;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Options for a chat turn (sub-agent RPC entry point).
|
|
156
|
+
*/
|
|
157
|
+
interface ChatOptions {
|
|
158
|
+
signal?: AbortSignal;
|
|
159
|
+
}
|
|
160
|
+
type AgentToolChildRunStatus =
|
|
161
|
+
| "starting"
|
|
162
|
+
| "running"
|
|
163
|
+
| "completed"
|
|
164
|
+
| "error"
|
|
165
|
+
| "aborted";
|
|
166
|
+
type AgentToolRunInspection<Output = unknown> = {
|
|
167
|
+
runId: string;
|
|
168
|
+
status: AgentToolChildRunStatus;
|
|
169
|
+
requestId?: string;
|
|
170
|
+
streamId?: string;
|
|
171
|
+
output?: Output;
|
|
172
|
+
summary?: string;
|
|
173
|
+
error?: string;
|
|
174
|
+
startedAt: number;
|
|
175
|
+
completedAt?: number;
|
|
176
|
+
};
|
|
177
|
+
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
|
|
178
|
+
type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
|
|
179
|
+
type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
|
|
180
|
+
type ThinkTime = `${Hour}:${Minute}`;
|
|
181
|
+
type ThinkIntervalSchedule =
|
|
182
|
+
| `every ${number} minute${"" | "s"}`
|
|
183
|
+
| `every ${number} hour${"" | "s"}`;
|
|
184
|
+
type ThinkWallClockSchedule =
|
|
185
|
+
| `every day at ${ThinkTime}`
|
|
186
|
+
| `every weekday at ${ThinkTime}`
|
|
187
|
+
| `every week on ${string} at ${ThinkTime}`;
|
|
188
|
+
type ThinkScheduledTaskSchedule =
|
|
189
|
+
| ThinkIntervalSchedule
|
|
190
|
+
| ThinkWallClockSchedule
|
|
191
|
+
| `${ThinkWallClockSchedule} in ${string}`;
|
|
192
|
+
type ThinkScheduledTaskContext = {
|
|
193
|
+
taskId: string;
|
|
194
|
+
scheduledFor: number;
|
|
195
|
+
scheduledForDate: Date;
|
|
196
|
+
occurrenceKey: string;
|
|
197
|
+
idempotencyKey: string;
|
|
198
|
+
schedule: string;
|
|
199
|
+
scheduleKind: "interval" | "wall-clock";
|
|
200
|
+
timezone?: string;
|
|
201
|
+
metadata?: Record<string, unknown>;
|
|
202
|
+
};
|
|
203
|
+
type ThinkScheduledTaskPromptAction = {
|
|
204
|
+
prompt: string | (() => string | Promise<string>);
|
|
205
|
+
handler?: never;
|
|
206
|
+
};
|
|
207
|
+
type ThinkScheduledTaskHandlerAction = {
|
|
208
|
+
handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
|
|
209
|
+
prompt?: never;
|
|
210
|
+
};
|
|
211
|
+
type ThinkScheduledTaskBase = (
|
|
212
|
+
| ThinkScheduledTaskPromptAction
|
|
213
|
+
| ThinkScheduledTaskHandlerAction
|
|
214
|
+
) & {
|
|
215
|
+
retry?: RetryOptions;
|
|
216
|
+
metadata?: Record<string, unknown>;
|
|
217
|
+
};
|
|
218
|
+
type ThinkScheduledTask =
|
|
219
|
+
| (ThinkScheduledTaskBase & {
|
|
220
|
+
schedule: ThinkIntervalSchedule;
|
|
221
|
+
timezone?: never;
|
|
222
|
+
})
|
|
223
|
+
| (ThinkScheduledTaskBase & {
|
|
224
|
+
schedule: ThinkWallClockSchedule;
|
|
225
|
+
timezone?: string;
|
|
226
|
+
})
|
|
227
|
+
| (ThinkScheduledTaskBase & {
|
|
228
|
+
schedule: `${ThinkWallClockSchedule} in ${string}`;
|
|
229
|
+
timezone?: string;
|
|
230
|
+
});
|
|
231
|
+
type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
|
|
232
|
+
declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
|
|
233
|
+
tasks: T
|
|
234
|
+
): T;
|
|
235
|
+
type DeclaredScheduledTaskPayload = {
|
|
236
|
+
taskId: string;
|
|
237
|
+
scheduleHash: string;
|
|
238
|
+
scheduledFor: number;
|
|
239
|
+
};
|
|
240
|
+
type AgentToolStoredChunk = {
|
|
241
|
+
sequence: number;
|
|
242
|
+
body: string;
|
|
243
|
+
};
|
|
244
|
+
type ThinkSubmissionStatus =
|
|
245
|
+
| "pending"
|
|
246
|
+
| "running"
|
|
247
|
+
| "completed"
|
|
248
|
+
| "aborted"
|
|
249
|
+
| "skipped"
|
|
250
|
+
| "error";
|
|
251
|
+
type SubmitMessagesOptions = {
|
|
252
|
+
submissionId?: string;
|
|
253
|
+
idempotencyKey?: string;
|
|
254
|
+
metadata?: Record<string, unknown>;
|
|
255
|
+
};
|
|
256
|
+
type ThinkWorkflowPromptContext = {
|
|
257
|
+
workflow: {
|
|
258
|
+
name: string;
|
|
259
|
+
id: string;
|
|
260
|
+
stepName: string;
|
|
261
|
+
eventType: string;
|
|
262
|
+
};
|
|
263
|
+
output?: {
|
|
264
|
+
schema: unknown;
|
|
265
|
+
};
|
|
266
|
+
fingerprint?: string;
|
|
267
|
+
};
|
|
268
|
+
type ThinkSubmissionInspection = {
|
|
269
|
+
submissionId: string;
|
|
270
|
+
idempotencyKey?: string;
|
|
271
|
+
requestId?: string;
|
|
272
|
+
status: ThinkSubmissionStatus;
|
|
273
|
+
error?: string;
|
|
274
|
+
metadata?: Record<string, unknown>;
|
|
275
|
+
createdAt: number;
|
|
276
|
+
startedAt?: number;
|
|
277
|
+
completedAt?: number;
|
|
278
|
+
};
|
|
279
|
+
type SubmitMessagesResult = ThinkSubmissionInspection & {
|
|
280
|
+
accepted: boolean;
|
|
281
|
+
};
|
|
282
|
+
type ListSubmissionsOptions = {
|
|
283
|
+
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
284
|
+
limit?: number;
|
|
285
|
+
};
|
|
286
|
+
type DeleteSubmissionsOptions = {
|
|
287
|
+
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
288
|
+
completedBefore?: Date;
|
|
289
|
+
limit?: number;
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* A chat turn request. Built automatically by each entry path
|
|
293
|
+
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
294
|
+
* to Think's inference loop.
|
|
295
|
+
*/
|
|
296
|
+
interface TurnInput {
|
|
297
|
+
signal?: AbortSignal;
|
|
298
|
+
/** Client-provided tool schemas for dynamic tool registration. */
|
|
299
|
+
clientTools?: ClientToolSchema[];
|
|
300
|
+
/** Custom body fields from the client request. */
|
|
301
|
+
body?: Record<string, unknown>;
|
|
302
|
+
/** Internal workflow prompt configuration, never sourced from client body. */
|
|
303
|
+
workflowPrompt?: ThinkWorkflowPromptContext;
|
|
304
|
+
/** Whether this is a continuation turn (auto-continue after tool result, recovery). */
|
|
305
|
+
continuation: boolean;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Context passed to the `beforeTurn` hook.
|
|
309
|
+
* Contains everything Think assembled — the hook can inspect and override.
|
|
310
|
+
*/
|
|
311
|
+
interface TurnContext {
|
|
312
|
+
/** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
|
|
313
|
+
system: string;
|
|
314
|
+
/** Assembled model messages (truncated, pruned). */
|
|
315
|
+
messages: ModelMessage[];
|
|
316
|
+
/** Merged tool set (workspace + getTools + session + MCP + client + caller). */
|
|
317
|
+
tools: ToolSet;
|
|
318
|
+
/** The language model from getModel(). */
|
|
319
|
+
model: LanguageModel;
|
|
320
|
+
/** Whether this is a continuation turn. */
|
|
321
|
+
continuation: boolean;
|
|
322
|
+
/** Custom body fields from the client request. */
|
|
323
|
+
body?: Record<string, unknown>;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Configuration returned by the `beforeTurn` hook to override defaults.
|
|
327
|
+
* All fields are optional — return only what you want to change.
|
|
328
|
+
*/
|
|
329
|
+
interface TurnConfig {
|
|
330
|
+
/** Override the model for this turn (e.g. cheap model for continuations). */
|
|
331
|
+
model?: LanguageModel;
|
|
332
|
+
/** Override the assembled system prompt. */
|
|
333
|
+
system?: string;
|
|
334
|
+
/** Override the assembled messages. */
|
|
335
|
+
messages?: ModelMessage[];
|
|
336
|
+
/** Extra tools to merge (additive — spread on top of existing tools). */
|
|
337
|
+
tools?: ToolSet;
|
|
338
|
+
/** Limit which tools the model can call (AI SDK activeTools). */
|
|
339
|
+
activeTools?: string[];
|
|
340
|
+
/** Force a specific tool call (AI SDK toolChoice). */
|
|
341
|
+
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
342
|
+
/** Override maxSteps for this turn. */
|
|
343
|
+
maxSteps?: number;
|
|
344
|
+
/**
|
|
345
|
+
* Additional AI SDK stop conditions for ending the turn early.
|
|
346
|
+
* Think always keeps its `maxSteps` stop condition as a safety bound.
|
|
347
|
+
*/
|
|
348
|
+
stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
|
|
349
|
+
/**
|
|
350
|
+
* Controls whether reasoning chunks are included in the UI message stream
|
|
351
|
+
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
352
|
+
*/
|
|
353
|
+
sendReasoning?: boolean;
|
|
354
|
+
/**
|
|
355
|
+
* Override the stream-stall inactivity watchdog timeout for THIS turn only
|
|
356
|
+
* (ms; `0` disables it for this turn). Defaults to the instance-level
|
|
357
|
+
* `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
|
|
358
|
+
* UI-message-stream chunks — which includes server-side tool execution — a
|
|
359
|
+
* turn known to invoke a slow tool can raise (or disable) the timeout for
|
|
360
|
+
* just that turn instead of permanently widening the global window. Auto-
|
|
361
|
+
* resets after the turn.
|
|
362
|
+
*/
|
|
363
|
+
chatStreamStallTimeoutMs?: number;
|
|
364
|
+
/** Maximum number of tokens to generate for this turn. */
|
|
365
|
+
maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
|
|
366
|
+
/** Temperature setting for this turn. */
|
|
367
|
+
temperature?: Parameters<typeof streamText>[0]["temperature"];
|
|
368
|
+
/** Nucleus sampling setting for this turn. */
|
|
369
|
+
topP?: Parameters<typeof streamText>[0]["topP"];
|
|
370
|
+
/** Top-K sampling setting for this turn. */
|
|
371
|
+
topK?: Parameters<typeof streamText>[0]["topK"];
|
|
372
|
+
/** Presence penalty setting for this turn. */
|
|
373
|
+
presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
|
|
374
|
+
/** Frequency penalty setting for this turn. */
|
|
375
|
+
frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
|
|
376
|
+
/** Stop sequences for this turn. */
|
|
377
|
+
stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
|
|
378
|
+
/** Seed for deterministic sampling when supported by the model. */
|
|
379
|
+
seed?: Parameters<typeof streamText>[0]["seed"];
|
|
380
|
+
/** Maximum number of retries for this turn. Set to 0 to disable retries. */
|
|
381
|
+
maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
|
|
382
|
+
/** Timeout configuration for this turn. */
|
|
383
|
+
timeout?: Parameters<typeof streamText>[0]["timeout"];
|
|
384
|
+
/** Additional HTTP headers for provider requests on this turn. */
|
|
385
|
+
headers?: Parameters<typeof streamText>[0]["headers"];
|
|
386
|
+
/** Provider-specific options (AI SDK providerOptions). */
|
|
387
|
+
providerOptions?: Record<string, unknown>;
|
|
388
|
+
/** Optional AI SDK telemetry configuration for this turn. */
|
|
389
|
+
experimental_telemetry?: Parameters<
|
|
390
|
+
typeof streamText
|
|
391
|
+
>[0]["experimental_telemetry"];
|
|
392
|
+
/**
|
|
393
|
+
* Optional structured-output specification (AI SDK `output`).
|
|
394
|
+
* Forwarded to `streamText` so the model's final response is parsed
|
|
395
|
+
* against the supplied schema. Use the AI SDK's `Output.object({ schema })`
|
|
396
|
+
* / `Output.text()` helpers. Combine with `activeTools: []` on the
|
|
397
|
+
* terminal turn if your provider strips tools when structured output
|
|
398
|
+
* is active (e.g. workers-ai-provider).
|
|
399
|
+
*/
|
|
400
|
+
output?: Parameters<typeof streamText>[0]["output"];
|
|
401
|
+
}
|
|
402
|
+
interface ChatErrorContext {
|
|
403
|
+
requestId?: string;
|
|
404
|
+
stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
|
|
405
|
+
messagesPersisted?: boolean;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Context passed to the `beforeStep` hook before each AI SDK step in
|
|
409
|
+
* the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
|
|
410
|
+
* parameter — exposes the previous `steps`, the zero-based `stepNumber`,
|
|
411
|
+
* the currently selected `model`, the `messages` about to be sent, and
|
|
412
|
+
* `experimental_context`.
|
|
413
|
+
*
|
|
414
|
+
* Pass an explicit `TOOLS` generic for typed previous tool calls / results.
|
|
415
|
+
*
|
|
416
|
+
* Limitations (AI SDK boundary, not Think):
|
|
417
|
+
* - No `abortSignal` is exposed in the context. If you do remote work
|
|
418
|
+
* inside `beforeStep`, it cannot be cancelled by turn-level abort.
|
|
419
|
+
* - `experimental_context` is typed `unknown`; users must narrow it.
|
|
420
|
+
* - `output` cannot be overridden per-step — set it at the turn level
|
|
421
|
+
* via `TurnConfig.output` (returned from `beforeTurn`).
|
|
422
|
+
*/
|
|
423
|
+
type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
424
|
+
PrepareStepFunction<TOOLS>
|
|
425
|
+
>[0];
|
|
426
|
+
/**
|
|
427
|
+
* Configuration returned by `beforeStep` to override defaults for the
|
|
428
|
+
* current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
|
|
429
|
+
* return only the fields you want to override (`model`, `toolChoice`,
|
|
430
|
+
* `activeTools`, `system`, `messages`, `experimental_context`,
|
|
431
|
+
* `providerOptions`).
|
|
432
|
+
*/
|
|
433
|
+
type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
|
|
434
|
+
/**
|
|
435
|
+
* Context passed to the `beforeToolCall` hook **before** the tool's
|
|
436
|
+
* `execute` function runs.
|
|
437
|
+
*
|
|
438
|
+
* Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
|
|
439
|
+
* `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
|
|
440
|
+
* fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
|
|
441
|
+
* dynamic/invalid/error discriminators) are spread at the top level for
|
|
442
|
+
* convenience, with the per-call event extras attached:
|
|
443
|
+
*
|
|
444
|
+
* - `stepNumber` — index of the current step
|
|
445
|
+
* - `messages` — conversation messages visible at tool execution time
|
|
446
|
+
* - `abortSignal` — signal that aborts if the turn is cancelled
|
|
447
|
+
*
|
|
448
|
+
* Pass an explicit `TOOLS` generic for full input typing:
|
|
449
|
+
*
|
|
450
|
+
* ```ts
|
|
451
|
+
* import type { ToolCallContext } from "@cloudflare/think";
|
|
452
|
+
* import type { tools } from "./my-tools";
|
|
453
|
+
*
|
|
454
|
+
* beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
455
|
+
* if (ctx.toolName === "search") {
|
|
456
|
+
* ctx.input.query; // typed
|
|
457
|
+
* }
|
|
458
|
+
* }
|
|
459
|
+
* ```
|
|
460
|
+
*/
|
|
461
|
+
type ToolCallContext<TOOLS extends ToolSet = ToolSet> = TypedToolCall<TOOLS> & {
|
|
462
|
+
/** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
|
|
463
|
+
| number
|
|
464
|
+
| undefined /** The conversation messages available at tool execution time. */;
|
|
465
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
|
|
466
|
+
readonly abortSignal: AbortSignal | undefined;
|
|
467
|
+
};
|
|
468
|
+
/**
|
|
469
|
+
* Decision returned by `beforeToolCall` to control tool execution.
|
|
470
|
+
* Return void/undefined to allow execution with original input.
|
|
471
|
+
*
|
|
472
|
+
* Discriminated union — each action has a clear, non-overlapping meaning:
|
|
473
|
+
* - `allow` — execute the tool (optionally with modified input)
|
|
474
|
+
* - `block` — don't execute; return `reason` as the tool result so the model can adjust
|
|
475
|
+
* - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
|
|
476
|
+
*/
|
|
477
|
+
type ToolCallDecision =
|
|
478
|
+
| {
|
|
479
|
+
action: "allow" /** Modified input — tool executes with this instead of the original. */;
|
|
480
|
+
input?: Record<string, unknown>;
|
|
481
|
+
}
|
|
482
|
+
| {
|
|
483
|
+
action: "block" /** Returned as the tool result so the model can adjust. */;
|
|
484
|
+
reason?: string;
|
|
485
|
+
}
|
|
486
|
+
| {
|
|
487
|
+
action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
|
|
488
|
+
output: unknown /** Optional input attribution for the afterToolCall log. */;
|
|
489
|
+
input?: Record<string, unknown>;
|
|
490
|
+
};
|
|
491
|
+
/**
|
|
492
|
+
* Context passed to the `afterToolCall` hook after a tool executes.
|
|
493
|
+
*
|
|
494
|
+
* Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
|
|
495
|
+
* `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
|
|
496
|
+
* fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
|
|
497
|
+
* level, plus the per-call event extras:
|
|
498
|
+
*
|
|
499
|
+
* - `stepNumber` — index of the current step
|
|
500
|
+
* - `messages` — conversation messages visible at tool execution time
|
|
501
|
+
* - `durationMs` — wall-clock execution time in milliseconds
|
|
502
|
+
* - `success`/`output`/`error` — discriminated outcome:
|
|
503
|
+
* - on success: `success: true`, `output: unknown`
|
|
504
|
+
* - on failure: `success: false`, `error: unknown`
|
|
505
|
+
*
|
|
506
|
+
* Pass an explicit `TOOLS` generic for full input typing:
|
|
507
|
+
*
|
|
508
|
+
* ```ts
|
|
509
|
+
* import type { ToolCallResultContext } from "@cloudflare/think";
|
|
510
|
+
* import type { tools } from "./my-tools";
|
|
511
|
+
*
|
|
512
|
+
* afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
|
|
513
|
+
* if (ctx.success) {
|
|
514
|
+
* console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
|
|
515
|
+
* } else {
|
|
516
|
+
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
517
|
+
* }
|
|
518
|
+
* }
|
|
519
|
+
* ```
|
|
520
|
+
*/
|
|
521
|
+
type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
|
|
522
|
+
TypedToolCall<TOOLS> & {
|
|
523
|
+
readonly stepNumber: number | undefined;
|
|
524
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
|
|
525
|
+
readonly durationMs: number;
|
|
526
|
+
} & (
|
|
527
|
+
| {
|
|
528
|
+
readonly success: true;
|
|
529
|
+
readonly output: unknown;
|
|
530
|
+
readonly error?: never;
|
|
531
|
+
}
|
|
532
|
+
| {
|
|
533
|
+
readonly success: false;
|
|
534
|
+
readonly output?: never;
|
|
535
|
+
readonly error: unknown;
|
|
536
|
+
}
|
|
537
|
+
);
|
|
538
|
+
/**
|
|
539
|
+
* Context passed to the `onStepFinish` hook after each step completes.
|
|
540
|
+
*
|
|
541
|
+
* This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
|
|
542
|
+
* the full step record including `text`, `reasoning`, `toolCalls`,
|
|
543
|
+
* `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
|
|
544
|
+
* `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
|
|
545
|
+
* `response`, and `providerMetadata` (where provider-specific cache
|
|
546
|
+
* accounting like `cacheCreationInputTokens` lives).
|
|
547
|
+
*
|
|
548
|
+
* Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
|
|
549
|
+
*/
|
|
550
|
+
type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
551
|
+
StreamTextOnStepFinishCallback<TOOLS>
|
|
552
|
+
>[0];
|
|
553
|
+
/**
|
|
554
|
+
* Context passed to the `onChunk` hook for each streaming chunk.
|
|
555
|
+
*
|
|
556
|
+
* This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
|
|
557
|
+
* where `chunk` is a discriminated union of `TextStreamPart` variants
|
|
558
|
+
* (text-delta, reasoning-delta, source, tool-call, tool-input-start,
|
|
559
|
+
* tool-input-delta, tool-result, raw).
|
|
560
|
+
*/
|
|
561
|
+
type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
562
|
+
StreamTextOnChunkCallback<TOOLS>
|
|
563
|
+
>[0];
|
|
564
|
+
/**
|
|
565
|
+
* @internal Re-export of the chunk variant union for consumers that need
|
|
566
|
+
* to narrow on `chunk.type` without importing `TextStreamPart` directly.
|
|
567
|
+
*/
|
|
568
|
+
type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
|
|
569
|
+
/**
|
|
570
|
+
* Configuration for a sandboxed extension, returned by getExtensions().
|
|
571
|
+
*/
|
|
572
|
+
interface ExtensionConfig {
|
|
573
|
+
/** Extension manifest (name, version, permissions, contributions). */
|
|
574
|
+
manifest: ExtensionManifest;
|
|
575
|
+
/** JavaScript source code defining the extension's tools. */
|
|
576
|
+
source: string;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* An opinionated chat agent base class.
|
|
580
|
+
*
|
|
581
|
+
* @experimental The API surface may change before stabilizing.
|
|
582
|
+
*/
|
|
583
|
+
declare class Think<
|
|
584
|
+
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
585
|
+
State = unknown,
|
|
586
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
587
|
+
> extends Agent<Env, State, Props> {
|
|
588
|
+
#private;
|
|
589
|
+
private _activeChatRecoveryRootRequestId;
|
|
590
|
+
private static readonly CONFIG_KEYS;
|
|
591
|
+
/**
|
|
592
|
+
* Wait for MCP server connections to be ready before the inference
|
|
593
|
+
* loop. MCP tools are auto-merged into the tool set.
|
|
594
|
+
*
|
|
595
|
+
* Set to `true` for a default 10s timeout, or `{ timeout: ms }`
|
|
596
|
+
* for a custom timeout. Defaults to `false` (no waiting).
|
|
597
|
+
*/
|
|
598
|
+
waitForMcpConnections:
|
|
599
|
+
| boolean
|
|
600
|
+
| {
|
|
601
|
+
timeout: number;
|
|
602
|
+
};
|
|
603
|
+
private _skillRegistry;
|
|
604
|
+
private _loggedSkillWarnings;
|
|
605
|
+
/**
|
|
606
|
+
* Controls how overlapping user submit requests behave while another
|
|
607
|
+
* chat turn is already active or queued.
|
|
608
|
+
*
|
|
609
|
+
* @default "queue"
|
|
610
|
+
*/
|
|
611
|
+
messageConcurrency: MessageConcurrency;
|
|
612
|
+
/**
|
|
613
|
+
* When true, chat turns are wrapped in `runFiber` for durable execution.
|
|
614
|
+
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
615
|
+
*/
|
|
616
|
+
chatRecovery: ChatRecoveryConfig;
|
|
617
|
+
static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
618
|
+
/**
|
|
619
|
+
* The conversation session — messages, context, compaction, search.
|
|
620
|
+
*
|
|
621
|
+
* Direct message writes are observed and mirrored into Think's live cache.
|
|
622
|
+
* Prefer the history helpers below when writing UI messages from subclasses;
|
|
623
|
+
* they sanitize content and enforce row-size limits before delegating here.
|
|
624
|
+
*/
|
|
625
|
+
session: Session;
|
|
626
|
+
/** Cached messages — kept in sync with session storage. */
|
|
627
|
+
private _cachedMessages;
|
|
628
|
+
private _activeMessengerContext?;
|
|
629
|
+
private _messengerRuntime?;
|
|
630
|
+
/**
|
|
631
|
+
* WorkerLoader binding for sandboxed extensions.
|
|
632
|
+
* Set this to enable `getExtensions()` and dynamic extension loading.
|
|
633
|
+
*/
|
|
634
|
+
extensionLoader?: WorkerLoader;
|
|
635
|
+
/**
|
|
636
|
+
* Extension manager — created automatically when `extensionLoader` is set.
|
|
637
|
+
* Use for dynamic `load()` / `unload()` at runtime.
|
|
638
|
+
*/
|
|
639
|
+
extensionManager?: ExtensionManager;
|
|
640
|
+
/**
|
|
641
|
+
* Workspace filesystem available in `getTools()` and lifecycle hooks.
|
|
642
|
+
* Defaults to a full `Workspace` backed by the DO's SQLite storage.
|
|
643
|
+
*
|
|
644
|
+
* Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
|
|
645
|
+
* replace it with anything that satisfies the interface — e.g. a proxy
|
|
646
|
+
* that forwards to a shared workspace owned by a parent DO. Override as
|
|
647
|
+
* a class field to skip the default init entirely:
|
|
648
|
+
*
|
|
649
|
+
* ```typescript
|
|
650
|
+
* // Default init with R2 spillover for large files.
|
|
651
|
+
* override workspace = new Workspace({
|
|
652
|
+
* sql: this.ctx.storage.sql,
|
|
653
|
+
* r2: this.env.R2,
|
|
654
|
+
* name: () => this.name
|
|
655
|
+
* });
|
|
656
|
+
*
|
|
657
|
+
* // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
|
|
658
|
+
* override workspace: WorkspaceLike = new SharedWorkspace(this);
|
|
659
|
+
* ```
|
|
660
|
+
*/
|
|
661
|
+
workspace: WorkspaceLike;
|
|
662
|
+
/**
|
|
663
|
+
* Include the default workspace Bash tool. Enabled by default so models can
|
|
664
|
+
* run shell-style multi-file workflows against the workspace. Set to `false`
|
|
665
|
+
* to omit it from the built-in workspace tools.
|
|
666
|
+
*/
|
|
667
|
+
workspaceBash:
|
|
668
|
+
| boolean
|
|
669
|
+
| NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
|
|
670
|
+
constructor(ctx: DurableObjectState, env: Env);
|
|
671
|
+
/**
|
|
672
|
+
* Conversation history as Think's live in-memory view.
|
|
673
|
+
*
|
|
674
|
+
* Storage remains the durable source of truth, but runtime logic should read
|
|
675
|
+
* through this cache so in-flight turns, tool updates, and recovery state all
|
|
676
|
+
* observe the same message list. Use `_syncMessages()` only at safe
|
|
677
|
+
* boundaries where a full storage reread cannot drop in-flight state.
|
|
678
|
+
*/
|
|
679
|
+
get messages(): UIMessage[];
|
|
680
|
+
/** Read the durable message path from session storage. */
|
|
681
|
+
private _readMessagesFromStorage;
|
|
682
|
+
/**
|
|
683
|
+
* Normalize a tool part's `input` into something the provider will accept.
|
|
684
|
+
*
|
|
685
|
+
* Malformed shapes 400 modern providers and persist forever once written:
|
|
686
|
+
* a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
|
|
687
|
+
* object), and any non-object `input` — `null`, `undefined`, `""`, an array,
|
|
688
|
+
* or a primitive — on a settled or interrupted tool call (Anthropic rejects
|
|
689
|
+
* a `tool_use` block whose `input` is not an object). We parse the former and
|
|
690
|
+
* default the latter to an empty object so the tool-call/tool-result pair
|
|
691
|
+
* stays valid. Delegates to the shared `normalizeToolInput` so the read-side
|
|
692
|
+
* repair and the write-side accumulator guard enforce the same invariant.
|
|
693
|
+
*/
|
|
694
|
+
private _normalizeToolInput;
|
|
695
|
+
/**
|
|
696
|
+
* Whether a tool part already has a settled result the provider accepts, so
|
|
697
|
+
* it must NOT be re-repaired into an errored result.
|
|
698
|
+
*
|
|
699
|
+
* Single source of truth for the terminal tool states, shared by the repair
|
|
700
|
+
* pass and the backstop detector so they cannot drift. Mirror the AI SDK's
|
|
701
|
+
* terminal states: `convertToModelMessages` emits a `tool-result` for
|
|
702
|
+
* `output-available`, `output-error`, AND `output-denied` (a user-denied
|
|
703
|
+
* approval — its denial reason becomes the tool-result). Omitting any of
|
|
704
|
+
* these makes repair re-flip the part every turn — clobbering a real
|
|
705
|
+
* `errorText`/denial with the generic "interrupted" message — and makes the
|
|
706
|
+
* backstop falsely drop a valid call.
|
|
707
|
+
*/
|
|
708
|
+
private _toolPartHasSettledResult;
|
|
709
|
+
/**
|
|
710
|
+
* Tool-call ids that still have no recorded result. After repair this should
|
|
711
|
+
* be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
|
|
712
|
+
* will drop those calls — i.e. repair missed a shape and should be extended.
|
|
713
|
+
*
|
|
714
|
+
* `approval-responded` is deliberately excluded: an approved server tool has
|
|
715
|
+
* no result *yet*, but it is not incomplete or abandoned — it is waiting for
|
|
716
|
+
* its continuation to run `execute()`. `convertToModelMessages` keeps that
|
|
717
|
+
* call (and the SDK executes it), so flagging it here would log a misleading
|
|
718
|
+
* "repair gap" warning and emit a spurious `chat:transcript:repaired` event
|
|
719
|
+
* on every approval continuation.
|
|
720
|
+
*/
|
|
721
|
+
private _incompleteToolCallIds;
|
|
722
|
+
/**
|
|
723
|
+
* Repair a single interrupted tool call — a tool part with no settled result,
|
|
724
|
+
* left behind when a stream was cut off mid-flight. Returns the replacement
|
|
725
|
+
* part that takes its place in the transcript. `input` has already been
|
|
726
|
+
* normalized to a valid object.
|
|
727
|
+
*
|
|
728
|
+
* The default flips it to an errored tool result so the record survives (no
|
|
729
|
+
* "disappearing" tool call) and `convertToModelMessages` still gets a
|
|
730
|
+
* tool-result for it (avoiding `AI_MissingToolResultsError`).
|
|
731
|
+
*
|
|
732
|
+
* Override to customize the repaired shape for client-resolved tools — e.g.
|
|
733
|
+
* convert an interrupted `ask_user` (a question with no server `execute`,
|
|
734
|
+
* normally answered by the user's next message) into a plain text part
|
|
735
|
+
* carrying the question prose, so the model sees it as ordinary conversation
|
|
736
|
+
* rather than a tool error and compaction keeps the question verbatim. This
|
|
737
|
+
* runs DURING transcript repair — before the repaired transcript is persisted
|
|
738
|
+
* and sent to the model — so the conversion shapes the current turn, not just
|
|
739
|
+
* the next one. A returned tool part MUST carry a settled result
|
|
740
|
+
* (`output-available` / `output-error` / `output-denied` or an
|
|
741
|
+
* `output`/`result` field); returning a non-tool part (e.g. text) is fine.
|
|
742
|
+
*/
|
|
743
|
+
protected repairInterruptedToolPart(
|
|
744
|
+
part: UIMessage["parts"][number]
|
|
745
|
+
): UIMessage["parts"][number];
|
|
746
|
+
private _repairToolTranscriptParts;
|
|
747
|
+
private _repairTranscriptForProvider;
|
|
748
|
+
/** Replace the live cache with a durable storage snapshot. */
|
|
749
|
+
private _replaceCachedMessages;
|
|
750
|
+
/** Refresh the live cache from durable storage at a safe boundary. */
|
|
751
|
+
private _syncMessages;
|
|
752
|
+
/** Patch or append one message in the live cache after a durable write. */
|
|
753
|
+
private _upsertCachedMessage;
|
|
754
|
+
/** Patch a message that is already present in the live cache. */
|
|
755
|
+
private _patchCachedMessage;
|
|
756
|
+
private _appendMessageToHistory;
|
|
757
|
+
private _updateMessageInHistory;
|
|
758
|
+
private _upsertMessageInHistory;
|
|
759
|
+
private _clearHistory;
|
|
760
|
+
/** Append a message while keeping Think's live message cache coherent. */
|
|
761
|
+
protected appendMessageToHistory(
|
|
762
|
+
message: UIMessage,
|
|
763
|
+
parentId?: string | null
|
|
764
|
+
): Promise<UIMessage>;
|
|
765
|
+
/** Update a message while keeping Think's live message cache coherent. */
|
|
766
|
+
protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
|
|
767
|
+
/** Refresh Think's live message cache from the durable session path. */
|
|
768
|
+
protected syncMessagesFromStorage(): Promise<UIMessage[]>;
|
|
769
|
+
private _aborts;
|
|
770
|
+
private _turnQueue;
|
|
771
|
+
protected _resumableStream: ResumableStream;
|
|
772
|
+
private _pendingResumeConnections;
|
|
773
|
+
private _lastClientTools;
|
|
774
|
+
private _lastBody;
|
|
775
|
+
private _continuation;
|
|
776
|
+
private _continuationTimer;
|
|
777
|
+
private _continuationBarrierActive;
|
|
778
|
+
private _insideResponseHook;
|
|
779
|
+
private _insideInferenceLoop;
|
|
780
|
+
private _pendingInteractionPromise;
|
|
781
|
+
private _interactionApplyTail;
|
|
782
|
+
private _streamingAssistant;
|
|
783
|
+
private _submitConcurrency;
|
|
784
|
+
private static MESSAGE_DEBOUNCE_MS;
|
|
785
|
+
private _agentToolForwarders;
|
|
786
|
+
private _agentToolClosers;
|
|
787
|
+
private _agentToolAbortControllers;
|
|
788
|
+
private _agentToolLastErrors;
|
|
789
|
+
private _agentToolPreTurnAssistantIds;
|
|
790
|
+
private _agentToolLiveSequences;
|
|
791
|
+
private _submissionTableEnsured;
|
|
792
|
+
private _workflowNotificationTableEnsured;
|
|
793
|
+
private _declaredScheduledTasksTableEnsured;
|
|
794
|
+
private _drainingSubmissions;
|
|
795
|
+
private _drainingWorkflowNotifications;
|
|
796
|
+
private _submissionAbortControllers;
|
|
797
|
+
private _programmaticStreamErrors;
|
|
798
|
+
protected static submissionRecoveryStaleMs: number;
|
|
799
|
+
broadcast(
|
|
800
|
+
msg: string | ArrayBuffer | ArrayBufferView,
|
|
801
|
+
without?: string[]
|
|
802
|
+
): void;
|
|
803
|
+
alarm(): Promise<void>;
|
|
804
|
+
/**
|
|
805
|
+
* Persist an arbitrary JSON-serializable configuration object for this
|
|
806
|
+
* agent instance. Stored in the Think-private `think_config` table —
|
|
807
|
+
* survives
|
|
808
|
+
* restarts and hibernation. Pass the config shape as a method generic
|
|
809
|
+
* for typed call sites:
|
|
810
|
+
*
|
|
811
|
+
* ```ts
|
|
812
|
+
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
813
|
+
* ```
|
|
814
|
+
*
|
|
815
|
+
* Prefer `state` / `setState` from `Agent` when you want the value
|
|
816
|
+
* broadcast to connected clients. Use `configure` for private
|
|
817
|
+
* per-instance config that should stay server-side.
|
|
818
|
+
*/
|
|
819
|
+
configure<T = Record<string, unknown>>(config: T): void;
|
|
820
|
+
/**
|
|
821
|
+
* Read the persisted configuration, or null if never configured.
|
|
822
|
+
* Pass the config shape as a method generic for a typed result:
|
|
823
|
+
*
|
|
824
|
+
* ```ts
|
|
825
|
+
* const cfg = this.getConfig<MyConfig>();
|
|
826
|
+
* ```
|
|
827
|
+
*/
|
|
828
|
+
getConfig<T = Record<string, unknown>>(): T | null;
|
|
829
|
+
protected _migrateLegacyConfigToThinkTable(): void;
|
|
830
|
+
private _ensureConfigTable;
|
|
831
|
+
private _configSet;
|
|
832
|
+
private _configGet;
|
|
833
|
+
private _configDelete;
|
|
834
|
+
/**
|
|
835
|
+
* Return the language model to use for inference.
|
|
836
|
+
* Must be overridden by subclasses.
|
|
837
|
+
*/
|
|
838
|
+
getModel(): LanguageModel;
|
|
839
|
+
/**
|
|
840
|
+
* Return the system prompt for the assistant.
|
|
841
|
+
* Used as fallback when no context blocks are configured via `configureSession`.
|
|
842
|
+
*/
|
|
843
|
+
getSystemPrompt(): string;
|
|
844
|
+
/** Return the tools available to the assistant. */
|
|
845
|
+
getTools(): ToolSet;
|
|
846
|
+
/** Return messenger integrations that should be routed through this Think agent. */
|
|
847
|
+
getMessengers(): ThinkMessengers;
|
|
848
|
+
getMessengerContext(): MessengerContext | undefined;
|
|
849
|
+
chatWithMessengerContext(
|
|
850
|
+
userMessage: string | UIMessage,
|
|
851
|
+
callback: StreamCallback,
|
|
852
|
+
context: MessengerContext,
|
|
853
|
+
options?: ChatOptions
|
|
854
|
+
): Promise<void>;
|
|
855
|
+
private _initializeMessengers;
|
|
856
|
+
/** Return code-declared scheduled tasks for this agent. */
|
|
857
|
+
getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks>;
|
|
858
|
+
/**
|
|
859
|
+
* Reconcile code-declared scheduled tasks immediately.
|
|
860
|
+
* Static declarations are reconciled on startup automatically; call this
|
|
861
|
+
* after changing app-owned data that `getScheduledTasks()` reads.
|
|
862
|
+
*/
|
|
863
|
+
internal_reconcileScheduledTasks(): Promise<void>;
|
|
864
|
+
/**
|
|
865
|
+
* Return the default timezone for wall-clock scheduled tasks.
|
|
866
|
+
* Task-local timezone declarations take precedence.
|
|
867
|
+
*/
|
|
868
|
+
getDefaultTimezone(): string | undefined | Promise<string | undefined>;
|
|
869
|
+
private _runChatRecoveryFiber;
|
|
870
|
+
private _systemPromptForTurn;
|
|
871
|
+
private _buildThinkCapabilityBlock;
|
|
872
|
+
/** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
|
|
873
|
+
maxSteps: number;
|
|
874
|
+
/**
|
|
875
|
+
* Whether reasoning chunks are sent to chat clients by default. Override
|
|
876
|
+
* per turn by returning `sendReasoning` from `beforeTurn`.
|
|
877
|
+
*/
|
|
878
|
+
sendReasoning: boolean;
|
|
879
|
+
/**
|
|
880
|
+
* Inactivity watchdog for the streaming read loop, in milliseconds.
|
|
881
|
+
*
|
|
882
|
+
* If a turn's model stream produces no chunk for this long, the watchdog
|
|
883
|
+
* aborts the turn and surfaces a terminal stream error instead of letting the
|
|
884
|
+
* loop park forever on a hung provider/transport (the "infinite spinner"
|
|
885
|
+
* failure: the stream never throws, so no error and no `done` ever arrives).
|
|
886
|
+
* A `chat:stream:stalled` observability event is emitted when it fires.
|
|
887
|
+
*
|
|
888
|
+
* This measures the gap *between UI-message-stream chunks*, which includes
|
|
889
|
+
* time spent executing server-side tools (no chunks flow while a tool runs).
|
|
890
|
+
* Set it comfortably above your slowest expected model time-to-first-token
|
|
891
|
+
* and your slowest tool execution, or you will abort healthy long turns.
|
|
892
|
+
*
|
|
893
|
+
* Default `0` (disabled) — opt in by setting a value (e.g. `120_000`).
|
|
894
|
+
*
|
|
895
|
+
* Can be overridden per-turn via `TurnConfig.chatStreamStallTimeoutMs`
|
|
896
|
+
* (returned from `beforeTurn`) for turns with known-slow tools.
|
|
897
|
+
*/
|
|
898
|
+
chatStreamStallTimeoutMs: number;
|
|
899
|
+
/**
|
|
900
|
+
* Per-turn stall-watchdog timeout resolved from `TurnConfig` in
|
|
901
|
+
* `_runInferenceLoop`, read by the stream loop when arming the watchdog.
|
|
902
|
+
* `undefined` falls back to the instance-level `chatStreamStallTimeoutMs`.
|
|
903
|
+
* Turns are serialized, so a single active value is safe; it is reset at the
|
|
904
|
+
* top of every `_runInferenceLoop`.
|
|
905
|
+
*/
|
|
906
|
+
private _activeStallTimeoutMs;
|
|
907
|
+
/**
|
|
908
|
+
* Configure the session. Called once during `onStart`.
|
|
909
|
+
* Override to add context blocks, compaction, search, skills.
|
|
910
|
+
*
|
|
911
|
+
* @example
|
|
912
|
+
* ```typescript
|
|
913
|
+
* configureSession(session: Session) {
|
|
914
|
+
* return session
|
|
915
|
+
* .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
|
|
916
|
+
* .withCachedPrompt();
|
|
917
|
+
* }
|
|
918
|
+
* ```
|
|
919
|
+
*/
|
|
920
|
+
configureSession(session: Session): Session | Promise<Session>;
|
|
921
|
+
/**
|
|
922
|
+
* Return Agent Skills sources for this Think agent.
|
|
923
|
+
*
|
|
924
|
+
* Bundled skills are typically imported with the Agents Vite plugin:
|
|
925
|
+
*
|
|
926
|
+
* ```typescript
|
|
927
|
+
* import productSkills from "agents:skills"; // -> ./skills next to this file
|
|
928
|
+
* ```
|
|
929
|
+
*
|
|
930
|
+
* Sources are applied in order; the first source to register a skill name
|
|
931
|
+
* wins, and later collisions are skipped with a logged warning.
|
|
932
|
+
*/
|
|
933
|
+
getSkills(): SkillSource[] | Promise<SkillSource[]>;
|
|
934
|
+
private _initializeSkills;
|
|
935
|
+
/**
|
|
936
|
+
* Log registry diagnostics (duplicate names, sources that failed to list),
|
|
937
|
+
* deduped by message so a new collision after a deploy still surfaces while
|
|
938
|
+
* the same warning is not repeated on every turn.
|
|
939
|
+
*/
|
|
940
|
+
private _logSkillWarnings;
|
|
941
|
+
/**
|
|
942
|
+
* Return an optional runner that enables the `run_skill_script` tool.
|
|
943
|
+
*
|
|
944
|
+
* @experimental Skill script execution is experimental and may change
|
|
945
|
+
* before stabilizing.
|
|
946
|
+
*/
|
|
947
|
+
getSkillScriptRunner(): SkillScriptRunner | null;
|
|
948
|
+
private _refreshSkillsIfChanged;
|
|
949
|
+
/**
|
|
950
|
+
* Return sandboxed extension configurations. Defines load order,
|
|
951
|
+
* which determines hook execution order.
|
|
952
|
+
* Requires `extensionLoader` to be set.
|
|
953
|
+
*/
|
|
954
|
+
getExtensions(): ExtensionConfig[];
|
|
955
|
+
/**
|
|
956
|
+
* Called before `streamText` — inspect the assembled context and
|
|
957
|
+
* return overrides. Think assembles tools, system prompt, and messages
|
|
958
|
+
* internally; this hook sees the result and can override any part.
|
|
959
|
+
*
|
|
960
|
+
* Return `void` to accept all defaults.
|
|
961
|
+
*
|
|
962
|
+
* @example Switch model for continuations
|
|
963
|
+
* ```typescript
|
|
964
|
+
* beforeTurn(ctx: TurnContext) {
|
|
965
|
+
* if (ctx.continuation) return { model: this.cheapModel };
|
|
966
|
+
* }
|
|
967
|
+
* ```
|
|
968
|
+
*
|
|
969
|
+
* @example Restrict active tools
|
|
970
|
+
* ```typescript
|
|
971
|
+
* beforeTurn(ctx: TurnContext) {
|
|
972
|
+
* return { activeTools: ["read", "write"] };
|
|
973
|
+
* }
|
|
974
|
+
* ```
|
|
975
|
+
*/
|
|
976
|
+
beforeTurn(_ctx: TurnContext): TurnConfig | void | Promise<TurnConfig | void>;
|
|
977
|
+
/**
|
|
978
|
+
* Called before each AI SDK step in the agentic loop. Backed by
|
|
979
|
+
* `streamText({ prepareStep })`.
|
|
980
|
+
*
|
|
981
|
+
* Return `void` to accept the current step defaults, or return a
|
|
982
|
+
* `StepConfig` to override the model, tool choice, active tools,
|
|
983
|
+
* system prompt, messages, experimental context, or provider options
|
|
984
|
+
* for this step. Use `beforeTurn` for turn-wide assembly and
|
|
985
|
+
* `beforeStep` when the decision depends on the step number or
|
|
986
|
+
* previous step results.
|
|
987
|
+
*
|
|
988
|
+
* @example Force search on the first step
|
|
989
|
+
* ```typescript
|
|
990
|
+
* beforeStep(ctx: PrepareStepContext) {
|
|
991
|
+
* if (ctx.stepNumber === 0) {
|
|
992
|
+
* return {
|
|
993
|
+
* activeTools: ["search"],
|
|
994
|
+
* toolChoice: { type: "tool", toolName: "search" }
|
|
995
|
+
* };
|
|
996
|
+
* }
|
|
997
|
+
* }
|
|
998
|
+
* ```
|
|
999
|
+
*
|
|
1000
|
+
* @example Switch to a cheaper model after tool results land
|
|
1001
|
+
* ```typescript
|
|
1002
|
+
* beforeStep(ctx: PrepareStepContext) {
|
|
1003
|
+
* // assumes a `fastSummaryModel` field on your Think subclass
|
|
1004
|
+
* if (ctx.steps.some((s) => s.toolResults.length > 0)) {
|
|
1005
|
+
* return { model: this.fastSummaryModel };
|
|
1006
|
+
* }
|
|
1007
|
+
* }
|
|
1008
|
+
* ```
|
|
1009
|
+
*/
|
|
1010
|
+
beforeStep(
|
|
1011
|
+
_ctx: PrepareStepContext
|
|
1012
|
+
): StepConfig | void | Promise<StepConfig | void>;
|
|
1013
|
+
/**
|
|
1014
|
+
* Called **before** the tool's `execute` function runs. Think wraps
|
|
1015
|
+
* every tool's `execute` so it can consult this hook and act on the
|
|
1016
|
+
* returned `ToolCallDecision`:
|
|
1017
|
+
*
|
|
1018
|
+
* - `void` (or `{ action: "allow" }` with no `input`) — run the
|
|
1019
|
+
* original `execute` with the original input.
|
|
1020
|
+
* - `{ action: "allow", input }` — run the original `execute` with
|
|
1021
|
+
* the substituted input.
|
|
1022
|
+
* - `{ action: "block", reason }` — skip `execute`; the model sees
|
|
1023
|
+
* `reason` as the tool's output.
|
|
1024
|
+
* - `{ action: "substitute", output }` — skip `execute`; the model
|
|
1025
|
+
* sees `output` as the tool's output.
|
|
1026
|
+
*
|
|
1027
|
+
* Only fires for server-side tools (tools with `execute`). Client
|
|
1028
|
+
* tools are handled on the client — Think can't intercept them.
|
|
1029
|
+
*
|
|
1030
|
+
* `afterToolCall` always fires after this hook (or after the original
|
|
1031
|
+
* `execute` when `allow`). For `block`/`substitute`, the substituted
|
|
1032
|
+
* value flows through `afterToolCall` as `success: true, output: ...`.
|
|
1033
|
+
*
|
|
1034
|
+
* @example Log tool calls
|
|
1035
|
+
* ```typescript
|
|
1036
|
+
* beforeToolCall(ctx: ToolCallContext) {
|
|
1037
|
+
* console.log(`Tool called: ${ctx.toolName}`, ctx.input);
|
|
1038
|
+
* }
|
|
1039
|
+
* ```
|
|
1040
|
+
*
|
|
1041
|
+
* @example Block a tool the model shouldn't be calling here
|
|
1042
|
+
* ```typescript
|
|
1043
|
+
* beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
|
|
1044
|
+
* if (ctx.toolName === "delete" && this.isReadOnlyMode) {
|
|
1045
|
+
* return { action: "block", reason: "delete is disabled in read-only mode" };
|
|
1046
|
+
* }
|
|
1047
|
+
* }
|
|
1048
|
+
* ```
|
|
1049
|
+
*
|
|
1050
|
+
* @example Substitute a cached result
|
|
1051
|
+
* ```typescript
|
|
1052
|
+
* async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {
|
|
1053
|
+
* if (ctx.toolName === "weather") {
|
|
1054
|
+
* const cached = await this.cache.get(JSON.stringify(ctx.input));
|
|
1055
|
+
* if (cached) return { action: "substitute", output: cached };
|
|
1056
|
+
* }
|
|
1057
|
+
* }
|
|
1058
|
+
* ```
|
|
1059
|
+
*/
|
|
1060
|
+
beforeToolCall(
|
|
1061
|
+
_ctx: ToolCallContext
|
|
1062
|
+
): ToolCallDecision | void | Promise<ToolCallDecision | void>;
|
|
1063
|
+
/**
|
|
1064
|
+
* Called **after** a tool's outcome is known — for real executions, for
|
|
1065
|
+
* `block` (carries the `reason` as `output`), and for `substitute`
|
|
1066
|
+
* (carries the substituted `output`). Backed by the AI SDK's
|
|
1067
|
+
* `experimental_onToolCallFinish`, so `durationMs` and the discriminated
|
|
1068
|
+
* `success`/`output`/`error` outcome reflect what the model actually
|
|
1069
|
+
* sees: a thrown error from the original `execute` becomes
|
|
1070
|
+
* `success: false, error: ...`; everything else (including blocked /
|
|
1071
|
+
* substituted calls) is `success: true, output: ...`.
|
|
1072
|
+
*
|
|
1073
|
+
* Override for logging, metrics, or result inspection.
|
|
1074
|
+
*
|
|
1075
|
+
* @example
|
|
1076
|
+
* ```typescript
|
|
1077
|
+
* afterToolCall(ctx: ToolCallResultContext) {
|
|
1078
|
+
* if (ctx.success) {
|
|
1079
|
+
* console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);
|
|
1080
|
+
* } else {
|
|
1081
|
+
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
1082
|
+
* }
|
|
1083
|
+
* }
|
|
1084
|
+
* ```
|
|
1085
|
+
*/
|
|
1086
|
+
afterToolCall(_ctx: ToolCallResultContext): void | Promise<void>;
|
|
1087
|
+
/**
|
|
1088
|
+
* Called after each step completes (initial, continue, tool-result).
|
|
1089
|
+
* Override for step-level logging or analytics.
|
|
1090
|
+
*/
|
|
1091
|
+
onStepFinish(_ctx: StepContext): void | Promise<void>;
|
|
1092
|
+
/**
|
|
1093
|
+
* Called for each streaming chunk. High-frequency — fires per token.
|
|
1094
|
+
* Override for streaming analytics, progress indicators, or token counting.
|
|
1095
|
+
* Observational only (void return).
|
|
1096
|
+
*/
|
|
1097
|
+
onChunk(_ctx: ChunkContext): void | Promise<void>;
|
|
1098
|
+
/**
|
|
1099
|
+
* Called after a chat turn completes and the assistant message has been
|
|
1100
|
+
* persisted. The turn lock is released before this hook runs, so it is
|
|
1101
|
+
* safe to call other methods from inside.
|
|
1102
|
+
*
|
|
1103
|
+
* Fires for all turn completion paths: WebSocket chat requests,
|
|
1104
|
+
* sub-agent RPC, and auto-continuation.
|
|
1105
|
+
*
|
|
1106
|
+
* Override for logging, chaining, analytics, usage tracking.
|
|
1107
|
+
*/
|
|
1108
|
+
onChatResponse(_result: ChatResponseResult): void | Promise<void>;
|
|
1109
|
+
/**
|
|
1110
|
+
* Handle an error that occurred during a chat turn.
|
|
1111
|
+
* Override to customize error handling (e.g. logging, metrics).
|
|
1112
|
+
*/
|
|
1113
|
+
onChatError(error: unknown, _ctx?: ChatErrorContext): unknown;
|
|
1114
|
+
private _initializeExtensions;
|
|
1115
|
+
/**
|
|
1116
|
+
* The single convergence point for all chat turn entry paths.
|
|
1117
|
+
* Merges tools, assembles context, fires lifecycle hooks, wraps tools
|
|
1118
|
+
* for interception, and calls streamText.
|
|
1119
|
+
*/
|
|
1120
|
+
private _runInferenceLoop;
|
|
1121
|
+
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
1122
|
+
protected _transformInferenceResult(
|
|
1123
|
+
result: StreamableResult
|
|
1124
|
+
): StreamableResult;
|
|
1125
|
+
/** Default hook timeout in milliseconds. */
|
|
1126
|
+
hookTimeout: number;
|
|
1127
|
+
/**
|
|
1128
|
+
* Pipeline beforeTurn through sandboxed extensions in load order.
|
|
1129
|
+
* Each extension sees the accumulated state from prior extensions
|
|
1130
|
+
* (snapshot is rebuilt after each extension's modifications).
|
|
1131
|
+
* Results are merged with last-write-wins for scalar fields.
|
|
1132
|
+
* Extensions that don't subscribe to beforeTurn are skipped.
|
|
1133
|
+
*/
|
|
1134
|
+
private _pipelineExtensionBeforeTurn;
|
|
1135
|
+
/**
|
|
1136
|
+
* Dispatch an observation hook to all extensions that subscribe to it.
|
|
1137
|
+
*
|
|
1138
|
+
* Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,
|
|
1139
|
+
* `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike
|
|
1140
|
+
* `beforeTurn`, these hooks are observation-only — extensions can't
|
|
1141
|
+
* influence the turn — so we ignore return values, log errors, and
|
|
1142
|
+
* apply a per-extension timeout.
|
|
1143
|
+
*
|
|
1144
|
+
* `onChunk` is high-frequency (per token) — extensions that subscribe
|
|
1145
|
+
* to it pay an RPC cost per chunk and should be used sparingly.
|
|
1146
|
+
*/
|
|
1147
|
+
private _dispatchExtensionObservation;
|
|
1148
|
+
/**
|
|
1149
|
+
* Wrap each tool's `execute` function so the agent's `beforeToolCall`
|
|
1150
|
+
* hook is consulted before the tool runs. The hook can return a
|
|
1151
|
+
* `ToolCallDecision` to:
|
|
1152
|
+
*
|
|
1153
|
+
* - `allow` (default if `void` is returned) — run the original
|
|
1154
|
+
* `execute`, optionally with a substituted `input`.
|
|
1155
|
+
* - `block` — skip `execute` and return `reason` (or a default string)
|
|
1156
|
+
* as the tool result. The model sees this as the tool's output.
|
|
1157
|
+
* - `substitute` — skip `execute` and return `output` directly. The
|
|
1158
|
+
* model sees this as the tool's output.
|
|
1159
|
+
*
|
|
1160
|
+
* The wrapped `execute` also dispatches the `beforeToolCall`
|
|
1161
|
+
* observation snapshot to subscribed extensions. `afterToolCall` is
|
|
1162
|
+
* still wired through the AI SDK's `experimental_onToolCallFinish`
|
|
1163
|
+
* callback so we get accurate `durationMs` and proper success/error
|
|
1164
|
+
* discrimination — `block` and `substitute` outcomes show up as
|
|
1165
|
+
* `success: true` with the substituted output; uncaught throws from
|
|
1166
|
+
* the original `execute` show up as `success: false` with the error.
|
|
1167
|
+
*
|
|
1168
|
+
* Tools without an `execute` (output-schema-only tools, client tools
|
|
1169
|
+
* routed via `needsApproval`) are left untouched.
|
|
1170
|
+
*
|
|
1171
|
+
* **Streaming tools (AsyncIterable):** the AI SDK supports tools whose
|
|
1172
|
+
* `execute` returns `AsyncIterable<output>` to emit preliminary
|
|
1173
|
+
* results before a final value. This works whether the iterator is
|
|
1174
|
+
* returned directly (sync function, `async function*`) or wrapped in
|
|
1175
|
+
* a Promise (`async function execute(...) { return makeIter(); }`).
|
|
1176
|
+
* Because the wrapper must `await beforeToolCall` first, preliminary
|
|
1177
|
+
* chunks are collapsed — only the *final* yielded value reaches the
|
|
1178
|
+
* model. If you need true preliminary streaming, override
|
|
1179
|
+
* `getTools()` to provide such tools and avoid using `beforeToolCall`
|
|
1180
|
+
* for them (or accept the collapse).
|
|
1181
|
+
*/
|
|
1182
|
+
private _wrapToolsWithDecision;
|
|
1183
|
+
private _pipelineExtensionToolCallStart;
|
|
1184
|
+
private _pipelineExtensionToolCallFinish;
|
|
1185
|
+
private _pipelineExtensionStepFinish;
|
|
1186
|
+
private _pipelineExtensionChunk;
|
|
1187
|
+
_hostReadFile(path: string): Promise<string | null>;
|
|
1188
|
+
_hostWriteFile(path: string, content: string): Promise<void>;
|
|
1189
|
+
_hostDeleteFile(path: string): Promise<boolean>;
|
|
1190
|
+
_hostListFiles(dir: string): Promise<
|
|
1191
|
+
Array<{
|
|
1192
|
+
name: string;
|
|
1193
|
+
type: string;
|
|
1194
|
+
size: number;
|
|
1195
|
+
path: string;
|
|
1196
|
+
}>
|
|
1197
|
+
>;
|
|
1198
|
+
_hostGetContext(label: string): Promise<string | null>;
|
|
1199
|
+
_hostSetContext(label: string, content: string): Promise<void>;
|
|
1200
|
+
_hostGetMessages(limit?: number): Promise<
|
|
1201
|
+
Array<{
|
|
1202
|
+
id: string;
|
|
1203
|
+
role: string;
|
|
1204
|
+
content: string;
|
|
1205
|
+
}>
|
|
1206
|
+
>;
|
|
1207
|
+
_hostSendMessage(content: string): Promise<void>;
|
|
1208
|
+
_hostGetSessionInfo(): Promise<{
|
|
1209
|
+
messageCount: number;
|
|
1210
|
+
}>;
|
|
1211
|
+
/**
|
|
1212
|
+
* Run a chat turn: persist the user message, run the agentic loop,
|
|
1213
|
+
* stream UIMessageChunk events via callback, and persist the
|
|
1214
|
+
* assistant's response.
|
|
1215
|
+
*
|
|
1216
|
+
* @param userMessage The user's message (string or UIMessage)
|
|
1217
|
+
* @param callback Streaming callback (typically an RpcTarget from the parent)
|
|
1218
|
+
* @param options Optional chat options (e.g. AbortSignal)
|
|
1219
|
+
*/
|
|
1220
|
+
chat(
|
|
1221
|
+
userMessage: string | UIMessage,
|
|
1222
|
+
callback: StreamCallback,
|
|
1223
|
+
options?: ChatOptions
|
|
1224
|
+
): Promise<void>;
|
|
1225
|
+
/** Get the conversation history as UIMessage[]. */
|
|
1226
|
+
getMessages(): Promise<UIMessage[]>;
|
|
1227
|
+
/** Clear all messages from storage. */
|
|
1228
|
+
clearMessages(): Promise<void>;
|
|
1229
|
+
private _ensureAgentToolChildRunTable;
|
|
1230
|
+
private _addAgentToolChildRunColumnIfMissing;
|
|
1231
|
+
private _readAgentToolChildRun;
|
|
1232
|
+
private _inspectionFromChildRow;
|
|
1233
|
+
protected formatAgentToolInput(input: unknown): UIMessage;
|
|
1234
|
+
protected getAgentToolOutput(_runId: string): unknown;
|
|
1235
|
+
protected getAgentToolSummary(runId: string, output: unknown): string;
|
|
1236
|
+
startAgentToolRun(
|
|
1237
|
+
input: unknown,
|
|
1238
|
+
options: {
|
|
1239
|
+
runId: string;
|
|
1240
|
+
}
|
|
1241
|
+
): Promise<AgentToolRunInspection>;
|
|
1242
|
+
cancelAgentToolRun(runId: string, reason?: unknown): Promise<void>;
|
|
1243
|
+
/**
|
|
1244
|
+
* Classify any in-flight chat-recovery on this child facet (#1630). A child
|
|
1245
|
+
* facet is dedicated to a single agent-tool run, so any recovery incident is
|
|
1246
|
+
* that run's. `detected`/`scheduled`/`attempting` mean recovery is still
|
|
1247
|
+
* resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a
|
|
1248
|
+
* completed recovery deletes its incident.
|
|
1249
|
+
*/
|
|
1250
|
+
private _classifyAgentToolChildRecovery;
|
|
1251
|
+
inspectAgentToolRun(runId: string): Promise<AgentToolRunInspection | null>;
|
|
1252
|
+
private _isStaleAgentToolChildRun;
|
|
1253
|
+
/**
|
|
1254
|
+
* Reconcile a stale (post-eviction) child run row from the child's own
|
|
1255
|
+
* durable recovery (#1630). The child facet self-heals its interrupted turn
|
|
1256
|
+
* via `chatRecovery`, but that path never writes the run row, so without this
|
|
1257
|
+
* the row strands `running` and the parent can only collect `interrupted`.
|
|
1258
|
+
*
|
|
1259
|
+
* Persisting the terminal here (rather than only computing it) is intentional:
|
|
1260
|
+
* it's a lazy materialization of the run's true terminal that also lets a
|
|
1261
|
+
* tailing parent's stream close promptly and makes subsequent inspects cheap.
|
|
1262
|
+
* While recovery is still resolving (active stream or in-progress incident)
|
|
1263
|
+
* the row is left `running` so the parent's bounded re-attach keeps waiting.
|
|
1264
|
+
*/
|
|
1265
|
+
private _reconcileStaleAgentToolChildRun;
|
|
1266
|
+
/** Release a re-attached run's live tail + per-run streaming bookkeeping. */
|
|
1267
|
+
private _finalizeAgentToolChildRunTailers;
|
|
1268
|
+
getAgentToolChunks(
|
|
1269
|
+
runId: string,
|
|
1270
|
+
options?: {
|
|
1271
|
+
afterSequence?: number;
|
|
1272
|
+
}
|
|
1273
|
+
): Promise<AgentToolStoredChunk[]>;
|
|
1274
|
+
tailAgentToolRun(
|
|
1275
|
+
runId: string,
|
|
1276
|
+
options?: {
|
|
1277
|
+
afterSequence?: number;
|
|
1278
|
+
signal?: AbortSignal;
|
|
1279
|
+
}
|
|
1280
|
+
): Promise<ReadableStream<AgentToolStoredChunk>>;
|
|
1281
|
+
private static _stringifyAgentToolOutput;
|
|
1282
|
+
private static _parseAgentToolOutput;
|
|
1283
|
+
/**
|
|
1284
|
+
* Whether the run produced an assistant turn (text or tool-only). Used by the
|
|
1285
|
+
* post-eviction reconcile to mark a settled run `completed` even when it ended
|
|
1286
|
+
* without final text. A dedicated child facet starts with no assistant
|
|
1287
|
+
* messages, so a missing in-memory pre-turn snapshot is treated as empty.
|
|
1288
|
+
*/
|
|
1289
|
+
private _hasRecoveredAgentToolAssistantTurn;
|
|
1290
|
+
private _getAgentToolFinalText;
|
|
1291
|
+
private _ensureDeclaredScheduledTasksTable;
|
|
1292
|
+
private _readDeclaredScheduledTaskRow;
|
|
1293
|
+
private _listDeclaredScheduledTaskRows;
|
|
1294
|
+
private _updateDeclaredScheduledTaskSchedule;
|
|
1295
|
+
private _normalizeDeclaredScheduledTasks;
|
|
1296
|
+
private _declaredScheduledTasksForNow;
|
|
1297
|
+
private _declaredScheduleOwnerKey;
|
|
1298
|
+
private _declaredScheduleValidationError;
|
|
1299
|
+
private _nextDeclaredScheduleTimeForConfig;
|
|
1300
|
+
private _reconcileDeclaredScheduledTasks;
|
|
1301
|
+
private _scheduleDeclaredTaskOccurrence;
|
|
1302
|
+
private _scheduleDeclaredTaskOccurrenceAt;
|
|
1303
|
+
private _advanceDeclaredScheduledTask;
|
|
1304
|
+
private _declaredScheduledTaskContext;
|
|
1305
|
+
_runDeclaredScheduledTask(
|
|
1306
|
+
payload: DeclaredScheduledTaskPayload
|
|
1307
|
+
): Promise<void>;
|
|
1308
|
+
private _ensureSubmissionTable;
|
|
1309
|
+
private _ensureWorkflowNotificationTable;
|
|
1310
|
+
private _readSubmission;
|
|
1311
|
+
private _readSubmissionByIdempotencyKey;
|
|
1312
|
+
private _normalizeStatusFilter;
|
|
1313
|
+
private _listSubmissionRows;
|
|
1314
|
+
private _listSubmissionRowsByStatus;
|
|
1315
|
+
private _inspectionFromSubmissionRow;
|
|
1316
|
+
private _parseJsonObject;
|
|
1317
|
+
private _parseSubmissionMessages;
|
|
1318
|
+
private _serializeSubmissionMessages;
|
|
1319
|
+
private _serializeMetadata;
|
|
1320
|
+
private _readWorkflowPromptContext;
|
|
1321
|
+
private _emitSubmissionStatus;
|
|
1322
|
+
protected onSubmissionStatus(
|
|
1323
|
+
_submission: ThinkSubmissionInspection
|
|
1324
|
+
): void | Promise<void>;
|
|
1325
|
+
private _enqueueWorkflowNotification;
|
|
1326
|
+
private _insertWorkflowNotification;
|
|
1327
|
+
private _recoverWorkflowNotifications;
|
|
1328
|
+
private _startWorkflowNotificationDrain;
|
|
1329
|
+
private _hasPendingWorkflowNotifications;
|
|
1330
|
+
private _drainWorkflowNotifications;
|
|
1331
|
+
private _scheduleWorkflowNotificationAlarm;
|
|
1332
|
+
inspectSubmission(
|
|
1333
|
+
submissionId: string
|
|
1334
|
+
): Promise<ThinkSubmissionInspection | null>;
|
|
1335
|
+
listSubmissions(
|
|
1336
|
+
options?: ListSubmissionsOptions
|
|
1337
|
+
): Promise<ThinkSubmissionInspection[]>;
|
|
1338
|
+
deleteSubmission(submissionId: string): Promise<boolean>;
|
|
1339
|
+
deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number>;
|
|
1340
|
+
private _listTerminalSubmissionRowsForDelete;
|
|
1341
|
+
private _isTerminalSubmissionStatus;
|
|
1342
|
+
cancelSubmission(submissionId: string, reason?: unknown): Promise<void>;
|
|
1343
|
+
submitMessages(
|
|
1344
|
+
messages: UIMessage[],
|
|
1345
|
+
options?: SubmitMessagesOptions
|
|
1346
|
+
): Promise<SubmitMessagesResult>;
|
|
1347
|
+
private _scheduleSubmissionDrain;
|
|
1348
|
+
private _startSubmissionDrain;
|
|
1349
|
+
private _hasPendingSubmissions;
|
|
1350
|
+
_drainThinkSubmissions(): Promise<void>;
|
|
1351
|
+
private _drainSubmissions;
|
|
1352
|
+
private _runSubmission;
|
|
1353
|
+
private _getSubmissionFinalStatus;
|
|
1354
|
+
private _markPendingSubmissionsSkipped;
|
|
1355
|
+
private _emitSkippedSubmissions;
|
|
1356
|
+
private _recoverSubmissionsOnStart;
|
|
1357
|
+
private _getSubmissionMessagesAppliedState;
|
|
1358
|
+
private _hasRecoverableChatTurn;
|
|
1359
|
+
private _hasFreshRecoverableSubmissionEvidence;
|
|
1360
|
+
private _hasScheduledRecoveredContinuation;
|
|
1361
|
+
/**
|
|
1362
|
+
* Inject messages and trigger a model turn — without a WebSocket request.
|
|
1363
|
+
*
|
|
1364
|
+
* Use for scheduled responses, webhook-triggered turns, proactive agents,
|
|
1365
|
+
* or chaining from `onChatResponse`.
|
|
1366
|
+
*
|
|
1367
|
+
* Accepts static messages or a callback that derives messages from the
|
|
1368
|
+
* current state (useful when multiple calls queue up — the callback runs
|
|
1369
|
+
* with the latest messages when the turn actually starts).
|
|
1370
|
+
*
|
|
1371
|
+
* Pass `options.signal` to cancel the turn from outside without knowing
|
|
1372
|
+
* the internally-generated request id. The signal is linked to the
|
|
1373
|
+
* registry's controller for this turn — when it aborts, the inference
|
|
1374
|
+
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
1375
|
+
* Pre-aborted signals short-circuit before any model work runs. See
|
|
1376
|
+
* {@link SaveMessagesOptions} for the integration point.
|
|
1377
|
+
*
|
|
1378
|
+
* @example Scheduled follow-up
|
|
1379
|
+
* ```typescript
|
|
1380
|
+
* async onScheduled() {
|
|
1381
|
+
* await this.saveMessages([{
|
|
1382
|
+
* id: crypto.randomUUID(),
|
|
1383
|
+
* role: "user",
|
|
1384
|
+
* parts: [{ type: "text", text: "Time for your daily summary." }]
|
|
1385
|
+
* }]);
|
|
1386
|
+
* }
|
|
1387
|
+
* ```
|
|
1388
|
+
*
|
|
1389
|
+
* @example Function form
|
|
1390
|
+
* ```typescript
|
|
1391
|
+
* await this.saveMessages((current) => [
|
|
1392
|
+
* ...current,
|
|
1393
|
+
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
1394
|
+
* ]);
|
|
1395
|
+
* ```
|
|
1396
|
+
*
|
|
1397
|
+
* @example External cancellation (helper-as-sub-agent)
|
|
1398
|
+
* ```typescript
|
|
1399
|
+
* // Inside a parent agent's tool execute — forward the AI SDK's
|
|
1400
|
+
* // abortSignal so a parent stop / tab close cancels the helper.
|
|
1401
|
+
* await helper.saveMessages([userMsg], { signal: abortSignal });
|
|
1402
|
+
* ```
|
|
1403
|
+
*/
|
|
1404
|
+
saveMessages(
|
|
1405
|
+
messages:
|
|
1406
|
+
| UIMessage[]
|
|
1407
|
+
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),
|
|
1408
|
+
options?: SaveMessagesOptions
|
|
1409
|
+
): Promise<SaveMessagesResult>;
|
|
1410
|
+
private _runProgrammaticMessagesTurn;
|
|
1411
|
+
/**
|
|
1412
|
+
* Run a new LLM call following the last assistant message.
|
|
1413
|
+
*
|
|
1414
|
+
* The model sees the full conversation (including the last assistant
|
|
1415
|
+
* response) and generates a new response. The new response is persisted
|
|
1416
|
+
* as a separate assistant message. Building block for chat recovery
|
|
1417
|
+
* (Phase 4), "generate more" buttons, and self-correction.
|
|
1418
|
+
*
|
|
1419
|
+
* Note: this creates a new message, not an append to the existing one.
|
|
1420
|
+
* True continuation-as-append (chunk rewriting) is planned for Phase 4.
|
|
1421
|
+
*
|
|
1422
|
+
* Returns early with `status: "skipped"` if there is no assistant message
|
|
1423
|
+
* to continue from.
|
|
1424
|
+
*
|
|
1425
|
+
* Pass `options.signal` to cancel the continuation from outside —
|
|
1426
|
+
* matches the {@link saveMessages} contract.
|
|
1427
|
+
*/
|
|
1428
|
+
protected continueLastTurn(
|
|
1429
|
+
body?: Record<string, unknown>,
|
|
1430
|
+
options?: SaveMessagesOptions
|
|
1431
|
+
): Promise<SaveMessagesResult>;
|
|
1432
|
+
private _retryLastUserTurn;
|
|
1433
|
+
private _setupProtocolHandlers;
|
|
1434
|
+
private _handleProtocolEvent;
|
|
1435
|
+
private _handleStreamResumeRequest;
|
|
1436
|
+
private _handleStreamResumeAck;
|
|
1437
|
+
private _handleChatRequest;
|
|
1438
|
+
/**
|
|
1439
|
+
* Abort the active turn, invalidate queued turns, and reset
|
|
1440
|
+
* concurrency/continuation state. Call this when intercepting
|
|
1441
|
+
* clear events or implementing custom reset logic.
|
|
1442
|
+
*
|
|
1443
|
+
* Does NOT clear messages, streams, or persisted state —
|
|
1444
|
+
* only turn execution state.
|
|
1445
|
+
*/
|
|
1446
|
+
protected resetTurnState(): void;
|
|
1447
|
+
/**
|
|
1448
|
+
* Abort a single in-flight chat turn by request id.
|
|
1449
|
+
*
|
|
1450
|
+
* Equivalent to the cancel path that fires when a client sends a
|
|
1451
|
+
* `chat-request-cancel` WebSocket message — the inference loop's
|
|
1452
|
+
* signal aborts, partial chunks already streamed are still
|
|
1453
|
+
* persisted, and the turn's `ChatResponseResult` reports
|
|
1454
|
+
* `status: "aborted"`.
|
|
1455
|
+
*
|
|
1456
|
+
* No-op if no controller exists for `requestId` (the turn already
|
|
1457
|
+
* completed, was never started, or used a different id).
|
|
1458
|
+
*
|
|
1459
|
+
* `chat()` callers can read the request id from
|
|
1460
|
+
* {@link StreamCallback.onStart} and later pass it here from another
|
|
1461
|
+
* RPC call.
|
|
1462
|
+
*
|
|
1463
|
+
* Prefer {@link SaveMessagesOptions.signal} when driving a turn
|
|
1464
|
+
* programmatically — it threads the abort intent in from the start
|
|
1465
|
+
* without requiring the caller to know the id.
|
|
1466
|
+
*/
|
|
1467
|
+
cancelChat(requestId: string, reason?: string): void;
|
|
1468
|
+
/** Abort every in-flight chat turn on this agent. */
|
|
1469
|
+
cancelAllChats(): void;
|
|
1470
|
+
protected abortRequest(requestId: string, reason?: unknown): void;
|
|
1471
|
+
/**
|
|
1472
|
+
* Abort every in-flight chat turn on this agent.
|
|
1473
|
+
*
|
|
1474
|
+
* Aborts all controllers in the registry and clears it. Used by
|
|
1475
|
+
* subclasses that drive single-purpose turns (e.g. a sub-agent
|
|
1476
|
+
* helper that runs one turn at a time over RPC) and want a coarse
|
|
1477
|
+
* "cancel whatever is running" handle without tracking request ids.
|
|
1478
|
+
*
|
|
1479
|
+
* Does NOT reset queued turns, continuation timers, or submit
|
|
1480
|
+
* concurrency state — use {@link resetTurnState} for the full
|
|
1481
|
+
* teardown that runs on `chat-clear`.
|
|
1482
|
+
*/
|
|
1483
|
+
protected abortAllRequests(): void;
|
|
1484
|
+
private _handleClear;
|
|
1485
|
+
private _streamResultToRpcCallback;
|
|
1486
|
+
/**
|
|
1487
|
+
* Whether storing this chunk should immediately flush the resumable-stream
|
|
1488
|
+
* buffer to SQLite.
|
|
1489
|
+
*
|
|
1490
|
+
* A settled tool result (`tool-output-available` / `tool-output-error` /
|
|
1491
|
+
* `tool-output-denied`) captures a completed, often non-idempotent side
|
|
1492
|
+
* effect — or, for a denial, a user decision — so it is flushed
|
|
1493
|
+
* **immediately**. An isolate eviction (deploy) before the next batch flush
|
|
1494
|
+
* would otherwise lose it, and recovery would re-anchor without it and re-run
|
|
1495
|
+
* the already-completed tool call (or drop the denial). Frequent recoverable
|
|
1496
|
+
* content (text / reasoning / tool-input streaming) is throttled to avoid
|
|
1497
|
+
* write amplification.
|
|
1498
|
+
*/
|
|
1499
|
+
private _shouldFlushRecoverableChunk;
|
|
1500
|
+
/**
|
|
1501
|
+
* Store a stream chunk, flushing settled tool results durably and promptly.
|
|
1502
|
+
* Shared by the WebSocket and sub-agent RPC streaming paths so both get
|
|
1503
|
+
* tool-call-level recovery durability (recovery loses at most the in-flight
|
|
1504
|
+
* step, never an already-completed tool call).
|
|
1505
|
+
*/
|
|
1506
|
+
private _storeChunkDurably;
|
|
1507
|
+
/**
|
|
1508
|
+
* Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives
|
|
1509
|
+
* within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and
|
|
1510
|
+
* the iterator throws, so the consumer loop exits with a terminal error
|
|
1511
|
+
* instead of parking forever on a hung provider/transport. `timeoutMs <= 0`
|
|
1512
|
+
* passes the source through untouched.
|
|
1513
|
+
*/
|
|
1514
|
+
private _iterateWithStallWatchdog;
|
|
1515
|
+
private _streamResult;
|
|
1516
|
+
private _persistAssistantMessage;
|
|
1517
|
+
/**
|
|
1518
|
+
* Persist an incoming message after reconciliation. For assistant
|
|
1519
|
+
* messages, also resolve their ID against any server-side row that
|
|
1520
|
+
* already owns the same `toolCallId` so we update the existing row
|
|
1521
|
+
* instead of inserting an orphan duplicate.
|
|
1522
|
+
*/
|
|
1523
|
+
private _persistIncomingMessage;
|
|
1524
|
+
private _persistClientTools;
|
|
1525
|
+
private _restoreClientTools;
|
|
1526
|
+
private _persistBody;
|
|
1527
|
+
private _restoreBody;
|
|
1528
|
+
/**
|
|
1529
|
+
* Serialize a client-tool result/approval apply behind any in-flight apply
|
|
1530
|
+
* (#1649). Parallel tool results arrive as independent WebSocket messages,
|
|
1531
|
+
* and each apply is a read-modify-write of the full message in durable
|
|
1532
|
+
* storage. Running them concurrently means every apply reads the same
|
|
1533
|
+
* snapshot (all siblings still `input-available`), patches only its own part,
|
|
1534
|
+
* and writes the whole message back — so the last write clobbers the others
|
|
1535
|
+
* back to `input-available`, and the auto-continuation barrier later times
|
|
1536
|
+
* out and the transcript-repair backstop errors the lost siblings.
|
|
1537
|
+
*
|
|
1538
|
+
* Chaining each apply off `_interactionApplyTail` makes the read-modify-write
|
|
1539
|
+
* atomic per result and in arrival order. `_pendingInteractionPromise` is set
|
|
1540
|
+
* to the newest link so the barrier's single-slot wake-up still observes the
|
|
1541
|
+
* latest apply; because the chain is serial, awaiting it transitively waits
|
|
1542
|
+
* for every predecessor.
|
|
1543
|
+
*
|
|
1544
|
+
* @internal
|
|
1545
|
+
*/
|
|
1546
|
+
protected _enqueueInteractionApply(
|
|
1547
|
+
apply: () => Promise<void>
|
|
1548
|
+
): Promise<boolean>;
|
|
1549
|
+
private _applyToolResult;
|
|
1550
|
+
private _applyToolApproval;
|
|
1551
|
+
private _applyToolUpdateToMessages;
|
|
1552
|
+
protected hasPendingInteraction(): boolean;
|
|
1553
|
+
protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
|
|
1554
|
+
private _awaitWithDeadline;
|
|
1555
|
+
private _messageHasPendingInteraction;
|
|
1556
|
+
/**
|
|
1557
|
+
* Names of the tools whose interrupted `input-available` part can still be
|
|
1558
|
+
* resolved by the CLIENT after a restart — i.e. the client tools (no server
|
|
1559
|
+
* `execute`) from the last request, which the SPA answers by replaying a
|
|
1560
|
+
* `tool-result` over the WebSocket. A server tool is intentionally absent:
|
|
1561
|
+
* its `execute()` promise died with the evicted isolate, so nothing will
|
|
1562
|
+
* ever post its result.
|
|
1563
|
+
*/
|
|
1564
|
+
private _clientResolvableToolNames;
|
|
1565
|
+
/** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
|
|
1566
|
+
private _toolPartName;
|
|
1567
|
+
/**
|
|
1568
|
+
* Whether a part is still awaiting a CLIENT interaction that can genuinely
|
|
1569
|
+
* arrive after a restart, so `waitUntilStable` must keep waiting for it:
|
|
1570
|
+
* - `approval-requested`: a reconnecting client can replay the approval.
|
|
1571
|
+
* - `input-available` for a CLIENT tool: the SPA can replay the
|
|
1572
|
+
* `tool-result` (this is why client-tool recovery works — see the
|
|
1573
|
+
* `tool-result` handler, which sets `_pendingInteractionPromise`).
|
|
1574
|
+
*
|
|
1575
|
+
* A SERVER tool's `input-available` is deliberately NOT pending. After an
|
|
1576
|
+
* eviction its `execute()` promise is gone and no interaction will ever
|
|
1577
|
+
* resolve it, so treating it as pending wedges `waitUntilStable` forever:
|
|
1578
|
+
* the recovery continuation times out every attempt, burns the attempt
|
|
1579
|
+
* budget on a wait that can never converge, and — if any transient
|
|
1580
|
+
* storage/schedule error throws on the way — the one-shot recovery alarm row
|
|
1581
|
+
* is swallowed and deleted with no terminal `onExhausted` (the half-finished
|
|
1582
|
+
* message wedges silently). Excluding it lets `waitUntilStable` converge so
|
|
1583
|
+
* `continueLastTurn` runs, where the existing transcript-repair pass
|
|
1584
|
+
* (`_repairTranscriptForProvider`) flips the orphan to an errored result and
|
|
1585
|
+
* the model proceeds.
|
|
1586
|
+
*/
|
|
1587
|
+
private _partAwaitsClientInteraction;
|
|
1588
|
+
private _resolveChatRecoveryConfig;
|
|
1589
|
+
private _chatRecoveryIncidentId;
|
|
1590
|
+
private _chatRecoveryIncidentKey;
|
|
1591
|
+
/**
|
|
1592
|
+
* Monotonic forward-progress signal for recovery budget resets.
|
|
1593
|
+
*
|
|
1594
|
+
* This used to count assistant messages in `this.messages`, but that is
|
|
1595
|
+
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
1596
|
+
* assistant messages into a summary, lowering the count — so a turn that had
|
|
1597
|
+
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
1598
|
+
* its budget prematurely (#1628). Instead we read a durably-persisted counter
|
|
1599
|
+
* that only ever increments — bumped at production time when new content is
|
|
1600
|
+
* durably flushed (see `_storeChunkDurably`), which is genuine forward
|
|
1601
|
+
* progress and is immune to client reconnects / recovery re-persists — so
|
|
1602
|
+
* compaction can never lower it and a reconnect can't fake it (#1637).
|
|
1603
|
+
*/
|
|
1604
|
+
private _chatRecoveryProgressMarker;
|
|
1605
|
+
/** Advance the durable recovery-progress counter. Called from
|
|
1606
|
+
* `_storeChunkDurably` when new content is durably flushed (real, reconnect-
|
|
1607
|
+
* immune forward progress). */
|
|
1608
|
+
private _bumpChatRecoveryProgress;
|
|
1609
|
+
/** In-memory wall-clock of the last N9 child-stream progress bump (reset per
|
|
1610
|
+
* isolate so the first forwarded chunk after a restart always credits). */
|
|
1611
|
+
private _lastAgentToolStreamProgressAt;
|
|
1612
|
+
/**
|
|
1613
|
+
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
1614
|
+
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
1615
|
+
* whose turn merely `await`s a child banks no progress of its own and its
|
|
1616
|
+
* no-progress window exhausts while the child is healthily streaming. Only
|
|
1617
|
+
* invoked after a child actually produced output (see
|
|
1618
|
+
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
1619
|
+
* Throttled (and reset per isolate) so we never write storage per token.
|
|
1620
|
+
*/
|
|
1621
|
+
protected _onAgentToolStreamProgress(): Promise<void>;
|
|
1622
|
+
/** Sweep recovery incidents that have been inactive past the TTL. */
|
|
1623
|
+
private _sweepStaleChatRecoveryIncidents;
|
|
1624
|
+
private _beginChatRecoveryIncident;
|
|
1625
|
+
private _updateChatRecoveryIncident;
|
|
1626
|
+
private _exhaustChatRecovery;
|
|
1627
|
+
/**
|
|
1628
|
+
* Route a stream-stall watchdog abort into bounded recovery instead of a
|
|
1629
|
+
* terminal error (#1626). A stall happens inside a LIVE isolate (no DO
|
|
1630
|
+
* restart), so the normal restart-detected recovery path never runs — we
|
|
1631
|
+
* open/advance a recovery incident here and schedule a continuation, reusing
|
|
1632
|
+
* the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
|
|
1633
|
+
* as deploy/eviction recovery. A transient hang recovers; a persistently
|
|
1634
|
+
* hanging provider exhausts the budget. Idempotency matches deploy recovery:
|
|
1635
|
+
* settled tool results are durable and won't re-run, but a tool that was
|
|
1636
|
+
* mid-execution when the stall fired re-runs on the continuation.
|
|
1637
|
+
*
|
|
1638
|
+
* Returns:
|
|
1639
|
+
* - `"scheduled"` — a continuation was scheduled; the caller suppresses the
|
|
1640
|
+
* terminal error and closes the stream cleanly.
|
|
1641
|
+
* - `"exhausted"` — the budget is spent; this routes through the SAME
|
|
1642
|
+
* `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
|
|
1643
|
+
* emits `chat:recovery:exhausted`, marks the submission interrupted, and
|
|
1644
|
+
* delivers the configured `terminalMessage`). The caller must NOT run the
|
|
1645
|
+
* generic terminal path — the terminal UX is already delivered.
|
|
1646
|
+
* - `"disabled"` — chat recovery is off; the caller falls through to the
|
|
1647
|
+
* generic terminal error (the watchdog's original "kill the spinner"
|
|
1648
|
+
* behavior, unchanged).
|
|
1649
|
+
*/
|
|
1650
|
+
private _routeStallToBoundedRecovery;
|
|
1651
|
+
protected _handleInternalFiberRecovery(
|
|
1652
|
+
ctx: FiberRecoveryContext
|
|
1653
|
+
): Promise<boolean>;
|
|
1654
|
+
private _recoverablePreStreamUserId;
|
|
1655
|
+
private _hasPersistedRecoveredAssistant;
|
|
1656
|
+
/**
|
|
1657
|
+
* Whether the orphaned stream's partial should be materialized into an
|
|
1658
|
+
* assistant message: there is a stream, and it is either still active or
|
|
1659
|
+
* terminal-but-not-yet-persisted. Shared by the normal recovery path AND the
|
|
1660
|
+
* exhaustion path so neither discards settled work nor duplicates a partial
|
|
1661
|
+
* an earlier attempt already saved.
|
|
1662
|
+
*/
|
|
1663
|
+
private _shouldPersistOrphanedPartial;
|
|
1664
|
+
/** Whether a reconstructed partial carries any settled (provider-accepted)
|
|
1665
|
+
* tool result — the completed, often non-idempotent work that a
|
|
1666
|
+
* `{ persist: false }` recovery return would silently discard. */
|
|
1667
|
+
private _partialHasSettledToolResults;
|
|
1668
|
+
/**
|
|
1669
|
+
* Reschedule a recovery callback that timed out waiting for stable state,
|
|
1670
|
+
* consuming one attempt. Returns `true` if rescheduled, `false` if the
|
|
1671
|
+
* attempt budget is exhausted (the caller then fails the turn terminally).
|
|
1672
|
+
*
|
|
1673
|
+
* Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the
|
|
1674
|
+
* non-idempotent scheduling invariant lives in exactly one place — a fix to
|
|
1675
|
+
* one path can't silently diverge from the other. Mirrors the same helper in
|
|
1676
|
+
* `@cloudflare/ai-chat`.
|
|
1677
|
+
*/
|
|
1678
|
+
private _rescheduleRecoveryAfterStableTimeout;
|
|
1679
|
+
/**
|
|
1680
|
+
* Resolve the stream id for a recovery turn so the give-up terminalization
|
|
1681
|
+
* can surface whatever partial the turn produced. Prefers the durable stream
|
|
1682
|
+
* row keyed by the recovery-root request id; falls back to the live active
|
|
1683
|
+
* stream. Returns `""` when neither is available (the terminal banner still
|
|
1684
|
+
* fires — `_exhaustChatRecovery` does not require a stream).
|
|
1685
|
+
*/
|
|
1686
|
+
private _resolveRecoveryStreamId;
|
|
1687
|
+
/**
|
|
1688
|
+
* Terminalize a recovery turn that is giving up — whether because the
|
|
1689
|
+
* stable-state-timeout retry budget drained, or because the recovery
|
|
1690
|
+
* continuation threw a non-recoverable error — by routing through the SAME
|
|
1691
|
+
* `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
|
|
1692
|
+
* (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
|
|
1693
|
+
* marks the durable submission interrupted, records the terminal chat status,
|
|
1694
|
+
* and delivers the configured `terminalMessage`. `reason` carries the cause
|
|
1695
|
+
* (`stable_timeout` for a budget give-up, `recovery_error` for a thrown
|
|
1696
|
+
* error) through to `onExhausted` / `chat:recovery:exhausted`.
|
|
1697
|
+
*
|
|
1698
|
+
* This replaces the older give-up that only set the incident to `failed` and
|
|
1699
|
+
* completed the recovered submission as `error`, which bypassed
|
|
1700
|
+
* `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
|
|
1701
|
+
* terminal banner regressed to an eternal spinner when recovery gave up under
|
|
1702
|
+
* extreme churn. The error path matters just as much: a non-reset throw in a
|
|
1703
|
+
* recovery callback is SWALLOWED by `Agent._executeScheduleCallback` (only a
|
|
1704
|
+
* code-update reset is re-thrown to preserve the one-shot row), so without
|
|
1705
|
+
* routing it here the alarm row is deleted with no terminal UX at all — the
|
|
1706
|
+
* half-finished message wedges silently. Shared by `_chatRecoveryRetry` and
|
|
1707
|
+
* `_chatRecoveryContinue`.
|
|
1708
|
+
*
|
|
1709
|
+
* Exactly-once terminalization is defended by two independent guards:
|
|
1710
|
+
* 1. The `stored?.status === "exhausted"` re-entry guard below — once an
|
|
1711
|
+
* incident is sealed, a duplicate stale alarm (or retried callback)
|
|
1712
|
+
* returns before re-firing. The sealed incident is re-persisted even when
|
|
1713
|
+
* the record was found missing, so a swept record is re-armed for the
|
|
1714
|
+
* guard on the next alarm.
|
|
1715
|
+
* 2. The durable-submission paths additionally short-circuit earlier at the
|
|
1716
|
+
* `submission_not_running` check (the submission is already `error` after
|
|
1717
|
+
* the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks
|
|
1718
|
+
* (no submission layer), so guard #1 carries it there.
|
|
1719
|
+
*
|
|
1720
|
+
* Two residual at-least-once edges, both deliberately accepted as "deliver a
|
|
1721
|
+
* second banner" ≫ "silently drop the turn":
|
|
1722
|
+
* • No `incidentId` at all in the payload (only reachable via a direct/test
|
|
1723
|
+
* invocation — every production scheduler carries one): the synthesized
|
|
1724
|
+
* incident can't be persisted (no key), so guard #1 can't arm.
|
|
1725
|
+
* • The record is swept AGAIN between two alarms (guard #1 re-persists on the
|
|
1726
|
+
* first, so this needs a second independent sweep) — vanishingly unlikely.
|
|
1727
|
+
*/
|
|
1728
|
+
private _exhaustRecoveryGiveUp;
|
|
1729
|
+
/**
|
|
1730
|
+
* Give-up after the stable-state-timeout retry budget drained. Thin wrapper
|
|
1731
|
+
* over `_exhaustRecoveryGiveUp` so the give-up cause is recorded as
|
|
1732
|
+
* `stable_timeout`.
|
|
1733
|
+
*/
|
|
1734
|
+
private _exhaustRecoveryAfterStableTimeout;
|
|
1735
|
+
/**
|
|
1736
|
+
* Whether an error is a transient "superseded isolate" failure — a deploy /
|
|
1737
|
+
* code update replaced the isolate mid-invocation. Mirrors the base `Agent`
|
|
1738
|
+
* check (`isDurableObjectCodeUpdateReset`) and MUST stay in lockstep with it:
|
|
1739
|
+
* the base `_executeScheduleCallback` re-throws this class for a one-shot row
|
|
1740
|
+
* (preserving it so the platform re-runs on the new code), so a recovery
|
|
1741
|
+
* callback must also re-throw — NOT terminalize — since recovery will re-run
|
|
1742
|
+
* and succeed on the fresh isolate. The matched family (kept identical to the
|
|
1743
|
+
* base):
|
|
1744
|
+
* - "Durable Object reset because its code was updated." (deploy bounce)
|
|
1745
|
+
* - "This script has been upgraded. Please send a new request to connect to
|
|
1746
|
+
* the new version." (a stub/connection to a superseded script)
|
|
1747
|
+
* "Network connection lost." is intentionally excluded (a connection error,
|
|
1748
|
+
* not an isolate replacement — see the base helper's note). The match stays
|
|
1749
|
+
* close to the verbatim platform strings so an ordinary error mentioning
|
|
1750
|
+
* those words isn't misclassified as a supersede.
|
|
1751
|
+
*/
|
|
1752
|
+
private _isDeployCodeUpdateReset;
|
|
1753
|
+
/**
|
|
1754
|
+
* Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
|
|
1755
|
+
* after the incident was opened.
|
|
1756
|
+
*
|
|
1757
|
+
* - A deploy code-update reset is re-thrown (after marking the incident
|
|
1758
|
+
* `failed` for observability) so `Agent._executeScheduleCallback` preserves
|
|
1759
|
+
* the one-shot alarm row and the platform re-runs recovery on the fresh
|
|
1760
|
+
* isolate — the turn can still recover, so it must NOT terminalize.
|
|
1761
|
+
* - Any OTHER error is terminalized through the give-up path
|
|
1762
|
+
* (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
|
|
1763
|
+
* the fix for the silent-seal failure mode: `_executeScheduleCallback`
|
|
1764
|
+
* swallows a non-reset throw and then `alarm()` deletes the one-shot row, so
|
|
1765
|
+
* without terminalizing here the half-finished turn is dropped with no
|
|
1766
|
+
* terminal event and no banner (the user stares at a frozen message until
|
|
1767
|
+
* they send something new).
|
|
1768
|
+
*/
|
|
1769
|
+
private _handleRecoveryCallbackError;
|
|
1770
|
+
_chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
|
|
1771
|
+
private _hasRunningSubmission;
|
|
1772
|
+
private _readRunningSubmissionByRequestId;
|
|
1773
|
+
private _markRecoveredSubmissionInterrupted;
|
|
1774
|
+
private _completeRecoveredSubmission;
|
|
1775
|
+
protected onChatRecovery(
|
|
1776
|
+
_ctx: ChatRecoveryContext
|
|
1777
|
+
): Promise<ChatRecoveryOptions | void>;
|
|
1778
|
+
_chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
|
|
1779
|
+
private _applyRecoveredRequestContext;
|
|
1780
|
+
private _getPartialStreamText;
|
|
1781
|
+
private _getSubmitConcurrencyDecision;
|
|
1782
|
+
private _completeSkippedRequest;
|
|
1783
|
+
private _rollbackDroppedSubmit;
|
|
1784
|
+
private _scheduleAutoContinuation;
|
|
1785
|
+
private _resetAutoContinuationTimer;
|
|
1786
|
+
/**
|
|
1787
|
+
* Fire an auto-continuation, but only once the model's parallel tool-call
|
|
1788
|
+
* batch is fully answered (#1649). When the model emits several tool calls in
|
|
1789
|
+
* one step the client answers each independently, so the first `autoContinue`
|
|
1790
|
+
* arrives while slower siblings are still `input-available`. Continuing then
|
|
1791
|
+
* would feed the provider an incomplete tool-result set
|
|
1792
|
+
* (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
|
|
1793
|
+
* error the in-flight sibling and run a spurious extra continuation. We hold
|
|
1794
|
+
* the continuation on a barrier until the batch settles. The wait is bounded
|
|
1795
|
+
* (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
|
|
1796
|
+
* call — e.g. the client disconnected mid-batch — still falls through to the
|
|
1797
|
+
* repair backstop rather than pinning the continuation open forever.
|
|
1798
|
+
*/
|
|
1799
|
+
private _fireAutoContinuationWhenStable;
|
|
1800
|
+
/**
|
|
1801
|
+
* Block until the latest assistant step's parallel tool batch is fully
|
|
1802
|
+
* answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
|
|
1803
|
+
* in-flight tool-result apply when one exists (so a sibling that lands
|
|
1804
|
+
* mid-wait is observed promptly) and polls otherwise.
|
|
1805
|
+
*/
|
|
1806
|
+
private _awaitToolBatch;
|
|
1807
|
+
/**
|
|
1808
|
+
* `true` when the latest assistant message is mid-batch: it carries at least
|
|
1809
|
+
* one settled tool result AND at least one tool call/approval still awaiting a
|
|
1810
|
+
* client result. That is the #1649 signature — the model fanned out parallel
|
|
1811
|
+
* tool calls and only some have been answered. Scoped to the leaf (the step
|
|
1812
|
+
* the continuation answers) so an unrelated dangling tool in an earlier
|
|
1813
|
+
* message doesn't block a legitimate follow-up continuation.
|
|
1814
|
+
*/
|
|
1815
|
+
private _hasIncompleteToolBatch;
|
|
1816
|
+
private _fireAutoContinuation;
|
|
1817
|
+
private _activateDeferredContinuation;
|
|
1818
|
+
private _fireResponseHook;
|
|
1819
|
+
/**
|
|
1820
|
+
* Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
|
|
1821
|
+
* the last terminal turn so it can be replayed to clients on connect. A
|
|
1822
|
+
* `completed`/`aborted` turn is conveyed by the persisted messages, so the
|
|
1823
|
+
* record is cleared; an `error`/`interrupted` turn has no durable trace
|
|
1824
|
+
* otherwise, so it is kept until a later turn resolves.
|
|
1825
|
+
*/
|
|
1826
|
+
private _recordTerminalChatStatus;
|
|
1827
|
+
private _pendingTerminalChatResponse;
|
|
1828
|
+
/**
|
|
1829
|
+
* Set or clear the live "recovering…" status for a durable chat turn (#1620).
|
|
1830
|
+
* Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
|
|
1831
|
+
* and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
|
|
1832
|
+
* transition, so a deploy/reconnect storm (which re-detects recovery many
|
|
1833
|
+
* times) doesn't spam the wire. Cleared on every terminal outcome so the
|
|
1834
|
+
* indicator can't spin forever.
|
|
1835
|
+
*/
|
|
1836
|
+
private _setChatRecovering;
|
|
1837
|
+
/**
|
|
1838
|
+
* Messages sent to a client on connect when no stream is active: the current
|
|
1839
|
+
* transcript, plus a replay of the last terminal error (if any) so a turn
|
|
1840
|
+
* that failed while the client was disconnected is surfaced rather than
|
|
1841
|
+
* silently frozen.
|
|
1842
|
+
*/
|
|
1843
|
+
private _buildIdleConnectMessages;
|
|
1844
|
+
private _notifyStreamResuming;
|
|
1845
|
+
private _persistOrphanedStream;
|
|
1846
|
+
private _broadcastChat;
|
|
1847
|
+
private _broadcast;
|
|
1848
|
+
private _broadcastMessages;
|
|
1849
|
+
}
|
|
1850
|
+
//#endregion
|
|
1851
|
+
//#region src/messengers/events.d.ts
|
|
1852
|
+
type MessengerEventKind =
|
|
1853
|
+
| "direct-message"
|
|
1854
|
+
| "mention"
|
|
1855
|
+
| "subscribed-message"
|
|
1856
|
+
| "action"
|
|
1857
|
+
| "delivery-event";
|
|
1858
|
+
interface MessengerAuthor {
|
|
1859
|
+
fullName?: string;
|
|
1860
|
+
isBot?: boolean | "unknown";
|
|
1861
|
+
isMe?: boolean;
|
|
1862
|
+
userId: string;
|
|
1863
|
+
userName?: string;
|
|
1864
|
+
}
|
|
1865
|
+
interface MessengerAttachment {
|
|
1866
|
+
data?: ArrayBuffer;
|
|
1867
|
+
fetch?: () => Promise<ArrayBuffer>;
|
|
1868
|
+
id?: string;
|
|
1869
|
+
mediaType?: string;
|
|
1870
|
+
name?: string;
|
|
1871
|
+
raw?: unknown;
|
|
1872
|
+
size?: number;
|
|
1873
|
+
text?: string;
|
|
1874
|
+
url?: string;
|
|
1875
|
+
}
|
|
1876
|
+
interface MessengerThread {
|
|
1877
|
+
channelId?: string;
|
|
1878
|
+
channelName?: string;
|
|
1879
|
+
id: string;
|
|
1880
|
+
isDirectMessage: boolean;
|
|
1881
|
+
providerThreadId: string;
|
|
1882
|
+
title?: string;
|
|
1883
|
+
}
|
|
1884
|
+
interface MessengerMessage {
|
|
1885
|
+
attachments: MessengerAttachment[];
|
|
1886
|
+
author: MessengerAuthor;
|
|
1887
|
+
createdAt?: Date;
|
|
1888
|
+
id: string;
|
|
1889
|
+
isMention?: boolean;
|
|
1890
|
+
providerMessageId: string;
|
|
1891
|
+
raw?: unknown;
|
|
1892
|
+
text: string;
|
|
1893
|
+
}
|
|
1894
|
+
interface MessengerAction {
|
|
1895
|
+
actionId: string;
|
|
1896
|
+
messageId?: string;
|
|
1897
|
+
raw?: unknown;
|
|
1898
|
+
user?: MessengerAuthor;
|
|
1899
|
+
value?: string;
|
|
1900
|
+
}
|
|
1901
|
+
interface MessengerCapabilities {
|
|
1902
|
+
canEditMessages?: boolean;
|
|
1903
|
+
canStream?: boolean;
|
|
1904
|
+
maxMessageLength?: number;
|
|
1905
|
+
supportsActions?: boolean;
|
|
1906
|
+
supportsAttachments?: boolean;
|
|
1907
|
+
supportsEphemeral?: boolean;
|
|
1908
|
+
}
|
|
1909
|
+
interface MessengerContext {
|
|
1910
|
+
action?: MessengerAction;
|
|
1911
|
+
author?: MessengerAuthor;
|
|
1912
|
+
capabilities: MessengerCapabilities;
|
|
1913
|
+
kind: MessengerEventKind;
|
|
1914
|
+
message?: MessengerMessage;
|
|
1915
|
+
messengerId: string;
|
|
1916
|
+
provider: string;
|
|
1917
|
+
thread: MessengerThread;
|
|
1918
|
+
}
|
|
1919
|
+
interface MessengerEvent extends MessengerContext {
|
|
1920
|
+
raw?: unknown;
|
|
1921
|
+
}
|
|
1922
|
+
declare function messengerContextFromEvent(
|
|
1923
|
+
event: MessengerEvent
|
|
1924
|
+
): MessengerContext;
|
|
1925
|
+
declare function serializableMessengerEvent(
|
|
1926
|
+
event: MessengerEvent
|
|
1927
|
+
): MessengerEvent;
|
|
1928
|
+
declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
|
|
1929
|
+
//#endregion
|
|
1930
|
+
//#region src/messengers/delivery.d.ts
|
|
1931
|
+
declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
|
|
1932
|
+
declare const EMPTY_MESSENGER_RESPONSE =
|
|
1933
|
+
"I couldn't produce a text response. Please try again.";
|
|
1934
|
+
declare const ERROR_MESSENGER_RESPONSE =
|
|
1935
|
+
"Sorry, I couldn't answer that right now. Please try again.";
|
|
1936
|
+
declare const INTERRUPTED_MESSENGER_RESPONSE =
|
|
1937
|
+
"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
|
|
1938
|
+
interface TextStreamCallbackOptions {
|
|
1939
|
+
onVisibleStart?: () => Promise<void> | void;
|
|
1940
|
+
visibleSoftLimit?: number;
|
|
1941
|
+
}
|
|
1942
|
+
declare class TextStreamCallback extends RpcTarget implements StreamCallback {
|
|
1943
|
+
private readonly onVisibleStart?;
|
|
1944
|
+
private readonly visibleChunks;
|
|
1945
|
+
private readonly wakeups;
|
|
1946
|
+
private readonly visibleSoftLimit?;
|
|
1947
|
+
private chatRequestId?;
|
|
1948
|
+
private closed;
|
|
1949
|
+
private interrupted;
|
|
1950
|
+
private error?;
|
|
1951
|
+
private text;
|
|
1952
|
+
private visibleClosed;
|
|
1953
|
+
private visibleLimitReachedValue;
|
|
1954
|
+
private visibleStarted;
|
|
1955
|
+
private visibleTextValue;
|
|
1956
|
+
constructor(options?: TextStreamCallbackOptions);
|
|
1957
|
+
onStart(event: ChatStartEvent): void;
|
|
1958
|
+
onEvent(json: string): void;
|
|
1959
|
+
onDone(): void;
|
|
1960
|
+
onError(error: string): void;
|
|
1961
|
+
onInterrupted(): void;
|
|
1962
|
+
wasInterrupted(): boolean;
|
|
1963
|
+
close(): void;
|
|
1964
|
+
fail(error: unknown): void;
|
|
1965
|
+
hasText(): boolean;
|
|
1966
|
+
remainingText(): string;
|
|
1967
|
+
requestId(): string | undefined;
|
|
1968
|
+
textSoFar(): string;
|
|
1969
|
+
visibleLimitReached(): boolean;
|
|
1970
|
+
visibleText(): string;
|
|
1971
|
+
stream(): AsyncIterable<string>;
|
|
1972
|
+
private pushVisibleText;
|
|
1973
|
+
private wake;
|
|
1974
|
+
private markVisibleStarted;
|
|
1975
|
+
}
|
|
1976
|
+
declare function textDeltaFromStreamChunk(json: string): string | null;
|
|
1977
|
+
type MessengerReplyStage = "accepted" | "streaming" | "completed";
|
|
1978
|
+
interface MessengerReplySnapshot {
|
|
1979
|
+
event: MessengerEvent;
|
|
1980
|
+
stage: MessengerReplyStage;
|
|
1981
|
+
thread?: unknown;
|
|
1982
|
+
type: typeof MESSENGER_REPLY_FIBER_NAME;
|
|
1983
|
+
}
|
|
1984
|
+
declare function messengerReplySnapshot(
|
|
1985
|
+
stage: MessengerReplyStage,
|
|
1986
|
+
event: MessengerEvent,
|
|
1987
|
+
thread?: unknown
|
|
1988
|
+
): MessengerReplySnapshot;
|
|
1989
|
+
declare function parseMessengerReplySnapshot(
|
|
1990
|
+
snapshot: unknown
|
|
1991
|
+
): MessengerReplySnapshot | null;
|
|
1992
|
+
declare function messengerReplyRecoveryMode(
|
|
1993
|
+
snapshot: MessengerReplySnapshot
|
|
1994
|
+
): "answer" | "apologize" | null;
|
|
1995
|
+
declare function messengerReplyFailureMode(
|
|
1996
|
+
hasStreamedText: boolean,
|
|
1997
|
+
completedModelTurn?: boolean,
|
|
1998
|
+
expectedDeliveryCompletion?: boolean
|
|
1999
|
+
): "apologize" | "error" | null;
|
|
2000
|
+
interface MessengerDeliveryTarget {
|
|
2001
|
+
cancelChat(
|
|
2002
|
+
requestId: string,
|
|
2003
|
+
reason?: string
|
|
2004
|
+
): boolean | void | Promise<boolean | void>;
|
|
2005
|
+
chat(
|
|
2006
|
+
userMessage: string | UIMessage,
|
|
2007
|
+
callback: StreamCallback
|
|
2008
|
+
): Promise<void>;
|
|
2009
|
+
chatWithMessengerContext?(
|
|
2010
|
+
userMessage: string | UIMessage,
|
|
2011
|
+
callback: StreamCallback,
|
|
2012
|
+
context: MessengerEvent
|
|
2013
|
+
): Promise<void>;
|
|
2014
|
+
}
|
|
2015
|
+
interface MessengerDeliverySurface {
|
|
2016
|
+
post(
|
|
2017
|
+
message:
|
|
2018
|
+
| string
|
|
2019
|
+
| {
|
|
2020
|
+
markdown: string;
|
|
2021
|
+
}
|
|
2022
|
+
| AsyncIterable<string>
|
|
2023
|
+
): Promise<unknown>;
|
|
2024
|
+
startTyping?(status?: string): Promise<void>;
|
|
2025
|
+
}
|
|
2026
|
+
interface MessengerDeliveryPolicy {
|
|
2027
|
+
emptyResponseText?: string;
|
|
2028
|
+
errorResponseText?: string;
|
|
2029
|
+
interruptedResponseText?: string;
|
|
2030
|
+
isExpectedDeliveryCompletion?(
|
|
2031
|
+
error: unknown,
|
|
2032
|
+
callback: TextStreamCallback
|
|
2033
|
+
): boolean;
|
|
2034
|
+
splitText?(text: string): string[];
|
|
2035
|
+
visibleSoftLimit?: number;
|
|
2036
|
+
}
|
|
2037
|
+
interface DeliverMessengerReplyOptions {
|
|
2038
|
+
checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
|
|
2039
|
+
event: MessengerEvent;
|
|
2040
|
+
fiber?: FiberContext;
|
|
2041
|
+
policy?: MessengerDeliveryPolicy;
|
|
2042
|
+
snapshotEvent?: MessengerEvent;
|
|
2043
|
+
snapshotThread?: unknown;
|
|
2044
|
+
surface: MessengerDeliverySurface;
|
|
2045
|
+
target: MessengerDeliveryTarget;
|
|
2046
|
+
userMessage?: UIMessage;
|
|
2047
|
+
}
|
|
2048
|
+
declare function deliverMessengerReply(
|
|
2049
|
+
options: DeliverMessengerReplyOptions
|
|
2050
|
+
): Promise<void>;
|
|
2051
|
+
//#endregion
|
|
2052
|
+
//#region src/messengers/chat-sdk.d.ts
|
|
2053
|
+
declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
|
|
2054
|
+
type MessengerRespondTo =
|
|
2055
|
+
| "action"
|
|
2056
|
+
| "direct-message"
|
|
2057
|
+
| "mention"
|
|
2058
|
+
| "subscribed-thread";
|
|
2059
|
+
type MessengerConversationMode = "self" | "thread";
|
|
2060
|
+
type MessengerConversationTarget =
|
|
2061
|
+
| {
|
|
2062
|
+
target: "self";
|
|
2063
|
+
}
|
|
2064
|
+
| {
|
|
2065
|
+
agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
|
|
2066
|
+
name: string;
|
|
2067
|
+
target: "subagent";
|
|
2068
|
+
};
|
|
2069
|
+
type MessengerConversationResolver = (
|
|
2070
|
+
event: MessengerEvent
|
|
2071
|
+
) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
|
|
2072
|
+
interface MessengerDefinition {
|
|
2073
|
+
adapter: Adapter;
|
|
2074
|
+
adapterName: string;
|
|
2075
|
+
capabilities?: MessengerCapabilities;
|
|
2076
|
+
conversation?: MessengerConversationMode | MessengerConversationResolver;
|
|
2077
|
+
delivery?: MessengerDeliveryPolicy;
|
|
2078
|
+
keyShard?: ChatSdkStateAdapterOptions["keyShard"];
|
|
2079
|
+
path?: string;
|
|
2080
|
+
provider: string;
|
|
2081
|
+
respondTo?: readonly MessengerRespondTo[];
|
|
2082
|
+
shardKey?: ChatSdkStateAdapterOptions["shardKey"];
|
|
2083
|
+
subscribeOnMention?: boolean;
|
|
2084
|
+
toEvent?: (
|
|
2085
|
+
input: ChatSdkMessengerEventInput
|
|
2086
|
+
) => MessengerEvent | Promise<MessengerEvent>;
|
|
2087
|
+
userName: string;
|
|
2088
|
+
verifyWebhook?:
|
|
2089
|
+
| false
|
|
2090
|
+
| ((request: Request) => boolean | Response | Promise<boolean | Response>);
|
|
2091
|
+
}
|
|
2092
|
+
type ThinkMessengers = Record<string, MessengerDefinition>;
|
|
2093
|
+
interface NormalizedMessengerDefinition extends MessengerDefinition {
|
|
2094
|
+
id: string;
|
|
2095
|
+
path: string;
|
|
2096
|
+
respondTo: readonly MessengerRespondTo[];
|
|
2097
|
+
subscribeOnMention: boolean;
|
|
2098
|
+
verifyWebhook:
|
|
2099
|
+
| false
|
|
2100
|
+
| ((request: Request) => boolean | Response | Promise<boolean | Response>);
|
|
2101
|
+
}
|
|
2102
|
+
interface ChatSdkMessengerOptions extends Omit<
|
|
2103
|
+
MessengerDefinition,
|
|
2104
|
+
"adapterName"
|
|
2105
|
+
> {
|
|
2106
|
+
adapterName?: string;
|
|
2107
|
+
}
|
|
2108
|
+
interface ChatSdkMessengerEventInput {
|
|
2109
|
+
action?: ActionEvent;
|
|
2110
|
+
eventKind: MessengerEventKind;
|
|
2111
|
+
message?: Message;
|
|
2112
|
+
raw?: unknown;
|
|
2113
|
+
thread: Thread;
|
|
2114
|
+
}
|
|
2115
|
+
interface MessengerThinkTarget {
|
|
2116
|
+
cancelChat(
|
|
2117
|
+
requestId: string,
|
|
2118
|
+
reason?: string
|
|
2119
|
+
): boolean | void | Promise<boolean | void>;
|
|
2120
|
+
chat(
|
|
2121
|
+
userMessage: string | UIMessage,
|
|
2122
|
+
callback: StreamCallback
|
|
2123
|
+
): Promise<void>;
|
|
2124
|
+
chatWithMessengerContext?(
|
|
2125
|
+
userMessage: string | UIMessage,
|
|
2126
|
+
callback: StreamCallback,
|
|
2127
|
+
context: MessengerEvent
|
|
2128
|
+
): Promise<void>;
|
|
2129
|
+
}
|
|
2130
|
+
interface MessengerThinkHost extends MessengerThinkTarget {
|
|
2131
|
+
constructor: {
|
|
2132
|
+
name: string;
|
|
2133
|
+
};
|
|
2134
|
+
name: string;
|
|
2135
|
+
parentPath: ReadonlyArray<{
|
|
2136
|
+
className: string;
|
|
2137
|
+
name: string;
|
|
2138
|
+
}>;
|
|
2139
|
+
startFiber(
|
|
2140
|
+
name: string,
|
|
2141
|
+
fn: (ctx: FiberContext) => Promise<void>,
|
|
2142
|
+
options?: StartFiberOptions
|
|
2143
|
+
): Promise<MessengerFiberStartResult>;
|
|
2144
|
+
resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
|
|
2145
|
+
subAgent<T extends Agent>(
|
|
2146
|
+
agentClass: SubAgentClass<T>,
|
|
2147
|
+
name: string
|
|
2148
|
+
): Promise<SubAgentStub<T>>;
|
|
2149
|
+
}
|
|
2150
|
+
interface MessengerFiberStartResult {
|
|
2151
|
+
accepted: boolean;
|
|
2152
|
+
fiberId: string;
|
|
2153
|
+
snapshot?: unknown;
|
|
2154
|
+
status: string;
|
|
2155
|
+
}
|
|
2156
|
+
declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
|
|
2157
|
+
declare function chatSdkMessenger(
|
|
2158
|
+
options: ChatSdkMessengerOptions
|
|
2159
|
+
): MessengerDefinition;
|
|
2160
|
+
declare class ThinkMessengerRuntime {
|
|
2161
|
+
private readonly host;
|
|
2162
|
+
private chat?;
|
|
2163
|
+
private readonly definitionsByAdapterName;
|
|
2164
|
+
private readonly definitionsById;
|
|
2165
|
+
private readonly definitions;
|
|
2166
|
+
constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
|
|
2167
|
+
get size(): number;
|
|
2168
|
+
initialize(): void;
|
|
2169
|
+
handleRequest(request: Request): Promise<Response | undefined>;
|
|
2170
|
+
handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
|
|
2171
|
+
private createChat;
|
|
2172
|
+
private enqueueReply;
|
|
2173
|
+
private answer;
|
|
2174
|
+
private resolveTarget;
|
|
2175
|
+
private definitionForThread;
|
|
2176
|
+
private definitionForThreadId;
|
|
2177
|
+
private hasUniqueProvider;
|
|
2178
|
+
private shardThread;
|
|
2179
|
+
private shardStateKey;
|
|
2180
|
+
private reviveChatObject;
|
|
2181
|
+
private toEvent;
|
|
2182
|
+
}
|
|
2183
|
+
declare function normalizeMessengers(
|
|
2184
|
+
messengers: ThinkMessengers
|
|
2185
|
+
): NormalizedMessengerDefinition[];
|
|
2186
|
+
declare function defaultConversationName(event: MessengerEvent): string;
|
|
2187
|
+
declare function idempotencyKeyForEvent(event: MessengerEvent): string;
|
|
2188
|
+
declare function defaultChatSdkEvent(
|
|
2189
|
+
definition: NormalizedMessengerDefinition,
|
|
2190
|
+
input: ChatSdkMessengerEventInput
|
|
2191
|
+
): MessengerEvent;
|
|
2192
|
+
declare function toMessengerThread(thread: Thread): MessengerThread;
|
|
2193
|
+
declare function toMessengerMessage(message: Message): MessengerMessage;
|
|
2194
|
+
declare function toMessengerAuthor(author: Author): MessengerAuthor;
|
|
2195
|
+
declare function toMessengerAttachment(
|
|
2196
|
+
attachment: Attachment
|
|
2197
|
+
): MessengerAttachment;
|
|
2198
|
+
//#endregion
|
|
2199
|
+
export {
|
|
2200
|
+
toMessengerUserMessage as $,
|
|
2201
|
+
defineScheduledTasks as $t,
|
|
2202
|
+
MessengerDeliverySurface as A,
|
|
2203
|
+
StreamableResult as At,
|
|
2204
|
+
parseMessengerReplySnapshot as B,
|
|
2205
|
+
ThinkSubmissionInspection as Bt,
|
|
2206
|
+
toMessengerThread as C,
|
|
2207
|
+
SkillRunContext as Ct,
|
|
2208
|
+
INTERRUPTED_MESSENGER_RESPONSE as D,
|
|
2209
|
+
StepResult as Dt,
|
|
2210
|
+
ERROR_MESSENGER_RESPONSE as E,
|
|
2211
|
+
StepContext as Et,
|
|
2212
|
+
TextStreamCallbackOptions as F,
|
|
2213
|
+
ThinkIntervalSchedule as Ft,
|
|
2214
|
+
MessengerCapabilities as G,
|
|
2215
|
+
ToolCallDecision as Gt,
|
|
2216
|
+
MessengerAction as H,
|
|
2217
|
+
ThinkTime as Ht,
|
|
2218
|
+
deliverMessengerReply as I,
|
|
2219
|
+
ThinkScheduledTask as It,
|
|
2220
|
+
MessengerEventKind as J,
|
|
2221
|
+
TurnContext as Jt,
|
|
2222
|
+
MessengerContext as K,
|
|
2223
|
+
ToolCallResultContext as Kt,
|
|
2224
|
+
messengerReplyFailureMode as L,
|
|
2225
|
+
ThinkScheduledTaskContext as Lt,
|
|
2226
|
+
MessengerReplySnapshot as M,
|
|
2227
|
+
SubmitMessagesResult as Mt,
|
|
2228
|
+
MessengerReplyStage as N,
|
|
2229
|
+
TextStreamPart as Nt,
|
|
2230
|
+
MESSENGER_REPLY_FIBER_NAME as O,
|
|
2231
|
+
StopCondition$1 as Ot,
|
|
2232
|
+
TextStreamCallback as P,
|
|
2233
|
+
Think as Pt,
|
|
2234
|
+
serializableMessengerEvent as Q,
|
|
2235
|
+
Workspace$1 as Qt,
|
|
2236
|
+
messengerReplyRecoveryMode as R,
|
|
2237
|
+
ThinkScheduledTaskSchedule as Rt,
|
|
2238
|
+
toMessengerMessage as S,
|
|
2239
|
+
Session$1 as St,
|
|
2240
|
+
EMPTY_MESSENGER_RESPONSE as T,
|
|
2241
|
+
StepConfig as Tt,
|
|
2242
|
+
MessengerAttachment as U,
|
|
2243
|
+
ThinkWallClockSchedule as Ut,
|
|
2244
|
+
textDeltaFromStreamChunk as V,
|
|
2245
|
+
ThinkSubmissionStatus as Vt,
|
|
2246
|
+
MessengerAuthor as W,
|
|
2247
|
+
ToolCallContext as Wt,
|
|
2248
|
+
MessengerThread as X,
|
|
2249
|
+
TypedToolCall$1 as Xt,
|
|
2250
|
+
MessengerMessage as Y,
|
|
2251
|
+
TurnInput as Yt,
|
|
2252
|
+
messengerContextFromEvent as Z,
|
|
2253
|
+
TypedToolResult as Zt,
|
|
2254
|
+
defineMessengers as _,
|
|
2255
|
+
PrepareStepFunction$1 as _t,
|
|
2256
|
+
MessengerConversationTarget as a,
|
|
2257
|
+
ChatRecoveryOptions$1 as at,
|
|
2258
|
+
toMessengerAttachment as b,
|
|
2259
|
+
SaveMessagesOptions$1 as bt,
|
|
2260
|
+
MessengerThinkHost as c,
|
|
2261
|
+
ChunkContext as ct,
|
|
2262
|
+
ThinkMessengerRuntime as d,
|
|
2263
|
+
ExtensionConfig as dt,
|
|
2264
|
+
skills as en,
|
|
2265
|
+
ChatErrorContext as et,
|
|
2266
|
+
ThinkMessengerStateAgent as f,
|
|
2267
|
+
FiberContext$1 as ft,
|
|
2268
|
+
defaultConversationName as g,
|
|
2269
|
+
PrepareStepContext as gt,
|
|
2270
|
+
defaultChatSdkEvent as h,
|
|
2271
|
+
MessageConcurrency$1 as ht,
|
|
2272
|
+
MessengerConversationResolver as i,
|
|
2273
|
+
ChatRecoveryExhaustedContext as it,
|
|
2274
|
+
MessengerDeliveryTarget as j,
|
|
2275
|
+
SubmitMessagesOptions as jt,
|
|
2276
|
+
MessengerDeliveryPolicy as k,
|
|
2277
|
+
StreamCallback as kt,
|
|
2278
|
+
MessengerThinkTarget as l,
|
|
2279
|
+
ChunkPart as lt,
|
|
2280
|
+
chatSdkMessenger as m,
|
|
2281
|
+
ListSubmissionsOptions as mt,
|
|
2282
|
+
ChatSdkMessengerOptions as n,
|
|
2283
|
+
ChatRecoveryConfig$1 as nt,
|
|
2284
|
+
MessengerDefinition as o,
|
|
2285
|
+
ChatResponseResult$1 as ot,
|
|
2286
|
+
ThinkMessengers as p,
|
|
2287
|
+
FiberRecoveryContext$1 as pt,
|
|
2288
|
+
MessengerEvent as q,
|
|
2289
|
+
TurnConfig as qt,
|
|
2290
|
+
MessengerConversationMode as r,
|
|
2291
|
+
ChatRecoveryContext$1 as rt,
|
|
2292
|
+
MessengerRespondTo as s,
|
|
2293
|
+
ChatStartEvent as st,
|
|
2294
|
+
ChatSdkMessengerEventInput as t,
|
|
2295
|
+
ChatOptions as tt,
|
|
2296
|
+
NormalizedMessengerDefinition as u,
|
|
2297
|
+
DeleteSubmissionsOptions as ut,
|
|
2298
|
+
idempotencyKeyForEvent as v,
|
|
2299
|
+
PrepareStepResult$1 as vt,
|
|
2300
|
+
DeliverMessengerReplyOptions as w,
|
|
2301
|
+
SkillSource$1 as wt,
|
|
2302
|
+
toMessengerAuthor as x,
|
|
2303
|
+
SaveMessagesResult$1 as xt,
|
|
2304
|
+
normalizeMessengers as y,
|
|
2305
|
+
ResolvedChatRecoveryConfig as yt,
|
|
2306
|
+
messengerReplySnapshot as z,
|
|
2307
|
+
ThinkScheduledTasks as zt
|
|
2308
|
+
};
|
|
2309
|
+
//# sourceMappingURL=index-DpPdyY46.d.ts.map
|