@agentforge-io/sdk-server 4.52.0 → 4.54.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.
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export type { AgentForgeClientOptions, RequestOptions } from './client';
3
3
  export { AgentForgeError, AgentForgeAuthError, AgentForgeNotFoundError, AgentForgeNetworkError, } from './errors';
4
4
  export { APP_WEBHOOK_HEADERS, TOOL_CALLBACK_HEADERS, ToolCallbackSignatureError, signToolCallbackPayload, verifyAppWebhook, verifyToolCallbackSignature, } from './webhooks';
5
5
  export { WebhookResource, type SetAppWebhookInput } from './resources/webhook';
6
- export type { AppWebhook, AppWebhookEvent, AppWebhookEventName, AgentMe, AgentSummary, AppUserConnectorStatus, ApprovalCopyBundle, ChannelContext, ChatStreamChunk, ChatStreamEvent, ChatTokenRecord, ConnectorDefaultsResult, ConnectorDefaultsSource, ConnectorResourceItem, ConnectorStatus, ConnectorToolInfo, ConversationHistory, ConversationStatus, CreateAgentInput, CreateClickupTaskInput, CreateClickupTaskResult, ExternalToolSummary, IssueChatTokenInput, ListAgentsResult, ListConnectorResourcesResult, McpServerConfig, MessageRecord, MessageRole, PublicAppBranding, PublicProfileBlock, PublicProfileTemplate, PublicTeamLanding, CreateTeamInput, UpdateTeamInput, TeamSummary, TeamDetail, TeamTheme, TeamBusinessHours, TeamWeekday, TeamProfileBlock, AppInstallation, TemplateConfigField, TemplateSummary, TemplateDetail, TemplateCategoryRef, MarketplaceCategory, MarketplaceCategoryGroup, MarketplaceLocale, TemplateInstallResult, TemplateReview, TemplateRatingSummary, TemplateReviewsPage, BusinessReview, BusinessReviewsPage, ListTemplateReviewsInput, SaveTemplateReviewInput, TemplateReportKind, CreateTemplateReportInput, TenantConfigEntry, Place, PlaceSuggestion, SearchPlacesInput, AutocompletePlacesInput, PlacesScope, CaseField, CaseBusinessState, CaseType, CaseState, CasePayment, CasePaymentAccount, CasePaymentStatus, CaseReceiptPayment, CaseDestination, CaseView, CaseStateStep, CreateDirectOrderInput, CreateDirectBookingInput, MoveCaseSlotInput, CaseSlot, CatalogAttendedAt, CatalogBookingRule, CaseOrigin, CaseOriginChannel, DirectOrderForm, DirectPaymentOption, CaseClosingMethod, CaseClosingOrder, CaseClosingReport, CaseReportPage, CaseReceipt, CaseReceiptLine, ListCasesInput, AddressValue, DeliveryLocalPricing, DeliverySettings, PaymentMethodKind, PaymentSettings, PaymentSettingsInput, PaymentAccount, PaymentCountry, PaymentFieldDef, PaymentMethodDef, StructuredConfigInput, StructuredConfigEntry, DeliveryQuoteStatus, DeliveryQuoteInput, DeliveryRoute, DeliveryRouteInput, DeliveryQuote, AppSelf, AppSelfConnector, AppSelfConnectors, AppSelfConnectorTools, AppSelfConnectorToolsResponse, RegisterToolInput, RegisterToolsInput, BusinessRoleEntry, Catalog, CatalogCheckoutCta, CatalogCategory, CatalogProduct, CatalogProductPhoto, CatalogProductKind, CatalogProductStatus, CatalogPriceKind, CatalogAvailability, CatalogLockableField, CatalogProductPage, UpsertCatalogInput, CreateCatalogCategoryInput, UpdateCatalogCategoryInput, CreateCatalogProductInput, UpdateCatalogProductInput, ListCatalogProductsInput, CatalogPhotoUploadTarget, SignCatalogPhotoUploadInput, AttachCatalogPhotoInput, CatalogImportItem, CatalogImportPreview, CatalogImportApplyResult, CatalogFileMapping, CatalogFilePlan, CatalogFilePreview, CatalogFileApplyResult, CatalogFileInput, CatalogFilePreviewInput, CatalogMenuItem, CatalogMenuRead, CatalogMenuReadInput, CatalogMenuAttachInput, CatalogMenuChatFile, CatalogMenuKeepInSyncInput, CatalogMenuKeepInSyncResult, CatalogOption, CatalogOptionGroup, SaveCatalogOptionGroupInput, CatalogOptionChoice, CatalogOptionChange, CatalogOptionChangesPlan, CatalogUnit, SaveCatalogUnitInput, CatalogSaleRule, CatalogFileApplyInput, CatalogFileErrorCode, CatalogImportSourceStatus, CatalogImportColumnMapping, CatalogImportRunResult, CatalogImportSource, CreateCatalogImportSourceInput, UpdateCatalogImportSourceInput, PreviewCatalogImportSourceInput, CatalogImportSourcePreview, CatalogSheetTab, CatalogTemplateSheet, CreateCatalogTemplateSheetInput, GoogleSheetsPickerInput, GoogleSheetsPickerSession, GoogleSheetsPickerErrorCode, GoogleSheetsPickerResult, RegisterToolsResult, ToolCallbackPayload, ToolCallRecord, ToolPermission, ToolPermissionMode, TokenUsage, TenantSecretEntry, UpdateAgentInput, InboxThreadMode, InboxMessageDirection, InboxMessageSource, InboxMessageType, InboxThreadCustomerProfileView, InboxThreadView, InboxMessageView, SupportKpiTotals, SupportKpiResponse, AgentAttentionLogRow, } from './types';
6
+ export type { AppWebhook, AppWebhookEvent, AppWebhookEventName, AppCaseWebhookEvent, AppCaseWebhookEventName, AppConversationMessageWebhookEvent, AppChannelStatusWebhookEvent, AgentMe, AgentSummary, AppUserConnectorStatus, ApprovalCopyBundle, ChannelContext, ChatStreamChunk, ChatStreamEvent, ChatTokenRecord, ConnectorDefaultsResult, ConnectorDefaultsSource, ConnectorResourceItem, ConnectorStatus, ConnectorToolInfo, ConversationHistory, ConversationStatus, CreateAgentInput, CreateClickupTaskInput, CreateClickupTaskResult, ExternalToolSummary, IssueChatTokenInput, ListAgentsResult, ListConnectorResourcesResult, McpServerConfig, MessageRecord, MessageRole, PublicAppBranding, PublicProfileBlock, PublicProfileTemplate, PublicTeamLanding, CreateTeamInput, UpdateTeamInput, TeamSummary, TeamDetail, TeamTheme, TeamBusinessHours, TeamWeekday, TeamProfileBlock, AppInstallation, TemplateConfigField, TemplateSummary, TemplateDetail, TemplateCategoryRef, MarketplaceCategory, MarketplaceCategoryGroup, MarketplaceLocale, TemplateInstallResult, TemplateReview, TemplateRatingSummary, TemplateReviewsPage, BusinessReview, BusinessReviewsPage, ListTemplateReviewsInput, SaveTemplateReviewInput, TemplateReportKind, CreateTemplateReportInput, TenantConfigEntry, Place, PlaceSuggestion, SearchPlacesInput, AutocompletePlacesInput, PlacesScope, CaseField, CaseBusinessState, CaseType, CaseState, CasePayment, CasePaymentAccount, CasePaymentStatus, CaseReceiptPayment, CaseDestination, CaseView, CaseStateStep, CreateDirectOrderInput, CreateDirectBookingInput, MoveCaseSlotInput, CaseSlot, CatalogAttendedAt, CatalogBookingRule, CaseOrigin, CaseOriginChannel, DirectOrderForm, DirectPaymentOption, CaseClosingMethod, CaseClosingOrder, CaseClosingReport, CaseReportPage, CaseReceipt, CaseReceiptLine, ListCasesInput, AddressValue, DeliveryLocalPricing, DeliverySettings, PaymentMethodKind, PaymentSettings, PaymentSettingsInput, PaymentAccount, PaymentCountry, PaymentFieldDef, PaymentMethodDef, StructuredConfigInput, StructuredConfigEntry, DeliveryQuoteStatus, DeliveryQuoteInput, DeliveryRoute, DeliveryRouteInput, DeliveryQuote, AppSelf, AppSelfConnector, AppSelfConnectors, AppSelfConnectorTools, AppSelfConnectorToolsResponse, RegisterToolInput, RegisterToolsInput, BusinessRoleEntry, Catalog, CatalogCheckoutCta, CatalogCategory, CatalogProduct, CatalogProductPhoto, CatalogProductKind, CatalogProductStatus, CatalogPriceKind, CatalogAvailability, CatalogLockableField, CatalogProductPage, UpsertCatalogInput, CreateCatalogCategoryInput, UpdateCatalogCategoryInput, CreateCatalogProductInput, UpdateCatalogProductInput, ListCatalogProductsInput, CatalogPhotoUploadTarget, SignCatalogPhotoUploadInput, AttachCatalogPhotoInput, CatalogImportItem, CatalogImportPreview, CatalogImportApplyResult, CatalogFileMapping, CatalogFilePlan, CatalogFilePreview, CatalogFileApplyResult, CatalogFileInput, CatalogFilePreviewInput, CatalogMenuItem, CatalogMenuRead, CatalogMenuReadInput, CatalogMenuAttachInput, CatalogMenuChatFile, CatalogMenuKeepInSyncInput, CatalogMenuKeepInSyncResult, CatalogOption, CatalogOptionGroup, SaveCatalogOptionGroupInput, CatalogOptionChoice, CatalogOptionChange, CatalogOptionChangesPlan, CatalogUnit, SaveCatalogUnitInput, CatalogSaleRule, CatalogFileApplyInput, CatalogFileErrorCode, CatalogImportSourceStatus, CatalogImportColumnMapping, CatalogImportRunResult, CatalogImportSource, CreateCatalogImportSourceInput, UpdateCatalogImportSourceInput, PreviewCatalogImportSourceInput, CatalogImportSourcePreview, CatalogSheetTab, CatalogTemplateSheet, CreateCatalogTemplateSheetInput, GoogleSheetsPickerInput, GoogleSheetsPickerSession, GoogleSheetsPickerErrorCode, GoogleSheetsPickerResult, RegisterToolsResult, ToolCallbackPayload, ToolCallRecord, ToolPermission, ToolPermissionMode, TokenUsage, TenantSecretEntry, UpdateAgentInput, InboxThreadMode, InboxMessageDirection, InboxMessageSource, InboxMessageType, InboxThreadCustomerProfileView, InboxThreadView, InboxMessageView, SupportKpiTotals, SupportKpiResponse, AgentAttentionLogRow, } from './types';
7
7
  export { AgentsResource } from './resources/agents';
