-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathcommand.tsx
More file actions
341 lines (309 loc) · 13 KB
/
command.tsx
File metadata and controls
341 lines (309 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import { findConfigRoot, getWorkingDirectory, readEnvFile } from '../../../lib';
import { getErrorMessage } from '../../errors';
import { ExecLogger } from '../../logging';
import {
callMcpTool,
createDevServer,
findAvailablePort,
getAgentPort,
getDevConfig,
getDevSupportedAgents,
getEndpointUrl,
invokeAgent,
invokeAgentStreaming,
invokeForProtocol,
listMcpTools,
loadProjectConfig,
} from '../../operations/dev';
import { getGatewayEnvVars } from '../../operations/dev/gateway-env.js';
import { FatalError } from '../../tui/components';
import { LayoutProvider } from '../../tui/context';
import { COMMAND_DESCRIPTIONS } from '../../tui/copy';
import { requireProject } from '../../tui/guards';
import { parseHeaderFlags } from '../shared/header-utils';
import type { Command } from '@commander-js/extra-typings';
import { Text, render } from 'ink';
import React from 'react';
// Alternate screen buffer - same as main TUI
const ENTER_ALT_SCREEN = '\x1B[?1049h\x1B[H';
const EXIT_ALT_SCREEN = '\x1B[?1049l';
const SHOW_CURSOR = '\x1B[?25h';
async function invokeDevServer(
port: number,
prompt: string,
stream: boolean,
headers?: Record<string, string>
): Promise<void> {
try {
if (stream) {
// Stream response to stdout
for await (const chunk of invokeAgentStreaming({ port, message: prompt, headers })) {
process.stdout.write(chunk);
}
process.stdout.write('\n');
} else {
const response = await invokeAgent({ port, message: prompt, headers });
console.log(response);
}
} catch (err) {
if (err instanceof Error && err.message.includes('ECONNREFUSED')) {
console.error(`Error: Dev server not running on port ${port}`);
console.error('Start it with: agentcore dev');
} else {
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
}
process.exit(1);
}
}
async function invokeA2ADevServer(port: number, prompt: string, headers?: Record<string, string>): Promise<void> {
try {
for await (const chunk of invokeForProtocol('A2A', { port, message: prompt, headers })) {
process.stdout.write(chunk);
}
process.stdout.write('\n');
} catch (err) {
if (err instanceof Error && err.message.includes('ECONNREFUSED')) {
console.error(`Error: Dev server not running on port ${port}`);
console.error('Start it with: agentcore dev');
} else {
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
}
process.exit(1);
}
}
async function handleMcpInvoke(
port: number,
invokeValue: string,
toolName?: string,
input?: string,
headers?: Record<string, string>
): Promise<void> {
try {
if (invokeValue === 'list-tools') {
const { tools } = await listMcpTools(port, undefined, headers);
if (tools.length === 0) {
console.log('No tools available.');
return;
}
console.log('Available tools:');
for (const tool of tools) {
const desc = tool.description ? ` - ${tool.description}` : '';
console.log(` ${tool.name}${desc}`);
}
} else if (invokeValue === 'call-tool') {
if (!toolName) {
console.error('Error: --tool is required with --invoke call-tool');
console.error('Usage: agentcore dev --invoke call-tool --tool <name> --input \'{"arg": "value"}\'');
process.exit(1);
}
// Initialize session first, then call tool with the session ID
const { sessionId } = await listMcpTools(port, undefined, headers);
let args: Record<string, unknown> = {};
if (input) {
try {
args = JSON.parse(input) as Record<string, unknown>;
} catch {
console.error(`Error: Invalid JSON for --input: ${input}`);
console.error('Expected format: --input \'{"key": "value"}\'');
process.exit(1);
}
}
const result = await callMcpTool(port, toolName, args, sessionId, undefined, headers);
console.log(result);
} else {
console.error(`Error: Unknown MCP invoke command "${invokeValue}"`);
console.error('Usage:');
console.error(' agentcore dev --invoke list-tools');
console.error(' agentcore dev --invoke call-tool --tool <name> --input \'{"arg": "value"}\'');
process.exit(1);
}
} catch (err) {
if (err instanceof Error && err.message.includes('ECONNREFUSED')) {
console.error(`Error: Dev server not running on port ${port}`);
console.error('Start it with: agentcore dev');
} else {
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
}
process.exit(1);
}
}
export const registerDev = (program: Command) => {
program
.command('dev')
.alias('d')
.description(COMMAND_DESCRIPTIONS.dev)
.option('-p, --port <port>', 'Port for development server', '8080')
.option('-a, --agent <name>', 'Agent to run or invoke (required if multiple agents)')
.option('-i, --invoke <prompt>', 'Invoke running dev server (use --agent if multiple) [non-interactive]')
.option('-s, --stream', 'Stream response when using --invoke [non-interactive]')
.option('-l, --logs', 'Run dev server with logs to stdout [non-interactive]')
.option('--tool <name>', 'MCP tool name (used with --invoke call-tool) [non-interactive]')
.option('--input <json>', 'MCP tool arguments as JSON (used with --invoke call-tool) [non-interactive]')
.option(
'-H, --header <header>',
'Custom header to forward to the agent (format: "Name: Value", repeatable) [non-interactive]',
(val: string, prev: string[]) => [...prev, val],
[] as string[]
)
.action(async opts => {
try {
const port = parseInt(opts.port, 10);
// Parse custom headers
let headers: Record<string, string> | undefined;
if (opts.header && opts.header.length > 0) {
headers = parseHeaderFlags(opts.header);
}
// If --invoke provided, call the dev server and exit
if (opts.invoke) {
const invokeProject = await loadProjectConfig(getWorkingDirectory());
// Determine which agent/port to invoke
let invokePort = port;
let targetAgent = invokeProject?.agents[0];
if (opts.agent && invokeProject) {
invokePort = getAgentPort(invokeProject, opts.agent, port);
targetAgent = invokeProject.agents.find(a => a.name === opts.agent);
} else if (invokeProject && invokeProject.agents.length > 1 && !opts.agent) {
const names = invokeProject.agents.map(a => a.name).join(', ');
console.error(`Error: Multiple agents found. Use --agent to specify which one.`);
console.error(`Available: ${names}`);
process.exit(1);
}
const protocol = targetAgent?.protocol ?? 'HTTP';
// Override port for protocols with fixed framework ports
if (protocol === 'A2A') invokePort = 9000;
else if (protocol === 'MCP') invokePort = 8000;
// Protocol-aware dispatch
if (protocol === 'MCP') {
await handleMcpInvoke(invokePort, opts.invoke, opts.tool, opts.input, headers);
} else if (protocol === 'A2A') {
await invokeA2ADevServer(invokePort, opts.invoke, headers);
} else {
await invokeDevServer(invokePort, opts.invoke, opts.stream ?? false, headers);
}
return;
}
requireProject();
const workingDir = getWorkingDirectory();
const project = await loadProjectConfig(workingDir);
if (!project) {
render(<FatalError message="No agentcore project found." suggestedCommand="agentcore create" />);
process.exit(1);
}
if (!project.agents || project.agents.length === 0) {
render(<FatalError message="No agents defined in project." suggestedCommand="agentcore add agent" />);
process.exit(1);
}
// Warn about VPC mode limitations in local dev
const targetDevAgent = opts.agent ? project.agents.find(a => a.name === opts.agent) : project.agents[0];
if (targetDevAgent?.networkMode === 'VPC') {
console.log(
'\x1b[33mWarning: This agent uses VPC network mode. Local dev server runs outside your VPC. Network behavior may differ from deployed environment.\x1b[0m\n'
);
}
const supportedAgents = getDevSupportedAgents(project);
if (supportedAgents.length === 0) {
render(
<FatalError message="No agents support dev mode. Dev mode requires Python agents with an entrypoint." />
);
process.exit(1);
}
// If --logs provided, run non-interactive mode
if (opts.logs) {
// Require --agent if multiple agents
if (project.agents.length > 1 && !opts.agent) {
const names = project.agents.map(a => a.name).join(', ');
console.error(`Error: Multiple agents found. Use --agent to specify which one.`);
console.error(`Available: ${names}`);
process.exit(1);
}
const agentName = opts.agent ?? project.agents[0]?.name;
const configRoot = findConfigRoot(workingDir);
const envVars = configRoot ? await readEnvFile(configRoot) : {};
const gatewayEnvVars = await getGatewayEnvVars();
// Gateway env vars go first, .env.local overrides take precedence
const mergedEnvVars = { ...gatewayEnvVars, ...envVars };
const config = getDevConfig(workingDir, project, configRoot ?? undefined, agentName);
if (!config) {
console.error('Error: No dev-supported agents found.');
process.exit(1);
}
// Create logger for log file path
const logger = new ExecLogger({ command: 'dev' });
// Calculate port: A2A/MCP use fixed framework ports, HTTP uses configurable port
const isA2A = config.protocol === 'A2A';
const isMcp = config.protocol === 'MCP';
const fixedPort = isA2A ? 9000 : isMcp ? 8000 : getAgentPort(project, config.agentName, port);
const actualPort = await findAvailablePort(fixedPort);
if ((isA2A || isMcp) && actualPort !== fixedPort) {
console.error(`Error: Port ${fixedPort} is in use. ${config.protocol} agents require port ${fixedPort}.`);
process.exit(1);
}
if (actualPort !== fixedPort) {
console.log(`Port ${fixedPort} in use, using ${actualPort}`);
}
// Get provider info from agent config
const providerInfo = '(see agent code)';
console.log(`Starting dev server...`);
console.log(`Agent: ${config.agentName}`);
if (config.protocol !== 'MCP') {
console.log(`Provider: ${providerInfo}`);
}
if (config.protocol !== 'HTTP') {
console.log(`Protocol: ${config.protocol}`);
}
console.log(`Server: ${getEndpointUrl(actualPort, config.protocol)}`);
console.log(`Log: ${logger.getRelativeLogPath()}`);
console.log(`Press Ctrl+C to stop\n`);
const devCallbacks = {
onLog: (level: string, msg: string) => {
const prefix = level === 'error' ? '❌' : level === 'warn' ? '⚠️' : '→';
console.log(`${prefix} ${msg}`);
logger.log(msg, level === 'error' ? 'error' : 'info');
},
onExit: (code: number | null) => {
console.log(`\nServer exited with code ${code ?? 0}`);
logger.finalize(code === 0);
process.exit(code ?? 0);
},
};
const server = createDevServer(config, { port: actualPort, envVars: mergedEnvVars, callbacks: devCallbacks });
await server.start();
// Handle Ctrl+C — use server.kill() for proper container cleanup
process.on('SIGINT', () => {
console.log('\nStopping server...');
server.kill();
});
// Keep process alive
// eslint-disable-next-line @typescript-eslint/no-empty-function
await new Promise(() => {});
}
// Enter alternate screen buffer for fullscreen mode
process.stdout.write(ENTER_ALT_SCREEN);
const exitAltScreen = () => {
process.stdout.write(EXIT_ALT_SCREEN);
process.stdout.write(SHOW_CURSOR);
};
const { DevScreen } = await import('../../tui/screens/dev/DevScreen');
const { unmount, waitUntilExit } = render(
<LayoutProvider>
<DevScreen
onBack={() => {
exitAltScreen();
unmount();
process.exit(0);
}}
workingDir={workingDir}
port={port}
agentName={opts.agent}
headers={headers}
/>
</LayoutProvider>
);
await waitUntilExit();
exitAltScreen();
} catch (error) {
render(<Text color="red">Error: {getErrorMessage(error)}</Text>);
process.exit(1);
}
});
};