@netnodeag/kraftwerk 0.96.0 → 0.97.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 (64) hide show
  1. package/README.md +30 -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 +1 -0
  10. package/dist/client/routes.js +1 -0
  11. package/dist/config.d.ts +34 -0
  12. package/dist/config.js +28 -1
  13. package/dist/core/boards.d.ts +1 -1
  14. package/dist/core/boards.js +10 -6
  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 +21 -2
  31. package/dist/server/api/presentations.js +2 -2
  32. package/dist/server/api/projects.d.ts +1 -1
  33. package/dist/server/api/projects.js +1 -1
  34. package/dist/server/api/router.js +5 -2
  35. package/dist/server/api/workspace.d.ts +14 -1
  36. package/dist/server/api/workspace.js +21 -1
  37. package/dist/server/cloud.d.ts +3 -0
  38. package/dist/server/cloud.js +20 -4
  39. package/dist/server/person.d.ts +9 -0
  40. package/dist/server/person.js +14 -0
  41. package/dist/server/server.js +60 -4
  42. package/dist/server/trust.d.ts +5 -1
  43. package/dist/server/users.d.ts +55 -0
  44. package/dist/server/users.js +258 -0
  45. package/package.json +1 -1
  46. package/schema/kraftwerk.schema.json +8 -0
  47. package/web/dist/assets/{dist-BiyjchCb.js → dist-BD4ooe-Y.js} +1 -1
  48. package/web/dist/assets/{dist-qkoQQWNK.js → dist-BduOHHOY.js} +1 -1
  49. package/web/dist/assets/{dist-DkDmdJNX.js → dist-BoajTxbz.js} +1 -1
  50. package/web/dist/assets/{dist-wkkpVezb.js → dist-DGLb7wE6.js} +1 -1
  51. package/web/dist/assets/{dist-14HFV7uD.js → dist-DJACzcZZ.js} +1 -1
  52. package/web/dist/assets/{dist-DO04nOS3.js → dist-DY6QplYX.js} +1 -1
  53. package/web/dist/assets/{dist-DbBrc07-.js → dist-D_uWSMLk.js} +1 -1
  54. package/web/dist/assets/{dist-DKQkCBo9.js → dist-P7JCq9c3.js} +1 -1
  55. package/web/dist/assets/dist-ajNgHt2Q.js +1 -0
  56. package/web/dist/assets/{dist-BYgXVWBg.js → dist-lcPkaK4d.js} +1 -1
  57. package/web/dist/assets/{dist-DOW1X_nG.js → dist-oRcLByHn.js} +1 -1
  58. package/web/dist/assets/{editor-DvkpSp7h.js → editor-hTceN7Iz.js} +3 -3
  59. package/web/dist/assets/index-BGgQaaA9.css +2 -0
  60. package/web/dist/assets/index-BOkjCxut.js +488 -0
  61. package/web/dist/index.html +2 -2
  62. package/web/dist/assets/dist-CCZcAg77.js +0 -1
  63. package/web/dist/assets/index-B5PLhJ-C.js +0 -488
  64. package/web/dist/assets/index-CWopPK15.css +0 -2
@@ -4,13 +4,13 @@ import { resolveWorkspace } from "../config.js";
4
4
  import { getConcept, initBundle, knowledgeRoot, listBundles, listConcepts, safeBundleName, verifyConcept, writeConcept, } from "../okf.js";
5
5
  import { workspaceRoot } from "./context.js";
6
6
  import { moveToTrash } from "./trash.js";
7
+ import { actorFor } from "./person.js";
7
8
  /**
8
9
  * Knowledge for the inspector: a thin API layer over the OKF
9
- * core (src/okf.ts). Writes from the UI are stamped as `human:user` — the
10
- * browser user is the human in the loop; agents write through the CLI (or
11
- * chat) with their own actor.
10
+ * core (src/okf.ts). Writes from the UI are stamped as the person asking
11
+ * (`human:<handle>`, core/person.ts) — the browser user is the human in the
12
+ * loop; agents write through the CLI (or chat) with their own actor.
12
13
  */
