directionallylocal 0.2.0 → 0.4.0

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/dist/cli.js CHANGED
@@ -2,27 +2,39 @@ import { readFileSync } from "node:fs";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { parseArgs } from "node:util";
4
4
  import { doctor, formatChecks } from "./doctor.js";
5
+ import { serverKeysCommand } from "./keys.js";
5
6
  import { briefStatus, connectLaptop, laptopsCommand, logsCommand, pairLaptop, serverHome, serverRunsCommand } from "./home.js";
6
- import { cancel, connect, describeError, laptopHome, pull, run, runs, servers, watch } from "./laptop/commands.js";
7
+ import { cancel, connect, describeError, laptopHome, pull, run, runs, servers, use, watch } from "./laptop/commands.js";
8
+ import { loadRemotes } from "./laptop/config.js";
9
+ import { keys } from "./laptop/keys.js";
10
+ import { setup } from "./laptop/setup.js";
11
+ import { localCommand } from "./local/cli.js";
12
+ import { setUpOnThisComputer } from "./local/setup.js";
7
13
  import { TtyPrompter } from "./prompt.js";
8
14
  import { readState } from "./state.js";
9
15
  import { DryRunSystem, RealSystem } from "./system.js";
10
16
  import { uninstall } from "./uninstall.js";
11
17
  import { JsonUi, PlainUi, TerminalUi, palette } from "./ui.js";
12
18
  import { needs, parseAccessMode, parseProvidedAnswers, up } from "./up.js";
13
- const HELP = `Directionally Local: background coding agents on your own server.
14
- Send a task from your laptop; it runs in its own sandbox and comes back as a pull request.
19
+ const HELP = `Directionally Local: coding agents that run on this computer or on your own server.
20
+ Send a task; it runs in its own sandbox and comes back as a pull request.
15
21
  (dl is short for directionallylocal; both work.)
16
22
 
17
23
  On your laptop:
18
- dl connect URL connect to your server (approve the code it shows)
19
- dl run "TASK" run a task on the server, from inside a GitHub repository
24
+ dl set up the first time; afterwards, an overview
25
+ dl setup set up or repair where your agents run (safe to re-run)
26
+ dl connect URL connect to a server someone else set up (approve the code it shows)
27
+ dl run "TASK" run a task, from inside a GitHub repository
20
28
  (your uncommitted changes go along; Ctrl-C stops watching, not the task)
21
29
  dl runs your tasks and their pull requests
22
30
  dl watch ID follow a task dl cancel ID stop one
23
31
  dl pull ID check out a task's branch here
24
- dl servers connected servers (dl servers remove NAME)
25
- run options: --server NAME, -m MODEL, --repo OWNER/NAME, --detach
32
+ dl servers where agents run (dl servers remove NAME · dl servers rename OLD NEW)
33
+ dl use [NAME] where tasks go without --server (no NAME: show it)
34
+ dl keys [openrouter|github] which keys are set, or replace one (--server NAME)
35
+ run options: --server NAME, -m/--model MODEL, --repo OWNER/NAME, --detach
36
+ dl local status agents running on this computer: running?, where, how many fit
37
+ dl local uninstall [--purge] stop and remove them (--purge also deletes keys and data)
26
38
 
27
39
  On the server:
28
40
  dl what this is, whether it's healthy, laptops, and runs
@@ -33,6 +45,7 @@ On the server:
33
45
  dl runs tasks running or done, with their pull requests
34
46
  dl logs [hotcell|autopilot] [-f] the services' logs
35
47
  dl doctor check every part, with a fix for each problem
48
+ dl keys [set openrouter|github] which keys are set, or replace one (hidden input)
36
49
  dl uninstall [--purge] remove everything (--purge also removes config and data)
37
50
 
38
51
  up options:
@@ -54,6 +67,7 @@ Used by the laptop's setup (over SSH, as root):
54
67
  install with the keys as one JSON object on stdin; progress as JSON lines
55
68
  dl up --needs [--access ssh] which keys dl up would still need, as JSON; changes nothing