8
8
  export { AnalyticsResource } from './resources/analytics';
9
9
  export type { GetSupportKpisInput, GetAgentAttentionLogInput, } from './resources/analytics';
@@ -11,7 +11,7 @@ export { AppsResource } from './resources/apps';
11
11
  export { ChatResource } from './resources/chat';
12
12
  export type { AnthropicClientOptions, AppCallerClaims, StreamMessageInput, StreamMessageForAppUserInput, } from './resources/chat';
13
13
  export { ConnectorsResource, parseGoogleSheetsPickerResult } from './resources/connectors';
14
- export type { InboxChannelView } from './resources/connectors';
14
+ export type { AppCreateInboxChannelInput, CreateInboxChannelInput, InboxChannelLinkMethod, InboxChannelReplyMode, InboxChannelView, RelinkInboxChannelInput, StartWhatsAppCloudLinkInput, WhatsAppCloudConnectionType, WhatsAppCloudLinkResult, WhatsAppCloudLinkStart, WhatsAppCloudLinkState, WhatsAppCloudLinkStatus, WhatsAppCloudNumber, } from './resources/connectors';
15
15
  export { InboxResource } from './resources/inbox';
16
16
  export { InstallationsResource } from './resources/installations';
17
17
  export type { InstallAppInput } from './resources/installations';
