-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnpm-tools.ts
More file actions
222 lines (196 loc) · 7.52 KB
/
Copy pathnpm-tools.ts
File metadata and controls
222 lines (196 loc) · 7.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { RunnableConfig } from "@langchain/core/runnables";
import { execa } from "execa";
import { z } from "zod";
import tryCatch from "../../utils/try-catch.js";
import { TTools } from "./types.js";
import { createTool, resolveWithinWorkDir } from "./utils.js";
async function runNpm(args: string[] = [], config?: RunnableConfig, opts: { timeout?: number } = {}): Promise<string>
{
const timeout = opts.timeout ?? 120_000; // npm can be slow, allow up to 2 minutes by default
const cwd = resolveWithinWorkDir(".", config?.metadata?.["workDir"]);
const { result, error } = await tryCatch(async () => execa("npm", args, { cwd, timeout, env: { CI: "true", npm_config_color: "always" } }));
// Prefer including both stdout and stderr to capture warnings/info
const stdout = result?.stdout?.toString() ?? "";
const stderr = (result?.stderr?.toString() || (error as any)?.stderr?.toString()) ?? "";
const output = [stdout && `STDOUT:\n${stdout}`.trim(), stderr && `STDERR:\n${stderr}`.trim()].filter(Boolean).join("\n\n");
if (!result)
{
// If execa failed before producing a result (timeout, spawn error, etc.)
const message = (error as Error)?.message ?? "Unknown error";
return `ERROR: npm ${args.join(" ")} failed: ${message}${output ? `\n\n${output}` : ""}`;
}
return output || `npm ${args.join(" ")} produced no output.`;
}
// Destructive tools
async function npmInstall(
{ packages = [], dev = false, exact = false, workspace }: { packages?: string[]; dev?: boolean; exact?: boolean; workspace?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"install",
...packages,
dev ? "--save-dev" : "",
exact ? "--save-exact" : "",
workspace ? "-w" : "",
workspace ?? "",
"--no-audit",
"--no-fund",
"--no-progress",
].filter(Boolean) as string[];
return runNpm(args, config);
}
async function npmUninstall(
{ packages = [], workspace }: { packages?: string[]; workspace?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"uninstall",
...packages,
workspace ? "-w" : "",
workspace ?? "",
"--no-audit",
"--no-fund",
].filter(Boolean) as string[];
return runNpm(args, config);
}
async function npmRun(
{ script, args: scriptArgs = [], workspace }: { script: string; args?: string[]; workspace?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"run",
script,
workspace ? "-w" : "",
workspace ?? "",
"--",
...scriptArgs,
].filter(Boolean) as string[];
return runNpm(args, config);
}
async function npmCi(
{ workspace }: { workspace?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"ci",
workspace ? "-w" : "",
workspace ?? "",
"--no-audit",
"--no-fund",
"--no-progress",
].filter(Boolean) as string[];
return runNpm(args, config, { timeout: 180_000 });
}
// Read-only tools
async function npmLs(
{ depth, json = true, workspace }: { depth?: number; json?: boolean; workspace?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"ls",
json ? "--json" : "",
typeof depth === "number" ? "--depth" : "",
typeof depth === "number" ? String(depth) : "",
workspace ? "-w" : "",
workspace ?? "",
].filter(Boolean) as string[];
return runNpm(args, config);
}
async function npmView(
{ packageName, field }: { packageName: string; field?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"view",
packageName,
field ?? "",
"--json",
].filter(Boolean) as string[];
return runNpm(args, config);
}
async function npmOutdated(
{ json = true, workspace }: { json?: boolean; workspace?: string },
config?: RunnableConfig,
): Promise<string>
{
const args = [
"outdated",
json ? "--json" : "",
workspace ? "-w" : "",
workspace ?? "",
].filter(Boolean) as string[];
return runNpm(args, config);
}
const _tools = [
// destructive
createTool(npmInstall, {
description: "Install dependencies with npm. Supports adding specific packages or performing a full install (no packages). Default flags: --no-audit --no-fund --no-progress.",
schema: z.object({
packages: z.array(z.string()).describe("Packages to add (e.g., ['lodash@^4']). If omitted, runs a full install.").optional().default([]),
dev: z.boolean().describe("Install as devDependency.").optional().default(false),
exact: z.boolean().describe("Save exact version with --save-exact.").optional().default(false),
workspace: z.string().describe("Workspace name or path to run the command in.").optional(),
}),
metadata: { destructive: true },
}),
createTool(npmUninstall, {
description: "Remove dependencies with npm.",
schema: z.object({
packages: z.array(z.string()).describe("Packages to remove.").optional().default([]),
workspace: z.string().describe("Workspace name or path to run the command in.").optional(),
}),
metadata: { destructive: true },
}),
createTool(npmRun, {
description: "Run an npm script (npm run <script> -- <args...>).",
schema: z.object({
script: z.string().describe("The script name from package.json to run."),
args: z.array(z.string()).describe("Additional arguments passed after --.").optional().default([]),
workspace: z.string().describe("Workspace name or path to run the command in.").optional(),
}),
metadata: { destructive: true },
}),
createTool(npmCi, {
description: "Run npm ci for reproducible installs. Default flags: --no-audit --no-fund --no-progress.",
schema: z.object({
workspace: z.string().describe("Workspace name or path to run the command in.").optional(),
}),
metadata: { destructive: true },
}),
// read-only
createTool(npmLs, {
description: "List installed dependencies (npm ls). Useful for inspection.",
schema: z.object({
depth: z.number().describe("Max depth to traverse dependency tree.").optional(),
json: z.boolean().describe("Output JSON.").optional().default(true),
workspace: z.string().describe("Workspace name or path to run the command in.").optional(),
}),
}),
createTool(npmView, {
description: "View package metadata from the registry (npm view <pkg> [field]). Outputs JSON.",
schema: z.object({
packageName: z.string().describe("The package name to query (optionally with version/tag)."),
field: z.string().describe("Optional field to fetch (e.g., 'versions', 'dist-tags.latest').").optional(),
}),
}),
createTool(npmOutdated, {
description: "Check for outdated dependencies (npm outdated).",
schema: z.object({
json: z.boolean().describe("Output JSON.").optional().default(true),
workspace: z.string().describe("Workspace name or path to run the command in.").optional(),
}),
}),
];
function getTools(props: { includeDestructiveTools?: boolean }): TTools
{
return _tools
.filter(t => props.includeDestructiveTools || !t.metadata?.["destructive"])
.reduce((tools, t) => ({ ...tools, [t.name]: t }), {});
}
export { getTools };