@xi4z/dsh-utils-utils-agents 0.0.0-stage → 0.7.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/lib/git.d.ts +87 -0
  3. package/lib/git.js +403 -0
  4. package/lib/git.js.map +1 -0
  5. package/lib/global-repo.d.ts +57 -0
  6. package/lib/global-repo.js +301 -0
  7. package/lib/global-repo.js.map +1 -0
  8. package/lib/index.d.ts +111 -0
  9. package/lib/index.js +470 -0
  10. package/lib/index.js.map +1 -0
  11. package/lib/legacy.d.ts +30 -0
  12. package/lib/legacy.js +141 -0
  13. package/lib/legacy.js.map +1 -0
  14. package/lib/native.d.ts +74 -0
  15. package/lib/native.js +232 -0
  16. package/lib/native.js.map +1 -0
  17. package/lib/presets.d.ts +34 -0
  18. package/lib/presets.js +312 -0
  19. package/lib/presets.js.map +1 -0
  20. package/lib/shared.d.ts +105 -0
  21. package/lib/shared.js +507 -0
  22. package/lib/shared.js.map +1 -0
  23. package/lib/skill-discovery.d.ts +52 -0
  24. package/lib/skill-discovery.js +850 -0
  25. package/lib/skill-discovery.js.map +1 -0
  26. package/lib/skill-panel.d.ts +36 -0
  27. package/lib/skill-panel.js +409 -0
  28. package/lib/skill-panel.js.map +1 -0
  29. package/lib/update.d.ts +129 -0
  30. package/lib/update.js +507 -0
  31. package/lib/update.js.map +1 -0
  32. package/lib/util.d.ts +215 -0
  33. package/lib/util.js +475 -0
  34. package/lib/util.js.map +1 -0
  35. package/locale/en.json +6 -0
  36. package/locale/zh.json +6 -0
  37. package/package.json +52 -3
  38. package/src/git.ts +444 -0
  39. package/src/global-repo.ts +343 -0
  40. package/src/index.ts +522 -0
  41. package/src/legacy.ts +170 -0
  42. package/src/native.ts +291 -0
  43. package/src/presets.ts +329 -0
  44. package/src/shared.ts +589 -0
  45. package/src/skill-discovery.ts +917 -0
  46. package/src/skill-panel.ts +488 -0
  47. package/src/update.ts +574 -0
  48. package/src/util.ts +570 -0
  49. package/README.md +0 -3
