@answerlayer/cli 0.1.7 → 0.1.9

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,30 +97,50 @@ 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
- Set the model-provider key privately, then let the CLI prepare the stack and
101
- configure itself:
100
+ Initialize and start the local runtime:
102
101
 
103
102
  ```bash
104
- read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
105
- answerlayer local up
103
+ answerlayer local init
104
+ answerlayer local start
106
105
  ```
107
106
 
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:
107
+ `local init` selects the CLI's supported public image by default. Use
108
+ `--image <tag-or-digest>` to select a different published version and `--port`
109
+ to change the local port. The CLI:
111
110
 
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
111
+ 1. Verifies Docker, its architecture and version, the port, and available disk.
112
+ 2. Pulls the public AnswerLayer image and pins its resolved immutable digest.
113
+ 3. Generates permission-restricted Compose, state, and secret files in the
114
+ platform application-data directory.
115
+ 4. Starts Postgres, runs migrations, and waits for AnswerLayer readiness.
116
+ 5. Creates a local-only organization and scoped key, verifies the key, and
116
117
  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
+ 6. Leaves you ready to connect a dedicated, read-only database user and test a
118
119
  small, approved schema first.
119
120
 
120
- The local stack never needs a hosted AnswerLayer account. The skill requires
121
- agent confirmation before it starts containers, creates a connection, or sends
122
- queries to a real database, and it instructs agents not to print or persist
123
- database passwords.
121
+ The local stack does not require a hosted AnswerLayer account, a source checkout,
122
+ private registry credentials, or a model-provider key for first boot. Add an
123
+ optional provider key later only when using features that call that provider.
124
+ The skill requires agent confirmation before it starts containers, creates a
125
+ connection, or sends queries to a real database, and it instructs agents not to
126
+ print or persist database passwords.
127
+
128
+ Inspect and manage the lifecycle with:
129
+
130
+ ```bash
131
+ answerlayer local status [--json]
132
+ answerlayer local logs [--follow] [answerlayer|migrate|postgres]
133
+ answerlayer local stop # preserves Postgres data
134
+ answerlayer local upgrade # moves to this CLI's supported default
135
+ answerlayer local upgrade --image <tag> # selects an explicit release
136
+ answerlayer local reset --force # permanently deletes local data
137
+ ```
138
+
139
+ The selected tag and resolved digest are recorded in `state.json` and displayed
140
+ by `local status`. Set `ANSWERLAYER_LOCAL_DIR` to override the application-data
141
+ directory or `ANSWERLAYER_LOCAL_IMAGE` to override the default image.
142
+ Each runtime directory receives stable, isolated Compose project, volume, and
143
+ network names, so stopping or resetting one runtime cannot affect another.
124
144
 
125
145
  Useful scopes:
126
146
 
@@ -138,7 +158,11 @@ Useful scopes:
138
158
  ```bash
139
159
  answerlayer health
140
160
  answerlayer openapi --output openapi.json
141
- answerlayer local up
161
+ answerlayer local init
162
+ answerlayer local start
163
+ answerlayer local status
164
+ answerlayer local logs
165
+ answerlayer local stop
142
166
 
143
167
  answerlayer connections list
144
168
  answerlayer connections get <connection-id>
@@ -163,12 +187,16 @@ answerlayer inquiry models
163
187
  answerlayer inquiry ask --connection <connection-id> --model claude-opus-4-6 "Investigate unusual revenue changes"
164
188
 
165
189
  answerlayer evals suites create --name "Revenue checks" --connection <connection-id>
166
- answerlayer evals cases create <suite-id> --title "Monthly revenue" --question "What was revenue last month?" --expected-sql "select sum(amount) from orders where ..."
190
+ answerlayer evals cases create <suite-id> --title "Monthly revenue" --question "What was revenue last month?" --category Revenue --expected-sql "select sum(amount) from orders where ..."
167
191
  answerlayer evals runs create <suite-id> --label "Before prompt change"
168
192
  answerlayer evals runs create <suite-id> --case <case-id> --case <case-id> --label "Focused smoke run"
193
+ answerlayer evals runs create <suite-id> --category Revenue --category Finance --case <case-id> --label "Focused category run"
169
194
  answerlayer evals runs create <suite-id> --model claude-opus-4-6 --label "Model comparison"
195
+ answerlayer evals runs create <suite-id> --concurrency 4 --label "Parallel smoke run"
196
+ answerlayer evals runs create-batch --suite <suite-id> --suite <suite-id> --concurrency 4 --label "Release candidate"
170
197
  answerlayer evals runs update <run-id> --label "Prompt experiment B"
171
198
  answerlayer evals runs compare <run-id> --baseline <baseline-run-id>
199
+ answerlayer evals runs analyze <run-id> --json
172
200
 
173
201
  answerlayer dashboards create --title "Executive overview" --visibility org
174
202
  answerlayer tiles create --title "Revenue" --source-type saved_query --source <saved-query-id>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@answerlayer/cli",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -30,26 +30,28 @@ already available in the Codex skills directory.
30
30
  npm install -g @answerlayer/cli
31
31
  ```
32
32
 
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:
33
+ 2. After confirmation, initialize the repository-free local runtime:
35
34
 
36
35
  ```bash
37
- read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
36
+ answerlayer local init
38
37
  ```
39
38
 
40
- 3. After confirmation, run the complete local setup:
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:
41
45
 
42
46
  ```bash
43
- answerlayer local up
47
+ answerlayer local start
44
48
  ```
45
49
 
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.
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
53
+ `answerlayer local logs` to inspect progress. `local stop` preserves data;
54
+ `local reset --force` is the explicit destructive reset.
53
55
 
54
56
  4. Before connecting real data, require a dedicated database account that is
55
57
  restricted to approved schemas and `SELECT` only. Show the proposed
@@ -147,7 +149,7 @@ to see exact flags before using one:
147
149
  - `saved-queries` — list / get / create / execute reusable queries
