@agent-native/core 0.7.50 → 0.7.52

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 (121) hide show
  1. package/dist/a2a/agent-card.d.ts.map +1 -1
  2. package/dist/a2a/agent-card.js +21 -16
  3. package/dist/a2a/agent-card.js.map +1 -1
  4. package/dist/a2a/artifact-response.d.ts.map +1 -1
  5. package/dist/a2a/artifact-response.js +109 -5
  6. package/dist/a2a/artifact-response.js.map +1 -1
  7. package/dist/a2a/auth-policy.d.ts +10 -0
  8. package/dist/a2a/auth-policy.d.ts.map +1 -0
  9. package/dist/a2a/auth-policy.js +34 -0
  10. package/dist/a2a/auth-policy.js.map +1 -0
  11. package/dist/a2a/handlers.d.ts.map +1 -1
  12. package/dist/a2a/handlers.js +5 -4
  13. package/dist/a2a/handlers.js.map +1 -1
  14. package/dist/a2a/index.d.ts +1 -0
  15. package/dist/a2a/index.d.ts.map +1 -1
  16. package/dist/a2a/index.js +1 -0
  17. package/dist/a2a/index.js.map +1 -1
  18. package/dist/a2a/server.d.ts.map +1 -1
  19. package/dist/a2a/server.js +27 -14
  20. package/dist/a2a/server.js.map +1 -1
  21. package/dist/client/resources/ResourceEditor.d.ts.map +1 -1
  22. package/dist/client/resources/ResourceEditor.js +2 -4
  23. package/dist/client/resources/ResourceEditor.js.map +1 -1
  24. package/dist/client/settings/AgentsSection.d.ts.map +1 -1
  25. package/dist/client/settings/AgentsSection.js +4 -6
  26. package/dist/client/settings/AgentsSection.js.map +1 -1
  27. package/dist/deploy/build.d.ts.map +1 -1
  28. package/dist/deploy/build.js +8 -0
  29. package/dist/deploy/build.js.map +1 -1
  30. package/dist/deploy/route-discovery.d.ts.map +1 -1
  31. package/dist/deploy/route-discovery.js +11 -2
  32. package/dist/deploy/route-discovery.js.map +1 -1
  33. package/dist/deploy/workspace-deploy.js +32 -3
  34. package/dist/deploy/workspace-deploy.js.map +1 -1
  35. package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -1
  36. package/dist/integrations/a2a-continuation-processor.js +17 -11
  37. package/dist/integrations/a2a-continuation-processor.js.map +1 -1
  38. package/dist/integrations/a2a-continuations-store.d.ts +2 -1
  39. package/dist/integrations/a2a-continuations-store.d.ts.map +1 -1
  40. package/dist/integrations/a2a-continuations-store.js +33 -4
  41. package/dist/integrations/a2a-continuations-store.js.map +1 -1
  42. package/dist/integrations/plugin.d.ts.map +1 -1
  43. package/dist/integrations/plugin.js +2 -1
  44. package/dist/integrations/plugin.js.map +1 -1
  45. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  46. package/dist/integrations/webhook-handler.js +11 -1
  47. package/dist/integrations/webhook-handler.js.map +1 -1
  48. package/dist/onboarding/plugin.d.ts.map +1 -1
  49. package/dist/onboarding/plugin.js +2 -1
  50. package/dist/onboarding/plugin.js.map +1 -1
  51. package/dist/org/plugin.d.ts.map +1 -1
  52. package/dist/org/plugin.js +2 -1
  53. package/dist/org/plugin.js.map +1 -1
  54. package/dist/resources/handlers.d.ts.map +1 -1
  55. package/dist/resources/handlers.js +2 -3
  56. package/dist/resources/handlers.js.map +1 -1
  57. package/dist/resources/metadata.d.ts +5 -0
  58. package/dist/resources/metadata.d.ts.map +1 -1
  59. package/dist/resources/metadata.js +17 -2
  60. package/dist/resources/metadata.js.map +1 -1
  61. package/dist/resources/store.d.ts.map +1 -1
  62. package/dist/resources/store.js +2 -1
  63. package/dist/resources/store.js.map +1 -1
  64. package/dist/scripts/call-agent.js +2 -2
  65. package/dist/scripts/call-agent.js.map +1 -1
  66. package/dist/server/action-routes.d.ts.map +1 -1
  67. package/dist/server/action-routes.js +5 -11
  68. package/dist/server/action-routes.js.map +1 -1
  69. package/dist/server/agent-chat-plugin.d.ts.map +1 -1
  70. package/dist/server/agent-chat-plugin.js +2 -1
  71. package/dist/server/agent-chat-plugin.js.map +1 -1
  72. package/dist/server/agent-discovery.d.ts.map +1 -1
  73. package/dist/server/agent-discovery.js +7 -4
  74. package/dist/server/agent-discovery.js.map +1 -1
  75. package/dist/server/auth-plugin.d.ts.map +1 -1
  76. package/dist/server/auth-plugin.js +2 -1
  77. package/dist/server/auth-plugin.js.map +1 -1
  78. package/dist/server/auth.d.ts.map +1 -1
  79. package/dist/server/auth.js +13 -12
  80. package/dist/server/auth.js.map +1 -1
  81. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  82. package/dist/server/core-routes-plugin.js +9 -29
  83. package/dist/server/core-routes-plugin.js.map +1 -1
  84. package/dist/server/cors-origins.d.ts +10 -0
  85. package/dist/server/cors-origins.d.ts.map +1 -0
  86. package/dist/server/cors-origins.js +34 -0
  87. package/dist/server/cors-origins.js.map +1 -0
  88. package/dist/server/create-server.d.ts.map +1 -1
  89. package/dist/server/create-server.js +10 -29
  90. package/dist/server/create-server.js.map +1 -1
  91. package/dist/server/framework-request-handler.d.ts +11 -0
  92. package/dist/server/framework-request-handler.d.ts.map +1 -1
  93. package/dist/server/framework-request-handler.js +24 -1
  94. package/dist/server/framework-request-handler.js.map +1 -1
  95. package/dist/server/resources-plugin.d.ts.map +1 -1
  96. package/dist/server/resources-plugin.js +2 -1
  97. package/dist/server/resources-plugin.js.map +1 -1
  98. package/dist/terminal/terminal-plugin.d.ts.map +1 -1
  99. package/dist/terminal/terminal-plugin.js +2 -1
  100. package/dist/terminal/terminal-plugin.js.map +1 -1
  101. package/dist/vite/index.d.ts +1 -1
  102. package/dist/vite/index.d.ts.map +1 -1
  103. package/dist/vite/index.js +1 -1
  104. package/dist/vite/index.js.map +1 -1
  105. package/docs/content/a2a-protocol.md +75 -6
  106. package/docs/content/creating-templates.md +10 -0
  107. package/docs/content/dispatch.md +94 -0
  108. package/docs/content/getting-started.md +8 -0
  109. package/docs/content/key-concepts.md +16 -0
  110. package/docs/content/messaging.md +45 -13
  111. package/docs/content/multi-app-workspace.md +10 -2
  112. package/docs/content/notifications.md +1 -1
  113. package/docs/content/observability.md +184 -0
  114. package/docs/content/onboarding.md +7 -2
  115. package/docs/content/template-dispatch.md +3 -1
  116. package/docs/content/tools.md +95 -1
  117. package/docs/content/tracking.md +1 -1
  118. package/docs/content/what-is-agent-native.md +3 -1
  119. package/docs/content/workspace-management.md +5 -5
  120. package/docs/content/workspace.md +2 -0
  121. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"a2a-continuations-store.js","sourceRoot":"","sources":["../../src/integrations/a2a-continuations-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAGjE,IAAI,YAAuC,CAAC;AAC5C,MAAM,yBAAyB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhD,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,MAAM,CAAC,OAAO,CAAC;;;;;;;;;;;;;;;qBAeN,OAAO,EAAE;0BACJ,OAAO,EAAE;;uBAEZ,OAAO,EAAE;uBACT,OAAO,EAAE;yBACP,OAAO,EAAE;;OAE3B,CAAC,CAAC;YACH,MAAM,MAAM,CAAC,OAAO,CAClB,sHAAsH,CACvH,CAAC;YACF,MAAM,MAAM,CAAC,OAAO,CAClB,mJAAmJ,CACpJ,CAAC;YACF,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,OAAO,CAClB,0EAA0E,CAC3E,CAAC;YACJ,CAAC;YAAC,MAAM,CAAC;gBACP,yBAAyB;YAC3B,CAAC;QACH,CAAC,CAAC,EAAE,CAAC;IACP,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC;AA8BD,SAAS,iBAAiB,CAAC,GAA4B;IACrD,OAAO;QACL,EAAE,EAAE,GAAG,CAAC,EAAY;QACpB,iBAAiB,EAAE,GAAG,CAAC,mBAA6B;QACpD,QAAQ,EAAE,GAAG,CAAC,QAAkB;QAChC,gBA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pB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;uBAEc;QACnB,IAAI,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;KACvD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { getDbExec, isPostgres, intType } from \"../db/client.js\";\nimport type { IncomingMessage } from \"./types.js\";\n\nlet _initPromise: Promise<void> | undefined;\nconst PROCESSING_STUCK_AFTER_MS = 5 * 60 * 1000;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await client.execute(`\n CREATE TABLE IF NOT EXISTS integration_a2a_continuations (\n id TEXT PRIMARY KEY,\n integration_task_id TEXT NOT NULL,\n platform TEXT NOT NULL,\n external_thread_id TEXT NOT NULL,\n incoming_payload TEXT NOT NULL,\n placeholder_ref TEXT,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n agent_name TEXT NOT NULL,\n agent_url TEXT NOT NULL,\n a2a_task_id TEXT NOT NULL,\n a2a_auth_token TEXT,\n status TEXT NOT NULL,\n attempts ${intType()} NOT NULL DEFAULT 0,\n next_check_at ${intType()} NOT NULL,\n error_message TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL,\n completed_at ${intType()}\n )\n `);\n await client.execute(\n `CREATE INDEX IF NOT EXISTS idx_a2a_continuations_status_next ON integration_a2a_continuations(status, next_check_at)`,\n );\n await client.execute(\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_a2a_continuations_remote_task ON integration_a2a_continuations(integration_task_id, agent_url, a2a_task_id)`,\n );\n try {\n await client.execute(\n `ALTER TABLE integration_a2a_continuations ADD COLUMN a2a_auth_token TEXT`,\n );\n } catch {\n // Column already exists.\n }\n })();\n }\n return _initPromise;\n}\n\nexport type A2AContinuationStatus =\n | \"pending\"\n | \"processing\"\n | \"completed\"\n | \"failed\";\n\nexport interface A2AContinuation {\n id: string;\n integrationTaskId: string;\n platform: string;\n externalThreadId: string;\n incoming: IncomingMessage;\n placeholderRef: string | null;\n ownerEmail: string;\n orgId: string | null;\n agentName: string;\n agentUrl: string;\n a2aTaskId: string;\n a2aAuthToken: string | null;\n status: A2AContinuationStatus;\n attempts: number;\n nextCheckAt: number;\n errorMessage: string | null;\n createdAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nfunction rowToContinuation(row: Record<string, unknown>): A2AContinuation {\n return {\n id: row.id as string,\n integrationTaskId: row.integration_task_id as string,\n platform: row.platform as string,\n externalThreadId: row.external_thread_id as string,\n incoming: JSON.parse(row.incoming_payload as string) as IncomingMessage,\n placeholderRef: (row.placeholder_ref as string | null) ?? null,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n agentName: row.agent_name as string,\n agentUrl: row.agent_url as string,\n a2aTaskId: row.a2a_task_id as string,\n a2aAuthToken: (row.a2a_auth_token as string | null) ?? null,\n status: row.status as A2AContinuationStatus,\n attempts: Number(row.attempts ?? 0),\n nextCheckAt: Number(row.next_check_at ?? 0),\n errorMessage: (row.error_message as string | null) ?? null,\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n completedAt:\n row.completed_at == null ? null : Number(row.completed_at as number),\n };\n}\n\nexport async function insertA2AContinuation(input: {\n integrationTaskId: string;\n platform: string;\n externalThreadId: string;\n incoming: IncomingMessage;\n placeholderRef?: string | null;\n ownerEmail: string;\n orgId?: string | null;\n agentName: string;\n agentUrl: string;\n a2aTaskId: string;\n a2aAuthToken?: string | null;\n}): Promise<A2AContinuation> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const id = `a2a-cont-${now}-${Math.random().toString(36).slice(2, 8)}`;\n const payload = JSON.stringify(input.incoming);\n\n try {\n await client.execute({\n sql: `INSERT INTO integration_a2a_continuations\n (id, integration_task_id, platform, external_thread_id, incoming_payload,\n placeholder_ref, owner_email, org_id, agent_name, agent_url, a2a_task_id, a2a_auth_token,\n status, attempts, next_check_at, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n input.integrationTaskId,\n input.platform,\n input.externalThreadId,\n payload,\n input.placeholderRef ?? null,\n input.ownerEmail,\n input.orgId ?? null,\n input.agentName,\n input.agentUrl,\n input.a2aTaskId,\n input.a2aAuthToken ?? null,\n \"pending\",\n 0,\n now,\n now,\n now,\n ],\n });\n return (await getA2AContinuation(id))!;\n } catch (err: any) {\n if (!isDuplicateContinuationError(err)) throw err;\n const existing = await findA2AContinuation(\n input.integrationTaskId,\n input.agentUrl,\n input.a2aTaskId,\n );\n if (existing) return existing;\n throw err;\n }\n}\n\nfunction isDuplicateContinuationError(err: unknown): boolean {\n const e = err as { code?: string; message?: string } | null;\n if (!e) return false;\n if (e.code === \"23505\") return true;\n const msg = String(e.message ?? \"\").toLowerCase();\n return (\n msg.includes(\"unique\") ||\n msg.includes(\"duplicate entry\") ||\n msg.includes(\"duplicate key\")\n );\n}\n\nasync function findA2AContinuation(\n integrationTaskId: string,\n agentUrl: string,\n a2aTaskId: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM integration_a2a_continuations\n WHERE integration_task_id = ? AND agent_url = ? AND a2a_task_id = ?\n LIMIT 1`,\n args: [integrationTaskId, agentUrl, a2aTaskId],\n });\n return rows[0] ? rowToContinuation(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function getA2AContinuation(\n id: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM integration_a2a_continuations WHERE id = ? LIMIT 1`,\n args: [id],\n });\n return rows[0] ? rowToContinuation(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function claimA2AContinuation(\n id: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const processingCutoff = now - PROCESSING_STUCK_AFTER_MS;\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_a2a_continuations\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ?\n AND (status = 'pending' OR (status = 'processing' AND updated_at <= ?))\n RETURNING *`\n : `UPDATE integration_a2a_continuations\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ?\n AND (status = 'pending' OR (status = 'processing' AND updated_at <= ?))`,\n args: [\"processing\", now, id, processingCutoff],\n });\n const rows = result.rows ?? [];\n if (isPostgres()) {\n return rows[0]\n ? rowToContinuation(rows[0] as Record<string, unknown>)\n : null;\n }\n const affected = (result as any)?.rowsAffected ?? (result as any)?.rowCount;\n if (affected === 0) return null;\n const fetched = await getA2AContinuation(id);\n if (!fetched || fetched.status !== \"processing\") return null;\n return fetched;\n}\n\nexport async function claimDueA2AContinuations(\n limit = 5,\n): Promise<A2AContinuation[]> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, next_check_at = ?, updated_at = ?\n WHERE status = 'processing' AND updated_at <= ?`,\n args: [\"pending\", now, now, now - 5 * 60 * 1000],\n });\n const { rows } = await client.execute({\n sql: `SELECT id FROM integration_a2a_continuations\n WHERE status = 'pending' AND next_check_at <= ?\n ORDER BY next_check_at ASC\n LIMIT ?`,\n args: [now, limit],\n });\n const claimed: A2AContinuation[] = [];\n for (const row of rows) {\n const continuation = await claimA2AContinuation(row.id as string);\n if (continuation) claimed.push(continuation);\n }\n return claimed;\n}\n\nexport async function rescheduleA2AContinuation(\n id: string,\n delayMs: number,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, next_check_at = ?, updated_at = ?\n WHERE id = ? AND status = 'processing'`,\n args: [\"pending\", now + delayMs, now, id],\n });\n}\n\nexport async function completeA2AContinuation(id: string): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, updated_at = ?, completed_at = ?\n WHERE id = ?`,\n args: [\"completed\", now, now, id],\n });\n}\n\nexport async function failA2AContinuation(\n id: string,\n errorMessage: string,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, updated_at = ?, error_message = ?\n WHERE id = ?`,\n args: [\"failed\", now, errorMessage.slice(0, 2000), id],\n });\n}\n"]}
