@netnodeag/kraftwerk 0.100.1 → 0.102.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.
Files changed (55) hide show
  1. package/README.md +73 -0
  2. package/dist/cli/cloud.d.ts +1 -0
  3. package/dist/cli/cloud.js +1 -1
  4. package/dist/cli/join.d.ts +2 -0
  5. package/dist/cli/join.js +52 -0
  6. package/dist/cli/kraftwerk.js +3 -0
  7. package/dist/client/routes.d.ts +2 -0
  8. package/dist/client/routes.js +2 -0
  9. package/dist/config.d.ts +2 -2
  10. package/dist/config.js +3 -3
  11. package/dist/core/boards.d.ts +3 -0
  12. package/dist/core/boards.js +16 -2
  13. package/dist/core/cloud.d.ts +5 -0
  14. package/dist/core/git.d.ts +46 -2
  15. package/dist/core/git.js +251 -8
  16. package/dist/core/notifications.d.ts +3 -2
  17. package/dist/core/settings.d.ts +1 -1
  18. package/dist/core/settings.js +2 -2
  19. package/dist/server/api/cloud.d.ts +4 -0
  20. package/dist/server/api/cloud.js +14 -0
  21. package/dist/server/api/git.d.ts +13 -1
  22. package/dist/server/api/git.js +39 -1
  23. package/dist/server/api/index.d.ts +10 -1
  24. package/dist/server/cloud-events.d.ts +8 -0
  25. package/dist/server/cloud-events.js +199 -0
  26. package/dist/server/cloud.d.ts +12 -0
  27. package/dist/server/cloud.js +53 -0
  28. package/dist/server/join.d.ts +38 -0
  29. package/dist/server/join.js +111 -0
  30. package/dist/server/relay.js +5 -0
  31. package/dist/server/sync-setup.d.ts +31 -0
  32. package/dist/server/sync-setup.js +90 -0
  33. package/dist/server/users.d.ts +11 -0
  34. package/dist/server/users.js +63 -15
  35. package/dist/server/workspace-cloud.d.ts +3 -1
  36. package/dist/server/workspace-cloud.js +18 -8
  37. package/package.json +1 -1
  38. package/web/dist/assets/{dist-Dj1JIIbI.js → dist-B09k-Kwi.js} +1 -1
  39. package/web/dist/assets/{dist-DQsdt9qV.js → dist-BG9MPqC7.js} +1 -1
  40. package/web/dist/assets/{dist-DxHapyfL.js → dist-BbST9sxK.js} +1 -1
  41. package/web/dist/assets/{dist-OUSFQqAo.js → dist-BrXAphjl.js} +1 -1
  42. package/web/dist/assets/{dist-CYnkW4NZ.js → dist-C0Ulmjwh.js} +1 -1
  43. package/web/dist/assets/{dist-DmqwXVk5.js → dist-C8wsDqpL.js} +1 -1
  44. package/web/dist/assets/{dist-Dhqv4G4v.js → dist-CJk4RtqY.js} +1 -1
  45. package/web/dist/assets/{dist-BQht4Kxn.js → dist-CfSpo_bP.js} +1 -1
  46. package/web/dist/assets/dist-DMU8iY9H.js +1 -0
  47. package/web/dist/assets/{dist-C6Hh2gvr.js → dist-Dv55aORJ.js} +1 -1
  48. package/web/dist/assets/{dist-KYJrjjHE.js → dist-QQHKzUGH.js} +1 -1
  49. package/web/dist/assets/{editor-DjVpjnNv.js → editor-Co8xGDnf.js} +3 -3
  50. package/web/dist/assets/index-CepQsH8H.js +488 -0
  51. package/web/dist/assets/index-DJGLnVQY.css +2 -0
  52. package/web/dist/index.html +2 -2
  53. package/web/dist/assets/dist-CxDUjCCR.js +0 -1
  54. package/web/dist/assets/index-BV1cBJKv.js +0 -488
  55. package/web/dist/assets/index-ClVr51ut.css +0 -2
