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,155 @@
1
+ // Request identities: a request a Bot names itself is sent once, however often it repeats it.
2
+ //
3
+ // `message_bot` merges what the recipient has not read yet, but a request that was read
4
+ // and whose answer was lost could be sent again, and the work would be done twice. A
5
+ // caller that names its request (`request_id`) gets that guarantee: the name belongs to
6
+ // the caller and to the conversation the request was made from, what the request stands
7
+ // for is remembered with a fingerprint of what was asked, and the receipt of the first
8
+ // call is given back instead of a second delivery. The receipt is written before the
9
+ // message goes out, so a restart cannot turn a lost answer into a second delivery either;
10
+ // when the outcome of an admission is not known, the request is not sent again.
11
+ //
12
+ // Accepted identities stay with the team: expiring one would permit an old retry to
13
+ // repeat side effects. Removing receipts needs a separate, explicit retention policy.
14
+ import { createHash, randomUUID } from "node:crypto";
15
+ /** A request name this long is a mistake, not an identity. */
16
+ export const NAME_MAX = 200;
17
+ export function install(rt) {
18
+ // This run's name: a receipt left pending by another run has an unknown outcome.
19
+ const run = randomUUID();
20
+ const table = rt.state;
21
+ const receipts = () => {
22
+ table.requests ??= {};
23
+ return table.requests;
24
+ };
25
+ // Requests being admitted now, so that two at once admit one.
26
+ const inflight = new Map();
27
+ // What the request asked for, as a short hash: the same name with the same content is
28
+ // the same request, and the same name with other content is a mistake.
29
+ // The payload is the call's own argument object, so stringifying it gives a string.
30
+ const print = (payload) => createHash("sha256")
31
+ .update(JSON.stringify(payload))
32
+ .digest("hex");
33
+ // The name of a request in the caller's own space: its Bot, the conversation the
34
+ // request was made from, and the name the caller gave it. The Bot, not its Session: a
35
+ // Bot that moves to a fresh part of its conversation keeps its name.
36
+ const identity = ({ caller, context, name, payload }) => ({
37
+ key: `${caller}\u0000${context}\u0000${name}`,
38
+ print: print(payload),
39
+ });
40
+ // What a request that was admitted before means for the caller now: its receipt, a
41
+ // conflict, or an outcome that is not known. Undefined when it was never admitted.
42
+ const verdict = (request, record) => {
43
+ if (record.fingerprint !== request.print)
44
+ return { status: "conflict" };
45
+ if (record.outcome === "delivered") {
46
+ // The receipt is gone, but the name stays taken: it is not used again by accident.
47
+ return record.receipt === undefined ? { status: "expired" } : { status: "replay", receipt: record.receipt };
48
+ }
49
+ if (record.outcome === "uncertain")
50
+ return { status: "uncertain" };
51
+ // Admitted, not settled: the call is still going, or it was cut short.
52
+ return undefined;
53
+ };
54
+ // What is known about a request that was admitted before. Undefined when the request
55
+ // was never admitted.
56
+ const known = async (request) => {
57
+ const record = rt.own(receipts(), request.key);
58
+ if (record === undefined)
59
+ return undefined;
60
+ const seen = verdict(request, record);
61
+ if (seen !== undefined)
62
+ return seen;
63
+ // Admitted, not settled: the call is still going in this run, or another run left it
64
+ // in the air, and then its outcome is not known.
65
+ if (record.run !== run)
66
+ return { status: "uncertain" };
67
+ const promise = inflight.get(request.key);
68
+ if (promise === undefined)
69
+ return { status: "uncertain" };
70
+ await promise.catch(() => { });
71
+ const settled = rt.own(receipts(), request.key);
72
+ if (settled === undefined)
73
+ return undefined;
74
+ return verdict(request, settled) ?? { status: "uncertain" };
75
+ };
76
+ // Admits the request once and runs it. `work` sends the message and gives the receipt
77
+ // the caller gets. The receipt is written before the message goes out, so that a restart
78
+ // knows the request was admitted.
79
+ const admit = async (request, work) => {
80
+ // The receipt is looked for and written without an await in between, so that two
81
+ // calls at once cannot both admit the same request.
82
+ const record = rt.own(receipts(), request.key);
83
+ if (record !== undefined) {
84
+ const seen = verdict(request, record);
85
+ if (seen !== undefined)
86
+ return seen;
87
+ if (record.run !== run)
88
+ return { status: "uncertain" };
89
+ const promise = inflight.get(request.key);
90
+ if (promise === undefined)
91
+ return { status: "uncertain" };
92
+ await promise.catch(() => { });
93
+ // The attempt that was going on gave up before it sent anything (its receipt could
94
+ // not be saved), so the request is free to be admitted again.
95
+ if (rt.own(receipts(), request.key) === undefined)
96
+ return admit(request, work);
97
+ return known(request);
98
+ }
99
+ // A receipt that cannot be saved cannot stop a second delivery later.
100
+ if (rt.readOnly() !== undefined)
101
+ return { status: "readonly" };
102
+ const fresh = { fingerprint: request.print, outcome: "pending", at: Date.now(), run };
103
+ receipts()[request.key] = fresh;
104
+ const promise = (async () => {
105
+ try {
106
+ // Ordinary saves may be skipped when this host closes or loses the lock.
107
+ await rt.save({ required: true });
108
+ }
109
+ catch (error) {
110
+ delete receipts()[request.key];
111
+ rt.warn("ocean-crew: the receipt of the request was not saved: %s", error);
112
+ throw error;
113
+ }
114
+ try {
115
+ const receipt = await work();
116
+ if (request.unsent === true) {
117
+ // The work decided before anything went out: it is not a delivered
118
+ // receipt, so the request is free to be admitted again. The removal has
119
+ // to be saved before that is true: a leftover pending record stays.
120
+ delete receipts()[request.key];
121
+ try {
122
+ await rt.save({ required: true });
123
+ }
124
+ catch (error) {
125
+ fresh.outcome = "uncertain";
126
+ fresh.at = Date.now();
127
+ receipts()[request.key] = fresh;
128
+ rt.warn("ocean-crew: the removal of the request receipt was not saved: %s", error);
129
+ }
130
+ return receipt;
131
+ }
132
+ fresh.outcome = "delivered";
133
+ fresh.receipt = receipt;
134
+ fresh.at = Date.now();
135
+ await rt.save().catch(() => { });
136
+ return receipt;
137
+ }
138
+ catch (error) {
139
+ // The message may have gone out; it is not sent again.
140
+ fresh.outcome = "uncertain";
141
+ fresh.at = Date.now();
142
+ await rt.save().catch(() => { });
143
+ throw error;
144
+ }
145
+ })();
146
+ inflight.set(request.key, promise);
147
+ try {
148
+ return { status: "sent", receipt: await promise };
149
+ }
150
+ finally {
151
+ inflight.delete(request.key);
152
+ }
153
+ };
154
+ Object.assign(rt, { requestIdentity: identity, knownRequest: known, admitRequest: admit });
155
+ }
@@ -0,0 +1,364 @@
1
+ // Resume: Bot work that DeepSeek Harness dropped when it closed or restarted. DSH closes a
2
+ // turn it never finished as interrupted when the Session next opens, and a clean shutdown
3
+ // also cancels the messages still waiting in a Session's inbox; nothing would ever run
4
+ // either again, and whoever waited for them was not told. Ocean Crew notes each running
5
+ // Bot turn and each message it delivers until a turn takes it up, in inflight.json; what
6
+ // is still noted at the next start is picked up once.
7
+ //
8
+ // Settling a turn that ended while Ocean Crew was not
9
+ // or answered here.
10
+ import { randomUUID } from "node:crypto";
11
+ import { readFileSync } from "node:fs";
12
+ import { mkdir, writeFile } from "node:fs/promises";
13
+ import { join } from "node:path";
14
+ import { SOURCE_KIND } from "../core/constants.js";
15
+ import { listenGlobal } from "../core/events.js";
16
+ // Long enough for DSH to finish opening its workspaces after a start.
17
+ export const RESUME_DELAY_MS = 3000;
18
+ export const resumeText = (record) => [
19
+ "DeepSeek Harness restarted while you were working on this, so your last turn stopped before it finished.",
20
+ record.approval
21
+ ? `You were waiting for the user's approval to run ${record.approval.tool || "a tool"}${record.approval.reason ? ` (${record.approval.reason})` : ""}; that request is gone, so ask again if you still need it.`
22
+ : "",
23
+ "Check what is already done (files, commands, messages) before you repeat anything, then finish the task and give your reply.",
24
+ ]
25
+ .filter(Boolean)
26
+ .join(" ");
27
+ // The trigger fields a resumed turn needs to answer the same sender.
28
+ const triggerOf = (info) => ({
29
+ role: info.role,
30
+ ...(info.exchangeId ? { exchangeId: info.exchangeId } : {}),
31
+ ...(info.senderSessionId ? { senderSessionId: info.senderSessionId } : {}),
32
+ ...(info.roomId ? { roomId: info.roomId } : {}),
33
+ ...(info.work ? { work: info.work } : {}),
34
+ ...(info.audience ? { audience: info.audience } : {}),
35
+ ...(info.askedBy ? { askedBy: info.askedBy } : {}),
36
+ ...(info.senderRoomId ? { senderRoomId: info.senderRoomId } : {}),
37
+ });
38
+ const readNotes = (file) => {
39
+ try {
40
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
41
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
42
+ return { turns: object(parsed?.turns), queued: object(parsed?.queued) };
43
+ }
44
+ catch {
45
+ return { turns: {}, queued: {} };
46
+ }
47
+ };
48
+ export function install(rt) {
49
+ const { ctx, home } = rt;
50
+ const file = join(home, "inflight.json");
51
+ // A test shortens the wait; the team starts its pickup once DSH has opened its workspaces.
52
+ const delayMs = typeof rt.resumeDelayMs === "number" ? rt.resumeDelayMs : RESUME_DELAY_MS;
53
+ // What the last run left; read before this run notes anything.
54
+ let interrupted = readNotes(file);
55
+ let turns = {};
56
+ // A new delivery can persist before recovery runs; it must keep the old queue.
57
+ let queued = interrupted.queued;
58
+ let writing = Promise.resolve();
59
+ let stopped = false;
60
+ let latest;
61
+ let due = false;
62
+ const persist = () => {
63
+ // Only the host that saves the team runs its work again.
64
+ if (stopped || rt.readOnly() !== undefined)
65
+ return;
66
+ latest = JSON.stringify({ turns, queued });
67
+ // One write waits at a time and takes the latest notes, so a busy round does not
68
+ // write the file once per change.
69
+ if (due)
70
+ return;
71
+ due = true;
72
+ // Written in place: a rename over the file fails on Windows while anything reads
73
+ // it, and a torn write only loses what one restart would pick up.
74
+ writing = writing
75
+ .then(async () => {
76
+ due = false;
77
+ const snapshot = latest;
78
+ await mkdir(home, { recursive: true });
79
+ await writeFile(file, snapshot ?? "", "utf8");
80
+ })
81
+ .catch((error) => rt.warn("ocean-crew: noting running turns failed: %s", error));
82
+ };
83
+ const update = (id, change) => {
84
+ const next = change(turns[id]);
85
+ if (next === turns[id])
86
+ return;
87
+ turns = { ...turns };
88
+ if (next === undefined)
89
+ delete turns[id];
90
+ else
91
+ turns[id] = next;
92
+ persist();
93
+ };
94
+ const forgetQueued = (exchangeId) => {
95
+ if (exchangeId === undefined)
96
+ return;
97
+ for (const [sessionId, list] of Object.entries(queued)) {
98
+ const at = list.findIndex((item) => item.args.exchangeId === exchangeId);
99
+ if (at === -1)
100
+ continue;
101
+ const rest = list.toSpliced(at, 1);
102
+ queued = { ...queued };
103
+ if (rest.length === 0)
104
+ delete queued[sessionId];
105
+ else
106
+ queued[sessionId] = rest;
107
+ persist();
108
+ return;
109
+ }
110
+ };
111
+ const deliverOriginal = rt.deliver;
112
+ rt.deliver = async (args) => {
113
+ const noted = { ...args, exchangeId: args.exchangeId ?? randomUUID() };
114
+ const sessionId = noted.sessionId ?? rt.chatOf(noted.toId);
115
+ // Noted before it is sent: a turn may take it up before the send returns. Notes are
116
+ // kept whole; nothing waits out a delivery silently.
117
+ queued = { ...queued, [sessionId]: [...(queued[sessionId] ?? []), { at: Date.now(), args: noted }] };
118
+ persist();
119
+ try {
120
+ return await deliverOriginal(noted);
121
+ }
122
+ catch (error) {
123
+ // A delivery that never reached the inbox stays noted: the next start sends it
124
+ // again. One whose Bot is gone is dropped, since it can never be sent.
125
+ if (rt.botOf(noted.toId) === undefined)
126
+ forgetQueued(noted.exchangeId);
127
+ throw error;
128
+ }
129
+ };
130
+ // What a Session was sent and no turn has read yet.
131
+ rt.unreadOf = (sessionId) => (queued[sessionId] ?? []).map((item) => item.args);
132
+ rt.forgetDelivery = forgetQueued;
133
+ // A message is done with once a turn takes it up, or once it leaves the inbox untaken
134
+ // while Ocean Crew runs: the user stopped the Bot, or Ocean Crew moved or withdrew it.
135
+ listenGlobal(ctx, "agent/inbox/discarded", ({ message } = {}) => {
136
+ if (message?.source?.kind === SOURCE_KIND && message.source.exchangeId)
137
+ forgetQueued(message.source.exchangeId);
138
+ });
139
+ // Exchanges a turn took up since this start, until the resends are done, so a resend
140
+ // never repeats one.
141
+ let taken = Object.keys(interrupted.queued).length > 0 ? new Set() : undefined;
142
+ // The first turn event of each Session since this start, until the noted turns are
143
+ // picked up. A turn that ends, or still runs, before one starts here outlived the
144
+ // last run: only Ocean Crew restarted (the plugin reloaded) and DSH went on.
145
+ let firstTurn = Object.keys(interrupted.turns).length > 0 ? new Map() : undefined;
146
+ listenGlobal(ctx, "session/event", (session, event) => {
147
+ const id = session?.id;
148
+ if (id === undefined)
149
+ return;
150
+ if ((event.type === "turn/start" || event.type === "turn/end") && firstTurn?.has(id) === false) {
151
+ firstTurn.set(id, { type: event.type, turn: event.data?.turn, reason: event.data?.reason });
152
+ }
153
+ if (event.type === "user/message" && event.data?.source?.kind === SOURCE_KIND && event.data.source.exchangeId) {
154
+ taken?.add(event.data.source.exchangeId);
155
+ forgetQueued(event.data.source.exchangeId);
156
+ }
157
+ if (!rt.isBotSession(id))
158
+ return;
159
+ switch (event.type) {
160
+ case "turn/start": {
161
+ const owner = rt.groupOwners.get(id);
162
+ const botId = owner?.botId ?? rt.chatOwners.get(id);
163
+ // turns.js runs first and has already claimed or restored the trigger.
164
+ const info = rt.live?.get(id)?.info;
165
+ update(id, () => ({
166
+ botId: botId,
167
+ ...(owner ? { roomId: owner.roomId } : {}),
168
+ since: event.time ?? Date.now(),
169
+ ...(info !== undefined ? { trigger: triggerOf(info) } : {}),
170
+ }));
171
+ break;
172
+ }
173
+ case "user/message": {
174
+ if (event.data?.source?.kind !== SOURCE_KIND)
175
+ break;
176
+ const info = rt.live?.get(id)?.info;
177
+ update(id, (record) => record === undefined || record.trigger !== undefined || info === undefined
178
+ ? record
179
+ : { ...record, trigger: triggerOf(info), ...(info.resumed ? { resumed: true } : {}) });
180
+ break;
181
+ }
182
+ case "turn/end": {
183
+ // DSH stops every turn as it shuts down; that one is picked up at the next start.
184
+ const reason = event.data?.reason;
185
+ if (reason?.kind === "aborted" && reason.reason?.kind === "disposed")
186
+ break;
187
+ update(id, () => undefined);
188
+ break;
189
+ }
190
+ }
191
+ });
192
+ // An approval the restart drops is named when the turn is picked up.
193
+ rt.noteApproval = (sessionId, approval) => update(sessionId, (record) => {
194
+ if (record === undefined)
195
+ return record;
196
+ if (approval === undefined) {
197
+ const { approval: _gone, ...rest } = record;
198
+ return rest;
199
+ }
200
+ return { ...record, approval };
201
+ });
202
+ async function resumeTurn(sessionId, record) {
203
+ const bot = rt.botOf(record.botId);
204
+ if (bot === undefined)
205
+ return;
206
+ const text = resumeText(record);
207
+ if (record.roomId !== undefined) {
208
+ const room = rt.roomOf(record.roomId);
209
+ if (room === undefined || !room.members.includes(bot.id))
210
+ return;
211
+ await rt.postToRoom?.(room, bot, "", {
212
+ resumed: true,
213
+ quiet: true,
214
+ ...(record.resumed ? { again: true } : {}),
215
+ });
216
+ // A turn already picked up once and cut off again stays stopped: a restart loop
217
+ // must not run it forever.
218
+ if (record.resumed)
219
+ return;
220
+ await rt.deliver({
221
+ toId: bot.id,
222
+ sessionId: room.sessions?.[bot.id] ?? sessionId,
223
+ role: "room",
224
+ roomId: room.id,
225
+ note: "picking up after a restart",
226
+ resumed: true,
227
+ text,
228
+ ...(record.trigger?.askedBy ? { askedBy: record.trigger.askedBy } : {}),
229
+ });
230
+ return;
231
+ }
232
+ if (record.resumed)
233
+ return;
234
+ const trigger = record.trigger;
235
+ if ((trigger?.role === "request" || trigger?.role === "stopped") &&
236
+ trigger.senderSessionId &&
237
+ trigger.audience !== "user" &&
238
+ rt.botOf(trigger.senderSessionId)) {
239
+ // The sender still waits for this turn's answer, so it goes on under the same exchange.
240
+ await rt.deliver({
241
+ fromId: trigger.senderSessionId,
242
+ toId: bot.id,
243
+ role: trigger.role,
244
+ ...(trigger.exchangeId ? { exchangeId: trigger.exchangeId } : {}),
245
+ ...(trigger.senderRoomId ? { fromRoomId: trigger.senderRoomId } : {}),
246
+ resumed: true,
247
+ text,
248
+ });
249
+ return;
250
+ }
251
+ // A turn that went on with work another Bot asked for still owes that Bot its answer.
252
+ await rt.deliver({
253
+ toId: bot.id,
254
+ role: "resume",
255
+ resumed: true,
256
+ text,
257
+ ...(trigger?.work ? { work: trigger.work } : {}),
258
+ });
259
+ }
260
+ // Where a queued note goes now: its Session if it still is one, else the current
261
+ // Session of its Bot, or of its group when the message went to one.
262
+ const sessionFor = (sessionId, args) => rt.isBotSession(sessionId)
263
+ ? sessionId
264
+ : args?.roomId === undefined
265
+ ? rt.chatOf(args?.toId)
266
+ : rt.roomOf(args.roomId)?.sessions?.[args.toId];
267
+ const resolveAgentOf = async (sessionId) => {
268
+ try {
269
+ return await rt.resolveAgent?.(sessionId);
270
+ }
271
+ catch {
272
+ return undefined;
273
+ }
274
+ };
275
+ // A hard stop keeps the inbox, which the Session runs once it wakes; only what DSH
276
+ // cancelled is sent again. The notes stay queued until a turn takes the messages up,
277
+ // so a send that fails here, or a Session that cannot be opened, leaves them for the
278
+ // next start instead of losing them.
279
+ async function resendQueued(sessionId, list) {
280
+ const fresh = list.filter((item) => rt.botOf(item.args?.toId) !== undefined &&
281
+ sessionFor(sessionId, item.args) !== undefined &&
282
+ taken?.has(item.args.exchangeId) !== true);
283
+ if (fresh.length === 0)
284
+ return;
285
+ const target = sessionFor(sessionId, fresh[0].args);
286
+ const agent = await rt.resolveAgent(target);
287
+ const waiting = new Set([...(agent.inbox?.nextStep ?? []), ...(agent.inbox?.nextTurn ?? [])].map((message) => message.source?.exchangeId));
288
+ for (const { args } of fresh) {
289
+ if (waiting.has(args.exchangeId))
290
+ continue;
291
+ if (taken?.has(args.exchangeId) === true) {
292
+ forgetQueued(args.exchangeId);
293
+ continue;
294
+ }
295
+ // A request that waited through a restart reaches its target late: the work it is
296
+ // for is marked, so the answer that comes back says so.
297
+ if (args.role === "request" || args.role === "stopped")
298
+ rt.lateWork?.(args.exchangeId);
299
+ await deliverOriginal({ ...args, sessionId: sessionFor(sessionId, args), steer: false, resent: true }).catch((error) => rt.warn("ocean-crew: sending again what %s was sent failed: %s", sessionId, error));
300
+ }
301
+ }
302
+ async function resumeAll() {
303
+ await rt.load();
304
+ if (rt.readOnly() !== undefined)
305
+ return;
306
+ const { turns: noted, queued: dropped } = interrupted;
307
+ interrupted = { turns: {}, queued: {} };
308
+ // What the last run still had on the way is noted again first, under the Session it
309
+ // would go to now: nothing is cleared before it is handed over. A Bot that is gone
310
+ // takes its notes with it; what a turn already read here is done with.
311
+ const pending = queued;
312
+ queued = {};
313
+ for (const [oldId, list] of Object.entries(pending)) {
314
+ if (!Array.isArray(list))
315
+ continue;
316
+ for (const item of list) {
317
+ if (item?.args?.exchangeId === undefined ||
318
+ taken?.has(item.args.exchangeId) === true ||
319
+ rt.botOf(item.args.toId) === undefined)
320
+ continue;
321
+ const key = sessionFor(oldId, item.args) ?? oldId;
322
+ queued = { ...queued, [key]: [...(queued[key] ?? []), item] };
323
+ }
324
+ }
325
+ persist();
326
+ // Agents and inboxes are read before anything wakes their Sessions.
327
+ const cut = [];
328
+ for (const [sessionId, record] of Object.entries(noted)) {
329
+ const first = firstTurn?.get(sessionId);
330
+ if (first?.type === "turn/end") {
331
+ rt.warn("ocean-crew: the turn of %s ended while Ocean Crew was not watching it, so its result could not be reconciled", sessionId);
332
+ continue;
333
+ }
334
+ // Still running: noted again, as if it had started here.
335
+ if (first === undefined && (await resolveAgentOf(sessionId))?.status === "running")
336
+ update(sessionId, () => record);
337
+ else
338
+ cut.push([sessionId, record]);
339
+ }
340
+ firstTurn = undefined;
341
+ for (const [sessionId, list] of Object.entries(dropped)) {
342
+ if (!Array.isArray(list))
343
+ continue;
344
+ await resendQueued(sessionId, list).catch((error) => rt.warn("ocean-crew: sending again what %s was sent failed: %s", sessionId, error));
345
+ }
346
+ taken = undefined;
347
+ for (const [sessionId, record] of cut) {
348
+ await resumeTurn(sessionId, record).catch((error) => rt.warn("ocean-crew: picking up the turn of %s failed: %s", sessionId, error));
349
+ }
350
+ }
351
+ ctx.effect(() => {
352
+ const pending = Object.keys(interrupted.turns).length > 0 || Object.keys(interrupted.queued).length > 0;
353
+ const timer = pending
354
+ ? setTimeout(() => void resumeAll().catch((error) => rt.warn("ocean-crew: picking up interrupted work failed: %s", error)), delayMs)
355
+ : undefined;
356
+ timer?.unref?.();
357
+ // What the turns stopped by this shutdown left stays as last noted.
358
+ return () => {
359
+ stopped = true;
360
+ clearTimeout(timer);
361
+ return writing;
362
+ };
363
+ }, "ocean-crew: resume interrupted turns");
364
+ }