directionallylocal 0.3.0 → 0.4.1

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -71,3 +71,7 @@ npm test # node:test through tsx; a simulated server exercises up, doct
71
71
  npm run typecheck
72
72
  npm run build
73
73
  ```
74
+
75
+ ## License
76
+
77
+ Apache-2.0. See [LICENSE](LICENSE).
package/dist/cli.js CHANGED
@@ -2,9 +2,11 @@ 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";
7
8
  import { loadRemotes } from "./laptop/config.js";
9
+ import { keys } from "./laptop/keys.js";
8
10
  import { setup } from "./laptop/setup.js";
9
11
  import { localCommand } from "./local/cli.js";
10
12
  import { setUpOnThisComputer } from "./local/setup.js";
@@ -14,21 +16,23 @@ import { DryRunSystem, RealSystem } from "./system.js";
14
16
  import { uninstall } from "./uninstall.js";
15
17
  import { JsonUi, PlainUi, TerminalUi, palette } from "./ui.js";
16
18
  import { needs, parseAccessMode, parseProvidedAnswers, up } from "./up.js";
17
- const HELP = `Directionally Local: background coding agents on your own server.
18
- 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.
19
21
  (dl is short for directionallylocal; both work.)
20
22
 
21
23
  On your laptop:
22
- dl set up where agents run (the first time; afterwards, an overview)
23
- dl setup set up, or repair, a server over SSH (safe to re-run)
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)
24
26
  dl connect URL connect to a server someone else set up (approve the code it shows)
25
- dl run "TASK" run a task on the server, from inside a GitHub repository
27
+ dl run "TASK" run a task, from inside a GitHub repository
26
28
  (your uncommitted changes go along; Ctrl-C stops watching, not the task)
27
29
  dl runs your tasks and their pull requests
28
30
  dl watch ID follow a task dl cancel ID stop one
29
31
  dl pull ID check out a task's branch here
30
- dl servers connected servers (dl servers remove NAME)
31
- 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
32
36
  dl local status agents running on this computer: running?, where, how many fit
33
37
  dl local uninstall [--purge] stop and remove them (--purge also deletes keys and data)
34
38
 
@@ -41,6 +45,7 @@ On the server:
41
45
  dl runs tasks running or done, with their pull requests
42
46
  dl logs [hotcell|autopilot] [-f] the services' logs
43
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)
44
49
  dl uninstall [--purge] remove everything (--purge also removes config and data)
45
50
 
46
51
  up options:
@@ -62,6 +67,7 @@ Used by the laptop's setup (over SSH, as root):
62
67
  install with the keys as one JSON object on stdin; progress as JSON lines
63
68
  dl up --needs [--access ssh] which keys dl up would still need, as JSON; changes nothing
64
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
65
71
  `;
66
72
  export async function main(argv, io = {
67
73
  out: (text) => process.stdout.write(text),
@@ -92,6 +98,8 @@ export async function main(argv, io = {
92
98
  "answers-stdin": { type: "boolean" },
93
99
  events: { type: "string" },
94
100
  needs: { type: "boolean" },
101
+ identity: { type: "string" },
102
+ stdin: { type: "boolean" },
95
103
  },
96
104
  });
97
105
  }
@@ -220,7 +228,7 @@ export async function main(argv, io = {
220
228
  return 0;
221
229
  }
222
230
  case "setup":
223
- return await setup({ io: laptopIO, terminal, localSetup: (input) => setUpOnThisComputer(input) });
231
+ return await setup({ io: laptopIO, terminal, localSetup: (input) => setUpOnThisComputer(input), ...(values.identity ? { identityFile: values.identity } : {}) });
224
232
  case "connect": {
225
233
  const url = parsed.positionals[1];
226
234
  if (!url) {
@@ -265,6 +273,8 @@ export async function main(argv, io = {
265
273
  }
266
274
  case "servers":
267
275
  return await servers(parsed.positionals.slice(1), laptopIO);
276
+ case "use":
277
+ return await use(parsed.positionals.slice(1), laptopIO);
268
278
  case "runs":
269
279
  // On a server, its runs; on a laptop, the tasks it sent.
270
280
  if (!(await readState(system))) {
@@ -293,6 +303,18 @@ export async function main(argv, io = {
293
303
  return await serverRunsCommand(system, io.out, colors);
294
304
  return await logsCommand(system, [...rest, ...(values.follow ? ["-f"] : [])]);
295
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
+ }
296
318
  case "local":
297
319
  return await localCommand(parsed.positionals.slice(1), { purge: Boolean(values.purge) }, io, colors, ui);
298
320
  case "uninstall":
@@ -321,10 +343,10 @@ export async function main(argv, io = {
321
343
  const NOT_A_SERVER = (c) => `