@@ -0,0 +1,199 @@
1
+ import { getAgent } from "../core/agents.js";
2
+ import { emitTaskEvent, setCloudTaskContext } from "../core/boards.js";
3
+ import { cloudPost } from "../core/cloud.js";
4
+ import { log } from "../core/log.js";
5
+ import { pushNotification } from "../core/notifications.js";
6
+ import { getCloudBoard, getCloudTask } from "./cloud-boards.js";
7
+ import { cloudStatus, inServedWorkspace, machineLink, onCloudChanged, onEventsWaiting } from "./cloud.js";
8
+ let running = null;
9
+ let again = false;
10
+ /** Fetch and act on what waits; a call while one runs makes it run once more after. */
11
+ export function fetchCloudEvents() {
12
+ if (running) {
13
+ again = true;
14
+ return running;
15
+ }
16
+ running = (async () => {
17
+ try {
18
+ do {
19
+ again = false;
20
+ await round();
21
+ } while (again);
22
+ }
23
+ finally {
24
+ running = null;
25
+ }
26
+ })();
27
+ return running;
28
+ }
29
+ async function round() {
30
+ const link = machineLink();
31
+ if (!link)
32
+ return;
33
+ const auth = { id: link.creds.id, secret: link.creds.secret };
34
+ let events;
35
+ try {
36
+ events = (await cloudPost(link.url, "/api/machines/events", auth, { version: link.version })).events ?? [];
37
+ }
38
+ catch (err) {
39
+ log("warn", "cloud", `could not fetch events: ${err.message}`);
40
+ return;
41
+ }
42
+ if (!events.length)
43
+ return;
44
+ const ack = [];
45
+ const claim = [];
46
+ for (const ev of events) {
47
+ if (ev.kind === "task_assigned") {
48
+ await inServedWorkspace(ev.workspaceId, () => notifyAssigned(ev)).catch(() => null);
49
+ ack.push(ev.id);
50
+ }
51
+ else {
52
+ const here = await inServedWorkspace(ev.workspaceId, async () => !!(ev.agent && (await getAgent(ev.agent).catch(() => null)))).catch(() => null);
53
+ if (here?.value)
54
+ claim.push({ ev, agentHere: true });
55
+ else
56
+ ack.push(ev.id);
57
+ }
58
+ }
59
+ let claimed = [];
60
+ try {
61
+ claimed = (await cloudPost(link.url, "/api/machines/events/ack", { ...auth, ack, claim: claim.map((c) => c.ev.id) }, { version: link.version })).claimed ?? [];
62
+ }
63
+ catch (err) {
64
+ log("warn", "cloud", `could not acknowledge events: ${err.message}`);
65
+ return;
66
+ }
67
+ for (const { ev } of claim) {
68
+ if (!claimed.includes(ev.id))
69
+ continue; // another machine with the agent took it
70
+ await inServedWorkspace(ev.workspaceId, () => wakeFor(ev)).catch((err) => log("warn", "cloud", `could not wake ${ev.agent} for @${ev.board}/${ev.number}: ${err.message}`));
71
+ }
72
+ }
73
+ const who = (actor) => actor.replace(/^human:/, "");
74
+ async function notifyAssigned(ev) {
75
+ await pushNotification({
76
+ kind: "task_assigned",
77
+ title: `📋 ${who(ev.by)} gave you “${ev.title}”`,
78
+ body: `${ev.boardTitle} · ${ev.status}${ev.message ? ` — ${ev.message}` : ""}`,
79
+ href: `/boards/@${ev.board}/${ev.number}`,
80
+ key: `task-assigned:@${ev.board}/${ev.number}`,
81
+ });
82
+ }
83
+ /** The agent's wake, as for a local board: a TaskEvent board-wake.ts consumes. */
84
+ async function wakeFor(ev) {
85
+ await emitTaskEvent({
86
+ at: new Date(ev.at).toISOString(),
87
+ ref: `@${ev.board}/${ev.number}`,
88
+ board: `@${ev.board}`,
89
+ task: String(ev.number),
90
+ title: ev.title,
91
+ agent: ev.agent,
92
+ status: ev.status,
93
+ reason: ev.reason,
94
+ actor: ev.by,
95
+ ...(ev.message ? { message: ev.message } : {}),
96
+ });
97
+ }
98
+ /** The context block of a cloud task for the agent woken for it (core/boards.ts taskContext). */
99
+ async function cloudContext(reference) {
100
+ const [board, n] = reference.split("/");
101
+ const flags = `--board ${board}`;
102
+ try {
103
+ const [t, b] = await Promise.all([getCloudTask({ kind: "local" }, board, n), getCloudBoard({ kind: "local" }, board).catch(() => null)]);
104
+ const cols = b ? b.columns.map((c) => c.slug).join(", ") : "";
105
+ return (`## Your task: ${t.number} ${t.title}\n` +
106
+ `Cloud board ${board}${b ? ` (columns: ${cols})` : ""} — kept in kraftwerk cloud, shared with everyone on the workspace; status ${t.status}${t.assignee ? `, assigned to ${t.assignee}` : ""}${t.due ? `, due ${t.due}` : ""}.\n` +
107
+ `\n### Notes\n${t.notes.trim() || "(none — ask in the log what done looks like)"}\n` +
108
+ `\n### Log (newest first)\n${t.log.trim() || "(empty)"}\n\n` +
109
+ `Work it through the CLI (${flags}, the number ${t.number} names the task): \`npx kraftwerk tasks move ${t.number} doing ${flags}\` when you start, ` +
110
+ `\`tasks log ${t.number} "<what you did>" ${flags}\` as you go (files into $KRAFTWERK_TEMP or the workspace), ` +
111
+ `\`tasks assign ${t.number} <agent or human:handle> -m "<note>" ${flags}\` to hand it over, \`tasks move ${t.number} review -m "<summary>" ${flags}\` when done. Never move it to a finished column.`);
112
+ }
113
+ catch (err) {
114
+ return `You were opened for task ${reference} on a cloud board, but it could not be read (${err.message}). Try \`npx kraftwerk tasks show ${n} ${flags}\`.`;
115
+ }
116
+ }
117
+ /* ---------- the event stream ---------- */
118
+ const PING_MS = 30_000;
119
+ const stream = {
120
+ ws: null,
121
+ /** The link it was opened for: url + machine id; another one closes it. */
122
+ key: "",
123
+ retry: null,
124
+ ping: null,
125
+ backoff: 1_000,
126
+ };
127
+ function closeStream() {
128
+ if (stream.retry)
129
+ clearTimeout(stream.retry);
130
+ if (stream.ping)
131
+ clearInterval(stream.ping);
132
+ stream.retry = null;
133
+ stream.ping = null;
134
+ const ws = stream.ws;
135
+ stream.ws = null;
136
+ stream.key = "";
137
+ try {
138
+ ws?.close();
139
+ }
140
+ catch { }
141
+ }
142
+ /** Hold the stream while connected and claimed; drop it otherwise. */
143
+ export function keepEventStream() {
144
+ const link = machineLink();
145
+ const st = cloudStatus();
146
+ const want = link && st.state === "connected" && st.account ? `${link.url} ${link.creds.id}` : "";
147
+ if (want === stream.key && (stream.ws || stream.retry))
148
+ return;
149
+ closeStream();
150
+ if (!want || !link || typeof WebSocket === "undefined")
151
+ return;
152
+ stream.key = want;
153
+ const ws = new WebSocket(`${link.url.replace(/^http/, "ws")}/api/machines/stream`);
154
+ stream.ws = ws;
155
+ ws.addEventListener("open", () => ws.send(JSON.stringify({ t: "auth", id: link.creds.id, secret: link.creds.secret })));
156
+ ws.addEventListener("message", (ev) => {
157
+ let msg;
158
+ try {
159
+ msg = JSON.parse(String(ev.data));
160
+ }
161
+ catch {
162
+ return;
163
+ }
164
+ if (msg.t === "ok") {
165
+ stream.backoff = 1_000;
166
+ stream.ping = setInterval(() => ws.readyState === WebSocket.OPEN && ws.send(JSON.stringify({ t: "ping" })), PING_MS);
167
+ stream.ping.unref?.();
168
+ // What came in while there was no stream.
169
+ void fetchCloudEvents().catch(() => { });
170
+ }
171
+ else if (msg.t === "poke")
172
+ void fetchCloudEvents().catch(() => { });
173
+ });
174
+ ws.addEventListener("close", () => {
175
+ if (stream.ws !== ws)
176
+ return;
177
+ if (stream.ping)
178
+ clearInterval(stream.ping);
179
+ stream.ping = null;
180
+ stream.ws = null;
181
+ // Gone (the cloud restarted, the network changed): again soon, slower each time; a refused auth waits for the next change.
182
+ stream.retry = setTimeout(() => {
183
+ stream.retry = null;
184
+ stream.key = "";
185
+ keepEventStream();
186
+ }, stream.backoff);
187
+ stream.retry.unref?.();
188
+ stream.backoff = Math.min(stream.backoff * 2, 60_000);
189
+ });
190
+ ws.addEventListener("error", () => { });
191
+ }
192
+ /** Whether the stream is up (tests, status). */
193
+ export const eventStreamOpen = () => stream.ws?.readyState === 1;
194
+ /** Hook in (cloud.ts startMachineCloud): the task context, the heartbeat's count, the link's changes. Not at import — the modules load each other. */
195
+ export function installCloudEvents() {
196
+ setCloudTaskContext(cloudContext);
197
+ onEventsWaiting(fetchCloudEvents);
198
+ onCloudChanged(keepEventStream);
199
+ }
@@ -104,6 +104,18 @@ export declare function machineLink(): {
104
104
  creds: Credentials;
105
105
  version: string;
106
106
  } | null;
