@hirefinn/sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +63 -13
  2. package/dist/cjs/client.d.ts +13 -1
  3. package/dist/cjs/client.js +5 -0
  4. package/dist/cjs/core.d.ts +16 -3
  5. package/dist/cjs/core.js +25 -6
  6. package/dist/cjs/errors.d.ts +1 -1
  7. package/dist/cjs/errors.js +11 -0
  8. package/dist/cjs/generated/openapi.d.ts +19867 -5738
  9. package/dist/cjs/generated/operations.d.ts +26 -0
  10. package/dist/cjs/generated/operations.js +176 -0
  11. package/dist/cjs/generated/resources.d.ts +1050 -0
  12. package/dist/cjs/generated/resources.js +816 -0
  13. package/dist/cjs/index.d.ts +2 -2
  14. package/dist/cjs/index.js +4 -1
  15. package/dist/cjs/pagination.d.ts +3 -0
  16. package/dist/cjs/pagination.js +26 -5
  17. package/dist/cjs/resource.d.ts +30 -0
  18. package/dist/cjs/resource.js +23 -0
  19. package/dist/cjs/resources.d.ts +64 -57
  20. package/dist/cjs/resources.js +31 -36
  21. package/dist/cjs/types.d.ts +11 -3
  22. package/dist/cjs/webhooks.d.ts +11 -1
  23. package/dist/esm/client.d.ts +13 -1
  24. package/dist/esm/client.js +6 -1
  25. package/dist/esm/core.d.ts +16 -3
  26. package/dist/esm/core.js +24 -5
  27. package/dist/esm/errors.d.ts +1 -1
  28. package/dist/esm/errors.js +11 -0
  29. package/dist/esm/generated/openapi.d.ts +19867 -5738
  30. package/dist/esm/generated/operations.d.ts +26 -0
  31. package/dist/esm/generated/operations.js +173 -0
  32. package/dist/esm/generated/resources.d.ts +1050 -0
  33. package/dist/esm/generated/resources.js +795 -0
  34. package/dist/esm/index.d.ts +2 -2
  35. package/dist/esm/index.js +2 -2
  36. package/dist/esm/pagination.d.ts +3 -0
  37. package/dist/esm/pagination.js +25 -5
  38. package/dist/esm/resource.d.ts +30 -0
  39. package/dist/esm/resource.js +19 -0
  40. package/dist/esm/resources.d.ts +64 -57
  41. package/dist/esm/resources.js +24 -34
  42. package/dist/esm/types.d.ts +11 -3
  43. package/dist/esm/webhooks.d.ts +11 -1
  44. package/package.json +2 -1
