@defai.digital/ax-cli 3.6.2 → 3.7.2

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.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * SDK Error Codes for programmatic error handling
3
+ *
4
+ * Use these codes to distinguish between different error types
5
+ * instead of parsing error messages.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * try {
10
+ * await createAgent();
11
+ * } catch (error) {
12
+ * if (error instanceof SDKError) {
13
+ * switch (error.code) {
14
+ * case SDKErrorCode.SETUP_NOT_RUN:
15
+ * console.log('Run ax-cli setup first');
16
+ * break;
17
+ * case SDKErrorCode.API_KEY_MISSING:
18
+ * console.log('API key not configured');
19
+ * break;
20
+ * }
21
+ * }
22
+ * }
23
+ * ```
24
+ */
25
+ export var SDKErrorCode;
26
+ (function (SDKErrorCode) {
27
+ /** ax-cli setup has not been run */
28
+ SDKErrorCode["SETUP_NOT_RUN"] = "SDK_SETUP_NOT_RUN";
29
+ /** API key is not configured in settings */
30
+ SDKErrorCode["API_KEY_MISSING"] = "SDK_API_KEY_MISSING";
31
+ /** Base URL is not configured in settings */
32
+ SDKErrorCode["BASE_URL_MISSING"] = "SDK_BASE_URL_MISSING";
33
+ /** Agent has been disposed and cannot be used */
34
+ SDKErrorCode["AGENT_DISPOSED"] = "SDK_AGENT_DISPOSED";
35
+ /** Input validation failed */
36
+ SDKErrorCode["VALIDATION_ERROR"] = "SDK_VALIDATION_ERROR";
37
+ /** Operation was aborted by user */
38
+ SDKErrorCode["ABORTED"] = "SDK_ABORTED";
39
+ /** Rate limit exceeded */
40
+ SDKErrorCode["RATE_LIMIT_EXCEEDED"] = "SDK_RATE_LIMIT_EXCEEDED";
41
+ /** Invalid configuration */
42
+ SDKErrorCode["INVALID_CONFIG"] = "SDK_INVALID_CONFIG";
43
+ /** Internal SDK error */
44
+ SDKErrorCode["INTERNAL_ERROR"] = "SDK_INTERNAL_ERROR";
45
+ })(SDKErrorCode || (SDKErrorCode = {}));
46
+ /**
47
+ * Structured error class for SDK errors
48
+ *
49
+ * Provides error codes for programmatic handling and preserves
50
+ * error chains for debugging.
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * throw new SDKError(
55
+ * SDKErrorCode.API_KEY_MISSING,
56
+ * 'No API key configured. Please run "ax-cli setup".',
57
+ * originalError
58
+ * );
59
+ * ```
60
+ */
61
+ export class SDKError extends Error {
62
+ code;
63
+ cause;
64
+ /**
65
+ * Create a new SDK error
66
+ *
67
+ * @param code - Error code for programmatic handling
68
+ * @param message - Human-readable error message
69
+ * @param cause - Original error that caused this error (optional)
70
+ */
71
+ constructor(code, message, cause) {
72
+ super(message);
73
+ this.code = code;
74
+ this.cause = cause;
75
+ this.name = 'SDKError';
76
+ // Maintain proper stack trace in V8 environments
77
+ if (Error.captureStackTrace) {
78
+ Error.captureStackTrace(this, SDKError);
79
+ }
80
+ }
81
+ /**
82
+ * Type guard to check if an error is an SDKError
83
+ *
84
+ * @param error - Error to check
85
+ * @returns True if error is an SDKError
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * try {
90
+ * await createAgent();
91
+ * } catch (error) {
92
+ * if (SDKError.isSDKError(error)) {
93
+ * console.log('SDK error:', error.code);
94
+ * }
95
+ * }
96
+ * ```
97
+ */
98
+ static isSDKError(error) {
99
+ return error instanceof SDKError;
100
+ }
101
+ /**
102
+ * Convert error to JSON (excludes cause to prevent circular refs)
103
+ */
104
+ toJSON() {
105
+ return {
106
+ name: this.name,
107
+ code: this.code,
108
+ message: this.message,
109
+ // Exclude cause to prevent circular references
110
+ // and avoid leaking sensitive information
111
+ };
112
+ }
113
+ /**
114
+ * Custom inspect for Node.js util.inspect
115
+ */
116
+ [Symbol.for('nodejs.util.inspect.custom')]() {
117
+ let result = `${this.name} [${this.code}]: ${this.message}`;
118
+ if (this.cause) {
119
+ result += `\n Caused by: ${this.cause.message}`;
120
+ }
121
+ return result;
122
+ }
123
+ }
124
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/sdk/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAN,IAAY,YA2BX;AA3BD,WAAY,YAAY;IACtB,oCAAoC;IACpC,mDAAmC,CAAA;IAEnC,4CAA4C;IAC5C,uDAAuC,CAAA;IAEvC,6CAA6C;IAC7C,yDAAyC,CAAA;IAEzC,iDAAiD;IACjD,qDAAqC,CAAA;IAErC,8BAA8B;IAC9B,yDAAyC,CAAA;IAEzC,oCAAoC;IACpC,uCAAuB,CAAA;IAEvB,0BAA0B;IAC1B,+DAA+C,CAAA;IAE/C,4BAA4B;IAC5B,qDAAqC,CAAA;IAErC,yBAAyB;IACzB,qDAAqC,CAAA;AACvC,CAAC,EA3BW,YAAY,KAAZ,YAAY,QA2BvB;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IASf;IAEA;IAVlB;;;;;;OAMG;IACH,YACkB,IAAkB,EAClC,OAAe,EACC,KAAa;QAE7B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,SAAI,GAAJ,IAAI,CAAc;QAElB,UAAK,GAAL,KAAK,CAAQ;QAG7B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QAEvB,iDAAiD;QACjD,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;YAC5B,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;IAED;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,UAAU,CAAC,KAAc;QAC9B,OAAO,KAAK,YAAY,QAAQ,CAAC;IACnC,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,OAAO;YACL,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,+CAA+C;YAC/C,0CAA0C;SAC3C,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,CAAC,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;QACxC,IAAI,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;QAC5D,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,kBAAkB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACnD,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"}
@@ -4,27 +4,51 @@
4
4
  * This SDK allows you to use AX CLI as a library instead of spawning CLI processes.
