@intelligence-cloud/sdk 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/LICENSE +22 -0
- package/README.md +384 -2
- package/dist/index.cjs +2838 -0
- package/dist/index.d.cts +12321 -0
- package/dist/index.d.ts +12321 -0
- package/dist/index.js +2788 -0
- package/package.json +59 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.1 (2026-11-29)
|
|
4
|
+
|
|
5
|
+
- Insights Hub "monitor all numbers" is never switched on. `provisionSeatCustomer` used to set `monitor_all_numbers` to true; it now leaves it off and switches it off where an earlier run switched it on. Insights Hub covers the lines listed for the location, which `addFrontlineUser` already adds. Re-run `provisionSeatCustomer` for customers set up with 0.1.0.
|
|
6
|
+
|
|
7
|
+
## 0.1.0: 2026-11-18 (Base Intelligence Seat manager lines)
|
|
8
|
+
|
|
9
|
+
- On the Base Intelligence Seat a manager's own phone line is not captured. `addManager(customer, user, { activateAlerts? })` no longer takes `ownExtension` or a string third argument (a string, or any option other than `activateAlerts`, now throws `FilterError` before any write): a manager is mapped to exactly the end-user lines at the location, and their own extension is never mapped, nor added to First Alert or Insights Hub. `AddManagerOptions` has `activateAlerts` only.
|
|
10
|
+
- `syncNumbers` sets every manager's mapping to exactly the lines (as for integration users); a number on a manager that is not a line is removed.
|
|
11
|
+
|
|
12
|
+
## 0.1.0: 2026-11-17 (review 2)
|
|
13
|
+
|
|
14
|
+
- Licence: the Intelligence Cloud SDK Licence (Copyright (c) 2026 Creo Solutions, Inc. d/b/a Tresic), the same text in every SDK: partners, their customers and contractors may use, copy, modify and distribute the SDK solely to access Intelligence Cloud; provided as is.
|
|
15
|
+
- `provisionSeatCustomer` never adopts a same-named company: pass `companyId` (store it from the first run), or a company is reused only when its name and primary contact email both match; otherwise `ConflictError` (`company_name_conflict`) before any write. New `companies.findCompanies`.
|
|
16
|
+
- Integration users are first-class: `addIntegrationUser` (tagged `department: "integration"`, all lines, every alert email off), `listIntegrationUsers`, `isIntegration`. They are never listed as end users or managers and keep every line as end users come and go. `removeUser` releases only an end user's line, and only one no other end user holds; removing an integration user, a manager or a multi-line user leaves every line in place. Managers are users with all three products. `syncNumbers` counts only end users holding exactly one line. `excludeUserIds` / `excludeEmails` on the customer object hide users from every workflow.
|
|
17
|
+
- Connector re-runs match on the phone-system domain; a connector in `error`, `inactive` or with changed settings gets the new settings and key and is restarted. `ProvisionResult.existing` lists what was found (`connector:updated`).
|
|
18
|
+
- `offboardCustomer`: pause the After Call webhook, clear the First Alert webhook, stop the connector, deactivate integration users, deactivate the company.
|
|
19
|
+
- Webhooks: `parseAfterCallEvent` returns an `UnknownEvent` (`isUnknownEvent`) for other event types instead of throwing, and refuses bodies over `MAX_EVENT_BYTES` (256 KB) with `PayloadTooLargeError`. `Deduplicator.isDuplicate` (same name and meaning in every SDK); `seen` is kept as an alias. Answer within 2 seconds. `examples/after-call-sample.json` added.
|
|
20
|
+
- Token store: optional `withLock`; `FileTokenStore` shares tokens safely between processes on one machine. A rate-limited renewal retries the same refresh token and never signs in.
|
|
21
|
+
- `Retry-After` over 60 seconds is thrown, not waited on. `loginRateLimitWait` option (default 60; 0 throws at once). `PasswordExpiredError`.
|
|
22
|
+
- Exception text never carries the server's error text (`serverMessage` holds it).
|
|
23
|
+
- `keepUnknownFields` option (the deny-list always applies).
|
|
24
|
+
- Alerts `numbers`: North American numbers are sent as their last 10 digits. `dueOn` Dates use the local calendar date.
|
|
25
|
+
- `baseUrl` must be https (http only for localhost). Node.js 20 or later.
|
|
26
|
+
- Next.js example: webhook tokens move from `?token=` to a path segment (`app/api/ic-webhook/[token]`, `app/api/ic-alert-webhook/[token]`), 32 characters minimum; the calls action starts with `requireSignedIn()` (fails closed until wired) and searches only the viewer's locations.
|
|
27
|
+
|
|
28
|
+
## 0.1.0 (2026-11-16)
|
|
29
|
+
|
|
30
|
+
First release.
|
|
31
|
+
|
|
32
|
+
- Client with email and password sign-in for a dedicated integration user (MFA off), single-use refresh tokens with rotation and a serialised renewal lock, pluggable token store.
|
|
33
|
+
- Retries for 429 and 5xx with backoff, jitter and `Retry-After`; 60 s wait on a sign-in 429.
|
|
34
|
+
- One error hierarchy over the API's error shapes.
|
|
35
|
+
- Responses keep only documented fields.
|
|
36
|
+
- Every documented operation as a typed method, paged lists with `iter*` iterators, strict filter validation.
|
|
37
|
+
- Read → merge → write helpers for full-replacement writes; idempotent user create with half-create recovery; connector create, reactivate and deactivate wait for the final status, checking every 10 seconds for up to 10 minutes (`timeout`, `checkInterval`).
|
|
38
|
+
- Base Intelligence Seat workflows: `provisionSeatCustomer`, `getSeatCustomer`, `addFrontlineUser`, `addManager`, `activateSeatAlerts`, `changeUserExtension`, `removeUser`, `listFrontlineUsers`, `listManagers`, `syncNumbers`. Users are invited last, once their lines are mapped; the two alerts are created off and switched on when the first manager is in place.
|
|
39
|
+
- Conversation intelligence helpers: calls, transcripts, recording links, alerts, tasks, insights, webhook configuration.
|
|
40
|
+
- After Call webhook receiver: `parseAfterCallEvent` and `Deduplicator`.
|
|
41
|
+
- New calls and alerts reach you on the After Call and First Alert webhooks (2026-11-17). The Next.js First Alert receiver example (`app/api/ic-alert-webhook/route.ts`) reads only the alert id and fetches the alert and its call with `getAlert(alertId, { withCall: true })`. The README covers a one-off catch-up after an outage.
|
|
42
|
+
- Examples: plain Node and Next.js App Router (route handler and server action).
|
|
43
|
+
- Shipped as a packed build, `intelligence-cloud-sdk-0.1.0.tgz`, with no runtime dependencies.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Intelligence Cloud SDK Licence
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Creo Solutions, Inc. d/b/a Tresic
|
|
4
|
+
|
|
5
|
+
Permission is granted to Intelligence Cloud partners, their customers, and contractors working for
|
|
6
|
+
either, to use, copy, modify and distribute this software, in source or compiled form and as part of
|
|
7
|
+
their own applications, solely to access Intelligence Cloud services under an agreement with Tresic
|
|
8
|
+
or an authorised Tresic partner. Keep this notice in copies of the source.
|
|
9
|
+
|
|
10
|
+
Use of the Intelligence Cloud API, with or without this software, is governed by the Intelligence
|
|
11
|
+
Cloud API and SDK Terms (https://docs.intelligence.cloud/terms/api) and by your
|
|
12
|
+
agreement with Tresic or with your provider.
|
|
13
|
+
|
|
14
|
+
This licence grants no right in any Tresic patent or patent application, trademark, or the
|
|
15
|
+
Intelligence Cloud service, other than the right to use this software as provided. This licence ends
|
|
16
|
+
when your right to access Intelligence Cloud ends.
|
|
17
|
+
|
|
18
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
|
|
19
|
+
WITHOUT LIMITATION THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
20
|
+
NON-INFRINGEMENT. CREO SOLUTIONS, INC. D/B/A TRESIC IS NOT LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
22
|
+
SOFTWARE OR ITS USE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,385 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Intelligence Cloud SDK for TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@intelligence-cloud/sdk` 0.1.1. The partner API for Node.js 20+ and Next.js server code (route handlers, server actions).
|
|
4
|
+
|
|
5
|
+
- **Customer lifecycle** (admin credentials): companies, locations, users, products, connectors, First Alert rules, Insights Hub, plus the Base Intelligence Seat workflows.
|
|
6
|
+
- **Conversation intelligence** (frontline credentials): calls, transcripts, recording links, alerts, tasks, insights, and the After Call webhook.
|
|
7
|
+
|
|
8
|
+
Zero runtime dependencies (uses the global `fetch`). ESM and CommonJS builds with full types.
|
|
9
|
+
|
|
10
|
+
The API reference is at https://docs.intelligence.cloud/reference.html; the source of truth is https://docs.intelligence.cloud/openapi.yaml.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @intelligence-cloud/sdk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The package holds only the compiled SDK and pulls in no dependencies.
|
|
19
|
+
|
|
20
|
+
Alternative, from the source download: it includes a packed build, `intelligence-cloud-sdk-0.1.1.tgz`.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
unzip typescript.zip -d vendor-src # creates vendor-src/typescript
|
|
24
|
+
npm install ./vendor-src/typescript/intelligence-cloud-sdk-0.1.1.tgz # from your project
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { Client } from "@intelligence-cloud/sdk"; // ESM
|
|
29
|
+
const { Client } = require("@intelligence-cloud/sdk"); // CommonJS
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
To rebuild from source: `npm install && npm run build && npm pack` in the SDK folder (the dev tools stay in that folder). `npm run generate` regenerates the types and operation table from `openapi.yaml` (download it from https://docs.intelligence.cloud/openapi.yaml and pass its path: `node scripts/generate.mjs openapi.yaml`).
|
|
33
|
+
|
|
34
|
+
## Credentials
|
|
35
|
+
|
|
36
|
+
Today every integration signs in with the email and password of a **dedicated integration user**. Turn MFA off for that user's company (`mfa_enforced: false`). **API keys arrive in December 2026.**
|
|
37
|
+
|
|
38
|
+
Use one client per credential:
|
|
39
|
+
|
|
40
|
+
| Client | Login | For |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| Admin (`IC_ADMIN_EMAIL`, `IC_ADMIN_PASSWORD` in the examples) | a reseller admin integration user | customer lifecycle |
|
|
43
|
+
| Data (`IC_DATA_EMAIL`, `IC_DATA_PASSWORD` in the examples) | a frontline integration user mapped to the lines you need | calls, alerts, tasks, insights |
|
|
44
|
+
|
|
45
|
+
Admin logins get empty lists from the conversation-data endpoints by design. The intelligence helpers check the role once and throw `FrontlineRequiredError` instead of returning nothing.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
const ic = new Client({
|
|
49
|
+
email: process.env.IC_DATA_EMAIL!,
|
|
50
|
+
password: process.env.IC_DATA_PASSWORD!,
|
|
51
|
+
// baseUrl: "https://app.intelligence.cloud/api/v1", (default; https only, plain http for localhost only)
|
|
52
|
+
// timeout: 30, (seconds)
|
|
53
|
+
// tokenStore: new FileTokenStore("/var/lib/my-app/ic-tokens.json"), (default: memory)
|
|
54
|
+
// loginRateLimitWait: 60, (seconds to wait once on a sign-in 429; 0 throws at once)
|
|
55
|
+
// keepUnknownFields: false, (true keeps fields the reference doesn't list yet)
|
|
56
|
+
// userAgent: "riverbend-bi-sync/1.0",
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
If you pass your own `fetch`, keep certificate verification on.
|
|
61
|
+
|
|
62
|
+
`keepUnknownFields: true` passes on response fields the reference doesn't list yet, so you can use a new field before you update the SDK. It applies to the customer-lifecycle (admin) reads: `/me`, sign-in and every conversation-data read (calls, transcripts, alerts, tasks, insights) always keep only the documented fields, and the one-time sign-in link is never passed on.
|
|
63
|
+
|
|
64
|
+
### How the client signs in
|
|
65
|
+
|
|
66
|
+
- It signs in on the first call and keeps the access and refresh tokens in its token store.
|
|
67
|
+
- It renews the access token before it expires and once after a 401. Refresh tokens are **single use**: the SDK marks the old one spent before sending it and stores the new pair before using it. Renewals are serialised, so concurrent calls share one refresh.
|
|
68
|
+
- Sign-in is rate limited. On a 429 at sign-in the client waits `loginRateLimitWait` seconds (60) once; set it to 0 inside a web request to fail at once.
|
|
69
|
+
- A rate-limited renewal (429) waits and retries the same refresh token; it never falls back to a sign-in. Any `Retry-After` over 60 seconds is not waited on: the client throws `RateLimitError` (`retryAfter` in seconds).
|
|
70
|
+
- An integration user with MFA on gets `MfaRequiredError`: "Integration users need MFA off for their company. API keys arrive in December 2026."
|
|
71
|
+
- A sign-in with an expired password throws `PasswordExpiredError`: a person must set a new password for the integration user in the app; then update your secret store.
|
|
72
|
+
|
|
73
|
+
### Several workers or serverless
|
|
74
|
+
|
|
75
|
+
Use one integration user per worker, or share one user's tokens through a store that **locks**. Without a lock, two processes can renew with the same refresh token, and the second renewal signs the user out everywhere. Never create a client per request: each one signs in.
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
interface TokenStore {
|
|
79
|
+
get(): Tokens | null | Promise<Tokens | null>;
|
|
80
|
+
set(tokens: Tokens | null): void | Promise<void>; // { accessToken, refreshToken, expiresAt }
|
|
81
|
+
withLock?<T>(fn: () => Promise<T>): Promise<T>; // held by every process sharing the store
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The client signs in and renews inside `withLock`, and re-reads the store first, so a pair another process just renewed is reused. `FileTokenStore(path)` does this for every process on one machine (a `.lock` file beside the token file, mode 0600). For several machines, implement `withLock` over your shared cache (for example a lock key with an expiry).
|
|
86
|
+
|
|
87
|
+
`client.close()` forgets the tokens. `client.logout()` **ends every session of that user**, the web app and other jobs included; the SDK never calls it on its own, and most integrations never need it.
|
|
88
|
+
|
|
89
|
+
## Quick start: conversation intelligence
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { Client } from "@intelligence-cloud/sdk";
|
|
93
|
+
|
|
94
|
+
const ic = new Client({ email: process.env.IC_DATA_EMAIL!, password: process.env.IC_DATA_PASSWORD! });
|
|
95
|
+
await ic.requireFrontline();
|
|
96
|
+
|
|
97
|
+
const since = new Date(Date.now() - 24 * 3600 * 1000);
|
|
98
|
+
|
|
99
|
+
// one page, with totals for the whole filter
|
|
100
|
+
const page = await ic.searchCalls({ dateFrom: since, sentiment: "negative" });
|
|
101
|
+
console.log(page.summary.total_calls, page.items.length, page.nextCursor);
|
|
102
|
+
|
|
103
|
+
// every match, following cursors 100 at a time
|
|
104
|
+
for await (const call of ic.iterCalls({ dateFrom: since, phone: "555-0142" })) {
|
|
105
|
+
const detail = await ic.getCall(call.id!);
|
|
106
|
+
const lines = await ic.getTranscript(call.id!);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// the recording: a signed WAV link, valid 120 minutes
|
|
110
|
+
const { url, expiresAt } = await ic.getRecordingUrl(callId);
|
|
111
|
+
|
|
112
|
+
// alerts for one rule, one alert with its call
|
|
113
|
+
const alerts = await ic.searchAlerts({ alertName: "Upset Customer", dateFrom: since });
|
|
114
|
+
const alert = await ic.getAlert(alertId, { withCall: true }); // null when not visible
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The same helpers are on `ic.intelligence` (`ic.intelligence.searchCalls(…)`).
|
|
118
|
+
|
|
119
|
+
### Calls
|
|
120
|
+
|
|
121
|
+
| Method | Does |
|
|
122
|
+
|---|---|
|
|
123
|
+
| `searchCalls(filters)` | One page: `items`, `summary` (totals for all pages), `total`, `nextCursor`, `hasMore` |
|
|
124
|
+
| `iterCalls(filters)` | Every match, newest first (`maxItems` stops early) |
|
|
125
|
+
| `getCall(callId)` | Full detail: analysis, tasks, recording fields. `NotFoundError` when outside the login's view |
|
|
126
|
+
| `getTranscript(callId)` | Lines in order: `time`, `speaker` ("Speaker 1" … "Speaker N"), `name`, `text` |
|
|
127
|
+
| `getRecordingUrl(callId)` | `{ url, expiresAt }` only |
|
|
128
|
+
|
|
129
|
+
Call filters:
|
|
130
|
+
|
|
131
|
+
| Filter | Notes |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `phone` | A number or extension in any format; partial digits match. Sent as the API's `search` |
|
|
134
|
+
| `text` | Names (typo-tolerant), summary, key points, transcript. Sent as `search`. At least 2 characters. Give `phone` **or** `text` |
|
|
135
|
+
| `dateFrom`, `dateTo` | `Date` or full RFC 3339 timestamp; sent as UTC. Date-only strings are refused. Default window: 00:00 UTC seven days ago until now. At most 366 days when both are given |
|
|
136
|
+
| `status` | `completed`, `missed`, `voicemail`, `failed`, `cancelled` |
|
|
137
|
+
| `sentiment` | `crisis`, `very_negative`, `negative`, `mildly_negative`, `below_neutral`, `neutral`, `positive`, `none` |
|
|
138
|
+
| `hasOpenTasks` | `true` only |
|
|
139
|
+
| `multiLeg` | `true`: more than one leg; `false`: single leg |
|
|
140
|
+
| `locationIds` | Up to 50 location ids |
|
|
141
|
+
| `companyId` | One company |
|
|
142
|
+
| `limit`, `cursor` | Page size 1–100 (default 10) and the next-page cursor |
|
|
143
|
+
|
|
144
|
+
**Recording links** are signed HTTPS links to the WAV audio. Fetch with a plain `GET` and no `Authorization` header; `Range` requests work. They expire 120 minutes after issue. Treat them as secrets: never log or store them; call `getRecordingUrl` again for a fresh link.
|
|
145
|
+
|
|
146
|
+
### Alerts
|
|
147
|
+
|
|
148
|
+
| Method | Does |
|
|
149
|
+
|---|---|
|
|
150
|
+
| `searchAlerts(filters)` | One page of First Alert hits; `total` counts every match |
|
|
151
|
+
| `iterAlerts(filters)` | Every match |
|
|
152
|
+
| `getAlert(alertId, { withCall })` | One alert by id (searched by id, no date window), with the call when asked; `null` when not visible |
|
|
153
|
+
| `getAlertsDashboard({ dateFrom, dateTo, locationIds, companyId })` | `kpis`, `top_triggered`, `recent_alerts` |
|
|
154
|
+
|
|
155
|
+
Alert filters: `alertName` (exact, case-sensitive rule name), `numbers` (up to 25; formatting is stripped to digits; substring match on caller or callee), `text` (names, numbers, summary, or an alert id), `sentiment`, `dateFrom`, `dateTo`, `locationIds`, `topic` (exact topic slug), `companyId`, `limit`, `cursor`.
|
|
156
|
+
|
|
157
|
+
Use these for look-ups. Alerts as they fire arrive on the [First Alert webhook](#receiving-the-first-alert-webhook); calls arrive on the After Call webhook. Don't poll the API for new data: read it when a person asks for something or when a webhook tells you to fetch details, and run scheduled jobs (exports, digests) at most once a day over a bounded date window.
|
|
158
|
+
|
|
159
|
+
### Tasks and insights
|
|
160
|
+
|
|
161
|
+
| Method | Filters |
|
|
162
|
+
|---|---|
|
|
163
|
+
| `listTasks(filters)` / `iterTasks` | `status` (`pending`, `in_progress`, `done`, `overdue`, `open`), `todayStart`, `callId`, `taskId`, `dueOn` (`YYYY-MM-DD` or Date), `dateFrom`, `dateTo` (creation time; no default window), `search`, `locationIds`, `companyId`, `limit`, `cursor`. `summary` counts by display status |
|
|
164
|
+
| `getInsightsDashboard({ start, end, trendingLimit, locationIds, companyId })` | `start` and `end` required, at most 366 days apart |
|
|
165
|
+
| `listTopicCalls(slug, filters)` / `iterTopicCalls` | `dateFrom`, `dateTo`, `sentiment` (`positive`, `neutral`, `negative`), `outcome` (`completed`, `missed`, `pending`), `search`, `locationIds`, `companyId`, `limit`, `cursor` |
|
|
166
|
+
|
|
167
|
+
### Webhook configuration
|
|
168
|
+
|
|
169
|
+
| Method | Credential | Does |
|
|
170
|
+
|---|---|---|
|
|
171
|
+
| `getAfterCallWebhook(locationId)` | any | The location's After Call webhook, or `null` |
|
|
172
|
+
| `setAfterCallWebhook(locationId, url, enabled = true)` | admin | One HTTPS URL per location. `enabled: false` pauses it (there is no delete) |
|
|
173
|
+
| `testAfterCallWebhook(locationId)` | admin | Sends the test event to the saved URL. Returns `{ success, http_status }` |
|
|
174
|
+
| `getFirstAlertWebhook(locationId)` | admin | The location alert webhook URL, or `null` |
|
|
175
|
+
| `setFirstAlertWebhook(locationId, url \| null)` | admin | Read → merge → write, so monitored numbers are kept |
|
|
176
|
+
| `testFirstAlertWebhook(locationId, url?)` | admin | Returns `{ success, http_status }` |
|
|
177
|
+
|
|
178
|
+
## Receiving the After Call webhook
|
|
179
|
+
|
|
180
|
+
Each processed call at the location is POSTed to the URL (`type: "end_of_call_summary"`). The webhook covers **every call at the location**, whatever users' number mappings say.
|
|
181
|
+
|
|
182
|
+
- Use HTTPS and a token of at least 32 random characters in the URL **path** (never a query string), one per location. Compare it in constant time (`crypto.timingSafeEqual`). Deliveries are not signed: the URL is the secret. Keep the path out of your proxy, CDN and APM logs.
|
|
183
|
+
- Answer 2xx within 2 seconds and do the work after responding. Redirects count as failures.
|
|
184
|
+
- Answer 2xx to event types you don't handle (`isUnknownEvent`) and ignore them. Answer 400 only for a body that isn't JSON, 413 for a body over 256 KB, 404 for a wrong token.
|
|
185
|
+
- Treat the event as a notification: read the call with `getCall(event.call.id)` before you write anything from it into another system. A 404 means drop it.
|
|
186
|
+
- Three attempts in all, then the delivery is dropped. Expect duplicates (retries, calls with several legs): upsert on `call.id`.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { Deduplicator, isUnknownEvent, parseAfterCallEvent } from "@intelligence-cloud/sdk";
|
|
190
|
+
|
|
191
|
+
const dedup = new Deduplicator(); // in-memory LRU; pass { store } for a shared store (a database or cache)
|
|
192
|
+
|
|
193
|
+
const event = parseAfterCallEvent(rawBody); // WebhookPayloadError (400) / PayloadTooLargeError (413)
|
|
194
|
+
if (isUnknownEvent(event)) return; // a type you don't handle: answer 2xx
|
|
195
|
+
if (!event.is_test && !(await dedup.isDuplicate(event.call.id))) {
|
|
196
|
+
queue.push(event.call.id); // read the call later with getCall(event.call.id)
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`parseAfterCallEvent(body, { maxBytes })` refuses bodies over `MAX_EVENT_BYTES` (262144). `Deduplicator.isDuplicate(id)` is true for a repeat (the same name and meaning in the Python and PHP SDKs; the older `seen` still works). `examples/after-call-sample.json` is a sample event: post it to your receiver locally, e.g. `curl -X POST http://localhost:3000/api/ic-webhook/$IC_WEBHOOK_TOKEN -H 'Content-Type: application/json' -d @examples/after-call-sample.json`.
|
|
201
|
+
|
|
202
|
+
The Next.js route handler in `examples/nextjs/app/api/ic-webhook/[token]/route.ts` shows the whole receiver: path token, size cap, parse, de-duplicate, respond, then read the call with `after()`.
|
|
203
|
+
|
|
204
|
+
## Receiving the First Alert webhook
|
|
205
|
+
|
|
206
|
+
Webhooks are how your integration hears about new calls and alerts: the After Call webhook for every call, the First Alert webhook for each alert as it fires. Subscribe to them; don't poll the API for new data.
|
|
207
|
+
|
|
208
|
+
The First Alert webhook posts the alert that fired: the alert id, the rule, the location, the call and the time. Read only the alert id, answer 2xx at once, then fetch the alert and its call with a frontline integration user in Manager Alerts:
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
const alertId = alertIdFrom(await request.text()); // see examples/nextjs/app/api/ic-alert-webhook/[token]/route.ts
|
|
212
|
+
if (alertId && !(await alertDedup.isDuplicate(alertId))) { // a second Deduplicator, keyed on the alert id
|
|
213
|
+
after(async () => {
|
|
214
|
+
const alert = await ic.getAlert(alertId, { withCall: true }); // null when this login can't see it
|
|
215
|
+
if (alert?.id && alert.call_id) await pageOnCallManager(alert.id, alert.call_id); // ids only
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
If your receiver was unavailable, read the window you missed once and skip alerts you have already handled. Alerts are dated by their call, so start the window 30 minutes before the receiver went down:
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
for await (const a of ic.iterAlerts({ dateFrom: new Date(wentDown.getTime() - 30 * 60_000), dateTo: cameBack })) {
|
|
224
|
+
if (a.id && !(await alertDedup.isDuplicate(a.id))) await handleAlert(a.id);
|
|
225
|
+
}
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
## Quick start: Base Intelligence Seat (admin credentials)
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
const admin = new Client({ email: process.env.IC_ADMIN_EMAIL!, password: process.env.IC_ADMIN_PASSWORD! });
|
|
232
|
+
|
|
233
|
+
const customer = await admin.provisionSeatCustomer({
|
|
234
|
+
// companyId: storedCompanyId, pass the id from the first run on every re-run
|
|
235
|
+
companyName: "Northgate Dental",
|
|
236
|
+
primaryAdmin: { name: "Avery Chen", email: "avery.chen@example.com", phone: "+15555550150" },
|
|
237
|
+
location: { name: "Northgate Dental - Main", street: "12 Elm St", city: "Springfield", state: "IL", country: "United States", zipcode: "62704" },
|
|
238
|
+
threatPhrases, // provided by your Tresic contact
|
|
239
|
+
connector: { apiUrl: "https://pbx.example.com/ns-api/v2", domain: "northgate.example", apiKey: phoneSystemKey },
|
|
240
|
+
// mfaOff: true, only for a company that holds an integration user
|
|
241
|
+
// sso: { domain: "northgate.example.com" }, returns the DNS TXT record to publish
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
// End users first: each line is mapped, then the invitation is emailed.
|
|
245
|
+
await admin.addFrontlineUser(customer, { email: "front.desk@example.com", firstName: "Alex", lastName: "Kim" }, "2101");
|
|
246
|
+
// The first manager switches the two alerts on, then gets the invitation.
|
|
247
|
+
await admin.addManager(customer, { email: "office.manager@example.com", firstName: "Sam", lastName: "Ortiz" });
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
- Both alert rules are created **switched off**. `addManager` switches them on once the manager is set up (`activateAlerts: true`, the default). To switch them on yourself, pass `{ activateAlerts: false }` and call `activateSeatAlerts(customer)` when you are ready. Re-running `provisionSeatCustomer` never switches a rule off.
|
|
251
|
+
- **Store the returned `companyId` and pass it on every re-run.** Without it, an existing company is reused only when both its name and its primary contact email match. A same-named company with another contact throws `ConflictError` (`code: "company_name_conflict"`) before anything is written: company names are not unique, and a new customer's users must never land in another customer's company.
|
|
252
|
+
- Users are created **without** an invitation. The workflow maps their lines and sets their products and groups, and only then emails the invitation. If a mapping is refused, `ExtensionMappingError` is thrown and no invitation has been sent. Pass `sendInvitation: false` to invite later with `admin.users.resendInvitation(companyId, userId)`.
|
|
253
|
+
|
|
254
|
+
The workflows are also on `admin.workflows`.
|
|
255
|
+
|
|
256
|
+
| Workflow | Does |
|
|
257
|
+
|---|---|
|
|
258
|
+
| `provisionSeatCustomer(spec)` | Creates the company (MFA off only with `mfaOff`, read back to verify), turns on After Call, First Alert and Insights Hub, creates the single location, the groups "Manager Alerts" and "Insights Hub Access", the rules "Upset Customer" (sentiment below −40) and "Customer Threat" (threat phrases and sentiment below −20) routed to Manager Alerts, and Insights Hub access for the group. Optional connector and single sign-on domain claim. **Idempotent**: re-running finds the company by `companyId` (or by name and contact email), the location, groups and rules by name, and the connector by its phone-system domain (or name); it only creates what is missing, and brings existing rules back in line (Manager Alerts routing, current phrases). A connector found in `error`, `inactive` or with other settings gets the new settings and key, and is restarted. Both rules are created switched off and left off (see `addManager` and `activateSeatAlerts`). A connector that ends in `error` is recorded on the result (`connectorStatus`, `connectorStateReason`), not thrown. A deactivated company or location is an error unless `reactivate: true`. Returns every id, `created[]` and `existing[]` (`connector:updated` when the connector got new settings) |
|
|
259
|
+
| `getSeatCustomer(companyId, { locationName? })` | Rebuilds the customer object (location, groups, rules, connector) by name |
|
|
260
|
+
| `addFrontlineUser(customer, user, extension)` | End user, created without an invitation: After Call only, alert email off, their extension mapped, then the extension added to every manager and integration user, First Alert and Insights Hub, and last the invitation emailed. Needs a connector |
|
|
261
|
+
| `addIntegrationUser(customer, user)` | Integration user (reads calls, alerts and insights for another system): created without an invitation, tagged `department: "integration"`, all three products, both groups, every alert email off, mapped to all lines; last the invitation emailed. Password sign-in only. Never counted as a seat or a manager, never switches alerts on |
|
|
262
|
+
| `addManager(customer, user, { activateAlerts? = true })` | Manager, created without an invitation: After Call, First Alert and Insights Hub, both groups, alert email on, mapped to exactly the end-user lines at the location; then both alerts switched on, and last the invitation emailed. The manager's own phone line is not captured on the Seat: it is never mapped, nor added to First Alert or Insights Hub |
|
|
263
|
+
| `activateSeatAlerts(customer)` | Switches on the Upset Customer and Customer Threat rules. Returns the ids it switched on |
|
|
264
|
+
| `changeUserExtension(customer, userId, old, new)` | Moves a user's extension and re-syncs managers, integration users, First Alert and Insights Hub |
|
|
265
|
+
| `removeUser(customer, userId, { keepExtensions? })` | In order: leaves every group, clears the number mapping, takes the user's line off managers, integration users, First Alert and Insights Hub (unless `keepExtensions`), then deactivates. Only an end user releases a line, and only one no other end user still holds; removing a manager, an integration user or any non-manager holding several lines leaves every line in place (`kind` says which). Products are left as they are |
|
|
266
|
+
| `listFrontlineUsers(customer)` / `listManagers(customer)` / `listIntegrationUsers(customer)` | One page-through of the location's users. End user: After Call only. Manager: all three products. Integration user: `department: "integration"`, never in the other two lists |
|
|
267
|
+
| `syncNumbers(customer, { dryRun? })` | Pushes the union of end-user lines (end users holding exactly one line) to managers, integration users, First Alert and Insights Hub; managers and integration users end up with exactly the lines (any other number on their mapping is removed); `dryRun` returns the diff only |
|
|
268
|
+
| `offboardCustomer(customer, { deactivateCompany? = true })` | A customer leaves, in order: pause the After Call webhook, clear the First Alert webhook address, deactivate the connector (stops call capture), deactivate the integration users, deactivate the company. Safe to re-run. Ask your Tresic contact about the retention of the customer's data |
|
|
269
|
+
|
|
270
|
+
`customer` can be the object returned by `provisionSeatCustomer` / `getSeatCustomer`, or a company id. Add `excludeUserIds` / `excludeEmails` to the customer object to hide users from every workflow (they are never counted, never updated, and their lines don't count). `user` is `{ email, firstName, lastName, phoneNumber?, sendInvitation? (default true), authMethod?, idempotencyKey? }`. The result carries `invited` (this call emailed the invitation) and `alertsActivated` (rule ids this call switched on).
|
|
271
|
+
|
|
272
|
+
The **Customer Threat phrases are provided by your Tresic contact**. `provisionSeatCustomer` needs them whenever it creates the Customer Threat rule and throws `FilterError` otherwise. `upsetCustomerRule(groupIds)` and `customerThreatRule(groupIds, phrases)` build the two rule bodies if you create rules yourself.
|
|
273
|
+
|
|
274
|
+
Workflows find users by email, so a re-run carries on with the same user. When the API refuses a user's number mapping (connector not `active`, or an extension another location monitors), the workflow stops before touching managers, First Alert and Insights Hub and throws `ExtensionMappingError` (`userId`, `cause`). The user exists but has not been invited: fix the cause and run the workflow again. The re-run finds the user, finishes the setup and emails the invitation; it also re-sends the invitation to any user who has not accepted one yet. Any other failure part-way throws `WorkflowError` with `step` (the failing step), `partial` (ids done so far) and `cause` (the original error).
|
|
275
|
+
|
|
276
|
+
Notes:
|
|
277
|
+
- Numbers are the extensions and DIDs from the customer's phone system. Read them there with your own key; the API cannot list them. Keep each extension at exactly one location.
|
|
278
|
+
- User number mappings need the connector to be `active`. A 409 means the extension is already monitored at another location (`ConflictError.extensions` lists it).
|
|
279
|
+
- Users are created with an `Idempotency-Key` and without an invitation; the workflow emails it last unless `sendInvitation: false`.
|
|
280
|
+
- Manage integration users with `addIntegrationUser` (or tag them `department: "integration"`), so the Seat workflows never treat them as end users or managers.
|
|
281
|
+
|
|
282
|
+
## Low-level methods
|
|
283
|
+
|
|
284
|
+
Every documented operation is a method named after its `operationId`, grouped by the reference's sections. Path parameters come first, then the JSON body, then the query filters. Responses are returned as documented, with any undocumented field removed.
|
|
285
|
+
|
|
286
|
+
- **Paged lists** (`list*` with a cursor) return one `Page`: `{ items, nextCursor, hasMore, total, raw }`, with each row's `attributes` unwrapped into `items`.
|
|
287
|
+
- Each paged list has an `iter*` twin that follows cursors with `limit=100` and yields rows (`maxItems` stops early).
|
|
288
|
+
- Query filters accept the reference's names (`is_active`) or camelCase (`isActive`).
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
const page = await admin.companies.listCompanies(resellerId, { search: "Riverbend", isActive: true });
|
|
292
|
+
for await (const loc of admin.locations.iterCompanyLocations(companyId)) console.log(loc.location_name);
|
|
293
|
+
await admin.firstAlert.updateAlertRule(locationId, ruleId, { enabled: true });
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
| Namespace | Methods |
|
|
297
|
+
|---|---|
|
|
298
|
+
| `resellers` | `getResellerBranding` `updateResellerBranding` `getResellerSmtpSettings` `saveResellerSmtpSettings` `deleteResellerSmtpSettings` |
|
|
299
|
+
| `companies` | `listCompanies` `iterCompanies` `createCompany` `getCompaniesMfaSummary` `getCompany` `updateCompany` `deactivateCompany` `reactivateCompany` `getCompanyBranding` `updateCompanyBranding` · helpers `addProducts` `removeProducts` `findCompany` `findCompanies` |
|
|
300
|
+
| `sso` | `listCompanyDomains` `claimCompanyDomain` `removeCompanyDomain` `listDomainVerifications` `verifyDomain` `getIdentityProvider` `connectIdentityProvider` `disconnectIdentityProvider` `testIdentityProvider` |
|
|
301
|
+
| `products` | `listProducts` `listCompanyProducts` `listUserProducts` `enableUserProduct` `disableUserProduct` |
|
|
302
|
+
| `locations` | `listVerticals` `listCompanyLocations` `iterCompanyLocations` `createLocation` `getLocation` `updateLocation` `deactivateLocation` `reactivateLocation` · helpers `addProducts` `removeProducts` `findLocation` |
|
|
303
|
+
| `groups` | `listUserGroups` `iterUserGroups` `createUserGroup` `getUserGroup` `updateUserGroup` `deleteUserGroup` `getUserGroupMembership` `setUserGroupMembership` · helpers `addMembers` `removeMembers` `userGroupIds` `addUserToGroups` `removeUserFromGroups` `findGroup` |
|
|
304
|
+
| `connectors` | `listConnectorTypes` `testConnector` `listLocationConnectors` `iterLocationConnectors` `createConnector` `getConnector` `updateConnector` `deactivateConnector` `reactivateConnector` `listCompanyConnectors` `iterCompanyConnectors` · helpers `waitForStatus` `findConnector` |
|
|
305
|
+
| `firstAlert` | `listAlertRules` `iterAlertRules` `createAlertRule` `getAlertRule` `updateAlertRule` `deleteAlertRule` `duplicateAlertRule` `getFirstAlertConfig` `saveFirstAlertConfig` `testFirstAlertWebhook` `getAlertNotificationPreferences` `setAlertEmailPreferences` `setAlertDigestPreferences` · helpers `addMonitoredNumbers` `removeMonitoredNumbers` `setMonitoredNumbers` `setWebhookUrl` `addRuleGroups` `removeRuleGroups` `findRule` |
|
|
306
|
+
| `insightsHub` | `getInsightsHubSetup` `saveInsightsHubSetup` `updateInsightsHubSetup` `getInsightsHubConfig` `updateInsightsHubConfig` `getUserInsightsHubAccess` · helpers `addNumbers` `removeNumbers` `setNumbers` `addGroups` `removeGroups` |
|
|
307
|
+
| `users` | `listCompanyUsers` `iterCompanyUsers` `createCompanyUser` `getCompanyUser` `updateCompanyUser` `deactivateCompanyUser` `reactivateCompanyUser` `resendInvitation` `resetPassword` `getUserNumberMappings` `setUserNumberMappings` `listLocationUsers` `iterLocationUsers` `getLocationUser` · helpers `findUserByEmail` `addLocations` `removeLocations` `userNumbers` `addNumbers` `removeNumbers` `setNumbers` `replaceNumber` |
|
|
308
|
+
| `afterCallSettings` | `getUserAfterCallSettings` `updateUserAfterCallSettings` |
|
|
309
|
+
| `account` | `getMe` `listVisibleLocations` `iterVisibleLocations` |
|
|
310
|
+
| `calls` | `listCalls` `iterCalls` `getCall` `getCallTranscript` |
|
|
311
|
+
| `alerts` | `listAlerts` `iterAlerts` `getAlertsDashboard` |
|
|
312
|
+
| `tasks` | `listTasks` `iterTasks` |
|
|
313
|
+
| `insights` | `getInsightsDashboard` `listTopicCalls` `iterTopicCalls` |
|
|
314
|
+
| `webhooks` | `getAfterCallWebhook` `saveAfterCallWebhook` `testAfterCallWebhook` |
|
|
315
|
+
|
|
316
|
+
What the SDK does for you on these:
|
|
317
|
+
|
|
318
|
+
- **Full-replacement writes** (`enabled_products`, `member_ids`, `group_ids`, rule triggers and groups, First Alert numbers and webhook URL, Insights Hub numbers and groups, user number mappings, user locations) have `add*` / `remove*` / `set*` helpers that read, merge, then write.
|
|
319
|
+
- `users.createCompanyUser` always sends an `Idempotency-Key` (a new UUID per call unless you pass `{ idempotencyKey }`) and reuses it on retries. After a 422 it looks the user up by email and fixes the half-created user with PATCH.
|
|
320
|
+
- Webhook test results and connector dry runs never carry the server's error text.
|
|
321
|
+
- `connectors.createConnector`, `reactivateConnector` and `updateConnector` (when it reconnects) wait until the connector is `active`, and throw `ConnectorError` with `stateReason` (for example `invalid_permissions` for a key without the permissions the connector needs) when it lands in `error`. `deactivateConnector` waits for `inactive`. They check the status every 10 seconds for up to 10 minutes. Pass `{ wait: false }` to return at once, or `{ timeout, checkInterval }` in seconds.
|
|
322
|
+
- The connector dry run and the webhook tests return only `success` and the HTTP status.
|
|
323
|
+
- `client.intelligence` and `client.workflows` hold the helpers above; the same methods are also on the client itself.
|
|
324
|
+
|
|
325
|
+
## Filters and validation
|
|
326
|
+
|
|
327
|
+
The API ignores parameters it doesn't know and returns unfiltered data. The SDK accepts only the documented filters and checks them **before** sending:
|
|
328
|
+
|
|
329
|
+
- An unknown filter throws `FilterError`.
|
|
330
|
+
- Dates: a `Date` or a full RFC 3339 timestamp, always sent as UTC. `2026-11-01` alone is refused; use `2026-11-01T00:00:00Z`. A `Date` passed as `dueOn` is sent as its local calendar date.
|
|
331
|
+
- `numbers`: at most 25, stripped to digits; a North American number with its leading 1 is sent as the last 10 digits (`+1 555-555-0142` → `5555550142`), because some numbers are stored without the 1. `locationIds`: at most 50 (longer query strings are refused before they reach the API).
|
|
332
|
+
- Enum values, UUIDs, page sizes (1–100) and required filters are checked.
|
|
333
|
+
|
|
334
|
+
## Errors
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
IntelligenceCloudError
|
|
338
|
+
├── ApiError (status, code, message, requestId, operationId, serverMessage)
|
|
339
|
+
│ ├── AuthError 401 (MfaRequiredError: MFA on; PasswordExpiredError: password expired)
|
|
340
|
+
│ ├── NotFoundError 404, also for records outside your login's scope
|
|
341
|
+
│ ├── ConflictError 409 (extensions: the refused extensions on a number conflict; code company_name_conflict)
|
|
342
|
+
│ ├── ValidationError 400, 422
|
|
343
|
+
│ └── RateLimitError 429 after retries (retryAfter in seconds)
|
|
344
|
+
├── FilterError unsupported filter or value, raised before sending
|
|
345
|
+
├── ConnectorError connector ended in error (stateReason) or did not settle
|
|
346
|
+
├── FrontlineRequiredError conversation data requested with an admin login
|
|
347
|
+
├── ExtensionMappingError a workflow could not map a user's numbers (userId, cause)
|
|
348
|
+
├── WorkflowError a workflow stopped (step, partial, cause)
|
|
349
|
+
└── WebhookPayloadError body isn't a JSON object, or a malformed After Call event (400)
|
|
350
|
+
└── PayloadTooLargeError body over 256 KB (413)
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
- 429 and 5xx are retried up to 3 times with backoff and jitter, honouring `Retry-After` up to 60 seconds (a longer `Retry-After` is thrown at once). A `POST` is retried on 5xx only when it carries an `Idempotency-Key`.
|
|
354
|
+
- The API's different error shapes are normalised into `status`, `code` and `requestId`. The exception text (`message`) never carries the server's error text, which can echo phone numbers or names: it reads e.g. `HTTP 422 VALIDATION_ERROR (request_id …)`. The server's text is on `serverMessage`.
|
|
355
|
+
- Log `status`, `code` and `requestId`, not exception text or response bodies.
|
|
356
|
+
- The text of a 409 on number mappings is replaced with "Extension is already monitored at another location." and `extensions` lists the requested extensions that were refused.
|
|
357
|
+
- Show your own messages to end users.
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
import { ConflictError, NotFoundError, ValidationError } from "@intelligence-cloud/sdk";
|
|
361
|
+
|
|
362
|
+
try {
|
|
363
|
+
await admin.users.addNumbers(companyId, userId, connectorId, ["2101"]);
|
|
364
|
+
} catch (err) {
|
|
365
|
+
if (err instanceof ConflictError) { /* release the extension at the other location first */ }
|
|
366
|
+
else if (err instanceof ValidationError && err.code === "CONNECTOR_NOT_VALID") { /* connector not active */ }
|
|
367
|
+
else throw err;
|
|
368
|
+
}
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
## Secrets
|
|
372
|
+
|
|
373
|
+
Never log access or refresh tokens, passwords, phone-system keys, webhook URLs or recording links. The SDK logs nothing and never returns the one-time sign-in link the API can include when a user is created.
|
|
374
|
+
|
|
375
|
+
## Build from source
|
|
376
|
+
|
|
377
|
+
```bash
|
|
378
|
+
npm run typecheck && npm run build
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
## Support
|
|
382
|
+
|
|
383
|
+
Partner support: your Tresic contact. Security reports: security@tresic.cloud.
|
|
384
|
+
|
|
385
|
+
Intelligence Cloud SDK Licence. Copyright (c) 2026 Creo Solutions, Inc. d/b/a Tresic. Partners, their customers and contractors working for either may use, copy, modify and distribute the SDK solely to access Intelligence Cloud. Use of the API is governed by the Intelligence Cloud API and SDK Terms (https://docs.intelligence.cloud/terms/api) and your agreement with Tresic or your provider. Provided as is. See `LICENSE`.
|