mycontext-cli 1.0.94 → 2.0.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.
- package/README.md +446 -130
- package/dist/agents/implementations/ClaudeAgentWorkflow.d.ts +110 -0
- package/dist/agents/implementations/ClaudeAgentWorkflow.d.ts.map +1 -0
- package/dist/agents/implementations/ClaudeAgentWorkflow.js +590 -0
- package/dist/agents/implementations/ClaudeAgentWorkflow.js.map +1 -0
- package/dist/agents/implementations/WorkflowAgent.d.ts +5 -0
- package/dist/agents/implementations/WorkflowAgent.d.ts.map +1 -1
- package/dist/agents/implementations/WorkflowAgent.js +98 -10
- package/dist/agents/implementations/WorkflowAgent.js.map +1 -1
- package/dist/agents/interfaces/SubAgent.d.ts +5 -0
- package/dist/agents/interfaces/SubAgent.d.ts.map +1 -1
- package/dist/commands/build-app.d.ts +5 -0
- package/dist/commands/build-app.d.ts.map +1 -1
- package/dist/commands/build-app.js +127 -4
- package/dist/commands/build-app.js.map +1 -1
- package/dist/commands/compile-prd.d.ts.map +1 -1
- package/dist/commands/compile-prd.js +18 -54
- package/dist/commands/compile-prd.js.map +1 -1
- package/dist/commands/enhance.d.ts +21 -0
- package/dist/commands/enhance.d.ts.map +1 -1
- package/dist/commands/enhance.js +155 -12
- package/dist/commands/enhance.js.map +1 -1
- package/dist/commands/generate-components.d.ts +43 -0
- package/dist/commands/generate-components.d.ts.map +1 -1
- package/dist/commands/generate-components.js +270 -0
- package/dist/commands/generate-components.js.map +1 -1
- package/dist/constants/fileNames.d.ts +68 -0
- package/dist/constants/fileNames.d.ts.map +1 -0
- package/dist/constants/fileNames.js +102 -0
- package/dist/constants/fileNames.js.map +1 -0
- package/dist/interfaces/AIClient.d.ts +198 -0
- package/dist/interfaces/AIClient.d.ts.map +1 -0
- package/dist/interfaces/AIClient.js +40 -0
- package/dist/interfaces/AIClient.js.map +1 -0
- package/dist/package.json +5 -3
- package/dist/types/index.d.ts +423 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/agentDefinitions.d.ts +60 -0
- package/dist/utils/agentDefinitions.d.ts.map +1 -0
- package/dist/utils/agentDefinitions.js +344 -0
- package/dist/utils/agentDefinitions.js.map +1 -0
- package/dist/utils/aiClientFactory.d.ts +93 -0
- package/dist/utils/aiClientFactory.d.ts.map +1 -0
- package/dist/utils/aiClientFactory.js +290 -0
- package/dist/utils/aiClientFactory.js.map +1 -0
- package/dist/utils/aiClientRouter.d.ts +121 -0
- package/dist/utils/aiClientRouter.d.ts.map +1 -0
- package/dist/utils/aiClientRouter.js +401 -0
- package/dist/utils/aiClientRouter.js.map +1 -0
- package/dist/utils/claudeAgentClient.d.ts +166 -0
- package/dist/utils/claudeAgentClient.d.ts.map +1 -0
- package/dist/utils/claudeAgentClient.js +714 -0
- package/dist/utils/claudeAgentClient.js.map +1 -0
- package/dist/utils/claudeClient.d.ts +7 -3
- package/dist/utils/claudeClient.d.ts.map +1 -1
- package/dist/utils/claudeClient.js +28 -5
- package/dist/utils/claudeClient.js.map +1 -1
- package/dist/utils/completeArchitectureEngine.d.ts +67 -0
- package/dist/utils/completeArchitectureEngine.d.ts.map +1 -0
- package/dist/utils/completeArchitectureEngine.js +329 -0
- package/dist/utils/completeArchitectureEngine.js.map +1 -0
- package/dist/utils/contextLoader.d.ts +1 -12
- package/dist/utils/contextLoader.d.ts.map +1 -1
- package/dist/utils/contextLoader.js +29 -150
- package/dist/utils/contextLoader.js.map +1 -1
- package/dist/utils/contextManager.d.ts +76 -0
- package/dist/utils/contextManager.d.ts.map +1 -0
- package/dist/utils/contextManager.js +327 -0
- package/dist/utils/contextManager.js.map +1 -0
- package/dist/utils/hybridAIClient.d.ts +25 -1
- package/dist/utils/hybridAIClient.d.ts.map +1 -1
- package/dist/utils/hybridAIClient.js +69 -2
- package/dist/utils/hybridAIClient.js.map +1 -1
- package/dist/utils/mcpAgentIntegration.d.ts +104 -0
- package/dist/utils/mcpAgentIntegration.d.ts.map +1 -0
- package/dist/utils/mcpAgentIntegration.js +382 -0
- package/dist/utils/mcpAgentIntegration.js.map +1 -0
- package/dist/utils/mcpTools.d.ts +164 -0
- package/dist/utils/mcpTools.d.ts.map +1 -0
- package/dist/utils/mcpTools.js +385 -0
- package/dist/utils/mcpTools.js.map +1 -0
- package/dist/utils/routeGenerator.d.ts +56 -0
- package/dist/utils/routeGenerator.d.ts.map +1 -0
- package/dist/utils/routeGenerator.js +231 -0
- package/dist/utils/routeGenerator.js.map +1 -0
- package/dist/utils/serverActionGenerator.d.ts +56 -0
- package/dist/utils/serverActionGenerator.d.ts.map +1 -0
- package/dist/utils/serverActionGenerator.js +258 -0
- package/dist/utils/serverActionGenerator.js.map +1 -0
- package/dist/utils/streamingHandler.d.ts +98 -0
- package/dist/utils/streamingHandler.d.ts.map +1 -0
- package/dist/utils/streamingHandler.js +259 -0
- package/dist/utils/streamingHandler.js.map +1 -0
- package/dist/utils/toolPermissions.d.ts +105 -0
- package/dist/utils/toolPermissions.d.ts.map +1 -0
- package/dist/utils/toolPermissions.js +408 -0
- package/dist/utils/toolPermissions.js.map +1 -0
- package/package.json +5 -3
|
@@ -0,0 +1,714 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.ClaudeAgentClient = void 0;
|
|
40
|
+
const claude_agent_sdk_1 = require("@anthropic-ai/claude-agent-sdk");
|
|
41
|
+
const fs = __importStar(require("fs"));
|
|
42
|
+
const path = __importStar(require("path"));
|
|
43
|
+
const chalk_1 = __importDefault(require("chalk"));
|
|
44
|
+
const streamingHandler_1 = require("./streamingHandler");
|
|
45
|
+
const mcpTools_1 = require("./mcpTools");
|
|
46
|
+
const agentDefinitions_1 = require("./agentDefinitions");
|
|
47
|
+
class ClaudeAgentClient {
|
|
48
|
+
constructor(workingDirectory) {
|
|
49
|
+
// AgentAIClient interface properties
|
|
50
|
+
this.clientType = 'agent-sdk';
|
|
51
|
+
this.supportsTools = true;
|
|
52
|
+
this.supportsStreaming = true;
|
|
53
|
+
this.queryInstance = null;
|
|
54
|
+
this.apiKey = null;
|
|
55
|
+
this.baseUrl = "https://api.anthropic.com/v1";
|
|
56
|
+
this.options = {};
|
|
57
|
+
// New SDK features
|
|
58
|
+
this.registeredAgents = {};
|
|
59
|
+
this.registeredHooks = {};
|
|
60
|
+
this.mcpServer = null;
|
|
61
|
+
this.streamingHandler = null;
|
|
62
|
+
this.workingDirectory = workingDirectory || process.cwd();
|
|
63
|
+
this.apiKey = this.loadApiKey();
|
|
64
|
+
// Auto-register built-in agents
|
|
65
|
+
this.registeredAgents = (0, agentDefinitions_1.getAllAgentDefinitions)();
|
|
66
|
+
}
|
|
67
|
+
hasApiKey() {
|
|
68
|
+
return !!this.apiKey;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Load API key from environment variables and project files
|
|
72
|
+
*/
|
|
73
|
+
loadApiKey() {
|
|
74
|
+
const candidates = [
|
|
75
|
+
process.env.MYCONTEXT_CLAUDE_API_KEY,
|
|
76
|
+
process.env.ANTHROPIC_API_KEY,
|
|
77
|
+
process.env.CLAUDE_API_KEY,
|
|
78
|
+
];
|
|
79
|
+
// Check for API key in environment
|
|
80
|
+
for (const key of candidates) {
|
|
81
|
+
if (key && key.trim()) {
|
|
82
|
+
return key.trim();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Load from project-level env files
|
|
86
|
+
return this.loadTokenFromEnvFiles();
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Load token from project-level env files
|
|
90
|
+
* Priority: .mycontext/.env -> .env
|
|
91
|
+
*/
|
|
92
|
+
loadTokenFromEnvFiles() {
|
|
93
|
+
try {
|
|
94
|
+
const candidates = [
|
|
95
|
+
path.join(this.workingDirectory, ".mycontext", ".env"),
|
|
96
|
+
path.join(this.workingDirectory, ".env"),
|
|
97
|
+
];
|
|
98
|
+
for (const file of candidates) {
|
|
99
|
+
if (fs.existsSync(file)) {
|
|
100
|
+
const content = fs.readFileSync(file, "utf8");
|
|
101
|
+
const lines = content.split("\n");
|
|
102
|
+
for (const line of lines) {
|
|
103
|
+
const trimmed = line.trim();
|
|
104
|
+
if (trimmed.startsWith("MYCONTEXT_CLAUDE_API_KEY=") ||
|
|
105
|
+
trimmed.startsWith("ANTHROPIC_API_KEY=") ||
|
|
106
|
+
trimmed.startsWith("CLAUDE_API_KEY=")) {
|
|
107
|
+
const keyValue = trimmed.split("=", 2);
|
|
108
|
+
if (keyValue.length === 2) {
|
|
109
|
+
const value = keyValue[1].replace(/^["']|["']$/g, ""); // Remove quotes
|
|
110
|
+
if (value && !value.startsWith("$")) {
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
// Ignore file read errors
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Initialize the Claude Agent with configuration
|
|
126
|
+
*/
|
|
127
|
+
async initialize(options = {}) {
|
|
128
|
+
if (!this.apiKey) {
|
|
129
|
+
throw new Error("Claude API key not configured. Set MYCONTEXT_CLAUDE_API_KEY or ANTHROPIC_API_KEY");
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
// Create system prompt for MyContext CLI
|
|
133
|
+
const systemPrompt = options.systemPrompt || this.getDefaultSystemPrompt();
|
|
134
|
+
// Configure options for the SDK with all new features
|
|
135
|
+
this.options = {
|
|
136
|
+
systemPrompt: {
|
|
137
|
+
type: "preset",
|
|
138
|
+
preset: "claude_code",
|
|
139
|
+
append: systemPrompt,
|
|
140
|
+
},
|
|
141
|
+
model: options.model || "claude-3-5-sonnet-20241022",
|
|
142
|
+
// Tool permissions
|
|
143
|
+
allowedTools: options.allowedTools,
|
|
144
|
+
disallowedTools: options.disallowedTools,
|
|
145
|
+
permissionMode: options.permissionMode || "default",
|
|
146
|
+
// Agent definitions (use registered + provided)
|
|
147
|
+
agents: {
|
|
148
|
+
...this.registeredAgents,
|
|
149
|
+
...(options.agents || {}),
|
|
150
|
+
},
|
|
151
|
+
// Setting sources (default to project-level only for reproducibility)
|
|
152
|
+
settingSources: options.settingSources || ['project', 'local'],
|
|
153
|
+
// Hooks
|
|
154
|
+
hooks: options.hooks ? this.convertHooks(options.hooks) : undefined,
|
|
155
|
+
// Permission callback
|
|
156
|
+
canUseTool: options.canUseTool ? this.wrapCanUseTool(options.canUseTool) : undefined,
|
|
157
|
+
};
|
|
158
|
+
// Register hooks if provided
|
|
159
|
+
if (options.hooks) {
|
|
160
|
+
this.registeredHooks = options.hooks;
|
|
161
|
+
}
|
|
162
|
+
// Setup MCP server with custom tools if provided
|
|
163
|
+
if (options.mcpTools || (0, mcpTools_1.getAllMCPTools)().length > 0) {
|
|
164
|
+
await this.setupMCPServer(options.mcpTools);
|
|
165
|
+
}
|
|
166
|
+
console.log(chalk_1.default.green("✅ Claude Agent SDK initialized successfully"));
|
|
167
|
+
// Log enabled features
|
|
168
|
+
if (Object.keys(this.options.agents || {}).length > 0) {
|
|
169
|
+
console.log(chalk_1.default.gray(` 📦 Agents: ${Object.keys(this.options.agents || {}).length} registered`));
|
|
170
|
+
}
|
|
171
|
+
if (this.mcpServer) {
|
|
172
|
+
console.log(chalk_1.default.gray(` 🔧 MCP Tools: ${(options.mcpTools || (0, mcpTools_1.getAllMCPTools)()).length} available`));
|
|
173
|
+
}
|
|
174
|
+
if (options.hooks && Object.keys(options.hooks).length > 0) {
|
|
175
|
+
console.log(chalk_1.default.gray(` 🪝 Hooks: ${Object.keys(options.hooks).length} registered`));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
throw new Error(`Failed to initialize Claude Agent: ${error.message}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Setup MCP server with custom tools
|
|
184
|
+
*/
|
|
185
|
+
async setupMCPServer(customTools) {
|
|
186
|
+
try {
|
|
187
|
+
const tools = customTools || (0, mcpTools_1.getAllMCPTools)();
|
|
188
|
+
if (tools.length > 0) {
|
|
189
|
+
this.mcpServer = (0, claude_agent_sdk_1.createSdkMcpServer)({
|
|
190
|
+
name: 'mycontext-tools',
|
|
191
|
+
version: '1.0.0',
|
|
192
|
+
tools: tools, // MCP tools are already in SDK format
|
|
193
|
+
});
|
|
194
|
+
console.log(chalk_1.default.gray(` 🔧 MCP Server created with ${tools.length} tools`));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
console.log(chalk_1.default.yellow(` ⚠️ MCP Server setup failed: ${error.message}`));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Convert our hook format to SDK hook format
|
|
203
|
+
*/
|
|
204
|
+
convertHooks(hooks) {
|
|
205
|
+
const sdkHooks = {};
|
|
206
|
+
for (const [event, callback] of Object.entries(hooks)) {
|
|
207
|
+
sdkHooks[event] = async (input, toolUseID, options) => {
|
|
208
|
+
const result = await callback(input, toolUseID, options);
|
|
209
|
+
return result;
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
return sdkHooks;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Wrap our CanUseTool callback for SDK compatibility
|
|
216
|
+
*/
|
|
217
|
+
wrapCanUseTool(callback) {
|
|
218
|
+
return async (toolName, input, options) => {
|
|
219
|
+
const result = await callback(toolName, input, options);
|
|
220
|
+
// Convert our format to SDK format
|
|
221
|
+
if (result.behavior === 'allow') {
|
|
222
|
+
return {
|
|
223
|
+
behavior: 'allow',
|
|
224
|
+
updatedInput: result.updatedInput || input,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
return {
|
|
229
|
+
behavior: 'deny',
|
|
230
|
+
message: result.message || 'Permission denied',
|
|
231
|
+
interrupt: result.interrupt,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Check connection to Claude API
|
|
238
|
+
*/
|
|
239
|
+
async checkConnection() {
|
|
240
|
+
if (!this.apiKey)
|
|
241
|
+
return false;
|
|
242
|
+
try {
|
|
243
|
+
if (!this.queryInstance) {
|
|
244
|
+
await this.initialize();
|
|
245
|
+
}
|
|
246
|
+
// Test with a simple request
|
|
247
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
248
|
+
prompt: "ping",
|
|
249
|
+
options: this.options,
|
|
250
|
+
});
|
|
251
|
+
// Check if query was created successfully
|
|
252
|
+
return !!this.queryInstance;
|
|
253
|
+
}
|
|
254
|
+
catch (error) {
|
|
255
|
+
console.log(`[ClaudeAgentClient] Connection check failed: ${error}`);
|
|
256
|
+
return false;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Generate text using Claude Agent SDK
|
|
261
|
+
*/
|
|
262
|
+
async generateText(prompt, options = {}) {
|
|
263
|
+
if (!this.queryInstance) {
|
|
264
|
+
await this.initialize(options);
|
|
265
|
+
}
|
|
266
|
+
try {
|
|
267
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
268
|
+
prompt,
|
|
269
|
+
options: this.options,
|
|
270
|
+
});
|
|
271
|
+
// Get the response from the query
|
|
272
|
+
let response = "";
|
|
273
|
+
for await (const message of this.queryInstance) {
|
|
274
|
+
if (message.type === "assistant") {
|
|
275
|
+
response += message.message.content[0]?.text || "";
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return response;
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
throw new Error(`Claude Agent generation failed: ${error.message}`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Generate React component with enhanced context
|
|
286
|
+
*/
|
|
287
|
+
async generateComponent(prompt, context = {}, options = {}) {
|
|
288
|
+
if (!this.queryInstance) {
|
|
289
|
+
await this.initialize(options);
|
|
290
|
+
}
|
|
291
|
+
// Build comprehensive context for component generation
|
|
292
|
+
const contextPrompt = this.buildComponentContextPrompt(prompt, context);
|
|
293
|
+
try {
|
|
294
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
295
|
+
prompt: contextPrompt,
|
|
296
|
+
options: this.options,
|
|
297
|
+
});
|
|
298
|
+
// Get the response from the query
|
|
299
|
+
let response = "";
|
|
300
|
+
for await (const message of this.queryInstance) {
|
|
301
|
+
if (message.type === "assistant") {
|
|
302
|
+
response += message.message.content[0]?.text || "";
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return response;
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
throw new Error(`Component generation failed: ${error.message}`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Refine existing component with Claude Agent SDK
|
|
313
|
+
*/
|
|
314
|
+
async generateComponentRefinement(componentCode, prompt, context = {}, options = {}) {
|
|
315
|
+
if (!this.queryInstance) {
|
|
316
|
+
await this.initialize(options);
|
|
317
|
+
}
|
|
318
|
+
const refinementPrompt = this.buildRefinementPrompt(componentCode, prompt, context);
|
|
319
|
+
try {
|
|
320
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
321
|
+
prompt: refinementPrompt,
|
|
322
|
+
options: this.options,
|
|
323
|
+
});
|
|
324
|
+
// Get the response from the query
|
|
325
|
+
let response = "";
|
|
326
|
+
for await (const message of this.queryInstance) {
|
|
327
|
+
if (message.type === "assistant") {
|
|
328
|
+
response += message.message.content[0]?.text || "";
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return response;
|
|
332
|
+
}
|
|
333
|
+
catch (error) {
|
|
334
|
+
throw new Error(`Component refinement failed: ${error.message}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Run agent workflow with context management
|
|
339
|
+
*/
|
|
340
|
+
async runAgentWorkflow(workflowPrompt, context = {}, options = {}) {
|
|
341
|
+
if (!this.queryInstance) {
|
|
342
|
+
await this.initialize(options);
|
|
343
|
+
}
|
|
344
|
+
// Build workflow context
|
|
345
|
+
const workflowContextPrompt = this.buildWorkflowContextPrompt(workflowPrompt, context);
|
|
346
|
+
try {
|
|
347
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
348
|
+
prompt: workflowContextPrompt,
|
|
349
|
+
options: this.options,
|
|
350
|
+
});
|
|
351
|
+
// Get the response from the query
|
|
352
|
+
let response = "";
|
|
353
|
+
for await (const message of this.queryInstance) {
|
|
354
|
+
if (message.type === "assistant") {
|
|
355
|
+
response += message.message.content[0]?.text || "";
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
// Update context with new information
|
|
359
|
+
const updatedContext = this.updateContextFromResponse(context, response);
|
|
360
|
+
return {
|
|
361
|
+
content: response,
|
|
362
|
+
context: updatedContext,
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
throw new Error(`Agent workflow failed: ${error.message}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Get available models
|
|
371
|
+
*/
|
|
372
|
+
async listModels() {
|
|
373
|
+
// Claude Agent SDK doesn't expose model listing directly
|
|
374
|
+
// Return common Claude models
|
|
375
|
+
return [
|
|
376
|
+
"claude-3-5-sonnet-20241022",
|
|
377
|
+
"claude-3-5-haiku-20241022",
|
|
378
|
+
"claude-3-opus-20240229",
|
|
379
|
+
"claude-3-sonnet-20240229",
|
|
380
|
+
"claude-3-haiku-20240307",
|
|
381
|
+
];
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Set API key
|
|
385
|
+
*/
|
|
386
|
+
setApiKey(apiKey) {
|
|
387
|
+
this.apiKey = apiKey;
|
|
388
|
+
this.queryInstance = null; // Reset query instance to reinitialize with new key
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Get default system prompt for MyContext CLI
|
|
392
|
+
*/
|
|
393
|
+
getDefaultSystemPrompt() {
|
|
394
|
+
return `You are an expert AI assistant specialized in React/Next.js development and component generation. You work with the MyContext CLI to help developers build production-ready applications.
|
|
395
|
+
|
|
396
|
+
Your expertise includes:
|
|
397
|
+
- React/TypeScript component development
|
|
398
|
+
- Next.js App Router patterns
|
|
399
|
+
- Shadcn UI component integration
|
|
400
|
+
- Tailwind CSS styling
|
|
401
|
+
- Component architecture and best practices
|
|
402
|
+
- Code optimization and performance
|
|
403
|
+
- Accessibility and responsive design
|
|
404
|
+
|
|
405
|
+
When generating components:
|
|
406
|
+
1. Always use TypeScript with proper interfaces
|
|
407
|
+
2. Follow Next.js App Router conventions
|
|
408
|
+
3. Use Shadcn UI components when appropriate
|
|
409
|
+
4. Include proper error handling and loading states
|
|
410
|
+
5. Add comprehensive comments for external dependencies
|
|
411
|
+
6. Ensure mobile-first responsive design
|
|
412
|
+
7. Follow accessibility best practices
|
|
413
|
+
|
|
414
|
+
Provide clean, production-ready code that follows modern React patterns.`;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Build comprehensive context prompt for component generation
|
|
418
|
+
*/
|
|
419
|
+
buildComponentContextPrompt(prompt, context) {
|
|
420
|
+
let contextPrompt = `Generate a production-ready React component based on the following requirements:\n\n${prompt}\n\n`;
|
|
421
|
+
if (context.prd) {
|
|
422
|
+
contextPrompt += `\n## Project Requirements Document:\n${context.prd}\n`;
|
|
423
|
+
}
|
|
424
|
+
if (context.types) {
|
|
425
|
+
contextPrompt += `\n## TypeScript Types:\n${context.types}\n`;
|
|
426
|
+
}
|
|
427
|
+
if (context.brand) {
|
|
428
|
+
contextPrompt += `\n## Branding Guidelines:\n${context.brand}\n`;
|
|
429
|
+
}
|
|
430
|
+
if (context.componentList) {
|
|
431
|
+
contextPrompt += `\n## Available Components:\n${JSON.stringify(context.componentList, null, 2)}\n`;
|
|
432
|
+
}
|
|
433
|
+
if (context.projectStructure) {
|
|
434
|
+
contextPrompt += `\n## Project Structure:\n${context.projectStructure}\n`;
|
|
435
|
+
}
|
|
436
|
+
contextPrompt += `\nPlease provide:
|
|
437
|
+
1. Complete component code in a \`\`\`tsx code block
|
|
438
|
+
2. Brief explanation of the implementation
|
|
439
|
+
3. Any external dependencies that need to be created
|
|
440
|
+
4. Usage examples if applicable`;
|
|
441
|
+
return contextPrompt;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Build refinement prompt
|
|
445
|
+
*/
|
|
446
|
+
buildRefinementPrompt(componentCode, prompt, context) {
|
|
447
|
+
let refinementPrompt = `Refine the following React component based on the requirements:\n\n${prompt}\n\n`;
|
|
448
|
+
refinementPrompt += `\n## Current Component:\n\`\`\`tsx\n${componentCode}\n\`\`\`\n`;
|
|
449
|
+
if (context.prd) {
|
|
450
|
+
refinementPrompt += `\n## Project Context:\n${context.prd}\n`;
|
|
451
|
+
}
|
|
452
|
+
refinementPrompt += `\nPlease provide:
|
|
453
|
+
1. Complete refactored component code in a \`\`\`tsx code block
|
|
454
|
+
2. Brief explanation of the changes made
|
|
455
|
+
3. Any new dependencies or considerations`;
|
|
456
|
+
return refinementPrompt;
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Build workflow context prompt
|
|
460
|
+
*/
|
|
461
|
+
buildWorkflowContextPrompt(prompt, context) {
|
|
462
|
+
let workflowPrompt = `Execute the following workflow:\n\n${prompt}\n\n`;
|
|
463
|
+
if (context.prd) {
|
|
464
|
+
workflowPrompt += `\n## Project Requirements:\n${context.prd}\n`;
|
|
465
|
+
}
|
|
466
|
+
if (context.previousOutputs) {
|
|
467
|
+
workflowPrompt += `\n## Previous Workflow Outputs:\n${JSON.stringify(context.previousOutputs, null, 2)}\n`;
|
|
468
|
+
}
|
|
469
|
+
if (context.projectStructure) {
|
|
470
|
+
workflowPrompt += `\n## Project Structure:\n${context.projectStructure}\n`;
|
|
471
|
+
}
|
|
472
|
+
workflowPrompt += `\nPlease provide a comprehensive response that addresses the workflow requirements.`;
|
|
473
|
+
return workflowPrompt;
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Update context from agent response
|
|
477
|
+
*/
|
|
478
|
+
updateContextFromResponse(currentContext, response) {
|
|
479
|
+
// Extract any new context information from the response
|
|
480
|
+
// This is a basic implementation - could be enhanced with more sophisticated parsing
|
|
481
|
+
const updatedContext = { ...currentContext };
|
|
482
|
+
// Look for generated code blocks that might contain new types or components
|
|
483
|
+
const codeBlockRegex = /```(?:tsx?|typescript|javascript|jsx)\n([\s\S]*?)\n```/g;
|
|
484
|
+
const codeBlocks = response.match(codeBlockRegex);
|
|
485
|
+
if (codeBlocks && codeBlocks.length > 0) {
|
|
486
|
+
// Store the latest generated code for potential future reference
|
|
487
|
+
updatedContext.previousOutputs = {
|
|
488
|
+
...updatedContext.previousOutputs,
|
|
489
|
+
lastGeneratedCode: codeBlocks[codeBlocks.length - 1],
|
|
490
|
+
timestamp: new Date().toISOString(),
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
return updatedContext;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Generate with specific tools enabled
|
|
497
|
+
*/
|
|
498
|
+
async generateWithTools(prompt, tools, context, options) {
|
|
499
|
+
if (!this.queryInstance) {
|
|
500
|
+
await this.initialize({
|
|
501
|
+
...options,
|
|
502
|
+
allowedTools: tools,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
const contextPrompt = this.buildComponentContextPrompt(prompt, context || {});
|
|
506
|
+
const startTime = Date.now();
|
|
507
|
+
try {
|
|
508
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
509
|
+
prompt: contextPrompt,
|
|
510
|
+
options: {
|
|
511
|
+
...this.options,
|
|
512
|
+
allowedTools: tools,
|
|
513
|
+
},
|
|
514
|
+
});
|
|
515
|
+
let response = "";
|
|
516
|
+
const toolsUsed = [];
|
|
517
|
+
for await (const message of this.queryInstance) {
|
|
518
|
+
if (message.type === "assistant") {
|
|
519
|
+
response += message.message.content[0]?.text || "";
|
|
520
|
+
}
|
|
521
|
+
// Track tool usage if available
|
|
522
|
+
if (message.type === "assistant" && message.message.content) {
|
|
523
|
+
for (const content of message.message.content) {
|
|
524
|
+
if (content.type === "tool_use") {
|
|
525
|
+
toolsUsed.push(content.name);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
content: response,
|
|
532
|
+
toolsUsed: [...new Set(toolsUsed)],
|
|
533
|
+
duration: Date.now() - startTime,
|
|
534
|
+
context: this.updateContextFromResponse(context || {}, response),
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
catch (error) {
|
|
538
|
+
throw new Error(`Tool-based generation failed: ${error.message}`);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Generate with streaming progress (using StreamingHandler)
|
|
543
|
+
*/
|
|
544
|
+
async generateStream(prompt, streamOptions, context, options) {
|
|
545
|
+
if (!this.queryInstance) {
|
|
546
|
+
await this.initialize(options);
|
|
547
|
+
}
|
|
548
|
+
const contextPrompt = this.buildComponentContextPrompt(prompt, context || {});
|
|
549
|
+
try {
|
|
550
|
+
this.queryInstance = (0, claude_agent_sdk_1.query)({
|
|
551
|
+
prompt: contextPrompt,
|
|
552
|
+
options: this.options,
|
|
553
|
+
});
|
|
554
|
+
// Use StreamingHandler for better progress tracking
|
|
555
|
+
const { content, stats } = await (0, streamingHandler_1.streamWithProgress)(this.queryInstance, {
|
|
556
|
+
showProgress: true,
|
|
557
|
+
showTokens: true,
|
|
558
|
+
showToolUsage: true,
|
|
559
|
+
onProgress: streamOptions.onProgress,
|
|
560
|
+
onToken: streamOptions.onToken,
|
|
561
|
+
onToolUse: streamOptions.onToolUse,
|
|
562
|
+
onError: streamOptions.onError,
|
|
563
|
+
});
|
|
564
|
+
return {
|
|
565
|
+
content,
|
|
566
|
+
toolsUsed: stats.toolsUsed,
|
|
567
|
+
duration: stats.duration,
|
|
568
|
+
usage: {
|
|
569
|
+
inputTokens: stats.inputTokens,
|
|
570
|
+
outputTokens: stats.outputTokens,
|
|
571
|
+
totalTokens: stats.totalTokens,
|
|
572
|
+
},
|
|
573
|
+
context: this.updateContextFromResponse(context || {}, content),
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
catch (error) {
|
|
577
|
+
if (streamOptions.onError) {
|
|
578
|
+
streamOptions.onError(error);
|
|
579
|
+
}
|
|
580
|
+
throw new Error(`Streaming generation failed: ${error.message}`);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Run agent workflow with enhanced context management
|
|
585
|
+
*/
|
|
586
|
+
async runWorkflow(workflowPrompt, context, options) {
|
|
587
|
+
const result = await this.runAgentWorkflow(workflowPrompt, context, options);
|
|
588
|
+
// Transform to WorkflowResult format
|
|
589
|
+
return {
|
|
590
|
+
success: true,
|
|
591
|
+
content: result.content,
|
|
592
|
+
steps: ['workflow-execution'],
|
|
593
|
+
context: result.context,
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Configure agent with specific settings
|
|
598
|
+
*/
|
|
599
|
+
async configureAgent(config) {
|
|
600
|
+
const agentOptions = {
|
|
601
|
+
model: config.model === 'inherit' ? undefined : `claude-3-${config.model}-20241022`,
|
|
602
|
+
systemPrompt: config.systemPrompt,
|
|
603
|
+
allowedTools: config.allowedTools,
|
|
604
|
+
disallowedTools: config.disallowedTools,
|
|
605
|
+
permissionMode: config.permissionMode,
|
|
606
|
+
};
|
|
607
|
+
await this.initialize(agentOptions);
|
|
608
|
+
console.log(chalk_1.default.green(`✅ Agent configured: ${config.name}`));
|
|
609
|
+
console.log(chalk_1.default.gray(` Description: ${config.description}`));
|
|
610
|
+
if (config.tools) {
|
|
611
|
+
console.log(chalk_1.default.gray(` Tools: ${config.tools.join(', ')}`));
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Request permission for an operation (placeholder for future implementation)
|
|
616
|
+
*/
|
|
617
|
+
async requestPermission(operation, target) {
|
|
618
|
+
// For now, return true as permissions are handled by the SDK
|
|
619
|
+
// In future, could add interactive prompts here
|
|
620
|
+
console.log(chalk_1.default.yellow(`⚠️ Requesting permission: ${operation} on ${target}`));
|
|
621
|
+
return true;
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Use a specific agent for generation
|
|
625
|
+
*/
|
|
626
|
+
async useAgent(agentName, prompt, context, options) {
|
|
627
|
+
const agent = this.registeredAgents[agentName] || (0, agentDefinitions_1.getAgentDefinition)(agentName);
|
|
628
|
+
if (!agent) {
|
|
629
|
+
throw new Error(`Agent '${agentName}' not found`);
|
|
630
|
+
}
|
|
631
|
+
console.log(chalk_1.default.blue(`🤖 Using agent: ${agentName}`));
|
|
632
|
+
console.log(chalk_1.default.gray(` ${agent.description}`));
|
|
633
|
+
// Initialize with agent-specific settings
|
|
634
|
+
await this.initialize({
|
|
635
|
+
...options,
|
|
636
|
+
agents: { [agentName]: agent },
|
|
637
|
+
allowedTools: agent.tools,
|
|
638
|
+
});
|
|
639
|
+
// Use the agent
|
|
640
|
+
const contextPrompt = `@${agentName}\n\n${prompt}`;
|
|
641
|
+
return await this.generateWithTools(contextPrompt, agent.tools || [], context, options);
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Register a custom agent
|
|
645
|
+
*/
|
|
646
|
+
registerAgent(name, agent) {
|
|
647
|
+
this.registeredAgents[name] = agent;
|
|
648
|
+
console.log(chalk_1.default.green(`✅ Agent registered: ${name}`));
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Register a hook
|
|
652
|
+
*/
|
|
653
|
+
registerHook(event, callback) {
|
|
654
|
+
this.registeredHooks[event] = callback;
|
|
655
|
+
console.log(chalk_1.default.green(`✅ Hook registered: ${event}`));
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Get list of available agents
|
|
659
|
+
*/
|
|
660
|
+
getAvailableAgents() {
|
|
661
|
+
return Object.keys(this.registeredAgents);
|
|
662
|
+
}
|
|
663
|
+
/**
|
|
664
|
+
* Get agent info
|
|
665
|
+
*/
|
|
666
|
+
getAgentInfo(name) {
|
|
667
|
+
return this.registeredAgents[name];
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Enable/disable specific tools
|
|
671
|
+
*/
|
|
672
|
+
setToolPermissions(allowed, disallowed) {
|
|
673
|
+
this.options.allowedTools = allowed;
|
|
674
|
+
this.options.disallowedTools = disallowed;
|
|
675
|
+
console.log(chalk_1.default.blue('🔧 Tool permissions updated'));
|
|
676
|
+
if (allowed) {
|
|
677
|
+
console.log(chalk_1.default.gray(` Allowed: ${allowed.join(', ')}`));
|
|
678
|
+
}
|
|
679
|
+
if (disallowed) {
|
|
680
|
+
console.log(chalk_1.default.gray(` Disallowed: ${disallowed.join(', ')}`));
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Get MCP server instance
|
|
685
|
+
*/
|
|
686
|
+
getMCPServer() {
|
|
687
|
+
return this.mcpServer;
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Check if agent is available
|
|
691
|
+
*/
|
|
692
|
+
hasAgent(name) {
|
|
693
|
+
return name in this.registeredAgents;
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Cleanup resources
|
|
697
|
+
*/
|
|
698
|
+
async cleanup() {
|
|
699
|
+
if (this.queryInstance) {
|
|
700
|
+
// Claude Agent SDK cleanup if needed
|
|
701
|
+
this.queryInstance = null;
|
|
702
|
+
}
|
|
703
|
+
if (this.streamingHandler) {
|
|
704
|
+
this.streamingHandler.stop();
|
|
705
|
+
this.streamingHandler = null;
|
|
706
|
+
}
|
|
707
|
+
if (this.mcpServer) {
|
|
708
|
+
// MCP server cleanup if needed
|
|
709
|
+
this.mcpServer = null;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
exports.ClaudeAgentClient = ClaudeAgentClient;
|
|
714
|
+
//# sourceMappingURL=claudeAgentClient.js.map
|