@deepagents/context 7.8.0 → 7.8.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/index.js CHANGED
@@ -216,24 +216,37 @@ function fragment(name, ...children) {
216
216
  data: children
217
217
  };
218
218
  }
219
- function withoutDuplicateReasoningParts(message2) {
220
- const seenReasoningItemIds = /* @__PURE__ */ new Set();
221
- let dropped = false;
222
- const parts = message2.parts.filter((part) => {
223
- if (part.type !== "reasoning") return true;
224
- const itemId = part.providerMetadata?.openai?.itemId;
225
- if (typeof itemId !== "string") return true;
226
- if (seenReasoningItemIds.has(itemId)) {
227
- dropped = true;
228
- return false;
219
+ function withReasoningItemsGrouped(message2) {
220
+ const partsByItemId = /* @__PURE__ */ new Map();
221
+ for (const part of message2.parts) {
222
+ const itemId = reasoningItemIdOf(part);
223
+ if (itemId === void 0) continue;
224
+ const itemParts = partsByItemId.get(itemId);
225
+ if (itemParts) {
226
+ itemParts.push(part);
227
+ } else {
228
+ partsByItemId.set(itemId, [part]);
229
229
  }
230
- seenReasoningItemIds.add(itemId);
231
- return true;
230
+ }
231
+ if (partsByItemId.values().every((itemParts) => itemParts.length === 1)) {
232
+ return message2;
233
+ }
234
+ const parts = message2.parts.flatMap((part) => {
235
+ const itemId = reasoningItemIdOf(part);
236
+ if (itemId === void 0) return [part];
237
+ const itemParts = partsByItemId.get(itemId) ?? [];
238
+ partsByItemId.delete(itemId);
239
+ return itemParts;
232
240
  });
233
- return dropped ? { ...message2, parts } : message2;
241
+ return { ...message2, parts };
242
+ }
243
+ function reasoningItemIdOf(part) {
244
+ if (part.type !== "reasoning") return void 0;
245
+ const itemId = part.providerMetadata?.openai?.itemId;
246
+ return typeof itemId === "string" ? itemId : void 0;
234
247
  }
235
248
  function assistant(message2) {
236
- const normalized = withoutDuplicateReasoningParts(message2);
249
+ const normalized = withReasoningItemsGrouped(message2);
237
250
  return {
238
251
  id: normalized.id,
239
252
  name: "assistant",
@@ -380,10 +393,10 @@ var Agent = class _Agent {
380
393
  }),
381
394
  stopWhen: this.#options.stopWhen ?? DEFAULT_STOP_WHEN,
382
395
  prepareStep: this.#withPrepareStep(
383
- this.#options.context.createPrepareStep({
396
+ this.#options.context.createReminderSession({
384
397
  steer: false,
385
398
  sandbox: this.#options.sandbox
386
- })
399
+ }).prepareStep
387
400
  ),
388
401
  experimental_sandbox: this.#options.sandbox.sandbox,
389
402
  tools: this.tools,
@@ -417,12 +430,11 @@ var Agent = class _Agent {
417
430
  if (!this.#options.model) {
418
431
  throw new Error(`Agent ${this.#options.name} is missing a model.`);
419
432
  }
420
- const prepareStep = this.#withPrepareStep(
421
- this.#options.context.createPrepareStep({
422
- additionalInput: this.#options.prepareStepInput,
423
- sandbox: this.#options.sandbox
424
- })
425
- );
433
+ const reminders = this.#options.context.createReminderSession({
434
+ additionalInput: this.#options.prepareStepInput,
435
+ sandbox: this.#options.sandbox
436
+ });
437
+ const prepareStep = this.#withPrepareStep(reminders.prepareStep);
426
438
  const result = await this.#createRawStream(
427
439
  options?.toolsContext,
428
440
  options,