107
+ export declare function onCloudChanged(fn: () => void): void;
108
+ export declare function onEventsWaiting(fn: () => Promise<void>): void;
109
+ /** Whether workspace `id` was deleted in kraftwerk cloud (its copies here stay, in local mode). */
110
+ export declare const deletedInCloud: (id: string | undefined) => boolean;
111
+ /** HTTP Basic with the machine's id and secret — what kraftwerk sync's git server takes from a machine. */
112
+ export declare const syncAuthHeader: (creds: Credentials) => string;
113
+ /** kraftwerk sync's repository for workspace `id` on this machine's cloud, or null without one. */
114
+ export declare function syncUrl(id: string): string | null;
115
+ /** Run `fn` inside the served workspace whose `id` is `id` (its own context: notifications, chats); null when none here serves it. */
116
+ export declare function inServedWorkspace<T>(id: string, fn: () => Promise<T>): Promise<{
117
+ value: T;
118
+ } | null>;
107
119
  /** The served workspace whose kraftwerk.yml `id` is `id` (vetoed ones not), or null. */
108
120
  export declare function servedWorkspace(id: string): Promise<{
109
121
  slug: string;
@@ -6,11 +6,15 @@ 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, setSyncAuthor } from "../core/git.js";
10
+ import { installCloudEvents } from "./cloud-events.js";
9
11
  const DEFAULT_INTERVAL = 60;
