paseo-office 0.2.0 → 0.2.2

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 (143) hide show
  1. package/OVERVIEW.md +27 -0
  2. package/README.md +65 -134
  3. package/client/action-button.tsx +4 -1
  4. package/client/activity-panel.tsx +6 -4
  5. package/client/agent-appearance.tsx +257 -0
  6. package/client/agent-card.tsx +2 -1
  7. package/client/agent-picker-text.ts +23 -4
  8. package/client/agent-picker.tsx +5 -8
  9. package/client/board-sheet.tsx +48 -16
  10. package/client/board-text.ts +12 -2
  11. package/client/brand.ts +1 -0
  12. package/client/chat-chrome.tsx +318 -0
  13. package/client/chat-compose-tools.tsx +314 -0
  14. package/client/chat-dictation.tsx +133 -0
  15. package/client/chat-more.tsx +119 -0
  16. package/client/chat-panel.tsx +401 -146
  17. package/client/chat-quick.tsx +198 -0
  18. package/client/chat-text.ts +25 -6
  19. package/client/column-sheet.tsx +93 -23
  20. package/client/conversation-model.ts +19 -5
  21. package/client/duty-sheet.tsx +321 -0
  22. package/client/duty-text.ts +20 -0
  23. package/client/fullscreen-header.tsx +28 -13
  24. package/client/fullscreen-theme.ts +38 -0
  25. package/client/host-details.tsx +269 -0
  26. package/client/host-styles.ts +129 -0
  27. package/client/host-switches.tsx +212 -83
  28. package/client/incidents-card.tsx +2 -1
  29. package/client/janitor-card.tsx +1 -1
  30. package/client/library-card.tsx +2 -1
  31. package/client/list-text.ts +8 -6
  32. package/client/lobby-board.tsx +73 -53
  33. package/client/machine-card.tsx +225 -85
  34. package/client/messenger-styles.ts +216 -0
  35. package/client/new-agent-form.tsx +153 -61
  36. package/client/new-agent-model.ts +2 -0
  37. package/client/notes-card.tsx +111 -83
  38. package/client/notes-days.tsx +1 -1
  39. package/client/office-brand-context.ts +44 -0
  40. package/client/office-column.tsx +2 -1
  41. package/client/office-keyboard.ts +79 -0
  42. package/client/office-link.ts +7 -1
  43. package/client/office-mark.tsx +29 -0
  44. package/client/office-modal.tsx +440 -0
  45. package/client/office-settings.tsx +75 -30
  46. package/client/office-state.ts +12 -2
  47. package/client/office-surface.tsx +591 -81
  48. package/client/pixel/actors.ts +2 -1
  49. package/client/pixel/art.ts +33 -19
  50. package/client/pixel/pixel-office.tsx +2 -2
  51. package/client/prompt-coach.tsx +152 -0
  52. package/client/qa-card.tsx +2 -1
  53. package/client/review-card.tsx +2 -1
  54. package/client/room-board.tsx +26 -2
  55. package/client/scene-picker.tsx +158 -0
  56. package/client/scene-previews.ts +10 -0
  57. package/client/session-pane.tsx +25 -5
  58. package/client/session-panel-detail.tsx +238 -0
  59. package/client/session-panel.tsx +222 -137
  60. package/client/session-styles.ts +224 -1
  61. package/client/session-transcript.tsx +243 -0
  62. package/client/sessions-panel.tsx +181 -22
  63. package/client/sessions-text.ts +18 -0
  64. package/client/settings-sections.tsx +126 -0
  65. package/client/sidebar-launcher.ts +29 -0
  66. package/client/ssh-hosts.tsx +331 -0
  67. package/client/ssh-metrics.ts +76 -0
  68. package/client/standup-card.tsx +2 -1
  69. package/client/structure-view.tsx +20 -3
  70. package/client/styles.ts +170 -62
  71. package/client/team-chat-preview.tsx +96 -0
  72. package/client/tracker-connections.tsx +252 -0
  73. package/client/transcript-styles.ts +90 -0
  74. package/client/use-device-switch.ts +21 -12
  75. package/client/use-duty-actions.ts +43 -0
  76. package/client/use-group-photo.ts +48 -0
  77. package/client/use-new-agent.ts +4 -0
  78. package/client/use-street.ts +8 -0
  79. package/client/workspace-office-tools.tsx +102 -0
  80. package/client/workspace-overlay-route.web.ts +47 -0
  81. package/client/workspace-overlay.tsx +195 -0
  82. package/client/world/adapter.ts +37 -2
  83. package/client/world/escape.ts +58 -0
  84. package/client/world/use-world-feed.ts +6 -2
  85. package/client/world/workspace-dock.ts +6 -0
  86. package/client/world/world-api.ts +45 -4
  87. package/client/world/world-bridge-page.ts +14 -3
  88. package/client/world/world-bridge.ts +50 -5
  89. package/client/world/world-frame.web.ts +8 -0
  90. package/client/world/world-view-native.tsx +31 -10
  91. package/client/world/world-view-shared.ts +36 -7
  92. package/client/world/world-view.tsx +93 -21
  93. package/docs/office.md +165 -64
  94. package/index.client.tsx +13 -6
  95. package/index.server.ts +232 -16
  96. package/package.json +2 -1
  97. package/server/activity.ts +42 -19
  98. package/server/agent-tools.ts +11 -5
  99. package/server/board-service.ts +381 -10
  100. package/server/brand-logo.ts +34 -0
  101. package/server/chat-group.ts +83 -0
  102. package/server/chat-service.ts +406 -62
  103. package/server/chat-store.ts +1 -4
  104. package/server/directory.ts +22 -7
  105. package/server/duty-service.ts +230 -0
  106. package/server/group-photo.ts +39 -0
  107. package/server/home-departure.ts +47 -0
  108. package/server/hub.ts +43 -1
  109. package/server/incidents-jira.ts +19 -7
  110. package/server/incidents-schedule.ts +10 -10
  111. package/server/incidents-sentry.ts +34 -8
  112. package/server/live-ports.ts +114 -18
  113. package/server/lobby-pickup.ts +170 -0
  114. package/server/machine/details.ts +91 -0
  115. package/server/mention-queue.ts +14 -0
  116. package/server/office.ts +110 -6
  117. package/server/paths.ts +14 -0
  118. package/server/ssh/LICENSE.paseo +211 -0
  119. package/server/ssh/client.ts +401 -0
  120. package/server/ssh/discovery.ts +230 -0
  121. package/server/ssh/installed.ts +104 -0
  122. package/server/ssh/monitor.ts +104 -0
  123. package/server/ssh/pid-files.ts +194 -0
  124. package/server/ssh/read.ts +136 -0
  125. package/server/subagent-names.ts +4 -0
  126. package/server/tracker-credentials.ts +141 -0
  127. package/server/words.generated.ts +1 -1
  128. package/server/world.generated.ts +1 -1
  129. package/shared/appearance.ts +43 -0
  130. package/shared/branding.ts +53 -0
  131. package/shared/chat-words.ts +2 -2
  132. package/shared/contracts.ts +199 -5
  133. package/shared/duties.ts +100 -0
  134. package/shared/host-details.ts +25 -0
  135. package/shared/lobby-assignment.ts +34 -0
  136. package/shared/model.ts +9 -1
  137. package/shared/names.ts +2 -0
  138. package/shared/settings.ts +14 -3
  139. package/shared/ssh.ts +34 -0
  140. package/shared/upstream/README.md +1 -3
  141. package/shared/upstream/chat-engine.d.ts +4 -0
  142. package/shared/upstream/prompt-coach.d.ts +6 -0
  143. package/shared/upstream/prompt-coach.js +178 -0