@@ -29,7 +29,7 @@ export { DeliveryResource } from './resources/delivery';
29
29
  export { CasesResource } from './resources/cases';
30
30
  export { BusinessRolesResource } from './resources/business-roles';
31
31
  export { CatalogResource, CatalogCategoriesResource, CatalogProductsResource, CatalogPhotosResource, CatalogImportResource, CatalogFileImportResource, CatalogMenuImportResource, CatalogOptionGroupsResource, CatalogUnitsResource, CatalogSourcesResource, AgentForgeCatalogImportLimitError, CATALOG_IMPORT_MAX_ITEMS, } from './resources/catalog';
32
- export type { ListThreadsOptions, SendMessageInput, AssignThreadInput, UnassignThreadInput, SetThreadModeInput, CloseThreadInput, } from './resources/inbox';
32
+ export type { ListThreadsOptions, ListNewestMessagesOptions, NewestMessagesPage, SendMessageInput, AssignThreadInput, UnassignThreadInput, SetThreadModeInput, CloseThreadInput, } from './resources/inbox';
33
33
  export { ProvisioningResource } from './resources/provisioning';
34
34
  export type { ProvisionedTenant, ProvisionedApp, ProvisionedTeam, } from './resources/provisioning';
35
35
  export { SecretsResource } from './resources/secrets';
@@ -195,10 +195,15 @@ export declare class ConnectorsResource {
195
195
  * `ak_live_` tenant-wide alcanza — el server valida que `agentId`
196
196
  * pertenezca a este tenant).
197
197
  *
198
+ * `includeDisconnected` adds the disconnected channels that still have
199
+ * threads to read, with `status: 'destroyed'`.
200
+ *
198
201
  * @example
199
202
  * const { items } = await af.connectors.listInboxChannels(agentId);
200
203
  */
