@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 +46 -18
- package/package.json +1 -1
- package/skills/answerlayer/SKILL.md +15 -13
- package/src/cli.js +81 -8
- package/src/local.js +478 -102
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
|
-
|
|
101
|
-
configure itself:
|
|
100
|
+
Initialize and start the local runtime:
|
|
102
101
|
|
|
103
102
|
```bash
|
|
104
|
-
|
|
105
|
-
answerlayer local
|
|
103
|
+
answerlayer local init
|
|
104
|
+
answerlayer local start
|
|
106
105
|
```
|
|
107
106
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
The
|
|
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
|
|
113
|
-
2.
|
|
114
|
-
3.
|
|
115
|
-
|
|
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
|
-
|
|
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
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
|
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
|
@@ -30,26 +30,28 @@ already available in the Codex skills directory.
|
|
|
30
30
|
npm install -g @answerlayer/cli
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
2.
|
|
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
|
-
|
|
36
|
+
answerlayer local init
|
|
38
37
|
```
|
|
39
38
|
|
|
40
|
-
|
|
39
|
+
This checks Docker, pulls the supported public AnswerLayer image, pins its
|
|
40
|
+
immutable digest, and generates permission-restricted runtime configuration
|
|
41
|
+
in the platform application-data directory. It does not require Git, a
|
|
42
|
+
source checkout, registry credentials, or a model-provider key.
|
|
43
|
+
|
|
44
|
+
3. After confirmation, start and configure the stack:
|
|
41
45
|
|
|
42
46
|
```bash
|
|
43
|
-
answerlayer local
|
|
47
|
+
answerlayer local start
|
|
44
48
|
```
|
|
45
49
|
|
|
46
|
-
This
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
|
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 {
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
"
|
|
15
|
-
"
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
const run = io.runCommand || runCommand;
|
|
26
|
+
return localStart(parsed, io);
|
|
27
|
+
}
|
|
22
28
|
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
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
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
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
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
|
|
74
|
-
|
|
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
|
|
78
|
-
const
|
|
79
|
-
|
|
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
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
|
102
|
-
|
|
103
|
-
|
|
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
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
|
128
|
-
|
|
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
|
|
270
|
+
async function waitUntilReady(baseUrl, io) {
|
|
132
271
|
const fetchImpl = io.fetch || globalThis.fetch;
|
|
133
|
-
const sleep = io.sleep || (
|
|
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}/
|
|
276
|
+
const response = await fetchImpl(`${baseUrl}/readyz`);
|
|
139
277
|
if (response.ok) return;
|
|
140
278
|
} catch {
|
|
141
|
-
//
|
|
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(`
|
|
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"
|
|
158
|
-
|
|
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
|
|
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");
|