@cloudflare/think 0.8.5 → 0.8.6
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 +32 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +316 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/cli.d.ts +77 -0
- package/dist/cli.js +8 -0
- package/dist/cli.js.map +1 -0
- package/dist/codegen-CauNNguA.js +140 -0
- package/dist/codegen-CauNNguA.js.map +1 -0
- package/dist/config-D512sQYg.d.ts +71 -0
- package/dist/framework/index.d.ts +215 -0
- package/dist/framework/index.js +58 -0
- package/dist/framework/index.js.map +1 -0
- package/dist/init-C9q1GbK-.js +361 -0
- package/dist/init-C9q1GbK-.js.map +1 -0
- package/dist/manifest-CpB-xngB.d.ts +143 -0
- package/dist/messengers/index.d.ts +54 -54
- package/dist/messengers/telegram.d.ts +4 -4
- package/dist/project-D1o1-3dN.js +685 -0
- package/dist/project-D1o1-3dN.js.map +1 -0
- package/dist/server-entry.d.ts +118 -0
- package/dist/server-entry.js +265 -0
- package/dist/server-entry.js.map +1 -0
- package/dist/{index-BzPfnYMr.d.ts → think-8jik2oZ5.d.ts} +1296 -1296
- package/dist/think.d.ts +2 -123
- package/dist/types-codegen-B6c5KpYH.js +125 -0
- package/dist/types-codegen-B6c5KpYH.js.map +1 -0
- package/dist/vite.d.ts +39 -0
- package/dist/vite.js +121 -0
- package/dist/vite.js.map +1 -0
- package/dist/workflows.d.ts +1 -1
- package/package.json +34 -4
|
@@ -82,889 +82,1237 @@ import {
|
|
|
82
82
|
import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
|
|
83
83
|
import { RpcTarget } from "cloudflare:workers";
|
|
84
84
|
|
|
85
|
-
//#region src/
|
|
86
|
-
type
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
lastBody?: Record<string, unknown> | null;
|
|
99
|
-
lastClientTools?: ClientToolSchema[] | null;
|
|
100
|
-
recoveredRequestId?: string;
|
|
101
|
-
};
|
|
102
|
-
/**
|
|
103
|
-
* Callback interface for streaming chat events from a Think sub-agent.
|
|
104
|
-
*
|
|
105
|
-
* Designed to work across the sub-agent RPC boundary — implement as
|
|
106
|
-
* an RpcTarget in the parent agent and pass to `chat()`.
|
|
107
|
-
*/
|
|
108
|
-
interface ChatStartEvent {
|
|
109
|
-
requestId: string;
|
|
85
|
+
//#region src/messengers/events.d.ts
|
|
86
|
+
type MessengerEventKind =
|
|
87
|
+
| "direct-message"
|
|
88
|
+
| "mention"
|
|
89
|
+
| "subscribed-message"
|
|
90
|
+
| "action"
|
|
91
|
+
| "delivery-event";
|
|
92
|
+
interface MessengerAuthor {
|
|
93
|
+
fullName?: string;
|
|
94
|
+
isBot?: boolean | "unknown";
|
|
95
|
+
isMe?: boolean;
|
|
96
|
+
userId: string;
|
|
97
|
+
userName?: string;
|
|
110
98
|
}
|
|
111
|
-
interface
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
* this callback — will produce the answer (delivered to other channels,
|
|
122
|
-
* e.g. WebSocket connections), OR
|
|
123
|
-
* - the recovery budget was exhausted, so the turn was already terminalized
|
|
124
|
-
* out-of-band (the configured `terminalMessage` + `onExhausted`) and is
|
|
125
|
-
* terminally over — there is NO continuation to come.
|
|
126
|
-
*
|
|
127
|
-
* This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
|
|
128
|
-
* raw stall is not surfaced as a terminal error here); without it the contract
|
|
129
|
-
* `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
|
|
130
|
-
* consumer that treats the clean resolve as success finalizes a truncated
|
|
131
|
-
* partial.
|
|
132
|
-
*
|
|
133
|
-
* Consumers should AVOID finalizing the partial on this signal — surface a
|
|
134
|
-
* "recovering…" / "interrupted, please retry" state, or re-attach via a
|
|
135
|
-
* durable channel — but must ALSO NOT block indefinitely waiting for a
|
|
136
|
-
* continuation: per the exhausted case above, one may never come. Optional →
|
|
137
|
-
* defaults to a no-op, so this is fully backward-compatible.
|
|
138
|
-
*
|
|
139
|
-
* Note: a deploy/eviction interruption kills the isolate (and this callback)
|
|
140
|
-
* before this can fire — the caller observes a transport break instead. This
|
|
141
|
-
* fires only for an in-isolate interruption (the stall→recovery path).
|
|
142
|
-
*/
|
|
143
|
-
onInterrupted?(): void | Promise<void>;
|
|
99
|
+
interface MessengerAttachment {
|
|
100
|
+
data?: ArrayBuffer;
|
|
101
|
+
fetch?: () => Promise<ArrayBuffer>;
|
|
102
|
+
id?: string;
|
|
103
|
+
mediaType?: string;
|
|
104
|
+
name?: string;
|
|
105
|
+
raw?: unknown;
|
|
106
|
+
size?: number;
|
|
107
|
+
text?: string;
|
|
108
|
+
url?: string;
|
|
144
109
|
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
}): AsyncIterable<unknown>;
|
|
153
|
-
output?: PromiseLike<unknown>;
|
|
110
|
+
interface MessengerThread {
|
|
111
|
+
channelId?: string;
|
|
112
|
+
channelName?: string;
|
|
113
|
+
id: string;
|
|
114
|
+
isDirectMessage: boolean;
|
|
115
|
+
providerThreadId: string;
|
|
116
|
+
title?: string;
|
|
154
117
|
}
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
118
|
+
interface MessengerMessage {
|
|
119
|
+
attachments: MessengerAttachment[];
|
|
120
|
+
author: MessengerAuthor;
|
|
121
|
+
createdAt?: Date;
|
|
122
|
+
id: string;
|
|
123
|
+
isMention?: boolean;
|
|
124
|
+
providerMessageId: string;
|
|
125
|
+
raw?: unknown;
|
|
126
|
+
text: string;
|
|
160
127
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
type AgentToolRunInspection<Output = unknown> = {
|
|
168
|
-
runId: string;
|
|
169
|
-
status: AgentToolChildRunStatus;
|
|
170
|
-
requestId?: string;
|
|
171
|
-
streamId?: string;
|
|
172
|
-
output?: Output;
|
|
173
|
-
summary?: string;
|
|
174
|
-
error?: string;
|
|
175
|
-
startedAt: number;
|
|
176
|
-
completedAt?: number;
|
|
177
|
-
};
|
|
178
|
-
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
|
|
179
|
-
type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
|
|
180
|
-
type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
|
|
181
|
-
type ThinkTime = `${Hour}:${Minute}`;
|
|
182
|
-
type ThinkIntervalSchedule =
|
|
183
|
-
| `every ${number} minute${"" | "s"}`
|
|
184
|
-
| `every ${number} hour${"" | "s"}`;
|
|
185
|
-
type ThinkWallClockSchedule =
|
|
186
|
-
| `every day at ${ThinkTime}`
|
|
187
|
-
| `every weekday at ${ThinkTime}`
|
|
188
|
-
| `every week on ${string} at ${ThinkTime}`;
|
|
189
|
-
type ThinkScheduledTaskSchedule =
|
|
190
|
-
| ThinkIntervalSchedule
|
|
191
|
-
| ThinkWallClockSchedule
|
|
192
|
-
| `${ThinkWallClockSchedule} in ${string}`;
|
|
193
|
-
type ThinkScheduledTaskContext = {
|
|
194
|
-
taskId: string;
|
|
195
|
-
scheduledFor: number;
|
|
196
|
-
scheduledForDate: Date;
|
|
197
|
-
occurrenceKey: string;
|
|
198
|
-
idempotencyKey: string;
|
|
199
|
-
schedule: string;
|
|
200
|
-
scheduleKind: "interval" | "wall-clock";
|
|
201
|
-
timezone?: string;
|
|
202
|
-
metadata?: Record<string, unknown>;
|
|
203
|
-
};
|
|
204
|
-
type ThinkScheduledTaskPromptAction = {
|
|
205
|
-
prompt: string | (() => string | Promise<string>);
|
|
206
|
-
handler?: never;
|
|
207
|
-
};
|
|
208
|
-
type ThinkScheduledTaskHandlerAction = {
|
|
209
|
-
handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
|
|
210
|
-
prompt?: never;
|
|
211
|
-
};
|
|
212
|
-
type ThinkScheduledTaskBase = (
|
|
213
|
-
| ThinkScheduledTaskPromptAction
|
|
214
|
-
| ThinkScheduledTaskHandlerAction
|
|
215
|
-
) & {
|
|
216
|
-
retry?: RetryOptions;
|
|
217
|
-
metadata?: Record<string, unknown>;
|
|
218
|
-
};
|
|
219
|
-
type ThinkScheduledTask =
|
|
220
|
-
| (ThinkScheduledTaskBase & {
|
|
221
|
-
schedule: ThinkIntervalSchedule;
|
|
222
|
-
timezone?: never;
|
|
223
|
-
})
|
|
224
|
-
| (ThinkScheduledTaskBase & {
|
|
225
|
-
schedule: ThinkWallClockSchedule;
|
|
226
|
-
timezone?: string;
|
|
227
|
-
})
|
|
228
|
-
| (ThinkScheduledTaskBase & {
|
|
229
|
-
schedule: `${ThinkWallClockSchedule} in ${string}`;
|
|
230
|
-
timezone?: string;
|
|
231
|
-
});
|
|
232
|
-
type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
|
|
233
|
-
declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
|
|
234
|
-
tasks: T
|
|
235
|
-
): T;
|
|
236
|
-
type DeclaredScheduledTaskPayload = {
|
|
237
|
-
taskId: string;
|
|
238
|
-
scheduleHash: string;
|
|
239
|
-
scheduledFor: number;
|
|
240
|
-
};
|
|
241
|
-
type AgentToolStoredChunk = {
|
|
242
|
-
sequence: number;
|
|
243
|
-
body: string;
|
|
244
|
-
};
|
|
245
|
-
type ThinkSubmissionStatus =
|
|
246
|
-
| "pending"
|
|
247
|
-
| "running"
|
|
248
|
-
| "completed"
|
|
249
|
-
| "aborted"
|
|
250
|
-
| "skipped"
|
|
251
|
-
| "error";
|
|
252
|
-
type SubmitMessagesOptions = {
|
|
253
|
-
submissionId?: string;
|
|
254
|
-
idempotencyKey?: string;
|
|
255
|
-
metadata?: Record<string, unknown>;
|
|
256
|
-
};
|
|
257
|
-
type ThinkWorkflowPromptContext = {
|
|
258
|
-
workflow: {
|
|
259
|
-
name: string;
|
|
260
|
-
id: string;
|
|
261
|
-
stepName: string;
|
|
262
|
-
eventType: string;
|
|
263
|
-
};
|
|
264
|
-
output?: {
|
|
265
|
-
schema: unknown;
|
|
266
|
-
};
|
|
267
|
-
fingerprint?: string;
|
|
268
|
-
};
|
|
269
|
-
type ThinkSubmissionInspection = {
|
|
270
|
-
submissionId: string;
|
|
271
|
-
idempotencyKey?: string;
|
|
272
|
-
requestId?: string;
|
|
273
|
-
status: ThinkSubmissionStatus;
|
|
274
|
-
error?: string;
|
|
275
|
-
metadata?: Record<string, unknown>;
|
|
276
|
-
createdAt: number;
|
|
277
|
-
startedAt?: number;
|
|
278
|
-
completedAt?: number;
|
|
279
|
-
};
|
|
280
|
-
type SubmitMessagesResult = ThinkSubmissionInspection & {
|
|
281
|
-
accepted: boolean;
|
|
282
|
-
};
|
|
283
|
-
type ListSubmissionsOptions = {
|
|
284
|
-
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
285
|
-
limit?: number;
|
|
286
|
-
};
|
|
287
|
-
type DeleteSubmissionsOptions = {
|
|
288
|
-
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
289
|
-
completedBefore?: Date;
|
|
290
|
-
limit?: number;
|
|
291
|
-
};
|
|
292
|
-
/**
|
|
293
|
-
* A chat turn request. Built automatically by each entry path
|
|
294
|
-
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
295
|
-
* to Think's inference loop.
|
|
296
|
-
*/
|
|
297
|
-
interface TurnInput {
|
|
298
|
-
signal?: AbortSignal;
|
|
299
|
-
/** Client-provided tool schemas for dynamic tool registration. */
|
|
300
|
-
clientTools?: ClientToolSchema[];
|
|
301
|
-
/** Custom body fields from the client request. */
|
|
302
|
-
body?: Record<string, unknown>;
|
|
303
|
-
/** Internal workflow prompt configuration, never sourced from client body. */
|
|
304
|
-
workflowPrompt?: ThinkWorkflowPromptContext;
|
|
305
|
-
/** Whether this is a continuation turn (auto-continue after tool result, recovery). */
|
|
306
|
-
continuation: boolean;
|
|
128
|
+
interface MessengerAction {
|
|
129
|
+
actionId: string;
|
|
130
|
+
messageId?: string;
|
|
131
|
+
raw?: unknown;
|
|
132
|
+
user?: MessengerAuthor;
|
|
133
|
+
value?: string;
|
|
307
134
|
}
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
/** Assembled model messages (truncated, pruned). */
|
|
316
|
-
messages: ModelMessage[];
|
|
317
|
-
/** Merged tool set (workspace + getTools + session + MCP + client + caller). */
|
|
318
|
-
tools: ToolSet;
|
|
319
|
-
/** The language model from getModel(). */
|
|
320
|
-
model: LanguageModel;
|
|
321
|
-
/** Whether this is a continuation turn. */
|
|
322
|
-
continuation: boolean;
|
|
323
|
-
/** Custom body fields from the client request. */
|
|
324
|
-
body?: Record<string, unknown>;
|
|
135
|
+
interface MessengerCapabilities {
|
|
136
|
+
canEditMessages?: boolean;
|
|
137
|
+
canStream?: boolean;
|
|
138
|
+
maxMessageLength?: number;
|
|
139
|
+
supportsActions?: boolean;
|
|
140
|
+
supportsAttachments?: boolean;
|
|
141
|
+
supportsEphemeral?: boolean;
|
|
325
142
|
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
/** Override the assembled messages. */
|
|
336
|
-
messages?: ModelMessage[];
|
|
337
|
-
/** Extra tools to merge (additive — spread on top of existing tools). */
|
|
338
|
-
tools?: ToolSet;
|
|
339
|
-
/** Limit which tools the model can call (AI SDK activeTools). */
|
|
340
|
-
activeTools?: string[];
|
|
341
|
-
/** Force a specific tool call (AI SDK toolChoice). */
|
|
342
|
-
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
343
|
-
/** Override maxSteps for this turn. */
|
|
344
|
-
maxSteps?: number;
|
|
345
|
-
/**
|
|
346
|
-
* Additional AI SDK stop conditions for ending the turn early.
|
|
347
|
-
* Think always keeps its `maxSteps` stop condition as a safety bound.
|
|
348
|
-
*/
|
|
349
|
-
stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
|
|
350
|
-
/**
|
|
351
|
-
* Controls whether reasoning chunks are included in the UI message stream
|
|
352
|
-
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
353
|
-
*/
|
|
354
|
-
sendReasoning?: boolean;
|
|
355
|
-
/**
|
|
356
|
-
* Override the stream-stall inactivity watchdog timeout for THIS turn only
|
|
357
|
-
* (ms; `0` disables it for this turn). Defaults to the instance-level
|
|
358
|
-
* `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
|
|
359
|
-
* UI-message-stream chunks — which includes server-side tool execution — a
|
|
360
|
-
* turn known to invoke a slow tool can raise (or disable) the timeout for
|
|
361
|
-
* just that turn instead of permanently widening the global window. Auto-
|
|
362
|
-
* resets after the turn.
|
|
363
|
-
*/
|
|
364
|
-
chatStreamStallTimeoutMs?: number;
|
|
365
|
-
/** Maximum number of tokens to generate for this turn. */
|
|
366
|
-
maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
|
|
367
|
-
/** Temperature setting for this turn. */
|
|
368
|
-
temperature?: Parameters<typeof streamText>[0]["temperature"];
|
|
369
|
-
/** Nucleus sampling setting for this turn. */
|
|
370
|
-
topP?: Parameters<typeof streamText>[0]["topP"];
|
|
371
|
-
/** Top-K sampling setting for this turn. */
|
|
372
|
-
topK?: Parameters<typeof streamText>[0]["topK"];
|
|
373
|
-
/** Presence penalty setting for this turn. */
|
|
374
|
-
presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
|
|
375
|
-
/** Frequency penalty setting for this turn. */
|
|
376
|
-
frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
|
|
377
|
-
/** Stop sequences for this turn. */
|
|
378
|
-
stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
|
|
379
|
-
/** Seed for deterministic sampling when supported by the model. */
|
|
380
|
-
seed?: Parameters<typeof streamText>[0]["seed"];
|
|
381
|
-
/** Maximum number of retries for this turn. Set to 0 to disable retries. */
|
|
382
|
-
maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
|
|
383
|
-
/** Timeout configuration for this turn. */
|
|
384
|
-
timeout?: Parameters<typeof streamText>[0]["timeout"];
|
|
385
|
-
/** Additional HTTP headers for provider requests on this turn. */
|
|
386
|
-
headers?: Parameters<typeof streamText>[0]["headers"];
|
|
387
|
-
/** Provider-specific options (AI SDK providerOptions). */
|
|
388
|
-
providerOptions?: Record<string, unknown>;
|
|
389
|
-
/** Optional AI SDK telemetry configuration for this turn. */
|
|
390
|
-
experimental_telemetry?: Parameters<
|
|
391
|
-
typeof streamText
|
|
392
|
-
>[0]["experimental_telemetry"];
|
|
393
|
-
/**
|
|
394
|
-
* Optional structured-output specification (AI SDK `output`).
|
|
395
|
-
* Forwarded to `streamText` so the model's final response is parsed
|
|
396
|
-
* against the supplied schema. Use the AI SDK's `Output.object({ schema })`
|
|
397
|
-
* / `Output.text()` helpers. Combine with `activeTools: []` on the
|
|
398
|
-
* terminal turn if your provider strips tools when structured output
|
|
399
|
-
* is active (e.g. workers-ai-provider).
|
|
400
|
-
*/
|
|
401
|
-
output?: Parameters<typeof streamText>[0]["output"];
|
|
143
|
+
interface MessengerContext {
|
|
144
|
+
action?: MessengerAction;
|
|
145
|
+
author?: MessengerAuthor;
|
|
146
|
+
capabilities: MessengerCapabilities;
|
|
147
|
+
kind: MessengerEventKind;
|
|
148
|
+
message?: MessengerMessage;
|
|
149
|
+
messengerId: string;
|
|
150
|
+
provider: string;
|
|
151
|
+
thread: MessengerThread;
|
|
402
152
|
}
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
*
|
|
406
|
-
* Think ships **no** provider-specific string/code matching — the app owns
|
|
407
|
-
* that knowledge (it knows which provider/model it talks to), exactly like the
|
|
408
|
-
* `tokenCounter` it already passes to `compactAfter()`. An app teaches Think
|
|
409
|
-
* what an error *means* by overriding `classifyChatError()`; Think then reacts
|
|
410
|
-
* generically (e.g. compact-and-retry on `context_overflow`).
|
|
411
|
-
*
|
|
412
|
-
* - `context_overflow` — the prompt exceeded the model's context window
|
|
413
|
-
* (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
|
|
414
|
-
* The only category Think currently acts on (auto-compact + retry).
|
|
415
|
-
* - `rate_limit` / `transient` — reserved for future backoff/retry policies.
|
|
416
|
-
* - `fatal` — unrecoverable; surface terminally.
|
|
417
|
-
* - `unknown` — default; Think applies its existing terminal behavior.
|
|
418
|
-
*/
|
|
419
|
-
type ChatErrorClassification =
|
|
420
|
-
| "context_overflow"
|
|
421
|
-
| "rate_limit"
|
|
422
|
-
| "transient"
|
|
423
|
-
| "fatal"
|
|
424
|
-
| "unknown";
|
|
425
|
-
/**
|
|
426
|
-
* Opt-in handling for a turn that overflows the model's context window
|
|
427
|
-
* mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a
|
|
428
|
-
* long, tool-heavy turn can grow past the window before the next check; the
|
|
429
|
-
* provider then rejects the request (`"prompt is too long"` /
|
|
430
|
-
* `context_length_exceeded`). Both layers reuse the session's compaction
|
|
431
|
-
* function and are provider-agnostic — the app maps the error via
|
|
432
|
-
* {@link Think.classifyChatError}; Think never matches provider strings itself.
|
|
433
|
-
*
|
|
434
|
-
* Set `Think.contextOverflow` to enable. Leaving it unset disables both layers
|
|
435
|
-
* (existing terminal behavior).
|
|
436
|
-
*/
|
|
437
|
-
interface ContextOverflowConfig {
|
|
438
|
-
/**
|
|
439
|
-
* Reactive backstop. When a turn fails with an error classified as
|
|
440
|
-
* `"context_overflow"`, discard the truncated partial, run
|
|
441
|
-
* `session.compact()`, and re-run the turn from the compacted history. The
|
|
442
|
-
* partial is intentionally not persisted: the turn restarts from scratch, so
|
|
443
|
-
* keeping the cut-off assistant message would orphan it beside the recovered
|
|
444
|
-
* answer (and duplicate any tool work the retry re-issues). If compaction
|
|
445
|
-
* cannot shorten history or the retry budget is spent, the overflow surfaces
|
|
446
|
-
* terminally through `onChatError` (classified) — it never loops or ends
|
|
447
|
-
* silently. Default `false`.
|
|
448
|
-
*/
|
|
449
|
-
reactive?: boolean;
|
|
450
|
-
/**
|
|
451
|
-
* Maximum compact-and-retry attempts for a single overflowing turn (the
|
|
452
|
-
* reactive backstop). Independent of the proactive guard's cap — see
|
|
453
|
-
* {@link proactive.maxCompactions}. Default `1`.
|
|
454
|
-
*/
|
|
455
|
-
maxRetries?: number;
|
|
456
|
-
/**
|
|
457
|
-
* Proactive guard. Before each step, read the previous step's model-reported
|
|
458
|
-
* `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,
|
|
459
|
-
* compact in place and feed the recompacted history into the upcoming step —
|
|
460
|
-
* heading off the provider rejection before it happens. Keys off usage (every
|
|
461
|
-
* provider reports it), not provider error strings. Unset disables it.
|
|
462
|
-
*
|
|
463
|
-
* If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`
|
|
464
|
-
* (input + output) — a safe over-approximation that compacts slightly early
|
|
465
|
-
* rather than missing the threshold. If neither is reported, the guard does
|
|
466
|
-
* nothing that step (the reactive backstop still catches a genuine overflow).
|
|
467
|
-
*
|
|
468
|
-
* `maxCompactions` caps how many times the guard may compact within a single
|
|
469
|
-
* step loop (default `1`, floored at `1`). It is independent of
|
|
470
|
-
* {@link maxRetries} (the reactive budget): a no-op compaction would repeat on
|
|
471
|
-
* every step, so the cap stops the guard from compacting (and emitting
|
|
472
|
-
* `chat:context:compacted`) on each one.
|
|
473
|
-
*/
|
|
474
|
-
proactive?: {
|
|
475
|
-
maxInputTokens: number;
|
|
476
|
-
headroom?: number;
|
|
477
|
-
maxCompactions?: number;
|
|
478
|
-
};
|
|
153
|
+
interface MessengerEvent extends MessengerContext {
|
|
154
|
+
raw?: unknown;
|
|
479
155
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
* Or combine with your own checks:
|
|
500
|
-
*
|
|
501
|
-
* @example
|
|
502
|
-
* ```typescript
|
|
503
|
-
* override classifyChatError(error: unknown): ChatErrorClassification | void {
|
|
504
|
-
* if (isMyRateLimit(error)) return "rate_limit";
|
|
505
|
-
* return defaultContextOverflowClassifier(error);
|
|
506
|
-
* }
|
|
507
|
-
* ```
|
|
508
|
-
*/
|
|
509
|
-
declare function defaultContextOverflowClassifier(
|
|
510
|
-
error: unknown
|
|
511
|
-
): ChatErrorClassification | undefined;
|
|
512
|
-
interface ChatErrorContext {
|
|
513
|
-
requestId?: string;
|
|
514
|
-
stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
|
|
515
|
-
messagesPersisted?: boolean;
|
|
516
|
-
/**
|
|
517
|
-
* App-provided semantic classification (from `classifyChatError`), when
|
|
518
|
-
* known. Lets `onChatError` overrides and observers distinguish e.g. a
|
|
519
|
-
* context-overflow from a generic provider failure without re-matching
|
|
520
|
-
* provider strings.
|
|
521
|
-
*/
|
|
522
|
-
classification?: ChatErrorClassification;
|
|
156
|
+
declare function messengerContextFromEvent(
|
|
157
|
+
event: MessengerEvent
|
|
158
|
+
): MessengerContext;
|
|
159
|
+
declare function serializableMessengerEvent(
|
|
160
|
+
event: MessengerEvent
|
|
161
|
+
): MessengerEvent;
|
|
162
|
+
declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region src/messengers/delivery.d.ts
|
|
165
|
+
declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
|
|
166
|
+
declare const EMPTY_MESSENGER_RESPONSE =
|
|
167
|
+
"I couldn't produce a text response. Please try again.";
|
|
168
|
+
declare const ERROR_MESSENGER_RESPONSE =
|
|
169
|
+
"Sorry, I couldn't answer that right now. Please try again.";
|
|
170
|
+
declare const INTERRUPTED_MESSENGER_RESPONSE =
|
|
171
|
+
"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
|
|
172
|
+
interface TextStreamCallbackOptions {
|
|
173
|
+
onVisibleStart?: () => Promise<void> | void;
|
|
174
|
+
visibleSoftLimit?: number;
|
|
523
175
|
}
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
176
|
+
declare class TextStreamCallback extends RpcTarget implements StreamCallback {
|
|
177
|
+
private readonly onVisibleStart?;
|
|
178
|
+
private readonly visibleChunks;
|
|
179
|
+
private readonly wakeups;
|
|
180
|
+
private readonly visibleSoftLimit?;
|
|
181
|
+
private chatRequestId?;
|
|
182
|
+
private closed;
|
|
183
|
+
private interrupted;
|
|
184
|
+
private error?;
|
|
185
|
+
private text;
|
|
186
|
+
private visibleClosed;
|
|
187
|
+
private visibleLimitReachedValue;
|
|
188
|
+
private visibleStarted;
|
|
189
|
+
private visibleTextValue;
|
|
190
|
+
constructor(options?: TextStreamCallbackOptions);
|
|
191
|
+
onStart(event: ChatStartEvent): void;
|
|
192
|
+
onEvent(json: string): void;
|
|
193
|
+
onDone(): void;
|
|
194
|
+
onError(error: string): void;
|
|
195
|
+
onInterrupted(): void;
|
|
196
|
+
wasInterrupted(): boolean;
|
|
197
|
+
close(): void;
|
|
198
|
+
fail(error: unknown): void;
|
|
199
|
+
hasText(): boolean;
|
|
200
|
+
remainingText(): string;
|
|
201
|
+
requestId(): string | undefined;
|
|
202
|
+
textSoFar(): string;
|
|
203
|
+
visibleLimitReached(): boolean;
|
|
204
|
+
visibleText(): string;
|
|
205
|
+
stream(): AsyncIterable<string>;
|
|
206
|
+
private pushVisibleText;
|
|
207
|
+
private wake;
|
|
208
|
+
private markVisibleStarted;
|
|
209
|
+
}
|
|
210
|
+
declare function textDeltaFromStreamChunk(json: string): string | null;
|
|
211
|
+
type MessengerReplyStage = "accepted" | "streaming" | "completed";
|
|
212
|
+
interface MessengerReplySnapshot {
|
|
213
|
+
event: MessengerEvent;
|
|
214
|
+
stage: MessengerReplyStage;
|
|
215
|
+
thread?: unknown;
|
|
216
|
+
type: typeof MESSENGER_REPLY_FIBER_NAME;
|
|
217
|
+
}
|
|
218
|
+
declare function messengerReplySnapshot(
|
|
219
|
+
stage: MessengerReplyStage,
|
|
220
|
+
event: MessengerEvent,
|
|
221
|
+
thread?: unknown
|
|
222
|
+
): MessengerReplySnapshot;
|
|
223
|
+
declare function parseMessengerReplySnapshot(
|
|
224
|
+
snapshot: unknown
|
|
225
|
+
): MessengerReplySnapshot | null;
|
|
226
|
+
declare function messengerReplyRecoveryMode(
|
|
227
|
+
snapshot: MessengerReplySnapshot
|
|
228
|
+
): "answer" | "apologize" | null;
|
|
229
|
+
declare function messengerReplyFailureMode(
|
|
230
|
+
hasStreamedText: boolean,
|
|
231
|
+
completedModelTurn?: boolean,
|
|
232
|
+
expectedDeliveryCompletion?: boolean
|
|
233
|
+
): "apologize" | "error" | null;
|
|
234
|
+
interface MessengerDeliveryTarget {
|
|
235
|
+
cancelChat(
|
|
236
|
+
requestId: string,
|
|
237
|
+
reason?: string
|
|
238
|
+
): boolean | void | Promise<boolean | void>;
|
|
239
|
+
chat(
|
|
240
|
+
userMessage: string | UIMessage,
|
|
241
|
+
callback: StreamCallback
|
|
242
|
+
): Promise<void>;
|
|
243
|
+
chatWithMessengerContext?(
|
|
244
|
+
userMessage: string | UIMessage,
|
|
245
|
+
callback: StreamCallback,
|
|
246
|
+
context: MessengerEvent
|
|
247
|
+
): Promise<void>;
|
|
248
|
+
}
|
|
249
|
+
interface MessengerDeliverySurface {
|
|
250
|
+
post(
|
|
251
|
+
message:
|
|
252
|
+
| string
|
|
253
|
+
| {
|
|
254
|
+
markdown: string;
|
|
255
|
+
}
|
|
256
|
+
| AsyncIterable<string>
|
|
257
|
+
): Promise<unknown>;
|
|
258
|
+
startTyping?(status?: string): Promise<void>;
|
|
259
|
+
}
|
|
260
|
+
interface MessengerDeliveryPolicy {
|
|
261
|
+
emptyResponseText?: string;
|
|
262
|
+
errorResponseText?: string;
|
|
263
|
+
interruptedResponseText?: string;
|
|
264
|
+
isExpectedDeliveryCompletion?(
|
|
265
|
+
error: unknown,
|
|
266
|
+
callback: TextStreamCallback
|
|
267
|
+
): boolean;
|
|
268
|
+
splitText?(text: string): string[];
|
|
269
|
+
visibleSoftLimit?: number;
|
|
270
|
+
}
|
|
271
|
+
interface DeliverMessengerReplyOptions {
|
|
272
|
+
checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
|
|
273
|
+
event: MessengerEvent;
|
|
274
|
+
fiber?: FiberContext;
|
|
275
|
+
policy?: MessengerDeliveryPolicy;
|
|
276
|
+
snapshotEvent?: MessengerEvent;
|
|
277
|
+
snapshotThread?: unknown;
|
|
278
|
+
surface: MessengerDeliverySurface;
|
|
279
|
+
target: MessengerDeliveryTarget;
|
|
280
|
+
userMessage?: UIMessage;
|
|
281
|
+
}
|
|
282
|
+
declare function deliverMessengerReply(
|
|
283
|
+
options: DeliverMessengerReplyOptions
|
|
284
|
+
): Promise<void>;
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region src/messengers/chat-sdk.d.ts
|
|
287
|
+
declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
|
|
288
|
+
type MessengerRespondTo =
|
|
289
|
+
| "action"
|
|
290
|
+
| "direct-message"
|
|
291
|
+
| "mention"
|
|
292
|
+
| "subscribed-thread";
|
|
293
|
+
type MessengerConversationMode = "self" | "thread";
|
|
294
|
+
type MessengerConversationTarget =
|
|
599
295
|
| {
|
|
600
|
-
|
|
601
|
-
reason?: string;
|
|
296
|
+
target: "self";
|
|
602
297
|
}
|
|
603
298
|
| {
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
299
|
+
agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
|
|
300
|
+
name: string;
|
|
301
|
+
target: "subagent";
|
|
607
302
|
};
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
interface
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
303
|
+
type MessengerConversationResolver = (
|
|
304
|
+
event: MessengerEvent
|
|
305
|
+
) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
|
|
306
|
+
interface MessengerDefinition {
|
|
307
|
+
adapter: Adapter;
|
|
308
|
+
adapterName: string;
|
|
309
|
+
capabilities?: MessengerCapabilities;
|
|
310
|
+
conversation?: MessengerConversationMode | MessengerConversationResolver;
|
|
311
|
+
delivery?: MessengerDeliveryPolicy;
|
|
312
|
+
keyShard?: ChatSdkStateAdapterOptions["keyShard"];
|
|
313
|
+
path?: string;
|
|
314
|
+
provider: string;
|
|
315
|
+
respondTo?: readonly MessengerRespondTo[];
|
|
316
|
+
shardKey?: ChatSdkStateAdapterOptions["shardKey"];
|
|
317
|
+
subscribeOnMention?: boolean;
|
|
318
|
+
toEvent?: (
|
|
319
|
+
input: ChatSdkMessengerEventInput
|
|
320
|
+
) => MessengerEvent | Promise<MessengerEvent>;
|
|
321
|
+
userName: string;
|
|
322
|
+
verifyWebhook?:
|
|
323
|
+
| false
|
|
324
|
+
| ((request: Request) => boolean | Response | Promise<boolean | Response>);
|
|
325
|
+
}
|
|
326
|
+
type ThinkMessengers = Record<string, MessengerDefinition>;
|
|
327
|
+
interface NormalizedMessengerDefinition extends MessengerDefinition {
|
|
328
|
+
id: string;
|
|
329
|
+
path: string;
|
|
330
|
+
respondTo: readonly MessengerRespondTo[];
|
|
331
|
+
subscribeOnMention: boolean;
|
|
332
|
+
verifyWebhook:
|
|
333
|
+
| false
|
|
334
|
+
| ((request: Request) => boolean | Response | Promise<boolean | Response>);
|
|
335
|
+
}
|
|
336
|
+
interface ChatSdkMessengerOptions extends Omit<
|
|
337
|
+
MessengerDefinition,
|
|
338
|
+
"adapterName"
|
|
339
|
+
> {
|
|
340
|
+
adapterName?: string;
|
|
341
|
+
}
|
|
342
|
+
interface ChatSdkMessengerEventInput {
|
|
343
|
+
action?: ActionEvent;
|
|
344
|
+
eventKind: MessengerEventKind;
|
|
345
|
+
message?: Message;
|
|
346
|
+
raw?: unknown;
|
|
347
|
+
thread: Thread;
|
|
348
|
+
}
|
|
349
|
+
interface MessengerThinkTarget {
|
|
350
|
+
cancelChat(
|
|
351
|
+
requestId: string,
|
|
352
|
+
reason?: string
|
|
353
|
+
): boolean | void | Promise<boolean | void>;
|
|
354
|
+
chat(
|
|
355
|
+
userMessage: string | UIMessage,
|
|
356
|
+
callback: StreamCallback
|
|
357
|
+
): Promise<void>;
|
|
358
|
+
chatWithMessengerContext?(
|
|
359
|
+
userMessage: string | UIMessage,
|
|
360
|
+
callback: StreamCallback,
|
|
361
|
+
context: MessengerEvent
|
|
362
|
+
): Promise<void>;
|
|
363
|
+
}
|
|
364
|
+
interface MessengerThinkHost extends MessengerThinkTarget {
|
|
365
|
+
constructor: {
|
|
366
|
+
name: string;
|
|
367
|
+
};
|
|
368
|
+
name: string;
|
|
369
|
+
parentPath: ReadonlyArray<{
|
|
370
|
+
className: string;
|
|
371
|
+
name: string;
|
|
372
|
+
}>;
|
|
373
|
+
startFiber(
|
|
374
|
+
name: string,
|
|
375
|
+
fn: (ctx: FiberContext) => Promise<void>,
|
|
376
|
+
options?: StartFiberOptions
|
|
377
|
+
): Promise<MessengerFiberStartResult>;
|
|
378
|
+
resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
|
|
379
|
+
subAgent<T extends Agent>(
|
|
380
|
+
agentClass: SubAgentClass<T>,
|
|
381
|
+
name: string
|
|
382
|
+
): Promise<SubAgentStub<T>>;
|
|
383
|
+
}
|
|
384
|
+
interface MessengerFiberStartResult {
|
|
385
|
+
accepted: boolean;
|
|
386
|
+
fiberId: string;
|
|
387
|
+
snapshot?: unknown;
|
|
388
|
+
status: string;
|
|
389
|
+
}
|
|
390
|
+
declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
|
|
391
|
+
declare function chatSdkMessenger(
|
|
392
|
+
options: ChatSdkMessengerOptions
|
|
393
|
+
): MessengerDefinition;
|
|
394
|
+
declare class ThinkMessengerRuntime {
|
|
395
|
+
private readonly host;
|
|
396
|
+
private chat?;
|
|
397
|
+
private readonly definitionsByAdapterName;
|
|
398
|
+
private readonly definitionsById;
|
|
399
|
+
private readonly definitions;
|
|
400
|
+
constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
|
|
401
|
+
get size(): number;
|
|
402
|
+
initialize(): void;
|
|
403
|
+
handleRequest(request: Request): Promise<Response | undefined>;
|
|
404
|
+
handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
|
|
405
|
+
private createChat;
|
|
406
|
+
private enqueueReply;
|
|
407
|
+
private answer;
|
|
408
|
+
private resolveTarget;
|
|
409
|
+
private definitionForThread;
|
|
410
|
+
private definitionForThreadId;
|
|
411
|
+
private hasUniqueProvider;
|
|
412
|
+
private shardThread;
|
|
413
|
+
private shardStateKey;
|
|
414
|
+
private reviveChatObject;
|
|
415
|
+
private toEvent;
|
|
694
416
|
}
|
|
417
|
+
declare function normalizeMessengers(
|
|
418
|
+
messengers: ThinkMessengers
|
|
419
|
+
): NormalizedMessengerDefinition[];
|
|
420
|
+
declare function defaultConversationName(event: MessengerEvent): string;
|
|
421
|
+
declare function idempotencyKeyForEvent(event: MessengerEvent): string;
|
|
422
|
+
declare function defaultChatSdkEvent(
|
|
423
|
+
definition: NormalizedMessengerDefinition,
|
|
424
|
+
input: ChatSdkMessengerEventInput
|
|
425
|
+
): MessengerEvent;
|
|
426
|
+
declare function toMessengerThread(thread: Thread): MessengerThread;
|
|
427
|
+
declare function toMessengerMessage(message: Message): MessengerMessage;
|
|
428
|
+
declare function toMessengerAuthor(author: Author): MessengerAuthor;
|
|
429
|
+
declare function toMessengerAttachment(
|
|
430
|
+
attachment: Attachment
|
|
431
|
+
): MessengerAttachment;
|
|
432
|
+
//#endregion
|
|
433
|
+
//#region src/think.d.ts
|
|
434
|
+
type ChatRecoveryRetryData = {
|
|
435
|
+
targetUserId?: string;
|
|
436
|
+
originalRequestId?: string;
|
|
437
|
+
incidentId?: string;
|
|
438
|
+
lastBody?: Record<string, unknown> | null;
|
|
439
|
+
lastClientTools?: ClientToolSchema[] | null;
|
|
440
|
+
recoveredRequestId?: string;
|
|
441
|
+
};
|
|
442
|
+
type ChatRecoveryContinueData = {
|
|
443
|
+
targetAssistantId?: string;
|
|
444
|
+
originalRequestId?: string;
|
|
445
|
+
incidentId?: string;
|
|
446
|
+
lastBody?: Record<string, unknown> | null;
|
|
447
|
+
lastClientTools?: ClientToolSchema[] | null;
|
|
448
|
+
recoveredRequestId?: string;
|
|
449
|
+
};
|
|
695
450
|
/**
|
|
696
|
-
*
|
|
451
|
+
* Callback interface for streaming chat events from a Think sub-agent.
|
|
697
452
|
*
|
|
698
|
-
*
|
|
453
|
+
* Designed to work across the sub-agent RPC boundary — implement as
|
|
454
|
+
* an RpcTarget in the parent agent and pass to `chat()`.
|
|
699
455
|
*/
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
456
|
+
interface ChatStartEvent {
|
|
457
|
+
requestId: string;
|
|
458
|
+
}
|
|
459
|
+
interface StreamCallback {
|
|
460
|
+
onStart(event: ChatStartEvent): void | Promise<void>;
|
|
461
|
+
onEvent(json: string): void | Promise<void>;
|
|
462
|
+
onDone(): void | Promise<void>;
|
|
463
|
+
onError(error: string): void | Promise<void>;
|
|
708
464
|
/**
|
|
709
|
-
*
|
|
710
|
-
*
|
|
465
|
+
* The current attempt was interrupted (a stream-stall watchdog abort routed
|
|
466
|
+
* into bounded recovery, #1626) and its final outcome will NOT arrive through
|
|
467
|
+
* this callback. One of two things is true:
|
|
468
|
+
* - a scheduled continuation — running in a LATER isolate invocation, without
|
|
469
|
+
* this callback — will produce the answer (delivered to other channels,
|
|
470
|
+
* e.g. WebSocket connections), OR
|
|
471
|
+
* - the recovery budget was exhausted, so the turn was already terminalized
|
|
472
|
+
* out-of-band (the configured `terminalMessage` + `onExhausted`) and is
|
|
473
|
+
* terminally over — there is NO continuation to come.
|
|
711
474
|
*
|
|
712
|
-
*
|
|
713
|
-
*
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
| {
|
|
718
|
-
timeout: number;
|
|
719
|
-
};
|
|
720
|
-
private _skillRegistry;
|
|
721
|
-
private _loggedSkillWarnings;
|
|
722
|
-
/**
|
|
723
|
-
* Controls how overlapping user submit requests behave while another
|
|
724
|
-
* chat turn is already active or queued.
|
|
475
|
+
* This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the
|
|
476
|
+
* raw stall is not surfaced as a terminal error here); without it the contract
|
|
477
|
+
* `onStart → onEvent* → (onDone | onError)` is silently abandoned and a
|
|
478
|
+
* consumer that treats the clean resolve as success finalizes a truncated
|
|
479
|
+
* partial.
|
|
725
480
|
*
|
|
726
|
-
*
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
*
|
|
731
|
-
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
481
|
+
* Consumers should AVOID finalizing the partial on this signal — surface a
|
|
482
|
+
* "recovering…" / "interrupted, please retry" state, or re-attach via a
|
|
483
|
+
* durable channel — but must ALSO NOT block indefinitely waiting for a
|
|
484
|
+
* continuation: per the exhausted case above, one may never come. Optional →
|
|
485
|
+
* defaults to a no-op, so this is fully backward-compatible.
|
|
732
486
|
*
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
736
|
-
* set in `onStart()` is applied too late and the built-in defaults are used
|
|
737
|
-
* for the recovery that matters. See {@link ChatRecoveryConfig}.
|
|
487
|
+
* Note: a deploy/eviction interruption kills the isolate (and this callback)
|
|
488
|
+
* before this can fire — the caller observes a transport break instead. This
|
|
489
|
+
* fires only for an in-isolate interruption (the stall→recovery path).
|
|
738
490
|
*/
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
491
|
+
onInterrupted?(): void | Promise<void>;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Minimal interface for the result of the inference loop.
|
|
495
|
+
* The AI SDK's `streamText()` result satisfies this interface.
|
|
496
|
+
*/
|
|
497
|
+
interface StreamableResult {
|
|
498
|
+
toUIMessageStream(options?: {
|
|
499
|
+
sendReasoning?: boolean;
|
|
500
|
+
}): AsyncIterable<unknown>;
|
|
501
|
+
output?: PromiseLike<unknown>;
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Options for a chat turn (sub-agent RPC entry point).
|
|
505
|
+
*/
|
|
506
|
+
interface ChatOptions {
|
|
507
|
+
signal?: AbortSignal;
|
|
508
|
+
}
|
|
509
|
+
type AgentToolChildRunStatus =
|
|
510
|
+
| "starting"
|
|
511
|
+
| "running"
|
|
512
|
+
| "completed"
|
|
513
|
+
| "error"
|
|
514
|
+
| "aborted";
|
|
515
|
+
type AgentToolRunInspection<Output = unknown> = {
|
|
516
|
+
runId: string;
|
|
517
|
+
status: AgentToolChildRunStatus;
|
|
518
|
+
requestId?: string;
|
|
519
|
+
streamId?: string;
|
|
520
|
+
output?: Output;
|
|
521
|
+
summary?: string;
|
|
522
|
+
error?: string;
|
|
523
|
+
startedAt: number;
|
|
524
|
+
completedAt?: number;
|
|
525
|
+
};
|
|
526
|
+
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
|
|
527
|
+
type Hour = `0${Digit}` | `1${Digit}` | "20" | "21" | "22" | "23";
|
|
528
|
+
type Minute = `${"0" | "1" | "2" | "3" | "4" | "5"}${Digit}`;
|
|
529
|
+
type ThinkTime = `${Hour}:${Minute}`;
|
|
530
|
+
type ThinkIntervalSchedule =
|
|
531
|
+
| `every ${number} minute${"" | "s"}`
|
|
532
|
+
| `every ${number} hour${"" | "s"}`;
|
|
533
|
+
type ThinkWallClockSchedule =
|
|
534
|
+
| `every day at ${ThinkTime}`
|
|
535
|
+
| `every weekday at ${ThinkTime}`
|
|
536
|
+
| `every week on ${string} at ${ThinkTime}`;
|
|
537
|
+
type ThinkScheduledTaskSchedule =
|
|
538
|
+
| ThinkIntervalSchedule
|
|
539
|
+
| ThinkWallClockSchedule
|
|
540
|
+
| `${ThinkWallClockSchedule} in ${string}`;
|
|
541
|
+
type ThinkScheduledTaskContext = {
|
|
542
|
+
taskId: string;
|
|
543
|
+
scheduledFor: number;
|
|
544
|
+
scheduledForDate: Date;
|
|
545
|
+
occurrenceKey: string;
|
|
546
|
+
idempotencyKey: string;
|
|
547
|
+
schedule: string;
|
|
548
|
+
scheduleKind: "interval" | "wall-clock";
|
|
549
|
+
timezone?: string;
|
|
550
|
+
metadata?: Record<string, unknown>;
|
|
551
|
+
};
|
|
552
|
+
type ThinkScheduledTaskPromptAction = {
|
|
553
|
+
prompt: string | (() => string | Promise<string>);
|
|
554
|
+
handler?: never;
|
|
555
|
+
};
|
|
556
|
+
type ThinkScheduledTaskHandlerAction = {
|
|
557
|
+
handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;
|
|
558
|
+
prompt?: never;
|
|
559
|
+
};
|
|
560
|
+
type ThinkScheduledTaskBase = (
|
|
561
|
+
| ThinkScheduledTaskPromptAction
|
|
562
|
+
| ThinkScheduledTaskHandlerAction
|
|
563
|
+
) & {
|
|
564
|
+
retry?: RetryOptions;
|
|
565
|
+
metadata?: Record<string, unknown>;
|
|
566
|
+
};
|
|
567
|
+
type ThinkScheduledTask =
|
|
568
|
+
| (ThinkScheduledTaskBase & {
|
|
569
|
+
schedule: ThinkIntervalSchedule;
|
|
570
|
+
timezone?: never;
|
|
571
|
+
})
|
|
572
|
+
| (ThinkScheduledTaskBase & {
|
|
573
|
+
schedule: ThinkWallClockSchedule;
|
|
574
|
+
timezone?: string;
|
|
575
|
+
})
|
|
576
|
+
| (ThinkScheduledTaskBase & {
|
|
577
|
+
schedule: `${ThinkWallClockSchedule} in ${string}`;
|
|
578
|
+
timezone?: string;
|
|
579
|
+
});
|
|
580
|
+
type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;
|
|
581
|
+
declare function defineScheduledTasks<const T extends ThinkScheduledTasks>(
|
|
582
|
+
tasks: T
|
|
583
|
+
): T;
|
|
584
|
+
type DeclaredScheduledTaskPayload = {
|
|
585
|
+
taskId: string;
|
|
586
|
+
scheduleHash: string;
|
|
587
|
+
scheduledFor: number;
|
|
588
|
+
};
|
|
589
|
+
type AgentToolStoredChunk = {
|
|
590
|
+
sequence: number;
|
|
591
|
+
body: string;
|
|
592
|
+
};
|
|
593
|
+
type ThinkSubmissionStatus =
|
|
594
|
+
| "pending"
|
|
595
|
+
| "running"
|
|
596
|
+
| "completed"
|
|
597
|
+
| "aborted"
|
|
598
|
+
| "skipped"
|
|
599
|
+
| "error";
|
|
600
|
+
type SubmitMessagesOptions = {
|
|
601
|
+
submissionId?: string;
|
|
602
|
+
idempotencyKey?: string;
|
|
603
|
+
metadata?: Record<string, unknown>;
|
|
604
|
+
};
|
|
605
|
+
type ThinkWorkflowPromptContext = {
|
|
606
|
+
workflow: {
|
|
607
|
+
name: string;
|
|
608
|
+
id: string;
|
|
609
|
+
stepName: string;
|
|
610
|
+
eventType: string;
|
|
611
|
+
};
|
|
612
|
+
output?: {
|
|
613
|
+
schema: unknown;
|
|
614
|
+
};
|
|
615
|
+
fingerprint?: string;
|
|
616
|
+
};
|
|
617
|
+
type ThinkSubmissionInspection = {
|
|
618
|
+
submissionId: string;
|
|
619
|
+
idempotencyKey?: string;
|
|
620
|
+
requestId?: string;
|
|
621
|
+
status: ThinkSubmissionStatus;
|
|
622
|
+
error?: string;
|
|
623
|
+
metadata?: Record<string, unknown>;
|
|
624
|
+
createdAt: number;
|
|
625
|
+
startedAt?: number;
|
|
626
|
+
completedAt?: number;
|
|
627
|
+
};
|
|
628
|
+
type SubmitMessagesResult = ThinkSubmissionInspection & {
|
|
629
|
+
accepted: boolean;
|
|
630
|
+
};
|
|
631
|
+
type ListSubmissionsOptions = {
|
|
632
|
+
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
633
|
+
limit?: number;
|
|
634
|
+
};
|
|
635
|
+
type DeleteSubmissionsOptions = {
|
|
636
|
+
status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];
|
|
637
|
+
completedBefore?: Date;
|
|
638
|
+
limit?: number;
|
|
639
|
+
};
|
|
640
|
+
/**
|
|
641
|
+
* A chat turn request. Built automatically by each entry path
|
|
642
|
+
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
643
|
+
* to Think's inference loop.
|
|
644
|
+
*/
|
|
645
|
+
interface TurnInput {
|
|
646
|
+
signal?: AbortSignal;
|
|
647
|
+
/** Client-provided tool schemas for dynamic tool registration. */
|
|
648
|
+
clientTools?: ClientToolSchema[];
|
|
649
|
+
/** Custom body fields from the client request. */
|
|
650
|
+
body?: Record<string, unknown>;
|
|
651
|
+
/** Internal workflow prompt configuration, never sourced from client body. */
|
|
652
|
+
workflowPrompt?: ThinkWorkflowPromptContext;
|
|
653
|
+
/** Whether this is a continuation turn (auto-continue after tool result, recovery). */
|
|
654
|
+
continuation: boolean;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Context passed to the `beforeTurn` hook.
|
|
658
|
+
* Contains everything Think assembled — the hook can inspect and override.
|
|
659
|
+
*/
|
|
660
|
+
interface TurnContext {
|
|
661
|
+
/** Assembled system prompt (from context blocks or getSystemPrompt fallback). */
|
|
662
|
+
system: string;
|
|
663
|
+
/** Assembled model messages (truncated, pruned). */
|
|
664
|
+
messages: ModelMessage[];
|
|
665
|
+
/** Merged tool set (workspace + getTools + session + MCP + client + caller). */
|
|
666
|
+
tools: ToolSet;
|
|
667
|
+
/** The language model from getModel(). */
|
|
668
|
+
model: LanguageModel;
|
|
669
|
+
/** Whether this is a continuation turn. */
|
|
670
|
+
continuation: boolean;
|
|
671
|
+
/** Custom body fields from the client request. */
|
|
672
|
+
body?: Record<string, unknown>;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Configuration returned by the `beforeTurn` hook to override defaults.
|
|
676
|
+
* All fields are optional — return only what you want to change.
|
|
677
|
+
*/
|
|
678
|
+
interface TurnConfig {
|
|
679
|
+
/** Override the model for this turn (e.g. cheap model for continuations). */
|
|
680
|
+
model?: LanguageModel;
|
|
681
|
+
/** Override the assembled system prompt. */
|
|
682
|
+
system?: string;
|
|
683
|
+
/** Override the assembled messages. */
|
|
684
|
+
messages?: ModelMessage[];
|
|
685
|
+
/** Extra tools to merge (additive — spread on top of existing tools). */
|
|
686
|
+
tools?: ToolSet;
|
|
687
|
+
/** Limit which tools the model can call (AI SDK activeTools). */
|
|
688
|
+
activeTools?: string[];
|
|
689
|
+
/** Force a specific tool call (AI SDK toolChoice). */
|
|
690
|
+
toolChoice?: Parameters<typeof streamText>[0]["toolChoice"];
|
|
691
|
+
/** Override maxSteps for this turn. */
|
|
692
|
+
maxSteps?: number;
|
|
758
693
|
/**
|
|
759
|
-
*
|
|
760
|
-
*
|
|
694
|
+
* Additional AI SDK stop conditions for ending the turn early.
|
|
695
|
+
* Think always keeps its `maxSteps` stop condition as a safety bound.
|
|
761
696
|
*/
|
|
762
|
-
|
|
697
|
+
stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;
|
|
763
698
|
/**
|
|
764
|
-
*
|
|
765
|
-
* Defaults to
|
|
766
|
-
*
|
|
767
|
-
* Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
|
|
768
|
-
* replace it with anything that satisfies the interface — e.g. a proxy
|
|
769
|
-
* that forwards to a shared workspace owned by a parent DO. Override as
|
|
770
|
-
* a class field to skip the default init entirely:
|
|
771
|
-
*
|
|
772
|
-
* ```typescript
|
|
773
|
-
* // Default init with R2 spillover for large files.
|
|
774
|
-
* override workspace = new Workspace({
|
|
775
|
-
* sql: this.ctx.storage.sql,
|
|
776
|
-
* r2: this.env.R2,
|
|
777
|
-
* name: () => this.name
|
|
778
|
-
* });
|
|
779
|
-
*
|
|
780
|
-
* // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
|
|
781
|
-
* override workspace: WorkspaceLike = new SharedWorkspace(this);
|
|
782
|
-
* ```
|
|
699
|
+
* Controls whether reasoning chunks are included in the UI message stream
|
|
700
|
+
* for this turn. Defaults to the instance-level `sendReasoning` setting.
|
|
783
701
|
*/
|
|
784
|
-
|
|
702
|
+
sendReasoning?: boolean;
|
|
785
703
|
/**
|
|
786
|
-
*
|
|
787
|
-
*
|
|
788
|
-
*
|
|
704
|
+
* Override the stream-stall inactivity watchdog timeout for THIS turn only
|
|
705
|
+
* (ms; `0` disables it for this turn). Defaults to the instance-level
|
|
706
|
+
* `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between
|
|
707
|
+
* UI-message-stream chunks — which includes server-side tool execution — a
|
|
708
|
+
* turn known to invoke a slow tool can raise (or disable) the timeout for
|
|
709
|
+
* just that turn instead of permanently widening the global window. Auto-
|
|
710
|
+
* resets after the turn.
|
|
789
711
|
*/
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
712
|
+
chatStreamStallTimeoutMs?: number;
|
|
713
|
+
/** Maximum number of tokens to generate for this turn. */
|
|
714
|
+
maxOutputTokens?: Parameters<typeof streamText>[0]["maxOutputTokens"];
|
|
715
|
+
/** Temperature setting for this turn. */
|
|
716
|
+
temperature?: Parameters<typeof streamText>[0]["temperature"];
|
|
717
|
+
/** Nucleus sampling setting for this turn. */
|
|
718
|
+
topP?: Parameters<typeof streamText>[0]["topP"];
|
|
719
|
+
/** Top-K sampling setting for this turn. */
|
|
720
|
+
topK?: Parameters<typeof streamText>[0]["topK"];
|
|
721
|
+
/** Presence penalty setting for this turn. */
|
|
722
|
+
presencePenalty?: Parameters<typeof streamText>[0]["presencePenalty"];
|
|
723
|
+
/** Frequency penalty setting for this turn. */
|
|
724
|
+
frequencyPenalty?: Parameters<typeof streamText>[0]["frequencyPenalty"];
|
|
725
|
+
/** Stop sequences for this turn. */
|
|
726
|
+
stopSequences?: Parameters<typeof streamText>[0]["stopSequences"];
|
|
727
|
+
/** Seed for deterministic sampling when supported by the model. */
|
|
728
|
+
seed?: Parameters<typeof streamText>[0]["seed"];
|
|
729
|
+
/** Maximum number of retries for this turn. Set to 0 to disable retries. */
|
|
730
|
+
maxRetries?: Parameters<typeof streamText>[0]["maxRetries"];
|
|
731
|
+
/** Timeout configuration for this turn. */
|
|
732
|
+
timeout?: Parameters<typeof streamText>[0]["timeout"];
|
|
733
|
+
/** Additional HTTP headers for provider requests on this turn. */
|
|
734
|
+
headers?: Parameters<typeof streamText>[0]["headers"];
|
|
735
|
+
/** Provider-specific options (AI SDK providerOptions). */
|
|
736
|
+
providerOptions?: Record<string, unknown>;
|
|
737
|
+
/** Optional AI SDK telemetry configuration for this turn. */
|
|
738
|
+
experimental_telemetry?: Parameters<
|
|
739
|
+
typeof streamText
|
|
740
|
+
>[0]["experimental_telemetry"];
|
|
794
741
|
/**
|
|
795
|
-
*
|
|
796
|
-
*
|
|
797
|
-
*
|
|
798
|
-
*
|
|
799
|
-
*
|
|
800
|
-
*
|
|
742
|
+
* Optional structured-output specification (AI SDK `output`).
|
|
743
|
+
* Forwarded to `streamText` so the model's final response is parsed
|
|
744
|
+
* against the supplied schema. Use the AI SDK's `Output.object({ schema })`
|
|
745
|
+
* / `Output.text()` helpers. Combine with `activeTools: []` on the
|
|
746
|
+
* terminal turn if your provider strips tools when structured output
|
|
747
|
+
* is active (e.g. workers-ai-provider).
|
|
801
748
|
*/
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
749
|
+
output?: Parameters<typeof streamText>[0]["output"];
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Provider-agnostic semantic classification of a chat-turn error.
|
|
753
|
+
*
|
|
754
|
+
* Think ships **no** provider-specific string/code matching — the app owns
|
|
755
|
+
* that knowledge (it knows which provider/model it talks to), exactly like the
|
|
756
|
+
* `tokenCounter` it already passes to `compactAfter()`. An app teaches Think
|
|
757
|
+
* what an error *means* by overriding `classifyChatError()`; Think then reacts
|
|
758
|
+
* generically (e.g. compact-and-retry on `context_overflow`).
|
|
759
|
+
*
|
|
760
|
+
* - `context_overflow` — the prompt exceeded the model's context window
|
|
761
|
+
* (Anthropic `"prompt is too long"`, OpenAI `context_length_exceeded`, …).
|
|
762
|
+
* The only category Think currently acts on (auto-compact + retry).
|
|
763
|
+
* - `rate_limit` / `transient` — reserved for future backoff/retry policies.
|
|
764
|
+
* - `fatal` — unrecoverable; surface terminally.
|
|
765
|
+
* - `unknown` — default; Think applies its existing terminal behavior.
|
|
766
|
+
*/
|
|
767
|
+
type ChatErrorClassification =
|
|
768
|
+
| "context_overflow"
|
|
769
|
+
| "rate_limit"
|
|
770
|
+
| "transient"
|
|
771
|
+
| "fatal"
|
|
772
|
+
| "unknown";
|
|
773
|
+
/**
|
|
774
|
+
* Opt-in handling for a turn that overflows the model's context window
|
|
775
|
+
* mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a
|
|
776
|
+
* long, tool-heavy turn can grow past the window before the next check; the
|
|
777
|
+
* provider then rejects the request (`"prompt is too long"` /
|
|
778
|
+
* `context_length_exceeded`). Both layers reuse the session's compaction
|
|
779
|
+
* function and are provider-agnostic — the app maps the error via
|
|
780
|
+
* {@link Think.classifyChatError}; Think never matches provider strings itself.
|
|
781
|
+
*
|
|
782
|
+
* Set `Think.contextOverflow` to enable. Leaving it unset disables both layers
|
|
783
|
+
* (existing terminal behavior).
|
|
784
|
+
*/
|
|
785
|
+
interface ContextOverflowConfig {
|
|
805
786
|
/**
|
|
806
|
-
*
|
|
807
|
-
*
|
|
808
|
-
*
|
|
809
|
-
*
|
|
810
|
-
*
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
*
|
|
814
|
-
*
|
|
815
|
-
* repair and the write-side accumulator guard enforce the same invariant.
|
|
787
|
+
* Reactive backstop. When a turn fails with an error classified as
|
|
788
|
+
* `"context_overflow"`, discard the truncated partial, run
|
|
789
|
+
* `session.compact()`, and re-run the turn from the compacted history. The
|
|
790
|
+
* partial is intentionally not persisted: the turn restarts from scratch, so
|
|
791
|
+
* keeping the cut-off assistant message would orphan it beside the recovered
|
|
792
|
+
* answer (and duplicate any tool work the retry re-issues). If compaction
|
|
793
|
+
* cannot shorten history or the retry budget is spent, the overflow surfaces
|
|
794
|
+
* terminally through `onChatError` (classified) — it never loops or ends
|
|
795
|
+
* silently. Default `false`.
|
|
816
796
|
*/
|
|
817
|
-
|
|
797
|
+
reactive?: boolean;
|
|
818
798
|
/**
|
|
819
|
-
*
|
|
820
|
-
*
|
|
821
|
-
*
|
|
822
|
-
* Single source of truth for the terminal tool states, shared by the repair
|
|
823
|
-
* pass and the backstop detector so they cannot drift. Mirror the AI SDK's
|
|
824
|
-
* terminal states: `convertToModelMessages` emits a `tool-result` for
|
|
825
|
-
* `output-available`, `output-error`, AND `output-denied` (a user-denied
|
|
826
|
-
* approval — its denial reason becomes the tool-result). Omitting any of
|
|
827
|
-
* these makes repair re-flip the part every turn — clobbering a real
|
|
828
|
-
* `errorText`/denial with the generic "interrupted" message — and makes the
|
|
829
|
-
* backstop falsely drop a valid call.
|
|
799
|
+
* Maximum compact-and-retry attempts for a single overflowing turn (the
|
|
800
|
+
* reactive backstop). Independent of the proactive guard's cap — see
|
|
801
|
+
* {@link proactive.maxCompactions}. Default `1`.
|
|
830
802
|
*/
|
|
831
|
-
|
|
803
|
+
maxRetries?: number;
|
|
832
804
|
/**
|
|
833
|
-
*
|
|
834
|
-
*
|
|
835
|
-
*
|
|
805
|
+
* Proactive guard. Before each step, read the previous step's model-reported
|
|
806
|
+
* `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,
|
|
807
|
+
* compact in place and feed the recompacted history into the upcoming step —
|
|
808
|
+
* heading off the provider rejection before it happens. Keys off usage (every
|
|
809
|
+
* provider reports it), not provider error strings. Unset disables it.
|
|
836
810
|
*
|
|
837
|
-
*
|
|
838
|
-
*
|
|
839
|
-
*
|
|
840
|
-
*
|
|
841
|
-
*
|
|
842
|
-
*
|
|
811
|
+
* If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`
|
|
812
|
+
* (input + output) — a safe over-approximation that compacts slightly early
|
|
813
|
+
* rather than missing the threshold. If neither is reported, the guard does
|
|
814
|
+
* nothing that step (the reactive backstop still catches a genuine overflow).
|
|
815
|
+
*
|
|
816
|
+
* `maxCompactions` caps how many times the guard may compact within a single
|
|
817
|
+
* step loop (default `1`, floored at `1`). It is independent of
|
|
818
|
+
* {@link maxRetries} (the reactive budget): a no-op compaction would repeat on
|
|
819
|
+
* every step, so the cap stops the guard from compacting (and emitting
|
|
820
|
+
* `chat:context:compacted`) on each one.
|
|
843
821
|
*/
|
|
844
|
-
|
|
822
|
+
proactive?: {
|
|
823
|
+
maxInputTokens: number;
|
|
824
|
+
headroom?: number;
|
|
825
|
+
maxCompactions?: number;
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* Opt-in default classifier for {@link Think.classifyChatError}. Matches the
|
|
830
|
+
* context-window-overflow error messages of the common providers (Anthropic,
|
|
831
|
+
* OpenAI, Google, Bedrock, Mistral, …) and returns `"context_overflow"`.
|
|
832
|
+
*
|
|
833
|
+
* Think ships this as an explicitly-imported helper rather than wiring it into
|
|
834
|
+
* core, so the framework default stays free of provider strings. Assign it (or
|
|
835
|
+
* delegate to it) when you do not need custom classification:
|
|
836
|
+
*
|
|
837
|
+
* @example
|
|
838
|
+
* ```typescript
|
|
839
|
+
* import { Think, defaultContextOverflowClassifier } from "@cloudflare/think";
|
|
840
|
+
*
|
|
841
|
+
* export class MyAgent extends Think<Env> {
|
|
842
|
+
* override contextOverflow = { reactive: true };
|
|
843
|
+
* override classifyChatError = defaultContextOverflowClassifier;
|
|
844
|
+
* }
|
|
845
|
+
* ```
|
|
846
|
+
*
|
|
847
|
+
* Or combine with your own checks:
|
|
848
|
+
*
|
|
849
|
+
* @example
|
|
850
|
+
* ```typescript
|
|
851
|
+
* override classifyChatError(error: unknown): ChatErrorClassification | void {
|
|
852
|
+
* if (isMyRateLimit(error)) return "rate_limit";
|
|
853
|
+
* return defaultContextOverflowClassifier(error);
|
|
854
|
+
* }
|
|
855
|
+
* ```
|
|
856
|
+
*/
|
|
857
|
+
declare function defaultContextOverflowClassifier(
|
|
858
|
+
error: unknown
|
|
859
|
+
): ChatErrorClassification | undefined;
|
|
860
|
+
interface ChatErrorContext {
|
|
861
|
+
requestId?: string;
|
|
862
|
+
stage: "parse" | "persist" | "turn" | "stream" | "recovery" | "transcript";
|
|
863
|
+
messagesPersisted?: boolean;
|
|
845
864
|
/**
|
|
846
|
-
*
|
|
847
|
-
*
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
*
|
|
851
|
-
* The default flips it to an errored tool result so the record survives (no
|
|
852
|
-
* "disappearing" tool call) and `convertToModelMessages` still gets a
|
|
853
|
-
* tool-result for it (avoiding `AI_MissingToolResultsError`).
|
|
854
|
-
*
|
|
855
|
-
* Override to customize the repaired shape for client-resolved tools — e.g.
|
|
856
|
-
* convert an interrupted `ask_user` (a question with no server `execute`,
|
|
857
|
-
* normally answered by the user's next message) into a plain text part
|
|
858
|
-
* carrying the question prose, so the model sees it as ordinary conversation
|
|
859
|
-
* rather than a tool error and compaction keeps the question verbatim. This
|
|
860
|
-
* runs DURING transcript repair — before the repaired transcript is persisted
|
|
861
|
-
* and sent to the model — so the conversion shapes the current turn, not just
|
|
862
|
-
* the next one. A returned tool part MUST carry a settled result
|
|
863
|
-
* (`output-available` / `output-error` / `output-denied` or an
|
|
864
|
-
* `output`/`result` field); returning a non-tool part (e.g. text) is fine.
|
|
865
|
+
* App-provided semantic classification (from `classifyChatError`), when
|
|
866
|
+
* known. Lets `onChatError` overrides and observers distinguish e.g. a
|
|
867
|
+
* context-overflow from a generic provider failure without re-matching
|
|
868
|
+
* provider strings.
|
|
865
869
|
*/
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
870
|
+
classification?: ChatErrorClassification;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Context passed to the `beforeStep` hook before each AI SDK step in
|
|
874
|
+
* the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`
|
|
875
|
+
* parameter — exposes the previous `steps`, the zero-based `stepNumber`,
|
|
876
|
+
* the currently selected `model`, the `messages` about to be sent, and
|
|
877
|
+
* `experimental_context`.
|
|
878
|
+
*
|
|
879
|
+
* Pass an explicit `TOOLS` generic for typed previous tool calls / results.
|
|
880
|
+
*
|
|
881
|
+
* Limitations (AI SDK boundary, not Think):
|
|
882
|
+
* - No `abortSignal` is exposed in the context. If you do remote work
|
|
883
|
+
* inside `beforeStep`, it cannot be cancelled by turn-level abort.
|
|
884
|
+
* - `experimental_context` is typed `unknown`; users must narrow it.
|
|
885
|
+
* - `output` cannot be overridden per-step — set it at the turn level
|
|
886
|
+
* via `TurnConfig.output` (returned from `beforeTurn`).
|
|
887
|
+
*/
|
|
888
|
+
type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
889
|
+
PrepareStepFunction<TOOLS>
|
|
890
|
+
>[0];
|
|
891
|
+
/**
|
|
892
|
+
* Configuration returned by `beforeStep` to override defaults for the
|
|
893
|
+
* current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —
|
|
894
|
+
* return only the fields you want to override (`model`, `toolChoice`,
|
|
895
|
+
* `activeTools`, `system`, `messages`, `experimental_context`,
|
|
896
|
+
* `providerOptions`).
|
|
897
|
+
*/
|
|
898
|
+
type StepConfig<TOOLS extends ToolSet = ToolSet> = PrepareStepResult<TOOLS>;
|
|
899
|
+
/**
|
|
900
|
+
* Context passed to the `beforeToolCall` hook **before** the tool's
|
|
901
|
+
* `execute` function runs.
|
|
902
|
+
*
|
|
903
|
+
* Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of
|
|
904
|
+
* `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`
|
|
905
|
+
* fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the
|
|
906
|
+
* dynamic/invalid/error discriminators) are spread at the top level for
|
|
907
|
+
* convenience, with the per-call event extras attached:
|
|
908
|
+
*
|
|
909
|
+
* - `stepNumber` — index of the current step
|
|
910
|
+
* - `messages` — conversation messages visible at tool execution time
|
|
911
|
+
* - `abortSignal` — signal that aborts if the turn is cancelled
|
|
912
|
+
*
|
|
913
|
+
* Pass an explicit `TOOLS` generic for full input typing:
|
|
914
|
+
*
|
|
915
|
+
* ```ts
|
|
916
|
+
* import type { ToolCallContext } from "@cloudflare/think";
|
|
917
|
+
* import type { tools } from "./my-tools";
|
|
918
|
+
*
|
|
919
|
+
* beforeToolCall(ctx: ToolCallContext<typeof tools>) {
|
|
920
|
+
* if (ctx.toolName === "search") {
|
|
921
|
+
* ctx.input.query; // typed
|
|
922
|
+
* }
|
|
923
|
+
* }
|
|
924
|
+
* ```
|
|
925
|
+
*/
|
|
926
|
+
type ToolCallContext<TOOLS extends ToolSet = ToolSet> = TypedToolCall<TOOLS> & {
|
|
927
|
+
/** Zero-based index of the current step where this tool call occurs. */ readonly stepNumber:
|
|
928
|
+
| number
|
|
929
|
+
| undefined /** The conversation messages available at tool execution time. */;
|
|
930
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Signal for cancelling the operation. */;
|
|
931
|
+
readonly abortSignal: AbortSignal | undefined;
|
|
932
|
+
};
|
|
933
|
+
/**
|
|
934
|
+
* Decision returned by `beforeToolCall` to control tool execution.
|
|
935
|
+
* Return void/undefined to allow execution with original input.
|
|
936
|
+
*
|
|
937
|
+
* Discriminated union — each action has a clear, non-overlapping meaning:
|
|
938
|
+
* - `allow` — execute the tool (optionally with modified input)
|
|
939
|
+
* - `block` — don't execute; return `reason` as the tool result so the model can adjust
|
|
940
|
+
* - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)
|
|
941
|
+
*/
|
|
942
|
+
type ToolCallDecision =
|
|
943
|
+
| {
|
|
944
|
+
action: "allow" /** Modified input — tool executes with this instead of the original. */;
|
|
945
|
+
input?: Record<string, unknown>;
|
|
946
|
+
}
|
|
947
|
+
| {
|
|
948
|
+
action: "block" /** Returned as the tool result so the model can adjust. */;
|
|
949
|
+
reason?: string;
|
|
950
|
+
}
|
|
951
|
+
| {
|
|
952
|
+
action: "substitute" /** The substitute tool output — model sees this instead of real execution. */;
|
|
953
|
+
output: unknown /** Optional input attribution for the afterToolCall log. */;
|
|
954
|
+
input?: Record<string, unknown>;
|
|
955
|
+
};
|
|
956
|
+
/**
|
|
957
|
+
* Context passed to the `afterToolCall` hook after a tool executes.
|
|
958
|
+
*
|
|
959
|
+
* Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of
|
|
960
|
+
* `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`
|
|
961
|
+
* fields (`toolName`, `toolCallId`, `input`, …) are spread at the top
|
|
962
|
+
* level, plus the per-call event extras:
|
|
963
|
+
*
|
|
964
|
+
* - `stepNumber` — index of the current step
|
|
965
|
+
* - `messages` — conversation messages visible at tool execution time
|
|
966
|
+
* - `durationMs` — wall-clock execution time in milliseconds
|
|
967
|
+
* - `success`/`output`/`error` — discriminated outcome:
|
|
968
|
+
* - on success: `success: true`, `output: unknown`
|
|
969
|
+
* - on failure: `success: false`, `error: unknown`
|
|
970
|
+
*
|
|
971
|
+
* Pass an explicit `TOOLS` generic for full input typing:
|
|
972
|
+
*
|
|
973
|
+
* ```ts
|
|
974
|
+
* import type { ToolCallResultContext } from "@cloudflare/think";
|
|
975
|
+
* import type { tools } from "./my-tools";
|
|
976
|
+
*
|
|
977
|
+
* afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
|
|
978
|
+
* if (ctx.success) {
|
|
979
|
+
* console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);
|
|
980
|
+
* } else {
|
|
981
|
+
* console.error(`${ctx.toolName} failed:`, ctx.error);
|
|
982
|
+
* }
|
|
983
|
+
* }
|
|
984
|
+
* ```
|
|
985
|
+
*/
|
|
986
|
+
type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =
|
|
987
|
+
TypedToolCall<TOOLS> & {
|
|
988
|
+
readonly stepNumber: number | undefined;
|
|
989
|
+
readonly messages: ReadonlyArray<ModelMessage> /** Wall-clock execution time in milliseconds. */;
|
|
990
|
+
readonly durationMs: number;
|
|
991
|
+
} & (
|
|
992
|
+
| {
|
|
993
|
+
readonly success: true;
|
|
994
|
+
readonly output: unknown;
|
|
995
|
+
readonly error?: never;
|
|
996
|
+
}
|
|
997
|
+
| {
|
|
998
|
+
readonly success: false;
|
|
999
|
+
readonly output?: never;
|
|
1000
|
+
readonly error: unknown;
|
|
1001
|
+
}
|
|
1002
|
+
);
|
|
1003
|
+
/**
|
|
1004
|
+
* Context passed to the `onStepFinish` hook after each step completes.
|
|
1005
|
+
*
|
|
1006
|
+
* This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —
|
|
1007
|
+
* the full step record including `text`, `reasoning`, `toolCalls`,
|
|
1008
|
+
* `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,
|
|
1009
|
+
* `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,
|
|
1010
|
+
* `response`, and `providerMetadata` (where provider-specific cache
|
|
1011
|
+
* accounting like `cacheCreationInputTokens` lives).
|
|
1012
|
+
*
|
|
1013
|
+
* Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.
|
|
1014
|
+
*/
|
|
1015
|
+
type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
1016
|
+
StreamTextOnStepFinishCallback<TOOLS>
|
|
1017
|
+
>[0];
|
|
1018
|
+
/**
|
|
1019
|
+
* Context passed to the `onChunk` hook for each streaming chunk.
|
|
1020
|
+
*
|
|
1021
|
+
* This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`
|
|
1022
|
+
* where `chunk` is a discriminated union of `TextStreamPart` variants
|
|
1023
|
+
* (text-delta, reasoning-delta, source, tool-call, tool-input-start,
|
|
1024
|
+
* tool-input-delta, tool-result, raw).
|
|
1025
|
+
*/
|
|
1026
|
+
type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<
|
|
1027
|
+
StreamTextOnChunkCallback<TOOLS>
|
|
1028
|
+
>[0];
|
|
1029
|
+
/**
|
|
1030
|
+
* @internal Re-export of the chunk variant union for consumers that need
|
|
1031
|
+
* to narrow on `chunk.type` without importing `TextStreamPart` directly.
|
|
1032
|
+
*/
|
|
1033
|
+
type ChunkPart<TOOLS extends ToolSet = ToolSet> = ChunkContext<TOOLS>["chunk"];
|
|
1034
|
+
/**
|
|
1035
|
+
* Configuration for a sandboxed extension, returned by getExtensions().
|
|
1036
|
+
*/
|
|
1037
|
+
interface ExtensionConfig {
|
|
1038
|
+
/** Extension manifest (name, version, permissions, contributions). */
|
|
1039
|
+
manifest: ExtensionManifest;
|
|
1040
|
+
/** JavaScript source code defining the extension's tools. */
|
|
1041
|
+
source: string;
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* An opinionated chat agent base class.
|
|
1045
|
+
*
|
|
1046
|
+
* @experimental The API surface may change before stabilizing.
|
|
1047
|
+
*/
|
|
1048
|
+
declare class Think<
|
|
1049
|
+
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
1050
|
+
State = unknown,
|
|
1051
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
1052
|
+
> extends Agent<Env, State, Props> {
|
|
1053
|
+
#private;
|
|
1054
|
+
private _activeChatRecoveryRootRequestId;
|
|
1055
|
+
private static readonly CONFIG_KEYS;
|
|
927
1056
|
/**
|
|
928
|
-
*
|
|
929
|
-
*
|
|
930
|
-
* survives
|
|
931
|
-
* restarts and hibernation. Pass the config shape as a method generic
|
|
932
|
-
* for typed call sites:
|
|
933
|
-
*
|
|
934
|
-
* ```ts
|
|
935
|
-
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
936
|
-
* ```
|
|
1057
|
+
* Wait for MCP server connections to be ready before the inference
|
|
1058
|
+
* loop. MCP tools are auto-merged into the tool set.
|
|
937
1059
|
*
|
|
938
|
-
*
|
|
939
|
-
*
|
|
940
|
-
* per-instance config that should stay server-side.
|
|
1060
|
+
* Set to `true` for a default 10s timeout, or `{ timeout: ms }`
|
|
1061
|
+
* for a custom timeout. Defaults to `false` (no waiting).
|
|
941
1062
|
*/
|
|
942
|
-
|
|
1063
|
+
waitForMcpConnections:
|
|
1064
|
+
| boolean
|
|
1065
|
+
| {
|
|
1066
|
+
timeout: number;
|
|
1067
|
+
};
|
|
1068
|
+
private _skillRegistry;
|
|
1069
|
+
private _loggedSkillWarnings;
|
|
943
1070
|
/**
|
|
944
|
-
*
|
|
945
|
-
*
|
|
1071
|
+
* Controls how overlapping user submit requests behave while another
|
|
1072
|
+
* chat turn is already active or queued.
|
|
946
1073
|
*
|
|
947
|
-
*
|
|
948
|
-
* const cfg = this.getConfig<MyConfig>();
|
|
949
|
-
* ```
|
|
1074
|
+
* @default "queue"
|
|
950
1075
|
*/
|
|
951
|
-
|
|
952
|
-
protected _migrateLegacyConfigToThinkTable(): void;
|
|
953
|
-
private _ensureConfigTable;
|
|
954
|
-
private _configSet;
|
|
955
|
-
private _configGet;
|
|
956
|
-
private _configDelete;
|
|
1076
|
+
messageConcurrency: MessageConcurrency;
|
|
957
1077
|
/**
|
|
958
|
-
*
|
|
959
|
-
*
|
|
1078
|
+
* When true, chat turns are wrapped in `runFiber` for durable execution.
|
|
1079
|
+
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
1080
|
+
*
|
|
1081
|
+
* Assign this as a class field or in the constructor — NOT in `onStart()`.
|
|
1082
|
+
* On every wake the SDK evaluates recovery budgets (and may seal an
|
|
1083
|
+
* interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config
|
|
1084
|
+
* set in `onStart()` is applied too late and the built-in defaults are used
|
|
1085
|
+
* for the recovery that matters. See {@link ChatRecoveryConfig}.
|
|
960
1086
|
*/
|
|
961
|
-
|
|
1087
|
+
chatRecovery: ChatRecoveryConfig;
|
|
1088
|
+
static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
962
1089
|
/**
|
|
963
|
-
*
|
|
964
|
-
*
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
1090
|
+
* The conversation session — messages, context, compaction, search.
|
|
1091
|
+
*
|
|
1092
|
+
* Direct message writes are observed and mirrored into Think's live cache.
|
|
1093
|
+
* Prefer the history helpers below when writing UI messages from subclasses;
|
|
1094
|
+
* they sanitize content and enforce row-size limits before delegating here.
|
|
1095
|
+
*/
|
|
1096
|
+
session: Session;
|
|
1097
|
+
/** Cached messages — kept in sync with session storage. */
|
|
1098
|
+
private _cachedMessages;
|
|
1099
|
+
private _activeMessengerContext?;
|
|
1100
|
+
private _messengerRuntime?;
|
|
1101
|
+
/**
|
|
1102
|
+
* WorkerLoader binding for sandboxed extensions.
|
|
1103
|
+
* Set this to enable `getExtensions()` and dynamic extension loading.
|
|
1104
|
+
*/
|
|
1105
|
+
extensionLoader?: WorkerLoader;
|
|
1106
|
+
/**
|
|
1107
|
+
* Extension manager — created automatically when `extensionLoader` is set.
|
|
1108
|
+
* Use for dynamic `load()` / `unload()` at runtime.
|
|
1109
|
+
*/
|
|
1110
|
+
extensionManager?: ExtensionManager;
|
|
1111
|
+
/**
|
|
1112
|
+
* Workspace filesystem available in `getTools()` and lifecycle hooks.
|
|
1113
|
+
* Defaults to a full `Workspace` backed by the DO's SQLite storage.
|
|
1114
|
+
*
|
|
1115
|
+
* Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
|
|
1116
|
+
* replace it with anything that satisfies the interface — e.g. a proxy
|
|
1117
|
+
* that forwards to a shared workspace owned by a parent DO. Override as
|
|
1118
|
+
* a class field to skip the default init entirely:
|
|
1119
|
+
*
|
|
1120
|
+
* ```typescript
|
|
1121
|
+
* // Default init with R2 spillover for large files.
|
|
1122
|
+
* override workspace = new Workspace({
|
|
1123
|
+
* sql: this.ctx.storage.sql,
|
|
1124
|
+
* r2: this.env.R2,
|
|
1125
|
+
* name: () => this.name
|
|
1126
|
+
* });
|
|
1127
|
+
*
|
|
1128
|
+
* // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
|
|
1129
|
+
* override workspace: WorkspaceLike = new SharedWorkspace(this);
|
|
1130
|
+
* ```
|
|
1131
|
+
*/
|
|
1132
|
+
workspace: WorkspaceLike;
|
|
1133
|
+
/**
|
|
1134
|
+
* Include the default workspace Bash tool. Enabled by default so models can
|
|
1135
|
+
* run shell-style multi-file workflows against the workspace. Set to `false`
|
|
1136
|
+
* to omit it from the built-in workspace tools.
|
|
1137
|
+
*/
|
|
1138
|
+
workspaceBash:
|
|
1139
|
+
| boolean
|
|
1140
|
+
| NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
|
|
1141
|
+
constructor(ctx: DurableObjectState, env: Env);
|
|
1142
|
+
/**
|
|
1143
|
+
* Conversation history as Think's live in-memory view.
|
|
1144
|
+
*
|
|
1145
|
+
* Storage remains the durable source of truth, but runtime logic should read
|
|
1146
|
+
* through this cache so in-flight turns, tool updates, and recovery state all
|
|
1147
|
+
* observe the same message list. Use `_syncMessages()` only at safe
|
|
1148
|
+
* boundaries where a full storage reread cannot drop in-flight state.
|
|
1149
|
+
*/
|
|
1150
|
+
get messages(): UIMessage[];
|
|
1151
|
+
/** Read the durable message path from session storage. */
|
|
1152
|
+
private _readMessagesFromStorage;
|
|
1153
|
+
/**
|
|
1154
|
+
* Normalize a tool part's `input` into something the provider will accept.
|
|
1155
|
+
*
|
|
1156
|
+
* Malformed shapes 400 modern providers and persist forever once written:
|
|
1157
|
+
* a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
|
|
1158
|
+
* object), and any non-object `input` — `null`, `undefined`, `""`, an array,
|
|
1159
|
+
* or a primitive — on a settled or interrupted tool call (Anthropic rejects
|
|
1160
|
+
* a `tool_use` block whose `input` is not an object). We parse the former and
|
|
1161
|
+
* default the latter to an empty object so the tool-call/tool-result pair
|
|
1162
|
+
* stays valid. Delegates to the shared `normalizeToolInput` so the read-side
|
|
1163
|
+
* repair and the write-side accumulator guard enforce the same invariant.
|
|
1164
|
+
*/
|
|
1165
|
+
private _normalizeToolInput;
|
|
1166
|
+
/**
|
|
1167
|
+
* Whether a tool part already has a settled result the provider accepts, so
|
|
1168
|
+
* it must NOT be re-repaired into an errored result.
|
|
1169
|
+
*
|
|
1170
|
+
* Single source of truth for the terminal tool states, shared by the repair
|
|
1171
|
+
* pass and the backstop detector so they cannot drift. Mirror the AI SDK's
|
|
1172
|
+
* terminal states: `convertToModelMessages` emits a `tool-result` for
|
|
1173
|
+
* `output-available`, `output-error`, AND `output-denied` (a user-denied
|
|
1174
|
+
* approval — its denial reason becomes the tool-result). Omitting any of
|
|
1175
|
+
* these makes repair re-flip the part every turn — clobbering a real
|
|
1176
|
+
* `errorText`/denial with the generic "interrupted" message — and makes the
|
|
1177
|
+
* backstop falsely drop a valid call.
|
|
1178
|
+
*/
|
|
1179
|
+
private _toolPartHasSettledResult;
|
|
1180
|
+
/**
|
|
1181
|
+
* Tool-call ids that still have no recorded result. After repair this should
|
|
1182
|
+
* be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
|
|
1183
|
+
* will drop those calls — i.e. repair missed a shape and should be extended.
|
|
1184
|
+
*
|
|
1185
|
+
* `approval-responded` is deliberately excluded: an approved server tool has
|
|
1186
|
+
* no result *yet*, but it is not incomplete or abandoned — it is waiting for
|
|
1187
|
+
* its continuation to run `execute()`. `convertToModelMessages` keeps that
|
|
1188
|
+
* call (and the SDK executes it), so flagging it here would log a misleading
|
|
1189
|
+
* "repair gap" warning and emit a spurious `chat:transcript:repaired` event
|
|
1190
|
+
* on every approval continuation.
|
|
1191
|
+
*/
|
|
1192
|
+
private _incompleteToolCallIds;
|
|
1193
|
+
/**
|
|
1194
|
+
* Repair a single interrupted tool call — a tool part with no settled result,
|
|
1195
|
+
* left behind when a stream was cut off mid-flight. Returns the replacement
|
|
1196
|
+
* part that takes its place in the transcript. `input` has already been
|
|
1197
|
+
* normalized to a valid object.
|
|
1198
|
+
*
|
|
1199
|
+
* The default flips it to an errored tool result so the record survives (no
|
|
1200
|
+
* "disappearing" tool call) and `convertToModelMessages` still gets a
|
|
1201
|
+
* tool-result for it (avoiding `AI_MissingToolResultsError`).
|
|
1202
|
+
*
|
|
1203
|
+
* Override to customize the repaired shape for client-resolved tools — e.g.
|
|
1204
|
+
* convert an interrupted `ask_user` (a question with no server `execute`,
|
|
1205
|
+
* normally answered by the user's next message) into a plain text part
|
|
1206
|
+
* carrying the question prose, so the model sees it as ordinary conversation
|
|
1207
|
+
* rather than a tool error and compaction keeps the question verbatim. This
|
|
1208
|
+
* runs DURING transcript repair — before the repaired transcript is persisted
|
|
1209
|
+
* and sent to the model — so the conversion shapes the current turn, not just
|
|
1210
|
+
* the next one. A returned tool part MUST carry a settled result
|
|
1211
|
+
* (`output-available` / `output-error` / `output-denied` or an
|
|
1212
|
+
* `output`/`result` field); returning a non-tool part (e.g. text) is fine.
|
|
1213
|
+
*/
|
|
1214
|
+
protected repairInterruptedToolPart(
|
|
1215
|
+
part: UIMessage["parts"][number]
|
|
1216
|
+
): UIMessage["parts"][number];
|
|
1217
|
+
private _repairToolTranscriptParts;
|
|
1218
|
+
private _repairTranscriptForProvider;
|
|
1219
|
+
/** Replace the live cache with a durable storage snapshot. */
|
|
1220
|
+
private _replaceCachedMessages;
|
|
1221
|
+
/** Refresh the live cache from durable storage at a safe boundary. */
|
|
1222
|
+
private _syncMessages;
|
|
1223
|
+
/** Patch or append one message in the live cache after a durable write. */
|
|
1224
|
+
private _upsertCachedMessage;
|
|
1225
|
+
/** Patch a message that is already present in the live cache. */
|
|
1226
|
+
private _patchCachedMessage;
|
|
1227
|
+
private _appendMessageToHistory;
|
|
1228
|
+
private _updateMessageInHistory;
|
|
1229
|
+
private _upsertMessageInHistory;
|
|
1230
|
+
private _clearHistory;
|
|
1231
|
+
/** Append a message while keeping Think's live message cache coherent. */
|
|
1232
|
+
protected appendMessageToHistory(
|
|
1233
|
+
message: UIMessage,
|
|
1234
|
+
parentId?: string | null
|
|
1235
|
+
): Promise<UIMessage>;
|
|
1236
|
+
/** Update a message while keeping Think's live message cache coherent. */
|
|
1237
|
+
protected updateMessageInHistory(message: UIMessage): Promise<UIMessage>;
|
|
1238
|
+
/** Refresh Think's live message cache from the durable session path. */
|
|
1239
|
+
protected syncMessagesFromStorage(): Promise<UIMessage[]>;
|
|
1240
|
+
private _aborts;
|
|
1241
|
+
private _turnQueue;
|
|
1242
|
+
protected _resumableStream: ResumableStream;
|
|
1243
|
+
private _pendingResumeConnections;
|
|
1244
|
+
private _lastClientTools;
|
|
1245
|
+
private _lastBody;
|
|
1246
|
+
private _continuation;
|
|
1247
|
+
private _continuationTimer;
|
|
1248
|
+
private _continuationBarrierActive;
|
|
1249
|
+
private _insideResponseHook;
|
|
1250
|
+
private _insideInferenceLoop;
|
|
1251
|
+
private _pendingInteractionPromise;
|
|
1252
|
+
private _interactionApplyTail;
|
|
1253
|
+
private _streamingAssistant;
|
|
1254
|
+
private _submitConcurrency;
|
|
1255
|
+
private static MESSAGE_DEBOUNCE_MS;
|
|
1256
|
+
private _agentToolForwarders;
|
|
1257
|
+
private _agentToolClosers;
|
|
1258
|
+
private _agentToolAbortControllers;
|
|
1259
|
+
private _agentToolLastErrors;
|
|
1260
|
+
private _agentToolPreTurnAssistantIds;
|
|
1261
|
+
private _agentToolLiveSequences;
|
|
1262
|
+
private _submissionTableEnsured;
|
|
1263
|
+
private _workflowNotificationTableEnsured;
|
|
1264
|
+
private _declaredScheduledTasksTableEnsured;
|
|
1265
|
+
private _drainingSubmissions;
|
|
1266
|
+
private _drainingWorkflowNotifications;
|
|
1267
|
+
private _submissionAbortControllers;
|
|
1268
|
+
private _programmaticStreamErrors;
|
|
1269
|
+
protected static submissionRecoveryStaleMs: number;
|
|
1270
|
+
broadcast(
|
|
1271
|
+
msg: string | ArrayBuffer | ArrayBufferView,
|
|
1272
|
+
without?: string[]
|
|
1273
|
+
): void;
|
|
1274
|
+
alarm(): Promise<void>;
|
|
1275
|
+
/**
|
|
1276
|
+
* Persist an arbitrary JSON-serializable configuration object for this
|
|
1277
|
+
* agent instance. Stored in the Think-private `think_config` table —
|
|
1278
|
+
* survives
|
|
1279
|
+
* restarts and hibernation. Pass the config shape as a method generic
|
|
1280
|
+
* for typed call sites:
|
|
1281
|
+
*
|
|
1282
|
+
* ```ts
|
|
1283
|
+
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
1284
|
+
* ```
|
|
1285
|
+
*
|
|
1286
|
+
* Prefer `state` / `setState` from `Agent` when you want the value
|
|
1287
|
+
* broadcast to connected clients. Use `configure` for private
|
|
1288
|
+
* per-instance config that should stay server-side.
|
|
1289
|
+
*/
|
|
1290
|
+
configure<T = Record<string, unknown>>(config: T): void;
|
|
1291
|
+
/**
|
|
1292
|
+
* Read the persisted configuration, or null if never configured.
|
|
1293
|
+
* Pass the config shape as a method generic for a typed result:
|
|
1294
|
+
*
|
|
1295
|
+
* ```ts
|
|
1296
|
+
* const cfg = this.getConfig<MyConfig>();
|
|
1297
|
+
* ```
|
|
1298
|
+
*/
|
|
1299
|
+
getConfig<T = Record<string, unknown>>(): T | null;
|
|
1300
|
+
protected _migrateLegacyConfigToThinkTable(): void;
|
|
1301
|
+
private _ensureConfigTable;
|
|
1302
|
+
private _configSet;
|
|
1303
|
+
private _configGet;
|
|
1304
|
+
private _configDelete;
|
|
1305
|
+
/**
|
|
1306
|
+
* Return the language model to use for inference.
|
|
1307
|
+
* Must be overridden by subclasses.
|
|
1308
|
+
*/
|
|
1309
|
+
getModel(): LanguageModel;
|
|
1310
|
+
/**
|
|
1311
|
+
* Return the system prompt for the assistant.
|
|
1312
|
+
* Used as fallback when no context blocks are configured via `configureSession`.
|
|
1313
|
+
*/
|
|
1314
|
+
getSystemPrompt(): string;
|
|
1315
|
+
/** Return the tools available to the assistant. */
|
|
968
1316
|
getTools(): ToolSet;
|
|
969
1317
|
/** Return messenger integrations that should be routed through this Think agent. */
|
|
970
1318
|
getMessengers(): ThinkMessengers;
|
|
@@ -2259,466 +2607,118 @@ declare class Think<
|
|
|
2259
2607
|
private _broadcastMessages;
|
|
2260
2608
|
}
|
|
2261
2609
|
//#endregion
|
|
2262
|
-
//#region src/messengers/events.d.ts
|
|
2263
|
-
type MessengerEventKind =
|
|
2264
|
-
| "direct-message"
|
|
2265
|
-
| "mention"
|
|
2266
|
-
| "subscribed-message"
|
|
2267
|
-
| "action"
|
|
2268
|
-
| "delivery-event";
|
|
2269
|
-
interface MessengerAuthor {
|
|
2270
|
-
fullName?: string;
|
|
2271
|
-
isBot?: boolean | "unknown";
|
|
2272
|
-
isMe?: boolean;
|
|
2273
|
-
userId: string;
|
|
2274
|
-
userName?: string;
|
|
2275
|
-
}
|
|
2276
|
-
interface MessengerAttachment {
|
|
2277
|
-
data?: ArrayBuffer;
|
|
2278
|
-
fetch?: () => Promise<ArrayBuffer>;
|
|
2279
|
-
id?: string;
|
|
2280
|
-
mediaType?: string;
|
|
2281
|
-
name?: string;
|
|
2282
|
-
raw?: unknown;
|
|
2283
|
-
size?: number;
|
|
2284
|
-
text?: string;
|
|
2285
|
-
url?: string;
|
|
2286
|
-
}
|
|
2287
|
-
interface MessengerThread {
|
|
2288
|
-
channelId?: string;
|
|
2289
|
-
channelName?: string;
|
|
2290
|
-
id: string;
|
|
2291
|
-
isDirectMessage: boolean;
|
|
2292
|
-
providerThreadId: string;
|
|
2293
|
-
title?: string;
|
|
2294
|
-
}
|
|
2295
|
-
interface MessengerMessage {
|
|
2296
|
-
attachments: MessengerAttachment[];
|
|
2297
|
-
author: MessengerAuthor;
|
|
2298
|
-
createdAt?: Date;
|
|
2299
|
-
id: string;
|
|
2300
|
-
isMention?: boolean;
|
|
2301
|
-
providerMessageId: string;
|
|
2302
|
-
raw?: unknown;
|
|
2303
|
-
text: string;
|
|
2304
|
-
}
|
|
2305
|
-
interface MessengerAction {
|
|
2306
|
-
actionId: string;
|
|
2307
|
-
messageId?: string;
|
|
2308
|
-
raw?: unknown;
|
|
2309
|
-
user?: MessengerAuthor;
|
|
2310
|
-
value?: string;
|
|
2311
|
-
}
|
|
2312
|
-
interface MessengerCapabilities {
|
|
2313
|
-
canEditMessages?: boolean;
|
|
2314
|
-
canStream?: boolean;
|
|
2315
|
-
maxMessageLength?: number;
|
|
2316
|
-
supportsActions?: boolean;
|
|
2317
|
-
supportsAttachments?: boolean;
|
|
2318
|
-
supportsEphemeral?: boolean;
|
|
2319
|
-
}
|
|
2320
|
-
interface MessengerContext {
|
|
2321
|
-
action?: MessengerAction;
|
|
2322
|
-
author?: MessengerAuthor;
|
|
2323
|
-
capabilities: MessengerCapabilities;
|
|
2324
|
-
kind: MessengerEventKind;
|
|
2325
|
-
message?: MessengerMessage;
|
|
2326
|
-
messengerId: string;
|
|
2327
|
-
provider: string;
|
|
2328
|
-
thread: MessengerThread;
|
|
2329
|
-
}
|
|
2330
|
-
interface MessengerEvent extends MessengerContext {
|
|
2331
|
-
raw?: unknown;
|
|
2332
|
-
}
|
|
2333
|
-
declare function messengerContextFromEvent(
|
|
2334
|
-
event: MessengerEvent
|
|
2335
|
-
): MessengerContext;
|
|
2336
|
-
declare function serializableMessengerEvent(
|
|
2337
|
-
event: MessengerEvent
|
|
2338
|
-
): MessengerEvent;
|
|
2339
|
-
declare function toMessengerUserMessage(event: MessengerEvent): UIMessage;
|
|
2340
|
-
//#endregion
|
|
2341
|
-
//#region src/messengers/delivery.d.ts
|
|
2342
|
-
declare const MESSENGER_REPLY_FIBER_NAME = "think:messenger-reply";
|
|
2343
|
-
declare const EMPTY_MESSENGER_RESPONSE =
|
|
2344
|
-
"I couldn't produce a text response. Please try again.";
|
|
2345
|
-
declare const ERROR_MESSENGER_RESPONSE =
|
|
2346
|
-
"Sorry, I couldn't answer that right now. Please try again.";
|
|
2347
|
-
declare const INTERRUPTED_MESSENGER_RESPONSE =
|
|
2348
|
-
"Sorry, my reply was interrupted. Please send your message again if you'd like me to retry.";
|
|
2349
|
-
interface TextStreamCallbackOptions {
|
|
2350
|
-
onVisibleStart?: () => Promise<void> | void;
|
|
2351
|
-
visibleSoftLimit?: number;
|
|
2352
|
-
}
|
|
2353
|
-
declare class TextStreamCallback extends RpcTarget implements StreamCallback {
|
|
2354
|
-
private readonly onVisibleStart?;
|
|
2355
|
-
private readonly visibleChunks;
|
|
2356
|
-
private readonly wakeups;
|
|
2357
|
-
private readonly visibleSoftLimit?;
|
|
2358
|
-
private chatRequestId?;
|
|
2359
|
-
private closed;
|
|
2360
|
-
private interrupted;
|
|
2361
|
-
private error?;
|
|
2362
|
-
private text;
|
|
2363
|
-
private visibleClosed;
|
|
2364
|
-
private visibleLimitReachedValue;
|
|
2365
|
-
private visibleStarted;
|
|
2366
|
-
private visibleTextValue;
|
|
2367
|
-
constructor(options?: TextStreamCallbackOptions);
|
|
2368
|
-
onStart(event: ChatStartEvent): void;
|
|
2369
|
-
onEvent(json: string): void;
|
|
2370
|
-
onDone(): void;
|
|
2371
|
-
onError(error: string): void;
|
|
2372
|
-
onInterrupted(): void;
|
|
2373
|
-
wasInterrupted(): boolean;
|
|
2374
|
-
close(): void;
|
|
2375
|
-
fail(error: unknown): void;
|
|
2376
|
-
hasText(): boolean;
|
|
2377
|
-
remainingText(): string;
|
|
2378
|
-
requestId(): string | undefined;
|
|
2379
|
-
textSoFar(): string;
|
|
2380
|
-
visibleLimitReached(): boolean;
|
|
2381
|
-
visibleText(): string;
|
|
2382
|
-
stream(): AsyncIterable<string>;
|
|
2383
|
-
private pushVisibleText;
|
|
2384
|
-
private wake;
|
|
2385
|
-
private markVisibleStarted;
|
|
2386
|
-
}
|
|
2387
|
-
declare function textDeltaFromStreamChunk(json: string): string | null;
|
|
2388
|
-
type MessengerReplyStage = "accepted" | "streaming" | "completed";
|
|
2389
|
-
interface MessengerReplySnapshot {
|
|
2390
|
-
event: MessengerEvent;
|
|
2391
|
-
stage: MessengerReplyStage;
|
|
2392
|
-
thread?: unknown;
|
|
2393
|
-
type: typeof MESSENGER_REPLY_FIBER_NAME;
|
|
2394
|
-
}
|
|
2395
|
-
declare function messengerReplySnapshot(
|
|
2396
|
-
stage: MessengerReplyStage,
|
|
2397
|
-
event: MessengerEvent,
|
|
2398
|
-
thread?: unknown
|
|
2399
|
-
): MessengerReplySnapshot;
|
|
2400
|
-
declare function parseMessengerReplySnapshot(
|
|
2401
|
-
snapshot: unknown
|
|
2402
|
-
): MessengerReplySnapshot | null;
|
|
2403
|
-
declare function messengerReplyRecoveryMode(
|
|
2404
|
-
snapshot: MessengerReplySnapshot
|
|
2405
|
-
): "answer" | "apologize" | null;
|
|
2406
|
-
declare function messengerReplyFailureMode(
|
|
2407
|
-
hasStreamedText: boolean,
|
|
2408
|
-
completedModelTurn?: boolean,
|
|
2409
|
-
expectedDeliveryCompletion?: boolean
|
|
2410
|
-
): "apologize" | "error" | null;
|
|
2411
|
-
interface MessengerDeliveryTarget {
|
|
2412
|
-
cancelChat(
|
|
2413
|
-
requestId: string,
|
|
2414
|
-
reason?: string
|
|
2415
|
-
): boolean | void | Promise<boolean | void>;
|
|
2416
|
-
chat(
|
|
2417
|
-
userMessage: string | UIMessage,
|
|
2418
|
-
callback: StreamCallback
|
|
2419
|
-
): Promise<void>;
|
|
2420
|
-
chatWithMessengerContext?(
|
|
2421
|
-
userMessage: string | UIMessage,
|
|
2422
|
-
callback: StreamCallback,
|
|
2423
|
-
context: MessengerEvent
|
|
2424
|
-
): Promise<void>;
|
|
2425
|
-
}
|
|
2426
|
-
interface MessengerDeliverySurface {
|
|
2427
|
-
post(
|
|
2428
|
-
message:
|
|
2429
|
-
| string
|
|
2430
|
-
| {
|
|
2431
|
-
markdown: string;
|
|
2432
|
-
}
|
|
2433
|
-
| AsyncIterable<string>
|
|
2434
|
-
): Promise<unknown>;
|
|
2435
|
-
startTyping?(status?: string): Promise<void>;
|
|
2436
|
-
}
|
|
2437
|
-
interface MessengerDeliveryPolicy {
|
|
2438
|
-
emptyResponseText?: string;
|
|
2439
|
-
errorResponseText?: string;
|
|
2440
|
-
interruptedResponseText?: string;
|
|
2441
|
-
isExpectedDeliveryCompletion?(
|
|
2442
|
-
error: unknown,
|
|
2443
|
-
callback: TextStreamCallback
|
|
2444
|
-
): boolean;
|
|
2445
|
-
splitText?(text: string): string[];
|
|
2446
|
-
visibleSoftLimit?: number;
|
|
2447
|
-
}
|
|
2448
|
-
interface DeliverMessengerReplyOptions {
|
|
2449
|
-
checkpoint?: (snapshot: MessengerReplySnapshot) => Promise<void> | void;
|
|
2450
|
-
event: MessengerEvent;
|
|
2451
|
-
fiber?: FiberContext;
|
|
2452
|
-
policy?: MessengerDeliveryPolicy;
|
|
2453
|
-
snapshotEvent?: MessengerEvent;
|
|
2454
|
-
snapshotThread?: unknown;
|
|
2455
|
-
surface: MessengerDeliverySurface;
|
|
2456
|
-
target: MessengerDeliveryTarget;
|
|
2457
|
-
userMessage?: UIMessage;
|
|
2458
|
-
}
|
|
2459
|
-
declare function deliverMessengerReply(
|
|
2460
|
-
options: DeliverMessengerReplyOptions
|
|
2461
|
-
): Promise<void>;
|
|
2462
|
-
//#endregion
|
|
2463
|
-
//#region src/messengers/chat-sdk.d.ts
|
|
2464
|
-
declare class ThinkMessengerStateAgent extends ChatSdkStateAgent {}
|
|
2465
|
-
type MessengerRespondTo =
|
|
2466
|
-
| "action"
|
|
2467
|
-
| "direct-message"
|
|
2468
|
-
| "mention"
|
|
2469
|
-
| "subscribed-thread";
|
|
2470
|
-
type MessengerConversationMode = "self" | "thread";
|
|
2471
|
-
type MessengerConversationTarget =
|
|
2472
|
-
| {
|
|
2473
|
-
target: "self";
|
|
2474
|
-
}
|
|
2475
|
-
| {
|
|
2476
|
-
agentClass?: SubAgentClass<Agent & MessengerThinkTarget>;
|
|
2477
|
-
name: string;
|
|
2478
|
-
target: "subagent";
|
|
2479
|
-
};
|
|
2480
|
-
type MessengerConversationResolver = (
|
|
2481
|
-
event: MessengerEvent
|
|
2482
|
-
) => MessengerConversationTarget | Promise<MessengerConversationTarget>;
|
|
2483
|
-
interface MessengerDefinition {
|
|
2484
|
-
adapter: Adapter;
|
|
2485
|
-
adapterName: string;
|
|
2486
|
-
capabilities?: MessengerCapabilities;
|
|
2487
|
-
conversation?: MessengerConversationMode | MessengerConversationResolver;
|
|
2488
|
-
delivery?: MessengerDeliveryPolicy;
|
|
2489
|
-
keyShard?: ChatSdkStateAdapterOptions["keyShard"];
|
|
2490
|
-
path?: string;
|
|
2491
|
-
provider: string;
|
|
2492
|
-
respondTo?: readonly MessengerRespondTo[];
|
|
2493
|
-
shardKey?: ChatSdkStateAdapterOptions["shardKey"];
|
|
2494
|
-
subscribeOnMention?: boolean;
|
|
2495
|
-
toEvent?: (
|
|
2496
|
-
input: ChatSdkMessengerEventInput
|
|
2497
|
-
) => MessengerEvent | Promise<MessengerEvent>;
|
|
2498
|
-
userName: string;
|
|
2499
|
-
verifyWebhook?:
|
|
2500
|
-
| false
|
|
2501
|
-
| ((request: Request) => boolean | Response | Promise<boolean | Response>);
|
|
2502
|
-
}
|
|
2503
|
-
type ThinkMessengers = Record<string, MessengerDefinition>;
|
|
2504
|
-
interface NormalizedMessengerDefinition extends MessengerDefinition {
|
|
2505
|
-
id: string;
|
|
2506
|
-
path: string;
|
|
2507
|
-
respondTo: readonly MessengerRespondTo[];
|
|
2508
|
-
subscribeOnMention: boolean;
|
|
2509
|
-
verifyWebhook:
|
|
2510
|
-
| false
|
|
2511
|
-
| ((request: Request) => boolean | Response | Promise<boolean | Response>);
|
|
2512
|
-
}
|
|
2513
|
-
interface ChatSdkMessengerOptions extends Omit<
|
|
2514
|
-
MessengerDefinition,
|
|
2515
|
-
"adapterName"
|
|
2516
|
-
> {
|
|
2517
|
-
adapterName?: string;
|
|
2518
|
-
}
|
|
2519
|
-
interface ChatSdkMessengerEventInput {
|
|
2520
|
-
action?: ActionEvent;
|
|
2521
|
-
eventKind: MessengerEventKind;
|
|
2522
|
-
message?: Message;
|
|
2523
|
-
raw?: unknown;
|
|
2524
|
-
thread: Thread;
|
|
2525
|
-
}
|
|
2526
|
-
interface MessengerThinkTarget {
|
|
2527
|
-
cancelChat(
|
|
2528
|
-
requestId: string,
|
|
2529
|
-
reason?: string
|
|
2530
|
-
): boolean | void | Promise<boolean | void>;
|
|
2531
|
-
chat(
|
|
2532
|
-
userMessage: string | UIMessage,
|
|
2533
|
-
callback: StreamCallback
|
|
2534
|
-
): Promise<void>;
|
|
2535
|
-
chatWithMessengerContext?(
|
|
2536
|
-
userMessage: string | UIMessage,
|
|
2537
|
-
callback: StreamCallback,
|
|
2538
|
-
context: MessengerEvent
|
|
2539
|
-
): Promise<void>;
|
|
2540
|
-
}
|
|
2541
|
-
interface MessengerThinkHost extends MessengerThinkTarget {
|
|
2542
|
-
constructor: {
|
|
2543
|
-
name: string;
|
|
2544
|
-
};
|
|
2545
|
-
name: string;
|
|
2546
|
-
parentPath: ReadonlyArray<{
|
|
2547
|
-
className: string;
|
|
2548
|
-
name: string;
|
|
2549
|
-
}>;
|
|
2550
|
-
startFiber(
|
|
2551
|
-
name: string,
|
|
2552
|
-
fn: (ctx: FiberContext) => Promise<void>,
|
|
2553
|
-
options?: StartFiberOptions
|
|
2554
|
-
): Promise<MessengerFiberStartResult>;
|
|
2555
|
-
resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
|
|
2556
|
-
subAgent<T extends Agent>(
|
|
2557
|
-
agentClass: SubAgentClass<T>,
|
|
2558
|
-
name: string
|
|
2559
|
-
): Promise<SubAgentStub<T>>;
|
|
2560
|
-
}
|
|
2561
|
-
interface MessengerFiberStartResult {
|
|
2562
|
-
accepted: boolean;
|
|
2563
|
-
fiberId: string;
|
|
2564
|
-
snapshot?: unknown;
|
|
2565
|
-
status: string;
|
|
2566
|
-
}
|
|
2567
|
-
declare function defineMessengers<T extends ThinkMessengers>(messengers: T): T;
|
|
2568
|
-
declare function chatSdkMessenger(
|
|
2569
|
-
options: ChatSdkMessengerOptions
|
|
2570
|
-
): MessengerDefinition;
|
|
2571
|
-
declare class ThinkMessengerRuntime {
|
|
2572
|
-
private readonly host;
|
|
2573
|
-
private chat?;
|
|
2574
|
-
private readonly definitionsByAdapterName;
|
|
2575
|
-
private readonly definitionsById;
|
|
2576
|
-
private readonly definitions;
|
|
2577
|
-
constructor(definitions: ThinkMessengers, host: MessengerThinkHost);
|
|
2578
|
-
get size(): number;
|
|
2579
|
-
initialize(): void;
|
|
2580
|
-
handleRequest(request: Request): Promise<Response | undefined>;
|
|
2581
|
-
handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
|
|
2582
|
-
private createChat;
|
|
2583
|
-
private enqueueReply;
|
|
2584
|
-
private answer;
|
|
2585
|
-
private resolveTarget;
|
|
2586
|
-
private definitionForThread;
|
|
2587
|
-
private definitionForThreadId;
|
|
2588
|
-
private hasUniqueProvider;
|
|
2589
|
-
private shardThread;
|
|
2590
|
-
private shardStateKey;
|
|
2591
|
-
private reviveChatObject;
|
|
2592
|
-
private toEvent;
|
|
2593
|
-
}
|
|
2594
|
-
declare function normalizeMessengers(
|
|
2595
|
-
messengers: ThinkMessengers
|
|
2596
|
-
): NormalizedMessengerDefinition[];
|
|
2597
|
-
declare function defaultConversationName(event: MessengerEvent): string;
|
|
2598
|
-
declare function idempotencyKeyForEvent(event: MessengerEvent): string;
|
|
2599
|
-
declare function defaultChatSdkEvent(
|
|
2600
|
-
definition: NormalizedMessengerDefinition,
|
|
2601
|
-
input: ChatSdkMessengerEventInput
|
|
2602
|
-
): MessengerEvent;
|
|
2603
|
-
declare function toMessengerThread(thread: Thread): MessengerThread;
|
|
2604
|
-
declare function toMessengerMessage(message: Message): MessengerMessage;
|
|
2605
|
-
declare function toMessengerAuthor(author: Author): MessengerAuthor;
|
|
2606
|
-
declare function toMessengerAttachment(
|
|
2607
|
-
attachment: Attachment
|
|
2608
|
-
): MessengerAttachment;
|
|
2609
|
-
//#endregion
|
|
2610
2610
|
export {
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2611
|
+
TurnInput as $,
|
|
2612
|
+
MessengerEventKind as $t,
|
|
2613
|
+
StepContext as A,
|
|
2614
|
+
EMPTY_MESSENGER_RESPONSE as At,
|
|
2615
|
+
ThinkScheduledTask as B,
|
|
2616
|
+
TextStreamCallbackOptions as Bt,
|
|
2617
|
+
ResolvedChatRecoveryConfig as C,
|
|
2618
|
+
idempotencyKeyForEvent as Ct,
|
|
2619
|
+
SkillRunContext as D,
|
|
2620
|
+
toMessengerMessage as Dt,
|
|
2621
|
+
Session$1 as E,
|
|
2622
|
+
toMessengerAuthor as Et,
|
|
2623
|
+
SubmitMessagesOptions as F,
|
|
2624
|
+
MessengerDeliverySurface as Ft,
|
|
2625
|
+
ThinkSubmissionStatus as G,
|
|
2626
|
+
parseMessengerReplySnapshot as Gt,
|
|
2627
|
+
ThinkScheduledTaskSchedule as H,
|
|
2628
|
+
messengerReplyFailureMode as Ht,
|
|
2629
|
+
SubmitMessagesResult as I,
|
|
2630
|
+
MessengerDeliveryTarget as It,
|
|
2631
|
+
ToolCallContext as J,
|
|
2632
|
+
MessengerAttachment as Jt,
|
|
2633
|
+
ThinkTime as K,
|
|
2634
|
+
textDeltaFromStreamChunk as Kt,
|
|
2635
|
+
TextStreamPart as L,
|
|
2636
|
+
MessengerReplySnapshot as Lt,
|
|
2637
|
+
StopCondition$1 as M,
|
|
2638
|
+
INTERRUPTED_MESSENGER_RESPONSE as Mt,
|
|
2639
|
+
StreamCallback as N,
|
|
2640
|
+
MESSENGER_REPLY_FIBER_NAME as Nt,
|
|
2641
|
+
SkillSource$1 as O,
|
|
2642
|
+
toMessengerThread as Ot,
|
|
2643
|
+
StreamableResult as P,
|
|
2644
|
+
MessengerDeliveryPolicy as Pt,
|
|
2645
|
+
TurnContext as Q,
|
|
2646
|
+
MessengerEvent as Qt,
|
|
2647
|
+
Think as R,
|
|
2648
|
+
MessengerReplyStage as Rt,
|
|
2649
|
+
PrepareStepResult$1 as S,
|
|
2650
|
+
defineMessengers as St,
|
|
2651
|
+
SaveMessagesResult$1 as T,
|
|
2652
|
+
toMessengerAttachment as Tt,
|
|
2653
|
+
ThinkScheduledTasks as U,
|
|
2654
|
+
messengerReplyRecoveryMode as Ut,
|
|
2655
|
+
ThinkScheduledTaskContext as V,
|
|
2656
|
+
deliverMessengerReply as Vt,
|
|
2657
|
+
ThinkSubmissionInspection as W,
|
|
2658
|
+
messengerReplySnapshot as Wt,
|
|
2659
|
+
ToolCallResultContext as X,
|
|
2660
|
+
MessengerCapabilities as Xt,
|
|
2661
|
+
ToolCallDecision as Y,
|
|
2662
|
+
MessengerAuthor as Yt,
|
|
2663
|
+
TurnConfig as Z,
|
|
2664
|
+
MessengerContext as Zt,
|
|
2665
|
+
FiberRecoveryContext$1 as _,
|
|
2666
|
+
ThinkMessengerStateAgent as _t,
|
|
2667
|
+
ChatRecoveryContext$1 as a,
|
|
2668
|
+
skills as at,
|
|
2669
|
+
PrepareStepContext as b,
|
|
2670
|
+
defaultChatSdkEvent as bt,
|
|
2671
|
+
ChatRecoveryProgressContext as c,
|
|
2672
|
+
MessengerConversationMode as ct,
|
|
2673
|
+
ChunkContext as d,
|
|
2674
|
+
MessengerDefinition as dt,
|
|
2675
|
+
MessengerMessage as en,
|
|
2676
|
+
TypedToolCall$1 as et,
|
|
2677
|
+
ChunkPart as f,
|
|
2678
|
+
MessengerRespondTo as ft,
|
|
2679
|
+
FiberContext$1 as g,
|
|
2680
|
+
ThinkMessengerRuntime as gt,
|
|
2681
|
+
ExtensionConfig as h,
|
|
2682
|
+
NormalizedMessengerDefinition as ht,
|
|
2683
|
+
ChatRecoveryConfig$1 as i,
|
|
2684
|
+
toMessengerUserMessage as in,
|
|
2685
|
+
defineScheduledTasks as it,
|
|
2686
|
+
StepResult as j,
|
|
2687
|
+
ERROR_MESSENGER_RESPONSE as jt,
|
|
2688
|
+
StepConfig as k,
|
|
2689
|
+
DeliverMessengerReplyOptions as kt,
|
|
2690
|
+
ChatResponseResult$1 as l,
|
|
2691
|
+
MessengerConversationResolver as lt,
|
|
2692
|
+
DeleteSubmissionsOptions as m,
|
|
2693
|
+
MessengerThinkTarget as mt,
|
|
2694
|
+
ChatErrorContext as n,
|
|
2695
|
+
messengerContextFromEvent as nn,
|
|
2696
|
+
Workspace$1 as nt,
|
|
2697
|
+
ChatRecoveryExhaustedContext as o,
|
|
2698
|
+
ChatSdkMessengerEventInput as ot,
|
|
2699
|
+
ContextOverflowConfig as p,
|
|
2700
|
+
MessengerThinkHost as pt,
|
|
2701
|
+
ThinkWallClockSchedule as q,
|
|
2702
|
+
MessengerAction as qt,
|
|
2703
|
+
ChatOptions as r,
|
|
2704
|
+
serializableMessengerEvent as rn,
|
|
2705
|
+
defaultContextOverflowClassifier as rt,
|
|
2706
|
+
ChatRecoveryOptions$1 as s,
|
|
2707
|
+
ChatSdkMessengerOptions as st,
|
|
2708
|
+
ChatErrorClassification as t,
|
|
2709
|
+
MessengerThread as tn,
|
|
2710
|
+
TypedToolResult as tt,
|
|
2711
|
+
ChatStartEvent as u,
|
|
2712
|
+
MessengerConversationTarget as ut,
|
|
2713
|
+
ListSubmissionsOptions as v,
|
|
2714
|
+
ThinkMessengers as vt,
|
|
2715
|
+
SaveMessagesOptions$1 as w,
|
|
2716
|
+
normalizeMessengers as wt,
|
|
2717
|
+
PrepareStepFunction$1 as x,
|
|
2718
|
+
defaultConversationName as xt,
|
|
2719
|
+
MessageConcurrency$1 as y,
|
|
2720
|
+
chatSdkMessenger as yt,
|
|
2721
|
+
ThinkIntervalSchedule as z,
|
|
2722
|
+
TextStreamCallback as zt
|
|
2723
2723
|
};
|
|
2724
|
-
//# sourceMappingURL=
|
|
2724
|
+
//# sourceMappingURL=think-8jik2oZ5.d.ts.map
|