@@ -6,6 +6,7 @@ import {
6
6
  } from "@getpaseo/plugin/server";
7
7
  import { z } from "zod";
8
8
  import {
9
+ DUTY,
9
10
  LOBBY,
10
11
  POST_TEXT_MAX,
11
12
  PostKindSchema,
@@ -32,9 +33,11 @@ export interface OfficeToolPorts {
32
33
  }
33
34
 
34
35
  const BoardChoiceSchema = z.enum(["room", "lobby"]);
36
+ /** The duty board is read, and its duties claimed and finished; it takes no post. */
37
+ const ReadChoiceSchema = z.enum(["room", "lobby", "duty"]);
35
38
 
36
39
  export const ReadInputSchema = z.object({
37
- board: BoardChoiceSchema.optional(),
40
+ board: ReadChoiceSchema.optional(),
38
41
  since: z.number().int().nonnegative().optional(),
39
42
  });
40
43
  export type ReadInput = z.output<typeof ReadInputSchema>;
@@ -53,8 +56,9 @@ export type UpdateInput = z.output<typeof UpdateInputSchema>;
53
56
  /** "room" is the caller's workspace board; without a workspace it is the lobby. */
54
57
  export function boardFor(
55
58
  agent: Pick<ToolAgent, "workspaceId">,
56
- choice: "room" | "lobby" | undefined,
59
+ choice: "room" | "lobby" | "duty" | undefined,
57
60
  ): string {
61
+ if (choice === "duty") return DUTY;
58
62
  return choice === "lobby" || agent.workspaceId === null ? LOBBY : agent.workspaceId;
59
63
  }
60
64
 
@@ -63,8 +67,9 @@ export function postLine(post: Post, label: (author: string) => string): string
63
67
  const name = (author: string) => oneLine(label(author));
64
68
  const state = post.state ? ` ${post.state}` : "";
65
69
  const claim = post.claimedBy ? ` by ${name(post.claimedBy)}` : "";
70
+ const link = post.link ? ` (${post.board === LOBBY ? "on" : "lobby"} ${post.link})` : "";
66
71
  const to = post.to ? ` to ${name(post.to)}` : "";
67
- return `${post.id} ${post.kind}${state}${claim}, from ${name(post.author)}${to}: ${indented(post.text)}`;
72
+ return `${post.id} ${post.kind}${state}${claim}${link}, from ${name(post.author)}${to}: ${indented(post.text)}`;
68
73
  }
