@cloudflare/think 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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-C7fYS0JL.js";
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._submitSequence = 0;
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 assistant_config table — survives
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 assistant_config (
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 (session_id, 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 assistant_config (session_id, key, value)
123
- VALUES (${sessionId}, ${key}, ${value})
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 assistant_config
131
- WHERE session_id = ${sessionId} AND key = ${key}
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 assistant_config
139
- WHERE session_id = ${sessionId} AND key = ${key}
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-CR9ZdLiu.js").then((n) => n.n);
312
- const { sanitizeName } = await import("./manager-CR9ZdLiu.js").then((n) => n.n);
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);
@@ -909,7 +955,7 @@ var Think = class Think extends Agent {
909
955
  const _onConnect = this.onConnect.bind(this);
910
956
  this.onConnect = async (connection, ctx) => {
911
957
  if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
912
- connection.send(JSON.stringify({
958
+ else connection.send(JSON.stringify({
913
959
  type: MSG_CHAT_MESSAGES,
914
960
  messages: this.messages
915
961
  }));
@@ -1021,39 +1067,62 @@ var Think = class Think extends Agent {
1021
1067
  this._completeSkippedRequest(connection, requestId);
1022
1068
  return;
1023
1069
  }
1024
- const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
1025
- if (requestClientTools) {
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);
1070
+ const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
1071
+ let pendingEnqueue = true;
1042
1072
  const epoch = this._turnQueue.generation;
1073
+ const releaseIfPending = () => {
1074
+ if (!pendingEnqueue) return;
1075
+ pendingEnqueue = false;
1076
+ releasePendingEnqueue();
1077
+ };
1043
1078
  try {
1079
+ const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
1080
+ if (requestClientTools) {
1081
+ this._lastClientTools = requestClientTools;
1082
+ this._persistClientTools();
1083
+ } else if (rawClientTools !== void 0) {
1084
+ this._lastClientTools = void 0;
1085
+ this._persistClientTools();
1086
+ }
1087
+ const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
1088
+ this._lastBody = requestBody;
1089
+ this._persistBody();
1090
+ const clientToolsForTurn = this._lastClientTools;
1091
+ const bodyForTurn = this._lastBody;
1092
+ const serverMessages = this.session.getHistory();
1093
+ const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
1094
+ let branchParentId;
1095
+ if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
1096
+ if (this._turnQueue.generation !== epoch) {
1097
+ this._completeSkippedRequest(connection, requestId);
1098
+ return;
1099
+ }
1100
+ for (const msg of reconciled) {
1101
+ if (this._turnQueue.generation !== epoch) {
1102
+ this._completeSkippedRequest(connection, requestId);
1103
+ return;
1104
+ }
1105
+ await this._persistIncomingMessage(msg, serverMessages);
1106
+ }
1107
+ if (this._turnQueue.generation !== epoch) {
1108
+ this._completeSkippedRequest(connection, requestId);
1109
+ return;
1110
+ }
1111
+ this._broadcastMessages([connection.id]);
1112
+ const abortSignal = this._aborts.getSignal(requestId);
1044
1113
  await this.keepAliveWhile(async () => {
1045
- if ((await this._turnQueue.enqueue(requestId, async () => {
1046
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
1114
+ const turnPromise = this._turnQueue.enqueue(requestId, async () => {
1115
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
1047
1116
  this._completeSkippedRequest(connection, requestId);
1048
1117
  return;
1049
1118
  }
1050
1119
  if (concurrencyDecision.debounceUntilMs !== null) {
1051
- await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
1120
+ await this._submitConcurrency.waitForTimestamp(concurrencyDecision.debounceUntilMs);
1052
1121
  if (this._turnQueue.generation !== epoch) {
1053
1122
  this._completeSkippedRequest(connection, requestId);
1054
1123
  return;
1055
1124
  }
1056
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
1125
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
1057
1126
  this._completeSkippedRequest(connection, requestId);
1058
1127
  return;
1059
1128
  }
@@ -1082,7 +1151,9 @@ var Think = class Think extends Agent {
1082
1151
  await chatTurnBody();
1083
1152
  });
1084
1153
  else await chatTurnBody();
1085
- })).status === "stale") this._broadcastChat({
1154
+ }, { generation: epoch });
1155
+ releaseIfPending();
1156
+ if ((await turnPromise).status === "stale") this._broadcastChat({
1086
1157
  type: MSG_CHAT_RESPONSE,
1087
1158
  id: requestId,
1088
1159
  body: "",
@@ -1098,6 +1169,7 @@ var Think = class Think extends Agent {
1098
1169
  error: true
1099
1170
  });
1100
1171
  } finally {
1172
+ releaseIfPending();
1101
1173
  this._aborts.remove(requestId);
1102
1174
  }
1103
1175
  }
@@ -1116,7 +1188,7 @@ var Think = class Think extends Agent {
1116
1188
  clearTimeout(this._continuationTimer);
1117
1189
  this._continuationTimer = null;
1118
1190
  }
1119
- this._cancelActiveDebounce();
1191
+ this._submitConcurrency.reset();
1120
1192
  this._pendingInteractionPromise = null;
1121
1193
  this._continuation.sendResumeNone();
1122
1194
  this._continuation.clearAll();
@@ -1231,6 +1303,20 @@ var Think = class Think extends Agent {
1231
1303
  if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
1232
1304
  else this.session.appendMessage(safe, parentId);
1233
1305
  }
1306
+ /**
1307
+ * Persist an incoming message after reconciliation. For assistant
1308
+ * messages, also resolve their ID against any server-side row that
1309
+ * already owns the same `toolCallId` so we update the existing row
1310
+ * instead of inserting an orphan duplicate.
1311
+ */
1312
+ async _persistIncomingMessage(msg, serverMessages) {
1313
+ const safe = enforceRowSizeLimit(sanitizeMessage(msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg));
1314
+ if (this.session.getMessage(safe.id)) {
1315
+ this.session.updateMessage(safe);
1316
+ return;
1317
+ }
1318
+ await this.session.appendMessage(safe);
1319
+ }
1234
1320
  _persistClientTools() {
1235
1321
  if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
1236
1322
  else this._configDelete("lastClientTools");
@@ -1287,7 +1373,7 @@ var Think = class Think extends Agent {
1287
1373
  async waitUntilStable(options) {
1288
1374
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
1289
1375
  while (true) {
1290
- if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
1376
+ if (await this._awaitWithDeadline(this._submitConcurrency.waitForIdle(() => this._turnQueue.waitForIdle()), deadline) === TIMED_OUT) return false;
1291
1377
  if (!this.hasPendingInteraction()) return true;
1292
1378
  const pending = this._pendingInteractionPromise;
1293
1379
  if (pending) {
@@ -1377,70 +1463,13 @@ var Think = class Think extends Agent {
1377
1463
  parts
1378
1464
  };
1379
1465
  }
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
1466
  _getSubmitConcurrencyDecision(isSubmitMessage) {
1389
- const queuedTurns = this._turnQueue.queuedCount();
1390
- if (!isSubmitMessage || queuedTurns === 0) return {
1391
- action: "execute",
1392
- submitSequence: null,
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);
1467
+ return this._submitConcurrency.decide({
1468
+ concurrency: this.messageConcurrency,
1469
+ isSubmitMessage,
1470
+ queuedTurns: this._turnQueue.queuedCount()
1432
1471
  });
1433
1472
  }
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
1473
  _completeSkippedRequest(connection, requestId) {
1445
1474
  connection.send(JSON.stringify({
1446
1475
  type: MSG_CHAT_RESPONSE,
@@ -1586,6 +1615,11 @@ var Think = class Think extends Agent {
1586
1615
  }, exclude);
1587
1616
  }
1588
1617
  };
1618
+ Think.CONFIG_KEYS = [
1619
+ "_think_config",
1620
+ "lastClientTools",
1621
+ "lastBody"
1622
+ ];
1589
1623
  Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1590
1624
  Think.MESSAGE_DEBOUNCE_MS = 750;
1591
1625
  //#endregion