nixflex 0.9.0 → 0.11.1

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/dist/cli/index.js CHANGED
@@ -2,10 +2,34 @@
2
2
 
3
3
  // src/cli/index.ts
4
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";
5
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, existsSync } from "fs";
6
+ import { homedir as homedir3 } from "os";
7
+ import { join as join4 } from "path";
8
+ import { createInterface as createInterface2 } from "readline";
9
+
10
+ // src/cli/kit-fields.ts
11
+ function recipientField(rec, key, value) {
12
+ if (key !== "country" && key !== "timezone") return false;
13
+ rec[key] = value;
14
+ return true;
15
+ }
16
+ var kitFlags = Object.fromEntries(["recipient-country", "recipient-timezone", "before", "recipient-cursor", "message-cursor"].map((key) => [key, { type: "string" }]));
17
+ function contactFields(values) {
18
+ return { recipient_country: values["recipient-country"], recipient_timezone: values["recipient-timezone"] };
19
+ }
20
+ function smsPage(values) {
21
+ const result = {};
22
+ if (values.limit !== void 0) {
23
+ if (typeof values.limit !== "string" || !/^[1-9]\d*$/.test(values.limit) || +values.limit > 500)
24
+ throw new Error("SMS detail --limit must be 1..500.");
25
+ result.limit = +values.limit;
26
+ }
27
+ for (const key of ["recipient-cursor", "message-cursor"]) if (values[key] !== void 0) {
28
+ if (typeof values[key] !== "string") throw new Error(`Invalid --${key}.`);
29
+ result[key.replace("-", "_")] = values[key];
30
+ }
31
+ return result;
32
+ }
9
33
 
10
34
  // src/errors.ts
