@chatpanel/bridge 0.10.26 → 0.10.28

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,338 @@
1
+ // GENERATED — do not edit.
2
+ // Source of truth: chatpanel-events/skill-manifest.js (npm @chatpanel/events).
3
+ // Edit there, then run: npm run sync:events
4
+ //
5
+ // Vendored rather than depended on: the bridge ships zero runtime dependencies so a
6
+ // curl one-liner install cannot fail on someone's registry, and so the compiled
7
+ // single-file binary has nothing to resolve.
8
+
9
+ // skill-manifest.js — what a skill IS, for every client that stores or runs one.
10
+ //
11
+ // A skill was a settings record: a prompt plus a few dropdowns, normalized by whichever
12
+ // client happened to save it. That was survivable while every skill was hand-written by
13
+ // the person running it. It stops being survivable the moment a skill can ARRIVE from
14
+ // somewhere — a hub, a repo, another agent's skill directory — because the questions
15
+ // change from "what does this prompt say" to "where did it come from, what may it reach,
16
+ // and has anything checked it".
17
+ //
18
+ // So this module owns the record. Not the storage (a platform question), not the UI (a
19
+ // platform question), not the fetching (F6 S3) — the shape, its evolution, and the two
20
+ // derivations no client may compute for itself:
21
+ //
22
+ // • TRUST IS DERIVED, NEVER DECLARED. A skill cannot say it is trusted. `trustOf()`
23
+ // reads provenance: shipped by us -> 'built-in', fetched -> 'community', neither ->
24
+ // 'user'. A stored `trust` field is stripped on normalize, and `builtin` is forced
25
+ // false whenever an origin is present — otherwise "trusted" would be a string an
26
+ // importer sets.
27
+ // • DECLARED ACCESS IS COMPUTED FROM THE RECORD. Everything a skill can reach is
28
+ // readable before it runs, which is what makes load-time approval possible (P10).
29
+ // If a reviewer's summary were assembled by the install screen, the install screen
30
+ // would be the security boundary.
31
+ //
32
+ // Versioning follows the log's discipline: additive only, absence means the previous
33
+ // default, and the upcast chain exists from the start so adding v3 does not mean
34
+ // rewriting every reader.
35
+
36
+ import { DATA_SCOPES } from './scopes.js';
37
+
38
+ export class SkillManifestError extends Error {
39
+ constructor(code, message) { super(message); this.name = 'SkillManifestError'; this.code = code; }
40
+ }
41
+
42
+ /** Schema version of the RECORD. Distinct from `version`, which is the author's semver. */
43
+ export const SKILL_MANIFEST_VERSION = 2;
44
+
45
+ export const SKILL_CONTEXTS = Object.freeze(['auto', 'page', 'selection', 'tabs', 'none']);
46
+ export const SKILL_HISTORY_SCOPES = Object.freeze(['none', 'chats', 'meetings', 'all']);
47
+ export const SKILL_MCP_MODES = Object.freeze(['none', 'selected', 'default']);
48
+
49
+ /**
50
+ * Derived, never stored. 'community' is deliberately the level for a skill fetched from
51
+ * a vendor repo with a famous name — only what we ship went through our review.
52
+ */
53
+ export const SKILL_TRUST = Object.freeze(['built-in', 'user', 'community']);
54
+
55
+ /**
56
+ * The directories a package may carry, matching the agentskills.io layout. `scripts` is
57
+ * the tier-3 one: it cannot run in a browser extension and must not be offered as if it
58
+ * could (see `needsBridge`).
59
+ */
60
+ export const SKILL_FILE_KINDS = Object.freeze(['references', 'scripts', 'assets', 'templates', 'examples']);
61
+
62
+ const str = (v) => typeof v === 'string' && v.length > 0;
63
+
64
+ // A slash command is typed by a human and matched case-insensitively against a stored
65
+ // string; anything outside this grammar either cannot be typed or collides with the
66
+ // leading-slash parse.
67
+ const COMMAND = /^[a-z0-9][a-z0-9_-]*$/;
68
+
69
+ /**
70
+ * A file path inside a package directory.
71
+ *
72
+ * The check is a security boundary, not tidiness: these strings become filesystem paths
73
+ * in the bridge's skill store, and a package is authored by a stranger. Rejected are
74
+ * absolute paths, any `..` segment, backslashes (a Windows separator that a POSIX
75
+ * `split('/')` would not see as one), leading/trailing whitespace and control characters.
76
+ * Allowing one of them is a directory-traversal write on someone's machine.
77
+ */
78
+ export function isSafeSkillPath(p) {
79
+ if (!str(p) || p.length > 255) return false;
80
+ if (p !== p.trim()) return false;
81
+ if (p.includes('\\')) return false;
82
+ // eslint-disable-next-line no-control-regex
83
+ if (/[\u0000-\u001f\u007f]/.test(p)) return false;
84
+ if (p.startsWith('/') || /^[a-z]:/i.test(p)) return false;
85
+ const parts = p.split('/');
86
+ if (parts.some((seg) => seg === '' || seg === '.' || seg === '..')) return false;
87
+ return true;
88
+ }
89
+
90
+ /** Did this skill come from somewhere, or did the user write it? */
91
+ export function originOf(skill) {
92
+ const o = skill?.origin;
93
+ return o && typeof o === 'object' && str(o.source) && str(o.id) ? o : null;
94
+ }
95
+
96
+ /**
97
+ * Derived from provenance, never read from the record. A skill that arrived from outside
98
+ * is 'community' whoever published it; 'built-in' means we shipped it.
99
+ */
100
+ export function trustOf(skill) {
101
+ if (originOf(skill)) return 'community';
102
+ return skill?.builtin ? 'built-in' : 'user';
103
+ }
104
+
105
+ /** The files a package carries, per directory, already filtered to safe paths. */
106
+ export function skillFiles(skill) {
107
+ const files = skill?.files;
108
+ const out = {};
109
+ if (!files || typeof files !== 'object') return out;
110
+ for (const kind of SKILL_FILE_KINDS) {
111
+ const list = Array.isArray(files[kind]) ? files[kind].filter(isSafeSkillPath) : [];
112
+ if (list.length) out[kind] = [...new Set(list)];
113
+ }
114
+ return out;
115
+ }
116
+
117
+ /**
118
+ * True when running this skill fully needs a host that can execute code — i.e. the
119
+ * bridge. The extension may still store, show and run the PROMPT half; what it may not
120
+ * do is pretend the scripts ran.
121
+ */
122
+ export function needsBridge(skill) {
123
+ return (skillFiles(skill).scripts || []).length > 0;
124
+ }
125
+
126
+ /**
127
+ * Everything this skill can reach, computed from the record. This is what an install
128
+ * review, the Plugins lens and an admin export all read — one derivation, so the three
129
+ * cannot disagree about what was approved.
130
+ */
131
+ export function declaredAccess(skill = {}) {
132
+ const files = skillFiles(skill);
133
+ const mcpMode = SKILL_MCP_MODES.includes(skill.mcpMode) ? skill.mcpMode : 'none';
134
+ const context = SKILL_CONTEXTS.includes(skill.context) ? skill.context : 'auto';
135
+ const history = SKILL_HISTORY_SCOPES.includes(skill.historyContext) ? skill.historyContext : 'none';
136
+ const reads = new Set(Array.isArray(skill.reads) ? skill.reads.filter((r) => DATA_SCOPES.includes(r)) : []);
137
+ // The dropdowns ARE access statements; a record that declared `reads` separately from
138
+ // them could claim less than it takes.
139
+ if (context !== 'none') reads.add('page');
140
+ if (history === 'chats' || history === 'all') reads.add('chats');
141
+ if (history === 'meetings' || history === 'all') reads.add('meetings');
142
+ return {
143
+ trust: trustOf(skill),
144
+ reads: [...reads].sort(),
145
+ page: context,
146
+ history,
147
+ mcp: mcpMode,
148
+ mcpServerIds: mcpMode === 'selected' && Array.isArray(skill.mcpServerIds) ? [...skill.mcpServerIds] : [],
149
+ sources: Array.isArray(skill.sources) ? [...new Set(skill.sources.filter(str))].sort() : [],
150
+ surfaces: Array.isArray(skill.surfaces) ? [...new Set(skill.surfaces.filter(str))].sort() : [],
151
+ scripts: files.scripts || [],
152
+ needsBridge: needsBridge(skill),
153
+ meeting: !!skill.meeting,
154
+ };
155
+ }
156
+
157
+ /** Human label for where a skill came from, for the surfaces that must show provenance. */
158
+ export function originLabel(skill) {
159
+ const o = originOf(skill);
160
+ if (!o) return trustOf(skill) === 'built-in' ? 'Built-in' : 'Written here';
161
+ return o.id.length > 48 ? `${o.source} · …${o.id.slice(-40)}` : `${o.source} · ${o.id}`;
162
+ }
163
+
164
+ /** Two records describing the same upstream skill — for update checks and dedupe. */
165
+ export function sameSkillOrigin(a, b) {
166
+ const x = originOf(a);
167
+ const y = originOf(b);
168
+ return !!x && !!y && x.source === y.source && x.id === y.id;
169
+ }
170
+
171
+ /**
172
+ * Has upstream changed since this was installed? `null` when unanswerable (no origin, or
173
+ * nothing was hashed) — which callers must treat as "do not claim it is current" rather
174
+ * than as "up to date".
175
+ */
176
+ export function skillIsStale(skill, upstreamHash) {
177
+ const o = originOf(skill);
178
+ if (!o || !str(o.hash) || !str(upstreamHash)) return null;
179
+ return o.hash !== upstreamHash;
180
+ }
181
+
182
+ /**
183
+ * Validate a skill DECLARATION — the static surface approved before anything runs.
184
+ * Throws on the first problem, like `validateCapability`.
185
+ */
186
+ export function validateSkill(skill) {
187
+ if (!skill || typeof skill !== 'object') throw new SkillManifestError('SHAPE', 'skill must be an object');
188
+ if (!str(skill.id)) throw new SkillManifestError('SHAPE', 'skill.id required');
189
+ if (!str(skill.name)) throw new SkillManifestError('SHAPE', `skill '${skill.id}': name required`);
190
+ if (skill.prompt != null && typeof skill.prompt !== 'string') {
191
+ throw new SkillManifestError('SHAPE', `skill '${skill.id}': prompt must be a string`);
192
+ }
193
+ if (skill.command != null && skill.command !== '' && !COMMAND.test(String(skill.command))) {
194
+ throw new SkillManifestError('SHAPE', `skill '${skill.id}': command must match ${COMMAND}`);
195
+ }
196
+ for (const [field, allowed] of [
197
+ ['context', SKILL_CONTEXTS], ['historyContext', SKILL_HISTORY_SCOPES], ['mcpMode', SKILL_MCP_MODES],
198
+ ]) {
199
+ if (skill[field] != null && !allowed.includes(skill[field])) {
200
+ throw new SkillManifestError('SHAPE', `skill '${skill.id}': ${field} must be one of ${allowed}`);
201
+ }
202
+ }
203
+ if (skill.reads != null) {
204
+ if (!Array.isArray(skill.reads) || !skill.reads.every((r) => DATA_SCOPES.includes(r))) {
205
+ throw new SkillManifestError('SHAPE', `skill '${skill.id}': reads must be within ${DATA_SCOPES}`);
206
+ }
207
+ }
208
+ for (const field of ['sources', 'surfaces']) {
209
+ if (skill[field] != null && (!Array.isArray(skill[field]) || !skill[field].every(str))) {
210
+ throw new SkillManifestError('SHAPE', `skill '${skill.id}': ${field} must be an array of ids`);
211
+ }
212
+ }
213
+ if (skill.origin != null) {
214
+ const o = skill.origin;
215
+ if (typeof o !== 'object') throw new SkillManifestError('SHAPE', `skill '${skill.id}': origin must be an object`);
216
+ // Without a source and an id it cannot be re-fetched or compared, which is the whole
217
+ // reason the field exists; a half-origin is worse than none because it looks answered.
218
+ if (!str(o.source) || !str(o.id)) {
219
+ throw new SkillManifestError('ORIGIN', `skill '${skill.id}': origin needs both source and id`);
220
+ }
221
+ }
222
+ if (skill.files != null) {
223
+ if (typeof skill.files !== 'object') throw new SkillManifestError('SHAPE', `skill '${skill.id}': files must be an object`);
224
+ for (const kind of Object.keys(skill.files)) {
225
+ if (!SKILL_FILE_KINDS.includes(kind)) {
226
+ throw new SkillManifestError('FILES', `skill '${skill.id}': unknown file kind '${kind}'`);
227
+ }
228
+ const list = skill.files[kind];
229
+ if (!Array.isArray(list) || !list.every(str)) {
230
+ throw new SkillManifestError('FILES', `skill '${skill.id}': files.${kind} must be an array of paths`);
231
+ }
232
+ const bad = list.find((p) => !isSafeSkillPath(p));
233
+ if (bad) throw new SkillManifestError('PATH', `skill '${skill.id}': unsafe path in files.${kind}: ${JSON.stringify(bad)}`);
234
+ }
235
+ }
236
+ // Files without an origin means someone hand-wrote a package record; that is allowed,
237
+ // but scripts without an origin cannot be scanned against anything, and an unscannable
238
+ // script is exactly what the admission gate exists to refuse.
239
+ if (!originOf(skill) && (skill.files?.scripts || []).length) {
240
+ throw new SkillManifestError('ORIGIN', `skill '${skill.id}': scripts require an origin to be scannable`);
241
+ }
242
+ return skill;
243
+ }
244
+
245
+ /**
246
+ * v(n) -> v(n+1). Each MUST be total: it may not throw for any record of its version.
247
+ *
248
+ * v1 -> v2 stamps the version and nothing else, on purpose. Every field F6 adds is
249
+ * absence-means-the-old-default, so there is nothing to fill in — the same discipline as
250
+ * storing which plugins are DISABLED rather than the full state, so a field added later
251
+ * needs no migration.
252
+ */
253
+ export const SKILL_UPCASTERS = Object.freeze({
254
+ 1: (s) => ({ ...s, v: SKILL_MANIFEST_VERSION }),
255
+ });
256
+
257
+ /** Carry a stored skill forward to the current schema. Pure; never mutates the input. */
258
+ export function upcastSkill(stored) {
259
+ if (!stored || typeof stored !== 'object') throw new SkillManifestError('SHAPE', 'skill must be an object');
260
+ // A record written before the version existed is v1 by definition.
261
+ let s = typeof stored.v === 'number' ? stored : { ...stored, v: 1 };
262
+ let guard = 0;
263
+ while (s.v < SKILL_MANIFEST_VERSION) {
264
+ const step = SKILL_UPCASTERS[s.v];
265
+ if (!step) throw new SkillManifestError('UPCAST', `no upcaster from v${s.v}`);
266
+ s = step(s);
267
+ if (++guard > 64) throw new SkillManifestError('UPCAST', 'upcaster chain did not terminate');
268
+ }
269
+ if (s.v > SKILL_MANIFEST_VERSION) {
270
+ throw new SkillManifestError('UPCAST', `skill is v${s.v}; this reader only knows v${SKILL_MANIFEST_VERSION}`);
271
+ }
272
+ return s;
273
+ }
274
+
275
+ export function upcastSkills(stored) {
276
+ return (Array.isArray(stored) ? stored : []).map(upcastSkill);
277
+ }
278
+
279
+ /**
280
+ * Coerce a record into the canonical shape a writer stores. Total and forgiving — this
281
+ * runs on save, where throwing would cost a user their edit; `validateSkill` is the
282
+ * strict gate, used where a record ARRIVES.
283
+ *
284
+ * The security-relevant coercions are the ones that cannot be left to a caller:
285
+ * `trust` is never persisted, `builtin` cannot survive an origin, and an unsafe file
286
+ * path is dropped rather than stored and rejected later.
287
+ */
288
+ export function normalizeSkill(skill) {
289
+ if (!skill || typeof skill !== 'object') return skill;
290
+ const out = { ...upcastSkill(skill) };
291
+
292
+ // Skills predate the enabled flag — absence means enabled.
293
+ out.enabled = out.enabled !== false;
294
+
295
+ const mode = String(out.mcpMode || 'none').toLowerCase();
296
+ out.mcpMode = SKILL_MCP_MODES.includes(mode) ? mode : 'none';
297
+ const ids = Array.isArray(out.mcpServerIds) ? out.mcpServerIds : [];
298
+ out.mcpServerIds = out.mcpMode === 'selected'
299
+ ? [...new Set(ids.map((id) => String(id || '').trim()).filter(Boolean))]
300
+ : [];
301
+
302
+ // Derived, never stored: a record that could assert its own trust would make every
303
+ // check downstream a formality.
304
+ delete out.trust;
305
+
306
+ const origin = originOf(out);
307
+ if (origin) {
308
+ out.builtin = false; // "we shipped it" is not something an import may claim
309
+ out.origin = {
310
+ source: origin.source,
311
+ id: origin.id,
312
+ ...(str(origin.url) ? { url: origin.url } : {}),
313
+ ...(str(origin.hash) ? { hash: origin.hash } : {}),
314
+ ...(origin.scanned && typeof origin.scanned === 'object' ? { scanned: { ...origin.scanned } } : {}),
315
+ };
316
+ } else if (out.origin != null) {
317
+ delete out.origin; // a half-origin looks answered and is not
318
+ }
319
+
320
+ if (out.reads != null) {
321
+ out.reads = [...new Set((Array.isArray(out.reads) ? out.reads : []).filter((r) => DATA_SCOPES.includes(r)))].sort();
322
+ }
323
+ for (const field of ['sources', 'surfaces']) {
324
+ if (out[field] != null) {
325
+ out[field] = [...new Set((Array.isArray(out[field]) ? out[field] : []).filter(str))];
326
+ }
327
+ }
328
+
329
+ if (out.files != null) {
330
+ const files = skillFiles(out);
331
+ if (Object.keys(files).length) out.files = files;
332
+ else delete out.files;
333
+ }
334
+
335
+ if (out.version != null && !str(out.version)) delete out.version;
336
+
337
+ return out;
338
+ }