@agent-native/core 0.131.6 → 0.131.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/corpus/README.md +1 -1
  2. package/corpus/core/CHANGELOG.md +31 -0
  3. package/corpus/core/docs/content/deployment.mdx +12 -10
  4. package/corpus/core/docs/content/security.mdx +2 -2
  5. package/corpus/core/package.json +1 -1
  6. package/corpus/core/src/a2a/invoke.ts +4 -2
  7. package/corpus/core/src/agent/action-continuation-guidance.ts +2 -1
  8. package/corpus/core/src/agent/engine/registry.ts +61 -9
  9. package/corpus/core/src/application-state/store.ts +18 -31
  10. package/corpus/core/src/cli/create.ts +115 -16
  11. package/corpus/core/src/client/AssistantChat.tsx +10 -2
  12. package/corpus/core/src/client/frame-protocol.ts +5 -1
  13. package/corpus/core/src/guards/no-env-credentials.ts +2 -0
  14. package/corpus/core/src/scripts/call-agent.ts +4 -2
  15. package/corpus/core/src/secrets/crypto.ts +44 -15
  16. package/corpus/core/src/secrets/storage.ts +6 -4
  17. package/corpus/core/src/server/agent-chat/action-filters-a2a.ts +2 -0
  18. package/corpus/core/src/templates/default/.agents/skills/secrets/SKILL.md +14 -9
  19. package/corpus/core/src/templates/headless/.agents/skills/secrets/SKILL.md +14 -9
  20. package/corpus/core/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +14 -9
  21. package/corpus/core/src/workspace-files/tool.ts +18 -11
  22. package/corpus/templates/analytics/AGENTS.md +1 -0
  23. package/corpus/templates/analytics/changelog/2026-07-30-delegated-analytics-questions-now-return-a-useful-current-me.md +6 -0
  24. package/corpus/templates/analytics/server/lib/real-data-actions.ts +10 -0
  25. package/corpus/templates/clips/actions/generate-workflow.ts +6 -4
  26. package/corpus/templates/clips/actions/reconcile-workflow-generation.ts +257 -0
  27. package/corpus/templates/clips/app/hooks/use-auto-title.ts +166 -4
  28. package/corpus/templates/clips/app/routes/r.$recordingId.tsx +1 -1
  29. package/corpus/templates/clips/changelog/2026-07-27-stopped-agent-runs-no-longer-leave-generated-workflow-cards-.md +6 -0
  30. package/corpus/templates/clips/changelog/2026-07-30-workflow-generation-now-stops-retrying-after-repeated-failur.md +6 -0
  31. package/corpus/templates/clips/shared/workflow.ts +5 -0
  32. package/corpus/templates/plan/actions/get-visual-plan.ts +10 -6
  33. package/corpus/templates/plan/actions/patch-visual-plan-source.ts +117 -1
  34. package/corpus/templates/plan/actions/update-visual-plan.ts +56 -14
  35. package/corpus/templates/plan/app/pages/PlansPage.tsx +1 -1
  36. package/corpus/templates/plan/changelog/2026-07-30-plan-agents-recover-with-targeted-writes.md +6 -0
  37. package/corpus/templates/plan/shared/plan-content.ts +35 -0
  38. package/corpus/templates/slides/actions/create-deck.ts +1 -1
  39. package/corpus/templates/slides/changelog/2026-07-30-new-decks-now-start-with-an-empty-slide-list-when-no-slides-.md +6 -0
  40. package/dist/a2a/invoke.d.ts.map +1 -1
  41. package/dist/a2a/invoke.js +4 -2
  42. package/dist/a2a/invoke.js.map +1 -1
  43. package/dist/agent/action-continuation-guidance.d.ts.map +1 -1
  44. package/dist/agent/action-continuation-guidance.js +2 -1
  45. package/dist/agent/action-continuation-guidance.js.map +1 -1
  46. package/dist/agent/engine/registry.d.ts.map +1 -1
  47. package/dist/agent/engine/registry.js +59 -12
  48. package/dist/agent/engine/registry.js.map +1 -1
  49. package/dist/application-state/store.d.ts.map +1 -1
  50. package/dist/application-state/store.js +20 -36
  51. package/dist/application-state/store.js.map +1 -1
  52. package/dist/cli/create.d.ts +8 -1
  53. package/dist/cli/create.d.ts.map +1 -1
  54. package/dist/cli/create.js +98 -16
  55. package/dist/cli/create.js.map +1 -1
  56. package/dist/client/AssistantChat.d.ts.map +1 -1
  57. package/dist/client/AssistantChat.js +10 -2
  58. package/dist/client/AssistantChat.js.map +1 -1
  59. package/dist/client/frame-protocol.d.ts +1 -0
  60. package/dist/client/frame-protocol.d.ts.map +1 -1
  61. package/dist/client/frame-protocol.js.map +1 -1
  62. package/dist/collab/routes.d.ts +1 -1
  63. package/dist/collab/struct-routes.d.ts +1 -1
  64. package/dist/file-upload/actions/upload-image.d.ts +1 -1
  65. package/dist/guards/no-env-credentials.d.ts.map +1 -1
  66. package/dist/guards/no-env-credentials.js +2 -0
  67. package/dist/guards/no-env-credentials.js.map +1 -1
  68. package/dist/mcp/screen-memory-stdio.d.ts +7 -7
  69. package/dist/mcp/screen-memory-stdio.d.ts.map +1 -1
  70. package/dist/notifications/routes.d.ts +6 -6
  71. package/dist/observability/routes.d.ts +3 -3
  72. package/dist/scripts/call-agent.d.ts.map +1 -1
  73. package/dist/scripts/call-agent.js +4 -2
  74. package/dist/scripts/call-agent.js.map +1 -1
  75. package/dist/secrets/crypto.d.ts +14 -9
  76. package/dist/secrets/crypto.d.ts.map +1 -1
  77. package/dist/secrets/crypto.js +42 -16
  78. package/dist/secrets/crypto.js.map +1 -1
  79. package/dist/secrets/storage.d.ts +6 -4
  80. package/dist/secrets/storage.d.ts.map +1 -1
  81. package/dist/secrets/storage.js +6 -4
  82. package/dist/secrets/storage.js.map +1 -1
  83. package/dist/server/agent-chat/action-filters-a2a.d.ts +1 -1
  84. package/dist/server/agent-chat/action-filters-a2a.d.ts.map +1 -1
  85. package/dist/server/agent-chat/action-filters-a2a.js +2 -0
  86. package/dist/server/agent-chat/action-filters-a2a.js.map +1 -1
  87. package/dist/server/realtime-token.d.ts +1 -1
  88. package/dist/server/transcribe-voice.d.ts +1 -1
  89. package/dist/templates/default/.agents/skills/secrets/SKILL.md +14 -9
  90. package/dist/templates/headless/.agents/skills/secrets/SKILL.md +14 -9
  91. package/dist/templates/workspace-core/.agents/skills/secrets/SKILL.md +14 -9
  92. package/dist/workspace-files/tool.d.ts.map +1 -1
  93. package/dist/workspace-files/tool.js +18 -11
  94. package/dist/workspace-files/tool.js.map +1 -1
  95. package/docs/content/deployment.mdx +12 -10
  96. package/docs/content/security.mdx +2 -2
  97. package/package.json +1 -1
  98. package/src/a2a/invoke.ts +4 -2
  99. package/src/agent/action-continuation-guidance.ts +2 -1
  100. package/src/agent/engine/registry.ts +61 -9
  101. package/src/application-state/store.ts +18 -31
  102. package/src/cli/create.ts +115 -16
  103. package/src/client/AssistantChat.tsx +10 -2
  104. package/src/client/frame-protocol.ts +5 -1
  105. package/src/guards/no-env-credentials.ts +2 -0
  106. package/src/scripts/call-agent.ts +4 -2
  107. package/src/secrets/crypto.ts +44 -15
  108. package/src/secrets/storage.ts +6 -4
  109. package/src/server/agent-chat/action-filters-a2a.ts +2 -0
  110. package/src/templates/default/.agents/skills/secrets/SKILL.md +14 -9
  111. package/src/templates/headless/.agents/skills/secrets/SKILL.md +14 -9
  112. package/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +14 -9
  113. package/src/workspace-files/tool.ts +18 -11
