@hirefinn/sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.3.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,7 +86,7 @@ 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}` |
@@ -100,16 +110,18 @@ and endpoints newer than the SDK through `finn.rawRequest({ method, path, pathPa
100
110
  ### Coverage
101
111
 
102
112
  <!-- generated:coverage:start (scripts/generate.mjs; do not edit by hand) -->
103
- The SDK covers **154 of 154** operations in the spec (Finn API v1):
104
- 72 through the hand-written methods above and 82 through generated ones, listed here.
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.
105
115
 
106
116
  | Property | Generated methods |
107
117
  |---|---|
108
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` |
109
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` |
110
- | `finn.dialer` | `listSessions`, `listAllSessions`, `getSession`, `getAnalytics`, `listFollowUps`, `getLeadBrief` |
111
- | `finn.webhooks` | `listEndpoints`, `listAllEndpoints`, `createEndpoint`, `getEndpoint`, `updateEndpoint`, `deleteEndpoint`, `listDeliveries`, `listAllDeliveries`, `listEventTypes` |
112
- | `finn.organization` | `get`, `listMembers`, `listAllMembers`, `listIntegrations`, `listAllIntegrations`, `listApiKeys`, `listAllApiKeys` |
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` |
113
125
  | `finn.sales` (experimental) | `listPlays`, `listPlayRuns`, `listProspects`, `runPlay`, `listDrafts`, `updateDraft`, `skipDraft`, `listThreads`, `getThread` |
114
126
  <!-- generated:coverage:end -->
115
127
 
@@ -125,11 +137,14 @@ change without a major version.
125
137
 
126
138
  Network errors, `408`, `429`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
127
139
  `maxRetries` times, with exponential backoff (0.5 s, 1 s, 2 s ... up to 8 s, with jitter). A `Retry-After` header
128
- 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.
129
143
 
130
144
  `GET`, `PUT` and `DELETE` are always retried. A `POST` or `PATCH` is retried **only when it carries an
131
145
  `Idempotency-Key` and its route dedupes by that key** (`IDEMPOTENT_WRITE_ROUTES`: calls, phone numbers,
132
- deployments, chat start/send, agents, case start, `/crm/*` writes, sales play runs and draft skips, webhook endpoint create). 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,
133
148
  such as `finns.create` or `contacts.create`, are sent once: the API ignores the key there, so a retry after a timeout
134
149
  could create a second record. Check with `honoursIdempotencyKey(method, path)`.
135
150
 
@@ -158,6 +173,10 @@ Finn signs each delivery with `X-Finn-Signature: t=<unix>,v1=<hex HMAC-SHA256(se
158
173
  `verifyWebhook` checks it in constant time, refuses timestamps more than 300 s from now, and returns the parsed event.
159
174
  Pass the **raw** body, not re-serialised JSON.
160
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
+
161
180
  ```ts
162
181
  import express from 'express';
163
182
  import { verifyWebhook, FinnWebhookVerificationError } from '@hirefinn/sdk';
@@ -180,9 +199,10 @@ Options: `toleranceSeconds` (default 300), and `secret` can be an array while yo
180
199
 
181
200
  Outward and spending writes from OAuth and MCP callers can answer `202 { status: 'pending_approval', approval_id,
182
201
  approve_url, expires_at, action, summary }` instead of doing the work: `calls.create`, `phoneNumbers.rent`,
183
- `deployments.createOutbound`, `cases.start`, `chat.conversations.start` and `chat.conversations.send`, and the CRM
184
- writes `crm.moveRecordStage`, `crm.submitForm`, `crm.createFormLink`, `crm.createUploadLink` and
185
- `crm.importRecords`. 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
186
206
  types include `PendingApproval`; narrow with `isPendingApproval(res)` and wait with `finn.waitForApproval(id)`.
187
207
 
188
208
  ## Errors
@@ -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.3.0";
3
+ export declare const SDK_VERSION = "0.5.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.3.0';
20
+ exports.SDK_VERSION = '0.5.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',
@@ -49,6 +53,10 @@ exports.IDEMPOTENT_WRITE_ROUTES = [
49
53
  'post /sales/plays/{slug}/run',
50
54
  'post /sales/drafts/{id}/skip',
51
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',
52
60
  ];
53
61
  const IDEMPOTENT_WRITE_MATCHERS = exports.IDEMPOTENT_WRITE_ROUTES.map((route) => {
54
62
  const [method, path] = route.split(' ');
@@ -67,6 +75,8 @@ function honoursIdempotencyKey(method, path) {
67
75
  const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
68
76
  const RETRY_BASE_DELAY_MS = 500;
69
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;
70
80
  /** A new random Idempotency-Key (a UUID v4). */
71
81
  function idempotencyKey() {
72
82
  const c = globalThis.crypto;
@@ -120,11 +130,12 @@ class FinnCore {
120
130
  __classPrivateFieldSet(this, _FinnCore_fetch, f, "f");
121
131
  this.baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
122
132
  this.org = options.org;
123
- this.version = options.version;
133
+ this.version = options.version === undefined ? exports.DEFAULT_FINN_VERSION : options.version ?? undefined;
124
134
  this.maxRetries = options.maxRetries ?? 2;
125
135
  this.timeoutMs = options.timeoutMs ?? 60000;
126
136
  this.autoIdempotency = options.autoIdempotency ?? true;
127
137
  this.maxRetryAfterMs = options.maxRetryAfterMs ?? 60000;
138
+ this.maxRetryWaitMs = options.maxRetryWaitMs ?? exports.DEFAULT_MAX_RETRY_WAIT_MS;
128
139
  __classPrivateFieldSet(this, _FinnCore_defaultHeaders, { ...(options.defaultHeaders ?? {}) }, "f");
129
140
  __classPrivateFieldSet(this, _FinnCore_sleep, options.sleep ?? defaultSleep, "f");
130
141
  }
@@ -155,6 +166,8 @@ class FinnCore {
155
166
  }
156
167
  const headers = new Headers();
157
168
  headers.set('Accept', 'application/json');
169
+ if (IS_NODE)
170
+ headers.set('User-Agent', `finn-node/${exports.SDK_VERSION}`);
158
171
  for (const [k, v] of Object.entries(__classPrivateFieldGet(this, _FinnCore_defaultHeaders, "f")))
159
172
  headers.set(k, v);
160
173
  const org = options.org ?? this.org;
@@ -181,6 +194,7 @@ class FinnCore {
181
194
  const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
182
195
  const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
183
196
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
197
+ let waitedMs = 0;
184
198
  for (let attempt = 0;; attempt += 1) {
185
199
  let response;
186
200
  try {
@@ -192,8 +206,10 @@ class FinnCore {
192
206
  const wrapped = err instanceof errors_js_1.FinnTimeoutError
193
207
  ? err
194
208
  : new errors_js_1.FinnConnectionError(`Could not reach the Finn API: ${err?.message ?? err}`, { cause: err });
195
- if (attempt < maxRetries) {
196
- 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);
197
213
  continue;
198
214
  }
199
215
  throw wrapped;
@@ -211,8 +227,9 @@ class FinnCore {
211
227
  const error = errors_js_1.FinnError.fromResponse(response.status, response.headers, parsed, response.statusText);
212
228
  if (attempt < maxRetries && isRetryable(error)) {
213
229
  const wait = error.retryAfter != null ? error.retryAfter * 1000 : backoffMs(attempt);
214
- if (wait > this.maxRetryAfterMs)
230
+ if (wait > this.maxRetryAfterMs || waitedMs + wait > this.maxRetryWaitMs)
215
231
  throw error;
232
+ waitedMs += wait;
216
233
  await __classPrivateFieldGet(this, _FinnCore_sleep, "f").call(this, wait, options.signal);
217
234
  continue;
218
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
  }