package/README.md CHANGED
@@ -4,10 +4,11 @@ Typed client for the [Finn](https://hirefinn.ai) public API (`https://api.hirefi
4
4
  Types are generated from the API's OpenAPI spec; the client is a thin hand-written layer over `fetch` with
5
5
  retries, idempotency keys, typed errors, pagination and approval helpers. No runtime dependencies.
6
6
 
7
- - Node 18+ and modern browsers (anything with `fetch`)
7
+ - Node 18+ or any server runtime with `fetch` (Deno, Bun, edge workers). The API sends no CORS headers for
8
+ arbitrary origins, so a web page cannot call it: call it from your server and never ship a key to a browser.
8
9
  - ESM and CommonJS, with `.d.ts` types
9
10
 
10
- > Status: pre-release (0.2.0). MIT licensed (see `LICENSE`).
11
+ > Status: pre-release (0.4.0). MIT licensed (see `LICENSE`).
11
12
 
12
13
  ## Install
13
14
 
@@ -21,6 +22,7 @@ npm install @hirefinn/sdk
21
22
  import { Finn, isPendingApproval, FinnError } from '@hirefinn/sdk';
22
23
 
23
24
  const finn = new Finn({ apiKey: process.env.FINN_API_KEY }); // finn_live_..., finn_test_... or an OAuth finn_oat_... token
25
+ // Note: finn_test_... keys can read and build, but outward actions such as calls.create answer 403 `test_mode`.
24
26
 
25
27
  // List, retrieve
26
28
  const { data: finns } = await finn.finns.list({ limit: 20 });
@@ -41,6 +43,11 @@ if (isPendingApproval(res)) {
41
43
  for await (const c of finn.calls.listAll({ status: 'completed' })) {
42
44
  console.log(c.call_uuid);
43
45
  }
46
+
47
+ // A case's events, oldest first (pages follow next_after)
48
+ for await (const e of finn.cases.listAllEvents('5c1e8f3a-9b2d-4a7e-8c6f-1d3b5a7e9f20')) {
49
+ console.log(e.seq, e.type);
50
+ }
44
51
  ```
45
52
 
46
53
  ## Client options
@@ -50,12 +57,13 @@ new Finn({
50
57
  apiKey, // default: process.env.FINN_API_KEY
51
58
  baseUrl, // default: https://api.hirefinn.ai/v1
52
59
  org, // Finn-Org header: which org a multi-org token acts in
53
- version, // Finn-Version header: pins the API version, e.g. '2026-11-01'
60
+ version, // Finn-Version header; default DEFAULT_FINN_VERSION ('2026-11-01'), null sends none
54
61
  maxRetries: 2, // retries after the first attempt
55
62
  timeoutMs: 60_000, // per attempt
56
63
  fetch, // custom fetch (tests, proxies, older runtimes)
57
64
  autoIdempotency: true,
58
65
  maxRetryAfterMs: 60_000,
66
+ maxRetryWaitMs: 20_000, // total wait between retries of one request
59
67
  defaultHeaders: {},
60
68
  });
61
69
  ```
@@ -63,6 +71,8 @@ new Finn({
63
71
  Every method also takes a last `options` argument that overrides these per call:
64
72
  `{ idempotencyKey, org, version, maxRetries, timeoutMs, signal, headers }`.
65
73
 
74
+ On Node and other server runtimes the SDK sends `User-Agent: finn-node/<version>`.
75
+
66
76
  ## Resources
67
77
 
68
78
  | Property | Endpoints |
@@ -76,11 +86,14 @@ Every method also takes a last `options` argument that overrides these per call:
76
86
  | `finn.wallet` | `retrieve`, `listTransactions`, `listAllTransactions` |
77
87
  | `finn.doNotCall` | `list`, `listAll`, `add`, `remove` |
78
88
  | `finn.contacts` (CRM records) | `list`, `listAll`, `create`, `retrieve`, `update`, `timeline`, `timelineAll`, `addNote`, `listKinds`, `listFields` |
79
- | `finn.cases` | `list`, `listAll`, `retrieve`, `listEvents`, `start` |
89
+ | `finn.cases` | `list`, `listAll`, `retrieve`, `listEvents`, `listAllEvents`, `start` |
80
90
  | `finn.approvals` | `list`, `listAll`, `retrieve`, `decide`, `approve`, `reject`, `wait` |
81
91
  | `finn.agents` | `list`, `listAll`, `create`, `draft`, `retrieve`, `saveDraft`, `validate`, `test`, `publish`, `driveTest` |
82
92
  | `finn.chat` | `listChannels`; `conversations.{list, listAll, start, retrieve, listMessages, listAllMessages, send}`; `contacts.{list, listAll, retrieve, update}` |
83
93
 
94
+ The other operations (`finn.crm`, `finn.dialer`, `finn.webhooks`, `finn.organization`, `finn.sales` and more
95
+ `finn.finns` methods) are generated from the spec: see [Coverage](#coverage).
96
+
84
97
  Methods return the response body exactly as the spec describes it (older voice endpoints wrap it in
85
98
  `{ success, data }`). Request and response types come from `src/generated/openapi.ts`; schemas are exported as
86
99
  `Schemas`, e.g. `Schemas['Call']`.
@@ -94,15 +107,44 @@ const full = await finn.requestWithResponse('get', '/wallet'); // { data, status
94
107
 
95
108
  and endpoints newer than the SDK through `finn.rawRequest({ method, path, pathParams, query, body })`.
96
109
 
110
+ ### Coverage
111
+
112
+ <!-- generated:coverage:start (scripts/generate.mjs; do not edit by hand) -->
113
+ The SDK covers **165 of 165** operations in the spec (Finn API v1):
114
+ 72 through the hand-written methods above and 93 through generated ones, listed here.
115
+
116
+ | Property | Generated methods |
117
+ |---|---|
118
+ | `finn.finns` | `generate`, `getFlow`, `enableFlow`, `disableFlow`, `getSettings`, `getVariables`, `updateVariables`, `updateHandbook`, `updateSpeechSettings`, `updateDraft`, `duplicate`, `getShareLink`, `createShareLink`, `getStats`, `getOutcomes` |
119
+ | `finn.agents` | `archive` |
120
+ | `finn.chat` | `getAgent`, `updateAgent`, `testAgent` |
121
+ | `finn.crm` | `getSetup`, `getFilterSchema`, `searchRecords`, `queryRecords`, `countRecords`, `countRecordsByStage`, `getRecord`, `updateRecord`, `getRecordTimeline`, `getStageGate`, `listRecordDocuments`, `listRecordFiles`, `attachFile`, `getFormsChecklist`, `listFormSubmissions`, `listFormDrafts`, `listForms`, `listFollowUps`, `listAllFollowUps`, `getFollowUpStats`, `getMyWork`, `listViews`, `saveView`, `getSummary`, `getStageCounts`, `getSpeed`, `listDuplicates`, `ask`, `addNote`, `createFollowUp`, `updateFollowUp`, `createRecord`, `setStageCheck`, `assignReferenceNo`, `setDocumentStatus`, `saveFormDraft`, `draftDocument`, `moveRecordStage`, `submitForm`, `createFormLink`, `createUploadLink`, `guessImportColumns`, `importRecords` |
122
+ | `finn.dialer` | `listSessions`, `listAllSessions`, `getSession`, `getAnalytics`, `listFollowUps`, `getLeadBrief`, `markFollowUpDone`, `setCallDisposition`, `addCallNote` |
123
+ | `finn.webhooks` | `listEndpoints`, `listAllEndpoints`, `createEndpoint`, `getEndpoint`, `updateEndpoint`, `deleteEndpoint`, `listDeliveries`, `listAllDeliveries`, `listEventTypes`, `testEndpoint`, `redeliverDelivery`, `rotateEndpointSecret` |
124
+ | `finn.organization` | `get`, `listMembers`, `listAllMembers`, `listIntegrations`, `listAllIntegrations`, `listApiKeys`, `listAllApiKeys`, `getUsage` |
125
+ | `finn.sales` (experimental) | `listPlays`, `listPlayRuns`, `listProspects`, `runPlay`, `listDrafts`, `updateDraft`, `skipDraft`, `listThreads`, `getThread` |
126
+ <!-- generated:coverage:end -->
127
+
128
+ Generated methods are named after the spec's `operationId` without the area's noun (`getFinnFlow` is
129
+ `finn.finns.getFlow`, `searchCrmRecords` is `finn.crm.searchRecords`). Path parameters come first, in path order,
130
+ then the body, then the query, then `options`. List operations that page by `cursor` also get a `listAll...` helper.
131
+
132
+ **`finn.sales` is experimental.** The Sales API (`/sales`) is switched off for every organization today, so its calls
133
+ answer an error until Finn turns it on for yours. Its methods are generated so the SDK matches the spec, and they may
134
+ change without a major version.
135
+
97
136
  ## Retries
98
137
 
99
138
  Network errors, `408`, `429`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
100
139
  `maxRetries` times, with exponential backoff (0.5 s, 1 s, 2 s ... up to 8 s, with jitter). A `Retry-After` header
101
- is honoured; one longer than `maxRetryAfterMs` throws instead of waiting. A `500` is not retried.
140
+ is honoured; one longer than `maxRetryAfterMs` throws instead of waiting. A `500` is not retried. The waits of one
141
+ request add up to at most `maxRetryWaitMs` (default 20 s): a retry that would go past it is not made, and the last
142
+ error is thrown.
102
143
 
103
144
  `GET`, `PUT` and `DELETE` are always retried. A `POST` or `PATCH` is retried **only when it carries an
104
145
  `Idempotency-Key` and its route dedupes by that key** (`IDEMPOTENT_WRITE_ROUTES`: calls, phone numbers,
105
- deployments, chat start/send, agents, case start, `/crm/*` writes, sales play runs and draft skips). Other writes,
146
+ deployments, chat start/send, agents, case start, `/crm/*` writes, sales play runs and draft skips, webhook endpoint create,
147
+ and the rolling-out dialer follow-up done / call notes and chat agent update / test turn). Other writes,
106
148
  such as `finns.create` or `contacts.create`, are sent once: the API ignores the key there, so a retry after a timeout
107
149
  could create a second record. Check with `honoursIdempotencyKey(method, path)`.
108
150
 
@@ -110,7 +152,7 @@ could create a second record. Check with `honoursIdempotencyKey(method, path)`.
110
152
 
111
153
  These writes get a fresh `Idempotency-Key` automatically, reused across their retries:
112
154
  `calls.create`, `phoneNumbers.rent`, `deployments.createOutbound`, `deployments.createInbound`,
113
- `chat.conversations.start`, `chat.conversations.send`, `agents.create`, `cases.start`.
155
+ `chat.conversations.start`, `chat.conversations.send`, `agents.create`, `cases.start`, `webhooks.createEndpoint`.
114
156
 
115
157
  ```ts
116
158
  import { idempotencyKey } from '@hirefinn/sdk';
@@ -121,7 +163,9 @@ await finn.calls.create(body, { idempotencyKey: false }); // opt out
121
163
  ```
122
164
 
123
165
  The API dedupes by key only on `IDEMPOTENT_WRITE_ROUTES`. Passing a key to another write (for example
124
- `finns.create`) does not make it safe to retry, and the SDK does not retry it.
166
+ `finns.create`) does not make it safe to retry, and the SDK does not retry it. The generated CRM and Sales writes
167
+ (`crm.*`, `sales.runPlay`, `sales.skipDraft`) are on that list but get no automatic key: pass `{ idempotencyKey }` to
168
+ make them safe to retry.
125
169
 
126
170
  ## Webhooks
127
171
 
@@ -129,6 +173,10 @@ Finn signs each delivery with `X-Finn-Signature: t=<unix>,v1=<hex HMAC-SHA256(se
129
173
  `verifyWebhook` checks it in constant time, refuses timestamps more than 300 s from now, and returns the parsed event.
130
174
  Pass the **raw** body, not re-serialised JSON.
131
175
 
176
+ When you rotate an endpoint's secret (`webhooks.rotateEndpointSecret`), Finn signs with both the new and the old
177
+ secret for 24 hours: `t=<unix>,v1=<new>,v1=<old>`. `verifyWebhook` accepts a delivery when **any** `v1` signature
178
+ matches **any** secret you pass, so `secret: [newSecret, oldSecret]` keeps working through the switch.
179
+
132
180
  ```ts
133
181
  import express from 'express';
134
182
  import { verifyWebhook, FinnWebhookVerificationError } from '@hirefinn/sdk';
@@ -151,7 +199,10 @@ Options: `toleranceSeconds` (default 300), and `secret` can be an array while yo
151
199
 
152
200
  Outward and spending writes from OAuth and MCP callers can answer `202 { status: 'pending_approval', approval_id,
153
201
  approve_url, expires_at, action, summary }` instead of doing the work: `calls.create`, `phoneNumbers.rent`,
154
- `deployments.createOutbound`, `cases.start`, `chat.conversations.start` and `chat.conversations.send`. Their return
202
+ `deployments.createOutbound`, `deployments.createInbound`, `cases.start`, `chat.conversations.start`,
203
+ `chat.conversations.send`, `chat.contacts.update`, `chat.updateAgent`, `sales.runPlay`, and the CRM writes
204
+ `crm.moveRecordStage`, `crm.submitForm`, `crm.createFormLink`, `crm.createUploadLink` and `crm.importRecords`.
205
+ Their return
155
206
  types include `PendingApproval`; narrow with `isPendingApproval(res)` and wait with `finn.waitForApproval(id)`.
156
207
 
157
208
  ## Errors
@@ -203,10 +254,9 @@ BACKEND=../hirefinn-web-app-backend npm run spec:pull # from the backend repo'
203
254
 
204
255
  Then `npm run typecheck && npm test`.
205
256
 
206
- `npm run spec:drift` compares the SDK with the live spec (`https://api.hirefinn.ai/v1/openapi.json`) and fails on
207
- new or removed endpoints; CI runs it on every PR and daily. Endpoints the SDK knowingly leaves to `rawRequest` are
208
- listed in `spec/uncovered-ops.json` (`node scripts/check-drift.mjs --write-baseline` rewrites it). New endpoints are reachable at once through `finn.request(...)`; add a
209
- resource method in `src/resources.ts` for the ones worth a name.
257
+ `npm run spec:drift` compares the SDK with the live spec (`https://api.hirefinn.ai/v1/openapi.json`) and fails when
258
+ the spec has an operation the SDK has no method for, or the SDK calls one the spec dropped; CI runs it on every PR
259
+ and daily. `npm run generate -- --check` fails when the committed generated code is older than `spec/openapi.json`.
210
260
 
211
261
  ## Development
212
262
 
@@ -1,5 +1,5 @@
1
1
  import { FinnCore, type FinnOptions } from './core.js';
2
- import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Deployments, DoNotCall, Finns, PhoneNumbers, Voices, Wallet, type WaitForApprovalOptions } from './resources.js';
2
+ import { Agents, Approvals, Audiences, Calls, Cases, Chat, Contacts, Crm, Deployments, Dialer, DoNotCall, Finns, Organization, PhoneNumbers, Sales, Voices, Wallet, Webhooks, type WaitForApprovalOptions } from './resources.js';
3
3
  import type { ApprovalHold, Schemas } from './types.js';
4
4
  /**
5
5
  * The Finn API client.
@@ -24,6 +24,18 @@ export declare class Finn extends FinnCore {
24
24
  readonly approvals: Approvals;
25
25
  readonly agents: Agents;
26
26
  readonly chat: Chat;
27
+ /** CRM: records, stages, forms, documents, follow-ups, views and imports (`/crm`). */
28
+ readonly crm: Crm;
29
+ readonly dialer: Dialer;
30
+ /** Webhook endpoints, deliveries and event types. */
31
+ readonly webhooks: Webhooks;
32
+ /** The organization, its members, integrations and API keys. */
33
+ readonly organization: Organization;
34
+ /**
35
+ * Sales plays, prospects, drafts and threads.
36
+ * @experimental The Sales API is switched off for every organization; calls answer an error until it is on for yours.
37
+ */
38
+ readonly sales: Sales;
27
39
  constructor(options?: FinnOptions);
28
40
  /** Polls an approval until it is decided (see approvals.wait). */
29
41
  waitForApproval(id: string, options?: WaitForApprovalOptions): Promise<ApprovalHold | Schemas['Approval']>;
@@ -26,6 +26,11 @@ class Finn extends core_js_1.FinnCore {
26
26
  this.approvals = new resources_js_1.Approvals(this);
27
27
  this.agents = new resources_js_1.Agents(this);
28
28
  this.chat = new resources_js_1.Chat(this);
29
+ this.crm = new resources_js_1.Crm(this);
30
+ this.dialer = new resources_js_1.Dialer(this);
31
+ this.webhooks = new resources_js_1.Webhooks(this);
32
+ this.organization = new resources_js_1.Organization(this);
33
+ this.sales = new resources_js_1.Sales(this);
29
34
  }
30
35
  /** Polls an approval until it is decided (see approvals.wait). */
31
36
  waitForApproval(id, options) {
@@ -1,6 +1,8 @@
1
1
  import type { FinnResponse, HttpMethod, Operation, PathsFor, RequestArgs, RequestOptions, ResultOf } from './types.js';
2
2
  export declare const DEFAULT_BASE_URL = "https://api.hirefinn.ai/v1";
3
- export declare const SDK_VERSION = "0.2.0";
3
+ export declare const SDK_VERSION = "0.4.0";
4
+ /** The API version this SDK was built against, sent as Finn-Version unless `version` says otherwise. */
5
+ export declare const DEFAULT_FINN_VERSION = "2026-11-01";
4
6
  export interface FinnOptions {
5
7
  /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
6
8
  apiKey?: string;
@@ -8,8 +10,11 @@ export interface FinnOptions {
8
10
  baseUrl?: string;
9
11
  /** Org to act in (Finn-Org header). Needed only for tokens that can use more than one org. */
10
12
  org?: string;
11
- /** Pins the API version (Finn-Version header), a date such as `2026-11-01`. */
12
- version?: string;
13
+ /**
14
+ * Pins the API version (Finn-Version header), a date such as `2026-11-01`. Defaults to DEFAULT_FINN_VERSION, the
15
+ * version this SDK was built against; `null` sends no header (the key's pinned version, else the current one).
16
+ */
17
+ version?: string | null;
13
18
  /**
14
19
  * Retries after the first attempt, on network errors, 408, 429, 502, 503 and 504. Only GET/HEAD/OPTIONS/PUT/DELETE
15
20
  * are retried freely; a POST or PATCH is retried only when it carries an Idempotency-Key and its route dedupes by
@@ -28,6 +33,11 @@ export interface FinnOptions {
28
33
  autoIdempotency?: boolean;
29
34
  /** Longest Retry-After the SDK will wait out; a longer one throws instead. Default 60000 ms. */
30
35
  maxRetryAfterMs?: number;
36
+ /**
37
+ * Most time one request spends waiting between its retries, `Retry-After` waits included. A retry whose wait would
38
+ * go past it is not made: the last error is thrown instead. Default 20000 ms.
39
+ */
40
+ maxRetryWaitMs?: number;
31
41
  /** Headers sent on every request. */
32
42
  defaultHeaders?: Record<string, string>;
33
43
  /** Replaces the wait between retries (for tests). */
@@ -43,6 +53,8 @@ export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
43
53
  export declare const IDEMPOTENT_WRITE_ROUTES: readonly string[];
44
54
  /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
45
55
  export declare function honoursIdempotencyKey(method: string, path: string): boolean;
56
+ /** Default cap on the total wait between retries of one request (`maxRetryWaitMs`). */
57
+ export declare const DEFAULT_MAX_RETRY_WAIT_MS = 20000;
46
58
  /** A new random Idempotency-Key (a UUID v4). */
47
59
  export declare function idempotencyKey(): string;
48
60
  /** Untyped request input, for paths the spec does not have yet. */
@@ -64,6 +76,7 @@ export declare class FinnCore {
64
76
  readonly timeoutMs: number;
65
77
  readonly autoIdempotency: boolean;
66
78
  readonly maxRetryAfterMs: number;
79
+ readonly maxRetryWaitMs: number;
67
80
  constructor(options?: FinnOptions);
68
81
  /**
69
82
  * Calls any operation in the spec, fully typed.
package/dist/cjs/core.js CHANGED
@@ -12,12 +12,16 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
12
12
  };
13
13
  var _FinnCore_apiKey, _FinnCore_fetch, _FinnCore_defaultHeaders, _FinnCore_sleep;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.FinnCore = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
15
+ exports.FinnCore = exports.DEFAULT_MAX_RETRY_WAIT_MS = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.DEFAULT_FINN_VERSION = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
16
16
  exports.honoursIdempotencyKey = honoursIdempotencyKey;
17
17
  exports.idempotencyKey = idempotencyKey;
18
18
  const errors_js_1 = require("./errors.js");
19
19
  exports.DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
20
- exports.SDK_VERSION = '0.2.0';
20
+ exports.SDK_VERSION = '0.4.0';
21
+ /** The API version this SDK was built against, sent as Finn-Version unless `version` says otherwise. */
22
+ exports.DEFAULT_FINN_VERSION = '2026-11-01';
23
+ // Browsers own the User-Agent header, so it is only set on server runtimes.
24
+ const IS_NODE = typeof globalThis.process?.versions?.node === 'string';
21
25
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
22
26
  exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
23
27
  'post /calls',
@@ -28,6 +32,7 @@ exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
28
32
  'post /chat/conversations/{id}/messages',
29
33
  'post /agents',
30
34
  'post /agents/{id}/cases',
35
+ 'post /webhook_endpoints',
31
36
  ]);
32
37
  /**
33
38
  * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
@@ -47,6 +52,11 @@ exports.IDEMPOTENT_WRITE_ROUTES = [
47
52
  'patch /crm/*',
48
53
  'post /sales/plays/{slug}/run',
49
54
  'post /sales/drafts/{id}/skip',
55
+ 'post /webhook_endpoints',
56
+ 'post /dialer/follow-ups/{call_id}/done',
57
+ 'post /dialer/calls/{call_id}/notes',
58
+ 'patch /chat/agents/{agent_id}',
59
+ 'post /chat/agents/{agent_id}/test_turn',
50
60
  ];
51
61
  const IDEMPOTENT_WRITE_MATCHERS = exports.IDEMPOTENT_WRITE_ROUTES.map((route) => {
52
62
  const [method, path] = route.split(' ');
@@ -65,6 +75,8 @@ function honoursIdempotencyKey(method, path) {
65
75
  const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
66
76
  const RETRY_BASE_DELAY_MS = 500;
67
77
  const RETRY_MAX_DELAY_MS = 8000;
78
+ /** Default cap on the total wait between retries of one request (`maxRetryWaitMs`). */
79
+ exports.DEFAULT_MAX_RETRY_WAIT_MS = 20000;
68
80
  /** A new random Idempotency-Key (a UUID v4). */
69
81
  function idempotencyKey() {
70
82
  const c = globalThis.crypto;
@@ -118,11 +130,12 @@ class FinnCore {
118
130
  __classPrivateFieldSet(this, _FinnCore_fetch, f, "f");
119
131
  this.baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
120
132
  this.org = options.org;
121
- this.version = options.version;
133
+ this.version = options.version === undefined ? exports.DEFAULT_FINN_VERSION : options.version ?? undefined;
122
134
  this.maxRetries = options.maxRetries ?? 2;
123
135
  this.timeoutMs = options.timeoutMs ?? 60000;
124
136
  this.autoIdempotency = options.autoIdempotency ?? true;
125
137
  this.maxRetryAfterMs = options.maxRetryAfterMs ?? 60000;
138
+ this.maxRetryWaitMs = options.maxRetryWaitMs ?? exports.DEFAULT_MAX_RETRY_WAIT_MS;
126
139
  __classPrivateFieldSet(this, _FinnCore_defaultHeaders, { ...(options.defaultHeaders ?? {}) }, "f");
127
140
  __classPrivateFieldSet(this, _FinnCore_sleep, options.sleep ?? defaultSleep, "f");
128
141
  }
@@ -153,6 +166,8 @@ class FinnCore {
153
166
  }
154
167
  const headers = new Headers();
155
168
  headers.set('Accept', 'application/json');
169
+ if (IS_NODE)
170
+ headers.set('User-Agent', `finn-node/${exports.SDK_VERSION}`);
156
171
  for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
157
172
  headers.set(k, v);
158
173
  const org = options.org ?? this.org;
@@ -179,6 +194,7 @@ class FinnCore {
179
194
  const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
180
195
  const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
181
196
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
197
+ let waitedMs = 0;
182
198
  for (let attempt = 0;; attempt += 1) {
183
199
  let response;
184
200
  try {
@@ -190,8 +206,10 @@ class FinnCore {
190
206
  const wrapped = err instanceof errors_js_1.FinnTimeoutError
191
207
  ? err
192
208
  : new errors_js_1.FinnConnectionError(`Could not reach the Finn API: ${err?.message ?? err}`, { cause: err });
193
- if (attempt < maxRetries) {
194
- await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, backoffMs(attempt), options.signal);
209
+ const wait = backoffMs(attempt);
210
+ if (attempt < maxRetries && waitedMs + wait <= this.maxRetryWaitMs) {
211
+ waitedMs += wait;
212
+ await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
195
213
  continue;
196
214
  }
197
215
  throw wrapped;
@@ -209,8 +227,9 @@ class FinnCore {
209
227
  const error = errors_js_1.FinnError.fromResponse(response.status, response.headers, parsed, response.statusText);
210
228
  if (attempt < maxRetries && isRetryable(error)) {
211
229
  const wait = error.retryAfter != null ? error.retryAfter * 1000 : backoffMs(attempt);
212
- if (wait > this.maxRetryAfterMs)
230
+ if (wait > this.maxRetryAfterMs || waitedMs + wait > this.maxRetryWaitMs)
213
231
  throw error;
232
+ waitedMs += wait;
214
233
  await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
215
234
  continue;
216
235
  }
@@ -34,7 +34,7 @@ export declare class FinnError extends FinnSdkError {
34
34
  readonly code: FinnErrorCode;
35
35
  /** Matches the `X-Request-Id` response header; quote it to support. */
36
36
  readonly requestId: string | null;
37
- /** Per-field problems (unified shape only; `[]` otherwise). */
37
+ /** Per-field problems (unified shape, and legacy bodies that name fields as a string list; `[]` otherwise). */
38
38
  readonly fields: FinnFieldError[];
39
39
  /** Link to the error's documentation, when the API sent one. */
40
40
  readonly docUrl: string | null;
@@ -90,6 +90,7 @@ class FinnError extends FinnSdkError {
90
90
  requestId: str(request_id) ?? headerRequestId,
91
91
  actionUrl: str(action_url),
92
92
  requiredScope: str(required_scope),
93
+ fields: legacyFields(rest.fields, error, str(message)),
93
94
  details: rest,
94
95
  });
95
96
  }
@@ -160,6 +161,16 @@ function isRecord(v) {
160
161
  function str(v) {
161
162
  return typeof v === 'string' && v !== '' ? v : null;
162
163
  }
164
+ // Legacy bodies list the offending fields by name (`fields: ['dob']`) or as field errors; both become FinnFieldError.
165
+ function legacyFields(v, code, message) {
166
+ if (!Array.isArray(v))
167
+ return [];
168
+ return v.flatMap((f) => {
169
+ if (typeof f === 'string')
170
+ return [{ field: f, code, message: message ?? code }];
171
+ return isFieldError(f) ? [f] : [];
172
+ });
173
+ }
163
174
  function isFieldError(v) {
164
175
  return isRecord(v) && typeof v.field === 'string';
165
176
  }