@bubblelab/bubble-core 0.1.198 → 0.1.199

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 (112) hide show
  1. package/dist/bubble-bundle.d.ts +159 -157
  2. package/dist/bubbles/service-bubble/agi-inc.d.ts +80 -80
  3. package/dist/bubbles/service-bubble/ai-agent.d.ts +23 -16
  4. package/dist/bubbles/service-bubble/ai-agent.d.ts.map +1 -1
  5. package/dist/bubbles/service-bubble/ai-agent.js +213 -8
  6. package/dist/bubbles/service-bubble/ai-agent.js.map +1 -1
  7. package/dist/bubbles/service-bubble/airtable.d.ts +74 -74
  8. package/dist/bubbles/service-bubble/apify/actors/google-maps-scraper.d.ts +2 -2
  9. package/dist/bubbles/service-bubble/apify/actors/instagram-hashtag-scraper.d.ts +4 -4
  10. package/dist/bubbles/service-bubble/apify/actors/instagram-scraper.d.ts +12 -12
  11. package/dist/bubbles/service-bubble/apify/actors/linkedin-jobs-scraper.d.ts +2 -2
  12. package/dist/bubbles/service-bubble/apify/actors/linkedin-posts-search.d.ts +8 -8
  13. package/dist/bubbles/service-bubble/apify/actors/linkedin-profile-detail.d.ts +52 -52
  14. package/dist/bubbles/service-bubble/apify/actors/linkedin-profile-posts.d.ts +18 -18
  15. package/dist/bubbles/service-bubble/apify/actors/tiktok-scraper.d.ts +10 -10
  16. package/dist/bubbles/service-bubble/apify/actors/twitter-scraper.d.ts +27 -27
  17. package/dist/bubbles/service-bubble/apify/actors/youtube-scraper.d.ts +8 -8
  18. package/dist/bubbles/service-bubble/apify/apify-scraper.schema.d.ts +131 -131
  19. package/dist/bubbles/service-bubble/apify/apify.d.ts +8 -8
  20. package/dist/bubbles/service-bubble/ashby/ashby.d.ts +94 -94
  21. package/dist/bubbles/service-bubble/ashby/ashby.schema.d.ts +84 -84
  22. package/dist/bubbles/service-bubble/attio/attio.d.ts +28 -28
  23. package/dist/bubbles/service-bubble/attio/attio.schema.d.ts +28 -28
  24. package/dist/bubbles/service-bubble/browserbase/browserbase.d.ts +28 -28
  25. package/dist/bubbles/service-bubble/browserbase/browserbase.schema.d.ts +30 -30
  26. package/dist/bubbles/service-bubble/confluence/confluence.d.ts +24 -24
  27. package/dist/bubbles/service-bubble/confluence/confluence.schema.d.ts +24 -24
  28. package/dist/bubbles/service-bubble/crustdata/crustdata.d.ts +52 -52
  29. package/dist/bubbles/service-bubble/crustdata/crustdata.schema.d.ts +158 -158
  30. package/dist/bubbles/service-bubble/eleven-labs.d.ts +28 -28
  31. package/dist/bubbles/service-bubble/firecrawl.d.ts +1015 -1015
  32. package/dist/bubbles/service-bubble/followupboss.d.ts +140 -140
  33. package/dist/bubbles/service-bubble/fullenrich/fullenrich.d.ts +68 -68
  34. package/dist/bubbles/service-bubble/fullenrich/fullenrich.schema.d.ts +108 -108
  35. package/dist/bubbles/service-bubble/github.d.ts +156 -156
  36. package/dist/bubbles/service-bubble/gmail.d.ts +140 -140
  37. package/dist/bubbles/service-bubble/google-calendar.d.ts +218 -218
  38. package/dist/bubbles/service-bubble/google-drive.d.ts +92 -92
  39. package/dist/bubbles/service-bubble/google-sheets/google-sheets.d.ts +44 -44
  40. package/dist/bubbles/service-bubble/google-sheets/google-sheets.schema.d.ts +48 -48
  41. package/dist/bubbles/service-bubble/hello-world.d.ts +8 -8
  42. package/dist/bubbles/service-bubble/http.d.ts +12 -12
  43. package/dist/bubbles/service-bubble/hubspot/hubspot.d.ts +8 -8
  44. package/dist/bubbles/service-bubble/hubspot/hubspot.schema.d.ts +8 -8
  45. package/dist/bubbles/service-bubble/insforge-db.d.ts +8 -8
  46. package/dist/bubbles/service-bubble/jira/jira.d.ts +56 -56
  47. package/dist/bubbles/service-bubble/jira/jira.schema.d.ts +94 -94
  48. package/dist/bubbles/service-bubble/linear/linear.d.ts +32 -32
  49. package/dist/bubbles/service-bubble/linear/linear.schema.d.ts +32 -32
  50. package/dist/bubbles/service-bubble/notion/notion.d.ts +1627 -1627
  51. package/dist/bubbles/service-bubble/notion/property-schemas.d.ts +8 -8
  52. package/dist/bubbles/service-bubble/postgresql.d.ts +8 -8
  53. package/dist/bubbles/service-bubble/posthog/posthog.d.ts +20 -20
  54. package/dist/bubbles/service-bubble/posthog/posthog.schema.d.ts +26 -26
  55. package/dist/bubbles/service-bubble/resend.d.ts +28 -28
  56. package/dist/bubbles/service-bubble/sendsafely/sendsafely.d.ts +6 -6
  57. package/dist/bubbles/service-bubble/sendsafely/sendsafely.schema.d.ts +12 -12
  58. package/dist/bubbles/service-bubble/slack/slack.d.ts +340 -340
  59. package/dist/bubbles/service-bubble/storage.d.ts +20 -20
  60. package/dist/bubbles/service-bubble/stripe/stripe.d.ts +115 -115
  61. package/dist/bubbles/service-bubble/stripe/stripe.schema.d.ts +143 -143
  62. package/dist/bubbles/service-bubble/telegram.d.ts +1562 -1562
  63. package/dist/bubbles/tool-bubble/amazon-shopping-tool/amazon-shopping-tool.d.ts +13 -13
  64. package/dist/bubbles/tool-bubble/amazon-shopping-tool/amazon-shopping-tool.schema.d.ts +13 -13
  65. package/dist/bubbles/tool-bubble/browser-tools/_shared/schema.d.ts +2 -2
  66. package/dist/bubbles/tool-bubble/browser-tools/linkedin-accept-invitations/schema.d.ts +2 -2
  67. package/dist/bubbles/tool-bubble/browser-tools/linkedin-accept-invitations/tool.d.ts +2 -2
  68. package/dist/bubbles/tool-bubble/browser-tools/linkedin-connection/schema.d.ts +2 -2
  69. package/dist/bubbles/tool-bubble/browser-tools/linkedin-connection/tool.d.ts +2 -2
  70. package/dist/bubbles/tool-bubble/browser-tools/linkedin-received-invitations/schema.d.ts +2 -2
  71. package/dist/bubbles/tool-bubble/browser-tools/linkedin-received-invitations/tool.d.ts +2 -2
  72. package/dist/bubbles/tool-bubble/browser-tools/linkedin-sent-invitations/schema.d.ts +2 -2
  73. package/dist/bubbles/tool-bubble/browser-tools/linkedin-sent-invitations/tool.d.ts +2 -2
  74. package/dist/bubbles/tool-bubble/bubbleflow-validation-tool.d.ts +20 -20
  75. package/dist/bubbles/tool-bubble/chart-js-tool.d.ts +26 -26
  76. package/dist/bubbles/tool-bubble/code-edit-tool.d.ts +4 -4
  77. package/dist/bubbles/tool-bubble/code-edit-tool.d.ts.map +1 -1
  78. package/dist/bubbles/tool-bubble/code-edit-tool.js +17 -6
  79. package/dist/bubbles/tool-bubble/code-edit-tool.js.map +1 -1
  80. package/dist/bubbles/tool-bubble/company-enrichment-tool.d.ts +52 -52
  81. package/dist/bubbles/tool-bubble/get-bubble-details-tool.d.ts +4 -4
  82. package/dist/bubbles/tool-bubble/get-trigger-detail-tool.d.ts +4 -4
  83. package/dist/bubbles/tool-bubble/google-maps-tool.d.ts +4 -4
  84. package/dist/bubbles/tool-bubble/instagram-tool.d.ts +14 -14
  85. package/dist/bubbles/tool-bubble/linkedin-tool.d.ts +186 -186
  86. package/dist/bubbles/tool-bubble/list-airtable-bases-tool.d.ts +4 -4
  87. package/dist/bubbles/tool-bubble/list-airtable-tables-tool.d.ts +4 -4
  88. package/dist/bubbles/tool-bubble/list-bubbles-tool.d.ts +4 -4
  89. package/dist/bubbles/tool-bubble/list-capabilities-tool.d.ts +8 -8
  90. package/dist/bubbles/tool-bubble/people-search-tool.d.ts +48 -48
  91. package/dist/bubbles/tool-bubble/reddit-scrape-tool.d.ts +28 -28
  92. package/dist/bubbles/tool-bubble/research-agent-tool.d.ts +8 -8
  93. package/dist/bubbles/tool-bubble/sql-query-tool.d.ts +4 -4
  94. package/dist/bubbles/tool-bubble/tiktok-tool.d.ts +28 -28
  95. package/dist/bubbles/tool-bubble/tool-template.d.ts +4 -4
  96. package/dist/bubbles/tool-bubble/twitter-tool.d.ts +54 -54
  97. package/dist/bubbles/tool-bubble/web-crawl-tool.d.ts +18 -18
  98. package/dist/bubbles/tool-bubble/web-extract-tool.d.ts +4 -4
  99. package/dist/bubbles/tool-bubble/web-scrape-tool.d.ts +4 -4
  100. package/dist/bubbles/tool-bubble/web-search-tool.d.ts +8 -8
  101. package/dist/bubbles/tool-bubble/yc-scraper-tool.d.ts +18 -18
  102. package/dist/bubbles/tool-bubble/youtube-tool.d.ts +18 -18
  103. package/dist/bubbles/workflow-bubble/database-analyzer.workflow.d.ts +4 -4
  104. package/dist/bubbles/workflow-bubble/generate-document.workflow.d.ts +28 -28
  105. package/dist/bubbles/workflow-bubble/parse-document.workflow.d.ts +8 -8
  106. package/dist/bubbles/workflow-bubble/pdf-form-operations.workflow.d.ts +104 -104
  107. package/dist/bubbles/workflow-bubble/pdf-ocr.workflow.d.ts +16 -16
  108. package/dist/bubbles/workflow-bubble/slack-data-assistant.workflow.d.ts +34 -34
  109. package/dist/bubbles/workflow-bubble/slack-formatter-agent.d.ts +94 -94
  110. package/dist/bubbles/workflow-bubble/slack-notifier.workflow.d.ts +8 -8
  111. package/dist/bubbles.json +1 -1
  112. package/package.json +2 -2
