@tangle-network/agent-integrations 0.25.7 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +11 -2
  2. package/dist/bin/tangle-catalog-runtime.js +6 -2
  3. package/dist/bin/tangle-catalog-runtime.js.map +1 -1
  4. package/dist/catalog.d.ts +4 -1
  5. package/dist/catalog.js +6 -2
  6. package/dist/chunk-2TW2QKGZ.js +94 -0
  7. package/dist/chunk-2TW2QKGZ.js.map +1 -0
  8. package/dist/chunk-ATYHZXLL.js +457 -0
  9. package/dist/chunk-ATYHZXLL.js.map +1 -0
  10. package/dist/{chunk-A5I3EYU5.js → chunk-ICSBYCE2.js} +122 -1
  11. package/dist/chunk-ICSBYCE2.js.map +1 -0
  12. package/dist/{chunk-WC63AI4Q.js → chunk-JU25UDN2.js} +1252 -225
  13. package/dist/chunk-JU25UDN2.js.map +1 -0
  14. package/dist/chunk-P24T3MLM.js +106 -0
  15. package/dist/chunk-P24T3MLM.js.map +1 -0
  16. package/dist/chunk-SVQ4PHDZ.js +129 -0
  17. package/dist/chunk-SVQ4PHDZ.js.map +1 -0
  18. package/dist/connect/index.d.ts +112 -0
  19. package/dist/connect/index.js +14 -0
  20. package/dist/connect/index.js.map +1 -0
  21. package/dist/connectors/adapters/index.d.ts +593 -1
  22. package/dist/connectors/adapters/index.js +22 -1
  23. package/dist/connectors/index.d.ts +2 -1
  24. package/dist/connectors/index.js +32 -10
  25. package/dist/index.d.ts +5 -2
  26. package/dist/index.js +57 -11
  27. package/dist/middleware/index.d.ts +137 -0
  28. package/dist/middleware/index.js +14 -0
  29. package/dist/middleware/index.js.map +1 -0
  30. package/dist/registry.d.ts +165 -2
  31. package/dist/registry.js +6 -2
  32. package/dist/runtime.d.ts +4 -1
  33. package/dist/runtime.js +6 -2
  34. package/dist/specs.d.ts +4 -1
  35. package/dist/tangle-catalog-runtime.d.ts +4 -1
  36. package/dist/tangle-catalog-runtime.js +6 -2
  37. package/dist/tangle-id-CTU4kGId.d.ts +553 -0
  38. package/dist/webhooks/index.d.ts +193 -0
  39. package/dist/webhooks/index.js +285 -0
  40. package/dist/webhooks/index.js.map +1 -0
  41. package/examples/discover-capabilities.ts +46 -0
  42. package/examples/webhook-router.ts +56 -0
  43. package/package.json +25 -12
  44. package/dist/chunk-A5I3EYU5.js.map +0 -1
  45. package/dist/chunk-WC63AI4Q.js.map +0 -1
  46. package/dist/index-BQY5ry2s.d.ts +0 -808
