@agent-native/core 0.12.18 → 0.12.20

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 (128) hide show
  1. package/dist/agent/default-model.d.ts +1 -20
  2. package/dist/agent/default-model.d.ts.map +1 -1
  3. package/dist/agent/default-model.js +1 -20
  4. package/dist/agent/default-model.js.map +1 -1
  5. package/dist/agent/engine/ai-sdk-engine.d.ts +2 -1
  6. package/dist/agent/engine/ai-sdk-engine.d.ts.map +1 -1
  7. package/dist/agent/engine/ai-sdk-engine.js +13 -38
  8. package/dist/agent/engine/ai-sdk-engine.js.map +1 -1
  9. package/dist/agent/engine/anthropic-engine.d.ts +1 -1
  10. package/dist/agent/engine/anthropic-engine.d.ts.map +1 -1
  11. package/dist/agent/engine/anthropic-engine.js +3 -11
  12. package/dist/agent/engine/anthropic-engine.js.map +1 -1
  13. package/dist/agent/engine/builder-engine.d.ts +2 -2
  14. package/dist/agent/engine/builder-engine.d.ts.map +1 -1
  15. package/dist/agent/engine/builder-engine.js +3 -21
  16. package/dist/agent/engine/builder-engine.js.map +1 -1
  17. package/dist/agent/model-config.d.ts +99 -0
  18. package/dist/agent/model-config.d.ts.map +1 -0
  19. package/dist/agent/model-config.js +112 -0
  20. package/dist/agent/model-config.js.map +1 -0
  21. package/dist/agent/production-agent.d.ts +1 -1
  22. package/dist/agent/production-agent.d.ts.map +1 -1
  23. package/dist/agent/production-agent.js +13 -1
  24. package/dist/agent/production-agent.js.map +1 -1
  25. package/dist/cli/create.d.ts +4 -1
  26. package/dist/cli/create.d.ts.map +1 -1
  27. package/dist/cli/create.js +19 -4
  28. package/dist/cli/create.js.map +1 -1
  29. package/dist/cli/index.js +1 -1
  30. package/dist/cli/index.js.map +1 -1
  31. package/dist/cli/workspace-dev.d.ts +3 -0
  32. package/dist/cli/workspace-dev.d.ts.map +1 -1
  33. package/dist/cli/workspace-dev.js +67 -27
  34. package/dist/cli/workspace-dev.js.map +1 -1
  35. package/dist/client/AgentPanel.d.ts +4 -0
  36. package/dist/client/AgentPanel.d.ts.map +1 -1
  37. package/dist/client/AgentPanel.js +34 -4
  38. package/dist/client/AgentPanel.js.map +1 -1
  39. package/dist/client/AssistantChat.d.ts +4 -0
  40. package/dist/client/AssistantChat.d.ts.map +1 -1
  41. package/dist/client/AssistantChat.js +10 -2
  42. package/dist/client/AssistantChat.js.map +1 -1
  43. package/dist/client/agent-chat-adapter.d.ts.map +1 -1
  44. package/dist/client/agent-chat-adapter.js +50 -8
  45. package/dist/client/agent-chat-adapter.js.map +1 -1
  46. package/dist/client/analytics.d.ts +4 -0
  47. package/dist/client/analytics.d.ts.map +1 -1
  48. package/dist/client/analytics.js +11 -2
  49. package/dist/client/analytics.js.map +1 -1
  50. package/dist/client/components/CodeRequiredDialog.d.ts.map +1 -1
  51. package/dist/client/components/CodeRequiredDialog.js +10 -9
  52. package/dist/client/components/CodeRequiredDialog.js.map +1 -1
  53. package/dist/client/composer/TiptapComposer.d.ts +5 -1
  54. package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
  55. package/dist/client/composer/TiptapComposer.js +19 -6
  56. package/dist/client/composer/TiptapComposer.js.map +1 -1
  57. package/dist/client/composer/pasted-text.d.ts.map +1 -1
  58. package/dist/client/composer/pasted-text.js +1 -1
  59. package/dist/client/composer/pasted-text.js.map +1 -1
  60. package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
  61. package/dist/client/resources/ResourcesPanel.js +5 -40
  62. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  63. package/dist/client/settings/AutomationsSection.d.ts.map +1 -1
  64. package/dist/client/settings/AutomationsSection.js +3 -30
  65. package/dist/client/settings/AutomationsSection.js.map +1 -1
  66. package/dist/client/terminal/AgentTerminal.d.ts.map +1 -1
  67. package/dist/client/terminal/AgentTerminal.js +44 -14
  68. package/dist/client/terminal/AgentTerminal.js.map +1 -1
  69. package/dist/client/use-chat-models.d.ts.map +1 -1
  70. package/dist/client/use-chat-models.js +41 -3
  71. package/dist/client/use-chat-models.js.map +1 -1
  72. package/dist/deploy/build.d.ts.map +1 -1
  73. package/dist/deploy/build.js +61 -6
  74. package/dist/deploy/build.js.map +1 -1
  75. package/dist/deploy/workspace-deploy.d.ts +1 -1
  76. package/dist/deploy/workspace-deploy.d.ts.map +1 -1
  77. package/dist/deploy/workspace-deploy.js +158 -7
  78. package/dist/deploy/workspace-deploy.js.map +1 -1
  79. package/dist/integrations/plugin.d.ts.map +1 -1
  80. package/dist/integrations/plugin.js +1 -2
  81. package/dist/integrations/plugin.js.map +1 -1
  82. package/dist/integrations/types.d.ts +1 -1
  83. package/dist/integrations/types.d.ts.map +1 -1
  84. package/dist/integrations/types.js.map +1 -1
  85. package/dist/integrations/webhook-handler.d.ts +2 -2
  86. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  87. package/dist/integrations/webhook-handler.js.map +1 -1
  88. package/dist/scripts/agent-engines/manage-agent-engine.js +1 -1
  89. package/dist/scripts/agent-engines/manage-agent-engine.js.map +1 -1
  90. package/dist/scripts/agent-engines/set-agent-engine.js +1 -1
  91. package/dist/scripts/agent-engines/set-agent-engine.js.map +1 -1
  92. package/dist/server/agent-chat-plugin.d.ts +1 -1
  93. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  94. package/dist/server/agent-chat-plugin.js +11 -7
  95. package/dist/server/agent-chat-plugin.js.map +1 -1
  96. package/dist/server/auth.d.ts +1 -0
  97. package/dist/server/auth.d.ts.map +1 -1
  98. package/dist/server/auth.js +49 -9
  99. package/dist/server/auth.js.map +1 -1
  100. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  101. package/dist/server/core-routes-plugin.js +4 -2
  102. package/dist/server/core-routes-plugin.js.map +1 -1
  103. package/dist/server/google-oauth.d.ts.map +1 -1
  104. package/dist/server/google-oauth.js +3 -9
  105. package/dist/server/google-oauth.js.map +1 -1
  106. package/dist/server/sentry-config.d.ts +5 -0
  107. package/dist/server/sentry-config.d.ts.map +1 -0
  108. package/dist/server/sentry-config.js +43 -0
  109. package/dist/server/sentry-config.js.map +1 -0
  110. package/dist/server/sentry-plugin.d.ts +1 -1
  111. package/dist/server/sentry-plugin.js +2 -2
  112. package/dist/server/sentry-plugin.js.map +1 -1
  113. package/dist/server/sentry.d.ts +4 -4
  114. package/dist/server/sentry.d.ts.map +1 -1
  115. package/dist/server/sentry.js +13 -13
  116. package/dist/server/sentry.js.map +1 -1
  117. package/dist/server/ssr-handler.d.ts.map +1 -1
  118. package/dist/server/ssr-handler.js +12 -2
  119. package/dist/server/ssr-handler.js.map +1 -1
  120. package/dist/templates/workspace-root/_gitignore +1 -0
  121. package/dist/usage/store.d.ts.map +1 -1
  122. package/dist/usage/store.js +5 -5
  123. package/dist/usage/store.js.map +1 -1
  124. package/docs/content/deployment.md +23 -3
  125. package/docs/content/multi-app-workspace.md +8 -2
  126. package/docs/content/observability.md +8 -8
  127. package/package.json +1 -1
  128. package/src/templates/workspace-root/_gitignore +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/integrations/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AACzE,OAAO,EACL,QAAQ,EACR,yBAAyB,GAC1B,MAAM,wCAAwC,CAAC;AAMhD,OAAO,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EACL,gBAAgB,EAEhB,iBAAiB,EACjB,cAAc,GACf,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC9E,OAAO,EAAE,QAAQ,EAA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AC/F,CAAC;IACN,CAAC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,EAAE,CAAC;AAEpE,wCAAwC;AACxC,SAAS,UAAU,CAAC,KAAU;IAC5B,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,IAAI,EAAE,CAAC;QAChE,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE,CACjC,OAAO,OAAO,CAAC,GAAG,KAAK,UAAU;YAC/B,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;YACnB,CAAC,CAAE,OAAkC,CAAC,IAAI,CAAC,CAAC;QAChD,MAAM,KAAK,GAAG,SAAS,CAAC,mBAAmB,CAAC,IAAI,MAAM,CAAC;QACvD,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,IAAI,gBAAgB,CAAC;QACnD,OAAO,yBAAyB,CAAC,GAAG,KAAK,MAAM,IAAI,EAAE,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,yBAAyB,CAAC,uBAAuB,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import { defineEventHandler, setResponseStatus, getMethod } from \"h3\";\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport {\n getH3App,\n markDefaultPluginProvided,\n} from \"../server/framework-request-handler.js\";\nimport type {\n PlatformAdapter,\n IntegrationsPluginOptions,\n IntegrationStatus,\n} from \"./types.js\";\nimport { handleWebhook, processIntegrationTask } from \"./webhook-handler.js\";\nimport { DEFAULT_MODEL } from \"../agent/default-model.js\";\nimport {\n claimPendingTask,\n getPendingTask,\n markTaskCompleted,\n markTaskFailed,\n} from \"./pending-tasks-store.js\";\nimport { extractBearerToken, verifyInternalToken } from \"./internal-token.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { getRequestHeader } from \"h3\";\nimport { getIntegrationConfig, saveIntegrationConfig } from \"./config-store.js\";\nimport { slackAdapter } from \"./adapters/slack.js\";\nimport { telegramAdapter } from \"./adapters/telegram.js\";\nimport { whatsappAdapter } from \"./adapters/whatsapp.js\";\nimport { googleDocsAdapter } from \"./adapters/google-docs.js\";\nimport { emailAdapter } from \"./adapters/email.js\";\nimport {\n startGoogleDocsPoller,\n handlePushNotification,\n} from \"./google-docs-poller.js\";\nimport { startPendingTasksRetryJob } from \"./pending-tasks-retry-job.js\";\nimport {\n processA2AContinuationById,\n processDueA2AContinuations,\n} from \"./a2a-continuation-processor.js\";\nimport { resourceGetByPath, SHARED_OWNER } from \"../resources/store.js\";\nimport { getTaskQueueStats } from \"./task-queue-stats.js\";\nimport { getSession } from \"../server/auth.js\";\nimport { getOrgContext } from \"../org/context.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\nlet a2aContinuationRetryInterval: ReturnType<typeof setInterval> | null = null;\n\nfunction startA2AContinuationRetryJob(\n adapters: Map<string, PlatformAdapter>,\n): void {\n if (a2aContinuationRetryInterval) return;\n setTimeout(() => {\n processDueA2AContinuations({ adapters }).catch((err) => {\n console.error(\"[integrations] A2A continuation retry job failed:\", err);\n });\n }, 10_000);\n a2aContinuationRetryInterval = setInterval(() => {\n processDueA2AContinuations({ adapters }).catch((err) => {\n console.error(\"[integrations] A2A continuation retry job failed:\", err);\n });\n }, 60_000);\n}\n\n// ─── Google Pub/Sub OIDC verifier (for Drive changes.watch push) ────────────\n// Cache Google's public keys for OIDC verification. jose handles TTL +\n// refresh internally — same pattern as templates/mail/.../gmail/push.post.ts.\n// Used to verify Google Pub/Sub push notifications carry a valid bearer token\n// signed by a configured service account. Without this, the webhook is wide\n// open to anonymous callers who can force a Drive sync (H7 in the audit).\nconst GOOGLE_JWKS = createRemoteJWKSet(\n new URL(\"https://www.googleapis.com/oauth2/v3/certs\"),\n);\nconst GOOGLE_ISSUERS = [\"https://accounts.google.com\", \"accounts.google.com\"];\n\n/**\n * Verify a Pub/Sub OIDC bearer token. Throws on any verification failure.\n * Requires GOOGLE_DOCS_PUSH_AUDIENCE and GOOGLE_DOCS_PUSH_SIGNER_EMAIL to be\n * set; if either is missing in production, the webhook handler refuses the\n * request entirely (so a misconfigured deployment fails closed, surfacing in\n * Pub/Sub's delivery metrics).\n */\nasync function verifyGoogleDocsPushToken(authHeader: string): Promise<void> {\n if (!authHeader.startsWith(\"Bearer \")) {\n throw new Error(\"missing bearer token\");\n }\n const token = authHeader.slice(7);\n const audience = process.env.GOOGLE_DOCS_PUSH_AUDIENCE;\n if (!audience) {\n throw new Error(\"GOOGLE_DOCS_PUSH_AUDIENCE not configured\");\n }\n const { payload } = await jwtVerify(token, GOOGLE_JWKS, {\n issuer: GOOGLE_ISSUERS,\n audience,\n });\n if (payload.email_verified !== true) {\n throw new Error(\"email_verified claim is not true\");\n }\n // Pin to a specific service account — without this, any Google-issued\n // token with the right audience could trigger a Drive sync.\n const expectedSigner = process.env.GOOGLE_DOCS_PUSH_SIGNER_EMAIL;\n if (!expectedSigner) {\n throw new Error(\"GOOGLE_DOCS_PUSH_SIGNER_EMAIL not configured\");\n }\n if (payload.email !== expectedSigner) {\n throw new Error(`unexpected signer: ${String(payload.email)}`);\n }\n}\n\n/** Built-in adapters, instantiated lazily */\nfunction getDefaultAdapters(): PlatformAdapter[] {\n return [\n slackAdapter(),\n telegramAdapter(),\n whatsappAdapter(),\n googleDocsAdapter(),\n emailAdapter(),\n ];\n}\n\n/**\n * Load resources for the integration agent's system prompt.\n * Mirrors the pattern from agent-chat-plugin.ts.\n */\nasync function loadResourcesForPrompt(owner: string): Promise<string> {\n const resourceNames = [\"AGENTS.md\", \"LEARNINGS.md\"];\n const sections: string[] = [];\n\n for (const name of resourceNames) {\n try {\n const shared = await resourceGetByPath(SHARED_OWNER, name);\n if (shared?.content?.trim()) {\n sections.push(\n `<resource name=\"${name}\" scope=\"shared\">\\n${shared.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n\n if (owner !== SHARED_OWNER) {\n try {\n const personal = await resourceGetByPath(owner, name);\n if (personal?.content?.trim()) {\n sections.push(\n `<resource name=\"${name}\" scope=\"personal\">\\n${personal.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n }\n }\n\n if (sections.length === 0) return \"\";\n return (\n \"\\n\\nThe following resources contain template-specific instructions and user context.\\n\\n\" +\n sections.join(\"\\n\\n\")\n );\n}\n\nconst INTEGRATION_SYSTEM_PROMPT = `You are an AI agent responding via a messaging platform integration (Slack, Telegram, WhatsApp, etc.).\n\nYou have the same capabilities as the web chat agent. Use your tools to help the user.\n\nKeep responses concise — messaging platforms have character limits and users expect shorter replies than in a web interface. Use markdown sparingly (bold and lists are fine, but avoid complex formatting that may not render well on all platforms).\n\nIf a task requires many steps, summarize what you did rather than streaming every detail.`;\n\n/**\n * Creates a Nitro plugin that mounts messaging platform integration webhook routes.\n *\n * Routes:\n * POST /_agent-native/integrations/:platform/webhook — receive platform webhooks\n * GET /_agent-native/integrations/status — all integrations status\n * GET /_agent-native/integrations/:platform/status — single platform status\n * POST /_agent-native/integrations/:platform/enable — enable integration\n * POST /_agent-native/integrations/:platform/disable — disable integration\n * POST /_agent-native/integrations/:platform/setup — platform-specific setup\n */\nexport function createIntegrationsPlugin(\n options?: IntegrationsPluginOptions,\n): NitroPluginDef {\n return async (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"integrations\");\n const adapters = options?.adapters ?? getDefaultAdapters();\n const adapterMap = new Map<string, PlatformAdapter>();\n for (const adapter of adapters) {\n adapterMap.set(adapter.platform, adapter);\n }\n\n const model = options?.model ?? DEFAULT_MODEL;\n // Read the API key at REQUEST time, not plugin-init time. On Netlify\n // Lambda the plugin module loads in a context where env vars from the\n // site's runtime config may not yet be populated, so capturing at\n // init can leave us with an empty string forever. The getter\n // re-resolves on every webhook so freshly-set secrets work without\n // a redeploy.\n const getApiKey = () =>\n options?.apiKey ?? process.env.ANTHROPIC_API_KEY ?? \"\";\n\n // Build the system prompt\n const baseSystemPrompt = options?.systemPrompt ?? INTEGRATION_SYSTEM_PROMPT;\n\n // Resolve actions — auto-include call-agent so the integration agent can\n // delegate to other A2A apps, matching the behavior of the agent-chat plugin.\n const localActions = options?.actions ?? {};\n let callAgentEntry: Record<string, unknown> = {};\n try {\n const mod = await import(\"../scripts/call-agent.js\");\n callAgentEntry = {\n \"call-agent\": {\n tool: mod.tool,\n run: (args: Record<string, string>, context: unknown) =>\n mod.run(args, context as any, options?.appId),\n },\n };\n } catch {\n // call-agent script not available — skip\n }\n const actions = {\n ...localActions,\n ...callAgentEntry,\n } as typeof localActions;\n\n const h3 = getH3App(nitroApp);\n const P = `${FRAMEWORK_ROUTE_PREFIX}/integrations`;\n\n async function requireSession(event: any): Promise<boolean> {\n const session = await getSession(event).catch(() => null);\n if (session?.email) return true;\n setResponseStatus(event, 401);\n return false;\n }\n\n /**\n * Gate destructive integration writes (enable/disable, setup,\n * setIntegrationConfig…) behind an org-owner/admin check.\n *\n * `integration_configs` is keyed `(platform, config_key)` with no\n * owner column in the PRIMARY KEY — so this row is effectively\n * deployment-wide. Any signed-in user toggling /enable or /disable\n * would otherwise affect every other user (a regular org member could\n * disable Slack/email org-wide, write a malicious allowlist for\n * inbound email, etc.). This check enforces that only owners and\n * admins of the user's active org may mutate integration config.\n *\n * Solo / no-org sessions (i.e. ctx.orgId == null) are allowed — that's\n * the local-dev / single-user case where there's no privilege gradient\n * to enforce. The deployment is single-tenant by definition there.\n *\n * Returns an `{ ok: true }` on pass, or `{ ok: false, error }` with the\n * status already set on the event. The error string lines up with the\n * status code (401 → \"unauthorized\"; 403 → admin-required message).\n */\n async function checkOrgAdmin(\n event: any,\n ): Promise<{ ok: true } | { ok: false; error: string }> {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) {\n setResponseStatus(event, 401);\n return { ok: false, error: \"unauthorized\" };\n }\n const ctx = await getOrgContext(event).catch(() => null);\n // Solo (no org membership) — single-tenant flow, allow.\n if (!ctx?.orgId) return { ok: true };\n if (ctx.role === \"owner\" || ctx.role === \"admin\") return { ok: true };\n setResponseStatus(event, 403);\n return {\n ok: false,\n error:\n \"Only organization owners and admins can mutate integration config\",\n };\n }\n\n // ─── Status endpoint (all integrations) ───────────────────────\n h3.use(\n `${P}/status`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (!(await requireSession(event))) return { error: \"unauthorized\" };\n const baseUrl = getBaseUrl(event);\n const statuses: IntegrationStatus[] = [];\n for (const adapter of adapters) {\n const status = await adapter.getStatus(baseUrl);\n const config = await getIntegrationConfig(adapter.platform);\n status.enabled = !!config?.configData?.enabled;\n status.webhookUrl = `${baseUrl}${P}/${adapter.platform}/webhook`;\n if (!status.requiredEnvKeys) {\n try {\n status.requiredEnvKeys = adapter.getRequiredEnvKeys();\n } catch {\n status.requiredEnvKeys = [];\n }\n }\n statuses.push(status);\n }\n return statuses;\n }),\n );\n\n // ─── Task queue status (observability) ───────────────────────\n // GET /_agent-native/integrations/task-queue/status\n // Returns counts + recent failures for the integration_pending_tasks\n // queue. Requires a normal session — this exposes operational data, not\n // platform secrets. If the queue table doesn't exist yet (no inbound\n // webhook has been processed), returns zeroed stats rather than 500.\n h3.use(\n `${P}/task-queue/status`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (!(await requireSession(event))) return { error: \"unauthorized\" };\n try {\n return await getTaskQueueStats();\n } catch (err: any) {\n setResponseStatus(event, 500);\n return { error: err?.message ?? String(err) };\n }\n }),\n );\n\n // ─── Process pending task (cross-platform task queue) ────────\n // POST /_agent-native/integrations/process-task\n // Internal endpoint invoked via fire-and-forget self-webhook from the\n // public webhook handler. Auth: HMAC bearer signed with A2A_SECRET.\n // Each invocation runs the agent loop in a fresh function execution.\n h3.use(\n `${P}/process-task`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const body = (await readBody(event)) as { taskId?: string };\n const taskId = body?.taskId;\n if (!taskId) {\n setResponseStatus(event, 400);\n return { error: \"taskId required\" };\n }\n\n // Auth: HMAC token bound to the task id.\n //\n // In production we MUST require A2A_SECRET — a publicly-callable\n // process-task endpoint lets attackers re-trigger any queued task\n // by guessing or sniffing its id (C3 in the webhook security audit).\n // The atomic SQL claim only prevents *double*-processing, not the\n // first attacker-driven processing.\n //\n // In dev we keep the loose posture so contributors don't have to\n // configure A2A_SECRET to play with the integration locally.\n if (!process.env.A2A_SECRET) {\n if (process.env.NODE_ENV === \"production\") {\n setResponseStatus(event, 503);\n return {\n error:\n \"A2A_SECRET not configured — internal token signing is required to process integration tasks in production.\",\n };\n }\n // Dev: fall through unsigned (the atomic claim still gates double-processing).\n } else {\n const tok = extractBearerToken(\n getRequestHeader(event, \"authorization\"),\n );\n if (!tok || !verifyInternalToken(taskId, tok)) {\n setResponseStatus(event, 401);\n return { error: \"Invalid or expired internal token\" };\n }\n }\n\n // Atomic claim: only one invocation gets to process this task\n const task = await claimPendingTask(taskId);\n if (!task) {\n setResponseStatus(event, 200);\n return { ok: true, skipped: \"already-claimed-or-missing\" };\n }\n\n try {\n const adapter = adapterMap.get(task.platform);\n if (!adapter) {\n await markTaskFailed(taskId, `Unknown platform: ${task.platform}`);\n setResponseStatus(event, 404);\n return { error: \"Unknown platform\" };\n }\n const resources = await loadResourcesForPrompt(task.ownerEmail);\n await processIntegrationTask(task, {\n adapter,\n systemPrompt: baseSystemPrompt + resources,\n actions,\n model,\n apiKey: getApiKey(),\n engine: options?.engine,\n ownerEmail: task.ownerEmail,\n });\n await markTaskCompleted(taskId);\n await processDueA2AContinuations({\n adapters: adapterMap,\n limit: 2,\n }).catch((err) => {\n console.error(\n \"[integrations] A2A continuation opportunistic sweep failed:\",\n err,\n );\n });\n return { ok: true, taskId };\n } catch (err: any) {\n await markTaskFailed(\n taskId,\n err?.message\n ? String(err.message).slice(0, 1000)\n : \"processor failed\",\n );\n // Log the detail server-side; never return the raw error message\n // to the caller. Raw messages have leaked DB error codes, schema\n // names, and stack hints in the past (L3 in the webhook security\n // audit). Sentry / log providers still see the full error.\n console.error(\"[integrations] process-task failure:\", err);\n setResponseStatus(event, 500);\n return { error: \"Internal task failed\" };\n }\n }),\n );\n\n // ─── Process deferred A2A continuation ──────────────────────────\n // POST /_agent-native/integrations/process-a2a-continuation\n // Internal endpoint invoked when call-agent timed out inside an\n // integration processor but the remote A2A task kept running.\n h3.use(\n `${P}/process-a2a-continuation`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const body = (await readBody(event)) as { continuationId?: string };\n const continuationId = body?.continuationId;\n if (!continuationId) {\n setResponseStatus(event, 400);\n return { error: \"continuationId required\" };\n }\n\n if (!process.env.A2A_SECRET) {\n if (process.env.NODE_ENV === \"production\") {\n setResponseStatus(event, 503);\n return {\n error:\n \"A2A_SECRET not configured — internal token signing is required to process A2A continuations in production.\",\n };\n }\n } else {\n const tok = extractBearerToken(\n getRequestHeader(event, \"authorization\"),\n );\n if (!tok || !verifyInternalToken(continuationId, tok)) {\n setResponseStatus(event, 401);\n return { error: \"Invalid or expired internal token\" };\n }\n }\n\n await processA2AContinuationById(continuationId, {\n adapters: adapterMap,\n });\n return { ok: true, continuationId };\n }),\n );\n\n // ─── Per-platform catch-all ───────────────────────────────────\n // Handles: webhook, status, enable, disable, setup for each platform\n h3.use(\n `${P}`,\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n // event.path is stripped to the remainder after the mount prefix\n const raw = (event.path || \"/\").split(\"?\")[0].replace(/^\\//, \"\");\n const parts = raw.split(\"/\").filter(Boolean);\n\n // Already handled by the dedicated /status route above\n if (parts[0] === \"status\" && parts.length === 1) return;\n // Already handled by the dedicated /task-queue/status route above\n if (parts[0] === \"task-queue\") return;\n // Already handled by the dedicated /process-task route above\n if (parts[0] === \"process-task\") return;\n // Already handled by the dedicated /process-a2a-continuation route above\n if (parts[0] === \"process-a2a-continuation\") return;\n\n const platform = parts[0];\n const action = parts[1]; // webhook, status, enable, disable, setup\n\n if (!platform) {\n setResponseStatus(event, 404);\n return { error: \"Platform required\" };\n }\n\n const adapter = adapterMap.get(platform);\n if (!adapter) {\n setResponseStatus(event, 404);\n return { error: `Unknown platform: ${platform}` };\n }\n\n // Set params for handlers that read them\n if (event.context) {\n event.context.params = {\n ...event.context.params,\n platform,\n };\n }\n\n // ─── GET /:platform/status ─────────────────────────────\n if (action === \"status\" && method === \"GET\") {\n if (!(await requireSession(event))) return { error: \"unauthorized\" };\n const baseUrl = getBaseUrl(event);\n const status = await adapter.getStatus(baseUrl);\n const config = await getIntegrationConfig(platform);\n status.enabled = !!config?.configData?.enabled;\n status.webhookUrl = `${baseUrl}${P}/${platform}/webhook`;\n if (!status.requiredEnvKeys) {\n try {\n status.requiredEnvKeys = adapter.getRequiredEnvKeys();\n } catch {\n status.requiredEnvKeys = [];\n }\n }\n return status;\n }\n\n // ─── POST /:platform/webhook ───────────────────────────\n if (action === \"webhook\" && method === \"POST\") {\n // Google Docs push notifications bypass the normal webhook flow —\n // they're opaque \"something changed\" pings, not message payloads.\n // We MUST verify the Pub/Sub OIDC token here. Without it, anyone\n // could POST any body to this URL and force a Drive changes pull\n // (H7 in the webhook security audit).\n if (platform === \"google-docs\") {\n const audience = process.env.GOOGLE_DOCS_PUSH_AUDIENCE;\n if (!audience) {\n if (process.env.NODE_ENV === \"production\") {\n // Fail closed in prod so a misconfigured deployment surfaces\n // in Pub/Sub's delivery metrics rather than silently\n // accepting anonymous requests.\n setResponseStatus(event, 503);\n return {\n ok: false,\n error:\n \"google-docs push endpoint disabled (audience not configured)\",\n };\n }\n // Dev: keep the loose posture so contributors can play with the\n // integration locally without configuring Pub/Sub.\n handlePushNotification().catch((err) => {\n console.error(\"[google-docs] Push handler error:\", err);\n });\n return \"ok\";\n }\n const authHeader = getRequestHeader(event, \"authorization\") || \"\";\n try {\n await verifyGoogleDocsPushToken(authHeader);\n } catch (err: any) {\n console.warn(\n `[google-docs] OIDC verify failed: ${err?.message ?? String(err)}`,\n );\n setResponseStatus(event, 401);\n return { ok: false, error: \"unauthorized\" };\n }\n handlePushNotification().catch((err) => {\n console.error(\"[google-docs] Push handler error:\", err);\n });\n return \"ok\";\n }\n\n // Handle platform verification challenges (e.g. Slack url_verification)\n // before checking enable state or parsing the message.\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return verification.response ?? \"ok\";\n }\n\n const config = await getIntegrationConfig(platform);\n if (!config?.configData?.enabled) {\n setResponseStatus(event, 404);\n return { error: `Integration ${platform} is not enabled` };\n }\n\n // Verify the webhook signature BEFORE parsing. We pre-parse the\n // body here (so handleWebhook can skip its second readBody, which\n // hangs on streaming providers), and that means handleWebhook's\n // own verifyWebhook step is bypassed. Without this call anyone\n // could POST a forged Slack/Telegram/email payload.\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n setResponseStatus(event, 401);\n return { error: \"Invalid webhook signature\" };\n }\n\n const incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n setResponseStatus(event, 200);\n return \"ok\";\n }\n let owner = `integration@${platform}`;\n if (options?.resolveOwner) {\n try {\n owner = await options.resolveOwner(incoming);\n } catch (err) {\n console.error(\n `[integrations] resolveOwner failed, using default:`,\n err,\n );\n }\n }\n const resources = await loadResourcesForPrompt(owner);\n const systemPrompt = baseSystemPrompt + resources;\n const result = await handleWebhook(event, {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey: getApiKey(),\n engine: options?.engine,\n ownerEmail: owner,\n beforeProcess: options?.beforeProcess,\n incoming,\n });\n setResponseStatus(event, result.status);\n return result.body;\n }\n\n // ─── POST /:platform/enable ────────────────────────────\n if (action === \"enable\" && method === \"POST\") {\n const adminCheck = await checkOrgAdmin(event);\n if (adminCheck.ok === false) return { error: adminCheck.error };\n // Stamp the org-admin who toggled this so downstream code can\n // tell who is responsible — useful for audit logs even though\n // the row itself remains deployment-wide.\n const session = await getSession(event).catch(() => null);\n await saveIntegrationConfig(\n platform,\n { enabled: true },\n \"default\",\n session?.email,\n );\n return { ok: true, platform, enabled: true };\n }\n\n // ─── POST /:platform/disable ───────────────────────────\n if (action === \"disable\" && method === \"POST\") {\n const adminCheck = await checkOrgAdmin(event);\n if (adminCheck.ok === false) return { error: adminCheck.error };\n const session = await getSession(event).catch(() => null);\n await saveIntegrationConfig(\n platform,\n { enabled: false },\n \"default\",\n session?.email,\n );\n return { ok: true, platform, enabled: false };\n }\n\n // ─── POST /:platform/setup ─────────────────────────────\n if (action === \"setup\" && method === \"POST\") {\n const adminCheck = await checkOrgAdmin(event);\n if (adminCheck.ok === false) return { error: adminCheck.error };\n if (platform === \"telegram\") {\n const baseUrl = getBaseUrl(event);\n const webhookUrl = `${baseUrl}${P}/telegram/webhook`;\n const token = process.env.TELEGRAM_BOT_TOKEN;\n if (!token) {\n setResponseStatus(event, 400);\n return { error: \"TELEGRAM_BOT_TOKEN not configured\" };\n }\n try {\n const res = await fetch(\n `https://api.telegram.org/bot${token}/setWebhook`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ url: webhookUrl }),\n },\n );\n const data = await res.json();\n return { ok: true, platform, webhookUrl, result: data };\n } catch (err: any) {\n setResponseStatus(event, 500);\n return { error: err.message };\n }\n }\n return { ok: true, platform, message: \"No setup required\" };\n }\n\n setResponseStatus(event, 404);\n return { error: \"Not found\" };\n }),\n );\n\n // ─── Start pending-tasks retry sweeper ────────────────────────\n // Sweeps the integration_pending_tasks queue every 60s and re-fires the\n // processor for any tasks that got stuck (initial dispatch lost or\n // processor killed mid-flight). No-ops gracefully if the queue table\n // hasn't been created yet on this deployment.\n startPendingTasksRetryJob({\n webhookBaseUrl: process.env.WEBHOOK_BASE_URL,\n });\n startA2AContinuationRetryJob(adapterMap);\n\n // ─── Start Google Docs poller/push ────────────────────────────\n if (adapterMap.has(\"google-docs\")) {\n // Defer startup slightly so the server is fully ready\n setTimeout(() => {\n // We don't know the base URL at plugin init time — it depends on\n // the incoming request. For push mode, the webhook URL needs to be\n // resolved. We pass it as a special option; the poller will attempt\n // to register a watch when the first request reveals the base URL,\n // or use the WEBHOOK_BASE_URL env var if set.\n const baseUrl = process.env.WEBHOOK_BASE_URL;\n const webhookUrl = baseUrl\n ? `${withConfiguredAppBasePath(baseUrl)}${P}/google-docs/webhook`\n : undefined;\n\n startGoogleDocsPoller({\n systemPrompt: baseSystemPrompt,\n actions,\n model,\n apiKey: getApiKey(),\n ownerEmail: \"integration@google-docs\",\n webhookUrl,\n });\n }, 2000);\n }\n\n if (process.env.DEBUG)\n console.log(\n `[integrations] Mounted integration routes for: ${adapters.map((a) => a.platform).join(\", \")}`,\n );\n };\n}\n\n/**\n * Default integrations plugin — auto-mounts all adapters.\n */\nexport const defaultIntegrationsPlugin = createIntegrationsPlugin();\n\n/** Extract base URL from the request */\nfunction getBaseUrl(event: any): string {\n try {\n const headers = event.node?.req?.headers || event.headers || {};\n const getHeader = (name: string) =>\n typeof headers.get === \"function\"\n ? headers.get(name)\n : (headers as Record<string, string>)[name];\n const proto = getHeader(\"x-forwarded-proto\") || \"http\";\n const host = getHeader(\"host\") || \"localhost:3000\";\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\"http://localhost:3000\");\n }\n}\n"]}
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/integrations/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AACrD,OAAO,EAAE,sBA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L,MAAM,EAAE,SAAS,EAAE;oBACnB,UAAU,EAAE,yBAAyB;oBACrC,UAAU;iBACX,CAAC,CAAC;YACL,CAAC,EAAE,IAAI,CAAC,CAAC;QACX,CAAC;QAED,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK;YACnB,OAAO,CAAC,GAAG,CACT,kDAAkD,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAC/F,CAAC;IACN,CAAC,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,wBAAwB,EAAE,CAAC;AAEpE,wCAAwC;AACxC,SAAS,UAAU,CAAC,KAAU;IAC5B,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,IAAI,KAAK,CAAC,OAAO,IAAI,EAAE,CAAC;QAChE,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,EAAE,CACjC,OAAO,OAAO,CAAC,GAAG,KAAK,UAAU;YAC/B,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;YACnB,CAAC,CAAE,OAAkC,CAAC,IAAI,CAAC,CAAC;QAChD,MAAM,KAAK,GAAG,SAAS,CAAC,mBAAmB,CAAC,IAAI,MAAM,CAAC;QACvD,MAAM,IAAI,GAAG,SAAS,CAAC,MAAM,CAAC,IAAI,gBAAgB,CAAC;QACnD,OAAO,yBAAyB,CAAC,GAAG,KAAK,MAAM,IAAI,EAAE,CAAC,CAAC;IACzD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,yBAAyB,CAAC,uBAAuB,CAAC,CAAC;IAC5D,CAAC;AACH,CAAC","sourcesContent":["import { defineEventHandler, setResponseStatus, getMethod } from \"h3\";\nimport { createRemoteJWKSet, jwtVerify } from \"jose\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport {\n getH3App,\n markDefaultPluginProvided,\n} from \"../server/framework-request-handler.js\";\nimport type {\n PlatformAdapter,\n IntegrationsPluginOptions,\n IntegrationStatus,\n} from \"./types.js\";\nimport { handleWebhook, processIntegrationTask } from \"./webhook-handler.js\";\nimport {\n claimPendingTask,\n getPendingTask,\n markTaskCompleted,\n markTaskFailed,\n} from \"./pending-tasks-store.js\";\nimport { extractBearerToken, verifyInternalToken } from \"./internal-token.js\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { getRequestHeader } from \"h3\";\nimport { getIntegrationConfig, saveIntegrationConfig } from \"./config-store.js\";\nimport { slackAdapter } from \"./adapters/slack.js\";\nimport { telegramAdapter } from \"./adapters/telegram.js\";\nimport { whatsappAdapter } from \"./adapters/whatsapp.js\";\nimport { googleDocsAdapter } from \"./adapters/google-docs.js\";\nimport { emailAdapter } from \"./adapters/email.js\";\nimport {\n startGoogleDocsPoller,\n handlePushNotification,\n} from \"./google-docs-poller.js\";\nimport { startPendingTasksRetryJob } from \"./pending-tasks-retry-job.js\";\nimport {\n processA2AContinuationById,\n processDueA2AContinuations,\n} from \"./a2a-continuation-processor.js\";\nimport { resourceGetByPath, SHARED_OWNER } from \"../resources/store.js\";\nimport { getTaskQueueStats } from \"./task-queue-stats.js\";\nimport { getSession } from \"../server/auth.js\";\nimport { getOrgContext } from \"../org/context.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\n\ntype NitroPluginDef = (nitroApp: any) => void | Promise<void>;\n\nlet a2aContinuationRetryInterval: ReturnType<typeof setInterval> | null = null;\n\nfunction startA2AContinuationRetryJob(\n adapters: Map<string, PlatformAdapter>,\n): void {\n if (a2aContinuationRetryInterval) return;\n setTimeout(() => {\n processDueA2AContinuations({ adapters }).catch((err) => {\n console.error(\"[integrations] A2A continuation retry job failed:\", err);\n });\n }, 10_000);\n a2aContinuationRetryInterval = setInterval(() => {\n processDueA2AContinuations({ adapters }).catch((err) => {\n console.error(\"[integrations] A2A continuation retry job failed:\", err);\n });\n }, 60_000);\n}\n\n// ─── Google Pub/Sub OIDC verifier (for Drive changes.watch push) ────────────\n// Cache Google's public keys for OIDC verification. jose handles TTL +\n// refresh internally — same pattern as templates/mail/.../gmail/push.post.ts.\n// Used to verify Google Pub/Sub push notifications carry a valid bearer token\n// signed by a configured service account. Without this, the webhook is wide\n// open to anonymous callers who can force a Drive sync (H7 in the audit).\nconst GOOGLE_JWKS = createRemoteJWKSet(\n new URL(\"https://www.googleapis.com/oauth2/v3/certs\"),\n);\nconst GOOGLE_ISSUERS = [\"https://accounts.google.com\", \"accounts.google.com\"];\n\n/**\n * Verify a Pub/Sub OIDC bearer token. Throws on any verification failure.\n * Requires GOOGLE_DOCS_PUSH_AUDIENCE and GOOGLE_DOCS_PUSH_SIGNER_EMAIL to be\n * set; if either is missing in production, the webhook handler refuses the\n * request entirely (so a misconfigured deployment fails closed, surfacing in\n * Pub/Sub's delivery metrics).\n */\nasync function verifyGoogleDocsPushToken(authHeader: string): Promise<void> {\n if (!authHeader.startsWith(\"Bearer \")) {\n throw new Error(\"missing bearer token\");\n }\n const token = authHeader.slice(7);\n const audience = process.env.GOOGLE_DOCS_PUSH_AUDIENCE;\n if (!audience) {\n throw new Error(\"GOOGLE_DOCS_PUSH_AUDIENCE not configured\");\n }\n const { payload } = await jwtVerify(token, GOOGLE_JWKS, {\n issuer: GOOGLE_ISSUERS,\n audience,\n });\n if (payload.email_verified !== true) {\n throw new Error(\"email_verified claim is not true\");\n }\n // Pin to a specific service account — without this, any Google-issued\n // token with the right audience could trigger a Drive sync.\n const expectedSigner = process.env.GOOGLE_DOCS_PUSH_SIGNER_EMAIL;\n if (!expectedSigner) {\n throw new Error(\"GOOGLE_DOCS_PUSH_SIGNER_EMAIL not configured\");\n }\n if (payload.email !== expectedSigner) {\n throw new Error(`unexpected signer: ${String(payload.email)}`);\n }\n}\n\n/** Built-in adapters, instantiated lazily */\nfunction getDefaultAdapters(): PlatformAdapter[] {\n return [\n slackAdapter(),\n telegramAdapter(),\n whatsappAdapter(),\n googleDocsAdapter(),\n emailAdapter(),\n ];\n}\n\n/**\n * Load resources for the integration agent's system prompt.\n * Mirrors the pattern from agent-chat-plugin.ts.\n */\nasync function loadResourcesForPrompt(owner: string): Promise<string> {\n const resourceNames = [\"AGENTS.md\", \"LEARNINGS.md\"];\n const sections: string[] = [];\n\n for (const name of resourceNames) {\n try {\n const shared = await resourceGetByPath(SHARED_OWNER, name);\n if (shared?.content?.trim()) {\n sections.push(\n `<resource name=\"${name}\" scope=\"shared\">\\n${shared.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n\n if (owner !== SHARED_OWNER) {\n try {\n const personal = await resourceGetByPath(owner, name);\n if (personal?.content?.trim()) {\n sections.push(\n `<resource name=\"${name}\" scope=\"personal\">\\n${personal.content.trim()}\\n</resource>`,\n );\n }\n } catch {}\n }\n }\n\n if (sections.length === 0) return \"\";\n return (\n \"\\n\\nThe following resources contain template-specific instructions and user context.\\n\\n\" +\n sections.join(\"\\n\\n\")\n );\n}\n\nconst INTEGRATION_SYSTEM_PROMPT = `You are an AI agent responding via a messaging platform integration (Slack, Telegram, WhatsApp, etc.).\n\nYou have the same capabilities as the web chat agent. Use your tools to help the user.\n\nKeep responses concise — messaging platforms have character limits and users expect shorter replies than in a web interface. Use markdown sparingly (bold and lists are fine, but avoid complex formatting that may not render well on all platforms).\n\nIf a task requires many steps, summarize what you did rather than streaming every detail.`;\n\n/**\n * Creates a Nitro plugin that mounts messaging platform integration webhook routes.\n *\n * Routes:\n * POST /_agent-native/integrations/:platform/webhook — receive platform webhooks\n * GET /_agent-native/integrations/status — all integrations status\n * GET /_agent-native/integrations/:platform/status — single platform status\n * POST /_agent-native/integrations/:platform/enable — enable integration\n * POST /_agent-native/integrations/:platform/disable — disable integration\n * POST /_agent-native/integrations/:platform/setup — platform-specific setup\n */\nexport function createIntegrationsPlugin(\n options?: IntegrationsPluginOptions,\n): NitroPluginDef {\n return async (nitroApp: any) => {\n markDefaultPluginProvided(nitroApp, \"integrations\");\n const adapters = options?.adapters ?? getDefaultAdapters();\n const adapterMap = new Map<string, PlatformAdapter>();\n for (const adapter of adapters) {\n adapterMap.set(adapter.platform, adapter);\n }\n\n const model = options?.model;\n // Read the API key at REQUEST time, not plugin-init time. On Netlify\n // Lambda the plugin module loads in a context where env vars from the\n // site's runtime config may not yet be populated, so capturing at\n // init can leave us with an empty string forever. The getter\n // re-resolves on every webhook so freshly-set secrets work without\n // a redeploy.\n const getApiKey = () =>\n options?.apiKey ?? process.env.ANTHROPIC_API_KEY ?? \"\";\n\n // Build the system prompt\n const baseSystemPrompt = options?.systemPrompt ?? INTEGRATION_SYSTEM_PROMPT;\n\n // Resolve actions — auto-include call-agent so the integration agent can\n // delegate to other A2A apps, matching the behavior of the agent-chat plugin.\n const localActions = options?.actions ?? {};\n let callAgentEntry: Record<string, unknown> = {};\n try {\n const mod = await import(\"../scripts/call-agent.js\");\n callAgentEntry = {\n \"call-agent\": {\n tool: mod.tool,\n run: (args: Record<string, string>, context: unknown) =>\n mod.run(args, context as any, options?.appId),\n },\n };\n } catch {\n // call-agent script not available — skip\n }\n const actions = {\n ...localActions,\n ...callAgentEntry,\n } as typeof localActions;\n\n const h3 = getH3App(nitroApp);\n const P = `${FRAMEWORK_ROUTE_PREFIX}/integrations`;\n\n async function requireSession(event: any): Promise<boolean> {\n const session = await getSession(event).catch(() => null);\n if (session?.email) return true;\n setResponseStatus(event, 401);\n return false;\n }\n\n /**\n * Gate destructive integration writes (enable/disable, setup,\n * setIntegrationConfig…) behind an org-owner/admin check.\n *\n * `integration_configs` is keyed `(platform, config_key)` with no\n * owner column in the PRIMARY KEY — so this row is effectively\n * deployment-wide. Any signed-in user toggling /enable or /disable\n * would otherwise affect every other user (a regular org member could\n * disable Slack/email org-wide, write a malicious allowlist for\n * inbound email, etc.). This check enforces that only owners and\n * admins of the user's active org may mutate integration config.\n *\n * Solo / no-org sessions (i.e. ctx.orgId == null) are allowed — that's\n * the local-dev / single-user case where there's no privilege gradient\n * to enforce. The deployment is single-tenant by definition there.\n *\n * Returns an `{ ok: true }` on pass, or `{ ok: false, error }` with the\n * status already set on the event. The error string lines up with the\n * status code (401 → \"unauthorized\"; 403 → admin-required message).\n */\n async function checkOrgAdmin(\n event: any,\n ): Promise<{ ok: true } | { ok: false; error: string }> {\n const session = await getSession(event).catch(() => null);\n if (!session?.email) {\n setResponseStatus(event, 401);\n return { ok: false, error: \"unauthorized\" };\n }\n const ctx = await getOrgContext(event).catch(() => null);\n // Solo (no org membership) — single-tenant flow, allow.\n if (!ctx?.orgId) return { ok: true };\n if (ctx.role === \"owner\" || ctx.role === \"admin\") return { ok: true };\n setResponseStatus(event, 403);\n return {\n ok: false,\n error:\n \"Only organization owners and admins can mutate integration config\",\n };\n }\n\n // ─── Status endpoint (all integrations) ───────────────────────\n h3.use(\n `${P}/status`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (!(await requireSession(event))) return { error: \"unauthorized\" };\n const baseUrl = getBaseUrl(event);\n const statuses: IntegrationStatus[] = [];\n for (const adapter of adapters) {\n const status = await adapter.getStatus(baseUrl);\n const config = await getIntegrationConfig(adapter.platform);\n status.enabled = !!config?.configData?.enabled;\n status.webhookUrl = `${baseUrl}${P}/${adapter.platform}/webhook`;\n if (!status.requiredEnvKeys) {\n try {\n status.requiredEnvKeys = adapter.getRequiredEnvKeys();\n } catch {\n status.requiredEnvKeys = [];\n }\n }\n statuses.push(status);\n }\n return statuses;\n }),\n );\n\n // ─── Task queue status (observability) ───────────────────────\n // GET /_agent-native/integrations/task-queue/status\n // Returns counts + recent failures for the integration_pending_tasks\n // queue. Requires a normal session — this exposes operational data, not\n // platform secrets. If the queue table doesn't exist yet (no inbound\n // webhook has been processed), returns zeroed stats rather than 500.\n h3.use(\n `${P}/task-queue/status`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n if (!(await requireSession(event))) return { error: \"unauthorized\" };\n try {\n return await getTaskQueueStats();\n } catch (err: any) {\n setResponseStatus(event, 500);\n return { error: err?.message ?? String(err) };\n }\n }),\n );\n\n // ─── Process pending task (cross-platform task queue) ────────\n // POST /_agent-native/integrations/process-task\n // Internal endpoint invoked via fire-and-forget self-webhook from the\n // public webhook handler. Auth: HMAC bearer signed with A2A_SECRET.\n // Each invocation runs the agent loop in a fresh function execution.\n h3.use(\n `${P}/process-task`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const body = (await readBody(event)) as { taskId?: string };\n const taskId = body?.taskId;\n if (!taskId) {\n setResponseStatus(event, 400);\n return { error: \"taskId required\" };\n }\n\n // Auth: HMAC token bound to the task id.\n //\n // In production we MUST require A2A_SECRET — a publicly-callable\n // process-task endpoint lets attackers re-trigger any queued task\n // by guessing or sniffing its id (C3 in the webhook security audit).\n // The atomic SQL claim only prevents *double*-processing, not the\n // first attacker-driven processing.\n //\n // In dev we keep the loose posture so contributors don't have to\n // configure A2A_SECRET to play with the integration locally.\n if (!process.env.A2A_SECRET) {\n if (process.env.NODE_ENV === \"production\") {\n setResponseStatus(event, 503);\n return {\n error:\n \"A2A_SECRET not configured — internal token signing is required to process integration tasks in production.\",\n };\n }\n // Dev: fall through unsigned (the atomic claim still gates double-processing).\n } else {\n const tok = extractBearerToken(\n getRequestHeader(event, \"authorization\"),\n );\n if (!tok || !verifyInternalToken(taskId, tok)) {\n setResponseStatus(event, 401);\n return { error: \"Invalid or expired internal token\" };\n }\n }\n\n // Atomic claim: only one invocation gets to process this task\n const task = await claimPendingTask(taskId);\n if (!task) {\n setResponseStatus(event, 200);\n return { ok: true, skipped: \"already-claimed-or-missing\" };\n }\n\n try {\n const adapter = adapterMap.get(task.platform);\n if (!adapter) {\n await markTaskFailed(taskId, `Unknown platform: ${task.platform}`);\n setResponseStatus(event, 404);\n return { error: \"Unknown platform\" };\n }\n const resources = await loadResourcesForPrompt(task.ownerEmail);\n await processIntegrationTask(task, {\n adapter,\n systemPrompt: baseSystemPrompt + resources,\n actions,\n model,\n apiKey: getApiKey(),\n engine: options?.engine,\n ownerEmail: task.ownerEmail,\n });\n await markTaskCompleted(taskId);\n await processDueA2AContinuations({\n adapters: adapterMap,\n limit: 2,\n }).catch((err) => {\n console.error(\n \"[integrations] A2A continuation opportunistic sweep failed:\",\n err,\n );\n });\n return { ok: true, taskId };\n } catch (err: any) {\n await markTaskFailed(\n taskId,\n err?.message\n ? String(err.message).slice(0, 1000)\n : \"processor failed\",\n );\n // Log the detail server-side; never return the raw error message\n // to the caller. Raw messages have leaked DB error codes, schema\n // names, and stack hints in the past (L3 in the webhook security\n // audit). Sentry / log providers still see the full error.\n console.error(\"[integrations] process-task failure:\", err);\n setResponseStatus(event, 500);\n return { error: \"Internal task failed\" };\n }\n }),\n );\n\n // ─── Process deferred A2A continuation ──────────────────────────\n // POST /_agent-native/integrations/process-a2a-continuation\n // Internal endpoint invoked when call-agent timed out inside an\n // integration processor but the remote A2A task kept running.\n h3.use(\n `${P}/process-a2a-continuation`,\n defineEventHandler(async (event) => {\n if (getMethod(event) !== \"POST\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n const body = (await readBody(event)) as { continuationId?: string };\n const continuationId = body?.continuationId;\n if (!continuationId) {\n setResponseStatus(event, 400);\n return { error: \"continuationId required\" };\n }\n\n if (!process.env.A2A_SECRET) {\n if (process.env.NODE_ENV === \"production\") {\n setResponseStatus(event, 503);\n return {\n error:\n \"A2A_SECRET not configured — internal token signing is required to process A2A continuations in production.\",\n };\n }\n } else {\n const tok = extractBearerToken(\n getRequestHeader(event, \"authorization\"),\n );\n if (!tok || !verifyInternalToken(continuationId, tok)) {\n setResponseStatus(event, 401);\n return { error: \"Invalid or expired internal token\" };\n }\n }\n\n await processA2AContinuationById(continuationId, {\n adapters: adapterMap,\n });\n return { ok: true, continuationId };\n }),\n );\n\n // ─── Per-platform catch-all ───────────────────────────────────\n // Handles: webhook, status, enable, disable, setup for each platform\n h3.use(\n `${P}`,\n defineEventHandler(async (event) => {\n const method = getMethod(event);\n // event.path is stripped to the remainder after the mount prefix\n const raw = (event.path || \"/\").split(\"?\")[0].replace(/^\\//, \"\");\n const parts = raw.split(\"/\").filter(Boolean);\n\n // Already handled by the dedicated /status route above\n if (parts[0] === \"status\" && parts.length === 1) return;\n // Already handled by the dedicated /task-queue/status route above\n if (parts[0] === \"task-queue\") return;\n // Already handled by the dedicated /process-task route above\n if (parts[0] === \"process-task\") return;\n // Already handled by the dedicated /process-a2a-continuation route above\n if (parts[0] === \"process-a2a-continuation\") return;\n\n const platform = parts[0];\n const action = parts[1]; // webhook, status, enable, disable, setup\n\n if (!platform) {\n setResponseStatus(event, 404);\n return { error: \"Platform required\" };\n }\n\n const adapter = adapterMap.get(platform);\n if (!adapter) {\n setResponseStatus(event, 404);\n return { error: `Unknown platform: ${platform}` };\n }\n\n // Set params for handlers that read them\n if (event.context) {\n event.context.params = {\n ...event.context.params,\n platform,\n };\n }\n\n // ─── GET /:platform/status ─────────────────────────────\n if (action === \"status\" && method === \"GET\") {\n if (!(await requireSession(event))) return { error: \"unauthorized\" };\n const baseUrl = getBaseUrl(event);\n const status = await adapter.getStatus(baseUrl);\n const config = await getIntegrationConfig(platform);\n status.enabled = !!config?.configData?.enabled;\n status.webhookUrl = `${baseUrl}${P}/${platform}/webhook`;\n if (!status.requiredEnvKeys) {\n try {\n status.requiredEnvKeys = adapter.getRequiredEnvKeys();\n } catch {\n status.requiredEnvKeys = [];\n }\n }\n return status;\n }\n\n // ─── POST /:platform/webhook ───────────────────────────\n if (action === \"webhook\" && method === \"POST\") {\n // Google Docs push notifications bypass the normal webhook flow —\n // they're opaque \"something changed\" pings, not message payloads.\n // We MUST verify the Pub/Sub OIDC token here. Without it, anyone\n // could POST any body to this URL and force a Drive changes pull\n // (H7 in the webhook security audit).\n if (platform === \"google-docs\") {\n const audience = process.env.GOOGLE_DOCS_PUSH_AUDIENCE;\n if (!audience) {\n if (process.env.NODE_ENV === \"production\") {\n // Fail closed in prod so a misconfigured deployment surfaces\n // in Pub/Sub's delivery metrics rather than silently\n // accepting anonymous requests.\n setResponseStatus(event, 503);\n return {\n ok: false,\n error:\n \"google-docs push endpoint disabled (audience not configured)\",\n };\n }\n // Dev: keep the loose posture so contributors can play with the\n // integration locally without configuring Pub/Sub.\n handlePushNotification().catch((err) => {\n console.error(\"[google-docs] Push handler error:\", err);\n });\n return \"ok\";\n }\n const authHeader = getRequestHeader(event, \"authorization\") || \"\";\n try {\n await verifyGoogleDocsPushToken(authHeader);\n } catch (err: any) {\n console.warn(\n `[google-docs] OIDC verify failed: ${err?.message ?? String(err)}`,\n );\n setResponseStatus(event, 401);\n return { ok: false, error: \"unauthorized\" };\n }\n handlePushNotification().catch((err) => {\n console.error(\"[google-docs] Push handler error:\", err);\n });\n return \"ok\";\n }\n\n // Handle platform verification challenges (e.g. Slack url_verification)\n // before checking enable state or parsing the message.\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return verification.response ?? \"ok\";\n }\n\n const config = await getIntegrationConfig(platform);\n if (!config?.configData?.enabled) {\n setResponseStatus(event, 404);\n return { error: `Integration ${platform} is not enabled` };\n }\n\n // Verify the webhook signature BEFORE parsing. We pre-parse the\n // body here (so handleWebhook can skip its second readBody, which\n // hangs on streaming providers), and that means handleWebhook's\n // own verifyWebhook step is bypassed. Without this call anyone\n // could POST a forged Slack/Telegram/email payload.\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n setResponseStatus(event, 401);\n return { error: \"Invalid webhook signature\" };\n }\n\n const incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n setResponseStatus(event, 200);\n return \"ok\";\n }\n let owner = `integration@${platform}`;\n if (options?.resolveOwner) {\n try {\n owner = await options.resolveOwner(incoming);\n } catch (err) {\n console.error(\n `[integrations] resolveOwner failed, using default:`,\n err,\n );\n }\n }\n const resources = await loadResourcesForPrompt(owner);\n const systemPrompt = baseSystemPrompt + resources;\n const result = await handleWebhook(event, {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey: getApiKey(),\n engine: options?.engine,\n ownerEmail: owner,\n beforeProcess: options?.beforeProcess,\n incoming,\n });\n setResponseStatus(event, result.status);\n return result.body;\n }\n\n // ─── POST /:platform/enable ────────────────────────────\n if (action === \"enable\" && method === \"POST\") {\n const adminCheck = await checkOrgAdmin(event);\n if (adminCheck.ok === false) return { error: adminCheck.error };\n // Stamp the org-admin who toggled this so downstream code can\n // tell who is responsible — useful for audit logs even though\n // the row itself remains deployment-wide.\n const session = await getSession(event).catch(() => null);\n await saveIntegrationConfig(\n platform,\n { enabled: true },\n \"default\",\n session?.email,\n );\n return { ok: true, platform, enabled: true };\n }\n\n // ─── POST /:platform/disable ───────────────────────────\n if (action === \"disable\" && method === \"POST\") {\n const adminCheck = await checkOrgAdmin(event);\n if (adminCheck.ok === false) return { error: adminCheck.error };\n const session = await getSession(event).catch(() => null);\n await saveIntegrationConfig(\n platform,\n { enabled: false },\n \"default\",\n session?.email,\n );\n return { ok: true, platform, enabled: false };\n }\n\n // ─── POST /:platform/setup ─────────────────────────────\n if (action === \"setup\" && method === \"POST\") {\n const adminCheck = await checkOrgAdmin(event);\n if (adminCheck.ok === false) return { error: adminCheck.error };\n if (platform === \"telegram\") {\n const baseUrl = getBaseUrl(event);\n const webhookUrl = `${baseUrl}${P}/telegram/webhook`;\n const token = process.env.TELEGRAM_BOT_TOKEN;\n if (!token) {\n setResponseStatus(event, 400);\n return { error: \"TELEGRAM_BOT_TOKEN not configured\" };\n }\n try {\n const res = await fetch(\n `https://api.telegram.org/bot${token}/setWebhook`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ url: webhookUrl }),\n },\n );\n const data = await res.json();\n return { ok: true, platform, webhookUrl, result: data };\n } catch (err: any) {\n setResponseStatus(event, 500);\n return { error: err.message };\n }\n }\n return { ok: true, platform, message: \"No setup required\" };\n }\n\n setResponseStatus(event, 404);\n return { error: \"Not found\" };\n }),\n );\n\n // ─── Start pending-tasks retry sweeper ────────────────────────\n // Sweeps the integration_pending_tasks queue every 60s and re-fires the\n // processor for any tasks that got stuck (initial dispatch lost or\n // processor killed mid-flight). No-ops gracefully if the queue table\n // hasn't been created yet on this deployment.\n startPendingTasksRetryJob({\n webhookBaseUrl: process.env.WEBHOOK_BASE_URL,\n });\n startA2AContinuationRetryJob(adapterMap);\n\n // ─── Start Google Docs poller/push ────────────────────────────\n if (adapterMap.has(\"google-docs\")) {\n // Defer startup slightly so the server is fully ready\n setTimeout(() => {\n // We don't know the base URL at plugin init time — it depends on\n // the incoming request. For push mode, the webhook URL needs to be\n // resolved. We pass it as a special option; the poller will attempt\n // to register a watch when the first request reveals the base URL,\n // or use the WEBHOOK_BASE_URL env var if set.\n const baseUrl = process.env.WEBHOOK_BASE_URL;\n const webhookUrl = baseUrl\n ? `${withConfiguredAppBasePath(baseUrl)}${P}/google-docs/webhook`\n : undefined;\n\n startGoogleDocsPoller({\n systemPrompt: baseSystemPrompt,\n actions,\n model,\n apiKey: getApiKey(),\n ownerEmail: \"integration@google-docs\",\n webhookUrl,\n });\n }, 2000);\n }\n\n if (process.env.DEBUG)\n console.log(\n `[integrations] Mounted integration routes for: ${adapters.map((a) => a.platform).join(\", \")}`,\n );\n };\n}\n\n/**\n * Default integrations plugin — auto-mounts all adapters.\n */\nexport const defaultIntegrationsPlugin = createIntegrationsPlugin();\n\n/** Extract base URL from the request */\nfunction getBaseUrl(event: any): string {\n try {\n const headers = event.node?.req?.headers || event.headers || {};\n const getHeader = (name: string) =>\n typeof headers.get === \"function\"\n ? headers.get(name)\n : (headers as Record<string, string>)[name];\n const proto = getHeader(\"x-forwarded-proto\") || \"http\";\n const host = getHeader(\"host\") || \"localhost:3000\";\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\"http://localhost:3000\");\n }\n}\n"]}
@@ -156,7 +156,7 @@ export interface IntegrationsPluginOptions {
156
156
  systemPrompt?: string;
157
157
  /** Actions registry (same as agent-chat). */
158
158
  actions?: Record<string, import("../agent/production-agent.js").ActionEntry>;
159
- /** Model to use. Default: claude-sonnet-4-6 */
159
+ /** Model to use. Defaults to the resolved engine's default model. */
160
160
  model?: string;
161
161
  /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var. */
162
162
  apiKey?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/integrations/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE/D;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,kEAAkE;IAClE,QAAQ,EAAE,MAAM,CAAC;IACjB,uDAAuD;IACvD,gBAAgB,EAAE,MAAM,CAAC;IACzB,2BAA2B;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,+DAA+D;IAC/D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,kCAAkC;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,iEAAiE;IACjE,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzC,mCAAmC;IACnC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,mCAAmC;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC1C;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,+EAA+E;IAC/E,WAAW,EAAE,MAAM,CAAC;IACpB,wEAAwE;IACxE,SA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AC;IACvE;;;OAGG;IACH,aAAa,CAAC,EAAE,CACd,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,eAAe,KACrB,OAAO,CACR;QACE,OAAO,EAAE,IAAI,CAAC;QACd,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,GACD;QAAE,OAAO,EAAE,KAAK,CAAA;KAAE,CACrB,CAAC;CACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/integrations/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { EnvKeyConfig } from \"../server/create-server.js\";\n\n/**\n * Normalized incoming message from any messaging platform.\n */\nexport interface IncomingMessage {\n /** Platform identifier (e.g., \"slack\", \"telegram\", \"whatsapp\") */\n platform: string;\n /** Platform-specific thread/conversation identifier */\n externalThreadId: string;\n /** Message text content */\n text: string;\n /** Display name of the sender */\n senderName?: string;\n /** Verified sender email, when the platform can provide one */\n senderEmail?: string;\n /** Platform-specific sender ID */\n senderId?: string;\n /** Raw platform-specific context needed for routing responses */\n platformContext: Record<string, unknown>;\n /** Message timestamp (epoch ms) */\n timestamp: number;\n}\n\n/**\n * Outgoing message to send back to a messaging platform.\n */\nexport interface OutgoingMessage {\n /** Text content of the response */\n text: string;\n /** Platform-specific payload (e.g., Slack blocks, Telegram parse_mode) */\n platformContext: Record<string, unknown>;\n}\n\n/**\n * Proactive outbound message target for a platform.\n * Used when the agent needs to send to a saved destination instead of replying\n * to the current inbound thread.\n */\nexport interface OutboundTarget {\n /** Canonical platform-specific destination id (channel, chat, thread, etc.) */\n destination: string;\n /** Optional thread reference when the destination supports threading */\n threadRef?: string | null;\n /** Optional fallback display label */\n label?: string;\n}\n\n/**\n * Connection status for a platform integration.\n */\nexport interface IntegrationStatus {\n platform: string;\n /** Human-readable label (e.g., \"Slack\", \"Telegram\") */\n label: string;\n /** Whether the integration is explicitly enabled */\n enabled: boolean;\n /** Whether all required credentials are configured */\n configured: boolean;\n /** Platform-specific details (workspace name, bot username, etc.) */\n details?: Record<string, unknown>;\n /** Error message if something is wrong */\n error?: string;\n /** The webhook URL that should be configured in the platform */\n webhookUrl?: string;\n /** The full list of env keys (required + optional) the adapter recognizes,\n * including UI hints. Surfaced on the integrations status endpoint so the\n * frontend can render fields without hard-coding them per platform. */\n requiredEnvKeys?: import(\"../server/create-server.js\").EnvKeyConfig[];\n}\n\n/**\n * Platform adapter interface — implement this for each messaging platform.\n *\n * Each adapter handles the platform-specific concerns:\n * - Webhook verification (HMAC signatures, challenge responses)\n * - Message parsing (platform events → normalized IncomingMessage)\n * - Response formatting (agent text → platform-specific format)\n * - Response delivery (POST back to platform API)\n */\nexport interface PlatformAdapter {\n /** Unique platform identifier */\n readonly platform: string;\n /** Human-readable label */\n readonly label: string;\n\n /** Env keys this adapter needs (tokens, secrets, etc.) */\n getRequiredEnvKeys(): EnvKeyConfig[];\n\n /**\n * Handle platform-specific verification challenges.\n * For example, Slack sends a `url_verification` event when setting up.\n * Return `{ handled: true, response }` to short-circuit the webhook handler.\n */\n handleVerification(event: H3Event): Promise<{\n handled: boolean;\n response?: unknown;\n }>;\n\n /**\n * Validate the webhook request signature.\n * Returns true if the request is authentic.\n */\n verifyWebhook(event: H3Event): Promise<boolean>;\n\n /**\n * Parse the webhook payload into a normalized IncomingMessage.\n * Return null to silently ignore the event (bot messages, edits, etc.).\n */\n parseIncomingMessage(event: H3Event): Promise<IncomingMessage | null>;\n\n /**\n * Send the agent's response back to the messaging platform.\n *\n * If `opts.placeholderRef` is provided (returned earlier by\n * `postProcessingPlaceholder`), adapters that support in-place edits should\n * update that placeholder message rather than posting a new one. Adapters\n * without an \"update message\" API can ignore the ref and post fresh.\n */\n sendResponse(\n message: OutgoingMessage,\n context: IncomingMessage,\n opts?: { placeholderRef?: string },\n ): Promise<void>;\n\n /**\n * Optionally post a \"working on it…\" placeholder message immediately when a\n * webhook arrives, before the agent loop runs. Adapters that support\n * in-place message edits (Slack via `chat.update`, etc.) return an opaque\n * `placeholderRef` that the webhook flow threads through to `sendResponse`\n * so the same message is updated with the final answer once ready.\n *\n * Adapters without edit support should leave this undefined; the webhook\n * handler will skip the placeholder step entirely.\n */\n postProcessingPlaceholder?(\n incoming: IncomingMessage,\n ): Promise<{ placeholderRef: string } | null>;\n\n /**\n * Send a proactive outbound message to a platform destination. Adapters that\n * only support direct replies can omit this.\n */\n sendMessageToTarget?(\n message: OutgoingMessage,\n target: OutboundTarget,\n ): Promise<void>;\n\n /**\n * Format plain agent response text into a platform-appropriate message.\n * Handles markdown conversion, message splitting for length limits, etc.\n *\n * `opts.threadDeepLinkUrl`, when present, is a URL back to the originating\n * thread in the dispatch UI. Adapters that support rich blocks should\n * render this as a button (Slack); adapters that don't may inline it as a\n * link or simply omit it.\n */\n formatAgentResponse(\n text: string,\n opts?: { threadDeepLinkUrl?: string },\n ): OutgoingMessage;\n\n /** Return current connection/configuration status for the settings UI. */\n getStatus(baseUrl?: string): Promise<IntegrationStatus>;\n}\n\n/**\n * Options for the integrations plugin.\n */\nexport interface IntegrationsPluginOptions {\n /** App identifier used by call-agent to prevent self-calls (e.g. \"dispatch\"). */\n appId?: string;\n /** Platform adapters to enable. Default: all built-in adapters with configured env keys. */\n adapters?: PlatformAdapter[];\n /** System prompt for the agent (same as agent-chat). Inherited from agent-chat plugin if not set. */\n systemPrompt?: string;\n /** Actions registry (same as agent-chat). */\n actions?: Record<string, import(\"../agent/production-agent.js\").ActionEntry>;\n /** Model to use. Default: claude-sonnet-4-6 */\n model?: string;\n /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the same engine resolver as web chat. */\n engine?:\n | import(\"../agent/engine/types.js\").AgentEngine\n | string\n | {\n name: string;\n config: Record<string, unknown>;\n };\n /**\n * Resolve which owner should receive personal resource context and own the\n * created chat thread for an incoming platform message.\n */\n resolveOwner?: (incoming: IncomingMessage) => string | Promise<string>;\n /**\n * Optional preprocessor for inbound platform messages. Can intercept special\n * commands (such as `/link`) before the agent loop runs.\n */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/integrations/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { EnvKeyConfig } from \"../server/create-server.js\";\n\n/**\n * Normalized incoming message from any messaging platform.\n */\nexport interface IncomingMessage {\n /** Platform identifier (e.g., \"slack\", \"telegram\", \"whatsapp\") */\n platform: string;\n /** Platform-specific thread/conversation identifier */\n externalThreadId: string;\n /** Message text content */\n text: string;\n /** Display name of the sender */\n senderName?: string;\n /** Verified sender email, when the platform can provide one */\n senderEmail?: string;\n /** Platform-specific sender ID */\n senderId?: string;\n /** Raw platform-specific context needed for routing responses */\n platformContext: Record<string, unknown>;\n /** Message timestamp (epoch ms) */\n timestamp: number;\n}\n\n/**\n * Outgoing message to send back to a messaging platform.\n */\nexport interface OutgoingMessage {\n /** Text content of the response */\n text: string;\n /** Platform-specific payload (e.g., Slack blocks, Telegram parse_mode) */\n platformContext: Record<string, unknown>;\n}\n\n/**\n * Proactive outbound message target for a platform.\n * Used when the agent needs to send to a saved destination instead of replying\n * to the current inbound thread.\n */\nexport interface OutboundTarget {\n /** Canonical platform-specific destination id (channel, chat, thread, etc.) */\n destination: string;\n /** Optional thread reference when the destination supports threading */\n threadRef?: string | null;\n /** Optional fallback display label */\n label?: string;\n}\n\n/**\n * Connection status for a platform integration.\n */\nexport interface IntegrationStatus {\n platform: string;\n /** Human-readable label (e.g., \"Slack\", \"Telegram\") */\n label: string;\n /** Whether the integration is explicitly enabled */\n enabled: boolean;\n /** Whether all required credentials are configured */\n configured: boolean;\n /** Platform-specific details (workspace name, bot username, etc.) */\n details?: Record<string, unknown>;\n /** Error message if something is wrong */\n error?: string;\n /** The webhook URL that should be configured in the platform */\n webhookUrl?: string;\n /** The full list of env keys (required + optional) the adapter recognizes,\n * including UI hints. Surfaced on the integrations status endpoint so the\n * frontend can render fields without hard-coding them per platform. */\n requiredEnvKeys?: import(\"../server/create-server.js\").EnvKeyConfig[];\n}\n\n/**\n * Platform adapter interface — implement this for each messaging platform.\n *\n * Each adapter handles the platform-specific concerns:\n * - Webhook verification (HMAC signatures, challenge responses)\n * - Message parsing (platform events → normalized IncomingMessage)\n * - Response formatting (agent text → platform-specific format)\n * - Response delivery (POST back to platform API)\n */\nexport interface PlatformAdapter {\n /** Unique platform identifier */\n readonly platform: string;\n /** Human-readable label */\n readonly label: string;\n\n /** Env keys this adapter needs (tokens, secrets, etc.) */\n getRequiredEnvKeys(): EnvKeyConfig[];\n\n /**\n * Handle platform-specific verification challenges.\n * For example, Slack sends a `url_verification` event when setting up.\n * Return `{ handled: true, response }` to short-circuit the webhook handler.\n */\n handleVerification(event: H3Event): Promise<{\n handled: boolean;\n response?: unknown;\n }>;\n\n /**\n * Validate the webhook request signature.\n * Returns true if the request is authentic.\n */\n verifyWebhook(event: H3Event): Promise<boolean>;\n\n /**\n * Parse the webhook payload into a normalized IncomingMessage.\n * Return null to silently ignore the event (bot messages, edits, etc.).\n */\n parseIncomingMessage(event: H3Event): Promise<IncomingMessage | null>;\n\n /**\n * Send the agent's response back to the messaging platform.\n *\n * If `opts.placeholderRef` is provided (returned earlier by\n * `postProcessingPlaceholder`), adapters that support in-place edits should\n * update that placeholder message rather than posting a new one. Adapters\n * without an \"update message\" API can ignore the ref and post fresh.\n */\n sendResponse(\n message: OutgoingMessage,\n context: IncomingMessage,\n opts?: { placeholderRef?: string },\n ): Promise<void>;\n\n /**\n * Optionally post a \"working on it…\" placeholder message immediately when a\n * webhook arrives, before the agent loop runs. Adapters that support\n * in-place message edits (Slack via `chat.update`, etc.) return an opaque\n * `placeholderRef` that the webhook flow threads through to `sendResponse`\n * so the same message is updated with the final answer once ready.\n *\n * Adapters without edit support should leave this undefined; the webhook\n * handler will skip the placeholder step entirely.\n */\n postProcessingPlaceholder?(\n incoming: IncomingMessage,\n ): Promise<{ placeholderRef: string } | null>;\n\n /**\n * Send a proactive outbound message to a platform destination. Adapters that\n * only support direct replies can omit this.\n */\n sendMessageToTarget?(\n message: OutgoingMessage,\n target: OutboundTarget,\n ): Promise<void>;\n\n /**\n * Format plain agent response text into a platform-appropriate message.\n * Handles markdown conversion, message splitting for length limits, etc.\n *\n * `opts.threadDeepLinkUrl`, when present, is a URL back to the originating\n * thread in the dispatch UI. Adapters that support rich blocks should\n * render this as a button (Slack); adapters that don't may inline it as a\n * link or simply omit it.\n */\n formatAgentResponse(\n text: string,\n opts?: { threadDeepLinkUrl?: string },\n ): OutgoingMessage;\n\n /** Return current connection/configuration status for the settings UI. */\n getStatus(baseUrl?: string): Promise<IntegrationStatus>;\n}\n\n/**\n * Options for the integrations plugin.\n */\nexport interface IntegrationsPluginOptions {\n /** App identifier used by call-agent to prevent self-calls (e.g. \"dispatch\"). */\n appId?: string;\n /** Platform adapters to enable. Default: all built-in adapters with configured env keys. */\n adapters?: PlatformAdapter[];\n /** System prompt for the agent (same as agent-chat). Inherited from agent-chat plugin if not set. */\n systemPrompt?: string;\n /** Actions registry (same as agent-chat). */\n actions?: Record<string, import(\"../agent/production-agent.js\").ActionEntry>;\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** Anthropic API key. Falls back to ANTHROPIC_API_KEY env var. */\n apiKey?: string;\n /** Agent engine to use. Defaults to the same engine resolver as web chat. */\n engine?:\n | import(\"../agent/engine/types.js\").AgentEngine\n | string\n | {\n name: string;\n config: Record<string, unknown>;\n };\n /**\n * Resolve which owner should receive personal resource context and own the\n * created chat thread for an incoming platform message.\n */\n resolveOwner?: (incoming: IncomingMessage) => string | Promise<string>;\n /**\n * Optional preprocessor for inbound platform messages. Can intercept special\n * commands (such as `/link`) before the agent loop runs.\n */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n"]}