package/src/update.ts ADDED
@@ -0,0 +1,574 @@
1
+ /**
2
+ * Published-version checks for the dsh-utils bundle itself.
3
+ *
4
+ * The panel can tell the user whether a newer `@xi4z/dsh-utils` exists than the
5
+ * version this component runs from, and can install it automatically. Where it
6
+ * asks depends on how the bundle was installed in the profile:
7
+ *
8
+ * - a registry spec asks the npm `latest` document (one GET);
9
+ * - a GitHub spec reads the repository's `package.json` on that ref
10
+ * (`raw.githubusercontent.com`, no token needed for public repositories),
11
+ * and a branch/tag install is re-added by `pnpm add <spec>`;
12
+ * - a `link:`/`file:`/unknown install has no remote to install, so the npm
13
+ * answer is shown for reference only and nothing is ever installed.
14
+ *
15
+ * The automatic check runs shortly after activation and then every
16
+ * `updateCheckIntervalHours` (default 6). A manual "检查更新" asks immediately.
17
+ * With `updateAutoInstall` (default on) an available update is installed in the
18
+ * background, then reported as "installed, restart to apply": replacing a
19
+ * running plugin's files cannot take effect inside this process.
20
+ *
21
+ * The answer is cached in $DSH_HOME/storages/dsh-utils-agents/update.json so a
22
+ * restart shows the last known answer before the first network call, and a
23
+ * failed check never hides the last successfully read version.
24
+ *
25
+ * @module dsh-utils/utils-agents/update
26
+ */
27
+
28
+ import { execFile } from 'node:child_process'
29
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
30
+ import { join, isAbsolute } from 'node:path'
31
+ import { randomBytes } from 'node:crypto'
32
+ import type { Context } from '@deepseek-ai/cordis'
33
+ import { agentsStorageDir, errorMessage, type Options } from './util.js'
34
+
35
+ /** File holding the last published-version answer. */
36
+ const CACHE_FILE_NAME = 'update.json'
37
+
38
+ /** One HTTP request to the registry or GitHub is bounded. */
39
+ const REQUEST_TIMEOUT_MS = 8000
40
+
41
+ /** One `pnpm add` run is bounded. */
42
+ const INSTALL_TIMEOUT_MS = 180000
43
+
44
+ /** The first automatic check runs shortly after activation, off the boot path. */
45
+ const FIRST_CHECK_DELAY_MS = 15000
46
+
47
+ /** A Git ref pinned to a commit cannot move, so it is never re-added. */
48
+ const PINNED_REF = /^[0-9a-f]{40,64}$/i
49
+
50
+ /** Where the newest version is read from. */
51
+ export type UpdateSourceKind = 'npm' | 'git' | 'local'
52
+
53
+ /** The state of one automatic install attempt. */
54
+ export interface UpdateInstall {
55
+ /** idle: nothing to do; installing: pnpm is running; installed: restart to apply; failed: see message. */
56
+ readonly phase: 'idle' | 'installing' | 'installed' | 'failed'
57
+ /** The version being installed. */
58
+ readonly version: string | null
59
+ /** Why the install failed, or the restart reminder after success. */
60
+ readonly message: string | null
61
+ /** When the last phase change happened. */
62
+ readonly at: string | null
63
+ }
64
+
65
+ /** The durable and returned shape of one update check. */
66
+ export interface UpdateStatus {
67
+ /** The version this component runs from; the bundle root package's version. */
68
+ readonly current: string
69
+ /** The last successfully read remote version, if any. */
70
+ readonly latest: string | null
71
+ /** Whether `latest` is newer than `current`. */
72
+ readonly updateAvailable: boolean
73
+ /** Which remote the answer describes: npm, GitHub, or none for a local install. */
74
+ readonly source: UpdateSourceKind
75
+ /** The exact remote the answer came from (registry base URL or raw GitHub URL). */
76
+ readonly origin: string
77
+ /** When `latest` was read successfully. */
78
+ readonly checkedAt: string | null
79
+ /** When the last attempt finished, successful or not. */
80
+ readonly attemptedAt: string | null
81
+ /** Why the last check failed; null after a successful one. */
82
+ readonly error: string | null
83
+ /** The last automatic install attempt. */
84
+ readonly install: UpdateInstall
85
+ }
86
+
87
+ /** What the panel needs to describe the schedule. */
88
+ export interface UpdateSchedule {
89
+ readonly enabled: boolean
90
+ readonly intervalHours: number
91
+ readonly registry: string
92
+ }
93
+
94
+ /** How this bundle was installed in the profile. */
95
+ interface InstallSource {
96
+ readonly kind: UpdateSourceKind
97
+ /** The profile dependency spec, when it could be read. */
98
+ readonly spec: string | null
99
+ /** A GitHub repository parsed from a Git spec. */
100
+ readonly git?: { readonly owner: string; readonly repo: string; readonly ref: string }
101
+ }
102
+
103
+ /** One install command for the profile. */
104
+ export interface InstallCommand {
105
+ /** The profile directory `pnpm add` runs in. */
106
+ readonly dir: string
107
+ /** The package spec to add. */
108
+ readonly spec: string
109
+ /** Whether to save an exact registry version. */
110
+ readonly exact: boolean
111
+ }
112
+
113
+ /** Runs one install; tests replace it. */
114
+ export type InstallRunner = (command: InstallCommand) => Promise<void>
115
+
116
+ /** Parsed semantic version: numeric core plus prerelease tail. */
117
+ interface ParsedVersion {
118
+ readonly core: readonly [number, number, number]
119
+ readonly pre: string
120
+ }
121
+
122
+ /** Parse `1.2.3`, `v1.2.3` and `1.2.3-beta.1`; null when it is not semver. */
123
+ function parseVersion(raw: string): ParsedVersion | null {
124
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(raw.trim())
125
+ if (match === null) return null
126
+ return { core: [Number(match[1]), Number(match[2]), Number(match[3])], pre: match[4] ?? '' }
127
+ }
128
+
129
+ /**
130
+ * Compare two semantic versions, ignoring build metadata.
131
+ * @returns negative when left is older, 0 when equal, positive when newer.
132
+ */
133
+ export function compareVersions(left: string, right: string): number {
134
+ const a = parseVersion(left)
135
+ const b = parseVersion(right)
136
+ if (a === null || b === null) return 0
137
+ for (let index = 0; index < 3; index += 1) {
138
+ const delta = a.core[index] - b.core[index]
139
+ if (delta !== 0) return delta
140
+ }
141
+ // A release is newer than its prereleases; between prereleases the plain
142
+ // lexical order is enough for the tags this project publishes.
143
+ if (a.pre === b.pre) return 0
144
+ if (a.pre === '') return 1
145
+ if (b.pre === '') return -1
146
+ return a.pre < b.pre ? -1 : 1
147
+ }
148
+
149
+ /** The running bundle's manifest: the package name to ask about and its version. */
150
+ async function packageIdentity(): Promise<{ name: string; version: string }> {
151
+ // lib/update.js -> packages/utils-agents -> package root.
152
+ const manifest = JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8')) as Record<string, unknown>
153
+ const name = typeof manifest.name === 'string' && manifest.name.trim() !== '' ? manifest.name.trim() : '@xi4z/dsh-utils'
154
+ const version = typeof manifest.version === 'string' && manifest.version.trim() !== '' ? manifest.version.trim() : '0.0.0'
155
+ return { name, version }
156
+ }
157
+
158
+ /** The profile directory the host reports, if it reports one. */
159
+ function profileDir(ctx: Context): string | null {
160
+ let service: unknown
161
+ try {
162
+ service = typeof (ctx as unknown as { get?: (name: string) => unknown }).get === 'function'
163
+ ? (ctx as unknown as { get: (name: string) => unknown }).get('profileContext')
164
+ : undefined
165
+ } catch {
166
+ service = undefined
167
+ }
168
+ const candidate = (service ?? (ctx as unknown as { profileContext?: unknown }).profileContext) as { dir?: unknown } | undefined
169
+ const dir = candidate?.dir
170
+ return typeof dir === 'string' && dir.trim() !== '' ? dir : null
171
+ }
172
+
173
+ /** The dependency spec this profile installed the bundle from. */
174
+ async function profileSpec(ctx: Context, name: string): Promise<string | null> {
175
+ const dir = profileDir(ctx)
176
+ if (dir === null) return null
177
+ try {
178
+ const manifest = JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as Record<string, unknown>
179
+ const groups = [manifest.dependencies, manifest.devDependencies]
180
+ for (const group of groups) {
181
+ if (group === null || typeof group !== 'object') continue
182
+ const spec = (group as Record<string, unknown>)[name]
183
+ if (typeof spec === 'string' && spec.trim() !== '') return spec.trim()
184
+ }
185
+ } catch {
186
+ // A profile without a readable manifest is treated as a local install.
187
+ }
188
+ return null
189
+ }
190
+
191
+ /**
192
+ * Read a GitHub repository out of a pnpm Git spec: `github:owner/repo`,
193
+ * `owner/repo`, `git+https://github.com/owner/repo.git#<ref>`, or the SSH form.
194
+ * A `#path:` parameter is dropped; the first remaining parameter is the ref.
195
+ */
196
+ export function parseGitSpec(spec: string): { owner: string; repo: string; ref: string } | null {
197
+ let text = spec.trim()
198
+ if (text === '') return null
199
+ let ref = 'HEAD'
200
+ const hash = text.indexOf('#')
201
+ if (hash !== -1) {
202
+ const fragment = text.slice(hash + 1)
203
+ text = text.slice(0, hash)
204
+ const parts = fragment.split('&').filter((part) => part !== '' && !part.startsWith('path:'))
205
+ if (parts.length > 0) ref = parts[0]
206
+ }
207
+ text = text.replace(/^git\+/, '')
208
+ const patterns: readonly RegExp[] = [
209
+ /^github:([^/\s]+)\/([^\s]+)$/i,
210
+ /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/,
211
+ /^git@github\.com:([^/\s]+)\/([^\s]+)$/i,
212
+ /^(?:ssh|https?):\/\/(?:git@)?github\.com\/([^/\s]+)\/([^\s]+)$/i,
213
+ ]
214
+ for (const pattern of patterns) {
215
+ const match = pattern.exec(text)
216
+ if (match === null) continue
217
+ const owner = match[1]
218
+ const repo = match[2].replace(/\.git$/i, '').replace(/\/+$/, '')
219
+ if (owner === '' || repo === '') return null
220
+ return { owner, repo, ref }
221
+ }
222
+ return null
223
+ }
224
+
225
+ /** Classify one profile spec. */
226
+ function classifySpec(spec: string | null): InstallSource {
227
+ if (spec === null) return { kind: 'local', spec }
228
+ const text = spec.trim()
229
+ if (/^(link|file|workspace):/i.test(text) || isAbsolute(text)) return { kind: 'local', spec: text }
230
+ const git = parseGitSpec(text)
231
+ if (git !== null) return { kind: 'git', spec: text, git }
232
+ return { kind: 'npm', spec: text }
233
+ }
234
+
235
+ /** The URL of one GitHub package manifest for the parsed ref. */
236
+ function gitManifestUrl(git: { owner: string; repo: string; ref: string }): string {
237
+ const ref = git.ref.split('/').map((part) => encodeURIComponent(part)).join('/')
238
+ return 'https://raw.githubusercontent.com/' + encodeURIComponent(git.owner) + '/' + encodeURIComponent(git.repo) + '/' + ref + '/package.json'
239
+ }
240
+
241
+ /** Read a manifest's version, refusing anything that is not a semver string. */
242
+ async function fetchVersion(url: string): Promise<string> {
243
+ const response = await fetch(url, {
244
+ headers: { accept: 'application/json' },
245
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
246
+ })
247
+ if (!response.ok) throw new Error('HTTP ' + response.status)
248
+ const body = await response.json() as Record<string, unknown>
249
+ const version = typeof body.version === 'string' ? body.version.trim() : ''
250
+ if (parseVersion(version) === null) throw new Error('answer carries no version')
251
+ return version
252
+ }
253
+
254
+ /** The npm `latest` document for one package. */
255
+ async function fetchNpmLatest(registry: string, name: string): Promise<string> {
256
+ const base = registry.replace(/\/+$/, '')
257
+ return await fetchVersion(base + '/' + name.replace('/', '%2F') + '/latest')
258
+ }
259
+
260
+ /** Run `pnpm add` in the profile; the only place this component writes there. */
261
+ async function runPnpmAdd(command: InstallCommand): Promise<void> {
262
+ const args = command.exact ? ['add', command.spec, '--save-exact'] : ['add', command.spec]
263
+ await new Promise<void>((resolvePromise, reject) => {
264
+ execFile('pnpm', args, {
265
+ cwd: command.dir,
266
+ timeout: INSTALL_TIMEOUT_MS,
267
+ maxBuffer: 8 * 1024 * 1024,
268
+ env: { ...process.env, CI: '1' },
269
+ }, (error, _stdout, stderr) => {
270
+ if (error === null) {
271
+ resolvePromise()
272
+ return
273
+ }
274
+ const detail = String(stderr ?? '').trim().split(/\r?\n/).slice(0, 3).join(' / ')
275
+ reject(new Error('pnpm add failed' + (detail === '' ? '' : ': ' + detail)))
276
+ })
277
+ })
278
+ }
279
+
280
+ /** The install command for one source and target version; null when it must not install. */
281
+ export function installCommand(source: InstallSource, profile: string, name: string, version: string): InstallCommand | null {
282
+ if (source.kind === 'local') return null
283
+ if (source.kind === 'npm') return { dir: profile, spec: name + '@' + version, exact: true }
284
+ const spec = source.spec
285
+ if (spec === null) return null
286
+ // A commit-pinned spec cannot move; re-adding it would only reinstall the same tree.
287
+ if (source.git !== undefined && PINNED_REF.test(source.git.ref)) return null
288
+ return { dir: profile, spec, exact: false }
289
+ }
290
+
291
+ /** Restore the two files an install may rewrite, so a failed run leaves the profile as it was. */
292
+ async function restoreProfile(dir: string, saved: readonly { name: string; text: string | null }[]): Promise<void> {
293
+ for (const file of saved) {
294
+ const path = join(dir, file.name)
295
+ try {
296
+ if (file.text === null) await rm(path, { force: true })
297
+ else await writeFile(path, file.text)
298
+ } catch {
299
+ // A read-only profile keeps whatever pnpm left; the failure is reported anyway.
300
+ }
301
+ }
302
+ }
303
+
304
+ /** The cache path under the panel's storage directory. */
305
+ function cachePath(): string {
306
+ return join(agentsStorageDir(), CACHE_FILE_NAME)
307
+ }
308
+
309
+ /** One install state that has not been attempted. */
310
+ const IDLE_INSTALL: UpdateInstall = { phase: 'idle', version: null, message: null, at: null }
311
+
312
+ /** Normalize a persisted install state. */
313
+ function normalizeInstall(raw: unknown): UpdateInstall {
314
+ if (raw === null || typeof raw !== 'object') return IDLE_INSTALL
315
+ const record = raw as Record<string, unknown>
316
+ const phase = record.phase
317
+ if (phase !== 'installing' && phase !== 'installed' && phase !== 'failed') return IDLE_INSTALL
318
+ return {
319
+ phase,
320
+ version: typeof record.version === 'string' && record.version !== '' ? record.version : null,
321
+ message: typeof record.message === 'string' && record.message !== '' ? record.message : null,
322
+ at: typeof record.at === 'string' && record.at !== '' ? record.at : null,
323
+ }
324
+ }
325
+
326
+ /** Read the cached answer, ignoring anything malformed. */
327
+ async function readCache(): Promise<UpdateStatus | null> {
328
+ let raw: unknown = null
329
+ try {
330
+ raw = JSON.parse(await readFile(cachePath(), 'utf8')) as unknown
331
+ } catch {
332
+ return null
333
+ }
334
+ if (raw === null || typeof raw !== 'object') return null
335
+ const record = raw as Record<string, unknown>
336
+ const current = typeof record.current === 'string' ? record.current : ''
337
+ if (current === '') return null
338
+ const source = record.source === 'git' || record.source === 'local' ? record.source : 'npm'
339
+ return {
340
+ current,
341
+ latest: typeof record.latest === 'string' && record.latest !== '' ? record.latest : null,
342
+ updateAvailable: record.updateAvailable === true,
343
+ source,
344
+ // A cache written before the source split stored the npm registry here.
345
+ origin: typeof record.origin === 'string' && record.origin !== ''
346
+ ? record.origin
347
+ : typeof record.registry === 'string' ? record.registry : '',
348
+ checkedAt: typeof record.checkedAt === 'string' && record.checkedAt !== '' ? record.checkedAt : null,
349
+ attemptedAt: typeof record.attemptedAt === 'string' && record.attemptedAt !== '' ? record.attemptedAt : null,
350
+ error: typeof record.error === 'string' && record.error !== '' ? record.error : null,
351
+ install: normalizeInstall(record.install),
352
+ }
353
+ }
354
+
355
+ /** Persist the answer atomically with mode 600; failures are the caller's business. */
356
+ async function writeCache(status: UpdateStatus): Promise<void> {
357
+ await mkdir(agentsStorageDir(), { recursive: true, mode: 0o700 })
358
+ const file = cachePath()
359
+ const temp = file + '.' + randomBytes(6).toString('hex') + '.tmp'
360
+ try {
361
+ await writeFile(temp, JSON.stringify(status, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
362
+ await rename(temp, file)
363
+ } catch (error) {
364
+ await rm(temp, { force: true })
365
+ throw error
366
+ }
367
+ }
368
+
369
+ /** One update checker per mounted component. */
370
+ export interface UpdateChecker {
371
+ /** The last known answer, reading the cache on first use. */
372
+ status(): Promise<UpdateStatus>
373
+ /** Ask the remote now; concurrent calls share one request. */
374
+ check(): Promise<UpdateStatus>
375
+ }
376
+
377
+ /**
378
+ * Create the checker for one component instance.
379
+ * @param ctx - host context, read for the profile directory the spec lives in.
380
+ * @param options - live settings snapshot; registry and auto-install are read per check.
381
+ * @param runner - how an install runs; defaults to `pnpm add` in the profile.
382
+ */
383
+ export function createUpdateChecker(ctx: Context, options: () => Options, runner: InstallRunner = runPnpmAdd): UpdateChecker {
384
+ let cached: UpdateStatus | null = null
385
+ let loading: Promise<UpdateStatus> | null = null
386
+ let inFlight: Promise<UpdateStatus> | null = null
387
+ let source: InstallSource | null = null
388
+ let installing = false
389
+
390
+ const resolveSource = async (): Promise<InstallSource> => {
391
+ if (source !== null) return source
392
+ const identity = await packageIdentity()
393
+ source = classifySpec(await profileSpec(ctx, identity.name))
394
+ return source
395
+ }
396
+
397
+ const seed = async (): Promise<UpdateStatus> => {
398
+ const identity = await packageIdentity()
399
+ const install = await resolveSource()
400
+ const stored = await readCache()
401
+ const origin = stored !== null && stored.origin !== ''
402
+ ? stored.origin
403
+ : install.kind === 'git' && install.git !== undefined ? gitManifestUrl(install.git) : options().updateRegistry
404
+ const latest = stored?.latest ?? null
405
+ // A restart applies an install the cache still marks as done for the old version,
406
+ // and an "installing" entry left behind by a killed process is stale.
407
+ const storedInstall = stored?.install ?? IDLE_INSTALL
408
+ const pending: UpdateInstall = storedInstall.phase === 'installed' && storedInstall.version === identity.version
409
+ ? IDLE_INSTALL
410
+ : storedInstall.phase === 'installing'
411
+ ? { phase: 'failed', version: storedInstall.version, message: '上次自动更新被中断(进程退出)', at: storedInstall.at }
412
+ : storedInstall
413
+ return {
414
+ current: identity.version,
415
+ latest,
416
+ updateAvailable: latest !== null && compareVersions(latest, identity.version) > 0,
417
+ source: install.kind,
418
+ origin,
419
+ checkedAt: stored?.checkedAt ?? null,
420
+ attemptedAt: stored?.attemptedAt ?? null,
421
+ error: stored?.error ?? null,
422
+ install: pending,
423
+ }
424
+ }
425
+
426
+ const status = async (): Promise<UpdateStatus> => {
427
+ if (cached !== null) return cached
428
+ loading ??= seed().then((value) => {
429
+ cached = value
430
+ return value
431
+ }).finally(() => { loading = null })
432
+ return loading
433
+ }
434
+
435
+ /** Install one update in the background and publish the outcome. */
436
+ const installInBackground = (command: InstallCommand, version: string): void => {
437
+ if (installing) return
438
+ installing = true
439
+ void (async () => {
440
+ const saved = await Promise.all(['package.json', 'pnpm-lock.yaml'].map(async (name) => {
441
+ try {
442
+ return { name, text: await readFile(join(command.dir, name), 'utf8') }
443
+ } catch {
444
+ return { name, text: null }
445
+ }
446
+ }))
447
+ let phase: UpdateInstall
448
+ try {
449
+ await runner(command)
450
+ phase = { phase: 'installed', version, message: '已安装,重启 dsh web 后生效', at: new Date().toISOString() }
451
+ } catch (error) {
452
+ await restoreProfile(command.dir, saved)
453
+ phase = { phase: 'failed', version, message: errorMessage(error), at: new Date().toISOString() }
454
+ }
455
+ const current = cached
456
+ if (current !== null) {
457
+ cached = { ...current, install: phase }
458
+ try {
459
+ await writeCache(cached)
460
+ } catch {
461
+ // A read-only home still keeps the in-memory answer.
462
+ }
463
+ }
464
+ installing = false
465
+ })()
466
+ }
467
+
468
+ const check = async (): Promise<UpdateStatus> => {
469
+ if (inFlight !== null) return inFlight
470
+ inFlight = (async () => {
471
+ const previous = await status()
472
+ const identity = await packageIdentity()
473
+ const install = await resolveSource()
474
+ const settings = options()
475
+ const attemptedAt = new Date().toISOString()
476
+ const git = install.git
477
+ const origin = install.kind === 'git' && git !== undefined ? gitManifestUrl(git) : settings.updateRegistry
478
+ let next: UpdateStatus
479
+ try {
480
+ const latest = install.kind === 'git' && git !== undefined
481
+ ? await fetchVersion(origin)
482
+ : await fetchNpmLatest(settings.updateRegistry, identity.name)
483
+ next = {
484
+ ...previous,
485
+ current: identity.version,
486
+ latest,
487
+ updateAvailable: compareVersions(latest, identity.version) > 0,
488
+ source: install.kind,
489
+ origin,
490
+ checkedAt: attemptedAt,
491
+ attemptedAt,
492
+ error: null,
493
+ }
494
+ const directory = profileDir(ctx)
495
+ const alreadyInstalled = previous.install.phase === 'installed' && previous.install.version === latest
496
+ const command = next.updateAvailable && settings.updateAutoInstall && directory !== null
497
+ && previous.install.phase !== 'installing' && !alreadyInstalled
498
+ ? installCommand(install, directory, identity.name, latest)
499
+ : null
500
+ if (command !== null) {
501
+ next = { ...next, install: { phase: 'installing', version: latest, message: null, at: attemptedAt } }
502
+ cached = next
503
+ try {
504
+ await writeCache(next)
505
+ } catch {
506
+ // The in-memory state still drives the panel.
507
+ }
508
+ installInBackground(command, latest)
509
+ return next
510
+ }
511
+ } catch (error) {
512
+ next = {
513
+ ...previous,
514
+ current: identity.version,
515
+ updateAvailable: previous.latest !== null && compareVersions(previous.latest, identity.version) > 0,
516
+ source: install.kind,
517
+ origin,
518
+ attemptedAt,
519
+ error: errorMessage(error),
520
+ }
521
+ }
522
+ cached = next
523
+ try {
524
+ await writeCache(next)
525
+ } catch {
526
+ // A read-only home must not turn a failed check into a failed request.
527
+ }
528
+ return next
529
+ })().finally(() => { inFlight = null })
530
+ return inFlight
531
+ }
532
+
533
+ return { status, check }
534
+ }
535
+
536
+ /**
537
+ * Run the automatic checks: one shortly after activation, then at the
538
+ * configured interval. The next delay is recomputed after every run, so an
539
+ * interval edited in the panel is picked up without a restart.
540
+ */
541
+ export function startUpdateWatcher(ctx: Context, checker: UpdateChecker, options: () => Options): void {
542
+ let disposed = false
543
+ let timer: NodeJS.Timeout | undefined
544
+
545
+ const schedule = (delayMs: number): void => {
546
+ if (disposed) return
547
+ timer = setTimeout(tick, delayMs)
548
+ // A pending check must not keep a headless process alive.
549
+ timer.unref?.()
550
+ }
551
+
552
+ const tick = async (): Promise<void> => {
553
+ if (disposed) return
554
+ const current = options()
555
+ if (current.updateCheck) {
556
+ try {
557
+ await checker.check()
558
+ } catch (error) {
559
+ ctx.logger.warn('utils-agents: published-version check failed: ' + errorMessage(error))
560
+ }
561
+ }
562
+ if (disposed) return
563
+ // Keep the timer alive even while checks are disabled, so enabling them in
564
+ // the panel takes effect on the next tick without a restart.
565
+ const next = options()
566
+ schedule(Math.max(1, next.updateCheckIntervalHours) * 3_600_000)
567
+ }
568
+
569
+ schedule(FIRST_CHECK_DELAY_MS)
570
+ ctx.effect(() => () => {
571
+ disposed = true
572
+ if (timer !== undefined) clearTimeout(timer)
573
+ }, 'utils-agents: update watcher')
574
+ }