@@ -431,6 +443,7 @@ var Agent = class _Agent {
431
443
  if (this.#guardrails.length === 0) {
432
444
  return {
433
445
  result,
446
+ reminders,
434
447
  toUIMessageStream: (uiOptions) => toUIMessageStream({
435
448
  stream: result.stream,
436
449
  tools: this.tools,
@@ -440,11 +453,13 @@ var Agent = class _Agent {
440
453
  }
441
454
  return {
442
455
  result,
456
+ reminders,
443
457
  toUIMessageStream: this.#guardedUIMessageStream(
444
458
  result,
445
459
  options?.toolsContext,
446
- options,
447
- prepareStep
460
+ reminders,
461
+ prepareStep,
462
+ options
448
463
  )
449
464
  };
450
465
  }
@@ -499,9 +514,7 @@ var Agent = class _Agent {
499
514
  }),
500
515
  repairToolCall: createRepairToolCall(model, config?.abortSignal),
501
516
  stopWhen: this.#options.stopWhen ?? DEFAULT_STOP_WHEN,
502
- prepareStep: prepareStep ?? context.createPrepareStep({
503
- sandbox: this.#options.sandbox
504
- }),
517
+ prepareStep,
505
518
  experimental_transform: config?.transform ?? smoothStream(),
506
519
  experimental_sandbox: this.#options.sandbox.sandbox,
507
520
  tools: this.tools,
@@ -518,7 +531,7 @@ var Agent = class _Agent {
518
531
  * 2. A finish-step is emitted, triggering onStepEnd to persist the self-correction
519
532
  * 3. A new stream is started and the model continues from the correction
520
533
  */
521
- #guardedUIMessageStream(result, toolsContext, config, prepareStep) {
534
+ #guardedUIMessageStream(result, toolsContext, reminders, prepareStep, config) {
522
535
  const maxRetries = config?.maxRetries ?? this.#options.maxGuardrailRetries ?? 3;
523
536
  const context = this.#options.context;
524
537
  if (!context) {
@@ -533,7 +546,7 @@ var Agent = class _Agent {
533
546
  if (!stepSaved) return;
534
547
  const head = await context.headMessage();
535
548
  if (head?.name === "assistant") {
536
- await context.writeAssistantSegment(responseMessage);
549
+ await reminders.writeAssistantSegment(responseMessage);
537
550
  } else {
538
551
  const message2 = assistantMsgId ? { ...responseMessage, id: assistantMsgId } : responseMessage;
539
552
  context.set(assistant(message2));
@@ -866,7 +879,7 @@ import {
866
879
  NoSuchToolError,
867
880
  ToolCallRepairError,
868
881
  createUIMessageStream as createUIMessageStream2,
869
- isToolUIPart
882
+ isToolUIPart as isToolUIPart2
870
883
  } from "ai";
871
884
 
872
885
  // packages/context/src/lib/fragments/reminders/src/reminders.ts
@@ -2235,7 +2248,10 @@ function once(id) {
2235
2248
  }
2236
2249
 
2237
2250
  // packages/context/src/lib/fragments/reminders/src/predicates/tool.ts
2238
- import { isStaticToolUIPart } from "ai";
2251
+ import {
2252
+ getToolName,
2253
+ isToolUIPart
2254
+ } from "ai";
2239
2255
  var COMPLETED_STATES = /* @__PURE__ */ new Set([
2240
2256
  "input-available",
2241
2257
  "output-available",
@@ -2244,12 +2260,9 @@ var COMPLETED_STATES = /* @__PURE__ */ new Set([
2244
2260
  function matchesName(spec, name) {
2245
2261
  return typeof spec === "function" ? spec(name) : spec === name;
2246
2262
  }
2247
- function toolNameOf(part) {
2248
- return part.type.slice("tool-".length);
2249
- }
2250
2263
  function toolPartsOf(message2) {
2251
2264
  if (!message2) return [];
2252
- return message2.parts.filter(isStaticToolUIPart);
2265
+ return message2.parts.filter(isToolUIPart);
2253
2266
  }
2254
2267
  function toolCall(options) {
2255
2268
  return (ctx) => {
@@ -2260,7 +2273,7 @@ function toolCall(options) {
2260
2273
  } else if (!COMPLETED_STATES.has(part.state)) {
2261
2274
  return false;
2262
2275
  }
2263
- if (options.name !== void 0 && !matchesName(options.name, toolNameOf(part))) {
2276
+ if (options.name !== void 0 && !matchesName(options.name, getToolName(part))) {
2264
2277
  return false;
2265
2278
  }
2266
2279
  if (options.input && !options.input(part.input)) {
@@ -2272,8 +2285,7 @@ function toolCall(options) {
2272
2285
  }
2273
2286
  if (options.errorText) {
2274
2287
  if (part.state !== "output-error") return false;
2275
- const text3 = part.errorText ?? "";
2276
- if (!options.errorText(text3)) return false;
2288
+ if (!options.errorText(part.errorText)) return false;
2277
2289
  }
2278
2290
  return true;
2279
2291
  });
@@ -2324,7 +2336,7 @@ function toolCallCount(name, spec) {
2324
2336
  assertCountSpec(spec);
2325
2337
  return (ctx) => {
2326
2338
  const count = toolPartsOf(ctx.lastAssistantMessage).filter(
2327
- (part) => COMPLETED_STATES.has(part.state) && matchesName(name, toolNameOf(part))
2339
+ (part) => COMPLETED_STATES.has(part.state) && matchesName(name, getToolName(part))
2328
2340
  ).length;
2329
2341
  return checkCount(count, spec);
2330
2342
  };
@@ -2341,7 +2353,7 @@ function everyNToolCalls(n) {
2341
2353
  }
2342
2354
  function toolFailureStreak(ctx, name) {
2343
2355
  const parts = (ctx.lastAssistantMessages ?? []).flatMap(
2344
- (message2) => toolPartsOf(message2).filter((part) => matchesName(name, toolNameOf(part)))
2356
+ (message2) => toolPartsOf(message2).filter((part) => matchesName(name, getToolName(part)))
2345
2357
  );
2346
2358
  let streak = 0;
2347
2359
  for (const part of parts.toReversed()) {
@@ -2357,6 +2369,9 @@ function toolFailedStreak(name, spec) {
2357
2369
 
2358
2370
  // packages/context/src/lib/fragments/reminders/src/predicates/turn.ts
2359
2371
  function everyNTurns(n) {
2372
+ if (!Number.isInteger(n) || n < 1) {
2373
+ throw new Error("everyNTurns(n) requires a positive integer");
2374
+ }
2360
2375
  return ({ turn }) => turn % n === 0;
2361
2376
  }
2362
2377
  function first() {
@@ -2658,7 +2673,7 @@ import { getErrorMessage } from "@ai-sdk/provider";
2658
2673
  import {
2659
2674
  convertToModelMessages as convertToModelMessages2,
2660
2675
  generateId as generateId5,
2661
- isStaticToolUIPart as isStaticToolUIPart2,
2676
+ isStaticToolUIPart,
2662
2677
  validateUIMessages
2663
2678
  } from "ai";
2664
2679
  import pMemoize2 from "p-memoize";
@@ -3292,7 +3307,7 @@ var SavePipeline = class _SavePipeline {
3292
3307
 
3293
3308
  // packages/context/src/lib/store/sqlite.store.ts
3294
3309
  import { Declaration } from "@zukhruf/sqlite-drift";
3295
- import { open } from "@zukhruf/sqlite-open";
3310
+ import { SQLITE_ERROR, open, sqliteResultCode } from "@zukhruf/sqlite-open";
3296
3311
  import { transaction } from "@zukhruf/sqlite-transaction";
3297
3312
  import { z as z4 } from "zod";
3298
3313
 
@@ -3532,7 +3547,7 @@ var SearchQuerySyntaxError = class extends Error {
3532
3547
  }
3533
3548
  };
3534
3549
  function isFts5QueryError(error) {
3535
- return Error.isError(error) && "errcode" in error && error.errcode === 1 && /^(fts5: syntax error near |no such column: |unterminated string$|unknown special query: |expected integer, got )/.test(
3550
+ return Error.isError(error) && sqliteResultCode(error)?.extendedCode === SQLITE_ERROR && /^(fts5: syntax error near |no such column: |unterminated string$|unknown special query: |expected integer, got )/.test(
3536
3551
  error.message
3537
3552
  );
3538
3553
  }
@@ -4136,7 +4151,7 @@ function terminalToolPartsFromStep(content) {
4136
4151
  function mergeTerminalToolParts(message2, liveParts) {
4137
4152
  const remaining = new Map(liveParts);
4138
4153
  const parts = message2.parts.map((part) => {
4139
- if (!isStaticToolUIPart2(part)) return part;
4154
+ if (!isStaticToolUIPart(part)) return part;
4140
4155
  remaining.delete(part.toolCallId);
4141
4156
  return part;
4142
4157
  });
@@ -4534,15 +4549,11 @@ var ContextEngine = class _ContextEngine {
4534
4549
  }
4535
4550
  }
4536
4551
  /**
4537
- * Writes the streamed assistant message: the whole message to the reserved
4538
- * head, until createPrepareStep() binds a reminder session's segments.
4539
- */
4540
- #writeAssistant = (headId, message2) => this.#writeWholeAssistant(headId, message2);
4541
- /**
4542
- * Build the `prepareStep` hook that injects reminders between model steps.
4543
- * Tool-output reminders are evaluated against the preceding step's completed
4544
- * tool results and appended after the SDK's tool-result message. Steer
4545
- * reminders share the same synthetic user message when both fire together.
4552
+ * Open the reminder session of one model stream. Its `prepareStep` injects
4553
+ * reminders between model steps: tool-output reminders are evaluated against
4554
+ * the preceding step's completed tool results and appended after the SDK's
4555
+ * tool-result message, and steer reminders share the same synthetic user
4556
+ * message when both fire together.
4546
4557
  *
4547
4558
  * Each eligible boundary evaluates its reminders independently. A predicate
4548
4559
  * that remains true fires at every boundary; compose `once()` when a durable
@@ -4550,12 +4561,11 @@ var ContextEngine = class _ContextEngine {
4550
4561
  * subsequent steps.
4551
4562
  *
4552
4563
  * Each injected input is persisted with a following assistant placeholder
4553
- * before prepareStep returns. writeAssistantSegment fills that placeholder,
4554
- * so process loss cannot make a delivered reminder eligible again and later
4555
- * requests reproduce the exact prompt prefix the model saw.
4564
+ * before `prepareStep` returns. The session's `writeAssistantSegment` fills
4565
+ * that placeholder, so process loss cannot make a delivered reminder eligible
4566
+ * again and later requests reproduce the exact prompt prefix the model saw.
4556
4567
  */
4557
- createPrepareStep(options = {}) {
4558
- const enableSteer = options.steer ?? true;
4568
+ createReminderSession(options = {}) {
4559
4569
  const session = {
4560
4570
  firedOnceIds: /* @__PURE__ */ new Set(),
4561
4571
  terminalToolParts: /* @__PURE__ */ new Map(),
@@ -4564,8 +4574,12 @@ var ContextEngine = class _ContextEngine {
4564
4574
  stepOffset: 0,
4565
4575
  lastStepNumber: null
4566
4576
  };
4567
- this.#writeAssistant = (headId, message2) => this.#writeSessionSegment(session, headId, message2);
4568
- return async ({ steps, stepNumber, messages }) => {
4577
+ const enableSteer = options.steer ?? true;
4578
+ const prepareStep = async ({
4579
+ steps,
4580
+ stepNumber,
4581
+ messages
4582
+ }) => {
4569
4583
  if (stepNumber === 0 && session.lastStepNumber !== null) {
4570
4584
  session.stepOffset += session.lastStepNumber + 1;
4571
4585
  }
@@ -4628,17 +4642,11 @@ var ContextEngine = class _ContextEngine {
4628
4642
  const inputModel = await convertToModelMessages2(inputs, {
4629
4643
  ignoreIncompleteToolCalls: true
4630
4644
  });
4631
- const head = await this.headMessage();
4632
- if (head?.name !== "assistant") {
4633
- throw new Error(
4634
- "createPrepareStep: expected an assistant message at chain head."
4635
- );
4636
- }
4637
- const currentSegmentId = head.id;
4645
+ const currentSegmentId = await this.#assistantHeadId("prepareStep");
4638
4646
  const currentSegment = await this.#store.getMessage(currentSegmentId);
4639
4647
  if (!currentSegment || currentSegment.name !== "assistant") {
4640
4648
  throw new Error(
4641
- "createPrepareStep: expected the open assistant segment to be persisted."
4649
+ "prepareStep: expected the open assistant segment to be persisted."
4642
4650
  );
4643
4651
  }
4644
4652
  requireUIMessage(
@@ -4672,28 +4680,32 @@ var ContextEngine = class _ContextEngine {
4672
4680
  }
4673
4681
  return void 0;
4674
4682
  };
4683
+ return {
4684
+ prepareStep,
4685
+ writeAssistantSegment: async (message2) => {
4686
+ const headId = await this.#assistantHeadId("writeAssistantSegment");
4687
+ await this.#writeSessionSegment(session, headId, message2);
4688
+ }
4689
+ };
4675
4690
  }
4676
4691
  /**
4677
- * Persist the streamed assistant message into its reserved segment.
4678
- *
4679
- * Called from chat()'s onStepEnd/onEnd (and the guardrail path) with the
4680
- * cumulative response message. prepareStep has already persisted reminder
4681
- * boundaries and reserved the open segment id, so this only updates that
4682
- * segment in place with the cumulative prefix removed. With no fired reminder
4683
- * it writes the whole message to the original reserved head.
4692
+ * Persist a streamed assistant message, whole, into the reserved head. A
4693
+ * stream whose reminders split the assistant writes through its
4694
+ * {@link ReminderSession}'s `writeAssistantSegment` instead.
4684
4695
  */
4685
4696
  async writeAssistantSegment(message2) {
4697
+ const headId = await this.#assistantHeadId("writeAssistantSegment");
4698
+ this.set(assistant({ ...message2, id: headId }));
4699
+ await this.save({ branch: false });
4700
+ }
4701
+ async #assistantHeadId(caller) {
4686
4702
  const head = await this.headMessage();
4687
4703
  if (head?.name !== "assistant") {
4688
4704
  throw new Error(
4689
- "writeAssistantSegment: expected an assistant message at chain head."
4705
+ `${caller}: expected an assistant message at chain head.`
4690
4706
  );
4691
4707
  }
4692
- await this.#writeAssistant(head.id, message2);
4693
- }
4694
- async #writeWholeAssistant(headId, message2) {
4695
- this.set(assistant({ ...message2, id: headId }));
4696
- await this.save({ branch: false });
4708
+ return head.id;
4697
4709
  }
4698
4710
  async #writeSessionSegment(session, headId, message2) {
4699
4711
  let id = headId;
@@ -5815,12 +5827,13 @@ async function chat(agent2, ...args) {
5815
5827
  const initialAssistantMsgId = head.id;
5816
5828
  const uiMessages = await context.getMessages();
5817
5829
  let result;
5830
+ const writeAssistantSegment = (message2) => (result?.reminders ?? context).writeAssistantSegment(message2);
5818
5831
  return createUIMessageStream2({
5819
5832
  originalMessages: uiMessages,
5820
5833
  generateId: () => initialAssistantMsgId,
5821
5834
  onError: options?.onError ?? formatChatError,
5822
5835
  onStepEnd: async ({ responseMessage }) => {
5823
- await context.writeAssistantSegment(responseMessage);
5836
+ await writeAssistantSegment(responseMessage);
5824
5837
  },
5825
5838
  onEnd: async ({ responseMessage, isAborted }) => {
5826
5839
  const settled = isAborted ? {
@@ -5831,7 +5844,7 @@ async function chat(agent2, ...args) {
5831
5844
  // A provider can end at its token limit midway through arguments.
5832
5845
  // That call failed; it is not waiting for client input or approval.
5833
5846
  parts: responseMessage.parts.map((part) => {
5834
- if (!isToolUIPart(part) || part.state !== "input-streaming")
5847
+ if (!isToolUIPart2(part) || part.state !== "input-streaming")
5835
5848
  return part;
5836
5849
  const failed = {
5837
5850
  ...part,
@@ -5850,7 +5863,7 @@ async function chat(agent2, ...args) {
5850
5863
  ...finalMetadata ?? {}
5851
5864
  };
5852
5865
  const message2 = Object.keys(mergedMetadata).length > 0 ? { ...settled, metadata: mergedMetadata } : settled;
5853
- await context.writeAssistantSegment(message2);
5866
+ await writeAssistantSegment(message2);
5854
5867
  const usage = await result?.result.usage;
5855
5868
  if (usage !== void 0) {
5856
5869
  await context.trackUsage(usage);
@@ -5889,7 +5902,7 @@ async function chat(agent2, ...args) {
5889
5902
  function sanitizeAbortedParts(parts) {
5890
5903
  const sanitized = [];
5891
5904
  for (const part of parts) {
5892
- if (!isToolUIPart(part)) {
5905
+ if (!isToolUIPart2(part)) {
5893
5906
  sanitized.push(part);
5894
5907
  continue;
5895
5908
  }