@apexhub/apex-ui-skill 0.0.0-stage → 1.2.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.
@@ -0,0 +1,229 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Apex UI Skill 使用上报(安装与活跃共用)。
4
+ *
5
+ * 用法:
6
+ * node report-usage.mjs active # 本地 AI 开始使用时执行
7
+ * node report-usage.mjs install --version 1.0.2 --targets claude,agents [--result partial]
8
+ *
9
+ * 行为:
10
+ * - 客户端 ID 存于用户目录 ~/.apex-ui/client-id(多项目、多工具共用;排他创建处理并发)。
11
+ * - 活跃事件同日只发送一次(usage-state.json 缓存北京时间日期);安装事件不受该缓存限制。
12
+ * - 默认关闭;仅显式设置有效的 APEX_UI_USAGE_ENDPOINT 时上报并创建客户端 ID。
13
+ * - APEX_UI_TELEMETRY_DISABLED=1、state enabled=false、CI 环境直接退出,不创建 ID。
14
+ * - 单次网络等待约 1 秒;失败不影响主流程、不后台重试。始终 exit 0。
15
+ */
16
+
17
+ import { randomUUID } from 'node:crypto'
18
+ import {
19
+ closeSync,
20
+ existsSync,
21
+ mkdirSync,
22
+ openSync,
23
+ readFileSync,
24
+ realpathSync,
25
+ writeFileSync,
26
+ } from 'node:fs'
27
+ import { homedir } from 'node:os'
28
+ import { dirname, join } from 'node:path'
29
+ import { fileURLToPath } from 'node:url'
30
+
31
+ const NETWORK_TIMEOUT_MS = 1000
32
+ const STATE_DIR = join(homedir(), '.apex-ui')
33
+ const CLIENT_ID_FILE = join(STATE_DIR, 'client-id')
34
+ const STATE_FILE = join(STATE_DIR, 'usage-state.json')
35
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
36
+
37
+ function isCi() {
38
+ return Boolean(process.env.CI || process.env.GITLAB_CI || process.env.GITHUB_ACTIONS)
39
+ }
40
+
41
+ function shanghaiToday() {
42
+ const parts = new Intl.DateTimeFormat('en-CA', {
43
+ timeZone: 'Asia/Shanghai',
44
+ year: 'numeric',
45
+ month: '2-digit',
46
+ day: '2-digit',
47
+ }).formatToParts(new Date())
48
+ const get = (t) => parts.find((p) => p.type === t)?.value ?? ''
49
+ return `${get('year')}-${get('month')}-${get('day')}`
50
+ }
51
+
52
+ function readState() {
53
+ try {
54
+ const raw = JSON.parse(readFileSync(STATE_FILE, 'utf8'))
55
+ return typeof raw === 'object' && raw !== null ? raw : {}
56
+ } catch {
57
+ return {}
58
+ }
59
+ }
60
+
61
+ function writeState(patch) {
62
+ try {
63
+ mkdirSync(STATE_DIR, { recursive: true })
64
+ writeFileSync(STATE_FILE, JSON.stringify({ ...readState(), ...patch }))
65
+ } catch {
66
+ // 状态文件丢失可重建;服务端每日唯一索引兜底
67
+ }
68
+ }
69
+
70
+ /** 读取或排他创建客户端 ID;无法安全读写时返回 null(跳过上报) */
71
+ function getClientId() {
72
+ try {
73
+ if (existsSync(CLIENT_ID_FILE)) {
74
+ const id = readFileSync(CLIENT_ID_FILE, 'utf8').trim()
75
+ if (UUID_RE.test(id)) return id
76
+ }
77
+ mkdirSync(STATE_DIR, { recursive: true })
78
+ const id = randomUUID()
79
+ // wx:排他创建,多进程并发时只有一个成功,其余读取已存在的值
80
+ const fd = openSync(CLIENT_ID_FILE, 'wx')
81
+ try {
82
+ writeFileSync(fd, id)
83
+ } finally {
84
+ closeSync(fd)
85
+ }
86
+ return id
87
+ } catch (err) {
88
+ if (err && err.code === 'EEXIST') {
89
+ try {
90
+ const id = readFileSync(CLIENT_ID_FILE, 'utf8').trim()
91
+ if (UUID_RE.test(id)) return id
92
+ } catch {
93
+ // fallthrough
94
+ }
95
+ }
96
+ return null
97
+ }
98
+ }
99
+
100
+ function resolveEndpoint() {
101
+ const configured = process.env.APEX_UI_USAGE_ENDPOINT
102
+ if (!configured) return null
103
+ try {
104
+ const url = new URL(configured)
105
+ if (
106
+ !['http:', 'https:'].includes(url.protocol) ||
107
+ url.username ||
108
+ url.password ||
109
+ url.search ||
110
+ url.hash
111
+ ) {
112
+ return null
113
+ }
114
+ return url.toString().replace(/\/+$/, '')
115
+ } catch {
116
+ return null
117
+ }
118
+ }
119
+
120
+ async function postEvent(endpoint, event) {
121
+ const controller = new AbortController()
122
+ const timer = setTimeout(() => controller.abort(), NETWORK_TIMEOUT_MS)
123
+ try {
124
+ await fetch(`${endpoint}/api/usage/events`, {
125
+ method: 'POST',
126
+ headers: { 'content-type': 'application/json' },
127
+ body: JSON.stringify(event),
128
+ signal: controller.signal,
129
+ })
130
+ return true
131
+ } catch {
132
+ return false
133
+ } finally {
134
+ clearTimeout(timer)
135
+ }
136
+ }
137
+
138
+ function telemetryDisabled(state) {
139
+ return process.env.APEX_UI_TELEMETRY_DISABLED === '1' || state.enabled === false || isCi()
140
+ }
141
+
142
+ async function reportActive(endpoint) {
143
+ const state = readState()
144
+ if (telemetryDisabled(state)) return
145
+ const today = shanghaiToday()
146
+ // 每日成功缓存只约束 skill_active
147
+ if (state.lastActiveDay === today) return
148
+ const clientId = getClientId()
149
+ if (!clientId) return
150
+ // 版本:安装器写入的 installed-meta.json(与本脚本同目录);缺失记 unknown
151
+ const version = readInstalledVersion()
152
+ const ok = await postEvent(endpoint, {
153
+ kind: 'skill_active',
154
+ event_id: randomUUID(),
155
+ subject_id: clientId,
156
+ version,
157
+ })
158
+ if (ok) writeState({ lastActiveDay: today })
159
+ }
160
+
161
+ function readInstalledVersion() {
162
+ try {
163
+ const here = dirname(fileURLToPath(import.meta.url))
164
+ const meta = JSON.parse(readFileSync(join(here, 'installed-meta.json'), 'utf8'))
165
+ if (typeof meta.version === 'string' && meta.version.length > 0 && meta.version.length <= 64) {
166
+ return meta.version
167
+ }
168
+ } catch {
169
+ // 手工复制缺失元信息
170
+ }
171
+ return 'unknown'
172
+ }
173
+
174
+ async function reportInstall(endpoint, { version, targets, result }) {
175
+ const state = readState()
176
+ if (telemetryDisabled(state)) return
177
+ const clientId = getClientId()
178
+ if (!clientId) return
179
+ await postEvent(endpoint, {
180
+ kind: 'skill_install',
181
+ event_id: randomUUID(),
182
+ subject_id: clientId,
183
+ version,
184
+ targets,
185
+ result,
186
+ })
187
+ // 安装事件不更新活跃日期缓存:安装完成不代表实际使用过
188
+ }
189
+
190
+ export async function main(argv) {
191
+ const [command, ...rest] = argv
192
+ const endpoint = resolveEndpoint()
193
+ if (!endpoint) return
194
+ if (command === 'active') {
195
+ await reportActive(endpoint)
196
+ return
197
+ }
198
+ if (command === 'install') {
199
+ const options = { version: 'unknown', targets: [], result: 'success' }
200
+ for (let i = 0; i < rest.length; i += 2) {
201
+ if (rest[i] === '--version' && rest[i + 1]) options.version = String(rest[i + 1]).slice(0, 64)
202
+ if (rest[i] === '--targets' && rest[i + 1]) {
203
+ options.targets = [
204
+ ...new Set(
205
+ String(rest[i + 1])
206
+ .split(',')
207
+ .map((t) => t.trim())
208
+ .filter(Boolean),
209
+ ),
210
+ ]
211
+ }
212
+ if (rest[i] === '--result' && rest[i + 1] === 'partial') options.result = 'partial'
213
+ }
214
+ if (options.targets.length === 0) return
215
+ await reportInstall(endpoint, options)
216
+ }
217
+ }
218
+
219
+ // 调用路径可能含符号链接(如 macOS /tmp → /private/tmp):比较物理路径
220
+ const isMain =
221
+ process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))
222
+ if (isMain) {
223
+ try {
224
+ await main(process.argv.slice(2))
225
+ } catch {
226
+ // 上报绝不改变主流程退出码
227
+ }
228
+ process.exit(0)
229
+ }
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "apex-ui",
3
+ "description": "在项目里正确使用 Apex UI:默认以源码模式安装,组件有问题直接修改项目内源码",
4
+ "default": true,
5
+ "rules": {
6
+ "claude": {
7
+ "file": "rules/claude.md",
8
+ "marker": "<!-- apex-ui:rule:start -->",
9
+ "endMarker": "<!-- apex-ui:rule:end -->",
10
+ "legacyMarker": "<!-- apex-ui:rule -->",
11
+ "appendTo": "CLAUDE.md",
12
+ "legacyFiles": ["CONTEXT.md"]
13
+ },
14
+ "gemini": {
15
+ "file": "rules/agents.md",
16
+ "marker": "<!-- apex-ui:rule:start -->",
17
+ "endMarker": "<!-- apex-ui:rule:end -->",
18
+ "appendTo": "GEMINI.md"
19
+ },
20
+ "copilot": {
21
+ "file": "rules/agents.md",
22
+ "marker": "<!-- apex-ui:rule:start -->",
23
+ "endMarker": "<!-- apex-ui:rule:end -->",
24
+ "appendTo": ".github/copilot-instructions.md"
25
+ },
26
+ "windsurf": {
27
+ "file": "rules/agents.md",
28
+ "marker": "<!-- apex-ui:rule:start -->",
29
+ "endMarker": "<!-- apex-ui:rule:end -->",
30
+ "appendTo": ".windsurf/rules/apex-ui.md",
31
+ "header": "---\ntrigger: always_on\n---"
32
+ },
33
+ "antigravity": {
34
+ "file": "rules/agents.md",
35
+ "marker": "<!-- apex-ui:rule:start -->",
36
+ "endMarker": "<!-- apex-ui:rule:end -->",
37
+ "appendTo": ".agent/rules/apex-ui.md",
38
+ "header": "---\ntrigger: always_on\n---"
39
+ },
40
+ "*": {
41
+ "file": "rules/agents.md",
42
+ "marker": "<!-- apex-ui:rule:start -->",
43
+ "endMarker": "<!-- apex-ui:rule:end -->",
44
+ "legacyMarker": "<!-- apex-ui:rule -->",
45
+ "appendTo": "AGENTS.md",
46
+ "legacyFiles": [".agents/AGENTS.md"]
47
+ }
48
+ }
49
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@apexhub/apex-ui-skill",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.2.0",
4
+ "description": "Apex UI AI skills — guided installer for Claude / Cursor / Copilot and more",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "apex-ui",
8
+ "skill",
9
+ "claude",
10
+ "cursor",
11
+ "copilot",
12
+ "ai"
13
+ ],
14
+ "type": "module",
15
+ "bin": {
16
+ "apex-ui": "./scripts/install-skills.mjs"
17
+ },
18
+ "files": [
19
+ "apex-ui",
20
+ "scripts"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "registry": "https://registry.npmjs.org/"
25
+ },
26
+ "scripts": {
27
+ "test": "node --test tests/*.test.mjs",
28
+ "typecheck": "node --check scripts/install-skills.mjs && node --check scripts/lib/detect.mjs && node --check scripts/lib/discover.mjs && node --check scripts/lib/install.mjs && node --check scripts/lib/parse-args.mjs && node --check scripts/lib/prompt.mjs && node --check scripts/lib/targets.mjs && node --check scripts/lib/ui.mjs && node --check scripts/lib/logo.mjs"
29
+ }
6
30
  }
