@glytos/node 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Glytos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # @glytos/node
2
+
3
+ [![CI](https://github.com/Glytos/glytos-sdk-node/actions/workflows/ci.yml/badge.svg)](https://github.com/Glytos/glytos-sdk-node/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@glytos/node)](https://www.npmjs.com/package/@glytos/node)
5
+ [![License](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
+
7
+ The official [Glytos](https://glytos.com) server SDK for Node.js and TypeScript.
8
+
9
+ Call the Glytos API from your backend with an API key: build and run voice agents,
10
+ start phone calls, mint browser web-call tokens, manage phone numbers, and verify
11
+ webhooks. Zero dependencies, fully typed, ESM.
12
+
13
+ > Never ship an API key to the browser. For in-browser voice, use
14
+ > [`@glytos/web`](https://www.npmjs.com/package/@glytos/web) with a short-lived
15
+ > token you mint here.
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install @glytos/node
21
+ ```
22
+
23
+ Requires Node.js 18+ (uses the global `fetch`).
24
+
25
+ ## Quickstart
26
+
27
+ ```ts
28
+ import { Glytos } from '@glytos/node';
29
+
30
+ const glytos = new Glytos(process.env.GLYTOS_API_KEY!);
31
+
32
+ // List your agents
33
+ const agents = await glytos.workflows.list();
34
+
35
+ // Mint a web-call token for the browser
36
+ const { token, ws_url } = await glytos.calls.webToken({
37
+ workflow_uuid: agents[0].uuid,
38
+ });
39
+ ```
40
+
41
+ The base URL defaults to the public API. Override it for a regional stack:
42
+
43
+ ```ts
44
+ const glytos = new Glytos({ apiKey: '...', baseUrl: 'https://api.glytos.com/api/v1' });
45
+ ```
46
+
47
+ ## Resources
48
+
49
+ | Namespace | Methods |
50
+ | --- | --- |
51
+ | `glytos.workflows` | `list`, `retrieve`, `create`, `publish`, `delete`, `templates`, `session`, `sessionEvents` |
52
+ | `glytos.calls` | `create`, `list`, `retrieve`, `webToken`, `control` |
53
+ | `glytos.phoneNumbers` | `search`, `list`, `provision`, `assign`, `release` |
54
+ | `glytos.sessions` | `list` |
55
+ | `glytos.webhooks` | `list`, `create`, `delete`, `events`, `verify` |
56
+
57
+ Any endpoint without a dedicated helper is one call away:
58
+
59
+ ```ts
60
+ const overview = await glytos.request('GET', '/analytics/overview');
61
+ ```
62
+
63
+ ## Errors
64
+
65
+ Non-2xx responses throw a `GlytosError` with the API error `code`, HTTP `status`,
66
+ and the `requestId` for support:
67
+
68
+ ```ts
69
+ import { GlytosError } from '@glytos/node';
70
+
71
+ try {
72
+ await glytos.workflows.retrieve('missing');
73
+ } catch (err) {
74
+ if (err instanceof GlytosError) {
75
+ console.error(err.status, err.code, err.message);
76
+ }
77
+ }
78
+ ```
79
+
80
+ ## Webhooks
81
+
82
+ Verify that a delivery really came from Glytos before trusting it. Pass the **raw**
83
+ request body, the `X-Glytos-Signature` header, and your endpoint secret:
84
+
85
+ ```ts
86
+ app.post('/webhooks/glytos', express.raw({ type: 'application/json' }), (req, res) => {
87
+ const ok = glytos.webhooks.verify(
88
+ req.body, // raw Buffer
89
+ req.header('X-Glytos-Signature') ?? '',
90
+ process.env.GLYTOS_WEBHOOK_SECRET!,
91
+ );
92
+ if (!ok) return res.status(400).end();
93
+ const event = JSON.parse(req.body.toString());
94
+ // handle event...
95
+ res.status(200).end();
96
+ });
97
+ ```
98
+
99
+ ## License
100
+
101
+ MIT
@@ -0,0 +1,196 @@
1
+ /**
2
+ * @glytos/node - the official Glytos server SDK for Node.js and TypeScript.
3
+ *
4
+ * Use it from your backend with an API key. Never ship an API key to the browser;
5
+ * for in-browser voice use `@glytos/web` with a short-lived, workflow-scoped token
6
+ * you mint here via `calls.webToken(...)`.
7
+ *
8
+ * ```ts
9
+ * import { Glytos } from '@glytos/node';
10
+ *
11
+ * const glytos = new Glytos(process.env.GLYTOS_API_KEY!);
12
+ *
13
+ * const agents = await glytos.workflows.list();
14
+ * const { token, ws_url } = await glytos.calls.webToken({ workflow_uuid: agents[0].uuid });
15
+ * ```
16
+ *
17
+ * Every resource method is a thin, typed wrapper over the REST API. For endpoints
18
+ * without a dedicated helper, call `glytos.request(method, path, { body, query })`.
19
+ */
20
+ export interface GlytosOptions {
21
+ /** Your organization API key (starts with `gly_`). */
22
+ apiKey: string;
23
+ /** Override the API base URL (e.g. a regional stack). Defaults to the public API. */
24
+ baseUrl?: string;
25
+ /**
26
+ * The environment to act in: `"dev"`, `"staging"`, `"prod"`, or an environment
27
+ * uuid. Defaults to the organization's default environment (Development). Agents
28
+ * are still created in Development regardless of this; it scopes reads and calls.
29
+ */
30
+ environment?: string;
31
+ /** Custom fetch implementation. Defaults to the global `fetch` (Node 18+). */
32
+ fetch?: typeof fetch;
33
+ }
34
+ /** Thrown on any non-2xx API response. Carries the API error `code` and status. */
35
+ export declare class GlytosError extends Error {
36
+ readonly status: number;
37
+ readonly code: string;
38
+ readonly requestId: string | undefined;
39
+ constructor(status: number, code: string, message: string, requestId?: string);
40
+ }
41
+ type Primitive = string | number | boolean;
42
+ export type Query = Record<string, Primitive | undefined | null>;
43
+ export interface RequestOptions {
44
+ query?: Query;
45
+ body?: unknown;
46
+ }
47
+ export interface Workflow {
48
+ uuid: string;
49
+ name: string;
50
+ mode: string;
51
+ status?: string;
52
+ archived?: boolean;
53
+ [key: string]: unknown;
54
+ }
55
+ export interface Call {
56
+ uuid: string;
57
+ status: string;
58
+ [key: string]: unknown;
59
+ }
60
+ export interface WebCallToken {
61
+ token: string;
62
+ ws_url: string;
63
+ [key: string]: unknown;
64
+ }
65
+ export interface PhoneNumber {
66
+ uuid: string;
67
+ e164: string;
68
+ [key: string]: unknown;
69
+ }
70
+ export interface Session {
71
+ session_uuid: string;
72
+ workflow_uuid?: string;
73
+ mode?: string;
74
+ status: string;
75
+ created_at?: string;
76
+ [key: string]: unknown;
77
+ }
78
+ export interface WebhookEndpoint {
79
+ id: number;
80
+ url: string;
81
+ events: string[];
82
+ [key: string]: unknown;
83
+ }
84
+ declare class Workflows {
85
+ private readonly client;
86
+ constructor(client: Glytos);
87
+ /** List your agents (prompt agents and visual workflows). */
88
+ list(): Promise<Workflow[]>;
89
+ /** Retrieve a single agent by uuid. */
90
+ retrieve(workflowUuid: string): Promise<Workflow>;
91
+ /** Create an agent. `mode` is `"prompt"` (default) or `"workflow"`. */
92
+ create(body: {
93
+ name: string;
94
+ mode?: 'prompt' | 'workflow';
95
+ config?: Record<string, unknown>;
96
+ }): Promise<Workflow>;
97
+ /** Publish the current draft so the agent goes live. */
98
+ publish(workflowUuid: string): Promise<Workflow>;
99
+ /** Delete an agent. */
100
+ delete(workflowUuid: string): Promise<void>;
101
+ /** Ready-made starter workflow graphs. */
102
+ templates(): Promise<Workflow[]>;
103
+ /** Full detail for one session of an agent (transcript, cost, latency, ...). */
104
+ session(workflowUuid: string, sessionUuid: string): Promise<Session>;
105
+ /** The run-event log for a session (routing decisions, tool calls, ...). */
106
+ sessionEvents(workflowUuid: string, sessionUuid: string): Promise<unknown[]>;
107
+ }
108
+ declare class Calls {
109
+ private readonly client;
110
+ constructor(client: Glytos);
111
+ /** Start an outbound phone call, or run a transient agent. */
112
+ create(body: Record<string, unknown>): Promise<Call>;
113
+ /** List calls. */
114
+ list(query?: Query): Promise<Call[]>;
115
+ /** Retrieve a call by uuid. */
116
+ retrieve(callUuid: string): Promise<Call>;
117
+ /**
118
+ * Mint a short-lived, workflow-scoped token for an in-browser web call. Hand the
119
+ * returned `{ token, ws_url }` to the browser and connect with `@glytos/web`.
120
+ */
121
+ webToken(body: {
122
+ workflow_uuid?: string;
123
+ agent?: Record<string, unknown>;
124
+ }): Promise<WebCallToken>;
125
+ /** Control an in-progress call (e.g. transfer, hang up). */
126
+ control(callUuid: string, body: Record<string, unknown>): Promise<unknown>;
127
+ }
128
+ declare class PhoneNumbers {
129
+ private readonly client;
130
+ constructor(client: Glytos);
131
+ /** Search carrier inventory for available numbers. */
132
+ search(query: Query): Promise<unknown[]>;
133
+ /** List the numbers on your account. */
134
+ list(): Promise<PhoneNumber[]>;
135
+ /** Provision (buy) a number by its e164 value. */
136
+ provision(body: {
137
+ e164: string;
138
+ [key: string]: unknown;
139
+ }): Promise<PhoneNumber>;
140
+ /** Assign a number to an agent. */
141
+ assign(numberUuid: string, body: Record<string, unknown>): Promise<PhoneNumber>;
142
+ /** Release (delete) a number. */
143
+ release(numberUuid: string): Promise<void>;
144
+ }
145
+ declare class Sessions {
146
+ private readonly client;
147
+ constructor(client: Glytos);
148
+ /** List sessions across your agents. */
149
+ list(query?: Query): Promise<Session[]>;
150
+ }
151
+ declare class Webhooks {
152
+ private readonly client;
153
+ constructor(client: Glytos);
154
+ /** List your webhook endpoints. */
155
+ list(): Promise<WebhookEndpoint[]>;
156
+ /** Create a webhook endpoint subscribed to the given events. */
157
+ create(body: {
158
+ url: string;
159
+ events: string[];
160
+ [key: string]: unknown;
161
+ }): Promise<WebhookEndpoint>;
162
+ /** Delete a webhook endpoint. */
163
+ delete(endpointId: number | string): Promise<void>;
164
+ /** The catalog of webhook event types you can subscribe to. */
165
+ events(): Promise<unknown[]>;
166
+ /**
167
+ * Verify a webhook delivery signature. Pass the RAW request body (string or
168
+ * Buffer), the `X-Glytos-Signature` header value, and the endpoint secret.
169
+ * Returns true only if the signature is valid and within the tolerance window.
170
+ */
171
+ verify(payload: string | Buffer, signatureHeader: string, secret: string, toleranceSeconds?: number): boolean;
172
+ }
173
+ export declare class Glytos {
174
+ readonly workflows: Workflows;
175
+ readonly calls: Calls;
176
+ readonly phoneNumbers: PhoneNumbers;
177
+ readonly sessions: Sessions;
178
+ readonly webhooks: Webhooks;
179
+ private readonly apiKey;
180
+ private readonly baseUrl;
181
+ private readonly environment?;
182
+ private readonly fetchImpl;
183
+ constructor(options: GlytosOptions | string);
184
+ /**
185
+ * Low-level request against any API endpoint. Path is relative to the API base
186
+ * (e.g. `"/workflows"`). Throws `GlytosError` on a non-2xx response.
187
+ */
188
+ request<T = unknown>(method: string, path: string, options?: RequestOptions): Promise<T>;
189
+ }
190
+ /**
191
+ * Standalone webhook signature verifier (also available as `glytos.webhooks.verify`).
192
+ * Matches the server scheme: HMAC-SHA256 over `"{timestamp}.{body}"`, sent as
193
+ * `X-Glytos-Signature: t=<ts>,v1=<hex>`.
194
+ */
195
+ export declare function verifyWebhook(payload: string | Buffer, signatureHeader: string, secret: string, toleranceSeconds?: number): boolean;
196
+ export default Glytos;
package/dist/index.js ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * @glytos/node - the official Glytos server SDK for Node.js and TypeScript.
3
+ *
4
+ * Use it from your backend with an API key. Never ship an API key to the browser;
5
+ * for in-browser voice use `@glytos/web` with a short-lived, workflow-scoped token
6
+ * you mint here via `calls.webToken(...)`.
7
+ *
8
+ * ```ts
9
+ * import { Glytos } from '@glytos/node';
10
+ *
11
+ * const glytos = new Glytos(process.env.GLYTOS_API_KEY!);
12
+ *
13
+ * const agents = await glytos.workflows.list();
14
+ * const { token, ws_url } = await glytos.calls.webToken({ workflow_uuid: agents[0].uuid });
15
+ * ```
16
+ *
17
+ * Every resource method is a thin, typed wrapper over the REST API. For endpoints
18
+ * without a dedicated helper, call `glytos.request(method, path, { body, query })`.
19
+ */
20
+ import { createHmac, timingSafeEqual } from 'node:crypto';
21
+ const DEFAULT_BASE_URL = 'https://api.glytos.com/api/v1';
22
+ /** Thrown on any non-2xx API response. Carries the API error `code` and status. */
23
+ export class GlytosError extends Error {
24
+ constructor(status, code, message, requestId) {
25
+ super(message);
26
+ this.name = 'GlytosError';
27
+ this.status = status;
28
+ this.code = code;
29
+ this.requestId = requestId;
30
+ }
31
+ }
32
+ const enc = encodeURIComponent;
33
+ class Workflows {
34
+ constructor(client) {
35
+ this.client = client;
36
+ }
37
+ /** List your agents (prompt agents and visual workflows). */
38
+ list() {
39
+ return this.client.request('GET', '/workflows');
40
+ }
41
+ /** Retrieve a single agent by uuid. */
42
+ retrieve(workflowUuid) {
43
+ return this.client.request('GET', `/workflows/${enc(workflowUuid)}`);
44
+ }
45
+ /** Create an agent. `mode` is `"prompt"` (default) or `"workflow"`. */
46
+ create(body) {
47
+ return this.client.request('POST', '/workflows', { body });
48
+ }
49
+ /** Publish the current draft so the agent goes live. */
50
+ publish(workflowUuid) {
51
+ return this.client.request('POST', `/workflows/${enc(workflowUuid)}/publish`);
52
+ }
53
+ /** Delete an agent. */
54
+ delete(workflowUuid) {
55
+ return this.client.request('DELETE', `/workflows/${enc(workflowUuid)}`);
56
+ }
57
+ /** Ready-made starter workflow graphs. */
58
+ templates() {
59
+ return this.client.request('GET', '/workflows/templates');
60
+ }
61
+ /** Full detail for one session of an agent (transcript, cost, latency, ...). */
62
+ session(workflowUuid, sessionUuid) {
63
+ return this.client.request('GET', `/workflows/${enc(workflowUuid)}/sessions/${enc(sessionUuid)}`);
64
+ }
65
+ /** The run-event log for a session (routing decisions, tool calls, ...). */
66
+ sessionEvents(workflowUuid, sessionUuid) {
67
+ return this.client.request('GET', `/workflows/${enc(workflowUuid)}/sessions/${enc(sessionUuid)}/events`);
68
+ }
69
+ }
70
+ class Calls {
71
+ constructor(client) {
72
+ this.client = client;
73
+ }
74
+ /** Start an outbound phone call, or run a transient agent. */
75
+ create(body) {
76
+ return this.client.request('POST', '/calls', { body });
77
+ }
78
+ /** List calls. */
79
+ list(query) {
80
+ return this.client.request('GET', '/calls', { query });
81
+ }
82
+ /** Retrieve a call by uuid. */
83
+ retrieve(callUuid) {
84
+ return this.client.request('GET', `/calls/${enc(callUuid)}`);
85
+ }
86
+ /**
87
+ * Mint a short-lived, workflow-scoped token for an in-browser web call. Hand the
88
+ * returned `{ token, ws_url }` to the browser and connect with `@glytos/web`.
89
+ */
90
+ webToken(body) {
91
+ return this.client.request('POST', '/calls/web-token', { body });
92
+ }
93
+ /** Control an in-progress call (e.g. transfer, hang up). */
94
+ control(callUuid, body) {
95
+ return this.client.request('POST', `/calls/${enc(callUuid)}/control`, { body });
96
+ }
97
+ }
98
+ class PhoneNumbers {
99
+ constructor(client) {
100
+ this.client = client;
101
+ }
102
+ /** Search carrier inventory for available numbers. */
103
+ search(query) {
104
+ return this.client.request('GET', '/telephony/numbers/search', { query });
105
+ }
106
+ /** List the numbers on your account. */
107
+ list() {
108
+ return this.client.request('GET', '/telephony/numbers');
109
+ }
110
+ /** Provision (buy) a number by its e164 value. */
111
+ provision(body) {
112
+ return this.client.request('POST', '/telephony/numbers', { body });
113
+ }
114
+ /** Assign a number to an agent. */
115
+ assign(numberUuid, body) {
116
+ return this.client.request('POST', `/telephony/numbers/${enc(numberUuid)}/assign`, { body });
117
+ }
118
+ /** Release (delete) a number. */
119
+ release(numberUuid) {
120
+ return this.client.request('DELETE', `/telephony/numbers/${enc(numberUuid)}`);
121
+ }
122
+ }
123
+ class Sessions {
124
+ constructor(client) {
125
+ this.client = client;
126
+ }
127
+ /** List sessions across your agents. */
128
+ list(query) {
129
+ return this.client.request('GET', '/sessions', { query });
130
+ }
131
+ }
132
+ class Webhooks {
133
+ constructor(client) {
134
+ this.client = client;
135
+ }
136
+ /** List your webhook endpoints. */
137
+ list() {
138
+ return this.client.request('GET', '/webhooks/endpoints');
139
+ }
140
+ /** Create a webhook endpoint subscribed to the given events. */
141
+ create(body) {
142
+ return this.client.request('POST', '/webhooks/endpoints', { body });
143
+ }
144
+ /** Delete a webhook endpoint. */
145
+ delete(endpointId) {
146
+ return this.client.request('DELETE', `/webhooks/endpoints/${enc(String(endpointId))}`);
147
+ }
148
+ /** The catalog of webhook event types you can subscribe to. */
149
+ events() {
150
+ return this.client.request('GET', '/webhooks/events');
151
+ }
152
+ /**
153
+ * Verify a webhook delivery signature. Pass the RAW request body (string or
154
+ * Buffer), the `X-Glytos-Signature` header value, and the endpoint secret.
155
+ * Returns true only if the signature is valid and within the tolerance window.
156
+ */
157
+ verify(payload, signatureHeader, secret, toleranceSeconds = 300) {
158
+ return verifyWebhook(payload, signatureHeader, secret, toleranceSeconds);
159
+ }
160
+ }
161
+ export class Glytos {
162
+ constructor(options) {
163
+ const opts = typeof options === 'string' ? { apiKey: options } : options;
164
+ if (!opts.apiKey)
165
+ throw new Error('Glytos: an apiKey is required');
166
+ this.apiKey = opts.apiKey;
167
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
168
+ this.environment = opts.environment;
169
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
170
+ if (typeof fetchImpl !== 'function') {
171
+ throw new Error('Glytos: no global fetch found; upgrade to Node 18+ or pass options.fetch');
172
+ }
173
+ this.fetchImpl = fetchImpl;
174
+ this.workflows = new Workflows(this);
175
+ this.calls = new Calls(this);
176
+ this.phoneNumbers = new PhoneNumbers(this);
177
+ this.sessions = new Sessions(this);
178
+ this.webhooks = new Webhooks(this);
179
+ }
180
+ /**
181
+ * Low-level request against any API endpoint. Path is relative to the API base
182
+ * (e.g. `"/workflows"`). Throws `GlytosError` on a non-2xx response.
183
+ */
184
+ async request(method, path, options = {}) {
185
+ const url = new URL(this.baseUrl + path);
186
+ if (options.query) {
187
+ for (const [key, value] of Object.entries(options.query)) {
188
+ if (value !== undefined && value !== null)
189
+ url.searchParams.set(key, String(value));
190
+ }
191
+ }
192
+ const headers = {
193
+ 'X-API-Key': this.apiKey,
194
+ Accept: 'application/json',
195
+ };
196
+ if (this.environment)
197
+ headers['X-Environment-Id'] = this.environment;
198
+ const init = { method, headers };
199
+ if (options.body !== undefined) {
200
+ headers['Content-Type'] = 'application/json';
201
+ init.body = JSON.stringify(options.body);
202
+ }
203
+ const response = await this.fetchImpl(url.toString(), init);
204
+ const requestId = response.headers.get('x-request-id') ?? undefined;
205
+ const text = await response.text();
206
+ const data = text ? safeParse(text) : undefined;
207
+ if (!response.ok) {
208
+ const error = data?.error;
209
+ throw new GlytosError(response.status, error?.code ?? 'error', error?.message ?? (response.statusText || 'Request failed'), requestId);
210
+ }
211
+ return data;
212
+ }
213
+ }
214
+ function safeParse(text) {
215
+ try {
216
+ return JSON.parse(text);
217
+ }
218
+ catch {
219
+ return text;
220
+ }
221
+ }
222
+ /**
223
+ * Standalone webhook signature verifier (also available as `glytos.webhooks.verify`).
224
+ * Matches the server scheme: HMAC-SHA256 over `"{timestamp}.{body}"`, sent as
225
+ * `X-Glytos-Signature: t=<ts>,v1=<hex>`.
226
+ */
227
+ export function verifyWebhook(payload, signatureHeader, secret, toleranceSeconds = 300) {
228
+ const parts = {};
229
+ for (const piece of signatureHeader.split(',')) {
230
+ const idx = piece.indexOf('=');
231
+ if (idx > 0)
232
+ parts[piece.slice(0, idx).trim()] = piece.slice(idx + 1).trim();
233
+ }
234
+ const timestamp = parts['t'];
235
+ const provided = parts['v1'];
236
+ if (!timestamp || !provided)
237
+ return false;
238
+ const body = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload;
239
+ const signed = Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), body]);
240
+ const expected = createHmac('sha256', secret).update(signed).digest('hex');
241
+ const expectedBuf = Buffer.from(expected, 'utf8');
242
+ const providedBuf = Buffer.from(provided, 'utf8');
243
+ if (expectedBuf.length !== providedBuf.length)
244
+ return false;
245
+ if (!timingSafeEqual(expectedBuf, providedBuf))
246
+ return false;
247
+ if (toleranceSeconds > 0) {
248
+ const ts = Number.parseInt(timestamp, 10);
249
+ if (!Number.isFinite(ts))
250
+ return false;
251
+ if (Math.abs(Date.now() / 1000 - ts) > toleranceSeconds)
252
+ return false;
253
+ }
254
+ return true;
255
+ }
256
+ export default Glytos;
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@glytos/node",
3
+ "version": "0.1.0",
4
+ "description": "Official Glytos server SDK for Node.js and TypeScript.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "sideEffects": false,
10
+ "files": ["dist", "src", "README.md"],
11
+ "engines": {
12
+ "node": ">=18"
13
+ },
14
+ "scripts": {
15
+ "build": "tsc -p tsconfig.json",
16
+ "typecheck": "tsc -p tsconfig.json --noEmit",
17
+ "test": "vitest run",
18
+ "prepublishOnly": "npm run build"
19
+ },
20
+ "keywords": ["glytos", "voice", "ai", "agent", "sdk", "api"],
21
+ "author": "Glytos",
22
+ "license": "MIT",
23
+ "homepage": "https://glytos.com",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/Glytos/glytos-sdk-node.git"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/Glytos/glytos-sdk-node/issues"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^20.0.0",
36
+ "typescript": "^5.4.0",
37
+ "vitest": "^2.0.0"
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,396 @@
1
+ /**
2
+ * @glytos/node - the official Glytos server SDK for Node.js and TypeScript.
3
+ *
4
+ * Use it from your backend with an API key. Never ship an API key to the browser;
5
+ * for in-browser voice use `@glytos/web` with a short-lived, workflow-scoped token
6
+ * you mint here via `calls.webToken(...)`.
7
+ *
8
+ * ```ts
9
+ * import { Glytos } from '@glytos/node';
10
+ *
11
+ * const glytos = new Glytos(process.env.GLYTOS_API_KEY!);
12
+ *
13
+ * const agents = await glytos.workflows.list();
14
+ * const { token, ws_url } = await glytos.calls.webToken({ workflow_uuid: agents[0].uuid });
15
+ * ```
16
+ *
17
+ * Every resource method is a thin, typed wrapper over the REST API. For endpoints
18
+ * without a dedicated helper, call `glytos.request(method, path, { body, query })`.
19
+ */
20
+
21
+ import { createHmac, timingSafeEqual } from 'node:crypto';
22
+
23
+ const DEFAULT_BASE_URL = 'https://api.glytos.com/api/v1';
24
+
25
+ export interface GlytosOptions {
26
+ /** Your organization API key (starts with `gly_`). */
27
+ apiKey: string;
28
+ /** Override the API base URL (e.g. a regional stack). Defaults to the public API. */
29
+ baseUrl?: string;
30
+ /**
31
+ * The environment to act in: `"dev"`, `"staging"`, `"prod"`, or an environment
32
+ * uuid. Defaults to the organization's default environment (Development). Agents
33
+ * are still created in Development regardless of this; it scopes reads and calls.
34
+ */
35
+ environment?: string;
36
+ /** Custom fetch implementation. Defaults to the global `fetch` (Node 18+). */
37
+ fetch?: typeof fetch;
38
+ }
39
+
40
+ /** Thrown on any non-2xx API response. Carries the API error `code` and status. */
41
+ export class GlytosError extends Error {
42
+ readonly status: number;
43
+ readonly code: string;
44
+ readonly requestId: string | undefined;
45
+
46
+ constructor(status: number, code: string, message: string, requestId?: string) {
47
+ super(message);
48
+ this.name = 'GlytosError';
49
+ this.status = status;
50
+ this.code = code;
51
+ this.requestId = requestId;
52
+ }
53
+ }
54
+
55
+ type Primitive = string | number | boolean;
56
+ export type Query = Record<string, Primitive | undefined | null>;
57
+
58
+ export interface RequestOptions {
59
+ query?: Query;
60
+ body?: unknown;
61
+ }
62
+
63
+ // Entity shapes carry the fields you rely on plus an index signature, so they stay
64
+ // forward-compatible as the API grows (new fields never break your build).
65
+ export interface Workflow {
66
+ uuid: string;
67
+ name: string;
68
+ mode: string;
69
+ status?: string;
70
+ archived?: boolean;
71
+ [key: string]: unknown;
72
+ }
73
+
74
+ export interface Call {
75
+ uuid: string;
76
+ status: string;
77
+ [key: string]: unknown;
78
+ }
79
+
80
+ export interface WebCallToken {
81
+ token: string;
82
+ ws_url: string;
83
+ [key: string]: unknown;
84
+ }
85
+
86
+ export interface PhoneNumber {
87
+ uuid: string;
88
+ e164: string;
89
+ [key: string]: unknown;
90
+ }
91
+
92
+ export interface Session {
93
+ session_uuid: string;
94
+ workflow_uuid?: string;
95
+ mode?: string;
96
+ status: string;
97
+ created_at?: string;
98
+ [key: string]: unknown;
99
+ }
100
+
101
+ export interface WebhookEndpoint {
102
+ id: number;
103
+ url: string;
104
+ events: string[];
105
+ [key: string]: unknown;
106
+ }
107
+
108
+ const enc = encodeURIComponent;
109
+
110
+ class Workflows {
111
+ constructor(private readonly client: Glytos) {}
112
+
113
+ /** List your agents (prompt agents and visual workflows). */
114
+ list(): Promise<Workflow[]> {
115
+ return this.client.request('GET', '/workflows');
116
+ }
117
+
118
+ /** Retrieve a single agent by uuid. */
119
+ retrieve(workflowUuid: string): Promise<Workflow> {
120
+ return this.client.request('GET', `/workflows/${enc(workflowUuid)}`);
121
+ }
122
+
123
+ /** Create an agent. `mode` is `"prompt"` (default) or `"workflow"`. */
124
+ create(body: {
125
+ name: string;
126
+ mode?: 'prompt' | 'workflow';
127
+ config?: Record<string, unknown>;
128
+ }): Promise<Workflow> {
129
+ return this.client.request('POST', '/workflows', { body });
130
+ }
131
+
132
+ /** Publish the current draft so the agent goes live. */
133
+ publish(workflowUuid: string): Promise<Workflow> {
134
+ return this.client.request('POST', `/workflows/${enc(workflowUuid)}/publish`);
135
+ }
136
+
137
+ /** Delete an agent. */
138
+ delete(workflowUuid: string): Promise<void> {
139
+ return this.client.request('DELETE', `/workflows/${enc(workflowUuid)}`);
140
+ }
141
+
142
+ /** Ready-made starter workflow graphs. */
143
+ templates(): Promise<Workflow[]> {
144
+ return this.client.request('GET', '/workflows/templates');
145
+ }
146
+
147
+ /** Full detail for one session of an agent (transcript, cost, latency, ...). */
148
+ session(workflowUuid: string, sessionUuid: string): Promise<Session> {
149
+ return this.client.request(
150
+ 'GET',
151
+ `/workflows/${enc(workflowUuid)}/sessions/${enc(sessionUuid)}`,
152
+ );
153
+ }
154
+
155
+ /** The run-event log for a session (routing decisions, tool calls, ...). */
156
+ sessionEvents(workflowUuid: string, sessionUuid: string): Promise<unknown[]> {
157
+ return this.client.request(
158
+ 'GET',
159
+ `/workflows/${enc(workflowUuid)}/sessions/${enc(sessionUuid)}/events`,
160
+ );
161
+ }
162
+ }
163
+
164
+ class Calls {
165
+ constructor(private readonly client: Glytos) {}
166
+
167
+ /** Start an outbound phone call, or run a transient agent. */
168
+ create(body: Record<string, unknown>): Promise<Call> {
169
+ return this.client.request('POST', '/calls', { body });
170
+ }
171
+
172
+ /** List calls. */
173
+ list(query?: Query): Promise<Call[]> {
174
+ return this.client.request('GET', '/calls', { query });
175
+ }
176
+
177
+ /** Retrieve a call by uuid. */
178
+ retrieve(callUuid: string): Promise<Call> {
179
+ return this.client.request('GET', `/calls/${enc(callUuid)}`);
180
+ }
181
+
182
+ /**
183
+ * Mint a short-lived, workflow-scoped token for an in-browser web call. Hand the
184
+ * returned `{ token, ws_url }` to the browser and connect with `@glytos/web`.
185
+ */
186
+ webToken(body: {
187
+ workflow_uuid?: string;
188
+ agent?: Record<string, unknown>;
189
+ }): Promise<WebCallToken> {
190
+ return this.client.request('POST', '/calls/web-token', { body });
191
+ }
192
+
193
+ /** Control an in-progress call (e.g. transfer, hang up). */
194
+ control(callUuid: string, body: Record<string, unknown>): Promise<unknown> {
195
+ return this.client.request('POST', `/calls/${enc(callUuid)}/control`, { body });
196
+ }
197
+ }
198
+
199
+ class PhoneNumbers {
200
+ constructor(private readonly client: Glytos) {}
201
+
202
+ /** Search carrier inventory for available numbers. */
203
+ search(query: Query): Promise<unknown[]> {
204
+ return this.client.request('GET', '/telephony/numbers/search', { query });
205
+ }
206
+
207
+ /** List the numbers on your account. */
208
+ list(): Promise<PhoneNumber[]> {
209
+ return this.client.request('GET', '/telephony/numbers');
210
+ }
211
+
212
+ /** Provision (buy) a number by its e164 value. */
213
+ provision(body: { e164: string; [key: string]: unknown }): Promise<PhoneNumber> {
214
+ return this.client.request('POST', '/telephony/numbers', { body });
215
+ }
216
+
217
+ /** Assign a number to an agent. */
218
+ assign(numberUuid: string, body: Record<string, unknown>): Promise<PhoneNumber> {
219
+ return this.client.request('POST', `/telephony/numbers/${enc(numberUuid)}/assign`, { body });
220
+ }
221
+
222
+ /** Release (delete) a number. */
223
+ release(numberUuid: string): Promise<void> {
224
+ return this.client.request('DELETE', `/telephony/numbers/${enc(numberUuid)}`);
225
+ }
226
+ }
227
+
228
+ class Sessions {
229
+ constructor(private readonly client: Glytos) {}
230
+
231
+ /** List sessions across your agents. */
232
+ list(query?: Query): Promise<Session[]> {
233
+ return this.client.request('GET', '/sessions', { query });
234
+ }
235
+ }
236
+
237
+ class Webhooks {
238
+ constructor(private readonly client: Glytos) {}
239
+
240
+ /** List your webhook endpoints. */
241
+ list(): Promise<WebhookEndpoint[]> {
242
+ return this.client.request('GET', '/webhooks/endpoints');
243
+ }
244
+
245
+ /** Create a webhook endpoint subscribed to the given events. */
246
+ create(body: { url: string; events: string[]; [key: string]: unknown }): Promise<WebhookEndpoint> {
247
+ return this.client.request('POST', '/webhooks/endpoints', { body });
248
+ }
249
+
250
+ /** Delete a webhook endpoint. */
251
+ delete(endpointId: number | string): Promise<void> {
252
+ return this.client.request('DELETE', `/webhooks/endpoints/${enc(String(endpointId))}`);
253
+ }
254
+
255
+ /** The catalog of webhook event types you can subscribe to. */
256
+ events(): Promise<unknown[]> {
257
+ return this.client.request('GET', '/webhooks/events');
258
+ }
259
+
260
+ /**
261
+ * Verify a webhook delivery signature. Pass the RAW request body (string or
262
+ * Buffer), the `X-Glytos-Signature` header value, and the endpoint secret.
263
+ * Returns true only if the signature is valid and within the tolerance window.
264
+ */
265
+ verify(
266
+ payload: string | Buffer,
267
+ signatureHeader: string,
268
+ secret: string,
269
+ toleranceSeconds = 300,
270
+ ): boolean {
271
+ return verifyWebhook(payload, signatureHeader, secret, toleranceSeconds);
272
+ }
273
+ }
274
+
275
+ export class Glytos {
276
+ readonly workflows: Workflows;
277
+ readonly calls: Calls;
278
+ readonly phoneNumbers: PhoneNumbers;
279
+ readonly sessions: Sessions;
280
+ readonly webhooks: Webhooks;
281
+
282
+ private readonly apiKey: string;
283
+ private readonly baseUrl: string;
284
+ private readonly environment?: string;
285
+ private readonly fetchImpl: typeof fetch;
286
+
287
+ constructor(options: GlytosOptions | string) {
288
+ const opts: GlytosOptions = typeof options === 'string' ? { apiKey: options } : options;
289
+ if (!opts.apiKey) throw new Error('Glytos: an apiKey is required');
290
+ this.apiKey = opts.apiKey;
291
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
292
+ this.environment = opts.environment;
293
+ const fetchImpl = opts.fetch ?? globalThis.fetch;
294
+ if (typeof fetchImpl !== 'function') {
295
+ throw new Error('Glytos: no global fetch found; upgrade to Node 18+ or pass options.fetch');
296
+ }
297
+ this.fetchImpl = fetchImpl;
298
+
299
+ this.workflows = new Workflows(this);
300
+ this.calls = new Calls(this);
301
+ this.phoneNumbers = new PhoneNumbers(this);
302
+ this.sessions = new Sessions(this);
303
+ this.webhooks = new Webhooks(this);
304
+ }
305
+
306
+ /**
307
+ * Low-level request against any API endpoint. Path is relative to the API base
308
+ * (e.g. `"/workflows"`). Throws `GlytosError` on a non-2xx response.
309
+ */
310
+ async request<T = unknown>(
311
+ method: string,
312
+ path: string,
313
+ options: RequestOptions = {},
314
+ ): Promise<T> {
315
+ const url = new URL(this.baseUrl + path);
316
+ if (options.query) {
317
+ for (const [key, value] of Object.entries(options.query)) {
318
+ if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
319
+ }
320
+ }
321
+
322
+ const headers: Record<string, string> = {
323
+ 'X-API-Key': this.apiKey,
324
+ Accept: 'application/json',
325
+ };
326
+ if (this.environment) headers['X-Environment-Id'] = this.environment;
327
+ const init: RequestInit = { method, headers };
328
+ if (options.body !== undefined) {
329
+ headers['Content-Type'] = 'application/json';
330
+ init.body = JSON.stringify(options.body);
331
+ }
332
+
333
+ const response = await this.fetchImpl(url.toString(), init);
334
+ const requestId = response.headers.get('x-request-id') ?? undefined;
335
+ const text = await response.text();
336
+ const data = text ? safeParse(text) : undefined;
337
+
338
+ if (!response.ok) {
339
+ const error = (data as { error?: { code?: string; message?: string } } | undefined)?.error;
340
+ throw new GlytosError(
341
+ response.status,
342
+ error?.code ?? 'error',
343
+ error?.message ?? (response.statusText || 'Request failed'),
344
+ requestId,
345
+ );
346
+ }
347
+ return data as T;
348
+ }
349
+ }
350
+
351
+ function safeParse(text: string): unknown {
352
+ try {
353
+ return JSON.parse(text);
354
+ } catch {
355
+ return text;
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Standalone webhook signature verifier (also available as `glytos.webhooks.verify`).
361
+ * Matches the server scheme: HMAC-SHA256 over `"{timestamp}.{body}"`, sent as
362
+ * `X-Glytos-Signature: t=<ts>,v1=<hex>`.
363
+ */
364
+ export function verifyWebhook(
365
+ payload: string | Buffer,
366
+ signatureHeader: string,
367
+ secret: string,
368
+ toleranceSeconds = 300,
369
+ ): boolean {
370
+ const parts: Record<string, string> = {};
371
+ for (const piece of signatureHeader.split(',')) {
372
+ const idx = piece.indexOf('=');
373
+ if (idx > 0) parts[piece.slice(0, idx).trim()] = piece.slice(idx + 1).trim();
374
+ }
375
+ const timestamp = parts['t'];
376
+ const provided = parts['v1'];
377
+ if (!timestamp || !provided) return false;
378
+
379
+ const body = typeof payload === 'string' ? Buffer.from(payload, 'utf8') : payload;
380
+ const signed = Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), body]);
381
+ const expected = createHmac('sha256', secret).update(signed).digest('hex');
382
+
383
+ const expectedBuf = Buffer.from(expected, 'utf8');
384
+ const providedBuf = Buffer.from(provided, 'utf8');
385
+ if (expectedBuf.length !== providedBuf.length) return false;
386
+ if (!timingSafeEqual(expectedBuf, providedBuf)) return false;
387
+
388
+ if (toleranceSeconds > 0) {
389
+ const ts = Number.parseInt(timestamp, 10);
390
+ if (!Number.isFinite(ts)) return false;
391
+ if (Math.abs(Date.now() / 1000 - ts) > toleranceSeconds) return false;
392
+ }
393
+ return true;
394
+ }
395
+
396
+ export default Glytos;