322
344
  ${c.bold("Directionally Local")} ${c.dim("isn't set up on this machine.")}
323
345
 
324
- 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,
325
347
  get a pull request back.
326
348
 
327
- ${c.dim("Set it up from your laptop (asks a few questions):")}
349
+ ${c.dim("Set it up here, or on a server over SSH (asks a few questions):")}
328
350
  dl setup
329
351
 
330
352
  ${c.dim("Or on a server (as root, on Ubuntu or Debian):")}
package/dist/doctor.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { detectHost, MIN_DISK_GB } from "./detect.js";
2
2
  import { nodeAdvisory } from "./node-advisory.js";
3
3
  import { AUTOPILOT_PORT, AUTO_UPGRADES, HOTCELL_PORT, NODE_AUTO_UPDATES, PATHS, SERVICES, parseEnvFile } from "./layout.js";
4
+ import { fileMtime, modelPricesHealth } from "./model-prices.js";
4
5
  import { describeAccess, readState } from "./state.js";
5
6
  import { palette } from "./ui.js";
6
7
  /** `directionallylocal doctor`: every moving part, with a fix for each failure. */
7
- export async function doctor(system) {
8
+ export async function doctor(system, now = new Date()) {
8
9
  const checks = [];
9
10
  const add = (check) => checks.push(check);
10
11
  const state = await readState(system);
@@ -45,6 +46,8 @@ export async function doctor(system) {
45
46
  const keys = await system.probe("runuser", ["-u", "hotcell", "--", "env", `HOTCELL_HOME=${PATHS.hotcellHome}`, "HOTCELL_KEYSTORE=file", "/usr/bin/node", `${PATHS.current}/node_modules/hotcell/dist/index.js`, "keys", "ls"]);
46
47
  const hasModelKey = keys.code === 0 && /^\s*openrouter\b/m.test(keys.stdout);
47
48
  add({ name: "model key", ok: hasModelKey, detail: hasModelKey ? "OpenRouter key in Hotcell" : "no OpenRouter key in Hotcell", fix: "sudo dl up (asks for it)" });
49
+ const prices = modelPricesHealth(await system.readFile(PATHS.modelPrices), await fileMtime(system, PATHS.modelPrices), now, "dl up");
50
+ add({ name: "model prices", ok: prices.ok, ...(prices.warn ? { warn: true } : {}), detail: prices.detail, fix: "sudo dl up (downloads them from openrouter.ai)" });
48
51
  const github = Boolean(parseEnvFile(await system.readFile(PATHS.githubEnv)).GITHUB_TOKEN);
49
52
  add({ name: "github", ok: github, detail: github ? "token configured" : "no token; runs can't push or open PRs", fix: "sudo dl up (asks for it)" });
50
53
  const autopilot = (await system.probe("curl", ["-s", "-o", "/dev/null", "-w", "%{http_code}", `http://127.0.0.1:${AUTOPILOT_PORT}/api/v1/health`])).stdout.trim();
@@ -63,9 +66,9 @@ export function formatChecks(checks, color = false) {
63
66
  const c = palette(color);
64
67
  const width = Math.max(...checks.map((check) => check.name.length)) + 2;
65
68
  const rows = checks.map((check) => {
66
- const glyph = check.ok ? c.green("✓") : c.red("✗");
69
+ const glyph = !check.ok ? c.red("✗") : check.warn ? c.yellow("!") : c.green("✓");
67
70
  const fix = !check.ok && check.fix ? `\n ${c.dim(`fix: ${check.fix}`)}` : "";
68
- return ` ${glyph} ${check.name.padEnd(width)}${check.ok ? c.dim(check.detail) : c.red(check.detail)}${fix}`;
71
+ return ` ${glyph} ${check.name.padEnd(width)}${!check.ok ? c.red(check.detail) : check.warn ? c.yellow(check.detail) : c.dim(check.detail)}${fix}`;
69
72
  });
70
73
  const failed = checks.filter((check) => !check.ok).length;
71
74
  const verdict = failed === 0 ? `${c.green("✓")} ${c.bold("All good")}` : `${c.red("✗")} ${c.bold(`${failed} to fix`)}`;
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
+ }