@mondaydotcomorg/atp-langchain 0.20.2 → 0.20.4

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.cjs ADDED
@@ -0,0 +1,591 @@
1
+ 'use strict';
2
+
3
+ var atpClient = require('@mondaydotcomorg/atp-client');
4
+ var tools = require('@langchain/core/tools');
5
+ var atpRuntime = require('@mondaydotcomorg/atp-runtime');
6
+ var messages = require('@langchain/core/messages');
7
+ var atpProtocol = require('@mondaydotcomorg/atp-protocol');
8
+
9
+ var __defProp = Object.defineProperty;
10
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
11
+ async function createATPTools(serverUrl, headers, hooks) {
12
+ const client = new atpClient.AgentToolProtocolClient({
13
+ baseUrl: serverUrl,
14
+ headers,
15
+ hooks
16
+ });
17
+ await client.connect();
18
+ const atpTools = atpClient.createToolsFromATPClient(client);
19
+ const tools$1 = atpTools.map((tool) => new tools.DynamicTool({
20
+ name: tool.name,
21
+ description: tool.description || "",
22
+ func: tool.func
23
+ }));
24
+ return {
25
+ client,
26
+ tools: tools$1
27
+ };
28
+ }
29
+ __name(createATPTools, "createATPTools");
30
+ function convertToLangChainTools(tools$1) {
31
+ return tools$1.map((tool) => new tools.DynamicTool({
32
+ name: tool.name,
33
+ description: tool.description || "",
34
+ func: tool.func
35
+ }));
36
+ }
37
+ __name(convertToLangChainTools, "convertToLangChainTools");
38
+ var ApprovalRequiredException = class extends atpClient.ClientCallbackError {
39
+ static {
40
+ __name(this, "ApprovalRequiredException");
41
+ }
42
+ approvalRequest;
43
+ constructor(approvalRequest) {
44
+ super(`Approval required: ${approvalRequest.message}`);
45
+ this.approvalRequest = approvalRequest;
46
+ this.name = "ApprovalRequiredException";
47
+ }
48
+ };
49
+ var LangGraphATPClient = class {
50
+ static {
51
+ __name(this, "LangGraphATPClient");
52
+ }
53
+ client;
54
+ llm;
55
+ embeddings;
56
+ useLangGraphInterrupts;
57
+ directApprovalHandler;
58
+ pendingApprovals = /* @__PURE__ */ new Map();
59
+ constructor(options) {
60
+ const { serverUrl, headers, llm, embeddings, tools, useLangGraphInterrupts = true, approvalHandler, hooks } = options;
61
+ this.client = new atpClient.AgentToolProtocolClient({
62
+ baseUrl: serverUrl,
63
+ headers,
64
+ hooks,
65
+ serviceProviders: tools ? {
66
+ tools
67
+ } : void 0
68
+ });
69
+ this.llm = llm;
70
+ this.embeddings = embeddings;
71
+ this.useLangGraphInterrupts = useLangGraphInterrupts;
72
+ this.directApprovalHandler = approvalHandler;
73
+ this.client.provideLLM({
74
+ call: /* @__PURE__ */ __name(async (prompt, options2) => {
75
+ return await this.handleLLMCall(prompt, options2);
76
+ }, "call"),
77
+ extract: /* @__PURE__ */ __name(async (prompt, schema, options2) => {
78
+ return await this.handleLLMExtract(prompt, schema, options2);
79
+ }, "extract"),
80
+ classify: /* @__PURE__ */ __name(async (text, categories, options2) => {
81
+ return await this.handleLLMClassify(text, categories, options2);
82
+ }, "classify")
83
+ });
84
+ if (this.embeddings) {
85
+ this.client.provideEmbedding({
86
+ embed: /* @__PURE__ */ __name(async (text) => {
87
+ return await this.handleEmbedding(text);
88
+ }, "embed")
89
+ });
90
+ }
91
+ this.client.provideApproval({
92
+ request: /* @__PURE__ */ __name(async (message, context) => {
93
+ return await this.handleApprovalRequest(message, context);
94
+ }, "request")
95
+ });
96
+ }
97
+ /**
98
+ * Initialize the client connection
99
+ */
100
+ async connect() {
101
+ await this.client.init({
102
+ name: "langgraph-atp-client",
103
+ version: "1.0.0"
104
+ });
105
+ await this.client.connect();
106
+ }
107
+ /**
108
+ * Get TypeScript API definitions
109
+ */
110
+ getTypeDefinitions() {
111
+ return this.client.getTypeDefinitions();
112
+ }
113
+ /**
114
+ * Execute ATP code with LangGraph interrupt support
115
+ *
116
+ * When approval is needed:
117
+ * - If useLangGraphInterrupts=true: Throws ApprovalRequiredException
118
+ * - If useLangGraphInterrupts=false: Uses direct approval handler
119
+ *
120
+ * @throws ApprovalRequiredException when approval is needed (interrupt mode)
121
+ */
122
+ async execute(code, config) {
123
+ const result = await this.client.execute(code, config);
124
+ return {
125
+ result,
126
+ needsApproval: false
127
+ };
128
+ }
129
+ /**
130
+ * Resume execution after approval decision
131
+ *
132
+ * Call this after LangGraph resumes from interrupt with approval decision.
133
+ */
134
+ async resumeWithApproval(executionId, approved, reason) {
135
+ const approvalResponse = {
136
+ approved,
137
+ reason,
138
+ timestamp: Date.now()
139
+ };
140
+ this.pendingApprovals.delete(executionId);
141
+ return await this.client.resume(executionId, approvalResponse);
142
+ }
143
+ /**
144
+ * Get pending approval request for an execution
145
+ */
146
+ getPendingApproval(executionId) {
147
+ return this.pendingApprovals.get(executionId);
148
+ }
149
+ /**
150
+ * Handle LLM call - route to LangChain LLM
151
+ */
152
+ async handleLLMCall(prompt, options) {
153
+ const messages$1 = [];
154
+ if (options?.systemPrompt) {
155
+ messages$1.push(new messages.SystemMessage(options.systemPrompt));
156
+ }
157
+ messages$1.push(new messages.HumanMessage(prompt));
158
+ const response = await this.llm.invoke(messages$1);
159
+ return typeof response.content === "string" ? response.content : JSON.stringify(response.content);
160
+ }
161
+ /**
162
+ * Handle LLM extract - route to LangChain LLM with structured output
163
+ */
164
+ async handleLLMExtract(prompt, schema, options) {
165
+ const structuredLLM = this.llm.withStructuredOutput(schema);
166
+ const messages$1 = [];
167
+ if (options?.systemPrompt) {
168
+ messages$1.push(new messages.SystemMessage(options.systemPrompt));
169
+ }
170
+ messages$1.push(new messages.HumanMessage(prompt));
171
+ const result = await structuredLLM.invoke(messages$1);
172
+ return result;
173
+ }
174
+ /**
175
+ * Handle LLM classify - route to LangChain LLM
176
+ */
177
+ async handleLLMClassify(text, categories, options) {
178
+ const prompt = `Classify the following text into one of these categories: ${categories.join(", ")}
179
+
180
+ Text: ${text}
181
+
182
+ Category:`;
183
+ const messages$1 = [];
184
+ if (options?.systemPrompt) {
185
+ messages$1.push(new messages.SystemMessage(options.systemPrompt));
186
+ }
187
+ messages$1.push(new messages.HumanMessage(prompt));
188
+ const response = await this.llm.invoke(messages$1);
189
+ const result = typeof response.content === "string" ? response.content.trim() : JSON.stringify(response.content).trim();
190
+ if (!categories.includes(result)) {
191
+ for (const category of categories) {
192
+ if (result.toLowerCase().includes(category.toLowerCase())) {
193
+ return category;
194
+ }
195
+ }
196
+ const fallback = categories[0];
197
+ if (!fallback) {
198
+ throw new Error("No categories provided for classification");
199
+ }
200
+ return fallback;
201
+ }
202
+ return result;
203
+ }
204
+ /**
205
+ * Handle embedding - route to LangChain embeddings model
206
+ */
207
+ async handleEmbedding(text) {
208
+ if (!this.embeddings) {
209
+ throw new Error("Embeddings model not provided. Pass embeddings option when creating LangGraphATPClient.");
210
+ }
211
+ return await this.embeddings.embedQuery(text);
212
+ }
213
+ /**
214
+ * Get the underlying ATP client for advanced usage
215
+ */
216
+ getUnderlyingClient() {
217
+ return this.client;
218
+ }
219
+ async handleApprovalRequest(message, context) {
220
+ const executionId = context?.executionId;
221
+ const cleanContext = context ? {
222
+ ...context
223
+ } : void 0;
224
+ if (cleanContext) {
225
+ delete cleanContext.executionId;
226
+ }
227
+ if (this.useLangGraphInterrupts) {
228
+ if (typeof executionId !== "string" || !executionId) {
229
+ throw new Error("executionId is missing in approval request context");
230
+ }
231
+ const approvalRequest = {
232
+ message,
233
+ context: cleanContext,
234
+ executionId,
235
+ timestamp: Date.now()
236
+ };
237
+ this.pendingApprovals.set(executionId, approvalRequest);
238
+ throw new ApprovalRequiredException(approvalRequest);
239
+ }
240
+ if (this.directApprovalHandler) {
241
+ const approved = await this.directApprovalHandler(message, cleanContext);
242
+ return {
243
+ approved,
244
+ timestamp: Date.now()
245
+ };
246
+ }
247
+ atpRuntime.log.warn(`Approval request rejected (no handler): ${message}`);
248
+ return {
249
+ approved: false,
250
+ timestamp: Date.now()
251
+ };
252
+ }
253
+ };
254
+ async function createATPTools2(options) {
255
+ const { serverUrl, defaultExecutionConfig, ...clientOptions } = options;
256
+ const client = new LangGraphATPClient({
257
+ serverUrl,
258
+ ...clientOptions
259
+ });
260
+ await client.connect();
261
+ const atpTools = atpClient.createToolsFromATPClient(client.getUnderlyingClient());
262
+ const tools$1 = atpTools.map((atpTool) => {
263
+ if (atpTool.name === atpClient.ToolNames.EXECUTE_CODE) {
264
+ let ATPExecuteTool = class ATPExecuteTool extends tools.Tool {
265
+ static {
266
+ __name(this, "ATPExecuteTool");
267
+ }
268
+ name = `atp_${atpTool.name}`;
269
+ description = atpTool.description || "Execute TypeScript code in ATP sandbox";
270
+ async _call(input) {
271
+ try {
272
+ let code;
273
+ try {
274
+ const parsed = JSON.parse(input);
275
+ code = parsed.code || input;
276
+ } catch {
277
+ code = input;
278
+ }
279
+ const result = await client.execute(code, defaultExecutionConfig);
280
+ if (result.result.status === atpProtocol.ExecutionStatus.COMPLETED) {
281
+ return JSON.stringify({
282
+ success: true,
283
+ result: result.result.result,
284
+ stats: result.result.stats
285
+ }, null, 2);
286
+ } else if (result.result.status === atpProtocol.ExecutionStatus.FAILED) {
287
+ return JSON.stringify({
288
+ success: false,
289
+ error: result.result.error,
290
+ stats: result.result.stats
291
+ }, null, 2);
292
+ } else {
293
+ return JSON.stringify({
294
+ success: false,
295
+ error: "Execution in unexpected state: " + result.result.status
296
+ }, null, 2);
297
+ }
298
+ } catch (error) {
299
+ if (error instanceof ApprovalRequiredException) {
300
+ throw error;
301
+ }
302
+ return JSON.stringify({
303
+ success: false,
304
+ error: error.message || "Unknown error"
305
+ }, null, 2);
306
+ }
307
+ }
308
+ };
309
+ return new ATPExecuteTool();
310
+ }
311
+ return new tools.DynamicStructuredTool({
312
+ name: `atp_${atpTool.name}`,
313
+ description: atpTool.description || "",
314
+ schema: atpTool.zodSchema || atpTool.inputSchema,
315
+ func: /* @__PURE__ */ __name(async (input) => {
316
+ try {
317
+ const result = await atpTool.func(input);
318
+ return typeof result === "string" ? result : JSON.stringify(result, null, 2);
319
+ } catch (error) {
320
+ return JSON.stringify({
321
+ success: false,
322
+ error: error.message
323
+ }, null, 2);
324
+ }
325
+ }, "func")
326
+ });
327
+ });
328
+ return {
329
+ client,
330
+ tools: tools$1,
331
+ isApprovalRequired: /* @__PURE__ */ __name((error) => {
332
+ return error instanceof ApprovalRequiredException;
333
+ }, "isApprovalRequired"),
334
+ resumeWithApproval: /* @__PURE__ */ __name(async (executionId, approved, reason) => {
335
+ return await client.resumeWithApproval(executionId, approved, reason);
336
+ }, "resumeWithApproval")
337
+ };
338
+ }
339
+ __name(createATPTools2, "createATPTools");
340
+ async function createSimpleATPTool(serverUrl, llm, headers) {
341
+ const result = await createATPTools2({
342
+ serverUrl,
343
+ headers,
344
+ llm
345
+ });
346
+ const tool = result.tools.find((t) => t.name === `atp_${atpClient.ToolNames.EXECUTE_CODE}`);
347
+ if (!tool) {
348
+ throw new Error("Failed to create ATP execute_code tool");
349
+ }
350
+ return tool;
351
+ }
352
+ __name(createSimpleATPTool, "createSimpleATPTool");
353
+ function createLangChainEventHandler(onEvent, options = {}) {
354
+ const { tags = [], metadata = {} } = options;
355
+ return (event) => {
356
+ const baseEvent = {
357
+ run_id: event.runId,
358
+ tags: [
359
+ "atp",
360
+ ...tags
361
+ ],
362
+ metadata: {
363
+ ...metadata,
364
+ timestamp: event.timestamp
365
+ }
366
+ };
367
+ switch (event.type) {
368
+ case atpProtocol.ATPEventType.THINKING: {
369
+ const data = event.data;
370
+ onEvent({
371
+ ...baseEvent,
372
+ event: "on_llm_stream",
373
+ name: "atp_thinking",
374
+ data: {
375
+ chunk: data.content,
376
+ step: data.step
377
+ }
378
+ });
379
+ break;
380
+ }
381
+ case atpProtocol.ATPEventType.TOOL_START: {
382
+ const data = event.data;
383
+ onEvent({
384
+ ...baseEvent,
385
+ event: "on_tool_start",
386
+ name: `${data.apiGroup}.${data.toolName}`,
387
+ data: {
388
+ input: data.input
389
+ },
390
+ metadata: {
391
+ ...baseEvent.metadata,
392
+ apiGroup: data.apiGroup,
393
+ toolName: data.toolName
394
+ }
395
+ });
396
+ break;
397
+ }
398
+ case atpProtocol.ATPEventType.TOOL_END: {
399
+ const data = event.data;
400
+ onEvent({
401
+ ...baseEvent,
402
+ event: "on_tool_end",
403
+ name: `${data.apiGroup}.${data.toolName}`,
404
+ data: {
405
+ output: data.output,
406
+ error: data.error
407
+ },
408
+ metadata: {
409
+ ...baseEvent.metadata,
410
+ apiGroup: data.apiGroup,
411
+ toolName: data.toolName,
412
+ duration: data.duration,
413
+ success: data.success
414
+ }
415
+ });
416
+ break;
417
+ }
418
+ case atpProtocol.ATPEventType.TEXT: {
419
+ const data = event.data;
420
+ onEvent({
421
+ ...baseEvent,
422
+ event: "on_chain_stream",
423
+ name: "atp_output",
424
+ data: {
425
+ chunk: data.text
426
+ }
427
+ });
428
+ break;
429
+ }
430
+ case atpProtocol.ATPEventType.TEXT_END:
431
+ onEvent({
432
+ ...baseEvent,
433
+ event: "on_chain_end",
434
+ name: "atp_output",
435
+ data: {}
436
+ });
437
+ break;
438
+ case atpProtocol.ATPEventType.SOURCE: {
439
+ const data = event.data;
440
+ onEvent({
441
+ ...baseEvent,
442
+ event: "on_custom_event",
443
+ name: "atp_source",
444
+ data: {
445
+ url: data.url,
446
+ title: data.title,
447
+ summary: data.summary,
448
+ createdAt: data.createdAt
449
+ }
450
+ });
451
+ break;
452
+ }
453
+ case atpProtocol.ATPEventType.PROGRESS: {
454
+ const data = event.data;
455
+ onEvent({
456
+ ...baseEvent,
457
+ event: "on_custom_event",
458
+ name: "atp_progress",
459
+ data: {
460
+ message: data.message,
461
+ fraction: data.fraction,
462
+ percentage: Math.round(data.fraction * 100)
463
+ }
464
+ });
465
+ break;
466
+ }
467
+ case atpProtocol.ATPEventType.ERROR: {
468
+ const data = event.data;
469
+ onEvent({
470
+ ...baseEvent,
471
+ event: "on_chain_error",
472
+ name: "atp_error",
473
+ data: {
474
+ error: data.message,
475
+ code: data.code
476
+ }
477
+ });
478
+ break;
479
+ }
480
+ default:
481
+ onEvent({
482
+ ...baseEvent,
483
+ event: "on_custom_event",
484
+ name: `atp_${event.type}`,
485
+ data: event.data
486
+ });
487
+ break;
488
+ }
489
+ };
490
+ }
491
+ __name(createLangChainEventHandler, "createLangChainEventHandler");
492
+ function createCallbackManagerHandler(callbackManager) {
493
+ return (event) => {
494
+ switch (event.type) {
495
+ case atpProtocol.ATPEventType.THINKING: {
496
+ const data = event.data;
497
+ callbackManager.handleLLMNewToken?.(data.content, void 0, event.runId);
498
+ break;
499
+ }
500
+ case atpProtocol.ATPEventType.TOOL_START: {
501
+ const data = event.data;
502
+ callbackManager.handleToolStart?.({
503
+ name: `${data.apiGroup}.${data.toolName}`
504
+ }, JSON.stringify(data.input), event.runId, void 0, [
505
+ "atp"
506
+ ], {
507
+ apiGroup: data.apiGroup
508
+ });
509
+ break;
510
+ }
511
+ case atpProtocol.ATPEventType.TOOL_END: {
512
+ const data = event.data;
513
+ callbackManager.handleToolEnd?.(JSON.stringify(data.output), event.runId, void 0, [
514
+ "atp"
515
+ ]);
516
+ break;
517
+ }
518
+ case atpProtocol.ATPEventType.TEXT: {
519
+ const data = event.data;
520
+ callbackManager.handleLLMNewToken?.(data.text, void 0, event.runId);
521
+ break;
522
+ }
523
+ default:
524
+ callbackManager.handleCustomEvent?.(`atp_${event.type}`, event.data, event.runId, [
525
+ "atp"
526
+ ], {
527
+ timestamp: event.timestamp
528
+ });
529
+ break;
530
+ }
531
+ };
532
+ }
533
+ __name(createCallbackManagerHandler, "createCallbackManagerHandler");
534
+ var ATPExecutionNode = class {
535
+ static {
536
+ __name(this, "ATPExecutionNode");
537
+ }
538
+ client;
539
+ constructor(client) {
540
+ this.client = client;
541
+ }
542
+ /**
543
+ * Execute code from the state and update the state with results
544
+ */
545
+ async execute(state) {
546
+ if (!state.code) {
547
+ throw new Error("No code provided in state");
548
+ }
549
+ const result = await this.client.execute(state.code);
550
+ return {
551
+ ...state,
552
+ executionResult: result,
553
+ lastExecutionStatus: result.status,
554
+ lastExecutionOutput: result.status === atpProtocol.ExecutionStatus.COMPLETED ? result.result : result.error
555
+ };
556
+ }
557
+ /**
558
+ * Create a function suitable for LangGraph node
559
+ */
560
+ asFunction() {
561
+ return this.execute.bind(this);
562
+ }
563
+ };
564
+ function createATPNode(client) {
565
+ return async (state) => {
566
+ if (!state.code) {
567
+ throw new Error("No code provided in state");
568
+ }
569
+ const result = await client.execute(state.code);
570
+ return {
571
+ ...state,
572
+ executionResult: result,
573
+ lastExecutionStatus: result.status,
574
+ lastExecutionOutput: result.status === atpProtocol.ExecutionStatus.COMPLETED ? result.result : result.error
575
+ };
576
+ };
577
+ }
578
+ __name(createATPNode, "createATPNode");
579
+
580
+ exports.ATPExecutionNode = ATPExecutionNode;
581
+ exports.ApprovalRequiredException = ApprovalRequiredException;
582
+ exports.LangGraphATPClient = LangGraphATPClient;
583
+ exports.convertToLangChainTools = convertToLangChainTools;
584
+ exports.createATPNode = createATPNode;
585
+ exports.createATPTools = createATPTools2;
586
+ exports.createATPToolsBasic = createATPTools;
587
+ exports.createCallbackManagerHandler = createCallbackManagerHandler;
588
+ exports.createLangChainEventHandler = createLangChainEventHandler;
589
+ exports.createSimpleATPTool = createSimpleATPTool;
590
+ //# sourceMappingURL=index.cjs.map
591
+ //# sourceMappingURL=index.cjs.map