@agent-native/core 0.7.23 → 0.7.24

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 (137) hide show
  1. package/README.md +2 -2
  2. package/dist/a2a/client.d.ts +10 -4
  3. package/dist/a2a/client.d.ts.map +1 -1
  4. package/dist/a2a/client.js +16 -1
  5. package/dist/a2a/client.js.map +1 -1
  6. package/dist/a2a/handlers.d.ts.map +1 -1
  7. package/dist/a2a/handlers.js +20 -17
  8. package/dist/a2a/handlers.js.map +1 -1
  9. package/dist/cli/create.d.ts +2 -1
  10. package/dist/cli/create.d.ts.map +1 -1
  11. package/dist/cli/create.js +13 -19
  12. package/dist/cli/create.js.map +1 -1
  13. package/dist/cli/index.js +23 -0
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/cli/workspace-dev.d.ts +3 -0
  16. package/dist/cli/workspace-dev.d.ts.map +1 -0
  17. package/dist/cli/workspace-dev.js +323 -0
  18. package/dist/cli/workspace-dev.js.map +1 -0
  19. package/dist/cli/workspacify.d.ts +3 -3
  20. package/dist/cli/workspacify.js +4 -4
  21. package/dist/cli/workspacify.js.map +1 -1
  22. package/dist/client/AgentPanel.d.ts.map +1 -1
  23. package/dist/client/AgentPanel.js +10 -9
  24. package/dist/client/AgentPanel.js.map +1 -1
  25. package/dist/client/AssistantChat.d.ts.map +1 -1
  26. package/dist/client/AssistantChat.js +2 -1
  27. package/dist/client/AssistantChat.js.map +1 -1
  28. package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
  29. package/dist/client/MultiTabAssistantChat.js +2 -1
  30. package/dist/client/MultiTabAssistantChat.js.map +1 -1
  31. package/dist/client/components/ui/tooltip.d.ts +8 -0
  32. package/dist/client/components/ui/tooltip.d.ts.map +1 -0
  33. package/dist/client/components/ui/tooltip.js +11 -0
  34. package/dist/client/components/ui/tooltip.js.map +1 -0
  35. package/dist/client/resources/ResourceTree.d.ts.map +1 -1
  36. package/dist/client/resources/ResourceTree.js +21 -17
  37. package/dist/client/resources/ResourceTree.js.map +1 -1
  38. package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
  39. package/dist/client/resources/ResourcesPanel.js +13 -11
  40. package/dist/client/resources/ResourcesPanel.js.map +1 -1
  41. package/dist/deploy/workspace-core.d.ts +1 -1
  42. package/dist/deploy/workspace-core.d.ts.map +1 -1
  43. package/dist/deploy/workspace-core.js +14 -11
  44. package/dist/deploy/workspace-core.js.map +1 -1
  45. package/dist/integrations/a2a-continuation-processor.d.ts +10 -0
  46. package/dist/integrations/a2a-continuation-processor.d.ts.map +1 -0
  47. package/dist/integrations/a2a-continuation-processor.js +150 -0
  48. package/dist/integrations/a2a-continuation-processor.js.map +1 -0
  49. package/dist/integrations/a2a-continuations-store.d.ts +41 -0
  50. package/dist/integrations/a2a-continuations-store.d.ts.map +1 -0
  51. package/dist/integrations/a2a-continuations-store.js +214 -0
  52. package/dist/integrations/a2a-continuations-store.js.map +1 -0
  53. package/dist/integrations/plugin.d.ts.map +1 -1
  54. package/dist/integrations/plugin.js +52 -0
  55. package/dist/integrations/plugin.js.map +1 -1
  56. package/dist/integrations/types.d.ts +5 -0
  57. package/dist/integrations/types.d.ts.map +1 -1
  58. package/dist/integrations/types.js.map +1 -1
  59. package/dist/integrations/webhook-handler.d.ts +6 -0
  60. package/dist/integrations/webhook-handler.d.ts.map +1 -1
  61. package/dist/integrations/webhook-handler.js +69 -15
  62. package/dist/integrations/webhook-handler.js.map +1 -1
  63. package/dist/org/handlers.d.ts.map +1 -1
  64. package/dist/org/handlers.js +22 -16
  65. package/dist/org/handlers.js.map +1 -1
  66. package/dist/scripts/call-agent.d.ts.map +1 -1
  67. package/dist/scripts/call-agent.js +91 -30
  68. package/dist/scripts/call-agent.js.map +1 -1
  69. package/dist/server/agent-discovery.d.ts.map +1 -1
  70. package/dist/server/agent-discovery.js +17 -105
  71. package/dist/server/agent-discovery.js.map +1 -1
  72. package/dist/server/agents-bundle.js +1 -1
  73. package/dist/server/agents-bundle.js.map +1 -1
  74. package/dist/server/auth.d.ts.map +1 -1
  75. package/dist/server/auth.js +29 -120
  76. package/dist/server/auth.js.map +1 -1
  77. package/dist/server/better-auth-instance.d.ts +1 -0
  78. package/dist/server/better-auth-instance.d.ts.map +1 -1
  79. package/dist/server/better-auth-instance.js.map +1 -1
  80. package/dist/server/builder-browser.d.ts.map +1 -1
  81. package/dist/server/builder-browser.js +7 -5
  82. package/dist/server/builder-browser.js.map +1 -1
  83. package/dist/server/framework-request-handler.js +1 -1
  84. package/dist/server/framework-request-handler.js.map +1 -1
  85. package/dist/server/onboarding-html.d.ts +1 -8
  86. package/dist/server/onboarding-html.d.ts.map +1 -1
  87. package/dist/server/onboarding-html.js +321 -152
  88. package/dist/server/onboarding-html.js.map +1 -1
  89. package/dist/server/request-context.d.ts +14 -3
  90. package/dist/server/request-context.d.ts.map +1 -1
  91. package/dist/server/request-context.js +3 -0
  92. package/dist/server/request-context.js.map +1 -1
  93. package/dist/templates/default/_gitignore +2 -0
  94. package/dist/templates/workspace-core/AGENTS.md +18 -71
  95. package/dist/templates/workspace-core/package.json +2 -20
  96. package/dist/templates/workspace-core/src/client/index.ts +2 -26
  97. package/dist/templates/workspace-core/src/index.ts +1 -21
  98. package/dist/templates/workspace-core/src/server/index.ts +3 -22
  99. package/dist/templates/workspace-root/README.md +17 -20
  100. package/dist/templates/workspace-root/_gitignore +3 -0
  101. package/dist/templates/workspace-root/package.json +6 -13
  102. package/dist/templates/workspace-root/pnpm-workspace.yaml +4 -2
  103. package/dist/vite/agents-bundle-plugin.js +2 -2
  104. package/dist/vite/agents-bundle-plugin.js.map +1 -1
  105. package/docs/content/authentication.md +3 -5
  106. package/docs/content/multi-app-workspace.md +38 -50
  107. package/package.json +1 -1
  108. package/src/templates/default/_gitignore +2 -0
  109. package/src/templates/workspace-core/AGENTS.md +18 -71
  110. package/src/templates/workspace-core/package.json +2 -20
  111. package/src/templates/workspace-core/src/client/index.ts +2 -26
  112. package/src/templates/workspace-core/src/index.ts +1 -21
  113. package/src/templates/workspace-core/src/server/index.ts +3 -22
  114. package/src/templates/workspace-root/README.md +17 -20
  115. package/src/templates/workspace-root/_gitignore +3 -0
  116. package/src/templates/workspace-root/package.json +6 -13
  117. package/src/templates/workspace-root/pnpm-workspace.yaml +4 -2
  118. package/dist/templates/default/.claude/settings.json +0 -100
  119. package/dist/templates/workspace-core/.agents/skills/company-policies/SKILL.md +0 -42
  120. package/dist/templates/workspace-core/actions/company-directory.ts +0 -38
  121. package/dist/templates/workspace-core/src/client/AuthenticatedLayout.tsx +0 -37
  122. package/dist/templates/workspace-core/src/credentials.ts +0 -67
  123. package/dist/templates/workspace-core/src/server/agent-chat-plugin.ts +0 -30
  124. package/dist/templates/workspace-core/src/server/auth-plugin.ts +0 -35
  125. package/dist/templates/workspace-core/styles/tokens.css +0 -22
  126. package/dist/templates/workspace-root/.github/workflows/ci.yml +0 -32
  127. package/dist/templates/workspace-root/scripts/workspace-dev.ts +0 -377
  128. package/src/templates/default/.claude/settings.json +0 -100
  129. package/src/templates/workspace-core/.agents/skills/company-policies/SKILL.md +0 -42
  130. package/src/templates/workspace-core/actions/company-directory.ts +0 -38
  131. package/src/templates/workspace-core/src/client/AuthenticatedLayout.tsx +0 -37
  132. package/src/templates/workspace-core/src/credentials.ts +0 -67
  133. package/src/templates/workspace-core/src/server/agent-chat-plugin.ts +0 -30
  134. package/src/templates/workspace-core/src/server/auth-plugin.ts +0 -35
  135. package/src/templates/workspace-core/styles/tokens.css +0 -22
  136. package/src/templates/workspace-root/.github/workflows/ci.yml +0 -32
  137. package/src/templates/workspace-root/scripts/workspace-dev.ts +0 -377