5
5
  * Perfect for integrations, VSCode extensions, and programmatic AI agent usage.
6
6
  *
7
+ * ## Quick Start
8
+ *
9
+ * 1. Run `ax-cli setup` to configure credentials (one-time setup)
10
+ * 2. Use the SDK in your code
11
+ *
7
12
  * @example
8
13
  * ```typescript
9
- * import { createAgent, getSettingsManager } from '@defai.digital/ax-cli/sdk';
10
- *
11
- * // Initialize settings
12
- * const settings = getSettingsManager();
13
- * await settings.loadUserSettings();
14
+ * import { createAgent, SDKError, SDKErrorCode } from '@defai.digital/ax-cli/sdk';
14
15
  *
15
- * // Create agent
16
+ * // Create agent (credentials from ax-cli setup)
16
17
  * const agent = await createAgent({
17
- * model: 'glm-4.6',
18
- * maxToolRounds: 50
18
+ * maxToolRounds: 50 // Optional: 1-1000, default 400
19
19
  * });
20
20
  *
21
- * // Listen to streaming responses
22
- * agent.on('stream', (chunk) => {
23
- * console.log(chunk.content);
24
- * });
21
+ * try {
22
+ * // Listen to streaming responses
23
+ * agent.on('stream', (chunk) => {
24
+ * if (chunk.type === 'content') {
25
+ * console.log(chunk.content);
26
+ * }
27
+ * });
28
+ *
29
+ * // Process messages
30
+ * const result = await agent.processUserMessage('List all TypeScript files');
31
+ * console.log('Done!', result.length, 'messages');
32
+ * } catch (error) {
33
+ * // Handle structured errors
34
+ * if (SDKError.isSDKError(error)) {
35
+ * if (error.code === SDKErrorCode.SETUP_NOT_RUN) {
36
+ * console.error('Please run: ax-cli setup');
37
+ * }
38
+ * }
39
+ * } finally {
40
+ * // Always cleanup resources
41
+ * await agent.dispose();
42
+ * }
43
+ * ```
44
+ *
45
+ * ## Testing
46
+ *
47
+ * ```typescript
48
+ * import { createMockAgent } from '@defai.digital/ax-cli/sdk/testing';
25
49
  *
26
- * // Process messages
27
- * const result = await agent.processUserMessage('List all TypeScript files');
50
+ * const mockAgent = createMockAgent(['Response 1', 'Response 2']);
51
+ * const result = await mockAgent.processUserMessage('Test');
28
52
  * ```
