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