@bridgebrew/plugin-manager 0.0.1 → 0.0.2

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.
@@ -0,0 +1,427 @@
1
+ // The Plugins section's pure part: a plugin as `GET /_bridge/workspaces/<slug>/plugins` lists it, its display name and
2
+ // source label, and the list's filters, search and order (failing plugins first, then by name).
3
+ /** Whether any of `parts` contains `text` (lowercased already); an empty search matches all. */
4
+ const matches = (text: string, parts: (string | undefined)[]) =>
5
+ !text || parts.some((part) => part?.toLowerCase().includes(text));
6
+ /** A screen's title, else the key capitalised. */
7
+ const sectionTitle = (key: string, screenTitle: string | undefined) =>
8
+ screenTitle ?? `${key.charAt(0).toUpperCase()}${key.slice(1)}`;
9
+
10
+ import type { Attention } from '@bridge/kernel/status';
11
+
12
+ export type Source =
13
+ | { type: 'bridge' | 'linked'; path: string }
14
+ | { type: 'registry' | 'tarball'; spec: string };
15
+ export interface NodeRef {
16
+ id: string;
17
+ title: string;
18
+ }
19
+ export interface PluginItem {
20
+ id: string;
21
+ key: string;
22
+ version: string;
23
+ /** The version its last update replaced (#472): Back installs it again. */
24
+ previous?: string;
25
+ /** The user went back on it (#472): no update until they lift the hold. */
26
+ held?: true;
27
+ /** Bridge's last update did not update it (research-102 rule 6b): why, and the version it stays behind. */
28
+ notUpdated?: NotUpdated;
29
+ /** It ran before Bridge's last update and fails since (research-102 §7.10); `update`: a newer version to try. */
30
+ stoppedAfterUpdate?: { update?: string };
31
+ state: 'enabled' | 'disabled' | 'failed' | 'unresolved';
32
+ source: Source;
33
+ system: boolean;
34
+ /** How it arrives and updates (research-066), from its install source. */
35
+ delivery: Delivery;
36
+ /** Its publisher is verified: Built-in, or an `@bridgebrew/*` package from the registry guarding that scope. */
37
+ official?: true;
38
+ kind?: string;
39
+ title?: string;
40
+ icon?: string;
41
+ description?: string;
42
+ manifestError?: string;
43
+ error?: string;
44
+ unresolved?: string[];
45
+ blockedBy?: string[];
46
+ reloadError?: string;
47
+ browserError?: string;
48
+ generation?: number;
49
+ /** What it reports needs attention, running (research-046): `needsSetup` when the user gets it out of there. */
50
+ attention?: Attention;
51
+ hint?: string;
52
+ settings: boolean;
53
+ /** It draws a page of its own in Settings and in its Settings tab (`settingsPage`, its `<key>.settings` factory). */
54
+ settingsPage?: true;
55
+ /** Its manifest says it is a trial (`experimental`). */
56
+ experimental?: true;
57
+ /** `_host`'s plugins only: what it is to Bridge. */
58
+ role?: 'storage' | 'shell' | 'extension';
59
+ /** Its domain (research-027 P8); none: Other. */
60
+ domain?: string;
61
+ /** The contracts it requires and implements, its screens and its agent tools (research-027 P4: What it adds). */
62
+ requires: string[];
63
+ implements: string[];
64
+ screens: { id: string; title: string; icon?: string }[];
65
+ tools: { name: string; description: string }[];
66
+ active: NodeRef[];
67
+ shown: NodeRef[];
68
+ /** A plugin of Bridge's that this installed one of its key replaces (research-087: Sessions Lite): not installed,
69
+ * listed greyed with a way back to it. */
70
+ replacedBy?: { id: string; title?: string };
71
+ }
72
+ export interface NotUpdated {
73
+ why: 'external' | 'held' | 'waits' | 'data' | 'migrates' | 'download' | 'failed';
74
+ to: string;
75
+ /** `waits`: the plugin and the version it waits for. */
76
+ waits?: string;
77
+ /** `download`, `failed`: what the update said. */
78
+ error?: string;
79
+ /** What its update would do to its data when `why` does not say it (`held`, `external`). */
80
+ data?: 'migrates' | 'unknown';
81
+ }
82
+ /** Why Bridge's update left `plugin` behind, after "Not updated: ". */
83
+ export const notUpdatedText = (plugin: Pick<PluginItem, 'version'>, { why, waits }: NotUpdated) =>
84
+ ({
85
+ external: 'external plugin',
86
+ held: `held by you on ${plugin.version}`,
87
+ waits: `waits for ${waits ?? 'another plugin'}`,
88
+ data: 'may change your data',
89
+ migrates: 'changes your data with no way back',
90
+ download: 'not downloaded, retry',
91
+ failed: 'the new version did not start, the previous one was put back',
92
+ })[why];
93
+ /** What its Update asks before it runs (research-102 §7.9): an external plugin Bridge does not test, a change of data
94
+ * no Back undoes (a migration it declares, #475, or one it may make). None: it updates at once. */
95
+ export const updateQuestion = (
96
+ plugin: Pick<PluginItem, 'id' | 'title' | 'notUpdated'>,
97
+ to: string,
98
+ ) => {
99
+ const { why, data } = plugin.notUpdated ?? {};
100
+ // Its data risk whatever the reason it stayed (a held one's Update lifts the hold, then installs): asked first.
101
+ const risk = data ?? (why === 'migrates' ? 'migrates' : why === 'data' ? 'unknown' : undefined);
102
+ return risk === 'migrates'
103
+ ? {
104
+ message: `${nameOf(plugin)} ${to} changes your data and cannot be undone`,
105
+ hint: 'Back will not be possible: the version you have now cannot read the changed data.',
106
+ }
107
+ : why === 'external'
108
+ ? {
109
+ message: `Bridge does not test ${nameOf(plugin)}: ${to} may not work with this Bridge`,
110
+ hint: 'If it does not, Back on its page returns to the version you have now.',
111
+ }
112
+ : risk === 'unknown'
113
+ ? {
114
+ message: `${nameOf(plugin)} ${to} may change your data, and going back would not undo it`,
115
+ hint: 'Bridge cannot tell before it runs whether a version changes its data.',
116
+ }
117
+ : undefined;
118
+ };
119
+ export interface PluginsList {
120
+ workspace: { slug: string; state: string; reason?: string };
121
+ safe: boolean;
122
+ plugins: PluginItem[];
123
+ /** The plugins of Bridge's another installed one replaces (`replacedBy`), apart from `plugins`. */
124
+ replaced?: PluginItem[];
125
+ }
126
+
127
+ export const filters = ['all', 'enabled', 'disabled', 'failed', 'system'] as const;
128
+ export type Filter = (typeof filters)[number];
129
+ export const filterLabels: Record<Filter, string> = {
130
+ all: 'All',
131
+ enabled: 'Enabled',
132
+ disabled: 'Disabled',
133
+ failed: 'Failed',
134
+ system: 'Built-in',
135
+ };
136
+
137
+ /** Its screen's title, else its package name without its scope, capitalised (`@acme/mailer` → "Mailer"). */
138
+ export const nameOf = (plugin: Pick<PluginItem, 'id' | 'title'>) =>
139
+ sectionTitle(plugin.id.replace(/^@[^/]+\//, ''), plugin.title);
140
+ /** `slug`'s plugins by key, each with the name and icon people see (`nameOf`): what Settings and System call them, as
141
+ * the Plugins list does. Empty when the host cannot answer: callers fall back to the key. */
142
+ export const pluginNames = (
143
+ fetch: (url: string, init?: RequestInit) => Promise<Response>,
144
+ slug: string,
145
+ ): Promise<Map<string, { title: string; icon?: string }>> =>
146
+ fetch(`/_bridge/workspaces/${encodeURIComponent(slug)}/plugins`, { cache: 'no-store' })
147
+ .then((res): Promise<Pick<PluginsList, 'plugins'>> | Pick<PluginsList, 'plugins'> =>
148
+ res.ok ? res.json() : { plugins: [] },
149
+ )
150
+ .then(
151
+ ({ plugins }) =>
152
+ new Map(
153
+ plugins.map((plugin) => [
154
+ plugin.key,
155
+ { title: nameOf(plugin), ...(plugin.icon !== undefined && { icon: plugin.icon }) },
156
+ ]),
157
+ ),
158
+ () => new Map(),
159
+ );
160
+ /** A host message as a sentence: its first letter capitalised. */
161
+ export const sentence = (text: string) => `${text.charAt(0).toUpperCase()}${text.slice(1)}`;
162
+ /** Needs attention: failed, waiting for a service, or with a reload or browser error. */
163
+ /** Reads only its state and errors: a status view's plugin (`/_bridge/status`) is one too. */
164
+ type Stated = Pick<
165
+ PluginItem,
166
+ 'state' | 'reloadError' | 'browserError' | 'replacedBy' | 'attention'
167
+ >;
168
+ export const failing = (plugin: Stated) =>
169
+ plugin.state === 'failed' ||
170
+ plugin.state === 'unresolved' ||
171
+ (plugin.state === 'enabled' &&
172
+ (plugin.reloadError !== undefined || plugin.browserError !== undefined));
173
+ /** Runs, but waits for the user (bridge#449): an attention they get it out of (`recovery: 'user'`: gh not installed, no
174
+ * connection set), on a plugin that is not failing. Amber, "Needs setup"; red stays for a failure. */
175
+ export const needsSetup = (plugin: Stated) =>
176
+ plugin.state === 'enabled' && !failing(plugin) && plugin.attention?.recovery === 'user';
177
+ /** How a plugin arrives and updates (research-066): its word, and what it means for its updates. */
178
+ export type Delivery = 'built-in' | 'package' | 'local';
179
+ export const deliveries: Record<Delivery, { label: string; updates: string }> = {
180
+ 'built-in': { label: 'Built-in', updates: 'Comes with Bridge and updates with it' },
181
+ package: { label: 'Package', updates: 'Installed at a version, updated on its own' },
182
+ local: {
183
+ label: 'Local',
184
+ updates: 'A folder on this machine, updated by its owner, never by Bridge',
185
+ },
186
+ };
187
+ /** The folder path or the spec. */
188
+ export const sourceText = (source: Source) => ('path' in source ? source.path : source.spec);
189
+ export const stateLabel = (plugin: Stated) =>
190
+ plugin.replacedBy
191
+ ? `Replaced by ${nameOf(plugin.replacedBy)}`
192
+ : plugin.state === 'failed'
193
+ ? 'Failed'
194
+ : plugin.state === 'unresolved'
195
+ ? 'Waiting'
196
+ : plugin.state === 'disabled'
197
+ ? 'Disabled'
198
+ : failing(plugin)
199
+ ? 'Error'
200
+ : needsSetup(plugin)
201
+ ? 'Needs setup'
202
+ : 'Enabled';
203
+
204
+ export const inFilter = (plugin: PluginItem, filter: Filter) =>
205
+ filter === 'all' ||
206
+ (filter === 'system'
207
+ ? plugin.system
208
+ : // A replaced one is not installed: Built-in only.
209
+ !plugin.replacedBy &&
210
+ (filter === 'failed'
211
+ ? failing(plugin)
212
+ : filter === 'enabled'
213
+ ? plugin.state === 'enabled' && !failing(plugin)
214
+ : plugin.state === filter));
215
+
216
+ /** How many plugins each filter keeps. */
217
+ export const counts = (plugins: PluginItem[]) =>
218
+ Object.fromEntries(
219
+ filters.map((filter) => [filter, plugins.filter((plugin) => inFilter(plugin, filter)).length]),
220
+ ) as Record<Filter, number>;
221
+
222
+ /** The plugins `filter` keeps whose name, id, key, description or source contains `query` (case-insensitive): failing
223
+ * ones first, then by name. */
224
+ export function visible(plugins: PluginItem[], query: string, filter: Filter) {
225
+ const text = query.trim().toLowerCase();
226
+ return plugins
227
+ .filter((plugin) => inFilter(plugin, filter) && found(text, plugin))
228
+ .sort((a, b) => Number(failing(b)) - Number(failing(a)) || nameOf(a).localeCompare(nameOf(b)));
229
+ }
230
+
231
+ /** Whether `plugin` answers the search `text` (lowercased): its name, id, key, description, source, domain, delivery,
232
+ * Official and the contracts it requires or implements. */
233
+ const found = (text: string, plugin: PluginItem) =>
234
+ matches(text, [
235
+ nameOf(plugin),
236
+ plugin.id,
237
+ plugin.key,
238
+ plugin.description,
239
+ sourceText(plugin.source),
240
+ domainTitle(domainOf(plugin)),
241
+ deliveries[plugin.delivery].label,
242
+ plugin.official && 'Official',
243
+ ...plugin.requires,
244
+ ...plugin.implements,
245
+ ]);
246
+
247
+ /** Bridge's domains (research-027 P8), in the kernel's order (`pluginDomains`, a test keeps them equal), then Other:
248
+ * a plugin without one, or with one this Bridge does not know. */
249
+ export const domains = [
250
+ { id: 'interface', title: 'Interface', icon: 'layout-dashboard' },
251
+ { id: 'appearance', title: 'Appearance', icon: 'image' },
252
+ { id: 'agents', title: 'Agents', icon: 'bot' },
253
+ { id: 'data', title: 'Data and storage', icon: 'database' },
254
+ { id: 'automation', title: 'Automation', icon: 'alarm-clock' },
255
+ { id: 'apps', title: 'Apps', icon: 'package' },
256
+ { id: 'development', title: 'Development', icon: 'git-branch' },
257
+ { id: 'network', title: 'Network and access', icon: 'globe' },
258
+ { id: 'security', title: 'Security and privacy', icon: 'shield' },
259
+ { id: 'system', title: 'System', icon: 'settings' },
260
+ { id: 'other', title: 'Other', icon: 'puzzle' },
261
+ ] as const;
262
+ export const domainOf = (plugin: Pick<PluginItem, 'domain'>) =>
263
+ domains.some(({ id }) => id === plugin.domain) ? plugin.domain! : 'other';
264
+ const domainTitle = (id: string) => domains.find((each) => each.id === id)!.title;
265
+
266
+ /** The Plugins screen's three taxonomies (P2). */
267
+ export const modes = [
268
+ { value: 'name', label: 'Name' },
269
+ { value: 'domain', label: 'Domain' },
270
+ { value: 'dependencies', label: 'Dependencies' },
271
+ ] as const;
272
+ export type Mode = (typeof modes)[number]['value'];
273
+
274
+ /** One root of the screen: a workspace's plugins. Admin has two (P10): Bridge (`_host`, Bridge's own plugins; named System until 14 October 2026) and Workspace (its own). */
275
+ export interface Root {
276
+ slug: string;
277
+ label: string;
278
+ plugins: PluginItem[];
279
+ }
280
+ /** A plugin on the screen, unique across roots (`storage` is in both of Admin's). */
281
+ export const entryKey = (slug: string, plugin: Pick<PluginItem, 'id'>) => `${slug}/${plugin.id}`;
282
+ export interface Group {
283
+ label: string;
284
+ entries: { root: Root; plugin: PluginItem }[];
285
+ }
286
+
287
+ /** The list modes' groups: by name, one per root (unlabelled when there is one); by domain, one per domain present, in
288
+ * Bridge's order, each root's in turn. Empty groups are left out. */
289
+ export function groups(
290
+ roots: Root[],
291
+ mode: 'name' | 'domain',
292
+ query: string,
293
+ filter: Filter,
294
+ ): Group[] {
295
+ const named = (root: Root, label: string) =>
296
+ roots.length > 1 ? (label ? `${root.label} · ${label}` : root.label) : label;
297
+ return roots
298
+ .flatMap((root) => {
299
+ const shown = visible(root.plugins, query, filter).map((plugin) => ({ root, plugin }));
300
+ if (mode === 'name') return [{ label: named(root, ''), entries: shown }];
301
+ return domains.map(({ id, title }) => ({
302
+ label: named(root, title),
303
+ entries: shown.filter(({ plugin }) => domainOf(plugin) === id),
304
+ }));
305
+ })
306
+ .filter((group) => group.entries.length > 0);
307
+ }
308
+
309
+ /** A row of the dependency tree: a plugin (`repeat` when shown already, higher up: no children again), or a required
310
+ * contract nobody provides (`missing`). `via`: the contract its parent requires of it. */
311
+ export interface DependencyNode {
312
+ key: string;
313
+ root: Root;
314
+ plugin?: PluginItem;
315
+ contract?: string;
316
+ via?: string;
317
+ repeat?: true;
318
+ missing?: true;
319
+ children: DependencyNode[];
320
+ }
321
+
322
+ /** `root`'s plugins as a tree (P2): the plugins no other one needs at the top, each with, below, the plugins providing
323
+ * the contracts it requires; a contract no plugin of `root` provides is looked for in the other roots (Admin's System
324
+ * provides to its Workspace), else shown missing. Dependencies are a graph: a plugin is expanded once, where it is met
325
+ * first, then shown again dimmed. Plugins in a cycle only, never met from a top, are tops too. */
326
+ export function dependencyTree(root: Root, roots: Root[]): DependencyNode[] {
327
+ const byName = (a: PluginItem, b: PluginItem) => nameOf(a).localeCompare(nameOf(b));
328
+ const providers = (contract: string) => {
329
+ for (const each of [root, ...roots.filter((other) => other !== root)]) {
330
+ const found = each.plugins
331
+ .filter((plugin) => plugin.implements.includes(contract))
332
+ .sort(byName);
333
+ if (found.length) return found.map((plugin) => ({ root: each, plugin }));
334
+ }
335
+ return [];
336
+ };
337
+ const needed = new Set(
338
+ root.plugins.flatMap((plugin) =>
339
+ plugin.requires.flatMap((contract) =>
340
+ providers(contract)
341
+ .filter((each) => each.root === root)
342
+ .map((each) => each.plugin.id),
343
+ ),
344
+ ),
345
+ );
346
+ const seen = new Set<string>();
347
+ const node = (at: Root, plugin: PluginItem, parent: string, via?: string): DependencyNode => {
348
+ const key = `${parent}>${entryKey(at.slug, plugin)}`;
349
+ const id = entryKey(at.slug, plugin);
350
+ const base = { key, root: at, plugin, ...(via !== undefined && { via }) };
351
+ if (seen.has(id)) return { ...base, repeat: true, children: [] };
352
+ seen.add(id);
353
+ return {
354
+ ...base,
355
+ children: plugin.requires.flatMap((contract) => {
356
+ const found = providers(contract);
357
+ if (!found.length)
358
+ return [
359
+ { key: `${key}>${contract}`, root: at, contract, missing: true as const, children: [] },
360
+ ];
361
+ return found.map((each) => node(each.root, each.plugin, key, contract));
362
+ }),
363
+ };
364
+ };
365
+ const sorted = [...root.plugins].sort(byName);
366
+ const tops = sorted
367
+ .filter((plugin) => !needed.has(plugin.id))
368
+ .map((plugin) => node(root, plugin, root.slug));
369
+ // One at a time: a cycle's first plugin met expands the others.
370
+ for (const plugin of sorted)
371
+ if (!seen.has(entryKey(root.slug, plugin))) tops.push(node(root, plugin, root.slug));
372
+ return tops;
373
+ }
374
+
375
+ /** The tree with only the rows that answer the search and the filter, and their ancestors. */
376
+ export function pruneTree(
377
+ nodes: DependencyNode[],
378
+ query: string,
379
+ filter: Filter,
380
+ ): DependencyNode[] {
381
+ const text = query.trim().toLowerCase();
382
+ if (!text && filter === 'all') return nodes;
383
+ return nodes.flatMap((each) => {
384
+ const children = pruneTree(each.children, query, filter);
385
+ const self = each.plugin
386
+ ? inFilter(each.plugin, filter) && found(text, each.plugin)
387
+ : filter === 'all' && matches(text, [each.contract]);
388
+ return self || children.length ? [{ ...each, children }] : [];
389
+ });
390
+ }
391
+
392
+ /** A navigation item `<root>/<plugin>[/<rest>]` cut in its parts. A scoped plugin's key (`@scope/name`) holds a slash of
393
+ * its own and stays whole (bridge#449); none without a root and a plugin. */
394
+ export function pluginItemOf(
395
+ item: string | undefined,
396
+ ): { root: string; plugin: string; rest: string[] } | undefined {
397
+ const [root, first, ...rest] = item?.split('/') ?? [];
398
+ const plugin = first?.startsWith('@') ? `${first}/${rest.shift() ?? ''}` : first;
399
+ if (!root || !plugin || plugin.endsWith('/')) return undefined;
400
+ return { root, plugin, rest };
401
+ }
402
+
403
+ /** What a navigation item opens on the Plugins screen (research-048: a ⌘-click on a row, a window beside):
404
+ * `<root>/<plugin>` that plugin's Info; `<root>/<plugin>/settings[/<page item>]` its Settings tab, its settings page
405
+ * on that item (`settingsPage`, the rest of the path); else its Logs as `logsOpening` reads them. */
406
+ export function pluginOpening(
407
+ item: string | undefined,
408
+ ): { key: string; tab: 'info' | 'logs' | 'settings'; until?: string; page?: string } | undefined {
409
+ const logs = logsOpening(item);
410
+ if (logs) return { ...logs, tab: 'logs' };
411
+ const parts = pluginItemOf(item);
412
+ if (!parts) return undefined;
413
+ const key = `${parts.root}/${parts.plugin}`;
414
+ const [tab, ...page] = parts.rest;
415
+ if (tab === 'settings')
416
+ return { key, tab: 'settings', ...(page.length > 0 && { page: page.join('/') }) };
417
+ return tab === undefined ? { key, tab: 'info' } : undefined;
418
+ }
419
+ /** What a navigation item asks of the Plugins screen (research-047, Health's Logs): `<root>/<plugin id>/logs/<ISO time>`
420
+ * opens that plugin's Logs tab on the records up to that time, `<root>/<plugin id>/logs` on its live log. */
421
+ export function logsOpening(item: string | undefined): { key: string; until?: string } | undefined {
422
+ const parts = pluginItemOf(item);
423
+ if (!parts || parts.rest[0] !== 'logs' || parts.rest.length > 2) return undefined;
424
+ const until = parts.rest[1];
425
+ if (until !== undefined && Number.isNaN(Date.parse(until))) return undefined;
426
+ return { key: `${parts.root}/${parts.plugin}`, ...(until !== undefined && { until }) };
427
+ }