@loopman/langchain-sdk 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +374 -0
  2. package/README.md +594 -0
  3. package/dist/agents/loopman-agent.d.ts +29 -0
  4. package/dist/agents/loopman-agent.d.ts.map +1 -0
  5. package/dist/agents/loopman-agent.js +441 -0
  6. package/dist/agents/loopman-agent.js.map +1 -0
  7. package/dist/client/loopman-api.d.ts +123 -0
  8. package/dist/client/loopman-api.d.ts.map +1 -0
  9. package/dist/client/loopman-api.js +407 -0
  10. package/dist/client/loopman-api.js.map +1 -0
  11. package/dist/helpers/prompt-orchestrator.d.ts +12 -0
  12. package/dist/helpers/prompt-orchestrator.d.ts.map +1 -0
  13. package/dist/helpers/prompt-orchestrator.js +133 -0
  14. package/dist/helpers/prompt-orchestrator.js.map +1 -0
  15. package/dist/index.d.ts +17 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +22 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/loopman-agent-wrapper.d.ts +70 -0
  20. package/dist/loopman-agent-wrapper.d.ts.map +1 -0
  21. package/dist/loopman-agent-wrapper.js +157 -0
  22. package/dist/loopman-agent-wrapper.js.map +1 -0
  23. package/dist/loopman-middleware.d.ts +78 -0
  24. package/dist/loopman-middleware.d.ts.map +1 -0
  25. package/dist/loopman-middleware.js +367 -0
  26. package/dist/loopman-middleware.js.map +1 -0
  27. package/dist/mcp/loopman-mcp-client.d.ts +17 -0
  28. package/dist/mcp/loopman-mcp-client.d.ts.map +1 -0
  29. package/dist/mcp/loopman-mcp-client.js +76 -0
  30. package/dist/mcp/loopman-mcp-client.js.map +1 -0
  31. package/dist/mcp/tool-registry.d.ts +29 -0
  32. package/dist/mcp/tool-registry.d.ts.map +1 -0
  33. package/dist/mcp/tool-registry.js +143 -0
  34. package/dist/mcp/tool-registry.js.map +1 -0
  35. package/dist/services/index.d.ts +12 -0
  36. package/dist/services/index.d.ts.map +1 -0
  37. package/dist/services/index.js +9 -0
  38. package/dist/services/index.js.map +1 -0
  39. package/dist/services/logger.service.d.ts +107 -0
  40. package/dist/services/logger.service.d.ts.map +1 -0
  41. package/dist/services/logger.service.js +173 -0
  42. package/dist/services/logger.service.js.map +1 -0
  43. package/dist/services/loopman.service.d.ts +72 -0
  44. package/dist/services/loopman.service.d.ts.map +1 -0
  45. package/dist/services/loopman.service.js +271 -0
  46. package/dist/services/loopman.service.js.map +1 -0
  47. package/dist/services/polling.service.d.ts +136 -0
  48. package/dist/services/polling.service.d.ts.map +1 -0
  49. package/dist/services/polling.service.js +428 -0
  50. package/dist/services/polling.service.js.map +1 -0
  51. package/dist/types.d.ts +242 -0
  52. package/dist/types.d.ts.map +1 -0
  53. package/dist/types.js +35 -0
  54. package/dist/types.js.map +1 -0
  55. package/package.json +58 -0
