@netnodeag/kraftwerk 0.100.1 → 0.101.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/README.md +37 -0
- package/dist/cli/cloud.d.ts +1 -0
- package/dist/cli/cloud.js +1 -1
- package/dist/cli/join.d.ts +2 -0
- package/dist/cli/join.js +50 -0
- package/dist/cli/kraftwerk.js +3 -0
- package/dist/client/routes.d.ts +2 -0
- package/dist/client/routes.js +2 -0
- package/dist/core/git.d.ts +12 -0
- package/dist/core/git.js +33 -2
- package/dist/server/api/cloud.d.ts +4 -0
- package/dist/server/api/cloud.js +14 -0
- package/dist/server/api/git.d.ts +13 -1
- package/dist/server/api/git.js +39 -1
- package/dist/server/api/index.d.ts +10 -1
- package/dist/server/cloud.d.ts +4 -0
- package/dist/server/cloud.js +13 -0
- package/dist/server/join.d.ts +34 -0
- package/dist/server/join.js +102 -0
- package/dist/server/sync-setup.d.ts +30 -0
- package/dist/server/sync-setup.js +87 -0
- package/package.json +1 -1
- package/web/dist/assets/{dist-CYnkW4NZ.js → dist-Bd_SvBeU.js} +1 -1
- package/web/dist/assets/{dist-Dj1JIIbI.js → dist-BgG4OIU9.js} +1 -1
- package/web/dist/assets/{dist-DxHapyfL.js → dist-Bi5Y6JmO.js} +1 -1
- package/web/dist/assets/{dist-Dhqv4G4v.js → dist-Cfj7O2BI.js} +1 -1
- package/web/dist/assets/{dist-OUSFQqAo.js → dist-CiGlBloC.js} +1 -1
- package/web/dist/assets/{dist-KYJrjjHE.js → dist-Co1Cz1EB.js} +1 -1
- package/web/dist/assets/{dist-C6Hh2gvr.js → dist-Cq4ezkbk.js} +1 -1
- package/web/dist/assets/{dist-DmqwXVk5.js → dist-DTxqCKQj.js} +1 -1
- package/web/dist/assets/{dist-BQht4Kxn.js → dist-DXGv3DRS.js} +1 -1
- package/web/dist/assets/{dist-DQsdt9qV.js → dist-Db9KgP0W.js} +1 -1
- package/web/dist/assets/dist-DeUP_9vJ.js +1 -0
- package/web/dist/assets/{editor-DjVpjnNv.js → editor-CH-WK0Ag.js} +3 -3
- package/web/dist/assets/{index-BV1cBJKv.js → index-CnwVoHX3.js} +19 -19
- package/web/dist/index.html +1 -1
- package/web/dist/assets/dist-CxDUjCCR.js +0 -1
package/README.md
CHANGED
|
@@ -542,6 +542,43 @@ writes `users: local` and leaves the machine as it is. Only an owner
|
|
|
542
542
|
switches a workspace in cloud mode, and two switches never run at once. `GET /api/workspace/cloud` reports the mode and
|
|
543
543
|
its steps, `POST /api/workspace/cloud {mode}` switches.
|
|
544
544
|
|
|
545
|
+
### Start on the platform: `kraftwerk join`
|
|
546
|
+
|
|
547
|
+
The quickest way in starts on kraftwerk cloud: sign up, click **New
|
|
548
|
+
workspace**, and copy the one command it shows:
|
|
549
|
+
|
|
550
|
+
```bash
|
|
551
|
+
npm i -g @netnodeag/kraftwerk && kraftwerk join https://srv.kraftwerk-cloud.netnode.cloud/join/XKQ7-2MPD-HH3A
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
It installs kraftwerk for good (the daemon then runs from that install), starts
|
|
555
|
+
the daemon if it does not run, links this machine to your account
|
|
556
|
+
(no claim code), clones the workspace from kraftwerk sync into `./<its name>`
|
|
557
|
+
(or `kraftwerk join <link> <folder>`) and opens it in the browser — already
|
|
558
|
+
in cloud mode. An invite works the same way: the person accepts it in the
|
|
559
|
+
browser (signing up on the way), and the page shows the same command. A
|
|
560
|
+
workspace's page in the cloud gives you a fresh command for each further
|
|
561
|
+
machine (*Install on a machine*). Running it again on a folder that holds the
|
|
562
|
+
workspace just opens it. `POST /api/cloud/join {link, cwd, dir?}` on the
|
|
563
|
+
daemon does the work.
|
|
564
|
+
|
|
565
|
+
### kraftwerk sync: the workspace's files in the cloud
|
|
566
|
+
|
|
567
|
+
In cloud mode a workspace's history can live in its own repository in
|
|
568
|
+
kraftwerk cloud (`<cloud>/git/<id>.git`) — no GitHub needed to share a
|
|
569
|
+
workspace. The daemon brings the machine's key along when git talks to that
|
|
570
|
+
address (a URL-scoped `http.extraHeader` in git's environment, never written
|
|
571
|
+
to a config), so there is no token to paste and no credential helper.
|
|
572
|
+
|
|
573
|
+
Workspaces made on the platform start with it. For one you started locally,
|
|
574
|
+
switch it to cloud, then on the **Git** page click *set up kraftwerk sync*
|
|
575
|
+
(`POST /api/git/sync-setup`): a repository if there is none, `git:` on with
|
|
576
|
+
`autosync: push`, the remote, a first commit, a push. A remote of your own
|
|
577
|
+
(GitHub, GitLab, a server in-house) is expert mode: kraftwerk never replaces
|
|
578
|
+
it, and the Git page says which of the two a workspace uses
|
|
579
|
+
(*managed by kraftwerk* or *own git provider · expert mode*) and shows the
|
|
580
|
+
remote's address.
|
|
581
|
+
|
|
545
582
|
### This machine in the kraftwerk cloud
|
|
546
583
|
|
|
547
584
|
The kraftwerk cloud is the `~/.kraftwerk` registry made reachable over the
|
package/dist/cli/cloud.d.ts
CHANGED
package/dist/cli/cloud.js
CHANGED
|
@@ -26,7 +26,7 @@ const fail = (message, code = 1) => {
|
|
|
26
26
|
console.error(chalk.red(`✖ ${message}`));
|
|
27
27
|
process.exit(code);
|
|
28
28
|
};
|
|
29
|
-
function openBrowser(url) {
|
|
29
|
+
export function openBrowser(url) {
|
|
30
30
|
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
31
31
|
try {
|
|
32
32
|
spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
|
package/dist/cli/join.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
import { findDaemon } from "../core/daemon.js";
|
|
3
|
+
import { tildify } from "../core/instances.js";
|
|
4
|
+
import { openBrowser } from "./cloud.js";
|
|
5
|
+
import { startDaemon } from "./daemon-control.js";
|
|
6
|
+
const fail = (message, code = 1) => {
|
|
7
|
+
console.error(chalk.red(`✖ ${message}`));
|
|
8
|
+
process.exit(code);
|
|
9
|
+
};
|
|
10
|
+
export function registerJoinCommand(program) {
|
|
11
|
+
program
|
|
12
|
+
.command("join")
|
|
13
|
+
.description("Bring a workspace from kraftwerk cloud onto this machine: the link from the platform (new workspace, install, accepted invite) — clones it into ./<name> and opens it")
|
|
14
|
+
.argument("<link>", "the join link (https://…/join/XXXX-XXXX-XXXX) or its code")
|
|
15
|
+
.argument("[folder]", "where the workspace goes (default: ./<its name>)")
|
|
16
|
+
.option("--no-open", "Do not open the browser")
|
|
17
|
+
.option("--json", "Machine-readable output")
|
|
18
|
+
.action(async (link, folder, opts) => {
|
|
19
|
+
if (!(await findDaemon())) {
|
|
20
|
+
if (!opts.json)
|
|
21
|
+
console.log(chalk.dim("kraftwerk runs as a daemon on this machine — starting it"));
|
|
22
|
+
await startDaemon({});
|
|
23
|
+
}
|
|
24
|
+
const daemon = (await findDaemon()) ?? fail("the daemon did not come up — `kraftwerk daemon logs`");
|
|
25
|
+
if (!opts.json)
|
|
26
|
+
process.stdout.write(chalk.dim("joining through kraftwerk cloud …"));
|
|
27
|
+
const r = await fetch(`http://127.0.0.1:${daemon.port}/api/cloud/join`, {
|
|
28
|
+
method: "POST",
|
|
29
|
+
headers: { "content-type": "application/json" },
|
|
30
|
+
body: JSON.stringify({ link, cwd: process.cwd(), ...(folder ? { dir: folder } : {}) }),
|
|
31
|
+
signal: AbortSignal.timeout(10 * 60_000),
|
|
32
|
+
}).catch((err) => fail(`the daemon did not answer: ${err.message}`));
|
|
33
|
+
if (!opts.json)
|
|
34
|
+
process.stdout.write("\n");
|
|
35
|
+
const data = (await r.json().catch(() => ({})));
|
|
36
|
+
if (!r.ok)
|
|
37
|
+
fail(data.error ?? `${r.status} from the daemon`);
|
|
38
|
+
if (opts.json) {
|
|
39
|
+
console.log(JSON.stringify(data, null, 2));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
console.log(`${chalk.green("✔")} ${chalk.bold(data.workspace.name)} ${chalk.dim(`(${data.workspace.id}, ${data.role})`)} is on this machine`);
|
|
43
|
+
console.log(` ${chalk.dim("folder")} ${tildify(data.root)}${data.cloned ? "" : chalk.dim(" (was already here)")}`);
|
|
44
|
+
console.log(` ${chalk.dim("account")} ${data.account} — this machine is linked to it`);
|
|
45
|
+
console.log(` ${chalk.dim("sync")} kraftwerk sync: what you commit goes to the cloud, the others' changes come in`);
|
|
46
|
+
console.log(` ${chalk.dim("open")} ${chalk.cyan(data.workspace.url)}`);
|
|
47
|
+
if (opts.open)
|
|
48
|
+
openBrowser(data.workspace.url);
|
|
49
|
+
});
|
|
50
|
+
}
|
package/dist/cli/kraftwerk.js
CHANGED
|
@@ -28,6 +28,7 @@ import { registerJournalCommands } from "./journal.js";
|
|
|
28
28
|
import { registerWhoamiCommand } from "./whoami.js";
|
|
29
29
|
import { registerCloudCommands } from "./cloud.js";
|
|
30
30
|
import { registerInviteCommand } from "./invite.js";
|
|
31
|
+
import { registerJoinCommand } from "./join.js";
|
|
31
32
|
import { applyDotenv } from "../dotenv.js";
|
|
32
33
|
import { resolveWorkspace } from "../config.js";
|
|
33
34
|
import { registerRoutineCommands } from "./routines.js";
|
|
@@ -60,6 +61,7 @@ import { runUi } from "./ui.js";
|
|
|
60
61
|
* kraftwerk cloud [on|off|status] this machine in the kraftwerk cloud (the daemon registers it)
|
|
61
62
|
* kraftwerk login / logout claim this machine into your cloud account (in the browser) / release it
|
|
62
63
|
* kraftwerk invite [--role owner] invite a remote member into this workspace (join code + link, via the daemon)
|
|
64
|
+
* kraftwerk join <link> [folder] bring a workspace from kraftwerk cloud onto this machine (claim, clone, open)
|
|
63
65
|
* kraftwerk doctor [--fix] preflight: harness CLIs, docker, workflows, env, routine runners
|
|
64
66
|
* kraftwerk validate [paths...] validate without executing
|
|
65
67
|
*
|
|
@@ -325,6 +327,7 @@ registerJournalCommands(program);
|
|
|
325
327
|
registerWhoamiCommand(program);
|
|
326
328
|
registerCloudCommands(program);
|
|
327
329
|
registerInviteCommand(program);
|
|
330
|
+
registerJoinCommand(program);
|
|
328
331
|
program
|
|
329
332
|
.command("ui")
|
|
330
333
|
.description("Start the inspector web UI for this project's runs and workflows")
|
package/dist/client/routes.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ export declare const ROUTES: {
|
|
|
53
53
|
readonly "chats.steer": readonly ["POST", "/api/chats/:id/steer"];
|
|
54
54
|
readonly "chats.stopTask": readonly ["POST", "/api/chats/:id/task-stop"];
|
|
55
55
|
readonly "cloud.invite": readonly ["POST", "/api/cloud/invite"];
|
|
56
|
+
readonly "cloud.join": readonly ["POST", "/api/cloud/join"];
|
|
56
57
|
readonly "cloud.set": readonly ["POST", "/api/cloud"];
|
|
57
58
|
readonly "cloud.status": readonly ["GET", "/api/cloud"];
|
|
58
59
|
readonly "cloud.sync": readonly ["POST", "/api/cloud/sync"];
|
|
@@ -89,6 +90,7 @@ export declare const ROUTES: {
|
|
|
89
90
|
readonly "git.fetch": readonly ["POST", "/api/git/fetch"];
|
|
90
91
|
readonly "git.pull": readonly ["POST", "/api/git/pull"];
|
|
91
92
|
readonly "git.push": readonly ["POST", "/api/git/push"];
|
|
93
|
+
readonly "git.setupSync": readonly ["POST", "/api/git/sync-setup"];
|
|
92
94
|
readonly "git.status": readonly ["GET", "/api/git"];
|
|
93
95
|
readonly "hub.close": readonly ["POST", "/api/hub/close"];
|
|
94
96
|
readonly "hub.list": readonly ["GET", "/api/hub"];
|
package/dist/client/routes.js
CHANGED
|
@@ -54,6 +54,7 @@ export const ROUTES = {
|
|
|
54
54
|
"chats.steer": ["POST", "/api/chats/:id/steer"],
|
|
55
55
|
"chats.stopTask": ["POST", "/api/chats/:id/task-stop"],
|
|
56
56
|
"cloud.invite": ["POST", "/api/cloud/invite"],
|
|
57
|
+
"cloud.join": ["POST", "/api/cloud/join"],
|
|
57
58
|
"cloud.set": ["POST", "/api/cloud"],
|
|
58
59
|
"cloud.status": ["GET", "/api/cloud"],
|
|
59
60
|
"cloud.sync": ["POST", "/api/cloud/sync"],
|
|
@@ -90,6 +91,7 @@ export const ROUTES = {
|
|
|
90
91
|
"git.fetch": ["POST", "/api/git/fetch"],
|
|
91
92
|
"git.pull": ["POST", "/api/git/pull"],
|
|
92
93
|
"git.push": ["POST", "/api/git/push"],
|
|
94
|
+
"git.setupSync": ["POST", "/api/git/sync-setup"],
|
|
93
95
|
"git.status": ["GET", "/api/git"],
|
|
94
96
|
"hub.close": ["POST", "/api/hub/close"],
|
|
95
97
|
"hub.list": ["GET", "/api/hub"],
|
package/dist/core/git.d.ts
CHANGED
|
@@ -55,6 +55,14 @@ export interface GitStatus {
|
|
|
55
55
|
/** Configured or inferred upstream, absent when the branch tracks nothing. */
|
|
56
56
|
upstream?: string;
|
|
57
57
|
remote?: string;
|
|
58
|
+
/** Where the remote lives (`git remote get-url`), any credentials in it cut out; absent without a remote. */
|
|
59
|
+
remoteUrl?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Who hosts the remote: "kraftwerk" (kraftwerk sync, the workspace's repo in
|
|
62
|
+
* kraftwerk cloud), "custom" (an own git provider — expert mode) or "none"
|
|
63
|
+
* (no remote yet). Set by the API, which knows the cloud.
|
|
64
|
+
*/
|
|
65
|
+
hosting?: "kraftwerk" | "custom" | "none";
|
|
58
66
|
ahead?: number;
|
|
59
67
|
behind?: number;
|
|
60
68
|
/** True when the branches have diverged, which needs a terminal. */
|
|
@@ -90,6 +98,8 @@ export declare function git(args: string[], cwd: string, timeoutMs?: number, env
|
|
|
90
98
|
export declare function sshCommandFor(repoRoot: string): Promise<string>;
|
|
91
99
|
/** A git call that may touch the network: longer timeout, non-interactive ssh. */
|
|
92
100
|
export declare function gitNet(args: string[], repoRoot: string): Promise<GitResult>;
|
|
101
|
+
export declare function setRemoteAuth(fn: () => Record<string, string>): void;
|
|
102
|
+
export declare function remoteAuthEnv(base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
93
103
|
/**
|
|
94
104
|
* Pathspecs are globs by default, so a file called `note[1].md` would not
|
|
95
105
|
* match itself. `:(literal)` turns the pattern off.
|
|
@@ -109,6 +119,8 @@ export declare function parseStatus(out: string): {
|
|
|
109
119
|
* of times, and the nav badge polls it from every open tab, so results are
|
|
110
120
|
* cached for a beat.
|
|
111
121
|
*/
|
|
122
|
+
/** A remote URL fit to show: `https://user:secret@host/x` → `https://host/x`. */
|
|
123
|
+
export declare function withoutCredentials(url: string): string;
|
|
112
124
|
export declare function gitStatus(fresh?: boolean): Promise<GitStatus>;
|
|
113
125
|
/**
|
|
114
126
|
* Unified diff for one changed file. Reading is as sensitive as writing
|
package/dist/core/git.js
CHANGED
|
@@ -135,7 +135,31 @@ export async function sshCommandFor(repoRoot) {
|
|
|
135
135
|
}
|
|
136
136
|
/** A git call that may touch the network: longer timeout, non-interactive ssh. */
|
|
137
137
|
export async function gitNet(args, repoRoot) {
|
|
138
|
-
return git(args, repoRoot, NET_TIMEOUT, { GIT_SSH_COMMAND: await sshCommandFor(repoRoot) });
|
|
138
|
+
return git(args, repoRoot, NET_TIMEOUT, { GIT_SSH_COMMAND: await sshCommandFor(repoRoot), ...remoteAuthEnv() });
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* HTTP credentials git gets for some remotes, by URL prefix → header. The
|
|
142
|
+
* daemon sets one for kraftwerk sync (`<cloud>/git/` → the machine's key, see
|
|
143
|
+
* server/cloud.ts), so a workspace syncs with its cloud repo without a token
|
|
144
|
+
* in a remote URL or a credential helper. They go in through the
|
|
145
|
+
* environment as URL-scoped `http.<prefix>.extraHeader` — never written to a
|
|
146
|
+
* git config, and git sends them to that prefix only.
|
|
147
|
+
*/
|
|
148
|
+
let remoteAuth = () => ({});
|
|
149
|
+
export function setRemoteAuth(fn) {
|
|
150
|
+
remoteAuth = fn;
|
|
151
|
+
}
|
|
152
|
+
export function remoteAuthEnv(base = process.env) {
|
|
153
|
+
const headers = Object.entries(remoteAuth());
|
|
154
|
+
if (headers.length === 0)
|
|
155
|
+
return {};
|
|
156
|
+
const start = Number(base.GIT_CONFIG_COUNT ?? 0) || 0;
|
|
157
|
+
const env = { GIT_CONFIG_COUNT: String(start + headers.length) };
|
|
158
|
+
headers.forEach(([prefix, header], i) => {
|
|
159
|
+
env[`GIT_CONFIG_KEY_${start + i}`] = `http.${prefix}.extraHeader`;
|
|
160
|
+
env[`GIT_CONFIG_VALUE_${start + i}`] = header;
|
|
161
|
+
});
|
|
162
|
+
return env;
|
|
139
163
|
}
|
|
140
164
|
/**
|
|
141
165
|
* Remote/branch names from kraftwerk.yml become git positionals. Config
|
|
@@ -381,6 +405,10 @@ function serial(fn) {
|
|
|
381
405
|
* of times, and the nav badge polls it from every open tab, so results are
|
|
382
406
|
* cached for a beat.
|
|
383
407
|
*/
|
|
408
|
+
/** A remote URL fit to show: `https://user:secret@host/x` → `https://host/x`. */
|
|
409
|
+
export function withoutCredentials(url) {
|
|
410
|
+
return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, "$1");
|
|
411
|
+
}
|
|
384
412
|
export async function gitStatus(fresh = false) {
|
|
385
413
|
const cached = gitState().statusCache;
|
|
386
414
|
if (!fresh && cached && Date.now() - cached.at < CACHE_MS)
|
|
@@ -393,12 +421,14 @@ export async function gitStatus(fresh = false) {
|
|
|
393
421
|
if (!repo)
|
|
394
422
|
return { enabled: true, error: opened.error, autosync: cfg?.autosync, interval: cfg?.interval };
|
|
395
423
|
const { repoRoot } = repo;
|
|
396
|
-
const [head, upstreamRes, status] = await Promise.all([
|
|
424
|
+
const [head, upstreamRes, status, urlRes] = await Promise.all([
|
|
397
425
|
checkedOut(repo),
|
|
398
426
|
git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], repoRoot),
|
|
399
427
|
git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], repoRoot),
|
|
428
|
+
git(["remote", "get-url", repo.cfg.remote], repoRoot),
|
|
400
429
|
]);
|
|
401
430
|
const upstream = upstreamRes.ok ? upstreamRes.stdout.trim() : undefined;
|
|
431
|
+
const remoteUrl = urlRes.ok && urlRes.stdout.trim() ? withoutCredentials(urlRes.stdout.trim()) : undefined;
|
|
402
432
|
let ahead;
|
|
403
433
|
let behind;
|
|
404
434
|
if (upstream) {
|
|
@@ -415,6 +445,7 @@ export async function gitStatus(fresh = false) {
|
|
|
415
445
|
branch: head.branch,
|
|
416
446
|
upstream,
|
|
417
447
|
remote: cfg?.remote ?? repo.cfg.remote,
|
|
448
|
+
remoteUrl,
|
|
418
449
|
ahead,
|
|
419
450
|
behind,
|
|
420
451
|
diverged: !!ahead && !!behind,
|
|
@@ -20,6 +20,10 @@ export declare const cloudRoutes: (import("./router.js").Route<"cloud.invite", i
|
|
|
20
20
|
member: "member";
|
|
21
21
|
owner: "owner";
|
|
22
22
|
}>>;
|
|
23
|
+
}, z.core.$strip>> | import("./router.js").Route<"cloud.join", import("../join.js").JoinResult, "/api/cloud/join", z.ZodObject<{
|
|
24
|
+
link: z.ZodString;
|
|
25
|
+
dir: z.ZodOptional<z.ZodString>;
|
|
26
|
+
cwd: z.ZodString;
|
|
23
27
|
}, z.core.$strip>> | import("./router.js").Route<"cloud.set", {
|
|
24
28
|
daemon: boolean;
|
|
25
29
|
url: string;
|
package/dist/server/api/cloud.js
CHANGED
|
@@ -2,6 +2,7 @@ import * as z from "zod";
|
|
|
2
2
|
import { writeCloudFile } from "../../core/cloud.js";
|
|
3
3
|
import { applyMachineCloud, cloudStatus, createWorkspaceInvite, syncMachineCloud, unlinkMachineCloud } from "../cloud.js";
|
|
4
4
|
import { currentHub } from "../hub-context.js";
|
|
5
|
+
import { joinWorkspace } from "../join.js";
|
|
5
6
|
import { setWorkspaceCloud, workspaceCloud } from "../workspace-cloud.js";
|
|
6
7
|
import { fail, route } from "./router.js";
|
|
7
8
|
/**
|
|
@@ -45,6 +46,19 @@ export const cloudRoutes = [
|
|
|
45
46
|
const { slug, root, role } = await c.body();
|
|
46
47
|
return createWorkspaceInvite({ slug, root }, role);
|
|
47
48
|
}),
|
|
49
|
+
// Start on the platform: `kraftwerk join <link>` (server/join.ts).
|
|
50
|
+
route({
|
|
51
|
+
name: "cloud.join",
|
|
52
|
+
method: "POST",
|
|
53
|
+
path: "/api/cloud/join",
|
|
54
|
+
summary: "bring a workspace from kraftwerk cloud onto this machine {link, dir?, cwd}: claim, clone from kraftwerk sync, open",
|
|
55
|
+
access: "local",
|
|
56
|
+
errors: 409,
|
|
57
|
+
body: z.object({ link: z.string().min(1, "link is required"), dir: z.string().optional(), cwd: z.string().min(1, "cwd is required") }),
|
|
58
|
+
}, async (c) => {
|
|
59
|
+
const { link, dir, cwd } = await c.body();
|
|
60
|
+
return joinWorkspace(link, dir, cwd);
|
|
61
|
+
}),
|
|
48
62
|
route({ name: "cloud.unlink", method: "POST", path: "/api/cloud/unlink", summary: "release the machine from its account; the cloud hands out a fresh claim code", access: "local", errors: 400 }, async () => ({
|
|
49
63
|
daemon: currentHub().daemon === true,
|
|
50
64
|
...(await unlinkMachineCloud()),
|
package/dist/server/api/git.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
|
+
import { type GitStatus } from "../../core/git.js";
|
|
3
|
+
/**
|
|
4
|
+
* Who hosts the workspace's remote: kraftwerk sync is the workspace's own
|
|
5
|
+
* repo in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
|
|
6
|
+
* machine knows it); anything else is an own git provider.
|
|
7
|
+
*/
|
|
8
|
+
export declare function hostingOf(remoteUrl: string | undefined): Promise<NonNullable<GitStatus["hosting"]>>;
|
|
2
9
|
/** The workspace's own git, and the repositories cloned under its repos root. */
|
|
3
10
|
export declare const gitRoutes: (import("./router.js").Route<"git.commit", import("./router.js").Reply<{
|
|
4
11
|
ok: boolean;
|
|
@@ -16,7 +23,12 @@ export declare const gitRoutes: (import("./router.js").Route<"git.commit", impor
|
|
|
16
23
|
}>, "/api/git/pull", undefined> | import("./router.js").Route<"git.push", import("./router.js").Reply<{
|
|
17
24
|
ok: boolean;
|
|
18
25
|
error?: string;
|
|
19
|
-
}>, "/api/git/push", undefined> | import("./router.js").Route<"git.
|
|
26
|
+
}>, "/api/git/push", undefined> | import("./router.js").Route<"git.setupSync", import("./router.js").Reply<{
|
|
27
|
+
ok: boolean;
|
|
28
|
+
done: string[];
|
|
29
|
+
error?: string;
|
|
30
|
+
status: GitStatus;
|
|
31
|
+
}>, "/api/git/sync-setup", undefined> | import("./router.js").Route<"git.status", GitStatus, "/api/git", undefined> | import("./router.js").Route<"repos.add", import("./router.js").Reply<import("../../core/repos.js").RepoInfo>, "/api/repos", z.ZodObject<{
|
|
20
32
|
url: z.ZodDefault<z.ZodString>;
|
|
21
33
|
name: z.ZodOptional<z.ZodString>;
|
|
22
34
|
branch: z.ZodOptional<z.ZodString>;
|
package/dist/server/api/git.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
|
+
import { resolveWorkspace } from "../../config.js";
|
|
3
|
+
import { workspaceRoot } from "../../core/context.js";
|
|
2
4
|
import { gitCommit, gitDiff, gitFetch, gitPull, gitPush, gitStatus } from "../../core/git.js";
|
|
5
|
+
import { cloudStatus } from "../cloud.js";
|
|
6
|
+
import { setupSync } from "../sync-setup.js";
|
|
3
7
|
import { addRepo, listRepos, openRepos, removeRepo, repoCommitDiff, repoDetail, repoDiff, updateRepo } from "../../core/repos.js";
|
|
4
8
|
import { fail, reply, route, statusByMessage } from "./router.js";
|
|
5
9
|
const repoErrors = statusByMessage(/^no repository/);
|
|
@@ -8,10 +12,38 @@ const conflictUnlessOk = (result) => reply(result.ok ? 200 : 409, result);
|
|
|
8
12
|
const Commit = z.object({ paths: z.array(z.string()).default([]), message: z.string().default("") });
|
|
9
13
|
/** A clone to add; url, name, branch and depth are checked by addRepo. */
|
|
10
14
|
const AddRepo = z.object({ url: z.string().default(""), name: z.string().optional(), branch: z.string().optional(), depth: z.number().optional() });
|
|
15
|
+
/**
|
|
16
|
+
* Who hosts the workspace's remote: kraftwerk sync is the workspace's own
|
|
17
|
+
* repo in kraftwerk cloud, `<cloud>/git/<id>.git` (the cloud's host when this
|
|
18
|
+
* machine knows it); anything else is an own git provider.
|
|
19
|
+
*/
|
|
20
|
+
export async function hostingOf(remoteUrl) {
|
|
21
|
+
if (!remoteUrl)
|
|
22
|
+
return "none";
|
|
23
|
+
const id = (await resolveWorkspace(workspaceRoot()).catch(() => null))?.config.id;
|
|
24
|
+
let u;
|
|
25
|
+
try {
|
|
26
|
+
u = new URL(remoteUrl);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return "custom"; // scp-like ssh (git@host:path) — never kraftwerk sync
|
|
30
|
+
}
|
|
31
|
+
const cloud = cloudStatus().url;
|
|
32
|
+
const sameHost = !cloud || (() => { try {
|
|
33
|
+
return new URL(cloud).host === u.host;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
} })();
|
|
38
|
+
return id && sameHost && u.pathname.replace(/\/+$/, "") === `/git/${encodeURIComponent(id)}.git` ? "kraftwerk" : "custom";
|
|
39
|
+
}
|
|
11
40
|
/** The workspace's own git, and the repositories cloned under its repos root. */
|
|
12
41
|
export const gitRoutes = [
|
|
13
42
|
// The git screen polls this, so it is cached for a beat; ?fresh=1 bypasses the cache.
|
|
14
|
-
route({ name: "git.status", method: "GET", path: "/api/git", summary: "branch, ahead/behind, changed files" }, async (c) =>
|
|
43
|
+
route({ name: "git.status", method: "GET", path: "/api/git", summary: "branch, ahead/behind, changed files" }, async (c) => {
|
|
44
|
+
const st = await gitStatus(c.query.has("fresh"));
|
|
45
|
+
return st.repoRoot ? { ...st, hosting: await hostingOf(st.remoteUrl) } : st;
|
|
46
|
+
}),
|
|
15
47
|
route({ name: "git.diff", method: "GET", path: "/api/git/diff", summary: "unified diff for one file ?path=" }, async (c) => {
|
|
16
48
|
const file = c.query.get("path");
|
|
17
49
|
if (!file)
|
|
@@ -24,6 +56,12 @@ export const gitRoutes = [
|
|
|
24
56
|
const result = await gitCommit(paths, message);
|
|
25
57
|
return reply(result.ok ? 200 : 409, result);
|
|
26
58
|
}),
|
|
59
|
+
// kraftwerk sync in one go (server/sync-setup.ts); 409 while cloud mode is not there or the remote is someone else's.
|
|
60
|
+
route({ name: "git.setupSync", method: "POST", path: "/api/git/sync-setup", summary: "set up kraftwerk sync: repo, git block, cloud remote, first push", errors: 409 }, async () => {
|
|
61
|
+
const r = await setupSync();
|
|
62
|
+
const st = r.status.repoRoot ? { ...r.status, hosting: await hostingOf(r.status.remoteUrl) } : r.status;
|
|
63
|
+
return reply(r.ok ? 200 : 409, { ...r, status: st });
|
|
64
|
+
}),
|
|
27
65
|
route({ name: "git.fetch", method: "POST", path: "/api/git/fetch", summary: "git fetch" }, async () => conflictUnlessOk(await gitFetch())),
|
|
28
66
|
route({ name: "git.pull", method: "POST", path: "/api/git/pull", summary: "git pull --ff-only" }, async () => conflictUnlessOk(await gitPull())),
|
|
29
67
|
route({ name: "git.push", method: "POST", path: "/api/git/push", summary: "git push" }, async () => conflictUnlessOk(await gitPush())),
|
|
@@ -351,6 +351,10 @@ export declare const routes: (Route<"agents.addJournal", {
|
|
|
351
351
|
member: "member";
|
|
352
352
|
owner: "owner";
|
|
353
353
|
}>>;
|
|
354
|
+
}, z.core.$strip>> | Route<"cloud.join", import("../join.js").JoinResult, "/api/cloud/join", z.ZodObject<{
|
|
355
|
+
link: z.ZodString;
|
|
356
|
+
dir: z.ZodOptional<z.ZodString>;
|
|
357
|
+
cwd: z.ZodString;
|
|
354
358
|
}, z.core.$strip>> | Route<"cloud.set", {
|
|
355
359
|
daemon: boolean;
|
|
356
360
|
url: string;
|
|
@@ -544,7 +548,12 @@ export declare const routes: (Route<"agents.addJournal", {
|
|
|
544
548
|
}>, "/api/git/pull", undefined> | Route<"git.push", import("./router.js").Reply<{
|
|
545
549
|
ok: boolean;
|
|
546
550
|
error?: string;
|
|
547
|
-
}>, "/api/git/push", undefined> | Route<"git.
|
|
551
|
+
}>, "/api/git/push", undefined> | Route<"git.setupSync", import("./router.js").Reply<{
|
|
552
|
+
ok: boolean;
|
|
553
|
+
done: string[];
|
|
554
|
+
error?: string;
|
|
555
|
+
status: import("../../core/git.js").GitStatus;
|
|
556
|
+
}>, "/api/git/sync-setup", undefined> | Route<"git.status", import("../../core/git.js").GitStatus, "/api/git", undefined> | Route<"hub.close", {
|
|
548
557
|
ok: boolean;
|
|
549
558
|
}, "/api/hub/close", z.ZodObject<{
|
|
550
559
|
root: z.ZodString;
|
package/dist/server/cloud.d.ts
CHANGED
|
@@ -104,6 +104,10 @@ export declare function machineLink(): {
|
|
|
104
104
|
creds: Credentials;
|
|
105
105
|
version: string;
|
|
106
106
|
} | null;
|
|
107
|
+
/** HTTP Basic with the machine's id and secret — what kraftwerk sync's git server takes from a machine. */
|
|
108
|
+
export declare const syncAuthHeader: (creds: Credentials) => string;
|
|
109
|
+
/** kraftwerk sync's repository for workspace `id` on this machine's cloud, or null without one. */
|
|
110
|
+
export declare function syncUrl(id: string): string | null;
|
|
107
111
|
/** The served workspace whose kraftwerk.yml `id` is `id` (vetoed ones not), or null. */
|
|
108
112
|
export declare function servedWorkspace(id: string): Promise<{
|
|
109
113
|
slug: string;
|
package/dist/server/cloud.js
CHANGED
|
@@ -6,6 +6,7 @@ import { claimUrlFor, machineCloud, machineGoodbye, machineHeartbeat, machineReg
|
|
|
6
6
|
import { identityString, readIdentity } from "../core/identity.js";
|
|
7
7
|
import { routineReport } from "../core/routines.js";
|
|
8
8
|
import { machineCredentials } from "./relay.js";
|
|
9
|
+
import { setRemoteAuth } from "../core/git.js";
|
|
9
10
|
const DEFAULT_INTERVAL = 60;
|
|
10
11
|
const STANDALONE = { url: "", state: "off", reason: "only the daemon registers this machine with the cloud (`kraftwerk daemon start`)" };
|
|
11
12
|
const m = {
|
|
@@ -218,6 +219,11 @@ export async function startMachineCloud(opts) {
|
|
|
218
219
|
await fs.rm(retiredCloudDir(), { recursive: true, force: true }).catch(() => { });
|
|
219
220
|
// The machine's id exists from the daemon's first start on, with the relay still off.
|
|
220
221
|
m.creds = await machineCredentials().catch(() => null);
|
|
222
|
+
// kraftwerk sync: git reaches the workspaces' cloud repos with this machine's key (core/git.ts).
|
|
223
|
+
setRemoteAuth(() => {
|
|
224
|
+
const link = machineLink();
|
|
225
|
+
return link ? { [`${link.url}/git/`]: syncAuthHeader(link.creds) } : {};
|
|
226
|
+
});
|
|
221
227
|
await serial(register);
|
|
222
228
|
schedule();
|
|
223
229
|
return m.status;
|
|
@@ -309,6 +315,13 @@ export function machineLink() {
|
|
|
309
315
|
return null;
|
|
310
316
|
return { url: m.status.url, creds: m.creds, version: m.version };
|
|
311
317
|
}
|
|
318
|
+
/** HTTP Basic with the machine's id and secret — what kraftwerk sync's git server takes from a machine. */
|
|
319
|
+
export const syncAuthHeader = (creds) => `Authorization: Basic ${Buffer.from(`${creds.id}:${creds.secret}`).toString("base64")}`;
|
|
320
|
+
/** kraftwerk sync's repository for workspace `id` on this machine's cloud, or null without one. */
|
|
321
|
+
export function syncUrl(id) {
|
|
322
|
+
const url = cloudStatus().url;
|
|
323
|
+
return url ? `${url}/git/${encodeURIComponent(id)}.git` : null;
|
|
324
|
+
}
|
|
312
325
|
/** The served workspace whose kraftwerk.yml `id` is `id` (vetoed ones not), or null. */
|
|
313
326
|
export async function servedWorkspace(id) {
|
|
314
327
|
for (const o of m.source()) {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `kraftwerk join <link>` on the daemon's side — start on the platform: a
|
|
3
|
+
* workspace made (or an invite accepted) on kraftwerk cloud comes onto this
|
|
4
|
+
* machine in one go.
|
|
5
|
+
*
|
|
6
|
+
* 1. the machine's cloud on, at the link's origin (a machine already linked
|
|
7
|
+
* to an account on another cloud is refused)
|
|
8
|
+
* 2. the machine presents the code with its key (POST /api/machines/join);
|
|
9
|
+
* the cloud claims it for the code's account and names the workspace
|
|
10
|
+
* 3. the workspace cloned from kraftwerk sync into the folder — the machine's
|
|
11
|
+
* key goes along through core/git.ts setRemoteAuth, nothing is stored;
|
|
12
|
+
* a cloud repository with no history yet gets a kraftwerk.yml of its own
|
|
13
|
+
* 4. the folder opened in the daemon
|
|
14
|
+
*
|
|
15
|
+
* Again on a folder that already holds the workspace: no clone, just open.
|
|
16
|
+
*/
|
|
17
|
+
export interface JoinResult {
|
|
18
|
+
workspace: {
|
|
19
|
+
id: string;
|
|
20
|
+
name: string;
|
|
21
|
+
slug: string;
|
|
22
|
+
url: string;
|
|
23
|
+
};
|
|
24
|
+
root: string;
|
|
25
|
+
role: string;
|
|
26
|
+
account: string;
|
|
27
|
+
cloned: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** `<origin>/join/<code>` or a bare code (this machine's cloud). */
|
|
30
|
+
export declare function parseJoinLink(raw: string): {
|
|
31
|
+
origin: string | null;
|
|
32
|
+
code: string;
|
|
33
|
+
};
|
|
34
|
+
export declare function joinWorkspace(link: string, dirIn: string | undefined, cwd: string): Promise<JoinResult>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { resolveWorkspace } from "../config.js";
|
|
5
|
+
import { cloudPost, envCloudOff, readCloudFile, writeCloudFile } from "../core/cloud.js";
|
|
6
|
+
import { git, NET_TIMEOUT, remoteAuthEnv } from "../core/git.js";
|
|
7
|
+
import { ApiError } from "./api/router.js";
|
|
8
|
+
import { applyMachineCloud, cloudStatus, machineLink, syncMachineCloud } from "./cloud.js";
|
|
9
|
+
import { currentHub } from "./hub-context.js";
|
|
10
|
+
/** `<origin>/join/<code>` or a bare code (this machine's cloud). */
|
|
11
|
+
export function parseJoinLink(raw) {
|
|
12
|
+
const text = raw.trim();
|
|
13
|
+
const m = /^(https?:\/\/[^/]+)\/join\/([^/?#]+)/i.exec(text);
|
|
14
|
+
if (m)
|
|
15
|
+
return { origin: m[1].replace(/\/+$/, ""), code: decodeURIComponent(m[2]) };
|
|
16
|
+
if (/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(text))
|
|
17
|
+
return { origin: null, code: text };
|
|
18
|
+
throw new ApiError(400, "that is not a join link — it looks like https://…/join/XKQ7-2MPD-HH3A");
|
|
19
|
+
}
|
|
20
|
+
const folderName = (name) => name.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "workspace";
|
|
21
|
+
async function until(fn, ms) {
|
|
22
|
+
const end = Date.now() + ms;
|
|
23
|
+
for (;;) {
|
|
24
|
+
const v = await fn();
|
|
25
|
+
if (v || Date.now() > end)
|
|
26
|
+
return v;
|
|
27
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** The machine connected to `origin` (its cloud turned on and pointed there when it is free to). */
|
|
31
|
+
async function connectTo(origin) {
|
|
32
|
+
if (currentHub().daemon !== true)
|
|
33
|
+
throw new ApiError(409, "only the kraftwerk daemon joins workspaces — `kraftwerk daemon start`");
|
|
34
|
+
if (envCloudOff())
|
|
35
|
+
throw new ApiError(409, "the cloud is turned off by KRAFTWERK_CLOUD_URL=off");
|
|
36
|
+
const st = cloudStatus();
|
|
37
|
+
if (origin && st.url && st.url !== origin) {
|
|
38
|
+
if (st.state === "connected" && st.account) {
|
|
39
|
+
throw new ApiError(409, `this machine is linked to ${st.url} (as ${st.account}) — the link is for ${origin}; \`kraftwerk cloud disconnect\` first to move it`);
|
|
40
|
+
}
|
|
41
|
+
if (st.source === "env")
|
|
42
|
+
throw new ApiError(409, `KRAFTWERK_CLOUD_URL points this machine at ${st.url}, the link is for ${origin}`);
|
|
43
|
+
}
|
|
44
|
+
const file = await readCloudFile();
|
|
45
|
+
if (file.enabled === false || (origin && st.url !== origin)) {
|
|
46
|
+
await writeCloudFile({ enabled: true, ...(origin ? { url: origin } : {}) });
|
|
47
|
+
await applyMachineCloud();
|
|
48
|
+
}
|
|
49
|
+
const up = await until(async () => {
|
|
50
|
+
const s = await syncMachineCloud().catch(() => cloudStatus());
|
|
51
|
+
return s.state === "connected" ? s : null;
|
|
52
|
+
}, 20_000);
|
|
53
|
+
if (!up) {
|
|
54
|
+
const s = cloudStatus();
|
|
55
|
+
throw new ApiError(502, `kraftwerk cloud did not answer${s.error ? `: ${s.error}` : ""}`);
|
|
56
|
+
}
|
|
57
|
+
return up.url;
|
|
58
|
+
}
|
|
59
|
+
export async function joinWorkspace(link, dirIn, cwd) {
|
|
60
|
+
const { origin, code } = parseJoinLink(link);
|
|
61
|
+
const url = await connectTo(origin);
|
|
62
|
+
const machine = machineLink();
|
|
63
|
+
if (!machine)
|
|
64
|
+
throw new ApiError(502, "this machine has no place in the cloud yet");
|
|
65
|
+
const joined = await cloudPost(url, "/api/machines/join", { id: machine.creds.id, secret: machine.creds.secret, code }, { version: machine.version }).catch((err) => {
|
|
66
|
+
throw new ApiError(err.status && err.status >= 400 && err.status < 500 ? err.status : 502, err.message);
|
|
67
|
+
});
|
|
68
|
+
// The claim shows in the next round; get it now, so git and sign-in see the account.
|
|
69
|
+
await syncMachineCloud().catch(() => { });
|
|
70
|
+
if (!joined.sync)
|
|
71
|
+
throw new ApiError(502, "this kraftwerk cloud keeps no repositories (kraftwerk sync is off there)");
|
|
72
|
+
const root = path.resolve(cwd, dirIn ?? folderName(joined.workspaceName));
|
|
73
|
+
let cloned = false;
|
|
74
|
+
const here = existsSync(root) ? await resolveWorkspace(root).catch(() => null) : null;
|
|
75
|
+
if (here?.configPath && path.dirname(here.configPath) === root && here.config.id === joined.workspaceId) {
|
|
76
|
+
// Already here: open it.
|
|
77
|
+
}
|
|
78
|
+
else if (existsSync(root) && (await fs.readdir(root)).length > 0) {
|
|
79
|
+
throw new ApiError(409, `${root} exists and is not empty — pass another folder: kraftwerk join <link> <folder>`);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
await fs.mkdir(path.dirname(root), { recursive: true });
|
|
83
|
+
const r = await git(["clone", "-q", "--", joined.sync.url, root], path.dirname(root), NET_TIMEOUT * 5, remoteAuthEnv());
|
|
84
|
+
if (!r.ok)
|
|
85
|
+
throw new ApiError(502, `cloning from kraftwerk sync failed: ${r.stderr || "unknown error"}`);
|
|
86
|
+
cloned = true;
|
|
87
|
+
// A workspace whose repository has no history yet (made locally, never pushed): its kraftwerk.yml starts here.
|
|
88
|
+
if (!existsSync(path.join(root, "kraftwerk.yml"))) {
|
|
89
|
+
await fs.writeFile(path.join(root, "kraftwerk.yml"), [`id: ${joined.workspaceId}`, `name: ${JSON.stringify(joined.workspaceName)}`, `users:`, ` mode: cloud`, `git:`, ` autosync: push`, ``].join("\n"));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const o = await currentHub().open(root);
|
|
93
|
+
// The cloud learns the workspace is here now (its host list, sign-in).
|
|
94
|
+
await syncMachineCloud().catch(() => { });
|
|
95
|
+
return {
|
|
96
|
+
workspace: { id: joined.workspaceId, name: joined.workspaceName, slug: o.slug, url: o.url },
|
|
97
|
+
root,
|
|
98
|
+
role: joined.role,
|
|
99
|
+
account: joined.account,
|
|
100
|
+
cloned,
|
|
101
|
+
};
|
|
102
|
+
}
|