@deepagents/context 7.0.2 → 7.1.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 (80) hide show
  1. package/README.md +4 -4
  2. package/dist/browser.js +210 -77
  3. package/dist/browser.js.map +4 -4
  4. package/dist/index.js +1311 -1363
  5. package/dist/index.js.map +4 -4
  6. package/dist/lib/agent.d.ts +21 -45
  7. package/dist/lib/agent.d.ts.map +1 -1
  8. package/dist/lib/chat.d.ts +11 -5
  9. package/dist/lib/chat.d.ts.map +1 -1
  10. package/dist/lib/codec/serialized-fragments.d.ts +7 -5
  11. package/dist/lib/codec/serialized-fragments.d.ts.map +1 -1
  12. package/dist/lib/engine.d.ts.map +1 -1
  13. package/dist/lib/estimate.d.ts +8 -3
  14. package/dist/lib/estimate.d.ts.map +1 -1
  15. package/dist/lib/fragments/plan-shared.d.ts +1 -1
  16. package/dist/lib/fragments/reminders/src/predicates/tool.d.ts.map +1 -1
  17. package/dist/lib/fragments.d.ts +6 -0
  18. package/dist/lib/fragments.d.ts.map +1 -1
  19. package/dist/lib/resolvers/async-resolver.d.ts +2 -2
  20. package/dist/lib/resolvers/async-resolver.d.ts.map +1 -1
  21. package/dist/lib/resolvers/function-resolver.d.ts +2 -2
  22. package/dist/lib/resolvers/function-resolver.d.ts.map +1 -1
  23. package/dist/lib/resolvers/generator-resolver.d.ts +2 -2
  24. package/dist/lib/resolvers/generator-resolver.d.ts.map +1 -1
  25. package/dist/lib/resolvers/iterable-resolver.d.ts +1 -1
  26. package/dist/lib/resolvers/iterable-resolver.d.ts.map +1 -1
  27. package/dist/lib/resolvers/loader-resolver.d.ts.map +1 -1
  28. package/dist/lib/resolvers/promise-resolver.d.ts +1 -1
  29. package/dist/lib/resolvers/promise-resolver.d.ts.map +1 -1
  30. package/dist/lib/resolvers/types.d.ts +3 -2
  31. package/dist/lib/resolvers/types.d.ts.map +1 -1
  32. package/dist/lib/sandbox/apple-container-sandbox.d.ts.map +1 -1
  33. package/dist/lib/sandbox/ast-utils.d.ts +3 -1
  34. package/dist/lib/sandbox/ast-utils.d.ts.map +1 -1
  35. package/dist/lib/sandbox/binary-bridges.d.ts.map +1 -1
  36. package/dist/lib/sandbox/cli-process.d.ts +6 -1
  37. package/dist/lib/sandbox/cli-process.d.ts.map +1 -1
  38. package/dist/lib/sandbox/container-engine.d.ts +4 -1
  39. package/dist/lib/sandbox/container-engine.d.ts.map +1 -1
  40. package/dist/lib/sandbox/container-sandbox.d.ts.map +1 -1
  41. package/dist/lib/sandbox/docker-sandbox.d.ts +3 -3
  42. package/dist/lib/sandbox/docker-sandbox.d.ts.map +1 -1
  43. package/dist/lib/sandbox/index.d.ts +0 -1
  44. package/dist/lib/sandbox/index.d.ts.map +1 -1
  45. package/dist/lib/sandbox/installers/installer.d.ts +6 -1
  46. package/dist/lib/sandbox/installers/installer.d.ts.map +1 -1
  47. package/dist/lib/sandbox/installers/url-binary.d.ts.map +1 -1
  48. package/dist/lib/sandbox/read-file.d.ts +2 -1
  49. package/dist/lib/sandbox/read-file.d.ts.map +1 -1
  50. package/dist/lib/sandbox/strace/index.js +3 -3
  51. package/dist/lib/sandbox/strace/index.js.map +2 -2
  52. package/dist/lib/sandbox/types.d.ts +4 -5
  53. package/dist/lib/sandbox/types.d.ts.map +1 -1
  54. package/dist/lib/skills/frontmatter.d.ts.map +1 -1
  55. package/dist/lib/store/columns.d.ts +13 -0
  56. package/dist/lib/store/columns.d.ts.map +1 -0
  57. package/dist/lib/store/postgres.store.d.ts.map +1 -1
  58. package/dist/lib/store/sqlite.store.d.ts.map +1 -1
  59. package/dist/lib/store/sqlserver.store.d.ts.map +1 -1
  60. package/dist/lib/stream/postgres-notify-change-source.d.ts.map +1 -1
  61. package/dist/lib/stream/postgres.stream-store.d.ts.map +1 -1
  62. package/dist/lib/stream/rows.d.ts +16 -0
  63. package/dist/lib/stream/rows.d.ts.map +1 -0
  64. package/dist/lib/stream/sqlite.stream-store.d.ts.map +1 -1
  65. package/dist/lib/stream-buffer.d.ts +10 -1
  66. package/dist/lib/stream-buffer.d.ts.map +1 -1
  67. package/dist/lib/telemetry/file/index.js +23 -13
  68. package/dist/lib/telemetry/file/index.js.map +2 -2
  69. package/dist/lib/telemetry/index.js +23 -13
  70. package/dist/lib/telemetry/index.js.map +2 -2
  71. package/dist/lib/telemetry/redact-telemetry-event.d.ts +1 -0
  72. package/dist/lib/telemetry/redact-telemetry-event.d.ts.map +1 -1
  73. package/dist/lib/tracing/index.js +27 -24
  74. package/dist/lib/tracing/index.js.map +3 -3
  75. package/dist/lib/tracing/openai-traces-integration.d.ts.map +1 -1
  76. package/dist/lib/tracing/serialization.d.ts +2 -0
  77. package/dist/lib/tracing/serialization.d.ts.map +1 -1
  78. package/package.json +3 -11
  79. package/dist/lib/sandbox/agent-os-sandbox.d.ts +0 -85
  80. package/dist/lib/sandbox/agent-os-sandbox.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -163,6 +163,23 @@ import { generateId } from "ai";
163
163
  function isFragment(data) {
164
164
  return typeof data === "object" && data !== null && "name" in data && ("data" in data || "codec" in data) && typeof data.name === "string";
165
165
  }