29
53
  *
30
54
  * @packageDocumentation
@@ -50,47 +74,97 @@ export { buildSystemPrompt } from '../utils/prompt-builder.js';
50
74
  export { getUsageTracker } from '../utils/usage-tracker.js';
51
75
  export { extractErrorMessage, createErrorMessage, ErrorCategory } from '../utils/error-handler.js';
52
76
  export { loadMCPConfig } from '../mcp/config.js';
53
- export { getMCPManager, initializeMCPServers } from '../llm/tools.js';
77
+ export { getMCPManager, initializeMCPServers, getMcpConnectionCount } from '../llm/tools.js';
54
78
  export type { MCPConfig } from '../mcp/config.js';
55
- export type { MCPServerConfig } from '../mcp/client.js';
79
+ export type { MCPServerConfig, MCPTool } from '../mcp/client.js';
80
+ export { MCPManager } from '../mcp/client.js';
56
81
  export { getTaskPlanner, isComplexRequest } from '../planner/index.js';
57
82
  export type { TaskPlanner, TaskPlan, TaskPhase, PhaseResult, PlanResult, } from '../planner/index.js';
58
83
  export { getCheckpointManager } from '../checkpoint/index.js';
59
84
  export type { CheckpointManager, Checkpoint } from '../checkpoint/index.js';
60
- export { GLM_MODELS, DEFAULT_MODEL, AGENT_CONFIG, PLANNER_CONFIG, type SupportedModel, } from '../constants.js';
85
+ export { ContextStore, getContextStore, resetDefaultStore } from '../memory/context-store.js';
86
+ export type { StoreResult } from '../memory/context-store.js';
87
+ export type { ProjectMemory, CacheStats } from '../memory/types.js';
88
+ export { ProgressReporter, getProgressReporter, ProgressEventType, type ProgressEvent } from './progress-reporter.js';
89
+ export { UnifiedLogger, getUnifiedLogger, LogLevel, parseLogLevel, getLogLevelName, type LogEntry, type LogSource, type LogFilter } from './unified-logger.js';
90
+ export { ToolRegistry, getToolRegistry, registerTools, createToolExecutor, type RegisteredTool, type ToolExecutor, type ToolExecutionContext, type ToolRegistrationOptions } from './tool-registry.js';
91
+ export { GLM_MODELS, DEFAULT_MODEL, AGENT_CONFIG, PLANNER_CONFIG, VerbosityLevel, UI_CONFIG, type SupportedModel, } from '../constants.js';
92
+ export { SDK_VERSION, SDK_API_VERSION, getSDKVersion, getSDKInfo, } from './version.js';
93
+ export { SDKError, SDKErrorCode } from './errors.js';
94
+ export { MockAgent, createMockAgent, MockSettingsManager, createMockSettings, } from './testing.js';
61
95
  /**
62
96
  * Agent configuration options for SDK users
97
+ *
98
+ * SECURITY: Credentials (apiKey, baseURL) must be configured via "ax-cli setup"
99
+ * and are NOT exposed through the SDK API to prevent security vulnerabilities.
63
100
  */
