@minhluudev/ai-tools 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # ai-tools
2
+
3
+ `@minhluudev/ai-tools` is an npm CLI that installs AI skills from GitHub branches in this repository into Codex and Claude.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @minhluudev/ai-tools
9
+ ai-tools install
10
+ ```
11
+
12
+ ## Supported Flow
13
+
14
+ The interactive installer asks for:
15
+
16
+ 1. Individual skills from the `skill-general` branch
17
+ 2. Skill groups from other branches such as `laravel-ddd`
18
+ 3. Installation location: `global` or `local`
19
+ 4. Target agent: `codex` or `claude`
20
+
21
+ Global installs write into:
22
+
23
+ - `~/.codex`
24
+ - `~/.claude`
25
+
26
+ Local installs write into:
27
+
28
+ - `./.codex`
29
+ - `./.claude`
30
+
31
+ ## Manifest Contract
32
+
33
+ Each source branch must expose `ai-tools.catalog.json` at the branch root.
34
+
35
+ ```json
36
+ {
37
+ "version": 1,
38
+ "type": "skills",
39
+ "label": "General Skills",
40
+ "description": "Standalone skills",
41
+ "items": [
42
+ {
43
+ "id": "laravel-code-reviewer",
44
+ "label": "Laravel Code Reviewer",
45
+ "description": "Review Laravel and PHP changes",
46
+ "sourcePath": "skills/laravel-code-reviewer",
47
+ "targets": {
48
+ "codex": {
49
+ "type": "directory",
50
+ "outputPath": "skills/laravel-code-reviewer"
51
+ },
52
+ "claude": {
53
+ "type": "file",
54
+ "outputPath": "agents/laravel-code-reviewer.md"
55
+ }
56
+ }
57
+ }
58
+ ]
59
+ }
60
+ ```
61
+
62
+ Rules:
63
+
64
+ - `skill-general` must use `"type": "skills"`
65
+ - group branches must use `"type": "group"`
66
+ - `sourcePath` and `outputPath` must stay inside the repository or install root
67
+ - each selected skill id must be unique across the final merged selection
68
+
69
+ ## Non-Interactive Usage
70
+
71
+ ```bash
72
+ ai-tools install \
73
+ --skills laravel-code-reviewer,mql5-ui-designer \
74
+ --groups laravel-ddd \
75
+ --location local \
76
+ --agent codex \
77
+ --yes
78
+ ```
79
+
80
+ ## CI/CD
81
+
82
+ GitHub Actions includes:
83
+
84
+ - `.github/workflows/ci.yml` for test and package validation on `push` to `main` and all pull requests
85
+ - `.github/workflows/publish.yml` for npm publish on tags matching `v*.*.*` and manual dispatch
86
+
87
+ To publish successfully, configure the repository secret `NPM_TOKEN` with publish access to the target npm package.
88
+
89
+ For the first public publish of this scoped package, use:
90
+
91
+ ```bash
92
+ npm publish --access public
93
+ ```
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from "../cli.js";
3
+ runCli(process.argv).catch((error) => {
4
+ const message = error instanceof Error ? error.message : String(error);
5
+ console.error(`Error: ${message}`);
6
+ process.exitCode = 1;
7
+ });
@@ -0,0 +1,214 @@
1
+ import * as process from "node:process";
2
+ import { parseArgs, printHelp } from "./lib/args.js";
3
+ import { loadPackageConfig } from "./lib/config.js";
4
+ import { loadCatalogIndex, mergeSelectedItems } from "./lib/catalog.js";
5
+ import { createPromptSession, promptConfirm, promptMultiSelect, promptSingleSelect } from "./lib/prompts.js";
6
+ import { createGitHubClient } from "./lib/github.js";
7
+ import { detectExistingTargets, installPlannedItems, planInstallations, resolveInstallRoot } from "./lib/install.js";
8
+ function formatSelectionChoices(items) {
9
+ return items.map((item) => {
10
+ const compatibility = [item.targets.codex ? "codex" : null, item.targets.claude ? "claude" : null]
11
+ .filter(Boolean)
12
+ .join(", ");
13
+ return {
14
+ value: item.id,
15
+ label: item.label,
16
+ description: `${item.description || "No description"} [${compatibility || "unsupported"}]`
17
+ };
18
+ });
19
+ }
20
+ function formatGroupChoices(groups) {
21
+ return groups.map((group) => ({
22
+ value: group.id,
23
+ label: group.label,
24
+ description: `${group.description || "No description"} (${group.items.length} skill${group.items.length === 1 ? "" : "s"})`
25
+ }));
26
+ }
27
+ function printSelectionSummary(input) {
28
+ console.log("");
29
+ console.log("Install summary");
30
+ console.log(`- Agent: ${input.agent}`);
31
+ console.log(`- Location: ${input.location}`);
32
+ console.log(`- Root: ${input.installRoot}`);
33
+ console.log(`- Individual skills: ${input.selectedSkills.length ? input.selectedSkills.join(", ") : "none"}`);
34
+ console.log(`- Groups: ${input.selectedGroups.length ? input.selectedGroups.join(", ") : "none"}`);
35
+ console.log(`- Final items: ${input.plannedItems.map((item) => item.id).join(", ")}`);
36
+ }
37
+ async function resolveInteractiveSelections(index, options) {
38
+ const prompt = createPromptSession();
39
+ try {
40
+ const selectedSkills = options.skills.length > 0
41
+ ? options.skills
42
+ : await promptMultiSelect(prompt, {
43
+ message: "Select individual skills",
44
+ choices: formatSelectionChoices(index.individualSkills),
45
+ allowEmpty: true
46
+ });
47
+ const selectedGroups = options.groups.length > 0
48
+ ? options.groups
49
+ : await promptMultiSelect(prompt, {
50
+ message: "Select skill groups",
51
+ choices: formatGroupChoices(index.groups),
52
+ allowEmpty: true
53
+ });
54
+ const location = options.location ||
55
+ (await promptSingleSelect(prompt, {
56
+ message: "Select installation location",
57
+ choices: [
58
+ {
59
+ value: "global",
60
+ label: "global",
61
+ description: "Install into the current user's home directory."
62
+ },
63
+ {
64
+ value: "local",
65
+ label: "local",
66
+ description: "Install into this project's dot directories."
67
+ }
68
+ ]
69
+ }));
70
+ const agent = options.agent ||
71
+ (await promptSingleSelect(prompt, {
72
+ message: "Select agent",
73
+ choices: [
74
+ {
75
+ value: "codex",
76
+ label: "codex",
77
+ description: "Install as Codex skills."
78
+ },
79
+ {
80
+ value: "claude",
81
+ label: "claude",
82
+ description: "Install as Claude custom agents."
83
+ }
84
+ ]
85
+ }));
86
+ return { selectedSkills, selectedGroups, location, agent };
87
+ }
88
+ finally {
89
+ await prompt.close();
90
+ }
91
+ }
92
+ function ensureNonInteractiveInputs(index, options) {
93
+ const missing = [];
94
+ if (options.skills.length === 0 && options.groups.length === 0) {
95
+ missing.push("--skills and/or --groups");
96
+ }
97
+ if (!options.location) {
98
+ missing.push("--location");
99
+ }
100
+ if (!options.agent) {
101
+ missing.push("--agent");
102
+ }
103
+ if (missing.length > 0) {
104
+ throw new Error(`Non-interactive mode requires ${missing.join(", ")}. Run in a TTY for prompts.`);
105
+ }
106
+ const unknownSkills = options.skills.filter((skillId) => !index.individualSkills.some((item) => item.id === skillId));
107
+ if (unknownSkills.length > 0) {
108
+ throw new Error(`Unknown skill id(s): ${unknownSkills.join(", ")}`);
109
+ }
110
+ const unknownGroups = options.groups.filter((groupId) => !index.groups.some((group) => group.id === groupId));
111
+ if (unknownGroups.length > 0) {
112
+ throw new Error(`Unknown group id(s): ${unknownGroups.join(", ")}`);
113
+ }
114
+ }
115
+ async function resolveSelections(index, options) {
116
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
117
+ ensureNonInteractiveInputs(index, options);
118
+ return {
119
+ selectedSkills: options.skills,
120
+ selectedGroups: options.groups,
121
+ location: options.location,
122
+ agent: options.agent
123
+ };
124
+ }
125
+ return resolveInteractiveSelections(index, options);
126
+ }
127
+ export async function runCli(argv = process.argv) {
128
+ const { command, options } = parseArgs(argv.slice(2));
129
+ if (options.help || command === "help") {
130
+ printHelp();
131
+ return;
132
+ }
133
+ if (command !== "install") {
134
+ throw new Error(`Unsupported command "${command}". Only "install" is available.`);
135
+ }
136
+ const config = await loadPackageConfig();
137
+ const client = createGitHubClient(config.github);
138
+ console.log("Loading remote catalogs...");
139
+ const index = await loadCatalogIndex(client, config.github);
140
+ if (index.individualSkills.length === 0 && index.groups.length === 0) {
141
+ throw new Error("No installable skills or groups were found in the configured repository.");
142
+ }
143
+ const { selectedSkills, selectedGroups, location, agent } = await resolveSelections(index, options);
144
+ const finalItems = mergeSelectedItems({
145
+ individualSkills: index.individualSkills,
146
+ groups: index.groups,
147
+ selectedSkillIds: selectedSkills,
148
+ selectedGroupIds: selectedGroups
149
+ });
150
+ if (finalItems.length === 0) {
151
+ throw new Error("No skills were selected.");
152
+ }
153
+ const installRoot = resolveInstallRoot({ agent, location, cwd: process.cwd() });
154
+ const plannedItems = planInstallations({
155
+ items: finalItems,
156
+ agent,
157
+ installRoot
158
+ });
159
+ printSelectionSummary({
160
+ location,
161
+ agent,
162
+ installRoot,
163
+ selectedSkills,
164
+ selectedGroups,
165
+ plannedItems
166
+ });
167
+ const existingTargets = await detectExistingTargets(plannedItems);
168
+ let overwriteExisting = options.yes;
169
+ if (existingTargets.length > 0 && !overwriteExisting) {
170
+ console.log("");
171
+ console.log("Existing targets detected:");
172
+ for (const item of existingTargets) {
173
+ console.log(`- ${item.id}: ${item.targetPath}`);
174
+ }
175
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
176
+ throw new Error("Existing targets require --yes in non-interactive mode.");
177
+ }
178
+ const prompt = createPromptSession();
179
+ try {
180
+ overwriteExisting = await promptConfirm(prompt, {
181
+ message: "Overwrite all existing targets?",
182
+ defaultValue: false
183
+ });
184
+ }
185
+ finally {
186
+ await prompt.close();
187
+ }
188
+ if (!overwriteExisting) {
189
+ throw new Error("Installation cancelled because existing targets would be overwritten.");
190
+ }
191
+ }
192
+ console.log("");
193
+ console.log("Installing...");
194
+ const results = await installPlannedItems({
195
+ plannedItems,
196
+ client,
197
+ overwriteExisting,
198
+ onProgress(item) {
199
+ console.log(`- ${item.id} from ${item.sourceBranch} -> ${item.targetPath}`);
200
+ }
201
+ });
202
+ console.log("");
203
+ console.log("Install complete");
204
+ for (const result of results) {
205
+ console.log(`- ${result.id}: ${result.targetPath}`);
206
+ }
207
+ if (index.warnings.length > 0) {
208
+ console.log("");
209
+ console.log("Catalog warnings");
210
+ for (const warning of index.warnings) {
211
+ console.log(`- ${warning}`);
212
+ }
213
+ }
214
+ }
@@ -0,0 +1,91 @@
1
+ const COMMANDS = new Set(["install", "help"]);
2
+ const AGENTS = new Set(["codex", "claude"]);
3
+ const LOCATIONS = new Set(["global", "local"]);
4
+ const FLAG_KEYS = new Set(["agent", "location", "skills", "groups"]);
5
+ function parseCsv(value) {
6
+ if (!value) {
7
+ return [];
8
+ }
9
+ return value
10
+ .split(",")
11
+ .map((item) => item.trim())
12
+ .filter(Boolean);
13
+ }
14
+ export function isAgent(value) {
15
+ return AGENTS.has(value);
16
+ }
17
+ export function isInstallLocation(value) {
18
+ return LOCATIONS.has(value);
19
+ }
20
+ export function parseArgs(argv) {
21
+ let command = "install";
22
+ const options = {
23
+ help: false,
24
+ yes: false,
25
+ agent: undefined,
26
+ location: undefined,
27
+ skills: [],
28
+ groups: []
29
+ };
30
+ for (let index = 0; index < argv.length; index += 1) {
31
+ const token = argv[index];
32
+ if (token === "--help" || token === "-h") {
33
+ options.help = true;
34
+ continue;
35
+ }
36
+ if (token === "--yes") {
37
+ options.yes = true;
38
+ continue;
39
+ }
40
+ if (!token.startsWith("--")) {
41
+ if (COMMANDS.has(token)) {
42
+ command = token;
43
+ continue;
44
+ }
45
+ throw new Error(`Unknown argument "${token}".`);
46
+ }
47
+ const key = token.slice(2);
48
+ if (!FLAG_KEYS.has(key)) {
49
+ throw new Error(`Unknown flag "${token}".`);
50
+ }
51
+ const value = argv[index + 1];
52
+ if (!value || value.startsWith("--")) {
53
+ throw new Error(`Flag "${token}" requires a value.`);
54
+ }
55
+ index += 1;
56
+ if (key === "skills" || key === "groups") {
57
+ options[key] = parseCsv(value);
58
+ continue;
59
+ }
60
+ if (key === "agent") {
61
+ if (!isAgent(value)) {
62
+ throw new Error(`Invalid agent "${value}". Use "codex" or "claude".`);
63
+ }
64
+ options.agent = value;
65
+ continue;
66
+ }
67
+ if (key === "location") {
68
+ if (!isInstallLocation(value)) {
69
+ throw new Error(`Invalid location "${value}". Use "global" or "local".`);
70
+ }
71
+ options.location = value;
72
+ }
73
+ }
74
+ return { command, options };
75
+ }
76
+ export function printHelp() {
77
+ console.log(`ai-tools
78
+
79
+ Usage:
80
+ ai-tools install [options]
81
+ ai-tools help
82
+
83
+ Options:
84
+ --skills <ids> Comma-separated individual skill ids
85
+ --groups <ids> Comma-separated group ids
86
+ --location <type> global | local
87
+ --agent <agent> codex | claude
88
+ --yes Skip overwrite prompts
89
+ --help, -h Show help
90
+ `);
91
+ }
@@ -0,0 +1,180 @@
1
+ import { normalizeManifestPath } from "./paths.js";
2
+ function validateTarget(target, agent, skillId) {
3
+ if (!target || typeof target !== "object") {
4
+ throw new Error(`Skill "${skillId}" has an invalid ${agent} target.`);
5
+ }
6
+ const targetRecord = target;
7
+ const type = targetRecord.type || "directory";
8
+ if (type !== "directory" && type !== "file") {
9
+ throw new Error(`Skill "${skillId}" has an invalid ${agent} target type "${String(type)}".`);
10
+ }
11
+ const outputPath = typeof targetRecord.outputPath === "string" && targetRecord.outputPath.trim() !== ""
12
+ ? normalizeManifestPath(targetRecord.outputPath, `${skillId}.${agent}.outputPath`)
13
+ : undefined;
14
+ return { type, outputPath };
15
+ }
16
+ function attachBranchMetadata(items, branch, sha) {
17
+ return items.map((item) => ({
18
+ ...item,
19
+ sourceBranch: branch,
20
+ sourceSha: sha
21
+ }));
22
+ }
23
+ export function validateManifest(rawManifest, input) {
24
+ if (!rawManifest || typeof rawManifest !== "object") {
25
+ throw new Error(`Manifest "${input.manifestPath}" in branch "${input.branch}" must be an object.`);
26
+ }
27
+ const manifest = rawManifest;
28
+ if (manifest.version !== 1) {
29
+ throw new Error(`Manifest "${input.manifestPath}" in branch "${input.branch}" must use version 1.`);
30
+ }
31
+ if (manifest.type !== "skills" && manifest.type !== "group") {
32
+ throw new Error(`Manifest "${input.manifestPath}" in branch "${input.branch}" must declare type "skills" or "group".`);
33
+ }
34
+ if (!Array.isArray(manifest.items)) {
35
+ throw new Error(`Manifest "${input.manifestPath}" in branch "${input.branch}" must contain an items array.`);
36
+ }
37
+ const items = manifest.items.map((item, index) => {
38
+ if (!item || typeof item !== "object") {
39
+ throw new Error(`Manifest item #${index + 1} in branch "${input.branch}" must be an object.`);
40
+ }
41
+ const manifestItem = item;
42
+ if (typeof manifestItem.id !== "string" || manifestItem.id.trim() === "") {
43
+ throw new Error(`Manifest item #${index + 1} in branch "${input.branch}" is missing a valid id.`);
44
+ }
45
+ if (typeof manifestItem.label !== "string" || manifestItem.label.trim() === "") {
46
+ throw new Error(`Manifest item "${manifestItem.id}" in branch "${input.branch}" is missing a valid label.`);
47
+ }
48
+ const sourcePath = normalizeManifestPath(manifestItem.sourcePath, `${manifestItem.id}.sourcePath`);
49
+ if (!manifestItem.targets || typeof manifestItem.targets !== "object") {
50
+ throw new Error(`Manifest item "${manifestItem.id}" in branch "${input.branch}" is missing targets.`);
51
+ }
52
+ const targets = {};
53
+ if (manifestItem.targets.codex) {
54
+ targets.codex = validateTarget(manifestItem.targets.codex, "codex", manifestItem.id);
55
+ }
56
+ if (manifestItem.targets.claude) {
57
+ targets.claude = validateTarget(manifestItem.targets.claude, "claude", manifestItem.id);
58
+ }
59
+ if (!targets.codex && !targets.claude) {
60
+ throw new Error(`Manifest item "${manifestItem.id}" in branch "${input.branch}" must support at least one agent.`);
61
+ }
62
+ return {
63
+ id: manifestItem.id.trim(),
64
+ label: manifestItem.label.trim(),
65
+ description: typeof manifestItem.description === "string" && manifestItem.description.trim() !== ""
66
+ ? manifestItem.description.trim()
67
+ : "",
68
+ sourcePath,
69
+ sourceBranch: input.branch,
70
+ targets
71
+ };
72
+ });
73
+ return {
74
+ branch: input.branch,
75
+ manifestPath: input.manifestPath,
76
+ type: manifest.type,
77
+ label: typeof manifest.label === "string" && manifest.label.trim() !== ""
78
+ ? manifest.label.trim()
79
+ : input.branch,
80
+ description: typeof manifest.description === "string" && manifest.description.trim() !== ""
81
+ ? manifest.description.trim()
82
+ : "",
83
+ items
84
+ };
85
+ }
86
+ function isSkillGroup(group) {
87
+ return group !== null;
88
+ }
89
+ export async function loadCatalogIndex(client, githubConfig) {
90
+ const warnings = [];
91
+ const branches = await client.listBranches();
92
+ const branchMap = new Map(branches.map((branch) => [branch.name, branch]));
93
+ const skillsBranch = branchMap.get(githubConfig.skillsBranch);
94
+ if (!skillsBranch) {
95
+ throw new Error(`Configured skills branch "${githubConfig.skillsBranch}" was not found.`);
96
+ }
97
+ const skillManifestRaw = await client.fetchManifest({
98
+ branch: skillsBranch.name,
99
+ sha: skillsBranch.sha,
100
+ manifestPath: githubConfig.manifestPath
101
+ });
102
+ const skillManifest = validateManifest(skillManifestRaw, {
103
+ branch: skillsBranch.name,
104
+ manifestPath: githubConfig.manifestPath
105
+ });
106
+ const excludedBranches = new Set([
107
+ githubConfig.skillsBranch,
108
+ ...githubConfig.excludeBranches,
109
+ githubConfig.defaultBranch
110
+ ]);
111
+ const groupBranches = branches.filter((branch) => !excludedBranches.has(branch.name));
112
+ const groupResults = await Promise.all(groupBranches.map(async (branch) => {
113
+ try {
114
+ const rawManifest = await client.fetchManifest({
115
+ branch: branch.name,
116
+ sha: branch.sha,
117
+ manifestPath: githubConfig.manifestPath
118
+ });
119
+ const manifest = validateManifest(rawManifest, {
120
+ branch: branch.name,
121
+ manifestPath: githubConfig.manifestPath
122
+ });
123
+ if (manifest.type !== "group") {
124
+ warnings.push(`Skipped branch "${branch.name}" because its manifest type is "${manifest.type}".`);
125
+ return null;
126
+ }
127
+ return {
128
+ id: branch.name,
129
+ label: manifest.label,
130
+ description: manifest.description,
131
+ branch: branch.name,
132
+ items: attachBranchMetadata(manifest.items, branch.name, branch.sha)
133
+ };
134
+ }
135
+ catch (error) {
136
+ const message = error instanceof Error ? error.message : String(error);
137
+ warnings.push(`Skipped branch "${branch.name}": ${message}`);
138
+ return null;
139
+ }
140
+ }));
141
+ return {
142
+ individualSkills: attachBranchMetadata(skillManifest.items, skillsBranch.name, skillsBranch.sha),
143
+ groups: groupResults.filter(isSkillGroup),
144
+ warnings
145
+ };
146
+ }
147
+ export function mergeSelectedItems(input) {
148
+ const selectedItems = [];
149
+ const skillMap = new Map(input.individualSkills.map((item) => [item.id, item]));
150
+ const groupMap = new Map(input.groups.map((group) => [group.id, group]));
151
+ for (const skillId of input.selectedSkillIds) {
152
+ const skill = skillMap.get(skillId);
153
+ if (!skill) {
154
+ throw new Error(`Unknown skill id "${skillId}".`);
155
+ }
156
+ selectedItems.push(skill);
157
+ }
158
+ for (const groupId of input.selectedGroupIds) {
159
+ const group = groupMap.get(groupId);
160
+ if (!group) {
161
+ throw new Error(`Unknown group id "${groupId}".`);
162
+ }
163
+ selectedItems.push(...group.items);
164
+ }
165
+ const dedupedItems = new Map();
166
+ for (const item of selectedItems) {
167
+ const existing = dedupedItems.get(item.id);
168
+ if (!existing) {
169
+ dedupedItems.set(item.id, item);
170
+ continue;
171
+ }
172
+ const sameSource = existing.sourceBranch === item.sourceBranch &&
173
+ existing.sourcePath === item.sourcePath &&
174
+ JSON.stringify(existing.targets) === JSON.stringify(item.targets);
175
+ if (!sameSource) {
176
+ throw new Error(`Skill id "${item.id}" was selected from multiple incompatible sources. Keep ids unique across skill and group manifests.`);
177
+ }
178
+ }
179
+ return [...dedupedItems.values()];
180
+ }
@@ -0,0 +1,24 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
5
+ export async function loadPackageConfig() {
6
+ const packageJsonPath = path.join(PACKAGE_ROOT, "package.json");
7
+ const rawPackageJson = await readFile(packageJsonPath, "utf8");
8
+ const packageJson = JSON.parse(rawPackageJson);
9
+ const aiTools = packageJson.aiTools;
10
+ if (!aiTools?.github?.owner || !aiTools.github.repo) {
11
+ throw new Error("package.json is missing aiTools.github.owner or aiTools.github.repo.");
12
+ }
13
+ return {
14
+ packageRoot: PACKAGE_ROOT,
15
+ github: {
16
+ owner: aiTools.github.owner,
17
+ repo: aiTools.github.repo,
18
+ defaultBranch: aiTools.github.defaultBranch || "main",
19
+ skillsBranch: aiTools.github.skillsBranch || "skill-general",
20
+ manifestPath: aiTools.github.manifestPath || "ai-tools.catalog.json",
21
+ excludeBranches: aiTools.github.excludeBranches || ["main", "master"]
22
+ }
23
+ };
24
+ }
@@ -0,0 +1,129 @@
1
+ import { mkdtemp, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ async function ensureDirectory(dirPath) {
6
+ await mkdir(dirPath, { recursive: true });
7
+ }
8
+ function apiHeaders() {
9
+ return {
10
+ accept: "application/vnd.github+json",
11
+ "user-agent": "ai-tools"
12
+ };
13
+ }
14
+ async function fetchJson(url) {
15
+ const response = await fetch(url, {
16
+ headers: apiHeaders()
17
+ });
18
+ if (!response.ok) {
19
+ throw new Error(`GitHub request failed (${response.status}) for ${url}`);
20
+ }
21
+ return (await response.json());
22
+ }
23
+ function runTar(args, cwd) {
24
+ return new Promise((resolve, reject) => {
25
+ const child = spawn("tar", args, {
26
+ cwd,
27
+ stdio: ["ignore", "pipe", "pipe"]
28
+ });
29
+ let stdout = "";
30
+ let stderr = "";
31
+ child.stdout.on("data", (chunk) => {
32
+ stdout += chunk.toString();
33
+ });
34
+ child.stderr.on("data", (chunk) => {
35
+ stderr += chunk.toString();
36
+ });
37
+ child.on("error", reject);
38
+ child.on("close", (code) => {
39
+ if (code !== 0) {
40
+ reject(new Error(stderr.trim() || `tar exited with code ${code}`));
41
+ return;
42
+ }
43
+ resolve(stdout);
44
+ });
45
+ });
46
+ }
47
+ async function getArchivePrefix(archivePath) {
48
+ const output = await runTar(["-tf", archivePath], process.cwd());
49
+ const firstLine = output.split(/\r?\n/).find(Boolean);
50
+ if (!firstLine) {
51
+ throw new Error(`Archive "${archivePath}" is empty.`);
52
+ }
53
+ const [prefix] = firstLine.split("/");
54
+ if (!prefix) {
55
+ throw new Error(`Could not detect archive prefix for "${archivePath}".`);
56
+ }
57
+ return prefix;
58
+ }
59
+ async function extractArchiveEntry(input) {
60
+ const prefix = await getArchivePrefix(input.archivePath);
61
+ await runTar(["-xzf", input.archivePath, "-C", input.destinationDir, `${prefix}/${input.entryPath}`], process.cwd());
62
+ return path.join(input.destinationDir, prefix, input.entryPath);
63
+ }
64
+ async function readArchiveEntryText(input) {
65
+ const tempRoot = await mkdtemp(path.join(os.tmpdir(), "ai-tools-manifest-"));
66
+ try {
67
+ const extractedPath = await extractArchiveEntry({
68
+ archivePath: input.archivePath,
69
+ entryPath: input.entryPath,
70
+ destinationDir: tempRoot
71
+ });
72
+ return await readFile(extractedPath, "utf8");
73
+ }
74
+ finally {
75
+ await rm(tempRoot, { recursive: true, force: true });
76
+ }
77
+ }
78
+ export function createGitHubClient(config) {
79
+ const cacheRoot = path.join(os.homedir(), ".ai-tools", "cache");
80
+ const archiveCacheRoot = path.join(cacheRoot, "archives");
81
+ async function listBranches() {
82
+ const url = `https://api.github.com/repos/${config.owner}/${config.repo}/branches?per_page=100`;
83
+ const branches = await fetchJson(url);
84
+ return branches.map((branch) => ({
85
+ name: branch.name,
86
+ sha: branch.commit?.sha || "unknown"
87
+ }));
88
+ }
89
+ async function getArchive(input) {
90
+ await ensureDirectory(archiveCacheRoot);
91
+ const archivePath = path.join(archiveCacheRoot, `${input.branch}-${input.sha}.tar.gz`);
92
+ try {
93
+ await stat(archivePath);
94
+ return archivePath;
95
+ }
96
+ catch {
97
+ // Download on cache miss.
98
+ }
99
+ const archiveUrl = `https://codeload.github.com/${config.owner}/${config.repo}/tar.gz/refs/heads/${encodeURIComponent(input.branch)}`;
100
+ const response = await fetch(archiveUrl, {
101
+ headers: {
102
+ "user-agent": "ai-tools"
103
+ }
104
+ });
105
+ if (!response.ok) {
106
+ throw new Error(`Failed to download branch "${input.branch}" (${response.status}).`);
107
+ }
108
+ const archiveBuffer = Buffer.from(await response.arrayBuffer());
109
+ const tempArchivePath = `${archivePath}.tmp`;
110
+ await writeFile(tempArchivePath, archiveBuffer);
111
+ await rename(tempArchivePath, archivePath);
112
+ return archivePath;
113
+ }
114
+ async function fetchManifest(input) {
115
+ const archivePath = await getArchive({ branch: input.branch, sha: input.sha });
116
+ const text = await readArchiveEntryText({
117
+ archivePath,
118
+ entryPath: input.manifestPath
119
+ });
120
+ return JSON.parse(text);
121
+ }
122
+ return {
123
+ config,
124
+ listBranches,
125
+ fetchManifest,
126
+ getArchive,
127
+ extractArchiveEntry
128
+ };
129
+ }
@@ -0,0 +1,95 @@
1
+ import { access, cp, mkdir, mkdtemp, rm } from "node:fs/promises";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { normalizeManifestPath, resolveInsideRoot } from "./paths.js";
5
+ export function resolveInstallRoot(input) {
6
+ const homeDir = os.homedir();
7
+ const globalRoot = input.agent === "codex" ? path.join(homeDir, ".codex") : path.join(homeDir, ".claude");
8
+ const localRoot = input.agent === "codex" ? path.join(input.cwd, ".codex") : path.join(input.cwd, ".claude");
9
+ if (input.location === "global") {
10
+ return globalRoot;
11
+ }
12
+ if (input.location === "local") {
13
+ return localRoot;
14
+ }
15
+ throw new Error(`Unsupported install location "${input.location}".`);
16
+ }
17
+ function defaultOutputPath(item, agent) {
18
+ if (agent === "codex") {
19
+ return path.posix.join("skills", item.id);
20
+ }
21
+ return path.posix.join("agents", `${item.id}.md`);
22
+ }
23
+ export function planInstallations(input) {
24
+ return input.items.map((item) => {
25
+ const target = item.targets[input.agent];
26
+ if (!target) {
27
+ throw new Error(`Skill "${item.id}" does not support the "${input.agent}" agent.`);
28
+ }
29
+ const outputPath = normalizeManifestPath(target.outputPath || defaultOutputPath(item, input.agent), `${item.id}.${input.agent}.outputPath`);
30
+ return {
31
+ ...item,
32
+ agent: input.agent,
33
+ targetType: target.type,
34
+ outputPath,
35
+ targetPath: resolveInsideRoot(input.installRoot, outputPath)
36
+ };
37
+ });
38
+ }
39
+ export async function detectExistingTargets(plannedItems) {
40
+ const existingItems = [];
41
+ for (const item of plannedItems) {
42
+ try {
43
+ await access(item.targetPath);
44
+ existingItems.push(item);
45
+ }
46
+ catch {
47
+ // Target does not exist.
48
+ }
49
+ }
50
+ return existingItems;
51
+ }
52
+ async function copyToTarget(input) {
53
+ await mkdir(path.dirname(input.targetPath), { recursive: true });
54
+ if (input.overwriteExisting) {
55
+ await rm(input.targetPath, { recursive: true, force: true });
56
+ }
57
+ const recursive = input.targetType === "directory";
58
+ await cp(input.sourcePath, input.targetPath, {
59
+ recursive,
60
+ force: input.overwriteExisting,
61
+ errorOnExist: !input.overwriteExisting
62
+ });
63
+ }
64
+ export async function installPlannedItems(input) {
65
+ const results = [];
66
+ const archiveCache = new Map();
67
+ for (const item of input.plannedItems) {
68
+ input.onProgress?.(item);
69
+ let archivePath = archiveCache.get(item.sourceBranch);
70
+ if (!archivePath) {
71
+ archivePath = await input.client.getArchive({
72
+ branch: item.sourceBranch,
73
+ sha: item.sourceSha || "latest"
74
+ });
75
+ archiveCache.set(item.sourceBranch, archivePath);
76
+ }
77
+ const tempDir = await mkdtemp(path.join(os.tmpdir(), "ai-tools-install-"));
78
+ const extractedPath = await input.client.extractArchiveEntry({
79
+ archivePath,
80
+ entryPath: item.sourcePath,
81
+ destinationDir: tempDir
82
+ });
83
+ await copyToTarget({
84
+ sourcePath: extractedPath,
85
+ targetPath: item.targetPath,
86
+ targetType: item.targetType,
87
+ overwriteExisting: input.overwriteExisting
88
+ });
89
+ results.push({
90
+ id: item.id,
91
+ targetPath: item.targetPath
92
+ });
93
+ }
94
+ return results;
95
+ }
@@ -0,0 +1,24 @@
1
+ import * as path from "node:path";
2
+ export function normalizeManifestPath(input, label) {
3
+ if (typeof input !== "string" || input.trim() === "") {
4
+ throw new Error(`${label} must be a non-empty string.`);
5
+ }
6
+ const normalized = path.posix.normalize(input.trim());
7
+ if (normalized === "." ||
8
+ normalized.startsWith("../") ||
9
+ normalized.includes("/../") ||
10
+ normalized.startsWith("/")) {
11
+ throw new Error(`${label} must stay inside the repository root.`);
12
+ }
13
+ return normalized;
14
+ }
15
+ export function resolveInsideRoot(rootPath, relativePath) {
16
+ const absolutePath = path.resolve(rootPath, relativePath);
17
+ const relativeFromRoot = path.relative(rootPath, absolutePath);
18
+ if (relativeFromRoot === ".." ||
19
+ relativeFromRoot.startsWith(`..${path.sep}`) ||
20
+ path.isAbsolute(relativeFromRoot)) {
21
+ throw new Error(`Resolved path escapes install root: ${relativePath}`);
22
+ }
23
+ return absolutePath;
24
+ }
@@ -0,0 +1,98 @@
1
+ import * as process from "node:process";
2
+ import { createInterface } from "node:readline/promises";
3
+ export function createPromptSession() {
4
+ const readline = createInterface({
5
+ input: process.stdin,
6
+ output: process.stdout
7
+ });
8
+ return {
9
+ async ask(question) {
10
+ return readline.question(question);
11
+ },
12
+ async close() {
13
+ readline.close();
14
+ }
15
+ };
16
+ }
17
+ function parseNumericSelection(input, maxIndex, allowEmpty) {
18
+ const trimmed = input.trim();
19
+ if (trimmed === "") {
20
+ if (allowEmpty) {
21
+ return [];
22
+ }
23
+ throw new Error("At least one option must be selected.");
24
+ }
25
+ if (trimmed.toLowerCase() === "all") {
26
+ return Array.from({ length: maxIndex }, (_, index) => index + 1);
27
+ }
28
+ const rawValues = trimmed.split(",").map((item) => item.trim());
29
+ const indexes = new Set();
30
+ for (const rawValue of rawValues) {
31
+ const number = Number.parseInt(rawValue, 10);
32
+ if (!Number.isInteger(number) || number < 1 || number > maxIndex) {
33
+ throw new Error(`"${rawValue}" is not a valid selection.`);
34
+ }
35
+ indexes.add(number);
36
+ }
37
+ return [...indexes].sort((a, b) => a - b);
38
+ }
39
+ function printChoices(message, choices) {
40
+ console.log("");
41
+ console.log(message);
42
+ for (const [index, choice] of choices.entries()) {
43
+ console.log(`${index + 1}. ${choice.label}`);
44
+ console.log(` ${choice.description}`);
45
+ }
46
+ }
47
+ export async function promptMultiSelect(prompt, options) {
48
+ if (options.choices.length === 0) {
49
+ return [];
50
+ }
51
+ printChoices(options.message, options.choices);
52
+ while (true) {
53
+ const answer = await prompt.ask(`Enter numbers separated by commas${options.allowEmpty ? ", blank for none," : ""} or "all": `);
54
+ try {
55
+ const indexes = parseNumericSelection(answer, options.choices.length, options.allowEmpty ?? false);
56
+ return indexes.map((choiceIndex) => options.choices[choiceIndex - 1].value);
57
+ }
58
+ catch (error) {
59
+ const message = error instanceof Error ? error.message : String(error);
60
+ console.error(message);
61
+ }
62
+ }
63
+ }
64
+ export async function promptSingleSelect(prompt, options) {
65
+ if (options.choices.length === 0) {
66
+ throw new Error(`No choices available for "${options.message}".`);
67
+ }
68
+ if (options.choices.length === 1) {
69
+ return options.choices[0].value;
70
+ }
71
+ printChoices(options.message, options.choices);
72
+ while (true) {
73
+ const answer = await prompt.ask("Enter one number: ");
74
+ const selectedIndex = Number.parseInt(answer.trim(), 10);
75
+ if (Number.isInteger(selectedIndex) &&
76
+ selectedIndex >= 1 &&
77
+ selectedIndex <= options.choices.length) {
78
+ return options.choices[selectedIndex - 1].value;
79
+ }
80
+ console.error(`"${answer.trim()}" is not a valid selection.`);
81
+ }
82
+ }
83
+ export async function promptConfirm(prompt, options) {
84
+ const defaultLabel = options.defaultValue ? "Y/n" : "y/N";
85
+ while (true) {
86
+ const answer = (await prompt.ask(`${options.message} (${defaultLabel}): `)).trim().toLowerCase();
87
+ if (answer === "") {
88
+ return options.defaultValue ?? false;
89
+ }
90
+ if (answer === "y" || answer === "yes") {
91
+ return true;
92
+ }
93
+ if (answer === "n" || answer === "no") {
94
+ return false;
95
+ }
96
+ console.error(`"${answer}" is not a valid answer.`);
97
+ }
98
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@minhluudev/ai-tools",
3
+ "version": "0.1.1",
4
+ "description": "CLI to install AI skills from GitHub branches into Codex and Claude.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/minhluudev/ai-tools.git"
10
+ },
11
+ "homepage": "https://github.com/minhluudev/ai-tools#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/minhluudev/ai-tools/issues"
14
+ },
15
+ "bin": {
16
+ "ai-tools": "dist/src/bin/ai-tools.js"
17
+ },
18
+ "files": [
19
+ "dist/src",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -p tsconfig.json",
24
+ "prepack": "npm run build",
25
+ "test": "npm run build && node --test dist/test/*.test.js"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "engines": {
31
+ "node": ">=22.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^22.15.30",
35
+ "typescript": "^5.8.3"
36
+ },
37
+ "aiTools": {
38
+ "github": {
39
+ "owner": "minhluudev",
40
+ "repo": "ai-tools",
41
+ "defaultBranch": "main",
42
+ "skillsBranch": "skill-general",
43
+ "manifestPath": "ai-tools.catalog.json",
44
+ "excludeBranches": [
45
+ "main",
46
+ "master"
47
+ ]
48
+ }
49
+ }
50
+ }