201
- listInboxChannels(agentId: string): Promise<{
204
+ listInboxChannels(agentId: string, opts?: {
205
+ includeDisconnected?: boolean;
206
+ }): Promise<{
202
207
  items: InboxChannelView[];
203
208
  }>;
204
209
  /**
@@ -208,22 +213,116 @@ export declare class ConnectorsResource {
208
213
  * `SlackBotProvider.credentialsForm` en agentforge-platform para el shape
209
214
  * exacto de cada provider).
210
215
  *
216
+ * With an App secret (`sk_live_`, usually through `forTenant`) leave
217
+ * `credentials` out: the platform provides the gateway and refuses them
218
+ * with a 400. Only `whatsapp-web` is accepted on that path, `label` is
219
+ * required, and `replyMode` defaults to `human`. An official number comes
220
+ * from `startWhatsAppCloudLink` or `connectWhatsAppCloudNumber` instead.
221
+ *
222
+ * Throws `AgentForgeError` with `code`: `channel_number_in_use` (409),
223
+ * `whatsapp_gateway_unavailable` (503).
224
+ *
211
225
  * @example
212
226
  * await af.connectors.createInboxChannel(agentId, {
213
227
  * providerId: 'slack-bot',
214
228
  * credentials: { signingSecret: '8f742...' },
215
229
  * });
230
+ *
231
+ * @example
232
+ * const channel = await af.forTenant(tenantId).connectors.createInboxChannel(agentId, {
233
+ * providerId: 'whatsapp-web',
234
+ * label: 'Tienda',
235
+ * linkMethod: 'phone',
236
+ * phoneNumber: '573001234567',
237
+ * });
216
238
  */
217
- createInboxChannel(agentId: string, input: {
218
- providerId: string;
219
- label?: string;
220
- credentials: Record<string, unknown>;
221
- }): Promise<InboxChannelView>;
239
+ createInboxChannel(agentId: string, input: CreateInboxChannelInput): Promise<InboxChannelView>;
240
+ createInboxChannel(agentId: string, input: AppCreateInboxChannelInput): Promise<InboxChannelView>;
222
241
  /**
223
242
  * `DELETE /connectors/inbox/agents/:agentId/inbox/channels/:channelId` —
224
243
  * desconecta un canal del inbox omnicanal.
225
244
  */
226
245
  destroyInboxChannel(agentId: string, channelId: string): Promise<void>;
246
+ /**
247
+ * `GET …/inbox/channels/:channelId` — a channel, with a fresh status. Poll it
248
+ * while a number links.
249
+ */
250
+ getInboxChannel(agentId: string, channelId: string): Promise<InboxChannelView>;
251
+ /**
252
+ * `GET …/inbox/channels/:channelId/qr.png` — the current QR as PNG bytes. It
253
+ * rotates: fetch it again rather than keep it.
254
+ *
255
+ * Throws `AgentForgeNotFoundError` with `code` `qr_not_ready` (poll again), or
256
+ * `AgentForgeError` with `whatsapp_gateway_unavailable` (503).
257
+ */
258
+ inboxChannelQrPng(agentId: string, channelId: string): Promise<Uint8Array>;
259
+ /**
260
+ * `GET …/inbox/channels/:channelId/pairing-code` — the 8-character code the
261
+ * owner types on their phone.
262
+ *
263
+ * Throws `AgentForgeNotFoundError` with `code` `pairing_code_not_ready` (poll
264
+ * again), or `AgentForgeError` with `whatsapp_gateway_unavailable` (503).
265
+ */
266
+ inboxChannelPairingCode(agentId: string, channelId: string): Promise<{
267
+ pairingCode: string;
268
+ }>;
269
+ /**
270
+ * `POST …/inbox/channels/:channelId/relink` — starts linking again, by QR or
271
+ * phone. `phoneNumber` goes with `linkMethod: 'phone'` only.
272
+ *
273
+ * Throws `AgentForgeError` with `code`: `channel_number_in_use`,
274
+ * `channel_already_linked` (disconnect it first), `channel_session_gone`
275
+ * (delete it and connect again), all 409; `whatsapp_gateway_unavailable` (503).
276
+ */
277
+ relinkInboxChannel(agentId: string, channelId: string, input: RelinkInboxChannelInput): Promise<InboxChannelView>;
278
+ /**
279
+ * `PATCH …/inbox/channels/:channelId` — who answers this channel. Accepted on
280
+ * `whatsapp-web` and `whatsapp-cloud` channels; 400 on any other provider.
281
+ */
282
+ setInboxChannelReplyMode(agentId: string, channelId: string, replyMode: InboxChannelReplyMode): Promise<InboxChannelView>;
283
+ /**
284
+ * `POST …/inbox/whatsapp-cloud/start` — starts linking an official number.
285
+ * Open `url`, then call `pollWhatsAppCloudLink` with `excludeIds`.
286
+ * `connectionTypes` defaults to `['coexistence']` on the platform.
287
+ *
288
+ * Throws `AgentForgeError` with `code`: `whatsapp_cloud_link_busy` (409,
289
+ * another agent or App of this business is connecting),
290
+ * `whatsapp_cloud_number_limit` (409), `whatsapp_cloud_unavailable` (503).
291
+ */
292
+ startWhatsAppCloudLink(agentId: string, input?: StartWhatsAppCloudLinkInput): Promise<WhatsAppCloudLinkStart>;
293
+ /**
294
+ * `POST …/inbox/whatsapp-cloud/poll` — `{ channel }` once the number is
295
+ * connected, with `replyMode: 'human'`, else `{ channel: null }`. Safe to repeat.
296
+ * `link` says how the link stands (see `WhatsAppCloudLinkStatus`); a poll with no
297
+ * session reads as `expired`.
298
+ *
299
+ * Throws `AgentForgeError` with `code`: `whatsapp_cloud_number_limit` (409),
300
+ * `whatsapp_cloud_unavailable` (503).
301
+ */
302
+ pollWhatsAppCloudLink(agentId: string, input?: {
303
+ excludeIds?: string[];
304
+ }): Promise<WhatsAppCloudLinkResult>;
305
+ /**
306
+ * `GET …/inbox/whatsapp-cloud/numbers` — the numbers already on Kapso that
307
+ * this business can connect: its own, free and connected.
308
+ *
309
+ * Throws `AgentForgeError` with `code` `whatsapp_cloud_unavailable` (503).
310
+ */
311
+ listWhatsAppCloudNumbers(agentId: string): Promise<{
312
+ items: WhatsAppCloudNumber[];
313
+ }>;
314
+ /**
315
+ * `POST …/inbox/whatsapp-cloud/connect` — connects a number from
316
+ * `listWhatsAppCloudNumbers`. `{ channel: null }` means another call is
317
+ * finishing it: call again. Safe to repeat.
318
+ *
319
+ * Throws `AgentForgeNotFoundError` with `code` `whatsapp_cloud_number_not_found`,
320
+ * or `AgentForgeError` with `channel_number_in_use` (409),
321
+ * `whatsapp_cloud_number_limit` (409), `whatsapp_cloud_unavailable` (503).
322
+ */
323
+ connectWhatsAppCloudNumber(agentId: string, phoneNumberId: string): Promise<WhatsAppCloudLinkResult>;
324
+ /** The App secret on the wire, whatever else this client holds. */
325
+ private asApp;
227
326
  /**
228
327
  * `POST /connectors/oauth/:id/authorize-for-app-user` — starts the
229
328
  * connector OAuth flow on behalf of ONE end user of the `sk_live_`/
@@ -398,6 +497,8 @@ export declare class ConnectorsResource {
398
497
  connectorId: string;
399
498
  }>;
400
499
  }
500
+ /** Who answers a channel: `agent` (the AI) or `human` (only people). */
501
+ export type InboxChannelReplyMode = 'human' | 'agent';
401
502
  export interface InboxChannelView {
402
503
  id: string;
403
504
  tenantId: string;
@@ -408,12 +509,85 @@ export interface InboxChannelView {
408
509
  status: string;
409
510
  lastError?: string;
410
511
  lastSeenAt?: string;
512
+ replyMode: InboxChannelReplyMode;
411
513
  displayName?: string;
412
514
  username?: string;
413
515
  avatarUrl?: string;
414
516
  createdAt: string;
415
517
  updatedAt: string;
416
518
  }
519
+ /** How a `whatsapp-web` channel links: a QR, or a code typed on the phone. */
520
+ export type InboxChannelLinkMethod = 'qr' | 'phone';
521
+ export interface CreateInboxChannelInput {
522
+ providerId: string;
523
+ label?: string;
524
+ credentials: Record<string, unknown>;
525
+ linkMethod?: InboxChannelLinkMethod;
526
+ phoneNumber?: string;
527
+ /** Absent: `agent` with an `ak_live_`. */
528
+ replyMode?: InboxChannelReplyMode;
529
+ }
530
+ /** What an App sends: no credentials, the platform provides the gateway. */
531
+ export interface AppCreateInboxChannelInput {
532
+ /** `whatsapp-web` is the only one an App can create this way. */
533
+ providerId: string;
534
+ /** Up to 120 characters. */
535
+ label: string;
536
+ /** Default: QR. */
537
+ linkMethod?: InboxChannelLinkMethod;
538
+ /** Required with `linkMethod: 'phone'`: 7 to 15 digits with the country code. */
539
+ phoneNumber?: string;
540
+ /** Default: `human`. */
541
+ replyMode?: InboxChannelReplyMode;
542
+ credentials?: undefined;
543
+ }
544
+ export interface RelinkInboxChannelInput {
545
+ linkMethod: InboxChannelLinkMethod;
546
+ /** Required with `linkMethod: 'phone'`, refused with `qr`. */
547
+ phoneNumber?: string;
548
+ }
549
+ export type WhatsAppCloudConnectionType = 'coexistence' | 'dedicated';
550
+ export interface StartWhatsAppCloudLinkInput {
551
+ /** Non-empty when present. Absent: `['coexistence']`. */
552
+ connectionTypes?: WhatsAppCloudConnectionType[];
553
+ /** Origin of the page that opens `url`. */
554
+ openerOrigin?: string;
555
+ }
556
+ export interface WhatsAppCloudLinkStart {
557
+ /** Where the owner connects the number. */
558
+ url: string;
559
+ /** Numbers that existed before this link. Pass them to `pollWhatsAppCloudLink`. */
560
+ excludeIds: string[];
561
+ }
562
+ export type WhatsAppCloudLinkState = 'waiting' | 'finished_no_number' | 'failed' | 'expired';
563
+ export interface WhatsAppCloudLinkStatus {
564
+ state: WhatsAppCloudLinkState;
565
+ /**
566
+ * Why. `failed`: `login_cancelled`, `phone_verification_failed`, `account_limit_reached`,
567
+ * `authorization_failed`, `browser_blocked`, `link_expired`, `link_already_used`,
568
+ * `link_replaced`, `number_limit_reached`, `number_in_use`, `setup_failed`.
569
+ * `finished_no_number`: `number_not_found`, `several_numbers`. `expired`: `session_expired`.
570
+ * A string, as the platform may add more.
571
+ */
572
+ reason?: string;
573
+ }
574
+ export interface WhatsAppCloudLinkResult {
575
+ channel: InboxChannelView | null;
576
+ /**
577
+ * How the link stands. `null` once there is a channel; absent on a platform from
578
+ * before it. `failed` and `finished_no_number` are not final: keep polling, a number
579
+ * can still arrive and wins. Stop on a channel or `expired`.
580
+ */
581
+ link?: WhatsAppCloudLinkStatus | null;
582
+ }
583
+ export interface WhatsAppCloudNumber {
584
+ phoneNumberId: string;
585
+ displayPhoneNumber: string | null;
586
+ verifiedName: string | null;
587
+ connectionType: WhatsAppCloudConnectionType | null;
588
+ /** This tenant had it on a channel: connecting it brings those chats back. */
589
+ previouslyConnected: boolean;
590
+ }
417
591
  /**
418
592
  * Reads the Google Sheets Picker outcome from the `returnTo` URL the hosted
419
593
  * picker navigated to (`connectors.googleSheetsPicker()`). Accepts the full
@@ -208,34 +208,137 @@ class ConnectorsResource {
208
208
  * `ak_live_` tenant-wide alcanza — el server valida que `agentId`
209
209
  * pertenezca a este tenant).
210
210
  *
211
+ * `includeDisconnected` adds the disconnected channels that still have
212
+ * threads to read, with `status: 'destroyed'`.
213
+ *
211
214
  * @example
212
215
  * const { items } = await af.connectors.listInboxChannels(agentId);
213
216
  */
214
- async listInboxChannels(agentId) {
215
- return this.client.requestWithApiKey('GET', `/connectors/inbox/agents/${encodeURIComponent(agentId)}/inbox/channels`);
217
+ async listInboxChannels(agentId, opts = {}) {
218
+ return this.client.requestWithApiKey('GET', `${inboxPath(agentId)}/channels${opts.includeDisconnected ? '?includeDisconnected=true' : ''}`);
216
219
  }
217
- /**
218
- * `POST /connectors/inbox/agents/:agentId/inbox/channels` — conecta un
219
- * canal del inbox omnicanal para `agentId` (ej. `providerId: 'slack-bot'`
220
- * con `credentials: { signingSecret, botUserId? }` — ver
221
- * `SlackBotProvider.credentialsForm` en agentforge-platform para el shape
222
- * exacto de cada provider).
223
- *
224
- * @example
225
- * await af.connectors.createInboxChannel(agentId, {
226
- * providerId: 'slack-bot',
227
- * credentials: { signingSecret: '8f742...' },
228
- * });
229
- */
230
220
  async createInboxChannel(agentId, input) {
231
- return this.client.requestWithApiKey('POST', `/connectors/inbox/agents/${encodeURIComponent(agentId)}/inbox/channels`, input);
221
+ // No credentials is the App path, even on a client that also has an ak_live_.
222
+ return input.credentials === undefined && this.client.getAppSecret()
223
+ ? this.client.request('POST', `${inboxPath(agentId)}/channels`, input, this.asApp('createInboxChannel'))
224
+ : this.client.requestWithApiKey('POST', `${inboxPath(agentId)}/channels`, input);
232
225
  }
233
226
  /**
234
227
  * `DELETE /connectors/inbox/agents/:agentId/inbox/channels/:channelId` —
235
228
  * desconecta un canal del inbox omnicanal.
236
229
  */
237
230
  async destroyInboxChannel(agentId, channelId) {
238
- await this.client.requestWithApiKey('DELETE', `/connectors/inbox/agents/${encodeURIComponent(agentId)}/inbox/channels/${encodeURIComponent(channelId)}`);
231
+ await this.client.requestWithApiKey('DELETE', `${inboxPath(agentId)}/channels/${encodeURIComponent(channelId)}`);
232
+ }
233
+ // ─── Inbox channels an App links from its own UI (AGF-101h) ─────────────
234
+ //
235
+ // The routes below take an App secret only (`sk_live_`/`sk_test_`, usually
236
+ // through `forTenant`): the server answers 401 to an `ak_live_`, and these
237
+ // throw early on a client without a secret. Same rule as the App-user scope
238
+ // further down, except the secret is forced with `asApp`, so a client that
239
+ // also holds an `ak_live_` or a ChatToken still authenticates as the App.
240
+ //
241
+ // Every one answers 404 when the agent is not this App's in this tenant.
242
+ /**
243
+ * `GET …/inbox/channels/:channelId` — a channel, with a fresh status. Poll it
244
+ * while a number links.
245
+ */
246
+ async getInboxChannel(agentId, channelId) {
247
+ return this.client.request('GET', `${inboxPath(agentId)}/channels/${encodeURIComponent(channelId)}`, undefined, this.asApp('getInboxChannel'));
248
+ }
249
+ /**
250
+ * `GET …/inbox/channels/:channelId/qr.png` — the current QR as PNG bytes. It
251
+ * rotates: fetch it again rather than keep it.
252
+ *
253
+ * Throws `AgentForgeNotFoundError` with `code` `qr_not_ready` (poll again), or
254
+ * `AgentForgeError` with `whatsapp_gateway_unavailable` (503).
255
+ */
256
+ async inboxChannelQrPng(agentId, channelId) {
257
+ const app = this.asApp('inboxChannelQrPng');
258
+ const res = await this.client.requestRaw('GET', `${inboxPath(agentId)}/channels/${encodeURIComponent(channelId)}/qr.png`, { ...app, headers: { ...app.headers, accept: 'image/png' } });
259
+ return new Uint8Array(await res.arrayBuffer());
260
+ }
261
+ /**
262
+ * `GET …/inbox/channels/:channelId/pairing-code` — the 8-character code the
263
+ * owner types on their phone.
264
+ *
265
+ * Throws `AgentForgeNotFoundError` with `code` `pairing_code_not_ready` (poll
266
+ * again), or `AgentForgeError` with `whatsapp_gateway_unavailable` (503).
267
+ */
268
+ async inboxChannelPairingCode(agentId, channelId) {
269
+ return this.client.request('GET', `${inboxPath(agentId)}/channels/${encodeURIComponent(channelId)}/pairing-code`, undefined, this.asApp('inboxChannelPairingCode'));
270
+ }
271
+ /**
272
+ * `POST …/inbox/channels/:channelId/relink` — starts linking again, by QR or
273
+ * phone. `phoneNumber` goes with `linkMethod: 'phone'` only.
274
+ *
275
+ * Throws `AgentForgeError` with `code`: `channel_number_in_use`,
276
+ * `channel_already_linked` (disconnect it first), `channel_session_gone`
277
+ * (delete it and connect again), all 409; `whatsapp_gateway_unavailable` (503).
278
+ */
279
+ async relinkInboxChannel(agentId, channelId, input) {
280
+ return this.client.request('POST', `${inboxPath(agentId)}/channels/${encodeURIComponent(channelId)}/relink`, input, this.asApp('relinkInboxChannel'));
281
+ }
282
+ /**
283
+ * `PATCH …/inbox/channels/:channelId` — who answers this channel. Accepted on
284
+ * `whatsapp-web` and `whatsapp-cloud` channels; 400 on any other provider.
285
+ */
286
+ async setInboxChannelReplyMode(agentId, channelId, replyMode) {
287
+ return this.client.request('PATCH', `${inboxPath(agentId)}/channels/${encodeURIComponent(channelId)}`, { replyMode }, this.asApp('setInboxChannelReplyMode'));
288
+ }
289
+ /**
290
+ * `POST …/inbox/whatsapp-cloud/start` — starts linking an official number.
291
+ * Open `url`, then call `pollWhatsAppCloudLink` with `excludeIds`.
292
+ * `connectionTypes` defaults to `['coexistence']` on the platform.
293
+ *
294
+ * Throws `AgentForgeError` with `code`: `whatsapp_cloud_link_busy` (409,
295
+ * another agent or App of this business is connecting),
296
+ * `whatsapp_cloud_number_limit` (409), `whatsapp_cloud_unavailable` (503).
297
+ */
298
+ async startWhatsAppCloudLink(agentId, input = {}) {
299
+ return this.client.request('POST', `${inboxPath(agentId)}/whatsapp-cloud/start`, input, this.asApp('startWhatsAppCloudLink'));
300
+ }
301
+ /**
302
+ * `POST …/inbox/whatsapp-cloud/poll` — `{ channel }` once the number is
303
+ * connected, with `replyMode: 'human'`, else `{ channel: null }`. Safe to repeat.
304
+ * `link` says how the link stands (see `WhatsAppCloudLinkStatus`); a poll with no
305
+ * session reads as `expired`.
306
+ *
307
+ * Throws `AgentForgeError` with `code`: `whatsapp_cloud_number_limit` (409),
308
+ * `whatsapp_cloud_unavailable` (503).
309
+ */
310
+ async pollWhatsAppCloudLink(agentId, input = {}) {
311
+ return this.client.request('POST', `${inboxPath(agentId)}/whatsapp-cloud/poll`, input, this.asApp('pollWhatsAppCloudLink'));
312
+ }
313
+ /**
314
+ * `GET …/inbox/whatsapp-cloud/numbers` — the numbers already on Kapso that
315
+ * this business can connect: its own, free and connected.
316
+ *
317
+ * Throws `AgentForgeError` with `code` `whatsapp_cloud_unavailable` (503).
318
+ */
319
+ async listWhatsAppCloudNumbers(agentId) {
320
+ return this.client.request('GET', `${inboxPath(agentId)}/whatsapp-cloud/numbers`, undefined, this.asApp('listWhatsAppCloudNumbers'));
321
+ }
322
+ /**
323
+ * `POST …/inbox/whatsapp-cloud/connect` — connects a number from
324
+ * `listWhatsAppCloudNumbers`. `{ channel: null }` means another call is
325
+ * finishing it: call again. Safe to repeat.
326
+ *
327
+ * Throws `AgentForgeNotFoundError` with `code` `whatsapp_cloud_number_not_found`,
328
+ * or `AgentForgeError` with `channel_number_in_use` (409),
329
+ * `whatsapp_cloud_number_limit` (409), `whatsapp_cloud_unavailable` (503).
330
+ */
331
+ async connectWhatsAppCloudNumber(agentId, phoneNumberId) {
332
+ return this.client.request('POST', `${inboxPath(agentId)}/whatsapp-cloud/connect`, { phoneNumberId }, this.asApp('connectWhatsAppCloudNumber'));
333
+ }
334
+ /** The App secret on the wire, whatever else this client holds. */
335
+ asApp(method) {
336
+ const secret = this.client.getAppSecret();
337
+ if (!secret) {
338
+ throw new Error(`connectors.${method} requires appSecret (sk_live_/sk_test_) in ` +
339
+ 'AgentForgeClient. This surface authenticates AS the App, not via chatToken/apiKey.');
340
+ }
341
+ return { forceApiKey: true, headers: { Authorization: `Bearer ${secret}` } };
239
342
  }
240
343
  // ─── App-user scope (AGF-072, Option A — APP_END_USER_CONNECTIONS_SDD.md §4.4) ──
241
344
  //
@@ -478,6 +581,9 @@ class ConnectorsResource {
478
581
  }
479
582
  }
480
583
  exports.ConnectorsResource = ConnectorsResource;
584
+ function inboxPath(agentId) {
585
+ return `/connectors/inbox/agents/${encodeURIComponent(agentId)}/inbox`;
586
+ }
481
587
  /**
482
588
  * Reads the Google Sheets Picker outcome from the `returnTo` URL the hosted
483
589
  * picker navigated to (`connectors.googleSheetsPicker()`). Accepts the full
@@ -3,6 +3,20 @@ import type { InboxThreadView, InboxMessageView, InboxThreadMode } from '../type
3
3
  export interface ListThreadsOptions {
4
4
  /** Optional filter to threads on a single channel of the agent. */
5
5
  channelId?: string;
6
+ /** Also the history of disconnected channels, marked `channelDisconnected`. */
7
+ includeDisconnected?: boolean;
8
+ }
9
+ export interface ListNewestMessagesOptions {
10
+ /** 1–100. Default 50. */
11
+ limit?: number;
12
+ /** `nextCursor` of the previous page, for older messages. */
13
+ cursor?: string;
14
+ }
15
+ export interface NewestMessagesPage {
16
+ /** Newest first. */
17
+ items: InboxMessageView[];
18
+ /** Absent on the last page. */
19
+ nextCursor?: string;
6
20
  }
7
21
  export interface SendMessageInput {
8
22
  /** The operator's text. */
@@ -68,9 +82,23 @@ export declare class InboxResource {
68
82
  listMessages: (threadId: string) => Promise<{
69
83
  items: InboxMessageView[];
70
84
  }>;
85
+ /**
86
+ * Pages from the newest message. `listMessages` returns the OLDEST 100, so
87
+ * past 100 a thread's new messages are not in it. Needs the platform's
88
+ * AGF-WA-LIVE; an older platform ignores the query and answers `listMessages`.
89
+ */
90
+ listNewestMessages: (threadId: string, opts?: ListNewestMessagesOptions) => Promise<NewestMessagesPage>;
91
+ /**
92
+ * The App read this thread: its unread count goes back to 0. A reply does
93
+ * not do this, so call it when a person opens the thread. Needs the
94
+ * platform's AGF-WA-LIVE.
95
+ */
96
+ markRead: (threadId: string) => Promise<void>;
71
97
  sendMessage: (threadId: string, input: SendMessageInput) => Promise<void>;
72
98
  assign: (threadId: string, input: AssignThreadInput) => Promise<void>;
73
99
  unassign: (threadId: string, input: UnassignThreadInput) => Promise<void>;
100
+ /** Throws `AgentForgeError` with `code` `channel_human_only` (409) when
101
+ * handing back on a channel whose `replyMode` is `human`. */
74
102
  setMode: (threadId: string, input: SetThreadModeInput) => Promise<void>;
75
103
  close: (threadId: string, input?: CloseThreadInput) => Promise<void>;
76
104
  };
@@ -48,9 +48,11 @@ class InboxResource {
48
48
  const base = `/connectors/inbox/agents/${encodeURIComponent(agentId)}/inbox`;
49
49
  return {
50
50
  listThreads: async (opts = {}) => {
51
- const qs = opts.channelId
52
- ? `?channelId=${encodeURIComponent(opts.channelId)}`
53
- : '';
51
+ const params = [
52
+ ...(opts.channelId ? [`channelId=${encodeURIComponent(opts.channelId)}`] : []),
53
+ ...(opts.includeDisconnected ? ['includeDisconnected=true'] : []),
54
+ ];
55
+ const qs = params.length ? `?${params.join('&')}` : '';
54
56
  return this.client.request('GET', `${base}/threads${qs}`);
55
57
  },
56
58
  getThread: async (threadId) => {
@@ -59,6 +61,27 @@ class InboxResource {
59
61
  listMessages: async (threadId) => {
60
62
  return this.client.request('GET', `${base}/threads/${encodeURIComponent(threadId)}/messages`);
61
63
  },
64
+ /**
65
+ * Pages from the newest message. `listMessages` returns the OLDEST 100, so
66
+ * past 100 a thread's new messages are not in it. Needs the platform's
67
+ * AGF-WA-LIVE; an older platform ignores the query and answers `listMessages`.
68
+ */
69
+ listNewestMessages: async (threadId, opts = {}) => {
70
+ const params = [
71
+ 'order=desc',
72
+ ...(opts.limit !== undefined ? [`limit=${opts.limit}`] : []),
73
+ ...(opts.cursor ? [`cursor=${encodeURIComponent(opts.cursor)}`] : []),
74
+ ];
75
+ return this.client.request('GET', `${base}/threads/${encodeURIComponent(threadId)}/messages?${params.join('&')}`);
76
+ },
77
+ /**
78
+ * The App read this thread: its unread count goes back to 0. A reply does
79
+ * not do this, so call it when a person opens the thread. Needs the
80
+ * platform's AGF-WA-LIVE.
81
+ */
82
+ markRead: async (threadId) => {
83
+ await this.client.request('POST', `${base}/threads/${encodeURIComponent(threadId)}/read`);
84
+ },
62
85
  sendMessage: async (threadId, input) => {
63
86
  await this.client.request('POST', `${base}/threads/${encodeURIComponent(threadId)}/messages`, input);
64
87
  },
@@ -68,6 +91,8 @@ class InboxResource {
68
91
  unassign: async (threadId, input) => {
69
92
  await this.client.request('DELETE', `${base}/threads/${encodeURIComponent(threadId)}/assign`, input);
70
93
  },
94
+ /** Throws `AgentForgeError` with `code` `channel_human_only` (409) when
95
+ * handing back on a channel whose `replyMode` is `human`. */
71
96
  setMode: async (threadId, input) => {
72
97
  await this.client.request('POST', `${base}/threads/${encodeURIComponent(threadId)}/mode`, input);
73
98
  },
@@ -8,6 +8,10 @@
8
8
  // returns it. Idempotent: calling it on every boot is fine. `receiptLink`
9
9
  // (AGF-CASE-RECEIPT R5) is where the App shows a receipt; the platform puts
10
10
  // it under case notices on channels without the receipt card (WhatsApp…).
11
+ // A `set` REPLACES the webhook: list every event you want, and send
12
+ // `receiptLink` again or it clears. `conversation.message` and
13
+ // `channel.status_changed` need the platform's AGF-WA-LIVE; before it, a `set`
14
+ // naming them answers 400 and the stored webhook stays as it was.
11
15
  // - `get()` — the current webhook (url, events, active), or null.
12
16
  // - `remove()` — stop receiving events.
13
17
  //
package/dist/types.d.ts CHANGED
@@ -555,9 +555,13 @@ export interface InboxThreadView {
555
555
  externalId: string;
556
556
  displayName?: string;
557
557
  mode: InboxThreadMode;
558
+ /** Its channel was disconnected: readable as history, no replies. */
559
+ channelDisconnected?: true;
558
560
  unreadCount: number;
559
561
  lastMessageAt?: string;
560
562
  lastMessagePreview?: string;
563
+ /** When the customer last wrote: what a messaging window counts from. Absent if they never did. Needs the platform's AGF-WA-LIVE. */
564
+ lastInboundAt?: string;
561
565
  /** Workspace user currently responsible for the thread. */
562
566
  assignedHumanUserId?: string;
563
567
  /** AGF-ASSIGN-P1-CLOSE. ISO timestamp when the human conversation was
@@ -2635,7 +2639,8 @@ export interface MoveCaseSlotInput {
2635
2639
  assigneeRef?: string | null;
2636
2640
  assigneeName?: string;
2637
2641
  }
2638
- export type AppWebhookEventName = 'case.submitted' | 'case.state_changed' | 'case.closed' | 'case.customer_request' | 'case.payment_changed';
2642
+ export type AppCaseWebhookEventName = 'case.submitted' | 'case.state_changed' | 'case.closed' | 'case.customer_request' | 'case.payment_changed';
2643
+ export type AppWebhookEventName = AppCaseWebhookEventName | 'conversation.message' | 'channel.status_changed';
2639
2644
  export interface AppWebhook {
2640
2645
  url: string;
2641
2646
  events: AppWebhookEventName[];
@@ -2645,13 +2650,47 @@ export interface AppWebhook {
2645
2650
  createdAt: string;
2646
2651
  updatedAt: string;
2647
2652
  }
2648
- /** What the platform POSTs. No customer data: read the case with `forTenant(tenantId).cases.get(caseId)`. */
2649
- export interface AppWebhookEvent {
2650
- /** Delivery id — dedupe on it (retries keep it). */
2653
+ /** What every delivery has. `id` is the delivery id: dedupe on it (retries keep it). */
2654
+ interface AppWebhookEventBase {
2651
2655
  id: string;
2652
- type: AppWebhookEventName;
2653
2656
  createdAt: string;
2654
2657
  tenantId: string;
2658
+ }
2659
+ /**
2660
+ * What the platform POSTs. No customer data: read with your own credential. Narrow on `type`.
2661
+ * A new event only arrives once the App lists it in `webhook.set({ events })`.
2662
+ */
2663
+ export type AppWebhookEvent = AppCaseWebhookEvent | AppConversationMessageWebhookEvent | AppChannelStatusWebhookEvent;
2664
+ /**
2665
+ * A message was committed on a thread of one of this App's agents, on any inbox channel. Only to the App that owns the
2666
+ * agent. No text, sender name or phone: read it with `forTenant(tenantId).inbox.forAgent(agentId)`. A burst on one thread
2667
+ * is coalesced (first at once, then at most one per second, per direction and source), so treat it as "this thread changed
2668
+ * up to `at`", not as one event per message. Delivery can fail for good: read again when your client reconnects.
2669
+ */
2670
+ export interface AppConversationMessageWebhookEvent extends AppWebhookEventBase {
2671
+ type: 'conversation.message';
2672
+ data: {
2673
+ threadId: string;
2674
+ channelId: string;
2675
+ agentId: string;
2676
+ direction: InboxMessageDirection;
2677
+ source: InboxMessageSource;
2678
+ at: string;
2679
+ };
2680
+ }
2681
+ /** A channel of one of this App's agents changed status. Only to the App that owns the agent; the last status of a burst wins. */
2682
+ export interface AppChannelStatusWebhookEvent extends AppWebhookEventBase {
2683
+ type: 'channel.status_changed';
2684
+ data: {
2685
+ channelId: string;
2686
+ agentId: string;
2687
+ status: string;
2688
+ at: string;
2689
+ };
2690
+ }
2691
+ /** Read the case with `forTenant(tenantId).cases.get(caseId)`. */
2692
+ export interface AppCaseWebhookEvent extends AppWebhookEventBase {
2693
+ type: AppCaseWebhookEventName;
2655
2694
  data: {
2656
2695
  caseId: string;
2657
2696
  caseNumber: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentforge-io/sdk-server",
3
- "version": "4.52.0",
3
+ "version": "4.54.0",
4
4
  "description": "Server-side SDK for backend apps integrating with AgentForge platform. Auth via ChatToken, ak_live_ API key or App secret (sk_live_), with App installations across tenants.",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",