@@ -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,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,eAA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B,CAAC,CAAC,sGAAsG;YACxG,CAAC,CAAC,2GAA2G,CAAC;QAClH,OAAO,CACL,GAAG,8BAA8B,IAAI;YACrC,OAAO,KAAK,CAAC,IAAI,UAAU,KAAK,iBAAiB,KAAK,CAAC,IAAI,6IAA6I,KAAK,CAAC,IAAI,kDAAkD,CACrQ,CAAC;IACJ,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 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 return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\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 `[Note: 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 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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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 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 return {\n ...(selfAppId?.trim() ? { callerApp: selfAppId.trim() } : {}),\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"]}
@@ -13,10 +13,13 @@
13
13
  * The generic encryption key is derived from
14
14
  * `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then
15
15
  * `SECRETS_ENCRYPTION_KEY`, then `BETTER_AUTH_SECRET`. Workspace-shared vault
16
- * rows use a different precedence: `SECRETS_ENCRYPTION_KEY`, then material
17
- * derived from the workspace-wide `A2A_SECRET`, then the app-local auth/key
18
- * fallbacks retained for backward-compatible reads. This keeps sibling apps
19
- * on one key even when each app correctly has a different auth secret.
16
+ * rows use a different precedence: `WORKSPACE_SECRETS_ENCRYPTION_KEY`, then
17
+ * the legacy shared `SECRETS_ENCRYPTION_KEY`, then material derived from the
18
+ * workspace-wide `A2A_SECRET`, then the app-local auth/key fallbacks retained
19
+ * for backward-compatible reads. A previous workspace key can be supplied
20
+ * during rotation with `WORKSPACE_SECRETS_ENCRYPTION_KEY_PREVIOUS`. This keeps
21
+ * sibling apps on one stable key even when each app correctly has a different
22
+ * auth secret, and prevents A2A trust rotation from stranding vault data.
20
23
  *
