@netnodeag/kraftwerk 0.101.0 → 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 (44) hide show
  1. package/README.md +38 -2
  2. package/dist/cli/join.js +4 -2
  3. package/dist/config.d.ts +2 -2
  4. package/dist/config.js +3 -3
  5. package/dist/core/boards.d.ts +3 -0
  6. package/dist/core/boards.js +16 -2
  7. package/dist/core/cloud.d.ts +5 -0
  8. package/dist/core/git.d.ts +34 -2
  9. package/dist/core/git.js +218 -6
  10. package/dist/core/notifications.d.ts +3 -2
  11. package/dist/core/settings.d.ts +1 -1
  12. package/dist/core/settings.js +2 -2
  13. package/dist/server/cloud-events.d.ts +8 -0
  14. package/dist/server/cloud-events.js +199 -0
  15. package/dist/server/cloud.d.ts +8 -0
  16. package/dist/server/cloud.js +41 -1
  17. package/dist/server/join.d.ts +6 -2
  18. package/dist/server/join.js +13 -4
  19. package/dist/server/relay.js +5 -0
  20. package/dist/server/sync-setup.d.ts +3 -2
  21. package/dist/server/sync-setup.js +6 -3
  22. package/dist/server/users.d.ts +11 -0
  23. package/dist/server/users.js +63 -15
  24. package/dist/server/workspace-cloud.d.ts +3 -1
  25. package/dist/server/workspace-cloud.js +18 -8
  26. package/package.json +1 -1
  27. package/web/dist/assets/{dist-BgG4OIU9.js → dist-B09k-Kwi.js} +1 -1
  28. package/web/dist/assets/{dist-Db9KgP0W.js → dist-BG9MPqC7.js} +1 -1
  29. package/web/dist/assets/{dist-Bi5Y6JmO.js → dist-BbST9sxK.js} +1 -1
  30. package/web/dist/assets/{dist-CiGlBloC.js → dist-BrXAphjl.js} +1 -1
  31. package/web/dist/assets/{dist-Bd_SvBeU.js → dist-C0Ulmjwh.js} +1 -1
  32. package/web/dist/assets/{dist-DTxqCKQj.js → dist-C8wsDqpL.js} +1 -1
  33. package/web/dist/assets/{dist-Cfj7O2BI.js → dist-CJk4RtqY.js} +1 -1
  34. package/web/dist/assets/{dist-DXGv3DRS.js → dist-CfSpo_bP.js} +1 -1
  35. package/web/dist/assets/dist-DMU8iY9H.js +1 -0
  36. package/web/dist/assets/{dist-Cq4ezkbk.js → dist-Dv55aORJ.js} +1 -1
  37. package/web/dist/assets/{dist-Co1Cz1EB.js → dist-QQHKzUGH.js} +1 -1
  38. package/web/dist/assets/{editor-CH-WK0Ag.js → editor-Co8xGDnf.js} +3 -3
  39. package/web/dist/assets/index-CepQsH8H.js +488 -0
  40. package/web/dist/assets/index-DJGLnVQY.css +2 -0
  41. package/web/dist/index.html +2 -2
  42. package/web/dist/assets/dist-DeUP_9vJ.js +0 -1
  43. package/web/dist/assets/index-ClVr51ut.css +0 -2
  44. package/web/dist/assets/index-CnwVoHX3.js +0 -488
@@ -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,10 +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;
107
111
  /** HTTP Basic with the machine's id and secret — what kraftwerk sync's git server takes from a machine. */
108
112
  export declare const syncAuthHeader: (creds: Credentials) => string;
109
113
  /** kraftwerk sync's repository for workspace `id` on this machine's cloud, or null without one. */
110
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>;
111
119
  /** The served workspace whose kraftwerk.yml `id` is `id` (vetoed ones not), or null. */
112
120
  export declare function servedWorkspace(id: string): Promise<{
113
121
  slug: string;
@@ -6,12 +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 } from "../core/git.js";
9
+ import { setRemoteAuth, setSyncAuthor } from "../core/git.js";
10
+ import { installCloudEvents } from "./cloud-events.js";
10
11
  const DEFAULT_INTERVAL = 60;
11
12
  const STANDALONE = { url: "", state: "off", reason: "only the daemon registers this machine with the cloud (`kraftwerk daemon start`)" };
