@agent-native/core 0.133.0 → 0.133.2

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 (43) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +26 -0
  3. package/corpus/core/package.json +1 -1
  4. package/corpus/core/src/a2a/client.ts +22 -5
  5. package/corpus/core/src/agent/engine/ai-sdk-engine.ts +28 -0
  6. package/corpus/core/src/agent/run-store.ts +19 -4
  7. package/corpus/core/src/integrations/webhook-handler.ts +7 -0
  8. package/corpus/core/src/scripts/call-agent.ts +29 -2
  9. package/corpus/templates/content/app/components/editor/database/sidebar.tsx +1 -34
  10. package/corpus/templates/content/app/components/sidebar/DocumentSidebar.tsx +77 -3
  11. package/corpus/templates/content/app/components/sidebar/DocumentTreeItem.tsx +4 -211
  12. package/corpus/templates/content/changelog/2026-07-30-deleting-a-page-no-longer-leaves-the-content-sidebar-unrespo.md +6 -0
  13. package/corpus/templates/content/e2e/playwright.config.ts +2 -1
  14. package/dist/a2a/client.d.ts +9 -1
  15. package/dist/a2a/client.d.ts.map +1 -1
  16. package/dist/a2a/client.js +12 -4
  17. package/dist/a2a/client.js.map +1 -1
  18. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
  19. package/dist/agent/engine/ai-sdk-engine.js +24 -0
  20. package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
  21. package/dist/agent/run-store.d.ts.map +1 -1
  22. package/dist/agent/run-store.js +18 -3
  23. package/dist/agent/run-store.js.map +1 -1
  24. package/dist/collab/awareness.d.ts +2 -2
  25. package/dist/collab/awareness.d.ts.map +1 -1
  26. package/dist/collab/routes.d.ts +1 -1
  27. package/dist/collab/struct-routes.d.ts +1 -1
  28. package/dist/file-upload/actions/upload-image.d.ts +1 -1
  29. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  30. package/dist/integrations/webhook-handler.js +3 -0
  31. package/dist/integrations/webhook-handler.js.map +1 -1
  32. package/dist/notifications/routes.d.ts +3 -3
  33. package/dist/observability/routes.d.ts +3 -3
  34. package/dist/scripts/call-agent.d.ts.map +1 -1
  35. package/dist/scripts/call-agent.js +24 -2
  36. package/dist/scripts/call-agent.js.map +1 -1
  37. package/dist/server/transcribe-voice.d.ts +1 -1
  38. package/package.json +1 -1
  39. package/src/a2a/client.ts +22 -5
  40. package/src/agent/engine/ai-sdk-engine.ts +28 -0
  41. package/src/agent/run-store.ts +19 -4
  42. package/src/integrations/webhook-handler.ts +7 -0
  43. package/src/scripts/call-agent.ts +29 -2
@@ -11,14 +11,14 @@
11
11
  * DELETE /_agent-native/notifications/:id — delete
12
12
  */
13
13
  export declare function createNotificationsHandler(): import("h3").EventHandlerWithFetch<import("h3").EventHandlerRequest, Promise<"" | import("./types.js").Notification[] | {
14
- error?: undefined;
15
14
  count: number;
16
15
  updated?: undefined;
16
+ error?: undefined;
17
17
  ok?: undefined;
18
18
  } | {
19
- error?: undefined;
20
19
  count?: undefined;
21
20
  updated: number;
21
+ error?: undefined;
22
22
  ok?: undefined;
23
23
  } | {
24
24
  count?: undefined;
@@ -26,9 +26,9 @@ export declare function createNotificationsHandler(): import("h3").EventHandlerW
26
26
  error: string;
27
27
  ok?: undefined;
28
28
  } | {
29
- error?: undefined;
30
29
  count?: undefined;
31
30
  updated?: undefined;
31
+ error?: undefined;
32
32
  ok: boolean;
33
33
  }>>;
34
34
  //# sourceMappingURL=routes.d.ts.map
@@ -41,16 +41,16 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
41
41
  thumbsUpRate: number;
42
42
  avgEvalScore: number;
43
43
  } | {
44
- error?: undefined;
45
44
  summary: import("./types.js").TraceSummary;
46
45
  spans: import("./types.js").TraceSpan[];
47
46
  id?: undefined;
47
+ error?: undefined;
48
48
  ok?: undefined;
49
49
  } | {
50
- error?: undefined;
51
50
  summary?: undefined;
52
51
  spans?: undefined;
53
52
  id: string;
53
+ error?: undefined;
54
54
  ok?: undefined;
55
55
  } | {
56
56
  summary?: undefined;
@@ -59,10 +59,10 @@ export declare function createObservabilityHandler(): import("h3").EventHandlerW
59
59
  error: any;
60
60
  ok?: undefined;
61
61
  } | {
62
- error?: undefined;
63
62
  summary?: undefined;
64
63
  spans?: undefined;
65
64
  id?: undefined;
66
65
  ok: boolean;
66
+ error?: undefined;
67
67
  }>>;
68
68
  //# sourceMappingURL=routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAoPpD,eAAO,MAAM,IAAI,EAAE,UAsDlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CA+kBjB;AAqPD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