@@ -0,0 +1,226 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Apex UI Skills 安装器
4
+ *
5
+ * 消费方项目根目录:
6
+ * npx @apexhub/apex-ui-skill
7
+ */
8
+ import { existsSync, readFileSync } from 'node:fs'
9
+ import { dirname, join, relative, resolve } from 'node:path'
10
+ import { fileURLToPath, pathToFileURL } from 'node:url'
11
+ import { resolveAutoTargets } from './lib/detect.mjs'
12
+ import { discoverSkills } from './lib/discover.mjs'
13
+ import { installSkillToTarget } from './lib/install.mjs'
14
+ import { parseArgs, validateTargetIds } from './lib/parse-args.mjs'
15
+ import { runWizard } from './lib/prompt.mjs'
16
+ import { DEFAULT_TARGET_IDS, getTarget, TARGETS } from './lib/targets.mjs'
17
+ import {
18
+ detectCapabilities,
19
+ playIntro,
20
+ playSuccess,
21
+ printPlainHelp,
22
+ runInstallSequence,
23
+ } from './lib/ui.mjs'
24
+
25
+ /** How each rule-file outcome is reported in the summary; `unchanged` / `skipped` stay silent. */
26
+ const RULE_ACTION_LABELS = {
27
+ created: '已写入 apex-ui 规则',
28
+ appended: '已追加 apex-ui 规则',
29
+ updated: '已更新 apex-ui 规则',
30
+ }
31
+
32
+ const here = dirname(fileURLToPath(import.meta.url))
33
+ const pkgRoot = resolve(here, '..')
34
+ const pkgJson = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8'))
35
+ const version = pkgJson.version
36
+
37
+ async function main() {
38
+ const args = parseArgs(process.argv.slice(2))
39
+ const caps = detectCapabilities({ plain: args.plain })
40
+ const cwd = process.cwd()
41
+ const skills = discoverSkills(pkgRoot)
42
+
43
+ if (args.help) {
44
+ printPlainHelp()
45
+ return
46
+ }
47
+
48
+ if (args.listTargets) {
49
+ for (const target of TARGETS) {
50
+ const def = target.default ? ' (default)' : ''
51
+ console.log(`${target.id.padEnd(12)} ${target.label}${def}`)
52
+ console.log(` → ${target.pathTemplate}`)
53
+ }
54
+ return
55
+ }
56
+
57
+ if (args.list) {
58
+ for (const skill of skills) {
59
+ const def = skill.default ? ' [default]' : ''
60
+ console.log(`${skill.name}${def} — ${skill.description || ''}`)
61
+ }
62
+ return
63
+ }
64
+
65
+ if (skills.length === 0) {
66
+ console.error('[apex-ui] 未找到任何 skill,请确认 @apexhub/apex-ui-skill 安装完整。')
67
+ process.exit(1)
68
+ }
69
+
70
+ let skillNames
71
+ let targetIds
72
+ // Which AI tools this project is used with: the one running us (if any) plus tools that already
73
+ // left config here. Used when nobody picks targets, for `--target auto`, and to pre-tick the wizard.
74
+ const detected = resolveAutoTargets({ env: process.env, cwd })
75
+
76
+ const hasExplicit =
77
+ args.all ||
78
+ args.defaultOnly ||
79
+ (args.skills && args.skills.length > 0) ||
80
+ (args.targets && args.targets.length > 0)
81
+
82
+ if (!hasExplicit && !caps.tty) {
83
+ // No terminal to answer the wizard: usually an AI tool (Codex, Claude Code, Cursor …) running
84
+ // `npx @apexhub/apex-ui-skill` for the user. Install the default skills where the detected tools read them.
85
+ skillNames = skills.filter((s) => s.default).map((s) => s.name)
86
+ if (skillNames.length === 0) skillNames = skills.map((s) => s.name)
87
+ targetIds = detected.targetIds
88
+ caps.plain = true
89
+ } else if (!hasExplicit) {
90
+ if (!caps.plain) await playIntro({ ...caps, version })
91
+ const preselect = [...new Set([...DEFAULT_TARGET_IDS, ...detected.targetIds])]
92
+ ;({ skillNames, targetIds } = await runWizard({ ...caps, skills, preselect }))
93
+ } else {
94
+ if (args.all) {
95
+ skillNames = skills.map((s) => s.name)
96
+ } else if (args.defaultOnly) {
97
+ skillNames = skills.filter((s) => s.default).map((s) => s.name)
98
+ if (skillNames.length === 0) skillNames = skills.map((s) => s.name)
99
+ } else {
100
+ skillNames = args.skills || skills.filter((s) => s.default).map((s) => s.name)
101
+ }
102
+
103
+ targetIds = args.targets || (caps.tty ? DEFAULT_TARGET_IDS : detected.targetIds)
104
+ }
105
+
106
+ if (targetIds.includes('auto')) {
107
+ targetIds = [...new Set(targetIds.flatMap((id) => (id === 'auto' ? detected.targetIds : [id])))]
108
+ }
109
+
110
+ validateTargetIds(targetIds)
111
+
112
+ const skillMap = new Map(skills.map((s) => [s.name, s]))
113
+ for (const name of skillNames) {
114
+ if (!skillMap.has(name)) {
115
+ console.error(`[apex-ui] 未知 skill:${name}(可用 --list 查看)`)
116
+ process.exit(1)
117
+ }
118
+ }
119
+
120
+ const ruleFiles = []
121
+ /**
122
+ * @typedef {{ id: string, label: string, detail: string, skillName: string, targetId: string, skill: object }} InstallJob
123
+ */
124
+
125
+ /** @type {InstallJob[]} */
126
+ const installTasks = []
127
+
128
+ for (const skillName of skillNames) {
129
+ const skill = skillMap.get(skillName)
130
+ for (const targetId of targetIds) {
131
+ const target = getTarget(targetId)
132
+ installTasks.push({
133
+ id: `${skillName}:${targetId}`,
134
+ label: target.label,
135
+ detail: target.pathTemplate.replace('{name}', skillName),
136
+ skillName,
137
+ targetId,
138
+ skill,
139
+ })
140
+ }
141
+ }
142
+
143
+ await runInstallSequence(
144
+ caps,
145
+ installTasks.map((t) => ({ id: t.id, label: t.label, detail: t.detail })),
146
+ async (task) => {
147
+ const job = installTasks.find((t) => t.id === task.id)
148
+ if (!job) return
149
+ const result = installSkillToTarget({
150
+ cwd,
151
+ skillDir: job.skill.dir,
152
+ skillName: job.skillName,
153
+ targetId: job.targetId,
154
+ rules: job.skill.rules,
155
+ })
156
+ // 统计元信息:写入所安装 Skill 的 scripts/installed-meta.json(尽力而为,失败不影响安装结果)
157
+ try {
158
+ const { writeFileSync, existsSync } = await import('node:fs')
159
+ const scriptsDir = join(result.destDir, 'scripts')
160
+ if (existsSync(scriptsDir)) {
161
+ writeFileSync(
162
+ join(scriptsDir, 'installed-meta.json'),
163
+ JSON.stringify({ version, installedAt: new Date().toISOString() }),
164
+ )
165
+ }
166
+ } catch {
167
+ // 元信息缺失时后续按 unknown 上报
168
+ }
169
+ for (const rule of result.ruleResults ?? []) {
170
+ const label = RULE_ACTION_LABELS[rule.action]
171
+ if (label && rule.file) ruleFiles.push(`${relative(cwd, rule.file)} ${label}`)
172
+ for (const file of rule.removedLegacy ?? []) {
173
+ ruleFiles.push(`${relative(cwd, file)} 已移除旧版 apex-ui 规则`)
174
+ }
175
+ }
176
+ },
177
+ )
178
+
179
+ // 使用统计:本轮结束后最多报告一次 skill_install;失败不改变退出码
180
+ try {
181
+ const reporterPath = join(pkgRoot, 'apex-ui', 'scripts', 'report-usage.mjs')
182
+ const { main: reportUsage } = await import(pathToFileURL(reporterPath).href)
183
+ await reportUsage([
184
+ 'install',
185
+ '--version',
186
+ version,
187
+ '--targets',
188
+ [...new Set(targetIds)].join(','),
189
+ ])
190
+ } catch {
191
+ // 上报失败不影响安装结果
192
+ }
193
+
194
+ await playSuccess(caps, {
195
+ skillCount: skillNames.length,
196
+ targetCount: installTasks.length,
197
+ ruleFiles: [...new Set(ruleFiles)],
198
+ skillEntries: installTasks.map((t) => `${t.detail}SKILL.md`),
199
+ interactive: caps.tty,
200
+ noProject: !existsSync(join(cwd, 'package.json')),
201
+ detected: describeDetection(detected, targetIds),
202
+ })
203
+ }
204
+
205
+ /**
206
+ * One line saying which AI tools were recognised and why, e.g.
207
+ * `Claude Code(当前运行环境)、Cursor(项目里已有配置)`. Empty when nothing was recognised.
208
+ * @param {{ host: string | null, fromProject: string[] }} detected
209
+ * @param {string[]} targetIds targets actually installed
210
+ */
211
+ function describeDetection(detected, targetIds) {
212
+ const parts = []
213
+ if (detected.host && targetIds.includes(detected.host)) {
214
+ parts.push(`${getTarget(detected.host).label}(当前运行环境)`)
215
+ }
216
+ for (const id of detected.fromProject) {
217
+ if (id !== detected.host && targetIds.includes(id))
218
+ parts.push(`${getTarget(id).label}(项目里已有配置)`)
219
+ }
220
+ return parts.join('、')
221
+ }
222
+
223
+ main().catch((err) => {
224
+ console.error(`[apex-ui] ${err.message}`)
225
+ process.exit(1)
226
+ })
@@ -0,0 +1,109 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /**
5
+ * Works out which AI tools a project is used with, so a user who only types "install Apex UI" into
6
+ * their AI tool gets the skill and rules where that tool reads them.
7
+ *
8
+ * Two kinds of evidence:
9
+ * - the host: the AI tool running the installer right now, told apart by environment variables it
10
+ * sets for the commands it runs;
11
+ * - the project: config files or folders other AI tools have already created in the project.
12
+ *
13
+ * The variable names are what each tool sets as far as we know; they are not a published contract.
14
+ * When a tool changes them, detection falls back to project markers and the shared `agents` target,
15
+ * so keep this table small and easy to correct.
16
+ */
17
+
18
+ /**
19
+ * Checked in order; the first match is the host. VS Code forks (Cursor, Windsurf, Antigravity) also
20
+ * set `TERM_PROGRAM=vscode`, so they come before the plain VS Code (Copilot) check.
21
+ * @type {Array<{ id: string, match: (env: Record<string, string | undefined>) => boolean }>}
22
+ */
23
+ export const HOST_SIGNALS = [
24
+ { id: 'claude', match: (env) => truthy(env.CLAUDECODE) || Boolean(env.CLAUDE_CODE_ENTRYPOINT) },
25
+ {
26
+ id: 'codex',
27
+ match: (env) =>
28
+ Boolean(
29
+ env.CODEX_SANDBOX ||
30
+ env.CODEX_SANDBOX_NETWORK_DISABLED ||
31
+ env.CODEX_THREAD_ID ||
32
+ env.CODEX_CI,
33
+ ),
34
+ },
35
+ { id: 'gemini', match: (env) => truthy(env.GEMINI_CLI) },
36
+ { id: 'opencode', match: (env) => truthy(env.OPENCODE) },
37
+ {
38
+ id: 'cursor',
39
+ match: (env) =>
40
+ Boolean(env.CURSOR_AGENT || env.CURSOR_TRACE_ID) ||
41
+ /cursor/i.test(env.__CFBundleIdentifier ?? ''),
42
+ },
43
+ {
44
+ id: 'windsurf',
45
+ match: (env) =>
46
+ /windsurf|exafunction/i.test(`${env.__CFBundleIdentifier ?? ''} ${env.TERM_PROGRAM ?? ''}`),
47
+ },
48
+ {
49
+ id: 'antigravity',
50
+ match: (env) =>
51
+ Boolean(env.ANTIGRAVITY_AGENT) ||
52
+ /antigravity/i.test(`${env.__CFBundleIdentifier ?? ''} ${env.TERM_PROGRAM ?? ''}`),
53
+ },
54
+ { id: 'copilot', match: (env) => env.TERM_PROGRAM === 'vscode' },
55
+ ]
56
+
57
+ /** Files or folders that show a project is already used with a tool. Paths are project-relative. */
58
+ export const PROJECT_MARKERS = {
59
+ claude: ['.claude', 'CLAUDE.md'],
60
+ codex: ['.codex'],
61
+ cursor: ['.cursor', '.cursorrules'],
62
+ opencode: ['.opencode', 'opencode.json', 'opencode.jsonc'],
63
+ copilot: ['.github/copilot-instructions.md', '.github/instructions', '.github/skills'],
64
+ windsurf: ['.windsurf', '.windsurfrules'],
65
+ gemini: ['.gemini', 'GEMINI.md'],
66
+ antigravity: ['.agent'],
67
+ }
68
+
69
+ /** Always installed: the shared `.agents/skills/` copy and the root `AGENTS.md` rule. */
70
+ export const SHARED_TARGET_ID = 'agents'
71
+
72
+ /** @param {string | undefined} value */
73
+ function truthy(value) {
74
+ return Boolean(value) && value !== '0' && value.toLowerCase() !== 'false'
75
+ }
76
+
77
+ /**
78
+ * @param {Record<string, string | undefined>} env
79
+ * @returns {string | null} target id of the AI tool running the installer, if recognised
80
+ */
81
+ export function detectHost(env) {
82
+ for (const signal of HOST_SIGNALS) {
83
+ if (signal.match(env)) return signal.id
84
+ }
85
+ return null
86
+ }
87
+
88
+ /**
89
+ * @param {string} cwd
90
+ * @returns {string[]} target ids of tools that already left config in the project
91
+ */
92
+ export function detectProjectTools(cwd) {
93
+ return Object.entries(PROJECT_MARKERS)
94
+ .filter(([, markers]) => markers.some((rel) => existsSync(join(cwd, rel))))
95
+ .map(([id]) => id)
96
+ }
97
+
98
+ /**
99
+ * Targets for an install nobody chose explicitly: the shared target, the host tool, and every tool
100
+ * the project already uses.
101
+ * @param {{ env: Record<string, string | undefined>, cwd: string }} options
102
+ * @returns {{ targetIds: string[], host: string | null, fromProject: string[] }}
103
+ */
104
+ export function resolveAutoTargets({ env, cwd }) {
105
+ const host = detectHost(env)
106
+ const fromProject = detectProjectTools(cwd)
107
+ const targetIds = [...new Set([SHARED_TARGET_ID, ...(host ? [host] : []), ...fromProject])]
108
+ return { targetIds, host, fromProject }
109
+ }
@@ -0,0 +1,30 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ const SKIP_DIRS = new Set(['scripts', 'node_modules'])
5
+
6
+ /**
7
+ * @param {string} pkgRoot
8
+ * @returns {Array<{ name: string, description?: string, default?: boolean, dir: string, rules?: Record<string, unknown> }>}
9
+ */
10
+ export function discoverSkills(pkgRoot) {
11
+ const skills = []
12
+
13
+ for (const entry of readdirSync(pkgRoot, { withFileTypes: true })) {
14
+ if (!entry.isDirectory() || SKIP_DIRS.has(entry.name)) continue
15
+
16
+ const dir = join(pkgRoot, entry.name)
17
+ const manifestPath = join(dir, 'skill.json')
18
+ const skillMdPath = join(dir, 'SKILL.md')
19
+
20
+ if (!existsSync(manifestPath) || !existsSync(skillMdPath)) continue
21
+
22
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
23
+ skills.push({
24
+ ...manifest,
25
+ dir,
26
+ })
27
+ }
28
+
29
+ return skills.sort((a, b) => a.name.localeCompare(b.name))
30
+ }