@answerlayer/cli 0.1.2 → 0.1.4

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,15 +97,25 @@ 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
- The flow is:
100
+ Set the model-provider key privately, then let the CLI prepare the stack and
101
+ configure itself:
101
102
 
102
- 1. Install the CLI/plugin.
103
- 2. Clone and start the local `answerlayer-core` Docker stack.
104
- 3. Run `make local-bootstrap` in that stack to create a local-only organization
105
- and scoped CLI key.
106
- 4. Configure the CLI for `http://localhost:8000` with the printed command.
107
- 5. Connect a dedicated, read-only database user and test a small, approved
108
- schema first.
103
+ ```bash
104
+ read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
105
+ answerlayer local up
106
+ ```
107
+
108
+ Use `--stack-dir <directory>` to reuse a different core checkout. If that
109
+ checkout already has a `.env`, the provider key does not need to be exported.
110
+ The command:
111
+
112
+ 1. Verifies Git and Docker and clones `answerlayer-core` when needed.
113
+ 2. Creates a permission-restricted `.env` and generates its encryption key.
114
+ 3. Starts Docker Compose and waits for the API to become healthy.
115
+ 4. Creates a local-only organization and scoped key, verifies the key, and
116
+ saves the CLI configuration without printing the key.
117
+ 5. Leaves you ready to connect a dedicated, read-only database user and test a
118
+ small, approved schema first.
109
119
 
110
120
  The local stack never needs a hosted AnswerLayer account. The skill requires
111
121
  agent confirmation before it starts containers, creates a connection, or sends
@@ -120,13 +130,15 @@ Useful scopes:
120
130
  - `saved_query:read`, `saved_query:execute`, and `saved_query:write` for saved-query workflows
121
131
  - `semantic:read`, `semantic:write`, and `semantic:generate` for semantic-layer workflows
122
132
  - `dashboard:read`, `dashboard:write`, `tile:read`, and `tile:write` for dashboard workflows
123
- - `inquiry:execute` for natural-language inquiry
133
+ - `inquiry:read` to inspect inquiry sessions and evaluation suites/runs
134
+ - `inquiry:execute` for natural-language inquiry and to manage/run evaluations
124
135
 
125
136
  ## Commands
126
137
 
127
138
  ```bash
128
139
  answerlayer health
129
140
  answerlayer openapi --output openapi.json
141
+ answerlayer local up
130
142
 
131
143
  answerlayer connections list
132
144
  answerlayer connections get <connection-id>
@@ -148,6 +160,11 @@ answerlayer semantic metrics generate --connection <connection-id> --prompt "Saa
148
160
  answerlayer inquiry ask --connection <connection-id> "What changed in revenue this month?"
149
161
  answerlayer inquiry ask --session <session-id> "Break that down by region"
150
162
 
163
+ answerlayer evals suites create --name "Revenue checks" --connection <connection-id>
164
+ answerlayer evals cases create <suite-id> --title "Monthly revenue" --question "What was revenue last month?" --expected-sql "select sum(amount) from orders where ..."
165
+ answerlayer evals runs create <suite-id> --label "Before prompt change"
166
+ answerlayer evals runs compare <run-id> --baseline <baseline-run-id>
167
+
151
168
  answerlayer dashboards create --title "Executive overview" --visibility org
152
169
  answerlayer tiles create --title "Revenue" --source-type saved_query --source <saved-query-id>
153
170
  answerlayer dashboards attach-tile <dashboard-id> --tile <tile-id> --x 0 --y 0 --w 6 --h 4
@@ -171,7 +188,7 @@ answerlayer branding update --data-file ./branding.json
171
188
  ## Command groups
172
189
 
173
190
  - Core: `api-keys`, `connections`, `metadata`, `query`, `query-results`
174
- - Data products: `saved-queries`, `semantic`, `inquiry`, `generation`, `tiles`, `dashboards`
191
+ - Data products: `saved-queries`, `semantic`, `inquiry`, `evals`, `generation`, `tiles`, `dashboards`
175
192
  - Supporting resources: `documents`, `branding`, `uploads`, `chains`, `users`, `org`, `roles`, `billing`, `stats`
176
193
 
177
194
  ## Development
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@answerlayer/cli",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -30,44 +30,34 @@ already available in the Codex skills directory.
30
30
  npm install -g @answerlayer/cli
31
31
  ```
