@agent-native/core 0.7.24 → 0.7.26

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.
@@ -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,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAMlE,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,CAAC;AACnD,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,yBAAyB,EAAE,MA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AI,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 { 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 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 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;AAC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AAU,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 { 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 +1 @@
1
- {"version":3,"file":"agent-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AA6BD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAUtE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,EAAE,CAAC,CAiE5B;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAItC;AAeD;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,EAOnD,CAAC"}
1
+ {"version":3,"file":"agent-discovery.d.ts","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,eAAe;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;CACf;AAmCD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,eAAe,EAAE,CAUtE;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,EAAE,CAAC,CAkE5B;AAED;;GAEG;AACH,wBAAsB,SAAS,CAC7B,QAAQ,EAAE,MAAM,EAChB,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC,CAItC;AAeD;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,EAOnD,CAAC"}
@@ -1,4 +1,4 @@
1
- import { visibleTemplates } from "../cli/templates-meta.js";
1
+ import { TEMPLATES, visibleTemplates } from "../cli/templates-meta.js";
2
2
  /**
3
3
  * Built-in agent registry. Derive this from the published CLI metadata so
4
4
  * connected-agent discovery stays aligned with the public template allow-list
@@ -15,6 +15,7 @@ const BUILTIN_AGENTS = visibleTemplates()
15
15
  devPort: template.devPort,
16
16
  color: template.color,
17
17
  }));
18
+ const HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(TEMPLATES.filter((template) => template.hidden && template.prodUrl).map((template) => template.name));
18
19
  /**
19
20
  * Get built-in agents (static, no DB). Used as fallback and for seeding.
20
21
  */
@@ -57,6 +58,8 @@ export async function discoverAgents(selfAppId) {
57
58
  const manifest = parseRemoteAgentManifest(full.content, r.path);
58
59
  if (!manifest || manifest.id === selfAppId)
59
60
  continue;
61
+ if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id))
62
+ continue;
60
63
  // If the resource override carries a localhost URL but we're running
61
64
  // in production (e.g. a stale dev-time seed got promoted to the prod
62
65
  // DB), fall back to the matching built-in's prod URL instead of
@@ -1 +1 @@
1
- {"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoB5D;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW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CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import { visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const resources = isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, \"remote-agents/\")\n : await resourceList(SHARED_OWNER, \"remote-agents/\");\n const { parseRemoteAgentManifest } =\n await import(\"../resources/metadata.js\");\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
1
+ {"version":3,"file":"agent-discovery.js","sourceRoot":"","sources":["../../src/server/agent-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAoBvE;;;;GAIG;AACH,MAAM,cAAc,GAAiB,gBAAgB,EAAE;KACpD,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAClB,EAAE,EAAE,QAAQ,CAAC,IAAI;IACjB,IAAI,EAAE,QAAQ,CAAC,KAAK;IACpB,WAAW,EAAE,QAAQ,CAAC,WAAW,IAAI,QAAQ,CAAC,IAAI;IAClD,GAAG,EAAE,QAAQ,CAAC,OAAQ;IACtB,MAAM,EAAE,oBAAoB,QAAQ,CAAC,OAAO,EAAE;IAC9C,OAAO,EAAE,QAAQ,CAAC,OAAO;IACzB,KAAK,EAAE,QAAQ,CAAC,KAAK;CACtB,CAAC,CAAC,CAAC;AAEN,MAAM,4BAA4B,GAAG,IAAI,GAAG,CAC1C,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,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AAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACpD,EAAE,EAAE,GAAG,CAAC,EAAE;IACV,IAAI,EAAE,GAAG,CAAC,IAAI;IACd,WAAW,EAAE,GAAG,CAAC,WAAW;IAC5B,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,cAAc;IAC5B,KAAK,EAAE,GAAG,CAAC,KAAK;CACjB,CAAC,CAAC,CAAC","sourcesContent":["import { TEMPLATES, visibleTemplates } from \"../cli/templates-meta.js\";\n\nexport interface DiscoveredAgent {\n id: string;\n name: string;\n description: string;\n url: string;\n color: string;\n}\n\ninterface AgentEntry {\n id: string;\n name: string;\n description: string;\n url: string;\n devUrl?: string;\n devPort: number;\n color: string;\n}\n\n/**\n * Built-in agent registry. Derive this from the published CLI metadata so\n * connected-agent discovery stays aligned with the public template allow-list\n * without depending on @agent-native/shared-app-config at runtime.\n */\nconst BUILTIN_AGENTS: AgentEntry[] = visibleTemplates()\n .filter((template) => !!template.prodUrl)\n .map((template) => ({\n id: template.name,\n name: template.label,\n description: template.description ?? template.hint,\n url: template.prodUrl!,\n devUrl: `http://localhost:${template.devPort}`,\n devPort: template.devPort,\n color: template.color,\n }));\n\nconst HIDDEN_FIRST_PARTY_AGENT_IDS = new Set(\n TEMPLATES.filter((template) => template.hidden && template.prodUrl).map(\n (template) => template.name,\n ),\n);\n\n/**\n * Get built-in agents (static, no DB). Used as fallback and for seeding.\n */\nexport function getBuiltinAgents(selfAppId?: string): DiscoveredAgent[] {\n return BUILTIN_AGENTS.filter((app) => app.id !== selfAppId && app.url).map(\n (app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: resolveAgentUrl(app),\n color: app.color,\n }),\n );\n}\n\n/**\n * Discover all agents: built-in + custom agents stored as resources.\n * Custom agents override built-in agents with the same ID.\n */\nexport async function discoverAgents(\n selfAppId?: string,\n): Promise<DiscoveredAgent[]> {\n const builtins = getBuiltinAgents(selfAppId);\n const agentsById = new Map<string, DiscoveredAgent>();\n\n // Start with built-ins\n for (const agent of builtins) {\n agentsById.set(agent.id, agent);\n }\n\n // Overlay custom agents from resources\n try {\n const { resourceList, resourceGet, SHARED_OWNER, resourceListAccessible } =\n await import(\"../resources/store.js\");\n const { DEV_MODE_USER_EMAIL } = await import(\"./auth.js\");\n\n const isDevMode =\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\";\n\n const resources = isDevMode\n ? await resourceListAccessible(DEV_MODE_USER_EMAIL, \"remote-agents/\")\n : await resourceList(SHARED_OWNER, \"remote-agents/\");\n const { parseRemoteAgentManifest } =\n await import(\"../resources/metadata.js\");\n\n for (const r of resources) {\n if (!r.path.endsWith(\".json\")) continue;\n try {\n const full = await resourceGet(r.id);\n if (!full) continue;\n const manifest = parseRemoteAgentManifest(full.content, r.path);\n if (!manifest || manifest.id === selfAppId) continue;\n if (HIDDEN_FIRST_PARTY_AGENT_IDS.has(manifest.id)) continue;\n\n // If the resource override carries a localhost URL but we're running\n // in production (e.g. a stale dev-time seed got promoted to the prod\n // DB), fall back to the matching built-in's prod URL instead of\n // letting the override win — otherwise outbound `call-agent` fetches\n // from a serverless function would target localhost and fail with\n // \"fetch failed\" instantly. The override still wins for non-localhost\n // URLs (the supported case for self-hosted custom agents).\n let url = manifest.url;\n if (\n !isDevMode &&\n typeof url === \"string\" &&\n /^https?:\\/\\/(localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0)(:|\\/|$)/.test(url)\n ) {\n const builtin = agentsById.get(manifest.id);\n if (builtin?.url) url = builtin.url;\n }\n\n agentsById.set(manifest.id, {\n id: manifest.id,\n name: manifest.name,\n description: manifest.description || \"\",\n url,\n color: manifest.color || \"#6B7280\",\n });\n } catch {\n // Skip unreadable resources\n }\n }\n } catch {\n // Resources not available — use built-ins only\n }\n\n return Array.from(agentsById.values());\n}\n\n/**\n * Look up a single agent by ID or name (case-insensitive).\n */\nexport async function findAgent(\n idOrName: string,\n selfAppId?: string,\n): Promise<DiscoveredAgent | undefined> {\n const lower = idOrName.toLowerCase();\n const agents = await discoverAgents(selfAppId);\n return agents.find((a) => a.id === lower || a.name.toLowerCase() === lower);\n}\n\nfunction isDevEnvironment(): boolean {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n}\n\nfunction resolveAgentUrl(app: AgentEntry): string {\n if (isDevEnvironment()) {\n return app.devUrl || `http://localhost:${app.devPort}`;\n }\n return app.url;\n}\n\n/**\n * Like `getBuiltinAgents`, but always returns the production URL — never the\n * env-resolved devUrl. Used by the resource seeder so that a one-time seed\n * (`ON CONFLICT DO NOTHING`) can't permanently bake a localhost URL into the\n * DB, which would override the built-in's prod URL for every later\n * production deploy.\n */\nexport const BUILTIN_AGENTS_FOR_SEEDING: DiscoveredAgent[] =\n BUILTIN_AGENTS.filter((app) => app.url).map((app) => ({\n id: app.id,\n name: app.name,\n description: app.description,\n url: app.url, // ALWAYS prod\n color: app.color,\n }));\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.7.24",
3
+ "version": "0.7.26",
4
4
  "type": "module",
5
5
  "description": "Framework for agent-native application development — where AI agents and UI share state via files",
6
6
  "license": "MIT",