@hirefinn/sdk 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +79 -9
  2. package/dist/cjs/client.d.ts +13 -1
  3. package/dist/cjs/client.js +5 -0
  4. package/dist/cjs/core.d.ts +14 -2
  5. package/dist/cjs/core.js +41 -4
  6. package/dist/cjs/generated/openapi.d.ts +17426 -5875
  7. package/dist/cjs/generated/operations.d.ts +26 -0
  8. package/dist/cjs/generated/operations.js +165 -0
  9. package/dist/cjs/generated/resources.d.ts +887 -0
  10. package/dist/cjs/generated/resources.js +737 -0
  11. package/dist/cjs/index.d.ts +4 -2
  12. package/dist/cjs/index.js +12 -1
  13. package/dist/cjs/resource.d.ts +30 -0
  14. package/dist/cjs/resource.js +23 -0
  15. package/dist/cjs/resources.d.ts +52 -59
  16. package/dist/cjs/resources.js +27 -37
  17. package/dist/cjs/types.d.ts +17 -5
  18. package/dist/cjs/webhooks.d.ts +57 -0
  19. package/dist/cjs/webhooks.js +181 -0
  20. package/dist/esm/client.d.ts +13 -1
  21. package/dist/esm/client.js +6 -1
  22. package/dist/esm/core.d.ts +14 -2
  23. package/dist/esm/core.js +39 -3
  24. package/dist/esm/generated/openapi.d.ts +17426 -5875
  25. package/dist/esm/generated/operations.d.ts +26 -0
  26. package/dist/esm/generated/operations.js +162 -0
  27. package/dist/esm/generated/resources.d.ts +887 -0
  28. package/dist/esm/generated/resources.js +716 -0
  29. package/dist/esm/index.d.ts +4 -2
  30. package/dist/esm/index.js +2 -1
  31. package/dist/esm/resource.d.ts +30 -0
  32. package/dist/esm/resource.js +19 -0
  33. package/dist/esm/resources.d.ts +52 -59
  34. package/dist/esm/resources.js +20 -35
  35. package/dist/esm/types.d.ts +17 -5
  36. package/dist/esm/webhooks.d.ts +57 -0
  37. package/dist/esm/webhooks.js +140 -0
  38. package/package.json +4 -1
package/README.md CHANGED
@@ -7,7 +7,7 @@ retries, idempotency keys, typed errors, pagination and approval helpers. No run
7
7
  - Node 18+ and modern browsers (anything with `fetch`)
8
8
  - ESM and CommonJS, with `.d.ts` types
9
9
 
10
- > Status: pre-release (0.1.0). MIT licensed (see `LICENSE`).
10
+ > Status: pre-release (0.3.0). MIT licensed (see `LICENSE`).
11
11
 
12
12
  ## Install
13
13
 
@@ -81,6 +81,9 @@ Every method also takes a last `options` argument that overrides these per call:
81
81
  | `finn.agents` | `list`, `listAll`, `create`, `draft`, `retrieve`, `saveDraft`, `validate`, `test`, `publish`, `driveTest` |
82
82
  | `finn.chat` | `listChannels`; `conversations.{list, listAll, start, retrieve, listMessages, listAllMessages, send}`; `contacts.{list, listAll, retrieve, update}` |
83
83
 
