-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathagent-headless.ts
More file actions
370 lines (329 loc) · 11.2 KB
/
agent-headless.ts
File metadata and controls
370 lines (329 loc) · 11.2 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
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview AgentHeadless — one-shot task execution wrapper around AgentCore.
*
* AgentHeadless manages
* the lifecycle of a single headless task: start → run → finish.
* It delegates all model reasoning and tool scheduling to AgentCore.
*
* For persistent interactive agents, see AgentInteractive (Phase 2).
*/
import type { Config } from '../../config/config.js';
import { createDebugLogger } from '../../utils/debugLogger.js';
import type {
AgentEventEmitter,
AgentStartEvent,
AgentErrorEvent,
AgentFinishEvent,
AgentHooks,
} from './agent-events.js';
import { AgentEventType } from './agent-events.js';
import type { AgentStatsSummary } from './agent-statistics.js';
import type {
PromptConfig,
ModelConfig,
RunConfig,
ToolConfig,
} from './agent-types.js';
import { AgentTerminateMode } from './agent-types.js';
import { logSubagentExecution } from '../../telemetry/loggers.js';
import { SubagentExecutionEvent } from '../../telemetry/types.js';
import { AgentCore } from './agent-core.js';
import { DEFAULT_QWEN_MODEL } from '../../config/models.js';
const debugLogger = createDebugLogger('SUBAGENT');
// ─── Utilities (unchanged, re-exported for consumers) ────────
/**
* Manages the runtime context state for the subagent.
* This class provides a mechanism to store and retrieve key-value pairs
* that represent the dynamic state and variables accessible to the subagent
* during its execution.
*/
export class ContextState {
private state: Record<string, unknown> = {};
/**
* Retrieves a value from the context state.
*
* @param key - The key of the value to retrieve.
* @returns The value associated with the key, or undefined if the key is not found.
*/
get(key: string): unknown {
return this.state[key];
}
/**
* Sets a value in the context state.
*
* @param key - The key to set the value under.
* @param value - The value to set.
*/
set(key: string, value: unknown): void {
this.state[key] = value;
}
/**
* Retrieves all keys in the context state.
*
* @returns An array of all keys in the context state.
*/
get_keys(): string[] {
return Object.keys(this.state);
}
}
/**
* Replaces `${...}` placeholders in a template string with values from a context.
*
* This function identifies all placeholders in the format `${key}`, validates that
* each key exists in the provided `ContextState`, and then performs the substitution.
*
* @param template The template string containing placeholders.
* @param context The `ContextState` object providing placeholder values.
* @returns The populated string with all placeholders replaced.
* @throws {Error} if any placeholder key is not found in the context.
*/
export function templateString(
template: string,
context: ContextState,
): string {
const placeholderRegex = /\$\{(\w+)\}/g;
// First, find all unique keys required by the template.
const requiredKeys = new Set(
Array.from(template.matchAll(placeholderRegex), (match) => match[1]),
);
// Check if all required keys exist in the context.
const contextKeys = new Set(context.get_keys());
const missingKeys = Array.from(requiredKeys).filter(
(key) => !contextKeys.has(key),
);
if (missingKeys.length > 0) {
throw new Error(
`Missing context values for the following keys: ${missingKeys.join(
', ',
)}`,
);
}
// Perform the replacement using a replacer function.
return template.replace(placeholderRegex, (_match, key) =>
String(context.get(key)),
);
}
// ─── AgentHeadless ──────────────────────────────────────────
/**
* AgentHeadless — one-shot task executor.
*
* Takes a task, runs it through AgentCore's reasoning loop, and returns
* the result.
*
* Lifecycle: Born → execute() → die.
*/
export class AgentHeadless {
private readonly core: AgentCore;
private finalText: string = '';
private terminateMode: AgentTerminateMode = AgentTerminateMode.ERROR;
private constructor(core: AgentCore) {
this.core = core;
}
/**
* Creates a new AgentHeadless instance.
*
* @param name - The name for the subagent, used for logging and identification.
* @param runtimeContext - The shared runtime configuration and services.
* @param promptConfig - Configuration for the subagent's prompt and behavior.
* @param modelConfig - Configuration for the generative model parameters.
* @param runConfig - Configuration for the subagent's execution environment.
* @param toolConfig - Optional configuration for tools available to the subagent.
* @param eventEmitter - Optional event emitter for streaming events to UI.
* @param hooks - Optional lifecycle hooks.
*/
static async create(
name: string,
runtimeContext: Config,
promptConfig: PromptConfig,
modelConfig: ModelConfig,
runConfig: RunConfig,
toolConfig?: ToolConfig,
eventEmitter?: AgentEventEmitter,
hooks?: AgentHooks,
): Promise<AgentHeadless> {
const core = new AgentCore(
name,
runtimeContext,
promptConfig,
modelConfig,
runConfig,
toolConfig,
eventEmitter,
hooks,
);
return new AgentHeadless(core);
}
/**
* Executes the task in headless mode.
*
* This method orchestrates the subagent's execution lifecycle:
* 1. Creates a chat session
* 2. Prepares tools
* 3. Runs the reasoning loop until completion/termination
* 4. Emits start/finish/error events
* 5. Records telemetry
*
* @param context - The current context state containing variables for prompt templating.
* @param externalSignal - Optional abort signal for external cancellation.
*/
async execute(
context: ContextState,
externalSignal?: AbortSignal,
options?: {
extraHistory?: Array<import('@google/genai').Content>;
/** Override generationConfig for cache sharing (fork subagent). */
generationConfigOverride?: import('@google/genai').GenerateContentConfig;
/** Override tool declarations for cache sharing (fork subagent). */
toolsOverride?: Array<import('@google/genai').FunctionDeclaration>;
},
): Promise<void> {
const chat = await this.core.createChat(context, {
extraHistory: options?.extraHistory,
generationConfigOverride: options?.generationConfigOverride,
});
if (!chat) {
this.terminateMode = AgentTerminateMode.ERROR;
return;
}
// Set up abort signal propagation
const abortController = new AbortController();
const onExternalAbort = () => {
abortController.abort();
};
if (externalSignal) {
externalSignal.addEventListener('abort', onExternalAbort);
}
if (externalSignal?.aborted) {
abortController.abort();
}
const toolsList = options?.toolsOverride ?? this.core.prepareTools();
const initialTaskText = String(
(context.get('task_prompt') as string) ?? 'Get Started!',
);
const initialMessages = [
{ role: 'user' as const, parts: [{ text: initialTaskText }] },
];
const startTime = Date.now();
this.core.executionStats.startTimeMs = startTime;
this.core.stats.start(startTime);
try {
// Emit start event
this.core.eventEmitter?.emit(AgentEventType.START, {
subagentId: this.core.subagentId,
name: this.core.name,
model:
this.core.modelConfig.model ||
this.core.runtimeContext.getModel() ||
DEFAULT_QWEN_MODEL,
tools: (this.core.toolConfig?.tools || ['*']).map((t) =>
typeof t === 'string' ? t : t.name,
),
timestamp: Date.now(),
} as AgentStartEvent);
// Log telemetry for subagent start
const startEvent = new SubagentExecutionEvent(this.core.name, 'started');
logSubagentExecution(this.core.runtimeContext, startEvent);
// Delegate to AgentCore's reasoning loop
const result = await this.core.runReasoningLoop(
chat,
initialMessages,
toolsList,
abortController,
{
maxTurns: this.core.runConfig.max_turns,
maxTimeMinutes: this.core.runConfig.max_time_minutes,
startTimeMs: startTime,
},
);
this.finalText = result.text;
this.terminateMode = result.terminateMode ?? AgentTerminateMode.GOAL;
} catch (error) {
debugLogger.error('Error during subagent execution:', error);
this.terminateMode = AgentTerminateMode.ERROR;
this.core.eventEmitter?.emit(AgentEventType.ERROR, {
subagentId: this.core.subagentId,
error: error instanceof Error ? error.message : String(error),
timestamp: Date.now(),
} as AgentErrorEvent);
throw error;
} finally {
if (externalSignal) {
externalSignal.removeEventListener('abort', onExternalAbort);
}
this.core.executionStats.totalDurationMs = Date.now() - startTime;
const summary = this.core.stats.getSummary(Date.now());
this.core.eventEmitter?.emit(AgentEventType.FINISH, {
subagentId: this.core.subagentId,
terminateReason: this.terminateMode,
timestamp: Date.now(),
rounds: summary.rounds,
totalDurationMs: summary.totalDurationMs,
totalToolCalls: summary.totalToolCalls,
successfulToolCalls: summary.successfulToolCalls,
failedToolCalls: summary.failedToolCalls,
inputTokens: summary.inputTokens,
outputTokens: summary.outputTokens,
totalTokens: summary.totalTokens,
} as AgentFinishEvent);
const completionEvent = new SubagentExecutionEvent(
this.core.name,
this.terminateMode === AgentTerminateMode.GOAL ? 'completed' : 'failed',
{
terminate_reason: this.terminateMode,
result: this.finalText,
execution_summary: this.core.stats.formatCompact(
'Subagent execution completed',
),
},
);
logSubagentExecution(this.core.runtimeContext, completionEvent);
await this.core.hooks?.onStop?.({
subagentId: this.core.subagentId,
name: this.core.name,
terminateReason: this.terminateMode,
summary: summary as unknown as Record<string, unknown>,
timestamp: Date.now(),
});
}
}
// ─── Accessors ─────────────────────────────────────────────
/**
* Provides access to the underlying AgentCore for advanced use cases.
* Used by AgentInteractive and InProcessBackend.
*/
getCore(): AgentCore {
return this.core;
}
get executionStats() {
return this.core.executionStats;
}
set executionStats(value) {
this.core.executionStats = value;
}
getEventEmitter() {
return this.core.getEventEmitter();
}
getStatistics() {
return this.core.getStatistics();
}
getExecutionSummary(): AgentStatsSummary {
return this.core.getExecutionSummary();
}
getFinalText(): string {
return this.finalText;
}
getTerminateMode(): AgentTerminateMode {
return this.terminateMode;
}
get name(): string {
return this.core.name;
}
get runtimeContext(): Config {
return this.core.runtimeContext;
}
}