10
12
  const STANDALONE = { url: "", state: "off", reason: "only the daemon registers this machine with the cloud (`kraftwerk daemon start`)" };
11
13
  const m = {
12
14
  status: { ...STANDALONE },
13
15
  creds: null,
16
+ /** Workspaces (ws_ ids) this machine reports that were deleted in the cloud. */
17
+ deleted: new Set(),
14
18
  registered: false,
15
19
  timer: null,
16
20
  started: false,
@@ -126,6 +130,8 @@ async function register() {
126
130
  // An unclaimed register carries no roots: the list counts as reported only when that is all the cloud should know.
127
131
  m.reported = r.account ? "" : JSON.stringify(list);
128
132
  await noteAccount(r);
133
+ m.deleted = new Set(r.deletedWorkspaces ?? []);
134
+ queueMicrotask(() => cloudChanged());
129
135
  m.status = {
130
136
  ...base, state: "connected", account: r.account ?? null, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null, interval: r.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
131
137
  claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(cloud.url, r.claimCode), workspaces: list.length,
@@ -159,6 +165,11 @@ async function heartbeat() {
159
165
  m.reported = now;
160
166
  m.routines = ran;
161
167
  await noteAccount(r);
168
+ m.deleted = new Set(r.deletedWorkspaces ?? []);
169
+ queueMicrotask(() => cloudChanged());
170
+ // Events a poke did not bring (the relay was down): fetch them now (cloud-events.ts).
171
+ if (r.events)
172
+ void Promise.resolve().then(() => eventsWaiting()).catch(() => { });
162
173
  m.status = {
163
174
  ...m.status, state: "connected", error: undefined, interval: r.interval || m.status.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
164
175
  ...(r.account !== undefined ? { account: r.account, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null } : {}),
@@ -218,6 +229,15 @@ export async function startMachineCloud(opts) {
218
229
  await fs.rm(retiredCloudDir(), { recursive: true, force: true }).catch(() => { });
219
230
  // The machine's id exists from the daemon's first start on, with the relay still off.
220
231
  m.creds = await machineCredentials().catch(() => null);
232
+ // Cloud-board events: notifications and agent wakes (cloud-events.ts).
233
+ installCloudEvents();
234
+ // kraftwerk sync: git reaches the workspaces' cloud repos with this machine's key (core/git.ts).
235
+ setRemoteAuth(() => {
236
+ const link = machineLink();
237
+ return link ? { [`${link.url}/git/`]: syncAuthHeader(link.creds) } : {};
238
+ });
239
+ // What kraftwerk sync commits by itself is by the account this machine is linked to.
240
+ setSyncAuthor(() => (m.status.state === "connected" && m.status.account ? { name: m.status.accountHandle || m.status.account, email: m.status.account } : null));
221
241
  await serial(register);
222
242
  schedule();
223
243
  return m.status;
@@ -244,6 +264,7 @@ export async function applyMachineCloud() {
244
264
  clearTimeout(m.timer);
245
265
  m.timer = null;
246
266
  m.status = { url: cloud.url, state: "off", source: cloud.source, ...(cloud.reason ? { reason: cloud.reason } : {}) };
267
+ cloudChanged();
247
268
  return m.status;
248
269
  }
249
270
  if (!m.registered)
@@ -276,6 +297,7 @@ export async function unlinkMachineCloud() {
276
297
  m.routines = "";
277
298
  await writeAccountFile(null);
278
299
  m.status = { ...m.status, account: null, accountId: null, accountHandle: null, claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(m.status.url, r.claimCode) };
300
+ cloudChanged();
279
301
  return m.status;
280
302
  });
281
303
  }
@@ -296,6 +318,7 @@ export async function stopMachineCloud(owner) {
296
318
  m.registered = false;
297
319
  m.reported = "";
298
320
  m.status = { ...STANDALONE };
321
+ cloudChanged();
299
322
  if (registered && creds && url)
300
323
  await machineGoodbye(url, creds, m.version).catch(() => { });
301
324
  }
@@ -309,6 +332,36 @@ export function machineLink() {
309
332
  return null;
310
333
  return { url: m.status.url, creds: m.creds, version: m.version };
311
334
  }
335
+ /** What runs when the machine's link changes — connected, claimed, stopped (cloud-events.ts keeps its stream to match). */
336
+ let cloudChanged = () => { };
337
+ export function onCloudChanged(fn) {
338
+ cloudChanged = fn;
339
+ }
340
+ /** What runs when the cloud says events wait for this machine (cloud-events.ts sets it). */
341
+ let eventsWaiting = async () => { };
342
+ export function onEventsWaiting(fn) {
343
+ eventsWaiting = fn;
344
+ }
345
+ /** Whether workspace `id` was deleted in kraftwerk cloud (its copies here stay, in local mode). */
346
+ export const deletedInCloud = (id) => !!id && m.deleted.has(id);
347
+ /** HTTP Basic with the machine's id and secret — what kraftwerk sync's git server takes from a machine. */
348
+ export const syncAuthHeader = (creds) => `Authorization: Basic ${Buffer.from(`${creds.id}:${creds.secret}`).toString("base64")}`;
349
+ /** kraftwerk sync's repository for workspace `id` on this machine's cloud, or null without one. */
350
+ export function syncUrl(id) {
351
+ const url = cloudStatus().url;
352
+ return url ? `${url}/git/${encodeURIComponent(id)}.git` : null;
353
+ }
354
+ /** Run `fn` inside the served workspace whose `id` is `id` (its own context: notifications, chats); null when none here serves it. */
355
+ export async function inServedWorkspace(id, fn) {
356
+ for (const o of m.source()) {
357
+ const ws = await resolveWorkspace(o.root).catch(() => null);
358
+ if (ws?.config.id !== id || !cloudIncluded(ws.config) || !o.ws)
359
+ continue;
360
+ const run = o.ws.run.bind(o.ws);
361
+ return { value: await run(fn) };
362
+ }
363
+ return null;
364
+ }
312
365
  /** The served workspace whose kraftwerk.yml `id` is `id` (vetoed ones not), or null. */
313
366
  export async function servedWorkspace(id) {
314
367
  for (const o of m.source()) {
@@ -0,0 +1,38 @@
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 is refused with what to do (its
13
+ * owner sets up kraftwerk sync first), nothing is made locally
14
+ * 4. the folder opened in the daemon, and a one-time sign-in link for the
15
+ * browser the CLI opens (no second round through the cloud)
16
+ *
17
+ * Again on a folder that already holds the workspace: no clone, just open.
18
+ */
19
+ export interface JoinResult {
20
+ workspace: {
21
+ id: string;
22
+ name: string;
23
+ slug: string;
24
+ url: string;
25
+ };
26
+ /** Opens the workspace signed in as the account (one use, five minutes); absent when the cloud did not confirm. */
27
+ signin?: string;
28
+ root: string;
29
+ role: string;
30
+ account: string;
31
+ cloned: boolean;
32
+ }
33
+ /** `<origin>/join/<code>` or a bare code (this machine's cloud). */
34
+ export declare function parseJoinLink(raw: string): {
35
+ origin: string | null;
36
+ code: string;
37
+ };
38
+ export declare function joinWorkspace(link: string, dirIn: string | undefined, cwd: string): Promise<JoinResult>;
@@ -0,0 +1,111 @@
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
+ import { issueHandoff } from "./users.js";
11
+ /** `<origin>/join/<code>` or a bare code (this machine's cloud). */
12
+ export function parseJoinLink(raw) {
13
+ const text = raw.trim();
14
+ const m = /^(https?:\/\/[^/]+)\/join\/([^/?#]+)/i.exec(text);
15
+ if (m)
16
+ return { origin: m[1].replace(/\/+$/, ""), code: decodeURIComponent(m[2]) };
17
+ if (/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(text))
18
+ return { origin: null, code: text };
19
+ throw new ApiError(400, "that is not a join link — it looks like https://…/join/XKQ7-2MPD-HH3A");
20
+ }
21
+ const folderName = (name) => name.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "workspace";
22
+ async function until(fn, ms) {
23
+ const end = Date.now() + ms;
24
+ for (;;) {
25
+ const v = await fn();
26
+ if (v || Date.now() > end)
27
+ return v;
28
+ await new Promise((r) => setTimeout(r, 500));
29
+ }
30
+ }
31
+ /** The machine connected to `origin` (its cloud turned on and pointed there when it is free to). */
32
+ async function connectTo(origin) {
33
+ if (currentHub().daemon !== true)
34
+ throw new ApiError(409, "only the kraftwerk daemon joins workspaces — `kraftwerk daemon start`");
35
+ if (envCloudOff())
36
+ throw new ApiError(409, "the cloud is turned off by KRAFTWERK_CLOUD_URL=off");
37
+ const st = cloudStatus();
38
+ if (origin && st.url && st.url !== origin) {
39
+ if (st.state === "connected" && st.account) {
40
+ 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`);
41
+ }
42
+ if (st.source === "env")
43
+ throw new ApiError(409, `KRAFTWERK_CLOUD_URL points this machine at ${st.url}, the link is for ${origin}`);
44
+ }
45
+ const file = await readCloudFile();
46
+ if (file.enabled === false || (origin && st.url !== origin)) {
47
+ await writeCloudFile({ enabled: true, ...(origin ? { url: origin } : {}) });
48
+ await applyMachineCloud();
49
+ }
50
+ const up = await until(async () => {
51
+ const s = await syncMachineCloud().catch(() => cloudStatus());
52
+ return s.state === "connected" ? s : null;
53
+ }, 20_000);
54
+ if (!up) {
55
+ const s = cloudStatus();
56
+ throw new ApiError(502, `kraftwerk cloud did not answer${s.error ? `: ${s.error}` : ""}`);
57
+ }
58
+ return up.url;
59
+ }
60
+ export async function joinWorkspace(link, dirIn, cwd) {
61
+ const { origin, code } = parseJoinLink(link);
62
+ const url = await connectTo(origin);
63
+ const machine = machineLink();
64
+ if (!machine)
65
+ throw new ApiError(502, "this machine has no place in the cloud yet");
66
+ const joined = await cloudPost(url, "/api/machines/join", { id: machine.creds.id, secret: machine.creds.secret, code }, { version: machine.version }).catch((err) => {
67
+ throw new ApiError(err.status && err.status >= 400 && err.status < 500 ? err.status : 502, err.message);
68
+ });
69
+ // The claim shows in the next round; get it now, so git and sign-in see the account.
70
+ await syncMachineCloud().catch(() => { });
71
+ if (!joined.sync)
72
+ throw new ApiError(502, "this kraftwerk cloud keeps no repositories (kraftwerk sync is off there)");
73
+ const root = path.resolve(cwd, dirIn ?? folderName(joined.workspaceName));
74
+ let cloned = false;
75
+ const here = existsSync(root) ? await resolveWorkspace(root).catch(() => null) : null;
76
+ if (here?.configPath && path.dirname(here.configPath) === root && here.config.id === joined.workspaceId) {
77
+ // Already here: open it.
78
+ }
79
+ else if (existsSync(root) && (await fs.readdir(root)).length > 0) {
80
+ throw new ApiError(409, `${root} exists and is not empty — pass another folder: kraftwerk join <link> <folder>`);
81
+ }
82
+ else {
83
+ // A workspace whose repository has no history yet (begun locally, kraftwerk sync not set up there yet):
84
+ // nothing to clone — a kraftwerk.yml made here would collide with the owner's first push.
85
+ const heads = await git(["ls-remote", "--heads", "--", joined.sync.url], cwd, NET_TIMEOUT, remoteAuthEnv());
86
+ if (!heads.ok)
87
+ throw new ApiError(502, `kraftwerk sync did not answer: ${heads.stderr || "unknown error"}`);
88
+ if (!heads.stdout.trim()) {
89
+ throw new ApiError(409, `${joined.workspaceName} has no files in kraftwerk sync yet — whoever runs it has to set up kraftwerk sync first (kraftwerk → Git → "set up kraftwerk sync"); then run this again. This machine is linked to ${joined.account} already.`);
90
+ }
91
+ await fs.mkdir(path.dirname(root), { recursive: true });
92
+ const r = await git(["clone", "-q", "--", joined.sync.url, root], path.dirname(root), NET_TIMEOUT * 5, remoteAuthEnv());
93
+ if (!r.ok)
94
+ throw new ApiError(502, `cloning from kraftwerk sync failed: ${r.stderr || "unknown error"}`);
95
+ cloned = true;
96
+ }
97
+ const o = await currentHub().open(root);
98
+ // The cloud learns the workspace is here now (its host list, sign-in).
99
+ await syncMachineCloud().catch(() => { });
100
+ // Signed in at once: the link proved the account (server/users.ts issueHandoff).
101
+ const accountId = cloudStatus().accountId;
102
+ const token = accountId ? await issueHandoff(joined.workspaceId, accountId) : null;
103
+ return {
104
+ workspace: { id: joined.workspaceId, name: joined.workspaceName, slug: o.slug, url: o.url },
105
+ ...(token ? { signin: `${o.url}/auth/handoff?t=${token}` } : {}),
106
+ root,
107
+ role: joined.role,
108
+ account: joined.account,
109
+ cloned,
110
+ };
111
+ }
@@ -1,3 +1,4 @@
1
+ import { fetchCloudEvents } from "./cloud-events.js";
1
2
  import { createHash, randomBytes } from "node:crypto";
2
3
  import { promises as fs } from "node:fs";
3
4
  import http from "node:http";
@@ -322,6 +323,10 @@ export async function startRelay(opts) {
322
323
  }
323
324
  else if (msg.t === "close" && msg.c)
324
325
  dropConn(msg.c);
326
+ else if (msg.t === "poke") {
327
+ // The cloud has events for this machine (a task handed to its person, one for an agent): fetch them now.
328
+ void fetchCloudEvents().catch(() => { });
329
+ }
325
330
  else if (msg.t === "push_invalid" && typeof msg.token === "string") {
326
331
  // Apple no longer knows the token (the app was deleted, or pushes turned off): stop sending to it.
327
332
  void dropPushToken(msg.token).catch(() => { });
@@ -0,0 +1,31 @@
1
+ import { type GitStatus } from "../core/git.js";
2
+ /**
3
+ * kraftwerk sync, set up in one go: the workspace's history goes to its own
4
+ * repository in kraftwerk cloud (`<cloud>/git/<id>.git`), and the daemon
5
+ * reaches it with the machine's key (server/cloud.ts → core/git.ts
6
+ * setRemoteAuth) — no token in a URL, no credential helper.
7
+ *
8
+ * 1. needs the workspace in cloud mode on a claimed, connected machine (the
9
+ * git server lets a machine in by its account's role on the workspace)
10
+ * 2. a git repository at the workspace's root (`git init -b main` when
11
+ * there is none; a workspace inside a bigger repository is expert mode
12
+ * and left alone)
13
+ * 3. `git:` on in kraftwerk.yml, `autosync: sync` every 60 s when it was
14
+ * off: what changes is committed and goes up by itself, the others'
15
+ * changes come in (core/git.ts syncNow)
16
+ * 4. the remote: added when there is none; one that already points at the
17
+ * workspace's cloud repo is fine; one of another provider (expert mode)
18
+ * is never replaced
19
+ * 5. a first commit of the workspace's files when there is no history yet,
20
+ * then a push that sets the upstream
21
+ *
22
+ * Safe to run again: each step that is already done is skipped.
23
+ */
24
+ export interface SyncSetup {
25
+ ok: boolean;
26
+ /** What was done, in order — for the UI's "done" line. */
27
+ done: string[];
28
+ error?: string;
29
+ status: GitStatus;
30
+ }
31
+ export declare function setupSync(): Promise<SyncSetup>;
@@ -0,0 +1,90 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { parseDocument } from "yaml";
4
+ import { resolveWorkspace, usersMode } from "../config.js";
5
+ import { workspaceRoot } from "../core/context.js";
6
+ import { git, gitCommit, gitFetch, gitPush, gitStatus, repoRootFor, withoutCredentials } from "../core/git.js";
7
+ import { ApiError } from "./api/router.js";
8
+ import { cloudStatus, syncUrl } from "./cloud.js";
9
+ const answer = async (done, error) => ({
10
+ ok: !error,
11
+ done,
12
+ ...(error ? { error } : {}),
13
+ status: await gitStatus(true),
14
+ });
15
+ export async function setupSync() {
16
+ const done = [];
17
+ const ws = await resolveWorkspace(workspaceRoot());
18
+ const st = cloudStatus();
19
+ if (!ws.config.id || usersMode(ws.config) !== "cloud") {
20
+ throw new ApiError(409, "kraftwerk sync is part of cloud mode — switch the workspace to cloud first (Settings → local or cloud)");
21
+ }
22
+ if (st.state !== "connected" || !st.account) {
23
+ throw new ApiError(409, "this machine is not connected to kraftwerk cloud with an account yet — finish cloud mode first");
24
+ }
25
+ const url = syncUrl(ws.config.id);
26
+ // 2. The repository.
27
+ const root = await repoRootFor(ws.root);
28
+ if (!root) {
29
+ const r = await git(["init", "-q", "-b", "main"], ws.root);
30
+ if (!r.ok)
31
+ throw new ApiError(500, `git init failed: ${r.stderr}`);
32
+ done.push("started a git repository");
33
+ }
34
+ else if (path.resolve(root) !== path.resolve(ws.root)) {
35
+ throw new ApiError(409, `the workspace is inside the git repository at ${root} — that is expert mode; set its remote up there`);
36
+ }
37
+ // 3. git: on.
38
+ const configPath = ws.configPath ?? path.join(ws.root, "kraftwerk.yml");
39
+ const doc = parseDocument(ws.configPath ? await fs.readFile(configPath, "utf8") : "");
40
+ const g = ws.config.git;
41
+ if (!g || g.enabled === false) {
42
+ doc.setIn(["git", "enabled"], true);
43
+ if (!g?.autosync) {
44
+ doc.setIn(["git", "autosync"], "sync");
45
+ if (g?.interval === undefined)
46
+ doc.setIn(["git", "interval"], 60);
47
+ }
48
+ await fs.writeFile(configPath, doc.toString());
49
+ done.push("turned git sync on (autosync: sync)");
50
+ }
51
+ const remote = g?.remote ?? "origin";
52
+ // 4. The remote.
53
+ const current = await git(["remote", "get-url", remote], ws.root);
54
+ if (!current.ok) {
55
+ const r = await git(["remote", "add", "--", remote, url], ws.root);
56
+ if (!r.ok)
57
+ throw new ApiError(500, `git remote add failed: ${r.stderr}`);
58
+ done.push(`added the remote ${remote} → ${url}`);
59
+ }
60
+ else if (withoutCredentials(current.stdout.trim()) !== url) {
61
+ throw new ApiError(409, `${remote} already points at ${withoutCredentials(current.stdout.trim())} — your own git provider (expert mode). kraftwerk sync does not replace it; remove that remote first to use kraftwerk sync instead`);
62
+ }
63
+ // 5. History, then up.
64
+ const hasHead = (await git(["rev-parse", "--verify", "-q", "HEAD"], ws.root)).ok;
65
+ if (!hasHead) {
66
+ const files = ((await gitStatus(true)).files ?? []).filter((f) => f.syncable).map((f) => f.path);
67
+ if (files.length === 0)
68
+ return answer(done, "nothing to commit yet — the workspace has no files git sync takes");
69
+ const c = await gitCommit(files, "kraftwerk sync: the workspace's first commit");
70
+ if (!c.ok)
71
+ return answer(done, c.error ?? "the first commit failed");
72
+ done.push(`committed ${files.length} file${files.length === 1 ? "" : "s"}`);
73
+ }
74
+ const fetched = await gitFetch();
75
+ if (!fetched.ok)
76
+ return answer(done, fetched.error ?? "could not reach the cloud repository");
77
+ const now = await gitStatus(true);
78
+ if (now.upstream && !now.ahead) {
79
+ done.push("kraftwerk sync is up to date");
80
+ return answer(done);
81
+ }
82
+ const pushed = await gitPush();
83
+ if (!pushed.ok) {
84
+ return answer(done, /rejected|non-fast-forward|fetch first/.test(pushed.error ?? "")
85
+ ? "the cloud repository already has other history — pull it in a terminal, then push"
86
+ : (pushed.error ?? "push failed"));
87
+ }
88
+ done.push("pushed to kraftwerk sync");
89
+ return answer(done);
90
+ }
@@ -22,6 +22,12 @@ import { type CloudUser } from "../core/cloud.js";
22
22
  *
23
23
  * The state of a sign-in in flight is bound to the browser that started it
24
24
  * (the kw_signin cookie) and lives ten minutes.
25
+ *
26
+ * `kraftwerk join` skips the round through the cloud: the link it was run
27
+ * with already proved the account (the cloud claimed this machine for it),
28
+ * so the daemon asks the cloud once more who that account is on the
29
+ * workspace (signinVerify) and hands the browser it opens a one-time
30
+ * /auth/handoff link — single use, five minutes — that becomes the session.
25
31
  */
26
32
  export declare const USER_COOKIE = "kw_user";
27
33
  /** How often a signed-in person is checked with the cloud again — tests shorten it; no argument restores the default. */
@@ -30,6 +36,11 @@ export interface SignedIn {
30
36
  user: CloudUser;
31
37
  role: "owner" | "member";
32
38
  }
39
+ /**
40
+ * A one-time sign-in for `accountId` on `workspaceId`, confirmed by the cloud
41
+ * now: the token for /auth/handoff?t=…. Null when the cloud does not confirm.
42
+ */
43
+ export declare function issueHandoff(workspaceId: string, accountId: string): Promise<string | null>;
33
44
  export declare function cookieOf(req: http.IncomingMessage, name: string): string | undefined;
34
45
  /**
35
46
  * Whether the request comes from a browser. Browsers say where a fetch came