148
150
  - `semantic` — entities, relationships, measures, metrics, dimensions, filters
149
151
  (most need `--connection <id>`)
150
- - `evals` — create evaluation suites and cases, run them, and compare runs
152
+ - `evals` — create evaluation suites and cases, run them, compare runs, and retrieve evidence-backed failure analysis
151
153
  - `dashboards`, `tiles` — build and read dashboards
152
154
  - `documents` — upload business-context docs and link them to connections
153
155
  - `connections` — create / test / inspect schema
package/src/cli.js CHANGED
@@ -5,7 +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
+ import { handleLocal } from "./local.js";
9
9
 
10
10
  const SEMANTIC_RESOURCES = new Set([
11
11
  "entities",
@@ -38,8 +38,7 @@ export async function main(argv, io) {
38
38
  }
39
39
 
40
40
  if (group === "local") {
41
- if (command !== "up") throw usage("Expected `answerlayer local up`");
42
- return localUp(parsed, io);
41
+ return handleLocal(command, parsed, io);
43
42
  }
44
43
 
45
44
  const { baseUrl, apiKey } = resolveAuth(parsed.flags, io.env);
@@ -679,11 +678,33 @@ async function handleEvals(client, resource, positionals, parsed, io) {
679
678
  use_semantic_layer: semanticLayerMode(parsed.flags),
680
679
  baseline_run_id: firstValue(parsed.flags.baseline),
681
680
  case_ids: optionalCsvOrRepeated(parsed.flags.case),
681
+ categories: optionalDistinctRepeated(parsed.flags.category),
682
+ case_concurrency: firstValue(parsed.flags.concurrency),
682
683
  });
683
684
  requirePayloadValue(payload, "suite_id", "evals runs create requires a suite id or --suite");
685
+ normalizeEvalCaseConcurrency(payload);
684
686
  return requestAndPrint(client, "POST", `${base}/runs`, parsed, io, { body: payload });
685
687
  }
686
688
 
689
+ if (command === "create-batch") {
690
+ const selectedSuites = csvOrRepeated([
691
+ ...rest,
692
+ ...allValues(parsed.flags.suite),
693
+ ]);
694
+ const payload = await readData(parsed.flags, io, {
695
+ suite_ids: selectedSuites.length > 0 ? selectedSuites : undefined,
696
+ label: firstValue(parsed.flags.label),
697
+ model: firstValue(parsed.flags.model),
698
+ use_semantic_layer: semanticLayerMode(parsed.flags),
699
+ case_concurrency: firstValue(parsed.flags.concurrency),
700
+ });
701
+ requireEvalBatchSuites(payload.suite_ids);
702
+ normalizeEvalCaseConcurrency(payload);
703
+ return requestAndPrint(client, "POST", `${base}/runs/batch`, parsed, io, {
704
+ body: payload,
705
+ });
706
+ }
707
+
687
708
  const runId = requirePositional(rest, 0, "eval run id");
688
709
  if (command === "get") {
689
710
  return requestAndPrint(client, "GET", `${base}/runs/${encodeURIComponent(runId)}`, parsed, io, {
@@ -705,6 +726,9 @@ async function handleEvals(client, resource, positionals, parsed, io) {
705
726
  query: { baseline_run_id: firstValue(parsed.flags.baseline) },
706
727
  });
707
728
  }
729
+ if (command === "analyze" || command === "analysis") {
730
+ return requestAndPrint(client, "GET", `${base}/runs/${encodeURIComponent(runId)}/analysis`, parsed, io);
731
+ }
708
732
  throw usage(`Unknown evals runs command: ${command}`);
709
733
  }
710
734
 