@@ -0,0 +1,407 @@
1
+ import { LoopmanConnectionError, } from "../types";
2
+ /**
3
+ * Loopman client for direct API connection
4
+ * Allows authentication with an API key and direct backoffice calls
5
+ */
6
+ export class LoopmanApiClient {
7
+ config;
8
+ authServiceUrl;
9
+ tokenCache = new Map();
10
+ bufferTimeSeconds = 60; // Renew token 60s before expiration
11
+ constructor(config) {
12
+ this.config = config;
13
+ this.authServiceUrl =
14
+ process.env.LOOPMAN_AUTH_URL || "https://auth.loopman.ai";
15
+ // Clean expired tokens every 5 minutes
16
+ setInterval(() => this.cleanupExpiredTokens(), 5 * 60 * 1000);
17
+ }
18
+ /**
19
+ * Exchange an API key for JWT tokens with caching
20
+ * @param apiKey The API key to exchange
21
+ * @returns Object containing accessToken and serverUrl
22
+ */
23
+ async getTokenFromApiKey(apiKey) {
24
+ // Check cache first
25
+ const cached = this.getCachedToken(apiKey);
26
+ if (cached) {
27
+ return cached;
28
+ }
29
+ // Cache miss or expired, get a new token
30
+ console.log("🔑 Getting a new token from the authentication service");
31
+ try {
32
+ const response = await fetch(`${this.authServiceUrl}/auth/tokens/exchange`, {
33
+ method: "POST",
34
+ headers: {
35
+ "Content-Type": "application/json",
36
+ },
37
+ body: JSON.stringify({ apiKey }),
38
+ });
39
+ if (!response.ok) {
40
+ const errorData = (await response
41
+ .json()
42
+ .catch(() => ({})));
43
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
44
+ }
45
+ const data = (await response.json());
46
+ const { accessToken, refreshToken, expiresIn, serverUrl } = data;
47
+ // Store in cache
48
+ this.setCachedToken(apiKey, {
49
+ accessToken,
50
+ refreshToken,
51
+ serverUrl,
52
+ expiresIn,
53
+ });
54
+ return { accessToken, serverUrl, fromCache: false };
55
+ }
56
+ catch (error) {
57
+ console.error("❌ Failed to exchange API key:", error);
58
+ this.handleNetworkError(error, "Authentication service", this.authServiceUrl);
59
+ }
60
+ }
61
+ /**
62
+ * Get authorization headers with access token and server URL
63
+ */
64
+ async getAuthHeaders(apiKey) {
65
+ const { accessToken, serverUrl } = await this.getTokenFromApiKey(apiKey);
66
+ return {
67
+ Authorization: `Bearer ${accessToken}`,
68
+ serverUrl,
69
+ };
70
+ }
71
+ /**
72
+ * Get current user from backoffice
73
+ * @param apiKey The API key for authentication
74
+ * @returns Current user information
75
+ */
76
+ async getCurrentUser(apiKey) {
77
+ console.log("👤 Getting current user from backoffice");
78
+ try {
79
+ const { Authorization, serverUrl } = await this.getAuthHeaders(apiKey);
80
+ //console.log(`🔗 Using backoffice URL: ${serverUrl}`);
81
+ const response = await fetch(`${serverUrl}/user/me`, {
82
+ headers: { Authorization },
83
+ });
84
+ if (!response.ok) {
85
+ const errorData = (await response
86
+ .json()
87
+ .catch(() => ({})));
88
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
89
+ }
90
+ const user = (await response.json());
91
+ console.log(`✅ Current user retrieved: ${user.email}`);
92
+ return user;
93
+ }
94
+ catch (error) {
95
+ console.error("❌ Failed to get current user:", error);
96
+ // Specific error handling for network errors
97
+ if (error instanceof TypeError &&
98
+ error.message.includes("fetch failed")) {
99
+ throw new LoopmanConnectionError(`Backoffice service inaccessible. ` +
100
+ `Check that the backoffice server is started and accessible. ` +
101
+ `Network error: ${error.message}`);
102
+ }
103
+ throw new LoopmanConnectionError(`Failed to get user: ${error instanceof Error ? error.message : "Unknown error"}`);
104
+ }
105
+ }
106
+ /**
107
+ * Generic method to make GET requests to backoffice
108
+ * @param apiKey The API key for authentication
109
+ * @param endpoint The endpoint to call (e.g. '/tasks', '/channels')
110
+ * @returns Response data
111
+ */
112
+ async get(apiKey, endpoint) {
113
+ console.log(`📥 GET ${endpoint}`);
114
+ try {
115
+ const { Authorization, serverUrl } = await this.getAuthHeaders(apiKey);
116
+ //console.log(`🔗 Using backoffice URL: ${serverUrl}`);
117
+ const response = await fetch(`${serverUrl}${endpoint}`, {
118
+ headers: { Authorization },
119
+ });
120
+ if (!response.ok) {
121
+ const errorData = (await response
122
+ .json()
123
+ .catch(() => ({})));
124
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
125
+ }
126
+ return (await response.json());
127
+ }
128
+ catch (error) {
129
+ console.error(`❌ Failed GET ${endpoint}:`, error);
130
+ throw new LoopmanConnectionError(`Failed GET ${endpoint}: ${error instanceof Error ? error.message : "Unknown error"}`);
131
+ }
132
+ }
133
+ /**
134
+ * Generic method to make POST requests to backoffice
135
+ * @param apiKey The API key for authentication
136
+ * @param endpoint The endpoint to call
137
+ * @param data The data to send
138
+ * @returns Response data
139
+ */
140
+ async post(apiKey, endpoint, data) {
141
+ console.log(`📤 POST ${endpoint}`);
142
+ try {
143
+ const { Authorization, serverUrl } = await this.getAuthHeaders(apiKey);
144
+ //console.log(`🔗 Using backoffice URL: ${serverUrl}`);
145
+ const response = await fetch(`${serverUrl}${endpoint}`, {
146
+ method: "POST",
147
+ headers: {
148
+ Authorization,
149
+ "Content-Type": "application/json",
150
+ },
151
+ body: JSON.stringify(data),
152
+ });
153
+ if (!response.ok) {
154
+ const errorData = (await response
155
+ .json()
156
+ .catch(() => ({})));
157
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
158
+ }
159
+ return (await response.json());
160
+ }
161
+ catch (error) {
162
+ console.error(`❌ Failed POST ${endpoint}:`, error);
163
+ throw new LoopmanConnectionError(`Failed POST ${endpoint}: ${error instanceof Error ? error.message : "Unknown error"}`);
164
+ }
165
+ }
166
+ /**
167
+ * Generic method to make PUT requests to backoffice
168
+ * @param apiKey The API key for authentication
169
+ * @param endpoint The endpoint to call
170
+ * @param data The data to send
171
+ * @returns Response data
172
+ */
173
+ async put(apiKey, endpoint, data) {
174
+ console.log(`📝 PUT ${endpoint}`);
175
+ try {
176
+ const { Authorization, serverUrl } = await this.getAuthHeaders(apiKey);
177
+ //console.log(`🔗 Using backoffice URL: ${serverUrl}`);
178
+ const response = await fetch(`${serverUrl}${endpoint}`, {
179
+ method: "PUT",
180
+ headers: {
181
+ Authorization,
182
+ "Content-Type": "application/json",
183
+ },
184
+ body: JSON.stringify(data),
185
+ });
186
+ if (!response.ok) {
187
+ const errorData = (await response
188
+ .json()
189
+ .catch(() => ({})));
190
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
191
+ }
192
+ return (await response.json());
193
+ }
194
+ catch (error) {
195
+ console.error(`❌ Failed PUT ${endpoint}:`, error);
196
+ throw new LoopmanConnectionError(`Failed PUT ${endpoint}: ${error instanceof Error ? error.message : "Unknown error"}`);
197
+ }
198
+ }
199
+ /**
200
+ * Generic method to make PATCH requests to backoffice
201
+ * @param apiKey The API key for authentication
202
+ * @param endpoint The endpoint to call
203
+ * @param data The data to send
204
+ * @returns Response data
205
+ */
206
+ async patch(apiKey, endpoint, data) {
207
+ console.log(`🔧 PATCH ${endpoint}`);
208
+ try {
209
+ const { Authorization, serverUrl } = await this.getAuthHeaders(apiKey);
210
+ //console.log(`🔗 Using backoffice URL: ${serverUrl}`);
211
+ const response = await fetch(`${serverUrl}${endpoint}`, {
212
+ method: "PATCH",
213
+ headers: {
214
+ Authorization,
215
+ "Content-Type": "application/json",
216
+ },
217
+ body: JSON.stringify(data),
218
+ });
219
+ if (!response.ok) {
220
+ const errorData = (await response
221
+ .json()
222
+ .catch(() => ({})));
223
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
224
+ }
225
+ return (await response.json());
226
+ }
227
+ catch (error) {
228
+ console.error(`❌ Failed PATCH ${endpoint}:`, error);
229
+ throw new LoopmanConnectionError(`Failed PATCH ${endpoint}: ${error instanceof Error ? error.message : "Unknown error"}`);
230
+ }
231
+ }
232
+ /**
233
+ * Generic method to make DELETE requests to backoffice
234
+ * @param apiKey The API key for authentication
235
+ * @param endpoint The endpoint to call
236
+ * @returns Response data
237
+ */
238
+ async delete(apiKey, endpoint) {
239
+ console.log(`🗑️ DELETE ${endpoint}`);
240
+ try {
241
+ const { Authorization, serverUrl } = await this.getAuthHeaders(apiKey);
242
+ //console.log(`🔗 Using backoffice URL: ${serverUrl}`);
243
+ const response = await fetch(`${serverUrl}${endpoint}`, {
244
+ method: "DELETE",
245
+ headers: { Authorization },
246
+ });
247
+ if (!response.ok) {
248
+ const errorData = (await response
249
+ .json()
250
+ .catch(() => ({})));
251
+ throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
252
+ }
253
+ return (await response.json());
254
+ }
255
+ catch (error) {
256
+ console.error(`❌ Failed DELETE ${endpoint}:`, error);
257
+ throw new LoopmanConnectionError(`Failed DELETE ${endpoint}: ${error instanceof Error ? error.message : "Unknown error"}`);
258
+ }
259
+ }
260
+ /**
261
+ * Get token from cache if valid, otherwise return null
262
+ */
263
+ getCachedToken(apiKey) {
264
+ const cached = this.tokenCache.get(apiKey);
265
+ if (!cached) {
266
+ console.log(`🔍 Cache miss for key: ${this.maskApiKey(apiKey)}`);
267
+ return null;
268
+ }
269
+ // Check if token is still valid
270
+ const now = Date.now();
271
+ if (cached.expiresAt <= now) {
272
+ console.log(`⏰ Token expired for key: ${this.maskApiKey(apiKey)} (expired ${Math.floor((now - cached.expiresAt) / 1000)}s ago)`);
273
+ this.tokenCache.delete(apiKey);
274
+ return null;
275
+ }
276
+ const ttl = Math.floor((cached.expiresAt - now) / 1000);
277
+ console.log(`✅ Cache hit for key: ${this.maskApiKey(apiKey)} (TTL: ${ttl}s)`);
278
+ return {
279
+ accessToken: cached.data.accessToken,
280
+ serverUrl: cached.data.serverUrl,
281
+ fromCache: true,
282
+ };
283
+ }
284
+ /**
285
+ * Store token in cache with expiration
286
+ */
287
+ setCachedToken(apiKey, tokenData) {
288
+ const now = Date.now();
289
+ const expiresAt = now + (tokenData.expiresIn - this.bufferTimeSeconds) * 1000;
290
+ this.tokenCache.set(apiKey, {
291
+ data: tokenData,
292
+ expiresAt,
293
+ });
294
+ const ttl = Math.floor((expiresAt - now) / 1000);
295
+ console.log(`💾 Token cached for key: ${this.maskApiKey(apiKey)} (TTL: ${ttl}s, expires at: ${new Date(expiresAt).toISOString()})`);
296
+ }
297
+ /**
298
+ * Remove a token from cache
299
+ */
300
+ clearCache(apiKey) {
301
+ const deleted = this.tokenCache.delete(apiKey);
302
+ if (deleted) {
303
+ console.log(`🗑️ Token removed from cache for key: ${this.maskApiKey(apiKey)}`);
304
+ }
305
+ }
306
+ /**
307
+ * Clear all token cache
308
+ */
309
+ clearAllCache() {
310
+ const size = this.tokenCache.size;
311
+ this.tokenCache.clear();
312
+ console.log(`🧹 Token cache cleared (${size} entries removed)`);
313
+ }
314
+ /**
315
+ * Get cache statistics
316
+ */
317
+ getCacheStats() {
318
+ const now = Date.now();
319
+ const entries = Array.from(this.tokenCache.entries()).map(([apiKey, cached]) => ({
320
+ apiKey: this.maskApiKey(apiKey),
321
+ serverUrl: cached.data.serverUrl,
322
+ expiresAt: new Date(cached.expiresAt).toISOString(),
323
+ ttl: Math.floor((cached.expiresAt - now) / 1000), // seconds until expiration
324
+ }));
325
+ return {
326
+ size: this.tokenCache.size,
327
+ entries,
328
+ };
329
+ }
330
+ /**
331
+ * Check if a token exists and is valid
332
+ */
333
+ hasValidToken(apiKey) {
334
+ const cached = this.tokenCache.get(apiKey);
335
+ if (!cached)
336
+ return false;
337
+ const isValid = cached.expiresAt > Date.now();
338
+ if (!isValid) {
339
+ this.tokenCache.delete(apiKey);
340
+ }
341
+ return isValid;
342
+ }
343
+ /**
344
+ * Get remaining TTL for a cached token
345
+ */
346
+ getTokenTTL(apiKey) {
347
+ const cached = this.tokenCache.get(apiKey);
348
+ if (!cached)
349
+ return 0;
350
+ const ttl = Math.floor((cached.expiresAt - Date.now()) / 1000);
351
+ return Math.max(0, ttl);
352
+ }
353
+ /**
354
+ * Clean up expired tokens from cache
355
+ */
356
+ cleanupExpiredTokens() {
357
+ const now = Date.now();
358
+ let removed = 0;
359
+ for (const [apiKey, cached] of this.tokenCache.entries()) {
360
+ if (cached.expiresAt <= now) {
361
+ this.tokenCache.delete(apiKey);
362
+ removed++;
363
+ }
364
+ }
365
+ if (removed > 0) {
366
+ console.log(`🧹 ${removed} expired token(s) cleaned from cache (${this.tokenCache.size} remaining)`);
367
+ }
368
+ }
369
+ /**
370
+ * Handle network errors consistently
371
+ */
372
+ handleNetworkError(error, serviceName, serviceUrl) {
373
+ if (error instanceof TypeError && error.message.includes("fetch failed")) {
374
+ throw new LoopmanConnectionError(`${serviceName} inaccessible at ${serviceUrl}. ` +
375
+ `Check that the server is started and accessible. ` +
376
+ `Network error: ${error.message}`);
377
+ }
378
+ if (error instanceof Error && error.message.includes("ECONNREFUSED")) {
379
+ throw new LoopmanConnectionError(`Connection refused to ${serviceName} (${serviceUrl}). ` +
380
+ `The server is probably not started. ` +
381
+ `Check that the service is running.`);
382
+ }
383
+ if (error instanceof Error && error.message.includes("ENOTFOUND")) {
384
+ throw new LoopmanConnectionError(`${serviceName} not found (${serviceUrl}). ` +
385
+ `Check the service URL in your configuration. ` +
386
+ `DNS error: ${error.message}`);
387
+ }
388
+ throw new LoopmanConnectionError(`Connection error to ${serviceName}. ` +
389
+ `Service: ${serviceUrl}. ` +
390
+ `Error: ${error instanceof Error ? error.message : "Unknown error"}`);
391
+ }
392
+ /**
393
+ * Mask API key for logs (show only first 8 characters)
394
+ */
395
+ maskApiKey(apiKey) {
396
+ if (apiKey.length <= 8)
397
+ return apiKey;
398
+ return `${apiKey.substring(0, 8)}...`;
399
+ }
400
+ /**
401
+ * Get current configuration
402
+ */
403
+ get configuration() {
404
+ return { ...this.config };
405
+ }
406
+ }
407
+ //# sourceMappingURL=loopman-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopman-api.js","sourceRoot":"","sources":["../../src/client/loopman-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,sBAAsB,GAIvB,MAAM,UAAU,CAAC;AAMlB;;;GAGG;AACH,MAAM,OAAO,gBAAgB;IAMP;IALZ,cAAc,CAAS;IACvB,UAAU,GAChB,IAAI,GAAG,EAAE,CAAC;IACK,iBAAiB,GAAG,EAAE,CAAC,CAAC,oCAAoC;IAE7E,YAAoB,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;QACvC,IAAI,CAAC,cAAc;YACjB,OAAO,CAAC,GAAG,CAAC,gBAAgB,IAAI,yBAAyB,CAAC;QAE5D,uCAAuC;QACvC,WAAW,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,oBAAoB,EAAE,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;IAChE,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,kBAAkB,CACtB,MAAc;QAEd,oBAAoB;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QAC3C,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,yCAAyC;QACzC,OAAO,CAAC,GAAG,CAAC,wDAAwD,CAAC,CAAC;QAEtE,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,KAAK,CAC1B,GAAG,IAAI,CAAC,cAAc,uBAAuB,EAC7C;gBACE,MAAM,EAAE,MAAM;gBACd,OAAO,EAAE;oBACP,cAAc,EAA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QACf,OAAO,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;IAC5B,CAAC;CACF"}
@@ -0,0 +1,12 @@
1
+ export interface LoopmanPromptOptions {
2
+ workflowId: string;
3
+ executionId: string;
4
+ taskId?: string;
5
+ category?: string;
6
+ systemPrompt?: string;
7
+ language?: string;
8
+ }
9
+ export declare function buildLoopmanSystemPrompt(options: LoopmanPromptOptions): string;
10
+ export declare function extractTaskId(response: string): string | undefined;
11
+ export declare function extractConfidence(response: string): number | undefined;
12
+ //# sourceMappingURL=prompt-orchestrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-orchestrator.d.ts","sourceRoot":"","sources":["../../src/helpers/prompt-orchestrator.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,oBAAoB;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,oBAAoB,GAC5B,MAAM,CAgBR;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGlE;AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAGtE"}
@@ -0,0 +1,133 @@
1
+ export function buildLoopmanSystemPrompt(options) {
2
+ const before = sanitizePlaceholders(ORCHESTRATOR_BEFORE, options);
3
+ const after = sanitizePlaceholders(ORCHESTRATOR_AFTER, options);
4
+ const variablePrompt = options.systemPrompt ?? "";
5
+ // Add language instruction if specified
6
+ let languageInstruction = "";
7
+ if (options.language) {
8
+ languageInstruction = `\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n🌍 LANGUAGE REQUIREMENT\n\nAll text content you provide to submitForHumanReview MUST be written in ${options.language}.\nThis includes:\n- title\n- description\n- proposedDecision\n- decisionReasoning\n- businessContext\n- information labels and values\n\nEven if the user communicates in another language, always use ${options.language} for human review content.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
9
+ }
10
+ if (variablePrompt.trim().length === 0) {
11
+ return `${before}${languageInstruction}\n${after}`;
12
+ }
13
+ return `${before}\n${variablePrompt}${languageInstruction}\n${after}`;
14
+ }
15
+ export function extractTaskId(response) {
16
+ const match = response.match(/<task_id>([^<]+)<\/task_id>/);
17
+ return match ? match[1] : undefined;
18
+ }
19
+ export function extractConfidence(response) {
20
+ const match = response.match(/confidence[:\s]+(\d+(?:\.\d+)?)/i);
21
+ return match ? parseFloat(match[1]) : undefined;
22
+ }
23
+ function sanitizePlaceholders(template, options) {
24
+ const replaced = template
25
+ .replace(/\{\{\s*\$workflow\.id\s*\}\}/g, options.workflowId)
26
+ .replace(/\{\{\s*\$execution\.id\s*\}\}/g, options.executionId)
27
+ .replace(/\{\{\s*\$json\.taskId\s*\}\}/g, options.taskId ?? "")
28
+ .replace(/\{\{\s*\$category\s*\}\}/g, options.category ?? "general");
29
+ return replaced;
30
+ }
31
+ const ORCHESTRATOR_BEFORE = `
32
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
33
+
34
+ 🔧 LOOPMAN HUMAN-IN-THE-LOOP WORKFLOW
35
+
36
+ 🚨 IMPORTANT: This is a STRICT workflow. You MUST NOT deviate from it.
37
+
38
+ ❌ DO NOT call business tools directly (send_email, publish_content, delete_data, etc.)
39
+ ✅ ALWAYS follow the 4-step process below
40
+
41
+ You MUST follow these steps IN ORDER:
42
+
43
+ 1️⃣ STEP 1: Call getHumanGuidelines
44
+ - workflow_id: "{{ $workflow.id }}"
45
+ - execution_id: "{{ $execution.id }}"
46
+ - category: "{{ $category }}"
47
+
48
+ 2️⃣ STEP 2: Call getDecisionContext
49
+ - workflow_id: "{{ $workflow.id }}"
50
+ - execution_id: "{{ $execution.id }}"
51
+
52
+ 3️⃣ STEP 3: Analyze the context
53
+
54
+ After completing Steps 1 and 2, analyze in your next Thought:
55
+
56
+ Thought: Steps 1 and 2 complete. Analyzing context:
57
+
58
+ 🚨 DECISION HIERARCHY (from highest to lowest priority):
59
+ 1. HUMAN DECISIONS (userType: USER) - Most authoritative
60
+ 2. GUIDELINES - Generic rules and policies
61
+ 3. SYSTEM DECISIONS (userType: SYSTEM) - Lowest priority
62
+
63
+ If a human previously approved/rejected something that contradicts a guideline,
64
+ the human decision takes precedence. Humans provide contextual judgment that
65
+ overrides generic rules.
66
+
67
+ Guidelines received:
68
+ - [RULE-ID-1]: [Description] → Applicable? [YES/NO and why]
69
+ - [RULE-ID-2]: [Description] → Applicable? [YES/NO and why]
70
+ - Initially applicable: [list]
71
+
72
+ Decision History analysis:
73
+ - Human decisions: [X] found
74
+ → [Summarize: what did humans approve/reject and why]
75
+ → [Note any conflicts with guidelines]
76
+ - System decisions: [Y] found
77
+ → [Summarize if no human override exists]
78
+
79
+ Conflicts resolution:
80
+ - Human override guideline [RULE-ID]? → [YES/NO: explain]
81
+ - Human override system decision? → [YES/NO: explain]
82
+
83
+ Final authoritative context:
84
+ - Must follow: [Human decisions that override guidelines/system]
85
+ - Must respect: [Guidelines not contradicted by humans]
86
+ - Can consider: [System decisions if no human/guideline exists]
87
+
88
+ Example:
89
+ - Guideline says "Reject emails from unknown domains"
90
+ - Human previously approved email from unknown domain X with comment "Trusted partner"
91
+ - → FOLLOW HUMAN: Approve similar emails from domain X
92
+ - → Human judgment > Generic guideline
93
+
94
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`;
95
+ const ORCHESTRATOR_AFTER = `
96
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
97
+
98
+ 4️⃣ STEP 4: Submit for human review
99
+
100
+ 🚨 CRITICAL RULES - READ CAREFULLY:
101
+
102
+ ❌ NEVER call business tools directly (like send_email, publish_content, delete_data, etc.)
103
+ ❌ NEVER skip the submitForHumanReview step
104
+ ✅ ALWAYS go through submitForHumanReview FIRST before any action
105
+
106
+ You MUST call submitForHumanReview in these cases:
107
+
108
+ A) First attempt: No previous decisions found
109
+ B) After NEED_CHANGES: getDecisionContext shows human feedback
110
+ → In this case, you MUST incorporate the feedback and RE-SUBMIT a corrected proposal
111
+
112
+ Do NOT skip this step if you see previous NEED_CHANGES feedback!
113
+ The human is waiting for your corrected proposal.
114
+
115
+ Call submitForHumanReview with ALL these REQUIRED fields:
116
+ * title (string, required): Brief description of the action (e.g., "Send email to Alice")
117
+ * description (string, required): Brief description of the decision being requested
118
+ * proposedDecision (string, REQUIRED): The exact action you propose (e.g., "Send email with subject 'Meeting' to alice@example.com")
119
+ - If re-submitting after NEED_CHANGES, incorporate the human feedback into your proposal
120
+ * decisionReasoning (string, required): Detailed explanation of why you made this decision based on guidelines
121
+ - If getDecisionContext returned previous human decisions, ALWAYS mention them in your reasoning
122
+ - Example: "Based on John Doe's previous feedback on 2024-01-15 requesting changes, I have updated the proposal to..."
123
+ - Include the human's name and their decision to show you incorporated their feedback
124
+ * businessContext (string, required): Background context about the situation - explain the circumstances like you're writing to your supervisor
125
+ * information (array, required): Supporting evidence with descriptive labels (e.g., [{"type": "text", "label": "Recipient", "value": "alice@example.com"}])
126
+ - The tool will automatically inject workflowIdentifier, executionIdentifier, and category
127
+ - Do NOT leave any required field empty or the call will fail
128
+
129
+ After calling submitForHumanReview, STOP and provide your final answer.
130
+ DO NOT call any other tools after submitForHumanReview.
131
+
132
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`;
133
+ //# sourceMappingURL=prompt-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ED,SAAS,oBAAoB,CAC3B,QAAgB,EAChB,OAA6B;IAE7B,MAAM,QAAQ,GAAG,QAAQ;SACtB,OAAO,CAAC,+BAA+B,EAAE,OAAO,CAAC,UAAU,CAAC;SAC5D,OAAO,CAAC,gCAAgC,EAAE,OAAO,CAAC,WAAW,CAAC;SAC9D,OAAO,CAAC,+BAA+B,EAAE,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC;SAC9D,OAAO,CAAC,2BAA2B,EAAE,OAAO,CAAC,QAAQ,IAAI,SAAS,CAAC,CAAC;IAEvE,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6DA+DiC,CAAC;AAE9D,MAAM,kBAAkB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6DAqCkC,CAAC"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Loopman SDK TypeScript
3
+ *
4
+ * LangChain middleware for Human-in-the-Loop validation via Loopman platform
5
+ */
6
+ export { loopmanMiddleware } from "./loopman-middleware";
7
+ export type { LoopmanDecision, LoopmanMiddlewareConfig, ToolCall, } from "./loopman-middleware";
8
+ export { createLoopmanAgent as createLoopmanAgentWrapper, createLoopmanAgent as deprecatedCreateLoopmanAgent, invokeWithRetry, // Recommended: explicit retry helper for invoke()
9
+ streamWithRetry, } from "./loopman-agent-wrapper";
10
+ export { createLoopmanAgent, LoopmanAgent } from "./agents/loopman-agent";
11
+ export { buildLoopmanSystemPrompt, extractConfidence, extractTaskId, } from "./helpers/prompt-orchestrator";
12
+ export { LoopmanMcpClient } from "./mcp/loopman-mcp-client";
13
+ export { LoopmanApiClient } from "./client/loopman-api";
14
+ export * from "./services";
15
+ export type { CachedToken, LoopmanConfig, LoopmanUser, TokenData, TokenExchangeResponse, } from "./types";
16
+ export { LoopmanConnectionError, LoopmanError, LoopmanTimeoutError, LoopmanValidationError, } from "./types";
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,YAAY,EACV,eAAe,EACf,uBAAuB,EACvB,QAAQ,GACT,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,kBAAkB,IAAI,yBAAyB,EAC/C,kBAAkB,IAAI,4BAA4B,EAClD,eAAe,EAAE,kDAAkD;AACnE,eAAe,GAChB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAG1E,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,aAAa,GACd,MAAM,+BAA+B,CAAC;AAGvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAG5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAGxD,cAAc,YAAY,CAAC;AAG3B,YAAY,EACV,WAAW,EACX,aAAa,EACb,WAAW,EACX,SAAS,EACT,qBAAqB,GACtB,MAAM,SAAS,CAAC;AAEjB,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Loopman SDK TypeScript
3
+ *
4
+ * LangChain middleware for Human-in-the-Loop validation via Loopman platform
5
+ */
6
+ // Middleware exports
7
+ export { loopmanMiddleware } from "./loopman-middleware";
8
+ // Agent helper exports (optional auto-retry on human feedback)
9
+ export { createLoopmanAgent as createLoopmanAgentWrapper, createLoopmanAgent as deprecatedCreateLoopmanAgent, invokeWithRetry, // Recommended: explicit retry helper for invoke()
10
+ streamWithRetry, } from "./loopman-agent-wrapper";
11
+ // New Agent implementation (MCP + HITL)
12
+ export { createLoopmanAgent, LoopmanAgent } from "./agents/loopman-agent";
13
+ // Prompt helpers
14
+ export { buildLoopmanSystemPrompt, extractConfidence, extractTaskId, } from "./helpers/prompt-orchestrator";
15
+ // MCP utilities
16
+ export { LoopmanMcpClient } from "./mcp/loopman-mcp-client";
17
+ // Client exports
18
+ export { LoopmanApiClient } from "./client/loopman-api";
19
+ // Service exports (import from services/index.ts for centralized exports)
20
+ export * from "./services";
21
+ export { LoopmanConnectionError, LoopmanError, LoopmanTimeoutError, LoopmanValidationError, } from "./types";
22
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,qBAAqB;AACrB,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAOzD,+DAA+D;AAC/D,OAAO,EACL,kBAAkB,IAAI,yBAAyB,EAC/C,kBAAkB,IAAI,4BAA4B,EAClD,eAAe,EAAE,kDAAkD;AACnE,eAAe,GAChB,MAAM,yBAAyB,CAAC;AAEjC,wCAAwC;AACxC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAE1E,iBAAiB;AACjB,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,aAAa,GACd,MAAM,+BAA+B,CAAC;AAEvC,gBAAgB;AAChB,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE5D,iBAAiB;AACjB,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,0EAA0E;AAC1E,cAAc,YAAY,CAAC;AAW3B,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,SAAS,CAAC"}