@tangle-network/agent-integrations 0.26.0 → 0.28.0

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 (46) hide show
  1. package/dist/bin/tangle-catalog-runtime.js +6 -2
  2. package/dist/bin/tangle-catalog-runtime.js.map +1 -1
  3. package/dist/catalog.d.ts +5 -1
  4. package/dist/catalog.js +6 -2
  5. package/dist/chunk-ATYHZXLL.js +457 -0
  6. package/dist/chunk-ATYHZXLL.js.map +1 -0
  7. package/dist/chunk-H4XYLS7T.js +75 -0
  8. package/dist/chunk-H4XYLS7T.js.map +1 -0
  9. package/dist/{chunk-GA4VTE3U.js → chunk-JU25UDN2.js} +5 -58
  10. package/dist/chunk-JU25UDN2.js.map +1 -0
  11. package/dist/chunk-P24T3MLM.js +106 -0
  12. package/dist/chunk-P24T3MLM.js.map +1 -0
  13. package/dist/chunk-SVQ4PHDZ.js +129 -0
  14. package/dist/chunk-SVQ4PHDZ.js.map +1 -0
  15. package/dist/{chunk-ALCIWTIR.js → chunk-UWRYFPJW.js} +41 -83
  16. package/dist/chunk-UWRYFPJW.js.map +1 -0
  17. package/dist/connect/index.d.ts +112 -0
  18. package/dist/connect/index.js +14 -0
  19. package/dist/connect/index.js.map +1 -0
  20. package/dist/connectors/adapters/index.d.ts +593 -1
  21. package/dist/connectors/adapters/index.js +15 -1
  22. package/dist/connectors/index.d.ts +2 -1
  23. package/dist/connectors/index.js +19 -5
  24. package/dist/errors-Bg3_rxnQ.d.ts +32 -0
  25. package/dist/index.d.ts +6 -2
  26. package/dist/index.js +47 -9
  27. package/dist/middleware/index.d.ts +137 -0
  28. package/dist/middleware/index.js +14 -0
  29. package/dist/middleware/index.js.map +1 -0
  30. package/dist/registry.d.ts +29 -33
  31. package/dist/registry.js +6 -2
  32. package/dist/router-BncoovUh.d.ts +149 -0
  33. package/dist/runtime.d.ts +5 -1
  34. package/dist/runtime.js +6 -2
  35. package/dist/specs.d.ts +5 -1
  36. package/dist/stripe/index.d.ts +812 -0
  37. package/dist/stripe/index.js +866 -0
  38. package/dist/stripe/index.js.map +1 -0
  39. package/dist/tangle-catalog-runtime.d.ts +5 -1
  40. package/dist/tangle-catalog-runtime.js +6 -2
  41. package/dist/tangle-id-CTU4kGId.d.ts +553 -0
  42. package/dist/webhooks/index.d.ts +3 -148
  43. package/package.json +16 -1
  44. package/dist/chunk-ALCIWTIR.js.map +0 -1
  45. package/dist/chunk-GA4VTE3U.js.map +0 -1
  46. package/dist/index-D4D4CEKX.d.ts +0 -976
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activepieces-catalog.ts","../src/activepieces-overrides.ts","../src/index.ts","../src/audit.ts","../src/approval.ts","../src/actions.ts","../src/bridge.ts","../src/client.ts","../src/consent.ts","../src/adapter-provider.ts","../src/credentials.ts","../src/discovery.ts","../src/events.ts","../src/guard.ts","../src/healthcheck.ts","../src/manifest.ts","../src/passthrough.ts","../src/policy.ts","../src/presets.ts","../src/sandbox.ts","../src/importers.ts","../src/gateway-catalog.ts","../src/activepieces-provider.ts","../src/activepieces-runtime.ts","../src/tangle-catalog-runtime.ts","../src/tangle-catalog-runtime-server.ts","../src/catalog-freshness.ts","../src/runtime.ts","../src/workflow.ts","../src/catalog-executor.ts","../src/tangle-catalog.ts","../src/registry.ts","../src/catalog.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\nimport type {\n IntegrationActionRisk,\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationConnectorTrigger,\n IntegrationDataClass,\n} from './index.js'\nimport { getActivepiecesOverride } from './activepieces-overrides.js'\n\nexport interface ActivepiecesCatalogEntry {\n id: string\n title: string\n description: string\n npmPackage?: string\n version?: string\n category: IntegrationConnectorCategory\n auth: IntegrationConnector['auth']\n authFields?: ActivepiecesCatalogAuthField[]\n domains: string[]\n actions: Array<{\n id: string\n title: string\n risk: IntegrationActionRisk\n upstreamName?: string\n }>\n triggers: Array<{\n id: string\n title: string\n upstreamName?: string\n }>\n source: {\n repository: string\n path: string\n license: 'MIT'\n }\n}\n\nexport interface ActivepiecesCatalogAuthField {\n key: string\n label: string\n required: boolean\n secret: boolean\n kind: 'text' | 'number' | 'boolean' | 'select' | 'object' | 'unknown'\n description?: string\n}\n\nconst CATALOG_RESOURCE_RELATIVE = '../data/activepieces-catalog.json'\n\nlet CACHED_CATALOG: ReadonlyArray<ActivepiecesCatalogEntry> | undefined\n\nfunction loadCatalog(): ReadonlyArray<ActivepiecesCatalogEntry> {\n if (CACHED_CATALOG) return CACHED_CATALOG\n const here = dirname(fileURLToPath(import.meta.url))\n const path = resolve(here, CATALOG_RESOURCE_RELATIVE)\n const raw = readFileSync(path, 'utf8')\n const parsed = JSON.parse(raw) as ActivepiecesCatalogEntry[]\n CACHED_CATALOG = parsed\n return parsed\n}\n\nexport function listActivepiecesCatalogEntries(): ActivepiecesCatalogEntry[] {\n return loadCatalog().map((entry) => ({\n ...entry,\n actions: [...entry.actions],\n triggers: [...entry.triggers],\n domains: [...entry.domains],\n source: { ...entry.source },\n }))\n}\n\nexport function buildActivepiecesConnectors(options: {\n providerId?: string\n includeCatalogActions?: boolean\n executable?: boolean\n} = {}): IntegrationConnector[] {\n const providerId = options.providerId ?? 'activepieces'\n const executable = options.executable === true\n return listActivepiecesCatalogEntries().map((entry) => {\n const override = getActivepiecesOverride(entry.id)\n const category = override?.category ?? entry.category\n const scopes = [`${entry.id}.read`, `${entry.id}.write`]\n const catalogActions = entry.actions.length > 0\n ? entry.actions.map((action) => toAction(applyActionOverride(action, override), scopes, dataClassFor(category)))\n : defaultActions(entry.id, scopes, dataClassFor(category))\n const catalogTriggers = entry.triggers.map((trigger) => toTrigger(trigger, scopes, dataClassFor(category)))\n return {\n id: entry.id,\n providerId,\n title: entry.title,\n category,\n auth: entry.auth,\n scopes: options.includeCatalogActions ? scopes : [],\n actions: options.includeCatalogActions ? catalogActions : [],\n triggers: options.includeCatalogActions ? catalogTriggers : undefined,\n metadata: {\n source: 'activepieces-community',\n executable,\n runtime: 'activepieces-piece',\n catalogOnly: !executable,\n supportTier: executable ? 'gatewayExecutable' : 'catalogOnly',\n catalogActionCount: catalogActions.length,\n catalogTriggerCount: catalogTriggers.length,\n npmPackage: entry.npmPackage,\n version: entry.version,\n license: entry.source.license,\n sourcePath: entry.source.path,\n domains: entry.domains,\n authFields: entry.authFields,\n ...(override ? { overridden: true } : {}),\n },\n }\n })\n}\n\nfunction applyActionOverride(\n action: ActivepiecesCatalogEntry['actions'][number],\n override: ReturnType<typeof getActivepiecesOverride>,\n): ActivepiecesCatalogEntry['actions'][number] {\n if (!override) return action\n const risk = override.actionRisks?.[action.id] ?? action.risk\n return { ...action, risk }\n}\n\nfunction toAction(\n action: ActivepiecesCatalogEntry['actions'][number],\n scopes: string[],\n dataClass: IntegrationDataClass,\n): IntegrationConnectorAction {\n return {\n id: action.id,\n title: action.title,\n risk: action.risk,\n requiredScopes: action.risk === 'read' ? [scopes[0]!] : [scopes[1]!],\n dataClass,\n approvalRequired: action.risk !== 'read',\n inputSchema: { type: 'object', additionalProperties: true, properties: {} },\n }\n}\n\nfunction toTrigger(\n trigger: ActivepiecesCatalogEntry['triggers'][number],\n scopes: string[],\n dataClass: IntegrationDataClass,\n): IntegrationConnectorTrigger {\n return {\n id: trigger.id,\n title: trigger.title,\n requiredScopes: [scopes[0]!],\n dataClass,\n payloadSchema: { type: 'object', additionalProperties: true, properties: {} },\n }\n}\n\nfunction defaultActions(\n id: string,\n scopes: string[],\n dataClass: IntegrationDataClass,\n): IntegrationConnectorAction[] {\n return [\n {\n id: 'records.search',\n title: 'Search records',\n risk: 'read',\n requiredScopes: [scopes[0]!],\n dataClass,\n inputSchema: { type: 'object', additionalProperties: true, properties: {} },\n },\n {\n id: 'records.upsert',\n title: 'Upsert record',\n risk: 'write',\n requiredScopes: [scopes[1]!],\n dataClass,\n approvalRequired: true,\n inputSchema: { type: 'object', additionalProperties: true, properties: {} },\n description: `Create or update a ${id} record through a catalog-backed connector.`,\n },\n ]\n}\n\nfunction dataClassFor(category: IntegrationConnectorCategory): IntegrationDataClass {\n if (category === 'database' || category === 'storage' || category === 'email') return 'private'\n if (category === 'crm' || category === 'chat' || category === 'docs') return 'private'\n if (category === 'internal') return 'sensitive'\n return 'internal'\n}\n","import type {\n IntegrationActionRisk,\n IntegrationConnectorCategory,\n} from './index.js'\n\nexport interface ActivepiecesPieceOverride {\n category?: IntegrationConnectorCategory\n actionRisks?: Record<string, IntegrationActionRisk>\n approvalRequired?: Record<string, boolean>\n}\n\nexport const ACTIVEPIECES_OVERRIDES: Record<string, ActivepiecesPieceOverride> = {\n slack: {\n category: 'chat',\n actionRisks: {\n 'slack.send.message': 'write',\n 'slack.send.direct.message': 'write',\n 'request.action.message': 'write',\n 'request.action.direct.message': 'write',\n 'request.approval.direct.message': 'write',\n 'request.send.approval.message': 'write',\n 'upload.file': 'write',\n 'search.messages': 'read',\n },\n },\n discord: { category: 'chat' },\n 'microsoft-teams': { category: 'chat' },\n whatsapp: { category: 'chat' },\n telegram: { category: 'chat' },\n\n gmail: {\n category: 'email',\n actionRisks: {\n 'gmail.send.email': 'write',\n 'gmail.reply.to.email': 'write',\n 'gmail.create.draft.reply': 'write',\n 'gmail.search.mail': 'read',\n 'gmail.get.email': 'read',\n 'request.approval.in.email': 'write',\n },\n },\n 'microsoft-outlook': { category: 'email' },\n sendgrid: { category: 'email' },\n postmark: { category: 'email' },\n mailchimp: { category: 'email' },\n resend: { category: 'email' },\n\n 'google-calendar': { category: 'calendar' },\n 'microsoft-outlook-calendar': { category: 'calendar' },\n cal: { category: 'calendar' },\n calendly: { category: 'calendar' },\n zoom: { category: 'calendar' },\n\n 'google-drive': { category: 'storage' },\n dropbox: { category: 'storage' },\n onedrive: { category: 'storage' },\n\n 'google-sheets': { category: 'database' },\n 'google-docs': { category: 'docs' },\n airtable: { category: 'database' },\n notion: { category: 'docs' },\n\n hubspot: { category: 'crm' },\n salesforce: { category: 'crm' },\n pipedrive: { category: 'crm' },\n intercom: { category: 'crm' },\n zendesk: { category: 'crm' },\n\n stripe: {\n category: 'crm',\n actionRisks: {\n 'stripe.create.customer': 'write',\n 'stripe.update.customer': 'write',\n 'stripe.retrieve.customer': 'read',\n 'stripe.search.customer': 'read',\n 'stripe.search.subscriptions': 'read',\n 'stripe.create.invoice': 'write',\n 'stripe.retrieve.invoice': 'read',\n 'stripe.find.invoice': 'read',\n 'stripe.create.subscription': 'write',\n 'stripe.cancel.subscription': 'destructive',\n 'stripe.create.payment.intent': 'write',\n 'stripe.retrieve.payment.intent': 'read',\n 'stripe.create.refund': 'destructive',\n 'stripe.create.product': 'write',\n 'stripe.create.price': 'write',\n 'stripe.create.payment.link': 'write',\n 'stripe.deactivate.payment.link': 'destructive',\n 'stripe.retrieve.payout': 'read',\n },\n approvalRequired: {\n 'stripe.create.refund': true,\n 'stripe.cancel.subscription': true,\n 'stripe.deactivate.payment.link': true,\n },\n },\n\n twilio: {\n category: 'chat',\n actionRisks: {\n 'send.sms': 'write',\n 'send.whatsapp.message': 'write',\n 'make.phone.call': 'write',\n },\n },\n\n shopify: { category: 'crm' },\n square: { category: 'crm' },\n}\n\nexport function getActivepiecesOverride(id: string): ActivepiecesPieceOverride | undefined {\n return ACTIVEPIECES_OVERRIDES[id]\n}\n","import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto'\nimport {\n composeIntegrationRegistry,\n type ComposeIntegrationRegistryOptions,\n type IntegrationRegistry,\n} from './registry.js'\n\nexport * from './audit.js'\nexport * from './approval.js'\nexport * from './actions.js'\nexport * from './bridge.js'\nexport * from './client.js'\nexport * from './consent.js'\nexport * from './credentials.js'\nexport * from './discovery.js'\nexport * from './errors.js'\nexport * from './events.js'\nexport * from './guard.js'\nexport * from './healthcheck.js'\nexport * from './manifest.js'\nexport * from './passthrough.js'\nexport * from './presets.js'\nexport * from './connect/index.js'\nexport * from './middleware/index.js'\n\nexport type IntegrationProviderKind =\n | 'first_party'\n | 'nango'\n | 'pipedream'\n | 'zapier'\n | 'activepieces'\n | 'tangle_catalog'\n | 'executor'\n | 'custom'\n\nexport type IntegrationConnectorCategory =\n | 'email'\n | 'calendar'\n | 'chat'\n | 'crm'\n | 'storage'\n | 'docs'\n | 'database'\n | 'webhook'\n | 'workflow'\n | 'internal'\n | 'other'\n\nexport type IntegrationActionRisk = 'read' | 'write' | 'destructive'\nexport type IntegrationDataClass = 'public' | 'internal' | 'private' | 'sensitive' | 'secret'\n\nexport interface IntegrationActor {\n type: 'user' | 'team' | 'app' | 'agent' | 'sandbox' | 'system'\n id: string\n}\n\nexport interface IntegrationConnectorAction {\n id: string\n title: string\n risk: IntegrationActionRisk\n requiredScopes: string[]\n dataClass: IntegrationDataClass\n description?: string\n approvalRequired?: boolean\n inputSchema?: unknown\n outputSchema?: unknown\n}\n\nexport interface IntegrationConnectorTrigger {\n id: string\n title: string\n requiredScopes: string[]\n dataClass: IntegrationDataClass\n description?: string\n payloadSchema?: unknown\n}\n\nexport interface IntegrationConnector {\n id: string\n providerId: string\n title: string\n category: IntegrationConnectorCategory\n auth: 'oauth2' | 'api_key' | 'none' | 'custom'\n scopes: string[]\n actions: IntegrationConnectorAction[]\n triggers?: IntegrationConnectorTrigger[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SecretRef {\n provider: string\n id: string\n label?: string\n}\n\nexport interface IntegrationConnection {\n id: string\n owner: IntegrationActor\n providerId: string\n connectorId: string\n status: 'pending' | 'active' | 'expired' | 'revoked' | 'error'\n grantedScopes: string[]\n account?: {\n id?: string\n email?: string\n displayName?: string\n }\n secretRef?: SecretRef\n createdAt: string\n updatedAt: string\n expiresAt?: string\n lastUsedAt?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface StartAuthRequest {\n connectorId: string\n owner: IntegrationActor\n requestedScopes: string[]\n redirectUri: string\n state?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface StartAuthResult {\n providerId: string\n connectorId: string\n authUrl: string\n state: string\n expiresAt?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface CompleteAuthRequest {\n connectorId: string\n owner: IntegrationActor\n code?: string\n state: string\n redirectUri: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationActionRequest {\n connectionId: string\n action: string\n input?: unknown\n idempotencyKey?: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationActionResult<T = unknown> {\n ok: boolean\n action: string\n output?: T\n externalId?: string\n warnings?: string[]\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationTriggerSubscription {\n id: string\n connectionId: string\n trigger: string\n targetUrl?: string\n status: 'active' | 'paused' | 'error'\n createdAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationTriggerEvent<T = unknown> {\n id: string\n providerId: string\n connectorId: string\n connectionId: string\n trigger: string\n occurredAt: string\n payload: T\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationProvider {\n id: string\n kind: IntegrationProviderKind\n listConnectors(): Promise<IntegrationConnector[]> | IntegrationConnector[]\n startAuth?(request: StartAuthRequest): Promise<StartAuthResult> | StartAuthResult\n completeAuth?(request: CompleteAuthRequest): Promise<IntegrationConnection> | IntegrationConnection\n invokeAction(connection: IntegrationConnection, request: IntegrationActionRequest): Promise<IntegrationActionResult> | IntegrationActionResult\n subscribeTrigger?(connection: IntegrationConnection, trigger: string, targetUrl?: string): Promise<IntegrationTriggerSubscription> | IntegrationTriggerSubscription\n unsubscribeTrigger?(subscriptionId: string): Promise<void> | void\n normalizeTriggerEvent?(raw: unknown): Promise<IntegrationTriggerEvent> | IntegrationTriggerEvent\n}\n\nexport interface IntegrationConnectionStore {\n get(connectionId: string): Promise<IntegrationConnection | undefined> | IntegrationConnection | undefined\n put(connection: IntegrationConnection): Promise<void> | void\n listByOwner(owner: IntegrationActor): Promise<IntegrationConnection[]> | IntegrationConnection[]\n delete?(connectionId: string): Promise<void> | void\n}\n\nexport interface IssueCapabilityRequest {\n subject: IntegrationActor\n connectionId: string\n scopes: string[]\n allowedActions: string[]\n ttlMs: number\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationCapability {\n id: string\n subject: IntegrationActor\n connectionId: string\n scopes: string[]\n allowedActions: string[]\n issuedAt: string\n expiresAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IssuedIntegrationCapability {\n capability: IntegrationCapability\n token: string\n}\n\n/**\n * Wraps every action invocation with cross-cutting discipline (idempotency,\n * conflict detection, rate-limiting, audit logging). Optional. When set on\n * the hub, runs BEFORE provider.invokeAction; can short-circuit (return a\n * result directly) or pass through (call `proceed()` to invoke the provider).\n *\n * Why this hook exists: production deployments need conflict-resolution\n * guarantees that span every provider, gateway, and webhook receiver. The\n * canonical implementation is a \"MutationGuard\" that:\n * 1. Short-circuits on a known idempotency key (returns recorded response).\n * 2. Refuses same-key-different-args (drift detection).\n * 3. Wraps `proceed()` and audit-logs the outcome.\n * 4. Translates upstream conflict signals into a structured result with\n * alternatives the agent can act on.\n *\n * Implementations live in consumers (every product has different\n * persistence + telemetry needs); this interface is the contract.\n */\nexport interface IntegrationActionGuard {\n /** Wrap an invokeAction call. Implementations MUST call `proceed()` to\n * invoke the underlying provider unless they're returning a cached or\n * short-circuited result.\n *\n * @param ctx connection + request the hub is about to dispatch\n * @param proceed call to invoke the wrapped provider; returns the\n * underlying IntegrationActionResult\n * @returns the result the hub should return to the caller\n */\n invokeAction(\n ctx: IntegrationGuardContext,\n proceed: () => Promise<IntegrationActionResult>,\n ): Promise<IntegrationActionResult>\n}\n\nexport interface IntegrationGuardContext {\n connection: IntegrationConnection\n request: IntegrationActionRequest\n /** The action descriptor from the connector manifest, if discovered. */\n action?: IntegrationConnectorAction\n}\n\nexport type IntegrationPolicyDecision =\n | { decision: 'allow'; reason: string; metadata?: Record<string, unknown> }\n | { decision: 'require_approval'; reason: string; approval: IntegrationApprovalRequest; metadata?: Record<string, unknown> }\n | { decision: 'deny'; reason: string; metadata?: Record<string, unknown> }\n\nexport interface IntegrationApprovalRequest {\n id: string\n connectionId: string\n providerId: string\n connectorId: string\n action: string\n actor: IntegrationActor\n risk: IntegrationActionRisk\n dataClass: IntegrationDataClass\n reason: string\n requestedAt: string\n inputPreview?: unknown\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationPolicyEngine {\n decide(ctx: IntegrationGuardContext & { subject: IntegrationActor }): Promise<IntegrationPolicyDecision> | IntegrationPolicyDecision\n}\n\nexport interface IntegrationHubOptions {\n providers: IntegrationProvider[]\n store: IntegrationConnectionStore\n capabilitySecret: string\n /** Optional cross-cutting guard. If provided, every invokeAction call\n * passes through it before reaching the provider. See {@link IntegrationActionGuard}. */\n guard?: IntegrationActionGuard\n /** Optional policy engine. Runs after capability/scope checks and before\n * provider invocation. Use it to pause writes, deny destructive actions,\n * or apply tenant-specific allow rules. */\n policy?: IntegrationPolicyEngine\n now?: () => Date\n}\n\nexport interface HttpIntegrationProviderOptions {\n id: string\n kind?: IntegrationProviderKind\n connectors: IntegrationConnector[]\n baseUrl: string\n bearer?: string\n fetchImpl?: typeof fetch\n}\n\nexport interface InvokeWithCapabilityRequest extends Omit<IntegrationActionRequest, 'connectionId'> {\n connectionId?: never\n}\n\nexport class IntegrationError extends Error {\n constructor(\n message: string,\n readonly code:\n | 'provider_not_found'\n | 'connector_not_found'\n | 'connection_not_found'\n | 'connection_not_active'\n | 'auth_not_supported'\n | 'capability_invalid'\n | 'capability_expired'\n | 'scope_denied'\n | 'action_denied'\n | 'action_not_found'\n | 'trigger_not_found'\n | 'approval_required'\n | 'policy_denied',\n ) {\n super(message)\n this.name = 'IntegrationError'\n }\n}\n\nexport class InMemoryConnectionStore implements IntegrationConnectionStore {\n private readonly connections = new Map<string, IntegrationConnection>()\n\n get(connectionId: string): IntegrationConnection | undefined {\n return this.connections.get(connectionId)\n }\n\n put(connection: IntegrationConnection): void {\n this.connections.set(connection.id, connection)\n }\n\n listByOwner(owner: IntegrationActor): IntegrationConnection[] {\n return [...this.connections.values()].filter((connection) =>\n connection.owner.type === owner.type && connection.owner.id === owner.id,\n )\n }\n\n delete(connectionId: string): void {\n this.connections.delete(connectionId)\n }\n}\n\nexport class IntegrationHub {\n private readonly providers = new Map<string, IntegrationProvider>()\n private readonly store: IntegrationConnectionStore\n private readonly capabilitySecret: string\n private readonly guard: IntegrationActionGuard | undefined\n private readonly policy: IntegrationPolicyEngine | undefined\n private readonly now: () => Date\n\n constructor(options: IntegrationHubOptions) {\n if (!options.capabilitySecret) {\n throw new IntegrationError('capabilitySecret is required.', 'capability_invalid')\n }\n for (const provider of options.providers) this.providers.set(provider.id, provider)\n this.store = options.store\n this.capabilitySecret = options.capabilitySecret\n this.guard = options.guard\n this.policy = options.policy\n this.now = options.now ?? (() => new Date())\n }\n\n async listConnectors(): Promise<IntegrationConnector[]> {\n const catalogs = await Promise.all([...this.providers.values()].map((provider) => provider.listConnectors()))\n return catalogs.flat()\n }\n\n async listRegistry(options: ComposeIntegrationRegistryOptions = {}): Promise<IntegrationRegistry> {\n const sources = await Promise.all([...this.providers.values()].map(async (provider) => ({\n id: provider.id,\n connectors: await provider.listConnectors(),\n })))\n return composeIntegrationRegistry(sources, options)\n }\n\n async startAuth(providerId: string, request: StartAuthRequest): Promise<StartAuthResult> {\n const provider = this.requireProvider(providerId)\n if (!provider.startAuth) throw new IntegrationError(`Provider ${providerId} does not support auth start.`, 'auth_not_supported')\n await this.requireConnector(provider, request.connectorId)\n return provider.startAuth(request)\n }\n\n async completeAuth(providerId: string, request: CompleteAuthRequest): Promise<IntegrationConnection> {\n const provider = this.requireProvider(providerId)\n if (!provider.completeAuth) throw new IntegrationError(`Provider ${providerId} does not support auth completion.`, 'auth_not_supported')\n const connection = await provider.completeAuth(request)\n await this.store.put(connection)\n return connection\n }\n\n async upsertConnection(connection: IntegrationConnection): Promise<IntegrationConnection> {\n await this.store.put(connection)\n return connection\n }\n\n async listConnections(owner: IntegrationActor): Promise<IntegrationConnection[]> {\n return this.store.listByOwner(owner)\n }\n\n async getConnection(connectionId: string): Promise<IntegrationConnection | undefined> {\n return this.store.get(connectionId)\n }\n\n async issueCapability(request: IssueCapabilityRequest): Promise<IssuedIntegrationCapability> {\n const connection = await this.requireConnection(request.connectionId)\n this.assertConnectionActive(connection)\n assertScopes(connection, request.scopes)\n const now = this.now()\n const capability: IntegrationCapability = {\n id: `cap_${randomUUID()}`,\n subject: request.subject,\n connectionId: request.connectionId,\n scopes: unique(request.scopes),\n allowedActions: unique(request.allowedActions),\n issuedAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + request.ttlMs).toISOString(),\n metadata: request.metadata,\n }\n return { capability, token: signCapability(capability, this.capabilitySecret) }\n }\n\n verifyCapability(token: string): IntegrationCapability {\n const capability = verifyCapabilityToken(token, this.capabilitySecret)\n if (Date.parse(capability.expiresAt) <= this.now().getTime()) {\n throw new IntegrationError('Integration capability expired.', 'capability_expired')\n }\n return capability\n }\n\n async invokeWithCapability(token: string, request: InvokeWithCapabilityRequest): Promise<IntegrationActionResult> {\n const capability = this.verifyCapability(token)\n if (!capability.allowedActions.includes(request.action)) {\n throw new IntegrationError(`Capability does not allow action ${request.action}.`, 'action_denied')\n }\n const connection = await this.requireConnection(capability.connectionId)\n this.assertConnectionActive(connection)\n const provider = this.requireProvider(connection.providerId)\n const connector = await this.requireConnector(provider, connection.connectorId)\n const action = connector.actions.find((candidate) => candidate.id === request.action)\n if (!action) throw new IntegrationError(`Action ${request.action} is not defined by connector ${connector.id}.`, 'action_not_found')\n assertScopes(connection, action.requiredScopes)\n assertScopes({ ...connection, grantedScopes: capability.scopes }, action.requiredScopes)\n const fullRequest: IntegrationActionRequest = { ...request, connectionId: connection.id }\n const proceed = async () => {\n if (!this.policy) return provider.invokeAction(connection, fullRequest)\n const decision = await this.policy.decide({\n connection,\n request: fullRequest,\n action,\n subject: capability.subject,\n })\n if (decision.decision === 'deny') {\n throw new IntegrationError(decision.reason, 'policy_denied')\n }\n if (decision.decision === 'require_approval') {\n return {\n ok: false,\n action: request.action,\n output: { approvalRequired: true, approval: decision.approval },\n metadata: { policyDecision: decision.decision, reason: decision.reason, ...decision.metadata },\n }\n }\n return provider.invokeAction(connection, fullRequest)\n }\n if (this.guard) {\n return this.guard.invokeAction({ connection, request: fullRequest, action }, proceed)\n }\n return proceed()\n }\n\n async subscribeTrigger(connectionId: string, trigger: string, targetUrl?: string): Promise<IntegrationTriggerSubscription> {\n const connection = await this.requireConnection(connectionId)\n this.assertConnectionActive(connection)\n const provider = this.requireProvider(connection.providerId)\n const connector = await this.requireConnector(provider, connection.connectorId)\n const spec = connector.triggers?.find((candidate) => candidate.id === trigger)\n if (!spec) throw new IntegrationError(`Trigger ${trigger} is not defined by connector ${connector.id}.`, 'trigger_not_found')\n assertScopes(connection, spec.requiredScopes)\n if (!provider.subscribeTrigger) {\n throw new IntegrationError(`Provider ${provider.id} does not support triggers.`, 'auth_not_supported')\n }\n return provider.subscribeTrigger(connection, trigger, targetUrl)\n }\n\n private requireProvider(providerId: string): IntegrationProvider {\n const provider = this.providers.get(providerId)\n if (!provider) throw new IntegrationError(`Provider ${providerId} not found.`, 'provider_not_found')\n return provider\n }\n\n private async requireConnector(provider: IntegrationProvider, connectorId: string): Promise<IntegrationConnector> {\n const connector = (await provider.listConnectors()).find((candidate) => candidate.id === connectorId)\n if (!connector) throw new IntegrationError(`Connector ${connectorId} not found.`, 'connector_not_found')\n return connector\n }\n\n private async requireConnection(connectionId: string): Promise<IntegrationConnection> {\n const connection = await this.store.get(connectionId)\n if (!connection) throw new IntegrationError(`Connection ${connectionId} not found.`, 'connection_not_found')\n return connection\n }\n\n private assertConnectionActive(connection: IntegrationConnection): void {\n if (connection.status !== 'active') {\n throw new IntegrationError(`Connection ${connection.id} is ${connection.status}.`, 'connection_not_active')\n }\n if (connection.expiresAt && Date.parse(connection.expiresAt) <= this.now().getTime()) {\n throw new IntegrationError(`Connection ${connection.id} is expired.`, 'connection_not_active')\n }\n }\n}\n\nexport function sanitizeConnection(connection: IntegrationConnection): Record<string, unknown> {\n return {\n id: connection.id,\n owner: connection.owner,\n providerId: connection.providerId,\n connectorId: connection.connectorId,\n status: connection.status,\n grantedScopes: connection.grantedScopes,\n account: connection.account,\n hasSecretRef: Boolean(connection.secretRef),\n createdAt: connection.createdAt,\n updatedAt: connection.updatedAt,\n expiresAt: connection.expiresAt,\n lastUsedAt: connection.lastUsedAt,\n }\n}\n\nexport function createMockIntegrationProvider(options: {\n id?: string\n connectors?: IntegrationConnector[]\n onInvoke?: (connection: IntegrationConnection, request: IntegrationActionRequest) => IntegrationActionResult | Promise<IntegrationActionResult>\n} = {}): IntegrationProvider {\n const providerId = options.id ?? 'mock'\n const connectors = options.connectors ?? [{\n id: 'gmail',\n providerId,\n title: 'Gmail',\n category: 'email',\n auth: 'oauth2',\n scopes: ['email.read', 'email.write'],\n actions: [\n { id: 'messages.search', title: 'Search messages', risk: 'read', requiredScopes: ['email.read'], dataClass: 'private' },\n { id: 'drafts.create', title: 'Create draft', risk: 'write', requiredScopes: ['email.write'], dataClass: 'private', approvalRequired: true },\n ],\n triggers: [\n { id: 'message.received', title: 'Message received', requiredScopes: ['email.read'], dataClass: 'private' },\n ],\n }]\n return {\n id: providerId,\n kind: 'custom',\n listConnectors: () => connectors,\n startAuth: (request) => ({\n providerId,\n connectorId: request.connectorId,\n authUrl: `https://auth.example.test/${request.connectorId}?state=${encodeURIComponent(request.state ?? 'state')}`,\n state: request.state ?? 'state',\n }),\n completeAuth: (request) => ({\n id: `conn_${request.connectorId}_${request.owner.id}`,\n owner: request.owner,\n providerId,\n connectorId: request.connectorId,\n status: 'active',\n grantedScopes: connectors.find((connector) => connector.id === request.connectorId)?.scopes ?? [],\n secretRef: { provider: providerId, id: `secret_${request.owner.id}` },\n createdAt: new Date(0).toISOString(),\n updatedAt: new Date(0).toISOString(),\n }),\n invokeAction: async (connection, request) => options.onInvoke?.(connection, request) ?? ({\n ok: true,\n action: request.action,\n output: { echo: request.input ?? null },\n }),\n subscribeTrigger: (connection, trigger, targetUrl) => ({\n id: `sub_${connection.id}_${trigger}`,\n connectionId: connection.id,\n trigger,\n targetUrl,\n status: 'active',\n createdAt: new Date(0).toISOString(),\n }),\n }\n}\n\nexport function createHttpIntegrationProvider(options: HttpIntegrationProviderOptions): IntegrationProvider {\n const fetcher = options.fetchImpl ?? fetch\n const baseUrl = options.baseUrl.replace(/\\/$/, '')\n return {\n id: options.id,\n kind: options.kind ?? 'custom',\n listConnectors: () => options.connectors,\n async startAuth(request) {\n const response = await postJson<StartAuthResult>(fetcher, `${baseUrl}/auth/start`, request, options.bearer)\n return response\n },\n async completeAuth(request) {\n const response = await postJson<IntegrationConnection>(fetcher, `${baseUrl}/auth/complete`, request, options.bearer)\n return response\n },\n async invokeAction(connection, request) {\n return postJson<IntegrationActionResult>(fetcher, `${baseUrl}/actions/invoke`, {\n connection,\n request,\n }, options.bearer)\n },\n async subscribeTrigger(connection, trigger, targetUrl) {\n return postJson<IntegrationTriggerSubscription>(fetcher, `${baseUrl}/triggers/subscribe`, {\n connection,\n trigger,\n targetUrl,\n }, options.bearer)\n },\n async unsubscribeTrigger(subscriptionId) {\n await postJson(fetcher, `${baseUrl}/triggers/unsubscribe`, { subscriptionId }, options.bearer)\n },\n async normalizeTriggerEvent(raw) {\n return postJson<IntegrationTriggerEvent>(fetcher, `${baseUrl}/triggers/normalize`, { raw }, options.bearer)\n },\n }\n}\n\nexport function signCapability(capability: IntegrationCapability, secret: string): string {\n const payload = base64UrlEncode(JSON.stringify(capability))\n const signature = hmac(payload, secret)\n return `${payload}.${signature}`\n}\n\nexport function verifyCapabilityToken(token: string, secret: string): IntegrationCapability {\n const [payload, signature] = token.split('.')\n if (!payload || !signature) throw new IntegrationError('Malformed integration capability.', 'capability_invalid')\n const expected = hmac(payload, secret)\n if (!constantTimeEqual(signature, expected)) throw new IntegrationError('Invalid integration capability signature.', 'capability_invalid')\n let parsed: IntegrationCapability\n try {\n parsed = JSON.parse(base64UrlDecode(payload)) as IntegrationCapability\n } catch {\n throw new IntegrationError('Invalid integration capability payload.', 'capability_invalid')\n }\n if (!parsed.id || !parsed.connectionId || !Array.isArray(parsed.scopes) || !Array.isArray(parsed.allowedActions)) {\n throw new IntegrationError('Invalid integration capability payload.', 'capability_invalid')\n }\n return parsed\n}\n\nasync function postJson<T = unknown>(\n fetcher: typeof fetch,\n url: string,\n body: unknown,\n bearer?: string,\n): Promise<T> {\n const response = await fetcher(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),\n },\n body: JSON.stringify(body),\n })\n if (!response.ok) throw new IntegrationError(`Integration provider returned HTTP ${response.status}.`, 'provider_not_found')\n return response.json() as Promise<T>\n}\n\nfunction assertScopes(connection: Pick<IntegrationConnection, 'grantedScopes'>, requiredScopes: string[]): void {\n const missing = requiredScopes.filter((scope) => !connection.grantedScopes.includes(scope))\n if (missing.length > 0) throw new IntegrationError(`Missing integration scopes: ${missing.join(', ')}`, 'scope_denied')\n}\n\nfunction hmac(payload: string, secret: string): string {\n return createHmac('sha256', secret).update(payload).digest('base64url')\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n const left = Buffer.from(a)\n const right = Buffer.from(b)\n return left.length === right.length && timingSafeEqual(left, right)\n}\n\nfunction base64UrlEncode(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url')\n}\n\nfunction base64UrlDecode(value: string): string {\n return Buffer.from(value, 'base64url').toString('utf8')\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n\n// ─── Connectors namespace ───────────────────────────────────────────────\n//\n// Lower-level adapter primitives — the contract a concrete first-party\n// integration (Google Calendar, HubSpot, Stripe, ...) implements. The\n// hub-side `IntegrationProvider` interface is the *catalog* facade above\n// these; one provider can wrap many connectors. See `src/connectors/types.ts`\n// for the layering details.\nexport * from './connectors/index.js'\nexport * from './catalog.js'\nexport * from './catalog-executor.js'\nexport * from './policy.js'\nexport * from './sandbox.js'\nexport * from './adapter-provider.js'\nexport * from './importers.js'\nexport * from './gateway-catalog.js'\nexport * from './activepieces-catalog.js'\nexport * from './activepieces-overrides.js'\nexport * from './activepieces-provider.js'\nexport * from './activepieces-runtime.js'\nexport * from './tangle-catalog.js'\nexport * from './tangle-catalog-runtime.js'\nexport * from './tangle-catalog-runtime-server.js'\nexport * from './catalog-freshness.js'\nexport * from './registry.js'\nexport * from './runtime.js'\nexport * from './workflow.js'\nexport * from './coverage-catalog.js'\nexport * from './specs/index.js'\n","import { randomUUID } from 'node:crypto'\nimport type {\n IntegrationActionGuard,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationActor,\n IntegrationConnection,\n IntegrationConnectorAction,\n IntegrationDataClass,\n IntegrationGuardContext,\n} from './index.js'\n\nexport type IntegrationAuditEventType =\n | 'connection.created'\n | 'connection.updated'\n | 'connection.revoked'\n | 'grant.created'\n | 'grant.revoked'\n | 'capability.issued'\n | 'action.invoked'\n | 'action.failed'\n | 'trigger.subscribed'\n | 'trigger.received'\n | 'workflow.installed'\n | 'approval.requested'\n | 'approval.resolved'\n | 'healthcheck.completed'\n\nexport interface IntegrationAuditEvent {\n id: string\n type: IntegrationAuditEventType\n occurredAt: string\n actor?: IntegrationActor\n connectionId?: string\n providerId?: string\n connectorId?: string\n action?: string\n risk?: IntegrationConnectorAction['risk']\n dataClass?: IntegrationDataClass\n ok?: boolean\n message?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationAuditSink {\n record(event: IntegrationAuditEvent): Promise<void> | void\n}\n\nexport interface IntegrationAuditStore extends IntegrationAuditSink {\n list(filter?: IntegrationAuditFilter): Promise<IntegrationAuditEvent[]> | IntegrationAuditEvent[]\n}\n\nexport interface IntegrationAuditFilter {\n type?: IntegrationAuditEventType\n actor?: IntegrationActor\n connectionId?: string\n providerId?: string\n connectorId?: string\n action?: string\n}\n\nexport class InMemoryIntegrationAuditStore implements IntegrationAuditStore {\n private readonly events: IntegrationAuditEvent[] = []\n\n record(event: IntegrationAuditEvent): void {\n this.events.push(event)\n }\n\n list(filter: IntegrationAuditFilter = {}): IntegrationAuditEvent[] {\n return this.events.filter((event) => matchesFilter(event, filter))\n }\n}\n\nexport function createIntegrationAuditEvent(input: Omit<IntegrationAuditEvent, 'id' | 'occurredAt'> & {\n id?: string\n occurredAt?: string | Date\n now?: () => Date\n}): IntegrationAuditEvent {\n const occurredAt = input.occurredAt instanceof Date\n ? input.occurredAt.toISOString()\n : input.occurredAt ?? (input.now?.() ?? new Date()).toISOString()\n return {\n ...input,\n id: input.id ?? `audit_${randomUUID()}`,\n occurredAt,\n metadata: input.metadata ? redactUnknown(input.metadata) as Record<string, unknown> : undefined,\n }\n}\n\nexport function createAuditingActionGuard(options: {\n sink: IntegrationAuditSink\n subject?: IntegrationActor\n now?: () => Date\n includeInputPreview?: boolean\n}): IntegrationActionGuard {\n const now = options.now ?? (() => new Date())\n return {\n async invokeAction(ctx: IntegrationGuardContext, proceed: () => Promise<IntegrationActionResult>): Promise<IntegrationActionResult> {\n const startedAt = now()\n try {\n const result = await proceed()\n await options.sink.record(actionEvent({\n ctx,\n request: ctx.request,\n result,\n type: result.ok ? 'action.invoked' : 'action.failed',\n subject: options.subject,\n occurredAt: startedAt,\n includeInputPreview: options.includeInputPreview,\n }))\n return result\n } catch (error) {\n await options.sink.record(actionEvent({\n ctx,\n request: ctx.request,\n type: 'action.failed',\n subject: options.subject,\n occurredAt: startedAt,\n includeInputPreview: options.includeInputPreview,\n message: error instanceof Error ? error.message : 'Integration action failed.',\n }))\n throw error\n }\n },\n }\n}\n\nexport function sanitizeAuditConnection(connection: IntegrationConnection): Record<string, unknown> {\n return {\n id: connection.id,\n owner: connection.owner,\n providerId: connection.providerId,\n connectorId: connection.connectorId,\n status: connection.status,\n grantedScopes: connection.grantedScopes,\n account: connection.account,\n hasSecretRef: Boolean(connection.secretRef),\n createdAt: connection.createdAt,\n updatedAt: connection.updatedAt,\n expiresAt: connection.expiresAt,\n lastUsedAt: connection.lastUsedAt,\n }\n}\n\nfunction actionEvent(input: {\n ctx: IntegrationGuardContext\n request: IntegrationActionRequest\n result?: IntegrationActionResult\n type: 'action.invoked' | 'action.failed'\n subject?: IntegrationActor\n occurredAt: Date\n includeInputPreview?: boolean\n message?: string\n}): IntegrationAuditEvent {\n return createIntegrationAuditEvent({\n type: input.type,\n occurredAt: input.occurredAt,\n actor: input.subject ?? input.ctx.connection.owner,\n connectionId: input.ctx.connection.id,\n providerId: input.ctx.connection.providerId,\n connectorId: input.ctx.connection.connectorId,\n action: input.request.action,\n risk: input.ctx.action?.risk,\n dataClass: input.ctx.action?.dataClass,\n ok: input.result?.ok ?? false,\n message: input.message,\n metadata: {\n idempotencyKey: input.request.idempotencyKey,\n dryRun: input.request.dryRun,\n externalId: input.result?.externalId,\n warnings: input.result?.warnings,\n inputPreview: input.includeInputPreview ? redactUnknown(input.request.input) : undefined,\n },\n })\n}\n\nfunction matchesFilter(event: IntegrationAuditEvent, filter: IntegrationAuditFilter): boolean {\n if (filter.type && event.type !== filter.type) return false\n if (filter.actor && (!event.actor || event.actor.type !== filter.actor.type || event.actor.id !== filter.actor.id)) return false\n if (filter.connectionId && event.connectionId !== filter.connectionId) return false\n if (filter.providerId && event.providerId !== filter.providerId) return false\n if (filter.connectorId && event.connectorId !== filter.connectorId) return false\n if (filter.action && event.action !== filter.action) return false\n return true\n}\n\nfunction redactUnknown(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactUnknown)\n if (!value || typeof value !== 'object') return value\n const out: Record<string, unknown> = {}\n for (const [key, child] of Object.entries(value)) {\n if (/token|secret|password|authorization|api[_-]?key|credential|refresh/i.test(key)) {\n out[key] = '[REDACTED]'\n } else {\n out[key] = redactUnknown(child)\n }\n }\n return out\n}\n","import { createHash } from 'node:crypto'\nimport type {\n IntegrationActor,\n IntegrationApprovalRequest,\n IntegrationGuardContext,\n IntegrationPolicyDecision,\n IntegrationPolicyEngine,\n} from './index.js'\nimport type { IntegrationAuditSink } from './audit.js'\nimport { createIntegrationAuditEvent } from './audit.js'\n\nexport type IntegrationApprovalStatus = 'pending' | 'approved' | 'denied' | 'expired'\n\nexport interface IntegrationApprovalRecord {\n id: string\n request: IntegrationApprovalRequest\n status: IntegrationApprovalStatus\n requestedAt: string\n resolvedAt?: string\n resolvedBy?: IntegrationActor\n reason?: string\n expiresAt?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationApprovalStore {\n get(approvalId: string): Promise<IntegrationApprovalRecord | undefined> | IntegrationApprovalRecord | undefined\n put(record: IntegrationApprovalRecord): Promise<void> | void\n list(filter?: IntegrationApprovalFilter): Promise<IntegrationApprovalRecord[]> | IntegrationApprovalRecord[]\n}\n\nexport interface IntegrationApprovalFilter {\n status?: IntegrationApprovalStatus\n connectionId?: string\n connectorId?: string\n action?: string\n actor?: IntegrationActor\n}\n\nexport interface ApprovalBackedPolicyOptions {\n base: IntegrationPolicyEngine\n store: IntegrationApprovalStore\n audit?: IntegrationAuditSink\n now?: () => Date\n approvalTtlMs?: number\n}\n\nexport class InMemoryIntegrationApprovalStore implements IntegrationApprovalStore {\n private readonly records = new Map<string, IntegrationApprovalRecord>()\n\n get(approvalId: string): IntegrationApprovalRecord | undefined {\n return this.records.get(approvalId)\n }\n\n put(record: IntegrationApprovalRecord): void {\n this.records.set(record.id, record)\n }\n\n list(filter: IntegrationApprovalFilter = {}): IntegrationApprovalRecord[] {\n return [...this.records.values()].filter((record) => matchesFilter(record, filter))\n }\n}\n\nexport class ApprovalBackedPolicyEngine implements IntegrationPolicyEngine {\n private readonly base: IntegrationPolicyEngine\n private readonly store: IntegrationApprovalStore\n private readonly audit: IntegrationAuditSink | undefined\n private readonly now: () => Date\n private readonly approvalTtlMs: number | undefined\n\n constructor(options: ApprovalBackedPolicyOptions) {\n this.base = options.base\n this.store = options.store\n this.audit = options.audit\n this.now = options.now ?? (() => new Date())\n this.approvalTtlMs = options.approvalTtlMs\n }\n\n async decide(ctx: IntegrationGuardContext & { subject: IntegrationActor }): Promise<IntegrationPolicyDecision> {\n const approved = await this.findApprovedRecord(ctx)\n if (approved) return { decision: 'allow', reason: `Approved by ${approved.resolvedBy?.type ?? 'actor'} ${approved.resolvedBy?.id ?? 'unknown'}.`, metadata: { approvalId: approved.id } }\n\n const decision = await this.base.decide(ctx)\n if (decision.decision !== 'require_approval') return decision\n\n const requestedAt = decision.approval.requestedAt\n const expiresAt = this.approvalTtlMs ? new Date(Date.parse(requestedAt) + this.approvalTtlMs).toISOString() : undefined\n const record: IntegrationApprovalRecord = {\n id: decision.approval.id,\n request: decision.approval,\n status: 'pending',\n requestedAt,\n expiresAt,\n metadata: { ...(decision.metadata ?? {}), inputHash: approvalInputHash(ctx.request.input) },\n }\n await this.store.put(record)\n await this.audit?.record(createIntegrationAuditEvent({\n type: 'approval.requested',\n actor: ctx.subject,\n connectionId: ctx.connection.id,\n providerId: ctx.connection.providerId,\n connectorId: ctx.connection.connectorId,\n action: ctx.request.action,\n risk: ctx.action?.risk,\n dataClass: ctx.action?.dataClass,\n message: decision.reason,\n metadata: { approvalId: record.id },\n now: this.now,\n }))\n return decision\n }\n\n private async findApprovedRecord(ctx: IntegrationGuardContext & { subject: IntegrationActor }): Promise<IntegrationApprovalRecord | undefined> {\n const approvalId = typeof ctx.request.metadata?.approvalId === 'string' ? ctx.request.metadata.approvalId : undefined\n if (!approvalId) return undefined\n const record = await this.store.get(approvalId)\n if (!record || record.status !== 'approved') return undefined\n if (record.expiresAt && Date.parse(record.expiresAt) <= this.now().getTime()) {\n await this.store.put({ ...record, status: 'expired' })\n return undefined\n }\n if (!approvalMatches(record, ctx)) return undefined\n return record\n }\n}\n\nexport function createApprovalBackedPolicyEngine(options: ApprovalBackedPolicyOptions): ApprovalBackedPolicyEngine {\n return new ApprovalBackedPolicyEngine(options)\n}\n\nexport async function resolveIntegrationApproval(input: {\n store: IntegrationApprovalStore\n approvalId: string\n approved: boolean\n resolvedBy: IntegrationActor\n reason?: string\n metadata?: Record<string, unknown>\n audit?: IntegrationAuditSink\n now?: () => Date\n}): Promise<IntegrationApprovalRecord> {\n const record = await input.store.get(input.approvalId)\n if (!record) throw new Error(`Approval ${input.approvalId} not found.`)\n const now = input.now ?? (() => new Date())\n const next: IntegrationApprovalRecord = {\n ...record,\n status: input.approved ? 'approved' : 'denied',\n resolvedAt: now().toISOString(),\n resolvedBy: input.resolvedBy,\n reason: input.reason,\n metadata: { ...(record.metadata ?? {}), ...(input.metadata ?? {}) },\n }\n await input.store.put(next)\n await input.audit?.record(createIntegrationAuditEvent({\n type: 'approval.resolved',\n actor: input.resolvedBy,\n connectionId: record.request.connectionId,\n providerId: record.request.providerId,\n connectorId: record.request.connectorId,\n action: record.request.action,\n risk: record.request.risk,\n dataClass: record.request.dataClass,\n ok: input.approved,\n message: input.reason,\n metadata: { approvalId: record.id, status: next.status },\n now,\n }))\n return next\n}\n\nfunction approvalMatches(record: IntegrationApprovalRecord, ctx: IntegrationGuardContext & { subject: IntegrationActor }): boolean {\n return record.request.connectionId === ctx.connection.id\n && record.request.providerId === ctx.connection.providerId\n && record.request.connectorId === ctx.connection.connectorId\n && record.request.action === ctx.request.action\n && record.request.actor.type === ctx.subject.type\n && record.request.actor.id === ctx.subject.id\n && record.metadata?.inputHash === approvalInputHash(ctx.request.input)\n}\n\nfunction matchesFilter(record: IntegrationApprovalRecord, filter: IntegrationApprovalFilter): boolean {\n if (filter.status && record.status !== filter.status) return false\n if (filter.connectionId && record.request.connectionId !== filter.connectionId) return false\n if (filter.connectorId && record.request.connectorId !== filter.connectorId) return false\n if (filter.action && record.request.action !== filter.action) return false\n if (filter.actor && (record.request.actor.type !== filter.actor.type || record.request.actor.id !== filter.actor.id)) return false\n return true\n}\n\nfunction approvalInputHash(input: unknown): string {\n return createHash('sha256').update(JSON.stringify(input ?? null)).digest('base64url')\n}\n","import type {\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorTrigger,\n} from './index.js'\n\nexport const CANONICAL_INTEGRATION_ACTIONS = {\n googleCalendarEventsList: 'google-calendar.events.list',\n googleCalendarEventsCreate: 'google-calendar.events.create',\n gmailMessagesSearch: 'gmail.messages.search',\n gmailMessagesSend: 'gmail.messages.send',\n googleDriveFilesSearch: 'google-drive.files.search',\n googleDriveFilesRead: 'google-drive.files.read',\n githubRepositoriesGet: 'github.repositories.get',\n githubIssuesSearch: 'github.issues.search',\n githubIssuesCreate: 'github.issues.create',\n githubPullRequestsComment: 'github.pull-requests.comment',\n slackChannelsList: 'slack.channels.list',\n slackMessagesSearch: 'slack.messages.search',\n slackMessagesPost: 'slack.messages.post',\n providerHttpRequest: 'provider.http.request',\n} as const\n\nexport type CanonicalIntegrationActionId =\n typeof CANONICAL_INTEGRATION_ACTIONS[keyof typeof CANONICAL_INTEGRATION_ACTIONS]\n\nexport interface CanonicalLaunchConnectorOptions {\n providerId?: string\n includeProviderPassthrough?: boolean\n}\n\nexport function buildCanonicalLaunchConnectors(options: CanonicalLaunchConnectorOptions = {}): IntegrationConnector[] {\n const providerId = options.providerId ?? 'tangle-platform'\n const connectors = [\n googleCalendarConnector(providerId),\n gmailConnector(providerId),\n googleDriveConnector(providerId),\n githubConnector(providerId),\n slackConnector(providerId),\n ]\n if (!options.includeProviderPassthrough) return connectors\n return connectors.map((connector) => ({\n ...connector,\n actions: [...connector.actions, providerPassthroughAction(connector.id)],\n }))\n}\n\nexport function canonicalActionConnectorId(actionId: string): string | undefined {\n if (actionId.startsWith('google-calendar.')) return 'google-calendar'\n if (actionId.startsWith('gmail.')) return 'gmail'\n if (actionId.startsWith('google-drive.')) return 'google-drive'\n if (actionId.startsWith('github.')) return 'github'\n if (actionId.startsWith('slack.')) return 'slack'\n if (actionId === CANONICAL_INTEGRATION_ACTIONS.providerHttpRequest) return undefined\n return actionId.split('.')[0]\n}\n\nfunction googleCalendarConnector(providerId: string): IntegrationConnector {\n return {\n id: 'google-calendar',\n providerId,\n title: 'Google Calendar',\n category: 'calendar',\n auth: 'oauth2',\n scopes: ['https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/calendar.events'],\n actions: [\n {\n id: CANONICAL_INTEGRATION_ACTIONS.googleCalendarEventsList,\n title: 'List calendar events',\n risk: 'read',\n requiredScopes: ['https://www.googleapis.com/auth/calendar.readonly'],\n dataClass: 'private',\n description: 'Read events from a Google Calendar over a bounded time range.',\n inputSchema: objectSchema({\n calendarId: { type: 'string', default: 'primary' },\n timeMin: { type: 'string', description: 'RFC3339 lower bound.' },\n timeMax: { type: 'string', description: 'RFC3339 upper bound.' },\n }, ['timeMin', 'timeMax']),\n },\n {\n id: CANONICAL_INTEGRATION_ACTIONS.googleCalendarEventsCreate,\n title: 'Create calendar event',\n risk: 'write',\n requiredScopes: ['https://www.googleapis.com/auth/calendar.events'],\n dataClass: 'private',\n approvalRequired: true,\n description: 'Create an event on a Google Calendar after user approval.',\n inputSchema: objectSchema({\n calendarId: { type: 'string', default: 'primary' },\n start: { type: 'string', description: 'RFC3339 start time.' },\n end: { type: 'string', description: 'RFC3339 end time.' },\n summary: { type: 'string' },\n description: { type: 'string' },\n attendees: { type: 'array', items: { type: 'string' } },\n }, ['start', 'end', 'summary']),\n },\n ],\n metadata: { source: 'canonical-launch', supportTier: 'setupReady' },\n }\n}\n\nfunction gmailConnector(providerId: string): IntegrationConnector {\n return {\n id: 'gmail',\n providerId,\n title: 'Gmail',\n category: 'email',\n auth: 'oauth2',\n scopes: ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.send'],\n actions: [\n {\n id: CANONICAL_INTEGRATION_ACTIONS.gmailMessagesSearch,\n title: 'Search Gmail messages',\n risk: 'read',\n requiredScopes: ['https://www.googleapis.com/auth/gmail.readonly'],\n dataClass: 'private',\n description: 'Search user Gmail messages and return bounded message metadata/snippets.',\n inputSchema: objectSchema({ query: { type: 'string' }, maxResults: { type: 'integer', minimum: 1, maximum: 50 } }, ['query']),\n },\n {\n id: CANONICAL_INTEGRATION_ACTIONS.gmailMessagesSend,\n title: 'Send Gmail message',\n risk: 'write',\n requiredScopes: ['https://www.googleapis.com/auth/gmail.send'],\n dataClass: 'private',\n approvalRequired: true,\n description: 'Send an email from the user account after approval.',\n inputSchema: objectSchema({\n to: { type: 'array', items: { type: 'string' } },\n subject: { type: 'string' },\n body: { type: 'string' },\n }, ['to', 'subject', 'body']),\n },\n ],\n triggers: [{\n id: 'gmail.messages.received',\n title: 'Gmail message received',\n requiredScopes: ['https://www.googleapis.com/auth/gmail.readonly'],\n dataClass: 'private',\n description: 'Triggered when a new matching Gmail message is received.',\n }],\n metadata: { source: 'canonical-launch', supportTier: 'setupReady' },\n }\n}\n\nfunction googleDriveConnector(providerId: string): IntegrationConnector {\n return {\n id: 'google-drive',\n providerId,\n title: 'Google Drive',\n category: 'storage',\n auth: 'oauth2',\n scopes: ['https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.file'],\n actions: [\n {\n id: CANONICAL_INTEGRATION_ACTIONS.googleDriveFilesSearch,\n title: 'Search Drive files',\n risk: 'read',\n requiredScopes: ['https://www.googleapis.com/auth/drive.readonly'],\n dataClass: 'private',\n description: 'Search user-visible Google Drive files.',\n inputSchema: objectSchema({ query: { type: 'string' }, maxResults: { type: 'integer', minimum: 1, maximum: 50 } }, ['query']),\n },\n {\n id: CANONICAL_INTEGRATION_ACTIONS.googleDriveFilesRead,\n title: 'Read Drive file',\n risk: 'read',\n requiredScopes: ['https://www.googleapis.com/auth/drive.readonly'],\n dataClass: 'private',\n description: 'Read metadata and content for an authorized Drive file.',\n inputSchema: objectSchema({ fileId: { type: 'string' } }, ['fileId']),\n },\n ],\n metadata: { source: 'canonical-launch', supportTier: 'setupReady' },\n }\n}\n\nfunction githubConnector(providerId: string): IntegrationConnector {\n return {\n id: 'github',\n providerId,\n title: 'GitHub',\n category: 'workflow',\n auth: 'oauth2',\n scopes: ['repo', 'read:user'],\n actions: [\n readAction(CANONICAL_INTEGRATION_ACTIONS.githubRepositoriesGet, 'Read repository metadata', ['repo'], objectSchema({ owner: { type: 'string' }, repo: { type: 'string' } }, ['owner', 'repo'])),\n readAction(CANONICAL_INTEGRATION_ACTIONS.githubIssuesSearch, 'Search issues and pull requests', ['repo'], objectSchema({ query: { type: 'string' }, limit: { type: 'integer', minimum: 1, maximum: 50 } }, ['query'])),\n writeAction(CANONICAL_INTEGRATION_ACTIONS.githubIssuesCreate, 'Create issue', ['repo'], objectSchema({ owner: { type: 'string' }, repo: { type: 'string' }, title: { type: 'string' }, body: { type: 'string' } }, ['owner', 'repo', 'title'])),\n writeAction(CANONICAL_INTEGRATION_ACTIONS.githubPullRequestsComment, 'Comment on pull request', ['repo'], objectSchema({ owner: { type: 'string' }, repo: { type: 'string' }, pullNumber: { type: 'integer' }, body: { type: 'string' } }, ['owner', 'repo', 'pullNumber', 'body'])),\n ],\n metadata: { source: 'canonical-launch', supportTier: 'setupReady' },\n }\n}\n\nfunction slackConnector(providerId: string): IntegrationConnector {\n return {\n id: 'slack',\n providerId,\n title: 'Slack',\n category: 'chat',\n auth: 'oauth2',\n scopes: ['channels:read', 'search:read', 'chat:write'],\n actions: [\n readAction(CANONICAL_INTEGRATION_ACTIONS.slackChannelsList, 'List Slack channels', ['channels:read'], objectSchema({ limit: { type: 'integer', minimum: 1, maximum: 200 } })),\n readAction(CANONICAL_INTEGRATION_ACTIONS.slackMessagesSearch, 'Search Slack messages', ['search:read'], objectSchema({ query: { type: 'string' }, count: { type: 'integer', minimum: 1, maximum: 50 } }, ['query'])),\n writeAction(CANONICAL_INTEGRATION_ACTIONS.slackMessagesPost, 'Post Slack message', ['chat:write'], objectSchema({ channel: { type: 'string' }, text: { type: 'string' }, blocks: { type: 'array' } }, ['channel', 'text'])),\n ],\n triggers: [trigger('slack.message.posted', 'Slack message posted', ['channels:read'])],\n metadata: { source: 'canonical-launch', supportTier: 'setupReady' },\n }\n}\n\nfunction readAction(id: string, title: string, scopes: string[], inputSchema: unknown): IntegrationConnectorAction {\n return { id, title, risk: 'read', requiredScopes: scopes, dataClass: 'private', inputSchema }\n}\n\nfunction writeAction(id: string, title: string, scopes: string[], inputSchema: unknown): IntegrationConnectorAction {\n return { id, title, risk: 'write', requiredScopes: scopes, dataClass: 'private', approvalRequired: true, inputSchema }\n}\n\nfunction trigger(id: string, title: string, scopes: string[]): IntegrationConnectorTrigger {\n return { id, title, requiredScopes: scopes, dataClass: 'private' }\n}\n\nfunction providerPassthroughAction(connectorId: string): IntegrationConnectorAction {\n return {\n id: CANONICAL_INTEGRATION_ACTIONS.providerHttpRequest,\n title: 'Provider HTTP request',\n risk: 'write',\n requiredScopes: [],\n dataClass: 'sensitive',\n approvalRequired: true,\n description: `Controlled provider-native passthrough for ${connectorId}. Disabled by default by platform policy.`,\n inputSchema: objectSchema({\n method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },\n path: { type: 'string' },\n query: { type: 'object' },\n body: { type: 'object' },\n }, ['method', 'path']),\n }\n}\n\nfunction objectSchema(properties: Record<string, unknown>, required: string[] = []): Record<string, unknown> {\n return { type: 'object', additionalProperties: false, properties, required }\n}\n","import type { IntegrationSandboxBundle } from './runtime.js'\n\nexport const DEFAULT_INTEGRATION_BRIDGE_ENV = 'TANGLE_INTEGRATION_BUNDLE'\n\nexport interface IntegrationBridgePayload {\n version: 1\n manifestId: string\n subject: IntegrationSandboxBundle['subject']\n expiresAt: string\n tools: IntegrationBridgeToolBinding[]\n}\n\nexport interface IntegrationBridgeToolBinding {\n name: string\n title: string\n connectorId: string\n connectionId: string\n action: string\n risk: string\n dataClass: string\n requiredScopes: string[]\n capabilityToken: string\n}\n\nexport function buildIntegrationBridgePayload(bundle: IntegrationSandboxBundle): IntegrationBridgePayload {\n return {\n version: 1,\n manifestId: bundle.manifestId,\n subject: bundle.subject,\n expiresAt: bundle.expiresAt,\n tools: bundle.tools.flatMap((tool) => {\n const binding = bundle.capabilities.find((candidate) =>\n candidate.connectorId === tool.connectorId\n && candidate.connectionId\n && candidate.allowedActions.includes(tool.action.id)\n )\n if (!binding) return []\n return [{\n name: tool.name,\n title: tool.title,\n connectorId: tool.connectorId,\n connectionId: binding.connectionId,\n action: tool.action.id,\n risk: tool.risk,\n dataClass: tool.dataClass,\n requiredScopes: tool.requiredScopes,\n capabilityToken: binding.capability.token,\n }]\n }),\n }\n}\n\nexport function encodeIntegrationBridgePayload(payload: IntegrationBridgePayload): string {\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')\n}\n\nexport function decodeIntegrationBridgePayload(encoded: string): IntegrationBridgePayload {\n const parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as unknown\n assertBridgePayload(parsed)\n return parsed\n}\n\nexport function buildIntegrationBridgeEnvironment(\n bundle: IntegrationSandboxBundle,\n options: { envVar?: string } = {},\n): Record<string, string> {\n const envVar = options.envVar ?? DEFAULT_INTEGRATION_BRIDGE_ENV\n return {\n [envVar]: encodeIntegrationBridgePayload(buildIntegrationBridgePayload(bundle)),\n }\n}\n\nexport function parseIntegrationBridgeEnvironment(\n env: Record<string, string | undefined>,\n options: { envVar?: string } = {},\n): IntegrationBridgePayload {\n const envVar = options.envVar ?? DEFAULT_INTEGRATION_BRIDGE_ENV\n const encoded = env[envVar]\n if (!encoded) throw new Error(`Missing ${envVar}.`)\n return decodeIntegrationBridgePayload(encoded)\n}\n\nexport function redactIntegrationBridgePayload(payload: IntegrationBridgePayload): IntegrationBridgePayload {\n return {\n ...payload,\n tools: payload.tools.map((tool) => ({\n ...tool,\n capabilityToken: '[REDACTED]',\n })),\n }\n}\n\nfunction assertBridgePayload(value: unknown): asserts value is IntegrationBridgePayload {\n if (!value || typeof value !== 'object') throw new Error('Invalid integration bridge payload.')\n const payload = value as Partial<IntegrationBridgePayload>\n if (payload.version !== 1) throw new Error('Unsupported integration bridge payload version.')\n if (typeof payload.manifestId !== 'string') throw new Error('Invalid integration bridge manifestId.')\n if (typeof payload.expiresAt !== 'string') throw new Error('Invalid integration bridge expiresAt.')\n if (!Array.isArray(payload.tools)) throw new Error('Invalid integration bridge tools.')\n}\n","import {\n DEFAULT_INTEGRATION_BRIDGE_ENV,\n parseIntegrationBridgeEnvironment,\n type IntegrationBridgePayload,\n type IntegrationBridgeToolBinding,\n} from './bridge.js'\nimport { IntegrationRuntimeError, normalizeIntegrationError } from './errors.js'\n\nexport interface TangleIntegrationsClientOptions {\n endpoint: string\n bridge?: IntegrationBridgePayload\n env?: Record<string, string | undefined>\n envVar?: string\n fetchImpl?: typeof fetch\n getCapabilityToken?: (tool: IntegrationBridgeToolBinding) => string | Promise<string>\n}\n\nexport interface TangleIntegrationInvokeInput<TInput = unknown> {\n tool: string\n input?: TInput\n idempotencyKey?: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface TangleIntegrationInvokeResult<TOutput = unknown> {\n status: 'ok' | 'approval_required' | 'failed'\n action: string\n output?: TOutput\n approval?: unknown\n error?: string\n metadata?: Record<string, unknown>\n}\n\nexport class TangleIntegrationsClient {\n private readonly endpoint: string\n private readonly bridge: IntegrationBridgePayload\n private readonly fetchImpl: typeof fetch\n private readonly getCapabilityToken: (tool: IntegrationBridgeToolBinding) => string | Promise<string>\n\n constructor(options: TangleIntegrationsClientOptions) {\n this.endpoint = options.endpoint.replace(/\\/$/, '')\n this.bridge = options.bridge ?? parseIntegrationBridgeEnvironment(\n options.env ?? readProcessEnv(),\n { envVar: options.envVar ?? DEFAULT_INTEGRATION_BRIDGE_ENV },\n )\n this.fetchImpl = options.fetchImpl ?? fetch\n this.getCapabilityToken = options.getCapabilityToken ?? ((tool) => tool.capabilityToken)\n }\n\n tools(): IntegrationBridgeToolBinding[] {\n return [...this.bridge.tools]\n }\n\n findTool(toolOrAction: string): IntegrationBridgeToolBinding {\n const found = this.bridge.tools.find((tool) =>\n tool.name === toolOrAction ||\n tool.action === toolOrAction ||\n `${tool.connectorId}.${tool.action}` === toolOrAction\n )\n if (!found) {\n throw new IntegrationRuntimeError({\n code: 'action_not_found',\n message: `Integration tool ${toolOrAction} is not available in this runtime.`,\n metadata: { available: this.bridge.tools.map((tool) => ({ name: tool.name, action: tool.action, connectorId: tool.connectorId })) },\n })\n }\n return found\n }\n\n async invoke<TOutput = unknown, TInput = unknown>(input: TangleIntegrationInvokeInput<TInput>): Promise<TangleIntegrationInvokeResult<TOutput>> {\n try {\n const tool = this.findTool(input.tool)\n const token = await this.getCapabilityToken(tool)\n const response = await this.fetchImpl(`${this.endpoint}/v1/integrations/invoke`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n action: tool.action,\n input: input.input,\n idempotencyKey: input.idempotencyKey ?? defaultIdempotencyKey(tool.action),\n dryRun: input.dryRun,\n metadata: input.metadata,\n }),\n })\n const json = await response.json().catch(() => undefined) as TangleIntegrationInvokeResult<TOutput> | undefined\n if (!response.ok && !json) {\n return { status: 'failed', action: tool.action, error: `Integration invoke failed with HTTP ${response.status}` }\n }\n return json ?? { status: 'failed', action: tool.action, error: 'Integration invoke returned an empty response.' }\n } catch (error) {\n const normalized = normalizeIntegrationError(error)\n return { status: 'failed', action: input.tool, error: normalized.message, metadata: { code: normalized.code, userAction: normalized.userAction } }\n }\n }\n}\n\nexport function createTangleIntegrationsClient(options: TangleIntegrationsClientOptions): TangleIntegrationsClient {\n return new TangleIntegrationsClient(options)\n}\n\nfunction defaultIdempotencyKey(action: string): string {\n return `${action}:${Date.now()}:${Math.random().toString(36).slice(2)}`\n}\n\nfunction readProcessEnv(): Record<string, string | undefined> {\n if (typeof process !== 'undefined' && process.env) return process.env\n return {}\n}\n","import type {\n IntegrationConnector,\n IntegrationConnectorAction,\n} from './index.js'\nimport type {\n IntegrationManifest,\n IntegrationManifestResolution,\n IntegrationRequirement,\n} from './runtime.js'\n\nexport interface ConsentSummary {\n title: string\n body: string\n bullets: string[]\n primaryAction: string\n risk: 'read' | 'write' | 'destructive'\n connectorIds: string[]\n}\n\nexport interface RenderConsentOptions {\n appName?: string\n connectors?: IntegrationConnector[]\n}\n\nexport function renderConsentSummary(\n manifestOrResolution: IntegrationManifest | IntegrationManifestResolution,\n options: RenderConsentOptions = {},\n): ConsentSummary {\n const manifest = 'manifest' in manifestOrResolution ? manifestOrResolution.manifest : manifestOrResolution\n const appName = options.appName ?? manifest.title ?? manifest.id\n const requirements = manifest.requirements\n const risk = aggregateRisk(requirements, options.connectors)\n const connectorIds = unique(requirements.map((requirement) => requirement.connectorId))\n const first = requirements[0]\n const body = first ? sentenceForRequirement(appName, first) : `${appName} does not request integrations.`\n return {\n title: `${appName} wants to use ${humanList(connectorIds.map(titleize))}`,\n body,\n bullets: requirements.map((requirement) => bulletForRequirement(requirement, options.connectors)),\n primaryAction: risk === 'read' ? 'Allow access' : risk === 'write' ? 'Review and allow' : 'Review destructive access',\n risk,\n connectorIds,\n }\n}\n\nexport function renderApprovalCopy(input: {\n appName: string\n connectorTitle: string\n action: IntegrationConnectorAction\n approvalId?: string\n}): ConsentSummary {\n return {\n title: `${input.appName} wants to ${input.action.title.toLowerCase()}`,\n body: `${input.appName} is requesting permission to run \"${input.action.title}\" on ${input.connectorTitle}.`,\n bullets: [\n `Risk: ${input.action.risk}`,\n `Data: ${input.action.dataClass}`,\n ...(input.approvalId ? [`Approval id: ${input.approvalId}`] : []),\n ],\n primaryAction: input.action.risk === 'read' ? 'Allow' : 'Approve action',\n risk: input.action.risk,\n connectorIds: [],\n }\n}\n\nfunction sentenceForRequirement(appName: string, requirement: IntegrationRequirement): string {\n if (requirement.connectorId === 'google-calendar' && requirement.mode === 'read') {\n return `${appName} wants to read your Google Calendar to find schedule-aware recommendations.`\n }\n if (requirement.connectorId === 'google-calendar' && requirement.mode === 'write') {\n return `${appName} wants to create or update Google Calendar events after your approval.`\n }\n if (requirement.mode === 'read') return `${appName} wants to read ${titleize(requirement.connectorId)} data.`\n if (requirement.mode === 'write') return `${appName} wants to write ${titleize(requirement.connectorId)} data after approval.`\n return `${appName} wants to subscribe to ${titleize(requirement.connectorId)} events.`\n}\n\nfunction bulletForRequirement(requirement: IntegrationRequirement, connectors: IntegrationConnector[] = []): string {\n const connector = connectors.find((candidate) => candidate.id === requirement.connectorId)\n const actions = requirement.requiredActions?.length\n ? requirement.requiredActions.map((id) => connector?.actions.find((action) => action.id === id)?.title ?? id)\n : requirement.requiredTriggers ?? []\n return `${titleize(requirement.connectorId)}: ${requirement.reason}${actions.length ? ` (${actions.join(', ')})` : ''}`\n}\n\nfunction aggregateRisk(requirements: IntegrationRequirement[], connectors: IntegrationConnector[] = []): 'read' | 'write' | 'destructive' {\n let rank = 0\n for (const requirement of requirements) {\n if (requirement.mode === 'write') rank = Math.max(rank, 1)\n const connector = connectors.find((candidate) => candidate.id === requirement.connectorId)\n for (const actionId of requirement.requiredActions ?? []) {\n const risk = connector?.actions.find((action) => action.id === actionId)?.risk\n if (risk === 'write') rank = Math.max(rank, 1)\n if (risk === 'destructive') rank = Math.max(rank, 2)\n }\n }\n return rank === 2 ? 'destructive' : rank === 1 ? 'write' : 'read'\n}\n\nfunction humanList(values: string[]): string {\n if (values.length <= 1) return values[0] ?? 'integrations'\n if (values.length === 2) return `${values[0]} and ${values[1]}`\n return `${values.slice(0, -1).join(', ')}, and ${values.at(-1)}`\n}\n\nfunction titleize(value: string): string {\n return value.split(/[-_.]/g).filter(Boolean).map((part) => part[0]!.toUpperCase() + part.slice(1)).join(' ')\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n","import type {\n CapabilityMutationResult,\n CapabilityReadResult,\n ConnectorAdapter,\n ConnectorInvocation,\n ResolvedDataSource,\n} from './connectors/types.js'\nimport type {\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationProvider,\n IntegrationProviderKind,\n} from './index.js'\nimport { IntegrationError } from './index.js'\nimport type { IntegrationCatalogSource } from './registry.js'\n\nexport interface ConnectorAdapterProviderOptions {\n id?: string\n kind?: IntegrationProviderKind\n adapters: ConnectorAdapter[]\n resolveDataSource: (connection: IntegrationConnection) => Promise<ResolvedDataSource> | ResolvedDataSource\n now?: () => Date\n}\n\nexport function createConnectorAdapterProvider(options: ConnectorAdapterProviderOptions): IntegrationProvider {\n const providerId = options.id ?? 'first-party'\n const now = options.now ?? (() => new Date())\n const adapters = new Map<string, ConnectorAdapter>()\n for (const adapter of options.adapters) {\n adapters.set(adapter.manifest.kind, adapter)\n }\n return {\n id: providerId,\n kind: options.kind ?? 'first_party',\n listConnectors: () => [...adapters.values()].map((adapter) => manifestToConnector(providerId, adapter)),\n async invokeAction(connection, request) {\n const adapter = adapters.get(connection.connectorId)\n if (!adapter) {\n throw new IntegrationError(`Connector adapter ${connection.connectorId} not found.`, 'connector_not_found')\n }\n const capability = adapter.manifest.capabilities.find((candidate) => candidate.name === request.action)\n if (!capability) {\n throw new IntegrationError(`Capability ${request.action} is not defined by ${connection.connectorId}.`, 'action_not_found')\n }\n const source = await options.resolveDataSource(connection)\n const invocation: ConnectorInvocation = {\n source,\n capabilityName: request.action,\n args: toRecord(request.input),\n idempotencyKey: request.idempotencyKey ?? `idem_${connection.id}_${request.action}_${now().getTime()}`,\n expectedEtag: typeof request.metadata?.expectedEtag === 'string' ? request.metadata.expectedEtag : undefined,\n callSessionId: typeof request.metadata?.callSessionId === 'string' ? request.metadata.callSessionId : undefined,\n }\n if (capability.class === 'read') {\n if (!adapter.executeRead) {\n throw new IntegrationError(`Connector ${connection.connectorId} does not implement reads.`, 'action_not_found')\n }\n const result = await adapter.executeRead(invocation)\n return readResultToAction(request, result)\n }\n if (capability.class === 'mutation') {\n if (!adapter.executeMutation) {\n throw new IntegrationError(`Connector ${connection.connectorId} does not implement mutations.`, 'action_not_found')\n }\n const result = await adapter.executeMutation(invocation)\n return mutationResultToAction(request, result)\n }\n throw new IntegrationError(`Capability ${request.action} is not invokable as an action.`, 'action_not_found')\n },\n }\n}\n\nexport function adapterManifestsToConnectors(\n adapters: ConnectorAdapter[],\n providerId = 'first-party',\n): IntegrationConnector[] {\n return adapters.map((adapter) => manifestToConnector(providerId, adapter))\n}\n\nexport function createConnectorAdapterCatalogSource(options: {\n id?: string\n providerId?: string\n adapters: ConnectorAdapter[]\n precedence?: number\n}): IntegrationCatalogSource {\n const sourceId = options.id ?? 'first-party'\n return {\n id: sourceId,\n precedence: options.precedence,\n connectors: adapterManifestsToConnectors(options.adapters, options.providerId ?? sourceId),\n }\n}\n\nexport function manifestToConnector(providerId: string, adapter: ConnectorAdapter): IntegrationConnector {\n const manifest = adapter.manifest\n return {\n id: manifest.kind,\n providerId,\n title: manifest.displayName,\n category: mapCategory(manifest.category),\n auth: mapAuth(manifest.auth.kind),\n scopes: manifest.auth.kind === 'oauth2' ? manifest.auth.scopes : [],\n actions: manifest.capabilities\n .filter((capability) => capability.class === 'read' || capability.class === 'mutation')\n .map((capability) => ({\n id: capability.name,\n title: titleFromName(capability.name),\n risk: capability.class === 'read' ? 'read' : capability.externalEffect ? 'destructive' : 'write',\n requiredScopes: capability.requiredScopes ?? [],\n dataClass: inferDataClass(manifest.category),\n description: capability.description,\n approvalRequired: capability.class === 'mutation',\n inputSchema: capability.parameters,\n })),\n metadata: {\n source: 'first-party-adapter',\n supportTier: 'firstPartyExecutable',\n executable: true,\n },\n }\n}\n\nfunction readResultToAction(request: IntegrationActionRequest, result: CapabilityReadResult): IntegrationActionResult {\n return {\n ok: true,\n action: request.action,\n output: result.data,\n metadata: {\n etag: result.etag,\n fetchedAt: result.fetchedAt,\n },\n }\n}\n\nfunction mutationResultToAction(request: IntegrationActionRequest, result: CapabilityMutationResult): IntegrationActionResult {\n if (result.status === 'committed') {\n return {\n ok: true,\n action: request.action,\n output: result.data,\n metadata: {\n etagAfter: result.etagAfter,\n committedAt: result.committedAt,\n idempotentReplay: result.idempotentReplay,\n },\n }\n }\n if (result.status === 'conflict') {\n return {\n ok: false,\n action: request.action,\n output: {\n conflict: true,\n message: result.message,\n alternatives: result.alternatives,\n currentState: result.currentState,\n },\n }\n }\n return {\n ok: false,\n action: request.action,\n output: {\n rateLimited: true,\n retryAfterMs: result.retryAfterMs,\n message: result.message,\n },\n }\n}\n\nfunction mapAuth(kind: ConnectorAdapter['manifest']['auth']['kind']): IntegrationConnector['auth'] {\n if (kind === 'oauth2') return 'oauth2'\n if (kind === 'api-key') return 'api_key'\n if (kind === 'none') return 'none'\n return 'custom'\n}\n\nfunction mapCategory(category: ConnectorAdapter['manifest']['category']): IntegrationConnector['category'] {\n if (category === 'comms') return 'chat'\n if (category === 'spreadsheet') return 'database'\n if (category === 'doc') return 'docs'\n if (category === 'commerce') return 'workflow'\n return category === 'other' ? 'other' : category\n}\n\nfunction inferDataClass(category: ConnectorAdapter['manifest']['category']): 'public' | 'internal' | 'private' | 'sensitive' {\n if (category === 'commerce') return 'sensitive'\n if (category === 'webhook') return 'internal'\n return 'private'\n}\n\nfunction titleFromName(name: string): string {\n return name\n .split(/[._-]/g)\n .filter(Boolean)\n .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))\n .join(' ')\n}\n\nfunction toRecord(input: unknown): Record<string, unknown> {\n if (input && typeof input === 'object' && !Array.isArray(input)) return input as Record<string, unknown>\n return {}\n}\n","import { createConnectorAdapterProvider, type ConnectorAdapterProviderOptions } from './adapter-provider.js'\nimport type {\n ConnectorAdapter,\n ConnectorCredentials,\n ResolvedDataSource,\n} from './connectors/types.js'\nimport type {\n IntegrationConnection,\n IntegrationConnectionStore,\n IntegrationProvider,\n SecretRef,\n} from './index.js'\n\nexport interface IntegrationSecretStore {\n get(ref: SecretRef): Promise<ConnectorCredentials | undefined> | ConnectorCredentials | undefined\n put(ref: SecretRef, credentials: ConnectorCredentials): Promise<void> | void\n delete?(ref: SecretRef): Promise<void> | void\n}\n\nexport interface ConnectionCredentialResolverOptions {\n secrets: IntegrationSecretStore\n connections?: IntegrationConnectionStore\n adapters?: ConnectorAdapter[]\n now?: () => Date\n markConnectionError?: (connection: IntegrationConnection, error: Error) => Promise<void> | void\n}\n\nexport class InMemoryIntegrationSecretStore implements IntegrationSecretStore {\n private readonly secrets = new Map<string, ConnectorCredentials>()\n\n get(ref: SecretRef): ConnectorCredentials | undefined {\n return this.secrets.get(secretKey(ref))\n }\n\n put(ref: SecretRef, credentials: ConnectorCredentials): void {\n this.secrets.set(secretKey(ref), credentials)\n }\n\n delete(ref: SecretRef): void {\n this.secrets.delete(secretKey(ref))\n }\n}\n\nexport function createConnectionCredentialResolver(options: ConnectionCredentialResolverOptions) {\n const now = options.now ?? (() => new Date())\n return async function resolveDataSource(connection: IntegrationConnection): Promise<ResolvedDataSource> {\n const credentials = await resolveConnectionCredentials(connection, {\n secrets: options.secrets,\n connections: options.connections,\n adapters: options.adapters,\n now,\n markConnectionError: options.markConnectionError,\n })\n return {\n id: connection.id,\n projectId: String(connection.metadata?.projectId ?? connection.owner.id),\n publishedAgentId: typeof connection.metadata?.publishedAgentId === 'string' ? connection.metadata.publishedAgentId : null,\n kind: connection.connectorId,\n label: connection.account?.displayName ?? connection.account?.email ?? connection.connectorId,\n consistencyModel: typeof connection.metadata?.consistencyModel === 'string' ? connection.metadata.consistencyModel as never : 'authoritative',\n scopes: connection.grantedScopes,\n metadata: connection.metadata ?? {},\n credentials,\n status: connection.status === 'active' ? 'active' : connection.status === 'revoked' ? 'revoked' : 'error',\n }\n }\n}\n\nexport async function resolveConnectionCredentials(input: IntegrationConnection, options: ConnectionCredentialResolverOptions): Promise<ConnectorCredentials> {\n if (input.status !== 'active') throw new Error(`Connection ${input.id} is ${input.status}.`)\n if (!input.secretRef) return { kind: 'none' }\n const current = await options.secrets.get(input.secretRef)\n if (!current) throw new Error(`Secret ${input.secretRef.provider}/${input.secretRef.id} not found.`)\n if (!isExpiredOauth(current, options.now ?? (() => new Date()))) return current\n\n const adapter = options.adapters?.find((candidate) => candidate.manifest.kind === input.connectorId)\n if (!adapter?.refreshToken) return current\n try {\n const refreshed = await adapter.refreshToken(current)\n await options.secrets.put(input.secretRef, refreshed)\n if (options.connections) {\n await options.connections.put({\n ...input,\n status: 'active',\n updatedAt: (options.now?.() ?? new Date()).toISOString(),\n expiresAt: refreshed.kind === 'oauth2' && refreshed.expiresAt ? new Date(refreshed.expiresAt).toISOString() : input.expiresAt,\n })\n }\n return refreshed\n } catch (error) {\n const err = error instanceof Error ? error : new Error('Credential refresh failed.')\n await options.markConnectionError?.(input, err)\n if (options.connections) {\n await options.connections.put({\n ...input,\n status: 'expired',\n updatedAt: (options.now?.() ?? new Date()).toISOString(),\n })\n }\n throw err\n }\n}\n\nexport function createCredentialBackedAdapterProvider(options: Omit<ConnectorAdapterProviderOptions, 'resolveDataSource'> & ConnectionCredentialResolverOptions): IntegrationProvider {\n return createConnectorAdapterProvider({\n ...options,\n resolveDataSource: createConnectionCredentialResolver(options),\n })\n}\n\nexport async function revokeConnection(input: {\n connection: IntegrationConnection\n connections?: IntegrationConnectionStore\n secrets?: IntegrationSecretStore\n now?: () => Date\n}): Promise<IntegrationConnection> {\n if (input.connection.secretRef) await input.secrets?.delete?.(input.connection.secretRef)\n const revoked: IntegrationConnection = {\n ...input.connection,\n status: 'revoked',\n updatedAt: (input.now?.() ?? new Date()).toISOString(),\n }\n await input.connections?.put(revoked)\n return revoked\n}\n\nfunction isExpiredOauth(credentials: ConnectorCredentials, now: () => Date): boolean {\n return credentials.kind === 'oauth2'\n && typeof credentials.expiresAt === 'number'\n && credentials.expiresAt <= now().getTime()\n && Boolean(credentials.refreshToken)\n}\n\nfunction secretKey(ref: SecretRef): string {\n return `${ref.provider}:${ref.id}`\n}\n","/**\n * Workspace capability discovery — answers \"what can this workspace do?\"\n * with a typed list of MCP-shape tool descriptors that the agent runtime\n * can flatten into a planner's tool registry.\n *\n * The agent runtime's gating question is one level above the existing\n * connector catalog (\"which integrations exist?\") and one level below\n * the issued capability-token surface (\"temporarily delegate scope X\n * via this signed token\"). This module bridges the two:\n *\n * discoverWorkspaceCapabilities({ owner, connectors, connections, scopes })\n * → WorkspaceCapability[]\n *\n * A `WorkspaceCapability` is hand-shaped to be cheap to emit alongside a\n * connector manifest and trivial to render into:\n * - an LLM tool-choice JSON array\n * - an MCP `tools/list` response\n * - a UI surface (\"Connect Gmail to enable: send_reply, list_messages…\")\n *\n * What this is NOT:\n * - A capability-token issuer. That stays in IntegrationHub.issueCapability.\n * - A connector registry. That stays in IntegrationRegistry / catalog.\n *\n * Scopes are the load-bearing input: a connector advertises N actions,\n * but only the subset whose `requiredScopes` are a subset of the\n * connection's `grantedScopes` is reachable. The discovery function\n * filters on that automatically.\n *\n * Stability: `@stable` — additions to WorkspaceCapability must be\n * additive and non-breaking.\n */\n\nimport type {\n IntegrationActor,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationConnectorTrigger,\n IntegrationDataClass,\n IntegrationActionRisk,\n IntegrationConnectionStore,\n IntegrationProvider,\n} from './index.js'\n\n/** MCP-shape tool descriptor. Mirrors the\n * [Model Context Protocol tool schema](https://modelcontextprotocol.io/specification)\n * closely enough that consumers can pipe a WorkspaceCapability straight\n * into a `tools/list` response. */\nexport interface WorkspaceToolSchema {\n name: string\n description?: string\n /** JSON-schema describing the action's input. */\n inputSchema?: unknown\n /** Optional JSON-schema describing the action's output. */\n outputSchema?: unknown\n}\n\n/** One discoverable capability — an action a connector exposes that the\n * workspace has the connection + scopes to invoke. */\nexport interface WorkspaceCapability {\n /** Stable, fully-qualified id. Format `<connector-id>.<action-id>`. */\n id: string\n /** Human label safe for UI. */\n title: string\n /** Optional one-line description. */\n description?: string\n /** Connector category for grouping. */\n category: IntegrationConnectorCategory\n /** Connector that hosts this capability. */\n connectorId: string\n /** Provider that hosts this connector (first-party, gateway, …). */\n providerId: string\n /** Underlying action id on the connector. */\n actionId: string\n /** Scopes required to invoke. The discovery function only returns\n * capabilities whose required scopes are a subset of the connection's\n * grantedScopes. */\n scopes: string[]\n /** Risk class — useful for UI (\"write\" / \"destructive\" lights). */\n risk: IntegrationActionRisk\n /** Data class of the action's output, when known. */\n dataClass: IntegrationDataClass\n /** MCP-shape tool schema the agent runtime can register directly. */\n toolSchema: WorkspaceToolSchema\n /** True iff the workspace has an active connection backing this\n * capability. False capabilities (advertised by the connector but\n * not yet connected) are included when `includeUnconnected: true`\n * is passed — useful for \"connect to unlock\" UI affordances. */\n connected: boolean\n /** Connection id backing this capability. Undefined when\n * `connected: false`. */\n connectionId?: string\n /** Whether the action requires explicit approval before invocation. */\n approvalRequired?: boolean\n}\n\n/** Optional inbound trigger surface. Same shape as a capability so the\n * consumer can render both with one component. */\nexport interface WorkspaceTrigger {\n id: string\n title: string\n description?: string\n category: IntegrationConnectorCategory\n connectorId: string\n providerId: string\n triggerId: string\n scopes: string[]\n dataClass: IntegrationDataClass\n connected: boolean\n connectionId?: string\n}\n\nexport interface DiscoverWorkspaceCapabilitiesInput {\n /** Workspace owner. Used to scope the connection lookup when `store`\n * is supplied (the canonical production path). */\n owner: IntegrationActor\n /** Either an explicit connection list (test/fixture path) or a store\n * the function should query for connections by owner. Exactly one\n * of `connections` / `store` MUST be provided. */\n connections?: IntegrationConnection[]\n store?: IntegrationConnectionStore\n /** Either an explicit connector list (test/fixture path) or a set of\n * providers the function should query via `listConnectors()`. */\n connectors?: IntegrationConnector[]\n providers?: IntegrationProvider[]\n /** Include capabilities whose connector is in the catalog but the\n * workspace has no active connection for. Useful to render\n * \"connect to unlock\" affordances. Default: false. */\n includeUnconnected?: boolean\n /** When true, include capabilities even if some required scopes are\n * missing from the connection grant. The default `false` hides such\n * capabilities — the agent runtime never sees them. */\n includeMissingScopes?: boolean\n}\n\nexport interface WorkspaceCapabilityDiscovery {\n capabilities: WorkspaceCapability[]\n triggers: WorkspaceTrigger[]\n /** Counts grouped by connector for telemetry / UI badges. */\n countsByConnector: Record<string, number>\n /** Connectors the workspace is connected to but the planner cannot\n * reach any actions on (e.g., zero scopes granted, or all actions\n * require an additional scope). */\n unreachableConnectors: Array<{ connectorId: string; reason: string }>\n}\n\n/** Resolve workspace-visible capabilities + triggers. Pure with respect\n * to the inputs — caller decides whether to back `connections` and\n * `connectors` with persistent state or static fixtures. */\nexport async function discoverWorkspaceCapabilities(\n input: DiscoverWorkspaceCapabilitiesInput,\n): Promise<WorkspaceCapabilityDiscovery> {\n const connections = await resolveConnections(input)\n const connectors = await resolveConnectors(input)\n const activeConnectionsByConnector = new Map<string, IntegrationConnection>()\n for (const conn of connections) {\n if (conn.status !== 'active') continue\n if (!activeConnectionsByConnector.has(conn.connectorId)) {\n activeConnectionsByConnector.set(conn.connectorId, conn)\n }\n }\n\n const capabilities: WorkspaceCapability[] = []\n const triggers: WorkspaceTrigger[] = []\n const countsByConnector: Record<string, number> = {}\n const unreachableConnectors: Array<{ connectorId: string; reason: string }> = []\n\n for (const connector of connectors) {\n const connection = activeConnectionsByConnector.get(connector.id)\n const connected = Boolean(connection)\n if (!connected && !input.includeUnconnected) continue\n\n const grantedScopes = new Set(connection?.grantedScopes ?? [])\n let actionsAdded = 0\n\n for (const action of connector.actions) {\n const missing = action.requiredScopes.filter((scope) => !grantedScopes.has(scope))\n if (connected && missing.length > 0 && !input.includeMissingScopes) continue\n capabilities.push(toCapability(connector, action, connection))\n actionsAdded += 1\n }\n for (const trigger of connector.triggers ?? []) {\n const missing = trigger.requiredScopes.filter((scope) => !grantedScopes.has(scope))\n if (connected && missing.length > 0 && !input.includeMissingScopes) continue\n triggers.push(toTrigger(connector, trigger, connection))\n }\n\n countsByConnector[connector.id] = actionsAdded\n if (connected && actionsAdded === 0 && connector.actions.length > 0) {\n unreachableConnectors.push({\n connectorId: connector.id,\n reason: 'all_actions_missing_scope',\n })\n }\n }\n\n return { capabilities, triggers, countsByConnector, unreachableConnectors }\n}\n\nasync function resolveConnections(input: DiscoverWorkspaceCapabilitiesInput): Promise<IntegrationConnection[]> {\n if (input.connections) return input.connections\n if (input.store) return await input.store.listByOwner(input.owner)\n throw new Error('discoverWorkspaceCapabilities: provide either connections or store')\n}\n\nasync function resolveConnectors(input: DiscoverWorkspaceCapabilitiesInput): Promise<IntegrationConnector[]> {\n if (input.connectors) return input.connectors\n if (input.providers) {\n const lists = await Promise.all(input.providers.map((p) => Promise.resolve(p.listConnectors())))\n return lists.flat()\n }\n throw new Error('discoverWorkspaceCapabilities: provide either connectors or providers')\n}\n\nfunction toCapability(\n connector: IntegrationConnector,\n action: IntegrationConnectorAction,\n connection: IntegrationConnection | undefined,\n): WorkspaceCapability {\n return {\n id: `${connector.id}.${action.id}`,\n title: action.title,\n description: action.description,\n category: connector.category,\n connectorId: connector.id,\n providerId: connector.providerId,\n actionId: action.id,\n scopes: action.requiredScopes,\n risk: action.risk,\n dataClass: action.dataClass,\n toolSchema: {\n name: `${connector.id}.${action.id}`,\n description: action.description,\n inputSchema: action.inputSchema,\n outputSchema: action.outputSchema,\n },\n connected: Boolean(connection),\n connectionId: connection?.id,\n approvalRequired: action.approvalRequired,\n }\n}\n\nfunction toTrigger(\n connector: IntegrationConnector,\n trigger: IntegrationConnectorTrigger,\n connection: IntegrationConnection | undefined,\n): WorkspaceTrigger {\n return {\n id: `${connector.id}.${trigger.id}`,\n title: trigger.title,\n description: trigger.description,\n category: connector.category,\n connectorId: connector.id,\n providerId: connector.providerId,\n triggerId: trigger.id,\n scopes: trigger.requiredScopes,\n dataClass: trigger.dataClass,\n connected: Boolean(connection),\n connectionId: connection?.id,\n }\n}\n\n/**\n * Filter a {@link WorkspaceCapabilityDiscovery} result by the calling\n * user's effective id.tangle.tools workspace scopes. Pair with the\n * `tangleIdentity()` adapter's `list_workspaces` / `switch_workspace`\n * output to keep what the agent runtime sees aligned with what the\n * workspace's plan actually permits.\n *\n * Semantics:\n * - Every workspace scope is matched against every capability's\n * `scopes` list. Wildcard scopes (`tangle:*`, `<connectorId>:*`) are\n * respected — a workspace with `tangle:*` sees everything; a\n * workspace with `gmail:*` sees every gmail capability regardless of\n * the upstream OAuth scope.\n * - When `workspaceScopes` is empty, returns the discovery as-is (no\n * workspace gate). Pass an explicit `denyByDefault: true` to flip\n * that to \"empty workspace sees nothing\" — matches the platform's\n * fail-closed posture for production tenants.\n *\n * Pure with respect to the inputs — no side effects.\n */\nexport function filterDiscoveryByWorkspaceScopes(\n discovery: WorkspaceCapabilityDiscovery,\n workspaceScopes: string[],\n opts: { denyByDefault?: boolean } = {},\n): WorkspaceCapabilityDiscovery {\n if (workspaceScopes.length === 0 && !opts.denyByDefault) return discovery\n const granted = new Set(workspaceScopes)\n const hasWildcard = granted.has('tangle:*')\n\n function allowed(connectorId: string, scopes: string[]): boolean {\n if (hasWildcard) return true\n if (granted.has(`${connectorId}:*`)) return true\n // A workspace scope satisfies the capability iff every required\n // upstream scope is also present, OR the workspace explicitly\n // grants the connector. We deliberately do NOT loosen this to\n // \"any granted scope intersects\" — that would let a tenant with\n // a read-only Gmail grant invoke send_reply by accident.\n for (const scope of scopes) {\n if (!granted.has(scope)) return false\n }\n return true\n }\n\n const capabilities = discovery.capabilities.filter((cap) => allowed(cap.connectorId, cap.scopes))\n const triggers = discovery.triggers.filter((t) => allowed(t.connectorId, t.scopes))\n const countsByConnector: Record<string, number> = {}\n for (const cap of capabilities) {\n countsByConnector[cap.connectorId] = (countsByConnector[cap.connectorId] ?? 0) + 1\n }\n return {\n capabilities,\n triggers,\n countsByConnector,\n unreachableConnectors: discovery.unreachableConnectors,\n }\n}\n","import type {\n ConnectorAdapter,\n InboundEvent,\n ResolvedDataSource,\n} from './connectors/types.js'\nimport type {\n IntegrationTriggerEvent,\n} from './index.js'\nimport type { IntegrationWorkflowRuntime } from './workflow.js'\n\nexport interface StoredIntegrationEvent {\n id: string\n sourceId: string\n connectorId: string\n eventType: string\n providerEventId?: string\n receivedAt: string\n payload: Record<string, unknown>\n dispatchedAt?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationEventStore {\n put(event: StoredIntegrationEvent): Promise<void> | void\n hasProviderEvent(sourceId: string, providerEventId: string): Promise<boolean> | boolean\n list(): Promise<StoredIntegrationEvent[]> | StoredIntegrationEvent[]\n}\n\nexport interface IntegrationWebhookReceiverResult {\n status: number\n body: unknown\n headers?: Record<string, string>\n received: StoredIntegrationEvent[]\n duplicates: StoredIntegrationEvent[]\n}\n\nexport class InMemoryIntegrationEventStore implements IntegrationEventStore {\n private readonly events = new Map<string, StoredIntegrationEvent>()\n private readonly providerIds = new Set<string>()\n\n put(event: StoredIntegrationEvent): void {\n this.events.set(event.id, event)\n if (event.providerEventId) this.providerIds.add(providerKey(event.sourceId, event.providerEventId))\n }\n\n hasProviderEvent(sourceId: string, providerEventId: string): boolean {\n return this.providerIds.has(providerKey(sourceId, providerEventId))\n }\n\n list(): StoredIntegrationEvent[] {\n return [...this.events.values()]\n }\n}\n\nexport async function receiveIntegrationWebhook(input: {\n adapter: ConnectorAdapter\n source: ResolvedDataSource\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n store: IntegrationEventStore\n workflowRuntime?: IntegrationWorkflowRuntime\n allowUnsignedWebhook?: boolean\n now?: () => Date\n}): Promise<IntegrationWebhookReceiverResult> {\n if (!input.adapter.handleInboundEvent) {\n return { status: 405, body: { ok: false, error: 'Connector does not support inbound webhooks.' }, received: [], duplicates: [] }\n }\n if (!input.adapter.verifySignature && !input.allowUnsignedWebhook) {\n return { status: 401, body: { ok: false, error: 'Webhook signature verification is required.' }, received: [], duplicates: [] }\n }\n const signature = input.adapter.verifySignature?.({\n rawBody: input.rawBody,\n headers: input.headers,\n source: input.source,\n })\n if (signature && !signature.valid) {\n return { status: 401, body: { ok: false, error: signature.reason ?? 'Invalid webhook signature.' }, received: [], duplicates: [] }\n }\n\n const handled = await input.adapter.handleInboundEvent({\n source: input.source,\n rawBody: input.rawBody,\n headers: input.headers,\n })\n const received: StoredIntegrationEvent[] = []\n const duplicates: StoredIntegrationEvent[] = []\n for (const inbound of handled.events) {\n const event = storedEvent(input.source, inbound, input.now ?? (() => new Date()))\n if (event.providerEventId && await input.store.hasProviderEvent(event.sourceId, event.providerEventId)) {\n duplicates.push(event)\n continue\n }\n await input.store.put(event)\n received.push(event)\n await dispatchStoredEvent(event, input.source, input.workflowRuntime)\n }\n\n return {\n status: handled.response?.status ?? 200,\n body: handled.response?.body ?? { received: true, count: received.length, duplicateCount: duplicates.length },\n headers: handled.response?.headers,\n received,\n duplicates,\n }\n}\n\nexport function storedEventToTriggerEvent(event: StoredIntegrationEvent, source: ResolvedDataSource): IntegrationTriggerEvent {\n return {\n id: event.id,\n providerId: String(source.metadata.providerId ?? 'first-party'),\n connectorId: event.connectorId,\n connectionId: source.id,\n trigger: event.eventType,\n occurredAt: event.receivedAt,\n payload: event.payload,\n metadata: {\n providerEventId: event.providerEventId,\n sourceId: event.sourceId,\n ...event.metadata,\n },\n }\n}\n\nasync function dispatchStoredEvent(\n event: StoredIntegrationEvent,\n source: ResolvedDataSource,\n workflowRuntime?: IntegrationWorkflowRuntime,\n): Promise<void> {\n if (!workflowRuntime) return\n await workflowRuntime.dispatchEvent(storedEventToTriggerEvent(event, source), () => undefined)\n}\n\nfunction storedEvent(source: ResolvedDataSource, event: InboundEvent, now: () => Date): StoredIntegrationEvent {\n return {\n id: `evt_${source.id}_${event.providerEventId ?? `${event.eventType}_${now().getTime()}`}`,\n sourceId: source.id,\n connectorId: source.kind,\n eventType: event.eventType,\n providerEventId: event.providerEventId,\n receivedAt: now().toISOString(),\n payload: event.payload,\n }\n}\n\nfunction providerKey(sourceId: string, providerEventId: string): string {\n return `${sourceId}:${providerEventId}`\n}\n","import { createHash } from 'node:crypto'\nimport type {\n IntegrationActionGuard,\n IntegrationActionResult,\n IntegrationGuardContext,\n} from './index.js'\nimport type { IntegrationAuditSink } from './audit.js'\nimport { createIntegrationAuditEvent } from './audit.js'\n\nexport interface IntegrationIdempotencyRecord {\n key: string\n requestHash: string\n result: IntegrationActionResult\n createdAt: string\n}\n\nexport interface IntegrationIdempotencyStore {\n get(key: string): Promise<IntegrationIdempotencyRecord | undefined> | IntegrationIdempotencyRecord | undefined\n put(record: IntegrationIdempotencyRecord): Promise<void> | void\n}\n\nexport interface IntegrationRateLimitDecision {\n allowed: boolean\n retryAfterMs?: number\n reason?: string\n}\n\nexport interface IntegrationRateLimiter {\n check(ctx: IntegrationGuardContext): Promise<IntegrationRateLimitDecision> | IntegrationRateLimitDecision\n}\n\nexport class InMemoryIntegrationIdempotencyStore implements IntegrationIdempotencyStore {\n private readonly records = new Map<string, IntegrationIdempotencyRecord>()\n\n get(key: string): IntegrationIdempotencyRecord | undefined {\n return this.records.get(key)\n }\n\n put(record: IntegrationIdempotencyRecord): void {\n this.records.set(record.key, record)\n }\n}\n\nexport class DefaultIntegrationActionGuard implements IntegrationActionGuard {\n private readonly idempotency: IntegrationIdempotencyStore | undefined\n private readonly audit: IntegrationAuditSink | undefined\n private readonly rateLimiter: IntegrationRateLimiter | undefined\n private readonly requireIdempotencyForMutations: boolean\n private readonly now: () => Date\n\n constructor(options: {\n idempotency?: IntegrationIdempotencyStore\n audit?: IntegrationAuditSink\n rateLimiter?: IntegrationRateLimiter\n requireIdempotencyForMutations?: boolean\n now?: () => Date\n } = {}) {\n this.idempotency = options.idempotency\n this.audit = options.audit\n this.rateLimiter = options.rateLimiter\n this.requireIdempotencyForMutations = options.requireIdempotencyForMutations ?? false\n this.now = options.now ?? (() => new Date())\n }\n\n async invokeAction(ctx: IntegrationGuardContext, proceed: () => Promise<IntegrationActionResult>): Promise<IntegrationActionResult> {\n const idempotencyKey = ctx.request.idempotencyKey\n const requestHash = hashRequest(ctx)\n if (this.requireIdempotencyForMutations && ctx.action?.risk !== 'read' && !idempotencyKey) {\n return {\n ok: false,\n action: ctx.request.action,\n output: {\n idempotencyRequired: true,\n message: 'State-changing integration actions require an idempotency key.',\n },\n }\n }\n if (idempotencyKey && this.idempotency) {\n const existing = await this.idempotency.get(idempotencyKey)\n if (existing) {\n if (existing.requestHash !== requestHash) {\n return {\n ok: false,\n action: ctx.request.action,\n output: { idempotencyConflict: true, message: 'Idempotency key was reused with different integration input.' },\n }\n }\n return {\n ...existing.result,\n metadata: { ...(existing.result.metadata ?? {}), idempotentReplay: true },\n }\n }\n }\n\n if (ctx.request.dryRun && ctx.action?.risk !== 'read') {\n const result: IntegrationActionResult = {\n ok: true,\n action: ctx.request.action,\n output: { dryRun: true },\n metadata: { dryRun: true },\n }\n await this.writeIdempotency(idempotencyKey, requestHash, result)\n return result\n }\n\n const rateLimit = await this.rateLimiter?.check(ctx)\n if (rateLimit && !rateLimit.allowed) {\n return {\n ok: false,\n action: ctx.request.action,\n output: { rateLimited: true, retryAfterMs: rateLimit.retryAfterMs, message: rateLimit.reason ?? 'Integration rate limit exceeded.' },\n }\n }\n\n try {\n const result = await proceed()\n if (result.ok) {\n await this.writeIdempotency(idempotencyKey, requestHash, result)\n }\n await this.audit?.record(createIntegrationAuditEvent({\n type: result.ok ? 'action.invoked' : 'action.failed',\n actor: ctx.connection.owner,\n connectionId: ctx.connection.id,\n providerId: ctx.connection.providerId,\n connectorId: ctx.connection.connectorId,\n action: ctx.request.action,\n risk: ctx.action?.risk,\n dataClass: ctx.action?.dataClass,\n ok: result.ok,\n metadata: { idempotencyKey, externalId: result.externalId, warnings: result.warnings },\n now: this.now,\n }))\n return result\n } catch (error) {\n await this.audit?.record(createIntegrationAuditEvent({\n type: 'action.failed',\n actor: ctx.connection.owner,\n connectionId: ctx.connection.id,\n providerId: ctx.connection.providerId,\n connectorId: ctx.connection.connectorId,\n action: ctx.request.action,\n risk: ctx.action?.risk,\n dataClass: ctx.action?.dataClass,\n ok: false,\n message: error instanceof Error ? error.message : 'Integration action failed.',\n metadata: { idempotencyKey },\n now: this.now,\n }))\n throw error\n }\n }\n\n private async writeIdempotency(key: string | undefined, requestHash: string, result: IntegrationActionResult): Promise<void> {\n if (!key || !this.idempotency) return\n await this.idempotency.put({\n key,\n requestHash,\n result,\n createdAt: this.now().toISOString(),\n })\n }\n}\n\nexport function createDefaultIntegrationActionGuard(options: ConstructorParameters<typeof DefaultIntegrationActionGuard>[0] = {}): DefaultIntegrationActionGuard {\n return new DefaultIntegrationActionGuard(options)\n}\n\nfunction hashRequest(ctx: IntegrationGuardContext): string {\n return createHash('sha256').update(JSON.stringify({\n connectionId: ctx.connection.id,\n action: ctx.request.action,\n input: ctx.request.input ?? null,\n dryRun: ctx.request.dryRun ?? false,\n })).digest('base64url')\n}\n","import type {\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n} from './index.js'\nimport type { IntegrationAuditSink } from './audit.js'\nimport { createIntegrationAuditEvent } from './audit.js'\nimport type { IntegrationRegistry } from './registry.js'\n\nexport type IntegrationHealthcheckStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown'\n\nexport interface IntegrationHealthcheckCheck {\n id: string\n status: IntegrationHealthcheckStatus\n message: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationHealthcheckResult {\n connectionId: string\n providerId: string\n connectorId: string\n status: IntegrationHealthcheckStatus\n checkedAt: string\n checks: IntegrationHealthcheckCheck[]\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationHealthcheckStore {\n put(result: IntegrationHealthcheckResult): Promise<void> | void\n get(connectionId: string): Promise<IntegrationHealthcheckResult | undefined> | IntegrationHealthcheckResult | undefined\n list(): Promise<IntegrationHealthcheckResult[]> | IntegrationHealthcheckResult[]\n}\n\nexport class InMemoryIntegrationHealthcheckStore implements IntegrationHealthcheckStore {\n private readonly results = new Map<string, IntegrationHealthcheckResult>()\n\n put(result: IntegrationHealthcheckResult): void {\n this.results.set(result.connectionId, result)\n }\n\n get(connectionId: string): IntegrationHealthcheckResult | undefined {\n return this.results.get(connectionId)\n }\n\n list(): IntegrationHealthcheckResult[] {\n return [...this.results.values()]\n }\n}\n\nexport async function runIntegrationHealthcheck(input: {\n connection: IntegrationConnection\n connector?: IntegrationConnector\n registry?: IntegrationRegistry\n test?: (connection: IntegrationConnection, connector: IntegrationConnector) => Promise<IntegrationActionResult | boolean> | IntegrationActionResult | boolean\n audit?: IntegrationAuditSink\n now?: () => Date\n}): Promise<IntegrationHealthcheckResult> {\n const now = input.now ?? (() => new Date())\n const checkedAt = now().toISOString()\n const connector = input.connector ?? input.registry?.byId.get(input.connection.connectorId)?.connector\n const checks: IntegrationHealthcheckCheck[] = []\n\n checks.push(connectionStatusCheck(input.connection, now))\n if (!connector) {\n checks.push({ id: 'connector-known', status: 'unknown', message: `Connector ${input.connection.connectorId} is not in the registry.` })\n } else {\n checks.push(connectorExecutableCheck(connector))\n checks.push(scopeShapeCheck(input.connection, connector))\n if (input.test && input.connection.status === 'active') {\n checks.push(await liveHealthcheck(input.connection, connector, input.test))\n }\n }\n\n const result: IntegrationHealthcheckResult = {\n connectionId: input.connection.id,\n providerId: input.connection.providerId,\n connectorId: input.connection.connectorId,\n status: rollupHealthStatus(checks),\n checkedAt,\n checks,\n }\n await input.audit?.record(createIntegrationAuditEvent({\n type: 'healthcheck.completed',\n actor: input.connection.owner,\n connectionId: input.connection.id,\n providerId: input.connection.providerId,\n connectorId: input.connection.connectorId,\n ok: result.status === 'healthy',\n message: result.status,\n metadata: { checks: checks.map((check) => ({ id: check.id, status: check.status, message: check.message })) },\n occurredAt: checkedAt,\n }))\n return result\n}\n\nexport async function runIntegrationHealthchecks(input: {\n connections: IntegrationConnection[]\n registry?: IntegrationRegistry\n store?: IntegrationHealthcheckStore\n audit?: IntegrationAuditSink\n now?: () => Date\n test?: (connection: IntegrationConnection, connector: IntegrationConnector) => Promise<IntegrationActionResult | boolean> | IntegrationActionResult | boolean\n}): Promise<IntegrationHealthcheckResult[]> {\n const results: IntegrationHealthcheckResult[] = []\n for (const connection of input.connections) {\n const result = await runIntegrationHealthcheck({\n connection,\n registry: input.registry,\n test: input.test,\n audit: input.audit,\n now: input.now,\n })\n await input.store?.put(result)\n results.push(result)\n }\n return results\n}\n\nexport function healthcheckRequest(action = 'healthcheck'): IntegrationActionRequest {\n return {\n connectionId: '__healthcheck__',\n action,\n input: {},\n dryRun: true,\n metadata: { healthcheck: true },\n }\n}\n\nfunction connectionStatusCheck(connection: IntegrationConnection, now: () => Date): IntegrationHealthcheckCheck {\n if (connection.status !== 'active') {\n return { id: 'connection-active', status: 'unhealthy', message: `Connection is ${connection.status}.` }\n }\n if (connection.expiresAt && Date.parse(connection.expiresAt) <= now().getTime()) {\n return { id: 'connection-active', status: 'unhealthy', message: 'Connection credentials are expired.' }\n }\n return { id: 'connection-active', status: 'healthy', message: 'Connection is active.' }\n}\n\nfunction connectorExecutableCheck(connector: IntegrationConnector): IntegrationHealthcheckCheck {\n const executable = connector.actions.length > 0 || (connector.triggers?.length ?? 0) > 0\n if (!executable) {\n return { id: 'connector-executable', status: 'degraded', message: `${connector.title} is catalog-only.` }\n }\n return { id: 'connector-executable', status: 'healthy', message: `${connector.title} has executable actions or triggers.` }\n}\n\nfunction scopeShapeCheck(connection: IntegrationConnection, connector: IntegrationConnector): IntegrationHealthcheckCheck {\n const declaredScopes = new Set(connector.scopes)\n const undeclared = connection.grantedScopes.filter((scope) => !declaredScopes.has(scope))\n if (connector.scopes.length === 0 && connection.grantedScopes.length > 0) {\n return { id: 'scope-shape', status: 'unknown', message: 'Connector does not declare a scope catalog.', metadata: { grantedScopes: connection.grantedScopes } }\n }\n if (undeclared.length > 0) {\n return { id: 'scope-shape', status: 'degraded', message: 'Connection has scopes not declared by the connector.', metadata: { undeclared } }\n }\n return { id: 'scope-shape', status: 'healthy', message: 'Granted scopes match the connector shape.' }\n}\n\nasync function liveHealthcheck(\n connection: IntegrationConnection,\n connector: IntegrationConnector,\n test: (connection: IntegrationConnection, connector: IntegrationConnector) => Promise<IntegrationActionResult | boolean> | IntegrationActionResult | boolean,\n): Promise<IntegrationHealthcheckCheck> {\n try {\n const result = await test(connection, connector)\n const ok = typeof result === 'boolean' ? result : result.ok\n return {\n id: 'provider-live-test',\n status: ok ? 'healthy' : 'unhealthy',\n message: ok ? 'Provider live test passed.' : 'Provider live test failed.',\n metadata: typeof result === 'boolean' ? undefined : { action: result.action, warnings: result.warnings },\n }\n } catch (error) {\n return {\n id: 'provider-live-test',\n status: 'unhealthy',\n message: error instanceof Error ? error.message : 'Provider live test failed.',\n }\n }\n}\n\nfunction rollupHealthStatus(checks: IntegrationHealthcheckCheck[]): IntegrationHealthcheckStatus {\n if (checks.some((check) => check.status === 'unhealthy')) return 'unhealthy'\n if (checks.some((check) => check.status === 'degraded')) return 'degraded'\n if (checks.some((check) => check.status === 'unknown')) return 'unknown'\n return 'healthy'\n}\n","import { CANONICAL_INTEGRATION_ACTIONS, canonicalActionConnectorId } from './actions.js'\nimport type {\n IntegrationManifest,\n IntegrationManifestResolution,\n IntegrationRequirement,\n IntegrationRequirementMode,\n} from './runtime.js'\n\nexport interface ManifestValidationIssue {\n path: string\n message: string\n}\n\nexport interface ManifestValidationResult {\n ok: boolean\n issues: ManifestValidationIssue[]\n}\n\nexport interface InferIntegrationRequirementsOptions {\n manifestId: string\n title?: string\n tools: Array<string | { action: string; reason?: string; mode?: IntegrationRequirementMode; connectorId?: string; scopes?: string[] }>\n metadata?: Record<string, unknown>\n}\n\nexport interface MissingRequirementExplanation {\n requirementId: string\n connectorId: string\n status: string\n message: string\n userAction: 'connect' | 'enable' | 'ignore_optional'\n}\n\nexport function validateIntegrationManifest(manifest: IntegrationManifest): ManifestValidationResult {\n const issues: ManifestValidationIssue[] = []\n if (!manifest.id?.trim()) issues.push({ path: 'id', message: 'Manifest id is required.' })\n if (!Array.isArray(manifest.requirements)) issues.push({ path: 'requirements', message: 'Requirements must be an array.' })\n const ids = new Set<string>()\n for (const [index, requirement] of (manifest.requirements ?? []).entries()) {\n const path = `requirements[${index}]`\n if (!requirement.id?.trim()) issues.push({ path: `${path}.id`, message: 'Requirement id is required.' })\n if (ids.has(requirement.id)) issues.push({ path: `${path}.id`, message: `Duplicate requirement id ${requirement.id}.` })\n ids.add(requirement.id)\n if (!requirement.connectorId?.trim()) issues.push({ path: `${path}.connectorId`, message: 'Connector id is required.' })\n if (!['read', 'write', 'trigger'].includes(requirement.mode)) issues.push({ path: `${path}.mode`, message: 'Mode must be read, write, or trigger.' })\n if (!requirement.reason?.trim()) issues.push({ path: `${path}.reason`, message: 'Human-readable reason is required.' })\n if (requirement.mode !== 'trigger' && !requirement.requiredActions?.length) {\n issues.push({ path: `${path}.requiredActions`, message: 'Non-trigger requirements should list required actions.' })\n }\n if (requirement.mode === 'trigger' && !requirement.requiredTriggers?.length) {\n issues.push({ path: `${path}.requiredTriggers`, message: 'Trigger requirements should list required triggers.' })\n }\n }\n return { ok: issues.length === 0, issues }\n}\n\nexport function assertValidIntegrationManifest(manifest: IntegrationManifest): void {\n const result = validateIntegrationManifest(manifest)\n if (!result.ok) {\n throw new Error(`Invalid integration manifest: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)\n }\n}\n\nexport function inferIntegrationManifestFromTools(options: InferIntegrationRequirementsOptions): IntegrationManifest {\n const byConnector = new Map<string, IntegrationRequirement>()\n for (const item of options.tools) {\n const action = typeof item === 'string' ? item : item.action\n const connectorId = typeof item === 'string' ? canonicalActionConnectorId(action) : item.connectorId ?? canonicalActionConnectorId(action)\n if (!connectorId) continue\n const mode = typeof item === 'string' ? inferMode(action) : item.mode ?? inferMode(action)\n const id = `${connectorId}-${mode}`\n const existing = byConnector.get(id)\n const reason = typeof item === 'string' ? defaultReason(connectorId, mode) : item.reason ?? defaultReason(connectorId, mode)\n if (existing) {\n byConnector.set(id, {\n ...existing,\n requiredActions: unique([...(existing.requiredActions ?? []), action]),\n requiredScopes: unique([...(existing.requiredScopes ?? []), ...(typeof item === 'string' ? [] : item.scopes ?? [])]),\n })\n } else {\n byConnector.set(id, {\n id,\n connectorId,\n mode,\n reason,\n requiredActions: mode === 'trigger' ? undefined : [action],\n requiredScopes: typeof item === 'string' ? undefined : item.scopes,\n })\n }\n }\n const manifest: IntegrationManifest = {\n id: options.manifestId,\n title: options.title,\n requirements: [...byConnector.values()],\n metadata: options.metadata,\n }\n assertValidIntegrationManifest(manifest)\n return manifest\n}\n\nexport function explainMissingRequirements(resolution: IntegrationManifestResolution): MissingRequirementExplanation[] {\n return [...resolution.missing, ...resolution.optionalMissing].map((item) => ({\n requirementId: item.requirement.id,\n connectorId: item.requirement.connectorId,\n status: item.status,\n message: item.message,\n userAction: item.requirement.optional ? 'ignore_optional' : item.status === 'not_executable' ? 'enable' : 'connect',\n }))\n}\n\nexport function calendarExercisePlannerManifest(id = 'exercise-calendar-planner'): IntegrationManifest {\n return {\n id,\n title: 'Exercise Calendar Planner',\n requirements: [{\n id: 'calendar-read',\n connectorId: 'google-calendar',\n mode: 'read',\n reason: 'Read busy and free calendar windows to recommend exercise sessions.',\n requiredActions: [CANONICAL_INTEGRATION_ACTIONS.googleCalendarEventsList],\n requiredScopes: ['https://www.googleapis.com/auth/calendar.readonly'],\n }],\n }\n}\n\nfunction inferMode(action: string): IntegrationRequirementMode {\n if (/(create|send|post|update|delete|write|comment|request)$/i.test(action)) return 'write'\n return 'read'\n}\n\nfunction defaultReason(connectorId: string, mode: IntegrationRequirementMode): string {\n if (connectorId === 'google-calendar' && mode === 'read') return 'Read calendar availability for the generated app.'\n if (connectorId === 'google-calendar' && mode === 'write') return 'Create or update calendar events after user approval.'\n return `${mode === 'read' ? 'Read from' : mode === 'write' ? 'Write to' : 'Subscribe to'} ${connectorId} for this app.`\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n","import { CANONICAL_INTEGRATION_ACTIONS } from './actions.js'\nimport { IntegrationRuntimeError } from './errors.js'\n\nexport interface ProviderHttpRequestInput {\n method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n path: string\n query?: Record<string, string | number | boolean | undefined>\n headers?: Record<string, string>\n body?: unknown\n}\n\nexport interface ProviderPassthroughPolicy {\n enabled: boolean\n allowedMethods?: ProviderHttpRequestInput['method'][]\n allowedPathPrefixes?: string[]\n maxBodyBytes?: number\n}\n\nexport const PROVIDER_PASSTHROUGH_ACTION = CANONICAL_INTEGRATION_ACTIONS.providerHttpRequest\n\nexport function validateProviderPassthroughRequest(\n input: ProviderHttpRequestInput,\n policy: ProviderPassthroughPolicy,\n): void {\n if (!policy.enabled) {\n throw new IntegrationRuntimeError({\n code: 'passthrough_disabled',\n message: 'Provider-native passthrough is disabled for this connector.',\n })\n }\n if (!input.path.startsWith('/')) {\n throw new IntegrationRuntimeError({ code: 'input_invalid', message: 'Provider passthrough path must start with /.' })\n }\n if (policy.allowedMethods?.length && !policy.allowedMethods.includes(input.method)) {\n throw new IntegrationRuntimeError({ code: 'action_denied', message: `Provider passthrough method ${input.method} is not allowed.` })\n }\n if (policy.allowedPathPrefixes?.length && !policy.allowedPathPrefixes.some((prefix) => input.path.startsWith(prefix))) {\n throw new IntegrationRuntimeError({ code: 'action_denied', message: `Provider passthrough path ${input.path} is not allowed.` })\n }\n const maxBodyBytes = policy.maxBodyBytes ?? 64 * 1024\n const bodyBytes = Buffer.byteLength(JSON.stringify(input.body ?? null), 'utf8')\n if (bodyBytes > maxBodyBytes) {\n throw new IntegrationRuntimeError({ code: 'input_invalid', message: `Provider passthrough body exceeds ${maxBodyBytes} bytes.` })\n }\n for (const key of Object.keys(input.headers ?? {})) {\n if (/authorization|cookie|token|secret|api[_-]?key/i.test(key)) {\n throw new IntegrationRuntimeError({ code: 'input_invalid', message: `Provider passthrough header ${key} is not caller-settable.` })\n }\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport type {\n IntegrationActionRisk,\n IntegrationApprovalRequest,\n IntegrationDataClass,\n IntegrationGuardContext,\n IntegrationPolicyDecision,\n IntegrationPolicyEngine,\n} from './index.js'\n\nexport type IntegrationPolicyEffect = 'allow' | 'require_approval' | 'deny'\n\nexport interface IntegrationPolicyRule {\n id: string\n effect: IntegrationPolicyEffect\n reason: string\n providerId?: string\n connectorId?: string\n action?: string\n maxRisk?: IntegrationActionRisk\n risk?: IntegrationActionRisk\n dataClass?: IntegrationDataClass\n}\n\nexport interface StaticIntegrationPolicyOptions {\n rules?: IntegrationPolicyRule[]\n defaultReadEffect?: IntegrationPolicyEffect\n defaultWriteEffect?: IntegrationPolicyEffect\n defaultDestructiveEffect?: IntegrationPolicyEffect\n now?: () => Date\n}\n\nexport interface IntegrationApprovalResolution {\n approvalId: string\n approved: boolean\n resolvedBy: string\n resolvedAt: string\n reason?: string\n metadata?: Record<string, unknown>\n}\n\nexport class StaticIntegrationPolicyEngine implements IntegrationPolicyEngine {\n private readonly rules: IntegrationPolicyRule[]\n private readonly defaultReadEffect: IntegrationPolicyEffect\n private readonly defaultWriteEffect: IntegrationPolicyEffect\n private readonly defaultDestructiveEffect: IntegrationPolicyEffect\n private readonly now: () => Date\n\n constructor(options: StaticIntegrationPolicyOptions = {}) {\n this.rules = options.rules ?? []\n this.defaultReadEffect = options.defaultReadEffect ?? 'allow'\n this.defaultWriteEffect = options.defaultWriteEffect ?? 'require_approval'\n this.defaultDestructiveEffect = options.defaultDestructiveEffect ?? 'deny'\n this.now = options.now ?? (() => new Date())\n }\n\n decide(ctx: IntegrationGuardContext & { subject: { type: string; id: string } }): IntegrationPolicyDecision {\n const action = ctx.action\n if (!action) return { decision: 'deny', reason: 'Integration action is missing from connector catalog.' }\n const matched = this.rules.find((rule) => ruleMatches(rule, ctx))\n const effect = matched?.effect ?? this.defaultEffect(action.risk)\n const reason = matched?.reason ?? defaultReason(effect, action.risk)\n if (effect === 'allow') return { decision: 'allow', reason, metadata: matched ? { ruleId: matched.id } : undefined }\n if (effect === 'deny') return { decision: 'deny', reason, metadata: matched ? { ruleId: matched.id } : undefined }\n return {\n decision: 'require_approval',\n reason,\n approval: buildApprovalRequest(ctx, reason, this.now()),\n metadata: matched ? { ruleId: matched.id } : undefined,\n }\n }\n\n private defaultEffect(risk: IntegrationActionRisk): IntegrationPolicyEffect {\n if (risk === 'read') return this.defaultReadEffect\n if (risk === 'write') return this.defaultWriteEffect\n return this.defaultDestructiveEffect\n }\n}\n\nexport function createDefaultIntegrationPolicyEngine(options: Omit<StaticIntegrationPolicyOptions, 'rules'> = {}): StaticIntegrationPolicyEngine {\n return new StaticIntegrationPolicyEngine(options)\n}\n\nexport function buildApprovalRequest(\n ctx: IntegrationGuardContext & { subject: { type: string; id: string } },\n reason: string,\n requestedAt: Date,\n): IntegrationApprovalRequest {\n if (!ctx.action) {\n throw new Error('Cannot build approval request without an action descriptor.')\n }\n return {\n id: `approval_${randomUUID()}`,\n connectionId: ctx.connection.id,\n providerId: ctx.connection.providerId,\n connectorId: ctx.connection.connectorId,\n action: ctx.request.action,\n actor: { type: ctx.subject.type as never, id: ctx.subject.id },\n risk: ctx.action.risk,\n dataClass: ctx.action.dataClass,\n reason,\n requestedAt: requestedAt.toISOString(),\n inputPreview: previewInput(ctx.request.input),\n }\n}\n\nexport function redactApprovalRequest(request: IntegrationApprovalRequest): IntegrationApprovalRequest {\n return {\n ...request,\n inputPreview: redactUnknown(request.inputPreview),\n }\n}\n\nfunction ruleMatches(rule: IntegrationPolicyRule, ctx: IntegrationGuardContext): boolean {\n if (!ctx.action) return false\n if (rule.providerId && rule.providerId !== ctx.connection.providerId) return false\n if (rule.connectorId && rule.connectorId !== ctx.connection.connectorId) return false\n if (rule.action && rule.action !== ctx.request.action) return false\n if (rule.risk && rule.risk !== ctx.action.risk) return false\n if (rule.maxRisk && riskRank(ctx.action.risk) > riskRank(rule.maxRisk)) return false\n if (rule.dataClass && rule.dataClass !== ctx.action.dataClass) return false\n return true\n}\n\nfunction riskRank(risk: IntegrationActionRisk): number {\n if (risk === 'read') return 0\n if (risk === 'write') return 1\n return 2\n}\n\nfunction defaultReason(effect: IntegrationPolicyEffect, risk: IntegrationActionRisk): string {\n if (effect === 'allow') return `${risk} integration action allowed by default policy.`\n if (effect === 'deny') return `${risk} integration action denied by default policy.`\n return `${risk} integration action requires approval by default policy.`\n}\n\nfunction previewInput(input: unknown): unknown {\n return redactUnknown(input)\n}\n\nfunction redactUnknown(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactUnknown)\n if (!value || typeof value !== 'object') return value\n const out: Record<string, unknown> = {}\n for (const [key, child] of Object.entries(value)) {\n if (/token|secret|password|authorization|api[_-]?key|credential/i.test(key)) {\n out[key] = '[REDACTED]'\n } else {\n out[key] = redactUnknown(child)\n }\n }\n return out\n}\n","import { StaticIntegrationPolicyEngine, type StaticIntegrationPolicyOptions } from './policy.js'\n\nexport interface PlatformIntegrationPolicyPresetOptions extends Omit<StaticIntegrationPolicyOptions, 'defaultReadEffect' | 'defaultWriteEffect' | 'defaultDestructiveEffect'> {\n allowWritesWithoutApproval?: boolean\n allowDestructiveActions?: boolean\n allowProviderPassthrough?: boolean\n}\n\nexport function createPlatformIntegrationPolicyPreset(options: PlatformIntegrationPolicyPresetOptions = {}): StaticIntegrationPolicyEngine {\n return new StaticIntegrationPolicyEngine({\n ...options,\n defaultReadEffect: 'allow',\n defaultWriteEffect: options.allowWritesWithoutApproval ? 'allow' : 'require_approval',\n defaultDestructiveEffect: options.allowDestructiveActions ? 'require_approval' : 'deny',\n rules: [\n ...(options.allowProviderPassthrough ? [] : [{\n id: 'deny-provider-native-passthrough',\n action: 'provider.http.request',\n effect: 'deny' as const,\n reason: 'Provider-native passthrough is disabled by default. Promote the connector action or enable passthrough explicitly.',\n }]),\n ...(options.rules ?? []),\n ],\n })\n}\n","import type {\n IntegrationActionResult,\n IntegrationApprovalRequest,\n IntegrationCapability,\n IntegrationConnector,\n InvokeWithCapabilityRequest,\n} from './index.js'\nimport { parseIntegrationToolName } from './catalog.js'\n\nexport interface IntegrationInvocationEnvelope {\n kind: 'integration.invocation'\n capabilityToken: string\n toolName: string\n action: string\n input?: unknown\n idempotencyKey: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationInvocationEnvelopeValidationOptions {\n connectors?: IntegrationConnector[]\n maxInputBytes?: number\n requireKnownTool?: boolean\n}\n\nexport type NormalizedIntegrationResult =\n | { status: 'ok'; action: string; output?: unknown; metadata?: Record<string, unknown> }\n | { status: 'approval_required'; action: string; approval: IntegrationApprovalRequest; metadata?: Record<string, unknown> }\n | { status: 'failed'; action: string; error: string; metadata?: Record<string, unknown> }\n\nexport interface IntegrationSandboxHostHub {\n invokeWithCapability(token: string, request: InvokeWithCapabilityRequest): Promise<IntegrationActionResult> | IntegrationActionResult\n}\n\nexport interface IntegrationSandboxHostOptions extends IntegrationInvocationEnvelopeValidationOptions {\n hub: IntegrationSandboxHostHub\n}\n\nexport function buildIntegrationInvocationEnvelope(input: {\n capabilityToken: string\n toolName: string\n args?: unknown\n idempotencyKey: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n}): IntegrationInvocationEnvelope {\n const parsed = parseIntegrationToolName(input.toolName)\n const envelope: IntegrationInvocationEnvelope = {\n kind: 'integration.invocation',\n capabilityToken: input.capabilityToken,\n toolName: input.toolName,\n action: parsed.actionId,\n input: input.args,\n idempotencyKey: input.idempotencyKey,\n dryRun: input.dryRun,\n metadata: input.metadata,\n }\n validateIntegrationInvocationEnvelope(envelope)\n return envelope\n}\n\nexport function invocationRequestFromEnvelope(envelope: IntegrationInvocationEnvelope): InvokeWithCapabilityRequest {\n validateIntegrationInvocationEnvelope(envelope)\n return {\n action: envelope.action,\n input: envelope.input,\n idempotencyKey: envelope.idempotencyKey,\n dryRun: envelope.dryRun,\n metadata: envelope.metadata,\n }\n}\n\nexport function validateIntegrationInvocationEnvelope(\n envelope: IntegrationInvocationEnvelope,\n options: IntegrationInvocationEnvelopeValidationOptions = {},\n): void {\n if (!envelope || typeof envelope !== 'object') throw new Error('Integration invocation envelope is required.')\n if (envelope.kind !== 'integration.invocation') throw new Error('Invalid integration invocation envelope kind.')\n if (!isNonEmptyString(envelope.capabilityToken)) throw new Error('Integration invocation envelope is missing capabilityToken.')\n if (!isNonEmptyString(envelope.toolName)) throw new Error('Integration invocation envelope is missing toolName.')\n if (!isNonEmptyString(envelope.action)) throw new Error('Integration invocation envelope is missing action.')\n if (!isNonEmptyString(envelope.idempotencyKey)) throw new Error('Integration invocation envelope is missing idempotencyKey.')\n if (envelope.metadata !== undefined && !isPlainRecord(envelope.metadata)) {\n throw new Error('Integration invocation envelope metadata must be an object.')\n }\n const parsed = parseIntegrationToolName(envelope.toolName)\n if (parsed.actionId !== envelope.action) {\n throw new Error(`Integration invocation action ${envelope.action} does not match tool ${parsed.actionId}.`)\n }\n const inputBytes = Buffer.byteLength(JSON.stringify(envelope.input ?? null), 'utf8')\n const maxInputBytes = options.maxInputBytes ?? 256 * 1024\n if (inputBytes > maxInputBytes) {\n throw new Error(`Integration invocation input exceeds ${maxInputBytes} bytes.`)\n }\n if (options.requireKnownTool || options.connectors) {\n if (!options.connectors) throw new Error('connectors are required when requireKnownTool is true.')\n const connector = options.connectors.find((candidate) =>\n candidate.providerId === parsed.providerId && candidate.id === parsed.connectorId\n )\n const action = connector?.actions.find((candidate) => candidate.id === parsed.actionId)\n if (!connector || !action) throw new Error(`Unknown integration tool ${envelope.toolName}.`)\n }\n}\n\nexport function redactInvocationEnvelope(envelope: IntegrationInvocationEnvelope): Omit<IntegrationInvocationEnvelope, 'capabilityToken'> & { capabilityToken: '[REDACTED]' } {\n return {\n ...envelope,\n capabilityToken: '[REDACTED]',\n input: redactUnknown(envelope.input),\n }\n}\n\nexport function redactCapability(capability: IntegrationCapability): IntegrationCapability {\n return {\n ...capability,\n metadata: redactUnknown(capability.metadata) as Record<string, unknown> | undefined,\n }\n}\n\nexport function normalizeIntegrationResult(result: IntegrationActionResult): NormalizedIntegrationResult {\n const output = result.output as { approvalRequired?: unknown; approval?: IntegrationApprovalRequest } | undefined\n if (!result.ok && output?.approvalRequired === true && output.approval) {\n return {\n status: 'approval_required',\n action: result.action,\n approval: output.approval,\n metadata: result.metadata,\n }\n }\n if (!result.ok) {\n return {\n status: 'failed',\n action: result.action,\n error: String(result.output ?? result.warnings?.[0] ?? 'integration action failed'),\n metadata: result.metadata,\n }\n }\n return {\n status: 'ok',\n action: result.action,\n output: result.output,\n metadata: result.metadata,\n }\n}\n\nexport async function dispatchIntegrationInvocation(\n envelope: IntegrationInvocationEnvelope,\n options: IntegrationSandboxHostOptions,\n): Promise<NormalizedIntegrationResult> {\n try {\n validateIntegrationInvocationEnvelope(envelope, options)\n const result = await options.hub.invokeWithCapability(\n envelope.capabilityToken,\n invocationRequestFromEnvelope(envelope),\n )\n return normalizeIntegrationResult(result)\n } catch (error) {\n return {\n status: 'failed',\n action: typeof envelope?.action === 'string' ? envelope.action : 'unknown',\n error: error instanceof Error ? error.message : 'Integration invocation failed.',\n }\n }\n}\n\nexport class IntegrationSandboxHost {\n private readonly options: IntegrationSandboxHostOptions\n\n constructor(options: IntegrationSandboxHostOptions) {\n this.options = options\n }\n\n dispatch(envelope: IntegrationInvocationEnvelope): Promise<NormalizedIntegrationResult> {\n return dispatchIntegrationInvocation(envelope, this.options)\n }\n}\n\nfunction redactUnknown(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactUnknown)\n if (!value || typeof value !== 'object') return value\n const out: Record<string, unknown> = {}\n for (const [key, child] of Object.entries(value)) {\n if (/token|secret|password|authorization|api[_-]?key|credential/i.test(key)) {\n out[key] = '[REDACTED]'\n } else {\n out[key] = redactUnknown(child)\n }\n }\n return out\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n","import type {\n IntegrationActionRisk,\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationDataClass,\n} from './index.js'\n\nexport interface ImportCatalogOptions {\n providerId: string\n connectorId: string\n connectorTitle: string\n category?: IntegrationConnectorCategory\n auth?: IntegrationConnector['auth']\n scopes?: string[]\n dataClass?: IntegrationDataClass\n defaultRisk?: IntegrationActionRisk\n}\n\nexport interface OpenApiDocument {\n openapi?: string\n swagger?: string\n info?: { title?: string }\n paths?: Record<string, Record<string, OpenApiOperation | unknown>>\n}\n\nexport interface OpenApiOperation {\n operationId?: string\n summary?: string\n description?: string\n parameters?: unknown[]\n requestBody?: unknown\n responses?: unknown\n security?: Array<Record<string, string[]>>\n tags?: string[]\n}\n\nexport interface GraphqlOperationSpec {\n name: string\n kind: 'query' | 'mutation'\n description?: string\n inputSchema?: unknown\n outputSchema?: unknown\n requiredScopes?: string[]\n}\n\nexport interface McpCatalogTool {\n name: string\n description?: string\n inputSchema?: unknown\n annotations?: {\n readOnlyHint?: boolean\n destructiveHint?: boolean\n openWorldHint?: boolean\n title?: string\n }\n}\n\nexport interface McpCatalog {\n tools: McpCatalogTool[]\n}\n\nconst HTTP_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete'])\n\nexport function importOpenApiConnector(document: OpenApiDocument, options: ImportCatalogOptions): IntegrationConnector {\n const actions: IntegrationConnectorAction[] = []\n for (const [path, methods] of Object.entries(document.paths ?? {})) {\n for (const [method, rawOperation] of Object.entries(methods)) {\n const normalizedMethod = method.toLowerCase()\n if (!HTTP_METHODS.has(normalizedMethod) || !isObject(rawOperation)) continue\n const operation = rawOperation as OpenApiOperation\n const operationId = operation.operationId ?? `${normalizedMethod}_${path.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '')}`\n actions.push({\n id: operationId,\n title: operation.summary ?? titleFromId(operationId),\n risk: riskFromHttpMethod(normalizedMethod, operation, options.defaultRisk),\n requiredScopes: scopesFromOpenApiOperation(operation, options.scopes ?? []),\n dataClass: options.dataClass ?? 'private',\n description: operation.description ?? operation.summary ?? `${normalizedMethod.toUpperCase()} ${path}`,\n approvalRequired: riskFromHttpMethod(normalizedMethod, operation, options.defaultRisk) !== 'read',\n inputSchema: openApiInputSchema(path, normalizedMethod, operation),\n outputSchema: operation.responses,\n })\n }\n }\n return connectorFromActions(options, actions)\n}\n\nexport function importGraphqlConnector(operations: GraphqlOperationSpec[], options: ImportCatalogOptions): IntegrationConnector {\n return connectorFromActions(options, operations.map((operation) => ({\n id: operation.name,\n title: titleFromId(operation.name),\n risk: operation.kind === 'query' ? 'read' : options.defaultRisk ?? 'write',\n requiredScopes: operation.requiredScopes ?? options.scopes ?? [],\n dataClass: options.dataClass ?? 'private',\n description: operation.description,\n approvalRequired: operation.kind === 'mutation',\n inputSchema: operation.inputSchema,\n outputSchema: operation.outputSchema,\n })))\n}\n\nexport function importMcpConnector(catalog: McpCatalog, options: ImportCatalogOptions): IntegrationConnector {\n return connectorFromActions(options, catalog.tools.map((tool) => {\n const risk = riskFromMcpTool(tool, options.defaultRisk)\n return {\n id: tool.name,\n title: tool.annotations?.title ?? titleFromId(tool.name),\n risk,\n requiredScopes: options.scopes ?? [],\n dataClass: options.dataClass ?? 'private',\n description: tool.description,\n approvalRequired: risk !== 'read',\n inputSchema: tool.inputSchema,\n }\n }))\n}\n\nfunction connectorFromActions(options: ImportCatalogOptions, actions: IntegrationConnectorAction[]): IntegrationConnector {\n const scopes = unique([\n ...(options.scopes ?? []),\n ...actions.flatMap((action) => action.requiredScopes),\n ])\n return {\n id: options.connectorId,\n providerId: options.providerId,\n title: options.connectorTitle,\n category: options.category ?? 'other',\n auth: options.auth ?? 'custom',\n scopes,\n actions,\n metadata: { source: 'catalog-importer' },\n }\n}\n\nfunction riskFromHttpMethod(method: string, operation: OpenApiOperation, fallback?: IntegrationActionRisk): IntegrationActionRisk {\n if (method === 'get') return 'read'\n if (method === 'delete') return 'destructive'\n const text = `${operation.operationId ?? ''} ${operation.summary ?? ''} ${operation.description ?? ''}`.toLowerCase()\n if (/\\b(delete|remove|destroy|cancel|void|revoke|drop)\\b/.test(text)) return 'destructive'\n return fallback && fallback !== 'read' ? fallback : 'write'\n}\n\nfunction riskFromMcpTool(tool: McpCatalogTool, fallback?: IntegrationActionRisk): IntegrationActionRisk {\n if (tool.annotations?.destructiveHint) return 'destructive'\n if (tool.annotations?.readOnlyHint) return 'read'\n const text = `${tool.name} ${tool.description ?? ''}`.toLowerCase()\n if (/\\b(delete|remove|destroy|cancel|void|revoke|drop)\\b/.test(text)) return 'destructive'\n if (/\\b(get|list|read|search|find|fetch|query)\\b/.test(text)) return 'read'\n return fallback ?? 'write'\n}\n\nfunction scopesFromOpenApiOperation(operation: OpenApiOperation, fallback: string[]): string[] {\n const scopes = (operation.security ?? []).flatMap((entry) => Object.values(entry).flat())\n return unique(scopes.length > 0 ? scopes : fallback)\n}\n\nfunction openApiInputSchema(path: string, method: string, operation: OpenApiOperation): unknown {\n return {\n type: 'object',\n additionalProperties: true,\n properties: {\n path: { const: path },\n method: { const: method.toUpperCase() },\n parameters: { type: 'object', additionalProperties: true },\n body: operation.requestBody ?? { type: 'object', additionalProperties: true },\n },\n }\n}\n\nfunction titleFromId(id: string): string {\n return id\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n .split(/[^a-zA-Z0-9]+/g)\n .filter(Boolean)\n .map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))\n .join(' ')\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n","import type {\n CompleteAuthRequest,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationConnectorTrigger,\n IntegrationDataClass,\n IntegrationProvider,\n IntegrationProviderKind,\n StartAuthRequest,\n StartAuthResult,\n} from './index.js'\nimport { IntegrationError } from './index.js'\n\nexport interface GatewayCatalogProviderOptions {\n id: string\n kind: Extract<IntegrationProviderKind, 'nango' | 'pipedream' | 'activepieces' | 'tangle_catalog' | 'zapier' | 'executor' | 'custom'>\n fetchCatalog: () => Promise<GatewayCatalogEntry[]> | GatewayCatalogEntry[]\n startAuth?: (request: StartAuthRequest) => Promise<StartAuthResult> | StartAuthResult\n completeAuth?: (request: CompleteAuthRequest) => Promise<IntegrationConnection> | IntegrationConnection\n invokeAction?: (connection: IntegrationConnection, request: IntegrationActionRequest) => Promise<IntegrationActionResult> | IntegrationActionResult\n cacheTtlMs?: number\n now?: () => Date\n}\n\nexport interface GatewayCatalogEntry {\n id?: string\n key?: string\n name?: string\n title?: string\n category?: string\n auth?: 'oauth2' | 'api_key' | 'none' | 'custom' | string\n scopes?: string[]\n actions?: GatewayCatalogAction[]\n triggers?: GatewayCatalogTrigger[]\n metadata?: Record<string, unknown>\n}\n\nexport interface GatewayCatalogAction {\n id?: string\n key?: string\n name?: string\n title?: string\n description?: string\n risk?: 'read' | 'write' | 'destructive' | string\n scopes?: string[]\n requiredScopes?: string[]\n dataClass?: IntegrationDataClass | string\n approvalRequired?: boolean\n inputSchema?: unknown\n outputSchema?: unknown\n}\n\nexport interface GatewayCatalogTrigger {\n id?: string\n key?: string\n name?: string\n title?: string\n description?: string\n scopes?: string[]\n requiredScopes?: string[]\n dataClass?: IntegrationDataClass | string\n payloadSchema?: unknown\n}\n\nexport function createGatewayCatalogProvider(options: GatewayCatalogProviderOptions): IntegrationProvider {\n const now = options.now ?? (() => new Date())\n let cachedAt = 0\n let cached: IntegrationConnector[] | undefined\n\n async function listConnectors(): Promise<IntegrationConnector[]> {\n const ttl = options.cacheTtlMs ?? 60_000\n const current = now().getTime()\n if (cached && current - cachedAt < ttl) return cached\n const entries = await options.fetchCatalog()\n cached = normalizeGatewayCatalog(entries, {\n providerId: options.id,\n providerKind: options.kind,\n })\n cachedAt = current\n return cached\n }\n\n return {\n id: options.id,\n kind: options.kind,\n listConnectors,\n startAuth: options.startAuth,\n completeAuth: options.completeAuth,\n async invokeAction(connection, request) {\n if (!options.invokeAction) {\n throw new IntegrationError(`Gateway provider ${options.id} does not implement action invocation.`, 'action_not_found')\n }\n await assertKnownGatewayAction(await listConnectors(), connection.connectorId, request.action)\n return options.invokeAction(connection, request)\n },\n }\n}\n\nexport function normalizeGatewayCatalog(\n entries: GatewayCatalogEntry[],\n options: { providerId: string; providerKind: IntegrationProviderKind },\n): IntegrationConnector[] {\n const out: IntegrationConnector[] = []\n const seen = new Set<string>()\n for (const entry of entries) {\n const id = slug(entry.id ?? entry.key ?? entry.name ?? entry.title ?? '')\n if (!id || seen.has(id)) continue\n seen.add(id)\n const title = entry.title ?? entry.name ?? titleFromId(id)\n const actions = normalizeActions(entry.actions ?? [], entry.scopes ?? [])\n out.push({\n id,\n providerId: options.providerId,\n title,\n category: normalizeCategory(entry.category),\n auth: normalizeAuth(entry.auth),\n scopes: unique([\n ...(entry.scopes ?? []),\n ...actions.flatMap((action) => action.requiredScopes),\n ]),\n actions: actions.length > 0 ? actions : defaultActionsFor(entry.category, entry.scopes ?? []),\n triggers: normalizeTriggers(entry.triggers ?? [], entry.scopes ?? []),\n metadata: {\n ...(entry.metadata ?? {}),\n source: 'gateway-catalog',\n providerKind: options.providerKind,\n executable: true,\n },\n })\n }\n return out\n}\n\nasync function assertKnownGatewayAction(connectors: IntegrationConnector[], connectorId: string, actionId: string): Promise<void> {\n const connector = connectors.find((candidate) => candidate.id === connectorId)\n if (!connector) throw new IntegrationError(`Connector ${connectorId} not found.`, 'connector_not_found')\n if (!connector.actions.some((action) => action.id === actionId)) {\n throw new IntegrationError(`Action ${actionId} is not defined by connector ${connectorId}.`, 'action_not_found')\n }\n}\n\nfunction normalizeActions(actions: GatewayCatalogAction[], fallbackScopes: string[]): IntegrationConnectorAction[] {\n return actions.map((action) => {\n const id = slug(action.id ?? action.key ?? action.name ?? action.title ?? '')\n return {\n id,\n title: action.title ?? action.name ?? titleFromId(id),\n risk: normalizeRisk(action.risk),\n requiredScopes: unique([\n ...(action.requiredScopes ?? []),\n ...(action.scopes ?? []),\n ...((action.requiredScopes?.length || action.scopes?.length) ? [] : fallbackScopes),\n ]),\n dataClass: normalizeDataClass(action.dataClass),\n description: action.description,\n approvalRequired: action.approvalRequired ?? normalizeRisk(action.risk) !== 'read',\n inputSchema: action.inputSchema,\n outputSchema: action.outputSchema,\n }\n }).filter((action) => action.id)\n}\n\nfunction normalizeTriggers(triggers: GatewayCatalogTrigger[], fallbackScopes: string[]): IntegrationConnectorTrigger[] | undefined {\n const normalized = triggers.map((trigger) => {\n const id = slug(trigger.id ?? trigger.key ?? trigger.name ?? trigger.title ?? '')\n return {\n id,\n title: trigger.title ?? trigger.name ?? titleFromId(id),\n requiredScopes: unique([\n ...(trigger.requiredScopes ?? []),\n ...(trigger.scopes ?? []),\n ...((trigger.requiredScopes?.length || trigger.scopes?.length) ? [] : fallbackScopes),\n ]),\n dataClass: normalizeDataClass(trigger.dataClass),\n description: trigger.description,\n payloadSchema: trigger.payloadSchema,\n }\n }).filter((trigger) => trigger.id)\n return normalized.length > 0 ? normalized : undefined\n}\n\nfunction defaultActionsFor(category: string | undefined, scopes: string[]): IntegrationConnectorAction[] {\n const readScope = scopes.find((scope) => scope.endsWith('.read')) ?? scopes[0]\n const writeScope = scopes.find((scope) => scope.endsWith('.write')) ?? scopes[1] ?? readScope\n const requiredRead = readScope ? [readScope] : []\n const requiredWrite = writeScope ? [writeScope] : []\n const dataClass = normalizeDataClass(category === 'finance' || category === 'commerce' || category === 'hr' ? 'sensitive' : 'private')\n return [\n {\n id: 'records.search',\n title: 'Search records',\n risk: 'read',\n requiredScopes: requiredRead,\n dataClass,\n description: 'Search provider records.',\n },\n {\n id: 'records.read',\n title: 'Read record',\n risk: 'read',\n requiredScopes: requiredRead,\n dataClass,\n description: 'Read a provider record.',\n },\n {\n id: 'records.upsert',\n title: 'Upsert record',\n risk: 'write',\n requiredScopes: requiredWrite,\n dataClass,\n approvalRequired: true,\n description: 'Create or update a provider record.',\n },\n ]\n}\n\nfunction normalizeCategory(category: string | undefined): IntegrationConnectorCategory {\n const value = slug(category ?? '')\n if (value === 'mail') return 'email'\n if (value === 'messaging' || value === 'communication' || value === 'communications') return 'chat'\n if (value === 'file' || value === 'files') return 'storage'\n if (value === 'project-management' || value === 'automation') return 'workflow'\n if (value === 'developer' || value === 'devops') return 'workflow'\n if (value === 'support') return 'crm'\n if ([\n 'email',\n 'calendar',\n 'chat',\n 'crm',\n 'storage',\n 'docs',\n 'database',\n 'webhook',\n 'workflow',\n 'internal',\n 'other',\n ].includes(value)) return value as IntegrationConnectorCategory\n return 'other'\n}\n\nfunction normalizeAuth(auth: GatewayCatalogEntry['auth']): IntegrationConnector['auth'] {\n if (auth === 'oauth2') return 'oauth2'\n if (auth === 'api_key' || auth === 'api-key' || auth === 'apikey') return 'api_key'\n if (auth === 'none') return 'none'\n return 'custom'\n}\n\nfunction normalizeRisk(risk: GatewayCatalogAction['risk']): IntegrationConnectorAction['risk'] {\n if (risk === 'read' || risk === 'write' || risk === 'destructive') return risk\n return 'write'\n}\n\nfunction normalizeDataClass(dataClass: GatewayCatalogAction['dataClass']): IntegrationDataClass {\n if (dataClass === 'public' || dataClass === 'internal' || dataClass === 'private' || dataClass === 'sensitive' || dataClass === 'secret') return dataClass\n return 'private'\n}\n\nfunction slug(value: string): string {\n return value.trim().toLowerCase()\n .replace(/&/g, 'and')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction titleFromId(id: string): string {\n return id.split('-').filter(Boolean).map((part) => part.slice(0, 1).toUpperCase() + part.slice(1)).join(' ')\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n","import {\n buildActivepiecesConnectors,\n listActivepiecesCatalogEntries,\n type ActivepiecesCatalogEntry,\n} from './activepieces-catalog.js'\nimport { createCatalogExecutorProvider } from './catalog-executor.js'\nimport type {\n CompleteAuthRequest,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationProvider,\n StartAuthRequest,\n StartAuthResult,\n} from './index.js'\nimport { IntegrationError } from './index.js'\n\nexport interface ActivepiecesExecutorInvocation {\n connection: IntegrationConnection\n request: IntegrationActionRequest\n connector: IntegrationConnector\n catalogEntry: ActivepiecesCatalogEntry\n piece: {\n id: string\n npmPackage?: string\n version?: string\n actionId: string\n upstreamActionName?: string\n }\n}\n\nexport interface ActivepiecesExecutorProviderOptions {\n id?: string\n connectors?: IntegrationConnector[]\n startAuth?: (request: StartAuthRequest) => Promise<StartAuthResult> | StartAuthResult\n completeAuth?: (request: CompleteAuthRequest) => Promise<IntegrationConnection> | IntegrationConnection\n executeAction: (invocation: ActivepiecesExecutorInvocation) => Promise<IntegrationActionResult> | IntegrationActionResult\n}\n\nexport function createActivepiecesExecutorProvider(options: ActivepiecesExecutorProviderOptions): IntegrationProvider {\n const providerId = options.id ?? 'activepieces'\n const connectors = options.connectors ?? buildActivepiecesConnectors({\n providerId,\n includeCatalogActions: true,\n executable: true,\n })\n const byEntry = new Map(listActivepiecesCatalogEntries().map((entry) => [entry.id, entry]))\n\n return createCatalogExecutorProvider({\n id: providerId,\n kind: 'activepieces',\n connectors,\n startAuth: options.startAuth,\n completeAuth: options.completeAuth,\n executeAction: async ({ connection, request, connector, action }) => {\n const catalogEntry = byEntry.get(connector.id)\n if (!catalogEntry) {\n throw new IntegrationError(`Activepieces catalog entry ${connector.id} not found.`, 'connector_not_found')\n }\n const catalogAction = catalogEntry.actions.find((candidate) => candidate.id === action.id)\n return options.executeAction({\n connection,\n request,\n connector,\n catalogEntry,\n piece: {\n id: catalogEntry.id,\n npmPackage: catalogEntry.npmPackage,\n version: catalogEntry.version,\n actionId: action.id,\n upstreamActionName: catalogAction?.upstreamName,\n },\n })\n },\n })\n}\n","import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto'\nimport type {\n ActivepiecesExecutorInvocation,\n ActivepiecesExecutorProviderOptions,\n} from './activepieces-provider.js'\nimport type {\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n} from './index.js'\n\nexport const ACTIVEPIECES_RUNTIME_SIGNATURE_HEADER = 'x-tangle-activepieces-signature'\nexport const TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER = 'x-tangle-catalog-signature'\n\nexport interface TangleCatalogRuntimeActionRequest {\n id: string\n input: unknown\n idempotencyKey?: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface TangleCatalogRuntimePiece {\n id: string\n packageName?: string\n version?: string\n actionId: string\n upstreamActionName?: string\n}\n\nexport interface TangleCatalogHttpExecutorOptions {\n endpoint: string\n path?: string\n signatureHeader?: string\n secret?: string\n fetchImpl?: typeof fetch\n headers?: Record<string, string>\n timeoutMs?: number\n requestId?: () => string\n}\n\nexport interface TangleCatalogHttpExecutorInvocation extends Omit<ActivepiecesExecutorInvocation, 'catalogEntry' | 'piece'> {\n catalogEntry: unknown\n piece: TangleCatalogRuntimePiece\n}\n\n/**\n * @deprecated Use the Tangle catalog runtime types. This name is kept only for\n * compatibility with the upstream catalog ingestion backend.\n */\nexport interface ActivepiecesRuntimeRequest {\n version: 1\n requestId: string\n providerId: string\n connection: IntegrationConnection\n connector: Pick<IntegrationConnector, 'id' | 'title' | 'auth' | 'scopes' | 'metadata'>\n piece: ActivepiecesExecutorInvocation['piece']\n action: TangleCatalogRuntimeActionRequest\n}\n\n/**\n * @deprecated Use `TangleCatalogHttpExecutorOptions`.\n */\nexport type ActivepiecesHttpExecutorOptions = TangleCatalogHttpExecutorOptions\n\n/**\n * @deprecated Use `createTangleCatalogHttpExecutor`.\n */\nexport function createActivepiecesHttpExecutor(\n options: ActivepiecesHttpExecutorOptions,\n): ActivepiecesExecutorProviderOptions['executeAction'] {\n const endpoint = options.endpoint.replace(/\\/$/, '')\n const path = options.path ?? '/v1/activepieces/actions/invoke'\n const normalizedPath = path.startsWith('/') ? path : `/${path}`\n const signatureHeader = options.signatureHeader ?? ACTIVEPIECES_RUNTIME_SIGNATURE_HEADER\n const fetchImpl = options.fetchImpl ?? fetch\n const requestId = options.requestId ?? (() => `apexec_${randomUUID()}`)\n return async (invocation) => {\n const body = buildActivepiecesRuntimeRequest(invocation, requestId())\n const serialized = JSON.stringify(body)\n const response = await fetchImpl(`${endpoint}${normalizedPath}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...options.headers,\n ...(options.secret\n ? { [signatureHeader]: signActivepiecesRuntimeRequest(serialized, options.secret) }\n : {}),\n },\n body: serialized,\n signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),\n })\n const parsed = await response.json().catch(() => undefined) as IntegrationActionResult | undefined\n if (!response.ok) {\n return parsed ?? {\n ok: false,\n action: invocation.request.action,\n output: { message: `Activepieces runtime returned HTTP ${response.status}.` },\n }\n }\n return parsed ?? {\n ok: false,\n action: invocation.request.action,\n output: { message: 'Activepieces runtime returned an empty response.' },\n }\n }\n}\n\n/**\n * @deprecated Use `buildTangleCatalogRuntimeRequest`.\n */\nexport function buildActivepiecesRuntimeRequest(\n invocation: ActivepiecesExecutorInvocation,\n requestId = `apexec_${randomUUID()}`,\n): ActivepiecesRuntimeRequest {\n return {\n version: 1,\n requestId,\n providerId: invocation.connection.providerId,\n connection: invocation.connection,\n connector: {\n id: invocation.connector.id,\n title: invocation.connector.title,\n auth: invocation.connector.auth,\n scopes: invocation.connector.scopes,\n metadata: invocation.connector.metadata,\n },\n piece: invocation.piece,\n action: {\n id: invocation.request.action,\n input: invocation.request.input,\n idempotencyKey: invocation.request.idempotencyKey,\n dryRun: invocation.request.dryRun,\n metadata: invocation.request.metadata,\n },\n }\n}\n\n/**\n * @deprecated Use `signTangleCatalogRuntimeRequest`.\n */\nexport function signActivepiecesRuntimeRequest(serializedBody: string, secret: string): string {\n return `sha256=${createHmac('sha256', secret).update(serializedBody).digest('hex')}`\n}\n\n/**\n * @deprecated Use `verifyTangleCatalogRuntimeSignature`.\n */\nexport function verifyActivepiecesRuntimeSignature(\n serializedBody: string,\n signature: string | null | undefined,\n secret: string,\n): boolean {\n if (!signature) return false\n const expected = signActivepiecesRuntimeRequest(serializedBody, secret)\n const left = Buffer.from(signature)\n const right = Buffer.from(expected)\n return left.length === right.length && timingSafeEqual(left, right)\n}\n\nexport interface TangleCatalogRuntimeRequest {\n version: 1\n requestId: string\n providerId: string\n connection: IntegrationConnection\n connector: Pick<IntegrationConnector, 'id' | 'title' | 'auth' | 'scopes' | 'metadata'>\n piece: TangleCatalogRuntimePiece\n action: TangleCatalogRuntimeActionRequest\n}\n\nexport function createTangleCatalogHttpExecutor(\n options: TangleCatalogHttpExecutorOptions,\n): (invocation: TangleCatalogHttpExecutorInvocation) => Promise<IntegrationActionResult> {\n const endpoint = options.endpoint.replace(/\\/$/, '')\n const path = options.path ?? '/v1/integration-catalog/actions/invoke'\n const normalizedPath = path.startsWith('/') ? path : `/${path}`\n const signatureHeader = options.signatureHeader ?? TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER\n const fetchImpl = options.fetchImpl ?? fetch\n const requestId = options.requestId ?? (() => `tcat_${randomUUID()}`)\n return async (invocation) => {\n const body = buildTangleCatalogRuntimeRequest(invocation, requestId())\n const serialized = JSON.stringify(body)\n const response = await fetchImpl(`${endpoint}${normalizedPath}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...options.headers,\n ...(options.secret\n ? { [signatureHeader]: signTangleCatalogRuntimeRequest(serialized, options.secret) }\n : {}),\n },\n body: serialized,\n signal: AbortSignal.timeout(options.timeoutMs ?? 30_000),\n })\n const parsed = await response.json().catch(() => undefined) as IntegrationActionResult | undefined\n if (!response.ok) {\n return parsed ?? {\n ok: false,\n action: invocation.request.action,\n output: { message: `Tangle catalog runtime returned HTTP ${response.status}.` },\n }\n }\n return parsed ?? {\n ok: false,\n action: invocation.request.action,\n output: { message: 'Tangle catalog runtime returned an empty response.' },\n }\n }\n}\n\nexport function buildTangleCatalogRuntimeRequest(\n invocation: TangleCatalogHttpExecutorInvocation,\n requestId = `tcat_${randomUUID()}`,\n): TangleCatalogRuntimeRequest {\n return {\n version: 1,\n requestId,\n providerId: invocation.connection.providerId,\n connection: invocation.connection,\n connector: {\n id: invocation.connector.id,\n title: invocation.connector.title,\n auth: invocation.connector.auth,\n scopes: invocation.connector.scopes,\n metadata: invocation.connector.metadata,\n },\n piece: invocation.piece,\n action: {\n id: invocation.request.action,\n input: invocation.request.input,\n idempotencyKey: invocation.request.idempotencyKey,\n dryRun: invocation.request.dryRun,\n metadata: invocation.request.metadata,\n },\n }\n}\n\nexport const signTangleCatalogRuntimeRequest = signActivepiecesRuntimeRequest\nexport const verifyTangleCatalogRuntimeSignature = verifyActivepiecesRuntimeSignature\n","import {\n TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER,\n signTangleCatalogRuntimeRequest,\n verifyTangleCatalogRuntimeSignature,\n type TangleCatalogRuntimeRequest,\n} from './activepieces-runtime.js'\nimport { randomUUID } from 'node:crypto'\nimport { listActivepiecesCatalogEntries } from './activepieces-catalog.js'\nimport { buildTangleIntegrationCatalogConnectors } from './tangle-catalog.js'\nimport type {\n ConnectorCredentials,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationSecretStore,\n} from './index.js'\n\nexport {\n TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER,\n signTangleCatalogRuntimeRequest,\n verifyTangleCatalogRuntimeSignature,\n}\n\nexport interface TangleCatalogRuntimeInvocation {\n request: TangleCatalogRuntimeRequest\n connection: IntegrationConnection\n connector: IntegrationConnector\n action: IntegrationConnectorAction\n}\n\nexport interface TangleCatalogRuntimeHandlerOptions {\n secret?: string\n requireSignature?: boolean\n signatureHeader?: string\n connectors?: IntegrationConnector[]\n maxBodyBytes?: number\n executeAction: (invocation: TangleCatalogRuntimeInvocation) => Promise<IntegrationActionResult> | IntegrationActionResult\n}\n\nexport interface TangleCatalogInstalledPackageExecutorOptions {\n moduleLoader?: (packageName: string) => Promise<unknown> | unknown\n actionAliases?: Record<string, Record<string, string>>\n allowFuzzyActionMatch?: boolean\n resolveAuth?: (connection: IntegrationConnection) => Promise<unknown> | unknown\n beforeRun?: (invocation: TangleCatalogRuntimeInvocation) => Promise<void> | void\n}\n\nexport interface TangleCatalogAuthResolverOptions {\n secrets: IntegrationSecretStore\n mapCredentials?: (input: {\n connection: IntegrationConnection\n credentials: ConnectorCredentials\n connectorId: string\n }) => unknown\n}\n\nexport interface TangleCatalogHttpAuthResolverOptions {\n endpoint: string\n secret: string\n path?: string\n timeoutMs?: number\n fetchImpl?: typeof fetch\n headers?: Record<string, string>\n requestId?: () => string\n}\n\nexport interface TangleCatalogHttpAuthResolverRequest {\n version: 1\n requestId: string\n providerId: string\n connectorId: string\n connectionId: string\n secretRef?: IntegrationConnection['secretRef']\n}\n\nexport interface TangleCatalogRuntimeModuleAction {\n name?: string\n displayName?: string\n run?: (context: {\n auth: unknown\n propsValue: unknown\n input: unknown\n connection: IntegrationConnection\n request: TangleCatalogRuntimeRequest\n }) => Promise<unknown> | unknown\n}\n\nexport interface TangleCatalogRuntimeHttpRequest {\n body: string | Uint8Array | TangleCatalogRuntimeRequest\n headers?: Headers | Record<string, string | string[] | undefined>\n}\n\nexport interface TangleCatalogRuntimeHttpResponse {\n status: number\n headers: Record<string, string>\n body: IntegrationActionResult | {\n ok: false\n action: string\n output: {\n code: string\n message: string\n }\n }\n}\n\nexport interface TangleCatalogRuntimePackageCoverageRow {\n connectorId: string\n packageName: string\n packageInstalled: boolean\n packageLoads: boolean\n pieceExportFound: boolean\n actionMappingsVerified: number\n actionMappingsTotal: number\n triggerMappingsFound: number\n triggerMappingsTotal: number\n triggerHostingSupported: boolean\n error?: string\n}\n\nexport interface TangleCatalogRuntimePackageCoverageOptions {\n connectorIds?: string[]\n moduleLoader?: (packageName: string) => Promise<unknown> | unknown\n}\n\nexport function createTangleCatalogRuntimeHandler(options: TangleCatalogRuntimeHandlerOptions) {\n const connectors = options.connectors ?? buildTangleIntegrationCatalogConnectors({\n includeCatalogActions: true,\n executable: true,\n })\n const byConnector = new Map(connectors.map((connector) => [connector.id, connector]))\n const requireSignature = options.requireSignature ?? Boolean(options.secret)\n const signatureHeader = options.signatureHeader ?? TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER\n const maxBodyBytes = options.maxBodyBytes ?? 1_000_000\n\n return async function handleTangleCatalogRuntimeRequest(\n input: TangleCatalogRuntimeHttpRequest,\n ): Promise<TangleCatalogRuntimeHttpResponse> {\n const serialized = serializeBody(input.body)\n if (Buffer.byteLength(serialized, 'utf8') > maxBodyBytes) {\n return errorResponse(413, 'unknown', 'payload_too_large', 'Tangle catalog runtime request is too large.')\n }\n\n if (requireSignature) {\n if (!options.secret) {\n return errorResponse(500, 'unknown', 'runtime_misconfigured', 'Tangle catalog runtime secret is not configured.')\n }\n const signature = readHeader(input.headers, signatureHeader)\n if (!verifyTangleCatalogRuntimeSignature(serialized, signature, options.secret)) {\n return errorResponse(401, 'unknown', 'signature_invalid', 'Tangle catalog runtime signature is invalid.')\n }\n }\n\n const parsed = parseRuntimeRequest(serialized)\n if (!parsed.ok) return parsed.response\n\n const request = parsed.request\n if (request.providerId !== request.connection.providerId) {\n return errorResponse(400, request.action.id, 'provider_mismatch', 'Request providerId does not match connection providerId.')\n }\n const connector = byConnector.get(request.connector.id)\n if (!connector) {\n return errorResponse(404, request.action.id, 'connector_not_found', `Connector ${request.connector.id} is not in the Tangle catalog runtime.`)\n }\n if (request.connection.connectorId !== connector.id) {\n return errorResponse(400, request.action.id, 'connector_mismatch', 'Connection connectorId does not match runtime connector.')\n }\n if (request.connection.providerId !== connector.providerId) {\n return errorResponse(400, request.action.id, 'provider_mismatch', 'Connection providerId does not match runtime connector.')\n }\n const action = connector.actions.find((candidate) => candidate.id === request.action.id)\n if (!action) {\n return errorResponse(404, request.action.id, 'action_not_found', `Action ${request.action.id} is not defined by connector ${connector.id}.`)\n }\n\n const result = await options.executeAction({\n request,\n connection: request.connection,\n connector,\n action,\n })\n return {\n status: result.ok ? 200 : 502,\n headers: { 'content-type': 'application/json' },\n body: result,\n }\n }\n}\n\nexport function createTangleCatalogInstalledPackageExecutor(\n options: TangleCatalogInstalledPackageExecutorOptions = {},\n): TangleCatalogRuntimeHandlerOptions['executeAction'] {\n const packageByConnector = new Map(\n listActivepiecesCatalogEntries()\n .filter((entry) => entry.npmPackage)\n .map((entry) => [entry.id, entry.npmPackage!]),\n )\n const moduleCache = new Map<string, Promise<unknown>>()\n\n return async (invocation) => {\n await options.beforeRun?.(invocation)\n const packageName = packageByConnector.get(invocation.connector.id)\n if (!packageName) {\n return runtimeFailure(invocation.action.id, 'runtime_not_available', `No installed runtime package is known for connector ${invocation.connector.id}.`)\n }\n if (invocation.request.piece.packageName && invocation.request.piece.packageName !== packageName) {\n return runtimeFailure(\n invocation.action.id,\n 'runtime_package_mismatch',\n `Runtime package ${invocation.request.piece.packageName} does not match catalog package ${packageName}.`,\n )\n }\n\n const loaded = await loadRuntimeModule(packageName, options.moduleLoader, moduleCache)\n if (!loaded.ok) {\n return runtimeFailure(invocation.action.id, 'runtime_not_installed', loaded.message)\n }\n\n const piece = findPieceExport(loaded.module, invocation.connector.id)\n if (!piece) {\n return runtimeFailure(invocation.action.id, 'runtime_invalid', `Runtime package ${packageName} does not export a recognizable piece for ${invocation.connector.id}.`)\n }\n\n const action = findRuntimeAction(piece, invocation, options.actionAliases, options.allowFuzzyActionMatch ?? false)\n if (!action?.run) {\n return runtimeFailure(invocation.action.id, 'action_not_implemented', `Runtime package ${packageName} does not expose executable action ${invocation.action.id}.`)\n }\n\n try {\n const output = await action.run({\n auth: await options.resolveAuth?.(invocation.connection),\n propsValue: invocation.request.action.input,\n input: invocation.request.action.input,\n connection: invocation.connection,\n request: invocation.request,\n })\n return {\n ok: true,\n action: invocation.action.id,\n output,\n }\n } catch (error) {\n return runtimeFailure(\n invocation.action.id,\n 'runtime_action_failed',\n error instanceof Error ? error.message : 'Runtime action failed.',\n )\n }\n }\n}\n\nexport async function auditTangleCatalogRuntimePackages(\n options: TangleCatalogRuntimePackageCoverageOptions = {},\n): Promise<TangleCatalogRuntimePackageCoverageRow[]> {\n const only = options.connectorIds ? new Set(options.connectorIds) : undefined\n const rows: TangleCatalogRuntimePackageCoverageRow[] = []\n const moduleCache = new Map<string, Promise<unknown>>()\n const entries = listActivepiecesCatalogEntries()\n .filter((entry) => entry.npmPackage && (!only || only.has(entry.id)))\n\n for (const entry of entries) {\n const packageName = entry.npmPackage!\n const base = {\n connectorId: entry.id,\n packageName,\n actionMappingsTotal: entry.actions.length,\n triggerMappingsTotal: entry.triggers.length,\n }\n const loaded = await loadRuntimeModule(packageName, options.moduleLoader, moduleCache)\n if (!loaded.ok) {\n rows.push({\n ...base,\n packageInstalled: false,\n packageLoads: false,\n pieceExportFound: false,\n actionMappingsVerified: 0,\n triggerMappingsFound: 0,\n triggerHostingSupported: false,\n error: loaded.message,\n })\n continue\n }\n const piece = findPieceExport(loaded.module, entry.id)\n const actions = piece?.actions ?? []\n const triggers = piece?.triggers ?? []\n rows.push({\n ...base,\n packageInstalled: true,\n packageLoads: true,\n pieceExportFound: Boolean(piece),\n actionMappingsVerified: entry.actions.filter((action) => hasRuntimeName(actions, [\n action.id,\n action.title,\n action.upstreamName,\n ])).length,\n triggerMappingsFound: entry.triggers.filter((trigger) => hasRuntimeName(triggers, [\n trigger.id,\n trigger.title,\n trigger.upstreamName,\n ])).length,\n triggerHostingSupported: entry.triggers.length === 0 || triggers.length > 0,\n })\n }\n\n return rows\n}\n\nexport function createTangleCatalogCredentialAuthResolver(options: TangleCatalogAuthResolverOptions) {\n return async function resolveTangleCatalogAuth(connection: IntegrationConnection): Promise<unknown> {\n if (!connection.secretRef) return undefined\n const credentials = await options.secrets.get(connection.secretRef)\n if (!credentials) throw new Error(`Secret ${connection.secretRef.provider}/${connection.secretRef.id} not found.`)\n return options.mapCredentials?.({\n connection,\n credentials,\n connectorId: connection.connectorId,\n }) ?? tangleCatalogAuthValue(credentials)\n }\n}\n\nexport function createTangleCatalogHttpAuthResolver(options: TangleCatalogHttpAuthResolverOptions) {\n const endpoint = options.endpoint.replace(/\\/$/, '')\n const path = options.path ?? '/v1/integration-catalog/credentials/resolve'\n const normalizedPath = path.startsWith('/') ? path : `/${path}`\n const fetchImpl = options.fetchImpl ?? fetch\n const requestId = options.requestId ?? (() => `tcat_auth_${randomUUID()}`)\n\n return async function resolveTangleCatalogHttpAuth(connection: IntegrationConnection): Promise<unknown> {\n const body: TangleCatalogHttpAuthResolverRequest = {\n version: 1,\n requestId: requestId(),\n providerId: connection.providerId,\n connectorId: connection.connectorId,\n connectionId: connection.id,\n secretRef: connection.secretRef,\n }\n const serialized = JSON.stringify(body)\n const response = await fetchImpl(`${endpoint}${normalizedPath}`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...options.headers,\n [TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER]: signTangleCatalogRuntimeRequest(serialized, options.secret),\n },\n body: serialized,\n signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),\n })\n const parsed = await response.json().catch(() => undefined) as {\n auth?: unknown\n credentials?: ConnectorCredentials\n error?: { message?: string }\n } | undefined\n if (!response.ok) {\n throw new Error(parsed?.error?.message ?? `Credential resolver returned HTTP ${response.status}.`)\n }\n if (parsed && 'auth' in parsed) return parsed.auth\n if (parsed?.credentials) return tangleCatalogAuthValue(parsed.credentials)\n return undefined\n }\n}\n\nexport function tangleCatalogAuthValue(credentials: ConnectorCredentials): unknown {\n if (credentials.kind === 'none') return undefined\n if (credentials.kind === 'api-key') return credentials.apiKey\n if (credentials.kind === 'hmac') return credentials.secret\n if (credentials.kind === 'custom') return credentials.values\n return {\n access_token: credentials.accessToken,\n refresh_token: credentials.refreshToken,\n expires_at: credentials.expiresAt,\n }\n}\n\n\nfunction serializeBody(body: TangleCatalogRuntimeHttpRequest['body']): string {\n if (typeof body === 'string') return body\n if (body instanceof Uint8Array) return new TextDecoder().decode(body)\n return JSON.stringify(body)\n}\n\nasync function loadRuntimeModule(\n packageName: string,\n moduleLoader: TangleCatalogInstalledPackageExecutorOptions['moduleLoader'],\n moduleCache: Map<string, Promise<unknown>>,\n): Promise<{ ok: true; module: unknown } | { ok: false; message: string }> {\n try {\n const load = moduleLoader ?? ((name: string) => import(name))\n const promise = moduleCache.get(packageName) ?? Promise.resolve(load(packageName))\n moduleCache.set(packageName, promise)\n return { ok: true, module: await promise }\n } catch (error) {\n return {\n ok: false,\n message: error instanceof Error\n ? `Runtime package ${packageName} could not be loaded: ${error.message}`\n : `Runtime package ${packageName} could not be loaded.`,\n }\n }\n}\n\nfunction findPieceExport(moduleValue: unknown, connectorId: string): { actions?: unknown[]; triggers?: unknown[] } | undefined {\n const mod = moduleValue && typeof moduleValue === 'object' ? moduleValue as Record<string, unknown> : {}\n const values = [\n mod.default,\n mod[camel(connectorId)],\n mod[connectorId],\n ...Object.values(mod),\n ]\n return values.find((value): value is { actions?: unknown[]; triggers?: unknown[] } => (\n Boolean(value)\n && typeof value === 'object'\n && Array.isArray((value as { actions?: unknown[] }).actions)\n ))\n}\n\nfunction hasRuntimeName(values: unknown[], candidates: Array<string | undefined>): boolean {\n const expected = new Set(candidates.filter((value): value is string => Boolean(value)))\n return values\n .filter((value): value is { name?: string; displayName?: string } => Boolean(value) && typeof value === 'object')\n .some((value) => [value.name, value.displayName].some((name) => typeof name === 'string' && expected.has(name)))\n}\n\nfunction findRuntimeAction(\n piece: { actions?: unknown[] },\n invocation: TangleCatalogRuntimeInvocation,\n aliases: TangleCatalogInstalledPackageExecutorOptions['actionAliases'] = {},\n allowFuzzyActionMatch = false,\n): TangleCatalogRuntimeModuleAction | undefined {\n const actions = (piece.actions ?? [])\n .filter((action): action is TangleCatalogRuntimeModuleAction => Boolean(action) && typeof action === 'object')\n const explicit = aliases[invocation.connector.id]?.[invocation.action.id]\n const candidates = new Set([\n invocation.action.id,\n invocation.action.title,\n invocation.request.piece.upstreamActionName,\n explicit,\n ].filter((value): value is string => Boolean(value)))\n\n for (const action of actions) {\n const names = [action.name, action.displayName].filter((value): value is string => Boolean(value))\n if (names.some((name) => candidates.has(name))) return action\n if (allowFuzzyActionMatch && names.some((name) => [...candidates].some((candidate) => comparable(name) === comparable(candidate)))) return action\n }\n return undefined\n}\n\nfunction runtimeFailure(action: string, code: string, message: string): IntegrationActionResult {\n return {\n ok: false,\n action,\n output: { code, message },\n }\n}\n\nfunction comparable(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\nfunction camel(value: string): string {\n return value.replace(/[-_.]+([a-z0-9])/g, (_, char: string) => char.toUpperCase())\n}\n\nfunction parseRuntimeRequest(serialized: string):\n | { ok: true; request: TangleCatalogRuntimeRequest }\n | { ok: false; response: TangleCatalogRuntimeHttpResponse } {\n try {\n const request = JSON.parse(serialized) as Partial<TangleCatalogRuntimeRequest>\n if (request.version !== 1) {\n return { ok: false, response: errorResponse(400, request.action?.id ?? 'unknown', 'version_invalid', 'Unsupported Tangle catalog runtime request version.') }\n }\n if (!request.connection || !request.connector || !request.action?.id) {\n return { ok: false, response: errorResponse(400, request.action?.id ?? 'unknown', 'request_invalid', 'Tangle catalog runtime request is missing required fields.') }\n }\n return { ok: true, request: request as TangleCatalogRuntimeRequest }\n } catch {\n return { ok: false, response: errorResponse(400, 'unknown', 'json_invalid', 'Tangle catalog runtime request body is not valid JSON.') }\n }\n}\n\nfunction readHeader(headers: TangleCatalogRuntimeHttpRequest['headers'], name: string): string | undefined {\n if (!headers) return undefined\n if (headers instanceof Headers) return headers.get(name) ?? undefined\n const wanted = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== wanted) continue\n if (Array.isArray(value)) return value[0]\n return value\n }\n return undefined\n}\n\nfunction errorResponse(\n status: number,\n action: string,\n code: string,\n message: string,\n): TangleCatalogRuntimeHttpResponse {\n return {\n status,\n headers: { 'content-type': 'application/json' },\n body: {\n ok: false,\n action,\n output: { code, message },\n },\n }\n}\n","import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport {\n createTangleCatalogHttpAuthResolver,\n createTangleCatalogInstalledPackageExecutor,\n createTangleCatalogRuntimeHandler,\n type TangleCatalogHttpAuthResolverOptions,\n type TangleCatalogInstalledPackageExecutorOptions,\n type TangleCatalogRuntimeHandlerOptions,\n} from './tangle-catalog-runtime.js'\n\nexport interface TangleCatalogRuntimeNodeServerOptions {\n secret: string\n host?: string\n port?: number\n path?: string\n maxBodyBytes?: number\n requireSignature?: boolean\n authResolver?: false | TangleCatalogHttpAuthResolverOptions\n executor?: Omit<TangleCatalogInstalledPackageExecutorOptions, 'resolveAuth'> & {\n resolveAuth?: TangleCatalogInstalledPackageExecutorOptions['resolveAuth']\n }\n onLog?: (event: {\n level: 'info' | 'warn' | 'error'\n message: string\n metadata?: Record<string, unknown>\n }) => void\n}\n\nexport interface StartedTangleCatalogRuntimeNodeServer {\n server: Server\n url: string\n close: () => Promise<void>\n}\n\nexport function createTangleCatalogRuntimeNodeRequestListener(\n options: TangleCatalogRuntimeNodeServerOptions,\n) {\n const path = options.path ?? '/v1/integration-catalog/actions/invoke'\n const maxBodyBytes = options.maxBodyBytes ?? 1_000_000\n const resolveAuth = options.executor?.resolveAuth\n ?? (options.authResolver\n ? createTangleCatalogHttpAuthResolver(options.authResolver)\n : undefined)\n const runtime = createTangleCatalogRuntimeHandler({\n secret: options.secret,\n requireSignature: options.requireSignature,\n maxBodyBytes,\n executeAction: createTangleCatalogInstalledPackageExecutor({\n ...options.executor,\n resolveAuth,\n }),\n } satisfies TangleCatalogRuntimeHandlerOptions)\n\n return async function tangleCatalogRuntimeNodeRequestListener(\n request: IncomingMessage,\n response: ServerResponse,\n ) {\n try {\n const url = new URL(request.url ?? '/', 'http://localhost')\n if (request.method === 'GET' && url.pathname === '/health') {\n writeJson(response, 200, { ok: true })\n return\n }\n if (request.method !== 'POST' || url.pathname !== path) {\n writeJson(response, 404, {\n ok: false,\n error: { code: 'not_found', message: 'Tangle catalog runtime route not found.' },\n })\n return\n }\n\n const body = await readBody(request, maxBodyBytes)\n const result = await runtime({\n body,\n headers: request.headers,\n })\n writeJson(response, result.status, result.body, result.headers)\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Tangle catalog runtime request failed.'\n options.onLog?.({ level: 'error', message })\n writeJson(response, message === 'payload_too_large' ? 413 : 500, {\n ok: false,\n action: 'unknown',\n output: {\n code: message === 'payload_too_large' ? 'payload_too_large' : 'runtime_request_failed',\n message: message === 'payload_too_large'\n ? 'Tangle catalog runtime request is too large.'\n : message,\n },\n })\n }\n }\n}\n\nexport async function startTangleCatalogRuntimeNodeServer(\n options: TangleCatalogRuntimeNodeServerOptions,\n): Promise<StartedTangleCatalogRuntimeNodeServer> {\n const host = options.host ?? '0.0.0.0'\n const port = options.port ?? 4109\n const listener = createTangleCatalogRuntimeNodeRequestListener(options)\n const server = createServer(listener)\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n resolve()\n })\n })\n const address = server.address()\n const actualPort = typeof address === 'object' && address ? address.port : port\n const urlHost = host === '0.0.0.0' ? '127.0.0.1' : host\n return {\n server,\n url: `http://${urlHost}:${actualPort}`,\n close: () => new Promise((resolve, reject) => {\n server.close((error) => {\n if (error) reject(error)\n else resolve()\n })\n }),\n }\n}\n\nfunction readBody(request: IncomingMessage, maxBodyBytes: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n let bytes = 0\n request.on('data', (chunk: Buffer) => {\n bytes += chunk.byteLength\n if (bytes > maxBodyBytes) {\n reject(new Error('payload_too_large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))\n request.on('error', reject)\n })\n}\n\nfunction writeJson(\n response: ServerResponse,\n status: number,\n body: unknown,\n headers: Record<string, string> = {},\n) {\n response.writeHead(status, {\n 'content-type': 'application/json',\n ...headers,\n })\n response.end(JSON.stringify(body))\n}\n","import {\n buildActivepiecesConnectors,\n listActivepiecesCatalogEntries,\n} from './activepieces-catalog.js'\nimport { createActivepiecesExecutorProvider } from './activepieces-provider.js'\nimport { buildIntegrationToolCatalog } from './catalog.js'\nimport {\n buildDefaultIntegrationRegistry,\n composeIntegrationRegistry,\n type IntegrationRegistryConflict,\n type IntegrationRegistrySummary,\n summarizeIntegrationRegistry,\n} from './registry.js'\n\nexport interface IntegrationCatalogFreshnessOptions {\n liveActivepieces?: boolean\n minActivepiecesConnectors?: number\n staleConnectorDelta?: number\n fetchImpl?: typeof fetch\n}\n\nexport interface IntegrationCatalogFreshnessResult {\n ok: boolean\n generatedAt: string\n local: {\n activepiecesEntries: number\n activepiecesConnectors: number\n activepiecesActions: number\n activepiecesTriggers: number\n executableActivepiecesConnectors: number\n executableActivepiecesActions: number\n executableActivepiecesTriggers: number\n executableToolDefinitions: number\n unsupportedExecutableConnectorIds: string[]\n registryEntries: number\n registrySummary: IntegrationRegistrySummary\n conflictSamples: IntegrationRegistryConflict[]\n }\n upstream?: {\n activepiecesPieces?: number\n activepiecesDelta?: number\n checkedUrl: string\n warning?: string\n }\n warnings: string[]\n}\n\nexport const ACTIVEPIECES_PUBLIC_CATALOG_URL = 'https://www.activepieces.com/pieces'\n\nfunction parseCount(value: string | undefined): number | undefined {\n if (!value) return undefined\n const parsed = Number.parseInt(value.replace(/,/g, ''), 10)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nexport function extractActivepiecesPublicPieceCount(html: string): number | undefined {\n const showingMatch = html.match(/Showing\\s+([0-9,]+)\\s+pieces/i)\n const integrationMatch = html.match(/([0-9,]+)\\+?\\s+Integrations/i)\n return parseCount(showingMatch?.[1]) ?? parseCount(integrationMatch?.[1])\n}\n\nexport async function auditIntegrationCatalogFreshness(\n options: IntegrationCatalogFreshnessOptions = {},\n): Promise<IntegrationCatalogFreshnessResult> {\n const minActivepiecesConnectors = options.minActivepiecesConnectors ?? 600\n const staleConnectorDelta = options.staleConnectorDelta ?? 25\n const activepiecesEntries = listActivepiecesCatalogEntries()\n const activepiecesConnectors = buildActivepiecesConnectors({\n includeCatalogActions: true,\n })\n const executableActivepiecesProvider = createActivepiecesExecutorProvider({\n executeAction: () => ({ ok: true, action: 'audit.noop' }),\n })\n const executableActivepiecesConnectors = await executableActivepiecesProvider.listConnectors()\n const executableRegistry = composeIntegrationRegistry([\n {\n id: executableActivepiecesProvider.id,\n connectors: executableActivepiecesConnectors,\n },\n ])\n const executableTools = buildIntegrationToolCatalog(executableRegistry.connectors)\n const unsupportedExecutableConnectorIds = executableActivepiecesConnectors\n .filter((connector) => connector.actions.length === 0)\n .map((connector) => connector.id)\n const registry = buildDefaultIntegrationRegistry({\n includeSpecs: true,\n includeActivepieces: true,\n })\n const warnings: string[] = []\n\n if (activepiecesConnectors.length < minActivepiecesConnectors) {\n warnings.push(\n `Activepieces catalog has ${activepiecesConnectors.length} connectors, below floor ${minActivepiecesConnectors}.`,\n )\n }\n if (unsupportedExecutableConnectorIds.length > 0) {\n warnings.push(\n `Activepieces executable provider has ${unsupportedExecutableConnectorIds.length} connectors without actions.`,\n )\n }\n if (executableTools.length < activepiecesEntries.length) {\n warnings.push(\n `Activepieces executable provider produced only ${executableTools.length} tool definitions for ${activepiecesEntries.length} entries.`,\n )\n }\n\n let upstream: IntegrationCatalogFreshnessResult['upstream']\n if (options.liveActivepieces) {\n upstream = await checkActivepiecesPublicCatalog({\n localConnectorCount: activepiecesConnectors.length,\n staleConnectorDelta,\n fetchImpl: options.fetchImpl,\n warnings,\n })\n }\n\n return {\n ok: warnings.length === 0,\n generatedAt: new Date().toISOString(),\n local: {\n activepiecesEntries: activepiecesEntries.length,\n activepiecesConnectors: activepiecesConnectors.length,\n activepiecesActions: activepiecesConnectors.reduce(\n (sum, connector) => sum + connector.actions.length,\n 0,\n ),\n activepiecesTriggers: activepiecesConnectors.reduce(\n (sum, connector) => sum + (connector.triggers?.length ?? 0),\n 0,\n ),\n executableActivepiecesConnectors: executableActivepiecesConnectors.length,\n executableActivepiecesActions: executableActivepiecesConnectors.reduce(\n (sum, connector) => sum + connector.actions.length,\n 0,\n ),\n executableActivepiecesTriggers: executableActivepiecesConnectors.reduce(\n (sum, connector) => sum + (connector.triggers?.length ?? 0),\n 0,\n ),\n executableToolDefinitions: executableTools.length,\n unsupportedExecutableConnectorIds,\n registryEntries: registry.entries.length,\n registrySummary: summarizeIntegrationRegistry(registry),\n conflictSamples: registry.entries\n .flatMap((entry) => entry.conflicts)\n .slice(0, 10),\n },\n upstream,\n warnings,\n }\n}\n\nasync function checkActivepiecesPublicCatalog(input: {\n localConnectorCount: number\n staleConnectorDelta: number\n fetchImpl?: typeof fetch\n warnings: string[]\n}): Promise<IntegrationCatalogFreshnessResult['upstream']> {\n try {\n const res = await (input.fetchImpl ?? fetch)(ACTIVEPIECES_PUBLIC_CATALOG_URL, {\n headers: { accept: 'text/html' },\n signal: AbortSignal.timeout(15_000),\n })\n if (!res.ok) {\n const warning = `Activepieces freshness request failed with HTTP ${res.status}.`\n input.warnings.push(warning)\n return {\n checkedUrl: ACTIVEPIECES_PUBLIC_CATALOG_URL,\n warning,\n }\n }\n const activepiecesPieces = extractActivepiecesPublicPieceCount(await res.text())\n const activepiecesDelta =\n activepiecesPieces === undefined\n ? undefined\n : activepiecesPieces - input.localConnectorCount\n if (\n activepiecesDelta !== undefined &&\n activepiecesDelta > input.staleConnectorDelta\n ) {\n input.warnings.push(\n `Activepieces upstream appears ${activepiecesDelta} connectors ahead of the vendored package catalog.`,\n )\n }\n return {\n activepiecesPieces,\n activepiecesDelta,\n checkedUrl: ACTIVEPIECES_PUBLIC_CATALOG_URL,\n warning:\n activepiecesPieces === undefined\n ? 'Could not parse upstream piece count.'\n : undefined,\n }\n } catch (error) {\n const warning =\n error instanceof Error\n ? error.message\n : 'Activepieces freshness request failed.'\n input.warnings.push(warning)\n return {\n checkedUrl: ACTIVEPIECES_PUBLIC_CATALOG_URL,\n warning,\n }\n }\n}\n","import {\n buildIntegrationToolCatalog,\n type IntegrationToolDefinition,\n} from './catalog.js'\nimport type {\n IntegrationActor,\n IntegrationConnection,\n IntegrationConnector,\n IssuedIntegrationCapability,\n} from './index.js'\nimport type {\n IntegrationRegistry,\n IntegrationRegistryEntry,\n} from './registry.js'\n\nexport type IntegrationRequirementMode = 'read' | 'write' | 'trigger'\nexport type IntegrationRequirementStatus = 'ready' | 'missing_connection' | 'not_executable' | 'unknown_connector'\n\nexport interface IntegrationRequirement {\n id: string\n connectorId: string\n reason: string\n mode: IntegrationRequirementMode\n requiredActions?: string[]\n requiredTriggers?: string[]\n requiredScopes?: string[]\n optional?: boolean\n}\n\nexport interface IntegrationManifest {\n id: string\n title?: string\n owner?: IntegrationActor\n requirements: IntegrationRequirement[]\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationRequirementResolution {\n requirement: IntegrationRequirement\n status: IntegrationRequirementStatus\n connector?: IntegrationConnector\n registryEntry?: IntegrationRegistryEntry\n connection?: IntegrationConnection\n missingScopes: string[]\n missingActions: string[]\n missingTriggers: string[]\n message: string\n}\n\nexport interface IntegrationManifestResolution {\n manifest: IntegrationManifest\n owner: IntegrationActor\n ready: IntegrationRequirementResolution[]\n missing: IntegrationRequirementResolution[]\n optionalMissing: IntegrationRequirementResolution[]\n}\n\nexport interface IntegrationGrant {\n id: string\n manifestId: string\n requirementId: string\n owner: IntegrationActor\n grantee: IntegrationActor\n connectionId: string\n connectorId: string\n scopes: string[]\n allowedActions: string[]\n allowedTriggers: string[]\n status: 'active' | 'revoked'\n createdAt: string\n updatedAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationGrantStore {\n get(grantId: string): Promise<IntegrationGrant | undefined> | IntegrationGrant | undefined\n put(grant: IntegrationGrant): Promise<void> | void\n listByManifest(manifestId: string, grantee?: IntegrationActor): Promise<IntegrationGrant[]> | IntegrationGrant[]\n listByGrantee(grantee: IntegrationActor): Promise<IntegrationGrant[]> | IntegrationGrant[]\n listByIds?(grantIds: string[]): Promise<IntegrationGrant[]> | IntegrationGrant[]\n delete?(grantId: string): Promise<void> | void\n}\n\nexport interface IntegrationCapabilityBinding {\n requirementId: string\n connectorId: string\n connectionId: string\n grantId: string\n scopes: string[]\n allowedActions: string[]\n allowedTriggers: string[]\n capability: IssuedIntegrationCapability\n}\n\nexport interface IntegrationSandboxBundle {\n manifestId: string\n subject: IntegrationActor\n capabilities: IntegrationCapabilityBinding[]\n connectors: IntegrationConnector[]\n tools: IntegrationToolDefinition[]\n expiresAt: string\n}\n\nexport interface IntegrationRuntimeHub {\n listRegistry(): Promise<IntegrationRegistry> | IntegrationRegistry\n listConnections(owner: IntegrationActor): Promise<IntegrationConnection[]> | IntegrationConnection[]\n getConnection(connectionId: string): Promise<IntegrationConnection | undefined> | IntegrationConnection | undefined\n issueCapability(input: {\n subject: IntegrationActor\n connectionId: string\n scopes: string[]\n allowedActions: string[]\n ttlMs: number\n metadata?: Record<string, unknown>\n }): Promise<IssuedIntegrationCapability> | IssuedIntegrationCapability\n}\n\nexport interface IntegrationRuntimeOptions {\n hub: IntegrationRuntimeHub\n grants?: IntegrationGrantStore\n now?: () => Date\n}\n\nexport class InMemoryIntegrationGrantStore implements IntegrationGrantStore {\n private readonly grants = new Map<string, IntegrationGrant>()\n\n get(grantId: string): IntegrationGrant | undefined {\n return this.grants.get(grantId)\n }\n\n put(grant: IntegrationGrant): void {\n this.grants.set(grant.id, grant)\n }\n\n listByManifest(manifestId: string, grantee?: IntegrationActor): IntegrationGrant[] {\n return [...this.grants.values()].filter((grant) =>\n grant.manifestId === manifestId && (!grantee || sameActor(grant.grantee, grantee))\n )\n }\n\n listByGrantee(grantee: IntegrationActor): IntegrationGrant[] {\n return [...this.grants.values()].filter((grant) => sameActor(grant.grantee, grantee))\n }\n\n listByIds(grantIds: string[]): IntegrationGrant[] {\n const wanted = new Set(grantIds)\n return [...this.grants.values()].filter((grant) => wanted.has(grant.id))\n }\n\n delete(grantId: string): void {\n this.grants.delete(grantId)\n }\n}\n\nexport class IntegrationRuntime {\n private readonly hub: IntegrationRuntimeHub\n private readonly grants: IntegrationGrantStore\n private readonly now: () => Date\n\n constructor(options: IntegrationRuntimeOptions) {\n this.hub = options.hub\n this.grants = options.grants ?? new InMemoryIntegrationGrantStore()\n this.now = options.now ?? (() => new Date())\n }\n\n async registry(): Promise<IntegrationRegistry> {\n return this.hub.listRegistry()\n }\n\n async resolveManifest(manifest: IntegrationManifest, owner: IntegrationActor): Promise<IntegrationManifestResolution> {\n const registry = await this.registry()\n const connections = await this.hub.listConnections(owner)\n const resolutions = manifest.requirements.map((requirement) =>\n resolveRequirement(requirement, owner, registry, connections),\n )\n return {\n manifest,\n owner,\n ready: resolutions.filter((resolution) => resolution.status === 'ready'),\n missing: resolutions.filter((resolution) => resolution.status !== 'ready' && !resolution.requirement.optional),\n optionalMissing: resolutions.filter((resolution) => resolution.status !== 'ready' && resolution.requirement.optional === true),\n }\n }\n\n async createGrants(input: {\n manifest: IntegrationManifest\n owner: IntegrationActor\n grantee: IntegrationActor\n metadata?: Record<string, unknown>\n }): Promise<IntegrationGrant[]> {\n const resolution = await this.resolveManifest(input.manifest, input.owner)\n if (resolution.missing.length > 0) {\n throw new Error(`Cannot create integration grants; missing requirements: ${resolution.missing.map((r) => r.requirement.id).join(', ')}`)\n }\n const now = this.now().toISOString()\n const grants = resolution.ready.map((ready): IntegrationGrant => ({\n id: `grant_${input.manifest.id}_${ready.requirement.id}_${ready.connection!.id}`,\n manifestId: input.manifest.id,\n requirementId: ready.requirement.id,\n owner: input.owner,\n grantee: input.grantee,\n connectionId: ready.connection!.id,\n connectorId: ready.connector!.id,\n scopes: requiredScopes(ready.requirement, ready.connector!),\n allowedActions: requiredActions(ready.requirement, ready.connector!),\n allowedTriggers: requiredTriggers(ready.requirement, ready.connector!),\n status: 'active',\n createdAt: now,\n updatedAt: now,\n metadata: input.metadata,\n }))\n for (const grant of grants) await this.grants.put(grant)\n return grants\n }\n\n async buildSandboxBundle(input: {\n manifestId?: string\n grantIds?: string[]\n owner: IntegrationActor\n subject: IntegrationActor\n ttlMs: number\n grantee?: IntegrationActor\n }): Promise<IntegrationSandboxBundle> {\n const grants = await this.resolveBundleGrants(input)\n if (grants.length === 0) {\n throw new Error('Cannot build integration bundle; no active integration grants matched the request.')\n }\n const registry = await this.registry()\n const bindings: IntegrationCapabilityBinding[] = []\n const connectors: IntegrationConnector[] = []\n let expiresAt = ''\n\n for (const grant of grants) {\n const connection = await this.hub.getConnection(grant.connectionId)\n if (!connection) {\n throw new Error(`Cannot build integration bundle; connection ${grant.connectionId} not found.`)\n }\n if (!sameActor(connection.owner, input.owner)) {\n throw new Error(`Cannot build integration bundle; connection ${connection.id} belongs to a different owner.`)\n }\n if (connection.status !== 'active') {\n throw new Error(`Cannot build integration bundle; connection ${connection.id} is ${connection.status}.`)\n }\n const entry = registry.byId.get(grant.connectorId)\n if (!entry) continue\n const connector = {\n ...entry.connector,\n actions: entry.connector.actions.filter((action) => grant.allowedActions.includes(action.id)),\n triggers: entry.connector.triggers?.filter((trigger) => grant.allowedTriggers.includes(trigger.id)),\n scopes: entry.connector.scopes.filter((scope) => grant.scopes.includes(scope)),\n }\n const capability = await this.hub.issueCapability({\n subject: input.subject,\n connectionId: grant.connectionId,\n scopes: grant.scopes,\n allowedActions: grant.allowedActions,\n ttlMs: input.ttlMs,\n metadata: {\n manifestId: grant.manifestId,\n grantId: grant.id,\n requirementId: grant.requirementId,\n },\n })\n bindings.push({\n requirementId: grant.requirementId,\n connectorId: grant.connectorId,\n connectionId: grant.connectionId,\n grantId: grant.id,\n scopes: grant.scopes,\n allowedActions: grant.allowedActions,\n allowedTriggers: grant.allowedTriggers,\n capability,\n })\n connectors.push(connector)\n expiresAt = capability.capability.expiresAt\n }\n\n return {\n manifestId: input.manifestId ?? grants[0]?.manifestId ?? 'explicit-grants',\n subject: input.subject,\n capabilities: bindings,\n connectors,\n tools: buildIntegrationToolCatalog(connectors),\n expiresAt,\n }\n }\n\n private async resolveBundleGrants(input: {\n manifestId?: string\n grantIds?: string[]\n owner: IntegrationActor\n grantee?: IntegrationActor\n }): Promise<IntegrationGrant[]> {\n if (input.grantIds?.length) {\n const uniqueGrantIds = unique(input.grantIds)\n const grants = this.grants.listByIds\n ? await this.grants.listByIds(uniqueGrantIds)\n : await Promise.all(uniqueGrantIds.map((grantId) => this.grants.get(grantId)))\n const found = grants.filter((grant): grant is IntegrationGrant => Boolean(grant))\n const foundIds = new Set(found.map((grant) => grant.id))\n const missing = uniqueGrantIds.filter((grantId) => !foundIds.has(grantId))\n if (missing.length > 0) {\n throw new Error(`Cannot build integration bundle; unknown grant id(s): ${missing.join(', ')}`)\n }\n const badOwner = found.find((grant) => !sameActor(grant.owner, input.owner))\n if (badOwner) {\n throw new Error(`Cannot build integration bundle; grant ${badOwner.id} belongs to a different owner.`)\n }\n const badGrantee = input.grantee\n ? found.find((grant) => !sameActor(grant.grantee, input.grantee!))\n : undefined\n if (badGrantee) {\n throw new Error(`Cannot build integration bundle; grant ${badGrantee.id} belongs to a different grantee.`)\n }\n const badManifest = input.manifestId\n ? found.find((grant) => grant.manifestId !== input.manifestId)\n : undefined\n if (badManifest) {\n throw new Error(`Cannot build integration bundle; grant ${badManifest.id} is not for manifest ${input.manifestId}.`)\n }\n const inactive = found.find((grant) => grant.status !== 'active')\n if (inactive) {\n throw new Error(`Cannot build integration bundle; grant ${inactive.id} is ${inactive.status}.`)\n }\n return found\n }\n if (!input.manifestId) {\n throw new Error('Cannot build integration bundle; manifestId or grantIds is required.')\n }\n return (await this.grants.listByManifest(input.manifestId, input.grantee))\n .filter((grant) => sameActor(grant.owner, input.owner))\n .filter((grant) => grant.status === 'active')\n }\n}\n\nexport function createIntegrationRuntime(options: IntegrationRuntimeOptions): IntegrationRuntime {\n return new IntegrationRuntime(options)\n}\n\nfunction resolveRequirement(\n requirement: IntegrationRequirement,\n owner: IntegrationActor,\n registry: IntegrationRegistry,\n connections: IntegrationConnection[],\n): IntegrationRequirementResolution {\n const entry = registry.byId.get(requirement.connectorId)\n if (!entry) {\n return missing(requirement, 'unknown_connector', `Unknown connector ${requirement.connectorId}.`)\n }\n const connector = entry.connector\n if (connector.actions.length === 0 && (connector.triggers?.length ?? 0) === 0) {\n return missing(requirement, 'not_executable', `${connector.title} is catalog-only and cannot be invoked yet.`, connector, entry)\n }\n const scopes = requiredScopes(requirement, connector)\n const actions = requiredActions(requirement, connector)\n const triggers = requiredTriggers(requirement, connector)\n const connection = connections.find((candidate) =>\n sameActor(candidate.owner, owner)\n && candidate.status === 'active'\n && (candidate.connectorId === connector.id || entry.aliases.includes(candidate.connectorId))\n && scopes.every((scope) => candidate.grantedScopes.includes(scope))\n )\n if (!connection) {\n return {\n requirement,\n status: 'missing_connection',\n connector,\n registryEntry: entry,\n missingScopes: scopes,\n missingActions: actions,\n missingTriggers: triggers,\n message: `${connector.title} needs an active user connection with the required scopes.`,\n }\n }\n return {\n requirement,\n status: 'ready',\n connector,\n registryEntry: entry,\n connection,\n missingScopes: [],\n missingActions: [],\n missingTriggers: [],\n message: `${connector.title} is ready.`,\n }\n}\n\nfunction missing(\n requirement: IntegrationRequirement,\n status: Exclude<IntegrationRequirementStatus, 'ready' | 'missing_connection'>,\n message: string,\n connector?: IntegrationConnector,\n registryEntry?: IntegrationRegistryEntry,\n): IntegrationRequirementResolution {\n return {\n requirement,\n status,\n connector,\n registryEntry,\n missingScopes: [],\n missingActions: [],\n missingTriggers: [],\n message,\n }\n}\n\nfunction requiredActions(requirement: IntegrationRequirement, connector: IntegrationConnector): string[] {\n if (requirement.mode === 'trigger') return []\n if (requirement.requiredActions?.length) return unique(requirement.requiredActions)\n const actions = connector.actions.filter((action) => {\n if (requirement.mode === 'read') return action.risk === 'read'\n if (requirement.mode === 'write') return action.risk === 'write'\n return false\n })\n return unique(actions.map((action) => action.id))\n}\n\nfunction requiredTriggers(requirement: IntegrationRequirement, connector: IntegrationConnector): string[] {\n if (requirement.requiredTriggers?.length) return unique(requirement.requiredTriggers)\n if (requirement.mode !== 'trigger') return []\n return unique((connector.triggers ?? []).map((trigger) => trigger.id))\n}\n\nfunction requiredScopes(requirement: IntegrationRequirement, connector: IntegrationConnector): string[] {\n if (requirement.requiredScopes?.length) return unique(requirement.requiredScopes)\n const actionIds = new Set(requiredActions(requirement, connector))\n const triggerIds = new Set(requiredTriggers(requirement, connector))\n return unique([\n ...connector.actions\n .filter((action) => actionIds.has(action.id))\n .flatMap((action) => action.requiredScopes),\n ...(connector.triggers ?? [])\n .filter((trigger) => triggerIds.has(trigger.id))\n .flatMap((trigger) => trigger.requiredScopes),\n ])\n}\n\nfunction sameActor(a: IntegrationActor, b: IntegrationActor): boolean {\n return a.type === b.type && a.id === b.id\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n","import type {\n IntegrationActor,\n IntegrationTriggerEvent,\n IntegrationTriggerSubscription,\n} from './index.js'\nimport {\n type IntegrationGrant,\n type IntegrationGrantStore,\n type IntegrationManifest,\n type IntegrationRuntime,\n} from './runtime.js'\n\nexport interface IntegrationWorkflowDefinition {\n id: string\n title?: string\n manifest: IntegrationManifest\n trigger: {\n requirementId: string\n triggerId: string\n targetUrl?: string\n }\n metadata?: Record<string, unknown>\n}\n\nexport interface InstalledIntegrationWorkflow {\n id: string\n workflowId: string\n manifestId: string\n owner: IntegrationActor\n grantee: IntegrationActor\n triggerGrantId: string\n subscription: IntegrationTriggerSubscription\n status: 'active' | 'paused' | 'error'\n createdAt: string\n metadata?: Record<string, unknown>\n}\n\nexport interface IntegrationWorkflowStore {\n put(workflow: InstalledIntegrationWorkflow): Promise<void> | void\n get(id: string): Promise<InstalledIntegrationWorkflow | undefined> | InstalledIntegrationWorkflow | undefined\n list(): Promise<InstalledIntegrationWorkflow[]> | InstalledIntegrationWorkflow[]\n listByWorkflow(workflowId: string): Promise<InstalledIntegrationWorkflow[]> | InstalledIntegrationWorkflow[]\n listByOwner(owner: IntegrationActor): Promise<InstalledIntegrationWorkflow[]> | InstalledIntegrationWorkflow[]\n}\n\nexport interface IntegrationWorkflowRuntimeHub {\n subscribeTrigger(connectionId: string, trigger: string, targetUrl?: string): Promise<IntegrationTriggerSubscription> | IntegrationTriggerSubscription\n}\n\nexport interface IntegrationWorkflowRuntimeOptions {\n runtime: IntegrationRuntime\n hub: IntegrationWorkflowRuntimeHub\n grants: IntegrationGrantStore\n store?: IntegrationWorkflowStore\n now?: () => Date\n}\n\nexport class InMemoryIntegrationWorkflowStore implements IntegrationWorkflowStore {\n private readonly workflows = new Map<string, InstalledIntegrationWorkflow>()\n\n put(workflow: InstalledIntegrationWorkflow): void {\n this.workflows.set(workflow.id, workflow)\n }\n\n get(id: string): InstalledIntegrationWorkflow | undefined {\n return this.workflows.get(id)\n }\n\n list(): InstalledIntegrationWorkflow[] {\n return [...this.workflows.values()]\n }\n\n listByWorkflow(workflowId: string): InstalledIntegrationWorkflow[] {\n return [...this.workflows.values()].filter((workflow) => workflow.workflowId === workflowId)\n }\n\n listByOwner(owner: IntegrationActor): InstalledIntegrationWorkflow[] {\n return [...this.workflows.values()].filter((workflow) => sameActor(workflow.owner, owner))\n }\n}\n\nexport class IntegrationWorkflowRuntime {\n private readonly runtime: IntegrationRuntime\n private readonly hub: IntegrationWorkflowRuntimeHub\n private readonly grants: IntegrationGrantStore\n private readonly store: IntegrationWorkflowStore\n private readonly now: () => Date\n\n constructor(options: IntegrationWorkflowRuntimeOptions) {\n this.runtime = options.runtime\n this.hub = options.hub\n this.grants = options.grants\n this.store = options.store ?? new InMemoryIntegrationWorkflowStore()\n this.now = options.now ?? (() => new Date())\n }\n\n async install(input: {\n workflow: IntegrationWorkflowDefinition\n owner: IntegrationActor\n grantee: IntegrationActor\n }): Promise<InstalledIntegrationWorkflow> {\n const grants = await this.runtime.createGrants({\n manifest: input.workflow.manifest,\n owner: input.owner,\n grantee: input.grantee,\n metadata: { workflowId: input.workflow.id },\n })\n const triggerGrant = findTriggerGrant(grants, input.workflow.trigger.requirementId, input.workflow.trigger.triggerId)\n const subscription = await this.hub.subscribeTrigger(\n triggerGrant.connectionId,\n input.workflow.trigger.triggerId,\n input.workflow.trigger.targetUrl,\n )\n const installed: InstalledIntegrationWorkflow = {\n id: `workflow_${input.workflow.id}_${triggerGrant.id}`,\n workflowId: input.workflow.id,\n manifestId: input.workflow.manifest.id,\n owner: input.owner,\n grantee: input.grantee,\n triggerGrantId: triggerGrant.id,\n subscription,\n status: 'active',\n createdAt: this.now().toISOString(),\n metadata: input.workflow.metadata,\n }\n await this.store.put(installed)\n return installed\n }\n\n async dispatchEvent<T = unknown>(\n event: IntegrationTriggerEvent<T>,\n handler: (input: { event: IntegrationTriggerEvent<T>; workflows: InstalledIntegrationWorkflow[] }) => Promise<void> | void,\n ): Promise<{ matched: InstalledIntegrationWorkflow[] }> {\n const workflows = (await this.store.list())\n .filter((workflow) =>\n workflow.status === 'active'\n && workflow.subscription.connectionId === event.connectionId\n && workflow.subscription.trigger === event.trigger\n )\n await handler({ event, workflows })\n return { matched: workflows }\n }\n}\n\nexport function createIntegrationWorkflowRuntime(options: IntegrationWorkflowRuntimeOptions): IntegrationWorkflowRuntime {\n return new IntegrationWorkflowRuntime(options)\n}\n\nfunction findTriggerGrant(grants: IntegrationGrant[], requirementId: string, triggerId: string): IntegrationGrant {\n const grant = grants.find((candidate) =>\n candidate.requirementId === requirementId && candidate.allowedTriggers.includes(triggerId)\n )\n if (!grant) throw new Error(`Missing trigger grant ${requirementId}/${triggerId}.`)\n return grant\n}\n\nfunction sameActor(a: IntegrationActor, b: IntegrationActor): boolean {\n return a.type === b.type && a.id === b.id\n}\n","import type {\n CompleteAuthRequest,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationProvider,\n IntegrationProviderKind,\n IntegrationTriggerEvent,\n IntegrationTriggerSubscription,\n StartAuthRequest,\n StartAuthResult,\n} from './index.js'\nimport { IntegrationError } from './index.js'\n\nexport interface CatalogExecutorInvocation {\n connection: IntegrationConnection\n request: IntegrationActionRequest\n connector: IntegrationConnector\n action: IntegrationConnector['actions'][number]\n}\n\nexport interface CatalogExecutorProviderOptions {\n id: string\n kind: IntegrationProviderKind\n connectors: IntegrationConnector[]\n startAuth?: (request: StartAuthRequest) => Promise<StartAuthResult> | StartAuthResult\n completeAuth?: (request: CompleteAuthRequest) => Promise<IntegrationConnection> | IntegrationConnection\n executeAction: (invocation: CatalogExecutorInvocation) => Promise<IntegrationActionResult> | IntegrationActionResult\n subscribeTrigger?: (\n connection: IntegrationConnection,\n trigger: NonNullable<IntegrationConnector['triggers']>[number],\n targetUrl?: string,\n ) => Promise<IntegrationTriggerSubscription> | IntegrationTriggerSubscription\n unsubscribeTrigger?: (subscriptionId: string) => Promise<void> | void\n normalizeTriggerEvent?: (raw: unknown) => Promise<IntegrationTriggerEvent> | IntegrationTriggerEvent\n}\n\nexport function createCatalogExecutorProvider(options: CatalogExecutorProviderOptions): IntegrationProvider {\n const byConnector = new Map(options.connectors.map((connector) => [connector.id, connector]))\n return {\n id: options.id,\n kind: options.kind,\n listConnectors: () => options.connectors,\n startAuth: options.startAuth,\n completeAuth: options.completeAuth,\n async invokeAction(connection, request) {\n const connector = byConnector.get(connection.connectorId)\n if (!connector) {\n throw new IntegrationError(`Connector ${connection.connectorId} not found.`, 'connector_not_found')\n }\n const action = connector.actions.find((candidate) => candidate.id === request.action)\n if (!action) {\n throw new IntegrationError(`Action ${request.action} is not defined by connector ${connector.id}.`, 'action_not_found')\n }\n return options.executeAction({ connection, request, connector, action })\n },\n async subscribeTrigger(connection, triggerId, targetUrl) {\n if (!options.subscribeTrigger) {\n throw new IntegrationError(`Provider ${options.id} does not support trigger subscriptions.`, 'trigger_not_found')\n }\n const connector = byConnector.get(connection.connectorId)\n if (!connector) {\n throw new IntegrationError(`Connector ${connection.connectorId} not found.`, 'connector_not_found')\n }\n const trigger = connector.triggers?.find((candidate) => candidate.id === triggerId)\n if (!trigger) {\n throw new IntegrationError(`Trigger ${triggerId} is not defined by connector ${connector.id}.`, 'trigger_not_found')\n }\n return options.subscribeTrigger(connection, trigger, targetUrl)\n },\n unsubscribeTrigger: options.unsubscribeTrigger,\n normalizeTriggerEvent: options.normalizeTriggerEvent,\n }\n}\n","import {\n buildActivepiecesConnectors,\n listActivepiecesCatalogEntries,\n type ActivepiecesCatalogEntry,\n} from './activepieces-catalog.js'\nimport { createCatalogExecutorProvider } from './catalog-executor.js'\nimport {\n auditIntegrationCatalogFreshness,\n extractActivepiecesPublicPieceCount,\n type IntegrationCatalogFreshnessOptions,\n} from './catalog-freshness.js'\nimport {\n IntegrationError,\n type CompleteAuthRequest,\n type IntegrationActionRequest,\n type IntegrationActionResult,\n type IntegrationConnection,\n type IntegrationConnector,\n type IntegrationTriggerEvent,\n type IntegrationTriggerSubscription,\n type StartAuthRequest,\n type StartAuthResult,\n} from './index.js'\n\nexport {\n TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER,\n buildTangleCatalogRuntimeRequest,\n createTangleCatalogHttpExecutor,\n signTangleCatalogRuntimeRequest,\n verifyTangleCatalogRuntimeSignature,\n type TangleCatalogHttpExecutorOptions,\n type TangleCatalogRuntimeRequest,\n} from './activepieces-runtime.js'\n\nexport const TANGLE_INTEGRATIONS_CATALOG_PROVIDER_ID = 'tangle-catalog'\nexport const TANGLE_INTEGRATIONS_CATALOG_SOURCE = 'tangle-integrations-catalog'\n\nexport type TangleIntegrationImplementationKind = 'native_adapter' | 'package_runtime'\nexport type TangleIntegrationContractStatus = 'contract_ready' | 'runtime_backed' | 'native_backed'\n\nexport interface TangleIntegrationCatalogEntry {\n id: string\n title: string\n description: string\n category: IntegrationConnector['category']\n auth: IntegrationConnector['auth']\n authFields?: ActivepiecesCatalogEntry['authFields']\n domains: string[]\n actions: Array<{\n id: string\n title: string\n risk: IntegrationConnector['actions'][number]['risk']\n upstreamName?: string\n }>\n triggers: Array<{\n id: string\n title: string\n upstreamName?: string\n }>\n}\n\nexport interface TangleIntegrationContract {\n id: string\n title: string\n description: string\n category: IntegrationConnector['category']\n auth: IntegrationConnector['auth']\n authFields: NonNullable<ActivepiecesCatalogEntry['authFields']>\n actions: Array<{\n id: string\n title: string\n risk: IntegrationConnector['actions'][number]['risk']\n upstreamName: string\n }>\n triggers: Array<{\n id: string\n title: string\n upstreamName: string\n }>\n implementation: {\n kind: TangleIntegrationImplementationKind\n runtimePackage?: string\n version?: string\n }\n status: TangleIntegrationContractStatus\n quality: {\n tangleContract: true\n authFieldsMapped: boolean\n actionNamesMapped: boolean\n triggerNamesMapped: boolean\n runtimePackageMapped: boolean\n nativeAdapter: boolean\n }\n}\n\nexport interface TangleCatalogRuntimePackageManifestOptions {\n name?: string\n includeAgentIntegrationsPackage?: boolean\n agentIntegrationsVersion?: string\n additionalDependencies?: Record<string, string>\n}\n\nexport interface TangleCatalogRuntimePackageManifest {\n name: string\n private: true\n type: 'module'\n dependencies: Record<string, string>\n tangle: {\n integrationContracts: number\n packageRuntimeBackends: number\n generatedFrom: typeof TANGLE_INTEGRATIONS_CATALOG_SOURCE\n }\n}\n\nexport interface TangleCatalogExecutorInvocation {\n connection: IntegrationConnection\n request: IntegrationActionRequest\n connector: IntegrationConnector\n catalogEntry: TangleIntegrationCatalogEntry\n piece: {\n id: string\n packageName?: string\n version?: string\n actionId: string\n upstreamActionName?: string\n }\n}\n\nexport interface TangleCatalogTriggerInvocation {\n connection: IntegrationConnection\n connector: IntegrationConnector\n catalogEntry: TangleIntegrationCatalogEntry\n trigger: NonNullable<IntegrationConnector['triggers']>[number]\n targetUrl?: string\n piece: {\n id: string\n packageName?: string\n version?: string\n triggerId: string\n upstreamTriggerName?: string\n }\n}\n\nexport interface TangleCatalogExecutorProviderOptions {\n id?: string\n connectors?: IntegrationConnector[]\n startAuth?: (request: StartAuthRequest) => Promise<StartAuthResult> | StartAuthResult\n completeAuth?: (request: CompleteAuthRequest) => Promise<IntegrationConnection> | IntegrationConnection\n executeAction: (invocation: TangleCatalogExecutorInvocation) => Promise<IntegrationActionResult> | IntegrationActionResult\n subscribeTrigger?: (invocation: TangleCatalogTriggerInvocation) => Promise<IntegrationTriggerSubscription> | IntegrationTriggerSubscription\n unsubscribeTrigger?: (subscriptionId: string) => Promise<void> | void\n normalizeTriggerEvent?: (raw: unknown) => Promise<IntegrationTriggerEvent> | IntegrationTriggerEvent\n}\n\nexport type TangleIntegrationCatalogFreshnessOptions = IntegrationCatalogFreshnessOptions\n\nexport interface TangleIntegrationCatalogFreshnessResult {\n ok: boolean\n generatedAt: string\n local: {\n catalogEntries: number\n catalogConnectors: number\n catalogActions: number\n catalogTriggers: number\n executableCatalogConnectors: number\n executableCatalogActions: number\n executableCatalogTriggers: number\n executableToolDefinitions: number\n unsupportedExecutableConnectorIds: string[]\n registryEntries: number\n registrySummary: Awaited<ReturnType<typeof auditIntegrationCatalogFreshness>>['local']['registrySummary']\n conflictSamples: Awaited<ReturnType<typeof auditIntegrationCatalogFreshness>>['local']['conflictSamples']\n }\n upstream?: {\n externalEntries?: number\n externalDelta?: number\n checkedUrl: string\n warning?: string\n }\n warnings: string[]\n}\n\nconst NATIVE_ADAPTER_IDS = new Set([\n 'google-calendar',\n 'google-sheets',\n 'microsoft-calendar',\n 'hubspot',\n 'slack',\n 'notion-database',\n 'twilio-sms',\n 'stripe-pack',\n 'webhook',\n 'stripe',\n 'slack-inbound',\n 'github',\n 'gitlab',\n 'airtable',\n 'asana',\n 'salesforce',\n])\n\nexport function listTangleIntegrationCatalogEntries(): TangleIntegrationCatalogEntry[] {\n return listActivepiecesCatalogEntries().map((entry) => sanitizeEntry(entry))\n}\n\nexport function listTangleIntegrationContracts(): TangleIntegrationContract[] {\n return listActivepiecesCatalogEntries().map((entry) => {\n const nativeAdapter = NATIVE_ADAPTER_IDS.has(entry.id)\n return {\n id: entry.id,\n title: entry.title,\n description: entry.description,\n category: entry.category,\n auth: entry.auth,\n authFields: entry.authFields ?? [],\n actions: entry.actions.map((action) => ({\n id: action.id,\n title: action.title,\n risk: action.risk,\n upstreamName: action.upstreamName ?? action.id,\n })),\n triggers: entry.triggers.map((trigger) => ({\n id: trigger.id,\n title: trigger.title,\n upstreamName: trigger.upstreamName ?? trigger.id,\n })),\n implementation: {\n kind: nativeAdapter ? 'native_adapter' : 'package_runtime',\n runtimePackage: entry.npmPackage,\n version: entry.version,\n },\n status: nativeAdapter ? 'native_backed' : entry.npmPackage ? 'runtime_backed' : 'contract_ready',\n quality: {\n tangleContract: true,\n authFieldsMapped: entry.auth === 'none' || Boolean(entry.authFields?.length),\n actionNamesMapped: entry.actions.every((action) => Boolean(action.upstreamName)),\n triggerNamesMapped: entry.triggers.every((trigger) => Boolean(trigger.upstreamName)),\n runtimePackageMapped: Boolean(entry.npmPackage),\n nativeAdapter,\n },\n }\n })\n}\n\nexport function listTangleIntegrationCatalogRuntimePackages(): Array<{\n connectorId: string\n packageName: string\n version?: string\n}> {\n return listActivepiecesCatalogEntries()\n .filter((entry): entry is ActivepiecesCatalogEntry & { npmPackage: string } => Boolean(entry.npmPackage))\n .map((entry) => ({\n connectorId: entry.id,\n packageName: entry.npmPackage,\n version: entry.version,\n }))\n}\n\nexport function buildTangleCatalogRuntimePackageManifest(\n options: TangleCatalogRuntimePackageManifestOptions = {},\n): TangleCatalogRuntimePackageManifest {\n const dependencies: Record<string, string> = {}\n if (options.includeAgentIntegrationsPackage ?? true) {\n dependencies['@tangle-network/agent-integrations'] = options.agentIntegrationsVersion ?? 'latest'\n }\n for (const pkg of listTangleIntegrationCatalogRuntimePackages()) {\n dependencies[pkg.packageName] = pkg.version ?? 'latest'\n }\n Object.assign(dependencies, options.additionalDependencies)\n return {\n name: options.name ?? '@tangle-network/agent-integrations-runtime-bundle',\n private: true,\n type: 'module',\n dependencies: Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b))),\n tangle: {\n integrationContracts: listTangleIntegrationContracts().length,\n packageRuntimeBackends: listTangleIntegrationContracts()\n .filter((contract) => contract.implementation.kind === 'package_runtime').length,\n generatedFrom: TANGLE_INTEGRATIONS_CATALOG_SOURCE,\n },\n }\n}\n\nexport function renderTangleCatalogRuntimePnpmAddCommand(options: {\n includeAgentIntegrationsPackage?: boolean\n agentIntegrationsVersion?: string\n} = {}): string {\n const manifest = buildTangleCatalogRuntimePackageManifest({\n includeAgentIntegrationsPackage: options.includeAgentIntegrationsPackage,\n agentIntegrationsVersion: options.agentIntegrationsVersion,\n })\n return [\n 'pnpm',\n 'add',\n ...Object.entries(manifest.dependencies).map(([name, version]) => `${name}@${version}`),\n ].join(' ')\n}\n\nexport function buildTangleIntegrationCatalogConnectors(options: {\n providerId?: string\n includeCatalogActions?: boolean\n executable?: boolean\n} = {}): IntegrationConnector[] {\n const providerId = options.providerId ?? TANGLE_INTEGRATIONS_CATALOG_PROVIDER_ID\n return buildActivepiecesConnectors({\n ...options,\n providerId,\n }).map((connector) => sanitizeConnector(connector, providerId))\n}\n\nexport function createTangleCatalogExecutorProvider(options: TangleCatalogExecutorProviderOptions) {\n const providerId = options.id ?? TANGLE_INTEGRATIONS_CATALOG_PROVIDER_ID\n const connectors = options.connectors ?? buildTangleIntegrationCatalogConnectors({\n providerId,\n includeCatalogActions: true,\n executable: true,\n })\n const byEntry = new Map(listActivepiecesCatalogEntries().map((entry) => [entry.id, entry]))\n\n return createCatalogExecutorProvider({\n id: providerId,\n kind: 'tangle_catalog',\n connectors,\n startAuth: options.startAuth,\n completeAuth: options.completeAuth,\n executeAction: async ({ connection, request, connector, action }) => {\n const importedEntry = byEntry.get(connector.id)\n if (!importedEntry) {\n throw new IntegrationError(`Tangle catalog entry ${connector.id} not found.`, 'connector_not_found')\n }\n const catalogAction = importedEntry.actions.find((candidate) => candidate.id === action.id)\n return options.executeAction({\n connection,\n request,\n connector,\n catalogEntry: sanitizeEntry(importedEntry),\n piece: {\n id: importedEntry.id,\n packageName: importedEntry.npmPackage,\n version: importedEntry.version,\n actionId: action.id,\n upstreamActionName: catalogAction?.upstreamName,\n },\n })\n },\n subscribeTrigger: options.subscribeTrigger\n ? async (connection, trigger, targetUrl) => {\n const connector = connectors.find((candidate) => candidate.id === connection.connectorId)\n const importedEntry = byEntry.get(connection.connectorId)\n if (!connector || !importedEntry) {\n throw new IntegrationError(`Tangle catalog entry ${connection.connectorId} not found.`, 'connector_not_found')\n }\n const catalogTrigger = importedEntry.triggers.find((candidate) => candidate.id === trigger.id)\n return options.subscribeTrigger!({\n connection,\n connector,\n catalogEntry: sanitizeEntry(importedEntry),\n trigger,\n targetUrl,\n piece: {\n id: importedEntry.id,\n packageName: importedEntry.npmPackage,\n version: importedEntry.version,\n triggerId: trigger.id,\n upstreamTriggerName: catalogTrigger?.upstreamName,\n },\n })\n }\n : undefined,\n unsubscribeTrigger: options.unsubscribeTrigger,\n normalizeTriggerEvent: options.normalizeTriggerEvent,\n })\n}\n\nexport const extractExternalCatalogPublicCount = extractActivepiecesPublicPieceCount\n\nexport async function auditTangleIntegrationCatalogFreshness(\n options: TangleIntegrationCatalogFreshnessOptions = {},\n): Promise<TangleIntegrationCatalogFreshnessResult> {\n const result = await auditIntegrationCatalogFreshness(options)\n return {\n ok: result.ok,\n generatedAt: result.generatedAt,\n local: {\n catalogEntries: result.local.activepiecesEntries,\n catalogConnectors: result.local.activepiecesConnectors,\n catalogActions: result.local.activepiecesActions,\n catalogTriggers: result.local.activepiecesTriggers,\n executableCatalogConnectors: result.local.executableActivepiecesConnectors,\n executableCatalogActions: result.local.executableActivepiecesActions,\n executableCatalogTriggers: result.local.executableActivepiecesTriggers,\n executableToolDefinitions: result.local.executableToolDefinitions,\n unsupportedExecutableConnectorIds: result.local.unsupportedExecutableConnectorIds,\n registryEntries: result.local.registryEntries,\n registrySummary: result.local.registrySummary,\n conflictSamples: result.local.conflictSamples,\n },\n upstream: result.upstream\n ? {\n externalEntries: result.upstream.activepiecesPieces,\n externalDelta: result.upstream.activepiecesDelta,\n checkedUrl: result.upstream.checkedUrl,\n warning: result.upstream.warning,\n }\n : undefined,\n warnings: result.warnings.map((warning) => warning.replaceAll('Activepieces', 'Tangle Integrations Catalog')),\n }\n}\n\nfunction sanitizeEntry(entry: ActivepiecesCatalogEntry): TangleIntegrationCatalogEntry {\n return {\n id: entry.id,\n title: entry.title,\n description: entry.description,\n category: entry.category,\n auth: entry.auth,\n authFields: entry.authFields,\n domains: entry.domains.filter((domain) => !domain.toLowerCase().includes('activepieces')),\n actions: entry.actions.map((action) => ({\n id: action.id,\n title: action.title,\n risk: action.risk,\n upstreamName: action.upstreamName,\n })),\n triggers: entry.triggers.map((trigger) => ({\n id: trigger.id,\n title: trigger.title,\n upstreamName: trigger.upstreamName,\n })),\n }\n}\n\nfunction sanitizeConnector(connector: IntegrationConnector, providerId: string): IntegrationConnector {\n const metadata = connector.metadata ?? {}\n return {\n ...connector,\n providerId,\n metadata: {\n source: TANGLE_INTEGRATIONS_CATALOG_SOURCE,\n providerId,\n executable: metadata.executable,\n runtime: 'tangle-catalog-runtime',\n catalogOnly: metadata.catalogOnly,\n supportTier: metadata.supportTier,\n catalogActionCount: metadata.catalogActionCount,\n catalogTriggerCount: metadata.catalogTriggerCount,\n license: metadata.license,\n version: metadata.version,\n domains: Array.isArray(metadata.domains)\n ? metadata.domains.filter((domain) => typeof domain === 'string' && !domain.toLowerCase().includes('activepieces'))\n : undefined,\n ...(metadata.overridden ? { overridden: true } : {}),\n },\n }\n}\n","import { buildActivepiecesConnectors } from './activepieces-catalog.js'\nimport { buildTangleIntegrationCatalogConnectors } from './tangle-catalog.js'\nimport type {\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorTrigger,\n} from './index.js'\nimport { integrationSpecToConnector, listIntegrationSpecs } from './specs/registry.js'\n\nexport type IntegrationSupportTier =\n | 'catalogOnly'\n | 'setupReady'\n | 'gatewayExecutable'\n | 'firstPartyExecutable'\n | 'sandboxExecutable'\n\nexport interface IntegrationCatalogSource {\n id: string\n connectors: IntegrationConnector[]\n precedence?: number\n}\n\nexport interface IntegrationRegistrySourceRef {\n sourceId: string\n providerId: string\n connectorId: string\n supportTier: IntegrationSupportTier\n actionCount: number\n triggerCount: number\n}\n\nexport interface IntegrationRegistryConflict {\n field: 'auth' | 'category'\n values: Array<{\n value: string\n sourceId: string\n connectorId: string\n }>\n}\n\nexport interface IntegrationRegistryEntry {\n canonicalId: string\n connector: IntegrationConnector\n aliases: string[]\n supportTier: IntegrationSupportTier\n sources: IntegrationRegistrySourceRef[]\n conflicts: IntegrationRegistryConflict[]\n}\n\nexport interface IntegrationRegistry {\n entries: IntegrationRegistryEntry[]\n connectors: IntegrationConnector[]\n byId: Map<string, IntegrationRegistryEntry>\n}\n\nexport interface IntegrationRegistrySummary {\n totalEntries: number\n totalSources: number\n toolBindableEntries: number\n conflictEntries: number\n bySupportTier: Record<IntegrationSupportTier, number>\n}\n\nexport interface ComposeIntegrationRegistryOptions {\n aliases?: Record<string, string>\n sourcePrecedence?: Record<string, number>\n}\n\nconst DEFAULT_ALIASES: Record<string, string> = {\n notion: 'notion-database',\n 'outlook-calendar': 'microsoft-calendar',\n 'microsoft-outlook-calendar': 'microsoft-calendar',\n 'microsoft-outlook': 'outlook-mail',\n 'gmail-mail': 'gmail',\n 'slack-bolt': 'slack',\n stripe: 'stripe-pack',\n twilio: 'twilio-sms',\n 'twilio-voice': 'twilio-sms',\n}\n\nconst DEFAULT_SOURCE_PRECEDENCE: Record<string, number> = {\n 'first-party': 500,\n spec: 400,\n gateway: 300,\n 'tangle-catalog': 100,\n activepieces: 100,\n coverage: 50,\n}\n\nconst SUPPORT_RANK: Record<IntegrationSupportTier, number> = {\n catalogOnly: 0,\n setupReady: 1,\n gatewayExecutable: 2,\n firstPartyExecutable: 3,\n sandboxExecutable: 4,\n}\n\nexport function buildDefaultIntegrationRegistry(options: {\n includeSpecs?: boolean\n includeTangleCatalog?: boolean\n tangleCatalogRuntimeExecutable?: boolean\n /** @deprecated Use includeTangleCatalog. */\n includeActivepieces?: boolean\n} = {}): IntegrationRegistry {\n const includeSpecs = options.includeSpecs ?? true\n const includeTangleCatalog = options.includeTangleCatalog ?? options.includeActivepieces ?? true\n const sources: IntegrationCatalogSource[] = []\n if (includeSpecs) {\n sources.push({\n id: 'spec',\n connectors: listIntegrationSpecs().map((spec) => integrationSpecToConnector(spec, 'spec')),\n })\n }\n if (includeTangleCatalog) {\n const tangleConnectors = options.tangleCatalogRuntimeExecutable\n ? buildTangleIntegrationCatalogConnectors({\n providerId: 'tangle-catalog',\n includeCatalogActions: true,\n executable: true,\n })\n : buildActivepiecesConnectors({ providerId: 'tangle-catalog' }).map((connector) => ({\n ...connector,\n providerId: 'tangle-catalog',\n metadata: {\n source: 'tangle-integrations-catalog',\n providerId: 'tangle-catalog',\n executable: connector.metadata?.executable,\n runtime: 'tangle-catalog-runtime',\n catalogOnly: connector.metadata?.catalogOnly,\n supportTier: connector.metadata?.supportTier,\n catalogActionCount: connector.metadata?.catalogActionCount,\n catalogTriggerCount: connector.metadata?.catalogTriggerCount,\n license: connector.metadata?.license,\n version: connector.metadata?.version,\n domains: Array.isArray(connector.metadata?.domains)\n ? connector.metadata.domains.filter((domain) => typeof domain === 'string' && !domain.toLowerCase().includes('activepieces'))\n : undefined,\n ...(connector.metadata?.overridden ? { overridden: true } : {}),\n },\n }))\n sources.push({\n id: 'tangle-catalog',\n connectors: tangleConnectors,\n })\n }\n return composeIntegrationRegistry(sources)\n}\n\nexport function composeIntegrationRegistry(\n sources: IntegrationCatalogSource[],\n options: ComposeIntegrationRegistryOptions = {},\n): IntegrationRegistry {\n const aliases = { ...DEFAULT_ALIASES, ...(options.aliases ?? {}) }\n const precedence = { ...DEFAULT_SOURCE_PRECEDENCE, ...(options.sourcePrecedence ?? {}) }\n const grouped = new Map<string, Candidate[]>()\n\n for (const source of sources) {\n for (const connector of source.connectors) {\n const canonicalId = canonicalConnectorId(connector.id, aliases)\n const candidates = grouped.get(canonicalId) ?? []\n candidates.push({\n source,\n connector,\n supportTier: inferIntegrationSupportTier(connector),\n })\n grouped.set(canonicalId, candidates)\n }\n }\n\n const entries = [...grouped.entries()]\n .map(([canonicalId, candidates]) => registryEntry(canonicalId, candidates, precedence, aliases))\n .sort((a, b) => a.canonicalId.localeCompare(b.canonicalId))\n const byId = new Map<string, IntegrationRegistryEntry>()\n for (const entry of entries) {\n byId.set(entry.canonicalId, entry)\n for (const alias of entry.aliases) byId.set(alias, entry)\n }\n return {\n entries,\n connectors: entries.map((entry) => entry.connector),\n byId,\n }\n}\n\nexport function summarizeIntegrationRegistry(registry: IntegrationRegistry): IntegrationRegistrySummary {\n const bySupportTier = {\n catalogOnly: 0,\n setupReady: 0,\n gatewayExecutable: 0,\n firstPartyExecutable: 0,\n sandboxExecutable: 0,\n } satisfies Record<IntegrationSupportTier, number>\n for (const entry of registry.entries) bySupportTier[entry.supportTier] += 1\n return {\n totalEntries: registry.entries.length,\n totalSources: registry.entries.reduce((sum, entry) => sum + entry.sources.length, 0),\n toolBindableEntries: registry.entries.filter((entry) => entry.connector.actions.length > 0).length,\n conflictEntries: registry.entries.filter((entry) => entry.conflicts.length > 0).length,\n bySupportTier,\n }\n}\n\nexport function canonicalConnectorId(id: string, aliases: Record<string, string> = DEFAULT_ALIASES): string {\n const normalized = slug(id)\n let current = normalized\n const seen = new Set<string>()\n while (aliases[current] && !seen.has(current)) {\n seen.add(current)\n current = aliases[current]\n }\n return current\n}\n\nexport function inferIntegrationSupportTier(connector: IntegrationConnector): IntegrationSupportTier {\n const metadata = connector.metadata ?? {}\n const explicit = metadata.supportTier\n if (isSupportTier(explicit)) return explicit\n if (metadata.sandboxExecutable === true) return 'sandboxExecutable'\n if (metadata.source === 'first-party-adapter' || connector.providerId === 'first-party') return 'firstPartyExecutable'\n if (metadata.source === 'gateway-catalog' && metadata.executable === true) return 'gatewayExecutable'\n if (metadata.source === 'integration-spec') return 'setupReady'\n if (\n metadata.source === 'coverage-catalog'\n || metadata.source === 'activepieces-community'\n || metadata.source === 'tangle-integrations-catalog'\n || metadata.catalogOnly === true\n ) return 'catalogOnly'\n if (connector.actions.length > 0) return 'gatewayExecutable'\n return 'catalogOnly'\n}\n\nfunction registryEntry(\n canonicalId: string,\n candidates: Candidate[],\n precedence: Record<string, number>,\n aliases: Record<string, string>,\n): IntegrationRegistryEntry {\n const ordered = [...candidates].sort((a, b) => compareCandidates(a, b, precedence))\n const primary = ordered[0]!\n const actions = mergeActions(ordered)\n const triggers = mergeTriggers(ordered)\n const scopes = unique(toolBindableCandidates(ordered).flatMap((candidate) => candidate.connector.scopes ?? []))\n const supportTier = ordered.reduce<IntegrationSupportTier>(\n (best, candidate) => SUPPORT_RANK[candidate.supportTier] > SUPPORT_RANK[best] ? candidate.supportTier : best,\n primary.supportTier,\n )\n const aliasesForEntry = unique([\n ...ordered.map((candidate) => candidate.connector.id),\n ...Object.entries(aliases)\n .filter(([, target]) => canonicalConnectorId(target, aliases) === canonicalId)\n .map(([alias]) => alias),\n ].map(slug).filter((id) => id && id !== canonicalId)).sort()\n const sources = ordered.map((candidate): IntegrationRegistrySourceRef => ({\n sourceId: candidate.source.id,\n providerId: candidate.connector.providerId,\n connectorId: candidate.connector.id,\n supportTier: candidate.supportTier,\n actionCount: candidate.connector.actions.length,\n triggerCount: candidate.connector.triggers?.length ?? 0,\n }))\n const conflicts = conflictDiagnostics(ordered)\n\n return {\n canonicalId,\n aliases: aliasesForEntry,\n supportTier,\n sources,\n conflicts,\n connector: {\n ...primary.connector,\n id: canonicalId,\n scopes,\n actions,\n triggers,\n metadata: {\n ...(primary.connector.metadata ?? {}),\n registry: {\n canonicalId,\n aliases: aliasesForEntry,\n supportTier,\n sources,\n conflicts,\n toolBindable: actions.length > 0,\n catalogOnlyActionCount: ordered\n .filter((candidate) => candidate.supportTier === 'catalogOnly')\n .reduce((sum, candidate) => sum + catalogActionCount(candidate.connector), 0),\n },\n },\n },\n }\n}\n\nfunction compareCandidates(a: Candidate, b: Candidate, precedence: Record<string, number>): number {\n return SUPPORT_RANK[b.supportTier] - SUPPORT_RANK[a.supportTier]\n || (b.source.precedence ?? precedence[b.source.id] ?? 0) - (a.source.precedence ?? precedence[a.source.id] ?? 0)\n || b.connector.actions.length - a.connector.actions.length\n || a.connector.id.localeCompare(b.connector.id)\n}\n\nfunction mergeActions(candidates: Candidate[]): IntegrationConnectorAction[] {\n const out = new Map<string, IntegrationConnectorAction>()\n for (const candidate of toolBindableCandidates(candidates)) {\n for (const action of candidate.connector.actions) {\n if (!out.has(action.id)) out.set(action.id, action)\n }\n }\n return [...out.values()]\n}\n\nfunction mergeTriggers(candidates: Candidate[]): IntegrationConnectorTrigger[] | undefined {\n const out = new Map<string, IntegrationConnectorTrigger>()\n for (const candidate of toolBindableCandidates(candidates)) {\n for (const trigger of candidate.connector.triggers ?? []) {\n if (!out.has(trigger.id)) out.set(trigger.id, trigger)\n }\n }\n return out.size > 0 ? [...out.values()] : undefined\n}\n\nfunction toolBindableCandidates(candidates: Candidate[]): Candidate[] {\n const bindable = candidates.filter((candidate) => candidate.supportTier !== 'catalogOnly')\n if (bindable.length === 0) return []\n const maxRank = Math.max(...bindable.map((candidate) => SUPPORT_RANK[candidate.supportTier]))\n return bindable.filter((candidate) => SUPPORT_RANK[candidate.supportTier] === maxRank)\n}\n\nfunction catalogActionCount(connector: IntegrationConnector): number {\n const value = connector.metadata?.catalogActionCount\n return typeof value === 'number' ? value : connector.actions.length\n}\n\nfunction conflictDiagnostics(candidates: Candidate[]): IntegrationRegistryConflict[] {\n return [\n conflictFor('auth', candidates.map((candidate) => ({\n value: candidate.connector.auth,\n sourceId: candidate.source.id,\n connectorId: candidate.connector.id,\n }))),\n conflictFor('category', candidates.map((candidate) => ({\n value: candidate.connector.category,\n sourceId: candidate.source.id,\n connectorId: candidate.connector.id,\n }))),\n ].filter((conflict): conflict is IntegrationRegistryConflict => Boolean(conflict))\n}\n\nfunction conflictFor(\n field: IntegrationRegistryConflict['field'],\n values: IntegrationRegistryConflict['values'],\n): IntegrationRegistryConflict | undefined {\n const uniqueValues = new Set(values.map((entry) => entry.value))\n if (uniqueValues.size <= 1) return undefined\n return { field, values }\n}\n\nfunction isSupportTier(value: unknown): value is IntegrationSupportTier {\n return value === 'catalogOnly'\n || value === 'setupReady'\n || value === 'gatewayExecutable'\n || value === 'firstPartyExecutable'\n || value === 'sandboxExecutable'\n}\n\nfunction slug(value: string): string {\n return value.trim().toLowerCase()\n .replace(/&/g, 'and')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n\ninterface Candidate {\n source: IntegrationCatalogSource\n connector: IntegrationConnector\n supportTier: IntegrationSupportTier\n}\n","import type {\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationActionRisk,\n IntegrationDataClass,\n} from './index.js'\nimport {\n summarizeIntegrationRegistry,\n type IntegrationRegistry,\n type IntegrationRegistrySummary,\n type IntegrationSupportTier,\n} from './registry.js'\n\nexport interface IntegrationToolDefinition {\n name: string\n title: string\n description: string\n providerId: string\n connectorId: string\n connectorTitle: string\n category: IntegrationConnectorCategory\n action: IntegrationConnectorAction\n risk: IntegrationActionRisk\n dataClass: IntegrationDataClass\n requiredScopes: string[]\n inputSchema?: unknown\n outputSchema?: unknown\n tags: string[]\n supportTier?: IntegrationSupportTier\n runnable?: boolean\n}\n\nexport interface IntegrationCatalogView {\n connectors: IntegrationConnector[]\n conflicts: IntegrationRegistry['entries'][number]['conflicts']\n summary: IntegrationRegistrySummary\n tools: IntegrationToolDefinition[]\n runtimeTools: IntegrationToolDefinition[]\n discoveryTools: IntegrationToolDefinition[]\n}\n\nexport interface IntegrationToolSearchFilters {\n providerId?: string\n connectorId?: string\n category?: IntegrationConnectorCategory\n maxRisk?: IntegrationActionRisk\n dataClass?: IntegrationDataClass\n limit?: number\n}\n\nexport interface IntegrationToolSearchResult {\n tool: IntegrationToolDefinition\n score: number\n matched: string[]\n}\n\nexport interface McpToolDefinition {\n name: string\n description: string\n inputSchema: unknown\n}\n\nconst riskRank: Record<IntegrationActionRisk, number> = {\n read: 0,\n write: 1,\n destructive: 2,\n}\n\nexport function integrationToolName(providerId: string, connectorId: string, actionId: string): string {\n return `int_${encodeToolPart(providerId)}_${encodeToolPart(connectorId)}_${encodeToolPart(actionId)}`\n}\n\nexport function parseIntegrationToolName(name: string): { providerId: string; connectorId: string; actionId: string } {\n const parts = name.split('_')\n if (parts.length !== 4 || parts[0] !== 'int') {\n throw new Error(`Invalid integration tool name: ${name}`)\n }\n return {\n providerId: decodeToolPart(parts[1]),\n connectorId: decodeToolPart(parts[2]),\n actionId: decodeToolPart(parts[3]),\n }\n}\n\nexport function buildIntegrationToolCatalog(connectors: IntegrationConnector[]): IntegrationToolDefinition[] {\n const tools: IntegrationToolDefinition[] = []\n for (const connector of connectors) {\n for (const action of connector.actions) {\n const tags = unique([\n connector.id,\n connector.providerId,\n connector.title,\n connector.category,\n action.id,\n action.title,\n action.risk,\n action.dataClass,\n ...(connector.scopes ?? []),\n ...(action.requiredScopes ?? []),\n ].flatMap(tokenize))\n tools.push({\n name: integrationToolName(connector.providerId, connector.id, action.id),\n title: `${connector.title}: ${action.title}`,\n description: action.description ?? `${action.risk} action ${action.id} on ${connector.title}`,\n providerId: connector.providerId,\n connectorId: connector.id,\n connectorTitle: connector.title,\n category: connector.category,\n action,\n risk: action.risk,\n dataClass: action.dataClass,\n requiredScopes: action.requiredScopes,\n inputSchema: action.inputSchema,\n outputSchema: action.outputSchema,\n tags,\n supportTier: toolSupportTier(connector),\n runnable: toolRunnable(connector),\n })\n }\n }\n return tools\n}\n\nexport function buildIntegrationCatalogView(input: {\n discoveryRegistry: IntegrationRegistry\n executableRegistry?: IntegrationRegistry\n}): IntegrationCatalogView {\n const runtimeConnectors =\n input.executableRegistry?.connectors ??\n input.discoveryRegistry.connectors.filter((connector) => toolRunnable(connector))\n const runtimeTools = buildIntegrationToolCatalog(runtimeConnectors)\n const discoveryTools = buildIntegrationToolCatalog(input.discoveryRegistry.connectors)\n return {\n connectors: input.discoveryRegistry.connectors,\n conflicts: input.discoveryRegistry.entries.flatMap((entry) => entry.conflicts),\n summary: summarizeIntegrationRegistry(input.discoveryRegistry),\n tools: runtimeTools,\n runtimeTools,\n discoveryTools,\n }\n}\n\nexport function searchIntegrationTools(\n catalog: IntegrationToolDefinition[],\n query: string,\n filters: IntegrationToolSearchFilters = {},\n): IntegrationToolSearchResult[] {\n const terms = tokenize(query)\n const filtered = catalog.filter((tool) => {\n if (filters.providerId && tool.providerId !== filters.providerId) return false\n if (filters.connectorId && tool.connectorId !== filters.connectorId) return false\n if (filters.category && tool.category !== filters.category) return false\n if (filters.dataClass && tool.dataClass !== filters.dataClass) return false\n if (filters.maxRisk && riskRank[tool.risk] > riskRank[filters.maxRisk]) return false\n return true\n })\n const scored = filtered.map((tool) => scoreTool(tool, terms))\n return scored\n .filter((result) => terms.length === 0 || result.score > 0)\n .sort((a, b) => b.score - a.score || a.tool.name.localeCompare(b.tool.name))\n .slice(0, filters.limit ?? 20)\n}\n\nexport function toMcpTools(tools: IntegrationToolDefinition[]): McpToolDefinition[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: `${tool.title}. ${tool.description}`,\n inputSchema: tool.inputSchema ?? {\n type: 'object',\n additionalProperties: true,\n properties: {},\n },\n }))\n}\n\nfunction scoreTool(tool: IntegrationToolDefinition, terms: string[]): IntegrationToolSearchResult {\n if (terms.length === 0) return { tool, score: 1, matched: [] }\n const haystack = new Set(tool.tags)\n const matched: string[] = []\n let score = 0\n for (const term of terms) {\n if (haystack.has(term)) {\n matched.push(term)\n score += 4\n continue\n }\n if (tool.tags.some((tag) => tag.includes(term))) {\n matched.push(term)\n score += 1\n }\n }\n if (tool.risk === 'read') score += 0.25\n return { tool, score, matched: unique(matched) }\n}\n\nfunction tokenize(value: string): string[] {\n return value\n .toLowerCase()\n .split(/[^a-z0-9]+/g)\n .map((part) => part.trim())\n .filter(Boolean)\n}\n\nfunction encodeToolPart(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url').replace(/_/g, '.')\n}\n\nfunction decodeToolPart(value: string): string {\n return Buffer.from(value.replace(/\\./g, '_'), 'base64url').toString('utf8')\n}\n\nfunction unique<T>(values: T[]): T[] {\n return [...new Set(values)]\n}\n\nfunction toolSupportTier(connector: IntegrationConnector): IntegrationSupportTier | undefined {\n const registry = connector.metadata?.registry\n if (registry && typeof registry === 'object' && !Array.isArray(registry)) {\n const supportTier = (registry as { supportTier?: unknown }).supportTier\n return isIntegrationSupportTier(supportTier) ? supportTier : undefined\n }\n const supportTier = connector.metadata?.supportTier\n return isIntegrationSupportTier(supportTier) ? supportTier : undefined\n}\n\nfunction toolRunnable(connector: IntegrationConnector): boolean {\n const registry = connector.metadata?.registry\n if (registry && typeof registry === 'object' && !Array.isArray(registry)) {\n const toolBindable = (registry as { toolBindable?: unknown }).toolBindable\n if (typeof toolBindable === 'boolean') return toolBindable\n }\n const tier = toolSupportTier(connector)\n return tier === 'gatewayExecutable' || tier === 'firstPartyExecutable' || tier === 'sandboxExecutable'\n}\n\nfunction isIntegrationSupportTier(value: unknown): value is IntegrationSupportTier {\n return (\n value === 'catalogOnly' ||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AO,gBAAgB,SAAS;AACtC,SAAO,SAAS,uBAAuB,SAAS,0BAA0B,SAAS;AACrF;AAEA,SAAS,yBAAyB,OAAiD;AACjF,SACE,UAAU,iBACV,UAAU,gBACV,UAAU,uBACV,UAAU,0BACV,UAAU;AAEd;","names":["trigger","createHmac","randomUUID","timingSafeEqual","matchesFilter","missing","trigger","toTrigger","createHash","createHash","unique","randomUUID","defaultReason","redactUnknown","redactUnknown","unique","titleFromId","unique","trigger","randomUUID","randomUUID","trigger","randomUUID","resolve","trigger","unique","missing","registryEntry","sameActor","randomUUID","unique","trigger","requiredScopes","missing","createHmac","timingSafeEqual","trigger","trigger","slug","unique","trigger","riskRank","unique","supportTier"]}