@@ -1140,6 +1164,7 @@ function evalCasePayload(flags) {
1140
1164
  return {
1141
1165
  title: firstValue(flags.title),
1142
1166
  question: firstValue(flags.question),
1167
+ category: firstValue(flags.category),
1143
1168
  expected_answer: firstValue(flags.expectedAnswer),
1144
1169
  expected_sql: firstValue(flags.expectedSql) || firstValue(flags.sql),
1145
1170
  expected_values: parseJsonFlag(firstValue(flags.expectedValues), "expected-values"),
@@ -1425,6 +1450,7 @@ function normalizeFlagName(rawName) {
1425
1450
  "--baseline-run": "baseline",
1426
1451
  "--case": "case",
1427
1452
  "--case-id": "case",
1453
+ "--category": "category",
1428
1454
  "--expected-answer": "expectedAnswer",
1429
1455
  "--expected-sql": "expectedSql",
1430
1456
  "--expected-values": "expectedValues",
@@ -1444,14 +1470,13 @@ function normalizeFlagName(rawName) {
1444
1470
  "--relationship-type": "relationshipType",
1445
1471
  "--join": "join",
1446
1472
  "--form": "form",
1447
- "--stack-dir": "stackDir",
1448
1473
  };
1449
1474
 
1450
1475
  return aliases[rawName] || rawName.replace(/^-+/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
1451
1476
  }
1452
1477
 
1453
1478
  function isBooleanFlag(rawName) {
1454
- return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force", "--active", "--inactive", "--include-inactive", "--include-semantic-snapshot", "--use-semantic-layer", "--no-semantic-layer"].includes(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);
1455
1480
  }
1456
1481
 
1457
1482
  function setFlag(flags, name, value) {
@@ -1483,6 +1508,18 @@ function parseNumber(value, name) {
1483
1508
  return parsed;
1484
1509
  }
1485
1510
 
1511
+ function parseBoundedInteger(value, name, minimum, maximum) {
1512
+ if (value === undefined || value === "") return undefined;
1513
+ if (typeof value !== "string" && typeof value !== "number") {
1514
+ throw usage(`Expected --${name} to be an integer from ${minimum} to ${maximum}`);
1515
+ }
1516
+ const parsed = Number(value);
1517
+ if (!Number.isInteger(parsed) || parsed < minimum || parsed > maximum) {
1518
+ throw usage(`Expected --${name} to be an integer from ${minimum} to ${maximum}`);
1519
+ }
1520
+ return parsed;
1521
+ }
1522
+
1486
1523
  function requirePositional(positionals, index, label) {
1487
1524
  const value = positionals[index];
1488
1525
  if (!value) throw usage(`Missing ${label}`);
@@ -1497,6 +1534,25 @@ function requirePayloadValue(payload, key, message) {
1497
1534
  if (!payload[key]) throw usage(message);
1498
1535
  }
1499
1536
 
1537
+ function requireEvalBatchSuites(suiteIds) {
1538
+ if (!Array.isArray(suiteIds) || suiteIds.length < 2 || suiteIds.length > 20) {
1539
+ throw usage("evals runs create-batch requires 2 to 20 suite ids");
1540
+ }
1541
+ if (new Set(suiteIds.map(String)).size !== suiteIds.length) {
1542
+ throw usage("evals runs create-batch requires distinct suite ids");
1543
+ }
1544
+ }
1545
+
1546
+ function normalizeEvalCaseConcurrency(payload) {
1547
+ if (payload.case_concurrency === undefined) return;
1548
+ payload.case_concurrency = parseBoundedInteger(
1549
+ payload.case_concurrency,
1550
+ "concurrency",
1551
+ 1,
1552
+ 8,
1553
+ );
1554
+ }
1555
+
1500
1556
  function csvOrRepeated(value) {
1501
1557
  const values = allValues(value);
1502
1558
  return values.flatMap((item) => String(item).split(",").map((part) => part.trim()).filter(Boolean));
@@ -1506,6 +1562,14 @@ function optionalCsvOrRepeated(value) {
1506
1562
  return value === undefined ? undefined : csvOrRepeated(value);
1507
1563
  }
1508
1564
 
1565
+ function optionalDistinctRepeated(value) {
1566
+ if (value === undefined) return undefined;
1567
+ const values = allValues(value)
1568
+ .map((item) => String(item).trim())
1569
+ .filter(Boolean);
1570
+ return [...new Set(values)];
1571
+ }
1572
+
1509
1573
  function firstValue(value) {
1510
1574
  return Array.isArray(value) ? value[0] : value;
1511
1575
  }
@@ -1549,7 +1613,10 @@ function helpText() {
1549
1613
 
1550
1614
  Usage:
1551
1615
  answerlayer skills install [--path <directory>] [--force]
1552
- answerlayer local up [--stack-dir <directory>]
1616
+ answerlayer local init [--image <image>] [--port <port>]
1617
+ answerlayer local start|status|logs|stop
1618
+ answerlayer local upgrade [--image <image>]
1619
+ answerlayer local reset --force
1553
1620
  answerlayer init --api-key <key> [--base-url <url>]
1554
1621
  answerlayer configure --base-url <url> --api-key <key>
1555
1622
  answerlayer health
@@ -1568,9 +1635,15 @@ Data products:
1568
1635
  answerlayer inquiry models|ask|sessions|create-session|session|update-session|delete-session|turn
1569
1636
  answerlayer evals suites list|create|get|update|delete
1570
1637
  answerlayer evals cases create|update|delete
1571
- answerlayer evals runs list|create|get|update|cancel|compare
1572
- create accepts --case <case-id> (repeat or comma-separate), and
1638
+ answerlayer evals runs list|create|create-batch|get|update|cancel|compare|analyze
1639
+ case create/update accept --category <name>
1640
+ run create accepts --case <case-id> (repeat or comma-separate) and
1641
+ --category <name> (repeat; category and case selectors are unioned),
1642
+ --concurrency <1-8> (default 3; 1 is serial), and
1573
1643
  --use-semantic-layer or --no-semantic-layer
1644
+ create-batch accepts 2 to 20 suite ids as positionals or repeatable
1645
+ --suite values, plus shared --label, --model, --concurrency <1-8>,
1646
+ and --use-semantic-layer or --no-semantic-layer
1574
1647
  update accepts --label <name>
1575
1648
  answerlayer generation start|list|get|status|stream|cancel|questions|guidance|delete
1576
1649
  answerlayer tiles list|get|create|update|data|delete
package/src/local.js CHANGED
@@ -1,148 +1,412 @@
1
1
  import crypto from "node:crypto";
2
2
  import fs from "node:fs";
3
+ import net from "node:net";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
5
6
  import { spawnSync } from "node:child_process";
6
7
  import { AnswerLayerClient } from "./client.js";
7
- import { readConfig, writeConfig } from "./config.js";
8
+ import { defaultConfigPath, readConfig, writeConfig } from "./config.js";
8
9
 
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
- ];
10
+ export const DEFAULT_LOCAL_IMAGE = "public.ecr.aws/s8d9x7y7/answerlayer:1.19.9";
11
+ const DEFAULT_PORT = 8000;
12
+ const MINIMUM_FREE_BYTES = 2 * 1024 * 1024 * 1024;
13
+
14
+ export async function handleLocal(command, parsed, io) {
15
+ if (command === "init") return localInit(parsed, io);
16
+ if (command === "start" || command === "up") return localStart(parsed, io);
17
+ if (command === "status") return localStatus(parsed, io);
18
+ if (command === "logs") return localLogs(parsed, io);
19
+ if (command === "stop") return localStop(parsed, io);
20
+ if (command === "upgrade") return localUpgrade(parsed, io);
21
+ if (command === "reset") return localReset(parsed, io);
22
+ throw new Error("Expected `answerlayer local init|start|status|logs|stop|upgrade|reset`");
23
+ }
17
24
 
18
25
  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;
26
+ return localStart(parsed, io);
27
+ }
22
28
 
23
- requireCommand(run, "git", ["--version"]);
24
- requireCommand(run, "docker", ["compose", "version"]);
29
+ async function localInit(parsed, io) {
30
+ const runtime = await ensureInitialized(parsed, io);
31
+ printRuntimeSummary(runtime, io, "Local AnswerLayer is initialized.");
32
+ write(io.stdout, "Next: answerlayer local start\n");
33
+ }
34
+
35
+ async function localStart(parsed, io) {
36
+ const run = io.runCommand || runCommand;
37
+ const runtime = await ensureInitialized(parsed, io);
38
+ const before = inspectStatus(runtime, run);
25
39
 
26
- const stackExists = fs.existsSync(stackDir);
27
- if (!fs.existsSync(envPath) && !io.env.ANTHROPIC_API_KEY) {
40
+ if (before.status === "stopped" && !(await portIsAvailable(runtime.state.port, io))) {
28
41
  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.",
42
+ `Port ${runtime.state.port} is already in use. Stop the process using it or choose another port with --port <port>.`,
30
43
  );
31
44
  }
32
45
 
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]);
46
+ write(io.stdout, `Starting AnswerLayer ${runtime.state.resolvedImage}...\n`);
47
+ try {
48
+ checked(run, "docker", [...composeArgs(runtime), "up", "--detach", "--wait", "--wait-timeout", "180"]);
49
+ } catch (error) {
50
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
51
+ const hint = status.status === "failed"
52
+ ? " Inspect `answerlayer local logs` for the migration or application error."
53
+ : " Check Docker Desktop/Engine and retry.";
54
+ throw new Error(`Local stack failed to start: ${error.message}.${hint}`);
37
55
  }
38
- validateCheckout(stackDir, run);
39
56
 
40
- if (!fs.existsSync(envPath)) {
41
- prepareEnvironment(stackDir, io.env.ANTHROPIC_API_KEY);
42
- write(io.stdout, `Created ${envPath} with permissions 0600\n`);
43
- }
57
+ const baseUrl = `http://127.0.0.1:${runtime.state.port}`;
58
+ await waitUntilReady(baseUrl, io);
59
+ const configPath = await ensureLocalCredentials(runtime, baseUrl, io);
60
+ const state = { ...runtime.state, lastStatus: "ready", updatedAt: new Date().toISOString() };
61
+ writeState(runtime.statePath, state);
44
62
 
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);
63
+ printRuntimeSummary({ ...runtime, state }, io, "Local AnswerLayer is ready.");
64
+ write(io.stdout, `CLI config: ${configPath}\n`);
65
+ write(io.stdout, "Next: answerlayer connections list\n");
66
+ }
55
67
 
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) };
68
+ async function localUpgrade(parsed, io) {
69
+ const image = firstValue(parsed.flags.image) || io.env.ANSWERLAYER_LOCAL_IMAGE || DEFAULT_LOCAL_IMAGE;
70
+ write(io.stdout, `Upgrading the local runtime to ${image}...\n`);
71
+ return localStart({ ...parsed, flags: { ...parsed.flags, image, forcePull: true } }, io);
72
+ }
59
73
 
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);
74
+ async function localStatus(parsed, io) {
75
+ const run = io.runCommand || runCommand;
76
+ const runtime = loadRuntime(parsed, io);
77
+ requireCommand(run, "docker", ["compose", "version"]);
78
+ const status = inspectStatus(runtime, run, { tolerateFailure: true });
79
+ const result = {
80
+ status: status.status,
81
+ url: `http://127.0.0.1:${runtime.state.port}`,
82
+ image: runtime.state.requestedImage,
83
+ resolvedImage: runtime.state.resolvedImage,
84
+ runtimeDirectory: runtime.directory,
85
+ services: status.services,
86
+ };
65
87
 
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}`);
88
+ if (parsed.flags.json) {
89
+ write(io.stdout, `${JSON.stringify(result, null, 2)}\n`);
90
+ return;
71
91
  }
92
+ write(io.stdout, `Status: ${result.status}\n`);
93
+ write(io.stdout, `URL: ${result.url}\n`);
94
+ write(io.stdout, `Image: ${result.resolvedImage}\n`);
95
+ write(io.stdout, `Runtime config: ${result.runtimeDirectory}\n`);
96
+ }
72
97
 
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");
98
+ async function localLogs(parsed, io) {
99
+ const run = io.runCommand || runCommand;
100
+ const runtime = loadRuntime(parsed, io);
101
+ requireCommand(run, "docker", ["compose", "version"]);
102
+ const args = [...composeArgs(runtime), "logs"];
103
+ if (parsed.flags.follow) args.push("--follow");
104
+ args.push("--tail", String(firstValue(parsed.flags.tail) || 100));
105
+ const service = parsed.positionals[2];
106
+ if (service) args.push(service);
107
+ checked(run, "docker", args, { passthrough: true });
75
108
  }
76
109
 
77
- function prepareEnvironment(stackDir, anthropicApiKey) {
78
- const examplePath = path.join(stackDir, ".env.example");
79
- if (!fs.existsSync(examplePath)) throw new Error(`Missing ${examplePath}`);
110
+ async function localStop(parsed, io) {
111
+ const run = io.runCommand || runCommand;
112
+ const runtime = loadRuntime(parsed, io);
113
+ requireCommand(run, "docker", ["compose", "version"]);
114
+ checked(run, "docker", [...composeArgs(runtime), "down"], { passthrough: true });
115
+ writeState(runtime.statePath, { ...runtime.state, lastStatus: "stopped", updatedAt: new Date().toISOString() });
116
+ write(io.stdout, "Local AnswerLayer stopped. Persistent data was preserved.\n");
117
+ write(io.stdout, "Resume with: answerlayer local start\n");
118
+ }
80
119
 
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`);
120
+ async function localReset(parsed, io) {
121
+ if (!parsed.flags.force) {
122
+ throw new Error(
123
+ "Reset permanently deletes the local AnswerLayer database. Rerun with `answerlayer local reset --force` to confirm.",
124
+ );
125
+ }
126
+ const run = io.runCommand || runCommand;
127
+ const runtime = loadRuntime(parsed, io);
128
+ requireCommand(run, "docker", ["compose", "version"]);
129
+ checked(run, "docker", [...composeArgs(runtime), "down", "--volumes", "--remove-orphans"], { passthrough: true });
130
+ writeState(runtime.statePath, { ...runtime.state, lastStatus: "stopped", resetAt: new Date().toISOString() });
131
+ write(io.stdout, "Deleted the local AnswerLayer database volume. Runtime configuration was preserved.\n");
132
+ write(io.stdout, "Create a fresh database with: answerlayer local start\n");
133
+ }
134
+
135
+ async function ensureInitialized(parsed, io) {
136
+ const run = io.runCommand || runCommand;
137
+ const runtime = runtimePaths(parsed, io);
138
+ fs.mkdirSync(runtime.directory, { recursive: true, mode: 0o700 });
139
+
140
+ preflight(run, runtime.directory, io);
141
+
142
+ const existingState = readState(runtime.statePath);
143
+ const explicitImage = firstValue(parsed.flags.image) || io.env.ANSWERLAYER_LOCAL_IMAGE;
144
+ const requestedImage = explicitImage || existingState?.requestedImage || DEFAULT_LOCAL_IMAGE;
145
+ const port = parsePort(firstValue(parsed.flags.port) || existingState?.port || DEFAULT_PORT);
146
+ const needsPull = parsed.flags.forcePull
147
+ || !existingState?.resolvedImage
148
+ || requestedImage !== existingState.requestedImage;
149
+
150
+ let resolvedImage = existingState?.resolvedImage;
151
+ if (needsPull) {
152
+ write(io.stdout, `Pulling ${requestedImage} from the public registry...\n`);
153
+ try {
154
+ checked(run, "docker", ["pull", requestedImage]);
155
+ resolvedImage = resolveDigest(run, requestedImage);
156
+ } catch (error) {
157
+ throw new Error(
158
+ `Could not pull the public AnswerLayer image ${requestedImage}: ${error.message}. Check network access and the image version, then retry.`,
159
+ );
93
160
  }
94
- contents = contents.replace(pattern, () => `${name}=${value}`);
95
161
  }
96
- const envPath = path.join(stackDir, ".env");
97
- fs.writeFileSync(envPath, contents, { encoding: "utf8", mode: 0o600 });
98
- fs.chmodSync(envPath, 0o600);
162
+
163
+ const state = {
164
+ schemaVersion: 1,
165
+ requestedImage,
166
+ resolvedImage,
167
+ port,
168
+ ...runtimeResourceNames(runtime.directory),
169
+ createdAt: existingState?.createdAt || new Date().toISOString(),
170
+ updatedAt: new Date().toISOString(),
171
+ lastStatus: existingState?.lastStatus || "stopped",
172
+ };
173
+
174
+ writeCompose(runtime.composePath);
175
+ writeEnvironment(runtime.envPath, state);
176
+ writeState(runtime.statePath, state);
177
+ return { ...runtime, state };
99
178
  }
