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
@@ -2,17 +2,20 @@ import { lifeLine } from "../shared/life-lines.js";
2
2
  import type { PluginTurnOutcome } from "@getpaseo/plugin/server";
3
3
  import {
4
4
  CHAT_MESSAGE_MAX,
5
+ GROUP_PHOTO_COUNT,
5
6
  CHAT_TEXT_MAX,
6
7
  ChatMessageSchema,
7
8
  type ChatChange,
9
+ type ChatImage,
8
10
  type ChatMessage,
9
11
  type ChatRequest,
10
12
  type ChatResult,
11
13
  type ChatSnapshot,
12
14
  type OfficeAgent,
13
15
  type OfficeWorkspace,
16
+ type Post,
14
17
  } from "../shared/contracts.js";
15
- import { agentTitle } from "../shared/model.js";
18
+ import { agentTitle, waitingOnOf } from "../shared/model.js";
16
19
  import {
17
20
  createChatEngine,
18
21
  type ChatEngine,
@@ -21,8 +24,11 @@ import {
21
24
  type Translate,
22
25
  } from "../shared/upstream/chat-engine.js";
23
26
  import type { ChatData, ChatStore } from "./chat-store.js";
27
+ import { isOfficePhoto } from "./group-photo.js";
24
28
  import { errorMessage } from "./errors.js";
25
29
  import type { DirectoryView } from "./hub.js";
30
+ import { autoGroupPrompt, matchingLobbyTaskAnswer } from "./chat-group.js";
31
+ import { NOTES_WRITER_TITLE } from "./notes-writer.js";
26
32
  import type { Clock } from "./timers.js";
27
33
 
28
34
  /** How often the engine's clock runs: the morning hello, the lunch poll, reminders. */
@@ -36,14 +42,38 @@ const USAGE_LIMIT =
36
42
  /usage limit|rate limit|quota|limit (?:reached|exceeded|resets)|out of (?:usage|credits)/i;
37
43
  const NAME_CHAR = /[\p{L}\p{N}_-]/u;
38
44
 
45
+ /** A refreshed session could not accept an automatic group message. Nothing was sent. */
46
+ export class GroupSessionUnavailable extends Error {}
47
+
48
+ export interface ChatDelivery {
49
+ group: boolean;
50
+ messageId: string;
51
+ sentAt: number;
52
+ }
53
+
39
54
  export interface ChatServicePorts {
55
+ lobbyPosts(): readonly Post[] | null;
40
56
  store: ChatStore;
41
57
  clock: Clock;
42
58
  tr: Translate;
43
59
  /** Sends a prompt that steers a running turn. */
44
- send(agentId: string, prompt: string): Promise<void>;
45
- /** The last assistant message of the turn `turnId`, read from the agent's timeline; null when there is none. */
46
- lastAnswer(agentId: string, turnId: string | null): Promise<string | null>;
60
+ send(
61
+ agentId: string,
62
+ prompt: string,
63
+ images?: ChatImage[],
64
+ delivery?: ChatDelivery,
65
+ ): Promise<void>;
66
+ /** For a group request, verify the user's timeline message and read only the answer after it. */
67
+ readTurn(
68
+ agentId: string,
69
+ turnId: string | null,
70
+ group?: ChatDelivery,
71
+ officeIds?: readonly string[],
72
+ ): Promise<{
73
+ privateTurn?: boolean;
74
+ matches: boolean;
75
+ text: string | null;
76
+ }>;
47
77
  emit(change: ChatChange): void;
48
78
  log(message: string): void;
49
79
  }
@@ -144,15 +174,82 @@ function memberOf(agent: OfficeAgent, workspaces: readonly OfficeWorkspace[]): C
144
174
  };
145
175
  }
146
176
 
147
- // Drops a photo's picture and the cards' bodies.
177
+ // Keep only the public fields that the chat can display.
148
178
  function wireOf(message: EngineMessage): ChatMessage | null {
149
179
  const parsed = ChatMessageSchema.safeParse(message);
150
180
  return parsed.success ? parsed.data : null;
151
181
  }
