@answerlayer/cli 0.1.10 → 0.1.11

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/README.md CHANGED
@@ -148,6 +148,33 @@ demo command reuses the same connection and semantic resources rather than
148
148
  duplicating them. `local reset --force` explicitly removes both application and
149
149
  demo data because they share the selected runtime's isolated Postgres volume.
150
150
 
151
+ Configure Anthropic privately from your own terminal when you are ready to use
152
+ model-backed features:
153
+
154
+ ```bash
155
+ answerlayer local provider set anthropic
156
+ answerlayer local provider status --json
157
+ ```
158
+
159
+ The interactive command disables terminal echo while you enter the key. It
160
+ stores the credential only in the selected runtime's mode-0600 environment,
161
+ recreates the application container without touching Postgres, and verifies the
162
+ key with Anthropic's model-list API from inside that container. The key is never
163
+ accepted as a command argument or returned by status output.
164
+
165
+ For non-interactive automation, place the key in a mode-0600 file and pass only
166
+ its path:
167
+
168
+ ```bash
169
+ answerlayer local provider set anthropic --from-file /secure/path/anthropic.key
170
+ # Or set ANSWERLAYER_PROVIDER_KEY_FILE to that path.
171
+ ```
172
+
173
+ Use `local provider rotate anthropic` to replace a working key. If validation
174
+ fails, the previous credential is restored. Use
175
+ `local provider remove anthropic --force` to disable model-backed features while
176
+ preserving all application and demo data.
177
+
151
178
  Inspect and manage the lifecycle with:
152
179
 
153
180
  ```bash
@@ -184,6 +211,7 @@ answerlayer openapi --output openapi.json
184
211
  answerlayer local init
185
212
  answerlayer local start
186
213
  answerlayer local demo --json
214
+ answerlayer local provider status --json
187
215
  answerlayer local status
188
216
  answerlayer local logs
189
217
  answerlayer local stop
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@answerlayer/cli",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -71,13 +71,32 @@ already available in the Codex skills directory.
71
71
  answerlayer saved-queries execute <saved-query-id> --format table
72
72
  ```
73
73
 
74
- 5. Before connecting real data, require a dedicated database account that is
74
+ 5. When the user wants natural-language inquiry, hand provider setup back to
75
+ them. Ask them to run this command privately in their own terminal:
76
+
77
+ ```bash
78
+ answerlayer local provider set anthropic
79
+ ```
80
+
81
+ Do not ask the user to paste a provider key into chat and do not pass a key
82
+ in command arguments. The CLI disables terminal echo, stores the credential
83
+ in the selected runtime's permission-restricted environment, recreates only
84
+ the application container, and verifies the provider. For automation, the
85
+ user may place the key in a mode-0600 file and pass its path with
86
+ `--from-file`; do not read or print that file. After the user confirms the
87
+ command completed, inspect only secret-free status:
88
+
89
+ ```bash
90
+ answerlayer local provider status --json
91
+ ```
92
+
93
+ 6. Before connecting real data, require a dedicated database account that is
75
94
  restricted to approved schemas and `SELECT` only. Show the proposed
76
95
  connection host, database, and username, then get confirmation before
77
96
  running `connections create` or any query. Put the password only in a local,
78
97
  permission-restricted JSON file; never print it or commit it.
79
98
 
80
- 6. Start with a small approved schema and read-only inspection. Confirm before
99
+ 7. Start with a small approved schema and read-only inspection. Confirm before
81
100
  creating connections, generating semantic objects, or executing queries.
82
101
 
83
102
  This workflow is for Docker Compose development only. Do not run