@@ -52,8 +52,8 @@ declare const AIAgentParamsSchema: z.ZodObject<{
52
52
  }, {
53
53
  data: string;
54
54
  type?: "base64" | undefined;
55
- mimeType?: string | undefined;
56
55
  description?: string | undefined;
56
+ mimeType?: string | undefined;
57
57
  }>, z.ZodObject<{
58
58
  type: z.ZodLiteral<"url">;
59
59
  url: z.ZodString;
@@ -230,13 +230,13 @@ declare const AIAgentParamsSchema: z.ZodObject<{
230
230
  memoryEnabled: boolean;
231
231
  enableSlackHistory: boolean;
232
232
  name?: string | undefined;
233
+ credentials?: Partial<Record<CredentialType, string>> | undefined;
233
234
  conversationHistory?: {
234
235
  role: "user" | "assistant" | "tool";
235
236
  content: string;
236
237
  toolCallId?: string | undefined;
237
238
  name?: string | undefined;
238
239
  }[] | undefined;
239
- credentials?: Partial<Record<CredentialType, string>> | undefined;
240
240
  customTools?: {
241
241
  description: string;
242
242
  name: string;
@@ -252,11 +252,12 @@ declare const AIAgentParamsSchema: z.ZodObject<{
252
252
  }, {
253
253
  message: string;
254
254
  name?: string | undefined;
255
+ credentials?: Partial<Record<CredentialType, string>> | undefined;
255
256
  images?: ({
256
257
  data: string;
257
258
  type?: "base64" | undefined;
258
- mimeType?: string | undefined;
259
259
  description?: string | undefined;
260
+ mimeType?: string | undefined;
260
261
  } | {
261
262
  type: "url";
262
263
  url: string;
@@ -285,7 +286,6 @@ declare const AIAgentParamsSchema: z.ZodObject<{
285
286
  maxRetries?: number | undefined;
286
287
  } | undefined;
287
288
  } | undefined;
288
- credentials?: Partial<Record<CredentialType, string>> | undefined;
289
289
  tools?: {
290
290
  name: "get-bubble-details-tool" | "get-trigger-detail-tool" | "list-bubbles-tool" | "list-capabilities-tool" | "sql-query-tool" | "chart-js-tool" | "web-search-tool" | "web-scrape-tool" | "web-crawl-tool" | "web-extract-tool" | "research-agent-tool" | "reddit-scrape-tool" | "bubbleflow-validation-tool" | "code-edit-tool" | "instagram-tool" | "linkedin-tool" | "tiktok-tool" | "twitter-tool" | "google-maps-tool" | "youtube-tool" | "amazon-shopping-tool" | "people-search-tool";
291
291
  credentials?: Partial<Record<CredentialType, string>> | undefined;
@@ -329,6 +329,8 @@ declare const AIAgentResultSchema: z.ZodObject<{
329
329
  error: z.ZodString;
330
330
  success: z.ZodBoolean;
331
331
  }, "strip", z.ZodTypeAny, {
332
+ success: boolean;
333
+ error: string;
332
334
  response: string;
333
335
  toolCalls: {
334
336
  tool: string;
@@ -336,11 +338,11 @@ declare const AIAgentResultSchema: z.ZodObject<{
336
338
  output?: unknown;
337
339
  }[];
338
340
  iterations: number;
339
- error: string;
340
- success: boolean;
341
341
  reasoning?: string | null | undefined;
342
342
  totalCost?: number | undefined;
343
343
  }, {
344
+ success: boolean;
345
+ error: string;
344
346
  response: string;
345
347
  toolCalls: {
346
348
  tool: string;
@@ -348,8 +350,6 @@ declare const AIAgentResultSchema: z.ZodObject<{
348
350
  output?: unknown;
349
351
  }[];
350
352
  iterations: number;
351
- error: string;
352
- success: boolean;
353
353
  reasoning?: string | null | undefined;
354
354
  totalCost?: number | undefined;
355
355
  }>;
@@ -386,8 +386,8 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
386
386
  }, {
387
387
  data: string;
388
388
  type?: "base64" | undefined;
389
- mimeType?: string | undefined;
390
389
  description?: string | undefined;
390
+ mimeType?: string | undefined;
391
391
  }>, z.ZodObject<{
392
392
  type: z.ZodLiteral<"url">;
393
393
  url: z.ZodString;
@@ -564,13 +564,13 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
564
564
  memoryEnabled: boolean;
565
565
  enableSlackHistory: boolean;
566
566
  name?: string | undefined;
567
+ credentials?: Partial<Record<CredentialType, string>> | undefined;
567
568
  conversationHistory?: {
568
569
  role: "user" | "assistant" | "tool";
569
570
  content: string;
570
571
  toolCallId?: string | undefined;
571
572
  name?: string | undefined;
572
573
  }[] | undefined;
573
- credentials?: Partial<Record<CredentialType, string>> | undefined;
574
574
  customTools?: {
575
575
  description: string;
576
576
  name: string;
@@ -586,11 +586,12 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
586
586
  }, {
587
587
  message: string;
588
588
  name?: string | undefined;
589
+ credentials?: Partial<Record<CredentialType, string>> | undefined;
589
590
  images?: ({
590
591
  data: string;
591
592
  type?: "base64" | undefined;
592
- mimeType?: string | undefined;
593
593
  description?: string | undefined;
594
+ mimeType?: string | undefined;
594
595
  } | {
595
596
  type: "url";
596
597
  url: string;
@@ -619,7 +620,6 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
619
620
  maxRetries?: number | undefined;
620
621
  } | undefined;
621
622
  } | undefined;
622
- credentials?: Partial<Record<CredentialType, string>> | undefined;
623
623
  tools?: {
624
624
  name: "get-bubble-details-tool" | "get-trigger-detail-tool" | "list-bubbles-tool" | "list-capabilities-tool" | "sql-query-tool" | "chart-js-tool" | "web-search-tool" | "web-scrape-tool" | "web-crawl-tool" | "web-extract-tool" | "research-agent-tool" | "reddit-scrape-tool" | "bubbleflow-validation-tool" | "code-edit-tool" | "instagram-tool" | "linkedin-tool" | "tiktok-tool" | "twitter-tool" | "google-maps-tool" | "youtube-tool" | "amazon-shopping-tool" | "people-search-tool";
625
625
  credentials?: Partial<Record<CredentialType, string>> | undefined;
@@ -663,6 +663,8 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
663
663
  error: z.ZodString;
664
664
  success: z.ZodBoolean;
665
665
  }, "strip", z.ZodTypeAny, {
666
+ success: boolean;
667
+ error: string;
666
668
  response: string;
667
669
  toolCalls: {
668
670
  tool: string;
@@ -670,11 +672,11 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
670
672
  output?: unknown;
671
673
  }[];
672
674
  iterations: number;
673
- error: string;
674
- success: boolean;
675
675
  reasoning?: string | null | undefined;
676
676
  totalCost?: number | undefined;
677
677
  }, {
678
+ success: boolean;
679
+ error: string;
678
680
  response: string;
679
681
  toolCalls: {
680
682
  tool: string;
@@ -682,8 +684,6 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
682
684
  output?: unknown;
683
685
  }[];
684
686
  iterations: number;
685
- error: string;
686
- success: boolean;
687
687
  reasoning?: string | null | undefined;
688
688
  totalCost?: number | undefined;
689
689
  }>;
@@ -701,7 +701,14 @@ export declare class AIAgentBubble extends ServiceBubble<AIAgentParamsParsed, AI
701
701
  private shouldStopAfterTools;
702
702
  private shouldContinueToAgent;
703
703
  private rescueAttempts;
704
+ /** Current graph messages — kept in sync by executeToolsWithHooks so that
705
+ * the use-capability tool can snapshot master state before delegation. */
706
+ private _currentGraphMessages;
707
+ /** Emit a trace event via executionMeta._onTrace (if wired by the host). */
708
+ private _trace;
704
709
  private static readonly MAX_RESCUE_ATTEMPTS;
710
+ /** Max characters for a single tool result before truncation (~50k chars ≈ ~12k tokens). */
711
+ private static readonly MAX_TOOL_RESULT_CHARS;
705
712
  constructor(params?: AIAgentParams, context?: BubbleContext, instanceId?: string);
706
713
  testCredential(): Promise<boolean>;
707
714
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ai-agent.d.ts","sourceRoot":"","sources":["../../../src/bubb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;;OAIG;IACH,OAAO,CAAC,yBAAyB;IAgDjC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAuDvB;;OAEG;YACW,qBAAqB;YAwOrB,gBAAgB;YAwVhB,YAAY;CA0oB3B"}
@@ -309,7 +309,19 @@ export class AIAgentBubble extends ServiceBubble {
309
309
  shouldStopAfterTools = false;
310
310
  shouldContinueToAgent = false;
311
311
  rescueAttempts = 0;
312
+ /** Current graph messages — kept in sync by executeToolsWithHooks so that
313
+ * the use-capability tool can snapshot master state before delegation. */
314
+ _currentGraphMessages = [];
315
+ /** Emit a trace event via executionMeta._onTrace (if wired by the host). */
316
+ _trace(source, message, data) {
317
+ const onTrace = this.context?.executionMeta?._onTrace;
318
+ if (typeof onTrace === 'function') {
319
+ onTrace(source, message, data);
320
+ }
321
+ }
312
322
  static MAX_RESCUE_ATTEMPTS = 1;
323
+ /** Max characters for a single tool result before truncation (~50k chars ≈ ~12k tokens). */
324
+ static MAX_TOOL_RESULT_CHARS = 50_000;
313
325
  constructor(params = {
314
326
  message: 'Hello, how are you?',
315
327
  systemPrompt: 'You are a helpful AI assistant',
@@ -1056,6 +1068,22 @@ export class AIAgentBubble extends ServiceBubble {
1056
1068
  const capDef = getCapability(capabilityId);
1057
1069
  if (!capConfig || !capDef)
1058
1070
  return { error: `Capability "${capabilityId}" not found` };
1071
+ // Snapshot master agent state before delegation so that the
1072
+ // subagent's beforeToolCall hook can save both states if an
1073
+ // approval interrupt is triggered (fixes multi-cap state leak).
1074
+ const execMeta = this.context?.executionMeta;
1075
+ if (execMeta && this._currentGraphMessages.length > 0) {
1076
+ const { mapChatMessagesToStoredMessages } = await import('@langchain/core/messages');
1077
+ execMeta._masterAgentSnapshot = {
1078
+ messages: mapChatMessagesToStoredMessages(this._currentGraphMessages),
1079
+ capabilityId,
1080
+ capabilityTask: task,
1081
+ };
1082
+ this._trace('use-capability', `snapshotted master state before delegating`, {
1083
+ masterMsgCount: this._currentGraphMessages.length,
1084
+ capabilityId,
1085
+ });
1086
+ }
1059
1087
  const subAgent = new AIAgentBubble({
1060
1088
  message: task,
1061
1089
  systemPrompt: '', // capability's systemPrompt fills this via beforeAction
@@ -1065,6 +1093,16 @@ export class AIAgentBubble extends ServiceBubble {
1065
1093
  credentials: this.params.credentials,
1066
1094
  }, this.context, `capability-${capabilityId}`);
1067
1095
  const result = await subAgent.action();
1096
+ // Clean up snapshot after delegation completes
1097
+ if (execMeta) {
1098
+ delete execMeta._masterAgentSnapshot;
1099
+ }
1100
+ this._trace('use-capability', `subAgent returned`, {
1101
+ capabilityId,
1102
+ success: result.success,
1103
+ pendingApproval: !!execMeta?._pendingApproval,
1104
+ shouldStopAfterTools: this.shouldStopAfterTools,
1105
+ });
1068
1106
  if (!result.success) {
1069
1107
  return { success: false, error: result.error };
1070
1108
  }
@@ -1268,8 +1306,15 @@ export class AIAgentBubble extends ServiceBubble {
1268
1306
  const toolMessages = [];
1269
1307
  let currentMessages = [...messages];
1270
1308
  let hooksModifiedMessages = false;
1309
+ // Keep master snapshot in sync so use-capability can capture state
1310
+ this._currentGraphMessages = currentMessages;
1271
1311
  // Reset stop flag at the start of tool execution
1272
1312
  this.shouldStopAfterTools = false;
1313
+ this._trace('executeToolsWithHooks', `ENTRY`, {
1314
+ toolCallCount: toolCalls.length,
1315
+ toolCalls: toolCalls.map(tc => `${tc.name}(${tc.id?.slice(-8)})`).join(', '),
1316
+ totalMsgs: messages.length,
1317
+ });
1273
1318
  // Execute each tool call
1274
1319
  for (const toolCall of toolCalls) {
1275
1320
  const tool = tools.find((t) => t.name === toolCall.name);
@@ -1362,11 +1407,17 @@ export class AIAgentBubble extends ServiceBubble {
1362
1407
  }
1363
1408
  // Execute the tool
1364
1409
  const toolOutput = await tool.invoke(toolCall.args);
1365
- // Create tool message
1410
+ // Create tool message — cap result size to avoid blowing up LLM context
1411
+ let toolContent = typeof toolOutput === 'string'
1412
+ ? toolOutput
1413
+ : JSON.stringify(toolOutput);
1414
+ if (toolContent.length > AIAgentBubble.MAX_TOOL_RESULT_CHARS) {
1415
+ toolContent =
1416
+ toolContent.slice(0, AIAgentBubble.MAX_TOOL_RESULT_CHARS) +
1417
+ `\n\n[... truncated — result was ${toolContent.length} chars, limit is ${AIAgentBubble.MAX_TOOL_RESULT_CHARS}]`;
1418
+ }
1366
1419
  const toolMessage = new ToolMessage({
1367
- content: typeof toolOutput === 'string'
1368
- ? toolOutput
1369
- : JSON.stringify(toolOutput),
1420
+ content: toolContent,
1370
1421
  tool_call_id: toolCall.id,
1371
1422
  });
1372
1423
  toolMessages.push(toolMessage);
@@ -1447,6 +1498,17 @@ export class AIAgentBubble extends ServiceBubble {
1447
1498
  async createAgentGraph(llm, tools, systemPrompt) {
1448
1499
  // Define the agent node
1449
1500
  const agentNode = async ({ messages }) => {
1501
+ this._trace('agentNode', `LLM CALL`, {
1502
+ msgCount: messages.length,
1503
+ lastMsgType: messages[messages.length - 1]?._getType(),
1504
+ lastMsgPreview: (() => {
1505
+ const last = messages[messages.length - 1];
1506
+ if (!last)
1507
+ return '';
1508
+ const content = typeof last.content === 'string' ? last.content : JSON.stringify(last.content);
1509
+ return content.slice(0, 120);
1510
+ })(),
1511
+ });
1450
1512
  // systemPrompt is already enhanced by beforeAction() if expectedOutputSchema was provided
1451
1513
  // Use cache_control for Anthropic models to cache the system prompt across iterations
1452
1514
  const isAnthropic = llm instanceof ChatAnthropic;
@@ -1648,25 +1710,36 @@ export class AIAgentBubble extends ServiceBubble {
1648
1710
  const lastAIMessage = aiMessages[aiMessages.length - 1];
1649
1711
  // Check if the last AI message has tool calls
1650
1712
  if (lastAIMessage?.tool_calls && lastAIMessage.tool_calls.length > 0) {
1713
+ this._trace('afterLLMCheck', `→ tools`, {
1714
+ toolCalls: lastAIMessage.tool_calls.map(tc => `${tc.name}(${tc.id?.slice(-8)})`).join(', '),
1715
+ });
1651
1716
  return 'tools';
1652
1717
  }
1718
+ this._trace('afterLLMCheck', `→ __end__ (no tool calls)`);
1653
1719
  return '__end__';
1654
1720
  };
1655
1721
  // Define conditional edge after tools to check if we should stop
1656
1722
  const shouldContinueAfterTools = () => {
1723
+ const execMeta = this.context?.executionMeta;
1724
+ this._trace('shouldContinueAfterTools', `CHECK`, {
1725
+ shouldStop: this.shouldStopAfterTools,
1726
+ pendingApproval: !!execMeta?._pendingApproval,
1727
+ });
1657
1728
  // Check if the afterToolCall hook requested stopping
1658
1729
  if (this.shouldStopAfterTools) {
1730
+ this._trace('shouldContinueAfterTools', `→ __end__ (shouldStopAfterTools)`);
1659
1731
  return '__end__';
1660
1732
  }
1661
1733
  // Check for pending approval signal from sub-agent (shared via executionMeta).
1662
1734
  // In multi-capability mode the master and sub-agent share the same BubbleContext,
1663
1735
  // so a sub-agent setting _pendingApproval is visible here.
1664
- const execMeta = this.context?.executionMeta;
1665
1736
  if (execMeta?._pendingApproval) {
1737
+ this._trace('shouldContinueAfterTools', `→ __end__ (pendingApproval)`);
1666
1738
  this.shouldStopAfterTools = true;
1667
1739
  return '__end__';
1668
1740
  }
1669
1741
  // Otherwise continue back to agent
1742
+ this._trace('shouldContinueAfterTools', `→ agent (continue)`);
1670
1743
  return 'agent';
1671
1744
  };
1672
1745
  // Build the graph
@@ -1704,8 +1777,125 @@ export class AIAgentBubble extends ServiceBubble {
1704
1777
  let enrichedMessage;
1705
1778
  // Resume from saved agent state (lossless — preserves tool_calls, etc.)
1706
1779
  const resumeExecMeta = this.context?.executionMeta;
1780
+ const resumeStateV2 = resumeExecMeta?._resumeAgentStateV2;
1707
1781
  const resumeState = resumeExecMeta?._resumeAgentState;
1708
- if (resumeState && Array.isArray(resumeState) && resumeState.length > 0) {
1782
+ // Clear stale _pendingApproval ONLY when actually resuming, so that
1783
+ // non-resume executeAgent calls (e.g. personality reflection) don't
1784
+ // wipe the flag before postFlowAction reads it.
1785
+ if (resumeExecMeta && (resumeStateV2 || resumeState)) {
1786
+ delete resumeExecMeta._pendingApproval;
1787
+ }
1788
+ if (resumeStateV2 && resumeStateV2.__version === 2) {
1789
+ // V2: Multi-cap scoped resume — master and subagent states are separate.
1790
+ // Restore the master's messages, find the pending use-capability call,
1791
+ // inject the subagent's state so it resumes via the V1 path, then
1792
+ // execute the use-capability tool directly.
1793
+ this._trace('v2-resume', `START`, {
1794
+ masterMsgs: resumeStateV2.masterState.length,
1795
+ subagentMsgs: resumeStateV2.subagentState.length,
1796
+ capabilityId: resumeStateV2.capabilityId,
1797
+ task: resumeStateV2.capabilityTask?.slice(0, 80),
1798
+ });
1799
+ const { mapStoredMessagesToChatMessages } = await import('@langchain/core/messages');
1800
+ const masterRestored = mapStoredMessagesToChatMessages(resumeStateV2.masterState);
1801
+ // Collect existing tool results
1802
+ const existingToolResultIds = new Set();
1803
+ for (const msg of masterRestored) {
1804
+ if (msg._getType() === 'tool') {
1805
+ const tm = msg;
1806
+ if (tm.tool_call_id)
1807
+ existingToolResultIds.add(tm.tool_call_id);
1808
+ }
1809
+ }
1810
+ // Build tool lookup for direct execution
1811
+ const toolsByName = new Map();
1812
+ if (tools) {
1813
+ for (const t of tools)
1814
+ toolsByName.set(t.name, t);
1815
+ }
1816
+ // Inject the subagent's state so the use-capability tool's subagent
1817
+ // picks it up via the V1 resume path in its own executeAgent call.
1818
+ // IMPORTANT: Delete _resumeAgentStateV2 BEFORE tool.invoke() so the
1819
+ // subagent doesn't re-enter the V2 path (it shares executionMeta).
1820
+ if (resumeExecMeta) {
1821
+ resumeExecMeta._resumeAgentState = resumeStateV2.subagentState;
1822
+ delete resumeExecMeta._resumeAgentStateV2;
1823
+ }
1824
+ // Repair master messages: find the pending use-capability tool call
1825
+ // and execute it (which re-creates the subagent that resumes via V1).
1826
+ const repairedMessages = [];
1827
+ for (let i = 0; i < masterRestored.length; i++) {
1828
+ repairedMessages.push(masterRestored[i]);
1829
+ const msg = masterRestored[i];
1830
+ if (msg._getType() !== 'ai')
1831
+ continue;
1832
+ const aiMsg = msg;
1833
+ const pendingCalls = aiMsg.tool_calls?.filter((tc) => tc.id && !existingToolResultIds.has(tc.id));
1834
+ if (!pendingCalls?.length)
1835
+ continue;
1836
+ for (const tc of pendingCalls) {
1837
+ if (toolsByName.has(tc.name)) {
1838
+ try {
1839
+ this._trace('v2-resume', `executing tool "${tc.name}"`, {
1840
+ callId: tc.id,
1841
+ args: JSON.stringify(tc.args).slice(0, 200),
1842
+ });
1843
+ const tool = toolsByName.get(tc.name);
1844
+ // Sync _currentGraphMessages so use-capability can snapshot
1845
+ // master state for the subagent's beforeToolCall hook.
1846
+ // Without this, _masterAgentSnapshot is empty during V2 resume
1847
+ // and subsequent approvals fall to the V1 path, corrupting state.
1848
+ this._currentGraphMessages = [...repairedMessages];
1849
+ const result = await tool.invoke(tc.args);
1850
+ let content = typeof result === 'string' ? result : JSON.stringify(result);
1851
+ if (content.length > AIAgentBubble.MAX_TOOL_RESULT_CHARS) {
1852
+ content =
1853
+ content.slice(0, AIAgentBubble.MAX_TOOL_RESULT_CHARS) +
1854
+ `\n\n[... truncated — result was ${content.length} chars, limit is ${AIAgentBubble.MAX_TOOL_RESULT_CHARS}]`;
1855
+ }
1856
+ repairedMessages.push(new ToolMessage({ content, tool_call_id: tc.id }));
1857
+ }
1858
+ catch (err) {
1859
+ console.warn(`[AIAgent] V2 resume: tool execution failed for "${tc.name}":`, err);
1860
+ repairedMessages.push(new ToolMessage({
1861
+ content: `Tool execution failed: ${err instanceof Error ? err.message : String(err)}`,
1862
+ tool_call_id: tc.id,
1863
+ }));
1864
+ }
1865
+ }
1866
+ else {
1867
+ repairedMessages.push(new ToolMessage({
1868
+ content: 'This action has been approved by the user. You may now execute this tool.',
1869
+ tool_call_id: tc.id,
1870
+ }));
1871
+ }
1872
+ existingToolResultIds.add(tc.id);
1873
+ }
1874
+ }
1875
+ // Clean up remaining resume state and pre-approval flag so that
1876
+ // subsequent subagents (created by normal master loop) don't
1877
+ // accidentally pick up stale state.
1878
+ // Note: _resumeAgentStateV2 already deleted above (before tool.invoke).
1879
+ if (resumeExecMeta) {
1880
+ delete resumeExecMeta._resumeAgentState;
1881
+ delete resumeExecMeta._approvedAction;
1882
+ }
1883
+ this._trace('v2-resume', `DONE`, {
1884
+ repairedMessages: repairedMessages.length,
1885
+ types: repairedMessages.map((m) => m._getType()).join(','),
1886
+ pendingApproval: !!resumeExecMeta?._pendingApproval,
1887
+ shouldStopAfterTools: this.shouldStopAfterTools,
1888
+ });
1889
+ // If a new approval was triggered during V2 resume (subagent set _pendingApproval),
1890
+ // we should stop the master loop immediately to avoid re-executing.
1891
+ if (resumeExecMeta?._pendingApproval) {
1892
+ this._trace('v2-resume', `_pendingApproval detected — will stop master loop`);
1893
+ this.shouldStopAfterTools = true;
1894
+ }
1895
+ initialMessages.push(...repairedMessages);
1896
+ }
1897
+ else if (resumeState && Array.isArray(resumeState) && resumeState.length > 0) {
1898
+ this._trace('v1-resume', `restoring ${resumeState.length} messages (single-cap/subagent path)`);
1709
1899
  const { mapStoredMessagesToChatMessages } = await import('@langchain/core/messages');
1710
1900
  const restored = mapStoredMessagesToChatMessages(resumeState);
1711
1901
  // Collect existing tool_call_ids that already have ToolMessage responses
@@ -1757,7 +1947,12 @@ export class AIAgentBubble extends ServiceBubble {
1757
1947
  console.log(`[AIAgent] Resume: executing approved tool "${tc.name}" directly`);
1758
1948
  const tool = toolsByName.get(tc.name);
1759
1949
  const result = await tool.invoke(tc.args);
1760
- const content = typeof result === 'string' ? result : JSON.stringify(result);
1950
+ let content = typeof result === 'string' ? result : JSON.stringify(result);
1951
+ if (content.length > AIAgentBubble.MAX_TOOL_RESULT_CHARS) {
1952
+ content =
1953
+ content.slice(0, AIAgentBubble.MAX_TOOL_RESULT_CHARS) +
1954
+ `\n\n[... truncated — result was ${content.length} chars, limit is ${AIAgentBubble.MAX_TOOL_RESULT_CHARS}]`;
1955
+ }
1761
1956
  repairedMessages.push(new ToolMessage({ content, tool_call_id: tc.id }));
1762
1957
  }
1763
1958
  catch (err) {
@@ -1874,10 +2069,20 @@ export class AIAgentBubble extends ServiceBubble {
1874
2069
  // state (it was the HumanMessage that started the original execution).
1875
2070
  // Re-appending it causes the LLM to see the same request twice, which
1876
2071
  // triggers a duplicate tool call. Skip it when resuming.
1877
- if (!resumeState) {
2072
+ if (!resumeState && !resumeStateV2) {
1878
2073
  initialMessages.push(humanMessage);
1879
2074
  }
2075
+ this._trace('agent-loop', `STARTING graph.invoke`, {
2076
+ initialMsgCount: initialMessages.length,
2077
+ initialMsgTypes: initialMessages.map((m) => m._getType()).join(','),
2078
+ shouldStopAfterTools: this.shouldStopAfterTools,
2079
+ maxIterations,
2080
+ });
1880
2081
  const result = await graph.invoke({ messages: initialMessages }, { recursionLimit: maxIterations });
2082
+ this._trace('agent-loop', `graph.invoke COMPLETED`, {
2083
+ totalMessages: result.messages.length,
2084
+ pendingApproval: !!this.context?.executionMeta?._pendingApproval,
2085
+ });
1881
2086
  console.log('[AIAgent] Graph execution completed');
1882
2087
  console.log('[AIAgent] Total messages:', result.messages.length);
1883
2088
  iterations = result.messages.length;