@@ -1 +1 @@
1
- {"version":3,"file":"webhook-handler.js","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CA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C;YAAE,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QAEtD,mBAAmB;QACnB,MAAM,OAAO,GAAG;YACd,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,EAAE,OAAO;YAC5B,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;YAC3C,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;SACpC,CAAC;QAEF,0CAA0C;QAC1C,MAAM,YAAY,GAAG,qBAAqB,CACxC,YAAY,CAAC,MAAM,IAAI,EAAE,EACzB,YAAY,CAAC,KAAK,CACnB,CAAC;QAEF,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5B,IAAI,YAAY,EAAE,CAAC;YACjB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,gBAAgB,CACpB,QAAQ,EACR,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EACpB,IAAI,CAAC,KAAK,IAAI,MAAM,EAAE,KAAK,IAAI,kBAAkB,EACjD,IAAI,CAAC,OAAO,IAAI,MAAM,EAAE,OAAO,IAAI,EAAE,EACrC,IAAI,CAAC,QAAQ,CAAC,MAAM,CACrB,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport type { PlatformAdapter, IncomingMessage } from \"./types.js\";\nimport { getThreadMapping, saveThreadMapping } from \"./thread-mapping-store.js\";\nimport { createThread, getThread } from \"../chat-threads/store.js\";\nimport {\n runAgentLoop,\n actionsToEngineTools,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { createAnthropicEngine } from \"../agent/engine/index.js\";\nimport type { EngineMessage } from \"../agent/engine/types.js\";\nimport { startRun, type ActiveRun } from \"../agent/run-manager.js\";\nimport {\n buildAssistantMessage,\n extractThreadMeta,\n} from \"../agent/thread-data-builder.js\";\nimport { updateThreadData } from \"../chat-threads/store.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveOrgIdForEmail } from \"../org/context.js\";\nimport {\n insertPendingTask,\n isDuplicateEventError,\n type PendingTask,\n} from \"./pending-tasks-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\n\n/**\n * Build a stable per-event dedup key from the incoming message. The same\n * key is computed for every retry of the same event from the platform —\n * Slack/Telegram retry on timeout (3s for Slack), so we MUST treat the\n * second delivery as a duplicate and return 200 silently.\n *\n * The `(platform, external_event_key)` UNIQUE index in\n * `integration_pending_tasks` enforces this at the SQL layer, replacing\n * the previous in-memory Map (H3 in the webhook security audit) which\n * couldn't survive serverless cold starts.\n */\nfunction buildEventDedupKey(incoming: IncomingMessage): string {\n return `${incoming.platform}:${incoming.externalThreadId}:${incoming.timestamp}`;\n}\n\nexport interface WebhookHandlerOptions {\n adapter: PlatformAdapter;\n /** Resolved system prompt string */\n systemPrompt: string;\n /** Action entries for the agent */\n actions: Record<string, ActionEntry>;\n /** Model to use */\n model: string;\n /** Anthropic API key */\n apiKey: string;\n /** Thread owner for personal/shared resource loading */\n ownerEmail: string;\n /**\n * Pre-parsed incoming message. When provided, handleWebhook skips its own\n * verification + parsing steps. Required when the caller has already read\n * the request body (h3 doesn't reliably cache parsed bodies, so re-parsing\n * the same event hangs on streaming providers).\n */\n incoming?: IncomingMessage;\n /** Optional hook to intercept inbound commands before agent execution */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\n/**\n * Process an incoming webhook from a messaging platform.\n *\n * Flow:\n * 1. Handle verification challenges (Slack url_verification, etc.)\n * 2. Verify webhook signature\n * 3. Parse incoming message (null = ignored event)\n * 4. Persist task to SQL\n * 5. Fire-and-forget POST to /_agent-native/integrations/process-task\n * (a fresh function execution with its own timeout budget)\n * 6. Return HTTP 200 immediately (within Slack's 3s SLA)\n *\n * The processor endpoint runs the actual agent loop. This split is essential\n * for serverless platforms (Netlify Lambda, Vercel, Cloudflare Workers) which\n * freeze the function as soon as the response is returned, killing any\n * lingering background promises.\n */\nexport async function handleWebhook(\n event: H3Event,\n options: WebhookHandlerOptions,\n): Promise<{ status: number; body: unknown }> {\n const { adapter, beforeProcess } = options;\n\n let incoming: IncomingMessage | null = options.incoming ?? null;\n\n // When the caller didn't pre-parse, run the full verify + parse pipeline.\n // Otherwise skip it — h3's body stream has already been consumed and a\n // second readBody call hangs on streaming providers.\n if (!incoming) {\n // Step 1: Handle platform-specific verification challenges\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return { status: 200, body: verification.response ?? \"ok\" };\n }\n\n // Step 2: Verify webhook signature\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n return { status: 401, body: { error: \"Invalid webhook signature\" } };\n }\n\n // Step 3: Parse the incoming message\n incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n // Not a user message (bot message, edit, reaction, etc.) — acknowledge silently\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Dedup is enforced inside enqueueAndDispatch — the unique index on\n // `(platform, external_event_key)` raises a constraint violation we treat\n // as \"already enqueued\" and respond 200. We can't dedup BEFORE the\n // beforeProcess hook because some templates use beforeProcess for\n // command-style intercepts that are stateless and idempotent (e.g. a\n // Slack `/help` command that doesn't enqueue a task).\n\n if (beforeProcess) {\n const result = await beforeProcess(incoming, adapter);\n if (result.handled) {\n if (result.responseText?.trim()) {\n const outgoing = adapter.formatAgentResponse(result.responseText);\n await adapter.sendResponse(outgoing, incoming);\n }\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Step 4 + 5: Enqueue to SQL and dispatch to processor in a fresh request.\n try {\n await enqueueAndDispatch(event, incoming, options);\n } catch (err) {\n // Duplicate event delivery: the SQL UNIQUE constraint on\n // (platform, external_event_key) rejected the second insert. This is\n // the expected path when a platform retries an event that already\n // landed (e.g. Slack 3-second timeout) — return 200 so the platform\n // stops retrying. See H3 in the webhook security audit.\n if (isDuplicateEventError(err)) {\n return { status: 200, body: \"ok\" };\n }\n console.error(\n `[integrations] Failed to enqueue/dispatch ${incoming.platform} message:`,\n err,\n );\n // Return 500 so the platform retries. If the SQL insert failed for a\n // non-dup reason, the message is genuinely lost — better to let Slack\n // retry (it will re-fire the same event_callback) than silently drop it.\n return { status: 500, body: { error: \"enqueue failed\" } };\n }\n\n return { status: 200, body: \"ok\" };\n}\n\n/**\n * Persist the task to SQL and dispatch a fresh HTTP request to the processor\n * endpoint. The dispatch is fire-and-forget — we deliberately do NOT await\n * the resulting fetch, so the current handler can return immediately.\n *\n * This pattern works on every supported host:\n * - Netlify Lambda: function returns; the dispatched request hits a fresh\n * Lambda with its own 26s budget.\n * - Vercel Functions: same.\n * - Cloudflare Workers: same (no waitUntil dependency).\n * - Self-hosted Node: a separate request comes back through the same\n * server, but each handler still runs to completion.\n */\nasync function enqueueAndDispatch(\n event: H3Event,\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Resolve the org id once at enqueue-time so the processor doesn't have to\n // re-derive it (and so we can drop it on the row for observability).\n let orgId: string | null = null;\n try {\n orgId = (await resolveOrgIdForEmail(options.ownerEmail)) ?? null;\n } catch {\n orgId = null;\n }\n\n // Post a \"thinking…\" placeholder immediately if the adapter supports\n // in-place edits. The processor flow will update this same message with\n // the final answer, so users see one tidy thread reply instead of\n // \"[silence] → answer\". Adapters without edit support skip this and the\n // processor posts a fresh response.\n let placeholderRef: string | undefined;\n try {\n if (options.adapter.postProcessingPlaceholder) {\n const placeholder =\n await options.adapter.postProcessingPlaceholder(incoming);\n if (placeholder?.placeholderRef) {\n placeholderRef = placeholder.placeholderRef;\n }\n }\n } catch (err) {\n console.error(\"[integrations] postProcessingPlaceholder failed:\", err);\n }\n\n const payload = JSON.stringify({ incoming, placeholderRef });\n\n await insertPendingTask({\n id: taskId,\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n payload,\n ownerEmail: options.ownerEmail,\n orgId,\n // SQL-level dedup key — duplicate webhook deliveries from the same\n // platform produce the same key, so the unique index rejects the\n // second insert (H3 in the webhook security audit).\n externalEventKey: buildEventDedupKey(incoming),\n });\n\n const baseUrl = resolveBaseUrl(event);\n const processUrl = `${baseUrl}${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\n // Sign the dispatch with an HMAC token so the processor endpoint can\n // verify the request came from us and not the public internet. The\n // processor refuses unsigned requests in production (C3 in the webhook\n // security audit). In dev, dispatching unsigned is allowed and falls\n // through to the SQL atomic claim for double-processing protection.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n // Distinguish \"secret not configured\" (the documented dev path) from\n // a real signing failure — silently swallowing both made malformed\n // secrets fail invisibly (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Fire-and-forget: do NOT await the full response (the processor's run\n // takes minutes — we don't want to block the caller). BUT on Netlify\n // Lambda, when we return immediately, the runtime can freeze the function\n // before the outbound TCP handshake even starts, which leaves the dispatch\n // request stuck waiting for the 60s retry-sweep job. Race the fetch\n // against a short timer so the request gets at least ~250ms to leave the\n // box; the trade-off is at most ~250ms of added webhook latency.\n const dispatchPromise = fetch(processUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n }).catch((err) => {\n console.error(\"[integrations] Failed to dispatch processor request:\", err);\n });\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) => setTimeout(resolve, 250)),\n ]);\n}\n\n/**\n * Resolve the base URL we should dispatch the processor request to.\n * Prefers explicit env vars (most reliable on serverless), falls back to the\n * inbound request's headers.\n */\nexport function resolveBaseUrl(event: H3Event): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(fromEnv);\n\n try {\n const headers = (event as any).node?.req?.headers ?? (event as any).headers;\n const get = (name: string): string | undefined => {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const lower = String(name).toLowerCase();\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[lower];\n };\n const proto = get(\"x-forwarded-proto\") || \"http\";\n const host = get(\"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\n `http://localhost:${process.env.PORT || 3000}`,\n );\n }\n}\n\n/**\n * Run the actual agent loop for a previously-enqueued task. Called by the\n * processor endpoint in `plugin.ts`. This is a fresh function execution, so\n * it gets its own timeout budget independent of the inbound webhook handler.\n */\nexport async function processIntegrationTask(\n task: PendingTask,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const parsed = JSON.parse(task.payload) as {\n incoming: IncomingMessage;\n placeholderRef?: string;\n };\n await processIncomingMessage(parsed.incoming, options, {\n placeholderRef: parsed.placeholderRef,\n });\n}\n\n/**\n * Resolve thread, run agent loop, post response, persist thread data.\n * Shared between the new processor endpoint and any direct callers.\n */\nasync function processIncomingMessage(\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n opts: { placeholderRef?: string } = {},\n): Promise<void> {\n const { adapter, systemPrompt, actions, model, apiKey, ownerEmail } = options;\n\n // Resolve or create internal thread\n let mapping = await getThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n );\n\n if (!mapping) {\n const thread = await createThread(ownerEmail, {\n title: `${adapter.label}: ${incoming.senderName || incoming.senderId || \"User\"}`,\n });\n await saveThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n thread.id,\n incoming.platformContext,\n );\n mapping = {\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n internalThreadId: thread.id,\n platformContext: incoming.platformContext,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n }\n\n const threadId = mapping.internalThreadId;\n\n // Load existing thread history for context\n const thread = await getThread(threadId);\n const existingMessages: EngineMessage[] = [];\n if (thread?.threadData) {\n try {\n const data = JSON.parse(thread.threadData);\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n const m = msg.message ?? msg;\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\")\n : \"\";\n if (m.role === \"user\") {\n existingMessages.push({\n role: \"user\",\n content: [{ type: \"text\", text: textContent }],\n });\n } else if (m.role === \"assistant\") {\n existingMessages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: textContent }],\n });\n }\n }\n }\n } catch {}\n }\n\n // Add the new user message. Include verified platform identity as lightweight\n // context so app-specific agents can attribute requests without guessing.\n const identityLines = [\n `Platform: ${incoming.platform}`,\n incoming.senderName ? `Sender name: ${incoming.senderName}` : null,\n incoming.senderEmail ? `Sender email: ${incoming.senderEmail}` : null,\n incoming.senderId ? `Sender ID: ${incoming.senderId}` : null,\n ].filter(Boolean);\n const userText =\n identityLines.length > 1\n ? `<integration-context>\\n${identityLines.join(\"\\n\")}\\n</integration-context>\\n\\n${incoming.text}`\n : incoming.text;\n\n const messages: EngineMessage[] = [\n ...existingMessages,\n { role: \"user\", content: [{ type: \"text\", text: userText }] },\n ];\n\n // Run agent loop via startRun, wrapped in a request context so that\n // tools (especially call-agent) can resolve the caller's org for org-scoped\n // A2A delegation. Without this, getRequestOrgId() returns undefined and\n // call-agent can't look up the org's a2a_secret or org_domain.\n const orgId = await resolveOrgIdForEmail(ownerEmail);\n const engine = createAnthropicEngine({ apiKey });\n const tools = actionsToEngineTools(actions);\n\n const runId = `integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Wait for the run to complete inside this fresh function execution.\n // We use a Promise so the processor endpoint can await the full lifecycle.\n await new Promise<void>((resolve) => {\n startRun(\n runId,\n threadId,\n async (send, signal) => {\n await runWithRequestContext(\n {\n userEmail: ownerEmail,\n orgId: orgId ?? undefined,\n // Lets downstream callers (call-agent script) apply tighter\n // budgets on integration paths without affecting normal\n // agent-chat. See `isIntegrationCallerRequest()`.\n isIntegrationCaller: true,\n },\n () =>\n runAgentLoop({\n engine,\n model,\n systemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n }),\n );\n },\n async (completedRun: ActiveRun) => {\n try {\n // Collect text events from the run, but drop any pre-tool-call\n // preamble so the user sees just the final answer instead of\n // \"I need to delegate this...\" run-on into the raw tool result.\n //\n // Heuristic: when the agent fired any tool, only keep text events\n // that come AFTER the last tool. The preamble (\"Let me check…\")\n // and the final answer (\"630\") are emitted as two separate text\n // events, and concatenating them with no separator was producing\n // \"...signup data.630\" in Slack.\n let lastToolIdx = -1;\n for (let i = completedRun.events.length - 1; i >= 0; i--) {\n const t = completedRun.events[i].event.type;\n if (t === \"tool_start\" || t === \"tool_done\") {\n lastToolIdx = i;\n break;\n }\n }\n const startIdx = lastToolIdx >= 0 ? lastToolIdx + 1 : 0;\n let responseText = \"\";\n for (let i = startIdx; i < completedRun.events.length; i++) {\n const ev = completedRun.events[i].event;\n if (ev.type === \"text\") responseText += ev.text;\n }\n // If the post-tool window had no text (tool spoke for itself),\n // fall back to all text events so we never leave the user with\n // an empty reply.\n if (!responseText.trim() && lastToolIdx >= 0) {\n for (const runEvent of completedRun.events) {\n if (runEvent.event.type === \"text\") {\n responseText += runEvent.event.text;\n }\n }\n }\n\n // If the run errored OR produced no text, post a graceful fallback so\n // the user isn't left wondering whether the bot saw their message.\n // Common case: an A2A delegation timed out and the agent loop bailed\n // before generating any user-facing text.\n const runErrored = completedRun.status === \"errored\";\n if (!responseText.trim() || runErrored) {\n if (runErrored) {\n responseText =\n (responseText.trim() ? responseText + \"\\n\\n\" : \"\") +\n \"I ran into a problem before I could finish that one. \" +\n \"If it was a complex analytics question, opening the analytics app \" +\n \"directly is the most reliable way to get an answer right now.\";\n } else {\n responseText = \"(No response)\";\n }\n }\n\n // Compute the deep-link to the dispatch UI for this thread, then\n // hand it to the adapter as a structured `threadDeepLinkUrl` so\n // platforms with rich blocks (Slack) can render a button instead\n // of inlining a `<url|text>` link that auto-unfurls into a giant\n // preview card.\n const baseUrl = process.env.APP_URL || process.env.URL || \"\";\n const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : \"\";\n const threadDeepLinkUrl =\n appBaseUrl && threadId\n ? `${appBaseUrl}/?thread=${threadId}`\n : undefined;\n\n // Format and send back to platform — update the \"thinking…\"\n // placeholder in place if the adapter supplied one.\n const outgoing = adapter.formatAgentResponse(responseText, {\n threadDeepLinkUrl,\n });\n await adapter.sendResponse(outgoing, incoming, {\n placeholderRef: opts.placeholderRef,\n });\n\n // Persist thread data\n await persistThreadData(\n threadId,\n incoming.text,\n completedRun,\n thread,\n );\n } catch (err) {\n console.error(\n `[integrations] Error sending response to ${incoming.platform}:`,\n err,\n );\n // Last-ditch: try to post a brief apology so the thread isn't silent.\n try {\n const fallback = adapter.formatAgentResponse(\n \"Something went wrong on my end while replying. Please try again.\",\n );\n await adapter.sendResponse(fallback, incoming);\n } catch {}\n } finally {\n resolve();\n }\n },\n );\n });\n}\n\n/**\n * Persist the user message and agent response to the thread data,\n * so the conversation history is available in the web UI too.\n */\nasync function persistThreadData(\n threadId: string,\n userText: string,\n completedRun: ActiveRun,\n thread: any,\n): Promise<void> {\n try {\n let repo: any;\n try {\n repo = JSON.parse(thread?.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n // Add user message\n const userMsg = {\n id: `msg-${Date.now()}-user`,\n role: \"user\",\n content: [{ type: \"text\", text: userText }],\n createdAt: new Date().toISOString(),\n };\n\n // Build assistant message from run events\n const assistantMsg = buildAssistantMessage(\n completedRun.events ?? [],\n completedRun.runId,\n );\n\n repo.messages.push(userMsg);\n if (assistantMsg) {\n repo.messages.push(assistantMsg);\n }\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread?.title || \"Integration Chat\",\n meta.preview || thread?.preview || \"\",\n repo.messages.length,\n );\n } catch {\n // Best-effort persistence\n }\n}\n"]}
1
+ {"version":3,"file":"webhook-handler.js","sourceRoot":"","sources":["../../src/integrations/webhook-handler.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,oBAAoB,EACpB,cAAc,EACd,gBAAgB,GAEjB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,sCAAsC,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAC3E,OAAO,EACL,uBAAuB,EACvB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAGlC,OAAO,EAAE,QAAQ,EAAkB,MAAM,yBAAyB,CAAC;AACnE,OAAO,EACL,qBAAqB,EACrB,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,C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apping, saveThreadMapping } from \"./thread-mapping-store.js\";\nimport { createThread, getThread } from \"../chat-threads/store.js\";\nimport {\n runAgentLoop,\n actionsToEngineTools,\n getOwnerActiveApiKey,\n getOwnerApiKey,\n engineToProvider,\n type ActionEntry,\n} from \"../agent/production-agent.js\";\nimport { PROVIDER_TO_ENV } from \"../agent/engine/provider-env-vars.js\";\nimport { isLocalDatabase } from \"../db/client.js\";\nimport { readDeployCredentialEnv } from \"../server/credential-provider.js\";\nimport {\n getStoredModelForEngine,\n resolveEngine,\n} from \"../agent/engine/index.js\";\nimport type { AgentEngine } from \"../agent/engine/types.js\";\nimport type { EngineMessage } from \"../agent/engine/types.js\";\nimport { startRun, type ActiveRun } from \"../agent/run-manager.js\";\nimport {\n buildAssistantMessage,\n extractThreadMeta,\n} from \"../agent/thread-data-builder.js\";\nimport { updateThreadData } from \"../chat-threads/store.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveOrgIdForEmail } from \"../org/context.js\";\nimport {\n insertPendingTask,\n isDuplicateEventError,\n type PendingTask,\n} from \"./pending-tasks-store.js\";\nimport { signInternalToken } from \"./internal-token.js\";\nimport { FRAMEWORK_ROUTE_PREFIX } from \"../server/core-routes-plugin.js\";\nimport { withConfiguredAppBasePath } from \"../server/app-base-path.js\";\n\n/**\n * Build a stable per-event dedup key from the incoming message. The same\n * key is computed for every retry of the same event from the platform —\n * Slack/Telegram retry on timeout (3s for Slack), so we MUST treat the\n * second delivery as a duplicate and return 200 silently.\n *\n * The `(platform, external_event_key)` UNIQUE index in\n * `integration_pending_tasks` enforces this at the SQL layer, replacing\n * the previous in-memory Map (H3 in the webhook security audit) which\n * couldn't survive serverless cold starts.\n */\nfunction buildEventDedupKey(incoming: IncomingMessage): string {\n return `${incoming.platform}:${incoming.externalThreadId}:${incoming.timestamp}`;\n}\n\nexport interface WebhookHandlerOptions {\n adapter: PlatformAdapter;\n /** Resolved system prompt string */\n systemPrompt: string;\n /** Action entries for the agent */\n actions: Record<string, ActionEntry>;\n /** Model to use */\n model: string;\n /** Anthropic API key */\n apiKey: string;\n /** Agent engine to use. Defaults to the same resolver as web chat. */\n engine?:\n | AgentEngine\n | string\n | { name: string; config: Record<string, unknown> };\n /** Thread owner for personal/shared resource loading */\n ownerEmail: string;\n /**\n * Pre-parsed incoming message. When provided, handleWebhook skips its own\n * verification + parsing steps. Required when the caller has already read\n * the request body (h3 doesn't reliably cache parsed bodies, so re-parsing\n * the same event hangs on streaming providers).\n */\n incoming?: IncomingMessage;\n /** Optional hook to intercept inbound commands before agent execution */\n beforeProcess?: (\n incoming: IncomingMessage,\n adapter: PlatformAdapter,\n ) => Promise<\n | {\n handled: true;\n responseText?: string;\n }\n | { handled: false }\n >;\n}\n\nfunction explicitEngineName(\n engineOption: WebhookHandlerOptions[\"engine\"],\n): string | undefined {\n if (!engineOption) return undefined;\n if (typeof engineOption === \"string\") return engineOption;\n if (\n typeof engineOption === \"object\" &&\n !(\"stream\" in engineOption) &&\n typeof engineOption.name === \"string\"\n ) {\n return engineOption.name;\n }\n return undefined;\n}\n\nfunction isMultiTenantDeploy(): boolean {\n if (process.env.NODE_ENV !== \"production\") return false;\n return !isLocalDatabase();\n}\n\nasync function resolveIntegrationApiKey(\n engineOption: WebhookHandlerOptions[\"engine\"],\n ownerEmail: string,\n fallbackApiKey: string,\n): Promise<string | undefined> {\n const engineName = explicitEngineName(engineOption);\n if (engineName) {\n const provider = engineToProvider(engineName);\n const userApiKey = await getOwnerApiKey(provider, ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n const envVar = PROVIDER_TO_ENV[provider];\n const providerEnvKey = envVar ? readDeployCredentialEnv(envVar) : undefined;\n return providerEnvKey || fallbackApiKey.trim() || undefined;\n }\n\n const userApiKey = await getOwnerActiveApiKey(ownerEmail);\n if (userApiKey || isMultiTenantDeploy()) return userApiKey;\n return fallbackApiKey.trim() || undefined;\n}\n\n/**\n * Process an incoming webhook from a messaging platform.\n *\n * Flow:\n * 1. Handle verification challenges (Slack url_verification, etc.)\n * 2. Verify webhook signature\n * 3. Parse incoming message (null = ignored event)\n * 4. Persist task to SQL\n * 5. Fire-and-forget POST to /_agent-native/integrations/process-task\n * (a fresh function execution with its own timeout budget)\n * 6. Return HTTP 200 immediately (within Slack's 3s SLA)\n *\n * The processor endpoint runs the actual agent loop. This split is essential\n * for serverless platforms (Netlify Lambda, Vercel, Cloudflare Workers) which\n * freeze the function as soon as the response is returned, killing any\n * lingering background promises.\n */\nexport async function handleWebhook(\n event: H3Event,\n options: WebhookHandlerOptions,\n): Promise<{ status: number; body: unknown }> {\n const { adapter, beforeProcess } = options;\n\n let incoming: IncomingMessage | null = options.incoming ?? null;\n\n // When the caller didn't pre-parse, run the full verify + parse pipeline.\n // Otherwise skip it — h3's body stream has already been consumed and a\n // second readBody call hangs on streaming providers.\n if (!incoming) {\n // Step 1: Handle platform-specific verification challenges\n const verification = await adapter.handleVerification(event);\n if (verification.handled) {\n return { status: 200, body: verification.response ?? \"ok\" };\n }\n\n // Step 2: Verify webhook signature\n const isValid = await adapter.verifyWebhook(event);\n if (!isValid) {\n return { status: 401, body: { error: \"Invalid webhook signature\" } };\n }\n\n // Step 3: Parse the incoming message\n incoming = await adapter.parseIncomingMessage(event);\n if (!incoming) {\n // Not a user message (bot message, edit, reaction, etc.) — acknowledge silently\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Dedup is enforced inside enqueueAndDispatch — the unique index on\n // `(platform, external_event_key)` raises a constraint violation we treat\n // as \"already enqueued\" and respond 200. We can't dedup BEFORE the\n // beforeProcess hook because some templates use beforeProcess for\n // command-style intercepts that are stateless and idempotent (e.g. a\n // Slack `/help` command that doesn't enqueue a task).\n\n if (beforeProcess) {\n const result = await beforeProcess(incoming, adapter);\n if (result.handled) {\n if (result.responseText?.trim()) {\n const outgoing = adapter.formatAgentResponse(result.responseText);\n await adapter.sendResponse(outgoing, incoming);\n }\n return { status: 200, body: \"ok\" };\n }\n }\n\n // Step 4 + 5: Enqueue to SQL and dispatch to processor in a fresh request.\n try {\n await enqueueAndDispatch(event, incoming, options);\n } catch (err) {\n // Duplicate event delivery: the SQL UNIQUE constraint on\n // (platform, external_event_key) rejected the second insert. This is\n // the expected path when a platform retries an event that already\n // landed (e.g. Slack 3-second timeout) — return 200 so the platform\n // stops retrying. See H3 in the webhook security audit.\n if (isDuplicateEventError(err)) {\n return { status: 200, body: \"ok\" };\n }\n console.error(\n `[integrations] Failed to enqueue/dispatch ${incoming.platform} message:`,\n err,\n );\n // Return 500 so the platform retries. If the SQL insert failed for a\n // non-dup reason, the message is genuinely lost — better to let Slack\n // retry (it will re-fire the same event_callback) than silently drop it.\n return { status: 500, body: { error: \"enqueue failed\" } };\n }\n\n return { status: 200, body: \"ok\" };\n}\n\n/**\n * Persist the task to SQL and dispatch a fresh HTTP request to the processor\n * endpoint. The dispatch is fire-and-forget — we deliberately do NOT await\n * the resulting fetch, so the current handler can return immediately.\n *\n * This pattern works on every supported host:\n * - Netlify Lambda: function returns; the dispatched request hits a fresh\n * Lambda with its own function budget.\n * - Vercel Functions: same.\n * - Cloudflare Workers: same (no waitUntil dependency).\n * - Self-hosted Node: a separate request comes back through the same\n * server, but each handler still runs to completion.\n */\nasync function enqueueAndDispatch(\n event: H3Event,\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Resolve the org id once at enqueue-time so the processor doesn't have to\n // re-derive it (and so we can drop it on the row for observability).\n let orgId: string | null = null;\n try {\n orgId = (await resolveOrgIdForEmail(options.ownerEmail)) ?? null;\n } catch {\n orgId = null;\n }\n\n // Post a \"thinking…\" placeholder immediately if the adapter supports\n // in-place edits. The processor flow will update this same message with\n // the final answer, so users see one tidy thread reply instead of\n // \"[silence] → answer\". Adapters without edit support skip this and the\n // processor posts a fresh response.\n let placeholderRef: string | undefined;\n try {\n if (options.adapter.postProcessingPlaceholder) {\n const placeholder =\n await options.adapter.postProcessingPlaceholder(incoming);\n if (placeholder?.placeholderRef) {\n placeholderRef = placeholder.placeholderRef;\n }\n }\n } catch (err) {\n console.error(\"[integrations] postProcessingPlaceholder failed:\", err);\n }\n\n const payload = JSON.stringify({ incoming, placeholderRef });\n\n await insertPendingTask({\n id: taskId,\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n payload,\n ownerEmail: options.ownerEmail,\n orgId,\n // SQL-level dedup key — duplicate webhook deliveries from the same\n // platform produce the same key, so the unique index rejects the\n // second insert (H3 in the webhook security audit).\n externalEventKey: buildEventDedupKey(incoming),\n });\n\n const baseUrl = resolveBaseUrl(event);\n const processUrl = `${baseUrl}${FRAMEWORK_ROUTE_PREFIX}/integrations/process-task`;\n\n // Sign the dispatch with an HMAC token so the processor endpoint can\n // verify the request came from us and not the public internet. The\n // processor refuses unsigned requests in production (C3 in the webhook\n // security audit). In dev, dispatching unsigned is allowed and falls\n // through to the SQL atomic claim for double-processing protection.\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n try {\n headers[\"Authorization\"] = `Bearer ${signInternalToken(taskId)}`;\n } catch (err) {\n // Distinguish \"secret not configured\" (the documented dev path) from\n // a real signing failure — silently swallowing both made malformed\n // secrets fail invisibly (L5 in the audit).\n if (err instanceof Error && !/A2A_SECRET/i.test(err.message)) {\n console.error(\n `[integrations] signInternalToken failed unexpectedly for ${taskId}:`,\n err,\n );\n }\n }\n\n // Fire-and-forget: do NOT await the full response (the processor's run\n // takes minutes — we don't want to block the caller). BUT on Netlify\n // Lambda, when we return immediately, the runtime can freeze the function\n // before the outbound TCP handshake even starts, which leaves the dispatch\n // request stuck waiting for the 60s retry-sweep job. Race the fetch\n // against a short timer so the request gets at least ~250ms to leave the\n // box; the trade-off is at most ~250ms of added webhook latency.\n const dispatchPromise = fetch(processUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ taskId }),\n }).catch((err) => {\n console.error(\"[integrations] Failed to dispatch processor request:\", err);\n });\n await Promise.race([\n dispatchPromise,\n new Promise<void>((resolve) => setTimeout(resolve, 250)),\n ]);\n}\n\n/**\n * Resolve the base URL we should dispatch the processor request to.\n * Prefers explicit env vars (most reliable on serverless), falls back to the\n * inbound request's headers.\n */\nexport function resolveBaseUrl(event: H3Event): string {\n const fromEnv =\n process.env.APP_URL ||\n process.env.URL ||\n process.env.DEPLOY_URL ||\n process.env.BETTER_AUTH_URL;\n if (fromEnv) return withConfiguredAppBasePath(fromEnv);\n\n try {\n const headers = (event as any).node?.req?.headers ?? (event as any).headers;\n const get = (name: string): string | undefined => {\n if (!headers) return undefined;\n if (typeof headers.get === \"function\") {\n return headers.get(name) ?? undefined;\n }\n const lower = String(name).toLowerCase();\n const map = headers as Record<string, string | undefined>;\n return map[name] ?? map[lower];\n };\n const proto = get(\"x-forwarded-proto\") || \"http\";\n const host = get(\"host\") || `localhost:${process.env.PORT || 3000}`;\n return withConfiguredAppBasePath(`${proto}://${host}`);\n } catch {\n return withConfiguredAppBasePath(\n `http://localhost:${process.env.PORT || 3000}`,\n );\n }\n}\n\n/**\n * Run the actual agent loop for a previously-enqueued task. Called by the\n * processor endpoint in `plugin.ts`. This is a fresh function execution, so\n * it gets its own timeout budget independent of the inbound webhook handler.\n */\nexport async function processIntegrationTask(\n task: PendingTask,\n options: WebhookHandlerOptions,\n): Promise<void> {\n const parsed = JSON.parse(task.payload) as {\n incoming: IncomingMessage;\n placeholderRef?: string;\n };\n await processIncomingMessage(parsed.incoming, options, {\n taskId: task.id,\n placeholderRef: parsed.placeholderRef,\n });\n}\n\n/**\n * Resolve thread, run agent loop, post response, persist thread data.\n * Shared between the new processor endpoint and any direct callers.\n */\nasync function processIncomingMessage(\n incoming: IncomingMessage,\n options: WebhookHandlerOptions,\n opts: { taskId?: string; placeholderRef?: string } = {},\n): Promise<void> {\n const {\n adapter,\n systemPrompt,\n actions,\n model,\n apiKey,\n ownerEmail,\n engine: engineOption,\n } = options;\n\n // Resolve or create internal thread\n let mapping = await getThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n );\n\n if (!mapping) {\n const thread = await createThread(ownerEmail, {\n title: `${adapter.label}: ${incoming.senderName || incoming.senderId || \"User\"}`,\n });\n await saveThreadMapping(\n incoming.platform,\n incoming.externalThreadId,\n thread.id,\n incoming.platformContext,\n );\n mapping = {\n platform: incoming.platform,\n externalThreadId: incoming.externalThreadId,\n internalThreadId: thread.id,\n platformContext: incoming.platformContext,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n };\n }\n\n const threadId = mapping.internalThreadId;\n\n // Load existing thread history for context\n const thread = await getThread(threadId);\n const existingMessages: EngineMessage[] = [];\n if (thread?.threadData) {\n try {\n const data = JSON.parse(thread.threadData);\n if (Array.isArray(data.messages)) {\n for (const msg of data.messages) {\n const m = msg.message ?? msg;\n const textContent =\n typeof m.content === \"string\"\n ? m.content\n : Array.isArray(m.content)\n ? m.content\n .filter((c: any) => c.type === \"text\")\n .map((c: any) => c.text)\n .join(\"\\n\")\n : \"\";\n if (m.role === \"user\") {\n existingMessages.push({\n role: \"user\",\n content: [{ type: \"text\", text: textContent }],\n });\n } else if (m.role === \"assistant\") {\n existingMessages.push({\n role: \"assistant\",\n content: [{ type: \"text\", text: textContent }],\n });\n }\n }\n }\n } catch {}\n }\n\n // Add the new user message. Include verified platform identity as lightweight\n // context so app-specific agents can attribute requests without guessing.\n const identityLines = [\n `Platform: ${incoming.platform}`,\n incoming.senderName ? `Sender name: ${incoming.senderName}` : null,\n incoming.senderEmail ? `Sender email: ${incoming.senderEmail}` : null,\n incoming.senderId ? `Sender ID: ${incoming.senderId}` : null,\n ].filter(Boolean);\n const userText =\n identityLines.length > 1\n ? `<integration-context>\\n${identityLines.join(\"\\n\")}\\n</integration-context>\\n\\n${incoming.text}`\n : incoming.text;\n\n const messages: EngineMessage[] = [\n ...existingMessages,\n { role: \"user\", content: [{ type: \"text\", text: userText }] },\n ];\n\n // Run agent loop via startRun, wrapped in a request context so that\n // tools (especially call-agent) can resolve the caller's org for org-scoped\n // A2A delegation. Without this, getRequestOrgId() returns undefined and\n // call-agent can't look up the org's a2a_secret or org_domain.\n const orgId = await resolveOrgIdForEmail(ownerEmail);\n const tools = actionsToEngineTools(actions);\n\n const runId = `integration-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n // Wait for the run to complete inside this fresh function execution.\n // We use a Promise so the processor endpoint can await the full lifecycle.\n await new Promise<void>((resolve) => {\n startRun(\n runId,\n threadId,\n async (send, signal) => {\n await runWithRequestContext(\n {\n userEmail: ownerEmail,\n orgId: orgId ?? undefined,\n // Lets downstream callers (call-agent script) apply tighter\n // budgets on integration paths without affecting normal\n // agent-chat. See `isIntegrationCallerRequest()`.\n isIntegrationCaller: true,\n integration: opts.taskId\n ? {\n taskId: opts.taskId,\n incoming,\n placeholderRef: opts.placeholderRef,\n }\n : undefined,\n },\n async () => {\n const effectiveApiKey = await resolveIntegrationApiKey(\n engineOption,\n ownerEmail,\n apiKey,\n );\n const engine = await resolveEngine({\n engineOption,\n apiKey: effectiveApiKey,\n model,\n });\n const resolvedModel =\n (await getStoredModelForEngine(engine)) ??\n model ??\n engine.defaultModel;\n\n return runAgentLoop({\n engine,\n model: resolvedModel,\n systemPrompt,\n tools,\n messages,\n actions,\n send,\n signal,\n });\n },\n );\n },\n async (completedRun: ActiveRun) => {\n try {\n // Collect text events from the run, but drop any pre-tool-call\n // preamble so the user sees just the final answer instead of\n // \"I need to delegate this...\" run-on into the raw tool result.\n //\n // Heuristic: when the agent fired any tool, only keep text events\n // that come AFTER the last tool. The preamble (\"Let me check…\")\n // and the final answer (\"630\") are emitted as two separate text\n // events, and concatenating them with no separator was producing\n // \"...signup data.630\" in Slack.\n let lastToolIdx = -1;\n for (let i = completedRun.events.length - 1; i >= 0; i--) {\n const t = completedRun.events[i].event.type;\n if (t === \"tool_start\" || t === \"tool_done\") {\n lastToolIdx = i;\n break;\n }\n }\n const startIdx = lastToolIdx >= 0 ? lastToolIdx + 1 : 0;\n let responseText = \"\";\n for (let i = startIdx; i < completedRun.events.length; i++) {\n const ev = completedRun.events[i].event;\n if (ev.type === \"text\") responseText += ev.text;\n }\n // If the post-tool window had no text (tool spoke for itself),\n // fall back to all text events so we never leave the user with\n // an empty reply.\n if (!responseText.trim() && lastToolIdx >= 0) {\n for (const runEvent of completedRun.events) {\n if (runEvent.event.type === \"text\") {\n responseText += runEvent.event.text;\n }\n }\n }\n\n // If the run errored OR produced no text, post a graceful fallback so\n // the user isn't left wondering whether the bot saw their message.\n // Common case: an A2A delegation timed out and the agent loop bailed\n // before generating any user-facing text.\n const runErrored = completedRun.status === \"errored\";\n if (!responseText.trim() || runErrored) {\n if (runErrored) {\n responseText =\n (responseText.trim() ? responseText + \"\\n\\n\" : \"\") +\n \"I ran into a problem before I could finish that one. \" +\n \"If it was a complex analytics question, opening the analytics app \" +\n \"directly is the most reliable way to get an answer right now.\";\n } else {\n responseText = \"(No response)\";\n }\n }\n\n // Compute the deep-link to the dispatch UI for this thread, then\n // hand it to the adapter as a structured `threadDeepLinkUrl` so\n // platforms with rich blocks (Slack) can render a button instead\n // of inlining a `<url|text>` link that auto-unfurls into a giant\n // preview card.\n const baseUrl = process.env.APP_URL || process.env.URL || \"\";\n const appBaseUrl = baseUrl ? withConfiguredAppBasePath(baseUrl) : \"\";\n const threadDeepLinkUrl =\n appBaseUrl && threadId\n ? `${appBaseUrl}/?thread=${threadId}`\n : undefined;\n\n // Format and send back to platform — update the \"thinking…\"\n // placeholder in place if the adapter supplied one.\n const outgoing = adapter.formatAgentResponse(responseText, {\n threadDeepLinkUrl,\n });\n await adapter.sendResponse(outgoing, incoming, {\n placeholderRef: opts.placeholderRef,\n });\n\n // Persist thread data\n await persistThreadData(\n threadId,\n incoming.text,\n completedRun,\n thread,\n );\n } catch (err) {\n console.error(\n `[integrations] Error sending response to ${incoming.platform}:`,\n err,\n );\n // Last-ditch: try to post a brief apology so the thread isn't silent.\n try {\n const fallback = adapter.formatAgentResponse(\n \"Something went wrong on my end while replying. Please try again.\",\n );\n await adapter.sendResponse(fallback, incoming);\n } catch {}\n } finally {\n resolve();\n }\n },\n );\n });\n}\n\n/**\n * Persist the user message and agent response to the thread data,\n * so the conversation history is available in the web UI too.\n */\nasync function persistThreadData(\n threadId: string,\n userText: string,\n completedRun: ActiveRun,\n thread: any,\n): Promise<void> {\n try {\n let repo: any;\n try {\n repo = JSON.parse(thread?.threadData || \"{}\");\n } catch {\n repo = {};\n }\n if (!Array.isArray(repo.messages)) repo.messages = [];\n\n // Add user message\n const userMsg = {\n id: `msg-${Date.now()}-user`,\n role: \"user\",\n content: [{ type: \"text\", text: userText }],\n createdAt: new Date().toISOString(),\n };\n\n // Build assistant message from run events\n const assistantMsg = buildAssistantMessage(\n completedRun.events ?? [],\n completedRun.runId,\n );\n\n repo.messages.push(userMsg);\n if (assistantMsg) {\n repo.messages.push(assistantMsg);\n }\n\n const meta = extractThreadMeta(repo);\n await updateThreadData(\n threadId,\n JSON.stringify(repo),\n meta.title || thread?.title || \"Integration Chat\",\n meta.preview || thread?.preview || \"\",\n repo.messages.length,\n );\n } catch {\n // Best-effort persistence\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../src/org/handlers.ts"],"names":[],"mappings":"AA4CA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AA2B1C,2FAA2F;AAC3F,eAAO,MAAM,eAAe;;;;;;;cAaA,OAAO;;;;;;;;;;eAIC,MAAM;iBAAW,MAAM;;;;GAoEzD,CAAC;AAEH,0DAA0D;AAC1D,eAAO,MAAM,gBAAgB;;;;GAkC3B,CAAC;AAEH,wDAAwD;AACxD,eAAO,MAAM,kBAAkB;;;cAWH,OAAO;;;GAIjC,CAAC;AAEH,mEAAmE;AACnE,eAAO,MAAM,uBAAuB;;;;;;GA+EnC,CAAC;AAEF,gFAAgF;AAChF,eAAO,MAAM,sBAAsB;;;;;;;;GAqBlC,CAAC;AAEF,4EAA4E;AAC5E,eAAO,MAAM,uBAA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M,mBAAmB;;GA2D/B,CAAC;AAEF,oFAAoF;AACpF,eAAO,MAAM,gBAAgB;;;GA4B3B,CAAC;AAEH,4EAA4E;AAC5E,eAAO,MAAM,gBAAgB;;;UAkCC,OAAO;GAEnC,CAAC;AAEH,mGAAmG;AACnG,eAAO,MAAM,mBAAmB;;;UAqDR,OAAO;GAG9B,CAAC;AAEF,+FAA+F;AAC/F,eAAO,MAAM,gBAAgB;;GA2C3B,CAAC;AAEH,oGAAoG;AACpG,eAAO,MAAM,mBAAmB;;;GA0C/B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,oBAAoB;;;;;YA2DvB,MAAM;cACJ,MAAM;aACP,MAAM;YACP,OAAO;iBACF,MAAM;gBACP,MAAM;;GAyDnB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,uBAAuB;;;GAgGnC,CAAC"}
@@ -71,22 +71,28 @@ export const getMyOrgHandler = defineEventHandler(async (event) => {
71
71
  orgName: String(r.orgName ?? r.org_name),
72
72
  }));
