@cloudflare/think 0.3.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;
@@ -68,8 +65,19 @@ var Think = class Think extends Agent {
68
65
  return this.session.getHistory();
69
66
  }
70
67
  /**
71
- * Persist a typed configuration object.
72
- * Stored in Session's assistant_config table — survives restarts and hibernation.
68
+ * Persist an arbitrary JSON-serializable configuration object for this
69
+ * agent instance. Stored in the Think-private `think_config` table —
70
+ * survives
71
+ * restarts and hibernation. Pass the config shape as a method generic
72
+ * for typed call sites:
73
+ *
74
+ * ```ts
75
+ * this.configure<MyConfig>({ modelTier: "fast" });
76
+ * ```
77
+ *
78
+ * Prefer `state` / `setState` from `Agent` when you want the value
79
+ * broadcast to connected clients. Use `configure` for private
80
+ * per-instance config that should stay server-side.
73
81
  */
74
82
  configure(config) {
75
83
  const json = JSON.stringify(config);
@@ -78,9 +86,14 @@ var Think = class Think extends Agent {
78
86
  }
79
87
  /**
80
88
  * Read the persisted configuration, or null if never configured.
89
+ * Pass the config shape as a method generic for a typed result:
90
+ *
91
+ * ```ts
92
+ * const cfg = this.getConfig<MyConfig>();
93
+ * ```
81
94
  */
82
95
  getConfig() {
83
- if (_classPrivateFieldGet2(_configCache, this)) return _classPrivateFieldGet2(_configCache, this);
96
+ if (_classPrivateFieldGet2(_configCache, this) !== null) return _classPrivateFieldGet2(_configCache, this);
84
97
  const raw = this._configGet("_think_config");
85
98
  if (raw !== void 0) {
86
99
  _classPrivateFieldSet2(_configCache, this, JSON.parse(raw));
@@ -88,45 +101,54 @@ var Think = class Think extends Agent {
88
101
  }
89
102
  return null;
90
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
+ }
91
119
  _ensureConfigTable() {
92
120
  if (_classPrivateFieldGet2(_configTableReady, this)) return;
93
121
  this.sql`
94
- CREATE TABLE IF NOT EXISTS assistant_config (
95
- session_id TEXT NOT NULL,
122
+ CREATE TABLE IF NOT EXISTS think_config (
96
123
  key TEXT NOT NULL,
97
124
  value TEXT NOT NULL,
98
- PRIMARY KEY (session_id, key)
125
+ PRIMARY KEY (key)
99
126
  )
100
127
  `;
128
+ this._migrateLegacyConfigToThinkTable();
101
129
  _classPrivateFieldSet2(_configTableReady, this, true);
102
130
  }
103
131
  _configSet(key, value) {
104
132
  this._ensureConfigTable();
105
- const sessionId = this._sessionId();
106
133
  this.sql`
107
- INSERT OR REPLACE INTO assistant_config (session_id, key, value)
108
- VALUES (${sessionId}, ${key}, ${value})
134
+ INSERT OR REPLACE INTO think_config (key, value)
135
+ VALUES (${key}, ${value})
109
136
  `;
110
137
  }
111
138
  _configGet(key) {
112
139
  this._ensureConfigTable();
113
- const sessionId = this._sessionId();
114
140
  return this.sql`
115
- SELECT value FROM assistant_config
116
- WHERE session_id = ${sessionId} AND key = ${key}
141
+ SELECT value FROM think_config
142
+ WHERE key = ${key}
117
143
  `[0]?.value;
118
144
  }
119
145
  _configDelete(key) {
120
146
  this._ensureConfigTable();
121
- const sessionId = this._sessionId();
122
147
  this.sql`
123
- DELETE FROM assistant_config
124
- WHERE session_id = ${sessionId} AND key = ${key}
148
+ DELETE FROM think_config
149
+ WHERE key = ${key}
125
150
  `;
126
151
  }
127
- _sessionId() {
128
- return "";
129
- }
130
152
  /**
131
153
  * Return the language model to use for inference.
132
154
  * Must be overridden by subclasses.
@@ -192,6 +214,40 @@ var Think = class Think extends Agent {
192
214
  */
193
215
  beforeTurn(_ctx) {}
194
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
+ /**
195
251
  * Called **before** the tool's `execute` function runs. Think wraps
196
252
  * every tool's `execute` so it can consult this hook and act on the
197
253
  * returned `ToolCallDecision`:
@@ -293,8 +349,8 @@ var Think = class Think extends Agent {
293
349
  return error;
294
350
  }
295
351
  async _initializeExtensions() {
296
- const { ExtensionManager } = await import("./manager-CR9ZdLiu.js").then((n) => n.n);
297
- 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);
298
354
  const agentClassName = this.constructor.name;
299
355
  const agentId = this.ctx.id.toString();
300
356
  const ctxExports = this.ctx.exports;
@@ -388,7 +444,12 @@ var Think = class Think extends Agent {
388
444
  toolChoice: config.toolChoice,
389
445
  stopWhen: stepCountIs(finalMaxSteps),
390
446
  providerOptions: config.providerOptions,
447
+ output: config.output,
391
448
  abortSignal: input.signal,
449
+ prepareStep: (async (event) => {
450
+ const result = await this.beforeStep(event);
451
+ return result == null ? {} : result;
452
+ }),
392
453
  onChunk: async (event) => {
393
454
  await this.onChunk(event);
394
455
  await this._pipelineExtensionChunk(event);
@@ -894,7 +955,7 @@ var Think = class Think extends Agent {
894
955
  const _onConnect = this.onConnect.bind(this);
895
956
  this.onConnect = async (connection, ctx) => {
896
957
  if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
897
- connection.send(JSON.stringify({
958
+ else connection.send(JSON.stringify({
898
959
  type: MSG_CHAT_MESSAGES,
899
960
  messages: this.messages
900
961
  }));
@@ -1006,39 +1067,62 @@ var Think = class Think extends Agent {
1006
1067
  this._completeSkippedRequest(connection, requestId);
1007
1068
  return;
1008
1069
  }
1009
- const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
1010
- if (requestClientTools) {
1011
- this._lastClientTools = requestClientTools;
1012
- this._persistClientTools();
1013
- } else if (rawClientTools !== void 0) {
1014
- this._lastClientTools = void 0;
1015
- this._persistClientTools();
1016
- }
1017
- const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
1018
- this._lastBody = requestBody;
1019
- this._persistBody();
1020
- const clientToolsForTurn = this._lastClientTools;
1021
- const bodyForTurn = this._lastBody;
1022
- let branchParentId;
1023
- if (isRegeneration && incomingMessages.length > 0) branchParentId = incomingMessages[incomingMessages.length - 1].id;
1024
- for (const msg of incomingMessages) await this.session.appendMessage(msg);
1025
- this._broadcastMessages([connection.id]);
1026
- const abortSignal = this._aborts.getSignal(requestId);
1070
+ const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();
1071
+ let pendingEnqueue = true;
1027
1072
  const epoch = this._turnQueue.generation;
1073
+ const releaseIfPending = () => {
1074
+ if (!pendingEnqueue) return;
1075
+ pendingEnqueue = false;
1076
+ releasePendingEnqueue();
1077
+ };
1028
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);
1029
1113
  await this.keepAliveWhile(async () => {
1030
- if ((await this._turnQueue.enqueue(requestId, async () => {
1031
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
1114
+ const turnPromise = this._turnQueue.enqueue(requestId, async () => {
1115
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
1032
1116
  this._completeSkippedRequest(connection, requestId);
1033
1117
  return;
1034
1118
  }
1035
1119
  if (concurrencyDecision.debounceUntilMs !== null) {
1036
- await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
1120
+ await this._submitConcurrency.waitForTimestamp(concurrencyDecision.debounceUntilMs);
1037
1121
  if (this._turnQueue.generation !== epoch) {
1038
1122
  this._completeSkippedRequest(connection, requestId);
1039
1123
  return;
1040
1124
  }
1041
- if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
1125
+ if (this._submitConcurrency.isSuperseded(concurrencyDecision.submitSequence)) {
1042
1126
  this._completeSkippedRequest(connection, requestId);
1043
1127
  return;
1044
1128
  }
@@ -1067,7 +1151,9 @@ var Think = class Think extends Agent {
1067
1151
  await chatTurnBody();
1068
1152
  });
1069
1153
  else await chatTurnBody();
1070
- })).status === "stale") this._broadcastChat({
1154
+ }, { generation: epoch });
1155
+ releaseIfPending();
1156
+ if ((await turnPromise).status === "stale") this._broadcastChat({
1071
1157
  type: MSG_CHAT_RESPONSE,
1072
1158
  id: requestId,
1073
1159
  body: "",
@@ -1083,6 +1169,7 @@ var Think = class Think extends Agent {
1083
1169
  error: true
1084
1170
  });
1085
1171
  } finally {
1172
+ releaseIfPending();
1086
1173
  this._aborts.remove(requestId);
1087
1174
  }
1088
1175
  }
@@ -1101,7 +1188,7 @@ var Think = class Think extends Agent {
1101
1188
  clearTimeout(this._continuationTimer);
1102
1189
  this._continuationTimer = null;
1103
1190
  }
1104
- this._cancelActiveDebounce();
1191
+ this._submitConcurrency.reset();
1105
1192
  this._pendingInteractionPromise = null;
1106
1193
  this._continuation.sendResumeNone();
1107
1194
  this._continuation.clearAll();
@@ -1216,6 +1303,20 @@ var Think = class Think extends Agent {
1216
1303
  if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
1217
1304
  else this.session.appendMessage(safe, parentId);
1218
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
+ }
1219
1320
  _persistClientTools() {
1220
1321
  if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
1221
1322
  else this._configDelete("lastClientTools");
@@ -1272,7 +1373,7 @@ var Think = class Think extends Agent {
1272
1373
  async waitUntilStable(options) {
1273
1374
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
1274
1375
  while (true) {
1275
- 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;
1276
1377
  if (!this.hasPendingInteraction()) return true;
1277
1378
  const pending = this._pendingInteractionPromise;
1278
1379
  if (pending) {
@@ -1362,70 +1463,13 @@ var Think = class Think extends Agent {
1362
1463
  parts
1363
1464
  };
1364
1465
  }
1365
- _normalizeMessageConcurrency() {
1366
- if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
1367
- const debounceMs = this.messageConcurrency.debounceMs;
1368
- return {
1369
- strategy: "debounce",
1370
- debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : Think.MESSAGE_DEBOUNCE_MS
1371
- };
1372
- }
1373
1466
  _getSubmitConcurrencyDecision(isSubmitMessage) {
1374
- const queuedTurns = this._turnQueue.queuedCount();
1375
- if (!isSubmitMessage || queuedTurns === 0) return {
1376
- action: "execute",
1377
- submitSequence: null,
1378
- debounceUntilMs: null
1379
- };
1380
- const concurrency = this._normalizeMessageConcurrency();
1381
- if (concurrency === "queue") return {
1382
- action: "execute",
1383
- submitSequence: null,
1384
- debounceUntilMs: null
1385
- };
1386
- if (concurrency === "drop") return {
1387
- action: "drop",
1388
- submitSequence: null,
1389
- debounceUntilMs: null
1390
- };
1391
- const submitSequence = ++this._submitSequence;
1392
- this._latestOverlappingSubmitSequence = submitSequence;
1393
- if (concurrency === "latest" || concurrency === "merge") return {
1394
- action: "execute",
1395
- submitSequence,
1396
- debounceUntilMs: null
1397
- };
1398
- return {
1399
- action: "execute",
1400
- submitSequence,
1401
- debounceUntilMs: Date.now() + concurrency.debounceMs
1402
- };
1403
- }
1404
- _isSupersededSubmit(submitSequence) {
1405
- return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
1406
- }
1407
- async _waitForTimestamp(timestampMs) {
1408
- const remainingMs = timestampMs - Date.now();
1409
- if (remainingMs <= 0) return;
1410
- await new Promise((resolve) => {
1411
- this._activeDebounceResolve = resolve;
1412
- this._activeDebounceTimer = setTimeout(() => {
1413
- this._activeDebounceTimer = null;
1414
- this._activeDebounceResolve = null;
1415
- resolve();
1416
- }, remainingMs);
1467
+ return this._submitConcurrency.decide({
1468
+ concurrency: this.messageConcurrency,
1469
+ isSubmitMessage,
1470
+ queuedTurns: this._turnQueue.queuedCount()
1417
1471
  });
1418
1472
  }
1419
- _cancelActiveDebounce() {
1420
- if (this._activeDebounceTimer !== null) {
1421
- clearTimeout(this._activeDebounceTimer);
1422
- this._activeDebounceTimer = null;
1423
- }
1424
- if (this._activeDebounceResolve !== null) {
1425
- this._activeDebounceResolve();
1426
- this._activeDebounceResolve = null;
1427
- }
1428
- }
1429
1473
  _completeSkippedRequest(connection, requestId) {
1430
1474
  connection.send(JSON.stringify({
1431
1475
  type: MSG_CHAT_RESPONSE,
@@ -1571,6 +1615,11 @@ var Think = class Think extends Agent {
1571
1615
  }, exclude);
1572
1616
  }
1573
1617
  };
1618
+ Think.CONFIG_KEYS = [
1619
+ "_think_config",
1620
+ "lastClientTools",
1621
+ "lastBody"
1622
+ ];
1574
1623
  Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1575
1624
  Think.MESSAGE_DEBOUNCE_MS = 750;
1576
1625
  //#endregion