@deepagents/context 7.1.3 → 7.2.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/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export * from './lib/guardrails/error-recovery.guardrail.ts';
20
20
  export * from './lib/models.generated.ts';
21
21
  export * from './lib/render.ts';
22
22
  export * from './lib/renderers/abstract.renderer.ts';
23
- export * from './lib/repair.ts';
23
+ export { createRepairToolCall } from '@deepagents/agent';
24
24
  export * from './lib/resolvers/index.ts';
25
25
  export * from './lib/sandbox/index.ts';
26
26
  export * from './lib/skills/index.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC;AACrC,cAAc,iCAAiC,CAAC;AAChD,cAAc,qCAAqC,CAAC;AACpD,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,yBAAyB,CAAC;AACxC,cAAc,oCAAoC,CAAC;AACnD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yBAAyB,CAAC;AACxC,cAAc,oBAAoB,CAAC;AACnC,cAAc,8CAA8C,CAAC;AAC7D,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,sCAAsC,CAAC;AACrD,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qCAAqC,CAAC;AACpD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uCAAuC,CAAC;AACtD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,+CAA+C,CAAC;AAC9D,cAAc,uCAAuC,CAAC;AACtD,cAAc,qCAAqC,CAAC;AACpD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC;AACrC,cAAc,iCAAiC,CAAC;AAChD,cAAc,qCAAqC,CAAC;AACpD,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,oBAAoB,CAAC;AACnC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iCAAiC,CAAC;AAChD,cAAc,yBAAyB,CAAC;AACxC,cAAc,oCAAoC,CAAC;AACnD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,kCAAkC,CAAC;AACjD,cAAc,yBAAyB,CAAC;AACxC,cAAc,oBAAoB,CAAC;AACnC,cAAc,8CAA8C,CAAC;AAC7D,cAAc,2BAA2B,CAAC;AAC1C,cAAc,iBAAiB,CAAC;AAChC,cAAc,sCAAsC,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qCAAqC,CAAC;AACpD,cAAc,+BAA+B,CAAC;AAC9C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,sBAAsB,CAAC;AACrC,cAAc,wBAAwB,CAAC;AACvC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,uCAAuC,CAAC;AACtD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,+CAA+C,CAAC;AAC9D,cAAc,uCAAuC,CAAC;AACtD,cAAc,qCAAqC,CAAC;AACpD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,8BAA8B,CAAC;AAC7C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -144,19 +144,22 @@ function mapGenerateErrorToCode(error) {
144
144
 
145
145
  // packages/context/src/lib/agent.ts
146
146
  import {
147
- Output as Output2,
147
+ Output,
148
148
  convertToModelMessages,
149
149
  createUIMessageStream,
150
150
  generateId as generateId3,
151
- generateText as generateText2,
151
+ generateText,
152
152
  isStepCount,
153
153
  smoothStream,
154
154
  streamText,
155
155
  tool
156
156
  } from "ai";
157
- import chalk2 from "chalk";
157
+ import chalk from "chalk";
158
158
  import z from "zod";
159
- import { withHostOnlyToolMetadata } from "@deepagents/agent";
159
+ import {
160
+ createRepairToolCall,
161
+ withHostOnlyToolMetadata
162
+ } from "@deepagents/agent";
160
163
 
161
164
  // packages/context/src/lib/fragments.ts
162
165
  import { generateId } from "ai";
@@ -327,39 +330,6 @@ function runGuardrailChain(part, guardrails, context) {
327
330
  return pass(currentPart);
328
331
  }
329
332
 
330
- // packages/context/src/lib/repair.ts
331
- import "@ai-sdk/provider";
332
- import {
333
- NoSuchToolError,
334
- Output,
335
- generateText
336
- } from "ai";
337
- import chalk from "chalk";
338
- function createRepairToolCall(model, abortSignal) {
339
- return async ({ toolCall: toolCall2, tools, inputSchema: inputSchema2, error }) => {
340
- if (NoSuchToolError.isInstance(error)) {
341
- return null;
342
- }
343
- console.log(
344
- `Debug: ${chalk.yellow("RepairingToolCall")}: ${toolCall2.toolName}`
345
- );
346
- const tool4 = tools[toolCall2.toolName];
347
- const { output } = await generateText({
348
- abortSignal,
349
- model,
350
- output: Output.object({ schema: tool4.inputSchema }),
351
- prompt: [
352
- `The model tried to call the tool "${toolCall2.toolName}" with the following inputs:`,
353
- JSON.stringify(toolCall2.input),
354
- `The tool accepts the following schema:`,
355
- JSON.stringify(inputSchema2(toolCall2)),
356
- "Please fix the inputs."
357
- ].join("\n")
358
- });
359
- return { ...toolCall2, input: JSON.stringify(output) };
360
- };
361
- }
362
-
363
333
  // packages/context/src/lib/agent.ts