56
69
  dl pair --name NAME --json a credential for that laptop, as JSON
70
+ dl keys set openrouter|github --stdin --json replace a key read from stdin
57
71
  `;
58
72
  export async function main(argv, io = {
59
73
  out: (text) => process.stdout.write(text),
@@ -84,6 +98,8 @@ export async function main(argv, io = {
84
98
  "answers-stdin": { type: "boolean" },
85
99
  events: { type: "string" },
86
100
  needs: { type: "boolean" },
101
+ identity: { type: "string" },
102
+ stdin: { type: "boolean" },
87
103
  },
88
104
  });
89
105
  }
@@ -193,6 +209,9 @@ export async function main(argv, io = {
193
209
  // A laptop connected to servers gets its own home; otherwise, what this is and how to start.
194
210
  if (!command && await laptopHome(laptopIO))
195
211
  return 0;
212
+ // A laptop with nothing set up yet: the wizard (it needs someone to answer it).
213
+ if (!command && terminal && !isRoot() && (await loadRemotes()).length === 0)
214
+ return await setup({ io: laptopIO, terminal, localSetup: (input) => setUpOnThisComputer(input) });
196
215
  io.out(NOT_A_SERVER(colors));
197
216
  return command ? 1 : 0;
198
217
  }
@@ -208,6 +227,8 @@ export async function main(argv, io = {
208
227
  await serverHome(system, state, io.out, colors);
209
228
  return 0;
210
229
  }
230
+ case "setup":
231
+ return await setup({ io: laptopIO, terminal, localSetup: (input) => setUpOnThisComputer(input), ...(values.identity ? { identityFile: values.identity } : {}) });
211
232
  case "connect": {
212
233
  const url = parsed.positionals[1];
213
234
  if (!url) {
@@ -252,6 +273,8 @@ export async function main(argv, io = {
252
273
  }
253
274
  case "servers":
254
275
  return await servers(parsed.positionals.slice(1), laptopIO);
276
+ case "use":
277
+ return await use(parsed.positionals.slice(1), laptopIO);
255
278
  case "runs":
256
279
  // On a server, its runs; on a laptop, the tasks it sent.
257
280
  if (!(await readState(system))) {
@@ -280,6 +303,20 @@ export async function main(argv, io = {
280
303
  return await serverRunsCommand(system, io.out, colors);
281
304
  return await logsCommand(system, [...rest, ...(values.follow ? ["-f"] : [])]);
282
305
  }
306
+ case "keys": {
307
+ // On a server, its own keys (as root); on a laptop, the keys where its agents run.
308
+ if (!(await readState(system)))
309
+ return await keys(parsed.positionals.slice(1), { ...(values.server ? { server: values.server } : {}), io: laptopIO, terminal });
310
+ if (!isRoot()) {
311
+ io.err(` Run it as root: sudo dl ${parsed.positionals.join(" ")}\n`);
312
+ return 1;
313
+ }
314
+ return await serverKeysCommand(system, parsed.positionals.slice(1), { json: Boolean(values.json), stdin: Boolean(values.stdin) }, {
315
+ out: io.out, err: io.err, colors, stdin: options.stdin ?? process.stdin, prompter: new TtyPrompter(),
316
+ });
317
+ }
318
+ case "local":
319
+ return await localCommand(parsed.positionals.slice(1), { purge: Boolean(values.purge) }, io, colors, ui);
283
320
  case "uninstall":
284
321
  await uninstall(system, { purge: Boolean(values.purge) });
285
322
  return 0;
@@ -306,10 +343,13 @@ export async function main(argv, io = {
306
343
  const NOT_A_SERVER = (c) => `
307
344
  ${c.bold("Directionally Local")} ${c.dim("isn't set up on this machine.")}
308
345
 
309
- Background coding agents on your own server: send a task from your laptop,
346
+ Coding agents that run on this computer or on your own server: send a task,
310
347
  get a pull request back.
311
348
 
