nixflex 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/cli/index.js +1081 -0
- package/dist/index.cjs +39 -6
- package/dist/index.d.cts +71 -1
- package/dist/index.d.ts +71 -1
- package/dist/index.js +36 -3
- package/package.json +3 -2
|
@@ -0,0 +1,1081 @@
|
|
|
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.7.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.7.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
|
+
function resolveKey(flagKey) {
|
|
645
|
+
const key = flagKey || process.env.NIXFLEX_API_KEY || readConfig().api_key;
|
|
646
|
+
if (!key) fail("No API key. Run `nixflex login`, or set NIXFLEX_API_KEY.", 2);
|
|
647
|
+
if (!/^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i.test(key)) fail("The key must be the full pair: nxf_xxx:nxfs_xxx (key id, colon, secret).", 2);
|
|
648
|
+
return key;
|
|
649
|
+
}
|
|
650
|
+
function ask(question, hidden = false) {
|
|
651
|
+
return new Promise((resolve) => {
|
|
652
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
653
|
+
if (hidden) {
|
|
654
|
+
const out2 = rl;
|
|
655
|
+
out2._writeToOutput = (s) => {
|
|
656
|
+
if (s.includes(question)) out2.output.write(question);
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
rl.question(question, (a) => {
|
|
660
|
+
rl.close();
|
|
661
|
+
if (hidden) process.stdout.write("\n");
|
|
662
|
+
resolve(a.trim());
|
|
663
|
+
});
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
var JSON_MODE = false;
|
|
667
|
+
function out(data) {
|
|
668
|
+
if (JSON_MODE) {
|
|
669
|
+
process.stdout.write(JSON.stringify(data, null, 2) + "\n");
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
if (Array.isArray(data)) {
|
|
673
|
+
table(data);
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
if (data && typeof data === "object") {
|
|
677
|
+
kv(data);
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
process.stdout.write(String(data) + "\n");
|
|
681
|
+
}
|
|
682
|
+
function cell(v) {
|
|
683
|
+
if (v === null || v === void 0) return "";
|
|
684
|
+
if (typeof v === "object") return JSON.stringify(v);
|
|
685
|
+
return String(v);
|
|
686
|
+
}
|
|
687
|
+
function table(rows) {
|
|
688
|
+
if (rows.length === 0) {
|
|
689
|
+
process.stdout.write("(none)\n");
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
const objs = rows.filter((r) => r && typeof r === "object");
|
|
693
|
+
const cols = Array.from(new Set(objs.flatMap((r) => Object.keys(r)))).filter((c) => !/^(system_prompt|sms_prompt|web_prompt|transcript|custom_prompt)$/.test(c)).slice(0, 8);
|
|
694
|
+
const widths = cols.map((c) => Math.min(40, Math.max(c.length, ...objs.map((r) => cell(r[c]).length))));
|
|
695
|
+
const line = (vals) => vals.map((v, i) => v.slice(0, widths[i]).padEnd(widths[i])).join(" ") + "\n";
|
|
696
|
+
process.stdout.write(line(cols.map((c) => c.toUpperCase())));
|
|
697
|
+
for (const r of objs) process.stdout.write(line(cols.map((c) => cell(r[c]))));
|
|
698
|
+
}
|
|
699
|
+
function kv(o) {
|
|
700
|
+
const w = Math.max(...Object.keys(o).map((k) => k.length));
|
|
701
|
+
for (const [k, v] of Object.entries(o)) process.stdout.write(k.padEnd(w) + " " + cell(v) + "\n");
|
|
702
|
+
}
|
|
703
|
+
function fail(msg, code = 1) {
|
|
704
|
+
process.stderr.write("error: " + msg + "\n");
|
|
705
|
+
process.exit(code);
|
|
706
|
+
}
|
|
707
|
+
function parseCsv(text) {
|
|
708
|
+
const rows = [];
|
|
709
|
+
let row = [];
|
|
710
|
+
let field = "";
|
|
711
|
+
let q = false;
|
|
712
|
+
for (let i = 0; i < text.length; i++) {
|
|
713
|
+
const ch = text[i];
|
|
714
|
+
if (q) {
|
|
715
|
+
if (ch === '"') {
|
|
716
|
+
if (text[i + 1] === '"') {
|
|
717
|
+
field += '"';
|
|
718
|
+
i++;
|
|
719
|
+
} else q = false;
|
|
720
|
+
} else field += ch;
|
|
721
|
+
continue;
|
|
722
|
+
}
|
|
723
|
+
if (ch === '"') q = true;
|
|
724
|
+
else if (ch === ",") {
|
|
725
|
+
row.push(field);
|
|
726
|
+
field = "";
|
|
727
|
+
} else if (ch === "\n" || ch === "\r") {
|
|
728
|
+
if (ch === "\r" && text[i + 1] === "\n") i++;
|
|
729
|
+
row.push(field);
|
|
730
|
+
rows.push(row);
|
|
731
|
+
row = [];
|
|
732
|
+
field = "";
|
|
733
|
+
} else field += ch;
|
|
734
|
+
}
|
|
735
|
+
if (field.length || row.length) {
|
|
736
|
+
row.push(field);
|
|
737
|
+
rows.push(row);
|
|
738
|
+
}
|
|
739
|
+
const [head, ...body] = rows.filter((r) => r.some((c) => c.trim() !== ""));
|
|
740
|
+
if (!head) return [];
|
|
741
|
+
const keys = head.map((h) => h.trim());
|
|
742
|
+
return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? "").trim()])));
|
|
743
|
+
}
|
|
744
|
+
var HELP = `nixflex ${VERSION} - the Nixflex voice AI platform from your terminal
|
|
745
|
+
|
|
746
|
+
USAGE nixflex <group> <command> [args] [--json] [--key KEY]
|
|
747
|
+
|
|
748
|
+
ACCOUNT
|
|
749
|
+
login store your API key (prompt, or NIXFLEX_API_KEY)
|
|
750
|
+
logout remove the stored key
|
|
751
|
+
whoami show which key is in use and the account balance
|
|
752
|
+
usage usage and balance
|
|
753
|
+
doctor check key, connectivity and version
|
|
754
|
+
|
|
755
|
+
AGENTS
|
|
756
|
+
agents list [--limit N]
|
|
757
|
+
agents get <agent_id>
|
|
758
|
+
agents create --name NAME --prompt TEXT|@file [--voice ID] [--language xx]
|
|
759
|
+
agents update <agent_id> [--name] [--prompt] [--voice] [--language] [--incall-sms true|false]
|
|
760
|
+
agents delete <agent_id> --confirm
|
|
761
|
+
|
|
762
|
+
CALLS
|
|
763
|
+
calls create --agent ID --to +44... --prompt TEXT|@file [--from +44...] [--var key=value ...]
|
|
764
|
+
calls list [--limit N] [--agent ID]
|
|
765
|
+
calls get <call_id>
|
|
766
|
+
|
|
767
|
+
NUMBERS
|
|
768
|
+
numbers list [--agent ID]
|
|
769
|
+
numbers update <number> [--sms-reply true|false] [--sms-prompt TEXT|@file] [--dtmf true|false|null]
|
|
770
|
+
|
|
771
|
+
CALLERS (caller context - what the agent knows about a caller on one of your numbers)
|
|
772
|
+
callers get <your_number> <caller_number>
|
|
773
|
+
callers set <your_number> <caller_number> [--name] [--email] [--phone] [--location] [--reference] [--preference]
|
|
774
|
+
(pass --email null to remove a field)
|
|
775
|
+
callers import <your_number> <file.csv> columns: caller_number,name,email,phone,location,reference_id,preference
|
|
776
|
+
callers delete <your_number> <caller_number> --confirm
|
|
777
|
+
|
|
778
|
+
SMS
|
|
779
|
+
sms send --agent ID --from +44... --to +44... --message TEXT
|
|
780
|
+
|
|
781
|
+
MCP
|
|
782
|
+
mcp setup <claude|cursor|vscode> write the Nixflex MCP server into that app's config
|
|
783
|
+
|
|
784
|
+
Every command accepts --json. Docs: https://docs.nixflex.com/cli
|
|
785
|
+
`;
|
|
786
|
+
function textOrFile(v) {
|
|
787
|
+
if (v === void 0) return void 0;
|
|
788
|
+
if (v.startsWith("@")) return readFileSync(v.slice(1), "utf8");
|
|
789
|
+
return v;
|
|
790
|
+
}
|
|
791
|
+
function boolOrNull(v) {
|
|
792
|
+
if (v === void 0) return void 0;
|
|
793
|
+
if (v === "true") return true;
|
|
794
|
+
if (v === "false") return false;
|
|
795
|
+
if (v === "null") return null;
|
|
796
|
+
fail("expected true, false or null, got " + v);
|
|
797
|
+
}
|
|
798
|
+
function nullable(v) {
|
|
799
|
+
if (v === void 0) return void 0;
|
|
800
|
+
return v === "null" ? null : v;
|
|
801
|
+
}
|
|
802
|
+
function vars(list) {
|
|
803
|
+
if (!list || list.length === 0) return void 0;
|
|
804
|
+
const o = {};
|
|
805
|
+
for (const kv2 of list) {
|
|
806
|
+
const i = kv2.indexOf("=");
|
|
807
|
+
if (i < 1) fail("--var expects key=value, got " + kv2);
|
|
808
|
+
o[kv2.slice(0, i)] = kv2.slice(i + 1);
|
|
809
|
+
}
|
|
810
|
+
return o;
|
|
811
|
+
}
|
|
812
|
+
function mcpSetup(app) {
|
|
813
|
+
const home = homedir();
|
|
814
|
+
const entry = { command: "npx", args: ["-y", "nixflex-mcp"], env: { NIXFLEX_API_KEY: "${NIXFLEX_API_KEY}" } };
|
|
815
|
+
let file;
|
|
816
|
+
let root;
|
|
817
|
+
if (app === "claude") {
|
|
818
|
+
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");
|
|
819
|
+
root = "mcpServers";
|
|
820
|
+
} else if (app === "cursor") {
|
|
821
|
+
file = join(home, ".cursor", "mcp.json");
|
|
822
|
+
root = "mcpServers";
|
|
823
|
+
} else if (app === "vscode") {
|
|
824
|
+
file = join(process.cwd(), ".vscode", "mcp.json");
|
|
825
|
+
root = "servers";
|
|
826
|
+
} else fail("mcp setup expects claude, cursor or vscode");
|
|
827
|
+
let cfg = {};
|
|
828
|
+
try {
|
|
829
|
+
cfg = JSON.parse(readFileSync(file, "utf8"));
|
|
830
|
+
} catch {
|
|
831
|
+
}
|
|
832
|
+
const servers = cfg[root] || {};
|
|
833
|
+
servers["nixflex"] = entry;
|
|
834
|
+
cfg[root] = servers;
|
|
835
|
+
const dir = join(file, "..");
|
|
836
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
837
|
+
writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
|
|
838
|
+
out({ written: file, server: "nixflex", note: "Set NIXFLEX_API_KEY in your environment, then restart " + app + "." });
|
|
839
|
+
}
|
|
840
|
+
async function main() {
|
|
841
|
+
const { values, positionals } = parseArgs({
|
|
842
|
+
args: process.argv.slice(2),
|
|
843
|
+
allowPositionals: true,
|
|
844
|
+
strict: false,
|
|
845
|
+
options: {
|
|
846
|
+
json: { type: "boolean" },
|
|
847
|
+
key: { type: "string" },
|
|
848
|
+
help: { type: "boolean", short: "h" },
|
|
849
|
+
version: { type: "boolean", short: "v" },
|
|
850
|
+
confirm: { type: "boolean" },
|
|
851
|
+
limit: { type: "string" },
|
|
852
|
+
name: { type: "string" },
|
|
853
|
+
prompt: { type: "string" },
|
|
854
|
+
voice: { type: "string" },
|
|
855
|
+
language: { type: "string" },
|
|
856
|
+
"incall-sms": { type: "string" },
|
|
857
|
+
agent: { type: "string" },
|
|
858
|
+
to: { type: "string" },
|
|
859
|
+
from: { type: "string" },
|
|
860
|
+
var: { type: "string", multiple: true },
|
|
861
|
+
message: { type: "string" },
|
|
862
|
+
"sms-reply": { type: "string" },
|
|
863
|
+
"sms-prompt": { type: "string" },
|
|
864
|
+
dtmf: { type: "string" },
|
|
865
|
+
email: { type: "string" },
|
|
866
|
+
phone: { type: "string" },
|
|
867
|
+
location: { type: "string" },
|
|
868
|
+
reference: { type: "string" },
|
|
869
|
+
preference: { type: "string" }
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
JSON_MODE = !!values.json;
|
|
873
|
+
const [group, cmd, a1, a2] = positionals;
|
|
874
|
+
if (values.version) {
|
|
875
|
+
process.stdout.write(VERSION + "\n");
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
if (!group || values.help) {
|
|
879
|
+
process.stdout.write(HELP);
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
const s = (k) => values[k];
|
|
883
|
+
if (group === "login") {
|
|
884
|
+
const key = process.env.NIXFLEX_API_KEY || await ask("API key (nxf_xxx:nxfs_xxx): ", true);
|
|
885
|
+
if (!/^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i.test(key)) fail("That is not a full key pair (nxf_xxx:nxfs_xxx).");
|
|
886
|
+
await new src_default({ apiKey: key }).usage.get().catch((e) => fail("Key rejected: " + e.message));
|
|
887
|
+
writeConfig({ ...readConfig(), api_key: key });
|
|
888
|
+
out({ logged_in: true, key_id: key.split(":")[0], config: CONFIG_FILE });
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
if (group === "logout") {
|
|
892
|
+
const c = readConfig();
|
|
893
|
+
delete c.api_key;
|
|
894
|
+
writeConfig(c);
|
|
895
|
+
out({ logged_out: true });
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
if (group === "mcp") {
|
|
899
|
+
if (cmd !== "setup") fail("usage: nixflex mcp setup <claude|cursor|vscode>");
|
|
900
|
+
mcpSetup(a1);
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
if (!["whoami", "usage", "doctor", "agents", "calls", "numbers", "callers", "sms"].includes(group)) fail('unknown command "' + group + '". Run `nixflex --help`.');
|
|
904
|
+
const client = new src_default({ apiKey: resolveKey(s("key")), baseUrl: readConfig().base_url });
|
|
905
|
+
const limit = s("limit") ? parseInt(s("limit"), 10) : void 0;
|
|
906
|
+
if (group === "whoami") {
|
|
907
|
+
const u = await client.usage.get();
|
|
908
|
+
out({ key_id: resolveKey(s("key")).split(":")[0], ...u });
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
if (group === "usage") {
|
|
912
|
+
out(await client.usage.get());
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
if (group === "doctor") {
|
|
916
|
+
const checks = { version: VERSION, node: process.version, key_source: s("key") ? "--key" : process.env.NIXFLEX_API_KEY ? "env" : "config" };
|
|
917
|
+
try {
|
|
918
|
+
const t = Date.now();
|
|
919
|
+
await client.usage.get();
|
|
920
|
+
checks.api = "ok (" + (Date.now() - t) + "ms)";
|
|
921
|
+
} catch (e) {
|
|
922
|
+
checks.api = "FAILED: " + e.message;
|
|
923
|
+
}
|
|
924
|
+
out(checks);
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
if (group === "agents") {
|
|
928
|
+
if (cmd === "list") {
|
|
929
|
+
out(await client.agents.list(limit ? { limit } : {}));
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
if (cmd === "get") {
|
|
933
|
+
if (!a1) fail("agents get <agent_id>");
|
|
934
|
+
out(await client.agents.get(a1));
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
if (cmd === "create") {
|
|
938
|
+
if (!s("name") || !s("prompt")) fail("agents create --name NAME --prompt TEXT|@file");
|
|
939
|
+
const body = { name: s("name"), system_prompt: textOrFile(s("prompt")) };
|
|
940
|
+
if (s("voice")) body.voice_id = s("voice");
|
|
941
|
+
if (s("language")) body.language = s("language");
|
|
942
|
+
out(await client.agents.create(body));
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
if (cmd === "update") {
|
|
946
|
+
if (!a1) fail("agents update <agent_id> [--name] [--prompt] [--voice] [--language] [--incall-sms]");
|
|
947
|
+
const body = {};
|
|
948
|
+
if (s("name")) body.name = s("name");
|
|
949
|
+
if (s("prompt")) body.system_prompt = textOrFile(s("prompt"));
|
|
950
|
+
if (s("voice")) body.voice_id = s("voice");
|
|
951
|
+
if (s("language")) body.language = s("language");
|
|
952
|
+
const ic = boolOrNull(s("incall-sms"));
|
|
953
|
+
if (ic !== void 0) body.incall_sms_enabled = ic;
|
|
954
|
+
if (Object.keys(body).length === 0) fail("nothing to update - pass at least one flag");
|
|
955
|
+
out(await client.agents.update(a1, body));
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
if (cmd === "delete") {
|
|
959
|
+
if (!a1) fail("agents delete <agent_id> --confirm");
|
|
960
|
+
if (!values.confirm) {
|
|
961
|
+
const ag = await client.agents.get(a1);
|
|
962
|
+
out({ would_delete: ag.name, agent_id: a1, hint: "add --confirm to delete" });
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
out(await client.agents.delete(a1));
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
fail("agents: list | get | create | update | delete");
|
|
969
|
+
}
|
|
970
|
+
if (group === "calls") {
|
|
971
|
+
if (cmd === "create") {
|
|
972
|
+
if (!s("agent") || !s("to") || !s("prompt")) fail("calls create --agent ID --to +44... --prompt TEXT|@file [--from +44...] [--var k=v]");
|
|
973
|
+
const body = { agent_id: s("agent"), to_number: s("to"), prompt: textOrFile(s("prompt")) };
|
|
974
|
+
if (s("from")) body.from_number = s("from");
|
|
975
|
+
const v = vars(values.var);
|
|
976
|
+
if (v) body.variables = v;
|
|
977
|
+
out(await client.calls.create(body));
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
if (cmd === "list") {
|
|
981
|
+
const q = {};
|
|
982
|
+
if (limit) q.limit = limit;
|
|
983
|
+
if (s("agent")) q.agent_id = s("agent");
|
|
984
|
+
out(await client.calls.list(q));
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (cmd === "get") {
|
|
988
|
+
if (!a1) fail("calls get <call_id>");
|
|
989
|
+
out(await client.calls.get(a1));
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
fail("calls: create | list | get");
|
|
993
|
+
}
|
|
994
|
+
if (group === "numbers") {
|
|
995
|
+
if (cmd === "list") {
|
|
996
|
+
const r = await client.phoneNumbers.list(s("agent") ? { agent_id: s("agent") } : {});
|
|
997
|
+
out(JSON_MODE ? r : r.phone_numbers);
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
if (cmd === "update") {
|
|
1001
|
+
if (!a1) fail("numbers update <number> [--sms-reply] [--sms-prompt] [--dtmf]");
|
|
1002
|
+
const body = {};
|
|
1003
|
+
const sr = boolOrNull(s("sms-reply"));
|
|
1004
|
+
if (sr !== void 0) body.sms_reply_enabled = sr;
|
|
1005
|
+
if (s("sms-prompt") !== void 0) body.sms_prompt = nullable(textOrFile(s("sms-prompt")));
|
|
1006
|
+
const d = boolOrNull(s("dtmf"));
|
|
1007
|
+
if (d !== void 0) body.dtmf_enabled = d;
|
|
1008
|
+
if (Object.keys(body).length === 0) fail("nothing to update - pass at least one flag");
|
|
1009
|
+
out(await client.phoneNumbers.update(a1, body));
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
fail("numbers: list | update");
|
|
1013
|
+
}
|
|
1014
|
+
if (group === "callers") {
|
|
1015
|
+
if (cmd === "get") {
|
|
1016
|
+
if (!a1 || !a2) fail("callers get <your_number> <caller_number>");
|
|
1017
|
+
const r = await client.callers.get(a1, a2);
|
|
1018
|
+
out(JSON_MODE ? r : r.caller.context);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
if (cmd === "set") {
|
|
1022
|
+
if (!a1 || !a2) fail("callers set <your_number> <caller_number> --name ... --email ...");
|
|
1023
|
+
const body = {};
|
|
1024
|
+
for (const [flag, field] of [["name", "name"], ["email", "email"], ["phone", "phone"], ["location", "location"], ["reference", "reference_id"], ["preference", "preference"]]) {
|
|
1025
|
+
const v = nullable(s(flag));
|
|
1026
|
+
if (v !== void 0) body[field] = v;
|
|
1027
|
+
}
|
|
1028
|
+
if (Object.keys(body).length === 0) fail("nothing to set - pass at least one of --name --email --phone --location --reference --preference");
|
|
1029
|
+
const r = await client.callers.set(a1, a2, body);
|
|
1030
|
+
out(JSON_MODE ? r : r.caller.context);
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
if (cmd === "import") {
|
|
1034
|
+
if (!a1 || !a2) fail("callers import <your_number> <file.csv>");
|
|
1035
|
+
const rows = parseCsv(readFileSync(a2, "utf8"));
|
|
1036
|
+
if (rows.length === 0) fail("no rows in " + a2);
|
|
1037
|
+
if (!("caller_number" in rows[0])) fail("the CSV needs a caller_number column");
|
|
1038
|
+
let imported = 0;
|
|
1039
|
+
for (let i = 0; i < rows.length; i += 1e3) {
|
|
1040
|
+
const chunk = rows.slice(i, i + 1e3).map((r2) => {
|
|
1041
|
+
const o = {};
|
|
1042
|
+
for (const [k, v] of Object.entries(r2)) if (v !== "") o[k] = v;
|
|
1043
|
+
return o;
|
|
1044
|
+
});
|
|
1045
|
+
const r = await client.callers.import(a1, chunk);
|
|
1046
|
+
imported += r.imported;
|
|
1047
|
+
}
|
|
1048
|
+
out({ phone_number: a1, imported, rows: rows.length });
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
if (cmd === "delete") {
|
|
1052
|
+
if (!a1 || !a2) fail("callers delete <your_number> <caller_number> --confirm");
|
|
1053
|
+
if (!values.confirm) {
|
|
1054
|
+
const r = await client.callers.get(a1, a2);
|
|
1055
|
+
out({ would_delete: r.caller.context, hint: "add --confirm to delete" });
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
out(await client.callers.delete(a1, a2));
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
fail("callers: get | set | import | delete");
|
|
1062
|
+
}
|
|
1063
|
+
if (group === "sms") {
|
|
1064
|
+
if (cmd === "send") {
|
|
1065
|
+
if (!s("agent") || !s("from") || !s("to") || !s("message")) fail("sms send --agent ID --from +44... --to +44... --message TEXT");
|
|
1066
|
+
out(await client.sms.send({ agent_id: s("agent"), from_number: s("from"), to: s("to"), message: s("message") }));
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
fail("sms: send");
|
|
1070
|
+
}
|
|
1071
|
+
fail('unknown command "' + group + '". Run `nixflex --help`.');
|
|
1072
|
+
}
|
|
1073
|
+
main().catch((e) => {
|
|
1074
|
+
if (e instanceof NixflexError) {
|
|
1075
|
+
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");
|
|
1076
|
+
else process.stderr.write("error " + (e.status || "") + " " + (e.code || "") + ": " + e.message + (e.docUrl ? "\n " + e.docUrl : "") + "\n");
|
|
1077
|
+
process.exitCode = 1;
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
fail(e.message);
|
|
1081
|
+
});
|