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,461 @@
1
+ // Model providers and their API keys, for a window that has no DSH Models page of its
2
+ // own. DSH keeps all of it: a provider route in the settings of the adapter that serves
3
+ // it, the route's key in DSH's credential store under the reference the route names.
4
+ // The providers to add are the ones DSH's directory of configurable providers offers.
5
+ //
6
+ // Nothing here reads a key back: a key is only written, replaced or removed. The
7
+ // missingKeys, providersView, setProviderKey, clearProviderKey, addProvider,
8
+ // discoverModels, removeProvider) plus providerEndpoint, the `provider-*` endpoint
9
+ // dispatcher the channel calls.
10
+ const PI_AI = "llm-pi-ai";
11
+ const ROUTE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
12
+ // The wire protocols DSH's pi-ai adapter serves on a route it ships nothing about.
13
+ export const PROTOCOLS = ["openai-completions", "openai-responses", "anthropic-messages"];
14
+ const MAX_MODELS = 500;
15
+ // pi-ai guesses compatibility from the endpoint hostname and treats any unrecognized
16
+ // gateway as OpenAI's own server (sending the `developer` role, `store: false`, and
17
+ // `max_completion_tokens`). Every OpenAI-compatible server accepts `system` and
18
+ // `max_tokens`, and reasoning models such as Kimi and DeepSeek require
19
+ // `reasoning_content` on replayed assistant messages.
20
+ const CUSTOM_COMPAT = {
21
+ "openai-completions": {
22
+ supportsDeveloperRole: false,
23
+ supportsStore: false,
24
+ maxTokensField: "max_tokens",
25
+ requiresReasoningContentOnAssistantMessages: true,
26
+ },
27
+ "openai-responses": {
28
+ supportsDeveloperRole: false,
29
+ },
30
+ };
31
+ const RESPONSES_PROVIDERS = new Set(["openai", "xai", "meta"]);
32
+ const COMPLETIONS_PROVIDERS = new Set([
33
+ "ant-ling",
34
+ "baseten",
35
+ "cerebras",
36
+ "cloudflare-ai-gateway",
37
+ "cloudflare-workers-ai",
38
+ "deepseek",
39
+ "fireworks",
40
+ "github-copilot",
41
+ "groq",
42
+ "huggingface",
43
+ "kimi-coding",
44
+ "moonshotai",
45
+ "moonshotai-cn",
46
+ "nvidia",
47
+ "opencode",
48
+ "opencode-go",
49
+ "openrouter",
50
+ "qwen-token-plan",
51
+ "qwen-token-plan-cn",
52
+ "qwen-token-plan-individual",
53
+ "together",
54
+ "xiaomi",
55
+ "xiaomi-token-plan-ams",
56
+ "xiaomi-token-plan-cn",
57
+ "xiaomi-token-plan-sgp",
58
+ "zai",
59
+ "zai-coding-cn",
60
+ ]);
61
+ const catalogProtocol = (id) => RESPONSES_PROVIDERS.has(id) ? "openai-responses" : COMPLETIONS_PROVIDERS.has(id) ? "openai-completions" : undefined;
62
+ // The reference DSH's own Models page derives for a route's key, so a provider added
63
+ // here and one added there read the same key.
64
+ export const keyRefFor = (provider) => `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
65
+ const invalid = (message) => Object.assign(new Error(message), { code: "bot/invalid" });
66
+ /** Whether a key is what an HTTP header can carry (DSH's own Models page check). */
67
+ export function checkKey(value) {
68
+ const key = typeof value === "string" ? value.trim() : "";
69
+ if (key === "")
70
+ throw invalid("Enter the API key");
71
+ if (/^[A-Za-z_][A-Za-z0-9_]*=[^=]/.test(key))
72
+ throw invalid("Paste only the key, not a NAME=value line");
73
+ if (/^(["']).*\1$/.test(key))
74
+ throw invalid("Paste the key without quotes");
75
+ if (!/^[\x21-\x7E]+$/.test(key))
76
+ throw invalid("An API key has no spaces or special characters");
77
+ return key;
78
+ }
79
+ function checkEndpoint(value) {
80
+ const text = typeof value === "string" ? value.trim() : "";
81
+ let url;
82
+ try {
83
+ url = new URL(text);
84
+ }
85
+ catch {
86
+ throw invalid("Enter the endpoint as an http or https address");
87
+ }
88
+ if (url.protocol !== "http:" && url.protocol !== "https:")
89
+ throw invalid("Enter the endpoint as an http or https address");
90
+ return text;
91
+ }
92
+ function lookupKnownModel(known, rawId) {
93
+ if (!known || known.size === 0 || typeof rawId !== "string")
94
+ return undefined;
95
+ const id = rawId.trim().toLowerCase();
96
+ if (id === "")
97
+ return undefined;
98
+ const bare = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
99
+ return (known.get(id) ??
100
+ known.get(bare) ??
101
+ (bare.startsWith("kimi-") ? known.get(bare.slice(5)) : known.get(`kimi-${bare}`)));
102
+ }
103
+ // A model as the route stores it: what discovery told about it, under pi-ai's names,
104
+ // with any missing capacity or modalities filled from a known catalog model of the same id.
105
+ function modelEntry(model, known) {
106
+ const record = typeof model === "string" ? {} : (model ?? {});
107
+ const id = typeof model === "string" ? model.trim() : typeof record.id === "string" ? record.id.trim() : "";
108
+ if (id === "")
109
+ throw invalid("Every model needs an id");
110
+ const match = lookupKnownModel(known, id);
111
+ const whole = (value) => typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
112
+ const contextWindow = whole(record.contextWindow) ?? whole(match?.contextWindow);
113
+ const maxTokens = whole(record.maxTokens);
114
+ const rawInput = Array.isArray(record.inputModalities) && record.inputModalities.length > 0
115
+ ? record.inputModalities
116
+ : Array.isArray(record.input) && record.input.length > 0
117
+ ? record.input
118
+ : match?.inputModalities;
119
+ const input = Array.isArray(rawInput) ? rawInput.filter((kind) => typeof kind === "string") : [];
120
+ return {
121
+ id,
122
+ ...(typeof record.name === "string" && record.name.trim() !== "" ? { name: record.name.trim() } : {}),
123
+ ...(contextWindow ? { contextWindow } : {}),
124
+ ...(maxTokens ? { maxTokens } : {}),
125
+ ...(input.length > 0 ? { input } : {}),
126
+ };
127
+ }
128
+ function compatForRoute(id, profile) {
129
+ if (typeof profile !== "object" || profile === null)
130
+ return undefined;
131
+ const record = profile;
132
+ const api = typeof record.api === "string"
133
+ ? record.api
134
+ : typeof record.baseURL === "string" || Array.isArray(record.models)
135
+ ? catalogProtocol(id)
136
+ : undefined;
137
+ const defaults = api === undefined ? undefined : CUSTOM_COMPAT[api];
138
+ if (defaults === undefined)
139
+ return undefined;
140
+ const current = typeof record.compat === "object" && record.compat !== null ? record.compat : {};
141
+ if (Object.keys(defaults).every((key) => current[key] !== undefined))
142
+ return undefined;
143
+ return { ...defaults, ...current };
144
+ }
145
+ export function install(rt) {
146
+ const { ctx } = rt;
147
+ const llm = () => ctx.llm;
148
+ const seams = () => {
149
+ const settings = ctx.get("settings");
150
+ const credentials = ctx.get("credentials");
151
+ return settings && credentials && llm().listConfigurableProviders ? { settings, credentials } : undefined;
152
+ };
153
+ const usable = () => {
154
+ const found = seams();
155
+ if (found === undefined)
156
+ throw invalid("This DSH cannot set up model providers");
157
+ return found;
158
+ };
159
+ const sections = (settings) => new Map(settings.describe({ redactSecrets: true }).map((section) => [section.ns, section]));
160
+ const profileOf = (entry, map, layer = "value") => entry.settingsPath.reduce((value, key) => value?.[key], map.get(entry.settingsNs)?.[layer]);
161
+ const refOf = (profile) => typeof profile?.apiKeyEnv === "string" && profile.apiKeyEnv !== "" ? profile.apiKeyEnv : undefined;
162
+ const entryOf = (provider) => llm()
163
+ .listConfigurableProviders?.()
164
+ .find((entry) => entry.provider === provider);
165
+ let knownCache;
166
+ async function knownCatalogModels() {
167
+ if (knownCache !== undefined)
168
+ return knownCache;
169
+ const entries = (llm().listConfigurableProviders?.() ?? []).filter((entry) => entry.settingsNs === PI_AI &&
170
+ entry.declared === false &&
171
+ (entry.nativeAuth !== undefined || entry.defaultBaseURL !== undefined));
172
+ if (entries.length === 0)
173
+ return new Map();
174
+ const map = new Map();
175
+ const remember = (key, model) => {
176
+ if (key && !map.has(key))
177
+ map.set(key, model);
178
+ };
179
+ for (const entry of entries) {
180
+ let list = [];
181
+ try {
182
+ list = await llm().discoverModels(PI_AI, { provider: entry.provider });
183
+ }
184
+ catch {
185
+ continue;
186
+ }
187
+ for (const model of list) {
188
+ const id = typeof model?.id === "string" ? model.id.trim().toLowerCase() : "";
189
+ if (!id)
190
+ continue;
191
+ remember(id, model);
192
+ const bare = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
193
+ remember(bare, model);
194
+ if (bare.startsWith("kimi-"))
195
+ remember(bare.slice(5), model);
196
+ }
197
+ }
198
+ knownCache = map;
199
+ return map;
200
+ }
201
+ // Backfill compatibility defaults onto custom routes (and catalog routes pointed at a
202
+ // custom gateway) that were saved before Ocean Crew wrote `compat`, or added through DSH's
203
+ // own Models page. Explicit user settings win per field.
204
+ let repairing = Promise.resolve();
205
+ async function ensureCustomCompat() {
206
+ const found = seams();
207
+ if (found === undefined)
208
+ return;
209
+ const section = sections(found.settings).get(PI_AI);
210
+ const userProviders = section?.user?.providers;
211
+ if (!userProviders || typeof userProviders !== "object")
212
+ return;
213
+ const ops = [];
214
+ for (const [id, profile] of Object.entries(userProviders)) {
215
+ const nextCompat = compatForRoute(id, profile);
216
+ if (nextCompat !== undefined)
217
+ ops.push({ op: "set", path: ["providers", id, "compat"], value: nextCompat });
218
+ }
219
+ if (ops.length === 0)
220
+ return;
221
+ await found.settings.mutate(PI_AI, ops, section.revision);
222
+ rt.dropCatalog();
223
+ }
224
+ function repairRoutes() {
225
+ repairing = repairing.then(ensureCustomCompat, ensureCustomCompat).catch(() => undefined);
226
+ return repairing;
227
+ }
228
+ void repairRoutes();
229
+ // Per provider route, the credential its DSH settings name as its API key. A
230
+ // provider with none authenticates some other way.
231
+ function keyRefs() {
232
+ const found = seams();
233
+ if (found === undefined)
234
+ return new Map();
235
+ const map = sections(found.settings);
236
+ const refs = new Map();
237
+ for (const entry of llm().listConfigurableProviders?.() ?? []) {
238
+ const ref = refOf(profileOf(entry, map));
239
+ if (ref !== undefined)
240
+ refs.set(entry.provider, ref);
241
+ }
242
+ return refs;
243
+ }
244
+ async function missingKeys(providers) {
245
+ await repairRoutes();
246
+ let refs;
247
+ try {
248
+ refs = keyRefs();
249
+ }
250
+ catch {
251
+ return new Set();
252
+ }
253
+ const missing = new Set();
254
+ await Promise.all(providers
255
+ .filter((id) => refs.has(id))
256
+ .map(async (id) => {
257
+ const info = await seams()
258
+ ?.credentials.describe(refs.get(id))
259
+ .catch(() => undefined);
260
+ if (info?.configured === false)
261
+ missing.add(id);
262
+ }));
263
+ return missing;
264
+ }
265
+ // The providers set up in DSH, with their models and key state, and the ones DSH
266
+ // can add. A provider with no key and no models (DeepSeek's account route before a
267
+ // sign-in) is left out.
268
+ async function providersView() {
269
+ await repairRoutes();
270
+ const found = seams();
271
+ if (found === undefined)
272
+ return { available: false };
273
+ const map = sections(found.settings);
274
+ const catalog = await rt.catalog({ fresh: true });
275
+ const providers = [];
276
+ const addable = [];
277
+ for (const entry of llm().listConfigurableProviders?.() ?? []) {
278
+ const profile = profileOf(entry, map);
279
+ if (entry.settingsNs === PI_AI && profile === undefined) {
280
+ if (entry.declared !== true)
281
+ addable.push({ id: entry.provider, name: entry.displayName });
282
+ continue;
283
+ }
284
+ const ref = refOf(profile);
285
+ const models = catalog
286
+ .filter((model) => model.provider === entry.provider)
287
+ .map((model) => ({ ref: model.ref, name: model.name }));
288
+ if (ref === undefined && models.length === 0 && entry.error === undefined)
289
+ continue;
290
+ const info = ref === undefined ? undefined : await found.credentials.describe(ref).catch(() => undefined);
291
+ providers.push({
292
+ id: entry.provider,
293
+ name: entry.displayName,
294
+ models,
295
+ key: ref === undefined ? null : { configured: info?.configured === true, writable: info?.writable !== false },
296
+ removable: entry.settingsNs === PI_AI &&
297
+ profileOf(entry, map, "user") !== undefined &&
298
+ profileOf(entry, map, "base") === undefined,
299
+ custom: entry.declared === true,
300
+ ...(entry.error ? { error: entry.error } : {}),
301
+ });
302
+ }
303
+ // The ones that come with the setup first, then the added ones as DSH lists them.
304
+ providers.sort((a, b) => Number(a.removable) - Number(b.removable));
305
+ return { available: true, providers, addable, protocols: PROTOCOLS };
306
+ }
307
+ async function writableRef(provider) {
308
+ const ref = keyRefs().get(provider);
309
+ if (ref === undefined)
310
+ throw invalid(`${provider} takes no API key here`);
311
+ if ((await usable().credentials.describe(ref))?.writable === false)
312
+ throw invalid(`The API key for ${provider} is set outside Ocean Crew and cannot be changed here`);
313
+ return ref;
314
+ }
315
+ // A key is only ever written; nothing here reads one back.
316
+ async function setProviderKey(provider, value) {
317
+ const key = checkKey(value);
318
+ await usable().credentials.set(await writableRef(provider), key);
319
+ rt.dropCatalog();
320
+ }
321
+ async function clearProviderKey(provider) {
322
+ await usable().credentials.unset(await writableRef(provider));
323
+ rt.dropCatalog();
324
+ }
325
+ // `provider` from DSH's directory, or a route the user declares (`custom`) for an
326
+ // endpoint DSH ships nothing about. The route goes in first, then its key, as DSH's
327
+ // own Models page does it: a failed key write leaves a provider that asks for one.
328
+ async function addProvider(body) {
329
+ await repairing;
330
+ const { settings, credentials } = usable();
331
+ const provider = String(body.provider ?? "").trim();
332
+ const custom = body.custom === true;
333
+ const known = custom ? await knownCatalogModels() : undefined;
334
+ const map = sections(settings);
335
+ const entry = entryOf(provider);
336
+ if (entry !== undefined && (entry.settingsNs !== PI_AI || profileOf(entry, map) !== undefined))
337
+ throw invalid(`${provider} is already set up`);
338
+ if (!custom && (entry === undefined || entry.declared === true))
339
+ throw invalid(`DSH offers no provider ${provider}`);
340
+ if (custom && !ROUTE_ID.test(provider))
341
+ throw invalid("A provider id is lowercase letters, digits and dashes, starting with a letter");
342
+ if (custom && entry !== undefined)
343
+ throw invalid(`DSH already offers ${provider}; add it from its list`);
344
+ const key = typeof body.key === "string" && body.key.trim() !== "" ? checkKey(body.key) : undefined;
345
+ const ref = keyRefFor(provider);
346
+ const info = (await credentials.describe(ref)) ?? {};
347
+ if (key !== undefined && info.writable === false)
348
+ throw invalid(`The API key for ${provider} is set outside Ocean Crew and cannot be changed here`);
349
+ // A blank key keeps a key that is already there, else the provider's own sign-in.
350
+ const keyed = key !== undefined || info.configured === true;
351
+ const profile = custom ? customProfile(body, known) : {};
352
+ if (keyed)
353
+ profile.apiKeyEnv = ref;
354
+ await settings.mutate(PI_AI, [{ op: "set", path: entry?.settingsPath ?? ["providers", provider], value: profile }], map.get(PI_AI)?.revision);
355
+ if (key !== undefined)
356
+ await credentials.set(ref, key);
357
+ rt.dropCatalog();
358
+ return providersView();
359
+ }
360
+ function customProfile(body, known) {
361
+ if (!PROTOCOLS.includes(body.api))
362
+ throw invalid(`The protocol must be one of ${PROTOCOLS.join(", ")}`);
363
+ const models = Array.isArray(body.models)
364
+ ? body.models.slice(0, MAX_MODELS).map((model) => modelEntry(model, known))
365
+ : [];
366
+ if (models.length === 0)
367
+ throw invalid("Add at least one model");
368
+ if (new Set(models.map((model) => model.id)).size !== models.length)
369
+ throw invalid("Two models have the same id");
370
+ const name = typeof body.name === "string" ? body.name.trim().slice(0, 80) : "";
371
+ const compat = CUSTOM_COMPAT[body.api];
372
+ return {
373
+ ...(name ? { displayName: name } : {}),
374
+ api: body.api,
375
+ baseURL: checkEndpoint(body.baseURL),
376
+ ...(compat ? { compat: { ...compat } } : {}),
377
+ models,
378
+ };
379
+ }
380
+ // The models an endpoint (or a provider DSH ships) says it serves. The key typed for
381
+ // the question goes with it and is not stored.
382
+ async function discoverModels(body) {
383
+ usable();
384
+ const provider = typeof body.provider === "string" && body.provider !== "" ? body.provider : undefined;
385
+ const request = provider !== undefined && entryOf(provider)?.declared === false
386
+ ? { provider }
387
+ : {
388
+ baseURL: checkEndpoint(body.baseURL),
389
+ ...(PROTOCOLS.includes(body.api) ? { api: body.api } : {}),
390
+ ...(typeof body.key === "string" && body.key.trim() !== "" ? { apiKey: checkKey(body.key) } : {}),
391
+ };
392
+ const models = await llm().discoverModels(PI_AI, request);
393
+ const known = request.provider === undefined ? await knownCatalogModels() : undefined;
394
+ return models.slice(0, MAX_MODELS).map((model) => {
395
+ const match = lookupKnownModel(known, model.id);
396
+ const contextWindow = model.contextWindow ?? match?.contextWindow;
397
+ const inputModalities = model.inputModalities ?? match?.inputModalities;
398
+ return {
399
+ id: model.id,
400
+ ...(model.name ? { name: model.name } : {}),
401
+ ...(contextWindow ? { contextWindow } : {}),
402
+ ...(model.maxTokens ? { maxTokens: model.maxTokens } : {}),
403
+ ...(inputModalities ? { inputModalities: [...inputModalities] } : {}),
404
+ };
405
+ });
406
+ }
407
+ // Only a route the user added goes; its key goes with it when it is the one this page
408
+ // derives and no other provider names it.
409
+ async function removeProvider(provider) {
410
+ await repairing;
411
+ const { settings, credentials } = usable();
412
+ const map = sections(settings);
413
+ const entry = entryOf(provider);
414
+ if (entry === undefined || entry.settingsNs !== PI_AI || profileOf(entry, map) === undefined)
415
+ throw invalid(`${provider} is not set up`);
416
+ if (profileOf(entry, map, "user") === undefined || profileOf(entry, map, "base") !== undefined)
417
+ throw invalid(`${provider} comes with this setup and cannot be removed`);
418
+ const ref = refOf(profileOf(entry, map));
419
+ const shared = [...keyRefs()].some(([other, otherRef]) => other !== provider && otherRef === ref);
420
+ await settings.mutate(PI_AI, [{ op: "unset", path: entry.settingsPath }], map.get(PI_AI)?.revision);
421
+ if (ref === keyRefFor(provider) && !shared) {
422
+ const info = await credentials.describe(ref);
423
+ if (info?.configured && info.writable)
424
+ await credentials.unset(ref);
425
+ }
426
+ rt.dropCatalog();
427
+ return providersView();
428
+ }
429
+ // channel called the members directly.
430
+ async function providerEndpoint(endpoint, body = {}) {
431
+ switch (endpoint) {
432
+ case "providers":
433
+ return providersView();
434
+ case "provider-key":
435
+ if (body.value === null)
436
+ await clearProviderKey(String(body.provider ?? ""));
437
+ else
438
+ await setProviderKey(String(body.provider ?? ""), body.value);
439
+ return providersView();
440
+ case "provider-add":
441
+ return addProvider(body);
442
+ case "provider-models":
443
+ return discoverModels(body);
444
+ case "provider-remove":
445
+ return removeProvider(String(body.provider ?? ""));
446
+ default:
447
+ throw new Error("Unknown provider operation.");
448
+ }
449
+ }
450
+ Object.assign(rt, {
451
+ keyRefs,
452
+ missingKeys,
453
+ providersView,
454
+ setProviderKey,
455
+ clearProviderKey,
456
+ addProvider,
457
+ discoverModels,
458
+ removeProvider,
459
+ providerEndpoint,
460
+ });
461
+ }