69
74
 
70
75
  export function readText(
@@ -132,7 +137,7 @@ export function officeTools(ports: OfficeToolPorts): AgentToolDefinition[] {
132
137
  defineAgentTool({
133
138
  name: "office_read",
134
139
  description:
135
- "Read your workspace's office board (or board: lobby). Up to 30 posts, newest last, and a cursor; pass it as since for newer posts only.",
140
+ "Read your workspace's office board (or board: lobby, or duty for the day's duties). Up to 30 posts, newest last; pass the cursor as since for newer only.",
136
141
  input: ReadInputSchema,
137
142
  execute: (input, { agent }) => runRead(ports, agent, input),
138
143
  }),
@@ -145,7 +150,8 @@ export function officeTools(ports: OfficeToolPorts): AgentToolDefinition[] {
145
150
  }),
146
151
  defineAgentTool({
147
152
  name: "office_update",
148
- description: "Claim, finish (done) or reopen a task on an office board, by post id.",
153
+ description:
154
+ "Claim, finish (done) or reopen a task or a duty on an office board (the duty board too), by post id.",
149
155
  input: UpdateInputSchema,
150
156
  execute: (input, { agent }) => runUpdate(ports, agent, input),
151
157
  }),
@@ -1,14 +1,20 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import {
2
3
  BOARD_POST_MAX,
3
4
  DONE_TASK_TTL_MS,
5
+ DUTY,
6
+ LOBBY,
4
7
  POST_TEXT_MAX,
5
8
  READ_POST_MAX,
9
+ USER_AUTHOR,
6
10
  type DeleteResult,
11
+ type Duty,
7
12
  type Post,
8
13
  type PostKind,
9
14
  type PostResult,
10
15
  type UpdateAction,
11
16
  } from "../shared/contracts.js";
17
+ import { dutyPostText } from "../shared/duties.js";
12
18
  import type { BoardStore, BoardsFile } from "./board-store.js";
13
19
  import { errorMessage } from "./errors.js";
14
20
  import type { Clock } from "./timers.js";
@@ -44,14 +50,39 @@ export interface BoardServicePorts {
44
50
  label(author: string): string;
45
51
  onBoard(board: string, posts: readonly Post[]): void;
46
52
  onBoardRemoved(board: string): void;
53
+ /** The workspace an agent works in, or null for none; its board gets the agent's lobby claims. */
54
+ workspaceOf(agentId: string): Promise<string | null>;
55
+ /** Why this update of this post is refused, before the claim rules; null when it is not. */
56
+ refuse?(post: Post, input: PostUpdate): string | null;
57
+ }
58
+
59
+ /** What the duty board is brought up to: the list, the board's day, and the duties due now. */
60
+ export interface DutySync {
61
+ duties: readonly Duty[];
62
+ /** The board's day (YYYY-MM-DD): done duties of earlier days leave the board. */
63
+ day: string;
64
+ /** Posted for `day` unless the duty has a post of that day or later, an owed one, or one finished that day. */
65
+ due: readonly Duty[];
66
+ /** The board's day an instant falls on: a done duty is judged by the day it was finished. */
67
+ dayOf(at: number): string;
47
68
  }
48
69
 
49
70
  export interface BoardService {
50
71
  start(): Promise<void>;
51
72
  boards(): Record<string, Post[]>;
73
+ postsOf(board: string): Post[];
52
74
  wakesPaused(): boolean;
53
75
  post(input: NewPost): Promise<PostResult>;
54
76
  update(input: PostUpdate): Promise<PostResult>;
77
+ /**
78
+ * Claims a lobby task or a duty for an automatic assignment. Returns null if the task changed or
79
+ * the agent can no longer pick it up: it holds one already, on either board.
80
+ */
81
+ claimLobbyTask(id: string, agentId: string, expectedSeq: number): Promise<Post | null>;
82
+ /** Reopens only this revision of the claim after its dispatch failed. */
83
+ releaseLobbyTask(claim: Post): Promise<void>;
84
+ confirmLobbyDelivery(claim: Post): Promise<void>;
85
+ finishLobbyClaim(claim: Post): Promise<void>;
55
86
  remove(id: string): Promise<DeleteResult>;
56
87
  /** Deletes every done task of `board`. */
57
88
  clearDone(board: string): Promise<DeleteResult>;
@@ -59,8 +90,15 @@ export interface BoardService {
59
90
  removeBoard(board: string): Promise<void>;
60
91
  setWakesPaused(paused: boolean): Promise<void>;
61
92
  prune(): Promise<void>;
93
+ /** Brings the duty board up to the list and the day, in one save. */
94
+ syncDuties(plan: DutySync): Promise<void>;
95
+ /** A pretend duty the 3D office acted out: done by that agent. Once done, it stays as it is. */
96
+ actDuty(id: string, agentId: string): Promise<PostResult>;
62
97
  }
63
98
 
99
+ /** The boards whose tasks the office hands to idle agents. */
100
+ const PICKUP_BOARDS: ReadonlySet<string> = new Set([LOBBY, DUTY]);
101
+
64
102
  type Outcome<T> = { ok: true; value: T } | { ok: false; error: string };
65
103
 
66
104
  const VERBS: Record<UpdateAction, string> = { claim: "claim", done: "finish", reopen: "reopen" };
@@ -90,10 +128,41 @@ function withoutClaim(post: Post): Post {
90
128
  updatedAt: post.updatedAt,
91
129
  };
92
130
  if (post.to !== undefined) next.to = post.to;
131
+ if (post.namedPickup) next.namedPickup = true;
93
132
  if (post.state !== undefined) next.state = post.state;
133
+ if (post.duty !== undefined) next.duty = post.duty;
94
134
  return next;
95
135
  }
96
136
 
137
+ function isDutyTask(post: Post): boolean {
138
+ return post.board === DUTY && post.kind === "task" && post.duty !== undefined;
139
+ }
140
+
141
+ /** The board's day a done duty was finished on: an owed one is finished on a later day than its own. */
142
+ function finishedDay(post: Post, plan: DutySync): string {
143
+ return plan.dayOf(Date.parse(post.updatedAt));
144
+ }
145
+
146
+ /** The weekday of a day (YYYY-MM-DD), 0 for Sunday. */
147
+ function weekdayOf(day: string): number {
148
+ return new Date(`${day}T00:00:00.000Z`).getUTCDay();
149
+ }
150
+
151
+ /**
152
+ * Off the board at a sync: a duty of an earlier day finished on an earlier day (a move of the
153
+ * notes' zone west can put either day after the plan's), and an open duty nobody holds that is no
154
+ * longer listed, or whose day is the plan's and no longer one of its weekdays.
155
+ */
156
+ function leavesAtSync(post: Post, plan: DutySync, listed: ReadonlyMap<string, Duty>): boolean {
157
+ if (!isDutyTask(post) || post.duty === undefined) return false;
158
+ if (post.state === "done") return post.duty.day < plan.day && finishedDay(post, plan) < plan.day;
159
+ if (post.state !== "open" || post.claimedBy !== undefined) return false;
160
+ const duty = listed.get(post.duty.id);
161
+ return (
162
+ duty === undefined || (post.duty.day === plan.day && !duty.days.includes(weekdayOf(plan.day)))
163
+ );
164
+ }
165
+
97
166
  export function createBoardService(ports: BoardServicePorts): BoardService {
98
167
  let data: BoardsFile = { version: 1, nextSeq: 1, wakesPaused: false, posts: [] };
99
168
  let chain: Promise<unknown> = Promise.resolve();
@@ -123,8 +192,24 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
123
192
  }
124
193
  }
