@minhluudev/ai-tools 0.1.1 → 1.0.2

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.
@@ -1,39 +1,42 @@
1
- import { access, cp, mkdir, mkdtemp, rm } from "node:fs/promises";
1
+ import { access, cp, mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { normalizeManifestPath, resolveInsideRoot } from "./paths.js";
5
+ const AGENT_INSTALL_DIR = {
6
+ codex: ".codex",
7
+ claude: ".claude"
8
+ };
5
9
  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");
10
+ const dir = AGENT_INSTALL_DIR[input.agent];
9
11
  if (input.location === "global") {
10
- return globalRoot;
12
+ return path.join(os.homedir(), dir);
11
13
  }
12
14
  if (input.location === "local") {
13
- return localRoot;
15
+ return path.join(input.cwd, dir);
14
16
  }
15
17
  throw new Error(`Unsupported install location "${input.location}".`);
16
18
  }
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`);
19
+ export function resolveProjectDocsRoot(cwd) {
20
+ return cwd;
21
+ }
22
+ function defaultOutputPath(item) {
23
+ return path.posix.join("skills", item.id);
22
24
  }
23
25
  export function planInstallations(input) {
24
- return input.items.map((item) => {
26
+ return input.items.flatMap((item) => {
25
27
  const target = item.targets[input.agent];
26
28
  if (!target) {
27
- throw new Error(`Skill "${item.id}" does not support the "${input.agent}" agent.`);
29
+ return [];
28
30
  }
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
- };
31
+ const outputPath = normalizeManifestPath(target.outputPath || defaultOutputPath(item), `${item.id}.${input.agent}.outputPath`);
32
+ return [{
33
+ ...item,
34
+ sourcePath: target.sourcePath ?? item.sourcePath,
35
+ agent: input.agent,
36
+ targetType: target.type,
37
+ outputPath,
38
+ targetPath: resolveInsideRoot(input.installRoot, outputPath)
39
+ }];
37
40
  });
38
41
  }
39
42
  export async function detectExistingTargets(plannedItems) {
@@ -49,6 +52,25 @@ export async function detectExistingTargets(plannedItems) {
49
52
  }
50
53
  return existingItems;
51
54
  }
55
+ export function planProjectDocsInstallations(input) {
56
+ const installRoot = resolveProjectDocsRoot(input.cwd);
57
+ return input.skills.map((skill) => {
58
+ if (!skill.sourceBranch) {
59
+ throw new Error(`Project docs skill "${skill.id}" is missing sourceBranch.`);
60
+ }
61
+ if (!skill.sourcePath) {
62
+ throw new Error(`Project docs skill "${skill.id}" is missing sourcePath.`);
63
+ }
64
+ return {
65
+ id: skill.id,
66
+ label: skill.label,
67
+ description: skill.description,
68
+ sourceBranch: skill.sourceBranch,
69
+ sourcePath: skill.sourcePath,
70
+ targetPath: installRoot
71
+ };
72
+ });
73
+ }
52
74
  async function copyToTarget(input) {
53
75
  await mkdir(path.dirname(input.targetPath), { recursive: true });
54
76
  if (input.overwriteExisting) {
@@ -61,6 +83,22 @@ async function copyToTarget(input) {
61
83
  errorOnExist: !input.overwriteExisting
62
84
  });
63
85
  }
86
+ async function copyDirectoryContents(input) {
87
+ await mkdir(input.targetDir, { recursive: true });
88
+ const entries = await readdir(input.sourceDir, { withFileTypes: true });
89
+ for (const entry of entries) {
90
+ const sourcePath = path.join(input.sourceDir, entry.name);
91
+ const targetPath = path.join(input.targetDir, entry.name);
92
+ if (input.overwriteExisting) {
93
+ await rm(targetPath, { recursive: true, force: true });
94
+ }
95
+ await cp(sourcePath, targetPath, {
96
+ recursive: entry.isDirectory(),
97
+ force: input.overwriteExisting,
98
+ errorOnExist: !input.overwriteExisting
99
+ });
100
+ }
101
+ }
64
102
  export async function installPlannedItems(input) {
65
103
  const results = [];
66
104
  const archiveCache = new Map();
@@ -93,3 +131,34 @@ export async function installPlannedItems(input) {
93
131
  }
94
132
  return results;
95
133
  }
134
+ export async function installProjectDocsItems(input) {
135
+ const results = [];
136
+ const archiveCache = new Map();
137
+ for (const item of input.plannedItems) {
138
+ input.onProgress?.(item);
139
+ let archivePath = archiveCache.get(item.sourceBranch);
140
+ if (!archivePath) {
141
+ archivePath = await input.client.getArchive({
142
+ branch: item.sourceBranch,
143
+ sha: "latest"
144
+ });
145
+ archiveCache.set(item.sourceBranch, archivePath);
146
+ }
147
+ const tempDir = await mkdtemp(path.join(os.tmpdir(), "ai-tools-project-docs-"));
148
+ const extractedPath = await input.client.extractArchiveEntry({
149
+ archivePath,
150
+ entryPath: item.sourcePath,
151
+ destinationDir: tempDir
152
+ });
153
+ await copyDirectoryContents({
154
+ sourceDir: extractedPath,
155
+ targetDir: item.targetPath,
156
+ overwriteExisting: input.overwriteExisting
157
+ });
158
+ results.push({
159
+ id: item.id,
160
+ targetPath: item.targetPath
161
+ });
162
+ }
163
+ return results;
164
+ }
@@ -0,0 +1,45 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import { normalizeManifestPath } from "./paths.js";
4
+ function validateSkillEntry(rawEntry, index) {
5
+ if (!rawEntry || typeof rawEntry !== "object") {
6
+ throw new Error(`Project docs catalog skill #${index + 1} must be an object.`);
7
+ }
8
+ const entry = rawEntry;
9
+ if (typeof entry.id !== "string" || entry.id.trim() === "") {
10
+ throw new Error(`Project docs catalog skill #${index + 1} is missing a valid id.`);
11
+ }
12
+ if (typeof entry.label !== "string" || entry.label.trim() === "") {
13
+ throw new Error(`Project docs catalog skill "${entry.id}" is missing a valid label.`);
14
+ }
15
+ const sourceBranch = typeof entry.sourceBranch === "string" && entry.sourceBranch.trim() !== ""
16
+ ? entry.sourceBranch.trim()
17
+ : undefined;
18
+ const sourcePath = typeof entry.sourcePath === "string" && entry.sourcePath.trim() !== ""
19
+ ? normalizeManifestPath(entry.sourcePath, `${entry.id}.sourcePath`)
20
+ : undefined;
21
+ return {
22
+ id: entry.id.trim(),
23
+ label: entry.label.trim(),
24
+ description: typeof entry.description === "string" && entry.description.trim() !== ""
25
+ ? entry.description.trim()
26
+ : "",
27
+ sourceBranch,
28
+ sourcePath
29
+ };
30
+ }
31
+ export async function loadProjectDocsCatalog(config) {
32
+ const catalogPath = path.join(config.packageRoot, config.projectDocsCatalogPath);
33
+ const rawCatalogText = await readFile(catalogPath, "utf8");
34
+ const rawCatalog = JSON.parse(rawCatalogText);
35
+ if (rawCatalog.version !== 1) {
36
+ throw new Error(`Project docs catalog "${config.projectDocsCatalogPath}" must use version 1.`);
37
+ }
38
+ if (!Array.isArray(rawCatalog.skills)) {
39
+ throw new Error(`Project docs catalog "${config.projectDocsCatalogPath}" must contain a skills array.`);
40
+ }
41
+ return {
42
+ version: 1,
43
+ skills: rawCatalog.skills.map((entry, index) => validateSkillEntry(entry, index))
44
+ };
45
+ }
@@ -1,98 +1,44 @@
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) {
1
+ import { checkbox, confirm, select } from "@inquirer/prompts";
2
+ const PROMPT_CONTEXT = {
3
+ clearPromptOnDone: true
4
+ };
5
+ export async function promptMultiSelect(options) {
48
6
  if (options.choices.length === 0) {
49
7
  return [];
50
8
  }
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
- }
9
+ const selectedValues = await checkbox({
10
+ message: options.message,
11
+ choices: options.choices.map((choice) => ({
12
+ value: choice.value,
13
+ name: choice.label,
14
+ description: choice.description
15
+ })),
16
+ required: !(options.allowEmpty ?? false)
17
+ }, PROMPT_CONTEXT);
18
+ if (selectedValues.length === 0 && !(options.allowEmpty ?? false)) {
19
+ throw new Error("At least one option must be selected.");
62
20
  }
21
+ return selectedValues;
63
22
  }
