@answerlayer/cli 0.1.10 → 0.1.12

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
@@ -97,7 +97,37 @@ This installs to `~/.codex/skills/answerlayer` by default. Use `--path` for a
97
97
  different skill directory; an existing skill is never replaced unless you pass
98
98
  `--force`.
99
99
 
100
- Initialize and start the local runtime:
100
+ The recommended path is one command:
101
+
102
+ ```bash
103
+ answerlayer local quickstart
104
+ ```
105
+
106
+ Quickstart asks for confirmation before it changes local state, then initializes
107
+ and starts the supported public-image runtime, authenticates the CLI, installs
108
+ the deterministic demo, and verifies the provider-free demo query. If no model
109
+ provider is configured, it stops with a safe handoff:
110
+
111
+ ```bash
112
+ answerlayer local provider set anthropic
113
+ answerlayer local quickstart
114
+ ```
115
+
116
+ The provider command must be run privately in the user's own terminal. The
117
+ resumed quickstart verifies the provider and runs one real model-backed inquiry
118
+ against the demo. Successful inquiry details are retained in the local runtime
119
+ state, so repeating quickstart reuses the verified session instead of creating
120
+ duplicate demo resources or inquiry sessions.
121
+
122
+ For agent automation after the user has explicitly approved starting
123
+ containers, use `answerlayer local quickstart --yes --json`. Progress is written
124
+ to stderr; stdout is one stable, credential-free JSON object containing the CLI
125
+ version, image digest, runtime directory, demo and provider status, local URL,
126
+ inquiry result, and next actions. `--yes` must not be used to bypass user
127
+ approval.
128
+
129
+ The underlying lifecycle commands remain available when manual control is
130
+ needed:
101
131
 
102
132
  ```bash
103
133
  answerlayer local init
@@ -148,6 +178,33 @@ demo command reuses the same connection and semantic resources rather than
148
178
  duplicating them. `local reset --force` explicitly removes both application and
149
179
  demo data because they share the selected runtime's isolated Postgres volume.
150
180
 
181
+ Configure Anthropic privately from your own terminal when you are ready to use
182
+ model-backed features:
183
+
184
+ ```bash
185
+ answerlayer local provider set anthropic
186
+ answerlayer local provider status --json
187
+ ```
188
+
189
+ The interactive command disables terminal echo while you enter the key. It
190
+ stores the credential only in the selected runtime's mode-0600 environment,
191
+ recreates the application container without touching Postgres, and verifies the
192
+ key with Anthropic's model-list API from inside that container. The key is never
193
+ accepted as a command argument or returned by status output.
194
+
195
+ For non-interactive automation, place the key in a mode-0600 file and pass only
196
+ its path:
197
+
198
+ ```bash
199
+ answerlayer local provider set anthropic --from-file /secure/path/anthropic.key
200
+ # Or set ANSWERLAYER_PROVIDER_KEY_FILE to that path.
201
+ ```
202
+
203
+ Use `local provider rotate anthropic` to replace a working key. If validation
204
+ fails, the previous credential is restored. Use
205
+ `local provider remove anthropic --force` to disable model-backed features while
206
+ preserving all application and demo data.
207
+
151
208
  Inspect and manage the lifecycle with:
152
209
 
153
210
  ```bash
@@ -183,7 +240,9 @@ answerlayer health
183
240
  answerlayer openapi --output openapi.json
184
241
  answerlayer local init
185
242
  answerlayer local start
243
+ answerlayer local quickstart --yes --json
186
244
  answerlayer local demo --json
245
+ answerlayer local provider status --json
187
246
  answerlayer local status
188
247
  answerlayer local logs
189
248
  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.12",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -30,24 +30,16 @@ already available in the Codex skills directory.
30
30
  npm install -g @answerlayer/cli
31
31
  ```
32
32
 
33
- 2. After confirmation, initialize the repository-free local runtime:
33
+ 2. Explain that quickstart may pull an image, start Docker containers, create a
34
+ persistent local volume, and install synthetic demo data. Get explicit user
35
+ confirmation, then run:
34
36
 
35
37
  ```bash
