@answerlayer/cli 0.1.9 → 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
@@ -115,8 +115,9 @@ to change the local port. The CLI:
115
115
  4. Starts Postgres, runs migrations, and waits for AnswerLayer readiness.
116
116
  5. Creates a local-only organization and scoped key, verifies the key, and
117
117
  saves the CLI configuration without printing the key.
118
- 6. Leaves you ready to connect a dedicated, read-only database user and test a
119
- small, approved schema first.
118
+ 6. Seeds a versioned synthetic retail demo in a separate Postgres database,
119
+ registers its dedicated read-only connection, creates starter semantic
120
+ objects and a saved query, and verifies a deterministic result.
120
121
 
121
122
  The local stack does not require a hosted AnswerLayer account, a source checkout,
122
123
  private registry credentials, or a model-provider key for first boot. Add an
@@ -125,6 +126,55 @@ The skill requires agent confirmation before it starts containers, creates a
125
126
  connection, or sends queries to a real database, and it instructs agents not to
126
127
  print or persist database passwords.
127
128
 
129
+ The demo is installed by default. Use `answerlayer local start --no-demo` to
130
+ skip it, or install/verify it later with:
131
+
132
+ ```bash
133
+ answerlayer local demo
134
+ answerlayer local demo --json
135
+ ```
136
+
137
+ `local demo --json` returns the demo version, connection ID, saved-query ID,
138
+ semantic-resource IDs, the verified result, and suggested natural-language
139
+ questions without returning credentials. The saved query works before a model
140
+ provider is configured:
141
+
142
+ ```bash
143
+ answerlayer saved-queries execute <saved-query-id> --format table
144
+ ```
145
+
146
+ Natural-language inquiry still requires provider configuration. Re-running the
147
+ demo command reuses the same connection and semantic resources rather than
148
+ duplicating them. `local reset --force` explicitly removes both application and
149
+ demo data because they share the selected runtime's isolated Postgres volume.
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
+
128
178
  Inspect and manage the lifecycle with:
129
179
 
130
180
  ```bash
@@ -160,6 +210,8 @@ answerlayer health
160
210
  answerlayer openapi --output openapi.json
161
211
  answerlayer local init
162
212
  answerlayer local start
213
+ answerlayer local demo --json
214
+ answerlayer local provider status --json
163
215
  answerlayer local status
164
216
  answerlayer local logs
165
217
  answerlayer local stop
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@answerlayer/cli",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -48,18 +48,55 @@ already available in the Codex skills directory.
48
48
  ```
49
49
 
50
50
  This starts Postgres, runs migrations, waits for readiness, creates the local
51
- identity and scoped key, verifies it, and configures the CLI. It captures the
52
- one-time key rather than printing it. Use `answerlayer local status` and
51
+ identity and scoped key, verifies it, and configures the CLI. It also seeds a
52
+ versioned synthetic retail demo in a separate database, registers a
53
+ dedicated read-only connection, creates starter semantic resources and a
54
+ saved query, and verifies a deterministic result. It captures generated
55
+ credentials rather than printing them. Use `answerlayer local status` and
53
56
  `answerlayer local logs` to inspect progress. `local stop` preserves data;
54
- `local reset --force` is the explicit destructive reset.
57
+ `local reset --force` is the explicit destructive reset. Use `--no-demo`
58
+ only when the user explicitly wants an empty instance.
55
59
 
56
- 4. Before connecting real data, require a dedicated database account that is
60
+ 4. Inspect the machine-readable demo handoff:
61
+
62
+ ```bash
63
+ answerlayer local demo --json
64
+ ```
65
+
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:
69
+
70
+ ```bash
71
+ answerlayer saved-queries execute <saved-query-id> --format table
72
+ ```
73
+
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
57
94
  restricted to approved schemas and `SELECT` only. Show the proposed
58
95
  connection host, database, and username, then get confirmation before
59
96
  running `connections create` or any query. Put the password only in a local,
60
97
  permission-restricted JSON file; never print it or commit it.
61
98
 