84
+ The other operations (`finn.crm`, `finn.dialer`, `finn.webhooks`, `finn.organization`, `finn.sales` and more
85
+ `finn.finns` methods) are generated from the spec: see [Coverage](#coverage).
86
+
84
87
  Methods return the response body exactly as the spec describes it (older voice endpoints wrap it in
85
88
  `{ success, data }`). Request and response types come from `src/generated/openapi.ts`; schemas are exported as
86
89
  `Schemas`, e.g. `Schemas['Call']`.
@@ -94,30 +97,94 @@ const full = await finn.requestWithResponse('get', '/wallet'); // { data, status
94
97
 
95
98
  and endpoints newer than the SDK through `finn.rawRequest({ method, path, pathParams, query, body })`.
96
99
 
100
+ ### Coverage
101
+
102
+ <!-- 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.
105
+
106
+ | Property | Generated methods |
107
+ |---|---|
108
+ | `finn.finns` | `generate`, `getFlow`, `enableFlow`, `disableFlow`, `getSettings`, `getVariables`, `updateVariables`, `updateHandbook`, `updateSpeechSettings`, `updateDraft`, `duplicate`, `getShareLink`, `createShareLink`, `getStats`, `getOutcomes` |
109
+ | `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` |
113
+ | `finn.sales` (experimental) | `listPlays`, `listPlayRuns`, `listProspects`, `runPlay`, `listDrafts`, `updateDraft`, `skipDraft`, `listThreads`, `getThread` |
114
+ <!-- generated:coverage:end -->
115
+
116
+ Generated methods are named after the spec's `operationId` without the area's noun (`getFinnFlow` is
117
+ `finn.finns.getFlow`, `searchCrmRecords` is `finn.crm.searchRecords`). Path parameters come first, in path order,
118
+ then the body, then the query, then `options`. List operations that page by `cursor` also get a `listAll...` helper.
119
+
120
+ **`finn.sales` is experimental.** The Sales API (`/sales`) is switched off for every organization today, so its calls
121
+ answer an error until Finn turns it on for yours. Its methods are generated so the SDK matches the spec, and they may
122
+ change without a major version.
123
+
97
124
  ## Retries
98
125
 
99
- Network errors, `408`, `429`, `500`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
126
+ Network errors, `408`, `429`, `502`, `503`, `504` and `409 idempotency_in_progress` are retried up to
100
127
  `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.
128
+ is honoured; one longer than `maxRetryAfterMs` throws instead of waiting. A `500` is not retried.
102
129
 
103
- `GET`, `PUT` and `DELETE` are always retried. `POST` and `PATCH` are retried **only when the request carries an
104
- `Idempotency-Key`**, so a retry can never place a call or spend credits twice.
130
+ `GET`, `PUT` and `DELETE` are always retried. A `POST` or `PATCH` is retried **only when it carries an
131
+ `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,
133
+ such as `finns.create` or `contacts.create`, are sent once: the API ignores the key there, so a retry after a timeout
134
+ could create a second record. Check with `honoursIdempotencyKey(method, path)`.
105
135
 
106
136
  ## Idempotency keys
107
137
 
108
138
  These writes get a fresh `Idempotency-Key` automatically, reused across their retries:
109
139
  `calls.create`, `phoneNumbers.rent`, `deployments.createOutbound`, `deployments.createInbound`,
110
- `chat.conversations.start`, `chat.conversations.send`, `agents.create`, `cases.start`.
140
+ `chat.conversations.start`, `chat.conversations.send`, `agents.create`, `cases.start`, `webhooks.createEndpoint`.
111
141
 
112
142
  ```ts
113
143
  import { idempotencyKey } from '@hirefinn/sdk';
114
144
 
115
145
  const key = idempotencyKey(); // store it with your job
116
146
  await finn.calls.create(body, { idempotencyKey: key }); // same key + same body within 24 h = same answer
117
- await finn.finns.create(body, { idempotencyKey: idempotencyKey() }); // opt in on any other write
118
147
  await finn.calls.create(body, { idempotencyKey: false }); // opt out
119
148
  ```
120
149
 
150
+ The API dedupes by key only on `IDEMPOTENT_WRITE_ROUTES`. Passing a key to another write (for example
151
+ `finns.create`) does not make it safe to retry, and the SDK does not retry it. The generated CRM and Sales writes
152
+ (`crm.*`, `sales.runPlay`, `sales.skipDraft`) are on that list but get no automatic key: pass `{ idempotencyKey }` to
153
+ make them safe to retry.
154
+
155
+ ## Webhooks
156
+
157
+ Finn signs each delivery with `X-Finn-Signature: t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`.
158
+ `verifyWebhook` checks it in constant time, refuses timestamps more than 300 s from now, and returns the parsed event.
159
+ Pass the **raw** body, not re-serialised JSON.
160
+
161
+ ```ts
162
+ import express from 'express';
163
+ import { verifyWebhook, FinnWebhookVerificationError } from '@hirefinn/sdk';
164
+
165
+ app.post('/finn-webhook', express.raw({ type: 'application/json' }), async (req, res) => {
166
+ try {
167
+ const event = await verifyWebhook({ payload: req.body, headers: req.headers, secret: process.env.FINN_WEBHOOK_SECRET! });
168
+ console.log(event.event, event.data);
169
+ res.sendStatus(200);
170
+ } catch (err) {
171
+ if (err instanceof FinnWebhookVerificationError) return res.sendStatus(400);
172
+ throw err;
173
+ }
174
+ });
175
+ ```
176
+
177
+ Options: `toleranceSeconds` (default 300), and `secret` can be an array while you rotate secrets.
178
+
179
+ ## Approval holds
180
+
181
+ Outward and spending writes from OAuth and MCP callers can answer `202 { status: 'pending_approval', approval_id,
182
+ 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
186
+ types include `PendingApproval`; narrow with `isPendingApproval(res)` and wait with `finn.waitForApproval(id)`.
187
+
121
188
  ## Errors
122
189
 
123
190
  Every API error throws a `FinnError`, whichever of the API's error shapes it answered with:
@@ -165,8 +232,11 @@ npm run generate -- https://host/openapi.json # from a URL (also copied into
165
232
  BACKEND=../hirefinn-web-app-backend npm run spec:pull # from the backend repo's prod branch
166
233
  ```
167
234
 
168
- Then `npm run typecheck && npm test`. New endpoints are reachable at once through `finn.request(...)`; add a
169
- resource method in `src/resources.ts` for the ones worth a name.
235
+ Then `npm run typecheck && npm test`.
236
+
237
+ `npm run spec:drift` compares the SDK with the live spec (`https://api.hirefinn.ai/v1/openapi.json`) and fails when
238
+ 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
239
+ and daily. `npm run generate -- --check` fails when the committed generated code is older than `spec/openapi.json`.
170
240
 
171
241
  ## Development
172
242
 
@@ -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,6 @@
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.1.0";
3
+ export declare const SDK_VERSION = "0.3.0";
4
4
  export interface FinnOptions {
5
5
  /** `finn_live_...` org key, `finn_test_...` test key, or an OAuth `finn_oat_...` token. Defaults to env FINN_API_KEY. */
6
6
  apiKey?: string;
@@ -10,7 +10,11 @@ export interface FinnOptions {
10
10
  org?: string;
11
11
  /** Pins the API version (Finn-Version header), a date such as `2026-11-01`. */
12
12
  version?: string;
13
- /** Retries after the first attempt, on network errors, 408, 429 and 5xx. Default 2. */
13
+ /**
14
+ * Retries after the first attempt, on network errors, 408, 429, 502, 503 and 504. Only GET/HEAD/OPTIONS/PUT/DELETE
15
+ * are retried freely; a POST or PATCH is retried only when it carries an Idempotency-Key and its route dedupes by
16
+ * that key (IDEMPOTENT_WRITE_ROUTES). Default 2.
17
+ */
14
18
  maxRetries?: number;
15
19
  /** Timeout per attempt in milliseconds. Default 60000. */
16
20
  timeoutMs?: number;
@@ -31,6 +35,14 @@ export interface FinnOptions {
31
35
  }
32
36
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
33
37
  export declare const AUTO_IDEMPOTENCY_ROUTES: ReadonlySet<string>;
38
+ /**
39
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
40
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
41
+ * after a timeout could create a second resource. `*` matches the rest of the path.
42
+ */
43
+ export declare const IDEMPOTENT_WRITE_ROUTES: readonly string[];
44
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
45
+ export declare function honoursIdempotencyKey(method: string, path: string): boolean;
34
46
  /** A new random Idempotency-Key (a UUID v4). */
35
47
  export declare function idempotencyKey(): string;
36
48
  /** Untyped request input, for paths the spec does not have yet. */
package/dist/cjs/core.js CHANGED
@@ -12,11 +12,12 @@ 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.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
15
+ exports.FinnCore = exports.IDEMPOTENT_WRITE_ROUTES = exports.AUTO_IDEMPOTENCY_ROUTES = exports.SDK_VERSION = exports.DEFAULT_BASE_URL = void 0;
16
+ exports.honoursIdempotencyKey = honoursIdempotencyKey;
16
17
  exports.idempotencyKey = idempotencyKey;
17
18
  const errors_js_1 = require("./errors.js");
18
19
  exports.DEFAULT_BASE_URL = 'https://api.hirefinn.ai/v1';
19
- exports.SDK_VERSION = '0.1.0';
20
+ exports.SDK_VERSION = '0.3.0';
20
21
  /** Writes that get an automatic Idempotency-Key (when autoIdempotency is on). */
21
22
  exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
22
23
  'post /calls',
@@ -27,7 +28,42 @@ exports.AUTO_IDEMPOTENCY_ROUTES = new Set([
27
28
  'post /chat/conversations/{id}/messages',
28
29
  'post /agents',
29
30
  'post /agents/{id}/cases',
31
+ 'post /webhook_endpoints',
30
32
  ]);
33
+ /**
34
+ * POST/PATCH routes where the API dedupes by Idempotency-Key (a retry with the same key and body replays the first
35
+ * answer). Only these writes are retried, and only when they carry a key: other routes ignore the header, so a retry
36
+ * after a timeout could create a second resource. `*` matches the rest of the path.
37
+ */
38
+ exports.IDEMPOTENT_WRITE_ROUTES = [
39
+ 'post /calls',
40
+ 'post /phone_numbers',
41
+ 'post /deployments',
42
+ 'post /deployments/inbound',
43
+ 'post /chat/conversations',
44
+ 'post /chat/conversations/{id}/messages',
45
+ 'post /agents',
46
+ 'post /agents/{id}/cases',
47
+ 'post /crm/*',
48
+ 'patch /crm/*',
49
+ 'post /sales/plays/{slug}/run',
50
+ 'post /sales/drafts/{id}/skip',
51
+ 'post /webhook_endpoints',
52
+ ];
53
+ const IDEMPOTENT_WRITE_MATCHERS = exports.IDEMPOTENT_WRITE_ROUTES.map((route) => {
54
+ const [method, path] = route.split(' ');
55
+ const body = path
56
+ .split('/')
57
+ .map((seg) => (seg === '*' ? '.+' : /^\{[^}]+\}$/.test(seg) ? '[^/]+' : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
58
+ .join('/');
59
+ return { method: method.toUpperCase(), re: new RegExp(`^${body}/?$`) };
60
+ });
61
+ /** True when the API dedupes this write by Idempotency-Key. `path` may be a template or a filled-in path. */
62
+ function honoursIdempotencyKey(method, path) {
63
+ const m = method.toUpperCase();
64
+ const p = path.split('?')[0];
65
+ return IDEMPOTENT_WRITE_MATCHERS.some((x) => x.method === m && x.re.test(p));
66
+ }
31
67
  const SAFE_TO_RETRY_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE']);
32
68
  const RETRY_BASE_DELAY_MS = 500;
33
69
  const RETRY_MAX_DELAY_MS = 8000;
@@ -141,7 +177,8 @@ class FinnCore {
141
177
  for (const [k, v] of Object.entries(options.headers ?? {}))
142
178
  headers.set(k, v);
143
179
  headers.set('Authorization', `Bearer ${__classPrivateFieldGet(this, _FinnCore_apiKey, "f")}`);
144
- const canRetry = SAFE_TO_RETRY_METHODS.has(method) || headers.has('Idempotency-Key');
180
+ // Idempotent methods always; a POST/PATCH only with a key on a route that dedupes by it.
181
+ const canRetry = SAFE_TO_RETRY_METHODS.has(method) || (headers.has('Idempotency-Key') && honoursIdempotencyKey(method, req.path));
145
182
  const maxRetries = canRetry ? Math.max(0, options.maxRetries ?? this.maxRetries) : 0;
146
183
  const timeoutMs = options.timeoutMs ?? this.timeoutMs;
147
184
  for (let attempt = 0;; attempt += 1) {
@@ -240,7 +277,7 @@ function isRetryable(error) {
240
277
  return true;
241
278
  if (error.status === 409)
242
279
  return error.code === 'idempotency_in_progress';
243
- return error.status === 500 || error.status === 502 || error.status === 503 || error.status === 504;
280
+ return error.status === 502 || error.status === 503 || error.status === 504;
244
281
  }
245
282
  function backoffMs(attempt) {
246
283
  const base = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** attempt);