64
- export async function promptSingleSelect(prompt, options) {
23
+ export async function promptSingleSelect(options) {
65
24
  if (options.choices.length === 0) {
66
25
  throw new Error(`No choices available for "${options.message}".`);
67
26
  }
68
27
  if (options.choices.length === 1) {
69
28
  return options.choices[0].value;
70
29
  }
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
- }
30
+ return select({
31
+ message: options.message,
32
+ choices: options.choices.map((choice) => ({
33
+ value: choice.value,
34
+ name: choice.label,
35
+ description: choice.description
36
+ }))
37
+ }, PROMPT_CONTEXT);
82
38
  }
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
- }
39
+ export async function promptConfirm(options) {
40
+ return confirm({
41
+ message: options.message,
42
+ default: options.defaultValue ?? false
43
+ }, PROMPT_CONTEXT);
98
44
  }
@@ -0,0 +1,140 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import { mergeSelectedItems, validateManifest, validateTarget } from "./catalog.js";
4
+ import { normalizeManifestPath } from "./paths.js";
5
+ function validateSelectionEntry(rawEntry, kind, index) {
6
+ if (!rawEntry || typeof rawEntry !== "object") {
7
+ throw new Error(`Selection catalog ${kind} #${index + 1} must be an object.`);
8
+ }
9
+ const entry = rawEntry;
10
+ if (typeof entry.id !== "string" || entry.id.trim() === "") {
11
+ throw new Error(`Selection catalog ${kind} #${index + 1} is missing a valid id.`);
12
+ }
13
+ if (typeof entry.label !== "string" || entry.label.trim() === "") {
14
+ throw new Error(`Selection catalog ${kind} "${entry.id}" is missing a valid label.`);
15
+ }
16
+ const sourceBranch = typeof entry.sourceBranch === "string" && entry.sourceBranch.trim() !== ""
17
+ ? entry.sourceBranch.trim()
18
+ : undefined;
19
+ const sourcePath = typeof entry.sourcePath === "string" && entry.sourcePath.trim() !== ""
20
+ ? normalizeManifestPath(entry.sourcePath, `${entry.id}.sourcePath`)
21
+ : undefined;
22
+ let targets;
23
+ if (entry.targets && typeof entry.targets === "object" && !Array.isArray(entry.targets)) {
24
+ const rawTargets = entry.targets;
25
+ targets = {};
26
+ for (const agent of ["codex", "claude"]) {
27
+ if (rawTargets[agent]) {
28
+ targets[agent] = validateTarget(rawTargets[agent], agent, entry.id.trim());
29
+ }
30
+ }
31
+ if (Object.keys(targets).length === 0) {
32
+ targets = undefined;
33
+ }
34
+ }
35
+ return {
36
+ id: entry.id.trim(),
37
+ label: entry.label.trim(),
38
+ description: typeof entry.description === "string" && entry.description.trim() !== ""
39
+ ? entry.description.trim()
40
+ : "",
41
+ sourceBranch,
42
+ sourcePath,
43
+ targets
44
+ };
45
+ }
46
+ export async function loadSelectionCatalog(config) {
47
+ const catalogPath = path.join(config.packageRoot, config.selectionCatalogPath);
48
+ const rawCatalogText = await readFile(catalogPath, "utf8");
49
+ const rawCatalog = JSON.parse(rawCatalogText);
50
+ if (rawCatalog.version !== 1) {
51
+ throw new Error(`Selection catalog "${config.selectionCatalogPath}" must use version 1.`);
52
+ }
53
+ if (!Array.isArray(rawCatalog.skills)) {
54
+ throw new Error(`Selection catalog "${config.selectionCatalogPath}" must contain a skills array.`);
55
+ }
56
+ const skills = rawCatalog.skills.map((entry, index) => validateSelectionEntry(entry, "skill", index));
57
+ const groups = Array.isArray(rawCatalog.groups)
58
+ ? rawCatalog.groups.map((entry, index) => validateSelectionEntry(entry, "group", index))
59
+ : [];
60
+ return {
61
+ version: 1,
62
+ skills,
63
+ groups
64
+ };
65
+ }
66
+ async function fetchBranchManifest(client, branch, manifestPath) {
67
+ const rawManifest = await client.fetchManifest({
68
+ branch,
69
+ sha: "latest",
70
+ manifestPath
71
+ });
72
+ return validateManifest(rawManifest, {
73
+ branch,
74
+ manifestPath
75
+ });
76
+ }
77
+ export async function resolveSelectionItems(input) {
78
+ const skillEntries = new Map(input.selectionCatalog.skills.map((entry) => [entry.id, entry]));
79
+ const groupEntries = new Map(input.selectionCatalog.groups.map((entry) => [entry.id, entry]));
80
+ const manifestCache = new Map();
81
+ async function getManifest(branch) {
82
+ const cached = manifestCache.get(branch);
83
+ if (cached) {
84
+ return cached;
85
+ }
86
+ const manifest = await fetchBranchManifest(input.client, branch, input.config.github.manifestPath);
87
+ manifestCache.set(branch, manifest);
88
+ return manifest;
89
+ }
90
+ const selectedSkills = [];
91
+ for (const skillId of input.selectedSkillIds) {
92
+ const selection = skillEntries.get(skillId);
93
+ if (!selection) {
94
+ throw new Error(`Unknown skill id "${skillId}" in selection catalog.`);
95
+ }
96
+ const sourceBranch = selection.sourceBranch || input.config.github.skillsBranch;
97
+ if (selection.sourcePath) {
98
+ selectedSkills.push({
99
+ id: selection.id,
100
+ label: selection.label,
101
+ description: selection.description,
102
+ sourceBranch,
103
+ sourcePath: selection.sourcePath,
104
+ targets: selection.targets ?? { codex: { type: "directory" }, claude: { type: "directory" } }
105
+ });
106
+ continue;
107
+ }
108
+ const manifest = await getManifest(sourceBranch);
109
+ const manifestItem = manifest.items.find((item) => item.id === selection.id);
110
+ if (!manifestItem) {
111
+ throw new Error(`Skill "${selection.id}" was not found in branch "${sourceBranch}".`);
112
+ }
113
+ selectedSkills.push(manifestItem);
114
+ }
115
+ const selectedGroups = [];
116
+ for (const groupId of input.selectedGroupIds) {
117
+ const selection = groupEntries.get(groupId);
118
+ if (!selection) {
119
+ throw new Error(`Unknown group id "${groupId}" in selection catalog.`);
120
+ }
121
+ const sourceBranch = selection.sourceBranch || selection.id;
122
+ const manifest = await getManifest(sourceBranch);
123
+ if (manifest.type !== "group") {
124
+ throw new Error(`Branch "${sourceBranch}" does not expose a group manifest.`);
125
+ }
126
+ selectedGroups.push({
127
+ id: selection.id,
128
+ label: selection.label,
129
+ description: selection.description,
130
+ branch: sourceBranch,
131
+ items: manifest.items
132
+ });
133
+ }
134
+ return mergeSelectedItems({
135
+ individualSkills: selectedSkills,
136
+ groups: selectedGroups,
137
+ selectedSkillIds: input.selectedSkillIds,
138
+ selectedGroupIds: input.selectedGroupIds
139
+ });
140
+ }
@@ -0,0 +1,125 @@
1
+ import blessed from "blessed";
2
+ import { canRun, DEBOUNCE_MOVE_MS, DEBOUNCE_SELECT_MS, renderBannerHeader } from "./tui-utils.js";
3
+ const MENU_ITEMS = [
4
+ {
5
+ id: "install-skills",
6
+ label: "Install agent skills",
7
+ description: "Open the terminal UI to install skills for Codex and Claude."
8
+ },
9
+ {
10
+ id: "install-project-docs",
11
+ label: "Install project docs",
12
+ description: "Install project documentation templates and guidance."
13
+ },
14
+ {
15
+ id: "install-libs",
16
+ label: "Install libs for AI",
17
+ description: "Install shared AI libraries and tooling."
18
+ },
19
+ {
20
+ id: "cancel",
21
+ label: "Cancel",
22
+ description: "Exit without running any installer."
23
+ }
24
+ ];
25
+ function renderItem(item, isActive) {
26
+ const text = `${isActive ? "> " : " "}${item.label}`;
27
+ return isActive ? `{black-fg}{yellow-bg}${text}{/yellow-bg}{/black-fg}` : text;
28
+ }
29
+ export async function runEntryMenu() {
30
+ return new Promise((resolve) => {
31
+ let cursor = 0;
32
+ let lastMoveAt = 0;
33
+ let lastSelectAt = 0;
34
+ const screen = blessed.screen({
35
+ smartCSR: true,
36
+ fullUnicode: true,
37
+ title: "ai-tools"
38
+ });
39
+ const headerBox = blessed.box({
40
+ parent: screen,
41
+ top: 0,
42
+ left: 0,
43
+ width: "100%",
44
+ height: 4,
45
+ tags: true
46
+ });
47
+ const listBox = blessed.list({
48
+ parent: screen,
49
+ top: 6,
50
+ left: 0,
51
+ width: "100%",
52
+ height: 6,
53
+ tags: true,
54
+ keys: false,
55
+ vi: false,
56
+ mouse: false,
57
+ interactive: false,
58
+ style: {
59
+ selected: {
60
+ bold: true,
61
+ fg: "black",
62
+ bg: "yellow"
63
+ }
64
+ }
65
+ });
66
+ const detailBox = blessed.box({
67
+ parent: screen,
68
+ top: 14,
69
+ left: 0,
70
+ width: "100%",
71
+ height: 3,
72
+ tags: true,
73
+ wrap: true
74
+ });
75
+ const footerBox = blessed.box({
76
+ parent: screen,
77
+ bottom: 0,
78
+ left: 0,
79
+ width: "100%",
80
+ height: 1,
81
+ tags: true
82
+ });
83
+ function cleanup() {
84
+ screen.destroy();
85
+ }
86
+ function render() {
87
+ headerBox.setContent(renderBannerHeader("Main menu", "Choose the workflow you want to run."));
88
+ listBox.setItems(MENU_ITEMS.map((item, index) => renderItem(item, index === cursor)));
89
+ listBox.select(cursor);
90
+ detailBox.setContent(`{bold}Details{/bold}\n${MENU_ITEMS[cursor].description}`);
91
+ footerBox.setContent("↑ ↓ move • enter select • q quit");
92
+ screen.render();
93
+ }
94
+ screen.key(["up"], () => {
95
+ if (!canRun(lastMoveAt, DEBOUNCE_MOVE_MS)) {
96
+ return;
97
+ }
98
+ lastMoveAt = Date.now();
99
+ cursor = (cursor - 1 + MENU_ITEMS.length) % MENU_ITEMS.length;
100
+ render();
101
+ });
102
+ screen.key(["down"], () => {
103
+ if (!canRun(lastMoveAt, DEBOUNCE_MOVE_MS)) {
104
+ return;
105
+ }
106
+ lastMoveAt = Date.now();
107
+ cursor = (cursor + 1) % MENU_ITEMS.length;
108
+ render();
109
+ });
110
+ screen.key(["enter"], () => {
111
+ if (!canRun(lastSelectAt, DEBOUNCE_SELECT_MS)) {
112
+ return;
113
+ }
114
+ lastSelectAt = Date.now();
115
+ const action = MENU_ITEMS[cursor].id;
116
+ cleanup();
117
+ resolve(action);
118
+ });
119
+ screen.key(["q", "escape", "C-c"], () => {
120
+ cleanup();
121
+ resolve("cancel");
122
+ });
123
+ render();
124
+ });
125
+ }