64
101
  export interface AgentOptions {
65
- /** API key (optional, will use settings if not provided) */
66
- apiKey?: string;
67
- /** Model to use (optional, will use settings if not provided) */
68
- model?: string;
69
- /** Base URL for API (optional, will use settings if not provided) */
70
- baseURL?: string;
71
- /** Maximum number of tool execution rounds */
102
+ /** Maximum number of tool execution rounds (1-1000, default: 400) */
72
103
  maxToolRounds?: number;
104
+ /**
105
+ * Enable debug mode for verbose logging
106
+ *
107
+ * When enabled, the SDK will log detailed information about:
108
+ * - Agent initialization
109
+ * - Message processing
110
+ * - Tool executions
111
+ * - Errors and warnings
112
+ *
113
+ * Debug logs are written to stderr and prefixed with [AX SDK DEBUG].
114
+ *
115
+ * @default false
116
+ */
117
+ debug?: boolean;
73
118
  }
74
119
  /**
75
120
  * Create a new LLM Agent with configuration
76
121
  *
77
- * @param options - Agent configuration options
122
+ * SECURITY: All credentials (API key, base URL, model) must be configured
123
+ * via "ax-cli setup" command. This prevents security vulnerabilities where
124
+ * credentials could be exposed in code or logs.
125
+ *
126
+ * @param options - Agent configuration options (non-sensitive only)
78
127
  * @returns Configured LLM Agent instance
128
+ * @throws {SDKError} With code SETUP_NOT_RUN if ax-cli setup has not been run
129
+ * @throws {SDKError} With code API_KEY_MISSING if API key not configured
130
+ * @throws {SDKError} With code BASE_URL_MISSING if base URL not configured
131
+ * @throws {SDKError} With code VALIDATION_ERROR if options are invalid
79
132
  *
80
133
  * @example
81
134
  * ```typescript
135
+ * import { createAgent, SDKError, SDKErrorCode } from '@defai.digital/ax-cli/sdk';
136
+ *
137
+ * // First, user must run: ax-cli setup
138
+ * // Then use SDK with settings from setup:
139
+ *
82
140
  * const agent = await createAgent({
83
- * model: 'glm-4.6',
84
- * maxToolRounds: 50
141
+ * maxToolRounds: 50 // Optional: 1-1000, default 400
85
142
  * });
86
143
  *
87
- * agent.on('stream', (chunk) => {
88
- * if (chunk.type === 'content') {
89
- * console.log(chunk.content);
144
+ * try {
145
+ * agent.on('stream', (chunk) => {
146
+ * if (chunk.type === 'content') {
147
+ * console.log(chunk.content);
148
+ * }
149
+ * });
150
+ *
151
+ * const result = await agent.processUserMessage('Analyze this codebase');
152
+ * console.log(result);
153
+ * } catch (error) {
154
+ * if (SDKError.isSDKError(error)) {
155
+ * switch (error.code) {
156
+ * case SDKErrorCode.SETUP_NOT_RUN:
157
+ * console.error('Run ax-cli setup first');
158
+ * break;
159
+ * case SDKErrorCode.API_KEY_MISSING:
160
+ * console.error('API key not configured');
161
+ * break;
162
+ * }
90
163
  * }
91
- * });
92
- *
93
- * const result = await agent.processUserMessage('Analyze this codebase');
164
+ * } finally {
165
+ * // Always cleanup resources
166
+ * await agent.dispose();
167
+ * }
94
168
  * ```
95
169
  */
96
170
  export declare function createAgent(options?: AgentOptions): Promise<LLMAgent>;
@@ -117,22 +191,18 @@ export declare function createAgent(options?: AgentOptions): Promise<LLMAgent>;
117
191
  */
