@deepagents/context 7.3.0 → 7.5.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.
Files changed (32) hide show
  1. package/dist/browser.js +1 -1
  2. package/dist/browser.js.map +2 -2
  3. package/dist/index.js +341 -348
  4. package/dist/index.js.map +3 -3
  5. package/dist/lib/agent.d.ts +15 -4
  6. package/dist/lib/agent.d.ts.map +1 -1
  7. package/dist/lib/chat.d.ts +4 -2
  8. package/dist/lib/chat.d.ts.map +1 -1
  9. package/dist/lib/engine.d.ts.map +1 -1
  10. package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -1
  11. package/dist/lib/sandbox/daytona-sandbox.d.ts.map +1 -1
  12. package/dist/lib/sandbox/docker-sandbox.d.ts +0 -1
  13. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
  14. package/dist/lib/sandbox/subcommand.d.ts.map +1 -1
  15. package/dist/lib/store/ddl.sqlite.d.ts +1 -1
  16. package/dist/lib/store/ddl.sqlite.d.ts.map +1 -1
  17. package/dist/lib/store/sqlite.store.d.ts +1 -1
  18. package/dist/lib/store/sqlite.store.d.ts.map +1 -1
  19. package/dist/lib/stream/ddl.stream.sqlite.d.ts +1 -1
  20. package/dist/lib/stream/ddl.stream.sqlite.d.ts.map +1 -1
  21. package/dist/lib/stream/sqlite.stream-store.d.ts +1 -1
  22. package/dist/lib/stream/sqlite.stream-store.d.ts.map +1 -1
  23. package/dist/lib/telemetry/create-telemetry-integration.d.ts.map +1 -1
  24. package/dist/lib/telemetry/file/index.js +1 -7
  25. package/dist/lib/telemetry/file/index.js.map +2 -2
  26. package/dist/lib/telemetry/index.js +1 -7
  27. package/dist/lib/telemetry/index.js.map +2 -2
  28. package/dist/lib/telemetry/redact-telemetry-event.d.ts.map +1 -1
  29. package/dist/lib/tracing/exporter.d.ts.map +1 -1
  30. package/dist/lib/tracing/index.js +2 -1
  31. package/dist/lib/tracing/index.js.map +2 -2
  32. package/package.json +7 -7
package/dist/index.js CHANGED
@@ -152,9 +152,10 @@ import {
152
152
  isStepCount,
153
153
  smoothStream,
154
154
  streamText,
155
+ toUIMessageStream,
155
156
  tool
156
157
  } from "ai";
157
- import chalk from "chalk";
158
+ import { styleText } from "node:util";
158
159
  import z from "zod";