package/src/cli.js CHANGED
@@ -1439,6 +1439,7 @@ function normalizeFlagName(rawName) {
1439
1439
  "--use-semantic-layer": "useSemanticLayer",
1440
1440
  "--no-semantic-layer": "noSemanticLayer",
1441
1441
  "--no-demo": "noDemo",
1442
+ "--from-file": "fromFile",
1442
1443
  "--options": "options",
1443
1444
  "--status": "status",
1444
1445
  "--summary": "summary",
@@ -1618,6 +1619,9 @@ Usage:
1618
1619
  answerlayer local start [--no-demo]
1619
1620
  answerlayer local status|logs|stop
1620
1621
  answerlayer local demo [--json]
1622
+ answerlayer local provider set|rotate anthropic [--from-file <mode-0600-path>]
1623
+ answerlayer local provider status|verify [anthropic] [--json]
1624
+ answerlayer local provider remove anthropic --force
1621
1625
  answerlayer local upgrade [--image <image>]
1622
1626
  answerlayer local reset --force
1623
1627
  answerlayer init --api-key <key> [--base-url <url>]
package/src/local.js CHANGED
@@ -10,6 +10,7 @@ import { defaultConfigPath, readConfig, writeConfig } from "./config.js";
10
10
  export const DEFAULT_LOCAL_IMAGE = "public.ecr.aws/s8d9x7y7/answerlayer:1.19.9";
11
11
  const DEFAULT_PORT = 8000;
12
12
  const MINIMUM_FREE_BYTES = 2 * 1024 * 1024 * 1024;
13
+ const PROVIDER_VALIDATION_TIMEOUT_MS = 15_000;
13
14
  const LOCAL_DEMO_VERSION = "retail-v1";
14
15
  const LOCAL_DEMO_CONNECTION_NAME = "AnswerLayer Demo";
15
16
  const LOCAL_DEMO_SAVED_QUERY_NAME = "Monthly revenue by region";
@@ -20,6 +21,12 @@ const LOCAL_DEMO_QUESTIONS = [
20
21
  "Which region generated the most completed revenue?",
21
22
  "How did completed revenue change from January to March?",
22
23
  ];
24
+ const LOCAL_PROVIDERS = {
25
+ anthropic: {
26
+ label: "Anthropic",
27
+ environmentName: "ANSWERLAYER_ANTHROPIC_API_KEY",
28
+ },
29
+ };
23
30
 
24
31
  export async function handleLocal(command, parsed, io) {
25
32
  if (command === "init") return localInit(parsed, io);
@@ -28,9 +35,10 @@ export async function handleLocal(command, parsed, io) {
28
35
  if (command === "logs") return localLogs(parsed, io);
29
36
  if (command === "stop") return localStop(parsed, io);
30
37
  if (command === "demo") return localDemo(parsed, io);
38
+ if (command === "provider") return localProvider(parsed, io);
31
39
  if (command === "upgrade") return localUpgrade(parsed, io);
32
40
  if (command === "reset") return localReset(parsed, io);
33
- throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|upgrade|reset`");
41
+ throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|provider|upgrade|reset`");
34
42
  }
35
43
 
36
44
  export async function localUp(parsed, io) {
@@ -110,6 +118,102 @@ async function localDemo(parsed, io) {
110
118
  printDemoSummary(demo, io);
111
119
  }
112
120
 
121
+ async function localProvider(parsed, io) {
122
+ const action = parsed.positionals[2];
123
+ if (!action || !["set", "rotate", "status", "verify", "remove"].includes(action)) {
124
+ throw new Error("Expected `answerlayer local provider set|rotate|status|verify|remove`");
125
+ }
126
+ const provider = resolveLocalProvider(parsed.positionals[3]);
127
+ if (action === "set" || action === "rotate") return localProviderSet(parsed, io, provider, action);
128
+ if (action === "status" || action === "verify") return localProviderStatus(parsed, io, provider, action);
129
+ return localProviderRemove(parsed, io, provider);
130
+ }
131
+
132
+ async function localProviderSet(parsed, io, provider, action) {
133
+ if (parsed.flags.apiKey) {
134
+ throw new Error("Provider secrets are not accepted in command arguments. Use the hidden prompt or --from-file <path>.");
135
+ }
136
+ const run = io.runCommand || runCommand;
137
+ const runtime = requireReadyRuntime(parsed, io, run);
138
+ const environment = readEnvironment(runtime.envPath);
139
+ const existingSecret = environment[provider.environmentName] || "";
140
+ if (action === "rotate" && !existingSecret) {
141
+ throw new Error(`${provider.label} is not configured. Use \`answerlayer local provider set ${provider.id}\` first.`);
142
+ }
143
+ const secret = await readProviderSecret(parsed, io, provider);
144
+
145
+ writeEnvironmentValue(runtime.envPath, provider.environmentName, secret);
146
+ try {
147
+ restartProviderRuntime(runtime, run);
148
+ } catch {
149
+ rollbackProviderCredential(runtime, run, provider, existingSecret, "updating");
150
+ throw new Error(`Could not restart AnswerLayer with the new ${provider.label} credential. The previous configuration was restored.`);
151
+ }
152
+
153
+ const verification = validateProvider(runtime, run, provider);
154
+ if (!verification.verified) {
155
+ rollbackProviderCredential(runtime, run, provider, existingSecret, "verifying");
156
+ throw new Error(`${provider.label} verification failed (${verification.errorCode}). The previous configuration was restored.`);
157
+ }
158
+
159
+ const result = providerResult(provider, true, "ready", verification);
160
+ if (parsed.flags.json) {
161
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
162
+ return;
163
+ }
164
+ write(io.stdout, `${provider.label} credential ${action === "rotate" || existingSecret ? "rotated" : "configured"} and verified.\n`);
165
+ write(io.stdout, "The AnswerLayer application was recreated; local database data was preserved.\n");
166
+ }
167
+
168
+ async function localProviderStatus(parsed, io, provider, action) {
169
+ const run = io.runCommand || runCommand;
170
+ const runtime = loadRuntime(parsed, io);
171
+ requireCommand(run, "docker", ["compose", "version"]);
172
+ const runtimeStatus = inspectStatus(runtime, run, { tolerateFailure: true }).status;
173
+ const configured = Boolean(readEnvironment(runtime.envPath)[provider.environmentName]);
174
+ const verification = configured && runtimeStatus === "ready"
175
+ ? validateProvider(runtime, run, provider)
176
+ : { verified: false, errorCode: configured ? "runtime-not-ready" : "not-configured" };
177
+ const result = providerResult(provider, configured, runtimeStatus, verification);
178
+
179
+ if (action === "verify" && result.status !== "verified") {
180
+ throw new Error(`${provider.label} is ${result.status}. Run \`answerlayer local provider set ${provider.id}\` to configure and verify it.`);
181
+ }
182
+ if (parsed.flags.json) {
183
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
184
+ return;
185
+ }
186
+ write(io.stdout, `Provider: ${provider.id}\n`);
187
+ write(io.stdout, `Status: ${result.status}\n`);
188
+ write(io.stdout, `Runtime: ${runtimeStatus}\n`);
189
+ if (result.errorCode && result.status === "verification-failed") {
190
+ write(io.stdout, `Verification error: ${result.errorCode}\n`);
191
+ }
192
+ }
193
+
194
+ async function localProviderRemove(parsed, io, provider) {
195
+ if (!parsed.flags.force) {
196
+ throw new Error(`Removing ${provider.label} disables model-backed features. Rerun with \`answerlayer local provider remove ${provider.id} --force\` to confirm.`);
197
+ }
198
+ const run = io.runCommand || runCommand;
199
+ const runtime = requireReadyRuntime(parsed, io, run);
200
+ const existingSecret = readEnvironment(runtime.envPath)[provider.environmentName] || "";
201
+ writeEnvironmentValue(runtime.envPath, provider.environmentName, "");
202
+ try {
203
+ restartProviderRuntime(runtime, run);
204
+ } catch {
205
+ rollbackProviderCredential(runtime, run, provider, existingSecret, "removing");
206
+ throw new Error(`Could not remove ${provider.label}. The previous configuration was restored.`);
207
+ }
208
+ const result = providerResult(provider, false, "ready", { verified: false, errorCode: "not-configured" });
209
+ if (parsed.flags.json) {
210
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
211
+ return;
212
+ }
213
+ write(io.stdout, `${provider.label} credential removed. Model-backed features are disabled.\n`);
214
+ write(io.stdout, "The AnswerLayer application was recreated; local database data was preserved.\n");
215
+ }
216
+
113
217
  async function localUpgrade(parsed, io) {
114
218
  const image = firstValue(parsed.flags.image) || io.env.ANSWERLAYER_LOCAL_IMAGE || DEFAULT_LOCAL_IMAGE;
115
219
  write(io.stdout, `Upgrading the local runtime to ${image}...\n`);
@@ -128,6 +232,7 @@ async function localStatus(parsed, io) {
128
232
  resolvedImage: runtime.state.resolvedImage,
129
233
  runtimeDirectory: runtime.directory,
130
234
  demo: runtime.state.demo || { status: "not-installed", version: LOCAL_DEMO_VERSION },
235
+ providers: localProviderConfiguration(runtime),
131
236
  services: status.services,
132
237
  };
133
238
 
@@ -140,6 +245,7 @@ async function localStatus(parsed, io) {
140
245
  write(io.stdout, `Image: ${result.resolvedImage}\n`);
141
246
  write(io.stdout, `Runtime config: ${result.runtimeDirectory}\n`);
142
247
  write(io.stdout, `Demo: ${result.demo.status} (${result.demo.version})\n`);
248
+ write(io.stdout, `Model provider: ${result.providers.anthropic.configured ? "anthropic (configured)" : "not configured"}\n`);
143
249
  }
144
250
 
145
251
  async function localLogs(parsed, io) {
@@ -423,6 +529,14 @@ function writeEnvironment(envPath, state) {
423
529
  fs.chmodSync(envPath, 0o600);
424
530
  }
425
531
 
532
+ function writeEnvironmentValue(envPath, name, value) {
533
+ const values = readEnvironment(envPath);
534
+ values[name] = value;
535
+ const contents = Object.entries(values).map(([entryName, entryValue]) => `${entryName}=${entryValue}`).join("\n");
536
+ fs.writeFileSync(envPath, `${contents}\n`, { encoding: "utf8", mode: 0o600 });
537
+ fs.chmodSync(envPath, 0o600);
538
+ }
539
+
426
540
  function readEnvironment(envPath) {
427
541
  if (!fs.existsSync(envPath)) return {};
428
542
  return Object.fromEntries(
@@ -433,6 +547,175 @@ function readEnvironment(envPath) {
433
547
  );
434
548
  }
435
549
 
550
+ function localProviderConfiguration(runtime) {
551
+ const environment = readEnvironment(runtime.envPath);
552
+ return Object.fromEntries(Object.entries(LOCAL_PROVIDERS).map(([id, provider]) => [
553
+ id,
554
+ { configured: Boolean(environment[provider.environmentName]) },
555
+ ]));
556
+ }
557
+
558
+ function resolveLocalProvider(value) {
559
+ const id = String(value || "anthropic").toLowerCase();
560
+ const provider = LOCAL_PROVIDERS[id];
561
+ if (!provider) {
562
+ throw new Error(`Unsupported local model provider ${value}. Supported providers: ${Object.keys(LOCAL_PROVIDERS).join(", ")}`);
563
+ }
564
+ return { id, ...provider };
565
+ }
566
+
567
+ function requireReadyRuntime(parsed, io, run) {
568
+ const runtime = loadRuntime(parsed, io);
569
+ requireCommand(run, "docker", ["compose", "version"]);
570
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
571
+ if (status.status !== "ready") {
572
+ throw new Error("Local AnswerLayer must be ready before changing a model provider. Run `answerlayer local start` first.");
573
+ }
574
+ return runtime;
575
+ }
576
+
577
+ async function readProviderSecret(parsed, io, provider) {
578
+ const filePath = firstValue(parsed.flags.fromFile) || io.env.ANSWERLAYER_PROVIDER_KEY_FILE;
579
+ let secret;
580
+ if (filePath) {
581
+ const resolvedPath = path.resolve(filePath);
582
+ let stats;
583
+ try {
584
+ stats = fs.statSync(resolvedPath);
585
+ } catch {
586
+ throw new Error(`Could not read the provider credential file at ${resolvedPath}`);
587
+ }
588
+ if (!stats.isFile()) throw new Error(`Provider credential path is not a file: ${resolvedPath}`);
589
+ if ((io.platform || process.platform) !== "win32" && (stats.mode & 0o077) !== 0) {
590
+ throw new Error(`Provider credential file permissions are too broad. Run \`chmod 600 ${resolvedPath}\` and retry.`);
591
+ }
592
+ secret = fs.readFileSync(resolvedPath, "utf8").trim();
593
+ } else if (io.readSecret) {
594
+ secret = await io.readSecret(`${provider.label} API key: `);
595
+ } else {
596
+ secret = await readHiddenInput(io.stdin, io.stderr, `${provider.label} API key: `);
597
+ }
598
+
599
+ if (typeof secret !== "string" || secret.length < 12 || /\s/.test(secret)) {
600
+ throw new Error(`${provider.label} credential is empty or invalid. Use a single-line API key.`);
601
+ }
602
+ return secret;
603
+ }
604
+
605
+ function readHiddenInput(input, output, prompt) {
606
+ if (!input?.isTTY || typeof input.setRawMode !== "function") {
607
+ throw new Error("A terminal is required for hidden credential entry. Run this command in your own terminal or use --from-file <mode-0600-path>.");
608
+ }
609
+ write(output, prompt);
610
+ return new Promise((resolve, reject) => {
611
+ const wasRaw = Boolean(input.isRaw);
612
+ const wasPaused = typeof input.isPaused === "function" ? input.isPaused() : false;
613
+ let secret = "";
614
+ let settled = false;
615
+ const cleanup = () => {
616
+ input.off("data", onData);
617
+ input.off("end", onEnd);
618
+ input.off("close", onClose);
619
+ input.off("error", onError);
620
+ input.setRawMode(wasRaw);
621
+ if (wasPaused && typeof input.pause === "function") input.pause();
622
+ write(output, "\n");
623
+ };
624
+ const finish = (error) => {
625
+ if (settled) return;
626
+ settled = true;
627
+ cleanup();
628
+ if (error) reject(error);
629
+ else resolve(secret);
630
+ };
631
+ const onData = chunk => {
632
+ for (const character of String(chunk)) {
633
+ if (character === "\r" || character === "\n") return finish();
634
+ if (character === "\u0003") return finish(new Error("Provider credential entry cancelled"));
635
+ if (character === "\u007f" || character === "\b") {
636
+ secret = secret.slice(0, -1);
637
+ } else if (character >= " ") {
638
+ secret += character;
639
+ }
640
+ }
641
+ };
642
+ const onEnd = () => finish(new Error("Provider credential input ended before submission"));
643
+ const onClose = () => finish(new Error("Provider credential input closed before submission"));
644
+ const onError = () => finish(new Error("Provider credential input failed before submission"));
645
+ input.setRawMode(true);
646
+ input.on("data", onData);
647
+ input.once("end", onEnd);
648
+ input.once("close", onClose);
649
+ input.once("error", onError);
650
+ if (typeof input.resume === "function") input.resume();
651
+ });
652
+ }
653
+
654
+ function restartProviderRuntime(runtime, run) {
655
+ const result = run("docker", [
656
+ ...composeArgs(runtime),
657
+ "up", "--detach", "--no-deps", "--force-recreate", "--wait", "--wait-timeout", "180", "answerlayer",
658
+ ], { capture: true });
659
+ if (result.error || result.status !== 0) {
660
+ throw new Error("AnswerLayer application restart failed");
661
+ }
662
+ }
663
+
664
+ function rollbackProviderCredential(runtime, run, provider, existingSecret, action) {
665
+ writeEnvironmentValue(runtime.envPath, provider.environmentName, existingSecret);
666
+ try {
667
+ restartProviderRuntime(runtime, run);
668
+ } catch {
669
+ throw new Error(`Could not restart AnswerLayer while ${action} ${provider.label}. The previous credential remains in runtime.env; run \`answerlayer local start\` to recover.`);
670
+ }
671
+ }
672
+
673
+ function validateProvider(runtime, run, provider) {
674
+ const result = run("docker", [
675
+ ...composeArgs(runtime),
676
+ "exec", "-T", "answerlayer", "python", "-c", PROVIDER_VALIDATION_SCRIPT,
677
+ ], { capture: true, timeout: PROVIDER_VALIDATION_TIMEOUT_MS });
678
+ if (result.error?.code === "ETIMEDOUT") {
679
+ return { verified: false, errorCode: `${provider.id}-verification-timeout` };
680
+ }
681
+ const payload = parseProviderValidation(result.stdout);
682
+ if (!result.error && result.status === 0 && payload?.verified === true) {
683
+ return { verified: true };
684
+ }
685
+ return {
686
+ verified: false,
687
+ errorCode: /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/.test(payload?.error || "")
688
+ ? payload.error
689
+ : `${provider.id}-verification-failed`,
690
+ };
691
+ }
692
+
693
+ function parseProviderValidation(stdout) {
694
+ const line = String(stdout || "").trim().split(/\r?\n/).at(-1);
695
+ try {
696
+ return JSON.parse(line);
697
+ } catch {
698
+ return null;
699
+ }
700
+ }
701
+
702
+ function providerResult(provider, configured, runtimeStatus, verification) {
703
+ const status = !configured
704
+ ? "unconfigured"
705
+ : runtimeStatus !== "ready"
706
+ ? "configured-runtime-not-ready"
707
+ : verification.verified
708
+ ? "verified"
709
+ : "verification-failed";
710
+ return {
711
+ provider: provider.id,
712
+ configured,
713
+ status,
714
+ runtimeStatus,
715
+ ...(status === "verification-failed" ? { errorCode: verification.errorCode } : {}),
716
+ };
717
+ }
718
+
436
719
  function readState(statePath) {
437
720
  if (!fs.existsSync(statePath)) return null;
438
721
  try {
@@ -516,6 +799,7 @@ function runCommand(command, args, options = {}) {
516
799
  return spawnSync(command, args, {
517
800
  encoding: options.capture ? "utf8" : undefined,
518
801
  input: options.input,
802
+ timeout: options.timeout,
519
803
  stdio: options.capture
520
804
  ? [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
521
805
  : "inherit",
@@ -814,6 +1098,25 @@ GROUP BY 1, 2
814
1098
  ORDER BY 1, 2
815
1099
  `.trim();
816
1100
 
1101
+ const PROVIDER_VALIDATION_SCRIPT = `
1102
+ import json
1103
+ import os
1104
+
1105
+ from anthropic import Anthropic
1106
+
1107
+ try:
1108
+ Anthropic(
1109
+ api_key=os.environ["ANTHROPIC_API_KEY"],
1110
+ max_retries=0,
1111
+ timeout=10.0,
1112
+ ).models.list(limit=1)
1113
+ except Exception as error:
1114
+ print(json.dumps({"verified": False, "error": type(error).__name__}))
1115
+ raise SystemExit(1)
1116
+
1117
+ print(json.dumps({"verified": True}))
1118
+ `.trim();
1119
+
817
1120
  function firstValue(value) {
818
1121
  return Array.isArray(value) ? value[0] : value;
819
1122
  }