118
192
  export declare function createSubagent(role: import('../agent/subagent-types.js').SubagentRole, config?: Partial<import('../agent/subagent-types.js').SubagentConfig>): Subagent;
119
193
  /**
120
- * Initialize SDK with configuration
194
+ * Initialize SDK and MCP servers
121
195
  *
122
- * @param config - SDK initialization configuration
196
+ * SECURITY: This function does NOT accept credentials. All credentials must be
197
+ * configured via "ax-cli setup" command. This function only initializes MCP servers.
123
198
  *
124
199
  * @example
125
200
  * ```typescript
126
- * await initializeSDK({
127
- * apiKey: 'your-api-key',
128
- * model: 'glm-4.6',
129
- * baseURL: 'https://api.example.com/v1'
130
- * });
201
+ * // Initialize MCP servers from ax-cli settings
202
+ * await initializeSDK();
131
203
  * ```
204
+ *
205
+ * @deprecated Most SDK users don't need to call this - createAgent() handles initialization.
206
+ * Only call this if you need to pre-initialize MCP servers.
132
207
  */
133
- export declare function initializeSDK(config: {
134
- apiKey?: string;
135
- model?: string;
136
- baseURL?: string;
137
- mcpServers?: Record<string, any>;
138
- }): Promise<void>;
208
+ export declare function initializeSDK(): Promise<void>;
package/dist/sdk/index.js CHANGED
@@ -4,27 +4,51 @@
4
4
  * This SDK allows you to use AX CLI as a library instead of spawning CLI processes.
5
5
  * Perfect for integrations, VSCode extensions, and programmatic AI agent usage.
6
6
  *
7
+ * ## Quick Start
8
+ *
9
+ * 1. Run `ax-cli setup` to configure credentials (one-time setup)
10
+ * 2. Use the SDK in your code
11
+ *
7
12
  * @example
8
13
  * ```typescript
9
- * import { createAgent, getSettingsManager } from '@defai.digital/ax-cli/sdk';
10
- *
11
- * // Initialize settings
12
- * const settings = getSettingsManager();
13
- * await settings.loadUserSettings();
14
+ * import { createAgent, SDKError, SDKErrorCode } from '@defai.digital/ax-cli/sdk';
14
15
  *
15
- * // Create agent
16
+ * // Create agent (credentials from ax-cli setup)
16
17
  * const agent = await createAgent({
17
- * model: 'glm-4.6',
18
- * maxToolRounds: 50
18
+ * maxToolRounds: 50 // Optional: 1-1000, default 400
19
19
  * });
20
20
  *
21
- * // Listen to streaming responses
22
- * agent.on('stream', (chunk) => {
23
- * console.log(chunk.content);
24
- * });
21
+ * try {
22
+ * // Listen to streaming responses
23
+ * agent.on('stream', (chunk) => {
24
+ * if (chunk.type === 'content') {
25
+ * console.log(chunk.content);
26
+ * }
27
+ * });
28
+ *
29
+ * // Process messages
30
+ * const result = await agent.processUserMessage('List all TypeScript files');
31
+ * console.log('Done!', result.length, 'messages');
32
+ * } catch (error) {
33
+ * // Handle structured errors
34
+ * if (SDKError.isSDKError(error)) {
35
+ * if (error.code === SDKErrorCode.SETUP_NOT_RUN) {
36
+ * console.error('Please run: ax-cli setup');
37
+ * }
38
+ * }
39
+ * } finally {
40
+ * // Always cleanup resources
41
+ * await agent.dispose();
42
+ * }
43
+ * ```
44
+ *
45
+ * ## Testing
46
+ *
47
+ * ```typescript
48
+ * import { createMockAgent } from '@defai.digital/ax-cli/sdk/testing';
25
49
  *
26
- * // Process messages
27
- * const result = await agent.processUserMessage('List all TypeScript files');
50
+ * const mockAgent = createMockAgent(['Response 1', 'Response 2']);
51
+ * const result = await mockAgent.processUserMessage('Test');
28
52
  * ```