152
182
 
183
+ // Only a short social command goes to the scene's simulated conversation.
184
+ const SOCIAL_COMMAND =
185
+ /^(?:(?:meeting|stand-?up)(?: now| again| at \d{1,2}(?::\d{2})?(?: ?[ap]m)?)?|milk tea|bubble tea|lunch|good job|well done|thanks|thank you|bye|goodbye|họp|trà sữa|tra sua|ăn trưa|cảm ơn|cám ơn|going home)[?!. ]*$/i;
186
+
187
+ function messageMode(
188
+ text: string,
189
+ hasTarget: boolean,
190
+ replyTo?: string,
191
+ ): "direct" | "social" | "group" {
192
+ if (hasTarget || replyTo || /(?:^|\s)@[\p{L}\p{N}_-]/u.test(text)) return "direct";
193
+ return SOCIAL_COMMAND.test(text) || !text ? "social" : "group";
194
+ }
195
+
196
+ function boardAnswer(text: string, lobbyPosts: ChatServicePorts["lobbyPosts"]): string | null {
197
+ const question = text
198
+ .toLowerCase()
199
+ .replaceAll("’", "'")
200
+ .replace(/^@director[,:]?\s+/i, "")
201
+ .replace(/[?.!]+$/, "")
202
+ .trim();
203
+ let state: "done" | "claimed" | "open" | "remaining";
204
+ if (
205
+ /^(?:(?:what(?:'s| is| was| has been| got)|which tasks (?:are|were)) (?:already )?(?:done|finished|completed)|what (?:did (?:you|we|the team) (?:finish|complete)|have (?:you|we) (?:done|finished|completed)))(?: so far)?$/.test(
206
+ question,
207
+ )
208
+ )
209
+ state = "done";
210
+ else if (
211
+ /^(?:what(?:'s| is) (?:in progress|being worked on)|what are (?:you|we) working on)$/.test(
212
+ question,
213
+ )
214
+ )
215
+ state = "claimed";
216
+ else if (/^what(?:'s| is) left(?: to do)?$/.test(question)) state = "remaining";
217
+ else if (/^what(?:'s| is) (?:still )?open$/.test(question)) state = "open";
218
+ else return null;
219
+ const posts = lobbyPosts();
220
+ if (!posts) return "The lobby board is unavailable right now.";
221
+ const tasks = posts
222
+ .filter(
223
+ (p) => p.kind === "task" && (state === "remaining" ? p.state !== "done" : p.state === state),
224
+ )
225
+ .sort((a, b) => b.seq - a.seq);
226
+ const label = {
227
+ done: "marked done",
228
+ claimed: "in progress",
229
+ open: "open",
230
+ remaining: "unfinished",
231
+ }[state];
232
+ if (!tasks.length) return `No lobby tasks are ${label}.`;
233
+ const lines = tasks
234
+ .slice(0, 5)
235
+ .map((p) => `${p.id} — ${short(p.text.replace(/\s+/g, " "), 120)}`);
236
+ return [
237
+ `${tasks.length} lobby task${tasks.length === 1 ? "" : "s"} ${label}.`,
238
+ ...lines,
239
+ ...(tasks.length > 5 ? ["Showing the five most recently updated."] : []),
240
+ ].join("\n");
241
+ }
242
+
153
243
  interface Waiting {
154
244
  member: ChatMember;
155
245
  reply: { id: string; name: string; text: string };
246
+ delivery: ChatDelivery;
247
+ }
248
+
249
+ function imageCountLabel(images: ChatImage[] | undefined): string {
250
+ const count = images?.length ?? 0;
251
+ if (!count) return "";
252
+ return count === 1 ? "1 image" : `${count} images`;
156
253
  }
157
254
 
158
255
  const OK: ChatResult = { ok: true };
@@ -162,6 +259,7 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
162
259
  const { clock, log, tr } = ports;
163
260
  const loaded = await ports.store.load();
164
261
  const roster = new Map<string, ChatMember>();
262
+ const availableForGroup = new Set<string>();
165
263
  // The prompts waiting for an answer, by agent, in send order; never an empty list. In memory only.
166
264
  // Each ends by its own failure, a turn end, a close or an archive.
167
265
  const waiting = new Map<string, readonly Waiting[]>();
@@ -219,7 +317,7 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
219
317
  if (message !== null) ports.emit({ op: op === "update" ? "update" : "add", message });
220
318
  return;
221
319
  }
222
- ports.emit({ op: "all", messages: wireMessages() });
320
+ ports.emit({ op: "all", messages: wireMessages(), pinned: engine.state.pinned });
223
321
  }
224
322
 
225
323
  const engine: ChatEngine = createChatEngine({
@@ -264,53 +362,211 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
264
362
  }
265
363
  scheduleClock();
266
364
 
267
- // Ends these waits of the agent. When none is left, typing stops while the agent is still a
268
- // member: the engine cannot name one that left.
269
- function release(agentId: string, ended: readonly Waiting[]): void {
270
- const entries = waiting.get(agentId);
271
- if (entries === undefined) return;
272
- const left = entries.filter((entry) => !ended.includes(entry));
273
- if (left.length > 0) {
274
- waiting.set(agentId, left);
275
- return;
365
+ // A close or send failure can settle some of these prompts while the timeline is being read.
366
+ // Reply only to waits that are still current, before removing the member from the engine.
367
+ function finish(
368
+ agentId: string,
369
+ ended: readonly Waiting[],
370
+ result: { answer: string } | { notice: string } | null,
371
+ ): void {
372
+ const current = waiting.get(agentId);
373
+ if (!current) return;
374
+ const pending = current.filter((entry) => ended.includes(entry));
375
+ const newest = pending.at(-1);
376
+ if (!newest) return;
377
+ if (result && "answer" in result) {
378
+ const allGroup = pending.every(({ reply }) => engine.byId(reply.id)?.tag === "group");
379
+ engine.say(agentId, clipAnswer(result.answer), {
380
+ now: true,
381
+ long: true,
382
+ reply: newest.reply,
383
+ tag: allGroup ? "group-reply" : undefined,
384
+ });
385
+ } else if (result) {
386
+ for (const entry of pending) {
387
+ engine.say(DIRECTOR, `${entry.member.name}: ${result.notice}`, {
388
+ now: true,
389
+ long: true,
390
+ reply: entry.reply,
391
+ tag: "delivery",
392
+ });
393
+ }
394
+ }
395
+ const left = current.filter((entry) => !ended.includes(entry));
396
+ if (left.length) waiting.set(agentId, left);
397
+ else {
398
+ engine.working(agentId, false);
399
+ waiting.delete(agentId);
276
400
  }
277
- engine.working(agentId, false);
278
- waiting.delete(agentId);
279
401
  }
280
402
 
281
- function prompt(member: ChatMember, text: string, reply: Waiting["reply"]): void {
282
- const entry: Waiting = { member, reply };
403
+ function prompt(
404
+ member: ChatMember,
405
+ text: string,
406
+ reply: Waiting["reply"],
407
+ images?: ChatImage[],
408
+ tryNext?: () => void,
409
+ ): void {
410
+ const delivery = {
411
+ messageId: `office-chat-${reply.id}`,
412
+ sentAt: clock.now(),
413
+ group: !!tryNext,
414
+ };
415
+ const entry: Waiting = { member, reply, delivery };
283
416
  waiting.set(member.id, [...(waiting.get(member.id) ?? []), entry]);
284
417
  engine.working(member.id, true);
285
- ports.send(member.id, PROMPT_PREFIX + text).catch((error: unknown) => {
286
- release(member.id, [entry]);
287
- engine.system(`Could not reach ${member.name}: ${errorMessage(error)}.`);
418
+ ports.send(member.id, text, images, delivery).catch((error: unknown) => {
419
+ if (tryNext && error instanceof GroupSessionUnavailable) {
420
+ if (!waiting.get(member.id)?.includes(entry)) return;
421
+ finish(member.id, [entry], null);
422
+ tryNext();
423
+ return;
424
+ }
425
+ finish(member.id, [entry], { notice: `Message delivery failed: ${errorMessage(error)}.` });
288
426
  });
289
427
  }
290
428
 
291
- function send(input: Extract<ChatRequest, { op: "send" }>): ChatResult {
292
- const text = (input.text ?? "").trim().slice(0, CHAT_TEXT_MAX);
293
- const sticker = input.sticker ?? null;
294
- if (text === "" && sticker === null) return { ok: false, error: "There is nothing to send." };
295
- if (sticker !== null && tr("chat.stickers", null, "list")[sticker] === undefined) {
296
- return { ok: false, error: "There is no such sticker." };
297
- }
298
- const team = members();
299
- const targets = mentionedIds(text, team).flatMap(
300
- (id) => team.find((member) => member.id === id) ?? [],
301
- );
429
+ function postMessage(
430
+ input: Extract<ChatRequest, { op: "send" }>,
431
+ text: string,
432
+ sticker: number | null,
433
+ imageLabel: string,
434
+ mode: "social" | "group" | "direct",
435
+ ) {
302
436
  const captured: EngineMessage[] = [];
303
437
  capture = captured;
304
438
  try {
305
- engine.send({ text, sticker, replyTo: input.replyTo ?? null });
439
+ if (mode !== "social") {
440
+ // A directed turn gets the session's actual answer. The engine's group send also
441
+ // schedules simulated replies and interprets words like "meeting" as a scene action.
442
+ const original = input.replyTo && engine.byId(input.replyTo);
443
+ const reply =
444
+ original && !original.recalled
445
+ ? {
446
+ id: original.id,
447
+ name: original.name ?? tr("chat.you"),
448
+ text: short(
449
+ original.text ||
450
+ original.poll?.q ||
451
+ tr(original.kind === "photo" ? "chat.photo" : "chat.sticker"),
452
+ 90,
453
+ ),
454
+ }
455
+ : null;
456
+ const posted = imageLabel && input.text?.trim() ? `${text}\n(${imageLabel})` : text;
457
+ engine.say("me", posted, {
458
+ now: true,
459
+ sticker,
460
+ reply,
461
+ tag: mode === "group" ? "group" : undefined,
462
+ });
463
+ } else {
464
+ engine.send({ text, sticker, replyTo: input.replyTo ?? null });
465
+ }
306
466
  } finally {
307
467
  capture = null;
308
468
  }
309
- const mine = captured.find((message) => message.from === "me");
310
- if (mine === undefined) return OK;
311
- const quote = { id: mine.id, name: tr("chat.boss"), text: short(text, 90) };
469
+ return captured.find((message) => message.from === "me");
470
+ }
471
+
472
+ function recipients(
473
+ input: Extract<ChatRequest, { op: "send" }>,
474
+ text: string,
475
+ ): ChatMember[] | null {
476
+ if (input.to !== undefined) {
477
+ const recipient = roster.get(input.to);
478
+ return recipient ? [recipient] : null;
479
+ }
480
+ const team = members();
481
+ const named = mentionedIds(text, team).flatMap(
482
+ (id) => team.find((member) => member.id === id) ?? [],
483
+ );
484
+ if (named.length || !input.replyTo) return named;
485
+ const original = engine.byId(input.replyTo);
486
+ const author = original?.from && !original.recalled ? roster.get(original.from) : undefined;
487
+ return author ? [author] : [];
488
+ }
489
+
490
+ function directorReply(
491
+ text: string,
492
+ quote: Waiting["reply"],
493
+ tag?: "group-reply" | "delivery",
494
+ ): void {
495
+ engine.say(DIRECTOR, text, { now: true, long: true, reply: quote, tag });
496
+ }
497
+
498
+ function answerGroup(
499
+ text: string,
500
+ quote: Waiting["reply"],
501
+ addressed: boolean,
502
+ replyTo?: string,
503
+ ): void {
504
+ const toDirector =
505
+ /^@director\b/i.test(text) || (replyTo && engine.byId(replyTo)?.from === DIRECTOR);
506
+ if (addressed && !toDirector) {
507
+ directorReply(
508
+ "That recipient is unavailable. Choose a session in To to send it directly.",
509
+ quote,
510
+ "delivery",
511
+ );
512
+ return;
513
+ }
514
+ const answer =
515
+ boardAnswer(text, ports.lobbyPosts) ??
516
+ matchingLobbyTaskAnswer(text, ports.lobbyPosts(), (id) => roster.get(id)?.name);
517
+ if (answer) {
518
+ directorReply(answer, quote, addressed ? undefined : "group-reply");
519
+ return;
520
+ }
521
+ if (addressed) {
522
+ directorReply(
523
+ "I can look up lobby tasks. Send to the whole group or choose a session in To for a conversation.",
524
+ quote,
525
+ "delivery",
526
+ );
527
+ return;
528
+ }
529
+ const candidates = [...availableForGroup];
530
+ const groupPrompt = autoGroupPrompt(text, engine.state.msgs, quote.id);
531
+ function tryNext(): void {
532
+ while (candidates.length) {
533
+ const id = candidates.shift()!;
534
+ const member = roster.get(id);
535
+ if (member && availableForGroup.has(id) && !waiting.has(id)) {
536
+ prompt(member, groupPrompt, quote, undefined, tryNext);
537
+ return;
538
+ }
539
+ }
540
+ directorReply(
541
+ "No session is available to answer the group right now. Choose a session in To to ask it directly.",
542
+ quote,
543
+ "delivery",
544
+ );
545
+ }
546
+ tryNext();
547
+ }
548
+
549
+ function send(input: Extract<ChatRequest, { op: "send" }>): ChatResult {
550
+ const imageLabel = imageCountLabel(input.images);
551
+ if (imageLabel && !input.to) return { ok: false, error: "Choose a session to send images." };
552
+ const text = (input.text ?? "").trim().slice(0, CHAT_TEXT_MAX) || imageLabel;
553
+ const sticker = input.sticker ?? null;
554
+ if (text === "" && sticker === null) return { ok: false, error: "There is nothing to send." };
555
+ if (sticker !== null && tr("chat.stickers", null, "list")[sticker] === undefined) {
556
+ return { ok: false, error: "There is no such sticker." };
557
+ }
558
+ const targets = recipients(input, text);
559
+ if (!targets)
560
+ return { ok: false, error: "That session has left the office. Choose another recipient." };
561
+ const mode = messageMode(text, targets.length > 0, input.replyTo);
562
+ const mine = postMessage(input, text, sticker, imageLabel, mode);
563
+ if (mine === undefined) return { ok: false, error: "The message could not be posted." };
564
+ const words = text || (sticker === null ? "" : tr("chat.stickers", null, "list")[sticker]);
565
+ const quote = { id: mine.id, name: tr("chat.boss"), text: short(words, 90) };
312
566
  // Not awaited: a send that fails is a line in the chat, not an error of this call.
313
- for (const member of targets) prompt(member, text, quote);
567
+ for (const member of targets) prompt(member, PROMPT_PREFIX + words, quote, input.images);
568
+ if (!targets.length && mode !== "social")
569
+ answerGroup(text, quote, mode === "direct", input.replyTo);
314
570
  return OK;
315
571
  }
316
572
 
@@ -342,9 +598,14 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
342
598
  }
343
599
 
344
600
  return {
345
- snapshot: () => ({ messages: wireMessages(), typing: [...engine.state.typing] }),
601
+ snapshot: () => ({
602
+ messages: wireMessages(),
603
+ typing: [...engine.state.typing],
604
+ ...(engine.state.pinned ? { pinned: engine.state.pinned } : {}),
605
+ }),
346
606
 
347
607
  view(next) {
608
+ availableForGroup.clear();
348
609
  if (next === null) {
349
610
  baseline = null;
350
611
  return;
@@ -352,7 +613,19 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
352
613
  const open = next.agents.filter((agent) => agent.status !== "closed");
353
614
  // The roster is set first: the engine looks the agent up for each event.
354
615
  roster.clear();
355
- for (const agent of open) roster.set(agent.id, memberOf(agent, next.workspaces));
616
+ const waitingOn = waitingOnOf(open);
617
+ for (const agent of open) {
618
+ roster.set(agent.id, memberOf(agent, next.workspaces));
619
+ if (
620
+ agent.status === "idle" &&
621
+ !agent.parentAgentId &&
622
+ !agent.permissions.length &&
623
+ !waitingOn.has(agent.id) &&
624
+ agent.title !== NOTES_WRITER_TITLE
625
+ ) {
626
+ availableForGroup.add(agent.id);
627
+ }
628
+ }
356
629
  const previous = baseline;
357
630
  baseline = new Map(
358
631
  open.map((agent) => [agent.id, new Set(agent.permissions.map((item) => item.id))]),
@@ -375,47 +648,101 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
375
648
  },
376
649
 
377
650
  async turnEnded(agent, outcome, turnId) {
378
- if (outcome.kind === "completed") engine.onEvent({ type: "stop", sess: agent.id });
379
- if (outcome.kind === "failed") {
380
- engine.onEvent({
381
- type: "fail",
382
- sess: agent.id,
383
- limit: isUsageLimit(outcome.error.message),
384
- });
651
+ if (stopped) return;
652
+ const consumed = waiting.get(agent.id);
653
+ if (!consumed) {
654
+ if (outcome.kind === "completed") engine.onEvent({ type: "stop", sess: agent.id });
655
+ if (outcome.kind === "failed") {
656
+ engine.onEvent({
657
+ type: "fail",
658
+ sess: agent.id,
659
+ limit: isUsageLimit(outcome.error.message),
660
+ });
661
+ }
662
+ return;
385
663
  }
386
- // This turn answers the prompts sent before it ended; one sent during the read waits on.
387
- const consumed = waiting.get(agent.id) ?? [];
388
- const newest = consumed.at(-1);
389
- if (newest === undefined) return;
390
- try {
391
- if (outcome.kind === "completed") {
392
- const text = await ports.lastAnswer(agent.id, turnId);
393
- if (text !== null) {
394
- engine.say(agent.id, clipAnswer(text), { now: true, long: true, reply: newest.reply });
664
+ // An earlier turn's hook can arrive after a group responder was reserved. Only the
665
+ // turn containing the group's SDK message id may answer or settle its wait.
666
+ const groupEntry = consumed.find((entry) => entry.delivery.group);
667
+ let text: string | null = null;
668
+ if (outcome.kind === "completed" || groupEntry) {
669
+ try {
670
+ const turn = await ports.readTurn(
671
+ agent.id,
672
+ turnId,
673
+ groupEntry?.delivery,
674
+ consumed.map((entry) => entry.delivery.messageId),
675
+ );
676
+ if (!turn.matches) return;
677
+ if (turn.privateTurn && outcome.kind === "completed") {
678
+ finish(agent.id, consumed, {
679
+ notice: "This turn also included a workspace message. Read the reply in the session.",
680
+ });
681
+ return;
395
682
  }
683
+ text = turn.text;
684
+ } catch (error) {
685
+ finish(agent.id, consumed, { notice: "Office could not read the session’s reply." });
686
+ log(`[office] chat could not read the answer of ${agent.id}: ${errorMessage(error)}`);
687
+ return;
396
688
  }
397
- } catch (error) {
398
- log(`[office] chat could not read the answer of ${agent.id}: ${errorMessage(error)}`);
399
- } finally {
400
- release(agent.id, consumed);
401
689
  }
690
+ if (outcome.kind === "canceled") {
691
+ finish(agent.id, consumed, {
692
+ notice: "The turn was canceled before a reply was available.",
693
+ });
694
+ return;
695
+ }
696
+ if (outcome.kind === "failed") {
697
+ const message = isUsageLimit(outcome.error.message)
698
+ ? "The provider reached its usage limit before the session could reply."
699
+ : "The session failed before it could reply. Open the session for details.";
700
+ finish(agent.id, consumed, { notice: message });
701
+ return;
702
+ }
703
+ finish(
704
+ agent.id,
705
+ consumed,
706
+ text === null ? { notice: "The turn ended without a text reply." } : { answer: text },
707
+ );
402
708
  },
403
709
 
404
710
  archived(agentId) {
711
+ availableForGroup.delete(agentId);
405
712
  const entries = waiting.get(agentId);
406
- if (entries !== undefined) release(agentId, entries);
407
713
  const member = roster.get(agentId) ?? entries?.[0]?.member;
714
+ if (entries)
715
+ finish(agentId, entries, {
716
+ notice: "The session was archived before a reply was available.",
717
+ });
408
718
  roster.delete(agentId);
409
719
  if (member !== undefined) engine.onLeft(member.name);
410
720
  },
411
721
 
412
722
  closed(agentId) {
723
+ availableForGroup.delete(agentId);
413
724
  const entries = waiting.get(agentId);
414
- if (entries !== undefined) release(agentId, entries);
725
+ if (entries)
726
+ finish(agentId, entries, { notice: "The session closed before a reply was available." });
415
727
  },
416
728
 
417
729
  async request(input) {
418
730
  switch (input.op) {
731
+ case "photo": {
732
+ if (!isOfficePhoto(input.data))
733
+ return { ok: false, error: "The office photo is not a valid 480 × 360 JPEG." };
734
+ if (!engine.fresh(`office-photo:${input.requestId}`)) return OK;
735
+ const pictures = engine.state.msgs.filter((message) => message.photo);
736
+ for (const old of pictures.slice(
737
+ 0,
738
+ Math.max(0, pictures.length + 1 - GROUP_PHOTO_COUNT),
739
+ )) {
740
+ old.photo = null;
741
+ emit("update", old);
742
+ }
743
+ engine.photo(input.data);
744
+ return OK;
745
+ }
419
746
  case "life":
420
747
  return life(input);
421
748
  case "send":
@@ -426,6 +753,16 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
426
753
  case "vote":
427
754
  engine.vote(input.id, "me", input.index);
428
755
  return OK;
756
+ case "poll":
757
+ engine.poll("me", input.question, input.options);
758
+ return OK;
759
+ case "pin": {
760
+ const message = engine.byId(input.id);
761
+ if (!message || message.recalled || message.kind === "sys")
762
+ return { ok: false, error: "This message cannot be pinned." };
763
+ if (engine.state.pinned !== input.id) engine.pin(input.id, tr("chat.boss"));
764
+ return OK;
765
+ }
429
766
  case "rsvp":
430
767
  engine.rsvp(input.id, "me", input.yes);
431
768
  return OK;
@@ -436,6 +773,13 @@ export async function createChatService(ports: ChatServicePorts): Promise<ChatSe
436
773
 
437
774
  async stop() {
438
775
  stopped = true;
776
+ // The session may carry on, but this process can no longer forward its reply. Store the
777
+ // notice with the original message, so a client that reconnects can still see it.
778
+ for (const [id, entries] of waiting) {
779
+ finish(id, entries, {
780
+ notice: "Office stopped while waiting for a reply. Check the session for its answer.",
781
+ });
782
+ }
439
783
  live = false;
440
784
  cancelClock?.();
441
785
  for (const cancel of timers) cancel();
@@ -4,10 +4,7 @@ import { z } from "zod";
4
4
  import { ChatMessageSchema, type ChatMessage } from "../shared/contracts.js";
5
5
  import { errorMessage } from "./errors.js";
6
6
 
7
- /**
8
- * The file upstream's engine saves. zod drops the keys it does not know, so a photo's picture and
9
- * a work card's body do not come back on load.
10
- */
7
+ /** The upstream engine keeps the newest six group photos with the conversation. */
11
8
  export const ChatFileSchema = z.object({
12
9
  v: z.literal(1),
13
10
  msgs: z.array(ChatMessageSchema),