364
334
  var DEFAULT_STOP_WHEN = isStepCount(200);
365
335
  var Agent = class _Agent {
@@ -390,7 +360,13 @@ var Agent = class _Agent {
390
360
  renderer: new XmlRenderer(),
391
361
  sandbox: this.#options.sandbox
392
362
  });
393
- return generateText2({
363
+ return generateText({
364
+ reasoning: this.#options.reasoning,
365
+ maxOutputTokens: this.#options.maxOutputTokens,
366
+ timeout: this.#options.timeout,
367
+ toolCallConcurrency: this.#options.toolCallConcurrency,
368
+ toolApproval: this.#options.toolApproval,
369
+ experimental_toolApprovalSecret: this.#options.experimental_toolApprovalSecret,
394
370
  abortSignal: options?.abortSignal,
395
371
  providerOptions: this.#options.providerOptions,
396
372
  telemetry: this.#options.telemetry,
@@ -489,6 +465,12 @@ var Agent = class _Agent {
489
465
  sandbox: this.#options.sandbox
490
466
  });
491
467
  return streamText({
468
+ reasoning: this.#options.reasoning,
469
+ maxOutputTokens: this.#options.maxOutputTokens,
470
+ timeout: this.#options.timeout,
471
+ toolCallConcurrency: this.#options.toolCallConcurrency,
472
+ toolApproval: this.#options.toolApproval,
473
+ experimental_toolApprovalSecret: this.#options.experimental_toolApprovalSecret,
492
474
  abortSignal: config?.abortSignal,
493
475
  onStart: config?.onStart,
494
476
  onStepStart: config?.onStepStart,
@@ -577,7 +559,7 @@ var Agent = class _Agent {
577
559
  guardrailFailed = true;
578
560
  failureFeedback = checkResult.feedback;
579
561
  console.log(
580
- chalk2.yellow(
562
+ chalk.yellow(
581
563
  `[${this.#options.name}] Guardrail triggered (attempt ${attempt}/${maxRetries}): ${failureFeedback.slice(0, 50)}...`
582
564
  )
583
565
  );
@@ -585,7 +567,7 @@ var Agent = class _Agent {
585
567
  }
586
568
  if (checkResult.type === "stop") {
587
569
  console.log(
588
- chalk2.red(
570
+ chalk.red(
589
571
  `[${this.#options.name}] Guardrail stopped - unrecoverable error, no retry`
590
572
  )
591
573
  );
@@ -601,7 +583,7 @@ var Agent = class _Agent {
601
583
  }
602
584
  if (attempt >= maxRetries) {
603
585
  console.error(
604
- chalk2.red(
586
+ chalk.red(
605
587
  `[${this.#options.name}] Guardrail retry limit (${maxRetries}) exceeded.`
606
588
  )
607
589
  );
@@ -715,7 +697,9 @@ ${details}
715
697
  );
716
698
  const advisorSystemPrompt = advisorCtx.render(new XmlRenderer());
717
699
  try {
718
- const result = await generateText2({
700
+ const result = await generateText({
701
+ reasoning: this.#options.reasoning,
702
+ timeout: this.#options.timeout,
719
703
  model: this.model,
720
704
  instructions: advisorSystemPrompt,
721
705
  messages: executionOptions.messages,
@@ -765,7 +749,13 @@ function structuredOutput(options) {
765
749
  renderer: new XmlRenderer(),
766
750
  sandbox: options.sandbox
767
751
  });
768
- const result = await generateText2({
752
+ const result = await generateText({
753
+ reasoning: options.reasoning,
754
+ maxOutputTokens: options.maxOutputTokens,
755
+ timeout: options.timeout,
756
+ toolCallConcurrency: options.toolCallConcurrency,
757
+ toolApproval: options.toolApproval,
758
+ experimental_toolApprovalSecret: options.experimental_toolApprovalSecret,
769
759
  abortSignal: callOptions?.abortSignal,
770
760
  providerOptions: options.providerOptions,
771
761
  telemetry: options.telemetry,
@@ -781,7 +771,7 @@ function structuredOutput(options) {
781
771
  callOptions?.abortSignal
782
772
  ),
783
773
  toolsContext: callOptions?.toolsContext,
784
- output: Output2.object({ schema: options.schema }),
774
+ output: Output.object({ schema: options.schema }),
785
775
  tools
786
776
  });
787
777
  return result.output;
@@ -798,6 +788,12 @@ function structuredOutput(options) {
798
788
  sandbox: options.sandbox
799
789
  });
800
790
  return streamText({
791
+ reasoning: options.reasoning,
792
+ maxOutputTokens: options.maxOutputTokens,
793
+ timeout: options.timeout,
794
+ toolCallConcurrency: options.toolCallConcurrency,
795
+ toolApproval: options.toolApproval,
796
+ experimental_toolApprovalSecret: options.experimental_toolApprovalSecret,
801
797
  abortSignal: callOptions?.abortSignal,
802
798
  providerOptions: options.providerOptions,
803
799
  telemetry: options.telemetry,
@@ -814,7 +810,7 @@ function structuredOutput(options) {
814
810
  stopWhen: DEFAULT_STOP_WHEN,
815
811
  experimental_transform: callOptions?.transform ?? smoothStream(),
816
812
  toolsContext: callOptions?.toolsContext,
817
- output: Output2.object({ schema: options.schema }),
813
+ output: Output.object({ schema: options.schema }),
818
814
  tools
819
815
  });
820
816
  }
@@ -849,7 +845,7 @@ function writeText(writer, text, openPartId) {
849
845
  import {
850
846
  APICallError as APICallError2,
851
847
  InvalidToolInputError,
852
- NoSuchToolError as NoSuchToolError2,
848
+ NoSuchToolError,
853
849
  ToolCallRepairError,
854
850
  createUIMessageStream as createUIMessageStream2,
855
851
  isToolUIPart
@@ -3299,6 +3295,7 @@ var SavePipeline = class _SavePipeline {
3299
3295
  };
3300
3296
 
3301
3297
  // packages/context/src/lib/store/sqlite.store.ts
3298
+ import { Declaration } from "@zukhruf/sqlite-drift";
3302
3299
  import { transaction } from "@zukhruf/sqlite-transaction";
3303
3300
  import {
3304
3301
  DatabaseSync
@@ -3316,8 +3313,88 @@ function parseJsonObject(text) {
3316
3313
  return jsonObject.parse(parseJson(text));
3317
3314
  }
3318
3315
 
3319
- // packages/context/src/lib/store/ddl.sqlite.sql
3320
- var ddl_sqlite_default = "-- Context Store DDL for SQLite\n-- This schema implements a DAG-based message history with branching and checkpoints.\n\n-- Performance PRAGMAs (session-level, run on each connection)\nPRAGMA journal_mode = WAL;\nPRAGMA synchronous = NORMAL;\nPRAGMA cache_size = -64000;\nPRAGMA temp_store = MEMORY;\nPRAGMA mmap_size = 268435456;\nPRAGMA busy_timeout = 5000;\n\n-- Integrity\nPRAGMA foreign_keys = ON;\n\n-- Chats table\n-- createdAt/updatedAt: DEFAULT for insert, inline SET for updates\nCREATE TABLE IF NOT EXISTS chats (\n id TEXT PRIMARY KEY,\n userId TEXT NOT NULL,\n title TEXT,\n metadata TEXT,\n createdAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),\n updatedAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)\n);\n\nCREATE INDEX IF NOT EXISTS idx_chats_updatedAt ON chats(updatedAt);\nCREATE INDEX IF NOT EXISTS idx_chats_userId ON chats(userId);\n-- Composite index for listChats(): WHERE userId = ? ORDER BY updatedAt DESC\nCREATE INDEX IF NOT EXISTS idx_chats_userId_updatedAt ON chats(userId, updatedAt DESC);\n\n-- Messages table (nodes in the DAG)\nCREATE TABLE IF NOT EXISTS messages (\n id TEXT PRIMARY KEY,\n chatId TEXT NOT NULL,\n parentId TEXT,\n name TEXT NOT NULL,\n type TEXT,\n data TEXT NOT NULL,\n createdAt INTEGER NOT NULL,\n FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,\n FOREIGN KEY (parentId) REFERENCES messages(id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_messages_chatId ON messages(chatId);\nCREATE INDEX IF NOT EXISTS idx_messages_parentId ON messages(parentId);\n-- Composite index for recursive CTE parent traversal in getMessageChain()\nCREATE INDEX IF NOT EXISTS idx_messages_chatId_parentId ON messages(chatId, parentId);\n\n-- Branches table (pointers to head messages)\nCREATE TABLE IF NOT EXISTS branches (\n id TEXT PRIMARY KEY,\n chatId TEXT NOT NULL,\n name TEXT NOT NULL,\n headMessageId TEXT,\n isActive INTEGER NOT NULL DEFAULT 0,\n createdAt INTEGER NOT NULL,\n FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,\n FOREIGN KEY (headMessageId) REFERENCES messages(id),\n UNIQUE(chatId, name)\n);\n\nCREATE INDEX IF NOT EXISTS idx_branches_chatId ON branches(chatId);\n-- Composite index for getActiveBranch(): WHERE chatId = ? AND isActive = 1\nCREATE INDEX IF NOT EXISTS idx_branches_chatId_isActive ON branches(chatId, isActive);\n\n-- Checkpoints table (pointers to message nodes)\nCREATE TABLE IF NOT EXISTS checkpoints (\n id TEXT PRIMARY KEY,\n chatId TEXT NOT NULL,\n name TEXT NOT NULL,\n messageId TEXT NOT NULL,\n createdAt INTEGER NOT NULL,\n FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,\n FOREIGN KEY (messageId) REFERENCES messages(id),\n UNIQUE(chatId, name)\n);\n\nCREATE INDEX IF NOT EXISTS idx_checkpoints_chatId ON checkpoints(chatId);\n\n-- FTS5 virtual table for full-text search\n-- messageId/chatId/name are UNINDEXED (stored but not searchable, used for filtering/joining)\n-- Only 'content' is indexed for full-text search\nCREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(\n messageId UNINDEXED,\n chatId UNINDEXED,\n name UNINDEXED,\n content,\n tokenize='porter unicode61'\n);\n";
3316
+ // packages/context/src/lib/store/ddl.sqlite.ts
3317
+ var SETUP = `
3318
+ PRAGMA journal_mode = WAL;
3319
+ PRAGMA synchronous = NORMAL;
3320
+ PRAGMA cache_size = -64000;
3321
+ PRAGMA temp_store = MEMORY;
3322
+ PRAGMA mmap_size = 268435456;
3323
+ PRAGMA busy_timeout = 5000;
3324
+ `;
3325
+ var statements = [
3326
+ // createdAt/updatedAt: DEFAULT for insert, inline SET for updates
3327
+ `CREATE TABLE chats (
3328
+ id TEXT PRIMARY KEY,
3329
+ userId TEXT NOT NULL,
3330
+ title TEXT,
3331
+ metadata TEXT,
3332
+ createdAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000),
3333
+ updatedAt INTEGER NOT NULL DEFAULT (strftime('%s', 'now') * 1000)
3334
+ )`,
3335
+ `CREATE INDEX idx_chats_updatedAt ON chats(updatedAt)`,
3336
+ `CREATE INDEX idx_chats_userId ON chats(userId)`,
3337
+ // Composite index for listChats(): WHERE userId = ? ORDER BY updatedAt DESC
3338
+ `CREATE INDEX idx_chats_userId_updatedAt ON chats(userId, updatedAt DESC)`,
3339
+ // Messages are the nodes of the DAG
3340
+ `CREATE TABLE messages (
3341
+ id TEXT PRIMARY KEY,
3342
+ chatId TEXT NOT NULL,
3343
+ parentId TEXT,
3344
+ name TEXT NOT NULL,
3345
+ type TEXT,
3346
+ data TEXT NOT NULL,
3347
+ createdAt INTEGER NOT NULL,
3348
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
3349
+ FOREIGN KEY (parentId) REFERENCES messages(id)
3350
+ )`,
3351
+ `CREATE INDEX idx_messages_chatId ON messages(chatId)`,
3352
+ `CREATE INDEX idx_messages_parentId ON messages(parentId)`,
3353
+ // Composite index for recursive CTE parent traversal in getMessageChain()
3354
+ `CREATE INDEX idx_messages_chatId_parentId ON messages(chatId, parentId)`,
3355
+ // Branches point to head messages
3356
+ `CREATE TABLE branches (
3357
+ id TEXT PRIMARY KEY,
3358
+ chatId TEXT NOT NULL,
3359
+ name TEXT NOT NULL,
3360
+ headMessageId TEXT,
3361
+ isActive INTEGER NOT NULL DEFAULT 0,
3362
+ createdAt INTEGER NOT NULL,
3363
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
3364
+ FOREIGN KEY (headMessageId) REFERENCES messages(id),
3365
+ UNIQUE(chatId, name)
3366
+ )`,
3367
+ `CREATE INDEX idx_branches_chatId ON branches(chatId)`,
3368
+ // Composite index for getActiveBranch(): WHERE chatId = ? AND isActive = 1
3369
+ `CREATE INDEX idx_branches_chatId_isActive ON branches(chatId, isActive)`,
3370
+ // Deleting a message checks this foreign key; without the index the check
3371
+ // scans every chat's branches
3372
+ `CREATE INDEX idx_branches_headMessageId ON branches(headMessageId)`,
3373
+ // Checkpoints point to message nodes
3374
+ `CREATE TABLE checkpoints (
3375
+ id TEXT PRIMARY KEY,
3376
+ chatId TEXT NOT NULL,
3377
+ name TEXT NOT NULL,
3378
+ messageId TEXT NOT NULL,
3379
+ createdAt INTEGER NOT NULL,
3380
+ FOREIGN KEY (chatId) REFERENCES chats(id) ON DELETE CASCADE,
3381
+ FOREIGN KEY (messageId) REFERENCES messages(id),
3382
+ UNIQUE(chatId, name)
3383
+ )`,
3384
+ `CREATE INDEX idx_checkpoints_chatId ON checkpoints(chatId)`,
3385
+ // Deleting a message checks this foreign key; without the index the check
3386
+ // scans every chat's checkpoints
3387
+ `CREATE INDEX idx_checkpoints_messageId ON checkpoints(messageId)`
3388
+ ];
3389
+ var searchStatements = [
3390
+ `CREATE VIRTUAL TABLE messages_fts USING fts5(
3391
+ messageId UNINDEXED,
3392
+ chatId UNINDEXED,
3393
+ name UNINDEXED,
3394
+ content,
3395
+ tokenize='porter unicode61'
3396
+ )`
3397
+ ];
3321
3398
 
3322
3399
  // packages/context/src/lib/store/store.ts
3323
3400
  var ContextStore = class {
@@ -3336,6 +3413,8 @@ var ContextStore = class {
3336
3413
  };
3337
3414
 
3338
3415
  // packages/context/src/lib/store/sqlite.store.ts
3416
+ var tables = new Declaration(statements, { rows: "keep" });
3417
+ var search = new Declaration(searchStatements, { rows: "replace" });
3339
3418
  var chatColumns = z4.object({
3340
3419
  id: z4.string(),
3341
3420
  userId: z4.string(),
@@ -3471,7 +3550,9 @@ var SqliteContextStore = class extends ContextStore {
3471
3550
  constructor(pathOrDb) {
3472
3551
  super();
3473
3552
  this.#db = typeof pathOrDb === "string" ? new DatabaseSync(pathOrDb) : pathOrDb;
3474
- this.#db.exec(ddl_sqlite_default);
3553
+ this.#db.exec(SETUP);
3554
+ tables.apply(this.#db);
3555
+ search.apply(this.#db);
3475
3556
  this.#sql = this.#db.createTagStore();
3476
3557
  }
3477
3558
  // ==========================================================================
@@ -5825,7 +5906,7 @@ function sanitizeAbortedParts(parts) {
5825
5906
  return sanitized;
5826
5907
  }
5827
5908
  function formatChatError(error) {
5828
- if (NoSuchToolError2.isInstance(error)) {
5909
+ if (NoSuchToolError.isInstance(error)) {
5829
5910
  return "The model tried to call an unknown tool.";
5830
5911
  }
5831
5912
  if (InvalidToolInputError.isInstance(error)) {
@@ -6964,7 +7045,7 @@ function review2(options) {
6964
7045
  var socraticPlan = { path: PLAN_FILE_PATH, instructions: instructions2, review: review2 };
6965
7046
 
6966
7047
  // packages/context/src/lib/guardrails/error-recovery.guardrail.ts
6967
- import chalk3 from "chalk";
7048
+ import chalk2 from "chalk";
6968
7049
  var errorRecoveryGuardrail = {
6969
7050
  id: "error-recovery",
6970
7051
  name: "API Error Recovery",
@@ -6973,16 +7054,16 @@ var errorRecoveryGuardrail = {
6973
7054
  return pass(part);
6974
7055
  }
6975
7056
  const errorText = part.errorText || "";
6976
- const prefix = chalk3.bold.magenta("[ErrorRecovery]");
7057
+ const prefix = chalk2.bold.magenta("[ErrorRecovery]");
6977
7058
  console.log(
6978
- `${prefix} ${chalk3.red("Caught error:")} ${chalk3.dim(errorText.slice(0, 150))}`
7059
+ `${prefix} ${chalk2.red("Caught error:")} ${chalk2.dim(errorText.slice(0, 150))}`
6979
7060
  );
6980
7061
  const logAndFail = (pattern, feedback) => {
6981
7062
  console.log(
6982
- `${prefix} ${chalk3.yellow("Pattern:")} ${chalk3.cyan(pattern)}`
7063
+ `${prefix} ${chalk2.yellow("Pattern:")} ${chalk2.cyan(pattern)}`
6983
7064
  );
6984
7065
  console.log(
6985
- `${prefix} ${chalk3.green("Feedback:")} ${chalk3.dim(feedback.slice(0, 80))}...`
7066
+ `${prefix} ${chalk2.green("Feedback:")} ${chalk2.dim(feedback.slice(0, 80))}...`
6986
7067
  );
6987
7068
  return fail(feedback);
6988
7069
  };
@@ -7055,7 +7136,7 @@ var errorRecoveryGuardrail = {
7055
7136
  );
7056
7137
  }
7057
7138
  console.log(
7058
- `${prefix} ${chalk3.yellow("Unknown error - stopping without retry")}`
7139
+ `${prefix} ${chalk2.yellow("Unknown error - stopping without retry")}`
7059
7140
  );
7060
7141
  return stop(part);
7061
7142
  }
@@ -7071,6 +7152,9 @@ function render(tag, ...fragments) {
7071
7152
  return renderer.render([wrapped]);
7072
7153
  }
7073
7154
 
7155
+ // packages/context/src/index.ts
7156
+ import { createRepairToolCall as createRepairToolCall2 } from "@deepagents/agent";
7157
+
7074
7158
  // packages/context/src/lib/sandbox/apple-container-sandbox.ts
7075
7159
  import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
7076
7160
  import { spawn as childSpawn2 } from "node:child_process";
@@ -9393,11 +9477,19 @@ var dockerEngine = {
9393
9477
  cli: "docker",
9394
9478
  bindMountsOnClient: false,
9395
9479
  isMissingBindSource(message2, source) {
9396
- const marker = `bind source path does not exist: ${source}`;
9397
- const index = message2.indexOf(marker);
9398
- if (index < 0) return false;
9399
- const remainder = message2.slice(index + marker.length);
9400
- return remainder === "" || remainder.startsWith("\n") || remainder.startsWith("\r\n");
9480
+ const canonicalSource = source.replace(
9481
+ /^\/(tmp|var|etc)(?=\/|$)/,
9482
+ "/private/$1"
9483
+ );
9484
+ return [source, `/host_mnt${source}`, `/host_mnt${canonicalSource}`].some(
9485
+ (candidate) => {
9486
+ const marker = `bind source path does not exist: ${candidate}`;
9487
+ const index = message2.indexOf(marker);
9488
+ if (index < 0) return false;
9489
+ const remainder = message2.slice(index + marker.length);
9490
+ return remainder === "" || remainder.startsWith("\n") || remainder.startsWith("\r\n");
9491
+ }
9492
+ );
9401
9493
  },
9402
9494
  runArgs(image, containerId, opts, workdir) {
9403
9495
  const {
@@ -11265,6 +11357,7 @@ CREATE TABLE IF NOT EXISTS "${schema}"."branches" (
11265
11357
  );
11266
11358
 
11267
11359
  CREATE INDEX IF NOT EXISTS "idx_${schema}_branches_chatId" ON "${schema}"."branches"(chatId);
11360
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_branches_headMessageId" ON "${schema}"."branches"(headMessageId);
11268
11361
 
11269
11362
  CREATE TABLE IF NOT EXISTS "${schema}"."checkpoints" (
11270
11363
  id TEXT PRIMARY KEY,
@@ -11278,6 +11371,7 @@ CREATE TABLE IF NOT EXISTS "${schema}"."checkpoints" (
11278
11371
  );
11279
11372
 
11280
11373
  CREATE INDEX IF NOT EXISTS "idx_${schema}_checkpoints_chatId" ON "${schema}"."checkpoints"(chatId);
11374
+ CREATE INDEX IF NOT EXISTS "idx_${schema}_checkpoints_messageId" ON "${schema}"."checkpoints"(messageId);
11281
11375
 
11282
11376
  CREATE TABLE IF NOT EXISTS "${schema}"."messages_fts" (
11283
11377
  messageId TEXT PRIMARY KEY REFERENCES "${schema}"."messages"(id) ON DELETE CASCADE,
@@ -12886,6 +12980,28 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12886
12980
  }
12887
12981
  };
12888
12982
 
12983
+ // packages/context/src/lib/stream/stream-store.ts
12984
+ function collectStreamFailures(chunks) {
12985
+ const failures = /* @__PURE__ */ new Map();
12986
+ for (const chunk of chunks) {
12987
+ if (failures.has(chunk.streamId)) continue;
12988
+ if (chunk.data.type === "error") {
12989
+ failures.set(chunk.streamId, chunk.data.errorText);
12990
+ } else if (chunk.data.type === "finish" && chunk.data.finishReason === "interrupted") {
12991
+ failures.set(
12992
+ chunk.streamId,
12993
+ "Model stream interrupted before completion."
12994
+ );
12995
+ }
12996
+ }
12997
+ return [...failures].map(([streamId, error]) => ({ streamId, error }));
12998
+ }
12999
+ var StreamStore = class {
13000
+ async listRunningStreamIds() {
13001
+ return this.listStreamIds({ status: "running" });
13002
+ }
13003
+ };
13004
+
12889
13005
  // packages/context/src/lib/stream-buffer.ts
12890
13006
  async function persistedWriter(options) {
12891
13007
  const {
@@ -12897,7 +13013,7 @@ async function persistedWriter(options) {
12897
13013
  } = options;
12898
13014
  let seq = 0;
12899
13015
  let buffer = [];
12900
- let failedByErrorChunk = false;
13016
+ let failedByChunk = false;
12901
13017
  let abortedByChunk = false;
12902
13018
  async function flush() {
12903
13019
  if (buffer.length === 0) return;
@@ -12913,15 +13029,9 @@ async function persistedWriter(options) {
12913
13029
  createdAt: Date.now()
12914
13030
  };
12915
13031
  }
12916
- function isStreamErrorPart(part) {
12917
- return part.type === "error";
12918
- }
12919
13032
  async function appendBatch(batch) {
12920
- const hasErrorPart = !failedByErrorChunk && batch.map((chunk) => chunk.data).some(isStreamErrorPart);
12921
13033
  await store.appendChunks(batch);
12922
- if (hasErrorPart) {
12923
- failedByErrorChunk = true;
12924
- }
13034
+ failedByChunk ||= collectStreamFailures(batch).length > 0;
12925
13035
  }
12926
13036
  async function persistChunk(chunk) {
12927
13037
  if (chunk.data.type === "abort") {
@@ -12958,7 +13068,7 @@ async function persistedWriter(options) {
12958
13068
  flush,
12959
13069
  async complete() {
12960
13070
  await flush();
12961
- if (failedByErrorChunk) return;
13071
+ if (failedByChunk) return;
12962
13072
  await store.updateStreamStatus(
12963
13073
  streamId,
12964
13074
  abortedByChunk ? "cancelled" : "completed"
@@ -12966,7 +13076,7 @@ async function persistedWriter(options) {
12966
13076
  },
12967
13077
  async fail(error) {
12968
13078
  await flush();
12969
- if (failedByErrorChunk) return;
13079
+ if (failedByChunk) return;
12970
13080
  await store.updateStreamStatus(streamId, "failed", { error });
12971
13081
  },
12972
13082
  async cleanup() {
@@ -13508,22 +13618,6 @@ function toStreamPart(value) {
13508
13618
  return validateTypes({ value, schema: uiMessageChunkSchema });
13509
13619
  }
13510
13620
 
13511
- // packages/context/src/lib/stream/stream-store.ts
13512
- function collectStreamFailures(chunks) {
13513
- const failures = /* @__PURE__ */ new Map();
13514
- for (const chunk of chunks) {
13515
- if (chunk.data.type === "error" && !failures.has(chunk.streamId)) {
13516
- failures.set(chunk.streamId, chunk.data.errorText);
13517
- }
13518
- }
13519
- return [...failures].map(([streamId, error]) => ({ streamId, error }));
13520
- }
13521
- var StreamStore = class {
13522
- async listRunningStreamIds() {
13523
- return this.listStreamIds({ status: "running" });
13524
- }
13525
- };
13526
-
13527
13621
  // packages/context/src/lib/stream/postgres.stream-store.ts
13528
13622
  var storedStream = z18.object({
13529
13623
  id: z18.string(),
@@ -13888,16 +13982,48 @@ function assertIdentifier2(value, label) {
13888
13982
  }
13889
13983
 
13890
13984
  // packages/context/src/lib/stream/sqlite.stream-store.ts
13985
+ import { Declaration as Declaration2 } from "@zukhruf/sqlite-drift";
13891
13986
  import { transaction as transaction2 } from "@zukhruf/sqlite-transaction";
13892
13987
  import {
13893
13988
  DatabaseSync as DatabaseSync2
13894
13989
  } from "node:sqlite";
13895
13990
  import { z as z19 } from "zod";
13896
13991
 
13897
- // packages/context/src/lib/stream/ddl.stream.sqlite.sql
13898
- var ddl_stream_sqlite_default = "PRAGMA busy_timeout = 5000;\nPRAGMA journal_mode = WAL;\nPRAGMA synchronous = NORMAL;\nPRAGMA foreign_keys = ON;\n\nCREATE TABLE IF NOT EXISTS streams (\n id TEXT PRIMARY KEY,\n status TEXT NOT NULL DEFAULT 'queued'\n CHECK(status IN ('queued','running','completed','failed','cancelled')),\n createdAt INTEGER NOT NULL,\n startedAt INTEGER,\n finishedAt INTEGER,\n cancelRequestedAt INTEGER,\n error TEXT\n);\n\nCREATE TABLE IF NOT EXISTS stream_chunks (\n streamId TEXT NOT NULL,\n seq INTEGER NOT NULL,\n data TEXT NOT NULL,\n createdAt INTEGER NOT NULL,\n PRIMARY KEY (streamId, seq),\n FOREIGN KEY (streamId) REFERENCES streams(id) ON DELETE CASCADE\n);\n\n-- Supports ordered listing across all streams.\nCREATE INDEX IF NOT EXISTS idx_streams_created_at_id\n ON streams(createdAt, id);\n\n-- Supports status-filtered ordered listing (e.g. running streams).\nCREATE INDEX IF NOT EXISTS idx_streams_status_created_at_id\n ON streams(status, createdAt, id);\n";
13992
+ // packages/context/src/lib/stream/ddl.stream.sqlite.ts
13993
+ var SETUP2 = `
13994
+ PRAGMA busy_timeout = 5000;
13995
+ PRAGMA journal_mode = WAL;
13996
+ PRAGMA synchronous = NORMAL;
13997
+ `;
13998
+ var statements2 = [
13999
+ `CREATE TABLE streams (
14000
+ id TEXT PRIMARY KEY,
14001
+ status TEXT NOT NULL DEFAULT 'queued'
14002
+ CHECK(status IN ('queued','running','completed','failed','cancelled')),
14003
+ createdAt INTEGER NOT NULL,
14004
+ startedAt INTEGER,
14005
+ finishedAt INTEGER,
14006
+ cancelRequestedAt INTEGER,
14007
+ error TEXT
14008
+ )`,
14009
+ `CREATE TABLE stream_chunks (
14010
+ streamId TEXT NOT NULL,
14011
+ seq INTEGER NOT NULL,
14012
+ data TEXT NOT NULL,
14013
+ createdAt INTEGER NOT NULL,
14014
+ PRIMARY KEY (streamId, seq),
14015
+ FOREIGN KEY (streamId) REFERENCES streams(id) ON DELETE CASCADE
14016
+ )`,
14017
+ // Supports ordered listing across all streams.
14018
+ `CREATE INDEX idx_streams_created_at_id
14019
+ ON streams(createdAt, id)`,
14020
+ // Supports status-filtered ordered listing (e.g. running streams).
14021
+ `CREATE INDEX idx_streams_status_created_at_id
14022
+ ON streams(status, createdAt, id)`
14023
+ ];
13899
14024
 
13900
14025
  // packages/context/src/lib/stream/sqlite.stream-store.ts
14026
+ var tables2 = new Declaration2(statements2, { rows: "keep" });
13901
14027
  var streamRow = z19.object({
13902
14028
  id: z19.string(),
13903
14029
  status: streamStatus,
@@ -13925,7 +14051,8 @@ var SqliteStreamStore = class extends StreamStore {
13925
14051
  constructor(pathOrDb) {
13926
14052
  super();
13927
14053
  this.#db = typeof pathOrDb === "string" ? new DatabaseSync2(pathOrDb) : pathOrDb;
13928
- this.#db.exec(ddl_stream_sqlite_default);
14054
+ this.#db.exec(SETUP2);
14055
+ tables2.apply(this.#db);
13929
14056
  this.#sql = this.#db.createTagStore();
13930
14057
  }
13931
14058
  async createStream(stream) {
@@ -14625,7 +14752,7 @@ export {
14625
14752
  createDockerSandbox,
14626
14753
  createInstallerContext,
14627
14754
  createMicrosandboxSandbox,
14628
- createRepairToolCall,
14755
+ createRepairToolCall2 as createRepairToolCall,
14629
14756
  createVirtualSandbox,
14630
14757
  dateReminder,
14631
14758
  dayChanged,