11
35
  var NixflexError = class extends Error {
@@ -21,7 +45,7 @@ var NixflexError = class extends Error {
21
45
  details;
22
46
  /** The x-railway-request-id (or similar) header when present - quote it to support. */
23
47
  requestId;
24
- constructor(status, body, requestId, fallbackMessage) {
48
+ constructor(status, body, requestId2, fallbackMessage) {
25
49
  const e = body == null ? void 0 : body.error;
26
50
  super((e == null ? void 0 : e.message) || fallbackMessage || `Nixflex API error (HTTP ${status})`);
27
51
  this.name = "NixflexError";
@@ -30,7 +54,24 @@ var NixflexError = class extends Error {
30
54
  this.type = (e == null ? void 0 : e.type) || "error";
31
55
  this.docUrl = e == null ? void 0 : e.doc_url;
32
56
  this.details = (e == null ? void 0 : e.details) || {};
33
- this.requestId = requestId;
57
+ this.requestId = requestId2 || (e == null ? void 0 : e.request_id) || (typeof this.details.request_id === "string" ? this.details.request_id : void 0);
58
+ }
59
+ get doc_url() {
60
+ return this.docUrl ?? null;
61
+ }
62
+ get request_id() {
63
+ return this.requestId ?? null;
64
+ }
65
+ toJSON() {
66
+ return { error: {
67
+ type: this.type,
68
+ code: this.code,
69
+ message: this.message,
70
+ details: this.details,
71
+ doc_url: this.doc_url,
72
+ status: this.status,
73
+ request_id: this.request_id
74
+ } };
34
75
  }
35
76
  };
36
77
  var NixflexAuthenticationError = class extends NixflexError {
@@ -53,8 +94,8 @@ var NixflexNotFoundError = class extends NixflexError {
53
94
  };
54
95
  var NixflexRateLimitError = class extends NixflexError {
55
96
  retryAfterSeconds;
56
- constructor(status, body, requestId, retryAfterSeconds) {
57
- super(status, body, requestId);
97
+ constructor(status, body, requestId2, retryAfterSeconds) {
98
+ super(status, body, requestId2);
58
99
  this.name = "NixflexRateLimitError";
59
100
  this.retryAfterSeconds = retryAfterSeconds;
60
101
  }
@@ -77,25 +118,337 @@ var NixflexConnectionError = class extends NixflexError {
77
118
  this.name = "NixflexConnectionError";
78
119
  }
79
120
  };
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);
121
+ var NixflexOutcomeUnknownError = class extends NixflexServerError {
122
+ outcome = "unknown";
123
+ safe_to_retry = false;
124
+ constructor(status = 0, body = null, requestId2) {
125
+ var _a, _b, _c;
126
+ super(status, { error: {
127
+ type: "outcome_unknown",
128
+ code: "outcome_unknown",
129
+ message: "Outcome unknown - check before retrying. The change may already have happened; it was not automatically repeated.",
130
+ doc_url: (_a = body == null ? void 0 : body.error) == null ? void 0 : _a.doc_url,
131
+ details: {
132
+ ...(_b = body == null ? void 0 : body.error) == null ? void 0 : _b.details,
133
+ original_code: (_c = body == null ? void 0 : body.error) == null ? void 0 : _c.code,
134
+ outcome: "unknown",
135
+ safe_to_retry: false
136
+ }
137
+ } }, requestId2);
138
+ this.name = "NixflexOutcomeUnknownError";
139
+ }
140
+ };
141
+ var NixflexConflictError = class extends NixflexError {
142
+ constructor(...args) {
143
+ super(...args);
144
+ this.name = "NixflexConflictError";
145
+ }
146
+ };
147
+ var NixflexDoNotContactError = class extends NixflexConflictError {
148
+ constructor(...args) {
149
+ super(...args);
150
+ this.name = "NixflexDoNotContactError";
151
+ }
152
+ };
153
+ function errorFromResponse(status, body, requestId2, retryAfterSeconds, mutation = false) {
154
+ var _a, _b;
155
+ const proof = (_a = body == null ? void 0 : body.error) == null ? void 0 : _a.details;
156
+ const notSent = (proof == null ? void 0 : proof.outcome) === "not_sent" && proof.sent === false && proof.charged === false && proof.safe_to_retry === true;
157
+ if (mutation && (status >= 500 || status >= 300 && status < 400) && !notSent) {
158
+ return new NixflexOutcomeUnknownError(status, body, requestId2);
159
+ }
160
+ if (status === 401) return new NixflexAuthenticationError(status, body, requestId2);
161
+ if (status === 402) return new NixflexPaymentRequiredError(status, body, requestId2);
162
+ if (status === 404) return new NixflexNotFoundError(status, body, requestId2);
163
+ if (status === 409 && ((_b = body == null ? void 0 : body.error) == null ? void 0 : _b.code) === "do_not_contact") return new NixflexDoNotContactError(status, body, requestId2);
164
+ if (status === 409) return new NixflexConflictError(status, body, requestId2);
165
+ if (status === 429) return new NixflexRateLimitError(status, body, requestId2, retryAfterSeconds);
166
+ if (status === 400 || status === 422) return new NixflexInvalidRequestError(status, body, requestId2);
167
+ if (status >= 500) return new NixflexServerError(status, body, requestId2);
168
+ return new NixflexError(status, body, requestId2);
169
+ }
170
+
171
+ // src/request-body.ts
172
+ function encodeRequest(body, options = {}) {
173
+ const headers = { "Content-Type": "application/json" };
174
+ if (options.rawBody !== void 0 && body !== void 0) throw new TypeError("Use JSON body or rawBody, not both.");
175
+ if (options.contentType && options.contentType !== "application/octet-stream") throw new TypeError("Unsupported content type.");
176
+ for (const [key, value] of Object.entries({
177
+ "Idempotency-Key": options.idempotencyKey,
178
+ "X-Filename": options.filename,
179
+ "X-Source-Title": options.sourceTitle
180
+ })) {
181
+ if (value === void 0) continue;
182
+ if (typeof value !== "string" || !value || value.length > 1024 || /[^\x20-\x7e]/.test(value))
183
+ throw new TypeError(`Invalid ${key}; use printable ASCII metadata.`);
184
+ headers[key] = value;
185
+ }
186
+ if (options.review !== void 0) {
187
+ if (typeof options.review !== "boolean") throw new TypeError("review must be boolean.");
188
+ headers["X-Review"] = String(options.review);
189
+ }
190
+ if (options.expectedRevision !== void 0) {
191
+ if (!Number.isSafeInteger(options.expectedRevision) || options.expectedRevision < 0) throw new TypeError("Invalid expectedRevision.");
192
+ headers["X-Expected-Revision"] = String(options.expectedRevision);
193
+ }
194
+ if (options.rawBody !== void 0) {
195
+ if (!(options.rawBody instanceof Uint8Array)) throw new TypeError("rawBody must be bytes.");
196
+ headers["Content-Type"] = "application/octet-stream";
197
+ return { headers, body: options.rawBody };
198
+ }
199
+ return { headers, body: body === void 0 ? void 0 : JSON.stringify(body) };
200
+ }
201
+
202
+ // src/response-stream.ts
203
+ async function* readStream(url, headers, timeout, retries, opts) {
204
+ var _a, _b, _c, _d, _e, _f;
205
+ if (!Number.isFinite(timeout) || timeout <= 0) throw new RangeError("timeoutMs must be positive.");
206
+ let emitted = false;
207
+ for (let attempt = 0; ; attempt++) {
208
+ const controller = new AbortController();
209
+ const abort = () => controller.abort();
210
+ if ((_a = opts == null ? void 0 : opts.signal) == null ? void 0 : _a.aborted) abort();
211
+ (_b = opts == null ? void 0 : opts.signal) == null ? void 0 : _b.addEventListener("abort", abort, { once: true });
212
+ const timer = setTimeout(abort, timeout);
213
+ let reader;
214
+ let response;
215
+ let delay;
216
+ try {
217
+ response = await fetch(url, { method: "GET", redirect: "error", headers, signal: controller.signal });
218
+ if (!response.ok) {
219
+ let body = null;
220
+ try {
221
+ body = await response.json();
222
+ } catch {
223
+ }
224
+ const retryAfter = Math.max(0, parseInt(response.headers.get("retry-after") || "0", 10) || 0);
225
+ if ((response.status === 429 || response.status >= 500) && attempt < retries) {
226
+ delay = response.status === 429 ? Math.min(retryAfter, 30) * 1e3 || 1e3 : 500 * (attempt + 1);
227
+ } else {
228
+ throw errorFromResponse(response.status, body, response.headers.get("x-request-id") || void 0, retryAfter);
229
+ }
230
+ } else {
231
+ if (!/^text\/csv(?:;|$)/i.test(response.headers.get("content-type") || "") || !response.body) {
232
+ throw new NixflexConnectionError("The activity export did not return CSV.");
233
+ }
234
+ reader = response.body.getReader();
235
+ while (true) {
236
+ const chunk = await reader.read();
237
+ if (chunk.done) return;
238
+ if (chunk.value.byteLength) {
239
+ emitted = true;
240
+ yield chunk.value;
241
+ }
242
+ }
243
+ }
244
+ } catch (error) {
245
+ if (error instanceof Error && error.name.startsWith("Nixflex")) throw error;
246
+ if (emitted || ((_c = opts == null ? void 0 : opts.signal) == null ? void 0 : _c.aborted) || attempt >= retries) {
247
+ throw new NixflexConnectionError(emitted ? "Activity export interrupted; discard the incomplete file. It was not restarted." : "Could not read the activity export.");
248
+ }
249
+ delay = 300 * (attempt + 1);
250
+ } finally {
251
+ try {
252
+ if (reader) await reader.cancel();
253
+ else await ((_d = response == null ? void 0 : response.body) == null ? void 0 : _d.cancel());
254
+ } catch {
255
+ }
256
+ controller.abort();
257
+ clearTimeout(timer);
258
+ (_e = opts == null ? void 0 : opts.signal) == null ? void 0 : _e.removeEventListener("abort", abort);
259
+ }
260
+ if ((_f = opts == null ? void 0 : opts.signal) == null ? void 0 : _f.aborted) throw new NixflexConnectionError("Activity export cancelled.");
261
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
262
+ }
263
+ }
264
+
265
+ // src/knowledge/transfer-context.ts
266
+ function transferContext(base, key, version, path2, timeout, retries, options, query) {
267
+ if (!path2.startsWith("/") || path2.startsWith("//") || /[?#\\]/.test(path2)) throw new TypeError("Use a relative API path.");
268
+ const url = new URL(base + "/v1" + path2);
269
+ for (const [name, value] of Object.entries(query || {})) if (value !== void 0) url.searchParams.set(name, value);
270
+ const deadline = (options == null ? void 0 : options.timeoutMs) ?? timeout;
271
+ if (!Number.isFinite(deadline) || deadline <= 0) throw new RangeError("timeoutMs must be positive.");
272
+ return {
273
+ url,
274
+ headers: { Authorization: "Bearer " + key, "User-Agent": "nixflex-node/" + version },
275
+ timeout: deadline,
276
+ retries
277
+ };
278
+ }
279
+ function transferAbort(timeout, signal) {
280
+ const controller = new AbortController();
281
+ const abort = () => controller.abort();
282
+ if (signal == null ? void 0 : signal.aborted) abort();
283
+ signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
284
+ const timer = setTimeout(abort, timeout);
285
+ return { signal: controller.signal, close: () => {
286
+ clearTimeout(timer);
287
+ signal == null ? void 0 : signal.removeEventListener("abort", abort);
288
+ controller.abort();
289
+ } };
290
+ }
291
+
292
+ // src/knowledge/upload.ts
293
+ import { open } from "fs/promises";
294
+ import { basename } from "path";
295
+ import { Transform } from "stream";
296
+ async function uploadFile(ctx, path2, opts = {}) {
297
+ const metadata = encodeRequest(void 0, { ...opts, filename: opts.filename || basename(path2) }).headers;
298
+ const file = await open(path2, "r");
299
+ let source;
300
+ let bounded;
301
+ let deadline;
302
+ try {
303
+ const info = await file.stat();
304
+ if (!info.isFile() || info.size <= 0 || info.size > 10 * 1024 * 1024)
305
+ throw new RangeError("Choose a non-empty regular file up to 10 MiB.");
306
+ if (ctx.url.pathname.endsWith("/replacements") && opts.expectedRevision === void 0)
307
+ throw new TypeError("File replacement requires the source expectedRevision.");
308
+ source = file.createReadStream({ highWaterMark: 64 * 1024, autoClose: false });
309
+ let bytes = 0;
310
+ bounded = new Transform({ transform(chunk, _encoding, done) {
311
+ bytes += chunk.length;
312
+ done(bytes > info.size ? new Error("The upload file changed.") : null, chunk);
313
+ }, flush(done) {
314
+ done(bytes !== info.size ? new Error("The upload file changed.") : null);
315
+ } });
316
+ source.on("error", (error) => bounded == null ? void 0 : bounded.destroy(error));
317
+ source.pipe(bounded);
318
+ deadline = transferAbort(ctx.timeout, opts.signal);
319
+ try {
320
+ const res = await fetch(ctx.url, {
321
+ method: "POST",
322
+ redirect: "error",
323
+ headers: { ...ctx.headers, ...metadata, "Content-Type": "application/octet-stream", "Content-Length": String(info.size) },
324
+ body: bounded,
325
+ signal: deadline.signal,
326
+ duplex: "half"
327
+ });
328
+ let data = null;
329
+ try {
330
+ data = await res.json();
331
+ } catch {
332
+ if (res.ok) throw new NixflexOutcomeUnknownError(res.status);
333
+ }
334
+ if (!res.ok) throw errorFromResponse(
335
+ res.status,
336
+ data,
337
+ res.headers.get("x-request-id") || void 0,
338
+ Number(res.headers.get("retry-after")) || 0,
339
+ true
340
+ );
341
+ return data;
342
+ } catch (error) {
343
+ if (error instanceof NixflexError) throw error;
344
+ throw new NixflexOutcomeUnknownError();
345
+ }
346
+ } finally {
347
+ deadline == null ? void 0 : deadline.close();
348
+ source == null ? void 0 : source.destroy();
349
+ bounded == null ? void 0 : bounded.destroy();
350
+ await file.close();
351
+ }
352
+ }
353
+
354
+ // src/knowledge/download.ts
355
+ async function* download(ctx, opts) {
356
+ var _a, _b, _c;
357
+ let emitted = false;
358
+ for (let attempt = 0; ; attempt++) {
359
+ const deadline = transferAbort(ctx.timeout, opts == null ? void 0 : opts.signal);
360
+ let response, reader;
361
+ let delay = 300 * (attempt + 1);
362
+ try {
363
+ response = await fetch(ctx.url, {
364
+ method: "GET",
365
+ redirect: "error",
366
+ signal: deadline.signal,
367
+ headers: { ...ctx.headers, Accept: "application/json" }
368
+ });
369
+ if (!response.ok) {
370
+ let data = null;
371
+ try {
372
+ data = await response.json();
373
+ } catch {
374
+ }
375
+ if ((response.status === 429 || response.status >= 500) && attempt < ctx.retries) {
376
+ delay = response.status === 429 ? Math.min(30, Math.max(0, Number(response.headers.get("retry-after")) || 1)) * 1e3 : 500 * (attempt + 1);
377
+ } else throw errorFromResponse(response.status, data, response.headers.get("x-request-id") || void 0, 0);
378
+ } else {
379
+ if (!/^application\/json(?:;|$)/i.test(response.headers.get("content-type") || "") || !response.body)
380
+ throw new NixflexConnectionError("The knowledge export did not return JSON.");
381
+ reader = response.body.getReader();
382
+ while (true) {
383
+ const item = await reader.read();
384
+ if (item.done) return;
385
+ if (item.value.byteLength) {
386
+ emitted = true;
387
+ yield item.value;
388
+ }
389
+ }
390
+ }
391
+ } catch (error) {
392
+ if (error instanceof NixflexError) throw error;
393
+ if (emitted || ((_a = opts == null ? void 0 : opts.signal) == null ? void 0 : _a.aborted) || attempt >= ctx.retries)
394
+ throw new NixflexConnectionError("Knowledge download interrupted. Discard any partial file; it was not restarted.");
395
+ } finally {
396
+ try {
397
+ if (reader) await reader.cancel();
398
+ else await ((_b = response == null ? void 0 : response.body) == null ? void 0 : _b.cancel());
399
+ } catch {
400
+ }
401
+ deadline.close();
402
+ }
403
+ if ((_c = opts == null ? void 0 : opts.signal) == null ? void 0 : _c.aborted) throw new NixflexConnectionError("Knowledge download cancelled.");
404
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
405
+ }
406
+ }
407
+
408
+ // src/content-delete.ts
409
+ function contentDeleteId(id) {
410
+ if (typeof id !== "string" || !id.length || id.length > 200 || id === "." || id === ".." || /[\x00-\x1f\x7f]/.test(id)) {
411
+ throw new TypeError("Choose a valid call or campaign identifier. Nothing was sent.");
412
+ }
413
+ return encodeURIComponent(id);
414
+ }
415
+ function queuedContentDelete(method, path2, status, body, requestId2) {
416
+ const route = /^\/(?:calls\/batch|sms\/campaigns|calls)\/[^/]+$/.test(path2);
417
+ const error = body == null ? void 0 : body.error, proof = error == null ? void 0 : error.details;
418
+ if (method === "DELETE" && route && status === 503 && (error == null ? void 0 : error.code) === "hangup_pending" && error.type === "server_error" && typeof error.message === "string" && (proof == null ? void 0 : proof.deleted) === false && proof.retry_pending === true) {
419
+ return new NixflexServerError(status, body, requestId2);
420
+ }
421
+ return void 0;
88
422
  }
89
423
 
90
424
  // src/client.ts
425
+ var SDK_VERSION = "0.11.1";
91
426
  var DEFAULT_BASE_URL = "https://api.nixflex.com";
92
427
  var DEFAULT_TIMEOUT_MS = 3e4;
93
- var SDK_VERSION = "0.8.0";
94
428
  var HttpClient = class {
429
+ knowledgeUpload(path2, file, opts) {
430
+ return uploadFile(transferContext(this.baseUrl, this.apiKey, SDK_VERSION, path2, this.timeoutMs, this.maxRetries, opts), file, opts);
431
+ }
432
+ knowledgeDownload(path2, query = {}, opts) {
433
+ return download(transferContext(this.baseUrl, this.apiKey, SDK_VERSION, path2, this.timeoutMs, this.maxRetries, opts, query), opts);
434
+ }
95
435
  apiKey;
96
436
  baseUrl;
97
437
  timeoutMs;
98
438
  maxRetries;
439
+ /** Streaming GET for activity CSV. No retry after the first returned byte. */
440
+ stream(path2, query, opts) {
441
+ if (!path2.startsWith("/") || path2.startsWith("//") || /[?#\\]/.test(path2)) throw new TypeError("Use a relative API path.");
442
+ const url = new URL(this.baseUrl + "/v1" + path2);
443
+ for (const [key, value] of Object.entries(query)) if (value !== void 0) url.searchParams.set(key, value);
444
+ return readStream(
445
+ url,
446
+ { Authorization: `Bearer ${this.apiKey}`, Accept: "text/csv", "User-Agent": `nixflex-node/${SDK_VERSION}` },
447
+ (opts == null ? void 0 : opts.timeoutMs) ?? this.timeoutMs,
448
+ this.maxRetries,
449
+ opts
450
+ );
451
+ }
99
452
  constructor(opts) {
100
453
  if (!opts || typeof opts.apiKey !== "string" || !opts.apiKey.includes(":")) {
101
454
  throw new Error(
@@ -105,16 +458,21 @@ var HttpClient = class {
105
458
  this.apiKey = opts.apiKey;
106
459
  this.baseUrl = (opts.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
107
460
  this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
108
- this.maxRetries = opts.maxRetries ?? 1;
461
+ this.maxRetries = Math.min(opts.maxRetries ?? 1, 3);
462
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0 || this.maxRetries > 3) throw new RangeError("maxRetries must be 0..3.");
463
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0) throw new RangeError("timeoutMs must be positive.");
109
464
  }
110
- async request(method, path, body, query, reqOpts) {
111
- const url = new URL(this.baseUrl + "/v1" + path);
465
+ async request(method, path2, body, query, reqOpts) {
466
+ const url = new URL(this.baseUrl + "/v1" + path2);
112
467
  if (query) {
113
468
  for (const [k, v] of Object.entries(query)) {
114
469
  if (v !== void 0 && v !== null) url.searchParams.set(k, String(v));
115
470
  }
116
471
  }
117
- const isIdempotent = method === "GET" || method === "DELETE";
472
+ if (!path2.startsWith("/") || path2.startsWith("//") || /[?#\\]/.test(path2)) throw new TypeError("Use a relative API path and the query argument.");
473
+ encodeRequest(body, reqOpts);
474
+ if ((reqOpts == null ? void 0 : reqOpts.timeoutMs) !== void 0 && (!Number.isFinite(reqOpts.timeoutMs) || reqOpts.timeoutMs <= 0)) throw new RangeError("timeoutMs must be positive.");
475
+ const isRead = method === "GET";
118
476
  let attempt = 0;
119
477
  while (true) {
120
478
  attempt++;
@@ -122,19 +480,29 @@ var HttpClient = class {
122
480
  try {
123
481
  res = await this.fetchWithTimeout(url.toString(), method, body, reqOpts);
124
482
  } catch (err) {
483
+ if (!isRead) throw new NixflexOutcomeUnknownError();
125
484
  if (attempt <= this.maxRetries) {
126
485
  await sleep(300 * attempt);
127
486
  continue;
128
487
  }
129
488
  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`
489
+ "Could not reach the Nixflex API. Check connectivity and https://nixflex.com/status"
131
490
  );
132
491
  }
133
492
  if (res.ok) {
134
493
  if (res.status === 204) return void 0;
135
- return await res.json();
494
+ try {
495
+ return await res.json();
496
+ } catch {
497
+ if (!isRead) throw new NixflexOutcomeUnknownError(
498
+ res.status,
499
+ null,
500
+ res.headers.get("x-request-id") || res.headers.get("x-railway-request-id") || void 0
501
+ );
502
+ throw new NixflexConnectionError("The API read returned an incomplete or invalid JSON reply.");
503
+ }
136
504
  }
137
- const requestId = res.headers.get("x-railway-request-id") || void 0;
505
+ const requestId2 = res.headers.get("x-request-id") || res.headers.get("x-railway-request-id") || void 0;
138
506
  const retryAfter = parseInt(res.headers.get("retry-after") || "0", 10) || 0;
139
507
  let errBody = null;
140
508
  try {
@@ -142,13 +510,13 @@ var HttpClient = class {
142
510
  } catch {
143
511
  }
144
512
  const retryable429 = res.status === 429;
145
- const retryable5xx = res.status >= 500 && isIdempotent;
146
- if ((retryable429 || retryable5xx) && attempt <= this.maxRetries) {
513
+ const retryable5xx = res.status >= 500;
514
+ if (isRead && (retryable429 || retryable5xx) && attempt <= this.maxRetries) {
147
515
  const waitMs = retryable429 ? Math.min(retryAfter, 30) * 1e3 || 1e3 : 500 * attempt;
148
516
  await sleep(waitMs);
149
517
  continue;
150
518
  }
151
- throw errorFromResponse(res.status, errBody, requestId, retryAfter);
519
+ throw queuedContentDelete(method, path2, res.status, errBody, requestId2) ?? errorFromResponse(res.status, errBody, requestId2, retryAfter, !isRead);
152
520
  }
153
521
  }
154
522
  async fetchWithTimeout(url, method, body, reqOpts) {
@@ -160,16 +528,19 @@ var HttpClient = class {
160
528
  else reqOpts.signal.addEventListener("abort", () => controller.abort(reqOpts.signal.reason), { once: true });
161
529
  }
162
530
  try {
163
- return await fetch(url, {
531
+ const res = await fetch(url, {
164
532
  method,
533
+ redirect: "error",
165
534
  headers: {
166
535
  Authorization: `Bearer ${this.apiKey}`,
167
- "Content-Type": "application/json",
536
+ ...encodeRequest(body, reqOpts).headers,
168
537
  "User-Agent": `nixflex-node/${SDK_VERSION}`
169
538
  },
170
- body: body === void 0 ? void 0 : JSON.stringify(body),
539
+ body: encodeRequest(body, reqOpts).body,
171
540
  signal: controller.signal
172
541
  });
542
+ const bytes = res.status === 204 ? null : await res.arrayBuffer();
543
+ return new Response(bytes, { status: res.status, statusText: res.statusText, headers: res.headers });
173
544
  } finally {
174
545
  clearTimeout(timer);
175
546
  }
@@ -190,14 +561,17 @@ var Agents = class {
190
561
  create(params = {}, opts) {
191
562
  return this.http.request("POST", "/agents", params, void 0, opts);
192
563
  }
193
- /** List active agents, newest first. Default 100, hard cap 200 per page. */
564
+ /** Bare array. Active by default; stable created_at DESC, agent_id DESC order. */
194
565
  list(params = {}, opts) {
195
- return this.http.request("GET", "/agents", void 0, { limit: params.limit, offset: params.offset }, opts);
566
+ return this.http.request("GET", "/agents", void 0, { limit: params.limit, offset: params.offset, status: params.status, search: params.search }, opts);
196
567
  }
197
- /** Iterate ALL agents across pages: `for await (const a of client.agents.iter()) { ... }` */
568
+ /** Iterate active agents across pages. pageSize must be a whole number 1..200.
569
+ * Offset pages are not a snapshot: concurrent creates/disables can shift rows. */
198
570
  async *iter(pageSize = 100, opts) {
571
+ if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 200) throw new RangeError("Agent pageSize must be a whole number from 1 to 200.");
199
572
  let offset = 0;
200
573
  while (true) {
574
+ if (offset > 1e6) throw new RangeError("Agent iteration exceeds the maximum offset of 1000000.");
201
575
  const page = await this.list({ limit: pageSize, offset }, opts);
202
576
  for (const item of page) yield item;
203
577
  if (page.length < pageSize) return;
@@ -210,40 +584,198 @@ var Agents = class {
210
584
  }
211
585
  /** Update an agent. Send ONLY the fields you want to change - omitted fields
212
586
  * keep their values. Active calls are unaffected; new calls use the new config.
213
- * Unknown field names return 200 and change nothing - check spelling. */
587
+ * Empty/unknown-only updates fail; mixed unknown keys return warnings. */
214
588
  update(agentId, params, opts) {
215
589
  return this.http.request("PUT", `/agents/${encodeURIComponent(agentId)}`, params, void 0, opts);
216
590
  }
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. */
591
+ /** Soft disable only (is_active=false). Does not detach numbers or erase history.
592
+ * The legacy response message is "Agent deleted". */
220
593
  delete(agentId, opts) {
221
594
  return this.http.request("DELETE", `/agents/${encodeURIComponent(agentId)}`, void 0, void 0, opts);
222
595
  }
223
596
  };
224
597
 
598
+ // src/call-requests.ts
599
+ import { randomUUID } from "crypto";
600
+
601
+ // src/call-request-errors.ts
602
+ var NixflexOutboundRequestError = class extends NixflexError {
603
+ };
604
+ var NixflexOutboundRequestPendingError = class extends NixflexOutboundRequestError {
605
+ };
606
+ var NixflexOutboundRequestUnknownError = class extends NixflexOutboundRequestError {
607
+ };
608
+ var NixflexRequestIdConflictError = class extends NixflexOutboundRequestError {
609
+ };
610
+ var NixflexOutboundRequestUnavailableError = class extends NixflexOutboundRequestError {
611
+ };
612
+ var NixflexCallBookingsUnavailableError = class extends NixflexError {
613
+ };
614
+ var classes = {
615
+ outbound_request_pending: NixflexOutboundRequestPendingError,
616
+ outbound_request_unknown: NixflexOutboundRequestUnknownError,
617
+ request_id_conflict: NixflexRequestIdConflictError,
618
+ outbound_request_unavailable: NixflexOutboundRequestUnavailableError
619
+ };
620
+ function outboundRequestError(value, requestId2, mutation) {
621
+ const e = value, raw = (e == null ? void 0 : e.details) || {};
622
+ const status = Number.isInteger(e == null ? void 0 : e.status) && e.status >= 0 && e.status <= 599 ? e.status : 0;
623
+ const original = (e == null ? void 0 : e.code) === "outcome_unknown" ? raw.original_code : e == null ? void 0 : e.code;
624
+ const code = typeof original === "string" && /^[a-z][a-z0-9_]{0,79}$/.test(original) && !["unknown_error", "invalid_response"].includes(original) ? original : mutation ? "outbound_request_unknown" : "outbound_request_unavailable";
625
+ const details = { request_id: requestId2 };
626
+ if (["pending", "accepted", "rejected", "unknown"].includes(String(raw.state))) details.state = raw.state;
627
+ if (mutation) {
628
+ details.safe_to_retry = false;
629
+ if (!details.state && (status === 0 || code === "outbound_request_unknown")) details.state = "unknown";
630
+ }
631
+ const type = {
632
+ 400: "invalid_request",
633
+ 422: "invalid_request",
634
+ 401: "authentication_error",
635
+ 402: "payment_required",
636
+ 403: "permission_denied",
637
+ 404: "not_found",
638
+ 409: "conflict",
639
+ 429: "rate_limit"
640
+ }[status] || (status >= 500 ? "server_error" : status === 0 && mutation ? "outcome_unknown" : "error");
641
+ const ErrorClass = classes[code] || NixflexOutboundRequestError;
642
+ const result = new ErrorClass(status, { error: {
643
+ type,
644
+ code,
645
+ message: mutation ? "Call request not confirmed. Keep this request_id; check its status and Call History before any manual retry. No automatic repeat." : "Call request status could not be read. Check the error code; this read placed no call.",
646
+ details
647
+ } });
648
+ result.name = ErrorClass.name;
649
+ return result;
650
+ }
651
+
652
+ // src/call-request-projection.ts
653
+ var requestUuid = (v) => typeof v === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v);
654
+ function requestId(value) {
655
+ if (!requestUuid(value)) throw new TypeError("request_id must be a UUID. No request sent.");
656
+ return value;
657
+ }
658
+ function callIdentifier(value) {
659
+ if (typeof value !== "string" || !value || value.length > 200 || [".", ".."].includes(value) || /[\u0000-\u001f]/.test(value))
660
+ throw new TypeError("call_id must be an existing call identifier. No request sent.");
661
+ return value;
662
+ }
663
+ var invalid = () => {
664
+ throw new NixflexConnectionError("Invalid call result shape. No result was inferred.");
665
+ };
666
+ var object = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : invalid();
667
+ var nullable = (v) => v === null || typeof v === "string";
668
+ var appointment = ["start", "end", "attendee_name", "attendee_email", "service", "timezone"];
669
+ function row(value, final) {
670
+ const v = object(value), fields = final ? ["booking_uid", "status", ...appointment] : ["action", "booking_uid", ...appointment, "at"];
671
+ if (typeof v.booking_uid !== "string" || !v.booking_uid || appointment.some((k) => k === "service" ? !(nullable(v[k]) || typeof v[k] === "number" && Number.isFinite(v[k])) : !nullable(v[k])) || (final ? !["active", "cancelled"].includes(v.status) : !["created", "rescheduled", "cancelled"].includes(v.action) || typeof v.at !== "string")) invalid();
672
+ return Object.fromEntries(fields.map((k) => [k, v[k]]));
673
+ }
674
+ function callBookings(value, id) {
675
+ const v = object(value);
676
+ if (v.call_id !== id || !["ready", "none", "processing", "deleted", "unavailable"].includes(v.state)) invalid();
677
+ if (v.state !== "ready") {
678
+ if (v.result !== null) invalid();
679
+ return { call_id: id, state: v.state, result: null };
680
+ }
681
+ const r = object(v.result), fields = ["event", "call_id", "agent_id", "from", "to", "number", "ended_at"];
682
+ if (r.event !== "call.bookings" || r.call_id !== id || fields.slice(2).some((k) => !nullable(r[k])) || !Array.isArray(r.timeline) || !r.timeline.length || !Array.isArray(r.final) || !r.final.length) invalid();
683
+ return { call_id: id, state: "ready", result: {
684
+ ...Object.fromEntries(fields.map((k) => [k, r[k]])),
685
+ timeline: r.timeline.map((v2) => row(v2, false)),
686
+ final: r.final.map((v2) => row(v2, true))
687
+ } };
688
+ }
689
+ function outboundRequest(value, id) {
690
+ const v = object(value);
691
+ if (typeof v.request_id !== "string" || v.request_id.toLowerCase() !== id.toLowerCase() || !["pending", "accepted", "rejected", "unknown"].includes(v.state) || !nullable(v.call_id) || !nullable(v.reason) || v.state === "accepted" && !v.call_id) invalid();
692
+ return { request_id: v.request_id, state: v.state, call_id: v.call_id, reason: v.reason };
693
+ }
694
+
695
+ // src/call-requests.ts
696
+ function prepareOutboundCall(params) {
697
+ const id = params.request_id === void 0 ? randomUUID() : requestId(params.request_id);
698
+ return { ...JSON.parse(JSON.stringify(params)), request_id: id };
699
+ }
700
+ async function createOutboundRequest(http, params, opts) {
701
+ const id = requestId(params.request_id);
702
+ try {
703
+ const value = await http.request("POST", "/calls/outbound", params, void 0, opts);
704
+ if (!value || typeof value.call_id !== "string" || !value.call_id || value.call_id.length > 200 || /[\u0000-\u0020]/.test(value.call_id) || value.status !== "initiated" || typeof value.request_id !== "string" || value.request_id.toLowerCase() !== id.toLowerCase() || value.replayed !== void 0 && value.replayed !== true || value.request_status !== void 0 && (value.request_status !== "unconfirmed" || value.safe_to_retry !== false) || value.safe_to_retry !== void 0 && value.safe_to_retry !== false) throw new NixflexConnectionError("Invalid acceptance receipt.");
705
+ return value;
706
+ } catch (e) {
707
+ throw outboundRequestError(e, id, true);
708
+ }
709
+ }
710
+ async function readCallBookings(http, id, opts) {
711
+ callIdentifier(id);
712
+ try {
713
+ return callBookings(await http.request("GET", `/calls/${encodeURIComponent(id)}/bookings`, void 0, void 0, opts), id);
714
+ } catch (e) {
715
+ if (!(e instanceof NixflexError) || e.code !== "call_bookings_unavailable") throw e;
716
+ const result = new NixflexCallBookingsUnavailableError(e.status, { error: {
717
+ type: e.type,
718
+ code: e.code,
719
+ message: "The booking result could not be checked. This does not mean no booking was made.",
720
+ details: {}
721
+ } });
722
+ result.name = "NixflexCallBookingsUnavailableError";
723
+ throw result;
724
+ }
725
+ }
726
+ async function readOutboundRequest(http, id, opts) {
727
+ requestId(id);
728
+ try {
729
+ return outboundRequest(await http.request("GET", `/calls/outbound/requests/${encodeURIComponent(id)}`, void 0, void 0, opts), id);
730
+ } catch (e) {
731
+ if (e instanceof NixflexError && e.code === "outbound_request_unavailable") throw outboundRequestError(e, id, false);
732
+ throw e;
733
+ }
734
+ }
735
+
225
736
  // src/resources/calls.ts
226
737
  var Calls = class {
227
738
  constructor(http) {
228
739
  this.http = http;
229
740
  }
230
741
  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). */
742
+ /** Generate a UUID locally before sending; save and reuse the returned body unchanged. */
743
+ prepare(params) {
744
+ return prepareOutboundCall(params);
745
+ }
746
+ bookings(callId, opts) {
747
+ return readCallBookings(this.http, callId, opts);
748
+ }
749
+ outboundRequest(requestId2, opts) {
750
+ return readOutboundRequest(this.http, requestId2, opts);
751
+ }
236
752
  create(params, opts) {
753
+ if (params.request_id !== void 0) return createOutboundRequest(this.http, params, opts);
237
754
  return this.http.request("POST", "/calls/outbound", params, void 0, opts);
238
755
  }
239
756
  /** List calls, newest first. Default 50, hard cap 200. The response is a
240
757
  * 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. */
758
+ * for within the 200 cap (or use iter()). Availability depends on retention. */
242
759
  list(params = {}, opts) {
760
+ if ("agent_id" in params) throw new TypeError("Legacy calls.list does not filter by agent; use calls.history({agent: id}).");
243
761
  return this.http.request("GET", "/calls", void 0, { limit: params.limit, offset: params.offset }, opts);
244
762
  }
245
- /** Iterate ALL calls across pages: `for await (const c of client.calls.iter()) { ... }` */
763
+ /** Dashboard-style filtered metadata, totals and stable cursor order. Not a frozen database snapshot. */
764
+ history(params = {}, opts) {
765
+ return this.http.request("GET", "/calls/history", void 0, { ...params }, opts);
766
+ }
767
+ /** Explicit nullable detail, failed-start and retained stubs; no raw storage URL. */
768
+ read(callId, opts) {
769
+ return this.http.request("GET", `/calls/${encodeURIComponent(callId)}`, void 0, { view: "detail" }, opts);
770
+ }
771
+ /** Managed-storage link: use expires_at, never a hardcoded lifetime, or a truthful non-downloadable state. Never reads BYO storage. */
772
+ recording(callId, opts) {
773
+ return this.http.request("GET", `/calls/${encodeURIComponent(callId)}/recording`, void 0, void 0, opts);
774
+ }
775
+ /** Iterate calls across pages. pageSize must be a whole number 1..200.
776
+ * Offset pages are not a snapshot: concurrent changes can shift rows. */
246
777
  async *iter(pageSize = 100, opts) {
778
+ if (!Number.isInteger(pageSize) || pageSize < 1 || pageSize > 200) throw new RangeError("Call pageSize must be a whole number from 1 to 200.");
247
779
  let offset = 0;
248
780
  while (true) {
249
781
  const page = await this.list({ limit: pageSize, offset }, opts);
@@ -253,19 +785,20 @@ var Calls = class {
253
785
  }
254
786
  }
255
787
  /** Fetch one call: transcript, recording URL, post-call analysis. Note:
256
- * duration_ms is time CONNECTED (what you are billed on) - ring time is
788
+ * duration_ms is time CONNECTED (not necessarily AI billed time) - ring time is
257
789
  * excluded, so it will not equal end_timestamp - start_timestamp on
258
790
  * outbound calls. */
259
791
  get(callId, opts) {
260
792
  return this.http.request("GET", `/calls/${encodeURIComponent(callId)}`, void 0, void 0, opts);
261
793
  }
262
- /** GDPR: PERMANENTLY erase one call - the record AND its recording file.
263
- * Irreversible. Throws NixflexNotFoundError if the ID is not yours. */
794
+ /** End a running call, then delete its content. 503 hangup_pending with
795
+ * retry_pending:true means queued, not deleted. Recording cleanup may remain
796
+ * queued or carrier best effort. One DELETE; never automatically repeated. */
264
797
  delete(callId, opts) {
265
- return this.http.request("DELETE", `/calls/${encodeURIComponent(callId)}`, void 0, void 0, opts);
798
+ return this.http.request("DELETE", `/calls/${contentDeleteId(callId)}`, void 0, void 0, opts);
266
799
  }
267
- /** GDPR: PERMANENTLY erase ALL calls, recordings, and SMS messages on this
268
- * key. Irreversible - intended for data-erasure requests and offboarding. */
800
+ /** Request guarded call cleanup, not account/SMS erasure. Safety holds can
801
+ * refuse it; legacy recording counters are not proof of every copy's erasure. */
269
802
  deleteAll(opts) {
270
803
  return this.http.request("DELETE", "/calls", void 0, void 0, opts);
271
804
  }
@@ -275,21 +808,164 @@ var Campaigns = class {
275
808
  this.http = http;
276
809
  }
277
810
  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. */
811
+ /** Cancel waiting work, end running calls and hide the campaign. History and used
812
+ * charges remain; no refund. Owner/Admin only. 503 hangup_pending is queued.
813
+ * Missing/foreign is 404. One DELETE; never automatically repeated. */
814
+ delete(id, opts) {
815
+ return this.http.request("DELETE", `/calls/batch/${contentDeleteId(id)}`, void 0, void 0, opts);
816
+ }
817
+ cancel(id, opts) {
818
+ return this.http.request("POST", `/calls/batch/${encodeURIComponent(id)}/cancel`, void 0, void 0, opts);
819
+ }
820
+ consent(id, params, opts) {
821
+ return this.http.request("POST", `/calls/batch/${encodeURIComponent(id)}/consent`, params, void 0, opts);
822
+ }
823
+ resume(id, opts) {
824
+ return this.http.request("POST", `/calls/batch/${encodeURIComponent(id)}/resume`, void 0, void 0, opts);
825
+ }
826
+ list(params = {}, opts) {
827
+ return this.http.request("GET", "/campaigns", void 0, { ...params }, opts);
828
+ }
829
+ /** Create executable work, not a draft. The default requests immediate launch; scheduled work can start automatically. Each dispatch still checks consent and local hours. */
283
830
  create(params, opts) {
284
831
  return this.http.request("POST", "/calls/batch", params, void 0, opts);
285
832
  }
286
- /** Launch a scheduled campaign immediately, overriding its schedule.
287
- * Already running = no-op returning current status. */
833
+ /** Request launch; it does not bypass recipient checks or prove delivery. Never auto-retried. */
288
834
  launch(campaignId, opts) {
289
835
  return this.http.request("POST", `/calls/batch/${encodeURIComponent(campaignId)}/launch`, void 0, void 0, opts);
290
836
  }
291
837
  };
292
838
 
839
+ // src/feature-errors.ts
840
+ var calendarErrorCodes = [
841
+ "invalid_return_url",
842
+ "number_not_found",
843
+ "already_connected",
844
+ "booking_provider_conflict",
845
+ "not_connected",
846
+ "agent_not_assigned",
847
+ "invalid_settings",
848
+ "invalid_timezone",
849
+ "invalid_hours",
850
+ "invalid_slot_minutes",
851
+ "invalid_calendar_id",
852
+ "invalid_send_invites",
853
+ "calendar_unavailable",
854
+ "expired_link",
855
+ "not_configured",
856
+ "guard_unavailable"
857
+ ];
858
+ var credentialErrorCodes = [
859
+ "invalid_request",
860
+ "invalid_credentials",
861
+ "number_not_in_account",
862
+ "number_not_found",
863
+ "carrier_mismatch",
864
+ "account_unavailable",
865
+ "number_operation_pending",
866
+ "number_release_pending",
867
+ "carrier_unavailable",
868
+ "credential_update_unavailable",
869
+ "carrier_outcome_unknown",
870
+ "credential_save_pending"
871
+ ];
872
+ var common = [
873
+ "unauthorized",
874
+ "invalid_api_key",
875
+ "permission_denied",
876
+ "forbidden",
877
+ "rate_limit_exceeded",
878
+ "organisation_disabled",
879
+ "organisation_unavailable",
880
+ "account_closed",
881
+ "account_inactive",
882
+ "outcome_unknown"
883
+ ];
884
+ var NixflexCalendarError = class extends NixflexError {
885
+ };
886
+ var NixflexCredentialError = class extends NixflexError {
887
+ };
888
+ function featureError(value, kind, mutation) {
889
+ var _a, _b;
890
+ const e = value;
891
+ const status = Number.isInteger(e == null ? void 0 : e.status) && e.status >= 0 && e.status <= 599 ? e.status : 0;
892
+ const original = (e == null ? void 0 : e.code) === "outcome_unknown" ? (_a = e.details) == null ? void 0 : _a.original_code : e == null ? void 0 : e.code;
893
+ const allowed = kind === "calendar" ? calendarErrorCodes : credentialErrorCodes;
894
+ const code = typeof original === "string" && (allowed.includes(original) || common.includes(original)) ? original : (e == null ? void 0 : e.code) === "outcome_unknown" ? "outcome_unknown" : "request_failed";
895
+ const uncertain = mutation && ((e == null ? void 0 : e.code) === "outcome_unknown" || status === 0 || status >= 500 || status >= 300 && status < 400);
896
+ const details = uncertain ? { outcome: "unknown", safe_to_retry: false } : {};
897
+ if (/^[a-f0-9-]{36}$/i.test(String(((_b = e == null ? void 0 : e.details) == null ? void 0 : _b.operation_id) || ""))) details.operation_id = e.details.operation_id;
898
+ const type = status === 400 || status === 422 ? "invalid_request" : status === 409 ? "conflict" : status === 404 ? "not_found" : status === 401 ? "authentication_error" : status === 403 ? "permission_denied" : status === 429 ? "rate_limit" : status >= 500 ? "server_error" : uncertain ? "outcome_unknown" : "error";
899
+ let message = kind === "calendar" ? "Google Calendar request failed. Check status and code." : "Carrier details update failed. Check status and code.";
900
+ if (code === "carrier_outcome_unknown") message = "Carrier routing is unconfirmed. Contact support before retrying.";
901
+ else if (code === "credential_save_pending") message = "Carrier change succeeded; saving is pending. Retry manually with exactly the same details to finish saving.";
902
+ else if (uncertain) message += " Outcome is unconfirmed; check before retrying. No automatic repeat.";
903
+ const ErrorClass = kind === "calendar" ? NixflexCalendarError : NixflexCredentialError;
904
+ const result = new ErrorClass(status, { error: { type, code, message, details } });
905
+ result.name = kind === "calendar" ? "NixflexCalendarError" : "NixflexCredentialError";
906
+ if (uncertain) Object.assign(result, { outcome: "unknown", safe_to_retry: false });
907
+ return result;
908
+ }
909
+
910
+ // src/number-features.ts
911
+ async function numberFeature(http, method, path2, body, kind, opts) {
912
+ try {
913
+ return await http.request(method, path2, body, void 0, opts);
914
+ } catch (e) {
915
+ throw featureError(e, kind, method !== "GET");
916
+ }
917
+ }
918
+ var calendarPath = (number) => `/integrations/google-calendar/number/${encodeURIComponent(number)}`;
919
+ function credentialPair(body) {
920
+ const keys = body && typeof body === "object" ? Object.keys(body) : [];
921
+ const fields = keys.includes("twilio_sid") ? ["twilio_sid", "twilio_token"] : ["telnyx_api_key", "telnyx_connection_id"];
922
+ const values = body;
923
+ if (keys.length !== 2 || keys.some((k) => !fields.includes(k)) || fields.some((k) => typeof values[k] !== "string" || !values[k].trim() || values[k].length > 4096 || /[\r\n\x00]/.test(values[k])))
924
+ throw new TypeError("Supply exactly one complete carrier credential pair privately.");
925
+ const clean = Object.fromEntries(fields.map((k) => [k, values[k].trim()]));
926
+ if (fields[0] === "twilio_sid" ? !/^AC[a-f0-9]{32}$/i.test(clean.twilio_sid) : clean.telnyx_connection_id.length > 200)
927
+ throw new TypeError("Invalid carrier credential format.");
928
+ return clean;
929
+ }
930
+ async function updateCredentials(http, number, body, opts) {
931
+ const result = await numberFeature(http, "POST", `/phone-numbers/${encodeURIComponent(number)}/credentials`, credentialPair(body), "credentials", opts);
932
+ if (!result || result.updated !== true || result.phone_number !== number || result.provider !== ("twilio_sid" in body ? "twilio" : "telnyx"))
933
+ throw featureError({ status: 0 }, "credentials", true);
934
+ return { phone_number: result.phone_number, provider: result.provider, updated: true };
935
+ }
936
+
937
+ // src/sms-campaign-input.ts
938
+ function smsCampaignInput(input) {
939
+ const data = { ...input };
940
+ for (const [alias, field] of [["message", "message_template"], ["scheduled_at", "scheduled_date"]]) {
941
+ if (Object.prototype.hasOwnProperty.call(data, alias)) {
942
+ if (Object.prototype.hasOwnProperty.call(data, field)) throw new TypeError(`Use ${alias} or ${field}, not both.`);
943
+ data[field] = data[alias];
944
+ delete data[alias];
945
+ }
946
+ }
947
+ return data;
948
+ }
949
+
950
+ // src/resources/number-usage.ts
951
+ function readNumberUsage(http, phone, params = {}, opts) {
952
+ return http.request(
953
+ "GET",
954
+ `/phone-numbers/${encodeURIComponent(phone)}/usage`,
955
+ void 0,
956
+ { period: params.period, time_zone: params.time_zone },
957
+ opts
958
+ );
959
+ }
960
+
961
+ // src/resources/number-move.ts
962
+ function moveNumber(http, number, params, opts) {
963
+ if (Object.keys(params).length !== 1 || typeof params.agent_id !== "string" || !params.agent_id.trim()) {
964
+ throw new Error("Send only agent_id when moving a number. Update other settings separately.");
965
+ }
966
+ return http.request("PATCH", `/phone-numbers/${encodeURIComponent(number)}`, params, void 0, opts);
967
+ }
968
+
293
969
  // src/webhook-verify.ts
294
970
  import { createHmac, timingSafeEqual } from "crypto";
295
971
  function verifyWebhookSignature(rawBody, signatureHeader, keySecret, options = {}) {
@@ -326,6 +1002,13 @@ var PhoneNumbers = class {
326
1002
  this.http = http;
327
1003
  }
328
1004
  http;
1005
+ updateCredentials(phoneNumber, body, opts) {
1006
+ return updateCredentials(this.http, phoneNumber, body, opts);
1007
+ }
1008
+ /** Retained-history usage, not a billing ledger. Defaults: all, UTC. */
1009
+ usage(phoneNumber, params = {}, opts) {
1010
+ return readNumberUsage(this.http, phoneNumber, params, opts);
1011
+ }
329
1012
  /** Attach a number you already own. Carrier inferred from credentials
330
1013
  * (twilio_sid+twilio_token OR telnyx_api_key+telnyx_connection_id).
331
1014
  * WARNING: Twilio import REPLACES the number's existing webhooks - another
@@ -333,35 +1016,32 @@ var PhoneNumbers = class {
333
1016
  import(params, opts) {
334
1017
  return this.http.request("POST", "/phone-numbers", params, void 0, opts);
335
1018
  }
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. */
1019
+ /** Owned public numbers, newest first. Opt into paging with limit/cursor.
1020
+ * count is returned rows. Without paging, the server's row cap still applies. */
338
1021
  list(params = {}, opts) {
339
- return this.http.request("GET", "/phone-numbers", void 0, { agent_id: params.agent_id }, opts);
1022
+ return this.http.request("GET", "/phone-numbers", void 0, { agent_id: params.agent_id, provider: params.provider, limit: params.limit, cursor: params.cursor }, opts);
1023
+ }
1024
+ /** Saved safe settings, effective website voice switch, and safe key status. */
1025
+ get(phoneNumber, opts) {
1026
+ return this.http.request("GET", `/phone-numbers/${enc(phoneNumber)}`, void 0, void 0, opts);
340
1027
  }
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
1028
  update(phoneNumber, params, opts) {
1029
+ if ("agent_id" in params) return moveNumber(this.http, phoneNumber, params, opts);
345
1030
  return this.http.request("PATCH", `/phone-numbers/${enc(phoneNumber)}`, params, void 0, opts);
346
1031
  }
1032
+ /** Same-account move; busy work is refused. Own number settings and history stay. */
1033
+ move(phoneNumber, agentId, opts) {
1034
+ return moveNumber(this.http, phoneNumber, { agent_id: agentId }, opts);
1035
+ }
347
1036
  /** Disconnect from Nixflex (clears carrier webhooks + our record). Does NOT
348
1037
  * release the number from your carrier - carrier billing continues until
349
1038
  * you release it in Twilio/Telnyx yourself. Reversible by re-importing. */
350
1039
  delete(phoneNumber, opts) {
351
1040
  return this.http.request("DELETE", `/phone-numbers/${enc(phoneNumber)}`, void 0, void 0, opts);
352
1041
  }
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
1042
  /** 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). */
1043
+ * Enabling alone is free. Premium applies to actual browser calls,
1044
+ * not ordinary phone calls just because this switch is enabled. */
365
1045
  setWebCalls(phoneNumber, enabled, opts) {
366
1046
  return this.http.request("PUT", `/integrations/web-calls/number/${enc(phoneNumber)}`, { enabled }, void 0, opts);
367
1047
  }
@@ -375,29 +1055,47 @@ var SmsCampaigns = class {
375
1055
  this.http = http;
376
1056
  }
377
1057
  http;
1058
+ cancel(id, opts) {
1059
+ return this.http.request("POST", `/sms/campaigns/${encodeURIComponent(id)}/cancel`, void 0, void 0, opts);
1060
+ }
1061
+ consent(id, params, opts) {
1062
+ return this.http.request("POST", `/sms/campaigns/${encodeURIComponent(id)}/consent`, params, void 0, opts);
1063
+ }
1064
+ resume(id, opts) {
1065
+ return this.http.request("POST", `/sms/campaigns/${encodeURIComponent(id)}/resume`, void 0, void 0, opts);
1066
+ }
1067
+ update(id, params, opts) {
1068
+ return this.http.request("PATCH", `/sms/campaigns/${encodeURIComponent(id)}`, params, void 0, opts);
1069
+ }
378
1070
  /** 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
1071
+ * up to 100,000 recipients). from_number may be on either carrier (Twilio or
380
1072
  * Telnyx) and must be a number on your own account. */
381
1073
  create(params, opts) {
382
- return this.http.request("POST", "/sms/campaigns", params, void 0, opts);
1074
+ return this.http.request("POST", "/sms/campaigns", smsCampaignInput(params), void 0, opts);
383
1075
  }
384
- /** Launch a draft/scheduled campaign immediately. */
1076
+ /** Request launch; scheduling and recipient contact-hour gates still apply. */
385
1077
  launch(campaignId, opts) {
386
1078
  return this.http.request("POST", `/sms/campaigns/${encodeURIComponent(campaignId)}/launch`, void 0, void 0, opts);
387
1079
  }
388
1080
  /** All campaigns, newest first, with live-computed delivery counts. */
389
1081
  list(params = {}, opts) {
390
- return this.http.request("GET", "/sms/campaigns", void 0, { status: params.status, limit: params.limit }, opts);
1082
+ return this.http.request("GET", "/sms/campaigns", void 0, { status: params.status, limit: params.limit, before: params.before }, opts);
391
1083
  }
392
- /** One campaign with per-recipient statuses. Twilio 'sent' (handed to
393
- * carrier, never confirmed on the handset) counts as FAILED, not delivered. */
1084
+ /** Detail envelope with independent recipient/message cursors; sent is not failed. */
394
1085
  get(campaignId, opts) {
395
- return this.http.request("GET", `/sms/campaigns/${encodeURIComponent(campaignId)}`, void 0, void 0, opts);
1086
+ return this.http.request(
1087
+ "GET",
1088
+ `/sms/campaigns/${encodeURIComponent(campaignId)}`,
1089
+ void 0,
1090
+ { limit: opts == null ? void 0 : opts.limit, recipient_cursor: opts == null ? void 0 : opts.recipient_cursor, message_cursor: opts == null ? void 0 : opts.message_cursor },
1091
+ opts
1092
+ );
396
1093
  }
397
- /** Cancel a scheduled/running campaign. Already-sent messages cannot be
398
- * recalled; cancelled_count = pending recipients that will not be messaged. */
1094
+ /** Cancel waiting work and hide the campaign. History/used charges remain, no refund
1095
+ * or recall of sent SMS. Owner/Admin only. 503 hangup_pending is queued, not success.
1096
+ * Missing/foreign is 404. One DELETE; never automatically repeated. */
399
1097
  delete(campaignId, opts) {
400
- return this.http.request("DELETE", `/sms/campaigns/${encodeURIComponent(campaignId)}`, void 0, void 0, opts);
1098
+ return this.http.request("DELETE", `/sms/campaigns/${contentDeleteId(campaignId)}`, void 0, void 0, opts);
401
1099
  }
402
1100
  };
403
1101
  var Sms = class {
@@ -420,226 +1118,3030 @@ var Keys = class {
420
1118
  this.http = http;
421
1119
  }
422
1120
  http;
1121
+ /** Retained request-log snapshot, not organisation audit events. Default today (UTC). */
1122
+ activity(params = {}, opts) {
1123
+ return this.http.request("GET", "/keys/activity", void 0, { ...params }, opts);
1124
+ }
423
1125
  /** Rotate the key SECRET (key_id stays stable - the Stripe model). The old
424
1126
  * secret stops working THE INSTANT this returns; the new one is shown ONCE.
425
1127
  * Update every deployed app before rotating in production. */
426
1128
  rotate(opts) {
427
1129
  return this.http.request("POST", "/keys/rotate", void 0, void 0, opts);
428
1130
  }
429
- };
430
- var UsageResource = class {
431
- constructor(http) {
432
- this.http = http;
1131
+ };
1132
+ var UsageResource = class {
1133
+ constructor(http) {
1134
+ this.http = http;
1135
+ }
1136
+ http;
1137
+ /** Usage + balance: calls, minutes, SMS, credit. minutes is fractional;
1138
+ * cost_usd excludes carrier charges (Twilio/Telnyx bill you directly). */
1139
+ get(opts) {
1140
+ return this.http.request("GET", "/usage", void 0, void 0, opts);
1141
+ }
1142
+ };
1143
+ var Webhooks = class {
1144
+ constructor(http) {
1145
+ this.http = http;
1146
+ }
1147
+ http;
1148
+ /** Verify a webhook delivery's X-Nixflex-Signature header. Pass the RAW
1149
+ * request body (string or Buffer) and the organisation signing secret (independent of API-key rotation). Returns true only
1150
+ * for an authentic, fresh signature. See webhook-verify.ts. */
1151
+ verify(rawBody, signatureHeader, keySecret, options) {
1152
+ return verifyWebhookSignature(rawBody, signatureHeader, keySecret, options);
1153
+ }
1154
+ /** Point a number's post-call events at your HTTPS endpoint.
1155
+ * slot 2 = the second destination (webhook2). */
1156
+ set(phoneNumber, url, slot = 1, opts) {
1157
+ const base = slot === 2 ? "webhook2" : "webhook";
1158
+ return this.http.request("PUT", `/integrations/${base}/number/${encodeURIComponent(phoneNumber)}`, { url }, void 0, opts);
1159
+ }
1160
+ /** Read the webhook configured on a number. */
1161
+ get(phoneNumber, slot = 1, opts) {
1162
+ const base = slot === 2 ? "webhook2" : "webhook";
1163
+ return this.http.request("GET", `/integrations/${base}/number/${encodeURIComponent(phoneNumber)}`, void 0, void 0, opts);
1164
+ }
1165
+ /** Remove the webhook from a number. */
1166
+ delete(phoneNumber, slot = 1, opts) {
1167
+ const base = slot === 2 ? "webhook2" : "webhook";
1168
+ return this.http.request("DELETE", `/integrations/${base}/number/${encodeURIComponent(phoneNumber)}`, void 0, void 0, opts);
1169
+ }
1170
+ };
1171
+
1172
+ // src/resources/callers.ts
1173
+ function enc2(phoneNumber) {
1174
+ return encodeURIComponent(phoneNumber);
1175
+ }
1176
+ var Callers = class {
1177
+ constructor(http) {
1178
+ this.http = http;
1179
+ }
1180
+ http;
1181
+ /** What the agent knows about this caller on this number - your fields plus
1182
+ * what the engine learned. 404 caller_not_found when there is no record. */
1183
+ get(phoneNumber, callerNumber, opts) {
1184
+ return this.http.request("GET", `/phone-numbers/${enc2(phoneNumber)}/callers/${enc2(callerNumber)}`, void 0, void 0, opts);
1185
+ }
1186
+ /** Set the caller's details. A field left out keeps its value; null removes it.
1187
+ * last_call / open_item are engine-only and are rejected (engine_only_field). */
1188
+ set(phoneNumber, callerNumber, params, opts) {
1189
+ return this.http.request("PUT", `/phone-numbers/${enc2(phoneNumber)}/callers/${enc2(callerNumber)}`, params, void 0, opts);
1190
+ }
1191
+ /** Erase the whole record for this caller on this number - yours and the engine's. */
1192
+ delete(phoneNumber, callerNumber, opts) {
1193
+ return this.http.request("DELETE", `/phone-numbers/${enc2(phoneNumber)}/callers/${enc2(callerNumber)}`, void 0, void 0, opts);
1194
+ }
1195
+ /** Up to 1,000 rows in one request. Every row is validated before any is
1196
+ * written. Split larger lists into several calls. */
1197
+ import(phoneNumber, callers, opts) {
1198
+ return this.http.request("POST", `/phone-numbers/${enc2(phoneNumber)}/callers/import`, { callers }, void 0, opts);
1199
+ }
1200
+ };
1201
+
1202
+ // src/key-create.ts
1203
+ async function createKey(params, baseUrl) {
1204
+ let res;
1205
+ try {
1206
+ res = await fetch(baseUrl.replace(/\/+$/, "") + "/v1/keys", {
1207
+ method: "POST",
1208
+ redirect: "error",
1209
+ headers: { "Content-Type": "application/json", "User-Agent": `nixflex-node/${SDK_VERSION}` },
1210
+ body: JSON.stringify(params),
1211
+ signal: AbortSignal.timeout(3e4)
1212
+ });
1213
+ } catch {
1214
+ throw new NixflexOutcomeUnknownError();
1215
+ }
1216
+ const requestId2 = res.headers.get("x-request-id") || res.headers.get("x-railway-request-id") || void 0;
1217
+ let body;
1218
+ try {
1219
+ body = await res.json();
1220
+ } catch {
1221
+ if (res.ok) throw new NixflexOutcomeUnknownError(res.status, null, requestId2);
1222
+ body = null;
1223
+ }
1224
+ if (!res.ok) throw errorFromResponse(
1225
+ res.status,
1226
+ body,
1227
+ requestId2,
1228
+ parseInt(res.headers.get("retry-after") || "0", 10) || 0,
1229
+ true
1230
+ );
1231
+ return body;
1232
+ }
1233
+
1234
+ // src/resources/integrations.ts
1235
+ var providers = ["calcom", "slack", "zapier", "make", "gohighlevel", "webhook", "webhook2", "precall", "web-calls"];
1236
+ function path(provider, number) {
1237
+ if (!providers.includes(provider)) throw new TypeError("Unknown public integration provider.");
1238
+ return `/integrations/${provider}/number/${encodeURIComponent(number)}`;
1239
+ }
1240
+ var functions = (number) => `/integrations/custom-functions/number/${encodeURIComponent(number)}`;
1241
+ var Integrations = class {
1242
+ constructor(http) {
1243
+ this.http = http;
1244
+ }
1245
+ http;
1246
+ /** Returns a short-lived link for a human to open; never opens a browser. */
1247
+ connectGoogleCalendar(number, returnUrl, opts) {
1248
+ return numberFeature(this.http, "POST", calendarPath(number) + "/connect", { return_url: returnUrl }, "calendar", opts);
1249
+ }
1250
+ getGoogleCalendar(number, opts) {
1251
+ return numberFeature(this.http, "GET", calendarPath(number), void 0, "calendar", opts);
1252
+ }
1253
+ disconnectGoogleCalendar(number, opts) {
1254
+ return numberFeature(this.http, "DELETE", calendarPath(number), void 0, "calendar", opts);
1255
+ }
1256
+ updateGoogleCalendarSettings(number, body, opts) {
1257
+ return numberFeature(this.http, "PATCH", calendarPath(number), body, "calendar", opts);
1258
+ }
1259
+ get(provider, number, opts) {
1260
+ return this.http.request("GET", path(provider, number), void 0, void 0, opts);
1261
+ }
1262
+ /** Provider PUT replaces configuration. Never automatically repeated. */
1263
+ set(provider, number, body, opts) {
1264
+ return this.http.request("PUT", path(provider, number), body, void 0, opts);
1265
+ }
1266
+ delete(provider, number, opts) {
1267
+ return this.http.request("DELETE", path(provider, number), void 0, void 0, opts);
1268
+ }
1269
+ getAgentPrecall(agentId, opts) {
1270
+ return this.http.request("GET", `/integrations/precall/agent/${encodeURIComponent(agentId)}`, void 0, void 0, opts);
1271
+ }
1272
+ setAgentPrecall(agentId, url, opts) {
1273
+ return this.http.request("PUT", `/integrations/precall/agent/${encodeURIComponent(agentId)}`, { url }, void 0, opts);
1274
+ }
1275
+ /** Removing the agent default affects every number without an override. */
1276
+ deleteAgentPrecall(agentId, opts) {
1277
+ return this.http.request("DELETE", `/integrations/precall/agent/${encodeURIComponent(agentId)}`, void 0, void 0, opts);
1278
+ }
1279
+ /** At most 15; an empty list is not proof that the number exists. */
1280
+ listFunctions(number, opts) {
1281
+ return this.http.request("GET", functions(number), void 0, void 0, opts);
1282
+ }
1283
+ createFunction(number, body, opts) {
1284
+ return this.http.request("POST", functions(number), body, void 0, opts);
1285
+ }
1286
+ /** PATCH changes supplied fields only. {} is refused by the server. */
1287
+ updateFunction(number, id, body, opts) {
1288
+ return this.http.request("PATCH", functions(number) + "/" + encodeURIComponent(id), body, void 0, opts);
1289
+ }
1290
+ deleteFunction(number, id, opts) {
1291
+ return this.http.request("DELETE", functions(number) + "/" + encodeURIComponent(id), void 0, void 0, opts);
1292
+ }
1293
+ };
1294
+
1295
+ // src/knowledge/guards.ts
1296
+ function writeOptions(opts) {
1297
+ const key = opts == null ? void 0 : opts.idempotencyKey;
1298
+ if (typeof key !== "string" || !/^[A-Za-z0-9_.:-]{8,128}$/.test(key) || key.startsWith("prompt:"))
1299
+ throw new TypeError("Supply an Idempotency-Key of 8..128 letters, digits, . _ : -, without the reserved prefix.");
1300
+ return opts;
1301
+ }
1302
+ function identifier(value) {
1303
+ if (typeof value !== "string" || !value) throw new TypeError("A non-empty knowledge identifier is required.");
1304
+ return encodeURIComponent(value);
1305
+ }
1306
+
1307
+ // src/knowledge/poll.ts
1308
+ async function pollJob(read, options = {}) {
1309
+ const { maxAttempts = 20, intervalMs = 1e3, timeoutMs = 3e4, signal } = options;
1310
+ if (!Number.isInteger(maxAttempts) || maxAttempts < 1 || maxAttempts > 100 || !Number.isFinite(intervalMs) || intervalMs < 0 || intervalMs > 3e4 || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 3e5)
1311
+ throw new RangeError("Use 1..100 attempts, a 0..30000 ms interval and a timeout up to 300000 ms.");
1312
+ const end = Date.now() + timeoutMs;
1313
+ for (let n = 0; n < maxAttempts; n++) {
1314
+ if (signal == null ? void 0 : signal.aborted) throw new NixflexConnectionError("Knowledge polling cancelled; the server job was not cancelled.");
1315
+ if (Date.now() >= end) break;
1316
+ const job = await read(Math.max(1, end - Date.now()));
1317
+ if (["ready", "failed", "cancelled", "deleted", "needs_review"].includes(job.state)) return job;
1318
+ if (n + 1 >= maxAttempts) break;
1319
+ await new Promise((resolve2) => {
1320
+ const finish = () => {
1321
+ clearTimeout(timer);
1322
+ signal == null ? void 0 : signal.removeEventListener("abort", finish);
1323
+ resolve2();
1324
+ };
1325
+ const timer = setTimeout(finish, Math.min(intervalMs, Math.max(0, end - Date.now())));
1326
+ signal == null ? void 0 : signal.addEventListener("abort", finish, { once: true });
1327
+ });
1328
+ }
1329
+ throw new NixflexConnectionError("Knowledge polling limit reached. Read the job again later; no change was sent.");
1330
+ }
1331
+
1332
+ // src/resources/knowledge.ts
1333
+ var Knowledge = class {
1334
+ constructor(http) {
1335
+ this.http = http;
1336
+ }
1337
+ http;
1338
+ /** DELETE /agents/:target/knowledge-base. Never auto-repeated; use a stable explicit operation key. */
1339
+ deleteScope(target, body, opts) {
1340
+ return this.http.request("DELETE", `/agents/${identifier(target)}/knowledge-base`, body, void 0, writeOptions(opts));
1341
+ }
1342
+ /** GET /agents/:target/knowledge-base. Read result is private customer data. */
1343
+ getScope(target, opts) {
1344
+ return this.http.request("GET", `/agents/${identifier(target)}/knowledge-base`, void 0, void 0, opts);
1345
+ }
1346
+ /** PUT /agents/:target/knowledge-base. Never auto-repeated; use a stable explicit operation key. */
1347
+ putScope(target, body, opts) {
1348
+ return this.http.request("PUT", `/agents/${identifier(target)}/knowledge-base`, body, void 0, writeOptions(opts));
1349
+ }
1350
+ /** POST /agents/:target/knowledge-base/source-measure. Read result is private customer data. */
1351
+ measureSource(target, body, opts) {
1352
+ return this.http.request("POST", `/agents/${identifier(target)}/knowledge-base/source-measure`, body, void 0, opts);
1353
+ }
1354
+ /** POST /agents/:target/knowledge-base/test-sessions. Never auto-repeated; use a stable explicit operation key. */
1355
+ startSession(target, body, opts) {
1356
+ return this.http.request("POST", `/agents/${identifier(target)}/knowledge-base/test-sessions`, body, void 0, writeOptions(opts));
1357
+ }
1358
+ /** GET /knowledge-bases/:kb. Read result is private customer data. */
1359
+ getBase(kb, opts) {
1360
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}`, void 0, void 0, opts);
1361
+ }
1362
+ /** DELETE /knowledge-bases/:kb/drafts/:id. Never auto-repeated; use a stable explicit operation key. */
1363
+ discardDraft(kb, id, body, opts) {
1364
+ return this.http.request("DELETE", `/knowledge-bases/${identifier(kb)}/drafts/${identifier(id)}`, body, void 0, writeOptions(opts));
1365
+ }
1366
+ /** GET /knowledge-bases/:kb/drafts/:id. Read result is private customer data. */
1367
+ getDraft(kb, id, opts) {
1368
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}/drafts/${identifier(id)}`, void 0, void 0, opts);
1369
+ }
1370
+ /** PATCH /knowledge-bases/:kb/drafts/:id. Never auto-repeated; use a stable explicit operation key. */
1371
+ updateDraft(kb, id, body, opts) {
1372
+ return this.http.request("PATCH", `/knowledge-bases/${identifier(kb)}/drafts/${identifier(id)}`, body, void 0, writeOptions(opts));
1373
+ }
1374
+ /** POST /knowledge-bases/:kb/drafts/:id/accept. Never auto-repeated; use a stable explicit operation key. */
1375
+ acceptDraft(kb, id, body, opts) {
1376
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/drafts/${identifier(id)}/accept`, body, void 0, writeOptions(opts));
1377
+ }
1378
+ /** POST /knowledge-bases/:kb/exports. Never auto-repeated; use a stable explicit operation key. */
1379
+ createExport(kb, body, opts) {
1380
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/exports`, body, void 0, writeOptions(opts));
1381
+ }
1382
+ /** GET /knowledge-bases/:kb/overview. Read result is private customer data. */
1383
+ overview(kb, opts) {
1384
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}/overview`, void 0, void 0, opts);
1385
+ }
1386
+ /** PATCH /knowledge-bases/:kb/settings. Never auto-repeated; use a stable explicit operation key. */
1387
+ updateSettings(kb, body, opts) {
1388
+ return this.http.request("PATCH", `/knowledge-bases/${identifier(kb)}/settings`, body, void 0, writeOptions(opts));
1389
+ }
1390
+ /** GET /knowledge-bases/:kb/sources. Read result is private customer data. */
1391
+ listSources(kb, query = {}, opts) {
1392
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}/sources`, void 0, { ...query }, opts);
1393
+ }
1394
+ /** POST /knowledge-bases/:kb/sources. Never auto-repeated; use a stable explicit operation key. */
1395
+ addSource(kb, body, opts) {
1396
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/sources`, body, void 0, writeOptions(opts));
1397
+ }
1398
+ /** DELETE /knowledge-bases/:kb/sources/:id. Never auto-repeated; use a stable explicit operation key. */
1399
+ deleteSource(kb, id, body, opts) {
1400
+ return this.http.request("DELETE", `/knowledge-bases/${identifier(kb)}/sources/${identifier(id)}`, body, void 0, writeOptions(opts));
1401
+ }
1402
+ /** PATCH /knowledge-bases/:kb/sources/:id. Never auto-repeated; use a stable explicit operation key. */
1403
+ renameSource(kb, id, body, opts) {
1404
+ return this.http.request("PATCH", `/knowledge-bases/${identifier(kb)}/sources/${identifier(id)}`, body, void 0, writeOptions(opts));
1405
+ }
1406
+ /** POST /knowledge-bases/:kb/sources/:id/replacements. Never auto-repeated; use a stable explicit operation key. */
1407
+ replaceSource(kb, id, body, opts) {
1408
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/sources/${identifier(id)}/replacements`, body, void 0, writeOptions(opts));
1409
+ }
1410
+ /** POST /knowledge-bases/:kb/sources/refresh. Never auto-repeated; use a stable explicit operation key. */
1411
+ refreshSources(kb, body, opts) {
1412
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/sources/refresh`, body, void 0, writeOptions(opts));
1413
+ }
1414
+ /** POST /knowledge-bases/:kb/topic-search. Read result is private customer data. */
1415
+ searchTopics(kb, body, opts) {
1416
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/topic-search`, body, void 0, opts);
1417
+ }
1418
+ /** GET /knowledge-bases/:kb/topics. Read result is private customer data. */
1419
+ listTopics(kb, query = {}, opts) {
1420
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}/topics`, void 0, { ...query }, opts);
1421
+ }
1422
+ /** POST /knowledge-bases/:kb/topics. Never auto-repeated; use a stable explicit operation key. */
1423
+ createTopic(kb, body, opts) {
1424
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/topics`, body, void 0, writeOptions(opts));
1425
+ }
1426
+ /** DELETE /knowledge-bases/:kb/topics/:id. Never auto-repeated; use a stable explicit operation key. */
1427
+ deleteTopic(kb, id, body, opts) {
1428
+ return this.http.request("DELETE", `/knowledge-bases/${identifier(kb)}/topics/${identifier(id)}`, body, void 0, writeOptions(opts));
1429
+ }
1430
+ /** GET /knowledge-bases/:kb/topics/:id. Read result is private customer data. */
1431
+ getTopic(kb, id, opts) {
1432
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}/topics/${identifier(id)}`, void 0, void 0, opts);
1433
+ }
1434
+ /** PATCH /knowledge-bases/:kb/topics/:id. Never auto-repeated; use a stable explicit operation key. */
1435
+ updateTopic(kb, id, body, opts) {
1436
+ return this.http.request("PATCH", `/knowledge-bases/${identifier(kb)}/topics/${identifier(id)}`, body, void 0, writeOptions(opts));
1437
+ }
1438
+ /** GET /knowledge-bases/:kb/unanswered. Read result is private customer data. */
1439
+ unanswered(kb, query = {}, opts) {
1440
+ return this.http.request("GET", `/knowledge-bases/${identifier(kb)}/unanswered`, void 0, { ...query }, opts);
1441
+ }
1442
+ /** POST /knowledge-bases/:kb/website-discoveries. Never auto-repeated; use a stable explicit operation key. */
1443
+ discoverWebsite(kb, body, opts) {
1444
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/website-discoveries`, body, void 0, writeOptions(opts));
1445
+ }
1446
+ /** POST /knowledge-bases/:kb/website-imports. Never auto-repeated; use a stable explicit operation key. */
1447
+ importWebsite(kb, body, opts) {
1448
+ return this.http.request("POST", `/knowledge-bases/${identifier(kb)}/website-imports`, body, void 0, writeOptions(opts));
1449
+ }
1450
+ /** GET /knowledge/capabilities. Read result is private customer data. */
1451
+ capabilities(opts) {
1452
+ return this.http.request("GET", `/knowledge/capabilities`, void 0, void 0, opts);
1453
+ }
1454
+ /** GET /knowledge/events. Read result is private customer data. */
1455
+ events(query = {}, opts) {
1456
+ return this.http.request("GET", `/knowledge/events`, void 0, { ...query }, opts);
1457
+ }
1458
+ /** GET /knowledge/exports/:id. Read result is private customer data. */
1459
+ downloadExport(id, query = {}, opts) {
1460
+ return this.http.knowledgeDownload(`/knowledge/exports/${identifier(id)}`, { ...query }, opts);
1461
+ }
1462
+ /** GET /knowledge/jobs/:id. Read result is private customer data. */
1463
+ getJob(id, opts) {
1464
+ return this.http.request("GET", `/knowledge/jobs/${identifier(id)}`, void 0, void 0, opts);
1465
+ }
1466
+ /** POST /knowledge/jobs/:id/cancel. Never auto-repeated; use a stable explicit operation key. */
1467
+ cancelJob(id, body, opts) {
1468
+ return this.http.request("POST", `/knowledge/jobs/${identifier(id)}/cancel`, body, void 0, writeOptions(opts));
1469
+ }
1470
+ /** POST /knowledge/jobs/:id/retry. Never auto-repeated; use a stable explicit operation key. */
1471
+ retryJob(id, body, opts) {
1472
+ return this.http.request("POST", `/knowledge/jobs/${identifier(id)}/retry`, body, void 0, writeOptions(opts));
1473
+ }
1474
+ /** GET /knowledge/targets. Read result is private customer data. */
1475
+ targets(query = {}, opts) {
1476
+ return this.http.request("GET", `/knowledge/targets`, void 0, { ...query }, opts);
1477
+ }
1478
+ /** GET /knowledge/test-sessions/:id. Read result is private customer data. */
1479
+ getSession(id, opts) {
1480
+ return this.http.request("GET", `/knowledge/test-sessions/${identifier(id)}`, void 0, void 0, opts);
1481
+ }
1482
+ /** POST /knowledge/test-sessions/:id/cancel. Never auto-repeated; use a stable explicit operation key. */
1483
+ cancelSession(id, body, opts) {
1484
+ return this.http.request("POST", `/knowledge/test-sessions/${identifier(id)}/cancel`, body, void 0, writeOptions(opts));
1485
+ }
1486
+ /** POST /knowledge/test-sessions/:id/messages. Never auto-repeated; use a stable explicit operation key. */
1487
+ ask(id, body, opts) {
1488
+ return this.http.request("POST", `/knowledge/test-sessions/${identifier(id)}/messages`, body, void 0, writeOptions(opts));
1489
+ }
1490
+ /** GET /knowledge/usage. Read result is private customer data. */
1491
+ usage(query = {}, opts) {
1492
+ return this.http.request("GET", `/knowledge/usage`, void 0, { ...query }, opts);
1493
+ }
1494
+ /** GET /agents/:target/knowledge-keyterms. Read result is private customer data. */
1495
+ keyterms(target, opts) {
1496
+ return this.http.request("GET", `/agents/${identifier(target)}/knowledge-keyterms`, void 0, void 0, opts);
1497
+ }
1498
+ uploadSource(kb, file, opts) {
1499
+ return this.http.knowledgeUpload("/knowledge-bases/" + identifier(kb) + "/sources", file, writeOptions(opts));
1500
+ }
1501
+ replaceSourceFile(kb, id, file, opts) {
1502
+ return this.http.knowledgeUpload("/knowledge-bases/" + identifier(kb) + "/sources/" + identifier(id) + "/replacements", file, writeOptions(opts));
1503
+ }
1504
+ measureFile(target, file, opts = {}) {
1505
+ return this.http.knowledgeUpload("/agents/" + identifier(target) + "/knowledge-base/source-measure", file, opts);
1506
+ }
1507
+ waitJob(id, options = {}) {
1508
+ return pollJob((timeoutMs) => this.getJob(id, { timeoutMs, signal: options.signal }), options);
1509
+ }
1510
+ };
1511
+
1512
+ // src/resources/organisation.ts
1513
+ var Organisation = class {
1514
+ constructor(http) {
1515
+ this.http = http;
1516
+ }
1517
+ http;
1518
+ get(opts) {
1519
+ return this.http.request("GET", "/organisation", void 0, void 0, opts);
1520
+ }
1521
+ members(opts) {
1522
+ return this.http.request("GET", "/organisation/members", void 0, void 0, opts);
1523
+ }
1524
+ invite(email, role = "member", opts) {
1525
+ return this.http.request("POST", "/organisation/invites", { email, role }, void 0, opts);
1526
+ }
1527
+ resend(inviteId, opts) {
1528
+ return this.http.request("POST", "/organisation/invites/" + encodeURIComponent(inviteId) + "/resend", void 0, void 0, opts);
1529
+ }
1530
+ revoke(inviteId, opts) {
1531
+ return this.http.request("DELETE", "/organisation/invites/" + encodeURIComponent(inviteId), void 0, void 0, opts);
1532
+ }
1533
+ removeMember(userId, opts) {
1534
+ return this.http.request("DELETE", "/organisation/members/" + encodeURIComponent(userId), void 0, void 0, opts);
1535
+ }
1536
+ setRole(userId, role, opts) {
1537
+ return this.http.request("PATCH", "/organisation/members/" + encodeURIComponent(userId), { role }, void 0, opts);
1538
+ }
1539
+ activity(params = {}, opts) {
1540
+ return this.http.request("GET", "/organisation/activity", void 0, { ...params }, opts);
1541
+ }
1542
+ /** Default JSON page is 50 events. Keep IDs/cursors as strings; from/to are inclusive UTC dates. */
1543
+ activityCsv(params = {}, opts) {
1544
+ return this.http.stream("/organisation/activity", { ...params, format: "csv" }, opts);
1545
+ }
1546
+ /** Owner API-key authority; trims to 2..100 characters on the server. */
1547
+ rename(name, opts) {
1548
+ return this.http.request("PATCH", "/organisation/name", { name }, void 0, opts);
1549
+ }
1550
+ /** Claim an existing API-only account: sends a verified-email invitation, never transfers an owned account. */
1551
+ claimInvite(email, opts) {
1552
+ return this.http.request("POST", "/organisation/claim-invite", { email }, void 0, opts);
1553
+ }
1554
+ };
1555
+
1556
+ // src/resources/core.ts
1557
+ var Account = class {
1558
+ constructor(http) {
1559
+ this.http = http;
1560
+ }
1561
+ http;
1562
+ retention(opts) {
1563
+ return this.http.request("GET", "/account/retention", void 0, void 0, opts);
1564
+ }
1565
+ };
1566
+ var Voices = class {
1567
+ constructor(http) {
1568
+ this.http = http;
1569
+ }
1570
+ http;
1571
+ list(params = {}, opts) {
1572
+ return this.http.request("GET", "/voices", void 0, { ...params }, opts);
1573
+ }
1574
+ get(voiceKey, params = {}, opts) {
1575
+ return this.http.request("GET", `/voices/${encodeURIComponent(voiceKey)}`, void 0, { ...params }, opts);
1576
+ }
1577
+ };
1578
+
1579
+ // src/resources/contacts.ts
1580
+ var Contacts = class {
1581
+ constructor(http) {
1582
+ this.http = http;
1583
+ }
1584
+ http;
1585
+ preview(params, opts) {
1586
+ return this.http.request("POST", "/contact-hours/preview", params, void 0, opts);
1587
+ }
1588
+ list(params = {}, opts) {
1589
+ return this.http.request("GET", "/contact-suppressions", void 0, { ...params }, opts);
1590
+ }
1591
+ add(params, opts) {
1592
+ return this.http.request("POST", "/contact-suppressions", params, void 0, opts);
1593
+ }
1594
+ remove(params, opts) {
1595
+ return this.http.request("DELETE", "/contact-suppressions", params, void 0, opts);
1596
+ }
1597
+ };
1598
+
1599
+ // src/resources/web-agent.ts
1600
+ var WebAgent = class {
1601
+ constructor(http) {
1602
+ this.http = http;
1603
+ }
1604
+ http;
1605
+ get(number, opts) {
1606
+ return this.http.request("GET", `/agent-web/${encodeURIComponent(number)}`, void 0, void 0, opts);
1607
+ }
1608
+ update(number, params, opts) {
1609
+ return this.http.request("PATCH", `/agent-web/${encodeURIComponent(number)}`, params, void 0, opts);
1610
+ }
1611
+ };
1612
+
1613
+ // src/resources/inbox.ts
1614
+ var Inbox = class {
1615
+ constructor(http) {
1616
+ this.http = http;
1617
+ }
1618
+ http;
1619
+ list(channel, number, params = {}, opts) {
1620
+ return this.http.request("GET", `/agent-inbox/${encodeURIComponent(channel)}/${encodeURIComponent(number)}`, void 0, { ...params }, opts);
1621
+ }
1622
+ thread(channel, number, thread, params = {}, opts) {
1623
+ return this.http.request("GET", `/agent-inbox/${encodeURIComponent(channel)}/${encodeURIComponent(number)}/thread/${encodeURIComponent(thread)}`, void 0, { ...params }, opts);
1624
+ }
1625
+ update(channel, number, thread, params, opts) {
1626
+ return this.http.request("PATCH", `/agent-inbox/${encodeURIComponent(channel)}/${encodeURIComponent(number)}/thread/${encodeURIComponent(thread)}`, params, void 0, opts);
1627
+ }
1628
+ features(opts) {
1629
+ return this.http.request("GET", "/agent-inbox/features", void 0, void 0, opts);
1630
+ }
1631
+ numbers(params = {}, opts) {
1632
+ return this.http.request("GET", "/agent-inbox/numbers", void 0, { ...params }, opts);
1633
+ }
1634
+ retention(params = {}, opts) {
1635
+ return this.http.request("GET", "/agent-inbox/retention", void 0, { ...params }, opts);
1636
+ }
1637
+ };
1638
+
1639
+ // src/index.ts
1640
+ var Nixflex = class {
1641
+ inbox;
1642
+ webAgent;
1643
+ contacts;
1644
+ account;
1645
+ voices;
1646
+ organisation;
1647
+ integrations;
1648
+ knowledge;
1649
+ /** AI agents - create, list, get, update, delete. */
1650
+ agents;
1651
+ /** Calls - trigger outbound, list history, fetch transcripts + analysis. */
1652
+ calls;
1653
+ /** Voice batch campaigns - many calls under one campaign, scheduling windows. */
1654
+ campaigns;
1655
+ /** Phone numbers - import (Twilio/Telnyx), settings, monitor + web-calls toggles. */
1656
+ phoneNumbers;
1657
+ /** SMS - single sends + bulk campaigns. */
1658
+ sms;
1659
+ /** API key management - rotate the secret. */
1660
+ keys;
1661
+ /** Usage + balance. */
1662
+ usage;
1663
+ /** Per-number post-call webhook configuration. */
1664
+ webhooks;
1665
+ /** Caller context - what the agent knows about each caller on one of your numbers. */
1666
+ callers;
1667
+ constructor(options) {
1668
+ const http = new HttpClient(options);
1669
+ this.inbox = new Inbox(http);
1670
+ this.webAgent = new WebAgent(http);
1671
+ this.contacts = new Contacts(http);
1672
+ this.account = new Account(http);
1673
+ this.voices = new Voices(http);
1674
+ this.organisation = new Organisation(http);
1675
+ this.integrations = new Integrations(http);
1676
+ this.knowledge = new Knowledge(http);
1677
+ this.agents = new Agents(http);
1678
+ this.calls = new Calls(http);
1679
+ this.campaigns = new Campaigns(http);
1680
+ this.phoneNumbers = new PhoneNumbers(http);
1681
+ this.sms = new Sms(http);
1682
+ this.keys = new Keys(http);
1683
+ this.usage = new UsageResource(http);
1684
+ this.webhooks = new Webhooks(http);
1685
+ this.callers = new Callers(http);
1686
+ }
1687
+ /** Create a brand-new API key (unauthenticated signup endpoint - most
1688
+ * developers use the dashboard instead). The key_secret is shown ONCE.
1689
+ * Rate-limited per IP to prevent abuse. */
1690
+ static async createKey(params = {}, baseUrl = "https://api.nixflex.com") {
1691
+ return createKey(params, baseUrl);
1692
+ }
1693
+ };
1694
+ var src_default = Nixflex;
1695
+
1696
+ // src/error-output.ts
1697
+ function errorOutput(e) {
1698
+ return { error: {
1699
+ type: e.type,
1700
+ code: e.code,
1701
+ status: e.status,
1702
+ message: e.message,
1703
+ doc_url: e.doc_url,
1704
+ details: e.details,
1705
+ request_id: e.request_id,
1706
+ ...e instanceof NixflexOutcomeUnknownError ? {
1707
+ outcome: e.outcome,
1708
+ safe_to_retry: e.safe_to_retry,
1709
+ request_id: e.request_id,
1710
+ details: e.details
1711
+ } : {}
1712
+ } };
1713
+ }
1714
+
1715
+ // src/cli/number-reads.ts
1716
+ async function readNumber(client, cmd, number, s, json) {
1717
+ if (cmd === "get") {
1718
+ if (!number) throw new Error("numbers get <number>");
1719
+ return client.phoneNumbers.get(number);
1720
+ }
1721
+ const provider = s("provider");
1722
+ if (provider !== void 0 && provider !== "twilio" && provider !== "telnyx") throw new Error("--provider must be twilio or telnyx");
1723
+ const raw = s("limit");
1724
+ if (raw !== void 0 && (!/^[1-9]\d*$/.test(raw) || Number(raw) > 100)) throw new Error("--limit must be 1..100");
1725
+ const params = { agent_id: s("agent"), provider, limit: raw === void 0 ? void 0 : Number(raw), cursor: s("cursor") };
1726
+ const result = await client.phoneNumbers.list(params);
1727
+ return json || params.limit !== void 0 || params.cursor !== void 0 ? result : result.phone_numbers;
1728
+ }
1729
+
1730
+ // src/cli/number-usage.ts
1731
+ function numberUsage(client, number, option) {
1732
+ if (!/^\+[1-9]\d{6,14}$/.test(number || "")) throw new Error("numbers usage <E.164 number> [--period today|7|14|30|90|all] [--time-zone Europe/London]");
1733
+ const period = option("period") ?? "all", timeZone = option("time-zone") ?? "UTC";
1734
+ if (!["today", "7", "14", "30", "90", "all"].includes(period)) throw new Error("--period must be today, 7, 14, 30, 90 or all");
1735
+ if (timeZone !== "UTC" && !timeZone.includes("/")) throw new Error("--time-zone must be an IANA zone, or UTC");
1736
+ new Intl.DateTimeFormat("en", { timeZone });
1737
+ return client.phoneNumbers.usage(number, { period, time_zone: timeZone });
1738
+ }
1739
+
1740
+ // src/cli/number-move.ts
1741
+ function numberMove(client, number, agent, body) {
1742
+ if (!number || !(agent == null ? void 0 : agent.trim())) throw new Error("numbers move <number> --agent <agent_id>");
1743
+ if (Object.keys(body).length) throw new Error("Move the number separately from other settings. Send only --agent.");
1744
+ return client.phoneNumbers.move(number, agent);
1745
+ }
1746
+
1747
+ // src/cli/agent-list.ts
1748
+ var agentListFlags = { offset: { type: "string" }, search: { type: "string" } };
1749
+ function agentListParams(values) {
1750
+ const out2 = {};
1751
+ for (const [key, min, max] of [["limit", 1, 200], ["offset", 0, 1e6]]) {
1752
+ const value = values[key];
1753
+ if (value === void 0) continue;
1754
+ if (typeof value !== "string" || !/^(0|[1-9]\d*)$/.test(value) || Number(value) < min || Number(value) > max) {
1755
+ throw new Error(`--${key} must be a whole number from ${min} to ${max}.`);
1756
+ }
1757
+ out2[key] = Number(value);
1758
+ }
1759
+ if (values.status !== void 0) {
1760
+ if (!["active", "disabled", "all"].includes(values.status)) throw new Error("--status must be active, disabled or all.");
1761
+ out2.status = values.status;
1762
+ }
1763
+ if (values.search !== void 0) {
1764
+ if (typeof values.search !== "string" || values.search.length > 200 || /[\u0000-\u001f\u007f]/.test(values.search)) throw new Error("--search must be text of at most 200 characters without control characters.");
1765
+ out2.search = values.search;
1766
+ }
1767
+ return out2;
1768
+ }
1769
+
1770
+ // src/cli/call-create.ts
1771
+ function callCreateBody(body, variables) {
1772
+ const has = (key) => Object.prototype.hasOwnProperty.call(body, key);
1773
+ if (has("variables") && has("dynamic_vars") || variables !== void 0 && (has("variables") || has("dynamic_vars"))) {
1774
+ throw new Error("Use only one of --var, variables or dynamic_vars for a single call.");
1775
+ }
1776
+ const { variables: alias, ...rest } = body;
1777
+ if (variables !== void 0) rest.dynamic_vars = variables;
1778
+ else if (has("variables")) rest.dynamic_vars = alias;
1779
+ return rest;
1780
+ }
1781
+
1782
+ // src/cli/call-reads.ts
1783
+ var callReadFlags = Object.fromEntries(["number", "direction", "outcome", "source", "period", "since", "until"].map((k) => [k, { type: "string" }]));
1784
+ function callHistoryParams(values) {
1785
+ const out2 = {};
1786
+ for (const [k, min, max] of [["limit", 1, 200], ["offset", 0, 1e6]]) {
1787
+ if (values[k] === void 0) continue;
1788
+ const v = values[k];
1789
+ if (typeof v !== "string" || !/^(0|[1-9]\d*)$/.test(v) || +v < min || +v > max) throw new Error(`Invalid --${k}.`);
1790
+ out2[k] = +v;
1791
+ }
1792
+ for (const k of ["agent", "number", "direction", "outcome", "source", "period", "since", "until", "search", "cursor"]) {
1793
+ if (values[k] !== void 0) {
1794
+ if (typeof values[k] !== "string") throw new Error(`Invalid --${k}.`);
1795
+ out2[k] = values[k];
1796
+ }
1797
+ }
1798
+ return out2;
1799
+ }
1800
+ async function callRead(client, command, id, values) {
1801
+ if (command === "history") return client.calls.history(callHistoryParams(values));
1802
+ if (!id) throw new Error(`calls ${command} requires a call ID.`);
1803
+ if (command === "read") return client.calls.read(id);
1804
+ if (command === "recording") return client.calls.recording(id);
1805
+ throw new Error("Unknown call read.");
1806
+ }
1807
+
1808
+ // src/cli/integration-output.ts
1809
+ var codes = /* @__PURE__ */ new Set([
1810
+ "unknown_error",
1811
+ "invalid_phone",
1812
+ "missing_field",
1813
+ "invalid_url",
1814
+ "invalid_name",
1815
+ "invalid_method",
1816
+ "limit_reached",
1817
+ "duplicate_function",
1818
+ "no_fields",
1819
+ "not_found",
1820
+ "server_error",
1821
+ "booking_provider_conflict",
1822
+ "outcome_unknown",
1823
+ "unauthorized",
1824
+ "invalid_api_key",
1825
+ "forbidden",
1826
+ "rate_limit_exceeded",
1827
+ "account_inactive",
1828
+ "account_closed",
1829
+ "invalid_json",
1830
+ "organisation_unavailable",
1831
+ "invalid_filter"
1832
+ ]);
1833
+ var publicFields = /* @__PURE__ */ new Set([
1834
+ "ok",
1835
+ "phone_number",
1836
+ "agent_id",
1837
+ "provider",
1838
+ "is_active",
1839
+ "deleted",
1840
+ "web_calls_enabled",
1841
+ "id",
1842
+ "name",
1843
+ "functions",
1844
+ "method",
1845
+ "timeout_ms",
1846
+ "has_headers",
1847
+ "is_set",
1848
+ "api_key_set",
1849
+ "webhook_url_set",
1850
+ "post_call_url_set",
1851
+ "in_call_url_set",
1852
+ "pit_set",
1853
+ "username",
1854
+ "event_slug",
1855
+ "default_timezone",
1856
+ "location_id",
1857
+ "tags",
1858
+ "tool_name"
1859
+ ]);
1860
+ function integrationOutput(value) {
1861
+ if (Array.isArray(value)) return value.map(integrationOutput);
1862
+ if (!value || typeof value !== "object") return value;
1863
+ const result = {};
1864
+ for (const [key, item] of Object.entries(value)) {
1865
+ if (/^(api_key|pit|headers|signing_secret|secret|token|authorization|parameters|tool_description|description|speak_during)$/i.test(key) || /(?:^|_)url(?:_2)?$/.test(key)) {
1866
+ result[key] = item == null ? null : "[omitted: private configuration]";
1867
+ } else if (publicFields.has(key)) result[key] = integrationOutput(item);
1868
+ }
1869
+ return result;
1870
+ }
1871
+ async function privateIntegration(action) {
1872
+ try {
1873
+ return integrationOutput(await action());
1874
+ } catch (error) {
1875
+ const e = error;
1876
+ const code = codes.has(e.code) ? e.code : "integration_request_failed";
1877
+ const unknown = e.code === "outcome_unknown";
1878
+ throw new NixflexError(Number.isInteger(e.status) ? e.status : 0, { error: {
1879
+ type: unknown ? "outcome_unknown" : "integration_error",
1880
+ code,
1881
+ message: unknown ? "Outcome unknown. Check the current state before retrying; the change was not repeated." : "Integration request failed. Check the status and error code; private details are omitted.",
1882
+ details: unknown ? { outcome: "unknown", safe_to_retry: false } : {}
1883
+ } });
1884
+ }
1885
+ }
1886
+
1887
+ // src/cli/integrations.ts
1888
+ var integrationsHelp = `
1889
+ INTEGRATION SETTINGS (private input; no credential output)
1890
+ integrations get <provider> <number>
1891
+ integrations set <provider> <number> --body @private-settings.json --confirm
1892
+ integrations delete <provider> <number> --confirm
1893
+ integrations getAgentPrecall <agent-id>
1894
+ integrations setAgentPrecall <agent-id> --body @private-settings.json --confirm
1895
+ integrations deleteAgentPrecall <agent-id> --confirm
1896
+ integrations listFunctions <number>
1897
+ integrations createFunction <number> --body @private-function.json --confirm
1898
+ integrations updateFunction <number> <function-id> --body @private-function.json --confirm
1899
+ integrations deleteFunction <number> <function-id> --confirm
1900
+ Providers: calcom | slack | zapier | make | gohighlevel | webhook | webhook2 | precall | web-calls
1901
+ PUT replaces provider config; PATCH changes supplied function fields only.
1902
+ URLs, headers and free-form configuration are omitted from output.
1903
+ New writes without --confirm send ZERO requests. Successful writes need manual tests.
1904
+ `;
1905
+ async function integrationsCommand(c, positions, body, confirmed) {
1906
+ const [, command, a, b] = positions;
1907
+ const read = ["get", "getAgentPrecall", "listFunctions"].includes(command);
1908
+ const write = ["set", "delete", "setAgentPrecall", "deleteAgentPrecall", "createFunction", "updateFunction", "deleteFunction"].includes(command);
1909
+ if (!read && !write) throw new Error("Unknown integrations command. Run nixflex --help.");
1910
+ if (write && !confirmed) return { confirmation_required: true, sent: false, hint: "No request sent. Review the change privately, then add --confirm." };
1911
+ if (!a || ["get", "set", "delete", "updateFunction", "deleteFunction"].includes(command) && !b) throw new Error("Supply the required integration identifiers.");
1912
+ const r = c.integrations;
1913
+ return privateIntegration(() => {
1914
+ if (command === "get") return r.get(a, b);
1915
+ if (command === "set") return r.set(a, b, body);
1916
+ if (command === "delete") return r.delete(a, b);
1917
+ if (command === "getAgentPrecall") return r.getAgentPrecall(a);
1918
+ if (command === "setAgentPrecall") {
1919
+ if (typeof body.url !== "string") throw new Error("A private URL is required.");
1920
+ return r.setAgentPrecall(a, body.url);
1921
+ }
1922
+ if (command === "deleteAgentPrecall") return r.deleteAgentPrecall(a);
1923
+ if (command === "listFunctions") return r.listFunctions(a);
1924
+ if (command === "createFunction") return r.createFunction(a, body);
1925
+ if (command === "updateFunction") return r.updateFunction(a, b, body);
1926
+ return r.deleteFunction(a, b);
1927
+ });
1928
+ }
1929
+
1930
+ // src/cli/number-features.ts
1931
+ var k6Flags = { "return-url": { type: "string" }, "credentials-stdin": { type: "boolean" } };
1932
+ var k6Help = `
1933
+ GOOGLE CALENDAR (owned number; consent link is opened by the human)
1934
+ integrations connectGoogleCalendar <number> --return-url https://app.example.test/done --confirm
1935
+ integrations getGoogleCalendar <number>
1936
+ integrations disconnectGoogleCalendar <number> --confirm
1937
+ integrations updateGoogleCalendarSettings <number> --body @calendar-settings.json --confirm
1938
+ PATCH: timezone, hours (all 7 days, null when closed), slot_minutes 15|30|45|60,
1939
+ calendar_id, send_invites (true|false). Omitted fields keep their saved values.
1940
+ NUMBER CARRIER DETAILS (sensitive; never put credentials in command arguments)
1941
+ numbers updateCredentials <number> --provider twilio --confirm
1942
+ numbers updateCredentials <number> --provider telnyx --confirm --credentials-stdin
1943
+ Env: NIXFLEX_TWILIO_SID + NIXFLEX_TWILIO_TOKEN, or
1944
+ NIXFLEX_TELNYX_API_KEY + NIXFLEX_TELNYX_CONNECTION_ID.
1945
+ --credentials-stdin reads the exact JSON pair privately. No credential file/args.
1946
+ Writes without --confirm send ZERO requests. No automatic write retry.
1947
+ `;
1948
+ var calendarCommands = ["connectGoogleCalendar", "getGoogleCalendar", "disconnectGoogleCalendar", "updateGoogleCalendarSettings"];
1949
+ var isK6 = (group, command) => group === "integrations" && calendarCommands.includes(command) || group === "numbers" && command === "updateCredentials";
1950
+ function guardCredentialArguments(args) {
1951
+ const at = args.findIndex((s, i) => s === "numbers" && args[i + 1] === "updateCredentials");
1952
+ if (at < 0) return;
1953
+ const flags = /* @__PURE__ */ new Set(["--confirm", "--yes", "-y", "--json", "--credentials-stdin", "--help", "-h"]);
1954
+ if (!/^\+[1-9]\d{6,14}$/.test(args[at + 2] || "")) throw new Error("Supply an E.164 number; credentials are private input only.");
1955
+ const options = [...args.slice(0, at), ...args.slice(at + 3)];
1956
+ for (let i = 0; i < options.length; i++) {
1957
+ if (flags.has(options[i])) continue;
1958
+ if (["--provider", "--base-url"].includes(options[i]) && options[i + 1] && !options[i + 1].startsWith("--")) {
1959
+ i++;
1960
+ continue;
1961
+ }
1962
+ throw new Error("Credential command accepts only number, provider, confirmation, output and private stdin flags. Never supply secret arguments.");
1963
+ }
1964
+ }
1965
+ async function credentialInput(provider, stdin) {
1966
+ if (!["twilio", "telnyx"].includes(String(provider))) throw new Error("Use --provider twilio or telnyx.");
1967
+ const fields = provider === "twilio" ? ["twilio_sid", "twilio_token"] : ["telnyx_api_key", "telnyx_connection_id"];
1968
+ if (stdin) {
1969
+ if (process.stdin.isTTY) throw new Error("Pipe private credential JSON to stdin; interactive echo is disabled.");
1970
+ let size = 0;
1971
+ const chunks = [];
1972
+ for await (const part of process.stdin) {
1973
+ const chunk = Buffer.from(part);
1974
+ size += chunk.length;
1975
+ if (size > 2e4) throw new Error("Credential input is too large.");
1976
+ chunks.push(chunk);
1977
+ }
1978
+ let value;
1979
+ try {
1980
+ value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1981
+ } catch {
1982
+ throw new Error("Private stdin must contain one credential JSON object.");
1983
+ }
1984
+ if (!value || Array.isArray(value) || Object.keys(value).length !== 2 || fields.some((k) => typeof value[k] !== "string"))
1985
+ throw new Error("Private stdin must contain exactly the selected carrier pair.");
1986
+ return value;
1987
+ }
1988
+ const env = provider === "twilio" ? ["NIXFLEX_TWILIO_SID", "NIXFLEX_TWILIO_TOKEN"] : ["NIXFLEX_TELNYX_API_KEY", "NIXFLEX_TELNYX_CONNECTION_ID"];
1989
+ if (env.some((k) => !process.env[k])) throw new Error("Configure both selected carrier credentials privately in the environment. No request sent.");
1990
+ return Object.fromEntries(fields.map((k, i) => [k, process.env[env[i]]]));
1991
+ }
1992
+ function calendarOutput(value, command) {
1993
+ const v = value;
1994
+ if (!v || typeof v !== "object") throw featureError({ status: 0 }, "calendar", command !== "getGoogleCalendar");
1995
+ const fields = command === "connectGoogleCalendar" ? ["url", "expires_at"] : command === "getGoogleCalendar" ? ["connected", "account_email", "calendar_id", "connected_at", "needs_reconnect", "send_invites"] : command === "disconnectGoogleCalendar" ? ["ok", "connected"] : ["timezone", "hours", "slot_minutes", "calendar_id", "send_invites"];
1996
+ if (command === "connectGoogleCalendar") {
1997
+ let url;
1998
+ try {
1999
+ url = new URL(String(v.url));
2000
+ } catch {
2001
+ throw featureError({ status: 0 }, "calendar", true);
2002
+ }
2003
+ if (url.protocol !== "https:" || url.hostname !== "accounts.google.com" || url.username || url.password || ["access_token", "refresh_token", "id_token", "code"].some((k) => url.searchParams.has(k))) throw featureError({ status: 0 }, "calendar", true);
2004
+ }
2005
+ const out2 = Object.fromEntries(fields.map((k) => [k, v[k]]));
2006
+ if ("hours" in out2 && out2.hours && typeof out2.hours === "object")
2007
+ out2.hours = Object.fromEntries(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].map((k) => [k, out2.hours[k]]));
2008
+ return out2;
2009
+ }
2010
+ async function k6Command(c, positions, values, confirmed, body) {
2011
+ const [group, command, number] = positions;
2012
+ if (command !== "getGoogleCalendar" && !confirmed) return { confirmation_required: true, sent: false, hint: "No request sent. Review this change, then add --confirm." };
2013
+ if (!/^\+[1-9]\d{6,14}$/.test(number || "") || positions.length !== 3) throw new Error("Supply exactly one owned E.164 number.");
2014
+ if (group === "numbers") return c.phoneNumbers.updateCredentials(number, await credentialInput(values.provider, values["credentials-stdin"]));
2015
+ const r = c.integrations;
2016
+ const value = command === "connectGoogleCalendar" ? await r.connectGoogleCalendar(number, String(values["return-url"] || "")) : command === "getGoogleCalendar" ? await r.getGoogleCalendar(number) : command === "disconnectGoogleCalendar" ? await r.disconnectGoogleCalendar(number) : await r.updateGoogleCalendarSettings(number, body());
2017
+ return calendarOutput(value, command);
2018
+ }
2019
+
2020
+ // src/cli/knowledge-output.ts
2021
+ import { open as open2, link, unlink } from "fs/promises";
2022
+ import { randomUUID as randomUUID2 } from "crypto";
2023
+ async function knowledgeOutput(chunks, output) {
2024
+ if (!output) throw new Error("Use --output FILE.json. Existing files are never overwritten.");
2025
+ const partial = output + ".partial-" + randomUUID2();
2026
+ const file = await open2(partial, "wx", 384);
2027
+ let bytes = 0;
2028
+ try {
2029
+ for await (const chunk of chunks) {
2030
+ let offset = 0;
2031
+ while (offset < chunk.length) {
2032
+ const written = await file.write(chunk, offset, chunk.length - offset);
2033
+ if (!written.bytesWritten) throw new Error("Export file could not be written.");
2034
+ offset += written.bytesWritten;
2035
+ }
2036
+ bytes += chunk.length;
2037
+ }
2038
+ await file.sync();
2039
+ await file.close();
2040
+ await link(partial, output);
2041
+ return { saved: true, bytes, file: output, format: "json-envelope" };
2042
+ } finally {
2043
+ await file.close().catch(() => {
2044
+ });
2045
+ await unlink(partial).catch(() => {
2046
+ });
2047
+ }
2048
+ }
2049
+
2050
+ // src/cli/call-requests.ts
2051
+ var callRequestFlags = { "request-id": { type: "string" } };
2052
+ var callRequestHelp = `
2053
+ CALL BOOKING RESULT / DURABLE REQUESTS
2054
+ calls bookings <call_id> ready | none | processing | deleted | unavailable
2055
+ calls outboundRequest <UUID> pending | accepted | rejected | unknown; GET only
2056
+ calls prepare --agent ID --to +44... --prompt TEXT|@file [--from +44...] [--var k=v] [--body @file]
2057
+ [--output prepared.json | --json]
2058
+ Generate a UUID locally; sends NOTHING. --output never overwrites.
2059
+ calls create --body @prepared.json Send the saved body once. Reuse it unchanged only after checking.
2060
+ calls create ... --request-id UUID Explicit existing UUID; no automatic retry/new ID.
2061
+ Save prepare's JSON before first send. It contains your call inputs; keep it private.
2062
+ After an uncertain result read the request and Call History; never run prepare again as a retry.
2063
+ `;
2064
+ function withCallRequestId(body, value) {
2065
+ if (value === void 0) return body;
2066
+ const id = requestId(value);
2067
+ if (body.request_id !== void 0 && requestId(body.request_id).toLowerCase() !== id.toLowerCase()) throw new Error("Supply request_id once, or use the same UUID in both places.");
2068
+ return { ...body, request_id: id };
2069
+ }
2070
+ async function prepareCallCli(values, body, prompt) {
2071
+ const vars2 = {};
2072
+ for (const entry of values.var || []) {
2073
+ const at = entry.indexOf("=");
2074
+ if (at < 1) throw new Error("--var requires key=value.");
2075
+ vars2[entry.slice(0, at)] = entry.slice(at + 1);
2076
+ }
2077
+ const named = { agent_id: values.agent, to_number: values.to, from_number: values.from, prompt, ...contactFields(values) };
2078
+ const input = { ...body, ...Object.fromEntries(Object.entries(named).filter(([, v]) => v !== void 0)) };
2079
+ if (!input.agent_id || !input.to_number || !input.prompt) throw new Error("calls prepare requires agent, to number and prompt. No call was placed.");
2080
+ const prepared = prepareOutboundCall(withCallRequestId(callCreateBody(input, values.var === void 0 ? void 0 : vars2), values["request-id"]));
2081
+ if (values.output === void 0) return prepared;
2082
+ const chunks = async function* () {
2083
+ yield Buffer.from(JSON.stringify(prepared, null, 2) + "\n", "utf8");
2084
+ };
2085
+ const saved = await knowledgeOutput(chunks(), values.output);
2086
+ return { ...saved, request_id: prepared.request_id, sent: false };
2087
+ }
2088
+ async function callRequestRead(client, command, id) {
2089
+ if (!id) throw new Error("Supply the call ID or request UUID.");
2090
+ return command === "bookings" ? client.calls.bookings(id) : client.calls.outboundRequest(id);
2091
+ }
2092
+
2093
+ // src/cli/campaign-delete.ts
2094
+ async function deleteCampaign(client, id, confirmed) {
2095
+ if (!id) throw new Error("campaigns delete <campaign_id> --confirm");
2096
+ if (!confirmed) return {
2097
+ would_delete: "voice campaign " + id,
2098
+ warning: "Waiting work will be cancelled and running calls ended. History and used charges remain; no refund.",
2099
+ hint: "Add --confirm to proceed. A queued hang-up is not a completed deletion."
2100
+ };
2101
+ return client.campaigns.delete(id);
2102
+ }
2103
+
2104
+ // src/cli/knowledge-plan.ts
2105
+ var knowledgePlan = [
2106
+ { "name": "deleteScope", "method": "DELETE", "params": ["target"], "mutating": true, "body": true, "query": false },
2107
+ { "name": "getScope", "method": "GET", "params": ["target"], "mutating": false, "body": false, "query": false },
2108
+ { "name": "putScope", "method": "PUT", "params": ["target"], "mutating": true, "body": true, "query": false },
2109
+ { "name": "measureSource", "method": "POST", "params": ["target"], "mutating": false, "body": true, "query": false },
2110
+ { "name": "startSession", "method": "POST", "params": ["target"], "mutating": true, "body": true, "query": false },
2111
+ { "name": "getBase", "method": "GET", "params": ["kb"], "mutating": false, "body": false, "query": false },
2112
+ { "name": "discardDraft", "method": "DELETE", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2113
+ { "name": "getDraft", "method": "GET", "params": ["kb", "id"], "mutating": false, "body": false, "query": false },
2114
+ { "name": "updateDraft", "method": "PATCH", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2115
+ { "name": "acceptDraft", "method": "POST", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2116
+ { "name": "createExport", "method": "POST", "params": ["kb"], "mutating": true, "body": true, "query": false },
2117
+ { "name": "overview", "method": "GET", "params": ["kb"], "mutating": false, "body": false, "query": false },
2118
+ { "name": "updateSettings", "method": "PATCH", "params": ["kb"], "mutating": true, "body": true, "query": false },
2119
+ { "name": "listSources", "method": "GET", "params": ["kb"], "mutating": false, "body": false, "query": true },
2120
+ { "name": "addSource", "method": "POST", "params": ["kb"], "mutating": true, "body": true, "query": false },
2121
+ { "name": "deleteSource", "method": "DELETE", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2122
+ { "name": "renameSource", "method": "PATCH", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2123
+ { "name": "replaceSource", "method": "POST", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2124
+ { "name": "refreshSources", "method": "POST", "params": ["kb"], "mutating": true, "body": true, "query": false },
2125
+ { "name": "searchTopics", "method": "POST", "params": ["kb"], "mutating": false, "body": true, "query": false },
2126
+ { "name": "listTopics", "method": "GET", "params": ["kb"], "mutating": false, "body": false, "query": true },
2127
+ { "name": "createTopic", "method": "POST", "params": ["kb"], "mutating": true, "body": true, "query": false },
2128
+ { "name": "deleteTopic", "method": "DELETE", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2129
+ { "name": "getTopic", "method": "GET", "params": ["kb", "id"], "mutating": false, "body": false, "query": false },
2130
+ { "name": "updateTopic", "method": "PATCH", "params": ["kb", "id"], "mutating": true, "body": true, "query": false },
2131
+ { "name": "unanswered", "method": "GET", "params": ["kb"], "mutating": false, "body": false, "query": true },
2132
+ { "name": "discoverWebsite", "method": "POST", "params": ["kb"], "mutating": true, "body": true, "query": false },
2133
+ { "name": "importWebsite", "method": "POST", "params": ["kb"], "mutating": true, "body": true, "query": false },
2134
+ { "name": "capabilities", "method": "GET", "params": [], "mutating": false, "body": false, "query": false },
2135
+ { "name": "events", "method": "GET", "params": [], "mutating": false, "body": false, "query": true },
2136
+ { "name": "downloadExport", "method": "GET", "params": ["id"], "mutating": false, "body": false, "query": true },
2137
+ { "name": "getJob", "method": "GET", "params": ["id"], "mutating": false, "body": false, "query": false },
2138
+ { "name": "cancelJob", "method": "POST", "params": ["id"], "mutating": true, "body": true, "query": false },
2139
+ { "name": "retryJob", "method": "POST", "params": ["id"], "mutating": true, "body": true, "query": false },
2140
+ { "name": "targets", "method": "GET", "params": [], "mutating": false, "body": false, "query": true },
2141
+ { "name": "getSession", "method": "GET", "params": ["id"], "mutating": false, "body": false, "query": false },
2142
+ { "name": "cancelSession", "method": "POST", "params": ["id"], "mutating": true, "body": true, "query": false },
2143
+ { "name": "ask", "method": "POST", "params": ["id"], "mutating": true, "body": true, "query": false },
2144
+ { "name": "usage", "method": "GET", "params": [], "mutating": false, "body": false, "query": true },
2145
+ { "name": "keyterms", "method": "GET", "params": ["target"], "mutating": false, "body": false, "query": false }
2146
+ ];
2147
+ var knowledgeHelp = "\nKNOWLEDGE (private customer content; use private JSON files for inputs)\n knowledge deleteScope <target> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge getScope <target>\n knowledge putScope <target> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge measureSource <target> --body @input.json --confirm\n knowledge startSession <target> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge getBase <kb>\n knowledge discardDraft <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge getDraft <kb> <id>\n knowledge updateDraft <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge acceptDraft <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge createExport <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge overview <kb>\n knowledge updateSettings <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge listSources <kb> --body @query.json\n knowledge addSource <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge deleteSource <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge renameSource <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge replaceSource <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge refreshSources <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge searchTopics <kb> --body @input.json --confirm\n knowledge listTopics <kb> --body @query.json\n knowledge createTopic <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge deleteTopic <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge getTopic <kb> <id>\n knowledge updateTopic <kb> <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge unanswered <kb> --body @query.json\n knowledge discoverWebsite <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge importWebsite <kb> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge capabilities \n knowledge events --body @query.json\n knowledge downloadExport <id> --body @query.json --output FILE.json\n knowledge getJob <id>\n knowledge cancelJob <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge retryJob <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge targets --body @query.json\n knowledge getSession <id>\n knowledge cancelSession <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge ask <id> --body @input.json --idempotency-key OPERATION_KEY --confirm\n knowledge usage --body @query.json\n knowledge keyterms <target>\n knowledge uploadSource <kb> --file FILE --idempotency-key KEY --confirm\n knowledge replaceSourceFile <kb> <id> --file FILE --expected-revision N --idempotency-key KEY --confirm\n knowledge measureFile <target> --file FILE --confirm\n knowledge waitJob <id> --timeout SECONDS\n Upload options: --filename ASCII_NAME --source-title ASCII_TITLE --review true|false\n POST measureSource/searchTopics also require --confirm; they never auto-retry.\n File uploads stream, maximum 10 MiB. Downloads stream exact JSON envelopes.\n Even format=text downloads are JSON with filename/content_type/text, not a raw TXT response.\n Job polling defaults: 20 attempts, 1 second interval, 30 second timeout; --wait applies only to returned jobs.\n needs_review/failed/cancelled/deleted are real stop states, never treated as successful publication.\n Keep revisions numeric, event cursors strings; follow next_cursor, do not invent offsets.\n Private responses are returned only when explicitly requested; no progress content is logged.\n";
2148
+
2149
+ // src/cli/knowledge.ts
2150
+ var safeCodes = /* @__PURE__ */ new Set([
2151
+ "invalid_input",
2152
+ "invalid_filter",
2153
+ "not_found",
2154
+ "unauthorized",
2155
+ "permission_denied",
2156
+ "stale_revision",
2157
+ "knowledge_missing",
2158
+ "session_closed",
2159
+ "target_changed",
2160
+ "knowledge_disabled",
2161
+ "busy",
2162
+ "idempotency_conflict",
2163
+ "export_expired",
2164
+ "source_limit",
2165
+ "unavailable",
2166
+ "retry_unavailable"
2167
+ ]);
2168
+ var knowledgeFlags = {
2169
+ file: { type: "string" },
2170
+ filename: { type: "string" },
2171
+ "source-title": { type: "string" },
2172
+ "idempotency-key": { type: "string" },
2173
+ review: { type: "string" },
2174
+ "expected-revision": { type: "string" }
2175
+ };
2176
+ async function knowledgeCommand(c, positions, values, body, confirmed) {
2177
+ const [, name, ...ids] = positions;
2178
+ const operation = knowledgePlan.find((row2) => row2.name === name);
2179
+ const file = ["uploadSource", "replaceSourceFile", "measureFile"].includes(name);
2180
+ if (!operation && !file && name !== "waitJob") throw new Error("Unknown knowledge command. Run nixflex --help.");
2181
+ if ((file || (operation == null ? void 0 : operation.method) !== "GET" && name !== "waitJob") && !confirmed)
2182
+ return { confirmation_required: true, sent: false, hint: "No request sent. Review the action, then add --confirm." };
2183
+ const options = {};
2184
+ if (values["idempotency-key"] !== void 0) options.idempotencyKey = values["idempotency-key"];
2185
+ if (values.timeout !== void 0) {
2186
+ const timeout = Number(values.timeout);
2187
+ if (!Number.isFinite(timeout) || timeout <= 0 || timeout > 300) throw new Error("Timeout must be 0..300 seconds.");
2188
+ options.timeoutMs = timeout * 1e3;
2189
+ }
2190
+ const api = c.knowledge;
2191
+ try {
2192
+ if (name === "waitJob") {
2193
+ if (ids.length !== 1) throw new TypeError("Supply one job ID.");
2194
+ return await c.knowledge.waitJob(ids[0], { timeoutMs: options.timeoutMs });
2195
+ }
2196
+ if (file) {
2197
+ const count = name === "replaceSourceFile" ? 2 : 1;
2198
+ if (ids.length !== count || typeof values.file !== "string") throw new TypeError("Supply identifiers and --file FILE.");
2199
+ if (values.review !== void 0) {
2200
+ if (!["true", "false"].includes(String(values.review))) throw new TypeError("Review must be true or false.");
2201
+ options.review = values.review === "true";
2202
+ }
2203
+ if (values["expected-revision"] !== void 0) options.expectedRevision = Number(values["expected-revision"]);
2204
+ if (values.filename !== void 0) options.filename = values.filename;
2205
+ if (values["source-title"] !== void 0) options.sourceTitle = values["source-title"];
2206
+ return await api[name](...ids, values.file, options);
2207
+ }
2208
+ if (!operation || ids.length !== operation.params.length) throw new TypeError("Supply the required knowledge identifiers.");
2209
+ const args = [...ids];
2210
+ if (operation.body || operation.query) args.push(body);
2211
+ args.push(options);
2212
+ if (name === "downloadExport")
2213
+ return await knowledgeOutput(api[name](...args), values.output);
2214
+ const result = await api[name](...args);
2215
+ if (values.wait === true && (result == null ? void 0 : result.id) && typeof result.state === "string")
2216
+ return await c.knowledge.waitJob(result.id, { timeoutMs: options.timeoutMs });
2217
+ return result;
2218
+ } catch (error) {
2219
+ const e = error;
2220
+ const status = Number.isInteger(e.status) && e.status >= 0 && e.status <= 599 ? e.status : 0;
2221
+ const code = e.code === "outcome_unknown" ? "outcome_unknown" : safeCodes.has(e.code || "") ? e.code : "knowledge_request_failed";
2222
+ const unknown = code === "outcome_unknown";
2223
+ if (unknown) throw new NixflexOutcomeUnknownError(status);
2224
+ throw new NixflexError(status || 0, { error: {
2225
+ type: "request_failed",
2226
+ code,
2227
+ message: "Knowledge request failed. Check identifiers, input, revision and operation key."
2228
+ } });
2229
+ }
2230
+ }
2231
+
2232
+ // src/cli/activity-export.ts
2233
+ import { open as open3, link as link2, unlink as unlink2 } from "fs/promises";
2234
+ import { randomUUID as randomUUID3 } from "crypto";
2235
+ function activityFilters(body) {
2236
+ const filters = {};
2237
+ for (const key of ["from", "to", "actor", "before"]) {
2238
+ const value = body[key];
2239
+ if (value === void 0) continue;
2240
+ if (key === "before" && typeof value === "number" && Number.isSafeInteger(value)) filters[key] = String(value);
2241
+ else if (typeof value === "string") filters[key] = value;
2242
+ else throw new Error("Activity filters must be strings; quote long cursors in a JSON body.");
2243
+ }
2244
+ return filters;
2245
+ }
2246
+ async function activityExport(c, output, body) {
2247
+ if (!output) throw new Error("Use --output FILE for CSV export. Existing files are never overwritten.");
2248
+ const filters = activityFilters(body);
2249
+ const partial = output + ".partial-" + randomUUID3();
2250
+ const file = await open3(partial, "wx", 384);
2251
+ let bytes = 0;
2252
+ try {
2253
+ for await (const chunk of c.organisation.activityCsv(filters)) {
2254
+ let offset = 0;
2255
+ while (offset < chunk.length) {
2256
+ const result = await file.write(chunk, offset, chunk.length - offset);
2257
+ if (!result.bytesWritten) throw new Error("CSV output could not be written.");
2258
+ offset += result.bytesWritten;
2259
+ }
2260
+ bytes += chunk.length;
2261
+ }
2262
+ await file.sync();
2263
+ await file.close();
2264
+ await link2(partial, output);
2265
+ return { saved: true, bytes, file: output };
2266
+ } finally {
2267
+ await file.close().catch(() => {
2268
+ });
2269
+ await unlink2(partial).catch(() => {
2270
+ });
2271
+ }
2272
+ }
2273
+
2274
+ // src/cli/organisation.ts
2275
+ var organisationHelp = "\nORGANISATION (candidate; not enabled)\n" + [
2276
+ "organisation rename --set name=Business --confirm",
2277
+ "organisation activityCsv --output activity.csv [--set from=2026-10-01 --set to=2026-10-31]",
2278
+ "organisation get",
2279
+ "organisation members",
2280
+ "organisation activity [--set before=123 --set actor=UUID]",
2281
+ "organisation invite --set email=person@example.com --set role=member",
2282
+ "organisation claim --set email=owner@example.com",
2283
+ "organisation resend INVITE_ID",
2284
+ "organisation revoke INVITE_ID",
2285
+ "organisation remove USER_ID",
2286
+ "organisation role USER_ID --set role=admin",
2287
+ "organisation removeMember USER_ID (alias of remove)",
2288
+ "organisation setRole USER_ID --set role=admin (alias of role)",
2289
+ "organisation claimInvite --set email=owner@example.com (alias of claim)"
2290
+ ].map((line) => " " + line).join("\n") + "\nChanges preview unless --confirm is supplied. Personal owner actions require the dashboard.\n";
2291
+ async function organisationCommand(client, command, id, body, confirmed) {
2292
+ const org = client.organisation;
2293
+ command = { removeMember: "remove", setRole: "role", claimInvite: "claim" }[command] || command;
2294
+ if (command === "get") return org.get();
2295
+ if (command === "members") return org.members();
2296
+ if (command === "activity") return org.activity(activityFilters(body));
2297
+ if (!["invite", "claim", "resend", "revoke", "remove", "role", "rename"].includes(command)) throw Error("organisation: get | members | activity | invite | claim | resend | revoke | remove | role");
2298
+ if (!confirmed) return { would_change: "organisation " + command, target: id || body.email || null, hint: "Review the person or invitation, then add --confirm. Removal never rolls the shared API key." };
2299
+ if (command === "rename") {
2300
+ if (typeof body.name !== "string") throw Error("Supply --set name=Business");
2301
+ return org.rename(body.name);
2302
+ }
2303
+ if (["invite", "claim"].includes(command)) {
2304
+ if (typeof body.email !== "string" || !body.email.includes("@")) throw Error("Pass --set email=person@example.com");
2305
+ if (command === "claim") return org.claimInvite(body.email);
2306
+ const role = body.role === void 0 ? "member" : body.role;
2307
+ if (role !== "member" && role !== "admin") throw Error("Use --set role=member or role=admin");
2308
+ return org.invite(body.email, role);
2309
+ }
2310
+ if (!id) throw Error("Pass the person or invitation ID.");
2311
+ if (command === "resend") return org.resend(id);
2312
+ if (command === "revoke") return org.revoke(id);
2313
+ if (command === "remove") return org.removeMember(id);
2314
+ if (body.role !== "admin" && body.role !== "member") throw Error("Use --set role=member or role=admin");
2315
+ return org.setRole(id, body.role);
2316
+ }
2317
+
2318
+ // src/cli/core.ts
2319
+ var coreGroups = ["account", "voices"];
2320
+ var coreFlags = {
2321
+ gender: { type: "string" },
2322
+ locale: { type: "string" },
2323
+ availability: { type: "string" },
2324
+ "agent-language": { type: "string" }
2325
+ };
2326
+ var coreHelp = `
2327
+ CORE READS
2328
+ calls list [--limit N] [--offset N] legacy array; --agent selects filtered history
2329
+ callers import <number> --body @callers.json preserves null clears and numeric values
2330
+ account retention saved default for new agents; not proof of erasure
2331
+ keys activity [--period today|7d]
2332
+ voices list [--language en] [--gender female|male|unknown] [--locale en-GB]
2333
+ [--agent ID | --agent-language multi] [--availability active|all] [--limit N] [--cursor CURSOR]
2334
+ voices get <voice_key> [--agent ID | --agent-language multi]
2335
+ keys create [--name NAME] [--email EMAIL] --confirm --json
2336
+ unauthenticated, separate API-only account; no automatic retry
2337
+ redirect stdout to your secret store; never print/share the returned secret
2338
+ `;
2339
+ async function createAccount(body, confirmed, baseUrl) {
2340
+ if (!confirmed) return {
2341
+ would_create: "A separate API-only account (not an extra key on this account)",
2342
+ warning: "The result contains a secret. Save it securely; do not log it. No public account deletion API exists.",
2343
+ hint: "Add --confirm only for intentional signup. A lost response must be reconciled, never blindly repeated."
2344
+ };
2345
+ for (const [key, value] of Object.entries(body)) {
2346
+ if (!["name", "email"].includes(key) || value !== null && typeof value !== "string")
2347
+ throw new Error("keys create accepts only name and email (string or null).");
2348
+ }
2349
+ return src_default.createKey(body, baseUrl);
2350
+ }
2351
+ async function coreRead(client, group, cmd, id, values) {
2352
+ const s = (key) => values[key];
2353
+ if (group === "account" && cmd === "retention") return client.account.retention();
2354
+ if (group === "keys" && cmd === "activity")
2355
+ return client.keys.activity({ period: s("period") });
2356
+ if (group === "voices") {
2357
+ const context = { agent_id: s("agent"), agent_language: s("agent-language") };
2358
+ if (cmd === "get" && id) return client.voices.get(id, context);
2359
+ if (cmd === "list") return client.voices.list({
2360
+ ...context,
2361
+ language: s("language"),
2362
+ gender: s("gender"),
2363
+ locale: s("locale"),
2364
+ availability: s("availability"),
2365
+ limit: s("limit") === void 0 ? void 0 : Number(s("limit")),
2366
+ cursor: s("cursor")
2367
+ });
2368
+ }
2369
+ throw new Error("Use account retention, keys activity, voices list, or voices get <voice_key>.");
2370
+ }
2371
+
2372
+ // src/cli/c5.ts
2373
+ var c5Groups = ["contacts", "web-agent", "inbox"];
2374
+ var c5Flags = Object.fromEntries(["channel", "after", "archived", "unread", "before-id", "thread", "number"].map((key) => [key, { type: "string" }]));
2375
+ var c5Help = `
2376
+ C5 CAMPAIGNS AND CONVERSATIONS
2377
+ campaigns list [--status S] [--limit N] default 50; cap 200; no cursor
2378
+ campaigns cancel <id> --confirm in-progress work may finish
2379
+ campaigns consent <id> --body @consent.json --confirm
2380
+ campaigns resume <id> --confirm one page only; may dial real people
2381
+ sms campaigns update <id> --body @settings.json --confirm
2382
+ sms campaigns cancel <id> --confirm
2383
+ sms campaigns consent <id> --body @consent.json --confirm
2384
+ sms campaigns resume <id> --confirm one page only; may send real texts
2385
+ contacts preview --body @preview.json advisory, not permission to contact
2386
+ contacts list [--channel all|voice|sms] [--after NUMBER] separate buckets, 200/page
2387
+ contacts add --body @numbers.json --confirm
2388
+ contacts remove --body @number.json --confirm may enable scheduled outreach
2389
+ web-agent get <number>
2390
+ web-agent update <number> --body @settings.json --confirm string revision, full appearance
2391
+ inbox list <sms|web> <number> [--archived true|false] [--unread true|false]
2392
+ [--search TEXT] [--since ISO | --period all|today|7|30|90] [--limit N] [--offset N]
2393
+ inbox thread <sms|web> <number> --thread ID [--limit N] [--before ISO --before-id ID]
2394
+ inbox update <sms|web> <number> --thread ID --body @change.json --confirm
2395
+ inbox features
2396
+ inbox numbers [--offset N] 100/page; agents capped at 1,000
2397
+ inbox retention [--number NUMBER]
2398
+ Reads never acknowledge messages. Preserve string read_version; archive is not erasure.
2399
+ Campaign creation is executable work, NOT a draft. Writes never auto-retry.
2400
+ `;
2401
+ function isC5(group, cmd, sub) {
2402
+ return c5Groups.includes(group) || group === "campaigns" && ["list", "cancel", "consent", "resume"].includes(cmd) || group === "sms" && cmd === "campaigns" && ["update", "cancel", "consent", "resume"].includes(sub || "");
2403
+ }
2404
+ async function c5Command(c, pos, values, body, confirmed) {
2405
+ const [group, cmd, a1, a2] = pos;
2406
+ const str = (key) => values[key];
2407
+ const num = (key) => values[key] === void 0 ? void 0 : Number(values[key]);
2408
+ const bool = (key) => {
2409
+ if (values[key] === void 0) return void 0;
2410
+ if (values[key] !== "true" && values[key] !== "false") throw new Error("--" + key + " must be true or false.");
2411
+ return values[key] === "true";
2412
+ };
2413
+ const required = (value, name) => {
2414
+ if (!value) throw new Error("Supply " + name + ".");
2415
+ return value;
2416
+ };
2417
+ const write = async (action) => confirmed ? action() : {
2418
+ confirmation_required: true,
2419
+ hint: "No request sent. Add --confirm only for this intentional change. Never repeat an uncertain write."
2420
+ };
2421
+ if (group === "campaigns" || group === "sms") {
2422
+ const action = group === "sms" ? a1 : cmd;
2423
+ const resource = group === "sms" ? c.sms.campaigns : c.campaigns;
2424
+ if (action === "list") return c.campaigns.list({ status: str("status"), limit: num("limit") });
2425
+ const id = required(group === "sms" ? a2 : a1, "campaign id");
2426
+ if (action === "cancel") return write(() => resource.cancel(id));
2427
+ if (action === "resume") return write(() => resource.resume(id));
2428
+ if (action === "consent") return write(() => resource.consent(id, body));
2429
+ if (group === "sms" && action === "update") return write(() => c.sms.campaigns.update(id, body));
2430
+ }
2431
+ if (group === "contacts") {
2432
+ if (cmd === "preview") return c.contacts.preview(body);
2433
+ if (cmd === "list") return c.contacts.list({ channel: str("channel"), after: str("after") });
2434
+ if (cmd === "add") return write(() => c.contacts.add(body));
2435
+ if (cmd === "remove") return write(() => c.contacts.remove(body));
2436
+ }
2437
+ if (group === "web-agent") {
2438
+ const number = required(a1, "number");
2439
+ if (cmd === "get") return c.webAgent.get(number);
2440
+ if (cmd === "update") return write(() => c.webAgent.update(number, body));
2441
+ }
2442
+ if (group === "inbox") {
2443
+ if (cmd === "features") return c.inbox.features();
2444
+ if (cmd === "numbers") return c.inbox.numbers({ offset: num("offset") });
2445
+ if (cmd === "retention") return c.inbox.retention({ number: str("number") });
2446
+ const channel = required(a1, "channel"), number = required(a2, "number");
2447
+ if (cmd === "list") return c.inbox.list(channel, number, {
2448
+ archived: bool("archived"),
2449
+ unread: bool("unread"),
2450
+ search: str("search"),
2451
+ since: str("since"),
2452
+ period: str("period"),
2453
+ limit: num("limit"),
2454
+ offset: num("offset")
2455
+ });
2456
+ const thread = required(str("thread"), "--thread");
2457
+ if (cmd === "thread") return c.inbox.thread(channel, number, thread, { limit: num("limit"), before: str("before"), before_id: str("before-id") });
2458
+ if (cmd === "update") return write(() => c.inbox.update(channel, number, thread, body));
2459
+ }
2460
+ throw new Error("Unknown C5 command. Run nixflex --help.");
2461
+ }
2462
+
2463
+ // src/cli/core-fields.ts
2464
+ function coreCallList(client, values) {
2465
+ const integer = (key) => values[key] === void 0 ? void 0 : Number(values[key]);
2466
+ const params = { limit: integer("limit"), offset: integer("offset") };
2467
+ return values.agent ? client.calls.history({ ...params, agent: String(values.agent) }) : client.calls.list(params);
2468
+ }
2469
+ function coreCallerImport(client, number, body) {
2470
+ if (!number || !Array.isArray(body.callers)) throw new Error("callers import <number> --body @callers.json (object with callers array)");
2471
+ return client.callers.import(number, body.callers);
2472
+ }
2473
+
2474
+ // src/cli/mcp/setup.mjs
2475
+ import { homedir as homedir2 } from "os";
2476
+ import { join as join3, resolve } from "path";
2477
+ import { readFileSync as readFileSync3, realpathSync, statSync } from "fs";
2478
+ import { createInterface } from "readline/promises";
2479
+
2480
+ // src/cli/mcp/connection.mjs
2481
+ import { readFileSync } from "fs";
2482
+ import { homedir } from "os";
2483
+ import { join, isAbsolute } from "path";
2484
+
2485
+ // src/cli/mcp/origins.mjs
2486
+ var APPROVED_ORIGINS = Object.freeze([
2487
+ "https://api.nixflex.com",
2488
+ "https://nixflex-voice-engine-staging.up.railway.app"
2489
+ ]);
2490
+ function approvedOrigin(value) {
2491
+ if (typeof value !== "string" || value !== value.trim() || /[\\\s]/.test(value))
2492
+ throw new Error("MCP API destination must be an approved HTTPS Nixflex origin.");
2493
+ let url;
2494
+ try {
2495
+ url = new URL(value);
2496
+ } catch {
2497
+ throw new Error("Invalid MCP API destination.");
2498
+ }
2499
+ if (url.username || url.password || url.search || url.hash || url.pathname !== "/" || !APPROVED_ORIGINS.includes(url.origin))
2500
+ throw new Error("MCP API destination must be an approved HTTPS Nixflex origin.");
2501
+ return url.origin;
2502
+ }
2503
+
2504
+ // src/cli/mcp/connection.mjs
2505
+ function readLegacy(file, read = readFileSync) {
2506
+ let raw;
2507
+ try {
2508
+ raw = read(file, "utf8");
2509
+ } catch (error) {
2510
+ if (error.code === "ENOENT") throw new Error("No MCP credentials. Use a full key and explicit API URL in the client environment, or an existing nixflex login file.");
2511
+ throw new Error("Cannot read the Nixflex credential file; no fallback was used.");
2512
+ }
2513
+ let cfg;
2514
+ try {
2515
+ cfg = JSON.parse(raw);
2516
+ } catch {
2517
+ throw new Error("Malformed Nixflex credential file; no fallback was used.");
2518
+ }
2519
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg))
2520
+ throw new Error("Invalid Nixflex credential file.");
2521
+ return cfg;
2522
+ }
2523
+ function resolveConnection({ env = process.env, home = homedir(), read = readFileSync } = {}) {
2524
+ var _a;
2525
+ const source = env.NIXFLEX_CREDENTIAL_SOURCE || (env.NIXFLEX_API_KEY ? "environment" : "legacy");
2526
+ if (!["environment", "legacy"].includes(source)) throw new Error("Invalid MCP credential source.");
2527
+ let key, baseUrl, configFile;
2528
+ if (source === "environment") {
2529
+ if (env.NIXFLEX_PROFILE) throw new Error("Choose an environment pair or a legacy profile, not both.");
2530
+ if (!env.NIXFLEX_BASE_URL) throw new Error("NIXFLEX_BASE_URL is required with an environment key; no production default was used.");
2531
+ key = env.NIXFLEX_API_KEY;
2532
+ baseUrl = approvedOrigin(env.NIXFLEX_BASE_URL);
2533
+ } else {
2534
+ configFile = env.NIXFLEX_CONFIG_FILE || join(home, ".nixflex", "config.json");
2535
+ if (!isAbsolute(configFile)) throw new Error("NIXFLEX_CONFIG_FILE must be an absolute path.");
2536
+ let cfg = readLegacy(configFile, read);
2537
+ if (env.NIXFLEX_PROFILE) {
2538
+ const name = env.NIXFLEX_PROFILE;
2539
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(name) || !cfg.profiles || !Object.hasOwn(cfg.profiles, name) || !((_a = cfg.profiles[name]) == null ? void 0 : _a.base_url))
2540
+ throw new Error("Legacy MCP profile missing or has no explicit API URL; no fallback was used.");
2541
+ cfg = cfg.profiles[name];
2542
+ }
2543
+ key = cfg.api_key;
2544
+ baseUrl = approvedOrigin(cfg.base_url === void 0 ? APPROVED_ORIGINS[0] : cfg.base_url);
2545
+ if (env.NIXFLEX_BASE_URL && approvedOrigin(env.NIXFLEX_BASE_URL) !== baseUrl)
2546
+ throw new Error("MCP credential file destination changed or conflicts with this installation; refusing to retarget the key.");
2547
+ }
2548
+ if (typeof key !== "string" || !/^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i.test(key))
2549
+ throw new Error("Missing or invalid full MCP API key. No request was sent.");
2550
+ return { key, baseUrl, source, configFile, profile: env.NIXFLEX_PROFILE };
2551
+ }
2552
+
2553
+ // src/cli/mcp/launch.mjs
2554
+ var SUPPORTED_CLIENTS = Object.freeze(["claude", "claude-code", "codex", "cursor"]);
2555
+ function buildServerConfig({ client, platform, version, baseUrl, source = "environment", configFile, profile }) {
2556
+ if (!SUPPORTED_CLIENTS.includes(client)) throw new Error("Supported tools: Claude Desktop, Claude Code, Codex and Cursor. VS Code setup is retired.");
2557
+ if (!["win32", "darwin", "linux"].includes(platform) || client === "claude" && platform === "linux")
2558
+ throw new Error("This client/platform combination is not supported.");
2559
+ if (typeof version !== "string" || version !== version.trim() || !/^\d+\.\d+\.\d+$/.test(version)) throw new Error("MCP launch requires a fixed release version.");
2560
+ if (!["environment", "legacy"].includes(source)) throw new Error("Invalid credential source.");
2561
+ const origin = approvedOrigin(baseUrl);
2562
+ const env = { NIXFLEX_CREDENTIAL_SOURCE: source, NIXFLEX_BASE_URL: origin };
2563
+ if (source === "legacy") {
2564
+ if (typeof configFile !== "string" || !configFile || /[\r\n]/.test(configFile)) throw new Error("Missing credential file path.");
2565
+ env.NIXFLEX_CONFIG_FILE = configFile;
2566
+ if (profile) {
2567
+ if (!/^[a-zA-Z0-9_-]{1,64}$/.test(profile)) throw new Error("Invalid profile name.");
2568
+ env.NIXFLEX_PROFILE = profile;
2569
+ }
2570
+ }
2571
+ const entry = platform === "win32" ? { command: "cmd.exe", args: ["/d", "/s", "/c", "npx -y nixflex-mcp@" + version], env } : { command: "npx", args: ["-y", "nixflex-mcp@" + version], env };
2572
+ if (source === "environment" && client === "cursor") env.NIXFLEX_API_KEY = "${env:NIXFLEX_API_KEY}";
2573
+ if (source === "environment" && client === "codex") entry.env_vars = ["NIXFLEX_API_KEY"];
2574
+ return entry;
2575
+ }
2576
+ function serverName(baseUrl) {
2577
+ return approvedOrigin(baseUrl) === "https://api.nixflex.com" ? "nixflex" : "nixflex-staging";
2578
+ }
2579
+
2580
+ // src/cli/mcp/config-write.mjs
2581
+ import { readFileSync as readFileSync2, lstatSync, mkdirSync, openSync, closeSync, writeFileSync, fsyncSync, renameSync, unlinkSync, linkSync } from "fs";
2582
+ import { dirname, join as join2 } from "path";
2583
+ import { randomUUID as randomUUID4 } from "crypto";
2584
+
2585
+ // node_modules/jsonc-parser/lib/esm/impl/scanner.js
2586
+ function createScanner(text, ignoreTrivia = false) {
2587
+ const len = text.length;
2588
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
2589
+ function scanHexDigits(count, exact) {
2590
+ let digits = 0;
2591
+ let value2 = 0;
2592
+ while (digits < count || !exact) {
2593
+ let ch = text.charCodeAt(pos);
2594
+ if (ch >= 48 && ch <= 57) {
2595
+ value2 = value2 * 16 + ch - 48;
2596
+ } else if (ch >= 65 && ch <= 70) {
2597
+ value2 = value2 * 16 + ch - 65 + 10;
2598
+ } else if (ch >= 97 && ch <= 102) {
2599
+ value2 = value2 * 16 + ch - 97 + 10;
2600
+ } else {
2601
+ break;
2602
+ }
2603
+ pos++;
2604
+ digits++;
2605
+ }
2606
+ if (digits < count) {
2607
+ value2 = -1;
2608
+ }
2609
+ return value2;
2610
+ }
2611
+ function setPosition(newPosition) {
2612
+ pos = newPosition;
2613
+ value = "";
2614
+ tokenOffset = 0;
2615
+ token = 16;
2616
+ scanError = 0;
2617
+ }
2618
+ function scanNumber() {
2619
+ let start = pos;
2620
+ if (text.charCodeAt(pos) === 48) {
2621
+ pos++;
2622
+ } else {
2623
+ pos++;
2624
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
2625
+ pos++;
2626
+ }
2627
+ }
2628
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
2629
+ pos++;
2630
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
2631
+ pos++;
2632
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
2633
+ pos++;
2634
+ }
2635
+ } else {
2636
+ scanError = 3;
2637
+ return text.substring(start, pos);
2638
+ }
2639
+ }
2640
+ let end = pos;
2641
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
2642
+ pos++;
2643
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
2644
+ pos++;
2645
+ }
2646
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
2647
+ pos++;
2648
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) {
2649
+ pos++;
2650
+ }
2651
+ end = pos;
2652
+ } else {
2653
+ scanError = 3;
2654
+ }
2655
+ }
2656
+ return text.substring(start, end);
2657
+ }
2658
+ function scanString() {
2659
+ let result = "", start = pos;
2660
+ while (true) {
2661
+ if (pos >= len) {
2662
+ result += text.substring(start, pos);
2663
+ scanError = 2;
2664
+ break;
2665
+ }
2666
+ const ch = text.charCodeAt(pos);
2667
+ if (ch === 34) {
2668
+ result += text.substring(start, pos);
2669
+ pos++;
2670
+ break;
2671
+ }
2672
+ if (ch === 92) {
2673
+ result += text.substring(start, pos);
2674
+ pos++;
2675
+ if (pos >= len) {
2676
+ scanError = 2;
2677
+ break;
2678
+ }
2679
+ const ch2 = text.charCodeAt(pos++);
2680
+ switch (ch2) {
2681
+ case 34:
2682
+ result += '"';
2683
+ break;
2684
+ case 92:
2685
+ result += "\\";
2686
+ break;
2687
+ case 47:
2688
+ result += "/";
2689
+ break;
2690
+ case 98:
2691
+ result += "\b";
2692
+ break;
2693
+ case 102:
2694
+ result += "\f";
2695
+ break;
2696
+ case 110:
2697
+ result += "\n";
2698
+ break;
2699
+ case 114:
2700
+ result += "\r";
2701
+ break;
2702
+ case 116:
2703
+ result += " ";
2704
+ break;
2705
+ case 117:
2706
+ const ch3 = scanHexDigits(4, true);
2707
+ if (ch3 >= 0) {
2708
+ result += String.fromCharCode(ch3);
2709
+ } else {
2710
+ scanError = 4;
2711
+ }
2712
+ break;
2713
+ default:
2714
+ scanError = 5;
2715
+ }
2716
+ start = pos;
2717
+ continue;
2718
+ }
2719
+ if (ch >= 0 && ch <= 31) {
2720
+ if (isLineBreak(ch)) {
2721
+ result += text.substring(start, pos);
2722
+ scanError = 2;
2723
+ break;
2724
+ } else {
2725
+ scanError = 6;
2726
+ }
2727
+ }
2728
+ pos++;
2729
+ }
2730
+ return result;
2731
+ }
2732
+ function scanNext() {
2733
+ value = "";
2734
+ scanError = 0;
2735
+ tokenOffset = pos;
2736
+ lineStartOffset = lineNumber;
2737
+ prevTokenLineStartOffset = tokenLineStartOffset;
2738
+ if (pos >= len) {
2739
+ tokenOffset = len;
2740
+ return token = 17;
2741
+ }
2742
+ let code = text.charCodeAt(pos);
2743
+ if (isWhiteSpace(code)) {
2744
+ do {
2745
+ pos++;
2746
+ value += String.fromCharCode(code);
2747
+ code = text.charCodeAt(pos);
2748
+ } while (isWhiteSpace(code));
2749
+ return token = 15;
2750
+ }
2751
+ if (isLineBreak(code)) {
2752
+ pos++;
2753
+ value += String.fromCharCode(code);
2754
+ if (code === 13 && text.charCodeAt(pos) === 10) {
2755
+ pos++;
2756
+ value += "\n";
2757
+ }
2758
+ lineNumber++;
2759
+ tokenLineStartOffset = pos;
2760
+ return token = 14;
2761
+ }
2762
+ switch (code) {
2763
+ // tokens: []{}:,
2764
+ case 123:
2765
+ pos++;
2766
+ return token = 1;
2767
+ case 125:
2768
+ pos++;
2769
+ return token = 2;
2770
+ case 91:
2771
+ pos++;
2772
+ return token = 3;
2773
+ case 93:
2774
+ pos++;
2775
+ return token = 4;
2776
+ case 58:
2777
+ pos++;
2778
+ return token = 6;
2779
+ case 44:
2780
+ pos++;
2781
+ return token = 5;
2782
+ // strings
2783
+ case 34:
2784
+ pos++;
2785
+ value = scanString();
2786
+ return token = 10;
2787
+ // comments
2788
+ case 47:
2789
+ const start = pos - 1;
2790
+ if (text.charCodeAt(pos + 1) === 47) {
2791
+ pos += 2;
2792
+ while (pos < len) {
2793
+ if (isLineBreak(text.charCodeAt(pos))) {
2794
+ break;
2795
+ }
2796
+ pos++;
2797
+ }
2798
+ value = text.substring(start, pos);
2799
+ return token = 12;
2800
+ }
2801
+ if (text.charCodeAt(pos + 1) === 42) {
2802
+ pos += 2;
2803
+ const safeLength = len - 1;
2804
+ let commentClosed = false;
2805
+ while (pos < safeLength) {
2806
+ const ch = text.charCodeAt(pos);
2807
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
2808
+ pos += 2;
2809
+ commentClosed = true;
2810
+ break;
2811
+ }
2812
+ pos++;
2813
+ if (isLineBreak(ch)) {
2814
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
2815
+ pos++;
2816
+ }
2817
+ lineNumber++;
2818
+ tokenLineStartOffset = pos;
2819
+ }
2820
+ }
2821
+ if (!commentClosed) {
2822
+ pos++;
2823
+ scanError = 1;
2824
+ }
2825
+ value = text.substring(start, pos);
2826
+ return token = 13;
2827
+ }
2828
+ value += String.fromCharCode(code);
2829
+ pos++;
2830
+ return token = 16;
2831
+ // numbers
2832
+ case 45:
2833
+ value += String.fromCharCode(code);
2834
+ pos++;
2835
+ if (pos === len || !isDigit(text.charCodeAt(pos))) {
2836
+ return token = 16;
2837
+ }
2838
+ // found a minus, followed by a number so
2839
+ // we fall through to proceed with scanning
2840
+ // numbers
2841
+ case 48:
2842
+ case 49:
2843
+ case 50:
2844
+ case 51:
2845
+ case 52:
2846
+ case 53:
2847
+ case 54:
2848
+ case 55:
2849
+ case 56:
2850
+ case 57:
2851
+ value += scanNumber();
2852
+ return token = 11;
2853
+ // literals and unknown symbols
2854
+ default:
2855
+ while (pos < len && isUnknownContentCharacter(code)) {
2856
+ pos++;
2857
+ code = text.charCodeAt(pos);
2858
+ }
2859
+ if (tokenOffset !== pos) {
2860
+ value = text.substring(tokenOffset, pos);
2861
+ switch (value) {
2862
+ case "true":
2863
+ return token = 8;
2864
+ case "false":
2865
+ return token = 9;
2866
+ case "null":
2867
+ return token = 7;
2868
+ }
2869
+ return token = 16;
2870
+ }
2871
+ value += String.fromCharCode(code);
2872
+ pos++;
2873
+ return token = 16;
2874
+ }
2875
+ }
2876
+ function isUnknownContentCharacter(code) {
2877
+ if (isWhiteSpace(code) || isLineBreak(code)) {
2878
+ return false;
2879
+ }
2880
+ switch (code) {
2881
+ case 125:
2882
+ case 93:
2883
+ case 123:
2884
+ case 91:
2885
+ case 34:
2886
+ case 58:
2887
+ case 44:
2888
+ case 47:
2889
+ return false;
2890
+ }
2891
+ return true;
2892
+ }
2893
+ function scanNextNonTrivia() {
2894
+ let result;
2895
+ do {
2896
+ result = scanNext();
2897
+ } while (result >= 12 && result <= 15);
2898
+ return result;
2899
+ }
2900
+ return {
2901
+ setPosition,
2902
+ getPosition: () => pos,
2903
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
2904
+ getToken: () => token,
2905
+ getTokenValue: () => value,
2906
+ getTokenOffset: () => tokenOffset,
2907
+ getTokenLength: () => pos - tokenOffset,
2908
+ getTokenStartLine: () => lineStartOffset,
2909
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
2910
+ getTokenError: () => scanError
2911
+ };
2912
+ }
2913
+ function isWhiteSpace(ch) {
2914
+ return ch === 32 || ch === 9;
2915
+ }
2916
+ function isLineBreak(ch) {
2917
+ return ch === 10 || ch === 13;
2918
+ }
2919
+ function isDigit(ch) {
2920
+ return ch >= 48 && ch <= 57;
2921
+ }
2922
+ var CharacterCodes;
2923
+ (function(CharacterCodes2) {
2924
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
2925
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
2926
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
2927
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
2928
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
2929
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
2930
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
2931
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
2932
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
2933
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
2934
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
2935
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
2936
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
2937
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
2938
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
2939
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
2940
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
2941
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
2942
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
2943
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
2944
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
2945
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
2946
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
2947
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
2948
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
2949
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
2950
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
2951
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
2952
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
2953
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
2954
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
2955
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
2956
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
2957
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
2958
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
2959
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
2960
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
2961
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
2962
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
2963
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
2964
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
2965
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
2966
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
2967
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
2968
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
2969
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
2970
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
2971
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
2972
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
2973
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
2974
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
2975
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
2976
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
2977
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
2978
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
2979
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
2980
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
2981
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
2982
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
2983
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
2984
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
2985
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
2986
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
2987
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
2988
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
2989
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
2990
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
2991
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
2992
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
2993
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
2994
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
2995
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
2996
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
2997
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
2998
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
2999
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
3000
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
3001
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
3002
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
3003
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
3004
+ })(CharacterCodes || (CharacterCodes = {}));
3005
+
3006
+ // node_modules/jsonc-parser/lib/esm/impl/string-intern.js
3007
+ var cachedSpaces = new Array(20).fill(0).map((_, index) => {
3008
+ return " ".repeat(index);
3009
+ });
3010
+ var maxCachedValues = 200;
3011
+ var cachedBreakLinesWithSpaces = {
3012
+ " ": {
3013
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
3014
+ return "\n" + " ".repeat(index);
3015
+ }),
3016
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
3017
+ return "\r" + " ".repeat(index);
3018
+ }),
3019
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
3020
+ return "\r\n" + " ".repeat(index);
3021
+ })
3022
+ },
3023
+ " ": {
3024
+ "\n": new Array(maxCachedValues).fill(0).map((_, index) => {
3025
+ return "\n" + " ".repeat(index);
3026
+ }),
3027
+ "\r": new Array(maxCachedValues).fill(0).map((_, index) => {
3028
+ return "\r" + " ".repeat(index);
3029
+ }),
3030
+ "\r\n": new Array(maxCachedValues).fill(0).map((_, index) => {
3031
+ return "\r\n" + " ".repeat(index);
3032
+ })
3033
+ }
3034
+ };
3035
+ var supportedEols = ["\n", "\r", "\r\n"];
3036
+
3037
+ // node_modules/jsonc-parser/lib/esm/impl/format.js
3038
+ function format(documentText, range, options) {
3039
+ let initialIndentLevel;
3040
+ let formatText;
3041
+ let formatTextStart;
3042
+ let rangeStart;
3043
+ let rangeEnd;
3044
+ if (range) {
3045
+ rangeStart = range.offset;
3046
+ rangeEnd = rangeStart + range.length;
3047
+ formatTextStart = rangeStart;
3048
+ while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {
3049
+ formatTextStart--;
3050
+ }
3051
+ let endOffset = rangeEnd;
3052
+ while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {
3053
+ endOffset++;
3054
+ }
3055
+ formatText = documentText.substring(formatTextStart, endOffset);
3056
+ initialIndentLevel = computeIndentLevel(formatText, options);
3057
+ } else {
3058
+ formatText = documentText;
3059
+ initialIndentLevel = 0;
3060
+ formatTextStart = 0;
3061
+ rangeStart = 0;
3062
+ rangeEnd = documentText.length;
3063
+ }
3064
+ const eol = getEOL(options, documentText);
3065
+ const eolFastPathSupported = supportedEols.includes(eol);
3066
+ let numberLineBreaks = 0;
3067
+ let indentLevel = 0;
3068
+ let indentValue;
3069
+ if (options.insertSpaces) {
3070
+ indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);
3071
+ } else {
3072
+ indentValue = " ";
3073
+ }
3074
+ const indentType = indentValue === " " ? " " : " ";
3075
+ let scanner = createScanner(formatText, false);
3076
+ let hasError = false;
3077
+ function newLinesAndIndent() {
3078
+ if (numberLineBreaks > 1) {
3079
+ return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);
3080
+ }
3081
+ const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);
3082
+ if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {
3083
+ return eol + repeat(indentValue, initialIndentLevel + indentLevel);
3084
+ }
3085
+ if (amountOfSpaces <= 0) {
3086
+ return eol;
3087
+ }
3088
+ return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];
3089
+ }
3090
+ function scanNext() {
3091
+ let token = scanner.scan();
3092
+ numberLineBreaks = 0;
3093
+ while (token === 15 || token === 14) {
3094
+ if (token === 14 && options.keepLines) {
3095
+ numberLineBreaks += 1;
3096
+ } else if (token === 14) {
3097
+ numberLineBreaks = 1;
3098
+ }
3099
+ token = scanner.scan();
3100
+ }
3101
+ hasError = token === 16 || scanner.getTokenError() !== 0;
3102
+ return token;
3103
+ }
3104
+ const editOperations = [];
3105
+ function addEdit(text, startOffset, endOffset) {
3106
+ if (!hasError && (!range || startOffset < rangeEnd && endOffset > rangeStart) && documentText.substring(startOffset, endOffset) !== text) {
3107
+ editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });
3108
+ }
3109
+ }
3110
+ let firstToken = scanNext();
3111
+ if (options.keepLines && numberLineBreaks > 0) {
3112
+ addEdit(repeat(eol, numberLineBreaks), 0, 0);
3113
+ }
3114
+ if (firstToken !== 17) {
3115
+ let firstTokenStart = scanner.getTokenOffset() + formatTextStart;
3116
+ let initialIndent = indentValue.length * initialIndentLevel < 20 && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel);
3117
+ addEdit(initialIndent, formatTextStart, firstTokenStart);
3118
+ }
3119
+ while (firstToken !== 17) {
3120
+ let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
3121
+ let secondToken = scanNext();
3122
+ let replaceContent = "";
3123
+ let needsLineBreak = false;
3124
+ while (numberLineBreaks === 0 && (secondToken === 12 || secondToken === 13)) {
3125
+ let commentTokenStart = scanner.getTokenOffset() + formatTextStart;
3126
+ addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);
3127
+ firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;
3128
+ needsLineBreak = secondToken === 12;
3129
+ replaceContent = needsLineBreak ? newLinesAndIndent() : "";
3130
+ secondToken = scanNext();
3131
+ }
3132
+ if (secondToken === 2) {
3133
+ if (firstToken !== 1) {
3134
+ indentLevel--;
3135
+ }
3136
+ ;
3137
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1) {
3138
+ replaceContent = newLinesAndIndent();
3139
+ } else if (options.keepLines) {
3140
+ replaceContent = cachedSpaces[1];
3141
+ }
3142
+ } else if (secondToken === 4) {
3143
+ if (firstToken !== 3) {
3144
+ indentLevel--;
3145
+ }
3146
+ ;
3147
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3) {
3148
+ replaceContent = newLinesAndIndent();
3149
+ } else if (options.keepLines) {
3150
+ replaceContent = cachedSpaces[1];
3151
+ }
3152
+ } else {
3153
+ switch (firstToken) {
3154
+ case 3:
3155
+ case 1:
3156
+ indentLevel++;
3157
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
3158
+ replaceContent = newLinesAndIndent();
3159
+ } else {
3160
+ replaceContent = cachedSpaces[1];
3161
+ }
3162
+ break;
3163
+ case 5:
3164
+ if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {
3165
+ replaceContent = newLinesAndIndent();
3166
+ } else {
3167
+ replaceContent = cachedSpaces[1];
3168
+ }
3169
+ break;
3170
+ case 12:
3171
+ replaceContent = newLinesAndIndent();
3172
+ break;
3173
+ case 13:
3174
+ if (numberLineBreaks > 0) {
3175
+ replaceContent = newLinesAndIndent();
3176
+ } else if (!needsLineBreak) {
3177
+ replaceContent = cachedSpaces[1];
3178
+ }
3179
+ break;
3180
+ case 6:
3181
+ if (options.keepLines && numberLineBreaks > 0) {
3182
+ replaceContent = newLinesAndIndent();
3183
+ } else if (!needsLineBreak) {
3184
+ replaceContent = cachedSpaces[1];
3185
+ }
3186
+ break;
3187
+ case 10:
3188
+ if (options.keepLines && numberLineBreaks > 0) {
3189
+ replaceContent = newLinesAndIndent();
3190
+ } else if (secondToken === 6 && !needsLineBreak) {
3191
+ replaceContent = "";
3192
+ }
3193
+ break;
3194
+ case 7:
3195
+ case 8:
3196
+ case 9:
3197
+ case 11:
3198
+ case 2:
3199
+ case 4:
3200
+ if (options.keepLines && numberLineBreaks > 0) {
3201
+ replaceContent = newLinesAndIndent();
3202
+ } else {
3203
+ if ((secondToken === 12 || secondToken === 13) && !needsLineBreak) {
3204
+ replaceContent = cachedSpaces[1];
3205
+ } else if (secondToken !== 5 && secondToken !== 17) {
3206
+ hasError = true;
3207
+ }
3208
+ }
3209
+ break;
3210
+ case 16:
3211
+ hasError = true;
3212
+ break;
3213
+ }
3214
+ if (numberLineBreaks > 0 && (secondToken === 12 || secondToken === 13)) {
3215
+ replaceContent = newLinesAndIndent();
3216
+ }
3217
+ }
3218
+ if (secondToken === 17) {
3219
+ if (options.keepLines && numberLineBreaks > 0) {
3220
+ replaceContent = newLinesAndIndent();
3221
+ } else {
3222
+ replaceContent = options.insertFinalNewline ? eol : "";
3223
+ }
3224
+ }
3225
+ const secondTokenStart = scanner.getTokenOffset() + formatTextStart;
3226
+ addEdit(replaceContent, firstTokenEnd, secondTokenStart);
3227
+ firstToken = secondToken;
3228
+ }
3229
+ return editOperations;
3230
+ }
3231
+ function repeat(s, count) {
3232
+ let result = "";
3233
+ for (let i = 0; i < count; i++) {
3234
+ result += s;
3235
+ }
3236
+ return result;
3237
+ }
3238
+ function computeIndentLevel(content, options) {
3239
+ let i = 0;
3240
+ let nChars = 0;
3241
+ const tabSize = options.tabSize || 4;
3242
+ while (i < content.length) {
3243
+ let ch = content.charAt(i);
3244
+ if (ch === cachedSpaces[1]) {
3245
+ nChars++;
3246
+ } else if (ch === " ") {
3247
+ nChars += tabSize;
3248
+ } else {
3249
+ break;
3250
+ }
3251
+ i++;
3252
+ }
3253
+ return Math.floor(nChars / tabSize);
3254
+ }
3255
+ function getEOL(options, text) {
3256
+ for (let i = 0; i < text.length; i++) {
3257
+ const ch = text.charAt(i);
3258
+ if (ch === "\r") {
3259
+ if (i + 1 < text.length && text.charAt(i + 1) === "\n") {
3260
+ return "\r\n";
3261
+ }
3262
+ return "\r";
3263
+ } else if (ch === "\n") {
3264
+ return "\n";
3265
+ }
3266
+ }
3267
+ return options && options.eol || "\n";
3268
+ }
3269
+ function isEOL(text, offset) {
3270
+ return "\r\n".indexOf(text.charAt(offset)) !== -1;
3271
+ }
3272
+
3273
+ // node_modules/jsonc-parser/lib/esm/impl/parser.js
3274
+ var ParseOptions;
3275
+ (function(ParseOptions2) {
3276
+ ParseOptions2.DEFAULT = {
3277
+ allowTrailingComma: false
3278
+ };
3279
+ })(ParseOptions || (ParseOptions = {}));
3280
+ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {
3281
+ let currentParent = { type: "array", offset: -1, length: -1, children: [], parent: void 0 };
3282
+ function ensurePropertyComplete(endOffset) {
3283
+ if (currentParent.type === "property") {
3284
+ currentParent.length = endOffset - currentParent.offset;
3285
+ currentParent = currentParent.parent;
3286
+ }
3287
+ }
3288
+ function onValue(valueNode) {
3289
+ currentParent.children.push(valueNode);
3290
+ return valueNode;
3291
+ }
3292
+ const visitor = {
3293
+ onObjectBegin: (offset) => {
3294
+ currentParent = onValue({ type: "object", offset, length: -1, parent: currentParent, children: [] });
3295
+ },
3296
+ onObjectProperty: (name, offset, length) => {
3297
+ currentParent = onValue({ type: "property", offset, length: -1, parent: currentParent, children: [] });
3298
+ currentParent.children.push({ type: "string", value: name, offset, length, parent: currentParent });
3299
+ },
3300
+ onObjectEnd: (offset, length) => {
3301
+ ensurePropertyComplete(offset + length);
3302
+ currentParent.length = offset + length - currentParent.offset;
3303
+ currentParent = currentParent.parent;
3304
+ ensurePropertyComplete(offset + length);
3305
+ },
3306
+ onArrayBegin: (offset, length) => {
3307
+ currentParent = onValue({ type: "array", offset, length: -1, parent: currentParent, children: [] });
3308
+ },
3309
+ onArrayEnd: (offset, length) => {
3310
+ currentParent.length = offset + length - currentParent.offset;
3311
+ currentParent = currentParent.parent;
3312
+ ensurePropertyComplete(offset + length);
3313
+ },
3314
+ onLiteralValue: (value, offset, length) => {
3315
+ onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });
3316
+ ensurePropertyComplete(offset + length);
3317
+ },
3318
+ onSeparator: (sep, offset, length) => {
3319
+ if (currentParent.type === "property") {
3320
+ if (sep === ":") {
3321
+ currentParent.colonOffset = offset;
3322
+ } else if (sep === ",") {
3323
+ ensurePropertyComplete(offset);
3324
+ }
3325
+ }
3326
+ },
3327
+ onError: (error, offset, length) => {
3328
+ errors.push({ error, offset, length });
3329
+ }
3330
+ };
3331
+ visit(text, visitor, options);
3332
+ const result = currentParent.children[0];
3333
+ if (result) {
3334
+ delete result.parent;
3335
+ }
3336
+ return result;
3337
+ }
3338
+ function findNodeAtLocation(root, path2) {
3339
+ if (!root) {
3340
+ return void 0;
3341
+ }
3342
+ let node = root;
3343
+ for (let segment of path2) {
3344
+ if (typeof segment === "string") {
3345
+ if (node.type !== "object" || !Array.isArray(node.children)) {
3346
+ return void 0;
3347
+ }
3348
+ let found = false;
3349
+ for (const propertyNode of node.children) {
3350
+ if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {
3351
+ node = propertyNode.children[1];
3352
+ found = true;
3353
+ break;
3354
+ }
3355
+ }
3356
+ if (!found) {
3357
+ return void 0;
3358
+ }
3359
+ } else {
3360
+ const index = segment;
3361
+ if (node.type !== "array" || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {
3362
+ return void 0;
3363
+ }
3364
+ node = node.children[index];
3365
+ }
3366
+ }
3367
+ return node;
3368
+ }
3369
+ function getNodeValue(node) {
3370
+ switch (node.type) {
3371
+ case "array":
3372
+ return node.children.map(getNodeValue);
3373
+ case "object":
3374
+ const obj = /* @__PURE__ */ Object.create(null);
3375
+ for (let prop of node.children) {
3376
+ const valueNode = prop.children[1];
3377
+ if (valueNode) {
3378
+ obj[prop.children[0].value] = getNodeValue(valueNode);
3379
+ }
3380
+ }
3381
+ return obj;
3382
+ case "null":
3383
+ case "string":
3384
+ case "number":
3385
+ case "boolean":
3386
+ return node.value;
3387
+ default:
3388
+ return void 0;
3389
+ }
3390
+ }
3391
+ function visit(text, visitor, options = ParseOptions.DEFAULT) {
3392
+ const _scanner = createScanner(text, false);
3393
+ const _jsonPath = [];
3394
+ let suppressedCallbacks = 0;
3395
+ function toNoArgVisit(visitFunction) {
3396
+ return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
433
3397
  }
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);
3398
+ function toOneArgVisit(visitFunction) {
3399
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
439
3400
  }
440
- };
441
- var Storage = class {
442
- constructor(http) {
443
- this.http = http;
3401
+ function toOneArgVisitWithPath(visitFunction) {
3402
+ return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
444
3403
  }
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);
3404
+ function toBeginVisit(visitFunction) {
3405
+ return visitFunction ? () => {
3406
+ if (suppressedCallbacks > 0) {
3407
+ suppressedCallbacks++;
3408
+ } else {
3409
+ let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());
3410
+ if (cbReturn === false) {
3411
+ suppressedCallbacks = 1;
3412
+ }
3413
+ }
3414
+ } : () => true;
456
3415
  }
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);
3416
+ function toEndVisit(visitFunction) {
3417
+ return visitFunction ? () => {
3418
+ if (suppressedCallbacks > 0) {
3419
+ suppressedCallbacks--;
3420
+ }
3421
+ if (suppressedCallbacks === 0) {
3422
+ visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());
3423
+ }
3424
+ } : () => true;
461
3425
  }
462
- };
463
- var Llm = class {
464
- constructor(http) {
465
- this.http = http;
3426
+ const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
3427
+ const disallowComments = options && options.disallowComments;
3428
+ const allowTrailingComma = options && options.allowTrailingComma;
3429
+ function scanNext() {
3430
+ while (true) {
3431
+ const token = _scanner.scan();
3432
+ switch (_scanner.getTokenError()) {
3433
+ case 4:
3434
+ handleError(
3435
+ 14
3436
+ /* ParseErrorCode.InvalidUnicode */
3437
+ );
3438
+ break;
3439
+ case 5:
3440
+ handleError(
3441
+ 15
3442
+ /* ParseErrorCode.InvalidEscapeCharacter */
3443
+ );
3444
+ break;
3445
+ case 3:
3446
+ handleError(
3447
+ 13
3448
+ /* ParseErrorCode.UnexpectedEndOfNumber */
3449
+ );
3450
+ break;
3451
+ case 1:
3452
+ if (!disallowComments) {
3453
+ handleError(
3454
+ 11
3455
+ /* ParseErrorCode.UnexpectedEndOfComment */
3456
+ );
3457
+ }
3458
+ break;
3459
+ case 2:
3460
+ handleError(
3461
+ 12
3462
+ /* ParseErrorCode.UnexpectedEndOfString */
3463
+ );
3464
+ break;
3465
+ case 6:
3466
+ handleError(
3467
+ 16
3468
+ /* ParseErrorCode.InvalidCharacter */
3469
+ );
3470
+ break;
3471
+ }
3472
+ switch (token) {
3473
+ case 12:
3474
+ case 13:
3475
+ if (disallowComments) {
3476
+ handleError(
3477
+ 10
3478
+ /* ParseErrorCode.InvalidCommentToken */
3479
+ );
3480
+ } else {
3481
+ onComment();
3482
+ }
3483
+ break;
3484
+ case 16:
3485
+ handleError(
3486
+ 1
3487
+ /* ParseErrorCode.InvalidSymbol */
3488
+ );
3489
+ break;
3490
+ case 15:
3491
+ case 14:
3492
+ break;
3493
+ default:
3494
+ return token;
3495
+ }
3496
+ }
466
3497
  }
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);
3498
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
3499
+ onError(error);
3500
+ if (skipUntilAfter.length + skipUntil.length > 0) {
3501
+ let token = _scanner.getToken();
3502
+ while (token !== 17) {
3503
+ if (skipUntilAfter.indexOf(token) !== -1) {
3504
+ scanNext();
3505
+ break;
3506
+ } else if (skipUntil.indexOf(token) !== -1) {
3507
+ break;
3508
+ }
3509
+ token = scanNext();
3510
+ }
3511
+ }
478
3512
  }
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);
3513
+ function parseString(isValue) {
3514
+ const value = _scanner.getTokenValue();
3515
+ if (isValue) {
3516
+ onLiteralValue(value);
3517
+ } else {
3518
+ onObjectProperty(value);
3519
+ _jsonPath.push(value);
3520
+ }
3521
+ scanNext();
3522
+ return true;
482
3523
  }
483
- };
484
- var Tts = class {
485
- constructor(http) {
486
- this.http = http;
3524
+ function parseLiteral() {
3525
+ switch (_scanner.getToken()) {
3526
+ case 11:
3527
+ const tokenValue = _scanner.getTokenValue();
3528
+ let value = Number(tokenValue);
3529
+ if (isNaN(value)) {
3530
+ handleError(
3531
+ 2
3532
+ /* ParseErrorCode.InvalidNumberFormat */
3533
+ );
3534
+ value = 0;
3535
+ }
3536
+ onLiteralValue(value);
3537
+ break;
3538
+ case 7:
3539
+ onLiteralValue(null);
3540
+ break;
3541
+ case 8:
3542
+ onLiteralValue(true);
3543
+ break;
3544
+ case 9:
3545
+ onLiteralValue(false);
3546
+ break;
3547
+ default:
3548
+ return false;
3549
+ }
3550
+ scanNext();
3551
+ return true;
487
3552
  }
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);
3553
+ function parseProperty() {
3554
+ if (_scanner.getToken() !== 10) {
3555
+ handleError(3, [], [
3556
+ 2,
3557
+ 5
3558
+ /* SyntaxKind.CommaToken */
3559
+ ]);
3560
+ return false;
3561
+ }
3562
+ parseString(false);
3563
+ if (_scanner.getToken() === 6) {
3564
+ onSeparator(":");
3565
+ scanNext();
3566
+ if (!parseValue2()) {
3567
+ handleError(4, [], [
3568
+ 2,
3569
+ 5
3570
+ /* SyntaxKind.CommaToken */
3571
+ ]);
3572
+ }
3573
+ } else {
3574
+ handleError(5, [], [
3575
+ 2,
3576
+ 5
3577
+ /* SyntaxKind.CommaToken */
3578
+ ]);
3579
+ }
3580
+ _jsonPath.pop();
3581
+ return true;
500
3582
  }
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);
3583
+ function parseObject() {
3584
+ onObjectBegin();
3585
+ scanNext();
3586
+ let needsComma = false;
3587
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
3588
+ if (_scanner.getToken() === 5) {
3589
+ if (!needsComma) {
3590
+ handleError(4, [], []);
3591
+ }
3592
+ onSeparator(",");
3593
+ scanNext();
3594
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
3595
+ break;
3596
+ }
3597
+ } else if (needsComma) {
3598
+ handleError(6, [], []);
3599
+ }
3600
+ if (!parseProperty()) {
3601
+ handleError(4, [], [
3602
+ 2,
3603
+ 5
3604
+ /* SyntaxKind.CommaToken */
3605
+ ]);
3606
+ }
3607
+ needsComma = true;
3608
+ }
3609
+ onObjectEnd();
3610
+ if (_scanner.getToken() !== 2) {
3611
+ handleError(7, [
3612
+ 2
3613
+ /* SyntaxKind.CloseBraceToken */
3614
+ ], []);
3615
+ } else {
3616
+ scanNext();
3617
+ }
3618
+ return true;
504
3619
  }
505
- };
506
- var Webhooks = class {
507
- constructor(http) {
508
- this.http = http;
3620
+ function parseArray() {
3621
+ onArrayBegin();
3622
+ scanNext();
3623
+ let isFirstElement = true;
3624
+ let needsComma = false;
3625
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
3626
+ if (_scanner.getToken() === 5) {
3627
+ if (!needsComma) {
3628
+ handleError(4, [], []);
3629
+ }
3630
+ onSeparator(",");
3631
+ scanNext();
3632
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
3633
+ break;
3634
+ }
3635
+ } else if (needsComma) {
3636
+ handleError(6, [], []);
3637
+ }
3638
+ if (isFirstElement) {
3639
+ _jsonPath.push(0);
3640
+ isFirstElement = false;
3641
+ } else {
3642
+ _jsonPath[_jsonPath.length - 1]++;
3643
+ }
3644
+ if (!parseValue2()) {
3645
+ handleError(4, [], [
3646
+ 4,
3647
+ 5
3648
+ /* SyntaxKind.CommaToken */
3649
+ ]);
3650
+ }
3651
+ needsComma = true;
3652
+ }
3653
+ onArrayEnd();
3654
+ if (!isFirstElement) {
3655
+ _jsonPath.pop();
3656
+ }
3657
+ if (_scanner.getToken() !== 4) {
3658
+ handleError(8, [
3659
+ 4
3660
+ /* SyntaxKind.CloseBracketToken */
3661
+ ], []);
3662
+ } else {
3663
+ scanNext();
3664
+ }
3665
+ return true;
509
3666
  }
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);
3667
+ function parseValue2() {
3668
+ switch (_scanner.getToken()) {
3669
+ case 3:
3670
+ return parseArray();
3671
+ case 1:
3672
+ return parseObject();
3673
+ case 10:
3674
+ return parseString(true);
3675
+ default:
3676
+ return parseLiteral();
3677
+ }
516
3678
  }
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);
3679
+ scanNext();
3680
+ if (_scanner.getToken() === 17) {
3681
+ if (options.allowEmptyContent) {
3682
+ return true;
3683
+ }
3684
+ handleError(4, [], []);
3685
+ return false;
522
3686
  }
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);
3687
+ if (!parseValue2()) {
3688
+ handleError(4, [], []);
3689
+ return false;
527
3690
  }
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);
3691
+ if (_scanner.getToken() !== 17) {
3692
+ handleError(9, [], []);
532
3693
  }
533
- };
3694
+ return true;
3695
+ }
3696
+ function getNodeType(value) {
3697
+ switch (typeof value) {
3698
+ case "boolean":
3699
+ return "boolean";
3700
+ case "number":
3701
+ return "number";
3702
+ case "string":
3703
+ return "string";
3704
+ case "object": {
3705
+ if (!value) {
3706
+ return "null";
3707
+ } else if (Array.isArray(value)) {
3708
+ return "array";
3709
+ }
3710
+ return "object";
3711
+ }
3712
+ default:
3713
+ return "null";
3714
+ }
3715
+ }
534
3716
 
535
- // src/resources/callers.ts
536
- function enc2(phoneNumber) {
537
- return encodeURIComponent(phoneNumber);
3717
+ // node_modules/jsonc-parser/lib/esm/impl/edit.js
3718
+ function setProperty(text, originalPath, value, options) {
3719
+ const path2 = originalPath.slice();
3720
+ const errors = [];
3721
+ const root = parseTree(text, errors);
3722
+ let parent = void 0;
3723
+ let lastSegment = void 0;
3724
+ while (path2.length > 0) {
3725
+ lastSegment = path2.pop();
3726
+ parent = findNodeAtLocation(root, path2);
3727
+ if (parent === void 0 && value !== void 0) {
3728
+ if (typeof lastSegment === "string") {
3729
+ value = { [lastSegment]: value };
3730
+ } else {
3731
+ value = [value];
3732
+ }
3733
+ } else {
3734
+ break;
3735
+ }
3736
+ }
3737
+ if (!parent) {
3738
+ if (value === void 0) {
3739
+ throw new Error("Can not delete in empty document");
3740
+ }
3741
+ return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);
3742
+ } else if (parent.type === "object" && typeof lastSegment === "string" && Array.isArray(parent.children)) {
3743
+ const existing = findNodeAtLocation(parent, [lastSegment]);
3744
+ if (existing !== void 0) {
3745
+ if (value === void 0) {
3746
+ if (!existing.parent) {
3747
+ throw new Error("Malformed AST");
3748
+ }
3749
+ const propertyIndex = parent.children.indexOf(existing.parent);
3750
+ let removeBegin;
3751
+ let removeEnd = existing.parent.offset + existing.parent.length;
3752
+ if (propertyIndex > 0) {
3753
+ let previous = parent.children[propertyIndex - 1];
3754
+ removeBegin = previous.offset + previous.length;
3755
+ } else {
3756
+ removeBegin = parent.offset + 1;
3757
+ if (parent.children.length > 1) {
3758
+ let next = parent.children[1];
3759
+ removeEnd = next.offset;
3760
+ }
3761
+ }
3762
+ return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: "" }, options);
3763
+ } else {
3764
+ return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);
3765
+ }
3766
+ } else {
3767
+ if (value === void 0) {
3768
+ return [];
3769
+ }
3770
+ const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;
3771
+ const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map((p) => p.children[0].value)) : parent.children.length;
3772
+ let edit;
3773
+ if (index > 0) {
3774
+ let previous = parent.children[index - 1];
3775
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
3776
+ } else if (parent.children.length === 0) {
3777
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
3778
+ } else {
3779
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
3780
+ }
3781
+ return withFormatting(text, edit, options);
3782
+ }
3783
+ } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
3784
+ const insertIndex = lastSegment;
3785
+ if (insertIndex === -1) {
3786
+ const newProperty = `${JSON.stringify(value)}`;
3787
+ let edit;
3788
+ if (parent.children.length === 0) {
3789
+ edit = { offset: parent.offset + 1, length: 0, content: newProperty };
3790
+ } else {
3791
+ const previous = parent.children[parent.children.length - 1];
3792
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
3793
+ }
3794
+ return withFormatting(text, edit, options);
3795
+ } else if (value === void 0 && parent.children.length >= 0) {
3796
+ const removalIndex = lastSegment;
3797
+ const toRemove = parent.children[removalIndex];
3798
+ let edit;
3799
+ if (parent.children.length === 1) {
3800
+ edit = { offset: parent.offset + 1, length: parent.length - 2, content: "" };
3801
+ } else if (parent.children.length - 1 === removalIndex) {
3802
+ let previous = parent.children[removalIndex - 1];
3803
+ let offset = previous.offset + previous.length;
3804
+ let parentEndOffset = parent.offset + parent.length;
3805
+ edit = { offset, length: parentEndOffset - 2 - offset, content: "" };
3806
+ } else {
3807
+ edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
3808
+ }
3809
+ return withFormatting(text, edit, options);
3810
+ } else if (value !== void 0) {
3811
+ let edit;
3812
+ const newProperty = `${JSON.stringify(value)}`;
3813
+ if (!options.isArrayInsertion && parent.children.length > lastSegment) {
3814
+ const toModify = parent.children[lastSegment];
3815
+ edit = { offset: toModify.offset, length: toModify.length, content: newProperty };
3816
+ } else if (parent.children.length === 0 || lastSegment === 0) {
3817
+ edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + "," };
3818
+ } else {
3819
+ const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;
3820
+ const previous = parent.children[index - 1];
3821
+ edit = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
3822
+ }
3823
+ return withFormatting(text, edit, options);
3824
+ } else {
3825
+ throw new Error(`Can not ${value === void 0 ? "remove" : options.isArrayInsertion ? "insert" : "modify"} Array index ${insertIndex} as length is not sufficient`);
3826
+ }
3827
+ } else {
3828
+ throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
3829
+ }
538
3830
  }
539
- var Callers = class {
540
- constructor(http) {
541
- this.http = http;
3831
+ function withFormatting(text, edit, options) {
3832
+ if (!options.formattingOptions) {
3833
+ return [edit];
542
3834
  }
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);
3835
+ let newText = applyEdit(text, edit);
3836
+ let begin = edit.offset;
3837
+ let end = edit.offset + edit.content.length;
3838
+ if (edit.length === 0 || edit.content.length === 0) {
3839
+ while (begin > 0 && !isEOL(newText, begin - 1)) {
3840
+ begin--;
3841
+ }
3842
+ while (end < newText.length && !isEOL(newText, end)) {
3843
+ end++;
3844
+ }
548
3845
  }
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);
3846
+ const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });
3847
+ for (let i = edits.length - 1; i >= 0; i--) {
3848
+ const edit2 = edits[i];
3849
+ newText = applyEdit(newText, edit2);
3850
+ begin = Math.min(begin, edit2.offset);
3851
+ end = Math.max(end, edit2.offset + edit2.length);
3852
+ end += edit2.content.length - edit2.length;
553
3853
  }
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);
3854
+ const editLength = text.length - (newText.length - end) - begin;
3855
+ return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];
3856
+ }
3857
+ function applyEdit(text, edit) {
3858
+ return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);
3859
+ }
3860
+
3861
+ // node_modules/jsonc-parser/lib/esm/main.js
3862
+ var ScanError;
3863
+ (function(ScanError2) {
3864
+ ScanError2[ScanError2["None"] = 0] = "None";
3865
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
3866
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
3867
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
3868
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
3869
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
3870
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
3871
+ })(ScanError || (ScanError = {}));
3872
+ var SyntaxKind;
3873
+ (function(SyntaxKind2) {
3874
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
3875
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
3876
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
3877
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
3878
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
3879
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
3880
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
3881
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
3882
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
3883
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
3884
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
3885
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
3886
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
3887
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
3888
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
3889
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
3890
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
3891
+ })(SyntaxKind || (SyntaxKind = {}));
3892
+ var parseTree2 = parseTree;
3893
+ var findNodeAtLocation2 = findNodeAtLocation;
3894
+ var getNodeValue2 = getNodeValue;
3895
+ var visit2 = visit;
3896
+ var ParseErrorCode;
3897
+ (function(ParseErrorCode2) {
3898
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
3899
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
3900
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
3901
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
3902
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
3903
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
3904
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
3905
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
3906
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
3907
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
3908
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
3909
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
3910
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
3911
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
3912
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
3913
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
3914
+ })(ParseErrorCode || (ParseErrorCode = {}));
3915
+ function modify(text, path2, value, options) {
3916
+ return setProperty(text, path2, value, options);
3917
+ }
3918
+ function applyEdits(text, edits) {
3919
+ let sortedEdits = edits.slice(0).sort((a, b) => {
3920
+ const diff = a.offset - b.offset;
3921
+ if (diff === 0) {
3922
+ return a.length - b.length;
3923
+ }
3924
+ return diff;
3925
+ });
3926
+ let lastModifiedOffset = text.length;
3927
+ for (let i = sortedEdits.length - 1; i >= 0; i--) {
3928
+ let e = sortedEdits[i];
3929
+ if (e.offset + e.length <= lastModifiedOffset) {
3930
+ text = applyEdit(text, e);
3931
+ } else {
3932
+ throw new Error("Overlapping edit");
3933
+ }
3934
+ lastModifiedOffset = e.offset;
557
3935
  }
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);
3936
+ return text;
3937
+ }
3938
+
3939
+ // src/cli/mcp/config-edit.mjs
3940
+ function planConfigEdit(text, name, entry, format2 = "jsonc") {
3941
+ var _a;
3942
+ if (format2 === "json") {
3943
+ try {
3944
+ JSON.parse(text);
3945
+ } catch {
3946
+ throw new Error("Malformed strict JSON configuration; nothing changed.");
3947
+ }
562
3948
  }
563
- };
3949
+ const errors = [], tree = parseTree2(text, errors, { allowTrailingComma: true });
3950
+ if (errors.length || !tree || tree.type !== "object") throw new Error("Malformed MCP configuration; nothing changed.");
3951
+ const stack = [];
3952
+ visit2(text, {
3953
+ onObjectBegin() {
3954
+ stack.push(/* @__PURE__ */ new Set());
3955
+ },
3956
+ onObjectProperty(key) {
3957
+ const set = stack.at(-1);
3958
+ if (set.has(key)) throw new Error("Duplicate configuration property; nothing changed.");
3959
+ set.add(key);
3960
+ },
3961
+ onObjectEnd() {
3962
+ stack.pop();
3963
+ }
3964
+ });
3965
+ const root = getNodeValue2(tree);
3966
+ if (root.mcpServers !== void 0 && (!root.mcpServers || typeof root.mcpServers !== "object" || Array.isArray(root.mcpServers)))
3967
+ throw new Error("Invalid mcpServers section; nothing changed.");
3968
+ const previous = (_a = root.mcpServers) == null ? void 0 : _a[name];
3969
+ const same = (a, b) => JSON.stringify(sort(a)) === JSON.stringify(sort(b));
3970
+ if (same(previous, entry)) return { text, changed: false, replacing: false, preview: [] };
3971
+ const oldNode = findNodeAtLocation2(tree, ["mcpServers", name]);
3972
+ if (oldNode) {
3973
+ let commented = false;
3974
+ visit2(text.slice(oldNode.offset, oldNode.offset + oldNode.length), { onComment() {
3975
+ commented = true;
3976
+ } });
3977
+ if (commented) throw new Error("Existing Nixflex entry has comments. Review it manually; nothing changed.");
3978
+ }
3979
+ const output = applyEdits(text, modify(text, ["mcpServers", name], entry, {}));
3980
+ const preview = Object.keys(entry).map((key) => ({
3981
+ field: name + "." + key,
3982
+ before: previous === void 0 ? "(absent)" : "[existing value hidden]",
3983
+ after: entry[key]
3984
+ }));
3985
+ return { text: output, changed: true, replacing: previous !== void 0, preview };
3986
+ }
3987
+ function sort(value) {
3988
+ if (Array.isArray(value)) return value.map(sort);
3989
+ if (value && typeof value === "object") return Object.fromEntries(Object.keys(value).sort().map((key) => [key, sort(value[key])]));
3990
+ return value;
3991
+ }
564
3992
 
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);
3993
+ // src/cli/mcp/private-file.mjs
3994
+ import { chmodSync } from "fs";
3995
+ import { spawnSync } from "child_process";
3996
+ function restrictFile(file) {
3997
+ var _a;
3998
+ if (process.platform !== "win32") {
3999
+ chmodSync(file, 384);
4000
+ return;
605
4001
  }
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
- );
4002
+ const user = spawnSync("whoami.exe", ["/user", "/fo", "csv", "/nh"], { encoding: "utf8", windowsHide: true });
4003
+ const sid = user.status === 0 && ((_a = user.stdout.match(/S-1-5-(?:\d+-)*\d+/)) == null ? void 0 : _a[0]);
4004
+ if (!sid) throw new Error("Cannot determine private configuration permissions. Nothing replaced.");
4005
+ const result = spawnSync(
4006
+ "icacls.exe",
4007
+ [file, "/inheritance:r", "/grant:r", "*" + sid + ":(F)", "*S-1-5-18:(F)"],
4008
+ { encoding: "utf8", windowsHide: true }
4009
+ );
4010
+ if (result.status !== 0) throw new Error("Cannot protect private configuration. Nothing replaced.");
4011
+ }
4012
+
4013
+ // src/cli/mcp/config-write.mjs
4014
+ function snapshot(file) {
4015
+ try {
4016
+ const stat = lstatSync(file);
4017
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw new Error("Not a regular private file");
4018
+ if (!(stat.mode & 128)) throw new Error("File is read-only");
4019
+ const text = readFileSync2(file, "utf8");
4020
+ return { text, stamp: [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs, stat.mode].join(":") };
4021
+ } catch (error) {
4022
+ if (error.code === "ENOENT") return { text: null, stamp: null };
4023
+ throw new Error("Cannot safely read MCP configuration; nothing changed.");
4024
+ }
4025
+ }
4026
+ async function writeMcpConfig({ file, name, entry, format: format2 = "jsonc", confirm, display = () => {
4027
+ }, beforeCommit = () => {
4028
+ } }) {
4029
+ for (let parent = dirname(file); ; parent = dirname(parent)) {
4030
+ try {
4031
+ if (lstatSync(parent).isSymbolicLink()) throw new Error("Linked configuration directory is not supported; nothing changed.");
4032
+ } catch (error) {
4033
+ if (error.code !== "ENOENT") throw error;
623
4034
  }
624
- return body;
4035
+ if (parent === dirname(parent)) break;
625
4036
  }
626
- };
627
- var src_default = Nixflex;
4037
+ mkdirSync(dirname(file), { recursive: true, mode: 448 });
4038
+ const lock = file + ".nixflex-setup.lock";
4039
+ let lockFd;
4040
+ try {
4041
+ lockFd = openSync(lock, "wx", 384);
4042
+ } catch {
4043
+ throw new Error("Another setup may be running. Configuration was not changed.");
4044
+ }
4045
+ const temporary = join2(dirname(file), ".nixflex-" + randomUUID4() + ".tmp");
4046
+ let tempFd;
4047
+ try {
4048
+ restrictFile(lock);
4049
+ const original = snapshot(file);
4050
+ const planned = planConfigEdit(original.text ?? "{}\n", name, entry, format2);
4051
+ if (!planned.changed) return { changed: false };
4052
+ display(planned.preview);
4053
+ if (planned.replacing && !await confirm()) throw new Error("Replacement not confirmed; nothing changed.");
4054
+ tempFd = openSync(temporary, "wx", 384);
4055
+ restrictFile(temporary);
4056
+ writeFileSync(tempFd, planned.text, "utf8");
4057
+ fsyncSync(tempFd);
4058
+ closeSync(tempFd);
4059
+ tempFd = void 0;
4060
+ await beforeCommit();
4061
+ const current = snapshot(file);
4062
+ if (current.stamp !== original.stamp || current.text !== original.text)
4063
+ throw new Error("MCP configuration changed during setup. Nothing replaced; review and retry.");
4064
+ if (original.text === null) {
4065
+ linkSync(temporary, file);
4066
+ unlinkSync(temporary);
4067
+ } else renameSync(temporary, file);
4068
+ return { changed: true };
4069
+ } finally {
4070
+ if (tempFd !== void 0) closeSync(tempFd);
4071
+ try {
4072
+ unlinkSync(temporary);
4073
+ } catch (error) {
4074
+ if (error.code !== "ENOENT") throw error;
4075
+ }
4076
+ closeSync(lockFd);
4077
+ unlinkSync(lock);
4078
+ }
4079
+ }
4080
+
4081
+ // src/cli/mcp/release.json
4082
+ var release_default = { mcpVersion: "0.5.0", minimumNodeMajor: 22, published: true };
4083
+
4084
+ // src/cli/mcp/setup.mjs
4085
+ async function setupMcp(app, { confirmed = false, localPackage, env = process.env, home = homedir2(), platform = process.platform } = {}) {
4086
+ var _a;
4087
+ if (!["claude", "cursor"].includes(app))
4088
+ throw new Error("Run 1 setup supports claude or cursor. Claude Code/Codex installers arrive in run 3; VS Code is retired.");
4089
+ if (Number(process.versions.node.split(".")[0]) < release_default.minimumNodeMajor) throw new Error("MCP setup requires Node 22 or newer.");
4090
+ const connection = resolveConnection({ env, home });
4091
+ const entry = buildServerConfig({ client: app, platform, version: release_default.mcpVersion, ...connection });
4092
+ const name = serverName(connection.baseUrl);
4093
+ const file = app === "cursor" ? join3(home, ".cursor", "mcp.json") : platform === "win32" ? join3(env.APPDATA || join3(home, "AppData", "Roaming"), "Claude", "claude_desktop_config.json") : join3(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
4094
+ if (localPackage) {
4095
+ const directory = realpathSync(resolve(localPackage));
4096
+ const pkg = JSON.parse(readFileSync3(join3(directory, "package.json"), "utf8"));
4097
+ if (pkg.name !== "nixflex-mcp" || pkg.version !== release_default.mcpVersion || ((_a = pkg.bin) == null ? void 0 : _a["nixflex-mcp"]) !== "./index.js" || !statSync(join3(directory, "index.js")).isFile())
4098
+ throw new Error("Local MCP package does not match the tested release. Nothing changed.");
4099
+ entry.command = process.execPath;
4100
+ entry.args = [join3(directory, "index.js")];
4101
+ } else if (!release_default.published) throw new Error("MCP " + release_default.mcpVersion + " is not published yet. Nothing changed. Use --mcp-local with the verified unpacked package (FOUNDATION.md).");
4102
+ const result = await writeMcpConfig({
4103
+ file,
4104
+ name,
4105
+ entry,
4106
+ format: app === "claude" ? "json" : "jsonc",
4107
+ display(preview) {
4108
+ process.stderr.write("Proposed MCP change (old values hidden):\n" + JSON.stringify(preview, null, 2) + "\n");
4109
+ },
4110
+ async confirm() {
4111
+ if (confirmed) return true;
4112
+ if (!process.stdin.isTTY) return false;
4113
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
4114
+ try {
4115
+ return (await rl.question("Replace only this Nixflex entry? Type yes: ")).trim().toLowerCase() === "yes";
4116
+ } finally {
4117
+ rl.close();
4118
+ }
4119
+ }
4120
+ });
4121
+ return {
4122
+ ...result,
4123
+ written: file,
4124
+ server: name,
4125
+ api: connection.baseUrl,
4126
+ credential_source: connection.source,
4127
+ note: "Fully quit and reopen the client. No key was written into its configuration."
4128
+ };
4129
+ }
628
4130
 
629
4131
  // src/cli/index.ts
630
- var VERSION = true ? "0.9.0" : "0.0.0";
631
- var CONFIG_DIR = join(homedir(), ".nixflex");
632
- var CONFIG_FILE = join(CONFIG_DIR, "config.json");
4132
+ var VERSION = true ? "0.11.1" : "0.0.0";
4133
+ var CONFIG_DIR = join4(homedir3(), ".nixflex");
4134
+ var CONFIG_FILE = join4(CONFIG_DIR, "config.json");
633
4135
  function readConfig() {
634
4136
  try {
635
- return JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
4137
+ return JSON.parse(readFileSync4(CONFIG_FILE, "utf8"));
636
4138
  } catch {
637
4139
  return {};
638
4140
  }
639
4141
  }
640
4142
  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 });
4143
+ if (!existsSync(CONFIG_DIR)) mkdirSync2(CONFIG_DIR, { recursive: true, mode: 448 });
4144
+ writeFileSync2(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n", { mode: 384 });
643
4145
  }
644
4146
  var KEY_RE = /^nxf_[a-z0-9]+:nxfs_[a-z0-9]+$/i;
645
4147
  function resolveKey(flagKey) {
@@ -649,11 +4151,11 @@ function resolveKey(flagKey) {
649
4151
  return key;
650
4152
  }
651
4153
  function ask(question) {
652
- return new Promise((resolve) => {
653
- const rl = createInterface({ input: process.stdin, output: process.stdout });
4154
+ return new Promise((resolve2) => {
4155
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
654
4156
  rl.question(question, (a) => {
655
4157
  rl.close();
656
- resolve(a.trim());
4158
+ resolve2(a.trim());
657
4159
  });
658
4160
  });
659
4161
  }
@@ -713,7 +4215,7 @@ function fail(msg, code = 1) {
713
4215
  }
714
4216
  function textOrFile(v) {
715
4217
  if (v === void 0) return void 0;
716
- if (v.startsWith("@")) return readFileSync(v.slice(1), "utf8");
4218
+ if (v.startsWith("@")) return readFileSync4(v.slice(1), "utf8");
717
4219
  return v;
718
4220
  }
719
4221
  function parseValue(raw) {
@@ -721,7 +4223,7 @@ function parseValue(raw) {
721
4223
  if (raw === "true") return true;
722
4224
  if (raw === "false") return false;
723
4225
  if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
724
- if (raw.startsWith("@")) return readFileSync(raw.slice(1), "utf8");
4226
+ if (raw.startsWith("@")) return readFileSync4(raw.slice(1), "utf8");
725
4227
  if (raw.startsWith("{") && raw.endsWith("}") || raw.startsWith("[") && raw.endsWith("]")) {
726
4228
  try {
727
4229
  return JSON.parse(raw);
@@ -734,7 +4236,7 @@ function bodyFrom(values, extra = {}) {
734
4236
  const body = {};
735
4237
  const b = values.body;
736
4238
  if (b) {
737
- const text = b === "-" ? readFileSync(0, "utf8") : textOrFile(b) || "";
4239
+ const text = b === "-" ? readFileSync4(0, "utf8") : textOrFile(b) || "";
738
4240
  try {
739
4241
  Object.assign(body, JSON.parse(text));
740
4242
  } catch {
@@ -768,7 +4270,7 @@ function vars(list) {
768
4270
  }
769
4271
  function parseCsv(text) {
770
4272
  const rows = [];
771
- let row = [];
4273
+ let row2 = [];
772
4274
  let field = "";
773
4275
  let q = false;
774
4276
  for (let i = 0; i < text.length; i++) {
@@ -784,19 +4286,19 @@ function parseCsv(text) {
784
4286
  }
785
4287
  if (ch === '"') q = true;
786
4288
  else if (ch === ",") {
787
- row.push(field);
4289
+ row2.push(field);
788
4290
  field = "";
789
4291
  } else if (ch === "\n" || ch === "\r") {
790
4292
  if (ch === "\r" && text[i + 1] === "\n") i++;
791
- row.push(field);
792
- rows.push(row);
793
- row = [];
4293
+ row2.push(field);
4294
+ rows.push(row2);
4295
+ row2 = [];
794
4296
  field = "";
795
4297
  } else field += ch;
796
4298
  }
797
- if (field.length || row.length) {
798
- row.push(field);
799
- rows.push(row);
4299
+ if (field.length || row2.length) {
4300
+ row2.push(field);
4301
+ rows.push(row2);
800
4302
  }
801
4303
  const [head, ...body] = rows.filter((r) => r.some((c) => c.trim() !== ""));
802
4304
  if (!head) return [];
@@ -804,7 +4306,7 @@ function parseCsv(text) {
804
4306
  return body.map((r) => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? "").trim()])));
805
4307
  }
806
4308
  function recipientsFromCsv(file, allowOverride) {
807
- const rows = parseCsv(readFileSync(file, "utf8"));
4309
+ const rows = parseCsv(readFileSync4(file, "utf8"));
808
4310
  if (rows.length === 0) fail("no rows in " + file);
809
4311
  if (!("phone" in rows[0])) fail("the CSV needs a `phone` column (E.164, e.g. +447700900123)");
810
4312
  return rows.map((r) => {
@@ -816,13 +4318,14 @@ function recipientsFromCsv(file, allowOverride) {
816
4318
  rec.prompt_override = val;
817
4319
  continue;
818
4320
  }
4321
+ if (recipientField(rec, k, val)) continue;
819
4322
  v[k] = val;
820
4323
  }
821
4324
  if (Object.keys(v).length) rec.variables = v;
822
4325
  return rec;
823
4326
  });
824
4327
  }
825
- var GROUPS = ["login", "logout", "whoami", "usage", "doctor", "completion", "mcp", "agents", "calls", "campaigns", "numbers", "callers", "sms", "webhooks", "keys", "storage", "llm", "tts"];
4328
+ var GROUPS = ["login", "logout", "whoami", "usage", "doctor", "completion", "mcp", "agents", "calls", "campaigns", "numbers", "callers", "sms", "webhooks", "keys", "organisation", "integrations", "knowledge", ...coreGroups, ...c5Groups];
826
4329
  var HELP = `nixflex ${VERSION} - the Nixflex voice AI platform from your terminal
827
4330
 
828
4331
  USAGE nixflex <group> <command> [args] [--json] [--key KEY] [--base-url URL]
@@ -843,7 +4346,7 @@ ACCOUNT
843
4346
  keys rotate --confirm new secret; the old one stops working immediately
844
4347
 
845
4348
  AGENTS
846
- agents list [--limit N]
4349
+ agents list [--limit 1..200] [--offset N] [--status active|disabled|all] [--search TEXT]
847
4350
  agents get <agent_id>
848
4351
  agents create --name NAME --prompt TEXT|@file [--voice ID] [--language xx] [--set k=v ...]
849
4352
  agents update <id> [--name] [--prompt] [--voice] [--language] [--incall-sms true|false] [--set k=v ...]
@@ -853,22 +4356,31 @@ CALLS
853
4356
  calls create --agent ID --to +44... --prompt TEXT|@file [--from +44...] [--var k=v ...] [--wait] [--timeout S]
854
4357
  calls list [--limit N] [--agent ID]
855
4358
  calls get <call_id>
856
- calls delete <call_id> --confirm
4359
+ calls history [--number +44...] [--outcome failed] [--period month] [--cursor CURSOR]
4360
+ calls read <call_id> nullable detail, including retained metadata
4361
+ calls recording <call_id> recording status and expires_at-based link
4362
+ calls delete <call_id> --confirm end the call, then delete its content; recording cleanup may stay queued
857
4363
  calls delete-all --confirm every call and recording on the account
858
4364
 
859
4365
  CAMPAIGNS (voice batch)
860
4366
  campaigns create --agent ID --from +44... --prompt TEXT|@file --csv people.csv [--name] [--set k=v ...]
861
4367
  CSV: phone (required), prompt_override (optional), any other column = variable
862
4368
  campaigns launch <campaign_id>
4369
+ campaigns delete <campaign_id> --confirm cancel waiting work, end calls and hide campaign; history/charges stay
863
4370
 
864
4371
  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=...
4372
+ numbers list [--agent ID] [--provider twilio|telnyx] [--limit N] [--cursor CURSOR]
4373
+ numbers usage <number> [--period today|7|14|30|90|all] [--time-zone Europe/London]
4374
+ numbers get <number> --json
4375
+ numbers import --set phone_number=+44... --set agent_id=ID --set twilio_sid=... --set twilio_token=...
867
4376
  (or --set telnyx_api_key=... --set telnyx_connection_id=...) or --body @number.json
868
4377
  numbers update <number> [--sms-reply] [--sms-prompt] [--dtmf] [--set k=v ...]
4378
+ numbers move <number> --agent ID (also: numbers update <number> --agent ID)
869
4379
  numbers delete <number> --confirm
870
- numbers monitor <number> [get|on|off]
871
4380
  numbers web-calls <number> [get|on|off]
4381
+ Number boolean --set fields: inbound_enabled, outbound_enabled, sms_reply_enabled,
4382
+ web_agent_enabled, web_calls_enabled, web_functions_enabled, monitor_enabled.
4383
+ Website voice also needs Web agent ON. Monitor ON does not attach a listener.
872
4384
 
873
4385
  CALLERS (caller context)
874
4386
  callers get <your_number> <caller_number>
@@ -882,20 +4394,16 @@ SMS
882
4394
  sms campaigns launch <id>
883
4395
  sms campaigns list [--status S] [--limit N]
884
4396
  sms campaigns get <id>
885
- sms campaigns delete <id> --confirm
4397
+ sms campaigns delete <id> --confirm cancel waiting work and hide campaign; history/charges stay, no refund
4398
+ Delete: 503 hangup_pending + retry_pending:true means queued, not deleted. No automatic retry.
886
4399
 
887
4400
  WEBHOOKS (per number)
888
4401
  webhooks set <number> <url> [--slot 1|2]
889
4402
  webhooks get <number> [--slot 1|2]
890
4403
  webhooks delete <number> [--slot 1|2] --confirm
891
4404
 
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
4405
  MCP
898
- mcp setup <claude|cursor|vscode> connect the Nixflex MCP server to that app
4406
+ mcp setup <claude|cursor> safe MCP setup (Claude Code/Codex in run 3; VS Code retired)
899
4407
 
900
4408
  FLAGS --json machine output --set field=value (repeat) --body @file.json | - --confirm / --yes
901
4409
  EXIT 0 ok 1 error 2 no API key
@@ -931,43 +4439,26 @@ _arguments "1: :(${words})"
931
4439
  `;
932
4440
  fail("completion expects bash, zsh or pwsh");
933
4441
  }
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 + "." });
4442
+ async function mcpSetup(app, confirmed, localPackage) {
4443
+ out(await setupMcp(app, { confirmed, localPackage }));
964
4444
  }
965
4445
  async function main() {
4446
+ guardCredentialArguments(process.argv.slice(2));
966
4447
  const { values, positionals } = parseArgs({
967
4448
  args: process.argv.slice(2),
968
4449
  allowPositionals: true,
969
4450
  strict: false,
970
4451
  options: {
4452
+ ...kitFlags,
4453
+ ...k6Flags,
4454
+ ...callRequestFlags,
4455
+ ...knowledgeFlags,
4456
+ ...coreFlags,
4457
+ ...c5Flags,
4458
+ output: { type: "string" },
4459
+ ...agentListFlags,
4460
+ ...callReadFlags,
4461
+ "mcp-local": { type: "string" },
971
4462
  json: { type: "boolean" },
972
4463
  key: { type: "string" },
973
4464
  "base-url": { type: "string" },
@@ -977,6 +4468,10 @@ async function main() {
977
4468
  yes: { type: "boolean", short: "y" },
978
4469
  limit: { type: "string" },
979
4470
  status: { type: "string" },
4471
+ provider: { type: "string" },
4472
+ cursor: { type: "string" },
4473
+ period: { type: "string" },
4474
+ "time-zone": { type: "string" },
980
4475
  set: { type: "string", multiple: true },
981
4476
  body: { type: "string" },
982
4477
  name: { type: "string" },
@@ -1012,13 +4507,17 @@ async function main() {
1012
4507
  return;
1013
4508
  }
1014
4509
  if (!group || values.help) {
1015
- process.stdout.write(HELP);
4510
+ process.stdout.write(HELP + organisationHelp + coreHelp + c5Help + integrationsHelp + knowledgeHelp + k6Help + callRequestHelp);
1016
4511
  return;
1017
4512
  }
1018
4513
  if (!GROUPS.includes(group)) {
1019
4514
  const c = closest(group, GROUPS);
1020
4515
  fail('unknown command "' + group + '".' + (c ? " Did you mean `nixflex " + c + "`?" : "") + " Run `nixflex --help`.");
1021
4516
  }
4517
+ if (group === "calls" && cmd === "prepare") {
4518
+ out(await prepareCallCli(values, bodyFrom(values), textOrFile(s("prompt"))));
4519
+ return;
4520
+ }
1022
4521
  if (group === "login") {
1023
4522
  const key = process.env.NIXFLEX_API_KEY || await ask("API key (nxf_xxx:nxfs_xxx): ");
1024
4523
  if (!KEY_RE.test(key)) fail("That is not a full key pair (nxf_xxx:nxfs_xxx).");
@@ -1041,11 +4540,43 @@ async function main() {
1041
4540
  return;
1042
4541
  }
1043
4542
  if (group === "mcp") {
1044
- if (cmd !== "setup") fail("usage: nixflex mcp setup <claude|cursor|vscode>");
1045
- mcpSetup(a1);
4543
+ if (cmd !== "setup") fail("usage: nixflex mcp setup <claude|cursor>");
4544
+ await mcpSetup(a1, confirmed, s("mcp-local"));
4545
+ return;
4546
+ }
4547
+ if (group === "keys" && cmd === "create") {
4548
+ out(await createAccount(bodyFrom(values, { name: s("name"), email: s("email") }), confirmed, s("base-url") || readConfig().base_url));
1046
4549
  return;
1047
4550
  }
1048
4551
  const client = new src_default({ apiKey: resolveKey(s("key")), baseUrl: s("base-url") || readConfig().base_url });
4552
+ if (isK6(group, cmd)) {
4553
+ out(await k6Command(client, positionals, values, confirmed, () => bodyFrom(values)));
4554
+ return;
4555
+ }
4556
+ if (isC5(group, cmd, a1)) {
4557
+ out(await c5Command(client, positionals, values, bodyFrom(values), confirmed));
4558
+ return;
4559
+ }
4560
+ if (coreGroups.includes(group) || group === "keys" && cmd === "activity") {
4561
+ out(await coreRead(client, group, cmd, a1, values));
4562
+ return;
4563
+ }
4564
+ if (group === "knowledge") {
4565
+ out(await knowledgeCommand(client, positionals, values, bodyFrom(values), confirmed));
4566
+ return;
4567
+ }
4568
+ if (group === "integrations") {
4569
+ out(await integrationsCommand(client, positionals, bodyFrom(values), confirmed));
4570
+ return;
4571
+ }
4572
+ if (group === "organisation" && cmd === "activityCsv") {
4573
+ out(await activityExport(client, s("output"), bodyFrom(values)));
4574
+ return;
4575
+ }
4576
+ if (group === "organisation") {
4577
+ out(await organisationCommand(client, cmd, a1, bodyFrom(values), confirmed));
4578
+ return;
4579
+ }
1049
4580
  const limit = s("limit") ? parseInt(s("limit"), 10) : void 0;
1050
4581
  const slot = s("slot") === "2" ? 2 : 1;
1051
4582
  const preview = async (what, fetch2) => {
@@ -1092,7 +4623,7 @@ async function main() {
1092
4623
  }
1093
4624
  if (group === "agents") {
1094
4625
  if (cmd === "list") {
1095
- out(await client.agents.list(limit ? { limit } : {}));
4626
+ out(await client.agents.list(agentListParams(values)));
1096
4627
  return;
1097
4628
  }
1098
4629
  if (cmd === "get") {
@@ -1102,7 +4633,6 @@ async function main() {
1102
4633
  }
1103
4634
  if (cmd === "create") {
1104
4635
  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
4636
  out(await client.agents.create(body));
1107
4637
  return;
1108
4638
  }
@@ -1122,8 +4652,16 @@ async function main() {
1122
4652
  fail("agents: list | get | create | update | delete");
1123
4653
  }
1124
4654
  if (group === "calls") {
4655
+ if (["bookings", "outboundRequest"].includes(cmd)) {
4656
+ out(await callRequestRead(client, cmd, a1));
4657
+ return;
4658
+ }
4659
+ if (["history", "read", "recording"].includes(cmd)) {
4660
+ out(await callRead(client, cmd, a1, values));
4661
+ return;
4662
+ }
1125
4663
  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) });
4664
+ const body = withCallRequestId(callCreateBody(bodyFrom(values, { agent_id: s("agent"), to_number: s("to"), prompt: textOrFile(s("prompt")), from_number: s("from"), ...contactFields(values) }), vars(values.var)), values["request-id"]);
1127
4665
  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
4666
  const created = await client.calls.create(body);
1129
4667
  if (!values.wait) {
@@ -1149,10 +4687,7 @@ async function main() {
1149
4687
  fail("still in progress after the timeout - `nixflex calls get " + id + "` later");
1150
4688
  }
1151
4689
  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));
4690
+ out(await coreCallList(client, values));
1156
4691
  return;
1157
4692
  }
1158
4693
  if (cmd === "get") {
@@ -1168,7 +4703,7 @@ async function main() {
1168
4703
  }
1169
4704
  if (cmd === "delete-all") {
1170
4705
  if (!confirmed) {
1171
- out({ would_delete: "EVERY call, recording and SMS record on this account", hint: "add --confirm to proceed - this cannot be undone" });
4706
+ out({ would_delete: "call records and their tracked recordings on this account (not SMS; safety holds may refuse cleanup)", hint: "add --confirm to proceed - this cannot be undone" });
1172
4707
  return;
1173
4708
  }
1174
4709
  out(await client.calls.deleteAll());
@@ -1177,6 +4712,10 @@ async function main() {
1177
4712
  fail("calls: create | list | get | delete | delete-all");
1178
4713
  }
1179
4714
  if (group === "campaigns") {
4715
+ if (cmd === "delete") {
4716
+ out(await deleteCampaign(client, a1, confirmed));
4717
+ return;
4718
+ }
1180
4719
  if (cmd === "create") {
1181
4720
  const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), prompt: textOrFile(s("prompt")), name: s("name") });
1182
4721
  if (s("csv")) body.recipients = recipientsFromCsv(s("csv"), true);
@@ -1190,12 +4729,19 @@ async function main() {
1190
4729
  out(await client.campaigns.launch(a1));
1191
4730
  return;
1192
4731
  }
1193
- fail("campaigns: create | launch");
4732
+ fail("campaigns: create | launch | delete");
1194
4733
  }
1195
4734
  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);
4735
+ if (cmd === "move" || cmd === "update" && s("agent") !== void 0) {
4736
+ out(await numberMove(client, a1, s("agent"), bodyFrom(values, { sms_reply_enabled: boolOrNull(s("sms-reply")), sms_prompt: s("sms-prompt"), dtmf_enabled: boolOrNull(s("dtmf")) })));
4737
+ return;
4738
+ }
4739
+ if (cmd === "usage") {
4740
+ out(await numberUsage(client, a1, s));
4741
+ return;
4742
+ }
4743
+ if (cmd === "list" || cmd === "get") {
4744
+ out(await readNumber(client, cmd, a1, s, JSON_MODE));
1199
4745
  return;
1200
4746
  }
1201
4747
  if (cmd === "import") {
@@ -1220,24 +4766,26 @@ async function main() {
1220
4766
  out(await client.phoneNumbers.delete(a1));
1221
4767
  return;
1222
4768
  }
1223
- if (cmd === "monitor" || cmd === "web-calls") {
4769
+ if (cmd === "web-calls") {
1224
4770
  if (!a1) fail("numbers " + cmd + " <number> [get|on|off]");
1225
4771
  const action = a2 || "get";
1226
- const isMon = cmd === "monitor";
1227
4772
  if (action === "get") {
1228
- out(isMon ? await client.phoneNumbers.getMonitor(a1) : await client.phoneNumbers.getWebCalls(a1));
4773
+ out(await client.phoneNumbers.getWebCalls(a1));
1229
4774
  return;
1230
4775
  }
1231
4776
  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"));
4777
+ out(await client.phoneNumbers.setWebCalls(a1, action === "on"));
1234
4778
  return;
1235
4779
  }
1236
4780
  fail("numbers " + cmd + " <number> [get|on|off]");
1237
4781
  }
1238
- fail("numbers: list | import | update | delete | monitor | web-calls");
4782
+ fail("numbers: list | get | usage | import | update | delete | web-calls");
1239
4783
  }
1240
4784
  if (group === "callers") {
4785
+ if (cmd === "import" && values.body !== void 0) {
4786
+ out(await coreCallerImport(client, a1, bodyFrom(values)));
4787
+ return;
4788
+ }
1241
4789
  if (cmd === "get") {
1242
4790
  if (!a1 || !a2) fail("callers get <your_number> <caller_number>");
1243
4791
  const r = await client.callers.get(a1, a2);
@@ -1255,7 +4803,7 @@ async function main() {
1255
4803
  }
1256
4804
  if (cmd === "import") {
1257
4805
  if (!a1 || !a2) fail("callers import <your_number> <file.csv>");
1258
- const rows = parseCsv(readFileSync(a2, "utf8"));
4806
+ const rows = parseCsv(readFileSync4(a2, "utf8"));
1259
4807
  if (rows.length === 0) fail("no rows in " + a2);
1260
4808
  if (!("caller_number" in rows[0])) fail("the CSV needs a caller_number column");
1261
4809
  let imported = 0;
@@ -1282,7 +4830,7 @@ async function main() {
1282
4830
  }
1283
4831
  if (group === "sms") {
1284
4832
  if (cmd === "send") {
1285
- const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), to: s("to"), message: textOrFile(s("message")) });
4833
+ const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), to: s("to"), message: textOrFile(s("message")), ...contactFields(values) });
1286
4834
  if (!body.agent_id || !body.from_number || !body.to || !body.message) fail("sms send --agent ID --from +44... --to +44... --message TEXT");
1287
4835
  out(await client.sms.send(body));
1288
4836
  return;
@@ -1291,9 +4839,9 @@ async function main() {
1291
4839
  const sub = a1;
1292
4840
  const id = a2;
1293
4841
  if (sub === "create") {
1294
- const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), message: textOrFile(s("message")), name: s("name") });
4842
+ const body = bodyFrom(values, { agent_id: s("agent"), from_number: s("from"), message_template: textOrFile(s("message")), name: s("name") });
1295
4843
  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");
4844
+ if (!body.agent_id || !body.from_number || !body.message_template || !Array.isArray(body.recipients)) fail("sms campaigns create --agent ID --from +44... --message TEXT|@file --csv people.csv");
1297
4845
  out(await client.sms.campaigns.create(body));
1298
4846
  return;
1299
4847
  }
@@ -1306,18 +4854,19 @@ async function main() {
1306
4854
  const q = {};
1307
4855
  if (limit) q.limit = limit;
1308
4856
  if (s("status")) q.status = s("status");
4857
+ if (s("before")) q.before = s("before");
1309
4858
  const r = await client.sms.campaigns.list(q);
1310
4859
  out(JSON_MODE ? r : r.campaigns || r);
1311
4860
  return;
1312
4861
  }
1313
4862
  if (sub === "get") {
1314
4863
  if (!id) fail("sms campaigns get <id>");
1315
- out(await client.sms.campaigns.get(id));
4864
+ out(await client.sms.campaigns.get(id, smsPage(values)));
1316
4865
  return;
1317
4866
  }
1318
4867
  if (sub === "delete") {
1319
4868
  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;
4869
+ if (!await preview("sms campaign " + id + " (active campaigns are refused; deletion is not cancellation)", () => client.sms.campaigns.get(id))) return;
1321
4870
  out(await client.sms.campaigns.delete(id));
1322
4871
  return;
1323
4872
  }
@@ -1328,46 +4877,27 @@ async function main() {
1328
4877
  if (group === "webhooks") {
1329
4878
  if (cmd === "set") {
1330
4879
  if (!a1 || !a2) fail("webhooks set <number> <url> [--slot 1|2]");
1331
- out(await client.webhooks.set(a1, a2, slot));
4880
+ out(await privateIntegration(() => client.webhooks.set(a1, a2, slot)));
1332
4881
  return;
1333
4882
  }
1334
4883
  if (cmd === "get") {
1335
4884
  if (!a1) fail("webhooks get <number> [--slot 1|2]");
1336
- out(await client.webhooks.get(a1, slot));
4885
+ out(await privateIntegration(() => client.webhooks.get(a1, slot)));
1337
4886
  return;
1338
4887
  }
1339
4888
  if (cmd === "delete") {
1340
4889
  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));
4890
+ if (!await preview("webhook slot " + slot + " on " + a1, () => privateIntegration(() => client.webhooks.get(a1, slot)))) return;
4891
+ out(await privateIntegration(() => client.webhooks.delete(a1, slot)));
1343
4892
  return;
1344
4893
  }
1345
4894
  fail("webhooks: set | get | delete");
1346
4895
  }
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
4896
  fail('unknown command "' + group + '". Run `nixflex --help`.');
1367
4897
  }
1368
4898
  main().catch((e) => {
1369
4899
  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");
4900
+ if (JSON_MODE) process.stdout.write(JSON.stringify(errorOutput(e), null, 2) + "\n");
1371
4901
  else process.stderr.write("error " + (e.status || "") + " " + (e.code || "") + ": " + e.message + (e.docUrl ? "\n " + e.docUrl : "") + "\n");
1372
4902
  process.exitCode = 1;
1373
4903
  return;