-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathremote-sync.ts
More file actions
214 lines (183 loc) · 5.38 KB
/
Copy pathremote-sync.ts
File metadata and controls
214 lines (183 loc) · 5.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { createHash } from 'node:crypto'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { TIMEOUTS } from '@browseros/shared/constants/timeouts'
import { EXTERNAL_URLS } from '@browseros/shared/constants/urls'
import { INLINED_ENV } from '../env'
import { getSkillsDir } from '../lib/browseros-dir'
import { logger } from '../lib/logger'
import type {
ManagedSkillRecord,
RemoteSkillCatalog,
RemoteSkillEntry,
SkillManifest,
} from './types'
const MANIFEST_FILE = '.remote-manifest.json'
let syncTimer: ReturnType<typeof setInterval> | null = null
function contentHash(content: string): string {
return createHash('sha256').update(content).digest('hex')
}
function getManifestPath(): string {
return join(getSkillsDir(), MANIFEST_FILE)
}
export async function loadManifest(): Promise<SkillManifest> {
try {
const raw = await readFile(getManifestPath(), 'utf-8')
return JSON.parse(raw) as SkillManifest
} catch {
return { lastSyncedAt: '', skills: {} }
}
}
async function saveManifest(manifest: SkillManifest): Promise<void> {
await writeFile(getManifestPath(), JSON.stringify(manifest, null, 2))
}
function getCatalogUrl(): string {
return INLINED_ENV.SKILLS_CATALOG_URL || EXTERNAL_URLS.SKILLS_CATALOG
}
export async function fetchRemoteCatalog(): Promise<RemoteSkillCatalog | null> {
try {
const response = await fetch(getCatalogUrl(), {
signal: AbortSignal.timeout(TIMEOUTS.SKILLS_FETCH),
})
if (!response.ok) {
logger.warn('Failed to fetch remote skill catalog', {
status: response.status,
})
return null
}
return (await response.json()) as RemoteSkillCatalog
} catch (err) {
logger.debug('Remote skill catalog unavailable', {
error: err instanceof Error ? err.message : String(err),
})
return null
}
}
function isSkillCustomized(
skillId: string,
currentContent: string,
manifest: SkillManifest,
): boolean {
const record = manifest.skills[skillId]
if (!record) return false
return contentHash(currentContent) !== record.contentHash
}
async function readSkillContent(skillId: string): Promise<string | null> {
try {
return await readFile(
join(getSkillsDir(), skillId, 'SKILL.md'),
'utf-8',
)
} catch {
return null
}
}
async function writeSkillFile(
skillId: string,
content: string,
): Promise<void> {
const targetDir = join(getSkillsDir(), skillId)
await mkdir(targetDir, { recursive: true })
await writeFile(join(targetDir, 'SKILL.md'), content)
}
async function installSkill(
skill: RemoteSkillEntry,
manifest: SkillManifest,
): Promise<void> {
await writeSkillFile(skill.id, skill.content)
manifest.skills[skill.id] = {
version: skill.version,
contentHash: contentHash(skill.content),
}
}
export async function syncRemoteSkills(): Promise<{
installed: number
updated: number
skipped: number
}> {
const result = { installed: 0, updated: 0, skipped: 0 }
const catalog = await fetchRemoteCatalog()
if (!catalog) return result
const manifest = await loadManifest()
for (const remoteSkill of catalog.skills) {
const localContent = await readSkillContent(remoteSkill.id)
const localRecord: ManagedSkillRecord | undefined =
manifest.skills[remoteSkill.id]
if (!localContent) {
await installSkill(remoteSkill, manifest)
result.installed++
continue
}
if (!localRecord) {
// Skill exists locally but isn't tracked — treat as user-managed
result.skipped++
continue
}
if (localRecord.version === remoteSkill.version) {
continue
}
if (isSkillCustomized(remoteSkill.id, localContent, manifest)) {
result.skipped++
continue
}
await installSkill(remoteSkill, manifest)
result.updated++
}
manifest.lastSyncedAt = new Date().toISOString()
await saveManifest(manifest)
return result
}
export async function seedFromRemote(): Promise<boolean> {
const catalog = await fetchRemoteCatalog()
if (!catalog || catalog.skills.length === 0) return false
const manifest = await loadManifest()
let seeded = 0
for (const skill of catalog.skills) {
try {
await writeSkillFile(skill.id, skill.content)
manifest.skills[skill.id] = {
version: skill.version,
contentHash: contentHash(skill.content),
}
seeded++
} catch (err) {
logger.warn('Failed to seed remote skill', {
id: skill.id,
error: err instanceof Error ? err.message : String(err),
})
}
}
if (seeded > 0) {
manifest.lastSyncedAt = new Date().toISOString()
await saveManifest(manifest)
logger.info(`Seeded ${seeded} skills from remote catalog`)
}
return seeded > 0
}
export function startSkillSync(): void {
if (syncTimer) return
syncTimer = setInterval(async () => {
try {
const { installed, updated, skipped } = await syncRemoteSkills()
if (installed > 0 || updated > 0) {
logger.info('Remote skill sync completed', {
installed,
updated,
skipped,
})
}
} catch (err) {
logger.warn('Skill sync failed', {
error: err instanceof Error ? err.message : String(err),
})
}
}, TIMEOUTS.SKILLS_SYNC_INTERVAL)
// Don't block process exit
syncTimer.unref()
}
export function stopSkillSync(): void {
if (syncTimer) {
clearInterval(syncTimer)
syncTimer = null
}
}