@cloudbase/agent-adapter-langgraph 1.0.1-alpha.21 → 1.0.1-alpha.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1360,7 +1360,7 @@ var init_esm2 = __esm({
1360
1360
  }
1361
1361
  });
1362
1362
 
1363
- // ../../observability/dist/chunk-3MVJN6UI.mjs
1363
+ // ../../observability/dist/chunk-DUKIGNZF.mjs
1364
1364
  function createTraceAttributes({
1365
1365
  name,
1366
1366
  userId,
@@ -1405,19 +1405,20 @@ function createObservationAttributes(type, attributes) {
1405
1405
  modelParameters,
1406
1406
  usageDetails
1407
1407
  } = attributes;
1408
+ const spanKind = OpenInferenceSpanKind[type.toUpperCase()] || "UNKNOWN";
1408
1409
  const otelAttributes = {
1409
- [SemanticConventions.OPENINFERENCE_SPAN_KIND]: type.toUpperCase(),
1410
+ [SemanticConventions.OPENINFERENCE_SPAN_KIND]: spanKind,
1410
1411
  [OtelSpanAttributes.OBSERVATION_TYPE]: type,
1411
1412
  [OtelSpanAttributes.OBSERVATION_LEVEL]: level,
1412
1413
  [OtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
1413
1414
  [OtelSpanAttributes.VERSION]: version,
1414
1415
  // Use OpenInference input.value convention
1415
1416
  [SemanticConventions.INPUT_VALUE]: _serialize(input),
1416
- // Also set legacy agkit.observation.input for compatibility
1417
+ // Also set observation.input for compatibility
1417
1418
  [OtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
1418
1419
  // Use OpenInference output.value convention
1419
1420
  [SemanticConventions.OUTPUT_VALUE]: _serialize(output),
1420
- // Also set legacy agkit.observation.output for compatibility
1421
+ // Also set observation.output for compatibility
1421
1422
  [OtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output)
1422
1423
  };
1423
1424
  if (type === "llm") {
@@ -1938,9 +1939,9 @@ function observe(fn, options = {}) {
1938
1939
  Object.defineProperty(wrappedFunction, "length", { value: fn.length });
1939
1940
  return wrappedFunction;
1940
1941
  }
1941
- var OtelSpanAttributes, init_constants, init_attributes, OBSERVABILITY_GLOBAL_SYMBOL, OBSERVABILITY_SDK_NAME, OBSERVABILITY_SDK_VERSION, init_tracerProvider, BaseObservation, ObservationSpan, ObservationLLM, ObservationEmbedding, ObservationAgent, ObservationTool, ObservationChain, ObservationRetriever, ObservationReranker, ObservationEvaluator, ObservationGuardrail, init_spanWrapper, src_exports, init_src;
1942
- var init_chunk_3MVJN6UI = __esm({
1943
- "../../observability/dist/chunk-3MVJN6UI.mjs"() {
1942
+ var OBSERVABILITY_TRACER_NAME, OBSERVABILITY_SDK_NAME, OBSERVABILITY_SDK_VERSION, OtelSpanAttributes, init_constants, init_attributes, OBSERVABILITY_GLOBAL_SYMBOL, init_tracerProvider, BaseObservation, ObservationSpan, ObservationLLM, ObservationEmbedding, ObservationAgent, ObservationTool, ObservationChain, ObservationRetriever, ObservationReranker, ObservationEvaluator, ObservationGuardrail, init_spanWrapper, src_exports, init_src;
1943
+ var init_chunk_DUKIGNZF = __esm({
1944
+ "../../observability/dist/chunk-DUKIGNZF.mjs"() {
1944
1945
  "use strict";
1945
1946
  init_chunk_NFEGQTCC();
1946
1947
  init_esm();
@@ -1951,34 +1952,37 @@ var init_chunk_3MVJN6UI = __esm({
1951
1952
  init_constants = __esm2({
1952
1953
  "src/core/constants.ts"() {
1953
1954
  "use strict";
1955
+ OBSERVABILITY_TRACER_NAME = "agui-tracer";
1956
+ OBSERVABILITY_SDK_NAME = "observability";
1957
+ OBSERVABILITY_SDK_VERSION = "0.1.0";
1954
1958
  OtelSpanAttributes = {
1955
1959
  // OpenInference - re-export all standard conventions
1956
1960
  ...SemanticConventions,
1957
- // AG-Kit Trace attributes (non-standard)
1961
+ // Trace attributes (non-standard)
1958
1962
  TRACE_NAME: "trace.name",
1959
1963
  TRACE_TAGS: "trace.tags",
1960
1964
  TRACE_PUBLIC: "trace.public",
1961
1965
  TRACE_METADATA: "trace.metadata",
1962
1966
  TRACE_INPUT: "trace.input",
1963
1967
  TRACE_OUTPUT: "trace.output",
1964
- // AG-Kit Observation attributes (non-standard)
1968
+ // Observation attributes (non-standard)
1965
1969
  OBSERVATION_TYPE: "observation.type",
1966
1970
  OBSERVATION_LEVEL: "observation.level",
1967
1971
  OBSERVATION_STATUS_MESSAGE: "observation.status_message",
1968
1972
  OBSERVATION_INPUT: "observation.input",
1969
1973
  OBSERVATION_OUTPUT: "observation.output",
1970
1974
  OBSERVATION_METADATA: "observation.metadata",
1971
- // AG-Kit LLM-specific (non-standard)
1975
+ // LLM-specific (non-standard)
1972
1976
  LLM_COMPLETION_START_TIME: "llm.completion_start_time",
1973
1977
  LLM_MODEL_PARAMETERS: "llm.model_parameters",
1974
1978
  LLM_USAGE_DETAILS: "llm.usage_details",
1975
1979
  LLM_COST_DETAILS: "llm.cost_details",
1976
- // AG-Kit Retriever-specific (non-standard)
1980
+ // Retriever-specific (non-standard)
1977
1981
  RETRIEVER_NAME: "retriever.name",
1978
1982
  RETRIEVER_QUERY: "retriever.query",
1979
1983
  RETRIEVER_INDEX_ID: "retriever.index_id",
1980
1984
  RETRIEVER_TOP_K: "retriever.top_k",
1981
- // AG-Kit General (non-standard)
1985
+ // General (non-standard)
1982
1986
  ENVIRONMENT: "environment",
1983
1987
  RELEASE: "release",
1984
1988
  VERSION: "version"
@@ -1994,9 +1998,8 @@ var init_chunk_3MVJN6UI = __esm({
1994
1998
  init_tracerProvider = __esm2({
1995
1999
  "src/core/tracerProvider.ts"() {
1996
2000
  "use strict";
2001
+ init_constants();
1997
2002
  OBSERVABILITY_GLOBAL_SYMBOL = /* @__PURE__ */ Symbol.for("observability");
1998
- OBSERVABILITY_SDK_NAME = "ag-kit-observability";
1999
- OBSERVABILITY_SDK_VERSION = "0.1.0";
2000
2003
  }
2001
2004
  });
2002
2005
  init_spanWrapper = __esm2({
@@ -2024,7 +2027,7 @@ var init_chunk_3MVJN6UI = __esm({
2024
2027
  );
2025
2028
  }
2026
2029
  }
2027
- /** Gets the AG-Kit OpenTelemetry tracer instance */
2030
+ /** Gets the OpenTelemetry tracer instance */
2028
2031
  get tracer() {
2029
2032
  return getTracer();
2030
2033
  }
@@ -2181,6 +2184,9 @@ var init_chunk_3MVJN6UI = __esm({
2181
2184
  });
2182
2185
  src_exports = {};
2183
2186
  __export2(src_exports, {
2187
+ OBSERVABILITY_SDK_NAME: () => OBSERVABILITY_SDK_NAME,
2188
+ OBSERVABILITY_SDK_VERSION: () => OBSERVABILITY_SDK_VERSION,
2189
+ OBSERVABILITY_TRACER_NAME: () => OBSERVABILITY_TRACER_NAME,
2184
2190
  ObservationAgent: () => ObservationAgent,
2185
2191
  ObservationChain: () => ObservationChain,
2186
2192
  ObservationEmbedding: () => ObservationEmbedding,
@@ -2211,6 +2217,7 @@ var init_chunk_3MVJN6UI = __esm({
2211
2217
  init_tracerProvider();
2212
2218
  init_attributes();
2213
2219
  init_tracerProvider();
2220
+ init_constants();
2214
2221
  }
2215
2222
  });
2216
2223
  }
@@ -2225,7 +2232,7 @@ var import_base, import_messages, import_agent_shared, CallbackHandler;
2225
2232
  var init_langchain = __esm({
2226
2233
  "../../observability/dist/langchain.mjs"() {
2227
2234
  "use strict";
2228
- init_chunk_3MVJN6UI();
2235
+ init_chunk_DUKIGNZF();
2229
2236
  init_chunk_NFEGQTCC();
2230
2237
  import_base = require("@langchain/core/callbacks/base");
2231
2238
  import_messages = require("@langchain/core/messages");
@@ -2776,6 +2783,7 @@ var index_exports = {};
2776
2783
  __export(index_exports, {
2777
2784
  ClientPropertiesAnnotation: () => ClientPropertiesAnnotation,
2778
2785
  ClientStateAnnotation: () => ClientStateAnnotation,
2786
+ CloudBaseSaver: () => CloudBaseSaver,
2779
2787
  LanggraphAgent: () => LanggraphAgent,
2780
2788
  TDAISaver: () => TDAISaver,
2781
2789
  TDAIStore: () => TDAIStore,
@@ -2910,11 +2918,9 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2910
2918
  };
2911
2919
  logger.trace?.({ aguiEvent: runStartedEvent }, "Emitting AGUI event");
2912
2920
  subscriber.next(runStartedEvent);
2913
- const isResume = !!input.forwardedProps?.resume;
2914
2921
  const lastUserMessage = messages.filter((m) => m.role === "user").pop();
2915
2922
  logger.debug?.(
2916
2923
  {
2917
- isResume,
2918
2924
  messageCount: messages.length,
2919
2925
  toolCount: input.tools?.length ?? 0,
2920
2926
  tools: input.tools?.map((t) => t.name),
@@ -2923,25 +2929,21 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2923
2929
  "Preparing stream input"
2924
2930
  );
2925
2931
  logger.trace?.({ messages, tools: input.tools }, "Full input messages");
2926
- const langChainMessages = isResume ? void 0 : aguiMessagesToLangChain(messages);
2927
- if (langChainMessages) {
2928
- logger.trace?.(
2929
- {
2930
- langChainMessages,
2931
- messageCount: langChainMessages.length,
2932
- messageTypes: langChainMessages.map((m) => ({
2933
- type: m.type,
2934
- id: m.id,
2935
- hasToolCalls: "tool_calls" in m && Array.isArray(m.tool_calls) && m.tool_calls.length > 0,
2936
- toolCallId: "tool_call_id" in m ? m.tool_call_id : void 0
2937
- }))
2938
- },
2939
- "Converted LangGraph messages"
2940
- );
2941
- }
2942
- const streamEventInput = isResume ? new import_langgraph.Command({
2943
- resume: JSON.stringify(input.forwardedProps?.resume?.payload)
2944
- }) : {
2932
+ const langChainMessages = aguiMessagesToLangChain(messages);
2933
+ logger.trace?.(
2934
+ {
2935
+ langChainMessages,
2936
+ messageCount: langChainMessages.length,
2937
+ messageTypes: langChainMessages.map((m) => ({
2938
+ type: m.type,
2939
+ id: m.id,
2940
+ hasToolCalls: "tool_calls" in m && Array.isArray(m.tool_calls) && m.tool_calls.length > 0,
2941
+ toolCallId: "tool_call_id" in m ? m.tool_call_id : void 0
2942
+ }))
2943
+ },
2944
+ "Converted LangGraph messages"
2945
+ );
2946
+ const streamEventInput = {
2945
2947
  messages: langChainMessages,
2946
2948
  client: {
2947
2949
  tools: convertActionsToDynamicStructuredTools(
@@ -2974,7 +2976,6 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2974
2976
  "Pre-populated handled tool call IDs from input messages"
2975
2977
  );
2976
2978
  }
2977
- let interrupt;
2978
2979
  let currentToolCall = null;
2979
2980
  let eventCount = 0;
2980
2981
  let toolCallCount = 0;
@@ -3299,46 +3300,17 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
3299
3300
  "State update with messages"
3300
3301
  );
3301
3302
  }
3302
- if (chunk?.__interrupt__ && Array.isArray(chunk.__interrupt__) && chunk.__interrupt__.length > 0) {
3303
- const rawInterrupt = chunk.__interrupt__[0];
3304
- logger.debug?.(
3305
- { interruptId: rawInterrupt.id },
3306
- "Interrupt received"
3307
- );
3308
- interrupt = {
3309
- id: rawInterrupt.id,
3310
- // TODO: replace with actual reason
3311
- reason: "agent requested interrupt",
3312
- payload: rawInterrupt.value
3313
- };
3314
- }
3315
3303
  }
3316
3304
  }
3317
3305
  const stats = { eventCount, toolCallCount, textChunkCount };
3318
- if (interrupt) {
3319
- const runFinishedEvent = {
3320
- type: import_client.EventType.RUN_FINISHED,
3321
- threadId,
3322
- runId,
3323
- outcome: "interrupt",
3324
- interrupt
3325
- };
3326
- logger.info?.(
3327
- { outcome: "interrupt", interruptId: interrupt.id, ...stats },
3328
- "Run finished with interrupt"
3329
- );
3330
- logger.trace?.({ aguiEvent: runFinishedEvent }, "Emitting AGUI event");
3331
- subscriber.next(runFinishedEvent);
3332
- } else {
3333
- const runFinishedEvent = {
3334
- type: import_client.EventType.RUN_FINISHED,
3335
- threadId,
3336
- runId
3337
- };
3338
- logger.info?.({ outcome: "complete", ...stats }, "Run finished");
3339
- logger.trace?.({ aguiEvent: runFinishedEvent }, "Emitting AGUI event");
3340
- subscriber.next(runFinishedEvent);
3341
- }
3306
+ const runFinishedEvent = {
3307
+ type: import_client.EventType.RUN_FINISHED,
3308
+ threadId,
3309
+ runId
3310
+ };
3311
+ logger.info?.({ outcome: "complete", ...stats }, "Run finished");
3312
+ logger.trace?.({ aguiEvent: runFinishedEvent }, "Emitting AGUI event");
3313
+ subscriber.next(runFinishedEvent);
3342
3314
  } catch (error) {
3343
3315
  logger.error?.(
3344
3316
  { err: error, eventCount, toolCallCount, textChunkCount },
@@ -3366,7 +3338,7 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
3366
3338
  }
3367
3339
  };
3368
3340
  function aguiMessagesToLangChain(messages) {
3369
- return messages.map((message, index) => {
3341
+ return messages.map((message) => {
3370
3342
  switch (message.role) {
3371
3343
  case "user":
3372
3344
  if (typeof message.content === "string") {
@@ -3676,9 +3648,364 @@ var TDAISaver = class extends import_langgraph2.BaseCheckpointSaver {
3676
3648
  }
3677
3649
  };
3678
3650
 
3679
- // src/store/tdai-store.ts
3651
+ // src/cloudbase-saver.ts
3680
3652
  var import_langgraph3 = require("@langchain/langgraph");
3681
- var TDAIStore = class extends import_langgraph3.BaseStore {
3653
+
3654
+ // ../../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.0_@langchain+core@1.1.16_@opentelemetry+api@1.9.0_@_6d00458ac2f8320fcf28949c4b5d31a3/node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js
3655
+ var ERROR = "__error__";
3656
+ var SCHEDULED = "__scheduled__";
3657
+ var INTERRUPT = "__interrupt__";
3658
+ var RESUME = "__resume__";
3659
+
3660
+ // ../../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.0_@langchain+core@1.1.16_@opentelemetry+api@1.9.0_@_6d00458ac2f8320fcf28949c4b5d31a3/node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js
3661
+ var import_load = require("@langchain/core/load");
3662
+
3663
+ // ../../../node_modules/.pnpm/@langchain+langgraph-checkpoint@1.0.0_@langchain+core@1.1.16_@opentelemetry+api@1.9.0_@_6d00458ac2f8320fcf28949c4b5d31a3/node_modules/@langchain/langgraph-checkpoint/dist/base.js
3664
+ function deepCopy(obj) {
3665
+ if (typeof obj !== "object" || obj === null) return obj;
3666
+ const newObj = Array.isArray(obj) ? [] : {};
3667
+ for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]);
3668
+ return newObj;
3669
+ }
3670
+ function copyCheckpoint(checkpoint) {
3671
+ return {
3672
+ v: checkpoint.v,
3673
+ id: checkpoint.id,
3674
+ ts: checkpoint.ts,
3675
+ channel_values: { ...checkpoint.channel_values },
3676
+ channel_versions: { ...checkpoint.channel_versions },
3677
+ versions_seen: deepCopy(checkpoint.versions_seen)
3678
+ };
3679
+ }
3680
+ var WRITES_IDX_MAP = {
3681
+ [ERROR]: -1,
3682
+ [SCHEDULED]: -2,
3683
+ [INTERRUPT]: -3,
3684
+ [RESUME]: -4
3685
+ };
3686
+
3687
+ // src/cloudbase-saver.ts
3688
+ var CloudBaseSaver = class extends import_langgraph3.BaseCheckpointSaver {
3689
+ constructor(config) {
3690
+ super();
3691
+ this.db = config.db;
3692
+ this.userId = config.userId;
3693
+ this.agentId = config.agentId ?? "default";
3694
+ this.checkpointsCollection = config.checkpointsCollection ?? "checkpoints";
3695
+ this.writesCollection = config.writesCollection ?? "checkpoint_writes";
3696
+ }
3697
+ /**
3698
+ * Setup the required collections in CloudBase.
3699
+ * Call this once before using the saver. Safe to call multiple times.
3700
+ */
3701
+ async setup() {
3702
+ const createIfNotExists = async (name) => {
3703
+ try {
3704
+ await this.db.createCollection(name);
3705
+ } catch (e) {
3706
+ const error = e;
3707
+ if (error.code !== "DATABASE_COLLECTION_ALREADY_EXIST") {
3708
+ throw e;
3709
+ }
3710
+ }
3711
+ };
3712
+ await Promise.all([
3713
+ createIfNotExists(this.checkpointsCollection),
3714
+ createIfNotExists(this.writesCollection)
3715
+ ]);
3716
+ }
3717
+ /**
3718
+ * Serialize data to JSON object using serde.
3719
+ * CloudBase is a document database, so we store JSON directly instead of Base64.
3720
+ * Binary data (Uint8Array) is not supported - fail early if encountered.
3721
+ */
3722
+ async serialize(data) {
3723
+ const [type, bytes] = await this.serde.dumpsTyped(data);
3724
+ if (type === "bytes") {
3725
+ throw new Error(
3726
+ "Binary data (Uint8Array) is not supported in CloudBaseSaver. CloudBase is a document database that only supports JSON-serializable data."
3727
+ );
3728
+ }
3729
+ const jsonString = new TextDecoder().decode(bytes);
3730
+ return JSON.parse(jsonString);
3731
+ }
3732
+ /**
3733
+ * Deserialize JSON object back to data using serde.
3734
+ */
3735
+ async deserialize(data) {
3736
+ const jsonString = JSON.stringify(data);
3737
+ const bytes = new TextEncoder().encode(jsonString);
3738
+ return this.serde.loadsTyped("json", bytes);
3739
+ }
3740
+ /**
3741
+ * Retrieves a checkpoint from CloudBase based on the provided config.
3742
+ */
3743
+ async getTuple(config) {
3744
+ const {
3745
+ thread_id,
3746
+ checkpoint_ns = "",
3747
+ checkpoint_id
3748
+ } = config.configurable ?? {};
3749
+ if (!thread_id) {
3750
+ return void 0;
3751
+ }
3752
+ const query = {
3753
+ _openid: this.userId,
3754
+ agent_id: this.agentId,
3755
+ thread_id,
3756
+ checkpoint_ns
3757
+ };
3758
+ if (checkpoint_id) {
3759
+ query.checkpoint_id = checkpoint_id;
3760
+ }
3761
+ const { data: docs } = await this.db.collection(this.checkpointsCollection).where(query).orderBy("checkpoint_id", "desc").limit(1).get();
3762
+ if (docs.length === 0) {
3763
+ return void 0;
3764
+ }
3765
+ const doc = docs[0];
3766
+ const checkpointId = doc.checkpoint_id;
3767
+ const checkpoint = await this.deserialize(doc.checkpoint);
3768
+ const metadata = await this.deserialize(
3769
+ doc.metadata
3770
+ );
3771
+ const writeDocs = [];
3772
+ let writeSkip = 0;
3773
+ const writePageSize = 100;
3774
+ while (true) {
3775
+ const { data: docs2 } = await this.db.collection(this.writesCollection).where({
3776
+ _openid: this.userId,
3777
+ agent_id: this.agentId,
3778
+ thread_id,
3779
+ checkpoint_ns,
3780
+ checkpoint_id: checkpointId
3781
+ }).orderBy("idx", "asc").skip(writeSkip).limit(writePageSize).get();
3782
+ writeDocs.push(...docs2);
3783
+ if (docs2.length < writePageSize) break;
3784
+ writeSkip += docs2.length;
3785
+ }
3786
+ const pendingWrites = await Promise.all(
3787
+ writeDocs.map(async (writeDoc) => {
3788
+ const value = await this.deserialize(writeDoc.value);
3789
+ return [
3790
+ writeDoc.task_id,
3791
+ writeDoc.channel,
3792
+ value
3793
+ ];
3794
+ })
3795
+ );
3796
+ return {
3797
+ config: {
3798
+ configurable: {
3799
+ thread_id,
3800
+ checkpoint_ns,
3801
+ checkpoint_id: checkpointId
3802
+ }
3803
+ },
3804
+ checkpoint,
3805
+ metadata,
3806
+ pendingWrites,
3807
+ parentConfig: doc.parent_checkpoint_id ? {
3808
+ configurable: {
3809
+ thread_id,
3810
+ checkpoint_ns,
3811
+ checkpoint_id: doc.parent_checkpoint_id
3812
+ }
3813
+ } : void 0
3814
+ };
3815
+ }
3816
+ /**
3817
+ * List checkpoints from CloudBase, ordered by checkpoint_id descending.
3818
+ */
3819
+ async *list(config, options) {
3820
+ const { limit, before, filter } = options ?? {};
3821
+ const thread_id = config.configurable?.thread_id;
3822
+ const checkpoint_ns = config.configurable?.checkpoint_ns;
3823
+ if (!thread_id) {
3824
+ throw new Error("Thread ID is required");
3825
+ }
3826
+ const _ = this.db.command;
3827
+ const query = {
3828
+ _openid: this.userId,
3829
+ agent_id: this.agentId,
3830
+ thread_id
3831
+ };
3832
+ if (checkpoint_ns !== void 0 && checkpoint_ns !== null) {
3833
+ query.checkpoint_ns = checkpoint_ns;
3834
+ }
3835
+ if (before?.configurable?.checkpoint_id) {
3836
+ query.checkpoint_id = _.lt(before.configurable.checkpoint_id);
3837
+ }
3838
+ const validCheckpointMetadataKeys = ["source", "step", "writes", "parents"];
3839
+ if (filter) {
3840
+ for (const [key, value] of Object.entries(filter)) {
3841
+ if (value !== void 0 && validCheckpointMetadataKeys.includes(key)) {
3842
+ query[`metadata.${key}`] = value;
3843
+ }
3844
+ }
3845
+ }
3846
+ let skip = 0;
3847
+ const pageSize = Math.min(limit ?? 100, 100);
3848
+ let yielded = 0;
3849
+ while (true) {
3850
+ const { data: docs } = await this.db.collection(this.checkpointsCollection).where(query).orderBy("checkpoint_id", "desc").skip(skip).limit(pageSize).get();
3851
+ if (docs.length === 0) break;
3852
+ for (const doc of docs) {
3853
+ const checkpoint = await this.deserialize(
3854
+ doc.checkpoint
3855
+ );
3856
+ const metadata = await this.deserialize(
3857
+ doc.metadata
3858
+ );
3859
+ const writeDocs = [];
3860
+ let writeSkip = 0;
3861
+ const writePageSize = 100;
3862
+ while (true) {
3863
+ const { data: pageWriteDocs } = await this.db.collection(this.writesCollection).where({
3864
+ _openid: this.userId,
3865
+ agent_id: this.agentId,
3866
+ thread_id: doc.thread_id,
3867
+ checkpoint_ns: doc.checkpoint_ns,
3868
+ checkpoint_id: doc.checkpoint_id
3869
+ }).orderBy("idx", "asc").skip(writeSkip).limit(writePageSize).get();
3870
+ writeDocs.push(...pageWriteDocs);
3871
+ if (pageWriteDocs.length < writePageSize) break;
3872
+ writeSkip += pageWriteDocs.length;
3873
+ }
3874
+ const pendingWrites = await Promise.all(
3875
+ writeDocs.map(async (writeDoc) => {
3876
+ const value = await this.deserialize(writeDoc.value);
3877
+ return [
3878
+ writeDoc.task_id,
3879
+ writeDoc.channel,
3880
+ value
3881
+ ];
3882
+ })
3883
+ );
3884
+ yield {
3885
+ config: {
3886
+ configurable: {
3887
+ thread_id: doc.thread_id,
3888
+ checkpoint_ns: doc.checkpoint_ns,
3889
+ checkpoint_id: doc.checkpoint_id
3890
+ }
3891
+ },
3892
+ checkpoint,
3893
+ metadata,
3894
+ pendingWrites,
3895
+ parentConfig: doc.parent_checkpoint_id ? {
3896
+ configurable: {
3897
+ thread_id: doc.thread_id,
3898
+ checkpoint_ns: doc.checkpoint_ns,
3899
+ checkpoint_id: doc.parent_checkpoint_id
3900
+ }
3901
+ } : void 0
3902
+ };
3903
+ yielded++;
3904
+ if (limit && yielded >= limit) return;
3905
+ }
3906
+ skip += docs.length;
3907
+ if (docs.length < pageSize) break;
3908
+ }
3909
+ }
3910
+ /**
3911
+ * Save a checkpoint to CloudBase.
3912
+ */
3913
+ async put(config, checkpoint, metadata) {
3914
+ if (!config.configurable) {
3915
+ throw new Error("Empty configuration supplied.");
3916
+ }
3917
+ const thread_id = config.configurable.thread_id;
3918
+ const checkpoint_ns = config.configurable.checkpoint_ns ?? "";
3919
+ const checkpoint_id = checkpoint.id;
3920
+ if (!thread_id) {
3921
+ throw new Error(
3922
+ 'Missing "thread_id" field in passed "config.configurable".'
3923
+ );
3924
+ }
3925
+ const preparedCheckpoint = copyCheckpoint(checkpoint);
3926
+ const serializedCheckpoint = await this.serialize(preparedCheckpoint);
3927
+ const serializedMetadata = await this.serialize(metadata);
3928
+ const doc = {
3929
+ _openid: this.userId,
3930
+ agent_id: this.agentId,
3931
+ thread_id,
3932
+ checkpoint_ns,
3933
+ checkpoint_id,
3934
+ parent_checkpoint_id: config.configurable.checkpoint_id ?? null,
3935
+ checkpoint: serializedCheckpoint,
3936
+ metadata: serializedMetadata,
3937
+ created_at: /* @__PURE__ */ new Date()
3938
+ };
3939
+ const docId = `${this.agentId}:${thread_id}:${checkpoint_ns}:${checkpoint_id}`;
3940
+ await this.db.collection(this.checkpointsCollection).doc(docId).set(doc);
3941
+ return {
3942
+ configurable: {
3943
+ thread_id,
3944
+ checkpoint_ns,
3945
+ checkpoint_id
3946
+ }
3947
+ };
3948
+ }
3949
+ /**
3950
+ * Save intermediate writes to CloudBase.
3951
+ */
3952
+ async putWrites(config, writes, taskId) {
3953
+ if (!config.configurable) {
3954
+ throw new Error("Empty configuration supplied.");
3955
+ }
3956
+ if (!config.configurable.thread_id) {
3957
+ throw new Error("Missing thread_id field in config.configurable.");
3958
+ }
3959
+ if (!config.configurable.checkpoint_id) {
3960
+ throw new Error("Missing checkpoint_id field in config.configurable.");
3961
+ }
3962
+ const thread_id = config.configurable.thread_id;
3963
+ const checkpoint_ns = config.configurable.checkpoint_ns ?? "";
3964
+ const checkpoint_id = config.configurable.checkpoint_id;
3965
+ const serializedWrites = await Promise.all(
3966
+ writes.map(async ([channel, value], idx) => ({
3967
+ channel,
3968
+ value: await this.serialize(value),
3969
+ idx,
3970
+ docId: `${this.agentId}:${thread_id}:${checkpoint_ns}:${checkpoint_id}:${taskId}:${idx}`
3971
+ }))
3972
+ );
3973
+ await this.db.runTransaction(async (transaction) => {
3974
+ for (const { channel, value, idx, docId } of serializedWrites) {
3975
+ await transaction.collection(this.writesCollection).doc(docId).set({
3976
+ _openid: this.userId,
3977
+ agent_id: this.agentId,
3978
+ thread_id,
3979
+ checkpoint_ns,
3980
+ checkpoint_id,
3981
+ task_id: taskId,
3982
+ idx,
3983
+ channel,
3984
+ value
3985
+ });
3986
+ }
3987
+ });
3988
+ }
3989
+ /**
3990
+ * Delete all checkpoints and writes for a thread.
3991
+ */
3992
+ async deleteThread(threadId) {
3993
+ await this.db.collection(this.checkpointsCollection).where({
3994
+ _openid: this.userId,
3995
+ agent_id: this.agentId,
3996
+ thread_id: threadId
3997
+ }).remove();
3998
+ await this.db.collection(this.writesCollection).where({
3999
+ _openid: this.userId,
4000
+ agent_id: this.agentId,
4001
+ thread_id: threadId
4002
+ }).remove();
4003
+ }
4004
+ };
4005
+
4006
+ // src/store/tdai-store.ts
4007
+ var import_langgraph4 = require("@langchain/langgraph");
4008
+ var TDAIStore = class extends import_langgraph4.BaseStore {
3682
4009
  constructor(config) {
3683
4010
  super();
3684
4011
  this.isSetup = false;
@@ -4108,6 +4435,7 @@ var import_agent_shared3 = require("@cloudbase/agent-shared");
4108
4435
  0 && (module.exports = {
4109
4436
  ClientPropertiesAnnotation,
4110
4437
  ClientStateAnnotation,
4438
+ CloudBaseSaver,
4111
4439
  LanggraphAgent,
4112
4440
  TDAISaver,
4113
4441
  TDAIStore,