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,263 @@
1
+ // Permissions. A Bot's permission preset is its own: kept on the Bot and set on every
2
+ // Session it speaks from, so a fresh part or a new group Session keeps it. A group may
3
+ // set one preset for all its members there, in place of each member's own, as it may
4
+ // set one working folder.
5
+ // DSH offers Auto review for the current Session only, so neither a Bot nor a group keeps it.
6
+ //
7
+ const SESSION_ONLY = "auto";
8
+ export function install(rt) {
9
+ const presets = () => rt.ctx.get?.("permissionPresets");
10
+ // The presets DSH offers, or undefined when the profile has none.
11
+ function permissionCatalog() {
12
+ const service = presets();
13
+ if (service === undefined)
14
+ return undefined;
15
+ const { options, defaultPreset } = service.catalog();
16
+ return { options: options.filter((option) => option.value !== SESSION_ONLY), defaultPreset };
17
+ }
18
+ const roomOfSession = (sessionId) => rt.roomOf(rt.groupOwners.get(sessionId)?.roomId);
19
+ // `name` may be a function: it is read once the agent resolves, so a change asked
20
+ // for while the resolve ran wins over the one still being applied.
21
+ async function setPreset(sessionId, name, context) {
22
+ const agent = (await rt.resolveAgent(sessionId));
23
+ const wanted = typeof name === "function" ? name() : name;
24
+ if (wanted === undefined)
25
+ return undefined;
26
+ bumpSession(sessionId);
27
+ const source = context?.source ?? (context?.bot === undefined ? "default" : sourceOf(context.room, context.bot));
28
+ try {
29
+ presets()?.set(agent.session, wanted);
30
+ }
31
+ catch (error) {
32
+ record(sessionId, {
33
+ preset: wanted,
34
+ source,
35
+ applied: false,
36
+ ...(context?.bot !== undefined ? { botId: context.bot.id } : {}),
37
+ ...(context?.room !== undefined ? { roomId: context.room.id } : {}),
38
+ error: error?.message ?? String(error),
39
+ });
40
+ throw error;
41
+ }
42
+ record(sessionId, {
43
+ preset: wanted,
44
+ source,
45
+ applied: true,
46
+ ...(context?.bot !== undefined ? { botId: context.bot.id } : {}),
47
+ ...(context?.room !== undefined ? { roomId: context.room.id } : {}),
48
+ });
49
+ return wanted;
50
+ }
51
+ // Sets the preset on one of the Bot's Sessions: its group's there, else its own; a Bot
52
+ // without one keeps DSH's default. `room` is for a group Session not indexed yet.
53
+ // Returns the preset it set, or undefined when it set none.
54
+ async function applyPermission(bot, sessionId, room = roomOfSession(sessionId)) {
55
+ const name = () => room?.permission ?? bot.permission;
56
+ if (presets() === undefined || !name())
57
+ return undefined;
58
+ return setPreset(sessionId, name, { bot, room });
59
+ }
60
+ function checkPreset(name, whose) {
61
+ const service = presets();
62
+ if (service === undefined)
63
+ throw new Error("Permissions are not available in this DeepSeek Harness");
64
+ const wanted = String(name ?? "").trim();
65
+ if (wanted === SESSION_ONLY)
66
+ throw new Error(`Auto review applies to one Session only and cannot be ${whose} permission`);
67
+ service.resolve(wanted);
68
+ return wanted;
69
+ }
70
+ // Per Bot, requests are numbered and the last preset an apply actually set is
71
+ // tracked: only the newest request may roll the field back, and then to that
72
+ // applied value, never to a value a request had only asked for.
73
+ const requests = new Map();
74
+ const effective = new Map();
75
+ const botsState = new Map();
76
+ const roomsState = new Map();
77
+ const sessionRevisions = new Map();
78
+ const botRevisions = new Map();
79
+ const roomRevisions = new Map();
80
+ let revision = 0;
81
+ const bump = () => ++revision;
82
+ const roomKey = (room) => room.id;
83
+ const bumpSession = (sessionId) => {
84
+ sessionRevisions.set(sessionId, (sessionRevisions.get(sessionId) ?? 0) + 1);
85
+ bump();
86
+ };
87
+ const record = (sessionId, entry) => {
88
+ effective.set(sessionId, { ...entry, at: entry.at ?? Date.now() });
89
+ };
90
+ const stateOf = (botId) => {
91
+ const found = botsState.get(botId);
92
+ if (found !== undefined)
93
+ return found;
94
+ const created = { applyRevision: 0, partial: false };
95
+ botsState.set(botId, created);
96
+ return created;
97
+ };
98
+ const sessionsOf = (bot) => {
99
+ const sessions = [rt.chatOf(bot.id), ...rt.groupSessionsOf(bot.id)];
100
+ return [...new Set(sessions)];
101
+ };
102
+ const sourceOf = (room, bot) => {
103
+ if (room?.permission !== undefined)
104
+ return "room";
105
+ return bot.permission !== undefined ? "bot" : "default";
106
+ };
107
+ const audit = (bot) => {
108
+ // A Session the group governs is the group's to apply; this audit only judges the
109
+ // Sessions the Bot's own change reached, and only a real failed apply is partial.
110
+ const rows = sessionsOf(bot)
111
+ .map((sessionId) => effective.get(sessionId))
112
+ .filter((row) => row !== undefined);
113
+ const state = stateOf(bot.id);
114
+ state.partial = rows.some((row) => row.applied === false);
115
+ return state.partial;
116
+ };
117
+ async function setPermission(bot, name) {
118
+ const wanted = checkPreset(name, "a Bot's");
119
+ const request = requests.get(bot.id) ?? { seq: 0, applied: bot.permission };
120
+ const mine = ++request.seq;
121
+ requests.set(bot.id, request);
122
+ // The change is known before its first await: the audit names the desired preset,
123
+ // its revision moves, and any approval asked under the old authority is withdrawn
124
+ // before a Session could still execute it.
125
+ const state = stateOf(bot.id);
126
+ state.desired = wanted;
127
+ state.applyRevision = mine;
128
+ state.lastError = undefined;
129
+ state.partial = false;
130
+ botRevisions.set(bot.id, (botRevisions.get(bot.id) ?? 0) + 1);
131
+ bump();
132
+ rt.invalidateApprovals?.(sessionsOf(bot));
133
+ // The preset is written before its first await: a request still being applied
134
+ // then reads the one asked for last.
135
+ bot.permission = wanted;
136
+ // The preset for one Session is read once its agent resolves: undefined once a
137
+ // newer request exists, so a superseded request writes no more Sessions — every
138
+ // Session the Bot has ends at the value the newest request actually applied.
139
+ const applyTo = (sessionId, room = roomOfSession(sessionId)) => setPreset(sessionId, () => (request.seq === mine ? (room?.permission ?? bot.permission) : undefined), {
140
+ bot,
141
+ room,
142
+ });
143
+ const groups = async (warnFail) => {
144
+ for (const sessionId of rt.groupSessionsOf(bot.id)) {
145
+ if (request.seq !== mine)
146
+ break;
147
+ if (roomOfSession(sessionId)?.permission)
148
+ continue;
149
+ await applyTo(sessionId).catch(warnFail);
150
+ }
151
+ };
152
+ try {
153
+ const applied = await applyTo(rt.chatOf(bot.id));
154
+ if (applied !== undefined)
155
+ request.applied = applied;
156
+ }
157
+ catch (error) {
158
+ if (request.seq === mine) {
159
+ state.lastError = error?.message ?? String(error);
160
+ if (request.applied === undefined)
161
+ delete bot.permission;
162
+ else {
163
+ bot.permission = request.applied;
164
+ // The restored preset goes back on every Session the change left behind.
165
+ const warnFail = (failure) => rt.warn("ocean-crew: permission for %s not restored: %s", bot.name, failure);
166
+ await applyTo(rt.chatOf(bot.id)).catch(warnFail);
167
+ await groups(warnFail);
168
+ }
169
+ }
170
+ // A change that failed is partial by definition: the audit names what the
171
+ // Sessions still hold after the rollback.
172
+ audit(bot);
173
+ throw error;
174
+ }
175
+ await groups((error) => rt.warn("ocean-crew: permission for %s in a group not applied: %s", bot.name, error));
176
+ audit(bot);
177
+ }
178
+ // The audit for a Bot, or for every Bot the host has seen: what was asked for, which
179
+ // revision applied it, the last error, and the preset each Session really holds.
180
+ function permissionState(botId) {
181
+ const ids = botId === undefined
182
+ ? [
183
+ ...new Set([...botsState.keys(), ...effective.values()].flatMap((entry) => typeof entry === "string" ? [] : entry.botId === undefined ? [] : [entry.botId])),
184
+ ]
185
+ : [botId];
186
+ const bots = {};
187
+ for (const id of ids) {
188
+ const state = stateOf(id);
189
+ const sessions = [...effective.entries()]
190
+ .filter(([, entry]) => entry.botId === id)
191
+ .map(([sessionId, entry]) => ({ sessionId, ...entry }));
192
+ bots[id] = { id, ...state, sessions };
193
+ }
194
+ return { revision, bots, rooms: Object.fromEntries(roomsState) };
195
+ }
196
+ // The revision an approval binds to: the Bot's, its group's, and the Session's own
197
+ // last apply, as one comparable string.
198
+ function permissionRevision(sessionId) {
199
+ const owner = rt.groupOwners.get(sessionId);
200
+ const botId = owner?.botId ?? rt.chatOwners.get(sessionId);
201
+ const roomId = owner?.roomId;
202
+ const botRev = botId === undefined ? 0 : (botRevisions.get(botId) ?? 0);
203
+ const roomRev = roomId === undefined ? 0 : (roomRevisions.get(roomId) ?? 0);
204
+ return `b${botRev}:r${roomRev}:s${sessionRevisions.get(sessionId) ?? 0}`;
205
+ }
206
+ const effectivePermission = (sessionId) => effective.get(sessionId);
207
+ // A group's preset, or null when each member uses its own.
208
+ const cleanRoomPermission = (name) => name === null || name === "" ? null : checkPreset(name, "a group's");
209
+ // Members' Sessions in the group change now; a member that has none there yet gets the
210
+ // group's preset when its first turn there makes one. Returns whether it changed.
211
+ async function setRoomPermission(room, name) {
212
+ const wanted = cleanRoomPermission(name) ?? undefined;
213
+ if (wanted === room.permission)
214
+ return false;
215
+ const key = roomKey(room);
216
+ const state = roomsState.get(key) ?? { applyRevision: 0, partial: false };
217
+ roomsState.set(key, state);
218
+ if (wanted === undefined)
219
+ delete room.permission;
220
+ else
221
+ room.permission = wanted;
222
+ state.permission = wanted;
223
+ state.applyRevision += 1;
224
+ state.lastError = undefined;
225
+ state.partial = false;
226
+ roomRevisions.set(key, (roomRevisions.get(key) ?? 0) + 1);
227
+ bump();
228
+ rt.invalidateApprovals?.(Object.values(room.sessions ?? {}));
229
+ const service = presets();
230
+ if (service === undefined)
231
+ return true;
232
+ const failed = [];
233
+ for (const [botId, sessionId] of Object.entries(room.sessions ?? {})) {
234
+ const bot = rt.botOf(botId);
235
+ if (bot === undefined)
236
+ continue;
237
+ // A member without a preset of its own goes back to the default its Session started on.
238
+ await setPreset(sessionId, () => room.permission ?? bot.permission ?? service.catalog().defaultPreset, {
239
+ bot,
240
+ room,
241
+ source: room.permission !== undefined ? "room" : bot.permission !== undefined ? "bot" : "default",
242
+ }).catch((error) => {
243
+ failed.push(sessionId);
244
+ rt.warn("ocean-crew: permission for %s in %s not applied: %s", bot.name, room.name, error);
245
+ });
246
+ }
247
+ if (failed.length > 0) {
248
+ state.partial = true;
249
+ state.lastError = `not applied to ${failed.length} Session${failed.length === 1 ? "" : "s"}`;
250
+ }
251
+ return true;
252
+ }
253
+ Object.assign(rt, {
254
+ permissionCatalog,
255
+ applyPermission,
256
+ setPermission,
257
+ cleanRoomPermission,
258
+ setRoomPermission,
259
+ permissionState,
260
+ permissionRevision,
261
+ effectivePermission,
262
+ });
263
+ }
@@ -0,0 +1,108 @@
1
+ // Private Bots. A private Bot reads the team like any Bot, but no other Bot reads it, and
2
+ // what it sends out waits for the user.
3
+ // privacy rules is here (who is private, which folders clash, what a change may make
4
+ // private, the kept-closed list), while the tool fence that checks file paths, shells and
5
+ import { resolve } from "node:path";
6
+ import { within } from "../core/folders.js";
7
+ // Windows and macOS file systems ignore case.
8
+ const fold = (text) => (process.platform === "linux" ? text : text.toLowerCase());
9
+ const overlap = (a, b) => within(a, b) || within(b, a);
10
+ export function install(rt) {
11
+ const state = rt.state;
12
+ const isPrivate = (id) => rt.botOf(id)?.private === true;
13
+ const archives = () => (state.privateArchives ?? []);
14
+ const privateBots = () => Object.values(state.bots).filter((bot) => bot.private === true);
15
+ // Deleting a private Bot does not make the files and memory it leaves behind public.
16
+ const protectedBots = () => [
17
+ ...new Map([...archives(), ...privateBots()].map((bot) => [bot.id, bot])).values(),
18
+ ];
19
+ // The folder the team works in; `defaultTeamFolder` is always there to fall back to.
20
+ const teamFolder = () => rt.teamFolder() ?? resolve(rt.defaultTeamFolder());
21
+ // A path as it is and as the file system resolves it, folded for comparing. realBeyond
22
+ // also resolves a link above a file that does not exist yet.
23
+ const spellings = async (path) => [
24
+ ...new Set([fold(resolve(path)), fold(await rt.realBeyond(resolve(path)))]),
25
+ ];
26
+ // A folder that a private Bot's folder would overlap, or that overlaps one.
27
+ async function privateClash(path, { except } = {}) {
28
+ const keys = await spellings(path);
29
+ for (const bot of protectedBots()) {
30
+ if (bot.id === except || bot.workDir === undefined)
31
+ continue;
32
+ const dirs = await spellings(bot.workDir);
33
+ if (keys.some((key) => dirs.some((dir) => overlap(key, dir))))
34
+ return { name: bot.name };
35
+ }
36
+ return undefined;
37
+ }
38
+ // Checks a change of `private` or of the folder of a Bot before it is written. A
39
+ // private Bot's folder is no other Bot's, no group's and not the team workspace —
40
+ // a member's own pick in a group counts as that member's folder — because DSH
41
+ // cannot be told which files of a shared folder to hide.
42
+ async function checkChange(bot, { flag, moving = false, workDir }) {
43
+ const makes = flag === undefined ? bot.private === true : flag;
44
+ const dir = moving ? workDir : bot.workDir;
45
+ if (!makes) {
46
+ const clash = moving && dir !== undefined ? await privateClash(dir, { except: bot.id }) : undefined;
47
+ if (clash)
48
+ throw new Error(`${dir} is in or around the folder of ${clash.name}, a private Bot, so ${bot.name} cannot work there`);
49
+ return;
50
+ }
51
+ if (rt.isMain(bot.id))
52
+ throw new Error(`${bot.name} is a Main Bot, so it cannot be private`);
53
+ if (dir === undefined)
54
+ throw new Error(`${bot.name} needs a folder of its own to be private`);
55
+ if (Object.values(state.rooms).some((room) => room.members.includes(bot.id)))
56
+ throw new Error(`${bot.name} is in a group chat, where every member reads what is said. Remove it from its groups first`);
57
+ const clash = await privateClash(dir, { except: bot.id });
58
+ if (clash)
59
+ throw new Error(`${dir} is in or around the folder of ${clash.name}, a private Bot, so ${bot.name} cannot work there`);
60
+ const keys = await spellings(dir);
61
+ const others = [
62
+ ["the team workspace", teamFolder()],
63
+ ...Object.values(state.bots)
64
+ .filter((other) => other.id !== bot.id && other.workDir !== undefined)
65
+ .map((other) => [`the folder of ${other.name}`, other.workDir]),
66
+ ...Object.values(state.rooms)
67
+ .filter((room) => room.workDir !== undefined)
68
+ .map((room) => [`the folder of "${room.name}"`, room.workDir]),
69
+ ...Object.values(state.rooms).flatMap((room) => Object.entries(room.memberDirs ?? {})
70
+ .filter(([member, dir]) => room.members.includes(member) && dir !== null)
71
+ .map(([member, dir]) => [
72
+ `the folder of ${rt.botOf(member)?.name ?? "a member"} in "${room.name}"`,
73
+ dir ?? undefined,
74
+ ])),
75
+ ];
76
+ for (const [what, path] of others) {
77
+ if (path === undefined)
78
+ continue;
79
+ const spelled = await spellings(path);
80
+ if (keys.some((key) => spelled.some((other) => overlap(key, other))))
81
+ throw new Error(`${dir} is in or around ${what}, so ${bot.name} cannot be private there. Give it a folder of its own`);
82
+ }
83
+ }
84
+ const checkNoPrivate = (ids) => {
85
+ const found = ids.map((id) => rt.botOf(id)).find((bot) => bot?.private === true);
86
+ if (found)
87
+ 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`);
88
+ };
89
+ // Deleting a private Bot keeps its places closed (see roster.ts deleteBot); only the
90
+ // user opens them again, one Bot at a time. The files stay where they are.
91
+ async function releaseArchive(id) {
92
+ const kept = archives();
93
+ if (!kept.some((entry) => entry.id === id))
94
+ throw new Error("Nothing kept closed for this Bot");
95
+ state.privateArchives = kept.filter((entry) => entry.id !== id);
96
+ await rt.save();
97
+ }
98
+ // What the settings list shows. Session ids stay on the host.
99
+ const archivesView = () => archives().map(({ id, name, workDir }) => ({ id, name, ...(workDir === undefined ? {} : { workDir }) }));
100
+ Object.assign(rt, {
101
+ isPrivate,
102
+ privateClash,
103
+ checkPrivacyChange: checkChange,
104
+ checkNoPrivate,
105
+ releaseArchive,
106
+ archivesView,
107
+ });
108
+ }
@@ -0,0 +1,86 @@
1
+ // Prompt: one section whose text depends only on the rendering Session's own Bot
2
+ // record, so the prefix stays byte-stable across turns and roster changes. The rule
3
+ const TEAM_RULES = [
4
+ "## How your Bot team works",
5
+ "- Every Bot is its own long-lived conversation with the user, with its own memory.",
6
+ "- The team changes over time. Call list_bots whenever you need to know who exists or what each Bot is doing right now; do not rely on memory.",
7
+ '- message_bot sends a message to another Bot. Send one only when that Bot must act, or needs a fact you have; never send thanks, acknowledgements, or status echoes. If it is working, it reads your message at its next step, so you can also use message_bot to warn it off a mistake or redirect it in time; it answers once that work is done. Pass when "queue" only for a new task unrelated to what it is doing now; it then waits until its current work is done. Its reply arrives later as a new "[Reply from …]" message. Never wait, poll, or resend. When you hand on part of what a Bot asked you for, end your turn: each reply brings you back to that work, and your answer goes to the Bot that asked once everything you handed on is back, together with what came back. Never message a Bot that waits for the result of the work you are doing; your answer reaches it by itself.',
8
+ '- When the user wants other Bots to tell them something themselves (introduce themselves, report in their own chats), call message_bot with reply_to "user": each Bot then answers the user in its own chat and nothing comes back to you. Do not relay those answers yourself.',
9
+ '- When a "[Message from …]" opens a turn, your final text in that turn is delivered back to that Bot automatically and the user does not see it. If one arrives while you are working on something else, take it into account in that work but do not answer it there: once the work is done, it comes back to you in a turn of its own to answer. Answer it directly and briefly, as a list of facts. Never invent facts: say "not discussed yet" when you do not know. If the message brings a request or a decision meant for the user, handle it in the same turn too — do the work, or ask the user with ask_user.',
10
+ '- When a "[Message from … · the user sees your reply here]" arrives, your reply is shown to the user in your own chat and is not sent back. Talk to the user directly, as yourself.',
11
+ '- A "[Reply from …]" ends that exchange: do not message that Bot back to answer or thank it. Tell the user the outcome if it matters to them. If you need more from that Bot, send it a new request.',
12
+ "- Chat like a teammate texting: short sentences, often two or three short messages instead of one long one, no headings. When the user asks for a deliverable (a plan, schedule, draft, or list), write it out in full in the chat; never claim you gave something you did not write. Mention other Bots by their exact name.",
13
+ "- Only for a direct user request in your own chat that needs several steps: write one short sentence of normal reply text before your first tool call, and make that tool call in the same response. Never start such a task with tools alone or end it with a promise. On long tasks, give brief factual updates only at meaningful milestones, then keep working.",
14
+ '- For "[Message from …]" or "[Reply from …]" messages, do not write plans or progress updates: use tools silently, then reply with the answer. Simple answers do not need progress messages.',
15
+ "- In a group chat, the group sees what you write while you work, not only your final reply. For work that takes more than a quick look, start with one short sentence on what you will do, in the same response as your first tool call. After that, write only when you find something the group should know or finish a part of the work, in a sentence or two, not at every step. End with the result. Simple answers need no updates.",
16
+ "- Offer choices with ask_user (a tap-to-answer card) instead of long option lists in text. Calling it ends your turn at once, so write everything you want to say before the call, in the same reply. The answer arrives as the user's next message.",
17
+ "- show_view draws a view inside your reply: a chart, key numbers, a table, a calculator whose inputs the user can change, or a choice, confirmation or short form. Use it when it shows something better than text, not for every answer. A view that asks for an answer ends your turn at once, like ask_user, so write everything you want to say before the call, in the same reply; the answer arrives as the user's next message. It only works in your own chat, not in a group. Never collect a key, token, or password with it; call request_secret. The view argument is limited to 8 KB.",
18
+ "- update_bot changes your own settings: name, role label, color, model, thinking level, working folder, or instructions. Leave out bot to change yourself. Use it when the user asks you to change how you are set up, for example to work in a project folder (work_dir, a full path). Only a Main Bot can change other Bots; when another Bot needs changing, ask a Main Bot.",
19
+ "- You may be in group chats with the user and other Bots. You speak in each group from a separate conversation of yours, apart from your own chat with the user. There your turn arrives as a \"[Group chat …]\" message that shows the speaking order, and your reply is posted to the group. When someone there asks you to do something, do the work in that turn: the group goes on without waiting and sees what you write as you go. Any member can hand work to another with @Name, and the one that asked answers the result. Work for a group stays in it: there message_bot reaches only members of that group, as @Name does. In a group, read_own_chat shows your own chat (the group sees that you looked; share only what the group needs). In your own chat, read_group_chat shows what was said in a group. A group may have an admin, who steers it: the admin can call members with @Name and change the group with update_group. From outside a group (your own chat or another group), post_to_group posts into a group you are in: the admin's post starts a new discussion there; another member's post calls only the members it names with @Name.",
20
+ "- When you need a key, token, or password, call request_secret: the user types it into a secure card and you never see it. Never ask the user to paste one into the chat. Use it through its environment variable ($DSH_SECRET_<NAME> in bash, $env:DSH_SECRET_<NAME> in PowerShell) and never print it. list_secrets shows which keys exist.",
21
+ "- web_search results say which search backend answered. If web_search fails, never guess URLs or present pages you remember as search results: tell the user that search is unavailable and the reason it gave.",
22
+ '- Your conversations are long-lived. When one grows long, either its older messages are condensed in place into a summary you wrote (a "[Checkpoint N]" message), or it moves on to a fresh part that opens with a handoff note you wrote and your latest messages (a "[Handoff · part N]" message). What leaves your working context stays saved. When you need the exact earlier wording or a detail the summary or note does not show in full (a full path, a figure, every item of a complete list or a final summary), call read_own_chat with words to look for, or with part N to read the note that closed an earlier part; never fill such a detail in from memory. Each line it returns starts with an anchor such as [part 2 #1234 · 10-08 14:22]; pass the anchor as around to read what was said around it.',
23
+ "- Reply in the user's language.",
24
+ ].join("\n");
25
+ const MAIN_RULES = [
26
+ "## You are the Main Bot (Chief of Staff)",
27
+ "- You run the user's Bot team: you decide who does what, create new Bots, and report back.",
28
+ "- When the user wants something that deserves its own ongoing specialist, call create_bot (check list_bots first to avoid duplicates). Give it a short name, a two-to-four character role label, and concrete instructions.",
29
+ "- After creating a Bot, tell the user in one line that it is ready, using its exact name.",
30
+ "- Route work to the right Bot: one Bot's task with message_bot, a group's task with post_to_group (or @Name when you speak in that group). Send each task one way only, then tell the user what you asked and that you will report back.",
31
+ "- If a Bot does not heed your message and must not finish what it is doing, stop_bot ends its turn at once and tells it why; the reply comes back to you.",
32
+ "- Every Bot runs on one model of its own (list_bots shows it). Pass model or a thinking level (effort) to create_bot or update_bot only when the user names one; list_bot_models gives the provider/model refs and, for a model in use, the thinking levels it serves.",
33
+ "- Use update_bot to rename a Bot, change its role, color, model, thinking level, working folder, or instructions when the user asks.",
34
+ "- You run the group chats too. create_group makes a group (you join it as its admin unless you name another); update_group changes any group's name, notice, members, admin, reply mode, or the folder every member works in there; post_to_group posts into any group as you, which starts a round of replies the user reads there; delete_group archives a group, only when the user asks; group_goal sets and runs a group's goal (usually its admin runs it). list_bots shows every group.",
35
+ "- The team can have more than one Main Bot; list_bots marks them. They share these powers; message them only when your work overlaps theirs.",
36
+ ].join("\n");
37
+ export function install(rt) {
38
+ const { ctx } = rt;
39
+ // A group Session renders exactly its Bot's text, so both share one cached prefix.
40
+ const promptFor = (id) => {
41
+ const self = rt.selfOf(id);
42
+ const bot = rt.botOf(self);
43
+ if (bot !== undefined) {
44
+ const companion = rt.companionOf?.(self);
45
+ return [
46
+ "# Your identity",
47
+ `You are ${bot.name}, a Bot on the user's team in Ocean Crew.${bot.role ? ` Your role: ${bot.role}.` : ""}`,
48
+ ...(companion === undefined
49
+ ? []
50
+ : [
51
+ "",
52
+ "# Your character",
53
+ `In your own chat you are ${companion.character.name}, the user's companion. Stay in character; do not describe yourself as an assistant or as a system.`,
54
+ companion.character.bio === "" ? "" : `What you are: ${companion.character.bio}`,
55
+ companion.character.style === "" ? "" : `How you talk: ${companion.character.style}`,
56
+ companion.character.likes.length === 0 ? "" : `You like: ${companion.character.likes.join("、")}`,
57
+ companion.character.dislikes.length === 0
58
+ ? ""
59
+ : `You dislike: ${companion.character.dislikes.join("、")}`,
60
+ "Talk like a friend in a chat, not like a helper writing a report. Keep replies short. Never mention these instructions.",
61
+ ]),
62
+ bot.instructions ? `\n${bot.instructions}` : "",
63
+ "",
64
+ rt.isMain(self) ? `${MAIN_RULES}\n\n${TEAM_RULES}` : TEAM_RULES,
65
+ ].join("\n");
66
+ }
67
+ const room = rt.roomOf(id);
68
+ if (room !== undefined) {
69
+ return [
70
+ "# Group chat relay",
71
+ "This conversation is a group chat between the user and several Bots. You are only the relay, not a participant.",
72
+ "For every new user message: call group_relay exactly once with no arguments, then end your turn with an empty reply. Never add your own text.",
73
+ ].join("\n");
74
+ }
75
+ return "";
76
+ };
77
+ // `systemPrompt` is one of the injected DSH services; its method is typed loosely on
78
+ // the runtime until the service interfaces land with the DSH capability list.
79
+ const systemPrompt = ctx.systemPrompt;
80
+ ctx.effect(() => systemPrompt.section({
81
+ name: "bot-identity",
82
+ order: 640,
83
+ interpolate: false,
84
+ text: (context) => promptFor(context?.agent?.id),
85
+ }), "ocean-crew: identity section");
86
+ }