29
53
  *
30
54
  * @packageDocumentation
@@ -41,6 +65,8 @@ import { LLMAgent } from '../agent/llm-agent.js';
41
65
  import { Subagent } from '../agent/subagent.js';
42
66
  import { getSettingsManager } from '../utils/settings-manager.js';
43
67
  import { initializeMCPServers } from '../llm/tools.js';
68
+ import { z } from 'zod';
69
+ import { SDKError, SDKErrorCode } from './errors.js';
44
70
  // ============================================================================
45
71
  // LLM Client
46
72
  // ============================================================================
@@ -62,7 +88,8 @@ export { extractErrorMessage, createErrorMessage, ErrorCategory } from '../utils
62
88
  // MCP Integration
63
89
  // ============================================================================
64
90
  export { loadMCPConfig } from '../mcp/config.js';
65
- export { getMCPManager, initializeMCPServers } from '../llm/tools.js';
91
+ export { getMCPManager, initializeMCPServers, getMcpConnectionCount } from '../llm/tools.js';
92
+ export { MCPManager } from '../mcp/client.js';
66
93
  // ============================================================================
67
94
  // Planning System
68
95
  // ============================================================================
@@ -72,47 +99,153 @@ export { getTaskPlanner, isComplexRequest } from '../planner/index.js';
72
99
  // ============================================================================
73
100
  export { getCheckpointManager } from '../checkpoint/index.js';
74
101
  // ============================================================================
102
+ // Memory and Context Cache
103
+ // ============================================================================
104
+ export { ContextStore, getContextStore, resetDefaultStore } from '../memory/context-store.js';
105
+ // ============================================================================
106
+ // Progress Reporting
107
+ // ============================================================================
108
+ export { ProgressReporter, getProgressReporter, ProgressEventType } from './progress-reporter.js';
109
+ // ============================================================================
110
+ // Unified Logging (Phase 3)
111
+ // ============================================================================
112
+ export { UnifiedLogger, getUnifiedLogger, LogLevel, parseLogLevel, getLogLevelName } from './unified-logger.js';
113
+ // ============================================================================
114
+ // Shared Tool Registry (Phase 3)
115
+ // ============================================================================
116
+ export { ToolRegistry, getToolRegistry, registerTools, createToolExecutor } from './tool-registry.js';
117
+ // ============================================================================
75
118
  // Constants
76
119
  // ============================================================================
