@netnodeag/kraftwerk 0.96.0 → 0.98.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 (69) hide show
  1. package/README.md +52 -0
  2. package/dist/cli/boards.js +6 -5
  3. package/dist/cli/init.js +2 -0
  4. package/dist/cli/knowledge.js +9 -6
  5. package/dist/cli/presentations.js +8 -4
  6. package/dist/cli/projects.js +1 -1
  7. package/dist/client/index.d.ts +2 -0
  8. package/dist/client/index.js +3 -0
  9. package/dist/client/routes.d.ts +12 -0
  10. package/dist/client/routes.js +12 -0
  11. package/dist/config.d.ts +34 -0
  12. package/dist/config.js +28 -1
  13. package/dist/core/boards.d.ts +3 -1
  14. package/dist/core/boards.js +32 -9
  15. package/dist/core/chat/sessions.d.ts +3 -3
  16. package/dist/core/chat/sessions.js +6 -5
  17. package/dist/core/chat/types.d.ts +2 -0
  18. package/dist/core/cloud.d.ts +45 -0
  19. package/dist/core/cloud.js +35 -0
  20. package/dist/core/knowledge.d.ts +0 -7
  21. package/dist/core/knowledge.js +6 -6
  22. package/dist/core/person.d.ts +41 -0
  23. package/dist/core/person.js +47 -0
  24. package/dist/core/projects.d.ts +1 -1
  25. package/dist/core/projects.js +3 -2
  26. package/dist/server/api/agents.js +2 -2
  27. package/dist/server/api/boards.js +1 -1
  28. package/dist/server/api/chats.js +11 -7
  29. package/dist/server/api/cloud.d.ts +8 -0
  30. package/dist/server/api/index.d.ts +86 -2
  31. package/dist/server/api/index.js +2 -0
  32. package/dist/server/api/presentations.js +2 -2
  33. package/dist/server/api/projects.d.ts +1 -1
  34. package/dist/server/api/projects.js +1 -1
  35. package/dist/server/api/remote-boards.d.ts +118 -0
  36. package/dist/server/api/remote-boards.js +51 -0
  37. package/dist/server/api/router.js +5 -2
  38. package/dist/server/api/workspace.d.ts +14 -1
  39. package/dist/server/api/workspace.js +21 -1
  40. package/dist/server/cloud.d.ts +3 -0
  41. package/dist/server/cloud.js +20 -4
  42. package/dist/server/person.d.ts +9 -0
  43. package/dist/server/person.js +14 -0
  44. package/dist/server/remote-boards.d.ts +35 -0
  45. package/dist/server/remote-boards.js +73 -0
  46. package/dist/server/server.js +60 -4
  47. package/dist/server/trust.d.ts +5 -1
  48. package/dist/server/users.d.ts +55 -0
  49. package/dist/server/users.js +258 -0
  50. package/package.json +1 -1
  51. package/schema/kraftwerk.schema.json +8 -0
  52. package/web/dist/assets/{dist-DkDmdJNX.js → dist-BKTdKbao.js} +1 -1
  53. package/web/dist/assets/{dist-DOW1X_nG.js → dist-BNpBR7sT.js} +1 -1
  54. package/web/dist/assets/dist-BRk23y92.js +1 -0
  55. package/web/dist/assets/{dist-DbBrc07-.js → dist-C83QYgqx.js} +1 -1
  56. package/web/dist/assets/{dist-14HFV7uD.js → dist-CJK_j1TB.js} +1 -1
  57. package/web/dist/assets/{dist-wkkpVezb.js → dist-CR_7NDsL.js} +1 -1
  58. package/web/dist/assets/{dist-DKQkCBo9.js → dist-ChYhEmdo.js} +1 -1
  59. package/web/dist/assets/{dist-DO04nOS3.js → dist-D-MsPdYw.js} +1 -1
  60. package/web/dist/assets/{dist-BYgXVWBg.js → dist-DxlgW6a_.js} +1 -1
  61. package/web/dist/assets/{dist-qkoQQWNK.js → dist-OpHqdZBt.js} +1 -1
  62. package/web/dist/assets/{dist-BiyjchCb.js → dist-gtc4RPDu.js} +1 -1
  63. package/web/dist/assets/{editor-DvkpSp7h.js → editor-RdZyT8Y9.js} +3 -3
  64. package/web/dist/assets/index-BGgQaaA9.css +2 -0
  65. package/web/dist/assets/index-J1hXaKgp.js +488 -0
  66. package/web/dist/index.html +2 -2
  67. package/web/dist/assets/dist-CCZcAg77.js +0 -1
  68. package/web/dist/assets/index-B5PLhJ-C.js +0 -488
  69. package/web/dist/assets/index-CWopPK15.css +0 -2