62
- 5. 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
63
100
  creating connections, generating semantic objects, or executing queries.
64
101
 
65
102
  This workflow is for Docker Compose development only. Do not run
package/src/cli.js CHANGED
@@ -1438,6 +1438,8 @@ function normalizeFlagName(rawName) {
1438
1438
  "--model": "model",
1439
1439
  "--use-semantic-layer": "useSemanticLayer",
1440
1440
  "--no-semantic-layer": "noSemanticLayer",
1441
+ "--no-demo": "noDemo",
1442
+ "--from-file": "fromFile",
1441
1443
  "--options": "options",
1442
1444
  "--status": "status",
1443
1445
  "--summary": "summary",
@@ -1476,7 +1478,7 @@ function normalizeFlagName(rawName) {
1476
1478
  }
1477
1479
 
1478
1480
  function isBooleanFlag(rawName) {
1479
- return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--follow", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot", "--use-semantic-layer", "--no-semantic-layer"].includes(rawName);
1481
+ 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);
1480
1482
  }
1481
1483
 
1482
1484
  function setFlag(flags, name, value) {
@@ -1614,7 +1616,12 @@ function helpText() {
1614
1616
  Usage:
1615
1617
  answerlayer skills install [--path <directory>] [--force]
1616
1618
  answerlayer local init [--image <image>] [--port <port>]
1617
- answerlayer local start|status|logs|stop
1619
+ answerlayer local start [--no-demo]
1620
+ answerlayer local status|logs|stop
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
1618
1625
  answerlayer local upgrade [--image <image>]
1619
1626
  answerlayer local reset --force
1620
1627
  answerlayer init --api-key <key> [--base-url <url>]
package/src/local.js CHANGED
@@ -10,6 +10,23 @@ 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;
14
+ const LOCAL_DEMO_VERSION = "retail-v1";
15
+ const LOCAL_DEMO_CONNECTION_NAME = "AnswerLayer Demo";
16
+ const LOCAL_DEMO_SAVED_QUERY_NAME = "Monthly revenue by region";
17
+ const LOCAL_DEMO_DATABASE = "answerlayer_demo";
18
+ const LOCAL_DEMO_USER = "answerlayer_demo_reader";
19
+ const LOCAL_DEMO_QUESTIONS = [
20
+ "How much completed revenue did we generate each month?",
21
+ "Which region generated the most completed revenue?",
22
+ "How did completed revenue change from January to March?",
23
+ ];
24
+ const LOCAL_PROVIDERS = {
25
+ anthropic: {
26
+ label: "Anthropic",
27
+ environmentName: "ANSWERLAYER_ANTHROPIC_API_KEY",
28
+ },
29
+ };
13
30
 
14
31
  export async function handleLocal(command, parsed, io) {
15
32
  if (command === "init") return localInit(parsed, io);
@@ -17,9 +34,11 @@ export async function handleLocal(command, parsed, io) {
17
34
  if (command === "status") return localStatus(parsed, io);
18
35
  if (command === "logs") return localLogs(parsed, io);
19
36
  if (command === "stop") return localStop(parsed, io);
37
+ if (command === "demo") return localDemo(parsed, io);
38
+ if (command === "provider") return localProvider(parsed, io);
20
39
  if (command === "upgrade") return localUpgrade(parsed, io);
21
40
  if (command === "reset") return localReset(parsed, io);
22
- throw new Error("Expected `answerlayer local init|start|status|logs|stop|upgrade|reset`");
41
+ throw new Error("Expected `answerlayer local init|start|status|logs|stop|demo|provider|upgrade|reset`");
23
42
  }
24
43
 
25
44
  export async function localUp(parsed, io) {
@@ -57,12 +76,142 @@ async function localStart(parsed, io) {
57
76
  const baseUrl = `http://127.0.0.1:${runtime.state.port}`;
58
77
  await waitUntilReady(baseUrl, io);
59
78
  const configPath = await ensureLocalCredentials(runtime, baseUrl, io);
60
- const state = { ...runtime.state, lastStatus: "ready", updatedAt: new Date().toISOString() };
79
+ const demo = parsed.flags.noDemo
80
+ ? { status: "skipped", version: LOCAL_DEMO_VERSION }
81
+ : await ensureLocalDemo(runtime, baseUrl, io);
82
+ const state = { ...runtime.state, demo, lastStatus: "ready", updatedAt: new Date().toISOString() };
61
83
  writeState(runtime.statePath, state);
62
84
 
63
85
  printRuntimeSummary({ ...runtime, state }, io, "Local AnswerLayer is ready.");
64
86
  write(io.stdout, `CLI config: ${configPath}\n`);
65
- write(io.stdout, "Next: answerlayer connections list\n");
87
+ if (demo.status === "ready") {
88
+ printDemoSummary(demo, io);
89
+ } else {
90
+ write(io.stdout, "Demo: skipped (--no-demo)\n");
91
+ write(io.stdout, "Install it later with: answerlayer local demo\n");
92
+ }
93
+ }
94
+
95
+ async function localDemo(parsed, io) {
96
+ const run = io.runCommand || runCommand;
97
+ const runtime = loadRuntime(parsed, io);
98
+ requireCommand(run, "docker", ["compose", "version"]);
99
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
100
+ if (status.status !== "ready") {
101
+ throw new Error("Local AnswerLayer must be ready before installing the demo. Run `answerlayer local start` first.");
102
+ }
103
+
104
+ const baseUrl = `http://127.0.0.1:${runtime.state.port}`;
105
+ await ensureLocalCredentials(runtime, baseUrl, io, { quiet: Boolean(parsed.flags.json) });
106
+ const demo = await ensureLocalDemo(runtime, baseUrl, io, { quiet: Boolean(parsed.flags.json) });
107
+ writeState(runtime.statePath, {
108
+ ...runtime.state,
109
+ demo,
110
+ lastStatus: "ready",
111
+ updatedAt: new Date().toISOString(),
112
+ });
113
+
114
+ if (parsed.flags.json) {
115
+ write(io.stdout, `${JSON.stringify(demo, null, 2)}\n`);
116
+ return;
117
+ }
118
+ printDemoSummary(demo, io);
119
+ }
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");
66
215
  }
67
216
 
68
217
  async function localUpgrade(parsed, io) {
@@ -82,6 +231,8 @@ async function localStatus(parsed, io) {
82
231
  image: runtime.state.requestedImage,
83
232
  resolvedImage: runtime.state.resolvedImage,
84
233
  runtimeDirectory: runtime.directory,
234
+ demo: runtime.state.demo || { status: "not-installed", version: LOCAL_DEMO_VERSION },
235
+ providers: localProviderConfiguration(runtime),
85
236
  services: status.services,
86
237
  };
87
238
 
@@ -93,6 +244,8 @@ async function localStatus(parsed, io) {
93
244
  write(io.stdout, `URL: ${result.url}\n`);
94
245
  write(io.stdout, `Image: ${result.resolvedImage}\n`);
95
246
  write(io.stdout, `Runtime config: ${result.runtimeDirectory}\n`);
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`);
96
249
  }
97
250
 
98
251
  async function localLogs(parsed, io) {
@@ -127,7 +280,12 @@ async function localReset(parsed, io) {
127
280
  const runtime = loadRuntime(parsed, io);
128
281
  requireCommand(run, "docker", ["compose", "version"]);
129
282
  checked(run, "docker", [...composeArgs(runtime), "down", "--volumes", "--remove-orphans"], { passthrough: true });
130
- writeState(runtime.statePath, { ...runtime.state, lastStatus: "stopped", resetAt: new Date().toISOString() });
283
+ writeState(runtime.statePath, {
284
+ ...runtime.state,
285
+ demo: { status: "not-installed", version: LOCAL_DEMO_VERSION },
286
+ lastStatus: "stopped",
287
+ resetAt: new Date().toISOString(),
288
+ });
131
289
  write(io.stdout, "Deleted the local AnswerLayer database volume. Runtime configuration was preserved.\n");
132
290
  write(io.stdout, "Create a fresh database with: answerlayer local start\n");
133
291
  }
@@ -165,6 +323,7 @@ async function ensureInitialized(parsed, io) {
165
323
  requestedImage,
166
324
  resolvedImage,
167
325
  port,
326
+ ...(existingState?.demo ? { demo: existingState.demo } : {}),
168
327
  ...runtimeResourceNames(runtime.directory),
169
328
  createdAt: existingState?.createdAt || new Date().toISOString(),
170
329
  updatedAt: new Date().toISOString(),
@@ -232,7 +391,7 @@ function imageRepository(image) {
232
391
  return colon > slash ? withoutDigest.slice(0, colon) : withoutDigest;
233
392
  }
234
393
 
235
- async function ensureLocalCredentials(runtime, baseUrl, io) {
394
+ async function ensureLocalCredentials(runtime, baseUrl, io, options = {}) {
236
395
  const existing = readConfig(io.env);
237
396
  const fetchImpl = io.fetch || globalThis.fetch;
238
397
  if (existing.baseUrl === baseUrl && existing.apiKey) {
@@ -245,7 +404,9 @@ async function ensureLocalCredentials(runtime, baseUrl, io) {
245
404
  }
246
405
  }
247
406
 
248
- write(io.stdout, "Creating a local-only CLI identity...\n");
407
+ if (!options.quiet) {
408
+ write(io.stdout, "Creating a local-only CLI identity...\n");
409
+ }
249
410
  const run = io.runCommand || runCommand;
250
411
  let bootstrap;
251
412
  try {
@@ -355,6 +516,7 @@ function writeEnvironment(envPath, state) {
355
516
  ANSWERLAYER_IMAGE: state.resolvedImage,
356
517
  ANSWERLAYER_POSTGRES_PASSWORD: existing.ANSWERLAYER_POSTGRES_PASSWORD || crypto.randomBytes(24).toString("hex"),
357
518
  ANSWERLAYER_ENCRYPTION_KEY: existing.ANSWERLAYER_ENCRYPTION_KEY || crypto.randomBytes(32).toString("hex"),
519
+ ANSWERLAYER_DEMO_PASSWORD: existing.ANSWERLAYER_DEMO_PASSWORD || crypto.randomBytes(24).toString("hex"),
358
520
  ANSWERLAYER_PORT: String(state.port),
359
521
  ANSWERLAYER_LOG_LEVEL: existing.ANSWERLAYER_LOG_LEVEL || "INFO",
360
522
  ANSWERLAYER_WEB_CONCURRENCY: existing.ANSWERLAYER_WEB_CONCURRENCY || "1",
@@ -367,6 +529,14 @@ function writeEnvironment(envPath, state) {
367
529
  fs.chmodSync(envPath, 0o600);
368
530
  }
369
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
+
370
540
  function readEnvironment(envPath) {
371
541
  if (!fs.existsSync(envPath)) return {};
372
542
  return Object.fromEntries(
@@ -377,6 +547,175 @@ function readEnvironment(envPath) {
377
547
  );
378
548
  }
379
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
+
380
719
  function readState(statePath) {
381
720
  if (!fs.existsSync(statePath)) return null;
382
721
  try {
@@ -447,7 +786,7 @@ function requireCommand(run, command, args) {
447
786
  }
448
787
 
449
788
  function checked(run, command, args, options = {}) {
450
- const result = run(command, args, { capture: !options.passthrough });
789
+ const result = run(command, args, { capture: !options.passthrough, input: options.input });
451
790
  if (result.error) throw result.error;
452
791
  if (result.status !== 0) {
453
792
  const detail = String(result.stderr || result.stdout || "").trim();
@@ -459,7 +798,11 @@ function checked(run, command, args, options = {}) {
459
798
  function runCommand(command, args, options = {}) {
460
799
  return spawnSync(command, args, {
461
800
  encoding: options.capture ? "utf8" : undefined,
462
- stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit",
801
+ input: options.input,
802
+ timeout: options.timeout,
803
+ stdio: options.capture
804
+ ? [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"]
805
+ : "inherit",
463
806
  maxBuffer: 50 * 1024 * 1024,
464
807
  });
465
808
  }
@@ -472,6 +815,308 @@ function printRuntimeSummary(runtime, io, heading) {
472
815
  write(io.stdout, `Runtime config: ${runtime.directory}\n`);
473
816
  }
474
817
 
818
+ function printDemoSummary(demo, io) {
819
+ write(io.stdout, `Demo: ready (${demo.version})\n`);
820
+ write(io.stdout, `Demo connection: ${demo.connectionId}\n`);
821
+ write(io.stdout, `Verified result: ${demo.validation.completedOrderCount} completed orders, $${demo.validation.totalRevenue} revenue\n`);
822
+ write(io.stdout, `Try now: answerlayer saved-queries execute ${demo.savedQueryId} --format table\n`);
823
+ write(io.stdout, `After configuring a model provider, ask: answerlayer inquiry ask --connection ${demo.connectionId} "${demo.questions[0]}"\n`);
824
+ }
825
+
826
+ async function ensureLocalDemo(runtime, baseUrl, io, options = {}) {
827
+ const environment = readEnvironment(runtime.envPath);
828
+ const demoPassword = environment.ANSWERLAYER_DEMO_PASSWORD;
829
+ if (!demoPassword || !/^[a-f0-9]{48}$/.test(demoPassword)) {
830
+ throw new Error("The local demo password is missing or invalid. Run `answerlayer local init` to repair runtime configuration.");
831
+ }
832
+
833
+ const run = io.runCommand || runCommand;
834
+ if (!options.quiet) {
835
+ write(io.stdout, `Preparing deterministic demo data (${LOCAL_DEMO_VERSION})...\n`);
836
+ }
837
+ checked(run, "docker", [
838
+ ...composeArgs(runtime),
839
+ "exec", "-T", "postgres", "psql",
840
+ "--set", "ON_ERROR_STOP=1",
841
+ "--username", "answerlayer",
842
+ "--dbname", "postgres",
843
+ ], { input: demoSeedSql(demoPassword) });
844
+
845
+ const config = readConfig(io.env);
846
+ if (config.baseUrl !== baseUrl || !config.apiKey) {
847
+ throw new Error("Local CLI credentials are not configured. Run `answerlayer local start` first.");
848
+ }
849
+ const client = new AnswerLayerClient({ baseUrl, apiKey: config.apiKey, fetchImpl: io.fetch || globalThis.fetch });
850
+
851
+ const connection = await ensureDemoConnection(client, demoPassword);
852
+ const connectionId = String(connection.id);
853
+ const entities = [
854
+ await ensureSemanticResource(client, "entities", connectionId, "Orders", {
855
+ name: "Orders",
856
+ source_table: "demo.orders",
857
+ identifier: "id",
858
+ temporal_key: "order_date",
859
+ description: "Completed and refunded retail orders in the AnswerLayer onboarding demo.",
860
+ }),
861
+ await ensureSemanticResource(client, "entities", connectionId, "Customers", {
862
+ name: "Customers",
863
+ source_table: "demo.customers",
864
+ identifier: "id",
865
+ description: "Synthetic customers grouped by region and business segment.",
866
+ }),
867
+ ];
868
+ const relationship = await ensureSemanticResource(client, "relationships", connectionId, "Orders to Customers", {
869
+ name: "Orders to Customers",
870
+ description: "Each order belongs to one customer.",
871
+ from_entity: "Orders",
872
+ to_entity: "Customers",
873
+ join_keys: { from: "customer_id", to: "id" },
874
+ cardinality: "many_to_one",
875
+ });
876
+ const dimensions = [
877
+ await ensureSemanticResource(client, "dimensions", connectionId, "Order date", {
878
+ name: "Order date",
879
+ entity: "Orders",
880
+ expression: "order_date",
881
+ description: "Calendar date on which the order was placed.",
882
+ }),
883
+ await ensureSemanticResource(client, "dimensions", connectionId, "Customer region", {
884
+ name: "Customer region",
885
+ entity: "Customers",
886
+ expression: "region",
887
+ description: "North, South, East, or West sales region.",
888
+ }),
889
+ ];
890
+ const measure = await ensureSemanticResource(client, "measures", connectionId, "Revenue", {
891
+ name: "Revenue",
892
+ entity: "Orders",
893
+ expression: "quantity * unit_price",
894
+ aggregation: "sum",
895
+ default_filters: [],
896
+ description: "Gross order value before refunds; use order status to select completed revenue.",
897
+ });
898
+ const savedQuery = await ensureDemoSavedQuery(client, connectionId);
899
+ const queryResult = await client.runQuery(connectionId, {
900
+ query: DEMO_VALIDATION_SQL,
901
+ row_limit: 1,
902
+ timeout: 30,
903
+ });
904
+ const completedOrderCount = Number(queryResult?.rows?.[0]?.[0]);
905
+ const totalRevenue = Number(queryResult?.rows?.[0]?.[1]);
906
+ if (completedOrderCount !== 11 || totalRevenue !== 12200) {
907
+ throw new Error(
908
+ `Demo verification returned an unexpected result (${completedOrderCount} orders, ${totalRevenue} revenue). Run \`answerlayer local demo\` to retry.`,
909
+ );
910
+ }
911
+
912
+ return {
913
+ status: "ready",
914
+ version: LOCAL_DEMO_VERSION,
915
+ connectionId,
916
+ savedQueryId: String(savedQuery.id),
917
+ semantic: {
918
+ entityIds: entities.map(item => String(item.id)),
919
+ relationshipId: String(relationship.id),
920
+ dimensionIds: dimensions.map(item => String(item.id)),
921
+ measureId: String(measure.id),
922
+ },
923
+ validation: {
924
+ completedOrderCount,
925
+ totalRevenue: totalRevenue.toFixed(2),
926
+ },
927
+ questions: LOCAL_DEMO_QUESTIONS,
928
+ };
929
+ }
930
+
931
+ async function ensureDemoConnection(client, demoPassword) {
932
+ const connections = await client.listConnections();
933
+ const existing = Array.isArray(connections)
934
+ ? connections.find(item => item.name === LOCAL_DEMO_CONNECTION_NAME)
935
+ : null;
936
+ if (existing) {
937
+ if (existing.db_type !== "postgresql") {
938
+ throw new Error(`The reserved connection name "${LOCAL_DEMO_CONNECTION_NAME}" is already used by a non-PostgreSQL connection.`);
939
+ }
940
+ const config = existing.config || {};
941
+ const ownsDemoDatabase = config.pg_host === "postgres"
942
+ && Number(config.pg_port) === 5432
943
+ && config.db_name === LOCAL_DEMO_DATABASE
944
+ && config.pg_username === LOCAL_DEMO_USER;
945
+ if (!ownsDemoDatabase) {
946
+ throw new Error(
947
+ `The reserved connection name "${LOCAL_DEMO_CONNECTION_NAME}" is already used by a different PostgreSQL database. Rename or remove that connection, then rerun \`answerlayer local demo\`.`,
948
+ );
949
+ }
950
+ return existing;
951
+ }
952
+
953
+ return client.request("POST", "/api/v1/connections/", {
954
+ body: {
955
+ name: LOCAL_DEMO_CONNECTION_NAME,
956
+ description: `Versioned synthetic retail data for local onboarding (${LOCAL_DEMO_VERSION}).`,
957
+ db_type: "postgresql",
958
+ config: {
959
+ host: "postgres",
960
+ port: 5432,
961
+ database_name: LOCAL_DEMO_DATABASE,
962
+ username: LOCAL_DEMO_USER,
963
+ password: demoPassword,
964
+ },
965
+ auto_pii_detection: false,
966
+ },
967
+ });
968
+ }
969
+
970
+ async function ensureSemanticResource(client, resource, connectionId, name, payload) {
971
+ const pathName = `/api/v1/semantic/${resource}`;
972
+ const result = await client.request("GET", pathName, { query: { connection_id: connectionId } });
973
+ const items = Array.isArray(result?.[resource]) ? result[resource] : [];
974
+ const existing = items.find(item => item.name === name);
975
+ if (existing) return existing;
976
+ return client.request("POST", pathName, {
977
+ query: { connection_id: connectionId },
978
+ body: payload,
979
+ });
980
+ }
981
+
982
+ async function ensureDemoSavedQuery(client, connectionId) {
983
+ const result = await client.listSavedQueries();
984
+ const items = Array.isArray(result?.saved_queries) ? result.saved_queries : [];
985
+ const existing = items.find(item => item.name === LOCAL_DEMO_SAVED_QUERY_NAME && String(item.connection_id) === connectionId);
986
+ if (existing) return existing;
987
+ return client.createSavedQuery({
988
+ name: LOCAL_DEMO_SAVED_QUERY_NAME,
989
+ description: "Completed order revenue grouped by month and customer region.",
990
+ visibility: "org",
991
+ sql: DEMO_SAVED_QUERY_SQL,
992
+ connection_id: connectionId,
993
+ });
994
+ }
995
+
996
+ function demoSeedSql(password) {
997
+ const passwordLiteral = `'${password.replaceAll("'", "''")}'`;
998
+ return `\\set ON_ERROR_STOP on
999
+ DO $role$
1000
+ BEGIN
1001
+ IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${LOCAL_DEMO_USER}') THEN
1002
+ CREATE ROLE ${LOCAL_DEMO_USER} LOGIN PASSWORD ${passwordLiteral};
1003
+ ELSE
1004
+ ALTER ROLE ${LOCAL_DEMO_USER} LOGIN PASSWORD ${passwordLiteral};
1005
+ END IF;
1006
+ END
1007
+ $role$;
1008
+
1009
+ SELECT 'CREATE DATABASE ${LOCAL_DEMO_DATABASE} OWNER answerlayer'
1010
+ WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = '${LOCAL_DEMO_DATABASE}')\\gexec
1011
+
1012
+ REVOKE ALL ON DATABASE ${LOCAL_DEMO_DATABASE} FROM PUBLIC;
1013
+ GRANT CONNECT ON DATABASE ${LOCAL_DEMO_DATABASE} TO ${LOCAL_DEMO_USER};
1014
+
1015
+ \\connect ${LOCAL_DEMO_DATABASE}
1016
+
1017
+ REVOKE CREATE ON SCHEMA public FROM PUBLIC;
1018
+ CREATE SCHEMA IF NOT EXISTS demo AUTHORIZATION answerlayer;
1019
+ REVOKE ALL ON SCHEMA demo FROM PUBLIC;
1020
+
1021
+ CREATE TABLE IF NOT EXISTS demo.bootstrap_versions (
1022
+ version text PRIMARY KEY,
1023
+ installed_at timestamptz NOT NULL DEFAULT now()
1024
+ );
1025
+
1026
+ CREATE TABLE IF NOT EXISTS demo.customers (
1027
+ id integer PRIMARY KEY,
1028
+ name text NOT NULL,
1029
+ region text NOT NULL,
1030
+ segment text NOT NULL,
1031
+ signup_date date NOT NULL
1032
+ );
1033
+
1034
+ CREATE TABLE IF NOT EXISTS demo.orders (
1035
+ id integer PRIMARY KEY,
1036
+ customer_id integer NOT NULL REFERENCES demo.customers(id),
1037
+ order_date date NOT NULL,
1038
+ product text NOT NULL,
1039
+ category text NOT NULL,
1040
+ quantity integer NOT NULL CHECK (quantity > 0),
1041
+ unit_price numeric(12, 2) NOT NULL CHECK (unit_price >= 0),
1042
+ status text NOT NULL CHECK (status IN ('completed', 'refunded'))
1043
+ );
1044
+
1045
+ DO $seed$
1046
+ BEGIN
1047
+ IF NOT EXISTS (SELECT 1 FROM demo.bootstrap_versions WHERE version = '${LOCAL_DEMO_VERSION}') THEN
1048
+ DELETE FROM demo.orders;
1049
+ DELETE FROM demo.customers;
1050
+ INSERT INTO demo.customers (id, name, region, segment, signup_date) VALUES
1051
+ (1, 'Maple & Co', 'North', 'SMB', '2025-10-12'),
1052
+ (2, 'Harbour Goods', 'South', 'Mid-market', '2025-11-03'),
1053
+ (3, 'Summit Systems', 'East', 'Enterprise', '2025-11-18'),
1054
+ (4, 'Cedar Studio', 'West', 'SMB', '2025-12-01'),
1055
+ (5, 'Northstar Labs', 'North', 'Enterprise', '2025-12-09'),
1056
+ (6, 'Lakeside Market', 'South', 'SMB', '2025-12-21');
1057
+ INSERT INTO demo.orders (id, customer_id, order_date, product, category, quantity, unit_price, status) VALUES
1058
+ (1, 1, '2026-01-05', 'Analytics seats', 'Subscription', 10, 50.00, 'completed'),
1059
+ (2, 2, '2026-01-08', 'Data connectors', 'Platform', 2, 900.00, 'completed'),
1060
+ (3, 3, '2026-01-12', 'Analytics seats', 'Subscription', 25, 50.00, 'completed'),
1061
+ (4, 4, '2026-01-20', 'Onboarding', 'Services', 1, 750.00, 'completed'),
1062
+ (5, 1, '2026-02-02', 'Analytics seats', 'Subscription', 12, 50.00, 'completed'),
1063
+ (6, 5, '2026-02-10', 'Data connectors', 'Platform', 3, 900.00, 'completed'),
1064
+ (7, 6, '2026-02-14', 'Onboarding', 'Services', 1, 750.00, 'completed'),
1065
+ (8, 3, '2026-02-22', 'Data connectors', 'Platform', 1, 900.00, 'refunded'),
1066
+ (9, 2, '2026-03-03', 'Analytics seats', 'Subscription', 18, 50.00, 'completed'),
1067
+ (10, 4, '2026-03-08', 'Data connectors', 'Platform', 2, 900.00, 'completed'),
1068
+ (11, 5, '2026-03-15', 'Onboarding', 'Services', 1, 750.00, 'completed'),
1069
+ (12, 6, '2026-03-25', 'Analytics seats', 'Subscription', 8, 50.00, 'completed');
1070
+ INSERT INTO demo.bootstrap_versions (version) VALUES ('${LOCAL_DEMO_VERSION}');
1071
+ END IF;
1072
+ END
1073
+ $seed$;
1074
+
1075
+ GRANT USAGE ON SCHEMA demo TO ${LOCAL_DEMO_USER};
1076
+ GRANT SELECT ON ALL TABLES IN SCHEMA demo TO ${LOCAL_DEMO_USER};
1077
+ ALTER DEFAULT PRIVILEGES IN SCHEMA demo GRANT SELECT ON TABLES TO ${LOCAL_DEMO_USER};
1078
+ `;
1079
+ }
1080
+
1081
+ const DEMO_VALIDATION_SQL = `
1082
+ SELECT
1083
+ count(*)::integer AS completed_order_count,
1084
+ round(sum(quantity * unit_price), 2) AS total_revenue
1085
+ FROM demo.orders
1086
+ WHERE status = 'completed'
1087
+ `.trim();
1088
+
1089
+ const DEMO_SAVED_QUERY_SQL = `
1090
+ SELECT
1091
+ date_trunc('month', o.order_date)::date AS month,
1092
+ c.region,
1093
+ round(sum(o.quantity * o.unit_price), 2) AS revenue
1094
+ FROM demo.orders AS o
1095
+ JOIN demo.customers AS c ON c.id = o.customer_id
1096
+ WHERE o.status = 'completed'
1097
+ GROUP BY 1, 2
1098
+ ORDER BY 1, 2
1099
+ `.trim();
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
+
475
1120
  function firstValue(value) {
476
1121
  return Array.isArray(value) ? value[0] : value;
477
1122
  }