forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaction.ts
More file actions
390 lines (348 loc) · 11.8 KB
/
Copy pathaction.ts
File metadata and controls
390 lines (348 loc) · 11.8 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import { ConfigIO } from '../../../lib';
import type { AgentCoreProjectSpec, AwsDeploymentTargets, DeployedState } from '../../../schema';
import {
executeBashCommand,
invokeA2ARuntime,
invokeAgentRuntime,
invokeAgentRuntimeStreaming,
mcpCallTool,
mcpInitSession,
mcpListTools,
} from '../../aws';
import { InvokeLogger } from '../../logging';
import { formatMcpToolList } from '../../operations/dev/utils';
import { canFetchRuntimeToken, fetchRuntimeToken } from '../../operations/fetch-access';
import type { InvokeOptions, InvokeResult } from './types';
export interface InvokeContext {
project: AgentCoreProjectSpec;
deployedState: DeployedState;
awsTargets: AwsDeploymentTargets;
}
/**
* Loads configuration required for invocation
*/
export async function loadInvokeConfig(configIO: ConfigIO = new ConfigIO()): Promise<InvokeContext> {
return {
project: await configIO.readProjectSpec(),
deployedState: await configIO.readDeployedState(),
awsTargets: await configIO.readAWSDeploymentTargets(),
};
}
/**
* Main invoke handler
*/
export async function handleInvoke(context: InvokeContext, options: InvokeOptions = {}): Promise<InvokeResult> {
const { project, deployedState, awsTargets } = context;
// Resolve target
const targetNames = Object.keys(deployedState.targets);
if (targetNames.length === 0) {
return { success: false, error: 'No deployed targets found. Run `agentcore deploy` first.' };
}
const selectedTargetName = options.targetName ?? targetNames[0]!;
if (options.targetName && !targetNames.includes(options.targetName)) {
return { success: false, error: `Target '${options.targetName}' not found. Available: ${targetNames.join(', ')}` };
}
const targetState = deployedState.targets[selectedTargetName];
const targetConfig = awsTargets.find(t => t.name === selectedTargetName);
if (!targetConfig) {
return { success: false, error: `Target config '${selectedTargetName}' not found in aws-targets` };
}
if (project.runtimes.length === 0) {
return { success: false, error: 'No agents defined in configuration' };
}
// Resolve agent
const agentNames = project.runtimes.map(a => a.name);
if (!options.agentName && project.runtimes.length > 1) {
return { success: false, error: `Multiple runtimes found. Use --runtime to specify one: ${agentNames.join(', ')}` };
}
const agentSpec = options.agentName ? project.runtimes.find(a => a.name === options.agentName) : project.runtimes[0];
if (options.agentName && !agentSpec) {
return { success: false, error: `Agent '${options.agentName}' not found. Available: ${agentNames.join(', ')}` };
}
if (!agentSpec) {
return { success: false, error: 'No agents defined in configuration' };
}
// Warn about VPC mode endpoint requirements
if (agentSpec.networkMode === 'VPC') {
console.log(
'\x1b[33mWarning: This agent uses VPC network mode. Ensure your VPC endpoints are configured for invocation.\x1b[0m'
);
}
// Get the deployed state for this specific agent
const agentState = targetState?.resources?.runtimes?.[agentSpec.name];
if (!agentState) {
return { success: false, error: `Agent '${agentSpec.name}' is not deployed to target '${selectedTargetName}'` };
}
// Auto-fetch bearer token for CUSTOM_JWT agents when not provided
if (agentSpec.authorizerType === 'CUSTOM_JWT' && !options.bearerToken) {
const canFetch = await canFetchRuntimeToken(agentSpec.name);
if (canFetch) {
try {
const tokenResult = await fetchRuntimeToken(agentSpec.name, { deployTarget: selectedTargetName });
options = { ...options, bearerToken: tokenResult.token };
} catch (err) {
return {
success: false,
error: `CUSTOM_JWT agent requires a bearer token. Auto-fetch failed: ${err instanceof Error ? err.message : String(err)}\nProvide one manually with --bearer-token.`,
};
}
} else {
return {
success: false,
error: `Agent '${agentSpec.name}' is configured for CUSTOM_JWT but no bearer token is available.\nEither provide --bearer-token or re-add the agent with --client-id and --client-secret to enable auto-fetch.`,
};
}
}
// Exec mode: run shell command in runtime container
if (options.exec) {
const logger = new InvokeLogger({
agentName: agentSpec.name,
runtimeArn: agentState.runtimeArn,
region: targetConfig.region,
sessionId: options.sessionId,
});
const command = options.prompt;
if (!command) {
return { success: false, error: '--exec requires a command (prompt)' };
}
logger.logPrompt(command, options.sessionId, options.userId);
try {
const result = await executeBashCommand({
region: targetConfig.region,
runtimeArn: agentState.runtimeArn,
command,
sessionId: options.sessionId,
timeout: options.timeout,
headers: options.headers,
bearerToken: options.bearerToken,
});
let stdout = '';
let stderr = '';
let exitCode: number | undefined;
let status: string | undefined;
for await (const event of result.stream) {
switch (event.type) {
case 'stdout':
if (event.data) {
stdout += event.data;
if (!options.json) {
process.stdout.write(event.data);
}
}
break;
case 'stderr':
if (event.data) {
stderr += event.data;
if (!options.json) {
process.stderr.write(event.data);
}
}
break;
case 'stop':
exitCode = event.exitCode;
status = event.status;
break;
}
}
logger.logResponse(stdout || stderr || `exit code: ${exitCode}`);
if (options.json) {
return {
success: exitCode === 0,
agentName: agentSpec.name,
targetName: selectedTargetName,
response: JSON.stringify({ stdout, stderr, exitCode, status }),
logFilePath: logger.logFilePath,
};
}
if (exitCode === undefined) {
return {
success: false,
agentName: agentSpec.name,
targetName: selectedTargetName,
error: 'Command stream ended without exit code',
logFilePath: logger.logFilePath,
};
}
if (exitCode !== 0) {
return {
success: false,
agentName: agentSpec.name,
targetName: selectedTargetName,
error: `Command exited with code ${exitCode}${status === 'TIMED_OUT' ? ' (timed out)' : ''}`,
logFilePath: logger.logFilePath,
};
}
return {
success: true,
agentName: agentSpec.name,
targetName: selectedTargetName,
logFilePath: logger.logFilePath,
};
} catch (err) {
logger.logError(err, 'exec command failed');
throw err;
}
}
// MCP protocol handling
if (agentSpec.protocol === 'MCP') {
const mcpOpts = {
region: targetConfig.region,
runtimeArn: agentState.runtimeArn,
userId: options.userId,
headers: options.headers,
bearerToken: options.bearerToken,
};
// list-tools: list available MCP tools
if (options.prompt === 'list-tools') {
try {
const result = await mcpListTools(mcpOpts);
const response = formatMcpToolList(result.tools);
return {
success: true,
agentName: agentSpec.name,
targetName: selectedTargetName,
response,
};
} catch (err) {
return {
success: false,
error: `Failed to list MCP tools: ${err instanceof Error ? err.message : String(err)}`,
};
}
}
// call-tool: call an MCP tool by name
if (options.prompt === 'call-tool') {
if (!options.tool) {
return {
success: false,
error: 'MCP call-tool requires --tool <name>. Use "list-tools" to see available tools.',
};
}
let args: Record<string, unknown> = {};
if (options.input) {
try {
args = JSON.parse(options.input) as Record<string, unknown>;
} catch {
return { success: false, error: `Invalid JSON for --input: ${options.input}` };
}
}
try {
// Lightweight init to get session ID (no tools/list round-trip)
const mcpSessionId = await mcpInitSession(mcpOpts);
const response = await mcpCallTool({ ...mcpOpts, mcpSessionId }, options.tool, args);
return {
success: true,
agentName: agentSpec.name,
targetName: selectedTargetName,
response,
};
} catch (err) {
return {
success: false,
error: `Failed to call MCP tool: ${err instanceof Error ? err.message : String(err)}`,
};
}
}
if (!options.prompt) {
return {
success: false,
error:
'MCP agents require a command. Usage:\n agentcore invoke list-tools\n agentcore invoke call-tool --tool <name> --input \'{"arg": "value"}\'',
};
}
}
if (!options.prompt) {
return { success: false, error: 'No prompt provided. Usage: agentcore invoke "your prompt"' };
}
// A2A protocol handling — send JSON-RPC message/send via InvokeAgentRuntime
if (agentSpec.protocol === 'A2A') {
try {
const a2aResult = await invokeA2ARuntime(
{
region: targetConfig.region,
runtimeArn: agentState.runtimeArn,
userId: options.userId,
sessionId: options.sessionId,
headers: options.headers,
},
options.prompt
);
let response = '';
for await (const chunk of a2aResult.stream) {
response += chunk;
if (options.stream) {
process.stdout.write(chunk);
}
}
if (options.stream) {
process.stdout.write('\n');
}
return {
success: true,
agentName: agentSpec.name,
targetName: selectedTargetName,
response,
};
} catch (err) {
return { success: false, error: `A2A invoke failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
// Create logger for this invocation
const logger = new InvokeLogger({
agentName: agentSpec.name,
runtimeArn: agentState.runtimeArn,
region: targetConfig.region,
sessionId: options.sessionId,
});
logger.logPrompt(options.prompt, options.sessionId, options.userId);
if (options.stream) {
// Streaming mode
let fullResponse = '';
try {
const result = await invokeAgentRuntimeStreaming({
region: targetConfig.region,
runtimeArn: agentState.runtimeArn,
payload: options.prompt,
sessionId: options.sessionId,
userId: options.userId,
logger,
headers: options.headers,
bearerToken: options.bearerToken,
});
for await (const chunk of result.stream) {
fullResponse += chunk;
process.stdout.write(chunk);
}
process.stdout.write('\n');
logger.logResponse(fullResponse);
return {
success: true,
agentName: agentSpec.name,
targetName: selectedTargetName,
response: fullResponse,
logFilePath: logger.logFilePath,
};
} catch (err) {
logger.logError(err, 'invoke streaming failed');
throw err;
}
}
// Non-streaming mode
const response = await invokeAgentRuntime({
region: targetConfig.region,
runtimeArn: agentState.runtimeArn,
payload: options.prompt,
sessionId: options.sessionId,
userId: options.userId,
headers: options.headers,
bearerToken: options.bearerToken,
});
logger.logResponse(response.content);
return {
success: true,
agentName: agentSpec.name,
targetName: selectedTargetName,
response: response.content,
logFilePath: logger.logFilePath,
};
}