@dialgem/sdk 0.1.0-beta.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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0-beta.0 (unreleased)
4
+
5
+ The first release.
6
+
7
+ - `Dialgem` client authenticated with an organization API key (`X-API-Key`).
8
+ - Resources:
9
+ - `agents`, with its `functions`, `knowledge` and `mcpServers` sub-resources
10
+ - `calls`: `list`, `retrieve`, `createPhoneCall`, `register`
11
+ - `phoneNumbers`, `voices`, `flowTemplates`, `promptTemplates`
12
+ - Webhooks: `Dialgem.webhooks.verify` and `constructEvent` check HMAC-SHA256 signatures and return typed events.
13
+ - Typed errors carrying `errCode`, `requestId` and `issues`.
14
+ - Retries with backoff on GET, PATCH and DELETE, honoring `Retry-After`. POST is never retried by default.
15
+ - `calls.list()` pagination: `await` it for one page, or iterate with `for await` across all pages.
16
+ - Request-body types generated from the agent service's OpenAPI schema.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,257 @@
1
+ # @dialgem/sdk
2
+
3
+ The official TypeScript SDK for the [Dialgem](https://dialgem.com) voice AI API. Use it from your backend to create voice agents, put them on phone numbers, place and register calls, pull transcripts, and verify webhooks.
4
+
5
+ - Written in TypeScript. Request bodies are typed from the API's own schema, including the full conversation-flow node union.
6
+ - Zero runtime dependencies. Ships ESM and CommonJS builds.
7
+ - Node.js 20+. It also runs on Bun, Deno and serverless runtimes that provide `fetch` and Web Crypto.
8
+ - Server-side only. Your API key grants full access to your organization.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @dialgem/sdk
14
+ # or
15
+ pnpm add @dialgem/sdk
16
+ # or
17
+ yarn add @dialgem/sdk
18
+ ```
19
+
20
+ ## Quickstart
21
+
22
+ Create an organization API key (`zk_…`) in the Dialgem dashboard and keep it in your server's environment.
23
+
24
+ ```ts
25
+ import { Dialgem } from "@dialgem/sdk"
26
+
27
+ const dialgem = new Dialgem() // reads DIALGEM_API_KEY
28
+
29
+ const agent = await dialgem.agents.create({
30
+ name: "Front desk",
31
+ system_prompt: "You are the front desk for {{business_name}}.",
32
+ first_message: "Thanks for calling, how can I help?",
33
+ default_dynamic_variables: { business_name: "Acme Dental" },
34
+ })
35
+ ```
36
+
37
+ | Option | Default | |
38
+ |---|---|---|
39
+ | `apiKey` | `process.env.DIALGEM_API_KEY` | Organization API key. |
40
+ | `baseURL` | `process.env.DIALGEM_BASE_URL`, then `https://api.dialgem.com` | Point at a self-hosted or local stack. |
41
+ | `timeout` | `60000` | Milliseconds per attempt. |
42
+ | `maxRetries` | `2` | See [Retries](#retries). |
43
+ | `fetch` | global `fetch` | Custom implementation (proxy agent, instrumentation). |
44
+ | `defaultHeaders` | `{}` | Sent with every request. |
45
+
46
+ Every method also takes an optional last argument, `{ timeout, maxRetries, signal, headers }`, which overrides these options for that one request.
47
+
48
+ Field names are the API's own snake_case, sent exactly as written.
49
+
50
+ ## Recipes
51
+
52
+ Complete, typechecked versions of each recipe ship with the package, in `node_modules/@dialgem/sdk/examples/`.
53
+
54
+ ### 1. Provision an agent on a phone number
55
+
56
+ ```ts
57
+ const agent = await dialgem.agents.create({ name: "Front desk", system_prompt: "…" })
58
+ const number = await dialgem.phoneNumbers.create({ phone_number: "+14155550100" })
59
+
60
+ await dialgem.phoneNumbers.update(number.id, {
61
+ inbound_agent_id: agent.id,
62
+ set_inbound_agent: true, // inbound_agent_id is ignored without this
63
+ })
64
+ ```
65
+
66
+ Agents also have tools, knowledge and MCP servers:
67
+
68
+ ```ts
69
+ await dialgem.agents.functions.create(agent.id, {
70
+ name: "lookup_order",
71
+ url: "https://example.com/api/orders/lookup",
72
+ parameters: { type: "object", properties: { order_id: { type: "string" } } },
73
+ })
74
+ await dialgem.agents.knowledge.create(agent.id, { filename: "faq.txt", content: faqText })
75
+ ```
76
+
77
+ To start from a built-in template, fetch it and pass its fields to `agents.create`:
78
+
79
+ ```ts
80
+ const tpl = await dialgem.promptTemplates.retrieve("dental_front_desk")
81
+ await dialgem.agents.create({
82
+ name: tpl.name,
83
+ system_prompt: tpl.system_prompt,
84
+ first_message: tpl.first_message,
85
+ default_dynamic_variables: { ...tpl.default_dynamic_variables, business_name: "Acme Dental" },
86
+ })
87
+ ```
88
+
89
+ ### 2. Place an outbound call
90
+
91
+ ```ts
92
+ const { call_id } = await dialgem.calls.createPhoneCall({
93
+ from_: "+14155550100", // a number on your organization (`from_` is the wire name)
94
+ to: "+14155550199",
95
+ agent_id: agent.id,
96
+ dialgem_llm_dynamic_variables: { customer_name: "Sam" },
97
+ })
98
+ ```
99
+
100
+ ### 3. Bring your own Twilio number
101
+
102
+ Point your Twilio number's Voice webhook at your backend. Register the call there, then return TwiML that connects Twilio's media stream to Dialgem:
103
+
104
+ ```ts
105
+ app.post("/twilio/voice", express.urlencoded({ extended: false }), async (req, res) => {
106
+ const { stream_url } = await dialgem.calls.register({
107
+ agent_id: AGENT_ID,
108
+ call_sid: req.body.CallSid,
109
+ from_number: req.body.From,
110
+ to_number: req.body.To,
111
+ })
112
+ // stream_url contains `&`: escape it for XML.
113
+ res.type("text/xml").send(`<Response><Connect><Stream url="${escapeXml(stream_url)}"/></Connect></Response>`)
114
+ })
115
+ ```
116
+
117
+ Your Twilio credentials are never shared with Dialgem. `stream_url` is signed and expires after `expires_in` seconds.
118
+
119
+ ### 4. Verify webhooks
120
+
121
+ Set `webhook_url`, `webhook_events` and `webhook_signing_secret` on the agent. Dialgem then POSTs `call_started`, `call_ended` and `call_analyzed` events, each signed with HMAC-SHA256 in the `x-dialgem-signature` header.
122
+
123
+ > **Verify the raw body.** The signature covers the exact bytes Dialgem sent. A body that was parsed and re-serialized, for example by `express.json()`, will never verify, even when the JSON is identical.
124
+
125
+ **Express**
126
+
127
+ ```ts
128
+ import { Dialgem, WebhookVerificationError } from "@dialgem/sdk"
129
+
130
+ app.post("/webhooks/dialgem", express.raw({ type: "application/json" }), async (req, res) => {
131
+ try {
132
+ const event = await Dialgem.webhooks.constructEvent(req.body, req.header("x-dialgem-signature"), SECRET)
133
+ if (event.event === "call_analyzed") await crm.update(event.call_id, event.analysis.variables)
134
+ res.sendStatus(204)
135
+ } catch (err) {
136
+ if (err instanceof WebhookVerificationError) return res.status(400).send(err.message)
137
+ throw err
138
+ }
139
+ })
140
+ ```
141
+
142
+ **Next.js route handler**
143
+
144
+ ```ts
145
+ export async function POST(request: Request) {
146
+ const event = await Dialgem.webhooks.constructEvent(
147
+ await request.text(),
148
+ request.headers.get("x-dialgem-signature"),
149
+ process.env.DIALGEM_WEBHOOK_SECRET!,
150
+ )
151
+ // …
152
+ return new Response(null, { status: 204 })
153
+ }
154
+ ```
155
+
156
+ **Fastify**: register a buffer parser for `application/json` on the webhook route. See `examples/webhook-fastify.ts`.
157
+
158
+ `event` is a discriminated union, so `switch (event.event)` narrows the payload type. A failed delivery is retried once, so make your handler idempotent on `(event, call_id)`. Respond within 10 seconds and queue any slow work. `webhooks.verify(body, signature, secret)` returns a boolean if you prefer to handle rejection yourself.
159
+
160
+ ### 5. Export calls and transcripts
161
+
162
+ `calls.list()` returns one page when you `await` it. Iterate over it with `for await` to walk every page:
163
+
164
+ ```ts
165
+ const cutoff = "2026-09-01T00:00:00"
166
+ for await (const call of dialgem.calls.list({ page_size: 50 })) {
167
+ if (call.started_at < cutoff) break // newest first: the rest are older
168
+ console.log(call.id, call.duration_s, call.analysis?.call_successful, call.transcript)
169
+ }
170
+
171
+ const page = await dialgem.calls.list({ page_size: 50 })
172
+ page.data // Call[]
173
+ page.total // number
174
+ if (page.hasNextPage()) await page.getNextPage()
175
+ ```
176
+
177
+ Pages are offset-based and ordered newest first. A call that starts mid-export shifts later pages by one, so de-duplicate on `id` if exactness matters.
178
+
179
+ ## Errors
180
+
181
+ Every error extends `DialgemError`. When the API returns an HTTP error, the SDK throws an `APIError` subclass chosen by status code:
182
+
183
+ | Status | Class |
184
+ |---|---|
185
+ | 400 | `BadRequestError` |
186
+ | 401 | `AuthenticationError` |
187
+ | 403 | `PermissionDeniedError` |
188
+ | 404 | `NotFoundError` |
189
+ | 409 | `ConflictError` |
190
+ | 422 | `UnprocessableEntityError` |
191
+ | 429 | `RateLimitError` |
192
+ | ≥500 | `InternalServerError` |
193
+ | no response | `APIConnectionError` / `APIConnectionTimeoutError` |
194
+ | your `signal` aborted | `APIUserAbortError` |
195
+
196
+ ```ts
197
+ try {
198
+ await dialgem.agents.update(id, { flow_config })
199
+ } catch (err) {
200
+ if (err instanceof UnprocessableEntityError && err.errCode === "flow_invalid") {
201
+ for (const issue of err.issues) console.log(issue.node_id, issue.message)
202
+ } else if (err instanceof APIError) {
203
+ console.error(err.status, err.errCode, err.message, err.requestId)
204
+ }
205
+ }
206
+ ```
207
+
208
+ Use `errCode` (for example `flow_invalid` or `flow_not_runnable`) to tell errors with the same status apart. Include `requestId` when you contact support.
209
+
210
+ ## Retries
211
+
212
+ The SDK retries GET, PATCH and DELETE requests up to `maxRetries` times on 408, 429, 5xx and connection failures. It backs off exponentially with jitter and honors `Retry-After`.
213
+
214
+ **POST requests are not retried by default.** Most POSTs create something: after an ambiguous failure, a retried `createPhoneCall` would dial the same person twice. To retry a specific POST anyway, opt in on that request: `dialgem.agents.create(body, { maxRetries: 2 })`.
215
+
216
+ The SDK never follows redirects. The API does not issue them, and following one would send your API key to wherever the redirect points. A 3xx response throws an `APIError`.
217
+
218
+ ## Coverage
219
+
220
+ | Resource | Methods |
221
+ |---|---|
222
+ | `agents` | `create`, `retrieve`, `list`, `update`, `delete` |
223
+ | `agents.functions` | `list`, `create`, `update`, `delete`, `reorder` |
224
+ | `agents.knowledge` | `list`, `create`, `delete` |
225
+ | `agents.mcpServers` | `list`, `create`, `update`, `delete`, `test` |
226
+ | `calls` | `list`, `retrieve`, `createPhoneCall`, `register` |
227
+ | `phoneNumbers` | `create`, `list`, `update`, `assign`, `delete` |
228
+ | `voices` | `list` |
229
+ | `flowTemplates`, `promptTemplates` | `list`, `retrieve` |
230
+ | `webhooks` | `verify`, `constructEvent` |
231
+
232
+ In-browser web calls are not part of this package.
233
+
234
+ ## Development
235
+
236
+ Requires Node 22.13+ and pnpm 11.
237
+
238
+ ```sh
239
+ pnpm install
240
+ pnpm typecheck && pnpm test # unit tests with a fake fetch, plus the OpenAPI contract test
241
+ pnpm build && pnpm smoke && pnpm lint:package
242
+
243
+ # After an API change: refresh the filtered OpenAPI snapshot, then regenerate request types.
244
+ pnpm sync:openapi --from https://api.dialgem.com/openapi.json
245
+ pnpm gen:types
246
+
247
+ # Against a running API, with an organization key:
248
+ DIALGEM_API_KEY=zk_… DIALGEM_BASE_URL=http://localhost:8002 pnpm test:live
249
+ ```
250
+
251
+ Request-body types are generated from `openapi/openapi.json`. Response types in `src/types/` are written by hand, so a change to a response shape needs a matching edit there.
252
+
253
+ To release, bump `version` in `package.json` and `src/version.ts`, add a CHANGELOG entry, merge to `main`, and push a matching tag (`git tag v0.1.0 && git push origin v0.1.0`). A version with a hyphen (`0.2.0-beta.1`) publishes to the `next` dist-tag.
254
+
255
+ ## License
256
+
257
+ Apache-2.0