@answerlayer/cli 0.1.2 → 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 CHANGED
@@ -97,15 +97,25 @@ This installs to `~/.codex/skills/answerlayer` by default. Use `--path` for a
97
97
  different skill directory; an existing skill is never replaced unless you pass
98
98
  `--force`.
99
99
 
100
- The flow is:
100
+ Set the model-provider key privately, then let the CLI prepare the stack and
101
+ configure itself:
101
102
 
102
- 1. Install the CLI/plugin.
103
- 2. Clone and start the local `answerlayer-core` Docker stack.
104
- 3. Run `make local-bootstrap` in that stack to create a local-only organization
105
- and scoped CLI key.
106
- 4. Configure the CLI for `http://localhost:8000` with the printed command.
107
- 5. Connect a dedicated, read-only database user and test a small, approved
108
- schema first.
103
+ ```bash
104
+ read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
105
+ answerlayer local up
106
+ ```
107
+
108
+ Use `--stack-dir <directory>` to reuse a different core checkout. If that
109
+ checkout already has a `.env`, the provider key does not need to be exported.
110
+ The command:
111
+
112
+ 1. Verifies Git and Docker and clones `answerlayer-core` when needed.
113
+ 2. Creates a permission-restricted `.env` and generates its encryption key.
114
+ 3. Starts Docker Compose and waits for the API to become healthy.
115
+ 4. Creates a local-only organization and scoped key, verifies the key, and
116
+ saves the CLI configuration without printing the key.
117
+ 5. Leaves you ready to connect a dedicated, read-only database user and test a
118
+ small, approved schema first.
109
119
 
110
120
  The local stack never needs a hosted AnswerLayer account. The skill requires
111
121
  agent confirmation before it starts containers, creates a connection, or sends
@@ -127,6 +137,7 @@ Useful scopes:
127
137
  ```bash
128
138
  answerlayer health
129
139
  answerlayer openapi --output openapi.json
140
+ answerlayer local up
130
141
 
131
142
  answerlayer connections list
132
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.2",
3
+ "version": "0.1.3",
4
4
  "description": "Open-source command line client for the AnswerLayer API.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -30,44 +30,34 @@ already available in the Codex skills directory.
30
30
  npm install -g @answerlayer/cli
31
31
  ```
32
32
 
33
- 2. Clone the core stack beside the user's work and prepare its environment:
33
+ 2. Ask the user to set their Anthropic key privately in their own terminal. Do
34
+ not ask them to paste it into chat or put it in shell history:
34
35
 
35
36
  ```bash
36
- git clone https://github.com/AnswerLayer/answerlayer-core.git
37
- cd answerlayer-core
38
- cp .env.example .env
37
+ read -s ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
39
38
  ```
40
39
 
41
- Ask the user to supply a real `ANTHROPIC_API_KEY` and a strong local
42
- `ENCRYPTION_KEY` in `.env`. Do not print, echo, or add either value to a
43
- command transcript. Clerk and Stripe placeholders are not needed for the
44
- local API-key workflow.
45
-
46
- 3. After confirmation, start the local stack and wait for its health endpoint:
47
-
48
- ```bash
49
- docker compose up --build -d
50
- curl --fail http://localhost:8000/healthz
51
- ```
52
-
53
- 4. After confirmation, create the local-only organization and CLI key:
40
+ 3. After confirmation, run the complete local setup:
54
41
 
55
42
  ```bash
56
- make local-bootstrap
43
+ answerlayer local up
57
44
  ```
58
45
 
59
- The command rotates any previous `local-cli-bootstrap` key and prints an
60
- `answerlayer init --base-url http://localhost:8000 --api-key ...` command.
61
- Have the user run that printed command in their terminal. Never copy the key
62
- into chat, source control, logs, or a shell command you display back to them.
46
+ This verifies Git and Docker, clones the core stack to
47
+ `~/.answerlayer/core` when needed, creates a permission-restricted `.env`
48
+ with a generated encryption key, starts Docker Compose, waits for health,
49
+ creates the local identity and scoped key, verifies it, and configures the
50
+ CLI. It captures the one-time key rather than printing it. Use
51
+ `--stack-dir <directory>` to reuse a different core checkout; when that
52
+ checkout already has a `.env`, `ANTHROPIC_API_KEY` need not be exported.
63
53
 
64
- 5. Before connecting real data, require a dedicated database account that is
54
+ 4. Before connecting real data, require a dedicated database account that is
65
55
  restricted to approved schemas and `SELECT` only. Show the proposed
66
56
  connection host, database, and username, then get confirmation before
67
57
  running `connections create` or any query. Put the password only in a local,
68
58
  permission-restricted JSON file; never print it or commit it.
69
59
 
70
- 6. Start with a small approved schema and read-only inspection. Confirm before
60
+ 5. Start with a small approved schema and read-only inspection. Confirm before
71
61
  creating connections, generating semantic objects, or executing queries.
72
62
 
73
63
  This workflow is for Docker Compose development only. Do not run
package/src/cli.js CHANGED
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { AnswerLayerClient } from "./client.js";
6
6
  import { formatJson, formatList, formatQueryResult } from "./format.js";
7
7
  import { DEFAULT_BASE_URL, readConfig, resolveAuth, writeConfig } from "./config.js";
8
+ import { localUp } from "./local.js";
8
9
 
9
10
  const SEMANTIC_RESOURCES = new Set([
10
11
  "entities",
@@ -36,6 +37,11 @@ export async function main(argv, io) {
36
37
  return initialize(parsed, io);
37
38
  }
38
39
 
40
+ if (group === "local") {
41
+ if (command !== "up") throw usage("Expected `answerlayer local up`");
42
+ return localUp(parsed, io);
43
+ }
44
+
39
45
  const { baseUrl, apiKey } = resolveAuth(parsed.flags, io.env);
40
46
  const client = new AnswerLayerClient({ baseUrl, apiKey });
41
47
 
@@ -1244,6 +1250,7 @@ function normalizeFlagName(rawName) {
1244
1250
  "--relationship-type": "relationshipType",
1245
1251
  "--join": "join",
1246
1252
  "--form": "form",
1253
+ "--stack-dir": "stackDir",
1247
1254
  };
1248
1255
 
1249
1256
  return aliases[rawName] || rawName.replace(/^-+/, "").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
@@ -1337,6 +1344,7 @@ function helpText() {
1337
1344
 
1338
1345
  Usage:
1339
1346
  answerlayer skills install [--path <directory>] [--force]
1347
+ answerlayer local up [--stack-dir <directory>]
1340
1348
  answerlayer init --api-key <key> [--base-url <url>]
1341
1349
  answerlayer configure --base-url <url> --api-key <key>
1342
1350
  answerlayer health
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
+ }