100
179
 
101
- function validateCheckout(stackDir, run) {
102
- if (!fs.existsSync(path.join(stackDir, ".git"))) {
103
- throw new Error(`${stackDir} is not a Git checkout`);
180
+ function preflight(run, directory, io) {
181
+ requireCommand(run, "docker", ["compose", "version"]);
182
+ const dockerVersion = checked(run, "docker", ["version", "--format", "{{.Server.Version}}"]).stdout.trim();
183
+ requireMinimumVersion(dockerVersion, [20, 10], "Docker Engine");
184
+ const composeVersion = checked(run, "docker", ["compose", "version", "--short"]).stdout.trim();
185
+ requireMinimumVersion(composeVersion, [2, 20], "Docker Compose");
186
+
187
+ const engine = checked(run, "docker", ["info", "--format", "{{.OSType}}/{{.Architecture}}"]).stdout.trim();
188
+ if (!/^linux\/(amd64|x86_64|arm64|aarch64)$/.test(engine)) {
189
+ throw new Error(`Unsupported Docker platform ${engine || "unknown"}. AnswerLayer supports linux/amd64 and linux/arm64 containers.`);
190
+ }
191
+
192
+ const availableBytes = io.availableBytes ?? freeBytes(directory);
193
+ if (availableBytes < MINIMUM_FREE_BYTES) {
194
+ throw new Error("AnswerLayer local setup requires at least 2 GB of free disk space for images and persistent data.");
104
195
  }
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}`);
196
+ }
197
+
198
+ function requireMinimumVersion(raw, minimum, label) {
199
+ const match = String(raw).match(/(\d+)\.(\d+)(?:\.(\d+))?/);
200
+ if (!match) throw new Error(`Could not determine ${label} version from ${raw || "empty output"}`);
201
+ const current = match.slice(1, 4).map(value => Number.parseInt(value || "0", 10));
202
+ for (let index = 0; index < minimum.length; index += 1) {
203
+ if (current[index] > minimum[index]) return;
204
+ if (current[index] < minimum[index]) {
205
+ throw new Error(`${label} ${minimum.join(".")} or newer is required; found ${raw}`);
108
206
  }
109
207
  }
208
+ }
110
209
 
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`);
210
+ function resolveDigest(run, requestedImage) {
211
+ const inspected = checked(
212
+ run,
213
+ "docker",
214
+ ["image", "inspect", "--format", "{{json .RepoDigests}}", requestedImage],
215
+ ).stdout.trim();
216
+ let digests;
217
+ try {
218
+ digests = JSON.parse(inspected);
219
+ } catch {
220
+ throw new Error("Docker did not return parseable image digest metadata");
114
221
  }
222
+ const repository = imageRepository(requestedImage);
223
+ const resolved = digests.find(item => String(item).startsWith(`${repository}@sha256:`));
224
+ if (!resolved) throw new Error("Docker did not return an immutable digest for the pulled image");
225
+ return resolved;
226
+ }
227
+
228
+ function imageRepository(image) {
229
+ const withoutDigest = String(image).split("@")[0];
230
+ const slash = withoutDigest.lastIndexOf("/");
231
+ const colon = withoutDigest.lastIndexOf(":");
232
+ return colon > slash ? withoutDigest.slice(0, colon) : withoutDigest;
115
233
  }
116
234
 
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");
235
+ async function ensureLocalCredentials(runtime, baseUrl, io) {
236
+ const existing = readConfig(io.env);
237
+ const fetchImpl = io.fetch || globalThis.fetch;
238
+ if (existing.baseUrl === baseUrl && existing.apiKey) {
239
+ const client = new AnswerLayerClient({ baseUrl, apiKey: existing.apiKey, fetchImpl });
240
+ try {
241
+ await client.rawRequest("GET", "/api/v1/auth/me");
242
+ return defaultConfigPath(io.env);
243
+ } catch {
244
+ // The database may have been reset. Bootstrap a replacement local key.
245
+ }
246
+ }
247
+
248
+ write(io.stdout, "Creating a local-only CLI identity...\n");
249
+ const run = io.runCommand || runCommand;
250
+ let bootstrap;
251
+ try {
252
+ bootstrap = checked(run, "docker", [
253
+ ...composeArgs(runtime),
254
+ "exec", "-T", "answerlayer", "python", "-m", "app.scripts.bootstrap_local",
255
+ ]);
256
+ } catch (error) {
257
+ throw new Error(`Local credential bootstrap failed: ${error.message}. Run \`answerlayer local logs answerlayer\` for details.`);
126
258
  }
127
- const host = publishedAddress[1] === "[::1]" ? "[::1]" : "127.0.0.1";
128
- return `http://${host}:${port}`;
259
+ const credentials = { baseUrl, apiKey: parseBootstrapApiKey(bootstrap.stdout) };
260
+ const configPath = writeConfig({ ...existing, ...credentials }, io.env);
261
+ const client = new AnswerLayerClient({ ...credentials, fetchImpl });
262
+ try {
263
+ await client.rawRequest("GET", "/api/v1/auth/me");
264
+ } catch (error) {
265
+ throw new Error(`Saved local credentials to ${configPath}, but verification failed: ${error.message}`);
266
+ }
267
+ return configPath;
129
268
  }
130
269
 
131
- async function waitUntilHealthy(baseUrl, io) {
270
+ async function waitUntilReady(baseUrl, io) {
132
271
  const fetchImpl = io.fetch || globalThis.fetch;
133
- const sleep = io.sleep || ((milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds)));
272
+ const sleep = io.sleep || (milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)));
134
273
  const attempts = io.healthAttempts || 60;
