universal-plugin-hub 1.5.5 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/local.js CHANGED
@@ -1,15 +1,20 @@
1
1
  import { existsSync, readdirSync, statSync, cpSync, copyFileSync, mkdirSync, writeFileSync, mkdtempSync, readFileSync, createWriteStream, rmSync } from 'node:fs'
2
2
  import { join, basename, resolve, dirname, relative, isAbsolute } from 'node:path'
3
3
  import { fileURLToPath } from 'node:url'
4
- import { execFile } from 'node:child_process'
4
+ import { execFile, spawn } from 'node:child_process'
5
5
  import { promisify } from 'node:util'
6
6
  import { load as parseYaml } from 'js-yaml'
7
7
  import { sourceCacheDir, readState, writeState, safeRmDir, slugify } from './store.js'
8
8
  import { safeSegment, pluginPath } from './market.js'
9
- import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache, invalidateParserCaches, formatDisplayName, normalizeVersion, MARKETPLACE_COMPONENT_KEYS } from './parser.js'
9
+ import {
10
+ parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest,
11
+ invalidateMarketplaceCache, invalidateParserCaches, readMarketplace, resolveMarketplacePluginDir,
12
+ formatDisplayName, normalizeVersion, MARKETPLACE_COMPONENT_KEYS,
13
+ } from './parser.js'
10
14
  import { installUploadedSkills, takenSkillNames } from './skill-uploads.js'
11
15
  import { invalidateLocalIconCache } from './icons.js'
12
- import { refreshInstalledPluginsFromSource } from './install.js'
16
+ import { invalidateAtPluginsCache } from './at-plugins.js'
17
+ import { refreshInstalledPluginsFromSource, withPluginLock, withSourceLock, removeManagedDirAsync, replaceManagedDirAsync } from './install.js'
13
18
 
14
19
  const execFileAsync = promisify(execFile)
15
20
 
@@ -41,12 +46,92 @@ function sweepTemp() {
41
46
  } catch {}
42
47
  }
43
48
 
49
+ function mapProgressRange(onProgress, startPct, endPct) {
50
+ if (typeof onProgress !== 'function') return null
51
+ return (evt) => {
52
+ const raw = Math.max(0, Math.min(100, Number(evt?.percent) || 0))
53
+ const scaled = Math.round(startPct + (raw / 100) * (endPct - startPct))
54
+ onProgress({ ...evt, percent: scaled })
55
+ }
56
+ }
57
+
44
58
  /** Native archive extraction (Windows bsdtar also handles ZIP). */