1
+ {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AA0QpD,eAAO,MAAM,IAAI,EAAE,UAsDlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC7B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAolBjB;AAqPD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
@@ -12,6 +12,7 @@ import { getRequestUserEmail, getRequestOrgId, getRequestRunContext, isIntegrati
12
12
  import { track } from "../tracking/registry.js";
13
13
  const DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;
14
14
  const NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;
15
+ const NETLIFY_INTEGRATION_A2A_SUBMISSION_TIMEOUT_MS = 15_000;
15
16
  const INTEGRATION_A2A_TOKEN_TTL = "30m";
16
17
  const A2A_INVOCATION_EVENT = "$a2a_invocation";
17
18
  function trackA2AInvocation(args) {
@@ -109,12 +110,28 @@ function parseTimeoutMs(value) {
109
110
  return undefined;
110
111
  return Math.floor(parsed);
111
112
  }
113
+ function hasExplicitNonHostedNetlifyOverride() {
114
+ return (process.env.NETLIFY_LOCAL === "true" || process.env.NETLIFY === "false");
115
+ }
116
+ function isNetlifyHostedRuntimeForIntegrationCall() {
117
+ if (hasExplicitNonHostedNetlifyOverride())
118
+ return false;
119
+ if (process.env.NETLIFY && process.env.NETLIFY !== "false")
120
+ return true;
121
+ // NETLIFY is a build-time marker, while deployed Netlify Functions expose
122
+ // SITE_ID at runtime. Recognize the same runtime-only marker used by the
123
+ // durable background and run-manager gates so the integration caller hands
124
+ // slow A2A work to durable delivery before its foreground budget expires.
125
+ return Boolean(process.env.SITE_ID); // guard:allow-env-credential -- Netlify's read-only public site identifier is a runtime host marker, not a user credential.
126
+ }
112
127
  function isServerlessHost() {
128
+ if (hasExplicitNonHostedNetlifyOverride())
129
+ return false;
113
130
  // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,
114
131
  // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —
115
132
  // the canonical signal is the `__cf_env`/`__env__` global injected by the
116
133
  // Cloudflare runtime adapter.
117
- return (!!process.env.NETLIFY ||
134
+ return (isNetlifyHostedRuntimeForIntegrationCall() ||
118
135
  !!process.env.AWS_LAMBDA_FUNCTION_NAME ||
119
136
  !!process.env.VERCEL ||
120
137
  "__cf_env" in globalThis ||
@@ -130,8 +147,9 @@ function getIntegrationCallTimeoutMs() {
130
147
  // calls very short so multi-agent integration requests queue downstream
131
148
  // continuations quickly instead of spending the parent Slack/email processor
132
149
  // budget waiting on separately deployed apps one-by-one.
133
- if (process.env.NETLIFY)
150
+ if (isNetlifyHostedRuntimeForIntegrationCall()) {
134
151
  return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;
152
+ }
135
153
  return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;
136
154
  }
137
155
  function integrationSourceContext() {
@@ -552,6 +570,9 @@ export async function run(args, context, selfAppId) {
552
570
  // Docker can wait for slow-but-valid answers; integration processors
553
571
  // still need to finish before their current function execution dies.
554
572
  const callTimeoutMs = getIntegrationCallTimeoutMs();
573
+ const submissionTimeoutMs = callTimeoutMs && isNetlifyHostedRuntimeForIntegrationCall()
574
+ ? NETLIFY_INTEGRATION_A2A_SUBMISSION_TIMEOUT_MS
575
+ : undefined;
555
576
  responseText = await callAgent(agent.url, messageWithHint, {
556
577
  apiKey,
557
578
  userEmail: callerEmail,
@@ -568,6 +589,7 @@ export async function run(args, context, selfAppId) {
568
589
  ...(callTimeoutMs
569
590
  ? {
570
591
  timeoutMs: callTimeoutMs,
592
+ ...(submissionTimeoutMs ? { submissionTimeoutMs } : {}),
571
593
  }
572
594
  : {}),
573
595
  });
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,mBAAmB,EACnB,6BAA6B,EAC7B,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAA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U,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,oDAAoD,EACpD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\n\nimport { parseA2AAgentActivityPart } from \"../a2a/activity.js\";\nimport {\n A2ATaskTimeoutError,\n MAX_A2A_CALLER_RESPONSE_CHARS,\n callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { MAX_A2A_DELEGATION_HOPS } from \"../a2a/correlation.js\";\nimport { invokeAgentAction } from \"../a2a/invoke.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContext,\n A2ASourceContextReference,\n Task,\n} from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport { trackingIdentityProperties } from \"../observability/tracking-identity.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n getRequestRunContext,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { track } from \"../tracking/registry.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\nconst A2A_INVOCATION_EVENT = \"$a2a_invocation\";\n\ntype A2AInvocationStatus = \"success\" | \"pending\" | \"error\";\n\nfunction trackA2AInvocation(args: {\n invocationId: string;\n callerApp?: string;\n targetApp: string;\n mode: \"message\" | \"task_poll\" | \"direct_action\";\n status: A2AInvocationStatus;\n startedAt: number;\n taskId?: string;\n terminalCode?: string;\n correlation: A2ACorrelationMetadata;\n}): void {\n try {\n track(\n A2A_INVOCATION_EVENT,\n {\n ...trackingIdentityProperties(),\n source: \"a2a_delegation\",\n invocation_id: args.invocationId,\n caller_app: args.callerApp ?? \"unknown\",\n target_app: args.targetApp,\n mode: args.mode,\n status: args.status,\n duration_ms: Math.max(0, Date.now() - args.startedAt),\n task_id: args.taskId,\n terminal_code: args.terminalCode,\n delegation_depth: args.correlation.delegationDepth,\n parent_run_id: args.correlation.parentRunId,\n parent_turn_id: args.correlation.parentTurnId,\n },\n { userId: getRequestUserEmail() },\n );\n } catch {\n // Tracking must never affect delegation.\n }\n}\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\n const self = normalizeAppHandle(selfAppId);\n const inheritedVisited = Array.isArray(context?.visitedApps)\n ? context.visitedApps.map(normalizeAppHandle).filter(Boolean)\n : [];\n const visitedApps = self\n ? [...new Set([...inheritedVisited, self])]\n : [...new Set(inheritedVisited)];\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n // The model this turn is actually running on, so a receiver with no model of\n // its own can match the user's selection instead of its own default. A\n // preference only — the receiver bounds it to its own engine's catalog.\n const callerModel = getRequestRunContext()?.model?.trim();\n return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\n ...(callerModel ? { callerModel } : {}),\n ...(context?.threadId ? { callerThreadId: context.threadId } : {}),\n ...(context?.runId ? { parentRunId: context.runId } : {}),\n ...(context?.turnId ? { parentTurnId: context.turnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n delegationDepth: Math.min(MAX_A2A_DELEGATION_HOPS, inheritedDepth + 1),\n ...(visitedApps.length > 0 ? { visitedApps } : {}),\n };\n}\n\nfunction normalizeAppHandle(value: unknown): string {\n return typeof value === \"string\"\n ? value\n .trim()\n .toLowerCase()\n .replace(/^agent-native-/, \"\")\n : \"\";\n}\n\nfunction terminalTaskError(value: unknown): {\n state: string;\n taskId?: string;\n responseText?: string;\n errorCode?: string;\n} | null {\n if (!value || typeof value !== \"object\") return null;\n const candidate = value as Record<string, unknown>;\n if (candidate.name !== \"A2ATaskTerminalError\") return null;\n return {\n state: String(candidate.state ?? \"failed\"),\n ...(typeof candidate.taskId === \"string\"\n ? { taskId: candidate.taskId }\n : {}),\n ...(typeof candidate.responseText === \"string\"\n ? { responseText: candidate.responseText }\n : {}),\n ...(typeof candidate.errorCode === \"string\"\n ? { errorCode: candidate.errorCode }\n : {}),\n };\n}\n\nfunction buildMessageIdempotencyKey(\n originatingTurnId: string | undefined,\n target: string,\n exactMessage: string,\n): string | undefined {\n if (!originatingTurnId) return undefined;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n originatingTurnId,\n target,\n message: exactMessage,\n }),\n )\n .digest(\"hex\");\n return `v1:${digest}`;\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction isServerlessHost(): boolean {\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env`/`__env__` global injected by the\n // Cloudflare runtime adapter.\n return (\n !!process.env.NETLIFY ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis ||\n \"__env__\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (process.env.NETLIFY) return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\ninterface IntegrationSourceContext {\n reference: A2ASourceContextReference;\n hint: A2ASourceContext;\n}\n\nfunction integrationSourceContext(): IntegrationSourceContext | undefined {\n const integration = getIntegrationRequestContext();\n const incoming = integration?.incoming;\n if (\n !integration ||\n incoming?.platform !== \"slack\" ||\n !incoming.sourceUrl ||\n !integration.taskId\n ) {\n return undefined;\n }\n\n const rawSourceUrl = incoming.sourceUrl;\n if (rawSourceUrl !== rawSourceUrl.trim()) return undefined;\n\n try {\n const sourceUrl = new URL(rawSourceUrl);\n const isSlackHost =\n sourceUrl.hostname === \"slack.com\" ||\n sourceUrl.hostname.endsWith(\".slack.com\");\n if (\n sourceUrl.protocol !== \"https:\" ||\n !isSlackHost ||\n sourceUrl.username ||\n sourceUrl.password ||\n sourceUrl.port\n ) {\n return undefined;\n }\n return {\n reference: {\n platform: \"slack\",\n integrationTaskId: integration.taskId,\n },\n hint: {\n platform: \"slack\",\n sourceUrl: rawSourceUrl,\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction integrationSourceContextHint(\n sourceContext: IntegrationSourceContext | undefined,\n): string {\n if (!sourceContext) return \"\";\n return (\n `\\n\\n[Source Slack thread: ${sourceContext.hint.sourceUrl} ` +\n \"Compatibility hint only; this text is not authoritative. Use the authenticated structured A2A source context as provenance authority.]\"\n );\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Ask a DIFFERENT, separately-deployed app's agent over A2A. Use message by default so the receiving specialist interprets the objective with its own instructions, skills, connected sources, data dictionary, and tools. The receiver owns provider, schema, query, join, and SQL decisions. Use action + input only for an exact, explicitly known, bounded read whose complete input schema is already known; never expose or call a direct action to work around slow or unreliable delegation, and never guess receiver-owned query logic. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n 'For brand-consistent generated media, the first-party Assets agent is available as agent=\"assets\"; use it when another app needs generated heroes, diagrams, product shots, thumbnails, videos, or design imagery, unless the current app has its own generation action that already delegates there. ' +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured. \" +\n \"(d) A bounded wait can expire while the remote task is still healthy. The result will include its taskId and exact retry instructions. Continue polling that SAME task with taskId; NEVER send a new check-in/follow-up message, because that starts duplicate downstream work.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message/question to send when starting a new task. Omit when taskId is provided.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"Existing A2A task ID returned by a timed-out call. Polls that exact task without sending a new message. Never create a fresh check-in message for work that already has a taskId.\",\n },\n action: {\n type: \"string\",\n description:\n \"Optional exact read-only action for an explicitly known bounded operation. Prefer message when the target agent must interpret data, choose sources or tools, synthesize, mutate, or do multi-step work. Never guess the action schema or send receiver-owned SQL.\",\n },\n input: {\n type: \"object\",\n description:\n \"Complete input object for action. The target app validates it and refuses actions that are not explicitly exposed read-only operations.\",\n additionalProperties: true,\n },\n approvedActions: {\n type: \"array\",\n description:\n \"Exact downstream tool calls the current user explicitly authorized in this chat. Never infer authorization or include a broader/different action.\",\n items: {\n type: \"object\",\n properties: {\n tool: { type: \"string\" },\n input: { type: \"object\", additionalProperties: true },\n },\n required: [\"tool\", \"input\"],\n },\n },\n },\n required: [\"agent\"],\n },\n};\n\nexport async function run(\n args: Record<string, unknown>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const agentIdOrName = String(args.agent ?? \"\");\n const message = String(args.message ?? \"\");\n const taskId = String(args.taskId ?? \"\").trim();\n const action = String(args.action ?? \"\").trim();\n const input = args.input ?? {};\n const approvedActions = Array.isArray(args.approvedActions)\n ? (args.approvedActions as A2AApprovedAction[])\n : undefined;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message && !taskId && !action) {\n return \"Error: --message, --taskId, or --action is required\";\n }\n if (action && (message || taskId)) {\n return \"Error: --action direct-invoke mode cannot be combined with --message or --taskId\";\n }\n if (action && (!input || typeof input !== \"object\" || Array.isArray(input))) {\n return \"Error: --input must be an object when --action is provided\";\n }\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n if (!taskId && inheritedDepth >= MAX_A2A_DELEGATION_HOPS) {\n return (\n `Error: Cross-app delegation stopped at the ${MAX_A2A_DELEGATION_HOPS}-hop limit. ` +\n \"Finish with the results already collected instead of starting another agent.\"\n );\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n if (!taskId) {\n const visited = new Set(\n (context?.visitedApps ?? []).map(normalizeAppHandle).filter(Boolean),\n );\n const self = normalizeAppHandle(selfAppId);\n if (self) visited.add(self);\n const targetHandles = [\n normalizeAppHandle((agent as { id?: string }).id),\n normalizeAppHandle(agent.name),\n normalizeAppHandle(agentIdOrName),\n ].filter(Boolean);\n const repeated = targetHandles.find((handle) => visited.has(handle));\n if (repeated) {\n return (\n `Error: Cross-app delegation cycle blocked before calling ${agent.name}. ` +\n `The request already visited ${[...visited].join(\" -> \")}.`\n );\n }\n }\n\n const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n const targetApp =\n normalizeAppHandle((agent as { id?: string }).id) ||\n normalizeAppHandle(agent.name) ||\n normalizeAppHandle(agentIdOrName) ||\n \"unknown\";\n\n if (action) {\n const agentCallId = randomUUID();\n const startedAt = Date.now();\n let terminalStatus: \"done\" | \"error\" = \"done\";\n let terminalCode: string | undefined;\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n }\n try {\n const output = await invokeReadOnlyAppAction(\n agent,\n action,\n input as Record<string, unknown>,\n buildDelegationCorrelation(context, selfAppId, randomUUID()),\n );\n if (/^Error\\b/i.test(output)) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n }\n if (context?.send && output) {\n context.send({\n type: \"agent_call_text\",\n agent: agent.name,\n text: output,\n agentCallId,\n });\n }\n return output;\n } catch (error) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n throw error;\n } finally {\n trackA2AInvocation({\n invocationId: agentCallId,\n callerApp: selfAppId,\n targetApp,\n mode: \"direct_action\",\n status: terminalStatus === \"done\" ? \"success\" : \"error\",\n startedAt,\n terminalCode,\n correlation,\n });\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n durationMs: Date.now() - startedAt,\n });\n }\n }\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const sourceContext = integrationSourceContext();\n const messageWithHint = taskId\n ? \"\"\n : `${message}${integrationSourceContextHint(sourceContext)}\\n\\n` +\n `<a2a-caller-hint>\\n` +\n `This request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts. ` +\n `Return a concise caller-ready synthesis rather than raw tool output or full transcripts; preserve source counts, IDs, short supporting quotes, and URLs needed to substantiate the answer.\\n` +\n `</a2a-caller-hint>`;\n\n const invocationId = randomUUID();\n const invocationStartedAt = Date.now();\n let invocationStatus: A2AInvocationStatus = \"error\";\n let invocationTaskId = taskId || undefined;\n let invocationTerminalCode: string | undefined;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: shouldPreferGlobalA2ASecret(callerOrgSecret),\n },\n );\n } catch {}\n }\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const agentCallId = randomUUID();\n let terminalStatus: \"done\" | \"pending\" | \"error\" = \"done\";\n const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) {\n invocationStatus = \"pending\";\n invocationTerminalCode = \"existing_continuation\";\n return existingContinuationText;\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n agentCallId,\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is that cross-app activity arrives at the poll cadence rather\n // than token-by-token. Agent Native peers attach their current reasoning,\n // tool status, and response preview to each task checkpoint, and the\n // receiver's full response still surfaces below.\n //\n // That trade-off has a second-order cost: callAgent()'s poll (see\n // A2AClient.sendAndWait in a2a/client.ts) can legitimately run for\n // minutes with nothing emitted to the parent between the \"start\" event\n // above and \"done\" below. On the parent run, that silence freezes\n // `last_progress_at` — shouldBumpProgressForEvent in\n // agent/run-manager.ts treats a stream of literally nothing as no\n // progress — which trips the client's stuck-detector\n // (DEFAULT_STUCK_THRESHOLD_MS = 90_000 in\n // client/use-run-stuck-detection.ts) and the server's stale-run sweep\n // (BACKGROUND_RUN_STALE_MS = 90_000 in agent/run-store.ts). In\n // production this handed users a \"still working, no progress\" Retry\n // button that aborted a perfectly healthy call and re-ran the sub-agent\n // from scratch.\n //\n // Fix: surface the REAL remote liveness the poll already gathers. The\n // A2A poll round-trips to the remote agent every ~2s and gets back a\n // task with `status.state` (see A2AClient.sendAndWait / `onUpdate`). We\n // emit an `agent_call_progress` event ONLY from that callback, and ONLY\n // when a poll actually succeeds AND reports an actively-working state.\n // Crucially this is NOT a timer: if the remote hangs or dies, the poll\n // fetch throws, `onUpdate` stops firing, we emit nothing, and the\n // stuck-detector correctly surfaces its banner. A wall-clock heartbeat\n // would instead keep a dead sub-agent looking alive forever — trading a\n // false stuck-positive for a worse false stuck-negative.\n //\n // Throttle: the poll runs every ~2s but both thresholds above are 90s,\n // so emitting per-poll would be ~45 events per stuck-window. We coalesce\n // to at most one emission per 30s — a 3x margin under 90s, so at least\n // two land inside either window even with jitter, without flooding.\n //\n // Shape: a dedicated `agent_call_progress` event type (see\n // agent/types.ts), not an extra `agent_call` status. `agent_call`\n // consumers (production-agent.ts's step summarizer, slack.ts's task\n // cards) render any status that isn't \"start\"/\"done\" as a failure, so a\n // \"progress\" status would surface an in-flight tick as an error. A\n // distinct type is instead ignored gracefully everywhere: the run-event\n // switches fall to their `default`, the client if-chains fall through,\n // and sse-event-processor returns `{action:\"continue\"}`. It still counts\n // as real progress in shouldBumpProgressForEvent (any non-special event\n // type does), which is the whole point.\n const PROGRESS_MIN_INTERVAL_MS = 30_000;\n // Terminal states resolve the poll; \"input-required\" means the remote is\n // blocked waiting on us, not making progress. Only actively-working\n // states count as liveness worth surfacing.\n const ACTIVELY_WORKING_STATES = new Set([\n \"working\",\n \"submitted\",\n \"processing\",\n ]);\n const callStartedAt = Date.now();\n let lastProgressEmitAt = callStartedAt;\n let lastActivitySequence = -1;\n const onRemotePollUpdate = (task: Task) => {\n const state = task?.status?.state;\n const parts = task.status?.message?.parts;\n const snapshot = Array.isArray(parts)\n ? parts.map(parseA2AAgentActivityPart).find((value) => value !== null)\n : undefined;\n if (snapshot && snapshot.sequence > lastActivitySequence) {\n lastActivitySequence = snapshot.sequence;\n context.send!({\n type: \"agent_call_activity\",\n agent: agent.name,\n agentCallId,\n snapshot,\n });\n }\n if (!state || !ACTIVELY_WORKING_STATES.has(state)) return;\n const now = Date.now();\n if (now - lastProgressEmitAt < PROGRESS_MIN_INTERVAL_MS) return;\n lastProgressEmitAt = now;\n const detail = extractRemoteProgressDetail(task);\n context.send!({\n type: \"agent_call_progress\",\n agent: agent.name,\n state,\n elapsedSeconds: Math.round((now - callStartedAt) / 1000),\n agentCallId,\n ...(detail ? { detail } : {}),\n });\n };\n\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n onUpdate: onRemotePollUpdate,\n returnRecoverableArtifactsOnTimeout: false,\n ...(callTimeoutMs\n ? {\n timeoutMs: callTimeoutMs,\n }\n : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n terminalStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n // The normal integration path must preserve the timeout task id so\n // it can enqueue a durable continuation. If that enqueue fails,\n // do not hide receiver-verified artifacts that were already\n // returned with the last poll; this mirrors callAgent's default\n // timeout behavior without treating arbitrary remote status text\n // as a completed response.\n const recoverableArtifactText =\n extractRecoverableTimeoutArtifactText(pollErr);\n if (recoverableArtifactText) {\n responseText = expandRelativeUrls(\n recoverableArtifactText,\n agent.url,\n );\n } else {\n responseText = formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n }\n } else if (terminalTaskError(pollErr)?.state === \"input-required\") {\n terminalStatus = \"pending\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n responseText = formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n } else if (terminalTaskError(pollErr)) {\n terminalStatus = \"error\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n const detail = expandRelativeUrls(\n terminal.responseText ?? pollErr?.message ?? \"unknown failure\",\n agent.url,\n );\n responseText =\n `Error: The ${agent.name} agent ended ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (detail ? `: ${detail}` : \"\");\n } else {\n terminalStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `Error: The ${agent.name} agent call failed. (${reason})`;\n }\n }\n\n if (!responseText && terminalStatus === \"done\") {\n terminalStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n }\n if (responseText.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n terminalStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n responseText =\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\";\n }\n invocationStatus =\n terminalStatus === \"done\"\n ? \"success\"\n : terminalStatus === \"pending\"\n ? \"pending\"\n : \"error\";\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n ...(invocationTaskId ? { taskId: invocationTaskId } : {}),\n durationMs: Date.now() - callStartedAt,\n });\n\n return (\n responseText || `Error: The ${agent.name} agent returned no result.`\n );\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context?.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n returnRecoverableArtifactsOnTimeout: false,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n const expanded = expandRelativeUrls(sanitized, agent.url);\n if (!expanded) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n return \"Error: The remote agent returned no result.\";\n }\n if (expanded.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n return (\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\"\n );\n }\n invocationStatus = \"success\";\n return expanded;\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n const terminal = terminalTaskError(err);\n if (terminal?.state === \"input-required\") {\n invocationStatus = \"pending\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n return formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n }\n if (terminal) {\n invocationStatus = \"error\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n return (\n `Error calling ${agent.name}: remote task ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (terminal.responseText ? `: ${terminal.responseText}` : \"\")\n );\n }\n const timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\n invocationStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n return formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"timeout_without_task\";\n return `Error calling ${agent.name}: the remote request timed out before a task id could be recovered.`;\n }\n invocationStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n return `Error calling ${agent.name}: ${msg}`;\n } finally {\n trackA2AInvocation({\n invocationId,\n callerApp: selfAppId,\n targetApp,\n mode: taskId ? \"task_poll\" : \"message\",\n status: invocationStatus,\n startedAt: invocationStartedAt,\n taskId: invocationTaskId,\n terminalCode: invocationTerminalCode,\n correlation,\n });\n }\n}\n\nasync function invokeReadOnlyAppAction(\n agent: { name: string; url: string },\n action: string,\n input: Record<string, unknown>,\n correlation: A2ACorrelationMetadata,\n): Promise<string> {\n const callerEmail = getRequestUserEmail();\n if (!callerEmail) {\n return `Error calling ${agent.name} action ${action}: a signed-in user identity is required`;\n }\n\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n callerOrgDomain = (await getOrgDomain(orgId)) ?? undefined;\n } catch {}\n try {\n callerOrgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {}\n }\n\n if (!callerOrgSecret && !process.env.A2A_SECRET) {\n return `Error calling ${agent.name} action ${action}: direct cross-app reads require A2A identity verification`;\n }\n\n try {\n const invocation = await invokeAgentAction({\n target: agent.url,\n action,\n input,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n correlation,\n });\n return invocation.result.status === \"completed\"\n ? invocation.result.output\n : `Error calling ${agent.name} action ${action}: ${invocation.result.output}`;\n } catch (error) {\n return `Error calling ${agent.name} action ${action}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n}\n\nfunction formatExistingTaskWaitInstruction(\n agentName: string,\n taskId: string,\n agentIdOrName: string,\n): string {\n return (\n `The ${agentName} task is still running under taskId \"${taskId}\". ` +\n `Do not send ${agentName} a new check-in or follow-up message; that would start duplicate work. ` +\n `Call call-agent again with agent=\"${agentIdOrName}\" and taskId=\"${taskId}\" (omit message) to continue waiting for this same task.`\n );\n}\n\nfunction formatInputRequiredWaitInstruction(\n agentName: string,\n terminal: {\n taskId?: string;\n responseText?: string;\n },\n agentIdOrName: string,\n): string {\n const detail = terminal.responseText?.trim();\n if (!terminal.taskId) {\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `Pending: The ${agentName} agent needs input before it can continue.`\n );\n }\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `The ${agentName} agent is waiting for input under taskId \"${terminal.taskId}\". ` +\n `After providing or approving the requested input, call call-agent with agent=\"${agentIdOrName}\" and taskId=\"${terminal.taskId}\" (omit message) to continue this same task. Do not start a new message for this work.`\n );\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n progressRef: integration.progressRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Pull a short human-readable detail from a polled A2A task's status message,\n// when the remote includes one, so the progress event can surface a real\n// signal (e.g. \"Generating hero image…\") instead of a bare elapsed counter.\n// Bounded so a chatty remote can't push a large payload through the event.\nconst MAX_PROGRESS_DETAIL_CHARS = 200;\nfunction extractRemoteProgressDetail(task: Task): string | undefined {\n const parts = task.status?.message?.parts;\n if (!Array.isArray(parts)) return undefined;\n const text = parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!text) return undefined;\n return text.length > MAX_PROGRESS_DETAIL_CHARS\n ? `${text.slice(0, MAX_PROGRESS_DETAIL_CHARS - 1)}…`\n : text;\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\n/**\n * Mirrors the A2A client's default timeout recovery for the exceptional case\n * where an integration cannot enqueue a durable continuation. Only an\n * explicitly receiver-marked task message is safe to surface as a completed\n * partial result; ordinary working-state text remains a timeout failure.\n */\nfunction extractRecoverableTimeoutArtifactText(err: unknown): string {\n const candidate = err as\n | { lastTask?: Task | unknown; name?: unknown }\n | null\n | undefined;\n const lastTask =\n err instanceof A2ATaskTimeoutError\n ? err.lastTask\n : candidate?.name === \"A2ATaskTimeoutError\"\n ? (candidate.lastTask as Task | undefined)\n : undefined;\n const message = lastTask?.status?.message;\n if (!message?.metadata?.agentNativeRecoverableArtifacts) return \"\";\n\n return message.parts\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
1
+ {"version":3,"file":"call-agent.js","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,mBAAmB,EACnB,6BAA6B,EAC7B,SAAS,EACT,2BAA2B,EAC3B,YAAY,GACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAQrD,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,GACrB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAC5F,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,mBAAmB,EACnB,eAAe,EACf,oBAAo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,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,uDAAuD,EAAE,GAAG,CAAC,CAAC;QAC5E,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,mCAAmC,CAAC,OAAe;IAC1D,MAAM,UAAU,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACvD,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAC7E,2EAA2E;AAC3E,4EAA4E;AAC5E,4CAA4C;AAC5C,MAAM,UAAU,kBAAkB,CAAC,IAAY,EAAE,QAAgB;IAC/D,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ;QAAE,OAAO,IAAI,CAAC;IACpC,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACzC,4EAA4E;IAC5E,8EAA8E;IAC9E,OAAO,IAAI,CAAC,OAAO,CACjB,oDAAoD,EACpD,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,EAAE,CAChD,CAAC;AACJ,CAAC","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\n\nimport { parseA2AAgentActivityPart } from \"../a2a/activity.js\";\nimport {\n A2ATaskTimeoutError,\n MAX_A2A_CALLER_RESPONSE_CHARS,\n callAgent,\n shouldPreferGlobalA2ASecret,\n signA2AToken,\n} from \"../a2a/client.js\";\nimport { MAX_A2A_DELEGATION_HOPS } from \"../a2a/correlation.js\";\nimport { invokeAgentAction } from \"../a2a/invoke.js\";\nimport type {\n A2AApprovedAction,\n A2ACorrelationMetadata,\n A2ASourceContext,\n A2ASourceContextReference,\n Task,\n} from \"../a2a/types.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { ActionRunContext } from \"../agent/production-agent.js\";\nimport type { ActionTool } from \"../agent/types.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"../integrations/a2a-continuation-marker.js\";\nimport { trackingIdentityProperties } from \"../observability/tracking-identity.js\";\nimport { getOrgDomain, getOrgA2ASecret } from \"../org/context.js\";\nimport { findAgent, discoverAgents } from \"../server/agent-discovery.js\";\nimport {\n getRequestUserEmail,\n getRequestOrgId,\n getRequestRunContext,\n isIntegrationCallerRequest,\n getIntegrationRequestContext,\n} from \"../server/request-context.js\";\nimport { track } from \"../tracking/registry.js\";\n\nconst DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS = 18_000;\nconst NETLIFY_INTEGRATION_A2A_TIMEOUT_MS = 2_000;\nconst NETLIFY_INTEGRATION_A2A_SUBMISSION_TIMEOUT_MS = 15_000;\nconst INTEGRATION_A2A_TOKEN_TTL = \"30m\";\nconst A2A_INVOCATION_EVENT = \"$a2a_invocation\";\n\ntype A2AInvocationStatus = \"success\" | \"pending\" | \"error\";\n\nfunction trackA2AInvocation(args: {\n invocationId: string;\n callerApp?: string;\n targetApp: string;\n mode: \"message\" | \"task_poll\" | \"direct_action\";\n status: A2AInvocationStatus;\n startedAt: number;\n taskId?: string;\n terminalCode?: string;\n correlation: A2ACorrelationMetadata;\n}): void {\n try {\n track(\n A2A_INVOCATION_EVENT,\n {\n ...trackingIdentityProperties(),\n source: \"a2a_delegation\",\n invocation_id: args.invocationId,\n caller_app: args.callerApp ?? \"unknown\",\n target_app: args.targetApp,\n mode: args.mode,\n status: args.status,\n duration_ms: Math.max(0, Date.now() - args.startedAt),\n task_id: args.taskId,\n terminal_code: args.terminalCode,\n delegation_depth: args.correlation.delegationDepth,\n parent_run_id: args.correlation.parentRunId,\n parent_turn_id: args.correlation.parentTurnId,\n },\n { userId: getRequestUserEmail() },\n );\n } catch {\n // Tracking must never affect delegation.\n }\n}\n\nfunction buildDelegationCorrelation(\n context: ActionRunContext | undefined,\n selfAppId: string | undefined,\n invocationId?: string,\n): A2ACorrelationMetadata {\n const self = normalizeAppHandle(selfAppId);\n const inheritedVisited = Array.isArray(context?.visitedApps)\n ? context.visitedApps.map(normalizeAppHandle).filter(Boolean)\n : [];\n const visitedApps = self\n ? [...new Set([...inheritedVisited, self])]\n : [...new Set(inheritedVisited)];\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n // The model this turn is actually running on, so a receiver with no model of\n // its own can match the user's selection instead of its own default. A\n // preference only — the receiver bounds it to its own engine's catalog.\n const callerModel = getRequestRunContext()?.model?.trim();\n return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\n ...(callerModel ? { callerModel } : {}),\n ...(context?.threadId ? { callerThreadId: context.threadId } : {}),\n ...(context?.runId ? { parentRunId: context.runId } : {}),\n ...(context?.turnId ? { parentTurnId: context.turnId } : {}),\n ...(invocationId ? { invocationId } : {}),\n delegationDepth: Math.min(MAX_A2A_DELEGATION_HOPS, inheritedDepth + 1),\n ...(visitedApps.length > 0 ? { visitedApps } : {}),\n };\n}\n\nfunction normalizeAppHandle(value: unknown): string {\n return typeof value === \"string\"\n ? value\n .trim()\n .toLowerCase()\n .replace(/^agent-native-/, \"\")\n : \"\";\n}\n\nfunction terminalTaskError(value: unknown): {\n state: string;\n taskId?: string;\n responseText?: string;\n errorCode?: string;\n} | null {\n if (!value || typeof value !== \"object\") return null;\n const candidate = value as Record<string, unknown>;\n if (candidate.name !== \"A2ATaskTerminalError\") return null;\n return {\n state: String(candidate.state ?? \"failed\"),\n ...(typeof candidate.taskId === \"string\"\n ? { taskId: candidate.taskId }\n : {}),\n ...(typeof candidate.responseText === \"string\"\n ? { responseText: candidate.responseText }\n : {}),\n ...(typeof candidate.errorCode === \"string\"\n ? { errorCode: candidate.errorCode }\n : {}),\n };\n}\n\nfunction buildMessageIdempotencyKey(\n originatingTurnId: string | undefined,\n target: string,\n exactMessage: string,\n): string | undefined {\n if (!originatingTurnId) return undefined;\n const digest = createHash(\"sha256\")\n .update(\n JSON.stringify({\n originatingTurnId,\n target,\n message: exactMessage,\n }),\n )\n .digest(\"hex\");\n return `v1:${digest}`;\n}\n\nfunction parseTimeoutMs(value: string | undefined): number | undefined {\n if (!value) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) return undefined;\n return Math.floor(parsed);\n}\n\nfunction hasExplicitNonHostedNetlifyOverride(): boolean {\n return (\n process.env.NETLIFY_LOCAL === \"true\" || process.env.NETLIFY === \"false\"\n );\n}\n\nfunction isNetlifyHostedRuntimeForIntegrationCall(): boolean {\n if (hasExplicitNonHostedNetlifyOverride()) return false;\n if (process.env.NETLIFY && process.env.NETLIFY !== \"false\") return true;\n\n // NETLIFY is a build-time marker, while deployed Netlify Functions expose\n // SITE_ID at runtime. Recognize the same runtime-only marker used by the\n // durable background and run-manager gates so the integration caller hands\n // slow A2A work to durable delivery before its foreground budget expires.\n return Boolean(process.env.SITE_ID); // guard:allow-env-credential -- Netlify's read-only public site identifier is a runtime host marker, not a user credential.\n}\n\nfunction isServerlessHost(): boolean {\n if (hasExplicitNonHostedNetlifyOverride()) return false;\n\n // Detection mirrors db/migrations.ts:297-301. On Cloudflare Workers/Pages,\n // `process.env` is shimmed and CF_PAGES isn't reliably populated at runtime —\n // the canonical signal is the `__cf_env`/`__env__` global injected by the\n // Cloudflare runtime adapter.\n return (\n isNetlifyHostedRuntimeForIntegrationCall() ||\n !!process.env.AWS_LAMBDA_FUNCTION_NAME ||\n !!process.env.VERCEL ||\n \"__cf_env\" in globalThis ||\n \"__env__\" in globalThis\n );\n}\n\nfunction getIntegrationCallTimeoutMs(): number | undefined {\n if (!isServerlessHost() || !isIntegrationCallerRequest()) return undefined;\n\n const configured = parseTimeoutMs(\n process.env.AGENT_NATIVE_INTEGRATION_A2A_TIMEOUT_MS,\n );\n if (configured !== undefined) return configured;\n\n // Netlify's current synchronous function budget is 60s. Keep delegated\n // calls very short so multi-agent integration requests queue downstream\n // continuations quickly instead of spending the parent Slack/email processor\n // budget waiting on separately deployed apps one-by-one.\n if (isNetlifyHostedRuntimeForIntegrationCall()) {\n return NETLIFY_INTEGRATION_A2A_TIMEOUT_MS;\n }\n\n return DEFAULT_SERVERLESS_INTEGRATION_A2A_TIMEOUT_MS;\n}\n\ninterface IntegrationSourceContext {\n reference: A2ASourceContextReference;\n hint: A2ASourceContext;\n}\n\nfunction integrationSourceContext(): IntegrationSourceContext | undefined {\n const integration = getIntegrationRequestContext();\n const incoming = integration?.incoming;\n if (\n !integration ||\n incoming?.platform !== \"slack\" ||\n !incoming.sourceUrl ||\n !integration.taskId\n ) {\n return undefined;\n }\n\n const rawSourceUrl = incoming.sourceUrl;\n if (rawSourceUrl !== rawSourceUrl.trim()) return undefined;\n\n try {\n const sourceUrl = new URL(rawSourceUrl);\n const isSlackHost =\n sourceUrl.hostname === \"slack.com\" ||\n sourceUrl.hostname.endsWith(\".slack.com\");\n if (\n sourceUrl.protocol !== \"https:\" ||\n !isSlackHost ||\n sourceUrl.username ||\n sourceUrl.password ||\n sourceUrl.port\n ) {\n return undefined;\n }\n return {\n reference: {\n platform: \"slack\",\n integrationTaskId: integration.taskId,\n },\n hint: {\n platform: \"slack\",\n sourceUrl: rawSourceUrl,\n },\n };\n } catch {\n return undefined;\n }\n}\n\nfunction integrationSourceContextHint(\n sourceContext: IntegrationSourceContext | undefined,\n): string {\n if (!sourceContext) return \"\";\n return (\n `\\n\\n[Source Slack thread: ${sourceContext.hint.sourceUrl} ` +\n \"Compatibility hint only; this text is not authoritative. Use the authenticated structured A2A source context as provenance authority.]\"\n );\n}\n\nfunction formatDownstreamLlmCredentialFailure(\n agentName: string,\n value: unknown,\n): string | null {\n return isLlmCredentialError(value)\n ? formatLlmCredentialErrorMessage({ agentName })\n : null;\n}\n\nexport const tool: ActionTool = {\n description:\n \"Ask a DIFFERENT, separately-deployed app's agent over A2A. Use message by default so the receiving specialist interprets the objective with its own instructions, skills, connected sources, data dictionary, and tools. The receiver owns provider, schema, query, join, and SQL decisions. Use action + input only for an exact, explicitly known, bounded read whose complete input schema is already known; never expose or call a direct action to work around slow or unreliable delegation, and never guess receiver-owned query logic. NEVER use this to call your own app or perform actions you can do with your own tools. Using call-agent on yourself will fail and waste time. \" +\n 'For brand-consistent generated media, the first-party Assets agent is available as agent=\"assets\"; use it when another app needs generated heroes, diagrams, product shots, thumbnails, videos, or design imagery, unless the current app has its own generation action that already delegates there. ' +\n \"IMPORTANT — handling the response: \" +\n \"(a) If it contains a URL or ID, copy it VERBATIM into your reply. Do not 'correct' or pluralize the path (e.g. /deck/ → /decks/), normalize casing, or change the slug — any edit breaks the link. \" +\n '(b) If it does NOT contain a URL/ID and the user asked for one, say so explicitly (e.g. \"the agent created the deck/image but didn\\'t return a link — open the app directly to view it\"). NEVER invent a URL, slug, or path — guessing produces broken links that look real. ' +\n \"(c) If the downstream response reports missing credentials, never repeat raw env var names, Vault key names, token names, secret names, or other credential identifiers. Tell the user the target app needs its LLM/provider connection configured. \" +\n \"(d) A bounded wait can expire while the remote task is still healthy. The result will include its taskId and exact retry instructions. Continue polling that SAME task with taskId; NEVER send a new check-in/follow-up message, because that starts duplicate downstream work.\",\n parameters: {\n type: \"object\",\n properties: {\n agent: {\n type: \"string\",\n description:\n \"Name or URL of a DIFFERENT deployed agent app (e.g. 'mail', 'calendar', 'analytics'). Must not be the current app's own name.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message/question to send when starting a new task. Omit when taskId is provided.\",\n },\n taskId: {\n type: \"string\",\n description:\n \"Existing A2A task ID returned by a timed-out call. Polls that exact task without sending a new message. Never create a fresh check-in message for work that already has a taskId.\",\n },\n action: {\n type: \"string\",\n description:\n \"Optional exact read-only action for an explicitly known bounded operation. Prefer message when the target agent must interpret data, choose sources or tools, synthesize, mutate, or do multi-step work. Never guess the action schema or send receiver-owned SQL.\",\n },\n input: {\n type: \"object\",\n description:\n \"Complete input object for action. The target app validates it and refuses actions that are not explicitly exposed read-only operations.\",\n additionalProperties: true,\n },\n approvedActions: {\n type: \"array\",\n description:\n \"Exact downstream tool calls the current user explicitly authorized in this chat. Never infer authorization or include a broader/different action.\",\n items: {\n type: \"object\",\n properties: {\n tool: { type: \"string\" },\n input: { type: \"object\", additionalProperties: true },\n },\n required: [\"tool\", \"input\"],\n },\n },\n },\n required: [\"agent\"],\n },\n};\n\nexport async function run(\n args: Record<string, unknown>,\n context?: ActionRunContext,\n selfAppId?: string,\n): Promise<string> {\n const agentIdOrName = String(args.agent ?? \"\");\n const message = String(args.message ?? \"\");\n const taskId = String(args.taskId ?? \"\").trim();\n const action = String(args.action ?? \"\").trim();\n const input = args.input ?? {};\n const approvedActions = Array.isArray(args.approvedActions)\n ? (args.approvedActions as A2AApprovedAction[])\n : undefined;\n\n if (!agentIdOrName) return \"Error: --agent is required\";\n if (!message && !taskId && !action) {\n return \"Error: --message, --taskId, or --action is required\";\n }\n if (action && (message || taskId)) {\n return \"Error: --action direct-invoke mode cannot be combined with --message or --taskId\";\n }\n if (action && (!input || typeof input !== \"object\" || Array.isArray(input))) {\n return \"Error: --input must be an object when --action is provided\";\n }\n\n // Prevent self-calls — the agent must use its own registered tools instead\n if (selfAppId && agentIdOrName.toLowerCase() === selfAppId.toLowerCase()) {\n return `Error: You cannot use call-agent to call yourself (${selfAppId}). Use your own registered actions/tools instead. call-agent is only for communicating with OTHER separately-deployed apps.`;\n }\n\n const inheritedDepth = Number.isInteger(context?.delegationDepth)\n ? Math.max(0, Number(context?.delegationDepth))\n : 0;\n if (!taskId && inheritedDepth >= MAX_A2A_DELEGATION_HOPS) {\n return (\n `Error: Cross-app delegation stopped at the ${MAX_A2A_DELEGATION_HOPS}-hop limit. ` +\n \"Finish with the results already collected instead of starting another agent.\"\n );\n }\n\n const agent = await findAgent(agentIdOrName, selfAppId);\n if (!agent) {\n const available = (await discoverAgents(selfAppId))\n .map((a) => a.name)\n .join(\", \");\n return `Error: Agent \"${agentIdOrName}\" not found. Available agents: ${available || \"(none)\"}`;\n }\n\n if (!taskId) {\n const visited = new Set(\n (context?.visitedApps ?? []).map(normalizeAppHandle).filter(Boolean),\n );\n const self = normalizeAppHandle(selfAppId);\n if (self) visited.add(self);\n const targetHandles = [\n normalizeAppHandle((agent as { id?: string }).id),\n normalizeAppHandle(agent.name),\n normalizeAppHandle(agentIdOrName),\n ].filter(Boolean);\n const repeated = targetHandles.find((handle) => visited.has(handle));\n if (repeated) {\n return (\n `Error: Cross-app delegation cycle blocked before calling ${agent.name}. ` +\n `The request already visited ${[...visited].join(\" -> \")}.`\n );\n }\n }\n\n const correlation = buildDelegationCorrelation(context, selfAppId);\n const idempotencyKey =\n message && !taskId\n ? buildMessageIdempotencyKey(context?.turnId, agent.url, message)\n : undefined;\n const targetApp =\n normalizeAppHandle((agent as { id?: string }).id) ||\n normalizeAppHandle(agent.name) ||\n normalizeAppHandle(agentIdOrName) ||\n \"unknown\";\n\n if (action) {\n const agentCallId = randomUUID();\n const startedAt = Date.now();\n let terminalStatus: \"done\" | \"error\" = \"done\";\n let terminalCode: string | undefined;\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n }\n try {\n const output = await invokeReadOnlyAppAction(\n agent,\n action,\n input as Record<string, unknown>,\n buildDelegationCorrelation(context, selfAppId, randomUUID()),\n );\n if (/^Error\\b/i.test(output)) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n }\n if (context?.send && output) {\n context.send({\n type: \"agent_call_text\",\n agent: agent.name,\n text: output,\n agentCallId,\n });\n }\n return output;\n } catch (error) {\n terminalStatus = \"error\";\n terminalCode = \"direct_action_failed\";\n throw error;\n } finally {\n trackA2AInvocation({\n invocationId: agentCallId,\n callerApp: selfAppId,\n targetApp,\n mode: \"direct_action\",\n status: terminalStatus === \"done\" ? \"success\" : \"error\",\n startedAt,\n terminalCode,\n correlation,\n });\n if (context?.send) {\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n durationMs: Date.now() - startedAt,\n });\n }\n }\n }\n\n // Append a small cross-app hint to the outgoing message so the receiving\n // agent (which may be on an older deploy without the receiver-side hint\n // in handlers.ts) still emits fully-qualified URLs. This is belt-and-\n // suspenders with the receiver hint — but it works against any current\n // deployment, no redeploy required.\n const sourceContext = integrationSourceContext();\n const messageWithHint = taskId\n ? \"\"\n : `${message}${integrationSourceContextHint(sourceContext)}\\n\\n` +\n `<a2a-caller-hint>\\n` +\n `This request comes from another app via A2A. The caller cannot see your local UI, deck list, or navigation — only the literal text you put in your reply. ` +\n `If you create or reference a deck/document/design/dashboard, include its FULLY-QUALIFIED URL (e.g. ${agent.url}/deck/<id>) in your reply, not a relative path. ` +\n `Use only artifact IDs and URL paths returned by successful actions — never invent slugs, IDs, or hosts. ` +\n `Return a concise caller-ready synthesis rather than raw tool output or full transcripts; preserve source counts, IDs, short supporting quotes, and URLs needed to substantiate the answer.\\n` +\n `</a2a-caller-hint>`;\n\n const invocationId = randomUUID();\n const invocationStartedAt = Date.now();\n let invocationStatus: A2AInvocationStatus = \"error\";\n let invocationTaskId = taskId || undefined;\n let invocationTerminalCode: string | undefined;\n\n try {\n // If we have a send context, use streaming so the UI shows progressive text\n if (context?.send) {\n const callerEmail = getRequestUserEmail();\n\n // Build metadata with identity\n const a2aMetadata: Record<string, unknown> = {};\n if (callerEmail) a2aMetadata.userEmail = callerEmail;\n\n // Include org domain for cross-app org resolution\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n const domain = await getOrgDomain(orgId);\n if (domain) {\n callerOrgDomain = domain;\n a2aMetadata.orgDomain = domain;\n }\n } catch {}\n try {\n const secret = await getOrgA2ASecret(orgId);\n if (secret) callerOrgSecret = secret;\n } catch {}\n }\n\n // Sign JWT with identity + org domain for the streaming client\n let apiKey: string | undefined;\n if (callerEmail && (callerOrgSecret || process.env.A2A_SECRET)) {\n try {\n apiKey = await signA2AToken(\n callerEmail,\n callerOrgDomain,\n callerOrgSecret,\n {\n expiresIn: INTEGRATION_A2A_TOKEN_TTL,\n preferGlobalSecret: shouldPreferGlobalA2ASecret(callerOrgSecret),\n },\n );\n } catch {}\n }\n\n if (process.env.NODE_ENV === \"production\" && callerEmail) {\n try {\n const { listOAuthAccountsByOwner } =\n await import(\"../oauth-tokens/store.js\");\n const accounts = await listOAuthAccountsByOwner(\n \"google\",\n callerEmail,\n );\n const tokens = accounts[0]?.tokens;\n if (tokens?.access_token) {\n a2aMetadata.googleToken = tokens.access_token;\n }\n } catch {}\n }\n\n let responseText = \"\";\n let lastSentLength = 0;\n const agentCallId = randomUUID();\n let terminalStatus: \"done\" | \"pending\" | \"error\" = \"done\";\n const existingContinuationText = taskId\n ? null\n : await formatExistingIntegrationContinuationIfRetry(agent, message);\n if (existingContinuationText) {\n invocationStatus = \"pending\";\n invocationTerminalCode = \"existing_continuation\";\n return existingContinuationText;\n }\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: \"start\",\n agentCallId,\n });\n\n const emitNewText = (newText: string) => {\n if (newText.length > lastSentLength) {\n context.send!({\n type: \"agent_call_text\",\n agent: agent.name,\n text: newText.slice(lastSentLength),\n agentCallId,\n });\n lastSentLength = newText.length;\n }\n responseText = newText;\n };\n\n // Skip the SSE streaming attempt and go straight to async + poll.\n // Why: on Netlify (Lambda), the receiving server has no streaming\n // response support, so message/stream returns a single JSON-RPC error\n // body in a 200 response that our SSE parser silently consumes — the\n // `for await` loop yields nothing AND keeps the connection open until\n // the function timeout, eating the current serverless budget. By the\n // time we get to the sync fallback, Lambda is dead and the second fetch\n // errors out as \"fetch failed\". Async+poll has its own short fetches\n // with their own budgets, so it works reliably across hosts. The\n // trade-off is that cross-app activity arrives at the poll cadence rather\n // than token-by-token. Agent Native peers attach their current reasoning,\n // tool status, and response preview to each task checkpoint, and the\n // receiver's full response still surfaces below.\n //\n // That trade-off has a second-order cost: callAgent()'s poll (see\n // A2AClient.sendAndWait in a2a/client.ts) can legitimately run for\n // minutes with nothing emitted to the parent between the \"start\" event\n // above and \"done\" below. On the parent run, that silence freezes\n // `last_progress_at` — shouldBumpProgressForEvent in\n // agent/run-manager.ts treats a stream of literally nothing as no\n // progress — which trips the client's stuck-detector\n // (DEFAULT_STUCK_THRESHOLD_MS = 90_000 in\n // client/use-run-stuck-detection.ts) and the server's stale-run sweep\n // (BACKGROUND_RUN_STALE_MS = 90_000 in agent/run-store.ts). In\n // production this handed users a \"still working, no progress\" Retry\n // button that aborted a perfectly healthy call and re-ran the sub-agent\n // from scratch.\n //\n // Fix: surface the REAL remote liveness the poll already gathers. The\n // A2A poll round-trips to the remote agent every ~2s and gets back a\n // task with `status.state` (see A2AClient.sendAndWait / `onUpdate`). We\n // emit an `agent_call_progress` event ONLY from that callback, and ONLY\n // when a poll actually succeeds AND reports an actively-working state.\n // Crucially this is NOT a timer: if the remote hangs or dies, the poll\n // fetch throws, `onUpdate` stops firing, we emit nothing, and the\n // stuck-detector correctly surfaces its banner. A wall-clock heartbeat\n // would instead keep a dead sub-agent looking alive forever — trading a\n // false stuck-positive for a worse false stuck-negative.\n //\n // Throttle: the poll runs every ~2s but both thresholds above are 90s,\n // so emitting per-poll would be ~45 events per stuck-window. We coalesce\n // to at most one emission per 30s — a 3x margin under 90s, so at least\n // two land inside either window even with jitter, without flooding.\n //\n // Shape: a dedicated `agent_call_progress` event type (see\n // agent/types.ts), not an extra `agent_call` status. `agent_call`\n // consumers (production-agent.ts's step summarizer, slack.ts's task\n // cards) render any status that isn't \"start\"/\"done\" as a failure, so a\n // \"progress\" status would surface an in-flight tick as an error. A\n // distinct type is instead ignored gracefully everywhere: the run-event\n // switches fall to their `default`, the client if-chains fall through,\n // and sse-event-processor returns `{action:\"continue\"}`. It still counts\n // as real progress in shouldBumpProgressForEvent (any non-special event\n // type does), which is the whole point.\n const PROGRESS_MIN_INTERVAL_MS = 30_000;\n // Terminal states resolve the poll; \"input-required\" means the remote is\n // blocked waiting on us, not making progress. Only actively-working\n // states count as liveness worth surfacing.\n const ACTIVELY_WORKING_STATES = new Set([\n \"working\",\n \"submitted\",\n \"processing\",\n ]);\n const callStartedAt = Date.now();\n let lastProgressEmitAt = callStartedAt;\n let lastActivitySequence = -1;\n const onRemotePollUpdate = (task: Task) => {\n const state = task?.status?.state;\n const parts = task.status?.message?.parts;\n const snapshot = Array.isArray(parts)\n ? parts.map(parseA2AAgentActivityPart).find((value) => value !== null)\n : undefined;\n if (snapshot && snapshot.sequence > lastActivitySequence) {\n lastActivitySequence = snapshot.sequence;\n context.send!({\n type: \"agent_call_activity\",\n agent: agent.name,\n agentCallId,\n snapshot,\n });\n }\n if (!state || !ACTIVELY_WORKING_STATES.has(state)) return;\n const now = Date.now();\n if (now - lastProgressEmitAt < PROGRESS_MIN_INTERVAL_MS) return;\n lastProgressEmitAt = now;\n const detail = extractRemoteProgressDetail(task);\n context.send!({\n type: \"agent_call_progress\",\n agent: agent.name,\n state,\n elapsedSeconds: Math.round((now - callStartedAt) / 1000),\n agentCallId,\n ...(detail ? { detail } : {}),\n });\n };\n\n try {\n // Apply a polling cap ONLY for integration-platform callers on\n // serverless hosts. Normal chat, local Node, self-hosted Node, and\n // Docker can wait for slow-but-valid answers; integration processors\n // still need to finish before their current function execution dies.\n const callTimeoutMs = getIntegrationCallTimeoutMs();\n const submissionTimeoutMs =\n callTimeoutMs && isNetlifyHostedRuntimeForIntegrationCall()\n ? NETLIFY_INTEGRATION_A2A_SUBMISSION_TIMEOUT_MS\n : undefined;\n responseText = await callAgent(agent.url, messageWithHint, {\n apiKey,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n onUpdate: onRemotePollUpdate,\n returnRecoverableArtifactsOnTimeout: false,\n ...(callTimeoutMs\n ? {\n timeoutMs: callTimeoutMs,\n ...(submissionTimeoutMs ? { submissionTimeoutMs } : {}),\n }\n : {}),\n });\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, responseText) ??\n responseText;\n // Some agents reply with relative paths (e.g. slides emits\n // \"/deck/abc\"). Those resolve against the caller's host, not the\n // receiver's, so they're broken for the user. Expand any leading-slash\n // URL into a fully-qualified one rooted at the receiving agent's host.\n responseText = expandRelativeUrls(responseText, agent.url);\n // Mirror the response into the streaming UI so the user sees it.\n if (responseText) emitNewText(responseText);\n } catch (pollErr: any) {\n const timeoutTaskId = getA2ATaskTimeoutTaskId(pollErr);\n if (timeoutTaskId) {\n terminalStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n const queued = await enqueueIntegrationContinuationIfPossible(\n timeoutTaskId,\n agent,\n message,\n callerEmail,\n );\n if (queued) {\n responseText =\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent accepted this delegated subtask and will post its own final result to the originating integration thread automatically. ` +\n `Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting its result separately.`;\n } else {\n // The normal integration path must preserve the timeout task id so\n // it can enqueue a durable continuation. If that enqueue fails,\n // do not hide receiver-verified artifacts that were already\n // returned with the last poll; this mirrors callAgent's default\n // timeout behavior without treating arbitrary remote status text\n // as a completed response.\n const recoverableArtifactText =\n extractRecoverableTimeoutArtifactText(pollErr);\n if (recoverableArtifactText) {\n responseText = expandRelativeUrls(\n recoverableArtifactText,\n agent.url,\n );\n } else {\n responseText = formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n }\n } else if (terminalTaskError(pollErr)?.state === \"input-required\") {\n terminalStatus = \"pending\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n responseText = formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n } else if (terminalTaskError(pollErr)) {\n terminalStatus = \"error\";\n const terminal = terminalTaskError(pollErr)!;\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n const detail = expandRelativeUrls(\n terminal.responseText ?? pollErr?.message ?? \"unknown failure\",\n agent.url,\n );\n responseText =\n `Error: The ${agent.name} agent ended ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (detail ? `: ${detail}` : \"\");\n } else {\n terminalStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n const reason = pollErr?.message ?? \"unknown error\";\n responseText =\n formatDownstreamLlmCredentialFailure(agent.name, pollErr) ??\n `Error: The ${agent.name} agent call failed. (${reason})`;\n }\n }\n\n if (!responseText && terminalStatus === \"done\") {\n terminalStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n }\n if (responseText.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n terminalStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n responseText =\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\";\n }\n invocationStatus =\n terminalStatus === \"done\"\n ? \"success\"\n : terminalStatus === \"pending\"\n ? \"pending\"\n : \"error\";\n\n context.send({\n type: \"agent_call\",\n agent: agent.name,\n status: terminalStatus,\n agentCallId,\n ...(invocationTaskId ? { taskId: invocationTaskId } : {}),\n durationMs: Date.now() - callStartedAt,\n });\n\n return (\n responseText || `Error: The ${agent.name} agent returned no result.`\n );\n }\n\n // No context — use the async + poll call so we don't get cut off at the\n // serverless gateway's ~30s timeout. callAgent defaults to async:true.\n const email = getRequestUserEmail();\n let domain: string | undefined;\n let orgSecret: string | undefined;\n const currentOrgId = getRequestOrgId();\n if (currentOrgId) {\n try {\n domain = (await getOrgDomain(currentOrgId)) ?? undefined;\n } catch {}\n try {\n orgSecret = (await getOrgA2ASecret(currentOrgId)) ?? undefined;\n } catch {}\n }\n const response = await callAgent(agent.url, messageWithHint, {\n userEmail: email,\n orgDomain: domain,\n orgSecret,\n approvedActions,\n ...(sourceContext ? { sourceContext: sourceContext.reference } : {}),\n contextId: context?.threadId,\n correlation,\n idempotencyKey,\n ...(taskId ? { taskId } : {}),\n returnRecoverableArtifactsOnTimeout: false,\n });\n const sanitized =\n formatDownstreamLlmCredentialFailure(agent.name, response) ?? response;\n const expanded = expandRelativeUrls(sanitized, agent.url);\n if (!expanded) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"empty_agent_response\";\n return \"Error: The remote agent returned no result.\";\n }\n if (expanded.length > MAX_A2A_CALLER_RESPONSE_CHARS) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"a2a_response_too_large\";\n return (\n `Error: The ${agent.name} agent returned more data than the caller can safely consume. ` +\n \"Ask it for a concise synthesis or a retrievable artifact instead.\"\n );\n }\n invocationStatus = \"success\";\n return expanded;\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n const credentialMessage = formatDownstreamLlmCredentialFailure(\n agent.name,\n err,\n );\n if (credentialMessage) return credentialMessage;\n const terminal = terminalTaskError(err);\n if (terminal?.state === \"input-required\") {\n invocationStatus = \"pending\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? \"input_required\";\n return formatInputRequiredWaitInstruction(\n agent.name,\n terminal,\n agentIdOrName,\n );\n }\n if (terminal) {\n invocationStatus = \"error\";\n invocationTaskId = terminal.taskId;\n invocationTerminalCode = terminal.errorCode ?? terminal.state;\n return (\n `Error calling ${agent.name}: remote task ${terminal.state}` +\n (terminal.errorCode ? ` (${terminal.errorCode})` : \"\") +\n (terminal.taskId ? ` [taskId: ${terminal.taskId}]` : \"\") +\n (terminal.responseText ? `: ${terminal.responseText}` : \"\")\n );\n }\n const timeoutTaskId = getA2ATaskTimeoutTaskId(err);\n if (timeoutTaskId) {\n invocationStatus = \"pending\";\n invocationTaskId = timeoutTaskId;\n invocationTerminalCode = \"timeout_pending\";\n return formatExistingTaskWaitInstruction(\n agent.name,\n timeoutTaskId,\n agentIdOrName,\n );\n }\n // Friendlier message for the common timeout case so the calling agent can\n // decide whether to give up or retry.\n if (/timeout|did not complete|Inactivity|504/i.test(msg)) {\n invocationStatus = \"error\";\n invocationTerminalCode = \"timeout_without_task\";\n return `Error calling ${agent.name}: the remote request timed out before a task id could be recovered.`;\n }\n invocationStatus = \"error\";\n invocationTerminalCode = \"call_failed\";\n return `Error calling ${agent.name}: ${msg}`;\n } finally {\n trackA2AInvocation({\n invocationId,\n callerApp: selfAppId,\n targetApp,\n mode: taskId ? \"task_poll\" : \"message\",\n status: invocationStatus,\n startedAt: invocationStartedAt,\n taskId: invocationTaskId,\n terminalCode: invocationTerminalCode,\n correlation,\n });\n }\n}\n\nasync function invokeReadOnlyAppAction(\n agent: { name: string; url: string },\n action: string,\n input: Record<string, unknown>,\n correlation: A2ACorrelationMetadata,\n): Promise<string> {\n const callerEmail = getRequestUserEmail();\n if (!callerEmail) {\n return `Error calling ${agent.name} action ${action}: a signed-in user identity is required`;\n }\n\n let callerOrgDomain: string | undefined;\n let callerOrgSecret: string | undefined;\n const orgId = getRequestOrgId();\n if (orgId) {\n try {\n callerOrgDomain = (await getOrgDomain(orgId)) ?? undefined;\n } catch {}\n try {\n callerOrgSecret = (await getOrgA2ASecret(orgId)) ?? undefined;\n } catch {}\n }\n\n if (!callerOrgSecret && !process.env.A2A_SECRET) {\n return `Error calling ${agent.name} action ${action}: direct cross-app reads require A2A identity verification`;\n }\n\n try {\n const invocation = await invokeAgentAction({\n target: agent.url,\n action,\n input,\n userEmail: callerEmail,\n orgDomain: callerOrgDomain,\n orgSecret: callerOrgSecret,\n correlation,\n });\n return invocation.result.status === \"completed\"\n ? invocation.result.output\n : `Error calling ${agent.name} action ${action}: ${invocation.result.output}`;\n } catch (error) {\n return `Error calling ${agent.name} action ${action}: ${\n error instanceof Error ? error.message : String(error)\n }`;\n }\n}\n\nfunction formatExistingTaskWaitInstruction(\n agentName: string,\n taskId: string,\n agentIdOrName: string,\n): string {\n return (\n `The ${agentName} task is still running under taskId \"${taskId}\". ` +\n `Do not send ${agentName} a new check-in or follow-up message; that would start duplicate work. ` +\n `Call call-agent again with agent=\"${agentIdOrName}\" and taskId=\"${taskId}\" (omit message) to continue waiting for this same task.`\n );\n}\n\nfunction formatInputRequiredWaitInstruction(\n agentName: string,\n terminal: {\n taskId?: string;\n responseText?: string;\n },\n agentIdOrName: string,\n): string {\n const detail = terminal.responseText?.trim();\n if (!terminal.taskId) {\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `Pending: The ${agentName} agent needs input before it can continue.`\n );\n }\n return (\n (detail ? `${detail}\\n\\n` : \"\") +\n `The ${agentName} agent is waiting for input under taskId \"${terminal.taskId}\". ` +\n `After providing or approving the requested input, call call-agent with agent=\"${agentIdOrName}\" and taskId=\"${terminal.taskId}\" (omit message) to continue this same task. Do not start a new message for this work.`\n );\n}\n\nasync function enqueueIntegrationContinuationIfPossible(\n taskId: string,\n agent: { name: string; url: string },\n message: string,\n ownerEmail: string | undefined,\n): Promise<boolean> {\n const integration = getIntegrationRequestContext();\n if (!integration || !ownerEmail) return false;\n\n try {\n const [{ insertA2AContinuation }, { dispatchA2AContinuation }] =\n await Promise.all([\n import(\"../integrations/a2a-continuations-store.js\"),\n import(\"../integrations/a2a-continuation-processor.js\"),\n ]);\n const continuation = await insertA2AContinuation({\n integrationTaskId: integration.taskId,\n platform: integration.incoming.platform,\n externalThreadId: integration.incoming.externalThreadId,\n incoming: integration.incoming,\n placeholderRef: integration.placeholderRef,\n progressRef: integration.progressRef,\n ownerEmail,\n orgId: getRequestOrgId() ?? null,\n agentName: agent.name,\n agentUrl: agent.url,\n dedupeKey: getIntegrationContinuationDedupeKey(message),\n a2aTaskId: taskId,\n // Do not persist the short-lived JWT used for the initial send. The\n // continuation processor can mint a fresh token for each poll.\n a2aAuthToken: null,\n });\n await dispatchA2AContinuation(continuation.id).catch((err) => {\n console.error(\n `[call-agent] Failed to dispatch A2A continuation ${continuation.id}:`,\n err,\n );\n });\n return true;\n } catch (err) {\n console.error(\"[call-agent] Failed to enqueue A2A continuation:\", err);\n return false;\n }\n}\n\n// Pull a short human-readable detail from a polled A2A task's status message,\n// when the remote includes one, so the progress event can surface a real\n// signal (e.g. \"Generating hero image…\") instead of a bare elapsed counter.\n// Bounded so a chatty remote can't push a large payload through the event.\nconst MAX_PROGRESS_DETAIL_CHARS = 200;\nfunction extractRemoteProgressDetail(task: Task): string | undefined {\n const parts = task.status?.message?.parts;\n if (!Array.isArray(parts)) return undefined;\n const text = parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (!text) return undefined;\n return text.length > MAX_PROGRESS_DETAIL_CHARS\n ? `${text.slice(0, MAX_PROGRESS_DETAIL_CHARS - 1)}…`\n : text;\n}\n\nfunction getA2ATaskTimeoutTaskId(err: unknown): string | null {\n if (err instanceof A2ATaskTimeoutError) return err.taskId;\n\n const candidate = err as\n | { name?: unknown; taskId?: unknown; message?: unknown }\n | null\n | undefined;\n const message = String(candidate?.message ?? \"\");\n if (\n candidate?.name === \"A2ATaskTimeoutError\" &&\n typeof candidate.taskId === \"string\"\n ) {\n return candidate.taskId;\n }\n\n const match = message.match(/^A2A task ([^\\s]+) did not complete\\b/);\n return match?.[1] ?? null;\n}\n\n/**\n * Mirrors the A2A client's default timeout recovery for the exceptional case\n * where an integration cannot enqueue a durable continuation. Only an\n * explicitly receiver-marked task message is safe to surface as a completed\n * partial result; ordinary working-state text remains a timeout failure.\n */\nfunction extractRecoverableTimeoutArtifactText(err: unknown): string {\n const candidate = err as\n | { lastTask?: Task | unknown; name?: unknown }\n | null\n | undefined;\n const lastTask =\n err instanceof A2ATaskTimeoutError\n ? err.lastTask\n : candidate?.name === \"A2ATaskTimeoutError\"\n ? (candidate.lastTask as Task | undefined)\n : undefined;\n const message = lastTask?.status?.message;\n if (!message?.metadata?.agentNativeRecoverableArtifacts) return \"\";\n\n return message.parts\n .filter(\n (part): part is { type: \"text\"; text: string } => part.type === \"text\",\n )\n .map((part) => part.text)\n .join(\"\\n\");\n}\n\nasync function formatExistingIntegrationContinuationIfRetry(\n agent: {\n name: string;\n url: string;\n },\n message: string,\n): Promise<string | null> {\n const integration = getIntegrationRequestContext();\n if (!integration || (integration.attempts ?? 1) <= 1) return null;\n\n try {\n const { getA2AContinuationsForIntegrationTaskAgent } =\n await import(\"../integrations/a2a-continuations-store.js\");\n const continuations = await getA2AContinuationsForIntegrationTaskAgent(\n integration.taskId,\n agent.url,\n getIntegrationContinuationDedupeKey(message),\n );\n const active = continuations.find((continuation) =>\n [\"pending\", \"processing\", \"delivering\", \"completed\"].includes(\n continuation.status,\n ),\n );\n if (!active) return null;\n\n const state =\n active.status === \"completed\"\n ? \"already completed this delegated subtask and posted its result to the originating integration thread\"\n : \"already accepted this delegated subtask and is still working on it for the originating integration thread\";\n return (\n `${A2A_CONTINUATION_QUEUED_MARKER}\\n` +\n `The ${agent.name} agent ${state}. Do not call ${agent.name} again for this same subtask. Continue any other requested work, then answer with the completed results you have; if needed, mention that ${agent.name} is posting or has posted its result separately.`\n );\n } catch (err) {\n console.error(\"[call-agent] Failed to inspect existing continuation:\", err);\n return null;\n }\n}\n\nfunction getIntegrationContinuationDedupeKey(message: string): string {\n const normalized = message.trim().replace(/\\s+/g, \" \");\n return createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\n// Expand bare leading-slash paths (e.g. \"/deck/abc\") into fully-qualified URLs\n// rooted at the receiving agent's host. The receiver doesn't always know it's\n// being called cross-app, so it may emit relative paths that resolve against\n// the caller's host (broken). Match a path that starts at a word boundary,\n// begins with `/`, and has at least one path segment after that. Skip if it\n// already looks like a fully-qualified URL.\nexport function expandRelativeUrls(text: string, agentUrl: string): string {\n if (!text || !agentUrl) return text;\n const base = agentUrl.replace(/\\/$/, \"\");\n // Path must start at boundary (start, whitespace, or punctuation that isn't\n // ':' — to avoid mangling `https://example.com/foo` or markdown link bodies).\n return text.replace(\n /(^|[\\s([<\"'`])(\\/[a-z0-9_-][a-z0-9_/?&=%#.,:-]*)/gi,\n (_match, lead, path) => `${lead}${base}${path}`,\n );\n}\n"]}
@@ -20,7 +20,7 @@ export declare function createTranscribeVoiceHandler(): import("h3").EventHandle
20
20
  error: string;
21
21
  text?: undefined;
22
22
  } | {
23
- error?: undefined;
24
23
  text: string;
24
+ error?: undefined;
25
25
  }>>;
26
26
  //# sourceMappingURL=transcribe-voice.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.133.0",
3
+ "version": "0.133.2",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/BuilderIO/agent-native#readme",
6
6
  "bugs": {
package/src/a2a/client.ts CHANGED
@@ -536,8 +536,14 @@ export class A2AClient {
536
536
  metadata?: Record<string, unknown>;
537
537
  idempotencyKey?: string;
538
538
  approvedActions?: A2AApprovedAction[];
539
- /** Total time to wait for completion. Default 5 min. */
539
+ /** Time to wait after submission for completion. Default 5 min. */
540
540
  timeoutMs?: number;
541
+ /**
542
+ * Optional separate budget for agent-card discovery and the initial
543
+ * async message submission. When omitted, timeoutMs remains the shared
544
+ * end-to-end deadline for backwards compatibility.
545
+ */
546
+ submissionTimeoutMs?: number;
541
547
  /** Poll interval. Default 2s. */
542
548
  pollIntervalMs?: number;
543
549
  /** Called with each polled task — useful for surfacing progress. */
@@ -545,7 +551,8 @@ export class A2AClient {
545
551
  },
546
552
  ): Promise<Task> {
547
553
  const timeoutMs = opts?.timeoutMs ?? 5 * 60_000;
548
- const deadlineMs = Date.now() + timeoutMs;
554
+ const submissionDeadlineMs =
555
+ Date.now() + (opts?.submissionTimeoutMs ?? timeoutMs);
549
556
  const submitted = await this.send(message, {
550
557
  contextId: opts?.contextId,
551
558
  metadata: opts?.metadata,
@@ -556,12 +563,19 @@ export class A2AClient {
556
563
  async: true,
557
564
  requestTimeoutMs: Math.min(
558
565
  this.requestTimeoutMs ?? DEFAULT_A2A_POLL_REQUEST_TIMEOUT_MS,
559
- Math.max(1, deadlineMs - Date.now()),
566
+ Math.max(1, submissionDeadlineMs - Date.now()),
560
567
  ),
561
- deadlineMs,
568
+ deadlineMs: submissionDeadlineMs,
562
569
  });
563
570
 
564
- return this.pollTask(submitted, { ...opts, timeoutMs, deadlineMs });
571
+ const pollingDeadlineMs = opts?.submissionTimeoutMs
572
+ ? Date.now() + timeoutMs
573
+ : submissionDeadlineMs;
574
+ return this.pollTask(submitted, {
575
+ ...opts,
576
+ timeoutMs,
577
+ deadlineMs: pollingDeadlineMs,
578
+ });
565
579
  }
566
580
 
567
581
  /**
@@ -1017,6 +1031,8 @@ export async function callAgent(
1017
1031
  async?: boolean;
1018
1032
  /** Total time to wait for the polled task (default 5 min). */
1019
1033
  timeoutMs?: number;
1034
+ /** Separate budget for discovery and initial async submission. */
1035
+ submissionTimeoutMs?: number;
1020
1036
  /**
1021
1037
  * Existing async task to keep polling. When set, no new message is sent.
1022
1038
  * This prevents a caller-side timeout from duplicating downstream work.
@@ -1092,6 +1108,7 @@ export async function callAgent(
1092
1108
  ? { approvedActions: opts.approvedActions }
1093
1109
  : {}),
1094
1110
  timeoutMs: opts?.timeoutMs,
1111
+ submissionTimeoutMs: opts?.submissionTimeoutMs,
1095
1112
  pollIntervalMs: opts?.pollIntervalMs,
1096
1113
  onUpdate: opts?.onUpdate,
1097
1114
  });