@answerlayer/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js ADDED
@@ -0,0 +1,1330 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { AnswerLayerClient } from "./client.js";
4
+ import { formatJson, formatList, formatQueryResult } from "./format.js";
5
+ import { DEFAULT_BASE_URL, readConfig, resolveAuth, writeConfig } from "./config.js";
6
+
7
+ const SEMANTIC_RESOURCES = new Set([
8
+ "entities",
9
+ "relationships",
10
+ "measures",
11
+ "metrics",
12
+ "dimensions",
13
+ "filters",
14
+ ]);
15
+
16
+ export async function main(argv, io) {
17
+ const parsed = parseArgs(argv);
18
+ const [group, command, ...positionals] = parsed.positionals;
19
+
20
+ if (!group || group === "help" || parsed.flags.help || parsed.flags.h) {
21
+ write(io.stdout, helpText());
22
+ return;
23
+ }
24
+
25
+ if (group === "configure") {
26
+ return configure(parsed, io);
27
+ }
28
+
29
+ const { baseUrl, apiKey } = resolveAuth(parsed.flags, io.env);
30
+ const client = new AnswerLayerClient({ baseUrl, apiKey });
31
+
32
+ if (group === "health") return handleHealth(client, command, parsed, io);
33
+ if (group === "openapi") return handleOpenApi(client, parsed, io);
34
+ if (group === "auth") return handleAuth(client, command, parsed, io);
35
+ if (group === "api-keys" || group === "keys") return handleApiKeys(client, command, positionals, parsed, io);
36
+ if (group === "connections") return handleConnections(client, command, positionals, parsed, io);
37
+ if (group === "metadata") return handleMetadata(client, command, positionals, parsed, io);
38
+ if (group === "query") return handleQuery(client, command, positionals, parsed, io);
39
+ if (group === "query-results" || group === "results") return handleQueryResults(client, command, positionals, parsed, io);
40
+ if (group === "saved-queries" || group === "saved") return handleSavedQueries(client, command, positionals, parsed, io);
41
+ if (group === "semantic") return handleSemantic(client, command, positionals, parsed, io);
42
+ if (group === "inquiry") return handleInquiry(client, command, positionals, parsed, io);
43
+ if (group === "generation") return handleGeneration(client, command, positionals, parsed, io);
44
+ if (group === "tiles") return handleTiles(client, command, positionals, parsed, io);
45
+ if (group === "dashboards") return handleDashboards(client, command, positionals, parsed, io);
46
+ if (group === "documents" || group === "context-documents") return handleDocuments(client, command, positionals, parsed, io);
47
+ if (group === "branding") return handleBranding(client, command, positionals, parsed, io);
48
+ if (group === "uploads") return handleUploads(client, command, positionals, parsed, io);
49
+ if (group === "chains") return handleChains(client, command, positionals, parsed, io);
50
+ if (group === "users") return handleUsers(client, command, positionals, parsed, io);
51
+ if (group === "org" || group === "organization") return handleOrganization(client, command, positionals, parsed, io);
52
+ if (group === "roles") return handleRoles(client, command, positionals, parsed, io);
53
+ if (group === "billing") return handleBilling(client, command, positionals, parsed, io);
54
+ if (group === "stats") return handleStats(client, command, parsed, io);
55
+
56
+ throw usage(`Unknown command group: ${group}`);
57
+ }
58
+
59
+ function configure(parsed, io) {
60
+ const existing = readConfig(io.env);
61
+ const baseUrl = firstValue(parsed.flags.baseUrl) || existing.baseUrl || DEFAULT_BASE_URL;
62
+ const apiKey = firstValue(parsed.flags.apiKey) || existing.apiKey;
63
+
64
+ if (!apiKey) {
65
+ throw usage("configure requires --api-key (--base-url defaults to https://app.answerlayer.io)");
66
+ }
67
+
68
+ const configPath = writeConfig({ ...existing, baseUrl, apiKey }, io.env);
69
+ write(io.stdout, `Saved AnswerLayer config to ${configPath}\n`);
70
+ }
71
+
72
+ async function handleHealth(client, command, parsed, io) {
73
+ const pathName = command === "ready" ? "/api/v1/ready" : "/api/v1/health";
74
+ return requestAndPrint(client, "GET", pathName, parsed, io, { auth: false, okText: "ok" });
75
+ }
76
+
77
+ async function handleOpenApi(client, parsed, io) {
78
+ return requestAndPrint(client, "GET", "/openapi.json", parsed, io, { auth: false });
79
+ }
80
+
81
+ async function handleAuth(client, command, parsed, io) {
82
+ if (command === "me" || !command) {
83
+ return requestAndPrint(client, "GET", "/api/v1/auth/me", parsed, io);
84
+ }
85
+ if (command === "logout") {
86
+ return requestAndPrint(client, "POST", "/api/v1/auth/logout", parsed, io);
87
+ }
88
+ throw usage(`Unknown auth command: ${command}`);
89
+ }
90
+
91
+ async function handleApiKeys(client, command, positionals, parsed, io) {
92
+ if (command === "list" || !command) {
93
+ return requestAndPrint(client, "GET", "/api/v1/api-keys/", parsed, io, {
94
+ table: [
95
+ { key: "id", label: "ID" },
96
+ { key: "name", label: "Name" },
97
+ { key: "prefix", label: "Prefix" },
98
+ { key: "is_active", label: "Active" },
99
+ { key: "is_admin", label: "Admin" },
100
+ ],
101
+ });
102
+ }
103
+
104
+ if (command === "create") {
105
+ const payload = await readData(parsed.flags, io, {
106
+ name: firstValue(parsed.flags.name),
107
+ scopes: csvOrRepeated(parsed.flags.scope),
108
+ is_admin: Boolean(parsed.flags.admin),
109
+ connection_id: firstValue(parsed.flags.connection),
110
+ expires_at: firstValue(parsed.flags.expiresAt),
111
+ });
112
+ requirePayloadValue(payload, "name", "api-keys create requires --name");
113
+ return requestAndPrint(client, "POST", "/api/v1/api-keys/", parsed, io, { body: payload });
114
+ }
115
+
116
+ if (command === "revoke" || command === "delete") {
117
+ const id = requirePositional(positionals, 0, "API key id");
118
+ return requestAndPrint(client, "DELETE", `/api/v1/api-keys/${encodeURIComponent(id)}`, parsed, io);
119
+ }
120
+
121
+ throw usage(`Unknown api-keys command: ${command}`);
122
+ }
123
+
124
+ async function handleConnections(client, command, positionals, parsed, io) {
125
+ if (command === "supported" || command === "supported-types") {
126
+ return requestAndPrint(client, "GET", "/api/v1/connections/supported_types", parsed, io, {
127
+ table: [
128
+ { key: "id", label: "ID" },
129
+ { key: "label", label: "Name" },
130
+ { key: "supported", label: "Supported" },
131
+ ],
132
+ });
133
+ }
134
+
135
+ if (command === "list" || !command) {
136
+ return requestAndPrint(client, "GET", "/api/v1/connections/", parsed, io, {
137
+ table: [
138
+ { key: "id", label: "ID" },
139
+ { key: "name", label: "Name" },
140
+ { key: "db_type", label: "Type" },
141
+ { key: "status", label: "Status" },
142
+ ],
143
+ });
144
+ }
145
+
146
+ if (command === "get") {
147
+ const id = requirePositional(positionals, 0, "connection id");
148
+ return requestAndPrint(client, "GET", `/api/v1/connections/${encodeURIComponent(id)}`, parsed, io);
149
+ }
150
+
151
+ if (command === "create") {
152
+ const payload = await readData(parsed.flags, io, {
153
+ name: firstValue(parsed.flags.name),
154
+ db_type: firstValue(parsed.flags.type) || firstValue(parsed.flags.dbType),
155
+ config: parseJsonFlag(firstValue(parsed.flags.config), "config"),
156
+ });
157
+ return requestAndPrint(client, "POST", "/api/v1/connections/", parsed, io, { body: payload });
158
+ }
159
+
160
+ if (command === "update") {
161
+ const id = requirePositional(positionals, 0, "connection id");
162
+ return requestAndPrint(client, "PUT", `/api/v1/connections/${encodeURIComponent(id)}`, parsed, io, {
163
+ body: await readData(parsed.flags, io),
164
+ });
165
+ }
166
+
167
+ if (command === "delete") {
168
+ const id = requirePositional(positionals, 0, "connection id");
169
+ return requestAndPrint(client, "DELETE", `/api/v1/connections/${encodeURIComponent(id)}`, parsed, io);
170
+ }
171
+
172
+ if (command === "schema") {
173
+ const id = requirePositional(positionals, 0, "connection id");
174
+ return requestAndPrint(client, "GET", `/api/v1/connections/${encodeURIComponent(id)}/schema`, parsed, io);
175
+ }
176
+
177
+ if (command === "config-schema") {
178
+ const dbType = requirePositional(positionals, 0, "database type");
179
+ return requestAndPrint(client, "GET", `/api/v1/connections/config_schema/${encodeURIComponent(dbType)}`, parsed, io);
180
+ }
181
+
182
+ if (command === "check-limit") {
183
+ return requestAndPrint(client, "GET", "/api/v1/connections/check_limit", parsed, io);
184
+ }
185
+
186
+ if (command === "request-type") {
187
+ const dbType = firstValue(parsed.flags.type) || requirePositional(positionals, 0, "database type");
188
+ return requestAndPrint(client, "POST", "/api/v1/connections/request_type", parsed, io, {
189
+ body: { db_type: dbType },
190
+ });
191
+ }
192
+
193
+ if (command === "test") {
194
+ const id = firstValue(parsed.flags.connection);
195
+ const payload = await readData(parsed.flags, io);
196
+ const pathName = id
197
+ ? `/api/v1/connections/${encodeURIComponent(id)}/test_existing`
198
+ : "/api/v1/connections/test_new_connection";
199
+ return requestAndPrint(client, "POST", pathName, parsed, io, { body: payload });
200
+ }
201
+
202
+ if (command === "preview-tables") {
203
+ return requestAndPrint(client, "POST", "/api/v1/connections/preview_tables", parsed, io, {
204
+ body: await readData(parsed.flags, io),
205
+ });
206
+ }
207
+
208
+ throw usage(`Unknown connections command: ${command}`);
209
+ }
210
+
211
+ async function handleMetadata(client, command, positionals, parsed, io) {
212
+ if (command === "structure") {
213
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 0, "connection id");
214
+ return requestAndPrint(client, "GET", `/api/v1/metadata/structure/${encodeURIComponent(connectionId)}`, parsed, io, {
215
+ query: { include_pii: firstValue(parsed.flags.includePii) },
216
+ });
217
+ }
218
+ if (command === "tables") {
219
+ const schemaId = requirePositional(positionals, 0, "schema id");
220
+ return requestAndPrint(client, "GET", `/api/v1/metadata/tables/${encodeURIComponent(schemaId)}`, parsed, io);
221
+ }
222
+ if (command === "columns") {
223
+ const tableId = requirePositional(positionals, 0, "table id");
224
+ return requestAndPrint(client, "GET", `/api/v1/metadata/columns/${encodeURIComponent(tableId)}`, parsed, io);
225
+ }
226
+ if (command === "pii-summary") {
227
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 0, "connection id");
228
+ return requestAndPrint(client, "GET", `/api/v1/metadata/${encodeURIComponent(connectionId)}/pii/summary`, parsed, io);
229
+ }
230
+ if (command === "pii-settings") {
231
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 0, "connection id");
232
+ return requestAndPrint(client, "PUT", `/api/v1/metadata/${encodeURIComponent(connectionId)}/pii/settings`, parsed, io, {
233
+ body: await readData(parsed.flags, io),
234
+ });
235
+ }
236
+ if (command === "detect-pii") {
237
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 0, "connection id");
238
+ return requestAndPrint(client, "POST", `/api/v1/metadata/${encodeURIComponent(connectionId)}/pii/detect-stream`, parsed, io, {
239
+ body: await readData(parsed.flags, io, {}),
240
+ rawDefault: true,
241
+ });
242
+ }
243
+ throw usage(`Unknown metadata command: ${command}`);
244
+ }
245
+
246
+ async function handleQuery(client, command, positionals, parsed, io) {
247
+ if (command !== "run" && command !== "validate" && command !== "export") {
248
+ throw usage("Expected query run, query validate, or query export");
249
+ }
250
+
251
+ const connectionId = requirePositional(positionals, 0, "connection id");
252
+ const sql = await readSql(parsed.flags, positionals.slice(1), io);
253
+ const payload = queryPayload(parsed.flags, sql);
254
+
255
+ if (command === "validate") {
256
+ return requestAndPrint(client, "POST", `/api/v1/query/${encodeURIComponent(connectionId)}/validate`, parsed, io, {
257
+ body: payload,
258
+ });
259
+ }
260
+
261
+ if (command === "export") {
262
+ const format = firstValue(parsed.flags.format) || "csv";
263
+ return requestAndPrint(client, "POST", `/api/v1/query/${encodeURIComponent(connectionId)}/export`, parsed, io, {
264
+ body: payload,
265
+ query: { format },
266
+ rawDefault: true,
267
+ });
268
+ }
269
+
270
+ const result = await client.request("POST", `/api/v1/query/${encodeURIComponent(connectionId)}`, { body: payload });
271
+ write(io.stdout, parsed.flags.json ? formatJson(result) : formatQueryResult(result, firstValue(parsed.flags.format) || "table"));
272
+ }
273
+
274
+ async function handleQueryResults(client, command, positionals, parsed, io) {
275
+ if (command === "get" || command === "fetch" || !command) {
276
+ const handle = requirePositional(positionals, 0, "result handle");
277
+ return requestAndPrint(client, "GET", `/api/v1/query-results/${encodeURIComponent(handle)}`, parsed, io, {
278
+ query: {
279
+ cursor: firstValue(parsed.flags.cursor),
280
+ limit: firstValue(parsed.flags.limit),
281
+ },
282
+ });
283
+ }
284
+ if (command === "delete") {
285
+ const handle = requirePositional(positionals, 0, "result handle");
286
+ return requestAndPrint(client, "DELETE", `/api/v1/query-results/${encodeURIComponent(handle)}`, parsed, io);
287
+ }
288
+ throw usage(`Unknown query-results command: ${command}`);
289
+ }
290
+
291
+ async function handleSavedQueries(client, command, positionals, parsed, io) {
292
+ if (command === "list" || !command) {
293
+ return requestAndPrint(client, "GET", "/api/v1/saved-queries", parsed, io, {
294
+ tableDataKey: "saved_queries",
295
+ table: [
296
+ { key: "id", label: "ID" },
297
+ { key: "name", label: "Name" },
298
+ { key: "visibility", label: "Visibility" },
299
+ { key: "connection_id", label: "Connection" },
300
+ ],
301
+ });
302
+ }
303
+ if (command === "get") {
304
+ const id = requirePositional(positionals, 0, "saved query id");
305
+ return requestAndPrint(client, "GET", `/api/v1/saved-queries/${encodeURIComponent(id)}`, parsed, io);
306
+ }
307
+ if (command === "create") {
308
+ const payload = await readData(parsed.flags, io, {
309
+ name: firstValue(parsed.flags.name),
310
+ description: firstValue(parsed.flags.description),
311
+ visibility: firstValue(parsed.flags.visibility),
312
+ sql: await optionalSql(parsed.flags, positionals, io),
313
+ connection_id: firstValue(parsed.flags.connection),
314
+ });
315
+ return requestAndPrint(client, "POST", "/api/v1/saved-queries", parsed, io, { body: payload });
316
+ }
317
+ if (command === "from-turn") {
318
+ const payload = await readData(parsed.flags, io, {
319
+ inquiry_turn_id: firstValue(parsed.flags.turn),
320
+ name: firstValue(parsed.flags.name),
321
+ description: firstValue(parsed.flags.description),
322
+ visibility: firstValue(parsed.flags.visibility),
323
+ });
324
+ return requestAndPrint(client, "POST", "/api/v1/saved-queries/from-inquiry-turn", parsed, io, { body: payload });
325
+ }
326
+ if (command === "update") {
327
+ const id = requirePositional(positionals, 0, "saved query id");
328
+ const payload = await readData(parsed.flags, io, {
329
+ name: firstValue(parsed.flags.name),
330
+ description: firstValue(parsed.flags.description),
331
+ visibility: firstValue(parsed.flags.visibility),
332
+ sql: await optionalSql(parsed.flags, positionals.slice(1), io),
333
+ connection_id: firstValue(parsed.flags.connection),
334
+ });
335
+ return requestAndPrint(client, "PATCH", `/api/v1/saved-queries/${encodeURIComponent(id)}`, parsed, io, { body: payload });
336
+ }
337
+ if (command === "delete") {
338
+ const id = requirePositional(positionals, 0, "saved query id");
339
+ return requestAndPrint(client, "DELETE", `/api/v1/saved-queries/${encodeURIComponent(id)}`, parsed, io);
340
+ }
341
+ if (command === "approve" || command === "unapprove") {
342
+ const id = requirePositional(positionals, 0, "saved query id");
343
+ const method = command === "approve" ? "POST" : "DELETE";
344
+ return requestAndPrint(client, method, `/api/v1/saved-queries/${encodeURIComponent(id)}/approve`, parsed, io);
345
+ }
346
+ if (command === "execute") {
347
+ const id = requirePositional(positionals, 0, "saved query id");
348
+ const result = await client.request("POST", `/api/v1/saved-queries/${encodeURIComponent(id)}/execute`, {
349
+ body: {
350
+ params: parseJsonFlag(firstValue(parsed.flags.params), "params"),
351
+ row_limit: parseInteger(firstValue(parsed.flags.rowLimit), 1000),
352
+ timeout: parseInteger(firstValue(parsed.flags.timeout), 30),
353
+ },
354
+ });
355
+ write(io.stdout, parsed.flags.json ? formatJson(result) : formatQueryResult(result, firstValue(parsed.flags.format) || "table"));
356
+ return;
357
+ }
358
+ throw usage(`Unknown saved-queries command: ${command}`);
359
+ }
360
+
361
+ async function handleSemantic(client, command, positionals, parsed, io) {
362
+ const resource = command;
363
+ if (!SEMANTIC_RESOURCES.has(resource)) {
364
+ throw usage(`Expected semantic resource: ${Array.from(SEMANTIC_RESOURCES).join(", ")}`);
365
+ }
366
+
367
+ const [verb = "list", idOrRest, ...rest] = positionals;
368
+ const base = `/api/v1/semantic/${resource}`;
369
+ const connectionId = firstValue(parsed.flags.connection);
370
+ const itemName = resource.replace(/s$/, "");
371
+ const query = { connection_id: connectionId };
372
+
373
+ if (verb === "list") {
374
+ requireConnection(connectionId, `semantic ${resource} list`);
375
+ return requestAndPrint(client, "GET", base, parsed, io, {
376
+ query,
377
+ tableDataKey: resource,
378
+ table: [
379
+ { key: "id", label: "ID" },
380
+ { key: "name", label: "Name" },
381
+ { key: "entity", label: "Entity" },
382
+ { key: "description", label: "Description" },
383
+ ],
384
+ });
385
+ }
386
+ if (verb === "get") {
387
+ const id = requirePositional([idOrRest], 0, `${itemName} id`);
388
+ return requestAndPrint(client, "GET", `${base}/${encodeURIComponent(id)}`, parsed, io, { query });
389
+ }
390
+ if (verb === "create") {
391
+ requireConnection(connectionId, `semantic ${resource} create`);
392
+ return requestAndPrint(client, "POST", base, parsed, io, {
393
+ query,
394
+ body: await semanticPayload(resource, parsed.flags, [idOrRest, ...rest].filter(Boolean), io),
395
+ });
396
+ }
397
+ if (verb === "update") {
398
+ requireConnection(connectionId, `semantic ${resource} update`);
399
+ const id = requirePositional([idOrRest], 0, `${itemName} id`);
400
+ return requestAndPrint(client, "PUT", `${base}/${encodeURIComponent(id)}`, parsed, io, {
401
+ query,
402
+ body: await semanticPayload(resource, parsed.flags, rest, io),
403
+ });
404
+ }
405
+ if (verb === "delete") {
406
+ requireConnection(connectionId, `semantic ${resource} delete`);
407
+ const id = requirePositional([idOrRest], 0, `${itemName} id`);
408
+ return requestAndPrint(client, "DELETE", `${base}/${encodeURIComponent(id)}`, parsed, io, { query });
409
+ }
410
+ if (verb === "delete-all") {
411
+ requireConnection(connectionId, `semantic ${resource} delete-all`);
412
+ return requestAndPrint(client, "DELETE", `${base}/all`, parsed, io, { query });
413
+ }
414
+ if (verb === "generate") {
415
+ requireConnection(connectionId, `semantic ${resource} generate`);
416
+ return requestAndPrint(client, "POST", `${base}/generate/stream`, parsed, io, {
417
+ body: await readData(parsed.flags, io, {
418
+ connection_id: connectionId,
419
+ prompt: firstValue(parsed.flags.prompt),
420
+ model: firstValue(parsed.flags.model),
421
+ options: parseJsonFlag(firstValue(parsed.flags.options), "options"),
422
+ }),
423
+ rawDefault: true,
424
+ });
425
+ }
426
+
427
+ throw usage(`Unknown semantic ${resource} command: ${verb}`);
428
+ }
429
+
430
+ async function handleInquiry(client, command, positionals, parsed, io) {
431
+ if (command === "ask") {
432
+ const question = firstValue(parsed.flags.question) || positionals.join(" ");
433
+ const connectionId = firstValue(parsed.flags.connection);
434
+ if (!question.trim()) throw usage("inquiry ask requires a question");
435
+
436
+ let sessionId = firstValue(parsed.flags.session);
437
+ if (!sessionId) {
438
+ if (!connectionId) throw usage("inquiry ask requires --connection when --session is not provided");
439
+ const session = await client.request("POST", "/api/v1/inquiry/sessions", {
440
+ body: { connection_id: connectionId, model: firstValue(parsed.flags.model) },
441
+ });
442
+ sessionId = session.session_id;
443
+ }
444
+
445
+ const result = await client.request("POST", `/api/v1/inquiry/sessions/${encodeURIComponent(sessionId)}/sync`, {
446
+ body: { user_input: question },
447
+ });
448
+ if (parsed.flags.json) {
449
+ write(io.stdout, formatJson({ session_id: sessionId, ...result }));
450
+ return;
451
+ }
452
+ write(io.stdout, `${result.final_response}\n`);
453
+ if (result.sql_queries && result.sql_queries.length > 0) {
454
+ write(io.stdout, "\nSQL:\n");
455
+ for (const sql of result.sql_queries) write(io.stdout, `${sql}\n`);
456
+ }
457
+ return;
458
+ }
459
+
460
+ if (command === "sessions" || command === "list") {
461
+ return requestAndPrint(client, "GET", "/api/v1/inquiry/sessions", parsed, io, {
462
+ query: {
463
+ connection_id: firstValue(parsed.flags.connection),
464
+ status: firstValue(parsed.flags.status),
465
+ limit: firstValue(parsed.flags.limit),
466
+ offset: firstValue(parsed.flags.offset),
467
+ },
468
+ table: [
469
+ { key: "id", label: "ID" },
470
+ { key: "connection_id", label: "Connection" },
471
+ { key: "status", label: "Status" },
472
+ { key: "turn_count", label: "Turns" },
473
+ ],
474
+ });
475
+ }
476
+
477
+ if (command === "create-session") {
478
+ return requestAndPrint(client, "POST", "/api/v1/inquiry/sessions", parsed, io, {
479
+ body: await readData(parsed.flags, io, {
480
+ connection_id: firstValue(parsed.flags.connection),
481
+ model: firstValue(parsed.flags.model),
482
+ }),
483
+ });
484
+ }
485
+
486
+ if (command === "session") {
487
+ const id = requirePositional(positionals, 0, "session id");
488
+ return requestAndPrint(client, "GET", `/api/v1/inquiry/sessions/${encodeURIComponent(id)}`, parsed, io);
489
+ }
490
+
491
+ if (command === "update-session") {
492
+ const id = requirePositional(positionals, 0, "session id");
493
+ return requestAndPrint(client, "PATCH", `/api/v1/inquiry/sessions/${encodeURIComponent(id)}`, parsed, io, {
494
+ body: await readData(parsed.flags, io, {
495
+ status: firstValue(parsed.flags.status),
496
+ thread_summary: firstValue(parsed.flags.summary),
497
+ }),
498
+ });
499
+ }
500
+
501
+ if (command === "delete-session") {
502
+ const id = requirePositional(positionals, 0, "session id");
503
+ return requestAndPrint(client, "DELETE", `/api/v1/inquiry/sessions/${encodeURIComponent(id)}`, parsed, io);
504
+ }
505
+
506
+ if (command === "turn") {
507
+ const sessionId = requirePositional(positionals, 0, "session id");
508
+ const turnId = requirePositional(positionals, 1, "turn id");
509
+ return requestAndPrint(client, "GET", `/api/v1/inquiry/sessions/${encodeURIComponent(sessionId)}/turns/${encodeURIComponent(turnId)}`, parsed, io);
510
+ }
511
+
512
+ throw usage(`Unknown inquiry command: ${command}`);
513
+ }
514
+
515
+ async function handleGeneration(client, command, positionals, parsed, io) {
516
+ const base = "/api/v1/semantic/jobs";
517
+ if (command === "start" || command === "create") {
518
+ return requestAndPrint(client, "POST", base, parsed, io, {
519
+ body: await readData(parsed.flags, io),
520
+ });
521
+ }
522
+ if (command === "list" || !command) {
523
+ return requestAndPrint(client, "GET", base, parsed, io, {
524
+ query: { connection_id: firstValue(parsed.flags.connection) },
525
+ });
526
+ }
527
+ const jobId = requirePositional(positionals, 0, "job id");
528
+ if (command === "get") return requestAndPrint(client, "GET", `${base}/${encodeURIComponent(jobId)}`, parsed, io);
529
+ if (command === "status") return requestAndPrint(client, "GET", `${base}/${encodeURIComponent(jobId)}/status`, parsed, io);
530
+ if (command === "stream") return requestAndPrint(client, "GET", `${base}/${encodeURIComponent(jobId)}/stream`, parsed, io, { rawDefault: true });
531
+ if (command === "cancel") return requestAndPrint(client, "POST", `${base}/${encodeURIComponent(jobId)}/cancel`, parsed, io);
532
+ if (command === "questions") return requestAndPrint(client, "GET", `${base}/${encodeURIComponent(jobId)}/questions`, parsed, io);
533
+ if (command === "guidance") return requestAndPrint(client, "POST", `${base}/${encodeURIComponent(jobId)}/guidance`, parsed, io, { body: await readData(parsed.flags, io) });
534
+ if (command === "delete") return requestAndPrint(client, "DELETE", `${base}/${encodeURIComponent(jobId)}`, parsed, io);
535
+ throw usage(`Unknown generation command: ${command}`);
536
+ }
537
+
538
+ async function handleTiles(client, command, positionals, parsed, io) {
539
+ if (command === "list" || !command) {
540
+ return requestAndPrint(client, "GET", "/api/v1/tiles", parsed, io, {
541
+ query: { dashboard_id: firstValue(parsed.flags.dashboard) },
542
+ tableDataKey: "tiles",
543
+ table: [
544
+ { key: "id", label: "ID" },
545
+ { key: "title", label: "Title" },
546
+ { key: "source_type", label: "Source" },
547
+ { key: "visibility", label: "Visibility" },
548
+ ],
549
+ });
550
+ }
551
+ if (command === "get") {
552
+ const id = requirePositional(positionals, 0, "tile id");
553
+ return requestAndPrint(client, "GET", `/api/v1/tiles/${encodeURIComponent(id)}`, parsed, io);
554
+ }
555
+ if (command === "create") {
556
+ return requestAndPrint(client, "POST", "/api/v1/tiles", parsed, io, {
557
+ body: await readData(parsed.flags, io, {
558
+ title: firstValue(parsed.flags.title) || firstValue(parsed.flags.name),
559
+ description: firstValue(parsed.flags.description),
560
+ visibility: firstValue(parsed.flags.visibility),
561
+ source_type: firstValue(parsed.flags.sourceType),
562
+ source_ref: firstValue(parsed.flags.source),
563
+ visualization: parseJsonFlag(firstValue(parsed.flags.visualization), "visualization"),
564
+ }),
565
+ });
566
+ }
567
+ if (command === "update") {
568
+ const id = requirePositional(positionals, 0, "tile id");
569
+ return requestAndPrint(client, "PATCH", `/api/v1/tiles/${encodeURIComponent(id)}`, parsed, io, {
570
+ body: await readData(parsed.flags, io, {
571
+ title: firstValue(parsed.flags.title) || firstValue(parsed.flags.name),
572
+ description: firstValue(parsed.flags.description),
573
+ visibility: firstValue(parsed.flags.visibility),
574
+ visualization: parseJsonFlag(firstValue(parsed.flags.visualization), "visualization"),
575
+ }),
576
+ });
577
+ }
578
+ if (command === "data") {
579
+ const id = requirePositional(positionals, 0, "tile id");
580
+ return requestAndPrint(client, "POST", `/api/v1/tiles/${encodeURIComponent(id)}/data`, parsed, io, {
581
+ body: await readData(parsed.flags, io, { filters: parseJsonFlag(firstValue(parsed.flags.filters), "filters") }),
582
+ });
583
+ }
584
+ if (command === "delete") {
585
+ const id = requirePositional(positionals, 0, "tile id");
586
+ return requestAndPrint(client, "DELETE", `/api/v1/tiles/${encodeURIComponent(id)}`, parsed, io);
587
+ }
588
+ throw usage(`Unknown tiles command: ${command}`);
589
+ }
590
+
591
+ async function handleDashboards(client, command, positionals, parsed, io) {
592
+ if (command === "list" || !command) {
593
+ return requestAndPrint(client, "GET", "/api/v1/dashboards", parsed, io, {
594
+ tableDataKey: "dashboards",
595
+ table: [
596
+ { key: "id", label: "ID" },
597
+ { key: "title", label: "Title" },
598
+ { key: "visibility", label: "Visibility" },
599
+ { key: "updated_at", label: "Updated" },
600
+ ],
601
+ });
602
+ }
603
+ if (command === "get" || command === "manifest" || command === "saved-queries") {
604
+ const id = requirePositional(positionals, 0, "dashboard id");
605
+ const suffix = command === "get" ? "" : `/${command}`;
606
+ return requestAndPrint(client, "GET", `/api/v1/dashboards/${encodeURIComponent(id)}${suffix}`, parsed, io);
607
+ }
608
+ if (command === "create") {
609
+ return requestAndPrint(client, "POST", "/api/v1/dashboards", parsed, io, {
610
+ body: await readData(parsed.flags, io, {
611
+ title: firstValue(parsed.flags.title) || firstValue(parsed.flags.name),
612
+ description: firstValue(parsed.flags.description),
613
+ visibility: firstValue(parsed.flags.visibility),
614
+ default_filters: parseJsonFlag(firstValue(parsed.flags.filters), "filters"),
615
+ }),
616
+ });
617
+ }
618
+ if (command === "update") {
619
+ const id = requirePositional(positionals, 0, "dashboard id");
620
+ return requestAndPrint(client, "PATCH", `/api/v1/dashboards/${encodeURIComponent(id)}`, parsed, io, {
621
+ body: await readData(parsed.flags, io, {
622
+ title: firstValue(parsed.flags.title) || firstValue(parsed.flags.name),
623
+ description: firstValue(parsed.flags.description),
624
+ visibility: firstValue(parsed.flags.visibility),
625
+ default_filters: parseJsonFlag(firstValue(parsed.flags.filters), "filters"),
626
+ }),
627
+ });
628
+ }
629
+ if (command === "delete" || command === "duplicate") {
630
+ const id = requirePositional(positionals, 0, "dashboard id");
631
+ const method = command === "delete" ? "DELETE" : "POST";
632
+ const suffix = command === "delete" ? "" : "/duplicate";
633
+ return requestAndPrint(client, method, `/api/v1/dashboards/${encodeURIComponent(id)}${suffix}`, parsed, io);
634
+ }
635
+ if (command === "tile-data") {
636
+ const dashboardId = requirePositional(positionals, 0, "dashboard id");
637
+ const tileId = requirePositional(positionals, 1, "tile id");
638
+ return requestAndPrint(client, "POST", `/api/v1/dashboards/${encodeURIComponent(dashboardId)}/tiles/${encodeURIComponent(tileId)}/data`, parsed, io, {
639
+ body: await readData(parsed.flags, io, {
640
+ filters: parseJsonFlag(firstValue(parsed.flags.filters), "filters"),
641
+ pagination: paginationPayload(parsed.flags),
642
+ result_handle: firstValue(parsed.flags.resultHandle),
643
+ }),
644
+ });
645
+ }
646
+ if (command === "attach-tile") {
647
+ const dashboardId = requirePositional(positionals, 0, "dashboard id");
648
+ return requestAndPrint(client, "POST", `/api/v1/dashboards/${encodeURIComponent(dashboardId)}/tiles`, parsed, io, {
649
+ body: await readData(parsed.flags, io, {
650
+ tile_id: firstValue(parsed.flags.tile),
651
+ position: positionPayload(parsed.flags),
652
+ }),
653
+ });
654
+ }
655
+ if (command === "move-tile") {
656
+ const dashboardId = requirePositional(positionals, 0, "dashboard id");
657
+ const tileId = requirePositional(positionals, 1, "tile id");
658
+ return requestAndPrint(client, "PATCH", `/api/v1/dashboards/${encodeURIComponent(dashboardId)}/tiles/${encodeURIComponent(tileId)}`, parsed, io, {
659
+ body: await readData(parsed.flags, io, { position: positionPayload(parsed.flags) }),
660
+ });
661
+ }
662
+ if (command === "detach-tile") {
663
+ const dashboardId = requirePositional(positionals, 0, "dashboard id");
664
+ const tileId = requirePositional(positionals, 1, "tile id");
665
+ return requestAndPrint(client, "DELETE", `/api/v1/dashboards/${encodeURIComponent(dashboardId)}/tiles/${encodeURIComponent(tileId)}`, parsed, io);
666
+ }
667
+ if (command === "assignments") {
668
+ const id = requirePositional(positionals, 0, "dashboard id");
669
+ return requestAndPrint(client, "GET", `/api/v1/dashboards/${encodeURIComponent(id)}/assignments`, parsed, io);
670
+ }
671
+ if (command === "assign") {
672
+ const id = requirePositional(positionals, 0, "dashboard id");
673
+ return requestAndPrint(client, "POST", `/api/v1/dashboards/${encodeURIComponent(id)}/assignments`, parsed, io, {
674
+ body: await readData(parsed.flags, io, {
675
+ user_id: firstValue(parsed.flags.user),
676
+ email: firstValue(parsed.flags.email),
677
+ }),
678
+ });
679
+ }
680
+ if (command === "unassign") {
681
+ const dashboardId = requirePositional(positionals, 0, "dashboard id");
682
+ const userId = firstValue(parsed.flags.user) || requirePositional(positionals, 1, "user id");
683
+ return requestAndPrint(client, "DELETE", `/api/v1/dashboards/${encodeURIComponent(dashboardId)}/assignments/${encodeURIComponent(userId)}`, parsed, io);
684
+ }
685
+ throw usage(`Unknown dashboards command: ${command}`);
686
+ }
687
+
688
+ async function handleDocuments(client, command, positionals, parsed, io) {
689
+ if (command === "list" || !command) {
690
+ return requestAndPrint(client, "GET", "/api/v1/context-documents/", parsed, io, {
691
+ query: { limit: firstValue(parsed.flags.limit), offset: firstValue(parsed.flags.offset) },
692
+ table: [
693
+ { key: "id", label: "ID" },
694
+ { key: "title", label: "Title" },
695
+ { key: "document_type", label: "Type" },
696
+ { key: "created_at", label: "Created" },
697
+ ],
698
+ });
699
+ }
700
+ if (command === "upload") {
701
+ const file = firstValue(parsed.flags.file) || requirePositional(positionals, 0, "document file");
702
+ return requestAndPrint(client, "POST", "/api/v1/context-documents/upload", parsed, io, {
703
+ body: multipart({
704
+ file,
705
+ fields: {
706
+ title: firstValue(parsed.flags.title) || firstValue(parsed.flags.name) || path.basename(file),
707
+ description: firstValue(parsed.flags.description),
708
+ },
709
+ }),
710
+ });
711
+ }
712
+ if (command === "get" || command === "connections") {
713
+ const id = requirePositional(positionals, 0, "document id");
714
+ const suffix = command === "connections" ? "/connections" : "";
715
+ return requestAndPrint(client, "GET", `/api/v1/context-documents/${encodeURIComponent(id)}${suffix}`, parsed, io);
716
+ }
717
+ if (command === "update") {
718
+ const id = requirePositional(positionals, 0, "document id");
719
+ return requestAndPrint(client, "PATCH", `/api/v1/context-documents/${encodeURIComponent(id)}`, parsed, io, {
720
+ body: await readData(parsed.flags, io, {
721
+ title: firstValue(parsed.flags.title) || firstValue(parsed.flags.name),
722
+ description: firstValue(parsed.flags.description),
723
+ }),
724
+ });
725
+ }
726
+ if (command === "delete") {
727
+ const id = requirePositional(positionals, 0, "document id");
728
+ return requestAndPrint(client, "DELETE", `/api/v1/context-documents/${encodeURIComponent(id)}`, parsed, io);
729
+ }
730
+ if (command === "link") {
731
+ const id = requirePositional(positionals, 0, "document id");
732
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 1, "connection id");
733
+ return requestAndPrint(client, "POST", `/api/v1/context-documents/${encodeURIComponent(id)}/link`, parsed, io, {
734
+ body: { connection_id: connectionId },
735
+ });
736
+ }
737
+ if (command === "unlink") {
738
+ const id = requirePositional(positionals, 0, "document id");
739
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 1, "connection id");
740
+ return requestAndPrint(client, "DELETE", `/api/v1/context-documents/${encodeURIComponent(id)}/link/${encodeURIComponent(connectionId)}`, parsed, io);
741
+ }
742
+ if (command === "for-connection") {
743
+ const connectionId = firstValue(parsed.flags.connection) || requirePositional(positionals, 0, "connection id");
744
+ return requestAndPrint(client, "GET", `/api/v1/context-documents/connections/${encodeURIComponent(connectionId)}/documents`, parsed, io);
745
+ }
746
+ throw usage(`Unknown documents command: ${command}`);
747
+ }
748
+
749
+ async function handleBranding(client, command, positionals, parsed, io) {
750
+ if (command === "get" || !command) {
751
+ return requestAndPrint(client, "GET", "/api/v1/branding", parsed, io);
752
+ }
753
+ if (command === "update") {
754
+ return requestAndPrint(client, "PATCH", "/api/v1/branding", parsed, io, {
755
+ body: await readData(parsed.flags, io),
756
+ });
757
+ }
758
+ if (command === "upload") {
759
+ const file = firstValue(parsed.flags.file) || requirePositional(positionals, 0, "asset file");
760
+ return requestAndPrint(client, "POST", "/api/v1/branding/assets", parsed, io, {
761
+ body: multipart({ file }),
762
+ });
763
+ }
764
+ if (command === "extract") {
765
+ const file = firstValue(parsed.flags.file) || requirePositional(positionals, 0, "design file");
766
+ return requestAndPrint(client, "POST", "/api/v1/branding/extract", parsed, io, {
767
+ body: multipart({ file }),
768
+ });
769
+ }
770
+ if (command === "asset") {
771
+ const name = requirePositional(positionals, 0, "asset name");
772
+ return requestAndPrint(client, "GET", `/api/v1/branding/assets/${encodeURIComponent(name)}`, parsed, io, { rawDefault: true });
773
+ }
774
+ throw usage(`Unknown branding command: ${command}`);
775
+ }
776
+
777
+ async function handleUploads(client, command, positionals, parsed, io) {
778
+ if (command !== "csv" && command !== "duckdb") {
779
+ throw usage("Expected uploads csv or uploads duckdb");
780
+ }
781
+
782
+ const base = `/api/v1/${command}`;
783
+ const action = positionals[0] || "upload";
784
+ if (action === "upload") {
785
+ const file = firstValue(parsed.flags.file) || requirePositional(positionals, 1, "file");
786
+ const formFields = Object.fromEntries(allValues(parsed.flags.form).map((item) => parsePair(item, "--form")));
787
+ const namedFields = command === "csv"
788
+ ? {
789
+ name: firstValue(parsed.flags.name),
790
+ description: firstValue(parsed.flags.description),
791
+ auto_pii_detection: firstValue(parsed.flags["auto-pii-detection"]),
792
+ has_header: firstValue(parsed.flags["has-header"]),
793
+ delimiter: firstValue(parsed.flags.delimiter),
794
+ quote_char: firstValue(parsed.flags["quote-char"]),
795
+ encoding: firstValue(parsed.flags.encoding),
796
+ }
797
+ : {
798
+ name: firstValue(parsed.flags.name),
799
+ description: firstValue(parsed.flags.description),
800
+ };
801
+ return requestAndPrint(client, "POST", `${base}/upload`, parsed, io, {
802
+ body: multipart({ file, fields: { ...namedFields, ...formFields } }),
803
+ });
804
+ }
805
+ if (action === "status") {
806
+ const id = firstValue(parsed.flags.connection) || requirePositional(positionals, 1, "connection id");
807
+ return requestAndPrint(client, "GET", `${base}/${encodeURIComponent(id)}/processing-status`, parsed, io);
808
+ }
809
+ if (command === "csv" && action === "reprocess") {
810
+ const id = firstValue(parsed.flags.connection) || requirePositional(positionals, 1, "connection id");
811
+ return requestAndPrint(client, "POST", `${base}/${encodeURIComponent(id)}/reprocess`, parsed, io);
812
+ }
813
+ throw usage(`Unknown uploads ${command} command: ${action}`);
814
+ }
815
+
816
+ async function handleChains(client, command, positionals, parsed, io) {
817
+ if (command === "list" || !command) {
818
+ return requestAndPrint(client, "GET", "/api/v1/chains/", parsed, io, {
819
+ query: { limit: firstValue(parsed.flags.limit) },
820
+ });
821
+ }
822
+ if (command === "answers") {
823
+ const id = requirePositional(positionals, 0, "chain id");
824
+ return requestAndPrint(client, "GET", `/api/v1/chains/${encodeURIComponent(id)}/answers`, parsed, io, {
825
+ query: { limit: firstValue(parsed.flags.limit) },
826
+ });
827
+ }
828
+ throw usage(`Unknown chains command: ${command}`);
829
+ }
830
+
831
+ async function handleUsers(client, command, positionals, parsed, io) {
832
+ if (command === "me" || !command) return requestAndPrint(client, "GET", "/api/v1/users/me", parsed, io);
833
+ if (command === "update-me") return requestAndPrint(client, "PUT", "/api/v1/users/me", parsed, io, { body: await readData(parsed.flags, io) });
834
+ if (command === "list") return requestAndPrint(client, "GET", "/api/v1/users/", parsed, io);
835
+ if (command === "get") {
836
+ const id = requirePositional(positionals, 0, "user id");
837
+ return requestAndPrint(client, "GET", `/api/v1/users/${encodeURIComponent(id)}`, parsed, io);
838
+ }
839
+ if (command === "update") {
840
+ const id = requirePositional(positionals, 0, "user id");
841
+ return requestAndPrint(client, "PUT", `/api/v1/users/${encodeURIComponent(id)}`, parsed, io, { body: await readData(parsed.flags, io) });
842
+ }
843
+ throw usage(`Unknown users command: ${command}`);
844
+ }
845
+
846
+ async function handleOrganization(client, command, positionals, parsed, io) {
847
+ if (command === "me" || !command) return requestAndPrint(client, "GET", "/api/v1/organizations/me", parsed, io);
848
+ if (command === "usage") return requestAndPrint(client, "GET", "/api/v1/organizations/me/usage", parsed, io);
849
+ if (command === "update") {
850
+ const id = requirePositional(positionals, 0, "organization id");
851
+ return requestAndPrint(client, "PUT", `/api/v1/organizations/${encodeURIComponent(id)}/details`, parsed, io, { body: await readData(parsed.flags, io) });
852
+ }
853
+ if (command === "invite") {
854
+ const id = requirePositional(positionals, 0, "organization id");
855
+ return requestAndPrint(client, "POST", `/api/v1/organizations/${encodeURIComponent(id)}/invite_member`, parsed, io, { body: await readData(parsed.flags, io) });
856
+ }
857
+ if (command === "deployment") {
858
+ const id = requirePositional(positionals, 0, "organization id");
859
+ return requestAndPrint(client, "GET", `/api/v1/organizations/${encodeURIComponent(id)}/deployment`, parsed, io);
860
+ }
861
+ if (command === "deploy") {
862
+ const id = requirePositional(positionals, 0, "organization id");
863
+ return requestAndPrint(client, "POST", `/api/v1/organizations/${encodeURIComponent(id)}/deployment`, parsed, io, { body: await readData(parsed.flags, io) });
864
+ }
865
+ if (command === "delete-deployment") {
866
+ const id = requirePositional(positionals, 0, "organization id");
867
+ return requestAndPrint(client, "DELETE", `/api/v1/organizations/${encodeURIComponent(id)}/deployment`, parsed, io);
868
+ }
869
+ throw usage(`Unknown org command: ${command}`);
870
+ }
871
+
872
+ async function handleRoles(client, command, positionals, parsed, io) {
873
+ if (command === "list" || !command) return requestAndPrint(client, "GET", "/api/v1/roles/", parsed, io);
874
+ if (command === "create") return requestAndPrint(client, "POST", "/api/v1/roles/", parsed, io, { body: await readData(parsed.flags, io) });
875
+ if (command === "get") {
876
+ const id = requirePositional(positionals, 0, "role id");
877
+ return requestAndPrint(client, "GET", `/api/v1/roles/${encodeURIComponent(id)}`, parsed, io);
878
+ }
879
+ if (command === "assign") {
880
+ const roleId = requirePositional(positionals, 0, "role id");
881
+ const userId = firstValue(parsed.flags.user) || requirePositional(positionals, 1, "user id");
882
+ return requestAndPrint(client, "POST", `/api/v1/roles/${encodeURIComponent(roleId)}/users/${encodeURIComponent(userId)}`, parsed, io);
883
+ }
884
+ if (command === "unassign") {
885
+ const roleId = requirePositional(positionals, 0, "role id");
886
+ const userId = firstValue(parsed.flags.user) || requirePositional(positionals, 1, "user id");
887
+ return requestAndPrint(client, "DELETE", `/api/v1/roles/${encodeURIComponent(roleId)}/users/${encodeURIComponent(userId)}`, parsed, io);
888
+ }
889
+ if (command === "sync-clerk") return requestAndPrint(client, "POST", "/api/v1/roles/sync_clerk_role", parsed, io, { body: await readData(parsed.flags, io) });
890
+ throw usage(`Unknown roles command: ${command}`);
891
+ }
892
+
893
+ async function handleBilling(client, command, positionals, parsed, io) {
894
+ const billingPaths = {
895
+ status: ["GET", "/api/v1/billing/status"],
896
+ plans: ["GET", "/api/v1/billing/plans"],
897
+ products: ["GET", "/api/v1/billing/billing-products"],
898
+ history: ["GET", "/api/v1/billing/history"],
899
+ "financial-history": ["GET", "/api/v1/billing/financial-history"],
900
+ "usage-trends": ["GET", "/api/v1/billing/usage/trends"],
901
+ sync: ["POST", "/api/v1/billing/sync"],
902
+ checkout: ["POST", "/api/v1/billing/checkout-session"],
903
+ portal: ["POST", "/api/v1/billing/customer-portal-session"],
904
+ };
905
+ if (command === "prices") {
906
+ const planId = requirePositional(positionals, 0, "plan id");
907
+ return requestAndPrint(client, "GET", `/api/v1/billing/plans/${encodeURIComponent(planId)}/prices`, parsed, io);
908
+ }
909
+ const entry = billingPaths[command || "status"];
910
+ if (entry) {
911
+ const [method, pathName] = entry;
912
+ const body = method === "GET" ? undefined : await readData(parsed.flags, io, {});
913
+ return requestAndPrint(client, method, pathName, parsed, io, {
914
+ query: {
915
+ limit: firstValue(parsed.flags.limit),
916
+ offset: firstValue(parsed.flags.offset),
917
+ days: firstValue(parsed.flags.days),
918
+ },
919
+ body,
920
+ });
921
+ }
922
+ throw usage(`Unknown billing command: ${command}`);
923
+ }
924
+
925
+ async function handleStats(client, command, parsed, io) {
926
+ if (command === "answers" || !command) return requestAndPrint(client, "GET", "/api/v1/answer_stats/", parsed, io);
927
+ if (command === "connections") return requestAndPrint(client, "GET", "/api/v1/connection_stats/", parsed, io);
928
+ throw usage(`Unknown stats command: ${command}`);
929
+ }
930
+
931
+ function queryPayload(flags, sql) {
932
+ return {
933
+ query: sql,
934
+ params: parseJsonFlag(firstValue(flags.params), "params") ?? null,
935
+ row_limit: parseInteger(firstValue(flags.rowLimit), 1000),
936
+ timeout: parseInteger(firstValue(flags.timeout), 30),
937
+ };
938
+ }
939
+
940
+ async function semanticPayload(resource, flags, positionals, io) {
941
+ const common = {
942
+ name: firstValue(flags.name) || positionals.join(" ") || undefined,
943
+ description: firstValue(flags.description),
944
+ entity: firstValue(flags.entity),
945
+ source_table: firstValue(flags.sourceTable),
946
+ identifier: firstValue(flags.identifier),
947
+ temporal_key: firstValue(flags.temporalKey),
948
+ expression: firstValue(flags.expression),
949
+ type: firstValue(flags.type),
950
+ sql: firstValue(flags.sql),
951
+ filters: parseJsonFlag(firstValue(flags.filters), "filters"),
952
+ };
953
+
954
+ if (resource === "relationships") {
955
+ Object.assign(common, {
956
+ from_entity: firstValue(flags.from),
957
+ to_entity: firstValue(flags.to),
958
+ relationship_type: firstValue(flags.relationshipType),
959
+ join_condition: firstValue(flags.join),
960
+ });
961
+ }
962
+
963
+ return readData(flags, io, common);
964
+ }
965
+
966
+ async function readSql(flags, positionals, io) {
967
+ const sql = firstValue(flags.sql);
968
+ const file = firstValue(flags.file);
969
+
970
+ if (sql) return sql;
971
+ if (file) return fs.readFileSync(file, "utf8");
972
+ if (positionals.length > 0) return positionals.join(" ");
973
+ if (!io.stdin.isTTY) return await readAll(io.stdin);
974
+ throw usage("SQL is required. Pass --sql, --file, a positional SQL string, or stdin.");
975
+ }
976
+
977
+ async function optionalSql(flags, positionals, io) {
978
+ if (firstValue(flags.sql) || firstValue(flags.file) || positionals.length > 0) {
979
+ return readSql(flags, positionals, io);
980
+ }
981
+ return undefined;
982
+ }
983
+
984
+ async function readData(flags, io, defaults = {}) {
985
+ const file = firstValue(flags.dataFile);
986
+ const inline = firstValue(flags.data);
987
+ let data = {};
988
+
989
+ if (file) {
990
+ data = parseJsonFlag(fs.readFileSync(file, "utf8"), "data-file");
991
+ } else if (inline) {
992
+ data = parseJsonFlag(inline, "data");
993
+ } else if (!io.stdin.isTTY) {
994
+ const text = await readAll(io.stdin);
995
+ if (text.trim()) data = parseJsonFlag(text, "stdin");
996
+ }
997
+
998
+ return dropUndefined({ ...defaults, ...data });
999
+ }
1000
+
1001
+ function multipart({ file, fields = {} }) {
1002
+ const form = new FormData();
1003
+ for (const [key, value] of Object.entries(dropUndefined(fields))) {
1004
+ form.append(key, String(value));
1005
+ }
1006
+ const buffer = fs.readFileSync(file);
1007
+ form.append("file", new Blob([buffer]), path.basename(file));
1008
+ return form;
1009
+ }
1010
+
1011
+ function positionPayload(flags) {
1012
+ const payload = {
1013
+ x: parseInteger(firstValue(flags.x), undefined),
1014
+ y: parseInteger(firstValue(flags.y), undefined),
1015
+ w: parseInteger(firstValue(flags.w), undefined),
1016
+ h: parseInteger(firstValue(flags.h), undefined),
1017
+ };
1018
+ return dropUndefined(payload);
1019
+ }
1020
+
1021
+ function paginationPayload(flags) {
1022
+ const payload = {
1023
+ limit: parseInteger(firstValue(flags.limit), undefined),
1024
+ cursor: firstValue(flags.cursor),
1025
+ };
1026
+ const clean = dropUndefined(payload);
1027
+ return Object.keys(clean).length > 0 ? clean : undefined;
1028
+ }
1029
+
1030
+ async function requestAndPrint(client, method, pathName, parsed, io, options = {}) {
1031
+ const result = await client.rawRequest(method, pathName, {
1032
+ auth: options.auth ?? true,
1033
+ query: options.query,
1034
+ body: options.body,
1035
+ headers: options.headers,
1036
+ });
1037
+
1038
+ const output = firstValue(parsed.flags.output);
1039
+ if (output) {
1040
+ fs.writeFileSync(output, result.buffer);
1041
+ write(io.stdout, `Wrote ${result.buffer.length} bytes to ${output}\n`);
1042
+ return;
1043
+ }
1044
+
1045
+ if (parsed.flags.include) {
1046
+ write(io.stdout, `HTTP ${result.status}\n`);
1047
+ for (const [key, value] of Object.entries(result.headers)) write(io.stdout, `${key}: ${value}\n`);
1048
+ write(io.stdout, "\n");
1049
+ }
1050
+
1051
+ if (parsed.flags.raw || options.rawDefault) {
1052
+ io.stdout.write(result.buffer);
1053
+ if (result.buffer.length > 0 && result.buffer[result.buffer.length - 1] !== 10) write(io.stdout, "\n");
1054
+ return;
1055
+ }
1056
+
1057
+ if (result.data === null) {
1058
+ write(io.stdout, parsed.flags.json ? "null\n" : `${options.okText || "ok"}\n`);
1059
+ return;
1060
+ }
1061
+
1062
+ if (!parsed.flags.json && options.table) {
1063
+ const rows = options.tableDataKey ? result.data[options.tableDataKey] : result.data;
1064
+ if (Array.isArray(rows)) {
1065
+ write(io.stdout, formatList(rows, options.table));
1066
+ return;
1067
+ }
1068
+ }
1069
+
1070
+ if (typeof result.data === "object" || parsed.flags.json) {
1071
+ write(io.stdout, formatJson(result.data));
1072
+ return;
1073
+ }
1074
+
1075
+ write(io.stdout, result.text.endsWith("\n") ? result.text : `${result.text}\n`);
1076
+ }
1077
+
1078
+ function parseArgs(argv) {
1079
+ const flags = {};
1080
+ const positionals = [];
1081
+
1082
+ for (let index = 0; index < argv.length; index += 1) {
1083
+ const token = argv[index];
1084
+ if (token === "--") {
1085
+ positionals.push(...argv.slice(index + 1));
1086
+ break;
1087
+ }
1088
+
1089
+ if (!token.startsWith("-") || token === "-") {
1090
+ positionals.push(token);
1091
+ continue;
1092
+ }
1093
+
1094
+ const equalsIndex = token.indexOf("=");
1095
+ const rawName = equalsIndex === -1 ? token : token.slice(0, equalsIndex);
1096
+ const inlineValue = equalsIndex === -1 ? undefined : token.slice(equalsIndex + 1);
1097
+ const name = normalizeFlagName(rawName);
1098
+ const next = argv[index + 1];
1099
+
1100
+ if (isBooleanFlag(rawName)) {
1101
+ setFlag(flags, name, true);
1102
+ continue;
1103
+ }
1104
+
1105
+ if (inlineValue !== undefined) {
1106
+ setFlag(flags, name, inlineValue);
1107
+ continue;
1108
+ }
1109
+
1110
+ if (next === undefined || next.startsWith("-")) {
1111
+ throw usage(`Missing value for ${rawName}`);
1112
+ }
1113
+
1114
+ setFlag(flags, name, next);
1115
+ index += 1;
1116
+ }
1117
+
1118
+ if (flags.help) positionals.unshift("help");
1119
+ return { flags, positionals };
1120
+ }
1121
+
1122
+ function normalizeFlagName(rawName) {
1123
+ const aliases = {
1124
+ "-h": "help",
1125
+ "--help": "help",
1126
+ "--base-url": "baseUrl",
1127
+ "--api-key": "apiKey",
1128
+ "--json": "json",
1129
+ "--include": "include",
1130
+ "-i": "include",
1131
+ "--output": "output",
1132
+ "-o": "output",
1133
+ "--raw": "raw",
1134
+ "--data": "data",
1135
+ "--data-file": "dataFile",
1136
+ "--body": "data",
1137
+ "--body-file": "dataFile",
1138
+ "--name": "name",
1139
+ "--title": "title",
1140
+ "--description": "description",
1141
+ "--visibility": "visibility",
1142
+ "--connection": "connection",
1143
+ "--type": "type",
1144
+ "--db-type": "dbType",
1145
+ "--config": "config",
1146
+ "--file": "file",
1147
+ "-f": "file",
1148
+ "--sql": "sql",
1149
+ "-q": "sql",
1150
+ "--params": "params",
1151
+ "--row-limit": "rowLimit",
1152
+ "--timeout": "timeout",
1153
+ "--format": "format",
1154
+ "--scope": "scope",
1155
+ "--admin": "admin",
1156
+ "--expires-at": "expiresAt",
1157
+ "--include-pii": "includePii",
1158
+ "--source-table": "sourceTable",
1159
+ "--identifier": "identifier",
1160
+ "--temporal-key": "temporalKey",
1161
+ "--entity": "entity",
1162
+ "--expression": "expression",
1163
+ "--source-type": "sourceType",
1164
+ "--source": "source",
1165
+ "--visualization": "visualization",
1166
+ "--dashboard": "dashboard",
1167
+ "--tile": "tile",
1168
+ "--user": "user",
1169
+ "--email": "email",
1170
+ "--filters": "filters",
1171
+ "--result-handle": "resultHandle",
1172
+ "--cursor": "cursor",
1173
+ "--limit": "limit",
1174
+ "--offset": "offset",
1175
+ "--days": "days",
1176
+ "--x": "x",
1177
+ "--y": "y",
1178
+ "--w": "w",
1179
+ "--h": "h",
1180
+ "--prompt": "prompt",
1181
+ "--model": "model",
1182
+ "--options": "options",
1183
+ "--status": "status",
1184
+ "--summary": "summary",
1185
+ "--session": "session",
1186
+ "--question": "question",
1187
+ "--turn": "turn",
1188
+ "--from": "from",
1189
+ "--to": "to",
1190
+ "--relationship-type": "relationshipType",
1191
+ "--join": "join",
1192
+ "--form": "form",
1193
+ };
1194
+
1195
+ return aliases[rawName] || rawName.replace(/^-+/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1196
+ }
1197
+
1198
+ function isBooleanFlag(rawName) {
1199
+ return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin"].includes(rawName);
1200
+ }
1201
+
1202
+ function setFlag(flags, name, value) {
1203
+ if (flags[name] === undefined) flags[name] = value;
1204
+ else if (Array.isArray(flags[name])) flags[name].push(value);
1205
+ else flags[name] = [flags[name], value];
1206
+ }
1207
+
1208
+ function parseJsonFlag(value, name) {
1209
+ if (value === undefined || value === null || value === "") return undefined;
1210
+ try {
1211
+ return JSON.parse(value);
1212
+ } catch (error) {
1213
+ throw usage(`Invalid JSON for --${name}: ${error.message}`);
1214
+ }
1215
+ }
1216
+
1217
+ function parseInteger(value, fallback) {
1218
+ if (value === undefined || value === null || value === "") return fallback;
1219
+ const parsed = Number.parseInt(value, 10);
1220
+ if (!Number.isFinite(parsed)) throw usage(`Expected an integer, received ${value}`);
1221
+ return parsed;
1222
+ }
1223
+
1224
+ function requirePositional(positionals, index, label) {
1225
+ const value = positionals[index];
1226
+ if (!value) throw usage(`Missing ${label}`);
1227
+ return value;
1228
+ }
1229
+
1230
+ function requireConnection(connectionId, label) {
1231
+ if (!connectionId) throw usage(`${label} requires --connection <id>`);
1232
+ }
1233
+
1234
+ function requirePayloadValue(payload, key, message) {
1235
+ if (!payload[key]) throw usage(message);
1236
+ }
1237
+
1238
+ function csvOrRepeated(value) {
1239
+ const values = allValues(value);
1240
+ return values.flatMap((item) => String(item).split(",").map((part) => part.trim()).filter(Boolean));
1241
+ }
1242
+
1243
+ function firstValue(value) {
1244
+ return Array.isArray(value) ? value[0] : value;
1245
+ }
1246
+
1247
+ function allValues(value) {
1248
+ if (value === undefined) return [];
1249
+ return Array.isArray(value) ? value : [value];
1250
+ }
1251
+
1252
+ function dropUndefined(object) {
1253
+ return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
1254
+ }
1255
+
1256
+ function parsePair(value, flagName) {
1257
+ const index = value.indexOf("=");
1258
+ if (index === -1) throw usage(`Expected ${flagName} key=value`);
1259
+ const key = value.slice(0, index);
1260
+ const item = value.slice(index + 1);
1261
+ if (!key) throw usage(`Expected ${flagName} key=value`);
1262
+ return [key, item];
1263
+ }
1264
+
1265
+ async function readAll(stream) {
1266
+ const chunks = [];
1267
+ for await (const chunk of stream) chunks.push(Buffer.from(chunk));
1268
+ return Buffer.concat(chunks).toString("utf8");
1269
+ }
1270
+
1271
+ function write(stream, text) {
1272
+ stream.write(text);
1273
+ }
1274
+
1275
+ function usage(message) {
1276
+ const error = new Error(`${message}\n\n${helpText()}`);
1277
+ error.exitCode = 2;
1278
+ return error;
1279
+ }
1280
+
1281
+ function helpText() {
1282
+ return `AnswerLayer CLI
1283
+
1284
+ Usage:
1285
+ answerlayer configure --base-url <url> --api-key <key>
1286
+ answerlayer health
1287
+ answerlayer openapi --output openapi.json
1288
+
1289
+ Core:
1290
+ answerlayer api-keys list|create|revoke
1291
+ answerlayer connections supported|list|get|create|update|delete|schema|test
1292
+ answerlayer metadata structure|tables|columns|pii-summary|pii-settings|detect-pii
1293
+ answerlayer query run|validate|export <connection-id> --sql <sql>
1294
+ answerlayer query-results get|delete <handle>
1295
+
1296
+ Data products:
1297
+ answerlayer saved-queries list|get|create|update|delete|approve|unapprove|execute
1298
+ answerlayer semantic <entities|relationships|measures|metrics|dimensions|filters> list|get|create|update|delete|delete-all|generate
1299
+ answerlayer inquiry ask|sessions|create-session|session|update-session|delete-session|turn
1300
+ answerlayer generation start|list|get|status|stream|cancel|questions|guidance|delete
1301
+ answerlayer tiles list|get|create|update|data|delete
1302
+ answerlayer dashboards list|get|create|update|delete|duplicate|manifest|attach-tile|move-tile|detach-tile|assignments|assign|unassign|tile-data
1303
+
1304
+ Admin and supporting resources:
1305
+ answerlayer documents upload|list|get|update|delete|link|unlink|connections|for-connection
1306
+ answerlayer branding get|update|upload|extract|asset
1307
+ answerlayer uploads csv|duckdb upload|status|reprocess
1308
+ answerlayer chains list|answers
1309
+ answerlayer users me|update-me|list|get|update
1310
+ answerlayer org me|usage|update|invite|deployment|deploy|delete-deployment
1311
+ answerlayer roles list|create|get|assign|unassign|sync-clerk
1312
+ answerlayer billing status|plans|products|prices|checkout|portal|history|usage-trends
1313
+ answerlayer stats answers|connections
1314
+
1315
+ Common options:
1316
+ --base-url <url> Env: ANSWERLAYER_BASE_URL
1317
+ --api-key <key> Env: ANSWERLAYER_API_KEY
1318
+ --json Print JSON instead of table output when available.
1319
+ --data <json> Structured request payload.
1320
+ --data-file <path> Structured request payload file.
1321
+ --output, -o <path> Write response bytes to a file.
1322
+
1323
+ SQL options:
1324
+ --sql, -q <sql> SQL text.
1325
+ --file, -f <path> Read SQL from a file, or upload a file for upload commands.
1326
+ --params <json> Query parameters as JSON.
1327
+ --row-limit <n> Row limit. Default: 1000.
1328
+ --timeout <sec> Timeout in seconds. Default: 30.
1329
+ `;
1330
+ }