45
- export async function extractZip(zipPath, destDir) {
59
+ export async function extractZip(zipPath, destDir, onProgress = null) {
46
60
  sweepTemp()
47
61
  mkdirSync(destDir, { recursive: true })
48
62
  const tar = process.platform === 'win32' ? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe') : 'tar'
49
- await execFileAsync(tar, ['-xf', zipPath, '-C', destDir], { windowsHide: true })
63
+ if (typeof onProgress !== 'function') {
64
+ await execFileAsync(tar, ['-xf', zipPath, '-C', destDir], { windowsHide: true })
65
+ return
66
+ }
67
+
68
+ let totalEntries = 0
69
+ try {
70
+ const { stdout } = await execFileAsync(tar, ['-tf', zipPath], { windowsHide: true, maxBuffer: 64 * 1024 * 1024 })
71
+ totalEntries = String(stdout || '').split(/\r?\n/).filter((l) => l.trim()).length
72
+ } catch {}
73
+ onProgress({ extracted: 0, totalEntries, ratio: 0 })
74
+
75
+ await new Promise((resolve, reject) => {
76
+ const child = spawn(tar, ['-xvf', zipPath, '-C', destDir], { windowsHide: true })
77
+ let extracted = 0
78
+ let lastEmit = 0
79
+ let stdoutBuf = ''
80
+ let stderrBuf = ''
81
+ const stderrLines = []
82
+
83
+ const emit = (force = false) => {
84
+ const now = Date.now()
85
+ if (!force && now - lastEmit < 40) return
86
+ lastEmit = now
87
+ const capped = totalEntries > 0 ? Math.min(extracted, totalEntries) : extracted
88
+ const ratio = totalEntries > 0 ? Math.min(1, capped / totalEntries) : 0
89
+ onProgress({ extracted: capped, totalEntries, ratio })
90
+ }
91
+
92
+ const consume = (chunk, bufName, isErr) => {
93
+ const next = (bufName === 'out' ? stdoutBuf : stderrBuf) + String(chunk)
94
+ const parts = next.split(/\r?\n/)
95
+ const tail = parts.pop() ?? ''
96
+ if (bufName === 'out') stdoutBuf = tail
97
+ else stderrBuf = tail
98
+
99
+ let added = false
100
+ for (const line of parts) {
101
+ const trimmed = line.trim()
102
+ if (!trimmed) continue
103
+ extracted += 1
104
+ added = true
105
+ if (isErr) {
106
+ stderrLines.push(trimmed)
107
+ if (stderrLines.length > 20) stderrLines.shift()
108
+ }
109
+ }
110
+ if (added) emit(false)
111
+ }
112
+
113
+ child.stdout?.on('data', (d) => consume(d, 'out', false))
114
+ child.stderr?.on('data', (d) => consume(d, 'err', true))
115
+ child.on('error', reject)
116
+ child.on('close', (code) => {
117
+ for (const [tail, isErr] of [[stdoutBuf, false], [stderrBuf, true]]) {
118
+ const trimmed = tail.trim()
119
+ if (trimmed) {
120
+ extracted += 1
121
+ if (isErr) {
122
+ stderrLines.push(trimmed)
123
+ if (stderrLines.length > 20) stderrLines.shift()
124
+ }
125
+ }
126
+ }
127
+ if (code === 0) {
128
+ onProgress({ extracted: totalEntries || extracted, totalEntries, ratio: 1 })
129
+ resolve()
130
+ } else {
131
+ reject(new Error(stderrLines.slice(-4).join(' | ') || `tar exited with code ${code}`))
132
+ }
133
+ })
134
+ })
50
135
  }
51
136
 
52
137
  export const MAX_UPLOAD_BYTES = 500 * 1024 * 1024
@@ -313,7 +398,7 @@ function marketSourceName(dir, fallbackName) {
313
398
  return formatDisplayName(fallbackName) || '本地市场'
314
399
  }
315
400
 
316
- export async function inspectLocalPlugin(rawPath) {
401
+ export async function inspectLocalPlugin(rawPath, { onProgress } = {}) {
317
402
  let targetPath = String(rawPath || '').trim().replace(/^["']|["']$/g, '')
318
403
  if (/^file:/i.test(targetPath)) targetPath = fileURLToPath(targetPath)
319
404
  if (!existsSync(targetPath)) {
@@ -328,7 +413,15 @@ export async function inspectLocalPlugin(rawPath) {
328
413
  mkdirSync(TEMP_ROOT(), { recursive: true })
329
414
  tempExtractDir = mkdtempSync(join(TEMP_ROOT(), 'inspect-'))
330
415
  try {
331
- await extractZip(targetPath, tempExtractDir)
416
+ await extractZip(targetPath, tempExtractDir, typeof onProgress === 'function' ? (p) => {
417
+ onProgress({
418
+ stage: 'extracting',
419
+ extracted: p.extracted,
420
+ totalEntries: p.totalEntries,
421
+ percent: Math.round((p.ratio || 0) * 80),
422
+ detail: p.totalEntries > 0 ? `正在解压 ${p.extracted} / ${p.totalEntries} 个文件` : `已解压 ${p.extracted} 个文件`,
423
+ })
424
+ } : null)
332
425
  inspectDir = tempExtractDir
333
426
  } catch (e) {
334
427
  if (tempExtractDir) safeRmDir(tempExtractDir)
@@ -396,6 +489,7 @@ export async function inspectLocalPlugin(rawPath) {
396
489
  const skills = entries.flatMap((e) => listSkills(e.dir))
397
490
  const agents = entries.flatMap((e) => listAgents(e.dir))
398
491
 
492
+ onProgress?.({ stage: 'analyzing', percent: 88, detail: '正在识别插件清单与冲突…' })
399
493
  const localConflicts = kind === 'skills' ? [] : collectLocalConflicts(entries)
400
494
  const suggestedLabel = kind === 'marketplace' ? marketSourceName(effectiveDir, fallbackName) : ''
401
495
  let exists = false
@@ -434,6 +528,7 @@ export async function inspectLocalPlugin(rawPath) {
434
528
  existingUpdatedAt = localConflicts[0].existingUpdatedAt
435
529
  }
436
530
 
531
+ onProgress?.({ stage: 'analyzing', percent: 95, detail: '正在整理预览信息…' })
437
532
  return {
438
533
  ok: true,
439
534
  kind,
@@ -487,16 +582,18 @@ function collectLocalConflicts(entries) {
487
582
  * Pure skill packages go straight into the Skills tab instead of the plugin
488
583
  * install pipeline: no mirrored copy, no agents/commands conversion.
489
584
  */
490
- export async function importLocalSkills(rawPath, { overwrite = false, overwriteNames = null } = {}) {
491
- const inspectRes = await inspectLocalPlugin(rawPath)
585
+ export async function importLocalSkills(rawPath, { overwrite = false, overwriteNames = null, onProgress = null } = {}) {
586
+ const inspectRes = await inspectLocalPlugin(rawPath, { onProgress: mapProgressRange(onProgress, 0, 70) })
492
587
  if (!inspectRes.ok) throw new Error(inspectRes.error)
493
588
  if (inspectRes.kind !== 'skills') throw new Error('该内容不是纯 Skills 包')
494
589
  const { tempExtractDir, entries, singleFile } = inspectRes
495
590
  try {
591
+ onProgress?.({ stage: 'copying', percent: 82, detail: '正在安装 Skill 到工作区…' })
496
592
  // A bare SKILL.md upload is one flat skill. When the folder it came from is
497
593
  // a collection, the walk up yields several entries, and flattening those
498
594
  // would drop each skill's assets along with its directory.
499
595
  const installed = installUploadedSkills(entries, { overwrite, overwriteNames, singleFile: singleFile && entries.length === 1 })
596
+ onProgress?.({ stage: 'copying', percent: 96, detail: 'Skill 安装完成' })
500
597
  return { ok: true, sourceId: 'skills-local', skills: installed, kind: 'skills' }
501
598
  } finally {
502
599
  if (tempExtractDir) safeRmDir(tempExtractDir)
@@ -561,7 +658,7 @@ function syncPluginManifestMetadata(destDir, row, { stripRootMarketplace = false
561
658
  writeFileSync(out, JSON.stringify(fields, null, 2), 'utf8')
562
659
  }
563
660
 
564
- async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtractDir = null, stripRootMarketplace = false } = {}) {
661
+ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtractDir = null, stripRootMarketplace = false, onProgress = null } = {}) {
565
662
  const localDir = sourceCacheDir('local')
566
663
  mkdirSync(localDir, { recursive: true })
567
664
  const clashing = []
@@ -582,17 +679,22 @@ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtract
582
679
  }
583
680
  const importedNames = []
584
681
  try {
585
- for (const { row, dir } of entries) {
682
+ for (let i = 0; i < entries.length; i++) {
683
+ const { row, dir } = entries[i]
586
684
  const cleanName = safeSegment(row.name, 'plugin name')
587
685
  const destDir = join(localDir, cleanName)
588
686
  if (resolve(destDir) !== resolve(dir)) {
589
- safeRmDir(destDir)
590
- cpSync(dir, destDir, { recursive: true, force: true })
687
+ await replaceManagedDirAsync(dir, destDir, undefined, false, { deferCleanup: true, inPlaceFallback: true })
591
688
  }
592
689
  if (stripRootMarketplace) {
593
690
  syncPluginManifestMetadata(destDir, row, { stripRootMarketplace: true })
594
691
  }
595
692
  importedNames.push(cleanName)
693
+ onProgress?.({
694
+ stage: 'copying',
695
+ percent: 55 + Math.round(((i + 1) / entries.length) * 25),
696
+ detail: `正在写入本地插件 (${i + 1} / ${entries.length})`,
697
+ })
596
698
  }
597
699
  } finally {
598
700
  if (tempExtractDir) safeRmDir(tempExtractDir)
@@ -600,10 +702,13 @@ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtract
600
702
  invalidateMarketplaceCache('local')
601
703
  invalidateParserCaches()
602
704
  invalidateLocalIconCache('local')
705
+ let refreshed = []
603
706
  if (overwrite && importedNames.length > 0) {
604
- await refreshInstalledPluginsFromSource('local', importedNames)
707
+ onProgress?.({ stage: 'refreshing', percent: 85, detail: '正在更新已安装副本…' })
708
+ refreshed = await refreshInstalledPluginsFromSource('local', importedNames)
709
+ onProgress?.({ stage: 'refreshing', percent: 96, detail: '已安装副本更新完成' })
605
710
  }
606
- return importedNames
711
+ return { importedNames, refreshed }
607
712
  }
608
713
 
609
714
  /**
@@ -612,8 +717,8 @@ async function copyEntriesToLocalCache(entries, { overwrite = false, tempExtract
612
717
  * without writing a root marketplace.json; otherwise plugins keep their manifest
613
718
  * layout inside `market/local-<slug>/` as an independent tab.
614
719
  */
615
- export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false, target = '' } = {}) {
616
- const inspectRes = await inspectLocalPlugin(rawPath)
720
+ export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false, target = '', onProgress = null } = {}) {
721
+ const inspectRes = await inspectLocalPlugin(rawPath, { onProgress: mapProgressRange(onProgress, 0, 55) })
617
722
  if (!inspectRes.ok) throw new Error(inspectRes.error)
618
723
  if (inspectRes.kind !== 'marketplace') throw new Error('该内容不是插件市场')
619
724
  const { effectiveDir, tempExtractDir, entries } = inspectRes
@@ -625,7 +730,7 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
625
730
  if (tempExtractDir) safeRmDir(tempExtractDir)
626
731
  throw new Error('尚未创建本地插件标签,请先上传单个本地插件或将其作为独立标签页添加')
627
732
  }
628
- await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: true })
733
+ const { refreshed } = await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: true, onProgress })
629
734
  return {
630
735
  ok: true,
631
736
  kind: 'marketplace',
@@ -633,6 +738,7 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
633
738
  sourceId: 'local',
634
739
  source: localSource,
635
740
  plugins: entries.map((entry) => entry.row),
741
+ refreshed,
636
742
  }
637
743
  }
638
744
 
@@ -661,7 +767,8 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
661
767
  try {
662
768
  safeRmDir(dest)
663
769
  mkdirSync(dest, { recursive: true })
664
- for (const { row, dir } of entries) {
770
+ for (let i = 0; i < entries.length; i++) {
771
+ const { row, dir } = entries[i]
665
772
  // Keep each plugin on the path its manifest declares: a rewritten layout
666
773
  // (`plugins/<name>`) would break `./external_plugins/x` and `./`, and the
667
774
  // reader resolves sources against the copied manifest after a restart.
@@ -669,6 +776,11 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
669
776
  mkdirSync(dirname(targetDir), { recursive: true })
670
777
  if (resolve(targetDir) !== resolve(dest)) cpSync(dir, targetDir, { recursive: true, force: true })
671
778
  else copyTreeContents(dir, targetDir)
779
+ onProgress?.({
780
+ stage: 'copying',
781
+ percent: 55 + Math.round(((i + 1) / entries.length) * 25),
782
+ detail: `正在写入插件市场 (${i + 1} / ${entries.length})`,
783
+ })
672
784
  }
673
785
  // Carry the marketplace manifest itself so the standard reader finds the
674
786
  // same rows on the next start, not only during this upload.
@@ -697,15 +809,18 @@ export async function importLocalMarketplace(rawPath, { sourceName = '', overwri
697
809
  invalidateMarketplaceCache(sourceId)
698
810
  invalidateParserCaches()
699
811
  invalidateLocalIconCache(sourceId)
812
+ let refreshed = []
700
813
  if (overwrite) {
701
- await refreshInstalledPluginsFromSource(sourceId, entries.map((entry) => entry.row.name))
814
+ onProgress?.({ stage: 'refreshing', percent: 85, detail: '正在更新已安装副本…' })
815
+ refreshed = await refreshInstalledPluginsFromSource(sourceId, entries.map((entry) => entry.row.name))
816
+ onProgress?.({ stage: 'refreshing', percent: 96, detail: '已安装副本更新完成' })
702
817
  }
703
- return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row) }
818
+ return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row), refreshed }
704
819
  }
705
820
 
706
821
  /** Legacy plugin-pipeline import; the UI routes pure skill packages elsewhere. */
707
- export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '' }) {
708
- const inspectRes = await inspectLocalPlugin(rawPath)
822
+ export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '', onProgress = null }) {
823
+ const inspectRes = await inspectLocalPlugin(rawPath, { onProgress: mapProgressRange(onProgress, 0, 55) })
709
824
  if (!inspectRes.ok) {
710
825
  throw new Error(inspectRes.error)
711
826
  }
@@ -718,7 +833,7 @@ export async function importLocalPlugin({ path: rawPath, overwrite = false, sour
718
833
  throw new Error(`已存在同名插件「${cleanPluginName}」`)
719
834
  }
720
835
 
721
- await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: false })
836
+ const { refreshed } = await copyEntriesToLocalCache(entries, { overwrite, tempExtractDir, stripRootMarketplace: false, onProgress })
722
837
 
723
838
  // The tab is named once, on the first import. Later imports land in that
724
839
  // same tab: re-applying a name here would silently rename a tab the user
@@ -742,6 +857,7 @@ export async function importLocalPlugin({ path: rawPath, overwrite = false, sour
742
857
  sourceId: 'local',
743
858
  plugin,
744
859
  plugins: entries.map((e) => e.row),
860
+ refreshed,
745
861
  }
746
862
  }
747
863
 
@@ -795,3 +911,71 @@ export function removeDuplicateLocalMarketTabs() {
795
911
  for (const id of ids) invalidateMarketplaceCache(id)
796
912
  return { removed: ids }
797
913
  }
914
+
915
+ /**
916
+ * Permanently delete an uninstalled plugin from the `local` (`Local Plugins`)
917
+ * source cache. Refuses when the plugin is still installed (409) or missing
918
+ * (404). When the deleted item was the last plugin in `local` and no installed
919
+ * `local` plugin remains, automatically removes the empty `local` tab and cache.
920
+ */
921
+ export async function deleteLocalPlugin(pluginName, { hasActiveStagedUploads, cleanupStagedUploads } = {}) {
922
+ const cleanName = safeSegment(pluginName, 'plugin name')
923
+ return withPluginLock(cleanName, () => withSourceLock('local', async () => {
924
+ const state = readState()
925
+ const cleanLower = cleanName.toLowerCase()
926
+ if ((state.plugins || []).some((p) => p && typeof p.name === 'string' && p.name.toLowerCase() === cleanLower)) {
927
+ const error = new Error('该插件当前已安装,请先卸载后再从本地列表删除')
928
+ error.status = 409
929
+ throw error
930
+ }
931
+
932
+ const localDir = sourceCacheDir('local')
933
+ let targetDir = resolveMarketplacePluginDir('local', cleanName)
934
+ if (!targetDir) {
935
+ const direct = join(localDir, cleanName)
936
+ if (existsSync(direct)) {
937
+ try {
938
+ if (statSync(direct).isDirectory()) targetDir = direct
939
+ } catch {}
940
+ }
941
+ }
942
+ if (!targetDir || !existsSync(targetDir) || !containsPath(localDir, targetDir) || resolve(targetDir) === resolve(localDir)) {
943
+ const error = new Error('本地插件不存在')
944
+ error.status = 404
945
+ throw error
946
+ }
947
+
948
+ await removeManagedDirAsync(targetDir, { allowTrash: false })
949
+ invalidateMarketplaceCache('local')
950
+ invalidateParserCaches()
951
+ invalidateLocalIconCache('local')
952
+ invalidateAtPluginsCache()
953
+
954
+ const remaining = readMarketplace('local')
955
+ const latestState = readState()
956
+ const hasInstalledLocal = (latestState.plugins || []).some((p) => p && p.sourceId === 'local')
957
+ if (remaining.length === 0 && !hasInstalledLocal) {
958
+ if (hasActiveStagedUploads?.()) {
959
+ for (const entry of readdirSync(localDir)) {
960
+ if (entry === '.temp') continue
961
+ await removeManagedDirAsync(join(localDir, entry), { allowTrash: false })
962
+ }
963
+ } else {
964
+ cleanupStagedUploads?.()
965
+ await removeManagedDirAsync(localDir, { allowTrash: false })
966
+ }
967
+ latestState.sources = (latestState.sources || []).filter((s) => s && s.id !== 'local')
968
+ if (Array.isArray(latestState.tabOrder)) {
969
+ latestState.tabOrder = latestState.tabOrder.filter((id) => id !== 'local')
970
+ }
971
+ writeState(latestState)
972
+ invalidateMarketplaceCache('local')
973
+ invalidateParserCaches()
974
+ invalidateLocalIconCache('local')
975
+ invalidateAtPluginsCache()
976
+ return { ok: true, pluginName: cleanName, sourceId: 'local', remainingCount: 0, sourceRemoved: true, plugins: [] }
977
+ }
978
+
979
+ return { ok: true, pluginName: cleanName, sourceId: 'local', remainingCount: remaining.length, sourceRemoved: false, plugins: remaining }
980
+ }))
981
+ }
package/src/parser.js CHANGED
@@ -1417,19 +1417,57 @@ export function listPrompts(dir, manifest = readPluginManifest(dir)) {
1417
1417
  return [...new Set(prompts)]
1418
1418
  }
1419
1419
 
1420
+ const CANONICAL_HOOK_EVENTS = {
1421
+ sessionstart: 'SessionStart',
1422
+ sessionend: 'SessionEnd',
1423
+ userpromptsubmit: 'UserPromptSubmit',
1424
+ pretooluse: 'PreToolUse',
1425
+ posttooluse: 'PostToolUse',
1426
+ posttoolusefailure: 'PostToolUseFailure',
1427
+ permissionrequest: 'PermissionRequest',
1428
+ stop: 'Stop',
1429
+ stopfailure: 'StopFailure',
1430
+ subagentstart: 'SubagentStart',
1431
+ subagentstop: 'SubagentStop',
1432
+ precompact: 'PreCompact',
1433
+ postcompact: 'PostCompact',
1434
+ cwdchanged: 'CwdChanged',
1435
+ notification: 'Notification',
1436
+ }
1437
+
1438
+ export function canonicalizeHookEventName(evt) {
1439
+ if (typeof evt !== 'string') return ''
1440
+ const trimmed = evt.trim()
1441
+ if (!trimmed) return ''
1442
+ const key = trimmed.replace(/[\s_-]+/g, '').toLowerCase()
1443
+ return CANONICAL_HOOK_EVENTS[key] || trimmed
1444
+ }
1445
+
1446
+ function isExistingFile(filePath) {
1447
+ try {
1448
+ return statSync(filePath).isFile()
1449
+ } catch {
1450
+ return false
1451
+ }
1452
+ }
1453
+
1420
1454
  function formatHookEventName(evt) {
1455
+ const canonical = canonicalizeHookEventName(evt)
1421
1456
  const map = {
1422
1457
  'PreToolUse': 'Pre-tool use',
1423
1458
  'PostToolUse': 'Post-tool use',
1459
+ 'PostToolUseFailure': 'Post-tool use failure',
1460
+ 'PermissionRequest': 'Permission request',
1461
+ 'UserPromptSubmit': 'User prompt submit',
1424
1462
  'PreCompact': 'Pre-compact',
1425
1463
  'PostCompact': 'Post-compact',
1426
- 'SessionStart': 'SessionStart',
1427
- 'SessionEnd': 'SessionEnd',
1428
- 'Stop': 'Stop',
1429
- 'PostToolUseFailure': 'PostToolUseFailure',
1430
- 'Notification': 'Notification',
1464
+ 'SessionEnd': 'Session end',
1465
+ 'StopFailure': 'Stop failure',
1466
+ 'SubagentStart': 'Subagent start',
1467
+ 'SubagentStop': 'Subagent stop',
1468
+ 'CwdChanged': 'Cwd changed',
1431
1469
  }
1432
- return map[evt] || evt
1470
+ return map[canonical] || canonical
1433
1471
  }
1434
1472
 
1435
1473
  function extractHookEventMap(raw, isJson) {
@@ -1581,28 +1619,49 @@ function formatHookCmdArg(arg) {
1581
1619
  return /[\s"'\\$`]/.test(arg) ? JSON.stringify(arg) : arg
1582
1620
  }
1583
1621
 
1622
+ const CODEX_ENV_VAR_RE = /(?<![A-Z0-9_])(?:PLUGIN_ROOT|PLUGIN_DATA)\b/
1623
+
1624
+ function valueReferencesCodexEnvVars(val) {
1625
+ if (typeof val === 'string') return CODEX_ENV_VAR_RE.test(val)
1626
+ if (Array.isArray(val)) return val.some(valueReferencesCodexEnvVars)
1627
+ if (val && typeof val === 'object') return Object.values(val).some(valueReferencesCodexEnvVars)
1628
+ return false
1629
+ }
1630
+
1584
1631
  /**
1585
1632
  * Compile all Claude/Codex hook sources (JSON, YAML, inline objects, mixed arrays,
1586
- * `args` arrays, and builtin variables) into a single JSON structure compatible
1587
- * with `@deepseek-ai/dsh-hooks-claude-code`. Returns null if no hook rules exist.
1633
+ * `args` arrays, and builtin variables) into a single normalized JSON structure
1634
+ * consumed by the native Cordis hook runtime (`src/hooks.js`).
1635
+ * Returns null if no hook rules exist.
1588
1636
  */
1589
1637
  export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(pluginRoot), explicitDataDir) {
1590
1638
  const compiled = {}
1591
1639
  const eventMaps = []
1640
+ const sources = collectHookSources(pluginRoot, manifest)
1641
+ let rawUsesCodexVars = false
1592
1642
 
1593
- for (const src of collectHookSources(pluginRoot, manifest)) {
1643
+ for (const src of sources) {
1594
1644
  if (src.type === 'file') {
1595
1645
  try {
1596
- const map = extractHookEventMap(readFileSync(src.path, 'utf8'), src.isJson)
1597
- if (map) eventMaps.push(map)
1646
+ const rawText = readFileSync(src.path, 'utf8')
1647
+ const map = extractHookEventMap(rawText, src.isJson)
1648
+ if (map) {
1649
+ eventMaps.push(map)
1650
+ // Inspect raw hook definition before expandPluginVars removes variable tokens.
1651
+ if (CODEX_ENV_VAR_RE.test(rawText)) rawUsesCodexVars = true
1652
+ }
1598
1653
  } catch {}
1599
1654
  } else if (src.type === 'inline') {
1600
1655
  eventMaps.push(src.eventMap)
1656
+ // Inspect raw inline definition before expandPluginVars removes variable tokens.
1657
+ if (valueReferencesCodexEnvVars(src.eventMap)) rawUsesCodexVars = true
1601
1658
  }
1602
1659
  }
1603
1660
 
1604
1661
  for (const eventMap of eventMaps) {
1605
- for (const [eventName, val] of Object.entries(eventMap)) {
1662
+ for (const [rawEventName, val] of Object.entries(eventMap)) {
1663
+ const eventName = canonicalizeHookEventName(rawEventName)
1664
+ if (!eventName) continue
1606
1665
  const rules = Array.isArray(val) ? val : (val && typeof val === 'object' ? [val] : [])
1607
1666
  for (const rule of rules) {
1608
1667
  if (!rule || typeof rule !== 'object') continue
@@ -1611,24 +1670,43 @@ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(p
1611
1670
  for (const h of rawInner) {
1612
1671
  if (!h || typeof h !== 'object') continue
1613
1672
  if (h.type === undefined || h.type === 'command') {
1673
+ const hasArgs = Array.isArray(h.args) && h.args.length > 0
1614
1674
  let cmd = typeof h.command === 'string' ? expandPluginVars(h.command, pluginRoot, explicitDataDir).trim() : ''
1615
1675
  if (pluginRoot && /^\.\.?[\\/]/.test(cmd)) {
1616
- const m = cmd.match(/^(\S+)([\s\S]*)$/)
1617
- if (m) {
1618
- const resolvedBin = resolvePluginCommand(m[1], pluginRoot, explicitDataDir)
1619
- cmd = resolvedBin ? `${resolvedBin}${m[2]}` : ''
1676
+ if (hasArgs && !h.shell && isExistingFile(resolve(pluginRoot, cmd))) {
1677
+ cmd = resolvePluginCommand(cmd, pluginRoot, explicitDataDir) || ''
1678
+ } else {
1679
+ const m = cmd.match(/^(\S+)([\s\S]*)$/)
1680
+ if (m) {
1681
+ const resolvedBin = resolvePluginCommand(m[1], pluginRoot, explicitDataDir)
1682
+ cmd = resolvedBin ? `${resolvedBin}${m[2]}` : ''
1683
+ }
1620
1684
  }
1621
1685
  }
1622
- if (Array.isArray(h.args) && h.args.length > 0) {
1623
- const extraArgs = h.args.map((a) => {
1624
- const expanded = expandPluginVars(String(a), pluginRoot, explicitDataDir)
1625
- return formatHookCmdArg(expanded)
1626
- })
1627
- cmd = [cmd, ...extraArgs].filter(Boolean).join(' ')
1628
- }
1629
1686
  if (!cmd) continue
1687
+ let preservedArgs
1688
+ if (hasArgs) {
1689
+ const expandedArgs = h.args.map((a) => expandPluginVars(String(a), pluginRoot, explicitDataDir))
1690
+ const relInPlugin = Boolean(pluginRoot && !isAbsolute(cmd) && /[\\/]/.test(cmd) && isExistingFile(resolve(pluginRoot, cmd)))
1691
+ const isExecForm = !h.shell && (!/\s/.test(cmd) || (isAbsolute(cmd) && isExistingFile(cmd)) || relInPlugin)
1692
+ if (isExecForm) {
1693
+ if (relInPlugin) {
1694
+ cmd = resolvePluginCommand(/^\.\.?[\\/]/.test(cmd) ? cmd : `./${cmd}`, pluginRoot, explicitDataDir) || ''
1695
+ if (!cmd) continue
1696
+ }
1697
+ preservedArgs = expandedArgs
1698
+ } else {
1699
+ cmd = [cmd, ...expandedArgs.map(formatHookCmdArg)].filter(Boolean).join(' ')
1700
+ }
1701
+ }
1630
1702
  const { args: _droppedArgs, ...rest } = h
1631
- compiledInner.push({ ...rest, type: 'command', command: cmd })
1703
+ const normalizedEntry = {
1704
+ ...expandPluginVars(rest, pluginRoot, explicitDataDir),
1705
+ type: 'command',
1706
+ command: cmd,
1707
+ ...(preservedArgs !== undefined ? { args: preservedArgs } : {}),
1708
+ }
1709
+ compiledInner.push(normalizedEntry)
1632
1710
  } else {
1633
1711
  compiledInner.push(expandPluginVars(h, pluginRoot, explicitDataDir))
1634
1712
  }
@@ -1637,6 +1715,7 @@ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(p
1637
1715
  if (!compiled[eventName]) compiled[eventName] = []
1638
1716
  compiled[eventName].push({
1639
1717
  ...(rule.matcher !== undefined ? { matcher: rule.matcher } : {}),
1718
+ ...(rule.if !== undefined ? { if: rule.if } : {}),
1640
1719
  hooks: compiledInner,
1641
1720
  })
1642
1721
  }
@@ -1644,7 +1723,22 @@ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(p
1644
1723
  }
1645
1724
  }
1646
1725
 
1647
- return Object.keys(compiled).length > 0 ? { hooks: compiled } : null
1726
+ if (Object.keys(compiled).length === 0) return null
1727
+
1728
+ const hasClaudeManifest = Boolean(pluginRoot && existsSync(join(pluginRoot, '.claude-plugin', 'plugin.json')))
1729
+ const hasCodexManifest = Boolean(pluginRoot && existsSync(join(pluginRoot, '.codex-plugin', 'plugin.json')))
1730
+ const hasCodexHookFile = sources.some((src) => src.type === 'file' && /codex/i.test(basename(src.path)))
1731
+ const dialect = (!hasClaudeManifest && (hasCodexManifest || hasCodexHookFile)) ? 'codex' : 'claude-code'
1732
+ const usesCodexEnvVars = dialect === 'codex' || rawUsesCodexVars
1733
+ const resolvedDataDir = pluginDataDirForRoot(pluginRoot, explicitDataDir)
1734
+
1735
+ return {
1736
+ hooks: compiled,
1737
+ pluginRoot: pluginRoot ? resolve(pluginRoot) : '',
1738
+ pluginData: resolvedDataDir ? resolve(resolvedDataDir) : '',
1739
+ dialect,
1740
+ usesCodexEnvVars,
1741
+ }
1648
1742
  }
1649
1743
 
1650
1744
  /**