135
-
136
274
  for (let attempt = 0; attempt < attempts; attempt += 1) {
137
275
  try {
138
- const response = await fetchImpl(`${baseUrl}/healthz`);
276
+ const response = await fetchImpl(`${baseUrl}/readyz`);
139
277
  if (response.ok) return;
140
278
  } catch {
141
- // The container may still be starting.
279
+ // Docker may have reported healthy just before the host port was reachable.
142
280
  }
143
281
  await sleep(2000);
144
282
  }
145
- throw new Error(`Local stack did not become healthy at ${baseUrl}/healthz`);
283
+ throw new Error(`AnswerLayer did not become ready at ${baseUrl}/readyz. Run \`answerlayer local logs\` for details.`);
284
+ }
285
+
286
+ function inspectStatus(runtime, run, options = {}) {
287
+ const result = run("docker", [...composeArgs(runtime), "ps", "--all", "--format", "json"], { capture: true });
288
+ if (result.error || result.status !== 0) {
289
+ if (options.tolerateFailure) return { status: "failed", services: [] };
290
+ throw new Error("Could not inspect the local Docker Compose stack");
291
+ }
292
+ const services = parseComposePs(result.stdout);
293
+ const migrate = services.find(service => String(service.Service).toLowerCase() === "migrate");
294
+ const app = services.find(service => String(service.Service).toLowerCase() === "answerlayer");
295
+ const state = value => String(value || "").toLowerCase();
296
+
297
+ if ([migrate, app].some(service => service && (state(service.Health) === "unhealthy" || (state(service.State) === "exited" && Number(service.ExitCode) !== 0)))) {
298
+ return { status: "failed", services };
299
+ }
300
+ if (migrate && state(migrate.State) === "running") return { status: "migrating", services };
301
+ if (app && state(app.State) === "running" && state(app.Health) === "healthy") return { status: "ready", services };
302
+ if (app && state(app.State) === "running") return { status: "starting", services };
303
+ return { status: "stopped", services };
304
+ }
305
+
306
+ function parseComposePs(stdout) {
307
+ const raw = String(stdout || "").trim();
308
+ if (!raw) return [];
309
+ try {
310
+ const parsed = JSON.parse(raw);
311
+ return Array.isArray(parsed) ? parsed : [parsed];
312
+ } catch {
313
+ return raw.split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
314
+ }
315
+ }
316
+
317
+ function loadRuntime(parsed, io) {
318
+ const runtime = runtimePaths(parsed, io);
319
+ const state = readState(runtime.statePath);
320
+ if (!state || !fs.existsSync(runtime.composePath) || !fs.existsSync(runtime.envPath)) {
321
+ throw new Error("Local AnswerLayer is not initialized. Run `answerlayer local init` first.");
322
+ }
323
+ return { ...runtime, state };
324
+ }
325
+
326
+ function runtimePaths(parsed, io) {
327
+ const directory = path.resolve(
328
+ firstValue(parsed.flags.runtimeDir)
329
+ || io.env.ANSWERLAYER_LOCAL_DIR
330
+ || defaultRuntimeDirectory(io.env, io.platform || process.platform),
331
+ );
332
+ return {
333
+ directory,
334
+ composePath: path.join(directory, "compose.yaml"),
335
+ envPath: path.join(directory, "runtime.env"),
336
+ statePath: path.join(directory, "state.json"),
337
+ };
338
+ }
339
+
340
+ function defaultRuntimeDirectory(env, platform) {
341
+ const home = env.HOME || os.homedir();
342
+ if (platform === "darwin") return path.join(home, "Library", "Application Support", "AnswerLayer", "local");
343
+ if (platform === "win32") return path.join(env.LOCALAPPDATA || path.join(home, "AppData", "Local"), "AnswerLayer", "local");
344
+ return path.join(env.XDG_DATA_HOME || path.join(home, ".local", "share"), "answerlayer", "local");
345
+ }
346
+
347
+ function writeCompose(composePath) {
348
+ fs.writeFileSync(composePath, `${COMPOSE_FILE}\n`, { encoding: "utf8", mode: 0o600 });
349
+ fs.chmodSync(composePath, 0o600);
350
+ }
351
+
352
+ function writeEnvironment(envPath, state) {
353
+ const existing = readEnvironment(envPath);
354
+ const values = {
355
+ ANSWERLAYER_IMAGE: state.resolvedImage,
356
+ ANSWERLAYER_POSTGRES_PASSWORD: existing.ANSWERLAYER_POSTGRES_PASSWORD || crypto.randomBytes(24).toString("hex"),
357
+ ANSWERLAYER_ENCRYPTION_KEY: existing.ANSWERLAYER_ENCRYPTION_KEY || crypto.randomBytes(32).toString("hex"),
358
+ ANSWERLAYER_PORT: String(state.port),
359
+ ANSWERLAYER_LOG_LEVEL: existing.ANSWERLAYER_LOG_LEVEL || "INFO",
360
+ ANSWERLAYER_WEB_CONCURRENCY: existing.ANSWERLAYER_WEB_CONCURRENCY || "1",
361
+ ANSWERLAYER_ANTHROPIC_API_KEY: existing.ANSWERLAYER_ANTHROPIC_API_KEY || "",
362
+ ANSWERLAYER_POSTGRES_VOLUME: state.postgresVolume,
363
+ ANSWERLAYER_NETWORK: state.networkName,
364
+ };
365
+ const contents = Object.entries(values).map(([name, value]) => `${name}=${value}`).join("\n");
366
+ fs.writeFileSync(envPath, `${contents}\n`, { encoding: "utf8", mode: 0o600 });
367
+ fs.chmodSync(envPath, 0o600);
368
+ }
369
+
370
+ function readEnvironment(envPath) {
371
+ if (!fs.existsSync(envPath)) return {};
372
+ return Object.fromEntries(
373
+ fs.readFileSync(envPath, "utf8").split(/\r?\n/).filter(line => line && !line.startsWith("#")).map(line => {
374
+ const separator = line.indexOf("=");
375
+ return [line.slice(0, separator), line.slice(separator + 1)];
376
+ }),
377
+ );
378
+ }
379
+
380
+ function readState(statePath) {
381
+ if (!fs.existsSync(statePath)) return null;
382
+ try {
383
+ return JSON.parse(fs.readFileSync(statePath, "utf8"));
384
+ } catch (error) {
385
+ throw new Error(`Invalid local runtime state at ${statePath}: ${error.message}`);
386
+ }
387
+ }
388
+
389
+ function writeState(statePath, state) {
390
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
391
+ fs.chmodSync(statePath, 0o600);
392
+ }
393
+
394
+ function composeArgs(runtime) {
395
+ return [
396
+ "compose", "--project-name", runtime.state.projectName,
397
+ "--file", runtime.composePath,
398
+ "--env-file", runtime.envPath,
399
+ ];
400
+ }
401
+
402
+ function runtimeResourceNames(directory) {
403
+ const id = crypto.createHash("sha256").update(path.resolve(directory)).digest("hex").slice(0, 12);
404
+ return {
405
+ runtimeId: id,
406
+ projectName: `answerlayer-local-${id}`,
407
+ postgresVolume: `answerlayer-local-${id}-postgres-data`,
408
+ networkName: `answerlayer-local-${id}-network`,
409
+ };
146
410
  }