312
- ${c.dim("Set up a server (as root, on Ubuntu or Debian):")}
349
+ ${c.dim("Set it up here, or on a server over SSH (asks a few questions):")}
350
+ dl setup
351
+
352
+ ${c.dim("Or on a server (as root, on Ubuntu or Debian):")}
313
353
  curl -fsSL https://directionallylocal.run | sh
314
354
 
315
355
  ${c.dim("Already have one? Connect this laptop to it:")}
package/dist/keys.js ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * `dl keys` on a server: replace the OpenRouter key or the GitHub token where `dl up`
3
+ * stored them, restart the one service that reads it, and show which keys are set (never
4
+ * their values). Keys come in on stdin (or hidden input on the server's own terminal),
5
+ * never argv, so they stay out of `ps`, shell history, and logs.
6
+ *
7
+ * OpenRouter Hotcell's file keystore, as the hotcell user → restart hotcell.service
8
+ * GitHub /etc/autopilot/github.env (0640 root:autopilot) → restart autopilot.service
9
+ *
10
+ * The laptop's `dl keys` runs `dl keys set <which> --stdin --json` here over SSH.
11
+ */
12
+ import { AUTOPILOT_PORT, HOTCELL_PORT, PATHS, SERVICES, USERS, githubEnv, hotcellBin, parseEnvFile } from "./layout.js";
13
+ import { asHotcell, validateGitHubToken, validateOpenRouterKey, waitUntil } from "./up.js";
14
+ export const KEY_NAMES = ["openrouter", "github"];
15
+ export const KEY_LABELS = { openrouter: "OpenRouter", github: "GitHub" };
16
+ export function parseKeyName(value) {
17
+ return KEY_NAMES.find((name) => name === value?.trim().toLowerCase());
18
+ }
19
+ /** Format first, then (with `fetchImpl`) the service itself; offline isn't fatal. */
20
+ export async function checkKey(which, value, fetchImpl) {
21
+ if (!value)
22
+ return { problem: "No key was given." };
23
+ if (which === "openrouter") {
24
+ const problem = await validateOpenRouterKey(value, fetchImpl);
25
+ return problem ? { problem } : {};
26
+ }
27
+ return validateGitHubToken(value, fetchImpl);
28
+ }
29
+ /** The key wasn't accepted; nothing was stored or restarted. */
30
+ export class KeyRejectedError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = "KeyRejectedError";
34
+ }
35
+ }
36
+ /** Stores the key exactly where `dl up` does, then restarts the service that reads it and waits for it. */
37
+ export async function setServerKey(system, which, value, options = {}) {
38
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
39
+ const key = value.trim();
40
+ const checked = await checkKey(which, key, options.fetchImpl);
41
+ if (checked.problem)
42
+ throw new KeyRejectedError(checked.problem);
43
+ if (which === "openrouter") {
44
+ if (!(await system.exists(hotcellBin())))
45
+ throw new Error("Hotcell isn't installed here; run dl up first.");
46
+ // Over stdin into Hotcell's keystore: never in argv, env files, or Autopilot's config. It replaces the old one.
47
+ await asHotcell(system, ["keys", "add", "openrouter", "--stdin"], { input: key, describe: "hotcell keys add openrouter --stdin (as hotcell)" });
48
+ // Hotcell reads its keystore at startup.
49
+ await system.run("systemctl", ["restart", SERVICES.hotcell]);
50
+ await waitUntil(system, sleep, "Hotcell", () => hotcellAnswers(system));
51
+ return { ok: true, key: which, detail: "replaced in Hotcell; Hotcell restarted" };
52
+ }
53
+ await system.mkdir(PATHS.autopilotEtc, { mode: 0o750, owner: `root:${USERS.autopilot}` });
54
+ await system.writeFile(PATHS.githubEnv, githubEnv(key), { mode: 0o640, owner: `root:${USERS.autopilot}`, secret: true });
55
+ // Autopilot reads GITHUB_TOKEN from its env file at startup.
56
+ await system.run("systemctl", ["restart", SERVICES.autopilot]);
57
+ await waitUntil(system, sleep, "Autopilot", () => autopilotAnswers(system));
58
+ return { ok: true, key: which, detail: `${checked.detail ? `${checked.detail}; ` : ""}Autopilot restarted` };
59
+ }
60
+ /** Which keys this server has. Reads and probes only; the GitHub login is a quick, optional API call. */
61
+ export async function listServerKeys(system, options = {}) {
62
+ let openrouter = { key: "openrouter", set: false };
63
+ if (await system.exists(hotcellBin())) {
64
+ const listed = await system.probe("runuser", [
65
+ "-u", USERS.hotcell, "--", "env", `HOTCELL_HOME=${PATHS.hotcellHome}`, "HOTCELL_KEYSTORE=file", "NO_COLOR=1", "/usr/bin/node", hotcellBin(), "keys", "ls",
66
+ ]);
67
+ if (listed.code === 0)
68
+ openrouter = { key: "openrouter", ...hotcellKeyListed(listed.stdout, "openrouter") };
69
+ }
70
+ const token = parseEnvFile(await system.readFile(PATHS.githubEnv)).GITHUB_TOKEN;
71
+ return [openrouter, await githubListing(token, options.fetchImpl)];
72
+ }
73
+ /**
74
+ * A provider's row in `hotcell keys ls` (`openrouter sk-or…ab file`), with Hotcell's
75
+ * mask. A column that's long enough to be a key isn't shown, in case the format changes.
76
+ */
77
+ export function hotcellKeyListed(stdout, provider) {
78
+ const plain = stdout.replace(/\x1b\[[0-9;]*m/g, "");
79
+ const row = plain.split("\n").map((line) => line.trim().split(/\s+/)).find((cells) => cells[0] === provider);
80
+ if (!row)
81
+ return { set: false };
82
+ const mask = row[1];
83
+ return mask && mask.length <= 12 && (mask.includes("…") || /^•+$/.test(mask)) ? { set: true, detail: mask } : { set: true };
84
+ }
85
+ /** The GitHub row: set or not, and whose token it is when GitHub answers within a few seconds. */
86
+ export async function githubListing(token, fetchImpl) {
87
+ if (!token)
88
+ return { key: "github", set: false };
89
+ if (!fetchImpl)
90
+ return { key: "github", set: true };
91
+ const quick = (input, init) => fetchImpl(input, { ...init, signal: AbortSignal.timeout(5_000) });
92
+ const checked = await validateGitHubToken(token, quick);
93
+ // A stored token in an unexpected format still counts as set; only GitHub's own refusal is a problem.
94
+ if (checked.problem && /rejected/.test(checked.problem))
95
+ return { key: "github", set: true, problem: checked.problem };
96
+ return { key: "github", set: true, ...(checked.detail ? { detail: checked.detail } : {}) };
97
+ }
98
+ /** `dl keys` as text: one line per key, values never shown. */
99
+ export function formatKeyListing(listing, c, where, replaceWith) {
100
+ const rows = listing.map((entry) => {
101
+ const label = KEY_LABELS[entry.key].padEnd(12);
102
+ if (!entry.set)
103
+ return ` ${c.red("✗")} ${label}${c.dim("not set")} ${replaceWith(entry.key)}\n`;
104
+ if (entry.problem)
105
+ return ` ${c.red("✗")} ${label}${entry.problem} ${c.dim("replace it:")} ${replaceWith(entry.key)}\n`;
106
+ return ` ${c.green("✓")} ${label}${c.dim(entry.detail ?? "set")}\n`;
107
+ });
108
+ const hint = listing.every((entry) => entry.set && !entry.problem)
109
+ ? `\n ${c.dim("Replace one:")} ${replaceWith("openrouter")} ${c.dim("or")} ${replaceWith("github")}\n`
110
+ : "";
111
+ return `\n ${c.bold("Keys")} ${c.dim(where)}\n\n${rows.join("")}${hint}\n`;
112
+ }
113
+ /**
114
+ * One line from stdin: the key, up to the first newline or the end. Never echoed, and a
115
+ * parse error never quotes it.
116
+ */
117
+ export async function readKeyLine(stdin) {
118
+ if (stdin.isTTY)
119
+ throw new Error("--stdin reads the key from a pipe, not a terminal; leave it off to type the key (hidden).");
120
+ let text = "";
121
+ for await (const chunk of stdin) {
122
+ text += typeof chunk === "string" ? chunk : chunk.toString("utf8");
123
+ if (text.includes("\n"))
124
+ break;
125
+ if (text.length > 4096)
126
+ throw new Error("The key on stdin is too long; expected one line.");
127
+ }
128
+ const line = text.split("\n")[0].trim();
129
+ if (line.length > 4096)
130
+ throw new Error("The key on stdin is too long; expected one line.");
131
+ return line;
132
+ }
133
+ const SERVER_USAGE = " Usage: dl keys which keys are set\n"
134
+ + " dl keys set openrouter|github replace one (hidden input; --stdin reads it from a pipe)\n";
135
+ /**
136
+ * `dl keys [ls]`, `dl keys set <openrouter|github> [--stdin] [--json]`, and `dl keys
137
+ * <openrouter|github>` (the same as `set`), as root on a server.
138
+ */
139
+ export async function serverKeysCommand(system, args, flags, deps) {
140
+ const c = deps.colors;
141
+ const env = deps.env ?? process.env;
142
+ const fetchImpl = env.DL_SKIP_CREDENTIAL_CHECK === "1" ? undefined : deps.fetchImpl ?? fetch;
143
+ const [first, second] = args;
144
+ if (first === undefined || first === "ls" || first === "list") {
145
+ const listing = await listServerKeys(system, { fetchImpl });
146
+ if (flags.json)
147
+ deps.out(`${JSON.stringify({ keys: listing })}\n`);
148
+ else
149
+ deps.out(formatKeyListing(listing, c, "on this server", (key) => `sudo dl keys set ${key}`));
150
+ return 0;
151
+ }
152
+ const which = parseKeyName(first === "set" ? second : first);
153
+ if (!which || (first !== "set" && second !== undefined)) {
154
+ deps.err(SERVER_USAGE);
155
+ return 2;
156
+ }
157
+ try {
158
+ let value;
159
+ if (flags.stdin)
160
+ value = await readKeyLine(deps.stdin);
161
+ else if (!flags.json)
162
+ value = await deps.prompter.secret(` ${KEY_LABELS[which]} ${which === "github" ? "token" : "key"} (hidden): `);
163
+ else
164
+ throw new Error("--json needs the key on stdin: dl keys set KEY --stdin --json");
165
+ const result = await setServerKey(system, which, value, { fetchImpl, ...(deps.sleep ? { sleep: deps.sleep } : {}) });
166
+ if (flags.json)
167
+ deps.out(`${JSON.stringify(result)}\n`);
168
+ else
169
+ deps.out(` ${c.green("✓")} ${KEY_LABELS[which]} ${which === "github" ? "token" : "key"} replaced ${c.dim(result.detail)}\n`);
170
+ return 0;
171
+ }
172
+ catch (error) {
173
+ const message = error instanceof Error ? error.message : String(error);
174
+ if (flags.json)
175
+ deps.out(`${JSON.stringify({ ok: false, key: which, error: message })}\n`);
176
+ else
177
+ deps.err(` ${c.red("✗")} ${message}\n`);
178
+ return 1;
179
+ }
180
+ }
181
+ async function hotcellAnswers(system) {
182
+ return (await system.probe("curl", ["-fsS", "-o", "/dev/null", `http://127.0.0.1:${HOTCELL_PORT}/`])).code === 0
183
+ || (await system.probe("sh", ["-c", `ss -ltn | grep -q '127.0.0.1:${HOTCELL_PORT}'`])).code === 0;
184
+ }
185
+ /** Without a token the Aster API answers 401: up, and refusing strangers. */
186
+ async function autopilotAnswers(system) {
187
+ return (await system.probe("curl", ["-s", "-o", "/dev/null", "-w", "%{http_code}", `http://127.0.0.1:${AUTOPILOT_PORT}/api/v1/health`])).stdout.trim() === "401";
188
+ }