159
160
  import {
160
161
  createRepairToolCall,
@@ -397,8 +398,8 @@ var Agent = class _Agent {
397
398
  /**
398
399
  * Stream a response from the agent.
399
400
  *
400
- * When guardrails are configured, `toUIMessageStream()` is wrapped to provide
401
- * self-correction behavior. Direct access to fullStream/textStream bypasses guardrails.
401
+ * When guardrails are configured, `toUIMessageStream()` provides
402
+ * self-correction behavior. Direct access to `result.stream` bypasses guardrails.
402
403
  *
403
404
  * @example
404
405
  * ```typescript
@@ -427,14 +428,24 @@ var Agent = class _Agent {
427
428
  prepareStep
428
429
  );
429
430
  if (this.#guardrails.length === 0) {
430
- return result;
431
+ return {
432
+ result,
433
+ toUIMessageStream: (uiOptions) => toUIMessageStream({
434
+ stream: result.stream,
435
+ tools: this.tools,
436
+ ...uiOptions
437
+ })
438
+ };
431
439
  }
432
- return this.#wrapWithGuardrails(
440
+ return {
433
441
  result,
434
- options?.toolsContext,
435
- options,
436
- prepareStep
437
- );
442
+ toUIMessageStream: this.#guardedUIMessageStream(
443
+ result,
444
+ options?.toolsContext,
445
+ options,
446
+ prepareStep
447
+ )
448
+ };
438
449
  }
439
450
  #withPrepareStep(prepareContext) {
440
451
  const prepareStep = this.#options.prepareStep;
@@ -498,21 +509,20 @@ var Agent = class _Agent {
498
509
  });
499
510
  }
500
511
  /**
501
- * Wrap a StreamTextResult with guardrail protection on toUIMessageStream().
512
+ * Build a UI message stream with guardrail protection.
502
513
  *
503
514
  * When a guardrail fails:
504
515
  * 1. The feedback is written to the output stream (user sees the correction)
505
516
  * 2. A finish-step is emitted, triggering onStepEnd to persist the self-correction
506
517
  * 3. A new stream is started and the model continues from the correction
507
518
  */
508
- #wrapWithGuardrails(result, toolsContext, config, prepareStep) {
519
+ #guardedUIMessageStream(result, toolsContext, config, prepareStep) {
509
520
  const maxRetries = config?.maxRetries ?? this.#options.maxGuardrailRetries ?? 3;
510
521
  const context = this.#options.context;
511
522
  if (!context) {
512
523
  throw new Error(`Agent ${this.#options.name} is missing a context.`);
513
524
  }
514
- const originalToUIMessageStream = result.toUIMessageStream.bind(result);
515
- result.toUIMessageStream = (options) => {
525
+ return (options) => {
516
526
  const assistantMsgId = options?.generateMessageId?.();
517
527
  let stepSaved = null;
518
528
  return createUIMessageStream({
@@ -546,7 +556,11 @@ var Agent = class _Agent {
546
556
  let guardrailFailed = false;
547
557
  let failureFeedback = "";
548
558
  let openTextId;
549
- const uiStream = currentResult === result ? originalToUIMessageStream(options) : currentResult.toUIMessageStream(options);
559
+ const uiStream = toUIMessageStream({
560
+ stream: currentResult.stream,
561
+ tools: this.tools,
562
+ ...options
563
+ });
550
564
  for await (const part of uiStream) {
551
565
  if (part.type === "text-start") openTextId = chunkId(part);
552
566
  if (part.type === "text-end") openTextId = void 0;
@@ -559,7 +573,8 @@ var Agent = class _Agent {
559
573
  guardrailFailed = true;
560
574
  failureFeedback = checkResult.feedback;
561
575
  console.log(
562
- chalk.yellow(
576
+ styleText(
577
+ "yellow",
563
578
  `[${this.#options.name}] Guardrail triggered (attempt ${attempt}/${maxRetries}): ${failureFeedback.slice(0, 50)}...`
564
579
  )
565
580
  );
@@ -567,7 +582,8 @@ var Agent = class _Agent {
567
582
  }
568
583
  if (checkResult.type === "stop") {
569
584
  console.log(
570
- chalk.red(
585
+ styleText(
586
+ "red",
571
587
  `[${this.#options.name}] Guardrail stopped - unrecoverable error, no retry`
572
588
  )
573
589
  );
@@ -583,7 +599,8 @@ var Agent = class _Agent {
583
599
  }
584
600
  if (attempt >= maxRetries) {
585
601
  console.error(
586
- chalk.red(
602
+ styleText(
603
+ "red",
587
604
  `[${this.#options.name}] Guardrail retry limit (${maxRetries}) exceeded.`
588
605
  )
589
606
  );
@@ -607,7 +624,6 @@ var Agent = class _Agent {
607
624
  }
608
625
  });
609
626
  };
610
- return result;
611
627
  }
612
628
  asTool(props) {
613
629
  return {
@@ -765,7 +781,7 @@ function structuredOutput(options) {
765
781
  ignoreIncompleteToolCalls: true,
766
782
  tools
767
783
  }),
768
- stopWhen: DEFAULT_STOP_WHEN,
784
+ stopWhen: options.stopWhen ?? DEFAULT_STOP_WHEN,
769
785
  repairToolCall: createRepairToolCall(
770
786
  options.model,
771
787
  callOptions?.abortSignal
@@ -807,7 +823,7 @@ function structuredOutput(options) {
807
823
  ignoreIncompleteToolCalls: true,
808
824
  tools
809
825
  }),
810
- stopWhen: DEFAULT_STOP_WHEN,
826
+ stopWhen: options.stopWhen ?? DEFAULT_STOP_WHEN,
811
827
  experimental_transform: callOptions?.transform ?? smoothStream(),
812
828
  toolsContext: callOptions?.toolsContext,
813
829
  output: Output.object({ schema: options.schema }),
@@ -1566,7 +1582,7 @@ ${entries}`;
1566
1582
  let intersection = new Set(Object.keys(objects[0]));
1567
1583
  for (const obj of objects) {
1568
1584
  const keys = new Set(Object.keys(obj));
1569
- intersection = new Set([...intersection].filter((k) => keys.has(k)));
1585
+ intersection = intersection.intersection(keys);
1570
1586
  for (const value of Object.values(obj)) {
1571
1587
  if (value == null) continue;
1572
1588
  if (!this.#isPrimitiveValue(value)) {
@@ -3274,10 +3290,8 @@ var SavePipeline = class _SavePipeline {
3274
3290
 
3275
3291
  // packages/context/src/lib/store/sqlite.store.ts
3276
3292
  import { Declaration } from "@zukhruf/sqlite-drift";
3293
+ import { open } from "@zukhruf/sqlite-open";
3277
3294
  import { transaction } from "@zukhruf/sqlite-transaction";
3278
- import {
3279
- DatabaseSync
3280
- } from "node:sqlite";
3281
3295
  import { z as z4 } from "zod";
3282
3296
 
3283
3297
  // packages/context/src/lib/store/columns.ts
@@ -3293,12 +3307,10 @@ function parseJsonObject(text) {
3293
3307
 
3294
3308
  // packages/context/src/lib/store/ddl.sqlite.ts
3295
3309
  var SETUP = `
3296
- PRAGMA journal_mode = WAL;
3297
3310
  PRAGMA synchronous = NORMAL;
3298
3311
  PRAGMA cache_size = -64000;
3299
3312
  PRAGMA temp_store = MEMORY;
3300
3313
  PRAGMA mmap_size = 268435456;
3301
- PRAGMA busy_timeout = 5000;
3302
3314
  `;
3303
3315
  var statements = [
3304
3316
  // createdAt/updatedAt: DEFAULT for insert, inline SET for updates
@@ -3527,7 +3539,7 @@ var SqliteContextStore = class extends ContextStore {
3527
3539
  #sql;
3528
3540
  constructor(pathOrDb) {
3529
3541
  super();
3530
- this.#db = typeof pathOrDb === "string" ? new DatabaseSync(pathOrDb) : pathOrDb;
3542
+ this.#db = typeof pathOrDb === "string" ? open(pathOrDb) : pathOrDb;
3531
3543
  this.#db.exec(SETUP);
3532
3544
  tables.apply(this.#db);
3533
3545
  search.apply(this.#db);
@@ -4207,17 +4219,17 @@ var ContextEngine = class _ContextEngine {
4207
4219
  `Active branch not found for chat "${this.#chatId}" after upsertChat`
4208
4220
  );
4209
4221
  }
4210
- const open = new OpenChat(chat2, branch);
4211
- this.#session = open;
4212
- return open;
4222
+ const open3 = new OpenChat(chat2, branch);
4223
+ this.#session = open3;
4224
+ return open3;
4213
4225
  }
4214
4226
  /**
4215
4227
  * Create a new branch from a specific message.
4216
4228
  * Shared logic between rewind() and btw().
4217
4229
  */
4218
- async #createBranchFrom(open, messageId, switchTo) {
4230
+ async #createBranchFrom(open3, messageId, switchTo) {
4219
4231
  const branches = await this.#store.listBranches(this.#chatId);
4220
- const baseName = open.branch.name;
4232
+ const baseName = open3.branch.name;
4221
4233
  const samePrefix = branches.filter(
4222
4234
  (it) => it.name === baseName || it.name.startsWith(`${baseName}-v`)
4223
4235
  );
@@ -4233,7 +4245,7 @@ var ContextEngine = class _ContextEngine {
4233
4245
  await this.#store.createBranch(newBranch);
4234
4246
  if (switchTo) {
4235
4247
  await this.#store.setActiveBranch(this.#chatId, newBranch.id);
4236
- open.branch = { ...newBranch, isActive: true };
4248
+ open3.branch = { ...newBranch, isActive: true };
4237
4249
  this.#pendingMessages = [];
4238
4250
  }
4239
4251
  const chain = await this.#store.getMessageChain(messageId);
@@ -4286,8 +4298,8 @@ var ContextEngine = class _ContextEngine {
4286
4298
  * Includes persisted messages and pending messages in the turn count.
4287
4299
  */
4288
4300
  async #getChainContext(pending = this.#pendingMessages) {
4289
- const open = await this.#open();
4290
- const stored = open.branch.headMessageId ? await this.#store.getMessageChain(open.branch.headMessageId) : [];
4301
+ const open3 = await this.#open();
4302
+ const stored = open3.branch.headMessageId ? await this.#store.getMessageChain(open3.branch.headMessageId) : [];
4291
4303
  return summarizeChain(stored, pending);
4292
4304
  }
4293
4305
  async getTurnCount() {
@@ -4295,10 +4307,10 @@ var ContextEngine = class _ContextEngine {
4295
4307
  return turn;
4296
4308
  }
4297
4309
  async firstUserMessage() {
4298
- const open = await this.#open();
4299
- if (open.branch.headMessageId) {
4310
+ const open3 = await this.#open();
4311
+ if (open3.branch.headMessageId) {
4300
4312
  const chain = await this.#store.getMessageChain(
4301
- open.branch.headMessageId
4313
+ open3.branch.headMessageId
4302
4314
  );
4303
4315
  for (const msg of chain) {
4304
4316
  if (msg.name === "user") {
@@ -4327,7 +4339,7 @@ var ContextEngine = class _ContextEngine {
4327
4339
  * @throws if the pending tail is missing an id (programming error).
4328
4340
  */
4329
4341
  async headMessage() {
4330
- const open = await this.#open();
4342
+ const open3 = await this.#open();
4331
4343
  if (this.#pendingMessages.length > 0) {
4332
4344
  const tail = this.#pendingMessages[this.#pendingMessages.length - 1];
4333
4345
  if (!tail.id) {
@@ -4337,8 +4349,8 @@ var ContextEngine = class _ContextEngine {
4337
4349
  }
4338
4350
  return { id: tail.id, name: tail.name };
4339
4351
  }
4340
- if (open.branch.headMessageId) {
4341
- const msg = await this.#store.getMessage(open.branch.headMessageId);
4352
+ if (open3.branch.headMessageId) {
4353
+ const msg = await this.#store.getMessage(open3.branch.headMessageId);
4342
4354
  if (msg) return { id: msg.id, name: msg.name };
4343
4355
  }
4344
4356
  return void 0;
@@ -4358,12 +4370,12 @@ var ContextEngine = class _ContextEngine {
4358
4370
  * For id-lookup use `headMessage()` instead — that one keeps placeholders.
4359
4371
  */
4360
4372
  async getMessages() {
4361
- const open = await this.#open();
4373
+ const open3 = await this.#open();
4362
4374
  const messages = [];
4363
4375
  const indexById = /* @__PURE__ */ new Map();
4364
- if (open.branch.headMessageId) {
4376
+ if (open3.branch.headMessageId) {
4365
4377
  const chain = await this.#store.getMessageChain(
4366
- open.branch.headMessageId
4378
+ open3.branch.headMessageId
4367
4379
  );
4368
4380
  for (const msg of chain) {
4369
4381
  const data = requireUIMessage(msg.data, `Stored message "${msg.id}"`);
@@ -4499,14 +4511,14 @@ var ContextEngine = class _ContextEngine {
4499
4511
  * ```
4500
4512
  */
4501
4513
  async save(options) {
4502
- const open = await this.#open();
4514
+ const open3 = await this.#open();
4503
4515
  if (this.#pendingMessages.length === 0) {
4504
- return { headMessageId: open.branch.headMessageId ?? void 0 };
4516
+ return { headMessageId: open3.branch.headMessageId ?? void 0 };
4505
4517
  }
4506
4518
  const pending = this.#pendingMessages;
4507
4519
  this.#pendingMessages = [];
4508
4520
  const pipeline = new SavePipeline(
4509
- this.#asSavePipelineEngine(open),
4521
+ this.#asSavePipelineEngine(open3),
4510
4522
  pending,
4511
4523
  options?.branch ?? true
4512
4524
  );
@@ -4519,7 +4531,11 @@ var ContextEngine = class _ContextEngine {
4519
4531
  throw error;
4520
4532
  }
4521
4533
  }
4522
- #currentReminderSession;
4534
+ /**
4535
+ * Writes the streamed assistant message: the whole message to the reserved
4536
+ * head, until createPrepareStep() binds a reminder session's segments.
4537
+ */
4538
+ #writeAssistant = (headId, message2) => this.#writeWholeAssistant(headId, message2);
4523
4539
  /**
4524
4540
  * Build the `prepareStep` hook that injects reminders between model steps.
4525
4541
  * Tool-output reminders are evaluated against the preceding step's completed
@@ -4546,7 +4562,7 @@ var ContextEngine = class _ContextEngine {
4546
4562
  stepOffset: 0,
4547
4563
  lastStepNumber: null
4548
4564
  };
4549
- this.#currentReminderSession = session;
4565
+ this.#writeAssistant = (headId, message2) => this.#writeSessionSegment(session, headId, message2);
4550
4566
  return async ({ steps, stepNumber, messages }) => {
4551
4567
  if (stepNumber === 0 && session.lastStepNumber !== null) {
4552
4568
  session.stepOffset += session.lastStepNumber + 1;
@@ -4671,53 +4687,57 @@ var ContextEngine = class _ContextEngine {
4671
4687
  "writeAssistantSegment: expected an assistant message at chain head."
4672
4688
  );
4673
4689
  }
4674
- const session = this.#currentReminderSession;
4675
- let id = head.id;
4690
+ await this.#writeAssistant(head.id, message2);
4691
+ }
4692
+ async #writeWholeAssistant(headId, message2) {
4693
+ this.set(assistant({ ...message2, id: headId }));
4694
+ await this.save({ branch: false });
4695
+ }
4696
+ async #writeSessionSegment(session, headId, message2) {
4697
+ let id = headId;
4676
4698
  let parts = message2.parts;
4677
- if (session) {
4678
- if (session.initialStepStarts === null) {
4679
- const initialId = session.segments[0]?.id ?? head.id;
4680
- const initial = await this.#store.getMessage(initialId);
4681
- if (!initial || initial.name !== "assistant") {
4682
- throw new Error(
4683
- `writeAssistantSegment: initial segment "${initialId}" was not found`
4684
- );
4685
- }
4686
- session.initialStepStarts = requireUIMessage(
4687
- initial.data,
4688
- `Stored assistant message "${initial.id}"`
4689
- ).parts.filter((part) => part.type === "step-start").length;
4690
- }
4691
- const streamStepStarts = message2.parts.flatMap(
4692
- (part, index) => part.type === "step-start" ? [index] : []
4693
- );
4694
- const completedSteps = streamStepStarts.length - session.initialStepStarts;
4695
- if (completedSteps < 0) {
4699
+ if (session.initialStepStarts === null) {
4700
+ const initialId = session.segments[0]?.id ?? headId;
4701
+ const initial = await this.#store.getMessage(initialId);
4702
+ if (!initial || initial.name !== "assistant") {
4696
4703
  throw new Error(
4697
- "writeAssistantSegment: response lost an existing step boundary"
4704
+ `writeAssistantSegment: initial segment "${initialId}" was not found`
4698
4705
  );
4699
4706
  }
4700
- const segmentIndex = session.segments.findLastIndex(
4701
- (candidate) => candidate.startStep < completedSteps
4707
+ session.initialStepStarts = requireUIMessage(
4708
+ initial.data,
4709
+ `Stored assistant message "${initial.id}"`
4710
+ ).parts.filter((part) => part.type === "step-start").length;
4711
+ }
4712
+ const streamStepStarts = message2.parts.flatMap(
4713
+ (part, index) => part.type === "step-start" ? [index] : []
4714
+ );
4715
+ const completedSteps = streamStepStarts.length - session.initialStepStarts;
4716
+ if (completedSteps < 0) {
4717
+ throw new Error(
4718
+ "writeAssistantSegment: response lost an existing step boundary"
4702
4719
  );
4703
- if (segmentIndex >= 0) {
4704
- const segment = session.segments[segmentIndex];
4705
- id = segment.id;
4706
- if (segmentIndex > 0) {
4707
- const start = streamStepStarts[session.initialStepStarts + segment.startStep];
4708
- if (start === void 0) {
4709
- throw new Error(
4710
- `writeAssistantSegment: response is missing step ${segment.startStep + 1}`
4711
- );
4712
- }
4713
- parts = message2.parts.slice(start);
4714
- }
4715
- } else {
4716
- const lastSegment = session.segments.at(-1);
4717
- if (lastSegment) {
4718
- id = lastSegment.id;
4719
- parts = [];
4720
+ }
4721
+ const segmentIndex = session.segments.findLastIndex(
4722
+ (candidate) => candidate.startStep < completedSteps
4723
+ );
4724
+ if (segmentIndex >= 0) {
4725
+ const segment = session.segments[segmentIndex];
4726
+ id = segment.id;
4727
+ if (segmentIndex > 0) {
4728
+ const start = streamStepStarts[session.initialStepStarts + segment.startStep];
4729
+ if (start === void 0) {
4730
+ throw new Error(
4731
+ `writeAssistantSegment: response is missing step ${segment.startStep + 1}`
4732
+ );
4720
4733
  }
4734
+ parts = message2.parts.slice(start);
4735
+ }
4736
+ } else {
4737
+ const lastSegment = session.segments.at(-1);
4738
+ if (lastSegment) {
4739
+ id = lastSegment.id;
4740
+ parts = [];
4721
4741
  }
4722
4742
  }
4723
4743
  const fragment2 = assistant({
@@ -4725,11 +4745,6 @@ var ContextEngine = class _ContextEngine {
4725
4745
  id,
4726
4746
  parts
4727
4747
  });
4728
- if (!session) {
4729
- this.set(fragment2);
4730
- await this.save({ branch: false });
4731
- return;
4732
- }
4733
4748
  const stored = await this.#store.getMessage(id);
4734
4749
  if (!stored) {
4735
4750
  throw new Error(
@@ -4859,7 +4874,7 @@ var ContextEngine = class _ContextEngine {
4859
4874
  session.terminalToolParts
4860
4875
  ),
4861
4876
  sandbox,
4862
- firedOnceIds: /* @__PURE__ */ new Set([...chain.firedOnceIds, ...session.firedOnceIds])
4877
+ firedOnceIds: chain.firedOnceIds.union(session.firedOnceIds)
4863
4878
  };
4864
4879
  }
4865
4880
  async #evaluateToolOutputReminders(outcomes, session, chain, sandbox) {
@@ -4875,10 +4890,7 @@ var ContextEngine = class _ContextEngine {
4875
4890
  const whenCtx = this.#buildWhenCtx(chain, currentMessage);
4876
4891
  whenCtx.sandbox = sandbox;
4877
4892
  whenCtx.toolOutcome = outcome;
4878
- whenCtx.firedOnceIds = /* @__PURE__ */ new Set([
4879
- ...chain.firedOnceIds,
4880
- ...session.firedOnceIds
4881
- ]);
4893
+ whenCtx.firedOnceIds = chain.firedOnceIds.union(session.firedOnceIds);
4882
4894
  const matched = await evaluateFiredReminders(configs, whenCtx);
4883
4895
  texts.push(...matched.map((item) => item.resolved.text));
4884
4896
  for (const id of matched.flatMap((item) => item.onceIds)) {
@@ -4888,36 +4900,36 @@ var ContextEngine = class _ContextEngine {
4888
4900
  }
4889
4901
  return { texts, onceIds: [...onceIds] };
4890
4902
  }
4891
- #asSavePipelineEngine(open) {
4903
+ #asSavePipelineEngine(open3) {
4892
4904
  return {
4893
4905
  store: this.#store,
4894
4906
  chatId: this.#chatId,
4895
4907
  getActiveBranch: () => ({
4896
- id: open.branch.id,
4897
- headMessageId: open.branch.headMessageId
4908
+ id: open3.branch.id,
4909
+ headMessageId: open3.branch.headMessageId
4898
4910
  }),
4899
4911
  commitHead: async (headMessageId, expectedHeadMessageId) => {
4900
4912
  const committed = await this.#store.updateBranchHead(
4901
- open.branch.id,
4913
+ open3.branch.id,
4902
4914
  headMessageId,
4903
4915
  expectedHeadMessageId
4904
4916
  );
4905
4917
  if (committed) {
4906
- open.branch.headMessageId = headMessageId;
4918
+ open3.branch.headMessageId = headMessageId;
4907
4919
  }
4908
4920
  return committed;
4909
4921
  },
4910
4922
  refreshBranch: async () => {
4911
4923
  const fresh = await this.#store.getBranch(
4912
4924
  this.#chatId,
4913
- open.branch.name
4925
+ open3.branch.name
4914
4926
  );
4915
4927
  if (!fresh) {
4916
4928
  throw new Error(
4917
- `Branch "${open.branch.name}" not found for chat "${this.#chatId}"`
4929
+ `Branch "${open3.branch.name}" not found for chat "${this.#chatId}"`
4918
4930
  );
4919
4931
  }
4920
- open.branch = fresh;
4932
+ open3.branch = fresh;
4921
4933
  return { id: fresh.id, headMessageId: fresh.headMessageId };
4922
4934
  },
4923
4935
  rewindForUpdate: (parentId) => this.#rewindForUpdate(parentId)
@@ -4936,7 +4948,7 @@ var ContextEngine = class _ContextEngine {
4936
4948
  * @returns Estimate result with token counts, costs, and per-fragment breakdown
4937
4949
  */
4938
4950
  async estimate(modelId, options = {}) {
4939
- const open = await this.#open();
4951
+ const open3 = await this.#open();
4940
4952
  await this.#loaderResolver.resolve(this.#fragments, {
4941
4953
  sandbox: options.sandbox,
4942
4954
  context: this,
@@ -4965,9 +4977,9 @@ var ContextEngine = class _ContextEngine {
4965
4977
  cost
4966
4978
  });
4967
4979
  }
4968
- if (open.branch.headMessageId) {
4980
+ if (open3.branch.headMessageId) {
4969
4981
  const chain = await this.#store.getMessageChain(
4970
- open.branch.headMessageId
4982
+ open3.branch.headMessageId
4971
4983
  );
4972
4984
  for (const msg of chain) {
4973
4985
  const content = estimateMessageContent(msg.data);
@@ -5039,7 +5051,7 @@ var ContextEngine = class _ContextEngine {
5039
5051
  * ```
5040
5052
  */
5041
5053
  async rewind(messageId) {
5042
- const open = await this.#open();
5054
+ const open3 = await this.#open();
5043
5055
  const message2 = await this.#store.getMessage(messageId);
5044
5056
  if (!message2) {
5045
5057
  throw new Error(`Message "${messageId}" not found`);
@@ -5047,7 +5059,7 @@ var ContextEngine = class _ContextEngine {
5047
5059
  if (message2.chatId !== this.#chatId) {
5048
5060
  throw new Error(`Message "${messageId}" belongs to a different chat`);
5049
5061
  }
5050
- return this.#createBranchFrom(open, messageId, true);
5062
+ return this.#createBranchFrom(open3, messageId, true);
5051
5063
  }
5052
5064
  /**
5053
5065
  * Create a checkpoint at the current position.
@@ -5069,15 +5081,15 @@ var ContextEngine = class _ContextEngine {
5069
5081
  * ```
5070
5082
  */
5071
5083
  async checkpoint(name) {
5072
- const open = await this.#open();
5073
- if (!open.branch.headMessageId) {
5084
+ const open3 = await this.#open();
5085
+ if (!open3.branch.headMessageId) {
5074
5086
  throw new Error("Cannot create checkpoint: no messages in conversation");
5075
5087
  }
5076
5088
  const checkpoint = {
5077
5089
  id: crypto.randomUUID(),
5078
5090
  chatId: this.#chatId,
5079
5091
  name,
5080
- messageId: open.branch.headMessageId,
5092
+ messageId: open3.branch.headMessageId,
5081
5093
  createdAt: Date.now()
5082
5094
  };
5083
5095
  await this.#store.createCheckpoint(checkpoint);
@@ -5130,13 +5142,13 @@ var ContextEngine = class _ContextEngine {
5130
5142
  * ```
5131
5143
  */
5132
5144
  async switchBranch(name) {
5133
- const open = await this.#open();
5145
+ const open3 = await this.#open();
5134
5146
  const branch = await this.#store.getBranch(this.#chatId, name);
5135
5147
  if (!branch) {
5136
5148
  throw new Error(`Branch "${name}" not found in chat "${this.#chatId}"`);
5137
5149
  }
5138
5150
  await this.#store.setActiveBranch(this.#chatId, branch.id);
5139
- open.branch = { ...branch, isActive: true };
5151
+ open3.branch = { ...branch, isActive: true };
5140
5152
  this.#pendingMessages = [];
5141
5153
  }
5142
5154
  /**
@@ -5171,11 +5183,11 @@ var ContextEngine = class _ContextEngine {
5171
5183
  * ```
5172
5184
  */
5173
5185
  async btw() {
5174
- const open = await this.#open();
5175
- if (!open.branch.headMessageId) {
5186
+ const open3 = await this.#open();
5187
+ if (!open3.branch.headMessageId) {
5176
5188
  throw new Error("Cannot create btw branch: no messages in conversation");
5177
5189
  }
5178
- return this.#createBranchFrom(open, open.branch.headMessageId, false);
5190
+ return this.#createBranchFrom(open3, open3.branch.headMessageId, false);
5179
5191
  }
5180
5192
  /**
5181
5193
  * Update metadata for the current chat.
@@ -5191,8 +5203,8 @@ var ContextEngine = class _ContextEngine {
5191
5203
  * ```
5192
5204
  */
5193
5205
  async updateChat(updates) {
5194
- const open = await this.#open();
5195
- open.chat = await this.#store.updateChat(this.#chatId, ({ metadata }) => ({
5206
+ const open3 = await this.#open();
5207
+ open3.chat = await this.#store.updateChat(this.#chatId, ({ metadata }) => ({
5196
5208
  title: updates.title,
5197
5209
  metadata: updates.metadata === void 0 ? void 0 : { ...metadata, ...updates.metadata }
5198
5210
  }));
@@ -5211,8 +5223,8 @@ var ContextEngine = class _ContextEngine {
5211
5223
  * ```
5212
5224
  */
5213
5225
  async trackUsage(usage) {
5214
- const open = await this.#open();
5215
- open.chat = await this.#store.updateChat(this.#chatId, ({ metadata }) => {
5226
+ const open3 = await this.#open();
5227
+ open3.chat = await this.#store.updateChat(this.#chatId, ({ metadata }) => {
5216
5228
  const storedUsage = metadata?.usage;
5217
5229
  const currentUsage = isLanguageModelUsage(storedUsage) ? storedUsage : void 0;
5218
5230
  return {
@@ -5287,7 +5299,7 @@ var ContextEngine = class _ContextEngine {
5287
5299
  * ```
5288
5300
  */
5289
5301
  async inspect(options) {
5290
- const open = await this.#open();
5302
+ const open3 = await this.#open();
5291
5303
  const { renderer } = options;
5292
5304
  const estimateResult = await this.estimate(options.modelId, {
5293
5305
  renderer,
@@ -5296,9 +5308,9 @@ var ContextEngine = class _ContextEngine {
5296
5308
  });
5297
5309
  const rendered = renderer.render(this.#renderableFragments);
5298
5310
  const persistedMessages = [];
5299
- if (open.branch.headMessageId) {
5311
+ if (open3.branch.headMessageId) {
5300
5312
  const chain = await this.#store.getMessageChain(
5301
- open.branch.headMessageId
5313
+ open3.branch.headMessageId
5302
5314
  );
5303
5315
  persistedMessages.push(...chain);
5304
5316
  }
@@ -5314,7 +5326,7 @@ var ContextEngine = class _ContextEngine {
5314
5326
  graph,
5315
5327
  meta: {
5316
5328
  chatId: this.#chatId,
5317
- branch: open.branch.name,
5329
+ branch: open3.branch.name,
5318
5330
  timestamp: Date.now()
5319
5331
  }
5320
5332
  };
@@ -5812,7 +5824,24 @@ async function chat(agent2, ...args) {
5812
5824
  const settled = isAborted ? {
5813
5825
  ...responseMessage,
5814
5826
  parts: sanitizeAbortedParts(responseMessage.parts)
5815
- } : responseMessage;
5827
+ } : {
5828
+ ...responseMessage,
5829
+ // A provider can end at its token limit midway through arguments.
5830
+ // That call failed; it is not waiting for client input or approval.
5831
+ parts: responseMessage.parts.map((part) => {
5832
+ if (!isToolUIPart(part) || part.state !== "input-streaming")
5833
+ return part;
5834
+ const failed = {
5835
+ ...part,
5836
+ state: "output-error",
5837
+ input: part.input,
5838
+ errorText: "Tool input ended before the call was complete."
5839
+ };
5840
+ delete failed.rawInput;
5841
+ delete failed.inputEncoding;
5842
+ return failed;
5843
+ })
5844
+ };
5816
5845
  const finalMetadata = await options?.finalAssistantMetadata?.(settled);
5817
5846
  const mergedMetadata = {
5818
5847
  ...isRecord(settled.metadata) ? settled.metadata : {},
@@ -5820,7 +5849,7 @@ async function chat(agent2, ...args) {
5820
5849
  };
5821
5850
  const message2 = Object.keys(mergedMetadata).length > 0 ? { ...settled, metadata: mergedMetadata } : settled;
5822
5851
  await context.writeAssistantSegment(message2);
5823
- const usage = await result?.usage;
5852
+ const usage = await result?.result.usage;
5824
5853
  if (usage !== void 0) {
5825
5854
  await context.trackUsage(usage);
5826
5855
  }
@@ -7023,7 +7052,7 @@ function review2(options) {
7023
7052
  var socraticPlan = { path: PLAN_FILE_PATH, instructions: instructions2, review: review2 };
7024
7053
 
7025
7054
  // packages/context/src/lib/guardrails/error-recovery.guardrail.ts
7026
- import chalk2 from "chalk";
7055
+ import { styleText as styleText2 } from "node:util";
7027
7056
  var errorRecoveryGuardrail = {
7028
7057
  id: "error-recovery",
7029
7058
  name: "API Error Recovery",
@@ -7032,16 +7061,16 @@ var errorRecoveryGuardrail = {
7032
7061
  return pass(part);
7033
7062
  }
7034
7063
  const errorText = part.errorText || "";
7035
- const prefix = chalk2.bold.magenta("[ErrorRecovery]");
7064
+ const prefix = styleText2(["bold", "magenta"], "[ErrorRecovery]");
7036
7065
  console.log(
7037
- `${prefix} ${chalk2.red("Caught error:")} ${chalk2.dim(errorText.slice(0, 150))}`
7066
+ `${prefix} ${styleText2("red", "Caught error:")} ${styleText2("dim", errorText.slice(0, 150))}`
7038
7067
  );
7039
7068
  const logAndFail = (pattern, feedback) => {
7040
7069
  console.log(
7041
- `${prefix} ${chalk2.yellow("Pattern:")} ${chalk2.cyan(pattern)}`
7070
+ `${prefix} ${styleText2("yellow", "Pattern:")} ${styleText2("cyan", pattern)}`
7042
7071
  );
7043
7072
  console.log(
7044
- `${prefix} ${chalk2.green("Feedback:")} ${chalk2.dim(feedback.slice(0, 80))}...`
7073
+ `${prefix} ${styleText2("green", "Feedback:")} ${styleText2("dim", feedback.slice(0, 80))}...`
7045
7074
  );
7046
7075
  return fail(feedback);
7047
7076
  };
@@ -7114,7 +7143,7 @@ var errorRecoveryGuardrail = {
7114
7143
  );
7115
7144
  }
7116
7145
  console.log(
7117
- `${prefix} ${chalk2.yellow("Unknown error - stopping without retry")}`
7146
+ `${prefix} ${styleText2("yellow", "Unknown error - stopping without retry")}`
7118
7147
  );
7119
7148
  return stop(part);
7120
7149
  }
@@ -7337,6 +7366,7 @@ async function writeFilesOverExec(executeCommand, files) {
7337
7366
  // packages/context/src/lib/sandbox/container-sandbox.ts
7338
7367
  import { createHash, randomUUID } from "node:crypto";
7339
7368
  import { existsSync, readFileSync } from "node:fs";
7369
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
7340
7370
 
7341
7371
  // packages/context/src/lib/sandbox/docker-sandbox-errors.ts
7342
7372
  var DockerSandboxError = class extends ContainerSandboxError {
@@ -7655,7 +7685,7 @@ var ContainerSandboxStrategy = class {
7655
7685
  const container = await this.engine.attach(name, image);
7656
7686
  if (container) return { container, attached: true };
7657
7687
  if (Date.now() >= timeoutAt) return void 0;
7658
- await new Promise((resolve3) => setTimeout(resolve3, 10));
7688
+ await setTimeout2(10);
7659
7689
  }
7660
7690
  }
7661
7691
  async prepareVolumes() {
@@ -8244,7 +8274,7 @@ function attachment(input, {
8244
8274
  type: "file",
8245
8275
  data: {
8246
8276
  type: "data",
8247
- data: Buffer.from(input.bytes).toString("base64")
8277
+ data: input.bytes.toBase64()
8248
8278
  },
8249
8279
  mediaType,
8250
8280
  filename: path2.posix.basename(input.path)
@@ -8793,6 +8823,7 @@ function mapToRealPath(fs, cwd) {
8793
8823
 
8794
8824
  // packages/context/src/lib/sandbox/daytona-sandbox.ts
8795
8825
  import { randomUUID as randomUUID2 } from "node:crypto";
8826
+ import { setTimeout as setTimeout3 } from "node:timers/promises";
8796
8827
  var DAYTONA_DEFAULT_DESTINATION = "/home/daytona";
8797
8828
  var DAYTONA_EXIT_POLL_INTERVAL_MS = 250;
8798
8829
  var DAYTONA_EXIT_POLL_TIMEOUT_MS = 3e4;
@@ -9025,10 +9056,103 @@ function createDaytonaSandboxMethods(args) {
9025
9056
  return {
9026
9057
  executeCommand,
9027
9058
  async spawn(command, options) {
9028
- return spawnDaytonaProcess(sandbox, command, {
9029
- ...options,
9030
- commandTimeout
9031
- });
9059
+ const sessionId = `deepagents-spawn-${randomUUID2()}`;
9060
+ const stdout = createTextReadable();
9061
+ const stderr = createTextReadable();
9062
+ const signal = options?.signal;
9063
+ const sessionCommand = buildSessionCommand(command, { ...options });
9064
+ const exit = (async () => {
9065
+ let sessionCreated = false;
9066
+ let aborted = signal?.aborted === true;
9067
+ const { promise: abortPromise, resolve: resolveAbort } = Promise.withResolvers();
9068
+ const abort = () => {
9069
+ aborted = true;
9070
+ resolveAbort("aborted");
9071
+ if (sessionCreated) {
9072
+ sandbox.process.deleteSession(sessionId).catch(() => {
9073
+ });
9074
+ }
9075
+ };
9076
+ if (signal) {
9077
+ if (signal.aborted) abort();
9078
+ else signal.addEventListener("abort", abort, { once: true });
9079
+ }
9080
+ try {
9081
+ await sandbox.process.createSession(sessionId);
9082
+ sessionCreated = true;
9083
+ if (aborted) return abortedExitInfo();
9084
+ const response = await sandbox.process.executeSessionCommand(
9085
+ sessionId,
9086
+ {
9087
+ command: sessionCommand,
9088
+ runAsync: true,
9089
+ suppressInputEcho: true
9090
+ },
9091
+ commandTimeout
9092
+ );
9093
+ const commandId = response.cmdId;
9094
+ if (!commandId) {
9095
+ throw new DaytonaCommandError(
9096
+ "Daytona did not return a command id for the spawned session command."
9097
+ );
9098
+ }
9099
+ if (aborted) return abortedExitInfo();
9100
+ const logsTask = sandbox.process.getSessionCommandLogs(
9101
+ sessionId,
9102
+ commandId,
9103
+ stdout.enqueue,
9104
+ stderr.enqueue
9105
+ );
9106
+ logsTask.catch(() => {
9107
+ });
9108
+ const winner = await Promise.race([logsTask, abortPromise]);
9109
+ if (winner === "aborted") {
9110
+ await sandbox.process.deleteSession(sessionId).catch(() => {
9111
+ });
9112
+ return abortedExitInfo();
9113
+ }
9114
+ const timeoutMs = commandTimeout === void 0 ? DAYTONA_EXIT_POLL_TIMEOUT_MS : Math.max(commandTimeout * 1e3, DAYTONA_EXIT_POLL_TIMEOUT_MS);
9115
+ const deadline = Date.now() + timeoutMs;
9116
+ while (true) {
9117
+ if (aborted)
9118
+ throw new DaytonaCommandError("Daytona command aborted.");
9119
+ const info = await sandbox.process.getSessionCommand(
9120
+ sessionId,
9121
+ commandId
9122
+ );
9123
+ if (typeof info.exitCode === "number") {
9124
+ return {
9125
+ code: info.exitCode,
9126
+ signal: null,
9127
+ success: info.exitCode === 0
9128
+ };
9129
+ }
9130
+ if (Date.now() >= deadline) {
9131
+ throw new DaytonaCommandError(
9132
+ `Daytona session command "${commandId}" logs closed before an exit code became available.`
9133
+ );
9134
+ }
9135
+ await setTimeout3(DAYTONA_EXIT_POLL_INTERVAL_MS);
9136
+ }
9137
+ } catch (error) {
9138
+ if (aborted) return abortedExitInfo();
9139
+ const err = toError(error);
9140
+ stdout.error(err);
9141
+ stderr.error(err);
9142
+ throw err;
9143
+ } finally {
9144
+ if (signal) {
9145
+ signal.removeEventListener("abort", abort);
9146
+ }
9147
+ stdout.close();
9148
+ stderr.close();
9149
+ if (sessionCreated) {
9150
+ await sandbox.process.deleteSession(sessionId).catch(() => {
9151
+ });
9152
+ }
9153
+ }
9154
+ })();
9155
+ return { stdout: stdout.stream, stderr: stderr.stream, exit };
9032
9156
  },
9033
9157
  async readFile(path6, options) {
9034
9158
  try {
@@ -9085,168 +9209,40 @@ function createDaytonaSandboxMethods(args) {
9085
9209
  }
9086
9210
  };
9087
9211
  }
9088
- function spawnDaytonaProcess(sandbox, command, options = {}) {
9089
- const sessionId = createSessionId("spawn");
9090
- const stdout = createTextReadable();
9091
- const stderr = createTextReadable();
9092
- const exit = runSpawnedSession({
9093
- sandbox,
9094
- sessionId,
9095
- command: buildSessionCommand(command, options),
9096
- signal: options.signal,
9097
- commandTimeout: options.commandTimeout,
9098
- stdout,
9099
- stderr
9100
- });
9101
- return {
9102
- stdout: stdout.stream,
9103
- stderr: stderr.stream,
9104
- exit
9105
- };
9106
- }
9107
- async function runSpawnedSession(args) {
9108
- const {
9109
- sandbox,
9110
- sessionId,
9111
- command,
9112
- signal,
9113
- commandTimeout,
9114
- stdout,
9115
- stderr
9116
- } = args;
9117
- let sessionCreated = false;
9118
- let aborted = signal?.aborted ?? false;
9119
- let resolveAbort;
9120
- const abortPromise = new Promise((resolve3) => {
9121
- resolveAbort = () => resolve3("aborted");
9122
- });
9123
- const abort = () => {
9124
- aborted = true;
9125
- resolveAbort?.();
9126
- if (sessionCreated) {
9127
- sandbox.process.deleteSession(sessionId).catch(() => {
9128
- });
9129
- }
9130
- };
9131
- if (signal) {
9132
- if (signal.aborted) abort();
9133
- else signal.addEventListener("abort", abort, { once: true });
9134
- }
9135
- try {
9136
- await sandbox.process.createSession(sessionId);
9137
- sessionCreated = true;
9138
- if (aborted) return abortedExitInfo();
9139
- const response = await sandbox.process.executeSessionCommand(
9140
- sessionId,
9141
- {
9142
- command,
9143
- runAsync: true,
9144
- suppressInputEcho: true
9145
- },
9146
- commandTimeout
9147
- );
9148
- const commandId = response.cmdId;
9149
- if (!commandId) {
9150
- throw new DaytonaCommandError(
9151
- "Daytona did not return a command id for the spawned session command."
9152
- );
9153
- }
9154
- if (aborted) return abortedExitInfo();
9155
- const logsTask = sandbox.process.getSessionCommandLogs(
9156
- sessionId,
9157
- commandId,
9158
- (chunk) => stdout.enqueue(chunk),
9159
- (chunk) => stderr.enqueue(chunk)
9160
- );
9161
- logsTask.catch(() => {
9162
- });
9163
- const winner = await Promise.race([
9164
- logsTask.then(() => "logs"),
9165
- abortPromise
9166
- ]);
9167
- if (winner === "aborted") {
9168
- await sandbox.process.deleteSession(sessionId).catch(() => {
9169
- });
9170
- return abortedExitInfo();
9171
- }
9172
- await logsTask;
9173
- const code = await waitForSessionCommandExitCode({
9174
- sandbox,
9175
- sessionId,
9176
- commandId,
9177
- timeoutMs: sessionExitPollTimeoutMs(commandTimeout),
9178
- isAborted: () => aborted
9179
- });
9180
- return { code, signal: null, success: code === 0 };
9181
- } catch (error) {
9182
- if (aborted) return abortedExitInfo();
9183
- const err = toError(error);
9184
- stdout.error(err);
9185
- stderr.error(err);
9186
- throw err;
9187
- } finally {
9188
- if (signal) {
9189
- signal.removeEventListener("abort", abort);
9190
- }
9191
- stdout.close();
9192
- stderr.close();
9193
- if (sessionCreated) {
9194
- await sandbox.process.deleteSession(sessionId).catch(() => {
9195
- });
9196
- }
9197
- }
9198
- }
9199
- async function waitForSessionCommandExitCode(args) {
9200
- const { sandbox, sessionId, commandId, timeoutMs, isAborted } = args;
9201
- const deadline = Date.now() + timeoutMs;
9202
- while (true) {
9203
- if (isAborted()) throw new DaytonaCommandError("Daytona command aborted.");
9204
- const info = await sandbox.process.getSessionCommand(sessionId, commandId);
9205
- if (typeof info.exitCode === "number") {
9206
- return info.exitCode;
9207
- }
9208
- if (Date.now() >= deadline) {
9209
- throw new DaytonaCommandError(
9210
- `Daytona session command "${commandId}" logs closed before an exit code became available.`
9211
- );
9212
- }
9213
- await delay(DAYTONA_EXIT_POLL_INTERVAL_MS);
9214
- }
9215
- }
9216
- function sessionExitPollTimeoutMs(commandTimeout) {
9217
- if (commandTimeout === void 0 || commandTimeout === 0) {
9218
- return DAYTONA_EXIT_POLL_TIMEOUT_MS;
9219
- }
9220
- return Math.max(commandTimeout * 1e3, DAYTONA_EXIT_POLL_TIMEOUT_MS);
9221
- }
9222
- function delay(ms) {
9223
- return new Promise((resolve3) => setTimeout(resolve3, ms));
9224
- }
9225
9212
  function createTextReadable() {
9226
9213
  const encoder = new TextEncoder();
9227
- let controller;
9228
- let closed = false;
9229
- return {
9230
- stream: new ReadableStream({
9231
- start(streamController) {
9232
- controller = streamController;
9233
- }
9234
- }),
9235
- enqueue(chunk) {
9236
- if (closed || !chunk) return;
9237
- controller?.enqueue(encoder.encode(chunk));
9214
+ const ended = {
9215
+ enqueue() {
9238
9216
  },
9239
9217
  close() {
9240
- if (closed) return;
9241
- closed = true;
9242
- controller?.close();
9243
9218
  },
9244
- error(error) {
9245
- if (closed) return;
9246
- closed = true;
9247
- controller?.error(error);
9219
+ error() {
9248
9220
  }
9249
9221
  };
9222
+ let sink = ended;
9223
+ const stream = new ReadableStream({
9224
+ start(controller) {
9225
+ sink = {
9226
+ enqueue(chunk) {
9227
+ if (chunk) controller.enqueue(encoder.encode(chunk));
9228
+ },
9229
+ close() {
9230
+ sink = ended;
9231
+ controller.close();
9232
+ },
9233
+ error(error) {
9234
+ sink = ended;
9235
+ controller.error(error);
9236
+ }
9237
+ };
9238
+ }
9239
+ });
9240
+ return {
9241
+ stream,
9242
+ enqueue: (chunk) => sink.enqueue(chunk),
9243
+ close: () => sink.close(),
9244
+ error: (error) => sink.error(error)
9245
+ };
9250
9246
  }
9251
9247
  function buildSessionCommand(command, options) {
9252
9248
  const cwdPrefix = options.cwd ? `cd ${shellQuote(options.cwd)} && ` : "";
@@ -9268,9 +9264,6 @@ function validateEnvKey(key) {
9268
9264
  );
9269
9265
  }
9270
9266
  }
9271
- function createSessionId(kind) {
9272
- return `deepagents-${kind}-${randomUUID2()}`;
9273
- }
9274
9267
  function abortedCommandResult() {
9275
9268
  return {
9276
9269
  stdout: "",
@@ -9322,10 +9315,10 @@ import {
9322
9315
  } from "@zukhruf/docker";
9323
9316
  import spawn3, { SubprocessError as SubprocessError4 } from "nano-spawn";
9324
9317
  import { spawn as childSpawn2 } from "node:child_process";
9325
- import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
9318
+ import { hash, randomUUID as randomUUID3 } from "node:crypto";
9326
9319
  import { readFileSync as readFileSync2 } from "node:fs";
9327
9320
  import { posix as posix2 } from "node:path";
9328
- import { setTimeout as delay2 } from "node:timers/promises";
9321
+ import { setTimeout as delay } from "node:timers/promises";
9329
9322
  function isDockerfileOptions(opts) {
9330
9323
  return "dockerfile" in opts;
9331
9324
  }
@@ -9768,7 +9761,7 @@ var DockerContainer = class {
9768
9761
  while (true) {
9769
9762
  const { stdout } = await this.#container.exec(this.#bash(readPid));
9770
9763
  if (stdout) return Number(stdout);
9771
- if (await Promise.race([exited, delay2(10).then(() => false)])) {
9764
+ if (await Promise.race([exited, delay(10).then(() => false)])) {
9772
9765
  return void 0;
9773
9766
  }
9774
9767
  }
@@ -9964,7 +9957,10 @@ var DockerEngine = class _DockerEngine {
9964
9957
  * `commandTimeout` bounds each command of the sandbox's containers.
9965
9958
  */
9966
9959
  static async connect(environment, commandTimeout) {
9967
- const docker = await Docker.connect({ environment }).catch(unavailable);
9960
+ const docker = await Docker.connect({
9961
+ clock: globalThis,
9962
+ environment
9963
+ }).catch(unavailable);
9968
9964
  return new _DockerEngine(docker, commandTimeout);
9969
9965
  }
9970
9966
  /** A sandbox container handle for a container of this engine. */
@@ -10087,7 +10083,7 @@ var DockerEngine = class _DockerEngine {
10087
10083
  return;
10088
10084
  } catch (error) {
10089
10085
  if (error instanceof VolumeInUseError && performance.now() < deadline) {
10090
- await delay2(25);
10086
+ await delay(25);
10091
10087
  continue;
10092
10088
  }
10093
10089
  if (error instanceof ConnectionFailedError) {
@@ -10137,12 +10133,7 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
10137
10133
  this.dockerEngine = engine;
10138
10134
  this.composeFile = args.compose;
10139
10135
  this.service = args.service;
10140
- this.projectName = this.computeProjectName();
10141
- }
10142
- computeProjectName() {
10143
- const content = readFileSync2(this.composeFile, "utf-8");
10144
- const hash = createHash2("sha256").update(content).digest("hex").slice(0, 8);
10145
- return `sandbox-${hash}`;
10136
+ this.projectName = `sandbox-${hash("sha256", readFileSync2(this.composeFile, "utf-8")).slice(0, 8)}`;
10146
10137
  }
10147
10138
  compose(command) {
10148
10139
  return spawn3(
@@ -11184,32 +11175,41 @@ async function pumpExecStream(args) {
11184
11175
  }
11185
11176
  }
11186
11177
  function createByteReadable() {
11187
- let controller;
11188
- let closed = false;
11189
- return {
11190
- stream: new ReadableStream({
11191
- start(streamController) {
11192
- controller = streamController;
11193
- },
11194
- cancel() {
11195
- closed = true;
11196
- }
11197
- }),
11198
- enqueue(chunk) {
11199
- if (closed || chunk.length === 0) return;
11200
- controller?.enqueue(chunk);
11178
+ const ended = {
11179
+ enqueue() {
11201
11180
  },
11202
11181
  close() {
11203
- if (closed) return;
11204
- closed = true;
11205
- controller?.close();
11206
11182
  },
11207
- error(error) {
11208
- if (closed) return;
11209
- closed = true;
11210
- controller?.error(error);
11183
+ error() {
11211
11184
  }
11212
11185
  };
11186
+ let sink = ended;
11187
+ const stream = new ReadableStream({
11188
+ start(controller) {
11189
+ sink = {
11190
+ enqueue(chunk) {
11191
+ if (chunk.length > 0) controller.enqueue(chunk);
11192
+ },
11193
+ close() {
11194
+ sink = ended;
11195
+ controller.close();
11196
+ },
11197
+ error(error) {
11198
+ sink = ended;
11199
+ controller.error(error);
11200
+ }
11201
+ };
11202
+ },
11203
+ cancel() {
11204
+ sink = ended;
11205
+ }
11206
+ });
11207
+ return {
11208
+ stream,
11209
+ enqueue: (chunk) => sink.enqueue(chunk),
11210
+ close: () => sink.close(),
11211
+ error: (error) => sink.error(error)
11212
+ };
11213
11213
  }
11214
11214
  async function readAllText(stream) {
11215
11215
  const decoder2 = new TextDecoder();
@@ -11270,9 +11270,6 @@ ${usageLines}`,
11270
11270
  };
11271
11271
  });
11272
11272
  }
11273
- function escapeRegExp(s) {
11274
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11275
- }
11276
11273
  function stripQuoteArtifacts(raw) {
11277
11274
  let s = raw.trim();
11278
11275
  if (s.startsWith('"')) {
@@ -11291,9 +11288,9 @@ function repairQuotedArg(rawArgs) {
11291
11288
  return `'${escaped}'`;
11292
11289
  }
11293
11290
  function buildSubcommandRepair(name, subcommands) {
11294
- const subNames = Object.keys(subcommands).map(escapeRegExp).join("|");
11291
+ const subNames = Object.keys(subcommands).map(RegExp.escape).join("|");
11295
11292
  const pattern = new RegExp(
11296
- `^(\\s*${escapeRegExp(name)}\\s+(?:${subNames}))\\s+([\\s\\S]+)$`
11293
+ `^(\\s*${RegExp.escape(name)}\\s+(?:${subNames}))\\s+([\\s\\S]+)$`
11297
11294
  );
11298
11295
  return function repair(raw) {
11299
11296
  const match = raw.match(pattern);
@@ -13286,7 +13283,7 @@ async function persistedWriter(options) {
13286
13283
  }
13287
13284
 
13288
13285
  // packages/context/src/lib/stream/polling-change-source.ts
13289
- import { setTimeout as delay3 } from "node:timers/promises";
13286
+ import { setTimeout as delay2 } from "node:timers/promises";
13290
13287
 
13291
13288
  // packages/context/src/lib/stream/polling-policy.ts
13292
13289
  var DEFAULT_WATCH_POLLING = {
@@ -13331,7 +13328,7 @@ function nextAdaptivePollingDelay(state) {
13331
13328
  state.config.minMs,
13332
13329
  state.config.maxMs
13333
13330
  );
13334
- const delay4 = applyJitter(
13331
+ const delay3 = applyJitter(
13335
13332
  current,
13336
13333
  state.config.jitterRatio,
13337
13334
  state.config.minMs,
@@ -13342,7 +13339,7 @@ function nextAdaptivePollingDelay(state) {
13342
13339
  state.config.minMs,
13343
13340
  state.config.maxMs
13344
13341
  );
13345
- return delay4;
13342
+ return delay3;
13346
13343
  }
13347
13344
  function normalizeAdaptivePolling(polling, fallback) {
13348
13345
  const merged = {
@@ -13442,7 +13439,7 @@ function isTerminal(status) {
13442
13439
  return status !== "queued" && status !== "running";
13443
13440
  }
13444
13441
  function waitForDelay(ms, signal) {
13445
- return delay3(ms, true, { signal }).catch((err) => {
13442
+ return delay2(ms, true, { signal }).catch((err) => {
13446
13443
  if (signal.aborted) return false;
13447
13444
  throw err;
13448
13445
  });
@@ -14183,16 +14180,12 @@ function assertIdentifier2(value, label) {
14183
14180
 
14184
14181
  // packages/context/src/lib/stream/sqlite.stream-store.ts
14185
14182
  import { Declaration as Declaration2 } from "@zukhruf/sqlite-drift";
14183
+ import { open as open2 } from "@zukhruf/sqlite-open";
14186
14184
  import { transaction as transaction2 } from "@zukhruf/sqlite-transaction";
14187
- import {
14188
- DatabaseSync as DatabaseSync2
14189
- } from "node:sqlite";
14190
14185
  import { z as z19 } from "zod";
14191
14186
 
14192
14187
  // packages/context/src/lib/stream/ddl.stream.sqlite.ts
14193
14188
  var SETUP2 = `
14194
- PRAGMA busy_timeout = 5000;
14195
- PRAGMA journal_mode = WAL;
14196
14189
  PRAGMA synchronous = NORMAL;
14197
14190
  `;
14198
14191
  var statements2 = [
@@ -14250,7 +14243,7 @@ var SqliteStreamStore = class extends StreamStore {
14250
14243
  }
14251
14244
  constructor(pathOrDb) {
14252
14245
  super();
14253
- this.#db = typeof pathOrDb === "string" ? new DatabaseSync2(pathOrDb) : pathOrDb;
14246
+ this.#db = typeof pathOrDb === "string" ? open2(pathOrDb) : pathOrDb;
14254
14247
  this.#db.exec(SETUP2);
14255
14248
  tables2.apply(this.#db);
14256
14249
  this.#sql = this.#db.createTagStore();