147
411
 
148
412
  function parseBootstrapApiKey(stdout) {
@@ -152,31 +416,62 @@ function parseBootstrapApiKey(stdout) {
152
416
  return match[1];
153
417
  }
154
418
 
419
+ function parsePort(value) {
420
+ const port = Number(value);
421
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
422
+ throw new Error(`Expected --port to be an integer from 1 to 65535; received ${value}`);
423
+ }
424
+ return port;
425
+ }
426
+
427
+ function freeBytes(directory) {
428
+ const stats = fs.statfsSync(directory);
429
+ return Number(stats.bavail) * Number(stats.bsize);
430
+ }
431
+
432
+ function portIsAvailable(port, io) {
433
+ if (io.portIsAvailable) return Promise.resolve(io.portIsAvailable(port));
434
+ return new Promise(resolve => {
435
+ const server = net.createServer();
436
+ server.unref();
437
+ server.once("error", () => resolve(false));
438
+ server.listen({ host: "127.0.0.1", port }, () => server.close(() => resolve(true)));
439
+ });
440
+ }
441
+
155
442
  function requireCommand(run, command, args) {
156
443
  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`);
444
+ if (result.error?.code === "ENOENT" || result.status !== 0) {
445
+ throw new Error(`${command} is required for local setup and must be running`);
446
+ }
159
447
  }
160
448
 
161
449
  function checked(run, command, args, options = {}) {
162
- const result = run(command, args, { capture: !options.passthrough, cwd: options.cwd });
450
+ const result = run(command, args, { capture: !options.passthrough });
163
451
  if (result.error) throw result.error;
164
452
  if (result.status !== 0) {
165
- const detail = String(result.stderr || "").trim();
453
+ const detail = String(result.stderr || result.stdout || "").trim();
166
454
  throw new Error(`${command} ${args.join(" ")} failed${detail ? `: ${detail}` : ""}`);
167
455
  }
168
- return result;
456
+ return { ...result, stdout: String(result.stdout || "") };
169
457
  }
170
458
 
171
459
  function runCommand(command, args, options = {}) {
172
460
  return spawnSync(command, args, {
173
- cwd: options.cwd,
174
461
  encoding: options.capture ? "utf8" : undefined,
175
462
  stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit",
176
463
  maxBuffer: 50 * 1024 * 1024,
177
464
  });
178
465
  }
179
466
 
467
+ function printRuntimeSummary(runtime, io, heading) {
468
+ write(io.stdout, `${heading}\n`);
469
+ write(io.stdout, `URL: http://127.0.0.1:${runtime.state.port}\n`);
470
+ write(io.stdout, `Image: ${runtime.state.requestedImage}\n`);
471
+ write(io.stdout, `Resolved image: ${runtime.state.resolvedImage}\n`);
472
+ write(io.stdout, `Runtime config: ${runtime.directory}\n`);
473
+ }
474
+
180
475
  function firstValue(value) {
181
476
  return Array.isArray(value) ? value[0] : value;
182
477
  }