1
+ {"version":3,"file":"a2a-continuations-store.js","sourceRoot":"","sources":["../../src/integrations/a2a-continuations-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAGjE,IAAI,YAAuC,CAAC;AAC5C,MAAM,yBAAyB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhD,KAAK,UAAU,WAAW;IACxB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,CAAC,KAAK,IAAI,EAAE;YACzB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;YAC3B,MAAM,MAAM,CAAC,OAAO,CAAC;;;;;;;;;;;;;;;qBAeN,OAAO,EAAE;0BACJ,OAAO,EAAE;;uBAEZ,OAAO,EAAE;uBACT,OAAO,EAAE;yBACP,OAAO,EAAE;;OAE3B,CAAC,CAAC;YACH,MAAM,MAAM,CAAC,OAAO,CAClB,sHAAsH,CACvH,CAAC;YACF,MAAM,MAAM,CAAC,OAAO,CAClB,mJAAmJ,CACpJ,CAAC;YACF,IAAI,CAAC;gBACH,MAAM,MAAM,CAAC,OAAO,CAClB,0EAA0E,CAC3E,CAAC;YACJ,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E,CAAC;IACpB,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;IAC3B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,MAAM,MAAM,CAAC,OAAO,CAAC;QACnB,GAAG,EAAE;;uBAEc;QACnB,IAAI,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC;KACvD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { getDbExec, isPostgres, intType } from \"../db/client.js\";\nimport type { IncomingMessage } from \"./types.js\";\n\nlet _initPromise: Promise<void> | undefined;\nconst PROCESSING_STUCK_AFTER_MS = 5 * 60 * 1000;\n\nasync function ensureTable(): Promise<void> {\n if (!_initPromise) {\n _initPromise = (async () => {\n const client = getDbExec();\n await client.execute(`\n CREATE TABLE IF NOT EXISTS integration_a2a_continuations (\n id TEXT PRIMARY KEY,\n integration_task_id TEXT NOT NULL,\n platform TEXT NOT NULL,\n external_thread_id TEXT NOT NULL,\n incoming_payload TEXT NOT NULL,\n placeholder_ref TEXT,\n owner_email TEXT NOT NULL,\n org_id TEXT,\n agent_name TEXT NOT NULL,\n agent_url TEXT NOT NULL,\n a2a_task_id TEXT NOT NULL,\n a2a_auth_token TEXT,\n status TEXT NOT NULL,\n attempts ${intType()} NOT NULL DEFAULT 0,\n next_check_at ${intType()} NOT NULL,\n error_message TEXT,\n created_at ${intType()} NOT NULL,\n updated_at ${intType()} NOT NULL,\n completed_at ${intType()}\n )\n `);\n await client.execute(\n `CREATE INDEX IF NOT EXISTS idx_a2a_continuations_status_next ON integration_a2a_continuations(status, next_check_at)`,\n );\n await client.execute(\n `CREATE UNIQUE INDEX IF NOT EXISTS idx_a2a_continuations_remote_task ON integration_a2a_continuations(integration_task_id, agent_url, a2a_task_id)`,\n );\n try {\n await client.execute(\n `ALTER TABLE integration_a2a_continuations ADD COLUMN a2a_auth_token TEXT`,\n );\n } catch {\n // Column already exists.\n }\n })();\n }\n return _initPromise;\n}\n\nexport type A2AContinuationStatus =\n | \"pending\"\n | \"processing\"\n | \"delivering\"\n | \"completed\"\n | \"failed\";\n\nexport interface A2AContinuation {\n id: string;\n integrationTaskId: string;\n platform: string;\n externalThreadId: string;\n incoming: IncomingMessage;\n placeholderRef: string | null;\n ownerEmail: string;\n orgId: string | null;\n agentName: string;\n agentUrl: string;\n a2aTaskId: string;\n a2aAuthToken: string | null;\n status: A2AContinuationStatus;\n attempts: number;\n nextCheckAt: number;\n errorMessage: string | null;\n createdAt: number;\n updatedAt: number;\n completedAt: number | null;\n}\n\nfunction rowToContinuation(row: Record<string, unknown>): A2AContinuation {\n return {\n id: row.id as string,\n integrationTaskId: row.integration_task_id as string,\n platform: row.platform as string,\n externalThreadId: row.external_thread_id as string,\n incoming: JSON.parse(row.incoming_payload as string) as IncomingMessage,\n placeholderRef: (row.placeholder_ref as string | null) ?? null,\n ownerEmail: row.owner_email as string,\n orgId: (row.org_id as string | null) ?? null,\n agentName: row.agent_name as string,\n agentUrl: row.agent_url as string,\n a2aTaskId: row.a2a_task_id as string,\n a2aAuthToken: (row.a2a_auth_token as string | null) ?? null,\n status: row.status as A2AContinuationStatus,\n attempts: Number(row.attempts ?? 0),\n nextCheckAt: Number(row.next_check_at ?? 0),\n errorMessage: (row.error_message as string | null) ?? null,\n createdAt: Number(row.created_at ?? 0),\n updatedAt: Number(row.updated_at ?? 0),\n completedAt:\n row.completed_at == null ? null : Number(row.completed_at as number),\n };\n}\n\nexport async function insertA2AContinuation(input: {\n integrationTaskId: string;\n platform: string;\n externalThreadId: string;\n incoming: IncomingMessage;\n placeholderRef?: string | null;\n ownerEmail: string;\n orgId?: string | null;\n agentName: string;\n agentUrl: string;\n a2aTaskId: string;\n a2aAuthToken?: string | null;\n}): Promise<A2AContinuation> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const id = `a2a-cont-${now}-${Math.random().toString(36).slice(2, 8)}`;\n const payload = JSON.stringify(input.incoming);\n\n try {\n await client.execute({\n sql: `INSERT INTO integration_a2a_continuations\n (id, integration_task_id, platform, external_thread_id, incoming_payload,\n placeholder_ref, owner_email, org_id, agent_name, agent_url, a2a_task_id, a2a_auth_token,\n status, attempts, next_check_at, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n args: [\n id,\n input.integrationTaskId,\n input.platform,\n input.externalThreadId,\n payload,\n input.placeholderRef ?? null,\n input.ownerEmail,\n input.orgId ?? null,\n input.agentName,\n input.agentUrl,\n input.a2aTaskId,\n input.a2aAuthToken ?? null,\n \"pending\",\n 0,\n now,\n now,\n now,\n ],\n });\n return (await getA2AContinuation(id))!;\n } catch (err: any) {\n if (!isDuplicateContinuationError(err)) throw err;\n const existing = await findA2AContinuation(\n input.integrationTaskId,\n input.agentUrl,\n input.a2aTaskId,\n );\n if (existing) return existing;\n throw err;\n }\n}\n\nfunction isDuplicateContinuationError(err: unknown): boolean {\n const e = err as { code?: string; message?: string } | null;\n if (!e) return false;\n if (e.code === \"23505\") return true;\n const msg = String(e.message ?? \"\").toLowerCase();\n return (\n msg.includes(\"unique\") ||\n msg.includes(\"duplicate entry\") ||\n msg.includes(\"duplicate key\")\n );\n}\n\nasync function findA2AContinuation(\n integrationTaskId: string,\n agentUrl: string,\n a2aTaskId: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM integration_a2a_continuations\n WHERE integration_task_id = ? AND agent_url = ? AND a2a_task_id = ?\n LIMIT 1`,\n args: [integrationTaskId, agentUrl, a2aTaskId],\n });\n return rows[0] ? rowToContinuation(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function getA2AContinuation(\n id: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const { rows } = await client.execute({\n sql: `SELECT * FROM integration_a2a_continuations WHERE id = ? LIMIT 1`,\n args: [id],\n });\n return rows[0] ? rowToContinuation(rows[0] as Record<string, unknown>) : null;\n}\n\nexport async function claimA2AContinuation(\n id: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const processingCutoff = now - PROCESSING_STUCK_AFTER_MS;\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_a2a_continuations\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ?\n AND (status = 'pending' OR (status IN ('processing', 'delivering') AND updated_at <= ?))\n RETURNING *`\n : `UPDATE integration_a2a_continuations\n SET status = ?, attempts = attempts + 1, updated_at = ?\n WHERE id = ?\n AND (status = 'pending' OR (status IN ('processing', 'delivering') AND updated_at <= ?))`,\n args: [\"processing\", now, id, processingCutoff],\n });\n const rows = result.rows ?? [];\n if (isPostgres()) {\n return rows[0]\n ? rowToContinuation(rows[0] as Record<string, unknown>)\n : null;\n }\n const affected = (result as any)?.rowsAffected ?? (result as any)?.rowCount;\n if (affected === 0) return null;\n const fetched = await getA2AContinuation(id);\n if (!fetched || fetched.status !== \"processing\") return null;\n return fetched;\n}\n\nexport async function claimDueA2AContinuations(\n limit = 5,\n): Promise<A2AContinuation[]> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, next_check_at = ?, updated_at = ?\n WHERE status IN ('processing', 'delivering') AND updated_at <= ?`,\n args: [\"pending\", now, now, now - 5 * 60 * 1000],\n });\n const { rows } = await client.execute({\n sql: `SELECT id FROM integration_a2a_continuations\n WHERE status = 'pending' AND next_check_at <= ?\n ORDER BY next_check_at ASC\n LIMIT ?`,\n args: [now, limit],\n });\n const claimed: A2AContinuation[] = [];\n for (const row of rows) {\n const continuation = await claimA2AContinuation(row.id as string);\n if (continuation) claimed.push(continuation);\n }\n return claimed;\n}\n\nexport async function claimA2AContinuationDelivery(\n id: string,\n): Promise<A2AContinuation | null> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n const result = await client.execute({\n sql: isPostgres()\n ? `UPDATE integration_a2a_continuations\n SET status = ?, updated_at = ?\n WHERE id = ? AND status = 'processing'\n RETURNING *`\n : `UPDATE integration_a2a_continuations\n SET status = ?, updated_at = ?\n WHERE id = ? AND status = 'processing'`,\n args: [\"delivering\", now, id],\n });\n const rows = result.rows ?? [];\n if (isPostgres()) {\n return rows[0]\n ? rowToContinuation(rows[0] as Record<string, unknown>)\n : null;\n }\n const affected = (result as any)?.rowsAffected ?? (result as any)?.rowCount;\n if (affected === 0) return null;\n const fetched = await getA2AContinuation(id);\n if (!fetched || fetched.status !== \"delivering\") return null;\n return fetched;\n}\n\nexport async function rescheduleA2AContinuation(\n id: string,\n delayMs: number,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, next_check_at = ?, updated_at = ?\n WHERE id = ? AND status IN ('processing', 'delivering')`,\n args: [\"pending\", now + delayMs, now, id],\n });\n}\n\nexport async function completeA2AContinuation(id: string): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, updated_at = ?, completed_at = ?\n WHERE id = ?`,\n args: [\"completed\", now, now, id],\n });\n}\n\nexport async function failA2AContinuation(\n id: string,\n errorMessage: string,\n): Promise<void> {\n await ensureTable();\n const client = getDbExec();\n const now = Date.now();\n await client.execute({\n sql: `UPDATE integration_a2a_continuations\n SET status = ?, updated_at = ?, error_message = ?\n WHERE id = ?`,\n args: [\"failed\", now, errorMessage.slice(0, 2000), id],\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/integrations/plugin.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAEV,yBAAyB,EAE1B,MAAM,YAAY,CAAC;AAiCpB,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAyH9D;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,CAAC,EAAE,yBAAyB,GAClC,cAAc,CA6iBhB;AAED;;GAEG;AACH,eAAO,MAAM,yBAAyB,gBAA6B,CAAC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/integrations/plugin.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAEV,yBAAyB,EAE1B,MAAM,YAAY,CAAC;AAiCpB,KAAK,cAAc,GAAG,CAAC,QAAQ,EAAE,GAAG,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAyH9D;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,CAAC,EAAE,yBAAyB,GAClC,cAAc,CA8iBhB;AAED;;GAEG;AACH,eAAO,MAAM,yBAAyB,gBAA6B,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { defineEventHandler, setResponseStatus, getMethod } from "h3";
2
2
  import { createRemoteJWKSet, jwtVerify } from "jose";
3
3
  import { FRAMEWORK_ROUTE_PREFIX } from "../server/core-routes-plugin.js";
4
- import { getH3App } from "../server/framework-request-handler.js";
4
+ import { getH3App, markDefaultPluginProvided, } from "../server/framework-request-handler.js";
5
5
  import { handleWebhook, processIntegrationTask } from "./webhook-handler.js";
6
6
  import { DEFAULT_MODEL } from "../agent/default-model.js";
7
7
  import { claimPendingTask, markTaskCompleted, markTaskFailed, } from "./pending-tasks-store.js";
@@ -138,6 +138,7 @@ If a task requires many steps, summarize what you did rather than streaming ever
138
138
  */
139
139
  export function createIntegrationsPlugin(options) {
140
140
  return async (nitroApp) => {
141
+ markDefaultPluginProvided(nitroApp, "integrations");
141
142
  const adapters = options?.adapters ?? getDefaultAdapters();
142
143
  const adapterMap = new Map();
143
144
  for (const adapter of adapters) {
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/integrations/plugin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BAAyB,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 { getH3App } 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 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,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,EAAE,MAAM,yBAAyB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,IAAI,CAAC;AACtC,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB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C,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 +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;AAwBlC,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,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;AA0CD;;;;;;;;;;;;;;;;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,CASf"}
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,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"}
@@ -17,6 +17,7 @@ import { FRAMEWORK_ROUTE_PREFIX } from "../server/core-routes-plugin.js";
17
17
  import { withConfiguredAppBasePath } from "../server/app-base-path.js";
18
18
  import { A2A_CONTINUATION_QUEUED_MARKER } from "./a2a-continuation-marker.js";
19
19
  import { collectFinalResponseTextFromAgentEvents } from "../a2a/response-text.js";
20
+ import { appendA2AArtifactLinks, } from "../a2a/artifact-response.js";
20
21
  const PROCESSOR_DISPATCH_SETTLE_WAIT_MS = 1_500;
21
22
  /**
22
23
  * Build a stable per-event dedup key from the incoming message. The same
@@ -49,6 +50,12 @@ function isMultiTenantDeploy() {
49
50
  return false;
50
51
  return !isLocalDatabase();
51
52
  }
53
+ function collectToolResultSummaries(completedRun) {
54
+ return completedRun.events
55
+ .map((runEvent) => runEvent.event)
56
+ .filter((event) => event.type === "tool_done")
57
+ .map((event) => ({ tool: event.tool, result: event.result }));
58
+ }
52
59
  async function resolveIntegrationApiKey(engineOption, ownerEmail, fallbackApiKey) {
53
60
  const engineName = explicitEngineName(engineOption);
54
61
  if (engineName) {
@@ -439,6 +446,9 @@ async function processIncomingMessage(incoming, options, opts = {}) {
439
446
  // preview card.
440
447
  const baseUrl = process.env.APP_URL || process.env.URL || "";
441
448
  const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : "";
449
+ if (!suppressPlatformReply) {
450
+ responseText = appendA2AArtifactLinks(responseText, collectToolResultSummaries(completedRun), { baseUrl: appBaseUrl || undefined });
451
+ }
442
452
  const threadDeepLinkUrl = appBaseUrl && threadId
443
453
  ? `${appBaseUrl}/?thread=${threadId}`
444
454
  : undefined;
@@ -484,7 +494,7 @@ function isQueuedA2AContinuationDeferral(text) {
484
494
  return true;
485
495
  if (normalized.includes(A2A_CONTINUATION_QUEUED_MARKER))
486
496
  return true;
487
- return /\b(?:still (?:working|processing)|taking longer than expected|will (?:post|update|surface|show up)|final result when it finishes|while you wait|as soon as (?:it|the result) (?:comes back|is ready)|relay from the .* agent)\b/i.test(normalized);
497
+ 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(normalized);
488
498
  }
489
499
  /**
490
500
  * Persist the user message and agent response to the thread data,