decklight 0.2.0 → 0.3.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +855 -80
  3. package/cli/agents.mjs +113 -9
  4. package/cli/associate.mjs +279 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +564 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +730 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +646 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +560 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +201 -0
  34. package/cli/units.mjs +488 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +5 -4
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +11 -2
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +139 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +316 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
@@ -0,0 +1,730 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight marketplace — register catalogs; never fetch unless asked to.
6
+ //
7
+ // decklight marketplace add <owner/repo | git url | path> [--name x]
8
+ // decklight marketplace list
9
+ // decklight marketplace update <name>
10
+ // decklight marketplace remove <name>
11
+ //
12
+ // A marketplace is a git repo (or a local directory) with
13
+ // `.decklight/marketplace.json` at its root, mirroring Claude Code's layout
14
+ // (MARKETPLACE.md MARKETPLACES). Registration lives under `~/.decklight/`:
15
+ // one registry file (`marketplaces.json`) plus a `marketplaces/` directory of
16
+ // cached manifests — the boring layout the engine wizard will share.
17
+ //
18
+ // The invariant this module exists to keep (SPEC MARKETPLACE_REGISTRY): the
19
+ // network is touched ONLY by an explicit `add` or `update` of a remote
20
+ // source. Registering is a filesystem write; `list` reads only the cache;
21
+ // nothing on the deck-load or presenting path imports this module at all. A
22
+ // deck on conference wifi, on a plane, or air-gapped behaves identically to
23
+ // one at a desk, marketplace or no marketplace.
24
+
25
+ import {
26
+ existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync,
27
+ } from 'node:fs';
28
+ import { execFileSync } from 'node:child_process';
29
+ import { homedir, tmpdir } from 'node:os';
30
+ import { join, resolve } from 'node:path';
31
+ import { argReader, isMain } from '../tools/args.mjs';
32
+ import { oneline } from './git.mjs';
33
+
34
+ export const MANIFEST_PATH = '.decklight/marketplace.json';
35
+ export const NAME_RE = /^[A-Za-z0-9_-]+$/;
36
+
37
+ /**
38
+ * Every kind of entry this decklight recognises, and how you install one.
39
+ *
40
+ * It lives here rather than in units.mjs because this module owns the manifest
41
+ * vocabulary and units.mjs is the layer above it — the other direction would
42
+ * be a cycle. A `null` hint means the kind is real but nothing installs it
43
+ * here yet, which `marketplace list` prints as its own state: "not yet" and
44
+ * "typo" must not look alike.
45
+ */
46
+ export const INSTALL_HINT = {
47
+ theme: 'decklight theme add <source> <deck>',
48
+ plugin: 'decklight plugin add <name>',
49
+ template: 'decklight template add <name>',
50
+ skill: 'decklight skills add <name>',
51
+ importer: 'decklight importer add <name>',
52
+ engine: 'decklight engine add <name>', // ENGINE_UNITS — the wizard then configures it
53
+ agent: 'decklight agent add <name>', // AGENT_UNITS — a descriptor, never code
54
+ transform: 'decklight transform add <name>', // EXTENSIONS#LOADER — installs; bundle --transform <name> runs it
55
+ voice: 'decklight voice add <name>',
56
+ 'publish-target': null,
57
+ };
58
+
59
+ export const KNOWN_TYPES = Object.keys(INSTALL_HINT);
60
+
61
+ /** The catalog every install registers, and no install ever fetches. */
62
+ export const FIRST_PARTY = { name: 'decklight', source: 'decklight/decklight-plugins-official' };
63
+
64
+ /** A failure with a message for a human — the mains print it, never a stack. */
65
+ export class MarketplaceError extends Error {}
66
+
67
+ // ── where everything lives ─────────────────────────────────────────────────
68
+
69
+ /** The decklight config home (ENGINES decided `~/.decklight/`). */
70
+ export const configHome = (env = process.env) =>
71
+ env.DECKLIGHT_HOME || join(homedir(), '.decklight');
72
+
73
+ const registryPath = (home) => join(home, 'marketplaces.json');
74
+ const cachePath = (home, name) => join(home, 'marketplaces', `${name}.json`);
75
+
76
+ export function loadRegistry(home = configHome()) {
77
+ const p = registryPath(home);
78
+ if (!existsSync(p)) return { version: 1, marketplaces: {} };
79
+ try {
80
+ const data = JSON.parse(readFileSync(p, 'utf8'));
81
+ return { version: 1, marketplaces: {}, ...data };
82
+ } catch (e) {
83
+ throw new MarketplaceError(`${p} is not valid JSON (${parseMsg(e)}) — fix or delete it`);
84
+ }
85
+ }
86
+
87
+ export function saveRegistry(reg, home = configHome()) {
88
+ mkdirSync(join(home, 'marketplaces'), { recursive: true });
89
+ writeFileSync(registryPath(home), JSON.stringify(reg, null, 2) + '\n');
90
+ }
91
+
92
+ /**
93
+ * Register the first-party marketplace on first run — REGISTERED, not
94
+ * fetched: this writes two files and touches nothing else, so first run
95
+ * offline is silent and instant. First run means "no registry file yet";
96
+ * once one exists this never fires again, so removing the first-party
97
+ * marketplace is respected rather than undone on the next command.
98
+ */
99
+ export function ensureFirstPartyRegistered(home = configHome()) {
100
+ if (existsSync(registryPath(home))) return false;
101
+ saveRegistry({
102
+ version: 1,
103
+ marketplaces: { [FIRST_PARTY.name]: { source: FIRST_PARTY.source, firstParty: true } },
104
+ }, home);
105
+ return true;
106
+ }
107
+
108
+ // ── the manifest, validated with line numbers ──────────────────────────────
109
+
110
+ /** "Unexpected token } in JSON at position 47" minus the part we say better. */
111
+ const parseMsg = (e) => String(e.message)
112
+ .replace(/ in JSON.*$/, '')
113
+ .replace(/,\s*(?:\.\.\.)?"[\s\S]*"(?:\.\.\.)? is not valid JSON$/, '')
114
+ .replace(/^JSON\.parse: /, '');
115
+
116
+ const lineAt = (raw, idx) => raw.slice(0, idx).split('\n').length;
117
+
118
+ // V8's snippet-style parse error ('Unexpected token X, ..."<context>"... is
119
+ // not valid JSON') carries no position — but the context starts a fixed 10
120
+ // characters before the error, so finding the snippet in the raw text
121
+ // recovers it. The other two message forms name the position outright.
122
+ const V8_SNIPPET_BEFORE = 10;
123
+
124
+ /** The line a JSON.parse SyntaxError points at, from any V8 message form. */
125
+ export function parseErrorLine(raw, e) {
126
+ const lc = /line (\d+) column \d+/.exec(e.message);
127
+ if (lc) return Number(lc[1]);
128
+ const pos = /position (\d+)/.exec(e.message);
129
+ if (pos) return lineAt(raw, Number(pos[1]));
130
+ const snip = /^Unexpected token '(.*?)', (\.\.\.)?"([\s\S]*)"(?:\.\.\.)? is not valid JSON$/.exec(e.message);
131
+ if (snip) {
132
+ const [, token, clipped, escaped] = snip;
133
+ const context = escaped.replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\\\/g, '\\');
134
+ const start = raw.indexOf(context.slice(0, V8_SNIPPET_BEFORE + 2));
135
+ if (start >= 0) {
136
+ const offset = clipped ? V8_SNIPPET_BEFORE : Math.max(0, context.indexOf(token));
137
+ return lineAt(raw, start + offset);
138
+ }
139
+ }
140
+ return 1;
141
+ }
142
+
143
+ /**
144
+ * Path → line for every key and array element in a VALID JSON text
145
+ * (`entries[2].type` → the line that key sits on), so a field error can name
146
+ * the line the way a parse error does. Only ever called after JSON.parse
147
+ * succeeded, which is what keeps this walk simple.
148
+ */
149
+ export function jsonLineMap(raw) {
150
+ const lines = new Map();
151
+ let i = 0;
152
+ const ws = () => { while (i < raw.length && /\s/.test(raw[i])) i++; };
153
+ const str = () => {
154
+ const s = i; i++;
155
+ while (raw[i] !== '"') i += raw[i] === '\\' ? 2 : 1;
156
+ i++;
157
+ return JSON.parse(raw.slice(s, i));
158
+ };
159
+ const value = (path) => {
160
+ ws();
161
+ const c = raw[i];
162
+ if (c === '{') {
163
+ i++; ws();
164
+ if (raw[i] === '}') { i++; return; }
165
+ for (;;) {
166
+ ws();
167
+ const keyStart = i;
168
+ const key = str();
169
+ const p = path ? `${path}.${key}` : key;
170
+ lines.set(p, lineAt(raw, keyStart));
171
+ ws(); i++; // the ':'
172
+ value(p);
173
+ ws();
174
+ if (raw[i] === ',') { i++; continue; }
175
+ i++; return; // '}'
176
+ }
177
+ }
178
+ if (c === '[') {
179
+ i++; ws();
180
+ if (raw[i] === ']') { i++; return; }
181
+ for (let idx = 0; ; idx++) {
182
+ ws();
183
+ lines.set(`${path}[${idx}]`, lineAt(raw, i));
184
+ value(`${path}[${idx}]`);
185
+ ws();
186
+ if (raw[i] === ',') { i++; continue; }
187
+ i++; return; // ']'
188
+ }
189
+ }
190
+ if (c === '"') { str(); return; }
191
+ while (i < raw.length && !/[\s,\]}]/.test(raw[i])) i++; // number/true/false/null
192
+ };
193
+ try { value(''); } catch { /* a walk bug never outranks the real report */ }
194
+ return lines;
195
+ }
196
+
197
+ /**
198
+ * The extra fields a given kind of entry must carry (`UNITS`).
199
+ *
200
+ * A type NOT in this table is accepted rather than refused, and that is
201
+ * deliberate: a catalog is a file someone else wrote, quite possibly against a
202
+ * newer decklight than the one reading it, and rejecting a manifest wholesale
203
+ * because one entry names a kind we have not shipped yet would make every
204
+ * catalog un-addable the day it adds an entry. The unknown kind is surfaced by
205
+ * `marketplace list` instead, where it is information rather than a wall.
206
+ */
207
+ /**
208
+ * The build-time transform invocation contract's own version (SPEC
209
+ * `UNIT_COMPAT`, `OPEN` 2 in MARKETPLACE.md).
210
+ *
211
+ * Deliberately NOT decklight's package version: `src/core/engine.js` has been
212
+ * split apart repeatedly (four modules pulled out in #147 alone) without that
213
+ * ever being a promise to anyone outside the repo, so checking a transform's
214
+ * compatibility against decklight's package.json would tie every installed
215
+ * extension to churn it never touches. This number instead tracks only the
216
+ * narrow "HTML in, HTML out" calling convention `EXTENSIONS#TRANSFORMS`
217
+ * declares, and moves the way `CAST_FORMAT`'s `decklightCast` does: additive
218
+ * only, bumped only when that calling convention itself would break an
219
+ * existing transform, never for an internal reorganisation. A transform
220
+ * declares the lowest version it needs; this decklight is compatible with
221
+ * anything at or below `TRANSFORM_API_VERSION`.
222
+ */
223
+ export const TRANSFORM_API_VERSION = 1;
224
+
225
+ /**
226
+ * The import-adapter invocation contract's own version (SPEC
227
+ * `EXTENSIONS_ADAPTERS`, `EXTENSIONS#ADAPTEREXEC`).
228
+ *
229
+ * A separate counter from `TRANSFORM_API_VERSION`, deliberately: the two are
230
+ * different calling conventions (`html, opts → html` vs `bytes, opts →
231
+ * html`) that will each grow a field on their own schedule, so sharing one
232
+ * number would bump every installed transform's compatibility the day the
233
+ * *importer* contract changed something a transform never touched — the same
234
+ * churn-isolation argument `TRANSFORM_API_VERSION` itself makes against
235
+ * decklight's own package version. Additive-only, the same way: bumped only
236
+ * when the import-adapter calling convention itself would break an existing
237
+ * adapter, never for an internal reorganisation.
238
+ */
239
+ export const IMPORTER_API_VERSION = 1;
240
+
241
+ /**
242
+ * The speech-engine invocation contract's own version (SPEC `ENGINE_UNITS`,
243
+ * `ENGINES#TTS`).
244
+ *
245
+ * A third counter beside the two above, for the third reason they are
246
+ * separate: an engine's convention is not `input → string` at all. It is a
247
+ * FACTORY — `opts → {name, voices, stylable, synth}` — and `synth` returns
248
+ * audio plus a usage record rather than text, so the day either of the other
249
+ * two grows a field, an engine's contract is untouched and must not be
250
+ * invalidated along with them. Additive-only on the same terms: bumped only
251
+ * when the factory or `synth` convention itself would break an installed
252
+ * engine, never for an internal reorganisation of `tools/tts-engines.mjs`
253
+ * (whose six built-ins are not units and are not versioned by this at all).
254
+ */
255
+ export const ENGINE_API_VERSION = 1;
256
+
257
+ /**
258
+ * What an installed engine's `capability` may say, and this decklight runs.
259
+ *
260
+ * `lipsync` joined `tts` with ENGINES#LIPSYNC: the loader's contract is the
261
+ * same factory either way, and what differs is the PREREQUISITES an engine
262
+ * declares (SPEC ENGINE_PREREQUISITES) — a binary and a checkout rather than
263
+ * only a pasted key.
264
+ */
265
+ export const ENGINE_CAPABILITIES = ['tts', 'lipsync'];
266
+
267
+ /**
268
+ * The pin a code-carrying entry installs against (SPEC `UNIT_PINNING`): the
269
+ * SHA-256 of the module file's bytes, lowercase hex, as `sha256sum` prints it
270
+ * and `decklight extension check` emits it on success.
271
+ *
272
+ * Validated for SHAPE when present, like everything else in `ENTRY_SHAPES` —
273
+ * but its ABSENCE is refused at install time (`cli/units.mjs`), not here.
274
+ * Requiring it at the manifest level would invalidate a whole catalog over
275
+ * one unpinned transform, costing its theme entries too — the same
276
+ * blast-radius reasoning that leaves an unknown `type` accepted. The refusal
277
+ * instead lands at the one moment the risk does: installing the executable
278
+ * entry.
279
+ */
280
+ const sha256Shape = (v) => (typeof v === 'string' && /^[0-9a-f]{64}$/.test(v)
281
+ ? null
282
+ : 'must be 64 lowercase hex characters — the SHA-256 of the module file\'s bytes (SPEC UNIT_PINNING)');
283
+
284
+ /** Fields a kind MAY carry, checked only when present — see `sha256Shape`. */
285
+ const ENTRY_SHAPES_OPTIONAL = {
286
+ importer: { sha256: sha256Shape },
287
+ transform: { sha256: sha256Shape },
288
+ // An engine entry wears one `type` for two jobs, and only one of them
289
+ // carries code. `{name, type: 'engine', source, wizard}` DECLARES a wizard
290
+ // for an engine decklight already ships (ENGINES#WIZARD) — it installs
291
+ // nothing, so it has no contract version and no capability to name. An
292
+ // engine UNIT (SPEC ENGINE_UNITS) is a module the loader runs, and needs
293
+ // both. Requiring them here would invalidate every catalog of the first
294
+ // kind, so they are shape-checked when present and their ABSENCE is
295
+ // refused at install (`cli/units.mjs`) — exactly where `sha256`'s is, for
296
+ // exactly the same blast-radius reason.
297
+ engine: {
298
+ sha256: sha256Shape,
299
+ apiVersion: (v) => (Number.isInteger(v) && v >= 1
300
+ ? null
301
+ : 'must be a positive integer — the ENGINE_UNITS contract version this engine needs, not a decklight version'),
302
+ capability: (v) => (typeof v === 'string' && /^[a-z][a-z0-9-]*$/.test(v)
303
+ ? null
304
+ : 'must name the affordance this engine answers for, e.g. "tts"'),
305
+ },
306
+ };
307
+
308
+ const ENTRY_SHAPES = {
309
+ // `import` has to name the adapter for a `.marp` file from the CACHE, with
310
+ // no network — so which extensions an adapter claims is a fact the catalog
311
+ // must carry, not something discoverable by installing it and looking.
312
+ // `apiVersion` is the same shape-only check `transform` gets below, against
313
+ // its own contract (SPEC EXTENSIONS_ADAPTERS) — an adapter is Node code
314
+ // running an installed unit, exactly like a transform is.
315
+ importer: {
316
+ extensions: (v) => (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string' && /^\.?[A-Za-z0-9]+$/.test(x))
317
+ ? null
318
+ : 'must be a non-empty array of file extensions the adapter reads, e.g. [".marp"]'),
319
+ apiVersion: (v) => (Number.isInteger(v) && v >= 1
320
+ ? null
321
+ : 'must be a positive integer — the EXTENSIONS_ADAPTERS contract version this adapter needs, not a decklight version'),
322
+ },
323
+ // A transform is Node code, so it declares the invocation-contract version
324
+ // it needs rather than pinning decklight's own package version (OPEN 2) —
325
+ // see TRANSFORM_API_VERSION above. Any positive integer validates here
326
+ // regardless of what THIS decklight currently implements: a catalog written
327
+ // against a newer contract must stay addable, the same reasoning that
328
+ // leaves an unknown `type` accepted rather than refused (below).
329
+ transform: {
330
+ apiVersion: (v) => (Number.isInteger(v) && v >= 1
331
+ ? null
332
+ : 'must be a positive integer — the EXTENSIONS#TRANSFORMS contract version this transform needs, not a decklight version'),
333
+ },
334
+ // An agent entry is a DESCRIPTOR (SPEC AGENT_UNITS): the binary you already
335
+ // installed, and the argv of its headless mode. Deliberately not code — the
336
+ // three shapes the built-in roster already covers (`-p …`, `exec
337
+ // --full-auto …`, `run -t …`) are a small closed vocabulary a template
338
+ // expresses completely, so teaching decklight a new agent never means
339
+ // downloading and running someone's module (which is why `agent` is in
340
+ // REFERENCE_ONLY below and carries no `sha256`).
341
+ agent: {
342
+ bin: (v) => (typeof v === 'string' && /^[A-Za-z0-9][\w.-]*$/.test(v)
343
+ ? null
344
+ : "must be the agent's executable name, e.g. \"claude\" — a bare command, never a path or a shell line"),
345
+ args: (v) => (Array.isArray(v) && v.length && v.every((x) => typeof x === 'string')
346
+ ? (v.some((x) => x.includes('{prompt}'))
347
+ ? null
348
+ : 'must include {prompt} in one of its arguments — otherwise the agent is handed no instruction')
349
+ : 'must be the argv of the agent\'s headless mode, as an array of strings, e.g. ["-p", "{prompt}"]'),
350
+ },
351
+ // A voice entry is a POINTER (SPEC VOICE_UNITS): which engine, and which of
352
+ // that engine's voices. Both are needed for the roster to be filtered to the
353
+ // engine actually running — a reference to an ElevenLabs voice is not an
354
+ // answer when the bridge is speaking piper.
355
+ voice: {
356
+ engine: (v) => (typeof v === 'string' && /^[a-z][a-z0-9-]*$/.test(v)
357
+ ? null
358
+ : 'must name the TTS engine the voice belongs to, e.g. "elevenlabs"'),
359
+ voiceId: (v) => (typeof v === 'string' && v.trim()
360
+ ? null
361
+ : "must be the engine's own identifier for the voice"),
362
+ },
363
+ };
364
+
365
+ /**
366
+ * Kinds that NAME a thing rather than carrying it (SPEC VOICE_UNITS).
367
+ *
368
+ * A voice is distributed as a reference and never as a payload — no model
369
+ * weights, no sample audio, nothing that reproduces a person offline. The
370
+ * enforcement is this set, and it works by SUBTRACTION: an entry listed here
371
+ * has no `source`, so the code path that fetches bytes is never entered and
372
+ * there is no field through which a cloned voice could arrive.
373
+ *
374
+ * That is deliberately a shape, not an attestation. A `consent: true` field
375
+ * would be one boolean an uploader types and nobody can check — the same
376
+ * defeatable green mark the ingredients label refuses to print (SPEC
377
+ * PRESENTING). Distributing only references puts the consent relationship
378
+ * where it can actually be enforced and revoked: the provider account whose
379
+ * terms governed the cloning, and which can unshare the voice.
380
+ */
381
+ export const REFERENCE_ONLY = new Set(['voice', 'agent']);
382
+
383
+ function shapeErrors(entry, p, err) {
384
+ // NOT an early return when a type declares no required fields: a kind can be
385
+ // all-optional (`engine`, whose two fields are enforced at install instead —
386
+ // ENTRY_SHAPES_OPTIONAL above), and bailing here would skip its shape checks
387
+ // entirely, silently accepting `capability: 42`.
388
+ for (const [field, check] of Object.entries(ENTRY_SHAPES[entry.type] ?? {})) {
389
+ if (entry[field] === undefined) {
390
+ err(`${p}.${field}`, `missing — ${entry.type} entries must declare it: ${check(undefined) ?? 'see UNITS'}`);
391
+ continue;
392
+ }
393
+ const why = check(entry[field]);
394
+ if (why) err(`${p}.${field}`, why);
395
+ }
396
+ for (const [field, check] of Object.entries(ENTRY_SHAPES_OPTIONAL[entry.type] ?? {})) {
397
+ if (entry[field] === undefined) continue;
398
+ const why = check(entry[field]);
399
+ if (why) err(`${p}.${field}`, why);
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Validate a manifest text. Returns `{ ok, manifest, errors }`; every error
405
+ * carries the LINE and the FIELD it is about — a typo in somebody's catalog
406
+ * is met with "line 7: entries[1].type — missing", never a stack trace.
407
+ */
408
+ export function validateManifest(raw) {
409
+ let data;
410
+ try { data = JSON.parse(raw); } catch (e) {
411
+ return { ok: false, manifest: null, errors: [{ line: parseErrorLine(raw, e), field: '(json)', msg: parseMsg(e) }] };
412
+ }
413
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
414
+ return { ok: false, manifest: null, errors: [{ line: 1, field: '(top level)', msg: 'must be a JSON object' }] };
415
+ }
416
+ const lines = jsonLineMap(raw);
417
+ const errors = [];
418
+ // a missing key has no line of its own; its container's line is the honest one
419
+ const at = (path) => lines.get(path) ?? lines.get(path.replace(/\.[^.[\]]+$/, '')) ?? 1;
420
+ const err = (path, msg) => errors.push({ line: at(path), field: path, msg });
421
+
422
+ if (data.name === undefined) err('name', 'missing — the marketplace needs a name');
423
+ else if (typeof data.name !== 'string' || !NAME_RE.test(data.name)) {
424
+ err('name', `${JSON.stringify(data.name)} — letters, digits, - and _ only (it names every entry: entry@${typeof data.name === 'string' ? data.name : 'name'})`);
425
+ }
426
+ if (data.entries === undefined) err('entries', 'missing — an array of { name, type, source, description? }');
427
+ else if (!Array.isArray(data.entries)) err('entries', 'must be an array');
428
+ else {
429
+ const seen = new Map();
430
+ data.entries.forEach((entry, idx) => {
431
+ const p = `entries[${idx}]`;
432
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) { err(p, 'must be an object'); return; }
433
+ if (entry.name === undefined) err(`${p}.name`, 'missing — the name an install asks for');
434
+ else if (typeof entry.name !== 'string' || !NAME_RE.test(entry.name)) {
435
+ err(`${p}.name`, `${JSON.stringify(entry.name)} — letters, digits, - and _ only`);
436
+ } else if (seen.has(entry.name)) {
437
+ err(`${p}.name`, `"${entry.name}" already used by entries[${seen.get(entry.name)}] — entry names are unique within a marketplace`);
438
+ } else seen.set(entry.name, idx);
439
+ if (entry.type === undefined) err(`${p}.type`, 'missing — what kind of thing this is (theme, template, skill, importer, engine, transform, …)');
440
+ else if (typeof entry.type !== 'string' || !/^[a-z][a-z0-9-]*$/.test(entry.type)) {
441
+ err(`${p}.type`, `${JSON.stringify(entry.type)} — a lowercase word (theme, template, skill, importer, engine, transform, …)`);
442
+ } else shapeErrors(entry, p, err);
443
+ if (REFERENCE_ONLY.has(entry.type)) {
444
+ // Refused, not ignored. A `source` on a reference-only entry is the one
445
+ // field through which a voice could arrive as bytes, and an ignored
446
+ // field would let a catalog carry a model that merely never loads.
447
+ if (entry.source !== undefined) {
448
+ err(`${p}.source`, `a ${entry.type} entry names a ${entry.type}, it does not carry one`
449
+ + ' — no source, no model, no sample (SPEC VOICE_UNITS)');
450
+ }
451
+ } else if (entry.source === undefined) {
452
+ err(`${p}.source`, 'missing — the repo-relative path or URL the entry is fetched from');
453
+ } else if (typeof entry.source !== 'string' || !entry.source) err(`${p}.source`, 'must be a non-empty string');
454
+ if (entry.description !== undefined && typeof entry.description !== 'string') {
455
+ err(`${p}.description`, 'must be a string');
456
+ }
457
+ });
458
+ }
459
+ return { ok: errors.length === 0, manifest: errors.length ? null : data, errors };
460
+ }
461
+
462
+ // ── sources: owner/repo, git URL, local path ───────────────────────────────
463
+
464
+ /** What kind of source a spec names. A path that exists always wins. */
465
+ export function classifySource(spec, { exists = existsSync } = {}) {
466
+ const gh = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(spec);
467
+ if (gh) return { kind: 'github', owner: gh[1], repo: gh[2], spec };
468
+ if (/^(git@|ssh:\/\/|git:\/\/|https?:\/\/)/.test(spec)) return { kind: 'git', url: spec, spec };
469
+ if (/^[\w.-]+\/[\w.-]+$/.test(spec) && !spec.startsWith('.') && !exists(spec)) {
470
+ const [owner, repo] = spec.split('/');
471
+ return { kind: 'github', owner, repo, spec };
472
+ }
473
+ return { kind: 'local', root: resolve(spec), spec };
474
+ }
475
+
476
+ const fetchWhy = (e, timeoutMs) =>
477
+ e.name === 'TimeoutError' || e.code === 'ABORT_ERR'
478
+ ? `no response after ${timeoutMs / 1000}s`
479
+ : String(e.cause?.code ?? e.cause?.message ?? e.message);
480
+
481
+ /**
482
+ * The manifest text at a source's root. The only network in the subsystem —
483
+ * and it fails FAST and says why: the fetch carries a timeout, git is told
484
+ * never to prompt, and offline is an answer, not a hang (a plane is a
485
+ * first-class place to run decklight).
486
+ */
487
+ export async function fetchManifestText(src, { fetchImpl = fetch, exec = execFileSync, timeoutMs = 8000 } = {}) {
488
+ if (src.kind === 'local') {
489
+ if (!existsSync(src.root)) throw new MarketplaceError(`no such directory: ${src.spec}`);
490
+ const p = join(src.root, MANIFEST_PATH);
491
+ if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
492
+ return readFileSync(p, 'utf8');
493
+ }
494
+ if (src.kind === 'github') {
495
+ const url = `https://raw.githubusercontent.com/${src.owner}/${src.repo}/HEAD/${MANIFEST_PATH}`;
496
+ let r;
497
+ try {
498
+ r = await fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), redirect: 'follow' });
499
+ } catch (e) {
500
+ throw new MarketplaceError(`could not fetch ${src.spec} — ${fetchWhy(e, timeoutMs)}`
501
+ + ' (offline? the cached copy, if any, still serves `marketplace list`)');
502
+ }
503
+ if (r.status === 404) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} (HTTP 404)`);
504
+ if (!r.ok) throw new MarketplaceError(`could not fetch ${src.spec} — HTTP ${r.status}`);
505
+ return await r.text();
506
+ }
507
+ // an arbitrary git URL: shallow-clone somewhere disposable, read one file
508
+ const tmp = mkdtempSync(join(tmpdir(), 'decklight-marketplace-'));
509
+ try {
510
+ exec('git', ['clone', '--quiet', '--depth', '1', src.url, tmp], {
511
+ stdio: ['ignore', 'pipe', 'pipe'], timeout: timeoutMs * 4,
512
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
513
+ });
514
+ const p = join(tmp, MANIFEST_PATH);
515
+ if (!existsSync(p)) throw new MarketplaceError(`${src.spec} has no ${MANIFEST_PATH} — is it a marketplace repo?`);
516
+ return readFileSync(p, 'utf8');
517
+ } catch (e) {
518
+ if (e instanceof MarketplaceError) throw e;
519
+ throw new MarketplaceError(`git clone ${src.spec} failed — ${oneline(e)}`);
520
+ } finally {
521
+ rmSync(tmp, { recursive: true, force: true });
522
+ }
523
+ }
524
+
525
+ // ── the cache, and names ───────────────────────────────────────────────────
526
+
527
+ /** The cached manifest for `name`: null when never fetched, else a validation. */
528
+ export function loadCatalog(name, home = configHome()) {
529
+ const p = cachePath(home, name);
530
+ if (!existsSync(p)) return null;
531
+ return validateManifest(readFileSync(p, 'utf8'));
532
+ }
533
+
534
+ /**
535
+ * Resolve an entry reference against every cached catalog. `name@marketplace`
536
+ * is exact; a bare name resolves only when it exists in exactly ONE
537
+ * registered marketplace — two is reported as ambiguous with the qualified
538
+ * forms to say instead, never silently resolved to either. This is the seam
539
+ * every install surface (theme browse, engine wizard, `init --from`) goes
540
+ * through; nothing in THIS command installs anything.
541
+ */
542
+ export function resolveEntry(ref, catalogs) {
543
+ const q = /^(.+)@([^@]+)$/.exec(ref);
544
+ if (q) {
545
+ const [, entryName, market] = q;
546
+ const cat = catalogs[market];
547
+ if (!cat) throw new MarketplaceError(`no marketplace "${market}" is registered (decklight marketplace list)`);
548
+ const entry = (cat.entries ?? []).find((e) => e.name === entryName);
549
+ if (!entry) throw new MarketplaceError(`no "${entryName}" in ${market}`);
550
+ return { entry, marketplace: market, qualified: `${entryName}@${market}` };
551
+ }
552
+ const hits = [];
553
+ for (const [market, cat] of Object.entries(catalogs)) {
554
+ for (const e of cat?.entries ?? []) {
555
+ if (e.name === ref) hits.push({ entry: e, marketplace: market, qualified: `${ref}@${market}` });
556
+ }
557
+ }
558
+ if (hits.length === 0) throw new MarketplaceError(`no "${ref}" in any registered marketplace`);
559
+ if (hits.length > 1) {
560
+ throw new MarketplaceError(`"${ref}" is ambiguous — it exists in ${hits.length} marketplaces:`
561
+ + ` ${hits.map((h) => h.qualified).join(', ')} — say which`);
562
+ }
563
+ return hits[0];
564
+ }
565
+
566
+ // ── the command ────────────────────────────────────────────────────────────
567
+
568
+ const USAGE = `usage: decklight marketplace <add|list|update|remove> …
569
+
570
+ decklight marketplace add <owner/repo | git url | path> [--name <name>]
571
+ read ${MANIFEST_PATH} at the source's root and register the catalog
572
+ under ~/.decklight/ — a local path never touches the network
573
+ EXAMPLE: decklight marketplace add decklight/decklight-plugins-official
574
+ EXAMPLE: decklight marketplace add ../my-marketplace
575
+
576
+ decklight marketplace list
577
+ every registered marketplace and its cached entries (as name@marketplace),
578
+ read from the cache alone — list works on a plane
579
+
580
+ decklight marketplace update <name>
581
+ re-fetch a marketplace's manifest and refresh the cached copy; for a
582
+ registered-not-fetched marketplace this is the FIRST fetch it ever gets
583
+
584
+ decklight marketplace remove <name>
585
+ unregister a marketplace and drop its cached manifest
586
+
587
+ registering is not fetching: the network is touched only by an explicit add
588
+ or update, never when a deck loads or presents (SPEC MARKETPLACE_REGISTRY).
589
+ DECKLIGHT_HOME overrides ~/.decklight/.`;
590
+
591
+ const printManifestErrors = (cmd, spec, errors) => {
592
+ console.error(`decklight marketplace ${cmd}: ${spec} — ${MANIFEST_PATH} is not a valid marketplace manifest:`);
593
+ for (const e of errors) console.error(` line ${e.line}: ${e.field} — ${e.msg}`);
594
+ };
595
+
596
+ const entriesSummary = (name, entries) => {
597
+ const shown = entries.slice(0, 6).map((e) => `${e.name}@${name}`);
598
+ if (entries.length > shown.length) shown.push(`… ${entries.length - shown.length} more`);
599
+ return `${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}${entries.length ? `: ${shown.join(', ')}` : ''}`;
600
+ };
601
+
602
+ async function addMain(args, home) {
603
+ const { opt } = argReader(args);
604
+ const [spec] = args.filter((a, i) => !a.startsWith('-') && args[i - 1] !== '--name');
605
+ if (!spec) { console.error(`decklight marketplace add: needs an owner/repo, a git url, or a path\n\n${USAGE}`); return 1; }
606
+
607
+ const src = classifySource(spec);
608
+ let raw;
609
+ try { raw = await fetchManifestText(src); } catch (e) {
610
+ console.error(`decklight marketplace add: ${e.message}`);
611
+ return 1;
612
+ }
613
+ const v = validateManifest(raw);
614
+ if (!v.ok) { printManifestErrors('add', spec, v.errors); return 1; }
615
+
616
+ const name = opt('--name') ?? v.manifest.name;
617
+ if (!NAME_RE.test(name)) { console.error(`decklight marketplace add: "${name}" is not a usable marketplace name`); return 1; }
618
+
619
+ const reg = loadRegistry(home);
620
+ const existing = reg.marketplaces[name];
621
+ if (existing && existing.source !== spec) {
622
+ console.error(`decklight marketplace add: "${name}" is already registered from ${existing.source}`);
623
+ console.error(` remove it first, or register this one under another name with --name`);
624
+ return 1;
625
+ }
626
+ reg.marketplaces[name] = { ...(existing ?? {}), source: spec };
627
+ writeCache(home, name, raw);
628
+ saveRegistry(reg, home);
629
+ console.log(`${existing ? 'refreshed' : 'registered'} ${name} from ${spec} — ${entriesSummary(name, v.manifest.entries)}`);
630
+ return 0;
631
+ }
632
+
633
+ function writeCache(home, name, raw) {
634
+ mkdirSync(join(home, 'marketplaces'), { recursive: true });
635
+ writeFileSync(cachePath(home, name), raw);
636
+ }
637
+
638
+ function listMain(home) {
639
+ const reg = loadRegistry(home);
640
+ const names = Object.keys(reg.marketplaces).sort();
641
+ if (!names.length) {
642
+ console.log('no marketplaces registered — decklight marketplace add <owner/repo | git url | path>');
643
+ return 0;
644
+ }
645
+ for (const name of names) {
646
+ const m = reg.marketplaces[name];
647
+ const head = `${name}${m.firstParty ? ' (first-party)' : ''} ${m.source}`;
648
+ const cached = loadCatalog(name, home);
649
+ if (cached === null) {
650
+ console.log(`${head} — registered, not fetched (decklight marketplace update ${name})`);
651
+ } else if (!cached.ok) {
652
+ console.log(`${head} — cached copy unreadable (decklight marketplace update ${name})`);
653
+ } else {
654
+ // Grouped by KIND rather than listed flat (UNITS): a catalog's entries
655
+ // are not one undifferentiated bag of names — what you can do with an
656
+ // entry depends entirely on what kind it is, and the install command
657
+ // differs per kind. A kind this decklight does not know is shown as
658
+ // exactly that, so a catalog written against a newer version reads as
659
+ // "not yet" rather than as a typo.
660
+ const entries = cached.manifest.entries;
661
+ console.log(`${head} — ${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}`);
662
+ const kinds = [...new Set(entries.map((e) => e.type))].sort();
663
+ for (const kind of kinds) {
664
+ const known = KNOWN_TYPES.includes(kind);
665
+ const how = INSTALL_HINT[kind];
666
+ console.log(` ${kind}${known ? '' : ' (this decklight does not install this kind)'}`
667
+ + `${how ? ` — ${how}` : ''}`);
668
+ for (const e of entries.filter((x) => x.type === kind)) {
669
+ console.log(` ${e.name}@${name}${e.description ? ` — ${e.description}` : ''}`);
670
+ }
671
+ }
672
+ }
673
+ }
674
+ return 0;
675
+ }
676
+
677
+ async function updateMain(args, home) {
678
+ const [name] = args.filter((a) => !a.startsWith('-'));
679
+ if (!name) { console.error(`decklight marketplace update: which one?\n\n${USAGE}`); return 1; }
680
+ const reg = loadRegistry(home);
681
+ const m = reg.marketplaces[name];
682
+ if (!m) { console.error(`decklight marketplace update: no marketplace "${name}" (decklight marketplace list)`); return 1; }
683
+
684
+ const first = loadCatalog(name, home) === null;
685
+ let raw;
686
+ try { raw = await fetchManifestText(classifySource(m.source)); } catch (e) {
687
+ console.error(`decklight marketplace update: ${name}: ${e.message}`);
688
+ if (!first) console.error(` the cached copy is untouched — list still works`);
689
+ return 1;
690
+ }
691
+ const v = validateManifest(raw);
692
+ if (!v.ok) { printManifestErrors('update', m.source, v.errors); return 1; }
693
+ writeCache(home, name, raw);
694
+ console.log(`${first ? 'fetched' : 'updated'} ${name} — ${entriesSummary(name, v.manifest.entries)}`);
695
+ return 0;
696
+ }
697
+
698
+ function removeMain(args, home) {
699
+ const [name] = args.filter((a) => !a.startsWith('-'));
700
+ if (!name) { console.error(`decklight marketplace remove: which one?\n\n${USAGE}`); return 1; }
701
+ const reg = loadRegistry(home);
702
+ const m = reg.marketplaces[name];
703
+ if (!m) { console.error(`decklight marketplace remove: no marketplace "${name}" (decklight marketplace list)`); return 1; }
704
+ delete reg.marketplaces[name];
705
+ saveRegistry(reg, home);
706
+ rmSync(cachePath(home, name), { force: true });
707
+ console.log(`removed ${name} — re-add any time with: decklight marketplace add ${m.source}`);
708
+ return 0;
709
+ }
710
+
711
+ export async function marketplaceMain(args = []) {
712
+ const sub = args[0];
713
+ if (!sub || sub === '--help' || sub === '-h' || sub === 'help') { console.log(USAGE); return sub ? 0 : 1; }
714
+ const rest = args.slice(1);
715
+ if (rest.includes('--help') || rest.includes('-h')) { console.log(USAGE); return 0; }
716
+ const home = configHome();
717
+ try {
718
+ if (sub === 'add') return await addMain(rest, home);
719
+ if (sub === 'list') return listMain(home);
720
+ if (sub === 'update') return await updateMain(rest, home);
721
+ if (sub === 'remove') return removeMain(rest, home);
722
+ } catch (e) {
723
+ if (e instanceof MarketplaceError) { console.error(`decklight marketplace ${sub}: ${e.message}`); return 1; }
724
+ throw e;
725
+ }
726
+ console.error(`decklight marketplace: unknown subcommand "${sub}"\n\n${USAGE}`);
727
+ return 1;
728
+ }
729
+
730
+ if (isMain(import.meta.url)) process.exit(await marketplaceMain(process.argv.slice(2)));