36
- answerlayer local init
38
+ answerlayer local quickstart --yes --json
37
39
  ```
38
40
 
39
- This checks Docker, pulls the supported public AnswerLayer image, pins its
40
- immutable digest, and generates permission-restricted runtime configuration
41
- in the platform application-data directory. It does not require Git, a
42
- source checkout, registry credentials, or a model-provider key.
43
-
44
- 3. After confirmation, start and configure the stack:
45
-
46
- ```bash
47
- answerlayer local start
48
- ```
49
-
50
- This starts Postgres, runs migrations, waits for readiness, creates the local
41
+ Never pass `--yes` before the user approves. This checks Docker, pulls and
42
+ pins the supported public image, starts Postgres, runs migrations, creates the local
51
43
  identity and scoped key, verifies it, and configures the CLI. It also seeds a
52
44
  versioned synthetic retail demo in a separate database, registers a
53
45
  dedicated read-only connection, creates starter semantic resources and a
@@ -55,29 +47,37 @@ already available in the Codex skills directory.
55
47
  credentials rather than printing them. Use `answerlayer local status` and
56
48
  `answerlayer local logs` to inspect progress. `local stop` preserves data;
57
49
  `local reset --force` is the explicit destructive reset. Use `--no-demo`
58
- only when the user explicitly wants an empty instance.
50
+ only when the user explicitly wants an empty instance. Progress appears on
51
+ stderr; parse the single credential-free JSON object on stdout.
59
52
 
60
- 4. Inspect the machine-readable demo handoff:
53
+ 3. If the JSON status is `provider-required`, report that the provider-free demo
54
+ succeeded and hand provider setup back to the user. Ask them to run this
55
+ privately in their own terminal:
61
56
 
62
57
  ```bash
63
- answerlayer local demo --json
58
+ answerlayer local provider set anthropic
64
59
  ```
65
60
 
66
- Report the demo version, connection, verified result, and suggested next
67
- action. Do not attempt a natural-language inquiry until a model provider is
68
- configured. The demo saved query can be executed without a provider:
61
+ Never ask the user to paste the key into chat, never pass it as an argument,
62
+ and do not read a credential file. After the user confirms setup completed,
63
+ resume the same idempotent workflow without another state-change approval:
69
64
 
70
65
  ```bash
