@aigne/cli 1.26.1-0 → 1.27.0

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.
@@ -12,109 +12,94 @@ import { isV1Package, toAIGNEPackage } from "../utils/agent-v1.js";
12
12
  import { downloadAndExtract } from "../utils/download.js";
13
13
  import { loadAIGNE } from "../utils/load-aigne.js";
14
14
  import { createRunAIGNECommand, parseAgentInputByCommander, runAgentWithAIGNE, } from "../utils/run-with-aigne.js";
15
- export function createRunCommand({ aigneFilePath, } = {}) {
16
- return {
17
- command: "run [path]",
18
- describe: "Run AIGNE from the specified agent",
19
- builder: (yargs) => {
20
- return createRunAIGNECommand(yargs)
21
- .positional("path", {
22
- describe: "Path to the agents directory or URL to aigne project",
23
- type: "string",
24
- default: ".",
25
- alias: ["url"],
26
- })
27
- .option("entry-agent", {
28
- describe: "Name of the agent to run (defaults to the first agent found)",
29
- type: "string",
30
- })
31
- .option("cache-dir", {
32
- describe: "Directory to download the package to (defaults to the ~/.aigne/xxx)",
33
- type: "string",
34
- });
35
- },
36
- handler: async (argv) => {
37
- const options = argv;
38
- const path = aigneFilePath || options.path;
39
- if (options.logLevel)
40
- logger.level = options.logLevel;
41
- const { cacheDir, dir } = prepareDirs(path, options);
42
- const { aigne, agent } = await new Listr([
43
- {
44
- title: "Prepare environment",
45
- task: (_, task) => {
46
- if (cacheDir) {
47
- return task.newListr([
48
- {
49
- title: "Download package",
50
- task: () => downloadPackage(path, cacheDir),
51
- },
52
- {
53
- title: "Extract package",
54
- task: () => extractPackage(cacheDir, dir),
55
- },
56
- ]);
57
- }
58
- },
59
- },
60
- {
61
- title: "Initialize AIGNE",
62
- task: async (ctx, task) => {
63
- // Load env files in the aigne directory
64
- config({ path: dir, silent: true });
65
- const aigne = await loadAIGNE(dir, { ...options, model: options.model || process.env.MODEL }, {
66
- inquirerPromptFn: (prompt) => {
67
- return task
68
- .prompt(ListrInquirerPromptAdapter)
69
- .run(select, prompt)
70
- .then((res) => ({ [prompt.name]: res }));
15
+ export function createRunCommand({ aigneFilePath } = {}) {
16
+ return createRunAIGNECommand()
17
+ .description("Run AIGNE from the specified agent")
18
+ .option("--url, --path <path_or_url>", "Path to the agents directory or URL to aigne project", ".")
19
+ .option("--entry-agent <entry-agent>", "Name of the agent to run (defaults to the first agent found)")
20
+ .option("--cache-dir <dir>", "Directory to download the package to (defaults to the ~/.aigne/xxx)")
21
+ .action(async (options) => {
22
+ const path = aigneFilePath || options.path;
23
+ if (options.logLevel)
24
+ logger.level = options.logLevel;
25
+ const { cacheDir, dir } = prepareDirs(path, options);
26
+ const { aigne, agent } = await new Listr([
27
+ {
28
+ title: "Prepare environment",
29
+ task: (_, task) => {
30
+ if (cacheDir) {
31
+ return task.newListr([
32
+ {
33
+ title: "Download package",
34
+ task: () => downloadPackage(path, cacheDir),
35
+ },
36
+ {
37
+ title: "Extract package",
38
+ task: () => extractPackage(cacheDir, dir),
71
39
  },
72
- });
73
- ctx.aigne = aigne;
74
- },
40
+ ]);
41
+ }
75
42
  },
76
- {
77
- task: (ctx) => {
78
- const { aigne } = ctx;
79
- assert(aigne);
80
- let entryAgent;
81
- if (options.entryAgent) {
82
- entryAgent = aigne.agents[options.entryAgent];
83
- if (!entryAgent) {
84
- throw new Error(`\
43
+ },
44
+ {
45
+ title: "Initialize AIGNE",
46
+ task: async (ctx, task) => {
47
+ // Load env files in the aigne directory
48
+ config({ path: dir, silent: true });
49
+ const aigne = await loadAIGNE(dir, { ...options, model: options.model || process.env.MODEL }, {
50
+ inquirerPromptFn: (prompt) => {
51
+ return task
52
+ .prompt(ListrInquirerPromptAdapter)
53
+ .run(select, prompt)
54
+ .then((res) => ({ [prompt.name]: res }));
55
+ },
56
+ });
57
+ ctx.aigne = aigne;
58
+ },
59
+ },
60
+ {
61
+ task: (ctx) => {
62
+ const { aigne } = ctx;
63
+ assert(aigne);
64
+ let entryAgent;
65
+ if (options.entryAgent) {
66
+ entryAgent = aigne.agents[options.entryAgent];
67
+ if (!entryAgent) {
68
+ throw new Error(`\
85
69
  Agent "${options.entryAgent}" not found in ${aigne.rootDir}
86
70
 
87
71
  Available agents:
88
72
  ${aigne.agents.map((agent) => ` - ${agent.name}`).join("\n")}
89
73
  `);
90
- }
91
- }
92
- else {
93
- entryAgent = aigne.agents[0];
94
- if (!entryAgent)
95
- throw new Error(`No any agent found in ${aigne.rootDir}`);
96
74
  }
97
- ctx.agent = entryAgent;
98
- },
99
- },
100
- ], {
101
- rendererOptions: {
102
- collapseSubtasks: false,
103
- showErrorMessage: false,
104
- timer: PRESET_TIMER,
75
+ }
76
+ else {
77
+ entryAgent = aigne.agents[0];
78
+ if (!entryAgent)
79
+ throw new Error(`No any agent found in ${aigne.rootDir}`);
80
+ }
81
+ ctx.agent = entryAgent;
105
82
  },
106
- }).run();
107
- assert(aigne);
108
- assert(agent);
109
- const input = await parseAgentInputByCommander(agent, options);
110
- try {
111
- await runAgentWithAIGNE(aigne, agent, { ...options, input });
112
- }
113
- finally {
114
- await aigne.shutdown();
115
- }
116
- },
117
- };
83
+ },
84
+ ], {
85
+ rendererOptions: {
86
+ collapseSubtasks: false,
87
+ showErrorMessage: false,
88
+ timer: PRESET_TIMER,
89
+ },
90
+ }).run();
91
+ assert(aigne);
92
+ assert(agent);
93
+ const input = await parseAgentInputByCommander(agent, options);
94
+ try {
95
+ await runAgentWithAIGNE(aigne, agent, { ...options, input });
96
+ }
97
+ finally {
98
+ await aigne.shutdown();
99
+ }
100
+ })
101
+ .showHelpAfterError(true)
102
+ .showSuggestionAfterError(true);
118
103
  }
119
104
  async function downloadPackage(url, cacheDir) {
120
105
  await rm(cacheDir, { recursive: true, force: true });
@@ -136,7 +121,7 @@ function prepareDirs(path, options) {
136
121
  if (!path.startsWith("http")) {
137
122
  dir = isAbsolute(path) ? path : resolve(process.cwd(), path);
138
123
  }
139
- else if (options?.cacheDir) {
124
+ else if (options.cacheDir) {
140
125
  dir = isAbsolute(options.cacheDir)
141
126
  ? options.cacheDir
142
127
  : resolve(process.cwd(), options.cacheDir);
@@ -148,7 +133,7 @@ function prepareDirs(path, options) {
148
133
  }
149
134
  return { cacheDir, dir };
150
135
  }
151
- export function getLocalPackagePathFromUrl(url, { subdir } = {}) {
136
+ function getLocalPackagePathFromUrl(url, { subdir } = {}) {
152
137
  const root = [homedir(), ".aigne", subdir].filter(isNonNullable);
153
138
  const u = new URL(url);
154
139
  return join(...root, u.hostname, u.pathname);
@@ -1,11 +1,4 @@
1
- import type { CommandModule } from "yargs";
2
- interface ServeMCPOptions {
3
- path: string;
4
- host: string;
5
- port?: number;
6
- pathname: string;
7
- }
8
- export declare function createServeMCPCommand({ aigneFilePath, }?: {
1
+ import { Command } from "commander";
2
+ export declare function createServeMCPCommand({ aigneFilePath }?: {
9
3
  aigneFilePath?: string;
10
- }): CommandModule<{}, ServeMCPOptions>;
11
- export {};
4
+ }): Command;
@@ -1,5 +1,6 @@
1
1
  import { isAbsolute, resolve } from "node:path";
2
2
  import { tryOrThrow } from "@aigne/core/utils/type-utils.js";
3
+ import { Command } from "commander";
3
4
  import { loadAIGNE } from "../utils/load-aigne.js";
4
5
  import { serveMCPServer } from "../utils/serve-mcp.js";
5
6
  const DEFAULT_PORT = () => tryOrThrow(() => {
@@ -11,45 +12,26 @@ const DEFAULT_PORT = () => tryOrThrow(() => {
11
12
  throw new Error(`Invalid PORT: ${PORT}`);
12
13
  return port;
13
14
  }, (error) => new Error(`parse PORT error ${error.message}`));
14
- export function createServeMCPCommand({ aigneFilePath, } = {}) {
15
- return {
16
- command: "serve-mcp",
17
- describe: "Serve the agents in the specified directory as a MCP server (streamable http)",
18
- builder: (yargs) => {
19
- return yargs
20
- .option("path", {
21
- describe: "Path to the agents directory or URL to aigne project",
22
- type: "string",
23
- default: ".",
24
- alias: ["url"],
25
- })
26
- .option("host", {
27
- describe: "Host to run the MCP server on, use 0.0.0.0 to publicly expose the server",
28
- type: "string",
29
- default: "localhost",
30
- })
31
- .option("port", {
32
- describe: "Port to run the MCP server on",
33
- type: "number",
34
- })
35
- .option("pathname", {
36
- describe: "Pathname to the service",
37
- type: "string",
38
- default: "/mcp",
39
- });
40
- },
41
- handler: async (options) => {
42
- const path = aigneFilePath || options.path;
43
- const absolutePath = isAbsolute(path) ? path : resolve(process.cwd(), path);
44
- const port = options.port || DEFAULT_PORT();
45
- const aigne = await loadAIGNE(absolutePath);
46
- await serveMCPServer({
47
- aigne,
48
- host: options.host,
49
- port,
50
- pathname: options.pathname,
51
- });
52
- console.log(`MCP server is running on http://${options.host}:${port}${options.pathname}`);
53
- },
54
- };
15
+ export function createServeMCPCommand({ aigneFilePath } = {}) {
16
+ return new Command("serve-mcp")
17
+ .description("Serve the agents in the specified directory as a MCP server (streamable http)")
18
+ .option("--url, --path <path_or_url>", "Path to the agents directory or URL to aigne project", ".")
19
+ .option("--host <host>", "Host to run the MCP server on, use 0.0.0.0 to publicly expose the server", "localhost")
20
+ .option("--port <port>", "Port to run the MCP server on", (s) => Number.parseInt(s))
21
+ .option("--pathname <pathname>", "Pathname to the service", "/mcp")
22
+ .action(async (options) => {
23
+ const path = aigneFilePath || options.path;
24
+ const absolutePath = isAbsolute(path) ? path : resolve(process.cwd(), path);
25
+ const port = options.port || DEFAULT_PORT();
26
+ const aigne = await loadAIGNE(absolutePath);
27
+ await serveMCPServer({
28
+ aigne,
29
+ host: options.host,
30
+ port,
31
+ pathname: options.pathname,
32
+ });
33
+ console.log(`MCP server is running on http://${options.host}:${port}${options.pathname}`);
34
+ })
35
+ .showHelpAfterError(true)
36
+ .showSuggestionAfterError(true);
55
37
  }
@@ -1,8 +1,4 @@
1
- import type { CommandModule } from "yargs";
2
- interface TestOptions {
3
- path: string;
4
- }
5
- export declare function createTestCommand({ aigneFilePath, }?: {
1
+ import { Command } from "commander";
2
+ export declare function createTestCommand({ aigneFilePath }?: {
6
3
  aigneFilePath?: string;
7
- }): CommandModule<{}, TestOptions>;
8
- export {};
4
+ }): Command;
@@ -1,25 +1,19 @@
1
1
  import assert from "node:assert";
2
2
  import { spawnSync } from "node:child_process";
3
3
  import { isAbsolute, resolve } from "node:path";
4
+ import { Command } from "commander";
4
5
  import { loadAIGNE } from "../utils/load-aigne.js";
5
- export function createTestCommand({ aigneFilePath, } = {}) {
6
- return {
7
- command: "test",
8
- describe: "Run tests in the specified agents directory",
9
- builder: (yargs) => {
10
- return yargs.option("path", {
11
- describe: "Path to the agents directory or URL to aigne project",
12
- type: "string",
13
- default: ".",
14
- alias: ["url"],
15
- });
16
- },
17
- handler: async (options) => {
18
- const path = aigneFilePath || options.path;
19
- const absolutePath = isAbsolute(path) ? path : resolve(process.cwd(), path);
20
- const aigne = await loadAIGNE(absolutePath);
21
- assert(aigne.rootDir);
22
- spawnSync("node", ["--test"], { cwd: aigne.rootDir, stdio: "inherit" });
23
- },
24
- };
6
+ export function createTestCommand({ aigneFilePath } = {}) {
7
+ return new Command("test")
8
+ .description("Run tests in the specified agents directory")
9
+ .option("--url, --path <path_or_url>", "Path to the agents directory or URL to aigne project", ".")
10
+ .action(async (options) => {
11
+ const path = aigneFilePath || options.path;
12
+ const absolutePath = isAbsolute(path) ? path : resolve(process.cwd(), path);
13
+ const aigne = await loadAIGNE(absolutePath);
14
+ assert(aigne.rootDir);
15
+ spawnSync("node", ["--test"], { cwd: aigne.rootDir, stdio: "inherit" });
16
+ })
17
+ .showHelpAfterError(true)
18
+ .showSuggestionAfterError(true);
25
19
  }
@@ -0,0 +1,16 @@
1
+ export interface UserInfoResult {
2
+ user: Record<string, any>;
3
+ enableCredit: boolean;
4
+ creditBalance: {
5
+ balance: string;
6
+ total: string;
7
+ grantCount: number;
8
+ pendingCredit: string;
9
+ } | null;
10
+ paymentLink: string | null;
11
+ profileLink: string;
12
+ }
13
+ export declare function getUserInfo({ baseUrl, accessKey, }: {
14
+ baseUrl: string;
15
+ accessKey: string;
16
+ }): Promise<UserInfoResult>;
@@ -0,0 +1,12 @@
1
+ import { joinURL } from "ufo";
2
+ export async function getUserInfo({ baseUrl, accessKey, }) {
3
+ const response = await fetch(joinURL(baseUrl, "/api/user/info"), {
4
+ headers: {
5
+ Authorization: `Bearer ${accessKey}`,
6
+ },
7
+ });
8
+ if (!response.ok)
9
+ throw new Error(`Failed to fetch user info: ${response.statusText}`);
10
+ const data = await response.json();
11
+ return data;
12
+ }
@@ -1,3 +1 @@
1
- export declare function downloadAndExtract(url: string, dir: string, options?: {
2
- strip?: number;
3
- }): Promise<void>;
1
+ export declare function downloadAndExtract(url: string, dir: string): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { Readable } from "node:stream";
2
2
  import { finished } from "node:stream/promises";
3
3
  import { x } from "tar";
4
- export async function downloadAndExtract(url, dir, options = {}) {
4
+ export async function downloadAndExtract(url, dir) {
5
5
  const response = await fetch(url).catch((error) => {
6
6
  throw new Error(`Failed to download package from ${url}: ${error.message}`);
7
7
  });
@@ -12,7 +12,7 @@ export async function downloadAndExtract(url, dir, options = {}) {
12
12
  throw new Error(`Failed to download package from ${url}: Unexpected to get empty response`);
13
13
  }
14
14
  try {
15
- await finished(Readable.fromWeb(response.body).pipe(x({ C: dir, ...options })));
15
+ await finished(Readable.fromWeb(response.body).pipe(x({ C: dir })));
16
16
  }
17
17
  catch (error) {
18
18
  error.message = `Failed to extract package from ${url}: ${error.message}`;
@@ -1,7 +1,7 @@
1
1
  import { type Agent, AIGNE, type ChatModelOptions, type Message } from "@aigne/core";
2
2
  import { LogLevel } from "@aigne/core/utils/logger.js";
3
3
  import { type PromiseOrValue } from "@aigne/core/utils/type-utils.js";
4
- import type { Argv } from "yargs";
4
+ import { Command } from "commander";
5
5
  import { type ChatLoopOptions } from "./run-chat-loop.js";
6
6
  export interface RunAIGNECommandOptions {
7
7
  chat?: boolean;
@@ -17,31 +17,7 @@ export interface RunAIGNECommandOptions {
17
17
  logLevel?: LogLevel;
18
18
  force?: boolean;
19
19
  }
20
- export declare const createRunAIGNECommand: (yargs: Argv) => Argv<{
21
- chat: boolean;
22
- } & {
23
- model: string | undefined;
24
- } & {
25
- temperature: number | undefined;
26
- } & {
27
- "top-p": number | undefined;
28
- } & {
29
- "presence-penalty": number | undefined;
30
- } & {
31
- "frequency-penalty": number | undefined;
32
- } & {
33
- input: (string | number)[] | undefined;
34
- } & {
35
- format: string | undefined;
36
- } & {
37
- output: string | undefined;
38
- } & {
39
- "output-key": string;
40
- } & {
41
- force: boolean;
42
- } & {
43
- "log-level": LogLevel;
44
- }>;
20
+ export declare const createRunAIGNECommand: (name?: string) => Command;
45
21
  export declare function parseAgentInputByCommander(agent: Agent, options?: RunAIGNECommandOptions & {
46
22
  inputKey?: string;
47
23
  argv?: string[];
@@ -4,90 +4,67 @@ import { dirname, isAbsolute, join } from "node:path";
4
4
  import { isatty } from "node:tty";
5
5
  import { promisify } from "node:util";
6
6
  import { exists } from "@aigne/agent-library/utils/fs.js";
7
- import { AIAgent, AIGNE, DEFAULT_OUTPUT_KEY, readAllString, UserAgent, } from "@aigne/core";
7
+ import { AIGNE, DEFAULT_OUTPUT_KEY, readAllString, UserAgent, } from "@aigne/core";
8
8
  import { loadModel } from "@aigne/core/loader/index.js";
9
9
  import { getLevelFromEnv, LogLevel, logger } from "@aigne/core/utils/logger.js";
10
- import { flat, isEmpty, tryOrThrow, } from "@aigne/core/utils/type-utils.js";
10
+ import { isEmpty, isNonNullable, tryOrThrow, } from "@aigne/core/utils/type-utils.js";
11
11
  import chalk from "chalk";
12
+ import { Command } from "commander";
12
13
  import { parse } from "yaml";
13
- import yargs from "yargs";
14
14
  import { ZodError, ZodObject, z } from "zod";
15
15
  import { availableModels } from "../constants.js";
16
16
  import { TerminalTracer } from "../tracer/terminal.js";
17
17
  import { DEFAULT_CHAT_INPUT_KEY, runChatLoopInTerminal, } from "./run-chat-loop.js";
18
- export const createRunAIGNECommand = (yargs) => yargs
19
- .option("chat", {
20
- describe: "Run chat loop in terminal",
21
- type: "boolean",
22
- default: false,
23
- })
24
- .option("model", {
25
- describe: `AI model to use in format 'provider[:model]' where model is optional. Examples: 'openai' or 'openai:gpt-4o-mini'. Available providers: ${availableModels()
26
- .map((i) => i.name.toLowerCase().replace(/ChatModel$/i, ""))
27
- .join(", ")} (default: openai)`,
28
- type: "string",
29
- })
30
- .option("temperature", {
31
- describe: "Temperature for the model (controls randomness, higher values produce more random outputs). Range: 0.0-2.0",
32
- type: "number",
33
- coerce: customZodError("--temperature", (s) => z.coerce.number().min(0).max(2).parse(s)),
34
- })
35
- .option("top-p", {
36
- describe: "Top P (nucleus sampling) parameter for the model (controls diversity). Range: 0.0-1.0",
37
- type: "number",
38
- coerce: customZodError("--top-p", (s) => z.coerce.number().min(0).max(1).parse(s)),
39
- })
40
- .option("presence-penalty", {
41
- describe: "Presence penalty for the model (penalizes repeating the same tokens). Range: -2.0 to 2.0",
42
- type: "number",
43
- coerce: customZodError("--presence-penalty", (s) => z.coerce.number().min(-2).max(2).parse(s)),
44
- })
45
- .option("frequency-penalty", {
46
- describe: "Frequency penalty for the model (penalizes frequency of token usage). Range: -2.0 to 2.0",
47
- type: "number",
48
- coerce: customZodError("--frequency-penalty", (s) => z.coerce.number().min(-2).max(2).parse(s)),
49
- })
50
- .option("input", {
51
- describe: "Input to the agent, use @<file> to read from a file",
52
- type: "array",
53
- alias: "i",
54
- })
55
- .option("format", {
56
- describe: "Input format for the agent (available: text, json, yaml default: text)",
57
- type: "string",
58
- })
59
- .option("output", {
60
- describe: "Output file to save the result (default: stdout)",
61
- type: "string",
62
- alias: "o",
63
- })
64
- .option("output-key", {
65
- describe: "Key in the result to save to the output file",
66
- type: "string",
67
- default: DEFAULT_OUTPUT_KEY,
68
- })
69
- .option("force", {
70
- describe: "Truncate the output file if it exists, and create directory if the output path is not exists",
71
- type: "boolean",
72
- default: false,
73
- })
74
- .option("log-level", {
75
- describe: `Log level for detailed debugging information. Values: ${Object.values(LogLevel).join(", ")}`,
76
- type: "string",
77
- default: getLevelFromEnv(logger.options.ns) || LogLevel.INFO,
78
- coerce: customZodError("--log-level", (s) => z.nativeEnum(LogLevel).parse(s)),
79
- });
18
+ export const createRunAIGNECommand = (name = "run") => new Command(name)
19
+ .allowUnknownOption(true)
20
+ .allowExcessArguments(true)
21
+ .description("Run agent with AIGNE in terminal")
22
+ .option("--chat", "Run chat loop in terminal", false)
23
+ .option("--model <provider[:model]>", `AI model to use in format 'provider[:model]' where model is optional. Examples: 'openai' or 'openai:gpt-4o-mini'. Available providers: ${availableModels()
24
+ .map((i) => i.name.toLowerCase().replace(/ChatModel$/i, ""))
25
+ .join(", ")} (default: openai)`)
26
+ .option("--temperature <temperature>", "Temperature for the model (controls randomness, higher values produce more random outputs). Range: 0.0-2.0", customZodError("--temperature", (s) => z.coerce.number().min(0).max(2).parse(s)))
27
+ .option("--top-p <top-p>", "Top P (nucleus sampling) parameter for the model (controls diversity). Range: 0.0-1.0", customZodError("--top-p", (s) => z.coerce.number().min(0).max(1).parse(s)))
28
+ .option("--presence-penalty <presence-penalty>", "Presence penalty for the model (penalizes repeating the same tokens). Range: -2.0 to 2.0", customZodError("--presence-penalty", (s) => z.coerce.number().min(-2).max(2).parse(s)))
29
+ .option("--frequency-penalty <frequency-penalty>", "Frequency penalty for the model (penalizes frequency of token usage). Range: -2.0 to 2.0", customZodError("--frequency-penalty", (s) => z.coerce.number().min(-2).max(2).parse(s)))
30
+ .option("--input -i <input...>", "Input to the agent, use @<file> to read from a file")
31
+ .option("--format <format>", "Input format for the agent (available: text, json, yaml default: text)")
32
+ .option("--output -o <output>", "Output file to save the result (default: stdout)")
33
+ .option("--output-key <output-key>", "Key in the result to save to the output file", DEFAULT_OUTPUT_KEY)
34
+ .option("--force", "Truncate the output file if it exists, and create directory if the output path is not exists", false)
35
+ .option("--log-level <level>", `Log level for detailed debugging information. Values: ${Object.values(LogLevel).join(", ")}`, customZodError("--log-level", (s) => z.nativeEnum(LogLevel).parse(s)), getLevelFromEnv(logger.options.ns) || LogLevel.INFO);
80
36
  export async function parseAgentInputByCommander(agent, options = {}) {
81
- const inputSchemaShape = flat(agent instanceof AIAgent ? agent.inputKey : undefined, agent.inputSchema instanceof ZodObject ? Object.keys(agent.inputSchema.shape) : []);
82
- const parsedInput = await yargs().parseAsync(options.argv ?? process.argv);
83
- const input = Object.fromEntries(await Promise.all(inputSchemaShape.map(async (key) => {
84
- const k = `input${key.charAt(0).toUpperCase()}${key.slice(1)}`;
85
- let value = parsedInput[k];
86
- if (typeof value === "string" && value.startsWith("@")) {
87
- value = await readFile(value.slice(1), "utf8");
88
- }
89
- return [key, value];
90
- })));
37
+ const cmd = new Command()
38
+ .description(`Run agent ${agent.name} with AIGNE`)
39
+ .allowUnknownOption(true)
40
+ .allowExcessArguments(true);
41
+ const inputSchemaShape = agent.inputSchema instanceof ZodObject ? Object.keys(agent.inputSchema.shape) : [];
42
+ for (const option of inputSchemaShape) {
43
+ cmd.option(`--input-${option} <${option}>`);
44
+ }
45
+ const input = await new Promise((resolve, reject) => {
46
+ cmd
47
+ .action(async (agentInputOptions) => {
48
+ try {
49
+ const input = Object.fromEntries((await Promise.all(Object.entries(agentInputOptions).map(async ([key, value]) => {
50
+ let k = key.replace(/^input/, "");
51
+ k = k.charAt(0).toLowerCase() + k.slice(1);
52
+ if (!k)
53
+ return null;
54
+ if (typeof value === "string" && value.startsWith("@")) {
55
+ value = await readFile(value.slice(1), "utf8");
56
+ }
57
+ return [k, value];
58
+ }))).filter(isNonNullable));
59
+ resolve(input);
60
+ }
61
+ catch (error) {
62
+ reject(error);
63
+ }
64
+ })
65
+ .parseAsync(options.argv ?? process.argv)
66
+ .catch((error) => reject(error));
67
+ });
91
68
  const rawInput = options.input ||
92
69
  (isatty(process.stdin.fd) || !(await stdinHasData())
93
70
  ? null
@@ -123,8 +100,10 @@ export const parseModelOption = (model) => {
123
100
  return { provider, name };
124
101
  };
125
102
  export async function runWithAIGNE(agentCreator, { argv = process.argv, chatLoopOptions, modelOptions, outputKey, } = {}) {
126
- await yargs()
127
- .command("$0", "Run an agent with AIGNE", (yargs) => createRunAIGNECommand(yargs), async (options) => {
103
+ await createRunAIGNECommand()
104
+ .showHelpAfterError(true)
105
+ .showSuggestionAfterError(true)
106
+ .action(async (options) => {
128
107
  if (options.logLevel) {
129
108
  logger.level = options.logLevel;
130
109
  }
@@ -155,8 +134,6 @@ export async function runWithAIGNE(agentCreator, { argv = process.argv, chatLoop
155
134
  await aigne.shutdown();
156
135
  }
157
136
  })
158
- .alias("h", "help")
159
- .alias("v", "version")
160
137
  .parseAsync(argv)
161
138
  .catch((error) => {
162
139
  console.error(`${chalk.red("Error:")} ${error.message}`);