@replicer/sdk 0.2.0 → 0.3.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.
@@ -36,7 +36,7 @@ interface OkResponse {
36
36
  * `code` values the API returns in its flat error body `{ error, code }`. Branch on `code`, never on
37
37
  * the human-readable `error` text. New codes may be added; fall back to the HTTP status.
38
38
  */
39
- type ApiErrorCode = 'validation_error' | 'bad_request' | 'unauthorized' | 'forbidden' | 'insufficient_scope' | 'not_found' | 'method_not_allowed' | 'conflict' | 'idempotency_key_reuse' | 'webhook_endpoint_limit' | 'webhook_endpoint_key_revoked' | 'webhook_endpoint_admin_disabled' | 'redelivery_limit' | 'test_mode_unsupported' | 'payload_too_large' | 'rate_limited' | 'rate_limit_exceeded' | 'rate_limiter_unavailable' | 'insufficient_balance' | 'quota_exceeded' | 'channel_not_configured' | 'sender_not_supported' | 'media_not_supported' | 'email_provider_not_supported' | 'internal_error' | 'bad_gateway' | 'service_unavailable' | 'gateway_timeout' | 'upstream_timeout' | (string & {});
39
+ type ApiErrorCode = 'validation_error' | 'bad_request' | 'unauthorized' | 'forbidden' | 'insufficient_scope' | 'not_found' | 'method_not_allowed' | 'conflict' | 'idempotency_key_reuse' | 'webhook_endpoint_limit' | 'webhook_endpoint_key_revoked' | 'webhook_endpoint_admin_disabled' | 'webhook_endpoint_in_use' | 'agent_in_use' | 'redelivery_limit' | 'test_mode_unsupported' | 'payload_too_large' | 'rate_limited' | 'rate_limit_exceeded' | 'rate_limiter_unavailable' | 'insufficient_balance' | 'quota_exceeded' | 'channel_not_configured' | 'sender_not_supported' | 'media_not_supported' | 'email_provider_not_supported' | 'internal_error' | 'bad_gateway' | 'service_unavailable' | 'gateway_timeout' | 'upstream_timeout' | (string & {});
40
40
  interface CreatePhoneCallInput {
41
41
  /** Agent id; must belong to your organization. */
42
42
  agent_id: string;
@@ -80,6 +80,26 @@ interface CancelCallInput {
80
80
  interface CancelCampaignPendingInput {
81
81
  campaign_id: string;
82
82
  }
83
+ interface SimulateInboundCallInput {
84
+ /** Id of one of your phone numbers (see `phoneNumber.list`); it must have an active inbound agent. */
85
+ phone_number_id: string;
86
+ /**
87
+ * Caller number. Default `+15550100000`. Use `+15550100004` or `+15550100005` for the other
88
+ * documented test outcomes; the unanswered numbers (`+15550100001` to `+15550100003`) are rejected.
89
+ */
90
+ from?: string;
91
+ /** Same key and body returns the same simulated call; same key, different body → 422 `idempotency_key_reuse`. */
92
+ idempotency_key?: string;
93
+ }
94
+ interface SimulateInboundCallResponse {
95
+ call_id: string;
96
+ /** `in_progress` for a new call; a replay returns the call's current status. */
97
+ status: string;
98
+ agent_id: string;
99
+ phone_number_id: string;
100
+ /** E.164 number that was called. */
101
+ phone_number: string;
102
+ }
83
103
  interface EnqueueCallResponse {
84
104
  call_id: string;
85
105
  /** `pending` or `scheduled` for a new call; a replay of an `idempotency_key` returns the call's current status. */
@@ -101,14 +121,25 @@ interface CancelCampaignPendingResponse {
101
121
  }
102
122
  /**
103
123
  * Call statuses (lowercase snake_case; filters also accept any case and `in-progress`). Final states: `analyzed` (the normal end state once post-call analysis is done),
104
- * `completed` (ended, analysis pending), `failed`, `cancelled`, `missed`, `error`.
124
+ * `completed` (ended, analysis pending), `failed`, `cancelled`, `missed`, `error`, `forwarded`.
125
+ *
126
+ * `forwarding` and `forwarded` belong to inbound calls that could not be taken by the agent
127
+ * (concurrent-call limit reached, agent unavailable) on a number with a `fallback_number`: the
128
+ * call is `forwarding` while it is handed over, then `forwarded`. A forwarded call has `duration`
129
+ * 0, is not billed and has no transcript; `disconnection_reason` is `fallback_concurrency_limit`
130
+ * or `fallback_agent_unavailable`. If the handover fails the call ends `failed` with
131
+ * `disconnection_reason` `fallback_transfer_failed`.
105
132
  */
106
- type CallStatus = 'pending' | 'scheduled' | 'queued' | 'retry' | 'in_progress' | 'completed' | 'analyzed' | 'failed' | 'cancelled' | 'missed' | 'error';
133
+ type CallStatus = 'pending' | 'scheduled' | 'queued' | 'retry' | 'in_progress' | 'completed' | 'analyzed' | 'failed' | 'cancelled' | 'missed' | 'error' | 'forwarding' | 'forwarded';
107
134
  /** Sentiment detected by the post-call analysis (lowercase). */
108
135
  type CallSentiment = 'positive' | 'neutral' | 'negative' | 'unknown';
109
136
  interface ListCallsParams extends PageParams {
110
137
  status?: CallStatus;
111
138
  direction?: CallDirection;
139
+ /** Only calls handled by this agent. */
140
+ agent_id?: string;
141
+ /** Only calls that involve this phone number (the number called for inbound calls, the number placed from for outbound calls). Calls made before `phone_number_id` existed are not matched. */
142
+ phone_number_id?: string;
112
143
  /** ISO 8601 lower bound on `started_at`. */
113
144
  date_from?: string;
114
145
  /** ISO 8601 upper bound on `started_at`. */
@@ -128,7 +159,7 @@ interface Call {
128
159
  transcript?: unknown;
129
160
  recording: string | null;
130
161
  call_successful: boolean | null;
131
- /** Credits consumed; `0` for a call that cost nothing (e.g. never connected), `null` until it is billed. */
162
+ /** Whole platform tokens debited from the organization's balance for the call (not a currency amount); `0` for a call that cost nothing (e.g. never connected), `null` until it is billed. */
132
163
  token_cost: number | null;
133
164
  agent_id: string | null;
134
165
  campaign_id: string | null;
@@ -142,6 +173,12 @@ interface Call {
142
173
  metadata: Record<string, unknown> | null;
143
174
  /** When the post-call analysis finished (`summary`, `sentiment`, `call_successful` are final), or `null`. */
144
175
  analyzed_at: string | null;
176
+ /** The organization's number involved in the call: the number called (inbound) or placed from (outbound), in E.164. `null` for calls made before this field existed. */
177
+ phone_number: string | null;
178
+ /** The id of `phone_number` (see `phoneNumber.list`), or `null`. Also `null` if the number was released afterwards. */
179
+ phone_number_id: string | null;
180
+ /** Variables the agent extracted during the call, by name, or `null` until the call is analyzed (`{}` when it extracted none). */
181
+ extracted_variables: Record<string, unknown> | null;
145
182
  }
146
183
  interface CreateCampaignInput {
147
184
  name: string;
@@ -261,8 +298,47 @@ interface PhoneNumber {
261
298
  is_active: boolean;
262
299
  inbound_agent_id: string | null;
263
300
  inbound_enabled: boolean;
301
+ /**
302
+ * E.164 number that inbound calls are forwarded to when the agent cannot take them (concurrent-call
303
+ * limit reached, agent unavailable). `null` when not set.
304
+ */
305
+ fallback_number: string | null;
264
306
  created_at: string;
265
307
  }
308
+ interface UpdatePhoneNumberInput {
309
+ /**
310
+ * The number to forward to, or `null` to remove it. E.164 (`+39 02 1234 5678` is accepted and
311
+ * normalized). It must be a valid number in the same country as the phone number, not a
312
+ * premium-rate or shared-cost number, and not one of your Replicer phone numbers. Only available
313
+ * on phone numbers purchased through Replicer (`409 conflict` otherwise).
314
+ */
315
+ fallback_number?: string | null;
316
+ /**
317
+ * The inbound agent that answers this number: an active agent of your organization with direction
318
+ * `inbound` (`400 validation_error` otherwise). `null` removes the agent and turns inbound routing
319
+ * off (`inbound_enabled` becomes `false`). Changing to another agent keeps the routing as it is.
320
+ * Setting an agent does not turn routing on: use `phoneNumber.provisionInbound`.
321
+ * Send at least one of `fallback_number` and `inbound_agent_id`.
322
+ */
323
+ inbound_agent_id?: string | null;
324
+ }
325
+ interface ImportPhoneNumberInput {
326
+ /** The number you own, E.164 (`+39 02 1234 5678` is accepted and normalized). Already connected → `409 conflict`. */
327
+ phone_number: string;
328
+ /** Free-text name, up to 100 characters. Returned as `label`. */
329
+ label?: string;
330
+ /** Two-letter ISO country code. */
331
+ country?: string;
332
+ /** SIP trunk details of your provider, used to dial out from this number. Never returned by the API. */
333
+ sip_domain?: string;
334
+ sip_username?: string;
335
+ sip_password?: string;
336
+ /**
337
+ * Inbound agent (active, direction `inbound`). When given, inbound routing is turned on at once;
338
+ * if that fails nothing is created.
339
+ */
340
+ inbound_agent_id?: string;
341
+ }
266
342
  /** Query parameters of `phoneNumber.deprovisionInbound`: the ids returned by `provisionInbound`. At least one is required. */
267
343
  interface DeprovisionInboundParams {
268
344
  trunk_id?: string;
@@ -471,6 +547,78 @@ interface Agent {
471
547
  phone_number_id: string | null;
472
548
  created_at: string;
473
549
  }
550
+ interface ListAgentsParams extends PageParams {
551
+ /** `false` lists the deactivated agents instead of the active ones (default `true`). */
552
+ is_active?: boolean;
553
+ }
554
+ /**
555
+ * One tool of an agent. The same tools as the dashboard: `end_call`, `transfer_call`,
556
+ * `extract_dynamic_variable`, `press_digit`, `agent_swap`, `check_calendar_availability`,
557
+ * `book_calendar_appointment`, `send_sms`, `send_email`, `schedule_callback`, `integration` and the
558
+ * legacy `custom`. Fields depend on the type (for example `calendarId` for the calendar tools,
559
+ * `transfer_destination` for `transfer_call`). `send_whatsapp` tools are set up in the dashboard and
560
+ * rejected here. For your own endpoints prefer [API tools](`agentTool.create`).
561
+ */
562
+ interface AgentToolConfig {
563
+ type: string;
564
+ name: string;
565
+ description?: string;
566
+ [field: string]: unknown;
567
+ }
568
+ interface AgentDetail {
569
+ id: string;
570
+ agent_name: string;
571
+ agent_type: AgentType;
572
+ call_direction: CallDirection;
573
+ description: string | null;
574
+ language: string | null;
575
+ /** Voice descriptor, as listed in the dashboard voice picker. */
576
+ voice: string | null;
577
+ prompt: string;
578
+ /** Spoken opening line; empty = generated by the agent. */
579
+ greeting: string;
580
+ knowledge_base_ids: string[];
581
+ tools: AgentToolConfig[];
582
+ is_active: boolean;
583
+ /** Workflow agents (`true`) can only be edited in the dashboard. */
584
+ is_advanced: boolean;
585
+ phone_number_id: string | null;
586
+ created_at: string;
587
+ updated_at: string;
588
+ }
589
+ type AgentTemplate = 'receptionist' | 'sales_qualifier' | 'callcenter_seller' | 'personal_secretary' | 'custom';
590
+ interface CreateAgentInput {
591
+ agent_name: string;
592
+ call_direction: CallDirection;
593
+ /** Starting prompt and greeting. Default `custom`, which needs your own `prompt`. */
594
+ template?: AgentTemplate;
595
+ /** Language code, for example `en-US` or `it-IT`. Default `en-US`. */
596
+ language?: string;
597
+ /** A voice of the catalog; default: the default voice of the language. */
598
+ voice?: string;
599
+ /** Replaces the template prompt. Required with the `custom` template. */
600
+ prompt?: string;
601
+ greeting?: string;
602
+ description?: string;
603
+ knowledge_base_ids?: string[];
604
+ /** An `end_call` tool is added when missing. */
605
+ tools?: AgentToolConfig[];
606
+ }
607
+ interface UpdateAgentInput {
608
+ agent_name?: string;
609
+ call_direction?: CallDirection;
610
+ language?: string;
611
+ voice?: string;
612
+ prompt?: string;
613
+ greeting?: string;
614
+ description?: string;
615
+ /** Replaces the agent's knowledge bases. */
616
+ knowledge_base_ids?: string[];
617
+ /** Replaces the agent's tools (WhatsApp tools it already has are kept). */
618
+ tools?: AgentToolConfig[];
619
+ /** Only `true`: reactivates a deactivated agent. */
620
+ is_active?: true;
621
+ }
474
622
  /** Calendar event statuses (lowercase snake_case). */
475
623
  type CalendarEventStatus = 'confirmed' | 'cancelled' | 'completed' | 'no_show';
476
624
  type CalendarType = 'location' | 'team_member' | 'resource';
@@ -493,6 +641,67 @@ interface Calendar {
493
641
  timezone: string;
494
642
  event_types: EventType[];
495
643
  }
644
+ /** One block of weekly opening hours of a calendar. */
645
+ interface CalendarAvailabilitySlot {
646
+ /** 0 (Sunday) to 6 (Saturday). */
647
+ day_of_week: Int;
648
+ /** `HH:MM`, 24-hour, in the calendar's time zone. */
649
+ start_time: string;
650
+ /** `HH:MM`, after `start_time`. */
651
+ end_time: string;
652
+ }
653
+ /** A calendar as returned by the calendar writes: the `Calendar` fields plus its state and weekly hours. */
654
+ interface CalendarDetail extends Calendar {
655
+ is_active: boolean;
656
+ /** Weekly opening hours, ordered by day then start time. */
657
+ availability: CalendarAvailabilitySlot[];
658
+ }
659
+ interface EventTypeInput {
660
+ name: string;
661
+ description?: string | null;
662
+ /** 5 to 480. */
663
+ duration_minutes: Int;
664
+ /** 0 to 60. Default 0. */
665
+ buffer_minutes?: Int;
666
+ }
667
+ interface CreateCalendarInput {
668
+ /** 1 to 100 characters. */
669
+ name: string;
670
+ description?: string | null;
671
+ type: CalendarType;
672
+ /** IANA time zone. Default `Europe/Rome`. */
673
+ timezone?: string;
674
+ /** Up to 32 event types to create together with the calendar. */
675
+ event_types?: EventTypeInput[];
676
+ /** Up to 100 weekly opening-hours blocks. */
677
+ availability?: CalendarAvailabilitySlot[];
678
+ }
679
+ interface UpdateCalendarInput {
680
+ name?: string;
681
+ description?: string | null;
682
+ type?: CalendarType;
683
+ timezone?: string;
684
+ /** `false` deactivates the calendar: it leaves `list-calendars` and cannot take new events. `true` reactivates it. */
685
+ is_active?: boolean;
686
+ /** Replaces ALL weekly opening hours; `[]` clears them. Omit to keep them. */
687
+ availability?: CalendarAvailabilitySlot[];
688
+ }
689
+ /** An event type as returned by the event type writes. */
690
+ interface EventTypeDetail extends EventType {
691
+ calendar_id: string;
692
+ is_active: boolean;
693
+ }
694
+ interface CreateEventTypeInput extends EventTypeInput {
695
+ calendar_id: string;
696
+ }
697
+ interface UpdateEventTypeInput {
698
+ name?: string;
699
+ description?: string | null;
700
+ duration_minutes?: Int;
701
+ buffer_minutes?: Int;
702
+ /** `false` deactivates the event type: it leaves `list-calendars`. `true` reactivates it. */
703
+ is_active?: boolean;
704
+ }
496
705
  interface ListCalendarEventsParams extends PageParams {
497
706
  calendar_id?: string;
498
707
  /** Any case is accepted (`confirmed`, `NO_SHOW`, `no_show`). */
@@ -746,6 +955,11 @@ interface UpdateWebhookEndpointInput {
746
955
  interface TestWebhookEndpointInput {
747
956
  /** Sends a sample event of this type (`livemode: false`). Omitted: a `webhook.test` event with `data: { "object": "test" }`. */
748
957
  event_type?: WebhookEventType;
958
+ /**
959
+ * How long to wait for the first attempt, in milliseconds (0 to 12000, default 12000). `0` returns
960
+ * as soon as the test delivery is queued, with `status: 'pending'`; read the outcome from the delivery list.
961
+ */
962
+ wait_ms?: Int;
749
963
  }
750
964
  /** Delivery statuses (lowercase). */
751
965
  type WebhookDeliveryStatus = 'pending' | 'succeeded' | 'failed' | 'abandoned';
@@ -928,5 +1142,110 @@ type AnyWebhookEvent = {
928
1142
  type: K;
929
1143
  };
930
1144
  }[WebhookEventType];
1145
+ /** A custom API tool of an agent: one LLM function whose calls are POSTed, signed, to `url`. */
1146
+ interface AgentTool {
1147
+ /** `tool_…` id. */
1148
+ id: string;
1149
+ agent_id: string;
1150
+ /** LLM function name, unique per agent: `^[a-z][a-z0-9_]{0,63}$`. */
1151
+ name: string;
1152
+ /** Tells the agent when to use the tool. */
1153
+ description: string;
1154
+ /** HTTPS URL on a public host (port 443). Redirects are not followed. */
1155
+ url: string;
1156
+ /** JSON Schema object (`{ "type": "object", "properties": {…}, "required": […] }`) of the arguments the agent may send. */
1157
+ parameters: Record<string, unknown>;
1158
+ /** Request timeout in milliseconds (1000 to 20000, default 8000). Never retried. */
1159
+ timeout_ms: Int;
1160
+ /** Webhook endpoint whose signing secret signs the requests. The request goes to `url`, not to the endpoint URL. */
1161
+ webhook_endpoint_id: string;
1162
+ /** Whether the agent speaks `execution_message` while the call is running (only if it takes longer than about 0.7 s). */
1163
+ speak_during_execution: boolean;
1164
+ execution_message: string | null;
1165
+ /** What the agent says when the call fails or times out; `null` uses a generic sentence. */
1166
+ error_message: string | null;
1167
+ /** false for a tool created with a test (`rpl_test_`) key. */
1168
+ livemode: boolean;
1169
+ created_by: WebhookEndpointCreatedBy;
1170
+ created_at: string;
1171
+ updated_at: string;
1172
+ }
1173
+ interface CreateAgentToolInput {
1174
+ agent_id: string;
1175
+ name: string;
1176
+ description: string;
1177
+ url: string;
1178
+ /** JSON Schema object. Default: no arguments. */
1179
+ parameters?: Record<string, unknown>;
1180
+ /** 1000 to 20000, default 8000. */
1181
+ timeout_ms?: Int;
1182
+ webhook_endpoint_id: string;
1183
+ speak_during_execution?: boolean;
1184
+ execution_message?: string | null;
1185
+ error_message?: string | null;
1186
+ /**
1187
+ * A retry with the same key (per organization) and body returns the tool already created instead of
1188
+ * creating a second one. Same key, different body → 422 `idempotency_key_reuse`. The `Idempotency-Key`
1189
+ * header works too.
1190
+ */
1191
+ idempotency_key?: string;
1192
+ }
1193
+ /** At least one field. `agent_id` cannot change. */
1194
+ interface UpdateAgentToolInput {
1195
+ name?: string;
1196
+ description?: string;
1197
+ url?: string;
1198
+ parameters?: Record<string, unknown>;
1199
+ timeout_ms?: Int;
1200
+ webhook_endpoint_id?: string;
1201
+ speak_during_execution?: boolean;
1202
+ /** `null` clears it. */
1203
+ execution_message?: string | null;
1204
+ /** `null` clears it. */
1205
+ error_message?: string | null;
1206
+ }
1207
+ interface ListAgentToolsParams extends PageParams {
1208
+ agent_id: string;
1209
+ }
1210
+ interface TestAgentToolInput {
1211
+ /** Sample arguments for the test call. Default `{}`. */
1212
+ arguments?: Record<string, unknown>;
1213
+ }
1214
+ /** Result of `agentTool.test`: one signed sample call to the tool URL. */
1215
+ interface TestAgentToolResponse {
1216
+ status: 'succeeded' | 'failed';
1217
+ latency_ms: Int;
1218
+ /** HTTP status your server answered, or `null` when no response was received. */
1219
+ response_status: Int | null;
1220
+ /** Start of your server's response body (at most 1 KB), only when it is a JSON object with a `result` key; any other body is not returned. */
1221
+ response_body_truncated: string | null;
1222
+ /** Fixed error sentence when `status` is `failed` (or a `2xx` answer has no `result`), else `null`. */
1223
+ error: string | null;
1224
+ }
1225
+ /** The JSON body Replicer POSTs to a tool URL. Verify `Replicer-Signature` before trusting it. */
1226
+ interface ToolCall<Args = Record<string, unknown>> {
1227
+ /** `tcall_…`, unique per invocation, also sent as `Replicer-Tool-Call-Id`. Use it for idempotency. */
1228
+ id: string;
1229
+ object: 'tool_call';
1230
+ created_at: string;
1231
+ tool: {
1232
+ id: string;
1233
+ name: string;
1234
+ };
1235
+ agent: {
1236
+ id: string;
1237
+ };
1238
+ call: {
1239
+ id: string;
1240
+ direction: 'inbound' | 'outbound' | 'web';
1241
+ from: string | null;
1242
+ to: string | null;
1243
+ };
1244
+ arguments: Args;
1245
+ }
1246
+ /** What your server answers with (2xx). `result` is read to the agent as data. */
1247
+ interface ToolCallResponse {
1248
+ result: unknown;
1249
+ }
931
1250
 
932
- export type { UpdateWebhookEndpointInput as $, Agent as A, CreateCalendarEventInput as B, CreatePhoneCallInput as C, CreateCalendarEventResponse as D, EnqueueCallResponse as E, FailFileInput as F, GetCampaignResponse as G, UpdateCalendarEventInput as H, ListMessagesParams as I, SendSmsInput as J, KnowledgeBaseCreateInput as K, ListCallsParams as L, Message as M, SendMessageResponse as N, OkResponse as O, Page as P, SendWhatsappInput as Q, SendEmailInput as R, StartCampaignResponse as S, CreateTtsInput as T, UpdateSourceInput as U, CreateTtsResponse as V, ListTtsParams as W, TtsGeneration as X, CreateWebhookEndpointInput as Y, WebhookEndpointWithSecret as Z, WebhookEndpoint as _, CancelCampaignPendingResponse as a, TestWebhookEndpointInput as a0, TestWebhookEndpointResponse as a1, ListWebhookDeliveriesParams as a2, WebhookDelivery as a3, ListWebhookDeliveryAttemptsParams as a4, WebhookDeliveryAttempt as a5, ListEventsParams as a6, WebhookEvent as a7, AgentType as a8, AnyWebhookEvent as a9, KnowledgeBaseTextSource as aA, KnowledgeSourceStatus as aB, KnowledgeSourceType as aC, MessageChannel as aD, MessageDirection as aE, MessageStatus as aF, OptOut as aG, OptOutSource as aH, Pagination as aI, PhoneNumberType as aJ, TtsStatus as aK, WebhookDeliveryErrorClass as aL, WebhookDeliveryStatus as aM, WebhookEndpointCreatedBy as aN, WebhookEndpointDisabledReason as aO, WebhookEventDataMap as aP, WebhookEventEnvelope as aQ, WebhookEventType as aR, WebhookTestData as aS, ApiErrorCode as aa, CalendarEventStatus as ab, CalendarType as ac, CallDirection as ad, CallSentiment as ae, CallStatus as af, CampaignListItem as ag, CampaignStatus as ah, CancelCallInput as ai, CancelCampaignPendingInput as aj, ContactIdentityConflict as ak, ContactIdentityType as al, Conversation as am, ConversationChannel as an, ConversationStatus as ao, CreateCampaignResponse as ap, DeleteKnowledgeBaseSourceParams as aq, DeletedResource as ar, DeprovisionInboundParams as as, DeprovisionInboundRemaining as at, EventType as au, Int as av, KnowledgeBaseChunk as aw, KnowledgeBaseRejectedUrl as ax, KnowledgeBaseSourceSummary as ay, KnowledgeBaseStatus as az, Call as b, CreateCampaignInput as c, Campaign as d, ListCampaignsParams as e, PageParams as f, PhoneNumber as g, ProvisionInboundInput as h, ProvisionInboundResponse as i, KnowledgeBaseSourcesResponse as j, KnowledgeBaseResponse as k, KnowledgeBaseListResponse as l, KnowledgeBaseAddSourcesInput as m, KnowledgeBaseUpdateInput as n, PresignFileInput as o, PresignFileResponse as p, UpdateChunkInput as q, KnowledgeBaseSourceDetail as r, PresignFileDownloadResponse as s, ListContactsParams as t, Contact as u, CreateContactInput as v, CreateContactResponse as w, Calendar as x, ListCalendarEventsParams as y, CalendarEvent as z };
1251
+ export type { UpdateCalendarEventInput as $, ListAgentsParams as A, Agent as B, CreatePhoneCallInput as C, AgentDetail as D, EnqueueCallResponse as E, FailFileInput as F, GetCampaignResponse as G, CreateAgentInput as H, ImportPhoneNumberInput as I, UpdateAgentInput as J, KnowledgeBaseCreateInput as K, ListCallsParams as L, Calendar as M, CreateCalendarInput as N, OkResponse as O, Page as P, CalendarDetail as Q, UpdateCalendarInput as R, SimulateInboundCallInput as S, CreateEventTypeInput as T, UpdatePhoneNumberInput as U, EventTypeDetail as V, UpdateEventTypeInput as W, ListCalendarEventsParams as X, CalendarEvent as Y, CreateCalendarEventInput as Z, CreateCalendarEventResponse as _, SimulateInboundCallResponse as a, MessageChannel as a$, ListMessagesParams as a0, Message as a1, SendSmsInput as a2, SendMessageResponse as a3, SendWhatsappInput as a4, SendEmailInput as a5, CreateTtsInput as a6, CreateTtsResponse as a7, ListTtsParams as a8, TtsGeneration as a9, CallDirection as aA, CallSentiment as aB, CallStatus as aC, CampaignListItem as aD, CampaignStatus as aE, CancelCallInput as aF, CancelCampaignPendingInput as aG, ContactIdentityConflict as aH, ContactIdentityType as aI, Conversation as aJ, ConversationChannel as aK, ConversationStatus as aL, CreateCampaignResponse as aM, DeleteKnowledgeBaseSourceParams as aN, DeletedResource as aO, DeprovisionInboundParams as aP, DeprovisionInboundRemaining as aQ, EventType as aR, EventTypeInput as aS, Int as aT, KnowledgeBaseChunk as aU, KnowledgeBaseRejectedUrl as aV, KnowledgeBaseSourceSummary as aW, KnowledgeBaseStatus as aX, KnowledgeBaseTextSource as aY, KnowledgeSourceStatus as aZ, KnowledgeSourceType as a_, CreateWebhookEndpointInput as aa, WebhookEndpointWithSecret as ab, WebhookEndpoint as ac, UpdateWebhookEndpointInput as ad, TestWebhookEndpointInput as ae, TestWebhookEndpointResponse as af, ListWebhookDeliveriesParams as ag, WebhookDelivery as ah, ListWebhookDeliveryAttemptsParams as ai, WebhookDeliveryAttempt as aj, CreateAgentToolInput as ak, AgentTool as al, ListAgentToolsParams as am, UpdateAgentToolInput as an, TestAgentToolInput as ao, TestAgentToolResponse as ap, ListEventsParams as aq, WebhookEvent as ar, AgentTemplate as as, AgentToolConfig as at, AgentType as au, AnyWebhookEvent as av, ApiErrorCode as aw, CalendarAvailabilitySlot as ax, CalendarEventStatus as ay, CalendarType as az, CancelCampaignPendingResponse as b, MessageDirection as b0, MessageStatus as b1, OptOut as b2, OptOutSource as b3, Pagination as b4, PhoneNumberType as b5, ToolCall as b6, ToolCallResponse as b7, TtsStatus as b8, WebhookDeliveryErrorClass as b9, WebhookDeliveryStatus as ba, WebhookEndpointCreatedBy as bb, WebhookEndpointDisabledReason as bc, WebhookEventDataMap as bd, WebhookEventEnvelope as be, WebhookEventType as bf, WebhookTestData as bg, Call as c, CreateCampaignInput as d, Campaign as e, ListCampaignsParams as f, StartCampaignResponse as g, PageParams as h, PhoneNumber as i, ProvisionInboundInput as j, ProvisionInboundResponse as k, KnowledgeBaseSourcesResponse as l, KnowledgeBaseResponse as m, KnowledgeBaseListResponse as n, KnowledgeBaseAddSourcesInput as o, KnowledgeBaseUpdateInput as p, PresignFileInput as q, PresignFileResponse as r, UpdateSourceInput as s, UpdateChunkInput as t, KnowledgeBaseSourceDetail as u, PresignFileDownloadResponse as v, ListContactsParams as w, Contact as x, CreateContactInput as y, CreateContactResponse as z };
package/dist/webhooks.cjs CHANGED
@@ -27,15 +27,11 @@ __export(webhooks_exports, {
27
27
  verifyWebhookSignature: () => verifyWebhookSignature
28
28
  });
29
29
  module.exports = __toCommonJS(webhooks_exports);
30
+
31
+ // src/signature.ts
30
32
  var import_node_crypto = require("crypto");
31
- var WEBHOOK_SIGNATURE_HEADER = "Replicer-Signature";
32
- var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
33
- var WebhookSignatureError = class extends Error {
34
- constructor(message) {
35
- super(message);
36
- this.name = "WebhookSignatureError";
37
- }
38
- };
33
+ var SIGNATURE_HEADER = "Replicer-Signature";
34
+ var DEFAULT_TOLERANCE_SECONDS = 300;
39
35
  var HEX_SHA256 = /^[0-9a-f]{64}$/i;
40
36
  var UNIX_SECONDS = /^\d{1,12}$/;
41
37
  function parseHeader(header) {
@@ -56,20 +52,10 @@ function parseHeader(header) {
56
52
  if (timestamp === null || signatures.length === 0) return null;
57
53
  return { timestamp, signatures };
58
54
  }
59
- function assertNoRenamedSignature(input) {
60
- if (!input || typeof input !== "object") return;
61
- const fields = input;
62
- if (fields.header === void 0 && "signature" in fields) {
63
- throw new TypeError(
64
- `'signature' was renamed to 'header' in @replicer/sdk 0.2.0: pass the ${WEBHOOK_SIGNATURE_HEADER} header value as 'header'`
65
- );
66
- }
67
- }
68
55
  function sign(secret, timestamp, payload) {
69
56
  return (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestamp}.`).update(payload).digest();
70
57
  }
71
- function verifyWebhookSignature(input) {
72
- assertNoRenamedSignature(input);
58
+ function verifySignatureHeader(input) {
73
59
  if (!input || typeof input.header !== "string") return false;
74
60
  const payload = input.payload;
75
61
  if (typeof payload !== "string" && !(payload instanceof Uint8Array)) return false;
@@ -77,7 +63,7 @@ function verifyWebhookSignature(input) {
77
63
  if (secrets.length === 0) return false;
78
64
  const parsed = parseHeader(input.header);
79
65
  if (!parsed) return false;
80
- const tolerance = typeof input.toleranceSeconds === "number" && Number.isFinite(input.toleranceSeconds) && input.toleranceSeconds >= 0 ? input.toleranceSeconds : DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
66
+ const tolerance = typeof input.toleranceSeconds === "number" && Number.isFinite(input.toleranceSeconds) && input.toleranceSeconds >= 0 ? input.toleranceSeconds : DEFAULT_TOLERANCE_SECONDS;
81
67
  const nowMs = (input.now ?? /* @__PURE__ */ new Date()).getTime();
82
68
  if (!Number.isFinite(nowMs)) return false;
83
69
  if (Math.abs(nowMs / 1e3 - parsed.timestamp) > tolerance) return false;
@@ -90,6 +76,29 @@ function verifyWebhookSignature(input) {
90
76
  }
91
77
  return match;
92
78
  }
79
+
80
+ // src/webhooks.ts
81
+ var WEBHOOK_SIGNATURE_HEADER = SIGNATURE_HEADER;
82
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
83
+ var WebhookSignatureError = class extends Error {
84
+ constructor(message) {
85
+ super(message);
86
+ this.name = "WebhookSignatureError";
87
+ }
88
+ };
89
+ function assertNoRenamedSignature(input) {
90
+ if (!input || typeof input !== "object") return;
91
+ const fields = input;
92
+ if (fields.header === void 0 && "signature" in fields) {
93
+ throw new TypeError(
94
+ `'signature' was renamed to 'header' in @replicer/sdk 0.2.0: pass the ${WEBHOOK_SIGNATURE_HEADER} header value as 'header'`
95
+ );
96
+ }
97
+ }
98
+ function verifyWebhookSignature(input) {
99
+ assertNoRenamedSignature(input);
100
+ return verifySignatureHeader(input);
101
+ }
93
102
  function constructEvent(input) {
94
103
  assertNoRenamedSignature(input);
95
104
  if (!verifyWebhookSignature(input)) {
@@ -105,6 +114,9 @@ function constructEvent(input) {
105
114
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
106
115
  throw new WebhookSignatureError("Webhook payload is not a JSON object");
107
116
  }
117
+ if (parsed.object !== "event") {
118
+ throw new WebhookSignatureError("Webhook payload is not an event");
119
+ }
108
120
  return parsed;
109
121
  }
110
122
  // Annotate the CommonJS export names for ESM import in node:
@@ -1,5 +1,5 @@
1
- import { a7 as WebhookEvent } from './types-CmxwElVc.cjs';
2
- export { a9 as AnyWebhookEvent, aP as WebhookEventDataMap, aR as WebhookEventType } from './types-CmxwElVc.cjs';
1
+ import { ar as WebhookEvent } from './types-DXQsrvOU.cjs';
2
+ export { av as AnyWebhookEvent, bd as WebhookEventDataMap, bf as WebhookEventType } from './types-DXQsrvOU.cjs';
3
3
 
4
4
  /** Name of the signature header (HTTP header names are case-insensitive). */
5
5
  declare const WEBHOOK_SIGNATURE_HEADER = "Replicer-Signature";
@@ -33,8 +33,9 @@ declare class WebhookSignatureError extends Error {
33
33
  declare function verifyWebhookSignature(input: VerifyWebhookSignatureInput): boolean;
34
34
  /**
35
35
  * Verify the signature, then parse the body. Throws `WebhookSignatureError` when the signature is
36
- * not valid (see `verifyWebhookSignature`) or the body is not a JSON object, and `TypeError` when
37
- * given the 0.1.0 `signature` field instead of `header`.
36
+ * not valid (see `verifyWebhookSignature`) or the body is not a JSON object with `object: "event"`
37
+ * (a signed API tool call is signed the same way and must not pass as an event), and `TypeError`
38
+ * when given the 0.1.0 `signature` field instead of `header`.
38
39
  */
39
40
  declare function constructEvent<T = Record<string, unknown>>(input: VerifyWebhookSignatureInput): WebhookEvent<T>;
40
41
 
@@ -1,5 +1,5 @@
1
- import { a7 as WebhookEvent } from './types-CmxwElVc.js';
2
- export { a9 as AnyWebhookEvent, aP as WebhookEventDataMap, aR as WebhookEventType } from './types-CmxwElVc.js';
1
+ import { ar as WebhookEvent } from './types-DXQsrvOU.js';
2
+ export { av as AnyWebhookEvent, bd as WebhookEventDataMap, bf as WebhookEventType } from './types-DXQsrvOU.js';
3
3
 
4
4
  /** Name of the signature header (HTTP header names are case-insensitive). */
5
5
  declare const WEBHOOK_SIGNATURE_HEADER = "Replicer-Signature";
@@ -33,8 +33,9 @@ declare class WebhookSignatureError extends Error {
33
33
  declare function verifyWebhookSignature(input: VerifyWebhookSignatureInput): boolean;
34
34
  /**
35
35
  * Verify the signature, then parse the body. Throws `WebhookSignatureError` when the signature is
36
- * not valid (see `verifyWebhookSignature`) or the body is not a JSON object, and `TypeError` when
37
- * given the 0.1.0 `signature` field instead of `header`.
36
+ * not valid (see `verifyWebhookSignature`) or the body is not a JSON object with `object: "event"`
37
+ * (a signed API tool call is signed the same way and must not pass as an event), and `TypeError`
38
+ * when given the 0.1.0 `signature` field instead of `header`.
38
39
  */
39
40
  declare function constructEvent<T = Record<string, unknown>>(input: VerifyWebhookSignatureInput): WebhookEvent<T>;
40
41
 
package/dist/webhooks.js CHANGED
@@ -1,33 +1,18 @@
1
+ import {
2
+ DEFAULT_TOLERANCE_SECONDS,
3
+ SIGNATURE_HEADER,
4
+ verifySignatureHeader
5
+ } from "./chunk-CIXVIMX2.js";
6
+
1
7
  // src/webhooks.ts
2
- import { createHmac, timingSafeEqual } from "crypto";
3
- var WEBHOOK_SIGNATURE_HEADER = "Replicer-Signature";
4
- var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
8
+ var WEBHOOK_SIGNATURE_HEADER = SIGNATURE_HEADER;
9
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = DEFAULT_TOLERANCE_SECONDS;
5
10
  var WebhookSignatureError = class extends Error {
6
11
  constructor(message) {
7
12
  super(message);
8
13
  this.name = "WebhookSignatureError";
9
14
  }
10
15
  };
11
- var HEX_SHA256 = /^[0-9a-f]{64}$/i;
12
- var UNIX_SECONDS = /^\d{1,12}$/;
13
- function parseHeader(header) {
14
- let timestamp = null;
15
- const signatures = [];
16
- for (const part of header.split(",")) {
17
- const eq = part.indexOf("=");
18
- if (eq <= 0) continue;
19
- const key = part.slice(0, eq).trim();
20
- const value = part.slice(eq + 1).trim();
21
- if (key === "t") {
22
- if (timestamp !== null || !UNIX_SECONDS.test(value)) return null;
23
- timestamp = Number(value);
24
- } else if (key === "v1" && HEX_SHA256.test(value)) {
25
- signatures.push(Buffer.from(value, "hex"));
26
- }
27
- }
28
- if (timestamp === null || signatures.length === 0) return null;
29
- return { timestamp, signatures };
30
- }
31
16
  function assertNoRenamedSignature(input) {
32
17
  if (!input || typeof input !== "object") return;
33
18
  const fields = input;
@@ -37,30 +22,9 @@ function assertNoRenamedSignature(input) {
37
22
  );
38
23
  }
39
24
  }
40
- function sign(secret, timestamp, payload) {
41
- return createHmac("sha256", secret).update(`${timestamp}.`).update(payload).digest();
42
- }
43
25
  function verifyWebhookSignature(input) {
44
26
  assertNoRenamedSignature(input);
45
- if (!input || typeof input.header !== "string") return false;
46
- const payload = input.payload;
47
- if (typeof payload !== "string" && !(payload instanceof Uint8Array)) return false;
48
- const secrets = [input.secret, ...Array.isArray(input.secrets) ? input.secrets : []].filter((s) => typeof s === "string" && s !== "");
49
- if (secrets.length === 0) return false;
50
- const parsed = parseHeader(input.header);
51
- if (!parsed) return false;
52
- const tolerance = typeof input.toleranceSeconds === "number" && Number.isFinite(input.toleranceSeconds) && input.toleranceSeconds >= 0 ? input.toleranceSeconds : DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
53
- const nowMs = (input.now ?? /* @__PURE__ */ new Date()).getTime();
54
- if (!Number.isFinite(nowMs)) return false;
55
- if (Math.abs(nowMs / 1e3 - parsed.timestamp) > tolerance) return false;
56
- let match = false;
57
- for (const secret of secrets) {
58
- const expected = sign(secret, parsed.timestamp, payload);
59
- for (const received of parsed.signatures) {
60
- if (timingSafeEqual(expected, received)) match = true;
61
- }
62
- }
63
- return match;
27
+ return verifySignatureHeader(input);
64
28
  }
65
29
  function constructEvent(input) {
66
30
  assertNoRenamedSignature(input);
@@ -77,6 +41,9 @@ function constructEvent(input) {
77
41
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
78
42
  throw new WebhookSignatureError("Webhook payload is not a JSON object");
79
43
  }
44
+ if (parsed.object !== "event") {
45
+ throw new WebhookSignatureError("Webhook payload is not an event");
46
+ }
80
47
  return parsed;
81
48
  }
82
49
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@replicer/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Typed JavaScript/TypeScript client for the Replicer API: calls, campaigns, knowledge bases, contacts, calendar, messages, TTS and webhooks.",
5
5
  "keywords": [
6
6
  "replicer",
@@ -41,12 +41,25 @@
41
41
  "default": "./dist/webhooks.cjs"
42
42
  }
43
43
  },
44
+ "./tools": {
45
+ "import": {
46
+ "types": "./dist/tools.d.ts",
47
+ "default": "./dist/tools.js"
48
+ },
49
+ "require": {
50
+ "types": "./dist/tools.d.cts",
51
+ "default": "./dist/tools.cjs"
52
+ }
53
+ },
44
54
  "./package.json": "./package.json"
45
55
  },
46
56
  "typesVersions": {
47
57
  "*": {
48
58
  "webhooks": [
49
59
  "./dist/webhooks.d.ts"
60
+ ],
61
+ "tools": [
62
+ "./dist/tools.d.ts"
50
63
  ]
51
64
  }
52
65
  },