12
13
  const m = {
13
14
  status: { ...STANDALONE },
14
15
  creds: null,
16
+ /** Workspaces (ws_ ids) this machine reports that were deleted in the cloud. */
17
+ deleted: new Set(),
15
18
  registered: false,
16
19
  timer: null,
17
20
  started: false,
@@ -127,6 +130,8 @@ async function register() {
127
130
  // An unclaimed register carries no roots: the list counts as reported only when that is all the cloud should know.
128
131
  m.reported = r.account ? "" : JSON.stringify(list);
129
132
  await noteAccount(r);
133
+ m.deleted = new Set(r.deletedWorkspaces ?? []);
134
+ queueMicrotask(() => cloudChanged());
130
135
  m.status = {
131
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(),
132
137
  claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(cloud.url, r.claimCode), workspaces: list.length,
@@ -160,6 +165,11 @@ async function heartbeat() {
160
165
  m.reported = now;
161
166
  m.routines = ran;
162
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(() => { });
163
173
  m.status = {
164
174
  ...m.status, state: "connected", error: undefined, interval: r.interval || m.status.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
165
175
  ...(r.account !== undefined ? { account: r.account, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null } : {}),
@@ -219,11 +229,15 @@ export async function startMachineCloud(opts) {
219
229
  await fs.rm(retiredCloudDir(), { recursive: true, force: true }).catch(() => { });
220
230
  // The machine's id exists from the daemon's first start on, with the relay still off.
221
231
  m.creds = await machineCredentials().catch(() => null);
232
+ // Cloud-board events: notifications and agent wakes (cloud-events.ts).
233
+ installCloudEvents();
222
234
  // kraftwerk sync: git reaches the workspaces' cloud repos with this machine's key (core/git.ts).
223
235
  setRemoteAuth(() => {
224
236
  const link = machineLink();
225
237
  return link ? { [`${link.url}/git/`]: syncAuthHeader(link.creds) } : {};
226
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));
227
241
  await serial(register);
228
242
  schedule();
229
243
  return m.status;
@@ -250,6 +264,7 @@ export async function applyMachineCloud() {
250
264
  clearTimeout(m.timer);
251
265
  m.timer = null;
252
266
  m.status = { url: cloud.url, state: "off", source: cloud.source, ...(cloud.reason ? { reason: cloud.reason } : {}) };
267
+ cloudChanged();
253
268
  return m.status;
254
269
  }
255
270
  if (!m.registered)
@@ -282,6 +297,7 @@ export async function unlinkMachineCloud() {
282
297
  m.routines = "";
283
298
  await writeAccountFile(null);
284
299
  m.status = { ...m.status, account: null, accountId: null, accountHandle: null, claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(m.status.url, r.claimCode) };
300
+ cloudChanged();
285
301
  return m.status;
286
302
  });
287
303
  }
@@ -302,6 +318,7 @@ export async function stopMachineCloud(owner) {
302
318
  m.registered = false;
303
319
  m.reported = "";
304
320
  m.status = { ...STANDALONE };
321
+ cloudChanged();
305
322
  if (registered && creds && url)
306
323
  await machineGoodbye(url, creds, m.version).catch(() => { });
307
324
  }
@@ -315,6 +332,18 @@ export function machineLink() {
315
332
  return null;
316
333
  return { url: m.status.url, creds: m.creds, version: m.version };
317
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);
318
347
  /** HTTP Basic with the machine's id and secret — what kraftwerk sync's git server takes from a machine. */
319
348
  export const syncAuthHeader = (creds) => `Authorization: Basic ${Buffer.from(`${creds.id}:${creds.secret}`).toString("base64")}`;
320
349
  /** kraftwerk sync's repository for workspace `id` on this machine's cloud, or null without one. */
@@ -322,6 +351,17 @@ export function syncUrl(id) {
322
351
  const url = cloudStatus().url;
323
352
  return url ? `${url}/git/${encodeURIComponent(id)}.git` : null;
324
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
+ }
325
365
  /** The served workspace whose kraftwerk.yml `id` is `id` (vetoed ones not), or null. */
326
366
  export async function servedWorkspace(id) {
327
367
  for (const o of m.source()) {
@@ -9,8 +9,10 @@
9
9
  * the cloud claims it for the code's account and names the workspace
10
10
  * 3. the workspace cloned from kraftwerk sync into the folder — the machine's
11
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
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)
14
16
  *
15
17
  * Again on a folder that already holds the workspace: no clone, just open.
16
18
  */
@@ -21,6 +23,8 @@ export interface JoinResult {
21
23
  slug: string;
22
24
  url: string;
23
25
  };
26
+ /** Opens the workspace signed in as the account (one use, five minutes); absent when the cloud did not confirm. */
27
+ signin?: string;
24
28
  root: string;
25
29
  role: string;
26
30
  account: string;
@@ -7,6 +7,7 @@ import { git, NET_TIMEOUT, remoteAuthEnv } from "../core/git.js";
7
7
  import { ApiError } from "./api/router.js";
8
8
  import { applyMachineCloud, cloudStatus, machineLink, syncMachineCloud } from "./cloud.js";
9
9
  import { currentHub } from "./hub-context.js";
10
+ import { issueHandoff } from "./users.js";
10
11
  /** `<origin>/join/<code>` or a bare code (this machine's cloud). */
11
12
  export function parseJoinLink(raw) {
12
13
  const text = raw.trim();
@@ -79,21 +80,29 @@ export async function joinWorkspace(link, dirIn, cwd) {
79
80
  throw new ApiError(409, `${root} exists and is not empty — pass another folder: kraftwerk join <link> <folder>`);
80
81
  }
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
+ }
82
91
  await fs.mkdir(path.dirname(root), { recursive: true });
83
92
  const r = await git(["clone", "-q", "--", joined.sync.url, root], path.dirname(root), NET_TIMEOUT * 5, remoteAuthEnv());
84
93
  if (!r.ok)
85
94
  throw new ApiError(502, `cloning from kraftwerk sync failed: ${r.stderr || "unknown error"}`);
86
95
  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
96
  }
92
97
  const o = await currentHub().open(root);
93
98
  // The cloud learns the workspace is here now (its host list, sign-in).
94
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;
95
103
  return {
96
104
  workspace: { id: joined.workspaceId, name: joined.workspaceName, slug: o.slug, url: o.url },
105
+ ...(token ? { signin: `${o.url}/auth/handoff?t=${token}` } : {}),
97
106
  root,
98
107
  role: joined.role,
99
108
  account: joined.account,
@@ -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(() => { });
@@ -10,8 +10,9 @@ import { type GitStatus } from "../core/git.js";
10
10
  * 2. a git repository at the workspace's root (`git init -b main` when
11
11
  * there is none; a workspace inside a bigger repository is expert mode
12
12
  * and left alone)
13
- * 3. `git:` on in kraftwerk.yml, `autosync: push` when it was off, so what
14
- * is committed goes up by itself
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)
15
16
  * 4. the remote: added when there is none; one that already points at the
16
17
  * workspace's cloud repo is fine; one of another provider (expert mode)
17
18
  * is never replaced
@@ -40,10 +40,13 @@ export async function setupSync() {
40
40
  const g = ws.config.git;
41
41
  if (!g || g.enabled === false) {
42
42
  doc.setIn(["git", "enabled"], true);
43
- if (!g?.autosync)
44
- doc.setIn(["git", "autosync"], "push");
43
+ if (!g?.autosync) {
44
+ doc.setIn(["git", "autosync"], "sync");
45
+ if (g?.interval === undefined)
46
+ doc.setIn(["git", "interval"], 60);
47
+ }
45
48
  await fs.writeFile(configPath, doc.toString());
46
- done.push("turned git sync on (autosync: push)");
49
+ done.push("turned git sync on (autosync: sync)");
47
50
  }
48
51
  const remote = g?.remote ?? "origin";
49
52
  // 4. The remote.
@@ -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
@@ -27,6 +27,12 @@ import { machineLink } from "./cloud.js";
27
27
  *
28
28
  * The state of a sign-in in flight is bound to the browser that started it
29
29
  * (the kw_signin cookie) and lives ten minutes.
30
+ *
31
+ * `kraftwerk join` skips the round through the cloud: the link it was run
32
+ * with already proved the account (the cloud claimed this machine for it),
33
+ * so the daemon asks the cloud once more who that account is on the
34
+ * workspace (signinVerify) and hands the browser it opens a one-time
35
+ * /auth/handoff link — single use, five minutes — that becomes the session.
30
36
  */
31
37
  export const USER_COOKIE = "kw_user";
32
38
  const STATE_COOKIE = "kw_signin";
@@ -38,6 +44,30 @@ let recheckMs = DEFAULT_RECHECK_MS;
38
44
  export function setUserRecheck(ms) {
39
45
  recheckMs = ms ?? DEFAULT_RECHECK_MS;
40
46
  }
47
+ const HANDOFF_TTL_MS = 5 * 60_000;
48
+ const handoffs = new Map();
49
+ /**
50
+ * A one-time sign-in for `accountId` on `workspaceId`, confirmed by the cloud
51
+ * now: the token for /auth/handoff?t=…. Null when the cloud does not confirm.
52
+ */
53
+ export async function issueHandoff(workspaceId, accountId) {
54
+ const link = machineLink();
55
+ if (!link)
56
+ return null;
57
+ let r;
58
+ try {
59
+ r = await signinVerify(link.url, link.creds, workspaceId, accountId, link.version);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ for (const [k, h] of handoffs)
65
+ if (Date.now() - h.at > HANDOFF_TTL_MS)
66
+ handoffs.delete(k);
67
+ const token = randomBytes(32).toString("base64url");
68
+ handoffs.set(hash(token), { workspaceId, user: r.user, role: r.role, at: Date.now() });
69
+ return token;
70
+ }
41
71
  const file = () => path.join(os.homedir(), ".kraftwerk", "user-sessions.json");
42
72
  const hash = (token) => createHash("sha256").update(token).digest("hex");
43
73
  let sessions = null;
@@ -183,6 +213,19 @@ export async function handleAuth(req, res, url, t) {
183
213
  redirect(res, signinUrl(link.url, { workspace: t.workspaceId, machine: link.creds.id, redirect: back, state }), [cookie(STATE_COOKIE, state, STATE_TTL_MS / 1000)]);
184
214
  return true;
185
215
  }
216
+ if (route === "/auth/handoff" && req.method === "GET") {
217
+ const key = hash(url.searchParams.get("t") ?? "");
218
+ const h = handoffs.get(key);
219
+ handoffs.delete(key);
220
+ if (!h || Date.now() - h.at > HANDOFF_TTL_MS || h.workspaceId !== t.workspaceId) {
221
+ problem(res, 400, "This sign-in link is used up", "It works once, for five minutes, for the workspace it was made for.", signinPath);
222
+ return true;
223
+ }
224
+ const token = await startSession(req, h.workspaceId, h.user, h.role);
225
+ log("info", "users", `${h.user.handle} (${h.user.email}) signed in to ${h.workspaceId} (kraftwerk join)`);
226
+ redirect(res, safeNext(url.searchParams.get("next"), t.prefix), [cookie(USER_COOKIE, token, SESSION_TTL_MS / 1000)]);
227
+ return true;
228
+ }
186
229
  if (route === "/auth/callback" && req.method === "GET") {
187
230
  const state = url.searchParams.get("state") ?? "";
188
231
  const code = url.searchParams.get("code") ?? "";
@@ -209,21 +252,7 @@ export async function handleAuth(req, res, url, t) {
209
252
  problem(res, 400, "Signing in did not work", "The cloud answered for another workspace.", signinPath);
210
253
  return true;
211
254
  }
212
- const all = await load();
213
- // The same account signing in to another workspace on this origin keeps one session; anyone else starts afresh.
214
- const old = cookieOf(req, USER_COOKIE);
215
- let key = old ? hash(old) : "";
216
- let token = old ?? "";
217
- let s = key ? all.get(key) : undefined;
218
- if (!s || s.user.id !== r.user.id) {
219
- token = randomBytes(32).toString("base64url");
220
- key = hash(token);
221
- s = { user: r.user, createdAt: Date.now(), workspaces: {} };
222
- all.set(key, s);
223
- }
224
- s.user = r.user;
225
- s.workspaces[r.workspaceId] = { role: r.role, checkedAt: Date.now() };
226
- await save();
255
+ const token = await startSession(req, r.workspaceId, r.user, r.role);
227
256
  log("info", "users", `${r.user.handle} (${r.user.email}) signed in to ${r.workspaceId}`);
228
257
  redirect(res, p.next, [cookie(USER_COOKIE, token, SESSION_TTL_MS / 1000), cookie(STATE_COOKIE, "", 0)]);
229
258
  return true;
@@ -250,6 +279,25 @@ export async function handleAuth(req, res, url, t) {
250
279
  }
251
280
  return false;
252
281
  }
282
+ /** The browser's session for `user` with `workspaceId` added: its cookie value. */
283
+ async function startSession(req, workspaceId, user, role) {
284
+ const all = await load();
285
+ // The same account signing in to another workspace on this origin keeps one session; anyone else starts afresh.
286
+ const old = cookieOf(req, USER_COOKIE);
287
+ let key = old ? hash(old) : "";
288
+ let token = old ?? "";
289
+ let s = key ? all.get(key) : undefined;
290
+ if (!s || s.user.id !== user.id) {
291
+ token = randomBytes(32).toString("base64url");
292
+ key = hash(token);
293
+ s = { user, createdAt: Date.now(), workspaces: {} };
294
+ all.set(key, s);
295
+ }
296
+ s.user = user;
297
+ s.workspaces[workspaceId] = { role, checkedAt: Date.now() };
298
+ await save();
299
+ return token;
300
+ }
253
301
  /** Forget every session in memory (tests: the next read loads the file again). */
254
302
  export function forgetUserSessions() {
255
303
  sessions = null;
@@ -46,8 +46,10 @@ export interface WorkspaceCloud {
46
46
  account: string | null;
47
47
  claimCode: string | null;
48
48
  claimUrl: string | null;
49
- /** Why the machine is not connected, when it is not. */
49
+ /** Why the machine is not connected, when it is not — or that the workspace was deleted in the cloud. */
50
50
  problem?: string;
51
+ /** Deleted in kraftwerk cloud: its files here stay; cloud mode is over for it (switch to local). */
52
+ deleted?: boolean;
51
53
  }
52
54
  export declare function workspaceCloud(): Promise<WorkspaceCloud>;
53
55
  /** Switch the workspace to `mode`; to cloud as far as it goes now (see the top). */
@@ -5,7 +5,7 @@ import { addWorkspaceId, resolveWorkspace, usersMode } from "../config.js";
5
5
  import { envCloudOff, writeCloudFile } from "../core/cloud.js";
6
6
  import { workspaceRoot } from "../core/context.js";
7
7
  import { ApiError } from "./api/router.js";
8
- import { applyMachineCloud, cloudStatus, syncMachineCloud } from "./cloud.js";
8
+ import { applyMachineCloud, cloudStatus, deletedInCloud, syncMachineCloud } from "./cloud.js";
9
9
  import { currentHub } from "./hub-context.js";
10
10
  async function configDoc() {
11
11
  const ws = await resolveWorkspace(workspaceRoot());
@@ -26,13 +26,16 @@ export async function workspaceCloud() {
26
26
  const mode = usersMode(ws.config);
27
27
  const steps = { machine: connected, claim: claimed, workspace: id, signin: mode === "cloud" };
28
28
  const next = mode === "cloud" && claimed ? null : !daemon ? "daemon" : !connected ? (st.state === "connecting" ? "connect" : "machine") : !claimed ? "claim" : null;
29
- const problem = !daemon
30
- ? "only the kraftwerk daemon connects to the cloud — run `kraftwerk daemon` and open the workspace there"
31
- : st.state === "error"
32
- ? `kraftwerk cloud does not answer: ${st.error ?? "unknown error"}`
33
- : st.state === "off" && envCloudOff()
34
- ? "the cloud is turned off by KRAFTWERK_CLOUD_URL=off"
35
- : undefined;
29
+ const deleted = deletedInCloud(ws.config.id);
30
+ const problem = deleted
31
+ ? "this workspace was deleted in kraftwerk cloud — its files here are yours; switch it to local to keep working (a new id comes with the next switch to cloud)"
32
+ : !daemon
33
+ ? "only the kraftwerk daemon connects to the cloud — run `kraftwerk daemon` and open the workspace there"
34
+ : st.state === "error"
35
+ ? `kraftwerk cloud does not answer: ${st.error ?? "unknown error"}`
36
+ : st.state === "off" && envCloudOff()
37
+ ? "the cloud is turned off by KRAFTWERK_CLOUD_URL=off"
38
+ : undefined;
36
39
  return {
37
40
  mode,
38
41
  next,
@@ -44,6 +47,7 @@ export async function workspaceCloud() {
44
47
  claimCode: st.claimCode ?? null,
45
48
  claimUrl: st.claimUrl ?? null,
46
49
  ...(problem ? { problem } : {}),
50
+ ...(deleted ? { deleted: true } : {}),
47
51
  };
48
52
  }
49
53
  /** One switch at a time per workspace (see the top). */
@@ -74,6 +78,12 @@ async function toLocal() {
74
78
  async function toCloud() {
75
79
  if (currentHub().daemon !== true || envCloudOff())
76
80
  return workspaceCloud();
81
+ // Deleted in the cloud: the old id is gone for good — a fresh one, as for a new workspace.
82
+ if (deletedInCloud((await resolveWorkspace(workspaceRoot())).config.id)) {
83
+ const { configPath, doc } = await configDoc();
84
+ doc.delete("id");
85
+ await fs.writeFile(configPath, doc.toString());
86
+ }
77
87
  // 1. The machine's cloud on.
78
88
  if (cloudStatus().state === "off") {
79
89
  await writeCloudFile({ enabled: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@netnodeag/kraftwerk",
3
- "version": "0.101.0",
3
+ "version": "0.102.0",
4
4
  "description": "Open-source agentic workspace for teams — where people and AI agents get work done together: agents (Claude Code, Codex, Pi), skills, shared knowledge, repeatable workflows, and deterministic verification",
5
5
  "keywords": [
6
6
  "agents",