21
24
  * In production we refuse to start without configured key material — a
22
25
  * CWD-derived fallback would be effectively static (e.g. `/var/task` on
@@ -34,11 +37,13 @@ export declare function getSecretEncryptionKey(): Buffer;
34
37
  /**
35
38
  * Derive the preferred workspace-shared key used by `app_secrets` rows.
36
39
  * Unlike generic column-level encryption, workspace vault data must decrypt
37
- * in sibling apps. An explicit `SECRETS_ENCRYPTION_KEY` wins; hosted
38
- * workspaces otherwise derive stable material from their shared `A2A_SECRET`
39
- * before considering app-local `BETTER_AUTH_SECRET` or app-scoped key
40
- * fallbacks. Reads try every configured legacy candidate and report when the
41
- * ciphertext should be refreshed under the preferred key.
40
+ * in sibling apps. An explicit `WORKSPACE_SECRETS_ENCRYPTION_KEY` wins without
41
+ * changing the key for app-local OAuth and credential ciphertext. The legacy
42
+ * shared `SECRETS_ENCRYPTION_KEY` remains supported; hosted workspaces
43
+ * otherwise derive material from their shared `A2A_SECRET` before considering
44
+ * app-local `BETTER_AUTH_SECRET` or app-scoped key fallbacks. Reads try every
45
+ * configured legacy/previous candidate and report when the ciphertext should
46
+ * be refreshed under the preferred key.
42
47
  */
43
48
  export declare function getSharedSecretEncryptionKey(): Buffer;
44
49
  /** Whether this deployment has stable workspace-shared key material. */
@@ -1 +1 @@
1
- {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/secrets/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAuIH;;;;GAIG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAkB/C;AAED;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,IAAI,MAAM,CASrD;AAED,wEAAwE;AACxE,wBAAgB,oCAAoC,IAAI,OAAO,CAO9D;AAiCD,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,MAAM,WAAW,0BAA0B;IACzC,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,cAAc,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,CAC9C,SAAS,EAAE,MAAM,GAChB,0BAA0B,CAwB5B;AAUD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEtE"}
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/secrets/crypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AA6JH;;;;GAIG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAkB/C;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,4BAA4B,IAAI,MAAM,CAUrD;AAED,wEAAwE;AACxE,wBAAgB,oCAAoC,IAAI,OAAO,CAQ9D;AAiCD,iEAAiE;AACjE,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,6EAA6E;AAC7E,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,MAAM,WAAW,0BAA0B;IACzC,KAAK,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,cAAc,EAAE,OAAO,CAAC;CACzB;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,CAC9C,SAAS,EAAE,MAAM,GAChB,0BAA0B,CAwB5B;AAUD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAEtE"}
@@ -13,10 +13,13 @@
13
13
  * The generic encryption key is derived from
14
14
  * `<APP_NAME>_SECRETS_ENCRYPTION_KEY` when set, then
15
15
  * `SECRETS_ENCRYPTION_KEY`, then `BETTER_AUTH_SECRET`. Workspace-shared vault
16
- * rows use a different precedence: `SECRETS_ENCRYPTION_KEY`, then material
17
- * derived from the workspace-wide `A2A_SECRET`, then the app-local auth/key
18
- * fallbacks retained for backward-compatible reads. This keeps sibling apps
19
- * on one key even when each app correctly has a different auth secret.
16
+ * rows use a different precedence: `WORKSPACE_SECRETS_ENCRYPTION_KEY`, then
17
+ * the legacy shared `SECRETS_ENCRYPTION_KEY`, then material derived from the
18
+ * workspace-wide `A2A_SECRET`, then the app-local auth/key fallbacks retained
19
+ * for backward-compatible reads. A previous workspace key can be supplied
20
+ * during rotation with `WORKSPACE_SECRETS_ENCRYPTION_KEY_PREVIOUS`. This keeps
21
+ * sibling apps on one stable key even when each app correctly has a different
22
+ * auth secret, and prevents A2A trust rotation from stranding vault data.
20
23
  *
21
24
  * In production we refuse to start without configured key material — a
22
25
  * CWD-derived fallback would be effectively static (e.g. `/var/task` on
@@ -76,6 +79,16 @@ function genericEncryptionKeyMaterial() {
76
79
  process.env.BETTER_AUTH_SECRET ||
77
80
  getWorkspaceA2ADerivedSecret("secrets-encryption"));
78
81
  }
82
+ function workspaceSharedEncryptionKeyMaterial() {
83
+ if (typeof process === "undefined")
84
+ return undefined;
85
+ return process.env.WORKSPACE_SECRETS_ENCRYPTION_KEY?.trim() || undefined;
86
+ }
87
+ function previousWorkspaceSharedEncryptionKeyMaterial() {
88
+ if (typeof process === "undefined")
89
+ return undefined;
90
+ return (process.env.WORKSPACE_SECRETS_ENCRYPTION_KEY_PREVIOUS?.trim() || undefined);
91
+ }
79
92
  /**
80
93
  * Vault sharing follows configured A2A trust even on independently deployed
81
94
  * sibling apps that are not launched by the workspace wrapper. The wrapper's
@@ -98,22 +111,31 @@ function a2aSharedEncryptionKeyMaterial() {
98
111
  * Stable materials that may be used for workspace-shared vault rows, ordered
99
112
  * from current preference to legacy compatibility fallbacks.
100
113
  *
101
- * `BETTER_AUTH_SECRET` deliberately comes after the A2A-derived material:
102
- * sibling apps normally have different auth secrets but share A2A trust.
114
+ * `BETTER_AUTH_SECRET` deliberately comes after the workspace and A2A-derived
115
+ * materials: sibling apps normally have different auth secrets but share
116
+ * workspace trust.
103
117
  */
104
118
  function sharedEncryptionKeyMaterials() {
105
119
  if (typeof process === "undefined")
106
120
  return [];
107
121
  const candidates = [
122
+ workspaceSharedEncryptionKeyMaterial(),
108
123
  process.env.SECRETS_ENCRYPTION_KEY,
109
124
  a2aSharedEncryptionKeyMaterial(),
125
+ previousWorkspaceSharedEncryptionKeyMaterial(),
110
126
  process.env.BETTER_AUTH_SECRET,
111
127
  appScopedEncryptionKey(),
112
128
  ].filter((value) => Boolean(value));
113
129
  return [...new Set(candidates)];
114
130
  }
115
131
  function preferredSharedEncryptionKeyMaterial() {
116
- return sharedEncryptionKeyMaterials()[0];
132
+ if (typeof process === "undefined")
133
+ return undefined;
134
+ return (workspaceSharedEncryptionKeyMaterial() ||
135
+ process.env.SECRETS_ENCRYPTION_KEY ||
136
+ a2aSharedEncryptionKeyMaterial() ||
137
+ process.env.BETTER_AUTH_SECRET ||
138
+ appScopedEncryptionKey());
117
139
  }
118
140
  function hashSecretEncryptionKey(material) {
119
141
  const { createHash } = requireNodeCrypto();
@@ -155,23 +177,27 @@ export function getSecretEncryptionKey() {
155
177
  /**
156
178
  * Derive the preferred workspace-shared key used by `app_secrets` rows.
157
179
  * Unlike generic column-level encryption, workspace vault data must decrypt
158
- * in sibling apps. An explicit `SECRETS_ENCRYPTION_KEY` wins; hosted
159
- * workspaces otherwise derive stable material from their shared `A2A_SECRET`
160
- * before considering app-local `BETTER_AUTH_SECRET` or app-scoped key
161
- * fallbacks. Reads try every configured legacy candidate and report when the
162
- * ciphertext should be refreshed under the preferred key.
180
+ * in sibling apps. An explicit `WORKSPACE_SECRETS_ENCRYPTION_KEY` wins without
181
+ * changing the key for app-local OAuth and credential ciphertext. The legacy
182
+ * shared `SECRETS_ENCRYPTION_KEY` remains supported; hosted workspaces
183
+ * otherwise derive material from their shared `A2A_SECRET` before considering
184
+ * app-local `BETTER_AUTH_SECRET` or app-scoped key fallbacks. Reads try every
185
+ * configured legacy/previous candidate and report when the ciphertext should
186
+ * be refreshed under the preferred key.
163
187
  */
164
188
  export function getSharedSecretEncryptionKey() {
165
189
  return deriveSecretEncryptionKey(preferredSharedEncryptionKeyMaterial(), "[agent-native/secrets] Refusing to start in production without encryption key material for workspace secrets. " +
166
- "Set SECRETS_ENCRYPTION_KEY, ensure a hosted workspace has A2A_SECRET, or set BETTER_AUTH_SECRET / an app-scoped " +
167
- "*_SECRETS_ENCRYPTION_KEY compatibility fallback in the deploy environment.", "[agent-native/secrets] SECRETS_ENCRYPTION_KEY not set — using app-scoped or machine-local fallback for workspace secrets. " +
168
- "Set SECRETS_ENCRYPTION_KEY or rely on A2A_SECRET-derived material on hosted workspace deploys so sibling apps share vault rows.");
190
+ "Set WORKSPACE_SECRETS_ENCRYPTION_KEY (preferred), SECRETS_ENCRYPTION_KEY, ensure a hosted workspace has A2A_SECRET, " +
191
+ "or set BETTER_AUTH_SECRET / an app-scoped " +
192
+ "*_SECRETS_ENCRYPTION_KEY compatibility fallback in the deploy environment.", "[agent-native/secrets] Workspace encryption key not set using app-scoped or machine-local fallback for workspace secrets. " +
193
+ "Set WORKSPACE_SECRETS_ENCRYPTION_KEY or rely on A2A_SECRET-derived material on hosted workspace deploys so sibling apps share vault rows.");
169
194
  }
170
195
  /** Whether this deployment has stable workspace-shared key material. */
171
196
  export function hasSharedSecretEncryptionKeyMaterial() {
172
197
  if (typeof process === "undefined")
173
198
  return false;
174
- return Boolean(process.env.SECRETS_ENCRYPTION_KEY ||
199
+ return Boolean(workspaceSharedEncryptionKeyMaterial() ||
200
+ process.env.SECRETS_ENCRYPTION_KEY ||
175
201
  a2aSharedEncryptionKeyMaterial() ||
176
202
  process.env.BETTER_AUTH_SECRET);
177
203
  }