nixflex 0.6.0 → 0.8.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.
@@ -0,0 +1,1376 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/index.ts
4
+ import { parseArgs } from "util";
5
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
6
+ import { homedir } from "os";
7
+ import { join } from "path";
8
+ import { createInterface } from "readline";
9
+
10
+ // src/errors.ts
11
+ var NixflexError = class extends Error {
12
+ /** HTTP status of the failed response (0 for network/timeout failures). */
13
+ status;
14
+ /** Machine-readable error code, e.g. 'invalid_json', 'rate_limit_exceeded'. */
15
+ code;
16
+ /** Error category from the API, e.g. 'invalid_request', 'rate_limit'. */
17
+ type;
18
+ /** Link to the error's documentation page. */
19
+ docUrl;
20
+ /** Structured extra info the API attached to this error. */
21
+ details;
22
+ /** The x-railway-request-id (or similar) header when present - quote it to support. */
23
+ requestId;
24
+ constructor(status, body, requestId, fallbackMessage) {
25
+ const e = body == null ? void 0 : body.error;
26
+ super((e == null ? void 0 : e.message) || fallbackMessage || `Nixflex API error (HTTP ${status})`);
27
+ this.name = "NixflexError";
28
+ this.status = status;
29
+ this.code = (e == null ? void 0 : e.code) || "unknown_error";
30
+ this.type = (e == null ? void 0 : e.type) || "error";
31
+ this.docUrl = e == null ? void 0 : e.doc_url;
32
+ this.details = (e == null ? void 0 : e.details) || {};
33
+ this.requestId = requestId;
34
+ }
35
+ };
36
+ var NixflexAuthenticationError = class extends NixflexError {
37
+ constructor(...args) {
38
+ super(...args);
39
+ this.name = "NixflexAuthenticationError";
40
+ }
41
+ };
42
+ var NixflexPaymentRequiredError = class extends NixflexError {
43
+ constructor(...args) {
44
+ super(...args);
45
+ this.name = "NixflexPaymentRequiredError";
46
+ }
47
+ };
48
+ var NixflexNotFoundError = class extends NixflexError {
49
+ constructor(...args) {
50
+ super(...args);
51
+ this.name = "NixflexNotFoundError";
52
+ }
53
+ };
54
+ var NixflexRateLimitError = class extends NixflexError {
55
+ retryAfterSeconds;
56
+ constructor(status, body, requestId, retryAfterSeconds) {
57
+ super(status, body, requestId);
58
+ this.name = "NixflexRateLimitError";
59
+ this.retryAfterSeconds = retryAfterSeconds;
60
+ }
61
+ };
62
+ var NixflexInvalidRequestError = class extends NixflexError {
63
+ constructor(...args) {
64
+ super(...args);
65
+ this.name = "NixflexInvalidRequestError";
66
+ }
67
+ };
68
+ var NixflexServerError = class extends NixflexError {
69
+ constructor(...args) {
70
+ super(...args);
71
+ this.name = "NixflexServerError";
72
+ }
73
+ };
74
+ var NixflexConnectionError = class extends NixflexError {
75
+ constructor(message) {
76
+ super(0, null, void 0, message);
77
+ this.name = "NixflexConnectionError";
78
+ }
79
+ };
80
+ function errorFromResponse(status, body, requestId, retryAfterSeconds) {
81
+ if (status === 401) return new NixflexAuthenticationError(status, body, requestId);
82
+ if (status === 402) return new NixflexPaymentRequiredError(status, body, requestId);
83
+ if (status === 404) return new NixflexNotFoundError(status, body, requestId);
84
+ if (status === 429) return new NixflexRateLimitError(status, body, requestId, retryAfterSeconds);
85
+ if (status === 400 || status === 422) return new NixflexInvalidRequestError(status, body, requestId);
86
+ if (status >= 500) return new NixflexServerError(status, body, requestId);
87
+ return new NixflexError(status, body, requestId);
88
+ }
89
+
90
+ // src/client.ts
91
+ var DEFAULT_BASE_URL = "https://api.nixflex.com";
92
+ var DEFAULT_TIMEOUT_MS = 3e4;
93
+ var SDK_VERSION = "0.8.0";
94
+ var HttpClient = class {
95
+ apiKey;
96
+ baseUrl;
97
+ timeoutMs;
98
+ maxRetries;
99
+ constructor(opts) {
100
+ if (!opts || typeof opts.apiKey !== "string" || !opts.apiKey.includes(":")) {
101
+ throw new Error(
102
+ 'Nixflex: apiKey is required in the form "key_id:key_secret" (both parts, joined by a colon). Find yours at https://dashboard.nixflex.com under API Keys.'
103
+ );
104
+ }
105
+ this.apiKey = opts.apiKey;
106
+ this.baseUrl = (opts.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
107
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
108
+ this.maxRetries = opts.maxRetries ?? 1;
109
+ }
110
+ async request(method, path, body, query, reqOpts) {
111
+ const url = new URL(this.baseUrl + "/v1" + path);
112
+ if (query) {
113
+ for (const [k, v] of Object.entries(query)) {
114
+ if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
115
+ }
116
+ }
117
+ const isIdempotent = method === "GET" || method === "DELETE";
118
+ let attempt = 0;
119
+ while (true) {
120
+ attempt++;
121
+ let res;
122
+ try {
123
+ res = await this.fetchWithTimeout(url.toString(), method, body, reqOpts);
124
+ } catch (err) {
125
+ if (attempt <= this.maxRetries) {
126
+ await sleep(300 * attempt);
127
+ continue;
128
+ }
129
+ throw new NixflexConnectionError(
130
+ `Could not reach the Nixflex API (${(err == null ? void 0 : err.message) || "network error"}). Check connectivity and https://nixflex.com/status`
131
+ );
132
+ }
133
+ if (res.ok) {
134
+ if (res.status === 204) return void 0;
135
+ return await res.json();
136
+ }
137
+ const requestId = res.headers.get("x-railway-request-id") || void 0;
138
+ const retryAfter = parseInt(res.headers.get("retry-after") || "0", 10) || 0;
139
+ let errBody = null;
140
+ try {
141
+ errBody = await res.json();
142
+ } catch {
143
+ }
144
+ const retryable429 = res.status === 429;
145
+ const retryable5xx = res.status >= 500 && isIdempotent;
146
+ if ((retryable429 || retryable5xx) && attempt <= this.maxRetries) {
147
+ const waitMs = retryable429 ? Math.min(retryAfter, 30) * 1e3 || 1e3 : 500 * attempt;
148
+ await sleep(waitMs);
149
+ continue;
150
+ }
151
+ throw errorFromResponse(res.status, errBody, requestId, retryAfter);
152
+ }
153
+ }
154
+ async fetchWithTimeout(url, method, body, reqOpts) {
155
+ const controller = new AbortController();
156
+ const timeoutMs = (reqOpts == null ? void 0 : reqOpts.timeoutMs) ?? this.timeoutMs;
157
+ const timer = setTimeout(() => controller.abort(new Error(`timeout after ${timeoutMs}ms`)), timeoutMs);
158
+ if (reqOpts == null ? void 0 : reqOpts.signal) {
159
+ if (reqOpts.signal.aborted) controller.abort(reqOpts.signal.reason);
160
+ else reqOpts.signal.addEventListener("abort", () => controller.abort(reqOpts.signal.reason), { once: true });
161
+ }
162
+ try {
163
+ return await fetch(url, {
164
+ method,
165
+ headers: {
166
+ Authorization: `Bearer ${this.apiKey}`,
167
+ "Content-Type": "application/json",
168
+ "User-Agent": `nixflex-node/${SDK_VERSION}`
169
+ },
170
+ body: body === void 0 ? void 0 : JSON.stringify(body),
171
+ signal: controller.signal
172
+ });
173
+ } finally {
174
+ clearTimeout(timer);
175
+ }
176
+ }
177
+ };
178
+ function sleep(ms) {
179
+ return new Promise((r) => setTimeout(r, ms));
180
+ }
181
+
182
+ // src/resources/agents.ts
183
+ var Agents = class {
184
+ constructor(http) {
185
+ this.http = http;
186
+ }
187
+ http;
188
+ /** Create an agent. Every field has a sensible default - `{ name }` alone works.
189
+ * The agent is immediately usable for numbers and outbound calls. */
190
+ create(params = {}, opts) {
191
+ return this.http.request("POST", "/agents", params, void 0, opts);
192
+ }
193
+ /** List active agents, newest first. Default 100, hard cap 200 per page. */
194
+ list(params = {}, opts) {
195
+ return this.http.request("GET", "/agents", void 0, { limit: params.limit, offset: params.offset }, opts);
196
+ }
197
+ /** Iterate ALL agents across pages: `for await (const a of client.agents.iter()) { ... }` */
198
+ async *iter(pageSize = 100, opts) {
199
+ let offset = 0;
200
+ while (true) {
201
+ const page = await this.list({ limit: pageSize, offset }, opts);
202
+ for (const item of page) yield item;
203
+ if (page.length < pageSize) return;
204
+ offset += page.length;
205
+ }
206
+ }
207
+ /** Fetch one agent with full configuration. Throws NixflexNotFoundError if the ID is not yours. */
208
+ get(agentId, opts) {
209
+ return this.http.request("GET", `/agents/${encodeURIComponent(agentId)}`, void 0, void 0, opts);
210
+ }
211
+ /** Update an agent. Send ONLY the fields you want to change - omitted fields
212
+ * keep their values. Active calls are unaffected; new calls use the new config.
213
+ * Unknown field names return 200 and change nothing - check spelling. */
214
+ update(agentId, params, opts) {
215
+ return this.http.request("PUT", `/agents/${encodeURIComponent(agentId)}`, params, void 0, opts);
216
+ }
217
+ /** PERMANENTLY delete an agent. Attached numbers detach and stop routing;
218
+ * historical calls stay accessible. To disable without losing setup, use
219
+ * update(agentId, { is_active: false }) instead. */
220
+ delete(agentId, opts) {
221
+ return this.http.request("DELETE", `/agents/${encodeURIComponent(agentId)}`, void 0, void 0, opts);
222
+ }
223
+ };
224
+
225
+ // src/resources/calls.ts
226
+ var Calls = class {
227
+ constructor(http) {
228
+ this.http = http;
229
+ }
230
+ http;
231
+ /** Trigger an outbound AI call. FIRE-AND-FORGET: returns immediately with a
232
+ * call_id; ringing, conversation and ending happen asynchronously. Set a
233
+ * webhook_url on the agent or number to receive call.completed when it ends.
234
+ * The dialling number must be OUTBOUND-ENABLED (inbound working does not
235
+ * mean outbound works - separate switches). */
236
+ create(params, opts) {
237
+ return this.http.request("POST", "/calls/outbound", params, void 0, opts);
238
+ }
239
+ /** List calls, newest first. Default 50, hard cap 200. The response is a
240
+ * bare array with no total - page until you get fewer rows than you asked
241
+ * for (or use iter()). Call data is retained 90 days. */
242
+ list(params = {}, opts) {
243
+ return this.http.request("GET", "/calls", void 0, { limit: params.limit, offset: params.offset }, opts);
244
+ }
245
+ /** Iterate ALL calls across pages: `for await (const c of client.calls.iter()) { ... }` */
246
+ async *iter(pageSize = 100, opts) {
247
+ let offset = 0;
248
+ while (true) {
249
+ const page = await this.list({ limit: pageSize, offset }, opts);
250
+ for (const item of page) yield item;
251
+ if (page.length < pageSize) return;
252
+ offset += page.length;
253
+ }
254
+ }
255
+ /** Fetch one call: transcript, recording URL, post-call analysis. Note:
256
+ * duration_ms is time CONNECTED (what you are billed on) - ring time is
257
+ * excluded, so it will not equal end_timestamp - start_timestamp on
258
+ * outbound calls. */
259
+ get(callId, opts) {
260
+ return this.http.request("GET", `/calls/${encodeURIComponent(callId)}`, void 0, void 0, opts);
261
+ }
262
+ /** GDPR: PERMANENTLY erase one call - the record AND its recording file.
263
+ * Irreversible. Throws NixflexNotFoundError if the ID is not yours. */
264
+ delete(callId, opts) {
265
+ return this.http.request("DELETE", `/calls/${encodeURIComponent(callId)}`, void 0, void 0, opts);
266
+ }
267
+ /** GDPR: PERMANENTLY erase ALL calls, recordings, and SMS messages on this
268
+ * key. Irreversible - intended for data-erasure requests and offboarding. */
269
+ deleteAll(opts) {
270
+ return this.http.request("DELETE", "/calls", void 0, void 0, opts);
271
+ }
272
+ };
273
+ var Campaigns = class {
274
+ constructor(http) {
275
+ this.http = http;
276
+ }
277
+ http;
278
+ /** Create a batch campaign - many outbound calls under one campaign_id.
279
+ * schedule_type 'now' launches immediately; 'schedule' waits for
280
+ * scheduled_date and fires INSIDE the calling window in the campaign's
281
+ * timezone (yours > the agent's > Europe/London). Overnight windows
282
+ * supported. One campaign = one timezone - split multi-country lists. */
283
+ create(params, opts) {
284
+ return this.http.request("POST", "/calls/batch", params, void 0, opts);
285
+ }
286
+ /** Launch a scheduled campaign immediately, overriding its schedule.
287
+ * Already running = no-op returning current status. */
288
+ launch(campaignId, opts) {
289
+ return this.http.request("POST", `/calls/batch/${encodeURIComponent(campaignId)}/launch`, void 0, void 0, opts);
290
+ }
291
+ };
292
+
293
+ // src/webhook-verify.ts
294
+ import { createHmac, timingSafeEqual } from "crypto";
295
+ function verifyWebhookSignature(rawBody, signatureHeader, keySecret, options = {}) {
296
+ try {
297
+ if (!signatureHeader || !keySecret) return false;
298
+ const parts = {};
299
+ for (const seg of signatureHeader.split(",")) {
300
+ const i = seg.indexOf("=");
301
+ if (i > 0) parts[seg.slice(0, i).trim()] = seg.slice(i + 1).trim();
302
+ }
303
+ const t = parseInt(parts["t"] || "", 10);
304
+ const v1 = parts["v1"] || "";
305
+ if (!isFinite(t) || !/^[0-9a-f]{64}$/.test(v1)) return false;
306
+ const tolerance = options.toleranceSeconds ?? 300;
307
+ const now = options.now ?? Math.floor(Date.now() / 1e3);
308
+ if (Math.abs(now - t) > tolerance) return false;
309
+ const body = typeof rawBody === "string" ? rawBody : rawBody.toString("utf8");
310
+ const expected = createHmac("sha256", keySecret).update(t + "." + body).digest("hex");
311
+ const a = Buffer.from(expected, "hex");
312
+ const b = Buffer.from(v1, "hex");
313
+ if (a.length !== b.length) return false;
314
+ return timingSafeEqual(a, b);
315
+ } catch {
316
+ return false;
317
+ }
318
+ }
319
+
320
+ // src/resources/stage3.ts
321
+ function enc(phoneNumber) {
322
+ return encodeURIComponent(phoneNumber);
323
+ }
324
+ var PhoneNumbers = class {
325
+ constructor(http) {
326
+ this.http = http;
327
+ }
328
+ http;
329
+ /** Attach a number you already own. Carrier inferred from credentials
330
+ * (twilio_sid+twilio_token OR telnyx_api_key+telnyx_connection_id).
331
+ * WARNING: Twilio import REPLACES the number's existing webhooks - another
332
+ * system using this number stops receiving calls and SMS. */
333
+ import(params, opts) {
334
+ return this.http.request("POST", "/phone-numbers", params, void 0, opts);
335
+ }
336
+ /** All numbers on your account (optionally one agent's), newest first.
337
+ * Not paginated - returns up to 1,000; filter by agent_id above that. */
338
+ list(params = {}, opts) {
339
+ return this.http.request("GET", "/phone-numbers", void 0, { agent_id: params.agent_id }, opts);
340
+ }
341
+ /** Update per-number settings. Send ONLY what changes (empty body is
342
+ * rejected). null clears/inherits - see each field's JSDoc; speaking_rate
343
+ * null INHERITS the agent's speed (send 1, not null, to force normal). */
344
+ update(phoneNumber, params, opts) {
345
+ return this.http.request("PATCH", `/phone-numbers/${enc(phoneNumber)}`, params, void 0, opts);
346
+ }
347
+ /** Disconnect from Nixflex (clears carrier webhooks + our record). Does NOT
348
+ * release the number from your carrier - carrier billing continues until
349
+ * you release it in Twilio/Telnyx yourself. Reversible by re-importing. */
350
+ delete(phoneNumber, opts) {
351
+ return this.http.request("DELETE", `/phone-numbers/${enc(phoneNumber)}`, void 0, void 0, opts);
352
+ }
353
+ /** Turn live call monitoring on/off for a number (off by default).
354
+ * NOTE: enabling bills that number's inbound calls at $0.09/min. */
355
+ setMonitor(phoneNumber, enabled, opts) {
356
+ return this.http.request("PUT", `/integrations/monitor/number/${enc(phoneNumber)}`, { enabled }, void 0, opts);
357
+ }
358
+ /** Current monitoring state for a number. */
359
+ getMonitor(phoneNumber, opts) {
360
+ return this.http.request("GET", `/integrations/monitor/number/${enc(phoneNumber)}`, void 0, void 0, opts);
361
+ }
362
+ /** Enable/disable browser (web) calls for a number (off by default).
363
+ * NOTE: enabling bills that number's calls at $0.09/min (same rule as
364
+ * Live Monitor - either on means 0.09, both on is still 0.09). */
365
+ setWebCalls(phoneNumber, enabled, opts) {
366
+ return this.http.request("PUT", `/integrations/web-calls/number/${enc(phoneNumber)}`, { enabled }, void 0, opts);
367
+ }
368
+ /** Current web-calls state for a number. */
369
+ getWebCalls(phoneNumber, opts) {
370
+ return this.http.request("GET", `/integrations/web-calls/number/${enc(phoneNumber)}`, void 0, void 0, opts);
371
+ }
372
+ };
373
+ var SmsCampaigns = class {
374
+ constructor(http) {
375
+ this.http = http;
376
+ }
377
+ http;
378
+ /** Create a one-time SMS broadcast ({{variable}} templating per recipient,
379
+ * up to 10,000 recipients). from_number may be on either carrier (Twilio or
380
+ * Telnyx) and must be a number on your own account. */
381
+ create(params, opts) {
382
+ return this.http.request("POST", "/sms/campaigns", params, void 0, opts);
383
+ }
384
+ /** Launch a draft/scheduled campaign immediately. */
385
+ launch(campaignId, opts) {
386
+ return this.http.request("POST", `/sms/campaigns/${encodeURIComponent(campaignId)}/launch`, void 0, void 0, opts);
387
+ }
388
+ /** All campaigns, newest first, with live-computed delivery counts. */
389
+ list(params = {}, opts) {
390
+ return this.http.request("GET", "/sms/campaigns", void 0, { status: params.status, limit: params.limit }, opts);
391
+ }
392
+ /** One campaign with per-recipient statuses. Twilio 'sent' (handed to
393
+ * carrier, never confirmed on the handset) counts as FAILED, not delivered. */
394
+ get(campaignId, opts) {
395
+ return this.http.request("GET", `/sms/campaigns/${encodeURIComponent(campaignId)}`, void 0, void 0, opts);
396
+ }
397
+ /** Cancel a scheduled/running campaign. Already-sent messages cannot be
398
+ * recalled; cancelled_count = pending recipients that will not be messaged. */
399
+ delete(campaignId, opts) {
400
+ return this.http.request("DELETE", `/sms/campaigns/${encodeURIComponent(campaignId)}`, void 0, void 0, opts);
401
+ }
402
+ };
403
+ var Sms = class {
404
+ constructor(http) {
405
+ this.http = http;
406
+ this.campaigns = new SmsCampaigns(http);
407
+ }
408
+ http;
409
+ /** SMS campaigns - one-time bulk broadcasts. */
410
+ campaigns;
411
+ /** Send a single SMS from one of your numbers (both carriers). NOTE: this
412
+ * endpoint uses `to` - NOT to_number (that is the outbound-call field).
413
+ * Replies are answered automatically by the agent's prompt. */
414
+ send(params, opts) {
415
+ return this.http.request("POST", "/sms", params, void 0, opts);
416
+ }
417
+ };
418
+ var Keys = class {
419
+ constructor(http) {
420
+ this.http = http;
421
+ }
422
+ http;
423
+ /** Rotate the key SECRET (key_id stays stable - the Stripe model). The old
424
+ * secret stops working THE INSTANT this returns; the new one is shown ONCE.
425
+ * Update every deployed app before rotating in production. */
426
+ rotate(opts) {
427
+ return this.http.request("POST", "/keys/rotate", void 0, void 0, opts);
428
+ }
429
+ };
430
+ var UsageResource = class {
431
+ constructor(http) {
432
+ this.http = http;
433
+ }
434
+ http;
435
+ /** Usage + balance: calls, minutes, SMS, credit. minutes is fractional;
436
+ * cost_usd excludes carrier charges (Twilio/Telnyx bill you directly). */
437
+ get(opts) {
438
+ return this.http.request("GET", "/usage", void 0, void 0, opts);
439
+ }
440
+ };
441
+ var Storage = class {
442
+ constructor(http) {
443
+ this.http = http;
444
+ }
445
+ http;
446
+ /** Connect your own S3-compatible bucket for call recordings (data residency).
447
+ * The connection is verified with a probe write BEFORE saving - broken
448
+ * credentials are rejected, never stored. Recordings then upload to your
449
+ * bucket and Nixflex keeps no copy; recording_url becomes a byo: path. */
450
+ set(params, opts) {
451
+ return this.http.request("PUT", "/account/storage", params, void 0, opts);
452
+ }
453
+ /** Current storage configuration. The secret is never included. */
454
+ get(opts) {
455
+ return this.http.request("GET", "/account/storage", void 0, void 0, opts);
456
+ }
457
+ /** Disconnect and clear. Recordings return to Nixflex EU storage from the
458
+ * next call; files already in your bucket are untouched - they are yours. */
459
+ delete(opts) {
460
+ return this.http.request("DELETE", "/account/storage", void 0, void 0, opts);
461
+ }
462
+ };
463
+ var Llm = class {
464
+ constructor(http) {
465
+ this.http = http;
466
+ }
467
+ http;
468
+ /** Connect an OpenAI-compatible model. Verified BEFORE saving with a real
469
+ * completion + a tool-calling round trip (models without tool calling are
470
+ * refused). Calls your model serves bill at a $0.015/min discount; if it
471
+ * fails on a call the standard stack takes over and that call bills standard. */
472
+ set(params, opts) {
473
+ return this.http.request("PUT", "/account/llm", params, void 0, opts);
474
+ }
475
+ /** Current LLM configuration. The provider key is never included. */
476
+ get(opts) {
477
+ return this.http.request("GET", "/account/llm", void 0, void 0, opts);
478
+ }
479
+ /** Disconnect. Calls return to the standard stack and rate from the next call. */
480
+ delete(opts) {
481
+ return this.http.request("DELETE", "/account/llm", void 0, void 0, opts);
482
+ }
483
+ };
484
+ var Tts = class {
485
+ constructor(http) {
486
+ this.http = http;
487
+ }
488
+ http;
489
+ /** Connect your voice provider (elevenlabs or cartesia). Verified BEFORE
490
+ * saving with one real synthesis using the exact voice ID. Phone calls only -
491
+ * web calls keep the standard voice. Calls your voice serves bill at a
492
+ * $0.02/min discount; on failure the standard voice takes over and that call
493
+ * bills the standard TTS rate. */
494
+ set(params, opts) {
495
+ return this.http.request("PUT", "/account/tts", params, void 0, opts);
496
+ }
497
+ /** Current TTS configuration. The provider key is never included. */
498
+ get(opts) {
499
+ return this.http.request("GET", "/account/tts", void 0, void 0, opts);
500
+ }
501
+ /** Disconnect. Calls return to the standard voice and rate from the next call. */
502
+ delete(opts) {
503
+ return this.http.request("DELETE", "/account/tts", void 0, void 0, opts);
504
+ }
505
+ };
506
+ var Webhooks = class {
507
+ constructor(http) {
508
+ this.http = http;
509
+ }
510
+ http;
511
+ /** Verify a webhook delivery's X-Nixflex-Signature header. Pass the RAW
512
+ * request body (string or Buffer) and your key_secret. Returns true only
513
+ * for an authentic, fresh signature. See webhook-verify.ts. */
514
+ verify(rawBody, signatureHeader, keySecret, options) {
515
+ return verifyWebhookSignature(rawBody, signatureHeader, keySecret, options);
516
+ }
517
+ /** Point a number's post-call events at your HTTPS endpoint.
518
+ * slot 2 = the second destination (webhook2). */
519
+ set(phoneNumber, url, slot = 1, opts) {
520
+ const base = slot === 2 ? "webhook2" : "webhook";
521
+ return this.http.request("PUT", `/integrations/${base}/number/${encodeURIComponent(phoneNumber)}`, { url }, void 0, opts);
522
+ }
523
+ /** Read the webhook configured on a number. */
524
+ get(phoneNumber, slot = 1, opts) {
525
+ const base = slot === 2 ? "webhook2" : "webhook";
526
+ return this.http.request("GET", `/integrations/${base}/number/${encodeURIComponent(phoneNumber)}`, void 0, void 0, opts);
527
+ }
528
+ /** Remove the webhook from a number. */
529
+ delete(phoneNumber, slot = 1, opts) {
530
+ const base = slot === 2 ? "webhook2" : "webhook";
531
+ return this.http.request("DELETE", `/integrations/${base}/number/${encodeURIComponent(phoneNumber)}`, void 0, void 0, opts);
532
+ }
533
+ };
534
+
535
+ // src/resources/callers.ts
536
+ function enc2(phoneNumber) {
537
+ return encodeURIComponent(phoneNumber);
538
+ }
539
+ var Callers = class {
540
+ constructor(http) {
541
+ this.http = http;
542
+ }
543
+ http;
544
+ /** What the agent knows about this caller on this number - your fields plus
545
+ * what the engine learned. 404 caller_not_found when there is no record. */
546
+ get(phoneNumber, callerNumber, opts) {
547
+ return this.http.request("GET", `/phone-numbers/${enc2(phoneNumber)}/callers/${enc2(callerNumber)}`, void 0, void 0, opts);
548
+ }
549
+ /** Set the caller's details. A field left out keeps its value; null removes it.
550
+ * last_call / open_item are engine-only and are rejected (engine_only_field). */
551
+ set(phoneNumber, callerNumber, params, opts) {
552
+ return this.http.request("PUT", `/phone-numbers/${enc2(phoneNumber)}/callers/${enc2(callerNumber)}`, params, void 0, opts);
553
+ }
554
+ /** Erase the whole record for this caller on this number - yours and the engine's. */
555
+ delete(phoneNumber, callerNumber, opts) {
556
+ return this.http.request("DELETE", `/phone-numbers/${enc2(phoneNumber)}/callers/${enc2(callerNumber)}`, void 0, void 0, opts);
557
+ }
558
+ /** Up to 1,000 rows in one request. Every row is validated before any is
559
+ * written. Split larger lists into several calls. */
560
+ import(phoneNumber, callers, opts) {
561
+ return this.http.request("POST", `/phone-numbers/${enc2(phoneNumber)}/callers/import`, { callers }, void 0, opts);
562
+ }
563
+ };
564
+
565
+ // src/index.ts
566
+ var Nixflex = class {
567
+ /** AI agents - create, list, get, update, delete. */
568
+ agents;
569
+ /** Calls - trigger outbound, list history, fetch transcripts + analysis. */
570
+ calls;
571
+ /** Voice batch campaigns - many calls under one campaign, scheduling windows. */
572
+ campaigns;
573
+ /** Phone numbers - import (Twilio/Telnyx), settings, monitor + web-calls toggles. */
574
+ phoneNumbers;
575
+ /** SMS - single sends + bulk campaigns. */
576
+ sms;
577
+ /** API key management - rotate the secret. */
578
+ keys;
579
+ /** Usage + balance. */
580
+ usage;
581
+ /** Per-number post-call webhook configuration. */
582
+ webhooks;
583
+ /** Your own S3-compatible recording storage (data residency). */
584
+ storage;
585
+ /** Your own LLM (OpenAI-compatible endpoint, verified with tool-calling probe). */
586
+ llm;
587
+ /** Your own TTS (elevenlabs/cartesia, verified with a real synthesis). */
588
+ tts;
589
+ /** Caller context - what the agent knows about each caller on one of your numbers. */
590
+ callers;
591
+ constructor(options) {
592
+ const http = new HttpClient(options);
593
+ this.agents = new Agents(http);
594
+ this.calls = new Calls(http);
595
+ this.campaigns = new Campaigns(http);
596
+ this.phoneNumbers = new PhoneNumbers(http);
597
+ this.sms = new Sms(http);
598
+ this.keys = new Keys(http);
599
+ this.usage = new UsageResource(http);
600
+ this.webhooks = new Webhooks(http);
601
+ this.storage = new Storage(http);
602
+ this.llm = new Llm(http);
603
+ this.tts = new Tts(http);
604
+ this.callers = new Callers(http);
605
+ }
606
+ /** Create a brand-new API key (unauthenticated signup endpoint - most
607
+ * developers use the dashboard instead). The key_secret is shown ONCE.
608
+ * Rate-limited per IP to prevent abuse. */
609
+ static async createKey(params = {}, baseUrl = "https://api.nixflex.com") {
610
+ const res = await fetch(baseUrl.replace(/\/+$/, "") + "/v1/keys", {
611
+ method: "POST",
612
+ headers: { "Content-Type": "application/json" },
613
+ body: JSON.stringify(params)
614
+ });
615
+ const body = await res.json();
616
+ if (!res.ok) {
617
+ throw errorFromResponse(
618
+ res.status,
619
+ body,
620
+ res.headers.get("x-railway-request-id") || void 0,
621
+ parseInt(res.headers.get("retry-after") || "0", 10) || 0
622
+ );
623
+ }
624
+ return body;
625
+ }
626
+ };
627
+ var src_default = Nixflex;
628
+
629
+ // src/cli/index.ts
630
+ var VERSION = true ? "0.8.0" : "0.0.0";
631
+ var CONFIG_DIR = join(homedir(), ".nixflex");
632
+ var CONFIG_FILE = join(CONFIG_DIR, "config.json");
633
+ function readConfig() {
634
+ try {
635
+ return JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
636
+ } catch {
637
+ return {};
638
+ }
639
+ }
640
+ function writeConfig(cfg) {
641
+ if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
642
+ writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n", { mode: 384 });
643
+ }
644
+ var KEY_RE = /^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i;
645
+ function resolveKey(flagKey) {
646
+ const key = flagKey || process.env.NIXFLEX_API_KEY || readConfig().api_key;
647
+ if (!key) fail("No API key. Run `nixflex login`, or set NIXFLEX_API_KEY.", 2);
648
+ if (!KEY_RE.test(key)) fail("The key must be the full pair: nxf_xxx:nxfs_xxx (key id, colon, secret).", 2);
649
+ return key;
650
+ }
651
+ function ask(question) {
652
+ return new Promise((resolve) => {
653
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
654
+ rl.question(question, (a) => {
655
+ rl.close();
656
+ resolve(a.trim());
657
+ });
658
+ });
659
+ }
660
+ var JSON_MODE = false;
661
+ var HIDE = /^(system_prompt|sms_prompt|web_prompt|transcript|custom_prompt|recording_url|api_key_id)$/;
662
+ function out(data) {
663
+ if (JSON_MODE) {
664
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
665
+ return;
666
+ }
667
+ if (Array.isArray(data)) {
668
+ table(data);
669
+ return;
670
+ }
671
+ if (data && typeof data === "object") {
672
+ kv(data);
673
+ return;
674
+ }
675
+ process.stdout.write(String(data) + "\n");
676
+ }
677
+ function cell(v) {
678
+ if (v === null || v === void 0) return "";
679
+ if (typeof v === "object") return JSON.stringify(v);
680
+ return String(v);
681
+ }
682
+ function table(rows) {
683
+ if (rows.length === 0) {
684
+ process.stdout.write("(none)\n");
685
+ return;
686
+ }
687
+ const objs = rows.filter((r) => r && typeof r === "object");
688
+ if (objs.length === 0) {
689
+ for (const r of rows) process.stdout.write(cell(r) + "\n");
690
+ return;
691
+ }
692
+ const cols = Array.from(new Set(objs.flatMap((r) => Object.keys(r)))).filter((c) => !HIDE.test(c)).slice(0, 8);
693
+ const widths = cols.map((c) => Math.min(40, Math.max(c.length, ...objs.map((r) => cell(r[c]).length))));
694
+ const line = (vals) => vals.map((v, i) => v.slice(0, widths[i]).padEnd(widths[i])).join(" ") + "\n";
695
+ process.stdout.write(line(cols.map((c) => c.toUpperCase())));
696
+ for (const r of objs) process.stdout.write(line(cols.map((c) => cell(r[c]))));
697
+ }
698
+ function kv(o) {
699
+ const keys = Object.keys(o);
700
+ if (keys.length === 0) {
701
+ process.stdout.write("{}\n");
702
+ return;
703
+ }
704
+ const w = Math.max(...keys.map((k) => k.length));
705
+ for (const [k, v] of Object.entries(o)) process.stdout.write(k.padEnd(w) + " " + cell(v) + "\n");
706
+ }
707
+ function note(msg) {
708
+ process.stderr.write(msg + "\n");
709
+ }
710
+ function fail(msg, code = 1) {
711
+ process.stderr.write("error: " + msg + "\n");
712
+ process.exit(code);
713
+ }
714
+ function textOrFile(v) {
715
+ if (v === void 0) return void 0;
716
+ if (v.startsWith("@")) return readFileSync(v.slice(1), "utf8");
717
+ return v;
718
+ }
719
+ function parseValue(raw) {
720
+ if (raw === "null") return null;
721
+ if (raw === "true") return true;
722
+ if (raw === "false") return false;
723
+ if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
724
+ if (raw.startsWith("@")) return readFileSync(raw.slice(1), "utf8");
725
+ if (raw.startsWith("{") && raw.endsWith("}") || raw.startsWith("[") && raw.endsWith("]")) {
726
+ try {
727
+ return JSON.parse(raw);
728
+ } catch {
729
+ }
730
+ }
731
+ return raw;
732
+ }
733
+ function bodyFrom(values, extra = {}) {
734
+ const body = {};
735
+ const b = values.body;
736
+ if (b) {
737
+ const text = b === "-" ? readFileSync(0, "utf8") : textOrFile(b) || "";
738
+ try {
739
+ Object.assign(body, JSON.parse(text));
740
+ } catch {
741
+ fail("--body must be JSON (a file with @path, or - for stdin)");
742
+ }
743
+ }
744
+ for (const kv2 of values.set || []) {
745
+ const i = kv2.indexOf("=");
746
+ if (i < 1) fail("--set expects field=value, got " + kv2);
747
+ body[kv2.slice(0, i)] = parseValue(kv2.slice(i + 1));
748
+ }
749
+ for (const [k, v] of Object.entries(extra)) if (v !== void 0) body[k] = v;
750
+ return body;
751
+ }
752
+ function boolOrNull(v) {
753
+ if (v === void 0) return void 0;
754
+ if (v === "true") return true;
755
+ if (v === "false") return false;
756
+ if (v === "null") return null;
757
+ fail("expected true, false or null, got " + v);
758
+ }
759
+ function vars(list) {
760
+ if (!list || list.length === 0) return void 0;
761
+ const o = {};
762
+ for (const kv2 of list) {
763
+ const i = kv2.indexOf("=");
764
+ if (i < 1) fail("--var expects key=value, got " + kv2);
765
+ o[kv2.slice(0, i)] = kv2.slice(i + 1);
766
+ }
767
+ return o;
768
+ }
769
+ function parseCsv(text) {
770
+ const rows = [];
771
+ let row = [];
772
+ let field = "";
773
+ let q = false;
774
+ for (let i = 0; i < text.length; i++) {
775
+ const ch = text[i];
776
+ if (q) {
777
+ if (ch === '"') {
778
+ if (text[i + 1] === '"') {
779
+ field += '"';
780
+ i++;
781
+ } else q = false;
782
+ } else field += ch;
783
+ continue;
784
+ }
785
+ if (ch === '"') q = true;
786
+ else if (ch === ",") {
787
+ row.push(field);
788
+ field = "";
789
+ } else if (ch === "\n" || ch === "\r") {
790
+ if (ch === "\r" && text[i + 1] === "\n") i++;
791
+ row.push(field);
792
+ rows.push(row);
793
+ row = [];
794
+ field = "";
795
+ } else field += ch;
796
+ }
797
+ if (field.length || row.length) {
798
+ row.push(field);
799
+ rows.push(row);
800
+ }
801
+ const [head, ...body] = rows.filter((r) => r.some((c) => c.trim() !== ""));
802
+ if (!head) return [];
803
+ const keys = head.map((h) => h.trim().replace(/^\uFEFF/, ""));
804
+ return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? "").trim()])));
805
+ }
806
+ function recipientsFromCsv(file, allowOverride) {
807
+ const rows = parseCsv(readFileSync(file, "utf8"));
808
+ if (rows.length === 0) fail("no rows in " + file);
809
+ if (!("phone" in rows[0])) fail("the CSV needs a `phone` column (E.164, e.g. +447700900123)");
810
+ return rows.map((r) => {
811
+ const rec = { phone: r.phone };
812
+ const v = {};
813
+ for (const [k, val] of Object.entries(r)) {
814
+ if (k === "phone" || val === "") continue;
815
+ if (k === "prompt_override" && allowOverride) {
816
+ rec.prompt_override = val;
817
+ continue;
818
+ }
819
+ v[k] = val;
820
+ }
821
+ if (Object.keys(v).length) rec.variables = v;
822
+ return rec;
823
+ });
824
+ }
825
+ var GROUPS = ["login", "logout", "whoami", "usage", "doctor", "completion", "mcp", "agents", "calls", "campaigns", "numbers", "callers", "sms", "webhooks", "keys", "storage", "llm", "tts"];
826
+ var HELP = `nixflex ${VERSION} - the Nixflex voice AI platform from your terminal
827
+
828
+ USAGE nixflex <group> <command> [args] [--json] [--key KEY] [--base-url URL]
829
+
830
+ EXAMPLES
831
+ nixflex login
832
+ nixflex agents update agent_x --set silence_hangup_seconds=12
833
+ nixflex calls create --agent agent_x --to +447700900123 --prompt @call.txt --wait
834
+ nixflex callers import +447450307843 ./customers.csv
835
+
836
+ ACCOUNT
837
+ login store your API key (prompt, or NIXFLEX_API_KEY)
838
+ logout remove the stored key
839
+ whoami key in use, usage and balance
840
+ usage usage and balance
841
+ doctor check key, connectivity and version
842
+ completion <bash|zsh|pwsh> print a shell completion script
843
+ keys rotate --confirm new secret; the old one stops working immediately
844
+
845
+ AGENTS
846
+ agents list [--limit N]
847
+ agents get <agent_id>
848
+ agents create --name NAME --prompt TEXT|@file [--voice ID] [--language xx] [--set k=v ...]
849
+ agents update <id> [--name] [--prompt] [--voice] [--language] [--incall-sms true|false] [--set k=v ...]
850
+ agents delete <id> --confirm
851
+
852
+ CALLS
853
+ calls create --agent ID --to +44... --prompt TEXT|@file [--from +44...] [--var k=v ...] [--wait] [--timeout S]
854
+ calls list [--limit N] [--agent ID]
855
+ calls get <call_id>
856
+ calls delete <call_id> --confirm
857
+ calls delete-all --confirm every call and recording on the account
858
+
859
+ CAMPAIGNS (voice batch)
860
+ campaigns create --agent ID --from +44... --prompt TEXT|@file --csv people.csv [--name] [--set k=v ...]
861
+ CSV: phone (required), prompt_override (optional), any other column = variable
862
+ campaigns launch <campaign_id>
863
+
864
+ NUMBERS
865
+ numbers list [--agent ID]
866
+ numbers import --set phone_number=+44... --set agent_id=ID --set twilio_account_sid=... --set twilio_auth_token=...
867
+ (or --set telnyx_api_key=... --set telnyx_connection_id=...) or --body @number.json
868
+ numbers update <number> [--sms-reply] [--sms-prompt] [--dtmf] [--set k=v ...]
869
+ numbers delete <number> --confirm
870
+ numbers monitor <number> [get|on|off]
871
+ numbers web-calls <number> [get|on|off]
872
+
873
+ CALLERS (caller context)
874
+ callers get <your_number> <caller_number>
875
+ callers set <your_number> <caller_number> [--name] [--email] [--phone] [--location] [--reference] [--preference]
876
+ callers import <your_number> <file.csv> columns: caller_number, name, email, phone, location, reference_id, preference
877
+ callers delete <your_number> <caller_number> --confirm
878
+
879
+ SMS
880
+ sms send --agent ID --from +44... --to +44... --message TEXT
881
+ sms campaigns create --agent ID --from +44... --message TEXT|@file --csv people.csv [--set k=v ...]
882
+ sms campaigns launch <id>
883
+ sms campaigns list [--status S] [--limit N]
884
+ sms campaigns get <id>
885
+ sms campaigns delete <id> --confirm
886
+
887
+ WEBHOOKS (per number)
888
+ webhooks set <number> <url> [--slot 1|2]
889
+ webhooks get <number> [--slot 1|2]
890
+ webhooks delete <number> [--slot 1|2] --confirm
891
+
892
+ BRING YOUR OWN
893
+ storage set --set k=v ... storage get storage delete --confirm
894
+ llm set --set k=v ... llm get llm delete --confirm
895
+ tts set --set k=v ... tts get tts delete --confirm
896
+
897
+ MCP
898
+ mcp setup <claude|cursor|vscode> connect the Nixflex MCP server to that app
899
+
900
+ FLAGS --json machine output --set field=value (repeat) --body @file.json | - --confirm / --yes
901
+ EXIT 0 ok 1 error 2 no API key
902
+ Docs: https://docs.nixflex.com/cli
903
+ `;
904
+ function closest(word, options) {
905
+ const dist = (a, b) => {
906
+ const m = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
907
+ for (let j = 1; j <= b.length; j++) m[0][j] = j;
908
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
909
+ return m[a.length][b.length];
910
+ };
911
+ let best = null;
912
+ let bd = 3;
913
+ for (const o of options) {
914
+ const d = dist(word, o);
915
+ if (d < bd) {
916
+ bd = d;
917
+ best = o;
918
+ }
919
+ }
920
+ return best;
921
+ }
922
+ function completion(shell) {
923
+ const words = GROUPS.join(" ");
924
+ if (shell === "bash") return `_nixflex() { COMPREPLY=($(compgen -W "${words}" -- "\${COMP_WORDS[COMP_CWORD]}")); }
925
+ complete -F _nixflex nixflex
926
+ `;
927
+ if (shell === "zsh") return `#compdef nixflex
928
+ _arguments "1: :(${words})"
929
+ `;
930
+ if (shell === "pwsh") return `Register-ArgumentCompleter -Native -CommandName nixflex -ScriptBlock { param($wordToComplete) '${GROUPS.join("','")}' | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } }
931
+ `;
932
+ fail("completion expects bash, zsh or pwsh");
933
+ }
934
+ function mcpSetup(app) {
935
+ const home = homedir();
936
+ const stored = readConfig().api_key;
937
+ const entry = { command: "npx", args: ["-y", "nixflex-mcp"] };
938
+ if (!stored && process.env.NIXFLEX_API_KEY) entry.env = { NIXFLEX_API_KEY: process.env.NIXFLEX_API_KEY };
939
+ if (!stored && !process.env.NIXFLEX_API_KEY) fail("Run 'nixflex login' first so the MCP server can find your key.");
940
+ let file;
941
+ let root;
942
+ if (app === "claude") {
943
+ file = process.platform === "win32" ? join(process.env.APPDATA || home, "Claude", "claude_desktop_config.json") : process.platform === "darwin" ? join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json") : join(home, ".config", "Claude", "claude_desktop_config.json");
944
+ root = "mcpServers";
945
+ } else if (app === "cursor") {
946
+ file = join(home, ".cursor", "mcp.json");
947
+ root = "mcpServers";
948
+ } else if (app === "vscode") {
949
+ file = join(process.cwd(), ".vscode", "mcp.json");
950
+ root = "servers";
951
+ } else fail("mcp setup expects claude, cursor or vscode");
952
+ let cfg = {};
953
+ try {
954
+ cfg = JSON.parse(readFileSync(file, "utf8"));
955
+ } catch {
956
+ }
957
+ const servers = cfg[root] || {};
958
+ servers["nixflex"] = entry;
959
+ cfg[root] = servers;
960
+ const dir = join(file, "..");
961
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
962
+ writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
963
+ out({ written: file, server: "nixflex", key: stored ? "from ~/.nixflex/config.json" : "written into the config env", note: "Fully quit and reopen " + app + "." });
964
+ }
965
+ async function main() {
966
+ const { values, positionals } = parseArgs({
967
+ args: process.argv.slice(2),
968
+ allowPositionals: true,
969
+ strict: false,
970
+ options: {
971
+ json: { type: "boolean" },
972
+ key: { type: "string" },
973
+ "base-url": { type: "string" },
974
+ help: { type: "boolean", short: "h" },
975
+ version: { type: "boolean", short: "v" },
976
+ confirm: { type: "boolean" },
977
+ yes: { type: "boolean", short: "y" },
978
+ limit: { type: "string" },
979
+ status: { type: "string" },
980
+ set: { type: "string", multiple: true },
981
+ body: { type: "string" },
982
+ name: { type: "string" },
983
+ prompt: { type: "string" },
984
+ voice: { type: "string" },
985
+ language: { type: "string" },
986
+ "incall-sms": { type: "string" },
987
+ agent: { type: "string" },
988
+ to: { type: "string" },
989
+ from: { type: "string" },
990
+ var: { type: "string", multiple: true },
991
+ message: { type: "string" },
992
+ wait: { type: "boolean" },
993
+ timeout: { type: "string" },
994
+ csv: { type: "string" },
995
+ slot: { type: "string" },
996
+ "sms-reply": { type: "string" },
997
+ "sms-prompt": { type: "string" },
998
+ dtmf: { type: "string" },
999
+ email: { type: "string" },
1000
+ phone: { type: "string" },
1001
+ location: { type: "string" },
1002
+ reference: { type: "string" },
1003
+ preference: { type: "string" }
1004
+ }
1005
+ });
1006
+ JSON_MODE = !!values.json;
1007
+ const confirmed = !!(values.confirm || values.yes);
1008
+ const [group, cmd, a1, a2] = positionals;
1009
+ const s = (k) => values[k];
1010
+ if (values.version) {
1011
+ process.stdout.write(VERSION + "\n");
1012
+ return;
1013
+ }
1014
+ if (!group || values.help) {
1015
+ process.stdout.write(HELP);
1016
+ return;
1017
+ }
1018
+ if (!GROUPS.includes(group)) {
1019
+ const c = closest(group, GROUPS);
1020
+ fail('unknown command "' + group + '".' + (c ? " Did you mean `nixflex " + c + "`?" : "") + " Run `nixflex --help`.");
1021
+ }
1022
+ if (group === "login") {
1023
+ const key = process.env.NIXFLEX_API_KEY || await ask("API key (nxf_xxx:nxfs_xxx): ");
1024
+ if (!KEY_RE.test(key)) fail("That is not a full key pair (nxf_xxx:nxfs_xxx).");
1025
+ await new src_default({ apiKey: key, baseUrl: s("base-url") }).usage.get().catch((e) => fail("Key rejected: " + e.message));
1026
+ const cfg = { ...readConfig(), api_key: key };
1027
+ if (s("base-url")) cfg.base_url = s("base-url");
1028
+ writeConfig(cfg);
1029
+ out({ logged_in: true, key_id: key.split(":")[0], config: CONFIG_FILE });
1030
+ return;
1031
+ }
1032
+ if (group === "logout") {
1033
+ const c = readConfig();
1034
+ delete c.api_key;
1035
+ writeConfig(c);
1036
+ out({ logged_out: true });
1037
+ return;
1038
+ }
1039
+ if (group === "completion") {
1040
+ process.stdout.write(completion(cmd || ""));
1041
+ return;
1042
+ }
1043
+ if (group === "mcp") {
1044
+ if (cmd !== "setup") fail("usage: nixflex mcp setup <claude|cursor|vscode>");
1045
+ mcpSetup(a1);
1046
+ return;
1047
+ }
1048
+ const client = new src_default({ apiKey: resolveKey(s("key")), baseUrl: s("base-url") || readConfig().base_url });
1049
+ const limit = s("limit") ? parseInt(s("limit"), 10) : void 0;
1050
+ const slot = s("slot") === "2" ? 2 : 1;
1051
+ const preview = async (what, fetch2) => {
1052
+ if (confirmed) return true;
1053
+ let current = null;
1054
+ try {
1055
+ current = await fetch2();
1056
+ } catch {
1057
+ }
1058
+ out({ would_delete: what, current, hint: "add --confirm (or --yes) to proceed" });
1059
+ return false;
1060
+ };
1061
+ if (group === "whoami") {
1062
+ const u = await client.usage.get();
1063
+ out({ key_id: resolveKey(s("key")).split(":")[0], ...u });
1064
+ return;
1065
+ }
1066
+ if (group === "usage") {
1067
+ out(await client.usage.get());
1068
+ return;
1069
+ }
1070
+ if (group === "doctor") {
1071
+ const checks = { version: VERSION, node: process.version, key_source: s("key") ? "--key" : process.env.NIXFLEX_API_KEY ? "env" : "config", base_url: s("base-url") || readConfig().base_url || "https://api.nixflex.com" };
1072
+ try {
1073
+ const t = Date.now();
1074
+ await client.usage.get();
1075
+ checks.api = "ok (" + (Date.now() - t) + "ms)";
1076
+ } catch (e) {
1077
+ checks.api = "FAILED: " + e.message;
1078
+ }
1079
+ out(checks);
1080
+ return;
1081
+ }
1082
+ if (group === "keys") {
1083
+ if (cmd !== "rotate") fail("keys: rotate --confirm");
1084
+ if (!confirmed) {
1085
+ out({ would_rotate: resolveKey(s("key")).split(":")[0], warning: "The current secret stops working the moment this runs. Update every place that uses it, then `nixflex login` again.", hint: "add --confirm to proceed" });
1086
+ return;
1087
+ }
1088
+ const r = await client.keys.rotate();
1089
+ out(r);
1090
+ note("Run `nixflex login` with the new secret.");
1091
+ return;
1092
+ }
1093
+ if (group === "agents") {
1094
+ if (cmd === "list") {
1095
+ out(await client.agents.list(limit ? { limit } : {}));
1096
+ return;
1097
+ }
1098
+ if (cmd === "get") {
1099
+ if (!a1) fail("agents get <agent_id>");
1100
+ out(await client.agents.get(a1));
1101
+ return;
1102
+ }
1103
+ if (cmd === "create") {
1104
+ const body = bodyFrom(values, { name: s("name"), system_prompt: textOrFile(s("prompt")), voice_id: s("voice"), language: s("language") });
1105
+ if (!body.name || !body.system_prompt) fail("agents create --name NAME --prompt TEXT|@file [--set k=v ...]");
1106
+ out(await client.agents.create(body));
1107
+ return;
1108
+ }
1109
+ if (cmd === "update") {
1110
+ if (!a1) fail("agents update <agent_id> [flags] [--set k=v ...]");
1111
+ const body = bodyFrom(values, { name: s("name"), system_prompt: textOrFile(s("prompt")), voice_id: s("voice"), language: s("language"), incall_sms_enabled: boolOrNull(s("incall-sms")) });
1112
+ if (Object.keys(body).length === 0) fail("nothing to update - pass a flag or --set field=value");
1113
+ out(await client.agents.update(a1, body));
1114
+ return;
1115
+ }
1116
+ if (cmd === "delete") {
1117
+ if (!a1) fail("agents delete <agent_id> --confirm");
1118
+ if (!await preview("agent " + a1, () => client.agents.get(a1))) return;
1119
+ out(await client.agents.delete(a1));
1120
+ return;
1121
+ }
1122
+ fail("agents: list | get | create | update | delete");
1123
+ }
1124
+ if (group === "calls") {
1125
+ if (cmd === "create") {
1126
+ const body = bodyFrom(values, { agent_id: s("agent"), to_number: s("to"), prompt: textOrFile(s("prompt")), from_number: s("from"), variables: vars(values.var) });
1127
+ if (!body.agent_id || !body.to_number || !body.prompt) fail("calls create --agent ID --to +44... --prompt TEXT|@file [--from] [--var k=v] [--wait]");
1128
+ const created = await client.calls.create(body);
1129
+ if (!values.wait) {
1130
+ out(created);
1131
+ return;
1132
+ }
1133
+ const id = created.call_id;
1134
+ if (!id) {
1135
+ out(created);
1136
+ return;
1137
+ }
1138
+ const deadline = Date.now() + (s("timeout") ? parseInt(s("timeout"), 10) : 300) * 1e3;
1139
+ note("call " + id + " placed - waiting for it to end (Ctrl+C to stop waiting; the call continues)");
1140
+ while (Date.now() < deadline) {
1141
+ await new Promise((r) => setTimeout(r, 3e3));
1142
+ const c = await client.calls.get(id).catch(() => null);
1143
+ if (c && (c.ended_reason || /^(completed|failed|no[-_]answer|busy|canceled|cancelled)$/i.test(c.call_status || ""))) {
1144
+ out(c);
1145
+ return;
1146
+ }
1147
+ note(" " + (c && c.call_status ? c.call_status : "in progress") + "...");
1148
+ }
1149
+ fail("still in progress after the timeout - `nixflex calls get " + id + "` later");
1150
+ }
1151
+ if (cmd === "list") {
1152
+ const q = {};
1153
+ if (limit) q.limit = limit;
1154
+ if (s("agent")) q.agent_id = s("agent");
1155
+ out(await client.calls.list(q));
1156
+ return;
1157
+ }
1158
+ if (cmd === "get") {
1159
+ if (!a1) fail("calls get <call_id>");
1160
+ out(await client.calls.get(a1));
1161
+ return;
1162
+ }
1163
+ if (cmd === "delete") {
1164
+ if (!a1) fail("calls delete <call_id> --confirm");
1165
+ if (!await preview("call " + a1 + " and its recording", () => client.calls.get(a1))) return;
1166
+ out(await client.calls.delete(a1));
1167
+ return;
1168
+ }
1169
+ if (cmd === "delete-all") {
1170
+ if (!confirmed) {
1171
+ out({ would_delete: "EVERY call, recording and SMS record on this account", hint: "add --confirm to proceed - this cannot be undone" });
1172
+ return;
1173
+ }
1174
+ out(await client.calls.deleteAll());
1175
+ return;
1176
+ }
1177
+ fail("calls: create | list | get | delete | delete-all");
1178
+ }
1179
+ if (group === "campaigns") {
1180
+ if (cmd === "create") {
1181
+ const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), prompt: textOrFile(s("prompt")), name: s("name") });
1182
+ if (s("csv")) body.recipients = recipientsFromCsv(s("csv"), true);
1183
+ if (!body.agent_id || !body.from_number || !body.prompt || !Array.isArray(body.recipients)) fail("campaigns create --agent ID --from +44... --prompt TEXT|@file --csv people.csv [--set k=v ...]");
1184
+ note("creating campaign with " + body.recipients.length + " recipient(s)");
1185
+ out(await client.campaigns.create(body));
1186
+ return;
1187
+ }
1188
+ if (cmd === "launch") {
1189
+ if (!a1) fail("campaigns launch <campaign_id>");
1190
+ out(await client.campaigns.launch(a1));
1191
+ return;
1192
+ }
1193
+ fail("campaigns: create | launch");
1194
+ }
1195
+ if (group === "numbers") {
1196
+ if (cmd === "list") {
1197
+ const r = await client.phoneNumbers.list(s("agent") ? { agent_id: s("agent") } : {});
1198
+ out(JSON_MODE ? r : r.phone_numbers);
1199
+ return;
1200
+ }
1201
+ if (cmd === "import") {
1202
+ const body = bodyFrom(values);
1203
+ if (!body.phone_number || !body.agent_id) fail("numbers import --set phone_number=+44... --set agent_id=ID --set <carrier credentials> (or --body @number.json)");
1204
+ out(await client.phoneNumbers.import(body));
1205
+ return;
1206
+ }
1207
+ if (cmd === "update") {
1208
+ if (!a1) fail("numbers update <number> [flags] [--set k=v ...]");
1209
+ const body = bodyFrom(values, { sms_reply_enabled: boolOrNull(s("sms-reply")), sms_prompt: s("sms-prompt") === void 0 ? void 0 : s("sms-prompt") === "null" ? null : textOrFile(s("sms-prompt")), dtmf_enabled: boolOrNull(s("dtmf")) });
1210
+ if (Object.keys(body).length === 0) fail("nothing to update - pass a flag or --set field=value");
1211
+ out(await client.phoneNumbers.update(a1, body));
1212
+ return;
1213
+ }
1214
+ if (cmd === "delete") {
1215
+ if (!a1) fail("numbers delete <number> --confirm");
1216
+ if (!confirmed) {
1217
+ out({ would_delete: "number " + a1 + " from Nixflex (your carrier keeps it and keeps billing it)", hint: "add --confirm to proceed" });
1218
+ return;
1219
+ }
1220
+ out(await client.phoneNumbers.delete(a1));
1221
+ return;
1222
+ }
1223
+ if (cmd === "monitor" || cmd === "web-calls") {
1224
+ if (!a1) fail("numbers " + cmd + " <number> [get|on|off]");
1225
+ const action = a2 || "get";
1226
+ const isMon = cmd === "monitor";
1227
+ if (action === "get") {
1228
+ out(isMon ? await client.phoneNumbers.getMonitor(a1) : await client.phoneNumbers.getWebCalls(a1));
1229
+ return;
1230
+ }
1231
+ if (action === "on" || action === "off") {
1232
+ if (isMon && action === "on") note("note: monitoring bills this number's inbound calls at the premium rate");
1233
+ out(isMon ? await client.phoneNumbers.setMonitor(a1, action === "on") : await client.phoneNumbers.setWebCalls(a1, action === "on"));
1234
+ return;
1235
+ }
1236
+ fail("numbers " + cmd + " <number> [get|on|off]");
1237
+ }
1238
+ fail("numbers: list | import | update | delete | monitor | web-calls");
1239
+ }
1240
+ if (group === "callers") {
1241
+ if (cmd === "get") {
1242
+ if (!a1 || !a2) fail("callers get <your_number> <caller_number>");
1243
+ const r = await client.callers.get(a1, a2);
1244
+ out(JSON_MODE ? r : r.caller.context);
1245
+ return;
1246
+ }
1247
+ if (cmd === "set") {
1248
+ if (!a1 || !a2) fail("callers set <your_number> <caller_number> --name ... --email ... [--set k=v]");
1249
+ const nul = (v) => v === void 0 ? void 0 : v === "null" ? null : v;
1250
+ const body = bodyFrom(values, { name: nul(s("name")), email: nul(s("email")), phone: nul(s("phone")), location: nul(s("location")), reference_id: nul(s("reference")), preference: nul(s("preference")) });
1251
+ if (Object.keys(body).length === 0) fail("nothing to set - pass at least one of --name --email --phone --location --reference --preference");
1252
+ const r = await client.callers.set(a1, a2, body);
1253
+ out(JSON_MODE ? r : r.caller.context);
1254
+ return;
1255
+ }
1256
+ if (cmd === "import") {
1257
+ if (!a1 || !a2) fail("callers import <your_number> <file.csv>");
1258
+ const rows = parseCsv(readFileSync(a2, "utf8"));
1259
+ if (rows.length === 0) fail("no rows in " + a2);
1260
+ if (!("caller_number" in rows[0])) fail("the CSV needs a caller_number column");
1261
+ let imported = 0;
1262
+ for (let i = 0; i < rows.length; i += 1e3) {
1263
+ const chunk = rows.slice(i, i + 1e3).map((r2) => {
1264
+ const o = {};
1265
+ for (const [k, v] of Object.entries(r2)) if (v !== "") o[k] = v;
1266
+ return o;
1267
+ });
1268
+ note("importing rows " + (i + 1) + "-" + Math.min(i + 1e3, rows.length) + " of " + rows.length);
1269
+ const r = await client.callers.import(a1, chunk);
1270
+ imported += r.imported;
1271
+ }
1272
+ out({ phone_number: a1, imported, rows: rows.length });
1273
+ return;
1274
+ }
1275
+ if (cmd === "delete") {
1276
+ if (!a1 || !a2) fail("callers delete <your_number> <caller_number> --confirm");
1277
+ if (!await preview("caller " + a2 + " on " + a1, async () => (await client.callers.get(a1, a2)).caller.context)) return;
1278
+ out(await client.callers.delete(a1, a2));
1279
+ return;
1280
+ }
1281
+ fail("callers: get | set | import | delete");
1282
+ }
1283
+ if (group === "sms") {
1284
+ if (cmd === "send") {
1285
+ const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), to: s("to"), message: textOrFile(s("message")) });
1286
+ if (!body.agent_id || !body.from_number || !body.to || !body.message) fail("sms send --agent ID --from +44... --to +44... --message TEXT");
1287
+ out(await client.sms.send(body));
1288
+ return;
1289
+ }
1290
+ if (cmd === "campaigns") {
1291
+ const sub = a1;
1292
+ const id = a2;
1293
+ if (sub === "create") {
1294
+ const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), message: textOrFile(s("message")), name: s("name") });
1295
+ if (s("csv")) body.recipients = recipientsFromCsv(s("csv"), false);
1296
+ if (!body.agent_id || !body.from_number || !body.message || !Array.isArray(body.recipients)) fail("sms campaigns create --agent ID --from +44... --message TEXT|@file --csv people.csv");
1297
+ out(await client.sms.campaigns.create(body));
1298
+ return;
1299
+ }
1300
+ if (sub === "launch") {
1301
+ if (!id) fail("sms campaigns launch <id>");
1302
+ out(await client.sms.campaigns.launch(id));
1303
+ return;
1304
+ }
1305
+ if (sub === "list") {
1306
+ const q = {};
1307
+ if (limit) q.limit = limit;
1308
+ if (s("status")) q.status = s("status");
1309
+ const r = await client.sms.campaigns.list(q);
1310
+ out(JSON_MODE ? r : r.campaigns || r);
1311
+ return;
1312
+ }
1313
+ if (sub === "get") {
1314
+ if (!id) fail("sms campaigns get <id>");
1315
+ out(await client.sms.campaigns.get(id));
1316
+ return;
1317
+ }
1318
+ if (sub === "delete") {
1319
+ if (!id) fail("sms campaigns delete <id> --confirm");
1320
+ if (!await preview("sms campaign " + id + " (pending recipients will not be messaged)", () => client.sms.campaigns.get(id))) return;
1321
+ out(await client.sms.campaigns.delete(id));
1322
+ return;
1323
+ }
1324
+ fail("sms campaigns: create | launch | list | get | delete");
1325
+ }
1326
+ fail("sms: send | campaigns");
1327
+ }
1328
+ if (group === "webhooks") {
1329
+ if (cmd === "set") {
1330
+ if (!a1 || !a2) fail("webhooks set <number> <url> [--slot 1|2]");
1331
+ out(await client.webhooks.set(a1, a2, slot));
1332
+ return;
1333
+ }
1334
+ if (cmd === "get") {
1335
+ if (!a1) fail("webhooks get <number> [--slot 1|2]");
1336
+ out(await client.webhooks.get(a1, slot));
1337
+ return;
1338
+ }
1339
+ if (cmd === "delete") {
1340
+ if (!a1) fail("webhooks delete <number> [--slot 1|2] --confirm");
1341
+ if (!await preview("webhook slot " + slot + " on " + a1, () => client.webhooks.get(a1, slot))) return;
1342
+ out(await client.webhooks.delete(a1, slot));
1343
+ return;
1344
+ }
1345
+ fail("webhooks: set | get | delete");
1346
+ }
1347
+ if (group === "storage" || group === "llm" || group === "tts") {
1348
+ const res = client[group];
1349
+ if (cmd === "set") {
1350
+ const body = bodyFrom(values);
1351
+ if (Object.keys(body).length === 0) fail(group + " set --set field=value ... (or --body @file.json) - see https://docs.nixflex.com/advanced/your-own-" + group);
1352
+ out(await res.set(body));
1353
+ return;
1354
+ }
1355
+ if (cmd === "get") {
1356
+ out(await res.get());
1357
+ return;
1358
+ }
1359
+ if (cmd === "delete") {
1360
+ if (!await preview("your own " + group + " configuration (calls fall back to Nixflex)", () => res.get())) return;
1361
+ out(await res.delete());
1362
+ return;
1363
+ }
1364
+ fail(group + ": set | get | delete");
1365
+ }
1366
+ fail('unknown command "' + group + '". Run `nixflex --help`.');
1367
+ }
1368
+ main().catch((e) => {
1369
+ if (e instanceof NixflexError) {
1370
+ if (JSON_MODE) process.stdout.write(JSON.stringify({ error: { code: e.code, status: e.status, message: e.message, doc_url: e.docUrl } }, null, 2) + "\n");
1371
+ else process.stderr.write("error " + (e.status || "") + " " + (e.code || "") + ": " + e.message + (e.docUrl ? "\n " + e.docUrl : "") + "\n");
1372
+ process.exitCode = 1;
1373
+ return;
1374
+ }
1375
+ fail(e.message);
1376
+ });