125
194
 
195
+ /** Drops each link whose post is gone, and adds the boards of the posts it changes. */
196
+ function withoutDeadLinks(next: BoardsFile, touched: string[]): BoardsFile {
197
+ const ids = new Set(next.posts.map((item) => item.id));
198
+ if (next.posts.every((item) => item.link === undefined || ids.has(item.link))) return next;
199
+ const posts = next.posts.map((item) => {
200
+ if (item.link === undefined || ids.has(item.link)) return item;
201
+ touched.push(item.board);
202
+ const unlinked = { ...item };
203
+ delete unlinked.link;
204
+ return unlinked;
205
+ });
206
+ return { ...next, posts };
207
+ }
208
+
126
209
  /** Saves `next`, then makes it current and announces the touched boards. */
127
- async function commit(next: BoardsFile, touched: readonly string[]): Promise<Outcome<null>> {
210
+ async function commit(proposed: BoardsFile, changed: readonly string[]): Promise<Outcome<null>> {
211
+ const touched = [...changed];
212
+ const next = withoutDeadLinks(proposed, touched);
128
213
  try {
129
214
  await ports.store.save(next);
130
215
  } catch (error) {
@@ -162,6 +247,8 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
162
247
  };
163
248
  if (input.to !== undefined) created.to = input.to;
164
249
  if (input.kind === "task") created.state = "open";
250
+ if (input.board === LOBBY && input.kind === "task" && input.to && input.to !== input.author)
251
+ created.namedPickup = true;
165
252
  // Make room among the existing posts, so the new one is never the one dropped.
166
253
  const kept = trimBoard(postsOf(input.board), BOARD_POST_MAX - 1);
167
254
  if (kept.length >= BOARD_POST_MAX) {
@@ -173,12 +260,66 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
173
260
  return saved.ok ? { ok: true, post: created } : saved;
174
261
  }
175
262
 
263
+ /** The post linked with `post`, if it still exists and links back. */
264
+ function partnerOf(post: Post): Post | undefined {
265
+ if (post.link === undefined) return undefined;
266
+ const other = data.posts.find((item) => item.id === post.link);
267
+ return other?.link === post.id ? other : undefined;
268
+ }
269
+
270
+ /** A lookup that fails is logged: the claim stands without a copy. */
271
+ async function roomOf(agentId: string): Promise<string | null> {
272
+ try {
273
+ return await ports.workspaceOf(agentId);
274
+ } catch (error) {
275
+ ports.log(`[office] no workspace for ${agentId}: ${errorMessage(error)}`);
276
+ return null;
277
+ }
278
+ }
279
+
280
+ /** `posts` with a copy of the lobby task on `room`, trimmed as a new post is; null when full. */
281
+ function withCopy(
282
+ posts: readonly Post[],
283
+ task: Post,
284
+ claimer: string,
285
+ room: string,
286
+ seq: number,
287
+ ): { posts: Post[]; copy: Post } | null {
288
+ const kept = trimBoard(
289
+ posts.filter((item) => item.board === room),
290
+ BOARD_POST_MAX - 1,
291
+ );
292
+ if (kept.length >= BOARD_POST_MAX) {
293
+ ports.log(
294
+ `[office] no copy of ${task.id} on ${room}: the board holds 200 open or claimed tasks`,
295
+ );
296
+ return null;
297
+ }
298
+ const stamp = now();
299
+ const copy: Post = {
300
+ id: `p${seq}`,
301
+ seq,
302
+ board: room,
303
+ kind: "task",
304
+ text: task.text,
305
+ author: task.author,
306
+ state: "claimed",
307
+ claimedBy: claimer,
308
+ link: task.id,
309
+ createdAt: stamp,
310
+ updatedAt: stamp,
311
+ };
312
+ return { posts: [...posts.filter((item) => item.board !== room), ...kept, copy], copy };
313
+ }
314
+
176
315
  function nextState(post: Post, input: PostUpdate): Outcome<Post | null> {
177
316
  const refuse = (reason: string): Outcome<Post | null> => ({
178
317
  ok: false,
179
318
  error: `Unable to ${VERBS[input.action]} ${post.id}: ${reason}`,
180
319
  });
181
320
  if (post.kind !== "task") return refuse("it is a note");
321
+ const refusal = ports.refuse?.(post, input) ?? null;
322
+ if (refusal !== null) return refuse(refusal);
182
323
  if (input.action === "claim") {
183
324
  if (post.state === "done") return refuse("it is done");
184
325
  if (post.state === "claimed" && post.claimedBy === input.actor)
@@ -189,27 +330,105 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
189
330
  return { ok: true, value: { ...post, state: "claimed", claimedBy: input.actor } };
190
331
  }
191
332
  if (input.action === "done") {
192
- return post.state === "done"
193
- ? { ok: true, value: null }
194
- : { ok: true, value: { ...post, state: "done" } };
333
+ const done = { ...post, state: "done" as const };
334
+ delete done.pickupMessageId;
335
+ return post.state === "done" ? { ok: true, value: null } : { ok: true, value: done };
195
336
  }
196
337
  // Like a repeated claim: an open task that nobody holds is not changed by a reopen.
197
338
  if (post.state === "open" && post.claimedBy === undefined) return { ok: true, value: null };
198
339
  return { ok: true, value: { ...withoutClaim(post), state: "open" } };
199
340
  }
200
341
 
201
- async function updatePost(input: PostUpdate): Promise<PostResult> {
342
+ async function updatePost(input: PostUpdate, pickupMessageId?: string): Promise<PostResult> {
202
343
  const post = data.posts.find((item) => item.id === input.id);
203
344
  if (!post) return { ok: false, error: `Unable to update ${input.id}: no such post` };
204
345
  const next = nextState(post, input);
205
346
  if (!next.ok) return next;
206
347
  if (next.value === null) return { ok: true, post };
207
- const changed: Post = { ...next.value, seq: data.nextSeq, updatedAt: now() };
208
- const posts = data.posts.map((item) => (item.id === post.id ? changed : item));
209
- const saved = await commit({ ...data, nextSeq: data.nextSeq + 1, posts }, [post.board]);
348
+ const partner = partnerOf(post);
349
+ if (partner?.board === LOBBY && next.value.state === "open")
350
+ return reopenFromCopy(post, partner);
351
+ const room =
352
+ partner === undefined &&
353
+ post.board === LOBBY &&
354
+ next.value.state === "claimed" &&
355
+ input.actor !== USER_AUTHOR
356
+ ? await roomOf(input.actor)
357
+ : null;
358
+ let seq = data.nextSeq;
359
+ const changed: Post = { ...next.value, seq: seq++, updatedAt: now() };
360
+ if (pickupMessageId) changed.pickupMessageId = pickupMessageId;
361
+ let posts = data.posts.map((item) => (item.id === post.id ? changed : item));
362
+ const touched = [post.board];
363
+ if (partner !== undefined && changed.state === "open") {
364
+ // The lobby task is free again: its copy goes, whatever its state.
365
+ posts = posts.filter((item) => item.id !== partner.id);
366
+ touched.push(partner.board);
367
+ } else if (partner !== undefined && changed.state === "done" && partner.state !== "done") {
368
+ const done: Post = { ...partner, state: "done", seq: seq++, updatedAt: now() };
369
+ delete done.pickupMessageId;
370
+ posts = posts.map((item) => (item.id === partner.id ? done : item));
371
+ touched.push(partner.board);
372
+ } else if (room !== null) {
373
+ const added = withCopy(posts, changed, input.actor, room, seq);
374
+ if (added !== null) {
375
+ seq++;
376
+ changed.link = added.copy.id;
377
+ posts = added.posts;
378
+ touched.push(room);
379
+ }
380
+ }
381
+ const saved = await commit({ ...data, nextSeq: seq, posts }, touched);
210
382
  return saved.ok ? { ok: true, post: changed } : saved;
211
383
  }
212
384
 
385
+ /** Reopening a copy reopens its lobby task and deletes the copy; the result is the lobby task. */
386
+ async function reopenFromCopy(copy: Post, task: Post): Promise<PostResult> {
387
+ // A linked lobby task is claimed or done, so a reopen always frees it.
388
+ const reopened: Post = {
389
+ ...withoutClaim(task),
390
+ state: "open",
391
+ seq: data.nextSeq,
392
+ updatedAt: now(),
393
+ };
394
+ const posts = data.posts
395
+ .filter((item) => item.id !== copy.id)
396
+ .map((item) => (item.id === task.id ? reopened : item));
397
+ const saved = await commit({ ...data, nextSeq: data.nextSeq + 1, posts }, [
398
+ task.board,
399
+ copy.board,
400
+ ]);
401
+ return saved.ok ? { ok: true, post: reopened } : saved;
402
+ }
403
+
404
+ /** Gives each lobby task claimed by an agent, without a copy, one on the agent's board. */
405
+ async function copyClaims(): Promise<void> {
406
+ let posts = data.posts;
407
+ let seq = data.nextSeq;
408
+ const touched: string[] = [];
409
+ for (const task of postsOf(LOBBY)) {
410
+ const claimer = task.claimedBy;
411
+ if (task.kind !== "task" || task.state !== "claimed" || partnerOf(task)) continue;
412
+ if (claimer === undefined || claimer === USER_AUTHOR) continue;
413
+ const room = await roomOf(claimer);
414
+ if (room === null) continue;
415
+ const added = withCopy(posts, task, claimer, room, seq);
416
+ if (added === null) continue;
417
+ // The task keeps its seq, so the completion line of its assignment still matches.
418
+ const linked = { ...task, link: added.copy.id };
419
+ posts = added.posts.map((item) => (item.id === task.id ? linked : item));
420
+ seq++;
421
+ touched.push(LOBBY, room);
422
+ }
423
+ if (touched.length > 0) await commit({ ...data, nextSeq: seq, posts }, touched);
424
+ }
425
+
426
+ async function updateForPickup(input: PostUpdate, pickupMessageId?: string): Promise<Post> {
427
+ const result = await updatePost(input, pickupMessageId);
428
+ if (!result.ok) throw new Error(result.error);
429
+ return result.post;
430
+ }
431
+
213
432
  async function prunePosts(): Promise<void> {
214
433
  const cutoff = ports.clock.now() - DONE_TASK_TTL_MS;
215
434
  const expired = data.posts.filter(
@@ -222,13 +441,93 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
222
441
  await commit({ ...data, posts: data.posts.filter((item) => !gone.has(item.id)) }, boards);
223
442
  }
224
443
 
444
+ /** Today's duties not yet posted, each as a new open post. */
445
+ function newDutyPosts(plan: DutySync, kept: readonly Post[], firstSeq: number): Post[] {
446
+ const stamp = now();
447
+ const held = (duty: Duty) =>
448
+ kept.some(
449
+ (post) =>
450
+ isDutyTask(post) &&
451
+ post.duty?.id === duty.id &&
452
+ (post.state !== "done" ||
453
+ post.duty.day >= plan.day ||
454
+ finishedDay(post, plan) === plan.day),
455
+ );
456
+ return plan.due
457
+ .filter((duty) => !held(duty))
458
+ .map((duty, index) => ({
459
+ id: `p${firstSeq + index}`,
460
+ seq: firstSeq + index,
461
+ board: DUTY,
462
+ kind: "task" as const,
463
+ text: dutyPostText(duty),
464
+ author: USER_AUTHOR,
465
+ state: "open" as const,
466
+ duty: { id: duty.id, day: plan.day },
467
+ createdAt: stamp,
468
+ updatedAt: stamp,
469
+ }));
470
+ }
471
+
472
+ async function syncDutyBoard(plan: DutySync): Promise<void> {
473
+ const listed = new Map(plan.duties.map((duty) => [duty.id, duty]));
474
+ let seq = data.nextSeq;
475
+ let changed = false;
476
+ const kept: Post[] = [];
477
+ for (const post of data.posts) {
478
+ if (leavesAtSync(post, plan, listed)) {
479
+ changed = true;
480
+ continue;
481
+ }
482
+ const duty = post.duty === undefined ? undefined : listed.get(post.duty.id);
483
+ const text = duty === undefined ? post.text : dutyPostText(duty);
484
+ const editable = isDutyTask(post) && post.state === "open" && post.claimedBy === undefined;
485
+ if (editable && text !== post.text) {
486
+ kept.push({ ...post, text, seq, updatedAt: now() });
487
+ seq += 1;
488
+ changed = true;
489
+ } else kept.push(post);
490
+ }
491
+ const added = newDutyPosts(plan, kept, seq);
492
+ if (!changed && added.length === 0) return;
493
+ const saved = await commit(
494
+ { ...data, nextSeq: seq + added.length, posts: [...kept, ...added] },
495
+ [DUTY],
496
+ );
497
+ if (!saved.ok) throw new Error(saved.error);
498
+ }
499
+
500
+ async function recordActed(id: string, agentId: string): Promise<PostResult> {
501
+ const post = data.posts.find((item) => item.id === id);
502
+ const refuse = (reason: string): PostResult => ({
503
+ ok: false,
504
+ error: `Unable to record ${id}: ${reason}`,
505
+ });
506
+ if (!post) return refuse("no such post");
507
+ if (!isDutyTask(post)) return refuse("it is not a duty");
508
+ if (post.state === "done") return { ok: true, post };
509
+ if (post.claimedBy !== undefined) return refuse(`claimed by ${ports.label(post.claimedBy)}`);
510
+ const acted: Post = {
511
+ ...post,
512
+ state: "done",
513
+ claimedBy: agentId,
514
+ seq: data.nextSeq,
515
+ updatedAt: now(),
516
+ };
517
+ const posts = data.posts.map((item) => (item.id === id ? acted : item));
518
+ const saved = await commit({ ...data, nextSeq: data.nextSeq + 1, posts }, [DUTY]);
519
+ return saved.ok ? { ok: true, post: acted } : saved;
520
+ }
521
+
225
522
  return {
226
523
  // Queued like every mutation, so a post made while the file loads waits for it.
227
524
  start: () =>
228
525
  exclusive(async () => {
229
526
  data = await ports.store.load();
527
+ await copyClaims();
230
528
  await prunePosts();
231
529
  }),
530
+ postsOf,
232
531
  boards() {
233
532
  const grouped: Record<string, Post[]> = {};
234
533
  for (const board of new Set(data.posts.map((item) => item.board)))
@@ -238,12 +537,82 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
238
537
  wakesPaused: () => data.wakesPaused,
239
538
  post: (input) => exclusive(() => createPost(input)),
240
539
  update: (input) => exclusive(() => updatePost(input)),
540
+ claimLobbyTask: (id, agentId, expectedSeq) =>
541
+ exclusive(async () => {
542
+ const pickup = data.posts.filter((post) => PICKUP_BOARDS.has(post.board));
543
+ const task = pickup.find((post) => post.id === id);
544
+ if (
545
+ data.wakesPaused ||
546
+ task?.seq !== expectedSeq ||
547
+ task.kind !== "task" ||
548
+ task.state !== "open" ||
549
+ (task.to !== undefined && (!task.namedPickup || task.to !== agentId)) ||
550
+ task.claimedBy !== undefined ||
551
+ task.author === agentId
552
+ )
553
+ return null;
554
+ if (pickup.some((post) => post.state === "claimed" && post.claimedBy === agentId))
555
+ return null;
556
+ if (ports.refuse?.(task, { id, actor: agentId, action: "claim" })) return null;
557
+ return updateForPickup({ id, actor: agentId, action: "claim" }, randomUUID());
558
+ }),
559
+ finishLobbyClaim: (claim) =>
560
+ exclusive(async () => {
561
+ const current = data.posts.find((p) => p.id === claim.id && PICKUP_BOARDS.has(p.board));
562
+ if (
563
+ current?.state === "claimed" &&
564
+ current.seq === claim.seq &&
565
+ current.claimedBy &&
566
+ current.claimedBy === claim.claimedBy
567
+ ) {
568
+ await updateForPickup({ id: current.id, action: "done", actor: current.claimedBy });
569
+ }
570
+ }),
571
+ confirmLobbyDelivery: (claim) =>
572
+ exclusive(async () => {
573
+ const current = data.posts.find((post) => post.id === claim.id);
574
+ if (
575
+ !current?.pickupMessageId ||
576
+ current.seq !== claim.seq ||
577
+ current.pickupMessageId !== claim.pickupMessageId
578
+ )
579
+ return;
580
+ const delivered = { ...current };
581
+ delete delivered.pickupMessageId;
582
+ const saved = await commit(
583
+ { ...data, posts: data.posts.map((p) => (p.id === claim.id ? delivered : p)) },
584
+ [],
585
+ );
586
+ if (!saved.ok) throw new Error(saved.error);
587
+ }),
588
+ releaseLobbyTask: (claim) =>
589
+ exclusive(async () => {
590
+ const task = data.posts.find((post) => post.id === claim.id);
591
+ if (
592
+ task !== undefined &&
593
+ PICKUP_BOARDS.has(task.board) &&
594
+ !!task.pickupMessageId &&
595
+ task.pickupMessageId === claim.pickupMessageId &&
596
+ task.seq === claim.seq &&
597
+ task.state === "claimed" &&
598
+ claim.claimedBy !== undefined &&
599
+ task.claimedBy === claim.claimedBy
600
+ ) {
601
+ await updateForPickup({ id: task.id, actor: claim.claimedBy, action: "reopen" });
602
+ }
603
+ }),
241
604
  remove: (id) =>
242
605
  exclusive(async (): Promise<DeleteResult> => {
243
606
  const post = data.posts.find((item) => item.id === id);
244
607
  if (!post) return { ok: false, error: `Unable to delete ${id}: no such post` };
245
- const posts = data.posts.filter((item) => item.id !== id);
246
- const saved = await commit({ ...data, posts }, [post.board]);
608
+ // A lobby task takes its copy with it; a deleted copy only unlinks its lobby task.
609
+ const partner = post.board === LOBBY ? partnerOf(post) : undefined;
610
+ const gone = new Set([id, ...(partner ? [partner.id] : [])]);
611
+ const posts = data.posts.filter((item) => !gone.has(item.id));
612
+ const saved = await commit({ ...data, posts }, [
613
+ post.board,
614
+ ...(partner ? [partner.board] : []),
615
+ ]);
247
616
  return saved.ok ? { ok: true } : saved;
248
617
  }),
249
618
  clearDone: (board) =>
@@ -280,5 +649,7 @@ export function createBoardService(ports: BoardServicePorts): BoardService {
280
649
  if (!saved.ok) throw new Error(saved.error);
281
650
  }),
282
651
  prune: () => exclusive(prunePosts),
652
+ syncDuties: (plan) => exclusive(() => syncDutyBoard(plan)),
653
+ actDuty: (id, agentId) => exclusive(() => recordActed(id, agentId)),
283
654
  };
284
655
  }
@@ -0,0 +1,34 @@
1
+ /** Only the host-configured logo may enter the offline 3D frame. */
2
+ export function createLogoReader(read = fetch) {
3
+ let cached: { url: string; until: number; result: Promise<string | null> } | undefined;
4
+ return (url: string) => {
5
+ if (cached?.url === url && Date.now() < cached.until) return cached.result;
6
+ const result = readLogo(url, read).catch(() => null);
7
+ cached = { url, until: Date.now() + 300_000, result };
8
+ return result;
9
+ };
10
+ }
11
+
12
+ async function readLogo(url: string, read: typeof fetch): Promise<string | null> {
13
+ const response = await read(url, { redirect: "error", signal: AbortSignal.timeout(5000) });
14
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
15
+ if (!response.ok || !type || !/^image\/(png|jpeg|webp|gif|svg\+xml|avif)$/.test(type)) {
16
+ await response.body?.cancel();
17
+ return null;
18
+ }
19
+ const reader = response.body?.getReader();
20
+ if (!reader) return null;
21
+ const chunks: Uint8Array[] = [];
22
+ let size = 0;
23
+ for (;;) {
24
+ const chunk = await reader.read();
25
+ if (chunk.done) break;
26
+ size += chunk.value.length;
27
+ if (size > 1024 * 1024) {
28
+ await reader.cancel();
29
+ return null;
30
+ }
31
+ chunks.push(chunk.value);
32
+ }
33
+ return size ? `data:${type};base64,${Buffer.concat(chunks).toString("base64")}` : null;
34
+ }