73
73
  let domainMatches = [];
74
- if (!ctx.orgId) {
75
- const domain = ctx.email.split("@")[1]?.toLowerCase();
76
- if (domain) {
77
- try {
78
- const dmRes = await e.execute({
79
- sql: `SELECT id, name FROM organizations WHERE LOWER(allowed_domain) = ?`,
80
- args: [domain],
81
- });
82
- domainMatches = dmRes.rows.map((r) => ({
83
- orgId: String(r.id),
84
- orgName: String(r.name),
85
- }));
86
- }
87
- catch {
88
- // allowed_domain column may not exist yet if migration hasn't run
89
- }
74
+ const domain = ctx.email.split("@")[1]?.toLowerCase();
75
+ if (domain) {
76
+ try {
77
+ const dmRes = await e.execute({
78
+ sql: `SELECT o.id, o.name
79
+ FROM organizations o
80
+ WHERE LOWER(o.allowed_domain) = ?
81
+ AND NOT EXISTS (
82
+ SELECT 1
83
+ FROM org_members m
84
+ WHERE m.org_id = o.id
85
+ AND LOWER(m.email) = ?
86
+ )`,
87
+ args: [domain, ctx.email.toLowerCase()],
88
+ });
89
+ domainMatches = dmRes.rows.map((r) => ({
90
+ orgId: String(r.id),
91
+ orgName: String(r.name),
92
+ }));
93
+ }
94
+ catch {
95
+ // allowed_domain column may not exist yet if migration hasn't run
90
96
  }
91
97
  }
92
98
  let allowedDomain = null;
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.js","sourceRoot":"","sources":["../../src/org/handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,WAAW,GAEZ,MAAM,IAAI,CAAC;AAEZ;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,KAAc;IACzC,MAAM,UAAU,GAAG,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/C,IAAI,UAAU;QAAE,OAAO,UAAU,CAAC;IAClC,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC;IAC3C,MAAM,KAAK,GACT,IAAI,CAAC,KAAK,CAAC,yBAAyB,CAAC;QACrC,IAAI,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;IACzD,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC/D,CAAC;AAED,iFAAiF;AACjF,SAAS,kBAAkB,CAAC,KAAc;IACxC,MAAM,UAAU,GAAG,cAAc,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAClD,IAAI,UAAU;QAAE,OAAO,UAAU,CAAC;IAClC,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC;IAC3C,MAAM,KAAK,GACT,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAC9E,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,kBAAk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EAAE,UAAU,CAAC;KAC9B,CAAC,CAAC;IAEH,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AACzC,CAAC,CACF,CAAC","sourcesContent":["import {\n defineEventHandler,\n getRouterParam,\n getRequestURL,\n createError,\n type H3Event,\n} from \"h3\";\n\n/**\n * Extract the :id from invitation-accept paths. The framework request handler\n * strips the mount prefix before calling the handler, so `event.url.pathname`\n * is the relative tail — e.g. `/some-id/accept`. Falls back to matching the\n * full path for contexts that don't strip, and to the h3 router param.\n */\nfunction extractInvitationId(event: H3Event): string | undefined {\n const fromRouter = getRouterParam(event, \"id\");\n if (fromRouter) return fromRouter;\n const path = getRequestURL(event).pathname;\n const match =\n path.match(/^\\/([^\\/]+)\\/accept\\/?$/) ??\n path.match(/\\/org\\/invitations\\/([^\\/]+)\\/accept\\/?$/);\n return match?.[1] ? decodeURIComponent(match[1]) : undefined;\n}\n\n/** Extract the :email from member-delete paths. Same prefix-stripping caveat. */\nfunction extractMemberEmail(event: H3Event): string | undefined {\n const fromRouter = getRouterParam(event, \"email\");\n if (fromRouter) return fromRouter;\n const path = getRequestURL(event).pathname;\n const match =\n path.match(/^\\/([^\\/]+)\\/?$/) ?? path.match(/\\/org\\/members\\/([^\\/]+)\\/?$/);\n return match?.[1] ? decodeURIComponent(match[1]) : undefined;\n}\nconst nanoid = (): string =>\n globalThis.crypto?.randomUUID?.().replace(/-/g, \"\") ??\n Math.random().toString(36).slice(2) + Date.now().toString(36);\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { getSession } from \"../server/auth.js\";\nimport { putUserSetting } from \"../settings/user-settings.js\";\nimport { getDbExec } from \"../db/client.js\";\nimport { sendEmail, isEmailConfigured } from \"../server/email.js\";\nimport { renderInviteEmail } from \"../server/email-templates.js\";\nimport { getAppProductionUrl } from \"../server/app-url.js\";\nimport { getOrgContext } from \"./context.js\";\nimport type { OrgRole } from \"./types.js\";\n\nfunction getInviteAppUrl(event: H3Event): string {\n return getAppProductionUrl(event);\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nasync function exec() {\n return getDbExec();\n}\n\nfunction requireAuthEmail(session: { email?: string } | null): string {\n const email = session?.email;\n if (!email) {\n throw createError({ statusCode: 401, message: \"Authentication required\" });\n }\n return email;\n}\n\n/** GET /_agent-native/org/me — current user's active org, all orgs, pending invitations */\nexport const getMyOrgHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n\n const e = await exec();\n const allOrgsRes = await e.execute({\n sql: `SELECT m.org_id AS \"orgId\", m.role AS role, o.name AS \"orgName\"\n FROM org_members m\n INNER JOIN organizations o ON m.org_id = o.id\n WHERE LOWER(m.email) = ?`,\n args: [ctx.email.toLowerCase()],\n });\n const orgs = allOrgsRes.rows.map((r: any) => ({\n orgId: String(r.orgId ?? r.org_id),\n role: String(r.role) as OrgRole,\n orgName: String(r.orgName ?? r.org_name),\n }));\n\n let domainMatches: Array<{ orgId: string; orgName: string }> = [];\n if (!ctx.orgId) {\n const domain = ctx.email.split(\"@\")[1]?.toLowerCase();\n if (domain) {\n try {\n const dmRes = await e.execute({\n sql: `SELECT id, name FROM organizations WHERE LOWER(allowed_domain) = ?`,\n args: [domain],\n });\n domainMatches = dmRes.rows.map((r: any) => ({\n orgId: String(r.id),\n orgName: String(r.name),\n }));\n } catch {\n // allowed_domain column may not exist yet if migration hasn't run\n }\n }\n }\n\n let allowedDomain: string | null = null;\n let a2aSecret: string | null = null;\n if (ctx.orgId) {\n try {\n const adRes = await e.execute({\n sql: `SELECT allowed_domain, a2a_secret FROM organizations WHERE id = ? LIMIT 1`,\n args: [ctx.orgId],\n });\n if (adRes.rows[0]) {\n allowedDomain =\n String((adRes.rows[0] as any).allowed_domain ?? \"\") || null;\n a2aSecret = String((adRes.rows[0] as any).a2a_secret ?? \"\") || null;\n }\n } catch {\n // Column may not exist yet\n }\n }\n\n const isOwnerOrAdmin = ctx.role === \"owner\" || ctx.role === \"admin\";\n\n const invitesRes = await e.execute({\n // Case-insensitive match: invitations are stored with whatever case\n // the inviter typed, but the session email may be normalized\n // differently by the auth provider. LOWER(both sides) keeps these\n // discoverable and matches getOrgContext.hasPendingInvitation.\n sql: `SELECT i.id AS id, i.org_id AS \"orgId\", o.name AS \"orgName\", i.invited_by AS \"invitedBy\"\n FROM org_invitations i\n INNER JOIN organizations o ON i.org_id = o.id\n WHERE LOWER(i.email) = ? AND i.status = 'pending'`,\n args: [ctx.email.toLowerCase()],\n });\n const pendingInvitations = invitesRes.rows.map((r: any) => ({\n id: String(r.id),\n orgId: String(r.orgId ?? r.org_id),\n orgName: String(r.orgName ?? r.org_name),\n invitedBy: String(r.invitedBy ?? r.invited_by),\n }));\n\n return {\n email: ctx.email,\n orgId: ctx.orgId,\n orgName: ctx.orgName,\n role: ctx.role,\n orgs,\n pendingInvitations,\n domainMatches,\n allowedDomain,\n a2aSecret: isOwnerOrAdmin ? a2aSecret : undefined,\n };\n});\n\n/** POST /_agent-native/org — create a new organization */\nexport const createOrgHandler = defineEventHandler(async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const body = await readBody(event);\n const name = body?.name?.trim();\n if (!name) {\n throw createError({\n statusCode: 400,\n message: \"Organization name is required\",\n });\n }\n\n const orgId = nanoid();\n const now = Date.now();\n const e = await exec();\n\n // Auto-generate a per-org A2A secret for cross-app delegation\n const { randomBytes } = await import(\"node:crypto\");\n const a2aSecret = randomBytes(32).toString(\"base64url\");\n\n await e.execute({\n sql: `INSERT INTO organizations (id, name, created_by, created_at, a2a_secret) VALUES (?, ?, ?, ?, ?)`,\n args: [orgId, name, email, now, a2aSecret],\n });\n\n await e.execute({\n sql: `INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, ?, ?)`,\n args: [nanoid(), orgId, email, \"owner\", now],\n });\n\n await putUserSetting(email, \"active-org-id\", { orgId });\n\n return { id: orgId, name, role: \"owner\" };\n});\n\n/** GET /_agent-native/org/members — list org members */\nexport const listMembersHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) return { members: [] };\n\n const e = await exec();\n const { rows } = await e.execute({\n sql: `SELECT email, role, joined_at AS \"joinedAt\" FROM org_members WHERE org_id = ?`,\n args: [ctx.orgId],\n });\n const members = rows.map((r: any) => ({\n email: String(r.email),\n role: String(r.role) as OrgRole,\n joinedAt: Number(r.joinedAt ?? r.joined_at),\n }));\n return { members };\n});\n\n/** POST /_agent-native/org/invitations — invite a user by email */\nexport const createInvitationHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({\n statusCode: 400,\n message: \"You must belong to an organization to invite members\",\n });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can invite members\",\n });\n }\n\n const body = await readBody(event);\n const email = body?.email?.trim()?.toLowerCase();\n if (!email) {\n throw createError({ statusCode: 400, message: \"Email is required\" });\n }\n\n const e = await exec();\n\n // Existing rows in org_members / org_invitations may have any case\n // (writes haven't been normalized historically). Compare with LOWER\n // on both sides so an \"alice@...\" invite check correctly recognizes\n // an existing \"Alice@...\" membership. `email` is already lowercased\n // at parse time above, but call .toLowerCase() explicitly here so\n // the contract at the SQL boundary matches every other handler in\n // this file.\n const existingMember = await e.execute({\n sql: `SELECT 1 FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [ctx.orgId, email.toLowerCase()],\n });\n if (existingMember.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"User is already a member of this organization\",\n });\n }\n\n const existingInvite = await e.execute({\n sql: `SELECT 1 FROM org_invitations WHERE org_id = ? AND LOWER(email) = ? AND status = 'pending' LIMIT 1`,\n args: [ctx.orgId, email.toLowerCase()],\n });\n if (existingInvite.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"An invitation is already pending for this email\",\n });\n }\n\n const id = nanoid();\n await e.execute({\n sql: `INSERT INTO org_invitations (id, org_id, email, invited_by, created_at, status) VALUES (?, ?, ?, ?, ?, 'pending')`,\n args: [id, ctx.orgId, email, ctx.email, Date.now()],\n });\n\n let emailSent = false;\n let emailError: string | undefined;\n if (isEmailConfigured()) {\n try {\n const { subject, html, text } = renderInviteEmail({\n invitee: email,\n orgName: ctx.orgName || \"your team\",\n acceptUrl: getInviteAppUrl(event),\n inviter: ctx.email,\n });\n await sendEmail({ to: email, subject, html, text });\n emailSent = true;\n } catch (err) {\n emailError = err instanceof Error ? err.message : String(err);\n console.error(\"[org/invitations] failed to send invite email\", err);\n }\n }\n\n return { id, email, status: \"pending\", emailSent, emailError };\n },\n);\n\n/** GET /_agent-native/org/invitations — list pending invitations for the org */\nexport const listInvitationsHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) return { invitations: [] };\n\n const e = await exec();\n const { rows } = await e.execute({\n sql: `SELECT id, email, invited_by AS \"invitedBy\", created_at AS \"createdAt\", status\n FROM org_invitations\n WHERE org_id = ? AND status = 'pending'`,\n args: [ctx.orgId],\n });\n const invitations = rows.map((r: any) => ({\n id: String(r.id),\n email: String(r.email),\n invitedBy: String(r.invitedBy ?? r.invited_by),\n createdAt: Number(r.createdAt ?? r.created_at),\n status: String(r.status),\n }));\n return { invitations };\n },\n);\n\n/** POST /_agent-native/org/invitations/:id/accept — accept an invitation */\nexport const acceptInvitationHandler = defineEventHandler(\n async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const invitationId = extractInvitationId(event);\n if (!invitationId) {\n throw createError({\n statusCode: 400,\n message: \"Invitation ID required\",\n });\n }\n\n const e = await exec();\n\n const invRes = await e.execute({\n // Case-insensitive on email — see comment on the analogous\n // pending-invitations query in getMyOrgHandler.\n sql: `SELECT id, org_id AS \"orgId\" FROM org_invitations\n WHERE id = ? AND LOWER(email) = ? AND status = 'pending' LIMIT 1`,\n args: [invitationId, email.toLowerCase()],\n });\n if (invRes.rows.length === 0) {\n throw createError({\n statusCode: 404,\n message: \"Invitation not found or already used\",\n });\n }\n const inv = invRes.rows[0] as any;\n const invOrgId = String(inv.orgId ?? inv.org_id);\n\n const existingMembership = await e.execute({\n sql: `SELECT role FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [invOrgId, email.toLowerCase()],\n });\n\n const orgRes = await e.execute({\n sql: `SELECT name FROM organizations WHERE id = ? LIMIT 1`,\n args: [invOrgId],\n });\n const orgName = String((orgRes.rows[0] as any)?.name ?? \"\");\n\n if (existingMembership.rows.length > 0) {\n await e.execute({\n sql: `UPDATE org_invitations SET status = 'accepted' WHERE id = ?`,\n args: [invitationId],\n });\n await putUserSetting(email, \"active-org-id\", { orgId: invOrgId });\n return {\n orgId: invOrgId,\n orgName,\n role: String((existingMembership.rows[0] as any).role) as OrgRole,\n };\n }\n\n await e.execute({\n sql: `INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, 'member', ?)`,\n args: [nanoid(), invOrgId, email, Date.now()],\n });\n\n await e.execute({\n sql: `UPDATE org_invitations SET status = 'accepted' WHERE id = ?`,\n args: [invitationId],\n });\n\n await putUserSetting(email, \"active-org-id\", { orgId: invOrgId });\n\n return { orgId: invOrgId, orgName, role: \"member\" as OrgRole };\n },\n);\n\n/** DELETE /_agent-native/org/members/:email — remove a member (owner/admin only) */\nexport const removeMemberHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({ statusCode: 400, message: \"No organization found\" });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can remove members\",\n });\n }\n\n const memberEmail = extractMemberEmail(event);\n if (!memberEmail) {\n throw createError({ statusCode: 400, message: \"Email is required\" });\n }\n\n // memberEmail comes from the URL path verbatim; org_members may\n // hold the row with any case. LOWER both sides for the lookup AND\n // the DELETE so removal works regardless of how either side cased\n // it. The self-removal guard ALSO compares case-insensitively —\n // otherwise an owner whose email was stored as Alice@... could\n // remove themselves via the lowercase URL alice@..., bypassing the\n // guard and leaving the org ownerless.\n const memberEmailLower = memberEmail.toLowerCase();\n if (memberEmailLower === ctx.email.toLowerCase() && ctx.role === \"owner\") {\n throw createError({\n statusCode: 400,\n message: \"Organization owner cannot remove themselves\",\n });\n }\n const e = await exec();\n // Look specifically for an OWNER row matching this email rather\n // than just \"any matching row\". Duplicate-case rows are possible\n // (e.g. legacy data with both \"Alice@...\" and \"alice@...\" in\n // org_members), and the prior `SELECT role ... LIMIT 1` could\n // return the non-owner duplicate, pass the role check, and then\n // the case-insensitive DELETE below would remove BOTH rows —\n // including the owner — leaving the org ownerless. Querying for\n // the owner row directly closes that case-mismatch attack.\n const ownerCheck = await e.execute({\n sql: `SELECT 1 FROM org_members WHERE org_id = ? AND LOWER(email) = ? AND role = 'owner' LIMIT 1`,\n args: [ctx.orgId, memberEmailLower],\n });\n if (ownerCheck.rows.length > 0) {\n throw createError({\n statusCode: 403,\n message: \"Cannot remove the organization owner\",\n });\n }\n\n await e.execute({\n sql: `DELETE FROM org_members WHERE org_id = ? AND LOWER(email) = ?`,\n args: [ctx.orgId, memberEmailLower],\n });\n\n return { success: true };\n },\n);\n\n/** PATCH /_agent-native/org — rename the current organization (owner/admin only) */\nexport const updateOrgHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({ statusCode: 400, message: \"No organization found\" });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can update the organization\",\n });\n }\n\n const body = await readBody(event);\n const name = body?.name?.trim();\n if (!name) {\n throw createError({\n statusCode: 400,\n message: \"Organization name is required\",\n });\n }\n\n const e = await exec();\n await e.execute({\n sql: `UPDATE organizations SET name = ? WHERE id = ?`,\n args: [name, ctx.orgId],\n });\n\n return { orgId: ctx.orgId, name };\n});\n\n/** PUT /_agent-native/org/switch — switch the user's active organization */\nexport const switchOrgHandler = defineEventHandler(async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const body = await readBody(event);\n const orgId = body?.orgId;\n\n if (!orgId) {\n await putUserSetting(email, \"active-org-id\", { orgId: null });\n return { orgId: null, orgName: null, role: null };\n }\n\n const e = await exec();\n const membership = await e.execute({\n sql: `SELECT m.role AS role, o.name AS \"orgName\"\n FROM org_members m\n INNER JOIN organizations o ON m.org_id = o.id\n WHERE m.org_id = ? AND LOWER(m.email) = ? LIMIT 1`,\n args: [orgId, email.toLowerCase()],\n });\n\n if (membership.rows.length === 0) {\n throw createError({\n statusCode: 403,\n message: \"You are not a member of that organization\",\n });\n }\n\n await putUserSetting(email, \"active-org-id\", { orgId });\n\n const row = membership.rows[0] as any;\n return {\n orgId,\n orgName: String(row.orgName ?? row.org_name),\n role: String(row.role) as OrgRole,\n };\n});\n\n/** POST /_agent-native/org/join-by-domain — join an org whose allowed_domain matches your email */\nexport const joinByDomainHandler = defineEventHandler(\n async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const body = await readBody(event);\n const orgId = body?.orgId;\n if (!orgId) {\n throw createError({ statusCode: 400, message: \"orgId is required\" });\n }\n\n const e = await exec();\n\n const orgRes = await e.execute({\n sql: `SELECT id, name, allowed_domain FROM organizations WHERE id = ? LIMIT 1`,\n args: [orgId],\n });\n if (orgRes.rows.length === 0) {\n throw createError({ statusCode: 404, message: \"Organization not found\" });\n }\n const org = orgRes.rows[0] as any;\n const allowedDomain = String(org.allowed_domain || \"\").toLowerCase();\n const userDomain = email.split(\"@\")[1]?.toLowerCase();\n\n if (!allowedDomain || allowedDomain !== userDomain) {\n throw createError({\n statusCode: 403,\n message:\n \"Your email domain does not match this organization's allowed domain\",\n });\n }\n\n const existing = await e.execute({\n sql: `SELECT 1 FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [orgId, email.toLowerCase()],\n });\n if (existing.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"Already a member of this organization\",\n });\n }\n\n await e.execute({\n sql: `INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, 'member', ?)`,\n args: [nanoid(), orgId, email, Date.now()],\n });\n\n await putUserSetting(email, \"active-org-id\", { orgId });\n\n return {\n orgId,\n orgName: String(org.name),\n role: \"member\" as OrgRole,\n };\n },\n);\n\n/** PUT /_agent-native/org/domain — set or clear the allowed email domain (owner/admin only) */\nexport const setDomainHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({ statusCode: 400, message: \"No active organization\" });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can set the allowed domain\",\n });\n }\n\n const body = await readBody(event);\n const raw = body?.domain?.trim()?.toLowerCase() || null;\n\n if (raw && !/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\\.)+[a-z]{2,}$/.test(raw)) {\n throw createError({\n statusCode: 400,\n message: \"Invalid domain format\",\n });\n }\n\n const e = await exec();\n\n if (raw) {\n const existing = await e.execute({\n sql: `SELECT id FROM organizations WHERE LOWER(allowed_domain) = ? AND id != ? LIMIT 1`,\n args: [raw, ctx.orgId],\n });\n if (existing.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"Another organization already uses this domain\",\n });\n }\n }\n\n await e.execute({\n sql: `UPDATE organizations SET allowed_domain = ? WHERE id = ?`,\n args: [raw, ctx.orgId],\n });\n\n return { domain: raw };\n});\n\n/** PUT /_agent-native/org/a2a-secret — regenerate or set the org's A2A secret (owner/admin only) */\nexport const setA2ASecretHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({\n statusCode: 400,\n message: \"No active organization\",\n });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can manage the A2A secret\",\n });\n }\n\n const body = await readBody(event);\n let secret = body?.secret?.trim() || null;\n\n // If no secret provided, auto-generate one\n if (!secret) {\n const { randomBytes } = await import(\"node:crypto\");\n secret = randomBytes(32).toString(\"base64url\");\n }\n\n const e = await exec();\n // Read the previous secret BEFORE overwriting so the client can chain a\n // sync call that signs JWTs with the secret peers still hold.\n const prevRes = await e.execute({\n sql: `SELECT a2a_secret FROM organizations WHERE id = ? LIMIT 1`,\n args: [ctx.orgId],\n });\n const previousSecret =\n String((prevRes.rows[0] as any)?.a2a_secret ?? \"\") || null;\n\n await e.execute({\n sql: `UPDATE organizations SET a2a_secret = ? WHERE id = ?`,\n args: [secret, ctx.orgId],\n });\n\n return { a2aSecret: secret, previousSecret };\n },\n);\n\n/**\n * POST /_agent-native/org/a2a-secret/sync — push the org's A2A secret to all\n * connected apps so cross-app delegation works without manual copy/paste.\n *\n * Auth: standard session — owner/admin only.\n *\n * For each discovered agent, signs a JWT with the org's CURRENT a2a_secret\n * and POSTs to `<app>/_agent-native/org/a2a-secret/receive` with the same\n * secret + the org's domain. The receiving app verifies the JWT using its\n * own copy of the secret (peers must already share a secret to be trusted)\n * — for the first-ever sync this means at least one peer must already hold\n * the secret, which is the bootstrap. For ongoing rotation, regenerate\n * locally and call sync immediately; sync signs with the secret that's\n * currently in DB, which the peers still have.\n *\n * Body (optional): { signSecret?: string } — sign the outbound JWTs with\n * this secret instead of the org's current secret. Used by the regenerate-\n * then-sync flow: regenerate stores the NEW secret, but sync needs to\n * authenticate using the OLD one that peers still hold. Owner/admin only,\n * gated by the session.\n */\nexport const syncA2ASecretHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({\n statusCode: 400,\n message: \"No active organization\",\n });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can sync the A2A secret\",\n });\n }\n\n const body = await readBody(event).catch(() => null);\n const overrideSignSecret =\n typeof body?.signSecret === \"string\" && body.signSecret.trim()\n ? body.signSecret.trim()\n : null;\n\n const e = await exec();\n const orgRes = await e.execute({\n sql: `SELECT a2a_secret, allowed_domain FROM organizations WHERE id = ? LIMIT 1`,\n args: [ctx.orgId],\n });\n if (orgRes.rows.length === 0) {\n throw createError({\n statusCode: 404,\n message: \"Organization not found\",\n });\n }\n const orgRow = orgRes.rows[0] as any;\n const secret = String(orgRow.a2a_secret ?? \"\") || null;\n const orgDomain = String(orgRow.allowed_domain ?? \"\") || null;\n\n if (!secret) {\n throw createError({\n statusCode: 400,\n message: \"Org has no A2A secret. Generate one first before syncing.\",\n });\n }\n if (!orgDomain) {\n throw createError({\n statusCode: 400,\n message:\n \"Org has no allowed domain set. Set the email domain first so connected apps can identify which org to update.\",\n });\n }\n\n const signSecret = overrideSignSecret || secret;\n\n const { discoverAgents } = await import(\"../server/agent-discovery.js\");\n const { signA2AToken } = await import(\"../a2a/client.js\");\n\n const agents = await discoverAgents();\n\n const results: Array<{\n id: string;\n name: string;\n url: string;\n ok: boolean;\n status?: number;\n error?: string;\n }> = [];\n\n await Promise.all(\n agents.map(async (agent) => {\n try {\n const token = await signA2AToken(ctx.email, orgDomain, signSecret);\n\n const target = `${agent.url.replace(/\\/$/, \"\")}/_agent-native/org/a2a-secret/receive`;\n const res = await fetch(target, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({ secret, orgDomain }),\n });\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n results.push({\n id: agent.id,\n name: agent.name,\n url: agent.url,\n ok: false,\n status: res.status,\n error: text || res.statusText,\n });\n return;\n }\n results.push({\n id: agent.id,\n name: agent.name,\n url: agent.url,\n ok: true,\n status: res.status,\n });\n } catch (err) {\n results.push({\n id: agent.id,\n name: agent.name,\n url: agent.url,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }),\n );\n\n const succeeded = results.filter((r) => r.ok).length;\n return {\n total: results.length,\n succeeded,\n failed: results.length - succeeded,\n results,\n };\n },\n);\n\n/**\n * POST /_agent-native/org/a2a-secret/receive — accept a secret push from a\n * connected agent-native app. Auth-exempt at the route guard; we verify a\n * JWT signed by the calling app using OUR copy of the org's a2a_secret. If\n * verification succeeds the calling app is a trusted peer and we overwrite\n * our local org's secret with the supplied value.\n *\n * Body: { secret: string, orgDomain: string }\n *\n * Header: Authorization: Bearer <JWT signed with the existing shared\n * a2a_secret, with `org_domain` matching the body's orgDomain>.\n */\nexport const receiveA2ASecretHandler = defineEventHandler(\n async (event: H3Event) => {\n const { getRequestHeader } = await import(\"h3\");\n const jose = await import(\"jose\");\n\n const authHeader = getRequestHeader(event, \"authorization\");\n if (!authHeader || !authHeader.startsWith(\"Bearer \")) {\n throw createError({\n statusCode: 401,\n message: \"Bearer token required\",\n });\n }\n const token = authHeader.slice(\"Bearer \".length);\n\n const body = await readBody(event);\n const newSecret =\n typeof body?.secret === \"string\" ? body.secret.trim() : \"\";\n const orgDomain =\n typeof body?.orgDomain === \"string\"\n ? body.orgDomain.trim().toLowerCase()\n : \"\";\n if (!newSecret || !orgDomain) {\n throw createError({\n statusCode: 400,\n message: \"secret and orgDomain are required\",\n });\n }\n\n // Peek at JWT (unverified) to confirm it claims the same domain we're\n // updating. Verification still happens below with the trusted secret.\n let claimedDomain: string | undefined;\n try {\n const unverified = jose.decodeJwt(token);\n claimedDomain =\n (unverified.org_domain as string | undefined) || undefined;\n } catch {\n throw createError({\n statusCode: 401,\n message: \"Malformed JWT\",\n });\n }\n if (\n !claimedDomain ||\n claimedDomain.toLowerCase() !== orgDomain.toLowerCase()\n ) {\n throw createError({\n statusCode: 401,\n message: \"JWT org_domain does not match request body\",\n });\n }\n\n // Look up our local org by the domain and grab the existing secret.\n const e = await exec();\n const orgRes = await e.execute({\n sql: `SELECT id, a2a_secret FROM organizations WHERE LOWER(allowed_domain) = ? LIMIT 1`,\n args: [orgDomain],\n });\n if (orgRes.rows.length === 0) {\n throw createError({\n statusCode: 404,\n message: \"No local org matches that domain\",\n });\n }\n const row = orgRes.rows[0] as any;\n const localOrgId = String(row.id);\n const existingSecret = String(row.a2a_secret ?? \"\") || null;\n\n if (!existingSecret) {\n // Bootstrap requires an existing shared secret to verify the caller.\n // If we have nothing on file, we can't verify trust — refuse.\n throw createError({\n statusCode: 401,\n message:\n \"Local org has no A2A secret yet — cannot verify caller. Set the secret manually for the first time.\",\n });\n }\n\n // Verify the JWT using OUR existing secret. If the caller is a trusted\n // peer they signed with the same secret and verification succeeds.\n try {\n await jose.jwtVerify(token, new TextEncoder().encode(existingSecret));\n } catch {\n throw createError({\n statusCode: 401,\n message: \"Invalid or expired JWT signature\",\n });\n }\n\n // Trusted — apply the new secret.\n await e.execute({\n sql: `UPDATE organizations SET a2a_secret = ? WHERE id = ?`,\n args: [newSecret, localOrgId],\n });\n\n return { ok: true, orgId: localOrgId };\n },\n);\n"]}
1
+ {"version":3,"file":"handlers.js","sourceRoot":"","sources":["../../src/org/handlers.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,WAAW,GAEZ,MAAM,IAAI,CAAC;AAEZ;;;;;GAKG;AACH,SAAS,mBAAmB,CAAC,KAAc;IACzC,MAAM,UAAU,GAAG,cAAc,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC/C,IAAI,UAAU;QAAE,OAAO,UAAU,CAAC;IAClC,MAAM,IAAI,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC,QAAQ,CAAC;IAC3C,MAAM,KAAK,GACT,IAAI,CAAC,KAAK,CAAC,yBAAyB,CAAC;QACrC,IAAI,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAC;IACzD,OAAO,KAAK,EAAE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AqE;QACrE,8DAA8D;QAC9D,MAAM,WAAW,CAAC;YAChB,UAAU,EAAE,GAAG;YACf,OAAO,EACL,qGAAqG;SACxG,CAAC,CAAC;IACL,CAAC;IAED,uEAAuE;IACvE,mEAAmE;IACnE,IAAI,CAAC;QACH,MAAM,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC;IACxE,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,WAAW,CAAC;YAChB,UAAU,EAAE,GAAG;YACf,OAAO,EAAE,kCAAkC;SAC5C,CAAC,CAAC;IACL,CAAC;IAED,kCAAkC;IAClC,MAAM,CAAC,CAAC,OAAO,CAAC;QACd,GAAG,EAAE,sDAAsD;QAC3D,IAAI,EAAE,CAAC,SAAS,EAAE,UAAU,CAAC;KAC9B,CAAC,CAAC;IAEH,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC;AACzC,CAAC,CACF,CAAC","sourcesContent":["import {\n defineEventHandler,\n getRouterParam,\n getRequestURL,\n createError,\n type H3Event,\n} from \"h3\";\n\n/**\n * Extract the :id from invitation-accept paths. The framework request handler\n * strips the mount prefix before calling the handler, so `event.url.pathname`\n * is the relative tail — e.g. `/some-id/accept`. Falls back to matching the\n * full path for contexts that don't strip, and to the h3 router param.\n */\nfunction extractInvitationId(event: H3Event): string | undefined {\n const fromRouter = getRouterParam(event, \"id\");\n if (fromRouter) return fromRouter;\n const path = getRequestURL(event).pathname;\n const match =\n path.match(/^\\/([^\\/]+)\\/accept\\/?$/) ??\n path.match(/\\/org\\/invitations\\/([^\\/]+)\\/accept\\/?$/);\n return match?.[1] ? decodeURIComponent(match[1]) : undefined;\n}\n\n/** Extract the :email from member-delete paths. Same prefix-stripping caveat. */\nfunction extractMemberEmail(event: H3Event): string | undefined {\n const fromRouter = getRouterParam(event, \"email\");\n if (fromRouter) return fromRouter;\n const path = getRequestURL(event).pathname;\n const match =\n path.match(/^\\/([^\\/]+)\\/?$/) ?? path.match(/\\/org\\/members\\/([^\\/]+)\\/?$/);\n return match?.[1] ? decodeURIComponent(match[1]) : undefined;\n}\nconst nanoid = (): string =>\n globalThis.crypto?.randomUUID?.().replace(/-/g, \"\") ??\n Math.random().toString(36).slice(2) + Date.now().toString(36);\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { getSession } from \"../server/auth.js\";\nimport { putUserSetting } from \"../settings/user-settings.js\";\nimport { getDbExec } from \"../db/client.js\";\nimport { sendEmail, isEmailConfigured } from \"../server/email.js\";\nimport { renderInviteEmail } from \"../server/email-templates.js\";\nimport { getAppProductionUrl } from \"../server/app-url.js\";\nimport { getOrgContext } from \"./context.js\";\nimport type { OrgRole } from \"./types.js\";\n\nfunction getInviteAppUrl(event: H3Event): string {\n return getAppProductionUrl(event);\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nasync function exec() {\n return getDbExec();\n}\n\nfunction requireAuthEmail(session: { email?: string } | null): string {\n const email = session?.email;\n if (!email) {\n throw createError({ statusCode: 401, message: \"Authentication required\" });\n }\n return email;\n}\n\n/** GET /_agent-native/org/me — current user's active org, all orgs, pending invitations */\nexport const getMyOrgHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n\n const e = await exec();\n const allOrgsRes = await e.execute({\n sql: `SELECT m.org_id AS \"orgId\", m.role AS role, o.name AS \"orgName\"\n FROM org_members m\n INNER JOIN organizations o ON m.org_id = o.id\n WHERE LOWER(m.email) = ?`,\n args: [ctx.email.toLowerCase()],\n });\n const orgs = allOrgsRes.rows.map((r: any) => ({\n orgId: String(r.orgId ?? r.org_id),\n role: String(r.role) as OrgRole,\n orgName: String(r.orgName ?? r.org_name),\n }));\n\n let domainMatches: Array<{ orgId: string; orgName: string }> = [];\n const domain = ctx.email.split(\"@\")[1]?.toLowerCase();\n if (domain) {\n try {\n const dmRes = await e.execute({\n sql: `SELECT o.id, o.name\n FROM organizations o\n WHERE LOWER(o.allowed_domain) = ?\n AND NOT EXISTS (\n SELECT 1\n FROM org_members m\n WHERE m.org_id = o.id\n AND LOWER(m.email) = ?\n )`,\n args: [domain, ctx.email.toLowerCase()],\n });\n domainMatches = dmRes.rows.map((r: any) => ({\n orgId: String(r.id),\n orgName: String(r.name),\n }));\n } catch {\n // allowed_domain column may not exist yet if migration hasn't run\n }\n }\n\n let allowedDomain: string | null = null;\n let a2aSecret: string | null = null;\n if (ctx.orgId) {\n try {\n const adRes = await e.execute({\n sql: `SELECT allowed_domain, a2a_secret FROM organizations WHERE id = ? LIMIT 1`,\n args: [ctx.orgId],\n });\n if (adRes.rows[0]) {\n allowedDomain =\n String((adRes.rows[0] as any).allowed_domain ?? \"\") || null;\n a2aSecret = String((adRes.rows[0] as any).a2a_secret ?? \"\") || null;\n }\n } catch {\n // Column may not exist yet\n }\n }\n\n const isOwnerOrAdmin = ctx.role === \"owner\" || ctx.role === \"admin\";\n\n const invitesRes = await e.execute({\n // Case-insensitive match: invitations are stored with whatever case\n // the inviter typed, but the session email may be normalized\n // differently by the auth provider. LOWER(both sides) keeps these\n // discoverable and matches getOrgContext.hasPendingInvitation.\n sql: `SELECT i.id AS id, i.org_id AS \"orgId\", o.name AS \"orgName\", i.invited_by AS \"invitedBy\"\n FROM org_invitations i\n INNER JOIN organizations o ON i.org_id = o.id\n WHERE LOWER(i.email) = ? AND i.status = 'pending'`,\n args: [ctx.email.toLowerCase()],\n });\n const pendingInvitations = invitesRes.rows.map((r: any) => ({\n id: String(r.id),\n orgId: String(r.orgId ?? r.org_id),\n orgName: String(r.orgName ?? r.org_name),\n invitedBy: String(r.invitedBy ?? r.invited_by),\n }));\n\n return {\n email: ctx.email,\n orgId: ctx.orgId,\n orgName: ctx.orgName,\n role: ctx.role,\n orgs,\n pendingInvitations,\n domainMatches,\n allowedDomain,\n a2aSecret: isOwnerOrAdmin ? a2aSecret : undefined,\n };\n});\n\n/** POST /_agent-native/org — create a new organization */\nexport const createOrgHandler = defineEventHandler(async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const body = await readBody(event);\n const name = body?.name?.trim();\n if (!name) {\n throw createError({\n statusCode: 400,\n message: \"Organization name is required\",\n });\n }\n\n const orgId = nanoid();\n const now = Date.now();\n const e = await exec();\n\n // Auto-generate a per-org A2A secret for cross-app delegation\n const { randomBytes } = await import(\"node:crypto\");\n const a2aSecret = randomBytes(32).toString(\"base64url\");\n\n await e.execute({\n sql: `INSERT INTO organizations (id, name, created_by, created_at, a2a_secret) VALUES (?, ?, ?, ?, ?)`,\n args: [orgId, name, email, now, a2aSecret],\n });\n\n await e.execute({\n sql: `INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, ?, ?)`,\n args: [nanoid(), orgId, email, \"owner\", now],\n });\n\n await putUserSetting(email, \"active-org-id\", { orgId });\n\n return { id: orgId, name, role: \"owner\" };\n});\n\n/** GET /_agent-native/org/members — list org members */\nexport const listMembersHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) return { members: [] };\n\n const e = await exec();\n const { rows } = await e.execute({\n sql: `SELECT email, role, joined_at AS \"joinedAt\" FROM org_members WHERE org_id = ?`,\n args: [ctx.orgId],\n });\n const members = rows.map((r: any) => ({\n email: String(r.email),\n role: String(r.role) as OrgRole,\n joinedAt: Number(r.joinedAt ?? r.joined_at),\n }));\n return { members };\n});\n\n/** POST /_agent-native/org/invitations — invite a user by email */\nexport const createInvitationHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({\n statusCode: 400,\n message: \"You must belong to an organization to invite members\",\n });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can invite members\",\n });\n }\n\n const body = await readBody(event);\n const email = body?.email?.trim()?.toLowerCase();\n if (!email) {\n throw createError({ statusCode: 400, message: \"Email is required\" });\n }\n\n const e = await exec();\n\n // Existing rows in org_members / org_invitations may have any case\n // (writes haven't been normalized historically). Compare with LOWER\n // on both sides so an \"alice@...\" invite check correctly recognizes\n // an existing \"Alice@...\" membership. `email` is already lowercased\n // at parse time above, but call .toLowerCase() explicitly here so\n // the contract at the SQL boundary matches every other handler in\n // this file.\n const existingMember = await e.execute({\n sql: `SELECT 1 FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [ctx.orgId, email.toLowerCase()],\n });\n if (existingMember.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"User is already a member of this organization\",\n });\n }\n\n const existingInvite = await e.execute({\n sql: `SELECT 1 FROM org_invitations WHERE org_id = ? AND LOWER(email) = ? AND status = 'pending' LIMIT 1`,\n args: [ctx.orgId, email.toLowerCase()],\n });\n if (existingInvite.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"An invitation is already pending for this email\",\n });\n }\n\n const id = nanoid();\n await e.execute({\n sql: `INSERT INTO org_invitations (id, org_id, email, invited_by, created_at, status) VALUES (?, ?, ?, ?, ?, 'pending')`,\n args: [id, ctx.orgId, email, ctx.email, Date.now()],\n });\n\n let emailSent = false;\n let emailError: string | undefined;\n if (isEmailConfigured()) {\n try {\n const { subject, html, text } = renderInviteEmail({\n invitee: email,\n orgName: ctx.orgName || \"your team\",\n acceptUrl: getInviteAppUrl(event),\n inviter: ctx.email,\n });\n await sendEmail({ to: email, subject, html, text });\n emailSent = true;\n } catch (err) {\n emailError = err instanceof Error ? err.message : String(err);\n console.error(\"[org/invitations] failed to send invite email\", err);\n }\n }\n\n return { id, email, status: \"pending\", emailSent, emailError };\n },\n);\n\n/** GET /_agent-native/org/invitations — list pending invitations for the org */\nexport const listInvitationsHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) return { invitations: [] };\n\n const e = await exec();\n const { rows } = await e.execute({\n sql: `SELECT id, email, invited_by AS \"invitedBy\", created_at AS \"createdAt\", status\n FROM org_invitations\n WHERE org_id = ? AND status = 'pending'`,\n args: [ctx.orgId],\n });\n const invitations = rows.map((r: any) => ({\n id: String(r.id),\n email: String(r.email),\n invitedBy: String(r.invitedBy ?? r.invited_by),\n createdAt: Number(r.createdAt ?? r.created_at),\n status: String(r.status),\n }));\n return { invitations };\n },\n);\n\n/** POST /_agent-native/org/invitations/:id/accept — accept an invitation */\nexport const acceptInvitationHandler = defineEventHandler(\n async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const invitationId = extractInvitationId(event);\n if (!invitationId) {\n throw createError({\n statusCode: 400,\n message: \"Invitation ID required\",\n });\n }\n\n const e = await exec();\n\n const invRes = await e.execute({\n // Case-insensitive on email — see comment on the analogous\n // pending-invitations query in getMyOrgHandler.\n sql: `SELECT id, org_id AS \"orgId\" FROM org_invitations\n WHERE id = ? AND LOWER(email) = ? AND status = 'pending' LIMIT 1`,\n args: [invitationId, email.toLowerCase()],\n });\n if (invRes.rows.length === 0) {\n throw createError({\n statusCode: 404,\n message: \"Invitation not found or already used\",\n });\n }\n const inv = invRes.rows[0] as any;\n const invOrgId = String(inv.orgId ?? inv.org_id);\n\n const existingMembership = await e.execute({\n sql: `SELECT role FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [invOrgId, email.toLowerCase()],\n });\n\n const orgRes = await e.execute({\n sql: `SELECT name FROM organizations WHERE id = ? LIMIT 1`,\n args: [invOrgId],\n });\n const orgName = String((orgRes.rows[0] as any)?.name ?? \"\");\n\n if (existingMembership.rows.length > 0) {\n await e.execute({\n sql: `UPDATE org_invitations SET status = 'accepted' WHERE id = ?`,\n args: [invitationId],\n });\n await putUserSetting(email, \"active-org-id\", { orgId: invOrgId });\n return {\n orgId: invOrgId,\n orgName,\n role: String((existingMembership.rows[0] as any).role) as OrgRole,\n };\n }\n\n await e.execute({\n sql: `INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, 'member', ?)`,\n args: [nanoid(), invOrgId, email, Date.now()],\n });\n\n await e.execute({\n sql: `UPDATE org_invitations SET status = 'accepted' WHERE id = ?`,\n args: [invitationId],\n });\n\n await putUserSetting(email, \"active-org-id\", { orgId: invOrgId });\n\n return { orgId: invOrgId, orgName, role: \"member\" as OrgRole };\n },\n);\n\n/** DELETE /_agent-native/org/members/:email — remove a member (owner/admin only) */\nexport const removeMemberHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({ statusCode: 400, message: \"No organization found\" });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can remove members\",\n });\n }\n\n const memberEmail = extractMemberEmail(event);\n if (!memberEmail) {\n throw createError({ statusCode: 400, message: \"Email is required\" });\n }\n\n // memberEmail comes from the URL path verbatim; org_members may\n // hold the row with any case. LOWER both sides for the lookup AND\n // the DELETE so removal works regardless of how either side cased\n // it. The self-removal guard ALSO compares case-insensitively —\n // otherwise an owner whose email was stored as Alice@... could\n // remove themselves via the lowercase URL alice@..., bypassing the\n // guard and leaving the org ownerless.\n const memberEmailLower = memberEmail.toLowerCase();\n if (memberEmailLower === ctx.email.toLowerCase() && ctx.role === \"owner\") {\n throw createError({\n statusCode: 400,\n message: \"Organization owner cannot remove themselves\",\n });\n }\n const e = await exec();\n // Look specifically for an OWNER row matching this email rather\n // than just \"any matching row\". Duplicate-case rows are possible\n // (e.g. legacy data with both \"Alice@...\" and \"alice@...\" in\n // org_members), and the prior `SELECT role ... LIMIT 1` could\n // return the non-owner duplicate, pass the role check, and then\n // the case-insensitive DELETE below would remove BOTH rows —\n // including the owner — leaving the org ownerless. Querying for\n // the owner row directly closes that case-mismatch attack.\n const ownerCheck = await e.execute({\n sql: `SELECT 1 FROM org_members WHERE org_id = ? AND LOWER(email) = ? AND role = 'owner' LIMIT 1`,\n args: [ctx.orgId, memberEmailLower],\n });\n if (ownerCheck.rows.length > 0) {\n throw createError({\n statusCode: 403,\n message: \"Cannot remove the organization owner\",\n });\n }\n\n await e.execute({\n sql: `DELETE FROM org_members WHERE org_id = ? AND LOWER(email) = ?`,\n args: [ctx.orgId, memberEmailLower],\n });\n\n return { success: true };\n },\n);\n\n/** PATCH /_agent-native/org — rename the current organization (owner/admin only) */\nexport const updateOrgHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({ statusCode: 400, message: \"No organization found\" });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can update the organization\",\n });\n }\n\n const body = await readBody(event);\n const name = body?.name?.trim();\n if (!name) {\n throw createError({\n statusCode: 400,\n message: \"Organization name is required\",\n });\n }\n\n const e = await exec();\n await e.execute({\n sql: `UPDATE organizations SET name = ? WHERE id = ?`,\n args: [name, ctx.orgId],\n });\n\n return { orgId: ctx.orgId, name };\n});\n\n/** PUT /_agent-native/org/switch — switch the user's active organization */\nexport const switchOrgHandler = defineEventHandler(async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const body = await readBody(event);\n const orgId = body?.orgId;\n\n if (!orgId) {\n await putUserSetting(email, \"active-org-id\", { orgId: null });\n return { orgId: null, orgName: null, role: null };\n }\n\n const e = await exec();\n const membership = await e.execute({\n sql: `SELECT m.role AS role, o.name AS \"orgName\"\n FROM org_members m\n INNER JOIN organizations o ON m.org_id = o.id\n WHERE m.org_id = ? AND LOWER(m.email) = ? LIMIT 1`,\n args: [orgId, email.toLowerCase()],\n });\n\n if (membership.rows.length === 0) {\n throw createError({\n statusCode: 403,\n message: \"You are not a member of that organization\",\n });\n }\n\n await putUserSetting(email, \"active-org-id\", { orgId });\n\n const row = membership.rows[0] as any;\n return {\n orgId,\n orgName: String(row.orgName ?? row.org_name),\n role: String(row.role) as OrgRole,\n };\n});\n\n/** POST /_agent-native/org/join-by-domain — join an org whose allowed_domain matches your email */\nexport const joinByDomainHandler = defineEventHandler(\n async (event: H3Event) => {\n const session = await getSession(event);\n const email = requireAuthEmail(session);\n\n const body = await readBody(event);\n const orgId = body?.orgId;\n if (!orgId) {\n throw createError({ statusCode: 400, message: \"orgId is required\" });\n }\n\n const e = await exec();\n\n const orgRes = await e.execute({\n sql: `SELECT id, name, allowed_domain FROM organizations WHERE id = ? LIMIT 1`,\n args: [orgId],\n });\n if (orgRes.rows.length === 0) {\n throw createError({ statusCode: 404, message: \"Organization not found\" });\n }\n const org = orgRes.rows[0] as any;\n const allowedDomain = String(org.allowed_domain || \"\").toLowerCase();\n const userDomain = email.split(\"@\")[1]?.toLowerCase();\n\n if (!allowedDomain || allowedDomain !== userDomain) {\n throw createError({\n statusCode: 403,\n message:\n \"Your email domain does not match this organization's allowed domain\",\n });\n }\n\n const existing = await e.execute({\n sql: `SELECT 1 FROM org_members WHERE org_id = ? AND LOWER(email) = ? LIMIT 1`,\n args: [orgId, email.toLowerCase()],\n });\n if (existing.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"Already a member of this organization\",\n });\n }\n\n await e.execute({\n sql: `INSERT INTO org_members (id, org_id, email, role, joined_at) VALUES (?, ?, ?, 'member', ?)`,\n args: [nanoid(), orgId, email, Date.now()],\n });\n\n await putUserSetting(email, \"active-org-id\", { orgId });\n\n return {\n orgId,\n orgName: String(org.name),\n role: \"member\" as OrgRole,\n };\n },\n);\n\n/** PUT /_agent-native/org/domain — set or clear the allowed email domain (owner/admin only) */\nexport const setDomainHandler = defineEventHandler(async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({ statusCode: 400, message: \"No active organization\" });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can set the allowed domain\",\n });\n }\n\n const body = await readBody(event);\n const raw = body?.domain?.trim()?.toLowerCase() || null;\n\n if (raw && !/^([a-z0-9]([a-z0-9-]*[a-z0-9])?\\.)+[a-z]{2,}$/.test(raw)) {\n throw createError({\n statusCode: 400,\n message: \"Invalid domain format\",\n });\n }\n\n const e = await exec();\n\n if (raw) {\n const existing = await e.execute({\n sql: `SELECT id FROM organizations WHERE LOWER(allowed_domain) = ? AND id != ? LIMIT 1`,\n args: [raw, ctx.orgId],\n });\n if (existing.rows.length > 0) {\n throw createError({\n statusCode: 409,\n message: \"Another organization already uses this domain\",\n });\n }\n }\n\n await e.execute({\n sql: `UPDATE organizations SET allowed_domain = ? WHERE id = ?`,\n args: [raw, ctx.orgId],\n });\n\n return { domain: raw };\n});\n\n/** PUT /_agent-native/org/a2a-secret — regenerate or set the org's A2A secret (owner/admin only) */\nexport const setA2ASecretHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({\n statusCode: 400,\n message: \"No active organization\",\n });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can manage the A2A secret\",\n });\n }\n\n const body = await readBody(event);\n let secret = body?.secret?.trim() || null;\n\n // If no secret provided, auto-generate one\n if (!secret) {\n const { randomBytes } = await import(\"node:crypto\");\n secret = randomBytes(32).toString(\"base64url\");\n }\n\n const e = await exec();\n // Read the previous secret BEFORE overwriting so the client can chain a\n // sync call that signs JWTs with the secret peers still hold.\n const prevRes = await e.execute({\n sql: `SELECT a2a_secret FROM organizations WHERE id = ? LIMIT 1`,\n args: [ctx.orgId],\n });\n const previousSecret =\n String((prevRes.rows[0] as any)?.a2a_secret ?? \"\") || null;\n\n await e.execute({\n sql: `UPDATE organizations SET a2a_secret = ? WHERE id = ?`,\n args: [secret, ctx.orgId],\n });\n\n return { a2aSecret: secret, previousSecret };\n },\n);\n\n/**\n * POST /_agent-native/org/a2a-secret/sync — push the org's A2A secret to all\n * connected apps so cross-app delegation works without manual copy/paste.\n *\n * Auth: standard session — owner/admin only.\n *\n * For each discovered agent, signs a JWT with the org's CURRENT a2a_secret\n * and POSTs to `<app>/_agent-native/org/a2a-secret/receive` with the same\n * secret + the org's domain. The receiving app verifies the JWT using its\n * own copy of the secret (peers must already share a secret to be trusted)\n * — for the first-ever sync this means at least one peer must already hold\n * the secret, which is the bootstrap. For ongoing rotation, regenerate\n * locally and call sync immediately; sync signs with the secret that's\n * currently in DB, which the peers still have.\n *\n * Body (optional): { signSecret?: string } — sign the outbound JWTs with\n * this secret instead of the org's current secret. Used by the regenerate-\n * then-sync flow: regenerate stores the NEW secret, but sync needs to\n * authenticate using the OLD one that peers still hold. Owner/admin only,\n * gated by the session.\n */\nexport const syncA2ASecretHandler = defineEventHandler(\n async (event: H3Event) => {\n const ctx = await getOrgContext(event);\n if (!ctx.orgId) {\n throw createError({\n statusCode: 400,\n message: \"No active organization\",\n });\n }\n if (ctx.role !== \"owner\" && ctx.role !== \"admin\") {\n throw createError({\n statusCode: 403,\n message: \"Only owners and admins can sync the A2A secret\",\n });\n }\n\n const body = await readBody(event).catch(() => null);\n const overrideSignSecret =\n typeof body?.signSecret === \"string\" && body.signSecret.trim()\n ? body.signSecret.trim()\n : null;\n\n const e = await exec();\n const orgRes = await e.execute({\n sql: `SELECT a2a_secret, allowed_domain FROM organizations WHERE id = ? LIMIT 1`,\n args: [ctx.orgId],\n });\n if (orgRes.rows.length === 0) {\n throw createError({\n statusCode: 404,\n message: \"Organization not found\",\n });\n }\n const orgRow = orgRes.rows[0] as any;\n const secret = String(orgRow.a2a_secret ?? \"\") || null;\n const orgDomain = String(orgRow.allowed_domain ?? \"\") || null;\n\n if (!secret) {\n throw createError({\n statusCode: 400,\n message: \"Org has no A2A secret. Generate one first before syncing.\",\n });\n }\n if (!orgDomain) {\n throw createError({\n statusCode: 400,\n message:\n \"Org has no allowed domain set. Set the email domain first so connected apps can identify which org to update.\",\n });\n }\n\n const signSecret = overrideSignSecret || secret;\n\n const { discoverAgents } = await import(\"../server/agent-discovery.js\");\n const { signA2AToken } = await import(\"../a2a/client.js\");\n\n const agents = await discoverAgents();\n\n const results: Array<{\n id: string;\n name: string;\n url: string;\n ok: boolean;\n status?: number;\n error?: string;\n }> = [];\n\n await Promise.all(\n agents.map(async (agent) => {\n try {\n const token = await signA2AToken(ctx.email, orgDomain, signSecret);\n\n const target = `${agent.url.replace(/\\/$/, \"\")}/_agent-native/org/a2a-secret/receive`;\n const res = await fetch(target, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({ secret, orgDomain }),\n });\n\n if (!res.ok) {\n const text = await res.text().catch(() => \"\");\n results.push({\n id: agent.id,\n name: agent.name,\n url: agent.url,\n ok: false,\n status: res.status,\n error: text || res.statusText,\n });\n return;\n }\n results.push({\n id: agent.id,\n name: agent.name,\n url: agent.url,\n ok: true,\n status: res.status,\n });\n } catch (err) {\n results.push({\n id: agent.id,\n name: agent.name,\n url: agent.url,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }),\n );\n\n const succeeded = results.filter((r) => r.ok).length;\n return {\n total: results.length,\n succeeded,\n failed: results.length - succeeded,\n results,\n };\n },\n);\n\n/**\n * POST /_agent-native/org/a2a-secret/receive — accept a secret push from a\n * connected agent-native app. Auth-exempt at the route guard; we verify a\n * JWT signed by the calling app using OUR copy of the org's a2a_secret. If\n * verification succeeds the calling app is a trusted peer and we overwrite\n * our local org's secret with the supplied value.\n *\n * Body: { secret: string, orgDomain: string }\n *\n * Header: Authorization: Bearer <JWT signed with the existing shared\n * a2a_secret, with `org_domain` matching the body's orgDomain>.\n */\nexport const receiveA2ASecretHandler = defineEventHandler(\n async (event: H3Event) => {\n const { getRequestHeader } = await import(\"h3\");\n const jose = await import(\"jose\");\n\n const authHeader = getRequestHeader(event, \"authorization\");\n if (!authHeader || !authHeader.startsWith(\"Bearer \")) {\n throw createError({\n statusCode: 401,\n message: \"Bearer token required\",\n });\n }\n const token = authHeader.slice(\"Bearer \".length);\n\n const body = await readBody(event);\n const newSecret =\n typeof body?.secret === \"string\" ? body.secret.trim() : \"\";\n const orgDomain =\n typeof body?.orgDomain === \"string\"\n ? body.orgDomain.trim().toLowerCase()\n : \"\";\n if (!newSecret || !orgDomain) {\n throw createError({\n statusCode: 400,\n message: \"secret and orgDomain are required\",\n });\n }\n\n // Peek at JWT (unverified) to confirm it claims the same domain we're\n // updating. Verification still happens below with the trusted secret.\n let claimedDomain: string | undefined;\n try {\n const unverified = jose.decodeJwt(token);\n claimedDomain =\n (unverified.org_domain as string | undefined) || undefined;\n } catch {\n throw createError({\n statusCode: 401,\n message: \"Malformed JWT\",\n });\n }\n if (\n !claimedDomain ||\n claimedDomain.toLowerCase() !== orgDomain.toLowerCase()\n ) {\n throw createError({\n statusCode: 401,\n message: \"JWT org_domain does not match request body\",\n });\n }\n\n // Look up our local org by the domain and grab the existing secret.\n const e = await exec();\n const orgRes = await e.execute({\n sql: `SELECT id, a2a_secret FROM organizations WHERE LOWER(allowed_domain) = ? LIMIT 1`,\n args: [orgDomain],\n });\n if (orgRes.rows.length === 0) {\n throw createError({\n statusCode: 404,\n message: \"No local org matches that domain\",\n });\n }\n const row = orgRes.rows[0] as any;\n const localOrgId = String(row.id);\n const existingSecret = String(row.a2a_secret ?? \"\") || null;\n\n if (!existingSecret) {\n // Bootstrap requires an existing shared secret to verify the caller.\n // If we have nothing on file, we can't verify trust — refuse.\n throw createError({\n statusCode: 401,\n message:\n \"Local org has no A2A secret yet — cannot verify caller. Set the secret manually for the first time.\",\n });\n }\n\n // Verify the JWT using OUR existing secret. If the caller is a trusted\n // peer they signed with the same secret and verification succeeds.\n try {\n await jose.jwtVerify(token, new TextEncoder().encode(existingSecret));\n } catch {\n throw createError({\n statusCode: 401,\n message: \"Invalid or expired JWT signature\",\n });\n }\n\n // Trusted — apply the new secret.\n await e.execute({\n sql: `UPDATE organizations SET a2a_secret = ? WHERE id = ?`,\n args: [newSecret, localOrgId],\n });\n\n return { ok: true, orgId: localOrgId };\n },\n);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAUrE,eAAO,MAAM,IAAI,EAAE,UAqBlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAqMjB;AAQD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}
1
+ {"version":3,"file":"call-agent.d.ts","sourceRoot":"","sources":["../../src/scripts/call-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAqDrE,eAAO,MAAM,IAAI,EAAE,UAqBlB,CAAC;AAEF,wBAAsB,GAAG,CACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,OAAO,CAAC,EAAE,gBAAgB,EAC1B,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,CAoMjB;AA+CD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CASzE"}