@cloudflare/think 0.4.0 → 0.4.2
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 +25 -5
- package/dist/{classPrivateFieldGet2-C7fYS0JL.js → classPrivateFieldGet2-Bvcn7kEw.js} +5 -5
- package/dist/extensions/index.js +2 -2
- package/dist/{manager-CR9ZdLiu.js → manager-DDC3Gb0V.js} +3 -3
- package/dist/{manager-CR9ZdLiu.js.map → manager-DDC3Gb0V.js.map} +1 -1
- package/dist/think.d.ts +170 -19
- package/dist/think.js +214 -113
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/dist/tools/workspace.d.ts +11 -2
- package/dist/tools/workspace.js +5 -1
- package/dist/tools/workspace.js.map +1 -1
- package/package.json +5 -5
package/dist/think.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createWorkspaceTools } from "./tools/workspace.js";
|
|
2
|
-
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-
|
|
2
|
+
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-Bvcn7kEw.js";
|
|
3
3
|
import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
|
|
4
4
|
import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
|
|
5
|
-
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
|
|
5
|
+
import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
|
|
6
6
|
import { Session, Session as Session$1 } from "agents/experimental/memory/session";
|
|
7
7
|
import { truncateOlderMessages } from "agents/experimental/memory/utils";
|
|
8
8
|
import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
|
|
@@ -35,10 +35,7 @@ var Think = class Think extends Agent {
|
|
|
35
35
|
this._insideResponseHook = false;
|
|
36
36
|
this._insideInferenceLoop = false;
|
|
37
37
|
this._pendingInteractionPromise = null;
|
|
38
|
-
this.
|
|
39
|
-
this._latestOverlappingSubmitSequence = 0;
|
|
40
|
-
this._activeDebounceTimer = null;
|
|
41
|
-
this._activeDebounceResolve = null;
|
|
38
|
+
this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS });
|
|
42
39
|
_classPrivateFieldInitSpec(this, _configCache, null);
|
|
43
40
|
_classPrivateFieldInitSpec(this, _configTableReady, false);
|
|
44
41
|
this.maxSteps = 10;
|
|
@@ -69,7 +66,8 @@ var Think = class Think extends Agent {
|
|
|
69
66
|
}
|
|
70
67
|
/**
|
|
71
68
|
* Persist an arbitrary JSON-serializable configuration object for this
|
|
72
|
-
* agent instance. Stored in the
|
|
69
|
+
* agent instance. Stored in the Think-private `think_config` table —
|
|
70
|
+
* survives
|
|
73
71
|
* restarts and hibernation. Pass the config shape as a method generic
|
|
74
72
|
* for typed call sites:
|
|
75
73
|
*
|
|
@@ -103,45 +101,54 @@ var Think = class Think extends Agent {
|
|
|
103
101
|
}
|
|
104
102
|
return null;
|
|
105
103
|
}
|
|
104
|
+
_migrateLegacyConfigToThinkTable() {
|
|
105
|
+
const rows = this.ctx.storage.sql.exec("SELECT sql FROM sqlite_master WHERE type='table' AND name='assistant_config'").toArray();
|
|
106
|
+
if (rows.length === 0) return;
|
|
107
|
+
if (!String(rows[0].sql ?? "").includes("session_id")) return;
|
|
108
|
+
for (const key of Think.CONFIG_KEYS) {
|
|
109
|
+
const value = this.sql`
|
|
110
|
+
SELECT value FROM assistant_config
|
|
111
|
+
WHERE session_id = '' AND key = ${key}
|
|
112
|
+
`[0]?.value;
|
|
113
|
+
if (value !== void 0) this.sql`
|
|
114
|
+
INSERT OR IGNORE INTO think_config (key, value)
|
|
115
|
+
VALUES (${key}, ${value})
|
|
116
|
+
`;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
106
119
|
_ensureConfigTable() {
|
|
107
120
|
if (_classPrivateFieldGet2(_configTableReady, this)) return;
|
|
108
121
|
this.sql`
|
|
109
|
-
CREATE TABLE IF NOT EXISTS
|
|
110
|
-
session_id TEXT NOT NULL,
|
|
122
|
+
CREATE TABLE IF NOT EXISTS think_config (
|
|
111
123
|
key TEXT NOT NULL,
|
|
112
124
|
value TEXT NOT NULL,
|
|
113
|
-
PRIMARY KEY (
|
|
125
|
+
PRIMARY KEY (key)
|
|
114
126
|
)
|
|
115
127
|
`;
|
|
128
|
+
this._migrateLegacyConfigToThinkTable();
|
|
116
129
|
_classPrivateFieldSet2(_configTableReady, this, true);
|
|
117
130
|
}
|
|
118
131
|
_configSet(key, value) {
|
|
119
132
|
this._ensureConfigTable();
|
|
120
|
-
const sessionId = this._sessionId();
|
|
121
133
|
this.sql`
|
|
122
|
-
INSERT OR REPLACE INTO
|
|
123
|
-
VALUES (${
|
|
134
|
+
INSERT OR REPLACE INTO think_config (key, value)
|
|
135
|
+
VALUES (${key}, ${value})
|
|
124
136
|
`;
|
|
125
137
|
}
|
|
126
138
|
_configGet(key) {
|
|
127
139
|
this._ensureConfigTable();
|
|
128
|
-
const sessionId = this._sessionId();
|
|
129
140
|
return this.sql`
|
|
130
|
-
SELECT value FROM
|
|
131
|
-
WHERE
|
|
141
|
+
SELECT value FROM think_config
|
|
142
|
+
WHERE key = ${key}
|
|
132
143
|
`[0]?.value;
|
|
133
144
|
}
|
|
134
145
|
_configDelete(key) {
|
|
135
146
|
this._ensureConfigTable();
|
|
136
|
-
const sessionId = this._sessionId();
|
|
137
147
|
this.sql`
|
|
138
|
-
DELETE FROM
|
|
139
|
-
WHERE
|
|
148
|
+
DELETE FROM think_config
|
|
149
|
+
WHERE key = ${key}
|
|
140
150
|
`;
|
|
141
151
|
}
|
|
142
|
-
_sessionId() {
|
|
143
|
-
return "";
|
|
144
|
-
}
|
|
145
152
|
/**
|
|
146
153
|
* Return the language model to use for inference.
|
|
147
154
|
* Must be overridden by subclasses.
|
|
@@ -207,6 +214,40 @@ var Think = class Think extends Agent {
|
|
|
207
214
|
*/
|
|
208
215
|
beforeTurn(_ctx) {}
|
|
209
216
|
/**
|
|
217
|
+
* Called before each AI SDK step in the agentic loop. Backed by
|
|
218
|
+
* `streamText({ prepareStep })`.
|
|
219
|
+
*
|
|
220
|
+
* Return `void` to accept the current step defaults, or return a
|
|
221
|
+
* `StepConfig` to override the model, tool choice, active tools,
|
|
222
|
+
* system prompt, messages, experimental context, or provider options
|
|
223
|
+
* for this step. Use `beforeTurn` for turn-wide assembly and
|
|
224
|
+
* `beforeStep` when the decision depends on the step number or
|
|
225
|
+
* previous step results.
|
|
226
|
+
*
|
|
227
|
+
* @example Force search on the first step
|
|
228
|
+
* ```typescript
|
|
229
|
+
* beforeStep(ctx: PrepareStepContext) {
|
|
230
|
+
* if (ctx.stepNumber === 0) {
|
|
231
|
+
* return {
|
|
232
|
+
* activeTools: ["search"],
|
|
233
|
+
* toolChoice: { type: "tool", toolName: "search" }
|
|
234
|
+
* };
|
|
235
|
+
* }
|
|
236
|
+
* }
|
|
237
|
+
* ```
|
|
238
|
+
*
|
|
239
|
+
* @example Switch to a cheaper model after tool results land
|
|
240
|
+
* ```typescript
|
|
241
|
+
* beforeStep(ctx: PrepareStepContext) {
|
|
242
|
+
* // assumes a `fastSummaryModel` field on your Think subclass
|
|
243
|
+
* if (ctx.steps.some((s) => s.toolResults.length > 0)) {
|
|
244
|
+
* return { model: this.fastSummaryModel };
|
|
245
|
+
* }
|
|
246
|
+
* }
|
|
247
|
+
* ```
|
|
248
|
+
*/
|
|
249
|
+
beforeStep(_ctx) {}
|
|
250
|
+
/**
|
|
210
251
|
* Called **before** the tool's `execute` function runs. Think wraps
|
|
211
252
|
* every tool's `execute` so it can consult this hook and act on the
|
|
212
253
|
* returned `ToolCallDecision`:
|
|
@@ -308,8 +349,8 @@ var Think = class Think extends Agent {
|
|
|
308
349
|
return error;
|
|
309
350
|
}
|
|
310
351
|
async _initializeExtensions() {
|
|
311
|
-
const { ExtensionManager } = await import("./manager-
|
|
312
|
-
const { sanitizeName } = await import("./manager-
|
|
352
|
+
const { ExtensionManager } = await import("./manager-DDC3Gb0V.js").then((n) => n.n);
|
|
353
|
+
const { sanitizeName } = await import("./manager-DDC3Gb0V.js").then((n) => n.n);
|
|
313
354
|
const agentClassName = this.constructor.name;
|
|
314
355
|
const agentId = this.ctx.id.toString();
|
|
315
356
|
const ctxExports = this.ctx.exports;
|
|
@@ -403,7 +444,12 @@ var Think = class Think extends Agent {
|
|
|
403
444
|
toolChoice: config.toolChoice,
|
|
404
445
|
stopWhen: stepCountIs(finalMaxSteps),
|
|
405
446
|
providerOptions: config.providerOptions,
|
|
447
|
+
output: config.output,
|
|
406
448
|
abortSignal: input.signal,
|
|
449
|
+
prepareStep: (async (event) => {
|
|
450
|
+
const result = await this.beforeStep(event);
|
|
451
|
+
return result == null ? {} : result;
|
|
452
|
+
}),
|
|
407
453
|
onChunk: async (event) => {
|
|
408
454
|
await this.onChunk(event);
|
|
409
455
|
await this._pipelineExtensionChunk(event);
|
|
@@ -774,6 +820,13 @@ var Think = class Think extends Agent {
|
|
|
774
820
|
* current state (useful when multiple calls queue up — the callback runs
|
|
775
821
|
* with the latest messages when the turn actually starts).
|
|
776
822
|
*
|
|
823
|
+
* Pass `options.signal` to cancel the turn from outside without knowing
|
|
824
|
+
* the internally-generated request id. The signal is linked to the
|
|
825
|
+
* registry's controller for this turn — when it aborts, the inference
|
|
826
|
+
* loop's signal aborts and the result reports `status: "aborted"`.
|
|
827
|
+
* Pre-aborted signals short-circuit before any model work runs. See
|
|
828
|
+
* {@link SaveMessagesOptions} for the integration point.
|
|
829
|
+
*
|
|
777
830
|
* @example Scheduled follow-up
|
|
778
831
|
* ```typescript
|
|
779
832
|
* async onScheduled() {
|
|
@@ -792,13 +845,21 @@ var Think = class Think extends Agent {
|
|
|
792
845
|
* { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
|
|
793
846
|
* ]);
|
|
794
847
|
* ```
|
|
848
|
+
*
|
|
849
|
+
* @example External cancellation (helper-as-sub-agent)
|
|
850
|
+
* ```typescript
|
|
851
|
+
* // Inside a parent agent's tool execute — forward the AI SDK's
|
|
852
|
+
* // abortSignal so a parent stop / tab close cancels the helper.
|
|
853
|
+
* await helper.saveMessages([userMsg], { signal: abortSignal });
|
|
854
|
+
* ```
|
|
795
855
|
*/
|
|
796
|
-
async saveMessages(messages) {
|
|
856
|
+
async saveMessages(messages, options) {
|
|
797
857
|
const requestId = crypto.randomUUID();
|
|
798
858
|
const clientTools = this._lastClientTools;
|
|
799
859
|
const body = this._lastBody;
|
|
800
860
|
const epoch = this._turnQueue.generation;
|
|
801
861
|
let status = "completed";
|
|
862
|
+
let wasAborted = false;
|
|
802
863
|
await this.keepAliveWhile(async () => {
|
|
803
864
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
804
865
|
const resolved = typeof messages === "function" ? await messages(this.messages) : messages;
|
|
@@ -813,6 +874,7 @@ var Think = class Think extends Agent {
|
|
|
813
874
|
return;
|
|
814
875
|
}
|
|
815
876
|
const abortSignal = this._aborts.getSignal(requestId);
|
|
877
|
+
const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
|
|
816
878
|
try {
|
|
817
879
|
const programmaticBody = async () => {
|
|
818
880
|
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
@@ -833,11 +895,14 @@ var Think = class Think extends Agent {
|
|
|
833
895
|
});
|
|
834
896
|
else await programmaticBody();
|
|
835
897
|
} finally {
|
|
898
|
+
if (abortSignal?.aborted) wasAborted = true;
|
|
899
|
+
detachExternal();
|
|
836
900
|
this._aborts.remove(requestId);
|
|
837
901
|
}
|
|
838
902
|
});
|
|
839
903
|
});
|
|
840
904
|
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
905
|
+
else if (wasAborted && status === "completed") status = "aborted";
|
|
841
906
|
return {
|
|
842
907
|
requestId,
|
|
843
908
|
status
|
|
@@ -856,8 +921,11 @@ var Think = class Think extends Agent {
|
|
|
856
921
|
*
|
|
857
922
|
* Returns early with `status: "skipped"` if there is no assistant message
|
|
858
923
|
* to continue from.
|
|
924
|
+
*
|
|
925
|
+
* Pass `options.signal` to cancel the continuation from outside —
|
|
926
|
+
* matches the {@link saveMessages} contract.
|
|
859
927
|
*/
|
|
860
|
-
async continueLastTurn(body) {
|
|
928
|
+
async continueLastTurn(body, options) {
|
|
861
929
|
const lastLeaf = this.session.getLatestLeaf();
|
|
862
930
|
if (!lastLeaf || lastLeaf.role !== "assistant") return {
|
|
863
931
|
requestId: "",
|
|
@@ -868,6 +936,7 @@ var Think = class Think extends Agent {
|
|
|
868
936
|
const resolvedBody = body ?? this._lastBody;
|
|
869
937
|
const epoch = this._turnQueue.generation;
|
|
870
938
|
let status = "completed";
|
|
939
|
+
let wasAborted = false;
|
|
871
940
|
await this.keepAliveWhile(async () => {
|
|
872
941
|
await this._turnQueue.enqueue(requestId, async () => {
|
|
873
942
|
if (this._turnQueue.generation !== epoch) {
|
|
@@ -875,6 +944,7 @@ var Think = class Think extends Agent {
|
|
|
875
944
|
return;
|
|
876
945
|
}
|
|
877
946
|
const abortSignal = this._aborts.getSignal(requestId);
|
|
947
|
+
const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
|
|
878
948
|
try {
|
|
879
949
|
const continueTurnBody = async () => {
|
|
880
950
|
const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
|
|
@@ -895,11 +965,14 @@ var Think = class Think extends Agent {
|
|
|
895
965
|
});
|
|
896
966
|
else await continueTurnBody();
|
|
897
967
|
} finally {
|
|
968
|
+
if (abortSignal?.aborted) wasAborted = true;
|
|
969
|
+
detachExternal();
|
|
898
970
|
this._aborts.remove(requestId);
|
|
899
971
|
}
|
|
900
972
|
});
|
|
901
973
|
});
|
|
902
974
|
if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
|
|
975
|
+
else if (wasAborted && status === "completed") status = "aborted";
|
|
903
976
|
return {
|
|
904
977
|
requestId,
|
|
905
978
|
status
|
|
@@ -909,7 +982,7 @@ var Think = class Think extends Agent {
|
|
|
909
982
|
const _onConnect = this.onConnect.bind(this);
|
|
910
983
|
this.onConnect = async (connection, ctx) => {
|
|
911
984
|
if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
|
|
912
|
-
connection.send(JSON.stringify({
|
|
985
|
+
else connection.send(JSON.stringify({
|
|
913
986
|
type: MSG_CHAT_MESSAGES,
|
|
914
987
|
messages: this.messages
|
|
915
988
|
}));
|
|
@@ -1021,39 +1094,62 @@ var Think = class Think extends Agent {
|
|
|
1021
1094
|
this._completeSkippedRequest(connection, requestId);
|
|
1022
1095
|
return;
|
|
1023
1096
|
}
|
|
1024
|
-
const
|
|
1025
|
-
|
|
1026
|
-
this._lastClientTools = requestClientTools;
|
|
1027
|
-
this._persistClientTools();
|
|
1028
|
-
} else if (rawClientTools !== void 0) {
|
|
1029
|
-
this._lastClientTools = void 0;
|
|
1030
|
-
this._persistClientTools();
|
|
1031
|
-
}
|
|
1032
|
-
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
1033
|
-
this._lastBody = requestBody;
|
|
1034
|
-
this._persistBody();
|
|
1035
|
-
const clientToolsForTurn = this._lastClientTools;
|
|
1036
|
-
const bodyForTurn = this._lastBody;
|
|
1037
|
-
let branchParentId;
|
|
1038
|
-
if (isRegeneration && incomingMessages.length > 0) branchParentId = incomingMessages[incomingMessages.length - 1].id;
|
|
1039
|
-
for (const msg of incomingMessages) await this.session.appendMessage(msg);
|
|
1040
|
-
this._broadcastMessages([connection.id]);
|
|
1041
|
-
const abortSignal = this._aborts.getSignal(requestId);
|
|
1097
|
+
const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
|
|
1098
|
+
let pendingEnqueue = true;
|
|
1042
1099
|
const epoch = this._turnQueue.generation;
|
|
1100
|
+
const releaseIfPending = () => {
|
|
1101
|
+
if (!pendingEnqueue) return;
|
|
1102
|
+
pendingEnqueue = false;
|
|
1103
|
+
releasePendingEnqueue();
|
|
1104
|
+
};
|
|
1043
1105
|
try {
|
|
1106
|
+
const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
|
|
1107
|
+
if (requestClientTools) {
|
|
1108
|
+
this._lastClientTools = requestClientTools;
|
|
1109
|
+
this._persistClientTools();
|
|
1110
|
+
} else if (rawClientTools !== void 0) {
|
|
1111
|
+
this._lastClientTools = void 0;
|
|
1112
|
+
this._persistClientTools();
|
|
1113
|
+
}
|
|
1114
|
+
const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
|
|
1115
|
+
this._lastBody = requestBody;
|
|
1116
|
+
this._persistBody();
|
|
1117
|
+
const clientToolsForTurn = this._lastClientTools;
|
|
1118
|
+
const bodyForTurn = this._lastBody;
|
|
1119
|
+
const serverMessages = this.session.getHistory();
|
|
1120
|
+
const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
|
|
1121
|
+
let branchParentId;
|
|
1122
|
+
if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
|
|
1123
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1124
|
+
this._completeSkippedRequest(connection, requestId);
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
for (const msg of reconciled) {
|
|
1128
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1129
|
+
this._completeSkippedRequest(connection, requestId);
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
await this._persistIncomingMessage(msg, serverMessages);
|
|
1133
|
+
}
|
|
1134
|
+
if (this._turnQueue.generation !== epoch) {
|
|
1135
|
+
this._completeSkippedRequest(connection, requestId);
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
this._broadcastMessages([connection.id]);
|
|
1139
|
+
const abortSignal = this._aborts.getSignal(requestId);
|
|
1044
1140
|
await this.keepAliveWhile(async () => {
|
|
1045
|
-
|
|
1046
|
-
if (this.
|
|
1141
|
+
const turnPromise = this._turnQueue.enqueue(requestId, async () => {
|
|
1142
|
+
if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
|
|
1047
1143
|
this._completeSkippedRequest(connection, requestId);
|
|
1048
1144
|
return;
|
|
1049
1145
|
}
|
|
1050
1146
|
if (concurrencyDecision.debounceUntilMs !== null) {
|
|
1051
|
-
await this.
|
|
1147
|
+
await this._submitConcurrency.waitForTimestamp(concurrencyDecision.debounceUntilMs);
|
|
1052
1148
|
if (this._turnQueue.generation !== epoch) {
|
|
1053
1149
|
this._completeSkippedRequest(connection, requestId);
|
|
1054
1150
|
return;
|
|
1055
1151
|
}
|
|
1056
|
-
if (this.
|
|
1152
|
+
if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
|
|
1057
1153
|
this._completeSkippedRequest(connection, requestId);
|
|
1058
1154
|
return;
|
|
1059
1155
|
}
|
|
@@ -1082,7 +1178,9 @@ var Think = class Think extends Agent {
|
|
|
1082
1178
|
await chatTurnBody();
|
|
1083
1179
|
});
|
|
1084
1180
|
else await chatTurnBody();
|
|
1085
|
-
}
|
|
1181
|
+
}, { generation: epoch });
|
|
1182
|
+
releaseIfPending();
|
|
1183
|
+
if ((await turnPromise).status === "stale") this._broadcastChat({
|
|
1086
1184
|
type: MSG_CHAT_RESPONSE,
|
|
1087
1185
|
id: requestId,
|
|
1088
1186
|
body: "",
|
|
@@ -1098,6 +1196,7 @@ var Think = class Think extends Agent {
|
|
|
1098
1196
|
error: true
|
|
1099
1197
|
});
|
|
1100
1198
|
} finally {
|
|
1199
|
+
releaseIfPending();
|
|
1101
1200
|
this._aborts.remove(requestId);
|
|
1102
1201
|
}
|
|
1103
1202
|
}
|
|
@@ -1116,11 +1215,51 @@ var Think = class Think extends Agent {
|
|
|
1116
1215
|
clearTimeout(this._continuationTimer);
|
|
1117
1216
|
this._continuationTimer = null;
|
|
1118
1217
|
}
|
|
1119
|
-
this.
|
|
1218
|
+
this._submitConcurrency.reset();
|
|
1120
1219
|
this._pendingInteractionPromise = null;
|
|
1121
1220
|
this._continuation.sendResumeNone();
|
|
1122
1221
|
this._continuation.clearAll();
|
|
1123
1222
|
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Abort a single in-flight chat turn by request id.
|
|
1225
|
+
*
|
|
1226
|
+
* Equivalent to the cancel path that fires when a client sends a
|
|
1227
|
+
* `chat-request-cancel` WebSocket message — the inference loop's
|
|
1228
|
+
* signal aborts, partial chunks already streamed are still
|
|
1229
|
+
* persisted, and the turn's `ChatResponseResult` reports
|
|
1230
|
+
* `status: "aborted"`.
|
|
1231
|
+
*
|
|
1232
|
+
* No-op if no controller exists for `requestId` (the turn already
|
|
1233
|
+
* completed, was never started, or used a different id).
|
|
1234
|
+
*
|
|
1235
|
+
* Most callers don't have the request id and want
|
|
1236
|
+
* {@link abortAllRequests} instead. This method is here for
|
|
1237
|
+
* symmetry with the WebSocket cancel surface and for callers that
|
|
1238
|
+
* happen to know the id (e.g. via a stash from an earlier
|
|
1239
|
+
* `saveMessages` return).
|
|
1240
|
+
*
|
|
1241
|
+
* Prefer {@link SaveMessagesOptions.signal} when driving a turn
|
|
1242
|
+
* programmatically — it threads the abort intent in from the start
|
|
1243
|
+
* without requiring the caller to know the id.
|
|
1244
|
+
*/
|
|
1245
|
+
abortRequest(requestId, reason) {
|
|
1246
|
+
this._aborts.cancel(requestId, reason);
|
|
1247
|
+
}
|
|
1248
|
+
/**
|
|
1249
|
+
* Abort every in-flight chat turn on this agent.
|
|
1250
|
+
*
|
|
1251
|
+
* Aborts all controllers in the registry and clears it. Used by
|
|
1252
|
+
* subclasses that drive single-purpose turns (e.g. a sub-agent
|
|
1253
|
+
* helper that runs one turn at a time over RPC) and want a coarse
|
|
1254
|
+
* "cancel whatever is running" handle without tracking request ids.
|
|
1255
|
+
*
|
|
1256
|
+
* Does NOT reset queued turns, continuation timers, or submit
|
|
1257
|
+
* concurrency state — use {@link resetTurnState} for the full
|
|
1258
|
+
* teardown that runs on `chat-clear`.
|
|
1259
|
+
*/
|
|
1260
|
+
abortAllRequests() {
|
|
1261
|
+
this._aborts.destroyAll();
|
|
1262
|
+
}
|
|
1124
1263
|
_handleClear(connection) {
|
|
1125
1264
|
this.resetTurnState();
|
|
1126
1265
|
this._resumableStream.clearAll();
|
|
@@ -1231,6 +1370,20 @@ var Think = class Think extends Agent {
|
|
|
1231
1370
|
if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
|
|
1232
1371
|
else this.session.appendMessage(safe, parentId);
|
|
1233
1372
|
}
|
|
1373
|
+
/**
|
|
1374
|
+
* Persist an incoming message after reconciliation. For assistant
|
|
1375
|
+
* messages, also resolve their ID against any server-side row that
|
|
1376
|
+
* already owns the same `toolCallId` so we update the existing row
|
|
1377
|
+
* instead of inserting an orphan duplicate.
|
|
1378
|
+
*/
|
|
1379
|
+
async _persistIncomingMessage(msg, serverMessages) {
|
|
1380
|
+
const safe = enforceRowSizeLimit(sanitizeMessage(msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg));
|
|
1381
|
+
if (this.session.getMessage(safe.id)) {
|
|
1382
|
+
this.session.updateMessage(safe);
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
await this.session.appendMessage(safe);
|
|
1386
|
+
}
|
|
1234
1387
|
_persistClientTools() {
|
|
1235
1388
|
if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
|
|
1236
1389
|
else this._configDelete("lastClientTools");
|
|
@@ -1287,7 +1440,7 @@ var Think = class Think extends Agent {
|
|
|
1287
1440
|
async waitUntilStable(options) {
|
|
1288
1441
|
const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
|
|
1289
1442
|
while (true) {
|
|
1290
|
-
if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
|
|
1443
|
+
if (await this._awaitWithDeadline(this._submitConcurrency.waitForIdle(() => this._turnQueue.waitForIdle()), deadline) === TIMED_OUT) return false;
|
|
1291
1444
|
if (!this.hasPendingInteraction()) return true;
|
|
1292
1445
|
const pending = this._pendingInteractionPromise;
|
|
1293
1446
|
if (pending) {
|
|
@@ -1377,70 +1530,13 @@ var Think = class Think extends Agent {
|
|
|
1377
1530
|
parts
|
|
1378
1531
|
};
|
|
1379
1532
|
}
|
|
1380
|
-
_normalizeMessageConcurrency() {
|
|
1381
|
-
if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
|
|
1382
|
-
const debounceMs = this.messageConcurrency.debounceMs;
|
|
1383
|
-
return {
|
|
1384
|
-
strategy: "debounce",
|
|
1385
|
-
debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : Think.MESSAGE_DEBOUNCE_MS
|
|
1386
|
-
};
|
|
1387
|
-
}
|
|
1388
1533
|
_getSubmitConcurrencyDecision(isSubmitMessage) {
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
debounceUntilMs: null
|
|
1394
|
-
};
|
|
1395
|
-
const concurrency = this._normalizeMessageConcurrency();
|
|
1396
|
-
if (concurrency === "queue") return {
|
|
1397
|
-
action: "execute",
|
|
1398
|
-
submitSequence: null,
|
|
1399
|
-
debounceUntilMs: null
|
|
1400
|
-
};
|
|
1401
|
-
if (concurrency === "drop") return {
|
|
1402
|
-
action: "drop",
|
|
1403
|
-
submitSequence: null,
|
|
1404
|
-
debounceUntilMs: null
|
|
1405
|
-
};
|
|
1406
|
-
const submitSequence = ++this._submitSequence;
|
|
1407
|
-
this._latestOverlappingSubmitSequence = submitSequence;
|
|
1408
|
-
if (concurrency === "latest" || concurrency === "merge") return {
|
|
1409
|
-
action: "execute",
|
|
1410
|
-
submitSequence,
|
|
1411
|
-
debounceUntilMs: null
|
|
1412
|
-
};
|
|
1413
|
-
return {
|
|
1414
|
-
action: "execute",
|
|
1415
|
-
submitSequence,
|
|
1416
|
-
debounceUntilMs: Date.now() + concurrency.debounceMs
|
|
1417
|
-
};
|
|
1418
|
-
}
|
|
1419
|
-
_isSupersededSubmit(submitSequence) {
|
|
1420
|
-
return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
|
|
1421
|
-
}
|
|
1422
|
-
async _waitForTimestamp(timestampMs) {
|
|
1423
|
-
const remainingMs = timestampMs - Date.now();
|
|
1424
|
-
if (remainingMs <= 0) return;
|
|
1425
|
-
await new Promise((resolve) => {
|
|
1426
|
-
this._activeDebounceResolve = resolve;
|
|
1427
|
-
this._activeDebounceTimer = setTimeout(() => {
|
|
1428
|
-
this._activeDebounceTimer = null;
|
|
1429
|
-
this._activeDebounceResolve = null;
|
|
1430
|
-
resolve();
|
|
1431
|
-
}, remainingMs);
|
|
1534
|
+
return this._submitConcurrency.decide({
|
|
1535
|
+
concurrency: this.messageConcurrency,
|
|
1536
|
+
isSubmitMessage,
|
|
1537
|
+
queuedTurns: this._turnQueue.queuedCount()
|
|
1432
1538
|
});
|
|
1433
1539
|
}
|
|
1434
|
-
_cancelActiveDebounce() {
|
|
1435
|
-
if (this._activeDebounceTimer !== null) {
|
|
1436
|
-
clearTimeout(this._activeDebounceTimer);
|
|
1437
|
-
this._activeDebounceTimer = null;
|
|
1438
|
-
}
|
|
1439
|
-
if (this._activeDebounceResolve !== null) {
|
|
1440
|
-
this._activeDebounceResolve();
|
|
1441
|
-
this._activeDebounceResolve = null;
|
|
1442
|
-
}
|
|
1443
|
-
}
|
|
1444
1540
|
_completeSkippedRequest(connection, requestId) {
|
|
1445
1541
|
connection.send(JSON.stringify({
|
|
1446
1542
|
type: MSG_CHAT_RESPONSE,
|
|
@@ -1586,6 +1682,11 @@ var Think = class Think extends Agent {
|
|
|
1586
1682
|
}, exclude);
|
|
1587
1683
|
}
|
|
1588
1684
|
};
|
|
1685
|
+
Think.CONFIG_KEYS = [
|
|
1686
|
+
"_think_config",
|
|
1687
|
+
"lastClientTools",
|
|
1688
|
+
"lastBody"
|
|
1689
|
+
];
|
|
1589
1690
|
Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
|
|
1590
1691
|
Think.MESSAGE_DEBOUNCE_MS = 750;
|
|
1591
1692
|
//#endregion
|