-
-
Notifications
You must be signed in to change notification settings - Fork 176
Expand file tree
/
Copy pathskillsRoutes.ts
More file actions
1691 lines (1583 loc) · 64.9 KB
/
Copy pathskillsRoutes.ts
File metadata and controls
1691 lines (1583 loc) · 64.9 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawn } from 'node:child_process'
import { mkdtemp, readFile, readdir, rm, mkdir, stat, lstat, readlink, symlink } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
import { writeFile } from 'node:fs/promises'
import { resolvePythonCommand, resolveSkillInstallerScriptPath } from '../commandResolution.js'
import { getSpawnInvocation } from '../utils/commandInvocation.js'
type AppServerLike = {
rpc(method: string, params: unknown): Promise<unknown>
}
type ReadJsonBody = (req: IncomingMessage) => Promise<unknown>
type SkillRouteContext = {
appServer: AppServerLike
readJsonBody: ReadJsonBody
}
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: null
}
function getErrorMessage(payload: unknown, fallback: string): string {
if (payload instanceof Error && payload.message.trim().length > 0) {
return payload.message
}
const record = asRecord(payload)
if (!record) return fallback
const error = record.error
if (typeof error === 'string' && error.length > 0) return error
const nestedError = asRecord(error)
if (nestedError && typeof nestedError.message === 'string' && nestedError.message.length > 0) {
return nestedError.message
}
return fallback
}
function setJson(res: ServerResponse, statusCode: number, payload: unknown): void {
res.statusCode = statusCode
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(payload))
}
function getCodexHomeDir(): string {
const codexHome = process.env.CODEX_HOME?.trim()
return codexHome && codexHome.length > 0 ? codexHome : join(homedir(), '.codex')
}
function splitAbsolutePath(pathValue: string): string[] {
return pathValue.split('/').filter(Boolean)
}
function buildAbsolutePath(parts: string[]): string {
return `/${parts.join('/')}`
}
function normalizeSkillMarkdownPath(skillPath: string): string {
if (!skillPath) return ''
return skillPath.endsWith('/SKILL.md') ? skillPath : `${skillPath}/SKILL.md`
}
function deriveSkillPathInfo(
skillPath: string,
knownPaths: Set<string> = new Set(),
): {
normalizedPath: string
rootSkillPath: string
rootSkillName: string
installDir: string
isNestedSkill: boolean
} | null {
const normalizedPath = normalizeSkillMarkdownPath(skillPath)
const parts = splitAbsolutePath(normalizedPath)
if (parts.length < 2) return null
const pluginSkillsIndex = parts.lastIndexOf('skills')
if (pluginSkillsIndex >= 2) {
const pluginName = parts[pluginSkillsIndex - 2] ?? ''
if (pluginName) {
const rootSkillPath = buildAbsolutePath([...parts.slice(0, pluginSkillsIndex + 1), pluginName, 'SKILL.md'])
if (knownPaths.has(rootSkillPath)) {
return {
normalizedPath,
rootSkillPath,
rootSkillName: pluginName,
installDir: buildAbsolutePath(parts.slice(0, pluginSkillsIndex + 1)),
isNestedSkill: normalizedPath !== rootSkillPath,
}
}
}
}
const firstSkillsIndex = parts.indexOf('skills')
if (firstSkillsIndex < 0 || firstSkillsIndex + 1 >= parts.length - 1) return null
const rootSkillName = parts[firstSkillsIndex + 1] ?? ''
if (!rootSkillName) return null
const rootParts = parts.slice(0, firstSkillsIndex + 2)
const installDirParts = parts.slice(0, firstSkillsIndex + 1)
return {
normalizedPath,
rootSkillPath: buildAbsolutePath([...rootParts, 'SKILL.md']),
rootSkillName,
installDir: buildAbsolutePath(installDirParts),
isNestedSkill: normalizedPath !== buildAbsolutePath([...rootParts, 'SKILL.md']),
}
}
function getSkillsInstallDir(): string {
return join(getCodexHomeDir(), 'skills')
}
const DEFAULT_COMMAND_TIMEOUT_MS = 120_000
const SKILL_SEARCH_METADATA_LIMIT = 20
const SKILL_SEARCH_METADATA_CONCURRENCY = 4
async function runCommand(command: string, args: string[], options: { cwd?: string; timeoutMs?: number } = {}): Promise<void> {
const timeout = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS
await new Promise<void>((resolve, reject) => {
const invocation = getSpawnInvocation(command, args)
const proc = spawn(invocation.command, invocation.args, {
cwd: options.cwd,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
})
let settled = false
let stdout = ''
let stderr = ''
const timer = setTimeout(() => {
if (settled) return
settled = true
proc.kill('SIGKILL')
reject(new Error(`Command timed out after ${timeout}ms (${command} ${args.join(' ')})`))
}, timeout)
proc.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
proc.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
proc.on('error', (err) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(err)
})
proc.on('close', (code) => {
if (settled) return
settled = true
clearTimeout(timer)
if (code === 0) {
resolve()
return
}
const details = [stderr.trim(), stdout.trim()].filter(Boolean).join('\n')
const suffix = details.length > 0 ? `: ${details}` : ''
reject(new Error(`Command failed (${command} ${args.join(' ')})${suffix}`))
})
})
}
async function runCommandWithOutput(command: string, args: string[], options: { cwd?: string; timeoutMs?: number } = {}): Promise<string> {
const timeout = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS
return await new Promise<string>((resolve, reject) => {
const invocation = getSpawnInvocation(command, args)
const proc = spawn(invocation.command, invocation.args, {
cwd: options.cwd,
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
})
let settled = false
let stdout = ''
let stderr = ''
const timer = setTimeout(() => {
if (settled) return
settled = true
proc.kill('SIGKILL')
reject(new Error(`Command timed out after ${timeout}ms (${command} ${args.join(' ')})`))
}, timeout)
proc.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
proc.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
proc.on('error', (err) => {
if (settled) return
settled = true
clearTimeout(timer)
reject(err)
})
proc.on('close', (code) => {
if (settled) return
settled = true
clearTimeout(timer)
if (code === 0) {
resolve(stdout.trim())
return
}
const details = [stderr.trim(), stdout.trim()].filter(Boolean).join('\n')
const suffix = details.length > 0 ? `: ${details}` : ''
reject(new Error(`Command failed (${command} ${args.join(' ')})${suffix}`))
})
})
}
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms)
promise.then(
(val) => { clearTimeout(timer); resolve(val) },
(err) => { clearTimeout(timer); reject(err) },
)
})
}
async function detectUserSkillsDir(appServer: AppServerLike): Promise<string> {
try {
const result = (await appServer.rpc('skills/list', {})) as {
data?: Array<{ skills?: Array<{ scope?: string; path?: string }> }>
}
for (const entry of result.data ?? []) {
for (const skill of entry.skills ?? []) {
if (skill.scope !== 'user' || !skill.path) continue
const skillInfo = deriveSkillPathInfo(skill.path)
if (!skillInfo) continue
return skillInfo.installDir
}
}
} catch {}
return getSkillsInstallDir()
}
async function ensureInstalledSkillIsValid(appServer: AppServerLike, skillPath: string): Promise<void> {
const result = (await appServer.rpc('skills/list', { forceReload: true })) as {
data?: Array<{ errors?: Array<{ path?: string; message?: string }> }>
}
const normalized = skillPath.endsWith('/SKILL.md') ? skillPath : `${skillPath}/SKILL.md`
for (const entry of result.data ?? []) {
for (const error of entry.errors ?? []) {
if (error.path === normalized) {
throw new Error(error.message || 'Installed skill is invalid')
}
}
}
}
type SkillHubEntry = {
name: string
owner: string
description: string
displayName: string
publishedAt: number
avatarUrl: string
url: string
installed: boolean
source?: string
path?: string
enabled?: boolean
installCountLabel?: string
}
async function runGitFetchWithRefLockRetry(repoDir: string, args: string[] = ['fetch', 'origin']): Promise<void> {
try {
await runCommand('git', args, { cwd: repoDir })
} catch (error) {
const message = getErrorMessage(error, '')
if (!message.includes("cannot lock ref 'refs/remotes/origin/")) throw error
const branchMatch = message.match(/refs\/remotes\/origin\/([^\s':]+)/)
if (!branchMatch?.[1]) throw error
const refPath = join(repoDir, '.git', 'refs', 'remotes', 'origin', branchMatch[1])
try { await rm(refPath, { force: true }) } catch {}
await runCommand('git', args, { cwd: repoDir })
}
}
async function buildLocalHubEntry(info: InstalledSkillInfo): Promise<SkillHubEntry> {
let description = ''
if (info.path) {
try {
description = extractSkillDescriptionFromMarkdown(await readFile(info.path, 'utf8'))
} catch {}
}
return {
name: info.name,
owner: 'local',
description,
displayName: '',
publishedAt: 0,
avatarUrl: '',
url: '',
installed: true,
path: info.path,
enabled: info.enabled,
}
}
function stripAnsi(value: string): string {
return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/gu, '')
}
function parseNpxSkillsFindOutput(output: string, installedMap: Map<string, InstalledSkillInfo>): SkillHubEntry[] {
const lines = stripAnsi(output).split(/\r?\n/u).map((line) => line.trim()).filter(Boolean)
const results: SkillHubEntry[] = []
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index] ?? ''
const match = line.match(/^(.+?@[^@\s]+)\s+([\d.]+[KMB]?)\s+installs$/iu)
if (!match) continue
const source = match[1]?.trim() ?? ''
const installs = match[2]?.trim() ?? ''
const atIndex = source.lastIndexOf('@')
if (atIndex <= 0 || atIndex >= source.length - 1) continue
const owner = source.slice(0, atIndex)
const name = source.slice(atIndex + 1)
let url = ''
const next = lines[index + 1] ?? ''
const urlMatch = next.match(/(?:^└\s*)?(https?:\/\/\S+)$/u)
if (urlMatch?.[1]) {
url = urlMatch[1]
index += 1
}
const installedInfo = installedMap.get(name)
results.push({
name,
owner,
displayName: name,
description: installs ? `${installs} installs` : '',
installCountLabel: installs ? `${installs} installs` : '',
publishedAt: 0,
avatarUrl: '',
url,
installed: Boolean(installedInfo),
source,
path: installedInfo?.path,
enabled: installedInfo?.enabled,
})
}
return results
}
function parseGithubSkillSource(source: string): { ownerRepo: string; skillName: string } | null {
const atIndex = source.lastIndexOf('@')
if (atIndex <= 0 || atIndex >= source.length - 1) return null
const ownerRepo = source.slice(0, atIndex).trim()
const skillName = source.slice(atIndex + 1).trim()
const ownerRepoParts = ownerRepo.split('/').filter(Boolean)
if (ownerRepoParts.length !== 2 || skillName.length === 0) return null
if (ownerRepoParts.some((part) => part.includes(':') || part.includes(' '))) return null
return { ownerRepo, skillName }
}
function getGithubOwnerAvatarUrl(source: string): string {
const parsed = parseGithubSkillSource(source)
if (!parsed) return ''
const owner = parsed.ownerRepo.split('/')[0] ?? ''
return owner ? `https://github.com/${encodeURIComponent(owner)}.png?size=64` : ''
}
function buildGithubSkillRawCandidates(source: string): string[] {
const parsed = parseGithubSkillSource(source)
if (!parsed) return []
const ownerRepo = parsed.ownerRepo.split('/').map(encodeURIComponent).join('/')
const skillName = encodeURIComponent(parsed.skillName)
const branches = ['main', 'master']
const paths = [
`skills/${skillName}/SKILL.md`,
`${skillName}/SKILL.md`,
'SKILL.md',
]
return branches.flatMap((branch) => paths.map((path) => `https://raw.githubusercontent.com/${ownerRepo}/${branch}/${path}`))
}
async function fetchTextWithTimeout(url: string, timeoutMs: number): Promise<string> {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), timeoutMs)
try {
const resp = await fetch(url, {
headers: { 'User-Agent': 'codex-web-local' },
signal: controller.signal,
})
if (!resp.ok) return ''
return await resp.text()
} finally {
clearTimeout(timeout)
}
}
function resolveSkillIconUrl(icon: string, markdownUrl: string): string {
const value = icon.trim().replace(/^['"]|['"]$/gu, '')
if (!value) return ''
if (/^https?:\/\//iu.test(value)) return value
try {
return new URL(value, markdownUrl).toString()
} catch {
return ''
}
}
async function fetchGithubSkillMetadata(source: string): Promise<Partial<Pick<SkillHubEntry, 'avatarUrl' | 'description'>>> {
for (const candidate of buildGithubSkillRawCandidates(source)) {
try {
const markdown = await fetchTextWithTimeout(candidate, 4_000)
if (!markdown) continue
const description = extractSkillDescriptionFromMarkdown(markdown)
const icon = extractSkillFrontmatterField(markdown, 'icon')
const avatarUrl = icon ? resolveSkillIconUrl(icon, candidate) : getGithubOwnerAvatarUrl(source)
if (description || avatarUrl) return { description, avatarUrl }
} catch {}
}
return { avatarUrl: getGithubOwnerAvatarUrl(source) }
}
async function mapWithConcurrency<T, R>(
items: T[],
concurrency: number,
mapper: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length)
let nextIndex = 0
const workerCount = Math.max(1, Math.min(concurrency, items.length))
await Promise.all(Array.from({ length: workerCount }, async () => {
while (nextIndex < items.length) {
const index = nextIndex
nextIndex += 1
results[index] = await mapper(items[index] as T, index)
}
}))
return results
}
async function enrichSkillSearchDescriptions(results: SkillHubEntry[]): Promise<SkillHubEntry[]> {
const enrichedHead = await mapWithConcurrency(
results.slice(0, SKILL_SEARCH_METADATA_LIMIT),
SKILL_SEARCH_METADATA_CONCURRENCY,
async (result) => {
if (!result.source) return result
const metadata = await fetchGithubSkillMetadata(result.source)
return {
...result,
description: metadata.description || result.description,
avatarUrl: metadata.avatarUrl || result.avatarUrl,
}
},
)
return [...enrichedHead, ...results.slice(SKILL_SEARCH_METADATA_LIMIT)]
}
type RpcSkillRecord = {
name?: string
description?: string
shortDescription?: string
path?: string
scope?: string
enabled?: boolean
}
function groupRpcSkillRecords<T extends RpcSkillRecord>(skills: T[]): T[] {
const normalizedPathSet = new Set(
skills
.map((skill) => normalizeSkillMarkdownPath(typeof skill.path === 'string' ? skill.path : ''))
.filter(Boolean),
)
const grouped = new Map<string, { preferred: T; hasRoot: boolean; anyEnabled: boolean }>()
for (const skill of skills) {
const rawPath = typeof skill.path === 'string' ? skill.path : ''
const pathInfo = rawPath ? deriveSkillPathInfo(rawPath, normalizedPathSet) : null
const groupingKey = pathInfo && pathInfo.isNestedSkill && normalizedPathSet.has(pathInfo.rootSkillPath)
? pathInfo.rootSkillPath
: (pathInfo?.normalizedPath || rawPath || `${skill.scope ?? ''}:${skill.name ?? ''}`)
const existing = grouped.get(groupingKey)
const isRootEntry = pathInfo?.normalizedPath === groupingKey
const groupedName = pathInfo && groupingKey === pathInfo.rootSkillPath
? pathInfo.rootSkillName
: skill.name
if (!existing) {
grouped.set(groupingKey, {
preferred: isRootEntry
? {
...skill,
name: groupedName,
path: groupingKey,
}
: {
...skill,
name: groupedName,
path: groupingKey,
},
hasRoot: isRootEntry,
anyEnabled: skill.enabled !== false,
})
continue
}
existing.anyEnabled = existing.anyEnabled || skill.enabled !== false
if (!existing.hasRoot && isRootEntry) {
existing.preferred = {
...skill,
name: groupedName,
path: groupingKey,
}
existing.hasRoot = true
continue
}
if (!existing.preferred.description && skill.description) {
existing.preferred = { ...existing.preferred, description: skill.description }
}
if (!existing.preferred.shortDescription && skill.shortDescription) {
existing.preferred = { ...existing.preferred, shortDescription: skill.shortDescription }
}
}
return Array.from(grouped.values()).map(({ preferred, anyEnabled }) => ({
...preferred,
enabled: preferred.enabled ?? anyEnabled,
}))
}
type InstalledSkillInfo = { name: string; path: string; enabled: boolean }
type SyncedSkill = { owner?: string; name: string; enabled: boolean }
type SkillsSyncState = {
githubToken?: string
githubUsername?: string
repoOwner?: string
repoName?: string
installedOwners?: Record<string, string>
lastPullCommitSha?: string
lastPushCommitSha?: string
lastSyncAttemptCount?: number
lastSyncError?: string
lastSyncAtIso?: string
}
type GithubDeviceCodeResponse = {
device_code: string
user_code: string
verification_uri: string
expires_in: number
interval: number
}
type GithubTokenResponse = { access_token?: string; error?: string }
const GITHUB_DEVICE_CLIENT_ID = 'Iv1.b507a08c87ecfe98'
const DEFAULT_SKILLS_SYNC_REPO_NAME = 'codexskills'
const SKILLS_SYNC_MANIFEST_PATH = 'installed-skills.json'
const SYNC_UPSTREAM_SKILLS_OWNER = 'OpenClawAndroid'
const SYNC_UPSTREAM_SKILLS_REPO = 'skills'
const PRIVATE_SYNC_BRANCH = 'main'
const PUBLIC_UPSTREAM_BRANCH_ANDROID = 'android'
const PUBLIC_UPSTREAM_BRANCH_DEFAULT = 'main'
let startupSkillsSyncInitialized = false
type StartupSyncStatus = {
inProgress: boolean
mode: 'unauthenticated-bootstrap' | 'authenticated-fork-sync' | 'idle'
branch: string
lastAction: string
lastRunAtIso: string
lastSuccessAtIso: string
lastError: string
}
const startupSyncStatus: StartupSyncStatus = {
inProgress: false,
mode: 'idle',
branch: PRIVATE_SYNC_BRANCH,
lastAction: 'not-started',
lastRunAtIso: '',
lastSuccessAtIso: '',
lastError: '',
}
async function scanInstalledSkillsFromDisk(): Promise<Map<string, InstalledSkillInfo>> {
const map = new Map<string, InstalledSkillInfo>()
const skillsDir = getSkillsInstallDir()
try {
const entries = await readdir(skillsDir, { withFileTypes: true })
for (const entry of entries) {
if (!entry.isDirectory() || entry.name.startsWith('.')) continue
const skillMd = join(skillsDir, entry.name, 'SKILL.md')
try {
await stat(skillMd)
map.set(entry.name, { name: entry.name, path: skillMd, enabled: true })
} catch {}
}
} catch {}
return map
}
async function collectInstalledSkillsMap(appServer: AppServerLike): Promise<Map<string, InstalledSkillInfo>> {
const installedMap = await scanInstalledSkillsFromDisk()
try {
const result = await appServer.rpc('skills/list', {}) as { data?: Array<{ skills?: RpcSkillRecord[] }> }
for (const entry of result.data ?? []) {
for (const skill of groupRpcSkillRecords(entry.skills ?? [])) {
if (skill.name) {
installedMap.set(skill.name, { name: skill.name, path: skill.path ?? '', enabled: skill.enabled !== false })
}
}
}
} catch {}
return installedMap
}
function extractSkillFrontmatterField(markdown: string, fieldName: string): string {
const lines = markdown.split(/\r?\n/)
if (lines[0]?.trim() !== '---') return ''
const frontmatter: string[] = []
for (let index = 1; index < lines.length; index += 1) {
const line = lines[index] ?? ''
if (line.trim() === '---') break
frontmatter.push(line)
}
const escapedFieldName = fieldName.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
const fieldPattern = new RegExp(`^${escapedFieldName}\\s*:`, 'iu')
const valuePattern = new RegExp(`^${escapedFieldName}\\s*:\\s*`, 'iu')
const fieldLine = frontmatter.find((line) => fieldPattern.test(line.trim()))
if (!fieldLine) return ''
return fieldLine.replace(valuePattern, '').replace(/^['"]|['"]$/gu, '').trim()
}
function extractSkillDescriptionFromMarkdown(markdown: string): string {
const frontmatterDescription = extractSkillFrontmatterField(markdown, 'description')
if (frontmatterDescription) return frontmatterDescription
const lines = markdown.split(/\r?\n/)
let inCodeFence = false
for (const rawLine of lines) {
const line = rawLine.trim()
if (line.startsWith('```')) {
inCodeFence = !inCodeFence
continue
}
if (inCodeFence || line.length === 0) continue
if (line.startsWith('#')) continue
if (line.startsWith('>')) continue
if (line.startsWith('- ') || line.startsWith('* ')) continue
return line
}
return ''
}
function getSkillsSyncStatePath(): string {
return join(getCodexHomeDir(), 'skills-sync.json')
}
async function readSkillsSyncState(): Promise<SkillsSyncState> {
try {
const raw = await readFile(getSkillsSyncStatePath(), 'utf8')
const parsed = JSON.parse(raw) as SkillsSyncState
return parsed && typeof parsed === 'object' ? parsed : {}
} catch {
return {}
}
}
async function writeSkillsSyncState(state: SkillsSyncState): Promise<void> {
await writeFile(getSkillsSyncStatePath(), JSON.stringify(state), 'utf8')
}
async function getGithubJson<T>(url: string, token: string, method = 'GET', body?: unknown): Promise<T> {
const resp = await fetch(url, {
method,
headers: {
Accept: 'application/vnd.github+json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'codex-web-local',
},
body: body ? JSON.stringify(body) : undefined,
})
if (!resp.ok) {
const text = await resp.text()
throw new Error(`GitHub API ${method} ${url} failed (${resp.status}): ${text}`)
}
return await resp.json() as T
}
async function startGithubDeviceLogin(): Promise<GithubDeviceCodeResponse> {
const resp = await fetch('https://github.com/login/device/code', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'codex-web-local',
},
body: new URLSearchParams({
client_id: GITHUB_DEVICE_CLIENT_ID,
scope: 'repo read:user',
}),
})
if (!resp.ok) {
throw new Error(`GitHub device flow init failed (${resp.status})`)
}
return await resp.json() as GithubDeviceCodeResponse
}
async function completeGithubDeviceLogin(deviceCode: string): Promise<{ token: string | null; error: string | null }> {
const resp = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'User-Agent': 'codex-web-local',
},
body: new URLSearchParams({
client_id: GITHUB_DEVICE_CLIENT_ID,
device_code: deviceCode,
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
}),
})
if (!resp.ok) {
throw new Error(`GitHub token exchange failed (${resp.status})`)
}
const payload = await resp.json() as GithubTokenResponse
if (!payload.access_token) return { token: null, error: payload.error || 'unknown_error' }
return { token: payload.access_token, error: null }
}
function isAndroidLikeRuntime(): boolean {
if (process.platform === 'android') return true
if (existsSync('/data/data/com.termux')) return true
if (process.env.TERMUX_VERSION) return true
const prefix = process.env.PREFIX?.toLowerCase() ?? ''
if (prefix.includes('/com.termux/')) return true
const proot = process.env.PROOT_TMP_DIR?.toLowerCase() ?? ''
return proot.length > 0
}
function getPreferredPublicUpstreamBranch(): string {
return isAndroidLikeRuntime() ? PUBLIC_UPSTREAM_BRANCH_ANDROID : PUBLIC_UPSTREAM_BRANCH_DEFAULT
}
function isUpstreamSkillsRepo(repoOwner: string, repoName: string): boolean {
return repoOwner.toLowerCase() === SYNC_UPSTREAM_SKILLS_OWNER.toLowerCase()
&& repoName.toLowerCase() === SYNC_UPSTREAM_SKILLS_REPO.toLowerCase()
}
async function resolveGithubUsername(token: string): Promise<string> {
const user = await getGithubJson<{ login: string }>('https://api.github.com/user', token)
return user.login
}
async function ensurePrivateForkFromUpstream(token: string, username: string, repoName: string): Promise<void> {
const repoUrl = `https://api.github.com/repos/${username}/${repoName}`
let created = false
const existing = await fetch(repoUrl, {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'codex-web-local',
},
})
if (existing.ok) {
const details = await existing.json() as { private?: boolean }
if (details.private === true) return
await getGithubJson(repoUrl, token, 'PATCH', { private: true })
return
}
if (existing.status !== 404) {
throw new Error(`Failed to check personal repo existence (${existing.status})`)
}
const createRepo = await fetch('https://api.github.com/user/repos', {
method: 'POST',
headers: {
Accept: 'application/vnd.github+json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'codex-web-local',
},
body: JSON.stringify({ name: repoName, private: true, auto_init: false, description: 'Codex skills private mirror sync' }),
})
if (!createRepo.ok) {
const text = await createRepo.text()
if (createRepo.status === 403 && text.includes('Resource not accessible by integration')) {
throw new Error(`GitHub login cannot create the private ${repoName} sync repo with this token. Create an empty private repo named ${repoName} on GitHub, then retry Device Login, or use the regular GitHub login button with repo access.`)
}
throw new Error(`GitHub API POST https://api.github.com/user/repos failed (${createRepo.status}): ${text}`)
}
created = true
let ready = false
for (let i = 0; i < 20; i++) {
const check = await fetch(repoUrl, {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'codex-web-local',
},
})
if (check.ok) {
ready = true
break
}
await new Promise((resolve) => setTimeout(resolve, 1000))
}
if (!ready) throw new Error('Private mirror repo was created but is not available yet')
if (!created) return
const tmp = await mkdtemp(join(tmpdir(), 'codex-skills-seed-'))
try {
const upstreamUrl = `https://github.com/${SYNC_UPSTREAM_SKILLS_OWNER}/${SYNC_UPSTREAM_SKILLS_REPO}.git`
const branch = PRIVATE_SYNC_BRANCH
try {
await runCommand('git', ['clone', '--depth', '1', '--single-branch', '--branch', branch, upstreamUrl, tmp])
} catch {
await runCommand('git', ['clone', '--depth', '1', upstreamUrl, tmp])
}
const privateRemote = toGitHubTokenRemote(username, repoName, token)
await runCommand('git', ['remote', 'set-url', 'origin', privateRemote], { cwd: tmp })
try { await runCommand('git', ['checkout', '-B', branch], { cwd: tmp }) } catch {}
await runCommand('git', ['push', '-u', 'origin', `HEAD:${branch}`], { cwd: tmp })
} finally {
await rm(tmp, { recursive: true, force: true })
}
}
async function readRemoteSkillsManifest(token: string, repoOwner: string, repoName: string): Promise<SyncedSkill[]> {
const url = `https://api.github.com/repos/${repoOwner}/${repoName}/contents/${SKILLS_SYNC_MANIFEST_PATH}`
const resp = await fetch(url, {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'codex-web-local',
},
})
if (resp.status === 404) return []
if (!resp.ok) throw new Error(`Failed to read remote manifest (${resp.status})`)
const payload = await resp.json() as { content?: string }
const content = payload.content ? Buffer.from(payload.content.replace(/\n/g, ''), 'base64').toString('utf8') : '[]'
const parsed = JSON.parse(content) as unknown
if (!Array.isArray(parsed)) return []
const skills: SyncedSkill[] = []
for (const row of parsed) {
const item = asRecord(row)
const owner = typeof item?.owner === 'string' ? item.owner : ''
const name = typeof item?.name === 'string' ? item.name : ''
if (!name) continue
skills.push({ ...(owner ? { owner } : {}), name, enabled: item?.enabled !== false })
}
return skills
}
async function writeRemoteSkillsManifest(token: string, repoOwner: string, repoName: string, skills: SyncedSkill[]): Promise<boolean> {
const url = `https://api.github.com/repos/${repoOwner}/${repoName}/contents/${SKILLS_SYNC_MANIFEST_PATH}`
let sha = ''
const nextContent = JSON.stringify(skills, null, 2)
const existing = await fetch(url, {
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${token}`,
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'codex-web-local',
},
})
if (existing.ok) {
const payload = await existing.json() as { sha?: string; content?: string }
sha = payload.sha ?? ''
const currentContent = payload.content ? Buffer.from(payload.content.replace(/\n/g, ''), 'base64').toString('utf8') : ''
if (currentContent === nextContent) return false
}
const content = Buffer.from(nextContent, 'utf8').toString('base64')
await getGithubJson(url, token, 'PUT', {
message: 'Update synced skills manifest',
content,
...(sha ? { sha } : {}),
})
return true
}
function toGitHubTokenRemote(repoOwner: string, repoName: string, token: string): string {
return `https://x-access-token:${encodeURIComponent(token)}@github.com/${repoOwner}/${repoName}.git`
}
async function ensureSkillsWorkingTreeRepo(repoUrl: string, branch: string): Promise<string> {
const localDir = getSkillsInstallDir()
await mkdir(localDir, { recursive: true })
const gitDir = join(localDir, '.git')
let hasGitDir = false
try { hasGitDir = (await stat(gitDir)).isDirectory() } catch { hasGitDir = false }
if (!hasGitDir) {
await runCommand('git', ['init'], { cwd: localDir })
await runCommand('git', ['config', 'user.email', 'skills-sync@local'], { cwd: localDir })
await runCommand('git', ['config', 'user.name', 'Skills Sync'], { cwd: localDir })
await runCommand('git', ['add', '-A'], { cwd: localDir })
try { await runCommand('git', ['commit', '-m', 'Local skills snapshot before sync'], { cwd: localDir }) } catch {}
await runCommand('git', ['branch', '-M', branch], { cwd: localDir })
try { await runCommand('git', ['remote', 'add', 'origin', repoUrl], { cwd: localDir }) } catch {
await runCommand('git', ['remote', 'set-url', 'origin', repoUrl], { cwd: localDir })
}
await runGitFetchWithRefLockRetry(localDir)
try {
await runCommand('git', ['merge', '--allow-unrelated-histories', '--no-edit', `origin/${branch}`], { cwd: localDir })
} catch {}
return localDir
}
await runCommand('git', ['remote', 'set-url', 'origin', repoUrl], { cwd: localDir })
await runGitFetchWithRefLockRetry(localDir)
const hasLocalChangesBeforeSync = await hasLocalUncommittedChanges(localDir)
const localMtimesBeforeSync = hasLocalChangesBeforeSync ? await snapshotFileMtimes(localDir) : new Map<string, number>()
await resolveMergeConflictsByNewerCommit(localDir, branch, localMtimesBeforeSync)
try {
await runCommand('git', ['checkout', branch], { cwd: localDir })
} catch {
await resolveMergeConflictsByNewerCommit(localDir, branch, localMtimesBeforeSync)
await runCommand('git', ['checkout', '-B', branch], { cwd: localDir })
}
await resolveMergeConflictsByNewerCommit(localDir, branch, localMtimesBeforeSync)
const hasLocalChangesBeforePull = await hasLocalUncommittedChanges(localDir)
const localMtimesBeforePull = hasLocalChangesBeforePull ? await snapshotFileMtimes(localDir) : new Map<string, number>()
let createdAutostash = false
let autostashRef = ''
try {
const stashOutput = await runCommandWithOutput('git', ['stash', 'push', '--include-untracked', '-m', 'codex-skills-autostash'], { cwd: localDir })
createdAutostash = !stashOutput.includes('No local changes to save')
if (createdAutostash) {
autostashRef = (await runCommandWithOutput('git', ['rev-parse', 'stash@{0}'], { cwd: localDir })).trim()
}
} catch (error) {
if (hasLocalChangesBeforePull) {
throw new Error(`Refusing to reset skills repo because local changes could not be stashed first: ${getErrorMessage(error, 'git stash failed')}`)
}
}
let pulledMtimes = new Map<string, number>()
await runGitFetchWithRefLockRetry(localDir, ['fetch', 'origin', branch])
await runCommand('git', ['reset', '--hard', `origin/${branch}`], { cwd: localDir })
pulledMtimes = await snapshotFileMtimes(localDir)
if (createdAutostash) {
try {
await runCommand('git', ['stash', 'pop'], { cwd: localDir })
} catch {
await resolveStashPopConflictsByFileTime(localDir, localMtimesBeforePull, pulledMtimes)
if (autostashRef) {
await restoreMissingUntrackedFilesFromStash(localDir, autostashRef)
}
}
}
return localDir
}
async function resolveMergeConflictsByNewerCommit(
repoDir: string,
branch: string,
localMtimesBeforeSync: Map<string, number> = new Map<string, number>(),
): Promise<void> {
// Keep resolving until merge/rebase no longer reports unmerged paths.
for (let i = 0; i < 20; i++) {
const unmerged = (await runCommandWithOutput('git', ['diff', '--name-only', '--diff-filter=U'], { cwd: repoDir }))
.split(/\r?\n/)
.map((row) => row.trim())
.filter(Boolean)
if (unmerged.length === 0) return
for (const path of unmerged) {
const localMtimeMs = localMtimesBeforeSync.get(path) ?? 0
const localMtimeSec = Math.floor(localMtimeMs / 1000)
const remoteCommitTime = await getCommitTime(repoDir, `origin/${branch}`, path)
if (remoteCommitTime > localMtimeSec) {
await checkoutConflictSideWithFallback(repoDir, path, '--theirs')
} else {
await checkoutConflictSideWithFallback(repoDir, path, '--ours')
}
await runCommand('git', ['add', '--', path], { cwd: repoDir })
}
const rebaseHead = await readOptionalGitRef(repoDir, 'REBASE_HEAD')
if (rebaseHead) {
try {
await runCommand('git', ['rebase', '--continue'], { cwd: repoDir })
continue
} catch {
// Continue loop and resolve next rebase-conflict batch.
continue
}
}
const mergeHead = await readOptionalGitRef(repoDir, 'MERGE_HEAD')
if (mergeHead) {
await runCommand('git', ['commit', '-m', 'Auto-resolve skills merge by mtime policy'], { cwd: repoDir })
continue
}
}
throw new Error('Auto-resolve exceeded retry limit while reconciling sync conflicts')
}
async function readOptionalGitRef(repoDir: string, ref: string): Promise<string> {
try {
return (await runCommandWithOutput('git', ['rev-parse', '-q', '--verify', ref], { cwd: repoDir })).trim()
} catch {
return ''
}
}
async function listUnmergedStages(repoDir: string, path: string): Promise<Set<number>> {
const raw = (await runCommandWithOutput('git', ['ls-files', '-u', '--', path], { cwd: repoDir })).trim()
const stages = new Set<number>()
if (!raw) return stages