@@ -0,0 +1,118 @@
1
+ import * as z from "zod";
2
+ /**
3
+ * Remote boards over this machine's API (server/remote-boards.ts): the
4
+ * workspace's boards in kraftwerk cloud, multiplayer, beside the local
5
+ * boards (api/boards.ts). Every call goes to the cloud as the caller's
6
+ * person; 503 `{offline: true}` while the cloud is off or unreachable.
7
+ * Shapes are the cloud's (kraftwerk-cloud src/boards.ts).
8
+ */
9
+ export interface RemoteColumn {
10
+ slug: string;
11
+ title: string;
12
+ }
13
+ export interface RemoteBoardSummary {
14
+ slug: string;
15
+ title: string;
16
+ columns: RemoteColumn[];
17
+ counts: Record<string, number>;
18
+ taskCount: number;
19
+ createdBy: string | null;
20
+ createdAt: number;
21
+ updatedAt: number;
22
+ }
23
+ export interface RemoteTaskSummary {
24
+ number: number;
25
+ title: string;
26
+ status: string;
27
+ position: number;
28
+ /** human:<handle> or an agent slug. */
29
+ assignee: string | null;
30
+ assigneeId?: string;
31
+ due: string | null;
32
+ tags: string[];
33
+ createdBy: string;
34
+ createdAt: number;
35
+ updatedAt: number;
36
+ last: string | null;
37
+ }
38
+ export interface RemoteTaskDetail extends RemoteTaskSummary {
39
+ board: string;
40
+ notes: string;
41
+ log: {
42
+ at: number;
43
+ actor: string;
44
+ entry: string;
45
+ }[];
46
+ }
47
+ export interface RemotePerson {
48
+ id: string;
49
+ handle: string;
50
+ email: string;
51
+ role: "owner" | "member";
52
+ }
53
+ export declare const remoteBoardRoutes: (import("./router.js").Route<"remoteBoards.create", import("./router.js").Reply<{
54
+ board: RemoteBoardSummary;
55
+ }>, "/api/remote-boards", z.ZodObject<{
56
+ title: z.ZodOptional<z.ZodString>;
57
+ slug: z.ZodOptional<z.ZodString>;
58
+ columns: z.ZodOptional<z.ZodArray<z.ZodObject<{
59
+ slug: z.ZodOptional<z.ZodString>;
60
+ title: z.ZodString;
61
+ }, z.core.$strip>>>;
62
+ }, z.core.$strip>> | import("./router.js").Route<"remoteBoards.delete", {
63
+ ok: true;
64
+ }, "/api/remote-boards/:board", undefined> | import("./router.js").Route<"remoteBoards.get", {
65
+ board: RemoteBoardSummary;
66
+ tasks: RemoteTaskSummary[];
67
+ people: RemotePerson[];
68
+ actor: string;
69
+ }, "/api/remote-boards/:board", undefined> | import("./router.js").Route<"remoteBoards.list", {
70
+ boards: RemoteBoardSummary[];
71
+ role: "owner" | "member";
72
+ actor: string;
73
+ cloudUrl: string | null;
74
+ }, "/api/remote-boards", undefined> | import("./router.js").Route<"remoteBoards.people", {
75
+ people: RemotePerson[];
76
+ actor: string;
77
+ role: "owner" | "member";
78
+ }, "/api/remote-boards/people", undefined> | import("./router.js").Route<"remoteBoards.save", {
79
+ board: RemoteBoardSummary;
80
+ }, "/api/remote-boards/:board", z.ZodObject<{
81
+ title: z.ZodOptional<z.ZodString>;
82
+ slug: z.ZodOptional<z.ZodString>;
83
+ columns: z.ZodOptional<z.ZodArray<z.ZodObject<{
84
+ slug: z.ZodOptional<z.ZodString>;
85
+ title: z.ZodString;
86
+ }, z.core.$strip>>>;
87
+ }, z.core.$strip>> | import("./router.js").Route<"remoteTasks.create", import("./router.js").Reply<{
88
+ task: RemoteTaskDetail;
89
+ }>, "/api/remote-boards/:board/tasks", z.ZodObject<{
90
+ title: z.ZodOptional<z.ZodString>;
91
+ status: z.ZodOptional<z.ZodString>;
92
+ position: z.ZodOptional<z.ZodNumber>;
93
+ assignee: z.ZodOptional<z.ZodNullable<z.ZodString>>;
94
+ due: z.ZodOptional<z.ZodNullable<z.ZodString>>;
95
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
96
+ notes: z.ZodOptional<z.ZodString>;
97
+ actor: z.ZodOptional<z.ZodString>;
98
+ }, z.core.$strip>> | import("./router.js").Route<"remoteTasks.delete", {
99
+ ok: true;
100
+ }, "/api/remote-boards/:board/tasks/:task", undefined> | import("./router.js").Route<"remoteTasks.get", {
101
+ task: RemoteTaskDetail;
102
+ }, "/api/remote-boards/:board/tasks/:task", undefined> | import("./router.js").Route<"remoteTasks.log", {
103
+ task: RemoteTaskDetail;
104
+ }, "/api/remote-boards/:board/tasks/:task/log", z.ZodObject<{
105
+ entry: z.ZodString;
106
+ actor: z.ZodOptional<z.ZodString>;
107
+ }, z.core.$strip>> | import("./router.js").Route<"remoteTasks.save", {
108
+ task: RemoteTaskDetail;
109
+ }, "/api/remote-boards/:board/tasks/:task", z.ZodObject<{
110
+ title: z.ZodOptional<z.ZodString>;
111
+ status: z.ZodOptional<z.ZodString>;
112
+ position: z.ZodOptional<z.ZodNumber>;
113
+ assignee: z.ZodOptional<z.ZodNullable<z.ZodString>>;
114
+ due: z.ZodOptional<z.ZodNullable<z.ZodString>>;
115
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
116
+ notes: z.ZodOptional<z.ZodString>;
117
+ actor: z.ZodOptional<z.ZodString>;
118
+ }, z.core.$strip>>)[];
@@ -0,0 +1,51 @@
1
+ import * as z from "zod";
2
+ import { remoteCall, remoteWorkspaceUrl } from "../remote-boards.js";
3
+ import { reply, route } from "./router.js";
4
+ const BoardFields = z.object({
5
+ title: z.string().optional(),
6
+ slug: z.string().optional(),
7
+ columns: z.array(z.object({ slug: z.string().optional(), title: z.string() })).optional(),
8
+ });
9
+ const TaskFields = z.object({
10
+ title: z.string().optional(),
11
+ status: z.string().optional(),
12
+ position: z.number().optional(),
13
+ assignee: z.string().nullable().optional(),
14
+ due: z.string().nullable().optional(),
15
+ tags: z.array(z.string()).optional(),
16
+ notes: z.string().optional(),
17
+ /** An agent or process naming itself; a person is whoever asks. */
18
+ actor: z.string().optional(),
19
+ });
20
+ const board = (c) => `boards/${encodeURIComponent(c.params.board)}`;
21
+ const task = (c) => `${board(c)}/tasks/${encodeURIComponent(c.params.task)}`;
22
+ const actorOf = (c) => c.query.get("actor") ?? undefined;
23
+ const withoutActor = (b) => {
24
+ const { actor: _a, ...rest } = b;
25
+ return rest;
26
+ };
27
+ export const remoteBoardRoutes = [
28
+ route({ name: "remoteBoards.list", method: "GET", path: "/api/remote-boards", summary: "the workspace's remote boards in kraftwerk cloud (503 offline: true while unreachable)" }, async (c) => {
29
+ const r = await remoteCall(c.trust, { method: "GET", path: "boards", actor: actorOf(c) });
30
+ return { ...r, cloudUrl: await remoteWorkspaceUrl() };
31
+ }),
32
+ route({ name: "remoteBoards.create", method: "POST", path: "/api/remote-boards", summary: "create a remote board {title, slug?, columns?}", body: BoardFields }, async (c) => reply(201, await remoteCall(c.trust, { method: "POST", path: "boards", body: await c.body() }))),
33
+ route({ name: "remoteBoards.people", method: "GET", path: "/api/remote-boards/people", summary: "the people of the workspace (assignable as human:<handle>) and who you are there" }, async (c) => remoteCall(c.trust, { method: "GET", path: "people", actor: actorOf(c) })),
34
+ route({ name: "remoteBoards.get", method: "GET", path: "/api/remote-boards/:board", summary: "a remote board: columns, counts, every task, the people" }, async (c) => remoteCall(c.trust, { method: "GET", path: board(c), actor: actorOf(c) })),
35
+ route({ name: "remoteBoards.save", method: "PUT", path: "/api/remote-boards/:board", summary: "rename a remote board or change its columns", body: BoardFields }, async (c) => remoteCall(c.trust, { method: "PUT", path: board(c), body: await c.body() })),
36
+ route({ name: "remoteBoards.delete", method: "DELETE", path: "/api/remote-boards/:board", summary: "delete a remote board with its tasks (owners only; no trash)" }, async (c) => remoteCall(c.trust, { method: "DELETE", path: board(c) })),
37
+ route({ name: "remoteTasks.create", method: "POST", path: "/api/remote-boards/:board/tasks", summary: "create a task {title, status?, assignee?, due?, tags?, notes?, actor?}", body: TaskFields }, async (c) => {
38
+ const b = await c.body();
39
+ return reply(201, await remoteCall(c.trust, { method: "POST", path: `${board(c)}/tasks`, body: withoutActor(b), actor: b.actor }));
40
+ }),
41
+ route({ name: "remoteTasks.get", method: "GET", path: "/api/remote-boards/:board/tasks/:task", summary: "a remote task with notes and its log (:task = number)" }, async (c) => remoteCall(c.trust, { method: "GET", path: task(c), actor: actorOf(c) })),
42
+ route({ name: "remoteTasks.save", method: "PUT", path: "/api/remote-boards/:board/tasks/:task", summary: "change a remote task (status, assignee, …); every change is logged with its actor", body: TaskFields }, async (c) => {
43
+ const b = await c.body();
44
+ return remoteCall(c.trust, { method: "PUT", path: task(c), body: withoutActor(b), actor: b.actor });
45
+ }),
46
+ route({ name: "remoteTasks.log", method: "POST", path: "/api/remote-boards/:board/tasks/:task/log", summary: "add a line to a remote task's log {entry, actor?}", body: z.object({ entry: z.string(), actor: z.string().optional() }) }, async (c) => {
47
+ const b = await c.body();
48
+ return remoteCall(c.trust, { method: "POST", path: `${task(c)}/log`, body: { entry: b.entry }, actor: b.actor });
49
+ }),
50
+ route({ name: "remoteTasks.delete", method: "DELETE", path: "/api/remote-boards/:board/tasks/:task", summary: "delete a remote task (no trash)" }, async (c) => remoteCall(c.trust, { method: "DELETE", path: task(c) })),
51
+ ];
@@ -1,5 +1,7 @@
1
1
  import * as z from "zod";
