@answerlayer/cli 0.1.1 → 0.1.3
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 +49 -3
- package/package.json +2 -1
- package/skills/answerlayer/SKILL.md +167 -0
- package/src/cli.js +65 -1
- package/src/local.js +186 -0
package/README.md
CHANGED
|
@@ -55,19 +55,25 @@ not change how `answerlayer` works from your terminal.
|
|
|
55
55
|
|
|
56
56
|
## Configure
|
|
57
57
|
|
|
58
|
-
Create an API key in AnswerLayer with the scopes needed by your workflow, then
|
|
58
|
+
Create an API key in AnswerLayer with the scopes needed by your workflow, then
|
|
59
|
+
initialize the CLI. `init` verifies the key before it writes the config file, so
|
|
60
|
+
an invalid or expired key never overwrites a working local setup:
|
|
59
61
|
|
|
60
62
|
```bash
|
|
61
|
-
answerlayer
|
|
63
|
+
answerlayer init --api-key al_live_...
|
|
62
64
|
```
|
|
63
65
|
|
|
64
66
|
The CLI talks to the hosted SaaS at `https://app.answerlayer.io` by default. For a
|
|
65
67
|
BYOC or self-hosted install, point it at your own URL:
|
|
66
68
|
|
|
67
69
|
```bash
|
|
68
|
-
answerlayer
|
|
70
|
+
answerlayer init --api-key al_live_... --base-url https://answerlayer.your-company.com
|
|
69
71
|
```
|
|
70
72
|
|
|
73
|
+
The first API key is currently created in the AnswerLayer app under **Settings →
|
|
74
|
+
API Keys**. A browser/device login flow is planned; until then, the CLI will tell
|
|
75
|
+
you exactly what credential is missing rather than saving an unverified value.
|
|
76
|
+
|
|
71
77
|
You can also skip the config file and use environment variables:
|
|
72
78
|
|
|
73
79
|
```bash
|
|
@@ -77,6 +83,45 @@ export ANSWERLAYER_BASE_URL=https://answerlayer.your-company.com # optional ove
|
|
|
77
83
|
|
|
78
84
|
The CLI sends API keys using the `X-API-Key` header.
|
|
79
85
|
|
|
86
|
+
## Run locally with an agent
|
|
87
|
+
|
|
88
|
+
The package includes an `answerlayer` agent skill for evaluating AnswerLayer
|
|
89
|
+
against your own database without first creating a hosted account. Install it
|
|
90
|
+
for Codex with:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
answerlayer skills install
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
This installs to `~/.codex/skills/answerlayer` by default. Use `--path` for a
|
|
97
|
+
different skill directory; an existing skill is never replaced unless you pass
|
|
98
|
+
`--force`.
|
|
99
|
+
|
|
100
|
+
Set the model-provider key privately, then let the CLI prepare the stack and
|
|
101
|
+
configure itself:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
|
|
105
|
+
answerlayer local up
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Use `--stack-dir <directory>` to reuse a different core checkout. If that
|
|
109
|
+
checkout already has a `.env`, the provider key does not need to be exported.
|
|
110
|
+
The command:
|
|
111
|
+
|
|
112
|
+
1. Verifies Git and Docker and clones `answerlayer-core` when needed.
|
|
113
|
+
2. Creates a permission-restricted `.env` and generates its encryption key.
|
|
114
|
+
3. Starts Docker Compose and waits for the API to become healthy.
|
|
115
|
+
4. Creates a local-only organization and scoped key, verifies the key, and
|
|
116
|
+
saves the CLI configuration without printing the key.
|
|
117
|
+
5. Leaves you ready to connect a dedicated, read-only database user and test a
|
|
118
|
+
small, approved schema first.
|
|
119
|
+
|
|
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.
|
|
124
|
+
|
|
80
125
|
Useful scopes:
|
|
81
126
|
|
|
82
127
|
- `api_key:manage` for API key management
|
|
@@ -92,6 +137,7 @@ Useful scopes:
|
|
|
92
137
|
```bash
|
|
93
138
|
answerlayer health
|
|
94
139
|
answerlayer openapi --output openapi.json
|
|
140
|
+
answerlayer local up
|
|
95
141
|
|
|
96
142
|
answerlayer connections list
|
|
97
143
|
answerlayer connections get <connection-id>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@answerlayer/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "Open-source command line client for the AnswerLayer API.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"files": [
|
|
11
11
|
"bin",
|
|
12
12
|
"src",
|
|
13
|
+
"skills",
|
|
13
14
|
"README.md",
|
|
14
15
|
"LICENSE"
|
|
15
16
|
],
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: answerlayer
|
|
3
|
+
description: Query databases in natural language with AnswerLayer. Use when the user wants to set up or configure AnswerLayer, connect to their data, ask analytical or business questions about a database (revenue, users, counts, "top N", trends, metrics), run SQL through AnswerLayer, or manage AnswerLayer connections, saved queries, the semantic layer, or dashboards.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# AnswerLayer
|
|
7
|
+
|
|
8
|
+
AnswerLayer turns natural-language questions into governed SQL against the user's
|
|
9
|
+
connected databases. This skill drives the **AnswerLayer CLI**, which talks to
|
|
10
|
+
the AnswerLayer API with an API key.
|
|
11
|
+
|
|
12
|
+
Work in three steps: **resolve the CLI → ensure it's configured → use it.**
|
|
13
|
+
|
|
14
|
+
When a user asks to evaluate AnswerLayer locally or against a real database
|
|
15
|
+
without creating a hosted account, use the local-stack workflow below instead
|
|
16
|
+
of the hosted-key workflow.
|
|
17
|
+
|
|
18
|
+
## Local stack workflow
|
|
19
|
+
|
|
20
|
+
Use this only when the user explicitly wants a local evaluation or authorizes
|
|
21
|
+
you to start Docker containers and create a local API key. Explain the commands
|
|
22
|
+
that will run and get confirmation before each state-changing phase.
|
|
23
|
+
|
|
24
|
+
Install this bundled skill with `answerlayer skills install` when it is not
|
|
25
|
+
already available in the Codex skills directory.
|
|
26
|
+
|
|
27
|
+
1. Install the CLI if it is not already available:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install -g @answerlayer/cli
|
|
31
|
+
```
|
|
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:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
3. After confirmation, run the complete local setup:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
answerlayer local up
|
|
44
|
+
```
|
|
45
|
+
|
|
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.
|
|
53
|
+
|
|
54
|
+
4. Before connecting real data, require a dedicated database account that is
|
|
55
|
+
restricted to approved schemas and `SELECT` only. Show the proposed
|
|
56
|
+
connection host, database, and username, then get confirmation before
|
|
57
|
+
running `connections create` or any query. Put the password only in a local,
|
|
58
|
+
permission-restricted JSON file; never print it or commit it.
|
|
59
|
+
|
|
60
|
+
5. Start with a small approved schema and read-only inspection. Confirm before
|
|
61
|
+
creating connections, generating semantic objects, or executing queries.
|
|
62
|
+
|
|
63
|
+
This workflow is for Docker Compose development only. Do not run
|
|
64
|
+
`local-bootstrap` against a hosted or customer deployment.
|
|
65
|
+
|
|
66
|
+
## 1. Resolve the CLI command (`AL`)
|
|
67
|
+
|
|
68
|
+
Pick the command once per session and reuse it. Run:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
command -v answerlayer.js >/dev/null && echo answerlayer.js \
|
|
72
|
+
|| command -v answerlayer >/dev/null && echo answerlayer \
|
|
73
|
+
|| echo "npx -y @answerlayer/cli"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
- `answerlayer.js` — ships with this plugin and is on your PATH (works offline).
|
|
77
|
+
- `answerlayer` — a global install (`npm i -g @answerlayer/cli`).
|
|
78
|
+
- `npx -y @answerlayer/cli` — fallback; downloads from npm on first use.
|
|
79
|
+
|
|
80
|
+
Use whichever it prints as `AL` below. They all run identical code.
|
|
81
|
+
|
|
82
|
+
## 2. Ensure it's configured
|
|
83
|
+
|
|
84
|
+
The CLI needs a base URL (defaults to `https://app.answerlayer.io`) and an API
|
|
85
|
+
key sent as `X-API-Key`. Check whether credentials already exist:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
AL auth me --json
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
- If it returns the caller's identity, you're configured — continue to step 3.
|
|
92
|
+
- If it errors with a missing-key/auth error, set credentials up:
|
|
93
|
+
|
|
94
|
+
1. Ask the user for their **API key**. Also ask for their **host** only if
|
|
95
|
+
they're on a BYOC / self-hosted install; otherwise the default
|
|
96
|
+
`https://app.answerlayer.io` is correct.
|
|
97
|
+
2. Configure (omit `--base-url` to accept the default):
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
AL init --api-key <KEY> [--base-url https://answerlayer.their-host.com]
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
This verifies the key before writing `~/.answerlayer/config.json` (mode
|
|
104
|
+
0600). Alternatively the user can export `ANSWERLAYER_API_KEY` (and
|
|
105
|
+
optionally `ANSWERLAYER_BASE_URL`).
|
|
106
|
+
3. Re-run `AL auth me --json` to confirm.
|
|
107
|
+
|
|
108
|
+
**Never print, echo, or log the API key.** Pass it straight to `init`. Tell
|
|
109
|
+
the user keys are created in the AnswerLayer dashboard under **Settings → API
|
|
110
|
+
Keys** and are shown only once.
|
|
111
|
+
|
|
112
|
+
## 3. Use it
|
|
113
|
+
|
|
114
|
+
Most questions need a **connection** (a database). List them and grab an `id`:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
AL connections list # human table; add --json to parse
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Ask questions in natural language (preferred for analytical questions)
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
# First question — use --json to capture the session id for follow-ups
|
|
124
|
+
AL inquiry ask --connection <connection-id> --json "What was revenue last month?"
|
|
125
|
+
|
|
126
|
+
# Follow-up in the same conversation (carries prior context)
|
|
127
|
+
AL inquiry ask --session <session-id> --json "Break that down by region"
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The JSON includes `session_id`, `final_response`, and `sql_queries`. Show the
|
|
131
|
+
user `final_response`; surface the SQL when they want to see how it was derived.
|
|
132
|
+
Without `--json` it prints the answer followed by the SQL as plain text.
|
|
133
|
+
|
|
134
|
+
### Run SQL directly
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
AL query run <connection-id> --sql "select count(*) from orders" --format table
|
|
138
|
+
AL query run <connection-id> --file ./report.sql --format csv
|
|
139
|
+
AL query validate <connection-id> --sql "select * from orders"
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Other resources
|
|
143
|
+
|
|
144
|
+
These follow `AL <group> <command>`. Run `AL <group> --help` (or `AL --help`)
|
|
145
|
+
to see exact flags before using one:
|
|
146
|
+
|
|
147
|
+
- `saved-queries` — list / get / create / execute reusable queries
|
|
148
|
+
- `semantic` — entities, relationships, measures, metrics, dimensions, filters
|
|
149
|
+
(most need `--connection <id>`)
|
|
150
|
+
- `dashboards`, `tiles` — build and read dashboards
|
|
151
|
+
- `documents` — upload business-context docs and link them to connections
|
|
152
|
+
- `connections` — create / test / inspect schema
|
|
153
|
+
- `metadata`, `api-keys`, `users`, `org`, `billing`, `stats`
|
|
154
|
+
|
|
155
|
+
## Conventions
|
|
156
|
+
|
|
157
|
+
- Prefer `inquiry ask` for analytical/business questions; use `query run` only
|
|
158
|
+
when the user gives or wants explicit SQL.
|
|
159
|
+
- Add `--json` whenever you need to parse output programmatically; query results
|
|
160
|
+
also support `--format table|json|csv`.
|
|
161
|
+
- **Read freely, but confirm before writes.** `create`, `update`, `delete`,
|
|
162
|
+
`revoke`, `approve`, `deploy`, and `assign`/`unassign` change state — show the
|
|
163
|
+
user what you're about to run and get a yes first.
|
|
164
|
+
- If a command fails with a `403` / missing-scope error, the API key lacks a
|
|
165
|
+
scope (e.g. `inquiry:execute`, `query:execute`, `connection:read`). Tell the
|
|
166
|
+
user which scope to add to their key.
|
|
167
|
+
- For the full command surface, run `AL --help` or see the project README.
|
package/src/cli.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
3
5
|
import { AnswerLayerClient } from "./client.js";
|
|
4
6
|
import { formatJson, formatList, formatQueryResult } from "./format.js";
|
|
5
7
|
import { DEFAULT_BASE_URL, readConfig, resolveAuth, writeConfig } from "./config.js";
|
|
8
|
+
import { localUp } from "./local.js";
|
|
6
9
|
|
|
7
10
|
const SEMANTIC_RESOURCES = new Set([
|
|
8
11
|
"entities",
|
|
@@ -26,6 +29,19 @@ export async function main(argv, io) {
|
|
|
26
29
|
return configure(parsed, io);
|
|
27
30
|
}
|
|
28
31
|
|
|
32
|
+
if (group === "skills") {
|
|
33
|
+
return installSkill(command, parsed, io);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (group === "init") {
|
|
37
|
+
return initialize(parsed, io);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (group === "local") {
|
|
41
|
+
if (command !== "up") throw usage("Expected `answerlayer local up`");
|
|
42
|
+
return localUp(parsed, io);
|
|
43
|
+
}
|
|
44
|
+
|
|
29
45
|
const { baseUrl, apiKey } = resolveAuth(parsed.flags, io.env);
|
|
30
46
|
const client = new AnswerLayerClient({ baseUrl, apiKey });
|
|
31
47
|
|
|
@@ -69,6 +85,50 @@ function configure(parsed, io) {
|
|
|
69
85
|
write(io.stdout, `Saved AnswerLayer config to ${configPath}\n`);
|
|
70
86
|
}
|
|
71
87
|
|
|
88
|
+
function installSkill(command, parsed, io) {
|
|
89
|
+
if (command !== "install") {
|
|
90
|
+
throw usage("Expected `answerlayer skills install`");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const source = path.resolve(
|
|
94
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
95
|
+
"../skills/answerlayer",
|
|
96
|
+
);
|
|
97
|
+
const codexHome = io.env.CODEX_HOME || path.join(os.homedir(), ".codex");
|
|
98
|
+
const target = firstValue(parsed.flags.path) || path.join(codexHome, "skills", "answerlayer");
|
|
99
|
+
|
|
100
|
+
if (fs.existsSync(target) && !parsed.flags.force) {
|
|
101
|
+
throw usage(
|
|
102
|
+
`Skill already exists at ${target}. Review it, then rerun with --force to replace it.`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
107
|
+
fs.cpSync(source, target, { recursive: true, force: true });
|
|
108
|
+
write(io.stdout, `Installed AnswerLayer skill to ${target}\n`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function initialize(parsed, io) {
|
|
112
|
+
const existing = readConfig(io.env);
|
|
113
|
+
const { baseUrl } = resolveAuth(parsed.flags, io.env);
|
|
114
|
+
const apiKey = firstValue(parsed.flags.apiKey);
|
|
115
|
+
|
|
116
|
+
if (!apiKey) {
|
|
117
|
+
throw usage(
|
|
118
|
+
"init requires an explicit --api-key. Use the command printed by `make local-bootstrap`, or create a key under Settings → API Keys.",
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Verify before writing so a typo or an expired key never replaces a working
|
|
123
|
+
// local configuration.
|
|
124
|
+
const client = new AnswerLayerClient({ baseUrl, apiKey });
|
|
125
|
+
await client.rawRequest("GET", "/api/v1/auth/me");
|
|
126
|
+
|
|
127
|
+
const configPath = writeConfig({ ...existing, baseUrl, apiKey }, io.env);
|
|
128
|
+
write(io.stdout, `Verified API key and saved AnswerLayer config to ${configPath}\n`);
|
|
129
|
+
write(io.stdout, "Next: answerlayer connections list\n");
|
|
130
|
+
}
|
|
131
|
+
|
|
72
132
|
async function handleHealth(client, command, parsed, io) {
|
|
73
133
|
const pathName = command === "ready" ? "/api/v1/ready" : "/api/v1/health";
|
|
74
134
|
return requestAndPrint(client, "GET", pathName, parsed, io, { auth: false, okText: "ok" });
|
|
@@ -1190,13 +1250,14 @@ function normalizeFlagName(rawName) {
|
|
|
1190
1250
|
"--relationship-type": "relationshipType",
|
|
1191
1251
|
"--join": "join",
|
|
1192
1252
|
"--form": "form",
|
|
1253
|
+
"--stack-dir": "stackDir",
|
|
1193
1254
|
};
|
|
1194
1255
|
|
|
1195
1256
|
return aliases[rawName] || rawName.replace(/^-+/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
1196
1257
|
}
|
|
1197
1258
|
|
|
1198
1259
|
function isBooleanFlag(rawName) {
|
|
1199
|
-
return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin"].includes(rawName);
|
|
1260
|
+
return ["--json", "--help", "-h", "--include", "-i", "--raw", "--admin", "--force"].includes(rawName);
|
|
1200
1261
|
}
|
|
1201
1262
|
|
|
1202
1263
|
function setFlag(flags, name, value) {
|
|
@@ -1282,6 +1343,9 @@ function helpText() {
|
|
|
1282
1343
|
return `AnswerLayer CLI
|
|
1283
1344
|
|
|
1284
1345
|
Usage:
|
|
1346
|
+
answerlayer skills install [--path <directory>] [--force]
|
|
1347
|
+
answerlayer local up [--stack-dir <directory>]
|
|
1348
|
+
answerlayer init --api-key <key> [--base-url <url>]
|
|
1285
1349
|
answerlayer configure --base-url <url> --api-key <key>
|
|
1286
1350
|
answerlayer health
|
|
1287
1351
|
answerlayer openapi --output openapi.json
|
package/src/local.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { AnswerLayerClient } from "./client.js";
|
|
7
|
+
import { readConfig, writeConfig } from "./config.js";
|
|
8
|
+
|
|
9
|
+
const CORE_REPOSITORY = "https://github.com/AnswerLayer/answerlayer-core.git";
|
|
10
|
+
const CORE_REMOTE_PATTERN = /(?:^|@|\/\/)github\.com[:/]AnswerLayer\/answerlayer-core(?:\.git)?\/?$/i;
|
|
11
|
+
const REQUIRED_CORE_PATHS = [
|
|
12
|
+
"docker-compose.yml",
|
|
13
|
+
".env.example",
|
|
14
|
+
"Makefile",
|
|
15
|
+
"backend/app/scripts/bootstrap_local.py",
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
export async function localUp(parsed, io) {
|
|
19
|
+
const stackDir = path.resolve(firstValue(parsed.flags.stackDir) || path.join(os.homedir(), ".answerlayer", "core"));
|
|
20
|
+
const envPath = path.join(stackDir, ".env");
|
|
21
|
+
const run = io.runCommand || runCommand;
|
|
22
|
+
|
|
23
|
+
requireCommand(run, "git", ["--version"]);
|
|
24
|
+
requireCommand(run, "docker", ["compose", "version"]);
|
|
25
|
+
|
|
26
|
+
const stackExists = fs.existsSync(stackDir);
|
|
27
|
+
if (!fs.existsSync(envPath) && !io.env.ANTHROPIC_API_KEY) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
"Set ANTHROPIC_API_KEY in your environment before the first `answerlayer local up`. It is written only to the local stack's permission-restricted .env file.",
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!stackExists) {
|
|
34
|
+
fs.mkdirSync(path.dirname(stackDir), { recursive: true, mode: 0o700 });
|
|
35
|
+
write(io.stdout, `Cloning the AnswerLayer stack into ${stackDir}\n`);
|
|
36
|
+
checked(run, "git", ["clone", "--depth", "1", CORE_REPOSITORY, stackDir]);
|
|
37
|
+
}
|
|
38
|
+
validateCheckout(stackDir, run);
|
|
39
|
+
|
|
40
|
+
if (!fs.existsSync(envPath)) {
|
|
41
|
+
prepareEnvironment(stackDir, io.env.ANTHROPIC_API_KEY);
|
|
42
|
+
write(io.stdout, `Created ${envPath} with permissions 0600\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
write(io.stdout, "Starting the local AnswerLayer stack...\n");
|
|
46
|
+
checked(run, "docker", ["compose", "up", "--build", "-d"], { cwd: stackDir, passthrough: true });
|
|
47
|
+
const publishedPort = checked(
|
|
48
|
+
run,
|
|
49
|
+
"docker",
|
|
50
|
+
["compose", "port", "answerlayer", "8000"],
|
|
51
|
+
{ cwd: stackDir },
|
|
52
|
+
);
|
|
53
|
+
const baseUrl = parsePublishedBaseUrl(publishedPort.stdout);
|
|
54
|
+
await waitUntilHealthy(baseUrl, io);
|
|
55
|
+
|
|
56
|
+
write(io.stdout, "Creating a local CLI identity and rotating its scoped key...\n");
|
|
57
|
+
const bootstrap = checked(run, "make", ["local-bootstrap"], { cwd: stackDir });
|
|
58
|
+
const credentials = { baseUrl, apiKey: parseBootstrapApiKey(bootstrap.stdout) };
|
|
59
|
+
|
|
60
|
+
// Bootstrap rotates the previous key, so persist the replacement before any
|
|
61
|
+
// network verification that may fail transiently. This keeps the only valid
|
|
62
|
+
// credential recoverable for a retry.
|
|
63
|
+
const existing = readConfig(io.env);
|
|
64
|
+
const configPath = writeConfig({ ...existing, ...credentials }, io.env);
|
|
65
|
+
|
|
66
|
+
const client = new AnswerLayerClient({ ...credentials, fetchImpl: io.fetch || globalThis.fetch });
|
|
67
|
+
try {
|
|
68
|
+
await client.rawRequest("GET", "/api/v1/auth/me");
|
|
69
|
+
} catch (error) {
|
|
70
|
+
throw new Error(`Saved rotated local credentials to ${configPath}, but verification failed: ${error.message}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
write(io.stdout, `Local AnswerLayer is ready. Verified credentials and saved config to ${configPath}\n`);
|
|
74
|
+
write(io.stdout, "Next: answerlayer connections list\n");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function prepareEnvironment(stackDir, anthropicApiKey) {
|
|
78
|
+
const examplePath = path.join(stackDir, ".env.example");
|
|
79
|
+
if (!fs.existsSync(examplePath)) throw new Error(`Missing ${examplePath}`);
|
|
80
|
+
|
|
81
|
+
if (/[\r\n]/.test(anthropicApiKey)) throw new Error("ANTHROPIC_API_KEY must not contain a newline");
|
|
82
|
+
const encryptionKey = crypto.randomBytes(32).toString("hex");
|
|
83
|
+
const template = fs.readFileSync(examplePath, "utf8");
|
|
84
|
+
const replacements = {
|
|
85
|
+
ANTHROPIC_API_KEY: anthropicApiKey,
|
|
86
|
+
ENCRYPTION_KEY: encryptionKey,
|
|
87
|
+
};
|
|
88
|
+
let contents = template;
|
|
89
|
+
for (const [name, value] of Object.entries(replacements)) {
|
|
90
|
+
const pattern = new RegExp(`^${name}=.*$`, "gm");
|
|
91
|
+
if ([...template.matchAll(pattern)].length !== 1) {
|
|
92
|
+
throw new Error(`${examplePath} must contain exactly one ${name}= entry`);
|
|
93
|
+
}
|
|
94
|
+
contents = contents.replace(pattern, () => `${name}=${value}`);
|
|
95
|
+
}
|
|
96
|
+
const envPath = path.join(stackDir, ".env");
|
|
97
|
+
fs.writeFileSync(envPath, contents, { encoding: "utf8", mode: 0o600 });
|
|
98
|
+
fs.chmodSync(envPath, 0o600);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function validateCheckout(stackDir, run) {
|
|
102
|
+
if (!fs.existsSync(path.join(stackDir, ".git"))) {
|
|
103
|
+
throw new Error(`${stackDir} is not a Git checkout`);
|
|
104
|
+
}
|
|
105
|
+
for (const relativePath of REQUIRED_CORE_PATHS) {
|
|
106
|
+
if (!fs.existsSync(path.join(stackDir, relativePath))) {
|
|
107
|
+
throw new Error(`${stackDir} is missing required AnswerLayer core file ${relativePath}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const remote = checked(run, "git", ["-C", stackDir, "remote", "get-url", "origin"]);
|
|
112
|
+
if (!CORE_REMOTE_PATTERN.test(String(remote.stdout).trim())) {
|
|
113
|
+
throw new Error(`${stackDir} does not use the official AnswerLayer core origin`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function parsePublishedBaseUrl(stdout) {
|
|
118
|
+
const publishedAddress = String(stdout)
|
|
119
|
+
.split(/\r?\n/)
|
|
120
|
+
.map(line => line.trim())
|
|
121
|
+
.map(line => line.match(/^(0\.0\.0\.0|127\.0\.0\.1|localhost|\[::\]|\[::1\]|::):(\d+)$/))
|
|
122
|
+
.find(Boolean);
|
|
123
|
+
const port = publishedAddress ? Number.parseInt(publishedAddress[2], 10) : 0;
|
|
124
|
+
if (port < 1 || port > 65535) {
|
|
125
|
+
throw new Error("Docker Compose did not publish answerlayer port 8000 on a local host interface");
|
|
126
|
+
}
|
|
127
|
+
const host = publishedAddress[1] === "[::1]" ? "[::1]" : "127.0.0.1";
|
|
128
|
+
return `http://${host}:${port}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function waitUntilHealthy(baseUrl, io) {
|
|
132
|
+
const fetchImpl = io.fetch || globalThis.fetch;
|
|
133
|
+
const sleep = io.sleep || ((milliseconds) => new Promise(resolve => setTimeout(resolve, milliseconds)));
|
|
134
|
+
const attempts = io.healthAttempts || 60;
|
|
135
|
+
|
|
136
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
137
|
+
try {
|
|
138
|
+
const response = await fetchImpl(`${baseUrl}/healthz`);
|
|
139
|
+
if (response.ok) return;
|
|
140
|
+
} catch {
|
|
141
|
+
// The container may still be starting.
|
|
142
|
+
}
|
|
143
|
+
await sleep(2000);
|
|
144
|
+
}
|
|
145
|
+
throw new Error(`Local stack did not become healthy at ${baseUrl}/healthz`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function parseBootstrapApiKey(stdout) {
|
|
149
|
+
const initLine = String(stdout).split(/\r?\n/).find(line => /(?:^|\s)answerlayer\s+init(?:\s|$)/.test(line));
|
|
150
|
+
const match = initLine?.match(/(?:^|\s)--api-key(?:=|\s+)(\S+)/);
|
|
151
|
+
if (!match) throw new Error("Local bootstrap completed without returning CLI credentials");
|
|
152
|
+
return match[1];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function requireCommand(run, command, args) {
|
|
156
|
+
const result = run(command, args, { capture: true });
|
|
157
|
+
if (result.error?.code === "ENOENT") throw new Error(`${command} is required for local setup`);
|
|
158
|
+
if (result.status !== 0) throw new Error(`${command} is required for local setup`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function checked(run, command, args, options = {}) {
|
|
162
|
+
const result = run(command, args, { capture: !options.passthrough, cwd: options.cwd });
|
|
163
|
+
if (result.error) throw result.error;
|
|
164
|
+
if (result.status !== 0) {
|
|
165
|
+
const detail = String(result.stderr || "").trim();
|
|
166
|
+
throw new Error(`${command} ${args.join(" ")} failed${detail ? `: ${detail}` : ""}`);
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function runCommand(command, args, options = {}) {
|
|
172
|
+
return spawnSync(command, args, {
|
|
173
|
+
cwd: options.cwd,
|
|
174
|
+
encoding: options.capture ? "utf8" : undefined,
|
|
175
|
+
stdio: options.capture ? ["ignore", "pipe", "pipe"] : "inherit",
|
|
176
|
+
maxBuffer: 50 * 1024 * 1024,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function firstValue(value) {
|
|
181
|
+
return Array.isArray(value) ? value[0] : value;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function write(stream, text) {
|
|
185
|
+
stream.write(text);
|
|
186
|
+
}
|