@@ -9,8 +9,8 @@ export interface WebhookHandlerOptions {
9
9
  systemPrompt: string;
10
10
  /** Action entries for the agent */
11
11
  actions: Record<string, ActionEntry>;
12
- /** Model to use */
13
- model: string;
12
+ /** Model to use. Defaults to the resolved engine's default model. */
13
+ model?: string;
14
14
  /** Anthropic API key */
15
15
  apiKey: string;
16
16
  /** Agent engine to use. Defaults to the same resolver as web chat. */
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-handler.d.ts","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAClC,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAGnE,OAAO,EAML,KAAK,WAAW,EACjB,MAAM,8BAA8B,CAAC;AAYtC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAU5D,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAC;AA+BlC,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,eAAe,CAAC;IACzB,oCAAoC;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,mCAAmC;IACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC,mBAAmB;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,wBAAwB;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,sEAAsE;IACtE,MAAM,CAAC,EACH,WAAW,GACX,MAAM,GACN;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IACtD,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,yEAAyE;IACzE,aAAa,CAAC,EAAE,CACd,QAAQ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,CAAC;IACf,sEAAsE;IACtE,MAAM,CAAC,EACH,WAAW,GACX,MAAM,GACN;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IACtD,wDAAwD;IACxD,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,yEAAyE;IACzE,aAAa,CAAC,EAAE,CACd,QAAQ,EAAE,eAAe,EACzB,OAAO,EAAE,eAAe,KACrB,OAAO,CACR;QACE,OAAO,EAAE,IAAI,CAAC;QACd,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,GACD;QAAE,OAAO,EAAE,KAAK,CAAA;KAAE,CACrB,CAAC;CACH;AAmDD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,aAAa,CACjC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC,CAsE5C;AAgHD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CA2BrD;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,WAAW,EACjB,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,IAAI,CAAC,CAWf"}
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-handler.js","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,EACd,gBAAgB,GAEjB,MAAM,8BAA8B,CAAC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,CAAC,KAAK,CACnB,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5B,IAAI,YAAY,EAAE,CAAC;YACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,gBAAgB,CACpB,QAAQ,EACR,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EACpB,IAAI,CAAC,KAAK,IAAI,MAAM,EAAE,KAAK,IAAI,kBAAkB,EACjD,IAAI,CAAC,OAAO,IAAI,MAAM,EAAE,OAAO,IAAI,EAAE,EACrC,IAAI,CAAC,QAAQ,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { PlatformAdapter, IncomingMessage } from \"./types.js\";\nimport { getThreadMapping, saveThreadMapping } from \"./thread-mapping-store.js\";\nimport { createThread, getThread } from \"../chat-threads/store.js\";\nimport {\n runAgentLoop,\n actionsToEngineTools,\n getOwnerActiveApiKey,\n getOwnerApiKey,\n engineToProvider,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { PROVIDER_TO_ENV } from \"../agent/engine/provider-env-vars.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport {\n getStoredModelForEngine,\n resolveEngine,\n} from \"../agent/engine/index.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { AgentEngine } from \"../agent/engine/types.js\";\nimport type { EngineMessage } from \"../agent/engine/types.js\";\nimport { startRun, type ActiveRun } from \"../agent/run-manager.js\";\nimport {\n buildAssistantMessage,\n extractThreadMeta,\n} from \"../agent/thread-data-builder.js\";\nimport { updateThreadData } from \"../chat-threads/store.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveOrgIdForEmail } from \"../org/context.js\";\nimport {\n insertPendingTask,\n isDuplicateEventError,\n type PendingTask,\n} from \"./pending-tasks-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"./a2a-continuation-marker.js\";\nimport { collectFinalResponseTextFromAgentEvents } from \"../a2a/response-text.js\";\nimport {\n appendA2AArtifactLinks,\n type A2AToolResultSummary,\n} from \"../a2a/artifact-response.js\";\nimport { buildRuntimeContextPrompt } from \"../agent/runtime-context.js\";\n\nconst PROCESSOR_DISPATCH_SETTLE_WAIT_MS = 1_500;\n\ntype ToolDoneEvent = { type: \"tool_done\"; tool: string; result: string };\n\n/**\n * Build a stable per-event dedup key from the incoming message. The same\n * key is computed for every retry of the same event from the platform —\n * Slack/Telegram retry on timeout (3s for Slack), so we MUST treat the\n * second delivery as a duplicate and return 200 silently.\n *\n * The `(platform, external_event_key)` UNIQUE index in\n * `integration_pending_tasks` enforces this at the SQL layer, replacing\n * the previous in-memory Map (H3 in the webhook security audit) which\n * couldn't survive serverless cold starts.\n */\nfunction buildEventDedupKey(incoming: IncomingMessage): string {\n return `${incoming.platform}:${incoming.externalThreadId}:${incoming.timestamp}`;\n}\n\nexport interface WebhookHandlerOptions {\n adapter: PlatformAdapter;\n /** Resolved system prompt string */\n systemPrompt: string;\n /** Action entries for the agent */\n actions: Record<string, ActionEntry>;\n /** Model to use */\n model: string;\n /** Anthropic API key */\n apiKey: string;\n /** Agent engine to use. Defaults to the same resolver as web chat. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Thread owner for personal/shared resource loading */\n ownerEmail: string;\n /**\n * Pre-parsed incoming message. When provided, handleWebhook skips its own\n * verification + parsing steps. Required when the caller has already read\n * the request body (h3 doesn't reliably cache parsed bodies, so re-parsing\n * the same event hangs on streaming providers).\n */\n incoming?: IncomingMessage;\n /** Optional hook to intercept inbound commands before agent execution */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nfunction explicitEngineName(\n engineOption: WebhookHandlerOptions[\"engine\"],\n): string | undefined {\n if (!engineOption) return undefined;\n if (typeof engineOption === \"string\") return engineOption;\n if (\n typeof engineOption === \"object\" &&\n !(\"stream\" in engineOption) &&\n typeof engineOption.name === \"string\"\n ) {\n return engineOption.name;\n }\n return undefined;\n}\n\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\nfunction collectToolResultSummaries(\n completedRun: ActiveRun,\n): A2AToolResultSummary[] {\n return completedRun.events\n .map((runEvent) => runEvent.event)\n .filter((event): event is ToolDoneEvent => event.type === \"tool_done\")\n .map((event) => ({ tool: event.tool, result: event.result }));\n}\n\nasync function resolveIntegrationApiKey(\n engineOption: WebhookHandlerOptions[\"engine\"],\n ownerEmail: string,\n fallbackApiKey: string,\n): Promise<string | undefined> {\n const engineName = explicitEngineName(engineOption);\n if (engineName) {\n const provider = engineToProvider(engineName);\n const userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n const envVar = PROVIDER_TO_ENV[provider];\n const providerEnvKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n return providerEnvKey || fallbackApiKey.trim() || undefined;\n }\n\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n return fallbackApiKey.trim() || undefined;\n}\n\n/**\n * Process an incoming webhook from a messaging platform.\n *\n * Flow:\n * 1. Handle verification challenges (Slack url_verification, etc.)\n * 2. Verify webhook signature\n * 3. Parse incoming message (null = ignored event)\n * 4. Persist task to SQL\n * 5. Fire-and-forget POST to /_agent-native/integrations/process-task\n * (a fresh function execution with its own timeout budget)\n * 6. Return HTTP 200 immediately (within Slack's 3s SLA)\n *\n * The processor endpoint runs the actual agent loop. This split is essential\n * for serverless platforms (Netlify Lambda, Vercel, Cloudflare Workers) which\n * freeze the function as soon as the response is returned, killing any\n * lingering background promises.\n */\nexport async function handleWebhook(\n event: H3Event,\n options: WebhookHandlerOptions,\n): Promise<{ status: number; body: unknown }> {\n const { adapter, beforeProcess } = options;\n\n let incoming: IncomingMessage | null = options.incoming ?? null;\n\n // When the caller didn't pre-parse, run the full verify + parse pipeline.\n // Otherwise skip it — h3's body stream has already been consumed and a\n // second readBody call hangs on streaming providers.\n if (!incoming) {\n // Step 1: Handle platform-specific verification challenges\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return { status: 200, body: verification.response ?? \"ok\" };\n }\n\n // Step 2: Verify webhook signature\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n return { status: 401, body: { error: \"Invalid webhook signature\" } };\n }\n\n // Step 3: Parse the incoming message\n incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n // Not a user message (bot message, edit, reaction, etc.) — acknowledge silently\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Dedup is enforced inside enqueueAndDispatch — the unique index on\n // `(platform, external_event_key)` raises a constraint violation we treat\n // as \"already enqueued\" and respond 200. We can't dedup BEFORE the\n // beforeProcess hook because some templates use beforeProcess for\n // command-style intercepts that are stateless and idempotent (e.g. a\n // Slack `/help` command that doesn't enqueue a task).\n\n if (beforeProcess) {\n const result = await beforeProcess(incoming, adapter);\n if (result.handled) {\n if (result.responseText?.trim()) {\n const outgoing = adapter.formatAgentResponse(result.responseText);\n await adapter.sendResponse(outgoing, incoming);\n }\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Step 4 + 5: Enqueue to SQL and dispatch to processor in a fresh request.\n try {\n await enqueueAndDispatch(event, incoming, options);\n } catch (err) {\n // Duplicate event delivery: the SQL UNIQUE constraint on\n // (platform, external_event_key) rejected the second insert. This is\n // the expected path when a platform retries an event that already\n // landed (e.g. Slack 3-second timeout) — return 200 so the platform\n // stops retrying. See H3 in the webhook security audit.\n if (isDuplicateEventError(err)) {\n return { status: 200, body: \"ok\" };\n }\n console.error(\n `[integrations] Failed to enqueue/dispatch ${incoming.platform} message:`,\n err,\n );\n // Return 500 so the platform retries. If the SQL insert failed for a\n // non-dup reason, the message is genuinely lost — better to let Slack\n // retry (it will re-fire the same event_callback) than silently drop it.\n return { status: 500, body: { error: \"enqueue failed\" } };\n }\n\n return { status: 200, body: \"ok\" };\n}\n\n/**\n * Persist the task to SQL and dispatch a fresh HTTP request to the processor\n * endpoint. The dispatch is fire-and-forget — we deliberately do NOT await\n * the resulting fetch, so the current handler can return immediately.\n *\n * This pattern works on every supported host:\n * - Netlify Lambda: function returns; the dispatched request hits a fresh\n * Lambda with its own function budget.\n * - Vercel Functions: same.\n * - Cloudflare Workers: same (no waitUntil dependency).\n * - Self-hosted Node: a separate request comes back through the same\n * server, but each handler still runs to completion.\n */\nasync function enqueueAndDispatch(\n event: H3Event,\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Resolve the org id once at enqueue-time so the processor doesn't have to\n // re-derive it (and so we can drop it on the row for observability).\n let orgId: string | null = null;\n try {\n orgId = (await resolveOrgIdForEmail(options.ownerEmail)) ?? null;\n } catch {\n orgId = null;\n }\n\n // Post a \"thinking…\" placeholder immediately if the adapter supports\n // in-place edits. The processor flow will update this same message with\n // the final answer, so users see one tidy thread reply instead of\n // \"[silence] → answer\". Adapters without edit support skip this and the\n // processor posts a fresh response.\n let placeholderRef: string | undefined;\n try {\n if (options.adapter.postProcessingPlaceholder) {\n const placeholder =\n await options.adapter.postProcessingPlaceholder(incoming);\n if (placeholder?.placeholderRef) {\n placeholderRef = placeholder.placeholderRef;\n }\n }\n } catch (err) {\n console.error(\"[integrations] postProcessingPlaceholder failed:\", err);\n }\n\n const payload = JSON.stringify({ incoming, placeholderRef });\n\n await insertPendingTask({\n id: taskId,\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n payload,\n ownerEmail: options.ownerEmail,\n orgId,\n // SQL-level dedup key — duplicate webhook deliveries from the same\n // platform produce the same key, so the unique index rejects the\n // second insert (H3 in the webhook security audit).\n externalEventKey: buildEventDedupKey(incoming),\n });\n\n const baseUrl = resolveBaseUrl(event);\n const processUrl = `${baseUrl}${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\n // Sign the dispatch with an HMAC token so the processor endpoint can\n // verify the request came from us and not the public internet. The\n // processor refuses unsigned requests in production (C3 in the webhook\n // security audit). In dev, dispatching unsigned is allowed and falls\n // through to the SQL atomic claim for double-processing protection.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n // Distinguish \"secret not configured\" (the documented dev path) from\n // a real signing failure — silently swallowing both made malformed\n // secrets fail invisibly (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Fire-and-forget: do NOT await the full response (the processor's run\n // takes minutes — we don't want to block the caller). BUT on Netlify\n // Lambda, when we return immediately, the runtime can freeze the function\n // before the outbound TCP handshake even starts, which leaves the dispatch\n // request stuck waiting for the 60s retry-sweep job. Race the fetch\n // against a short timer so the request gets a reasonable chance to leave\n // the box; the trade-off is at most a couple seconds of added webhook\n // latency, still inside Slack's timeout window.\n const dispatchPromise = fetch(processUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n }).catch((err) => {\n console.error(\"[integrations] Failed to dispatch processor request:\", err);\n });\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) =>\n setTimeout(resolve, PROCESSOR_DISPATCH_SETTLE_WAIT_MS),\n ),\n ]);\n}\n\n/**\n * Resolve the base URL we should dispatch the processor request to.\n * Prefers explicit env vars (most reliable on serverless), falls back to the\n * inbound request's headers.\n */\nexport function resolveBaseUrl(event: H3Event): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(fromEnv);\n\n try {\n const headers = (event as any).node?.req?.headers ?? (event as any).headers;\n const get = (name: string): string | undefined => {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const lower = String(name).toLowerCase();\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[lower];\n };\n const proto = get(\"x-forwarded-proto\") || \"http\";\n const host = get(\"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\n `http://localhost:${process.env.PORT || 3000}`,\n );\n }\n}\n\n/**\n * Run the actual agent loop for a previously-enqueued task. Called by the\n * processor endpoint in `plugin.ts`. This is a fresh function execution, so\n * it gets its own timeout budget independent of the inbound webhook handler.\n */\nexport async function processIntegrationTask(\n task: PendingTask,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const parsed = JSON.parse(task.payload) as {\n incoming: IncomingMessage;\n placeholderRef?: string;\n };\n\n await processIncomingMessage(parsed.incoming, options, {\n taskId: task.id,\n attempts: task.attempts,\n placeholderRef: parsed.placeholderRef,\n });\n}\n\n/**\n * Resolve thread, run agent loop, post response, persist thread data.\n * Shared between the new processor endpoint and any direct callers.\n */\nasync function processIncomingMessage(\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n opts: { taskId?: string; attempts?: number; placeholderRef?: string } = {},\n): Promise<void> {\n const {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey,\n ownerEmail,\n engine: engineOption,\n } = options;\n const effectiveSystemPrompt = systemPrompt + buildRuntimeContextPrompt();\n\n // Resolve or create internal thread\n let mapping = await getThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n );\n\n if (!mapping) {\n const thread = await createThread(ownerEmail, {\n title: `${adapter.label}: ${incoming.senderName || incoming.senderId || \"User\"}`,\n });\n await saveThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n thread.id,\n incoming.platformContext,\n );\n mapping = {\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n internalThreadId: thread.id,\n platformContext: incoming.platformContext,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n }\n\n const threadId = mapping.internalThreadId;\n\n // Load existing thread history for context\n const thread = await getThread(threadId);\n const existingMessages: EngineMessage[] = [];\n if (thread?.threadData) {\n try {\n const data = JSON.parse(thread.threadData);\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n const m = msg.message ?? msg;\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\")\n : \"\";\n if (m.role === \"user\") {\n existingMessages.push({\n role: \"user\",\n content: [{ type: \"text\", text: textContent }],\n });\n } else if (m.role === \"assistant\") {\n existingMessages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: textContent }],\n });\n }\n }\n }\n } catch {}\n }\n\n // Add the new user message. Include verified platform identity as lightweight\n // context so app-specific agents can attribute requests without guessing.\n const identityLines = [\n `Platform: ${incoming.platform}`,\n incoming.senderName ? `Sender name: ${incoming.senderName}` : null,\n incoming.senderEmail ? `Sender email: ${incoming.senderEmail}` : null,\n incoming.senderId ? `Sender ID: ${incoming.senderId}` : null,\n ].filter(Boolean);\n const userText =\n identityLines.length > 1\n ? `<integration-context>\\n${identityLines.join(\"\\n\")}\\n</integration-context>\\n\\n${incoming.text}`\n : incoming.text;\n\n const messages: EngineMessage[] = [\n ...existingMessages,\n { role: \"user\", content: [{ type: \"text\", text: userText }] },\n ];\n\n // Run agent loop via startRun, wrapped in a request context so that\n // tools (especially call-agent) can resolve the caller's org for org-scoped\n // A2A delegation. Without this, getRequestOrgId() returns undefined and\n // call-agent can't look up the org's a2a_secret or org_domain.\n const orgId = await resolveOrgIdForEmail(ownerEmail);\n const tools = actionsToEngineTools(actions);\n\n const runId = `integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Wait for the run to complete inside this fresh function execution.\n // We use a Promise so the processor endpoint can await the full lifecycle.\n await new Promise<void>((resolve) => {\n startRun(\n runId,\n threadId,\n async (send, signal) => {\n await runWithRequestContext(\n {\n userEmail: ownerEmail,\n orgId: orgId ?? undefined,\n // Lets downstream callers (call-agent script) apply tighter\n // budgets on integration paths without affecting normal\n // agent-chat. See `isIntegrationCallerRequest()`.\n isIntegrationCaller: true,\n integration: opts.taskId\n ? {\n taskId: opts.taskId,\n attempts: opts.attempts,\n incoming,\n placeholderRef: opts.placeholderRef,\n }\n : undefined,\n },\n async () => {\n const effectiveApiKey = await resolveIntegrationApiKey(\n engineOption,\n ownerEmail,\n apiKey,\n );\n const engine = await resolveEngine({\n engineOption,\n apiKey: effectiveApiKey,\n model,\n });\n const resolvedModel =\n (await getStoredModelForEngine(engine)) ??\n model ??\n engine.defaultModel;\n\n return runAgentLoop({\n engine,\n model: resolvedModel,\n systemPrompt: effectiveSystemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n });\n },\n );\n },\n async (completedRun: ActiveRun) => {\n try {\n const queuedA2AContinuation = hasQueuedA2AContinuation(completedRun);\n let responseText = collectFinalResponseTextFromAgentEvents(\n completedRun.events.map((runEvent) => runEvent.event),\n { fallbackToPreToolText: !queuedA2AContinuation },\n );\n if (!queuedA2AContinuation && !responseText.trim()) {\n const recoverableA2AArtifactText =\n extractRecoverableA2AArtifactToolResult(completedRun);\n if (recoverableA2AArtifactText) {\n responseText = recoverableA2AArtifactText;\n }\n }\n\n const suppressPlatformReply =\n queuedA2AContinuation &&\n isQueuedA2AContinuationDeferral(responseText);\n\n // If the run errored OR produced no text, post a graceful fallback so\n // the user isn't left wondering whether the bot saw their message.\n // Common case: an A2A delegation timed out and the agent loop bailed\n // before generating any user-facing text.\n const runErrored = completedRun.status === \"errored\";\n const runErrorText = completedRun.events\n .map((runEvent) =>\n runEvent.event.type === \"error\" ? runEvent.event.error : \"\",\n )\n .filter(Boolean)\n .join(\"\\n\");\n if (\n isLlmCredentialError(responseText) ||\n isLlmCredentialError(runErrorText)\n ) {\n responseText = formatLlmCredentialErrorMessage();\n } else if (\n !suppressPlatformReply &&\n (!responseText.trim() || runErrored)\n ) {\n if (runErrored) {\n responseText =\n (responseText.trim() ? responseText + \"\\n\\n\" : \"\") +\n \"I ran into a problem before I could finish that one. \" +\n \"If it was a complex analytics question, opening the analytics app \" +\n \"directly is the most reliable way to get an answer right now.\";\n } else {\n responseText = \"(No response)\";\n }\n }\n\n // Compute the deep-link to the dispatch UI for this thread, then\n // hand it to the adapter as a structured `threadDeepLinkUrl` so\n // platforms with rich blocks (Slack) can render a button instead\n // of inlining a `<url|text>` link that auto-unfurls into a giant\n // preview card.\n const baseUrl = process.env.APP_URL || process.env.URL || \"\";\n const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : \"\";\n if (!suppressPlatformReply) {\n responseText = appendA2AArtifactLinks(\n responseText,\n collectToolResultSummaries(completedRun),\n { baseUrl: appBaseUrl || undefined },\n );\n }\n const threadDeepLinkUrl =\n appBaseUrl && threadId\n ? `${appBaseUrl}/?thread=${threadId}`\n : undefined;\n\n // Format and send back to platform — update the \"thinking…\"\n // placeholder in place if the adapter supplied one.\n if (!suppressPlatformReply) {\n const outgoing = adapter.formatAgentResponse(responseText, {\n threadDeepLinkUrl,\n });\n await adapter.sendResponse(outgoing, incoming, {\n placeholderRef: opts.placeholderRef,\n });\n }\n\n // Persist thread data\n await persistThreadData(\n threadId,\n incoming.text,\n completedRun,\n thread,\n );\n } catch (err) {\n console.error(\n `[integrations] Error sending response to ${incoming.platform}:`,\n err,\n );\n // Last-ditch: try to post a brief apology so the thread isn't silent.\n try {\n const fallback = adapter.formatAgentResponse(\n \"Something went wrong on my end while replying. Please try again.\",\n );\n await adapter.sendResponse(fallback, incoming);\n } catch {}\n } finally {\n resolve();\n }\n },\n );\n });\n}\n\nfunction hasQueuedA2AContinuation(completedRun: ActiveRun): boolean {\n return completedRun.events.some((runEvent) => {\n const event = runEvent.event;\n return (\n event.type === \"tool_done\" &&\n event.tool === \"call-agent\" &&\n String(event.result ?? \"\").includes(A2A_CONTINUATION_QUEUED_MARKER)\n );\n });\n}\n\nfunction extractRecoverableA2AArtifactToolResult(\n completedRun: ActiveRun,\n): string | null {\n for (let i = completedRun.events.length - 1; i >= 0; i--) {\n const event = completedRun.events[i].event;\n if (event.type !== \"tool_done\" || event.tool !== \"call-agent\") continue;\n\n const result = String(event.result ?? \"\").trim();\n if (\n result.includes(\"verified artifacts already exist\") &&\n result.includes(\"\\nArtifacts:\\n\")\n ) {\n return result;\n }\n }\n return null;\n}\n\nfunction isQueuedA2AContinuationDeferral(text: string): boolean {\n const normalized = text.replace(/\\s+/g, \" \").trim();\n if (!normalized) return true;\n if (hasSubstantiveA2APartialAnswer(text)) return false;\n if (normalized.includes(A2A_CONTINUATION_QUEUED_MARKER)) return true;\n return /\\b(?:still (?:working|processing)|is working on|taking longer than expected|will (?:post|update|surface|show up)|(?:it'?ll|it will|the result will|the final result will) (?:post|be posted|update|be updated|surface|show up)|will be (?:posted|updated|sent|shared)|final result when it finishes|while you wait|as soon as (?:it|it'?s|it is|the result|the artifact) (?:comes back|is ready|ready)|hang tight|relay from the .* agent)\\b/i.test(\n normalized,\n );\n}\n\nfunction hasSubstantiveA2APartialAnswer(text: string): boolean {\n const withoutMarker = text\n .replaceAll(A2A_CONTINUATION_QUEUED_MARKER, \"\")\n .trim();\n if (!withoutMarker) return false;\n if (/https?:\\/\\//i.test(withoutMarker)) return true;\n if (/\\|\\s*[-:]+\\s*\\|/.test(withoutMarker)) return true;\n if (\n /\\b(?:page\\s*views?|unique\\s+visitors?|dashboard|artifact id|document id|deck id|source|query|bigquery|created successfully)\\b/i.test(\n withoutMarker,\n )\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Persist the user message and agent response to the thread data,\n * so the conversation history is available in the web UI too.\n */\nasync function persistThreadData(\n threadId: string,\n userText: string,\n completedRun: ActiveRun,\n thread: any,\n): Promise<void> {\n try {\n let repo: any;\n try {\n repo = JSON.parse(thread?.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n // Add user message\n const userMsg = {\n id: `msg-${Date.now()}-user`,\n role: \"user\",\n content: [{ type: \"text\", text: userText }],\n createdAt: new Date().toISOString(),\n };\n\n // Build assistant message from run events\n const assistantMsg = buildAssistantMessage(\n completedRun.events ?? [],\n completedRun.runId,\n );\n\n repo.messages.push(userMsg);\n if (assistantMsg) {\n repo.messages.push(assistantMsg);\n }\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread?.title || \"Integration Chat\",\n meta.preview || thread?.preview || \"\",\n repo.messages.length,\n );\n } catch {\n // Best-effort persistence\n }\n}\n"]}
1
+ {"version":3,"file":"webhook-handler.js","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,EACd,gBAAgB,GAEjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,sCAAsC,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EACL,uBAAuB,EAC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,CAAC;QAED,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,gBAAgB,CACpB,QAAQ,EACR,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EACpB,IAAI,CAAC,KAAK,IAAI,MAAM,EAAE,KAAK,IAAI,kBAAkB,EACjD,IAAI,CAAC,OAAO,IAAI,MAAM,EAAE,OAAO,IAAI,EAAE,EACrC,IAAI,CAAC,QAAQ,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { PlatformAdapter, IncomingMessage } from \"./types.js\";\nimport { getThreadMapping, saveThreadMapping } from \"./thread-mapping-store.js\";\nimport { createThread, getThread } from \"../chat-threads/store.js\";\nimport {\n runAgentLoop,\n actionsToEngineTools,\n getOwnerActiveApiKey,\n getOwnerApiKey,\n engineToProvider,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { PROVIDER_TO_ENV } from \"../agent/engine/provider-env-vars.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport {\n getStoredModelForEngine,\n resolveEngine,\n} from \"../agent/engine/index.js\";\nimport {\n formatLlmCredentialErrorMessage,\n isLlmCredentialError,\n} from \"../agent/engine/credential-errors.js\";\nimport type { AgentEngine } from \"../agent/engine/types.js\";\nimport type { EngineMessage } from \"../agent/engine/types.js\";\nimport { startRun, type ActiveRun } from \"../agent/run-manager.js\";\nimport {\n buildAssistantMessage,\n extractThreadMeta,\n} from \"../agent/thread-data-builder.js\";\nimport { updateThreadData } from \"../chat-threads/store.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveOrgIdForEmail } from \"../org/context.js\";\nimport {\n insertPendingTask,\n isDuplicateEventError,\n type PendingTask,\n} from \"./pending-tasks-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\nimport { A2A_CONTINUATION_QUEUED_MARKER } from \"./a2a-continuation-marker.js\";\nimport { collectFinalResponseTextFromAgentEvents } from \"../a2a/response-text.js\";\nimport {\n appendA2AArtifactLinks,\n type A2AToolResultSummary,\n} from \"../a2a/artifact-response.js\";\nimport { buildRuntimeContextPrompt } from \"../agent/runtime-context.js\";\n\nconst PROCESSOR_DISPATCH_SETTLE_WAIT_MS = 1_500;\n\ntype ToolDoneEvent = { type: \"tool_done\"; tool: string; result: string };\n\n/**\n * Build a stable per-event dedup key from the incoming message. The same\n * key is computed for every retry of the same event from the platform —\n * Slack/Telegram retry on timeout (3s for Slack), so we MUST treat the\n * second delivery as a duplicate and return 200 silently.\n *\n * The `(platform, external_event_key)` UNIQUE index in\n * `integration_pending_tasks` enforces this at the SQL layer, replacing\n * the previous in-memory Map (H3 in the webhook security audit) which\n * couldn't survive serverless cold starts.\n */\nfunction buildEventDedupKey(incoming: IncomingMessage): string {\n return `${incoming.platform}:${incoming.externalThreadId}:${incoming.timestamp}`;\n}\n\nexport interface WebhookHandlerOptions {\n adapter: PlatformAdapter;\n /** Resolved system prompt string */\n systemPrompt: string;\n /** Action entries for the agent */\n actions: Record<string, ActionEntry>;\n /** Model to use. Defaults to the resolved engine's default model. */\n model?: string;\n /** Anthropic API key */\n apiKey: string;\n /** Agent engine to use. Defaults to the same resolver as web chat. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Thread owner for personal/shared resource loading */\n ownerEmail: string;\n /**\n * Pre-parsed incoming message. When provided, handleWebhook skips its own\n * verification + parsing steps. Required when the caller has already read\n * the request body (h3 doesn't reliably cache parsed bodies, so re-parsing\n * the same event hangs on streaming providers).\n */\n incoming?: IncomingMessage;\n /** Optional hook to intercept inbound commands before agent execution */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nfunction explicitEngineName(\n engineOption: WebhookHandlerOptions[\"engine\"],\n): string | undefined {\n if (!engineOption) return undefined;\n if (typeof engineOption === \"string\") return engineOption;\n if (\n typeof engineOption === \"object\" &&\n !(\"stream\" in engineOption) &&\n typeof engineOption.name === \"string\"\n ) {\n return engineOption.name;\n }\n return undefined;\n}\n\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\nfunction collectToolResultSummaries(\n completedRun: ActiveRun,\n): A2AToolResultSummary[] {\n return completedRun.events\n .map((runEvent) => runEvent.event)\n .filter((event): event is ToolDoneEvent => event.type === \"tool_done\")\n .map((event) => ({ tool: event.tool, result: event.result }));\n}\n\nasync function resolveIntegrationApiKey(\n engineOption: WebhookHandlerOptions[\"engine\"],\n ownerEmail: string,\n fallbackApiKey: string,\n): Promise<string | undefined> {\n const engineName = explicitEngineName(engineOption);\n if (engineName) {\n const provider = engineToProvider(engineName);\n const userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n const envVar = PROVIDER_TO_ENV[provider];\n const providerEnvKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n return providerEnvKey || fallbackApiKey.trim() || undefined;\n }\n\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n return fallbackApiKey.trim() || undefined;\n}\n\n/**\n * Process an incoming webhook from a messaging platform.\n *\n * Flow:\n * 1. Handle verification challenges (Slack url_verification, etc.)\n * 2. Verify webhook signature\n * 3. Parse incoming message (null = ignored event)\n * 4. Persist task to SQL\n * 5. Fire-and-forget POST to /_agent-native/integrations/process-task\n * (a fresh function execution with its own timeout budget)\n * 6. Return HTTP 200 immediately (within Slack's 3s SLA)\n *\n * The processor endpoint runs the actual agent loop. This split is essential\n * for serverless platforms (Netlify Lambda, Vercel, Cloudflare Workers) which\n * freeze the function as soon as the response is returned, killing any\n * lingering background promises.\n */\nexport async function handleWebhook(\n event: H3Event,\n options: WebhookHandlerOptions,\n): Promise<{ status: number; body: unknown }> {\n const { adapter, beforeProcess } = options;\n\n let incoming: IncomingMessage | null = options.incoming ?? null;\n\n // When the caller didn't pre-parse, run the full verify + parse pipeline.\n // Otherwise skip it — h3's body stream has already been consumed and a\n // second readBody call hangs on streaming providers.\n if (!incoming) {\n // Step 1: Handle platform-specific verification challenges\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return { status: 200, body: verification.response ?? \"ok\" };\n }\n\n // Step 2: Verify webhook signature\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n return { status: 401, body: { error: \"Invalid webhook signature\" } };\n }\n\n // Step 3: Parse the incoming message\n incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n // Not a user message (bot message, edit, reaction, etc.) — acknowledge silently\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Dedup is enforced inside enqueueAndDispatch — the unique index on\n // `(platform, external_event_key)` raises a constraint violation we treat\n // as \"already enqueued\" and respond 200. We can't dedup BEFORE the\n // beforeProcess hook because some templates use beforeProcess for\n // command-style intercepts that are stateless and idempotent (e.g. a\n // Slack `/help` command that doesn't enqueue a task).\n\n if (beforeProcess) {\n const result = await beforeProcess(incoming, adapter);\n if (result.handled) {\n if (result.responseText?.trim()) {\n const outgoing = adapter.formatAgentResponse(result.responseText);\n await adapter.sendResponse(outgoing, incoming);\n }\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Step 4 + 5: Enqueue to SQL and dispatch to processor in a fresh request.\n try {\n await enqueueAndDispatch(event, incoming, options);\n } catch (err) {\n // Duplicate event delivery: the SQL UNIQUE constraint on\n // (platform, external_event_key) rejected the second insert. This is\n // the expected path when a platform retries an event that already\n // landed (e.g. Slack 3-second timeout) — return 200 so the platform\n // stops retrying. See H3 in the webhook security audit.\n if (isDuplicateEventError(err)) {\n return { status: 200, body: \"ok\" };\n }\n console.error(\n `[integrations] Failed to enqueue/dispatch ${incoming.platform} message:`,\n err,\n );\n // Return 500 so the platform retries. If the SQL insert failed for a\n // non-dup reason, the message is genuinely lost — better to let Slack\n // retry (it will re-fire the same event_callback) than silently drop it.\n return { status: 500, body: { error: \"enqueue failed\" } };\n }\n\n return { status: 200, body: \"ok\" };\n}\n\n/**\n * Persist the task to SQL and dispatch a fresh HTTP request to the processor\n * endpoint. The dispatch is fire-and-forget — we deliberately do NOT await\n * the resulting fetch, so the current handler can return immediately.\n *\n * This pattern works on every supported host:\n * - Netlify Lambda: function returns; the dispatched request hits a fresh\n * Lambda with its own function budget.\n * - Vercel Functions: same.\n * - Cloudflare Workers: same (no waitUntil dependency).\n * - Self-hosted Node: a separate request comes back through the same\n * server, but each handler still runs to completion.\n */\nasync function enqueueAndDispatch(\n event: H3Event,\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Resolve the org id once at enqueue-time so the processor doesn't have to\n // re-derive it (and so we can drop it on the row for observability).\n let orgId: string | null = null;\n try {\n orgId = (await resolveOrgIdForEmail(options.ownerEmail)) ?? null;\n } catch {\n orgId = null;\n }\n\n // Post a \"thinking…\" placeholder immediately if the adapter supports\n // in-place edits. The processor flow will update this same message with\n // the final answer, so users see one tidy thread reply instead of\n // \"[silence] → answer\". Adapters without edit support skip this and the\n // processor posts a fresh response.\n let placeholderRef: string | undefined;\n try {\n if (options.adapter.postProcessingPlaceholder) {\n const placeholder =\n await options.adapter.postProcessingPlaceholder(incoming);\n if (placeholder?.placeholderRef) {\n placeholderRef = placeholder.placeholderRef;\n }\n }\n } catch (err) {\n console.error(\"[integrations] postProcessingPlaceholder failed:\", err);\n }\n\n const payload = JSON.stringify({ incoming, placeholderRef });\n\n await insertPendingTask({\n id: taskId,\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n payload,\n ownerEmail: options.ownerEmail,\n orgId,\n // SQL-level dedup key — duplicate webhook deliveries from the same\n // platform produce the same key, so the unique index rejects the\n // second insert (H3 in the webhook security audit).\n externalEventKey: buildEventDedupKey(incoming),\n });\n\n const baseUrl = resolveBaseUrl(event);\n const processUrl = `${baseUrl}${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\n // Sign the dispatch with an HMAC token so the processor endpoint can\n // verify the request came from us and not the public internet. The\n // processor refuses unsigned requests in production (C3 in the webhook\n // security audit). In dev, dispatching unsigned is allowed and falls\n // through to the SQL atomic claim for double-processing protection.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n // Distinguish \"secret not configured\" (the documented dev path) from\n // a real signing failure — silently swallowing both made malformed\n // secrets fail invisibly (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Fire-and-forget: do NOT await the full response (the processor's run\n // takes minutes — we don't want to block the caller). BUT on Netlify\n // Lambda, when we return immediately, the runtime can freeze the function\n // before the outbound TCP handshake even starts, which leaves the dispatch\n // request stuck waiting for the 60s retry-sweep job. Race the fetch\n // against a short timer so the request gets a reasonable chance to leave\n // the box; the trade-off is at most a couple seconds of added webhook\n // latency, still inside Slack's timeout window.\n const dispatchPromise = fetch(processUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n }).catch((err) => {\n console.error(\"[integrations] Failed to dispatch processor request:\", err);\n });\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) =>\n setTimeout(resolve, PROCESSOR_DISPATCH_SETTLE_WAIT_MS),\n ),\n ]);\n}\n\n/**\n * Resolve the base URL we should dispatch the processor request to.\n * Prefers explicit env vars (most reliable on serverless), falls back to the\n * inbound request's headers.\n */\nexport function resolveBaseUrl(event: H3Event): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(fromEnv);\n\n try {\n const headers = (event as any).node?.req?.headers ?? (event as any).headers;\n const get = (name: string): string | undefined => {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const lower = String(name).toLowerCase();\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[lower];\n };\n const proto = get(\"x-forwarded-proto\") || \"http\";\n const host = get(\"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\n `http://localhost:${process.env.PORT || 3000}`,\n );\n }\n}\n\n/**\n * Run the actual agent loop for a previously-enqueued task. Called by the\n * processor endpoint in `plugin.ts`. This is a fresh function execution, so\n * it gets its own timeout budget independent of the inbound webhook handler.\n */\nexport async function processIntegrationTask(\n task: PendingTask,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const parsed = JSON.parse(task.payload) as {\n incoming: IncomingMessage;\n placeholderRef?: string;\n };\n\n await processIncomingMessage(parsed.incoming, options, {\n taskId: task.id,\n attempts: task.attempts,\n placeholderRef: parsed.placeholderRef,\n });\n}\n\n/**\n * Resolve thread, run agent loop, post response, persist thread data.\n * Shared between the new processor endpoint and any direct callers.\n */\nasync function processIncomingMessage(\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n opts: { taskId?: string; attempts?: number; placeholderRef?: string } = {},\n): Promise<void> {\n const {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey,\n ownerEmail,\n engine: engineOption,\n } = options;\n const effectiveSystemPrompt = systemPrompt + buildRuntimeContextPrompt();\n\n // Resolve or create internal thread\n let mapping = await getThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n );\n\n if (!mapping) {\n const thread = await createThread(ownerEmail, {\n title: `${adapter.label}: ${incoming.senderName || incoming.senderId || \"User\"}`,\n });\n await saveThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n thread.id,\n incoming.platformContext,\n );\n mapping = {\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n internalThreadId: thread.id,\n platformContext: incoming.platformContext,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n }\n\n const threadId = mapping.internalThreadId;\n\n // Load existing thread history for context\n const thread = await getThread(threadId);\n const existingMessages: EngineMessage[] = [];\n if (thread?.threadData) {\n try {\n const data = JSON.parse(thread.threadData);\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n const m = msg.message ?? msg;\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\")\n : \"\";\n if (m.role === \"user\") {\n existingMessages.push({\n role: \"user\",\n content: [{ type: \"text\", text: textContent }],\n });\n } else if (m.role === \"assistant\") {\n existingMessages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: textContent }],\n });\n }\n }\n }\n } catch {}\n }\n\n // Add the new user message. Include verified platform identity as lightweight\n // context so app-specific agents can attribute requests without guessing.\n const identityLines = [\n `Platform: ${incoming.platform}`,\n incoming.senderName ? `Sender name: ${incoming.senderName}` : null,\n incoming.senderEmail ? `Sender email: ${incoming.senderEmail}` : null,\n incoming.senderId ? `Sender ID: ${incoming.senderId}` : null,\n ].filter(Boolean);\n const userText =\n identityLines.length > 1\n ? `<integration-context>\\n${identityLines.join(\"\\n\")}\\n</integration-context>\\n\\n${incoming.text}`\n : incoming.text;\n\n const messages: EngineMessage[] = [\n ...existingMessages,\n { role: \"user\", content: [{ type: \"text\", text: userText }] },\n ];\n\n // Run agent loop via startRun, wrapped in a request context so that\n // tools (especially call-agent) can resolve the caller's org for org-scoped\n // A2A delegation. Without this, getRequestOrgId() returns undefined and\n // call-agent can't look up the org's a2a_secret or org_domain.\n const orgId = await resolveOrgIdForEmail(ownerEmail);\n const tools = actionsToEngineTools(actions);\n\n const runId = `integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Wait for the run to complete inside this fresh function execution.\n // We use a Promise so the processor endpoint can await the full lifecycle.\n await new Promise<void>((resolve) => {\n startRun(\n runId,\n threadId,\n async (send, signal) => {\n await runWithRequestContext(\n {\n userEmail: ownerEmail,\n orgId: orgId ?? undefined,\n // Lets downstream callers (call-agent script) apply tighter\n // budgets on integration paths without affecting normal\n // agent-chat. See `isIntegrationCallerRequest()`.\n isIntegrationCaller: true,\n integration: opts.taskId\n ? {\n taskId: opts.taskId,\n attempts: opts.attempts,\n incoming,\n placeholderRef: opts.placeholderRef,\n }\n : undefined,\n },\n async () => {\n const effectiveApiKey = await resolveIntegrationApiKey(\n engineOption,\n ownerEmail,\n apiKey,\n );\n const engine = await resolveEngine({\n engineOption,\n apiKey: effectiveApiKey,\n model,\n });\n const resolvedModel =\n (await getStoredModelForEngine(engine)) ??\n model ??\n engine.defaultModel;\n\n return runAgentLoop({\n engine,\n model: resolvedModel,\n systemPrompt: effectiveSystemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n });\n },\n );\n },\n async (completedRun: ActiveRun) => {\n try {\n const queuedA2AContinuation = hasQueuedA2AContinuation(completedRun);\n let responseText = collectFinalResponseTextFromAgentEvents(\n completedRun.events.map((runEvent) => runEvent.event),\n { fallbackToPreToolText: !queuedA2AContinuation },\n );\n if (!queuedA2AContinuation && !responseText.trim()) {\n const recoverableA2AArtifactText =\n extractRecoverableA2AArtifactToolResult(completedRun);\n if (recoverableA2AArtifactText) {\n responseText = recoverableA2AArtifactText;\n }\n }\n\n const suppressPlatformReply =\n queuedA2AContinuation &&\n isQueuedA2AContinuationDeferral(responseText);\n\n // If the run errored OR produced no text, post a graceful fallback so\n // the user isn't left wondering whether the bot saw their message.\n // Common case: an A2A delegation timed out and the agent loop bailed\n // before generating any user-facing text.\n const runErrored = completedRun.status === \"errored\";\n const runErrorText = completedRun.events\n .map((runEvent) =>\n runEvent.event.type === \"error\" ? runEvent.event.error : \"\",\n )\n .filter(Boolean)\n .join(\"\\n\");\n if (\n isLlmCredentialError(responseText) ||\n isLlmCredentialError(runErrorText)\n ) {\n responseText = formatLlmCredentialErrorMessage();\n } else if (\n !suppressPlatformReply &&\n (!responseText.trim() || runErrored)\n ) {\n if (runErrored) {\n responseText =\n (responseText.trim() ? responseText + \"\\n\\n\" : \"\") +\n \"I ran into a problem before I could finish that one. \" +\n \"If it was a complex analytics question, opening the analytics app \" +\n \"directly is the most reliable way to get an answer right now.\";\n } else {\n responseText = \"(No response)\";\n }\n }\n\n // Compute the deep-link to the dispatch UI for this thread, then\n // hand it to the adapter as a structured `threadDeepLinkUrl` so\n // platforms with rich blocks (Slack) can render a button instead\n // of inlining a `<url|text>` link that auto-unfurls into a giant\n // preview card.\n const baseUrl = process.env.APP_URL || process.env.URL || \"\";\n const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : \"\";\n if (!suppressPlatformReply) {\n responseText = appendA2AArtifactLinks(\n responseText,\n collectToolResultSummaries(completedRun),\n { baseUrl: appBaseUrl || undefined },\n );\n }\n const threadDeepLinkUrl =\n appBaseUrl && threadId\n ? `${appBaseUrl}/?thread=${threadId}`\n : undefined;\n\n // Format and send back to platform — update the \"thinking…\"\n // placeholder in place if the adapter supplied one.\n if (!suppressPlatformReply) {\n const outgoing = adapter.formatAgentResponse(responseText, {\n threadDeepLinkUrl,\n });\n await adapter.sendResponse(outgoing, incoming, {\n placeholderRef: opts.placeholderRef,\n });\n }\n\n // Persist thread data\n await persistThreadData(\n threadId,\n incoming.text,\n completedRun,\n thread,\n );\n } catch (err) {\n console.error(\n `[integrations] Error sending response to ${incoming.platform}:`,\n err,\n );\n // Last-ditch: try to post a brief apology so the thread isn't silent.\n try {\n const fallback = adapter.formatAgentResponse(\n \"Something went wrong on my end while replying. Please try again.\",\n );\n await adapter.sendResponse(fallback, incoming);\n } catch {}\n } finally {\n resolve();\n }\n },\n );\n });\n}\n\nfunction hasQueuedA2AContinuation(completedRun: ActiveRun): boolean {\n return completedRun.events.some((runEvent) => {\n const event = runEvent.event;\n return (\n event.type === \"tool_done\" &&\n event.tool === \"call-agent\" &&\n String(event.result ?? \"\").includes(A2A_CONTINUATION_QUEUED_MARKER)\n );\n });\n}\n\nfunction extractRecoverableA2AArtifactToolResult(\n completedRun: ActiveRun,\n): string | null {\n for (let i = completedRun.events.length - 1; i >= 0; i--) {\n const event = completedRun.events[i].event;\n if (event.type !== \"tool_done\" || event.tool !== \"call-agent\") continue;\n\n const result = String(event.result ?? \"\").trim();\n if (\n result.includes(\"verified artifacts already exist\") &&\n result.includes(\"\\nArtifacts:\\n\")\n ) {\n return result;\n }\n }\n return null;\n}\n\nfunction isQueuedA2AContinuationDeferral(text: string): boolean {\n const normalized = text.replace(/\\s+/g, \" \").trim();\n if (!normalized) return true;\n if (hasSubstantiveA2APartialAnswer(text)) return false;\n if (normalized.includes(A2A_CONTINUATION_QUEUED_MARKER)) return true;\n return /\\b(?:still (?:working|processing)|is working on|taking longer than expected|will (?:post|update|surface|show up)|(?:it'?ll|it will|the result will|the final result will) (?:post|be posted|update|be updated|surface|show up)|will be (?:posted|updated|sent|shared)|final result when it finishes|while you wait|as soon as (?:it|it'?s|it is|the result|the artifact) (?:comes back|is ready|ready)|hang tight|relay from the .* agent)\\b/i.test(\n normalized,\n );\n}\n\nfunction hasSubstantiveA2APartialAnswer(text: string): boolean {\n const withoutMarker = text\n .replaceAll(A2A_CONTINUATION_QUEUED_MARKER, \"\")\n .trim();\n if (!withoutMarker) return false;\n if (/https?:\\/\\//i.test(withoutMarker)) return true;\n if (/\\|\\s*[-:]+\\s*\\|/.test(withoutMarker)) return true;\n if (\n /\\b(?:page\\s*views?|unique\\s+visitors?|dashboard|artifact id|document id|deck id|source|query|bigquery|created successfully)\\b/i.test(\n withoutMarker,\n )\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * Persist the user message and agent response to the thread data,\n * so the conversation history is available in the web UI too.\n */\nasync function persistThreadData(\n threadId: string,\n userText: string,\n completedRun: ActiveRun,\n thread: any,\n): Promise<void> {\n try {\n let repo: any;\n try {\n repo = JSON.parse(thread?.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n // Add user message\n const userMsg = {\n id: `msg-${Date.now()}-user`,\n role: \"user\",\n content: [{ type: \"text\", text: userText }],\n createdAt: new Date().toISOString(),\n };\n\n // Build assistant message from run events\n const assistantMsg = buildAssistantMessage(\n completedRun.events ?? [],\n completedRun.runId,\n );\n\n repo.messages.push(userMsg);\n if (assistantMsg) {\n repo.messages.push(assistantMsg);\n }\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread?.title || \"Integration Chat\",\n meta.preview || thread?.preview || \"\",\n repo.messages.length,\n );\n } catch {\n // Best-effort persistence\n }\n}\n"]}
@@ -23,7 +23,7 @@ export const tool = {
23
23
  },
24
24
  model: {
25
25
  type: "string",
26
- description: "Model ID (e.g. 'claude-sonnet-4-6', 'gpt-4o'). Optional for \"set\" and \"test\"; defaults to the engine's default model.",
26
+ description: "Model ID (e.g. 'gpt-5.5', 'claude-sonnet-4-6'). Optional for \"set\" and \"test\"; defaults to the engine's default model.",
27
27
  },
28
28
  },
29
29
  required: ["action"],