@cloudflare/think 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +420 -43
- package/dist/chat-sdk-CJwYlbp9.js +669 -0
- package/dist/chat-sdk-CJwYlbp9.js.map +1 -0
- package/dist/extensions/index.d.ts +2 -2
- package/dist/{hook-proxy-5248W-ea.js → hook-proxy-DHwqL8MV.js} +1 -1
- package/dist/{hook-proxy-5248W-ea.js.map → hook-proxy-DHwqL8MV.js.map} +1 -1
- package/dist/index-CYp8VDIe.d.ts +2202 -0
- package/dist/{index-BsB4GUsL.d.ts → index-DS00xJwR.d.ts} +2 -2
- package/dist/{manager-DCbSiSWT.d.ts → manager-C1zjft70.d.ts} +1 -1
- package/dist/messengers/index.d.ts +110 -0
- package/dist/messengers/index.js +2 -0
- package/dist/messengers/telegram.d.ts +62 -0
- package/dist/messengers/telegram.js +84 -0
- package/dist/messengers/telegram.js.map +1 -0
- package/dist/think.d.ts +73 -1144
- package/dist/think.js +2370 -179
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/workspace.d.ts +35 -334
- package/dist/tools/workspace.js +283 -3
- package/dist/tools/workspace.js.map +1 -1
- package/dist/workflows.d.ts +78 -0
- package/dist/workflows.js +119 -0
- package/dist/workflows.js.map +1 -0
- package/dist/workspace-Bri0ANBX.d.ts +342 -0
- package/package.json +24 -7
package/dist/think.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-BP1jgEfY.js";
|
|
2
2
|
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
3
|
-
import {
|
|
3
|
+
import { t as ThinkMessengerRuntime } from "./chat-sdk-CJwYlbp9.js";
|
|
4
|
+
import { Output, convertToModelMessages, jsonSchema, stepCountIs, streamText } from "ai";
|
|
5
|
+
import * as skills from "agents/skills";
|
|
6
|
+
import { SkillRegistry } from "agents/skills";
|
|
4
7
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
5
|
-
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
|
|
8
|
+
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
|
|
6
9
|
import { Session, Session as Session$1 } from "agents/experimental/memory/session";
|
|
7
10
|
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
8
11
|
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
@@ -14,6 +17,7 @@ const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
|
|
|
14
17
|
const MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;
|
|
15
18
|
const MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;
|
|
16
19
|
const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
|
|
20
|
+
const MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;
|
|
17
21
|
function sendIfOpen(connection, message) {
|
|
18
22
|
try {
|
|
19
23
|
connection.send(message);
|
|
@@ -26,6 +30,302 @@ function sendIfOpen(connection, message) {
|
|
|
26
30
|
function isWebSocketClosedSendError(error) {
|
|
27
31
|
return error instanceof TypeError && error.message.includes("WebSocket send() after close");
|
|
28
32
|
}
|
|
33
|
+
function shouldMarkSkippedAfterGenerationChange(status) {
|
|
34
|
+
return status === "completed";
|
|
35
|
+
}
|
|
36
|
+
function stableStringify(value) {
|
|
37
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
38
|
+
if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
|
|
39
|
+
const record = value;
|
|
40
|
+
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
|
|
41
|
+
}
|
|
42
|
+
function stableHash(value) {
|
|
43
|
+
const input = stableStringify(value);
|
|
44
|
+
let h1 = 1779033703;
|
|
45
|
+
let h2 = 3144134277;
|
|
46
|
+
let h3 = 1013904242;
|
|
47
|
+
let h4 = 2773480762;
|
|
48
|
+
for (let i = 0; i < input.length; i++) {
|
|
49
|
+
const code = input.charCodeAt(i);
|
|
50
|
+
h1 = h2 ^ Math.imul(h1 ^ code, 597399067);
|
|
51
|
+
h2 = h3 ^ Math.imul(h2 ^ code, 2869860233);
|
|
52
|
+
h3 = h4 ^ Math.imul(h3 ^ code, 951274213);
|
|
53
|
+
h4 = h1 ^ Math.imul(h4 ^ code, 2716044179);
|
|
54
|
+
}
|
|
55
|
+
h1 = Math.imul(h3 ^ h1 >>> 18, 597399067);
|
|
56
|
+
h2 = Math.imul(h4 ^ h2 >>> 22, 2869860233);
|
|
57
|
+
h3 = Math.imul(h1 ^ h3 >>> 17, 951274213);
|
|
58
|
+
h4 = Math.imul(h2 ^ h4 >>> 19, 2716044179);
|
|
59
|
+
return [
|
|
60
|
+
h1,
|
|
61
|
+
h2,
|
|
62
|
+
h3,
|
|
63
|
+
h4
|
|
64
|
+
].map((part) => (part >>> 0).toString(16).padStart(8, "0")).join("");
|
|
65
|
+
}
|
|
66
|
+
function validateTimezone(timezone) {
|
|
67
|
+
try {
|
|
68
|
+
return new Intl.DateTimeFormat("en-US", { timeZone: timezone }).resolvedOptions().timeZone;
|
|
69
|
+
} catch {
|
|
70
|
+
throw new Error(`Invalid timezone "${timezone}"`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function parseTime(value) {
|
|
74
|
+
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value);
|
|
75
|
+
if (!match) throw new Error(`Invalid schedule time "${value}"; expected HH:mm`);
|
|
76
|
+
return {
|
|
77
|
+
hour: Number(match[1]),
|
|
78
|
+
minute: Number(match[2])
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const declaredScheduleDayNumbers = {
|
|
82
|
+
sun: 0,
|
|
83
|
+
sunday: 0,
|
|
84
|
+
mon: 1,
|
|
85
|
+
monday: 1,
|
|
86
|
+
tue: 2,
|
|
87
|
+
tuesday: 2,
|
|
88
|
+
wed: 3,
|
|
89
|
+
wednesday: 3,
|
|
90
|
+
thu: 4,
|
|
91
|
+
thursday: 4,
|
|
92
|
+
fri: 5,
|
|
93
|
+
friday: 5,
|
|
94
|
+
sat: 6,
|
|
95
|
+
saturday: 6
|
|
96
|
+
};
|
|
97
|
+
function parseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone) {
|
|
98
|
+
const result = tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone);
|
|
99
|
+
if (!result.ok) throw new Error(result.error);
|
|
100
|
+
return result.schedule;
|
|
101
|
+
}
|
|
102
|
+
function tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone) {
|
|
103
|
+
try {
|
|
104
|
+
return {
|
|
105
|
+
ok: true,
|
|
106
|
+
schedule: parseDeclaredTaskScheduleUnchecked(rawSchedule, taskTimezone, defaultTimezone)
|
|
107
|
+
};
|
|
108
|
+
} catch (error) {
|
|
109
|
+
return {
|
|
110
|
+
ok: false,
|
|
111
|
+
error: error instanceof Error ? error.message : String(error)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function parseDeclaredTaskScheduleUnchecked(rawSchedule, taskTimezone, defaultTimezone) {
|
|
116
|
+
const trimmed = rawSchedule.trim().replace(/\s+/g, " ").toLowerCase();
|
|
117
|
+
const inlineTimezoneMatch = /^(.*) in ([A-Za-z_][A-Za-z0-9_+\-/]*)$/.exec(trimmed);
|
|
118
|
+
const schedule = inlineTimezoneMatch?.[1] ?? trimmed;
|
|
119
|
+
const inlineTimezone = inlineTimezoneMatch?.[2];
|
|
120
|
+
if (inlineTimezone && taskTimezone && validateTimezone(inlineTimezone) !== validateTimezone(taskTimezone)) throw new Error(`Schedule timezone "${inlineTimezone}" does not match task timezone "${taskTimezone}"`);
|
|
121
|
+
const intervalMatch = /^every ([1-9]\d*) (minute|minutes|hour|hours)$/.exec(schedule);
|
|
122
|
+
if (intervalMatch) {
|
|
123
|
+
if (inlineTimezone || taskTimezone) throw new Error("Interval schedules cannot specify a timezone");
|
|
124
|
+
const count = Number(intervalMatch[1]);
|
|
125
|
+
const unit = intervalMatch[2];
|
|
126
|
+
if (count === 1 && unit.endsWith("s")) throw new Error(`Use singular unit for "${rawSchedule}"`);
|
|
127
|
+
if (count !== 1 && !unit.endsWith("s")) throw new Error(`Use plural unit for "${rawSchedule}"`);
|
|
128
|
+
return {
|
|
129
|
+
kind: "interval",
|
|
130
|
+
intervalMs: count * (unit.startsWith("hour") ? 60 * 6e4 : 6e4),
|
|
131
|
+
normalizedSchedule: `every ${count} ${unit}`
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const timezone = inlineTimezone ?? taskTimezone ?? defaultTimezone;
|
|
135
|
+
if (!timezone) throw new Error(`Wall-clock schedule "${rawSchedule}" requires a timezone or getDefaultTimezone()`);
|
|
136
|
+
const resolvedTimezone = validateTimezone(timezone);
|
|
137
|
+
const dailyMatch = /^every day at ([0-2]\d:[0-5]\d)$/.exec(schedule);
|
|
138
|
+
if (dailyMatch) {
|
|
139
|
+
const { hour, minute } = parseTime(dailyMatch[1]);
|
|
140
|
+
return {
|
|
141
|
+
kind: "wall-clock",
|
|
142
|
+
normalizedSchedule: `every day at ${dailyMatch[1]}`,
|
|
143
|
+
timezone: resolvedTimezone,
|
|
144
|
+
hour,
|
|
145
|
+
minute,
|
|
146
|
+
days: "daily"
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
const weekdayMatch = /^every weekday at ([0-2]\d:[0-5]\d)$/.exec(schedule);
|
|
150
|
+
if (weekdayMatch) {
|
|
151
|
+
const { hour, minute } = parseTime(weekdayMatch[1]);
|
|
152
|
+
return {
|
|
153
|
+
kind: "wall-clock",
|
|
154
|
+
normalizedSchedule: `every weekday at ${weekdayMatch[1]}`,
|
|
155
|
+
timezone: resolvedTimezone,
|
|
156
|
+
hour,
|
|
157
|
+
minute,
|
|
158
|
+
days: "weekday"
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
const weeklyMatch = /^every week on ([a-z,\s]+) at ([0-2]\d:[0-5]\d)$/.exec(schedule);
|
|
162
|
+
if (weeklyMatch) {
|
|
163
|
+
const seen = /* @__PURE__ */ new Set();
|
|
164
|
+
const days = weeklyMatch[1].split(",").map((day) => {
|
|
165
|
+
const normalized = day.trim();
|
|
166
|
+
const dayNumber = declaredScheduleDayNumbers[normalized];
|
|
167
|
+
if (dayNumber === void 0) throw new Error(`Invalid schedule day "${normalized}"`);
|
|
168
|
+
if (seen.has(dayNumber)) throw new Error(`Duplicate schedule day "${normalized}"`);
|
|
169
|
+
seen.add(dayNumber);
|
|
170
|
+
return dayNumber;
|
|
171
|
+
});
|
|
172
|
+
if (days.length === 0) throw new Error("Weekly schedule requires at least one day");
|
|
173
|
+
const { hour, minute } = parseTime(weeklyMatch[2]);
|
|
174
|
+
return {
|
|
175
|
+
kind: "wall-clock",
|
|
176
|
+
normalizedSchedule: `every week on ${weeklyMatch[1].split(",").map((day) => day.trim()).join(",")} at ${weeklyMatch[2]}`,
|
|
177
|
+
timezone: resolvedTimezone,
|
|
178
|
+
hour,
|
|
179
|
+
minute,
|
|
180
|
+
days
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
throw new Error(`Unsupported schedule DSL "${rawSchedule}"`);
|
|
184
|
+
}
|
|
185
|
+
function getZonedParts(date, timezone) {
|
|
186
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
187
|
+
timeZone: timezone,
|
|
188
|
+
calendar: "iso8601",
|
|
189
|
+
numberingSystem: "latn",
|
|
190
|
+
weekday: "short",
|
|
191
|
+
year: "numeric",
|
|
192
|
+
month: "2-digit",
|
|
193
|
+
day: "2-digit",
|
|
194
|
+
hour: "2-digit",
|
|
195
|
+
minute: "2-digit",
|
|
196
|
+
second: "2-digit",
|
|
197
|
+
hourCycle: "h23"
|
|
198
|
+
}).formatToParts(date);
|
|
199
|
+
const part = (type) => parts.find((entry) => entry.type === type)?.value ?? "";
|
|
200
|
+
return {
|
|
201
|
+
year: Number(part("year")),
|
|
202
|
+
month: Number(part("month")),
|
|
203
|
+
day: Number(part("day")),
|
|
204
|
+
hour: Number(part("hour")),
|
|
205
|
+
minute: Number(part("minute")),
|
|
206
|
+
second: Number(part("second")),
|
|
207
|
+
weekday: [
|
|
208
|
+
"Sun",
|
|
209
|
+
"Mon",
|
|
210
|
+
"Tue",
|
|
211
|
+
"Wed",
|
|
212
|
+
"Thu",
|
|
213
|
+
"Fri",
|
|
214
|
+
"Sat"
|
|
215
|
+
].indexOf(part("weekday"))
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function compareLocalParts(left, right) {
|
|
219
|
+
for (const field of [
|
|
220
|
+
"year",
|
|
221
|
+
"month",
|
|
222
|
+
"day",
|
|
223
|
+
"hour",
|
|
224
|
+
"minute"
|
|
225
|
+
]) {
|
|
226
|
+
const diff = left[field] - right[field];
|
|
227
|
+
if (diff !== 0) return diff;
|
|
228
|
+
}
|
|
229
|
+
return 0;
|
|
230
|
+
}
|
|
231
|
+
function findZonedInstant(target, timezone) {
|
|
232
|
+
const approximate = Date.UTC(target.year, target.month - 1, target.day, target.hour, target.minute);
|
|
233
|
+
const start = approximate - 840 * 6e4;
|
|
234
|
+
const end = approximate + 840 * 6e4;
|
|
235
|
+
for (let time = start; time <= end; time += 6e4) {
|
|
236
|
+
const candidate = new Date(time);
|
|
237
|
+
if (compareLocalParts(getZonedParts(candidate, timezone), target) === 0) return candidate;
|
|
238
|
+
}
|
|
239
|
+
for (let time = start; time <= end; time += 6e4) {
|
|
240
|
+
const candidate = new Date(time);
|
|
241
|
+
if (compareLocalParts(getZonedParts(candidate, timezone), target) > 0) return candidate;
|
|
242
|
+
}
|
|
243
|
+
throw new Error(`Unable to resolve local time in timezone "${timezone}"`);
|
|
244
|
+
}
|
|
245
|
+
function addLocalDays(parts, days) {
|
|
246
|
+
const date = new Date(Date.UTC(parts.year, parts.month - 1, parts.day + days));
|
|
247
|
+
return {
|
|
248
|
+
year: date.getUTCFullYear(),
|
|
249
|
+
month: date.getUTCMonth() + 1,
|
|
250
|
+
day: date.getUTCDate()
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function isAllowedWallClockDay(weekday, days) {
|
|
254
|
+
if (days.days === "daily") return true;
|
|
255
|
+
if (days.days === "weekday") return weekday >= 1 && weekday <= 5;
|
|
256
|
+
return days.days.includes(weekday);
|
|
257
|
+
}
|
|
258
|
+
function nextDeclaredScheduleTime(schedule, now, previousScheduledFor) {
|
|
259
|
+
if (schedule.kind === "interval") {
|
|
260
|
+
let next = previousScheduledFor === void 0 ? now.getTime() + schedule.intervalMs : previousScheduledFor + schedule.intervalMs;
|
|
261
|
+
while (next <= now.getTime()) next += schedule.intervalMs;
|
|
262
|
+
return new Date(next);
|
|
263
|
+
}
|
|
264
|
+
const nowParts = getZonedParts(now, schedule.timezone);
|
|
265
|
+
for (let offset = 0; offset < 370; offset++) {
|
|
266
|
+
const candidate = findZonedInstant({
|
|
267
|
+
...addLocalDays(nowParts, offset),
|
|
268
|
+
hour: schedule.hour,
|
|
269
|
+
minute: schedule.minute
|
|
270
|
+
}, schedule.timezone);
|
|
271
|
+
const weekday = getZonedParts(candidate, schedule.timezone).weekday;
|
|
272
|
+
if (!isAllowedWallClockDay(weekday, schedule)) continue;
|
|
273
|
+
if (candidate.getTime() > now.getTime()) return candidate;
|
|
274
|
+
}
|
|
275
|
+
throw new Error("Unable to compute next scheduled task occurrence");
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Thrown by `_iterateWithStallWatchdog` when the inactivity watchdog fires
|
|
279
|
+
* (a model/transport stream that parks without ever throwing). Distinct from
|
|
280
|
+
* in-band model/stream errors so the read-loop catch can route a stall into
|
|
281
|
+
* bounded recovery (#1626) — a transient hang is retried within the existing
|
|
282
|
+
* recovery budget — while genuine errors stay terminal.
|
|
283
|
+
*/
|
|
284
|
+
var ChatStreamStalledError = class extends Error {
|
|
285
|
+
constructor(message) {
|
|
286
|
+
super(message);
|
|
287
|
+
this.isChatStreamStall = true;
|
|
288
|
+
this.name = "ChatStreamStalledError";
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
|
|
292
|
+
const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
|
|
293
|
+
const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
|
|
294
|
+
const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
|
|
295
|
+
const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
|
|
296
|
+
const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
|
|
297
|
+
const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
|
|
298
|
+
const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
|
|
299
|
+
const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
|
|
300
|
+
const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
|
|
301
|
+
const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
|
|
302
|
+
const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
|
|
303
|
+
const CONTINUE_CHECKPOINT_PROMPT = "Continue your previous response from exactly where it left off. Do not repeat any of it.";
|
|
304
|
+
/**
|
|
305
|
+
* Ensure a model request does not end in an assistant message.
|
|
306
|
+
*
|
|
307
|
+
* Continuing a partial assistant turn (e.g. after a deploy interrupts a stream)
|
|
308
|
+
* replays a transcript whose final message is that partial assistant message —
|
|
309
|
+
* an "assistant prefill". Modern chat models reject this: Anthropic Claude 4.6+
|
|
310
|
+
* returns a 400 ("This model does not support assistant message prefill. The
|
|
311
|
+
* conversation must end with a user message."). To reach a valid continue
|
|
312
|
+
* checkpoint across providers we append an ephemeral user message. This shapes
|
|
313
|
+
* only the model request; it is never persisted to the transcript.
|
|
314
|
+
*/
|
|
315
|
+
function ensureValidContinueCheckpoint(messages) {
|
|
316
|
+
if (messages.length === 0) return messages;
|
|
317
|
+
if (messages[messages.length - 1]?.role !== "assistant") return messages;
|
|
318
|
+
return [...messages, {
|
|
319
|
+
role: "user",
|
|
320
|
+
content: CONTINUE_CHECKPOINT_PROMPT
|
|
321
|
+
}];
|
|
322
|
+
}
|
|
323
|
+
const CHAT_LAST_TERMINAL_KEY = "cf:chat:last-terminal";
|
|
324
|
+
const CHAT_RECOVERING_KEY = "cf:chat:recovering";
|
|
325
|
+
function defineScheduledTasks(tasks) {
|
|
326
|
+
return tasks;
|
|
327
|
+
}
|
|
328
|
+
const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
|
|
29
329
|
const TIMED_OUT = Symbol("timed-out");
|
|
30
330
|
var _configCache = /* @__PURE__ */ new WeakMap();
|
|
31
331
|
var _configTableReady = /* @__PURE__ */ new WeakMap();
|
|
@@ -38,14 +338,18 @@ var Think = class Think extends Agent {
|
|
|
38
338
|
constructor(ctx, env) {
|
|
39
339
|
super(ctx, env);
|
|
40
340
|
this.waitForMcpConnections = false;
|
|
341
|
+
this._skillRegistry = null;
|
|
342
|
+
this._loggedSkillWarnings = /* @__PURE__ */ new Set();
|
|
41
343
|
this.messageConcurrency = "queue";
|
|
42
344
|
this.chatRecovery = true;
|
|
43
345
|
this._cachedMessages = [];
|
|
346
|
+
this.workspaceBash = true;
|
|
44
347
|
this._aborts = new AbortRegistry();
|
|
45
348
|
this._turnQueue = new TurnQueue();
|
|
46
349
|
this._pendingResumeConnections = /* @__PURE__ */ new Set();
|
|
47
350
|
this._continuation = new ContinuationState();
|
|
48
351
|
this._continuationTimer = null;
|
|
352
|
+
this._continuationBarrierActive = false;
|
|
49
353
|
this._insideResponseHook = false;
|
|
50
354
|
this._insideInferenceLoop = false;
|
|
51
355
|
this._pendingInteractionPromise = null;
|
|
@@ -57,14 +361,19 @@ var Think = class Think extends Agent {
|
|
|
57
361
|
this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
|
|
58
362
|
this._agentToolLiveSequences = /* @__PURE__ */ new Map();
|
|
59
363
|
this._submissionTableEnsured = false;
|
|
364
|
+
this._workflowNotificationTableEnsured = false;
|
|
365
|
+
this._declaredScheduledTasksTableEnsured = false;
|
|
60
366
|
this._drainingSubmissions = false;
|
|
367
|
+
this._drainingWorkflowNotifications = false;
|
|
61
368
|
this._submissionAbortControllers = /* @__PURE__ */ new Map();
|
|
62
369
|
this._programmaticStreamErrors = /* @__PURE__ */ new Map();
|
|
63
370
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
64
371
|
_classPrivateFieldInitSpec(this, _configTableReady, false);
|
|
65
372
|
this.maxSteps = 10;
|
|
66
373
|
this.sendReasoning = true;
|
|
374
|
+
this.chatStreamStallTimeoutMs = 0;
|
|
67
375
|
this.hookTimeout = 5e3;
|
|
376
|
+
this._lastAgentToolStreamProgressAt = 0;
|
|
68
377
|
const _onStart = this.onStart.bind(this);
|
|
69
378
|
this.onStart = async () => {
|
|
70
379
|
if (!this.workspace) this.workspace = new Workspace$1({
|
|
@@ -91,15 +400,20 @@ var Think = class Think extends Agent {
|
|
|
91
400
|
break;
|
|
92
401
|
}
|
|
93
402
|
});
|
|
403
|
+
await this._initializeSkills();
|
|
94
404
|
await this._syncMessages();
|
|
95
405
|
if (this.extensionLoader) await this._initializeExtensions();
|
|
96
406
|
this._resumableStream = new ResumableStream(this.sql.bind(this));
|
|
97
407
|
this._restoreClientTools();
|
|
98
408
|
this._restoreBody();
|
|
99
409
|
this._setupProtocolHandlers();
|
|
410
|
+
this._initializeMessengers();
|
|
100
411
|
await _onStart();
|
|
412
|
+
await this._reconcileDeclaredScheduledTasks();
|
|
101
413
|
await this._recoverSubmissionsOnStart();
|
|
414
|
+
this._recoverWorkflowNotifications();
|
|
102
415
|
this._startSubmissionDrain();
|
|
416
|
+
this._startWorkflowNotificationDrain();
|
|
103
417
|
};
|
|
104
418
|
}
|
|
105
419
|
/**
|
|
@@ -117,6 +431,181 @@ var Think = class Think extends Agent {
|
|
|
117
431
|
async _readMessagesFromStorage() {
|
|
118
432
|
return await this.session.getHistory();
|
|
119
433
|
}
|
|
434
|
+
/**
|
|
435
|
+
* Normalize a tool part's `input` into something the provider will accept.
|
|
436
|
+
*
|
|
437
|
+
* Two malformed shapes 400 modern providers (and persist forever once
|
|
438
|
+
* written): a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead
|
|
439
|
+
* of the object) and a missing/`null` `input` on a settled or interrupted
|
|
440
|
+
* tool call (Anthropic rejects a `tool_use` block whose `input` is absent).
|
|
441
|
+
* We parse the former and default the latter to an empty object so the
|
|
442
|
+
* tool-call/tool-result pair stays valid. Any other value is left untouched.
|
|
443
|
+
*/
|
|
444
|
+
_normalizeToolInput(record) {
|
|
445
|
+
const raw = "input" in record ? record.input : void 0;
|
|
446
|
+
if (typeof raw === "string") {
|
|
447
|
+
const trimmed = raw.trim();
|
|
448
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
|
|
449
|
+
return {
|
|
450
|
+
input: JSON.parse(raw),
|
|
451
|
+
changed: true
|
|
452
|
+
};
|
|
453
|
+
} catch {
|
|
454
|
+
return {
|
|
455
|
+
input: raw,
|
|
456
|
+
changed: false
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
if (raw === void 0 || raw === null) return {
|
|
461
|
+
input: {},
|
|
462
|
+
changed: true
|
|
463
|
+
};
|
|
464
|
+
return {
|
|
465
|
+
input: raw,
|
|
466
|
+
changed: false
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* Whether a tool part already has a settled result the provider accepts, so
|
|
471
|
+
* it must NOT be re-repaired into an errored result.
|
|
472
|
+
*
|
|
473
|
+
* Single source of truth for the terminal tool states, shared by the repair
|
|
474
|
+
* pass and the backstop detector so they cannot drift. Mirror the AI SDK's
|
|
475
|
+
* terminal states: `convertToModelMessages` emits a `tool-result` for
|
|
476
|
+
* `output-available`, `output-error`, AND `output-denied` (a user-denied
|
|
477
|
+
* approval — its denial reason becomes the tool-result). Omitting any of
|
|
478
|
+
* these makes repair re-flip the part every turn — clobbering a real
|
|
479
|
+
* `errorText`/denial with the generic "interrupted" message — and makes the
|
|
480
|
+
* backstop falsely drop a valid call.
|
|
481
|
+
*/
|
|
482
|
+
_toolPartHasSettledResult(record) {
|
|
483
|
+
if ("output" in record || "result" in record) return true;
|
|
484
|
+
const state = typeof record.state === "string" ? record.state : "";
|
|
485
|
+
return state === "output-available" || state === "output-error" || state === "output-denied";
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Tool-call ids that still have no recorded result. After repair this should
|
|
489
|
+
* be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
|
|
490
|
+
* will drop those calls — i.e. repair missed a shape and should be extended.
|
|
491
|
+
*
|
|
492
|
+
* `approval-responded` is deliberately excluded: an approved server tool has
|
|
493
|
+
* no result *yet*, but it is not incomplete or abandoned — it is waiting for
|
|
494
|
+
* its continuation to run `execute()`. `convertToModelMessages` keeps that
|
|
495
|
+
* call (and the SDK executes it), so flagging it here would log a misleading
|
|
496
|
+
* "repair gap" warning and emit a spurious `chat:transcript:repaired` event
|
|
497
|
+
* on every approval continuation.
|
|
498
|
+
*/
|
|
499
|
+
_incompleteToolCallIds(messages) {
|
|
500
|
+
const ids = [];
|
|
501
|
+
for (const message of messages) for (const part of message.parts) {
|
|
502
|
+
const record = part;
|
|
503
|
+
const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : void 0;
|
|
504
|
+
if (!(typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && toolCallId)) continue;
|
|
505
|
+
if (record.state === "approval-responded") continue;
|
|
506
|
+
if (!this._toolPartHasSettledResult(record)) ids.push(toolCallId);
|
|
507
|
+
}
|
|
508
|
+
return ids;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Repair a single interrupted tool call — a tool part with no settled result,
|
|
512
|
+
* left behind when a stream was cut off mid-flight. Returns the replacement
|
|
513
|
+
* part that takes its place in the transcript. `input` has already been
|
|
514
|
+
* normalized to a valid object.
|
|
515
|
+
*
|
|
516
|
+
* The default flips it to an errored tool result so the record survives (no
|
|
517
|
+
* "disappearing" tool call) and `convertToModelMessages` still gets a
|
|
518
|
+
* tool-result for it (avoiding `AI_MissingToolResultsError`).
|
|
519
|
+
*
|
|
520
|
+
* Override to customize the repaired shape for client-resolved tools — e.g.
|
|
521
|
+
* convert an interrupted `ask_user` (a question with no server `execute`,
|
|
522
|
+
* normally answered by the user's next message) into a plain text part
|
|
523
|
+
* carrying the question prose, so the model sees it as ordinary conversation
|
|
524
|
+
* rather than a tool error and compaction keeps the question verbatim. This
|
|
525
|
+
* runs DURING transcript repair — before the repaired transcript is persisted
|
|
526
|
+
* and sent to the model — so the conversion shapes the current turn, not just
|
|
527
|
+
* the next one. A returned tool part MUST carry a settled result
|
|
528
|
+
* (`output-available` / `output-error` / `output-denied` or an
|
|
529
|
+
* `output`/`result` field); returning a non-tool part (e.g. text) is fine.
|
|
530
|
+
*/
|
|
531
|
+
repairInterruptedToolPart(part) {
|
|
532
|
+
return {
|
|
533
|
+
...part,
|
|
534
|
+
state: "output-error",
|
|
535
|
+
errorText: "The tool call was interrupted before a result was recorded."
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
_repairToolTranscriptParts(messages) {
|
|
539
|
+
let removedToolCalls = 0;
|
|
540
|
+
let normalizedInputs = 0;
|
|
541
|
+
const toolCallIds = [];
|
|
542
|
+
const repaired = [];
|
|
543
|
+
for (const message of messages) {
|
|
544
|
+
const parts = [];
|
|
545
|
+
let messageChanged = false;
|
|
546
|
+
for (const part of message.parts) {
|
|
547
|
+
const record = part;
|
|
548
|
+
const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : void 0;
|
|
549
|
+
if (!(typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && toolCallId)) {
|
|
550
|
+
parts.push(part);
|
|
551
|
+
continue;
|
|
552
|
+
}
|
|
553
|
+
if (!this._toolPartHasSettledResult(record)) {
|
|
554
|
+
if ((typeof record.state === "string" ? record.state : "") === "approval-responded") {
|
|
555
|
+
parts.push(part);
|
|
556
|
+
continue;
|
|
557
|
+
}
|
|
558
|
+
const normalized = this._normalizeToolInput(record);
|
|
559
|
+
parts.push(this.repairInterruptedToolPart({
|
|
560
|
+
...part,
|
|
561
|
+
input: normalized.input
|
|
562
|
+
}));
|
|
563
|
+
if (normalized.changed) normalizedInputs++;
|
|
564
|
+
removedToolCalls++;
|
|
565
|
+
messageChanged = true;
|
|
566
|
+
toolCallIds.push(toolCallId);
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
const normalized = this._normalizeToolInput(record);
|
|
570
|
+
if (normalized.changed) {
|
|
571
|
+
parts.push({
|
|
572
|
+
...part,
|
|
573
|
+
input: normalized.input
|
|
574
|
+
});
|
|
575
|
+
normalizedInputs++;
|
|
576
|
+
messageChanged = true;
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
parts.push(part);
|
|
580
|
+
}
|
|
581
|
+
repaired.push(messageChanged ? {
|
|
582
|
+
...message,
|
|
583
|
+
parts
|
|
584
|
+
} : message);
|
|
585
|
+
}
|
|
586
|
+
return {
|
|
587
|
+
messages: repaired,
|
|
588
|
+
removedToolCalls,
|
|
589
|
+
normalizedInputs,
|
|
590
|
+
toolCallIds
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
async _repairTranscriptForProvider(messages) {
|
|
594
|
+
const repair = this._repairToolTranscriptParts(messages);
|
|
595
|
+
if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
|
|
596
|
+
for (const message of repair.messages) {
|
|
597
|
+
const original = messages.find((candidate) => candidate.id === message.id);
|
|
598
|
+
if (original && original.parts !== message.parts) await this.session.updateMessage(sanitizeMessage(message));
|
|
599
|
+
}
|
|
600
|
+
this._replaceCachedMessages(repair.messages);
|
|
601
|
+
this._broadcastMessages();
|
|
602
|
+
this._emit("chat:transcript:repaired", {
|
|
603
|
+
removedToolCalls: repair.removedToolCalls,
|
|
604
|
+
normalizedInputs: repair.normalizedInputs,
|
|
605
|
+
toolCallIds: repair.toolCallIds
|
|
606
|
+
});
|
|
607
|
+
return repair.messages;
|
|
608
|
+
}
|
|
120
609
|
/** Replace the live cache with a durable storage snapshot. */
|
|
121
610
|
_replaceCachedMessages(messages) {
|
|
122
611
|
this._cachedMessages = messages;
|
|
@@ -186,6 +675,10 @@ var Think = class Think extends Agent {
|
|
|
186
675
|
} catch {}
|
|
187
676
|
super.broadcast(msg, without);
|
|
188
677
|
}
|
|
678
|
+
async alarm() {
|
|
679
|
+
await super.alarm();
|
|
680
|
+
this._startWorkflowNotificationDrain();
|
|
681
|
+
}
|
|
189
682
|
/**
|
|
190
683
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
191
684
|
* agent instance. Stored in the Think-private `think_config` table —
|
|
@@ -295,6 +788,62 @@ var Think = class Think extends Agent {
|
|
|
295
788
|
getTools() {
|
|
296
789
|
return {};
|
|
297
790
|
}
|
|
791
|
+
/** Return messenger integrations that should be routed through this Think agent. */
|
|
792
|
+
getMessengers() {
|
|
793
|
+
return {};
|
|
794
|
+
}
|
|
795
|
+
getMessengerContext() {
|
|
796
|
+
if (this._activeMessengerContext) return this._activeMessengerContext;
|
|
797
|
+
return this.messages.at(-1)?.metadata?.messenger;
|
|
798
|
+
}
|
|
799
|
+
async chatWithMessengerContext(userMessage, callback, context, options) {
|
|
800
|
+
const previous = this._activeMessengerContext;
|
|
801
|
+
this._activeMessengerContext = context;
|
|
802
|
+
try {
|
|
803
|
+
await this.chat(userMessage, callback, options);
|
|
804
|
+
} finally {
|
|
805
|
+
this._activeMessengerContext = previous;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
_initializeMessengers() {
|
|
809
|
+
if (this.parentPath.length > 0) return;
|
|
810
|
+
const messengers = this.getMessengers();
|
|
811
|
+
if (Object.keys(messengers).length === 0) return;
|
|
812
|
+
this._messengerRuntime = new ThinkMessengerRuntime(messengers, this);
|
|
813
|
+
this._messengerRuntime.initialize();
|
|
814
|
+
}
|
|
815
|
+
/** Return code-declared scheduled tasks for this agent. */
|
|
816
|
+
getScheduledTasks() {
|
|
817
|
+
return {};
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Reconcile code-declared scheduled tasks immediately.
|
|
821
|
+
* Static declarations are reconciled on startup automatically; call this
|
|
822
|
+
* after changing app-owned data that `getScheduledTasks()` reads.
|
|
823
|
+
*/
|
|
824
|
+
async internal_reconcileScheduledTasks() {
|
|
825
|
+
await this._reconcileDeclaredScheduledTasks();
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Return the default timezone for wall-clock scheduled tasks.
|
|
829
|
+
* Task-local timezone declarations take precedence.
|
|
830
|
+
*/
|
|
831
|
+
getDefaultTimezone() {}
|
|
832
|
+
async _runChatRecoveryFiber(requestId, continuation, fn) {
|
|
833
|
+
const snapshot = createChatFiberSnapshot({
|
|
834
|
+
kind: "think-chat-turn",
|
|
835
|
+
requestId,
|
|
836
|
+
recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
|
|
837
|
+
continuation,
|
|
838
|
+
messages: this.messages,
|
|
839
|
+
lastBody: this._lastBody,
|
|
840
|
+
lastClientTools: this._lastClientTools
|
|
841
|
+
});
|
|
842
|
+
return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
|
|
843
|
+
initialSnapshot: wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, null),
|
|
844
|
+
wrapStash: (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data)
|
|
845
|
+
});
|
|
846
|
+
}
|
|
298
847
|
_systemPromptForTurn(baseSystem, tools) {
|
|
299
848
|
if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
|
|
300
849
|
return `${baseSystem.trimEnd()}\n\n${this._buildThinkCapabilityBlock(tools)}`;
|
|
@@ -347,6 +896,75 @@ var Think = class Think extends Agent {
|
|
|
347
896
|
return session;
|
|
348
897
|
}
|
|
349
898
|
/**
|
|
899
|
+
* Return Agent Skills sources for this Think agent.
|
|
900
|
+
*
|
|
901
|
+
* Bundled skills are typically imported with the Agents Vite plugin:
|
|
902
|
+
*
|
|
903
|
+
* ```typescript
|
|
904
|
+
* import productSkills from "agents:skills"; // -> ./skills next to this file
|
|
905
|
+
* ```
|
|
906
|
+
*
|
|
907
|
+
* Sources are applied in order; the first source to register a skill name
|
|
908
|
+
* wins, and later collisions are skipped with a logged warning.
|
|
909
|
+
*/
|
|
910
|
+
getSkills() {
|
|
911
|
+
return [];
|
|
912
|
+
}
|
|
913
|
+
async _initializeSkills() {
|
|
914
|
+
try {
|
|
915
|
+
const sources = await this.getSkills();
|
|
916
|
+
if (sources.length === 0) return;
|
|
917
|
+
const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
|
|
918
|
+
await registry.load();
|
|
919
|
+
this._logSkillWarnings(registry);
|
|
920
|
+
this._skillRegistry = registry;
|
|
921
|
+
await this.session.addContext(registry.contextLabel, {
|
|
922
|
+
description: "Think skills: available skill catalog",
|
|
923
|
+
provider: { get: () => registry.systemPrompt() }
|
|
924
|
+
});
|
|
925
|
+
if (this._configGet("skillsFingerprint") !== registry.fingerprint) {
|
|
926
|
+
await this.session.refreshSystemPrompt();
|
|
927
|
+
this._configSet("skillsFingerprint", registry.fingerprint);
|
|
928
|
+
}
|
|
929
|
+
} catch (error) {
|
|
930
|
+
console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Log registry diagnostics (duplicate names, sources that failed to list),
|
|
935
|
+
* deduped by message so a new collision after a deploy still surfaces while
|
|
936
|
+
* the same warning is not repeated on every turn.
|
|
937
|
+
*/
|
|
938
|
+
_logSkillWarnings(registry) {
|
|
939
|
+
for (const warning of registry.warnings) {
|
|
940
|
+
if (this._loggedSkillWarnings.has(warning)) continue;
|
|
941
|
+
this._loggedSkillWarnings.add(warning);
|
|
942
|
+
console.warn(`[think] ${warning}`);
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* Return an optional runner that enables the `run_skill_script` tool.
|
|
947
|
+
*
|
|
948
|
+
* @experimental Skill script execution is experimental and may change
|
|
949
|
+
* before stabilizing.
|
|
950
|
+
*/
|
|
951
|
+
getSkillScriptRunner() {
|
|
952
|
+
return null;
|
|
953
|
+
}
|
|
954
|
+
async _refreshSkillsIfChanged() {
|
|
955
|
+
if (!this._skillRegistry) return;
|
|
956
|
+
try {
|
|
957
|
+
await this._skillRegistry.refresh();
|
|
958
|
+
this._logSkillWarnings(this._skillRegistry);
|
|
959
|
+
if (this._configGet("skillsFingerprint") !== this._skillRegistry.fingerprint) {
|
|
960
|
+
await this.session.refreshSystemPrompt();
|
|
961
|
+
this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
|
|
962
|
+
}
|
|
963
|
+
} catch (error) {
|
|
964
|
+
console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
350
968
|
* Return sandboxed extension configurations. Defines load order,
|
|
351
969
|
* which determines hook execution order.
|
|
352
970
|
* Requires `extensionLoader` to be set.
|
|
@@ -508,7 +1126,7 @@ var Think = class Think extends Agent {
|
|
|
508
1126
|
* Handle an error that occurred during a chat turn.
|
|
509
1127
|
* Override to customize error handling (e.g. logging, metrics).
|
|
510
1128
|
*/
|
|
511
|
-
onChatError(error) {
|
|
1129
|
+
onChatError(error, _ctx) {
|
|
512
1130
|
return error;
|
|
513
1131
|
}
|
|
514
1132
|
async _initializeExtensions() {
|
|
@@ -554,27 +1172,43 @@ var Think = class Think extends Agent {
|
|
|
554
1172
|
* for interception, and calls streamText.
|
|
555
1173
|
*/
|
|
556
1174
|
async _runInferenceLoop(input) {
|
|
1175
|
+
this._activeStallTimeoutMs = void 0;
|
|
557
1176
|
if (this.waitForMcpConnections) {
|
|
558
1177
|
const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
|
|
559
1178
|
await this.mcp.waitForConnections({ timeout });
|
|
560
1179
|
}
|
|
561
|
-
const workspaceTools = createWorkspaceTools(this.workspace);
|
|
1180
|
+
const workspaceTools = createWorkspaceTools(this.workspace, { bash: this.workspaceBash });
|
|
562
1181
|
const baseTools = this.getTools();
|
|
563
1182
|
const extensionTools = this.extensionManager?.getTools() ?? {};
|
|
1183
|
+
await this._refreshSkillsIfChanged();
|
|
564
1184
|
const contextTools = await this.session.tools();
|
|
1185
|
+
const skillTools = this._skillRegistry?.tools() ?? {};
|
|
565
1186
|
const clientToolSet = createToolsFromClientSchemas(input.clientTools);
|
|
566
1187
|
const tools = {
|
|
567
1188
|
...workspaceTools,
|
|
568
1189
|
...baseTools,
|
|
569
1190
|
...extensionTools,
|
|
570
1191
|
...contextTools,
|
|
1192
|
+
...skillTools,
|
|
571
1193
|
...this.mcp?.getAITools?.() ?? {},
|
|
572
1194
|
...clientToolSet
|
|
573
1195
|
};
|
|
574
1196
|
const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
|
|
575
1197
|
const system = this._systemPromptForTurn(baseSystem, tools);
|
|
576
|
-
const
|
|
577
|
-
const
|
|
1198
|
+
const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
|
|
1199
|
+
const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
|
|
1200
|
+
if (incompleteAfterRepair.length > 0) {
|
|
1201
|
+
console.warn(`[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(", ")}. This indicates a gap in _repairToolTranscriptParts.`);
|
|
1202
|
+
this._emit("chat:transcript:repaired", {
|
|
1203
|
+
removedToolCalls: incompleteAfterRepair.length,
|
|
1204
|
+
normalizedInputs: 0,
|
|
1205
|
+
toolCallIds: incompleteAfterRepair
|
|
1206
|
+
});
|
|
1207
|
+
}
|
|
1208
|
+
const messages = await convertToModelMessages(truncated, {
|
|
1209
|
+
tools,
|
|
1210
|
+
ignoreIncompleteToolCalls: true
|
|
1211
|
+
});
|
|
578
1212
|
if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
|
|
579
1213
|
const model = this.getModel();
|
|
580
1214
|
const ctx = {
|
|
@@ -587,12 +1221,14 @@ var Think = class Think extends Agent {
|
|
|
587
1221
|
};
|
|
588
1222
|
const subclassConfig = await this.beforeTurn(ctx) ?? {};
|
|
589
1223
|
const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
|
|
1224
|
+
const workflowPrompt = input.workflowPrompt;
|
|
1225
|
+
const workflowOutput = workflowPrompt?.output ? Output.object({ schema: jsonSchema(workflowPrompt.output.schema) }) : void 0;
|
|
590
1226
|
const finalModel = config.model ?? model;
|
|
591
1227
|
const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
|
|
592
1228
|
...tools,
|
|
593
1229
|
...config.tools
|
|
594
1230
|
} : tools);
|
|
595
|
-
const finalMessages = config.messages ?? messages;
|
|
1231
|
+
const finalMessages = ensureValidContinueCheckpoint(config.messages ?? messages);
|
|
596
1232
|
const mergedTools = config.tools ? {
|
|
597
1233
|
...tools,
|
|
598
1234
|
...config.tools
|
|
@@ -600,6 +1236,8 @@ var Think = class Think extends Agent {
|
|
|
600
1236
|
const finalTools = this._wrapToolsWithDecision(mergedTools);
|
|
601
1237
|
const finalMaxSteps = config.maxSteps ?? this.maxSteps;
|
|
602
1238
|
const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
|
|
1239
|
+
this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
1240
|
+
const finalOutput = workflowOutput ?? config.output;
|
|
603
1241
|
const finalStopWhen = [stepCountIs(finalMaxSteps), ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []];
|
|
604
1242
|
const result = streamText({
|
|
605
1243
|
model: finalModel,
|
|
@@ -622,7 +1260,7 @@ var Think = class Think extends Agent {
|
|
|
622
1260
|
stopWhen: finalStopWhen,
|
|
623
1261
|
providerOptions: config.providerOptions,
|
|
624
1262
|
experimental_telemetry: config.experimental_telemetry,
|
|
625
|
-
output:
|
|
1263
|
+
output: finalOutput,
|
|
626
1264
|
abortSignal: input.signal,
|
|
627
1265
|
prepareStep: (async (event) => {
|
|
628
1266
|
const result = await this.beforeStep(event);
|
|
@@ -656,7 +1294,13 @@ var Think = class Think extends Agent {
|
|
|
656
1294
|
await this._pipelineExtensionToolCallFinish(event);
|
|
657
1295
|
})
|
|
658
1296
|
});
|
|
659
|
-
|
|
1297
|
+
const outputPromise = finalOutput && result.output ? Promise.resolve(result.output) : void 0;
|
|
1298
|
+
if (outputPromise) outputPromise.catch(() => {});
|
|
1299
|
+
const streamResult = {
|
|
1300
|
+
toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }),
|
|
1301
|
+
output: outputPromise
|
|
1302
|
+
};
|
|
1303
|
+
return this._transformInferenceResult(streamResult);
|
|
660
1304
|
}
|
|
661
1305
|
/** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
|
|
662
1306
|
_transformInferenceResult(result) {
|
|
@@ -673,7 +1317,7 @@ var Think = class Think extends Agent {
|
|
|
673
1317
|
if (!this.extensionManager) return subclassConfig;
|
|
674
1318
|
const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
|
|
675
1319
|
if (subscribers.length === 0) return subclassConfig;
|
|
676
|
-
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-
|
|
1320
|
+
const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-DHwqL8MV.js");
|
|
677
1321
|
let snapshot = createTurnContextSnapshot(ctx);
|
|
678
1322
|
let accumulated = { ...subclassConfig };
|
|
679
1323
|
if (accumulated.system !== void 0) snapshot.system = accumulated.system;
|
|
@@ -844,25 +1488,25 @@ var Think = class Think extends Agent {
|
|
|
844
1488
|
async _pipelineExtensionToolCallStart(event) {
|
|
845
1489
|
if (!this.extensionManager) return;
|
|
846
1490
|
if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
|
|
847
|
-
const { createToolCallStartSnapshot } = await import("./hook-proxy-
|
|
1491
|
+
const { createToolCallStartSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
|
|
848
1492
|
await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
|
|
849
1493
|
}
|
|
850
1494
|
async _pipelineExtensionToolCallFinish(event) {
|
|
851
1495
|
if (!this.extensionManager) return;
|
|
852
1496
|
if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
|
|
853
|
-
const { createToolCallFinishSnapshot } = await import("./hook-proxy-
|
|
1497
|
+
const { createToolCallFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
|
|
854
1498
|
await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
|
|
855
1499
|
}
|
|
856
1500
|
async _pipelineExtensionStepFinish(event) {
|
|
857
1501
|
if (!this.extensionManager) return;
|
|
858
1502
|
if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
|
|
859
|
-
const { createStepFinishSnapshot } = await import("./hook-proxy-
|
|
1503
|
+
const { createStepFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
|
|
860
1504
|
await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
|
|
861
1505
|
}
|
|
862
1506
|
async _pipelineExtensionChunk(event) {
|
|
863
1507
|
if (!this.extensionManager) return;
|
|
864
1508
|
if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
|
|
865
|
-
const { createChunkSnapshot } = await import("./hook-proxy-
|
|
1509
|
+
const { createChunkSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
|
|
866
1510
|
await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
|
|
867
1511
|
}
|
|
868
1512
|
async _hostReadFile(path) {
|
|
@@ -931,7 +1575,7 @@ var Think = class Think extends Agent {
|
|
|
931
1575
|
const ignoredTools = options?.tools;
|
|
932
1576
|
if (ignoredTools != null && typeof ignoredTools === "object" && Object.keys(ignoredTools).length > 0) console.warn("[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.");
|
|
933
1577
|
try {
|
|
934
|
-
await callback.onStart
|
|
1578
|
+
await callback.onStart({ requestId });
|
|
935
1579
|
await this.keepAliveWhile(async () => {
|
|
936
1580
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
937
1581
|
const userMsg = typeof userMessage === "string" ? {
|
|
@@ -957,19 +1601,22 @@ var Think = class Think extends Agent {
|
|
|
957
1601
|
continuation: false
|
|
958
1602
|
}));
|
|
959
1603
|
} catch (error) {
|
|
960
|
-
const wrapped = this.onChatError(error
|
|
1604
|
+
const wrapped = this.onChatError(error, {
|
|
1605
|
+
stage: "turn",
|
|
1606
|
+
messagesPersisted: true
|
|
1607
|
+
});
|
|
961
1608
|
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
1609
|
+
this._emit("chat:request:failed", {
|
|
1610
|
+
stage: "turn",
|
|
1611
|
+
messagesPersisted: true,
|
|
1612
|
+
error: errorMessage
|
|
1613
|
+
});
|
|
1614
|
+
await callback.onError(errorMessage);
|
|
1615
|
+
return;
|
|
967
1616
|
}
|
|
968
1617
|
await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
|
|
969
1618
|
};
|
|
970
|
-
if (this.chatRecovery) await this.
|
|
971
|
-
await chatBody();
|
|
972
|
-
});
|
|
1619
|
+
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatBody);
|
|
973
1620
|
else await chatBody();
|
|
974
1621
|
});
|
|
975
1622
|
});
|
|
@@ -1070,6 +1717,7 @@ var Think = class Think extends Agent {
|
|
|
1070
1717
|
this._agentToolAbortControllers.set(options.runId, controller);
|
|
1071
1718
|
this._agentToolLiveSequences.set(options.runId, 0);
|
|
1072
1719
|
this._agentToolPreTurnAssistantIds.set(options.runId, new Set(this.messages.filter((m) => m.role === "assistant").map((m) => m.id)));
|
|
1720
|
+
const epoch = this._turnQueue.generation;
|
|
1073
1721
|
this.keepAliveWhile(async () => {
|
|
1074
1722
|
try {
|
|
1075
1723
|
this.sql`
|
|
@@ -1081,9 +1729,9 @@ var Think = class Think extends Agent {
|
|
|
1081
1729
|
const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
|
|
1082
1730
|
const output = this.getAgentToolOutput(options.runId);
|
|
1083
1731
|
const summary = this.getAgentToolSummary(options.runId, output);
|
|
1084
|
-
const streamError = this._agentToolLastErrors.get(options.runId);
|
|
1085
|
-
const skipped = result.status === "skipped";
|
|
1086
|
-
const status = result.status === "
|
|
1732
|
+
const streamError = result.error ?? this._agentToolLastErrors.get(options.runId);
|
|
1733
|
+
const skipped = result.status === "skipped" || result.status === "aborted" && this._turnQueue.generation !== epoch;
|
|
1734
|
+
const status = result.status === "error" || skipped || streamError ? "error" : result.status === "aborted" ? "aborted" : "completed";
|
|
1087
1735
|
const error = status === "error" ? streamError ?? "Agent tool run was skipped before the child could finish." : null;
|
|
1088
1736
|
this.sql`
|
|
1089
1737
|
UPDATE cf_agent_tool_child_runs
|
|
@@ -1095,6 +1743,7 @@ var Think = class Think extends Agent {
|
|
|
1095
1743
|
error_message = ${error},
|
|
1096
1744
|
completed_at = ${Date.now()}
|
|
1097
1745
|
WHERE run_id = ${options.runId}
|
|
1746
|
+
AND completed_at IS NULL
|
|
1098
1747
|
`;
|
|
1099
1748
|
} catch (error) {
|
|
1100
1749
|
this.sql`
|
|
@@ -1103,6 +1752,7 @@ var Think = class Think extends Agent {
|
|
|
1103
1752
|
error_message = ${error instanceof Error ? error.message : String(error)},
|
|
1104
1753
|
completed_at = ${Date.now()}
|
|
1105
1754
|
WHERE run_id = ${options.runId}
|
|
1755
|
+
AND completed_at IS NULL
|
|
1106
1756
|
`;
|
|
1107
1757
|
} finally {
|
|
1108
1758
|
this._agentToolAbortControllers.delete(options.runId);
|
|
@@ -1133,9 +1783,78 @@ var Think = class Think extends Agent {
|
|
|
1133
1783
|
AND status NOT IN ('completed', 'error', 'aborted')
|
|
1134
1784
|
`;
|
|
1135
1785
|
}
|
|
1786
|
+
/**
|
|
1787
|
+
* Classify any in-flight chat-recovery on this child facet (#1630). A child
|
|
1788
|
+
* facet is dedicated to a single agent-tool run, so any recovery incident is
|
|
1789
|
+
* that run's. `detected`/`scheduled`/`attempting` mean recovery is still
|
|
1790
|
+
* resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a
|
|
1791
|
+
* completed recovery deletes its incident.
|
|
1792
|
+
*/
|
|
1793
|
+
async _classifyAgentToolChildRecovery() {
|
|
1794
|
+
const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
|
|
1795
|
+
let failed = false;
|
|
1796
|
+
for (const incident of entries.values()) {
|
|
1797
|
+
if (incident.status === "detected" || incident.status === "scheduled" || incident.status === "attempting") return "in-progress";
|
|
1798
|
+
if (incident.status === "exhausted" || incident.status === "failed") failed = true;
|
|
1799
|
+
}
|
|
1800
|
+
return failed ? "failed" : "none";
|
|
1801
|
+
}
|
|
1136
1802
|
async inspectAgentToolRun(runId) {
|
|
1137
|
-
|
|
1138
|
-
|
|
1803
|
+
let row = this._readAgentToolChildRun(runId);
|
|
1804
|
+
if (!row) return null;
|
|
1805
|
+
if (this._isStaleAgentToolChildRun(row)) {
|
|
1806
|
+
await this._reconcileStaleAgentToolChildRun(runId);
|
|
1807
|
+
row = this._readAgentToolChildRun(runId) ?? row;
|
|
1808
|
+
}
|
|
1809
|
+
return this._inspectionFromChildRow(row, this.getAgentToolOutput(runId));
|
|
1810
|
+
}
|
|
1811
|
+
_isStaleAgentToolChildRun(row) {
|
|
1812
|
+
return (row.status === "running" || row.status === "starting") && row.completed_at === null && !this._agentToolAbortControllers.has(row.run_id);
|
|
1813
|
+
}
|
|
1814
|
+
/**
|
|
1815
|
+
* Reconcile a stale (post-eviction) child run row from the child's own
|
|
1816
|
+
* durable recovery (#1630). The child facet self-heals its interrupted turn
|
|
1817
|
+
* via `chatRecovery`, but that path never writes the run row, so without this
|
|
1818
|
+
* the row strands `running` and the parent can only collect `interrupted`.
|
|
1819
|
+
*
|
|
1820
|
+
* Persisting the terminal here (rather than only computing it) is intentional:
|
|
1821
|
+
* it's a lazy materialization of the run's true terminal that also lets a
|
|
1822
|
+
* tailing parent's stream close promptly and makes subsequent inspects cheap.
|
|
1823
|
+
* While recovery is still resolving (active stream or in-progress incident)
|
|
1824
|
+
* the row is left `running` so the parent's bounded re-attach keeps waiting.
|
|
1825
|
+
*/
|
|
1826
|
+
async _reconcileStaleAgentToolChildRun(runId) {
|
|
1827
|
+
const recovery = await this._classifyAgentToolChildRecovery();
|
|
1828
|
+
if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
|
|
1829
|
+
if (recovery !== "failed" && this._hasRecoveredAgentToolAssistantTurn(runId)) {
|
|
1830
|
+
const output = this.getAgentToolOutput(runId);
|
|
1831
|
+
const summary = this.getAgentToolSummary(runId, output);
|
|
1832
|
+
this.sql`
|
|
1833
|
+
UPDATE cf_agent_tool_child_runs
|
|
1834
|
+
SET status = 'completed',
|
|
1835
|
+
summary = ${summary},
|
|
1836
|
+
output_json = ${Think._stringifyAgentToolOutput(output)},
|
|
1837
|
+
error_message = null,
|
|
1838
|
+
completed_at = ${Date.now()}
|
|
1839
|
+
WHERE run_id = ${runId} AND completed_at IS NULL
|
|
1840
|
+
`;
|
|
1841
|
+
} else this.sql`
|
|
1842
|
+
UPDATE cf_agent_tool_child_runs
|
|
1843
|
+
SET status = 'error',
|
|
1844
|
+
error_message = ${"Agent tool run was interrupted before the child could finish."},
|
|
1845
|
+
completed_at = ${Date.now()}
|
|
1846
|
+
WHERE run_id = ${runId} AND completed_at IS NULL
|
|
1847
|
+
`;
|
|
1848
|
+
this._finalizeAgentToolChildRunTailers(runId);
|
|
1849
|
+
}
|
|
1850
|
+
/** Release a re-attached run's live tail + per-run streaming bookkeeping. */
|
|
1851
|
+
_finalizeAgentToolChildRunTailers(runId) {
|
|
1852
|
+
for (const close of this._agentToolClosers.get(runId) ?? []) close();
|
|
1853
|
+
this._agentToolClosers.delete(runId);
|
|
1854
|
+
this._agentToolForwarders.delete(runId);
|
|
1855
|
+
this._agentToolLiveSequences.delete(runId);
|
|
1856
|
+
this._agentToolLastErrors.delete(runId);
|
|
1857
|
+
this._agentToolPreTurnAssistantIds.delete(runId);
|
|
1139
1858
|
}
|
|
1140
1859
|
async getAgentToolChunks(runId, options) {
|
|
1141
1860
|
const row = this._readAgentToolChildRun(runId);
|
|
@@ -1148,24 +1867,50 @@ var Think = class Think extends Agent {
|
|
|
1148
1867
|
}
|
|
1149
1868
|
async tailAgentToolRun(runId, options) {
|
|
1150
1869
|
const self = this;
|
|
1870
|
+
const signal = options?.signal;
|
|
1871
|
+
let closed = false;
|
|
1872
|
+
let forward;
|
|
1873
|
+
const detach = () => {
|
|
1874
|
+
if (forward) {
|
|
1875
|
+
self._agentToolForwarders.get(runId)?.delete(forward);
|
|
1876
|
+
forward = void 0;
|
|
1877
|
+
}
|
|
1878
|
+
};
|
|
1151
1879
|
return new ReadableStream({
|
|
1152
1880
|
async start(controller) {
|
|
1881
|
+
const close = () => {
|
|
1882
|
+
if (closed) return;
|
|
1883
|
+
closed = true;
|
|
1884
|
+
detach();
|
|
1885
|
+
try {
|
|
1886
|
+
controller.close();
|
|
1887
|
+
} catch {}
|
|
1888
|
+
};
|
|
1889
|
+
if (signal?.aborted) {
|
|
1890
|
+
close();
|
|
1891
|
+
return;
|
|
1892
|
+
}
|
|
1893
|
+
signal?.addEventListener("abort", close, { once: true });
|
|
1153
1894
|
const replayed = await self.getAgentToolChunks(runId, options);
|
|
1154
|
-
for (const chunk of replayed)
|
|
1895
|
+
for (const chunk of replayed) {
|
|
1896
|
+
if (closed) return;
|
|
1897
|
+
controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
|
|
1898
|
+
}
|
|
1155
1899
|
const lastReplay = replayed[replayed.length - 1]?.sequence;
|
|
1156
1900
|
if (lastReplay !== void 0) self._agentToolLiveSequences.set(runId, lastReplay + 1);
|
|
1157
1901
|
const row = self._readAgentToolChildRun(runId);
|
|
1158
1902
|
if (!row || row.completed_at !== null) {
|
|
1159
|
-
|
|
1903
|
+
close();
|
|
1160
1904
|
return;
|
|
1161
1905
|
}
|
|
1162
|
-
|
|
1163
|
-
if (chunk.sequence
|
|
1164
|
-
};
|
|
1165
|
-
const close = () => {
|
|
1906
|
+
forward = (chunk) => {
|
|
1907
|
+
if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) return;
|
|
1166
1908
|
try {
|
|
1167
|
-
controller.
|
|
1168
|
-
} catch {
|
|
1909
|
+
controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
|
|
1910
|
+
} catch {
|
|
1911
|
+
closed = true;
|
|
1912
|
+
detach();
|
|
1913
|
+
}
|
|
1169
1914
|
};
|
|
1170
1915
|
const forwarders = self._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
|
|
1171
1916
|
forwarders.add(forward);
|
|
@@ -1174,8 +1919,9 @@ var Think = class Think extends Agent {
|
|
|
1174
1919
|
closers.add(close);
|
|
1175
1920
|
self._agentToolClosers.set(runId, closers);
|
|
1176
1921
|
},
|
|
1177
|
-
cancel(
|
|
1178
|
-
|
|
1922
|
+
cancel() {
|
|
1923
|
+
closed = true;
|
|
1924
|
+
detach();
|
|
1179
1925
|
}
|
|
1180
1926
|
});
|
|
1181
1927
|
}
|
|
@@ -1195,9 +1941,18 @@ var Think = class Think extends Agent {
|
|
|
1195
1941
|
return;
|
|
1196
1942
|
}
|
|
1197
1943
|
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Whether the run produced an assistant turn (text or tool-only). Used by the
|
|
1946
|
+
* post-eviction reconcile to mark a settled run `completed` even when it ended
|
|
1947
|
+
* without final text. A dedicated child facet starts with no assistant
|
|
1948
|
+
* messages, so a missing in-memory pre-turn snapshot is treated as empty.
|
|
1949
|
+
*/
|
|
1950
|
+
_hasRecoveredAgentToolAssistantTurn(runId) {
|
|
1951
|
+
const before = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
|
|
1952
|
+
return this.messages.some((msg) => msg.role === "assistant" && !before.has(msg.id));
|
|
1953
|
+
}
|
|
1198
1954
|
_getAgentToolFinalText(runId) {
|
|
1199
|
-
const before = this._agentToolPreTurnAssistantIds.get(runId);
|
|
1200
|
-
if (!before) return null;
|
|
1955
|
+
const before = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
|
|
1201
1956
|
for (const msg of this.messages) {
|
|
1202
1957
|
if (msg.role !== "assistant" || before.has(msg.id)) continue;
|
|
1203
1958
|
const text = msg.parts.map((part) => part.type === "text" ? part.text : "").filter((part) => part.length > 0).join("\n");
|
|
@@ -1205,6 +1960,255 @@ var Think = class Think extends Agent {
|
|
|
1205
1960
|
}
|
|
1206
1961
|
return null;
|
|
1207
1962
|
}
|
|
1963
|
+
_ensureDeclaredScheduledTasksTable() {
|
|
1964
|
+
if (this._declaredScheduledTasksTableEnsured) return;
|
|
1965
|
+
this.sql`
|
|
1966
|
+
CREATE TABLE IF NOT EXISTS cf_think_scheduled_tasks (
|
|
1967
|
+
owner_key TEXT NOT NULL,
|
|
1968
|
+
task_id TEXT NOT NULL,
|
|
1969
|
+
schedule_hash TEXT NOT NULL,
|
|
1970
|
+
task_hash TEXT NOT NULL,
|
|
1971
|
+
schedule_id TEXT,
|
|
1972
|
+
next_run_at INTEGER,
|
|
1973
|
+
created_at INTEGER NOT NULL,
|
|
1974
|
+
updated_at INTEGER NOT NULL,
|
|
1975
|
+
PRIMARY KEY (owner_key, task_id)
|
|
1976
|
+
)
|
|
1977
|
+
`;
|
|
1978
|
+
this._declaredScheduledTasksTableEnsured = true;
|
|
1979
|
+
}
|
|
1980
|
+
_readDeclaredScheduledTaskRow(taskId) {
|
|
1981
|
+
this._ensureDeclaredScheduledTasksTable();
|
|
1982
|
+
const ownerKey = this._declaredScheduleOwnerKey();
|
|
1983
|
+
return this.sql`
|
|
1984
|
+
SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,
|
|
1985
|
+
next_run_at, created_at, updated_at
|
|
1986
|
+
FROM cf_think_scheduled_tasks
|
|
1987
|
+
WHERE task_id = ${taskId}
|
|
1988
|
+
AND owner_key = ${ownerKey}
|
|
1989
|
+
LIMIT 1
|
|
1990
|
+
`[0] ?? null;
|
|
1991
|
+
}
|
|
1992
|
+
_listDeclaredScheduledTaskRows() {
|
|
1993
|
+
this._ensureDeclaredScheduledTasksTable();
|
|
1994
|
+
const ownerKey = this._declaredScheduleOwnerKey();
|
|
1995
|
+
return this.sql`
|
|
1996
|
+
SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,
|
|
1997
|
+
next_run_at, created_at, updated_at
|
|
1998
|
+
FROM cf_think_scheduled_tasks
|
|
1999
|
+
WHERE owner_key = ${ownerKey}
|
|
2000
|
+
ORDER BY task_id ASC
|
|
2001
|
+
`;
|
|
2002
|
+
}
|
|
2003
|
+
_updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, updatedAt = Date.now()) {
|
|
2004
|
+
this.sql`
|
|
2005
|
+
UPDATE cf_think_scheduled_tasks
|
|
2006
|
+
SET schedule_hash = ${task.scheduleHash},
|
|
2007
|
+
task_hash = ${task.taskHash},
|
|
2008
|
+
schedule_id = ${scheduled.scheduleId},
|
|
2009
|
+
next_run_at = ${scheduled.scheduledFor},
|
|
2010
|
+
updated_at = ${updatedAt}
|
|
2011
|
+
WHERE owner_key = ${ownerKey}
|
|
2012
|
+
AND task_id = ${task.taskId}
|
|
2013
|
+
`;
|
|
2014
|
+
}
|
|
2015
|
+
async _normalizeDeclaredScheduledTasks(tasks, defaultTimezone) {
|
|
2016
|
+
const normalized = /* @__PURE__ */ new Map();
|
|
2017
|
+
for (const [taskId, task] of Object.entries(tasks)) {
|
|
2018
|
+
if (!/^[A-Za-z0-9_-]+$/.test(taskId)) throw new Error(`Invalid scheduled task id "${taskId}"; use letters, numbers, "_" or "-"`);
|
|
2019
|
+
const schedule = parseDeclaredTaskSchedule(task.schedule, task.timezone, defaultTimezone);
|
|
2020
|
+
const hasPrompt = "prompt" in task && task.prompt !== void 0;
|
|
2021
|
+
const hasHandler = "handler" in task && task.handler !== void 0;
|
|
2022
|
+
if (hasPrompt === hasHandler) throw new Error(`Scheduled task "${taskId}" must define exactly one of prompt or handler`);
|
|
2023
|
+
const scheduleHash = stableHash({
|
|
2024
|
+
schedule,
|
|
2025
|
+
retry: task.retry
|
|
2026
|
+
});
|
|
2027
|
+
const taskHash = stableHash({
|
|
2028
|
+
scheduleHash,
|
|
2029
|
+
action: hasPrompt ? {
|
|
2030
|
+
type: "prompt",
|
|
2031
|
+
value: typeof task.prompt === "string" ? task.prompt : "<function>"
|
|
2032
|
+
} : { type: "handler" },
|
|
2033
|
+
metadata: task.metadata
|
|
2034
|
+
});
|
|
2035
|
+
normalized.set(taskId, {
|
|
2036
|
+
taskId,
|
|
2037
|
+
...hasPrompt ? { prompt: task.prompt } : {},
|
|
2038
|
+
...hasHandler ? { handler: task.handler } : {},
|
|
2039
|
+
schedule,
|
|
2040
|
+
retry: task.retry,
|
|
2041
|
+
metadata: task.metadata,
|
|
2042
|
+
scheduleHash,
|
|
2043
|
+
taskHash
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
return normalized;
|
|
2047
|
+
}
|
|
2048
|
+
async _declaredScheduledTasksForNow() {
|
|
2049
|
+
const defaultTimezone = await this.getDefaultTimezone();
|
|
2050
|
+
const resolvedDefaultTimezone = defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone);
|
|
2051
|
+
return this._normalizeDeclaredScheduledTasks(await this.getScheduledTasks(), resolvedDefaultTimezone);
|
|
2052
|
+
}
|
|
2053
|
+
_declaredScheduleOwnerKey() {
|
|
2054
|
+
return stableHash(this.selfPath);
|
|
2055
|
+
}
|
|
2056
|
+
_declaredScheduleValidationError(rawSchedule, taskTimezone, defaultTimezone) {
|
|
2057
|
+
const result = tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone));
|
|
2058
|
+
return result.ok ? null : result.error;
|
|
2059
|
+
}
|
|
2060
|
+
_nextDeclaredScheduleTimeForConfig(rawSchedule, now, options = {}) {
|
|
2061
|
+
const resolvedDefaultTimezone = options.defaultTimezone === void 0 ? void 0 : validateTimezone(options.defaultTimezone);
|
|
2062
|
+
return nextDeclaredScheduleTime(parseDeclaredTaskSchedule(rawSchedule, options.taskTimezone, resolvedDefaultTimezone), now, options.previousScheduledFor);
|
|
2063
|
+
}
|
|
2064
|
+
async _reconcileDeclaredScheduledTasks() {
|
|
2065
|
+
const tasks = await this._declaredScheduledTasksForNow();
|
|
2066
|
+
this._ensureDeclaredScheduledTasksTable();
|
|
2067
|
+
const ownerKey = this._declaredScheduleOwnerKey();
|
|
2068
|
+
const now = Date.now();
|
|
2069
|
+
const existing = this._listDeclaredScheduledTaskRows();
|
|
2070
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2071
|
+
for (const [taskId, task] of tasks) {
|
|
2072
|
+
seen.add(taskId);
|
|
2073
|
+
const row = existing.find((candidate) => candidate.task_id === taskId);
|
|
2074
|
+
if (!row) {
|
|
2075
|
+
this.sql`
|
|
2076
|
+
INSERT INTO cf_think_scheduled_tasks (
|
|
2077
|
+
owner_key, task_id, schedule_hash, task_hash, schedule_id,
|
|
2078
|
+
next_run_at, created_at, updated_at
|
|
2079
|
+
)
|
|
2080
|
+
VALUES (
|
|
2081
|
+
${ownerKey}, ${taskId}, ${task.scheduleHash}, ${task.taskHash},
|
|
2082
|
+
NULL, NULL, ${now}, ${now}
|
|
2083
|
+
)
|
|
2084
|
+
`;
|
|
2085
|
+
const scheduled = await this._scheduleDeclaredTaskOccurrence(task, new Date(now));
|
|
2086
|
+
this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
|
|
2087
|
+
continue;
|
|
2088
|
+
}
|
|
2089
|
+
if (row.schedule_hash !== task.scheduleHash) {
|
|
2090
|
+
if (row.schedule_id) await this.cancelSchedule(row.schedule_id);
|
|
2091
|
+
this.sql`
|
|
2092
|
+
UPDATE cf_think_scheduled_tasks
|
|
2093
|
+
SET schedule_hash = ${task.scheduleHash},
|
|
2094
|
+
task_hash = ${task.taskHash},
|
|
2095
|
+
schedule_id = NULL,
|
|
2096
|
+
next_run_at = NULL,
|
|
2097
|
+
updated_at = ${now}
|
|
2098
|
+
WHERE owner_key = ${ownerKey}
|
|
2099
|
+
AND task_id = ${taskId}
|
|
2100
|
+
`;
|
|
2101
|
+
const scheduled = await this._scheduleDeclaredTaskOccurrence(task, new Date(now));
|
|
2102
|
+
this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
|
|
2103
|
+
continue;
|
|
2104
|
+
}
|
|
2105
|
+
if (!row.schedule_id) {
|
|
2106
|
+
const scheduled = row.next_run_at === null ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now)) : await this._scheduleDeclaredTaskOccurrenceAt(task, row.next_run_at);
|
|
2107
|
+
this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
|
|
2108
|
+
continue;
|
|
2109
|
+
}
|
|
2110
|
+
if (row.schedule_id) {
|
|
2111
|
+
if (!await this.getScheduleById(row.schedule_id)) {
|
|
2112
|
+
const scheduled = row.next_run_at === null ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now)) : await this._scheduleDeclaredTaskOccurrenceAt(task, row.next_run_at);
|
|
2113
|
+
this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
|
|
2114
|
+
continue;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
if (row.task_hash !== task.taskHash) this.sql`
|
|
2118
|
+
UPDATE cf_think_scheduled_tasks
|
|
2119
|
+
SET task_hash = ${task.taskHash}, updated_at = ${now}
|
|
2120
|
+
WHERE owner_key = ${ownerKey}
|
|
2121
|
+
AND task_id = ${taskId}
|
|
2122
|
+
`;
|
|
2123
|
+
}
|
|
2124
|
+
for (const row of existing) {
|
|
2125
|
+
if (seen.has(row.task_id)) continue;
|
|
2126
|
+
if (row.schedule_id) await this.cancelSchedule(row.schedule_id);
|
|
2127
|
+
this.sql`
|
|
2128
|
+
DELETE FROM cf_think_scheduled_tasks
|
|
2129
|
+
WHERE owner_key = ${ownerKey}
|
|
2130
|
+
AND task_id = ${row.task_id}
|
|
2131
|
+
`;
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
async _scheduleDeclaredTaskOccurrence(task, now, previousScheduledFor) {
|
|
2135
|
+
const next = nextDeclaredScheduleTime(task.schedule, now, previousScheduledFor);
|
|
2136
|
+
return this._scheduleDeclaredTaskOccurrenceAt(task, next.getTime());
|
|
2137
|
+
}
|
|
2138
|
+
async _scheduleDeclaredTaskOccurrenceAt(task, scheduledFor) {
|
|
2139
|
+
return {
|
|
2140
|
+
scheduleId: (await this.schedule(new Date(scheduledFor), "_runDeclaredScheduledTask", {
|
|
2141
|
+
taskId: task.taskId,
|
|
2142
|
+
scheduleHash: task.scheduleHash,
|
|
2143
|
+
scheduledFor
|
|
2144
|
+
}, { idempotent: true })).id,
|
|
2145
|
+
scheduledFor
|
|
2146
|
+
};
|
|
2147
|
+
}
|
|
2148
|
+
async _advanceDeclaredScheduledTask(task, payload, ownerKey) {
|
|
2149
|
+
const scheduled = await this._scheduleDeclaredTaskOccurrence(task, /* @__PURE__ */ new Date(), payload.scheduledFor);
|
|
2150
|
+
this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled);
|
|
2151
|
+
}
|
|
2152
|
+
_declaredScheduledTaskContext(task, payload, ownerKey) {
|
|
2153
|
+
const occurrenceKey = `${payload.taskId}:${payload.scheduledFor}`;
|
|
2154
|
+
return {
|
|
2155
|
+
taskId: payload.taskId,
|
|
2156
|
+
scheduledFor: payload.scheduledFor,
|
|
2157
|
+
scheduledForDate: new Date(payload.scheduledFor),
|
|
2158
|
+
occurrenceKey,
|
|
2159
|
+
idempotencyKey: `think-schedule:${ownerKey}:${occurrenceKey}`,
|
|
2160
|
+
schedule: task.schedule.normalizedSchedule,
|
|
2161
|
+
scheduleKind: task.schedule.kind,
|
|
2162
|
+
...task.schedule.kind === "wall-clock" && { timezone: task.schedule.timezone },
|
|
2163
|
+
...task.metadata !== void 0 && { metadata: task.metadata }
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
async _runDeclaredScheduledTask(payload) {
|
|
2167
|
+
if (!payload || typeof payload.taskId !== "string" || typeof payload.scheduleHash !== "string" || typeof payload.scheduledFor !== "number") throw new Error("Invalid declared scheduled task payload");
|
|
2168
|
+
const row = this._readDeclaredScheduledTaskRow(payload.taskId);
|
|
2169
|
+
if (!row || row.schedule_hash !== payload.scheduleHash) return;
|
|
2170
|
+
if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) return;
|
|
2171
|
+
const task = (await this._declaredScheduledTasksForNow()).get(payload.taskId);
|
|
2172
|
+
if (!task || task.scheduleHash !== payload.scheduleHash) return;
|
|
2173
|
+
const ownerKey = this._declaredScheduleOwnerKey();
|
|
2174
|
+
const context = this._declaredScheduledTaskContext(task, payload, ownerKey);
|
|
2175
|
+
let actionError;
|
|
2176
|
+
try {
|
|
2177
|
+
await this.retry(async () => {
|
|
2178
|
+
if (task.prompt !== void 0) {
|
|
2179
|
+
const prompt = typeof task.prompt === "function" ? await task.prompt() : task.prompt;
|
|
2180
|
+
await this.submitMessages([{
|
|
2181
|
+
id: crypto.randomUUID(),
|
|
2182
|
+
role: "user",
|
|
2183
|
+
parts: [{
|
|
2184
|
+
type: "text",
|
|
2185
|
+
text: prompt
|
|
2186
|
+
}]
|
|
2187
|
+
}], {
|
|
2188
|
+
idempotencyKey: context.idempotencyKey,
|
|
2189
|
+
metadata: {
|
|
2190
|
+
...task.metadata,
|
|
2191
|
+
source: "scheduled-task",
|
|
2192
|
+
ownerKey,
|
|
2193
|
+
taskId: payload.taskId,
|
|
2194
|
+
scheduledFor: payload.scheduledFor,
|
|
2195
|
+
schedule: task.schedule.normalizedSchedule
|
|
2196
|
+
}
|
|
2197
|
+
});
|
|
2198
|
+
} else await task.handler?.(context);
|
|
2199
|
+
}, task.retry);
|
|
2200
|
+
} catch (error) {
|
|
2201
|
+
actionError = error;
|
|
2202
|
+
} finally {
|
|
2203
|
+
await this._advanceDeclaredScheduledTask(task, payload, ownerKey);
|
|
2204
|
+
}
|
|
2205
|
+
if (actionError !== void 0) {
|
|
2206
|
+
console.error(`[Think] Scheduled task "${payload.taskId}" failed; next occurrence was still scheduled`, actionError);
|
|
2207
|
+
try {
|
|
2208
|
+
await this.onError(actionError);
|
|
2209
|
+
} catch {}
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
1208
2212
|
_ensureSubmissionTable() {
|
|
1209
2213
|
if (this._submissionTableEnsured) return;
|
|
1210
2214
|
this.sql`
|
|
@@ -1237,10 +2241,38 @@ var Think = class Think extends Agent {
|
|
|
1237
2241
|
`;
|
|
1238
2242
|
this._submissionTableEnsured = true;
|
|
1239
2243
|
}
|
|
1240
|
-
|
|
1241
|
-
this.
|
|
1242
|
-
|
|
1243
|
-
|
|
2244
|
+
_ensureWorkflowNotificationTable() {
|
|
2245
|
+
if (this._workflowNotificationTableEnsured) return;
|
|
2246
|
+
this.sql`
|
|
2247
|
+
CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (
|
|
2248
|
+
notification_id TEXT PRIMARY KEY,
|
|
2249
|
+
submission_id TEXT NOT NULL,
|
|
2250
|
+
workflow_name TEXT NOT NULL,
|
|
2251
|
+
workflow_id TEXT NOT NULL,
|
|
2252
|
+
event_type TEXT NOT NULL,
|
|
2253
|
+
payload_json TEXT NOT NULL,
|
|
2254
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
2255
|
+
last_error TEXT,
|
|
2256
|
+
created_at INTEGER NOT NULL,
|
|
2257
|
+
updated_at INTEGER NOT NULL,
|
|
2258
|
+
delivered_at INTEGER
|
|
2259
|
+
)
|
|
2260
|
+
`;
|
|
2261
|
+
try {
|
|
2262
|
+
this.ctx.storage.sql.exec("ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER");
|
|
2263
|
+
} catch (error) {
|
|
2264
|
+
if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
|
|
2265
|
+
}
|
|
2266
|
+
this.sql`
|
|
2267
|
+
CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx
|
|
2268
|
+
ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)
|
|
2269
|
+
`;
|
|
2270
|
+
this._workflowNotificationTableEnsured = true;
|
|
2271
|
+
}
|
|
2272
|
+
_readSubmission(submissionId) {
|
|
2273
|
+
this._ensureSubmissionTable();
|
|
2274
|
+
return this.sql`
|
|
2275
|
+
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
1244
2276
|
messages_json, metadata_json, error_message, created_at,
|
|
1245
2277
|
messages_applied_at, started_at, completed_at
|
|
1246
2278
|
FROM cf_think_submissions
|
|
@@ -1321,7 +2353,28 @@ var Think = class Think extends Agent {
|
|
|
1321
2353
|
_serializeMetadata(metadata) {
|
|
1322
2354
|
return metadata === void 0 ? null : JSON.stringify(metadata);
|
|
1323
2355
|
}
|
|
1324
|
-
|
|
2356
|
+
_readWorkflowPromptContext(metadata) {
|
|
2357
|
+
const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];
|
|
2358
|
+
if (workflowPromptValue === null || typeof workflowPromptValue !== "object" || Array.isArray(workflowPromptValue)) return null;
|
|
2359
|
+
const workflowPrompt = workflowPromptValue;
|
|
2360
|
+
const workflowValue = workflowPrompt.workflow;
|
|
2361
|
+
if (workflowValue === null || typeof workflowValue !== "object" || Array.isArray(workflowValue)) return null;
|
|
2362
|
+
const workflowRecord = workflowValue;
|
|
2363
|
+
if (typeof workflowRecord.name !== "string" || typeof workflowRecord.id !== "string" || typeof workflowRecord.stepName !== "string" || typeof workflowRecord.eventType !== "string") return null;
|
|
2364
|
+
const output = workflowPrompt.output;
|
|
2365
|
+
const outputRecord = output !== null && typeof output === "object" && !Array.isArray(output) ? output : null;
|
|
2366
|
+
return {
|
|
2367
|
+
workflow: {
|
|
2368
|
+
name: workflowRecord.name,
|
|
2369
|
+
id: workflowRecord.id,
|
|
2370
|
+
stepName: workflowRecord.stepName,
|
|
2371
|
+
eventType: workflowRecord.eventType
|
|
2372
|
+
},
|
|
2373
|
+
...outputRecord ? { output: { schema: outputRecord.schema } } : {},
|
|
2374
|
+
...typeof workflowPrompt.fingerprint === "string" && { fingerprint: workflowPrompt.fingerprint }
|
|
2375
|
+
};
|
|
2376
|
+
}
|
|
2377
|
+
async _emitSubmissionStatus(row, output) {
|
|
1325
2378
|
const inspection = this._inspectionFromSubmissionRow(row);
|
|
1326
2379
|
this._emit("submission:status", {
|
|
1327
2380
|
submissionId: inspection.submissionId,
|
|
@@ -1333,6 +2386,7 @@ var Think = class Think extends Agent {
|
|
|
1333
2386
|
requestId: inspection.requestId,
|
|
1334
2387
|
error: inspection.error
|
|
1335
2388
|
});
|
|
2389
|
+
if (this._isTerminalSubmissionStatus(inspection.status)) await this._enqueueWorkflowNotification(inspection, output);
|
|
1336
2390
|
await this.keepAliveWhile(async () => {
|
|
1337
2391
|
try {
|
|
1338
2392
|
await this.onSubmissionStatus(inspection);
|
|
@@ -1342,6 +2396,136 @@ var Think = class Think extends Agent {
|
|
|
1342
2396
|
});
|
|
1343
2397
|
}
|
|
1344
2398
|
onSubmissionStatus(_submission) {}
|
|
2399
|
+
async _enqueueWorkflowNotification(submission, output) {
|
|
2400
|
+
this._insertWorkflowNotification(submission, output);
|
|
2401
|
+
this._startWorkflowNotificationDrain();
|
|
2402
|
+
}
|
|
2403
|
+
_insertWorkflowNotification(submission, output, override) {
|
|
2404
|
+
const workflowPrompt = this._readWorkflowPromptContext(submission.metadata ?? null);
|
|
2405
|
+
if (!workflowPrompt) return false;
|
|
2406
|
+
this._ensureWorkflowNotificationTable();
|
|
2407
|
+
const now = Date.now();
|
|
2408
|
+
const status = override?.status ?? submission.status;
|
|
2409
|
+
const error = override?.error ?? submission.error;
|
|
2410
|
+
const payload = {
|
|
2411
|
+
submissionId: submission.submissionId,
|
|
2412
|
+
status,
|
|
2413
|
+
...status === "completed" && { output },
|
|
2414
|
+
...error && { error }
|
|
2415
|
+
};
|
|
2416
|
+
this.sql`
|
|
2417
|
+
INSERT OR IGNORE INTO cf_think_workflow_notifications (
|
|
2418
|
+
notification_id, submission_id, workflow_name, workflow_id, event_type,
|
|
2419
|
+
payload_json, attempts, last_error, created_at, updated_at, delivered_at
|
|
2420
|
+
)
|
|
2421
|
+
VALUES (
|
|
2422
|
+
${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},
|
|
2423
|
+
${submission.submissionId},
|
|
2424
|
+
${workflowPrompt.workflow.name},
|
|
2425
|
+
${workflowPrompt.workflow.id},
|
|
2426
|
+
${workflowPrompt.workflow.eventType},
|
|
2427
|
+
${JSON.stringify(payload)},
|
|
2428
|
+
0,
|
|
2429
|
+
NULL,
|
|
2430
|
+
${now},
|
|
2431
|
+
${now},
|
|
2432
|
+
NULL
|
|
2433
|
+
)
|
|
2434
|
+
`;
|
|
2435
|
+
return true;
|
|
2436
|
+
}
|
|
2437
|
+
_recoverWorkflowNotifications() {
|
|
2438
|
+
this._ensureSubmissionTable();
|
|
2439
|
+
this._ensureWorkflowNotificationTable();
|
|
2440
|
+
const terminalRows = this.sql`
|
|
2441
|
+
SELECT submission_id, idempotency_key, request_id, stream_id, status,
|
|
2442
|
+
messages_json, metadata_json, error_message, created_at,
|
|
2443
|
+
messages_applied_at, started_at, completed_at
|
|
2444
|
+
FROM cf_think_submissions
|
|
2445
|
+
WHERE status IN ('aborted', 'skipped', 'error')
|
|
2446
|
+
ORDER BY completed_at DESC, created_at DESC
|
|
2447
|
+
LIMIT 100
|
|
2448
|
+
`;
|
|
2449
|
+
let recovered = false;
|
|
2450
|
+
for (const row of terminalRows) {
|
|
2451
|
+
const inspection = this._inspectionFromSubmissionRow(row);
|
|
2452
|
+
const workflowPrompt = this._readWorkflowPromptContext(inspection.metadata ?? null);
|
|
2453
|
+
if (!workflowPrompt) continue;
|
|
2454
|
+
const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;
|
|
2455
|
+
if (this.sql`
|
|
2456
|
+
SELECT notification_id
|
|
2457
|
+
FROM cf_think_workflow_notifications
|
|
2458
|
+
WHERE notification_id = ${notificationId}
|
|
2459
|
+
LIMIT 1
|
|
2460
|
+
`[0]) continue;
|
|
2461
|
+
recovered = this._insertWorkflowNotification(inspection) || recovered;
|
|
2462
|
+
}
|
|
2463
|
+
if (recovered) this._startWorkflowNotificationDrain();
|
|
2464
|
+
}
|
|
2465
|
+
_startWorkflowNotificationDrain() {
|
|
2466
|
+
this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch((error) => {
|
|
2467
|
+
console.error("[Think] Failed to drain workflow notifications", error);
|
|
2468
|
+
this._scheduleWorkflowNotificationAlarm();
|
|
2469
|
+
});
|
|
2470
|
+
}
|
|
2471
|
+
async _drainWorkflowNotifications() {
|
|
2472
|
+
if (this._drainingWorkflowNotifications) return;
|
|
2473
|
+
this._ensureWorkflowNotificationTable();
|
|
2474
|
+
this._drainingWorkflowNotifications = true;
|
|
2475
|
+
try {
|
|
2476
|
+
const rows = this.sql`
|
|
2477
|
+
SELECT notification_id, submission_id, workflow_name, workflow_id,
|
|
2478
|
+
event_type, payload_json, attempts, last_error, created_at,
|
|
2479
|
+
updated_at, delivered_at
|
|
2480
|
+
FROM cf_think_workflow_notifications
|
|
2481
|
+
WHERE delivered_at IS NULL
|
|
2482
|
+
ORDER BY created_at ASC, notification_id ASC
|
|
2483
|
+
LIMIT 25
|
|
2484
|
+
`;
|
|
2485
|
+
for (const row of rows) try {
|
|
2486
|
+
const payload = JSON.parse(row.payload_json);
|
|
2487
|
+
await this.sendWorkflowEvent(row.workflow_name, row.workflow_id, {
|
|
2488
|
+
type: row.event_type,
|
|
2489
|
+
payload
|
|
2490
|
+
});
|
|
2491
|
+
this.sql`
|
|
2492
|
+
UPDATE cf_think_workflow_notifications
|
|
2493
|
+
SET payload_json = '{}',
|
|
2494
|
+
last_error = NULL,
|
|
2495
|
+
updated_at = ${Date.now()},
|
|
2496
|
+
delivered_at = ${Date.now()}
|
|
2497
|
+
WHERE notification_id = ${row.notification_id}
|
|
2498
|
+
AND delivered_at IS NULL
|
|
2499
|
+
`;
|
|
2500
|
+
} catch (error) {
|
|
2501
|
+
this.sql`
|
|
2502
|
+
UPDATE cf_think_workflow_notifications
|
|
2503
|
+
SET attempts = attempts + 1,
|
|
2504
|
+
last_error = ${error instanceof Error ? error.message : String(error)},
|
|
2505
|
+
updated_at = ${Date.now()}
|
|
2506
|
+
WHERE notification_id = ${row.notification_id}
|
|
2507
|
+
`;
|
|
2508
|
+
}
|
|
2509
|
+
} finally {
|
|
2510
|
+
this._drainingWorkflowNotifications = false;
|
|
2511
|
+
}
|
|
2512
|
+
await this._scheduleWorkflowNotificationAlarm();
|
|
2513
|
+
}
|
|
2514
|
+
async _scheduleWorkflowNotificationAlarm() {
|
|
2515
|
+
this._ensureWorkflowNotificationTable();
|
|
2516
|
+
const pending = this.sql`
|
|
2517
|
+
SELECT attempts
|
|
2518
|
+
FROM cf_think_workflow_notifications
|
|
2519
|
+
WHERE delivered_at IS NULL
|
|
2520
|
+
ORDER BY created_at ASC, notification_id ASC
|
|
2521
|
+
LIMIT 1
|
|
2522
|
+
`;
|
|
2523
|
+
if (!pending[0]) return;
|
|
2524
|
+
const delayMs = Math.min(300 * 1e3, 1e3 * 2 ** Math.min(pending[0].attempts, 8));
|
|
2525
|
+
const nextAlarm = Date.now() + delayMs;
|
|
2526
|
+
const existingAlarm = await this.ctx.storage.getAlarm();
|
|
2527
|
+
if (existingAlarm === null || existingAlarm > nextAlarm) await this.ctx.storage.setAlarm(nextAlarm);
|
|
2528
|
+
}
|
|
1345
2529
|
async inspectSubmission(submissionId) {
|
|
1346
2530
|
const row = this._readSubmission(submissionId);
|
|
1347
2531
|
return row ? this._inspectionFromSubmissionRow(row) : null;
|
|
@@ -1525,11 +2709,16 @@ var Think = class Think extends Agent {
|
|
|
1525
2709
|
await this._emitSubmissionStatus(claimed);
|
|
1526
2710
|
const controller = new AbortController();
|
|
1527
2711
|
this._submissionAbortControllers.set(row.submission_id, controller);
|
|
2712
|
+
let output;
|
|
1528
2713
|
try {
|
|
1529
2714
|
const messages = this._parseSubmissionMessages(row.messages_json);
|
|
2715
|
+
const metadata = this._parseJsonObject(row.metadata_json);
|
|
2716
|
+
const workflowPrompt = this._readWorkflowPromptContext(metadata);
|
|
1530
2717
|
const result = await this._runProgrammaticMessagesTurn(requestId, messages, {
|
|
1531
2718
|
signal: controller.signal,
|
|
1532
2719
|
captureProgrammaticStreamError: true,
|
|
2720
|
+
captureOutput: Boolean(workflowPrompt?.output),
|
|
2721
|
+
workflowPrompt: workflowPrompt ?? void 0,
|
|
1533
2722
|
onMessagesApplied: () => {
|
|
1534
2723
|
this.sql`
|
|
1535
2724
|
UPDATE cf_think_submissions
|
|
@@ -1540,33 +2729,55 @@ var Think = class Think extends Agent {
|
|
|
1540
2729
|
`;
|
|
1541
2730
|
}
|
|
1542
2731
|
});
|
|
2732
|
+
output = result.output;
|
|
1543
2733
|
const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
|
|
1544
2734
|
const streamError = this._programmaticStreamErrors.get(result.requestId);
|
|
1545
|
-
const finalStatus = this._getSubmissionFinalStatus(result.status, streamError);
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
2735
|
+
const finalStatus = this._getSubmissionFinalStatus(result.status, result.error ?? streamError);
|
|
2736
|
+
const errorMessage = result.error ?? streamError ?? null;
|
|
2737
|
+
const completedAt = Date.now();
|
|
2738
|
+
this.ctx.storage.transactionSync(() => {
|
|
2739
|
+
this.sql`
|
|
2740
|
+
UPDATE cf_think_submissions
|
|
2741
|
+
SET status = ${finalStatus},
|
|
2742
|
+
request_id = ${result.requestId},
|
|
2743
|
+
stream_id = ${streamId},
|
|
2744
|
+
error_message = ${finalStatus === "error" ? errorMessage : null},
|
|
2745
|
+
completed_at = ${completedAt}
|
|
2746
|
+
WHERE submission_id = ${row.submission_id}
|
|
2747
|
+
AND status = 'running'
|
|
2748
|
+
`;
|
|
2749
|
+
this._insertWorkflowNotification({
|
|
2750
|
+
...this._inspectionFromSubmissionRow(claimed),
|
|
2751
|
+
requestId: result.requestId,
|
|
2752
|
+
status: finalStatus,
|
|
2753
|
+
error: finalStatus === "error" ? errorMessage ?? void 0 : void 0,
|
|
2754
|
+
completedAt
|
|
2755
|
+
}, output);
|
|
2756
|
+
});
|
|
1556
2757
|
} catch (error) {
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
2758
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2759
|
+
const completedAt = Date.now();
|
|
2760
|
+
this.ctx.storage.transactionSync(() => {
|
|
2761
|
+
this.sql`
|
|
2762
|
+
UPDATE cf_think_submissions
|
|
2763
|
+
SET status = 'error',
|
|
2764
|
+
error_message = ${errorMessage},
|
|
2765
|
+
completed_at = ${completedAt}
|
|
2766
|
+
WHERE submission_id = ${row.submission_id}
|
|
2767
|
+
AND status = 'running'
|
|
2768
|
+
`;
|
|
2769
|
+
this._insertWorkflowNotification({
|
|
2770
|
+
...this._inspectionFromSubmissionRow(claimed),
|
|
2771
|
+
status: "error",
|
|
2772
|
+
error: errorMessage,
|
|
2773
|
+
completedAt
|
|
2774
|
+
});
|
|
2775
|
+
});
|
|
1565
2776
|
} finally {
|
|
1566
2777
|
this._programmaticStreamErrors.delete(requestId);
|
|
1567
2778
|
this._submissionAbortControllers.delete(row.submission_id);
|
|
1568
2779
|
const updated = this._readSubmission(row.submission_id);
|
|
1569
|
-
if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
|
|
2780
|
+
if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated, output);
|
|
1570
2781
|
}
|
|
1571
2782
|
}
|
|
1572
2783
|
_getSubmissionFinalStatus(resultStatus, streamError) {
|
|
@@ -1762,9 +2973,11 @@ var Think = class Think extends Agent {
|
|
|
1762
2973
|
}
|
|
1763
2974
|
async _runProgrammaticMessagesTurn(requestId, messages, options) {
|
|
1764
2975
|
const clientTools = this._lastClientTools;
|
|
1765
|
-
const body = this._lastBody;
|
|
2976
|
+
const body = options?.body ?? this._lastBody;
|
|
1766
2977
|
const epoch = this._turnQueue.generation;
|
|
1767
2978
|
let status = "completed";
|
|
2979
|
+
let error;
|
|
2980
|
+
let output;
|
|
1768
2981
|
let wasAborted = false;
|
|
1769
2982
|
await this.keepAliveWhile(async () => {
|
|
1770
2983
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
@@ -1793,13 +3006,20 @@ var Think = class Think extends Agent {
|
|
|
1793
3006
|
signal: abortSignal,
|
|
1794
3007
|
clientTools,
|
|
1795
3008
|
body,
|
|
3009
|
+
workflowPrompt: options?.workflowPrompt,
|
|
1796
3010
|
continuation: false
|
|
1797
3011
|
}));
|
|
1798
|
-
if (result)
|
|
3012
|
+
if (result) {
|
|
3013
|
+
const streamResult = await this._streamResult(requestId, result, abortSignal, {
|
|
3014
|
+
captureProgrammaticStreamError: options?.captureProgrammaticStreamError,
|
|
3015
|
+
captureOutput: options?.captureOutput
|
|
3016
|
+
});
|
|
3017
|
+
status = streamResult.status;
|
|
3018
|
+
error = streamResult.error;
|
|
3019
|
+
output = streamResult.output;
|
|
3020
|
+
}
|
|
1799
3021
|
};
|
|
1800
|
-
if (this.chatRecovery) await this.
|
|
1801
|
-
await programmaticBody();
|
|
1802
|
-
});
|
|
3022
|
+
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
|
|
1803
3023
|
else await programmaticBody();
|
|
1804
3024
|
} finally {
|
|
1805
3025
|
if (abortSignal?.aborted) wasAborted = true;
|
|
@@ -1808,11 +3028,13 @@ var Think = class Think extends Agent {
|
|
|
1808
3028
|
}
|
|
1809
3029
|
});
|
|
1810
3030
|
});
|
|
1811
|
-
if (this._turnQueue.generation !== epoch && status
|
|
3031
|
+
if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
|
|
1812
3032
|
else if (wasAborted && status === "completed") status = "aborted";
|
|
1813
3033
|
return {
|
|
1814
3034
|
requestId,
|
|
1815
|
-
status
|
|
3035
|
+
status,
|
|
3036
|
+
...error !== void 0 && { error },
|
|
3037
|
+
...output !== void 0 && { output }
|
|
1816
3038
|
};
|
|
1817
3039
|
}
|
|
1818
3040
|
/**
|
|
@@ -1843,6 +3065,7 @@ var Think = class Think extends Agent {
|
|
|
1843
3065
|
const resolvedBody = body ?? this._lastBody;
|
|
1844
3066
|
const epoch = this._turnQueue.generation;
|
|
1845
3067
|
let status = "completed";
|
|
3068
|
+
let error;
|
|
1846
3069
|
let wasAborted = false;
|
|
1847
3070
|
await this.keepAliveWhile(async () => {
|
|
1848
3071
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
@@ -1865,11 +3088,13 @@ var Think = class Think extends Agent {
|
|
|
1865
3088
|
body: resolvedBody,
|
|
1866
3089
|
continuation: true
|
|
1867
3090
|
}));
|
|
1868
|
-
if (result)
|
|
3091
|
+
if (result) {
|
|
3092
|
+
const streamResult = await this._streamResult(requestId, result, abortSignal, { continuation: true });
|
|
3093
|
+
status = streamResult.status;
|
|
3094
|
+
error = streamResult.error;
|
|
3095
|
+
}
|
|
1869
3096
|
};
|
|
1870
|
-
if (this.chatRecovery) await this.
|
|
1871
|
-
await continueTurnBody();
|
|
1872
|
-
});
|
|
3097
|
+
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, continueTurnBody);
|
|
1873
3098
|
else await continueTurnBody();
|
|
1874
3099
|
} finally {
|
|
1875
3100
|
if (abortSignal?.aborted) wasAborted = true;
|
|
@@ -1878,11 +3103,67 @@ var Think = class Think extends Agent {
|
|
|
1878
3103
|
}
|
|
1879
3104
|
});
|
|
1880
3105
|
});
|
|
1881
|
-
if (this._turnQueue.generation !== epoch && status
|
|
3106
|
+
if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
|
|
1882
3107
|
else if (wasAborted && status === "completed") status = "aborted";
|
|
1883
3108
|
return {
|
|
1884
3109
|
requestId,
|
|
1885
|
-
status
|
|
3110
|
+
status,
|
|
3111
|
+
...error !== void 0 && { error }
|
|
3112
|
+
};
|
|
3113
|
+
}
|
|
3114
|
+
async _retryLastUserTurn(clientTools, body, options) {
|
|
3115
|
+
const lastLeaf = await this.session.getLatestLeaf();
|
|
3116
|
+
if (!lastLeaf || lastLeaf.role !== "user") return {
|
|
3117
|
+
requestId: "",
|
|
3118
|
+
status: "skipped"
|
|
3119
|
+
};
|
|
3120
|
+
const requestId = crypto.randomUUID();
|
|
3121
|
+
const epoch = this._turnQueue.generation;
|
|
3122
|
+
let status = "completed";
|
|
3123
|
+
let error;
|
|
3124
|
+
let wasAborted = false;
|
|
3125
|
+
await this.keepAliveWhile(async () => {
|
|
3126
|
+
await this._turnQueue.enqueue(requestId, async () => {
|
|
3127
|
+
if (this._turnQueue.generation !== epoch) {
|
|
3128
|
+
status = "skipped";
|
|
3129
|
+
return;
|
|
3130
|
+
}
|
|
3131
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
3132
|
+
const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
|
|
3133
|
+
try {
|
|
3134
|
+
const retryTurnBody = async () => {
|
|
3135
|
+
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
3136
|
+
agent: this,
|
|
3137
|
+
connection: void 0,
|
|
3138
|
+
request: void 0,
|
|
3139
|
+
email: void 0
|
|
3140
|
+
}, () => this._runInferenceLoop({
|
|
3141
|
+
signal: abortSignal,
|
|
3142
|
+
clientTools,
|
|
3143
|
+
body,
|
|
3144
|
+
continuation: false
|
|
3145
|
+
}));
|
|
3146
|
+
if (result) {
|
|
3147
|
+
const streamResult = await this._streamResult(requestId, result, abortSignal);
|
|
3148
|
+
status = streamResult.status;
|
|
3149
|
+
error = streamResult.error;
|
|
3150
|
+
}
|
|
3151
|
+
};
|
|
3152
|
+
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, retryTurnBody);
|
|
3153
|
+
else await retryTurnBody();
|
|
3154
|
+
} finally {
|
|
3155
|
+
if (abortSignal?.aborted) wasAborted = true;
|
|
3156
|
+
detachExternal();
|
|
3157
|
+
this._aborts.remove(requestId);
|
|
3158
|
+
}
|
|
3159
|
+
});
|
|
3160
|
+
});
|
|
3161
|
+
if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
|
|
3162
|
+
else if (wasAborted && status === "completed") status = "aborted";
|
|
3163
|
+
return {
|
|
3164
|
+
requestId,
|
|
3165
|
+
status,
|
|
3166
|
+
...error !== void 0 && { error }
|
|
1886
3167
|
};
|
|
1887
3168
|
}
|
|
1888
3169
|
_setupProtocolHandlers() {
|
|
@@ -1890,18 +3171,13 @@ var Think = class Think extends Agent {
|
|
|
1890
3171
|
this.onConnect = async (connection, ctx) => {
|
|
1891
3172
|
if (this._cf_requestTargetsSubAgent(ctx.request)) return _onConnect(connection, ctx);
|
|
1892
3173
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
1893
|
-
else connection.send(JSON.stringify(
|
|
1894
|
-
type: MSG_CHAT_MESSAGES,
|
|
1895
|
-
messages: this.messages
|
|
1896
|
-
}));
|
|
3174
|
+
else for (const message of await this._buildIdleConnectMessages()) connection.send(JSON.stringify(message));
|
|
1897
3175
|
return _onConnect(connection, ctx);
|
|
1898
3176
|
};
|
|
1899
3177
|
const _onClose = this.onClose.bind(this);
|
|
1900
3178
|
this.onClose = async (connection, code, reason, wasClean) => {
|
|
1901
3179
|
this._pendingResumeConnections.delete(connection.id);
|
|
1902
|
-
this._continuation.
|
|
1903
|
-
if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
|
|
1904
|
-
if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
|
|
3180
|
+
this._continuation.releaseConnection(connection.id);
|
|
1905
3181
|
return _onClose(connection, code, reason, wasClean);
|
|
1906
3182
|
};
|
|
1907
3183
|
const _onMessage = this.onMessage.bind(this);
|
|
@@ -1920,6 +3196,8 @@ var Think = class Think extends Agent {
|
|
|
1920
3196
|
this.onRequest = async (request) => {
|
|
1921
3197
|
const url = new URL(request.url);
|
|
1922
3198
|
if (url.pathname === "/get-messages" || url.pathname.endsWith("/get-messages")) return Response.json(this.messages);
|
|
3199
|
+
const messengerResponse = await this._messengerRuntime?.handleRequest(request);
|
|
3200
|
+
if (messengerResponse) return messengerResponse;
|
|
1923
3201
|
return _onRequest(request);
|
|
1924
3202
|
};
|
|
1925
3203
|
}
|
|
@@ -1974,7 +3252,7 @@ var Think = class Think extends Agent {
|
|
|
1974
3252
|
_handleStreamResumeRequest(connection) {
|
|
1975
3253
|
if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
1976
3254
|
else this._notifyStreamResuming(connection);
|
|
1977
|
-
else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
3255
|
+
else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
|
|
1978
3256
|
else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
|
|
1979
3257
|
}
|
|
1980
3258
|
async _handleStreamResumeAck(connection, requestId) {
|
|
@@ -1995,7 +3273,18 @@ var Think = class Think extends Agent {
|
|
|
1995
3273
|
let rawParsed;
|
|
1996
3274
|
try {
|
|
1997
3275
|
rawParsed = JSON.parse(event.init.body);
|
|
1998
|
-
} catch {
|
|
3276
|
+
} catch (error) {
|
|
3277
|
+
const wrapped = this.onChatError(error, {
|
|
3278
|
+
requestId: event.id,
|
|
3279
|
+
stage: "parse",
|
|
3280
|
+
messagesPersisted: false
|
|
3281
|
+
});
|
|
3282
|
+
this._emit("chat:request:failed", {
|
|
3283
|
+
requestId: event.id,
|
|
3284
|
+
stage: "parse",
|
|
3285
|
+
messagesPersisted: false,
|
|
3286
|
+
error: wrapped instanceof Error ? wrapped.message : String(wrapped)
|
|
3287
|
+
});
|
|
1999
3288
|
return;
|
|
2000
3289
|
}
|
|
2001
3290
|
const { messages: incomingMessages, clientTools: rawClientTools, trigger: rawTrigger, ...customBody } = rawParsed;
|
|
@@ -2003,6 +3292,8 @@ var Think = class Think extends Agent {
|
|
|
2003
3292
|
const isRegeneration = rawTrigger === "regenerate-message";
|
|
2004
3293
|
const isSubmitMessage = !isRegeneration;
|
|
2005
3294
|
const requestId = event.id;
|
|
3295
|
+
let messagesPersisted = false;
|
|
3296
|
+
let failureStage = "persist";
|
|
2006
3297
|
const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
|
|
2007
3298
|
if (concurrencyDecision.action === "drop") {
|
|
2008
3299
|
this._rollbackDroppedSubmit(connection);
|
|
@@ -2052,6 +3343,8 @@ var Think = class Think extends Agent {
|
|
|
2052
3343
|
}
|
|
2053
3344
|
await this._syncMessages();
|
|
2054
3345
|
this._broadcastMessages([connection.id]);
|
|
3346
|
+
messagesPersisted = true;
|
|
3347
|
+
failureStage = "turn";
|
|
2055
3348
|
const abortSignal = this._aborts.getSignal(requestId);
|
|
2056
3349
|
await this.keepAliveWhile(async () => {
|
|
2057
3350
|
const turnPromise = this._turnQueue.enqueue(requestId, async () => {
|
|
@@ -2090,9 +3383,7 @@ var Think = class Think extends Agent {
|
|
|
2090
3383
|
done: true
|
|
2091
3384
|
});
|
|
2092
3385
|
};
|
|
2093
|
-
if (this.chatRecovery) await this.
|
|
2094
|
-
await chatTurnBody();
|
|
2095
|
-
});
|
|
3386
|
+
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
|
|
2096
3387
|
else await chatTurnBody();
|
|
2097
3388
|
}, { generation: epoch });
|
|
2098
3389
|
releaseIfPending();
|
|
@@ -2104,10 +3395,23 @@ var Think = class Think extends Agent {
|
|
|
2104
3395
|
});
|
|
2105
3396
|
});
|
|
2106
3397
|
} catch (error) {
|
|
3398
|
+
const wrapped = this.onChatError(error, {
|
|
3399
|
+
requestId,
|
|
3400
|
+
stage: failureStage,
|
|
3401
|
+
messagesPersisted
|
|
3402
|
+
});
|
|
3403
|
+
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
3404
|
+
this._emit("chat:request:failed", {
|
|
3405
|
+
requestId,
|
|
3406
|
+
stage: failureStage,
|
|
3407
|
+
messagesPersisted,
|
|
3408
|
+
error: errorMessage
|
|
3409
|
+
});
|
|
3410
|
+
await this._recordTerminalChatStatus("error", requestId, errorMessage);
|
|
2107
3411
|
this._broadcastChat({
|
|
2108
3412
|
type: MSG_CHAT_RESPONSE,
|
|
2109
3413
|
id: requestId,
|
|
2110
|
-
body:
|
|
3414
|
+
body: errorMessage,
|
|
2111
3415
|
done: true,
|
|
2112
3416
|
error: true
|
|
2113
3417
|
});
|
|
@@ -2139,6 +3443,7 @@ var Think = class Think extends Agent {
|
|
|
2139
3443
|
}
|
|
2140
3444
|
this._submitConcurrency.reset();
|
|
2141
3445
|
this._pendingInteractionPromise = null;
|
|
3446
|
+
this._continuationBarrierActive = false;
|
|
2142
3447
|
this._continuation.sendResumeNone();
|
|
2143
3448
|
this._continuation.clearAll();
|
|
2144
3449
|
}
|
|
@@ -2205,12 +3510,24 @@ var Think = class Think extends Agent {
|
|
|
2205
3510
|
let assistantMsg = null;
|
|
2206
3511
|
let aborted = false;
|
|
2207
3512
|
let doneSent = false;
|
|
3513
|
+
let streamError;
|
|
3514
|
+
let pendingRpcError;
|
|
3515
|
+
const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
2208
3516
|
try {
|
|
2209
3517
|
this._insideInferenceLoop = true;
|
|
2210
|
-
|
|
2211
|
-
|
|
3518
|
+
const flushState = {
|
|
3519
|
+
chunksSinceFlush: 0,
|
|
3520
|
+
hasFlushedContent: false
|
|
3521
|
+
};
|
|
2212
3522
|
try {
|
|
2213
|
-
|
|
3523
|
+
const guardedStream = this._iterateWithStallWatchdog(result.toUIMessageStream(), stallTimeoutMs, () => {
|
|
3524
|
+
this._emit("chat:stream:stalled", {
|
|
3525
|
+
requestId,
|
|
3526
|
+
timeoutMs: stallTimeoutMs
|
|
3527
|
+
});
|
|
3528
|
+
this.abortRequest(requestId, /* @__PURE__ */ new Error("chat stream stalled: inactivity watchdog fired"));
|
|
3529
|
+
});
|
|
3530
|
+
for await (const chunk of guardedStream) {
|
|
2214
3531
|
if (abortSignal?.aborted) {
|
|
2215
3532
|
aborted = true;
|
|
2216
3533
|
break;
|
|
@@ -2218,6 +3535,8 @@ var Think = class Think extends Agent {
|
|
|
2218
3535
|
const streamChunk = chunk;
|
|
2219
3536
|
const { action } = accumulator.applyChunk(streamChunk);
|
|
2220
3537
|
if (action?.type === "error") {
|
|
3538
|
+
streamError = action.error;
|
|
3539
|
+
this._emit("message:error", { error: streamError });
|
|
2221
3540
|
this._broadcastChat({
|
|
2222
3541
|
type: MSG_CHAT_RESPONSE,
|
|
2223
3542
|
id: requestId,
|
|
@@ -2225,16 +3544,10 @@ var Think = class Think extends Agent {
|
|
|
2225
3544
|
done: false,
|
|
2226
3545
|
error: true
|
|
2227
3546
|
});
|
|
2228
|
-
|
|
3547
|
+
break;
|
|
2229
3548
|
}
|
|
2230
3549
|
const chunkBody = JSON.stringify(chunk);
|
|
2231
|
-
this.
|
|
2232
|
-
chunksSinceFlush++;
|
|
2233
|
-
if (this._shouldFlushRpcStreamChunk(streamChunk, chunksSinceFlush, hasFlushedContent)) {
|
|
2234
|
-
this._resumableStream.flushBuffer();
|
|
2235
|
-
chunksSinceFlush = 0;
|
|
2236
|
-
hasFlushedContent = true;
|
|
2237
|
-
}
|
|
3550
|
+
await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
|
|
2238
3551
|
this._broadcastChat({
|
|
2239
3552
|
type: MSG_CHAT_RESPONSE,
|
|
2240
3553
|
id: requestId,
|
|
@@ -2246,7 +3559,8 @@ var Think = class Think extends Agent {
|
|
|
2246
3559
|
} finally {
|
|
2247
3560
|
this._insideInferenceLoop = false;
|
|
2248
3561
|
}
|
|
2249
|
-
this._resumableStream.
|
|
3562
|
+
if (streamError) this._resumableStream.markError(streamId);
|
|
3563
|
+
else this._resumableStream.complete(streamId);
|
|
2250
3564
|
streamFinalized = true;
|
|
2251
3565
|
this._broadcastChat({
|
|
2252
3566
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -2256,9 +3570,20 @@ var Think = class Think extends Agent {
|
|
|
2256
3570
|
});
|
|
2257
3571
|
doneSent = true;
|
|
2258
3572
|
assistantMsg = accumulator.toMessage();
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
3573
|
+
if (accumulator.parts.length > 0) {
|
|
3574
|
+
await this._persistAssistantMessage(assistantMsg);
|
|
3575
|
+
this._broadcastMessages();
|
|
3576
|
+
}
|
|
3577
|
+
if (streamError) {
|
|
3578
|
+
await this._fireResponseHook({
|
|
3579
|
+
message: assistantMsg,
|
|
3580
|
+
requestId,
|
|
3581
|
+
continuation: false,
|
|
3582
|
+
status: "error",
|
|
3583
|
+
error: streamError
|
|
3584
|
+
});
|
|
3585
|
+
pendingRpcError = streamError;
|
|
3586
|
+
} else if (!aborted) {
|
|
2262
3587
|
await callback.onDone();
|
|
2263
3588
|
await this._fireResponseHook({
|
|
2264
3589
|
message: assistantMsg,
|
|
@@ -2273,6 +3598,45 @@ var Think = class Think extends Agent {
|
|
|
2273
3598
|
status: "aborted"
|
|
2274
3599
|
});
|
|
2275
3600
|
} catch (error) {
|
|
3601
|
+
if (error instanceof ChatStreamStalledError) {
|
|
3602
|
+
if (!assistantMsg && accumulator.parts.length > 0) {
|
|
3603
|
+
assistantMsg = accumulator.toMessage();
|
|
3604
|
+
await this._persistAssistantMessage(assistantMsg);
|
|
3605
|
+
this._broadcastMessages();
|
|
3606
|
+
}
|
|
3607
|
+
const outcome = await this._routeStallToBoundedRecovery({
|
|
3608
|
+
requestId,
|
|
3609
|
+
streamId,
|
|
3610
|
+
partialParts: (assistantMsg ?? accumulator.toMessage()).parts,
|
|
3611
|
+
targetAssistantId: assistantMsg?.id
|
|
3612
|
+
});
|
|
3613
|
+
if (outcome === "scheduled") {
|
|
3614
|
+
if (!streamFinalized) {
|
|
3615
|
+
this._resumableStream.complete(streamId);
|
|
3616
|
+
streamFinalized = true;
|
|
3617
|
+
}
|
|
3618
|
+
if (!doneSent) {
|
|
3619
|
+
this._broadcastChat({
|
|
3620
|
+
type: MSG_CHAT_RESPONSE,
|
|
3621
|
+
id: requestId,
|
|
3622
|
+
body: "",
|
|
3623
|
+
done: true
|
|
3624
|
+
});
|
|
3625
|
+
doneSent = true;
|
|
3626
|
+
}
|
|
3627
|
+
await callback.onInterrupted?.();
|
|
3628
|
+
return;
|
|
3629
|
+
}
|
|
3630
|
+
if (outcome === "exhausted") {
|
|
3631
|
+
if (!streamFinalized) {
|
|
3632
|
+
this._resumableStream.markError(streamId);
|
|
3633
|
+
streamFinalized = true;
|
|
3634
|
+
}
|
|
3635
|
+
doneSent = true;
|
|
3636
|
+
await callback.onInterrupted?.();
|
|
3637
|
+
return;
|
|
3638
|
+
}
|
|
3639
|
+
}
|
|
2276
3640
|
if (!streamFinalized) {
|
|
2277
3641
|
this._resumableStream.markError(streamId);
|
|
2278
3642
|
streamFinalized = true;
|
|
@@ -2293,8 +3657,18 @@ var Think = class Think extends Agent {
|
|
|
2293
3657
|
await this._persistAssistantMessage(assistantMsg);
|
|
2294
3658
|
this._broadcastMessages();
|
|
2295
3659
|
}
|
|
2296
|
-
const wrapped = this.onChatError(error
|
|
3660
|
+
const wrapped = this.onChatError(error, {
|
|
3661
|
+
requestId,
|
|
3662
|
+
stage: "stream",
|
|
3663
|
+
messagesPersisted: true
|
|
3664
|
+
});
|
|
2297
3665
|
const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
|
|
3666
|
+
this._emit("chat:request:failed", {
|
|
3667
|
+
requestId,
|
|
3668
|
+
stage: "stream",
|
|
3669
|
+
messagesPersisted: true,
|
|
3670
|
+
error: errorMessage
|
|
3671
|
+
});
|
|
2298
3672
|
if (assistantMsg) await this._fireResponseHook({
|
|
2299
3673
|
message: assistantMsg,
|
|
2300
3674
|
requestId,
|
|
@@ -2302,12 +3676,87 @@ var Think = class Think extends Agent {
|
|
|
2302
3676
|
status: "error",
|
|
2303
3677
|
error: errorMessage
|
|
2304
3678
|
});
|
|
2305
|
-
|
|
2306
|
-
else throw wrapped;
|
|
3679
|
+
await callback.onError(errorMessage);
|
|
2307
3680
|
}
|
|
3681
|
+
if (pendingRpcError) await callback.onError(pendingRpcError);
|
|
2308
3682
|
}
|
|
2309
|
-
|
|
2310
|
-
|
|
3683
|
+
/**
|
|
3684
|
+
* Whether storing this chunk should immediately flush the resumable-stream
|
|
3685
|
+
* buffer to SQLite.
|
|
3686
|
+
*
|
|
3687
|
+
* A settled tool result (`tool-output-available` / `tool-output-error` /
|
|
3688
|
+
* `tool-output-denied`) captures a completed, often non-idempotent side
|
|
3689
|
+
* effect — or, for a denial, a user decision — so it is flushed
|
|
3690
|
+
* **immediately**. An isolate eviction (deploy) before the next batch flush
|
|
3691
|
+
* would otherwise lose it, and recovery would re-anchor without it and re-run
|
|
3692
|
+
* the already-completed tool call (or drop the denial). Frequent recoverable
|
|
3693
|
+
* content (text / reasoning / tool-input streaming) is throttled to avoid
|
|
3694
|
+
* write amplification.
|
|
3695
|
+
*/
|
|
3696
|
+
_shouldFlushRecoverableChunk(chunk, chunksSinceFlush, hasFlushedContent) {
|
|
3697
|
+
if (chunk.type === "tool-output-available" || chunk.type === "tool-output-error" || chunk.type === "tool-output-denied") return true;
|
|
3698
|
+
return (chunk.type === "text-delta" || chunk.type === "reasoning-delta" || chunk.type === "tool-input-available") && (!hasFlushedContent || chunksSinceFlush >= 10);
|
|
3699
|
+
}
|
|
3700
|
+
/**
|
|
3701
|
+
* Store a stream chunk, flushing settled tool results durably and promptly.
|
|
3702
|
+
* Shared by the WebSocket and sub-agent RPC streaming paths so both get
|
|
3703
|
+
* tool-call-level recovery durability (recovery loses at most the in-flight
|
|
3704
|
+
* step, never an already-completed tool call).
|
|
3705
|
+
*/
|
|
3706
|
+
async _storeChunkDurably(streamId, chunk, chunkBody, state) {
|
|
3707
|
+
this._resumableStream.storeChunk(streamId, chunkBody);
|
|
3708
|
+
state.chunksSinceFlush++;
|
|
3709
|
+
if (this._shouldFlushRecoverableChunk(chunk, state.chunksSinceFlush, state.hasFlushedContent)) {
|
|
3710
|
+
this._resumableStream.flushBuffer();
|
|
3711
|
+
state.chunksSinceFlush = 0;
|
|
3712
|
+
state.hasFlushedContent = true;
|
|
3713
|
+
await this._bumpChatRecoveryProgress();
|
|
3714
|
+
}
|
|
3715
|
+
}
|
|
3716
|
+
/**
|
|
3717
|
+
* Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives
|
|
3718
|
+
* within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and
|
|
3719
|
+
* the iterator throws, so the consumer loop exits with a terminal error
|
|
3720
|
+
* instead of parking forever on a hung provider/transport. `timeoutMs <= 0`
|
|
3721
|
+
* passes the source through untouched.
|
|
3722
|
+
*/
|
|
3723
|
+
async *_iterateWithStallWatchdog(source, timeoutMs, onStall) {
|
|
3724
|
+
if (!(timeoutMs > 0)) {
|
|
3725
|
+
yield* source;
|
|
3726
|
+
return;
|
|
3727
|
+
}
|
|
3728
|
+
const iterator = source[Symbol.asyncIterator]();
|
|
3729
|
+
let selfAborted = false;
|
|
3730
|
+
try {
|
|
3731
|
+
while (true) {
|
|
3732
|
+
let timer;
|
|
3733
|
+
let stalled = false;
|
|
3734
|
+
const stall = new Promise((_, reject) => {
|
|
3735
|
+
timer = setTimeout(() => {
|
|
3736
|
+
stalled = true;
|
|
3737
|
+
reject(new ChatStreamStalledError(`Chat stream stalled: no activity for ${timeoutMs}ms; the turn was aborted by the stall watchdog.`));
|
|
3738
|
+
}, timeoutMs);
|
|
3739
|
+
});
|
|
3740
|
+
const nextPromise = iterator.next();
|
|
3741
|
+
nextPromise.catch(() => {});
|
|
3742
|
+
let next;
|
|
3743
|
+
try {
|
|
3744
|
+
next = await Promise.race([nextPromise, stall]);
|
|
3745
|
+
} catch (err) {
|
|
3746
|
+
if (stalled) {
|
|
3747
|
+
selfAborted = true;
|
|
3748
|
+
onStall();
|
|
3749
|
+
}
|
|
3750
|
+
throw err;
|
|
3751
|
+
} finally {
|
|
3752
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
3753
|
+
}
|
|
3754
|
+
if (next.done) return;
|
|
3755
|
+
yield next.value;
|
|
3756
|
+
}
|
|
3757
|
+
} finally {
|
|
3758
|
+
if (!selfAborted) await iterator.return?.(void 0).catch(() => {});
|
|
3759
|
+
}
|
|
2311
3760
|
}
|
|
2312
3761
|
async _streamResult(requestId, result, abortSignal, options) {
|
|
2313
3762
|
const clearGen = this._turnQueue.generation;
|
|
@@ -2322,47 +3771,105 @@ var Think = class Think extends Agent {
|
|
|
2322
3771
|
let doneSent = false;
|
|
2323
3772
|
let streamAborted = false;
|
|
2324
3773
|
let streamError;
|
|
3774
|
+
let output;
|
|
3775
|
+
const flushState = {
|
|
3776
|
+
chunksSinceFlush: 0,
|
|
3777
|
+
hasFlushedContent: false
|
|
3778
|
+
};
|
|
3779
|
+
const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
|
|
2325
3780
|
try {
|
|
2326
3781
|
this._insideInferenceLoop = true;
|
|
2327
3782
|
try {
|
|
2328
|
-
|
|
3783
|
+
const guardedStream = this._iterateWithStallWatchdog(result.toUIMessageStream(), stallTimeoutMs, () => {
|
|
3784
|
+
this._emit("chat:stream:stalled", {
|
|
3785
|
+
requestId,
|
|
3786
|
+
timeoutMs: stallTimeoutMs
|
|
3787
|
+
});
|
|
3788
|
+
this.abortRequest(requestId, /* @__PURE__ */ new Error("chat stream stalled: inactivity watchdog fired"));
|
|
3789
|
+
});
|
|
3790
|
+
for await (const chunk of guardedStream) {
|
|
2329
3791
|
if (abortSignal?.aborted) {
|
|
2330
3792
|
streamAborted = true;
|
|
2331
3793
|
break;
|
|
2332
3794
|
}
|
|
2333
|
-
const
|
|
3795
|
+
const streamChunk = chunk;
|
|
3796
|
+
const { action } = accumulator.applyChunk(streamChunk);
|
|
3797
|
+
if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
|
|
2334
3798
|
if (action?.type === "error") {
|
|
3799
|
+
streamError = action.error;
|
|
3800
|
+
if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
3801
|
+
this._emit("message:error", { error: streamError });
|
|
2335
3802
|
this._broadcastChat({
|
|
2336
3803
|
type: MSG_CHAT_RESPONSE,
|
|
2337
3804
|
id: requestId,
|
|
2338
3805
|
body: action.error,
|
|
2339
3806
|
done: false,
|
|
2340
|
-
error: true
|
|
3807
|
+
error: true,
|
|
3808
|
+
...continuation && { continuation: true }
|
|
2341
3809
|
});
|
|
2342
|
-
|
|
3810
|
+
break;
|
|
2343
3811
|
}
|
|
2344
3812
|
const chunkBody = JSON.stringify(chunk);
|
|
2345
|
-
this.
|
|
3813
|
+
await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
|
|
2346
3814
|
this._broadcastChat({
|
|
2347
3815
|
type: MSG_CHAT_RESPONSE,
|
|
2348
3816
|
id: requestId,
|
|
2349
3817
|
body: chunkBody,
|
|
2350
|
-
done: false
|
|
3818
|
+
done: false,
|
|
3819
|
+
...continuation && { continuation: true }
|
|
2351
3820
|
});
|
|
2352
3821
|
}
|
|
2353
3822
|
} finally {
|
|
2354
3823
|
this._insideInferenceLoop = false;
|
|
2355
3824
|
}
|
|
2356
|
-
this._resumableStream.
|
|
3825
|
+
if (streamError) this._resumableStream.markError(streamId);
|
|
3826
|
+
else this._resumableStream.complete(streamId);
|
|
2357
3827
|
this._pendingResumeConnections.clear();
|
|
2358
3828
|
this._broadcastChat({
|
|
2359
3829
|
type: MSG_CHAT_RESPONSE,
|
|
2360
3830
|
id: requestId,
|
|
2361
3831
|
body: "",
|
|
2362
|
-
done: true
|
|
3832
|
+
done: true,
|
|
3833
|
+
...continuation && { continuation: true }
|
|
2363
3834
|
});
|
|
2364
3835
|
doneSent = true;
|
|
2365
3836
|
} catch (error) {
|
|
3837
|
+
if (error instanceof ChatStreamStalledError) {
|
|
3838
|
+
let targetAssistantId;
|
|
3839
|
+
const partialMsg = accumulator.toMessage();
|
|
3840
|
+
if (this._turnQueue.generation === clearGen && accumulator.parts.length > 0) {
|
|
3841
|
+
await this._persistAssistantMessage(partialMsg, parentId);
|
|
3842
|
+
this._broadcastMessages();
|
|
3843
|
+
targetAssistantId = partialMsg.id;
|
|
3844
|
+
}
|
|
3845
|
+
const outcome = await this._routeStallToBoundedRecovery({
|
|
3846
|
+
requestId,
|
|
3847
|
+
streamId,
|
|
3848
|
+
partialParts: partialMsg.parts,
|
|
3849
|
+
targetAssistantId
|
|
3850
|
+
});
|
|
3851
|
+
if (outcome === "scheduled") {
|
|
3852
|
+
this._resumableStream.complete(streamId);
|
|
3853
|
+
this._pendingResumeConnections.clear();
|
|
3854
|
+
if (!doneSent) {
|
|
3855
|
+
this._broadcastChat({
|
|
3856
|
+
type: MSG_CHAT_RESPONSE,
|
|
3857
|
+
id: requestId,
|
|
3858
|
+
body: "",
|
|
3859
|
+
done: true,
|
|
3860
|
+
...continuation && { continuation: true }
|
|
3861
|
+
});
|
|
3862
|
+
doneSent = true;
|
|
3863
|
+
}
|
|
3864
|
+
return { status: "aborted" };
|
|
3865
|
+
}
|
|
3866
|
+
if (outcome === "exhausted") {
|
|
3867
|
+
this._resumableStream.markError(streamId);
|
|
3868
|
+
this._pendingResumeConnections.clear();
|
|
3869
|
+
doneSent = true;
|
|
3870
|
+
return { status: "aborted" };
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
2366
3873
|
streamError = error instanceof Error ? error.message : "Stream error";
|
|
2367
3874
|
if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
2368
3875
|
this._resumableStream.markError(streamId);
|
|
@@ -2373,7 +3880,8 @@ var Think = class Think extends Agent {
|
|
|
2373
3880
|
id: requestId,
|
|
2374
3881
|
body: streamError,
|
|
2375
3882
|
done: true,
|
|
2376
|
-
error: true
|
|
3883
|
+
error: true,
|
|
3884
|
+
...continuation && { continuation: true }
|
|
2377
3885
|
});
|
|
2378
3886
|
doneSent = true;
|
|
2379
3887
|
}
|
|
@@ -2385,24 +3893,40 @@ var Think = class Think extends Agent {
|
|
|
2385
3893
|
type: MSG_CHAT_RESPONSE,
|
|
2386
3894
|
id: requestId,
|
|
2387
3895
|
body: "",
|
|
2388
|
-
done: true
|
|
3896
|
+
done: true,
|
|
3897
|
+
...continuation && { continuation: true }
|
|
2389
3898
|
});
|
|
2390
3899
|
}
|
|
2391
3900
|
}
|
|
2392
|
-
if (
|
|
3901
|
+
if (options?.captureOutput && result.output && !streamError && !streamAborted) try {
|
|
3902
|
+
output = await result.output;
|
|
3903
|
+
} catch (error) {
|
|
3904
|
+
streamError = error instanceof Error ? error.message : "Structured output error";
|
|
3905
|
+
if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
|
|
3906
|
+
}
|
|
3907
|
+
if (this._turnQueue.generation === clearGen) try {
|
|
2393
3908
|
const assistantMsg = accumulator.toMessage();
|
|
2394
|
-
|
|
2395
|
-
|
|
3909
|
+
if (accumulator.parts.length > 0) {
|
|
3910
|
+
await this._persistAssistantMessage(assistantMsg, parentId);
|
|
3911
|
+
this._broadcastMessages();
|
|
3912
|
+
}
|
|
2396
3913
|
await this._fireResponseHook({
|
|
2397
3914
|
message: assistantMsg,
|
|
2398
3915
|
requestId,
|
|
2399
3916
|
continuation,
|
|
2400
|
-
status:
|
|
3917
|
+
status: streamError ? "error" : streamAborted ? "aborted" : "completed",
|
|
2401
3918
|
error: streamError
|
|
2402
3919
|
});
|
|
2403
3920
|
} catch (e) {
|
|
2404
3921
|
console.error("Failed to persist assistant message:", e);
|
|
2405
3922
|
}
|
|
3923
|
+
return streamError ? {
|
|
3924
|
+
status: "error",
|
|
3925
|
+
error: streamError
|
|
3926
|
+
} : {
|
|
3927
|
+
status: streamAborted ? "aborted" : "completed",
|
|
3928
|
+
...output !== void 0 && { output }
|
|
3929
|
+
};
|
|
2406
3930
|
}
|
|
2407
3931
|
async _persistAssistantMessage(msg, parentId) {
|
|
2408
3932
|
await this._upsertMessageInHistory(msg, parentId);
|
|
@@ -2453,13 +3977,16 @@ var Think = class Think extends Agent {
|
|
|
2453
3977
|
const history = await this._readMessagesFromStorage();
|
|
2454
3978
|
for (let i = 0; i < history.length; i++) {
|
|
2455
3979
|
const msg = history[i];
|
|
2456
|
-
const
|
|
3980
|
+
const msgParts = msg.parts;
|
|
3981
|
+
const result = applyToolUpdate(msgParts, update);
|
|
2457
3982
|
if (result) {
|
|
3983
|
+
if (result.parts[result.index] === msgParts[result.index]) return;
|
|
2458
3984
|
const updatedMsg = {
|
|
2459
3985
|
...msg,
|
|
2460
3986
|
parts: result.parts
|
|
2461
3987
|
};
|
|
2462
3988
|
const safe = await this._updateMessageInHistory(updatedMsg);
|
|
3989
|
+
this._patchCachedMessage(safe);
|
|
2463
3990
|
this._broadcast({
|
|
2464
3991
|
type: MSG_MESSAGE_UPDATED,
|
|
2465
3992
|
message: safe
|
|
@@ -2501,10 +4028,239 @@ var Think = class Think extends Agent {
|
|
|
2501
4028
|
_messageHasPendingInteraction(message) {
|
|
2502
4029
|
return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
|
|
2503
4030
|
}
|
|
4031
|
+
_resolveChatRecoveryConfig() {
|
|
4032
|
+
const raw = this.chatRecovery;
|
|
4033
|
+
const custom = typeof raw === "object" ? raw : void 0;
|
|
4034
|
+
return {
|
|
4035
|
+
enabled: raw !== false,
|
|
4036
|
+
maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
|
|
4037
|
+
stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
|
|
4038
|
+
terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
|
|
4039
|
+
...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
|
|
4040
|
+
};
|
|
4041
|
+
}
|
|
4042
|
+
_chatRecoveryIncidentId(input) {
|
|
4043
|
+
return [input.recoveryRootRequestId ?? input.requestId, input.latestUserMessageId ?? ""].join(":");
|
|
4044
|
+
}
|
|
4045
|
+
_chatRecoveryIncidentKey(incidentId) {
|
|
4046
|
+
return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;
|
|
4047
|
+
}
|
|
4048
|
+
/**
|
|
4049
|
+
* Monotonic forward-progress signal for recovery budget resets.
|
|
4050
|
+
*
|
|
4051
|
+
* This used to count assistant messages in `this.messages`, but that is
|
|
4052
|
+
* recomputed from the live, mutable transcript. Compaction collapses older
|
|
4053
|
+
* assistant messages into a summary, lowering the count — so a turn that had
|
|
4054
|
+
* genuinely advanced could read as "no progress" between attempts and exhaust
|
|
4055
|
+
* its budget prematurely (#1628). Instead we read a durably-persisted counter
|
|
4056
|
+
* that only ever increments — bumped at production time when new content is
|
|
4057
|
+
* durably flushed (see `_storeChunkDurably`), which is genuine forward
|
|
4058
|
+
* progress and is immune to client reconnects / recovery re-persists — so
|
|
4059
|
+
* compaction can never lower it and a reconnect can't fake it (#1637).
|
|
4060
|
+
*/
|
|
4061
|
+
async _chatRecoveryProgressMarker() {
|
|
4062
|
+
return await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
|
|
4063
|
+
}
|
|
4064
|
+
/** Advance the durable recovery-progress counter. Called from
|
|
4065
|
+
* `_storeChunkDurably` when new content is durably flushed (real, reconnect-
|
|
4066
|
+
* immune forward progress). */
|
|
4067
|
+
async _bumpChatRecoveryProgress() {
|
|
4068
|
+
const current = await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
|
|
4069
|
+
await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);
|
|
4070
|
+
}
|
|
4071
|
+
/**
|
|
4072
|
+
* N9: forwarding a sub-agent's chunks IS forward progress for this parent
|
|
4073
|
+
* turn, so credit the parent's recovery progress marker — otherwise a parent
|
|
4074
|
+
* whose turn merely `await`s a child banks no progress of its own and its
|
|
4075
|
+
* no-progress window exhausts while the child is healthily streaming. Only
|
|
4076
|
+
* invoked after a child actually produced output (see
|
|
4077
|
+
* `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
|
|
4078
|
+
* Throttled (and reset per isolate) so we never write storage per token.
|
|
4079
|
+
*/
|
|
4080
|
+
async _onAgentToolStreamProgress() {
|
|
4081
|
+
const now = Date.now();
|
|
4082
|
+
if (now - this._lastAgentToolStreamProgressAt < AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS) return;
|
|
4083
|
+
this._lastAgentToolStreamProgressAt = now;
|
|
4084
|
+
await this._bumpChatRecoveryProgress();
|
|
4085
|
+
}
|
|
4086
|
+
/** Sweep recovery incidents that have been inactive past the TTL. */
|
|
4087
|
+
async _sweepStaleChatRecoveryIncidents(now) {
|
|
4088
|
+
const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
|
|
4089
|
+
const staleKeys = [];
|
|
4090
|
+
for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
|
|
4091
|
+
for (const key of staleKeys) await this.ctx.storage.delete(key);
|
|
4092
|
+
}
|
|
4093
|
+
async _beginChatRecoveryIncident(input) {
|
|
4094
|
+
const config = this._resolveChatRecoveryConfig();
|
|
4095
|
+
const incidentId = this._chatRecoveryIncidentId(input);
|
|
4096
|
+
const key = this._chatRecoveryIncidentKey(incidentId);
|
|
4097
|
+
const now = input.nowMs ?? Date.now();
|
|
4098
|
+
await this._sweepStaleChatRecoveryIncidents(now);
|
|
4099
|
+
const existing = await this.ctx.storage.get(key);
|
|
4100
|
+
const prevProgress = existing?.progress ?? 0;
|
|
4101
|
+
const currentProgress = await this._chatRecoveryProgressMarker();
|
|
4102
|
+
const madeProgress = existing != null && currentProgress > prevProgress;
|
|
4103
|
+
const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
|
|
4104
|
+
const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
|
|
4105
|
+
const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
|
|
4106
|
+
const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
|
|
4107
|
+
const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
|
|
4108
|
+
const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
|
|
4109
|
+
const incident = {
|
|
4110
|
+
incidentId,
|
|
4111
|
+
requestId: input.requestId,
|
|
4112
|
+
recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
|
|
4113
|
+
recoveryKind: input.recoveryKind,
|
|
4114
|
+
attempt,
|
|
4115
|
+
maxAttempts: config.maxAttempts,
|
|
4116
|
+
status: exhausted ? "exhausted" : "attempting",
|
|
4117
|
+
firstSeenAt: existing?.firstSeenAt ?? now,
|
|
4118
|
+
lastAttemptAt: now,
|
|
4119
|
+
lastProgressAt,
|
|
4120
|
+
progress: Math.max(prevProgress, currentProgress),
|
|
4121
|
+
...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
|
|
4122
|
+
};
|
|
4123
|
+
await this.ctx.storage.put(key, incident);
|
|
4124
|
+
if (!existing) this._emit("chat:recovery:detected", {
|
|
4125
|
+
incidentId,
|
|
4126
|
+
requestId: input.requestId,
|
|
4127
|
+
attempt,
|
|
4128
|
+
maxAttempts: config.maxAttempts,
|
|
4129
|
+
recoveryKind: input.recoveryKind
|
|
4130
|
+
});
|
|
4131
|
+
this._emit("chat:recovery:attempt", {
|
|
4132
|
+
incidentId,
|
|
4133
|
+
requestId: input.requestId,
|
|
4134
|
+
attempt,
|
|
4135
|
+
maxAttempts: config.maxAttempts,
|
|
4136
|
+
recoveryKind: input.recoveryKind
|
|
4137
|
+
});
|
|
4138
|
+
return {
|
|
4139
|
+
incident,
|
|
4140
|
+
config,
|
|
4141
|
+
exhausted
|
|
4142
|
+
};
|
|
4143
|
+
}
|
|
4144
|
+
async _updateChatRecoveryIncident(incidentId, status, reason) {
|
|
4145
|
+
if (!incidentId) return;
|
|
4146
|
+
const key = this._chatRecoveryIncidentKey(incidentId);
|
|
4147
|
+
const incident = await this.ctx.storage.get(key);
|
|
4148
|
+
if (!incident) return;
|
|
4149
|
+
if (status === "completed") await this.ctx.storage.delete(key);
|
|
4150
|
+
else await this.ctx.storage.put(key, {
|
|
4151
|
+
...incident,
|
|
4152
|
+
status,
|
|
4153
|
+
...reason ? { reason } : {}
|
|
4154
|
+
});
|
|
4155
|
+
const eventType = status === "completed" ? "chat:recovery:completed" : status === "skipped" ? "chat:recovery:skipped" : status === "failed" ? "chat:recovery:failed" : void 0;
|
|
4156
|
+
if (eventType) this._emit(eventType, {
|
|
4157
|
+
incidentId,
|
|
4158
|
+
requestId: incident.requestId,
|
|
4159
|
+
attempt: incident.attempt,
|
|
4160
|
+
maxAttempts: incident.maxAttempts,
|
|
4161
|
+
recoveryKind: incident.recoveryKind,
|
|
4162
|
+
...reason ? { reason } : {}
|
|
4163
|
+
});
|
|
4164
|
+
if (status === "scheduled") await this._setChatRecovering(true, incident.recoveryRootRequestId ?? incident.requestId);
|
|
4165
|
+
else if (status === "completed" || status === "skipped" || status === "failed") await this._setChatRecovering(false);
|
|
4166
|
+
}
|
|
4167
|
+
async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
|
|
4168
|
+
const ctx = {
|
|
4169
|
+
incidentId: incident.incidentId,
|
|
4170
|
+
requestId: incident.requestId,
|
|
4171
|
+
recoveryRootRequestId: incident.recoveryRootRequestId ?? incident.requestId,
|
|
4172
|
+
attempt: incident.attempt,
|
|
4173
|
+
maxAttempts: incident.maxAttempts,
|
|
4174
|
+
recoveryKind: incident.recoveryKind,
|
|
4175
|
+
streamId,
|
|
4176
|
+
createdAt,
|
|
4177
|
+
partialText: partial.text,
|
|
4178
|
+
partialParts: partial.parts,
|
|
4179
|
+
reason: incident.reason ?? "max_attempts_exceeded",
|
|
4180
|
+
terminalMessage: config.terminalMessage
|
|
4181
|
+
};
|
|
4182
|
+
this._emit("chat:recovery:exhausted", ctx);
|
|
4183
|
+
try {
|
|
4184
|
+
await config.onExhausted?.(ctx);
|
|
4185
|
+
} catch (error) {
|
|
4186
|
+
console.error("[Think] chatRecovery onExhausted hook threw", error);
|
|
4187
|
+
}
|
|
4188
|
+
await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
|
|
4189
|
+
await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
|
|
4190
|
+
this._broadcastChat({
|
|
4191
|
+
type: MSG_CHAT_RESPONSE,
|
|
4192
|
+
id: incident.requestId,
|
|
4193
|
+
body: config.terminalMessage,
|
|
4194
|
+
done: true,
|
|
4195
|
+
error: true
|
|
4196
|
+
});
|
|
4197
|
+
}
|
|
4198
|
+
/**
|
|
4199
|
+
* Route a stream-stall watchdog abort into bounded recovery instead of a
|
|
4200
|
+
* terminal error (#1626). A stall happens inside a LIVE isolate (no DO
|
|
4201
|
+
* restart), so the normal restart-detected recovery path never runs — we
|
|
4202
|
+
* open/advance a recovery incident here and schedule a continuation, reusing
|
|
4203
|
+
* the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
|
|
4204
|
+
* as deploy/eviction recovery. A transient hang recovers; a persistently
|
|
4205
|
+
* hanging provider exhausts the budget. Idempotency matches deploy recovery:
|
|
4206
|
+
* settled tool results are durable and won't re-run, but a tool that was
|
|
4207
|
+
* mid-execution when the stall fired re-runs on the continuation.
|
|
4208
|
+
*
|
|
4209
|
+
* Returns:
|
|
4210
|
+
* - `"scheduled"` — a continuation was scheduled; the caller suppresses the
|
|
4211
|
+
* terminal error and closes the stream cleanly.
|
|
4212
|
+
* - `"exhausted"` — the budget is spent; this routes through the SAME
|
|
4213
|
+
* `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
|
|
4214
|
+
* emits `chat:recovery:exhausted`, marks the submission interrupted, and
|
|
4215
|
+
* delivers the configured `terminalMessage`). The caller must NOT run the
|
|
4216
|
+
* generic terminal path — the terminal UX is already delivered.
|
|
4217
|
+
* - `"disabled"` — chat recovery is off; the caller falls through to the
|
|
4218
|
+
* generic terminal error (the watchdog's original "kill the spinner"
|
|
4219
|
+
* behavior, unchanged).
|
|
4220
|
+
*/
|
|
4221
|
+
async _routeStallToBoundedRecovery(input) {
|
|
4222
|
+
if (!this._resolveChatRecoveryConfig().enabled) return "disabled";
|
|
4223
|
+
const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
|
|
4224
|
+
const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
|
|
4225
|
+
const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
|
|
4226
|
+
requestId: input.requestId,
|
|
4227
|
+
recoveryRootRequestId,
|
|
4228
|
+
latestUserMessageId,
|
|
4229
|
+
recoveryKind: "continue"
|
|
4230
|
+
});
|
|
4231
|
+
if (exhausted) {
|
|
4232
|
+
const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
|
|
4233
|
+
await this._exhaustChatRecovery(incident, config, {
|
|
4234
|
+
text: partialText,
|
|
4235
|
+
parts: input.partialParts
|
|
4236
|
+
}, input.streamId, incident.firstSeenAt);
|
|
4237
|
+
return "exhausted";
|
|
4238
|
+
}
|
|
4239
|
+
await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
|
|
4240
|
+
this._emit("chat:recovery:scheduled", {
|
|
4241
|
+
incidentId: incident.incidentId,
|
|
4242
|
+
requestId: input.requestId,
|
|
4243
|
+
attempt: incident.attempt,
|
|
4244
|
+
maxAttempts: incident.maxAttempts,
|
|
4245
|
+
recoveryKind: "continue"
|
|
4246
|
+
});
|
|
4247
|
+
const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId) ? recoveryRootRequestId : void 0;
|
|
4248
|
+
await this.schedule(0, "_chatRecoveryContinue", {
|
|
4249
|
+
...input.targetAssistantId ? { targetAssistantId: input.targetAssistantId } : {},
|
|
4250
|
+
originalRequestId: recoveryRootRequestId,
|
|
4251
|
+
incidentId: incident.incidentId,
|
|
4252
|
+
lastBody: this._lastBody ?? null,
|
|
4253
|
+
lastClientTools: this._lastClientTools ?? null,
|
|
4254
|
+
...recoveredRequestId ? { recoveredRequestId } : {}
|
|
4255
|
+
}, { idempotent: true });
|
|
4256
|
+
return "scheduled";
|
|
4257
|
+
}
|
|
2504
4258
|
async _handleInternalFiberRecovery(ctx) {
|
|
4259
|
+
if (await this._messengerRuntime?.handleFiberRecovery(ctx)) return true;
|
|
2505
4260
|
const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
|
|
2506
4261
|
if (!ctx.name.startsWith(chatPrefix)) return false;
|
|
2507
4262
|
const requestId = ctx.name.slice(chatPrefix.length);
|
|
4263
|
+
const { snapshot: recoverySnapshot, user: recoveryData } = unwrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", ctx.snapshot, "think-chat-turn");
|
|
2508
4264
|
let streamId = "";
|
|
2509
4265
|
let streamStatus;
|
|
2510
4266
|
if (requestId) {
|
|
@@ -2526,35 +4282,287 @@ var Think = class Think extends Agent {
|
|
|
2526
4282
|
text: "",
|
|
2527
4283
|
parts: []
|
|
2528
4284
|
};
|
|
2529
|
-
const options = await this.onChatRecovery({
|
|
2530
|
-
streamId: streamId ?? "",
|
|
2531
|
-
requestId,
|
|
2532
|
-
partialText: partial.text,
|
|
2533
|
-
partialParts: partial.parts,
|
|
2534
|
-
recoveryData: ctx.snapshot,
|
|
2535
|
-
messages: [...this.messages],
|
|
2536
|
-
lastBody: this._lastBody,
|
|
2537
|
-
lastClientTools: this._lastClientTools,
|
|
2538
|
-
createdAt: ctx.createdAt
|
|
2539
|
-
});
|
|
2540
4285
|
const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
|
|
2541
4286
|
const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
const
|
|
2545
|
-
const
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
4287
|
+
const retryTargetUserId = await this._recoverablePreStreamUserId(recoverySnapshot, streamId ?? "", partial);
|
|
4288
|
+
const recoveryKind = retryTargetUserId !== null && !streamIsTerminal ? "retry" : "continue";
|
|
4289
|
+
const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
|
|
4290
|
+
const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
|
|
4291
|
+
requestId,
|
|
4292
|
+
recoveryRootRequestId,
|
|
4293
|
+
latestUserMessageId: recoverySnapshot?.latestUserMessageId,
|
|
4294
|
+
recoveryKind
|
|
4295
|
+
});
|
|
4296
|
+
if (exhausted) {
|
|
4297
|
+
if (await this._shouldPersistOrphanedPartial(streamId, {
|
|
4298
|
+
streamStillActive: Boolean(streamStillActive),
|
|
4299
|
+
streamIsTerminal,
|
|
4300
|
+
snapshot: recoverySnapshot
|
|
4301
|
+
})) await this._persistOrphanedStream(streamId);
|
|
4302
|
+
await this._exhaustChatRecovery(incident, config, partial, streamId ?? "", ctx.createdAt);
|
|
4303
|
+
return true;
|
|
4304
|
+
}
|
|
4305
|
+
try {
|
|
4306
|
+
const options = await this.onChatRecovery({
|
|
4307
|
+
incidentId: incident.incidentId,
|
|
4308
|
+
recoveryRootRequestId,
|
|
4309
|
+
attempt: incident.attempt,
|
|
4310
|
+
maxAttempts: incident.maxAttempts,
|
|
4311
|
+
recoveryKind,
|
|
4312
|
+
streamId: streamId ?? "",
|
|
4313
|
+
requestId,
|
|
4314
|
+
partialText: partial.text,
|
|
4315
|
+
partialParts: partial.parts,
|
|
4316
|
+
recoveryData,
|
|
4317
|
+
messages: [...this.messages],
|
|
4318
|
+
lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
|
|
4319
|
+
lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
|
|
4320
|
+
createdAt: ctx.createdAt
|
|
4321
|
+
}) ?? {};
|
|
4322
|
+
if (await this._shouldPersistOrphanedPartial(streamId, {
|
|
4323
|
+
streamStillActive: Boolean(streamStillActive),
|
|
4324
|
+
streamIsTerminal,
|
|
4325
|
+
snapshot: recoverySnapshot
|
|
4326
|
+
}) && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
|
|
4327
|
+
if (streamStillActive) this._resumableStream.complete(streamId);
|
|
4328
|
+
const shouldRetry = retryTargetUserId !== null && options.continue !== false && !streamIsTerminal;
|
|
4329
|
+
const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();
|
|
4330
|
+
const targetId = lastLeaf?.role === "assistant" && !streamIsTerminal ? lastLeaf.id : void 0;
|
|
4331
|
+
const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
|
|
4332
|
+
const hasRunningSubmission = this._hasRunningSubmission(recoveryRootRequestId);
|
|
4333
|
+
if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(recoveryRootRequestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
|
|
4334
|
+
const recoveredRequestId = (canContinue || shouldRetry) && hasRunningSubmission ? recoveryRootRequestId : void 0;
|
|
4335
|
+
if (shouldRetry) {
|
|
4336
|
+
await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
|
|
4337
|
+
this._emit("chat:recovery:scheduled", {
|
|
4338
|
+
incidentId: incident.incidentId,
|
|
4339
|
+
requestId,
|
|
4340
|
+
attempt: incident.attempt,
|
|
4341
|
+
maxAttempts: incident.maxAttempts,
|
|
4342
|
+
recoveryKind
|
|
4343
|
+
});
|
|
4344
|
+
await this.schedule(0, "_chatRecoveryRetry", {
|
|
4345
|
+
targetUserId: retryTargetUserId,
|
|
4346
|
+
originalRequestId: recoveryRootRequestId,
|
|
4347
|
+
incidentId: incident.incidentId,
|
|
4348
|
+
lastBody: recoverySnapshot?.lastBody ?? null,
|
|
4349
|
+
lastClientTools: recoverySnapshot?.lastClientTools ?? null,
|
|
4350
|
+
...recoveredRequestId ? { recoveredRequestId } : {}
|
|
4351
|
+
}, { idempotent: true });
|
|
4352
|
+
} else if (canContinue) {
|
|
4353
|
+
await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
|
|
4354
|
+
this._emit("chat:recovery:scheduled", {
|
|
4355
|
+
incidentId: incident.incidentId,
|
|
4356
|
+
requestId,
|
|
4357
|
+
attempt: incident.attempt,
|
|
4358
|
+
maxAttempts: incident.maxAttempts,
|
|
4359
|
+
recoveryKind
|
|
4360
|
+
});
|
|
4361
|
+
await this.schedule(0, "_chatRecoveryContinue", {
|
|
4362
|
+
...targetId ? { targetAssistantId: targetId } : {},
|
|
4363
|
+
originalRequestId: recoveryRootRequestId,
|
|
4364
|
+
incidentId: incident.incidentId,
|
|
4365
|
+
...recoverySnapshot ? {
|
|
4366
|
+
lastBody: recoverySnapshot.lastBody ?? null,
|
|
4367
|
+
lastClientTools: recoverySnapshot.lastClientTools ?? null
|
|
4368
|
+
} : {},
|
|
4369
|
+
...recoveredRequestId ? { recoveredRequestId } : {}
|
|
4370
|
+
}, { idempotent: true });
|
|
4371
|
+
} else if (options.continue === false && !streamIsTerminal) {
|
|
4372
|
+
await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
|
|
4373
|
+
const disabledMessage = "Submission was interrupted and chat recovery was disabled.";
|
|
4374
|
+
await this._markRecoveredSubmissionInterrupted(recoveryRootRequestId, disabledMessage);
|
|
4375
|
+
await this._recordTerminalChatStatus("interrupted", requestId, disabledMessage);
|
|
4376
|
+
this._broadcastChat({
|
|
4377
|
+
type: MSG_CHAT_RESPONSE,
|
|
4378
|
+
id: requestId,
|
|
4379
|
+
body: disabledMessage,
|
|
4380
|
+
done: true,
|
|
4381
|
+
error: true
|
|
4382
|
+
});
|
|
4383
|
+
} else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", streamIsTerminal ? "stream_terminal" : "not_recoverable");
|
|
4384
|
+
return true;
|
|
4385
|
+
} catch (error) {
|
|
4386
|
+
await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
|
|
4387
|
+
throw error;
|
|
4388
|
+
}
|
|
4389
|
+
}
|
|
4390
|
+
async _recoverablePreStreamUserId(snapshot, streamId, partial) {
|
|
4391
|
+
if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return null;
|
|
4392
|
+
const lastLeaf = await this.session.getLatestLeaf();
|
|
4393
|
+
return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
|
|
4394
|
+
}
|
|
4395
|
+
async _hasPersistedRecoveredAssistant(snapshot) {
|
|
4396
|
+
const lastLeaf = await this.session.getLatestLeaf();
|
|
4397
|
+
return lastLeaf?.role === "assistant" && lastLeaf.id !== snapshot?.latestMessageId;
|
|
4398
|
+
}
|
|
4399
|
+
/**
|
|
4400
|
+
* Whether the orphaned stream's partial should be materialized into an
|
|
4401
|
+
* assistant message: there is a stream, and it is either still active or
|
|
4402
|
+
* terminal-but-not-yet-persisted. Shared by the normal recovery path AND the
|
|
4403
|
+
* exhaustion path so neither discards settled work nor duplicates a partial
|
|
4404
|
+
* an earlier attempt already saved.
|
|
4405
|
+
*/
|
|
4406
|
+
async _shouldPersistOrphanedPartial(streamId, opts) {
|
|
4407
|
+
if (!streamId) return false;
|
|
4408
|
+
const alreadyPersisted = opts.streamIsTerminal && await this._hasPersistedRecoveredAssistant(opts.snapshot);
|
|
4409
|
+
return opts.streamStillActive || opts.streamIsTerminal && !alreadyPersisted;
|
|
4410
|
+
}
|
|
4411
|
+
/** Whether a reconstructed partial carries any settled (provider-accepted)
|
|
4412
|
+
* tool result — the completed, often non-idempotent work that a
|
|
4413
|
+
* `{ persist: false }` recovery return would silently discard. */
|
|
4414
|
+
_partialHasSettledToolResults(parts) {
|
|
4415
|
+
return parts.some((part) => {
|
|
4416
|
+
const record = part;
|
|
4417
|
+
const type = typeof record.type === "string" ? record.type : "";
|
|
4418
|
+
return (type.startsWith("tool-") || type === "dynamic-tool") && this._toolPartHasSettledResult(record);
|
|
4419
|
+
});
|
|
4420
|
+
}
|
|
4421
|
+
/**
|
|
4422
|
+
* Reschedule a recovery callback that timed out waiting for stable state,
|
|
4423
|
+
* consuming one attempt. Returns `true` if rescheduled, `false` if the
|
|
4424
|
+
* attempt budget is exhausted (the caller then fails the turn terminally).
|
|
4425
|
+
*
|
|
4426
|
+
* Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the
|
|
4427
|
+
* non-idempotent scheduling invariant lives in exactly one place — a fix to
|
|
4428
|
+
* one path can't silently diverge from the other. Mirrors the same helper in
|
|
4429
|
+
* `@cloudflare/ai-chat`.
|
|
4430
|
+
*/
|
|
4431
|
+
async _rescheduleRecoveryAfterStableTimeout(callback, data, maxAttempts) {
|
|
4432
|
+
const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
|
|
4433
|
+
const incident = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
|
|
4434
|
+
if (!incident || !incidentKey) return false;
|
|
4435
|
+
const attempt = incident.attempt ?? 0;
|
|
4436
|
+
if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;
|
|
4437
|
+
await this.ctx.storage.put(incidentKey, {
|
|
4438
|
+
...incident,
|
|
4439
|
+
attempt: attempt + 1,
|
|
4440
|
+
status: "scheduled",
|
|
4441
|
+
lastAttemptAt: Date.now(),
|
|
4442
|
+
reason: "stable_timeout_retry"
|
|
4443
|
+
});
|
|
4444
|
+
await this.schedule(CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, callback, data ?? {}, { idempotent: false });
|
|
2556
4445
|
return true;
|
|
2557
4446
|
}
|
|
4447
|
+
/**
|
|
4448
|
+
* Resolve the stream id for a recovery turn so the give-up terminalization
|
|
4449
|
+
* can surface whatever partial the turn produced. Prefers the durable stream
|
|
4450
|
+
* row keyed by the recovery-root request id; falls back to the live active
|
|
4451
|
+
* stream. Returns `""` when neither is available (the terminal banner still
|
|
4452
|
+
* fires — `_exhaustChatRecovery` does not require a stream).
|
|
4453
|
+
*/
|
|
4454
|
+
_resolveRecoveryStreamId(requestId) {
|
|
4455
|
+
if (requestId) {
|
|
4456
|
+
const fromMetadata = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id;
|
|
4457
|
+
if (fromMetadata) return fromMetadata;
|
|
4458
|
+
}
|
|
4459
|
+
return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
|
|
4460
|
+
}
|
|
4461
|
+
/**
|
|
4462
|
+
* Terminalize a recovery turn that has run out of stable-state-timeout retry
|
|
4463
|
+
* budget — or whose incident record has vanished — by routing through the
|
|
4464
|
+
* SAME `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
|
|
4465
|
+
* (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
|
|
4466
|
+
* marks the durable submission interrupted, records the terminal chat status,
|
|
4467
|
+
* and delivers the configured `terminalMessage`.
|
|
4468
|
+
*
|
|
4469
|
+
* This replaces the older give-up that only set the incident to `failed` and
|
|
4470
|
+
* completed the recovered submission as `error`, which bypassed
|
|
4471
|
+
* `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
|
|
4472
|
+
* terminal banner regressed to an eternal spinner when recovery gave up under
|
|
4473
|
+
* extreme churn (the stable-state wait timing out every attempt until the
|
|
4474
|
+
* budget drained). Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue`.
|
|
4475
|
+
*
|
|
4476
|
+
* Exactly-once terminalization is defended by two independent guards:
|
|
4477
|
+
* 1. The `stored?.status === "exhausted"` re-entry guard below — once an
|
|
4478
|
+
* incident is sealed, a duplicate stale alarm (or retried callback)
|
|
4479
|
+
* returns before re-firing. The sealed incident is re-persisted even when
|
|
4480
|
+
* the record was found missing, so a swept record is re-armed for the
|
|
4481
|
+
* guard on the next alarm.
|
|
4482
|
+
* 2. The durable-submission paths additionally short-circuit earlier at the
|
|
4483
|
+
* `submission_not_running` check (the submission is already `error` after
|
|
4484
|
+
* the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks
|
|
4485
|
+
* (no submission layer), so guard #1 carries it there.
|
|
4486
|
+
*
|
|
4487
|
+
* Two residual at-least-once edges, both deliberately accepted as "deliver a
|
|
4488
|
+
* second banner" ≫ "silently drop the turn":
|
|
4489
|
+
* • No `incidentId` at all in the payload (only reachable via a direct/test
|
|
4490
|
+
* invocation — every production scheduler carries one): the synthesized
|
|
4491
|
+
* incident can't be persisted (no key), so guard #1 can't arm.
|
|
4492
|
+
* • The record is swept AGAIN between two alarms (guard #1 re-persists on the
|
|
4493
|
+
* first, so this needs a second independent sweep) — vanishingly unlikely.
|
|
4494
|
+
*/
|
|
4495
|
+
async _exhaustRecoveryAfterStableTimeout(callback, data) {
|
|
4496
|
+
const config = this._resolveChatRecoveryConfig();
|
|
4497
|
+
const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
|
|
4498
|
+
const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
|
|
4499
|
+
if (stored?.status === "exhausted") return;
|
|
4500
|
+
const rootRequestId = data?.originalRequestId ?? data?.recoveredRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
|
|
4501
|
+
const incident = stored ? {
|
|
4502
|
+
...stored,
|
|
4503
|
+
status: "exhausted",
|
|
4504
|
+
reason: "stable_timeout"
|
|
4505
|
+
} : {
|
|
4506
|
+
incidentId: data?.incidentId ?? crypto.randomUUID(),
|
|
4507
|
+
requestId: rootRequestId,
|
|
4508
|
+
recoveryRootRequestId: rootRequestId,
|
|
4509
|
+
recoveryKind: callback === "_chatRecoveryRetry" ? "retry" : "continue",
|
|
4510
|
+
attempt: config.maxAttempts,
|
|
4511
|
+
maxAttempts: config.maxAttempts,
|
|
4512
|
+
status: "exhausted",
|
|
4513
|
+
firstSeenAt: Date.now(),
|
|
4514
|
+
lastAttemptAt: Date.now(),
|
|
4515
|
+
reason: "stable_timeout"
|
|
4516
|
+
};
|
|
4517
|
+
if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
|
|
4518
|
+
const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
|
|
4519
|
+
const partial = streamId ? this._getPartialStreamText(streamId) : {
|
|
4520
|
+
text: "",
|
|
4521
|
+
parts: []
|
|
4522
|
+
};
|
|
4523
|
+
await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
|
|
4524
|
+
}
|
|
4525
|
+
async _chatRecoveryRetry(data) {
|
|
4526
|
+
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
|
|
4527
|
+
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
4528
|
+
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
4529
|
+
return;
|
|
4530
|
+
}
|
|
4531
|
+
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
4532
|
+
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
4533
|
+
const controller = recoveredSubmission ? new AbortController() : null;
|
|
4534
|
+
if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
|
|
4535
|
+
try {
|
|
4536
|
+
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
4537
|
+
if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
|
|
4538
|
+
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
|
|
4539
|
+
await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
|
|
4540
|
+
return;
|
|
4541
|
+
}
|
|
4542
|
+
const lastLeaf = await this.session.getLatestLeaf();
|
|
4543
|
+
if (!lastLeaf || lastLeaf.role !== "user") {
|
|
4544
|
+
await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "no_unanswered_user_message");
|
|
4545
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
|
|
4546
|
+
return;
|
|
4547
|
+
}
|
|
4548
|
+
if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {
|
|
4549
|
+
await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
|
|
4550
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
|
|
4551
|
+
return;
|
|
4552
|
+
}
|
|
4553
|
+
this._applyRecoveredRequestContext(data);
|
|
4554
|
+
const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? { signal: controller.signal } : void 0);
|
|
4555
|
+
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
4556
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
|
|
4557
|
+
} catch (error) {
|
|
4558
|
+
await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
|
|
4559
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
|
|
4560
|
+
throw error;
|
|
4561
|
+
} finally {
|
|
4562
|
+
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
4563
|
+
if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
2558
4566
|
_hasRunningSubmission(requestId) {
|
|
2559
4567
|
return this._readRunningSubmissionByRequestId(requestId) !== null;
|
|
2560
4568
|
}
|
|
@@ -2623,30 +4631,54 @@ var Think = class Think extends Agent {
|
|
|
2623
4631
|
}
|
|
2624
4632
|
async _chatRecoveryContinue(data) {
|
|
2625
4633
|
const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
|
|
2626
|
-
if (data?.recoveredRequestId && !recoveredSubmission)
|
|
4634
|
+
if (data?.recoveredRequestId && !recoveredSubmission) {
|
|
4635
|
+
await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
|
|
4636
|
+
return;
|
|
4637
|
+
}
|
|
4638
|
+
const previousRootRequestId = this._activeChatRecoveryRootRequestId;
|
|
4639
|
+
this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
|
|
2627
4640
|
const controller = recoveredSubmission ? new AbortController() : null;
|
|
2628
4641
|
if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
|
|
2629
4642
|
try {
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
4643
|
+
const recoveryConfig = this._resolveChatRecoveryConfig();
|
|
4644
|
+
if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
|
|
4645
|
+
console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state");
|
|
4646
|
+
if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
|
|
4647
|
+
await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
|
|
2633
4648
|
return;
|
|
2634
4649
|
}
|
|
2635
4650
|
const targetId = data?.targetAssistantId;
|
|
2636
4651
|
const lastLeaf = await this.session.getLatestLeaf();
|
|
2637
4652
|
if (targetId && lastLeaf?.id !== targetId) {
|
|
2638
|
-
|
|
4653
|
+
const supersededByNewerUserTurn = lastLeaf?.role === "user";
|
|
4654
|
+
await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
|
|
4655
|
+
if (data?.recoveredRequestId && supersededByNewerUserTurn) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
|
|
2639
4656
|
return;
|
|
2640
4657
|
}
|
|
4658
|
+
this._applyRecoveredRequestContext(data);
|
|
2641
4659
|
const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
|
|
2642
|
-
|
|
4660
|
+
await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
|
|
4661
|
+
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
|
|
2643
4662
|
} catch (error) {
|
|
4663
|
+
await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
|
|
2644
4664
|
if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
|
|
2645
4665
|
throw error;
|
|
2646
4666
|
} finally {
|
|
4667
|
+
this._activeChatRecoveryRootRequestId = previousRootRequestId;
|
|
2647
4668
|
if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
|
|
2648
4669
|
}
|
|
2649
4670
|
}
|
|
4671
|
+
_applyRecoveredRequestContext(data) {
|
|
4672
|
+
if (!data) return;
|
|
4673
|
+
if ("lastClientTools" in data) {
|
|
4674
|
+
this._lastClientTools = data.lastClientTools ?? void 0;
|
|
4675
|
+
this._persistClientTools();
|
|
4676
|
+
}
|
|
4677
|
+
if ("lastBody" in data) {
|
|
4678
|
+
this._lastBody = data.lastBody ?? void 0;
|
|
4679
|
+
this._persistBody();
|
|
4680
|
+
}
|
|
4681
|
+
}
|
|
2650
4682
|
_getPartialStreamText(streamId) {
|
|
2651
4683
|
const chunks = this._resumableStream.getStreamChunks(streamId);
|
|
2652
4684
|
const parts = [];
|
|
@@ -2696,30 +4728,116 @@ var Think = class Think extends Agent {
|
|
|
2696
4728
|
this._continuation.pending.connectionId = connection.id;
|
|
2697
4729
|
this._continuation.pending.clientTools = this._lastClientTools;
|
|
2698
4730
|
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
4731
|
+
this._resetAutoContinuationTimer();
|
|
2699
4732
|
return;
|
|
2700
4733
|
}
|
|
4734
|
+
this._continuation.pending = {
|
|
4735
|
+
connection,
|
|
4736
|
+
connectionId: connection.id,
|
|
4737
|
+
requestId: crypto.randomUUID(),
|
|
4738
|
+
clientTools: this._lastClientTools,
|
|
4739
|
+
body: void 0,
|
|
4740
|
+
errorPrefix: "[Think] Auto-continuation failed:",
|
|
4741
|
+
prerequisite: null,
|
|
4742
|
+
pastCoalesce: false
|
|
4743
|
+
};
|
|
4744
|
+
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
4745
|
+
this._resetAutoContinuationTimer();
|
|
4746
|
+
}
|
|
4747
|
+
_resetAutoContinuationTimer() {
|
|
2701
4748
|
if (this._continuationTimer) clearTimeout(this._continuationTimer);
|
|
2702
4749
|
this._continuationTimer = setTimeout(() => {
|
|
2703
4750
|
this._continuationTimer = null;
|
|
2704
|
-
this.
|
|
4751
|
+
const pending = this._continuation.pending;
|
|
4752
|
+
if (!pending) return;
|
|
4753
|
+
this._fireAutoContinuationWhenStable(pending.connection);
|
|
2705
4754
|
}, 50);
|
|
2706
4755
|
}
|
|
4756
|
+
/**
|
|
4757
|
+
* Fire an auto-continuation, but only once the model's parallel tool-call
|
|
4758
|
+
* batch is fully answered (#1649). When the model emits several tool calls in
|
|
4759
|
+
* one step the client answers each independently, so the first `autoContinue`
|
|
4760
|
+
* arrives while slower siblings are still `input-available`. Continuing then
|
|
4761
|
+
* would feed the provider an incomplete tool-result set
|
|
4762
|
+
* (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
|
|
4763
|
+
* error the in-flight sibling and run a spurious extra continuation. We hold
|
|
4764
|
+
* the continuation on a barrier until the batch settles. The wait is bounded
|
|
4765
|
+
* (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
|
|
4766
|
+
* call — e.g. the client disconnected mid-batch — still falls through to the
|
|
4767
|
+
* repair backstop rather than pinning the continuation open forever.
|
|
4768
|
+
*/
|
|
4769
|
+
_fireAutoContinuationWhenStable(connection) {
|
|
4770
|
+
if (!this._continuation.pending) return;
|
|
4771
|
+
if (this._continuation.pending.pastCoalesce) return;
|
|
4772
|
+
if (this._continuationBarrierActive) return;
|
|
4773
|
+
if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {
|
|
4774
|
+
this._fireAutoContinuation(connection);
|
|
4775
|
+
return;
|
|
4776
|
+
}
|
|
4777
|
+
this._continuationBarrierActive = true;
|
|
4778
|
+
this.keepAliveWhile(() => this._awaitToolBatch()).catch(() => {}).finally(() => {
|
|
4779
|
+
this._continuationBarrierActive = false;
|
|
4780
|
+
const pending = this._continuation.pending;
|
|
4781
|
+
if (pending) this._fireAutoContinuation(pending.connection);
|
|
4782
|
+
});
|
|
4783
|
+
}
|
|
4784
|
+
/**
|
|
4785
|
+
* Block until the latest assistant step's parallel tool batch is fully
|
|
4786
|
+
* answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
|
|
4787
|
+
* in-flight tool-result apply when one exists (so a sibling that lands
|
|
4788
|
+
* mid-wait is observed promptly) and polls otherwise.
|
|
4789
|
+
*/
|
|
4790
|
+
async _awaitToolBatch() {
|
|
4791
|
+
const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
|
|
4792
|
+
while (Date.now() < deadline) {
|
|
4793
|
+
if (!this._continuation.pending) return;
|
|
4794
|
+
const pending = this._pendingInteractionPromise;
|
|
4795
|
+
if (pending) {
|
|
4796
|
+
try {
|
|
4797
|
+
await pending;
|
|
4798
|
+
} catch {}
|
|
4799
|
+
continue;
|
|
4800
|
+
}
|
|
4801
|
+
if (!this._hasIncompleteToolBatch()) return;
|
|
4802
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
4803
|
+
}
|
|
4804
|
+
console.warn(`[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
|
|
4805
|
+
}
|
|
4806
|
+
/**
|
|
4807
|
+
* `true` when the latest assistant message is mid-batch: it carries at least
|
|
4808
|
+
* one settled tool result AND at least one tool call/approval still awaiting a
|
|
4809
|
+
* client result. That is the #1649 signature — the model fanned out parallel
|
|
4810
|
+
* tool calls and only some have been answered. Scoped to the leaf (the step
|
|
4811
|
+
* the continuation answers) so an unrelated dangling tool in an earlier
|
|
4812
|
+
* message doesn't block a legitimate follow-up continuation.
|
|
4813
|
+
*/
|
|
4814
|
+
_hasIncompleteToolBatch() {
|
|
4815
|
+
const messages = this.messages;
|
|
4816
|
+
let leaf;
|
|
4817
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") {
|
|
4818
|
+
leaf = messages[i];
|
|
4819
|
+
break;
|
|
4820
|
+
}
|
|
4821
|
+
if (!leaf) return false;
|
|
4822
|
+
let hasPending = false;
|
|
4823
|
+
let hasSettled = false;
|
|
4824
|
+
for (const part of leaf.parts) {
|
|
4825
|
+
const record = part;
|
|
4826
|
+
const state = record.state;
|
|
4827
|
+
if (state === "input-available" || state === "approval-requested") hasPending = true;
|
|
4828
|
+
else if (typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && (state === "output-available" || state === "output-error" || state === "output-denied" || state === "approval-responded")) hasSettled = true;
|
|
4829
|
+
if (hasPending && hasSettled) return true;
|
|
4830
|
+
}
|
|
4831
|
+
return false;
|
|
4832
|
+
}
|
|
2707
4833
|
_fireAutoContinuation(connection) {
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
requestId,
|
|
2714
|
-
clientTools: this._lastClientTools,
|
|
2715
|
-
body: void 0,
|
|
2716
|
-
errorPrefix: "[Think] Auto-continuation failed:",
|
|
2717
|
-
prerequisite: null,
|
|
2718
|
-
pastCoalesce: false
|
|
2719
|
-
};
|
|
2720
|
-
this._continuation.awaitingConnections.set(connection.id, connection);
|
|
4834
|
+
const pending = this._continuation.pending;
|
|
4835
|
+
if (!pending) return;
|
|
4836
|
+
if (this._continuationTimer) {
|
|
4837
|
+
clearTimeout(this._continuationTimer);
|
|
4838
|
+
this._continuationTimer = null;
|
|
2721
4839
|
}
|
|
2722
|
-
const { requestId, clientTools } =
|
|
4840
|
+
const { requestId, clientTools } = pending;
|
|
2723
4841
|
const abortSignal = this._aborts.getSignal(requestId);
|
|
2724
4842
|
this.keepAliveWhile(async () => {
|
|
2725
4843
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
@@ -2743,9 +4861,7 @@ var Think = class Think extends Agent {
|
|
|
2743
4861
|
streamed = true;
|
|
2744
4862
|
}
|
|
2745
4863
|
};
|
|
2746
|
-
if (this.chatRecovery) await this.
|
|
2747
|
-
await continuationBody();
|
|
2748
|
-
});
|
|
4864
|
+
if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, continuationBody);
|
|
2749
4865
|
else await continuationBody();
|
|
2750
4866
|
} finally {
|
|
2751
4867
|
this._aborts.remove(requestId);
|
|
@@ -2762,9 +4878,10 @@ var Think = class Think extends Agent {
|
|
|
2762
4878
|
_activateDeferredContinuation() {
|
|
2763
4879
|
const pending = this._continuation.activateDeferred(() => crypto.randomUUID());
|
|
2764
4880
|
if (!pending) return;
|
|
2765
|
-
this.
|
|
4881
|
+
this._fireAutoContinuationWhenStable(pending.connection);
|
|
2766
4882
|
}
|
|
2767
4883
|
async _fireResponseHook(result) {
|
|
4884
|
+
await this._recordTerminalChatStatus(result.status, result.requestId, result.error ?? "The assistant was interrupted.");
|
|
2768
4885
|
if (this._insideResponseHook) return;
|
|
2769
4886
|
this._insideResponseHook = true;
|
|
2770
4887
|
try {
|
|
@@ -2775,6 +4892,79 @@ var Think = class Think extends Agent {
|
|
|
2775
4892
|
this._insideResponseHook = false;
|
|
2776
4893
|
}
|
|
2777
4894
|
}
|
|
4895
|
+
/**
|
|
4896
|
+
* Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
|
|
4897
|
+
* the last terminal turn so it can be replayed to clients on connect. A
|
|
4898
|
+
* `completed`/`aborted` turn is conveyed by the persisted messages, so the
|
|
4899
|
+
* record is cleared; an `error`/`interrupted` turn has no durable trace
|
|
4900
|
+
* otherwise, so it is kept until a later turn resolves.
|
|
4901
|
+
*/
|
|
4902
|
+
async _recordTerminalChatStatus(status, requestId, body) {
|
|
4903
|
+
if (status === "error" || status === "interrupted") await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
|
|
4904
|
+
requestId,
|
|
4905
|
+
body
|
|
4906
|
+
});
|
|
4907
|
+
else await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
|
|
4908
|
+
await this._setChatRecovering(false);
|
|
4909
|
+
}
|
|
4910
|
+
async _pendingTerminalChatResponse() {
|
|
4911
|
+
return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
|
|
4912
|
+
}
|
|
4913
|
+
/**
|
|
4914
|
+
* Set or clear the live "recovering…" status for a durable chat turn (#1620).
|
|
4915
|
+
* Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
|
|
4916
|
+
* and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
|
|
4917
|
+
* transition, so a deploy/reconnect storm (which re-detects recovery many
|
|
4918
|
+
* times) doesn't spam the wire. Cleared on every terminal outcome so the
|
|
4919
|
+
* indicator can't spin forever.
|
|
4920
|
+
*/
|
|
4921
|
+
async _setChatRecovering(active, requestId) {
|
|
4922
|
+
const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
|
|
4923
|
+
const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
|
|
4924
|
+
if (active) {
|
|
4925
|
+
if (activeExisting) return;
|
|
4926
|
+
await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
|
|
4927
|
+
...requestId ? { requestId } : {},
|
|
4928
|
+
at: Date.now()
|
|
4929
|
+
});
|
|
4930
|
+
} else {
|
|
4931
|
+
if (!existing) return;
|
|
4932
|
+
await this.ctx.storage.delete(CHAT_RECOVERING_KEY);
|
|
4933
|
+
requestId = requestId ?? existing.requestId;
|
|
4934
|
+
}
|
|
4935
|
+
this._broadcastChat({
|
|
4936
|
+
type: MSG_CHAT_RECOVERING,
|
|
4937
|
+
recovering: active,
|
|
4938
|
+
...requestId ? { id: requestId } : {}
|
|
4939
|
+
});
|
|
4940
|
+
}
|
|
4941
|
+
/**
|
|
4942
|
+
* Messages sent to a client on connect when no stream is active: the current
|
|
4943
|
+
* transcript, plus a replay of the last terminal error (if any) so a turn
|
|
4944
|
+
* that failed while the client was disconnected is surfaced rather than
|
|
4945
|
+
* silently frozen.
|
|
4946
|
+
*/
|
|
4947
|
+
async _buildIdleConnectMessages() {
|
|
4948
|
+
const messages = [{
|
|
4949
|
+
type: MSG_CHAT_MESSAGES,
|
|
4950
|
+
messages: this.messages
|
|
4951
|
+
}];
|
|
4952
|
+
const pending = await this._pendingTerminalChatResponse();
|
|
4953
|
+
if (pending) messages.push({
|
|
4954
|
+
type: MSG_CHAT_RESPONSE,
|
|
4955
|
+
id: pending.requestId,
|
|
4956
|
+
body: pending.body,
|
|
4957
|
+
done: true,
|
|
4958
|
+
error: true
|
|
4959
|
+
});
|
|
4960
|
+
const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
|
|
4961
|
+
if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS) messages.push({
|
|
4962
|
+
type: MSG_CHAT_RECOVERING,
|
|
4963
|
+
recovering: true,
|
|
4964
|
+
...recovering.requestId ? { id: recovering.requestId } : {}
|
|
4965
|
+
});
|
|
4966
|
+
return messages;
|
|
4967
|
+
}
|
|
2778
4968
|
_notifyStreamResuming(connection) {
|
|
2779
4969
|
if (!this._resumableStream.hasActiveStream()) return;
|
|
2780
4970
|
if (sendIfOpen(connection, JSON.stringify({
|
|
@@ -2812,12 +5002,13 @@ var Think = class Think extends Agent {
|
|
|
2812
5002
|
Think.CONFIG_KEYS = [
|
|
2813
5003
|
"_think_config",
|
|
2814
5004
|
"lastClientTools",
|
|
2815
|
-
"lastBody"
|
|
5005
|
+
"lastBody",
|
|
5006
|
+
"skillsFingerprint"
|
|
2816
5007
|
];
|
|
2817
5008
|
Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
2818
5009
|
Think.MESSAGE_DEBOUNCE_MS = 750;
|
|
2819
5010
|
Think.submissionRecoveryStaleMs = 900 * 1e3;
|
|
2820
5011
|
//#endregion
|
|
2821
|
-
export { Session, Think, Workspace };
|
|
5012
|
+
export { Session, Think, Workspace, defineScheduledTasks, skills };
|
|
2822
5013
|
|
|
2823
5014
|
//# sourceMappingURL=think.js.map
|