166
+ function isFragmentData(value) {
167
+ return fitsFragmentData(value, /* @__PURE__ */ new WeakSet());
168
+ }
169
+ function fitsFragmentData(value, visited) {
170
+ if (typeof value !== "object") {
171
+ return typeof value !== "bigint" && typeof value !== "symbol";
172
+ }
173
+ if (value === null || visited.has(value)) return true;
174
+ visited.add(value);
175
+ if (Array.isArray(value)) {
176
+ return value.every((item) => fitsFragmentData(item, visited));
177
+ }
178
+ if (value instanceof Promise) return true;
179
+ if (Symbol.asyncIterator in value || Symbol.iterator in value) return true;
180
+ if (isFragment(value)) return fitsFragmentData(value.data, visited);
181
+ return Object.values(value).every((item) => fitsFragmentData(item, visited));
182
+ }
166
183
  function isFragmentObject(data) {
167
184
  if (typeof data !== "object" || data === null) return false;
168
185
  if (Array.isArray(data)) return false;
@@ -176,7 +193,13 @@ function isMessageFragment(fragment2) {
176
193
  }
177
194
  function getFragmentData(fragment2) {
178
195
  if (fragment2.codec) {
179
- return fragment2.codec.decode();
196
+ const decoded = fragment2.codec.decode();
197
+ if (!isFragmentData(decoded)) {
198
+ throw new Error(
199
+ `Fragment "${fragment2.name}" codec decoded a value that is not fragment data`
200
+ );
201
+ }
202
+ return decoded;
180
203
  }
181
204
  if ("data" in fragment2) {
182
205
  return fragment2.data;
@@ -407,9 +430,6 @@ var Agent = class _Agent {
407
430
  *
408
431
  * // With guardrails - use toUIMessageStream for protection
409
432
  * await printer.readableStream(stream.toUIMessageStream());
410
- *
411
- * // Or use printer.stdout which uses toUIMessageStream internally
412
- * await printer.stdout(stream);
413
433
  * ```
414
434
  */
415
435
  async stream(...[options]) {
@@ -485,13 +505,11 @@ var Agent = class _Agent {
485
505
  }),
486
506
  repairToolCall: createRepairToolCall(model, config?.abortSignal),
487
507
  stopWhen: this.#options.stopWhen ?? DEFAULT_STOP_WHEN,
488
- // Streaming erases the tool-set type; the callback still receives this.tools.
489
508
  prepareStep: prepareStep ?? context.createPrepareStep({
490
509
  sandbox: this.#options.sandbox
491
510
  }),
492
511
  experimental_transform: config?.transform ?? smoothStream(),
493
512
  tools: this.tools,
494
- // Generic wrappers cannot reduce AI SDK's conditional context or caller maps.
495
513
  toolsContext,
496
514
  experimental_toolCallers: this.#options.experimental_toolCallers,
497
515
  toolChoice: this.#options.toolChoice
@@ -610,7 +628,7 @@ var Agent = class _Agent {
610
628
  return result;
611
629
  }
612
630
  asTool(props) {
613
- const definition = {
631
+ return {
614
632
  description: props?.toolDescription || `Delegate to the ${this.#options.name} agent to handle the request.`,
615
633
  metadata: props?.metadata,
616
634
  toModelOutput: props?.toModelOutput,
@@ -660,7 +678,6 @@ ${details}
660
678
  }
661
679
  }
662
680
  };
663
- return tool(definition);
664
681
  }
665
682
  asAdvisor(options) {
666
683
  const maxUses = options?.maxUses;
@@ -735,7 +752,7 @@ function agent(options) {
735
752
  return new Agent(options);
736
753
  }
737
754
  function structuredOutput(options) {
738
- const tools = withHostOnlyToolMetadata({ ...options.tools });
755
+ const tools = options.tools === void 0 ? void 0 : withHostOnlyToolMetadata(options.tools);
739
756
  return {
740
757
  async generate(...[callOptions]) {
741
758
  if (!options.context) {
@@ -807,8 +824,7 @@ function chunkId(chunk) {
807
824
  if (typeof chunk !== "object" || chunk === null || !("id" in chunk)) {
808
825
  return void 0;
809
826
  }
810
- const { id } = chunk;
811
- return typeof id === "string" ? id : void 0;
827
+ return typeof chunk.id === "string" ? chunk.id : void 0;
812
828
  }
813
829
  function writeText(writer, text, openPartId) {
814
830
  const feedbackPartId = openPartId ?? generateId3();
@@ -839,18 +855,6 @@ import {
839
855
  isToolUIPart
840
856
  } from "ai";
841
857
 
842
- // packages/context/src/lib/title.ts
843
- import { z as z2 } from "zod";
844
-
845
- // packages/context/src/lib/engine.ts
846
- import { getErrorMessage } from "@ai-sdk/provider";
847
- import {
848
- convertToModelMessages as convertToModelMessages2,
849
- generateId as generateId5,
850
- isStaticToolUIPart as isStaticToolUIPart2,
851
- validateUIMessages
852
- } from "ai";
853
-
854
858
  // packages/context/src/lib/fragments/reminders/src/reminders.ts
855
859
  import { generateId as generateId4 } from "ai";
856
860
 
@@ -2250,8 +2254,7 @@ function toolCall(options) {
2250
2254
  }
2251
2255
  if (options.output) {
2252
2256
  if (part.state !== "output-available") return false;
2253
- if (!options.output(part.output))
2254
- return false;
2257
+ if (!options.output(part.output)) return false;
2255
2258
  }
2256
2259
  if (options.errorText) {
2257
2260
  if (part.state !== "output-error") return false;
@@ -2633,6 +2636,18 @@ function temporalReminder(options) {
2633
2636
  ];
2634
2637
  }
2635
2638
 
2639
+ // packages/context/src/lib/title.ts
2640
+ import { z as z5 } from "zod";
2641
+
2642
+ // packages/context/src/lib/engine.ts
2643
+ import { getErrorMessage } from "@ai-sdk/provider";
2644
+ import {
2645
+ convertToModelMessages as convertToModelMessages2,
2646
+ generateId as generateId5,
2647
+ isStaticToolUIPart as isStaticToolUIPart2,
2648
+ validateUIMessages
2649
+ } from "ai";
2650
+
2636
2651
  // packages/context/src/lib/ui-message-guards.ts
2637
2652
  function isRecord2(value) {
2638
2653
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -2714,7 +2729,7 @@ var ChainSummaryBuilder = class {
2714
2729
  this.#messageCount++;
2715
2730
  if (fragment2.name !== "user") return;
2716
2731
  const encoded = fragment2.codec?.encode();
2717
- if (encoded && isSyntheticReminderMessage(encoded)) return;
2732
+ if (isUIMessage(encoded) && isSyntheticReminderMessage(encoded)) return;
2718
2733
  this.#turn++;
2719
2734
  }
2720
2735
  build() {
@@ -2733,6 +2748,7 @@ var ChainSummaryBuilder = class {
2733
2748
 
2734
2749
  // packages/context/src/lib/estimate.ts
2735
2750
  import { encode } from "gpt-tokenizer";
2751
+ import { z as z2 } from "zod";
2736
2752
  var defaultTokenizer = {
2737
2753
  encode(text) {
2738
2754
  return encode(text);
@@ -2741,6 +2757,36 @@ var defaultTokenizer = {
2741
2757
  return encode(text).length;
2742
2758
  }
2743
2759
  };
2760
+ var modelCostSchema = z2.object({
2761
+ input: z2.number(),
2762
+ output: z2.number(),
2763
+ cache_read: z2.number().optional(),
2764
+ cache_write: z2.number().optional(),
2765
+ reasoning: z2.number().optional()
2766
+ });
2767
+ var modelsDevResponseSchema = z2.record(
2768
+ z2.string(),
2769
+ z2.object({
2770
+ models: z2.record(
2771
+ z2.string(),
2772
+ z2.object({
2773
+ id: z2.string(),
2774
+ name: z2.string(),
2775
+ family: z2.string().optional(),
2776
+ cost: modelCostSchema.optional(),
2777
+ limit: z2.object({ context: z2.number(), output: z2.number() })
2778
+ })
2779
+ )
2780
+ })
2781
+ );
2782
+ function inputPricePerMillion(model) {
2783
+ if (!model.cost) {
2784
+ throw new Error(
2785
+ `Model "${model.provider}:${model.id}" has no pricing data on models.dev`
2786
+ );
2787
+ }
2788
+ return model.cost.input;
2789
+ }
2744
2790
  var ModelsRegistry = class {
2745
2791
  #cache = /* @__PURE__ */ new Map();
2746
2792
  #loaded = false;
@@ -2755,7 +2801,7 @@ var ModelsRegistry = class {
2755
2801
  if (!response.ok) {
2756
2802
  throw new Error(`Failed to fetch models: ${response.statusText}`);
2757
2803
  }
2758
- const data = await response.json();
2804
+ const data = modelsDevResponseSchema.parse(await response.json());
2759
2805
  for (const [providerId, provider] of Object.entries(data)) {
2760
2806
  for (const [modelId, model] of Object.entries(provider.models)) {
2761
2807
  const info = {
@@ -2808,14 +2854,9 @@ var ModelsRegistry = class {
2808
2854
  * Get the appropriate tokenizer for a model
2809
2855
  */
2810
2856
  getTokenizer(modelId) {
2811
- const model = this.get(modelId);
2812
- if (model) {
2813
- const familyTokenizer = this.#tokenizers.get(model.family);
2814
- if (familyTokenizer) {
2815
- return familyTokenizer;
2816
- }
2817
- }
2818
- return this.#defaultTokenizer;
2857
+ const family = this.get(modelId)?.family;
2858
+ const familyTokenizer = family === void 0 ? void 0 : this.#tokenizers.get(family);
2859
+ return familyTokenizer ?? this.#defaultTokenizer;
2819
2860
  }
2820
2861
  /**
2821
2862
  * Estimate token count and cost for given text and model
@@ -2829,9 +2870,10 @@ var ModelsRegistry = class {
2829
2870
  `Model "${modelId}" not found. Call load() first or check model ID.`
2830
2871
  );
2831
2872
  }
2873
+ const inputPrice = inputPricePerMillion(model);
2832
2874
  const tokenizer = this.getTokenizer(modelId);
2833
2875
  const tokens = tokenizer.count(input);
2834
- const cost = tokens / 1e6 * model.cost.input;
2876
+ const cost = tokens / 1e6 * inputPrice;
2835
2877
  return {
2836
2878
  model: model.id,
2837
2879
  provider: model.provider,
@@ -2846,12 +2888,9 @@ var ModelsRegistry = class {
2846
2888
  };
2847
2889
  }
2848
2890
  };
2849
- var _registry = null;
2891
+ var sharedRegistry = new ModelsRegistry();
2850
2892
  function getModelsRegistry() {
2851
- if (!_registry) {
2852
- _registry = new ModelsRegistry();
2853
- }
2854
- return _registry;
2893
+ return sharedRegistry;
2855
2894
  }
2856
2895
  async function estimate(modelId, renderer, ...fragments) {
2857
2896
  const registry = getModelsRegistry();
@@ -2863,13 +2902,14 @@ async function estimate(modelId, renderer, ...fragments) {
2863
2902
  `Model "${modelId}" not found. Call load() first or check model ID.`
2864
2903
  );
2865
2904
  }
2905
+ const inputPrice = inputPricePerMillion(model);
2866
2906
  const tokenizer = registry.getTokenizer(modelId);
2867
2907
  const totalTokens = tokenizer.count(input);
2868
- const totalCost = totalTokens / 1e6 * model.cost.input;
2908
+ const totalCost = totalTokens / 1e6 * inputPrice;
2869
2909
  const fragmentEstimates = fragments.map((fragment2) => {
2870
2910
  const rendered = renderer.render([fragment2]);
2871
2911
  const tokens = tokenizer.count(rendered);
2872
- const cost = tokens / 1e6 * model.cost.input;
2912
+ const cost = tokens / 1e6 * inputPrice;
2873
2913
  return {
2874
2914
  id: fragment2.id,
2875
2915
  name: fragment2.name,
@@ -2898,7 +2938,10 @@ var AsyncResolver = class {
2898
2938
  canResolve(value) {
2899
2939
  return typeof value === "function" && value.constructor.name === "AsyncFunction";
2900
2940
  }
2901
- resolve(value, ctx) {
2941
+ async resolve(value, ctx) {
2942
+ if (!this.canResolve(value)) {
2943
+ throw new TypeError(`${this.name} cannot resolve a ${typeof value}`);
2944
+ }
2902
2945
  return value(ctx);
2903
2946
  }
2904
2947
  };
@@ -2911,8 +2954,10 @@ var FunctionResolver = class {
2911
2954
  return typeof value === "function";
2912
2955
  }
2913
2956
  async resolve(value, ctx) {
2914
- const loader = value;
2915
- return loader(ctx);
2957
+ if (!this.canResolve(value)) {
2958
+ throw new TypeError(`${this.name} cannot resolve a ${typeof value}`);
2959
+ }
2960
+ return value(ctx);
2916
2961
  }
2917
2962
  };
2918
2963
 
@@ -2933,6 +2978,9 @@ var GeneratorResolver = class {
2933
2978
  return typeof value === "function" && GENERATOR_CTOR_NAMES.has(value.constructor.name);
2934
2979
  }
2935
2980
  async resolve(value, ctx) {
2981
+ if (!this.canResolve(value)) {
2982
+ throw new TypeError(`${this.name} cannot resolve a ${typeof value}`);
2983
+ }
2936
2984
  const iterable = value(ctx);
2937
2985
  const collected = [];
2938
2986
  if (isAsyncIterable(iterable)) {
@@ -2983,14 +3031,16 @@ var IterableResolver = class {
2983
3031
  return hasIterableProtocol(value);
2984
3032
  }
2985
3033
  async resolve(value, _ctx) {
2986
- const iterable = value;
3034
+ if (!this.canResolve(value)) {
3035
+ throw new TypeError(`${this.name} cannot resolve a ${typeof value}`);
3036
+ }
2987
3037
  const collected = [];
2988
- if (isAsyncIterable2(iterable)) {
2989
- for await (const chunk of iterable) {
3038
+ if (isAsyncIterable2(value)) {
3039
+ for await (const chunk of value) {
2990
3040
  pushLimited2(collected, chunk, this.#maxItems, this.name);
2991
3041
  }
2992
3042
  } else {
2993
- for (const chunk of iterable) {
3043
+ for (const chunk of value) {
2994
3044
  pushLimited2(collected, chunk, this.#maxItems, this.name);
2995
3045
  }
2996
3046
  }
@@ -3015,7 +3065,10 @@ var PromiseResolver = class {
3015
3065
  canResolve(value) {
3016
3066
  return value instanceof Promise;
3017
3067
  }
3018
- resolve(value, _ctx) {
3068
+ async resolve(value, _ctx) {
3069
+ if (!this.canResolve(value)) {
3070
+ throw new TypeError(`${this.name} cannot resolve a ${typeof value}`);
3071
+ }
3019
3072
  return value;
3020
3073
  }
3021
3074
  };
@@ -3035,13 +3088,19 @@ var FragmentLoaderResolver = class {
3035
3088
  }
3036
3089
  async #walkFragment(fragment2, ctx, depth, ancestors, path6) {
3037
3090
  if (!("data" in fragment2)) return;
3038
- fragment2.data = await this.#walkData(
3091
+ const data = await this.#walkData(
3039
3092
  fragment2.data,
3040
3093
  ctx,
3041
3094
  depth,
3042
3095
  ancestors,
3043
3096
  path6
3044
3097
  );
3098
+ if (!isFragmentData(data)) {
3099
+ throw new Error(
3100
+ `Fragment '${path6}' resolved to a value that is not fragment data`
3101
+ );
3102
+ }
3103
+ fragment2.data = data;
3045
3104
  }
3046
3105
  async #walkData(value, ctx, depth, ancestors, path6) {
3047
3106
  if (ctx.signal?.aborted) {
@@ -3265,6 +3324,18 @@ var SavePipeline = class _SavePipeline {
3265
3324
 
3266
3325
  // packages/context/src/lib/store/sqlite.store.ts
3267
3326
  import { DatabaseSync } from "node:sqlite";
3327
+ import { z as z4 } from "zod";
3328
+
3329
+ // packages/context/src/lib/store/columns.ts
3330
+ import { z as z3 } from "zod";
3331
+ var bigintColumn = z3.union([z3.number(), z3.string().regex(/^-?\d+$/)]).transform(Number);
3332
+ var jsonObject = z3.record(z3.string(), z3.unknown());
3333
+ function parseJson(text) {
3334
+ return JSON.parse(text);
3335
+ }
3336
+ function parseJsonObject(text) {
3337
+ return jsonObject.parse(parseJson(text));
3338
+ }
3268
3339
 
3269
3340
  // packages/context/src/lib/store/ddl.sqlite.sql
3270
3341
  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";
@@ -3286,6 +3357,121 @@ var ContextStore = class {
3286
3357
  };
3287
3358
 
3288
3359
  // packages/context/src/lib/store/sqlite.store.ts
3360
+ var chatColumns = z4.object({
3361
+ id: z4.string(),
3362
+ userId: z4.string(),
3363
+ title: z4.string().nullable(),
3364
+ metadata: z4.string().nullable(),
3365
+ createdAt: z4.number(),
3366
+ updatedAt: z4.number()
3367
+ });
3368
+ var storedChat = chatColumns.transform(toStoredChat);
3369
+ var chatInfo = chatColumns.extend({ messageCount: z4.number(), branchCount: z4.number() }).transform((row) => ({
3370
+ ...toStoredChat(row),
3371
+ messageCount: row.messageCount,
3372
+ branchCount: row.branchCount
3373
+ }));
3374
+ var messageColumns = z4.object({
3375
+ id: z4.string(),
3376
+ chatId: z4.string(),
3377
+ parentId: z4.string().nullable(),
3378
+ name: z4.string(),
3379
+ type: z4.string().nullable(),
3380
+ data: z4.string(),
3381
+ createdAt: z4.number()
3382
+ });
3383
+ var storedMessage = messageColumns.transform(toMessage);
3384
+ var searchResult = messageColumns.extend({ rank: z4.number(), snippet: z4.string() }).transform((row) => ({
3385
+ message: toMessage(row),
3386
+ rank: row.rank,
3387
+ snippet: row.snippet
3388
+ }));
3389
+ var storedBranch = z4.object({
3390
+ id: z4.string(),
3391
+ chatId: z4.string(),
3392
+ name: z4.string(),
3393
+ headMessageId: z4.string().nullable(),
3394
+ isActive: z4.number(),
3395
+ createdAt: z4.number()
3396
+ }).transform((row) => ({
3397
+ id: row.id,
3398
+ chatId: row.chatId,
3399
+ name: row.name,
3400
+ headMessageId: row.headMessageId,
3401
+ isActive: row.isActive === 1,
3402
+ createdAt: row.createdAt
3403
+ }));
3404
+ var branchInfo = z4.object({
3405
+ id: z4.string(),
3406
+ name: z4.string(),
3407
+ headMessageId: z4.string().nullable(),
3408
+ isActive: z4.number(),
3409
+ createdAt: z4.number(),
3410
+ messageCount: z4.number()
3411
+ }).transform((row) => ({
3412
+ id: row.id,
3413
+ name: row.name,
3414
+ headMessageId: row.headMessageId,
3415
+ isActive: row.isActive === 1,
3416
+ messageCount: row.messageCount,
3417
+ createdAt: row.createdAt
3418
+ }));
3419
+ var storedCheckpoint = z4.object({
3420
+ id: z4.string(),
3421
+ chatId: z4.string(),
3422
+ name: z4.string(),
3423
+ messageId: z4.string(),
3424
+ createdAt: z4.number()
3425
+ });
3426
+ var checkpointInfo = z4.object({
3427
+ id: z4.string(),
3428
+ name: z4.string(),
3429
+ messageId: z4.string(),
3430
+ createdAt: z4.number()
3431
+ });
3432
+ var idRow = z4.object({ id: z4.string() });
3433
+ var hasChildrenRow = z4.object({ hasChildren: z4.number() });
3434
+ var graphMessageRow = z4.object({
3435
+ id: z4.string(),
3436
+ parentId: z4.string().nullable(),
3437
+ name: z4.string(),
3438
+ data: z4.string(),
3439
+ createdAt: z4.number()
3440
+ });
3441
+ var graphBranch = z4.object({
3442
+ name: z4.string(),
3443
+ headMessageId: z4.string().nullable(),
3444
+ isActive: z4.number()
3445
+ }).transform((row) => ({
3446
+ name: row.name,
3447
+ headMessageId: row.headMessageId,
3448
+ isActive: row.isActive === 1
3449
+ }));
3450
+ var graphCheckpoint = z4.object({
3451
+ name: z4.string(),
3452
+ messageId: z4.string()
3453
+ });
3454
+ function toStoredChat(row) {
3455
+ return {
3456
+ id: row.id,
3457
+ userId: row.userId,
3458
+ title: row.title ?? void 0,
3459
+ metadata: row.metadata ? parseJsonObject(row.metadata) : void 0,
3460
+ createdAt: row.createdAt,
3461
+ updatedAt: row.updatedAt
3462
+ };
3463
+ }
3464
+ function toMessage(row) {
3465
+ return {
3466
+ id: row.id,
3467
+ chatId: row.chatId,
3468
+ parentId: row.parentId,
3469
+ name: row.name,
3470
+ type: row.type ?? void 0,
3471
+ data: parseJson(row.data),
3472
+ createdAt: row.createdAt
3473
+ };
3474
+ }
3289
3475
  var SqliteContextStore = class extends ContextStore {
3290
3476
  #db;
3291
3477
  #statements = /* @__PURE__ */ new Map();
@@ -3332,70 +3518,49 @@ var SqliteContextStore = class extends ContextStore {
3332
3518
  // ==========================================================================
3333
3519
  async createChat(chat2) {
3334
3520
  return this.#useTransaction(() => {
3335
- const row = this.#db.prepare(
3336
- `INSERT INTO chats (id, userId, title, metadata)
3521
+ const created = storedChat.parse(
3522
+ this.#db.prepare(
3523
+ `INSERT INTO chats (id, userId, title, metadata)
3337
3524
  VALUES (?, ?, ?, ?)
3338
3525
  RETURNING *`
3339
- ).get(
3340
- chat2.id,
3341
- chat2.userId,
3342
- chat2.title ?? null,
3343
- chat2.metadata ? JSON.stringify(chat2.metadata) : null
3526
+ ).get(
3527
+ chat2.id,
3528
+ chat2.userId,
3529
+ chat2.title ?? null,
3530
+ chat2.metadata ? JSON.stringify(chat2.metadata) : null
3531
+ )
3344
3532
  );
3345
3533
  this.#db.prepare(
3346
3534
  `INSERT INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
3347
3535
  VALUES (?, ?, 'main', NULL, 1, ?)`
3348
3536
  ).run(crypto.randomUUID(), chat2.id, Date.now());
3349
- return {
3350
- id: row.id,
3351
- userId: row.userId,
3352
- title: row.title ?? void 0,
3353
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3354
- createdAt: row.createdAt,
3355
- updatedAt: row.updatedAt
3356
- };
3537
+ return created;
3357
3538
  });
3358
3539
  }
3359
3540
  async upsertChat(chat2) {
3360
3541
  return this.#useTransaction(() => {
3361
- const row = this.#db.prepare(
3362
- `INSERT INTO chats (id, userId, title, metadata)
3542
+ const upserted = storedChat.parse(
3543
+ this.#db.prepare(
3544
+ `INSERT INTO chats (id, userId, title, metadata)
3363
3545
  VALUES (?, ?, ?, ?)
3364
3546
  ON CONFLICT(id) DO UPDATE SET id = excluded.id
3365
3547
  RETURNING *`
3366
- ).get(
3367
- chat2.id,
3368
- chat2.userId,
3369
- chat2.title ?? null,
3370
- chat2.metadata ? JSON.stringify(chat2.metadata) : null
3548
+ ).get(
3549
+ chat2.id,
3550
+ chat2.userId,
3551
+ chat2.title ?? null,
3552
+ chat2.metadata ? JSON.stringify(chat2.metadata) : null
3553
+ )
3371
3554
  );
3372
3555
  this.#db.prepare(
3373
3556
  `INSERT OR IGNORE INTO branches (id, chatId, name, headMessageId, isActive, createdAt)
3374
3557
  VALUES (?, ?, 'main', NULL, 1, ?)`
3375
3558
  ).run(crypto.randomUUID(), chat2.id, Date.now());
3376
- return {
3377
- id: row.id,
3378
- userId: row.userId,
3379
- title: row.title ?? void 0,
3380
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3381
- createdAt: row.createdAt,
3382
- updatedAt: row.updatedAt
3383
- };
3559
+ return upserted;
3384
3560
  });
3385
3561
  }
3386
3562
  #getChat(chatId) {
3387
- const row = this.#db.prepare("SELECT * FROM chats WHERE id = ?").get(chatId);
3388
- if (!row) {
3389
- return void 0;
3390
- }
3391
- return {
3392
- id: row.id,
3393
- userId: row.userId,
3394
- title: row.title ?? void 0,
3395
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3396
- createdAt: row.createdAt,
3397
- updatedAt: row.updatedAt
3398
- };
3563
+ return storedChat.optional().parse(this.#db.prepare("SELECT * FROM chats WHERE id = ?").get(chatId));
3399
3564
  }
3400
3565
  async getChat(chatId) {
3401
3566
  return this.#getChat(chatId);
@@ -3419,17 +3584,11 @@ var SqliteContextStore = class extends ContextStore {
3419
3584
  params.push(JSON.stringify(updates.metadata));
3420
3585
  }
3421
3586
  params.push(chatId);
3422
- const row = this.#db.prepare(
3423
- `UPDATE chats SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
3424
- ).get(...params);
3425
- return {
3426
- id: row.id,
3427
- userId: row.userId,
3428
- title: row.title ?? void 0,
3429
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3430
- createdAt: row.createdAt,
3431
- updatedAt: row.updatedAt
3432
- };
3587
+ return storedChat.parse(
3588
+ this.#db.prepare(
3589
+ `UPDATE chats SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
3590
+ ).get(...params)
3591
+ );
3433
3592
  }, "immediate");
3434
3593
  }
3435
3594
  async listChats(options) {
@@ -3456,8 +3615,9 @@ var SqliteContextStore = class extends ContextStore {
3456
3615
  params.push(options.offset);
3457
3616
  }
3458
3617
  }
3459
- const rows = this.#db.prepare(
3460
- `SELECT
3618
+ return z4.array(chatInfo).parse(
3619
+ this.#db.prepare(
3620
+ `SELECT
3461
3621
  c.id,
3462
3622
  c.userId,
3463
3623
  c.title,
@@ -3472,21 +3632,14 @@ var SqliteContextStore = class extends ContextStore {
3472
3632
  ${whereClause}
3473
3633
  GROUP BY c.id
3474
3634
  ORDER BY c.updatedAt DESC${limitClause}`
3475
- ).all(...params);
3476
- return rows.map((row) => ({
3477
- id: row.id,
3478
- userId: row.userId,
3479
- title: row.title ?? void 0,
3480
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
3481
- messageCount: row.messageCount,
3482
- branchCount: row.branchCount,
3483
- createdAt: row.createdAt,
3484
- updatedAt: row.updatedAt
3485
- }));
3635
+ ).all(...params)
3636
+ );
3486
3637
  }
3487
3638
  async deleteChat(chatId, options) {
3488
3639
  return this.#useTransaction(() => {
3489
- const messageIds = this.#db.prepare("SELECT id FROM messages WHERE chatId = ?").all(chatId);
3640
+ const messageIds = z4.array(idRow).parse(
3641
+ this.#db.prepare("SELECT id FROM messages WHERE chatId = ?").all(chatId)
3642
+ );
3490
3643
  let sql = "DELETE FROM chats WHERE id = ?";
3491
3644
  const params = [chatId];
3492
3645
  if (options?.userId !== void 0) {
@@ -3556,25 +3709,12 @@ var SqliteContextStore = class extends ContextStore {
3556
3709
  }
3557
3710
  }
3558
3711
  async getMessage(messageId) {
3559
- const row = this.#stmt("SELECT * FROM messages WHERE id = ?").get(
3560
- messageId
3561
- );
3562
- if (!row) {
3563
- return void 0;
3564
- }
3565
- return {
3566
- id: row.id,
3567
- chatId: row.chatId,
3568
- parentId: row.parentId,
3569
- name: row.name,
3570
- type: row.type ?? void 0,
3571
- data: JSON.parse(row.data),
3572
- createdAt: row.createdAt
3573
- };
3712
+ return storedMessage.optional().parse(this.#stmt("SELECT * FROM messages WHERE id = ?").get(messageId));
3574
3713
  }
3575
3714
  async getMessageChain(headId) {
3576
- const rows = this.#stmt(
3577
- `WITH RECURSIVE chain AS (
3715
+ return z4.array(storedMessage).parse(
3716
+ this.#stmt(
3717
+ `WITH RECURSIVE chain AS (
3578
3718
  SELECT *, 0 as depth FROM messages WHERE id = ?
3579
3719
  UNION ALL
3580
3720
  SELECT m.*, c.depth + 1 FROM messages m
@@ -3583,21 +3723,15 @@ var SqliteContextStore = class extends ContextStore {
3583
3723
  )
3584
3724
  SELECT * FROM chain
3585
3725
  ORDER BY depth DESC`
3586
- ).all(headId);
3587
- return rows.map((row) => ({
3588
- id: row.id,
3589
- chatId: row.chatId,
3590
- parentId: row.parentId,
3591
- name: row.name,
3592
- type: row.type ?? void 0,
3593
- data: JSON.parse(row.data),
3594
- createdAt: row.createdAt
3595
- }));
3726
+ ).all(headId)
3727
+ );
3596
3728
  }
3597
3729
  async hasChildren(messageId) {
3598
- const row = this.#stmt(
3599
- "SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = ?) as hasChildren"
3600
- ).get(messageId);
3730
+ const row = hasChildrenRow.parse(
3731
+ this.#stmt(
3732
+ "SELECT EXISTS(SELECT 1 FROM messages WHERE parentId = ?) as hasChildren"
3733
+ ).get(messageId)
3734
+ );
3601
3735
  return row.hasChildren === 1;
3602
3736
  }
3603
3737
  async getMessages(chatId) {
@@ -3628,34 +3762,16 @@ var SqliteContextStore = class extends ContextStore {
3628
3762
  );
3629
3763
  }
3630
3764
  async getBranch(chatId, name) {
3631
- const row = this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND name = ?").get(chatId, name);
3632
- if (!row) {
3633
- return void 0;
3634
- }
3635
- return {
3636
- id: row.id,
3637
- chatId: row.chatId,
3638
- name: row.name,
3639
- headMessageId: row.headMessageId,
3640
- isActive: row.isActive === 1,
3641
- createdAt: row.createdAt
3642
- };
3765
+ return storedBranch.optional().parse(
3766
+ this.#db.prepare("SELECT * FROM branches WHERE chatId = ? AND name = ?").get(chatId, name)
3767
+ );
3643
3768
  }
3644
3769
  async getActiveBranch(chatId) {
3645
- const row = this.#stmt(
3646
- "SELECT * FROM branches WHERE chatId = ? AND isActive = 1"
3647
- ).get(chatId);
3648
- if (!row) {
3649
- return void 0;
3650
- }
3651
- return {
3652
- id: row.id,
3653
- chatId: row.chatId,
3654
- name: row.name,
3655
- headMessageId: row.headMessageId,
3656
- isActive: true,
3657
- createdAt: row.createdAt
3658
- };
3770
+ return storedBranch.optional().parse(
3771
+ this.#stmt(
3772
+ "SELECT * FROM branches WHERE chatId = ? AND isActive = 1"
3773
+ ).get(chatId)
3774
+ );
3659
3775
  }
3660
3776
  async setActiveBranch(chatId, branchId) {
3661
3777
  this.#db.prepare("UPDATE branches SET isActive = 0 WHERE chatId = ?").run(chatId);
@@ -3668,8 +3784,9 @@ var SqliteContextStore = class extends ContextStore {
3668
3784
  return result.changes > 0;
3669
3785
  }
3670
3786
  async listBranches(chatId) {
3671
- const rows = this.#db.prepare(
3672
- `SELECT
3787
+ return z4.array(branchInfo).parse(
3788
+ this.#db.prepare(
3789
+ `SELECT
3673
3790
  b.id,
3674
3791
  b.name,
3675
3792
  b.headMessageId,
@@ -3690,15 +3807,8 @@ var SqliteContextStore = class extends ContextStore {
3690
3807
  FROM branches b
3691
3808
  WHERE b.chatId = ?
3692
3809
  ORDER BY b.createdAt ASC`
3693
- ).all(chatId);
3694
- return rows.map((row) => ({
3695
- id: row.id,
3696
- name: row.name,
3697
- headMessageId: row.headMessageId,
3698
- isActive: row.isActive === 1,
3699
- messageCount: row.messageCount,
3700
- createdAt: row.createdAt
3701
- }));
3810
+ ).all(chatId)
3811
+ );
3702
3812
  }
3703
3813
  // ==========================================================================
3704
3814
  // Checkpoint Operations
@@ -3719,31 +3829,19 @@ var SqliteContextStore = class extends ContextStore {
3719
3829
  );
3720
3830
  }
3721
3831
  async getCheckpoint(chatId, name) {
3722
- const row = this.#db.prepare("SELECT * FROM checkpoints WHERE chatId = ? AND name = ?").get(chatId, name);
3723
- if (!row) {
3724
- return void 0;
3725
- }
3726
- return {
3727
- id: row.id,
3728
- chatId: row.chatId,
3729
- name: row.name,
3730
- messageId: row.messageId,
3731
- createdAt: row.createdAt
3732
- };
3832
+ return storedCheckpoint.optional().parse(
3833
+ this.#db.prepare("SELECT * FROM checkpoints WHERE chatId = ? AND name = ?").get(chatId, name)
3834
+ );
3733
3835
  }
3734
3836
  async listCheckpoints(chatId) {
3735
- const rows = this.#db.prepare(
3736
- `SELECT id, name, messageId, createdAt
3837
+ return z4.array(checkpointInfo).parse(
3838
+ this.#db.prepare(
3839
+ `SELECT id, name, messageId, createdAt
3737
3840
  FROM checkpoints
3738
3841
  WHERE chatId = ?
3739
3842
  ORDER BY createdAt DESC`
3740
- ).all(chatId);
3741
- return rows.map((row) => ({
3742
- id: row.id,
3743
- name: row.name,
3744
- messageId: row.messageId,
3745
- createdAt: row.createdAt
3746
- }));
3843
+ ).all(chatId)
3844
+ );
3747
3845
  }
3748
3846
  async deleteCheckpoint(chatId, name) {
3749
3847
  this.#db.prepare("DELETE FROM checkpoints WHERE chatId = ? AND name = ?").run(chatId, name);
@@ -3778,31 +3876,20 @@ var SqliteContextStore = class extends ContextStore {
3778
3876
  }
3779
3877
  sql += " ORDER BY fts.rank LIMIT ?";
3780
3878
  params.push(limit);
3781
- const rows = this.#db.prepare(sql).all(...params);
3782
- return rows.map((row) => ({
3783
- message: {
3784
- id: row.id,
3785
- chatId: row.chatId,
3786
- parentId: row.parentId,
3787
- name: row.name,
3788
- type: row.type ?? void 0,
3789
- data: JSON.parse(row.data),
3790
- createdAt: row.createdAt
3791
- },
3792
- rank: row.rank,
3793
- snippet: row.snippet
3794
- }));
3879
+ return z4.array(searchResult).parse(this.#db.prepare(sql).all(...params));
3795
3880
  }
3796
3881
  // ==========================================================================
3797
3882
  // Visualization Operations
3798
3883
  // ==========================================================================
3799
3884
  async getGraph(chatId) {
3800
- const messageRows = this.#db.prepare(
3801
- `SELECT id, parentId, name, data, createdAt
3885
+ const messageRows = z4.array(graphMessageRow).parse(
3886
+ this.#db.prepare(
3887
+ `SELECT id, parentId, name, data, createdAt
3802
3888
  FROM messages
3803
3889
  WHERE chatId = ?
3804
3890
  ORDER BY createdAt ASC`
3805
- ).all(chatId);
3891
+ ).all(chatId)
3892
+ );
3806
3893
  const nodes = messageRows.map((row) => {
3807
3894
  const data = JSON.parse(row.data);
3808
3895
  const content = typeof data === "string" ? data : Array.isArray(data.parts) ? data.parts.filter((p) => p.type === "text").map((p) => p.text).join(" ") : JSON.stringify(data);
@@ -3814,27 +3901,22 @@ var SqliteContextStore = class extends ContextStore {
3814
3901
  createdAt: row.createdAt
3815
3902
  };
3816
3903
  });
3817
- const branchRows = this.#db.prepare(
3818
- `SELECT name, headMessageId, isActive
3904
+ const branches = z4.array(graphBranch).parse(
3905
+ this.#db.prepare(
3906
+ `SELECT name, headMessageId, isActive
3819
3907
  FROM branches
3820
3908
  WHERE chatId = ?
3821
3909
  ORDER BY createdAt ASC`
3822
- ).all(chatId);
3823
- const branches = branchRows.map((row) => ({
3824
- name: row.name,
3825
- headMessageId: row.headMessageId,
3826
- isActive: row.isActive === 1
3827
- }));
3828
- const checkpointRows = this.#db.prepare(
3829
- `SELECT name, messageId
3910
+ ).all(chatId)
3911
+ );
3912
+ const checkpoints = z4.array(graphCheckpoint).parse(
3913
+ this.#db.prepare(
3914
+ `SELECT name, messageId
3830
3915
  FROM checkpoints
3831
3916
  WHERE chatId = ?
3832
3917
  ORDER BY createdAt ASC`
3833
- ).all(chatId);
3834
- const checkpoints = checkpointRows.map((row) => ({
3835
- name: row.name,
3836
- messageId: row.messageId
3837
- }));
3918
+ ).all(chatId)
3919
+ );
3838
3920
  return {
3839
3921
  chatId,
3840
3922
  nodes,
@@ -3933,7 +4015,7 @@ function mergeLanguageModelUsage(current, next) {
3933
4015
  };
3934
4016
  }
3935
4017
  function isAvailableSkill(value) {
3936
- return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
4018
+ return isRecord(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3937
4019
  }
3938
4020
  function isEmptyAssistantPlaceholder(message2) {
3939
4021
  return message2.role === "assistant" && message2.parts.length === 0;
@@ -4682,7 +4764,7 @@ var ContextEngine = class _ContextEngine {
4682
4764
  const fragmentIndex = pending.findLastIndex((fragment3) => {
4683
4765
  if (fragment3.name !== "user") return false;
4684
4766
  const encoded = fragment3.codec?.encode();
4685
- return !encoded || !isSyntheticReminderMessage(encoded);
4767
+ return !isUIMessage(encoded) || !isSyntheticReminderMessage(encoded);
4686
4768
  });
4687
4769
  if (fragmentIndex < 0) return;
4688
4770
  const fragment2 = pending[fragmentIndex];
@@ -4710,7 +4792,7 @@ var ContextEngine = class _ContextEngine {
4710
4792
  };
4711
4793
  if (onceIds.length > 0) {
4712
4794
  carrier.metadata = {
4713
- ...carrier.metadata,
4795
+ ...isRecord(carrier.metadata) ? carrier.metadata : {},
4714
4796
  onceIds
4715
4797
  };
4716
4798
  }
@@ -4842,12 +4924,13 @@ var ContextEngine = class _ContextEngine {
4842
4924
  `Model "${modelId}" not found. Call load() first or check model ID.`
4843
4925
  );
4844
4926
  }
4927
+ const inputPrice = inputPricePerMillion(model);
4845
4928
  const tokenizer = registry.getTokenizer(modelId);
4846
4929
  const fragmentEstimates = [];
4847
4930
  for (const fragment2 of this.#renderableFragments) {
4848
4931
  const rendered = renderer.render([fragment2]);
4849
4932
  const tokens = tokenizer.count(rendered);
4850
- const cost = tokens / 1e6 * model.cost.input;
4933
+ const cost = tokens / 1e6 * inputPrice;
4851
4934
  fragmentEstimates.push({
4852
4935
  id: fragment2.id,
4853
4936
  name: fragment2.name,
@@ -4862,7 +4945,7 @@ var ContextEngine = class _ContextEngine {
4862
4945
  for (const msg of chain) {
4863
4946
  const content = estimateMessageContent(msg.data);
4864
4947
  const tokens = tokenizer.count(content);
4865
- const cost = tokens / 1e6 * model.cost.input;
4948
+ const cost = tokens / 1e6 * inputPrice;
4866
4949
  fragmentEstimates.push({
4867
4950
  name: msg.name,
4868
4951
  id: msg.id,
@@ -4876,7 +4959,7 @@ var ContextEngine = class _ContextEngine {
4876
4959
  fragment2.codec ? fragment2.codec.encode() : getFragmentData(fragment2)
4877
4960
  );
4878
4961
  const tokens = tokenizer.count(content);
4879
- const cost = tokens / 1e6 * model.cost.input;
4962
+ const cost = tokens / 1e6 * inputPrice;
4880
4963
  fragmentEstimates.push({
4881
4964
  name: fragment2.name,
4882
4965
  id: fragment2.id,
@@ -5600,7 +5683,7 @@ Examples:
5600
5683
  - "help me write an essay about space" -> Space Essay Help
5601
5684
  - "hi" -> New Conversation
5602
5685
  - "debug my python code" -> Python Debugging`;
5603
- var titleSchema = z2.object({ title: z2.string() });
5686
+ var titleSchema = z5.object({ title: z5.string() });
5604
5687
  var TitleGenerator = class {
5605
5688
  #context;
5606
5689
  constructor(options) {
@@ -5706,18 +5789,16 @@ async function chat(agent2, ...args) {
5706
5789
  await context.writeAssistantSegment(responseMessage);
5707
5790
  },
5708
5791
  onEnd: async ({ responseMessage, isAborted }) => {
5709
- let message2 = responseMessage;
5710
- if (isAborted) {
5711
- message2 = { ...message2, parts: sanitizeAbortedParts(message2.parts) };
5712
- }
5713
- const finalMetadata = await options?.finalAssistantMetadata?.(message2);
5792
+ const settled = isAborted ? {
5793
+ ...responseMessage,
5794
+ parts: sanitizeAbortedParts(responseMessage.parts)
5795
+ } : responseMessage;
5796
+ const finalMetadata = await options?.finalAssistantMetadata?.(settled);
5714
5797
  const mergedMetadata = {
5715
- ...message2.metadata ?? {},
5798
+ ...isRecord(settled.metadata) ? settled.metadata : {},
5716
5799
  ...finalMetadata ?? {}
5717
5800
  };
5718
- if (Object.keys(mergedMetadata).length > 0) {
5719
- message2 = { ...message2, metadata: mergedMetadata };
5720
- }
5801
+ const message2 = Object.keys(mergedMetadata).length > 0 ? { ...settled, metadata: mergedMetadata } : settled;
5721
5802
  await context.writeAssistantSegment(message2);
5722
5803
  const usage = await result?.usage;
5723
5804
  if (usage !== void 0) {
@@ -5754,11 +5835,6 @@ async function chat(agent2, ...args) {
5754
5835
  }
5755
5836
  });
5756
5837
  }
5757
- var TERMINAL_TOOL_STATES = /* @__PURE__ */ new Set([
5758
- "output-available",
5759
- "output-error",
5760
- "output-denied"
5761
- ]);
5762
5838
  function sanitizeAbortedParts(parts) {
5763
5839
  const sanitized = [];
5764
5840
  for (const part of parts) {
@@ -5766,16 +5842,24 @@ function sanitizeAbortedParts(parts) {
5766
5842
  sanitized.push(part);
5767
5843
  continue;
5768
5844
  }
5769
- if (TERMINAL_TOOL_STATES.has(part.state)) {
5770
- sanitized.push(part);
5771
- continue;
5845
+ switch (part.state) {
5846
+ case "output-available":
5847
+ case "output-error":
5848
+ case "output-denied":
5849
+ sanitized.push(part);
5850
+ break;
5851
+ case "input-streaming":
5852
+ break;
5853
+ default: {
5854
+ const { approval, ...pending } = part;
5855
+ sanitized.push({
5856
+ ...pending,
5857
+ state: "output-error",
5858
+ errorText: "Cancelled by user",
5859
+ ...approval?.approved === true ? { approval: { ...approval, approved: true } } : {}
5860
+ });
5861
+ }
5772
5862
  }
5773
- if (part.state === "input-streaming") continue;
5774
- sanitized.push({
5775
- ...part,
5776
- state: "output-error",
5777
- errorText: "Cancelled by user"
5778
- });
5779
5863
  }
5780
5864
  return sanitized;
5781
5865
  }
@@ -5809,6 +5893,9 @@ async function makeTitle(options) {
5809
5893
  return result?.title ?? null;
5810
5894
  }
5811
5895
 
5896
+ // packages/context/src/lib/codec/serialized-fragments.ts
5897
+ import { z as z6 } from "zod";
5898
+
5812
5899
  // packages/context/src/lib/fragments/user.ts
5813
5900
  function identity(input) {
5814
5901
  return {
@@ -5926,118 +6013,198 @@ function toFragmentData(value, options) {
5926
6013
  ])
5927
6014
  );
5928
6015
  }
6016
+ if (!isFragmentData(value)) {
6017
+ throw new Error(`Unsupported serialized value of type ${typeof value}`);
6018
+ }
5929
6019
  return value;
5930
6020
  }
6021
+ function builtInEntry(schema, build) {
6022
+ return {
6023
+ toFragment: (input, options) => {
6024
+ const parsed = schema.safeParse(input);
6025
+ if (!parsed.success) {
6026
+ throw new Error(
6027
+ `Invalid serialized ${input.type} fragment: ${z6.prettifyError(parsed.error)}`
6028
+ );
6029
+ }
6030
+ return build(parsed.data, options);
6031
+ }
6032
+ };
6033
+ }
6034
+ var nestedPolicies = z6.array(z6.unknown()).optional();
5931
6035
  var builtInSerializedRegistry = {
5932
- term: {
5933
- toFragment: (input) => term(input.name, input.definition)
5934
- },
5935
- hint: {
5936
- toFragment: (input) => hint(input.text)
5937
- },
5938
- guardrail: {
5939
- toFragment: (input) => guardrail({
6036
+ term: builtInEntry(
6037
+ z6.object({ name: z6.string(), definition: z6.string() }),
6038
+ (input) => term(input.name, input.definition)
6039
+ ),
6040
+ hint: builtInEntry(
6041
+ z6.object({ text: z6.string() }),
6042
+ (input) => hint(input.text)
6043
+ ),
6044
+ guardrail: builtInEntry(
6045
+ z6.object({
6046
+ rule: z6.string(),
6047
+ reason: z6.string().optional(),
6048
+ action: z6.string().optional()
6049
+ }),
6050
+ (input) => guardrail({
5940
6051
  rule: input.rule,
5941
6052
  reason: input.reason,
5942
6053
  action: input.action
5943
6054
  })
5944
- },
5945
- explain: {
5946
- toFragment: (input) => explain({
6055
+ ),
6056
+ explain: builtInEntry(
6057
+ z6.object({
6058
+ concept: z6.string(),
6059
+ explanation: z6.string(),
6060
+ therefore: z6.string().optional()
6061
+ }),
6062
+ (input) => explain({
5947
6063
  concept: input.concept,
5948
6064
  explanation: input.explanation,
5949
6065
  therefore: input.therefore
5950
6066
  })
5951
- },
5952
- example: {
5953
- toFragment: (input) => example({
6067
+ ),
6068
+ example: builtInEntry(
6069
+ z6.object({
6070
+ question: z6.string(),
6071
+ answer: z6.string(),
6072
+ note: z6.string().optional()
6073
+ }),
6074
+ (input) => example({
5954
6075
  question: input.question,
5955
6076
  answer: input.answer,
5956
6077
  note: input.note
5957
6078
  })
5958
- },
5959
- clarification: {
5960
- toFragment: (input) => clarification({
6079
+ ),
6080
+ clarification: builtInEntry(
6081
+ z6.object({ when: z6.string(), ask: z6.string(), reason: z6.string() }),
6082
+ (input) => clarification({
5961
6083
  when: input.when,
5962
6084
  ask: input.ask,
5963
6085
  reason: input.reason
5964
6086
  })
5965
- },
5966
- workflow: {
5967
- toFragment: (input) => workflow({
6087
+ ),
6088
+ workflow: builtInEntry(
6089
+ z6.object({
6090
+ task: z6.string(),
6091
+ steps: z6.array(z6.string()),
6092
+ triggers: z6.array(z6.string()).optional(),
6093
+ notes: z6.string().optional()
6094
+ }),
6095
+ (input) => workflow({
5968
6096
  task: input.task,
5969
6097
  steps: input.steps,
5970
6098
  triggers: input.triggers,
5971
6099
  notes: input.notes
5972
6100
  })
5973
- },
5974
- quirk: {
5975
- toFragment: (input) => quirk({
6101
+ ),
6102
+ quirk: builtInEntry(
6103
+ z6.object({ issue: z6.string(), workaround: z6.string() }),
6104
+ (input) => quirk({
5976
6105
  issue: input.issue,
5977
6106
  workaround: input.workaround
5978
6107
  })
5979
- },
5980
- styleGuide: {
5981
- toFragment: (input) => styleGuide({
6108
+ ),
6109
+ styleGuide: builtInEntry(
6110
+ z6.object({
6111
+ prefer: z6.string(),
6112
+ never: z6.string().optional(),
6113
+ always: z6.string().optional()
6114
+ }),
6115
+ (input) => styleGuide({
5982
6116
  prefer: input.prefer,
5983
6117
  never: input.never,
5984
6118
  always: input.always
5985
6119
  })
5986
- },
5987
- analogy: {
5988
- toFragment: (input) => analogy({
6120
+ ),
6121
+ analogy: builtInEntry(
6122
+ z6.object({
6123
+ concepts: z6.array(z6.string()),
6124
+ relationship: z6.string(),
6125
+ insight: z6.string().optional(),
6126
+ therefore: z6.string().optional(),
6127
+ pitfall: z6.string().optional()
6128
+ }),
6129
+ (input) => analogy({
5989
6130
  concepts: input.concepts,
5990
6131
  relationship: input.relationship,
5991
6132
  insight: input.insight,
5992
6133
  therefore: input.therefore,
5993
6134
  pitfall: input.pitfall
5994
6135
  })
5995
- },
5996
- glossary: {
5997
- toFragment: (input) => glossary(input.entries)
5998
- },
5999
- role: {
6000
- toFragment: (input) => role(input.content)
6001
- },
6002
- principle: {
6003
- toFragment: (input, options) => principle({
6136
+ ),
6137
+ glossary: builtInEntry(
6138
+ z6.object({ entries: z6.record(z6.string(), z6.string()) }),
6139
+ (input) => glossary(input.entries)
6140
+ ),
6141
+ role: builtInEntry(
6142
+ z6.object({ content: z6.string() }),
6143
+ (input) => role(input.content)
6144
+ ),
6145
+ principle: builtInEntry(
6146
+ z6.object({
6147
+ title: z6.string(),
6148
+ description: z6.string(),
6149
+ policies: nestedPolicies
6150
+ }),
6151
+ (input, options) => principle({
6004
6152
  title: input.title,
6005
6153
  description: input.description,
6006
6154
  policies: input.policies?.map((item) => toFragmentData(item, options))
6007
6155
  })
6008
- },
6009
- policy: {
6010
- toFragment: (input, options) => policy({
6156
+ ),
6157
+ policy: builtInEntry(
6158
+ z6.object({
6159
+ rule: z6.string(),
6160
+ before: z6.string().optional(),
6161
+ reason: z6.string().optional(),
6162
+ policies: nestedPolicies
6163
+ }),
6164
+ (input, options) => policy({
6011
6165
  rule: input.rule,
6012
6166
  before: input.before,
6013
6167
  reason: input.reason,
6014
6168
  policies: input.policies?.map((item) => toFragmentData(item, options))
6015
6169
  })
6016
- },
6017
- identity: {
6018
- toFragment: (input) => identity({
6170
+ ),
6171
+ identity: builtInEntry(
6172
+ z6.object({ name: z6.string().optional(), role: z6.string().optional() }),
6173
+ (input) => identity({
6019
6174
  name: input.name,
6020
6175
  role: input.role
6021
6176
  })
6022
- },
6023
- persona: {
6024
- toFragment: (input) => persona({
6177
+ ),
6178
+ persona: builtInEntry(
6179
+ z6.object({
6180
+ name: z6.string(),
6181
+ role: z6.string().optional(),
6182
+ objective: z6.string().optional(),
6183
+ tone: z6.string().optional()
6184
+ }),
6185
+ (input) => persona({
6025
6186
  name: input.name,
6026
6187
  role: input.role,
6027
6188
  objective: input.objective,
6028
6189
  tone: input.tone
6029
6190
  })
6030
- },
6031
- alias: {
6032
- toFragment: (input) => alias(input.term, input.meaning)
6033
- },
6034
- preference: {
6035
- toFragment: (input) => preference(input.aspect, input.value)
6036
- },
6037
- correction: {
6038
- toFragment: (input) => correction(input.subject, input.clarification)
6039
- }
6191
+ ),
6192
+ alias: builtInEntry(
6193
+ z6.object({ term: z6.string(), meaning: z6.string() }),
6194
+ (input) => alias(input.term, input.meaning)
6195
+ ),
6196
+ preference: builtInEntry(
6197
+ z6.object({ aspect: z6.string(), value: z6.string() }),
6198
+ (input) => preference(input.aspect, input.value)
6199
+ ),
6200
+ correction: builtInEntry(
6201
+ z6.object({ subject: z6.string(), clarification: z6.string() }),
6202
+ (input) => correction(input.subject, input.clarification)
6203
+ )
6040
6204
  };
6205
+ function isBuiltInSerializedType(type) {
6206
+ return Object.hasOwn(builtInSerializedRegistry, type);
6207
+ }
6041
6208
  var messageLikeTypes = /* @__PURE__ */ new Set(["user", "assistant", "message"]);
6042
6209
  function findCustomSerializedFragment(fragment2, options) {
6043
6210
  if (!options?.registry) {
@@ -6057,7 +6224,7 @@ function toFragment(input, options) {
6057
6224
  "Message fragments are not supported by serialized fragment conversion"
6058
6225
  );
6059
6226
  }
6060
- const entry = options?.registry?.[input.type] ?? builtInSerializedRegistry[input.type];
6227
+ const entry = options?.registry?.[input.type] ?? (isBuiltInSerializedType(input.type) ? builtInSerializedRegistry[input.type] : void 0);
6061
6228
  if (!entry) {
6062
6229
  throw new Error(`Unsupported serialized fragment type: ${input.type}`);
6063
6230
  }
@@ -6082,7 +6249,7 @@ function fromFragment(fragment2, options) {
6082
6249
  }
6083
6250
  return encoded;
6084
6251
  }
6085
- if (!builtInSerializedRegistry[fragment2.name]) {
6252
+ if (!isBuiltInSerializedType(fragment2.name)) {
6086
6253
  throw new Error(`Unsupported fragment name: ${fragment2.name}`);
6087
6254
  }
6088
6255
  throw new Error(`Fragment "${fragment2.name}" is missing codec`);
@@ -6090,11 +6257,11 @@ function fromFragment(fragment2, options) {
6090
6257
 
6091
6258
  // packages/context/src/lib/fragments/plan.ts
6092
6259
  import dedent2 from "dedent";
6093
- import z4 from "zod";
6260
+ import z8 from "zod";
6094
6261
 
6095
6262
  // packages/context/src/lib/fragments/plan-shared.ts
6096
6263
  import dedent from "dedent";
6097
- import z3 from "zod";
6264
+ import z7 from "zod";
6098
6265
  var PLAN_FILE_PATH = "/workspace/.deepagents/plan.json";
6099
6266
  var PLAN_FOUNDATION_INSTRUCTIONS = dedent`
6100
6267
  You own the plan. The user is not required to provide a structured objective, success criteria, constraints, or task breakdown.
@@ -6125,20 +6292,20 @@ var PLAN_FOUNDATION_INSTRUCTIONS = dedent`
6125
6292
  var PLAN_REVIEW_INSTRUCTIONS = dedent`
6126
6293
  Whenever plan review fires, record lastReview before continuing. Its revision is the plan revision that was evaluated. If the decision is revise or replace, increment the plan revision when applying the resulting changes while preserving the evaluated revision in lastReview.
6127
6294
  `;
6128
- var nonEmptyString = z3.string().trim().min(1);
6129
- var statementBasis = z3.enum([
6295
+ var nonEmptyString = z7.string().trim().min(1);
6296
+ var statementBasis = z7.enum([
6130
6297
  "explicit_requirement",
6131
6298
  "discovered_constraint",
6132
6299
  "inference",
6133
6300
  "assumption"
6134
6301
  ]);
6135
- var evidence = z3.strictObject({
6302
+ var evidence = z7.strictObject({
6136
6303
  summary: nonEmptyString,
6137
6304
  source: nonEmptyString
6138
6305
  });
6139
- var lastReview = z3.strictObject({
6140
- revision: z3.number().int().positive(),
6141
- decision: z3.enum(["continue", "revise", "replace", "complete", "blocked"]),
6306
+ var lastReview = z7.strictObject({
6307
+ revision: z7.number().int().positive(),
6308
+ decision: z7.enum(["continue", "revise", "replace", "complete", "blocked"]),
6142
6309
  summary: nonEmptyString
6143
6310
  });
6144
6311
  function parsePlanSchema(schema, value) {
@@ -6272,29 +6439,29 @@ var EXECUTION_REVIEW_REMINDER = [
6272
6439
  "If yes, continue. If not, revise it before taking another action.",
6273
6440
  "Before claiming completion, verify the success criteria against evidence."
6274
6441
  ].join("\n");
6275
- var statement = z4.strictObject({
6442
+ var statement = z8.strictObject({
6276
6443
  text: nonEmptyString,
6277
6444
  basis: statementBasis,
6278
6445
  source: nonEmptyString
6279
6446
  });
6280
6447
  var successCriterion = statement.extend({
6281
6448
  id: nonEmptyString,
6282
- evidence: z4.array(evidence)
6449
+ evidence: z8.array(evidence)
6283
6450
  });
6284
- var task = z4.strictObject({
6451
+ var task = z8.strictObject({
6285
6452
  id: nonEmptyString,
6286
6453
  title: nonEmptyString,
6287
- status: z4.enum(["pending", "in_progress", "completed"]),
6288
- blockedBy: z4.array(nonEmptyString),
6289
- evidence: z4.array(evidence)
6454
+ status: z8.enum(["pending", "in_progress", "completed"]),
6455
+ blockedBy: z8.array(nonEmptyString),
6456
+ evidence: z8.array(evidence)
6290
6457
  });
6291
- var executionPlanState = z4.strictObject({
6292
- revision: z4.number().int().positive(),
6458
+ var executionPlanState = z8.strictObject({
6459
+ revision: z8.number().int().positive(),
6293
6460
  objective: statement,
6294
- successCriteria: z4.array(successCriterion).min(1),
6295
- constraints: z4.array(statement),
6296
- assumptions: z4.array(statement),
6297
- tasks: z4.array(task),
6461
+ successCriteria: z8.array(successCriterion).min(1),
6462
+ constraints: z8.array(statement),
6463
+ assumptions: z8.array(statement),
6464
+ tasks: z8.array(task),
6298
6465
  lastReview: lastReview.optional()
6299
6466
  });
6300
6467
  function validateExecutionPlan(state) {
@@ -6601,7 +6768,7 @@ function socraticPrompting() {
6601
6768
 
6602
6769
  // packages/context/src/lib/fragments/socratic-plan.ts
6603
6770
  import dedent3 from "dedent";
6604
- import z5 from "zod";
6771
+ import z9 from "zod";
6605
6772
  var SOCRATIC_PLAN_INSTRUCTIONS = dedent3`
6606
6773
  Use a Socratic plan as an evolving question-and-answer inquiry, not an execution task list whose titles merely end in question marks. It has this shape:
6607
6774
  The only top-level keys are revision, objective, successCriteria, constraints, assumptions, inquiries, and lastReview.
@@ -6634,13 +6801,13 @@ var SOCRATIC_REVIEW_REMINDER = [
6634
6801
  var questionText = nonEmptyString.refine((text) => text.endsWith("?"), {
6635
6802
  message: "must end with a question mark"
6636
6803
  });
6637
- var answer = z5.strictObject({
6804
+ var answer = z9.strictObject({
6638
6805
  text: nonEmptyString,
6639
6806
  basis: statementBasis,
6640
6807
  source: nonEmptyString,
6641
- evidence: z5.array(evidence).min(1)
6808
+ evidence: z9.array(evidence).min(1)
6642
6809
  });
6643
- var question = z5.strictObject({
6810
+ var question = z9.strictObject({
6644
6811
  question: questionText,
6645
6812
  basis: statementBasis,
6646
6813
  source: nonEmptyString,
@@ -6649,20 +6816,20 @@ var question = z5.strictObject({
6649
6816
  var successQuestion = question.extend({ id: nonEmptyString });
6650
6817
  var inquiry = question.extend({
6651
6818
  id: nonEmptyString,
6652
- phase: z5.enum(["domain", "case", "bridge"]),
6653
- status: z5.enum(["open", "answering", "answered"]),
6654
- blockedBy: z5.array(nonEmptyString)
6819
+ phase: z9.enum(["domain", "case", "bridge"]),
6820
+ status: z9.enum(["open", "answering", "answered"]),
6821
+ blockedBy: z9.array(nonEmptyString)
6655
6822
  });
6656
6823
  var socraticLastReview = lastReview.extend({
6657
6824
  nextQuestionId: nonEmptyString.nullable()
6658
6825
  });
6659
- var socraticPlanState = z5.strictObject({
6660
- revision: z5.number().int().positive(),
6826
+ var socraticPlanState = z9.strictObject({
6827
+ revision: z9.number().int().positive(),
6661
6828
  objective: question,
6662
- successCriteria: z5.array(successQuestion).min(1),
6663
- constraints: z5.array(question),
6664
- assumptions: z5.array(question),
6665
- inquiries: z5.array(inquiry).min(1),
6829
+ successCriteria: z9.array(successQuestion).min(1),
6830
+ constraints: z9.array(question),
6831
+ assumptions: z9.array(question),
6832
+ inquiries: z9.array(inquiry).min(1),
6666
6833
  lastReview: socraticLastReview.nullable().optional()
6667
6834
  });
6668
6835
  function validateSocraticPlan(state) {
@@ -6943,268 +7110,46 @@ function render(tag, ...fragments) {
6943
7110
  return renderer.render([wrapped]);
6944
7111
  }
6945
7112
 
6946
- // packages/context/src/lib/sandbox/agent-os-sandbox.ts
6947
- import { PassThrough, Readable } from "node:stream";
6948
-
6949
- // packages/context/src/lib/sandbox/read-file.ts
6950
- var decoder = new TextDecoder();
6951
- function readFileContent(bytes, options) {
6952
- const content = options?.encoding === "binary" ? bytes : decoder.decode(bytes);
6953
- return content;
6954
- }
7113
+ // packages/context/src/lib/sandbox/apple-container-sandbox.ts
7114
+ import spawn3, { SubprocessError as SubprocessError3 } from "nano-spawn";
7115
+ import { spawn as childSpawn2 } from "node:child_process";
7116
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
7117
+ import { tmpdir } from "node:os";
7118
+ import { join } from "node:path";
7119
+ import z10 from "zod";
6955
7120
 
6956
- // packages/context/src/lib/sandbox/agent-os-sandbox.ts
6957
- var AgentOsSandboxError = class extends Error {
6958
- constructor(message2) {
7121
+ // packages/context/src/lib/sandbox/container-sandbox-errors.ts
7122
+ var ContainerSandboxError = class extends Error {
7123
+ containerId;
7124
+ constructor(message2, containerId) {
6959
7125
  super(message2);
6960
- this.name = "AgentOsSandboxError";
7126
+ this.name = "ContainerSandboxError";
7127
+ this.containerId = containerId;
6961
7128
  }
6962
7129
  };
6963
- var AgentOsNotAvailableError = class extends AgentOsSandboxError {
6964
- constructor(cause) {
7130
+
7131
+ // packages/context/src/lib/sandbox/apple-container-sandbox-errors.ts
7132
+ var AppleContainerSandboxError = class extends ContainerSandboxError {
7133
+ constructor(message2, containerId) {
7134
+ super(message2, containerId);
7135
+ this.name = "AppleContainerSandboxError";
7136
+ }
7137
+ };
7138
+ var ContainerServiceNotRunningError = class extends AppleContainerSandboxError {
7139
+ constructor() {
6965
7140
  super(
6966
- "@rivet-dev/agent-os-core is not installed. Install it with: npm install @rivet-dev/agent-os-core @rivet-dev/agent-os-common"
7141
+ "Apple container service is not running. Start it with `container system start` (first run also needs `container system kernel set --recommended`)."
6967
7142
  );
6968
- this.name = "AgentOsNotAvailableError";
6969
- this.cause = cause;
7143
+ this.name = "ContainerServiceNotRunningError";
6970
7144
  }
6971
7145
  };
6972
- var AgentOsCreationError = class extends AgentOsSandboxError {
6973
- constructor(message2, cause) {
6974
- super(`Failed to create Agent OS instance: ${message2}`);
6975
- this.name = "AgentOsCreationError";
6976
- this.cause = cause;
6977
- }
6978
- };
6979
- async function importAgentOs() {
6980
- try {
6981
- return await import("@rivet-dev/agent-os-core");
6982
- } catch (error) {
6983
- throw new AgentOsNotAvailableError(
6984
- error instanceof Error ? error : void 0
6985
- );
6986
- }
6987
- }
6988
- var SIGKILL_EXIT_CODE = 9;
6989
- function startKernelProcess(os, command, options) {
6990
- const stdout = new PassThrough();
6991
- const stderr = new PassThrough();
6992
- const onStdout = (chunk) => stdout.write(chunk);
6993
- const onStderr = (chunk) => stderr.write(chunk);
6994
- const { pid } = os.spawn("bash", ["-lc", command], {
6995
- ...options,
6996
- onStdout,
6997
- onStderr
6998
- });
6999
- const unsubOut = os.onProcessStdout(pid, onStdout);
7000
- const unsubErr = os.onProcessStderr(pid, onStderr);
7001
- let killSignalled = false;
7002
- const exit = os.waitProcess(pid).finally(() => {
7003
- unsubOut();
7004
- unsubErr();
7005
- stdout.end();
7006
- stderr.end();
7007
- });
7008
- return {
7009
- pid,
7010
- stdout,
7011
- stderr,
7012
- exit,
7013
- kill: () => {
7014
- if (killSignalled) return;
7015
- killSignalled = true;
7016
- os.killProcess(pid);
7017
- },
7018
- wasKilled: (exitCode) => killSignalled && exitCode === SIGKILL_EXIT_CODE
7019
- };
7020
- }
7021
- async function readAll(stream) {
7022
- const chunks = [];
7023
- for await (const chunk of stream) chunks.push(chunk);
7024
- return Buffer.concat(chunks).toString("utf8");
7025
- }
7026
- function bindAbort(signal, onAbort) {
7027
- if (!signal) return () => {
7028
- };
7029
- if (signal.aborted) {
7030
- onAbort();
7031
- return () => {
7032
- };
7033
- }
7034
- signal.addEventListener("abort", onAbort, { once: true });
7035
- return () => signal.removeEventListener("abort", onAbort);
7036
- }
7037
- async function createAgentOsSandbox(options = {}) {
7038
- const { AgentOs } = await importAgentOs();
7039
- const { readiness, ...kernelOptions } = options;
7040
- let os;
7041
- try {
7042
- os = await AgentOs.create(kernelOptions);
7043
- } catch (error) {
7044
- const err = error instanceof Error ? error : new Error(String(error));
7045
- throw new AgentOsCreationError(err.message, err);
7046
- }
7047
- try {
7048
- const probe = startKernelProcess(os, ":", {});
7049
- const [, stderr, exitCode] = await Promise.all([
7050
- readAll(probe.stdout),
7051
- readAll(probe.stderr),
7052
- probe.exit
7053
- ]);
7054
- if (exitCode !== 0) {
7055
- throw new Error(stderr.trim() || `exit code ${exitCode}`);
7056
- }
7057
- } catch (error) {
7058
- await os.dispose().catch(() => {
7059
- });
7060
- const err = error instanceof Error ? error : new Error(String(error));
7061
- throw new AgentOsCreationError(
7062
- `Bash is required to execute sandbox commands but could not be started: ${err.message}`,
7063
- err
7064
- );
7065
- }
7066
- const sandbox = {
7067
- async executeCommand(command, { signal } = {}) {
7068
- if (signal?.aborted) {
7069
- return { stdout: "", stderr: "", exitCode: SIGKILL_EXIT_CODE };
7070
- }
7071
- const proc = startKernelProcess(os, command, {});
7072
- const unbind = bindAbort(signal, proc.kill);
7073
- try {
7074
- const [stdout, stderr, exitCode] = await Promise.all([
7075
- readAll(proc.stdout),
7076
- readAll(proc.stderr),
7077
- proc.exit
7078
- ]);
7079
- return { stdout, stderr, exitCode };
7080
- } finally {
7081
- unbind();
7082
- }
7083
- },
7084
- spawn(command, { signal, env, cwd } = {}) {
7085
- if (signal?.aborted) {
7086
- const empty = () => new ReadableStream({ start: (c) => c.close() });
7087
- return {
7088
- stdout: empty(),
7089
- stderr: empty(),
7090
- exit: Promise.resolve({
7091
- code: null,
7092
- signal: "SIGKILL",
7093
- success: false
7094
- })
7095
- };
7096
- }
7097
- const proc = startKernelProcess(os, command, { env, cwd });
7098
- const unbind = bindAbort(signal, proc.kill);
7099
- const exit = proc.exit.then((code) => {
7100
- const killed = proc.wasKilled(code);
7101
- return {
7102
- code: killed ? null : code,
7103
- signal: killed ? "SIGKILL" : null,
7104
- success: !killed && code === 0
7105
- };
7106
- }).finally(unbind);
7107
- return {
7108
- stdout: Readable.toWeb(proc.stdout),
7109
- stderr: Readable.toWeb(proc.stderr),
7110
- exit
7111
- };
7112
- },
7113
- async readFile(path6, options2) {
7114
- try {
7115
- const bytes = await os.readFile(path6);
7116
- return readFileContent(bytes, options2);
7117
- } catch (error) {
7118
- throw new Error(
7119
- `Failed to read file "${path6}": ${error instanceof Error ? error.message : String(error)}`
7120
- );
7121
- }
7122
- },
7123
- async exists(path6) {
7124
- return os.exists(path6);
7125
- },
7126
- async writeFiles(files) {
7127
- const results = await os.writeFiles(
7128
- files.map((f) => ({
7129
- path: f.path,
7130
- content: typeof f.content === "string" ? f.content : new Uint8Array(f.content)
7131
- }))
7132
- );
7133
- const failures = results.filter((r) => !r.success);
7134
- if (failures.length > 0) {
7135
- const details = failures.map((f) => `${f.path}: ${f.error}`).join(", ");
7136
- throw new Error(`Failed to write files: ${details}`);
7137
- }
7138
- },
7139
- async dispose() {
7140
- try {
7141
- await os.dispose();
7142
- } catch {
7143
- }
7144
- },
7145
- [Symbol.asyncDispose]() {
7146
- return this.dispose();
7147
- }
7148
- };
7149
- if (readiness) {
7150
- try {
7151
- await readiness(sandbox);
7152
- } catch (error) {
7153
- await sandbox.dispose().catch(() => {
7154
- });
7155
- throw error;
7156
- }
7157
- }
7158
- return sandbox;
7159
- }
7160
- async function useAgentOsSandbox(options, fn) {
7161
- const sandbox = await createAgentOsSandbox(options);
7162
- try {
7163
- return await fn(sandbox);
7164
- } finally {
7165
- await sandbox.dispose();
7166
- }
7167
- }
7168
-
7169
- // packages/context/src/lib/sandbox/apple-container-sandbox.ts
7170
- import spawn3 from "nano-spawn";
7171
- import { spawn as childSpawn2 } from "node:child_process";
7172
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
7173
- import { tmpdir } from "node:os";
7174
- import { join } from "node:path";
7175
-
7176
- // packages/context/src/lib/sandbox/container-sandbox-errors.ts
7177
- var ContainerSandboxError = class extends Error {
7178
- containerId;
7179
- constructor(message2, containerId) {
7180
- super(message2);
7181
- this.name = "ContainerSandboxError";
7182
- this.containerId = containerId;
7183
- }
7184
- };
7185
-
7186
- // packages/context/src/lib/sandbox/apple-container-sandbox-errors.ts
7187
- var AppleContainerSandboxError = class extends ContainerSandboxError {
7188
- constructor(message2, containerId) {
7189
- super(message2, containerId);
7190
- this.name = "AppleContainerSandboxError";
7191
- }
7192
- };
7193
- var ContainerServiceNotRunningError = class extends AppleContainerSandboxError {
7194
- constructor() {
7195
- super(
7196
- "Apple container service is not running. Start it with `container system start` (first run also needs `container system kernel set --recommended`)."
7197
- );
7198
- this.name = "ContainerServiceNotRunningError";
7199
- }
7200
- };
7201
- var AppleContainerCreationError = class extends AppleContainerSandboxError {
7202
- image;
7203
- cause;
7204
- constructor(message2, image, cause) {
7205
- super(`Failed to create container from image "${image}": ${message2}`);
7206
- this.name = "AppleContainerCreationError";
7207
- this.image = image;
7146
+ var AppleContainerCreationError = class extends AppleContainerSandboxError {
7147
+ image;
7148
+ cause;
7149
+ constructor(message2, image, cause) {
7150
+ super(`Failed to create container from image "${image}": ${message2}`);
7151
+ this.name = "AppleContainerCreationError";
7152
+ this.image = image;
7208
7153
  this.cause = cause;
7209
7154
  }
7210
7155
  };
@@ -7268,7 +7213,8 @@ import { createHash } from "node:crypto";
7268
7213
  import { existsSync, readFileSync } from "node:fs";
7269
7214
 
7270
7215
  // packages/context/src/lib/sandbox/cli-process.ts
7271
- import { Readable as Readable2 } from "node:stream";
7216
+ import { SubprocessError } from "nano-spawn";
7217
+ import { Readable } from "node:stream";
7272
7218
 
7273
7219
  // packages/context/src/lib/sandbox/shell-quote.ts
7274
7220
  function shellQuote(s) {
@@ -7276,6 +7222,20 @@ function shellQuote(s) {
7276
7222
  }
7277
7223
 
7278
7224
  // packages/context/src/lib/sandbox/cli-process.ts
7225
+ function commandResultFrom(error) {
7226
+ if (error instanceof SubprocessError) {
7227
+ return {
7228
+ stdout: error.stdout,
7229
+ stderr: error.stderr || error.message,
7230
+ exitCode: error.exitCode ?? 1
7231
+ };
7232
+ }
7233
+ return {
7234
+ stdout: "",
7235
+ stderr: error instanceof Error ? error.message : "",
7236
+ exitCode: 1
7237
+ };
7238
+ }
7279
7239
  function toSandboxProcess(child, abortSignal) {
7280
7240
  if (!child.stdout || !child.stderr) {
7281
7241
  child.kill("SIGKILL");
@@ -7287,8 +7247,8 @@ function toSandboxProcess(child, abortSignal) {
7287
7247
  else abortSignal.addEventListener("abort", onAbort, { once: true });
7288
7248
  }
7289
7249
  return {
7290
- stdout: Readable2.toWeb(child.stdout),
7291
- stderr: Readable2.toWeb(child.stderr),
7250
+ stdout: Readable.toWeb(child.stdout),
7251
+ stderr: Readable.toWeb(child.stderr),
7292
7252
  exit: new Promise((resolve3, reject) => {
7293
7253
  const settle = () => {
7294
7254
  child.removeListener("exit", onExitEvent);
@@ -7333,7 +7293,7 @@ function existsCommand(path6) {
7333
7293
  }
7334
7294
 
7335
7295
  // packages/context/src/lib/sandbox/installers/installer.ts
7336
- import spawn from "nano-spawn";
7296
+ import spawn, { SubprocessError as SubprocessError2 } from "nano-spawn";
7337
7297
 
7338
7298
  // packages/context/src/lib/sandbox/docker-sandbox-errors.ts
7339
7299
  var DockerSandboxError = class extends ContainerSandboxError {
@@ -7476,14 +7436,14 @@ function isDebianBased(image) {
7476
7436
  const debianPatterns = ["debian", "ubuntu", "node", "python"];
7477
7437
  return debianPatterns.some((pattern) => lower.includes(pattern));
7478
7438
  }
7479
- function createInstallerContext(containerId, image) {
7439
+ function createInstallerContext(cli, containerId, image) {
7480
7440
  const packageManager = isDebianBased(image) ? "apt-get" : "apk";
7481
7441
  let archPromise = null;
7482
7442
  const ensuredTools = /* @__PURE__ */ new Set();
7483
7443
  let aptUpdated = false;
7484
7444
  const exec = async (command) => {
7485
7445
  try {
7486
- const result = await spawn("docker", [
7446
+ const result = await spawn(cli.binary, [
7487
7447
  "exec",
7488
7448
  containerId,
7489
7449
  "sh",
@@ -7492,11 +7452,17 @@ function createInstallerContext(containerId, image) {
7492
7452
  ]);
7493
7453
  return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
7494
7454
  } catch (error) {
7495
- const err = error;
7455
+ if (error instanceof SubprocessError2) {
7456
+ return {
7457
+ stdout: error.stdout,
7458
+ stderr: error.stderr,
7459
+ exitCode: error.exitCode ?? 1
7460
+ };
7461
+ }
7496
7462
  return {
7497
- stdout: err.stdout ?? "",
7498
- stderr: err.stderr ?? err.message ?? "",
7499
- exitCode: err.exitCode ?? 1
7463
+ stdout: "",
7464
+ stderr: error instanceof Error ? error.message : "",
7465
+ exitCode: 1
7500
7466
  };
7501
7467
  }
7502
7468
  };
@@ -7505,7 +7471,7 @@ function createInstallerContext(containerId, image) {
7505
7471
  const attempt = (async () => {
7506
7472
  const result = await exec("uname -m");
7507
7473
  if (result.exitCode !== 0) {
7508
- throw new DockerSandboxError(
7474
+ throw new cli.SandboxError(
7509
7475
  `Failed to detect container architecture: ${result.stderr}`,
7510
7476
  containerId
7511
7477
  );
@@ -7562,6 +7528,12 @@ function createInstallerContext(containerId, image) {
7562
7528
  };
7563
7529
  }
7564
7530
 
7531
+ // packages/context/src/lib/sandbox/read-file.ts
7532
+ var decoder = new TextDecoder();
7533
+ function readFileContent(bytes, options) {
7534
+ return options?.encoding === "binary" ? bytes : decoder.decode(bytes);
7535
+ }
7536
+
7565
7537
  // packages/context/src/lib/sandbox/container-sandbox.ts
7566
7538
  var CONTAINER_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
7567
7539
  var ContainerSandboxStrategy = class {
@@ -7684,7 +7656,11 @@ var ContainerSandboxStrategy = class {
7684
7656
  if (this.isServiceDown(message2)) {
7685
7657
  throw this.engine.errors.serviceNotAvailable();
7686
7658
  }
7687
- throw this.engine.errors.creation(message2, image, error);
7659
+ throw this.engine.errors.creation(
7660
+ message2,
7661
+ image,
7662
+ error instanceof Error ? error : void 0
7663
+ );
7688
7664
  }
7689
7665
  }
7690
7666
  async inspectContainer(containerId) {
@@ -7753,7 +7729,7 @@ var ContainerSandboxStrategy = class {
7753
7729
  containerPaths.add(volume.containerPath);
7754
7730
  if (volume.type === "bind") {
7755
7731
  this.validateMountValue("hostPath", volume.hostPath, volume);
7756
- if (!existsSync(volume.hostPath)) {
7732
+ if (this.engine.bindMountsOnClient && !existsSync(volume.hostPath)) {
7757
7733
  throw this.engine.errors.volumePath(
7758
7734
  volume.hostPath,
7759
7735
  volume.containerPath,
@@ -7820,7 +7796,7 @@ var ContainerSandboxStrategy = class {
7820
7796
  }
7821
7797
  }
7822
7798
  async createVolume(volume) {
7823
- const args = this.engine.volumeCreateArgs(volume);
7799
+ const args = this.engine.volumeCreateArgs(volume, this.opts);
7824
7800
  try {
7825
7801
  await spawn2(this.engine.cli, args);
7826
7802
  } catch (error) {
@@ -7851,8 +7827,10 @@ var ContainerSandboxStrategy = class {
7851
7827
  await this.cleanupCreatedVolumes();
7852
7828
  } catch (cleanupError) {
7853
7829
  if (originalError instanceof Error) {
7854
- const original = originalError;
7855
- original.suppressed = [...original.suppressed ?? [], cleanupError];
7830
+ const suppressed = "suppressed" in originalError && Array.isArray(originalError.suppressed) ? originalError.suppressed : [];
7831
+ Object.assign(originalError, {
7832
+ suppressed: [...suppressed, cleanupError]
7833
+ });
7856
7834
  }
7857
7835
  }
7858
7836
  }
@@ -7871,7 +7849,20 @@ var ContainerSandboxStrategy = class {
7871
7849
  if (this.isServiceDown(message2)) {
7872
7850
  throw this.engine.errors.serviceNotAvailable();
7873
7851
  }
7874
- throw this.engine.errors.creation(message2, image, error);
7852
+ for (const volume of this.volumes) {
7853
+ if (volume.type === "bind" && this.engine.isMissingBindSource?.(message2, volume.hostPath)) {
7854
+ throw this.engine.errors.volumePath(
7855
+ volume.hostPath,
7856
+ volume.containerPath,
7857
+ "hostPath does not exist on host"
7858
+ );
7859
+ }
7860
+ }
7861
+ throw this.engine.errors.creation(
7862
+ message2,
7863
+ image,
7864
+ error instanceof Error ? error : void 0
7865
+ );
7875
7866
  }
7876
7867
  }
7877
7868
  async stopContainer(containerId) {
@@ -7893,12 +7884,7 @@ var ContainerSandboxStrategy = class {
7893
7884
  exitCode: 0
7894
7885
  };
7895
7886
  } catch (error) {
7896
- const err = error;
7897
- return {
7898
- stdout: err.stdout || "",
7899
- stderr: err.stderr || err.message || "",
7900
- exitCode: err.exitCode ?? 1
7901
- };
7887
+ return commandResultFrom(error);
7902
7888
  }
7903
7889
  }
7904
7890
  async assertBashAvailable() {
@@ -8035,8 +8021,10 @@ function buildMountArg(volume) {
8035
8021
  return parts.join(",");
8036
8022
  }
8037
8023
  function getCliErrorMessage(error) {
8038
- const err = error;
8039
- return err.stderr?.trim() || err.stdout?.trim() || err.message || String(error);
8024
+ if (error instanceof SubprocessError3) {
8025
+ return error.stderr.trim() || error.stdout.trim() || error.message;
8026
+ }
8027
+ return error instanceof Error && error.message || String(error);
8040
8028
  }
8041
8029
  function safeParseArray(stdout) {
8042
8030
  try {
@@ -8046,11 +8034,15 @@ function safeParseArray(stdout) {
8046
8034
  return [];
8047
8035
  }
8048
8036
  }
8037
+ var containerInspectEntry = z10.object({
8038
+ status: z10.union([
8039
+ z10.string(),
8040
+ z10.object({ state: z10.string() }).transform(({ state }) => state)
8041
+ ])
8042
+ });
8049
8043
  function readContainerStatus(entry) {
8050
- const raw = entry?.status;
8051
- const status = String(
8052
- (typeof raw === "object" && raw !== null ? raw.state : raw) ?? ""
8053
- ).toLowerCase();
8044
+ const parsed = containerInspectEntry.safeParse(entry);
8045
+ const status = parsed.success ? parsed.data.status.toLowerCase() : "";
8054
8046
  if (status === "running" || status === "booted") return "running";
8055
8047
  if (status === "stopped") return "stopped";
8056
8048
  throw new AppleContainerSandboxError(
@@ -8059,6 +8051,7 @@ function readContainerStatus(entry) {
8059
8051
  }
8060
8052
  var appleEngine = {
8061
8053
  cli: CLI,
8054
+ bindMountsOnClient: true,
8062
8055
  runArgs(image, containerId, opts) {
8063
8056
  const { memory = "1024M", cpus = 2 } = opts.resources ?? {};
8064
8057
  const args = [
@@ -8148,7 +8141,12 @@ var appleEngine = {
8148
8141
  ]);
8149
8142
  },
8150
8143
  defaultImage: "docker.io/library/bash:5.3-alpine3.24",
8151
- createInstallerContext: createAppleInstallerContext,
8144
+ // The Docker installer suite, driven through `container exec`.
8145
+ createInstallerContext: (containerId, image) => createInstallerContext(
8146
+ { binary: CLI, SandboxError: AppleContainerSandboxError },
8147
+ containerId,
8148
+ image
8149
+ ),
8152
8150
  async imageExists(tag) {
8153
8151
  try {
8154
8152
  await spawn3(CLI, ["image", "inspect", tag]);
@@ -8196,91 +8194,6 @@ var appleEngine = {
8196
8194
  volumeRemove: (name, reason) => new AppleContainerVolumeRemoveError(name, reason)
8197
8195
  }
8198
8196
  };
8199
- function createAppleInstallerContext(containerId, image) {
8200
- const packageManager = isDebianBased(image) ? "apt-get" : "apk";
8201
- let archPromise = null;
8202
- const ensuredTools = /* @__PURE__ */ new Set();
8203
- let aptUpdated = false;
8204
- const exec = async (command) => {
8205
- try {
8206
- const result = await spawn3(CLI, [
8207
- "exec",
8208
- containerId,
8209
- "sh",
8210
- "-c",
8211
- command
8212
- ]);
8213
- return { stdout: result.stdout, stderr: result.stderr, exitCode: 0 };
8214
- } catch (error) {
8215
- const err = error;
8216
- return {
8217
- stdout: err.stdout ?? "",
8218
- stderr: err.stderr ?? err.message ?? "",
8219
- exitCode: err.exitCode ?? 1
8220
- };
8221
- }
8222
- };
8223
- const arch = async () => {
8224
- if (!archPromise) {
8225
- const attempt = (async () => {
8226
- const result = await exec("uname -m");
8227
- if (result.exitCode !== 0) {
8228
- throw new AppleContainerSandboxError(
8229
- `Failed to detect container architecture: ${result.stderr}`,
8230
- containerId
8231
- );
8232
- }
8233
- return result.stdout.trim();
8234
- })();
8235
- archPromise = attempt.catch((err) => {
8236
- archPromise = null;
8237
- throw err;
8238
- });
8239
- }
8240
- return archPromise;
8241
- };
8242
- const installPackages = async (packages) => {
8243
- if (packages.length === 0) return;
8244
- const quoted = packages.map(shellQuote).join(" ");
8245
- let cmd;
8246
- if (packageManager === "apt-get") {
8247
- cmd = aptUpdated ? `apt-get install -y ${quoted}` : `apt-get update && apt-get install -y ${quoted}`;
8248
- } else {
8249
- cmd = `apk add --no-cache ${quoted}`;
8250
- }
8251
- const result = await exec(cmd);
8252
- if (result.exitCode !== 0) {
8253
- throw new PackageInstallError(
8254
- packages,
8255
- image,
8256
- packageManager,
8257
- result.stderr,
8258
- containerId
8259
- );
8260
- }
8261
- if (packageManager === "apt-get") aptUpdated = true;
8262
- };
8263
- const ensureTool = async (checkName, installName) => {
8264
- const cacheKey = installName ?? checkName;
8265
- if (ensuredTools.has(cacheKey)) return;
8266
- const check = await exec(`which ${shellQuote(checkName)}`);
8267
- if (check.exitCode === 0) {
8268
- ensuredTools.add(cacheKey);
8269
- return;
8270
- }
8271
- await installPackages([installName ?? checkName]);
8272
- ensuredTools.add(cacheKey);
8273
- };
8274
- return {
8275
- containerId,
8276
- image,
8277
- packageManager,
8278
- arch,
8279
- exec,
8280
- installPackages,
8281
- ensureTool
8282
- };
8283
- }
8284
8197
  async function runAppleBuild(args, showBuildLogs) {
8285
8198
  try {
8286
8199
  if (showBuildLogs) {
@@ -8339,13 +8252,13 @@ import fg from "fast-glob";
8339
8252
  import { BashTransformPipeline, TeePlugin } from "just-bash";
8340
8253
  import { readFile } from "node:fs/promises";
8341
8254
  import * as path4 from "node:path";
8342
- import z7 from "zod";
8255
+ import z12 from "zod";
8343
8256
  import { withHostOnlyToolMetadata as withHostOnlyToolMetadata2 } from "@deepagents/agent";
8344
8257
 
8345
8258
  // packages/context/src/lib/sandbox/read-file-tool/index.ts
8346
8259
  import { tool as tool2 } from "ai";
8347
8260
  import path3 from "node:path";
8348
- import z6 from "zod";
8261
+ import z11 from "zod";
8349
8262
 
8350
8263
  // packages/context/src/lib/sandbox/read-file-tool/binary.ts
8351
8264
  import { detectMediaType } from "@ai-sdk/provider-utils";
@@ -8494,10 +8407,10 @@ var formats = [
8494
8407
  binaryFileFormat,
8495
8408
  textFileFormat
8496
8409
  ];
8497
- var inputSchema = z6.strictObject({
8498
- path: z6.string().min(1).describe("The path to the file to read"),
8499
- offset: z6.number().int().min(1).optional().describe("1-based line number to start at for text files"),
8500
- limit: z6.number().int().min(1).optional().describe("Number of text lines to return from offset")
8410
+ var inputSchema = z11.strictObject({
8411
+ path: z11.string().min(1).describe("The path to the file to read"),
8412
+ offset: z11.number().int().min(1).optional().describe("1-based line number to start at for text files"),
8413
+ limit: z11.number().int().min(1).optional().describe("Number of text lines to return from offset")
8501
8414
  });
8502
8415
  function createReadFileTool({
8503
8416
  sandbox,
@@ -8773,9 +8686,9 @@ async function createBashTool(options) {
8773
8686
  extraInstructions,
8774
8687
  experimentalTeeTransform
8775
8688
  }),
8776
- inputSchema: z7.object({
8777
- command: z7.string().describe("The bash command to execute"),
8778
- reasoning: z7.string().trim().min(1).describe("Brief reason for executing this command")
8689
+ inputSchema: z12.object({
8690
+ command: z12.string().describe("The bash command to execute"),
8691
+ reasoning: z12.string().trim().min(1).describe("Brief reason for executing this command")
8779
8692
  }),
8780
8693
  execute: async ({ command: originalCommand }, executionOptions) => {
8781
8694
  let command = originalCommand;
@@ -8818,9 +8731,9 @@ async function createBashTool(options) {
8818
8731
  const readFile2 = createReadFileTool({ sandbox, destination });
8819
8732
  const writeFile2 = tool3({
8820
8733
  description: "Write content to a file in the sandbox. Creates parent directories if needed.",
8821
- inputSchema: z7.object({
8822
- path: z7.string().describe("The path where the file should be written"),
8823
- content: z7.string().describe("The content to write to the file")
8734
+ inputSchema: z12.object({
8735
+ path: z12.string().describe("The path where the file should be written"),
8736
+ content: z12.string().describe("The content to write to the file")
8824
8737
  }),
8825
8738
  execute: async ({ path: filePath, content }) => {
8826
8739
  try {
@@ -8844,7 +8757,7 @@ async function createBashTool(options) {
8844
8757
  // packages/context/src/lib/sandbox/binary-bridges.ts
8845
8758
  import { existsSync as existsSync2 } from "fs";
8846
8759
  import { defineCommand } from "just-bash";
8847
- import spawn4 from "nano-spawn";
8760
+ import spawn4, { SubprocessError as SubprocessError4 } from "nano-spawn";
8848
8761
  import * as path5 from "path";
8849
8762
  function createBinaryBridges(...binaries) {
8850
8763
  return binaries.map((input) => {
@@ -8892,24 +8805,21 @@ function createBinaryBridges(...binaries) {
8892
8805
  exitCode: 0
8893
8806
  };
8894
8807
  } catch (error) {
8895
- if (error && typeof error === "object") {
8896
- const err = error;
8897
- const cause = err.cause;
8898
- if (cause?.code === "ENOENT") {
8808
+ if (error instanceof SubprocessError4) {
8809
+ if (hasErrorCode(error.cause, "ENOENT")) {
8899
8810
  return {
8900
8811
  stdout: "",
8901
8812
  stderr: `${name}: ${binaryPath} not found`,
8902
8813
  exitCode: 127
8903
8814
  };
8904
8815
  }
8905
- }
8906
- if (error && typeof error === "object" && "exitCode" in error) {
8907
- const subprocessError = error;
8908
- return {
8909
- stdout: subprocessError.stdout ?? "",
8910
- stderr: subprocessError.stderr ?? "",
8911
- exitCode: subprocessError.exitCode ?? 1
8912
- };
8816
+ if ("exitCode" in error) {
8817
+ return {
8818
+ stdout: error.stdout,
8819
+ stderr: error.stderr,
8820
+ exitCode: error.exitCode ?? 1
8821
+ };
8822
+ }
8913
8823
  }
8914
8824
  return {
8915
8825
  stdout: "",
@@ -8920,21 +8830,25 @@ function createBinaryBridges(...binaries) {
8920
8830
  });
8921
8831
  });
8922
8832
  }
8833
+ function hasErrorCode(value, code) {
8834
+ return typeof value === "object" && value !== null && "code" in value && value.code === code;
8835
+ }
8923
8836
  function resolveRealCwd(ctx) {
8924
- const fs = ctx.fs;
8925
- let realCwd;
8926
- if (fs.root) {
8927
- realCwd = path5.join(fs.root, ctx.cwd);
8928
- } else if (typeof fs.getMountPoint === "function" && typeof fs.toRealPath === "function") {
8929
- const real = fs.toRealPath(ctx.cwd);
8930
- realCwd = real ?? process.cwd();
8931
- } else {
8932
- realCwd = process.cwd();
8837
+ const realCwd = mapToRealPath(ctx.fs, ctx.cwd) ?? process.cwd();
8838
+ return existsSync2(realCwd) ? realCwd : process.cwd();
8839
+ }
8840
+ function mapToRealPath(fs, cwd) {
8841
+ if (typeof fs !== "object" || fs === null) {
8842
+ return null;
8933
8843
  }
8934
- if (!existsSync2(realCwd)) {
8935
- realCwd = process.cwd();
8844
+ if ("root" in fs && typeof fs.root === "string" && fs.root) {
8845
+ return path5.join(fs.root, cwd);
8936
8846
  }
8937
- return realCwd;
8847
+ if ("getMountPoint" in fs && typeof fs.getMountPoint === "function" && "toRealPath" in fs && typeof fs.toRealPath === "function") {
8848
+ const real = fs.toRealPath(cwd);
8849
+ return typeof real === "string" ? real : null;
8850
+ }
8851
+ return null;
8938
8852
  }
8939
8853
 
8940
8854
  // packages/context/src/lib/sandbox/daytona-sandbox.ts
@@ -8962,15 +8876,15 @@ var DaytonaCommandError = class extends DaytonaSandboxError {
8962
8876
  }
8963
8877
  };
8964
8878
  async function createDaytonaSandbox(client, options = {}) {
8965
- validateDaytonaOptions(options);
8879
+ const target = validateDaytonaOptions(options);
8966
8880
  const sdk = await import("@daytona/sdk");
8967
8881
  let sandbox;
8968
8882
  try {
8969
- if (options.sandboxId !== void 0) {
8970
- sandbox = await client.get(options.sandboxId);
8883
+ if ("sandboxId" in target) {
8884
+ sandbox = await client.get(target.sandboxId);
8971
8885
  await startIfStopped(sandbox, options);
8972
8886
  } else {
8973
- sandbox = await acquireReusedSandbox(client, options, sdk);
8887
+ sandbox = await acquireReusedSandbox(client, target.name, options, sdk);
8974
8888
  }
8975
8889
  } catch (error) {
8976
8890
  throw normalizeDaytonaError(error, sdk);
@@ -9015,10 +8929,10 @@ var UNRECOVERABLE_SANDBOX_STATES = /* @__PURE__ */ new Set([
9015
8929
  "build_failed",
9016
8930
  "destroyed"
9017
8931
  ]);
9018
- async function acquireReusedSandbox(client, options, sdk) {
8932
+ async function acquireReusedSandbox(client, name, options, sdk) {
9019
8933
  let existing;
9020
8934
  try {
9021
- existing = await client.get(options.name);
8935
+ existing = await client.get(name);
9022
8936
  } catch (error) {
9023
8937
  if (error instanceof sdk.DaytonaNotFoundError) {
9024
8938
  return createSandbox(client, options);
@@ -9094,13 +9008,16 @@ function validateDaytonaOptions(options) {
9094
9008
  'Daytona sandbox options can only include "resources" when creating from "image". The Daytona SDK does not apply resources during default or snapshot creation.'
9095
9009
  );
9096
9010
  }
9097
- if (options.sandboxId === void 0 && options.name === void 0) {
9098
- throw new DaytonaSandboxError(
9099
- 'Daytona sandbox options require "name" (get-or-create) or "sandboxId" (attach). An unnamed sandbox cannot be reclaimed, since dispose() does not delete it.'
9100
- );
9011
+ if (options.sandboxId === void 0) {
9012
+ if (options.name === void 0) {
9013
+ throw new DaytonaSandboxError(
9014
+ 'Daytona sandbox options require "name" (get-or-create) or "sandboxId" (attach). An unnamed sandbox cannot be reclaimed, since dispose() does not delete it.'
9015
+ );
9016
+ }
9017
+ return { name: options.name };
9101
9018
  }
9102
9019
  if (!options.sandboxId) {
9103
- return;
9020
+ return { sandboxId: options.sandboxId };
9104
9021
  }
9105
9022
  const creationOnlyFields = [
9106
9023
  "name",
@@ -9129,6 +9046,7 @@ function validateDaytonaOptions(options) {
9129
9046
  `Daytona sandbox options cannot combine "sandboxId" with creation options: ${present.join(", ")}`
9130
9047
  );
9131
9048
  }
9049
+ return { sandboxId: options.sandboxId };
9132
9050
  }
9133
9051
  function createDaytonaSandboxMethods(args) {
9134
9052
  const { sdk, sandbox, commandTimeout } = args;
@@ -9159,12 +9077,7 @@ function createDaytonaSandboxMethods(args) {
9159
9077
  };
9160
9078
  } catch (error) {
9161
9079
  if (aborted) return abortedCommandResult();
9162
- const err = error;
9163
- return {
9164
- stdout: err.stdout ?? "",
9165
- stderr: err.stderr ?? err.message ?? String(error),
9166
- exitCode: err.exitCode ?? 1
9167
- };
9080
+ return { stdout: "", stderr: toError(error).message, exitCode: 1 };
9168
9081
  } finally {
9169
9082
  options?.signal?.removeEventListener("abort", abort);
9170
9083
  }
@@ -9443,10 +9356,10 @@ function uniqueParentDirectories(paths) {
9443
9356
  return [...dirs];
9444
9357
  }
9445
9358
  function compactObject(input) {
9446
- const output = {};
9447
- for (const [key, value] of Object.entries(input)) {
9448
- if (value !== void 0) {
9449
- output[key] = value;
9359
+ const output = { ...input };
9360
+ for (const [key, value] of Object.entries(output)) {
9361
+ if (value === void 0) {
9362
+ Reflect.deleteProperty(output, key);
9450
9363
  }
9451
9364
  }
9452
9365
  return output;
@@ -9456,7 +9369,7 @@ function toError(error) {
9456
9369
  }
9457
9370
 
9458
9371
  // packages/context/src/lib/sandbox/docker-sandbox.ts
9459
- import spawn5 from "nano-spawn";
9372
+ import spawn5, { SubprocessError as SubprocessError5 } from "nano-spawn";
9460
9373
  import { spawn as childSpawn3 } from "node:child_process";
9461
9374
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
9462
9375
  import { readFileSync as readFileSync2 } from "node:fs";
@@ -9517,6 +9430,14 @@ function runDockerBuild(args, stdin, showBuildLogs) {
9517
9430
  }
9518
9431
  var dockerEngine = {
9519
9432
  cli: "docker",
9433
+ bindMountsOnClient: false,
9434
+ isMissingBindSource(message2, source) {
9435
+ const marker = `bind source path does not exist: ${source}`;
9436
+ const index = message2.indexOf(marker);
9437
+ if (index < 0) return false;
9438
+ const remainder = message2.slice(index + marker.length);
9439
+ return remainder === "" || remainder.startsWith("\n") || remainder.startsWith("\r\n");
9440
+ },
9520
9441
  runArgs(image, containerId, opts, workdir) {
9521
9442
  const {
9522
9443
  memory = "1g",
@@ -9661,8 +9582,10 @@ var dockerEngine = {
9661
9582
  parseStatus(status) {
9662
9583
  return status === "running" ? "running" : "stopped";
9663
9584
  },
9664
- volumeCreateArgs(volume) {
9585
+ volumeCreateArgs(volume, opts) {
9665
9586
  const args = ["volume", "create"];
9587
+ for (const [key, value] of Object.entries(opts.labels ?? {}))
9588
+ args.push("--label", `${key}=${value}`);
9666
9589
  if (volume.driver) {
9667
9590
  args.push("--driver", volume.driver);
9668
9591
  }
@@ -9673,8 +9596,10 @@ var dockerEngine = {
9673
9596
  return args;
9674
9597
  },
9675
9598
  errorMessage(error) {
9676
- const err = error;
9677
- return err.stderr || err.stdout || err.message || String(error);
9599
+ if (error instanceof SubprocessError5) {
9600
+ return error.stderr || error.stdout || error.message;
9601
+ }
9602
+ return error instanceof Error && error.message || String(error);
9678
9603
  },
9679
9604
  async removeVolume(name) {
9680
9605
  const deadline = performance.now() + 3e4;
@@ -9697,7 +9622,7 @@ var dockerEngine = {
9697
9622
  return message2.toLowerCase().includes("no such container");
9698
9623
  },
9699
9624
  isMissingVolume(message2) {
9700
- return message2.toLowerCase().includes("no such volume");
9625
+ return /no such volume|volume \S+ not found/i.test(message2);
9701
9626
  },
9702
9627
  isNameConflict(message2) {
9703
9628
  return message2.toLowerCase().includes("is already in use by container");
@@ -9705,7 +9630,11 @@ var dockerEngine = {
9705
9630
  async ensureWorkdir() {
9706
9631
  },
9707
9632
  defaultImage: "bash:5.3-alpine3.24",
9708
- createInstallerContext,
9633
+ createInstallerContext: (containerId, image) => createInstallerContext(
9634
+ { binary: "docker", SandboxError: DockerSandboxError },
9635
+ containerId,
9636
+ image
9637
+ ),
9709
9638
  async imageExists(tag) {
9710
9639
  try {
9711
9640
  await spawn5("docker", ["image", "inspect", tag]);
@@ -9759,17 +9688,32 @@ function buildDockerExecFlags(options) {
9759
9688
  }
9760
9689
  return flags;
9761
9690
  }
9762
- function managedDockerCommand(command, controlPath) {
9691
+ function managedDockerCommand(command, controlPath, commandTimeout) {
9763
9692
  return [
9764
9693
  "set -m",
9765
9694
  `control=${shellQuote(controlPath)}`,
9766
9695
  ': > "$control" || exit 1',
9767
- `trap 'rm -f "$control"' EXIT`,
9696
+ "timer=",
9697
+ `trap 'if [ -n "$timer" ]; then kill -TERM "$timer" 2>/dev/null || :; wait "$timer" 2>/dev/null || :; fi; rm -f "$control" "$control.timeout"' EXIT`,
9768
9698
  `bash -lc ${shellQuote(command)} &`,
9769
9699
  "pid=$!",
9770
9700
  `printf '%s\\n' "$pid" > "$control"`,
9701
+ ...commandTimeout ? [
9702
+ // Keep the deadline on the engine host: SSH setup/round trips must not
9703
+ // let the command run past its execution budget.
9704
+ "(",
9705
+ `sleep ${commandTimeout / 1e3} &`,
9706
+ "alarm=$!",
9707
+ `trap 'kill "$alarm" 2>/dev/null || :; wait "$alarm" 2>/dev/null || :; exit 0' TERM`,
9708
+ 'wait "$alarm" || exit',
9709
+ 'if kill -0 -- "-$pid" 2>/dev/null; then : > "$control.timeout"; kill -KILL -- "-$pid" 2>/dev/null || :; fi',
9710
+ ") &",
9711
+ "timer=$!"
9712
+ ] : [],
9771
9713
  'wait "$pid"',
9772
- 'exit "$?"'
9714
+ "status=$?",
9715
+ '[ ! -e "$control.timeout" ] || exit 124',
9716
+ 'exit "$status"'
9773
9717
  ].join("\n");
9774
9718
  }
9775
9719
  async function waitForDockerExecPid(execArgs, controlPath, localExit) {
@@ -9825,36 +9769,35 @@ function spawnDockerProcess(execArgs, command, options = {}, commandTimeout) {
9825
9769
  const localProcess = toSandboxProcess(
9826
9770
  childSpawn3(
9827
9771
  "docker",
9828
- execArgs(managedDockerCommand(command, controlPath), options)
9772
+ execArgs(
9773
+ managedDockerCommand(command, controlPath, commandTimeout),
9774
+ options
9775
+ )
9829
9776
  ),
9830
9777
  void 0
9831
9778
  );
9832
9779
  let termination;
9833
- const terminate = (reason) => {
9834
- termination ??= {
9835
- reason,
9836
- confirmed: terminateDockerExec(execArgs, controlPath, localProcess.exit)
9837
- };
9780
+ const onAbort = () => {
9781
+ termination ??= terminateDockerExec(
9782
+ execArgs,
9783
+ controlPath,
9784
+ localProcess.exit
9785
+ );
9786
+ void termination.catch(() => {
9787
+ });
9838
9788
  };
9839
- const onAbort = () => terminate("abort");
9840
9789
  if (options.signal?.aborted) onAbort();
9841
9790
  else options.signal?.addEventListener("abort", onAbort, { once: true });
9842
- let timeout;
9843
- if (commandTimeout) {
9844
- timeout = setTimeout(() => terminate("timeout"), commandTimeout);
9845
- timeout.unref();
9846
- }
9847
9791
  return {
9848
9792
  stdout: localProcess.stdout,
9849
9793
  stderr: localProcess.stderr,
9850
9794
  exit: localProcess.exit.then(async (info) => {
9851
9795
  const activeTermination = termination;
9852
- if (!activeTermination || !await activeTermination.confirmed) {
9796
+ if (!activeTermination || !await activeTermination) {
9853
9797
  return info;
9854
9798
  }
9855
- return activeTermination.reason === "timeout" ? { code: 124, signal: null, success: false } : { code: null, signal: "SIGKILL", success: false };
9799
+ return { code: null, signal: "SIGKILL", success: false };
9856
9800
  }).finally(() => {
9857
- clearTimeout(timeout);
9858
9801
  options.signal?.removeEventListener("abort", onAbort);
9859
9802
  })
9860
9803
  };
@@ -9865,12 +9808,7 @@ async function executeDockerCommand(execArgs, command, options = {}, commandTime
9865
9808
  const result2 = await spawn5("docker", execArgs(command));
9866
9809
  return { stdout: result2.stdout, stderr: result2.stderr, exitCode: 0 };
9867
9810
  } catch (error) {
9868
- const err = error;
9869
- return {
9870
- stdout: err.stdout || "",
9871
- stderr: err.stderr || err.message || "",
9872
- exitCode: err.exitCode ?? 1
9873
- };
9811
+ return commandResultFrom(error);
9874
9812
  }
9875
9813
  }
9876
9814
  const process2 = spawnDockerProcess(
@@ -9965,11 +9903,14 @@ var ComposeStrategy = class extends ContainerSandboxStrategy {
9965
9903
  "-d"
9966
9904
  ]);
9967
9905
  } catch (error) {
9968
- const err = error;
9969
- if (err.stderr?.includes("Cannot connect")) {
9906
+ const stderr = error instanceof SubprocessError5 ? error.stderr : "";
9907
+ if (stderr.includes("Cannot connect")) {
9970
9908
  throw this.engine.errors.serviceNotAvailable();
9971
9909
  }
9972
- throw new ComposeStartError(this.composeFile, err.stderr || err.message);
9910
+ throw new ComposeStartError(
9911
+ this.composeFile,
9912
+ stderr || (error instanceof Error ? error.message : String(error))
9913
+ );
9973
9914
  }
9974
9915
  }
9975
9916
  defaultContainerId() {
@@ -10059,7 +10000,7 @@ import { randomUUID as randomUUID3 } from "node:crypto";
10059
10000
  import { posix as posix3 } from "node:path";
10060
10001
 
10061
10002
  // packages/context/src/lib/sandbox/strace/index.ts
10062
- import spawn6 from "nano-spawn";
10003
+ import spawn6, { SubprocessError as SubprocessError6 } from "nano-spawn";
10063
10004
  import { posix as posix2 } from "node:path";
10064
10005
  var STRACE_FLAGS = "-f -y -qq -e trace=%file,write,pwrite64,writev";
10065
10006
  function buildStraceCommand(command, traceFile, traceDir) {
@@ -10463,6 +10404,14 @@ function resolveName(binary, options) {
10463
10404
  }
10464
10405
 
10465
10406
  // packages/context/src/lib/sandbox/installers/url-binary.ts
10407
+ var ARCHITECTURES = [
10408
+ "x86_64",
10409
+ "aarch64",
10410
+ "armv7l"
10411
+ ];
10412
+ function isArchitecture(value) {
10413
+ return ARCHITECTURES.some((architecture) => architecture === value);
10414
+ }
10466
10415
  var UrlBinaryInstaller = class extends Installer {
10467
10416
  kind;
10468
10417
  options;
@@ -10487,7 +10436,7 @@ function urlBinary(options) {
10487
10436
  async function resolveUrl(ctx, options) {
10488
10437
  if (typeof options.url === "string") return options.url;
10489
10438
  const arch = await ctx.arch();
10490
- const archUrl = options.url[arch];
10439
+ const archUrl = isArchitecture(arch) ? options.url[arch] : void 0;
10491
10440
  if (!archUrl) {
10492
10441
  throw new InstallError({
10493
10442
  target: options.name,
@@ -11239,6 +11188,16 @@ var SKILLS_INSTRUCTIONS = dedent4`A skill is a set of local instructions to foll
11239
11188
 
11240
11189
  // packages/context/src/lib/skills/frontmatter.ts
11241
11190
  import YAML from "yaml";
11191
+ import { z as z13 } from "zod";
11192
+ var MISSING_NAME = 'Invalid SKILL.md: frontmatter must have a "name" field';
11193
+ var MISSING_DESCRIPTION = 'Invalid SKILL.md: frontmatter must have a "description" field';
11194
+ var frontmatterSchema = z13.looseObject(
11195
+ {
11196
+ name: z13.string({ error: MISSING_NAME }).min(1, { error: MISSING_NAME }),
11197
+ description: z13.string({ error: MISSING_DESCRIPTION }).min(1, { error: MISSING_DESCRIPTION })
11198
+ },
11199
+ { error: MISSING_NAME }
11200
+ );
11242
11201
  function parseFrontmatter(content) {
11243
11202
  const frontmatterRegex = /^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/;
11244
11203
  const match = content.match(frontmatterRegex);
@@ -11246,17 +11205,12 @@ function parseFrontmatter(content) {
11246
11205
  throw new Error("Invalid SKILL.md: missing or malformed frontmatter");
11247
11206
  }
11248
11207
  const [, yamlContent, body] = match;
11249
- const frontmatter = YAML.parse(yamlContent);
11250
- if (!frontmatter.name || typeof frontmatter.name !== "string") {
11251
- throw new Error('Invalid SKILL.md: frontmatter must have a "name" field');
11252
- }
11253
- if (!frontmatter.description || typeof frontmatter.description !== "string") {
11254
- throw new Error(
11255
- 'Invalid SKILL.md: frontmatter must have a "description" field'
11256
- );
11208
+ const parsed = frontmatterSchema.safeParse(YAML.parse(yamlContent));
11209
+ if (!parsed.success) {
11210
+ throw new Error(parsed.error.issues[0].message);
11257
11211
  }
11258
11212
  return {
11259
- frontmatter,
11213
+ frontmatter: parsed.data,
11260
11214
  body: body.trim()
11261
11215
  };
11262
11216
  }
@@ -11292,6 +11246,7 @@ function soul() {
11292
11246
 
11293
11247
  // packages/context/src/lib/store/postgres.store.ts
11294
11248
  import { createRequire } from "node:module";
11249
+ import { z as z14 } from "zod";
11295
11250
 
11296
11251
  // packages/context/src/lib/store/ddl.postgres.ts
11297
11252
  function storeDDL(schema) {
@@ -11380,6 +11335,125 @@ CREATE TRIGGER "${schema}_messages_fts_vector_update"
11380
11335
  }
11381
11336
 
11382
11337
  // packages/context/src/lib/store/postgres.store.ts
11338
+ var chatColumns2 = z14.object({
11339
+ id: z14.string(),
11340
+ userid: z14.string(),
11341
+ title: z14.string().nullable(),
11342
+ metadata: jsonObject.nullable(),
11343
+ createdat: bigintColumn,
11344
+ updatedat: bigintColumn
11345
+ });
11346
+ var storedChat2 = chatColumns2.transform(toStoredChat2);
11347
+ var chatInfo2 = chatColumns2.extend({ messagecount: bigintColumn, branchcount: bigintColumn }).transform((row) => ({
11348
+ ...toStoredChat2(row),
11349
+ messageCount: row.messagecount,
11350
+ branchCount: row.branchcount
11351
+ }));
11352
+ var messageColumns2 = z14.object({
11353
+ id: z14.string(),
11354
+ chatid: z14.string(),
11355
+ parentid: z14.string().nullable(),
11356
+ name: z14.string(),
11357
+ type: z14.string().nullable(),
11358
+ data: z14.unknown(),
11359
+ createdat: bigintColumn
11360
+ });
11361
+ var storedMessage2 = messageColumns2.transform(toMessage2);
11362
+ var searchResult2 = messageColumns2.extend({ rank: z14.number(), snippet: z14.string() }).transform((row) => ({
11363
+ message: toMessage2(row),
11364
+ rank: row.rank,
11365
+ snippet: row.snippet
11366
+ }));
11367
+ var storedBranch2 = z14.object({
11368
+ id: z14.string(),
11369
+ chatid: z14.string(),
11370
+ name: z14.string(),
11371
+ headmessageid: z14.string().nullable(),
11372
+ isactive: z14.boolean(),
11373
+ createdat: bigintColumn
11374
+ }).transform((row) => ({
11375
+ id: row.id,
11376
+ chatId: row.chatid,
11377
+ name: row.name,
11378
+ headMessageId: row.headmessageid,
11379
+ isActive: row.isactive,
11380
+ createdAt: row.createdat
11381
+ }));
11382
+ var branchRow = z14.object({
11383
+ id: z14.string(),
11384
+ name: z14.string(),
11385
+ headmessageid: z14.string().nullable(),
11386
+ isactive: z14.boolean(),
11387
+ createdat: bigintColumn
11388
+ });
11389
+ var storedCheckpoint2 = z14.object({
11390
+ id: z14.string(),
11391
+ chatid: z14.string(),
11392
+ name: z14.string(),
11393
+ messageid: z14.string(),
11394
+ createdat: bigintColumn
11395
+ }).transform((row) => ({
11396
+ id: row.id,
11397
+ chatId: row.chatid,
11398
+ name: row.name,
11399
+ messageId: row.messageid,
11400
+ createdAt: row.createdat
11401
+ }));
11402
+ var checkpointInfo2 = z14.object({
11403
+ id: z14.string(),
11404
+ name: z14.string(),
11405
+ messageid: z14.string(),
11406
+ createdat: bigintColumn
11407
+ }).transform((row) => ({
11408
+ id: row.id,
11409
+ name: row.name,
11410
+ messageId: row.messageid,
11411
+ createdAt: row.createdat
11412
+ }));
11413
+ var idRow2 = z14.object({ id: z14.string() });
11414
+ var existsRow = z14.object({ exists: z14.boolean() });
11415
+ var countRow = z14.object({ count: bigintColumn });
11416
+ var graphMessageRow2 = z14.object({
11417
+ id: z14.string(),
11418
+ parentid: z14.string().nullable(),
11419
+ name: z14.string(),
11420
+ data: z14.unknown(),
11421
+ createdat: bigintColumn
11422
+ });
11423
+ var graphBranch2 = z14.object({
11424
+ name: z14.string(),
11425
+ headmessageid: z14.string().nullable(),
11426
+ isactive: z14.boolean()
11427
+ }).transform((row) => ({
11428
+ name: row.name,
11429
+ headMessageId: row.headmessageid,
11430
+ isActive: row.isactive
11431
+ }));
11432
+ var graphCheckpoint2 = z14.object({ name: z14.string(), messageid: z14.string() }).transform((row) => ({
11433
+ name: row.name,
11434
+ messageId: row.messageid
11435
+ }));
11436
+ function toStoredChat2(row) {
11437
+ return {
11438
+ id: row.id,
11439
+ userId: row.userid,
11440
+ title: row.title ?? void 0,
11441
+ metadata: row.metadata ?? void 0,
11442
+ createdAt: row.createdat,
11443
+ updatedAt: row.updatedat
11444
+ };
11445
+ }
11446
+ function toMessage2(row) {
11447
+ return {
11448
+ id: row.id,
11449
+ chatId: row.chatid,
11450
+ parentId: row.parentid,
11451
+ name: row.name,
11452
+ type: row.type ?? void 0,
11453
+ data: row.data,
11454
+ createdAt: row.createdat
11455
+ };
11456
+ }
11383
11457
  var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11384
11458
  #pool;
11385
11459
  #schema;
@@ -11453,6 +11527,12 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11453
11527
  const result = await this.#pool.query(sql, params);
11454
11528
  return result.rows;
11455
11529
  }
11530
+ /**
11531
+ * Execute a query using the pool and parse every returned row.
11532
+ */
11533
+ async #rows(row, sql, params) {
11534
+ return z14.array(row).parse(await this.#query(sql, params));
11535
+ }
11456
11536
  /**
11457
11537
  * Close the pool connection.
11458
11538
  * Call this when done with the store.
@@ -11478,20 +11558,13 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11478
11558
  chat2.metadata ? JSON.stringify(chat2.metadata) : null
11479
11559
  ]
11480
11560
  );
11481
- const row = result.rows[0];
11561
+ const created = storedChat2.parse(result.rows[0]);
11482
11562
  await client.query(
11483
11563
  `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11484
11564
  VALUES ($1, $2, 'main', NULL, TRUE, $3)`,
11485
11565
  [crypto.randomUUID(), chat2.id, Date.now()]
11486
11566
  );
11487
- return {
11488
- id: row.id,
11489
- userId: row.userid,
11490
- title: row.title ?? void 0,
11491
- metadata: row.metadata ?? void 0,
11492
- createdAt: Number(row.createdat),
11493
- updatedAt: Number(row.updatedat)
11494
- };
11567
+ return created;
11495
11568
  });
11496
11569
  }
11497
11570
  async upsertChat(chat2) {
@@ -11508,37 +11581,23 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11508
11581
  chat2.metadata ? JSON.stringify(chat2.metadata) : null
11509
11582
  ]
11510
11583
  );
11511
- const row = result.rows[0];
11584
+ const upserted = storedChat2.parse(result.rows[0]);
11512
11585
  await client.query(
11513
11586
  `INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
11514
11587
  VALUES ($1, $2, 'main', NULL, TRUE, $3)
11515
11588
  ON CONFLICT(chatId, name) DO NOTHING`,
11516
11589
  [crypto.randomUUID(), chat2.id, Date.now()]
11517
11590
  );
11518
- return {
11519
- id: row.id,
11520
- userId: row.userid,
11521
- title: row.title ?? void 0,
11522
- metadata: row.metadata ?? void 0,
11523
- createdAt: Number(row.createdat),
11524
- updatedAt: Number(row.updatedat)
11525
- };
11591
+ return upserted;
11526
11592
  });
11527
11593
  }
11528
11594
  async getChat(chatId) {
11529
- const rows = await this.#query(`SELECT * FROM ${this.#t("chats")} WHERE id = $1`, [chatId]);
11530
- if (rows.length === 0) {
11531
- return void 0;
11532
- }
11533
- const row = rows[0];
11534
- return {
11535
- id: row.id,
11536
- userId: row.userid,
11537
- title: row.title ?? void 0,
11538
- metadata: row.metadata ?? void 0,
11539
- createdAt: Number(row.createdat),
11540
- updatedAt: Number(row.updatedat)
11541
- };
11595
+ const [chat2] = await this.#rows(
11596
+ storedChat2,
11597
+ `SELECT * FROM ${this.#t("chats")} WHERE id = $1`,
11598
+ [chatId]
11599
+ );
11600
+ return chat2;
11542
11601
  }
11543
11602
  async updateChat(chatId, update) {
11544
11603
  return this.#useTransaction(async (client) => {
@@ -11546,18 +11605,10 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11546
11605
  `SELECT * FROM ${this.#t("chats")} WHERE id = $1 FOR UPDATE`,
11547
11606
  [chatId]
11548
11607
  );
11549
- const row = result.rows[0];
11550
- if (!row) {
11608
+ const current = storedChat2.optional().parse(result.rows[0]);
11609
+ if (!current) {
11551
11610
  throw new Error(`updateChat: chat "${chatId}" not found`);
11552
11611
  }
11553
- const current = {
11554
- id: row.id,
11555
- userId: row.userid,
11556
- title: row.title ?? void 0,
11557
- metadata: row.metadata ?? void 0,
11558
- createdAt: Number(row.createdat),
11559
- updatedAt: Number(row.updatedat)
11560
- };
11561
11612
  const updates = update(current);
11562
11613
  if (updates === void 0) return current;
11563
11614
  const setClauses = [
@@ -11578,15 +11629,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11578
11629
  `UPDATE ${this.#t("chats")} SET ${setClauses.join(", ")} WHERE id = $${paramIndex} RETURNING *`,
11579
11630
  params
11580
11631
  );
11581
- const next = updated.rows[0];
11582
- return {
11583
- id: next.id,
11584
- userId: next.userid,
11585
- title: next.title ?? void 0,
11586
- metadata: next.metadata ?? void 0,
11587
- createdAt: Number(next.createdat),
11588
- updatedAt: Number(next.updatedat)
11589
- };
11632
+ return storedChat2.parse(updated.rows[0]);
11590
11633
  });
11591
11634
  }
11592
11635
  async listChats(options) {
@@ -11614,7 +11657,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11614
11657
  params.push(options.offset);
11615
11658
  }
11616
11659
  }
11617
- const rows = await this.#query(
11660
+ return this.#rows(
11661
+ chatInfo2,
11618
11662
  `SELECT
11619
11663
  c.id,
11620
11664
  c.userId,
@@ -11632,16 +11676,6 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11632
11676
  ORDER BY c.updatedAt DESC${limitClause}`,
11633
11677
  params
11634
11678
  );
11635
- return rows.map((row) => ({
11636
- id: row.id,
11637
- userId: row.userid,
11638
- title: row.title ?? void 0,
11639
- metadata: row.metadata ?? void 0,
11640
- messageCount: Number(row.messagecount),
11641
- branchCount: Number(row.branchcount),
11642
- createdAt: Number(row.createdat),
11643
- updatedAt: Number(row.updatedat)
11644
- }));
11645
11679
  }
11646
11680
  async deleteChat(chatId, options) {
11647
11681
  return this.#useTransaction(async (client) => {
@@ -11696,7 +11730,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11696
11730
  if (parentId === messageId) {
11697
11731
  throw new Error(`Message ${messageId} cannot be its own parent`);
11698
11732
  }
11699
- const rows = await this.#query(
11733
+ const rows = await this.#rows(
11734
+ idRow2,
11700
11735
  `UPDATE ${this.#t("messages")} SET parentId = $1 WHERE id = $2 RETURNING id`,
11701
11736
  [parentId, messageId]
11702
11737
  );
@@ -11705,23 +11740,16 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11705
11740
  }
11706
11741
  }
11707
11742
  async getMessage(messageId) {
11708
- const rows = await this.#query(`SELECT * FROM ${this.#t("messages")} WHERE id = $1`, [messageId]);
11709
- if (rows.length === 0) {
11710
- return void 0;
11711
- }
11712
- const row = rows[0];
11713
- return {
11714
- id: row.id,
11715
- chatId: row.chatid,
11716
- parentId: row.parentid,
11717
- name: row.name,
11718
- type: row.type ?? void 0,
11719
- data: row.data,
11720
- createdAt: Number(row.createdat)
11721
- };
11743
+ const [message2] = await this.#rows(
11744
+ storedMessage2,
11745
+ `SELECT * FROM ${this.#t("messages")} WHERE id = $1`,
11746
+ [messageId]
11747
+ );
11748
+ return message2;
11722
11749
  }
11723
11750
  async getMessageChain(headId) {
11724
- const rows = await this.#query(
11751
+ return this.#rows(
11752
+ storedMessage2,
11725
11753
  `WITH RECURSIVE chain AS (
11726
11754
  SELECT *, 0 as depth FROM ${this.#t("messages")} WHERE id = $1
11727
11755
  UNION ALL
@@ -11733,22 +11761,14 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11733
11761
  ORDER BY depth DESC`,
11734
11762
  [headId]
11735
11763
  );
11736
- return rows.map((row) => ({
11737
- id: row.id,
11738
- chatId: row.chatid,
11739
- parentId: row.parentid,
11740
- name: row.name,
11741
- type: row.type ?? void 0,
11742
- data: row.data,
11743
- createdAt: Number(row.createdat)
11744
- }));
11745
11764
  }
11746
11765
  async hasChildren(messageId) {
11747
- const rows = await this.#query(
11766
+ const [row] = await this.#rows(
11767
+ existsRow,
11748
11768
  `SELECT EXISTS(SELECT 1 FROM ${this.#t("messages")} WHERE parentId = $1) as exists`,
11749
11769
  [messageId]
11750
11770
  );
11751
- return rows[0].exists;
11771
+ return row.exists;
11752
11772
  }
11753
11773
  async getMessages(chatId) {
11754
11774
  const chat2 = await this.getChat(chatId);
@@ -11779,40 +11799,20 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11779
11799
  );
11780
11800
  }
11781
11801
  async getBranch(chatId, name) {
11782
- const rows = await this.#query(`SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND name = $2`, [
11783
- chatId,
11784
- name
11785
- ]);
11786
- if (rows.length === 0) {
11787
- return void 0;
11788
- }
11789
- const row = rows[0];
11790
- return {
11791
- id: row.id,
11792
- chatId: row.chatid,
11793
- name: row.name,
11794
- headMessageId: row.headmessageid,
11795
- isActive: row.isactive,
11796
- createdAt: Number(row.createdat)
11797
- };
11802
+ const [branch] = await this.#rows(
11803
+ storedBranch2,
11804
+ `SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND name = $2`,
11805
+ [chatId, name]
11806
+ );
11807
+ return branch;
11798
11808
  }
11799
11809
  async getActiveBranch(chatId) {
11800
- const rows = await this.#query(
11810
+ const [branch] = await this.#rows(
11811
+ storedBranch2,
11801
11812
  `SELECT * FROM ${this.#t("branches")} WHERE chatId = $1 AND isActive = TRUE`,
11802
11813
  [chatId]
11803
11814
  );
11804
- if (rows.length === 0) {
11805
- return void 0;
11806
- }
11807
- const row = rows[0];
11808
- return {
11809
- id: row.id,
11810
- chatId: row.chatid,
11811
- name: row.name,
11812
- headMessageId: row.headmessageid,
11813
- isActive: true,
11814
- createdAt: Number(row.createdat)
11815
- };
11815
+ return branch;
11816
11816
  }
11817
11817
  async setActiveBranch(chatId, branchId) {
11818
11818
  await this.#useTransaction(async (client) => {
@@ -11827,7 +11827,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11827
11827
  });
11828
11828
  }
11829
11829
  async updateBranchHead(branchId, messageId, expectedHeadMessageId) {
11830
- const rows = await this.#query(
11830
+ const rows = await this.#rows(
11831
+ idRow2,
11831
11832
  `UPDATE ${this.#t("branches")} SET headMessageId = $1
11832
11833
  WHERE id = $2 AND headMessageId IS NOT DISTINCT FROM $3
11833
11834
  RETURNING id`,
@@ -11836,7 +11837,8 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11836
11837
  return rows.length > 0;
11837
11838
  }
11838
11839
  async listBranches(chatId) {
11839
- const branches = await this.#query(
11840
+ const branches = await this.#rows(
11841
+ branchRow,
11840
11842
  `SELECT
11841
11843
  id,
11842
11844
  name,
@@ -11850,31 +11852,31 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11850
11852
  );
11851
11853
  const result = [];
11852
11854
  for (const branch of branches) {
11853
- let messageCount = 0;
11854
- if (branch.headmessageid) {
11855
- const countRows = await this.#query(
11856
- `WITH RECURSIVE chain AS (
11857
- SELECT id, parentId FROM ${this.#t("messages")} WHERE id = $1
11858
- UNION ALL
11859
- SELECT m.id, m.parentId FROM ${this.#t("messages")} m
11860
- INNER JOIN chain c ON m.id = c.parentId
11861
- )
11862
- SELECT COUNT(*) as count FROM chain`,
11863
- [branch.headmessageid]
11864
- );
11865
- messageCount = Number(countRows[0].count);
11866
- }
11867
11855
  result.push({
11868
11856
  id: branch.id,
11869
11857
  name: branch.name,
11870
11858
  headMessageId: branch.headmessageid,
11871
11859
  isActive: branch.isactive,
11872
- messageCount,
11873
- createdAt: Number(branch.createdat)
11860
+ messageCount: branch.headmessageid ? await this.#countChain(branch.headmessageid) : 0,
11861
+ createdAt: branch.createdat
11874
11862
  });
11875
11863
  }
11876
11864
  return result;
11877
11865
  }
11866
+ async #countChain(headMessageId) {
11867
+ const [row] = await this.#rows(
11868
+ countRow,
11869
+ `WITH RECURSIVE chain AS (
11870
+ SELECT id, parentId FROM ${this.#t("messages")} WHERE id = $1
11871
+ UNION ALL
11872
+ SELECT m.id, m.parentId FROM ${this.#t("messages")} m
11873
+ INNER JOIN chain c ON m.id = c.parentId
11874
+ )
11875
+ SELECT COUNT(*) as count FROM chain`,
11876
+ [headMessageId]
11877
+ );
11878
+ return row.count;
11879
+ }
11878
11880
  // ==========================================================================
11879
11881
  // Checkpoint Operations
11880
11882
  // ==========================================================================
@@ -11895,36 +11897,22 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11895
11897
  );
11896
11898
  }
11897
11899
  async getCheckpoint(chatId, name) {
11898
- const rows = await this.#query(
11900
+ const [checkpoint] = await this.#rows(
11901
+ storedCheckpoint2,
11899
11902
  `SELECT * FROM ${this.#t("checkpoints")} WHERE chatId = $1 AND name = $2`,
11900
11903
  [chatId, name]
11901
11904
  );
11902
- if (rows.length === 0) {
11903
- return void 0;
11904
- }
11905
- const row = rows[0];
11906
- return {
11907
- id: row.id,
11908
- chatId: row.chatid,
11909
- name: row.name,
11910
- messageId: row.messageid,
11911
- createdAt: Number(row.createdat)
11912
- };
11905
+ return checkpoint;
11913
11906
  }
11914
11907
  async listCheckpoints(chatId) {
11915
- const rows = await this.#query(
11908
+ return this.#rows(
11909
+ checkpointInfo2,
11916
11910
  `SELECT id, name, messageId, createdAt
11917
11911
  FROM ${this.#t("checkpoints")}
11918
11912
  WHERE chatId = $1
11919
11913
  ORDER BY createdAt DESC`,
11920
11914
  [chatId]
11921
11915
  );
11922
- return rows.map((row) => ({
11923
- id: row.id,
11924
- name: row.name,
11925
- messageId: row.messageid,
11926
- createdAt: Number(row.createdat)
11927
- }));
11928
11916
  }
11929
11917
  async deleteCheckpoint(chatId, name) {
11930
11918
  await this.#query(
@@ -11964,26 +11952,14 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11964
11952
  }
11965
11953
  sql += ` ORDER BY rank DESC LIMIT $${paramIndex}`;
11966
11954
  params.push(limit);
11967
- const rows = await this.#query(sql, params);
11968
- return rows.map((row) => ({
11969
- message: {
11970
- id: row.id,
11971
- chatId: row.chatid,
11972
- parentId: row.parentid,
11973
- name: row.name,
11974
- type: row.type ?? void 0,
11975
- data: row.data,
11976
- createdAt: Number(row.createdat)
11977
- },
11978
- rank: row.rank,
11979
- snippet: row.snippet
11980
- }));
11955
+ return this.#rows(searchResult2, sql, params);
11981
11956
  }
11982
11957
  // ==========================================================================
11983
11958
  // Visualization Operations
11984
11959
  // ==========================================================================
11985
11960
  async getGraph(chatId) {
11986
- const messageRows = await this.#query(
11961
+ const messageRows = await this.#rows(
11962
+ graphMessageRow2,
11987
11963
  `SELECT id, parentId, name, data, createdAt
11988
11964
  FROM ${this.#t("messages")}
11989
11965
  WHERE chatId = $1
@@ -11998,32 +11974,25 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
11998
11974
  parentId: row.parentid,
11999
11975
  role: row.name,
12000
11976
  content: content.length > 50 ? content.slice(0, 50) + "..." : content,
12001
- createdAt: Number(row.createdat)
11977
+ createdAt: row.createdat
12002
11978
  };
12003
11979
  });
12004
- const branchRows = await this.#query(
11980
+ const branches = await this.#rows(
11981
+ graphBranch2,
12005
11982
  `SELECT name, headMessageId, isActive
12006
11983
  FROM ${this.#t("branches")}
12007
11984
  WHERE chatId = $1
12008
11985
  ORDER BY createdAt ASC`,
12009
11986
  [chatId]
12010
11987
  );
12011
- const branches = branchRows.map((row) => ({
12012
- name: row.name,
12013
- headMessageId: row.headmessageid,
12014
- isActive: row.isactive
12015
- }));
12016
- const checkpointRows = await this.#query(
11988
+ const checkpoints = await this.#rows(
11989
+ graphCheckpoint2,
12017
11990
  `SELECT name, messageId
12018
11991
  FROM ${this.#t("checkpoints")}
12019
11992
  WHERE chatId = $1
12020
11993
  ORDER BY createdAt ASC`,
12021
11994
  [chatId]
12022
11995
  );
12023
- const checkpoints = checkpointRows.map((row) => ({
12024
- name: row.name,
12025
- messageId: row.messageid
12026
- }));
12027
11996
  return {
12028
11997
  chatId,
12029
11998
  nodes,
@@ -12035,6 +12004,7 @@ var PostgresContextStore = class _PostgresContextStore extends ContextStore {
12035
12004
 
12036
12005
  // packages/context/src/lib/store/sqlserver.store.ts
12037
12006
  import { createRequire as createRequire2 } from "node:module";
12007
+ import { z as z15 } from "zod";
12038
12008
 
12039
12009
  // packages/context/src/lib/store/ddl.sqlserver.ts
12040
12010
  function storeDDL2(schema) {
@@ -12153,6 +12123,104 @@ END;
12153
12123
  }
12154
12124
 
12155
12125
  // packages/context/src/lib/store/sqlserver.store.ts
12126
+ var chatColumns3 = z15.object({
12127
+ id: z15.string(),
12128
+ userId: z15.string(),
12129
+ title: z15.string().nullable(),
12130
+ metadata: z15.string().nullable(),
12131
+ createdAt: bigintColumn,
12132
+ updatedAt: bigintColumn
12133
+ });
12134
+ var storedChat3 = chatColumns3.transform(toStoredChat3);
12135
+ var chatInfo3 = chatColumns3.extend({ messageCount: z15.number(), branchCount: z15.number() }).transform((row) => ({
12136
+ ...toStoredChat3(row),
12137
+ messageCount: row.messageCount,
12138
+ branchCount: row.branchCount
12139
+ }));
12140
+ var messageColumns3 = z15.object({
12141
+ id: z15.string(),
12142
+ chatId: z15.string(),
12143
+ parentId: z15.string().nullable(),
12144
+ name: z15.string(),
12145
+ type: z15.string().nullable(),
12146
+ data: z15.string(),
12147
+ createdAt: bigintColumn
12148
+ });
12149
+ var storedMessage3 = messageColumns3.transform(toMessage3);
12150
+ var searchResult3 = messageColumns3.extend({ rank: z15.number(), snippet: z15.string() }).transform((row) => ({
12151
+ message: toMessage3(row),
12152
+ rank: row.rank,
12153
+ snippet: row.snippet
12154
+ }));
12155
+ var storedBranch3 = z15.object({
12156
+ id: z15.string(),
12157
+ chatId: z15.string(),
12158
+ name: z15.string(),
12159
+ headMessageId: z15.string().nullable(),
12160
+ isActive: z15.boolean(),
12161
+ createdAt: bigintColumn
12162
+ });
12163
+ var branchRow2 = z15.object({
12164
+ id: z15.string(),
12165
+ name: z15.string(),
12166
+ headMessageId: z15.string().nullable(),
12167
+ isActive: z15.boolean(),
12168
+ createdAt: bigintColumn
12169
+ });
12170
+ var storedCheckpoint3 = z15.object({
12171
+ id: z15.string(),
12172
+ chatId: z15.string(),
12173
+ name: z15.string(),
12174
+ messageId: z15.string(),
12175
+ createdAt: bigintColumn
12176
+ });
12177
+ var checkpointInfo3 = z15.object({
12178
+ id: z15.string(),
12179
+ name: z15.string(),
12180
+ messageId: z15.string(),
12181
+ createdAt: bigintColumn
12182
+ });
12183
+ var idRow3 = z15.object({ id: z15.string() });
12184
+ var hasChildrenRow2 = z15.object({ hasChildren: z15.number() });
12185
+ var countRow2 = z15.object({ count: z15.number() });
12186
+ var ftsInstalledRow = z15.object({ ftsInstalled: z15.number().nullable() });
12187
+ var graphMessageRow3 = z15.object({
12188
+ id: z15.string(),
12189
+ parentId: z15.string().nullable(),
12190
+ name: z15.string(),
12191
+ data: z15.string(),
12192
+ createdAt: bigintColumn
12193
+ });
12194
+ var graphBranch3 = z15.object({
12195
+ name: z15.string(),
12196
+ headMessageId: z15.string().nullable(),
12197
+ isActive: z15.boolean()
12198
+ });
12199
+ var graphCheckpoint3 = z15.object({
12200
+ name: z15.string(),
12201
+ messageId: z15.string()
12202
+ });
12203
+ function toStoredChat3(row) {
12204
+ return {
12205
+ id: row.id,
12206
+ userId: row.userId,
12207
+ title: row.title ?? void 0,
12208
+ metadata: row.metadata ? parseJsonObject(row.metadata) : void 0,
12209
+ createdAt: row.createdAt,
12210
+ updatedAt: row.updatedAt
12211
+ };
12212
+ }
12213
+ function toMessage3(row) {
12214
+ return {
12215
+ id: row.id,
12216
+ chatId: row.chatId,
12217
+ parentId: row.parentId,
12218
+ name: row.name,
12219
+ type: row.type ?? void 0,
12220
+ data: parseJson(row.data),
12221
+ createdAt: row.createdAt
12222
+ };
12223
+ }
12156
12224
  var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12157
12225
  #pool;
12158
12226
  #schema;
@@ -12247,6 +12315,12 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12247
12315
  const result = await request.query(sql);
12248
12316
  return result.recordset;
12249
12317
  }
12318
+ /**
12319
+ * Execute a query using the pool and parse every returned row.
12320
+ */
12321
+ async #rows(row, sql, params) {
12322
+ return z15.array(row).parse(await this.#query(sql, params));
12323
+ }
12250
12324
  /**
12251
12325
  * Close the pool connection.
12252
12326
  * Call this when done with the store.
@@ -12276,7 +12350,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12276
12350
  OUTPUT INSERTED.*
12277
12351
  VALUES (@p0, @p1, @p2, @p3)
12278
12352
  `);
12279
- const row = result.recordset[0];
12353
+ const created = storedChat3.parse(result.recordset[0]);
12280
12354
  const branchRequest = transaction.request();
12281
12355
  branchRequest.input("p0", mssql.NVarChar, crypto.randomUUID());
12282
12356
  branchRequest.input("p1", mssql.NVarChar, chat2.id);
@@ -12285,14 +12359,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12285
12359
  INSERT INTO ${this.#t("branches")} (id, chatId, name, headMessageId, isActive, createdAt)
12286
12360
  VALUES (@p0, @p1, 'main', NULL, 1, @p2)
12287
12361
  `);
12288
- return {
12289
- id: row.id,
12290
- userId: row.userId,
12291
- title: row.title ?? void 0,
12292
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
12293
- createdAt: Number(row.createdAt),
12294
- updatedAt: Number(row.updatedAt)
12295
- };
12362
+ return created;
12296
12363
  });
12297
12364
  }
12298
12365
  async upsertChat(chat2) {
@@ -12319,7 +12386,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12319
12386
  VALUES (source.id, source.userId, source.title, source.metadata, @p4, @p4)
12320
12387
  OUTPUT INSERTED.*;
12321
12388
  `);
12322
- const row = result.recordset[0];
12389
+ const upserted = storedChat3.parse(result.recordset[0]);
12323
12390
  const branchRequest = transaction.request();
12324
12391
  branchRequest.input("p0", mssql.NVarChar, crypto.randomUUID());
12325
12392
  branchRequest.input("p1", mssql.NVarChar, chat2.id);
@@ -12331,30 +12398,16 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12331
12398
  VALUES (@p0, @p1, 'main', NULL, 1, @p2)
12332
12399
  END
12333
12400
  `);
12334
- return {
12335
- id: row.id,
12336
- userId: row.userId,
12337
- title: row.title ?? void 0,
12338
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
12339
- createdAt: Number(row.createdAt),
12340
- updatedAt: Number(row.updatedAt)
12341
- };
12401
+ return upserted;
12342
12402
  });
12343
12403
  }
12344
12404
  async getChat(chatId) {
12345
- const rows = await this.#query(`SELECT * FROM ${this.#t("chats")} WHERE id = @p0`, [chatId]);
12346
- if (rows.length === 0) {
12347
- return void 0;
12348
- }
12349
- const row = rows[0];
12350
- return {
12351
- id: row.id,
12352
- userId: row.userId,
12353
- title: row.title ?? void 0,
12354
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
12355
- createdAt: Number(row.createdAt),
12356
- updatedAt: Number(row.updatedAt)
12357
- };
12405
+ const [chat2] = await this.#rows(
12406
+ storedChat3,
12407
+ `SELECT * FROM ${this.#t("chats")} WHERE id = @p0`,
12408
+ [chatId]
12409
+ );
12410
+ return chat2;
12358
12411
  }
12359
12412
  async updateChat(chatId, update) {
12360
12413
  return this.#useTransaction(async (transaction) => {
@@ -12366,18 +12419,10 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12366
12419
  FROM ${this.#t("chats")} WITH (UPDLOCK, HOLDLOCK)
12367
12420
  WHERE id = @chatId;
12368
12421
  `);
12369
- const row = result.recordset[0];
12370
- if (!row) {
12422
+ const current = storedChat3.optional().parse(result.recordset[0]);
12423
+ if (!current) {
12371
12424
  throw new Error(`updateChat: chat "${chatId}" not found`);
12372
12425
  }
12373
- const current = {
12374
- id: row.id,
12375
- userId: row.userId,
12376
- title: row.title ?? void 0,
12377
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
12378
- createdAt: Number(row.createdAt),
12379
- updatedAt: Number(row.updatedAt)
12380
- };
12381
12426
  const updates = update(current);
12382
12427
  if (updates === void 0) return current;
12383
12428
  const setClauses = [
@@ -12402,15 +12447,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12402
12447
  OUTPUT INSERTED.*
12403
12448
  WHERE id = @chatId;
12404
12449
  `);
12405
- const next = updated.recordset[0];
12406
- return {
12407
- id: next.id,
12408
- userId: next.userId,
12409
- title: next.title ?? void 0,
12410
- metadata: next.metadata ? JSON.parse(next.metadata) : void 0,
12411
- createdAt: Number(next.createdAt),
12412
- updatedAt: Number(next.updatedAt)
12413
- };
12450
+ return storedChat3.parse(updated.recordset[0]);
12414
12451
  });
12415
12452
  }
12416
12453
  async listChats(options) {
@@ -12436,7 +12473,8 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12436
12473
  params.push(options.offset ?? 0);
12437
12474
  params.push(options.limit);
12438
12475
  }
12439
- const rows = await this.#query(
12476
+ return this.#rows(
12477
+ chatInfo3,
12440
12478
  `SELECT
12441
12479
  c.id,
12442
12480
  c.userId,
@@ -12454,16 +12492,6 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12454
12492
  ORDER BY c.updatedAt DESC${paginationClause}`,
12455
12493
  params
12456
12494
  );
12457
- return rows.map((row) => ({
12458
- id: row.id,
12459
- userId: row.userId,
12460
- title: row.title ?? void 0,
12461
- metadata: row.metadata ? JSON.parse(row.metadata) : void 0,
12462
- messageCount: Number(row.messageCount),
12463
- branchCount: Number(row.branchCount),
12464
- createdAt: Number(row.createdAt),
12465
- updatedAt: Number(row.updatedAt)
12466
- }));
12467
12495
  }
12468
12496
  async deleteChat(chatId, options) {
12469
12497
  return this.#useTransaction(async (transaction) => {
@@ -12528,7 +12556,8 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12528
12556
  if (parentId === messageId) {
12529
12557
  throw new Error(`Message ${messageId} cannot be its own parent`);
12530
12558
  }
12531
- const rows = await this.#query(
12559
+ const rows = await this.#rows(
12560
+ idRow3,
12532
12561
  `UPDATE ${this.#t("messages")} SET parentId = @p0
12533
12562
  OUTPUT INSERTED.id
12534
12563
  WHERE id = @p1`,
@@ -12539,23 +12568,16 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12539
12568
  }
12540
12569
  }
12541
12570
  async getMessage(messageId) {
12542
- const rows = await this.#query(`SELECT * FROM ${this.#t("messages")} WHERE id = @p0`, [messageId]);
12543
- if (rows.length === 0) {
12544
- return void 0;
12545
- }
12546
- const row = rows[0];
12547
- return {
12548
- id: row.id,
12549
- chatId: row.chatId,
12550
- parentId: row.parentId,
12551
- name: row.name,
12552
- type: row.type ?? void 0,
12553
- data: JSON.parse(row.data),
12554
- createdAt: Number(row.createdAt)
12555
- };
12571
+ const [message2] = await this.#rows(
12572
+ storedMessage3,
12573
+ `SELECT * FROM ${this.#t("messages")} WHERE id = @p0`,
12574
+ [messageId]
12575
+ );
12576
+ return message2;
12556
12577
  }
12557
12578
  async getMessageChain(headId) {
12558
- const rows = await this.#query(
12579
+ return this.#rows(
12580
+ storedMessage3,
12559
12581
  `WITH chain AS (
12560
12582
  SELECT *, 0 as depth FROM ${this.#t("messages")} WHERE id = @p0
12561
12583
  UNION ALL
@@ -12567,22 +12589,14 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12567
12589
  ORDER BY depth DESC`,
12568
12590
  [headId]
12569
12591
  );
12570
- return rows.map((row) => ({
12571
- id: row.id,
12572
- chatId: row.chatId,
12573
- parentId: row.parentId,
12574
- name: row.name,
12575
- type: row.type ?? void 0,
12576
- data: JSON.parse(row.data),
12577
- createdAt: Number(row.createdAt)
12578
- }));
12579
12592
  }
12580
12593
  async hasChildren(messageId) {
12581
- const rows = await this.#query(
12594
+ const [row] = await this.#rows(
12595
+ hasChildrenRow2,
12582
12596
  `SELECT CASE WHEN EXISTS(SELECT 1 FROM ${this.#t("messages")} WHERE parentId = @p0) THEN 1 ELSE 0 END as hasChildren`,
12583
12597
  [messageId]
12584
12598
  );
12585
- return rows[0].hasChildren === 1;
12599
+ return row.hasChildren === 1;
12586
12600
  }
12587
12601
  async getMessages(chatId) {
12588
12602
  const chat2 = await this.getChat(chatId);
@@ -12613,40 +12627,20 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12613
12627
  );
12614
12628
  }
12615
12629
  async getBranch(chatId, name) {
12616
- const rows = await this.#query(
12630
+ const [branch] = await this.#rows(
12631
+ storedBranch3,
12617
12632
  `SELECT * FROM ${this.#t("branches")} WHERE chatId = @p0 AND name = @p1`,
12618
12633
  [chatId, name]
12619
12634
  );
12620
- if (rows.length === 0) {
12621
- return void 0;
12622
- }
12623
- const row = rows[0];
12624
- return {
12625
- id: row.id,
12626
- chatId: row.chatId,
12627
- name: row.name,
12628
- headMessageId: row.headMessageId,
12629
- isActive: row.isActive === true || row.isActive === 1,
12630
- createdAt: Number(row.createdAt)
12631
- };
12635
+ return branch;
12632
12636
  }
12633
12637
  async getActiveBranch(chatId) {
12634
- const rows = await this.#query(
12638
+ const [branch] = await this.#rows(
12639
+ storedBranch3,
12635
12640
  `SELECT * FROM ${this.#t("branches")} WHERE chatId = @p0 AND isActive = 1`,
12636
12641
  [chatId]
12637
12642
  );
12638
- if (rows.length === 0) {
12639
- return void 0;
12640
- }
12641
- const row = rows[0];
12642
- return {
12643
- id: row.id,
12644
- chatId: row.chatId,
12645
- name: row.name,
12646
- headMessageId: row.headMessageId,
12647
- isActive: true,
12648
- createdAt: Number(row.createdAt)
12649
- };
12643
+ return branch;
12650
12644
  }
12651
12645
  async setActiveBranch(chatId, branchId) {
12652
12646
  await this.#useTransaction(async (transaction) => {
@@ -12664,7 +12658,8 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12664
12658
  });
12665
12659
  }
12666
12660
  async updateBranchHead(branchId, messageId, expectedHeadMessageId) {
12667
- const rows = await this.#query(
12661
+ const rows = await this.#rows(
12662
+ idRow3,
12668
12663
  `UPDATE ${this.#t("branches")} SET headMessageId = @p0
12669
12664
  OUTPUT INSERTED.id
12670
12665
  WHERE id = @p1
@@ -12674,7 +12669,8 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12674
12669
  return rows.length > 0;
12675
12670
  }
12676
12671
  async listBranches(chatId) {
12677
- const branches = await this.#query(
12672
+ const branches = await this.#rows(
12673
+ branchRow2,
12678
12674
  `SELECT
12679
12675
  id,
12680
12676
  name,
@@ -12688,31 +12684,31 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12688
12684
  );
12689
12685
  const result = [];
12690
12686
  for (const branch of branches) {
12691
- let messageCount = 0;
12692
- if (branch.headMessageId) {
12693
- const countRows = await this.#query(
12694
- `WITH chain AS (
12695
- SELECT id, parentId FROM ${this.#t("messages")} WHERE id = @p0
12696
- UNION ALL
12697
- SELECT m.id, m.parentId FROM ${this.#t("messages")} m
12698
- INNER JOIN chain c ON m.id = c.parentId
12699
- )
12700
- SELECT COUNT(*) as count FROM chain`,
12701
- [branch.headMessageId]
12702
- );
12703
- messageCount = Number(countRows[0].count);
12704
- }
12705
12687
  result.push({
12706
12688
  id: branch.id,
12707
12689
  name: branch.name,
12708
12690
  headMessageId: branch.headMessageId,
12709
- isActive: branch.isActive === true || branch.isActive === 1,
12710
- messageCount,
12711
- createdAt: Number(branch.createdAt)
12691
+ isActive: branch.isActive,
12692
+ messageCount: branch.headMessageId ? await this.#countChain(branch.headMessageId) : 0,
12693
+ createdAt: branch.createdAt
12712
12694
  });
12713
12695
  }
12714
12696
  return result;
12715
12697
  }
12698
+ async #countChain(headMessageId) {
12699
+ const [row] = await this.#rows(
12700
+ countRow2,
12701
+ `WITH chain AS (
12702
+ SELECT id, parentId FROM ${this.#t("messages")} WHERE id = @p0
12703
+ UNION ALL
12704
+ SELECT m.id, m.parentId FROM ${this.#t("messages")} m
12705
+ INNER JOIN chain c ON m.id = c.parentId
12706
+ )
12707
+ SELECT COUNT(*) as count FROM chain`,
12708
+ [headMessageId]
12709
+ );
12710
+ return row.count;
12711
+ }
12716
12712
  // ==========================================================================
12717
12713
  // Checkpoint Operations
12718
12714
  // ==========================================================================
@@ -12738,36 +12734,22 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12738
12734
  });
12739
12735
  }
12740
12736
  async getCheckpoint(chatId, name) {
12741
- const rows = await this.#query(
12737
+ const [checkpoint] = await this.#rows(
12738
+ storedCheckpoint3,
12742
12739
  `SELECT * FROM ${this.#t("checkpoints")} WHERE chatId = @p0 AND name = @p1`,
12743
12740
  [chatId, name]
12744
12741
  );
12745
- if (rows.length === 0) {
12746
- return void 0;
12747
- }
12748
- const row = rows[0];
12749
- return {
12750
- id: row.id,
12751
- chatId: row.chatId,
12752
- name: row.name,
12753
- messageId: row.messageId,
12754
- createdAt: Number(row.createdAt)
12755
- };
12742
+ return checkpoint;
12756
12743
  }
12757
12744
  async listCheckpoints(chatId) {
12758
- const rows = await this.#query(
12745
+ return this.#rows(
12746
+ checkpointInfo3,
12759
12747
  `SELECT id, name, messageId, createdAt
12760
12748
  FROM ${this.#t("checkpoints")}
12761
12749
  WHERE chatId = @p0
12762
12750
  ORDER BY createdAt DESC`,
12763
12751
  [chatId]
12764
12752
  );
12765
- return rows.map((row) => ({
12766
- id: row.id,
12767
- name: row.name,
12768
- messageId: row.messageId,
12769
- createdAt: Number(row.createdAt)
12770
- }));
12771
12753
  }
12772
12754
  async deleteCheckpoint(chatId, name) {
12773
12755
  await this.#query(
@@ -12781,7 +12763,8 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12781
12763
  async searchMessages(chatId, query, options) {
12782
12764
  const limit = options?.limit ?? 20;
12783
12765
  const roles = options?.roles;
12784
- const ftsCheck = await this.#query(
12766
+ const ftsCheck = await this.#rows(
12767
+ ftsInstalledRow,
12785
12768
  `SELECT CAST(SERVERPROPERTY('IsFullTextInstalled') AS INT) as ftsInstalled`
12786
12769
  );
12787
12770
  const ftsAvailable = ftsCheck[0]?.ftsInstalled === 1;
@@ -12812,20 +12795,7 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12812
12795
  }
12813
12796
  sql += ` ORDER BY ct.RANK DESC OFFSET 0 ROWS FETCH NEXT @p${paramIndex} ROWS ONLY`;
12814
12797
  params.push(limit);
12815
- const rows = await this.#query(sql, params);
12816
- return rows.map((row) => ({
12817
- message: {
12818
- id: row.id,
12819
- chatId: row.chatId,
12820
- parentId: row.parentId,
12821
- name: row.name,
12822
- type: row.type ?? void 0,
12823
- data: JSON.parse(row.data),
12824
- createdAt: Number(row.createdAt)
12825
- },
12826
- rank: row.rank,
12827
- snippet: row.snippet
12828
- }));
12798
+ return this.#rows(searchResult3, sql, params);
12829
12799
  } else {
12830
12800
  let sql = `
12831
12801
  SELECT
@@ -12851,27 +12821,15 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12851
12821
  }
12852
12822
  sql += ` ORDER BY m.createdAt DESC OFFSET 0 ROWS FETCH NEXT @p${paramIndex} ROWS ONLY`;
12853
12823
  params.push(limit);
12854
- const rows = await this.#query(sql, params);
12855
- return rows.map((row) => ({
12856
- message: {
12857
- id: row.id,
12858
- chatId: row.chatId,
12859
- parentId: row.parentId,
12860
- name: row.name,
12861
- type: row.type ?? void 0,
12862
- data: JSON.parse(row.data),
12863
- createdAt: Number(row.createdAt)
12864
- },
12865
- rank: row.rank,
12866
- snippet: row.snippet
12867
- }));
12824
+ return this.#rows(searchResult3, sql, params);
12868
12825
  }
12869
12826
  }
12870
12827
  // ==========================================================================
12871
12828
  // Visualization Operations
12872
12829
  // ==========================================================================
12873
12830
  async getGraph(chatId) {
12874
- const messageRows = await this.#query(
12831
+ const messageRows = await this.#rows(
12832
+ graphMessageRow3,
12875
12833
  `SELECT id, parentId, name, data, createdAt
12876
12834
  FROM ${this.#t("messages")}
12877
12835
  WHERE chatId = @p0
@@ -12879,39 +12837,32 @@ var SqlServerContextStore = class _SqlServerContextStore extends ContextStore {
12879
12837
  [chatId]
12880
12838
  );
12881
12839
  const nodes = messageRows.map((row) => {
12882
- const data = JSON.parse(row.data);
12840
+ const data = parseJson(row.data);
12883
12841
  const content = typeof data === "string" ? data : JSON.stringify(data);
12884
12842
  return {
12885
12843
  id: row.id,
12886
12844
  parentId: row.parentId,
12887
12845
  role: row.name,
12888
12846
  content: content.length > 50 ? content.slice(0, 50) + "..." : content,
12889
- createdAt: Number(row.createdAt)
12847
+ createdAt: row.createdAt
12890
12848
  };
12891
12849
  });
12892
- const branchRows = await this.#query(
12850
+ const branches = await this.#rows(
12851
+ graphBranch3,
12893
12852
  `SELECT name, headMessageId, isActive
12894
12853
  FROM ${this.#t("branches")}
12895
12854
  WHERE chatId = @p0
12896
12855
  ORDER BY createdAt ASC`,
12897
12856
  [chatId]
12898
12857
  );
12899
- const branches = branchRows.map((row) => ({
12900
- name: row.name,
12901
- headMessageId: row.headMessageId,
12902
- isActive: row.isActive === true || row.isActive === 1
12903
- }));
12904
- const checkpointRows = await this.#query(
12858
+ const checkpoints = await this.#rows(
12859
+ graphCheckpoint3,
12905
12860
  `SELECT name, messageId
12906
12861
  FROM ${this.#t("checkpoints")}
12907
12862
  WHERE chatId = @p0
12908
12863
  ORDER BY createdAt ASC`,
12909
12864
  [chatId]
12910
12865
  );
12911
- const checkpoints = checkpointRows.map((row) => ({
12912
- name: row.name,
12913
- messageId: row.messageId
12914
- }));
12915
12866
  return {
12916
12867
  chatId,
12917
12868
  nodes,
@@ -13179,47 +13130,37 @@ function asStaticWordText(word, options = {}) {
13179
13130
  if (!word) {
13180
13131
  return null;
13181
13132
  }
13182
- return asStaticWordPartText(
13183
- word.parts,
13184
- options
13185
- );
13133
+ return asStaticWordPartText(word.parts, options);
13186
13134
  }
13187
13135
  function asStaticWordPartText(parts, options = {}) {
13188
- let text = "";
13136
+ const texts = [];
13189
13137
  for (const part of parts) {
13190
- const type = part.type;
13191
- if (type === "Literal" || type === "SingleQuoted" || type === "Escaped") {
13192
- if (typeof part.value !== "string") {
13193
- return null;
13194
- }
13195
- text += part.value;
13196
- continue;
13197
- }
13198
- if (type === "DoubleQuoted") {
13199
- if (!Array.isArray(part.parts)) {
13200
- return null;
13201
- }
13202
- const inner = asStaticWordPartText(
13203
- part.parts,
13204
- options
13205
- );
13206
- if (inner == null) {
13207
- return null;
13208
- }
13209
- text += inner;
13210
- continue;
13211
- }
13212
- if (options.preserveLegacyBackticks && type === "CommandSubstitution" && part.legacy === true) {
13213
- text += "`" + serialize(part.body).trim() + "`";
13214
- continue;
13138
+ const text = staticPartText(part, options);
13139
+ if (text == null) {
13140
+ return null;
13215
13141
  }
13216
- return null;
13142
+ texts.push(text);
13143
+ }
13144
+ return texts.join("");
13145
+ }
13146
+ function staticPartText(part, options) {
13147
+ switch (part.type) {
13148
+ case "Literal":
13149
+ case "SingleQuoted":
13150
+ case "Escaped":
13151
+ return part.value;
13152
+ case "DoubleQuoted":
13153
+ return asStaticWordPartText(part.parts, options);
13154
+ case "CommandSubstitution":
13155
+ return options.preserveLegacyBackticks && part.legacy ? "`" + serialize(part.body).trim() + "`" : null;
13156
+ default:
13157
+ return null;
13217
13158
  }
13218
- return text;
13219
13159
  }
13220
13160
 
13221
13161
  // packages/context/src/lib/stream/postgres-notify-change-source.ts
13222
13162
  import { createRequire as createRequire3 } from "node:module";
13163
+ import { z as z16 } from "zod";
13223
13164
 
13224
13165
  // packages/context/src/lib/stream/ddl.stream.postgres-notify.ts
13225
13166
  var DEFAULT_POSTGRES_STREAM_CHANGES_CHANNEL = "deepagents_stream_changes";
@@ -13549,19 +13490,15 @@ var ChangeQueue = class {
13549
13490
  });
13550
13491
  }
13551
13492
  };
13493
+ var notificationPayload = z16.object({
13494
+ schema: z16.string(),
13495
+ streamId: z16.string(),
13496
+ kind: z16.string()
13497
+ });
13552
13498
  function parsePayload(payload) {
13553
13499
  try {
13554
- const parsed = JSON.parse(payload);
13555
- if (!parsed || typeof parsed !== "object") return void 0;
13556
- const candidate = parsed;
13557
- if (typeof candidate.schema !== "string" || typeof candidate.streamId !== "string" || typeof candidate.kind !== "string") {
13558
- return void 0;
13559
- }
13560
- return {
13561
- schema: candidate.schema,
13562
- streamId: candidate.streamId,
13563
- kind: candidate.kind
13564
- };
13500
+ const parsed = notificationPayload.safeParse(parseJson(payload));
13501
+ return parsed.success ? parsed.data : void 0;
13565
13502
  } catch {
13566
13503
  return void 0;
13567
13504
  }
@@ -13577,6 +13514,7 @@ function assertIdentifier(value, label) {
13577
13514
 
13578
13515
  // packages/context/src/lib/stream/postgres.stream-store.ts
13579
13516
  import { createRequire as createRequire4 } from "node:module";
13517
+ import { z as z18 } from "zod";
13580
13518
 
13581
13519
  // packages/context/src/lib/stream/ddl.stream.postgres.ts
13582
13520
  function postgresStreamDDL(schema) {
@@ -13611,6 +13549,21 @@ CREATE INDEX IF NOT EXISTS "idx_${schema}_streams_status_created_at_id"
13611
13549
  `;
13612
13550
  }
13613
13551
 
13552
+ // packages/context/src/lib/stream/rows.ts
13553
+ import { validateTypes } from "@ai-sdk/provider-utils";
13554
+ import { uiMessageChunkSchema } from "ai";
13555
+ import { z as z17 } from "zod";
13556
+ var streamStatus = z17.enum([
13557
+ "queued",
13558
+ "running",
13559
+ "completed",
13560
+ "failed",
13561
+ "cancelled"
13562
+ ]);
13563
+ function toStreamPart(value) {
13564
+ return validateTypes({ value, schema: uiMessageChunkSchema });
13565
+ }
13566
+
13614
13567
  // packages/context/src/lib/stream/stream-store.ts
13615
13568
  function collectStreamFailures(chunks) {
13616
13569
  const failures = /* @__PURE__ */ new Map();
@@ -13628,6 +13581,31 @@ var StreamStore = class {
13628
13581
  };
13629
13582
 
13630
13583
  // packages/context/src/lib/stream/postgres.stream-store.ts
13584
+ var storedStream = z18.object({
13585
+ id: z18.string(),
13586
+ status: streamStatus,
13587
+ created_at: bigintColumn,
13588
+ started_at: bigintColumn.nullable(),
13589
+ finished_at: bigintColumn.nullable(),
13590
+ cancel_requested_at: bigintColumn.nullable(),
13591
+ error: z18.string().nullable()
13592
+ }).transform((row) => ({
13593
+ id: row.id,
13594
+ status: row.status,
13595
+ createdAt: row.created_at,
13596
+ startedAt: row.started_at,
13597
+ finishedAt: row.finished_at,
13598
+ cancelRequestedAt: row.cancel_requested_at,
13599
+ error: row.error
13600
+ }));
13601
+ var statusRow = z18.object({ status: streamStatus });
13602
+ var idRow4 = z18.object({ id: z18.string() });
13603
+ var chunkRow = z18.object({
13604
+ stream_id: z18.string(),
13605
+ seq: z18.number(),
13606
+ data: z18.unknown(),
13607
+ created_at: bigintColumn
13608
+ });
13631
13609
  var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13632
13610
  #pool;
13633
13611
  #schema;
@@ -13684,6 +13662,9 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13684
13662
  const result = await this.#pool.query(sql, params);
13685
13663
  return result.rows;
13686
13664
  }
13665
+ async #rows(row, sql, params) {
13666
+ return z18.array(row).parse(await this.#query(sql, params));
13667
+ }
13687
13668
  async #useTransaction(fn) {
13688
13669
  this.#ensureInitialized();
13689
13670
  const client = await this.#pool.connect();
@@ -13708,7 +13689,8 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13708
13689
  );
13709
13690
  }
13710
13691
  async upsertStream(stream) {
13711
- const rows = await this.#query(
13692
+ const [created] = await this.#rows(
13693
+ storedStream,
13712
13694
  `INSERT INTO ${this.#t("streams")}
13713
13695
  (id, status, created_at, started_at, finished_at, cancel_requested_at, error)
13714
13696
  VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -13716,8 +13698,8 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13716
13698
  RETURNING *`,
13717
13699
  streamParams(stream)
13718
13700
  );
13719
- if (rows[0]) {
13720
- return { stream: rowToStream(rows[0]), created: true };
13701
+ if (created) {
13702
+ return { stream: created, created: true };
13721
13703
  }
13722
13704
  const existing = await this.getStream(stream.id);
13723
13705
  if (!existing) {
@@ -13728,14 +13710,16 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13728
13710
  return { stream: existing, created: false };
13729
13711
  }
13730
13712
  async getStream(streamId) {
13731
- const rows = await this.#query(
13713
+ const [found] = await this.#rows(
13714
+ storedStream,
13732
13715
  `SELECT * FROM ${this.#t("streams")} WHERE id = $1`,
13733
13716
  [streamId]
13734
13717
  );
13735
- return rows[0] ? rowToStream(rows[0]) : void 0;
13718
+ return found;
13736
13719
  }
13737
13720
  async getStreamStatus(streamId) {
13738
- const rows = await this.#query(
13721
+ const rows = await this.#rows(
13722
+ statusRow,
13739
13723
  `SELECT status FROM ${this.#t("streams")} WHERE id = $1`,
13740
13724
  [streamId]
13741
13725
  );
@@ -13749,7 +13733,7 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13749
13733
  sql += ` WHERE status = $${params.length}`;
13750
13734
  }
13751
13735
  sql += " ORDER BY created_at ASC, id ASC";
13752
- const rows = await this.#query(sql, params);
13736
+ const rows = await this.#rows(idRow4, sql, params);
13753
13737
  return rows.map((row) => row.id);
13754
13738
  }
13755
13739
  async updateStream(streamId, update) {
@@ -13758,11 +13742,10 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13758
13742
  `SELECT * FROM ${this.#t("streams")} WHERE id = $1 FOR UPDATE`,
13759
13743
  [streamId]
13760
13744
  );
13761
- const row = selected.rows[0];
13762
- if (!row) {
13745
+ const stream = storedStream.optional().parse(selected.rows[0]);
13746
+ if (!stream) {
13763
13747
  throw new Error(`updateStream: stream "${streamId}" not found`);
13764
13748
  }
13765
- const stream = rowToStream(row);
13766
13749
  const updates = update(stream);
13767
13750
  if (updates === void 0) return { stream, updated: false };
13768
13751
  const setClauses = [];
@@ -13789,7 +13772,7 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13789
13772
  RETURNING *`,
13790
13773
  params
13791
13774
  );
13792
- return { stream: rowToStream(updated.rows[0]), updated: true };
13775
+ return { stream: storedStream.parse(updated.rows[0]), updated: true };
13793
13776
  });
13794
13777
  }
13795
13778
  async updateStreamStatus(streamId, status, options) {
@@ -13888,13 +13871,15 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13888
13871
  params.push(limit);
13889
13872
  sql += ` LIMIT $${params.length}`;
13890
13873
  }
13891
- const rows = await this.#query(sql, params);
13892
- return rows.map((row) => ({
13893
- streamId: row.stream_id,
13894
- seq: row.seq,
13895
- data: row.data,
13896
- createdAt: toNumber(row.created_at)
13897
- }));
13874
+ const rows = await this.#rows(chunkRow, sql, params);
13875
+ return Promise.all(
13876
+ rows.map(async (row) => ({
13877
+ streamId: row.stream_id,
13878
+ seq: row.seq,
13879
+ data: await toStreamPart(row.data),
13880
+ createdAt: row.created_at
13881
+ }))
13882
+ );
13898
13883
  }
13899
13884
  async deleteStream(streamId) {
13900
13885
  await this.#query(`DELETE FROM ${this.#t("streams")} WHERE id = $1`, [
@@ -13907,7 +13892,7 @@ var PostgresStreamStore = class _PostgresStreamStore extends StreamStore {
13907
13892
  `SELECT * FROM ${this.#t("streams")} WHERE id = $1 FOR UPDATE`,
13908
13893
  [streamId]
13909
13894
  );
13910
- const row = result.rows[0];
13895
+ const row = statusRow.optional().parse(result.rows[0]);
13911
13896
  if (!row) {
13912
13897
  throw new Error(`Stream "${streamId}" not found`);
13913
13898
  }
@@ -13950,23 +13935,6 @@ function streamParams(stream) {
13950
13935
  stream.error
13951
13936
  ];
13952
13937
  }
13953
- function rowToStream(row) {
13954
- return {
13955
- id: row.id,
13956
- status: row.status,
13957
- createdAt: toNumber(row.created_at),
13958
- startedAt: toNullableNumber(row.started_at),
13959
- finishedAt: toNullableNumber(row.finished_at),
13960
- cancelRequestedAt: toNullableNumber(row.cancel_requested_at),
13961
- error: row.error
13962
- };
13963
- }
13964
- function toNumber(value) {
13965
- return typeof value === "number" ? value : Number(value);
13966
- }
13967
- function toNullableNumber(value) {
13968
- return value == null ? null : toNumber(value);
13969
- }
13970
13938
  function isTerminal2(status) {
13971
13939
  return status !== "queued" && status !== "running";
13972
13940
  }
@@ -13978,11 +13946,29 @@ function assertIdentifier2(value, label) {
13978
13946
 
13979
13947
  // packages/context/src/lib/stream/sqlite.stream-store.ts
13980
13948
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13949
+ import { z as z19 } from "zod";
13981
13950
 
13982
13951
  // packages/context/src/lib/stream/ddl.stream.sqlite.sql
13983
13952
  var ddl_stream_sqlite_default = "PRAGMA 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";
13984
13953
 
13985
13954
  // packages/context/src/lib/stream/sqlite.stream-store.ts
13955
+ var streamRow = z19.object({
13956
+ id: z19.string(),
13957
+ status: streamStatus,
13958
+ createdAt: z19.number(),
13959
+ startedAt: z19.number().nullable(),
13960
+ finishedAt: z19.number().nullable(),
13961
+ cancelRequestedAt: z19.number().nullable(),
13962
+ error: z19.string().nullable()
13963
+ });
13964
+ var statusRow2 = z19.object({ status: streamStatus });
13965
+ var idRow5 = z19.object({ id: z19.string() });
13966
+ var chunkRow2 = z19.object({
13967
+ streamId: z19.string(),
13968
+ seq: z19.number(),
13969
+ data: z19.string(),
13970
+ createdAt: z19.number()
13971
+ });
13986
13972
  var SqliteStreamStore = class extends StreamStore {
13987
13973
  #db;
13988
13974
  #statements = /* @__PURE__ */ new Map();
@@ -14021,33 +14007,24 @@ var SqliteStreamStore = class extends StreamStore {
14021
14007
  );
14022
14008
  }
14023
14009
  async upsertStream(stream) {
14024
- const row = this.#stmt(
14025
- `INSERT INTO streams (id, status, createdAt, startedAt, finishedAt, cancelRequestedAt, error)
14010
+ const created = streamRow.optional().parse(
14011
+ this.#stmt(
14012
+ `INSERT INTO streams (id, status, createdAt, startedAt, finishedAt, cancelRequestedAt, error)
14026
14013
  VALUES (?, ?, ?, ?, ?, ?, ?)
14027
14014
  ON CONFLICT(id) DO NOTHING
14028
14015
  RETURNING *`
14029
- ).get(
14030
- stream.id,
14031
- stream.status,
14032
- stream.createdAt,
14033
- stream.startedAt,
14034
- stream.finishedAt,
14035
- stream.cancelRequestedAt,
14036
- stream.error
14016
+ ).get(
14017
+ stream.id,
14018
+ stream.status,
14019
+ stream.createdAt,
14020
+ stream.startedAt,
14021
+ stream.finishedAt,
14022
+ stream.cancelRequestedAt,
14023
+ stream.error
14024
+ )
14037
14025
  );
14038
- if (row) {
14039
- return {
14040
- stream: {
14041
- id: row.id,
14042
- status: row.status,
14043
- createdAt: row.createdAt,
14044
- startedAt: row.startedAt,
14045
- finishedAt: row.finishedAt,
14046
- cancelRequestedAt: row.cancelRequestedAt,
14047
- error: row.error
14048
- },
14049
- created: true
14050
- };
14026
+ if (created) {
14027
+ return { stream: created, created: true };
14051
14028
  }
14052
14029
  const existing = await this.getStream(stream.id);
14053
14030
  if (!existing) {
@@ -14058,23 +14035,11 @@ var SqliteStreamStore = class extends StreamStore {
14058
14035
  return { stream: existing, created: false };
14059
14036
  }
14060
14037
  async getStream(streamId) {
14061
- const row = this.#stmt("SELECT * FROM streams WHERE id = ?").get(
14062
- streamId
14063
- );
14064
- if (!row) return void 0;
14065
- return {
14066
- id: row.id,
14067
- status: row.status,
14068
- createdAt: row.createdAt,
14069
- startedAt: row.startedAt,
14070
- finishedAt: row.finishedAt,
14071
- cancelRequestedAt: row.cancelRequestedAt,
14072
- error: row.error
14073
- };
14038
+ return streamRow.optional().parse(this.#stmt("SELECT * FROM streams WHERE id = ?").get(streamId));
14074
14039
  }
14075
14040
  async getStreamStatus(streamId) {
14076
- const row = this.#stmt("SELECT status FROM streams WHERE id = ?").get(
14077
- streamId
14041
+ const row = statusRow2.optional().parse(
14042
+ this.#stmt("SELECT status FROM streams WHERE id = ?").get(streamId)
14078
14043
  );
14079
14044
  return row?.status;
14080
14045
  }
@@ -14086,18 +14051,15 @@ var SqliteStreamStore = class extends StreamStore {
14086
14051
  params.push(options.status);
14087
14052
  }
14088
14053
  sql += " ORDER BY createdAt ASC, id ASC";
14089
- const rows = this.#stmt(sql).all(...params);
14054
+ const rows = z19.array(idRow5).parse(this.#stmt(sql).all(...params));
14090
14055
  return rows.map((row) => row.id);
14091
14056
  }
14092
14057
  async updateStream(streamId, update) {
14093
14058
  return this.#transaction(() => {
14094
- const current = this.#stmt("SELECT * FROM streams WHERE id = ?").get(
14095
- streamId
14096
- );
14097
- if (!current) {
14059
+ const stream = streamRow.optional().parse(this.#stmt("SELECT * FROM streams WHERE id = ?").get(streamId));
14060
+ if (!stream) {
14098
14061
  throw new Error(`updateStream: stream "${streamId}" not found`);
14099
14062
  }
14100
- const stream = { ...current };
14101
14063
  const updates = update(stream);
14102
14064
  if (updates === void 0) return { stream, updated: false };
14103
14065
  const setClauses = [];
@@ -14117,10 +14079,12 @@ var SqliteStreamStore = class extends StreamStore {
14117
14079
  if (updates.error !== void 0) set("error", updates.error);
14118
14080
  if (setClauses.length === 0) return { stream, updated: false };
14119
14081
  params.push(streamId);
14120
- const next = this.#stmt(
14121
- `UPDATE streams SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
14122
- ).get(...params);
14123
- return { stream: { ...next }, updated: true };
14082
+ const next = streamRow.parse(
14083
+ this.#stmt(
14084
+ `UPDATE streams SET ${setClauses.join(", ")} WHERE id = ? RETURNING *`
14085
+ ).get(...params)
14086
+ );
14087
+ return { stream: next, updated: true };
14124
14088
  });
14125
14089
  }
14126
14090
  async updateStreamStatus(streamId, status, options) {
@@ -14206,22 +14170,22 @@ var SqliteStreamStore = class extends StreamStore {
14206
14170
  sql += " LIMIT ?";
14207
14171
  params.push(limit);
14208
14172
  }
14209
- const rows = this.#stmt(sql).all(...params);
14210
- return rows.map((row) => ({
14211
- streamId: row.streamId,
14212
- seq: row.seq,
14213
- data: JSON.parse(row.data),
14214
- createdAt: row.createdAt
14215
- }));
14173
+ const rows = z19.array(chunkRow2).parse(this.#stmt(sql).all(...params));
14174
+ return Promise.all(
14175
+ rows.map(async (row) => ({
14176
+ streamId: row.streamId,
14177
+ seq: row.seq,
14178
+ data: await toStreamPart(parseJson(row.data)),
14179
+ createdAt: row.createdAt
14180
+ }))
14181
+ );
14216
14182
  }
14217
14183
  async deleteStream(streamId) {
14218
14184
  this.#stmt("DELETE FROM streams WHERE id = ?").run(streamId);
14219
14185
  }
14220
14186
  async reopenStream(streamId) {
14221
14187
  return this.#transaction(() => {
14222
- const row = this.#stmt("SELECT * FROM streams WHERE id = ?").get(
14223
- streamId
14224
- );
14188
+ const row = statusRow2.optional().parse(this.#stmt("SELECT * FROM streams WHERE id = ?").get(streamId));
14225
14189
  if (!row) {
14226
14190
  throw new Error(`Stream "${streamId}" not found`);
14227
14191
  }
@@ -14605,20 +14569,7 @@ function isAbortError(error) {
14605
14569
  return error instanceof Error && (error.name === "AbortError" || /aborted/i.test(error.message));
14606
14570
  }
14607
14571
  async function drain(stream, signal) {
14608
- const reader = stream.getReader();
14609
- const onAbort = () => reader.cancel();
14610
- if (signal) {
14611
- signal.addEventListener("abort", onAbort, { once: true });
14612
- }
14613
- try {
14614
- while (true) {
14615
- const { done } = await reader.read();
14616
- if (done) break;
14617
- }
14618
- } finally {
14619
- signal?.removeEventListener("abort", onAbort);
14620
- reader.releaseLock();
14621
- }
14572
+ await stream.pipeTo(new WritableStream(), { signal });
14622
14573
  }
14623
14574
 
14624
14575
  // packages/context/src/lib/visualize.ts
@@ -14677,9 +14628,6 @@ function visualizeGraph(data) {
14677
14628
  return lines.join("\n");
14678
14629
  }
14679
14630
  export {
14680
- AgentOsCreationError,
14681
- AgentOsNotAvailableError,
14682
- AgentOsSandboxError,
14683
14631
  AppleContainerCreationError,
14684
14632
  AppleContainerImageBuildError,
14685
14633
  AppleContainerSandboxError,
@@ -14786,7 +14734,6 @@ export {
14786
14734
  contentPattern,
14787
14735
  correction,
14788
14736
  createAdaptivePollingState,
14789
- createAgentOsSandbox,
14790
14737
  createAppleContainerSandbox,
14791
14738
  createBashTool,
14792
14739
  createBinaryBridges,
@@ -14833,12 +14780,14 @@ export {
14833
14780
  hint,
14834
14781
  hourChanged,
14835
14782
  identity,
14783
+ inputPricePerMillion,
14836
14784
  isAppleContainerfileOptions,
14837
14785
  isComposeOptions,
14838
14786
  isConditionalReminder,
14839
14787
  isDebianBased,
14840
14788
  isDockerfileOptions,
14841
14789
  isFragment,
14790
+ isFragmentData,
14842
14791
  isFragmentObject,
14843
14792
  isMessageFragment,
14844
14793
  isRecord,
@@ -14911,7 +14860,6 @@ export {
14911
14860
  toolOutput,
14912
14861
  urlBinary,
14913
14862
  usageExceeds,
14914
- useAgentOsSandbox,
14915
14863
  useAppleContainerSandbox,
14916
14864
  useSandbox,
14917
14865
  user,