ocean-crew 0.0.0-stage → 0.4.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 (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/THIRD_PARTY_NOTICES.md +159 -0
  4. package/client.js +31389 -0
  5. package/cordis.patch.yml +6 -0
  6. package/dist/host/chat/btw.js +436 -0
  7. package/dist/host/chat/channel.js +1241 -0
  8. package/dist/host/chat/chat-index.js +344 -0
  9. package/dist/host/chat/delivery.js +231 -0
  10. package/dist/host/chat/feed.js +165 -0
  11. package/dist/host/chat/handoffs.js +625 -0
  12. package/dist/host/chat/parts.js +2033 -0
  13. package/dist/host/chat/requests.js +155 -0
  14. package/dist/host/chat/resume.js +364 -0
  15. package/dist/host/chat/side.js +457 -0
  16. package/dist/host/chat/steer.js +346 -0
  17. package/dist/host/chat/turns.js +1457 -0
  18. package/dist/host/connectors/catalog.js +331 -0
  19. package/dist/host/connectors/gateway.js +339 -0
  20. package/dist/host/connectors/index.js +1235 -0
  21. package/dist/host/connectors/mail/index.js +912 -0
  22. package/dist/host/connectors/mail/presets.js +53 -0
  23. package/dist/host/connectors/mail/transport.js +519 -0
  24. package/dist/host/connectors/oauth.js +337 -0
  25. package/dist/host/core/constants.js +123 -0
  26. package/dist/host/core/diagnostics.js +310 -0
  27. package/dist/host/core/dsh-update.js +212 -0
  28. package/dist/host/core/events.js +16 -0
  29. package/dist/host/core/files.js +37 -0
  30. package/dist/host/core/folders.js +283 -0
  31. package/dist/host/core/home-lock.js +137 -0
  32. package/dist/host/core/links.js +52 -0
  33. package/dist/host/core/runtime.js +5 -0
  34. package/dist/host/core/store.js +662 -0
  35. package/dist/host/core/text.js +59 -0
  36. package/dist/host/core/thinking.js +60 -0
  37. package/dist/host/core/time-context.js +69 -0
  38. package/dist/host/core/update.js +466 -0
  39. package/dist/host/groups/calls.js +684 -0
  40. package/dist/host/groups/index.js +79 -0
  41. package/dist/host/groups/log.js +334 -0
  42. package/dist/host/groups/prompt.js +124 -0
  43. package/dist/host/groups/relay.js +489 -0
  44. package/dist/host/groups/round.js +992 -0
  45. package/dist/host/groups/tasks.js +217 -0
  46. package/dist/host/groups/tools.js +478 -0
  47. package/dist/host/groups/types.js +8 -0
  48. package/dist/host/im/format.js +228 -0
  49. package/dist/host/im/index.js +2461 -0
  50. package/dist/host/im/platforms/feishu.js +1134 -0
  51. package/dist/host/im/platforms/index.js +6 -0
  52. package/dist/host/im/platforms/media-type.js +70 -0
  53. package/dist/host/im/platforms/weixin.js +1117 -0
  54. package/dist/host/im/reaction.js +51 -0
  55. package/dist/host/im/supervisor.js +56 -0
  56. package/dist/host/team/agents.js +161 -0
  57. package/dist/host/team/models.js +427 -0
  58. package/dist/host/team/permissions.js +263 -0
  59. package/dist/host/team/privacy.js +108 -0
  60. package/dist/host/team/prompt.js +86 -0
  61. package/dist/host/team/providers.js +461 -0
  62. package/dist/host/team/roster.js +1011 -0
  63. package/dist/host/team/tools.js +1638 -0
  64. package/dist/host/work/approvals.js +290 -0
  65. package/dist/host/work/avatar-library.js +155 -0
  66. package/dist/host/work/avatar.js +132 -0
  67. package/dist/host/work/capabilities.js +862 -0
  68. package/dist/host/work/companion.js +306 -0
  69. package/dist/host/work/goal-skills.js +91 -0
  70. package/dist/host/work/goals.js +1337 -0
  71. package/dist/host/work/images.js +283 -0
  72. package/dist/host/work/learning.js +1021 -0
  73. package/dist/host/work/memory-pending.js +108 -0
  74. package/dist/host/work/memory.js +3237 -0
  75. package/dist/host/work/notify.js +146 -0
  76. package/dist/host/work/reset.js +43 -0
  77. package/dist/host/work/schedules.js +309 -0
  78. package/dist/host/work/secrets.js +702 -0
  79. package/dist/host/work/steward.js +166 -0
  80. package/dist/host/work/tts.js +192 -0
  81. package/dist/host/work/usage.js +84 -0
  82. package/dist/index.js +137 -0
  83. package/dist/shared/api.js +32 -0
  84. package/dist/shared/companion.js +110 -0
  85. package/dist/shared/config.js +3 -0
  86. package/dist/shared/coordination.js +6 -0
  87. package/dist/shared/group-replies.js +95 -0
  88. package/dist/shared/im-platforms.js +35 -0
  89. package/dist/shared/im.js +3 -0
  90. package/dist/shared/mentions.js +85 -0
  91. package/dist/shared/state.js +25 -0
  92. package/package.json +81 -5
@@ -0,0 +1,1011 @@
1
+ // Roster: creating, changing, and deleting Bots and group chats, the Main Bot role, and
2
+ // the first Main Bot of a new team.
3
+ //
4
+ // names. The slices it calls (models, permissions, privacy, folders, delivery, parts,
5
+ // memory) may be installed after it, or absent from a minimal runtime: each one has a
6
+ // documented fallback below, never a second implementation of the slice.
7
+ import { mkdir, stat } from "node:fs/promises";
8
+ import { join } from "node:path";
9
+ import { nameProblem } from "../../shared/mentions.js";
10
+ import { MAX_AVATAR_IMAGE, ROOM_MAX_MEMBERS, ROOM_MODES, ROOM_NAME_MAX, ROOM_NOTICE_MAX } from "../core/constants.js";
11
+ import { currentColor, isColor, normalize, unquote } from "../core/text.js";
12
+ const HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*$/;
13
+ const AVATAR_IMAGE = /^data:image\/(png|jpeg|webp|gif|svg\+xml);base64,[A-Za-z0-9+/=]+$/;
14
+ const OWN_RULES = "Where your instructions say otherwise, follow them.";
15
+ const writeIn = (language) => `Write in ${language ?? "the user's language if known; otherwise Chinese"}.`;
16
+ // The first Main Bot's greeting when the user wrote before it had a model that works.
17
+ const AFTER_USER = "You were just set up as the user's Main Bot. The user wrote to you before your model could answer; their message above has no answer yet. Answer it now, and say in one short sentence that you run their Bot team.";
18
+ /** Installs the roster and publishes its members on `rt`. */
19
+ export function install(rt) {
20
+ const { ctx } = rt;
21
+ const state = rt.state;
22
+ const { warn } = rt;
23
+ const workspaces = (ctx.workspaceRegistry ?? {});
24
+ const sessions = (ctx.sessionController ?? {});
25
+ const sessionTitle = ctx.sessionTitle;
26
+ let bootstrapping = null;
27
+ // A function another slice publishes on `rt`, or the fallback used while that slice
28
+ // is absent.
29
+ // several slices (folders, privacy, resume, groups) install after roster, and their
30
+ // functions must be picked up once they exist. The fallbacks are the smallest
31
+ // behaviour that leaves the roster's own promises intact; they never reimplement them.
32
+ const dependency = (name, fallback) => ((...args) => {
33
+ const live = rt[name];
34
+ return typeof live === "function" ? live(...args) : fallback(...args);
35
+ });
36
+ // `deliver` is the one fallback that must not be silent: a greeting with nowhere to
37
+ // go is a host installed without the delivery slice, which is a configuration fault.
38
+ let deliveryMissing = false;
39
+ const deliver = dependency("deliver", async () => {
40
+ if (deliveryMissing)
41
+ return;
42
+ deliveryMissing = true;
43
+ warn("ocean-crew: delivery is not installed, so a greeting was not sent");
44
+ });
45
+ const teamFolder = dependency("teamFolder", () => workspaces.get?.(state.workspaceId)?.path);
46
+ const defaultTeamFolder = dependency("defaultTeamFolder", () => rt.config.workspace ?? join(rt.home, "workspace"));
47
+ const isFolder = dependency("isFolder", async (path) => {
48
+ try {
49
+ return (await stat(path)).isDirectory();
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ });
55
+ const resolveModel = dependency("resolveModel", async (text) => String(text ?? "").trim());
56
+ const defaultBotModel = dependency("defaultBotModel", async () => undefined);
57
+ const resolveEffort = dependency("resolveEffort", async (_ref, text) => {
58
+ const wanted = String(text ?? "").trim();
59
+ return wanted === "" ? undefined : wanted;
60
+ });
61
+ const defaultEffort = dependency("defaultEffort", async () => undefined);
62
+ const cleanWorkDir = dependency("cleanWorkDir", async (input) => {
63
+ const text = String(input ?? "").trim();
64
+ return text === "" ? undefined : text;
65
+ });
66
+ const privateClash = dependency("privateClash", async () => undefined);
67
+ const applyModel = dependency("applyModel", async () => undefined);
68
+ const waitForModel = dependency("waitForModel", async (bot) => bot.model);
69
+ const catalog = dependency("catalog", async () => []);
70
+ const isUsable = dependency("isUsable", (ref) => ref !== undefined);
71
+ const unreadOf = dependency("unreadOf", () => []);
72
+ const archiveBotMemory = dependency("archiveBotMemory", async () => undefined);
73
+ const archiveGroupMemory = dependency("archiveGroupMemory", async () => undefined);
74
+ const releaseBot = dependency("releaseBot", async () => undefined);
75
+ const forgetBotSecrets = dependency("forgetBotSecrets", async () => undefined);
76
+ const dropGroupLines = dependency("dropGroupLines", () => undefined);
77
+ const setPermission = dependency("setPermission", async () => {
78
+ throw new Error("Permissions are not available in this DeepSeek Harness");
79
+ });
80
+ // `null` means each member uses its own preset; a name is a group-wide one.
81
+ const cleanRoomPermission = dependency("cleanRoomPermission", (name) => name === null || name === "" ? null : String(name ?? "").trim() || null);
82
+ const setRoomPermission = dependency("setRoomPermission", async (room, name) => {
83
+ const wanted = name ?? undefined;
84
+ if (wanted === room.permission)
85
+ return false;
86
+ if (wanted === undefined)
87
+ delete room.permission;
88
+ else
89
+ room.permission = wanted;
90
+ return true;
91
+ });
92
+ const checkNoPrivate = dependency("checkNoPrivate", (ids) => {
93
+ const found = ids.map((id) => rt.botOf(id)).find((bot) => bot?.private === true);
94
+ if (found !== undefined)
95
+ throw new Error(`${found.name} is a private Bot and cannot be in a group chat: what is said in a group is read by every member`);
96
+ });
97
+ const checkPrivacyChange = dependency("checkPrivacyChange", async (bot, change) => {
98
+ const makes = change.flag === undefined ? bot.private === true : change.flag;
99
+ const dir = change.moving ? change.workDir : bot.workDir;
100
+ if (!makes) {
101
+ const clash = change.moving && dir !== undefined ? await privateClash(dir) : undefined;
102
+ if (clash)
103
+ throw new Error(`${dir} is in or around the folder of ${clash.name}, a private Bot, so ${bot.name} cannot work there`);
104
+ return;
105
+ }
106
+ if (rt.isMain(bot.id))
107
+ throw new Error(`${bot.name} is a Main Bot, so it cannot be private`);
108
+ if (dir === undefined)
109
+ throw new Error(`${bot.name} needs a folder of its own to be private`);
110
+ if (Object.values(state.rooms).some((room) => room.members.includes(bot.id)))
111
+ throw new Error(`${bot.name} is in a group chat, where every member reads what is said. Remove it from its groups first`);
112
+ const clash = await privateClash(dir);
113
+ if (clash)
114
+ throw new Error(`${dir} is in or around the folder of ${clash.name}, a private Bot, so ${bot.name} cannot work there`);
115
+ });
116
+ // The Session a Bot or group speaks from, resolved through delivery.ts or, before
117
+ // that slice lands, through the DSH controller itself.
118
+ const resolveAgent = async (sessionId) => {
119
+ if (typeof rt.resolveAgent === "function")
120
+ return rt.resolveAgent(sessionId);
121
+ const resolved = (await sessions.resolveAgent?.(sessionId));
122
+ if (resolved !== undefined && resolved !== null && resolved.error !== undefined)
123
+ throw Object.assign(new Error(resolved.error.message ?? "Session unavailable"), { code: resolved.error.code });
124
+ return (resolved?.agent ?? {});
125
+ };
126
+ const archive = (sessionId, options) => sessionId === undefined ? Promise.resolve() : Promise.resolve(workspaces.archiveSession?.(sessionId, options));
127
+ const kickoffOf = (bot) => bot?.kickoff;
128
+ function cleanAvatar(input) {
129
+ if (input === null || typeof input !== "object")
130
+ return undefined;
131
+ const source = input;
132
+ const avatar = {};
133
+ if (typeof source.shape === "string" && /^[a-z][\w-]{0,31}$/.test(source.shape))
134
+ avatar.shape = source.shape;
135
+ if (typeof source.image === "string") {
136
+ if (!AVATAR_IMAGE.test(source.image))
137
+ throw new Error("Avatar images must be PNG, JPEG, WebP, GIF, or SVG");
138
+ if (source.image.length > MAX_AVATAR_IMAGE)
139
+ throw new Error("Avatar image is too large");
140
+ avatar.image = source.image;
141
+ }
142
+ return Object.keys(avatar).length > 0 ? avatar : undefined;
143
+ }
144
+ // The team folder is Ocean Crew's own: deleted, it is made again before a Session needs it.
145
+ async function keepTeamFolder() {
146
+ const team = teamFolder();
147
+ if (team !== undefined)
148
+ await mkdir(team, { recursive: true }).catch((error) => warn("ocean-crew: team folder %s not made again: %s", team, error));
149
+ return team;
150
+ }
151
+ async function ensureWorkspace() {
152
+ if (state.workspaceId !== undefined && workspaces.get?.(state.workspaceId) !== undefined) {
153
+ await keepTeamFolder();
154
+ return state.workspaceId;
155
+ }
156
+ const path = defaultTeamFolder();
157
+ await mkdir(path, { recursive: true });
158
+ const workspace = (await workspaces.resolveByPath?.(path)) ?? (await workspaces.create?.(path, "Ocean Crew"));
159
+ if (workspace === undefined || workspace.id === undefined)
160
+ throw new Error("DeepSeek Harness could not register the team folder as a workspace");
161
+ state.workspaceId = workspace.id;
162
+ await rt.save();
163
+ return workspace.id;
164
+ }
165
+ // Under the PTC preset (DSH Desktop's default) a model may call only run_code, which
166
+ // turns down the group_relay call that a group chat's Session is given. A Session
167
+ // keeps the preset it is made with.
168
+ async function botPreset() {
169
+ const presets = ctx.get("agentPresets");
170
+ if (presets === undefined)
171
+ return {};
172
+ const standard = ((await presets.list?.()) ?? []).some((preset) => preset.id === "standard" && preset.broken === undefined);
173
+ return standard ? { agentPreset: "standard" } : {};
174
+ }
175
+ // `dir` is a working folder outside the team workspace. Such a Session is made by cwd
176
+ // alone, so it joins no DSH workspace and the user's own project lists stay as they are —
177
+ // unless the folder is already registered as a workspace, which it then joins (#710).
178
+ async function createSession(title, { dir } = {}) {
179
+ // A Bot's tools run here too; while another dsh holds the team, a new Session would
180
+ // belong to no saved Bot.
181
+ const readOnly = rt.readOnly();
182
+ if (readOnly !== undefined)
183
+ throw new Error(readOnly);
184
+ const usable = dir !== undefined && (await isFolder(dir));
185
+ if (dir !== undefined && !usable)
186
+ warn("ocean-crew: the working folder %s is gone; %s starts in the team workspace", dir, title);
187
+ const known = usable ? await workspaces.resolveByPath?.(dir) : undefined;
188
+ let place;
189
+ if (known !== undefined)
190
+ place = { workspaceId: known.id };
191
+ else if (dir !== undefined && usable)
192
+ place = { cwd: dir };
193
+ else
194
+ place = { workspaceId: await ensureWorkspace() };
195
+ if (typeof sessions.create !== "function")
196
+ throw new Error("DeepSeek Harness did not provide a session controller");
197
+ const { sessionId } = await sessions.create({ ...place, ...(await botPreset()) });
198
+ const agent = await resolveAgent(sessionId);
199
+ await sessionTitle?.rename?.(agent.session, title);
200
+ return sessionId;
201
+ }
202
+ // A new Bot or group is written only after its Session is made, several awaits after
203
+ // its name was checked. The name is held from the check until the create ends, so a
204
+ // create or rename that runs meanwhile cannot take it too.
205
+ const held = { bot: new Set(), room: new Set() };
206
+ const isHeld = (kind, name) => held[kind].has(normalize(name));
207
+ async function holdName(kind, name, work) {
208
+ const key = normalize(name);
209
+ if (key === "")
210
+ return work();
211
+ held[kind].add(key);
212
+ try {
213
+ return await work();
214
+ }
215
+ finally {
216
+ held[kind].delete(key);
217
+ }
218
+ }
219
+ const botNameTaken = (name) => rt.findBot(name) !== undefined || isHeld("bot", name);
220
+ const freshName = (base) => {
221
+ const stem = base.slice(0, 34);
222
+ if (!botNameTaken(stem))
223
+ return stem;
224
+ let index = 2;
225
+ while (botNameTaken(`${stem} ${index}`))
226
+ index += 1;
227
+ return `${stem} ${index}`;
228
+ };
229
+ // `pickModel` leaves the model to the user: the chat opens on a model card, and the
230
+ // greeting waits until a model is chosen. So does a Bot made when no model it can
231
+ // run on is served.
232
+ async function createBot(options) {
233
+ const cleanName = String(options.name ?? "")
234
+ .trim()
235
+ .slice(0, 40);
236
+ const problem = nameProblem(cleanName);
237
+ if (problem !== undefined)
238
+ throw new Error(problem);
239
+ if (botNameTaken(cleanName))
240
+ throw new Error(`A Bot named ${cleanName} already exists`);
241
+ return holdName("bot", cleanName, () => buildBot(cleanName, options));
242
+ }
243
+ async function buildBot(cleanName, options) {
244
+ const { role = "", instructions = "", color, brief = "", createdBy, main = false, avatar, model, effort, workDir, copyOf, pickModel = false, } = options;
245
+ const cleanAvatarValue = cleanAvatar(avatar);
246
+ // The model is fixed at creation, so a later change of the DSH default leaves it alone.
247
+ const modelRef = model ? await resolveModel(model) : pickModel ? undefined : await defaultBotModel();
248
+ // A thinking level needs a model to resolve against; with none it would be dropped
249
+ // silently, so the create fails before a Session is made.
250
+ if (effort && modelRef === undefined)
251
+ throw new Error("Pick a model before choosing a thinking level");
252
+ // An explicit level wins; an explicit Default (null) picks the model's own level; an
253
+ // untouched pick inherits the profile default's level.
254
+ const effortId = modelRef === undefined
255
+ ? undefined
256
+ : effort === null || effort === ""
257
+ ? undefined
258
+ : ((await resolveEffort(modelRef, effort)) ?? (await defaultEffort(modelRef)));
259
+ const dir = workDir === undefined || workDir === null ? undefined : await cleanWorkDir(workDir);
260
+ const clash = dir === undefined ? undefined : await privateClash(dir);
261
+ if (clash)
262
+ throw new Error(`${dir} is in or around the folder of ${clash.name}, a private Bot, so ${cleanName} cannot work there`);
263
+ const id = await createSession(cleanName, dir === undefined ? {} : { dir });
264
+ try {
265
+ const picked = currentColor(typeof color === "string" ? color : undefined);
266
+ state.bots[id] = {
267
+ id,
268
+ name: cleanName,
269
+ role: String(role).trim().slice(0, 24),
270
+ // A color is only stored when the user picks one; otherwise the id picks it.
271
+ ...(isColor(picked) ? { color: picked } : {}),
272
+ ...(cleanAvatarValue ? { avatar: cleanAvatarValue } : {}),
273
+ ...(modelRef ? { model: modelRef } : {}),
274
+ ...(effortId ? { effort: effortId } : {}),
275
+ ...(dir ? { workDir: dir } : {}),
276
+ instructions: String(instructions).trim(),
277
+ createdAt: Date.now(),
278
+ createdBy: createdBy ?? null,
279
+ capabilities: [],
280
+ };
281
+ if (main)
282
+ state.mainBotIds.push(id);
283
+ const creator = rt.botOf(createdBy);
284
+ const original = rt.botOf(copyOf);
285
+ const language = rt.uiLanguage?.();
286
+ // The kickoff arrives as a user message, so it outranks the Bot's instructions
287
+ // unless it gives way to them, and it names no tool those instructions may rule out.
288
+ const kickoff = main
289
+ ? `You were just set up as the user's Main Bot. Greet the user in one or two short messages: say you will run their Bot team and that they can come to you for anything that needs a decision. Then ask in one short question what they want the team to help with first. ${writeIn(language)}`
290
+ : original
291
+ ? `The user just made you as a copy of ${original.name}: same job, fresh memory. Greet the user in one short message, then ask in one short question what this copy should focus on.`
292
+ : creator
293
+ ? `${creator.name} just created you for the user.${brief ? ` Why you exist: ${brief}` : ""}\nGreet the user in one short message, then ask in one short question where to start. Keep it brief.`
294
+ : brief
295
+ ? `The user just created you and sent this first message:\n\n${brief}\n\nIntroduce yourself in one short line, then help with it.`
296
+ : "The user just created you. Greet the user in one short message, then ask in one short question what you should focus on.";
297
+ const opener = `${kickoff}\n${OWN_RULES}`;
298
+ const text = !main && language ? `${opener}\nWrite in ${language}.` : opener;
299
+ const bot = state.bots[id];
300
+ const greeting = { text, from: createdBy ?? null, ...(main ? { main: true } : {}) };
301
+ // The Bot is saved by now; a failure here must not archive it in the catch below.
302
+ const scopeTools = () => resolveAgent(id).catch((error) => warn("ocean-crew: scoped tools for %s not applied: %s", cleanName, error));
303
+ if (modelRef === undefined) {
304
+ bot.kickoff = greeting;
305
+ await rt.save();
306
+ // The Session was resolved before the Bot existed, so its scoped tools land now.
307
+ await scopeTools();
308
+ return bot;
309
+ }
310
+ await rt.save();
311
+ await scopeTools();
312
+ // The greeting runs on the Bot's own model, once its provider is registered.
313
+ void waitForModel(bot)
314
+ .then(() => applyModel(bot).catch((error) => warn("ocean-crew: model for %s not applied: %s", cleanName, error)))
315
+ .then(() => sendKickoff(bot, greeting));
316
+ return bot;
317
+ }
318
+ catch (error) {
319
+ // The Bot's Session was already made: archive it instead of leaving an orphan.
320
+ delete state.bots[id];
321
+ state.mainBotIds = state.mainBotIds.filter((other) => other !== id);
322
+ rt.chatOwners.delete(id);
323
+ // A save that another change queued meanwhile still carries this Bot; a later one
324
+ // writes the team without it.
325
+ void rt.save().catch(() => undefined);
326
+ await archive(id).catch((archiveError) => warn("ocean-crew: archiving the Session for %s failed: %s", cleanName, archiveError));
327
+ throw error;
328
+ }
329
+ }
330
+ // Greetings sent, by Bot: one whose turn a key, a sign-in or a balance stops is held
331
+ // again (turns.ts), to go out once the user has fixed that.
332
+ const sentKickoffs = new Map();
333
+ function sendKickoff(bot, greeting) {
334
+ sentKickoffs.set(bot.id, greeting);
335
+ const text = greeting.afterUser
336
+ ? `${AFTER_USER} ${writeIn(rt.uiLanguage?.())}\n${OWN_RULES}`
337
+ : greeting.text;
338
+ void deliver({ fromId: greeting.from ?? undefined, toId: bot.id, text, role: "kickoff" }).catch((error) => warn("ocean-crew: kickoff failed: %s", error));
339
+ }
340
+ // A held greeting goes out once its Bot has a model, on that model once its provider
341
+ // is registered. False while the Bot has none.
342
+ const releasing = new Set();
343
+ async function releaseKickoff(bot) {
344
+ const greeting = kickoffOf(bot);
345
+ if (greeting === undefined || !bot.model)
346
+ return false;
347
+ delete bot.kickoff;
348
+ releasing.add(bot.id);
349
+ await rt.save().catch((error) => {
350
+ releasing.delete(bot.id);
351
+ throw error;
352
+ });
353
+ const send = () => {
354
+ releasing.delete(bot.id);
355
+ sendKickoff(bot, greeting);
356
+ };
357
+ void waitForModel(bot).then(send, send);
358
+ return true;
359
+ }
360
+ // A greeting on its way to a Bot: released and waiting for its model, or sent to its
361
+ // chat and not yet taken up by a turn there (resume.ts notes what no turn took up).
362
+ function greetingOut(botId) {
363
+ if (releasing.has(botId))
364
+ return true;
365
+ return unreadOf(rt.chatOf(botId)).some((args) => args?.role === "kickoff");
366
+ }
367
+ function holdKickoffAgain(botId) {
368
+ const bot = rt.botOf(botId);
369
+ const greeting = sentKickoffs.get(botId);
370
+ sentKickoffs.delete(botId);
371
+ if (bot === undefined || greeting === undefined || bot.kickoff !== undefined)
372
+ return;
373
+ // "You are the Main Bot" must not go out after a demotion.
374
+ if (greeting.main && !rt.isMain(botId))
375
+ return;
376
+ bot.kickoff = greeting;
377
+ void rt.save().catch(() => undefined);
378
+ }
379
+ // The user wrote in a Bot's own chat, so a held greeting would only interrupt. The
380
+ // first Main Bot's stays while that Bot has no model it can run on, and a Bot that a
381
+ // key, a sign-in or a balance blocks has none: once it has one, it answers the message
382
+ // first, unless a turn answered it meanwhile (userAnswered). Read from the catalog as
383
+ // last listed, so it is marked before that turn can end.
384
+ function userWrote(botId) {
385
+ const bot = rt.botOf(botId);
386
+ const greeting = kickoffOf(bot);
387
+ if (bot === undefined || greeting === undefined || greeting.afterUser)
388
+ return;
389
+ if (greeting.main && (bot.blocked !== undefined || !isUsable(bot.model)))
390
+ greeting.afterUser = true;
391
+ else
392
+ delete bot.kickoff;
393
+ void rt.save().catch(() => undefined);
394
+ }
395
+ // A turn that answered the user in a Bot's own chat leaves nothing for a greeting held
396
+ // for that message to answer.
397
+ function userAnswered(botId) {
398
+ const bot = rt.botOf(botId);
399
+ if (bot?.kickoff?.afterUser !== true)
400
+ return;
401
+ delete bot?.kickoff;
402
+ void rt.save().catch(() => undefined);
403
+ }
404
+ async function duplicateBot(id) {
405
+ const bot = rt.botOf(id);
406
+ if (bot === undefined)
407
+ throw new Error("Unknown Bot");
408
+ if (bot.private === true)
409
+ throw new Error(`${bot.name} is private, so it cannot be copied`);
410
+ const served = (await catalog()).some((entry) => entry.ref === bot.model);
411
+ // A folder that went away since leaves the copy in the team workspace.
412
+ const workDir = bot.workDir !== undefined && (await isFolder(bot.workDir)) ? bot.workDir : undefined;
413
+ // No await from here to createBot's check, so two copies at once get different names.
414
+ return createBot({
415
+ name: freshName(`${bot.name} copy`),
416
+ role: bot.role,
417
+ instructions: bot.instructions,
418
+ color: bot.color,
419
+ avatar: bot.avatar,
420
+ model: served ? bot.model : undefined,
421
+ // A copy of a Bot on the model's own default stays on it (null marks the
422
+ // explicit Default pick); else the create would inherit the profile level.
423
+ effort: served ? (bot.effort ?? null) : undefined,
424
+ workDir,
425
+ copyOf: bot.id,
426
+ });
427
+ }
428
+ async function updateBot(id, patch, actorId, fromSessionId) {
429
+ const bot = rt.botOf(id);
430
+ if (bot === undefined)
431
+ throw new Error("Unknown Bot");
432
+ if (patch.private !== undefined && actorId !== undefined)
433
+ throw new Error(`Only the user can make ${bot.name} private or open`);
434
+ // Checked first, so a folder, model or level that does not pass leaves the rest
435
+ // unchanged too.
436
+ const moving = patch.workDir !== undefined;
437
+ const workDir = moving ? await cleanWorkDir(patch.workDir ?? "") : undefined;
438
+ const flag = patch.private === undefined ? undefined : patch.private === true;
439
+ await checkPrivacyChange(bot, { flag, moving, workDir });
440
+ const modelRef = patch.model === undefined
441
+ ? undefined
442
+ : patch.model === null || patch.model === ""
443
+ ? null
444
+ : await resolveModel(patch.model);
445
+ // What a Bot runs on changes only from its settings, after the user confirmed: every
446
+ // conversation of the Bot starts a new part for it. A Bot without a model runs on the
447
+ // one it last ran on, and one that never ran runs on Ocean Crew's models.
448
+ const engineBefore = rt.engineOf === undefined ? undefined : (rt.engineOfBot?.(bot) ?? "model");
449
+ if (modelRef === null && engineBefore !== undefined && engineBefore !== "model")
450
+ throw new Error(`${bot.name} runs on a local agent and keeps a model of it`);
451
+ const engineChanged = !!modelRef && engineBefore !== undefined && rt.engineOf?.(modelRef) !== engineBefore;
452
+ if (engineChanged && actorId !== undefined)
453
+ throw new Error(`Only the user can change what ${bot.name} runs on, in the Bot's settings`);
454
+ if (engineChanged && patch.changeEngine !== true)
455
+ throw new Error(`Changing what ${bot.name} runs on needs a confirmation in the Bot's settings`);
456
+ // A new level resolves against the model the Bot will run on: the new one, the
457
+ // model it keeps, or — the model cleared — the one it last ran on.
458
+ const effortRef = modelRef === undefined ? (bot.model ?? bot.appliedModel) : (modelRef ?? bot.appliedModel);
459
+ let effortId;
460
+ if (patch.effort !== undefined) {
461
+ if (patch.effort === null || patch.effort === "")
462
+ effortId = null;
463
+ else {
464
+ if (effortRef === undefined)
465
+ throw new Error("Pick a model before choosing a thinking level");
466
+ effortId = await resolveEffort(effortRef, patch.effort);
467
+ }
468
+ }
469
+ if (patch.name !== undefined) {
470
+ const next = String(patch.name).trim().slice(0, 40);
471
+ const clash = rt.findBot(next);
472
+ const pending = isHeld("bot", next) && normalize(next) !== normalize(bot.name);
473
+ if (next === "" || (clash !== undefined && clash.id !== id) || pending)
474
+ throw new Error(`Name ${next} is not available`);
475
+ // A name saved before the rule stays usable until it changes.
476
+ const problem = next === bot.name ? undefined : nameProblem(next);
477
+ if (problem !== undefined)
478
+ throw new Error(problem);
479
+ bot.name = next;
480
+ const agent = await resolveAgent(rt.chatOf(id));
481
+ await sessionTitle?.rename?.(agent.session, next);
482
+ await followMemberNames(Object.values(state.rooms).filter((room) => room.members.includes(id)));
483
+ }
484
+ const roleBefore = bot.role;
485
+ const instructionsBefore = bot.instructions;
486
+ if (patch.role !== undefined)
487
+ bot.role = String(patch.role).trim().slice(0, 24);
488
+ if (patch.instructions !== undefined)
489
+ bot.instructions = String(patch.instructions).trim();
490
+ let modelChanged = false;
491
+ if (patch.color !== undefined) {
492
+ if (patch.color === null)
493
+ delete bot.color;
494
+ else {
495
+ const picked = currentColor(String(patch.color));
496
+ if (isColor(picked))
497
+ bot.color = picked;
498
+ }
499
+ }
500
+ if (patch.avatar !== undefined) {
501
+ const avatar = cleanAvatar(patch.avatar);
502
+ if (avatar)
503
+ bot.avatar = avatar;
504
+ else
505
+ delete bot.avatar;
506
+ }
507
+ if (patch.model !== undefined) {
508
+ // A failure that blocked the Bot was its old model's (turns.js).
509
+ if ((modelRef ?? undefined) !== bot.model)
510
+ delete bot.blocked;
511
+ if (modelRef === null)
512
+ delete bot.model;
513
+ else
514
+ bot.model = modelRef;
515
+ modelChanged = true;
516
+ }
517
+ if (patch.effort !== undefined) {
518
+ if (effortId === null)
519
+ delete bot.effort;
520
+ else
521
+ bot.effort = effortId;
522
+ modelChanged = true;
523
+ }
524
+ if (patch.permission !== undefined)
525
+ await setPermission(bot, patch.permission);
526
+ if (flag === true)
527
+ bot.private = true;
528
+ else if (flag === false)
529
+ delete bot.private;
530
+ const moved = moving && workDir !== bot.workDir;
531
+ if (moving) {
532
+ if (workDir === undefined)
533
+ delete bot.workDir;
534
+ else
535
+ bot.workDir = workDir;
536
+ }
537
+ await rt.save();
538
+ // The system prompt reads the live profile every turn, but a Session with several
539
+ // rounds behind it follows the old kickoff's pull until a message lands; notify the
540
+ // Bot's chat so the next turn honors the new profile.
541
+ const notes = [];
542
+ if (bot.role !== roleBefore)
543
+ notes.push(`Your role is now "${bot.role || "(none)"}"`);
544
+ if (bot.instructions !== instructionsBefore)
545
+ notes.push(`Your instructions now read:\n${bot.instructions || "(none)"}`);
546
+ // A held greeting means the model pick is still open: the kickoff it later sends
547
+ // already reads the new profile, and a notice would start a turn before that.
548
+ // A Bot editing itself in its own chat just got the tool result in the turn that
549
+ // made the edit; a notice there would only buy it a second, unsolicited reply.
550
+ const selfEditInChat = actorId === bot.id && fromSessionId === rt.chatOf(bot.id);
551
+ if (notes.length > 0 && bot.kickoff === undefined && !selfEditInChat) {
552
+ void deliver({ toId: bot.id, text: notes.join("\n"), role: "update" }).catch((error) => warn("ocean-crew: profile update for %s not delivered: %s", bot.name, error?.message ?? error));
553
+ }
554
+ if (modelChanged)
555
+ await applyModel(bot, { force: true });
556
+ if (engineChanged)
557
+ void rt.followEngine?.(bot.id);
558
+ if (moved)
559
+ void rt.followFolder?.({ botId: bot.id });
560
+ // A new model lifted what blocked the Bot; a new thinking level alone fixes nothing.
561
+ // releaseKickoff itself leaves when the Bot still lacks a model or holds no greeting.
562
+ if (modelChanged && bot.blocked === undefined)
563
+ await releaseKickoff(bot);
564
+ return bot;
565
+ }
566
+ async function setFlags(id, flags) {
567
+ const found = (rt.botOf(id) ?? rt.roomOf(id) ?? rt.own(state.agents, id));
568
+ if (found === undefined)
569
+ throw new Error("Unknown conversation");
570
+ const entry = found;
571
+ if (typeof flags.pinned === "boolean")
572
+ entry.pinned = flags.pinned;
573
+ if (typeof flags.hidden === "boolean")
574
+ entry.hidden = flags.hidden;
575
+ await rt.save();
576
+ return found;
577
+ }
578
+ // ---------------------------------------------------------------------------
579
+ // Group chat settings. The user and every Main Bot may change any group; a group's
580
+ // admin may change its own group but not delete it. Only a member can be admin.
581
+ const roomBusy = (id) => {
582
+ const rounds = (rt.roomProgress?.values?.() ?? []);
583
+ return [...rounds].some((round) => round.roomId === id);
584
+ };
585
+ const autoRoomName = (members) => ["You", ...members.map((id) => rt.botOf(id)?.name).filter((name) => name !== undefined)].join(", ");
586
+ // A notice past the limit is refused rather than silently cut (#710).
587
+ const cleanNotice = (text) => {
588
+ const notice = String(text ?? "").trim();
589
+ if (notice.length > ROOM_NOTICE_MAX)
590
+ throw new Error(`A group's notice can hold at most ${ROOM_NOTICE_MAX} characters; this one has ${notice.length}`);
591
+ return notice;
592
+ };
593
+ function cleanRoomName(text, selfId) {
594
+ const next = unquote(text).replace(/\s+/g, " ").slice(0, ROOM_NAME_MAX);
595
+ if (next !== "" && (rt.findRooms(next).some((room) => room.id !== selfId) || isHeld("room", next)))
596
+ throw new Error(`Another group chat is already called "${next}"`);
597
+ return next;
598
+ }
599
+ async function retitleRoom(room) {
600
+ try {
601
+ const agent = await resolveAgent(rt.sessionOfRoom(room));
602
+ await sessionTitle?.rename?.(agent.session, room.name);
603
+ }
604
+ catch (error) {
605
+ warn("ocean-crew: group title for %s not updated: %s", room.name, error);
606
+ }
607
+ }
608
+ // Groups without a chosen name are named after their members, so they follow renames.
609
+ async function followMemberNames(rooms = Object.values(state.rooms)) {
610
+ for (const room of rooms) {
611
+ if (room.named)
612
+ continue;
613
+ const next = autoRoomName(room.members);
614
+ if (next === room.name)
615
+ continue;
616
+ room.name = next;
617
+ await retitleRoom(room);
618
+ }
619
+ }
620
+ function checkMembers(members) {
621
+ if (members.length < 2)
622
+ throw new Error("A group chat needs at least two Bots");
623
+ if (members.length > ROOM_MAX_MEMBERS)
624
+ throw new Error(`A group chat holds at most ${ROOM_MAX_MEMBERS} Bots`);
625
+ checkNoPrivate(members);
626
+ }
627
+ // A Main Bot leads the groups it makes; a group the user makes is led by a Main Bot
628
+ // member when it has one.
629
+ const defaultAdmin = (members, createdBy) => createdBy !== undefined && members.includes(createdBy)
630
+ ? createdBy
631
+ : (members.find((id) => rt.isMain(id)) ?? null);
632
+ async function createRoom(options = {}) {
633
+ const memberIds = Array.isArray(options.members) ? options.members : [];
634
+ const members = [...new Set(memberIds)].filter((id) => rt.botOf(id) !== undefined);
635
+ checkMembers(members);
636
+ const custom = cleanRoomName(options.name ?? "", undefined);
637
+ const adminId = options.admin !== undefined ? options.admin : defaultAdmin(members, options.createdBy);
638
+ if (adminId !== null && !members.includes(adminId))
639
+ throw new Error("The admin must be a member of the group");
640
+ if (options.mode !== undefined && !ROOM_MODES.includes(String(options.mode)))
641
+ throw new Error(`Reply mode must be one of ${ROOM_MODES.join(", ")}`);
642
+ return holdName("room", custom, () => buildRoom({
643
+ members,
644
+ custom,
645
+ notice: options.notice,
646
+ mode: options.mode,
647
+ adminId,
648
+ createdBy: options.createdBy,
649
+ }));
650
+ }
651
+ async function buildRoom({ members, custom, notice, mode, adminId, createdBy, }) {
652
+ const title = custom || autoRoomName(members);
653
+ // The group's own Session only relays; like a member's it moves to a fresh part
654
+ // in the group's folder once the group has one (parts.js).
655
+ const id = await createSession(title);
656
+ try {
657
+ // A member deleted while the Session was made stays out, and the group is checked
658
+ // again as it is written.
659
+ const live = members.filter((member) => rt.botOf(member) !== undefined);
660
+ checkMembers(live);
661
+ const lead = adminId === null || live.includes(adminId) ? adminId : defaultAdmin(live, createdBy);
662
+ const name = custom || autoRoomName(live);
663
+ const room = {
664
+ id,
665
+ name,
666
+ ...(custom ? { named: true } : {}),
667
+ members: live,
668
+ admin: lead,
669
+ mode: (mode ?? "admin"),
670
+ notice: cleanNotice(notice),
671
+ createdAt: Date.now(),
672
+ createdBy: createdBy ?? null,
673
+ };
674
+ state.rooms[id] = room;
675
+ await rt.save();
676
+ // The Session was resolved before the group owned it, so its relay tool lands now.
677
+ await resolveAgent(id);
678
+ if (name !== title)
679
+ await retitleRoom(room);
680
+ return room;
681
+ }
682
+ catch (error) {
683
+ // The group's Session was already made: archive it instead of leaving an orphan.
684
+ delete state.rooms[id];
685
+ void rt.save().catch(() => undefined);
686
+ await archive(id).catch((archiveError) => warn("ocean-crew: archiving the Session for %s failed: %s", title, archiveError));
687
+ throw error;
688
+ }
689
+ }
690
+ // What a change would write to the group as it is now, or why it cannot be made. It
691
+ // reads only the team, so updateRoom runs it to fail fast and again after its last
692
+ // await: another change or a deleted Bot may have come in meanwhile, and `add` and
693
+ // `remove` apply to the members the group has then.
694
+ function planRoomChange(room, patch, actorId) {
695
+ const byMain = actorId === undefined || rt.isMain(actorId);
696
+ const byAdmin = !byMain && rt.isAdminOf(room, actorId);
697
+ if (!byMain && !byAdmin)
698
+ throw new Error(`Only the user, a Main Bot, or the admin of "${room.name}" can change it`);
699
+ let members = Array.isArray(patch.members) ? [...new Set(patch.members)] : [...room.members];
700
+ for (const member of Array.isArray(patch.add) ? patch.add : [])
701
+ if (!members.includes(member))
702
+ members.push(member);
703
+ const removed = Array.isArray(patch.remove) ? patch.remove : [];
704
+ members = members.filter((member) => !removed.includes(member) && rt.botOf(member) !== undefined);
705
+ // A group left with one Bot by a deletion can still change its other settings.
706
+ const current = room.members.filter((member) => rt.botOf(member) !== undefined);
707
+ if (members.length !== current.length || members.some((member) => !current.includes(member)))
708
+ checkMembers(members);
709
+ let admin = room.admin ?? null;
710
+ if (patch.admin !== undefined) {
711
+ admin = patch.admin === null || patch.admin === "" ? null : patch.admin;
712
+ if (admin === null && byAdmin)
713
+ throw new Error("Hand the admin role to another member instead of leaving the group without one");
714
+ if (admin !== null && !members.includes(admin))
715
+ throw new Error(`${rt.botOf(admin)?.name ?? "That Bot"} must be a member to be the admin`);
716
+ }
717
+ if (admin !== null && !members.includes(admin)) {
718
+ if (byAdmin && admin === actorId)
719
+ throw new Error("Hand the admin role to another member before leaving the group");
720
+ admin = null;
721
+ }
722
+ if (patch.mode !== undefined && !ROOM_MODES.includes(String(patch.mode)))
723
+ throw new Error(`Reply mode must be one of ${ROOM_MODES.join(", ")}`);
724
+ const notice = patch.notice === undefined ? undefined : cleanNotice(patch.notice);
725
+ if (patch.workDir !== undefined && byAdmin)
726
+ throw new Error(`Only the user or a Main Bot can set the folder of "${room.name}"`);
727
+ // A Bot's own permissions are the user's to set, so a group's are too.
728
+ if (patch.permission !== undefined && actorId !== undefined)
729
+ throw new Error(`Only the user can set the permissions of "${room.name}"`);
730
+ const permission = patch.permission === undefined ? undefined : cleanRoomPermission(patch.permission);
731
+ // The second run is the last check before the change is written, so no other change
732
+ // can take the name in between.
733
+ const name = patch.name === undefined ? undefined : cleanRoomName(patch.name, room.id);
734
+ return { members, admin, name, notice, permission };
735
+ }
736
+ // `actorId` is the Bot asking, or undefined for the user. Returns what changed, in words.
737
+ async function updateRoom(id, patch, actorId) {
738
+ const asked = rt.roomOf(id);
739
+ if (asked === undefined)
740
+ throw new Error("Unknown group chat");
741
+ planRoomChange(asked, patch, actorId);
742
+ const moving = patch.workDir !== undefined;
743
+ const workDir = moving ? await cleanWorkDir(patch.workDir ?? "") : undefined;
744
+ const clash = workDir === undefined ? undefined : await privateClash(workDir);
745
+ if (clash)
746
+ throw new Error(`${workDir} is in or around the folder of ${clash.name}, a private Bot, so a group cannot work there`);
747
+ // No await from here until every change is written.
748
+ const room = rt.roomOf(id);
749
+ if (room === undefined)
750
+ throw new Error("Unknown group chat");
751
+ const { members, admin, name, notice, permission } = planRoomChange(room, patch, actorId);
752
+ const changes = [];
753
+ const names = (ids) => ids
754
+ .map((member) => rt.botOf(member)?.name)
755
+ .filter(Boolean)
756
+ .join(", ");
757
+ const added = members.filter((member) => !room.members.includes(member));
758
+ const removed = room.members.filter((member) => !members.includes(member));
759
+ if (added.length > 0)
760
+ changes.push(`added ${names(added)}`);
761
+ // A deleted Bot still listed goes without a word.
762
+ if (names(removed) !== "")
763
+ changes.push(`removed ${names(removed)}`);
764
+ // A member who leaves and comes back starts from a fresh look at the log.
765
+ for (const member of removed) {
766
+ if (room.seen !== undefined)
767
+ delete room.seen[member];
768
+ rt.dropGroupSession(room, member);
769
+ }
770
+ room.members = members;
771
+ if (admin !== (room.admin ?? null))
772
+ changes.push(admin ? `made ${rt.botOf(admin)?.name} the admin` : "removed the admin");
773
+ room.admin = admin;
774
+ if (patch.mode !== undefined && String(patch.mode) !== room.mode) {
775
+ room.mode = patch.mode;
776
+ changes.push(patch.mode === "admin" ? "plain messages now go to the admin first" : "every member now replies in turn");
777
+ }
778
+ if (notice !== undefined && notice !== (room.notice ?? "")) {
779
+ room.notice = notice;
780
+ changes.push(notice ? "updated the notice" : "cleared the notice");
781
+ }
782
+ // Members' group conversations move on to the folder at their next turn there;
783
+ // the group's own Session moves the same way, now when it is idle.
784
+ if (moving && workDir !== room.workDir) {
785
+ delete room.folderNotice;
786
+ if (workDir === undefined)
787
+ delete room.workDir;
788
+ else
789
+ room.workDir = workDir;
790
+ // A member's own pick for this group gives way to the group's folder, and a
791
+ // cleared one does not bring it back.
792
+ delete room.memberDirs;
793
+ changes.push(workDir ? `every member now works in ${workDir} here` : "every member works in its own folder again");
794
+ void rt.followFolder?.({ roomId: room.id });
795
+ }
796
+ const before = room.name;
797
+ if (name !== undefined) {
798
+ if (name !== "") {
799
+ room.named = true;
800
+ room.name = name;
801
+ }
802
+ else {
803
+ delete room.named;
804
+ }
805
+ }
806
+ if (!room.named)
807
+ room.name = autoRoomName(room.members);
808
+ // The preset is written before its first await; the members' Sessions follow it.
809
+ if (permission !== undefined && (await setRoomPermission(room, permission))) {
810
+ changes.push(permission
811
+ ? `every member now works with the ${permission} permissions here`
812
+ : "every member uses its own permissions again");
813
+ }
814
+ if (room.name !== before) {
815
+ changes.push(`renamed it "${room.name}"`);
816
+ await retitleRoom(room);
817
+ }
818
+ await rt.save();
819
+ return { room, changes };
820
+ }
821
+ async function deleteRoom(id) {
822
+ const room = rt.roomOf(id);
823
+ if (room === undefined)
824
+ throw new Error("Unknown group chat");
825
+ // Before the group's Sessions leave the state, which the archive reads.
826
+ const archived = archiveGroupMemory(room);
827
+ for (const botId of Object.keys(room.sessions ?? {}))
828
+ rt.dropGroupSession(room, botId);
829
+ for (const segment of room.parts ?? [])
830
+ delete state.switching[segment.sessionId];
831
+ delete state.switching[rt.sessionOfRoom(room)];
832
+ delete state.rooms[id];
833
+ rt.roomInbox?.delete(id);
834
+ dropGroupLines(id);
835
+ await archived;
836
+ const failed = await saveForDelete();
837
+ // Armed scheduled tasks refuse a plain archive and would keep delivering into
838
+ // the deleted group; the session-stop that stopActivity runs removes them.
839
+ await archive(rt.sessionOfRoom(room), { stopActivity: true }).catch((error) => warn("ocean-crew: group chat %s not archived: %s", room.name, error));
840
+ if (failed !== undefined)
841
+ throw failed;
842
+ }
843
+ // The first Main Bot is the sidebar tile. `replace` gives a Main Bot's place to
844
+ // another Bot in one step, so the team never has none; `primary` moves a Bot to the
845
+ // front and keeps the others.
846
+ async function setMain(id, main, { primary = false, replace } = {}) {
847
+ const bot = rt.botOf(id);
848
+ if (bot === undefined)
849
+ throw new Error("Unknown Bot");
850
+ if (main && bot.private === true)
851
+ throw new Error(`${bot.name} is private, so it cannot be a Main Bot`);
852
+ const others = state.mainBotIds.filter((other) => other !== id);
853
+ let next;
854
+ if (!main) {
855
+ if (!rt.isMain(id))
856
+ return;
857
+ if (others.length === 0)
858
+ throw new Error("The team needs at least one Main Bot");
859
+ next = others;
860
+ }
861
+ else if (replace !== undefined && replace !== id) {
862
+ const at = others.indexOf(replace);
863
+ if (at === -1)
864
+ throw new Error("Only a Main Bot can be replaced");
865
+ next = others.with(at, id);
866
+ }
867
+ else if (primary) {
868
+ next = [id, ...others];
869
+ }
870
+ else {
871
+ next = rt.isMain(id) ? state.mainBotIds : [...others, id];
872
+ }
873
+ // The sidebar shows every Main Bot, so a hidden Bot would vanish again once demoted.
874
+ if (main)
875
+ delete bot.hidden;
876
+ // A held setup greeting says "you are the Main Bot"; it must not go out after demotion.
877
+ for (const other of state.mainBotIds.filter((other) => !next.includes(other))) {
878
+ const demoted = rt.botOf(other);
879
+ if (demoted?.kickoff?.main)
880
+ delete demoted?.kickoff;
881
+ }
882
+ state.mainBotIds = next;
883
+ await rt.save();
884
+ }
885
+ async function deleteBot(id) {
886
+ const bot = rt.botOf(id);
887
+ if (bot === undefined)
888
+ throw new Error("Unknown Bot");
889
+ if (rt.isMain(id))
890
+ throw new Error("A Main Bot cannot be deleted; remove its Main Bot role first");
891
+ // Before the Bot and its group Sessions leave the state, which the archive reads.
892
+ const archived = archiveBotMemory(id);
893
+ const current = rt.chatOf(id);
894
+ // Questions and exchange turns are kept per Session, so every part of the chat is cleared.
895
+ const parts = new Set([id, current, ...(bot.segments ?? []).map((segment) => segment.sessionId)]);
896
+ // `archiving` stands until the archive's path is known: the memory may already be
897
+ // there, and no region of its own closes it yet.
898
+ const closedArchive = bot.private === true
899
+ ? {
900
+ id: bot.id,
901
+ name: bot.name,
902
+ ...(bot.workDir === undefined ? {} : { workDir: bot.workDir }),
903
+ sessionIds: [...parts, ...rt.groupSessionsOf(id)],
904
+ archiving: true,
905
+ }
906
+ : undefined;
907
+ await releaseBot(id, [...parts, ...rt.groupSessionsOf(id)]);
908
+ if (closedArchive !== undefined)
909
+ state.privateArchives = [
910
+ ...(state.privateArchives ?? []).filter((entry) => entry.id !== id),
911
+ closedArchive,
912
+ ];
913
+ delete state.bots[id];
914
+ // The shared capability list is the user's and keeps its items; only a
915
+ // still-unapproved local MCP this Bot alone asked for leaves with it.
916
+ rt.dropOrphanCapabilities?.(bot);
917
+ for (const part of parts) {
918
+ delete state.questions[part];
919
+ if (state.views !== undefined)
920
+ delete state.views[part];
921
+ if (state.closedCards !== undefined)
922
+ delete state.closedCards[part];
923
+ delete state.exchangeTurns[part];
924
+ delete state.switching[part];
925
+ }
926
+ const touched = [];
927
+ for (const room of Object.values(state.rooms)) {
928
+ if (!room.members.includes(id))
929
+ continue;
930
+ room.members = room.members.filter((member) => member !== id);
931
+ if (room.admin === id)
932
+ room.admin = null;
933
+ rt.dropGroupSession(room, id);
934
+ touched.push(room);
935
+ }
936
+ await followMemberNames(touched);
937
+ await forgetBotSecrets(id);
938
+ const archivePath = await archived;
939
+ if (closedArchive !== undefined) {
940
+ // No path means nothing was moved: a memory that stayed in place is a region already.
941
+ if (archivePath !== undefined)
942
+ closedArchive.archivePath = archivePath;
943
+ delete closedArchive.archiving;
944
+ }
945
+ const failed = await saveForDelete();
946
+ // Same as deleteRoom: stopActivity removes the Session's armed scheduled tasks.
947
+ // Past parts are archived too: a part move can leave tasks on the old Session,
948
+ // which otherwise stays armed and invisible. Already-archived ids are a no-op.
949
+ for (const part of parts)
950
+ await archive(part, { stopActivity: true }).catch((error) => warn("ocean-crew: Bot %s not archived: %s", bot.name, error));
951
+ if (failed !== undefined)
952
+ throw failed;
953
+ }
954
+ // A deletion whose save fails stays in memory, and the next save writes it, so its
955
+ // Sessions are stopped anyway: left armed, their scheduled tasks would keep running
956
+ // with nothing in the team to show or delete them. Only a host that lost the team
957
+ // to another dsh keeps them, since the other host's copy still has them.
958
+ async function saveForDelete() {
959
+ try {
960
+ await rt.save();
961
+ return undefined;
962
+ }
963
+ catch (error) {
964
+ if (error?.code === "ELOCKLOST" || rt.readOnly() !== undefined)
965
+ throw error;
966
+ return error;
967
+ }
968
+ }
969
+ async function bootstrap() {
970
+ await rt.load();
971
+ void rt.syncModels?.();
972
+ if (state.mainBotIds.some((id) => rt.botOf(id) !== undefined))
973
+ return;
974
+ // Only the team's first Main Bot is stored as the DeepSeek whale; other Bots get a
975
+ // look from their id, and a Bot made Main Bot later keeps its own.
976
+ bootstrapping ??= createBot({
977
+ name: rt.defaults.mainName,
978
+ role: rt.defaults.mainRole,
979
+ main: true,
980
+ color: "deepseek",
981
+ avatar: { shape: "marine-whale" },
982
+ pickModel: true,
983
+ }).finally(() => {
984
+ bootstrapping = null;
985
+ });
986
+ await bootstrapping;
987
+ }
988
+ Object.assign(rt, {
989
+ ensureWorkspace,
990
+ keepTeamFolder,
991
+ createSession,
992
+ createBot,
993
+ duplicateBot,
994
+ updateBot,
995
+ setFlags,
996
+ roomBusy,
997
+ autoRoomName,
998
+ retitleRoom,
999
+ createRoom,
1000
+ updateRoom,
1001
+ deleteRoom,
1002
+ setMain,
1003
+ deleteBot,
1004
+ bootstrap,
1005
+ releaseKickoff,
1006
+ greetingOut,
1007
+ holdKickoffAgain,
1008
+ userWrote,
1009
+ userAnswered,
1010
+ });
1011
+ }