dsh-version-manager 0.0.0-stage → 0.1.1

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,1336 @@
1
+ /**
2
+ * The JSON surface the panel talks to.
3
+ *
4
+ * Every route is read-only unless its name says otherwise, and the two write
5
+ * routes (`snapshot`, `update`) demand an explicit `{ confirm: true }` body in
6
+ * addition to passing the host's own admission check. There is no timer here and
7
+ * no work starts on its own: a refresh is a request, and a change is a request,
8
+ * which keeps the plugin's cost equal to what the user asked for.
9
+ *
10
+ * Admission comes from `connection.admit(req)`, the same check the host applies
11
+ * to its own browser traffic. When that service is absent the route refuses
12
+ * rather than falling back to "it is localhost so it is fine" — a local port is
13
+ * shared by every process on the machine.
14
+ *
15
+ * @module dsh-version-manager/lib/host/routes
16
+ */
17
+
18
+ import { readFile } from 'node:fs/promises'
19
+ import { join } from 'node:path'
20
+
21
+ import {
22
+ buildPluginRows,
23
+ readLoaderPhases,
24
+ readProfileManifest,
25
+ } from './inventory.js'
26
+ import { evaluateCompatibility, manifestVersion } from './compat.js'
27
+ import { hostInfo, readInstalledManifest } from './locate.js'
28
+ import { registryFor } from './lockfile.js'
29
+ import { readRegistry } from './git-skill.js'
30
+ import {
31
+ listGitSkills,
32
+ previewGitRoute,
33
+ registerGitRoute,
34
+ restoreGitRoute,
35
+ unregisterGitRoute,
36
+ updateGitRoute,
37
+ } from './git-routes.js'
38
+ import { listSkillSnapshots, readSkills, snapshotSkill } from './skills.js'
39
+ import { previewSkillRestore, restoreSkillSnapshot, skillRestoreRefusal } from './skill-restore.js'
40
+ import { TERMINAL, beginOperation, listOperations, transition, unresolved } from './operations.js'
41
+ import {
42
+ deleteSnapshot,
43
+ fingerprintTree,
44
+ listSnapshots,
45
+ recoveryVerdict,
46
+ snapshotsBeyondRetention,
47
+ writeSnapshot,
48
+ } from './snapshot-store.js'
49
+ import { classifySpec, declaredSpecMatches, isPrerelease, updateRefusal } from './spec.js'
50
+
51
+ /** Every route this plugin publishes, so the panel and the tests share one list. */
52
+ export const ROUTE_BASE = '/dsh-version-manager'
53
+
54
+ /** Bodies are tiny here; anything larger is not a request this plugin serves. */
55
+ const MAX_BODY = 64 * 1024
56
+
57
+ /**
58
+ * Send JSON and never let a rejected promise silence the response.
59
+ *
60
+ * @param {import('node:http').ServerResponse} response
61
+ * @param {number} status
62
+ * @param {unknown} body
63
+ */
64
+ export function sendJson(response, status, body) {
65
+ const text = JSON.stringify(body)
66
+ response.writeHead(status, {
67
+ 'content-type': 'application/json; charset=utf-8',
68
+ // A version panel that answers with a cached body describes a machine state
69
+ // that may no longer exist, and every row shows its own `observedAt`.
70
+ 'cache-control': 'no-store',
71
+ })
72
+ response.end(text)
73
+ }
74
+
75
+ /**
76
+ * Read a JSON body, bounded.
77
+ *
78
+ * @param {import('node:http').IncomingMessage} request
79
+ * @returns {Promise<{ ok: true, value: any } | { ok: false, status: number, message: string }>}
80
+ */
81
+ export async function readJsonBody(request) {
82
+ const chunks = []
83
+ let size = 0
84
+ try {
85
+ for await (const chunk of request) {
86
+ size += chunk.length
87
+ if (size > MAX_BODY) return { ok: false, status: 413, message: 'request body too large' }
88
+ chunks.push(chunk)
89
+ }
90
+ } catch {
91
+ return { ok: false, status: 400, message: 'request body could not be read' }
92
+ }
93
+ if (size === 0) return { ok: true, value: {} }
94
+ try {
95
+ return { ok: true, value: JSON.parse(Buffer.concat(chunks).toString('utf8')) }
96
+ } catch {
97
+ return { ok: false, status: 400, message: 'request body was not JSON' }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Is this request allowed to run anything at all?
103
+ *
104
+ * @param {any} ctx
105
+ * @param {import('node:http').IncomingMessage} request
106
+ * @returns {{ ok: true, principal: string } | { ok: false, status: number }}
107
+ */
108
+ export function admit(ctx, request) {
109
+ const connection = ctx?.get?.('connection')
110
+ if (connection === undefined || connection === null || typeof connection.admit !== 'function') {
111
+ // No admission service means no way to tell the browser from any other local
112
+ // process. Refusing is the only answer that does not invent a security model.
113
+ return { ok: false, status: 401 }
114
+ }
115
+ let admission
116
+ try {
117
+ admission = connection.admit(request)
118
+ } catch {
119
+ return { ok: false, status: 401 }
120
+ }
121
+ if (admission === null || typeof admission !== 'object') return { ok: false, status: 401 }
122
+ if ('rejection' in admission) return { ok: false, status: admission.rejection }
123
+ const kind = admission.peer?.principal?.kind
124
+ if (kind !== 'owner') return { ok: false, status: 403 }
125
+ return { ok: true, principal: kind }
126
+ }
127
+
128
+ /**
129
+ * Everything the panel needs to draw the first screen.
130
+ *
131
+ * @param {any} ctx
132
+ * @returns {Promise<Object>}
133
+ */
134
+ export async function buildOverview(ctx) {
135
+ const profile = readProfileContext(ctx)
136
+ const pluginManager = ctx?.get?.('pluginManager')
137
+
138
+ let bundles = []
139
+ let inventoryError = null
140
+ if (pluginManager === undefined || pluginManager === null) {
141
+ inventoryError = 'The plugin manager service is not available in this host.'
142
+ } else {
143
+ try {
144
+ bundles = await pluginManager.listBundles()
145
+ } catch (error) {
146
+ inventoryError = error instanceof Error ? error.message : String(error)
147
+ }
148
+ }
149
+
150
+ const phases = await readLoaderPhases(ctx)
151
+ const manifest = await readManifest(profile.dir)
152
+ const lock = await readLockfile(profile.dir)
153
+ const { runtimeVersion, runtimeSource } = readRuntime(ctx)
154
+ const exemptions = await readExemptions(profile.dir)
155
+ const hostRoot = hostInfo().root
156
+
157
+ const rows = buildPluginRows({
158
+ bundles: Array.isArray(bundles) ? bundles : [],
159
+ phases: phases.byName,
160
+ phaseAvailable: phases.available,
161
+ phaseDiagnostic: phases.diagnostic,
162
+ profileId: profile.id,
163
+ runtimeVersion,
164
+ })
165
+
166
+ for (const row of rows) {
167
+ // A registry is stored per install, not per profile: an explicit `--registry`
168
+ // lands in the lockfile as an https tarball, and an ordinary install leaves
169
+ // the host unrecorded. Both answers are shown, and "unknown" keeps its reason.
170
+ const fromLock = registryFor({
171
+ name: row.targetId,
172
+ lockText: lock.text,
173
+ lockfileReadable: lock.readable,
174
+ declaredSpec: row.declaredSpec,
175
+ })
176
+ row.source.registry = fromLock.registry
177
+ row.source.registryReason = fromLock.reason
178
+
179
+ // The profile manifest stores the bare range ("1.7.3", "^0.4.0"), while the
180
+ // host reports the install spec ("name@range"). Compare the range half so a
181
+ // matching pair is not reported as a drift. A profile with no manifest is
182
+ // normal right after it is created, and it must degrade to "nothing recorded"
183
+ // rather than take the whole overview down with it.
184
+ const declared = manifest?.dependencies?.[row.targetId]
185
+ row.declaredSpecObserved = typeof declared === 'string' ? declared : null
186
+ row.declaredSpecMatchesManifest = declaredSpecMatches(
187
+ row.declaredSpec,
188
+ row.declaredSpecObserved,
189
+ row.targetId,
190
+ )
191
+
192
+ // Compatibility is evaluated from the installed manifest the same way the
193
+ // host evaluates it before loading a bundle. Without a manifest the answer
194
+ // is "unknown", never "fine".
195
+ const installed = readInstalledManifest(row.targetId, { profileDir: profile.dir, hostRoot })
196
+ row.compatibility = evaluateCompatibility({
197
+ manifest: installed,
198
+ runtimeVersion,
199
+ exemptions,
200
+ packageVersion: manifestVersion(installed) ?? row.installedVersion ?? null,
201
+ exemptionKey: `${row.targetId}@${manifestVersion(installed) ?? row.installedVersion ?? ''}`,
202
+ })
203
+ row.compatibility.detail = typeof row.loadError === 'string' ? row.loadError : null
204
+
205
+ row.snapshots = (await listSnapshots(profile.home, profile.id, row.targetId)).map(summarise)
206
+ }
207
+
208
+ const operations = await listOperations(profile.home, profile.id, 30)
209
+
210
+ return {
211
+ schemaVersion: 1,
212
+ observedAt: new Date().toISOString(),
213
+ profile: {
214
+ id: profile.id,
215
+ // A directory is a local fact. The panel shows it; a shared report does not.
216
+ dir: profile.dir ?? null,
217
+ home: profile.home ?? null,
218
+ kind: profile.kind,
219
+ identitySource: profile.identitySource,
220
+ },
221
+ host: {
222
+ runtimeVersion,
223
+ runtimeSource,
224
+ node: process.versions?.node ?? null,
225
+ platform: process.platform,
226
+ pluginManager: pluginManager !== undefined && pluginManager !== null,
227
+ loader: phases.available,
228
+ },
229
+ counts: {
230
+ total: rows.length,
231
+ // Named for what it measures. "Writable" means the host would accept an
232
+ // update for this entry; it says nothing about whether a newer version
233
+ // exists, which only a per-target version check can answer. Calling this
234
+ // "updatable" made the panel promise updates that did not exist.
235
+ writable: rows.filter((row) => row.updateRefusal === null).length,
236
+ official: rows.filter((row) => row.official).length,
237
+ // Three useful totals: what the host would let us write, what the host
238
+ // would refuse to load, and what this plugin could not evaluate.
239
+ unsatisfied: rows.filter((row) => row.compatibility?.verdict === 'unsatisfied').length,
240
+ unknownCompatibility: rows.filter((row) => row.compatibility?.verdict === 'unknown').length,
241
+ },
242
+ plugins: rows,
243
+ operations: operations.map(summariseOperation),
244
+ unresolved: unresolved(operations).map((record) => record.id),
245
+ error: inventoryError,
246
+ }
247
+ }
248
+
249
+ /**
250
+ * @param {object} row
251
+ * @returns {object}
252
+ */
253
+ function summarise(row) {
254
+ return {
255
+ seq: row.seq,
256
+ id: row.id,
257
+ takenAt: row.takenAt,
258
+ reason: row.reason,
259
+ installedVersion: row.installedVersion,
260
+ file: row.file,
261
+ }
262
+ }
263
+
264
+ /**
265
+ * @param {object} record
266
+ * @returns {object}
267
+ */
268
+ function summariseOperation(record) {
269
+ return {
270
+ id: record.id,
271
+ startedAt: record.startedAt,
272
+ state: record.state,
273
+ targetId: record.target?.targetId ?? null,
274
+ fromVersion: record.target?.fromVersion ?? null,
275
+ toVersion: record.target?.toVersion ?? null,
276
+ snapshotId: record.snapshotId ?? null,
277
+ error: record.error ?? null,
278
+ terminal: TERMINAL.includes(record.state),
279
+ transitions: record.transitions ?? [],
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Read the profile identity from the host, and say where each part came from.
285
+ *
286
+ * A profile whose identity cannot be established is not a profile this plugin
287
+ * will write into: snapshots are keyed by it, so a guessed key would put two
288
+ * different profiles' history in one place.
289
+ *
290
+ * @param {any} ctx
291
+ * @returns {{ id: string, dir: string | null, home: string | null, kind: string, identitySource: string }}
292
+ */
293
+ export function readProfileContext(ctx) {
294
+ const profile = ctx?.get?.('profileContext')
295
+ const name = profile?.name
296
+ const home = profile?.home ?? process.env.DSH_HOME ?? null
297
+ const cwd = typeof profile?.cwd === 'string' ? profile.cwd : null
298
+ if (typeof name === 'string' && name !== '') {
299
+ return {
300
+ id: name,
301
+ dir: typeof profile?.dir === 'string' ? profile.dir : null,
302
+ home,
303
+ cwd,
304
+ kind: 'dsh-profile',
305
+ identitySource: 'profileContext',
306
+ }
307
+ }
308
+ return {
309
+ id: 'unknown',
310
+ dir: null,
311
+ home,
312
+ cwd,
313
+ kind: 'unknown',
314
+ identitySource: 'no profileContext service',
315
+ }
316
+ }
317
+
318
+ /**
319
+ * Read the host's runtime version, or admit that it is not readable.
320
+ *
321
+ * `pluginContext`-independent: the version DSH writes into compatibility checks
322
+ * belongs to the app-boot package, and importing it here would tie this plugin to
323
+ * a peer that a newer host may move. The panel therefore reports what it could
324
+ * observe and marks the rest unknown.
325
+ *
326
+ * @param {any} ctx
327
+ * @returns {{ runtimeVersion: string | null }}
328
+ */
329
+ export function readRuntime(ctx) {
330
+ const fromHost = ctx?.get?.('dshRuntimeVersion')
331
+ if (typeof fromHost === 'string' && fromHost !== '') {
332
+ return { runtimeVersion: fromHost, runtimeSource: 'host service' }
333
+ }
334
+ const env = process.env.DSH_VERSION
335
+ if (typeof env === 'string' && env !== '') {
336
+ return { runtimeVersion: env, runtimeSource: 'DSH_VERSION' }
337
+ }
338
+ // The host does not expose its own version as a service, but the package that
339
+ // owns the compatibility rule is on disk next to the running process. Reading
340
+ // its manifest is the same number the host compares against, so this is an
341
+ // observation rather than a guess.
342
+ const located = hostInfo()
343
+ if (located.runtimeVersion !== null) {
344
+ return { runtimeVersion: located.runtimeVersion, runtimeSource: located.source }
345
+ }
346
+ return { runtimeVersion: null, runtimeSource: null }
347
+ }
348
+
349
+ /**
350
+ * Read the profile's exact-version exemptions.
351
+ *
352
+ * The file is written by `dsh plugin allow-version` and lives at the profile
353
+ * root. A malformed or absent file means "no exemptions", which only ever makes
354
+ * the panel stricter, never looser.
355
+ *
356
+ * @param {string | null} dir
357
+ * @returns {Promise<Record<string, string[]>>}
358
+ */
359
+ async function readExemptions(dir) {
360
+ if (dir === null) return {}
361
+ try {
362
+ const parsed = JSON.parse(await readFile(join(dir, 'compatibility.json'), 'utf8'))
363
+ if (parsed === null || typeof parsed !== 'object') return {}
364
+ /** @type {Record<string, string[]>} */
365
+ const out = {}
366
+ for (const [key, value] of Object.entries(parsed)) {
367
+ if (Array.isArray(value)) out[key] = value.filter((item) => typeof item === 'string')
368
+ }
369
+ return out
370
+ } catch {
371
+ return {}
372
+ }
373
+ }
374
+
375
+ /**
376
+ * @param {string | null} dir
377
+ * @returns {Promise<object | null>}
378
+ */
379
+ async function readManifest(dir) {
380
+ if (dir === null) return null
381
+ try {
382
+ return JSON.parse(await readFile(join(dir, 'package.json'), 'utf8'))
383
+ } catch {
384
+ return null
385
+ }
386
+ }
387
+
388
+ /**
389
+ * @param {string | null} dir
390
+ * @returns {Promise<{ text: string | null, readable: boolean }>}
391
+ */
392
+ async function readLockfile(dir) {
393
+ if (dir === null) return { text: null, readable: false }
394
+ for (const file of ['pnpm-lock.yaml', 'pnpm-lock.yml', 'package-lock.json']) {
395
+ try {
396
+ return { text: await readFile(join(dir, file), 'utf8'), readable: true }
397
+ } catch {
398
+ // Try the next lockfile format. A profile may have none at all.
399
+ }
400
+ }
401
+ return { text: null, readable: false }
402
+ }
403
+
404
+ /**
405
+ * Versions newer than the installed one, with the facts needed to decide.
406
+ *
407
+ * Prereleases are separated rather than filtered away: a user who is already on
408
+ * a prerelease must see their own channel, and a user on a stable release must
409
+ * not be pushed onto one by default.
410
+ *
411
+ * @param {any} ctx
412
+ * @param {string} name
413
+ * @param {{ registry?: string }} options
414
+ * @returns {Promise<object>}
415
+ */
416
+ export async function readVersions(ctx, name, options = {}) {
417
+ const profile = readProfileContext(ctx)
418
+ const pluginManager = ctx?.get?.('pluginManager')
419
+ if (pluginManager === undefined || pluginManager === null) {
420
+ return { status: 'unavailable', reason: 'no-plugin-manager', versions: [] }
421
+ }
422
+
423
+ let bundles = []
424
+ try {
425
+ bundles = await pluginManager.listBundles()
426
+ } catch (error) {
427
+ return { status: 'unavailable', reason: 'inventory-failed', message: messageOf(error), versions: [] }
428
+ }
429
+ const row = bundles.find((bundle) => bundle.name === name)
430
+ if (row === undefined) {
431
+ return { status: 'unknown-target', reason: 'not-in-profile', versions: [] }
432
+ }
433
+ const parsed = classifySpec(row.source, { official: row.official })
434
+ const refusal = updateRefusal(row, parsed)
435
+ if (refusal !== null) {
436
+ return {
437
+ status: 'read_only',
438
+ reason: 'update-not-offered',
439
+ message: refusal,
440
+ versions: [],
441
+ }
442
+ }
443
+
444
+ let result
445
+ try {
446
+ result = await pluginManager.listVersions(name, options.registry === undefined ? undefined : { registry: options.registry })
447
+ } catch (error) {
448
+ return { status: 'error', reason: 'list-failed', message: messageOf(error), versions: [] }
449
+ }
450
+ if (result === null || typeof result !== 'object') {
451
+ return { status: 'error', reason: 'bad-response', versions: [] }
452
+ }
453
+ if (result.status === 'refused') {
454
+ return {
455
+ status: 'read_only',
456
+ reason: result.problem ?? 'refused',
457
+ message: typeof result.reason === 'string' ? result.reason : null,
458
+ versions: [],
459
+ }
460
+ }
461
+
462
+ const versions = Array.isArray(result.versions) ? result.versions : []
463
+ const stable = []
464
+ const prerelease = []
465
+ for (const entry of versions) {
466
+ const item = {
467
+ version: typeof entry.version === 'string' ? entry.version : null,
468
+ publishedAt: entry.publishedAt ?? null,
469
+ deprecated: entry.deprecated ?? null,
470
+ isBundle: entry.bundle === true,
471
+ compatibility: entry.compatibility ?? null,
472
+ prerelease: isPrerelease(entry.version),
473
+ }
474
+ if (item.version === null) continue
475
+ if (item.prerelease) prerelease.push(item)
476
+ else stable.push(item)
477
+ }
478
+
479
+ return {
480
+ status: 'ok',
481
+ observedAt: new Date().toISOString(),
482
+ profileId: profile.id,
483
+ installed: typeof row.version === 'string' ? row.version : null,
484
+ registry: result.registry ?? null,
485
+ attempts: result.attempts ?? [],
486
+ omitted: result.omitted ?? 0,
487
+ stable,
488
+ prerelease,
489
+ versions: [...stable, ...prerelease],
490
+ }
491
+ }
492
+
493
+ /**
494
+ * @param {unknown} error
495
+ * @returns {string}
496
+ */
497
+ function messageOf(error) {
498
+ if (error instanceof Error) return error.message
499
+ return String(error)
500
+ }
501
+
502
+ /**
503
+ * Take a snapshot of one installed target.
504
+ *
505
+ * @param {any} ctx
506
+ * @param {{ targetId: string, reason?: string }} body
507
+ * @returns {Promise<{ status: number, body: object }>}
508
+ */
509
+ /**
510
+ * Copy one skill directory into the snapshot store.
511
+ *
512
+ * The skill is located through the host's own catalog rather than from a path
513
+ * in the request, so a crafted body cannot point this at an arbitrary folder.
514
+ */
515
+ export async function takeSkillSnapshot(ctx, body) {
516
+ const profile = readProfileContext(ctx)
517
+ if (profile.home === null || profile.id === 'unknown') {
518
+ return { status: 409, body: { error: 'profile-identity-unknown' } }
519
+ }
520
+ const name = typeof body.name === 'string' ? body.name : ''
521
+ if (name === '') return { status: 400, body: { error: 'missing-name' } }
522
+
523
+ const catalog = await readSkills(ctx, { cwd: profile.cwd })
524
+ const skill = catalog.skills.find((entry) => entry.name === name)
525
+ if (skill === undefined) {
526
+ return {
527
+ status: 404,
528
+ body: {
529
+ error: 'unknown-skill',
530
+ message: catalog.available ? 'That skill is not in the host catalog.' : catalog.reason,
531
+ },
532
+ }
533
+ }
534
+ if (skill.directory === null) {
535
+ return {
536
+ status: 409,
537
+ body: {
538
+ error: 'no-directory',
539
+ message: 'This skill is a single file, so there is no directory to copy.',
540
+ },
541
+ }
542
+ }
543
+ try {
544
+ const result = await snapshotSkill({
545
+ dshHome: profile.home,
546
+ profileId: profile.id,
547
+ name,
548
+ directory: skill.directory,
549
+ git: skill.git,
550
+ })
551
+ return {
552
+ status: 200,
553
+ body: {
554
+ ok: true,
555
+ snapshot: {
556
+ takenAt: result.manifest.takenAt,
557
+ digest: result.manifest.skill.digest,
558
+ fileCount: result.manifest.skill.fileCount,
559
+ revision: result.manifest.git?.revision ?? null,
560
+ },
561
+ },
562
+ }
563
+ } catch (error) {
564
+ return { status: 409, body: { error: 'snapshot-failed', message: messageOf(error) } }
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Resolve one skill from the host catalog, never from a path in the request.
570
+ *
571
+ * @param {any} ctx
572
+ * @param {string} name
573
+ * @returns {Promise<{ ok: true, profile: object, skill: object } | { ok: false, status: number, body: object }>}
574
+ */
575
+ async function locateSkill(ctx, name) {
576
+ const profile = readProfileContext(ctx)
577
+ if (profile.home === null || profile.id === 'unknown') {
578
+ return { ok: false, status: 409, body: { error: 'profile-identity-unknown' } }
579
+ }
580
+ if (name === '') return { ok: false, status: 400, body: { error: 'missing-name' } }
581
+ const catalog = await readSkills(ctx, { cwd: profile.cwd })
582
+ const skill = catalog.skills.find((entry) => entry.name === name)
583
+ if (skill === undefined) {
584
+ return {
585
+ ok: false,
586
+ status: 404,
587
+ body: {
588
+ error: 'unknown-skill',
589
+ message: catalog.available ? 'That skill is not in the host catalog.' : catalog.reason,
590
+ },
591
+ }
592
+ }
593
+ if (skill.directory === null) {
594
+ return {
595
+ ok: false,
596
+ status: 409,
597
+ body: { error: 'no-directory', message: 'This skill is a single file, so there is no directory to restore.' },
598
+ }
599
+ }
600
+ return { ok: true, profile, skill }
601
+ }
602
+
603
+ /**
604
+ * Say what a restore would do, including every reason it would be refused.
605
+ *
606
+ * @param {any} ctx
607
+ * @param {string} name
608
+ * @param {string} file
609
+ * @returns {Promise<{ status: number, body: object }>}
610
+ */
611
+ export async function previewSkillRestoreRoute(ctx, name, file) {
612
+ const located = await locateSkill(ctx, name)
613
+ if (!located.ok) return { status: located.status, body: located.body }
614
+ try {
615
+ const preview = await previewSkillRestore({
616
+ dshHome: located.profile.home,
617
+ profileId: located.profile.id,
618
+ name,
619
+ directory: located.skill.directory,
620
+ // The snapshot may exist, but a bundled skill is DSH's own file tree.
621
+ source: located.skill.source ?? null,
622
+ file,
623
+ })
624
+ return {
625
+ status: 200,
626
+ body: {
627
+ schemaVersion: 1,
628
+ ok: preview.ok,
629
+ reason: preview.reason,
630
+ detail: preview.detail,
631
+ skill: {
632
+ name,
633
+ directory: located.skill.directory,
634
+ source: located.skill.source ?? null,
635
+ restoreRefusal: skillRestoreRefusal(located.skill),
636
+ file,
637
+ },
638
+ },
639
+ }
640
+ } catch (error) {
641
+ return { status: 500, body: { error: 'preview-failed', message: messageOf(error) } }
642
+ }
643
+ }
644
+
645
+ /**
646
+ * Replace one skill directory with the bytes a snapshot recorded.
647
+ *
648
+ * @param {any} ctx
649
+ * @param {{ name?: string, file?: string }} body
650
+ * @returns {Promise<{ status: number, body: object }>}
651
+ */
652
+ export async function restoreSkillRoute(ctx, body) {
653
+ const name = typeof body.name === 'string' ? body.name : ''
654
+ const file = typeof body.file === 'string' ? body.file : ''
655
+ if (file === '') return { status: 400, body: { error: 'missing-file' } }
656
+ const located = await locateSkill(ctx, name)
657
+ if (!located.ok) return { status: located.status, body: located.body }
658
+ try {
659
+ const result = await restoreSkillSnapshot({
660
+ dshHome: located.profile.home,
661
+ profileId: located.profile.id,
662
+ name,
663
+ directory: located.skill.directory,
664
+ source: located.skill.source ?? null,
665
+ file,
666
+ })
667
+ if (!result.ok) {
668
+ // Every refusal is a 409: the request was understood, the state is what
669
+ // makes it unsafe.
670
+ return {
671
+ status: 409,
672
+ body: {
673
+ error: result.reason,
674
+ message: result.message,
675
+ evidence: result.evidence,
676
+ restoredTo: null,
677
+ undo: result.undo,
678
+ },
679
+ }
680
+ }
681
+ const after = await readSkills(ctx, { cwd: located.profile.cwd })
682
+ const current = after.skills.find((entry) => entry.name === name)
683
+ return {
684
+ status: 200,
685
+ body: {
686
+ ok: true,
687
+ restoredTo: result.restoredTo,
688
+ undo: result.undo,
689
+ evidence: result.evidence,
690
+ message: null,
691
+ note: 'This restores the skill directory only. It does not touch Git, and it does not restore anything outside that directory.',
692
+ current: current ?? null,
693
+ },
694
+ }
695
+ } catch (error) {
696
+ return { status: 500, body: { error: 'restore-failed', message: messageOf(error) } }
697
+ }
698
+ }
699
+
700
+ export async function takeSnapshot(ctx, body) {
701
+ const profile = readProfileContext(ctx)
702
+ if (profile.dir === null || profile.id === 'unknown') {
703
+ return { status: 409, body: { error: 'profile-identity-unknown' } }
704
+ }
705
+ const overview = await buildOverview(ctx)
706
+ const row = overview.plugins.find((entry) => entry.targetId === body.targetId)
707
+ if (row === undefined) return { status: 404, body: { error: 'unknown-target' } }
708
+
709
+ const directory = join(profile.dir, 'node_modules', row.targetId)
710
+ const fingerprint = await fingerprintTree(directory).catch(() => null)
711
+ if (fingerprint === null) {
712
+ return {
713
+ status: 409,
714
+ body: {
715
+ error: 'not-installed',
716
+ message: 'The package directory could not be read, so there is nothing to fingerprint.',
717
+ },
718
+ }
719
+ }
720
+ const document = await writeSnapshot({
721
+ dshHome: profile.home,
722
+ profileId: profile.id,
723
+ target: row,
724
+ fingerprint,
725
+ reason: typeof body.reason === 'string' ? body.reason : 'manual',
726
+ })
727
+ return {
728
+ status: 200,
729
+ body: {
730
+ ok: true,
731
+ snapshot: { id: document.id, seq: document.seq, takenAt: document.takenAt },
732
+ },
733
+ }
734
+ }
735
+
736
+ /**
737
+ * Update one target to one version, recording every step.
738
+ *
739
+ * The order is: verify the target is still updatable, snapshot, verify the
740
+ * snapshot, mark applying, hand off to the host, then read the result back. The
741
+ * host is the only writer of the profile; this function never edits
742
+ * `package.json` itself.
743
+ *
744
+ * @param {any} ctx
745
+ * @param {{ targetId: string, toVersion: string, allowPrerelease?: boolean }} body
746
+ * @returns {Promise<{ status: number, body: object }>}
747
+ */
748
+ export async function runUpdate(ctx, body) {
749
+ const profile = readProfileContext(ctx)
750
+ if (profile.dir === null || profile.id === 'unknown') {
751
+ return { status: 409, body: { error: 'profile-identity-unknown' } }
752
+ }
753
+ const pluginManager = ctx?.get?.('pluginManager')
754
+ if (pluginManager === undefined || pluginManager === null) {
755
+ return { status: 409, body: { error: 'no-plugin-manager' } }
756
+ }
757
+ const toVersion = body.toVersion
758
+ if (typeof toVersion !== 'string' || toVersion === '') {
759
+ return { status: 400, body: { error: 'missing-version' } }
760
+ }
761
+
762
+ const overview = await buildOverview(ctx)
763
+ const row = overview.plugins.find((entry) => entry.targetId === body.targetId)
764
+ if (row === undefined) return { status: 404, body: { error: 'unknown-target' } }
765
+ if (row.updateRefusal !== null) {
766
+ return { status: 409, body: { error: 'not-updatable', message: row.updateRefusal } }
767
+ }
768
+ if (isPrerelease(toVersion) && body.allowPrerelease !== true) {
769
+ return {
770
+ status: 409,
771
+ body: {
772
+ error: 'prerelease-not-confirmed',
773
+ message: 'The target version is a prerelease and this request did not opt in.',
774
+ },
775
+ }
776
+ }
777
+ if (toVersion === row.installedVersion) {
778
+ return { status: 409, body: { error: 'already-at-version' } }
779
+ }
780
+
781
+ const directory = join(profile.dir, 'node_modules', row.targetId)
782
+ const fingerprint = await fingerprintTree(directory).catch(() => null)
783
+ const snapshot = await writeSnapshot({
784
+ dshHome: profile.home,
785
+ profileId: profile.id,
786
+ target: row,
787
+ fingerprint,
788
+ reason: `before update to ${toVersion}`,
789
+ })
790
+
791
+ // Verify the snapshot can be read back before anything is touched: a snapshot
792
+ // taken but unreadable is the same as no snapshot.
793
+ const written = await listSnapshots(profile.home, profile.id, row.targetId)
794
+ const verified = written.find((entry) => entry.id === snapshot.id)
795
+ if (verified === undefined) {
796
+ return { status: 500, body: { error: 'snapshot-not-verifiable', snapshotId: snapshot.id } }
797
+ }
798
+
799
+ const record = await beginOperation({
800
+ dshHome: profile.home,
801
+ profileId: profile.id,
802
+ target: row,
803
+ toVersion,
804
+ })
805
+ await transition(profile.home, profile.id, record, 'snapshot_verified', {
806
+ snapshotId: snapshot.id,
807
+ })
808
+ await transition(profile.home, profile.id, record, 'applying')
809
+
810
+ // The host owns every write to the profile. An update is its removal plus its
811
+ // installation; a failure between them is the host's `restore` path, not ours.
812
+ let result
813
+ try {
814
+ result = await pluginManager.updateBundle(row.targetId, toVersion, {})
815
+ } catch (error) {
816
+ await transition(profile.home, profile.id, record, 'failed', { error: messageOf(error) })
817
+ return {
818
+ status: 502,
819
+ body: { error: 'update-threw', message: messageOf(error), operationId: record.id, snapshotId: snapshot.id },
820
+ }
821
+ }
822
+
823
+ await transition(profile.home, profile.id, record, 'verifying')
824
+ const outcome = classifyUpdateResult(result)
825
+ const finalState = outcome.ok ? 'succeeded' : 'recovery_required'
826
+ await transition(profile.home, profile.id, record, finalState, {
827
+ error: outcome.message,
828
+ })
829
+
830
+ const after = await buildOverview(ctx)
831
+ const afterRow = after.plugins.find((entry) => entry.targetId === body.targetId)
832
+
833
+ return {
834
+ status: outcome.ok ? 200 : 502,
835
+ body: {
836
+ ok: outcome.ok,
837
+ operationId: record.id,
838
+ snapshotId: snapshot.id,
839
+ fromVersion: row.installedVersion,
840
+ toVersion,
841
+ observedVersion: afterRow?.installedVersion ?? null,
842
+ result,
843
+ message: outcome.message,
844
+ },
845
+ }
846
+ }
847
+
848
+
849
+ /**
850
+ * Reinstall one exact version through the host.
851
+ *
852
+ * The host's installer refuses to install a package that is already present
853
+ * while hot module replacement is on ("already-installed"), because the loader
854
+ * still holds the running copy. Its own update path therefore removes first and
855
+ * installs second. A restore has the same shape: the package is present at the
856
+ * wrong version, and the only way back is to remove it and install the recorded
857
+ * version. Nothing here edits the profile; both steps go through the host's own
858
+ * manager so its manifest writer lock and logging still apply.
859
+ *
860
+ * @param {any} ctx
861
+ * @param {any} pluginManager
862
+ * @param {string} targetId
863
+ * @param {string} version
864
+ * @param {{ registry?: string }} options
865
+ * @returns {Promise<object>}
866
+ */
867
+ async function reinstallVersion(ctx, pluginManager, targetId, version, options) {
868
+ const spec = `${targetId}@${version}`
869
+ const installOptions = {
870
+ saveExact: true,
871
+ registry: options.registry,
872
+ enabled: true,
873
+ }
874
+ const first = await pluginManager.installBundle(spec, installOptions)
875
+ if (!isAlreadyInstalled(first)) return first
876
+ if (typeof pluginManager.removeBundle !== 'function') {
877
+ throw new Error('The host cannot remove a bundle, so an already installed version cannot be replaced.')
878
+ }
879
+ await pluginManager.removeBundle(targetId)
880
+ return pluginManager.installBundle(spec, installOptions)
881
+ }
882
+
883
+ /**
884
+ * Did the host refuse because the package was already present?
885
+ *
886
+ * The host reports this as a result body rather than as a thrown error:
887
+ * `result.result.error.code === 'already-installed'`. Both the nested and the
888
+ * hoisted shape are read, because the refusal is checked structurally and not
889
+ * by matching a message string.
890
+ *
891
+ * @param {unknown} result
892
+ * @returns {boolean}
893
+ */
894
+ export function isAlreadyInstalled(result) {
895
+ if (result === null || typeof result !== 'object') return false
896
+ const levels = [result, result.result].filter((level) => level !== null && typeof level === 'object')
897
+ return levels.some((level) => level.error?.code === 'already-installed')
898
+ }
899
+
900
+ /**
901
+ * Did the host's update actually change anything?
902
+ *
903
+ * `changed: false` is not a failure of the request — it is the host saying the
904
+ * application did not run. Reporting that as success would be the "claimed but
905
+ * never happened" bug this plugin exists to avoid.
906
+ *
907
+ * @param {unknown} result
908
+ * @returns {{ ok: boolean, message: string | null }}
909
+ */
910
+ export function classifyUpdateResult(result) {
911
+ if (result === null || typeof result !== 'object') {
912
+ return { ok: false, message: 'The host returned no update result.' }
913
+ }
914
+ // The host nests the applied result one level down: { from, to, step,
915
+ // result: { stage, target, changed, application, ... } }. Both levels are
916
+ // read because a future host may hoist the flag, and neither level is
917
+ // invented when absent.
918
+ const inner = result.result !== null && typeof result.result === 'object' ? result.result : {}
919
+ const changed = result.changed === true || inner.changed === true
920
+ const application = result.application ?? inner.application ?? 'not-applied'
921
+ if (!changed) {
922
+ const detail = result.error?.message ?? inner.error?.message ?? result.diagnostic ?? inner.diagnostic ?? null
923
+ return {
924
+ ok: false,
925
+ message: detail === null ? `The host reported "${application}" without applying the update.` : String(detail),
926
+ }
927
+ }
928
+ if (application !== 'applied') {
929
+ return {
930
+ ok: false,
931
+ message: `The host changed files but reported application "${application}".`,
932
+ }
933
+ }
934
+ return { ok: true, message: null }
935
+ }
936
+
937
+ /**
938
+ * Restore a target from one snapshot.
939
+ *
940
+ * Only the version is restored, and only when the files still match the
941
+ * fingerprint taken before that change. Configuration, the dependency tree and
942
+ * agent presets are explicitly out of scope, and the reply says so.
943
+ *
944
+ * @param {any} ctx
945
+ * @param {{ targetId: string, snapshotId: string }} body
946
+ * @returns {Promise<{ status: number, body: object }>}
947
+ */
948
+ export async function restoreSnapshot(ctx, body) {
949
+ const profile = readProfileContext(ctx)
950
+ if (profile.dir === null || profile.id === 'unknown') {
951
+ return { status: 409, body: { error: 'profile-identity-unknown' } }
952
+ }
953
+ const pluginManager = ctx?.get?.('pluginManager')
954
+ if (pluginManager === undefined || pluginManager === null) {
955
+ return { status: 409, body: { error: 'no-plugin-manager' } }
956
+ }
957
+
958
+ const rows = await listSnapshots(profile.home, profile.id, body.targetId)
959
+ const chosen = rows.find((entry) => entry.id === body.snapshotId)
960
+ if (chosen === undefined) return { status: 404, body: { error: 'unknown-snapshot' } }
961
+
962
+ const document = await readSnapshotDocument(profile.home, profile.id, body.targetId, chosen.file)
963
+ if (document === null) return { status: 409, body: { error: 'snapshot-unreadable' } }
964
+
965
+ const directory = join(profile.dir, 'node_modules', body.targetId)
966
+ const current = await fingerprintTree(directory).catch(() => null)
967
+ const verdict = recoveryVerdict(document, current)
968
+
969
+ if (!verdict.ok) {
970
+ return {
971
+ status: 409,
972
+ body: {
973
+ error: verdict.reason,
974
+ message: verdict.detail,
975
+ // Restoring is refused, and the reason names the exact condition that
976
+ // failed so the user can decide what to do instead of retrying blindly.
977
+ note: 'Version restore only; configuration, dependency tree and presets are not rolled back.',
978
+ },
979
+ }
980
+ }
981
+
982
+ // What the fingerprint check actually proved, kept as evidence rather than
983
+ // folded into the verdict: "the files are not the ones this snapshot recorded"
984
+ // is the normal case right after an update, and it is worth showing.
985
+ const evidence = {
986
+ filesMatch: verdict.filesMatch,
987
+ recordedDigest: document.target.fingerprint?.digest ?? null,
988
+ currentDigest: current?.digest ?? null,
989
+ registry: document.target.source.registry ?? null,
990
+ }
991
+
992
+ const targetVersion = document.target.installedVersion
993
+ const overview = await buildOverview(ctx)
994
+ const row = overview.plugins.find((entry) => entry.targetId === body.targetId)
995
+
996
+ // Nothing to reinstall when the profile already carries that version. Saying
997
+ // "restored" here would claim an action that never ran; the reply says what
998
+ // is true instead, and keeps the fingerprint evidence because a version match
999
+ // does not prove the files are untouched.
1000
+ if (row !== undefined && row.installedVersion === targetVersion) {
1001
+ return {
1002
+ status: 200,
1003
+ body: {
1004
+ ok: true,
1005
+ alreadyAtVersion: true,
1006
+ restoredVersion: targetVersion,
1007
+ observedVersion: row.installedVersion,
1008
+ message: null,
1009
+ evidence,
1010
+ note: 'Version restore only; configuration, dependency tree and presets are not rolled back.',
1011
+ },
1012
+ }
1013
+ }
1014
+ const record = await beginOperation({
1015
+ dshHome: profile.home,
1016
+ profileId: profile.id,
1017
+ target: row ?? { kind: 'plugin', targetId: body.targetId, installedVersion: current?.digest ?? null, declaredSpec: document.target.declaredSpec, source: { kind: 'registry' } },
1018
+ toVersion: targetVersion,
1019
+ })
1020
+
1021
+ // An update snapshots what it is about to replace, and a restore replaces a
1022
+ // version too. Without this, restoring is the only write in the plugin with no
1023
+ // way back: the moment it runs, the version you were on is unreachable. The
1024
+ // snapshot is taken before the swap and verified by reading it back, for the
1025
+ // same reason the update path verifies its own.
1026
+ const currentFingerprint = await fingerprintTree(directory).catch(() => null)
1027
+ const undo = await writeSnapshot({
1028
+ dshHome: profile.home,
1029
+ profileId: profile.id,
1030
+ // The row when the host still lists the target, otherwise what the snapshot
1031
+ // being restored recorded about it. Both carry the fields a later restore
1032
+ // reads back; neither invents a value the host did not report.
1033
+ target: row ?? {
1034
+ kind: 'plugin',
1035
+ targetId: body.targetId,
1036
+ declaredSpec: document.target.declaredSpec,
1037
+ installedVersion: document.target.installedVersion,
1038
+ source: document.target.source,
1039
+ enabledState: document.target.enabledState,
1040
+ compatibility: document.target.compatibility,
1041
+ },
1042
+ fingerprint: currentFingerprint,
1043
+ reason: `before restore to ${targetVersion}`,
1044
+ })
1045
+ const written = await listSnapshots(profile.home, profile.id, body.targetId)
1046
+ if (written.find((entry) => entry.id === undo.id) === undefined) {
1047
+ await transition(profile.home, profile.id, record, 'failed', { error: 'snapshot-not-verifiable' })
1048
+ return { status: 500, body: { error: 'snapshot-not-verifiable', snapshotId: undo.id, operationId: record.id } }
1049
+ }
1050
+
1051
+ await transition(profile.home, profile.id, record, 'snapshot_verified', { snapshotId: undo.id })
1052
+ await transition(profile.home, profile.id, record, 'applying', {
1053
+ detail: 'restoring a recorded version',
1054
+ })
1055
+
1056
+ let result
1057
+ try {
1058
+ result = await reinstallVersion(ctx, pluginManager, body.targetId, targetVersion, {
1059
+ registry: document.target.source.registry ?? undefined,
1060
+ })
1061
+ } catch (error) {
1062
+ await transition(profile.home, profile.id, record, 'failed', { error: messageOf(error) })
1063
+ return { status: 502, body: { error: 'restore-threw', message: messageOf(error), operationId: record.id } }
1064
+ }
1065
+
1066
+ await transition(profile.home, profile.id, record, 'verifying')
1067
+ // Same nesting as an update: the host reports the applied stage under
1068
+ // `result`. A restore that only *started* must not be reported as done.
1069
+ const outcome = classifyUpdateResult(result)
1070
+ const ok = outcome.ok
1071
+ await transition(profile.home, profile.id, record, ok ? 'succeeded' : 'recovery_required', {
1072
+ error: outcome.message,
1073
+ })
1074
+
1075
+ return {
1076
+ status: ok ? 200 : 502,
1077
+ body: {
1078
+ ok,
1079
+ operationId: record.id,
1080
+ restoredVersion: targetVersion,
1081
+ observedVersion: (await buildOverview(ctx)).plugins.find((entry) => entry.targetId === body.targetId)?.installedVersion ?? null,
1082
+ message: outcome.message,
1083
+ evidence,
1084
+ // The snapshot taken before the swap, so the version that was just
1085
+ // replaced can itself be restored.
1086
+ undo: { id: undo.id, seq: undo.seq, version: row?.installedVersion ?? null },
1087
+ result,
1088
+ note: 'Version restore only; configuration, dependency tree and presets are not rolled back.',
1089
+ },
1090
+ }
1091
+ }
1092
+
1093
+ /**
1094
+ * Read one stored snapshot document by its file name.
1095
+ *
1096
+ * @param {string} dshHome
1097
+ * @param {string} profileId
1098
+ * @param {string} targetId
1099
+ * @param {string} file
1100
+ * @returns {Promise<object | null>}
1101
+ */
1102
+ async function readSnapshotDocument(dshHome, profileId, targetId, file) {
1103
+ if (typeof file !== 'string' || file.includes('/') || file.includes('\\') || file.includes('..')) {
1104
+ return null
1105
+ }
1106
+ const path = join(
1107
+ dshHome,
1108
+ 'version-manager',
1109
+ 'snapshots',
1110
+ String(profileId).replace(/\//g, '%2F'),
1111
+ String(targetId).replace(/\//g, '%2F'),
1112
+ file,
1113
+ )
1114
+ try {
1115
+ return JSON.parse(await readFile(path, 'utf8'))
1116
+ } catch {
1117
+ return null
1118
+ }
1119
+ }
1120
+
1121
+ export { snapshotsBeyondRetention, deleteSnapshot }
1122
+
1123
+ /**
1124
+ * Register every route on the host webserver.
1125
+ *
1126
+ * @param {any} ctx
1127
+ * @param {{ webServer: { register: (route: any) => () => void } }} scope
1128
+ * @returns {() => void[]} disposers
1129
+ */
1130
+ export function registerRoutes(ctx, scope) {
1131
+ const { webServer } = scope
1132
+ const disposers = []
1133
+ const publish = (path, handler) => {
1134
+ const dispose = webServer.register({ kind: 'exact', path: `${ROUTE_BASE}${path}`, handler })
1135
+ disposers.push(dispose)
1136
+ }
1137
+
1138
+ /** @param {(request: any, response: any, body: any) => Promise<{status: number, body: unknown}>} run */
1139
+ const writeRoute = (path, run) => {
1140
+ publish(path, async (request, response) => {
1141
+ const allowed = admit(ctx, request)
1142
+ if (!allowed.ok) {
1143
+ sendJson(response, allowed.status, { error: allowed.status === 403 ? 'forbidden' : 'unauthorized' })
1144
+ return
1145
+ }
1146
+ if (request.method !== 'POST') {
1147
+ response.writeHead(405, { allow: 'POST' })
1148
+ response.end()
1149
+ return
1150
+ }
1151
+ const parsed = await readJsonBody(request)
1152
+ if (!parsed.ok) {
1153
+ sendJson(response, parsed.status, { error: parsed.message })
1154
+ return
1155
+ }
1156
+ if (parsed.value?.confirm !== true) {
1157
+ // The confirmation is per request. A UI that forgets to send it gets a
1158
+ // refusal, not a silent write.
1159
+ sendJson(response, 400, { error: 'confirm required' })
1160
+ return
1161
+ }
1162
+ try {
1163
+ const result = await run(request, response, parsed.value)
1164
+ sendJson(response, result.status, result.body)
1165
+ } catch (error) {
1166
+ // A thrown handler would be turned into a bare 400 by the host, losing
1167
+ // which step failed. Answering here keeps the reason.
1168
+ sendJson(response, 500, { error: 'handler-failed', message: messageOf(error) })
1169
+ }
1170
+ })
1171
+ }
1172
+
1173
+ publish('/overview', async (request, response) => {
1174
+ const allowed = admit(ctx, request)
1175
+ if (!allowed.ok) {
1176
+ sendJson(response, allowed.status, { error: allowed.status === 403 ? 'forbidden' : 'unauthorized' })
1177
+ return
1178
+ }
1179
+ if (request.method !== 'GET') {
1180
+ response.writeHead(405, { allow: 'GET' })
1181
+ response.end()
1182
+ return
1183
+ }
1184
+ try {
1185
+ sendJson(response, 200, await buildOverview(ctx))
1186
+ } catch (error) {
1187
+ sendJson(response, 500, { error: 'overview-failed', message: messageOf(error) })
1188
+ }
1189
+ })
1190
+
1191
+ publish('/versions', async (request, response) => {
1192
+ const allowed = admit(ctx, request)
1193
+ if (!allowed.ok) {
1194
+ sendJson(response, allowed.status, { error: allowed.status === 403 ? 'forbidden' : 'unauthorized' })
1195
+ return
1196
+ }
1197
+ if (request.method !== 'GET') {
1198
+ response.writeHead(405, { allow: 'GET' })
1199
+ response.end()
1200
+ return
1201
+ }
1202
+ const url = new URL(request.url ?? '/', 'http://localhost')
1203
+ const name = url.searchParams.get('target')
1204
+ if (name === null || name === '') {
1205
+ sendJson(response, 400, { error: 'missing target' })
1206
+ return
1207
+ }
1208
+ try {
1209
+ sendJson(response, 200, await readVersions(ctx, name))
1210
+ } catch (error) {
1211
+ sendJson(response, 500, { error: 'versions-failed', message: messageOf(error) })
1212
+ }
1213
+ })
1214
+
1215
+ publish('/skills', async (request, response) => {
1216
+ const allowed = admit(ctx, request)
1217
+ if (!allowed.ok) {
1218
+ sendJson(response, allowed.status, { error: allowed.status === 403 ? 'forbidden' : 'unauthorized' })
1219
+ return
1220
+ }
1221
+ if (request.method !== 'GET') {
1222
+ response.writeHead(405, { allow: 'GET' })
1223
+ response.end()
1224
+ return
1225
+ }
1226
+ try {
1227
+ const profile = readProfileContext(ctx)
1228
+ const host = readRuntime(ctx)
1229
+ const catalog = await readSkills(ctx, { cwd: profile.cwd })
1230
+ const gitRegistry = profile.home === null ? [] : await readRegistry(profile.home, profile.id)
1231
+ const gitByName = new Map(gitRegistry.map((entry) => [entry.name, entry]))
1232
+ const skills = []
1233
+ for (const skill of catalog.skills) {
1234
+ const managed = gitByName.get(skill.name)
1235
+ skills.push({
1236
+ ...skill,
1237
+ // Whether this row may be written at all. A single-file skill, a
1238
+ // bundled skill and a skill inside a Git checkout are all listed and
1239
+ // none of them is restorable. A Skill this plugin itself keeps in step
1240
+ // with a Git tree is the one exception: it was registered on purpose
1241
+ // and its history is known.
1242
+ restoreRefusal: skillRestoreRefusal(skill),
1243
+ // Present only for a Skill this plugin keeps in step with a Git tree.
1244
+ // `restoreRefusal` above stays the same for it: registration refuses
1245
+ // directories inside a checkout, so a registered Skill never reads as
1246
+ // `inside-git-checkout`.
1247
+ gitManaged:
1248
+ managed === undefined
1249
+ ? null
1250
+ : { remote: managed.remote, subpath: managed.subpath, revision: managed.revision },
1251
+ snapshots:
1252
+ skill.directory === null
1253
+ ? []
1254
+ : await listSkillSnapshots(profile.home, profile.id, skill.name),
1255
+ })
1256
+ }
1257
+ sendJson(response, 200, {
1258
+ schemaVersion: 1,
1259
+ observedAt: new Date().toISOString(),
1260
+ profile: { id: profile.id, dir: profile.dir, home: profile.home },
1261
+ host,
1262
+ available: catalog.available,
1263
+ reason: catalog.reason,
1264
+ complete: catalog.complete,
1265
+ provider: catalog.provider,
1266
+ skills,
1267
+ git: await listGitSkills(ctx, profile).then((result) => result.body),
1268
+ })
1269
+ } catch (error) {
1270
+ sendJson(response, 500, { error: 'skills-failed', message: messageOf(error) })
1271
+ }
1272
+ })
1273
+
1274
+ publish('/skills/restore-preview', async (request, response) => {
1275
+ const allowed = admit(ctx, request)
1276
+ if (!allowed.ok) {
1277
+ sendJson(response, allowed.status, { error: allowed.status === 403 ? 'forbidden' : 'unauthorized' })
1278
+ return
1279
+ }
1280
+ if (request.method !== 'GET') {
1281
+ response.writeHead(405, { allow: 'GET' })
1282
+ response.end()
1283
+ return
1284
+ }
1285
+ const url = new URL(request.url ?? '/', 'http://localhost')
1286
+ const name = url.searchParams.get('name') ?? ''
1287
+ const file = url.searchParams.get('file') ?? ''
1288
+ if (file === '') {
1289
+ sendJson(response, 400, { error: 'missing-file' })
1290
+ return
1291
+ }
1292
+ const result = await previewSkillRestoreRoute(ctx, name, file)
1293
+ sendJson(response, result.status, result.body)
1294
+ })
1295
+
1296
+ publish('/skills/git', async (request, response) => {
1297
+ const allowed = admit(ctx, request)
1298
+ if (!allowed.ok) {
1299
+ sendJson(response, allowed.status, { error: allowed.status === 403 ? 'forbidden' : 'unauthorized' })
1300
+ return
1301
+ }
1302
+ if (request.method !== 'GET') {
1303
+ response.writeHead(405, { allow: 'GET' })
1304
+ response.end()
1305
+ return
1306
+ }
1307
+ const result = await listGitSkills(ctx, readProfileContext(ctx))
1308
+ sendJson(response, result.status, result.body)
1309
+ })
1310
+
1311
+ writeRoute('/skills/git/register', async (_request, _response, body) =>
1312
+ registerGitRoute(ctx, readProfileContext(ctx), body),
1313
+ )
1314
+ writeRoute('/skills/git/remove', async (_request, _response, body) =>
1315
+ unregisterGitRoute(readProfileContext(ctx), body),
1316
+ )
1317
+ // A preview reaches the network (it fetches the remote into this plugin's own
1318
+ // cache), so it is a POST as well: the method says what the call costs.
1319
+ writeRoute('/skills/git/preview', async (_request, _response, body) =>
1320
+ previewGitRoute(readProfileContext(ctx), body),
1321
+ )
1322
+ writeRoute('/skills/git/update', async (_request, _response, body) =>
1323
+ updateGitRoute(readProfileContext(ctx), body),
1324
+ )
1325
+ writeRoute('/skills/git/restore', async (_request, _response, body) =>
1326
+ restoreGitRoute(readProfileContext(ctx), body),
1327
+ )
1328
+
1329
+ writeRoute('/skills/snapshot', async (_request, _response, body) => takeSkillSnapshot(ctx, body))
1330
+ writeRoute('/skills/restore', async (_request, _response, body) => restoreSkillRoute(ctx, body))
1331
+ writeRoute('/snapshot', async (_request, _response, body) => takeSnapshot(ctx, body))
1332
+ writeRoute('/update', async (_request, _response, body) => runUpdate(ctx, body))
1333
+ writeRoute('/restore', async (_request, _response, body) => restoreSnapshot(ctx, body))
1334
+
1335
+ return disposers
1336
+ }