requestshield 0.1.2 → 0.1.4

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,91 +1,185 @@
1
- // @ts-check
2
-
3
- import { cp, lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { randomUUID } from "node:crypto";
7
- import { CliError } from "../errors.mjs";
8
- import { getAsset, isSea } from "node:sea";
9
-
10
- const skillAsset = "requestshield-skill.md";
11
-
12
- /**
13
- * @param {{ agent: string, force: boolean }} options
14
- * @param {{ env?: NodeJS.ProcessEnv, homeDir?: string, log: (message: string) => void, sourceDir?: string }} deps
15
- */
16
- export async function setupAgent(options, deps) {
17
- if (options.agent !== "codex") {
18
- throw new CliError(`Unsupported agent: ${options.agent}`, { exitCode: 2 });
19
- }
20
- const env = deps.env ?? process.env;
21
- const codexHome = env.CODEX_HOME || path.join(deps.homeDir ?? os.homedir(), ".codex");
22
- const skillsRoot = path.join(codexHome, "skills");
23
- const destination = path.join(skillsRoot, "requestshield");
24
- await mkdir(skillsRoot, { recursive: true });
25
-
26
- const exists = await pathExists(destination);
27
- if (exists && !options.force) {
28
- throw new CliError(`RequestShield skill already exists at ${destination}; use --force to replace it`, {
29
- code: "SKILL_EXISTS",
30
- exitCode: 2,
31
- });
32
- }
33
-
34
- const staging = path.join(skillsRoot, `.requestshield-${randomUUID()}.tmp`);
35
- const backup = `${destination}.${randomUUID()}.backup`;
36
- try {
37
- if (deps.sourceDir) {
38
- // Dùng trong test hoặc khi caller chỉ định source.
39
- await cp(deps.sourceDir, staging, {
40
- recursive: true,
41
- errorOnExist: true,
42
- });
43
- } else if (isSea()) {
44
- // SEA không có thư mục source trên disk, đọc skill đã nhúng.
45
- await mkdir(staging);
46
-
47
- await writeFile(
48
- path.join(staging, "SKILL.md"),
49
- Buffer.from(getAsset(skillAsset)),
50
- );
51
- } else {
52
- // Chạy từ source/npm hoặc chạy bundle CJS trên disk.
53
- //
54
- // src/main.mjs -> ../skills/requestshield
55
- // dist/requestshield.cjs -> ../skills/requestshield
56
- const executableDir = path.dirname(path.resolve(process.argv[1]));
57
- const source = path.resolve(
58
- executableDir,
59
- "../skills/requestshield",
60
- );
61
-
62
- await cp(source, staging, {
63
- recursive: true,
64
- errorOnExist: true,
65
- });
66
- }
67
- if (exists) await rename(destination, backup);
68
- await rename(staging, destination);
69
- if (exists) await rm(backup, { recursive: true, force: true });
70
- } catch (error) {
71
- await rm(staging, { recursive: true, force: true });
72
- if (await pathExists(backup)) {
73
- await rm(destination, { recursive: true, force: true });
74
- await rename(backup, destination);
75
- }
76
- throw error;
77
- }
78
- deps.log(`Installed RequestShield skill for Codex at ${destination}`);
79
- deps.log("Restart Codex or start a new task before using the skill.");
80
- }
81
-
82
- /** @param {string} target */
83
- async function pathExists(target) {
84
- try {
85
- await lstat(target);
86
- return true;
87
- } catch (error) {
88
- if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") return false;
89
- throw error;
90
- }
91
- }
1
+ // @ts-check
2
+
3
+ import { cp, lstat, mkdir, realpath, rename, rm, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { randomUUID } from "node:crypto";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { CliError } from "../errors.mjs";
9
+ import { detectAgents } from "../agent-detector.mjs";
10
+ import { getAsset, isSea } from "node:sea";
11
+
12
+ const skillAsset = "requestshield-skill.md";
13
+
14
+ /**
15
+ * @param {{ agent?: "codex" | "claude", force: boolean }} options
16
+ * @param {{ env?: NodeJS.ProcessEnv, homeDir?: string, log: (message: string) => void, sourceDir?: string, executablePath?: string, detectAgents?: () => Promise<Array<"codex" | "claude">>, selectAgent?: (detected: Array<"codex" | "claude">) => Promise<"codex" | "claude"> }} deps
17
+ */
18
+ export async function setupAgent(options, deps) {
19
+ const agent = await resolveAgent(options.agent, deps);
20
+ const homeDir = deps.homeDir ?? os.homedir();
21
+
22
+ // Codex and Claude discover personal skills from different directories.
23
+ const skillsRoot = agent === "codex"
24
+ ? path.join(homeDir, ".agents", "skills")
25
+ : path.join(homeDir, ".claude", "skills");
26
+ const destination = path.join(skillsRoot, "requestshield");
27
+ await mkdir(skillsRoot, { recursive: true });
28
+
29
+ const exists = await pathExists(destination);
30
+ if (exists && !options.force) {
31
+ throw new CliError(`RequestShield skill already exists at ${destination}; use --force to replace it`, {
32
+ code: "SKILL_EXISTS",
33
+ exitCode: 2,
34
+ });
35
+ }
36
+
37
+ // Copy into a staging directory so an interrupted copy cannot leave a
38
+ // partially installed skill at the final destination.
39
+ const staging = path.join(skillsRoot, `.requestshield-${randomUUID()}.tmp`);
40
+ const backup = `${destination}.${randomUUID()}.backup`;
41
+ try {
42
+ if (deps.sourceDir) {
43
+ // Tests and alternate packagers can provide an explicit skill source.
44
+ await cp(deps.sourceDir, staging, {
45
+ recursive: true,
46
+ errorOnExist: true,
47
+ });
48
+ } else if (isSea()) {
49
+ // A single-executable build reads the skill from its embedded assets.
50
+ await mkdir(staging);
51
+
52
+ await writeFile(
53
+ path.join(staging, "SKILL.md"),
54
+ Buffer.from(getAsset(skillAsset)),
55
+ );
56
+ } else {
57
+ // Source, npm, and on-disk CJS builds keep the skill beside the program.
58
+ //
59
+ // src/main.mjs -> ../skills/requestshield
60
+ // dist/requestshield.cjs -> ../skills/requestshield
61
+ // npm link and global npm installs expose a symlink in their bin folder.
62
+ // Follow it before resolving the adjacent packaged skills directory.
63
+ const executable = await realpath(deps.executablePath ?? process.argv[1]);
64
+ const executableDir = path.dirname(executable);
65
+ const source = path.resolve(
66
+ executableDir,
67
+ "../skills/requestshield",
68
+ );
69
+
70
+ await cp(source, staging, {
71
+ recursive: true,
72
+ errorOnExist: true,
73
+ });
74
+ }
75
+
76
+ // Keep the old installation recoverable until the staged copy is in place.
77
+ if (exists) await rename(destination, backup);
78
+ await rename(staging, destination);
79
+ if (exists) await rm(backup, { recursive: true, force: true });
80
+ } catch (error) {
81
+ await rm(staging, { recursive: true, force: true });
82
+ if (await pathExists(backup)) {
83
+ await rm(destination, { recursive: true, force: true });
84
+ await rename(backup, destination);
85
+ }
86
+ throw error;
87
+ }
88
+ const agentLabel = agent === "codex" ? "Codex" : "Claude";
89
+ deps.log(`Installed RequestShield skill for ${agentLabel} at ${destination}`);
90
+ deps.log(`Restart ${agentLabel} or start a new task before using the skill.`);
91
+ }
92
+
93
+ /**
94
+ * Explicit selection bypasses detection. Automatic setup selects a single
95
+ * detected agent or asks the user when both agents are present.
96
+ *
97
+ * @param {"codex" | "claude" | undefined} requested
98
+ * @param {{ env?: NodeJS.ProcessEnv, homeDir?: string, detectAgents?: () => Promise<Array<"codex" | "claude">>, selectAgent?: (detected: Array<"codex" | "claude">) => Promise<"codex" | "claude"> }} deps
99
+ * @returns {Promise<"codex" | "claude">}
100
+ */
101
+ async function resolveAgent(requested, deps) {
102
+ // A command-line choice is authoritative and avoids probing the machine.
103
+ if (requested) return requested;
104
+
105
+ const detected = deps.detectAgents
106
+ ? await deps.detectAgents()
107
+ : await detectAgents({ env: deps.env, homeDir: deps.homeDir });
108
+
109
+ if (detected.length === 1) return detected[0];
110
+ if (detected.length === 0) {
111
+ throw new CliError(
112
+ [
113
+ "No supported coding agent detected.",
114
+ "",
115
+ "Choose one explicitly:",
116
+ " requestshield agent setup --codex",
117
+ " requestshield agent setup --claude",
118
+ ].join("\n"),
119
+ { code: "AGENT_NOT_FOUND", exitCode: 2 },
120
+ );
121
+ }
122
+
123
+ // Never choose silently when both agents are present. Interactive users get
124
+ // a prompt; non-interactive callers receive a stable conflict error.
125
+ const selectAgent = deps.selectAgent ?? promptForAgent;
126
+ const selected = await selectAgent(detected);
127
+ if (!detected.includes(selected)) {
128
+ throw new CliError(`Selected agent is not available: ${selected}`, {
129
+ code: "INVALID_AGENT",
130
+ exitCode: 2,
131
+ });
132
+ }
133
+ return selected;
134
+ }
135
+
136
+ /**
137
+ * Ask an interactive user which detected agent should receive the skill.
138
+ *
139
+ * @returns {Promise<"codex" | "claude">}
140
+ */
141
+ async function promptForAgent() {
142
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
143
+ throw new CliError(
144
+ [
145
+ "Multiple coding agents detected.",
146
+ "",
147
+ "Choose one explicitly:",
148
+ " requestshield agent setup --codex",
149
+ " requestshield agent setup --claude",
150
+ ].join("\n"),
151
+ { code: "INSTALL_CONFLICT", exitCode: 2 },
152
+ );
153
+ }
154
+
155
+ const prompt = createInterface({
156
+ input: process.stdin,
157
+ output: process.stdout,
158
+ });
159
+ try {
160
+ process.stdout.write(
161
+ "Multiple coding agents detected.\n\n 1. Codex\n 2. Claude\n\n",
162
+ );
163
+ while (true) {
164
+ const answer = (await prompt.question("Select an agent [1-2]: "))
165
+ .trim()
166
+ .toLowerCase();
167
+ if (answer === "1" || answer === "codex") return "codex";
168
+ if (answer === "2" || answer === "claude") return "claude";
169
+ process.stdout.write("Enter 1 for Codex or 2 for Claude.\n");
170
+ }
171
+ } finally {
172
+ prompt.close();
173
+ }
174
+ }
175
+
176
+ /** @param {string} target */
177
+ async function pathExists(target) {
178
+ try {
179
+ await lstat(target);
180
+ return true;
181
+ } catch (error) {
182
+ if (/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT") return false;
183
+ throw error;
184
+ }
185
+ }