2
2
  import { touch } from "../live.js";
3
+ import { runAs } from "../../core/person.js";
4
+ import { personOf } from "../person.js";
3
5
  /** A result with a status other than 200 (201 created, 409 with a body, …), and headers for HTTP (a cookie); the socket ignores them. */
4
6
  export class Reply {
5
7
  status;
@@ -176,7 +178,8 @@ export function createRouter(routes) {
176
178
  return validate(route, parsed);
177
179
  })),
178
180
  };
179
- const result = await route.handle(c);
181
+ // Whoever asks is who a human change is signed with (core/person.ts).
182
+ const result = await runAs(() => personOf(trust), () => route.handle(c));
180
183
  if (route.method !== "GET")
181
184
  touch();
182
185
  if (route.raw)
@@ -225,7 +228,7 @@ export function createRouter(routes) {
225
228
  trust,
226
229
  body: async () => validate(route, input.body ?? {}),
227
230
  };
228
- const result = await route.handle(c);
231
+ const result = await runAs(() => personOf(trust), () => route.handle(c));
229
232
  if (route.method !== "GET")
230
233
  touch();
231
234
  return result instanceof Reply ? { status: result.status, data: result.body } : { status: 200, data: result };
@@ -11,7 +11,18 @@ export declare const workspaceRoutes: (import("./router.js").Route<"identity.get
11
11
  machine: string;
12
12
  identity: string;
13
13
  previous: string[];
14
- }, "/api/identity", undefined> | import("./router.js").Route<"meta.get", {
14
+ }, "/api/identity", undefined> | import("./router.js").Route<"me.get", {
15
+ mode: import("../../config.js").UsersMode;
16
+ handle: string;
17
+ actor: string;
18
+ id?: string | undefined;
19
+ email?: string | undefined;
20
+ /** A browser signed in with its cloud account (users: cloud); false for this machine's own shell, a device, a member. */
21
+ signedIn: boolean;
22
+ role?: "member" | "owner" | undefined;
23
+ /** How the signed-in person got here: through the relay as a member, or on this machine. */
24
+ via: "device" | "local" | "member";
25
+ }, "/api/me", undefined> | import("./router.js").Route<"meta.get", {
15
26
  workspaceName: string;
16
27
  workspaceSlug: string;
17
28
  workspaceIcon: string;
@@ -50,6 +61,8 @@ export declare const workspaceRoutes: (import("./router.js").Route<"identity.get
50
61
  id?: string;
51
62
  machine?: string;
52
63
  account?: string | null;
64
+ accountId?: string | null;
65
+ accountHandle?: string | null;
53
66
  interval?: number;
54
67
  lastSeen?: string;
55
68
  claimCode?: string | null;
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import * as z from "zod";
3
- import { absolutePath, resolveWorkspace, slugFromFolder, workspaceSlug } from "../../config.js";
3
+ import { absolutePath, resolveWorkspace, slugFromFolder, usersMode, workspaceSlug } from "../../config.js";
4
4
  import { disposeAllBackends } from "../../core/chat/sessions.js";
5
5
  import { cloudStatus } from "../cloud.js";
6
6
  import { workspaceRoot } from "../../core/context.js";
@@ -12,6 +12,7 @@ import { canSelfUpdate, startUpdate, updateStatus } from "../../core/update.js";
12
12
  import { getDiskVersion, getPkgName, getPkgVersion, RESTART_EXIT_CODE, supervised } from "../version.js";
13
13
  import { disposeAllDevs } from "../../core/vibeables.js";
14
14
  import { identityString, readIdentity } from "../../core/identity.js";
15
+ import { currentPerson, humanActor } from "../../core/person.js";
15
16
  import { fail, reply, route } from "./router.js";
16
17
  /** A feature block with a folder (repos, vibeables, projects); saveSettings checks the root. Nested blocks are plain objects: saveSettings reads only these fields. */
17
18
  const RootBlock = z.object({ enabled: z.boolean(), root: z.string().optional() });
@@ -126,6 +127,25 @@ export const workspaceRoutes = [
126
127
  const id = await readIdentity();
127
128
  return { handle: id.handle, machine: id.machine, identity: identityString(id), previous: id.previous };
128
129
  }),
130
+ // The person asking, in this workspace's users mode (kraftwerk.yml `users:`, core/person.ts).
131
+ route({ name: "me.get", method: "GET", path: "/api/me", summary: "who you are here: users mode (local | cloud), your handle, and with cloud your account (uuid, email) and how to sign out" }, async (c) => {
132
+ const ws = await resolveWorkspace(workspaceRoot()).catch(() => null);
133
+ const mode = ws ? usersMode(ws.config) : "local";
134
+ const p = await currentPerson();
135
+ const signedIn = c.trust.kind === "local" && !!c.trust.user;
136
+ return {
137
+ mode,
138
+ handle: p.handle,
139
+ actor: humanActor(p),
140
+ ...(p.id ? { id: p.id } : {}),
141
+ ...(p.email ? { email: p.email } : {}),
142
+ /** A browser signed in with its cloud account (users: cloud); false for this machine's own shell, a device, a member. */
143
+ signedIn,
144
+ ...(signedIn && c.trust.kind === "local" ? { role: c.trust.user.role } : {}),
145
+ /** How the signed-in person got here: through the relay as a member, or on this machine. */
146
+ via: c.trust.kind === "member" ? "member" : c.trust.kind === "device" ? "device" : "local",
147
+ };
148
+ }),
129
149
  route({ name: "settings.get", method: "GET", path: "/api/settings", summary: "kraftwerk.yml, parsed, with resolved paths" }, async () => getSettings()),
130
150
  route({ name: "settings.save", method: "PUT", path: "/api/settings", summary: "write the UI-editable subset of kraftwerk.yml", errors: 400, body: SettingsFields }, async (c) => saveSettings((await c.body()))),
131
151
  route({ name: "workspaces.list", method: "GET", path: "/api/workspaces", summary: "every known workspace incl. this one, with state and counts" }, async () => placeInHub(await listWorkspacesDetailed())),
@@ -44,6 +44,9 @@ export interface CloudStatus {
44
44
  machine?: string;
45
45
  /** Email of the account that claimed the machine; null while unclaimed. */
46
46
  account?: string | null;
47
+ /** That account's uuid and handle (what the machine's own shell acts as; ~/.kraftwerk/account.json). */
48
+ accountId?: string | null;
49
+ accountHandle?: string | null;
47
50
  /** Effective seconds between heartbeats (what the cloud asked for). */
48
51
  interval?: number;
49
52
  /** Last successful register or heartbeat. */
@@ -2,7 +2,7 @@ import { promises as fs } from "node:fs";
2
2
  import { log } from "../core/log.js";
3
3
  import os from "node:os";
4
4
  import { resolveWorkspace } from "../config.js";
5
- import { claimUrlFor, machineCloud, machineGoodbye, machineHeartbeat, machineRegister, machineUnlink, MAX_REPORTED_ROUTINES, retiredCloudDir, unknownMachine, workspaceInvite, } from "../core/cloud.js";
5
+ import { claimUrlFor, machineCloud, machineGoodbye, machineHeartbeat, machineRegister, machineUnlink, MAX_REPORTED_ROUTINES, retiredCloudDir, unknownMachine, workspaceInvite, writeAccountFile, } from "../core/cloud.js";
6
6
  import { identityString, readIdentity } from "../core/identity.js";
7
7
  import { routineReport } from "../core/routines.js";
8
8
  import { machineCredentials } from "./relay.js";
@@ -47,6 +47,19 @@ async function entries(withRoots) {
47
47
  return { list, ymlUrls };
48
48
  }
49
49
  const claimed = () => typeof m.status.account === "string" && m.status.account.length > 0;
50
+ /**
51
+ * Keep ~/.kraftwerk/account.json in step with the claim: the account the
52
+ * cloud names (uuid, email, handle), or none once unclaimed. A cloud that
53
+ * names no uuid (older) leaves the file as it is.
54
+ */
55
+ async function noteAccount(r) {
56
+ if (r.account === undefined)
57
+ return;
58
+ if (!r.account)
59
+ return writeAccountFile(null);
60
+ if (r.accountId && r.accountHandle)
61
+ await writeAccountFile({ id: r.accountId, email: r.account, handle: r.accountHandle }).catch(() => { });
62
+ }
50
63
  /** The routines that ran here, per served workspace with a ws_ id (vetoed ones left out), capped. */
51
64
  async function routineEntries() {
52
65
  const out = [];
@@ -112,8 +125,9 @@ async function register() {
112
125
  m.routines = "";
113
126
  // An unclaimed register carries no roots: the list counts as reported only when that is all the cloud should know.
114
127
  m.reported = r.account ? "" : JSON.stringify(list);
128
+ await noteAccount(r);
115
129
  m.status = {
116
- ...base, state: "connected", account: r.account ?? null, interval: r.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
130
+ ...base, state: "connected", account: r.account ?? null, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null, interval: r.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
117
131
  claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(cloud.url, r.claimCode), workspaces: list.length,
118
132
  };
119
133
  // Already claimed: the roots follow at once.
@@ -144,9 +158,10 @@ async function heartbeat() {
144
158
  });
145
159
  m.reported = now;
146
160
  m.routines = ran;
161
+ await noteAccount(r);
147
162
  m.status = {
148
163
  ...m.status, state: "connected", error: undefined, interval: r.interval || m.status.interval || DEFAULT_INTERVAL, lastSeen: new Date().toISOString(),
149
- ...(r.account !== undefined ? { account: r.account } : {}),
164
+ ...(r.account !== undefined ? { account: r.account, accountId: r.accountId ?? null, accountHandle: r.accountHandle ?? null } : {}),
150
165
  ...(r.claimCode !== undefined ? { claimCode: r.claimCode, claimUrl: claimUrlFor(m.status.url, r.claimCode) } : {}),
151
166
  workspaces: list.length,
152
167
  };
@@ -259,7 +274,8 @@ export async function unlinkMachineCloud() {
259
274
  // The next heartbeat sends the list again — without roots now.
260
275
  m.reported = "";
261
276
  m.routines = "";
262
- m.status = { ...m.status, account: null, claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(m.status.url, r.claimCode) };
277
+ await writeAccountFile(null);
278
+ m.status = { ...m.status, account: null, accountId: null, accountHandle: null, claimCode: r.claimCode ?? null, claimUrl: claimUrlFor(m.status.url, r.claimCode) };
263
279
  return m.status;
264
280
  });
265
281
  }
@@ -0,0 +1,9 @@
1
+ import { type Person } from "../core/person.js";
2
+ import type { Trust } from "./trust.js";
3
+ /**
4
+ * The person behind a caller (core/person.ts): the account a browser signed
5
+ * in with (`users: cloud`), a remote member as the cloud vouched for them,
6
+ * else this machine's person — a paired device, this machine's own shell,
7
+ * any request in a `users: local` workspace.
8
+ */
9
+ export declare function personOf(trust: Trust): Promise<Person>;
@@ -0,0 +1,14 @@
1
+ import { machinePerson } from "../core/person.js";
2
+ /**
3
+ * The person behind a caller (core/person.ts): the account a browser signed
4
+ * in with (`users: cloud`), a remote member as the cloud vouched for them,
5
+ * else this machine's person — a paired device, this machine's own shell,
6
+ * any request in a `users: local` workspace.
7
+ */
8
+ export async function personOf(trust) {
9
+ if (trust.kind === "local" && trust.user)
10
+ return { handle: trust.user.user.handle, id: trust.user.user.id, email: trust.user.user.email };
11
+ if (trust.kind === "member")
12
+ return { handle: trust.member.handle, email: trust.member.email };
13
+ return machinePerson();
14
+ }
@@ -0,0 +1,35 @@
1
+ import type { Trust } from "./trust.js";
2
+ /**
3
+ * Remote boards — a workspace's boards kept in kraftwerk cloud (the cloud's
4
+ * boards.ts), multiplayer, beside the local boards (core/boards.ts, files in
5
+ * the repo, single player). They never sync with each other.
6
+ *
7
+ * The daemon is the way there from this machine's UI, CLI and agents: it
8
+ * calls the cloud with the machine's id + secret and says who it acts for —
9
+ *
10
+ * a browser signed in with its cloud account (users: cloud) → that person
11
+ * everyone else on this machine (its shell, a paired device,
12
+ * a users: local workspace) → the account that claimed the machine
13
+ * a remote member through the relay → refused: they use the cloud's own UI
14
+ *
15
+ * — and an agent or process naming itself (`actor`) is passed on as such;
16
+ * the cloud never takes a human actor from a machine. The cloud allows a
17
+ * machine to act only for its account and the people who signed in to it.
18
+ *
19
+ * Offline is offline: no cache. With the machine not connected (cloud off,
20
+ * not claimed, the workspace without a ws_ id) or the cloud not answering,
21
+ * calls fail 503 with `offline: true` and the UI marks remote boards offline.
22
+ */
23
+ export interface RemoteCall {
24
+ method: "GET" | "POST" | "PUT" | "DELETE";
25
+ /** After /api/workspaces/<ws>/, e.g. "boards/launch/tasks/3". */
26
+ path: string;
27
+ body?: unknown;
28
+ /** An agent or process naming itself (lisa/claude, process:sync); a human actor is ignored. */
29
+ actor?: string;
30
+ }
31
+ /** The ws_ id of the workspace this request is in; 409 without one (`kraftwerk doctor --fix` writes it). */
32
+ export declare function remoteWorkspaceId(): Promise<string>;
33
+ export declare function remoteCall<T>(trust: Trust, call: RemoteCall): Promise<T>;
34
+ /** The cloud's address for this workspace's page, for "open in cloud" links. */
35
+ export declare function remoteWorkspaceUrl(): Promise<string | null>;
@@ -0,0 +1,73 @@
1
+ import { resolveWorkspace } from "../config.js";
2
+ import { readAccountFile } from "../core/cloud.js";
3
+ import { workspaceRoot } from "../core/context.js";
4
+ import { ApiError } from "./api/router.js";
5
+ import { machineLink } from "./cloud.js";
6
+ import { personOf } from "./person.js";
7
+ const REMOTE_TIMEOUT_MS = 10_000;
8
+ const offline = (why) => new ApiError(503, why, { error: why, offline: true });
9
+ /** The ws_ id of the workspace this request is in; 409 without one (`kraftwerk doctor --fix` writes it). */
10
+ export async function remoteWorkspaceId() {
11
+ const ws = await resolveWorkspace(workspaceRoot());
12
+ const id = ws.config.id;
13
+ if (!id)
14
+ throw new ApiError(409, "this workspace has no id yet — `kraftwerk doctor --fix` gives it one", { error: "this workspace has no id yet — `kraftwerk doctor --fix` gives it one", offline: true });
15
+ return id;
16
+ }
17
+ export async function remoteCall(trust, call) {
18
+ if (trust.kind === "member")
19
+ throw new ApiError(403, "remote boards are in kraftwerk cloud — open them there");
20
+ const link = machineLink();
21
+ if (!link)
22
+ throw offline("kraftwerk cloud is off or not connected on this machine");
23
+ const wsId = await remoteWorkspaceId();
24
+ const [person, account] = await Promise.all([personOf(trust), readAccountFile()]);
25
+ if (!account)
26
+ throw offline("this machine is not claimed by a cloud account — `kraftwerk login`");
27
+ const as = person.id && person.id !== account.id ? person.id : undefined;
28
+ const actor = call.actor && !call.actor.trim().startsWith("human:") ? call.actor.trim() : undefined;
29
+ let r;
30
+ try {
31
+ r = await fetch(`${link.url}/api/workspaces/${encodeURIComponent(wsId)}/${call.path}`, {
32
+ method: call.method,
33
+ headers: {
34
+ "user-agent": `kraftwerk/${link.version}`,
35
+ "x-kw-machine-id": link.creds.id,
36
+ "x-kw-machine-secret": link.creds.secret,
37
+ ...(as ? { "x-kw-user": as } : {}),
38
+ ...(actor ? { "x-kw-actor": actor } : {}),
39
+ ...(call.body !== undefined ? { "content-type": "application/json" } : {}),
40
+ },
41
+ body: call.body !== undefined ? JSON.stringify(call.body) : undefined,
42
+ signal: AbortSignal.timeout(REMOTE_TIMEOUT_MS),
43
+ });
44
+ }
45
+ catch (err) {
46
+ throw offline(`kraftwerk cloud does not answer (${err.message})`);
47
+ }
48
+ const text = await r.text();
49
+ let data = {};
50
+ try {
51
+ data = text ? JSON.parse(text) : {};
52
+ }
53
+ catch {
54
+ throw offline(`kraftwerk cloud answered ${r.status}, not JSON`);
55
+ }
56
+ if (r.status >= 500)
57
+ throw offline(String(data.error ?? `kraftwerk cloud answered ${r.status}`));
58
+ if (!r.ok) {
59
+ const error = String(data.error ?? `kraftwerk cloud answered ${r.status}`);
60
+ // A person who signed in before the cloud kept sign-ins must sign in once more.
61
+ const signin = r.status === 403 && /may act only for/.test(error) && as ? { signin: true } : {};
62
+ throw new ApiError(r.status, error, { error, ...signin });
63
+ }
64
+ return data;
65
+ }
66
+ /** The cloud's address for this workspace's page, for "open in cloud" links. */
67
+ export async function remoteWorkspaceUrl() {
68
+ const link = machineLink();
69
+ if (!link)
70
+ return null;
71
+ const ws = await resolveWorkspace(workspaceRoot()).catch(() => null);
72
+ return ws?.config.id ? `${link.url}/w/${encodeURIComponent(ws.config.id)}` : null;
73
+ }
@@ -22,6 +22,8 @@ import { json } from "./api/router.js";
22
22
  import { MIME } from "./api/mime.js";
23
23
  import { getPkgVersion, RESTART_EXIT_CODE } from "./version.js";
24
24
  import { trustOf } from "./trust.js";
25
+ import { fromBrowser, handleAuth, signedIn } from "./users.js";
26
+ import { configAt, usersMode } from "../config.js";
25
27
  import { targetOf } from "./target.js";
26
28
  import { isDir, resolveWorkspace, workspaceSlug } from "../config.js";
27
29
  export { RESTART_EXIT_CODE };
@@ -238,6 +240,33 @@ function hubPage(req, res, open, trust) {
238
240
  : "<li>No workspace is open. Run <code>kraftwerk ui</code> in a workspace folder.</li>";
239
241
  res.end(`${head}<ul>${rows}</ul>`);
240
242
  }
243
+ /**
244
+ * A `users: cloud` workspace (kraftwerk.yml, server/users.ts): what signing
245
+ * in there needs, or undefined for a `users: local` one.
246
+ */
247
+ async function cloudUsers(open, prefix) {
248
+ if (!open)
249
+ return undefined;
250
+ const config = await configAt(open.root);
251
+ if (usersMode(config) !== "cloud")
252
+ return undefined;
253
+ return { workspaceId: config.id, name: open.name, prefix };
254
+ }
255
+ /**
256
+ * This machine's browser in a `users: cloud` workspace must be signed in:
257
+ * its trust names the person (`user`), or it has none yet (`signin`).
258
+ * Scripts and tools on this machine (not a browser, users.ts fromBrowser: the CLI,
259
+ * curl) are the machine's own shell and pass as before; paired devices
260
+ * and remote members have their own credentials.
261
+ */
262
+ async function withUser(req, trust, cu) {
263
+ if (!cu || trust.kind !== "local" || !fromBrowser(req))
264
+ return { trust };
265
+ const user = cu.workspaceId ? await signedIn(req, cu.workspaceId) : null;
266
+ return user ? { trust: { kind: "local", user } } : { trust, signin: true };
267
+ }
268
+ /** The `/w/<slug>` a path-form request came in under, else "". */
269
+ const prefixOf = (req, target) => (target.slug !== undefined && /^\/w\//.test(req.url ?? "") ? `/w/${target.slug}` : "");
241
270
  export async function startHub(opts) {
242
271
  const trustOpts = { trustLoopback: opts.trustLoopback !== false && !REQUIRE_PAIRING, trustNetwork: TRUST_NETWORK };
243
272
  const bySlug = new Map();
@@ -259,11 +288,31 @@ export async function startHub(opts) {
259
288
  if (target.slug !== undefined && !open)
260
289
  return json(res, { error: `no workspace "${target.slug}" here` }, 404);
261
290
  const { url } = target;
262
- const trust = await trustOf(req, url, trustOpts);
291
+ const prefix = prefixOf(req, target);
292
+ const cu = await cloudUsers(open, prefix);
293
+ const gate = await withUser(req, await trustOf(req, url, trustOpts), cu);
294
+ const { trust } = gate;
263
295
  // A member session (members.ts) reaches its one workspace and nothing else: not another, not the hub page.
264
296
  if (trust.kind === "member" && open?.slug !== trust.slug) {
265
297
  return json(res, { error: `a member session reaches only its workspace — /w/${trust.slug}/…` }, 403);
266
298
  }
299
+ // Signing in (users: cloud): the way there and back is open; everything else waits for it.
300
+ if (cu && url.pathname.startsWith("/auth/") && trust.kind === "local") {
301
+ if (req.method === "POST" && !sameOrigin(req))
302
+ return json(res, { error: "cross-origin request refused" }, 403);
303
+ if (await handleAuth(req, res, url, cu))
304
+ return;
305
+ }
306
+ if (gate.signin) {
307
+ const signin = `${prefix}/auth/signin`;
308
+ if (url.pathname.startsWith("/api/"))
309
+ return json(res, { error: "sign in first", signin }, 401);
310
+ // The UI's own files (hashed, no data) load on the sign-in redirect's way back; pages and app files wait.
311
+ if (!url.pathname.startsWith("/assets/") && !/^\/[^/]+\.(ico|png|svg|webmanifest)$/.test(url.pathname)) {
312
+ res.writeHead(302, { location: `${signin}?next=${encodeURIComponent(`${prefix}${url.pathname}${url.search}`)}`, "cache-control": "no-store" });
313
+ return void res.end();
314
+ }
315
+ }
267
316
  const run = (fn) => runInHub(hub, () => (open ? open.ws.run(fn) : fn()));
268
317
  if (url.pathname.startsWith("/api/")) {
269
318
  const method = req.method ?? "GET";
@@ -301,8 +350,10 @@ export async function startHub(opts) {
301
350
  if (target.slug !== undefined && !open)
302
351
  return void socket.end("HTTP/1.1 404 Not Found\r\nconnection: close\r\n\r\n");
303
352
  const { url } = target;
304
- const trust = await trustOf(req, url, trustOpts, true);
305
- if (trust.kind === "none")
353
+ const cu = await cloudUsers(open, prefixOf(req, target));
354
+ const gate = await withUser(req, await trustOf(req, url, trustOpts, true), cu);
355
+ const { trust } = gate;
356
+ if (trust.kind === "none" || gate.signin)
306
357
  return void socket.end("HTTP/1.1 401 Unauthorized\r\nconnection: close\r\n\r\n");
307
358
  // A socket may name any workspace per message; a member session's scope is per request, so it gets none.
308
359
  if (trust.kind === "member")
@@ -327,7 +378,12 @@ export async function startHub(opts) {
327
378
  const entry = { slug: own, close: () => conn.close(4404, "workspace closed") };
328
379
  sockets.add(entry);
329
380
  conn.onClose(() => sockets.delete(entry));
330
- runInHub(hub, () => serveSocket(conn, resolve, version, trust, () => trustOf(req, url, trustOpts, true), hub));
381
+ // Re-checked per message: a person signed out (or removed in the cloud) loses the socket's rights with the next one.
382
+ const recheck = async () => {
383
+ const g = await withUser(req, await trustOf(req, url, trustOpts, true), cu);
384
+ return g.signin ? { kind: "none" } : g.trust;
385
+ };
386
+ runInHub(hub, () => serveSocket(conn, resolve, version, trust, recheck, hub));
331
387
  })().catch(() => socket.destroy());
332
388
  };
333
389
  const server = http.createServer(handler(() => fallback));
@@ -1,6 +1,7 @@
1
1
  import type http from "node:http";
2
2
  import { type Device } from "../core/devices.js";
3
3
  import { type Member } from "./members.js";
4
+ import type { SignedIn } from "./users.js";
4
5
  /**
5
6
  * Who is asking. Every request and socket gets one of:
6
7
  *
@@ -28,8 +29,11 @@ import { type Member } from "./members.js";
28
29
  * - `none`: anyone else. Gets the web UI's shell (to show the pairing
29
30
  * screen), the protocol description and the pairing route — nothing else.
30
31
  */
31
- export type Trust = {
32
+ export type Trust =
33
+ /** `user`: the person signed in with their cloud account (kraftwerk.yml `users: cloud`, server/users.ts). */
34
+ {
32
35
  kind: "local";
36
+ user?: SignedIn;
33
37
  } | {
34
38
  kind: "device";
35
39
  device: Device;