77
- export { GLM_MODELS, DEFAULT_MODEL, AGENT_CONFIG, PLANNER_CONFIG, } from '../constants.js';
120
+ export { GLM_MODELS, DEFAULT_MODEL, AGENT_CONFIG, PLANNER_CONFIG, VerbosityLevel, UI_CONFIG, } from '../constants.js';
121
+ // ============================================================================
122
+ // SDK Version (Phase 1.5: Best Practices)
123
+ // ============================================================================
124
+ export { SDK_VERSION, SDK_API_VERSION, getSDKVersion, getSDKInfo, } from './version.js';
125
+ // ============================================================================
126
+ // SDK Errors (Phase 1: Best Practices)
127
+ // ============================================================================
128
+ export { SDKError, SDKErrorCode } from './errors.js';
129
+ // ============================================================================
130
+ // Testing Utilities (Phase 1: Best Practices)
131
+ // ============================================================================
132
+ export { MockAgent, createMockAgent, MockSettingsManager, createMockSettings, } from './testing.js';
133
+ // ============================================================================
134
+ // SDK Helper Functions
135
+ // ============================================================================
136
+ /**
137
+ * Validation schema for agent options
138
+ * @internal
139
+ */
140
+ const AgentOptionsSchema = z.object({
141
+ maxToolRounds: z.number().int().min(1).max(1000).optional(),
142
+ debug: z.boolean().optional(),
143
+ }).strict();
78
144
  /**
79
145
  * Create a new LLM Agent with configuration
80
146
  *
81
- * @param options - Agent configuration options
147
+ * SECURITY: All credentials (API key, base URL, model) must be configured
148
+ * via "ax-cli setup" command. This prevents security vulnerabilities where
149
+ * credentials could be exposed in code or logs.
150
+ *
151
+ * @param options - Agent configuration options (non-sensitive only)
82
152
  * @returns Configured LLM Agent instance
153
+ * @throws {SDKError} With code SETUP_NOT_RUN if ax-cli setup has not been run
154
+ * @throws {SDKError} With code API_KEY_MISSING if API key not configured
155
+ * @throws {SDKError} With code BASE_URL_MISSING if base URL not configured
156
+ * @throws {SDKError} With code VALIDATION_ERROR if options are invalid
83
157
  *
84
158
  * @example
85
159
  * ```typescript
160
+ * import { createAgent, SDKError, SDKErrorCode } from '@defai.digital/ax-cli/sdk';
161
+ *
162
+ * // First, user must run: ax-cli setup
163
+ * // Then use SDK with settings from setup:
164
+ *
86
165
  * const agent = await createAgent({
87
- * model: 'glm-4.6',
88
- * maxToolRounds: 50
166
+ * maxToolRounds: 50 // Optional: 1-1000, default 400
89
167
  * });
90
168
  *
91
- * agent.on('stream', (chunk) => {
92
- * if (chunk.type === 'content') {
93
- * console.log(chunk.content);
94
- * }
95
- * });
169
+ * try {
170
+ * agent.on('stream', (chunk) => {
171
+ * if (chunk.type === 'content') {
172
+ * console.log(chunk.content);
173
+ * }
174
+ * });
96
175
  *
97
- * const result = await agent.processUserMessage('Analyze this codebase');
176
+ * const result = await agent.processUserMessage('Analyze this codebase');
177
+ * console.log(result);
178
+ * } catch (error) {
179
+ * if (SDKError.isSDKError(error)) {
180
+ * switch (error.code) {
181
+ * case SDKErrorCode.SETUP_NOT_RUN:
182
+ * console.error('Run ax-cli setup first');
183
+ * break;
184
+ * case SDKErrorCode.API_KEY_MISSING:
185
+ * console.error('API key not configured');
186
+ * break;
187
+ * }
188
+ * }
189
+ * } finally {
190
+ * // Always cleanup resources
191
+ * await agent.dispose();
192
+ * }
98
193
  * ```
99
194
  */
