@iqai/adk-cli
Version:
CLI tool for creating, running, and testing ADK-TS agents
251 lines • 9.67 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorHandlingUtils = void 0;
const node_url_1 = require("node:url");
const zod_1 = require("zod");
const env_utils_1 = require("./env-utils");
class ErrorHandlingUtils {
logger;
constructor(logger) {
this.logger = logger;
}
isMissingEnvError(error) {
if (error instanceof zod_1.ZodError) {
const allMissingVars = error.issues
.filter((issue) => issue.code === "invalid_type" && issue.expected !== "undefined")
.map((issue) => issue.path?.[0])
.filter((v) => !!v);
const requiredMissing = [];
const optionalMissing = [];
const optionalPatterns = [
/^.*_DEBUG$/i,
/^.*_ENABLED$/i,
/^PORT$/i,
/^HOST$/i,
/^NODE_ENV$/i,
/^ADK_/i,
];
for (const varName of allMissingVars) {
if (optionalPatterns.some((p) => p.test(varName)))
optionalMissing.push(varName);
else
requiredMissing.push(varName);
}
if (allMissingVars.length > 0) {
return {
isMissing: true,
varName: allMissingVars[0],
allMissing: allMissingVars,
requiredMissing,
optionalMissing,
hasOnlyOptionalMissing: requiredMissing.length === 0 && optionalMissing.length > 0,
};
}
}
return { isMissing: false };
}
async handleImportError(error, outFile, projectRoot) {
const envUtils = new env_utils_1.EnvUtils(this.logger);
const envCheck = this.isMissingEnvError(error);
if (envCheck.isMissing) {
if (envCheck.hasOnlyOptionalMissing) {
this.logger.warn(`⚠️ Missing optional environment variables: ${envCheck.optionalMissing?.join(", ")}`);
}
else {
this.logger.error(envUtils.generateEnvErrorMessage(projectRoot, envCheck.varName, envCheck.requiredMissing ?? envCheck.allMissing));
throw new Error(`Missing required environment variable${envCheck.requiredMissing?.length &&
envCheck.requiredMissing.length > 1
? "s"
: ""}: ${(envCheck.requiredMissing ?? envCheck.allMissing)?.join(", ")}`);
}
}
try {
return (await Promise.resolve(`${(0, node_url_1.pathToFileURL)(outFile).href}`).then(s => __importStar(require(s))));
}
catch (fallbackErr) {
throw new Error(`Failed to load agent: ${fallbackErr instanceof Error
? fallbackErr.message
: String(fallbackErr)}`);
}
}
/**
* Formats Zod or runtime errors into a human-readable string
*/
formatUserError(error) {
if (error instanceof zod_1.ZodError) {
const issues = error.issues.map((i) => {
const path = i.path?.length ? i.path.join(".") : "(root)";
return ` • ${path}: ${i.message}`;
});
return [
"",
"❌ Validation Error",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"Agent configuration or schema validation failed:",
"",
...issues,
"",
"💡 Tip: Check your agent's state schema, tools configuration,",
" or environment variable validation.",
"",
].join("\n");
}
if (error instanceof Error) {
const category = this.categorizeErrorForConsole(error);
const lines = [
"",
`❌ ${category.title}`,
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
this.cleanErrorMessage(error.message),
];
if (category.suggestions.length > 0) {
lines.push("");
lines.push(...category.suggestions.map((s) => `💡 ${s}`));
}
// Only show stack in debug mode
if (error.stack && process.env.ADK_DEBUG_NEST === "1") {
lines.push("");
lines.push("Stack trace:");
lines.push(error.stack);
}
lines.push("");
return lines.join("\n");
}
return [
"",
"❌ Unknown Error",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
String(error),
"",
].join("\n");
}
/**
* Categorize error for console output with helpful suggestions
*/
categorizeErrorForConsole(error) {
const msg = error.message.toLowerCase();
// Agent loading errors
if (msg.includes("failed to load agent") ||
msg.includes("failed to import")) {
return {
title: "Agent Loading Error",
suggestions: [
"Check your agent.ts file for syntax errors",
"Ensure all imports are correct",
"Verify dependencies are installed (npm install)",
],
};
}
// Module not found
if (msg.includes("cannot find module")) {
const moduleName = this.extractModuleName(error.message);
return {
title: "Module Not Found",
suggestions: moduleName
? [
`Install the missing module: npm install ${moduleName}`,
"Or add it to your package.json dependencies",
]
: [
"Check your imports and package.json",
"Run: npm install or pnpm install",
],
};
}
// Syntax errors
if (error.name === "SyntaxError") {
return {
title: "Syntax Error",
suggestions: [
"Review your TypeScript/JavaScript code",
"Check for missing brackets, quotes, or semicolons",
],
};
}
// Type errors
if (error.name === "TypeError") {
return {
title: "Type Error",
suggestions: [
"Check for null or undefined values",
"Verify object properties exist before accessing them",
],
};
}
// Agent not found
if (msg.includes("agent not found")) {
return {
title: "Agent Not Found",
suggestions: [
"Verify the agent path is correct",
"Run 'adk list' to see available agents",
],
};
}
// Runtime/execution errors
if (msg.includes("runtime") ||
msg.includes("execution") ||
msg.includes("failed executing")) {
return {
title: "Agent Runtime Error",
suggestions: ["Review your agent's code for runtime issues"],
};
}
// Generic error
return {
title: error.name || "Error",
suggestions: [],
};
}
/**
* Clean up error messages by removing redundant prefixes
*/
cleanErrorMessage(message) {
return message
.replace(/^Error:\s*/i, "")
.replace(/^Failed to\s+/i, "Failed to ")
.trim();
}
/**
* Extract module name from error message
*/
extractModuleName(message) {
const match = message.match(/Cannot find module ['"]([^'"]+)['"]/);
return match ? match[1] : null;
}
}
exports.ErrorHandlingUtils = ErrorHandlingUtils;
//# sourceMappingURL=error-handling-utils.js.map