32
32
 
33
- 2. Clone the core stack beside the user's work and prepare its environment:
33
+ 2. Ask the user to set their Anthropic key privately in their own terminal. Do
34
+ not ask them to paste it into chat or put it in shell history:
34
35
 
35
36
  ```bash
36
- git clone https://github.com/AnswerLayer/answerlayer-core.git
37
- cd answerlayer-core
38
- cp .env.example .env
37
+ read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
39
38
  ```
40
39
 
41
- Ask the user to supply a real `ANTHROPIC_API_KEY` and a strong local
42
- `ENCRYPTION_KEY` in `.env`. Do not print, echo, or add either value to a
43
- command transcript. Clerk and Stripe placeholders are not needed for the
44
- local API-key workflow.
45
-
46
- 3. After confirmation, start the local stack and wait for its health endpoint:
47
-
48
- ```bash
49
- docker compose up --build -d
50
- curl --fail http://localhost:8000/healthz
51
- ```
52
-
53
- 4. After confirmation, create the local-only organization and CLI key:
40
+ 3. After confirmation, run the complete local setup:
54
41
 
55
42
  ```bash
56
- make local-bootstrap
43
+ answerlayer local up
57
44
  ```
58
45
 
59
- The command rotates any previous `local-cli-bootstrap` key and prints an
60
- `answerlayer init --base-url http://localhost:8000 --api-key ...` command.
61
- Have the user run that printed command in their terminal. Never copy the key
62
- into chat, source control, logs, or a shell command you display back to them.
46
+ This verifies Git and Docker, clones the core stack to
47
+ `~/.answerlayer/core` when needed, creates a permission-restricted `.env`
48
+ with a generated encryption key, starts Docker Compose, waits for health,
49
+ creates the local identity and scoped key, verifies it, and configures the
50
+ CLI. It captures the one-time key rather than printing it. Use
51
+ `--stack-dir <directory>` to reuse a different core checkout; when that
52
+ checkout already has a `.env`, `ANTHROPIC_API_KEY` need not be exported.
63
53
 
64
- 5. Before connecting real data, require a dedicated database account that is
54
+ 4. Before connecting real data, require a dedicated database account that is
65
55
  restricted to approved schemas and `SELECT` only. Show the proposed
66
56
  connection host, database, and username, then get confirmation before
67
57
  running `connections create` or any query. Put the password only in a local,
68
58
  permission-restricted JSON file; never print it or commit it.
69
59
 
70
- 6. Start with a small approved schema and read-only inspection. Confirm before
60
+ 5. Start with a small approved schema and read-only inspection. Confirm before
71
61
  creating connections, generating semantic objects, or executing queries.
72
62
 
73
63
  This workflow is for Docker Compose development only. Do not run
@@ -157,6 +147,7 @@ to see exact flags before using one:
157
147
  - `saved-queries` — list / get / create / execute reusable queries
158
148
  - `semantic` — entities, relationships, measures, metrics, dimensions, filters
159
149
  (most need `--connection <id>`)
150
+ - `evals` — create evaluation suites and cases, run them, and compare runs
160
151
  - `dashboards`, `tiles` — build and read dashboards
161
152
  - `documents` — upload business-context docs and link them to connections
162
153
  - `connections` — create / test / inspect schema
package/src/cli.js CHANGED
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { AnswerLayerClient } from "./client.js";
6
6
  import { formatJson, formatList, formatQueryResult } from "./format.js";