100
195
  export async function createAgent(options = {}) {
196
+ // Validate input options
197
+ let validated;
198
+ try {
199
+ validated = AgentOptionsSchema.parse(options);
200
+ }
201
+ catch (error) {
202
+ throw new SDKError(SDKErrorCode.VALIDATION_ERROR, `Invalid agent options: ${error instanceof Error ? error.message : 'Unknown validation error'}`, error instanceof Error ? error : undefined);
203
+ }
101
204
  const settingsManager = getSettingsManager();
102
- // Load settings if not already loaded
205
+ // Load settings from ax-cli setup
103
206
  try {
104
207
  settingsManager.loadUserSettings();
105
208
  }
106
- catch {
107
- // Settings may not exist yet, that's okay
209
+ catch (error) {
210
+ throw new SDKError(SDKErrorCode.SETUP_NOT_RUN, 'ax-cli setup has not been run. Please run "ax-cli setup" to configure your API key, model, and base URL before using the SDK.', error instanceof Error ? error : undefined);
211
+ }
212
+ // Get configuration ONLY from settings (security requirement)
213
+ const apiKey = settingsManager.getApiKey();
214
+ const model = settingsManager.getCurrentModel();
215
+ const baseURL = settingsManager.getBaseURL();
216
+ // Validate required settings exist
217
+ if (!apiKey) {
218
+ throw new SDKError(SDKErrorCode.API_KEY_MISSING, 'No API key configured. Please run "ax-cli setup" to configure your credentials.');
219
+ }
220
+ if (!baseURL) {
221
+ throw new SDKError(SDKErrorCode.BASE_URL_MISSING, 'No base URL configured. Please run "ax-cli setup" to configure your API provider.');
108
222
  }
109
- // Get configuration (use options or settings)
110
- const apiKey = options.apiKey || settingsManager.getApiKey() || '';
111
- const model = options.model || settingsManager.getCurrentModel();
112
- const baseURL = options.baseURL || settingsManager.getBaseURL();
113
- const maxToolRounds = options.maxToolRounds;
114
- // Create agent instance
223
+ const maxToolRounds = validated.maxToolRounds;
224
+ const debug = validated.debug ?? false;
225
+ // Debug logging
226
+ if (debug) {
227
+ console.error('[AX SDK DEBUG] Creating agent with settings:');
228
+ console.error('[AX SDK DEBUG] Model:', model);
229
+ console.error('[AX SDK DEBUG] Base URL:', baseURL);
230
+ console.error('[AX SDK DEBUG] Max tool rounds:', maxToolRounds ?? 400);
231
+ console.error('[AX SDK DEBUG] API key configured:', !!apiKey);
232
+ }
233
+ // Create agent instance with settings from ax-cli setup
115
234
  const agent = new LLMAgent(apiKey, baseURL, model, maxToolRounds);
235
+ // Enable debug mode on agent if requested
236
+ if (debug) {
237
+ // Add debug event listener
238
+ agent.on('stream', (chunk) => {
239
+ if (chunk.type === 'tool_calls' && chunk.toolCalls) {
240
+ const toolNames = chunk.toolCalls.map((tc) => tc.function.name).join(', ');
241
+ console.error('[AX SDK DEBUG] Tool calls:', toolNames);
242
+ }
243
+ else if (chunk.type === 'tool_result' && chunk.toolResult) {
244
+ console.error('[AX SDK DEBUG] Tool result:', chunk.toolResult.success ? 'success' : 'failed');
245
+ }
246
+ });
247
+ console.error('[AX SDK DEBUG] Agent created successfully');
248
+ }
116
249
  return agent;
117
250
  }
118
251
  /**
@@ -140,34 +273,22 @@ export function createSubagent(role, config) {
140
273
  return new Subagent(role, config);
141
274
  }
142
275
  /**
143
- * Initialize SDK with configuration
276
+ * Initialize SDK and MCP servers
144
277
  *
145
- * @param config - SDK initialization configuration
278
+ * SECURITY: This function does NOT accept credentials. All credentials must be
279
+ * configured via "ax-cli setup" command. This function only initializes MCP servers.
146
280
  *
147
281
  * @example
148
282
  * ```typescript
149
- * await initializeSDK({
150
- * apiKey: 'your-api-key',
151
- * model: 'glm-4.6',
152
- * baseURL: 'https://api.example.com/v1'
153
- * });
283
+ * // Initialize MCP servers from ax-cli settings
284
+ * await initializeSDK();
154
285
  * ```
286
+ *
287
+ * @deprecated Most SDK users don't need to call this - createAgent() handles initialization.
288
+ * Only call this if you need to pre-initialize MCP servers.
155
289
  */
156
- export async function initializeSDK(config) {
157
- const settingsManager = getSettingsManager();
158
- // Update settings
159
- if (config.apiKey) {
160
- settingsManager.updateUserSetting('apiKey', config.apiKey);
161
- }
162
- if (config.model) {
163
- settingsManager.updateUserSetting('defaultModel', config.model);
164
- }
165
- if (config.baseURL) {
166
- settingsManager.updateUserSetting('baseURL', config.baseURL);
167
- }
168
- // Initialize MCP servers if provided
169
- if (config.mcpServers) {
170
- await initializeMCPServers();
171
- }
290
+ export async function initializeSDK() {
291
+ // Initialize MCP servers from settings configured via ax-cli setup
292
+ await initializeMCPServers();
172
293
  }
173
294
  //# sourceMappingURL=index.js.map