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,702 @@
1
+ // Secrets: keys the user types into a card for a Bot. A value lives only in
2
+ // secrets.json (mode 600) and in this process; Bots use it as $DSH_SECRET_<NAME> in
3
+ // their shell, tool results lose it before they are saved, and every model request has
4
+ // it replaced by [secret:<NAME>] before it leaves.
5
+ //
6
+ // The request/answer flow, the redaction rules and the file handling are the
7
+ // The module publishes the same runtime members: secretsView,
8
+ // secretValue, canUseSecret, secretEndpoint, forgetBotSecrets, loadSecrets and
9
+ // redactSecrets; the request_secret and list_secrets tools are registered here, as the
10
+ import { randomUUID } from "node:crypto";
11
+ import { chmodSync, copyFileSync, readFileSync } from "node:fs";
12
+ import { chmod, mkdir, unlink, writeFile } from "node:fs/promises";
13
+ import { join } from "node:path";
14
+ import { defineTool } from "@deepseek-ai/dsh-tools";
15
+ import { replaceFile } from "../core/files.js";
16
+ export const SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
17
+ export const ENV_PREFIX = "DSH_SECRET_";
18
+ // A short value (a PIN, a short password) would also hit ordinary words if it were
19
+ // replaced wherever it appears, so below WHOLE_VALUE it is replaced only where it
20
+ // stands alone: no letter or digit right before or after it.
21
+ export const MIN_VALUE = 4;
22
+ export const WHOLE_VALUE = 8;
23
+ export const MAX_VALUE = 16384;
24
+ const MAX_REQUESTS = 20;
25
+ const USED_SAVE_MS = 5000;
26
+ export const envName = (name) => `${ENV_PREFIX}${name}`;
27
+ export const canUse = (secret, botId) => secret !== undefined &&
28
+ botId !== undefined &&
29
+ (secret.scope === "all" || (Array.isArray(secret.scope) && secret.scope.includes(botId)));
30
+ export function normalizeName(raw) {
31
+ return String(raw ?? "")
32
+ .trim()
33
+ .replace(/^\$(env:)?/i, "")
34
+ .replace(/^DSH_SECRET_/i, "")
35
+ .replace(/[\s-]+/g, "_")
36
+ .toUpperCase();
37
+ }
38
+ // encodeURIComponent leaves ' as is, but new URL() turns it into %27 in a query, so the
39
+ // URL sent out would hold a form the redactor does not know. Encoding these characters
40
+ // too keeps the sent URL equal to the text the redactor looks for.
41
+ export const encodeUrlComponent = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
42
+ // One function that replaces every known value in a string, longest first so a value
43
+ // that contains another is replaced whole. JSON-escaped and URL-encoded forms are
44
+ // covered too.
45
+ export function redactor(entries) {
46
+ const pairs = [];
47
+ for (const { name, value } of entries) {
48
+ if (typeof value !== "string" || value.length < MIN_VALUE)
49
+ continue;
50
+ const label = `[secret:${name}]`;
51
+ const short = value.length < WHOLE_VALUE;
52
+ pairs.push([value, label, short]);
53
+ const escaped = JSON.stringify(value).slice(1, -1);
54
+ if (escaped !== value)
55
+ pairs.push([escaped, label, short]);
56
+ // encodeURIComponent throws on a lone surrogate; such a value cannot sit in a URL anyway.
57
+ const encoded = value.isWellFormed() ? encodeUrlComponent(value) : value;
58
+ if (encoded !== value && encoded !== escaped)
59
+ pairs.push([encoded, label, short]);
60
+ }
61
+ pairs.sort((a, b) => b[0].length - a[0].length);
62
+ if (pairs.length === 0)
63
+ return (text) => text;
64
+ // One pass, so a label already written is never matched again.
65
+ const labels = new Map();
66
+ for (const [value, label] of pairs)
67
+ if (!labels.has(value))
68
+ labels.set(value, label);
69
+ const quote = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
70
+ const pattern = new RegExp(pairs
71
+ .map(([value, , short]) => (short ? `(?<![\\p{L}\\p{N}])${quote(value)}(?![\\p{L}\\p{N}])` : quote(value)))
72
+ .join("|"), "gu");
73
+ return (text) => {
74
+ if (typeof text !== "string" || !pairs.some(([value]) => text.includes(value)))
75
+ return text;
76
+ return text.replace(pattern, (match) => labels.get(match) ?? match);
77
+ };
78
+ }
79
+ // Returns the same reference when nothing changed, so callers can tell cheaply.
80
+ export function redactDeep(value, redact) {
81
+ if (typeof value === "string")
82
+ return redact(value);
83
+ if (Array.isArray(value)) {
84
+ let changed = false;
85
+ const next = value.map((item) => {
86
+ const replaced = redactDeep(item, redact);
87
+ if (replaced !== item)
88
+ changed = true;
89
+ return replaced;
90
+ });
91
+ return (changed ? next : value);
92
+ }
93
+ if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
94
+ let changed = false;
95
+ const next = {};
96
+ for (const [key, item] of Object.entries(value)) {
97
+ const replaced = redactDeep(item, redact);
98
+ if (replaced !== item)
99
+ changed = true;
100
+ next[key] = replaced;
101
+ }
102
+ return (changed ? next : value);
103
+ }
104
+ return value;
105
+ }
106
+ const output = {
107
+ schema: { type: "string" },
108
+ render: (_args, value) => [
109
+ { type: "text", text: String(value) },
110
+ ],
111
+ };
112
+ // The DSH package compiles the author schema into the served JSON schema; runtime.ts's
113
+ // TeamTool bridge is loose, so the one cast lives here.
114
+ const tool = (options) => defineTool({ ...options, output });
115
+ export function install(rt) {
116
+ const { ctx, home, state } = rt;
117
+ const path = join(home, "secrets.json");
118
+ const secrets = new Map();
119
+ let loaded = null;
120
+ let writing = Promise.resolve();
121
+ let redact = (text) => text;
122
+ let refreshEnv = () => { };
123
+ let blocked;
124
+ let loadedReadOnly = false;
125
+ // Reading the pending cards never creates the table; only a Bot asking creates it
126
+ const storedRequests = () => (state.secretRequests ?? {});
127
+ const changed = () => {
128
+ redact = redactor([...secrets.values()]);
129
+ refreshEnv();
130
+ rt.secretsChanged?.();
131
+ };
132
+ // Error messages from JSON.parse quote the file, so only the code or name is logged.
133
+ const reason = (error) => {
134
+ const code = error?.code;
135
+ if (typeof code === "string")
136
+ return code;
137
+ const name = error?.name;
138
+ return typeof name === "string" ? name : "error";
139
+ };
140
+ // While another dsh holds the team, that host writes secrets.json, so a reading host
141
+ // reads it again each time; a copy read then is also read again after taking over,
142
+ // before this host saves anything.
143
+ const loadSecrets = () => {
144
+ if (loaded !== null && (loadedReadOnly || rt.readOnly() !== undefined || blocked !== undefined))
145
+ loaded = null;
146
+ loaded ??= readSecrets();
147
+ return loaded;
148
+ };
149
+ // Synchronous on purpose: a shell resolves its environment without an await, so the
150
+ // map must be full before the first resolve after a start reads it.
151
+ const readSecrets = async () => {
152
+ loadedReadOnly = rt.readOnly() !== undefined;
153
+ let contents;
154
+ try {
155
+ contents = readFileSync(path, "utf8");
156
+ }
157
+ catch (error) {
158
+ if (error.code === "ENOENT") {
159
+ blocked = undefined;
160
+ secrets.clear();
161
+ }
162
+ else {
163
+ blocked = reason(error);
164
+ rt.warn("ocean-crew: unreadable secrets file %s (%s)", path, blocked);
165
+ }
166
+ changed();
167
+ return;
168
+ }
169
+ let parsed;
170
+ try {
171
+ parsed = JSON.parse(contents);
172
+ }
173
+ catch {
174
+ parsed = null;
175
+ }
176
+ if (parsed === null || typeof parsed !== "object" || !Array.isArray(parsed.secrets)) {
177
+ // A file that is not a secrets file is kept aside, like a broken state.json, then
178
+ // the store goes on with an empty one.
179
+ const backup = `${path}.broken-${Date.now()}`;
180
+ try {
181
+ copyFileSync(path, backup);
182
+ blocked = undefined;
183
+ secrets.clear();
184
+ rt.warn("ocean-crew: unreadable secrets file %s; backed up as %s", path, backup);
185
+ }
186
+ catch (error) {
187
+ blocked = reason(error);
188
+ rt.warn("ocean-crew: unreadable secrets file %s; backup failed: %s", path, error);
189
+ }
190
+ changed();
191
+ return;
192
+ }
193
+ blocked = undefined;
194
+ secrets.clear();
195
+ for (const raw of parsed.secrets) {
196
+ const entry = (raw ?? {});
197
+ if (!SECRET_NAME.test(entry.name ?? "") || typeof entry.value !== "string")
198
+ continue;
199
+ const name = entry.name;
200
+ secrets.set(name, {
201
+ name,
202
+ value: entry.value,
203
+ purpose: typeof entry.purpose === "string" ? entry.purpose : "",
204
+ scope: entry.scope === "all"
205
+ ? "all"
206
+ : Array.isArray(entry.scope)
207
+ ? entry.scope.filter((id) => typeof id === "string")
208
+ : "all",
209
+ requestedBy: typeof entry.requestedBy === "string" ? entry.requestedBy : null,
210
+ createdAt: Number(entry.createdAt) || Date.now(),
211
+ updatedAt: Number(entry.updatedAt) || Date.now(),
212
+ ...(Number.isFinite(entry.lastUsedAt) ? { lastUsedAt: entry.lastUsedAt } : {}),
213
+ });
214
+ }
215
+ if (!loadedReadOnly)
216
+ try {
217
+ chmodSync(path, 0o600);
218
+ }
219
+ catch {
220
+ // The file stays readable; a mode that cannot change is not an error here.
221
+ }
222
+ changed();
223
+ };
224
+ // Resolves once secrets.json holds the current map; rejects when the write failed.
225
+ const persist = () => {
226
+ if (blocked !== undefined)
227
+ return Promise.reject(new Error(`The secrets file ${path} could not be read (${blocked}). Ocean Crew does not change it; fix or move the file and reload.`));
228
+ const readOnly = rt.readOnly();
229
+ if (readOnly !== undefined)
230
+ return Promise.reject(new Error(readOnly));
231
+ const snapshot = JSON.stringify({ version: 1, secrets: [...secrets.values()] }, null, 2);
232
+ const job = writing.then(async () => {
233
+ await mkdir(home, { recursive: true });
234
+ const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;
235
+ try {
236
+ await writeFile(temp, snapshot, { encoding: "utf8", mode: 0o600 });
237
+ await chmod(temp, 0o600);
238
+ await replaceFile(temp, path);
239
+ }
240
+ catch (error) {
241
+ await unlink(temp).catch(() => undefined);
242
+ throw error;
243
+ }
244
+ });
245
+ writing = job.catch((error) => rt.warn("ocean-crew: secrets write failed (%s)", reason(error)));
246
+ return job;
247
+ };
248
+ let usedTimer = null;
249
+ const noteUsed = () => {
250
+ if (usedTimer !== null)
251
+ return;
252
+ usedTimer = setTimeout(() => {
253
+ usedTimer = null;
254
+ if (loadedReadOnly || rt.readOnly() !== undefined || blocked !== undefined)
255
+ return;
256
+ void persist()
257
+ .then(() => rt.save())
258
+ .catch(() => undefined);
259
+ }, USED_SAVE_MS);
260
+ usedTimer.unref?.();
261
+ };
262
+ // A Bot's pending secret cards, keyed by its id. A key that is not a real Bot (and
263
+ // never an inherited name like "__proto__", which a plain assignment would not even
264
+ // set as a key) gets a throwaway list instead of a stored one.
265
+ const requestsOf = (botId) => {
266
+ if (rt.botOf(botId) === undefined) {
267
+ const known = storedRequests();
268
+ if (!Object.hasOwn(known, botId))
269
+ return [];
270
+ if (known[botId] === undefined)
271
+ known[botId] = [];
272
+ return known[botId];
273
+ }
274
+ const team = state;
275
+ team.secretRequests ??= {};
276
+ const requests = team.secretRequests;
277
+ if (requests[botId] === undefined)
278
+ requests[botId] = [];
279
+ return requests[botId];
280
+ };
281
+ const findRequest = (id) => {
282
+ for (const [botId, list] of Object.entries(storedRequests())) {
283
+ const request = list.find((entry) => entry.id === id);
284
+ if (request !== undefined)
285
+ return { botId, request };
286
+ }
287
+ return undefined;
288
+ };
289
+ const trimRequests = (list) => {
290
+ while (list.length > MAX_REQUESTS) {
291
+ const settled = list.findIndex((entry) => entry.status !== "pending");
292
+ list.splice(settled === -1 ? 0 : settled, 1);
293
+ }
294
+ };
295
+ const scopeText = (scope) => {
296
+ if (scope === "all")
297
+ return "every Bot";
298
+ const names = scope.map((id) => rt.botOf(id)?.name).filter((name) => Boolean(name));
299
+ return names.length === 0 ? "no Bot" : names.join(", ");
300
+ };
301
+ const usage = (name) => `$${envName(name)} in bash, or $env:${envName(name)} in PowerShell`;
302
+ const tell = async (botId, text) => {
303
+ if (rt.botOf(botId) === undefined)
304
+ return;
305
+ await rt
306
+ .deliver({ toId: botId, role: "secret", text })
307
+ .catch((error) => rt.warn("ocean-crew: secret note to %s failed: %s", botId, error));
308
+ };
309
+ const savedNote = (name, lead) => [
310
+ `${lead} Use it as ${usage(name)}.`,
311
+ "You cannot see the value. Never print, echo, or log it, and never ask the user to paste it into the chat. Carry on with what you needed it for.",
312
+ ].join(" ");
313
+ function settle(_botId, request, status) {
314
+ request.status = status;
315
+ request.settledAt = Date.now();
316
+ if (status === "saved" || status === "allowed")
317
+ request.scope = secrets.get(request.name)?.scope ?? "all";
318
+ }
319
+ // After any change to `name`, every pending card for it either resolves (its Bot can
320
+ // use the key now) or shows the form that still applies.
321
+ function reconcile(name, notes, except) {
322
+ const secret = secrets.get(name);
323
+ for (const [botId, list] of Object.entries(storedRequests())) {
324
+ for (const request of list) {
325
+ if (request.status !== "pending" || request.name !== name || request === except)
326
+ continue;
327
+ if (canUse(secret, botId)) {
328
+ settle(botId, request, "saved");
329
+ notes.push([botId, savedNote(name, `The user saved ${name}, and you may use it now.`)]);
330
+ }
331
+ else {
332
+ request.kind = secret ? "allow" : "fill";
333
+ }
334
+ }
335
+ }
336
+ }
337
+ async function commit(notes) {
338
+ changed();
339
+ await persist();
340
+ await rt.save();
341
+ for (const [botId, text] of notes)
342
+ await tell(botId, text);
343
+ }
344
+ const cleanValue = (raw) => {
345
+ if (typeof raw !== "string")
346
+ throw new Error("Type the key first");
347
+ const value = raw.trim();
348
+ if (value.length < MIN_VALUE)
349
+ throw new Error(`A key must have at least ${MIN_VALUE} characters`);
350
+ if (value.length > MAX_VALUE)
351
+ throw new Error(`A key can have at most ${MAX_VALUE} characters`);
352
+ return value;
353
+ };
354
+ const cleanScope = (raw) => {
355
+ if (raw === "all")
356
+ return "all";
357
+ if (!Array.isArray(raw))
358
+ throw new Error("Choose every Bot or a list of Bots");
359
+ return [...new Set(raw.filter((id) => typeof id === "string" && rt.botOf(id) !== undefined))];
360
+ };
361
+ const pendingRequest = (id) => {
362
+ const found = findRequest(String(id ?? ""));
363
+ if (found === undefined)
364
+ throw new Error("This request is gone");
365
+ if (found.request.status !== "pending")
366
+ throw new Error("This request was already answered");
367
+ return found;
368
+ };
369
+ const secretView = (secret) => ({
370
+ name: secret.name,
371
+ purpose: secret.purpose,
372
+ scope: secret.scope,
373
+ requestedBy: secret.requestedBy,
374
+ createdAt: secret.createdAt,
375
+ updatedAt: secret.updatedAt,
376
+ ...(secret.lastUsedAt !== undefined ? { lastUsedAt: secret.lastUsedAt } : {}),
377
+ });
378
+ const secretsView = () => [...secrets.values()].sort((a, b) => a.name.localeCompare(b.name)).map(secretView);
379
+ const endpoints = {
380
+ // From a card (requestId) or from the settings page (name).
381
+ "secret-set": async (body) => {
382
+ const value = cleanValue(body.value);
383
+ const now = Date.now();
384
+ const notes = [];
385
+ if (body.requestId !== undefined) {
386
+ const { botId, request } = pendingRequest(body.requestId);
387
+ const existing = secrets.get(request.name);
388
+ let scope;
389
+ if (existing === undefined || request.kind === "fill")
390
+ scope = body.scope === "bot" ? [botId] : "all";
391
+ else
392
+ scope = existing.scope === "all" ? "all" : [...new Set([...existing.scope, botId])];
393
+ secrets.set(request.name, {
394
+ name: request.name,
395
+ value,
396
+ purpose: existing?.purpose || request.purpose,
397
+ scope,
398
+ requestedBy: existing?.requestedBy ?? botId,
399
+ createdAt: existing?.createdAt ?? now,
400
+ updatedAt: now,
401
+ ...(existing?.lastUsedAt !== undefined ? { lastUsedAt: existing.lastUsedAt } : {}),
402
+ });
403
+ settle(botId, request, "saved");
404
+ notes.push([botId, savedNote(request.name, `The user saved ${request.name} for ${scopeText(scope)}.`)]);
405
+ reconcile(request.name, notes, request);
406
+ await commit(notes);
407
+ return secretView(secrets.get(request.name));
408
+ }
409
+ const name = normalizeName(body.name);
410
+ if (!SECRET_NAME.test(name))
411
+ throw new Error("A name uses capitals, digits, and underscores, and starts with a letter");
412
+ const existing = secrets.get(name);
413
+ secrets.set(name, {
414
+ name,
415
+ value,
416
+ purpose: typeof body.purpose === "string" && body.purpose.trim() !== ""
417
+ ? body.purpose.trim().slice(0, 300)
418
+ : (existing?.purpose ?? ""),
419
+ scope: body.scope !== undefined ? cleanScope(body.scope) : (existing?.scope ?? "all"),
420
+ requestedBy: existing?.requestedBy ?? null,
421
+ createdAt: existing?.createdAt ?? now,
422
+ updatedAt: now,
423
+ ...(existing?.lastUsedAt !== undefined ? { lastUsedAt: existing.lastUsedAt } : {}),
424
+ });
425
+ reconcile(name, notes);
426
+ await commit(notes);
427
+ return secretView(secrets.get(name));
428
+ },
429
+ "secret-allow": async (body) => {
430
+ const { botId, request } = pendingRequest(body.requestId);
431
+ const secret = secrets.get(request.name);
432
+ if (secret === undefined)
433
+ throw new Error(`${request.name} is not saved yet`);
434
+ if (!canUse(secret, botId)) {
435
+ const current = secret.scope === "all" ? [] : secret.scope;
436
+ secret.scope = [...new Set([...current, botId])];
437
+ }
438
+ secret.updatedAt = Date.now();
439
+ settle(botId, request, "allowed");
440
+ const notes = [
441
+ [botId, savedNote(request.name, `The user let you use ${request.name}.`)],
442
+ ];
443
+ reconcile(request.name, notes, request);
444
+ await commit(notes);
445
+ return secretView(secret);
446
+ },
447
+ "secret-cancel": async (body) => {
448
+ const { botId, request } = pendingRequest(body.requestId);
449
+ settle(botId, request, "canceled");
450
+ await rt.save();
451
+ await tell(botId, `The user canceled your request for ${request.name}. Do not ask for it again unless the user brings it up; carry on without it, or tell the user what you cannot do without it.`);
452
+ return true;
453
+ },
454
+ "secret-update": async (body) => {
455
+ const secret = secrets.get(normalizeName(body.name));
456
+ if (secret === undefined)
457
+ throw new Error("No such key");
458
+ if (body.scope !== undefined)
459
+ secret.scope = cleanScope(body.scope);
460
+ if (typeof body.purpose === "string")
461
+ secret.purpose = body.purpose.trim().slice(0, 300);
462
+ secret.updatedAt = Date.now();
463
+ const notes = [];
464
+ reconcile(secret.name, notes);
465
+ await commit(notes);
466
+ return secretView(secret);
467
+ },
468
+ "secret-delete": async (body) => {
469
+ const name = normalizeName(body.name);
470
+ if (!secrets.delete(name))
471
+ throw new Error("No such key");
472
+ const notes = [];
473
+ reconcile(name, notes);
474
+ await commit(notes);
475
+ return true;
476
+ },
477
+ };
478
+ async function secretEndpoint(endpoint, body) {
479
+ await loadSecrets();
480
+ return endpoints[endpoint](body ?? {});
481
+ }
482
+ // A deleted Bot leaves every list it was on, and its cards go with it.
483
+ async function forgetBotSecrets(botId) {
484
+ await loadSecrets();
485
+ const requests = state.secretRequests;
486
+ if (requests !== undefined)
487
+ delete requests[botId];
488
+ let touched = false;
489
+ for (const secret of secrets.values()) {
490
+ if (Array.isArray(secret.scope) && secret.scope.includes(botId)) {
491
+ secret.scope = secret.scope.filter((id) => id !== botId);
492
+ touched = true;
493
+ }
494
+ }
495
+ if (touched) {
496
+ changed();
497
+ await persist().catch(() => undefined);
498
+ }
499
+ }
500
+ const callerOf = (exec) => rt.selfOf(exec.agent?.session?.header?.id ?? exec.agent?.id);
501
+ const addTool = (definition) => {
502
+ if (typeof rt.addTeamTool === "function")
503
+ rt.addTeamTool(definition);
504
+ else
505
+ rt.teamTools.push(definition);
506
+ };
507
+ addTool(tool({
508
+ name: "request_secret",
509
+ description: "Ask the user for a key, token, or password through a secure card in your own chat. The user types it into the card; you never see the value. It reaches your shell as an environment variable. When the key is already saved for you, this only tells you its variable. Showing a card ends your turn; a note arrives when the user saves or cancels.",
510
+ parameters: {
511
+ name: {
512
+ type: "string",
513
+ required: true,
514
+ description: "Key name in capitals, digits, and underscores, e.g. GITHUB_TOKEN",
515
+ },
516
+ purpose: {
517
+ type: "string",
518
+ required: true,
519
+ description: "One short line for the user: what you need it for",
520
+ },
521
+ },
522
+ execute: async (args, exec) => {
523
+ await rt.load();
524
+ await loadSecrets();
525
+ const id = exec.agent?.id;
526
+ const bot = rt.botOf(callerOf(exec));
527
+ if (bot === undefined)
528
+ return "Only Bots on the team can use request_secret.";
529
+ const name = normalizeName(args.name);
530
+ if (!SECRET_NAME.test(name))
531
+ return "Name the key with capitals, digits, and underscores, starting with a letter (for example GITHUB_TOKEN).";
532
+ const secret = secrets.get(name);
533
+ if (canUse(secret, bot.id))
534
+ return `${name} is already saved and you may use it: ${usage(name)}. You cannot see the value; never print it.`;
535
+ if (rt.groupOwners.has(id ?? ""))
536
+ return "Secret cards only work in your own chat. Tell the group you will ask the user in your own chat, and call request_secret there.";
537
+ if (!rt.chatOwners.has(id ?? ""))
538
+ return "Secret cards only work in your current own chat.";
539
+ const readOnly = rt.readOnly();
540
+ if (readOnly !== undefined)
541
+ return `No card can be shown now. ${readOnly}`;
542
+ const list = requestsOf(bot.id);
543
+ const now = Date.now();
544
+ for (const request of list) {
545
+ if (request.status === "pending" && request.name === name) {
546
+ request.status = "canceled";
547
+ request.settledAt = now;
548
+ }
549
+ }
550
+ list.push({
551
+ id: randomUUID(),
552
+ ...(exec.callId ? { callId: exec.callId } : {}),
553
+ sessionId: id,
554
+ name,
555
+ purpose: String(args.purpose ?? "")
556
+ .trim()
557
+ .slice(0, 300),
558
+ kind: secret ? "allow" : "fill",
559
+ status: "pending",
560
+ askedAt: now,
561
+ });
562
+ trimRequests(list);
563
+ await rt.save();
564
+ exec.concludeTurn?.();
565
+ return secret
566
+ ? `The card asking the user to let you use ${name} is on screen. A note arrives when the user answers; you will not see the value.`
567
+ : `The card asking the user for ${name} is on screen. A note arrives when the user saves or cancels; you will not see the value.`;
568
+ },
569
+ }));
570
+ addTool(tool({
571
+ name: "list_secrets",
572
+ description: "List the keys the user saved for the team: name, purpose, which Bots may use them, and whether you may. Values are never shown.",
573
+ parameters: {},
574
+ execute: async (_args, exec) => {
575
+ await rt.load();
576
+ await loadSecrets();
577
+ const self = callerOf(exec);
578
+ if (rt.botOf(self) === undefined)
579
+ return "Only Bots on the team can use list_secrets.";
580
+ if (secrets.size === 0)
581
+ return "No keys are saved yet. Ask for one with request_secret.";
582
+ return [
583
+ "Saved keys (values are never shown):",
584
+ ...secretsView().map((secret) => `- ${secret.name}${secret.purpose ? ` — ${secret.purpose}` : ""} — for ${scopeText(secret.scope)} — ${canUse(secrets.get(secret.name), self) ? `you may use it as $${envName(secret.name)}` : "you may not use it; ask with request_secret"}`),
585
+ ].join("\n");
586
+ },
587
+ }));
588
+ // Tool results lose the values before the registry renders and saves them. Every
589
+ // field is redacted — a wrapper further out in the pipeline still sees a whole
590
+ // result (its `content`, `meta`, and `additionalContexts` too), and the registry
591
+ // re-renders a changed success result from its redacted value.
592
+ ctx.on("tools/execute", async (_exec, next) => {
593
+ const result = await next();
594
+ if (secrets.size === 0 || result === null || typeof result !== "object")
595
+ return result;
596
+ return redactDeep(result, redact);
597
+ });
598
+ // is replaced before the request leaves. `next` cannot take new options, so the
599
+ // request starts over; it then carries no value and passes through here.
600
+ // A value that is part of its own label would be replaced again on every pass, so a
601
+ // request this listener rewrote passes straight through.
602
+ const rewritten = new WeakSet();
603
+ ctx.on("llm/stream", (options, next) => {
604
+ if (secrets.size === 0 || rewritten.has(options.messages))
605
+ return next();
606
+ const messages = redactDeep(options.messages, redact);
607
+ const system = redactDeep(options.system, redact);
608
+ if (messages === options.messages && system === options.system)
609
+ return next();
610
+ const fresh = [...(messages ?? [])];
611
+ rewritten.add(fresh);
612
+ rt.carryUsageTag?.(options.messages, fresh);
613
+ return ctx.llm.stream({
614
+ ...options,
615
+ messages: fresh,
616
+ ...(system !== undefined ? { system } : {}),
617
+ });
618
+ });
619
+ const resolveEnv = (execution) => {
620
+ const botId = rt.selfOf(execution?.agent?.session?.header?.id ?? execution?.agent?.id);
621
+ if (rt.botOf(botId) === undefined)
622
+ return {};
623
+ const command = typeof execution.arguments?.command === "string" ? execution.arguments.command : "";
624
+ const values = {};
625
+ let used = false;
626
+ for (const secret of secrets.values()) {
627
+ if (!canUse(secret, botId))
628
+ continue;
629
+ values[envName(secret.name)] = secret.value;
630
+ if (command.includes(envName(secret.name))) {
631
+ secret.lastUsedAt = Date.now();
632
+ used = true;
633
+ }
634
+ }
635
+ if (used)
636
+ noteUsed();
637
+ return values;
638
+ };
639
+ // Keys must be declared up front, so the contribution is registered again whenever
640
+ // the set of names (or a purpose, which describes the key) changes.
641
+ const attachShellEnv = (sub) => {
642
+ let unregister = null;
643
+ let declared = "";
644
+ refreshEnv = () => {
645
+ const list = [...secrets.values()].sort((a, b) => a.name.localeCompare(b.name));
646
+ const key = list.map((secret) => `${secret.name}\u0000${secret.purpose}`).join("\n");
647
+ if (key === declared)
648
+ return;
649
+ unregister?.();
650
+ unregister = null;
651
+ declared = key;
652
+ if (list.length === 0)
653
+ return;
654
+ try {
655
+ unregister = sub.shellEnv?.register({
656
+ name: "ocean-crew-secrets",
657
+ variables: Object.fromEntries(list.map((secret) => [
658
+ envName(secret.name),
659
+ {
660
+ description: `Ocean Crew secret ${secret.name}${secret.purpose ? `: ${secret.purpose}` : ""}`,
661
+ },
662
+ ])),
663
+ resolve: resolveEnv,
664
+ });
665
+ }
666
+ catch (error) {
667
+ declared = "";
668
+ rt.warn("ocean-crew: secrets not offered to the shell: %s", error?.message ?? error);
669
+ }
670
+ };
671
+ refreshEnv();
672
+ sub.effect?.(() => () => {
673
+ unregister?.();
674
+ unregister = null;
675
+ declared = "";
676
+ refreshEnv = () => { };
677
+ }, "ocean-crew: secrets shell env");
678
+ };
679
+ if (typeof ctx.inject === "function")
680
+ ctx.inject(["shellEnv"], attachShellEnv);
681
+ else if (ctx.get("shellEnv") !== undefined)
682
+ attachShellEnv({
683
+ shellEnv: ctx.get("shellEnv"),
684
+ effect: (execute, label) => ctx.effect(execute, label),
685
+ });
686
+ ctx.effect(() => {
687
+ void loadSecrets();
688
+ return () => {
689
+ if (usedTimer !== null)
690
+ clearTimeout(usedTimer);
691
+ };
692
+ }, "ocean-crew: load secrets");
693
+ Object.assign(rt, {
694
+ secretsView,
695
+ secretValue: (name) => secrets.get(name)?.value,
696
+ canUseSecret: (name, botId) => canUse(secrets.get(name), botId),
697
+ secretEndpoint,
698
+ forgetBotSecrets,
699
+ loadSecrets,
700
+ redactSecrets: (text) => redact(text),
701
+ });
702
+ }