13
- export const UI_ACTOR = "human:user";
14
14
  async function root() {
15
15
  const project = await resolveWorkspace(workspaceRoot());
16
16
  return knowledgeRoot(project.root, project.config.knowledge);
@@ -41,8 +41,8 @@ export async function conceptDetail(bundle, id) {
41
41
  return getConcept(await root(), bundle, id);
42
42
  }
43
43
  export async function putConcept(bundle, id, content) {
44
- return (await writeConcept(await root(), bundle, id, content, UI_ACTOR)).concept;
44
+ return (await writeConcept(await root(), bundle, id, content, await actorFor())).concept;
45
45
  }
46
46
  export async function verifyFromUi(bundle, id) {
47
- return verifyConcept(await root(), bundle, id, UI_ACTOR);
47
+ return verifyConcept(await root(), bundle, id, await actorFor());
48
48
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Who a human change is signed with — the person behind a request, else
3
+ * the machine's own.
4
+ *
5
+ * A person is a handle, and with `users: cloud` (kraftwerk.yml, see
6
+ * UsersConfig) also the cloud account's uuid and email: the same person on
7
+ * every machine and clone. Logs and provenance write `human:<handle>`
8
+ * (readable; the cloud keeps handles unique); chats keep the whole person.
9
+ *
10
+ * The server runs every API call as its caller (`runAs`, router.ts): a
11
+ * signed-in browser, a remote member, this machine. Outside a request —
12
+ * the CLI, a routine — it is the machine's person:
13
+ *
14
+ * users: local the identity handle (~/.kraftwerk/identity.json)
15
+ * users: cloud the account that claimed the machine (~/.kraftwerk/account.json),
16
+ * the identity handle while there is none
17
+ *
18
+ * A `human:` actor is never taken from what a caller of the API says:
19
+ * whoever asks is who it is (`actorFor`). The machine's own shell (the CLI,
20
+ * outside any request) may still name one — it can edit the files anyway.
21
+ * Other actors — `lisa/claude`, `process:sync` — are agents and processes
22
+ * naming themselves, and stand as given.
23
+ */
24
+ export interface Person {
25
+ handle: string;
26
+ /** The cloud account's uuid (users: cloud, or a remote member's when the cloud says it). */
27
+ id?: string;
28
+ email?: string;
29
+ }
30
+ /** Run `fn` as the person `who` resolves to (resolved once, when first asked). */
31
+ export declare function runAs<T>(who: () => Promise<Person>, fn: () => T): T;
32
+ /** This machine's person: the claiming account in a `users: cloud` workspace, else the identity handle. */
33
+ export declare function machinePerson(): Promise<Person>;
34
+ /** The person the current request runs as, else this machine's. */
35
+ export declare function currentPerson(): Promise<Person>;
36
+ export declare const humanActor: (p: Pick<Person, "handle">) => string;
37
+ /**
38
+ * The actor a change is stamped with: an agent's or a process's own name as
39
+ * given, else the person asking — in a request a given `human:…` too.
40
+ */
41
+ export declare function actorFor(given?: string): Promise<string>;
@@ -0,0 +1,47 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { resolveWorkspace, usersMode } from "../config.js";
3
+ import { readAccountFile } from "./cloud.js";
4
+ import { workspaceRoot } from "./context.js";
5
+ import { readIdentity } from "./identity.js";
6
+ const storage = new AsyncLocalStorage();
7
+ /** Run `fn` as the person `who` resolves to (resolved once, when first asked). */
8
+ export function runAs(who, fn) {
9
+ let memo;
10
+ return storage.run(() => (memo ??= who()), fn);
11
+ }
12
+ /** This machine's person: the claiming account in a `users: cloud` workspace, else the identity handle. */
13
+ export async function machinePerson() {
14
+ // The CLI runs outside any served workspace: the one around its cwd.
15
+ let root;
16
+ try {
17
+ root = workspaceRoot();
18
+ }
19
+ catch {
20
+ root = process.cwd();
21
+ }
22
+ const cloud = await resolveWorkspace(root)
23
+ .then((ws) => usersMode(ws.config) === "cloud")
24
+ .catch(() => false);
25
+ if (cloud) {
26
+ const account = await readAccountFile();
27
+ if (account)
28
+ return { handle: account.handle, id: account.id, email: account.email };
29
+ }
30
+ return { handle: (await readIdentity()).handle };
31
+ }
32
+ /** The person the current request runs as, else this machine's. */
33
+ export async function currentPerson() {
34
+ const who = storage.getStore();
35
+ return who ? who() : machinePerson();
36
+ }
37
+ export const humanActor = (p) => `human:${p.handle}`;
38
+ /**
39
+ * The actor a change is stamped with: an agent's or a process's own name as
40
+ * given, else the person asking — in a request a given `human:…` too.
41
+ */
42
+ export async function actorFor(given) {
43
+ const g = (given ?? "").trim();
44
+ if (g && (!g.startsWith("human:") || !storage.getStore()))
45
+ return g;
46
+ return humanActor(await currentPerson());
47
+ }
@@ -168,7 +168,7 @@ export declare function linkProject(slug: string, kind: string, target: string,
168
168
  * knowledge bundle's log). The actor is stamped so a line written by an
169
169
  * agent reads as such next to a human's.
170
170
  */
171
- export declare function appendProjectLog(slug: string, entry: string, actor: string): Promise<string>;
171
+ export declare function appendProjectLog(slug: string, entry: string, actor?: string): Promise<string>;
172
172
  /** Move the folder to the trash. */
173
173
  export declare function deleteProject(slug: string): Promise<void>;
174
174
  /**
@@ -13,6 +13,7 @@ import { listRepos } from "./repos.js";
13
13
  import { SLUG_RE, slugify } from "./slug.js";
14
14
  import { moveToTrash } from "./trash.js";
15
15
  import { filesContext } from "./files.js";
16
+ import { actorFor } from "./person.js";
16
17
  /**
17
18
  * Projects: a goal with everything the agents need to reach it gathered in
18
19
  * one folder — the brief, the systems of record where the truth is managed
@@ -302,7 +303,7 @@ export async function createProject(input) {
302
303
  for (const [name, content] of Object.entries(projectStarter(def))) {
303
304
  await fs.writeFile(path.join(dir, name), content);
304
305
  }
305
- await appendProjectLog(slug, `**Created**: project "${title}".`, "human:user");
306
+ await appendProjectLog(slug, `**Created**: project "${title}".`);
306
307
  return (await getProject(slug));
307
308
  }
308
309
  /** Merge the given fields into project.yml (and brief/state when given); lists replace wholesale. */
@@ -359,7 +360,7 @@ export async function appendProjectLog(slug, entry, actor) {
359
360
  const text = entry.trim().replace(/\s*\n\s*/g, " ");
360
361
  if (!text)
361
362
  throw new Error("entry is required");
362
- const who = actor.trim() || "human:user";
363
+ const who = await actorFor(actor);
363
364
  const file = path.join(dir, "log.md");
364
365
  const today = new Date().toISOString().slice(0, 10);
365
366
  let raw = await fs.readFile(file, "utf8").catch(() => null);
@@ -1,7 +1,7 @@
1
1
  import * as z from "zod";
2
2
  import { agentsRoot, deleteAgent, getAgent, listAgents, safeAgentSlug, saveAgent, setAgentArchived } from "../../core/agents.js";
3
3
  import { appendJournal, readJournal } from "../../core/journal.js";
4
- import { UI_ACTOR } from "../../core/knowledge.js";
4
+ import { actorFor } from "../../core/person.js";
5
5
  import { adoptRoutine, deleteRoutine, listRoutines, routineStatuses, runRoutineNow, saveRoutine } from "../../core/routines.js";
6
6
  import { deleteAgentSkill, listAgentSkills, readSkill, saveAgentSkill } from "../../core/skills.js";
7
7
  import { fail, route } from "./router.js";
@@ -90,7 +90,7 @@ export const agentRoutes = [
90
90
  body: z.object({ entry: z.string().default(""), kind: z.string().optional() }),
91
91
  }, async (c) => {
92
92
  const { entry, kind } = await c.body();
93
- return { journal: await appendJournal(c.params.slug, entry, { kind, actor: UI_ACTOR }) };
93
+ return { journal: await appendJournal(c.params.slug, entry, { kind, actor: await actorFor() }) };
94
94
  }),
95
95
  route({ name: "agents.routines", method: "GET", path: "/api/agents/:slug/routines", summary: "the agent's routines with run state", errors: 400 }, async (c) => ({
96
96
  routines: await routineStatuses(own(c.params.slug)),
@@ -27,7 +27,7 @@ const TaskFields = z.object({
27
27
  tags: z.array(z.string()).optional(),
28
28
  refs: z.array(z.string()).optional(),
29
29
  notes: z.string().optional(),
30
- /** Who writes (human:user by default) and a line for the log. */
30
+ /** Who writes (an agent or process naming itself; a person is whoever asks) and a line for the log. */
31
31
  actor: z.string().optional(),
32
32
  message: z.string().optional(),
33
33
  });
@@ -2,9 +2,10 @@ import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import * as z from "zod";
4
4
  import { getAgent } from "../../core/agents.js";
5
- import { answerElicitation, cancelChat, createChat, deleteChat, forkChat, getChat, listAgentSessionsFor, startOptionsFor, listChats, localPerson, postMessage, renameChat, resetSession, resolvePermission, setChatConfig, setChatProject, setChatVibeable, steerChat, stopChatTask, subscribeChat, } from "../../core/chat/sessions.js";
5
+ import { answerElicitation, cancelChat, createChat, deleteChat, forkChat, getChat, listAgentSessionsFor, startOptionsFor, listChats, postMessage, renameChat, resetSession, resolvePermission, setChatConfig, setChatProject, setChatVibeable, steerChat, stopChatTask, subscribeChat, } from "../../core/chat/sessions.js";
6
6
  import { attachmentPath, readMeta, saveAttachment } from "../../core/chat/store.js";
7
7
  import { remoteCaller } from "../trust.js";
8
+ import { personOf } from "../person.js";
8
9
  import { findTask } from "../../core/boards.js";
9
10
  import { getProject } from "../../core/projects.js";
10
11
  import { MIME } from "./mime.js";
@@ -82,8 +83,11 @@ async function projectSlug(slug) {
82
83
  fail(404, "project not found");
83
84
  return found.slug;
84
85
  }
85
- /** Who a chat or message is signed with: a member session's member, else this machine's person. */
86
- const personOf = async (trust) => trust.kind === "member" ? { handle: trust.member.handle, email: trust.member.email } : localPerson();
86
+ /** Who a chat or message is signed with: the person asking (server/person.ts). */
87
+ const chatPersonOf = async (trust) => {
88
+ const p = await personOf(trust);
89
+ return { handle: p.handle, ...(p.id ? { id: p.id } : {}), ...(p.email ? { email: p.email } : {}) };
90
+ };
87
91
  /**
88
92
  * A private routine's run (meta.private) is not there for a remote caller
89
93
  * (trust.ts remoteCaller): a 404, as if it did not exist. This machine and
@@ -129,7 +133,7 @@ export const chatRoutes = [
129
133
  return await createChat({
130
134
  agent: agent,
131
135
  scope,
132
- author: await personOf(c.trust),
136
+ author: await chatPersonOf(c.trust),
133
137
  ...(project ? { project } : {}),
134
138
  ...(task ? { task } : {}),
135
139
  ...(body.resume ? { resume: body.resume } : {}),
@@ -203,7 +207,7 @@ export const chatRoutes = [
203
207
  const { slug } = await c.body();
204
208
  return metaOf(await setChatVibeable(c.params.id, slug || null));
205
209
  }),
206
- route({ name: "chats.fork", method: "POST", path: "/api/chats/:id/fork", summary: "a new chat continuing a copy of this one's session", errors: 400 }, async (c) => metaOf(await forkChat(c.params.id, await personOf(c.trust)))),
210
+ route({ name: "chats.fork", method: "POST", path: "/api/chats/:id/fork", summary: "a new chat continuing a copy of this one's session", errors: 400 }, async (c) => metaOf(await forkChat(c.params.id, await chatPersonOf(c.trust)))),
207
211
  route({ name: "chats.resetSession", method: "POST", path: "/api/chats/:id/reset-session", summary: "forget the agent's session; the next message starts fresh", errors: 400 }, async (c) => metaOf(await resetSession(c.params.id))),
208
212
  // The body is the file itself; x-file-name names it, content-type types it.
209
213
  route({ name: "chats.attach", method: "POST", path: "/api/chats/:id/attachments", summary: "upload an attachment for the next message", errors: 400, upload: true }, async (c) => {
@@ -235,8 +239,8 @@ export const chatRoutes = [
235
239
  res.end(data);
236
240
  }),
237
241
  // Channels: `from` is the poster's display name, which signs the message.
238
- act("chats.message", "/api/chats/:id/message", "send a message {text, attachments?, from?}", Said.extend({ from: z.string().optional() }), async (c, body) => postMessage(c.params.id, textOf(body), { from: body.from, attachments: body.attachments, by: await personOf(c.trust) })),
239
- act("chats.steer", "/api/chats/:id/steer", "add to the running turn {text, attachments?}", Said, async (c, body) => steerChat(c.params.id, textOf(body), body.attachments, await personOf(c.trust))),
242
+ act("chats.message", "/api/chats/:id/message", "send a message {text, attachments?, from?}", Said.extend({ from: z.string().optional() }), async (c, body) => postMessage(c.params.id, textOf(body), { from: body.from, attachments: body.attachments, by: await chatPersonOf(c.trust) })),
243
+ act("chats.steer", "/api/chats/:id/steer", "add to the running turn {text, attachments?}", Said, async (c, body) => steerChat(c.params.id, textOf(body), body.attachments, await chatPersonOf(c.trust))),
240
244
  act("chats.permission", "/api/chats/:id/permission", "answer a permission request {requestId, optionId | null}", z.object({ requestId: z.string().default(""), optionId: z.string().nullable().default(null) }), (c, body) => resolvePermission(c.params.id, body.requestId, body.optionId)),
241
245
  // Channels: `agent` stops one member; without it every agent in the chat.
242
246
  act("chats.cancel", "/api/chats/:id/cancel", "stop the running turn {agent?}", z.object({ agent: z.string().optional() }), (c, body) => cancelChat(c.params.id, body.agent || undefined)),
@@ -30,6 +30,8 @@ export declare const cloudRoutes: (import("./router.js").Route<"cloud.invite", i
30
30
  id?: string;
31
31
  machine?: string;
32
32
  account?: string | null;
33
+ accountId?: string | null;
34
+ accountHandle?: string | null;
33
35
  interval?: number;
34
36
  lastSeen?: string;
35
37
  claimCode?: string | null;
@@ -48,6 +50,8 @@ export declare const cloudRoutes: (import("./router.js").Route<"cloud.invite", i
48
50
  id?: string;
49
51
  machine?: string;
50
52
  account?: string | null;
53
+ accountId?: string | null;
54
+ accountHandle?: string | null;
51
55
  interval?: number;
52
56
  lastSeen?: string;
53
57
  claimCode?: string | null;
@@ -63,6 +67,8 @@ export declare const cloudRoutes: (import("./router.js").Route<"cloud.invite", i
63
67
  id?: string;
64
68
  machine?: string;
65
69
  account?: string | null;
70
+ accountId?: string | null;
71
+ accountHandle?: string | null;
66
72
  interval?: number;
67
73
  lastSeen?: string;
68
74
  claimCode?: string | null;
@@ -78,6 +84,8 @@ export declare const cloudRoutes: (import("./router.js").Route<"cloud.invite", i
78
84
  id?: string;
79
85
  machine?: string;
80
86
  account?: string | null;
87
+ accountId?: string | null;
88
+ accountHandle?: string | null;
81
89
  interval?: number;
82
90
  lastSeen?: string;
83
91
  claimCode?: string | null;
@@ -350,6 +350,8 @@ export declare const routes: (Route<"agents.addJournal", {
350
350
  id?: string;
351
351
  machine?: string;
352
352
  account?: string | null;
353
+ accountId?: string | null;
354
+ accountHandle?: string | null;
353
355
  interval?: number;
354
356
  lastSeen?: string;
355
357
  claimCode?: string | null;
@@ -368,6 +370,8 @@ export declare const routes: (Route<"agents.addJournal", {
368
370
  id?: string;
369
371
  machine?: string;
370
372
  account?: string | null;
373
+ accountId?: string | null;
374
+ accountHandle?: string | null;
371
375
  interval?: number;
372
376
  lastSeen?: string;
373
377
  claimCode?: string | null;
@@ -383,6 +387,8 @@ export declare const routes: (Route<"agents.addJournal", {
383
387
  id?: string;
384
388
  machine?: string;
385
389
  account?: string | null;
390
+ accountId?: string | null;
391
+ accountHandle?: string | null;
386
392
  interval?: number;
387
393
  lastSeen?: string;
388
394
  claimCode?: string | null;
@@ -398,6 +404,8 @@ export declare const routes: (Route<"agents.addJournal", {
398
404
  id?: string;
399
405
  machine?: string;
400
406
  account?: string | null;
407
+ accountId?: string | null;
408
+ accountHandle?: string | null;
401
409
  interval?: number;
402
410
  lastSeen?: string;
403
411
  claimCode?: string | null;
@@ -561,7 +569,16 @@ export declare const routes: (Route<"agents.addJournal", {
561
569
  content: z.ZodDefault<z.ZodString>;
562
570
  }, z.core.$strip>> | Route<"knowledge.verify", import("../../okf.js").ConceptDetail, "/api/knowledge/:bundle/verify", z.ZodObject<{
563
571
  id: z.ZodDefault<z.ZodString>;
564
- }, z.core.$strip>> | Route<"meta.get", {
572
+ }, z.core.$strip>> | Route<"me.get", {
573
+ mode: import("../../config.js").UsersMode;
574
+ handle: string;
575
+ actor: string;
576
+ id?: string | undefined;
577
+ email?: string | undefined;
578
+ signedIn: boolean;
579
+ role?: "member" | "owner" | undefined;
580
+ via: "device" | "local" | "member";
581
+ }, "/api/me", undefined> | Route<"meta.get", {
565
582
  workspaceName: string;
566
583
  workspaceSlug: string;
567
584
  workspaceIcon: string;
@@ -598,6 +615,8 @@ export declare const routes: (Route<"agents.addJournal", {
598
615
  id?: string;
599
616
  machine?: string;
600
617
  account?: string | null;
618
+ accountId?: string | null;
619
+ accountHandle?: string | null;
601
620
  interval?: number;
602
621
  lastSeen?: string;
603
622
  claimCode?: string | null;
@@ -696,7 +715,7 @@ export declare const routes: (Route<"agents.addJournal", {
696
715
  log: string;
697
716
  }, "/api/projects/:slug/log", z.ZodObject<{
698
717
  entry: z.ZodString;
699
- actor: z.ZodDefault<z.ZodString>;
718
+ actor: z.ZodOptional<z.ZodString>;
700
719
  }, z.core.$strip>> | Route<"projects.save", import("../../core/projects.js").ProjectDetail, "/api/projects/:slug", z.ZodObject<{
701
720
  title: z.ZodOptional<z.ZodString>;
702
721
  status: z.ZodOptional<z.ZodString>;
@@ -3,7 +3,7 @@ import { stat } from "node:fs/promises";
3
3
  import * as z from "zod";
4
4
  import { createDeck, deckSlidePng, deleteDeck, exportBytes, getDeck, listAllDecks, listDecks, listTemplates, openPresentations, saveAsset, addComment, updateComment, deleteComment, StaleDeckError, existingDeckDir, deckVersions, deckVersion, deckFile, templateFile, saveDeck, } from "../../core/presentations/index.js";
5
5
  import { ApiError, fail, reply, route, statusByMessage } from "./router.js";
6
- import { localPerson } from "../../core/chat/sessions.js";
6
+ import { personOf } from "../person.js";
7
7
  import { tasksReferencing } from "../../core/boards.js";
8
8
  import { leavePresence, touchPresence } from "../../core/presentations/presence.js";
9
9
  /**
@@ -45,7 +45,7 @@ const refOf = (c) => {
45
45
  return { ...(project ? { project } : {}), name: c.params.name };
46
46
  };
47
47
  /** Who writes a comment: a member by their handle, else this machine's person. */
48
- const authorOf = async (trust) => (trust.kind === "member" ? trust.member.handle : (await localPerson()).handle);
48
+ const authorOf = async (trust) => (await personOf(trust)).handle;
49
49
  const requireOn = async () => {
50
50
  if ((await openPresentations()).off)
51
51
  fail(409, "presentations are off");
@@ -16,7 +16,7 @@ export declare const projectRoutes: (import("./router.js").Route<"projects.creat
16
16
  log: string;
17
17
  }, "/api/projects/:slug/log", z.ZodObject<{
18
18
  entry: z.ZodString;
19
- actor: z.ZodDefault<z.ZodString>;
19
+ actor: z.ZodOptional<z.ZodString>;
20
20
  }, z.core.$strip>> | import("./router.js").Route<"projects.save", import("../../core/projects.js").ProjectDetail, "/api/projects/:slug", z.ZodObject<{
21
21
  title: z.ZodOptional<z.ZodString>;
22
22
  status: z.ZodOptional<z.ZodString>;
@@ -58,7 +58,7 @@ export const projectRoutes = [
58
58
  path: "/api/projects/:slug/log",
59
59
  summary: "append a stamped line {entry, actor?} to log.md",
60
60
  errors: projectErrors,
61
- body: z.object({ entry: z.string(), actor: z.string().default("human:user") }),
61
+ body: z.object({ entry: z.string(), actor: z.string().optional() }),
62
62
  }, async (c) => {
63
63
  const { entry, actor } = await c.body();
64
64
  return { ok: true, log: await appendProjectLog(c.params.slug, entry, actor) };
@@ -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
+ }