71
- answerlayer saved-queries execute <saved-query-id> --format table
66
+ answerlayer local quickstart --yes --json
72
67
  ```
73
68
 
74
- 5. Before connecting real data, require a dedicated database account that is
69
+ A `complete` status proves a real model-backed inquiry ran against the demo.
70
+ Report the local URL, verified question/result, and suggested next actions.
71
+ Repeating quickstart reuses the completed inquiry rather than creating a
72
+ duplicate session.
73
+
74
+ 4. Before connecting real data, require a dedicated database account that is
75
75
  restricted to approved schemas and `SELECT` only. Show the proposed
76
76
  connection host, database, and username, then get confirmation before
77
77
  running `connections create` or any query. Put the password only in a local,
78
78
  permission-restricted JSON file; never print it or commit it.
79
79
 
80
- 6. Start with a small approved schema and read-only inspection. Confirm before
80
+ 5. Start with a small approved schema and read-only inspection. Confirm before
81
81
  creating connections, generating semantic objects, or executing queries.
82
82
 
83
83
  This workflow is for Docker Compose development only. Do not run
package/src/cli.js CHANGED
@@ -1439,6 +1439,9 @@ function normalizeFlagName(rawName) {
1439
1439
  "--use-semantic-layer": "useSemanticLayer",
1440
1440
  "--no-semantic-layer": "noSemanticLayer",
1441
1441
  "--no-demo": "noDemo",
1442
+ "--from-file": "fromFile",
1443
+ "--yes": "yes",
1444
+ "-y": "yes",
1442
1445
  "--options": "options",
1443
1446
  "--status": "status",
1444
1447
  "--summary": "summary",
@@ -1477,7 +1480,7 @@ function normalizeFlagName(rawName) {
1477
1480
  }
1478
1481
 
1479
1482
  function isBooleanFlag(rawName) {
1480
- return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--follow", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot", "--use-semantic-layer", "--no-semantic-layer", "--no-demo"].includes(rawName);
1483
+ return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--follow", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot", "--use-semantic-layer", "--no-semantic-layer", "--no-demo", "--yes", "-y"].includes(rawName);
1481
1484
  }
1482
1485
 
1483
1486
  function setFlag(flags, name, value) {
@@ -1618,6 +1621,10 @@ Usage:
1618
1621
  answerlayer local start [--no-demo]
1619
1622
  answerlayer local status|logs|stop
1620
1623
  answerlayer local demo [--json]
1624
+ answerlayer local quickstart [--yes] [--json]
1625
+ answerlayer local provider set|rotate anthropic [--from-file <mode-0600-path>]
1626
+ answerlayer local provider status|verify [anthropic] [--json]
1627
+ answerlayer local provider remove anthropic --force
1621
1628
  answerlayer local upgrade [--image <image>]
1622
1629
  answerlayer local reset --force
1623
1630
  answerlayer init --api-key <key> [--base-url <url>]
package/src/local.js CHANGED
@@ -4,12 +4,14 @@ import net from "node:net";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { spawnSync } from "node:child_process";
7
+ import { createInterface } from "node:readline/promises";
7
8
  import { AnswerLayerClient } from "./client.js";
8
9
  import { defaultConfigPath, readConfig, writeConfig } from "./config.js";
9
10
 
10
11
  export const DEFAULT_LOCAL_IMAGE = "public.ecr.aws/s8d9x7y7/answerlayer:1.19.9";
11
12
  const DEFAULT_PORT = 8000;
12
13
  const MINIMUM_FREE_BYTES = 2 * 1024 * 1024 * 1024;
14
+ const PROVIDER_VALIDATION_TIMEOUT_MS = 15_000;
13
15
  const LOCAL_DEMO_VERSION = "retail-v1";
14
16
  const LOCAL_DEMO_CONNECTION_NAME = "AnswerLayer Demo";
15
17
  const LOCAL_DEMO_SAVED_QUERY_NAME = "Monthly revenue by region";
@@ -20,6 +22,14 @@ const LOCAL_DEMO_QUESTIONS = [
20
22
  "Which region generated the most completed revenue?",
21
23
  "How did completed revenue change from January to March?",
22
24
  ];
25
+ const LOCAL_QUICKSTART_QUESTION = LOCAL_DEMO_QUESTIONS[0];
26
+ const LOCAL_PROVIDERS = {
27
+ anthropic: {
28
+ label: "Anthropic",
29
+ environmentName: "ANSWERLAYER_ANTHROPIC_API_KEY",
30
+ },
31
+ };
32
+ const CLI_VERSION = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
23
33
 
24
34
  export async function handleLocal(command, parsed, io) {
25
35
  if (command === "init") return localInit(parsed, io);
@@ -28,9 +38,11 @@ export async function handleLocal(command, parsed, io) {
28
38
  if (command === "logs") return localLogs(parsed, io);
29
39
  if (command === "stop") return localStop(parsed, io);
30
40
  if (command === "demo") return localDemo(parsed, io);
41
+ if (command === "provider") return localProvider(parsed, io);
42
+ if (command === "quickstart") return localQuickstart(parsed, io);
31
43
  if (command === "upgrade") return localUpgrade(parsed, io);
32
44
  if (command === "reset") return localReset(parsed, io);
33
- throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|upgrade|reset`");
45
+ throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|provider|quickstart|upgrade|reset`");
34
46
  }
35
47
 
36
48
  export async function localUp(parsed, io) {
@@ -82,6 +94,70 @@ async function localStart(parsed, io) {
82
94
  write(io.stdout, "Demo: skipped (--no-demo)\n");
83
95
  write(io.stdout, "Install it later with: answerlayer local demo\n");
84
96
  }
97
+ return { runtime: { ...runtime, state }, baseUrl, configPath, demo };
98
+ }
99
+
100
+ async function localQuickstart(parsed, io) {
101
+ if (!(await confirmQuickstart(parsed, io))) {
102
+ throw new Error("Quickstart cancelled before making local runtime changes.");
103
+ }
104
+
105
+ const progressIo = { ...io, stdout: io.stderr };
106
+ const started = await localStart({
107
+ ...parsed,
108
+ flags: { ...parsed.flags, noDemo: false },
109
+ }, progressIo);
110
+ const { runtime, baseUrl, demo } = started;
111
+ const provider = resolveLocalProvider("anthropic");
112
+ const configured = Boolean(readEnvironment(runtime.envPath)[provider.environmentName]);
113
+ let providerStatus;
114
+
115
+ if (!configured) {
116
+ providerStatus = providerResult(provider, false, "ready", { verified: false, errorCode: "not-configured" });
117
+ const result = quickstartResult(runtime, demo, providerStatus, {
118
+ status: "not-run",
119
+ question: LOCAL_QUICKSTART_QUESTION,
120
+ });
121
+ persistQuickstart(runtime, { status: "provider-required", question: LOCAL_QUICKSTART_QUESTION });
122
+ printQuickstart(result, parsed, io);
123
+ return result;
124
+ }
125
+
126
+ const verification = validateProvider(runtime, io.runCommand || runCommand, provider);
127
+ providerStatus = providerResult(provider, true, "ready", verification);
128
+ if (!verification.verified) {
129
+ const result = quickstartResult(runtime, demo, providerStatus, {
130
+ status: "not-run",
131
+ question: LOCAL_QUICKSTART_QUESTION,
132
+ });
133
+ persistQuickstart(runtime, {
134
+ status: "provider-verification-failed",
135
+ question: LOCAL_QUICKSTART_QUESTION,
136
+ errorCode: verification.errorCode,
137
+ });
138
+ printQuickstart(result, parsed, io);
139
+ return result;
140
+ }
141
+
142
+ let inquiry = runtime.state.quickstart?.status === "complete"
143
+ && runtime.state.quickstart.question === LOCAL_QUICKSTART_QUESTION
144
+ && runtime.state.quickstart.connectionId === demo.connectionId
145
+ ? runtime.state.quickstart.inquiry
146
+ : null;
147
+ if (!inquiry) {
148
+ inquiry = await runQuickstartInquiry(baseUrl, demo.connectionId, io);
149
+ persistQuickstart(runtime, {
150
+ status: "complete",
151
+ question: LOCAL_QUICKSTART_QUESTION,
152
+ connectionId: demo.connectionId,
153
+ inquiry,
154
+ completedAt: new Date().toISOString(),
155
+ });
156
+ }
157
+
158
+ const result = quickstartResult(runtime, demo, providerStatus, inquiry);
159
+ printQuickstart(result, parsed, io);
160
+ return result;
85
161
  }
86
162
 
87
163
  async function localDemo(parsed, io) {
@@ -110,6 +186,102 @@ async function localDemo(parsed, io) {
110
186
  printDemoSummary(demo, io);
111
187
  }
112
188
 
189
+ async function localProvider(parsed, io) {
190
+ const action = parsed.positionals[2];
191
+ if (!action || !["set", "rotate", "status", "verify", "remove"].includes(action)) {
192
+ throw new Error("Expected `answerlayer local provider set|rotate|status|verify|remove`");
193
+ }
194
+ const provider = resolveLocalProvider(parsed.positionals[3]);
195
+ if (action === "set" || action === "rotate") return localProviderSet(parsed, io, provider, action);
196
+ if (action === "status" || action === "verify") return localProviderStatus(parsed, io, provider, action);
197
+ return localProviderRemove(parsed, io, provider);
198
+ }
199
+
200
+ async function localProviderSet(parsed, io, provider, action) {
201
+ if (parsed.flags.apiKey) {
202
+ throw new Error("Provider secrets are not accepted in command arguments. Use the hidden prompt or --from-file <path>.");
203
+ }
204
+ const run = io.runCommand || runCommand;
205
+ const runtime = requireReadyRuntime(parsed, io, run);
206
+ const environment = readEnvironment(runtime.envPath);
207
+ const existingSecret = environment[provider.environmentName] || "";
208
+ if (action === "rotate" && !existingSecret) {
209
+ throw new Error(`${provider.label} is not configured. Use \`answerlayer local provider set ${provider.id}\` first.`);
210
+ }
211
+ const secret = await readProviderSecret(parsed, io, provider);
212
+
213
+ writeEnvironmentValue(runtime.envPath, provider.environmentName, secret);
214
+ try {
215
+ restartProviderRuntime(runtime, run);
216
+ } catch {
217
+ rollbackProviderCredential(runtime, run, provider, existingSecret, "updating");
218
+ throw new Error(`Could not restart AnswerLayer with the new ${provider.label} credential. The previous configuration was restored.`);
219
+ }
220
+
221
+ const verification = validateProvider(runtime, run, provider);
222
+ if (!verification.verified) {
223
+ rollbackProviderCredential(runtime, run, provider, existingSecret, "verifying");
224
+ throw new Error(`${provider.label} verification failed (${verification.errorCode}). The previous configuration was restored.`);
225
+ }
226
+
227
+ const result = providerResult(provider, true, "ready", verification);
228
+ if (parsed.flags.json) {
229
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
230
+ return;
231
+ }
232
+ write(io.stdout, `${provider.label} credential ${action === "rotate" || existingSecret ? "rotated" : "configured"} and verified.\n`);
233
+ write(io.stdout, "The AnswerLayer application was recreated; local database data was preserved.\n");
234
+ }
235
+
236
+ async function localProviderStatus(parsed, io, provider, action) {
237
+ const run = io.runCommand || runCommand;
238
+ const runtime = loadRuntime(parsed, io);
239
+ requireCommand(run, "docker", ["compose", "version"]);
240
+ const runtimeStatus = inspectStatus(runtime, run, { tolerateFailure: true }).status;
241
+ const configured = Boolean(readEnvironment(runtime.envPath)[provider.environmentName]);
242
+ const verification = configured && runtimeStatus === "ready"
243
+ ? validateProvider(runtime, run, provider)
244
+ : { verified: false, errorCode: configured ? "runtime-not-ready" : "not-configured" };
245
+ const result = providerResult(provider, configured, runtimeStatus, verification);
246
+
247
+ if (action === "verify" && result.status !== "verified") {
248
+ throw new Error(`${provider.label} is ${result.status}. Run \`answerlayer local provider set ${provider.id}\` to configure and verify it.`);
249
+ }
250
+ if (parsed.flags.json) {
251
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
252
+ return;
253
+ }
254
+ write(io.stdout, `Provider: ${provider.id}\n`);
255
+ write(io.stdout, `Status: ${result.status}\n`);
256
+ write(io.stdout, `Runtime: ${runtimeStatus}\n`);
257
+ if (result.errorCode && result.status === "verification-failed") {
258
+ write(io.stdout, `Verification error: ${result.errorCode}\n`);
259
+ }
260
+ }
261
+
262
+ async function localProviderRemove(parsed, io, provider) {
263
+ if (!parsed.flags.force) {
264
+ throw new Error(`Removing ${provider.label} disables model-backed features. Rerun with \`answerlayer local provider remove ${provider.id} --force\` to confirm.`);
265
+ }
266
+ const run = io.runCommand || runCommand;
267
+ const runtime = requireReadyRuntime(parsed, io, run);
268
+ const existingSecret = readEnvironment(runtime.envPath)[provider.environmentName] || "";
269
+ writeEnvironmentValue(runtime.envPath, provider.environmentName, "");
270
+ try {
271
+ restartProviderRuntime(runtime, run);
272
+ } catch {
273
+ rollbackProviderCredential(runtime, run, provider, existingSecret, "removing");
274
+ throw new Error(`Could not remove ${provider.label}. The previous configuration was restored.`);
275
+ }
276
+ const result = providerResult(provider, false, "ready", { verified: false, errorCode: "not-configured" });
277
+ if (parsed.flags.json) {
278
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
279
+ return;
280
+ }
281
+ write(io.stdout, `${provider.label} credential removed. Model-backed features are disabled.\n`);
282
+ write(io.stdout, "The AnswerLayer application was recreated; local database data was preserved.\n");
283
+ }
284
+
113
285
  async function localUpgrade(parsed, io) {
114
286
  const image = firstValue(parsed.flags.image) || io.env.ANSWERLAYER_LOCAL_IMAGE || DEFAULT_LOCAL_IMAGE;
115
287
  write(io.stdout, `Upgrading the local runtime to ${image}...\n`);
@@ -128,6 +300,8 @@ async function localStatus(parsed, io) {
128
300
  resolvedImage: runtime.state.resolvedImage,
129
301
  runtimeDirectory: runtime.directory,
130
302
  demo: runtime.state.demo || { status: "not-installed", version: LOCAL_DEMO_VERSION },
303
+ quickstart: runtime.state.quickstart || { status: "not-started", question: LOCAL_QUICKSTART_QUESTION },
304
+ providers: localProviderConfiguration(runtime),
131
305
  services: status.services,
132
306
  };
133
307
 
@@ -140,6 +314,8 @@ async function localStatus(parsed, io) {
140
314
  write(io.stdout, `Image: ${result.resolvedImage}\n`);
141
315
  write(io.stdout, `Runtime config: ${result.runtimeDirectory}\n`);
142
316
  write(io.stdout, `Demo: ${result.demo.status} (${result.demo.version})\n`);
317
+ write(io.stdout, `Quickstart: ${result.quickstart.status}\n`);
318
+ write(io.stdout, `Model provider: ${result.providers.anthropic.configured ? "anthropic (configured)" : "not configured"}\n`);
143
319
  }
144
320
 
145
321
  async function localLogs(parsed, io) {
@@ -177,6 +353,7 @@ async function localReset(parsed, io) {
177
353
  writeState(runtime.statePath, {
178
354
  ...runtime.state,
179
355
  demo: { status: "not-installed", version: LOCAL_DEMO_VERSION },
356
+ quickstart: { status: "not-started", question: LOCAL_QUICKSTART_QUESTION },
180
357
  lastStatus: "stopped",
181
358
  resetAt: new Date().toISOString(),
182
359
  });
@@ -218,6 +395,7 @@ async function ensureInitialized(parsed, io) {
218
395
  resolvedImage,
219
396
  port,
220
397
  ...(existingState?.demo ? { demo: existingState.demo } : {}),
398
+ ...(existingState?.quickstart ? { quickstart: existingState.quickstart } : {}),
221
399
  ...runtimeResourceNames(runtime.directory),
222
400
  createdAt: existingState?.createdAt || new Date().toISOString(),
223
401
  updatedAt: new Date().toISOString(),
@@ -423,6 +601,14 @@ function writeEnvironment(envPath, state) {
423
601
  fs.chmodSync(envPath, 0o600);
424
602
  }
425
603
 
604
+ function writeEnvironmentValue(envPath, name, value) {
605
+ const values = readEnvironment(envPath);
606
+ values[name] = value;
607
+ const contents = Object.entries(values).map(([entryName, entryValue]) => `${entryName}=${entryValue}`).join("\n");
608
+ fs.writeFileSync(envPath, `${contents}\n`, { encoding: "utf8", mode: 0o600 });
609
+ fs.chmodSync(envPath, 0o600);
610
+ }
611
+
426
612
  function readEnvironment(envPath) {
427
613
  if (!fs.existsSync(envPath)) return {};
428
614
  return Object.fromEntries(
@@ -433,6 +619,299 @@ function readEnvironment(envPath) {
433
619
  );
434
620
  }
435
621
 
622
+ function localProviderConfiguration(runtime) {
623
+ const environment = readEnvironment(runtime.envPath);
624
+ return Object.fromEntries(Object.entries(LOCAL_PROVIDERS).map(([id, provider]) => [
625
+ id,
626
+ { configured: Boolean(environment[provider.environmentName]) },
627
+ ]));
628
+ }
629
+
630
+ function resolveLocalProvider(value) {
631
+ const id = String(value || "anthropic").toLowerCase();
632
+ const provider = LOCAL_PROVIDERS[id];
633
+ if (!provider) {
634
+ throw new Error(`Unsupported local model provider ${value}. Supported providers: ${Object.keys(LOCAL_PROVIDERS).join(", ")}`);
635
+ }
636
+ return { id, ...provider };
637
+ }
638
+
639
+ function requireReadyRuntime(parsed, io, run) {
640
+ const runtime = loadRuntime(parsed, io);
641
+ requireCommand(run, "docker", ["compose", "version"]);
642
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
643
+ if (status.status !== "ready") {
644
+ throw new Error("Local AnswerLayer must be ready before changing a model provider. Run `answerlayer local start` first.");
645
+ }
646
+ return runtime;
647
+ }
648
+
649
+ async function readProviderSecret(parsed, io, provider) {
650
+ const filePath = firstValue(parsed.flags.fromFile) || io.env.ANSWERLAYER_PROVIDER_KEY_FILE;
651
+ let secret;
652
+ if (filePath) {
653
+ const resolvedPath = path.resolve(filePath);
654
+ let stats;
655
+ try {
656
+ stats = fs.statSync(resolvedPath);
657
+ } catch {
658
+ throw new Error(`Could not read the provider credential file at ${resolvedPath}`);
659
+ }
660
+ if (!stats.isFile()) throw new Error(`Provider credential path is not a file: ${resolvedPath}`);
661
+ if ((io.platform || process.platform) !== "win32" && (stats.mode & 0o077) !== 0) {
662
+ throw new Error(`Provider credential file permissions are too broad. Run \`chmod 600 ${resolvedPath}\` and retry.`);
663
+ }
664
+ secret = fs.readFileSync(resolvedPath, "utf8").trim();
665
+ } else if (io.readSecret) {
666
+ secret = await io.readSecret(`${provider.label} API key: `);
667
+ } else {
668
+ secret = await readHiddenInput(io.stdin, io.stderr, `${provider.label} API key: `);
669
+ }
670
+
671
+ if (typeof secret !== "string" || secret.length < 12 || /\s/.test(secret)) {
672
+ throw new Error(`${provider.label} credential is empty or invalid. Use a single-line API key.`);
673
+ }
674
+ return secret;
675
+ }
676
+
677
+ function readHiddenInput(input, output, prompt) {
678
+ if (!input?.isTTY || typeof input.setRawMode !== "function") {
679
+ 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>.");
680
+ }
681
+ write(output, prompt);
682
+ return new Promise((resolve, reject) => {
683
+ const wasRaw = Boolean(input.isRaw);
684
+ const wasPaused = typeof input.isPaused === "function" ? input.isPaused() : false;
685
+ let secret = "";
686
+ let settled = false;
687
+ const cleanup = () => {
688
+ input.off("data", onData);
689
+ input.off("end", onEnd);
690
+ input.off("close", onClose);
691
+ input.off("error", onError);
692
+ input.setRawMode(wasRaw);
693
+ if (wasPaused && typeof input.pause === "function") input.pause();
694
+ write(output, "\n");
695
+ };
696
+ const finish = (error) => {
697
+ if (settled) return;
698
+ settled = true;
699
+ cleanup();
700
+ if (error) reject(error);
701
+ else resolve(secret);
702
+ };
703
+ const onData = chunk => {
704
+ for (const character of String(chunk)) {
705
+ if (character === "\r" || character === "\n") return finish();
706
+ if (character === "\u0003") return finish(new Error("Provider credential entry cancelled"));
707
+ if (character === "\u007f" || character === "\b") {
708
+ secret = secret.slice(0, -1);
709
+ } else if (character >= " ") {
710
+ secret += character;
711
+ }
712
+ }
713
+ };
714
+ const onEnd = () => finish(new Error("Provider credential input ended before submission"));
715
+ const onClose = () => finish(new Error("Provider credential input closed before submission"));
716
+ const onError = () => finish(new Error("Provider credential input failed before submission"));
717
+ input.setRawMode(true);
718
+ input.on("data", onData);
719
+ input.once("end", onEnd);
720
+ input.once("close", onClose);
721
+ input.once("error", onError);
722
+ if (typeof input.resume === "function") input.resume();
723
+ });
724
+ }
725
+
726
+ function restartProviderRuntime(runtime, run) {
727
+ const result = run("docker", [
728
+ ...composeArgs(runtime),
729
+ "up", "--detach", "--no-deps", "--force-recreate", "--wait", "--wait-timeout", "180", "answerlayer",
730
+ ], { capture: true });
731
+ if (result.error || result.status !== 0) {
732
+ throw new Error("AnswerLayer application restart failed");
733
+ }
734
+ }
735
+
736
+ function rollbackProviderCredential(runtime, run, provider, existingSecret, action) {
737
+ writeEnvironmentValue(runtime.envPath, provider.environmentName, existingSecret);
738
+ try {
739
+ restartProviderRuntime(runtime, run);
740
+ } catch {
741
+ throw new Error(`Could not restart AnswerLayer while ${action} ${provider.label}. The previous credential remains in runtime.env; run \`answerlayer local start\` to recover.`);
742
+ }
743
+ }
744
+
745
+ function validateProvider(runtime, run, provider) {
746
+ const result = run("docker", [
747
+ ...composeArgs(runtime),
748
+ "exec", "-T", "answerlayer", "python", "-c", PROVIDER_VALIDATION_SCRIPT,
749
+ ], { capture: true, timeout: PROVIDER_VALIDATION_TIMEOUT_MS });
750
+ if (result.error?.code === "ETIMEDOUT") {
751
+ return { verified: false, errorCode: `${provider.id}-verification-timeout` };
752
+ }
753
+ const payload = parseProviderValidation(result.stdout);
754
+ if (!result.error && result.status === 0 && payload?.verified === true) {
755
+ return { verified: true };
756
+ }
757
+ return {
758
+ verified: false,
759
+ errorCode: /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/.test(payload?.error || "")
760
+ ? payload.error
761
+ : `${provider.id}-verification-failed`,
762
+ };
763
+ }
764
+
765
+ function parseProviderValidation(stdout) {
766
+ const line = String(stdout || "").trim().split(/\r?\n/).at(-1);
767
+ try {
768
+ return JSON.parse(line);
769
+ } catch {
770
+ return null;
771
+ }
772
+ }
773
+
774
+ function providerResult(provider, configured, runtimeStatus, verification) {
775
+ const status = !configured
776
+ ? "unconfigured"
777
+ : runtimeStatus !== "ready"
778
+ ? "configured-runtime-not-ready"
779
+ : verification.verified
780
+ ? "verified"
781
+ : "verification-failed";
782
+ return {
783
+ provider: provider.id,
784
+ configured,
785
+ status,
786
+ runtimeStatus,
787
+ ...(status === "verification-failed" ? { errorCode: verification.errorCode } : {}),
788
+ };
789
+ }
790
+
791
+ async function confirmQuickstart(parsed, io) {
792
+ if (parsed.flags.yes) return true;
793
+ const prompt = "Quickstart may pull an image, start local containers, and create persistent demo data. Continue? [y/N] ";
794
+ if (io.confirm) return Boolean(await io.confirm(prompt));
795
+ if (!io.stdin?.isTTY) {
796
+ throw new Error("Quickstart requires confirmation before starting containers. Rerun interactively or use --yes only after the user approves.");
797
+ }
798
+ const terminal = createInterface({ input: io.stdin, output: io.stderr });
799
+ try {
800
+ const answer = await terminal.question(prompt);
801
+ return /^(?:y|yes)$/i.test(answer.trim());
802
+ } finally {
803
+ terminal.close();
804
+ }
805
+ }
806
+
807
+ async function runQuickstartInquiry(baseUrl, connectionId, io) {
808
+ const config = readConfig(io.env);
809
+ if (config.baseUrl !== baseUrl || !config.apiKey) {
810
+ throw new Error("Local CLI credentials are unavailable. Run `answerlayer local start` and retry quickstart.");
811
+ }
812
+ const client = new AnswerLayerClient({
813
+ baseUrl,
814
+ apiKey: config.apiKey,
815
+ fetchImpl: io.fetch || globalThis.fetch,
816
+ });
817
+ const catalog = await client.request("GET", "/api/v1/inquiry/models");
818
+ const model = catalog?.default_model;
819
+ if (!model) throw new Error("The local runtime did not return a default inquiry model.");
820
+ const session = await client.request("POST", "/api/v1/inquiry/sessions", {
821
+ body: { connection_id: connectionId, model, use_semantic_layer: true },
822
+ });
823
+ if (!session?.session_id) throw new Error("Quickstart inquiry did not return a session ID.");
824
+ const turn = await client.request(
825
+ "POST",
826
+ `/api/v1/inquiry/sessions/${encodeURIComponent(session.session_id)}/sync`,
827
+ { body: { user_input: LOCAL_QUICKSTART_QUESTION } },
828
+ );
829
+ if (!String(turn?.final_response || "").trim()) {
830
+ throw new Error("Quickstart inquiry completed without a model response. Check `answerlayer local logs answerlayer` and retry.");
831
+ }
832
+ return {
833
+ status: "verified",
834
+ sessionId: String(session.session_id),
835
+ turnId: turn.turn_id ? String(turn.turn_id) : null,
836
+ model,
837
+ question: LOCAL_QUICKSTART_QUESTION,
838
+ answer: String(turn.final_response),
839
+ sqlQueries: Array.isArray(turn.sql_queries) ? turn.sql_queries.map(String) : [],
840
+ };
841
+ }
842
+
843
+ function persistQuickstart(runtime, quickstart) {
844
+ const state = {
845
+ ...runtime.state,
846
+ quickstart,
847
+ updatedAt: new Date().toISOString(),
848
+ };
849
+ writeState(runtime.statePath, state);
850
+ runtime.state = state;
851
+ }
852
+
853
+ function quickstartResult(runtime, demo, provider, inquiry) {
854
+ const status = provider.status === "unconfigured"
855
+ ? "provider-required"
856
+ : provider.status !== "verified"
857
+ ? "provider-verification-failed"
858
+ : inquiry.status === "verified"
859
+ ? "complete"
860
+ : "inquiry-not-run";
861
+ return {
862
+ schemaVersion: 1,
863
+ status,
864
+ cliVersion: CLI_VERSION,
865
+ runtime: {
866
+ status: "ready",
867
+ url: `http://127.0.0.1:${runtime.state.port}`,
868
+ image: runtime.state.requestedImage,
869
+ resolvedImage: runtime.state.resolvedImage,
870
+ directory: runtime.directory,
871
+ },
872
+ demo: {
873
+ status: demo.status,
874
+ version: demo.version,
875
+ connectionId: demo.connectionId,
876
+ savedQueryId: demo.savedQueryId,
877
+ validation: demo.validation,
878
+ },
879
+ provider,
880
+ inquiry,
881
+ nextActions: status === "provider-required"
882
+ ? ["answerlayer local provider set anthropic", "answerlayer local quickstart"]
883
+ : status === "provider-verification-failed"
884
+ ? ["answerlayer local provider set anthropic", "answerlayer local quickstart"]
885
+ : LOCAL_DEMO_QUESTIONS.slice(1).map(question => `answerlayer inquiry ask --connection ${demo.connectionId} "${question}"`),
886
+ };
887
+ }
888
+
889
+ function printQuickstart(result, parsed, io) {
890
+ if (parsed.flags.json) {
891
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
892
+ return;
893
+ }
894
+ write(io.stdout, `AnswerLayer quickstart: ${result.status}\n`);
895
+ write(io.stdout, `URL: ${result.runtime.url}\n`);
896
+ write(io.stdout, `Demo: ${result.demo.status} (${result.demo.version})\n`);
897
+ if (result.status === "provider-required") {
898
+ write(io.stdout, "A model provider is required for natural-language inquiry.\n");
899
+ write(io.stdout, "Enter the credential privately in your terminal: answerlayer local provider set anthropic\n");
900
+ write(io.stdout, "Then resume with: answerlayer local quickstart\n");
901
+ return;
902
+ }
903
+ if (result.status === "provider-verification-failed") {
904
+ write(io.stdout, `Provider verification failed: ${result.provider.errorCode}\n`);
905
+ write(io.stdout, "Repair it privately with: answerlayer local provider set anthropic\n");
906
+ return;
907
+ }
908
+ write(io.stdout, `Model inquiry verified with ${result.inquiry.model}.\n`);
909
+ write(io.stdout, `Question: ${result.inquiry.question}\n`);
910
+ write(io.stdout, `Answer: ${result.inquiry.answer}\n`);
911
+ write(io.stdout, `Session: ${result.inquiry.sessionId}\n`);
912
+ write(io.stdout, `Next: ${result.nextActions[0]}\n`);
913
+ }
914
+
436
915
  function readState(statePath) {
437
916
  if (!fs.existsSync(statePath)) return null;
438
917
  try {
@@ -516,6 +995,7 @@ function runCommand(command, args, options = {}) {
516
995
  return spawnSync(command, args, {
517
996
  encoding: options.capture ? "utf8" : undefined,
518
997
  input: options.input,
998
+ timeout: options.timeout,
519
999
  stdio: options.capture
520
1000
  ? [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
521
1001
  : "inherit",
@@ -814,6 +1294,25 @@ GROUP BY 1, 2
814
1294
  ORDER BY 1, 2
815
1295
  `.trim();
816
1296
 
1297
+ const PROVIDER_VALIDATION_SCRIPT = `
1298
+ import json
1299
+ import os
1300
+
1301
+ from anthropic import Anthropic
1302
+
1303
+ try:
1304
+ Anthropic(
1305
+ api_key=os.environ["ANTHROPIC_API_KEY"],
1306
+ max_retries=0,
1307
+ timeout=10.0,
1308
+ ).models.list(limit=1)
1309
+ except Exception as error:
1310
+ print(json.dumps({"verified": False, "error": type(error).__name__}))
1311
+ raise SystemExit(1)
1312
+
1313
+ print(json.dumps({"verified": True}))
1314
+ `.trim();
1315
+
817
1316
  function firstValue(value) {
818
1317
  return Array.isArray(value) ? value[0] : value;
819
1318
  }