directionallylocal 0.3.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 +33 -11
- package/dist/keys.js +188 -0
- package/dist/laptop/commands.js +120 -24
- package/dist/laptop/config.js +108 -22
- package/dist/laptop/credentials.js +2 -2
- package/dist/laptop/keys.js +133 -0
- package/dist/laptop/setup.js +101 -53
- package/dist/laptop/ssh.js +11 -6
- package/dist/local/keys.js +100 -0
- package/dist/local/setup.js +1 -1
- package/dist/local/test-support/fake-computer.js +20 -3
- package/dist/up.js +6 -4
- package/package.json +1 -1
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:
|
|
18
|
-
Send a task
|
|
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
|
|
23
|
-
dl setup set up
|
|
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
|
|
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
|
|
31
|
-
|
|
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
|
-
|
|
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
|
|
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/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
|
+
}
|
package/dist/laptop/commands.js
CHANGED
|
@@ -1,23 +1,29 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
import { homedir, hostname } from "node:os";
|
|
4
5
|
import { promisify } from "node:util";
|
|
5
6
|
import { palette } from "../ui.js";
|
|
6
7
|
import { RemoteApiError, RemoteClient, TERMINAL_STATUSES } from "./client.js";
|
|
7
|
-
import { defaultRemoteName, loadRemotes, normalizeServerUrl, REMOTE_NAME_RE, removeRemote, resolveRemote, saveRemote } from "./config.js";
|
|
8
|
+
import { defaultRemoteName, loadRemotes, loadRemotesFile, normalizeServerUrl, recordLastUsed, REMOTE_NAME_RE, removeRemote, renameRemote, resolveRemote, resolveTarget, saveRemote, setDefaultRemote, } from "./config.js";
|
|
9
|
+
import { autopilotConfigPath } from "./credentials.js";
|
|
10
|
+
import { PAIRED_NAME } from "../local/layout.js";
|
|
8
11
|
import { detectGitHubRepository, snapshotWorkingTree } from "./git.js";
|
|
9
12
|
import { sshCommandLine } from "./ssh.js";
|
|
10
13
|
import { openBrowser } from "./open-browser.js";
|
|
11
14
|
import { withConnections } from "./tunnel.js";
|
|
12
15
|
/**
|
|
13
|
-
* `dl` on a laptop:
|
|
14
|
-
* pull requests. It talks to the server's API directly (the
|
|
15
|
-
* `--on` uses, and shares its list of servers), so the laptop needs
|
|
16
|
+
* `dl` on a laptop: send tasks to where agents run (this computer, or your own server),
|
|
17
|
+
* follow them, and check out the pull requests. It talks to the server's API directly (the
|
|
18
|
+
* same one Autopilot's `--on` uses, and shares its list of servers), so the laptop needs
|
|
19
|
+
* nothing else.
|
|
16
20
|
* Servers set up with `dl setup` are reached through an SSH tunnel that each command
|
|
17
21
|
* opens and closes (see tunnel.ts); `open` lets tests swap the tunnel out.
|
|
18
22
|
*/
|
|
19
23
|
const execFileAsync = promisify(execFile);
|
|
20
24
|
const RUN_END_EVENTS = new Set(["completed", "failed", "cancelled", "interrupted"]);
|
|
25
|
+
/** The model a task gets when neither -m nor the laptop's Autopilot picks one the server offers. */
|
|
26
|
+
export const DEFAULT_MODEL = "moonshotai/kimi-k2.6";
|
|
21
27
|
const processIO = {
|
|
22
28
|
out: (text) => process.stdout.write(text),
|
|
23
29
|
err: (text) => process.stderr.write(text),
|
|
@@ -60,10 +66,11 @@ export async function connect(input, io = processIO) {
|
|
|
60
66
|
* checkout (uncommitted changes go along). Follows it until it ends; Ctrl-C only detaches.
|
|
61
67
|
*/
|
|
62
68
|
export async function run(input, io = processIO) {
|
|
63
|
-
const remote = await
|
|
64
|
-
|
|
69
|
+
const { remote, reason } = await resolveTarget(input.server);
|
|
70
|
+
const preferred = input.preferredModel ?? await (input.autopilotModel ?? (() => readAutopilotModel()))();
|
|
71
|
+
return withConnections(input.open, async (connections) => runOn(await connections.client(remote), remote, reason, { ...input, ...(preferred ? { preferredModel: preferred } : {}) }, io));
|
|
65
72
|
}
|
|
66
|
-
async function runOn(client, remote, input, io) {
|
|
73
|
+
async function runOn(client, remote, reason, input, io) {
|
|
67
74
|
const c = palette(io.color === true);
|
|
68
75
|
const repository = input.repository ?? await detectGitHubRepository(input.cwd);
|
|
69
76
|
const snapshot = await snapshotWorkingTree(input.cwd);
|
|
@@ -73,7 +80,8 @@ async function runOn(client, remote, input, io) {
|
|
|
73
80
|
throw new Error(`${remote.name} has no workspace this laptop can use`);
|
|
74
81
|
const model = pickModel(models, input.model, input.preferredModel);
|
|
75
82
|
const changes = snapshot.files.length ? ` + ${snapshot.files.length} local change${snapshot.files.length === 1 ? "" : "s"}` : "";
|
|
76
|
-
|
|
83
|
+
const why = reason === "default" || reason === "last used" ? ` ${c.dim(`(${reason})`)}` : "";
|
|
84
|
+
io.err(`\n ${c.cyan("·")} Sending to ${c.bold(remote.name)}${why}: ${repository} at ${snapshot.baseCommit.slice(0, 7)}${changes} ${c.dim(model)}\n`);
|
|
77
85
|
const conversation = await client.createCodeConversation({
|
|
78
86
|
workspaceId: workspace.id,
|
|
79
87
|
model,
|
|
@@ -83,6 +91,8 @@ async function runOn(client, remote, input, io) {
|
|
|
83
91
|
idempotencyKey: `dl-${randomUUID()}`,
|
|
84
92
|
});
|
|
85
93
|
await client.submitTurn(conversation.conversationId, input.task, `dl-${randomUUID()}`);
|
|
94
|
+
// Only a fallback (a default, or the only place, always wins), so failing to write it is harmless.
|
|
95
|
+
await recordLastUsed(remote.name).catch(() => undefined);
|
|
86
96
|
const id = conversation.conversationId.slice(0, 8);
|
|
87
97
|
io.err(`${rewrite(io)} ${c.green("✓")} Started ${c.bold(id)} on ${remote.name} ${c.dim(`branch ${conversation.branch ?? "?"}`)}\n`);
|
|
88
98
|
if (input.detach) {
|
|
@@ -96,7 +106,7 @@ async function runOn(client, remote, input, io) {
|
|
|
96
106
|
export async function runs(input, io = processIO) {
|
|
97
107
|
const remotes = input.server ? [await resolveRemote(input.server)] : await loadRemotes();
|
|
98
108
|
if (remotes.length === 0)
|
|
99
|
-
throw new Error("
|
|
109
|
+
throw new Error("Nothing is set up yet. Run: dl setup (or, for a server someone else set up: dl connect https://your-server)");
|
|
100
110
|
return withConnections(input.open, (connections) => listRuns(remotes, connections, input.json === true, io));
|
|
101
111
|
}
|
|
102
112
|
async function listRuns(remotes, connections, json, io) {
|
|
@@ -173,9 +183,11 @@ export async function pull(input, io = processIO) {
|
|
|
173
183
|
}
|
|
174
184
|
io.out(` ${c.green("✓")} On ${c.bold(branch)}${found.pullRequestURL ? ` ${c.dim(found.pullRequestURL)}` : ""}\n`);
|
|
175
185
|
}
|
|
176
|
-
/** `dl servers [remove NAME]`: the servers this laptop is connected to. */
|
|
186
|
+
/** `dl servers [remove NAME | rename OLD NEW]`: the servers this laptop is connected to. */
|
|
177
187
|
export async function servers(args, io = processIO) {
|
|
178
188
|
const c = palette(io.color === true);
|
|
189
|
+
if (args[0] === "rename")
|
|
190
|
+
return renameServer(args.slice(1), io);
|
|
179
191
|
if (args[0] === "remove") {
|
|
180
192
|
const name = args[1] ?? "";
|
|
181
193
|
const removed = (await loadRemotes()).find((remote) => remote.name === name);
|
|
@@ -189,13 +201,65 @@ export async function servers(args, io = processIO) {
|
|
|
189
201
|
}
|
|
190
202
|
const remotes = await loadRemotes();
|
|
191
203
|
if (remotes.length === 0) {
|
|
192
|
-
io.out(`\n
|
|
204
|
+
io.out(`\n Nothing set up yet. ${c.bold("dl setup")} ${c.dim("or, for a server someone else set up:")} ${c.bold("dl connect https://your-server")}\n\n`);
|
|
193
205
|
return 0;
|
|
194
206
|
}
|
|
207
|
+
const current = await defaultName();
|
|
195
208
|
io.out("\n");
|
|
196
209
|
for (const remote of remotes)
|
|
197
|
-
io.out(` ${c
|
|
198
|
-
io.out("\n");
|
|
210
|
+
io.out(` ${mark(remote, current, c)} ${remote.name.padEnd(16)} ${where(remote)} ${c.dim(`until ${remote.expiresAt.slice(0, 10)}`)}\n`);
|
|
211
|
+
io.out(remotes.length > 1 ? `\n ${c.dim(`● is where tasks go without --server. Change it: dl use NAME`)}\n\n` : "\n");
|
|
212
|
+
return 0;
|
|
213
|
+
}
|
|
214
|
+
/** `dl use [NAME]`: set, or show, where commands go when no --server is given. */
|
|
215
|
+
export async function use(args, io = processIO) {
|
|
216
|
+
const c = palette(io.color === true);
|
|
217
|
+
const name = args[0];
|
|
218
|
+
if (name === undefined) {
|
|
219
|
+
const file = await loadRemotesFile();
|
|
220
|
+
if (file.remotes.length === 0) {
|
|
221
|
+
io.out(` Nothing set up yet. ${c.bold("dl setup")}\n`);
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
const current = await defaultName();
|
|
225
|
+
io.out(current
|
|
226
|
+
? ` Tasks go to ${c.bold(current)} unless you pass --server NAME.${file.remotes.length > 1 ? ` ${c.dim(`Change it: dl use NAME (${file.remotes.map((entry) => entry.name).join(", ")})`)}` : ""}\n`
|
|
227
|
+
: ` No default yet. Pick one: dl use NAME ${c.dim(`(${file.remotes.map((entry) => entry.name).join(", ")})`)}\n`);
|
|
228
|
+
return 0;
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const remote = await setDefaultRemote(name);
|
|
232
|
+
io.out(` ${c.green("✓")} Tasks now go to ${c.bold(remote.name)} ${c.dim(where(remote))} unless you pass --server NAME.\n`);
|
|
233
|
+
return 0;
|
|
234
|
+
}
|
|
235
|
+
catch (error) {
|
|
236
|
+
io.err(` ${c.red("✗")} ${describeError(error)}\n`);
|
|
237
|
+
return 1;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** Where a command without --server goes, or undefined when that's ambiguous. */
|
|
241
|
+
async function defaultName() {
|
|
242
|
+
return resolveTarget(undefined).then((target) => target.remote.name, () => undefined);
|
|
243
|
+
}
|
|
244
|
+
function mark(remote, current, c) {
|
|
245
|
+
return remote.name === current ? c.green("●") : c.dim("○");
|
|
246
|
+
}
|
|
247
|
+
/** `dl servers rename OLD NEW`: only this laptop's name for it; the server doesn't change. */
|
|
248
|
+
export async function renameServer(args, io = processIO, path) {
|
|
249
|
+
const c = palette(io.color === true);
|
|
250
|
+
const [from, to] = args;
|
|
251
|
+
if (!from || !to || args.length > 2) {
|
|
252
|
+
io.err(` Usage: dl servers rename OLD NEW ${c.dim("(names: lowercase letters, digits, and dashes)")}\n`);
|
|
253
|
+
return 2;
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
await renameRemote(from, to, path);
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
io.err(` ${c.red("✗")} ${error.message}.\n`.replace(/\.\.\n$/, ".\n"));
|
|
260
|
+
return 1;
|
|
261
|
+
}
|
|
262
|
+
io.out(` ${c.green("✓")} Renamed ${from} to ${c.bold(to)} ${c.dim(`dl run --server ${to} …`)}\n`);
|
|
199
263
|
return 0;
|
|
200
264
|
}
|
|
201
265
|
/** `dl` on a laptop: what this is, which servers it's connected to, what to type next. */
|
|
@@ -213,9 +277,10 @@ export async function laptopHome(io = processIO, open) {
|
|
|
213
277
|
total += list?.length ?? 0;
|
|
214
278
|
}
|
|
215
279
|
});
|
|
280
|
+
const current = await defaultName();
|
|
216
281
|
io.out(`\n ${c.bold("Directionally Local")} ${c.dim("on this laptop")}\n\n`);
|
|
217
|
-
io.out("
|
|
218
|
-
io.out(` ${c.dim("
|
|
282
|
+
io.out(" Coding agents that run on this computer or your own server: send a task, get a pull request back.\n\n");
|
|
283
|
+
io.out(` ${c.dim("Runs on".padEnd(11))}${remotes.map((remote) => `${mark(remote, current, c)} ${remote.name} ${c.dim(where(remote))}`).join(", ")} ${c.dim(remotes.length > 1 ? "dl servers · dl use NAME" : "dl servers")}\n`);
|
|
219
284
|
io.out(` ${c.dim("Tasks".padEnd(11))}${running} running · ${total} in all ${c.dim("dl runs")}\n\n`);
|
|
220
285
|
io.out(` ${c.dim("Send a task, from inside a GitHub repository:")}\n ${c.bold('dl run "fix the flaky checkout test"')}\n\n`);
|
|
221
286
|
return true;
|
|
@@ -326,22 +391,53 @@ async function findRun(id, server, connections) {
|
|
|
326
391
|
throw new Error(`${id} matches several tasks; use more characters`);
|
|
327
392
|
return matches[0];
|
|
328
393
|
}
|
|
329
|
-
|
|
394
|
+
/**
|
|
395
|
+
* The task's model: -m/--model; else the laptop's Autopilot default, if the server offers it;
|
|
396
|
+
* else DEFAULT_MODEL, if offered. Never just the first in the server's list (that's the
|
|
397
|
+
* whole OpenRouter catalog, in no useful order).
|
|
398
|
+
*/
|
|
399
|
+
export function pickModel(models, requested, preferred) {
|
|
400
|
+
const how = `Pick one: dl run -m <model> "task" (model IDs: https://openrouter.ai/models)`;
|
|
330
401
|
if (requested) {
|
|
331
402
|
if (!models.includes(requested))
|
|
332
|
-
throw new Error(`The server doesn't offer ${requested}`);
|
|
403
|
+
throw new Error(`The server doesn't offer ${requested}. ${how}`);
|
|
333
404
|
return requested;
|
|
334
405
|
}
|
|
335
406
|
if (preferred && models.includes(preferred))
|
|
336
407
|
return preferred;
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
408
|
+
if (models.includes(DEFAULT_MODEL))
|
|
409
|
+
return DEFAULT_MODEL;
|
|
410
|
+
if (models.length === 0)
|
|
411
|
+
throw new Error("The server offers no models; check its OpenRouter key (on the server: dl doctor)");
|
|
412
|
+
const tried = preferred && preferred !== DEFAULT_MODEL ? `your Autopilot model (${preferred}) or ${DEFAULT_MODEL}` : DEFAULT_MODEL;
|
|
413
|
+
throw new Error(`The server doesn't offer ${tried}. ${how}`);
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* The laptop's Autopilot default model: KIMI_MODEL (Autopilot's own override) or the
|
|
417
|
+
* `model` in its config. undefined when neither is set or the config can't be read.
|
|
418
|
+
*/
|
|
419
|
+
export async function readAutopilotModel(sources = {}) {
|
|
420
|
+
const env = sources.env ?? process.env;
|
|
421
|
+
const fromEnv = env.KIMI_MODEL?.trim();
|
|
422
|
+
if (fromEnv)
|
|
423
|
+
return fromEnv;
|
|
424
|
+
const read = sources.readFile ?? ((path) => readFile(path, "utf8").catch(() => undefined));
|
|
425
|
+
const raw = await read(autopilotConfigPath(env, sources.home ?? homedir()));
|
|
426
|
+
if (!raw)
|
|
427
|
+
return undefined;
|
|
428
|
+
try {
|
|
429
|
+
const model = JSON.parse(raw).model;
|
|
430
|
+
return typeof model === "string" && model.trim() ? model.trim() : undefined;
|
|
431
|
+
}
|
|
432
|
+
catch {
|
|
433
|
+
return undefined;
|
|
434
|
+
}
|
|
341
435
|
}
|
|
342
|
-
/** Where a
|
|
436
|
+
/** Where a place is, as people know it: this computer, its URL, or the SSH destination its tunnel goes to. */
|
|
343
437
|
function where(remote) {
|
|
344
|
-
|
|
438
|
+
if (remote.ssh)
|
|
439
|
+
return `ssh ${remote.ssh.target}${remote.ssh.port ? `:${remote.ssh.port}` : ""}`;
|
|
440
|
+
return remote.name === PAIRED_NAME ? "this computer" : remote.url;
|
|
345
441
|
}
|
|
346
442
|
function clientName() {
|
|
347
443
|
const host = hostname().replace(/\.local$/, "").replace(/[^\p{L}\p{N} ._'()@-]/gu, "-").slice(0, 40) || "laptop";
|