@@ -184,3 +479,84 @@ function firstValue(value) {
184
479
  function write(stream, text) {
185
480
  stream.write(text);
186
481
  }
482
+
483
+ const COMPOSE_FILE = [
484
+ "name: answerlayer-local",
485
+ "",
486
+ "x-answerlayer-database-environment: &answerlayer-database-environment",
487
+ " DB_HOST: postgres",
488
+ " DB_PORT: \"5432\"",
489
+ " DB_USER: answerlayer",
490
+ " DB_PASSWORD: ${ANSWERLAYER_POSTGRES_PASSWORD:?Set ANSWERLAYER_POSTGRES_PASSWORD}",
491
+ " DB_NAME: answerlayer",
492
+ "",
493
+ "services:",
494
+ " postgres:",
495
+ " image: postgres:14",
496
+ " environment:",
497
+ " POSTGRES_USER: answerlayer",
498
+ " POSTGRES_PASSWORD: ${ANSWERLAYER_POSTGRES_PASSWORD:?Set ANSWERLAYER_POSTGRES_PASSWORD}",
499
+ " POSTGRES_DB: answerlayer",
500
+ " volumes:",
501
+ " - postgres-data:/var/lib/postgresql/data",
502
+ " healthcheck:",
503
+ " test: [\"CMD-SHELL\", \"pg_isready -U answerlayer -d answerlayer\"]",
504
+ " interval: 5s",
505
+ " timeout: 5s",
506
+ " retries: 12",
507
+ " restart: unless-stopped",
508
+ " networks: [internal]",
509
+ "",
510
+ " migrate:",
511
+ " image: ${ANSWERLAYER_IMAGE:?Set ANSWERLAYER_IMAGE}",
512
+ " command: [\"alembic\", \"upgrade\", \"head\"]",
513
+ " environment:",
514
+ " <<: *answerlayer-database-environment",
515
+ " depends_on:",
516
+ " postgres:",
517
+ " condition: service_healthy",
518
+ " restart: \"no\"",
519
+ " networks: [internal]",
520
+ "",
521
+ " answerlayer:",
522
+ " image: ${ANSWERLAYER_IMAGE:?Set ANSWERLAYER_IMAGE}",
523
+ " environment:",
524
+ " <<: *answerlayer-database-environment",
525
+ " ENVIRONMENT: development",
526
+ " LOG_LEVEL: ${ANSWERLAYER_LOG_LEVEL:-INFO}",
527
+ " WEB_CONCURRENCY: ${ANSWERLAYER_WEB_CONCURRENCY:-1}",
528
+ " ENCRYPTION_KEY: ${ANSWERLAYER_ENCRYPTION_KEY:?Set ANSWERLAYER_ENCRYPTION_KEY}",
529
+ " ANTHROPIC_API_KEY: ${ANSWERLAYER_ANTHROPIC_API_KEY:-}",
530
+ " ALLOW_INTERNAL_AUTH: \"true\"",
531
+ " LOCAL_BOOTSTRAP_ENABLED: \"true\"",
532
+ " DEBUG_ENDPOINTS_ENABLED: \"false\"",
533
+ " EVAL_WORKER_ENABLED: \"false\"",
534
+ " RESULT_GC_INTERVAL_SECONDS: \"0\"",
535
+ " TELEMETRY_PUSH_INTERVAL_SECONDS: \"0\"",
536
+ " METER_SYNC_INTERVAL_SECONDS: \"0\"",
537
+ " FRONTEND_BASE_URL: http://127.0.0.1:${ANSWERLAYER_PORT:-8000}",
538
+ " CORS_ORIGINS: http://127.0.0.1:${ANSWERLAYER_PORT:-8000},http://localhost:${ANSWERLAYER_PORT:-8000}",
539
+ " ports:",
540
+ " - \"127.0.0.1:${ANSWERLAYER_PORT:-8000}:8000\"",
541
+ " depends_on:",
542
+ " postgres:",
543
+ " condition: service_healthy",
544
+ " migrate:",
545
+ " condition: service_completed_successfully",
546
+ " healthcheck:",
547
+ " test: [\"CMD\", \"curl\", \"--fail\", \"http://localhost:8000/readyz\"]",
548
+ " interval: 5s",
549
+ " timeout: 5s",
550
+ " start_period: 10s",
551
+ " retries: 12",
552
+ " restart: unless-stopped",
553
+ " networks: [internal]",
554
+ "",
555
+ "volumes:",
556
+ " postgres-data:",
557
+ " name: ${ANSWERLAYER_POSTGRES_VOLUME:-answerlayer-local-postgres-data}",
558
+ "",
559
+ "networks:",
560
+ " internal:",
561
+ " name: ${ANSWERLAYER_NETWORK:-answerlayer-local-network}",
562
+ ].join("\n");