@@ -1,808 +0,0 @@
1
- /**
2
- * Connector primitives — the contract a concrete first-party integration
3
- * (Google Calendar, HubSpot, Stripe, ...) implements. Lower level than the
4
- * hub-side `IntegrationProvider` interface from `../index.ts`: a single
5
- * `IntegrationProvider` typically wraps several connectors (e.g., a
6
- * "first-party" provider that lists all your shipped connectors as a
7
- * single catalog).
8
- *
9
- * Layering:
10
- *
11
- * IntegrationHub — vendor-neutral facade (../index.ts)
12
- * ↓
13
- * IntegrationProvider — one per gateway or first-party provider
14
- * ↓
15
- * ConnectorAdapter (this file) — one per integration (Google Calendar, ...)
16
- * ↓
17
- * upstream HTTP API — vendor SDK / fetch / OAuth
18
- *
19
- * Three load-bearing decisions encoded here:
20
- *
21
- * 1. Capabilities are typed (`read` vs `mutation`). Every mutation MUST
22
- * declare a CAS strategy. Conflict resolution is the SDK's job, not the
23
- * connector's. `validateConnectorManifest()` rejects unsafe manifests
24
- * before a connector is registered.
25
- *
26
- * 2. ConsistencyModel pins what the rest of the system can assume:
27
- * authoritative → the source IS the truth (Calendar, payments)
28
- * cache → we mirror with TTL and may serve stale (price list)
29
- * advisory → informational only (FAQ doc)
30
- * Agent planners can (and should) refuse to promise outcomes based on
31
- * `cache`/`advisory` data without a live `authoritative` confirmation.
32
- *
33
- * 3. Capabilities surface to the calling agent's tool registry by
34
- * transformation, not by hand-wiring. Adding a connector automatically
35
- * expands the agent's toolbelt for that specific user without touching
36
- * the prompt or runner.
37
- */
38
- /** Minimal JSON-schema shape used for capability arg validation. We
39
- * intentionally don't pull `@types/json-schema` — most consumers already
40
- * declare parameters as `Record<string, unknown>` and the
41
- * shape is whatever the LLM SDK's structured-output expects. Keep the
42
- * contract loose at the boundary; tighten via runtime zod where needed. */
43
- type CapabilityParameterSchema = Record<string, unknown>;
44
- /** What the rest of the system is allowed to assume about freshness. */
45
- type ConsistencyModel = 'authoritative' | 'cache' | 'advisory';
46
- /** Capability classes. `read` is safe to retry; `mutation` must go through
47
- * MutationGuard (CAS + idempotency). `subscribe` is reserved for future
48
- * push-driven sources (webhook callbacks) and is not yet wired. */
49
- type CapabilityClass = 'read' | 'mutation' | 'subscribe';
50
- /** Compare-and-swap strategy a mutation uses to detect conflicts. */
51
- type CASStrategy =
52
- /** Upstream returns an etag/sequence on read, accepts If-Match on write
53
- * (Google Calendar, GitHub, GDocs revision_id). The connector returns
54
- * 412 / Precondition Failed on conflict; the SDK maps to ResourceContention. */
55
- 'etag-if-match'
56
- /** Upstream guarantees exactly-once-per-key (Stripe, idempotent webhooks).
57
- * The SDK passes the idempotency key through; no etag check. */
58
- | 'native-idempotency'
59
- /** No upstream concurrency control. Connector MUST do read-then-write
60
- * and verify nothing changed in-between (best-effort). Suitable only
61
- * for low-contention single-user resources; rejected for any
62
- * consistencyModel='authoritative' write that may race. */
63
- | 'optimistic-read-verify'
64
- /** Source is not contended (e.g. logging, telemetry). Mutations are
65
- * fire-and-forget. Marks the capability as not eligible for
66
- * authoritative writes. */
67
- | 'none';
68
- interface CapabilityRead {
69
- name: string;
70
- class: 'read';
71
- description: string;
72
- /** JSON-schema for the tool args the agent passes when invoking. */
73
- parameters: CapabilityParameterSchema;
74
- /** Optional: declare which scopes (per the connector manifest) this
75
- * capability requires. The capability is hidden from the agent's
76
- * tool registry if the user's grant didn't include them. */
77
- requiredScopes?: string[];
78
- }
79
- interface CapabilityMutation {
80
- name: string;
81
- class: 'mutation';
82
- description: string;
83
- parameters: CapabilityParameterSchema;
84
- /** Mandatory: how does the connector guarantee at-most-once + conflict-detect? */
85
- cas: CASStrategy;
86
- /** True for capabilities that affect resources outside the calling user
87
- * (e.g. booking against a shared calendar, charging a card). The agent's
88
- * planner treats these specially: requires explicit caller confirmation
89
- * before the call. */
90
- externalEffect: boolean;
91
- requiredScopes?: string[];
92
- }
93
- type Capability = CapabilityRead | CapabilityMutation;
94
- /** OAuth2 scope catalog the user has granted us, plus arbitrary metadata
95
- * the connector pinned at connect-time (calendar id, sheet id, webhook
96
- * url, …). `metadata` MUST NOT contain secrets — those go in the
97
- * encrypted credentials envelope. */
98
- interface DataSourceMetadata {
99
- scopes: string[];
100
- [key: string]: unknown;
101
- }
102
- /** A connected, authenticated, ready-to-call data source for a project.
103
- * Persistence shape mirrors the product's connection/source row but normalized — the
104
- * encrypted credentials envelope is decrypted at hand-out time and held
105
- * in memory only for the duration of the call. */
106
- interface ResolvedDataSource {
107
- id: string;
108
- projectId: string;
109
- publishedAgentId: string | null;
110
- kind: string;
111
- label: string;
112
- consistencyModel: ConsistencyModel;
113
- scopes: string[];
114
- metadata: Record<string, unknown>;
115
- /** Unwrapped credentials handed to the connector at call-time. Never
116
- * persisted in this shape; never logged. */
117
- credentials: ConnectorCredentials;
118
- status: 'active' | 'revoked' | 'error';
119
- }
120
- /** Discriminated union of credential shapes. Connectors that need new
121
- * shapes extend this union — `kind` is sealed via the tagged pattern so
122
- * TypeScript catches an exhaustiveness gap at compile time. */
123
- type ConnectorCredentials = {
124
- kind: 'oauth2';
125
- accessToken: string;
126
- refreshToken?: string;
127
- expiresAt?: number;
128
- } | {
129
- kind: 'api-key';
130
- apiKey: string;
131
- } | {
132
- kind: 'custom';
133
- values: Record<string, unknown>;
134
- } | {
135
- kind: 'hmac';
136
- secret: string;
137
- } | {
138
- kind: 'none';
139
- };
140
- /** Result of a read capability invocation. */
141
- interface CapabilityReadResult {
142
- /** Free-form payload — the connector's data shape. The agent receives
143
- * this as the tool result; planners consume it via JSON-shape contract
144
- * declared in the capability's `parameters` (output schema). */
145
- data: unknown;
146
- /** Optional etag/sequence the caller can reuse for a subsequent CAS
147
- * mutation. */
148
- etag?: string;
149
- /** When this read happened (UTC ms since epoch). */
150
- fetchedAt: number;
151
- }
152
- /** Result of a mutation capability invocation. Either committed (with the
153
- * resulting etag/sequence so the caller can chain mutations), or
154
- * contended (the upstream rejected with a state mismatch — the agent
155
- * should re-read and retry, or surface alternatives to the caller). */
156
- type CapabilityMutationResult = {
157
- status: 'committed';
158
- data: unknown;
159
- etagAfter?: string;
160
- committedAt: number;
161
- /** True iff this commit was returned from the idempotency store
162
- * rather than executed against upstream. The caller can use this
163
- * to suppress confirmation messages on retry. */
164
- idempotentReplay: boolean;
165
- } | {
166
- status: 'conflict';
167
- /** Best-effort alternative options the upstream surfaced (e.g.,
168
- * next-available calendar slots after a booking conflict). */
169
- alternatives: unknown[];
170
- /** The current authoritative state, if the connector could re-read
171
- * cheaply. */
172
- currentState?: unknown;
173
- message: string;
174
- } | {
175
- status: 'rate-limited';
176
- /** Wall-clock ms the caller should wait before retrying. The SDK
177
- * computes this from the bucket's refill schedule so the agent
178
- * doesn't have to guess. */
179
- retryAfterMs: number;
180
- message: string;
181
- };
182
- /** Inputs the SDK passes into the connector's executeRead / executeMutation. */
183
- interface ConnectorInvocation {
184
- source: ResolvedDataSource;
185
- capabilityName: string;
186
- args: Record<string, unknown>;
187
- /** Idempotency key the caller (or the SDK's defaulting policy) supplied.
188
- * Always present at the connector boundary — the SDK manufactures one
189
- * if the agent didn't pass one. */
190
- idempotencyKey: string;
191
- /** Optional caller-supplied etag the connector should send as If-Match. */
192
- expectedEtag?: string;
193
- /** Product/session id (if any) for forensic logging. */
194
- callSessionId?: string;
195
- }
196
- /** A single inbound event extracted from a push payload. The webhook
197
- * receiver persists one `InboundEvent` row per entry the connector returns. */
198
- interface InboundEvent {
199
- eventType: string;
200
- providerEventId?: string;
201
- payload: Record<string, unknown>;
202
- }
203
- /** Adapter response from an inbound-webhook dispatch. The receiver persists
204
- * every `events[]` entry, then either honors the connector's `response`
205
- * override (Slack `url_verification` echo, provider-specific 2xx body) or
206
- * defaults to `{status: 200, body: {received: true, count: events.length}}`. */
207
- interface EventHandlerResult {
208
- events: InboundEvent[];
209
- /** Optional: how to respond to the provider. Stripe wants 200 within
210
- * 30s; Slack wants the challenge param echoed. */
211
- response?: {
212
- status: number;
213
- body: unknown;
214
- headers?: Record<string, string>;
215
- };
216
- }
217
- /**
218
- * Connector adapter — one per integration kind. Stateless. The SDK holds
219
- * the persistence + crypto + mutation-guard concerns; the adapter only
220
- * knows how to talk to its upstream.
221
- */
222
- interface ConnectorAdapter {
223
- /** Manifest entry the registry uses to render UI + validate args. */
224
- manifest: ConnectorManifest;
225
- /** Read invocation. Required when manifest.capabilities contains reads.
226
- * Should return whatever shape the capability declared
227
- * in its parameters output schema. */
228
- executeRead?(inv: ConnectorInvocation): Promise<CapabilityReadResult>;
229
- /** Mutation invocation. Required when manifest.capabilities contains mutations.
230
- * Throws ResourceContention on a CAS miss; throws
231
- * any other Error for upstream failures. The MutationGuard wraps this
232
- * with idempotency-key short-circuit + audit logging — adapters do
233
- * NOT manage their own dedup. */
234
- executeMutation?(inv: ConnectorInvocation): Promise<CapabilityMutationResult>;
235
- /** Inbound webhook signature verifier. Called BEFORE handleInboundEvent.
236
- * MUST use constant-time comparison (`crypto.timingSafeEqual`) for any
237
- * HMAC check. The receiver returns 401 on `valid=false` without invoking
238
- * handleInboundEvent. Optional: connectors that don't accept push events
239
- * omit this method and the receiver returns 405 for the kind. */
240
- verifySignature?(input: {
241
- rawBody: string;
242
- headers: Record<string, string | string[] | undefined>;
243
- source: ResolvedDataSource;
244
- }): {
245
- valid: boolean;
246
- reason?: string;
247
- };
248
- /** Inbound webhook dispatch. Called AFTER verifySignature passes. The
249
- * adapter parses the provider payload and emits zero-or-more
250
- * `InboundEvent` rows; the receiver persists them as one row each (modulo
251
- * the (dataSourceId, providerEventId) dedup unique). The optional
252
- * `response` overrides the receiver's default 200 (Slack `url_verification`
253
- * needs to echo the challenge in the body to pass Slack's app-config check). */
254
- handleInboundEvent?(input: {
255
- source: ResolvedDataSource;
256
- rawBody: string;
257
- headers: Record<string, string | string[] | undefined>;
258
- }): Promise<EventHandlerResult>;
259
- /** OAuth callback handler — exchanges the auth code for tokens, returns
260
- * the credentials envelope + scopes + metadata. Only present for
261
- * oauth2-style adapters. */
262
- exchangeOAuth?(input: {
263
- code: string;
264
- state: string;
265
- codeVerifier: string;
266
- redirectUri: string;
267
- }): Promise<{
268
- credentials: ConnectorCredentials;
269
- scopes: string[];
270
- metadata: Record<string, unknown>;
271
- }>;
272
- /** Refresh access token. Only required for oauth2 adapters with
273
- * short-lived access tokens. */
274
- refreshToken?(input: ConnectorCredentials): Promise<ConnectorCredentials>;
275
- /** Health check — invoked when the user clicks "Test connection" in the
276
- * UI. Should perform the cheapest possible read that proves the grant
277
- * is still valid. Returns `{ok: false, reason}` rather than throwing
278
- * for the common case (token expired, scope missing). */
279
- test(source: ResolvedDataSource): Promise<{
280
- ok: true;
281
- } | {
282
- ok: false;
283
- reason: string;
284
- }>;
285
- }
286
- /** Static manifest a connector module exports. Drives the UI catalog,
287
- * scope display, capability discovery for the agent's tool registry. */
288
- interface ConnectorManifest {
289
- /** Stable kind id used as the foreign key in DataSource.kind. */
290
- kind: string;
291
- /** Human label shown in the UI catalog. */
292
- displayName: string;
293
- /** One-paragraph description shown next to the connect button. */
294
- description: string;
295
- /** Auth shape this connector requires. */
296
- auth: AuthSpec;
297
- /** Capability catalog — the agent's tool registry derives ToolDefinition
298
- * entries from this list at request time. */
299
- capabilities: Capability[];
300
- /** ConsistencyModel default for this kind — overridable per DataSource
301
- * if a particular instance is special (e.g., a user marks a sheet as
302
- * `cache` because they refresh it nightly). */
303
- defaultConsistencyModel: ConsistencyModel;
304
- /** Connector category for UI grouping. */
305
- category: 'calendar' | 'spreadsheet' | 'crm' | 'doc' | 'webhook' | 'storage' | 'comms' | 'commerce' | 'other';
306
- /** Optional icon URL or named icon. */
307
- icon?: string;
308
- /** Optional per-kind rate-limit budget. The SDK enforces it inside
309
- * `executeGuardedMutation` and the read path of `/invoke`. Omit to
310
- * leave the connector unrestricted. */
311
- rateLimit?: RateLimitSpec;
312
- }
313
- /** Token-bucket budget the SDK enforces against the connector's upstream.
314
- * We meter on OUR side rather than letting the upstream reject so a
315
- * chatty agent can't burn quota that's shared across customers (almost
316
- * every OAuth client is). */
317
- interface RateLimitSpec {
318
- /** Max requests per window. */
319
- requests: number;
320
- /** Window in ms. */
321
- windowMs: number;
322
- /** Whether to apply across all DataSources sharing the same OAuth
323
- * client (true; default), or per-DataSource (false). The former
324
- * matches how upstreams meter (per-app), so almost always pick true. */
325
- scope?: 'oauth-client' | 'data-source';
326
- }
327
- type AuthSpec = {
328
- kind: 'oauth2';
329
- /** Authorization endpoint URL. */
330
- authorizationUrl: string;
331
- /** Token endpoint URL. */
332
- tokenUrl: string;
333
- /** Scopes requested in the authorization grant. The user UI shows
334
- * these so the customer knows what's being shared. */
335
- scopes: string[];
336
- /** Whether the connector supports incremental authorization (Google
337
- * does; many don't). */
338
- incremental?: boolean;
339
- /** Env-var name holding the OAuth client_id. */
340
- clientIdEnv: string;
341
- /** Env-var name holding the OAuth client_secret. */
342
- clientSecretEnv: string;
343
- /** Optional extra params attached to the authorization URL (e.g.,
344
- * Google's `access_type=offline&prompt=consent` to obtain refresh
345
- * tokens). */
346
- extraAuthParams?: Record<string, string>;
347
- } | {
348
- kind: 'api-key';
349
- /** UI hint shown when collecting the key. */
350
- hint: string;
351
- } | {
352
- kind: 'hmac';
353
- } | {
354
- kind: 'none';
355
- };
356
- /** Thrown by `executeMutation` when upstream rejects on CAS — caught and
357
- * rewrapped by MutationGuard. */
358
- declare class ResourceContention extends Error {
359
- readonly alternatives: unknown[];
360
- readonly currentState?: unknown | undefined;
361
- readonly name = "ResourceContention";
362
- constructor(message: string, alternatives?: unknown[], currentState?: unknown | undefined);
363
- }
364
- /** Thrown when the connector finds the user's grant has been revoked or
365
- * the access token is no longer valid AND refresh failed. Surfaces to
366
- * the UI as "Reconnect required". */
367
- declare class CredentialsExpired extends Error {
368
- readonly dataSourceId: string;
369
- readonly name = "CredentialsExpired";
370
- constructor(message: string, dataSourceId: string);
371
- }
372
- interface ConnectorManifestValidationIssue {
373
- path: string;
374
- message: string;
375
- }
376
- interface ConnectorManifestValidationResult {
377
- ok: boolean;
378
- issues: ConnectorManifestValidationIssue[];
379
- }
380
- /** Validate the static connector manifest before a provider registers it.
381
- * This catches the expensive mistakes early: duplicate capability names,
382
- * mutation capabilities without CAS, authoritative fire-and-forget writes,
383
- * and invalid rate-limit specs. */
384
- declare function validateConnectorManifest(manifest: ConnectorManifest): ConnectorManifestValidationResult;
385
- declare function assertValidConnectorManifest(manifest: ConnectorManifest): void;
386
-
387
- /**
388
- * Google Calendar connector — CAS reference implementation.
389
- *
390
- * Scopes: `https://www.googleapis.com/auth/calendar` covers list/insert/
391
- * patch on the user's calendars. We could split read/write but for v1 the
392
- * single scope keeps the consent screen simple; an operator who wants
393
- * read-only-Calendar can pick a different `kind` later (`google-calendar-readonly`).
394
- *
395
- * The two capabilities the agent actually needs:
396
- *
397
- * list_availability(calendarId, timeMin, timeMax)
398
- * → {busy: [{start, end}], events: [{id, etag, start, end, summary}]}
399
- * Read; no CAS. Cheap (events.list).
400
- *
401
- * book_slot(calendarId, start, end, summary, attendees?)
402
- * → {eventId, etag}
403
- * Mutation. CAS by Calendar's own conflict-detection: we re-list
404
- * events for the requested window inside the same call, and if any
405
- * OVERLAP exists we return `conflict` with the next-3 free slots
406
- * mined from the user's freebusy, instead of inserting.
407
- *
408
- * Why pre-flight read-then-insert rather than relying on If-Match:
409
- * `events.insert` doesn't take If-Match (you can't precondition an
410
- * insert against a non-existent resource). Calendar's own
411
- * `freebusy.query` is the canonical conflict signal. The whole flow is:
412
- *
413
- * 1. freebusy.query for [start, end] on this calendarId
414
- * 2. if busy → emit ResourceContention with next-3 free slots
415
- * (computed by walking forward in 30-min steps until 3 free
416
- * windows of (end-start) duration found)
417
- * 3. else events.insert with idempotency-key as `requestId` (a Calendar
418
- * API feature that gives us per-key dedup at upstream)
419
- *
420
- * Step 3's `requestId` parameter means a retry of the same idempotency
421
- * key on the same calendar will return the original event rather than
422
- * creating a duplicate, which composes correctly with our MutationGuard's
423
- * idempotency record (which short-circuits before ever hitting upstream
424
- * on the second call). Defense-in-depth.
425
- */
426
-
427
- /** OAuth client config the factory closes over. Caller resolves these
428
- * at construction time (env, DB, secret manager — package doesn't care). */
429
- interface GoogleCalendarOptions {
430
- clientId: string;
431
- clientSecret: string;
432
- }
433
- declare function googleCalendar(opts: GoogleCalendarOptions): ConnectorAdapter;
434
-
435
- /**
436
- * Google Sheets connector — live KB source + writable rows.
437
- *
438
- * The flagship for the "agent reads from a live spreadsheet" UX. The
439
- * customer points the connection at a Sheet (spreadsheetId + sheetName +
440
- * headerRow). We expose:
441
- *
442
- * list_rows(filter?, limit?)
443
- * → {rows: [{...header→cell}], nextCursor?}
444
- * Cheap; just spreadsheets.values.get with the configured range.
445
- *
446
- * query_rows(predicate)
447
- * → same shape as list_rows but with a structured filter (k=v pairs
448
- * ANDed together). Simple and explainable; no SQL.
449
- *
450
- * update_row(rowKey, patch)
451
- * → {row: {...header→cell}, updatedRange}
452
- * Mutation. CAS via Sheets' spreadsheets.values.update + a
453
- * pre-flight read of the row's revisionId-equivalent hash. Sheets
454
- * doesn't expose a per-row etag, so we synthesize one — see
455
- * `rowFingerprint`. If the fingerprint doesn't match what the agent
456
- * last read, we surface ResourceContention with the current row in
457
- * `currentState`.
458
- *
459
- * KB binding: when a Sheet is `consistencyModel: 'cache'` (the default
460
- * for spreadsheets — they're slow-moving), the system also indexes the
461
- * rows as KB chunks. The KB build pipeline calls `list_rows` and emits
462
- * one markdown page per row; on a connector-level "refresh" event the
463
- * agent's KB rebuilds.
464
- */
465
-
466
- /** OAuth client config the factory closes over. Caller resolves these
467
- * at construction time (env, DB, secret manager — package doesn't care). */
468
- interface GoogleSheetsOptions {
469
- clientId: string;
470
- clientSecret: string;
471
- }
472
- declare function googleSheets(opts: GoogleSheetsOptions): ConnectorAdapter;
473
-
474
- /**
475
- * Microsoft Graph Calendar connector — the Outlook half of the
476
- * voice-agent's "book me a slot" surface.
477
- *
478
- * Mirrors the Google Calendar pattern almost line-for-line, with two
479
- * upstream-specific quirks worth calling out:
480
- *
481
- * 1. Graph exposes `@odata.etag` on every event resource AND honors
482
- * `If-Match` on `events.patch` / `events.delete`. So unlike Calendar
483
- * (insert can't be preconditioned against a non-existent resource),
484
- * we DO get real etag CAS for updates after the booking. We still
485
- * use the freebusy pre-flight for the create path, because the
486
- * "two callers grab the same slot" race happens before any event
487
- * exists.
488
- *
489
- * 2. `getSchedule` is the Graph equivalent of `freeBusy.query`. Same
490
- * shape: send `[start, end]` plus the calendar's email/UPN, get
491
- * back a `scheduleItems` list of busy windows.
492
- *
493
- * Why the same flow ports cleanly: the conflict mode is identical
494
- * ("did someone else grab this slot between read and write?"). The
495
- * mechanism — pre-flight read + idempotent insert — composes regardless
496
- * of whether upstream gives us a request-id dedup feature. Graph does
497
- * not have a `requestId` analogue on `events.create`, so we rely
498
- * exclusively on MutationGuard's idempotency-key short-circuit ABOVE
499
- * the connector. That layer prevents duplicate inserts on retry.
500
- */
501
-
502
- /** OAuth client config the factory closes over. Caller resolves these
503
- * at construction time (env, DB, secret manager — package doesn't care). */
504
- interface MicrosoftCalendarOptions {
505
- clientId: string;
506
- clientSecret: string;
507
- }
508
- declare function microsoftCalendar(opts: MicrosoftCalendarOptions): ConnectorAdapter;
509
-
510
- /**
511
- * HubSpot CRM connector — three load-bearing capabilities, picked to
512
- * cover the voice-agent's CRM hot path without trying to swallow all of
513
- * HubSpot's surface in v1.
514
- *
515
- * find_contact(email)
516
- * → {contact: {id, properties}} | {found: false}
517
- * POST /crm/v3/objects/contacts/search with an email-equality filter.
518
- * Cheap, idempotent, no CAS needed (read).
519
- *
520
- * upsert_contact(email, properties)
521
- * → {contactId, created}
522
- * Mutation. CAS strategy = native-idempotency, BUT: HubSpot's
523
- * `idempotencyKey` query param is ONLY available on the v3 *batch*
524
- * endpoints (`/crm/v3/objects/contacts/batch/upsert`). The
525
- * single-record endpoints don't honor it. We use the batch endpoint
526
- * with a single-element array to get native idempotency on retry.
527
- *
528
- * create_note(contactId, body)
529
- * → {noteId}
530
- * Mutation that logs a note engagement on a contact and associates
531
- * it. Notes are append-only — there's no conflict to detect — so we
532
- * use native-idempotency via the same batch trick on
533
- * `/crm/v3/objects/notes/batch/create`.
534
- *
535
- * Why three and not thirty: the agent's leverage on HubSpot is
536
- * "remember who I just spoke to". `find_contact` lets the agent address
537
- * a returning caller by name; `upsert_contact` captures a new one
538
- * without duplicates; `create_note` writes the call's outcome as a CRM
539
- * activity. Anything beyond these (deals, tickets, lists) lives in
540
- * Tier-2 specific kinds — keeping the manifest tight keeps the agent's
541
- * tool registry comprehensible.
542
- */
543
-
544
- /** OAuth client config the factory closes over. Caller resolves these
545
- * at construction time (env, DB, secret manager — package doesn't care). */
546
- interface HubSpotOptions {
547
- clientId: string;
548
- clientSecret: string;
549
- }
550
- declare function hubspot(opts: HubSpotOptions): ConnectorAdapter;
551
-
552
- /**
553
- * Slack connector — bot-token OAuth, three messaging-oriented capabilities.
554
- *
555
- * post_message(channel, text|blocks) → mutation; cas: 'none'
556
- * lookup_user(email) → read
557
- * list_channels(types?, limit?) → read
558
- *
559
- * Why `cas: 'none'` is acceptable here (and only here in this batch):
560
- * Slack messages are advisory — we set
561
- * `defaultConsistencyModel: 'advisory'`. The registry validator allows
562
- * `cas: 'none'` only on non-authoritative connectors precisely so that
563
- * append-only messaging surfaces don't have to invent fake CAS theatre.
564
- * The agent's planner already treats `advisory` data as informational
565
- * and does not promise outcomes based on its post results without
566
- * a separate authoritative confirm. MutationGuard's idempotency-key
567
- * dedup remains in force above the connector — a retry of the same
568
- * post_message call will short-circuit before reaching Slack.
569
- *
570
- * Auth: standard OAuth2. Slack's `/oauth.v2.access` returns a bot
571
- * `access_token` (`xoxb-…`) but does NOT return a refresh_token unless
572
- * the app has rotated tokens enabled. Bot tokens are long-lived by
573
- * default; we surface refreshToken handling but treat its absence as
574
- * normal rather than an error.
575
- */
576
-
577
- /** OAuth client config the factory closes over. Caller resolves these
578
- * at construction time (env, DB, secret manager — package doesn't care). */
579
- interface SlackOptions {
580
- clientId: string;
581
- clientSecret: string;
582
- }
583
- declare function slack(opts: SlackOptions): ConnectorAdapter;
584
-
585
- /**
586
- * Notion database connector — query + page-level CRUD against a single
587
- * connected database.
588
- *
589
- * query_database(filter?, pageSize?) → read
590
- * create_page(properties) → mutation; cas: 'native-idempotency'
591
- * update_page(pageId, properties) → mutation; cas: 'etag-if-match'
592
- *
593
- * CAS quirks worth flagging:
594
- *
595
- * 1. Notion added support for the `Idempotency-Key` HTTP header on
596
- * mutating requests. We forward our SDK's idempotency key on
597
- * create_page, which gives at-most-once semantics under the same
598
- * key for ~24h. MutationGuard's record short-circuits above us;
599
- * Notion's dedup is the second line of defense.
600
- *
601
- * 2. Notion does NOT expose a per-page etag the way Graph does. The
602
- * canonical drift signal is `last_edited_time` (RFC3339). Our
603
- * `update_page` capability accepts an `expectedLastEditedTime` arg;
604
- * if supplied, we GET the page first and compare. Mismatch →
605
- * ResourceContention with the current page state. Conflict-free
606
- * callers can omit the field (last-write-wins, the Notion default).
607
- *
608
- * Auth: standard OAuth2. Notion's token endpoint follows RFC 6749 with
609
- * one twist — the workspace_id and bot_id come back in the response and
610
- * we stash them in `metadata` so the agent can address resources by
611
- * workspace where useful.
612
- */
613
-
614
- /** OAuth client config the factory closes over. Caller resolves these
615
- * at construction time (env, DB, secret manager — package doesn't care). */
616
- interface NotionDatabaseOptions {
617
- clientId: string;
618
- clientSecret: string;
619
- }
620
- declare function notionDatabase(opts: NotionDatabaseOptions): ConnectorAdapter;
621
-
622
- type RestCredentialPlacement = {
623
- kind: 'bearer';
624
- } | {
625
- kind: 'header';
626
- header: string;
627
- prefix?: string;
628
- } | {
629
- kind: 'query';
630
- parameter: string;
631
- };
632
- interface RestConnectorSpec {
633
- kind: string;
634
- displayName: string;
635
- description: string;
636
- auth: ConnectorAdapter['manifest']['auth'];
637
- category: ConnectorAdapter['manifest']['category'];
638
- defaultConsistencyModel: ConnectorAdapter['manifest']['defaultConsistencyModel'];
639
- baseUrl: string | {
640
- metadataKey: string;
641
- fallback?: string;
642
- };
643
- credentialPlacement?: RestCredentialPlacement;
644
- defaultHeaders?: Record<string, string>;
645
- capabilities: RestOperationSpec[];
646
- test?: RestRequestSpec;
647
- }
648
- interface RestOperationSpec {
649
- name: string;
650
- class: 'read' | 'mutation';
651
- description: string;
652
- parameters: Record<string, unknown>;
653
- requiredScopes?: string[];
654
- request: RestRequestSpec;
655
- cas?: 'etag-if-match' | 'native-idempotency' | 'optimistic-read-verify' | 'none';
656
- externalEffect?: boolean;
657
- }
658
- interface RestRequestSpec {
659
- method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
660
- path: string;
661
- query?: Record<string, string | number | boolean | undefined>;
662
- headers?: Record<string, string>;
663
- body?: 'args' | string | Record<string, unknown>;
664
- }
665
- declare function declarativeRestConnector(spec: RestConnectorSpec): ConnectorAdapter;
666
-
667
- /**
668
- * Twilio SMS connector — outbound texts + recent-message lookup. The
669
- * agent's "send the caller a confirmation link" surface.
670
- *
671
- * Auth: HTTP Basic (Account SID + Auth Token). Twilio's API key auth
672
- * also supports SID/Secret pairs; we accept either by treating the
673
- * stored apiKey envelope as `accountSid:authToken` (or
674
- * `accountSid:keySid:secret`) — the connector parses it at call time.
675
- *
676
- * send_sms(to, body)
677
- * Mutation. CAS = native-idempotency. Twilio added the
678
- * `Idempotency-Key` HTTP header to POST /Messages in 2024 — same
679
- * key + same args within 24h returns the original Message resource
680
- * instead of sending a second SMS. MutationGuard's record short-
681
- * circuits before us; Twilio's own dedup is defense-in-depth.
682
- *
683
- * lookup_number(phoneNumber)
684
- * Read. Hits /v1/PhoneNumbers/{e164} on Lookup API. Confirms the
685
- * number is real, returns carrier info if the caller has Lookup
686
- * enabled on their account.
687
- *
688
- * find_recent_messages(toOrFrom?, limit?)
689
- * Read. Returns the most recent Messages on the account, optionally
690
- * filtered by To/From. Useful for "did the confirmation actually
691
- * send?" introspection inside an agent run.
692
- */
693
-
694
- declare const twilioSmsConnector: ConnectorAdapter;
695
-
696
- /**
697
- * Stripe pack connector — single connector kind packing 3 capabilities,
698
- * validating the "connector pack" concept (one auth handshake, multiple
699
- * related capabilities) without exploding the registry into
700
- * `stripe-customers`, `stripe-checkout`, `stripe-invoices` triplets.
701
- *
702
- * find_customer(email) → read; CAS n/a
703
- * create_invoice(customerId, items) → mutation; cas: 'native-idempotency'
704
- * create_checkout_session(...) → mutation; cas: 'native-idempotency'
705
- *
706
- * Auth: API key (Stripe restricted key). Operator pastes the key into
707
- * the Connections UI. We never see their account password / OAuth flow;
708
- * Stripe restricted keys are the customer's responsibility (they pick
709
- * which permissions the key carries). The kind exposes a webhook URL
710
- * post-connect for the operator to paste into the Stripe dashboard —
711
- * we'll wire the receiver to P-3's inbound webhook surface in a later
712
- * commit. That URL is returned in `metadata.webhookUrl` so the UI can
713
- * render it.
714
- *
715
- * Why this is the textbook example of `cas: 'native-idempotency'`:
716
- * Stripe's `Idempotency-Key` HTTP header is THE reference implementation
717
- * of native idempotency. Same key + same args within 24h returns the
718
- * stored response (Stripe's words, not ours). Same key + different args
719
- * → 400 with `idempotency_error`. We forward the SDK's idempotency key
720
- * directly. MutationGuard short-circuits before us on retry; Stripe's
721
- * own dedup is the second line of defense.
722
- */
723
-
724
- declare const stripePackConnector: ConnectorAdapter;
725
-
726
- /**
727
- * Universal webhook connector — the long-tail escape hatch.
728
- *
729
- * The user declares a target URL + a JSON-schema for the request body
730
- * the agent should send, plus an optional shared secret. We sign every
731
- * outbound POST with HMAC-SHA256 over `timestamp.body` and forward the
732
- * agent's idempotency key as a header. The receiving system enforces
733
- * its own idempotency.
734
- *
735
- * One adapter, two capabilities. Both arity-1 — `body` is whatever JSON
736
- * the agent's planner constructs from the operator-defined schema (which
737
- * lives in DataSource.metadata.requestSchema). The agent's planner reads
738
- * that schema at request time and constructs valid args.
739
- *
740
- * Why one connector covers 50 systems badly and 1 system well: the agent
741
- * gets a generic "send_event" tool that doesn't *know* what the upstream
742
- * does with the payload. That's fine for fire-and-forget event posting
743
- * (Zapier-style); it's wrong for booking against a calendar where you
744
- * need conflict-resolution. So webhook's `post_event` capability is
745
- * marked `cas: 'native-idempotency'` (we forward the key — the receiver
746
- * MUST honor it) and `defaultConsistencyModel: 'advisory'`. Anyone
747
- * needing real CAS uses a kind-specific connector (Calendar, Sheets, ...).
748
- */
749
-
750
- declare const webhookConnector: ConnectorAdapter;
751
-
752
- /**
753
- * Stripe inbound-webhook receiver — push-only side of a Stripe connector.
754
- *
755
- * The full Stripe connector (charges/customers/invoices read+mutation) is
756
- * tracked in INTEGRATIONS.md as separate `stripe-customers` / `stripe-invoices`
757
- * rows. This adapter only ships the inbound surface today: receive a push,
758
- * verify the signature, persist one `InboundEvent` per Stripe event so the
759
- * agent's runtime can react (e.g. payment_failed → outbound dunning call).
760
- *
761
- * This connector is for the connected account owner: they paste their
762
- * `whsec_*` and the consuming product listens on a per-data-source URL such
763
- * as /api/webhooks/inbound/stripe/:dataSourceId.
764
- *
765
- * Signature scheme: Stripe's `t=<unix>,v1=<hmac>` header. HMAC is
766
- * sha256(`${t}.${rawBody}`) keyed by the customer's webhook secret. We use
767
- * `timingSafeEqual` to defeat timing oracles and bound timestamp skew at
768
- * 5 minutes (Stripe's recommendation) to thwart replay against captured
769
- * signatures.
770
- */
771
-
772
- declare const stripeWebhookReceiverConnector: ConnectorAdapter;
773
-
774
- /**
775
- * Slack Events API inbound receiver.
776
- *
777
- * Slack sends two distinct request shapes to the same webhook URL:
778
- *
779
- * 1. `url_verification` — a one-off handshake during app-config. The body
780
- * contains a `challenge` string we MUST echo back as the response body
781
- * (Slack's app-config UI fails the URL otherwise). No InboundEvent is
782
- * persisted for this — it's an infrastructure ping, not a user event.
783
- *
784
- * 2. `event_callback` — every actual workspace event (message posted,
785
- * reaction added, channel created, …). We persist one InboundEvent
786
- * keyed by `event_id` so a Slack retry (Slack retries 3 times on any
787
- * non-2xx) is deduped at the unique constraint, not after we've
788
- * double-processed.
789
- *
790
- * Signature scheme: `v0=<hmac(sha256, "v0:<timestamp>:<rawBody>")>` keyed by
791
- * the app's signing secret. Header `X-Slack-Request-Timestamp` carries the
792
- * timestamp; we reject anything older than 5 minutes (Slack's recommendation)
793
- * to bound replay risk.
794
- */
795
-
796
- declare const slackEventsConnector: ConnectorAdapter;
797
-
798
- declare const githubConnector: ConnectorAdapter;
799
-
800
- declare const gitlabConnector: ConnectorAdapter;
801
-
802
- declare const airtableConnector: ConnectorAdapter;
803
-
804
- declare const asanaConnector: ConnectorAdapter;
805
-
806
- declare const salesforceConnector: ConnectorAdapter;
807
-
808
- export { type AuthSpec as A, githubConnector as B, type ConnectorAdapter as C, type DataSourceMetadata as D, type EventHandlerResult as E, gitlabConnector as F, type GoogleCalendarOptions as G, type HubSpotOptions as H, type InboundEvent as I, googleCalendar as J, googleSheets as K, hubspot as L, type MicrosoftCalendarOptions as M, type NotionDatabaseOptions as N, microsoftCalendar as O, notionDatabase as P, salesforceConnector as Q, type ResolvedDataSource as R, type SlackOptions as S, slack as T, slackEventsConnector as U, stripePackConnector as V, stripeWebhookReceiverConnector as W, twilioSmsConnector as X, validateConnectorManifest as Y, webhookConnector as Z, type ConnectorCredentials as a, type CASStrategy as b, type Capability as c, type CapabilityClass as d, type CapabilityMutation as e, type CapabilityMutationResult as f, type CapabilityParameterSchema as g, type CapabilityRead as h, type CapabilityReadResult as i, type ConnectorInvocation as j, type ConnectorManifest as k, type ConnectorManifestValidationIssue as l, type ConnectorManifestValidationResult as m, type ConsistencyModel as n, CredentialsExpired as o, type GoogleSheetsOptions as p, type RateLimitSpec as q, ResourceContention as r, type RestConnectorSpec as s, type RestCredentialPlacement as t, type RestOperationSpec as u, type RestRequestSpec as v, airtableConnector as w, asanaConnector as x, assertValidConnectorManifest as y, declarativeRestConnector as z };