@tangle-network/agent-integrations 0.21.0 → 0.22.1
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.
- package/README.md +4 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +98 -0
- package/dist/index.js.map +1 -1
- package/dist/specs.d.ts +19 -1
- package/docs/integration-execution-audit.md +233 -0
- package/docs/integration-execution-matrix.json +14448 -0
- package/package.json +2 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/activepieces-catalog.ts","../src/activepieces-overrides.ts","../src/registry.ts","../src/audit.ts","../src/approval.ts","../src/actions.ts","../src/bridge.ts","../src/errors.ts","../src/client.ts","../src/consent.ts","../src/adapter-provider.ts","../src/credentials.ts","../src/events.ts","../src/guard.ts","../src/healthcheck.ts","../src/manifest.ts","../src/passthrough.ts","../src/policy.ts","../src/presets.ts","../src/connectors/types.ts","../src/connectors/oauth.ts","../src/connectors/webhooks.ts","../src/connectors/adapters/google-calendar.ts","../src/connectors/adapters/google-sheets.ts","../src/connectors/adapters/microsoft-calendar.ts","../src/connectors/adapters/hubspot.ts","../src/connectors/adapters/slack.ts","../src/connectors/adapters/notion-database.ts","../src/connectors/adapters/declarative-rest.ts","../src/connectors/adapters/twilio-sms.ts","../src/connectors/adapters/stripe-pack.ts","../src/connectors/adapters/webhook.ts","../src/connectors/adapters/stripe-webhook-receiver.ts","../src/connectors/adapters/slack-events.ts","../src/connectors/adapters/github.ts","../src/connectors/adapters/gitlab.ts","../src/connectors/adapters/airtable.ts","../src/connectors/adapters/asana.ts","../src/connectors/adapters/salesforce.ts","../src/catalog.ts","../src/catalog-executor.ts","../src/sandbox.ts","../src/importers.ts","../src/gateway-catalog.ts","../src/activepieces-provider.ts","../src/activepieces-runtime.ts","../src/catalog-freshness.ts","../src/tangle-catalog.ts","../src/tangle-catalog-runtime.ts","../src/runtime.ts","../src/workflow.ts"],"sourcesContent":["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 './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'\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 | '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 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 if (this.policy) {\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 }\n const proceed = () => Promise.resolve(provider.invokeAction(connection, fullRequest))\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}.`, 'action_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 './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 { 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 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 }>\n source: {\n repository: string\n path: string\n license: 'MIT'\n }\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 ...(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 { buildActivepiecesConnectors } from './activepieces-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 /** @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 sources.push({\n id: 'tangle-catalog',\n connectors: 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 })\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 { 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","export type IntegrationErrorCode =\n | 'missing_connection'\n | 'missing_grant'\n | 'approval_required'\n | 'approval_denied'\n | 'connection_revoked'\n | 'connection_expired'\n | 'scope_missing'\n | 'action_denied'\n | 'action_not_found'\n | 'provider_rate_limited'\n | 'provider_auth_failed'\n | 'provider_unavailable'\n | 'provider_error'\n | 'capability_expired'\n | 'capability_invalid'\n | 'manifest_invalid'\n | 'passthrough_disabled'\n | 'input_invalid'\n | 'unknown'\n\nexport interface IntegrationUserAction {\n type: 'connect' | 'reconnect' | 'approve' | 'retry' | 'contact_support' | 'change_request'\n label: string\n connectorId?: string\n approvalId?: string\n}\n\nexport class IntegrationRuntimeError extends Error {\n readonly code: IntegrationErrorCode\n readonly status: number\n readonly userAction?: IntegrationUserAction\n readonly metadata?: Record<string, unknown>\n\n constructor(input: {\n code: IntegrationErrorCode\n message: string\n status?: number\n userAction?: IntegrationUserAction\n metadata?: Record<string, unknown>\n }) {\n super(input.message)\n this.name = 'IntegrationRuntimeError'\n this.code = input.code\n this.status = input.status ?? statusForCode(input.code)\n this.userAction = input.userAction\n this.metadata = input.metadata\n }\n}\n\nexport interface NormalizedIntegrationError {\n ok: false\n code: IntegrationErrorCode\n message: string\n status: number\n userAction?: IntegrationUserAction\n metadata?: Record<string, unknown>\n}\n\nexport function normalizeIntegrationError(error: unknown): NormalizedIntegrationError {\n if (error instanceof IntegrationRuntimeError) {\n return {\n ok: false,\n code: error.code,\n message: error.message,\n status: error.status,\n userAction: error.userAction,\n metadata: redactUnknown(error.metadata) as Record<string, unknown> | undefined,\n }\n }\n const message = error instanceof Error ? error.message : String(error ?? 'Unknown integration error.')\n return {\n ok: false,\n code: inferCode(message),\n message,\n status: 500,\n }\n}\n\nexport function statusForCode(code: IntegrationErrorCode): number {\n if (code === 'missing_connection' || code === 'missing_grant') return 409\n if (code === 'approval_required') return 202\n if (code === 'approval_denied') return 403\n if (code === 'connection_revoked' || code === 'connection_expired' || code === 'provider_auth_failed') return 401\n if (code === 'scope_missing' || code === 'action_denied' || code === 'passthrough_disabled') return 403\n if (code === 'action_not_found' || code === 'manifest_invalid' || code === 'input_invalid') return 400\n if (code === 'provider_rate_limited') return 429\n if (code === 'provider_unavailable') return 503\n if (code === 'capability_expired' || code === 'capability_invalid') return 401\n return 500\n}\n\nfunction inferCode(message: string): IntegrationErrorCode {\n if (/approval/i.test(message)) return 'approval_required'\n if (/scope/i.test(message)) return 'scope_missing'\n if (/expired/i.test(message)) return 'connection_expired'\n if (/revoked/i.test(message)) return 'connection_revoked'\n if (/rate.?limit|429/i.test(message)) return 'provider_rate_limited'\n if (/unauth|forbidden|401|403/i.test(message)) return 'provider_auth_failed'\n return 'unknown'\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 {\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","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 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 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 now: () => Date\n\n constructor(options: {\n idempotency?: IntegrationIdempotencyStore\n audit?: IntegrationAuditSink\n rateLimiter?: IntegrationRateLimiter\n now?: () => Date\n } = {}) {\n this.idempotency = options.idempotency\n this.audit = options.audit\n this.rateLimiter = options.rateLimiter\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 (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 await this.writeIdempotency(idempotencyKey, requestHash, result)\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","/**\n * Connector primitives — the contract a concrete first-party integration\n * (Google Calendar, HubSpot, Stripe, ...) implements. Lower level than the\n * hub-side `IntegrationProvider` interface from `../index.ts`: a single\n * `IntegrationProvider` typically wraps several connectors (e.g., a\n * \"first-party\" provider that lists all your shipped connectors as a\n * single catalog).\n *\n * Layering:\n *\n * IntegrationHub — vendor-neutral facade (../index.ts)\n * ↓\n * IntegrationProvider — one per gateway or first-party provider\n * ↓\n * ConnectorAdapter (this file) — one per integration (Google Calendar, ...)\n * ↓\n * upstream HTTP API — vendor SDK / fetch / OAuth\n *\n * Three load-bearing decisions encoded here:\n *\n * 1. Capabilities are typed (`read` vs `mutation`). Every mutation MUST\n * declare a CAS strategy. Conflict resolution is the SDK's job, not the\n * connector's. `validateConnectorManifest()` rejects unsafe manifests\n * before a connector is registered.\n *\n * 2. ConsistencyModel pins what the rest of the system can assume:\n * authoritative → the source IS the truth (Calendar, payments)\n * cache → we mirror with TTL and may serve stale (price list)\n * advisory → informational only (FAQ doc)\n * Agent planners can (and should) refuse to promise outcomes based on\n * `cache`/`advisory` data without a live `authoritative` confirmation.\n *\n * 3. Capabilities surface to the calling agent's tool registry by\n * transformation, not by hand-wiring. Adding a connector automatically\n * expands the agent's toolbelt for that specific user without touching\n * the prompt or runner.\n */\n\n/** Minimal JSON-schema shape used for capability arg validation. We\n * intentionally don't pull `@types/json-schema` — most consumers already\n * declare parameters as `Record<string, unknown>` and the\n * shape is whatever the LLM SDK's structured-output expects. Keep the\n * contract loose at the boundary; tighten via runtime zod where needed. */\nexport type CapabilityParameterSchema = Record<string, unknown>\n\n/** What the rest of the system is allowed to assume about freshness. */\nexport type ConsistencyModel = 'authoritative' | 'cache' | 'advisory'\n\n/** Capability classes. `read` is safe to retry; `mutation` must go through\n * MutationGuard (CAS + idempotency). `subscribe` is reserved for future\n * push-driven sources (webhook callbacks) and is not yet wired. */\nexport type CapabilityClass = 'read' | 'mutation' | 'subscribe'\n\n/** Compare-and-swap strategy a mutation uses to detect conflicts. */\nexport type CASStrategy =\n /** Upstream returns an etag/sequence on read, accepts If-Match on write\n * (Google Calendar, GitHub, GDocs revision_id). The connector returns\n * 412 / Precondition Failed on conflict; the SDK maps to ResourceContention. */\n | 'etag-if-match'\n /** Upstream guarantees exactly-once-per-key (Stripe, idempotent webhooks).\n * The SDK passes the idempotency key through; no etag check. */\n | 'native-idempotency'\n /** No upstream concurrency control. Connector MUST do read-then-write\n * and verify nothing changed in-between (best-effort). Suitable only\n * for low-contention single-user resources; rejected for any\n * consistencyModel='authoritative' write that may race. */\n | 'optimistic-read-verify'\n /** Source is not contended (e.g. logging, telemetry). Mutations are\n * fire-and-forget. Marks the capability as not eligible for\n * authoritative writes. */\n | 'none'\n\nexport interface CapabilityRead {\n name: string\n class: 'read'\n description: string\n /** JSON-schema for the tool args the agent passes when invoking. */\n parameters: CapabilityParameterSchema\n /** Optional: declare which scopes (per the connector manifest) this\n * capability requires. The capability is hidden from the agent's\n * tool registry if the user's grant didn't include them. */\n requiredScopes?: string[]\n}\n\nexport interface CapabilityMutation {\n name: string\n class: 'mutation'\n description: string\n parameters: CapabilityParameterSchema\n /** Mandatory: how does the connector guarantee at-most-once + conflict-detect? */\n cas: CASStrategy\n /** True for capabilities that affect resources outside the calling user\n * (e.g. booking against a shared calendar, charging a card). The agent's\n * planner treats these specially: requires explicit caller confirmation\n * before the call. */\n externalEffect: boolean\n requiredScopes?: string[]\n}\n\nexport type Capability = CapabilityRead | CapabilityMutation\n\n/** OAuth2 scope catalog the user has granted us, plus arbitrary metadata\n * the connector pinned at connect-time (calendar id, sheet id, webhook\n * url, …). `metadata` MUST NOT contain secrets — those go in the\n * encrypted credentials envelope. */\nexport interface DataSourceMetadata {\n scopes: string[]\n [key: string]: unknown\n}\n\n/** A connected, authenticated, ready-to-call data source for a project.\n * Persistence shape mirrors the product's connection/source row but normalized — the\n * encrypted credentials envelope is decrypted at hand-out time and held\n * in memory only for the duration of the call. */\nexport interface ResolvedDataSource {\n id: string\n projectId: string\n publishedAgentId: string | null\n kind: string\n label: string\n consistencyModel: ConsistencyModel\n scopes: string[]\n metadata: Record<string, unknown>\n /** Unwrapped credentials handed to the connector at call-time. Never\n * persisted in this shape; never logged. */\n credentials: ConnectorCredentials\n status: 'active' | 'revoked' | 'error'\n}\n\n/** Discriminated union of credential shapes. Connectors that need new\n * shapes extend this union — `kind` is sealed via the tagged pattern so\n * TypeScript catches an exhaustiveness gap at compile time. */\nexport type ConnectorCredentials =\n | { kind: 'oauth2'; accessToken: string; refreshToken?: string; expiresAt?: number }\n | { kind: 'api-key'; apiKey: string }\n | { kind: 'hmac'; secret: string }\n | { kind: 'none' }\n\n/** Result of a read capability invocation. */\nexport interface CapabilityReadResult {\n /** Free-form payload — the connector's data shape. The agent receives\n * this as the tool result; planners consume it via JSON-shape contract\n * declared in the capability's `parameters` (output schema). */\n data: unknown\n /** Optional etag/sequence the caller can reuse for a subsequent CAS\n * mutation. */\n etag?: string\n /** When this read happened (UTC ms since epoch). */\n fetchedAt: number\n}\n\n/** Result of a mutation capability invocation. Either committed (with the\n * resulting etag/sequence so the caller can chain mutations), or\n * contended (the upstream rejected with a state mismatch — the agent\n * should re-read and retry, or surface alternatives to the caller). */\nexport type CapabilityMutationResult =\n | {\n status: 'committed'\n data: unknown\n etagAfter?: string\n committedAt: number\n /** True iff this commit was returned from the idempotency store\n * rather than executed against upstream. The caller can use this\n * to suppress confirmation messages on retry. */\n idempotentReplay: boolean\n }\n | {\n status: 'conflict'\n /** Best-effort alternative options the upstream surfaced (e.g.,\n * next-available calendar slots after a booking conflict). */\n alternatives: unknown[]\n /** The current authoritative state, if the connector could re-read\n * cheaply. */\n currentState?: unknown\n message: string\n }\n | {\n status: 'rate-limited'\n /** Wall-clock ms the caller should wait before retrying. The SDK\n * computes this from the bucket's refill schedule so the agent\n * doesn't have to guess. */\n retryAfterMs: number\n message: string\n }\n\n/** Inputs the SDK passes into the connector's executeRead / executeMutation. */\nexport interface ConnectorInvocation {\n source: ResolvedDataSource\n capabilityName: string\n args: Record<string, unknown>\n /** Idempotency key the caller (or the SDK's defaulting policy) supplied.\n * Always present at the connector boundary — the SDK manufactures one\n * if the agent didn't pass one. */\n idempotencyKey: string\n /** Optional caller-supplied etag the connector should send as If-Match. */\n expectedEtag?: string\n /** Product/session id (if any) for forensic logging. */\n callSessionId?: string\n}\n\n/** A single inbound event extracted from a push payload. The webhook\n * receiver persists one `InboundEvent` row per entry the connector returns. */\nexport interface InboundEvent {\n eventType: string\n providerEventId?: string\n payload: Record<string, unknown>\n}\n\n/** Adapter response from an inbound-webhook dispatch. The receiver persists\n * every `events[]` entry, then either honors the connector's `response`\n * override (Slack `url_verification` echo, provider-specific 2xx body) or\n * defaults to `{status: 200, body: {received: true, count: events.length}}`. */\nexport interface EventHandlerResult {\n events: InboundEvent[]\n /** Optional: how to respond to the provider. Stripe wants 200 within\n * 30s; Slack wants the challenge param echoed. */\n response?: { status: number; body: unknown; headers?: Record<string, string> }\n}\n\n/**\n * Connector adapter — one per integration kind. Stateless. The SDK holds\n * the persistence + crypto + mutation-guard concerns; the adapter only\n * knows how to talk to its upstream.\n */\nexport interface ConnectorAdapter {\n /** Manifest entry the registry uses to render UI + validate args. */\n manifest: ConnectorManifest\n /** Read invocation. Required when manifest.capabilities contains reads.\n * Should return whatever shape the capability declared\n * in its parameters output schema. */\n executeRead?(inv: ConnectorInvocation): Promise<CapabilityReadResult>\n /** Mutation invocation. Required when manifest.capabilities contains mutations.\n * Throws ResourceContention on a CAS miss; throws\n * any other Error for upstream failures. The MutationGuard wraps this\n * with idempotency-key short-circuit + audit logging — adapters do\n * NOT manage their own dedup. */\n executeMutation?(inv: ConnectorInvocation): Promise<CapabilityMutationResult>\n /** Inbound webhook signature verifier. Called BEFORE handleInboundEvent.\n * MUST use constant-time comparison (`crypto.timingSafeEqual`) for any\n * HMAC check. The receiver returns 401 on `valid=false` without invoking\n * handleInboundEvent. Optional: connectors that don't accept push events\n * omit this method and the receiver returns 405 for the kind. */\n verifySignature?(input: {\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n source: ResolvedDataSource\n }): { valid: boolean; reason?: string }\n /** Inbound webhook dispatch. Called AFTER verifySignature passes. The\n * adapter parses the provider payload and emits zero-or-more\n * `InboundEvent` rows; the receiver persists them as one row each (modulo\n * the (dataSourceId, providerEventId) dedup unique). The optional\n * `response` overrides the receiver's default 200 (Slack `url_verification`\n * needs to echo the challenge in the body to pass Slack's app-config check). */\n handleInboundEvent?(input: {\n source: ResolvedDataSource\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n }): Promise<EventHandlerResult>\n /** OAuth callback handler — exchanges the auth code for tokens, returns\n * the credentials envelope + scopes + metadata. Only present for\n * oauth2-style adapters. */\n exchangeOAuth?(input: {\n code: string\n state: string\n codeVerifier: string\n redirectUri: string\n }): Promise<{\n credentials: ConnectorCredentials\n scopes: string[]\n metadata: Record<string, unknown>\n }>\n /** Refresh access token. Only required for oauth2 adapters with\n * short-lived access tokens. */\n refreshToken?(input: ConnectorCredentials): Promise<ConnectorCredentials>\n /** Health check — invoked when the user clicks \"Test connection\" in the\n * UI. Should perform the cheapest possible read that proves the grant\n * is still valid. Returns `{ok: false, reason}` rather than throwing\n * for the common case (token expired, scope missing). */\n test(source: ResolvedDataSource): Promise<{ ok: true } | { ok: false; reason: string }>\n}\n\n/** Static manifest a connector module exports. Drives the UI catalog,\n * scope display, capability discovery for the agent's tool registry. */\nexport interface ConnectorManifest {\n /** Stable kind id used as the foreign key in DataSource.kind. */\n kind: string\n /** Human label shown in the UI catalog. */\n displayName: string\n /** One-paragraph description shown next to the connect button. */\n description: string\n /** Auth shape this connector requires. */\n auth: AuthSpec\n /** Capability catalog — the agent's tool registry derives ToolDefinition\n * entries from this list at request time. */\n capabilities: Capability[]\n /** ConsistencyModel default for this kind — overridable per DataSource\n * if a particular instance is special (e.g., a user marks a sheet as\n * `cache` because they refresh it nightly). */\n defaultConsistencyModel: ConsistencyModel\n /** Connector category for UI grouping. */\n category: 'calendar' | 'spreadsheet' | 'crm' | 'doc' | 'webhook' | 'storage' | 'comms' | 'commerce' | 'other'\n /** Optional icon URL or named icon. */\n icon?: string\n /** Optional per-kind rate-limit budget. The SDK enforces it inside\n * `executeGuardedMutation` and the read path of `/invoke`. Omit to\n * leave the connector unrestricted. */\n rateLimit?: RateLimitSpec\n}\n\n/** Token-bucket budget the SDK enforces against the connector's upstream.\n * We meter on OUR side rather than letting the upstream reject so a\n * chatty agent can't burn quota that's shared across customers (almost\n * every OAuth client is). */\nexport interface RateLimitSpec {\n /** Max requests per window. */\n requests: number\n /** Window in ms. */\n windowMs: number\n /** Whether to apply across all DataSources sharing the same OAuth\n * client (true; default), or per-DataSource (false). The former\n * matches how upstreams meter (per-app), so almost always pick true. */\n scope?: 'oauth-client' | 'data-source'\n}\n\nexport type AuthSpec =\n | {\n kind: 'oauth2'\n /** Authorization endpoint URL. */\n authorizationUrl: string\n /** Token endpoint URL. */\n tokenUrl: string\n /** Scopes requested in the authorization grant. The user UI shows\n * these so the customer knows what's being shared. */\n scopes: string[]\n /** Whether the connector supports incremental authorization (Google\n * does; many don't). */\n incremental?: boolean\n /** Env-var name holding the OAuth client_id. */\n clientIdEnv: string\n /** Env-var name holding the OAuth client_secret. */\n clientSecretEnv: string\n /** Optional extra params attached to the authorization URL (e.g.,\n * Google's `access_type=offline&prompt=consent` to obtain refresh\n * tokens). */\n extraAuthParams?: Record<string, string>\n }\n | {\n kind: 'api-key'\n /** UI hint shown when collecting the key. */\n hint: string\n }\n | { kind: 'hmac' }\n | { kind: 'none' }\n\n/** Thrown by `executeMutation` when upstream rejects on CAS — caught and\n * rewrapped by MutationGuard. */\nexport class ResourceContention extends Error {\n override readonly name = 'ResourceContention'\n constructor(\n message: string,\n public readonly alternatives: unknown[] = [],\n public readonly currentState?: unknown,\n ) {\n super(message)\n }\n}\n\n/** Thrown when the connector finds the user's grant has been revoked or\n * the access token is no longer valid AND refresh failed. Surfaces to\n * the UI as \"Reconnect required\". */\nexport class CredentialsExpired extends Error {\n override readonly name = 'CredentialsExpired'\n constructor(message: string, public readonly dataSourceId: string) {\n super(message)\n }\n}\n\nexport interface ConnectorManifestValidationIssue {\n path: string\n message: string\n}\n\nexport interface ConnectorManifestValidationResult {\n ok: boolean\n issues: ConnectorManifestValidationIssue[]\n}\n\n/** Validate the static connector manifest before a provider registers it.\n * This catches the expensive mistakes early: duplicate capability names,\n * mutation capabilities without CAS, authoritative fire-and-forget writes,\n * and invalid rate-limit specs. */\nexport function validateConnectorManifest(manifest: ConnectorManifest): ConnectorManifestValidationResult {\n const issues: ConnectorManifestValidationIssue[] = []\n if (!manifest.kind.trim()) issues.push({ path: 'kind', message: 'kind is required' })\n if (!manifest.displayName.trim()) issues.push({ path: 'displayName', message: 'displayName is required' })\n const seen = new Set<string>()\n for (const [index, capability] of manifest.capabilities.entries()) {\n const path = `capabilities[${index}]`\n if (!capability.name.trim()) issues.push({ path: `${path}.name`, message: 'capability name is required' })\n if (seen.has(capability.name)) issues.push({ path: `${path}.name`, message: `duplicate capability name: ${capability.name}` })\n seen.add(capability.name)\n if (capability.class === 'mutation') {\n if (!capability.cas) issues.push({ path: `${path}.cas`, message: 'mutation capability must declare a CAS strategy' })\n if (manifest.defaultConsistencyModel === 'authoritative' && capability.cas === 'none') {\n issues.push({ path: `${path}.cas`, message: 'authoritative mutations cannot use cas=\"none\"' })\n }\n }\n }\n if (manifest.rateLimit) {\n if (!Number.isFinite(manifest.rateLimit.requests) || manifest.rateLimit.requests <= 0) {\n issues.push({ path: 'rateLimit.requests', message: 'rateLimit.requests must be positive' })\n }\n if (!Number.isFinite(manifest.rateLimit.windowMs) || manifest.rateLimit.windowMs <= 0) {\n issues.push({ path: 'rateLimit.windowMs', message: 'rateLimit.windowMs must be positive' })\n }\n }\n return { ok: issues.length === 0, issues }\n}\n\nexport function assertValidConnectorManifest(manifest: ConnectorManifest): void {\n const result = validateConnectorManifest(manifest)\n if (!result.ok) {\n throw new Error(`Invalid connector manifest ${manifest.kind || '<unknown>'}: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)\n }\n}\n","/**\n * Generic OAuth2 helper used by every oauth-shaped connector (Google\n * Calendar, Sheets, Drive, HubSpot, Salesforce, Zoom, ...).\n *\n * Everything PKCE-aware. Opaque-state CSRF guard. Refresh-token aware.\n * No connector-specific logic lives here — adapters hand a `clientId`,\n * `clientSecret`, `tokenUrl`, optional `extraAuthParams` and the rest is\n * mechanical.\n *\n * State and code_verifier are kept in a short-TTL flow store keyed by the\n * opaque `state` we round-trip through the provider. The default store is\n * in-memory for local/dev and tests. Production deployments should inject a\n * durable store backed by KV/Redis/D1/etc. so callbacks can land on any worker.\n */\n\nimport { createHash, randomBytes } from 'crypto'\n\nexport interface PendingOAuthFlow {\n /** code_verifier for PKCE. */\n codeVerifier: string\n /** Opaque-state value also returned in the OAuth redirect. */\n state: string\n /** Project the user is connecting under. */\n projectId: string\n /** Connector kind (e.g. 'google-calendar'). */\n kind: string\n /** Operator-supplied label that becomes DataSource.label. */\n label: string\n /** When we drop the entry. */\n expiresAt: number\n /** The redirectUri we used in the start step — must match exactly on\n * the callback exchange. */\n redirectUri: string\n}\n\nconst PENDING_TTL_MS = 10 * 60 * 1000\n\nexport interface OAuthFlowStore {\n put(state: string, flow: PendingOAuthFlow): Promise<void> | void\n consume(state: string): Promise<PendingOAuthFlow | undefined> | PendingOAuthFlow | undefined\n sweep?(now: number): Promise<void> | void\n clear?(): Promise<void> | void\n}\n\nexport class InMemoryOAuthFlowStore implements OAuthFlowStore {\n private readonly pendingFlows = new Map<string, PendingOAuthFlow>()\n\n put(state: string, flow: PendingOAuthFlow): void {\n this.pendingFlows.set(state, flow)\n }\n\n consume(state: string): PendingOAuthFlow | undefined {\n const flow = this.pendingFlows.get(state)\n this.pendingFlows.delete(state)\n if (!flow || flow.expiresAt <= Date.now()) return undefined\n return flow\n }\n\n sweep(now: number): void {\n for (const [k, v] of this.pendingFlows) {\n if (v.expiresAt <= now) this.pendingFlows.delete(k)\n }\n }\n\n clear(): void {\n this.pendingFlows.clear()\n }\n}\n\nconst defaultFlowStore = new InMemoryOAuthFlowStore()\n\nexport interface StartOAuthInput {\n projectId: string\n kind: string\n label: string\n authorizationUrl: string\n scopes: string[]\n clientId: string\n redirectUri: string\n /** Optional extra query params; Google needs `access_type=offline` and\n * `prompt=consent` to issue refresh tokens reliably. */\n extraAuthParams?: Record<string, string>\n /** Optional flow store. Use a durable store in distributed production\n * runtimes; omitted means local in-memory storage. */\n store?: OAuthFlowStore\n /** Override clock for tests. */\n now?: number\n}\n\nexport interface StartOAuthOutput {\n /** URL the SPA should redirect the user to. */\n authorizationUrl: string\n /** State token — caller stashes this in localStorage to verify on\n * callback. */\n state: string\n}\n\n/** Build the authorization URL + state. SPA navigates the user there;\n * user consents; provider redirects back to redirectUri with `code` +\n * `state`. The caller's callback then invokes `consumePendingFlow`. */\nexport function startOAuthFlow(input: StartOAuthInput): StartOAuthOutput {\n const store = input.store ?? defaultFlowStore\n const now = input.now ?? Date.now()\n store.sweep?.(now)\n const codeVerifier = base64Url(randomBytes(48))\n const codeChallenge = base64Url(createHash('sha256').update(codeVerifier).digest())\n const state = base64Url(randomBytes(24))\n\n store.put(state, {\n codeVerifier,\n state,\n projectId: input.projectId,\n kind: input.kind,\n label: input.label,\n redirectUri: input.redirectUri,\n expiresAt: now + PENDING_TTL_MS,\n })\n\n const url = new URL(input.authorizationUrl)\n url.searchParams.set('response_type', 'code')\n url.searchParams.set('client_id', input.clientId)\n url.searchParams.set('redirect_uri', input.redirectUri)\n url.searchParams.set('scope', input.scopes.join(' '))\n url.searchParams.set('state', state)\n url.searchParams.set('code_challenge', codeChallenge)\n url.searchParams.set('code_challenge_method', 'S256')\n if (input.extraAuthParams) {\n for (const [k, v] of Object.entries(input.extraAuthParams)) {\n url.searchParams.set(k, v)\n }\n }\n return { authorizationUrl: url.toString(), state }\n}\n\n/** Look up + remove the pending flow record. Throws if state is unknown\n * or expired (CSRF guard / replay protection). */\nexport async function consumePendingFlow(state: string, store: OAuthFlowStore = defaultFlowStore): Promise<PendingOAuthFlow> {\n await store.sweep?.(Date.now())\n const flow = await store.consume(state)\n if (!flow) {\n throw new Error('Unknown or expired OAuth state: possible CSRF, replay, or stale flow')\n }\n return flow\n}\n\nexport interface ExchangeCodeInput {\n tokenUrl: string\n clientId: string\n clientSecret: string\n code: string\n codeVerifier: string\n redirectUri: string\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}\n\nexport interface OAuthTokens {\n accessToken: string\n refreshToken?: string\n expiresIn?: number\n scope?: string\n tokenType?: string\n}\n\n/** POST authorization code → token endpoint. Provider-agnostic; if a\n * provider returns a non-standard JSON shape, the adapter wraps this\n * call rather than reaching into the helper. */\nexport async function exchangeAuthorizationCode(input: ExchangeCodeInput): Promise<OAuthTokens> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: input.clientId,\n client_secret: input.clientSecret,\n code: input.code,\n redirect_uri: input.redirectUri,\n code_verifier: input.codeVerifier,\n })\n const res = await (input.fetchImpl ?? fetch)(input.tokenUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body,\n signal: input.signal,\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`OAuth token exchange failed: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n access_token: string\n refresh_token?: string\n expires_in?: number\n scope?: string\n token_type?: string\n }\n return {\n accessToken: json.access_token,\n refreshToken: json.refresh_token,\n expiresIn: json.expires_in,\n scope: json.scope,\n tokenType: json.token_type,\n }\n}\n\nexport interface RefreshInput {\n tokenUrl: string\n clientId: string\n clientSecret: string\n refreshToken: string\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}\n\n/** Refresh an access token. Returns the new tokens — the connector layer\n * is responsible for re-encrypting + persisting the envelope. */\nexport async function refreshAccessToken(input: RefreshInput): Promise<OAuthTokens> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: input.clientId,\n client_secret: input.clientSecret,\n refresh_token: input.refreshToken,\n })\n const res = await (input.fetchImpl ?? fetch)(input.tokenUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body,\n signal: input.signal,\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`OAuth refresh failed: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n access_token: string\n refresh_token?: string\n expires_in?: number\n scope?: string\n token_type?: string\n }\n return {\n accessToken: json.access_token,\n // Some providers omit refresh_token on refresh — keep the previous one\n // in that case (caller passes through if undefined).\n refreshToken: json.refresh_token,\n expiresIn: json.expires_in,\n scope: json.scope,\n tokenType: json.token_type,\n }\n}\n\nfunction base64Url(buf: Buffer): string {\n return buf.toString('base64').replace(/=+$/, '').replace(/\\+/g, '-').replace(/\\//g, '_')\n}\n\n/** Test-only — drop pending flows between unit-test runs. */\nexport function _resetPendingFlowsForTests(): void {\n defaultFlowStore.clear?.()\n}\n","/**\n * Inbound webhook signature verifiers — provider-specific HMAC schemes.\n *\n * Each signature scheme is a pure function:\n * (rawBody: string, headers, secret, now?) → boolean\n *\n * Constant-time comparison via `crypto.timingSafeEqual`. Timestamps are\n * checked against a configurable tolerance to bound replay risk; the default\n * mirrors the upstream provider's documented window (Stripe: 5 min, Slack: 5 min).\n *\n * These verifiers are the building blocks for any inbound-webhook receiver\n * (a route + a `verify` call + a per-event handler). They live in this\n * package so every consumer of the integration substrate gets correct\n * verification — not just one product reimplementing it.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto'\n\n/** Default replay-protection window. Providers commonly use 5 minutes. */\nexport const DEFAULT_SIGNATURE_TOLERANCE_SECONDS = 5 * 60\n\n// ─── Stripe ─────────────────────────────────────────────────────────────\n//\n// Stripe signs webhooks with a single header `Stripe-Signature` of the form\n//\n// t=<timestamp>,v1=<sig1>,v1=<sig2>,...\n//\n// where `t` is the Unix timestamp the event was generated, and each `v1`\n// is `HMAC-SHA256(secret, \"<t>.<rawBody>\")`. Multiple `v1` entries appear\n// during secret rotation — any one matching is sufficient.\n//\n// https://stripe.com/docs/webhooks/signatures\n\nexport interface ParsedStripeSignatureHeader {\n t: number\n sigs: string[]\n}\n\nexport function parseStripeSignatureHeader(header: string): ParsedStripeSignatureHeader | null {\n const acc: { ts?: number; sigs: string[] } = { sigs: [] }\n for (const part of header.split(',')) {\n const idx = part.indexOf('=')\n if (idx < 0) continue\n const key = part.slice(0, idx).trim()\n const val = part.slice(idx + 1).trim()\n if (key === 't') {\n const n = Number(val)\n if (Number.isFinite(n)) acc.ts = n\n } else if (key === 'v1') {\n acc.sigs.push(val)\n }\n }\n if (acc.ts === undefined || acc.sigs.length === 0) return null\n return { t: acc.ts, sigs: acc.sigs }\n}\n\nexport interface StripeVerifyOptions {\n /** Replay-protection window in seconds. Default 300. */\n toleranceSeconds?: number\n /** Override `now()` for tests. UTC seconds. */\n now?: number\n}\n\n/** Verify a Stripe webhook signature against the raw request body. */\nexport function verifyStripeSignature(\n rawBody: string,\n signatureHeader: string,\n secret: string,\n options: StripeVerifyOptions = {},\n): boolean {\n const parsed = parseStripeSignatureHeader(signatureHeader)\n if (!parsed) return false\n const tolerance = options.toleranceSeconds ?? DEFAULT_SIGNATURE_TOLERANCE_SECONDS\n const now = options.now ?? Math.floor(Date.now() / 1000)\n if (Math.abs(now - parsed.t) > tolerance) return false\n const expected = createHmac('sha256', secret).update(`${parsed.t}.${rawBody}`).digest('hex')\n const expectedBuf = Buffer.from(expected, 'utf8')\n for (const sig of parsed.sigs) {\n const sigBuf = Buffer.from(sig, 'utf8')\n if (sigBuf.length !== expectedBuf.length) continue\n if (timingSafeEqual(sigBuf, expectedBuf)) return true\n }\n return false\n}\n\n// ─── Slack ──────────────────────────────────────────────────────────────\n//\n// Slack signs request bodies with two headers:\n//\n// X-Slack-Signature: v0=<HMAC-SHA256(secret, \"v0:<ts>:<body>\")>\n// X-Slack-Request-Timestamp: <ts>\n//\n// https://api.slack.com/authentication/verifying-requests-from-slack\n\nexport interface SlackVerifyOptions {\n toleranceSeconds?: number\n now?: number\n}\n\nexport function verifySlackSignature(\n rawBody: string,\n signatureHeader: string,\n timestampHeader: string,\n secret: string,\n options: SlackVerifyOptions = {},\n): boolean {\n if (!signatureHeader.startsWith('v0=')) return false\n const ts = Number(timestampHeader)\n if (!Number.isFinite(ts)) return false\n const tolerance = options.toleranceSeconds ?? DEFAULT_SIGNATURE_TOLERANCE_SECONDS\n const now = options.now ?? Math.floor(Date.now() / 1000)\n if (Math.abs(now - ts) > tolerance) return false\n const expected = 'v0=' + createHmac('sha256', secret).update(`v0:${ts}:${rawBody}`).digest('hex')\n const expectedBuf = Buffer.from(expected, 'utf8')\n const sigBuf = Buffer.from(signatureHeader, 'utf8')\n if (sigBuf.length !== expectedBuf.length) return false\n return timingSafeEqual(sigBuf, expectedBuf)\n}\n\n// ─── Generic HMAC ───────────────────────────────────────────────────────\n//\n// For \"we shipped a webhook URL with a shared HMAC secret\" patterns —\n// covers any custom integration where the operator picks the message\n// format. The signed message is the literal `rawBody` (no timestamp\n// prefix); replay protection is the caller's responsibility (use a\n// nonce header + a small dedup cache).\n\nexport interface GenericHmacVerifyOptions {\n /** sha256 (default) | sha1 | sha512 — matches the algorithm the receiver\n * computed at sign time. */\n algorithm?: 'sha256' | 'sha1' | 'sha512'\n /** Optional prefix the receiver prepends to the signature in the header\n * (e.g., `'sha256='`). Stripped before constant-time comparison. */\n signaturePrefix?: string\n /** Lowercase comparison (most providers emit hex-lowercase). Default true. */\n lowercaseHex?: boolean\n}\n\nexport function verifyHmacSignature(\n rawBody: string,\n signatureHeader: string,\n secret: string,\n options: GenericHmacVerifyOptions = {},\n): boolean {\n const algorithm = options.algorithm ?? 'sha256'\n const prefix = options.signaturePrefix ?? ''\n const lower = options.lowercaseHex ?? true\n let candidate = signatureHeader\n if (prefix) {\n if (!candidate.startsWith(prefix)) return false\n candidate = candidate.slice(prefix.length)\n }\n if (lower) candidate = candidate.toLowerCase()\n const expected = createHmac(algorithm, secret).update(rawBody).digest('hex')\n const expectedBuf = Buffer.from(expected, 'utf8')\n const sigBuf = Buffer.from(candidate, 'utf8')\n if (sigBuf.length !== expectedBuf.length) return false\n return timingSafeEqual(sigBuf, expectedBuf)\n}\n\n// ─── Twilio ─────────────────────────────────────────────────────────────\n//\n// Twilio's webhook signature scheme is unlike Stripe/Slack — it doesn't\n// sign the raw body. It signs the concatenation of:\n//\n// fullUrl + sortedConcatenatedParams\n//\n// where `fullUrl` is the public URL Twilio called (scheme + host + path\n// + query, exactly as Twilio constructed it from your console config),\n// and `sortedConcatenatedParams` is `key1+value1+key2+value2+...` over\n// the alphabetically-sorted keys of the POST body params (form-encoded).\n//\n// For JSON-bodied Twilio webhooks (Conversations API), the body is signed\n// as raw bytes — pass `{ bodyAsRaw: true, rawBody }` for that path.\n//\n// HMAC-SHA1, base64-encoded. Header: `X-Twilio-Signature`.\n//\n// https://www.twilio.com/docs/usage/webhooks/webhooks-security\n\nexport interface TwilioVerifyOptions {\n /** Skip verification when the auth token isn't configured. Useful in\n * dev where the receiver wants to accept any payload. Default `false`\n * — production should always require a configured token. */\n skipWhenAuthTokenMissing?: boolean\n /** When true, sign the raw body instead of the URL-encoded sorted-params\n * reduction. Twilio uses raw-body signing for `application/json`\n * webhook bodies. Default `false`. */\n bodyAsRaw?: boolean\n /** When `bodyAsRaw` is true, the raw body to sign. Ignored otherwise. */\n rawBody?: string\n}\n\n/** Verify a Twilio webhook signature. */\nexport function verifyTwilioSignature(\n input: {\n authToken: string | null | undefined\n signatureHeader: string | string[] | undefined\n fullUrl: string | null | undefined\n params: Record<string, string> | undefined\n },\n options: TwilioVerifyOptions = {},\n): boolean {\n if (!input.authToken) {\n return options.skipWhenAuthTokenMissing === true\n }\n const signature = input.signatureHeader\n if (!signature || Array.isArray(signature)) return false\n if (!input.fullUrl) return false\n\n const data = options.bodyAsRaw === true\n ? input.fullUrl + (options.rawBody ?? '')\n : Object.keys(input.params ?? {})\n .sort()\n .reduce((acc, key) => acc + key + (input.params![key] ?? ''), input.fullUrl)\n\n const expected = createHmac('sha1', input.authToken).update(data).digest('base64')\n const expectedBuf = Buffer.from(expected)\n const sigBuf = Buffer.from(signature)\n if (expectedBuf.length !== sigBuf.length) return false\n return timingSafeEqual(expectedBuf, sigBuf)\n}\n\n// ─── Header helper ──────────────────────────────────────────────────────\n//\n// Most fastify/express adapters expose request headers as\n// `Record<string, string | string[] | undefined>`. This helper picks the\n// first canonical value for a given name (case-insensitive).\n\nexport function firstHeader(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const v = headers[name]\n ?? headers[name.toLowerCase()]\n ?? Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1]\n if (Array.isArray(v)) return v[0]\n return typeof v === 'string' ? v : undefined\n}\n","/**\n * Google Calendar connector — CAS reference implementation.\n *\n * Scopes: `https://www.googleapis.com/auth/calendar` covers list/insert/\n * patch on the user's calendars. We could split read/write but for v1 the\n * single scope keeps the consent screen simple; an operator who wants\n * read-only-Calendar can pick a different `kind` later (`google-calendar-readonly`).\n *\n * The two capabilities the agent actually needs:\n *\n * list_availability(calendarId, timeMin, timeMax)\n * → {busy: [{start, end}], events: [{id, etag, start, end, summary}]}\n * Read; no CAS. Cheap (events.list).\n *\n * book_slot(calendarId, start, end, summary, attendees?)\n * → {eventId, etag}\n * Mutation. CAS by Calendar's own conflict-detection: we re-list\n * events for the requested window inside the same call, and if any\n * OVERLAP exists we return `conflict` with the next-3 free slots\n * mined from the user's freebusy, instead of inserting.\n *\n * Why pre-flight read-then-insert rather than relying on If-Match:\n * `events.insert` doesn't take If-Match (you can't precondition an\n * insert against a non-existent resource). Calendar's own\n * `freebusy.query` is the canonical conflict signal. The whole flow is:\n *\n * 1. freebusy.query for [start, end] on this calendarId\n * 2. if busy → emit ResourceContention with next-3 free slots\n * (computed by walking forward in 30-min steps until 3 free\n * windows of (end-start) duration found)\n * 3. else events.insert with idempotency-key as `requestId` (a Calendar\n * API feature that gives us per-key dedup at upstream)\n *\n * Step 3's `requestId` parameter means a retry of the same idempotency\n * key on the same calendar will return the original event rather than\n * creating a duplicate, which composes correctly with our MutationGuard's\n * idempotency record (which short-circuits before ever hitting upstream\n * on the second call). Defense-in-depth.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport {\n exchangeAuthorizationCode,\n refreshAccessToken,\n} from '../oauth.js'\n\nconst SCOPES = ['https://www.googleapis.com/auth/calendar']\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth'\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface GoogleCalendarOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function googleCalendar(opts: GoogleCalendarOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'google-calendar',\n displayName: 'Google Calendar',\n description:\n \"Let your agent check availability and book against a Google Calendar. Conflict-resolved: two callers can't grab the same slot — the second one is offered the next free time.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'GOOGLE_OAUTH_CLIENT_ID',\n clientSecretEnv: 'GOOGLE_OAUTH_CLIENT_SECRET',\n extraAuthParams: { access_type: 'offline', prompt: 'consent', include_granted_scopes: 'true' },\n },\n category: 'calendar',\n defaultConsistencyModel: 'authoritative',\n // Google Calendar's per-project quota is ~600 req/min before\n // throttling kicks in (Calendar API \"Queries per minute per user\",\n // shared per OAuth client). We meter at that rate locally so the\n // FIRST chatty agent doesn't push the shared client into Google's\n // throttle pool and degrade everyone else's quota.\n rateLimit: { requests: 600, windowMs: 60_000, scope: 'oauth-client' },\n capabilities: [\n {\n name: 'list_availability',\n class: 'read',\n description:\n 'Look up busy/free times on the connected calendar between timeMin and timeMax (RFC3339 timestamps).',\n parameters: {\n type: 'object',\n properties: {\n timeMin: { type: 'string', description: 'RFC3339 lower bound (inclusive)' },\n timeMax: { type: 'string', description: 'RFC3339 upper bound (exclusive)' },\n },\n required: ['timeMin', 'timeMax'],\n },\n },\n {\n name: 'book_slot',\n class: 'mutation',\n description:\n 'Reserve a time window on the connected calendar. Returns conflict + alternatives if the slot is no longer free.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n start: { type: 'string', description: 'RFC3339 start time' },\n end: { type: 'string', description: 'RFC3339 end time' },\n summary: { type: 'string', description: 'Event title shown on the calendar' },\n description: { type: 'string', description: 'Optional event description' },\n attendees: {\n type: 'array',\n items: { type: 'string', description: 'email' },\n },\n },\n required: ['start', 'end', 'summary'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'list_availability') {\n throw new Error(`google-calendar: unknown read capability ${inv.capabilityName}`)\n }\n const calendarId = readMetaString(inv.source.metadata, 'calendarId')\n const { timeMin, timeMax } = inv.args as { timeMin: string; timeMax: string }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const fb = await freebusyQuery({ accessToken, calendarId, timeMin, timeMax })\n return {\n data: { busy: fb.busy },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'book_slot') {\n throw new Error(`google-calendar: unknown mutation capability ${inv.capabilityName}`)\n }\n const calendarId = readMetaString(inv.source.metadata, 'calendarId')\n const { start, end, summary, description, attendees } = inv.args as {\n start: string\n end: string\n summary: string\n description?: string\n attendees?: string[]\n }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n\n // Pre-flight: is the requested window busy?\n const fb = await freebusyQuery({ accessToken, calendarId, timeMin: start, timeMax: end })\n if (fb.busy.length > 0) {\n const startMs = Date.parse(start)\n const endMs = Date.parse(end)\n const durMs = endMs - startMs\n const alternatives = await findNextFreeSlots({\n accessToken,\n calendarId,\n searchFromMs: endMs,\n durationMs: durMs,\n wanted: 3,\n })\n throw new ResourceContention(\n `requested slot ${start}–${end} is no longer free`,\n alternatives,\n { busy: fb.busy },\n )\n }\n\n // Insert. requestId == idempotencyKey gives upstream-side dedup.\n // Calendar requires it to be ≤1024 chars and ASCII.\n const requestId = inv.idempotencyKey.replace(/[^a-zA-Z0-9_:.-]/g, '_').slice(0, 1024)\n const event = {\n summary,\n description,\n start: { dateTime: start },\n end: { dateTime: end },\n attendees: attendees?.map(email => ({ email })),\n }\n const res = await fetch(\n `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?conferenceDataVersion=0&sendUpdates=none&requestId=${encodeURIComponent(requestId)}`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(event),\n signal: AbortSignal.timeout(15_000),\n },\n )\n if (res.status === 409) {\n // Calendar reports duplicate; return as committed by treating the\n // recovered event as the response (idempotent semantics).\n const dup = (await res.json().catch(() => ({}))) as { id?: string; etag?: string }\n return {\n status: 'committed',\n data: dup,\n etagAfter: dup.etag,\n committedAt: Date.now(),\n idempotentReplay: true,\n }\n }\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Google Calendar rejected token (${res.status})`, inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`google-calendar book_slot ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; etag: string; htmlLink?: string }\n return {\n status: 'committed',\n data: { eventId: created.id, htmlLink: created.htmlLink },\n etagAfter: created.etag,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n // Pin which calendar this connection points at. Default to the\n // user's primary; the UI lets the user pick a different calendar\n // post-connect by patching DataSource.metadata.calendarId.\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n metadata: { calendarId: 'primary' },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('google-calendar.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n const calendarId = readMetaString(source.metadata, 'calendarId')\n const url = `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403) {\n return { ok: false, reason: `Google rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `Google returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\ninterface FreeBusyResult {\n busy: Array<{ start: string; end: string }>\n}\n\nasync function freebusyQuery(input: {\n accessToken: string\n calendarId: string\n timeMin: string\n timeMax: string\n}): Promise<FreeBusyResult> {\n const res = await fetch('https://www.googleapis.com/calendar/v3/freeBusy', {\n method: 'POST',\n headers: {\n authorization: `Bearer ${input.accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n timeMin: input.timeMin,\n timeMax: input.timeMax,\n items: [{ id: input.calendarId }],\n }),\n signal: AbortSignal.timeout(10_000),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`freebusy ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n calendars?: Record<string, { busy?: Array<{ start: string; end: string }> }>\n }\n return { busy: json.calendars?.[input.calendarId]?.busy ?? [] }\n}\n\n/** Given a starting point and a duration, walk forward looking up\n * freebusy in 24-hour windows, mining (wanted) free slots that are at\n * least durationMs long. Stops at a horizon of 14 days from search\n * start — past that and the agent should propose a different day. */\nasync function findNextFreeSlots(input: {\n accessToken: string\n calendarId: string\n searchFromMs: number\n durationMs: number\n wanted: number\n}): Promise<Array<{ start: string; end: string }>> {\n const horizonMs = input.searchFromMs + 14 * 24 * 60 * 60 * 1000\n const out: Array<{ start: string; end: string }> = []\n let cursor = input.searchFromMs\n // Step the search window 1 day at a time.\n while (cursor < horizonMs && out.length < input.wanted) {\n const windowEnd = Math.min(cursor + 24 * 60 * 60 * 1000, horizonMs)\n const fb = await freebusyQuery({\n accessToken: input.accessToken,\n calendarId: input.calendarId,\n timeMin: new Date(cursor).toISOString(),\n timeMax: new Date(windowEnd).toISOString(),\n })\n // Walk through free intervals between busy spans inside this window.\n const busy = fb.busy\n .map(b => ({ s: Date.parse(b.start), e: Date.parse(b.end) }))\n .filter(b => Number.isFinite(b.s) && Number.isFinite(b.e))\n .sort((a, b) => a.s - b.s)\n let pos = cursor\n for (const b of busy) {\n if (out.length >= input.wanted) break\n if (b.s > pos && b.s - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n pos = Math.max(pos, b.e)\n }\n if (out.length < input.wanted && windowEnd - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n cursor = windowEnd\n }\n return out.slice(0, input.wanted)\n}\n\n/** If access token is missing or expired, refresh it. Caller is\n * responsible for persisting the rotated envelope back to the row —\n * for now we mutate the in-memory copy so this single call works, and\n * the route layer handles the persistence on call-completion. */\nasync function ensureFreshAccessToken(\n creds: ConnectorCredentials,\n clientId: string,\n clientSecret: string,\n): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('google-calendar: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('Google Calendar access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n // Mutate so the caller within this request sees the fresh token; the\n // persisting write happens at the route layer on completion.\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`google-calendar DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","/**\n * Google Sheets connector — live KB source + writable rows.\n *\n * The flagship for the \"agent reads from a live spreadsheet\" UX. The\n * customer points the connection at a Sheet (spreadsheetId + sheetName +\n * headerRow). We expose:\n *\n * list_rows(filter?, limit?)\n * → {rows: [{...header→cell}], nextCursor?}\n * Cheap; just spreadsheets.values.get with the configured range.\n *\n * query_rows(predicate)\n * → same shape as list_rows but with a structured filter (k=v pairs\n * ANDed together). Simple and explainable; no SQL.\n *\n * update_row(rowKey, patch)\n * → {row: {...header→cell}, updatedRange}\n * Mutation. CAS via Sheets' spreadsheets.values.update + a\n * pre-flight read of the row's revisionId-equivalent hash. Sheets\n * doesn't expose a per-row etag, so we synthesize one — see\n * `rowFingerprint`. If the fingerprint doesn't match what the agent\n * last read, we surface ResourceContention with the current row in\n * `currentState`.\n *\n * KB binding: when a Sheet is `consistencyModel: 'cache'` (the default\n * for spreadsheets — they're slow-moving), the system also indexes the\n * rows as KB chunks. The KB build pipeline calls `list_rows` and emits\n * one markdown page per row; on a connector-level \"refresh\" event the\n * agent's KB rebuilds.\n */\n\nimport { createHash } from 'crypto'\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = ['https://www.googleapis.com/auth/spreadsheets']\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth'\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface GoogleSheetsOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function googleSheets(opts: GoogleSheetsOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'google-sheets',\n displayName: 'Google Sheets',\n description:\n \"Bind your agent's knowledge base or pricing/availability lookup to a live Google Sheet. Edit the sheet, and the agent picks up changes — no redeploys.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'GOOGLE_OAUTH_CLIENT_ID',\n clientSecretEnv: 'GOOGLE_OAUTH_CLIENT_SECRET',\n extraAuthParams: { access_type: 'offline', prompt: 'consent', include_granted_scopes: 'true' },\n },\n category: 'spreadsheet',\n defaultConsistencyModel: 'cache',\n // Sheets API caps OAuth-client-wide reads + writes at 300 req/min\n // each (Google's published quotas: \"Read requests per minute per\n // project\" and the matching write bucket). We meter the tighter of\n // the two so neither side exhausts before us.\n rateLimit: { requests: 300, windowMs: 60_000, scope: 'oauth-client' },\n capabilities: [\n {\n name: 'list_rows',\n class: 'read',\n description: 'Return rows from the connected sheet. Each row is keyed by the header cells declared at connect time.',\n parameters: {\n type: 'object',\n properties: {\n limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },\n },\n },\n },\n {\n name: 'query_rows',\n class: 'read',\n description: 'Return rows matching every key=value pair in `predicate` (string equality, case-insensitive).',\n parameters: {\n type: 'object',\n properties: {\n predicate: {\n type: 'object',\n additionalProperties: { type: 'string' },\n },\n limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },\n },\n required: ['predicate'],\n },\n },\n {\n name: 'update_row',\n class: 'mutation',\n description: 'Update a row identified by `rowKey` (the value in the configured key column). Patch is a {column: newValue} map. Returns conflict if the row changed since the agent last read it.',\n cas: 'optimistic-read-verify',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n rowKey: { type: 'string', description: 'Value in the key column identifying the row to update.' },\n patch: {\n type: 'object',\n additionalProperties: { type: 'string' },\n },\n expectedFingerprint: {\n type: 'string',\n description: 'Optional. The fingerprint the agent read on its last list_rows/query_rows call. If supplied and stale, the update is rejected with conflict.',\n },\n },\n required: ['rowKey', 'patch'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const meta = readSheetMeta(inv.source.metadata)\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const rows = await fetchAllRows(accessToken, meta)\n const limit = clampLimit(inv.args.limit, 100)\n let filtered = rows\n if (inv.capabilityName === 'query_rows') {\n const predicate = (inv.args.predicate ?? {}) as Record<string, string>\n filtered = rows.filter(row => matchesPredicate(row, predicate))\n } else if (inv.capabilityName !== 'list_rows') {\n throw new Error(`google-sheets: unknown read ${inv.capabilityName}`)\n }\n const sliced = filtered.slice(0, limit)\n return {\n data: {\n rows: sliced.map(r => ({ ...r.values, _fingerprint: r.fingerprint, _rowIndex: r.rowIndex })),\n total: filtered.length,\n truncated: filtered.length > sliced.length,\n },\n etag: meta.etag, // currently undefined — Sheets values.get doesn't surface etag; row-level fingerprints are the conflict signal\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'update_row') {\n throw new Error(`google-sheets: unknown mutation ${inv.capabilityName}`)\n }\n const meta = readSheetMeta(inv.source.metadata)\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const { rowKey, patch, expectedFingerprint } = inv.args as {\n rowKey: string\n patch: Record<string, string>\n expectedFingerprint?: string\n }\n\n // Pre-flight: read the row, compute fingerprint, compare.\n const rows = await fetchAllRows(accessToken, meta)\n const target = rows.find(r => normalizeKey(r.values[meta.keyColumn]) === normalizeKey(rowKey))\n if (!target) {\n throw new ResourceContention(\n `row with key \"${rowKey}\" not found`,\n [],\n { availableRows: rows.length },\n )\n }\n if (expectedFingerprint && expectedFingerprint !== target.fingerprint) {\n throw new ResourceContention(\n `row \"${rowKey}\" was modified since the agent last read it; re-read and try again`,\n [],\n { current: target.values, currentFingerprint: target.fingerprint },\n )\n }\n\n // Build the new row preserving column order.\n const updatedValues: string[] = meta.headers.map(h =>\n h in patch ? String(patch[h]) : (target.values[h] ?? ''),\n )\n const range = `${meta.sheetName}!A${target.rowIndex + 1}:${columnIndexToLetter(meta.headers.length - 1)}${target.rowIndex + 1}`\n const url = `https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(meta.spreadsheetId)}/values/${encodeURIComponent(range)}?valueInputOption=USER_ENTERED`\n const res = await fetch(url, {\n method: 'PUT',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ values: [updatedValues] }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Google Sheets rejected token (${res.status})`, inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`google-sheets update_row ${res.status}: ${text.slice(0, 200)}`)\n }\n const updatedValuesByHeader = Object.fromEntries(\n meta.headers.map((h, i) => [h, updatedValues[i] ?? '']),\n )\n return {\n status: 'committed',\n data: {\n row: updatedValuesByHeader,\n fingerprint: rowFingerprint(updatedValuesByHeader),\n updatedRange: range,\n },\n etagAfter: rowFingerprint(updatedValuesByHeader),\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n // Operator must select the spreadsheet + range post-connect; we\n // can't infer it during the OAuth handshake.\n metadata: { spreadsheetId: '', sheetName: 'Sheet1', headerRow: 1, keyColumn: '' },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('google-sheets.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n const meta = readSheetMeta(source.metadata)\n if (!meta.spreadsheetId) {\n return { ok: false, reason: 'spreadsheetId not configured — pick a sheet in the connection settings' }\n }\n const url = `https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(meta.spreadsheetId)}?fields=spreadsheetId,properties.title`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403) {\n return { ok: false, reason: `Google rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `Google returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\ninterface SheetMeta {\n spreadsheetId: string\n sheetName: string\n /** 1-indexed header row in the sheet. */\n headerRow: number\n /** Header name that uniquely identifies a row (used by update_row). */\n keyColumn: string\n /** Cached column headers — populated on first fetch. Optional in metadata\n * because we resolve them at fetch time and write back via the route\n * layer when the user pins the connection. */\n headers: string[]\n /** Whatever the upstream surfaces as a top-level revision identifier;\n * if absent we synthesize per-row fingerprints instead. */\n etag?: string\n}\n\nfunction readSheetMeta(meta: Record<string, unknown>): SheetMeta {\n const spreadsheetId = String(meta.spreadsheetId ?? '')\n const sheetName = String(meta.sheetName ?? 'Sheet1')\n const headerRow = Number(meta.headerRow ?? 1)\n const keyColumn = String(meta.keyColumn ?? '')\n const headers = Array.isArray(meta.headers) ? (meta.headers as string[]).map(String) : []\n if (!spreadsheetId || !keyColumn) {\n throw new Error('google-sheets metadata missing spreadsheetId or keyColumn')\n }\n return { spreadsheetId, sheetName, headerRow, keyColumn, headers }\n}\n\ninterface ResolvedRow {\n rowIndex: number // 0-indexed offset from the data start (NOT including header)\n values: Record<string, string>\n fingerprint: string\n}\n\n/** Fetch every row in the configured sheet/range and project to keyed\n * records. We don't paginate — Sheets values.get returns the whole range\n * in one call. For very wide sheets the operator can split the\n * connection into multiple DataSources, each with a narrower range. */\nasync function fetchAllRows(accessToken: string, meta: SheetMeta): Promise<ResolvedRow[]> {\n const range = `${meta.sheetName}`\n const url = `https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(meta.spreadsheetId)}/values/${encodeURIComponent(range)}`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Google Sheets rejected token (${res.status})`, '')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`google-sheets values.get ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as { values?: string[][] }\n const grid = json.values ?? []\n if (grid.length === 0) return []\n const headers = meta.headers.length > 0 ? meta.headers : grid[meta.headerRow - 1] ?? []\n if (headers.length === 0) return []\n const dataRows = grid.slice(meta.headerRow)\n return dataRows.map((rowCells, i) => {\n const values: Record<string, string> = {}\n for (let c = 0; c < headers.length; c++) {\n values[headers[c]] = (rowCells[c] ?? '').toString()\n }\n return {\n // rowIndex is the absolute row in the sheet (1-indexed) where this\n // row's data lives. Header is at meta.headerRow. So this row is at\n // headerRow + i + 1 (1-indexed).\n rowIndex: meta.headerRow + i,\n values,\n fingerprint: rowFingerprint(values),\n }\n })\n}\n\n/** Stable fingerprint of a row's cells. Used as a synthetic etag for\n * optimistic-read-verify CAS. */\nfunction rowFingerprint(values: Record<string, string>): string {\n const keys = Object.keys(values).sort()\n const blob = keys.map(k => `${k}=${values[k]}`).join('\u0001')\n return createHash('sha256').update(blob).digest('hex').slice(0, 16)\n}\n\nfunction matchesPredicate(row: ResolvedRow, predicate: Record<string, string>): boolean {\n for (const [k, v] of Object.entries(predicate)) {\n const cell = row.values[k]\n if (cell === undefined) return false\n if (cell.toLowerCase().trim() !== String(v).toLowerCase().trim()) return false\n }\n return true\n}\n\nfunction normalizeKey(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase()\n}\n\nfunction clampLimit(v: unknown, dflt: number): number {\n const n = typeof v === 'number' ? v : Number(v)\n if (!Number.isFinite(n) || n <= 0) return dflt\n return Math.min(Math.max(1, Math.floor(n)), 500)\n}\n\nfunction columnIndexToLetter(idx: number): string {\n // 0 → A, 25 → Z, 26 → AA, 27 → AB ...\n let n = idx\n let s = ''\n while (n >= 0) {\n s = String.fromCharCode((n % 26) + 65) + s\n n = Math.floor(n / 26) - 1\n }\n return s\n}\n\nasync function ensureFreshAccessToken(creds: ConnectorCredentials, clientId: string, clientSecret: string): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('google-sheets: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('Google Sheets access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n","/**\n * Microsoft Graph Calendar connector — the Outlook half of the\n * voice-agent's \"book me a slot\" surface.\n *\n * Mirrors the Google Calendar pattern almost line-for-line, with two\n * upstream-specific quirks worth calling out:\n *\n * 1. Graph exposes `@odata.etag` on every event resource AND honors\n * `If-Match` on `events.patch` / `events.delete`. So unlike Calendar\n * (insert can't be preconditioned against a non-existent resource),\n * we DO get real etag CAS for updates after the booking. We still\n * use the freebusy pre-flight for the create path, because the\n * \"two callers grab the same slot\" race happens before any event\n * exists.\n *\n * 2. `getSchedule` is the Graph equivalent of `freeBusy.query`. Same\n * shape: send `[start, end]` plus the calendar's email/UPN, get\n * back a `scheduleItems` list of busy windows.\n *\n * Why the same flow ports cleanly: the conflict mode is identical\n * (\"did someone else grab this slot between read and write?\"). The\n * mechanism — pre-flight read + idempotent insert — composes regardless\n * of whether upstream gives us a request-id dedup feature. Graph does\n * not have a `requestId` analogue on `events.create`, so we rely\n * exclusively on MutationGuard's idempotency-key short-circuit ABOVE\n * the connector. That layer prevents duplicate inserts on retry.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = [\n 'https://graph.microsoft.com/Calendars.ReadWrite',\n // offline_access is required to receive a refresh_token from the v2.0\n // endpoint; without it Graph hands back access tokens only and the\n // connection silently dies after ~1 hour.\n 'offline_access',\n]\nconst AUTH_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'\nconst TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface MicrosoftCalendarOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function microsoftCalendar(opts: MicrosoftCalendarOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'microsoft-calendar',\n displayName: 'Microsoft Calendar (Outlook 365)',\n description:\n \"Let your agent check availability and book against an Outlook / Microsoft 365 calendar. Conflict-resolved via Graph's getSchedule pre-flight; etag-guarded on event updates.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'MS_OAUTH_CLIENT_ID',\n clientSecretEnv: 'MS_OAUTH_CLIENT_SECRET',\n // Microsoft v2.0 doesn't need extra params to issue a refresh_token\n // as long as `offline_access` is in scopes (above).\n },\n category: 'calendar',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'list_availability',\n class: 'read',\n description:\n 'Look up busy windows on the connected Outlook calendar between timeMin and timeMax (RFC3339 timestamps).',\n parameters: {\n type: 'object',\n properties: {\n timeMin: { type: 'string', description: 'ISO8601 lower bound (inclusive)' },\n timeMax: { type: 'string', description: 'ISO8601 upper bound (exclusive)' },\n },\n required: ['timeMin', 'timeMax'],\n },\n },\n {\n name: 'book_slot',\n class: 'mutation',\n description:\n 'Reserve a time window on the connected Outlook calendar. Returns conflict + alternatives if the slot is no longer free.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n start: { type: 'string', description: 'ISO8601 start time' },\n end: { type: 'string', description: 'ISO8601 end time' },\n summary: { type: 'string', description: 'Event title (subject)' },\n description: { type: 'string', description: 'Optional event body' },\n attendees: {\n type: 'array',\n items: { type: 'string', description: 'attendee email' },\n },\n },\n required: ['start', 'end', 'summary'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'list_availability') {\n throw new Error(`microsoft-calendar: unknown read capability ${inv.capabilityName}`)\n }\n const userPrincipal = readMetaString(inv.source.metadata, 'userPrincipal')\n const { timeMin, timeMax } = inv.args as { timeMin: string; timeMax: string }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const busy = await getScheduleBusy({ accessToken, userPrincipal, timeMin, timeMax })\n return {\n data: { busy },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'book_slot') {\n throw new Error(`microsoft-calendar: unknown mutation capability ${inv.capabilityName}`)\n }\n const userPrincipal = readMetaString(inv.source.metadata, 'userPrincipal')\n const { start, end, summary, description, attendees } = inv.args as {\n start: string\n end: string\n summary: string\n description?: string\n attendees?: string[]\n }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n\n // Pre-flight: getSchedule for [start, end] on this user.\n const busy = await getScheduleBusy({ accessToken, userPrincipal, timeMin: start, timeMax: end })\n if (busy.length > 0) {\n const startMs = Date.parse(start)\n const endMs = Date.parse(end)\n const durMs = endMs - startMs\n const alternatives = await findNextFreeSlots({\n accessToken,\n userPrincipal,\n searchFromMs: endMs,\n durationMs: durMs,\n wanted: 3,\n })\n throw new ResourceContention(\n `requested slot ${start}–${end} is no longer free`,\n alternatives,\n { busy },\n )\n }\n\n const event = {\n subject: summary,\n body: description ? { contentType: 'text', content: description } : undefined,\n start: { dateTime: start, timeZone: 'UTC' },\n end: { dateTime: end, timeZone: 'UTC' },\n attendees: attendees?.map(email => ({\n emailAddress: { address: email },\n type: 'required',\n })),\n }\n const res = await fetch('https://graph.microsoft.com/v1.0/me/events', {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(event),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Microsoft Graph rejected token (${res.status})`, inv.source.id)\n }\n if (res.status === 412 || res.status === 409) {\n // 412 = If-Match precondition failed (not used on insert but Graph\n // can return it under specific concurrent-update races). 409 covers\n // duplicate resourceId on rare retries.\n throw new ResourceContention(\n `Microsoft Graph reported conflict on book_slot (${res.status})`,\n [],\n )\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`microsoft-calendar book_slot ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; '@odata.etag'?: string; webLink?: string }\n return {\n status: 'committed',\n data: { eventId: created.id, webLink: created.webLink },\n etagAfter: created['@odata.etag'],\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('Microsoft OAuth client not configured (MS_OAUTH_CLIENT_ID / _SECRET)')\n }\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n // Operator picks the shared mailbox / room calendar post-connect.\n // Default to the authenticated user's own primary calendar via 'me'.\n metadata: { userPrincipal: 'me' },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('microsoft-calendar.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n // Cheapest possible Graph call that proves the grant: GET /me.\n const res = await fetch('https://graph.microsoft.com/v1.0/me?$select=id', {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403) {\n return { ok: false, reason: `Microsoft rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `Microsoft Graph returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\ninterface BusyWindow {\n start: string\n end: string\n}\n\n/** Graph's getSchedule returns scheduleItems[].status in {free, busy,\n * tentative, oof, workingElsewhere, unknown}. We treat anything other\n * than 'free' as busy — same conservative reading Outlook uses. */\nasync function getScheduleBusy(input: {\n accessToken: string\n userPrincipal: string\n timeMin: string\n timeMax: string\n}): Promise<BusyWindow[]> {\n // 'me' shorthand only resolves on /me/calendar/getSchedule; if a\n // specific UPN was pinned in metadata we'd have to use the user-id\n // form. /me/calendar/getSchedule with schedules=[upn or 'me'] handles\n // both.\n const target = input.userPrincipal === 'me' ? 'me' : input.userPrincipal\n const url = 'https://graph.microsoft.com/v1.0/me/calendar/getSchedule'\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${input.accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n schedules: [target],\n startTime: { dateTime: input.timeMin, timeZone: 'UTC' },\n endTime: { dateTime: input.timeMax, timeZone: 'UTC' },\n availabilityViewInterval: 30,\n }),\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Microsoft Graph rejected token (${res.status})`, '')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`microsoft-calendar getSchedule ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n value?: Array<{\n scheduleItems?: Array<{\n status?: string\n start?: { dateTime: string }\n end?: { dateTime: string }\n }>\n }>\n }\n const items = json.value?.[0]?.scheduleItems ?? []\n return items\n .filter(it => it.status && it.status !== 'free' && it.start && it.end)\n .map(it => ({ start: it.start!.dateTime, end: it.end!.dateTime }))\n}\n\nasync function findNextFreeSlots(input: {\n accessToken: string\n userPrincipal: string\n searchFromMs: number\n durationMs: number\n wanted: number\n}): Promise<BusyWindow[]> {\n const horizonMs = input.searchFromMs + 14 * 24 * 60 * 60 * 1000\n const out: BusyWindow[] = []\n let cursor = input.searchFromMs\n while (cursor < horizonMs && out.length < input.wanted) {\n const windowEnd = Math.min(cursor + 24 * 60 * 60 * 1000, horizonMs)\n const busy = await getScheduleBusy({\n accessToken: input.accessToken,\n userPrincipal: input.userPrincipal,\n timeMin: new Date(cursor).toISOString(),\n timeMax: new Date(windowEnd).toISOString(),\n })\n const norm = busy\n .map(b => ({ s: Date.parse(b.start), e: Date.parse(b.end) }))\n .filter(b => Number.isFinite(b.s) && Number.isFinite(b.e))\n .sort((a, b) => a.s - b.s)\n let pos = cursor\n for (const b of norm) {\n if (out.length >= input.wanted) break\n if (b.s > pos && b.s - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n pos = Math.max(pos, b.e)\n }\n if (out.length < input.wanted && windowEnd - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n cursor = windowEnd\n }\n return out.slice(0, input.wanted)\n}\n\nasync function ensureFreshAccessToken(creds: ConnectorCredentials, clientId: string, clientSecret: string): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('microsoft-calendar: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('Microsoft Calendar access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`microsoft-calendar DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","/**\n * HubSpot CRM connector — three load-bearing capabilities, picked to\n * cover the voice-agent's CRM hot path without trying to swallow all of\n * HubSpot's surface in v1.\n *\n * find_contact(email)\n * → {contact: {id, properties}} | {found: false}\n * POST /crm/v3/objects/contacts/search with an email-equality filter.\n * Cheap, idempotent, no CAS needed (read).\n *\n * upsert_contact(email, properties)\n * → {contactId, created}\n * Mutation. CAS strategy = native-idempotency, BUT: HubSpot's\n * `idempotencyKey` query param is ONLY available on the v3 *batch*\n * endpoints (`/crm/v3/objects/contacts/batch/upsert`). The\n * single-record endpoints don't honor it. We use the batch endpoint\n * with a single-element array to get native idempotency on retry.\n *\n * create_note(contactId, body)\n * → {noteId}\n * Mutation that logs a note engagement on a contact and associates\n * it. Notes are append-only — there's no conflict to detect — so we\n * use native-idempotency via the same batch trick on\n * `/crm/v3/objects/notes/batch/create`.\n *\n * Why three and not thirty: the agent's leverage on HubSpot is\n * \"remember who I just spoke to\". `find_contact` lets the agent address\n * a returning caller by name; `upsert_contact` captures a new one\n * without duplicates; `create_note` writes the call's outcome as a CRM\n * activity. Anything beyond these (deals, tickets, lists) lives in\n * Tier-2 specific kinds — keeping the manifest tight keeps the agent's\n * tool registry comprehensible.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = [\n 'crm.objects.contacts.read',\n 'crm.objects.contacts.write',\n]\nconst AUTH_URL = 'https://app.hubspot.com/oauth/authorize'\nconst TOKEN_URL = 'https://api.hubapi.com/oauth/v1/token'\nconst API = 'https://api.hubapi.com'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface HubSpotOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function hubspot(opts: HubSpotOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'hubspot',\n displayName: 'HubSpot CRM',\n description:\n \"Look up callers in HubSpot, upsert contacts without duplicates, and log call notes as CRM activities. Three capabilities — the voice-agent's CRM hot path.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'HUBSPOT_OAUTH_CLIENT_ID',\n clientSecretEnv: 'HUBSPOT_OAUTH_CLIENT_SECRET',\n },\n category: 'crm',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'find_contact',\n class: 'read',\n description: 'Search HubSpot contacts by email. Returns the first match or {found:false}.',\n parameters: {\n type: 'object',\n properties: { email: { type: 'string', description: 'Email to search for (case-insensitive).' } },\n required: ['email'],\n },\n },\n {\n name: 'upsert_contact',\n class: 'mutation',\n description:\n 'Create-or-update a contact identified by email. Returns the contact id and a `created` flag indicating whether the row was new.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n email: { type: 'string' },\n properties: {\n type: 'object',\n additionalProperties: { type: 'string' },\n description: 'Property map (firstname, lastname, phone, company, …).',\n },\n },\n required: ['email'],\n },\n },\n {\n name: 'create_note',\n class: 'mutation',\n description:\n 'Log a note engagement against a contact. Append-only — note bodies do not conflict.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n contactId: { type: 'string' },\n body: { type: 'string', description: 'Note body (HTML or plain text).' },\n },\n required: ['contactId', 'body'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'find_contact') {\n throw new Error(`hubspot: unknown read capability ${inv.capabilityName}`)\n }\n const { email } = inv.args as { email: string }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const res = await fetch(`${API}/crm/v3/objects/contacts/search`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n filterGroups: [\n {\n filters: [{ propertyName: 'email', operator: 'EQ', value: email.toLowerCase() }],\n },\n ],\n properties: ['email', 'firstname', 'lastname', 'phone', 'company'],\n limit: 1,\n }),\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired(`HubSpot rejected token (401)`, inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`hubspot find_contact ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n results?: Array<{ id: string; properties: Record<string, string> }>\n }\n const first = json.results?.[0]\n return {\n data: first\n ? { found: true, contact: { id: first.id, properties: first.properties } }\n : { found: false },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n if (inv.capabilityName === 'upsert_contact') {\n return upsertContact(inv, accessToken)\n }\n if (inv.capabilityName === 'create_note') {\n return createNote(inv, accessToken)\n }\n throw new Error(`hubspot: unknown mutation capability ${inv.capabilityName}`)\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('HubSpot OAuth client not configured (HUBSPOT_OAUTH_CLIENT_ID / _SECRET)')\n }\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n metadata: {},\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('hubspot.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n // /oauth/v1/access-tokens/{token} is the cheapest grant-validity probe.\n const res = await fetch(`${API}/oauth/v1/access-tokens/${encodeURIComponent(accessToken)}`, {\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403 || res.status === 404) {\n return { ok: false, reason: `HubSpot rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `HubSpot returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\nasync function upsertContact(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const { email, properties } = inv.args as { email: string; properties?: Record<string, string> }\n const idemKey = sanitizeIdempotencyKey(inv.idempotencyKey)\n // Batch-upsert is the only HubSpot endpoint that honors `idempotencyKey`.\n // See https://developers.hubspot.com/docs/api/crm/contacts batch upsert.\n const url = `${API}/crm/v3/objects/contacts/batch/upsert?idempotencyKey=${encodeURIComponent(idemKey)}`\n const body = {\n inputs: [\n {\n idProperty: 'email',\n id: email.toLowerCase(),\n properties: { email: email.toLowerCase(), ...(properties ?? {}) },\n },\n ],\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired(`HubSpot rejected token (401)`, inv.source.id)\n }\n if (res.status === 409) {\n // HubSpot returns 409 when the upsert targets a record that's been\n // concurrently mutated in a way batch can't reconcile.\n const text = await res.text().catch(() => '')\n throw new ResourceContention(`hubspot upsert_contact conflict: ${text.slice(0, 200)}`)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`hubspot upsert_contact ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n results?: Array<{ id: string; createdAt?: string; updatedAt?: string }>\n status?: string\n }\n const first = json.results?.[0]\n if (!first) {\n throw new Error('hubspot upsert_contact: empty results array')\n }\n const created = first.createdAt && first.updatedAt && first.createdAt === first.updatedAt\n return {\n status: 'committed',\n data: { contactId: first.id, created: Boolean(created) },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nasync function createNote(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const { contactId, body } = inv.args as { contactId: string; body: string }\n const idemKey = sanitizeIdempotencyKey(inv.idempotencyKey)\n const url = `${API}/crm/v3/objects/notes/batch/create?idempotencyKey=${encodeURIComponent(idemKey)}`\n const payload = {\n inputs: [\n {\n properties: {\n hs_note_body: body,\n hs_timestamp: new Date().toISOString(),\n },\n associations: [\n {\n to: { id: contactId },\n // 202 = note→contact association type id (standard HubSpot mapping)\n types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: 202 }],\n },\n ],\n },\n ],\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired(`HubSpot rejected token (401)`, inv.source.id)\n }\n if (res.status === 409) {\n const text = await res.text().catch(() => '')\n throw new ResourceContention(`hubspot create_note conflict: ${text.slice(0, 200)}`)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`hubspot create_note ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as { results?: Array<{ id: string }> }\n const first = json.results?.[0]\n if (!first) {\n throw new Error('hubspot create_note: empty results array')\n }\n return {\n status: 'committed',\n data: { noteId: first.id },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\n/** HubSpot's `idempotencyKey` requires URL-safe ASCII, ≤ 64 chars. */\nfunction sanitizeIdempotencyKey(k: string): string {\n return k.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\nasync function ensureFreshAccessToken(creds: ConnectorCredentials, clientId: string, clientSecret: string): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('hubspot: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('HubSpot access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n","/**\n * Slack connector — bot-token OAuth, three messaging-oriented capabilities.\n *\n * post_message(channel, text|blocks) → mutation; cas: 'none'\n * lookup_user(email) → read\n * list_channels(types?, limit?) → read\n *\n * Why `cas: 'none'` is acceptable here (and only here in this batch):\n * Slack messages are advisory — we set\n * `defaultConsistencyModel: 'advisory'`. The registry validator allows\n * `cas: 'none'` only on non-authoritative connectors precisely so that\n * append-only messaging surfaces don't have to invent fake CAS theatre.\n * The agent's planner already treats `advisory` data as informational\n * and does not promise outcomes based on its post results without\n * a separate authoritative confirm. MutationGuard's idempotency-key\n * dedup remains in force above the connector — a retry of the same\n * post_message call will short-circuit before reaching Slack.\n *\n * Auth: standard OAuth2. Slack's `/oauth.v2.access` returns a bot\n * `access_token` (`xoxb-…`) but does NOT return a refresh_token unless\n * the app has rotated tokens enabled. Bot tokens are long-lived by\n * default; we surface refreshToken handling but treat its absence as\n * normal rather than an error.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = ['chat:write', 'users:read', 'users:read.email', 'channels:read']\nconst AUTH_URL = 'https://slack.com/oauth/v2/authorize'\nconst TOKEN_URL = 'https://slack.com/api/oauth.v2.access'\nconst API = 'https://slack.com/api'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface SlackOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function slack(opts: SlackOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n // The inbound Events API receiver registers kind `slack-inbound`\n // (hmac signing-secret auth). This connector — kind `slack` —\n // carries the OAuth bot-token outbound surface. Two kinds, one\n // logical product, deliberately split because the credential shapes\n // are different (HMAC secret vs bot OAuth) and operators commonly\n // wire one without the other.\n kind: 'slack',\n displayName: 'Slack',\n description:\n \"Post messages from the agent into Slack, look up users by email, and list channels. Advisory surface — Slack posts are informational, not transactional.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'SLACK_OAUTH_CLIENT_ID',\n clientSecretEnv: 'SLACK_OAUTH_CLIENT_SECRET',\n },\n category: 'comms',\n defaultConsistencyModel: 'advisory',\n capabilities: [\n {\n name: 'post_message',\n class: 'mutation',\n description: 'Post a message from the bot to a channel or user DM. Append-only — no CAS.',\n cas: 'none',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n channel: { type: 'string', description: 'Channel id (C…) or user id (U…) for DM.' },\n text: { type: 'string' },\n blocks: { type: 'array', description: 'Optional Slack Block Kit blocks.' },\n },\n required: ['channel'],\n },\n },\n {\n name: 'lookup_user',\n class: 'read',\n description: 'Look up a Slack workspace user by email.',\n parameters: {\n type: 'object',\n properties: { email: { type: 'string' } },\n required: ['email'],\n },\n },\n {\n name: 'list_channels',\n class: 'read',\n description: 'List channels visible to the bot. `types` defaults to public_channel,private_channel.',\n parameters: {\n type: 'object',\n properties: {\n types: { type: 'string', description: 'Comma-separated channel types.' },\n limit: { type: 'integer', minimum: 1, maximum: 1000, default: 200 },\n },\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const accessToken = readBotToken(inv.source.credentials)\n if (inv.capabilityName === 'lookup_user') {\n const { email } = inv.args as { email: string }\n const url = `${API}/users.lookupByEmail?email=${encodeURIComponent(email)}`\n const json = await slackGet(url, accessToken, inv.source.id)\n if (!json.ok) {\n if (json.error === 'users_not_found') {\n return { data: { found: false }, fetchedAt: Date.now() }\n }\n throw new Error(`slack lookup_user: ${json.error ?? 'unknown'}`)\n }\n const u = json.user as { id: string; name?: string; real_name?: string; profile?: unknown } | undefined\n return {\n data: { found: true, user: u ? { id: u.id, name: u.name, realName: u.real_name } : null },\n fetchedAt: Date.now(),\n }\n }\n if (inv.capabilityName === 'list_channels') {\n const { types, limit } = inv.args as { types?: string; limit?: number }\n const params = new URLSearchParams({\n limit: String(Math.min(Math.max(1, limit ?? 200), 1000)),\n types: types ?? 'public_channel,private_channel',\n })\n const json = await slackGet(`${API}/conversations.list?${params.toString()}`, accessToken, inv.source.id)\n if (!json.ok) {\n throw new Error(`slack list_channels: ${json.error ?? 'unknown'}`)\n }\n const channels = (json.channels as Array<{ id: string; name: string; is_private?: boolean }>) ?? []\n return {\n data: { channels: channels.map(c => ({ id: c.id, name: c.name, isPrivate: c.is_private ?? false })) },\n fetchedAt: Date.now(),\n }\n }\n throw new Error(`slack: unknown read capability ${inv.capabilityName}`)\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'post_message') {\n throw new Error(`slack: unknown mutation capability ${inv.capabilityName}`)\n }\n const accessToken = readBotToken(inv.source.credentials)\n const { channel, text, blocks } = inv.args as {\n channel: string\n text?: string\n blocks?: unknown[]\n }\n const res = await fetch(`${API}/chat.postMessage`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json; charset=utf-8',\n },\n body: JSON.stringify({ channel, text, blocks }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Slack rejected token (401)', inv.source.id)\n }\n if (!res.ok) {\n const t = await res.text().catch(() => '')\n throw new Error(`slack post_message HTTP ${res.status}: ${t.slice(0, 200)}`)\n }\n // Slack returns 200 with `ok:false` on logical errors. Map common\n // auth/scope failures back to CredentialsExpired so the UI can prompt\n // a reconnect.\n const json = (await res.json()) as {\n ok?: boolean\n error?: string\n ts?: string\n channel?: string\n }\n if (!json.ok) {\n if (\n json.error === 'invalid_auth' ||\n json.error === 'token_expired' ||\n json.error === 'not_authed' ||\n json.error === 'token_revoked'\n ) {\n throw new CredentialsExpired(`Slack rejected token: ${json.error}`, inv.source.id)\n }\n throw new Error(`slack post_message: ${json.error ?? 'unknown'}`)\n }\n return {\n status: 'committed',\n data: { ts: json.ts, channel: json.channel },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('Slack OAuth client not configured (SLACK_OAUTH_CLIENT_ID / _SECRET)')\n }\n // Slack's oauth.v2.access response is non-standard: the bot token\n // lives at `access_token` inside the top-level response (NOT nested\n // — that's the v1 quirk). We use exchangeAuthorizationCode for the\n // POST mechanics, then re-tag the result.\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/[,\\s]+/) ?? SCOPES,\n metadata: {},\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n // Slack bot tokens are long-lived without rotation; absence of\n // refresh_token is normal. Return creds unchanged so the caller\n // doesn't trigger a reconnect prematurely.\n return creds\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = readBotToken(source.credentials)\n const res = await fetch(`${API}/auth.test`, {\n method: 'POST',\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (!res.ok) return { ok: false, reason: `Slack returned ${res.status}` }\n const json = (await res.json()) as { ok?: boolean; error?: string }\n if (!json.ok) {\n return { ok: false, reason: `Slack auth.test: ${json.error ?? 'unknown'} — reconnect required` }\n }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\nfunction readBotToken(creds: ConnectorCredentials): string {\n if (creds.kind !== 'oauth2' || typeof creds.accessToken !== 'string') {\n throw new Error('slack: expected oauth2 credentials')\n }\n return creds.accessToken\n}\n\ninterface SlackJsonResponse {\n ok?: boolean\n error?: string\n [k: string]: unknown\n}\n\nasync function slackGet(url: string, accessToken: string, dataSourceId: string): Promise<SlackJsonResponse> {\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Slack rejected token (401)', dataSourceId)\n }\n if (!res.ok) {\n const t = await res.text().catch(() => '')\n throw new Error(`slack HTTP ${res.status}: ${t.slice(0, 200)}`)\n }\n return (await res.json()) as SlackJsonResponse\n}\n","/**\n * Notion database connector — query + page-level CRUD against a single\n * connected database.\n *\n * query_database(filter?, pageSize?) → read\n * create_page(properties) → mutation; cas: 'native-idempotency'\n * update_page(pageId, properties) → mutation; cas: 'etag-if-match'\n *\n * CAS quirks worth flagging:\n *\n * 1. Notion added support for the `Idempotency-Key` HTTP header on\n * mutating requests. We forward our SDK's idempotency key on\n * create_page, which gives at-most-once semantics under the same\n * key for ~24h. MutationGuard's record short-circuits above us;\n * Notion's dedup is the second line of defense.\n *\n * 2. Notion does NOT expose a per-page etag the way Graph does. The\n * canonical drift signal is `last_edited_time` (RFC3339). Our\n * `update_page` capability accepts an `expectedLastEditedTime` arg;\n * if supplied, we GET the page first and compare. Mismatch →\n * ResourceContention with the current page state. Conflict-free\n * callers can omit the field (last-write-wins, the Notion default).\n *\n * Auth: standard OAuth2. Notion's token endpoint follows RFC 6749 with\n * one twist — the workspace_id and bot_id come back in the response and\n * we stash them in `metadata` so the agent can address resources by\n * workspace where useful.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst AUTH_URL = 'https://api.notion.com/v1/oauth/authorize'\nconst TOKEN_URL = 'https://api.notion.com/v1/oauth/token'\nconst API = 'https://api.notion.com/v1'\nconst NOTION_VERSION = '2022-06-28'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface NotionDatabaseOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function notionDatabase(opts: NotionDatabaseOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'notion-database',\n displayName: 'Notion (database)',\n description:\n \"Query a Notion database, create new pages, and update existing ones with optimistic concurrency via last_edited_time.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n // Notion does not use OAuth scopes — the workspace owner picks\n // which pages/databases the integration sees during install. We\n // declare an empty scope list so the consent screen renders cleanly.\n scopes: [],\n clientIdEnv: 'NOTION_OAUTH_CLIENT_ID',\n clientSecretEnv: 'NOTION_OAUTH_CLIENT_SECRET',\n extraAuthParams: { owner: 'user' },\n },\n category: 'doc',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'query_database',\n class: 'read',\n description: 'Query the connected Notion database with an optional filter object (Notion query DSL).',\n parameters: {\n type: 'object',\n properties: {\n filter: { type: 'object', description: 'Notion API filter object — passed through verbatim.' },\n pageSize: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n startCursor: { type: 'string' },\n },\n },\n },\n {\n name: 'create_page',\n class: 'mutation',\n description: 'Create a new page inside the connected database.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n properties: {\n type: 'object',\n description: 'Notion property map keyed by property name.',\n },\n },\n required: ['properties'],\n },\n },\n {\n name: 'update_page',\n class: 'mutation',\n description:\n 'Update properties on an existing page. If `expectedLastEditedTime` is supplied and stale, the update is rejected with conflict.',\n cas: 'etag-if-match',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n pageId: { type: 'string' },\n properties: { type: 'object' },\n expectedLastEditedTime: {\n type: 'string',\n description: 'RFC3339 timestamp the agent observed on its last read. Drift triggers ResourceContention.',\n },\n },\n required: ['pageId', 'properties'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'query_database') {\n throw new Error(`notion-database: unknown read capability ${inv.capabilityName}`)\n }\n const accessToken = readToken(inv.source.credentials)\n const databaseId = readMetaString(inv.source.metadata, 'databaseId')\n const { filter, pageSize, startCursor } = inv.args as {\n filter?: unknown\n pageSize?: number\n startCursor?: string\n }\n const body: Record<string, unknown> = {\n page_size: Math.min(Math.max(1, pageSize ?? 50), 100),\n }\n if (filter) body.filter = filter\n if (startCursor) body.start_cursor = startCursor\n\n const res = await fetch(`${API}/databases/${encodeURIComponent(databaseId)}/query`, {\n method: 'POST',\n headers: notionHeaders(accessToken),\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`notion-database query_database ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n results?: Array<{ id: string; last_edited_time: string; properties: unknown; url?: string }>\n has_more?: boolean\n next_cursor?: string | null\n }\n return {\n data: {\n results: json.results ?? [],\n hasMore: json.has_more ?? false,\n nextCursor: json.next_cursor ?? null,\n },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const accessToken = readToken(inv.source.credentials)\n if (inv.capabilityName === 'create_page') return createPage(inv, accessToken)\n if (inv.capabilityName === 'update_page') return updatePage(inv, accessToken)\n throw new Error(`notion-database: unknown mutation capability ${inv.capabilityName}`)\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('Notion OAuth client not configured (NOTION_OAUTH_CLIENT_ID / _SECRET)')\n }\n // Notion REQUIRES Basic auth on the token endpoint and does not\n // accept client_id/client_secret in the form body. exchangeAuthorizationCode\n // posts both in the body; Notion ignores the duplicates and accepts\n // the Basic header — but we have to add the header explicitly.\n // We do the POST inline rather than extending the helper's\n // signature, since this is the one upstream that needs Basic.\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code: input.code,\n redirect_uri: input.redirectUri,\n code_verifier: input.codeVerifier,\n })\n const res = await fetch(TOKEN_URL, {\n method: 'POST',\n headers: {\n authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n 'Notion-Version': NOTION_VERSION,\n },\n body,\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`Notion OAuth token exchange failed: ${res.status} — ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n access_token: string\n refresh_token?: string\n bot_id?: string\n workspace_id?: string\n workspace_name?: string\n duplicated_template_id?: string\n }\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: json.access_token,\n refreshToken: json.refresh_token,\n },\n scopes: [],\n metadata: {\n botId: json.bot_id,\n workspaceId: json.workspace_id,\n workspaceName: json.workspace_name,\n // Operator picks the database in a follow-up step; default empty.\n databaseId: '',\n },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n // Notion's standard tokens don't expire and don't ship a\n // refresh_token. If we have neither expiresAt nor refreshToken,\n // treat the existing access token as durable.\n if (creds.kind === 'oauth2' && creds.accessToken && !creds.expiresAt) {\n return creds\n }\n throw new Error('notion-database.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = readToken(source.credentials)\n // /users/me is the cheapest grant-validity probe.\n const res = await fetch(`${API}/users/me`, {\n headers: notionHeaders(accessToken),\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401) return { ok: false, reason: 'Notion rejected token (401) — reconnect required' }\n if (!res.ok) return { ok: false, reason: `Notion returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\nasync function createPage(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const databaseId = readMetaString(inv.source.metadata, 'databaseId')\n const { properties } = inv.args as { properties: Record<string, unknown> }\n const res = await fetch(`${API}/pages`, {\n method: 'POST',\n headers: {\n ...notionHeaders(accessToken),\n 'Idempotency-Key': inv.idempotencyKey,\n },\n body: JSON.stringify({\n parent: { database_id: databaseId },\n properties,\n }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (res.status === 409) {\n throw new ResourceContention('Notion idempotency-key conflict — different args under same key')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`notion-database create_page ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; url?: string; last_edited_time?: string }\n return {\n status: 'committed',\n data: { pageId: created.id, url: created.url, lastEditedTime: created.last_edited_time },\n etagAfter: created.last_edited_time,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nasync function updatePage(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const { pageId, properties, expectedLastEditedTime } = inv.args as {\n pageId: string\n properties: Record<string, unknown>\n expectedLastEditedTime?: string\n }\n // Optional pre-flight CAS: if the agent supplied the timestamp it\n // observed on its last read, fetch the page and compare BEFORE\n // committing. The window between this read and the patch isn't\n // closed by Notion (no If-Match), but it shrinks the race to\n // milliseconds — sufficient for typical voice-agent cadences.\n if (expectedLastEditedTime) {\n const headRes = await fetch(`${API}/pages/${encodeURIComponent(pageId)}`, {\n headers: notionHeaders(accessToken),\n signal: AbortSignal.timeout(10_000),\n })\n if (headRes.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (!headRes.ok) {\n const text = await headRes.text().catch(() => '')\n throw new Error(`notion-database update_page (preflight) ${headRes.status}: ${text.slice(0, 200)}`)\n }\n const page = (await headRes.json()) as { last_edited_time?: string; properties?: unknown }\n if (page.last_edited_time && page.last_edited_time !== expectedLastEditedTime) {\n throw new ResourceContention(\n `Notion page ${pageId} was modified since the agent last read it`,\n [],\n { last_edited_time: page.last_edited_time, properties: page.properties },\n )\n }\n }\n\n const res = await fetch(`${API}/pages/${encodeURIComponent(pageId)}`, {\n method: 'PATCH',\n headers: notionHeaders(accessToken),\n body: JSON.stringify({ properties }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (res.status === 409 || res.status === 412) {\n throw new ResourceContention(`Notion update_page conflict (${res.status})`)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`notion-database update_page ${res.status}: ${text.slice(0, 200)}`)\n }\n const updated = (await res.json()) as { id: string; last_edited_time?: string; url?: string }\n return {\n status: 'committed',\n data: { pageId: updated.id, url: updated.url, lastEditedTime: updated.last_edited_time },\n etagAfter: updated.last_edited_time,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nfunction notionHeaders(accessToken: string): Record<string, string> {\n return {\n authorization: `Bearer ${accessToken}`,\n 'Notion-Version': NOTION_VERSION,\n 'content-type': 'application/json',\n }\n}\n\nfunction readToken(creds: ConnectorCredentials): string {\n if (creds.kind !== 'oauth2' || typeof creds.accessToken !== 'string') {\n throw new Error('notion-database: expected oauth2 credentials')\n }\n return creds.accessToken\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`notion-database DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","import {\n type Capability,\n type CapabilityMutationResult,\n type CapabilityReadResult,\n type ConnectorAdapter,\n type ConnectorCredentials,\n type ConnectorInvocation,\n CredentialsExpired,\n} from '../types.js'\n\nexport type RestCredentialPlacement =\n | { kind: 'bearer' }\n | { kind: 'header'; header: string; prefix?: string }\n | { kind: 'query'; parameter: string }\n\nexport interface RestConnectorSpec {\n kind: string\n displayName: string\n description: string\n auth: ConnectorAdapter['manifest']['auth']\n category: ConnectorAdapter['manifest']['category']\n defaultConsistencyModel: ConnectorAdapter['manifest']['defaultConsistencyModel']\n baseUrl: string | { metadataKey: string; fallback?: string }\n credentialPlacement?: RestCredentialPlacement\n defaultHeaders?: Record<string, string>\n capabilities: RestOperationSpec[]\n test?: RestRequestSpec\n}\n\nexport interface RestOperationSpec {\n name: string\n class: 'read' | 'mutation'\n description: string\n parameters: Record<string, unknown>\n requiredScopes?: string[]\n request: RestRequestSpec\n cas?: 'etag-if-match' | 'native-idempotency' | 'optimistic-read-verify' | 'none'\n externalEffect?: boolean\n}\n\nexport interface RestRequestSpec {\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?: 'args' | string | Record<string, unknown>\n}\n\nexport function declarativeRestConnector(spec: RestConnectorSpec): ConnectorAdapter {\n const capabilities = spec.capabilities.map(operationToCapability)\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: spec.kind,\n displayName: spec.displayName,\n description: spec.description,\n auth: spec.auth,\n category: spec.category,\n defaultConsistencyModel: spec.defaultConsistencyModel,\n capabilities,\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const op = readOperation(spec, inv.capabilityName, 'read')\n const response = await executeRestRequest(spec, op.request, inv)\n return {\n data: response.data,\n etag: response.etag,\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const op = readOperation(spec, inv.capabilityName, 'mutation')\n const response = await executeRestRequest(spec, op.request, inv)\n return {\n status: 'committed',\n data: response.data,\n etagAfter: response.etag,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async test(source) {\n if (!spec.test) return { ok: true }\n try {\n await executeRestRequest(spec, spec.test, {\n source,\n capabilityName: '__test__',\n args: {},\n idempotencyKey: 'test',\n })\n return { ok: true }\n } catch (error) {\n return { ok: false, reason: error instanceof Error ? error.message : 'unknown error' }\n }\n },\n }\n return adapter\n}\n\nfunction operationToCapability(op: RestOperationSpec): Capability {\n const base = {\n name: op.name,\n description: op.description,\n parameters: op.parameters,\n requiredScopes: op.requiredScopes,\n }\n if (op.class === 'read') {\n return { ...base, class: 'read' }\n }\n return {\n ...base,\n class: 'mutation',\n cas: op.cas ?? 'native-idempotency',\n externalEffect: op.externalEffect ?? true,\n }\n}\n\nfunction readOperation(spec: RestConnectorSpec, name: string, expected: 'read' | 'mutation'): RestOperationSpec {\n const op = spec.capabilities.find((candidate) => candidate.name === name)\n if (!op || op.class !== expected) {\n throw new Error(`${spec.kind}: unknown ${expected} capability ${name}`)\n }\n return op\n}\n\nasync function executeRestRequest(\n spec: RestConnectorSpec,\n request: RestRequestSpec,\n inv: ConnectorInvocation,\n): Promise<{ data: unknown; etag?: string }> {\n const baseUrl = resolveBaseUrl(spec.baseUrl, inv.source.metadata)\n const url = new URL(interpolate(request.path, inv.args), baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`)\n for (const [key, value] of Object.entries(request.query ?? {})) {\n const rendered = renderQueryValue(value, inv.args)\n if (rendered !== undefined && rendered !== '') url.searchParams.set(key, String(rendered))\n }\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...spec.defaultHeaders,\n ...renderHeaders(request.headers ?? {}, inv.args),\n }\n applyCredentials(headers, url, spec.credentialPlacement ?? { kind: 'bearer' }, inv.source.credentials)\n if (inv.expectedEtag) headers['if-match'] = inv.expectedEtag\n if (request.method !== 'GET' && request.method !== 'DELETE') {\n headers['content-type'] = headers['content-type'] ?? 'application/json'\n }\n const res = await fetch(url, {\n method: request.method,\n headers,\n body: request.method === 'GET' || request.method === 'DELETE' ? undefined : JSON.stringify(resolveBody(request.body, inv.args)),\n signal: AbortSignal.timeout(20_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`${spec.displayName} rejected credentials (${res.status})`, inv.source.id)\n }\n if (res.status === 409 || res.status === 412) {\n return {\n data: {\n status: 'conflict',\n message: await safeErrorText(res),\n },\n etag: res.headers.get('etag') ?? undefined,\n }\n }\n if (res.status === 429) {\n return {\n data: {\n status: 'rate-limited',\n retryAfter: res.headers.get('retry-after') ?? undefined,\n message: await safeErrorText(res),\n },\n }\n }\n if (!res.ok) {\n throw new Error(`${spec.kind} ${request.method} ${url.pathname} HTTP ${res.status}: ${(await safeErrorText(res)).slice(0, 300)}`)\n }\n const text = await res.text()\n const data = text ? JSON.parse(text) as unknown : null\n return { data, etag: res.headers.get('etag') ?? undefined }\n}\n\nfunction resolveBaseUrl(baseUrl: RestConnectorSpec['baseUrl'], metadata: Record<string, unknown>): string {\n if (typeof baseUrl === 'string') return baseUrl\n const value = metadata[baseUrl.metadataKey]\n if (typeof value === 'string' && value.trim()) return value\n if (baseUrl.fallback) return baseUrl.fallback\n throw new Error(`missing metadata.${baseUrl.metadataKey} base URL`)\n}\n\nfunction applyCredentials(\n headers: Record<string, string>,\n url: URL,\n placement: RestCredentialPlacement,\n credentials: ConnectorCredentials,\n): void {\n const token = credentialToken(credentials)\n if (placement.kind === 'bearer') headers.authorization = `Bearer ${token}`\n if (placement.kind === 'header') headers[placement.header] = `${placement.prefix ?? ''}${token}`\n if (placement.kind === 'query') url.searchParams.set(placement.parameter, token)\n}\n\nfunction credentialToken(credentials: ConnectorCredentials): string {\n if (credentials.kind === 'oauth2') return credentials.accessToken\n if (credentials.kind === 'api-key') return credentials.apiKey\n throw new Error(`declarative REST connectors require oauth2 or api-key credentials, got ${credentials.kind}`)\n}\n\nfunction resolveBody(body: RestRequestSpec['body'], args: Record<string, unknown>): unknown {\n if (!body || body === 'args') return args\n if (typeof body === 'string') return renderValue(body, args)\n return renderObject(body, args)\n}\n\nfunction renderHeaders(headers: Record<string, string>, args: Record<string, unknown>): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, interpolate(value, args)]))\n}\n\nfunction renderObject(input: Record<string, unknown>, args: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, renderValue(value, args)]))\n}\n\nfunction renderValue(value: unknown, args: Record<string, unknown>): unknown {\n if (typeof value === 'string') {\n const exact = value.match(/^\\{([a-zA-Z0-9_.-]+)\\}$/)\n if (exact) return readRequiredPath(args, exact[1])\n return interpolate(value, args)\n }\n return value\n}\n\nfunction renderQueryValue(value: unknown, args: Record<string, unknown>): unknown {\n if (typeof value !== 'string') return value\n const exact = value.match(/^\\{([a-zA-Z0-9_.-]+)\\}$/)\n if (exact) return readPath(args, exact[1])\n try {\n return interpolate(value, args)\n } catch {\n return undefined\n }\n}\n\nfunction interpolate(template: string, args: Record<string, unknown>): string {\n return template.replace(/\\{([a-zA-Z0-9_.-]+)\\}/g, (_match, key: string) => {\n const value = readPath(args, key)\n if (value === undefined || value === null) {\n throw new Error(`missing required argument: ${key}`)\n }\n return encodeURIComponent(String(value))\n })\n}\n\nfunction readRequiredPath(input: Record<string, unknown>, path: string): unknown {\n const value = readPath(input, path)\n if (value === undefined || value === null) throw new Error(`missing required argument: ${path}`)\n return value\n}\n\nfunction readPath(input: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce<unknown>((value, part) => {\n if (value && typeof value === 'object' && part in value) {\n return (value as Record<string, unknown>)[part]\n }\n return undefined\n }, input)\n}\n\nasync function safeErrorText(res: Response): Promise<string> {\n return (await res.text().catch(() => res.statusText)) || res.statusText\n}\n","/**\n * Twilio SMS connector — outbound texts + recent-message lookup. The\n * agent's \"send the caller a confirmation link\" surface.\n *\n * Auth: HTTP Basic (Account SID + Auth Token). Twilio's API key auth\n * also supports SID/Secret pairs; we accept either by treating the\n * stored apiKey envelope as `accountSid:authToken` (or\n * `accountSid:keySid:secret`) — the connector parses it at call time.\n *\n * send_sms(to, body)\n * Mutation. CAS = native-idempotency. Twilio added the\n * `Idempotency-Key` HTTP header to POST /Messages in 2024 — same\n * key + same args within 24h returns the original Message resource\n * instead of sending a second SMS. MutationGuard's record short-\n * circuits before us; Twilio's own dedup is defense-in-depth.\n *\n * lookup_number(phoneNumber)\n * Read. Hits /v1/PhoneNumbers/{e164} on Lookup API. Confirms the\n * number is real, returns carrier info if the caller has Lookup\n * enabled on their account.\n *\n * find_recent_messages(toOrFrom?, limit?)\n * Read. Returns the most recent Messages on the account, optionally\n * filtered by To/From. Useful for \"did the confirmation actually\n * send?\" introspection inside an agent run.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\n\nconst API = 'https://api.twilio.com/2010-04-01'\nconst LOOKUP_API = 'https://lookups.twilio.com/v1'\n\nexport const twilioSmsConnector: ConnectorAdapter = {\n manifest: {\n kind: 'twilio-sms',\n displayName: 'Twilio SMS',\n description:\n \"Send outbound SMS, look up phone numbers, and audit recent messages. Twilio's native Idempotency-Key prevents duplicate sends on retry.\",\n auth: {\n kind: 'api-key',\n hint: 'Paste your Twilio credentials as \"AccountSid:AuthToken\" (e.g. \"AC123…:abc…\"). API-key style \"AccountSid:KeySid:Secret\" is also accepted.',\n },\n category: 'comms',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'send_sms',\n class: 'mutation',\n description: 'Send an SMS from the configured Twilio number to the supplied destination.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n to: { type: 'string', description: 'E.164 destination, e.g. +14155551212' },\n body: { type: 'string', description: 'Message body (≤1600 chars after Twilio segments).' },\n from: { type: 'string', description: 'Optional E.164 sender; falls back to metadata.fromNumber.' },\n },\n required: ['to', 'body'],\n },\n },\n {\n name: 'lookup_number',\n class: 'read',\n description: 'Validate a phone number and (if your account has Lookup) retrieve carrier metadata.',\n parameters: {\n type: 'object',\n properties: {\n phoneNumber: { type: 'string', description: 'E.164 number to look up.' },\n includeCarrier: { type: 'boolean', default: false },\n },\n required: ['phoneNumber'],\n },\n },\n {\n name: 'find_recent_messages',\n class: 'read',\n description: 'Return up to `limit` recent Messages on the account, optionally filtered by To or From.',\n parameters: {\n type: 'object',\n properties: {\n to: { type: 'string', description: 'Optional E.164 filter on the To address.' },\n from: { type: 'string', description: 'Optional E.164 filter on the From address.' },\n limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },\n },\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const auth = parseAuth(inv.source.credentials)\n if (inv.capabilityName === 'lookup_number') {\n const { phoneNumber, includeCarrier } = inv.args as { phoneNumber: string; includeCarrier?: boolean }\n const url = `${LOOKUP_API}/PhoneNumbers/${encodeURIComponent(phoneNumber)}${includeCarrier ? '?Type=carrier' : ''}`\n const res = await fetch(url, {\n headers: { authorization: basicAuth(auth) },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Twilio rejected credentials (401)', inv.source.id)\n if (res.status === 404) {\n return { data: { valid: false }, fetchedAt: Date.now() }\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`twilio-sms lookup_number ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as { phone_number?: string; carrier?: unknown; country_code?: string }\n return {\n data: {\n valid: true,\n phoneNumber: json.phone_number,\n countryCode: json.country_code,\n carrier: json.carrier,\n },\n fetchedAt: Date.now(),\n }\n }\n if (inv.capabilityName === 'find_recent_messages') {\n const { to, from, limit } = inv.args as { to?: string; from?: string; limit?: number }\n const params = new URLSearchParams()\n params.set('PageSize', String(Math.min(Math.max(1, limit ?? 20), 100)))\n if (to) params.set('To', to)\n if (from) params.set('From', from)\n const url = `${API}/Accounts/${encodeURIComponent(auth.accountSid)}/Messages.json?${params.toString()}`\n const res = await fetch(url, {\n headers: { authorization: basicAuth(auth) },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Twilio rejected credentials (401)', inv.source.id)\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`twilio-sms find_recent_messages ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n messages?: Array<{ sid: string; to: string; from: string; body: string; status: string; date_sent?: string }>\n }\n return {\n data: { messages: json.messages ?? [] },\n fetchedAt: Date.now(),\n }\n }\n throw new Error(`twilio-sms: unknown read capability ${inv.capabilityName}`)\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'send_sms') {\n throw new Error(`twilio-sms: unknown mutation capability ${inv.capabilityName}`)\n }\n const auth = parseAuth(inv.source.credentials)\n const { to, body, from } = inv.args as { to: string; body: string; from?: string }\n const fromNumber = from ?? readMetaString(inv.source.metadata, 'fromNumber')\n const formBody = new URLSearchParams({ To: to, From: fromNumber, Body: body })\n const url = `${API}/Accounts/${encodeURIComponent(auth.accountSid)}/Messages.json`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: basicAuth(auth),\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': inv.idempotencyKey,\n },\n body: formBody,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Twilio rejected credentials (401)', inv.source.id)\n if (res.status === 409) {\n // Twilio surfaces 409 when an idempotency-key conflict is detected\n // (same key, different request body).\n throw new ResourceContention('Twilio idempotency-key conflict — different args under same key')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`twilio-sms send_sms ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as {\n sid: string\n status: string\n to: string\n from: string\n date_sent?: string\n }\n return {\n status: 'committed',\n data: { messageSid: created.sid, deliveryStatus: created.status, to: created.to, from: created.from },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async test(source) {\n try {\n const auth = parseAuth(source.credentials)\n // GET /Accounts/{sid}.json is the cheapest auth probe.\n const res = await fetch(`${API}/Accounts/${encodeURIComponent(auth.accountSid)}.json`, {\n headers: { authorization: basicAuth(auth) },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401) return { ok: false, reason: 'Twilio rejected credentials (401) — reconnect required' }\n if (!res.ok) return { ok: false, reason: `Twilio returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n}\n\ninterface TwilioAuth {\n accountSid: string\n /** Either the Account auth token, or an API key SID. */\n username: string\n /** Either the same auth token, or the API key secret. */\n password: string\n}\n\nfunction parseAuth(creds: { kind: string; apiKey?: string }): TwilioAuth {\n if (creds.kind !== 'api-key' || typeof creds.apiKey !== 'string') {\n throw new Error('twilio-sms: expected api-key credentials')\n }\n const parts = creds.apiKey.split(':')\n if (parts.length === 2) {\n // accountSid:authToken — username is the SID, password is the token.\n const [accountSid, authToken] = parts\n if (!accountSid.startsWith('AC')) {\n throw new Error('twilio-sms: AccountSid must start with \"AC\"')\n }\n return { accountSid, username: accountSid, password: authToken }\n }\n if (parts.length === 3) {\n // accountSid:apiKeySid:apiKeySecret — basic-auth username is the\n // API key SID, not the AccountSid.\n const [accountSid, keySid, secret] = parts\n if (!accountSid.startsWith('AC')) {\n throw new Error('twilio-sms: AccountSid must start with \"AC\"')\n }\n return { accountSid, username: keySid, password: secret }\n }\n throw new Error('twilio-sms: apiKey must be \"AccountSid:AuthToken\" or \"AccountSid:KeySid:Secret\"')\n}\n\nfunction basicAuth(auth: TwilioAuth): string {\n return `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString('base64')}`\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`twilio-sms DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","/**\n * Stripe pack connector — single connector kind packing 3 capabilities,\n * validating the \"connector pack\" concept (one auth handshake, multiple\n * related capabilities) without exploding the registry into\n * `stripe-customers`, `stripe-checkout`, `stripe-invoices` triplets.\n *\n * find_customer(email) → read; CAS n/a\n * create_invoice(customerId, items) → mutation; cas: 'native-idempotency'\n * create_checkout_session(...) → mutation; cas: 'native-idempotency'\n *\n * Auth: API key (Stripe restricted key). Operator pastes the key into\n * the Connections UI. We never see their account password / OAuth flow;\n * Stripe restricted keys are the customer's responsibility (they pick\n * which permissions the key carries). The kind exposes a webhook URL\n * post-connect for the operator to paste into the Stripe dashboard —\n * we'll wire the receiver to P-3's inbound webhook surface in a later\n * commit. That URL is returned in `metadata.webhookUrl` so the UI can\n * render it.\n *\n * Why this is the textbook example of `cas: 'native-idempotency'`:\n * Stripe's `Idempotency-Key` HTTP header is THE reference implementation\n * of native idempotency. Same key + same args within 24h returns the\n * stored response (Stripe's words, not ours). Same key + different args\n * → 400 with `idempotency_error`. We forward the SDK's idempotency key\n * directly. MutationGuard short-circuits before us on retry; Stripe's\n * own dedup is the second line of defense.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\n\nconst API = 'https://api.stripe.com/v1'\n\nexport const stripePackConnector: ConnectorAdapter = {\n manifest: {\n kind: 'stripe-pack',\n displayName: 'Stripe (customers, invoices, checkout)',\n description:\n \"Look up Stripe customers, draft invoices, and spin up hosted Checkout sessions from a single Stripe restricted key. Idempotency-Key forwarded on every mutation.\",\n auth: {\n kind: 'api-key',\n hint: 'Paste a Stripe restricted key (rk_live_…) with read access on customers and write access on invoices + checkout sessions.',\n },\n category: 'commerce',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'find_customer',\n class: 'read',\n description: 'Search Stripe customers by email. Returns the first match or {found:false}.',\n parameters: {\n type: 'object',\n properties: { email: { type: 'string' } },\n required: ['email'],\n },\n },\n {\n name: 'create_invoice',\n class: 'mutation',\n description:\n 'Draft + finalize a Stripe invoice for a customer with line items. Idempotency-Key guarantees at-most-once.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n customerId: { type: 'string' },\n items: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n description: { type: 'string' },\n amount: { type: 'integer', description: 'Amount in the smallest currency unit (cents).' },\n currency: { type: 'string', description: '3-letter ISO currency code, lowercase.' },\n quantity: { type: 'integer', minimum: 1, default: 1 },\n },\n required: ['amount', 'currency'],\n },\n },\n autoFinalize: { type: 'boolean', default: true },\n },\n required: ['customerId', 'items'],\n },\n },\n {\n name: 'create_checkout_session',\n class: 'mutation',\n description:\n 'Create a Stripe Checkout session and return its hosted URL. Idempotency-Key guarantees at-most-once.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n customerId: { type: 'string' },\n mode: { type: 'string', enum: ['payment', 'subscription'], default: 'payment' },\n successUrl: { type: 'string' },\n cancelUrl: { type: 'string' },\n lineItems: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n price: { type: 'string', description: 'Stripe price id (price_...)' },\n quantity: { type: 'integer', minimum: 1, default: 1 },\n },\n required: ['price'],\n },\n },\n },\n required: ['successUrl', 'cancelUrl', 'lineItems'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'find_customer') {\n throw new Error(`stripe-pack: unknown read capability ${inv.capabilityName}`)\n }\n const apiKey = readApiKey(inv.source.credentials)\n const { email } = inv.args as { email: string }\n // Stripe's /customers/search is the canonical email lookup. Falls\n // back to /customers?email= for accounts on legacy Search-disabled\n // tier — most accounts have Search enabled by default in 2024+.\n const url = `${API}/customers/search?query=${encodeURIComponent(`email:'${email.toLowerCase()}'`)}&limit=1`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${apiKey}` },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe-pack find_customer ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n data?: Array<{ id: string; email?: string; name?: string; phone?: string }>\n }\n const first = json.data?.[0]\n return {\n data: first\n ? { found: true, customer: { id: first.id, email: first.email, name: first.name, phone: first.phone } }\n : { found: false },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const apiKey = readApiKey(inv.source.credentials)\n if (inv.capabilityName === 'create_invoice') return createInvoice(inv, apiKey)\n if (inv.capabilityName === 'create_checkout_session') return createCheckoutSession(inv, apiKey)\n throw new Error(`stripe-pack: unknown mutation capability ${inv.capabilityName}`)\n },\n\n async test(source) {\n try {\n const apiKey = readApiKey(source.credentials)\n // /v1/account is the cheapest grant-validity probe.\n const res = await fetch(`${API}/account`, {\n headers: { authorization: `Bearer ${apiKey}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401) {\n return { ok: false, reason: 'Stripe rejected API key (401) — reconnect required' }\n }\n if (!res.ok) return { ok: false, reason: `Stripe returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n}\n\nasync function createInvoice(inv: ConnectorInvocation, apiKey: string): Promise<CapabilityMutationResult> {\n const { customerId, items, autoFinalize } = inv.args as {\n customerId: string\n items: Array<{ description?: string; amount: number; currency: string; quantity?: number }>\n autoFinalize?: boolean\n }\n // Stripe requires invoiceitem.create BEFORE invoice.create. We do\n // both under the same idempotency-key prefix so retries are exactly\n // replayed across both calls.\n const idemKey = inv.idempotencyKey\n for (let i = 0; i < items.length; i++) {\n const it = items[i]\n const body = new URLSearchParams({\n customer: customerId,\n amount: String(it.amount),\n currency: it.currency.toLowerCase(),\n quantity: String(it.quantity ?? 1),\n })\n if (it.description) body.set('description', it.description)\n const res = await fetch(`${API}/invoiceitems`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': `${idemKey}-item-${i}`,\n },\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n if (res.status === 409) {\n throw new ResourceContention('Stripe invoiceitem conflict — retry rejected by idempotency check')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe-pack create_invoice (item ${i}) ${res.status}: ${text.slice(0, 200)}`)\n }\n }\n\n const invBody = new URLSearchParams({\n customer: customerId,\n auto_advance: autoFinalize === false ? 'false' : 'true',\n collection_method: 'send_invoice',\n days_until_due: '14',\n })\n const invRes = await fetch(`${API}/invoices`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': `${idemKey}-invoice`,\n },\n body: invBody,\n signal: AbortSignal.timeout(15_000),\n })\n if (invRes.status === 401) throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n if (invRes.status === 409) {\n throw new ResourceContention('Stripe invoice conflict — retry rejected by idempotency check')\n }\n if (!invRes.ok) {\n const text = await invRes.text().catch(() => '')\n throw new Error(`stripe-pack create_invoice ${invRes.status}: ${text.slice(0, 200)}`)\n }\n const created = (await invRes.json()) as { id: string; hosted_invoice_url?: string; status?: string }\n return {\n status: 'committed',\n data: { invoiceId: created.id, hostedInvoiceUrl: created.hosted_invoice_url, status: created.status },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nasync function createCheckoutSession(\n inv: ConnectorInvocation,\n apiKey: string,\n): Promise<CapabilityMutationResult> {\n const { customerId, mode, successUrl, cancelUrl, lineItems } = inv.args as {\n customerId?: string\n mode?: 'payment' | 'subscription'\n successUrl: string\n cancelUrl: string\n lineItems: Array<{ price: string; quantity?: number }>\n }\n const body = new URLSearchParams({\n mode: mode ?? 'payment',\n success_url: successUrl,\n cancel_url: cancelUrl,\n })\n if (customerId) body.set('customer', customerId)\n lineItems.forEach((it, i) => {\n body.set(`line_items[${i}][price]`, it.price)\n body.set(`line_items[${i}][quantity]`, String(it.quantity ?? 1))\n })\n const res = await fetch(`${API}/checkout/sessions`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': inv.idempotencyKey,\n },\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n if (res.status === 409) {\n throw new ResourceContention('Stripe checkout session conflict — retry rejected by idempotency check')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe-pack create_checkout_session ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; url?: string; payment_status?: string }\n return {\n status: 'committed',\n data: { sessionId: created.id, url: created.url, paymentStatus: created.payment_status },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nfunction readApiKey(creds: { kind: string; apiKey?: string }): string {\n if (creds.kind !== 'api-key' || typeof creds.apiKey !== 'string' || creds.apiKey.length === 0) {\n throw new Error('stripe-pack: expected api-key credentials')\n }\n return creds.apiKey\n}\n","/**\n * Universal webhook connector — the long-tail escape hatch.\n *\n * The user declares a target URL + a JSON-schema for the request body\n * the agent should send, plus an optional shared secret. We sign every\n * outbound POST with HMAC-SHA256 over `timestamp.body` and forward the\n * agent's idempotency key as a header. The receiving system enforces\n * its own idempotency.\n *\n * One adapter, two capabilities. Both arity-1 — `body` is whatever JSON\n * the agent's planner constructs from the operator-defined schema (which\n * lives in DataSource.metadata.requestSchema). The agent's planner reads\n * that schema at request time and constructs valid args.\n *\n * Why one connector covers 50 systems badly and 1 system well: the agent\n * gets a generic \"send_event\" tool that doesn't *know* what the upstream\n * does with the payload. That's fine for fire-and-forget event posting\n * (Zapier-style); it's wrong for booking against a calendar where you\n * need conflict-resolution. So webhook's `post_event` capability is\n * marked `cas: 'native-idempotency'` (we forward the key — the receiver\n * MUST honor it) and `defaultConsistencyModel: 'advisory'`. Anyone\n * needing real CAS uses a kind-specific connector (Calendar, Sheets, ...).\n */\n\nimport { createHmac } from 'crypto'\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n} from '../types.js'\n\nexport const webhookConnector: ConnectorAdapter = {\n manifest: {\n kind: 'webhook',\n displayName: 'Webhook (custom URL)',\n description:\n \"Fire signed HTTP POSTs from your agent to any URL you control. The escape hatch when there's no native connector — receive the agent's intent, run your own logic, return a result.\",\n auth: { kind: 'hmac' },\n category: 'webhook',\n defaultConsistencyModel: 'advisory',\n capabilities: [\n {\n name: 'post_event',\n class: 'mutation',\n description:\n 'Send a JSON event to the configured webhook URL. The receiver SHOULD return 200 on accept and 409 on conflict (the agent will offer alternatives if you include them in the response).',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n additionalProperties: true,\n description: 'Whatever JSON the operator declared at connect time. The DataSource.metadata.requestSchema is the source of truth at runtime.',\n },\n },\n {\n name: 'fetch_state',\n class: 'read',\n description: 'GET the configured webhook URL with the agent-supplied query params. Returns whatever JSON the receiver responds with.',\n parameters: {\n type: 'object',\n additionalProperties: true,\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const url = readMetaString(inv.source.metadata, 'url')\n const params = inv.args && typeof inv.args === 'object' ? inv.args : {}\n const u = new URL(url)\n for (const [k, v] of Object.entries(params)) {\n u.searchParams.set(k, typeof v === 'string' ? v : JSON.stringify(v))\n }\n const res = await fetch(u.toString(), {\n method: 'GET',\n headers: signHeaders(inv.source.credentials, '', inv.idempotencyKey),\n signal: AbortSignal.timeout(15_000),\n })\n if (!res.ok) {\n throw new Error(`webhook fetch_state ${res.status}: ${(await res.text()).slice(0, 200)}`)\n }\n const data = (await res.json()) as unknown\n return {\n data,\n etag: res.headers.get('etag') ?? undefined,\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const url = readMetaString(inv.source.metadata, 'url')\n const body = JSON.stringify(inv.args ?? {})\n const res = await fetch(url, {\n method: 'POST',\n headers: signHeaders(inv.source.credentials, body, inv.idempotencyKey),\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 409) {\n // Conflict by convention — receiver returns alternatives in the body.\n const json = (await res.json().catch(() => ({}))) as { alternatives?: unknown[]; message?: string }\n return {\n status: 'conflict',\n alternatives: json.alternatives ?? [],\n message: json.message ?? 'webhook receiver returned 409',\n }\n }\n if (!res.ok) {\n throw new Error(`webhook post_event ${res.status}: ${(await res.text()).slice(0, 200)}`)\n }\n const data = (await res.json().catch(() => ({}))) as unknown\n return {\n status: 'committed',\n data,\n etagAfter: res.headers.get('etag') ?? undefined,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async test(source) {\n try {\n const url = readMetaString(source.metadata, 'url')\n // HEAD if the receiver supports it, otherwise GET. Either way a\n // non-5xx response counts as healthy — we don't validate semantics.\n const res = await fetch(url, {\n method: 'HEAD',\n headers: signHeaders(source.credentials, '', `health-${Date.now()}`),\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status >= 500) return { ok: false, reason: `webhook returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`webhook DataSource.metadata.${key} is missing`)\n }\n return v\n}\n\nfunction signHeaders(\n creds: { kind: string; secret?: string; [k: string]: unknown },\n body: string,\n idempotencyKey: string,\n): Record<string, string> {\n const ts = Math.floor(Date.now() / 1000).toString()\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'x-phony-timestamp': ts,\n 'x-phony-idempotency-key': idempotencyKey,\n }\n if (creds.kind === 'hmac' && typeof creds.secret === 'string' && creds.secret.length > 0) {\n const sig = createHmac('sha256', creds.secret).update(`${ts}.${body}`).digest('hex')\n headers['x-phony-signature'] = `sha256=${sig}`\n }\n return headers\n}\n","/**\n * Stripe inbound-webhook receiver — push-only side of a Stripe connector.\n *\n * The full Stripe connector (charges/customers/invoices read+mutation) is\n * tracked in INTEGRATIONS.md as separate `stripe-customers` / `stripe-invoices`\n * rows. This adapter only ships the inbound surface today: receive a push,\n * verify the signature, persist one `InboundEvent` per Stripe event so the\n * agent's runtime can react (e.g. payment_failed → outbound dunning call).\n *\n * Why a dedicated `kind: 'stripe'` rather than reusing the billing webhook\n * at /api/billing/stripe-webhook: that route is hard-coded for OUR Stripe\n * account (Builder subscription state). This connector is for the customer's\n * OWN Stripe account — they paste their `whsec_*` and we listen on a\n * per-DataSource URL, /api/webhooks/inbound/stripe/:dataSourceId.\n *\n * Signature scheme: Stripe's `t=<unix>,v1=<hmac>` header. HMAC is\n * sha256(`${t}.${rawBody}`) keyed by the customer's webhook secret. We use\n * `timingSafeEqual` to defeat timing oracles and bound timestamp skew at\n * 5 minutes (Stripe's recommendation) to thwart replay against captured\n * signatures.\n */\n\nimport {\n type ConnectorAdapter,\n type EventHandlerResult,\n type InboundEvent,\n} from '../types.js'\nimport { firstHeader, verifyStripeSignature } from '../webhooks.js'\n\nexport const stripeWebhookReceiverConnector: ConnectorAdapter = {\n manifest: {\n kind: 'stripe',\n displayName: 'Stripe (inbound events)',\n description:\n \"Receive Stripe webhook events from your own Stripe account. Paste your endpoint signing secret (whsec_*) at connect time; we'll verify every push and feed events to your agent's runtime.\",\n auth: { kind: 'hmac' },\n category: 'commerce',\n // Inbound-only. Stripe events are advisory in this incarnation — the\n // agent reacts to them but doesn't compete for writes against the same\n // resource.\n defaultConsistencyModel: 'advisory',\n capabilities: [],\n },\n\n verifySignature({ rawBody, headers, source }) {\n if (source.credentials.kind !== 'hmac') return { valid: false, reason: 'missing_hmac_secret' }\n const sig = firstHeader(headers, 'stripe-signature')\n if (!sig) return { valid: false, reason: 'missing_stripe_signature_header' }\n const ok = verifyStripeSignature(rawBody, sig, source.credentials.secret)\n return ok ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n\n async handleInboundEvent({ rawBody }): Promise<EventHandlerResult> {\n let parsed: unknown\n try {\n parsed = JSON.parse(rawBody)\n } catch {\n return { events: [], response: { status: 400, body: { error: 'invalid_json' } } }\n }\n if (!parsed || typeof parsed !== 'object') {\n return { events: [], response: { status: 400, body: { error: 'invalid_payload' } } }\n }\n const evt = parsed as { id?: unknown; type?: unknown; data?: unknown; created?: unknown }\n const eventType = typeof evt.type === 'string' ? evt.type : 'stripe.unknown'\n const providerEventId = typeof evt.id === 'string' ? evt.id : undefined\n const events: InboundEvent[] = [\n {\n eventType,\n providerEventId,\n payload: evt as Record<string, unknown>,\n },\n ]\n return { events }\n },\n\n async test(source) {\n if (source.credentials.kind !== 'hmac' || !source.credentials.secret) {\n return { ok: false, reason: 'webhook secret not configured' }\n }\n return { ok: true }\n },\n}\n","/**\n * Slack Events API inbound receiver.\n *\n * Slack sends two distinct request shapes to the same webhook URL:\n *\n * 1. `url_verification` — a one-off handshake during app-config. The body\n * contains a `challenge` string we MUST echo back as the response body\n * (Slack's app-config UI fails the URL otherwise). No InboundEvent is\n * persisted for this — it's an infrastructure ping, not a user event.\n *\n * 2. `event_callback` — every actual workspace event (message posted,\n * reaction added, channel created, …). We persist one InboundEvent\n * keyed by `event_id` so a Slack retry (Slack retries 3 times on any\n * non-2xx) is deduped at the unique constraint, not after we've\n * double-processed.\n *\n * Signature scheme: `v0=<hmac(sha256, \"v0:<timestamp>:<rawBody>\")>` keyed by\n * the app's signing secret. Header `X-Slack-Request-Timestamp` carries the\n * timestamp; we reject anything older than 5 minutes (Slack's recommendation)\n * to bound replay risk.\n */\n\nimport {\n type ConnectorAdapter,\n type EventHandlerResult,\n type InboundEvent,\n} from '../types.js'\nimport { firstHeader, verifySlackSignature } from '../webhooks.js'\n\nexport const slackEventsConnector: ConnectorAdapter = {\n manifest: {\n // NOTE: `slack` is owned by the OAuth bot connector in slack.ts (post_message,\n // lookup_user, list_channels). This adapter is the HMAC-only inbound-events\n // sibling — distinct kind so a customer can stand up the Events API receiver\n // without granting bot OAuth, and so the registry doesn't reject duplicate\n // kinds at boot.\n kind: 'slack-inbound',\n displayName: 'Slack (Events API)',\n description:\n \"Receive workspace events (messages, reactions, app mentions, …) from Slack's Events API. Outbound bot messaging will land in a follow-up.\",\n auth: { kind: 'hmac' },\n category: 'comms',\n // Inbound-only. Events are advisory in this incarnation — agents observe\n // and react, no CAS.\n defaultConsistencyModel: 'advisory',\n capabilities: [],\n },\n\n verifySignature({ rawBody, headers, source }) {\n if (source.credentials.kind !== 'hmac') return { valid: false, reason: 'missing_hmac_secret' }\n const sig = firstHeader(headers, 'x-slack-signature')\n const ts = firstHeader(headers, 'x-slack-request-timestamp')\n if (!sig || !ts) return { valid: false, reason: 'missing_slack_headers' }\n const ok = verifySlackSignature(rawBody, sig, ts, source.credentials.secret)\n return ok ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n\n async handleInboundEvent({ rawBody }): Promise<EventHandlerResult> {\n let parsed: unknown\n try {\n parsed = JSON.parse(rawBody)\n } catch {\n return { events: [], response: { status: 400, body: { error: 'invalid_json' } } }\n }\n if (!parsed || typeof parsed !== 'object') {\n return { events: [], response: { status: 400, body: { error: 'invalid_payload' } } }\n }\n const obj = parsed as Record<string, unknown>\n\n // Handshake: echo the challenge. No event persisted.\n if (obj.type === 'url_verification') {\n const challenge = typeof obj.challenge === 'string' ? obj.challenge : ''\n return {\n events: [],\n response: { status: 200, body: { challenge } },\n }\n }\n\n // Workspace event: persist one row keyed by Slack's event_id.\n if (obj.type === 'event_callback') {\n const inner = obj.event\n const innerType =\n inner && typeof inner === 'object' && 'type' in inner && typeof (inner as { type?: unknown }).type === 'string'\n ? (inner as { type: string }).type\n : 'slack.event'\n const providerEventId = typeof obj.event_id === 'string' ? obj.event_id : undefined\n const event: InboundEvent = {\n eventType: `slack.${innerType}`,\n providerEventId,\n payload: obj,\n }\n return { events: [event] }\n }\n\n // Unknown envelope (Slack adds new top-level types occasionally) — ack\n // so Slack stops retrying, but don't persist a malformed row.\n return { events: [] }\n },\n\n async test(source) {\n if (source.credentials.kind !== 'hmac' || !source.credentials.secret) {\n return { ok: false, reason: 'signing secret not configured' }\n }\n return { ok: true }\n },\n}\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nconst repoParams = {\n type: 'object',\n properties: {\n owner: { type: 'string' },\n repo: { type: 'string' },\n },\n required: ['owner', 'repo'],\n}\n\nexport const githubConnector = declarativeRestConnector({\n kind: 'github',\n displayName: 'GitHub',\n description: 'Search repositories/issues and create or update GitHub issues through a user-scoped token.',\n auth: { kind: 'api-key', hint: 'GitHub fine-grained personal access token or installation token.' },\n category: 'other',\n defaultConsistencyModel: 'authoritative',\n baseUrl: 'https://api.github.com',\n defaultHeaders: {\n 'x-github-api-version': '2022-11-28',\n },\n test: { method: 'GET', path: '/user' },\n capabilities: [\n {\n name: 'repositories.get',\n class: 'read',\n description: 'Read repository metadata.',\n parameters: repoParams,\n request: { method: 'GET', path: '/repos/{owner}/{repo}' },\n },\n {\n name: 'issues.search',\n class: 'read',\n description: 'Search GitHub issues and pull requests.',\n parameters: {\n type: 'object',\n properties: { q: { type: 'string' }, per_page: { type: 'integer', minimum: 1, maximum: 100 } },\n required: ['q'],\n },\n request: { method: 'GET', path: '/search/issues', query: { q: '{q}', per_page: '{per_page}' } },\n },\n {\n name: 'issues.create',\n class: 'mutation',\n description: 'Create an issue in a repository.',\n parameters: {\n type: 'object',\n properties: {\n owner: { type: 'string' },\n repo: { type: 'string' },\n title: { type: 'string' },\n body: { type: 'string' },\n labels: { type: 'array', items: { type: 'string' } },\n },\n required: ['owner', 'repo', 'title'],\n },\n request: { method: 'POST', path: '/repos/{owner}/{repo}/issues', body: 'args' },\n cas: 'native-idempotency',\n },\n {\n name: 'issues.update',\n class: 'mutation',\n description: 'Update an issue by number.',\n parameters: {\n type: 'object',\n properties: {\n owner: { type: 'string' },\n repo: { type: 'string' },\n issue_number: { type: 'integer' },\n title: { type: 'string' },\n body: { type: 'string' },\n state: { type: 'string', enum: ['open', 'closed'] },\n },\n required: ['owner', 'repo', 'issue_number'],\n },\n request: { method: 'PATCH', path: '/repos/{owner}/{repo}/issues/{issue_number}', body: 'args' },\n cas: 'etag-if-match',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nexport const gitlabConnector = declarativeRestConnector({\n kind: 'gitlab',\n displayName: 'GitLab',\n description: 'Search GitLab projects/issues and create or update issues through a personal, project, or group token.',\n auth: { kind: 'api-key', hint: 'GitLab access token with api/read_api scope.' },\n category: 'other',\n defaultConsistencyModel: 'authoritative',\n baseUrl: { metadataKey: 'baseUrl', fallback: 'https://gitlab.com/api/v4' },\n credentialPlacement: { kind: 'header', header: 'PRIVATE-TOKEN' },\n test: { method: 'GET', path: '/user' },\n capabilities: [\n {\n name: 'projects.search',\n class: 'read',\n description: 'Search projects visible to the token.',\n parameters: {\n type: 'object',\n properties: { search: { type: 'string' }, per_page: { type: 'integer', minimum: 1, maximum: 100 } },\n required: ['search'],\n },\n request: { method: 'GET', path: '/projects', query: { search: '{search}', per_page: '{per_page}' } },\n },\n {\n name: 'issues.search',\n class: 'read',\n description: 'Search issues in a project.',\n parameters: {\n type: 'object',\n properties: { projectId: { type: 'string' }, search: { type: 'string' }, per_page: { type: 'integer' } },\n required: ['projectId', 'search'],\n },\n request: { method: 'GET', path: '/projects/{projectId}/issues', query: { search: '{search}', per_page: '{per_page}' } },\n },\n {\n name: 'issues.create',\n class: 'mutation',\n description: 'Create a GitLab project issue.',\n parameters: {\n type: 'object',\n properties: { projectId: { type: 'string' }, title: { type: 'string' }, description: { type: 'string' } },\n required: ['projectId', 'title'],\n },\n request: { method: 'POST', path: '/projects/{projectId}/issues', body: 'args' },\n cas: 'native-idempotency',\n },\n {\n name: 'issues.update',\n class: 'mutation',\n description: 'Update a GitLab issue.',\n parameters: {\n type: 'object',\n properties: { projectId: { type: 'string' }, issueIid: { type: 'integer' }, title: { type: 'string' }, description: { type: 'string' }, state_event: { type: 'string' } },\n required: ['projectId', 'issueIid'],\n },\n request: { method: 'PUT', path: '/projects/{projectId}/issues/{issueIid}', body: 'args' },\n cas: 'etag-if-match',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nconst baseTableParams = {\n type: 'object',\n properties: {\n baseId: { type: 'string' },\n tableName: { type: 'string' },\n },\n required: ['baseId', 'tableName'],\n}\n\nexport const airtableConnector = declarativeRestConnector({\n kind: 'airtable',\n displayName: 'Airtable',\n description: 'Query and update Airtable records for lightweight operational databases.',\n auth: { kind: 'api-key', hint: 'Airtable personal access token.' },\n category: 'spreadsheet',\n defaultConsistencyModel: 'authoritative',\n baseUrl: 'https://api.airtable.com',\n test: { method: 'GET', path: '/v0/meta/whoami' },\n capabilities: [\n {\n name: 'records.list',\n class: 'read',\n description: 'List records in a table.',\n parameters: {\n ...baseTableParams,\n properties: {\n ...baseTableParams.properties,\n maxRecords: { type: 'integer', minimum: 1, maximum: 100 },\n filterByFormula: { type: 'string' },\n },\n },\n request: { method: 'GET', path: '/v0/{baseId}/{tableName}', query: { maxRecords: '{maxRecords}', filterByFormula: '{filterByFormula}' } },\n },\n {\n name: 'records.get',\n class: 'read',\n description: 'Read a single Airtable record.',\n parameters: {\n type: 'object',\n properties: { baseId: { type: 'string' }, tableName: { type: 'string' }, recordId: { type: 'string' } },\n required: ['baseId', 'tableName', 'recordId'],\n },\n request: { method: 'GET', path: '/v0/{baseId}/{tableName}/{recordId}' },\n },\n {\n name: 'records.create',\n class: 'mutation',\n description: 'Create an Airtable record.',\n parameters: {\n type: 'object',\n properties: { baseId: { type: 'string' }, tableName: { type: 'string' }, fields: { type: 'object' } },\n required: ['baseId', 'tableName', 'fields'],\n },\n request: { method: 'POST', path: '/v0/{baseId}/{tableName}', body: { fields: '{fields}' } },\n cas: 'native-idempotency',\n },\n {\n name: 'records.update',\n class: 'mutation',\n description: 'Update an Airtable record.',\n parameters: {\n type: 'object',\n properties: { baseId: { type: 'string' }, tableName: { type: 'string' }, recordId: { type: 'string' }, fields: { type: 'object' } },\n required: ['baseId', 'tableName', 'recordId', 'fields'],\n },\n request: { method: 'PATCH', path: '/v0/{baseId}/{tableName}/{recordId}', body: { fields: '{fields}' } },\n cas: 'optimistic-read-verify',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nexport const asanaConnector = declarativeRestConnector({\n kind: 'asana',\n displayName: 'Asana',\n description: 'Search projects/tasks and create or update Asana tasks.',\n auth: { kind: 'api-key', hint: 'Asana personal access token.' },\n category: 'other',\n defaultConsistencyModel: 'authoritative',\n baseUrl: 'https://app.asana.com/api/1.0',\n test: { method: 'GET', path: '/users/me' },\n capabilities: [\n {\n name: 'projects.search',\n class: 'read',\n description: 'List or search projects in a workspace.',\n parameters: {\n type: 'object',\n properties: { workspace: { type: 'string' }, archived: { type: 'boolean' }, limit: { type: 'integer' } },\n required: ['workspace'],\n },\n request: { method: 'GET', path: '/projects', query: { workspace: '{workspace}', archived: '{archived}', limit: '{limit}' } },\n },\n {\n name: 'tasks.search',\n class: 'read',\n description: 'Search tasks in a workspace.',\n parameters: {\n type: 'object',\n properties: { workspace: { type: 'string' }, text: { type: 'string' }, limit: { type: 'integer' } },\n required: ['workspace'],\n },\n request: { method: 'GET', path: '/workspaces/{workspace}/tasks/search', query: { text: '{text}', limit: '{limit}' } },\n },\n {\n name: 'tasks.create',\n class: 'mutation',\n description: 'Create an Asana task.',\n parameters: {\n type: 'object',\n properties: { data: { type: 'object' } },\n required: ['data'],\n },\n request: { method: 'POST', path: '/tasks', body: { data: '{data}' } },\n cas: 'native-idempotency',\n },\n {\n name: 'tasks.update',\n class: 'mutation',\n description: 'Update an Asana task.',\n parameters: {\n type: 'object',\n properties: { taskGid: { type: 'string' }, data: { type: 'object' } },\n required: ['taskGid', 'data'],\n },\n request: { method: 'PUT', path: '/tasks/{taskGid}', body: { data: '{data}' } },\n cas: 'optimistic-read-verify',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nexport const salesforceConnector = declarativeRestConnector({\n kind: 'salesforce',\n displayName: 'Salesforce',\n description: 'Query Salesforce records with SOQL and create or update sObjects.',\n auth: {\n kind: 'oauth2',\n authorizationUrl: 'https://login.salesforce.com/services/oauth2/authorize',\n tokenUrl: 'https://login.salesforce.com/services/oauth2/token',\n scopes: ['api', 'refresh_token'],\n clientIdEnv: 'SALESFORCE_OAUTH_CLIENT_ID',\n clientSecretEnv: 'SALESFORCE_OAUTH_CLIENT_SECRET',\n },\n category: 'crm',\n defaultConsistencyModel: 'authoritative',\n baseUrl: { metadataKey: 'instanceUrl' },\n test: { method: 'GET', path: '/services/data/v61.0/' },\n capabilities: [\n {\n name: 'records.query',\n class: 'read',\n description: 'Run a SOQL query.',\n parameters: {\n type: 'object',\n properties: { q: { type: 'string' } },\n required: ['q'],\n },\n request: { method: 'GET', path: '/services/data/v61.0/query', query: { q: '{q}' } },\n requiredScopes: ['api'],\n },\n {\n name: 'records.get',\n class: 'read',\n description: 'Read a Salesforce sObject record.',\n parameters: {\n type: 'object',\n properties: { objectName: { type: 'string' }, recordId: { type: 'string' } },\n required: ['objectName', 'recordId'],\n },\n request: { method: 'GET', path: '/services/data/v61.0/sobjects/{objectName}/{recordId}' },\n requiredScopes: ['api'],\n },\n {\n name: 'records.create',\n class: 'mutation',\n description: 'Create a Salesforce sObject record.',\n parameters: {\n type: 'object',\n properties: { objectName: { type: 'string' }, fields: { type: 'object' } },\n required: ['objectName', 'fields'],\n },\n request: { method: 'POST', path: '/services/data/v61.0/sobjects/{objectName}', body: '{fields}' },\n cas: 'native-idempotency',\n requiredScopes: ['api'],\n },\n {\n name: 'records.update',\n class: 'mutation',\n description: 'Update a Salesforce sObject record.',\n parameters: {\n type: 'object',\n properties: { objectName: { type: 'string' }, recordId: { type: 'string' }, fields: { type: 'object' } },\n required: ['objectName', 'recordId', 'fields'],\n },\n request: { method: 'PATCH', path: '/services/data/v61.0/sobjects/{objectName}/{recordId}', body: '{fields}' },\n cas: 'etag-if-match',\n requiredScopes: ['api'],\n },\n ],\n})\n","import type {\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationActionRisk,\n IntegrationDataClass,\n} from './index.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}\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 })\n }\n }\n return tools\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","import type {\n CompleteAuthRequest,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationProvider,\n IntegrationProviderKind,\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}\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 }\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 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: {\n id: string\n input: unknown\n idempotencyKey?: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n }\n}\n\nexport interface ActivepiecesHttpExecutorOptions {\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 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\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\nexport function signActivepiecesRuntimeRequest(serializedBody: string, secret: string): string {\n return `sha256=${createHmac('sha256', secret).update(serializedBody).digest('hex')}`\n}\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: TangleCatalogHttpExecutorInvocation['piece']\n action: ActivepiecesRuntimeRequest['action']\n}\n\nexport type TangleCatalogHttpExecutorOptions = ActivepiecesHttpExecutorOptions\nexport interface TangleCatalogHttpExecutorInvocation extends Omit<ActivepiecesExecutorInvocation, 'catalogEntry' | 'piece'> {\n catalogEntry: unknown\n piece: {\n id: string\n packageName?: string\n version?: string\n actionId: string\n upstreamActionName?: string\n }\n}\n\nexport function createTangleCatalogHttpExecutor(\n options: TangleCatalogHttpExecutorOptions,\n): (invocation: TangleCatalogHttpExecutorInvocation) => ReturnType<ActivepiecesExecutorProviderOptions['executeAction']> {\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 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 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 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 interface TangleIntegrationCatalogEntry {\n id: string\n title: string\n description: string\n category: IntegrationConnector['category']\n auth: IntegrationConnector['auth']\n domains: string[]\n actions: Array<{\n id: string\n title: string\n risk: IntegrationConnector['actions'][number]['risk']\n }>\n triggers: Array<{\n id: string\n title: string\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 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}\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\nexport function listTangleIntegrationCatalogEntries(): TangleIntegrationCatalogEntry[] {\n return listActivepiecesCatalogEntries().map((entry) => sanitizeEntry(entry))\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 version: importedEntry.version,\n actionId: action.id,\n upstreamActionName: catalogAction?.upstreamName,\n },\n })\n },\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 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 })),\n triggers: entry.triggers.map((trigger) => ({\n id: trigger.id,\n title: trigger.title,\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 {\n TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER,\n verifyTangleCatalogRuntimeSignature,\n type TangleCatalogRuntimeRequest,\n} from './activepieces-runtime.js'\nimport { buildTangleIntegrationCatalogConnectors } from './tangle-catalog.js'\nimport type {\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationConnectorAction,\n} from './index.js'\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 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 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 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\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\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 {\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 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 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 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 subject: IntegrationActor\n ttlMs: number\n grantee?: IntegrationActor\n }): Promise<IntegrationSandboxBundle> {\n const grants = (await this.grants.listByManifest(input.manifestId, input.grantee))\n .filter((grant) => grant.status === 'active')\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 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,\n subject: input.subject,\n capabilities: bindings,\n connectors,\n tools: buildIntegrationToolCatalog(connectors),\n expiresAt,\n }\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 !== 'read'\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,aAAY,cAAAC,aAAY,mBAAAC,wBAAuB;;;ACAxD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,eAAe;;;ACS1B,IAAM,yBAAoE;AAAA,EAC/E,OAAO;AAAA,IACL,UAAU;AAAA,IACV,aAAa;AAAA,MACX,sBAAsB;AAAA,MACtB,6BAA6B;AAAA,MAC7B,0BAA0B;AAAA,MAC1B,iCAAiC;AAAA,MACjC,mCAAmC;AAAA,MACnC,iCAAiC;AAAA,MACjC,eAAe;AAAA,MACf,mBAAmB;AAAA,IACrB;AAAA,EACF;AAAA,EACA,SAAS,EAAE,UAAU,OAAO;AAAA,EAC5B,mBAAmB,EAAE,UAAU,OAAO;AAAA,EACtC,UAAU,EAAE,UAAU,OAAO;AAAA,EAC7B,UAAU,EAAE,UAAU,OAAO;AAAA,EAE7B,OAAO;AAAA,IACL,UAAU;AAAA,IACV,aAAa;AAAA,MACX,oBAAoB;AAAA,MACpB,wBAAwB;AAAA,MACxB,4BAA4B;AAAA,MAC5B,qBAAqB;AAAA,MACrB,mBAAmB;AAAA,MACnB,6BAA6B;AAAA,IAC/B;AAAA,EACF;AAAA,EACA,qBAAqB,EAAE,UAAU,QAAQ;AAAA,EACzC,UAAU,EAAE,UAAU,QAAQ;AAAA,EAC9B,UAAU,EAAE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,MAAM,CAAC;AAC5B;","names":["createHmac","randomUUID","timingSafeEqual","trigger","trigger","matchesFilter","redactUnknown","unique","createHash","createHash","unique","randomUUID","defaultReason","redactUnknown","createHash","createHash","SCOPES","AUTH_URL","TOKEN_URL","ensureFreshAccessToken","createHash","SCOPES","AUTH_URL","TOKEN_URL","readMetaString","ensureFreshAccessToken","findNextFreeSlots","SCOPES","AUTH_URL","TOKEN_URL","ensureFreshAccessToken","SCOPES","AUTH_URL","TOKEN_URL","API","AUTH_URL","TOKEN_URL","API","readMetaString","API","readMetaString","API","createHmac","readMetaString","githubConnector","riskRank","unique","redactUnknown","unique","slug","titleFromId","unique","trigger","createHmac","randomUUID","timingSafeEqual","trigger","trigger","registryEntry","unique","sameActor","randomUUID","unique","trigger","requiredScopes","missing","createHmac","timingSafeEqual"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/activepieces-catalog.ts","../src/activepieces-overrides.ts","../src/registry.ts","../src/audit.ts","../src/approval.ts","../src/actions.ts","../src/bridge.ts","../src/errors.ts","../src/client.ts","../src/consent.ts","../src/adapter-provider.ts","../src/credentials.ts","../src/events.ts","../src/guard.ts","../src/healthcheck.ts","../src/manifest.ts","../src/passthrough.ts","../src/policy.ts","../src/presets.ts","../src/connectors/types.ts","../src/connectors/oauth.ts","../src/connectors/webhooks.ts","../src/connectors/adapters/google-calendar.ts","../src/connectors/adapters/google-sheets.ts","../src/connectors/adapters/microsoft-calendar.ts","../src/connectors/adapters/hubspot.ts","../src/connectors/adapters/slack.ts","../src/connectors/adapters/notion-database.ts","../src/connectors/adapters/declarative-rest.ts","../src/connectors/adapters/twilio-sms.ts","../src/connectors/adapters/stripe-pack.ts","../src/connectors/adapters/webhook.ts","../src/connectors/adapters/stripe-webhook-receiver.ts","../src/connectors/adapters/slack-events.ts","../src/connectors/adapters/github.ts","../src/connectors/adapters/gitlab.ts","../src/connectors/adapters/airtable.ts","../src/connectors/adapters/asana.ts","../src/connectors/adapters/salesforce.ts","../src/catalog.ts","../src/catalog-executor.ts","../src/sandbox.ts","../src/importers.ts","../src/gateway-catalog.ts","../src/activepieces-provider.ts","../src/activepieces-runtime.ts","../src/catalog-freshness.ts","../src/tangle-catalog.ts","../src/tangle-catalog-runtime.ts","../src/runtime.ts","../src/workflow.ts"],"sourcesContent":["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 './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'\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 | '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 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 if (this.policy) {\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 }\n const proceed = () => Promise.resolve(provider.invokeAction(connection, fullRequest))\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}.`, 'action_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 './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 { 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 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 }>\n source: {\n repository: string\n path: string\n license: 'MIT'\n }\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 ...(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 { buildActivepiecesConnectors } from './activepieces-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 /** @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 sources.push({\n id: 'tangle-catalog',\n connectors: 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 })\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 { 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","export type IntegrationErrorCode =\n | 'missing_connection'\n | 'missing_grant'\n | 'approval_required'\n | 'approval_denied'\n | 'connection_revoked'\n | 'connection_expired'\n | 'scope_missing'\n | 'action_denied'\n | 'action_not_found'\n | 'provider_rate_limited'\n | 'provider_auth_failed'\n | 'provider_unavailable'\n | 'provider_error'\n | 'capability_expired'\n | 'capability_invalid'\n | 'manifest_invalid'\n | 'passthrough_disabled'\n | 'input_invalid'\n | 'unknown'\n\nexport interface IntegrationUserAction {\n type: 'connect' | 'reconnect' | 'approve' | 'retry' | 'contact_support' | 'change_request'\n label: string\n connectorId?: string\n approvalId?: string\n}\n\nexport class IntegrationRuntimeError extends Error {\n readonly code: IntegrationErrorCode\n readonly status: number\n readonly userAction?: IntegrationUserAction\n readonly metadata?: Record<string, unknown>\n\n constructor(input: {\n code: IntegrationErrorCode\n message: string\n status?: number\n userAction?: IntegrationUserAction\n metadata?: Record<string, unknown>\n }) {\n super(input.message)\n this.name = 'IntegrationRuntimeError'\n this.code = input.code\n this.status = input.status ?? statusForCode(input.code)\n this.userAction = input.userAction\n this.metadata = input.metadata\n }\n}\n\nexport interface NormalizedIntegrationError {\n ok: false\n code: IntegrationErrorCode\n message: string\n status: number\n userAction?: IntegrationUserAction\n metadata?: Record<string, unknown>\n}\n\nexport function normalizeIntegrationError(error: unknown): NormalizedIntegrationError {\n if (error instanceof IntegrationRuntimeError) {\n return {\n ok: false,\n code: error.code,\n message: error.message,\n status: error.status,\n userAction: error.userAction,\n metadata: redactUnknown(error.metadata) as Record<string, unknown> | undefined,\n }\n }\n const message = error instanceof Error ? error.message : String(error ?? 'Unknown integration error.')\n return {\n ok: false,\n code: inferCode(message),\n message,\n status: 500,\n }\n}\n\nexport function statusForCode(code: IntegrationErrorCode): number {\n if (code === 'missing_connection' || code === 'missing_grant') return 409\n if (code === 'approval_required') return 202\n if (code === 'approval_denied') return 403\n if (code === 'connection_revoked' || code === 'connection_expired' || code === 'provider_auth_failed') return 401\n if (code === 'scope_missing' || code === 'action_denied' || code === 'passthrough_disabled') return 403\n if (code === 'action_not_found' || code === 'manifest_invalid' || code === 'input_invalid') return 400\n if (code === 'provider_rate_limited') return 429\n if (code === 'provider_unavailable') return 503\n if (code === 'capability_expired' || code === 'capability_invalid') return 401\n return 500\n}\n\nfunction inferCode(message: string): IntegrationErrorCode {\n if (/approval/i.test(message)) return 'approval_required'\n if (/scope/i.test(message)) return 'scope_missing'\n if (/expired/i.test(message)) return 'connection_expired'\n if (/revoked/i.test(message)) return 'connection_revoked'\n if (/rate.?limit|429/i.test(message)) return 'provider_rate_limited'\n if (/unauth|forbidden|401|403/i.test(message)) return 'provider_auth_failed'\n return 'unknown'\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 {\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","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 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 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 now: () => Date\n\n constructor(options: {\n idempotency?: IntegrationIdempotencyStore\n audit?: IntegrationAuditSink\n rateLimiter?: IntegrationRateLimiter\n now?: () => Date\n } = {}) {\n this.idempotency = options.idempotency\n this.audit = options.audit\n this.rateLimiter = options.rateLimiter\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 (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 await this.writeIdempotency(idempotencyKey, requestHash, result)\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","/**\n * Connector primitives — the contract a concrete first-party integration\n * (Google Calendar, HubSpot, Stripe, ...) implements. Lower level than the\n * hub-side `IntegrationProvider` interface from `../index.ts`: a single\n * `IntegrationProvider` typically wraps several connectors (e.g., a\n * \"first-party\" provider that lists all your shipped connectors as a\n * single catalog).\n *\n * Layering:\n *\n * IntegrationHub — vendor-neutral facade (../index.ts)\n * ↓\n * IntegrationProvider — one per gateway or first-party provider\n * ↓\n * ConnectorAdapter (this file) — one per integration (Google Calendar, ...)\n * ↓\n * upstream HTTP API — vendor SDK / fetch / OAuth\n *\n * Three load-bearing decisions encoded here:\n *\n * 1. Capabilities are typed (`read` vs `mutation`). Every mutation MUST\n * declare a CAS strategy. Conflict resolution is the SDK's job, not the\n * connector's. `validateConnectorManifest()` rejects unsafe manifests\n * before a connector is registered.\n *\n * 2. ConsistencyModel pins what the rest of the system can assume:\n * authoritative → the source IS the truth (Calendar, payments)\n * cache → we mirror with TTL and may serve stale (price list)\n * advisory → informational only (FAQ doc)\n * Agent planners can (and should) refuse to promise outcomes based on\n * `cache`/`advisory` data without a live `authoritative` confirmation.\n *\n * 3. Capabilities surface to the calling agent's tool registry by\n * transformation, not by hand-wiring. Adding a connector automatically\n * expands the agent's toolbelt for that specific user without touching\n * the prompt or runner.\n */\n\n/** Minimal JSON-schema shape used for capability arg validation. We\n * intentionally don't pull `@types/json-schema` — most consumers already\n * declare parameters as `Record<string, unknown>` and the\n * shape is whatever the LLM SDK's structured-output expects. Keep the\n * contract loose at the boundary; tighten via runtime zod where needed. */\nexport type CapabilityParameterSchema = Record<string, unknown>\n\n/** What the rest of the system is allowed to assume about freshness. */\nexport type ConsistencyModel = 'authoritative' | 'cache' | 'advisory'\n\n/** Capability classes. `read` is safe to retry; `mutation` must go through\n * MutationGuard (CAS + idempotency). `subscribe` is reserved for future\n * push-driven sources (webhook callbacks) and is not yet wired. */\nexport type CapabilityClass = 'read' | 'mutation' | 'subscribe'\n\n/** Compare-and-swap strategy a mutation uses to detect conflicts. */\nexport type CASStrategy =\n /** Upstream returns an etag/sequence on read, accepts If-Match on write\n * (Google Calendar, GitHub, GDocs revision_id). The connector returns\n * 412 / Precondition Failed on conflict; the SDK maps to ResourceContention. */\n | 'etag-if-match'\n /** Upstream guarantees exactly-once-per-key (Stripe, idempotent webhooks).\n * The SDK passes the idempotency key through; no etag check. */\n | 'native-idempotency'\n /** No upstream concurrency control. Connector MUST do read-then-write\n * and verify nothing changed in-between (best-effort). Suitable only\n * for low-contention single-user resources; rejected for any\n * consistencyModel='authoritative' write that may race. */\n | 'optimistic-read-verify'\n /** Source is not contended (e.g. logging, telemetry). Mutations are\n * fire-and-forget. Marks the capability as not eligible for\n * authoritative writes. */\n | 'none'\n\nexport interface CapabilityRead {\n name: string\n class: 'read'\n description: string\n /** JSON-schema for the tool args the agent passes when invoking. */\n parameters: CapabilityParameterSchema\n /** Optional: declare which scopes (per the connector manifest) this\n * capability requires. The capability is hidden from the agent's\n * tool registry if the user's grant didn't include them. */\n requiredScopes?: string[]\n}\n\nexport interface CapabilityMutation {\n name: string\n class: 'mutation'\n description: string\n parameters: CapabilityParameterSchema\n /** Mandatory: how does the connector guarantee at-most-once + conflict-detect? */\n cas: CASStrategy\n /** True for capabilities that affect resources outside the calling user\n * (e.g. booking against a shared calendar, charging a card). The agent's\n * planner treats these specially: requires explicit caller confirmation\n * before the call. */\n externalEffect: boolean\n requiredScopes?: string[]\n}\n\nexport type Capability = CapabilityRead | CapabilityMutation\n\n/** OAuth2 scope catalog the user has granted us, plus arbitrary metadata\n * the connector pinned at connect-time (calendar id, sheet id, webhook\n * url, …). `metadata` MUST NOT contain secrets — those go in the\n * encrypted credentials envelope. */\nexport interface DataSourceMetadata {\n scopes: string[]\n [key: string]: unknown\n}\n\n/** A connected, authenticated, ready-to-call data source for a project.\n * Persistence shape mirrors the product's connection/source row but normalized — the\n * encrypted credentials envelope is decrypted at hand-out time and held\n * in memory only for the duration of the call. */\nexport interface ResolvedDataSource {\n id: string\n projectId: string\n publishedAgentId: string | null\n kind: string\n label: string\n consistencyModel: ConsistencyModel\n scopes: string[]\n metadata: Record<string, unknown>\n /** Unwrapped credentials handed to the connector at call-time. Never\n * persisted in this shape; never logged. */\n credentials: ConnectorCredentials\n status: 'active' | 'revoked' | 'error'\n}\n\n/** Discriminated union of credential shapes. Connectors that need new\n * shapes extend this union — `kind` is sealed via the tagged pattern so\n * TypeScript catches an exhaustiveness gap at compile time. */\nexport type ConnectorCredentials =\n | { kind: 'oauth2'; accessToken: string; refreshToken?: string; expiresAt?: number }\n | { kind: 'api-key'; apiKey: string }\n | { kind: 'hmac'; secret: string }\n | { kind: 'none' }\n\n/** Result of a read capability invocation. */\nexport interface CapabilityReadResult {\n /** Free-form payload — the connector's data shape. The agent receives\n * this as the tool result; planners consume it via JSON-shape contract\n * declared in the capability's `parameters` (output schema). */\n data: unknown\n /** Optional etag/sequence the caller can reuse for a subsequent CAS\n * mutation. */\n etag?: string\n /** When this read happened (UTC ms since epoch). */\n fetchedAt: number\n}\n\n/** Result of a mutation capability invocation. Either committed (with the\n * resulting etag/sequence so the caller can chain mutations), or\n * contended (the upstream rejected with a state mismatch — the agent\n * should re-read and retry, or surface alternatives to the caller). */\nexport type CapabilityMutationResult =\n | {\n status: 'committed'\n data: unknown\n etagAfter?: string\n committedAt: number\n /** True iff this commit was returned from the idempotency store\n * rather than executed against upstream. The caller can use this\n * to suppress confirmation messages on retry. */\n idempotentReplay: boolean\n }\n | {\n status: 'conflict'\n /** Best-effort alternative options the upstream surfaced (e.g.,\n * next-available calendar slots after a booking conflict). */\n alternatives: unknown[]\n /** The current authoritative state, if the connector could re-read\n * cheaply. */\n currentState?: unknown\n message: string\n }\n | {\n status: 'rate-limited'\n /** Wall-clock ms the caller should wait before retrying. The SDK\n * computes this from the bucket's refill schedule so the agent\n * doesn't have to guess. */\n retryAfterMs: number\n message: string\n }\n\n/** Inputs the SDK passes into the connector's executeRead / executeMutation. */\nexport interface ConnectorInvocation {\n source: ResolvedDataSource\n capabilityName: string\n args: Record<string, unknown>\n /** Idempotency key the caller (or the SDK's defaulting policy) supplied.\n * Always present at the connector boundary — the SDK manufactures one\n * if the agent didn't pass one. */\n idempotencyKey: string\n /** Optional caller-supplied etag the connector should send as If-Match. */\n expectedEtag?: string\n /** Product/session id (if any) for forensic logging. */\n callSessionId?: string\n}\n\n/** A single inbound event extracted from a push payload. The webhook\n * receiver persists one `InboundEvent` row per entry the connector returns. */\nexport interface InboundEvent {\n eventType: string\n providerEventId?: string\n payload: Record<string, unknown>\n}\n\n/** Adapter response from an inbound-webhook dispatch. The receiver persists\n * every `events[]` entry, then either honors the connector's `response`\n * override (Slack `url_verification` echo, provider-specific 2xx body) or\n * defaults to `{status: 200, body: {received: true, count: events.length}}`. */\nexport interface EventHandlerResult {\n events: InboundEvent[]\n /** Optional: how to respond to the provider. Stripe wants 200 within\n * 30s; Slack wants the challenge param echoed. */\n response?: { status: number; body: unknown; headers?: Record<string, string> }\n}\n\n/**\n * Connector adapter — one per integration kind. Stateless. The SDK holds\n * the persistence + crypto + mutation-guard concerns; the adapter only\n * knows how to talk to its upstream.\n */\nexport interface ConnectorAdapter {\n /** Manifest entry the registry uses to render UI + validate args. */\n manifest: ConnectorManifest\n /** Read invocation. Required when manifest.capabilities contains reads.\n * Should return whatever shape the capability declared\n * in its parameters output schema. */\n executeRead?(inv: ConnectorInvocation): Promise<CapabilityReadResult>\n /** Mutation invocation. Required when manifest.capabilities contains mutations.\n * Throws ResourceContention on a CAS miss; throws\n * any other Error for upstream failures. The MutationGuard wraps this\n * with idempotency-key short-circuit + audit logging — adapters do\n * NOT manage their own dedup. */\n executeMutation?(inv: ConnectorInvocation): Promise<CapabilityMutationResult>\n /** Inbound webhook signature verifier. Called BEFORE handleInboundEvent.\n * MUST use constant-time comparison (`crypto.timingSafeEqual`) for any\n * HMAC check. The receiver returns 401 on `valid=false` without invoking\n * handleInboundEvent. Optional: connectors that don't accept push events\n * omit this method and the receiver returns 405 for the kind. */\n verifySignature?(input: {\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n source: ResolvedDataSource\n }): { valid: boolean; reason?: string }\n /** Inbound webhook dispatch. Called AFTER verifySignature passes. The\n * adapter parses the provider payload and emits zero-or-more\n * `InboundEvent` rows; the receiver persists them as one row each (modulo\n * the (dataSourceId, providerEventId) dedup unique). The optional\n * `response` overrides the receiver's default 200 (Slack `url_verification`\n * needs to echo the challenge in the body to pass Slack's app-config check). */\n handleInboundEvent?(input: {\n source: ResolvedDataSource\n rawBody: string\n headers: Record<string, string | string[] | undefined>\n }): Promise<EventHandlerResult>\n /** OAuth callback handler — exchanges the auth code for tokens, returns\n * the credentials envelope + scopes + metadata. Only present for\n * oauth2-style adapters. */\n exchangeOAuth?(input: {\n code: string\n state: string\n codeVerifier: string\n redirectUri: string\n }): Promise<{\n credentials: ConnectorCredentials\n scopes: string[]\n metadata: Record<string, unknown>\n }>\n /** Refresh access token. Only required for oauth2 adapters with\n * short-lived access tokens. */\n refreshToken?(input: ConnectorCredentials): Promise<ConnectorCredentials>\n /** Health check — invoked when the user clicks \"Test connection\" in the\n * UI. Should perform the cheapest possible read that proves the grant\n * is still valid. Returns `{ok: false, reason}` rather than throwing\n * for the common case (token expired, scope missing). */\n test(source: ResolvedDataSource): Promise<{ ok: true } | { ok: false; reason: string }>\n}\n\n/** Static manifest a connector module exports. Drives the UI catalog,\n * scope display, capability discovery for the agent's tool registry. */\nexport interface ConnectorManifest {\n /** Stable kind id used as the foreign key in DataSource.kind. */\n kind: string\n /** Human label shown in the UI catalog. */\n displayName: string\n /** One-paragraph description shown next to the connect button. */\n description: string\n /** Auth shape this connector requires. */\n auth: AuthSpec\n /** Capability catalog — the agent's tool registry derives ToolDefinition\n * entries from this list at request time. */\n capabilities: Capability[]\n /** ConsistencyModel default for this kind — overridable per DataSource\n * if a particular instance is special (e.g., a user marks a sheet as\n * `cache` because they refresh it nightly). */\n defaultConsistencyModel: ConsistencyModel\n /** Connector category for UI grouping. */\n category: 'calendar' | 'spreadsheet' | 'crm' | 'doc' | 'webhook' | 'storage' | 'comms' | 'commerce' | 'other'\n /** Optional icon URL or named icon. */\n icon?: string\n /** Optional per-kind rate-limit budget. The SDK enforces it inside\n * `executeGuardedMutation` and the read path of `/invoke`. Omit to\n * leave the connector unrestricted. */\n rateLimit?: RateLimitSpec\n}\n\n/** Token-bucket budget the SDK enforces against the connector's upstream.\n * We meter on OUR side rather than letting the upstream reject so a\n * chatty agent can't burn quota that's shared across customers (almost\n * every OAuth client is). */\nexport interface RateLimitSpec {\n /** Max requests per window. */\n requests: number\n /** Window in ms. */\n windowMs: number\n /** Whether to apply across all DataSources sharing the same OAuth\n * client (true; default), or per-DataSource (false). The former\n * matches how upstreams meter (per-app), so almost always pick true. */\n scope?: 'oauth-client' | 'data-source'\n}\n\nexport type AuthSpec =\n | {\n kind: 'oauth2'\n /** Authorization endpoint URL. */\n authorizationUrl: string\n /** Token endpoint URL. */\n tokenUrl: string\n /** Scopes requested in the authorization grant. The user UI shows\n * these so the customer knows what's being shared. */\n scopes: string[]\n /** Whether the connector supports incremental authorization (Google\n * does; many don't). */\n incremental?: boolean\n /** Env-var name holding the OAuth client_id. */\n clientIdEnv: string\n /** Env-var name holding the OAuth client_secret. */\n clientSecretEnv: string\n /** Optional extra params attached to the authorization URL (e.g.,\n * Google's `access_type=offline&prompt=consent` to obtain refresh\n * tokens). */\n extraAuthParams?: Record<string, string>\n }\n | {\n kind: 'api-key'\n /** UI hint shown when collecting the key. */\n hint: string\n }\n | { kind: 'hmac' }\n | { kind: 'none' }\n\n/** Thrown by `executeMutation` when upstream rejects on CAS — caught and\n * rewrapped by MutationGuard. */\nexport class ResourceContention extends Error {\n override readonly name = 'ResourceContention'\n constructor(\n message: string,\n public readonly alternatives: unknown[] = [],\n public readonly currentState?: unknown,\n ) {\n super(message)\n }\n}\n\n/** Thrown when the connector finds the user's grant has been revoked or\n * the access token is no longer valid AND refresh failed. Surfaces to\n * the UI as \"Reconnect required\". */\nexport class CredentialsExpired extends Error {\n override readonly name = 'CredentialsExpired'\n constructor(message: string, public readonly dataSourceId: string) {\n super(message)\n }\n}\n\nexport interface ConnectorManifestValidationIssue {\n path: string\n message: string\n}\n\nexport interface ConnectorManifestValidationResult {\n ok: boolean\n issues: ConnectorManifestValidationIssue[]\n}\n\n/** Validate the static connector manifest before a provider registers it.\n * This catches the expensive mistakes early: duplicate capability names,\n * mutation capabilities without CAS, authoritative fire-and-forget writes,\n * and invalid rate-limit specs. */\nexport function validateConnectorManifest(manifest: ConnectorManifest): ConnectorManifestValidationResult {\n const issues: ConnectorManifestValidationIssue[] = []\n if (!manifest.kind.trim()) issues.push({ path: 'kind', message: 'kind is required' })\n if (!manifest.displayName.trim()) issues.push({ path: 'displayName', message: 'displayName is required' })\n const seen = new Set<string>()\n for (const [index, capability] of manifest.capabilities.entries()) {\n const path = `capabilities[${index}]`\n if (!capability.name.trim()) issues.push({ path: `${path}.name`, message: 'capability name is required' })\n if (seen.has(capability.name)) issues.push({ path: `${path}.name`, message: `duplicate capability name: ${capability.name}` })\n seen.add(capability.name)\n if (capability.class === 'mutation') {\n if (!capability.cas) issues.push({ path: `${path}.cas`, message: 'mutation capability must declare a CAS strategy' })\n if (manifest.defaultConsistencyModel === 'authoritative' && capability.cas === 'none') {\n issues.push({ path: `${path}.cas`, message: 'authoritative mutations cannot use cas=\"none\"' })\n }\n }\n }\n if (manifest.rateLimit) {\n if (!Number.isFinite(manifest.rateLimit.requests) || manifest.rateLimit.requests <= 0) {\n issues.push({ path: 'rateLimit.requests', message: 'rateLimit.requests must be positive' })\n }\n if (!Number.isFinite(manifest.rateLimit.windowMs) || manifest.rateLimit.windowMs <= 0) {\n issues.push({ path: 'rateLimit.windowMs', message: 'rateLimit.windowMs must be positive' })\n }\n }\n return { ok: issues.length === 0, issues }\n}\n\nexport function assertValidConnectorManifest(manifest: ConnectorManifest): void {\n const result = validateConnectorManifest(manifest)\n if (!result.ok) {\n throw new Error(`Invalid connector manifest ${manifest.kind || '<unknown>'}: ${result.issues.map((issue) => `${issue.path}: ${issue.message}`).join('; ')}`)\n }\n}\n","/**\n * Generic OAuth2 helper used by every oauth-shaped connector (Google\n * Calendar, Sheets, Drive, HubSpot, Salesforce, Zoom, ...).\n *\n * Everything PKCE-aware. Opaque-state CSRF guard. Refresh-token aware.\n * No connector-specific logic lives here — adapters hand a `clientId`,\n * `clientSecret`, `tokenUrl`, optional `extraAuthParams` and the rest is\n * mechanical.\n *\n * State and code_verifier are kept in a short-TTL flow store keyed by the\n * opaque `state` we round-trip through the provider. The default store is\n * in-memory for local/dev and tests. Production deployments should inject a\n * durable store backed by KV/Redis/D1/etc. so callbacks can land on any worker.\n */\n\nimport { createHash, randomBytes } from 'crypto'\n\nexport interface PendingOAuthFlow {\n /** code_verifier for PKCE. */\n codeVerifier: string\n /** Opaque-state value also returned in the OAuth redirect. */\n state: string\n /** Project the user is connecting under. */\n projectId: string\n /** Connector kind (e.g. 'google-calendar'). */\n kind: string\n /** Operator-supplied label that becomes DataSource.label. */\n label: string\n /** When we drop the entry. */\n expiresAt: number\n /** The redirectUri we used in the start step — must match exactly on\n * the callback exchange. */\n redirectUri: string\n}\n\nconst PENDING_TTL_MS = 10 * 60 * 1000\n\nexport interface OAuthFlowStore {\n put(state: string, flow: PendingOAuthFlow): Promise<void> | void\n consume(state: string): Promise<PendingOAuthFlow | undefined> | PendingOAuthFlow | undefined\n sweep?(now: number): Promise<void> | void\n clear?(): Promise<void> | void\n}\n\nexport class InMemoryOAuthFlowStore implements OAuthFlowStore {\n private readonly pendingFlows = new Map<string, PendingOAuthFlow>()\n\n put(state: string, flow: PendingOAuthFlow): void {\n this.pendingFlows.set(state, flow)\n }\n\n consume(state: string): PendingOAuthFlow | undefined {\n const flow = this.pendingFlows.get(state)\n this.pendingFlows.delete(state)\n if (!flow || flow.expiresAt <= Date.now()) return undefined\n return flow\n }\n\n sweep(now: number): void {\n for (const [k, v] of this.pendingFlows) {\n if (v.expiresAt <= now) this.pendingFlows.delete(k)\n }\n }\n\n clear(): void {\n this.pendingFlows.clear()\n }\n}\n\nconst defaultFlowStore = new InMemoryOAuthFlowStore()\n\nexport interface StartOAuthInput {\n projectId: string\n kind: string\n label: string\n authorizationUrl: string\n scopes: string[]\n clientId: string\n redirectUri: string\n /** Optional extra query params; Google needs `access_type=offline` and\n * `prompt=consent` to issue refresh tokens reliably. */\n extraAuthParams?: Record<string, string>\n /** Optional flow store. Use a durable store in distributed production\n * runtimes; omitted means local in-memory storage. */\n store?: OAuthFlowStore\n /** Override clock for tests. */\n now?: number\n}\n\nexport interface StartOAuthOutput {\n /** URL the SPA should redirect the user to. */\n authorizationUrl: string\n /** State token — caller stashes this in localStorage to verify on\n * callback. */\n state: string\n}\n\n/** Build the authorization URL + state. SPA navigates the user there;\n * user consents; provider redirects back to redirectUri with `code` +\n * `state`. The caller's callback then invokes `consumePendingFlow`. */\nexport function startOAuthFlow(input: StartOAuthInput): StartOAuthOutput {\n const store = input.store ?? defaultFlowStore\n const now = input.now ?? Date.now()\n store.sweep?.(now)\n const codeVerifier = base64Url(randomBytes(48))\n const codeChallenge = base64Url(createHash('sha256').update(codeVerifier).digest())\n const state = base64Url(randomBytes(24))\n\n store.put(state, {\n codeVerifier,\n state,\n projectId: input.projectId,\n kind: input.kind,\n label: input.label,\n redirectUri: input.redirectUri,\n expiresAt: now + PENDING_TTL_MS,\n })\n\n const url = new URL(input.authorizationUrl)\n url.searchParams.set('response_type', 'code')\n url.searchParams.set('client_id', input.clientId)\n url.searchParams.set('redirect_uri', input.redirectUri)\n url.searchParams.set('scope', input.scopes.join(' '))\n url.searchParams.set('state', state)\n url.searchParams.set('code_challenge', codeChallenge)\n url.searchParams.set('code_challenge_method', 'S256')\n if (input.extraAuthParams) {\n for (const [k, v] of Object.entries(input.extraAuthParams)) {\n url.searchParams.set(k, v)\n }\n }\n return { authorizationUrl: url.toString(), state }\n}\n\n/** Look up + remove the pending flow record. Throws if state is unknown\n * or expired (CSRF guard / replay protection). */\nexport async function consumePendingFlow(state: string, store: OAuthFlowStore = defaultFlowStore): Promise<PendingOAuthFlow> {\n await store.sweep?.(Date.now())\n const flow = await store.consume(state)\n if (!flow) {\n throw new Error('Unknown or expired OAuth state: possible CSRF, replay, or stale flow')\n }\n return flow\n}\n\nexport interface ExchangeCodeInput {\n tokenUrl: string\n clientId: string\n clientSecret: string\n code: string\n codeVerifier: string\n redirectUri: string\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}\n\nexport interface OAuthTokens {\n accessToken: string\n refreshToken?: string\n expiresIn?: number\n scope?: string\n tokenType?: string\n}\n\n/** POST authorization code → token endpoint. Provider-agnostic; if a\n * provider returns a non-standard JSON shape, the adapter wraps this\n * call rather than reaching into the helper. */\nexport async function exchangeAuthorizationCode(input: ExchangeCodeInput): Promise<OAuthTokens> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: input.clientId,\n client_secret: input.clientSecret,\n code: input.code,\n redirect_uri: input.redirectUri,\n code_verifier: input.codeVerifier,\n })\n const res = await (input.fetchImpl ?? fetch)(input.tokenUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body,\n signal: input.signal,\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`OAuth token exchange failed: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n access_token: string\n refresh_token?: string\n expires_in?: number\n scope?: string\n token_type?: string\n }\n return {\n accessToken: json.access_token,\n refreshToken: json.refresh_token,\n expiresIn: json.expires_in,\n scope: json.scope,\n tokenType: json.token_type,\n }\n}\n\nexport interface RefreshInput {\n tokenUrl: string\n clientId: string\n clientSecret: string\n refreshToken: string\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}\n\n/** Refresh an access token. Returns the new tokens — the connector layer\n * is responsible for re-encrypting + persisting the envelope. */\nexport async function refreshAccessToken(input: RefreshInput): Promise<OAuthTokens> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: input.clientId,\n client_secret: input.clientSecret,\n refresh_token: input.refreshToken,\n })\n const res = await (input.fetchImpl ?? fetch)(input.tokenUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body,\n signal: input.signal,\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`OAuth refresh failed: ${res.status} ${res.statusText} — ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n access_token: string\n refresh_token?: string\n expires_in?: number\n scope?: string\n token_type?: string\n }\n return {\n accessToken: json.access_token,\n // Some providers omit refresh_token on refresh — keep the previous one\n // in that case (caller passes through if undefined).\n refreshToken: json.refresh_token,\n expiresIn: json.expires_in,\n scope: json.scope,\n tokenType: json.token_type,\n }\n}\n\nfunction base64Url(buf: Buffer): string {\n return buf.toString('base64').replace(/=+$/, '').replace(/\\+/g, '-').replace(/\\//g, '_')\n}\n\n/** Test-only — drop pending flows between unit-test runs. */\nexport function _resetPendingFlowsForTests(): void {\n defaultFlowStore.clear?.()\n}\n","/**\n * Inbound webhook signature verifiers — provider-specific HMAC schemes.\n *\n * Each signature scheme is a pure function:\n * (rawBody: string, headers, secret, now?) → boolean\n *\n * Constant-time comparison via `crypto.timingSafeEqual`. Timestamps are\n * checked against a configurable tolerance to bound replay risk; the default\n * mirrors the upstream provider's documented window (Stripe: 5 min, Slack: 5 min).\n *\n * These verifiers are the building blocks for any inbound-webhook receiver\n * (a route + a `verify` call + a per-event handler). They live in this\n * package so every consumer of the integration substrate gets correct\n * verification — not just one product reimplementing it.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto'\n\n/** Default replay-protection window. Providers commonly use 5 minutes. */\nexport const DEFAULT_SIGNATURE_TOLERANCE_SECONDS = 5 * 60\n\n// ─── Stripe ─────────────────────────────────────────────────────────────\n//\n// Stripe signs webhooks with a single header `Stripe-Signature` of the form\n//\n// t=<timestamp>,v1=<sig1>,v1=<sig2>,...\n//\n// where `t` is the Unix timestamp the event was generated, and each `v1`\n// is `HMAC-SHA256(secret, \"<t>.<rawBody>\")`. Multiple `v1` entries appear\n// during secret rotation — any one matching is sufficient.\n//\n// https://stripe.com/docs/webhooks/signatures\n\nexport interface ParsedStripeSignatureHeader {\n t: number\n sigs: string[]\n}\n\nexport function parseStripeSignatureHeader(header: string): ParsedStripeSignatureHeader | null {\n const acc: { ts?: number; sigs: string[] } = { sigs: [] }\n for (const part of header.split(',')) {\n const idx = part.indexOf('=')\n if (idx < 0) continue\n const key = part.slice(0, idx).trim()\n const val = part.slice(idx + 1).trim()\n if (key === 't') {\n const n = Number(val)\n if (Number.isFinite(n)) acc.ts = n\n } else if (key === 'v1') {\n acc.sigs.push(val)\n }\n }\n if (acc.ts === undefined || acc.sigs.length === 0) return null\n return { t: acc.ts, sigs: acc.sigs }\n}\n\nexport interface StripeVerifyOptions {\n /** Replay-protection window in seconds. Default 300. */\n toleranceSeconds?: number\n /** Override `now()` for tests. UTC seconds. */\n now?: number\n}\n\n/** Verify a Stripe webhook signature against the raw request body. */\nexport function verifyStripeSignature(\n rawBody: string,\n signatureHeader: string,\n secret: string,\n options: StripeVerifyOptions = {},\n): boolean {\n const parsed = parseStripeSignatureHeader(signatureHeader)\n if (!parsed) return false\n const tolerance = options.toleranceSeconds ?? DEFAULT_SIGNATURE_TOLERANCE_SECONDS\n const now = options.now ?? Math.floor(Date.now() / 1000)\n if (Math.abs(now - parsed.t) > tolerance) return false\n const expected = createHmac('sha256', secret).update(`${parsed.t}.${rawBody}`).digest('hex')\n const expectedBuf = Buffer.from(expected, 'utf8')\n for (const sig of parsed.sigs) {\n const sigBuf = Buffer.from(sig, 'utf8')\n if (sigBuf.length !== expectedBuf.length) continue\n if (timingSafeEqual(sigBuf, expectedBuf)) return true\n }\n return false\n}\n\n// ─── Slack ──────────────────────────────────────────────────────────────\n//\n// Slack signs request bodies with two headers:\n//\n// X-Slack-Signature: v0=<HMAC-SHA256(secret, \"v0:<ts>:<body>\")>\n// X-Slack-Request-Timestamp: <ts>\n//\n// https://api.slack.com/authentication/verifying-requests-from-slack\n\nexport interface SlackVerifyOptions {\n toleranceSeconds?: number\n now?: number\n}\n\nexport function verifySlackSignature(\n rawBody: string,\n signatureHeader: string,\n timestampHeader: string,\n secret: string,\n options: SlackVerifyOptions = {},\n): boolean {\n if (!signatureHeader.startsWith('v0=')) return false\n const ts = Number(timestampHeader)\n if (!Number.isFinite(ts)) return false\n const tolerance = options.toleranceSeconds ?? DEFAULT_SIGNATURE_TOLERANCE_SECONDS\n const now = options.now ?? Math.floor(Date.now() / 1000)\n if (Math.abs(now - ts) > tolerance) return false\n const expected = 'v0=' + createHmac('sha256', secret).update(`v0:${ts}:${rawBody}`).digest('hex')\n const expectedBuf = Buffer.from(expected, 'utf8')\n const sigBuf = Buffer.from(signatureHeader, 'utf8')\n if (sigBuf.length !== expectedBuf.length) return false\n return timingSafeEqual(sigBuf, expectedBuf)\n}\n\n// ─── Generic HMAC ───────────────────────────────────────────────────────\n//\n// For \"we shipped a webhook URL with a shared HMAC secret\" patterns —\n// covers any custom integration where the operator picks the message\n// format. The signed message is the literal `rawBody` (no timestamp\n// prefix); replay protection is the caller's responsibility (use a\n// nonce header + a small dedup cache).\n\nexport interface GenericHmacVerifyOptions {\n /** sha256 (default) | sha1 | sha512 — matches the algorithm the receiver\n * computed at sign time. */\n algorithm?: 'sha256' | 'sha1' | 'sha512'\n /** Optional prefix the receiver prepends to the signature in the header\n * (e.g., `'sha256='`). Stripped before constant-time comparison. */\n signaturePrefix?: string\n /** Lowercase comparison (most providers emit hex-lowercase). Default true. */\n lowercaseHex?: boolean\n}\n\nexport function verifyHmacSignature(\n rawBody: string,\n signatureHeader: string,\n secret: string,\n options: GenericHmacVerifyOptions = {},\n): boolean {\n const algorithm = options.algorithm ?? 'sha256'\n const prefix = options.signaturePrefix ?? ''\n const lower = options.lowercaseHex ?? true\n let candidate = signatureHeader\n if (prefix) {\n if (!candidate.startsWith(prefix)) return false\n candidate = candidate.slice(prefix.length)\n }\n if (lower) candidate = candidate.toLowerCase()\n const expected = createHmac(algorithm, secret).update(rawBody).digest('hex')\n const expectedBuf = Buffer.from(expected, 'utf8')\n const sigBuf = Buffer.from(candidate, 'utf8')\n if (sigBuf.length !== expectedBuf.length) return false\n return timingSafeEqual(sigBuf, expectedBuf)\n}\n\n// ─── Twilio ─────────────────────────────────────────────────────────────\n//\n// Twilio's webhook signature scheme is unlike Stripe/Slack — it doesn't\n// sign the raw body. It signs the concatenation of:\n//\n// fullUrl + sortedConcatenatedParams\n//\n// where `fullUrl` is the public URL Twilio called (scheme + host + path\n// + query, exactly as Twilio constructed it from your console config),\n// and `sortedConcatenatedParams` is `key1+value1+key2+value2+...` over\n// the alphabetically-sorted keys of the POST body params (form-encoded).\n//\n// For JSON-bodied Twilio webhooks (Conversations API), the body is signed\n// as raw bytes — pass `{ bodyAsRaw: true, rawBody }` for that path.\n//\n// HMAC-SHA1, base64-encoded. Header: `X-Twilio-Signature`.\n//\n// https://www.twilio.com/docs/usage/webhooks/webhooks-security\n\nexport interface TwilioVerifyOptions {\n /** Skip verification when the auth token isn't configured. Useful in\n * dev where the receiver wants to accept any payload. Default `false`\n * — production should always require a configured token. */\n skipWhenAuthTokenMissing?: boolean\n /** When true, sign the raw body instead of the URL-encoded sorted-params\n * reduction. Twilio uses raw-body signing for `application/json`\n * webhook bodies. Default `false`. */\n bodyAsRaw?: boolean\n /** When `bodyAsRaw` is true, the raw body to sign. Ignored otherwise. */\n rawBody?: string\n}\n\n/** Verify a Twilio webhook signature. */\nexport function verifyTwilioSignature(\n input: {\n authToken: string | null | undefined\n signatureHeader: string | string[] | undefined\n fullUrl: string | null | undefined\n params: Record<string, string> | undefined\n },\n options: TwilioVerifyOptions = {},\n): boolean {\n if (!input.authToken) {\n return options.skipWhenAuthTokenMissing === true\n }\n const signature = input.signatureHeader\n if (!signature || Array.isArray(signature)) return false\n if (!input.fullUrl) return false\n\n const data = options.bodyAsRaw === true\n ? input.fullUrl + (options.rawBody ?? '')\n : Object.keys(input.params ?? {})\n .sort()\n .reduce((acc, key) => acc + key + (input.params![key] ?? ''), input.fullUrl)\n\n const expected = createHmac('sha1', input.authToken).update(data).digest('base64')\n const expectedBuf = Buffer.from(expected)\n const sigBuf = Buffer.from(signature)\n if (expectedBuf.length !== sigBuf.length) return false\n return timingSafeEqual(expectedBuf, sigBuf)\n}\n\n// ─── Header helper ──────────────────────────────────────────────────────\n//\n// Most fastify/express adapters expose request headers as\n// `Record<string, string | string[] | undefined>`. This helper picks the\n// first canonical value for a given name (case-insensitive).\n\nexport function firstHeader(\n headers: Record<string, string | string[] | undefined>,\n name: string,\n): string | undefined {\n const v = headers[name]\n ?? headers[name.toLowerCase()]\n ?? Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1]\n if (Array.isArray(v)) return v[0]\n return typeof v === 'string' ? v : undefined\n}\n","/**\n * Google Calendar connector — CAS reference implementation.\n *\n * Scopes: `https://www.googleapis.com/auth/calendar` covers list/insert/\n * patch on the user's calendars. We could split read/write but for v1 the\n * single scope keeps the consent screen simple; an operator who wants\n * read-only-Calendar can pick a different `kind` later (`google-calendar-readonly`).\n *\n * The two capabilities the agent actually needs:\n *\n * list_availability(calendarId, timeMin, timeMax)\n * → {busy: [{start, end}], events: [{id, etag, start, end, summary}]}\n * Read; no CAS. Cheap (events.list).\n *\n * book_slot(calendarId, start, end, summary, attendees?)\n * → {eventId, etag}\n * Mutation. CAS by Calendar's own conflict-detection: we re-list\n * events for the requested window inside the same call, and if any\n * OVERLAP exists we return `conflict` with the next-3 free slots\n * mined from the user's freebusy, instead of inserting.\n *\n * Why pre-flight read-then-insert rather than relying on If-Match:\n * `events.insert` doesn't take If-Match (you can't precondition an\n * insert against a non-existent resource). Calendar's own\n * `freebusy.query` is the canonical conflict signal. The whole flow is:\n *\n * 1. freebusy.query for [start, end] on this calendarId\n * 2. if busy → emit ResourceContention with next-3 free slots\n * (computed by walking forward in 30-min steps until 3 free\n * windows of (end-start) duration found)\n * 3. else events.insert with idempotency-key as `requestId` (a Calendar\n * API feature that gives us per-key dedup at upstream)\n *\n * Step 3's `requestId` parameter means a retry of the same idempotency\n * key on the same calendar will return the original event rather than\n * creating a duplicate, which composes correctly with our MutationGuard's\n * idempotency record (which short-circuits before ever hitting upstream\n * on the second call). Defense-in-depth.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport {\n exchangeAuthorizationCode,\n refreshAccessToken,\n} from '../oauth.js'\n\nconst SCOPES = ['https://www.googleapis.com/auth/calendar']\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth'\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface GoogleCalendarOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function googleCalendar(opts: GoogleCalendarOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'google-calendar',\n displayName: 'Google Calendar',\n description:\n \"Let your agent check availability and book against a Google Calendar. Conflict-resolved: two callers can't grab the same slot — the second one is offered the next free time.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'GOOGLE_OAUTH_CLIENT_ID',\n clientSecretEnv: 'GOOGLE_OAUTH_CLIENT_SECRET',\n extraAuthParams: { access_type: 'offline', prompt: 'consent', include_granted_scopes: 'true' },\n },\n category: 'calendar',\n defaultConsistencyModel: 'authoritative',\n // Google Calendar's per-project quota is ~600 req/min before\n // throttling kicks in (Calendar API \"Queries per minute per user\",\n // shared per OAuth client). We meter at that rate locally so the\n // FIRST chatty agent doesn't push the shared client into Google's\n // throttle pool and degrade everyone else's quota.\n rateLimit: { requests: 600, windowMs: 60_000, scope: 'oauth-client' },\n capabilities: [\n {\n name: 'list_availability',\n class: 'read',\n description:\n 'Look up busy/free times on the connected calendar between timeMin and timeMax (RFC3339 timestamps).',\n parameters: {\n type: 'object',\n properties: {\n timeMin: { type: 'string', description: 'RFC3339 lower bound (inclusive)' },\n timeMax: { type: 'string', description: 'RFC3339 upper bound (exclusive)' },\n },\n required: ['timeMin', 'timeMax'],\n },\n },\n {\n name: 'book_slot',\n class: 'mutation',\n description:\n 'Reserve a time window on the connected calendar. Returns conflict + alternatives if the slot is no longer free.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n start: { type: 'string', description: 'RFC3339 start time' },\n end: { type: 'string', description: 'RFC3339 end time' },\n summary: { type: 'string', description: 'Event title shown on the calendar' },\n description: { type: 'string', description: 'Optional event description' },\n attendees: {\n type: 'array',\n items: { type: 'string', description: 'email' },\n },\n },\n required: ['start', 'end', 'summary'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'list_availability') {\n throw new Error(`google-calendar: unknown read capability ${inv.capabilityName}`)\n }\n const calendarId = readMetaString(inv.source.metadata, 'calendarId')\n const { timeMin, timeMax } = inv.args as { timeMin: string; timeMax: string }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const fb = await freebusyQuery({ accessToken, calendarId, timeMin, timeMax })\n return {\n data: { busy: fb.busy },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'book_slot') {\n throw new Error(`google-calendar: unknown mutation capability ${inv.capabilityName}`)\n }\n const calendarId = readMetaString(inv.source.metadata, 'calendarId')\n const { start, end, summary, description, attendees } = inv.args as {\n start: string\n end: string\n summary: string\n description?: string\n attendees?: string[]\n }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n\n // Pre-flight: is the requested window busy?\n const fb = await freebusyQuery({ accessToken, calendarId, timeMin: start, timeMax: end })\n if (fb.busy.length > 0) {\n const startMs = Date.parse(start)\n const endMs = Date.parse(end)\n const durMs = endMs - startMs\n const alternatives = await findNextFreeSlots({\n accessToken,\n calendarId,\n searchFromMs: endMs,\n durationMs: durMs,\n wanted: 3,\n })\n throw new ResourceContention(\n `requested slot ${start}–${end} is no longer free`,\n alternatives,\n { busy: fb.busy },\n )\n }\n\n // Insert. requestId == idempotencyKey gives upstream-side dedup.\n // Calendar requires it to be ≤1024 chars and ASCII.\n const requestId = inv.idempotencyKey.replace(/[^a-zA-Z0-9_:.-]/g, '_').slice(0, 1024)\n const event = {\n summary,\n description,\n start: { dateTime: start },\n end: { dateTime: end },\n attendees: attendees?.map(email => ({ email })),\n }\n const res = await fetch(\n `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?conferenceDataVersion=0&sendUpdates=none&requestId=${encodeURIComponent(requestId)}`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(event),\n signal: AbortSignal.timeout(15_000),\n },\n )\n if (res.status === 409) {\n // Calendar reports duplicate; return as committed by treating the\n // recovered event as the response (idempotent semantics).\n const dup = (await res.json().catch(() => ({}))) as { id?: string; etag?: string }\n return {\n status: 'committed',\n data: dup,\n etagAfter: dup.etag,\n committedAt: Date.now(),\n idempotentReplay: true,\n }\n }\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Google Calendar rejected token (${res.status})`, inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`google-calendar book_slot ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; etag: string; htmlLink?: string }\n return {\n status: 'committed',\n data: { eventId: created.id, htmlLink: created.htmlLink },\n etagAfter: created.etag,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n // Pin which calendar this connection points at. Default to the\n // user's primary; the UI lets the user pick a different calendar\n // post-connect by patching DataSource.metadata.calendarId.\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n metadata: { calendarId: 'primary' },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('google-calendar.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n const calendarId = readMetaString(source.metadata, 'calendarId')\n const url = `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403) {\n return { ok: false, reason: `Google rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `Google returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\ninterface FreeBusyResult {\n busy: Array<{ start: string; end: string }>\n}\n\nasync function freebusyQuery(input: {\n accessToken: string\n calendarId: string\n timeMin: string\n timeMax: string\n}): Promise<FreeBusyResult> {\n const res = await fetch('https://www.googleapis.com/calendar/v3/freeBusy', {\n method: 'POST',\n headers: {\n authorization: `Bearer ${input.accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n timeMin: input.timeMin,\n timeMax: input.timeMax,\n items: [{ id: input.calendarId }],\n }),\n signal: AbortSignal.timeout(10_000),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`freebusy ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n calendars?: Record<string, { busy?: Array<{ start: string; end: string }> }>\n }\n return { busy: json.calendars?.[input.calendarId]?.busy ?? [] }\n}\n\n/** Given a starting point and a duration, walk forward looking up\n * freebusy in 24-hour windows, mining (wanted) free slots that are at\n * least durationMs long. Stops at a horizon of 14 days from search\n * start — past that and the agent should propose a different day. */\nasync function findNextFreeSlots(input: {\n accessToken: string\n calendarId: string\n searchFromMs: number\n durationMs: number\n wanted: number\n}): Promise<Array<{ start: string; end: string }>> {\n const horizonMs = input.searchFromMs + 14 * 24 * 60 * 60 * 1000\n const out: Array<{ start: string; end: string }> = []\n let cursor = input.searchFromMs\n // Step the search window 1 day at a time.\n while (cursor < horizonMs && out.length < input.wanted) {\n const windowEnd = Math.min(cursor + 24 * 60 * 60 * 1000, horizonMs)\n const fb = await freebusyQuery({\n accessToken: input.accessToken,\n calendarId: input.calendarId,\n timeMin: new Date(cursor).toISOString(),\n timeMax: new Date(windowEnd).toISOString(),\n })\n // Walk through free intervals between busy spans inside this window.\n const busy = fb.busy\n .map(b => ({ s: Date.parse(b.start), e: Date.parse(b.end) }))\n .filter(b => Number.isFinite(b.s) && Number.isFinite(b.e))\n .sort((a, b) => a.s - b.s)\n let pos = cursor\n for (const b of busy) {\n if (out.length >= input.wanted) break\n if (b.s > pos && b.s - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n pos = Math.max(pos, b.e)\n }\n if (out.length < input.wanted && windowEnd - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n cursor = windowEnd\n }\n return out.slice(0, input.wanted)\n}\n\n/** If access token is missing or expired, refresh it. Caller is\n * responsible for persisting the rotated envelope back to the row —\n * for now we mutate the in-memory copy so this single call works, and\n * the route layer handles the persistence on call-completion. */\nasync function ensureFreshAccessToken(\n creds: ConnectorCredentials,\n clientId: string,\n clientSecret: string,\n): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('google-calendar: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('Google Calendar access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n // Mutate so the caller within this request sees the fresh token; the\n // persisting write happens at the route layer on completion.\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`google-calendar DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","/**\n * Google Sheets connector — live KB source + writable rows.\n *\n * The flagship for the \"agent reads from a live spreadsheet\" UX. The\n * customer points the connection at a Sheet (spreadsheetId + sheetName +\n * headerRow). We expose:\n *\n * list_rows(filter?, limit?)\n * → {rows: [{...header→cell}], nextCursor?}\n * Cheap; just spreadsheets.values.get with the configured range.\n *\n * query_rows(predicate)\n * → same shape as list_rows but with a structured filter (k=v pairs\n * ANDed together). Simple and explainable; no SQL.\n *\n * update_row(rowKey, patch)\n * → {row: {...header→cell}, updatedRange}\n * Mutation. CAS via Sheets' spreadsheets.values.update + a\n * pre-flight read of the row's revisionId-equivalent hash. Sheets\n * doesn't expose a per-row etag, so we synthesize one — see\n * `rowFingerprint`. If the fingerprint doesn't match what the agent\n * last read, we surface ResourceContention with the current row in\n * `currentState`.\n *\n * KB binding: when a Sheet is `consistencyModel: 'cache'` (the default\n * for spreadsheets — they're slow-moving), the system also indexes the\n * rows as KB chunks. The KB build pipeline calls `list_rows` and emits\n * one markdown page per row; on a connector-level \"refresh\" event the\n * agent's KB rebuilds.\n */\n\nimport { createHash } from 'crypto'\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = ['https://www.googleapis.com/auth/spreadsheets']\nconst AUTH_URL = 'https://accounts.google.com/o/oauth2/v2/auth'\nconst TOKEN_URL = 'https://oauth2.googleapis.com/token'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface GoogleSheetsOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function googleSheets(opts: GoogleSheetsOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'google-sheets',\n displayName: 'Google Sheets',\n description:\n \"Bind your agent's knowledge base or pricing/availability lookup to a live Google Sheet. Edit the sheet, and the agent picks up changes — no redeploys.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'GOOGLE_OAUTH_CLIENT_ID',\n clientSecretEnv: 'GOOGLE_OAUTH_CLIENT_SECRET',\n extraAuthParams: { access_type: 'offline', prompt: 'consent', include_granted_scopes: 'true' },\n },\n category: 'spreadsheet',\n defaultConsistencyModel: 'cache',\n // Sheets API caps OAuth-client-wide reads + writes at 300 req/min\n // each (Google's published quotas: \"Read requests per minute per\n // project\" and the matching write bucket). We meter the tighter of\n // the two so neither side exhausts before us.\n rateLimit: { requests: 300, windowMs: 60_000, scope: 'oauth-client' },\n capabilities: [\n {\n name: 'list_rows',\n class: 'read',\n description: 'Return rows from the connected sheet. Each row is keyed by the header cells declared at connect time.',\n parameters: {\n type: 'object',\n properties: {\n limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },\n },\n },\n },\n {\n name: 'query_rows',\n class: 'read',\n description: 'Return rows matching every key=value pair in `predicate` (string equality, case-insensitive).',\n parameters: {\n type: 'object',\n properties: {\n predicate: {\n type: 'object',\n additionalProperties: { type: 'string' },\n },\n limit: { type: 'integer', minimum: 1, maximum: 500, default: 100 },\n },\n required: ['predicate'],\n },\n },\n {\n name: 'update_row',\n class: 'mutation',\n description: 'Update a row identified by `rowKey` (the value in the configured key column). Patch is a {column: newValue} map. Returns conflict if the row changed since the agent last read it.',\n cas: 'optimistic-read-verify',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n rowKey: { type: 'string', description: 'Value in the key column identifying the row to update.' },\n patch: {\n type: 'object',\n additionalProperties: { type: 'string' },\n },\n expectedFingerprint: {\n type: 'string',\n description: 'Optional. The fingerprint the agent read on its last list_rows/query_rows call. If supplied and stale, the update is rejected with conflict.',\n },\n },\n required: ['rowKey', 'patch'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const meta = readSheetMeta(inv.source.metadata)\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const rows = await fetchAllRows(accessToken, meta)\n const limit = clampLimit(inv.args.limit, 100)\n let filtered = rows\n if (inv.capabilityName === 'query_rows') {\n const predicate = (inv.args.predicate ?? {}) as Record<string, string>\n filtered = rows.filter(row => matchesPredicate(row, predicate))\n } else if (inv.capabilityName !== 'list_rows') {\n throw new Error(`google-sheets: unknown read ${inv.capabilityName}`)\n }\n const sliced = filtered.slice(0, limit)\n return {\n data: {\n rows: sliced.map(r => ({ ...r.values, _fingerprint: r.fingerprint, _rowIndex: r.rowIndex })),\n total: filtered.length,\n truncated: filtered.length > sliced.length,\n },\n etag: meta.etag, // currently undefined — Sheets values.get doesn't surface etag; row-level fingerprints are the conflict signal\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'update_row') {\n throw new Error(`google-sheets: unknown mutation ${inv.capabilityName}`)\n }\n const meta = readSheetMeta(inv.source.metadata)\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const { rowKey, patch, expectedFingerprint } = inv.args as {\n rowKey: string\n patch: Record<string, string>\n expectedFingerprint?: string\n }\n\n // Pre-flight: read the row, compute fingerprint, compare.\n const rows = await fetchAllRows(accessToken, meta)\n const target = rows.find(r => normalizeKey(r.values[meta.keyColumn]) === normalizeKey(rowKey))\n if (!target) {\n throw new ResourceContention(\n `row with key \"${rowKey}\" not found`,\n [],\n { availableRows: rows.length },\n )\n }\n if (expectedFingerprint && expectedFingerprint !== target.fingerprint) {\n throw new ResourceContention(\n `row \"${rowKey}\" was modified since the agent last read it; re-read and try again`,\n [],\n { current: target.values, currentFingerprint: target.fingerprint },\n )\n }\n\n // Build the new row preserving column order.\n const updatedValues: string[] = meta.headers.map(h =>\n h in patch ? String(patch[h]) : (target.values[h] ?? ''),\n )\n const range = `${meta.sheetName}!A${target.rowIndex + 1}:${columnIndexToLetter(meta.headers.length - 1)}${target.rowIndex + 1}`\n const url = `https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(meta.spreadsheetId)}/values/${encodeURIComponent(range)}?valueInputOption=USER_ENTERED`\n const res = await fetch(url, {\n method: 'PUT',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ values: [updatedValues] }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Google Sheets rejected token (${res.status})`, inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`google-sheets update_row ${res.status}: ${text.slice(0, 200)}`)\n }\n const updatedValuesByHeader = Object.fromEntries(\n meta.headers.map((h, i) => [h, updatedValues[i] ?? '']),\n )\n return {\n status: 'committed',\n data: {\n row: updatedValuesByHeader,\n fingerprint: rowFingerprint(updatedValuesByHeader),\n updatedRange: range,\n },\n etagAfter: rowFingerprint(updatedValuesByHeader),\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n // Operator must select the spreadsheet + range post-connect; we\n // can't infer it during the OAuth handshake.\n metadata: { spreadsheetId: '', sheetName: 'Sheet1', headerRow: 1, keyColumn: '' },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('google-sheets.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n const meta = readSheetMeta(source.metadata)\n if (!meta.spreadsheetId) {\n return { ok: false, reason: 'spreadsheetId not configured — pick a sheet in the connection settings' }\n }\n const url = `https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(meta.spreadsheetId)}?fields=spreadsheetId,properties.title`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403) {\n return { ok: false, reason: `Google rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `Google returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\ninterface SheetMeta {\n spreadsheetId: string\n sheetName: string\n /** 1-indexed header row in the sheet. */\n headerRow: number\n /** Header name that uniquely identifies a row (used by update_row). */\n keyColumn: string\n /** Cached column headers — populated on first fetch. Optional in metadata\n * because we resolve them at fetch time and write back via the route\n * layer when the user pins the connection. */\n headers: string[]\n /** Whatever the upstream surfaces as a top-level revision identifier;\n * if absent we synthesize per-row fingerprints instead. */\n etag?: string\n}\n\nfunction readSheetMeta(meta: Record<string, unknown>): SheetMeta {\n const spreadsheetId = String(meta.spreadsheetId ?? '')\n const sheetName = String(meta.sheetName ?? 'Sheet1')\n const headerRow = Number(meta.headerRow ?? 1)\n const keyColumn = String(meta.keyColumn ?? '')\n const headers = Array.isArray(meta.headers) ? (meta.headers as string[]).map(String) : []\n if (!spreadsheetId || !keyColumn) {\n throw new Error('google-sheets metadata missing spreadsheetId or keyColumn')\n }\n return { spreadsheetId, sheetName, headerRow, keyColumn, headers }\n}\n\ninterface ResolvedRow {\n rowIndex: number // 0-indexed offset from the data start (NOT including header)\n values: Record<string, string>\n fingerprint: string\n}\n\n/** Fetch every row in the configured sheet/range and project to keyed\n * records. We don't paginate — Sheets values.get returns the whole range\n * in one call. For very wide sheets the operator can split the\n * connection into multiple DataSources, each with a narrower range. */\nasync function fetchAllRows(accessToken: string, meta: SheetMeta): Promise<ResolvedRow[]> {\n const range = `${meta.sheetName}`\n const url = `https://sheets.googleapis.com/v4/spreadsheets/${encodeURIComponent(meta.spreadsheetId)}/values/${encodeURIComponent(range)}`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Google Sheets rejected token (${res.status})`, '')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`google-sheets values.get ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as { values?: string[][] }\n const grid = json.values ?? []\n if (grid.length === 0) return []\n const headers = meta.headers.length > 0 ? meta.headers : grid[meta.headerRow - 1] ?? []\n if (headers.length === 0) return []\n const dataRows = grid.slice(meta.headerRow)\n return dataRows.map((rowCells, i) => {\n const values: Record<string, string> = {}\n for (let c = 0; c < headers.length; c++) {\n values[headers[c]] = (rowCells[c] ?? '').toString()\n }\n return {\n // rowIndex is the absolute row in the sheet (1-indexed) where this\n // row's data lives. Header is at meta.headerRow. So this row is at\n // headerRow + i + 1 (1-indexed).\n rowIndex: meta.headerRow + i,\n values,\n fingerprint: rowFingerprint(values),\n }\n })\n}\n\n/** Stable fingerprint of a row's cells. Used as a synthetic etag for\n * optimistic-read-verify CAS. */\nfunction rowFingerprint(values: Record<string, string>): string {\n const keys = Object.keys(values).sort()\n const blob = keys.map(k => `${k}=${values[k]}`).join('\u0001')\n return createHash('sha256').update(blob).digest('hex').slice(0, 16)\n}\n\nfunction matchesPredicate(row: ResolvedRow, predicate: Record<string, string>): boolean {\n for (const [k, v] of Object.entries(predicate)) {\n const cell = row.values[k]\n if (cell === undefined) return false\n if (cell.toLowerCase().trim() !== String(v).toLowerCase().trim()) return false\n }\n return true\n}\n\nfunction normalizeKey(s: string | undefined): string {\n return (s ?? '').trim().toLowerCase()\n}\n\nfunction clampLimit(v: unknown, dflt: number): number {\n const n = typeof v === 'number' ? v : Number(v)\n if (!Number.isFinite(n) || n <= 0) return dflt\n return Math.min(Math.max(1, Math.floor(n)), 500)\n}\n\nfunction columnIndexToLetter(idx: number): string {\n // 0 → A, 25 → Z, 26 → AA, 27 → AB ...\n let n = idx\n let s = ''\n while (n >= 0) {\n s = String.fromCharCode((n % 26) + 65) + s\n n = Math.floor(n / 26) - 1\n }\n return s\n}\n\nasync function ensureFreshAccessToken(creds: ConnectorCredentials, clientId: string, clientSecret: string): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('google-sheets: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('Google Sheets access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n","/**\n * Microsoft Graph Calendar connector — the Outlook half of the\n * voice-agent's \"book me a slot\" surface.\n *\n * Mirrors the Google Calendar pattern almost line-for-line, with two\n * upstream-specific quirks worth calling out:\n *\n * 1. Graph exposes `@odata.etag` on every event resource AND honors\n * `If-Match` on `events.patch` / `events.delete`. So unlike Calendar\n * (insert can't be preconditioned against a non-existent resource),\n * we DO get real etag CAS for updates after the booking. We still\n * use the freebusy pre-flight for the create path, because the\n * \"two callers grab the same slot\" race happens before any event\n * exists.\n *\n * 2. `getSchedule` is the Graph equivalent of `freeBusy.query`. Same\n * shape: send `[start, end]` plus the calendar's email/UPN, get\n * back a `scheduleItems` list of busy windows.\n *\n * Why the same flow ports cleanly: the conflict mode is identical\n * (\"did someone else grab this slot between read and write?\"). The\n * mechanism — pre-flight read + idempotent insert — composes regardless\n * of whether upstream gives us a request-id dedup feature. Graph does\n * not have a `requestId` analogue on `events.create`, so we rely\n * exclusively on MutationGuard's idempotency-key short-circuit ABOVE\n * the connector. That layer prevents duplicate inserts on retry.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = [\n 'https://graph.microsoft.com/Calendars.ReadWrite',\n // offline_access is required to receive a refresh_token from the v2.0\n // endpoint; without it Graph hands back access tokens only and the\n // connection silently dies after ~1 hour.\n 'offline_access',\n]\nconst AUTH_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'\nconst TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface MicrosoftCalendarOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function microsoftCalendar(opts: MicrosoftCalendarOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'microsoft-calendar',\n displayName: 'Microsoft Calendar (Outlook 365)',\n description:\n \"Let your agent check availability and book against an Outlook / Microsoft 365 calendar. Conflict-resolved via Graph's getSchedule pre-flight; etag-guarded on event updates.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'MS_OAUTH_CLIENT_ID',\n clientSecretEnv: 'MS_OAUTH_CLIENT_SECRET',\n // Microsoft v2.0 doesn't need extra params to issue a refresh_token\n // as long as `offline_access` is in scopes (above).\n },\n category: 'calendar',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'list_availability',\n class: 'read',\n description:\n 'Look up busy windows on the connected Outlook calendar between timeMin and timeMax (RFC3339 timestamps).',\n parameters: {\n type: 'object',\n properties: {\n timeMin: { type: 'string', description: 'ISO8601 lower bound (inclusive)' },\n timeMax: { type: 'string', description: 'ISO8601 upper bound (exclusive)' },\n },\n required: ['timeMin', 'timeMax'],\n },\n },\n {\n name: 'book_slot',\n class: 'mutation',\n description:\n 'Reserve a time window on the connected Outlook calendar. Returns conflict + alternatives if the slot is no longer free.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n start: { type: 'string', description: 'ISO8601 start time' },\n end: { type: 'string', description: 'ISO8601 end time' },\n summary: { type: 'string', description: 'Event title (subject)' },\n description: { type: 'string', description: 'Optional event body' },\n attendees: {\n type: 'array',\n items: { type: 'string', description: 'attendee email' },\n },\n },\n required: ['start', 'end', 'summary'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'list_availability') {\n throw new Error(`microsoft-calendar: unknown read capability ${inv.capabilityName}`)\n }\n const userPrincipal = readMetaString(inv.source.metadata, 'userPrincipal')\n const { timeMin, timeMax } = inv.args as { timeMin: string; timeMax: string }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const busy = await getScheduleBusy({ accessToken, userPrincipal, timeMin, timeMax })\n return {\n data: { busy },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'book_slot') {\n throw new Error(`microsoft-calendar: unknown mutation capability ${inv.capabilityName}`)\n }\n const userPrincipal = readMetaString(inv.source.metadata, 'userPrincipal')\n const { start, end, summary, description, attendees } = inv.args as {\n start: string\n end: string\n summary: string\n description?: string\n attendees?: string[]\n }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n\n // Pre-flight: getSchedule for [start, end] on this user.\n const busy = await getScheduleBusy({ accessToken, userPrincipal, timeMin: start, timeMax: end })\n if (busy.length > 0) {\n const startMs = Date.parse(start)\n const endMs = Date.parse(end)\n const durMs = endMs - startMs\n const alternatives = await findNextFreeSlots({\n accessToken,\n userPrincipal,\n searchFromMs: endMs,\n durationMs: durMs,\n wanted: 3,\n })\n throw new ResourceContention(\n `requested slot ${start}–${end} is no longer free`,\n alternatives,\n { busy },\n )\n }\n\n const event = {\n subject: summary,\n body: description ? { contentType: 'text', content: description } : undefined,\n start: { dateTime: start, timeZone: 'UTC' },\n end: { dateTime: end, timeZone: 'UTC' },\n attendees: attendees?.map(email => ({\n emailAddress: { address: email },\n type: 'required',\n })),\n }\n const res = await fetch('https://graph.microsoft.com/v1.0/me/events', {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(event),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Microsoft Graph rejected token (${res.status})`, inv.source.id)\n }\n if (res.status === 412 || res.status === 409) {\n // 412 = If-Match precondition failed (not used on insert but Graph\n // can return it under specific concurrent-update races). 409 covers\n // duplicate resourceId on rare retries.\n throw new ResourceContention(\n `Microsoft Graph reported conflict on book_slot (${res.status})`,\n [],\n )\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`microsoft-calendar book_slot ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; '@odata.etag'?: string; webLink?: string }\n return {\n status: 'committed',\n data: { eventId: created.id, webLink: created.webLink },\n etagAfter: created['@odata.etag'],\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('Microsoft OAuth client not configured (MS_OAUTH_CLIENT_ID / _SECRET)')\n }\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n // Operator picks the shared mailbox / room calendar post-connect.\n // Default to the authenticated user's own primary calendar via 'me'.\n metadata: { userPrincipal: 'me' },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('microsoft-calendar.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n // Cheapest possible Graph call that proves the grant: GET /me.\n const res = await fetch('https://graph.microsoft.com/v1.0/me?$select=id', {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403) {\n return { ok: false, reason: `Microsoft rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `Microsoft Graph returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\ninterface BusyWindow {\n start: string\n end: string\n}\n\n/** Graph's getSchedule returns scheduleItems[].status in {free, busy,\n * tentative, oof, workingElsewhere, unknown}. We treat anything other\n * than 'free' as busy — same conservative reading Outlook uses. */\nasync function getScheduleBusy(input: {\n accessToken: string\n userPrincipal: string\n timeMin: string\n timeMax: string\n}): Promise<BusyWindow[]> {\n // 'me' shorthand only resolves on /me/calendar/getSchedule; if a\n // specific UPN was pinned in metadata we'd have to use the user-id\n // form. /me/calendar/getSchedule with schedules=[upn or 'me'] handles\n // both.\n const target = input.userPrincipal === 'me' ? 'me' : input.userPrincipal\n const url = 'https://graph.microsoft.com/v1.0/me/calendar/getSchedule'\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${input.accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n schedules: [target],\n startTime: { dateTime: input.timeMin, timeZone: 'UTC' },\n endTime: { dateTime: input.timeMax, timeZone: 'UTC' },\n availabilityViewInterval: 30,\n }),\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`Microsoft Graph rejected token (${res.status})`, '')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`microsoft-calendar getSchedule ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n value?: Array<{\n scheduleItems?: Array<{\n status?: string\n start?: { dateTime: string }\n end?: { dateTime: string }\n }>\n }>\n }\n const items = json.value?.[0]?.scheduleItems ?? []\n return items\n .filter(it => it.status && it.status !== 'free' && it.start && it.end)\n .map(it => ({ start: it.start!.dateTime, end: it.end!.dateTime }))\n}\n\nasync function findNextFreeSlots(input: {\n accessToken: string\n userPrincipal: string\n searchFromMs: number\n durationMs: number\n wanted: number\n}): Promise<BusyWindow[]> {\n const horizonMs = input.searchFromMs + 14 * 24 * 60 * 60 * 1000\n const out: BusyWindow[] = []\n let cursor = input.searchFromMs\n while (cursor < horizonMs && out.length < input.wanted) {\n const windowEnd = Math.min(cursor + 24 * 60 * 60 * 1000, horizonMs)\n const busy = await getScheduleBusy({\n accessToken: input.accessToken,\n userPrincipal: input.userPrincipal,\n timeMin: new Date(cursor).toISOString(),\n timeMax: new Date(windowEnd).toISOString(),\n })\n const norm = busy\n .map(b => ({ s: Date.parse(b.start), e: Date.parse(b.end) }))\n .filter(b => Number.isFinite(b.s) && Number.isFinite(b.e))\n .sort((a, b) => a.s - b.s)\n let pos = cursor\n for (const b of norm) {\n if (out.length >= input.wanted) break\n if (b.s > pos && b.s - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n pos = Math.max(pos, b.e)\n }\n if (out.length < input.wanted && windowEnd - pos >= input.durationMs) {\n out.push({ start: new Date(pos).toISOString(), end: new Date(pos + input.durationMs).toISOString() })\n }\n cursor = windowEnd\n }\n return out.slice(0, input.wanted)\n}\n\nasync function ensureFreshAccessToken(creds: ConnectorCredentials, clientId: string, clientSecret: string): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('microsoft-calendar: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('Microsoft Calendar access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`microsoft-calendar DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","/**\n * HubSpot CRM connector — three load-bearing capabilities, picked to\n * cover the voice-agent's CRM hot path without trying to swallow all of\n * HubSpot's surface in v1.\n *\n * find_contact(email)\n * → {contact: {id, properties}} | {found: false}\n * POST /crm/v3/objects/contacts/search with an email-equality filter.\n * Cheap, idempotent, no CAS needed (read).\n *\n * upsert_contact(email, properties)\n * → {contactId, created}\n * Mutation. CAS strategy = native-idempotency, BUT: HubSpot's\n * `idempotencyKey` query param is ONLY available on the v3 *batch*\n * endpoints (`/crm/v3/objects/contacts/batch/upsert`). The\n * single-record endpoints don't honor it. We use the batch endpoint\n * with a single-element array to get native idempotency on retry.\n *\n * create_note(contactId, body)\n * → {noteId}\n * Mutation that logs a note engagement on a contact and associates\n * it. Notes are append-only — there's no conflict to detect — so we\n * use native-idempotency via the same batch trick on\n * `/crm/v3/objects/notes/batch/create`.\n *\n * Why three and not thirty: the agent's leverage on HubSpot is\n * \"remember who I just spoke to\". `find_contact` lets the agent address\n * a returning caller by name; `upsert_contact` captures a new one\n * without duplicates; `create_note` writes the call's outcome as a CRM\n * activity. Anything beyond these (deals, tickets, lists) lives in\n * Tier-2 specific kinds — keeping the manifest tight keeps the agent's\n * tool registry comprehensible.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = [\n 'crm.objects.contacts.read',\n 'crm.objects.contacts.write',\n]\nconst AUTH_URL = 'https://app.hubspot.com/oauth/authorize'\nconst TOKEN_URL = 'https://api.hubapi.com/oauth/v1/token'\nconst API = 'https://api.hubapi.com'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface HubSpotOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function hubspot(opts: HubSpotOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'hubspot',\n displayName: 'HubSpot CRM',\n description:\n \"Look up callers in HubSpot, upsert contacts without duplicates, and log call notes as CRM activities. Three capabilities — the voice-agent's CRM hot path.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'HUBSPOT_OAUTH_CLIENT_ID',\n clientSecretEnv: 'HUBSPOT_OAUTH_CLIENT_SECRET',\n },\n category: 'crm',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'find_contact',\n class: 'read',\n description: 'Search HubSpot contacts by email. Returns the first match or {found:false}.',\n parameters: {\n type: 'object',\n properties: { email: { type: 'string', description: 'Email to search for (case-insensitive).' } },\n required: ['email'],\n },\n },\n {\n name: 'upsert_contact',\n class: 'mutation',\n description:\n 'Create-or-update a contact identified by email. Returns the contact id and a `created` flag indicating whether the row was new.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n email: { type: 'string' },\n properties: {\n type: 'object',\n additionalProperties: { type: 'string' },\n description: 'Property map (firstname, lastname, phone, company, …).',\n },\n },\n required: ['email'],\n },\n },\n {\n name: 'create_note',\n class: 'mutation',\n description:\n 'Log a note engagement against a contact. Append-only — note bodies do not conflict.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n contactId: { type: 'string' },\n body: { type: 'string', description: 'Note body (HTML or plain text).' },\n },\n required: ['contactId', 'body'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'find_contact') {\n throw new Error(`hubspot: unknown read capability ${inv.capabilityName}`)\n }\n const { email } = inv.args as { email: string }\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n const res = await fetch(`${API}/crm/v3/objects/contacts/search`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({\n filterGroups: [\n {\n filters: [{ propertyName: 'email', operator: 'EQ', value: email.toLowerCase() }],\n },\n ],\n properties: ['email', 'firstname', 'lastname', 'phone', 'company'],\n limit: 1,\n }),\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired(`HubSpot rejected token (401)`, inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`hubspot find_contact ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n results?: Array<{ id: string; properties: Record<string, string> }>\n }\n const first = json.results?.[0]\n return {\n data: first\n ? { found: true, contact: { id: first.id, properties: first.properties } }\n : { found: false },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const accessToken = await ensureFreshAccessToken(inv.source.credentials, clientId, clientSecret)\n if (inv.capabilityName === 'upsert_contact') {\n return upsertContact(inv, accessToken)\n }\n if (inv.capabilityName === 'create_note') {\n return createNote(inv, accessToken)\n }\n throw new Error(`hubspot: unknown mutation capability ${inv.capabilityName}`)\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('HubSpot OAuth client not configured (HUBSPOT_OAUTH_CLIENT_ID / _SECRET)')\n }\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/\\s+/) ?? SCOPES,\n metadata: {},\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n throw new Error('hubspot.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = await ensureFreshAccessToken(source.credentials, clientId, clientSecret)\n // /oauth/v1/access-tokens/{token} is the cheapest grant-validity probe.\n const res = await fetch(`${API}/oauth/v1/access-tokens/${encodeURIComponent(accessToken)}`, {\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401 || res.status === 403 || res.status === 404) {\n return { ok: false, reason: `HubSpot rejected token (${res.status}) — reconnect required` }\n }\n if (!res.ok) return { ok: false, reason: `HubSpot returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\nasync function upsertContact(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const { email, properties } = inv.args as { email: string; properties?: Record<string, string> }\n const idemKey = sanitizeIdempotencyKey(inv.idempotencyKey)\n // Batch-upsert is the only HubSpot endpoint that honors `idempotencyKey`.\n // See https://developers.hubspot.com/docs/api/crm/contacts batch upsert.\n const url = `${API}/crm/v3/objects/contacts/batch/upsert?idempotencyKey=${encodeURIComponent(idemKey)}`\n const body = {\n inputs: [\n {\n idProperty: 'email',\n id: email.toLowerCase(),\n properties: { email: email.toLowerCase(), ...(properties ?? {}) },\n },\n ],\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired(`HubSpot rejected token (401)`, inv.source.id)\n }\n if (res.status === 409) {\n // HubSpot returns 409 when the upsert targets a record that's been\n // concurrently mutated in a way batch can't reconcile.\n const text = await res.text().catch(() => '')\n throw new ResourceContention(`hubspot upsert_contact conflict: ${text.slice(0, 200)}`)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`hubspot upsert_contact ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n results?: Array<{ id: string; createdAt?: string; updatedAt?: string }>\n status?: string\n }\n const first = json.results?.[0]\n if (!first) {\n throw new Error('hubspot upsert_contact: empty results array')\n }\n const created = first.createdAt && first.updatedAt && first.createdAt === first.updatedAt\n return {\n status: 'committed',\n data: { contactId: first.id, created: Boolean(created) },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nasync function createNote(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const { contactId, body } = inv.args as { contactId: string; body: string }\n const idemKey = sanitizeIdempotencyKey(inv.idempotencyKey)\n const url = `${API}/crm/v3/objects/notes/batch/create?idempotencyKey=${encodeURIComponent(idemKey)}`\n const payload = {\n inputs: [\n {\n properties: {\n hs_note_body: body,\n hs_timestamp: new Date().toISOString(),\n },\n associations: [\n {\n to: { id: contactId },\n // 202 = note→contact association type id (standard HubSpot mapping)\n types: [{ associationCategory: 'HUBSPOT_DEFINED', associationTypeId: 202 }],\n },\n ],\n },\n ],\n }\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired(`HubSpot rejected token (401)`, inv.source.id)\n }\n if (res.status === 409) {\n const text = await res.text().catch(() => '')\n throw new ResourceContention(`hubspot create_note conflict: ${text.slice(0, 200)}`)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`hubspot create_note ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as { results?: Array<{ id: string }> }\n const first = json.results?.[0]\n if (!first) {\n throw new Error('hubspot create_note: empty results array')\n }\n return {\n status: 'committed',\n data: { noteId: first.id },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\n/** HubSpot's `idempotencyKey` requires URL-safe ASCII, ≤ 64 chars. */\nfunction sanitizeIdempotencyKey(k: string): string {\n return k.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\nasync function ensureFreshAccessToken(creds: ConnectorCredentials, clientId: string, clientSecret: string): Promise<string> {\n if (creds.kind !== 'oauth2') {\n throw new Error('hubspot: expected oauth2 credentials')\n }\n if (creds.accessToken && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000)) {\n return creds.accessToken\n }\n if (!creds.refreshToken) {\n throw new CredentialsExpired('HubSpot access token expired and no refresh token', '')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n creds.accessToken = refreshed.accessToken\n creds.expiresAt = refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined\n if (refreshed.refreshToken) creds.refreshToken = refreshed.refreshToken\n return creds.accessToken\n}\n","/**\n * Slack connector — bot-token OAuth, three messaging-oriented capabilities.\n *\n * post_message(channel, text|blocks) → mutation; cas: 'none'\n * lookup_user(email) → read\n * list_channels(types?, limit?) → read\n *\n * Why `cas: 'none'` is acceptable here (and only here in this batch):\n * Slack messages are advisory — we set\n * `defaultConsistencyModel: 'advisory'`. The registry validator allows\n * `cas: 'none'` only on non-authoritative connectors precisely so that\n * append-only messaging surfaces don't have to invent fake CAS theatre.\n * The agent's planner already treats `advisory` data as informational\n * and does not promise outcomes based on its post results without\n * a separate authoritative confirm. MutationGuard's idempotency-key\n * dedup remains in force above the connector — a retry of the same\n * post_message call will short-circuit before reaching Slack.\n *\n * Auth: standard OAuth2. Slack's `/oauth.v2.access` returns a bot\n * `access_token` (`xoxb-…`) but does NOT return a refresh_token unless\n * the app has rotated tokens enabled. Bot tokens are long-lived by\n * default; we surface refreshToken handling but treat its absence as\n * normal rather than an error.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst SCOPES = ['chat:write', 'users:read', 'users:read.email', 'channels:read']\nconst AUTH_URL = 'https://slack.com/oauth/v2/authorize'\nconst TOKEN_URL = 'https://slack.com/api/oauth.v2.access'\nconst API = 'https://slack.com/api'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface SlackOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function slack(opts: SlackOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n // The inbound Events API receiver registers kind `slack-inbound`\n // (hmac signing-secret auth). This connector — kind `slack` —\n // carries the OAuth bot-token outbound surface. Two kinds, one\n // logical product, deliberately split because the credential shapes\n // are different (HMAC secret vs bot OAuth) and operators commonly\n // wire one without the other.\n kind: 'slack',\n displayName: 'Slack',\n description:\n \"Post messages from the agent into Slack, look up users by email, and list channels. Advisory surface — Slack posts are informational, not transactional.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n scopes: SCOPES,\n clientIdEnv: 'SLACK_OAUTH_CLIENT_ID',\n clientSecretEnv: 'SLACK_OAUTH_CLIENT_SECRET',\n },\n category: 'comms',\n defaultConsistencyModel: 'advisory',\n capabilities: [\n {\n name: 'post_message',\n class: 'mutation',\n description: 'Post a message from the bot to a channel or user DM. Append-only — no CAS.',\n cas: 'none',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n channel: { type: 'string', description: 'Channel id (C…) or user id (U…) for DM.' },\n text: { type: 'string' },\n blocks: { type: 'array', description: 'Optional Slack Block Kit blocks.' },\n },\n required: ['channel'],\n },\n },\n {\n name: 'lookup_user',\n class: 'read',\n description: 'Look up a Slack workspace user by email.',\n parameters: {\n type: 'object',\n properties: { email: { type: 'string' } },\n required: ['email'],\n },\n },\n {\n name: 'list_channels',\n class: 'read',\n description: 'List channels visible to the bot. `types` defaults to public_channel,private_channel.',\n parameters: {\n type: 'object',\n properties: {\n types: { type: 'string', description: 'Comma-separated channel types.' },\n limit: { type: 'integer', minimum: 1, maximum: 1000, default: 200 },\n },\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const accessToken = readBotToken(inv.source.credentials)\n if (inv.capabilityName === 'lookup_user') {\n const { email } = inv.args as { email: string }\n const url = `${API}/users.lookupByEmail?email=${encodeURIComponent(email)}`\n const json = await slackGet(url, accessToken, inv.source.id)\n if (!json.ok) {\n if (json.error === 'users_not_found') {\n return { data: { found: false }, fetchedAt: Date.now() }\n }\n throw new Error(`slack lookup_user: ${json.error ?? 'unknown'}`)\n }\n const u = json.user as { id: string; name?: string; real_name?: string; profile?: unknown } | undefined\n return {\n data: { found: true, user: u ? { id: u.id, name: u.name, realName: u.real_name } : null },\n fetchedAt: Date.now(),\n }\n }\n if (inv.capabilityName === 'list_channels') {\n const { types, limit } = inv.args as { types?: string; limit?: number }\n const params = new URLSearchParams({\n limit: String(Math.min(Math.max(1, limit ?? 200), 1000)),\n types: types ?? 'public_channel,private_channel',\n })\n const json = await slackGet(`${API}/conversations.list?${params.toString()}`, accessToken, inv.source.id)\n if (!json.ok) {\n throw new Error(`slack list_channels: ${json.error ?? 'unknown'}`)\n }\n const channels = (json.channels as Array<{ id: string; name: string; is_private?: boolean }>) ?? []\n return {\n data: { channels: channels.map(c => ({ id: c.id, name: c.name, isPrivate: c.is_private ?? false })) },\n fetchedAt: Date.now(),\n }\n }\n throw new Error(`slack: unknown read capability ${inv.capabilityName}`)\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'post_message') {\n throw new Error(`slack: unknown mutation capability ${inv.capabilityName}`)\n }\n const accessToken = readBotToken(inv.source.credentials)\n const { channel, text, blocks } = inv.args as {\n channel: string\n text?: string\n blocks?: unknown[]\n }\n const res = await fetch(`${API}/chat.postMessage`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'content-type': 'application/json; charset=utf-8',\n },\n body: JSON.stringify({ channel, text, blocks }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Slack rejected token (401)', inv.source.id)\n }\n if (!res.ok) {\n const t = await res.text().catch(() => '')\n throw new Error(`slack post_message HTTP ${res.status}: ${t.slice(0, 200)}`)\n }\n // Slack returns 200 with `ok:false` on logical errors. Map common\n // auth/scope failures back to CredentialsExpired so the UI can prompt\n // a reconnect.\n const json = (await res.json()) as {\n ok?: boolean\n error?: string\n ts?: string\n channel?: string\n }\n if (!json.ok) {\n if (\n json.error === 'invalid_auth' ||\n json.error === 'token_expired' ||\n json.error === 'not_authed' ||\n json.error === 'token_revoked'\n ) {\n throw new CredentialsExpired(`Slack rejected token: ${json.error}`, inv.source.id)\n }\n throw new Error(`slack post_message: ${json.error ?? 'unknown'}`)\n }\n return {\n status: 'committed',\n data: { ts: json.ts, channel: json.channel },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('Slack OAuth client not configured (SLACK_OAUTH_CLIENT_ID / _SECRET)')\n }\n // Slack's oauth.v2.access response is non-standard: the bot token\n // lives at `access_token` inside the top-level response (NOT nested\n // — that's the v1 quirk). We use exchangeAuthorizationCode for the\n // POST mechanics, then re-tag the result.\n const tokens = await exchangeAuthorizationCode({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n code: input.code,\n codeVerifier: input.codeVerifier,\n redirectUri: input.redirectUri,\n })\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresIn ? Date.now() + tokens.expiresIn * 1000 : undefined,\n },\n scopes: tokens.scope?.split(/[,\\s]+/) ?? SCOPES,\n metadata: {},\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n // Slack bot tokens are long-lived without rotation; absence of\n // refresh_token is normal. Return creds unchanged so the caller\n // doesn't trigger a reconnect prematurely.\n return creds\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = readBotToken(source.credentials)\n const res = await fetch(`${API}/auth.test`, {\n method: 'POST',\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (!res.ok) return { ok: false, reason: `Slack returned ${res.status}` }\n const json = (await res.json()) as { ok?: boolean; error?: string }\n if (!json.ok) {\n return { ok: false, reason: `Slack auth.test: ${json.error ?? 'unknown'} — reconnect required` }\n }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\nfunction readBotToken(creds: ConnectorCredentials): string {\n if (creds.kind !== 'oauth2' || typeof creds.accessToken !== 'string') {\n throw new Error('slack: expected oauth2 credentials')\n }\n return creds.accessToken\n}\n\ninterface SlackJsonResponse {\n ok?: boolean\n error?: string\n [k: string]: unknown\n}\n\nasync function slackGet(url: string, accessToken: string, dataSourceId: string): Promise<SlackJsonResponse> {\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${accessToken}` },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Slack rejected token (401)', dataSourceId)\n }\n if (!res.ok) {\n const t = await res.text().catch(() => '')\n throw new Error(`slack HTTP ${res.status}: ${t.slice(0, 200)}`)\n }\n return (await res.json()) as SlackJsonResponse\n}\n","/**\n * Notion database connector — query + page-level CRUD against a single\n * connected database.\n *\n * query_database(filter?, pageSize?) → read\n * create_page(properties) → mutation; cas: 'native-idempotency'\n * update_page(pageId, properties) → mutation; cas: 'etag-if-match'\n *\n * CAS quirks worth flagging:\n *\n * 1. Notion added support for the `Idempotency-Key` HTTP header on\n * mutating requests. We forward our SDK's idempotency key on\n * create_page, which gives at-most-once semantics under the same\n * key for ~24h. MutationGuard's record short-circuits above us;\n * Notion's dedup is the second line of defense.\n *\n * 2. Notion does NOT expose a per-page etag the way Graph does. The\n * canonical drift signal is `last_edited_time` (RFC3339). Our\n * `update_page` capability accepts an `expectedLastEditedTime` arg;\n * if supplied, we GET the page first and compare. Mismatch →\n * ResourceContention with the current page state. Conflict-free\n * callers can omit the field (last-write-wins, the Notion default).\n *\n * Auth: standard OAuth2. Notion's token endpoint follows RFC 6749 with\n * one twist — the workspace_id and bot_id come back in the response and\n * we stash them in `metadata` so the agent can address resources by\n * workspace where useful.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n type ConnectorCredentials,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\nimport { exchangeAuthorizationCode, refreshAccessToken } from '../oauth.js'\n\nconst AUTH_URL = 'https://api.notion.com/v1/oauth/authorize'\nconst TOKEN_URL = 'https://api.notion.com/v1/oauth/token'\nconst API = 'https://api.notion.com/v1'\nconst NOTION_VERSION = '2022-06-28'\n\n/** OAuth client config the factory closes over. Caller resolves these\n * at construction time (env, DB, secret manager — package doesn't care). */\nexport interface NotionDatabaseOptions {\n clientId: string\n clientSecret: string\n}\n\nexport function notionDatabase(opts: NotionDatabaseOptions): ConnectorAdapter {\n const { clientId, clientSecret } = opts\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: 'notion-database',\n displayName: 'Notion (database)',\n description:\n \"Query a Notion database, create new pages, and update existing ones with optimistic concurrency via last_edited_time.\",\n auth: {\n kind: 'oauth2',\n authorizationUrl: AUTH_URL,\n tokenUrl: TOKEN_URL,\n // Notion does not use OAuth scopes — the workspace owner picks\n // which pages/databases the integration sees during install. We\n // declare an empty scope list so the consent screen renders cleanly.\n scopes: [],\n clientIdEnv: 'NOTION_OAUTH_CLIENT_ID',\n clientSecretEnv: 'NOTION_OAUTH_CLIENT_SECRET',\n extraAuthParams: { owner: 'user' },\n },\n category: 'doc',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'query_database',\n class: 'read',\n description: 'Query the connected Notion database with an optional filter object (Notion query DSL).',\n parameters: {\n type: 'object',\n properties: {\n filter: { type: 'object', description: 'Notion API filter object — passed through verbatim.' },\n pageSize: { type: 'integer', minimum: 1, maximum: 100, default: 50 },\n startCursor: { type: 'string' },\n },\n },\n },\n {\n name: 'create_page',\n class: 'mutation',\n description: 'Create a new page inside the connected database.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n properties: {\n type: 'object',\n description: 'Notion property map keyed by property name.',\n },\n },\n required: ['properties'],\n },\n },\n {\n name: 'update_page',\n class: 'mutation',\n description:\n 'Update properties on an existing page. If `expectedLastEditedTime` is supplied and stale, the update is rejected with conflict.',\n cas: 'etag-if-match',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n pageId: { type: 'string' },\n properties: { type: 'object' },\n expectedLastEditedTime: {\n type: 'string',\n description: 'RFC3339 timestamp the agent observed on its last read. Drift triggers ResourceContention.',\n },\n },\n required: ['pageId', 'properties'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'query_database') {\n throw new Error(`notion-database: unknown read capability ${inv.capabilityName}`)\n }\n const accessToken = readToken(inv.source.credentials)\n const databaseId = readMetaString(inv.source.metadata, 'databaseId')\n const { filter, pageSize, startCursor } = inv.args as {\n filter?: unknown\n pageSize?: number\n startCursor?: string\n }\n const body: Record<string, unknown> = {\n page_size: Math.min(Math.max(1, pageSize ?? 50), 100),\n }\n if (filter) body.filter = filter\n if (startCursor) body.start_cursor = startCursor\n\n const res = await fetch(`${API}/databases/${encodeURIComponent(databaseId)}/query`, {\n method: 'POST',\n headers: notionHeaders(accessToken),\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`notion-database query_database ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n results?: Array<{ id: string; last_edited_time: string; properties: unknown; url?: string }>\n has_more?: boolean\n next_cursor?: string | null\n }\n return {\n data: {\n results: json.results ?? [],\n hasMore: json.has_more ?? false,\n nextCursor: json.next_cursor ?? null,\n },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const accessToken = readToken(inv.source.credentials)\n if (inv.capabilityName === 'create_page') return createPage(inv, accessToken)\n if (inv.capabilityName === 'update_page') return updatePage(inv, accessToken)\n throw new Error(`notion-database: unknown mutation capability ${inv.capabilityName}`)\n },\n\n async exchangeOAuth(input) {\n if (!clientId || !clientSecret) {\n throw new Error('Notion OAuth client not configured (NOTION_OAUTH_CLIENT_ID / _SECRET)')\n }\n // Notion REQUIRES Basic auth on the token endpoint and does not\n // accept client_id/client_secret in the form body. exchangeAuthorizationCode\n // posts both in the body; Notion ignores the duplicates and accepts\n // the Basic header — but we have to add the header explicitly.\n // We do the POST inline rather than extending the helper's\n // signature, since this is the one upstream that needs Basic.\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code: input.code,\n redirect_uri: input.redirectUri,\n code_verifier: input.codeVerifier,\n })\n const res = await fetch(TOKEN_URL, {\n method: 'POST',\n headers: {\n authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n 'Notion-Version': NOTION_VERSION,\n },\n body,\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`Notion OAuth token exchange failed: ${res.status} — ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n access_token: string\n refresh_token?: string\n bot_id?: string\n workspace_id?: string\n workspace_name?: string\n duplicated_template_id?: string\n }\n return {\n credentials: {\n kind: 'oauth2',\n accessToken: json.access_token,\n refreshToken: json.refresh_token,\n },\n scopes: [],\n metadata: {\n botId: json.bot_id,\n workspaceId: json.workspace_id,\n workspaceName: json.workspace_name,\n // Operator picks the database in a follow-up step; default empty.\n databaseId: '',\n },\n }\n },\n\n async refreshToken(creds) {\n if (creds.kind !== 'oauth2' || !creds.refreshToken) {\n // Notion's standard tokens don't expire and don't ship a\n // refresh_token. If we have neither expiresAt nor refreshToken,\n // treat the existing access token as durable.\n if (creds.kind === 'oauth2' && creds.accessToken && !creds.expiresAt) {\n return creds\n }\n throw new Error('notion-database.refreshToken: missing refresh token')\n }\n const refreshed = await refreshAccessToken({\n tokenUrl: TOKEN_URL,\n clientId,\n clientSecret,\n refreshToken: creds.refreshToken,\n })\n return {\n kind: 'oauth2',\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken ?? creds.refreshToken,\n expiresAt: refreshed.expiresIn ? Date.now() + refreshed.expiresIn * 1000 : undefined,\n }\n },\n\n async test(source) {\n try {\n const accessToken = readToken(source.credentials)\n // /users/me is the cheapest grant-validity probe.\n const res = await fetch(`${API}/users/me`, {\n headers: notionHeaders(accessToken),\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401) return { ok: false, reason: 'Notion rejected token (401) — reconnect required' }\n if (!res.ok) return { ok: false, reason: `Notion returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n }\n return adapter\n}\n\nasync function createPage(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const databaseId = readMetaString(inv.source.metadata, 'databaseId')\n const { properties } = inv.args as { properties: Record<string, unknown> }\n const res = await fetch(`${API}/pages`, {\n method: 'POST',\n headers: {\n ...notionHeaders(accessToken),\n 'Idempotency-Key': inv.idempotencyKey,\n },\n body: JSON.stringify({\n parent: { database_id: databaseId },\n properties,\n }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (res.status === 409) {\n throw new ResourceContention('Notion idempotency-key conflict — different args under same key')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`notion-database create_page ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; url?: string; last_edited_time?: string }\n return {\n status: 'committed',\n data: { pageId: created.id, url: created.url, lastEditedTime: created.last_edited_time },\n etagAfter: created.last_edited_time,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nasync function updatePage(inv: ConnectorInvocation, accessToken: string): Promise<CapabilityMutationResult> {\n const { pageId, properties, expectedLastEditedTime } = inv.args as {\n pageId: string\n properties: Record<string, unknown>\n expectedLastEditedTime?: string\n }\n // Optional pre-flight CAS: if the agent supplied the timestamp it\n // observed on its last read, fetch the page and compare BEFORE\n // committing. The window between this read and the patch isn't\n // closed by Notion (no If-Match), but it shrinks the race to\n // milliseconds — sufficient for typical voice-agent cadences.\n if (expectedLastEditedTime) {\n const headRes = await fetch(`${API}/pages/${encodeURIComponent(pageId)}`, {\n headers: notionHeaders(accessToken),\n signal: AbortSignal.timeout(10_000),\n })\n if (headRes.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (!headRes.ok) {\n const text = await headRes.text().catch(() => '')\n throw new Error(`notion-database update_page (preflight) ${headRes.status}: ${text.slice(0, 200)}`)\n }\n const page = (await headRes.json()) as { last_edited_time?: string; properties?: unknown }\n if (page.last_edited_time && page.last_edited_time !== expectedLastEditedTime) {\n throw new ResourceContention(\n `Notion page ${pageId} was modified since the agent last read it`,\n [],\n { last_edited_time: page.last_edited_time, properties: page.properties },\n )\n }\n }\n\n const res = await fetch(`${API}/pages/${encodeURIComponent(pageId)}`, {\n method: 'PATCH',\n headers: notionHeaders(accessToken),\n body: JSON.stringify({ properties }),\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Notion rejected token (401)', inv.source.id)\n }\n if (res.status === 409 || res.status === 412) {\n throw new ResourceContention(`Notion update_page conflict (${res.status})`)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`notion-database update_page ${res.status}: ${text.slice(0, 200)}`)\n }\n const updated = (await res.json()) as { id: string; last_edited_time?: string; url?: string }\n return {\n status: 'committed',\n data: { pageId: updated.id, url: updated.url, lastEditedTime: updated.last_edited_time },\n etagAfter: updated.last_edited_time,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nfunction notionHeaders(accessToken: string): Record<string, string> {\n return {\n authorization: `Bearer ${accessToken}`,\n 'Notion-Version': NOTION_VERSION,\n 'content-type': 'application/json',\n }\n}\n\nfunction readToken(creds: ConnectorCredentials): string {\n if (creds.kind !== 'oauth2' || typeof creds.accessToken !== 'string') {\n throw new Error('notion-database: expected oauth2 credentials')\n }\n return creds.accessToken\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`notion-database DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","import {\n type Capability,\n type CapabilityMutationResult,\n type CapabilityReadResult,\n type ConnectorAdapter,\n type ConnectorCredentials,\n type ConnectorInvocation,\n CredentialsExpired,\n} from '../types.js'\n\nexport type RestCredentialPlacement =\n | { kind: 'bearer' }\n | { kind: 'header'; header: string; prefix?: string }\n | { kind: 'query'; parameter: string }\n\nexport interface RestConnectorSpec {\n kind: string\n displayName: string\n description: string\n auth: ConnectorAdapter['manifest']['auth']\n category: ConnectorAdapter['manifest']['category']\n defaultConsistencyModel: ConnectorAdapter['manifest']['defaultConsistencyModel']\n baseUrl: string | { metadataKey: string; fallback?: string }\n credentialPlacement?: RestCredentialPlacement\n defaultHeaders?: Record<string, string>\n capabilities: RestOperationSpec[]\n test?: RestRequestSpec\n}\n\nexport interface RestOperationSpec {\n name: string\n class: 'read' | 'mutation'\n description: string\n parameters: Record<string, unknown>\n requiredScopes?: string[]\n request: RestRequestSpec\n cas?: 'etag-if-match' | 'native-idempotency' | 'optimistic-read-verify' | 'none'\n externalEffect?: boolean\n}\n\nexport interface RestRequestSpec {\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?: 'args' | string | Record<string, unknown>\n}\n\nexport function declarativeRestConnector(spec: RestConnectorSpec): ConnectorAdapter {\n const capabilities = spec.capabilities.map(operationToCapability)\n const adapter: ConnectorAdapter = {\n manifest: {\n kind: spec.kind,\n displayName: spec.displayName,\n description: spec.description,\n auth: spec.auth,\n category: spec.category,\n defaultConsistencyModel: spec.defaultConsistencyModel,\n capabilities,\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const op = readOperation(spec, inv.capabilityName, 'read')\n const response = await executeRestRequest(spec, op.request, inv)\n return {\n data: response.data,\n etag: response.etag,\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const op = readOperation(spec, inv.capabilityName, 'mutation')\n const response = await executeRestRequest(spec, op.request, inv)\n return {\n status: 'committed',\n data: response.data,\n etagAfter: response.etag,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async test(source) {\n if (!spec.test) return { ok: true }\n try {\n await executeRestRequest(spec, spec.test, {\n source,\n capabilityName: '__test__',\n args: {},\n idempotencyKey: 'test',\n })\n return { ok: true }\n } catch (error) {\n return { ok: false, reason: error instanceof Error ? error.message : 'unknown error' }\n }\n },\n }\n return adapter\n}\n\nfunction operationToCapability(op: RestOperationSpec): Capability {\n const base = {\n name: op.name,\n description: op.description,\n parameters: op.parameters,\n requiredScopes: op.requiredScopes,\n }\n if (op.class === 'read') {\n return { ...base, class: 'read' }\n }\n return {\n ...base,\n class: 'mutation',\n cas: op.cas ?? 'native-idempotency',\n externalEffect: op.externalEffect ?? true,\n }\n}\n\nfunction readOperation(spec: RestConnectorSpec, name: string, expected: 'read' | 'mutation'): RestOperationSpec {\n const op = spec.capabilities.find((candidate) => candidate.name === name)\n if (!op || op.class !== expected) {\n throw new Error(`${spec.kind}: unknown ${expected} capability ${name}`)\n }\n return op\n}\n\nasync function executeRestRequest(\n spec: RestConnectorSpec,\n request: RestRequestSpec,\n inv: ConnectorInvocation,\n): Promise<{ data: unknown; etag?: string }> {\n const baseUrl = resolveBaseUrl(spec.baseUrl, inv.source.metadata)\n const url = new URL(interpolate(request.path, inv.args), baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`)\n for (const [key, value] of Object.entries(request.query ?? {})) {\n const rendered = renderQueryValue(value, inv.args)\n if (rendered !== undefined && rendered !== '') url.searchParams.set(key, String(rendered))\n }\n const headers: Record<string, string> = {\n accept: 'application/json',\n ...spec.defaultHeaders,\n ...renderHeaders(request.headers ?? {}, inv.args),\n }\n applyCredentials(headers, url, spec.credentialPlacement ?? { kind: 'bearer' }, inv.source.credentials)\n if (inv.expectedEtag) headers['if-match'] = inv.expectedEtag\n if (request.method !== 'GET' && request.method !== 'DELETE') {\n headers['content-type'] = headers['content-type'] ?? 'application/json'\n }\n const res = await fetch(url, {\n method: request.method,\n headers,\n body: request.method === 'GET' || request.method === 'DELETE' ? undefined : JSON.stringify(resolveBody(request.body, inv.args)),\n signal: AbortSignal.timeout(20_000),\n })\n if (res.status === 401 || res.status === 403) {\n throw new CredentialsExpired(`${spec.displayName} rejected credentials (${res.status})`, inv.source.id)\n }\n if (res.status === 409 || res.status === 412) {\n return {\n data: {\n status: 'conflict',\n message: await safeErrorText(res),\n },\n etag: res.headers.get('etag') ?? undefined,\n }\n }\n if (res.status === 429) {\n return {\n data: {\n status: 'rate-limited',\n retryAfter: res.headers.get('retry-after') ?? undefined,\n message: await safeErrorText(res),\n },\n }\n }\n if (!res.ok) {\n throw new Error(`${spec.kind} ${request.method} ${url.pathname} HTTP ${res.status}: ${(await safeErrorText(res)).slice(0, 300)}`)\n }\n const text = await res.text()\n const data = text ? JSON.parse(text) as unknown : null\n return { data, etag: res.headers.get('etag') ?? undefined }\n}\n\nfunction resolveBaseUrl(baseUrl: RestConnectorSpec['baseUrl'], metadata: Record<string, unknown>): string {\n if (typeof baseUrl === 'string') return baseUrl\n const value = metadata[baseUrl.metadataKey]\n if (typeof value === 'string' && value.trim()) return value\n if (baseUrl.fallback) return baseUrl.fallback\n throw new Error(`missing metadata.${baseUrl.metadataKey} base URL`)\n}\n\nfunction applyCredentials(\n headers: Record<string, string>,\n url: URL,\n placement: RestCredentialPlacement,\n credentials: ConnectorCredentials,\n): void {\n const token = credentialToken(credentials)\n if (placement.kind === 'bearer') headers.authorization = `Bearer ${token}`\n if (placement.kind === 'header') headers[placement.header] = `${placement.prefix ?? ''}${token}`\n if (placement.kind === 'query') url.searchParams.set(placement.parameter, token)\n}\n\nfunction credentialToken(credentials: ConnectorCredentials): string {\n if (credentials.kind === 'oauth2') return credentials.accessToken\n if (credentials.kind === 'api-key') return credentials.apiKey\n throw new Error(`declarative REST connectors require oauth2 or api-key credentials, got ${credentials.kind}`)\n}\n\nfunction resolveBody(body: RestRequestSpec['body'], args: Record<string, unknown>): unknown {\n if (!body || body === 'args') return args\n if (typeof body === 'string') return renderValue(body, args)\n return renderObject(body, args)\n}\n\nfunction renderHeaders(headers: Record<string, string>, args: Record<string, unknown>): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, interpolate(value, args)]))\n}\n\nfunction renderObject(input: Record<string, unknown>, args: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, renderValue(value, args)]))\n}\n\nfunction renderValue(value: unknown, args: Record<string, unknown>): unknown {\n if (typeof value === 'string') {\n const exact = value.match(/^\\{([a-zA-Z0-9_.-]+)\\}$/)\n if (exact) return readRequiredPath(args, exact[1])\n return interpolate(value, args)\n }\n return value\n}\n\nfunction renderQueryValue(value: unknown, args: Record<string, unknown>): unknown {\n if (typeof value !== 'string') return value\n const exact = value.match(/^\\{([a-zA-Z0-9_.-]+)\\}$/)\n if (exact) return readPath(args, exact[1])\n try {\n return interpolate(value, args)\n } catch {\n return undefined\n }\n}\n\nfunction interpolate(template: string, args: Record<string, unknown>): string {\n return template.replace(/\\{([a-zA-Z0-9_.-]+)\\}/g, (_match, key: string) => {\n const value = readPath(args, key)\n if (value === undefined || value === null) {\n throw new Error(`missing required argument: ${key}`)\n }\n return encodeURIComponent(String(value))\n })\n}\n\nfunction readRequiredPath(input: Record<string, unknown>, path: string): unknown {\n const value = readPath(input, path)\n if (value === undefined || value === null) throw new Error(`missing required argument: ${path}`)\n return value\n}\n\nfunction readPath(input: Record<string, unknown>, path: string): unknown {\n return path.split('.').reduce<unknown>((value, part) => {\n if (value && typeof value === 'object' && part in value) {\n return (value as Record<string, unknown>)[part]\n }\n return undefined\n }, input)\n}\n\nasync function safeErrorText(res: Response): Promise<string> {\n return (await res.text().catch(() => res.statusText)) || res.statusText\n}\n","/**\n * Twilio SMS connector — outbound texts + recent-message lookup. The\n * agent's \"send the caller a confirmation link\" surface.\n *\n * Auth: HTTP Basic (Account SID + Auth Token). Twilio's API key auth\n * also supports SID/Secret pairs; we accept either by treating the\n * stored apiKey envelope as `accountSid:authToken` (or\n * `accountSid:keySid:secret`) — the connector parses it at call time.\n *\n * send_sms(to, body)\n * Mutation. CAS = native-idempotency. Twilio added the\n * `Idempotency-Key` HTTP header to POST /Messages in 2024 — same\n * key + same args within 24h returns the original Message resource\n * instead of sending a second SMS. MutationGuard's record short-\n * circuits before us; Twilio's own dedup is defense-in-depth.\n *\n * lookup_number(phoneNumber)\n * Read. Hits /v1/PhoneNumbers/{e164} on Lookup API. Confirms the\n * number is real, returns carrier info if the caller has Lookup\n * enabled on their account.\n *\n * find_recent_messages(toOrFrom?, limit?)\n * Read. Returns the most recent Messages on the account, optionally\n * filtered by To/From. Useful for \"did the confirmation actually\n * send?\" introspection inside an agent run.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\n\nconst API = 'https://api.twilio.com/2010-04-01'\nconst LOOKUP_API = 'https://lookups.twilio.com/v1'\n\nexport const twilioSmsConnector: ConnectorAdapter = {\n manifest: {\n kind: 'twilio-sms',\n displayName: 'Twilio SMS',\n description:\n \"Send outbound SMS, look up phone numbers, and audit recent messages. Twilio's native Idempotency-Key prevents duplicate sends on retry.\",\n auth: {\n kind: 'api-key',\n hint: 'Paste your Twilio credentials as \"AccountSid:AuthToken\" (e.g. \"AC123…:abc…\"). API-key style \"AccountSid:KeySid:Secret\" is also accepted.',\n },\n category: 'comms',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'send_sms',\n class: 'mutation',\n description: 'Send an SMS from the configured Twilio number to the supplied destination.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n to: { type: 'string', description: 'E.164 destination, e.g. +14155551212' },\n body: { type: 'string', description: 'Message body (≤1600 chars after Twilio segments).' },\n from: { type: 'string', description: 'Optional E.164 sender; falls back to metadata.fromNumber.' },\n },\n required: ['to', 'body'],\n },\n },\n {\n name: 'lookup_number',\n class: 'read',\n description: 'Validate a phone number and (if your account has Lookup) retrieve carrier metadata.',\n parameters: {\n type: 'object',\n properties: {\n phoneNumber: { type: 'string', description: 'E.164 number to look up.' },\n includeCarrier: { type: 'boolean', default: false },\n },\n required: ['phoneNumber'],\n },\n },\n {\n name: 'find_recent_messages',\n class: 'read',\n description: 'Return up to `limit` recent Messages on the account, optionally filtered by To or From.',\n parameters: {\n type: 'object',\n properties: {\n to: { type: 'string', description: 'Optional E.164 filter on the To address.' },\n from: { type: 'string', description: 'Optional E.164 filter on the From address.' },\n limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },\n },\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const auth = parseAuth(inv.source.credentials)\n if (inv.capabilityName === 'lookup_number') {\n const { phoneNumber, includeCarrier } = inv.args as { phoneNumber: string; includeCarrier?: boolean }\n const url = `${LOOKUP_API}/PhoneNumbers/${encodeURIComponent(phoneNumber)}${includeCarrier ? '?Type=carrier' : ''}`\n const res = await fetch(url, {\n headers: { authorization: basicAuth(auth) },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Twilio rejected credentials (401)', inv.source.id)\n if (res.status === 404) {\n return { data: { valid: false }, fetchedAt: Date.now() }\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`twilio-sms lookup_number ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as { phone_number?: string; carrier?: unknown; country_code?: string }\n return {\n data: {\n valid: true,\n phoneNumber: json.phone_number,\n countryCode: json.country_code,\n carrier: json.carrier,\n },\n fetchedAt: Date.now(),\n }\n }\n if (inv.capabilityName === 'find_recent_messages') {\n const { to, from, limit } = inv.args as { to?: string; from?: string; limit?: number }\n const params = new URLSearchParams()\n params.set('PageSize', String(Math.min(Math.max(1, limit ?? 20), 100)))\n if (to) params.set('To', to)\n if (from) params.set('From', from)\n const url = `${API}/Accounts/${encodeURIComponent(auth.accountSid)}/Messages.json?${params.toString()}`\n const res = await fetch(url, {\n headers: { authorization: basicAuth(auth) },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Twilio rejected credentials (401)', inv.source.id)\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`twilio-sms find_recent_messages ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n messages?: Array<{ sid: string; to: string; from: string; body: string; status: string; date_sent?: string }>\n }\n return {\n data: { messages: json.messages ?? [] },\n fetchedAt: Date.now(),\n }\n }\n throw new Error(`twilio-sms: unknown read capability ${inv.capabilityName}`)\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n if (inv.capabilityName !== 'send_sms') {\n throw new Error(`twilio-sms: unknown mutation capability ${inv.capabilityName}`)\n }\n const auth = parseAuth(inv.source.credentials)\n const { to, body, from } = inv.args as { to: string; body: string; from?: string }\n const fromNumber = from ?? readMetaString(inv.source.metadata, 'fromNumber')\n const formBody = new URLSearchParams({ To: to, From: fromNumber, Body: body })\n const url = `${API}/Accounts/${encodeURIComponent(auth.accountSid)}/Messages.json`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n authorization: basicAuth(auth),\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': inv.idempotencyKey,\n },\n body: formBody,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Twilio rejected credentials (401)', inv.source.id)\n if (res.status === 409) {\n // Twilio surfaces 409 when an idempotency-key conflict is detected\n // (same key, different request body).\n throw new ResourceContention('Twilio idempotency-key conflict — different args under same key')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`twilio-sms send_sms ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as {\n sid: string\n status: string\n to: string\n from: string\n date_sent?: string\n }\n return {\n status: 'committed',\n data: { messageSid: created.sid, deliveryStatus: created.status, to: created.to, from: created.from },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async test(source) {\n try {\n const auth = parseAuth(source.credentials)\n // GET /Accounts/{sid}.json is the cheapest auth probe.\n const res = await fetch(`${API}/Accounts/${encodeURIComponent(auth.accountSid)}.json`, {\n headers: { authorization: basicAuth(auth) },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401) return { ok: false, reason: 'Twilio rejected credentials (401) — reconnect required' }\n if (!res.ok) return { ok: false, reason: `Twilio returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n}\n\ninterface TwilioAuth {\n accountSid: string\n /** Either the Account auth token, or an API key SID. */\n username: string\n /** Either the same auth token, or the API key secret. */\n password: string\n}\n\nfunction parseAuth(creds: { kind: string; apiKey?: string }): TwilioAuth {\n if (creds.kind !== 'api-key' || typeof creds.apiKey !== 'string') {\n throw new Error('twilio-sms: expected api-key credentials')\n }\n const parts = creds.apiKey.split(':')\n if (parts.length === 2) {\n // accountSid:authToken — username is the SID, password is the token.\n const [accountSid, authToken] = parts\n if (!accountSid.startsWith('AC')) {\n throw new Error('twilio-sms: AccountSid must start with \"AC\"')\n }\n return { accountSid, username: accountSid, password: authToken }\n }\n if (parts.length === 3) {\n // accountSid:apiKeySid:apiKeySecret — basic-auth username is the\n // API key SID, not the AccountSid.\n const [accountSid, keySid, secret] = parts\n if (!accountSid.startsWith('AC')) {\n throw new Error('twilio-sms: AccountSid must start with \"AC\"')\n }\n return { accountSid, username: keySid, password: secret }\n }\n throw new Error('twilio-sms: apiKey must be \"AccountSid:AuthToken\" or \"AccountSid:KeySid:Secret\"')\n}\n\nfunction basicAuth(auth: TwilioAuth): string {\n return `Basic ${Buffer.from(`${auth.username}:${auth.password}`).toString('base64')}`\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`twilio-sms DataSource.metadata.${key} is missing`)\n }\n return v\n}\n","/**\n * Stripe pack connector — single connector kind packing 3 capabilities,\n * validating the \"connector pack\" concept (one auth handshake, multiple\n * related capabilities) without exploding the registry into\n * `stripe-customers`, `stripe-checkout`, `stripe-invoices` triplets.\n *\n * find_customer(email) → read; CAS n/a\n * create_invoice(customerId, items) → mutation; cas: 'native-idempotency'\n * create_checkout_session(...) → mutation; cas: 'native-idempotency'\n *\n * Auth: API key (Stripe restricted key). Operator pastes the key into\n * the Connections UI. We never see their account password / OAuth flow;\n * Stripe restricted keys are the customer's responsibility (they pick\n * which permissions the key carries). The kind exposes a webhook URL\n * post-connect for the operator to paste into the Stripe dashboard —\n * we'll wire the receiver to P-3's inbound webhook surface in a later\n * commit. That URL is returned in `metadata.webhookUrl` so the UI can\n * render it.\n *\n * Why this is the textbook example of `cas: 'native-idempotency'`:\n * Stripe's `Idempotency-Key` HTTP header is THE reference implementation\n * of native idempotency. Same key + same args within 24h returns the\n * stored response (Stripe's words, not ours). Same key + different args\n * → 400 with `idempotency_error`. We forward the SDK's idempotency key\n * directly. MutationGuard short-circuits before us on retry; Stripe's\n * own dedup is the second line of defense.\n */\n\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n ResourceContention,\n CredentialsExpired,\n} from '../types.js'\n\nconst API = 'https://api.stripe.com/v1'\n\nexport const stripePackConnector: ConnectorAdapter = {\n manifest: {\n kind: 'stripe-pack',\n displayName: 'Stripe (customers, invoices, checkout)',\n description:\n \"Look up Stripe customers, draft invoices, and spin up hosted Checkout sessions from a single Stripe restricted key. Idempotency-Key forwarded on every mutation.\",\n auth: {\n kind: 'api-key',\n hint: 'Paste a Stripe restricted key (rk_live_…) with read access on customers and write access on invoices + checkout sessions.',\n },\n category: 'commerce',\n defaultConsistencyModel: 'authoritative',\n capabilities: [\n {\n name: 'find_customer',\n class: 'read',\n description: 'Search Stripe customers by email. Returns the first match or {found:false}.',\n parameters: {\n type: 'object',\n properties: { email: { type: 'string' } },\n required: ['email'],\n },\n },\n {\n name: 'create_invoice',\n class: 'mutation',\n description:\n 'Draft + finalize a Stripe invoice for a customer with line items. Idempotency-Key guarantees at-most-once.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n customerId: { type: 'string' },\n items: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n description: { type: 'string' },\n amount: { type: 'integer', description: 'Amount in the smallest currency unit (cents).' },\n currency: { type: 'string', description: '3-letter ISO currency code, lowercase.' },\n quantity: { type: 'integer', minimum: 1, default: 1 },\n },\n required: ['amount', 'currency'],\n },\n },\n autoFinalize: { type: 'boolean', default: true },\n },\n required: ['customerId', 'items'],\n },\n },\n {\n name: 'create_checkout_session',\n class: 'mutation',\n description:\n 'Create a Stripe Checkout session and return its hosted URL. Idempotency-Key guarantees at-most-once.',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n properties: {\n customerId: { type: 'string' },\n mode: { type: 'string', enum: ['payment', 'subscription'], default: 'payment' },\n successUrl: { type: 'string' },\n cancelUrl: { type: 'string' },\n lineItems: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n price: { type: 'string', description: 'Stripe price id (price_...)' },\n quantity: { type: 'integer', minimum: 1, default: 1 },\n },\n required: ['price'],\n },\n },\n },\n required: ['successUrl', 'cancelUrl', 'lineItems'],\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n if (inv.capabilityName !== 'find_customer') {\n throw new Error(`stripe-pack: unknown read capability ${inv.capabilityName}`)\n }\n const apiKey = readApiKey(inv.source.credentials)\n const { email } = inv.args as { email: string }\n // Stripe's /customers/search is the canonical email lookup. Falls\n // back to /customers?email= for accounts on legacy Search-disabled\n // tier — most accounts have Search enabled by default in 2024+.\n const url = `${API}/customers/search?query=${encodeURIComponent(`email:'${email.toLowerCase()}'`)}&limit=1`\n const res = await fetch(url, {\n headers: { authorization: `Bearer ${apiKey}` },\n signal: AbortSignal.timeout(10_000),\n })\n if (res.status === 401) {\n throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe-pack find_customer ${res.status}: ${text.slice(0, 200)}`)\n }\n const json = (await res.json()) as {\n data?: Array<{ id: string; email?: string; name?: string; phone?: string }>\n }\n const first = json.data?.[0]\n return {\n data: first\n ? { found: true, customer: { id: first.id, email: first.email, name: first.name, phone: first.phone } }\n : { found: false },\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const apiKey = readApiKey(inv.source.credentials)\n if (inv.capabilityName === 'create_invoice') return createInvoice(inv, apiKey)\n if (inv.capabilityName === 'create_checkout_session') return createCheckoutSession(inv, apiKey)\n throw new Error(`stripe-pack: unknown mutation capability ${inv.capabilityName}`)\n },\n\n async test(source) {\n try {\n const apiKey = readApiKey(source.credentials)\n // /v1/account is the cheapest grant-validity probe.\n const res = await fetch(`${API}/account`, {\n headers: { authorization: `Bearer ${apiKey}` },\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status === 401) {\n return { ok: false, reason: 'Stripe rejected API key (401) — reconnect required' }\n }\n if (!res.ok) return { ok: false, reason: `Stripe returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n}\n\nasync function createInvoice(inv: ConnectorInvocation, apiKey: string): Promise<CapabilityMutationResult> {\n const { customerId, items, autoFinalize } = inv.args as {\n customerId: string\n items: Array<{ description?: string; amount: number; currency: string; quantity?: number }>\n autoFinalize?: boolean\n }\n // Stripe requires invoiceitem.create BEFORE invoice.create. We do\n // both under the same idempotency-key prefix so retries are exactly\n // replayed across both calls.\n const idemKey = inv.idempotencyKey\n for (let i = 0; i < items.length; i++) {\n const it = items[i]\n const body = new URLSearchParams({\n customer: customerId,\n amount: String(it.amount),\n currency: it.currency.toLowerCase(),\n quantity: String(it.quantity ?? 1),\n })\n if (it.description) body.set('description', it.description)\n const res = await fetch(`${API}/invoiceitems`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': `${idemKey}-item-${i}`,\n },\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n if (res.status === 409) {\n throw new ResourceContention('Stripe invoiceitem conflict — retry rejected by idempotency check')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe-pack create_invoice (item ${i}) ${res.status}: ${text.slice(0, 200)}`)\n }\n }\n\n const invBody = new URLSearchParams({\n customer: customerId,\n auto_advance: autoFinalize === false ? 'false' : 'true',\n collection_method: 'send_invoice',\n days_until_due: '14',\n })\n const invRes = await fetch(`${API}/invoices`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': `${idemKey}-invoice`,\n },\n body: invBody,\n signal: AbortSignal.timeout(15_000),\n })\n if (invRes.status === 401) throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n if (invRes.status === 409) {\n throw new ResourceContention('Stripe invoice conflict — retry rejected by idempotency check')\n }\n if (!invRes.ok) {\n const text = await invRes.text().catch(() => '')\n throw new Error(`stripe-pack create_invoice ${invRes.status}: ${text.slice(0, 200)}`)\n }\n const created = (await invRes.json()) as { id: string; hosted_invoice_url?: string; status?: string }\n return {\n status: 'committed',\n data: { invoiceId: created.id, hostedInvoiceUrl: created.hosted_invoice_url, status: created.status },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nasync function createCheckoutSession(\n inv: ConnectorInvocation,\n apiKey: string,\n): Promise<CapabilityMutationResult> {\n const { customerId, mode, successUrl, cancelUrl, lineItems } = inv.args as {\n customerId?: string\n mode?: 'payment' | 'subscription'\n successUrl: string\n cancelUrl: string\n lineItems: Array<{ price: string; quantity?: number }>\n }\n const body = new URLSearchParams({\n mode: mode ?? 'payment',\n success_url: successUrl,\n cancel_url: cancelUrl,\n })\n if (customerId) body.set('customer', customerId)\n lineItems.forEach((it, i) => {\n body.set(`line_items[${i}][price]`, it.price)\n body.set(`line_items[${i}][quantity]`, String(it.quantity ?? 1))\n })\n const res = await fetch(`${API}/checkout/sessions`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${apiKey}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'idempotency-key': inv.idempotencyKey,\n },\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 401) throw new CredentialsExpired('Stripe rejected API key (401)', inv.source.id)\n if (res.status === 409) {\n throw new ResourceContention('Stripe checkout session conflict — retry rejected by idempotency check')\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new Error(`stripe-pack create_checkout_session ${res.status}: ${text.slice(0, 200)}`)\n }\n const created = (await res.json()) as { id: string; url?: string; payment_status?: string }\n return {\n status: 'committed',\n data: { sessionId: created.id, url: created.url, paymentStatus: created.payment_status },\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n}\n\nfunction readApiKey(creds: { kind: string; apiKey?: string }): string {\n if (creds.kind !== 'api-key' || typeof creds.apiKey !== 'string' || creds.apiKey.length === 0) {\n throw new Error('stripe-pack: expected api-key credentials')\n }\n return creds.apiKey\n}\n","/**\n * Universal webhook connector — the long-tail escape hatch.\n *\n * The user declares a target URL + a JSON-schema for the request body\n * the agent should send, plus an optional shared secret. We sign every\n * outbound POST with HMAC-SHA256 over `timestamp.body` and forward the\n * agent's idempotency key as a header. The receiving system enforces\n * its own idempotency.\n *\n * One adapter, two capabilities. Both arity-1 — `body` is whatever JSON\n * the agent's planner constructs from the operator-defined schema (which\n * lives in DataSource.metadata.requestSchema). The agent's planner reads\n * that schema at request time and constructs valid args.\n *\n * Why one connector covers 50 systems badly and 1 system well: the agent\n * gets a generic \"send_event\" tool that doesn't *know* what the upstream\n * does with the payload. That's fine for fire-and-forget event posting\n * (Zapier-style); it's wrong for booking against a calendar where you\n * need conflict-resolution. So webhook's `post_event` capability is\n * marked `cas: 'native-idempotency'` (we forward the key — the receiver\n * MUST honor it) and `defaultConsistencyModel: 'advisory'`. Anyone\n * needing real CAS uses a kind-specific connector (Calendar, Sheets, ...).\n */\n\nimport { createHmac } from 'crypto'\nimport {\n type ConnectorAdapter,\n type ConnectorInvocation,\n type CapabilityReadResult,\n type CapabilityMutationResult,\n} from '../types.js'\n\nexport const webhookConnector: ConnectorAdapter = {\n manifest: {\n kind: 'webhook',\n displayName: 'Webhook (custom URL)',\n description:\n \"Fire signed HTTP POSTs from your agent to any URL you control. The escape hatch when there's no native connector — receive the agent's intent, run your own logic, return a result.\",\n auth: { kind: 'hmac' },\n category: 'webhook',\n defaultConsistencyModel: 'advisory',\n capabilities: [\n {\n name: 'post_event',\n class: 'mutation',\n description:\n 'Send a JSON event to the configured webhook URL. The receiver SHOULD return 200 on accept and 409 on conflict (the agent will offer alternatives if you include them in the response).',\n cas: 'native-idempotency',\n externalEffect: true,\n parameters: {\n type: 'object',\n additionalProperties: true,\n description: 'Whatever JSON the operator declared at connect time. The DataSource.metadata.requestSchema is the source of truth at runtime.',\n },\n },\n {\n name: 'fetch_state',\n class: 'read',\n description: 'GET the configured webhook URL with the agent-supplied query params. Returns whatever JSON the receiver responds with.',\n parameters: {\n type: 'object',\n additionalProperties: true,\n },\n },\n ],\n },\n\n async executeRead(inv: ConnectorInvocation): Promise<CapabilityReadResult> {\n const url = readMetaString(inv.source.metadata, 'url')\n const params = inv.args && typeof inv.args === 'object' ? inv.args : {}\n const u = new URL(url)\n for (const [k, v] of Object.entries(params)) {\n u.searchParams.set(k, typeof v === 'string' ? v : JSON.stringify(v))\n }\n const res = await fetch(u.toString(), {\n method: 'GET',\n headers: signHeaders(inv.source.credentials, '', inv.idempotencyKey),\n signal: AbortSignal.timeout(15_000),\n })\n if (!res.ok) {\n throw new Error(`webhook fetch_state ${res.status}: ${(await res.text()).slice(0, 200)}`)\n }\n const data = (await res.json()) as unknown\n return {\n data,\n etag: res.headers.get('etag') ?? undefined,\n fetchedAt: Date.now(),\n }\n },\n\n async executeMutation(inv: ConnectorInvocation): Promise<CapabilityMutationResult> {\n const url = readMetaString(inv.source.metadata, 'url')\n const body = JSON.stringify(inv.args ?? {})\n const res = await fetch(url, {\n method: 'POST',\n headers: signHeaders(inv.source.credentials, body, inv.idempotencyKey),\n body,\n signal: AbortSignal.timeout(15_000),\n })\n if (res.status === 409) {\n // Conflict by convention — receiver returns alternatives in the body.\n const json = (await res.json().catch(() => ({}))) as { alternatives?: unknown[]; message?: string }\n return {\n status: 'conflict',\n alternatives: json.alternatives ?? [],\n message: json.message ?? 'webhook receiver returned 409',\n }\n }\n if (!res.ok) {\n throw new Error(`webhook post_event ${res.status}: ${(await res.text()).slice(0, 200)}`)\n }\n const data = (await res.json().catch(() => ({}))) as unknown\n return {\n status: 'committed',\n data,\n etagAfter: res.headers.get('etag') ?? undefined,\n committedAt: Date.now(),\n idempotentReplay: false,\n }\n },\n\n async test(source) {\n try {\n const url = readMetaString(source.metadata, 'url')\n // HEAD if the receiver supports it, otherwise GET. Either way a\n // non-5xx response counts as healthy — we don't validate semantics.\n const res = await fetch(url, {\n method: 'HEAD',\n headers: signHeaders(source.credentials, '', `health-${Date.now()}`),\n signal: AbortSignal.timeout(8_000),\n })\n if (res.status >= 500) return { ok: false, reason: `webhook returned ${res.status}` }\n return { ok: true }\n } catch (err) {\n return { ok: false, reason: err instanceof Error ? err.message : String(err) }\n }\n },\n}\n\nfunction readMetaString(meta: Record<string, unknown>, key: string): string {\n const v = meta[key]\n if (typeof v !== 'string' || v.length === 0) {\n throw new Error(`webhook DataSource.metadata.${key} is missing`)\n }\n return v\n}\n\nfunction signHeaders(\n creds: { kind: string; secret?: string; [k: string]: unknown },\n body: string,\n idempotencyKey: string,\n): Record<string, string> {\n const ts = Math.floor(Date.now() / 1000).toString()\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'x-phony-timestamp': ts,\n 'x-phony-idempotency-key': idempotencyKey,\n }\n if (creds.kind === 'hmac' && typeof creds.secret === 'string' && creds.secret.length > 0) {\n const sig = createHmac('sha256', creds.secret).update(`${ts}.${body}`).digest('hex')\n headers['x-phony-signature'] = `sha256=${sig}`\n }\n return headers\n}\n","/**\n * Stripe inbound-webhook receiver — push-only side of a Stripe connector.\n *\n * The full Stripe connector (charges/customers/invoices read+mutation) is\n * tracked in INTEGRATIONS.md as separate `stripe-customers` / `stripe-invoices`\n * rows. This adapter only ships the inbound surface today: receive a push,\n * verify the signature, persist one `InboundEvent` per Stripe event so the\n * agent's runtime can react (e.g. payment_failed → outbound dunning call).\n *\n * Why a dedicated `kind: 'stripe'` rather than reusing the billing webhook\n * at /api/billing/stripe-webhook: that route is hard-coded for OUR Stripe\n * account (Builder subscription state). This connector is for the customer's\n * OWN Stripe account — they paste their `whsec_*` and we listen on a\n * per-DataSource URL, /api/webhooks/inbound/stripe/:dataSourceId.\n *\n * Signature scheme: Stripe's `t=<unix>,v1=<hmac>` header. HMAC is\n * sha256(`${t}.${rawBody}`) keyed by the customer's webhook secret. We use\n * `timingSafeEqual` to defeat timing oracles and bound timestamp skew at\n * 5 minutes (Stripe's recommendation) to thwart replay against captured\n * signatures.\n */\n\nimport {\n type ConnectorAdapter,\n type EventHandlerResult,\n type InboundEvent,\n} from '../types.js'\nimport { firstHeader, verifyStripeSignature } from '../webhooks.js'\n\nexport const stripeWebhookReceiverConnector: ConnectorAdapter = {\n manifest: {\n kind: 'stripe',\n displayName: 'Stripe (inbound events)',\n description:\n \"Receive Stripe webhook events from your own Stripe account. Paste your endpoint signing secret (whsec_*) at connect time; we'll verify every push and feed events to your agent's runtime.\",\n auth: { kind: 'hmac' },\n category: 'commerce',\n // Inbound-only. Stripe events are advisory in this incarnation — the\n // agent reacts to them but doesn't compete for writes against the same\n // resource.\n defaultConsistencyModel: 'advisory',\n capabilities: [],\n },\n\n verifySignature({ rawBody, headers, source }) {\n if (source.credentials.kind !== 'hmac') return { valid: false, reason: 'missing_hmac_secret' }\n const sig = firstHeader(headers, 'stripe-signature')\n if (!sig) return { valid: false, reason: 'missing_stripe_signature_header' }\n const ok = verifyStripeSignature(rawBody, sig, source.credentials.secret)\n return ok ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n\n async handleInboundEvent({ rawBody }): Promise<EventHandlerResult> {\n let parsed: unknown\n try {\n parsed = JSON.parse(rawBody)\n } catch {\n return { events: [], response: { status: 400, body: { error: 'invalid_json' } } }\n }\n if (!parsed || typeof parsed !== 'object') {\n return { events: [], response: { status: 400, body: { error: 'invalid_payload' } } }\n }\n const evt = parsed as { id?: unknown; type?: unknown; data?: unknown; created?: unknown }\n const eventType = typeof evt.type === 'string' ? evt.type : 'stripe.unknown'\n const providerEventId = typeof evt.id === 'string' ? evt.id : undefined\n const events: InboundEvent[] = [\n {\n eventType,\n providerEventId,\n payload: evt as Record<string, unknown>,\n },\n ]\n return { events }\n },\n\n async test(source) {\n if (source.credentials.kind !== 'hmac' || !source.credentials.secret) {\n return { ok: false, reason: 'webhook secret not configured' }\n }\n return { ok: true }\n },\n}\n","/**\n * Slack Events API inbound receiver.\n *\n * Slack sends two distinct request shapes to the same webhook URL:\n *\n * 1. `url_verification` — a one-off handshake during app-config. The body\n * contains a `challenge` string we MUST echo back as the response body\n * (Slack's app-config UI fails the URL otherwise). No InboundEvent is\n * persisted for this — it's an infrastructure ping, not a user event.\n *\n * 2. `event_callback` — every actual workspace event (message posted,\n * reaction added, channel created, …). We persist one InboundEvent\n * keyed by `event_id` so a Slack retry (Slack retries 3 times on any\n * non-2xx) is deduped at the unique constraint, not after we've\n * double-processed.\n *\n * Signature scheme: `v0=<hmac(sha256, \"v0:<timestamp>:<rawBody>\")>` keyed by\n * the app's signing secret. Header `X-Slack-Request-Timestamp` carries the\n * timestamp; we reject anything older than 5 minutes (Slack's recommendation)\n * to bound replay risk.\n */\n\nimport {\n type ConnectorAdapter,\n type EventHandlerResult,\n type InboundEvent,\n} from '../types.js'\nimport { firstHeader, verifySlackSignature } from '../webhooks.js'\n\nexport const slackEventsConnector: ConnectorAdapter = {\n manifest: {\n // NOTE: `slack` is owned by the OAuth bot connector in slack.ts (post_message,\n // lookup_user, list_channels). This adapter is the HMAC-only inbound-events\n // sibling — distinct kind so a customer can stand up the Events API receiver\n // without granting bot OAuth, and so the registry doesn't reject duplicate\n // kinds at boot.\n kind: 'slack-inbound',\n displayName: 'Slack (Events API)',\n description:\n \"Receive workspace events (messages, reactions, app mentions, …) from Slack's Events API. Outbound bot messaging will land in a follow-up.\",\n auth: { kind: 'hmac' },\n category: 'comms',\n // Inbound-only. Events are advisory in this incarnation — agents observe\n // and react, no CAS.\n defaultConsistencyModel: 'advisory',\n capabilities: [],\n },\n\n verifySignature({ rawBody, headers, source }) {\n if (source.credentials.kind !== 'hmac') return { valid: false, reason: 'missing_hmac_secret' }\n const sig = firstHeader(headers, 'x-slack-signature')\n const ts = firstHeader(headers, 'x-slack-request-timestamp')\n if (!sig || !ts) return { valid: false, reason: 'missing_slack_headers' }\n const ok = verifySlackSignature(rawBody, sig, ts, source.credentials.secret)\n return ok ? { valid: true } : { valid: false, reason: 'invalid_signature' }\n },\n\n async handleInboundEvent({ rawBody }): Promise<EventHandlerResult> {\n let parsed: unknown\n try {\n parsed = JSON.parse(rawBody)\n } catch {\n return { events: [], response: { status: 400, body: { error: 'invalid_json' } } }\n }\n if (!parsed || typeof parsed !== 'object') {\n return { events: [], response: { status: 400, body: { error: 'invalid_payload' } } }\n }\n const obj = parsed as Record<string, unknown>\n\n // Handshake: echo the challenge. No event persisted.\n if (obj.type === 'url_verification') {\n const challenge = typeof obj.challenge === 'string' ? obj.challenge : ''\n return {\n events: [],\n response: { status: 200, body: { challenge } },\n }\n }\n\n // Workspace event: persist one row keyed by Slack's event_id.\n if (obj.type === 'event_callback') {\n const inner = obj.event\n const innerType =\n inner && typeof inner === 'object' && 'type' in inner && typeof (inner as { type?: unknown }).type === 'string'\n ? (inner as { type: string }).type\n : 'slack.event'\n const providerEventId = typeof obj.event_id === 'string' ? obj.event_id : undefined\n const event: InboundEvent = {\n eventType: `slack.${innerType}`,\n providerEventId,\n payload: obj,\n }\n return { events: [event] }\n }\n\n // Unknown envelope (Slack adds new top-level types occasionally) — ack\n // so Slack stops retrying, but don't persist a malformed row.\n return { events: [] }\n },\n\n async test(source) {\n if (source.credentials.kind !== 'hmac' || !source.credentials.secret) {\n return { ok: false, reason: 'signing secret not configured' }\n }\n return { ok: true }\n },\n}\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nconst repoParams = {\n type: 'object',\n properties: {\n owner: { type: 'string' },\n repo: { type: 'string' },\n },\n required: ['owner', 'repo'],\n}\n\nexport const githubConnector = declarativeRestConnector({\n kind: 'github',\n displayName: 'GitHub',\n description: 'Search repositories/issues and create or update GitHub issues through a user-scoped token.',\n auth: { kind: 'api-key', hint: 'GitHub fine-grained personal access token or installation token.' },\n category: 'other',\n defaultConsistencyModel: 'authoritative',\n baseUrl: 'https://api.github.com',\n defaultHeaders: {\n 'x-github-api-version': '2022-11-28',\n },\n test: { method: 'GET', path: '/user' },\n capabilities: [\n {\n name: 'repositories.get',\n class: 'read',\n description: 'Read repository metadata.',\n parameters: repoParams,\n request: { method: 'GET', path: '/repos/{owner}/{repo}' },\n },\n {\n name: 'issues.search',\n class: 'read',\n description: 'Search GitHub issues and pull requests.',\n parameters: {\n type: 'object',\n properties: { q: { type: 'string' }, per_page: { type: 'integer', minimum: 1, maximum: 100 } },\n required: ['q'],\n },\n request: { method: 'GET', path: '/search/issues', query: { q: '{q}', per_page: '{per_page}' } },\n },\n {\n name: 'issues.create',\n class: 'mutation',\n description: 'Create an issue in a repository.',\n parameters: {\n type: 'object',\n properties: {\n owner: { type: 'string' },\n repo: { type: 'string' },\n title: { type: 'string' },\n body: { type: 'string' },\n labels: { type: 'array', items: { type: 'string' } },\n },\n required: ['owner', 'repo', 'title'],\n },\n request: { method: 'POST', path: '/repos/{owner}/{repo}/issues', body: 'args' },\n cas: 'native-idempotency',\n },\n {\n name: 'issues.update',\n class: 'mutation',\n description: 'Update an issue by number.',\n parameters: {\n type: 'object',\n properties: {\n owner: { type: 'string' },\n repo: { type: 'string' },\n issue_number: { type: 'integer' },\n title: { type: 'string' },\n body: { type: 'string' },\n state: { type: 'string', enum: ['open', 'closed'] },\n },\n required: ['owner', 'repo', 'issue_number'],\n },\n request: { method: 'PATCH', path: '/repos/{owner}/{repo}/issues/{issue_number}', body: 'args' },\n cas: 'etag-if-match',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nexport const gitlabConnector = declarativeRestConnector({\n kind: 'gitlab',\n displayName: 'GitLab',\n description: 'Search GitLab projects/issues and create or update issues through a personal, project, or group token.',\n auth: { kind: 'api-key', hint: 'GitLab access token with api/read_api scope.' },\n category: 'other',\n defaultConsistencyModel: 'authoritative',\n baseUrl: { metadataKey: 'baseUrl', fallback: 'https://gitlab.com/api/v4' },\n credentialPlacement: { kind: 'header', header: 'PRIVATE-TOKEN' },\n test: { method: 'GET', path: '/user' },\n capabilities: [\n {\n name: 'projects.search',\n class: 'read',\n description: 'Search projects visible to the token.',\n parameters: {\n type: 'object',\n properties: { search: { type: 'string' }, per_page: { type: 'integer', minimum: 1, maximum: 100 } },\n required: ['search'],\n },\n request: { method: 'GET', path: '/projects', query: { search: '{search}', per_page: '{per_page}' } },\n },\n {\n name: 'issues.search',\n class: 'read',\n description: 'Search issues in a project.',\n parameters: {\n type: 'object',\n properties: { projectId: { type: 'string' }, search: { type: 'string' }, per_page: { type: 'integer' } },\n required: ['projectId', 'search'],\n },\n request: { method: 'GET', path: '/projects/{projectId}/issues', query: { search: '{search}', per_page: '{per_page}' } },\n },\n {\n name: 'issues.create',\n class: 'mutation',\n description: 'Create a GitLab project issue.',\n parameters: {\n type: 'object',\n properties: { projectId: { type: 'string' }, title: { type: 'string' }, description: { type: 'string' } },\n required: ['projectId', 'title'],\n },\n request: { method: 'POST', path: '/projects/{projectId}/issues', body: 'args' },\n cas: 'native-idempotency',\n },\n {\n name: 'issues.update',\n class: 'mutation',\n description: 'Update a GitLab issue.',\n parameters: {\n type: 'object',\n properties: { projectId: { type: 'string' }, issueIid: { type: 'integer' }, title: { type: 'string' }, description: { type: 'string' }, state_event: { type: 'string' } },\n required: ['projectId', 'issueIid'],\n },\n request: { method: 'PUT', path: '/projects/{projectId}/issues/{issueIid}', body: 'args' },\n cas: 'etag-if-match',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nconst baseTableParams = {\n type: 'object',\n properties: {\n baseId: { type: 'string' },\n tableName: { type: 'string' },\n },\n required: ['baseId', 'tableName'],\n}\n\nexport const airtableConnector = declarativeRestConnector({\n kind: 'airtable',\n displayName: 'Airtable',\n description: 'Query and update Airtable records for lightweight operational databases.',\n auth: { kind: 'api-key', hint: 'Airtable personal access token.' },\n category: 'spreadsheet',\n defaultConsistencyModel: 'authoritative',\n baseUrl: 'https://api.airtable.com',\n test: { method: 'GET', path: '/v0/meta/whoami' },\n capabilities: [\n {\n name: 'records.list',\n class: 'read',\n description: 'List records in a table.',\n parameters: {\n ...baseTableParams,\n properties: {\n ...baseTableParams.properties,\n maxRecords: { type: 'integer', minimum: 1, maximum: 100 },\n filterByFormula: { type: 'string' },\n },\n },\n request: { method: 'GET', path: '/v0/{baseId}/{tableName}', query: { maxRecords: '{maxRecords}', filterByFormula: '{filterByFormula}' } },\n },\n {\n name: 'records.get',\n class: 'read',\n description: 'Read a single Airtable record.',\n parameters: {\n type: 'object',\n properties: { baseId: { type: 'string' }, tableName: { type: 'string' }, recordId: { type: 'string' } },\n required: ['baseId', 'tableName', 'recordId'],\n },\n request: { method: 'GET', path: '/v0/{baseId}/{tableName}/{recordId}' },\n },\n {\n name: 'records.create',\n class: 'mutation',\n description: 'Create an Airtable record.',\n parameters: {\n type: 'object',\n properties: { baseId: { type: 'string' }, tableName: { type: 'string' }, fields: { type: 'object' } },\n required: ['baseId', 'tableName', 'fields'],\n },\n request: { method: 'POST', path: '/v0/{baseId}/{tableName}', body: { fields: '{fields}' } },\n cas: 'native-idempotency',\n },\n {\n name: 'records.update',\n class: 'mutation',\n description: 'Update an Airtable record.',\n parameters: {\n type: 'object',\n properties: { baseId: { type: 'string' }, tableName: { type: 'string' }, recordId: { type: 'string' }, fields: { type: 'object' } },\n required: ['baseId', 'tableName', 'recordId', 'fields'],\n },\n request: { method: 'PATCH', path: '/v0/{baseId}/{tableName}/{recordId}', body: { fields: '{fields}' } },\n cas: 'optimistic-read-verify',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nexport const asanaConnector = declarativeRestConnector({\n kind: 'asana',\n displayName: 'Asana',\n description: 'Search projects/tasks and create or update Asana tasks.',\n auth: { kind: 'api-key', hint: 'Asana personal access token.' },\n category: 'other',\n defaultConsistencyModel: 'authoritative',\n baseUrl: 'https://app.asana.com/api/1.0',\n test: { method: 'GET', path: '/users/me' },\n capabilities: [\n {\n name: 'projects.search',\n class: 'read',\n description: 'List or search projects in a workspace.',\n parameters: {\n type: 'object',\n properties: { workspace: { type: 'string' }, archived: { type: 'boolean' }, limit: { type: 'integer' } },\n required: ['workspace'],\n },\n request: { method: 'GET', path: '/projects', query: { workspace: '{workspace}', archived: '{archived}', limit: '{limit}' } },\n },\n {\n name: 'tasks.search',\n class: 'read',\n description: 'Search tasks in a workspace.',\n parameters: {\n type: 'object',\n properties: { workspace: { type: 'string' }, text: { type: 'string' }, limit: { type: 'integer' } },\n required: ['workspace'],\n },\n request: { method: 'GET', path: '/workspaces/{workspace}/tasks/search', query: { text: '{text}', limit: '{limit}' } },\n },\n {\n name: 'tasks.create',\n class: 'mutation',\n description: 'Create an Asana task.',\n parameters: {\n type: 'object',\n properties: { data: { type: 'object' } },\n required: ['data'],\n },\n request: { method: 'POST', path: '/tasks', body: { data: '{data}' } },\n cas: 'native-idempotency',\n },\n {\n name: 'tasks.update',\n class: 'mutation',\n description: 'Update an Asana task.',\n parameters: {\n type: 'object',\n properties: { taskGid: { type: 'string' }, data: { type: 'object' } },\n required: ['taskGid', 'data'],\n },\n request: { method: 'PUT', path: '/tasks/{taskGid}', body: { data: '{data}' } },\n cas: 'optimistic-read-verify',\n },\n ],\n})\n","import { declarativeRestConnector } from './declarative-rest.js'\n\nexport const salesforceConnector = declarativeRestConnector({\n kind: 'salesforce',\n displayName: 'Salesforce',\n description: 'Query Salesforce records with SOQL and create or update sObjects.',\n auth: {\n kind: 'oauth2',\n authorizationUrl: 'https://login.salesforce.com/services/oauth2/authorize',\n tokenUrl: 'https://login.salesforce.com/services/oauth2/token',\n scopes: ['api', 'refresh_token'],\n clientIdEnv: 'SALESFORCE_OAUTH_CLIENT_ID',\n clientSecretEnv: 'SALESFORCE_OAUTH_CLIENT_SECRET',\n },\n category: 'crm',\n defaultConsistencyModel: 'authoritative',\n baseUrl: { metadataKey: 'instanceUrl' },\n test: { method: 'GET', path: '/services/data/v61.0/' },\n capabilities: [\n {\n name: 'records.query',\n class: 'read',\n description: 'Run a SOQL query.',\n parameters: {\n type: 'object',\n properties: { q: { type: 'string' } },\n required: ['q'],\n },\n request: { method: 'GET', path: '/services/data/v61.0/query', query: { q: '{q}' } },\n requiredScopes: ['api'],\n },\n {\n name: 'records.get',\n class: 'read',\n description: 'Read a Salesforce sObject record.',\n parameters: {\n type: 'object',\n properties: { objectName: { type: 'string' }, recordId: { type: 'string' } },\n required: ['objectName', 'recordId'],\n },\n request: { method: 'GET', path: '/services/data/v61.0/sobjects/{objectName}/{recordId}' },\n requiredScopes: ['api'],\n },\n {\n name: 'records.create',\n class: 'mutation',\n description: 'Create a Salesforce sObject record.',\n parameters: {\n type: 'object',\n properties: { objectName: { type: 'string' }, fields: { type: 'object' } },\n required: ['objectName', 'fields'],\n },\n request: { method: 'POST', path: '/services/data/v61.0/sobjects/{objectName}', body: '{fields}' },\n cas: 'native-idempotency',\n requiredScopes: ['api'],\n },\n {\n name: 'records.update',\n class: 'mutation',\n description: 'Update a Salesforce sObject record.',\n parameters: {\n type: 'object',\n properties: { objectName: { type: 'string' }, recordId: { type: 'string' }, fields: { type: 'object' } },\n required: ['objectName', 'recordId', 'fields'],\n },\n request: { method: 'PATCH', path: '/services/data/v61.0/sobjects/{objectName}/{recordId}', body: '{fields}' },\n cas: 'etag-if-match',\n requiredScopes: ['api'],\n },\n ],\n})\n","import type {\n IntegrationConnector,\n IntegrationConnectorAction,\n IntegrationConnectorCategory,\n IntegrationActionRisk,\n IntegrationDataClass,\n} from './index.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}\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 })\n }\n }\n return tools\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","import type {\n CompleteAuthRequest,\n IntegrationActionRequest,\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationProvider,\n IntegrationProviderKind,\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}\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 }\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 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: {\n id: string\n input: unknown\n idempotencyKey?: string\n dryRun?: boolean\n metadata?: Record<string, unknown>\n }\n}\n\nexport interface ActivepiecesHttpExecutorOptions {\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 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\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\nexport function signActivepiecesRuntimeRequest(serializedBody: string, secret: string): string {\n return `sha256=${createHmac('sha256', secret).update(serializedBody).digest('hex')}`\n}\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: TangleCatalogHttpExecutorInvocation['piece']\n action: ActivepiecesRuntimeRequest['action']\n}\n\nexport type TangleCatalogHttpExecutorOptions = ActivepiecesHttpExecutorOptions\nexport interface TangleCatalogHttpExecutorInvocation extends Omit<ActivepiecesExecutorInvocation, 'catalogEntry' | 'piece'> {\n catalogEntry: unknown\n piece: {\n id: string\n packageName?: string\n version?: string\n actionId: string\n upstreamActionName?: string\n }\n}\n\nexport function createTangleCatalogHttpExecutor(\n options: TangleCatalogHttpExecutorOptions,\n): (invocation: TangleCatalogHttpExecutorInvocation) => ReturnType<ActivepiecesExecutorProviderOptions['executeAction']> {\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 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 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 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 interface TangleIntegrationCatalogEntry {\n id: string\n title: string\n description: string\n category: IntegrationConnector['category']\n auth: IntegrationConnector['auth']\n domains: string[]\n actions: Array<{\n id: string\n title: string\n risk: IntegrationConnector['actions'][number]['risk']\n }>\n triggers: Array<{\n id: string\n title: string\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 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}\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\nexport function listTangleIntegrationCatalogEntries(): TangleIntegrationCatalogEntry[] {\n return listActivepiecesCatalogEntries().map((entry) => sanitizeEntry(entry))\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 version: importedEntry.version,\n actionId: action.id,\n upstreamActionName: catalogAction?.upstreamName,\n },\n })\n },\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 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 })),\n triggers: entry.triggers.map((trigger) => ({\n id: trigger.id,\n title: trigger.title,\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 {\n TANGLE_CATALOG_RUNTIME_SIGNATURE_HEADER,\n verifyTangleCatalogRuntimeSignature,\n type TangleCatalogRuntimeRequest,\n} from './activepieces-runtime.js'\nimport { listActivepiecesCatalogEntries } from './activepieces-catalog.js'\nimport { buildTangleIntegrationCatalogConnectors } from './tangle-catalog.js'\nimport type {\n IntegrationActionResult,\n IntegrationConnection,\n IntegrationConnector,\n IntegrationConnectorAction,\n} from './index.js'\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 resolveAuth?: (connection: IntegrationConnection) => Promise<unknown> | unknown\n beforeRun?: (invocation: TangleCatalogRuntimeInvocation) => Promise<void> | void\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 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 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\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)\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\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[] } | 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[] } => (\n Boolean(value)\n && typeof value === 'object'\n && Array.isArray((value as { actions?: unknown[] }).actions)\n ))\n}\n\nfunction findRuntimeAction(\n piece: { actions?: unknown[] },\n invocation: TangleCatalogRuntimeInvocation,\n aliases: TangleCatalogInstalledPackageExecutorOptions['actionAliases'] = {},\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 (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 {\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 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 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 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 subject: IntegrationActor\n ttlMs: number\n grantee?: IntegrationActor\n }): Promise<IntegrationSandboxBundle> {\n const grants = (await this.grants.listByManifest(input.manifestId, input.grantee))\n .filter((grant) => grant.status === 'active')\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 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,\n subject: input.subject,\n capabilities: bindings,\n connectors,\n tools: buildIntegrationToolCatalog(connectors),\n expiresAt,\n }\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 !== 'read'\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,aAAY,cAAAC,aAAY,mBAAAC,wBAAuB;;;ACAxD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,eAAe;;;ACS1B,IAAM,yBAAoE;AAAA,EAC/E,OAAO;AAAA,IACL,UAAU;AAAA,IACV,aAAa;AAAA,MACX,sBAAsB;AAAA,MACtB,6BAA6B;AAAA,MAC7B,0BAA0B;AAAA,MAC1B,iCAAiC;AAAA,MACjC,mCAAmC;AAAA,MACnC,iCAAiC;AAAA,MACjC,eAAe;AAAA,MACf,mBAAmB;AAAA,IACrB;AAAA,EACF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AO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC5B;","names":["createHmac","randomUUID","timingSafeEqual","trigger","trigger","matchesFilter","redactUnknown","unique","createHash","createHash","unique","randomUUID","defaultReason","redactUnknown","createHash","createHash","SCOPES","AUTH_URL","TOKEN_URL","ensureFreshAccessToken","createHash","SCOPES","AUTH_URL","TOKEN_URL","readMetaString","ensureFreshAccessToken","findNextFreeSlots","SCOPES","AUTH_URL","TOKEN_URL","ensureFreshAccessToken","SCOPES","AUTH_URL","TOKEN_URL","API","AUTH_URL","TOKEN_URL","API","readMetaString","API","readMetaString","API","createHmac","readMetaString","githubConnector","riskRank","unique","redactUnknown","unique","slug","titleFromId","unique","trigger","createHmac","randomUUID","timingSafeEqual","trigger","trigger","registryEntry","unique","sameActor","randomUUID","unique","trigger","requiredScopes","missing","createHmac","timingSafeEqual"]}
|