7
7
  import { DEFAULT_BASE_URL, readConfig, resolveAuth, writeConfig } from "./config.js";
8
+ import { localUp } from "./local.js";
8
9
 
9
10
  const SEMANTIC_RESOURCES = new Set([
10
11
  "entities",
@@ -36,6 +37,11 @@ export async function main(argv, io) {
36
37
  return initialize(parsed, io);
37
38
  }
38
39
 
40
+ if (group === "local") {
41
+ if (command !== "up") throw usage("Expected `answerlayer local up`");
42
+ return localUp(parsed, io);
43
+ }
44
+
39
45
  const { baseUrl, apiKey } = resolveAuth(parsed.flags, io.env);
40
46
  const client = new AnswerLayerClient({ baseUrl, apiKey });
41
47
 
@@ -50,6 +56,7 @@ export async function main(argv, io) {
50
56
  if (group === "saved-queries" || group === "saved") return handleSavedQueries(client, command, positionals, parsed, io);
51
57
  if (group === "semantic") return handleSemantic(client, command, positionals, parsed, io);
52
58
  if (group === "inquiry") return handleInquiry(client, command, positionals, parsed, io);
59
+ if (group === "evals" || group === "evaluations") return handleEvals(client, command, positionals, parsed, io);
53
60
  if (group === "generation") return handleGeneration(client, command, positionals, parsed, io);
54
61
  if (group === "tiles") return handleTiles(client, command, positionals, parsed, io);
55
62
  if (group === "dashboards") return handleDashboards(client, command, positionals, parsed, io);
@@ -566,6 +573,119 @@ async function handleInquiry(client, command, positionals, parsed, io) {
566
573
  throw usage(`Unknown inquiry command: ${command}`);
567
574
  }
568
575
 
576
+ async function handleEvals(client, resource, positionals, parsed, io) {
577
+ const [command, ...rest] = positionals;
578
+ const base = "/api/v1/evals";
579
+
580
+ if (resource === "suites" || resource === "suite") {
581
+ if (command === "list" || !command) {
582
+ return requestAndPrint(client, "GET", `${base}/suites`, parsed, io, {
583
+ query: {
584
+ connection_id: firstValue(parsed.flags.connection),
585
+ include_inactive: parsed.flags.includeInactive || undefined,
586
+ },
587
+ table: [
588
+ { key: "id", label: "ID" },
589
+ { key: "name", label: "Name" },
590
+ { key: "connection_id", label: "Connection" },
591
+ { key: "version", label: "Version" },
592
+ { key: "case_count", label: "Cases" },
593
+ { key: "is_active", label: "Active" },
594
+ ],
595
+ });
596
+ }
597
+
598
+ if (command === "create") {
599
+ const payload = await readData(parsed.flags, io, {
600
+ name: firstValue(parsed.flags.name),
601
+ connection_id: firstValue(parsed.flags.connection),
602
+ description: firstValue(parsed.flags.description),
603
+ });
604
+ requirePayloadValue(payload, "name", "evals suites create requires --name");
605
+ requirePayloadValue(payload, "connection_id", "evals suites create requires --connection");
606
+ return requestAndPrint(client, "POST", `${base}/suites`, parsed, io, { body: payload });
607
+ }
608
+
609
+ const suiteId = requirePositional(rest, 0, "eval suite id");
610
+ if (command === "get") return requestAndPrint(client, "GET", `${base}/suites/${encodeURIComponent(suiteId)}`, parsed, io);
611
+ if (command === "update") {
612
+ return requestAndPrint(client, "PATCH", `${base}/suites/${encodeURIComponent(suiteId)}`, parsed, io, {
613
+ body: await readData(parsed.flags, io, {
614
+ name: firstValue(parsed.flags.name),
615
+ description: firstValue(parsed.flags.description),
616
+ is_active: activeFlag(parsed.flags),
617
+ }),
618
+ });
619
+ }
620
+ if (command === "delete") return requestAndPrint(client, "DELETE", `${base}/suites/${encodeURIComponent(suiteId)}`, parsed, io);
621
+ throw usage(`Unknown evals suites command: ${command}`);
622
+ }
623
+
624
+ if (resource === "cases" || resource === "case") {
625
+ if (command === "create") {
626
+ const suiteId = firstValue(parsed.flags.suite) || requirePositional(rest, 0, "eval suite id");
627
+ return requestAndPrint(client, "POST", `${base}/suites/${encodeURIComponent(suiteId)}/cases`, parsed, io, {
628
+ body: await readData(parsed.flags, io, evalCasePayload(parsed.flags)),
629
+ });
630
+ }
631
+
632
+ const caseId = requirePositional(rest, 0, "eval case id");
633
+ if (command === "update") {
634
+ return requestAndPrint(client, "PATCH", `${base}/cases/${encodeURIComponent(caseId)}`, parsed, io, {
635
+ body: await readData(parsed.flags, io, { ...evalCasePayload(parsed.flags), is_active: activeFlag(parsed.flags) }),
636
+ });
637
+ }
638
+ if (command === "delete") return requestAndPrint(client, "DELETE", `${base}/cases/${encodeURIComponent(caseId)}`, parsed, io);
639
+ throw usage(`Unknown evals cases command: ${command}`);
640
+ }
641
+
642
+ if (resource === "runs" || resource === "run") {
643
+ if (command === "list" || !command) {
644
+ return requestAndPrint(client, "GET", `${base}/runs`, parsed, io, {
645
+ query: {
646
+ suite_id: firstValue(parsed.flags.suite),
647
+ limit: firstValue(parsed.flags.limit),
648
+ offset: firstValue(parsed.flags.offset),
649
+ },
650
+ table: [
651
+ { key: "id", label: "ID" },
652
+ { key: "suite_id", label: "Suite" },
653
+ { key: "label", label: "Label" },
654
+ { key: "status", label: "Status" },
655
+ { key: "suite_version", label: "Version" },
656
+ ],
657
+ });
658
+ }
659
+
660
+ if (command === "create") {
661
+ const payload = await readData(parsed.flags, io, {
662
+ suite_id: firstValue(parsed.flags.suite) || rest[0],
663
+ label: firstValue(parsed.flags.label),
664
+ model: firstValue(parsed.flags.model),
665
+ baseline_run_id: firstValue(parsed.flags.baseline),
666
+ });
667
+ requirePayloadValue(payload, "suite_id", "evals runs create requires a suite id or --suite");
668
+ return requestAndPrint(client, "POST", `${base}/runs`, parsed, io, { body: payload });
669
+ }
670
+
671
+ const runId = requirePositional(rest, 0, "eval run id");
672
+ if (command === "get") {
673
+ return requestAndPrint(client, "GET", `${base}/runs/${encodeURIComponent(runId)}`, parsed, io, {
674
+ query: { include_semantic_snapshot: parsed.flags.includeSemanticSnapshot || undefined },
675
+ });
676
+ }
677
+ if (command === "cancel") return requestAndPrint(client, "POST", `${base}/runs/${encodeURIComponent(runId)}/cancel`, parsed, io);
678
+ if (command === "compare") {
679
+ return requestAndPrint(client, "GET", `${base}/runs/${encodeURIComponent(runId)}/compare`, parsed, io, {
680
+ query: { baseline_run_id: firstValue(parsed.flags.baseline) },
681
+ });
682
+ }
683
+ throw usage(`Unknown evals runs command: ${command}`);
684
+ }
685
+
686
+ throw usage(`Expected evals resource: suites, cases, or runs`);
687
+ }
688
+
569
689
  async function handleGeneration(client, command, positionals, parsed, io) {
570
690
  const base = "/api/v1/semantic/jobs";
571
691
  if (command === "start" || command === "create") {
@@ -991,6 +1111,29 @@ function queryPayload(flags, sql) {
991
1111
  };
992
1112
  }
993
1113
 
1114
+ function evalCasePayload(flags) {
1115
+ return {
1116
+ title: firstValue(flags.title),
1117
+ question: firstValue(flags.question),
1118
+ expected_answer: firstValue(flags.expectedAnswer),
1119
+ expected_sql: firstValue(flags.expectedSql) || firstValue(flags.sql),
1120
+ expected_values: parseJsonFlag(firstValue(flags.expectedValues), "expected-values"),
1121
+ required_tools: optionalCsvOrRepeated(flags.requiredTool),
1122
+ forbidden_tools: optionalCsvOrRepeated(flags.forbiddenTool),
1123
+ tags: optionalCsvOrRepeated(flags.tag),
1124
+ evaluator_config: parseJsonFlag(firstValue(flags.evaluatorConfig), "evaluator-config"),
1125
+ numeric_tolerance: parseNumber(firstValue(flags.numericTolerance), "numeric-tolerance"),
1126
+ pass_threshold: parseNumber(firstValue(flags.passThreshold), "pass-threshold"),
1127
+ };
1128
+ }
1129
+
1130
+ function activeFlag(flags) {
1131
+ if (flags.active && flags.inactive) throw usage("Use only one of --active or --inactive");
1132
+ if (flags.active) return true;
1133
+ if (flags.inactive) return false;
1134
+ return undefined;
1135
+ }
1136
+
994
1137
  async function semanticPayload(resource, flags, positionals, io) {
995
1138
  const common = {
996
1139
  name: firstValue(flags.name) || positionals.join(" ") || undefined,
@@ -1238,19 +1381,38 @@ function normalizeFlagName(rawName) {
1238
1381
  "--summary": "summary",
1239
1382
  "--session": "session",
1240
1383
  "--question": "question",
1384
+ "--suite": "suite",
1385
+ "--suite-id": "suite",
1386
+ "--label": "label",
1387
+ "--baseline": "baseline",
1388
+ "--baseline-run": "baseline",
1389
+ "--expected-answer": "expectedAnswer",
1390
+ "--expected-sql": "expectedSql",
1391
+ "--expected-values": "expectedValues",
1392
+ "--required-tool": "requiredTool",
1393
+ "--forbidden-tool": "forbiddenTool",
1394
+ "--tag": "tag",
1395
+ "--evaluator-config": "evaluatorConfig",
1396
+ "--numeric-tolerance": "numericTolerance",
1397
+ "--pass-threshold": "passThreshold",
1398
+ "--active": "active",
1399
+ "--inactive": "inactive",
1400
+ "--include-inactive": "includeInactive",
1401
+ "--include-semantic-snapshot": "includeSemanticSnapshot",
1241
1402
  "--turn": "turn",
1242
1403
  "--from": "from",
1243
1404
  "--to": "to",
1244
1405
  "--relationship-type": "relationshipType",
1245
1406
  "--join": "join",
1246
1407
  "--form": "form",
1408
+ "--stack-dir": "stackDir",
1247
1409
  };
1248
1410
 
1249
1411
  return aliases[rawName] || rawName.replace(/^-+/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1250
1412
  }
1251
1413
 
1252
1414
  function isBooleanFlag(rawName) {
1253
- return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force"].includes(rawName);
1415
+ return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot"].includes(rawName);
1254
1416
  }
1255
1417
 
1256
1418
  function setFlag(flags, name, value) {
@@ -1275,6 +1437,13 @@ function parseInteger(value, fallback) {
1275
1437
  return parsed;
1276
1438
  }
1277
1439
 
1440
+ function parseNumber(value, name) {
1441
+ if (value === undefined || value === null || value === "") return undefined;
1442
+ const parsed = Number(value);
1443
+ if (!Number.isFinite(parsed)) throw usage(`Expected a number for --${name}, received ${value}`);
1444
+ return parsed;
1445
+ }
1446
+
1278
1447
  function requirePositional(positionals, index, label) {
1279
1448
  const value = positionals[index];
1280
1449
  if (!value) throw usage(`Missing ${label}`);
@@ -1294,6 +1463,10 @@ function csvOrRepeated(value) {
1294
1463
  return values.flatMap((item) => String(item).split(",").map((part) => part.trim()).filter(Boolean));
1295
1464
  }
1296
1465
 
1466
+ function optionalCsvOrRepeated(value) {
1467
+ return value === undefined ? undefined : csvOrRepeated(value);
1468
+ }
1469
+
1297
1470
  function firstValue(value) {
1298
1471
  return Array.isArray(value) ? value[0] : value;
1299
1472
  }
@@ -1337,6 +1510,7 @@ function helpText() {
1337
1510
 
1338
1511
  Usage:
1339
1512
  answerlayer skills install [--path <directory>] [--force]
1513
+ answerlayer local up [--stack-dir <directory>]
1340
1514
  answerlayer init --api-key <key> [--base-url <url>]
1341
1515
  answerlayer configure --base-url <url> --api-key <key>
1342
1516
  answerlayer health
@@ -1353,6 +1527,9 @@ Data products:
1353
1527
  answerlayer saved-queries list|get|create|update|delete|approve|unapprove|execute
1354
1528
  answerlayer semantic <entities|relationships|measures|metrics|dimensions|filters> list|get|create|update|delete|delete-all|generate
1355
1529
  answerlayer inquiry ask|sessions|create-session|session|update-session|delete-session|turn
1530
+ answerlayer evals suites list|create|get|update|delete
1531
+ answerlayer evals cases create|update|delete
1532
+ answerlayer evals runs list|create|get|cancel|compare
1356
1533
  answerlayer generation start|list|get|status|stream|cancel|questions|guidance|delete
1357
1534
  answerlayer tiles list|get|create|update|data|delete
1358
1535
  answerlayer dashboards list|get|create|update|delete|duplicate|manifest|attach-tile|move-tile|detach-tile|assignments|assign|unassign|tile-data
package/src/local.js ADDED
@@ -0,0 +1,186 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import { AnswerLayerClient } from "./client.js";
7
+ import { readConfig, writeConfig } from "./config.js";
8
+
9
+ const CORE_REPOSITORY = "https://github.com/AnswerLayer/answerlayer-core.git";
10
+ const CORE_REMOTE_PATTERN = /(?:^|@|\/\/)github\.com[:/]AnswerLayer\/answerlayer-core(?:\.git)?\/?$/i;
11
+ const REQUIRED_CORE_PATHS = [
12
+ "docker-compose.yml",
13
+ ".env.example",
14
+ "Makefile",
15
+ "backend/app/scripts/bootstrap_local.py",
16
+ ];
17
+
18
+ export async function localUp(parsed, io) {
19
+ const stackDir = path.resolve(firstValue(parsed.flags.stackDir) || path.join(os.homedir(), ".answerlayer", "core"));
20
+ const envPath = path.join(stackDir, ".env");
21
+ const run = io.runCommand || runCommand;
22
+
23
+ requireCommand(run, "git", ["--version"]);
24
+ requireCommand(run, "docker", ["compose", "version"]);
25
+
26
+ const stackExists = fs.existsSync(stackDir);
27
+ if (!fs.existsSync(envPath) && !io.env.ANTHROPIC_API_KEY) {
28
+ throw new Error(
29
+ "Set ANTHROPIC_API_KEY in your environment before the first `answerlayer local up`. It is written only to the local stack's permission-restricted .env file.",
30
+ );
31
+ }
32
+
33
+ if (!stackExists) {
34
+ fs.mkdirSync(path.dirname(stackDir), { recursive: true, mode: 0o700 });
35
+ write(io.stdout, `Cloning the AnswerLayer stack into ${stackDir}\n`);
36
+ checked(run, "git", ["clone", "--depth", "1", CORE_REPOSITORY, stackDir]);
37
+ }
38
+ validateCheckout(stackDir, run);
39
+
40
+ if (!fs.existsSync(envPath)) {
41
+ prepareEnvironment(stackDir, io.env.ANTHROPIC_API_KEY);
42
+ write(io.stdout, `Created ${envPath} with permissions 0600\n`);
43
+ }
44
+
45
+ write(io.stdout, "Starting the local AnswerLayer stack...\n");
46
+ checked(run, "docker", ["compose", "up", "--build", "-d"], { cwd: stackDir, passthrough: true });
47
+ const publishedPort = checked(
48
+ run,
49
+ "docker",
50
+ ["compose", "port", "answerlayer", "8000"],
51
+ { cwd: stackDir },
52
+ );
53
+ const baseUrl = parsePublishedBaseUrl(publishedPort.stdout);
54
+ await waitUntilHealthy(baseUrl, io);
55
+
56
+ write(io.stdout, "Creating a local CLI identity and rotating its scoped key...\n");
57
+ const bootstrap = checked(run, "make", ["local-bootstrap"], { cwd: stackDir });
58
+ const credentials = { baseUrl, apiKey: parseBootstrapApiKey(bootstrap.stdout) };
59
+
60
+ // Bootstrap rotates the previous key, so persist the replacement before any
61
+ // network verification that may fail transiently. This keeps the only valid
62
+ // credential recoverable for a retry.
63
+ const existing = readConfig(io.env);
64
+ const configPath = writeConfig({ ...existing, ...credentials }, io.env);
65
+
66
+ const client = new AnswerLayerClient({ ...credentials, fetchImpl: io.fetch || globalThis.fetch });
67
+ try {
68
+ await client.rawRequest("GET", "/api/v1/auth/me");
69
+ } catch (error) {
70
+ throw new Error(`Saved rotated local credentials to ${configPath}, but verification failed: ${error.message}`);
71
+ }
72
+
73
+ write(io.stdout, `Local AnswerLayer is ready. Verified credentials and saved config to ${configPath}\n`);
74
+ write(io.stdout, "Next: answerlayer connections list\n");
75
+ }
76
+
77
+ function prepareEnvironment(stackDir, anthropicApiKey) {
78
+ const examplePath = path.join(stackDir, ".env.example");
79
+ if (!fs.existsSync(examplePath)) throw new Error(`Missing ${examplePath}`);
80
+
81
+ if (/[\r\n]/.test(anthropicApiKey)) throw new Error("ANTHROPIC_API_KEY must not contain a newline");
82
+ const encryptionKey = crypto.randomBytes(32).toString("hex");
83
+ const template = fs.readFileSync(examplePath, "utf8");
84
+ const replacements = {
85
+ ANTHROPIC_API_KEY: anthropicApiKey,
86
+ ENCRYPTION_KEY: encryptionKey,
87
+ };
88
+ let contents = template;
89
+ for (const [name, value] of Object.entries(replacements)) {
90
+ const pattern = new RegExp(`^${name}=.*$`, "gm");
91
+ if ([...template.matchAll(pattern)].length !== 1) {
92
+ throw new Error(`${examplePath} must contain exactly one ${name}= entry`);
93
+ }
94
+ contents = contents.replace(pattern, () => `${name}=${value}`);
95
+ }
96
+ const envPath = path.join(stackDir, ".env");
97
+ fs.writeFileSync(envPath, contents, { encoding: "utf8", mode: 0o600 });
98
+ fs.chmodSync(envPath, 0o600);
99
+ }
100
+
101
+ function validateCheckout(stackDir, run) {
102
+ if (!fs.existsSync(path.join(stackDir, ".git"))) {
103
+ throw new Error(`${stackDir} is not a Git checkout`);
104
+ }
105
+ for (const relativePath of REQUIRED_CORE_PATHS) {
106
+ if (!fs.existsSync(path.join(stackDir, relativePath))) {
107
+ throw new Error(`${stackDir} is missing required AnswerLayer core file ${relativePath}`);
108
+ }
109
+ }
110
+
111
+ const remote = checked(run, "git", ["-C", stackDir, "remote", "get-url", "origin"]);
112
+ if (!CORE_REMOTE_PATTERN.test(String(remote.stdout).trim())) {
113
+ throw new Error(`${stackDir} does not use the official AnswerLayer core origin`);
114
+ }
115
+ }
116
+
117
+ function parsePublishedBaseUrl(stdout) {
118
+ const publishedAddress = String(stdout)
119
+ .split(/\r?\n/)
120
+ .map(line => line.trim())
121
+ .map(line => line.match(/^(0\.0\.0\.0|127\.0\.0\.1|localhost|\[::\]|\[::1\]|::):(\d+)$/))
122
+ .find(Boolean);
123
+ const port = publishedAddress ? Number.parseInt(publishedAddress[2], 10) : 0;
124
+ if (port < 1 || port > 65535) {
125
+ throw new Error("Docker Compose did not publish answerlayer port 8000 on a local host interface");
126
+ }
127
+ const host = publishedAddress[1] === "[::1]" ? "[::1]" : "127.0.0.1";
128
+ return `http://${host}:${port}`;
129
+ }
130
+
131
+ async function waitUntilHealthy(baseUrl, io) {
132
+ const fetchImpl = io.fetch || globalThis.fetch;
133
+ const sleep = io.sleep || ((milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds)));
134
+ const attempts = io.healthAttempts || 60;
135
+
136
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
137
+ try {
138
+ const response = await fetchImpl(`${baseUrl}/healthz`);
139
+ if (response.ok) return;
140
+ } catch {
141
+ // The container may still be starting.
142
+ }
143
+ await sleep(2000);
144
+ }
145
+ throw new Error(`Local stack did not become healthy at ${baseUrl}/healthz`);
146
+ }
147
+
148
+ function parseBootstrapApiKey(stdout) {
149
+ const initLine = String(stdout).split(/\r?\n/).find(line => /(?:^|\s)answerlayer\s+init(?:\s|$)/.test(line));
150
+ const match = initLine?.match(/(?:^|\s)--api-key(?:=|\s+)(\S+)/);
151
+ if (!match) throw new Error("Local bootstrap completed without returning CLI credentials");
152
+ return match[1];
153
+ }
154
+
155
+ function requireCommand(run, command, args) {
156
+ const result = run(command, args, { capture: true });
157
+ if (result.error?.code === "ENOENT") throw new Error(`${command} is required for local setup`);
158
+ if (result.status !== 0) throw new Error(`${command} is required for local setup`);
159
+ }
160
+
161
+ function checked(run, command, args, options = {}) {
162
+ const result = run(command, args, { capture: !options.passthrough, cwd: options.cwd });
163
+ if (result.error) throw result.error;
164
+ if (result.status !== 0) {
165
+ const detail = String(result.stderr || "").trim();
166
+ throw new Error(`${command} ${args.join(" ")} failed${detail ? `: ${detail}` : ""}`);
167
+ }
168
+ return result;
169
+ }
170
+
171
+ function runCommand(command, args, options = {}) {
172
+ return spawnSync(command, args, {
173
+ cwd: options.cwd,
174
+ encoding: options.capture ? "utf8" : undefined,
175
+ stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit",
176
+ maxBuffer: 50 * 1024 * 1024,
177
+ });
178
+ }
179
+
180
+ function firstValue(value) {
181
+ return Array.isArray(value) ? value[0] : value;
182
+ }
183
+
184
+ function write(stream, text) {
185
+ stream.write(text);
186
+ }