@cloudbase/agent-adapter-langgraph 0.0.16 → 0.0.18

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
@@ -5,2583 +5,39 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
34
-
35
- // ../../observability/dist/chunk-NFEGQTCC.mjs
36
- var __defProp2, __getOwnPropDesc2, __getOwnPropNames2, __hasOwnProp2, __esm2, __export2, __copyProps2, __toCommonJS2;
37
- var init_chunk_NFEGQTCC = __esm({
38
- "../../observability/dist/chunk-NFEGQTCC.mjs"() {
39
- "use strict";
40
- __defProp2 = Object.defineProperty;
41
- __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
42
- __getOwnPropNames2 = Object.getOwnPropertyNames;
43
- __hasOwnProp2 = Object.prototype.hasOwnProperty;
44
- __esm2 = (fn, res) => function __init() {
45
- return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res;
46
- };
47
- __export2 = (target, all) => {
48
- for (var name in all)
49
- __defProp2(target, name, { get: all[name], enumerable: true });
50
- };
51
- __copyProps2 = (to, from, except, desc) => {
52
- if (from && typeof from === "object" || typeof from === "function") {
53
- for (let key of __getOwnPropNames2(from))
54
- if (!__hasOwnProp2.call(to, key) && key !== except)
55
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
56
- }
57
- return to;
58
- };
59
- __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
60
- }
61
- });
62
-
63
- // ../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/trace/SemanticConventions.js
64
- var SemanticAttributePrefixes, LLMAttributePostfixes, RetrievalAttributePostfixes, RerankerAttributePostfixes, EmbeddingAttributePostfixes, ToolAttributePostfixes, MessageAttributePostfixes, MessageContentsAttributePostfixes, ImageAttributesPostfixes, ToolCallAttributePostfixes, DocumentAttributePostfixes, TagAttributePostfixes, SessionAttributePostfixes, UserAttributePostfixes, AudioAttributesPostfixes, PromptAttributePostfixes, AgentPostfixes, GraphPostfixes, INPUT_VALUE, INPUT_MIME_TYPE, OUTPUT_VALUE, OUTPUT_MIME_TYPE, LLM_INPUT_MESSAGES, LLM_PROMPTS, LLM_INVOCATION_PARAMETERS, LLM_OUTPUT_MESSAGES, LLM_MODEL_NAME, LLM_PROVIDER, LLM_SYSTEM, LLM_TOKEN_COUNT_COMPLETION, LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING, LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO, LLM_TOKEN_COUNT_PROMPT, LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE, LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ, LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_INPUT, LLM_TOKEN_COUNT_PROMPT_DETAILS_AUDIO, LLM_TOKEN_COUNT_TOTAL, LLM_TOKEN_COUNT_PROMPT_DETAILS, LLM_TOKEN_COUNT_COMPLETION_DETAILS, LLM_COST, LLM_COST_PROMPT, LLM_COST_COMPLETION, LLM_COST_TOTAL, LLM_COST_INPUT, LLM_COST_OUTPUT, LLM_COST_COMPLETION_DETAILS_REASONING, LLM_COST_COMPLETION_DETAILS_AUDIO, LLM_COST_PROMPT_DETAILS_CACHE_WRITE, LLM_COST_PROMPT_DETAILS_CACHE_READ, LLM_COST_PROMPT_DETAILS_CACHE_INPUT, LLM_COST_PROMPT_DETAILS_AUDIO, MESSAGE_ROLE, MESSAGE_NAME, MESSAGE_TOOL_CALLS, MESSAGE_TOOL_CALL_ID, TOOL_CALL_FUNCTION_NAME, TOOL_CALL_FUNCTION_ARGUMENTS_JSON, TOOL_CALL_ID, MESSAGE_FUNCTION_CALL_NAME, MESSAGE_FUNCTION_CALL_ARGUMENTS_JSON, MESSAGE_CONTENT, MESSAGE_CONTENTS, MESSAGE_CONTENT_TYPE, MESSAGE_CONTENT_TEXT, MESSAGE_CONTENT_IMAGE, IMAGE_URL, DOCUMENT_ID, DOCUMENT_CONTENT, DOCUMENT_SCORE, DOCUMENT_METADATA, EMBEDDING_TEXT, EMBEDDING_MODEL_NAME, EMBEDDING_VECTOR, EMBEDDING_EMBEDDINGS, RETRIEVAL_DOCUMENTS, PROMPT_TEMPLATE_PREFIX, PROMPT_TEMPLATE_VARIABLES, PROMPT_TEMPLATE_TEMPLATE, LLM_FUNCTION_CALL, LLM_TOOLS, TOOL_NAME, TOOL_DESCRIPTION, TOOL_PARAMETERS, TOOL_JSON_SCHEMA, SESSION_ID, USER_ID, RERANKER_INPUT_DOCUMENTS, RERANKER_OUTPUT_DOCUMENTS, RERANKER_QUERY, RERANKER_MODEL_NAME, RERANKER_TOP_K, METADATA, PROMPT_TEMPLATE_VERSION, TAG_TAGS, AUDIO_URL, AUDIO_MIME_TYPE, AUDIO_TRANSCRIPT, PROMPT_VENDOR, PROMPT_ID, PROMPT_URL, AGENT_NAME, GRAPH_NODE_ID, GRAPH_NODE_NAME, GRAPH_NODE_PARENT_ID, SemanticConventions, OpenInferenceSpanKind, MimeType, LLMSystem, LLMProvider;
65
- var init_SemanticConventions = __esm({
66
- "../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/trace/SemanticConventions.js"() {
67
- "use strict";
68
- SemanticAttributePrefixes = {
69
- input: "input",
70
- output: "output",
71
- llm: "llm",
72
- retrieval: "retrieval",
73
- reranker: "reranker",
74
- messages: "messages",
75
- message: "message",
76
- document: "document",
77
- embedding: "embedding",
78
- tool: "tool",
79
- tool_call: "tool_call",
80
- metadata: "metadata",
81
- tag: "tag",
82
- session: "session",
83
- user: "user",
84
- openinference: "openinference",
85
- message_content: "message_content",
86
- image: "image",
87
- audio: "audio",
88
- prompt: "prompt",
89
- agent: "agent",
90
- graph: "graph"
91
- };
92
- LLMAttributePostfixes = {
93
- provider: "provider",
94
- system: "system",
95
- model_name: "model_name",
96
- token_count: "token_count",
97
- input_messages: "input_messages",
98
- output_messages: "output_messages",
99
- invocation_parameters: "invocation_parameters",
100
- prompts: "prompts",
101
- prompt_template: "prompt_template",
102
- function_call: "function_call",
103
- tools: "tools",
104
- cost: "cost"
105
- };
106
- RetrievalAttributePostfixes = {
107
- documents: "documents"
108
- };
109
- RerankerAttributePostfixes = {
110
- input_documents: "input_documents",
111
- output_documents: "output_documents",
112
- query: "query",
113
- model_name: "model_name",
114
- top_k: "top_k"
115
- };
116
- EmbeddingAttributePostfixes = {
117
- embeddings: "embeddings",
118
- text: "text",
119
- model_name: "model_name",
120
- vector: "vector"
121
- };
122
- ToolAttributePostfixes = {
123
- name: "name",
124
- description: "description",
125
- parameters: "parameters",
126
- json_schema: "json_schema"
127
- };
128
- MessageAttributePostfixes = {
129
- role: "role",
130
- content: "content",
131
- contents: "contents",
132
- name: "name",
133
- function_call_name: "function_call_name",
134
- function_call_arguments_json: "function_call_arguments_json",
135
- tool_calls: "tool_calls",
136
- tool_call_id: "tool_call_id"
137
- };
138
- MessageContentsAttributePostfixes = {
139
- type: "type",
140
- text: "text",
141
- image: "image"
142
- };
143
- ImageAttributesPostfixes = {
144
- url: "url"
145
- };
146
- ToolCallAttributePostfixes = {
147
- function_name: "function.name",
148
- function_arguments_json: "function.arguments",
149
- id: "id"
150
- };
151
- DocumentAttributePostfixes = {
152
- id: "id",
153
- content: "content",
154
- score: "score",
155
- metadata: "metadata"
156
- };
157
- TagAttributePostfixes = {
158
- tags: "tags"
159
- };
160
- SessionAttributePostfixes = {
161
- id: "id"
162
- };
163
- UserAttributePostfixes = {
164
- id: "id"
165
- };
166
- AudioAttributesPostfixes = {
167
- url: "url",
168
- mime_type: "mime_type",
169
- transcript: "transcript"
170
- };
171
- PromptAttributePostfixes = {
172
- vendor: "vendor",
173
- id: "id",
174
- url: "url"
175
- };
176
- AgentPostfixes = {
177
- name: "name"
178
- };
179
- GraphPostfixes = {
180
- node_id: "node.id",
181
- node_name: "node.name",
182
- node_parent_id: "node.parent_id"
183
- };
184
- INPUT_VALUE = `${SemanticAttributePrefixes.input}.value`;
185
- INPUT_MIME_TYPE = `${SemanticAttributePrefixes.input}.mime_type`;
186
- OUTPUT_VALUE = `${SemanticAttributePrefixes.output}.value`;
187
- OUTPUT_MIME_TYPE = `${SemanticAttributePrefixes.output}.mime_type`;
188
- LLM_INPUT_MESSAGES = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.input_messages}`;
189
- LLM_PROMPTS = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.prompts}`;
190
- LLM_INVOCATION_PARAMETERS = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.invocation_parameters}`;
191
- LLM_OUTPUT_MESSAGES = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.output_messages}`;
192
- LLM_MODEL_NAME = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.model_name}`;
193
- LLM_PROVIDER = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.provider}`;
194
- LLM_SYSTEM = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.system}`;
195
- LLM_TOKEN_COUNT_COMPLETION = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.completion`;
196
- LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.completion_details.reasoning`;
197
- LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.completion_details.audio`;
198
- LLM_TOKEN_COUNT_PROMPT = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.prompt`;
199
- LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.prompt_details.cache_write`;
200
- LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.prompt_details.cache_read`;
201
- LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_INPUT = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.prompt_details.cache_input`;
202
- LLM_TOKEN_COUNT_PROMPT_DETAILS_AUDIO = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.prompt_details.audio`;
203
- LLM_TOKEN_COUNT_TOTAL = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.total`;
204
- LLM_TOKEN_COUNT_PROMPT_DETAILS = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.prompt_details`;
205
- LLM_TOKEN_COUNT_COMPLETION_DETAILS = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.token_count}.completion_details`;
206
- LLM_COST = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}`;
207
- LLM_COST_PROMPT = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.prompt`;
208
- LLM_COST_COMPLETION = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.completion`;
209
- LLM_COST_TOTAL = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.total`;
210
- LLM_COST_INPUT = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.prompt_details.input`;
211
- LLM_COST_OUTPUT = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.completion_details.output`;
212
- LLM_COST_COMPLETION_DETAILS_REASONING = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.completion_details.reasoning`;
213
- LLM_COST_COMPLETION_DETAILS_AUDIO = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.completion_details.audio`;
214
- LLM_COST_PROMPT_DETAILS_CACHE_WRITE = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.prompt_details.cache_write`;
215
- LLM_COST_PROMPT_DETAILS_CACHE_READ = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.prompt_details.cache_read`;
216
- LLM_COST_PROMPT_DETAILS_CACHE_INPUT = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.prompt_details.cache_input`;
217
- LLM_COST_PROMPT_DETAILS_AUDIO = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.cost}.prompt_details.audio`;
218
- MESSAGE_ROLE = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.role}`;
219
- MESSAGE_NAME = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.name}`;
220
- MESSAGE_TOOL_CALLS = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.tool_calls}`;
221
- MESSAGE_TOOL_CALL_ID = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.tool_call_id}`;
222
- TOOL_CALL_FUNCTION_NAME = `${SemanticAttributePrefixes.tool_call}.${ToolCallAttributePostfixes.function_name}`;
223
- TOOL_CALL_FUNCTION_ARGUMENTS_JSON = `${SemanticAttributePrefixes.tool_call}.${ToolCallAttributePostfixes.function_arguments_json}`;
224
- TOOL_CALL_ID = `${SemanticAttributePrefixes.tool_call}.${ToolCallAttributePostfixes.id}`;
225
- MESSAGE_FUNCTION_CALL_NAME = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.function_call_name}`;
226
- MESSAGE_FUNCTION_CALL_ARGUMENTS_JSON = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.function_call_arguments_json}`;
227
- MESSAGE_CONTENT = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.content}`;
228
- MESSAGE_CONTENTS = `${SemanticAttributePrefixes.message}.${MessageAttributePostfixes.contents}`;
229
- MESSAGE_CONTENT_TYPE = `${SemanticAttributePrefixes.message_content}.${MessageContentsAttributePostfixes.type}`;
230
- MESSAGE_CONTENT_TEXT = `${SemanticAttributePrefixes.message_content}.${MessageContentsAttributePostfixes.text}`;
231
- MESSAGE_CONTENT_IMAGE = `${SemanticAttributePrefixes.message_content}.${MessageContentsAttributePostfixes.image}`;
232
- IMAGE_URL = `${SemanticAttributePrefixes.image}.${ImageAttributesPostfixes.url}`;
233
- DOCUMENT_ID = `${SemanticAttributePrefixes.document}.${DocumentAttributePostfixes.id}`;
234
- DOCUMENT_CONTENT = `${SemanticAttributePrefixes.document}.${DocumentAttributePostfixes.content}`;
235
- DOCUMENT_SCORE = `${SemanticAttributePrefixes.document}.${DocumentAttributePostfixes.score}`;
236
- DOCUMENT_METADATA = `${SemanticAttributePrefixes.document}.${DocumentAttributePostfixes.metadata}`;
237
- EMBEDDING_TEXT = `${SemanticAttributePrefixes.embedding}.${EmbeddingAttributePostfixes.text}`;
238
- EMBEDDING_MODEL_NAME = `${SemanticAttributePrefixes.embedding}.${EmbeddingAttributePostfixes.model_name}`;
239
- EMBEDDING_VECTOR = `${SemanticAttributePrefixes.embedding}.${EmbeddingAttributePostfixes.vector}`;
240
- EMBEDDING_EMBEDDINGS = `${SemanticAttributePrefixes.embedding}.${EmbeddingAttributePostfixes.embeddings}`;
241
- RETRIEVAL_DOCUMENTS = `${SemanticAttributePrefixes.retrieval}.${RetrievalAttributePostfixes.documents}`;
242
- PROMPT_TEMPLATE_PREFIX = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.prompt_template}`;
243
- PROMPT_TEMPLATE_VARIABLES = `${PROMPT_TEMPLATE_PREFIX}.variables`;
244
- PROMPT_TEMPLATE_TEMPLATE = `${PROMPT_TEMPLATE_PREFIX}.template`;
245
- LLM_FUNCTION_CALL = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.function_call}`;
246
- LLM_TOOLS = `${SemanticAttributePrefixes.llm}.${LLMAttributePostfixes.tools}`;
247
- TOOL_NAME = `${SemanticAttributePrefixes.tool}.${ToolAttributePostfixes.name}`;
248
- TOOL_DESCRIPTION = `${SemanticAttributePrefixes.tool}.${ToolAttributePostfixes.description}`;
249
- TOOL_PARAMETERS = `${SemanticAttributePrefixes.tool}.${ToolAttributePostfixes.parameters}`;
250
- TOOL_JSON_SCHEMA = `${SemanticAttributePrefixes.tool}.${ToolAttributePostfixes.json_schema}`;
251
- SESSION_ID = `${SemanticAttributePrefixes.session}.${SessionAttributePostfixes.id}`;
252
- USER_ID = `${SemanticAttributePrefixes.user}.${UserAttributePostfixes.id}`;
253
- RERANKER_INPUT_DOCUMENTS = `${SemanticAttributePrefixes.reranker}.${RerankerAttributePostfixes.input_documents}`;
254
- RERANKER_OUTPUT_DOCUMENTS = `${SemanticAttributePrefixes.reranker}.${RerankerAttributePostfixes.output_documents}`;
255
- RERANKER_QUERY = `${SemanticAttributePrefixes.reranker}.${RerankerAttributePostfixes.query}`;
256
- RERANKER_MODEL_NAME = `${SemanticAttributePrefixes.reranker}.${RerankerAttributePostfixes.model_name}`;
257
- RERANKER_TOP_K = `${SemanticAttributePrefixes.reranker}.${RerankerAttributePostfixes.top_k}`;
258
- METADATA = "metadata";
259
- PROMPT_TEMPLATE_VERSION = `${PROMPT_TEMPLATE_PREFIX}.version`;
260
- TAG_TAGS = `${SemanticAttributePrefixes.tag}.${TagAttributePostfixes.tags}`;
261
- AUDIO_URL = `${SemanticAttributePrefixes.audio}.${AudioAttributesPostfixes.url}`;
262
- AUDIO_MIME_TYPE = `${SemanticAttributePrefixes.audio}.${AudioAttributesPostfixes.mime_type}`;
263
- AUDIO_TRANSCRIPT = `${SemanticAttributePrefixes.audio}.${AudioAttributesPostfixes.transcript}`;
264
- PROMPT_VENDOR = `${SemanticAttributePrefixes.prompt}.${PromptAttributePostfixes.vendor}`;
265
- PROMPT_ID = `${SemanticAttributePrefixes.prompt}.${PromptAttributePostfixes.id}`;
266
- PROMPT_URL = `${SemanticAttributePrefixes.prompt}.${PromptAttributePostfixes.url}`;
267
- AGENT_NAME = `${SemanticAttributePrefixes.agent}.${AgentPostfixes.name}`;
268
- GRAPH_NODE_ID = `${SemanticAttributePrefixes.graph}.${GraphPostfixes.node_id}`;
269
- GRAPH_NODE_NAME = `${SemanticAttributePrefixes.graph}.${GraphPostfixes.node_name}`;
270
- GRAPH_NODE_PARENT_ID = `${SemanticAttributePrefixes.graph}.${GraphPostfixes.node_parent_id}`;
271
- SemanticConventions = {
272
- IMAGE_URL,
273
- INPUT_VALUE,
274
- INPUT_MIME_TYPE,
275
- OUTPUT_VALUE,
276
- OUTPUT_MIME_TYPE,
277
- LLM_INPUT_MESSAGES,
278
- LLM_OUTPUT_MESSAGES,
279
- LLM_MODEL_NAME,
280
- LLM_PROMPTS,
281
- LLM_INVOCATION_PARAMETERS,
282
- LLM_TOKEN_COUNT_COMPLETION,
283
- LLM_TOKEN_COUNT_COMPLETION_DETAILS,
284
- LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING,
285
- LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO,
286
- LLM_TOKEN_COUNT_PROMPT,
287
- LLM_TOKEN_COUNT_PROMPT_DETAILS,
288
- LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE,
289
- LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ,
290
- LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_INPUT,
291
- LLM_TOKEN_COUNT_PROMPT_DETAILS_AUDIO,
292
- LLM_TOKEN_COUNT_TOTAL,
293
- LLM_SYSTEM,
294
- LLM_PROVIDER,
295
- LLM_TOOLS,
296
- LLM_COST,
297
- LLM_COST_PROMPT,
298
- LLM_COST_COMPLETION,
299
- LLM_COST_TOTAL,
300
- LLM_COST_INPUT,
301
- LLM_COST_OUTPUT,
302
- LLM_COST_COMPLETION_DETAILS_REASONING,
303
- LLM_COST_COMPLETION_DETAILS_AUDIO,
304
- LLM_COST_PROMPT_DETAILS_CACHE_WRITE,
305
- LLM_COST_PROMPT_DETAILS_CACHE_READ,
306
- LLM_COST_PROMPT_DETAILS_CACHE_INPUT,
307
- LLM_COST_PROMPT_DETAILS_AUDIO,
308
- MESSAGE_ROLE,
309
- MESSAGE_NAME,
310
- MESSAGE_TOOL_CALLS,
311
- MESSAGE_TOOL_CALL_ID,
312
- TOOL_CALL_ID,
313
- TOOL_CALL_FUNCTION_NAME,
314
- TOOL_CALL_FUNCTION_ARGUMENTS_JSON,
315
- MESSAGE_FUNCTION_CALL_NAME,
316
- MESSAGE_FUNCTION_CALL_ARGUMENTS_JSON,
317
- MESSAGE_CONTENT,
318
- MESSAGE_CONTENTS,
319
- MESSAGE_CONTENT_IMAGE,
320
- MESSAGE_CONTENT_TEXT,
321
- MESSAGE_CONTENT_TYPE,
322
- DOCUMENT_ID,
323
- DOCUMENT_CONTENT,
324
- DOCUMENT_SCORE,
325
- DOCUMENT_METADATA,
326
- EMBEDDING_EMBEDDINGS,
327
- EMBEDDING_TEXT,
328
- EMBEDDING_MODEL_NAME,
329
- EMBEDDING_VECTOR,
330
- TOOL_DESCRIPTION,
331
- TOOL_NAME,
332
- TOOL_PARAMETERS,
333
- TOOL_JSON_SCHEMA,
334
- PROMPT_TEMPLATE_VARIABLES,
335
- PROMPT_TEMPLATE_TEMPLATE,
336
- PROMPT_TEMPLATE_VERSION,
337
- RERANKER_INPUT_DOCUMENTS,
338
- RERANKER_OUTPUT_DOCUMENTS,
339
- RERANKER_QUERY,
340
- RERANKER_MODEL_NAME,
341
- RERANKER_TOP_K,
342
- LLM_FUNCTION_CALL,
343
- RETRIEVAL_DOCUMENTS,
344
- SESSION_ID,
345
- USER_ID,
346
- METADATA,
347
- TAG_TAGS,
348
- OPENINFERENCE_SPAN_KIND: `${SemanticAttributePrefixes.openinference}.span.kind`,
349
- PROMPT_VENDOR,
350
- PROMPT_ID,
351
- PROMPT_URL,
352
- AGENT_NAME,
353
- GRAPH_NODE_ID,
354
- GRAPH_NODE_NAME,
355
- GRAPH_NODE_PARENT_ID
356
- };
357
- (function(OpenInferenceSpanKind2) {
358
- OpenInferenceSpanKind2["LLM"] = "LLM";
359
- OpenInferenceSpanKind2["CHAIN"] = "CHAIN";
360
- OpenInferenceSpanKind2["TOOL"] = "TOOL";
361
- OpenInferenceSpanKind2["RETRIEVER"] = "RETRIEVER";
362
- OpenInferenceSpanKind2["RERANKER"] = "RERANKER";
363
- OpenInferenceSpanKind2["EMBEDDING"] = "EMBEDDING";
364
- OpenInferenceSpanKind2["AGENT"] = "AGENT";
365
- OpenInferenceSpanKind2["GUARDRAIL"] = "GUARDRAIL";
366
- OpenInferenceSpanKind2["EVALUATOR"] = "EVALUATOR";
367
- })(OpenInferenceSpanKind || (OpenInferenceSpanKind = {}));
368
- (function(MimeType2) {
369
- MimeType2["TEXT"] = "text/plain";
370
- MimeType2["JSON"] = "application/json";
371
- MimeType2["AUDIO_WAV"] = "audio/wav";
372
- })(MimeType || (MimeType = {}));
373
- (function(LLMSystem2) {
374
- LLMSystem2["OPENAI"] = "openai";
375
- LLMSystem2["ANTHROPIC"] = "anthropic";
376
- LLMSystem2["MISTRALAI"] = "mistralai";
377
- LLMSystem2["COHERE"] = "cohere";
378
- LLMSystem2["VERTEXAI"] = "vertexai";
379
- LLMSystem2["AI21"] = "ai21";
380
- LLMSystem2["META"] = "meta";
381
- LLMSystem2["AMAZON"] = "amazon";
382
- })(LLMSystem || (LLMSystem = {}));
383
- (function(LLMProvider2) {
384
- LLMProvider2["OPENAI"] = "openai";
385
- LLMProvider2["ANTHROPIC"] = "anthropic";
386
- LLMProvider2["MISTRALAI"] = "mistralai";
387
- LLMProvider2["COHERE"] = "cohere";
388
- LLMProvider2["GOOGLE"] = "google";
389
- LLMProvider2["AWS"] = "aws";
390
- LLMProvider2["AZURE"] = "azure";
391
- LLMProvider2["XAI"] = "xai";
392
- LLMProvider2["DEEPSEEK"] = "deepseek";
393
- })(LLMProvider || (LLMProvider = {}));
394
- }
395
- });
396
-
397
- // ../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/trace/index.js
398
- var init_trace = __esm({
399
- "../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/trace/index.js"() {
400
- "use strict";
401
- init_SemanticConventions();
402
- }
403
- });
404
-
405
- // ../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/resource/SemanticResourceAttributes.js
406
- var init_SemanticResourceAttributes = __esm({
407
- "../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/resource/SemanticResourceAttributes.js"() {
408
- "use strict";
409
- }
410
- });
411
-
412
- // ../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/resource/index.js
413
- var init_resource = __esm({
414
- "../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/resource/index.js"() {
415
- "use strict";
416
- init_SemanticResourceAttributes();
417
- }
418
- });
419
-
420
- // ../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/index.js
421
- var init_esm = __esm({
422
- "../../../node_modules/.pnpm/@arizeai+openinference-semantic-conventions@2.1.7/node_modules/@arizeai/openinference-semantic-conventions/dist/esm/index.js"() {
423
- "use strict";
424
- init_trace();
425
- init_resource();
426
- }
427
- });
428
-
429
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
430
- var _globalThis;
431
- var init_globalThis = __esm({
432
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js"() {
433
- "use strict";
434
- _globalThis = typeof globalThis === "object" ? globalThis : global;
435
- }
436
- });
437
-
438
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/index.js
439
- var init_node = __esm({
440
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/node/index.js"() {
441
- "use strict";
442
- init_globalThis();
443
- }
444
- });
445
-
446
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/index.js
447
- var init_platform = __esm({
448
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/platform/index.js"() {
449
- "use strict";
450
- init_node();
451
- }
452
- });
453
-
454
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js
455
- var VERSION;
456
- var init_version = __esm({
457
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/version.js"() {
458
- "use strict";
459
- VERSION = "1.9.0";
460
- }
461
- });
462
-
463
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js
464
- function _makeCompatibilityCheck(ownVersion) {
465
- var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
466
- var rejectedVersions = /* @__PURE__ */ new Set();
467
- var myVersionMatch = ownVersion.match(re);
468
- if (!myVersionMatch) {
469
- return function() {
470
- return false;
471
- };
472
- }
473
- var ownVersionParsed = {
474
- major: +myVersionMatch[1],
475
- minor: +myVersionMatch[2],
476
- patch: +myVersionMatch[3],
477
- prerelease: myVersionMatch[4]
478
- };
479
- if (ownVersionParsed.prerelease != null) {
480
- return function isExactmatch(globalVersion) {
481
- return globalVersion === ownVersion;
482
- };
483
- }
484
- function _reject(v) {
485
- rejectedVersions.add(v);
486
- return false;
487
- }
488
- function _accept(v) {
489
- acceptedVersions.add(v);
490
- return true;
491
- }
492
- return function isCompatible2(globalVersion) {
493
- if (acceptedVersions.has(globalVersion)) {
494
- return true;
495
- }
496
- if (rejectedVersions.has(globalVersion)) {
497
- return false;
498
- }
499
- var globalVersionMatch = globalVersion.match(re);
500
- if (!globalVersionMatch) {
501
- return _reject(globalVersion);
502
- }
503
- var globalVersionParsed = {
504
- major: +globalVersionMatch[1],
505
- minor: +globalVersionMatch[2],
506
- patch: +globalVersionMatch[3],
507
- prerelease: globalVersionMatch[4]
508
- };
509
- if (globalVersionParsed.prerelease != null) {
510
- return _reject(globalVersion);
511
- }
512
- if (ownVersionParsed.major !== globalVersionParsed.major) {
513
- return _reject(globalVersion);
514
- }
515
- if (ownVersionParsed.major === 0) {
516
- if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
517
- return _accept(globalVersion);
518
- }
519
- return _reject(globalVersion);
520
- }
521
- if (ownVersionParsed.minor <= globalVersionParsed.minor) {
522
- return _accept(globalVersion);
523
- }
524
- return _reject(globalVersion);
525
- };
526
- }
527
- var re, isCompatible;
528
- var init_semver = __esm({
529
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/semver.js"() {
530
- "use strict";
531
- init_version();
532
- re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
533
- isCompatible = _makeCompatibilityCheck(VERSION);
534
- }
535
- });
536
-
537
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
538
- function registerGlobal(type, instance, diag, allowOverride) {
539
- var _a;
540
- if (allowOverride === void 0) {
541
- allowOverride = false;
542
- }
543
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
544
- version: VERSION
545
- };
546
- if (!allowOverride && api[type]) {
547
- var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
548
- diag.error(err.stack || err.message);
549
- return false;
550
- }
551
- if (api.version !== VERSION) {
552
- var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
553
- diag.error(err.stack || err.message);
554
- return false;
555
- }
556
- api[type] = instance;
557
- diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
558
- return true;
559
- }
560
- function getGlobal(type) {
561
- var _a, _b;
562
- var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
563
- if (!globalVersion || !isCompatible(globalVersion)) {
564
- return;
565
- }
566
- return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
567
- }
568
- function unregisterGlobal(type, diag) {
569
- diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
570
- var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
571
- if (api) {
572
- delete api[type];
573
- }
574
- }
575
- var major, GLOBAL_OPENTELEMETRY_API_KEY, _global;
576
- var init_global_utils = __esm({
577
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() {
578
- "use strict";
579
- init_platform();
580
- init_version();
581
- init_semver();
582
- major = VERSION.split(".")[0];
583
- GLOBAL_OPENTELEMETRY_API_KEY = /* @__PURE__ */ Symbol.for("opentelemetry.js.api." + major);
584
- _global = _globalThis;
585
- }
586
- });
587
-
588
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
589
- function logProxy(funcName, namespace, args) {
590
- var logger = getGlobal("diag");
591
- if (!logger) {
592
- return;
593
- }
594
- args.unshift(namespace);
595
- return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
596
- }
597
- var __read, __spreadArray, DiagComponentLogger;
598
- var init_ComponentLogger = __esm({
599
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() {
600
- "use strict";
601
- init_global_utils();
602
- __read = function(o, n) {
603
- var m = typeof Symbol === "function" && o[Symbol.iterator];
604
- if (!m) return o;
605
- var i = m.call(o), r, ar = [], e;
606
- try {
607
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
608
- } catch (error) {
609
- e = { error };
610
- } finally {
611
- try {
612
- if (r && !r.done && (m = i["return"])) m.call(i);
613
- } finally {
614
- if (e) throw e.error;
615
- }
616
- }
617
- return ar;
618
- };
619
- __spreadArray = function(to, from, pack) {
620
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
621
- if (ar || !(i in from)) {
622
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
623
- ar[i] = from[i];
624
- }
625
- }
626
- return to.concat(ar || Array.prototype.slice.call(from));
627
- };
628
- DiagComponentLogger = /** @class */
629
- (function() {
630
- function DiagComponentLogger2(props) {
631
- this._namespace = props.namespace || "DiagComponentLogger";
632
- }
633
- DiagComponentLogger2.prototype.debug = function() {
634
- var args = [];
635
- for (var _i = 0; _i < arguments.length; _i++) {
636
- args[_i] = arguments[_i];
637
- }
638
- return logProxy("debug", this._namespace, args);
639
- };
640
- DiagComponentLogger2.prototype.error = function() {
641
- var args = [];
642
- for (var _i = 0; _i < arguments.length; _i++) {
643
- args[_i] = arguments[_i];
644
- }
645
- return logProxy("error", this._namespace, args);
646
- };
647
- DiagComponentLogger2.prototype.info = function() {
648
- var args = [];
649
- for (var _i = 0; _i < arguments.length; _i++) {
650
- args[_i] = arguments[_i];
651
- }
652
- return logProxy("info", this._namespace, args);
653
- };
654
- DiagComponentLogger2.prototype.warn = function() {
655
- var args = [];
656
- for (var _i = 0; _i < arguments.length; _i++) {
657
- args[_i] = arguments[_i];
658
- }
659
- return logProxy("warn", this._namespace, args);
660
- };
661
- DiagComponentLogger2.prototype.verbose = function() {
662
- var args = [];
663
- for (var _i = 0; _i < arguments.length; _i++) {
664
- args[_i] = arguments[_i];
665
- }
666
- return logProxy("verbose", this._namespace, args);
667
- };
668
- return DiagComponentLogger2;
669
- })();
670
- }
671
- });
672
-
673
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js
674
- var DiagLogLevel;
675
- var init_types = __esm({
676
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/types.js"() {
677
- "use strict";
678
- (function(DiagLogLevel2) {
679
- DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
680
- DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
681
- DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
682
- DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
683
- DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
684
- DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
685
- DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
686
- })(DiagLogLevel || (DiagLogLevel = {}));
687
- }
688
- });
689
-
690
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
691
- function createLogLevelDiagLogger(maxLevel, logger) {
692
- if (maxLevel < DiagLogLevel.NONE) {
693
- maxLevel = DiagLogLevel.NONE;
694
- } else if (maxLevel > DiagLogLevel.ALL) {
695
- maxLevel = DiagLogLevel.ALL;
696
- }
697
- logger = logger || {};
698
- function _filterFunc(funcName, theLevel) {
699
- var theFunc = logger[funcName];
700
- if (typeof theFunc === "function" && maxLevel >= theLevel) {
701
- return theFunc.bind(logger);
702
- }
703
- return function() {
704
- };
705
- }
706
- return {
707
- error: _filterFunc("error", DiagLogLevel.ERROR),
708
- warn: _filterFunc("warn", DiagLogLevel.WARN),
709
- info: _filterFunc("info", DiagLogLevel.INFO),
710
- debug: _filterFunc("debug", DiagLogLevel.DEBUG),
711
- verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
712
- };
713
- }
714
- var init_logLevelLogger = __esm({
715
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() {
716
- "use strict";
717
- init_types();
718
- }
719
- });
720
-
721
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js
722
- var __read2, __spreadArray2, API_NAME, DiagAPI;
723
- var init_diag = __esm({
724
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/diag.js"() {
725
- "use strict";
726
- init_ComponentLogger();
727
- init_logLevelLogger();
728
- init_types();
729
- init_global_utils();
730
- __read2 = function(o, n) {
731
- var m = typeof Symbol === "function" && o[Symbol.iterator];
732
- if (!m) return o;
733
- var i = m.call(o), r, ar = [], e;
734
- try {
735
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
736
- } catch (error) {
737
- e = { error };
738
- } finally {
739
- try {
740
- if (r && !r.done && (m = i["return"])) m.call(i);
741
- } finally {
742
- if (e) throw e.error;
743
- }
744
- }
745
- return ar;
746
- };
747
- __spreadArray2 = function(to, from, pack) {
748
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
749
- if (ar || !(i in from)) {
750
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
751
- ar[i] = from[i];
752
- }
753
- }
754
- return to.concat(ar || Array.prototype.slice.call(from));
755
- };
756
- API_NAME = "diag";
757
- DiagAPI = /** @class */
758
- (function() {
759
- function DiagAPI2() {
760
- function _logProxy(funcName) {
761
- return function() {
762
- var args = [];
763
- for (var _i = 0; _i < arguments.length; _i++) {
764
- args[_i] = arguments[_i];
765
- }
766
- var logger = getGlobal("diag");
767
- if (!logger)
768
- return;
769
- return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
770
- };
771
- }
772
- var self = this;
773
- var setLogger = function(logger, optionsOrLogLevel) {
774
- var _a, _b, _c;
775
- if (optionsOrLogLevel === void 0) {
776
- optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
777
- }
778
- if (logger === self) {
779
- var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
780
- self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
781
- return false;
782
- }
783
- if (typeof optionsOrLogLevel === "number") {
784
- optionsOrLogLevel = {
785
- logLevel: optionsOrLogLevel
786
- };
787
- }
788
- var oldLogger = getGlobal("diag");
789
- var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
790
- if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
791
- var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
792
- oldLogger.warn("Current logger will be overwritten from " + stack);
793
- newLogger.warn("Current logger will overwrite one already registered from " + stack);
794
- }
795
- return registerGlobal("diag", newLogger, self, true);
796
- };
797
- self.setLogger = setLogger;
798
- self.disable = function() {
799
- unregisterGlobal(API_NAME, self);
800
- };
801
- self.createComponentLogger = function(options) {
802
- return new DiagComponentLogger(options);
803
- };
804
- self.verbose = _logProxy("verbose");
805
- self.debug = _logProxy("debug");
806
- self.info = _logProxy("info");
807
- self.warn = _logProxy("warn");
808
- self.error = _logProxy("error");
809
- }
810
- DiagAPI2.instance = function() {
811
- if (!this._instance) {
812
- this._instance = new DiagAPI2();
813
- }
814
- return this._instance;
815
- };
816
- return DiagAPI2;
817
- })();
818
- }
819
- });
820
-
821
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js
822
- function createContextKey(description) {
823
- return Symbol.for(description);
824
- }
825
- var BaseContext, ROOT_CONTEXT;
826
- var init_context = __esm({
827
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/context.js"() {
828
- "use strict";
829
- BaseContext = /** @class */
830
- /* @__PURE__ */ (function() {
831
- function BaseContext2(parentContext) {
832
- var self = this;
833
- self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
834
- self.getValue = function(key) {
835
- return self._currentContext.get(key);
836
- };
837
- self.setValue = function(key, value) {
838
- var context2 = new BaseContext2(self._currentContext);
839
- context2._currentContext.set(key, value);
840
- return context2;
841
- };
842
- self.deleteValue = function(key) {
843
- var context2 = new BaseContext2(self._currentContext);
844
- context2._currentContext.delete(key);
845
- return context2;
846
- };
847
- }
848
- return BaseContext2;
849
- })();
850
- ROOT_CONTEXT = new BaseContext();
851
- }
852
- });
853
-
854
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
855
- var __read3, __spreadArray3, NoopContextManager;
856
- var init_NoopContextManager = __esm({
857
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js"() {
858
- "use strict";
859
- init_context();
860
- __read3 = function(o, n) {
861
- var m = typeof Symbol === "function" && o[Symbol.iterator];
862
- if (!m) return o;
863
- var i = m.call(o), r, ar = [], e;
864
- try {
865
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
866
- } catch (error) {
867
- e = { error };
868
- } finally {
869
- try {
870
- if (r && !r.done && (m = i["return"])) m.call(i);
871
- } finally {
872
- if (e) throw e.error;
873
- }
874
- }
875
- return ar;
876
- };
877
- __spreadArray3 = function(to, from, pack) {
878
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
879
- if (ar || !(i in from)) {
880
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
881
- ar[i] = from[i];
882
- }
883
- }
884
- return to.concat(ar || Array.prototype.slice.call(from));
885
- };
886
- NoopContextManager = /** @class */
887
- (function() {
888
- function NoopContextManager2() {
889
- }
890
- NoopContextManager2.prototype.active = function() {
891
- return ROOT_CONTEXT;
892
- };
893
- NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
894
- var args = [];
895
- for (var _i = 3; _i < arguments.length; _i++) {
896
- args[_i - 3] = arguments[_i];
897
- }
898
- return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
899
- };
900
- NoopContextManager2.prototype.bind = function(_context, target) {
901
- return target;
902
- };
903
- NoopContextManager2.prototype.enable = function() {
904
- return this;
905
- };
906
- NoopContextManager2.prototype.disable = function() {
907
- return this;
908
- };
909
- return NoopContextManager2;
910
- })();
911
- }
912
- });
913
-
914
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js
915
- var __read4, __spreadArray4, API_NAME2, NOOP_CONTEXT_MANAGER, ContextAPI;
916
- var init_context2 = __esm({
917
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/context.js"() {
918
- "use strict";
919
- init_NoopContextManager();
920
- init_global_utils();
921
- init_diag();
922
- __read4 = function(o, n) {
923
- var m = typeof Symbol === "function" && o[Symbol.iterator];
924
- if (!m) return o;
925
- var i = m.call(o), r, ar = [], e;
926
- try {
927
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
928
- } catch (error) {
929
- e = { error };
930
- } finally {
931
- try {
932
- if (r && !r.done && (m = i["return"])) m.call(i);
933
- } finally {
934
- if (e) throw e.error;
935
- }
936
- }
937
- return ar;
938
- };
939
- __spreadArray4 = function(to, from, pack) {
940
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
941
- if (ar || !(i in from)) {
942
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
943
- ar[i] = from[i];
944
- }
945
- }
946
- return to.concat(ar || Array.prototype.slice.call(from));
947
- };
948
- API_NAME2 = "context";
949
- NOOP_CONTEXT_MANAGER = new NoopContextManager();
950
- ContextAPI = /** @class */
951
- (function() {
952
- function ContextAPI2() {
953
- }
954
- ContextAPI2.getInstance = function() {
955
- if (!this._instance) {
956
- this._instance = new ContextAPI2();
957
- }
958
- return this._instance;
959
- };
960
- ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
961
- return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
962
- };
963
- ContextAPI2.prototype.active = function() {
964
- return this._getContextManager().active();
965
- };
966
- ContextAPI2.prototype.with = function(context2, fn, thisArg) {
967
- var _a;
968
- var args = [];
969
- for (var _i = 3; _i < arguments.length; _i++) {
970
- args[_i - 3] = arguments[_i];
971
- }
972
- return (_a = this._getContextManager()).with.apply(_a, __spreadArray4([context2, fn, thisArg], __read4(args), false));
973
- };
974
- ContextAPI2.prototype.bind = function(context2, target) {
975
- return this._getContextManager().bind(context2, target);
976
- };
977
- ContextAPI2.prototype._getContextManager = function() {
978
- return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
979
- };
980
- ContextAPI2.prototype.disable = function() {
981
- this._getContextManager().disable();
982
- unregisterGlobal(API_NAME2, DiagAPI.instance());
983
- };
984
- return ContextAPI2;
985
- })();
986
- }
987
- });
988
-
989
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js
990
- var TraceFlags;
991
- var init_trace_flags = __esm({
992
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js"() {
993
- "use strict";
994
- (function(TraceFlags2) {
995
- TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
996
- TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
997
- })(TraceFlags || (TraceFlags = {}));
998
- }
999
- });
1000
-
1001
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js
1002
- var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT;
1003
- var init_invalid_span_constants = __esm({
1004
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js"() {
1005
- "use strict";
1006
- init_trace_flags();
1007
- INVALID_SPANID = "0000000000000000";
1008
- INVALID_TRACEID = "00000000000000000000000000000000";
1009
- INVALID_SPAN_CONTEXT = {
1010
- traceId: INVALID_TRACEID,
1011
- spanId: INVALID_SPANID,
1012
- traceFlags: TraceFlags.NONE
1013
- };
1014
- }
1015
- });
1016
-
1017
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js
1018
- var NonRecordingSpan;
1019
- var init_NonRecordingSpan = __esm({
1020
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js"() {
1021
- "use strict";
1022
- init_invalid_span_constants();
1023
- NonRecordingSpan = /** @class */
1024
- (function() {
1025
- function NonRecordingSpan2(_spanContext) {
1026
- if (_spanContext === void 0) {
1027
- _spanContext = INVALID_SPAN_CONTEXT;
1028
- }
1029
- this._spanContext = _spanContext;
1030
- }
1031
- NonRecordingSpan2.prototype.spanContext = function() {
1032
- return this._spanContext;
1033
- };
1034
- NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
1035
- return this;
1036
- };
1037
- NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
1038
- return this;
1039
- };
1040
- NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
1041
- return this;
1042
- };
1043
- NonRecordingSpan2.prototype.addLink = function(_link) {
1044
- return this;
1045
- };
1046
- NonRecordingSpan2.prototype.addLinks = function(_links) {
1047
- return this;
1048
- };
1049
- NonRecordingSpan2.prototype.setStatus = function(_status) {
1050
- return this;
1051
- };
1052
- NonRecordingSpan2.prototype.updateName = function(_name) {
1053
- return this;
1054
- };
1055
- NonRecordingSpan2.prototype.end = function(_endTime) {
1056
- };
1057
- NonRecordingSpan2.prototype.isRecording = function() {
1058
- return false;
1059
- };
1060
- NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
1061
- };
1062
- return NonRecordingSpan2;
1063
- })();
1064
- }
1065
- });
1066
-
1067
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js
1068
- function getSpan(context2) {
1069
- return context2.getValue(SPAN_KEY) || void 0;
1070
- }
1071
- function getActiveSpan() {
1072
- return getSpan(ContextAPI.getInstance().active());
1073
- }
1074
- function setSpan(context2, span) {
1075
- return context2.setValue(SPAN_KEY, span);
1076
- }
1077
- function deleteSpan(context2) {
1078
- return context2.deleteValue(SPAN_KEY);
1079
- }
1080
- function setSpanContext(context2, spanContext) {
1081
- return setSpan(context2, new NonRecordingSpan(spanContext));
1082
- }
1083
- function getSpanContext(context2) {
1084
- var _a;
1085
- return (_a = getSpan(context2)) === null || _a === void 0 ? void 0 : _a.spanContext();
1086
- }
1087
- var SPAN_KEY;
1088
- var init_context_utils = __esm({
1089
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js"() {
1090
- "use strict";
1091
- init_context();
1092
- init_NonRecordingSpan();
1093
- init_context2();
1094
- SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
1095
- }
1096
- });
1097
-
1098
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js
1099
- function isValidTraceId(traceId) {
1100
- return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
1101
- }
1102
- function isValidSpanId(spanId) {
1103
- return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
1104
- }
1105
- function isSpanContextValid(spanContext) {
1106
- return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
1107
- }
1108
- function wrapSpanContext(spanContext) {
1109
- return new NonRecordingSpan(spanContext);
1110
- }
1111
- var VALID_TRACEID_REGEX, VALID_SPANID_REGEX;
1112
- var init_spancontext_utils = __esm({
1113
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js"() {
1114
- "use strict";
1115
- init_invalid_span_constants();
1116
- init_NonRecordingSpan();
1117
- VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
1118
- VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
1119
- }
1120
- });
1121
-
1122
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js
1123
- function isSpanContext(spanContext) {
1124
- return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
1125
- }
1126
- var contextApi, NoopTracer;
1127
- var init_NoopTracer = __esm({
1128
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js"() {
1129
- "use strict";
1130
- init_context2();
1131
- init_context_utils();
1132
- init_NonRecordingSpan();
1133
- init_spancontext_utils();
1134
- contextApi = ContextAPI.getInstance();
1135
- NoopTracer = /** @class */
1136
- (function() {
1137
- function NoopTracer2() {
1138
- }
1139
- NoopTracer2.prototype.startSpan = function(name, options, context2) {
1140
- if (context2 === void 0) {
1141
- context2 = contextApi.active();
1142
- }
1143
- var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
1144
- if (root) {
1145
- return new NonRecordingSpan();
1146
- }
1147
- var parentFromContext = context2 && getSpanContext(context2);
1148
- if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
1149
- return new NonRecordingSpan(parentFromContext);
1150
- } else {
1151
- return new NonRecordingSpan();
1152
- }
1153
- };
1154
- NoopTracer2.prototype.startActiveSpan = function(name, arg2, arg3, arg4) {
1155
- var opts;
1156
- var ctx;
1157
- var fn;
1158
- if (arguments.length < 2) {
1159
- return;
1160
- } else if (arguments.length === 2) {
1161
- fn = arg2;
1162
- } else if (arguments.length === 3) {
1163
- opts = arg2;
1164
- fn = arg3;
1165
- } else {
1166
- opts = arg2;
1167
- ctx = arg3;
1168
- fn = arg4;
1169
- }
1170
- var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
1171
- var span = this.startSpan(name, opts, parentContext);
1172
- var contextWithSpanSet = setSpan(parentContext, span);
1173
- return contextApi.with(contextWithSpanSet, fn, void 0, span);
1174
- };
1175
- return NoopTracer2;
1176
- })();
1177
- }
1178
- });
1179
-
1180
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js
1181
- var NOOP_TRACER, ProxyTracer;
1182
- var init_ProxyTracer = __esm({
1183
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js"() {
1184
- "use strict";
1185
- init_NoopTracer();
1186
- NOOP_TRACER = new NoopTracer();
1187
- ProxyTracer = /** @class */
1188
- (function() {
1189
- function ProxyTracer2(_provider, name, version, options) {
1190
- this._provider = _provider;
1191
- this.name = name;
1192
- this.version = version;
1193
- this.options = options;
1194
- }
1195
- ProxyTracer2.prototype.startSpan = function(name, options, context2) {
1196
- return this._getTracer().startSpan(name, options, context2);
1197
- };
1198
- ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
1199
- var tracer = this._getTracer();
1200
- return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
1201
- };
1202
- ProxyTracer2.prototype._getTracer = function() {
1203
- if (this._delegate) {
1204
- return this._delegate;
1205
- }
1206
- var tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
1207
- if (!tracer) {
1208
- return NOOP_TRACER;
1209
- }
1210
- this._delegate = tracer;
1211
- return this._delegate;
1212
- };
1213
- return ProxyTracer2;
1214
- })();
1215
- }
1216
- });
1217
-
1218
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js
1219
- var NoopTracerProvider;
1220
- var init_NoopTracerProvider = __esm({
1221
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js"() {
1222
- "use strict";
1223
- init_NoopTracer();
1224
- NoopTracerProvider = /** @class */
1225
- (function() {
1226
- function NoopTracerProvider2() {
1227
- }
1228
- NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
1229
- return new NoopTracer();
1230
- };
1231
- return NoopTracerProvider2;
1232
- })();
1233
- }
1234
- });
1235
-
1236
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js
1237
- var NOOP_TRACER_PROVIDER, ProxyTracerProvider;
1238
- var init_ProxyTracerProvider = __esm({
1239
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js"() {
1240
- "use strict";
1241
- init_ProxyTracer();
1242
- init_NoopTracerProvider();
1243
- NOOP_TRACER_PROVIDER = new NoopTracerProvider();
1244
- ProxyTracerProvider = /** @class */
1245
- (function() {
1246
- function ProxyTracerProvider2() {
1247
- }
1248
- ProxyTracerProvider2.prototype.getTracer = function(name, version, options) {
1249
- var _a;
1250
- return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
1251
- };
1252
- ProxyTracerProvider2.prototype.getDelegate = function() {
1253
- var _a;
1254
- return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
1255
- };
1256
- ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
1257
- this._delegate = delegate;
1258
- };
1259
- ProxyTracerProvider2.prototype.getDelegateTracer = function(name, version, options) {
1260
- var _a;
1261
- return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
1262
- };
1263
- return ProxyTracerProvider2;
1264
- })();
1265
- }
1266
- });
1267
-
1268
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js
1269
- var SpanStatusCode;
1270
- var init_status = __esm({
1271
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace/status.js"() {
1272
- "use strict";
1273
- (function(SpanStatusCode2) {
1274
- SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
1275
- SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
1276
- SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
1277
- })(SpanStatusCode || (SpanStatusCode = {}));
1278
- }
1279
- });
1280
-
1281
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js
1282
- var context;
1283
- var init_context_api = __esm({
1284
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/context-api.js"() {
1285
- "use strict";
1286
- init_context2();
1287
- context = ContextAPI.getInstance();
1288
- }
1289
- });
1290
-
1291
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js
1292
- var API_NAME3, TraceAPI;
1293
- var init_trace2 = __esm({
1294
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/api/trace.js"() {
1295
- "use strict";
1296
- init_global_utils();
1297
- init_ProxyTracerProvider();
1298
- init_spancontext_utils();
1299
- init_context_utils();
1300
- init_diag();
1301
- API_NAME3 = "trace";
1302
- TraceAPI = /** @class */
1303
- (function() {
1304
- function TraceAPI2() {
1305
- this._proxyTracerProvider = new ProxyTracerProvider();
1306
- this.wrapSpanContext = wrapSpanContext;
1307
- this.isSpanContextValid = isSpanContextValid;
1308
- this.deleteSpan = deleteSpan;
1309
- this.getSpan = getSpan;
1310
- this.getActiveSpan = getActiveSpan;
1311
- this.getSpanContext = getSpanContext;
1312
- this.setSpan = setSpan;
1313
- this.setSpanContext = setSpanContext;
1314
- }
1315
- TraceAPI2.getInstance = function() {
1316
- if (!this._instance) {
1317
- this._instance = new TraceAPI2();
1318
- }
1319
- return this._instance;
1320
- };
1321
- TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
1322
- var success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
1323
- if (success) {
1324
- this._proxyTracerProvider.setDelegate(provider);
1325
- }
1326
- return success;
1327
- };
1328
- TraceAPI2.prototype.getTracerProvider = function() {
1329
- return getGlobal(API_NAME3) || this._proxyTracerProvider;
1330
- };
1331
- TraceAPI2.prototype.getTracer = function(name, version) {
1332
- return this.getTracerProvider().getTracer(name, version);
1333
- };
1334
- TraceAPI2.prototype.disable = function() {
1335
- unregisterGlobal(API_NAME3, DiagAPI.instance());
1336
- this._proxyTracerProvider = new ProxyTracerProvider();
1337
- };
1338
- return TraceAPI2;
1339
- })();
1340
- }
1341
- });
1342
-
1343
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js
1344
- var trace;
1345
- var init_trace_api = __esm({
1346
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/trace-api.js"() {
1347
- "use strict";
1348
- init_trace2();
1349
- trace = TraceAPI.getInstance();
1350
- }
1351
- });
1352
-
1353
- // ../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/index.js
1354
- var init_esm2 = __esm({
1355
- "../../../node_modules/.pnpm/@opentelemetry+api@1.9.0/node_modules/@opentelemetry/api/build/esm/index.js"() {
1356
- "use strict";
1357
- init_status();
1358
- init_context_api();
1359
- init_trace_api();
1360
- }
1361
- });
1362
-
1363
- // ../../observability/dist/chunk-ZGEMAYS4.mjs
1364
- function createTraceAttributes({
1365
- name,
1366
- userId,
1367
- sessionId,
1368
- version,
1369
- release,
1370
- input,
1371
- output,
1372
- metadata,
1373
- tags,
1374
- environment,
1375
- public: isPublic
1376
- } = {}) {
1377
- const attributes = {
1378
- [OtelSpanAttributes.TRACE_NAME]: name,
1379
- // Use OpenInference standard attributes for user and session
1380
- [OtelSpanAttributes.USER_ID]: userId,
1381
- [OtelSpanAttributes.SESSION_ID]: sessionId,
1382
- [OtelSpanAttributes.VERSION]: version,
1383
- [OtelSpanAttributes.RELEASE]: release,
1384
- [OtelSpanAttributes.TRACE_INPUT]: _serialize(input),
1385
- [OtelSpanAttributes.TRACE_OUTPUT]: _serialize(output),
1386
- [OtelSpanAttributes.TRACE_TAGS]: tags,
1387
- [OtelSpanAttributes.ENVIRONMENT]: environment,
1388
- [OtelSpanAttributes.TRACE_PUBLIC]: isPublic,
1389
- ..._flattenAndSerializeMetadata(metadata, OtelSpanAttributes.TRACE_METADATA)
1390
- };
1391
- return Object.fromEntries(
1392
- Object.entries(attributes).filter(([_, v]) => v != null)
1393
- );
1394
- }
1395
- function createObservationAttributes(type, attributes) {
1396
- const {
1397
- metadata,
1398
- input,
1399
- output,
1400
- level,
1401
- statusMessage,
1402
- version,
1403
- completionStartTime,
1404
- model,
1405
- modelParameters,
1406
- usageDetails
1407
- } = attributes;
1408
- const otelAttributes = {
1409
- [SemanticConventions.OPENINFERENCE_SPAN_KIND]: type.toUpperCase(),
1410
- [OtelSpanAttributes.OBSERVATION_TYPE]: type,
1411
- [OtelSpanAttributes.OBSERVATION_LEVEL]: level,
1412
- [OtelSpanAttributes.OBSERVATION_STATUS_MESSAGE]: statusMessage,
1413
- [OtelSpanAttributes.VERSION]: version,
1414
- // Use OpenInference input.value convention
1415
- [SemanticConventions.INPUT_VALUE]: _serialize(input),
1416
- // Also set legacy agkit.observation.input for compatibility
1417
- [OtelSpanAttributes.OBSERVATION_INPUT]: _serialize(input),
1418
- // Use OpenInference output.value convention
1419
- [SemanticConventions.OUTPUT_VALUE]: _serialize(output),
1420
- // Also set legacy agkit.observation.output for compatibility
1421
- [OtelSpanAttributes.OBSERVATION_OUTPUT]: _serialize(output)
1422
- };
1423
- if (type === "llm") {
1424
- if (model) {
1425
- otelAttributes[SemanticConventions.LLM_MODEL_NAME] = model;
1426
- }
1427
- if (modelParameters) {
1428
- otelAttributes[SemanticConventions.LLM_INVOCATION_PARAMETERS] = _serialize(modelParameters);
1429
- otelAttributes[OtelSpanAttributes.LLM_MODEL_PARAMETERS] = _serialize(modelParameters);
1430
- }
1431
- if (usageDetails) {
1432
- if (typeof usageDetails === "object") {
1433
- const usage = usageDetails;
1434
- if (usage.promptTokens !== void 0) {
1435
- otelAttributes[SemanticConventions.LLM_TOKEN_COUNT_PROMPT] = usage.promptTokens;
1436
- }
1437
- if (usage.completionTokens !== void 0) {
1438
- otelAttributes[SemanticConventions.LLM_TOKEN_COUNT_COMPLETION] = usage.completionTokens;
1439
- }
1440
- if (usage.totalTokens !== void 0) {
1441
- otelAttributes[SemanticConventions.LLM_TOKEN_COUNT_TOTAL] = usage.totalTokens;
1442
- }
1443
- }
1444
- otelAttributes[OtelSpanAttributes.LLM_USAGE_DETAILS] = _serialize(usageDetails);
1445
- }
1446
- if (completionStartTime) {
1447
- otelAttributes[OtelSpanAttributes.LLM_COMPLETION_START_TIME] = _serialize(completionStartTime);
1448
- }
1449
- }
1450
- if (type === "embedding") {
1451
- if (model) {
1452
- otelAttributes[SemanticConventions.EMBEDDING_MODEL_NAME] = model;
1453
- }
1454
- if (modelParameters) {
1455
- otelAttributes[SemanticConventions.LLM_INVOCATION_PARAMETERS] = _serialize(modelParameters);
1456
- }
1457
- }
1458
- const metadataAttrs = _flattenAndSerializeMetadata(
1459
- metadata,
1460
- SemanticConventions.METADATA
1461
- );
1462
- Object.assign(otelAttributes, metadataAttrs);
1463
- const obsetvabilityMetadataAttrs = _flattenAndSerializeMetadata(
1464
- metadata,
1465
- OtelSpanAttributes.OBSERVATION_METADATA
1466
- );
1467
- Object.assign(otelAttributes, obsetvabilityMetadataAttrs);
1468
- return Object.fromEntries(
1469
- Object.entries(otelAttributes).filter(([_, v]) => v != null)
1470
- );
1471
- }
1472
- function _serialize(obj) {
1473
- try {
1474
- if (typeof obj === "string") return obj;
1475
- if (obj instanceof Date) return obj.toISOString();
1476
- return obj != null ? JSON.stringify(obj) : void 0;
1477
- } catch {
1478
- return "<failed to serialize>";
1479
- }
1480
- }
1481
- function _flattenAndSerializeMetadata(metadata, prefix) {
1482
- const metadataAttributes = {};
1483
- if (metadata === void 0 || metadata === null) {
1484
- return metadataAttributes;
1485
- }
1486
- if (typeof metadata !== "object" || Array.isArray(metadata)) {
1487
- const serialized = _serialize(metadata);
1488
- if (serialized) {
1489
- metadataAttributes[prefix] = serialized;
1490
- }
1491
- } else {
1492
- for (const [key, value] of Object.entries(metadata)) {
1493
- const serialized = typeof value === "string" ? value : _serialize(value);
1494
- if (serialized) {
1495
- metadataAttributes[`${prefix}.${key}`] = serialized;
1496
- }
1497
- }
1498
- }
1499
- return metadataAttributes;
1500
- }
1501
- function createState() {
1502
- return {
1503
- isolatedTracerProvider: null
1504
- };
1505
- }
1506
- function getObservabilityGlobalState() {
1507
- const initialState = createState();
1508
- try {
1509
- const g = globalThis;
1510
- if (typeof g !== "object" || g === null) {
1511
- console.warn(
1512
- "[Observability] globalThis is not available, using fallback state"
1513
- );
1514
- return initialState;
1515
- }
1516
- if (!g[OBSERVABILITY_GLOBAL_SYMBOL]) {
1517
- Object.defineProperty(g, OBSERVABILITY_GLOBAL_SYMBOL, {
1518
- value: initialState,
1519
- writable: false,
1520
- configurable: false,
1521
- enumerable: false
1522
- });
1523
- }
1524
- return g[OBSERVABILITY_GLOBAL_SYMBOL];
1525
- } catch (err) {
1526
- console.error(
1527
- `[Observability] Failed to access global state: ${err instanceof Error ? err.message : String(err)}`
1528
- );
1529
- return initialState;
1530
- }
1531
- }
1532
- function setTracerProvider(provider) {
1533
- getObservabilityGlobalState().isolatedTracerProvider = provider;
1534
- }
1535
- function getTracerProvider() {
1536
- const { isolatedTracerProvider } = getObservabilityGlobalState();
1537
- if (isolatedTracerProvider) return isolatedTracerProvider;
1538
- return trace.getTracerProvider();
1539
- }
1540
- function getTracer() {
1541
- return getTracerProvider().getTracer(
1542
- OBSERVABILITY_SDK_NAME,
1543
- OBSERVABILITY_SDK_VERSION
1544
- );
1545
- }
1546
- function createOtelSpan(params) {
1547
- return getTracer().startSpan(
1548
- params.name,
1549
- { startTime: params.startTime },
1550
- createParentContext(params.parentSpanContext)
1551
- );
1552
- }
1553
- function createParentContext(parentSpanContext) {
1554
- if (!parentSpanContext) return;
1555
- return trace.setSpanContext(context.active(), parentSpanContext);
1556
- }
1557
- function startObservation(name, attributes, options) {
1558
- const { asType = "span", ...observationOptions } = options || {};
1559
- const otelSpan = createOtelSpan({
1560
- name,
1561
- ...observationOptions
1562
- });
1563
- switch (asType) {
1564
- case "llm":
1565
- return new ObservationLLM({
1566
- otelSpan,
1567
- attributes
1568
- });
1569
- case "embedding":
1570
- return new ObservationEmbedding({
1571
- otelSpan,
1572
- attributes
1573
- });
1574
- case "agent":
1575
- return new ObservationAgent({
1576
- otelSpan,
1577
- attributes
1578
- });
1579
- case "tool":
1580
- return new ObservationTool({
1581
- otelSpan,
1582
- attributes
1583
- });
1584
- case "chain":
1585
- return new ObservationChain({
1586
- otelSpan,
1587
- attributes
1588
- });
1589
- case "retriever":
1590
- return new ObservationRetriever({
1591
- otelSpan,
1592
- attributes
1593
- });
1594
- case "reranker":
1595
- return new ObservationReranker({
1596
- otelSpan,
1597
- attributes
1598
- });
1599
- case "evaluator":
1600
- return new ObservationEvaluator({
1601
- otelSpan,
1602
- attributes
1603
- });
1604
- case "guardrail":
1605
- return new ObservationGuardrail({
1606
- otelSpan,
1607
- attributes
1608
- });
1609
- case "span":
1610
- default:
1611
- return new ObservationSpan({
1612
- otelSpan,
1613
- attributes
1614
- });
1615
- }
1616
- }
1617
- function updateActiveTrace(attributes) {
1618
- const span = trace.getActiveSpan();
1619
- if (!span) {
1620
- console.warn(
1621
- "[Observability] No active OTEL span in context. Skipping trace update."
1622
- );
1623
- return;
1624
- }
1625
- span.setAttributes(createTraceAttributes(attributes));
1626
- }
1627
- function getActiveTraceId() {
1628
- return trace.getActiveSpan()?.spanContext().traceId;
1629
- }
1630
- function getActiveSpanId() {
1631
- return trace.getActiveSpan()?.spanContext().spanId;
1632
- }
1633
- function wrapPromise(promise, span, endOnExit) {
1634
- return promise.then(
1635
- (value) => {
1636
- if (endOnExit !== false) {
1637
- span.end();
1638
- }
1639
- return value;
1640
- },
1641
- (err) => {
1642
- span.setStatus({
1643
- code: SpanStatusCode.ERROR,
1644
- message: err instanceof Error ? err.message : "Unknown error"
1645
- });
1646
- if (endOnExit !== false) {
1647
- span.end();
1648
- }
1649
- throw err;
1650
- }
1651
- );
1652
- }
1653
- function startActiveObservation(name, fn, options) {
1654
- const { asType = "span", endOnExit, ...observationOptions } = options || {};
1655
- return getTracer().startActiveSpan(
1656
- name,
1657
- { startTime: observationOptions?.startTime },
1658
- createParentContext(observationOptions?.parentSpanContext) ?? context.active(),
1659
- (span) => {
1660
- try {
1661
- let observation;
1662
- switch (asType) {
1663
- case "llm":
1664
- observation = new ObservationLLM({ otelSpan: span });
1665
- break;
1666
- case "embedding":
1667
- observation = new ObservationEmbedding({ otelSpan: span });
1668
- break;
1669
- case "agent":
1670
- observation = new ObservationAgent({ otelSpan: span });
1671
- break;
1672
- case "tool":
1673
- observation = new ObservationTool({ otelSpan: span });
1674
- break;
1675
- case "chain":
1676
- observation = new ObservationChain({ otelSpan: span });
1677
- break;
1678
- case "retriever":
1679
- observation = new ObservationRetriever({ otelSpan: span });
1680
- break;
1681
- case "reranker":
1682
- observation = new ObservationReranker({ otelSpan: span });
1683
- break;
1684
- case "evaluator":
1685
- observation = new ObservationEvaluator({ otelSpan: span });
1686
- break;
1687
- case "guardrail":
1688
- observation = new ObservationGuardrail({ otelSpan: span });
1689
- break;
1690
- case "span":
1691
- default:
1692
- observation = new ObservationSpan({ otelSpan: span });
1693
- }
1694
- const result = fn(observation);
1695
- if (result instanceof Promise) {
1696
- return wrapPromise(
1697
- result,
1698
- span,
1699
- endOnExit
1700
- );
1701
- } else {
1702
- if (endOnExit !== false) {
1703
- span.end();
1704
- }
1705
- return result;
1706
- }
1707
- } catch (err) {
1708
- span.setStatus({
1709
- code: SpanStatusCode.ERROR,
1710
- message: err instanceof Error ? err.message : "Unknown error"
1711
- });
1712
- if (endOnExit !== false) {
1713
- span.end();
1714
- }
1715
- throw err;
1716
- }
1717
- }
1718
- );
1719
- }
1720
- function updateActiveObservation(attributes) {
1721
- const span = trace.getActiveSpan();
1722
- if (!span) {
1723
- console.warn(
1724
- "[Observability] No active OTEL span in context. Skipping observation update."
1725
- );
1726
- return;
1727
- }
1728
- span.setAttributes(createObservationAttributes("span", attributes));
1729
- }
1730
- function _captureArguments(args) {
1731
- if (args.length === 0) return {};
1732
- if (args.length === 1) return { arg: args[0] };
1733
- return { args };
1734
- }
1735
- function observe(fn, options = {}) {
1736
- const {
1737
- asType = "span",
1738
- captureInput = true,
1739
- captureOutput = true,
1740
- ...observationOptions
1741
- } = options;
1742
- const wrappedFunction = function(...args) {
1743
- const name = fn.name || "anonymous-function";
1744
- const inputData = captureInput ? _captureArguments(args) : void 0;
1745
- const observation = startObservation(
1746
- name,
1747
- inputData ? { input: inputData } : {},
1748
- {
1749
- ...observationOptions,
1750
- asType
1751
- }
1752
- );
1753
- const activeContext = trace.setSpan(context.active(), observation.otelSpan);
1754
- const result = context.with(activeContext, () => fn.apply(this, args));
1755
- if (result instanceof Promise) {
1756
- return result.then(
1757
- (value) => {
1758
- if (captureOutput) {
1759
- observation.update({ output: value });
1760
- }
1761
- observation.end();
1762
- return value;
1763
- },
1764
- (err) => {
1765
- observation.update({
1766
- level: "ERROR",
1767
- statusMessage: err instanceof Error ? err.message : "Unknown error"
1768
- });
1769
- observation.end();
1770
- throw err;
1771
- }
1772
- );
1773
- }
1774
- if (captureOutput) {
1775
- observation.update({ output: result });
1776
- }
1777
- observation.end();
1778
- return result;
1779
- };
1780
- Object.defineProperty(wrappedFunction, "name", { value: fn.name });
1781
- Object.defineProperty(wrappedFunction, "length", { value: fn.length });
1782
- return wrappedFunction;
1783
- }
1784
- 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;
1785
- var init_chunk_ZGEMAYS4 = __esm({
1786
- "../../observability/dist/chunk-ZGEMAYS4.mjs"() {
1787
- "use strict";
1788
- init_chunk_NFEGQTCC();
1789
- init_esm();
1790
- init_esm();
1791
- init_esm2();
1792
- init_esm2();
1793
- init_constants = __esm2({
1794
- "src/core/constants.ts"() {
1795
- "use strict";
1796
- OtelSpanAttributes = {
1797
- // OpenInference - re-export all standard conventions
1798
- ...SemanticConventions,
1799
- // AG-Kit Trace attributes (non-standard)
1800
- TRACE_NAME: "trace.name",
1801
- TRACE_TAGS: "trace.tags",
1802
- TRACE_PUBLIC: "trace.public",
1803
- TRACE_METADATA: "trace.metadata",
1804
- TRACE_INPUT: "trace.input",
1805
- TRACE_OUTPUT: "trace.output",
1806
- // AG-Kit Observation attributes (non-standard)
1807
- OBSERVATION_TYPE: "observation.type",
1808
- OBSERVATION_LEVEL: "observation.level",
1809
- OBSERVATION_STATUS_MESSAGE: "observation.status_message",
1810
- OBSERVATION_INPUT: "observation.input",
1811
- OBSERVATION_OUTPUT: "observation.output",
1812
- OBSERVATION_METADATA: "observation.metadata",
1813
- // AG-Kit LLM-specific (non-standard)
1814
- LLM_COMPLETION_START_TIME: "llm.completion_start_time",
1815
- LLM_MODEL_PARAMETERS: "llm.model_parameters",
1816
- LLM_USAGE_DETAILS: "llm.usage_details",
1817
- LLM_COST_DETAILS: "llm.cost_details",
1818
- // AG-Kit Retriever-specific (non-standard)
1819
- RETRIEVER_NAME: "retriever.name",
1820
- RETRIEVER_QUERY: "retriever.query",
1821
- RETRIEVER_INDEX_ID: "retriever.index_id",
1822
- RETRIEVER_TOP_K: "retriever.top_k",
1823
- // AG-Kit General (non-standard)
1824
- ENVIRONMENT: "environment",
1825
- RELEASE: "release",
1826
- VERSION: "version"
1827
- };
1828
- }
1829
- });
1830
- init_attributes = __esm2({
1831
- "src/core/attributes.ts"() {
1832
- "use strict";
1833
- init_constants();
1834
- }
1835
- });
1836
- init_tracerProvider = __esm2({
1837
- "src/core/tracerProvider.ts"() {
1838
- "use strict";
1839
- OBSERVABILITY_GLOBAL_SYMBOL = /* @__PURE__ */ Symbol.for("observability");
1840
- OBSERVABILITY_SDK_NAME = "ag-kit-observability";
1841
- OBSERVABILITY_SDK_VERSION = "0.1.0";
1842
- }
1843
- });
1844
- init_spanWrapper = __esm2({
1845
- "src/core/spanWrapper.ts"() {
1846
- "use strict";
1847
- init_attributes();
1848
- init_tracerProvider();
1849
- BaseObservation = class {
1850
- constructor(params) {
1851
- /** The underlying OpenTelemetry span */
1852
- __publicField(this, "otelSpan");
1853
- /** The observation type */
1854
- __publicField(this, "type");
1855
- /** The span ID from the OpenTelemetry span context */
1856
- __publicField(this, "id");
1857
- /** The trace ID from the OpenTelemetry span context */
1858
- __publicField(this, "traceId");
1859
- this.otelSpan = params.otelSpan;
1860
- this.id = params.otelSpan.spanContext().spanId;
1861
- this.traceId = params.otelSpan.spanContext().traceId;
1862
- this.type = params.type;
1863
- if (params.attributes) {
1864
- this.otelSpan.setAttributes(
1865
- createObservationAttributes(params.type, params.attributes)
1866
- );
1867
- }
1868
- }
1869
- /** Gets the AG-Kit OpenTelemetry tracer instance */
1870
- get tracer() {
1871
- return getTracer();
1872
- }
1873
- /**
1874
- * Ends the observation, marking it as complete.
1875
- *
1876
- * @param endTime - Optional end time, defaults to current time
1877
- */
1878
- end(endTime) {
1879
- this.otelSpan.end(endTime);
1880
- }
1881
- /**
1882
- * Updates the OTEL span attributes.
1883
- *
1884
- * @param attributes - Attributes to update
1885
- * @internal
1886
- */
1887
- updateOtelSpanAttributes(attributes) {
1888
- this.otelSpan.setAttributes(
1889
- createObservationAttributes(this.type, attributes)
1890
- );
1891
- }
1892
- /**
1893
- * Updates the parent trace with new attributes.
1894
- *
1895
- * @param attributes - Trace attributes to set
1896
- * @returns This observation for method chaining
1897
- */
1898
- updateTrace(attributes) {
1899
- this.otelSpan.setAttributes(createTraceAttributes(attributes));
1900
- return this;
1901
- }
1902
- startObservation(name, attributes, options) {
1903
- const { startObservation: startObs } = (init_src(), __toCommonJS2(src_exports));
1904
- const { asType = "span" } = options || {};
1905
- return startObs(name, attributes, {
1906
- asType,
1907
- parentSpanContext: this.otelSpan.spanContext()
1908
- });
1909
- }
1910
- };
1911
- ObservationSpan = class extends BaseObservation {
1912
- constructor(params) {
1913
- super({ ...params, type: "span" });
1914
- }
1915
- update(attributes) {
1916
- super.updateOtelSpanAttributes(attributes);
1917
- return this;
1918
- }
1919
- };
1920
- ObservationLLM = class extends BaseObservation {
1921
- constructor(params) {
1922
- super({ ...params, type: "llm" });
1923
- }
1924
- update(attributes) {
1925
- super.updateOtelSpanAttributes(attributes);
1926
- return this;
1927
- }
1928
- };
1929
- ObservationEmbedding = class extends BaseObservation {
1930
- constructor(params) {
1931
- super({ ...params, type: "embedding" });
1932
- }
1933
- update(attributes) {
1934
- super.updateOtelSpanAttributes(attributes);
1935
- return this;
1936
- }
1937
- };
1938
- ObservationAgent = class extends BaseObservation {
1939
- constructor(params) {
1940
- super({ ...params, type: "agent" });
1941
- }
1942
- update(attributes) {
1943
- super.updateOtelSpanAttributes(attributes);
1944
- return this;
1945
- }
1946
- };
1947
- ObservationTool = class extends BaseObservation {
1948
- constructor(params) {
1949
- super({ ...params, type: "tool" });
1950
- }
1951
- update(attributes) {
1952
- super.updateOtelSpanAttributes(attributes);
1953
- return this;
1954
- }
1955
- };
1956
- ObservationChain = class extends BaseObservation {
1957
- constructor(params) {
1958
- super({ ...params, type: "chain" });
1959
- }
1960
- update(attributes) {
1961
- super.updateOtelSpanAttributes(attributes);
1962
- return this;
1963
- }
1964
- };
1965
- ObservationRetriever = class extends BaseObservation {
1966
- constructor(params) {
1967
- super({ ...params, type: "retriever" });
1968
- }
1969
- update(attributes) {
1970
- super.updateOtelSpanAttributes(attributes);
1971
- return this;
1972
- }
1973
- };
1974
- ObservationReranker = class extends BaseObservation {
1975
- constructor(params) {
1976
- super({ ...params, type: "reranker" });
1977
- }
1978
- update(attributes) {
1979
- super.updateOtelSpanAttributes(attributes);
1980
- return this;
1981
- }
1982
- };
1983
- ObservationEvaluator = class extends BaseObservation {
1984
- constructor(params) {
1985
- super({ ...params, type: "evaluator" });
1986
- }
1987
- update(attributes) {
1988
- super.updateOtelSpanAttributes(attributes);
1989
- return this;
1990
- }
1991
- };
1992
- ObservationGuardrail = class extends BaseObservation {
1993
- constructor(params) {
1994
- super({ ...params, type: "guardrail" });
1995
- }
1996
- update(attributes) {
1997
- super.updateOtelSpanAttributes(attributes);
1998
- return this;
1999
- }
2000
- };
2001
- }
2002
- });
2003
- src_exports = {};
2004
- __export2(src_exports, {
2005
- ObservationAgent: () => ObservationAgent,
2006
- ObservationChain: () => ObservationChain,
2007
- ObservationEmbedding: () => ObservationEmbedding,
2008
- ObservationEvaluator: () => ObservationEvaluator,
2009
- ObservationGuardrail: () => ObservationGuardrail,
2010
- ObservationLLM: () => ObservationLLM,
2011
- ObservationReranker: () => ObservationReranker,
2012
- ObservationRetriever: () => ObservationRetriever,
2013
- ObservationSpan: () => ObservationSpan,
2014
- ObservationTool: () => ObservationTool,
2015
- createObservationAttributes: () => createObservationAttributes,
2016
- createTraceAttributes: () => createTraceAttributes,
2017
- getActiveSpanId: () => getActiveSpanId,
2018
- getActiveTraceId: () => getActiveTraceId,
2019
- getTracer: () => getTracer,
2020
- getTracerProvider: () => getTracerProvider,
2021
- observe: () => observe,
2022
- setTracerProvider: () => setTracerProvider,
2023
- startActiveObservation: () => startActiveObservation,
2024
- startObservation: () => startObservation,
2025
- updateActiveObservation: () => updateActiveObservation,
2026
- updateActiveTrace: () => updateActiveTrace
2027
- });
2028
- init_src = __esm2({
2029
- "src/index.ts"() {
2030
- init_attributes();
2031
- init_spanWrapper();
2032
- init_tracerProvider();
2033
- init_attributes();
2034
- init_tracerProvider();
2035
- }
2036
- });
2037
- }
2038
- });
2039
-
2040
- // ../../observability/dist/langchain.mjs
2041
- var langchain_exports = {};
2042
- __export(langchain_exports, {
2043
- CallbackHandler: () => CallbackHandler
2044
- });
2045
- var import_base, import_messages, import_agent_shared, CallbackHandler;
2046
- var init_langchain = __esm({
2047
- "../../observability/dist/langchain.mjs"() {
2048
- "use strict";
2049
- init_chunk_ZGEMAYS4();
2050
- init_chunk_NFEGQTCC();
2051
- import_base = require("@langchain/core/callbacks/base");
2052
- import_messages = require("@langchain/core/messages");
2053
- import_agent_shared = require("@cloudbase/agent-shared");
2054
- init_src();
2055
- CallbackHandler = class extends import_base.BaseCallbackHandler {
2056
- constructor(params) {
2057
- super();
2058
- __publicField(this, "name", "ObservabilityCallbackHandler");
2059
- __publicField(this, "userId");
2060
- __publicField(this, "version");
2061
- __publicField(this, "sessionId");
2062
- __publicField(this, "tags");
2063
- __publicField(this, "traceMetadata");
2064
- __publicField(this, "completionStartTimes", {});
2065
- __publicField(this, "promptToParentRunMap");
2066
- __publicField(this, "runMap", /* @__PURE__ */ new Map());
2067
- __publicField(this, "last_trace_id", null);
2068
- // External parent context from AG-UI.Server span
2069
- __publicField(this, "externalParentSpanContext");
2070
- // Adapter name for ROOT span prefix
2071
- __publicField(this, "adapterName");
2072
- // Logger for debug output (defaults to noopLogger for silent operation)
2073
- __publicField(this, "logger");
2074
- this.sessionId = params?.sessionId;
2075
- this.userId = params?.userId;
2076
- this.tags = params?.tags ?? [];
2077
- this.traceMetadata = params?.traceMetadata;
2078
- this.version = params?.version;
2079
- this.adapterName = params?.adapterName;
2080
- this.logger = params?.logger ?? import_agent_shared.noopLogger;
2081
- this.promptToParentRunMap = /* @__PURE__ */ new Map();
2082
- }
2083
- /**
2084
- * Set external parent SpanContext from AG-UI.Server span.
2085
- * This allows the CallbackHandler to link LangChain/LangGraph spans
2086
- * to the server-level span, creating a unified trace hierarchy.
2087
- *
2088
- * @param spanContext - SpanContext from the AG-UI.Server span
2089
- * @public
2090
- */
2091
- setExternalParentContext(spanContext) {
2092
- this.externalParentSpanContext = spanContext;
2093
- }
2094
- async handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, _fields) {
2095
- if (runId && !(runId in this.completionStartTimes)) {
2096
- this.logger.debug?.(`LLM first streaming token: ${runId}`);
2097
- this.completionStartTimes[runId] = /* @__PURE__ */ new Date();
2098
- }
2099
- }
2100
- async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
2101
- try {
2102
- this.logger.debug?.(`Chain start with Id: ${runId}`);
2103
- const runName = name ?? chain.id.at(-1)?.toString() ?? "Langchain Run";
2104
- this.registerPromptInfo(parentRunId, metadata);
2105
- let finalInput = inputs;
2106
- if (typeof inputs === "object" && "input" in inputs && Array.isArray(inputs["input"]) && inputs["input"].every((m) => m instanceof import_messages.BaseMessage)) {
2107
- finalInput = inputs["input"].map(
2108
- (m) => this.extractChatMessageContent(m)
2109
- );
2110
- } else if (typeof inputs === "object" && "messages" in inputs && Array.isArray(inputs["messages"]) && inputs["messages"].every((m) => m instanceof import_messages.BaseMessage)) {
2111
- finalInput = inputs["messages"].map(
2112
- (m) => this.extractChatMessageContent(m)
2113
- );
2114
- } else if (typeof inputs === "object" && "content" in inputs && typeof inputs["content"] === "string") {
2115
- finalInput = inputs["content"];
2116
- }
2117
- const observation = this.startAndRegisterObservation({
2118
- runName,
2119
- parentRunId,
2120
- runId,
2121
- tags,
2122
- metadata,
2123
- attributes: {
2124
- input: finalInput
2125
- },
2126
- asType: "span"
2127
- });
2128
- const traceTags = [.../* @__PURE__ */ new Set([...tags ?? [], ...this.tags])];
2129
- if (!parentRunId) {
2130
- observation.updateTrace({
2131
- tags: traceTags,
2132
- userId: metadata && "userId" in metadata && typeof metadata["userId"] === "string" ? metadata["userId"] : this.userId,
2133
- sessionId: metadata && "sessionId" in metadata && typeof metadata["sessionId"] === "string" ? metadata["sessionId"] : this.sessionId,
2134
- metadata: this.traceMetadata,
2135
- version: this.version
2136
- });
2137
- }
2138
- } catch (e) {
2139
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2140
- }
2141
- }
2142
- async handleAgentAction(action, runId, parentRunId) {
2143
- try {
2144
- this.logger.debug?.(`Agent action ${action.tool} with ID: ${runId}`);
2145
- this.startAndRegisterObservation({
2146
- runId,
2147
- parentRunId,
2148
- runName: action.tool,
2149
- attributes: {
2150
- input: action
2151
- },
2152
- asType: "tool"
2153
- });
2154
- } catch (e) {
2155
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2156
- }
2157
- }
2158
- async handleAgentEnd(action, runId, _parentRunId) {
2159
- try {
2160
- this.logger.debug?.(`Agent finish with ID: ${runId}`);
2161
- this.handleObservationEnd({
2162
- runId,
2163
- attributes: { output: action }
2164
- });
2165
- } catch (e) {
2166
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2167
- }
2168
- }
2169
- async handleChainError(err, runId, _parentRunId) {
2170
- try {
2171
- this.logger.debug?.(`Chain error: ${err} with ID: ${runId}`);
2172
- this.handleObservationEnd({
2173
- runId,
2174
- attributes: {
2175
- level: "ERROR",
2176
- statusMessage: err.toString()
2177
- }
2178
- });
2179
- } catch (e) {
2180
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2181
- }
2182
- }
2183
- async handleGenerationStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
2184
- this.logger.debug?.(
2185
- `Generation start with ID: ${runId} and parentRunId ${parentRunId}`
2186
- );
2187
- const runName = name ?? llm.id.at(-1)?.toString() ?? "Langchain Generation";
2188
- const modelParameters = {};
2189
- const invocationParams = extraParams?.["invocation_params"];
2190
- for (const [key, value] of Object.entries({
2191
- temperature: invocationParams?.temperature,
2192
- max_tokens: invocationParams?.max_tokens,
2193
- top_p: invocationParams?.top_p,
2194
- frequency_penalty: invocationParams?.frequency_penalty,
2195
- presence_penalty: invocationParams?.presence_penalty,
2196
- request_timeout: invocationParams?.request_timeout
2197
- })) {
2198
- if (value !== void 0 && value !== null) {
2199
- modelParameters[key] = value;
2200
- }
2201
- }
2202
- let extractedModelName;
2203
- if (extraParams) {
2204
- const invocationParamsModelName = extraParams.invocation_params.model;
2205
- const metadataModelName = metadata && "ls_model_name" in metadata ? metadata["ls_model_name"] : void 0;
2206
- extractedModelName = invocationParamsModelName ?? metadataModelName;
2207
- }
2208
- const registeredPrompt = this.promptToParentRunMap.get(
2209
- parentRunId ?? "root"
2210
- );
2211
- if (registeredPrompt && parentRunId) {
2212
- this.deregisterPromptInfo(parentRunId);
2213
- }
2214
- this.startAndRegisterObservation({
2215
- runId,
2216
- parentRunId,
2217
- metadata,
2218
- tags,
2219
- runName,
2220
- attributes: {
2221
- input: messages,
2222
- model: extractedModelName,
2223
- modelParameters
2224
- },
2225
- asType: "llm"
2226
- });
2227
- }
2228
- async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) {
2229
- try {
2230
- this.logger.debug?.(`Chat model start with ID: ${runId}`);
2231
- const prompts = messages.flatMap(
2232
- (message) => message.map((m) => this.extractChatMessageContent(m))
2233
- );
2234
- this.handleGenerationStart(
2235
- llm,
2236
- prompts,
2237
- runId,
2238
- parentRunId,
2239
- extraParams,
2240
- tags,
2241
- metadata,
2242
- name
2243
- );
2244
- } catch (e) {
2245
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2246
- }
2247
- }
2248
- async handleChainEnd(outputs, runId, _parentRunId) {
2249
- try {
2250
- this.logger.debug?.(`Chain end with ID: ${runId}`);
2251
- let finalOutput = outputs;
2252
- if (typeof outputs === "object" && "output" in outputs && typeof outputs["output"] === "string") {
2253
- finalOutput = outputs["output"];
2254
- } else if (typeof outputs === "object" && "messages" in outputs && Array.isArray(outputs["messages"]) && outputs["messages"].every((m) => m instanceof import_messages.BaseMessage)) {
2255
- finalOutput = {
2256
- messages: outputs.messages.map(
2257
- (message) => this.extractChatMessageContent(message)
2258
- )
2259
- };
2260
- }
2261
- this.handleObservationEnd({
2262
- runId,
2263
- attributes: {
2264
- output: finalOutput
2265
- }
2266
- });
2267
- this.deregisterPromptInfo(runId);
2268
- } catch (e) {
2269
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2270
- }
2271
- }
2272
- async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) {
2273
- try {
2274
- this.logger.debug?.(`LLM start with ID: ${runId}`);
2275
- this.handleGenerationStart(
2276
- llm,
2277
- prompts,
2278
- runId,
2279
- parentRunId,
2280
- extraParams,
2281
- tags,
2282
- metadata,
2283
- name
2284
- );
2285
- } catch (e) {
2286
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2287
- }
2288
- }
2289
- async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) {
2290
- try {
2291
- this.logger.debug?.(`Tool start with ID: ${runId}`);
2292
- this.startAndRegisterObservation({
2293
- runId,
2294
- parentRunId,
2295
- runName: name ?? tool.id.at(-1)?.toString() ?? "Tool execution",
2296
- attributes: {
2297
- input
2298
- },
2299
- metadata,
2300
- tags,
2301
- asType: "tool"
2302
- });
2303
- } catch (e) {
2304
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2305
- }
2306
- }
2307
- async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) {
2308
- try {
2309
- this.logger.debug?.(`Retriever start with ID: ${runId}`);
2310
- this.startAndRegisterObservation({
2311
- runId,
2312
- parentRunId,
2313
- runName: name ?? retriever.id.at(-1)?.toString() ?? "Retriever",
2314
- attributes: {
2315
- input: query
2316
- },
2317
- tags,
2318
- metadata,
2319
- asType: "span"
2320
- });
2321
- } catch (e) {
2322
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2323
- }
2324
- }
2325
- async handleRetrieverEnd(documents, runId, _parentRunId) {
2326
- try {
2327
- this.logger.debug?.(`Retriever end with ID: ${runId}`);
2328
- this.handleObservationEnd({
2329
- runId,
2330
- attributes: {
2331
- output: documents
2332
- }
2333
- });
2334
- } catch (e) {
2335
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2336
- }
2337
- }
2338
- async handleRetrieverError(err, runId, _parentRunId) {
2339
- try {
2340
- this.logger.debug?.(`Retriever error: ${err} with ID: ${runId}`);
2341
- this.handleObservationEnd({
2342
- runId,
2343
- attributes: {
2344
- level: "ERROR",
2345
- statusMessage: err.toString()
2346
- }
2347
- });
2348
- } catch (e) {
2349
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2350
- }
2351
- }
2352
- async handleToolEnd(output, runId, _parentRunId) {
2353
- try {
2354
- this.logger.debug?.(`Tool end with ID: ${runId}`);
2355
- this.handleObservationEnd({
2356
- runId,
2357
- attributes: { output }
2358
- });
2359
- } catch (e) {
2360
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2361
- }
2362
- }
2363
- async handleToolError(err, runId, _parentRunId) {
2364
- try {
2365
- this.logger.debug?.(`Tool error ${err} with ID: ${runId}`);
2366
- this.handleObservationEnd({
2367
- runId,
2368
- attributes: {
2369
- level: "ERROR",
2370
- statusMessage: err.toString()
2371
- }
2372
- });
2373
- } catch (e) {
2374
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2375
- }
2376
- }
2377
- async handleLLMEnd(output, runId, _parentRunId) {
2378
- try {
2379
- this.logger.debug?.(`LLM end with ID: ${runId}`);
2380
- const lastResponse = output.generations[output.generations.length - 1][output.generations[output.generations.length - 1].length - 1];
2381
- const llmUsage = this.extractUsageMetadata(lastResponse) ?? output.llmOutput?.["tokenUsage"];
2382
- const modelName = this.extractModelNameFromMetadata(lastResponse);
2383
- const usageDetails = {
2384
- input: llmUsage?.input_tokens ?? ("promptTokens" in llmUsage ? llmUsage?.promptTokens : void 0),
2385
- output: llmUsage?.output_tokens ?? ("completionTokens" in llmUsage ? llmUsage?.completionTokens : void 0),
2386
- total: llmUsage?.total_tokens ?? ("totalTokens" in llmUsage ? llmUsage?.totalTokens : void 0)
2387
- };
2388
- if (llmUsage && "input_token_details" in llmUsage) {
2389
- for (const [key, val] of Object.entries(
2390
- llmUsage["input_token_details"] ?? {}
2391
- )) {
2392
- usageDetails[`input_${key}`] = val;
2393
- if ("input" in usageDetails && typeof val === "number") {
2394
- usageDetails["input"] = Math.max(0, usageDetails["input"] - val);
2395
- }
2396
- }
2397
- }
2398
- if (llmUsage && "output_token_details" in llmUsage) {
2399
- for (const [key, val] of Object.entries(
2400
- llmUsage["output_token_details"] ?? {}
2401
- )) {
2402
- usageDetails[`output_${key}`] = val;
2403
- if ("output" in usageDetails && typeof val === "number") {
2404
- usageDetails["output"] = Math.max(0, usageDetails["output"] - val);
2405
- }
2406
- }
2407
- }
2408
- const extractedOutput = "message" in lastResponse ? this.extractChatMessageContent(
2409
- lastResponse["message"]
2410
- ) : lastResponse.text;
2411
- this.handleObservationEnd({
2412
- runId,
2413
- attributes: {
2414
- model: modelName,
2415
- output: extractedOutput,
2416
- completionStartTime: runId in this.completionStartTimes ? this.completionStartTimes[runId] : void 0,
2417
- usageDetails
2418
- }
2419
- });
2420
- if (runId in this.completionStartTimes) {
2421
- delete this.completionStartTimes[runId];
2422
- }
2423
- } catch (e) {
2424
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2425
- }
2426
- }
2427
- async handleLLMError(err, runId, _parentRunId) {
2428
- try {
2429
- this.logger.debug?.(`LLM error ${err} with ID: ${runId}`);
2430
- this.handleObservationEnd({
2431
- runId,
2432
- attributes: {
2433
- level: "ERROR",
2434
- statusMessage: err.toString()
2435
- }
2436
- });
2437
- } catch (e) {
2438
- this.logger.debug?.(e instanceof Error ? e.message : String(e));
2439
- }
2440
- }
2441
- registerPromptInfo(parentRunId, metadata) {
2442
- if (metadata && "promptInfo" in metadata && parentRunId) {
2443
- this.promptToParentRunMap.set(
2444
- parentRunId,
2445
- metadata.promptInfo
2446
- );
2447
- }
2448
- }
2449
- deregisterPromptInfo(runId) {
2450
- this.promptToParentRunMap.delete(runId);
2451
- }
2452
- startAndRegisterObservation(params) {
2453
- const { runName, runId, parentRunId, attributes, metadata, tags, asType } = params;
2454
- let parentSpanContext;
2455
- if (parentRunId) {
2456
- parentSpanContext = this.runMap.get(parentRunId)?.otelSpan.spanContext();
2457
- } else if (this.externalParentSpanContext) {
2458
- parentSpanContext = this.externalParentSpanContext;
2459
- }
2460
- let finalRunName = runName;
2461
- if (!parentRunId && this.adapterName) {
2462
- finalRunName = `Adapter.${this.adapterName}`;
2463
- }
2464
- const observation = startObservation(
2465
- finalRunName,
2466
- {
2467
- version: this.version,
2468
- metadata: this.joinTagsAndMetaData(tags, metadata),
2469
- ...attributes
2470
- },
2471
- {
2472
- asType: asType ?? "span",
2473
- parentSpanContext
2474
- }
2475
- );
2476
- this.runMap.set(runId, observation);
2477
- return observation;
2478
- }
2479
- handleObservationEnd(params) {
2480
- const { runId, attributes = {} } = params;
2481
- const observation = this.runMap.get(runId);
2482
- if (!observation) {
2483
- this.logger.warn?.("Observation not found in runMap. Skipping operation.");
2484
- return;
2485
- }
2486
- observation.update(attributes).end();
2487
- this.last_trace_id = observation.traceId;
2488
- this.runMap.delete(runId);
2489
- }
2490
- joinTagsAndMetaData(tags, metadata1, metadata2) {
2491
- const finalDict = {};
2492
- if (tags && tags.length > 0) {
2493
- finalDict.tags = tags;
2494
- }
2495
- if (metadata1) {
2496
- Object.assign(finalDict, metadata1);
2497
- }
2498
- if (metadata2) {
2499
- Object.assign(finalDict, metadata2);
2500
- }
2501
- return this.stripObservabilityKeysFromMetadata(finalDict);
2502
- }
2503
- stripObservabilityKeysFromMetadata(metadata) {
2504
- if (!metadata) {
2505
- return;
2506
- }
2507
- const reservedKeys = ["promptInfo", "userId", "sessionId"];
2508
- return Object.fromEntries(
2509
- Object.entries(metadata).filter(([key, _]) => !reservedKeys.includes(key))
2510
- );
2511
- }
2512
- extractUsageMetadata(generation) {
2513
- try {
2514
- const usageMetadata = "message" in generation && (import_messages.AIMessage.isInstance(generation["message"]) || import_messages.AIMessageChunk.isInstance(generation["message"])) ? generation["message"].usage_metadata : void 0;
2515
- return usageMetadata;
2516
- } catch (err) {
2517
- this.logger.debug?.(`Error extracting usage metadata: ${err}`);
2518
- return;
2519
- }
2520
- }
2521
- extractModelNameFromMetadata(generation) {
2522
- try {
2523
- return "message" in generation && (import_messages.AIMessage.isInstance(generation["message"]) || import_messages.AIMessageChunk.isInstance(generation["message"])) ? generation["message"].response_metadata.model_name : void 0;
2524
- } catch {
2525
- }
2526
- }
2527
- extractChatMessageContent(message) {
2528
- let response = void 0;
2529
- if (message.getType() === "human") {
2530
- response = { content: message.content, role: "user" };
2531
- } else if (message.getType() === "generic") {
2532
- response = {
2533
- content: message.content,
2534
- role: "human"
2535
- };
2536
- } else if (message.getType() === "ai") {
2537
- response = { content: message.content, role: "assistant" };
2538
- if ("tool_calls" in message && Array.isArray(message.tool_calls) && (message.tool_calls?.length ?? 0) > 0) {
2539
- response["tool_calls"] = message["tool_calls"];
2540
- }
2541
- if ("additional_kwargs" in message && "tool_calls" in message["additional_kwargs"]) {
2542
- response["tool_calls"] = message["additional_kwargs"]["tool_calls"];
2543
- }
2544
- } else if (message.getType() === "system") {
2545
- response = { content: message.content, role: "system" };
2546
- } else if (message.getType() === "function") {
2547
- response = {
2548
- content: message.content,
2549
- additional_kwargs: message.additional_kwargs,
2550
- role: message.name
2551
- };
2552
- } else if (message.getType() === "tool") {
2553
- response = {
2554
- content: message.content,
2555
- additional_kwargs: message.additional_kwargs,
2556
- role: message.name
2557
- };
2558
- } else if (!message.name) {
2559
- response = { content: message.content };
2560
- } else {
2561
- response = {
2562
- role: message.name,
2563
- content: message.content
2564
- };
2565
- }
2566
- if ((message.additional_kwargs.function_call || message.additional_kwargs.tool_calls) && response["tool_calls"] === void 0) {
2567
- return { ...response, additional_kwargs: message.additional_kwargs };
2568
- }
2569
- return response;
2570
- }
2571
- };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2572
17
  }
2573
- });
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
2574
29
 
2575
30
  // src/index.ts
2576
31
  var index_exports = {};
2577
32
  __export(index_exports, {
2578
33
  ClientPropertiesAnnotation: () => ClientPropertiesAnnotation,
2579
34
  ClientStateAnnotation: () => ClientStateAnnotation,
35
+ CloudBaseSaver: () => CloudBaseSaver,
2580
36
  LanggraphAgent: () => LanggraphAgent,
2581
37
  TDAISaver: () => TDAISaver,
2582
38
  TDAIStore: () => TDAIStore,
2583
- createConsoleLogger: () => import_agent_shared3.createConsoleLogger,
2584
- noopLogger: () => import_agent_shared3.noopLogger
39
+ createConsoleLogger: () => import_agent_shared2.createConsoleLogger,
40
+ noopLogger: () => import_agent_shared2.noopLogger
2585
41
  });
2586
42
  module.exports = __toCommonJS(index_exports);
2587
43
 
@@ -2638,9 +94,8 @@ function convertJsonSchemaToZodSchema(jsonSchema, required) {
2638
94
  }
2639
95
 
2640
96
  // src/agent.ts
2641
- var import_agent_shared2 = require("@cloudbase/agent-shared");
97
+ var import_agent_shared = require("@cloudbase/agent-shared");
2642
98
  var LangChainCallbackHandler;
2643
- var observabilityLoadAttempted = false;
2644
99
  var ClientPropertiesAnnotation = import_langgraph.Annotation.Root({
2645
100
  tools: import_langgraph.Annotation
2646
101
  });
@@ -2653,7 +108,7 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2653
108
  super(agentConfig);
2654
109
  this.compiledWorkflow = agentConfig.compiledWorkflow;
2655
110
  this.adapterName = agentConfig.adapterName || "LangGraph";
2656
- const baseLogger = agentConfig.logger ?? import_agent_shared2.noopLogger;
111
+ const baseLogger = agentConfig.logger ?? import_agent_shared.noopLogger;
2657
112
  this.logger = baseLogger.child?.({ component: "langgraph-agent" }) ?? baseLogger;
2658
113
  }
2659
114
  run(input) {
@@ -2665,45 +120,7 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2665
120
  const { messages, runId, threadId } = input;
2666
121
  const logger = this.logger.child?.({ runId, threadId }) ?? this.logger;
2667
122
  logger.info?.("Run started");
2668
- if (!observabilityLoadAttempted && !this.observabilityCallback) {
2669
- observabilityLoadAttempted = true;
2670
- try {
2671
- logger.debug?.("Attempting to load observability...");
2672
- const obsModule = await Promise.resolve().then(() => (init_langchain(), langchain_exports));
2673
- LangChainCallbackHandler = obsModule.CallbackHandler;
2674
- if (LangChainCallbackHandler) {
2675
- this.observabilityCallback = new LangChainCallbackHandler({
2676
- adapterName: this.adapterName,
2677
- logger
2678
- // Reuse the run-specific logger with context
2679
- });
2680
- logger.debug?.("\u2713 Observability callback created");
2681
- }
2682
- } catch (e) {
2683
- logger.debug?.(
2684
- "\u2717 Observability not available:",
2685
- e instanceof Error ? e.message : String(e)
2686
- );
2687
- }
2688
- }
2689
- if (this.observabilityCallback && input.forwardedProps?.__agui_server_context) {
2690
- try {
2691
- const serverContextData = input.forwardedProps.__agui_server_context;
2692
- const serverSpanContext = {
2693
- traceId: serverContextData.traceId,
2694
- spanId: serverContextData.spanId,
2695
- traceFlags: serverContextData.traceFlags,
2696
- isRemote: false
2697
- };
2698
- this.observabilityCallback.setExternalParentContext(serverSpanContext);
2699
- logger.debug?.("\u2713 Server context restored:", {
2700
- traceId: serverSpanContext.traceId,
2701
- spanId: serverSpanContext.spanId
2702
- });
2703
- } catch (e) {
2704
- logger.debug?.("Failed to restore server context:", e);
2705
- }
2706
- }
123
+ await this.setupObservability(input, logger);
2707
124
  const runStartedEvent = {
2708
125
  type: import_client.EventType.RUN_STARTED,
2709
126
  threadId,
@@ -2711,11 +128,9 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2711
128
  };
2712
129
  logger.trace?.({ aguiEvent: runStartedEvent }, "Emitting AGUI event");
2713
130
  subscriber.next(runStartedEvent);
2714
- const isResume = !!input.forwardedProps?.resume;
2715
131
  const lastUserMessage = messages.filter((m) => m.role === "user").pop();
2716
132
  logger.debug?.(
2717
133
  {
2718
- isResume,
2719
134
  messageCount: messages.length,
2720
135
  toolCount: input.tools?.length ?? 0,
2721
136
  tools: input.tools?.map((t) => t.name),
@@ -2724,25 +139,21 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2724
139
  "Preparing stream input"
2725
140
  );
2726
141
  logger.trace?.({ messages, tools: input.tools }, "Full input messages");
2727
- const langChainMessages = isResume ? void 0 : aguiMessagesToLangChain(messages);
2728
- if (langChainMessages) {
2729
- logger.trace?.(
2730
- {
2731
- langChainMessages,
2732
- messageCount: langChainMessages.length,
2733
- messageTypes: langChainMessages.map((m) => ({
2734
- type: m.type,
2735
- id: m.id,
2736
- hasToolCalls: "tool_calls" in m && Array.isArray(m.tool_calls) && m.tool_calls.length > 0,
2737
- toolCallId: "tool_call_id" in m ? m.tool_call_id : void 0
2738
- }))
2739
- },
2740
- "Converted LangGraph messages"
2741
- );
2742
- }
2743
- const streamEventInput = isResume ? new import_langgraph.Command({
2744
- resume: JSON.stringify(input.forwardedProps?.resume?.payload)
2745
- }) : {
142
+ const langChainMessages = aguiMessagesToLangChain(messages, logger);
143
+ logger.trace?.(
144
+ {
145
+ langChainMessages,
146
+ messageCount: langChainMessages.length,
147
+ messageTypes: langChainMessages.map((m) => ({
148
+ type: m.type,
149
+ id: m.id,
150
+ hasToolCalls: "tool_calls" in m && Array.isArray(m.tool_calls) && m.tool_calls.length > 0,
151
+ toolCallId: "tool_call_id" in m ? m.tool_call_id : void 0
152
+ }))
153
+ },
154
+ "Converted LangGraph messages"
155
+ );
156
+ const streamEventInput = {
2746
157
  messages: langChainMessages,
2747
158
  client: {
2748
159
  tools: convertActionsToDynamicStructuredTools(
@@ -2775,7 +186,6 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
2775
186
  "Pre-populated handled tool call IDs from input messages"
2776
187
  );
2777
188
  }
2778
- let interrupt;
2779
189
  let currentToolCall = null;
2780
190
  let eventCount = 0;
2781
191
  let toolCallCount = 0;
@@ -3100,52 +510,23 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
3100
510
  "State update with messages"
3101
511
  );
3102
512
  }
3103
- if (chunk?.__interrupt__ && Array.isArray(chunk.__interrupt__) && chunk.__interrupt__.length > 0) {
3104
- const rawInterrupt = chunk.__interrupt__[0];
3105
- logger.debug?.(
3106
- { interruptId: rawInterrupt.id },
3107
- "Interrupt received"
3108
- );
3109
- interrupt = {
3110
- id: rawInterrupt.id,
3111
- // TODO: replace with actual reason
3112
- reason: "agent requested interrupt",
3113
- payload: rawInterrupt.value
3114
- };
3115
- }
3116
513
  }
3117
514
  }
3118
515
  const stats = { eventCount, toolCallCount, textChunkCount };
3119
- if (interrupt) {
3120
- const runFinishedEvent = {
3121
- type: import_client.EventType.RUN_FINISHED,
3122
- threadId,
3123
- runId,
3124
- outcome: "interrupt",
3125
- interrupt
3126
- };
3127
- logger.info?.(
3128
- { outcome: "interrupt", interruptId: interrupt.id, ...stats },
3129
- "Run finished with interrupt"
3130
- );
3131
- logger.trace?.({ aguiEvent: runFinishedEvent }, "Emitting AGUI event");
3132
- subscriber.next(runFinishedEvent);
3133
- } else {
3134
- const runFinishedEvent = {
3135
- type: import_client.EventType.RUN_FINISHED,
3136
- threadId,
3137
- runId
3138
- };
3139
- logger.info?.({ outcome: "complete", ...stats }, "Run finished");
3140
- logger.trace?.({ aguiEvent: runFinishedEvent }, "Emitting AGUI event");
3141
- subscriber.next(runFinishedEvent);
3142
- }
516
+ const runFinishedEvent = {
517
+ type: import_client.EventType.RUN_FINISHED,
518
+ threadId,
519
+ runId
520
+ };
521
+ logger.info?.({ outcome: "complete", ...stats }, "Run finished");
522
+ logger.trace?.({ aguiEvent: runFinishedEvent }, "Emitting AGUI event");
523
+ subscriber.next(runFinishedEvent);
3143
524
  } catch (error) {
3144
525
  logger.error?.(
3145
526
  { err: error, eventCount, toolCallCount, textChunkCount },
3146
527
  "Error during stream processing"
3147
528
  );
3148
- const errorCode = (0, import_agent_shared2.isErrorWithCode)(error) ? error.code : "INTERNAL_ERROR";
529
+ const errorCode = (0, import_agent_shared.isErrorWithCode)(error) ? error.code : "INTERNAL_ERROR";
3149
530
  const errorMessage = error instanceof Error ? error.message : String(error);
3150
531
  subscriber.next({
3151
532
  type: import_client.EventType.RUN_ERROR,
@@ -3165,9 +546,56 @@ var LanggraphAgent = class extends import_client.AbstractAgent {
3165
546
  cloned.logger = logger;
3166
547
  return cloned;
3167
548
  }
549
+ /**
550
+ * Setup observability for agent execution.
551
+ * Lazy loads observability callback, restores server context from forwardedProps,
552
+ * and configures the callback for graph execution.
553
+ */
554
+ async setupObservability(input, logger) {
555
+ if (!LangChainCallbackHandler) {
556
+ try {
557
+ logger.debug?.("Attempting to load observability...");
558
+ const obsModule = await import("@cloudbase/agent-observability/langchain");
559
+ LangChainCallbackHandler = obsModule.CallbackHandler;
560
+ logger.debug?.("\u2713 Observability handler loaded");
561
+ } catch (e) {
562
+ logger.debug?.(
563
+ "\u2717 Observability not available:",
564
+ e instanceof Error ? e.message : String(e)
565
+ );
566
+ }
567
+ }
568
+ this.observabilityCallback = LangChainCallbackHandler ? new LangChainCallbackHandler({
569
+ adapterName: this.adapterName,
570
+ logger
571
+ }) : void 0;
572
+ if (this.observabilityCallback && input.forwardedProps?.__agui_server_context) {
573
+ try {
574
+ const serverContextData = input.forwardedProps.__agui_server_context;
575
+ const serverSpanContext = {
576
+ traceId: serverContextData.traceId,
577
+ spanId: serverContextData.spanId,
578
+ traceFlags: serverContextData.traceFlags,
579
+ isRemote: false
580
+ };
581
+ this.observabilityCallback.setExternalParentContext(serverSpanContext, {
582
+ threadId: input.threadId,
583
+ runId: input.runId
584
+ });
585
+ logger.debug?.("\u2713 Server context restored:", {
586
+ traceId: serverSpanContext.traceId,
587
+ spanId: serverSpanContext.spanId,
588
+ threadId: input.threadId,
589
+ runId: input.runId
590
+ });
591
+ } catch (e) {
592
+ logger.debug?.("Failed to restore server context:", e);
593
+ }
594
+ }
595
+ }
3168
596
  };
3169
- function aguiMessagesToLangChain(messages) {
3170
- return messages.map((message, index) => {
597
+ function aguiMessagesToLangChain(messages, logger) {
598
+ return messages.map((message) => {
3171
599
  switch (message.role) {
3172
600
  case "user":
3173
601
  if (typeof message.content === "string") {
@@ -3178,10 +606,34 @@ function aguiMessagesToLangChain(messages) {
3178
606
  type: "human"
3179
607
  };
3180
608
  } else {
609
+ const langChainContent = [];
610
+ for (const part of message.content) {
611
+ if (part.type === "text") {
612
+ langChainContent.push({ type: "text", text: part.text });
613
+ } else if (part.type === "binary") {
614
+ const imageUrl = convertBinaryToImageUrl(
615
+ part,
616
+ message.id,
617
+ logger
618
+ );
619
+ if (imageUrl) {
620
+ langChainContent.push({
621
+ type: "image_url",
622
+ image_url: { url: imageUrl }
623
+ });
624
+ }
625
+ }
626
+ }
627
+ if (langChainContent.length === 0) {
628
+ logger?.warn?.(
629
+ { messageId: message.id },
630
+ "User message content array resulted in empty LangChain content"
631
+ );
632
+ }
3181
633
  return {
3182
634
  id: message.id,
3183
635
  role: message.role,
3184
- content: message.content.filter((m) => m.type === "text"),
636
+ content: langChainContent,
3185
637
  type: "human"
3186
638
  };
3187
639
  }
@@ -3226,6 +678,22 @@ function isValidJson(json) {
3226
678
  return false;
3227
679
  }
3228
680
  }
681
+ function convertBinaryToImageUrl(part, messageId, logger) {
682
+ if (!part.mimeType.startsWith("image/")) {
683
+ logger?.debug?.(
684
+ { mimeType: part.mimeType, messageId },
685
+ "Skipping non-image binary content"
686
+ );
687
+ return void 0;
688
+ }
689
+ if (part.url) {
690
+ return part.url;
691
+ }
692
+ if (part.data) {
693
+ return `data:${part.mimeType};base64,${part.data}`;
694
+ }
695
+ return void 0;
696
+ }
3229
697
 
3230
698
  // src/checkpoint.ts
3231
699
  var import_langgraph2 = require("@langchain/langgraph");
@@ -3477,9 +945,364 @@ var TDAISaver = class extends import_langgraph2.BaseCheckpointSaver {
3477
945
  }
3478
946
  };
3479
947
 
3480
- // src/store/tdai-store.ts
948
+ // src/cloudbase-saver.ts
3481
949
  var import_langgraph3 = require("@langchain/langgraph");
3482
- var TDAIStore = class extends import_langgraph3.BaseStore {
950
+
951
+ // ../../../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
952
+ var ERROR = "__error__";
953
+ var SCHEDULED = "__scheduled__";
954
+ var INTERRUPT = "__interrupt__";
955
+ var RESUME = "__resume__";
956
+
957
+ // ../../../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
958
+ var import_load = require("@langchain/core/load");
959
+
960
+ // ../../../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
961
+ function deepCopy(obj) {
962
+ if (typeof obj !== "object" || obj === null) return obj;
963
+ const newObj = Array.isArray(obj) ? [] : {};
964
+ for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]);
965
+ return newObj;
966
+ }
967
+ function copyCheckpoint(checkpoint) {
968
+ return {
969
+ v: checkpoint.v,
970
+ id: checkpoint.id,
971
+ ts: checkpoint.ts,
972
+ channel_values: { ...checkpoint.channel_values },
973
+ channel_versions: { ...checkpoint.channel_versions },
974
+ versions_seen: deepCopy(checkpoint.versions_seen)
975
+ };
976
+ }
977
+ var WRITES_IDX_MAP = {
978
+ [ERROR]: -1,
979
+ [SCHEDULED]: -2,
980
+ [INTERRUPT]: -3,
981
+ [RESUME]: -4
982
+ };
983
+
984
+ // src/cloudbase-saver.ts
985
+ var CloudBaseSaver = class extends import_langgraph3.BaseCheckpointSaver {
986
+ constructor(config) {
987
+ super();
988
+ this.db = config.db;
989
+ this.userId = config.userId;
990
+ this.agentId = config.agentId ?? "default";
991
+ this.checkpointsCollection = config.checkpointsCollection ?? "checkpoints";
992
+ this.writesCollection = config.writesCollection ?? "checkpoint_writes";
993
+ }
994
+ /**
995
+ * Setup the required collections in CloudBase.
996
+ * Call this once before using the saver. Safe to call multiple times.
997
+ */
998
+ async setup() {
999
+ const createIfNotExists = async (name) => {
1000
+ try {
1001
+ await this.db.createCollection(name);
1002
+ } catch (e) {
1003
+ const error = e;
1004
+ if (error.code !== "DATABASE_COLLECTION_ALREADY_EXIST") {
1005
+ throw e;
1006
+ }
1007
+ }
1008
+ };
1009
+ await Promise.all([
1010
+ createIfNotExists(this.checkpointsCollection),
1011
+ createIfNotExists(this.writesCollection)
1012
+ ]);
1013
+ }
1014
+ /**
1015
+ * Serialize data to JSON object using serde.
1016
+ * CloudBase is a document database, so we store JSON directly instead of Base64.
1017
+ * Binary data (Uint8Array) is not supported - fail early if encountered.
1018
+ */
1019
+ async serialize(data) {
1020
+ const [type, bytes] = await this.serde.dumpsTyped(data);
1021
+ if (type === "bytes") {
1022
+ throw new Error(
1023
+ "Binary data (Uint8Array) is not supported in CloudBaseSaver. CloudBase is a document database that only supports JSON-serializable data."
1024
+ );
1025
+ }
1026
+ const jsonString = new TextDecoder().decode(bytes);
1027
+ return JSON.parse(jsonString);
1028
+ }
1029
+ /**
1030
+ * Deserialize JSON object back to data using serde.
1031
+ */
1032
+ async deserialize(data) {
1033
+ const jsonString = JSON.stringify(data);
1034
+ const bytes = new TextEncoder().encode(jsonString);
1035
+ return this.serde.loadsTyped("json", bytes);
1036
+ }
1037
+ /**
1038
+ * Retrieves a checkpoint from CloudBase based on the provided config.
1039
+ */
1040
+ async getTuple(config) {
1041
+ const {
1042
+ thread_id,
1043
+ checkpoint_ns = "",
1044
+ checkpoint_id
1045
+ } = config.configurable ?? {};
1046
+ if (!thread_id) {
1047
+ return void 0;
1048
+ }
1049
+ const query = {
1050
+ _openid: this.userId,
1051
+ agent_id: this.agentId,
1052
+ thread_id,
1053
+ checkpoint_ns
1054
+ };
1055
+ if (checkpoint_id) {
1056
+ query.checkpoint_id = checkpoint_id;
1057
+ }
1058
+ const { data: docs } = await this.db.collection(this.checkpointsCollection).where(query).orderBy("checkpoint_id", "desc").limit(1).get();
1059
+ if (docs.length === 0) {
1060
+ return void 0;
1061
+ }
1062
+ const doc = docs[0];
1063
+ const checkpointId = doc.checkpoint_id;
1064
+ const checkpoint = await this.deserialize(doc.checkpoint);
1065
+ const metadata = await this.deserialize(
1066
+ doc.metadata
1067
+ );
1068
+ const writeDocs = [];
1069
+ let writeSkip = 0;
1070
+ const writePageSize = 100;
1071
+ while (true) {
1072
+ const { data: docs2 } = await this.db.collection(this.writesCollection).where({
1073
+ _openid: this.userId,
1074
+ agent_id: this.agentId,
1075
+ thread_id,
1076
+ checkpoint_ns,
1077
+ checkpoint_id: checkpointId
1078
+ }).orderBy("idx", "asc").skip(writeSkip).limit(writePageSize).get();
1079
+ writeDocs.push(...docs2);
1080
+ if (docs2.length < writePageSize) break;
1081
+ writeSkip += docs2.length;
1082
+ }
1083
+ const pendingWrites = await Promise.all(
1084
+ writeDocs.map(async (writeDoc) => {
1085
+ const value = await this.deserialize(writeDoc.value);
1086
+ return [
1087
+ writeDoc.task_id,
1088
+ writeDoc.channel,
1089
+ value
1090
+ ];
1091
+ })
1092
+ );
1093
+ return {
1094
+ config: {
1095
+ configurable: {
1096
+ thread_id,
1097
+ checkpoint_ns,
1098
+ checkpoint_id: checkpointId
1099
+ }
1100
+ },
1101
+ checkpoint,
1102
+ metadata,
1103
+ pendingWrites,
1104
+ parentConfig: doc.parent_checkpoint_id ? {
1105
+ configurable: {
1106
+ thread_id,
1107
+ checkpoint_ns,
1108
+ checkpoint_id: doc.parent_checkpoint_id
1109
+ }
1110
+ } : void 0
1111
+ };
1112
+ }
1113
+ /**
1114
+ * List checkpoints from CloudBase, ordered by checkpoint_id descending.
1115
+ */
1116
+ async *list(config, options) {
1117
+ const { limit, before, filter } = options ?? {};
1118
+ const thread_id = config.configurable?.thread_id;
1119
+ const checkpoint_ns = config.configurable?.checkpoint_ns;
1120
+ if (!thread_id) {
1121
+ throw new Error("Thread ID is required");
1122
+ }
1123
+ const _ = this.db.command;
1124
+ const query = {
1125
+ _openid: this.userId,
1126
+ agent_id: this.agentId,
1127
+ thread_id
1128
+ };
1129
+ if (checkpoint_ns !== void 0 && checkpoint_ns !== null) {
1130
+ query.checkpoint_ns = checkpoint_ns;
1131
+ }
1132
+ if (before?.configurable?.checkpoint_id) {
1133
+ query.checkpoint_id = _.lt(before.configurable.checkpoint_id);
1134
+ }
1135
+ const validCheckpointMetadataKeys = ["source", "step", "writes", "parents"];
1136
+ if (filter) {
1137
+ for (const [key, value] of Object.entries(filter)) {
1138
+ if (value !== void 0 && validCheckpointMetadataKeys.includes(key)) {
1139
+ query[`metadata.${key}`] = value;
1140
+ }
1141
+ }
1142
+ }
1143
+ let skip = 0;
1144
+ const pageSize = Math.min(limit ?? 100, 100);
1145
+ let yielded = 0;
1146
+ while (true) {
1147
+ const { data: docs } = await this.db.collection(this.checkpointsCollection).where(query).orderBy("checkpoint_id", "desc").skip(skip).limit(pageSize).get();
1148
+ if (docs.length === 0) break;
1149
+ for (const doc of docs) {
1150
+ const checkpoint = await this.deserialize(
1151
+ doc.checkpoint
1152
+ );
1153
+ const metadata = await this.deserialize(
1154
+ doc.metadata
1155
+ );
1156
+ const writeDocs = [];
1157
+ let writeSkip = 0;
1158
+ const writePageSize = 100;
1159
+ while (true) {
1160
+ const { data: pageWriteDocs } = await this.db.collection(this.writesCollection).where({
1161
+ _openid: this.userId,
1162
+ agent_id: this.agentId,
1163
+ thread_id: doc.thread_id,
1164
+ checkpoint_ns: doc.checkpoint_ns,
1165
+ checkpoint_id: doc.checkpoint_id
1166
+ }).orderBy("idx", "asc").skip(writeSkip).limit(writePageSize).get();
1167
+ writeDocs.push(...pageWriteDocs);
1168
+ if (pageWriteDocs.length < writePageSize) break;
1169
+ writeSkip += pageWriteDocs.length;
1170
+ }
1171
+ const pendingWrites = await Promise.all(
1172
+ writeDocs.map(async (writeDoc) => {
1173
+ const value = await this.deserialize(writeDoc.value);
1174
+ return [
1175
+ writeDoc.task_id,
1176
+ writeDoc.channel,
1177
+ value
1178
+ ];
1179
+ })
1180
+ );
1181
+ yield {
1182
+ config: {
1183
+ configurable: {
1184
+ thread_id: doc.thread_id,
1185
+ checkpoint_ns: doc.checkpoint_ns,
1186
+ checkpoint_id: doc.checkpoint_id
1187
+ }
1188
+ },
1189
+ checkpoint,
1190
+ metadata,
1191
+ pendingWrites,
1192
+ parentConfig: doc.parent_checkpoint_id ? {
1193
+ configurable: {
1194
+ thread_id: doc.thread_id,
1195
+ checkpoint_ns: doc.checkpoint_ns,
1196
+ checkpoint_id: doc.parent_checkpoint_id
1197
+ }
1198
+ } : void 0
1199
+ };
1200
+ yielded++;
1201
+ if (limit && yielded >= limit) return;
1202
+ }
1203
+ skip += docs.length;
1204
+ if (docs.length < pageSize) break;
1205
+ }
1206
+ }
1207
+ /**
1208
+ * Save a checkpoint to CloudBase.
1209
+ */
1210
+ async put(config, checkpoint, metadata) {
1211
+ if (!config.configurable) {
1212
+ throw new Error("Empty configuration supplied.");
1213
+ }
1214
+ const thread_id = config.configurable.thread_id;
1215
+ const checkpoint_ns = config.configurable.checkpoint_ns ?? "";
1216
+ const checkpoint_id = checkpoint.id;
1217
+ if (!thread_id) {
1218
+ throw new Error(
1219
+ 'Missing "thread_id" field in passed "config.configurable".'
1220
+ );
1221
+ }
1222
+ const preparedCheckpoint = copyCheckpoint(checkpoint);
1223
+ const serializedCheckpoint = await this.serialize(preparedCheckpoint);
1224
+ const serializedMetadata = await this.serialize(metadata);
1225
+ const doc = {
1226
+ _openid: this.userId,
1227
+ agent_id: this.agentId,
1228
+ thread_id,
1229
+ checkpoint_ns,
1230
+ checkpoint_id,
1231
+ parent_checkpoint_id: config.configurable.checkpoint_id ?? null,
1232
+ checkpoint: serializedCheckpoint,
1233
+ metadata: serializedMetadata,
1234
+ created_at: /* @__PURE__ */ new Date()
1235
+ };
1236
+ const docId = `${this.agentId}:${thread_id}:${checkpoint_ns}:${checkpoint_id}`;
1237
+ await this.db.collection(this.checkpointsCollection).doc(docId).set(doc);
1238
+ return {
1239
+ configurable: {
1240
+ thread_id,
1241
+ checkpoint_ns,
1242
+ checkpoint_id
1243
+ }
1244
+ };
1245
+ }
1246
+ /**
1247
+ * Save intermediate writes to CloudBase.
1248
+ */
1249
+ async putWrites(config, writes, taskId) {
1250
+ if (!config.configurable) {
1251
+ throw new Error("Empty configuration supplied.");
1252
+ }
1253
+ if (!config.configurable.thread_id) {
1254
+ throw new Error("Missing thread_id field in config.configurable.");
1255
+ }
1256
+ if (!config.configurable.checkpoint_id) {
1257
+ throw new Error("Missing checkpoint_id field in config.configurable.");
1258
+ }
1259
+ const thread_id = config.configurable.thread_id;
1260
+ const checkpoint_ns = config.configurable.checkpoint_ns ?? "";
1261
+ const checkpoint_id = config.configurable.checkpoint_id;
1262
+ const serializedWrites = await Promise.all(
1263
+ writes.map(async ([channel, value], idx) => ({
1264
+ channel,
1265
+ value: await this.serialize(value),
1266
+ idx,
1267
+ docId: `${this.agentId}:${thread_id}:${checkpoint_ns}:${checkpoint_id}:${taskId}:${idx}`
1268
+ }))
1269
+ );
1270
+ await this.db.runTransaction(async (transaction) => {
1271
+ for (const { channel, value, idx, docId } of serializedWrites) {
1272
+ await transaction.collection(this.writesCollection).doc(docId).set({
1273
+ _openid: this.userId,
1274
+ agent_id: this.agentId,
1275
+ thread_id,
1276
+ checkpoint_ns,
1277
+ checkpoint_id,
1278
+ task_id: taskId,
1279
+ idx,
1280
+ channel,
1281
+ value
1282
+ });
1283
+ }
1284
+ });
1285
+ }
1286
+ /**
1287
+ * Delete all checkpoints and writes for a thread.
1288
+ */
1289
+ async deleteThread(threadId) {
1290
+ await this.db.collection(this.checkpointsCollection).where({
1291
+ _openid: this.userId,
1292
+ agent_id: this.agentId,
1293
+ thread_id: threadId
1294
+ }).remove();
1295
+ await this.db.collection(this.writesCollection).where({
1296
+ _openid: this.userId,
1297
+ agent_id: this.agentId,
1298
+ thread_id: threadId
1299
+ }).remove();
1300
+ }
1301
+ };
1302
+
1303
+ // src/store/tdai-store.ts
1304
+ var import_langgraph4 = require("@langchain/langgraph");
1305
+ var TDAIStore = class extends import_langgraph4.BaseStore {
3483
1306
  constructor(config) {
3484
1307
  super();
3485
1308
  this.isSetup = false;
@@ -3904,11 +1727,12 @@ var TDAIStore = class extends import_langgraph3.BaseStore {
3904
1727
  };
3905
1728
 
3906
1729
  // src/index.ts
3907
- var import_agent_shared3 = require("@cloudbase/agent-shared");
1730
+ var import_agent_shared2 = require("@cloudbase/agent-shared");
3908
1731
  // Annotate the CommonJS export names for ESM import in node:
3909
1732
  0 && (module.exports = {
3910
1733
  ClientPropertiesAnnotation,
3911
1734
  ClientStateAnnotation,
1735
+ CloudBaseSaver,
3912
1736
  LanggraphAgent,
3913
1737
  TDAISaver,
3914
1738
  TDAIStore,