@agentic-patterns/runtime 0.1.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/LICENSE +21 -0
- package/README.md +402 -0
- package/dist/index.cjs +7233 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3406 -0
- package/dist/index.d.ts +3406 -0
- package/dist/index.js +7109 -0
- package/dist/index.js.map +1 -0
- package/package.json +85 -0
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,3406 @@
|
|
|
1
|
+
import { LanguageModelV1, CoreMessage, LanguageModelV1CallOptions } from 'ai';
|
|
2
|
+
import * as _anthropic_ai_claude_agent_sdk from '@anthropic-ai/claude-agent-sdk';
|
|
3
|
+
import { Options } from '@anthropic-ai/claude-agent-sdk';
|
|
4
|
+
import * as _agentic_patterns_core from '@agentic-patterns/core';
|
|
5
|
+
import { Capability, ToolSchema, Toolbox, ToolDefinition, Agent, Agency, Role, Judgment, Responsibility } from '@agentic-patterns/core';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Claude Code hook event — bridges Claude Code lifecycle hooks into the
|
|
10
|
+
* AgentEventBus.
|
|
11
|
+
*
|
|
12
|
+
* The Claude Code CLI emits hook callbacks (PreToolUse, PostToolUse,
|
|
13
|
+
* SessionStart, etc.) as JSON payloads to a configured command. The hook
|
|
14
|
+
* bridge in `@agentic-patterns/server` receives those payloads via HTTP
|
|
15
|
+
* and republishes each one as a `ClaudeCodeHookEvent`.
|
|
16
|
+
*
|
|
17
|
+
* The full raw hook payload is preserved on `payload` so downstream
|
|
18
|
+
* consumers (dashboards, exporters) never lose information. A small
|
|
19
|
+
* mappable subset (PreToolUse / PostToolUse) is also projected onto the
|
|
20
|
+
* canonical `agent.tool.start` / `agent.tool.end` events by the
|
|
21
|
+
* `mapClaudeCodeHookToAgentEvents` helper in
|
|
22
|
+
* `./claude-code-mapper.ts` — that lives in a separate file so this
|
|
23
|
+
* module stays a pure type/constant declaration.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
declare const CLAUDE_CODE_HOOK_EVENTS: readonly ["SessionStart", "InstructionsLoaded", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PermissionDenied", "PostToolUse", "PostToolUseFailure", "Notification", "SubagentStart", "SubagentStop", "TaskCreated", "TaskCompleted", "Stop", "StopFailure", "TeammateIdle", "ConfigChange", "CwdChanged", "FileChanged", "WorktreeCreate", "WorktreeRemove", "PreCompact", "PostCompact", "Elicitation", "ElicitationResult", "SessionEnd"];
|
|
27
|
+
type ClaudeCodeHookName = (typeof CLAUDE_CODE_HOOK_EVENTS)[number];
|
|
28
|
+
/**
|
|
29
|
+
* A single Claude Code hook callback, lifted into an AgentEvent.
|
|
30
|
+
*
|
|
31
|
+
* Every Claude Code hook invocation produces one of these. The full
|
|
32
|
+
* raw payload is preserved on `payload`; common fields (sessionId,
|
|
33
|
+
* cwd, toolName, ...) are also surfaced as top-level convenience
|
|
34
|
+
* properties for typed consumers. PreToolUse and PostToolUse can be
|
|
35
|
+
* additionally mapped to canonical `agent.tool.start` / `agent.tool.end`
|
|
36
|
+
* events via `mapClaudeCodeHookToAgentEvents`.
|
|
37
|
+
*/
|
|
38
|
+
interface ClaudeCodeHookEvent extends BaseEvent {
|
|
39
|
+
readonly type: "claude_code.hook";
|
|
40
|
+
readonly hookName: ClaudeCodeHookName;
|
|
41
|
+
readonly sessionId: string;
|
|
42
|
+
readonly transcriptPath?: string;
|
|
43
|
+
readonly cwd?: string;
|
|
44
|
+
readonly permissionMode?: string;
|
|
45
|
+
readonly toolName?: string;
|
|
46
|
+
readonly toolInput?: unknown;
|
|
47
|
+
readonly toolResponse?: unknown;
|
|
48
|
+
readonly toolUseId?: string;
|
|
49
|
+
/** Full raw hook payload, preserved verbatim. */
|
|
50
|
+
readonly payload: Record<string, unknown>;
|
|
51
|
+
/**
|
|
52
|
+
* Correlation id propagated from a runner (e.g. `ClaudeCodeRunner`) that
|
|
53
|
+
* is already observing this session. When present, the hook route SKIPS
|
|
54
|
+
* deriving `agent.tool.start`/`agent.tool.end` events — the runner
|
|
55
|
+
* already emits them — while still preserving the raw hook event for
|
|
56
|
+
* full fidelity (PreCompact, PermissionRequest, etc.).
|
|
57
|
+
*/
|
|
58
|
+
readonly runnerCorrelationId?: string;
|
|
59
|
+
}
|
|
60
|
+
declare function isClaudeCodeHookName(s: unknown): s is ClaudeCodeHookName;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Core event types for runner observability.
|
|
64
|
+
*
|
|
65
|
+
* All events use a discriminated union on the `type` field.
|
|
66
|
+
* Trace fields (traceId, runId, spanId, parentSpanId, timestamp) on every event.
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
interface BaseEvent {
|
|
70
|
+
readonly type: string;
|
|
71
|
+
readonly traceId: string;
|
|
72
|
+
readonly runId: string;
|
|
73
|
+
readonly spanId: string;
|
|
74
|
+
readonly parentSpanId?: string;
|
|
75
|
+
readonly timestamp: Date;
|
|
76
|
+
}
|
|
77
|
+
interface MessageStartEvent extends BaseEvent {
|
|
78
|
+
readonly type: "agent.message.start";
|
|
79
|
+
readonly agentName: string;
|
|
80
|
+
readonly agentConfig?: Record<string, unknown>;
|
|
81
|
+
}
|
|
82
|
+
interface MessageChunkEvent extends BaseEvent {
|
|
83
|
+
readonly type: "agent.message.chunk";
|
|
84
|
+
readonly delta: string;
|
|
85
|
+
readonly chunkIndex: number;
|
|
86
|
+
}
|
|
87
|
+
interface MessageCompleteEvent extends BaseEvent {
|
|
88
|
+
readonly type: "agent.message.complete";
|
|
89
|
+
readonly content: string;
|
|
90
|
+
readonly inputTokens: number;
|
|
91
|
+
readonly outputTokens: number;
|
|
92
|
+
readonly model: string;
|
|
93
|
+
}
|
|
94
|
+
interface ReasoningEvent extends BaseEvent {
|
|
95
|
+
readonly type: "agent.reasoning";
|
|
96
|
+
readonly content: string;
|
|
97
|
+
readonly isComplete: boolean;
|
|
98
|
+
}
|
|
99
|
+
interface ToolCallIntent extends BaseEvent {
|
|
100
|
+
readonly type: "agent.tool.intent";
|
|
101
|
+
readonly toolCallId: string;
|
|
102
|
+
readonly toolName: string;
|
|
103
|
+
readonly arguments: Record<string, unknown>;
|
|
104
|
+
}
|
|
105
|
+
interface ToolCallRejectedEvent extends BaseEvent {
|
|
106
|
+
readonly type: "agent.tool.rejected";
|
|
107
|
+
readonly toolName: string;
|
|
108
|
+
readonly reason: string;
|
|
109
|
+
readonly gateName: string;
|
|
110
|
+
readonly gateCategory: string;
|
|
111
|
+
readonly originalIntent: ToolCallIntent;
|
|
112
|
+
}
|
|
113
|
+
interface ToolCallStartEvent extends BaseEvent {
|
|
114
|
+
readonly type: "agent.tool.start";
|
|
115
|
+
readonly toolCallId: string;
|
|
116
|
+
readonly toolName: string;
|
|
117
|
+
readonly arguments: Record<string, unknown>;
|
|
118
|
+
readonly parentEventId?: string;
|
|
119
|
+
}
|
|
120
|
+
interface ToolCallEndEvent extends BaseEvent {
|
|
121
|
+
readonly type: "agent.tool.end";
|
|
122
|
+
readonly toolCallId: string;
|
|
123
|
+
readonly toolName: string;
|
|
124
|
+
readonly arguments: Record<string, unknown>;
|
|
125
|
+
readonly result: unknown;
|
|
126
|
+
readonly error?: string;
|
|
127
|
+
readonly durationMs: number;
|
|
128
|
+
readonly resultTokens: number;
|
|
129
|
+
}
|
|
130
|
+
interface IterationStartEvent extends BaseEvent {
|
|
131
|
+
readonly type: "agent.iteration.start";
|
|
132
|
+
readonly iteration: number;
|
|
133
|
+
readonly maxIterations: number;
|
|
134
|
+
}
|
|
135
|
+
interface IterationEndEvent extends BaseEvent {
|
|
136
|
+
readonly type: "agent.iteration.end";
|
|
137
|
+
readonly iteration: number;
|
|
138
|
+
readonly toolCallsCount: number;
|
|
139
|
+
readonly hasMore: boolean;
|
|
140
|
+
}
|
|
141
|
+
interface LLMCallStartEvent extends BaseEvent {
|
|
142
|
+
readonly type: "agent.llm.start";
|
|
143
|
+
readonly model: string;
|
|
144
|
+
readonly messageCount: number;
|
|
145
|
+
readonly hasTools: boolean;
|
|
146
|
+
}
|
|
147
|
+
interface LLMCallEndEvent extends BaseEvent {
|
|
148
|
+
readonly type: "agent.llm.end";
|
|
149
|
+
readonly model: string;
|
|
150
|
+
readonly inputTokens: number;
|
|
151
|
+
readonly outputTokens: number;
|
|
152
|
+
readonly durationMs: number;
|
|
153
|
+
readonly hasToolCalls: boolean;
|
|
154
|
+
readonly finishReason: string;
|
|
155
|
+
}
|
|
156
|
+
interface ConversationStartEvent extends BaseEvent {
|
|
157
|
+
readonly type: "agent.conversation.start";
|
|
158
|
+
readonly conversationId: string;
|
|
159
|
+
readonly agentName: string;
|
|
160
|
+
}
|
|
161
|
+
interface ConversationEndEvent extends BaseEvent {
|
|
162
|
+
readonly type: "agent.conversation.end";
|
|
163
|
+
readonly conversationId: string;
|
|
164
|
+
readonly reason: "completed" | "error" | "cancelled";
|
|
165
|
+
}
|
|
166
|
+
interface MessageCancelEvent extends BaseEvent {
|
|
167
|
+
readonly type: "agent.message.cancel";
|
|
168
|
+
readonly reason?: string;
|
|
169
|
+
}
|
|
170
|
+
interface ThinkingStartEvent extends BaseEvent {
|
|
171
|
+
readonly type: "agent.thinking.start";
|
|
172
|
+
}
|
|
173
|
+
interface ToolProgressEvent extends BaseEvent {
|
|
174
|
+
readonly type: "agent.tool.progress";
|
|
175
|
+
readonly toolCallId: string;
|
|
176
|
+
readonly progress?: number;
|
|
177
|
+
readonly statusText?: string;
|
|
178
|
+
}
|
|
179
|
+
interface ErrorEvent extends BaseEvent {
|
|
180
|
+
readonly type: "agent.error";
|
|
181
|
+
readonly errorType: string;
|
|
182
|
+
readonly message: string;
|
|
183
|
+
readonly recoverable: boolean;
|
|
184
|
+
readonly stackTrace?: string;
|
|
185
|
+
readonly context: Record<string, unknown>;
|
|
186
|
+
}
|
|
187
|
+
type AgentEvent = ConversationStartEvent | ConversationEndEvent | MessageStartEvent | MessageChunkEvent | MessageCompleteEvent | MessageCancelEvent | ReasoningEvent | ThinkingStartEvent | ToolCallIntent | ToolCallRejectedEvent | ToolCallStartEvent | ToolCallEndEvent | ToolProgressEvent | IterationStartEvent | IterationEndEvent | LLMCallStartEvent | LLMCallEndEvent | ErrorEvent | ClaudeCodeHookEvent;
|
|
188
|
+
/** All possible agent event type strings. */
|
|
189
|
+
type AgentEventType = AgentEvent["type"];
|
|
190
|
+
/** Subset of events for backward-compatible StreamEvent alias. */
|
|
191
|
+
type StreamEvent = ConversationStartEvent | ConversationEndEvent | MessageStartEvent | MessageChunkEvent | MessageCompleteEvent | MessageCancelEvent | ReasoningEvent | ThinkingStartEvent | ToolCallIntent | ToolCallStartEvent | ToolCallEndEvent | ToolProgressEvent | IterationStartEvent | IterationEndEvent | LLMCallStartEvent | LLMCallEndEvent;
|
|
192
|
+
/**
|
|
193
|
+
* Create an event with auto-filled timestamp and optional spanId.
|
|
194
|
+
*
|
|
195
|
+
* @param type - The event type discriminant
|
|
196
|
+
* @param data - Event fields (excluding type, timestamp; spanId optional)
|
|
197
|
+
* @returns A fully-formed event
|
|
198
|
+
*/
|
|
199
|
+
declare function createEvent<T extends AgentEventType>(type: T, data: Omit<Extract<AgentEvent, {
|
|
200
|
+
type: T;
|
|
201
|
+
}>, "type" | "timestamp" | "spanId"> & {
|
|
202
|
+
spanId?: string;
|
|
203
|
+
}): Extract<AgentEvent, {
|
|
204
|
+
type: T;
|
|
205
|
+
}>;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Map Claude Code hook events to canonical AgentEvent variants.
|
|
209
|
+
*
|
|
210
|
+
* Only PreToolUse / PostToolUse currently map to standard events
|
|
211
|
+
* (`agent.tool.start` / `agent.tool.end`). All other hook names yield
|
|
212
|
+
* an empty array — consumers that want full coverage should subscribe
|
|
213
|
+
* to `claude_code.hook` directly.
|
|
214
|
+
*/
|
|
215
|
+
|
|
216
|
+
declare function mapClaudeCodeHookToAgentEvents(event: ClaudeCodeHookEvent): AgentEvent[];
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Sandbox events for inter-agent communication and environment lifecycle.
|
|
220
|
+
*
|
|
221
|
+
* All sandbox events carry an AgentAddress origin and extend BaseEvent.
|
|
222
|
+
*/
|
|
223
|
+
|
|
224
|
+
interface AgentAddress {
|
|
225
|
+
readonly deviceId: string;
|
|
226
|
+
readonly instanceId: string;
|
|
227
|
+
readonly agentId: string;
|
|
228
|
+
readonly role: string;
|
|
229
|
+
}
|
|
230
|
+
declare function createAgentAddress(partial?: Partial<AgentAddress>): AgentAddress;
|
|
231
|
+
declare function agentAddressToString(addr: AgentAddress): string;
|
|
232
|
+
interface BaseSandboxEvent extends BaseEvent {
|
|
233
|
+
readonly origin: AgentAddress;
|
|
234
|
+
readonly target?: AgentAddress;
|
|
235
|
+
readonly correlationId?: string;
|
|
236
|
+
readonly agencyId: string;
|
|
237
|
+
readonly lineupRunId: string;
|
|
238
|
+
}
|
|
239
|
+
interface AgentMessageEvent extends BaseSandboxEvent {
|
|
240
|
+
readonly type: "sandbox.agent.message";
|
|
241
|
+
readonly content: string;
|
|
242
|
+
readonly metadata: Record<string, unknown>;
|
|
243
|
+
}
|
|
244
|
+
interface AgentBroadcastEvent extends BaseSandboxEvent {
|
|
245
|
+
readonly type: "sandbox.agent.broadcast";
|
|
246
|
+
readonly content: string;
|
|
247
|
+
readonly channel: string;
|
|
248
|
+
}
|
|
249
|
+
interface AgentJoinEvent extends BaseSandboxEvent {
|
|
250
|
+
readonly type: "sandbox.agent.join";
|
|
251
|
+
readonly reason: string;
|
|
252
|
+
}
|
|
253
|
+
interface AgentLeaveEvent extends BaseSandboxEvent {
|
|
254
|
+
readonly type: "sandbox.agent.leave";
|
|
255
|
+
readonly reason: string;
|
|
256
|
+
}
|
|
257
|
+
interface TaskCreateEvent extends BaseSandboxEvent {
|
|
258
|
+
readonly type: "sandbox.task.create";
|
|
259
|
+
readonly taskId: string;
|
|
260
|
+
readonly taskTitle: string;
|
|
261
|
+
}
|
|
262
|
+
interface TaskUpdateEvent extends BaseSandboxEvent {
|
|
263
|
+
readonly type: "sandbox.task.update";
|
|
264
|
+
readonly taskId: string;
|
|
265
|
+
readonly changes: Record<string, unknown>;
|
|
266
|
+
}
|
|
267
|
+
interface TaskAssignEvent extends BaseSandboxEvent {
|
|
268
|
+
readonly type: "sandbox.task.assign";
|
|
269
|
+
readonly taskId: string;
|
|
270
|
+
readonly assignee: AgentAddress;
|
|
271
|
+
}
|
|
272
|
+
interface HealthPingEvent extends BaseSandboxEvent {
|
|
273
|
+
readonly type: "sandbox.health.ping";
|
|
274
|
+
}
|
|
275
|
+
interface HealthPongEvent extends BaseSandboxEvent {
|
|
276
|
+
readonly type: "sandbox.health.pong";
|
|
277
|
+
readonly status: string;
|
|
278
|
+
readonly uptimeSeconds: number;
|
|
279
|
+
}
|
|
280
|
+
interface NodeLifecycleEvent extends BaseSandboxEvent {
|
|
281
|
+
readonly type: "sandbox.node.lifecycle";
|
|
282
|
+
readonly nodeEventType: "node.started" | "node.stopped" | "node.message_received" | "node.response_sent";
|
|
283
|
+
readonly message: string;
|
|
284
|
+
readonly metadata: Record<string, unknown>;
|
|
285
|
+
}
|
|
286
|
+
type SandboxEvent = AgentMessageEvent | AgentBroadcastEvent | AgentJoinEvent | AgentLeaveEvent | TaskCreateEvent | TaskUpdateEvent | TaskAssignEvent | HealthPingEvent | HealthPongEvent | NodeLifecycleEvent;
|
|
287
|
+
type SandboxEventType = SandboxEvent["type"];
|
|
288
|
+
/**
|
|
289
|
+
* Serialize a sandbox event to a JSON string for transport.
|
|
290
|
+
*/
|
|
291
|
+
declare function serializeSandboxEventToString(event: SandboxEvent): string;
|
|
292
|
+
/**
|
|
293
|
+
* Serialize a sandbox event to bytes for transport.
|
|
294
|
+
*/
|
|
295
|
+
declare function serializeSandboxEvent(event: SandboxEvent): Uint8Array;
|
|
296
|
+
/**
|
|
297
|
+
* Deserialize a sandbox event from a JSON string.
|
|
298
|
+
*/
|
|
299
|
+
declare function deserializeSandboxEventFromString(json: string): SandboxEvent;
|
|
300
|
+
/**
|
|
301
|
+
* Deserialize a sandbox event from bytes.
|
|
302
|
+
*/
|
|
303
|
+
declare function deserializeSandboxEvent(data: Uint8Array): SandboxEvent;
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Async-capable event bus for publishing and subscribing to events.
|
|
307
|
+
*
|
|
308
|
+
* Handlers sorted by priority (higher = executed first).
|
|
309
|
+
* Middleware can transform or drop events (return null).
|
|
310
|
+
*/
|
|
311
|
+
|
|
312
|
+
/** Handler function that receives an event. Can be sync or async. */
|
|
313
|
+
type EventHandlerFn<E extends BaseEvent = BaseEvent> = (event: E) => unknown | Promise<unknown>;
|
|
314
|
+
/** Middleware function. Return null to stop propagation, or a new event to transform. */
|
|
315
|
+
type MiddlewareFn<E extends BaseEvent = BaseEvent> = (event: E) => E | null | Promise<E | null>;
|
|
316
|
+
declare class EventBus {
|
|
317
|
+
private _handlers;
|
|
318
|
+
private _globalHandlers;
|
|
319
|
+
private _middleware;
|
|
320
|
+
/**
|
|
321
|
+
* Subscribe a handler to a specific event type.
|
|
322
|
+
*
|
|
323
|
+
* @param eventType - Event type string to listen for
|
|
324
|
+
* @param handler - Handler function (sync or async)
|
|
325
|
+
* @param priority - Higher priority executes first (default 0)
|
|
326
|
+
*/
|
|
327
|
+
subscribe(eventType: string, handler: EventHandlerFn, priority?: number): void;
|
|
328
|
+
/**
|
|
329
|
+
* Subscribe a handler to all events.
|
|
330
|
+
*/
|
|
331
|
+
subscribeAll(handler: EventHandlerFn, priority?: number): void;
|
|
332
|
+
/**
|
|
333
|
+
* Unsubscribe a handler from a specific event type.
|
|
334
|
+
*/
|
|
335
|
+
unsubscribe(eventType: string, handler: EventHandlerFn): void;
|
|
336
|
+
/**
|
|
337
|
+
* Unsubscribe a handler from all events.
|
|
338
|
+
*/
|
|
339
|
+
unsubscribeAll(handler: EventHandlerFn): void;
|
|
340
|
+
/**
|
|
341
|
+
* Add middleware to process events before handlers.
|
|
342
|
+
*
|
|
343
|
+
* Middleware can modify events or stop propagation by returning null.
|
|
344
|
+
*/
|
|
345
|
+
addMiddleware(middleware: MiddlewareFn): void;
|
|
346
|
+
/**
|
|
347
|
+
* Publish an event to all registered handlers.
|
|
348
|
+
*
|
|
349
|
+
* @returns List of handler results
|
|
350
|
+
*/
|
|
351
|
+
publish(event: BaseEvent): Promise<unknown[]>;
|
|
352
|
+
/**
|
|
353
|
+
* Clear all handlers and middleware.
|
|
354
|
+
*/
|
|
355
|
+
clear(): void;
|
|
356
|
+
/**
|
|
357
|
+
* Get the number of handlers for an event type or total.
|
|
358
|
+
*/
|
|
359
|
+
getHandlerCount(eventType?: string): number;
|
|
360
|
+
}
|
|
361
|
+
declare function getEventBus(): EventBus;
|
|
362
|
+
declare function setEventBus(bus: EventBus): void;
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Event profiles for curated event subscriptions.
|
|
366
|
+
*
|
|
367
|
+
* Profiles are handler groups that subscribe to specific event types
|
|
368
|
+
* for different use cases (UX rendering, observability, debugging).
|
|
369
|
+
*/
|
|
370
|
+
|
|
371
|
+
declare const EventProfile: {
|
|
372
|
+
readonly UX: "ux";
|
|
373
|
+
readonly OBSERVABILITY: "obs";
|
|
374
|
+
readonly DEBUG: "debug";
|
|
375
|
+
readonly TOOLS: "tools";
|
|
376
|
+
readonly STREAMING: "stream";
|
|
377
|
+
};
|
|
378
|
+
type EventProfile = (typeof EventProfile)[keyof typeof EventProfile];
|
|
379
|
+
declare const PROFILE_EVENT_TYPES: Readonly<Record<EventProfile, readonly string[]>>;
|
|
380
|
+
/**
|
|
381
|
+
* Subscribe handler to all event types in a profile.
|
|
382
|
+
*
|
|
383
|
+
* @returns List of event types subscribed to.
|
|
384
|
+
*/
|
|
385
|
+
declare function subscribeProfile(bus: EventBus, profile: EventProfile, handler: EventHandlerFn, priority?: number): string[];
|
|
386
|
+
/**
|
|
387
|
+
* Unsubscribe handler from all event types in a profile.
|
|
388
|
+
*/
|
|
389
|
+
declare function unsubscribeProfile(bus: EventBus, profile: EventProfile, handler: EventHandlerFn): void;
|
|
390
|
+
/**
|
|
391
|
+
* Subscribe to multiple profiles, deduplicating event types.
|
|
392
|
+
*/
|
|
393
|
+
declare function subscribeProfiles(bus: EventBus, profiles: EventProfile[], handler: EventHandlerFn, priority?: number): string[];
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Gate base interface and types.
|
|
397
|
+
*
|
|
398
|
+
* Gates intercept intent events and can block, allow, or modify them.
|
|
399
|
+
* They execute in category order: SAFETY -> RATE_LIMIT -> APPROVAL -> AUDIT.
|
|
400
|
+
*/
|
|
401
|
+
|
|
402
|
+
declare const GateCategory: {
|
|
403
|
+
readonly SAFETY: 0;
|
|
404
|
+
readonly RATE_LIMIT: 1;
|
|
405
|
+
readonly APPROVAL: 2;
|
|
406
|
+
readonly AUDIT: 3;
|
|
407
|
+
};
|
|
408
|
+
type GateCategory = (typeof GateCategory)[keyof typeof GateCategory];
|
|
409
|
+
declare const GATE_CATEGORY_NAMES: Readonly<Record<GateCategory, string>>;
|
|
410
|
+
type GateResult = {
|
|
411
|
+
action: "allow";
|
|
412
|
+
} | {
|
|
413
|
+
action: "block";
|
|
414
|
+
reason: string;
|
|
415
|
+
} | {
|
|
416
|
+
action: "modify";
|
|
417
|
+
event: BaseEvent;
|
|
418
|
+
};
|
|
419
|
+
declare const GateAllow: GateResult;
|
|
420
|
+
declare function GateBlock(reason: string): GateResult;
|
|
421
|
+
declare function GateModify(event: BaseEvent): GateResult;
|
|
422
|
+
interface Gate {
|
|
423
|
+
/** Category of this gate for ordering. */
|
|
424
|
+
readonly category: GateCategory;
|
|
425
|
+
/** Gate name for rejection messages. */
|
|
426
|
+
readonly name: string;
|
|
427
|
+
/** Human-readable category name. */
|
|
428
|
+
readonly categoryName: string;
|
|
429
|
+
/** Check an intent event. */
|
|
430
|
+
check(event: BaseEvent): Promise<GateResult>;
|
|
431
|
+
/** Get reason why event was blocked. */
|
|
432
|
+
getBlockReason(event: BaseEvent): string;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Abstract base class for gates.
|
|
436
|
+
* Subclasses must implement check() and set category.
|
|
437
|
+
*/
|
|
438
|
+
declare abstract class BaseGate implements Gate {
|
|
439
|
+
abstract readonly category: GateCategory;
|
|
440
|
+
get name(): string;
|
|
441
|
+
get categoryName(): string;
|
|
442
|
+
abstract check(event: BaseEvent): Promise<GateResult>;
|
|
443
|
+
getBlockReason(_event: BaseEvent): string;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Agent-specific event bus with gate chain for intent filtering.
|
|
448
|
+
*
|
|
449
|
+
* Extends the base EventBus with safety gates that can intercept,
|
|
450
|
+
* block, or modify intent events before they're published.
|
|
451
|
+
*/
|
|
452
|
+
|
|
453
|
+
declare class AgentEventBus extends EventBus {
|
|
454
|
+
private _gateChain;
|
|
455
|
+
/**
|
|
456
|
+
* Add a gate to the chain, automatically sorted by category.
|
|
457
|
+
*/
|
|
458
|
+
addGate(gate: Gate): void;
|
|
459
|
+
/**
|
|
460
|
+
* Remove a gate from the chain.
|
|
461
|
+
*/
|
|
462
|
+
removeGate(gate: Gate): void;
|
|
463
|
+
/**
|
|
464
|
+
* Clear all gates from the chain.
|
|
465
|
+
*/
|
|
466
|
+
clearGates(): void;
|
|
467
|
+
/**
|
|
468
|
+
* Get a copy of the gate chain.
|
|
469
|
+
*/
|
|
470
|
+
get gates(): readonly Gate[];
|
|
471
|
+
/**
|
|
472
|
+
* Publish an event, running intent events through gate chain.
|
|
473
|
+
*
|
|
474
|
+
* Intent events (those with type ending in ".intent") are checked by each gate.
|
|
475
|
+
* If any gate blocks the event, a ToolCallRejected event is emitted instead.
|
|
476
|
+
* Regular events bypass gates entirely.
|
|
477
|
+
*/
|
|
478
|
+
publish(event: BaseEvent): Promise<unknown[]>;
|
|
479
|
+
private _emitRejection;
|
|
480
|
+
}
|
|
481
|
+
declare function getAgentEventBus(): AgentEventBus;
|
|
482
|
+
declare function setAgentEventBus(bus: AgentEventBus): void;
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* Transport protocol abstraction for cross-agent communication.
|
|
486
|
+
*
|
|
487
|
+
* Defines the Transport interface and TransportMessage type.
|
|
488
|
+
* Only InProcessTransport is implemented for v1; the interface
|
|
489
|
+
* preserves the NATS upgrade path.
|
|
490
|
+
*/
|
|
491
|
+
/**
|
|
492
|
+
* Wrapper around raw transport message bytes.
|
|
493
|
+
*/
|
|
494
|
+
interface TransportMessage {
|
|
495
|
+
readonly data: Uint8Array;
|
|
496
|
+
readonly subject: string;
|
|
497
|
+
ack(): Promise<void>;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Abstract transport for inter-agent messaging.
|
|
501
|
+
*
|
|
502
|
+
* Implementations must support NATS-style subject wildcards:
|
|
503
|
+
* - `*` matches exactly one token
|
|
504
|
+
* - `>` matches one or more trailing tokens (must be last segment)
|
|
505
|
+
*/
|
|
506
|
+
interface Transport {
|
|
507
|
+
connect(): Promise<void>;
|
|
508
|
+
close(): Promise<void>;
|
|
509
|
+
ensureStream(name: string, subjects: string[]): Promise<void>;
|
|
510
|
+
publish(subject: string, data: Uint8Array): Promise<void>;
|
|
511
|
+
subscribe(subject: string, callback: (msg: TransportMessage) => void | Promise<void>, durable?: string): Promise<void>;
|
|
512
|
+
request(subject: string, data: Uint8Array, timeout?: number): Promise<Uint8Array>;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* SandboxEventBus - AgentEventBus with pluggable transport for cross-agent messaging.
|
|
517
|
+
*
|
|
518
|
+
* Extends AgentEventBus with dual publish: local handlers + transport publish
|
|
519
|
+
* for SandboxEvents. Subscribes to both direct and broadcast channels.
|
|
520
|
+
*/
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* AgentEventBus extended with transport-aware publishing.
|
|
524
|
+
*
|
|
525
|
+
* - `publish()` dispatches both locally AND to transport for SandboxEvents.
|
|
526
|
+
* - Regular AgentEvents only dispatch locally.
|
|
527
|
+
* - Remote events received via transport are dispatched locally only (no echo loop).
|
|
528
|
+
*/
|
|
529
|
+
declare class SandboxEventBus extends AgentEventBus {
|
|
530
|
+
readonly address: AgentAddress;
|
|
531
|
+
private _transport;
|
|
532
|
+
/**
|
|
533
|
+
* Set of spanIds that this bus has already dispatched locally.
|
|
534
|
+
* Prevents duplicate local dispatch when the InProcessTransport
|
|
535
|
+
* echoes our own publish back to us via subscription.
|
|
536
|
+
*/
|
|
537
|
+
private _locallyPublished;
|
|
538
|
+
constructor(address: AgentAddress, transport: Transport);
|
|
539
|
+
/**
|
|
540
|
+
* Connect transport and set up subscriptions for direct + broadcast channels.
|
|
541
|
+
*/
|
|
542
|
+
start(): Promise<void>;
|
|
543
|
+
/**
|
|
544
|
+
* Close transport.
|
|
545
|
+
*/
|
|
546
|
+
stop(): Promise<void>;
|
|
547
|
+
/**
|
|
548
|
+
* Publish event locally and to transport if it's a SandboxEvent.
|
|
549
|
+
*
|
|
550
|
+
* 1. Local gate chain + handlers (via super.publish)
|
|
551
|
+
* 2. If SandboxEvent, also publish to transport
|
|
552
|
+
*/
|
|
553
|
+
publish(event: BaseEvent): Promise<unknown[]>;
|
|
554
|
+
/**
|
|
555
|
+
* Map event target to transport subject.
|
|
556
|
+
*
|
|
557
|
+
* Targeted: agency.{agencyId}.run.{lineupRunId}.agent.{targetId}
|
|
558
|
+
* Broadcast: agency.{agencyId}._broadcast
|
|
559
|
+
*/
|
|
560
|
+
private _resolveSubject;
|
|
561
|
+
/**
|
|
562
|
+
* Inject remote transport message into local EventBus (no re-publish to transport).
|
|
563
|
+
*
|
|
564
|
+
* Skips events we already published locally (echo prevention for shared transport).
|
|
565
|
+
*/
|
|
566
|
+
private _onRemoteEvent;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Safety gate for blocking dangerous operations.
|
|
571
|
+
*
|
|
572
|
+
* Category: SAFETY (runs first in chain)
|
|
573
|
+
*/
|
|
574
|
+
|
|
575
|
+
declare class SafetyGate extends BaseGate {
|
|
576
|
+
readonly category: 0;
|
|
577
|
+
private _blockedTools;
|
|
578
|
+
private _blockedPatterns;
|
|
579
|
+
private _blockMessage;
|
|
580
|
+
constructor(options?: {
|
|
581
|
+
blockedTools?: Set<string>;
|
|
582
|
+
blockedPatterns?: string[];
|
|
583
|
+
blockMessage?: string;
|
|
584
|
+
});
|
|
585
|
+
check(event: BaseEvent): Promise<GateResult>;
|
|
586
|
+
getBlockReason(event: BaseEvent): string;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Rate limit gate using token bucket algorithm.
|
|
591
|
+
*
|
|
592
|
+
* Category: RATE_LIMIT (runs second)
|
|
593
|
+
*/
|
|
594
|
+
|
|
595
|
+
declare class RateLimitGate extends BaseGate {
|
|
596
|
+
readonly category: 1;
|
|
597
|
+
private _rate;
|
|
598
|
+
private _burst;
|
|
599
|
+
private _tokens;
|
|
600
|
+
private _lastUpdate;
|
|
601
|
+
constructor(options?: {
|
|
602
|
+
callsPerMinute?: number;
|
|
603
|
+
burstSize?: number;
|
|
604
|
+
});
|
|
605
|
+
check(event: BaseEvent): Promise<GateResult>;
|
|
606
|
+
getBlockReason(_event: BaseEvent): string;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* Human approval gate for tool calls.
|
|
611
|
+
*
|
|
612
|
+
* Category: APPROVAL (runs third)
|
|
613
|
+
*/
|
|
614
|
+
|
|
615
|
+
/** Callback that decides whether to approve a tool call. */
|
|
616
|
+
type ApprovalCallback = (event: ToolCallIntent) => boolean | Promise<boolean>;
|
|
617
|
+
declare class HumanApprovalGate extends BaseGate {
|
|
618
|
+
readonly category: 2;
|
|
619
|
+
private _approvalFn;
|
|
620
|
+
private _tools;
|
|
621
|
+
private _autoApprove;
|
|
622
|
+
constructor(options?: {
|
|
623
|
+
approvalFn?: ApprovalCallback;
|
|
624
|
+
tools?: Set<string>;
|
|
625
|
+
autoApprove?: boolean;
|
|
626
|
+
});
|
|
627
|
+
check(event: BaseEvent): Promise<GateResult>;
|
|
628
|
+
getBlockReason(event: BaseEvent): string;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Audit gate for logging all intents.
|
|
633
|
+
*
|
|
634
|
+
* Category: AUDIT (runs last, never blocks)
|
|
635
|
+
*/
|
|
636
|
+
|
|
637
|
+
/** Logger interface — matches console.info signature. */
|
|
638
|
+
interface AuditLogger {
|
|
639
|
+
info(message: string, ...args: unknown[]): void;
|
|
640
|
+
}
|
|
641
|
+
declare class AuditGate extends BaseGate {
|
|
642
|
+
readonly category: 3;
|
|
643
|
+
/** Recorded entries for testing/inspection. */
|
|
644
|
+
readonly entries: Array<{
|
|
645
|
+
type: string;
|
|
646
|
+
toolName: string;
|
|
647
|
+
timestamp: Date;
|
|
648
|
+
}>;
|
|
649
|
+
private _logger;
|
|
650
|
+
constructor(options?: {
|
|
651
|
+
logger?: AuditLogger;
|
|
652
|
+
});
|
|
653
|
+
check(event: BaseEvent): Promise<GateResult>;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* Runner types — AgentLike, RunResult, ToolExecutor, RunnerProtocol, RunOptions.
|
|
658
|
+
*
|
|
659
|
+
* Ported from Python: systems/runners/base.py
|
|
660
|
+
*/
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* The minimal agent shape consumed by runners, workflows, conversations,
|
|
664
|
+
* and transport adapters.
|
|
665
|
+
*
|
|
666
|
+
* This is a projection of the full `Agent` class (from @agentic-patterns/core)
|
|
667
|
+
* containing only the methods and properties needed to execute a tool loop.
|
|
668
|
+
* `getTools()` returns `unknown[]` so protocol consumers don't need to import
|
|
669
|
+
* `ToolSchema` from core — only `AgentRunner` itself narrows the type when
|
|
670
|
+
* converting tools for the LLM.
|
|
671
|
+
*/
|
|
672
|
+
interface AgentLike {
|
|
673
|
+
readonly role: {
|
|
674
|
+
readonly name: string;
|
|
675
|
+
};
|
|
676
|
+
getModel(): string;
|
|
677
|
+
getTools(): unknown[];
|
|
678
|
+
getSystemPrompt(): string;
|
|
679
|
+
renderInitialPrompt(): string;
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Result of an agent execution.
|
|
683
|
+
*/
|
|
684
|
+
interface RunResult {
|
|
685
|
+
/** The final text response from the agent. */
|
|
686
|
+
readonly response: string;
|
|
687
|
+
/** Total input tokens used across all iterations. */
|
|
688
|
+
readonly inputTokens: number;
|
|
689
|
+
/** Total output tokens generated across all iterations. */
|
|
690
|
+
readonly outputTokens: number;
|
|
691
|
+
/** Total number of tool calls executed. */
|
|
692
|
+
readonly toolCallsCount: number;
|
|
693
|
+
/** Number of loop iterations completed. */
|
|
694
|
+
readonly iterations: number;
|
|
695
|
+
/** Reason the run finished (e.g. "stop", "max_iterations"). */
|
|
696
|
+
readonly finishReason: string;
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Protocol for executing tools.
|
|
700
|
+
*
|
|
701
|
+
* Implementations handle the actual tool execution logic.
|
|
702
|
+
* The runner calls execute() for each tool call from the LLM.
|
|
703
|
+
*/
|
|
704
|
+
interface ToolExecutor {
|
|
705
|
+
execute(name: string, args: Record<string, unknown>): Promise<unknown>;
|
|
706
|
+
}
|
|
707
|
+
interface CanonicalMessagePart {
|
|
708
|
+
readonly type: string;
|
|
709
|
+
readonly content?: string;
|
|
710
|
+
readonly id?: string;
|
|
711
|
+
readonly name?: string;
|
|
712
|
+
readonly tool_name?: string;
|
|
713
|
+
readonly tool_call_id?: string;
|
|
714
|
+
readonly arguments?: Record<string, unknown>;
|
|
715
|
+
}
|
|
716
|
+
interface CanonicalMessage {
|
|
717
|
+
readonly kind: "request" | "response";
|
|
718
|
+
readonly parts: CanonicalMessagePart[];
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Options for agent execution.
|
|
722
|
+
*/
|
|
723
|
+
interface RunOptions {
|
|
724
|
+
/** Optional conversation history in canonical format. */
|
|
725
|
+
messageHistory?: CanonicalMessage[];
|
|
726
|
+
/** Optional executor for tool calls. */
|
|
727
|
+
toolExecutor?: ToolExecutor;
|
|
728
|
+
/** Optional event bus for emitting agent events. */
|
|
729
|
+
eventBus?: AgentEventBus;
|
|
730
|
+
/** Maximum tool loop iterations (default 10). */
|
|
731
|
+
maxIterations?: number;
|
|
732
|
+
/** Optional trace ID for multi-agent orchestration. */
|
|
733
|
+
traceId?: string;
|
|
734
|
+
/** Optional parent span ID linking to orchestrator. */
|
|
735
|
+
parentSpanId?: string;
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Protocol for agent runners.
|
|
739
|
+
*
|
|
740
|
+
* Runners execute agents with optional tool execution and hooks.
|
|
741
|
+
* Two modes: run() for single response, stream() for streaming.
|
|
742
|
+
*/
|
|
743
|
+
interface RunnerProtocol {
|
|
744
|
+
/**
|
|
745
|
+
* Execute an agent and return the final result.
|
|
746
|
+
*/
|
|
747
|
+
run(agent: AgentLike, message: string, options?: RunOptions): Promise<RunResult>;
|
|
748
|
+
/**
|
|
749
|
+
* Execute an agent with streaming response.
|
|
750
|
+
* Optional — not all runners support streaming.
|
|
751
|
+
*/
|
|
752
|
+
stream?(agent: AgentLike, message: string, options?: RunOptions): AsyncGenerator<AgentEvent>;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* AgentRunner — The standard agentic execution loop on Vercel AI SDK.
|
|
757
|
+
*
|
|
758
|
+
* Ported from Python: systems/runners/agent.py
|
|
759
|
+
*
|
|
760
|
+
* Key differences from Python:
|
|
761
|
+
* - Parallel tool execution via Promise.all (Python is sequential)
|
|
762
|
+
* - Vercel AI SDK handles tool schema conversion (Python manually builds OpenAI JSON)
|
|
763
|
+
* - maxSteps: 1 forces one LLM call per iteration for gate interception control
|
|
764
|
+
* - MockLanguageModelV1 for testing (replaces Python's MockRunner)
|
|
765
|
+
*/
|
|
766
|
+
|
|
767
|
+
declare class ToolCallBlocked extends Error {
|
|
768
|
+
readonly toolName: string;
|
|
769
|
+
readonly reason: string;
|
|
770
|
+
constructor(toolName: string, reason: string);
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* The standard agentic execution loop.
|
|
774
|
+
*
|
|
775
|
+
* Executes agents using a tool loop pattern with the Vercel AI SDK.
|
|
776
|
+
*
|
|
777
|
+
* The runner implements an agentic tool loop:
|
|
778
|
+
* 1. Send message to LLM with system prompt and tools
|
|
779
|
+
* 2. If LLM returns tool_calls, execute them via toolExecutor (parallel)
|
|
780
|
+
* 3. Feed tool results back to LLM
|
|
781
|
+
* 4. Repeat until LLM returns final response or maxIterations reached
|
|
782
|
+
*/
|
|
783
|
+
declare class AgentRunner implements RunnerProtocol {
|
|
784
|
+
private _eventBus;
|
|
785
|
+
private readonly _model;
|
|
786
|
+
constructor(model: LanguageModelV1, eventBus?: AgentEventBus);
|
|
787
|
+
private get eventBus();
|
|
788
|
+
private emit;
|
|
789
|
+
/**
|
|
790
|
+
* Emit an intent event and check if it was blocked by a gate.
|
|
791
|
+
* Returns true if allowed, false if blocked.
|
|
792
|
+
*/
|
|
793
|
+
private emitIntent;
|
|
794
|
+
/**
|
|
795
|
+
* Convert agent tools to Vercel AI SDK tool format.
|
|
796
|
+
*/
|
|
797
|
+
private convertTools;
|
|
798
|
+
run(agent: AgentLike, message: string, options?: RunOptions): Promise<RunResult>;
|
|
799
|
+
stream(agent: AgentLike, message: string, options?: RunOptions): AsyncGenerator<AgentEvent>;
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* Message history conversion — canonical format to Vercel AI SDK CoreMessage[].
|
|
804
|
+
*
|
|
805
|
+
* Ported from Python: _convert_history_to_messages() in runners/agent.py
|
|
806
|
+
*/
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Convert canonical internal message format to Vercel AI SDK CoreMessage[].
|
|
810
|
+
*
|
|
811
|
+
* Canonical format (from orchestration layer):
|
|
812
|
+
* { kind: "request", parts: [{ type: "user_prompt", content: "..." }] }
|
|
813
|
+
* { kind: "response", parts: [
|
|
814
|
+
* { type: "text", content: "..." },
|
|
815
|
+
* { type: "tool_call", tool_name: "...", tool_call_id: "...", arguments: {} },
|
|
816
|
+
* { type: "tool_return", tool_name: "...", tool_call_id: "...", content: "..." },
|
|
817
|
+
* ]}
|
|
818
|
+
*
|
|
819
|
+
* Vercel AI SDK format:
|
|
820
|
+
* { role: "user", content: "..." }
|
|
821
|
+
* { role: "assistant", content: [{ type: "text", text: "..." }, { type: "tool-call", ... }] }
|
|
822
|
+
* { role: "tool", content: [{ type: "tool-result", ... }] }
|
|
823
|
+
*/
|
|
824
|
+
declare function convertHistory(history: CanonicalMessage[]): CoreMessage[];
|
|
825
|
+
|
|
826
|
+
declare function buildCapabilityServer(capability: Capability): {
|
|
827
|
+
serverName: string;
|
|
828
|
+
serverConfig: _anthropic_ai_claude_agent_sdk.McpSdkServerConfigWithInstance;
|
|
829
|
+
allowedTools: string[];
|
|
830
|
+
};
|
|
831
|
+
interface AgentLikeForBridge {
|
|
832
|
+
readonly role: {
|
|
833
|
+
readonly name: string;
|
|
834
|
+
readonly capabilities: ReadonlyArray<Capability>;
|
|
835
|
+
};
|
|
836
|
+
getModel(): string;
|
|
837
|
+
getTools(): ToolSchema[];
|
|
838
|
+
getSystemPrompt(): string;
|
|
839
|
+
renderInitialPrompt(): string;
|
|
840
|
+
}
|
|
841
|
+
declare function buildAgentServers(agent: AgentLikeForBridge): {
|
|
842
|
+
mcpServers: Record<string, unknown>;
|
|
843
|
+
allowedTools: string[];
|
|
844
|
+
};
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* ClaudeCodeRunner — Runner backed by the Claude Agent SDK.
|
|
848
|
+
*
|
|
849
|
+
* Mirrors Python: agentic_patterns/core/systems/runners/claude_code.py
|
|
850
|
+
*
|
|
851
|
+
* Wraps the Claude Agent SDK's query() function to execute agents through
|
|
852
|
+
* Claude Code's subprocess-based architecture. Claude Code manages its own
|
|
853
|
+
* tool loop, so toolExecutor is accepted for interface compatibility but
|
|
854
|
+
* not used.
|
|
855
|
+
*
|
|
856
|
+
* Event bridging:
|
|
857
|
+
* - PreToolUse hook → ToolCallIntent (gate chain) + ToolCallStartEvent
|
|
858
|
+
* - PostToolUse hook → ToolCallEndEvent with result
|
|
859
|
+
* - SDKAssistantMessage → MessageStart/Complete, Reasoning
|
|
860
|
+
* - SDKResultMessage → MessageComplete with usage stats
|
|
861
|
+
* - SDKPartialAssistantMessage → MessageChunk (streaming)
|
|
862
|
+
*/
|
|
863
|
+
|
|
864
|
+
interface ClaudeCodeRunnerOptions {
|
|
865
|
+
/** Default SDK options applied before per-run overrides. */
|
|
866
|
+
defaults?: Partial<Options>;
|
|
867
|
+
/** Optional event bus for emitting agent events. */
|
|
868
|
+
eventBus?: AgentEventBus;
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Runner that delegates execution to Claude Code via the Agent SDK.
|
|
872
|
+
*
|
|
873
|
+
* Claude Code manages its own tool loop, permissions, and file access.
|
|
874
|
+
* This runner translates SDK messages into the AgentEvent stream so that
|
|
875
|
+
* the rest of the framework (gates, exporters, UX) works transparently.
|
|
876
|
+
*
|
|
877
|
+
* Gate enforcement is handled via PreToolUse hooks — if a gate blocks a
|
|
878
|
+
* ToolCallIntent, the hook returns `permissionDecision: 'deny'` to the
|
|
879
|
+
* SDK so the tool is never executed.
|
|
880
|
+
*/
|
|
881
|
+
declare class ClaudeCodeRunner implements RunnerProtocol {
|
|
882
|
+
protected _eventBus: AgentEventBus | undefined;
|
|
883
|
+
protected readonly _defaults: Partial<Options>;
|
|
884
|
+
constructor(opts?: ClaudeCodeRunnerOptions);
|
|
885
|
+
protected get eventBus(): AgentEventBus;
|
|
886
|
+
protected emit(event: AgentEvent): Promise<void>;
|
|
887
|
+
/**
|
|
888
|
+
* Publish a ToolCallIntent through the gate chain.
|
|
889
|
+
* Returns true if the intent was allowed, false if blocked.
|
|
890
|
+
*/
|
|
891
|
+
protected emitIntent(intent: AgentEvent & {
|
|
892
|
+
type: "agent.tool.intent";
|
|
893
|
+
}): Promise<boolean>;
|
|
894
|
+
run(agent: AgentLikeForBridge, message: string, options?: RunOptions): Promise<RunResult>;
|
|
895
|
+
stream(agent: AgentLikeForBridge, message: string, options?: RunOptions): AsyncGenerator<AgentEvent>;
|
|
896
|
+
protected _buildOptions(agent: AgentLikeForBridge, options: RunOptions | undefined, context: {
|
|
897
|
+
runId: string;
|
|
898
|
+
traceId: string;
|
|
899
|
+
parentSpanId?: string;
|
|
900
|
+
includePartialMessages?: boolean;
|
|
901
|
+
}): Options;
|
|
902
|
+
/**
|
|
903
|
+
* Create SDK hook definitions that bridge to AgentEvent emissions.
|
|
904
|
+
*
|
|
905
|
+
* PreToolUse: emits ToolCallIntent through the gate chain. If gates
|
|
906
|
+
* block the intent, returns `permissionDecision: 'deny'` to the SDK
|
|
907
|
+
* so the tool is never executed. Otherwise emits ToolCallStartEvent.
|
|
908
|
+
*
|
|
909
|
+
* PostToolUse: emits ToolCallEndEvent with the tool result.
|
|
910
|
+
*/
|
|
911
|
+
private _makeHooks;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* ClaudeCodeAPIRunner — API-only mode wrapper on ClaudeCodeRunner.
|
|
916
|
+
*
|
|
917
|
+
* Uses Claude Code under the hood but blocks all Code-native tools
|
|
918
|
+
* (file, bash, agent, etc.) so the agent behaves like a plain Claude
|
|
919
|
+
* API call with a system prompt injected. MCP tools from agent
|
|
920
|
+
* capabilities remain available. Uses the same Max subscription OAuth token.
|
|
921
|
+
*
|
|
922
|
+
* Named "ClaudeCodeAPIRunner" (not "ClaudeAPIRunner") because it still
|
|
923
|
+
* runs through the Claude Code subprocess — a future ClaudeAPIRunner
|
|
924
|
+
* may talk directly to the Claude API without the Code layer.
|
|
925
|
+
*
|
|
926
|
+
* Mirrors Python: agentic_patterns/core/systems/runners/claude_api.py
|
|
927
|
+
*/
|
|
928
|
+
|
|
929
|
+
/**
|
|
930
|
+
* Runner that uses Claude Code SDK in API-only mode.
|
|
931
|
+
*
|
|
932
|
+
* Blocks all file/bash/agent tools so the agent behaves like a plain
|
|
933
|
+
* Claude API call with the framework's system prompt. MCP tools from
|
|
934
|
+
* agent capabilities remain available.
|
|
935
|
+
*/
|
|
936
|
+
declare class ClaudeCodeAPIRunner extends ClaudeCodeRunner {
|
|
937
|
+
protected _buildOptions(agent: AgentLikeForBridge, options: RunOptions | undefined, context: {
|
|
938
|
+
runId: string;
|
|
939
|
+
traceId: string;
|
|
940
|
+
parentSpanId?: string;
|
|
941
|
+
includePartialMessages?: boolean;
|
|
942
|
+
}): Options;
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* MockRunner — Deterministic runner for testing agents without LLM calls.
|
|
947
|
+
*
|
|
948
|
+
* Pattern-based response routing with tool call simulation and event emission.
|
|
949
|
+
* Implements RunnerProtocol for drop-in testing.
|
|
950
|
+
*/
|
|
951
|
+
|
|
952
|
+
/** A canned response for the mock runner. */
|
|
953
|
+
interface MockResponse {
|
|
954
|
+
content: string;
|
|
955
|
+
toolCalls?: Array<{
|
|
956
|
+
name: string;
|
|
957
|
+
arguments: Record<string, unknown>;
|
|
958
|
+
result?: unknown;
|
|
959
|
+
}>;
|
|
960
|
+
inputTokens?: number;
|
|
961
|
+
outputTokens?: number;
|
|
962
|
+
delayMs?: number;
|
|
963
|
+
error?: Error;
|
|
964
|
+
}
|
|
965
|
+
/** A recorded call to the mock runner. */
|
|
966
|
+
interface MockCall {
|
|
967
|
+
message: string;
|
|
968
|
+
agentName: string;
|
|
969
|
+
model: string;
|
|
970
|
+
timestamp: Date;
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
* Deterministic runner for testing agents without LLM calls.
|
|
974
|
+
*
|
|
975
|
+
* Supports substring-based trigger matching, wildcard defaults,
|
|
976
|
+
* tool call simulation, delay simulation, and full event lifecycle.
|
|
977
|
+
*
|
|
978
|
+
* Example:
|
|
979
|
+
* const runner = new MockRunner()
|
|
980
|
+
* .addResponse("hello", { content: "Hi there!" })
|
|
981
|
+
* .addResponse("*", { content: "Default response" });
|
|
982
|
+
*/
|
|
983
|
+
declare class MockRunner implements RunnerProtocol {
|
|
984
|
+
private _responses;
|
|
985
|
+
private _callHistory;
|
|
986
|
+
/** Read-only call history. */
|
|
987
|
+
get callHistory(): readonly MockCall[];
|
|
988
|
+
/**
|
|
989
|
+
* Add a canned response.
|
|
990
|
+
*
|
|
991
|
+
* @param trigger - Substring to match against the message, or "*" for wildcard default.
|
|
992
|
+
* @param response - The response to return when triggered.
|
|
993
|
+
* @returns this for fluent chaining.
|
|
994
|
+
*/
|
|
995
|
+
addResponse(trigger: string, response: MockResponse): this;
|
|
996
|
+
/**
|
|
997
|
+
* Clear all responses and call history.
|
|
998
|
+
*
|
|
999
|
+
* @returns this for fluent chaining.
|
|
1000
|
+
*/
|
|
1001
|
+
clear(): this;
|
|
1002
|
+
/**
|
|
1003
|
+
* Execute an agent and return a result (non-streaming).
|
|
1004
|
+
*/
|
|
1005
|
+
run(agent: AgentLike, message: string, options?: RunOptions): Promise<RunResult>;
|
|
1006
|
+
/**
|
|
1007
|
+
* Execute an agent with streaming event emission.
|
|
1008
|
+
*/
|
|
1009
|
+
stream(agent: AgentLike, message: string, options?: RunOptions): AsyncGenerator<AgentEvent>;
|
|
1010
|
+
/** Find matching response: substring first, then wildcard, then auto-fallback. */
|
|
1011
|
+
private _findResponse;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/**
|
|
1015
|
+
* ToolboxExecutor — adapts an agent's Capability toolboxes into the
|
|
1016
|
+
* ToolExecutor interface that AgentRunner needs to actually execute
|
|
1017
|
+
* tool calls.
|
|
1018
|
+
*
|
|
1019
|
+
* Without this, AgentRunner can FORMAT tool schemas for the LLM but
|
|
1020
|
+
* can't EXECUTE them — tool calls silently return
|
|
1021
|
+
* "No tool executor configured".
|
|
1022
|
+
*/
|
|
1023
|
+
|
|
1024
|
+
/** Minimal shape — matches what Agent.role.capabilities[].toolbox exposes. */
|
|
1025
|
+
interface ToolboxLike {
|
|
1026
|
+
readonly name: string;
|
|
1027
|
+
execute(name: string, args: unknown): Promise<unknown>;
|
|
1028
|
+
readonly tools: Record<string, {
|
|
1029
|
+
execute: (args: Record<string, unknown>) => Promise<unknown>;
|
|
1030
|
+
}>;
|
|
1031
|
+
}
|
|
1032
|
+
/** Minimal shape — matches what Agent.role.capabilities[] exposes. */
|
|
1033
|
+
interface CapabilityLike {
|
|
1034
|
+
readonly toolbox: ToolboxLike;
|
|
1035
|
+
}
|
|
1036
|
+
/** Minimal shape — matches what Agent.role exposes. */
|
|
1037
|
+
interface AgentWithCapabilities {
|
|
1038
|
+
readonly role: {
|
|
1039
|
+
readonly name: string;
|
|
1040
|
+
readonly capabilities?: readonly CapabilityLike[];
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Build a `ToolExecutor` from an agent's capability toolboxes.
|
|
1045
|
+
*
|
|
1046
|
+
* Iterates the agent's capabilities, indexes every tool by name, and
|
|
1047
|
+
* dispatches `execute(name, args)` to the owning toolbox. Handles the
|
|
1048
|
+
* `mcp__<toolbox>__<tool>` naming convention that MCP-bridged tools use.
|
|
1049
|
+
*/
|
|
1050
|
+
declare function createToolboxExecutor(agent: AgentWithCapabilities): ToolExecutor;
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Provider adapter protocol.
|
|
1054
|
+
*
|
|
1055
|
+
* A `ProviderProtocol` describes one LLM provider in three axes:
|
|
1056
|
+
* • which env vars indicate the provider is available
|
|
1057
|
+
* • a cross-provider tier map (opus / sonnet / haiku) giving default
|
|
1058
|
+
* model ids at each quality/cost rung
|
|
1059
|
+
* • a `load(modelId)` method that dynamically imports the provider
|
|
1060
|
+
* package and returns a Vercel AI SDK `LanguageModelV1`
|
|
1061
|
+
*
|
|
1062
|
+
* Adding a provider = dropping one file under `providers/`. No conditionals
|
|
1063
|
+
* to grow — `createRunner()` reads the registry in `providers/index.ts`.
|
|
1064
|
+
*/
|
|
1065
|
+
|
|
1066
|
+
/** Supported provider identifiers. Matches directory / file names below. */
|
|
1067
|
+
type SupportedProvider = "anthropic" | "openai" | "google" | "groq" | "mistral" | "xai" | "deepseek" | "openrouter" | "ollama";
|
|
1068
|
+
/**
|
|
1069
|
+
* Cross-provider tier selector.
|
|
1070
|
+
*
|
|
1071
|
+
* opus — most capable / expensive / slowest
|
|
1072
|
+
* sonnet — balanced default
|
|
1073
|
+
* haiku — fastest / cheapest / smallest
|
|
1074
|
+
*
|
|
1075
|
+
* Agents written against tiers stay portable across providers and hardware.
|
|
1076
|
+
*/
|
|
1077
|
+
type ProviderTier = "opus" | "sonnet" | "haiku";
|
|
1078
|
+
/** Per-provider adapter. One constant per provider file. */
|
|
1079
|
+
interface ProviderProtocol {
|
|
1080
|
+
readonly name: SupportedProvider;
|
|
1081
|
+
/** Default model id for each tier. */
|
|
1082
|
+
readonly tiers: Readonly<Record<ProviderTier, string>>;
|
|
1083
|
+
/**
|
|
1084
|
+
* Env variables whose presence indicates this provider is usable.
|
|
1085
|
+
* First-matched-first-wins during `createRunner()` auto-detection.
|
|
1086
|
+
*/
|
|
1087
|
+
readonly envVars: readonly string[];
|
|
1088
|
+
/**
|
|
1089
|
+
* Dynamically import the provider's `@ai-sdk/*` (or equivalent) package
|
|
1090
|
+
* and return a `LanguageModelV1` for the given model id. Throws a helpful
|
|
1091
|
+
* error if the package isn't installed.
|
|
1092
|
+
*/
|
|
1093
|
+
load(modelId: string): Promise<LanguageModelV1>;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
declare const anthropicProvider: ProviderProtocol;
|
|
1097
|
+
|
|
1098
|
+
declare const openaiProvider: ProviderProtocol;
|
|
1099
|
+
|
|
1100
|
+
declare const googleProvider: ProviderProtocol;
|
|
1101
|
+
|
|
1102
|
+
declare const groqProvider: ProviderProtocol;
|
|
1103
|
+
|
|
1104
|
+
declare const mistralProvider: ProviderProtocol;
|
|
1105
|
+
|
|
1106
|
+
declare const xaiProvider: ProviderProtocol;
|
|
1107
|
+
|
|
1108
|
+
declare const deepseekProvider: ProviderProtocol;
|
|
1109
|
+
|
|
1110
|
+
/**
|
|
1111
|
+
* OpenRouter gateways 150+ models across every major provider. Our tier
|
|
1112
|
+
* defaults route to Claude (repo's center of gravity); callers who want
|
|
1113
|
+
* a non-Claude default pass `modelId` explicitly (e.g. "meta-llama/llama-3.3-70b").
|
|
1114
|
+
*/
|
|
1115
|
+
declare const openrouterProvider: ProviderProtocol;
|
|
1116
|
+
|
|
1117
|
+
/**
|
|
1118
|
+
* Ollama — local-only OSS models via HTTP.
|
|
1119
|
+
*
|
|
1120
|
+
* Default tier map uses the Qwen3 family because Qwen's team explicitly
|
|
1121
|
+
* prioritizes tool-calling and keeps the same grammar across sizes — so
|
|
1122
|
+
* agents scale between haiku↔sonnet↔opus without prompt changes.
|
|
1123
|
+
*
|
|
1124
|
+
* Sized for 16GB-class consumer GPUs (tested on 4080 Super):
|
|
1125
|
+
* opus (30B MoE, activates 3B/token) — ~14 GB VRAM, 50–80 tok/s
|
|
1126
|
+
* sonnet (14B dense) — ~9 GB VRAM, 30–50 tok/s
|
|
1127
|
+
* haiku (4B dense) — ~3 GB VRAM, 100+ tok/s
|
|
1128
|
+
*
|
|
1129
|
+
* Override with `options.modelId` if you want a different family.
|
|
1130
|
+
*/
|
|
1131
|
+
declare const ollamaProvider: ProviderProtocol;
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* Claude Code LanguageModelV1 provider.
|
|
1135
|
+
*
|
|
1136
|
+
* Wraps the Claude Agent SDK's `query()` function in a Vercel AI SDK
|
|
1137
|
+
* `LanguageModelV1` so agents can be executed through `AgentRunner` using
|
|
1138
|
+
* a Claude Max subscription (OAuth cached in ~/.claude) or an
|
|
1139
|
+
* `ANTHROPIC_API_KEY` env var picked up by the SDK itself.
|
|
1140
|
+
*
|
|
1141
|
+
* Unlike `ClaudeCodeRunner` / `ClaudeCodeAPIRunner`, this provider plugs
|
|
1142
|
+
* into the *standard* AgentRunner execution loop. That means the full
|
|
1143
|
+
* canonical event vocabulary (`iteration.start`, `llm.start`, `tool.*`,
|
|
1144
|
+
* `iteration.end`, `llm.end`, …) fires automatically — closing the
|
|
1145
|
+
* observability gap those runners have.
|
|
1146
|
+
*
|
|
1147
|
+
* Each `doGenerate` / `doStream` call runs a fresh single-turn SDK query:
|
|
1148
|
+
*
|
|
1149
|
+
* 1. System prompt + conversation history (including prior tool
|
|
1150
|
+
* use / tool result parts) is flattened to a string prompt.
|
|
1151
|
+
* 2. Tool schemas are registered as MCP tools on an in-process server.
|
|
1152
|
+
* 3. `canUseTool` intercepts tool invocations, records them, and denies
|
|
1153
|
+
* with `interrupt: true` so the SDK stops immediately. The recorded
|
|
1154
|
+
* tool calls are surfaced in the LanguageModelV1 response as
|
|
1155
|
+
* `toolCalls`.
|
|
1156
|
+
* 4. SDK assistant / result messages are translated back to
|
|
1157
|
+
* LanguageModelV1 output shape (`text`, `toolCalls`, `finishReason`,
|
|
1158
|
+
* `usage`).
|
|
1159
|
+
* 5. Claude-Code-native tools (Read/Write/Edit/Bash/…) are disallowed so
|
|
1160
|
+
* only framework tools flow.
|
|
1161
|
+
*/
|
|
1162
|
+
|
|
1163
|
+
interface ClaudeCodeProviderOptions {
|
|
1164
|
+
/** Defaults merged with every SDK query call. */
|
|
1165
|
+
defaults?: Partial<Options>;
|
|
1166
|
+
/** Include Claude Code's built-in tools (Read/Write/Bash/…). Default: false. */
|
|
1167
|
+
allowBuiltinTools?: boolean;
|
|
1168
|
+
/** Max turns inside the SDK loop. Default: 1 (one Claude call per model step). */
|
|
1169
|
+
maxTurns?: number;
|
|
1170
|
+
}
|
|
1171
|
+
declare class ClaudeCodeLanguageModel implements LanguageModelV1 {
|
|
1172
|
+
readonly specificationVersion: "v1";
|
|
1173
|
+
readonly provider = "claude-code";
|
|
1174
|
+
readonly modelId: string;
|
|
1175
|
+
readonly defaultObjectGenerationMode: "tool";
|
|
1176
|
+
private readonly _opts;
|
|
1177
|
+
constructor(modelId: string, opts?: ClaudeCodeProviderOptions);
|
|
1178
|
+
doGenerate(options: LanguageModelV1CallOptions): ReturnType<LanguageModelV1["doGenerate"]>;
|
|
1179
|
+
private _doGenerate;
|
|
1180
|
+
doStream(options: LanguageModelV1CallOptions): ReturnType<LanguageModelV1["doStream"]>;
|
|
1181
|
+
private _doStream;
|
|
1182
|
+
private _prepare;
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Create a `LanguageModelV1` backed by the Claude Agent SDK.
|
|
1186
|
+
*
|
|
1187
|
+
* @example
|
|
1188
|
+
* ```ts
|
|
1189
|
+
* import { claudeCode } from "@agentic-patterns/runtime/providers";
|
|
1190
|
+
* import { AgentRunner } from "@agentic-patterns/runtime";
|
|
1191
|
+
*
|
|
1192
|
+
* const runner = new AgentRunner(claudeCode("sonnet"));
|
|
1193
|
+
* const result = await runner.run(agent, "What is 17 + 28?");
|
|
1194
|
+
* ```
|
|
1195
|
+
*/
|
|
1196
|
+
declare function claudeCode(modelId: string, opts?: ClaudeCodeProviderOptions): ClaudeCodeLanguageModel;
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* Provider adapter registry.
|
|
1200
|
+
*
|
|
1201
|
+
* Each provider exports a `ProviderProtocol` constant that knows its env
|
|
1202
|
+
* vars, tier map, and how to dynamically load the `@ai-sdk/*` (or
|
|
1203
|
+
* equivalent) package. The registry below is consumed by `createRunner()`
|
|
1204
|
+
* for provider auto-detection and tier resolution.
|
|
1205
|
+
*
|
|
1206
|
+
* Registry order matters for env-based auto-detection: the first provider
|
|
1207
|
+
* with a matching env var wins. We lead with Anthropic (repo's center of
|
|
1208
|
+
* gravity: the Claude Agent SDK is a peer dep). Callers who want a
|
|
1209
|
+
* different order pass `options.provider` explicitly.
|
|
1210
|
+
*/
|
|
1211
|
+
|
|
1212
|
+
/** All supported providers keyed by name. */
|
|
1213
|
+
declare const PROVIDERS: Readonly<Record<SupportedProvider, ProviderProtocol>>;
|
|
1214
|
+
/**
|
|
1215
|
+
* Env-detection priority. First entry whose `envVars` include a set env
|
|
1216
|
+
* variable wins. Order reflects repo defaults — Anthropic first, OSS local
|
|
1217
|
+
* (Ollama) last so remote providers are preferred when both exist.
|
|
1218
|
+
*/
|
|
1219
|
+
declare const PROVIDER_PRIORITY: readonly SupportedProvider[];
|
|
1220
|
+
/** Resolve a model id for a (provider, tier?, explicitModelId?) triple. */
|
|
1221
|
+
declare function resolveModelId(provider: ProviderProtocol, explicitModelId?: string, tier?: ProviderTier): string;
|
|
1222
|
+
|
|
1223
|
+
/**
|
|
1224
|
+
* `createRunner()` — zero-config runner factory.
|
|
1225
|
+
*
|
|
1226
|
+
* Selection priority (first match wins):
|
|
1227
|
+
* 1. options.runner → use it verbatim
|
|
1228
|
+
* 2. options.model (LanguageModelV1) → new AgentRunner(model)
|
|
1229
|
+
* 3. options.provider + tier/modelId → new AgentRunner(provider.load(...))
|
|
1230
|
+
* 4. env vars (in PROVIDER_PRIORITY order) → new AgentRunner(...)
|
|
1231
|
+
* 5. claude CLI on PATH → new ClaudeCodeAPIRunner() (fallback, limited events)
|
|
1232
|
+
* 6. options.fallbackToMock === true → new MockRunner()
|
|
1233
|
+
* 7. throw
|
|
1234
|
+
*
|
|
1235
|
+
* See docs/runners.md (§4) for the design doc.
|
|
1236
|
+
*/
|
|
1237
|
+
|
|
1238
|
+
interface CreateRunnerOptions {
|
|
1239
|
+
/**
|
|
1240
|
+
* Explicit runner instance. Wins over everything else — useful for
|
|
1241
|
+
* tests (`runner: new MockRunner()`) or bespoke setups.
|
|
1242
|
+
*/
|
|
1243
|
+
runner?: RunnerProtocol;
|
|
1244
|
+
/**
|
|
1245
|
+
* Explicit provider. Overrides env-based detection. Requires the
|
|
1246
|
+
* corresponding `@ai-sdk/*` package to be installed.
|
|
1247
|
+
*/
|
|
1248
|
+
provider?: SupportedProvider;
|
|
1249
|
+
/**
|
|
1250
|
+
* Explicit model id. Falls through to the provider's tier default.
|
|
1251
|
+
* Ignored if `runner` or `model` is set.
|
|
1252
|
+
*/
|
|
1253
|
+
modelId?: string;
|
|
1254
|
+
/**
|
|
1255
|
+
* Cross-provider tier selector — "opus" | "sonnet" | "haiku". Resolved
|
|
1256
|
+
* via each `ProviderProtocol.tiers` map. Default: "sonnet".
|
|
1257
|
+
* Ignored if `modelId` is set.
|
|
1258
|
+
*/
|
|
1259
|
+
tier?: ProviderTier;
|
|
1260
|
+
/**
|
|
1261
|
+
* Pre-constructed `LanguageModelV1`. Short-circuits provider resolution;
|
|
1262
|
+
* the factory wraps it in `AgentRunner`.
|
|
1263
|
+
*/
|
|
1264
|
+
model?: LanguageModelV1;
|
|
1265
|
+
/** Optional event bus. Passed through to the constructed runner. */
|
|
1266
|
+
eventBus?: AgentEventBus;
|
|
1267
|
+
/** Log the selection decision to console. Defaults to true. */
|
|
1268
|
+
verbose?: boolean;
|
|
1269
|
+
/**
|
|
1270
|
+
* If no runnable configuration is found, fall back to `MockRunner`
|
|
1271
|
+
* instead of throwing. Defaults to false.
|
|
1272
|
+
*/
|
|
1273
|
+
fallbackToMock?: boolean;
|
|
1274
|
+
}
|
|
1275
|
+
type RunnerSource = "explicit-runner" | "explicit-model" | "explicit-provider" | `env-${SupportedProvider}` | "claude-cli" | "mock-fallback";
|
|
1276
|
+
interface RunnerSelection {
|
|
1277
|
+
runner: RunnerProtocol;
|
|
1278
|
+
/** Human-readable explanation, e.g. `"using anthropic (env ANTHROPIC_API_KEY)"`. */
|
|
1279
|
+
reason: string;
|
|
1280
|
+
/** Which branch of the priority tree fired. */
|
|
1281
|
+
source: RunnerSource;
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Construct a runner from explicit opts / env vars / Claude CLI presence.
|
|
1285
|
+
* Returns the runner plus metadata about why it was chosen.
|
|
1286
|
+
*/
|
|
1287
|
+
declare function createRunner(opts?: CreateRunnerOptions): Promise<RunnerSelection>;
|
|
1288
|
+
|
|
1289
|
+
/**
|
|
1290
|
+
* In-process transport with NATS-compatible subject wildcards.
|
|
1291
|
+
*
|
|
1292
|
+
* Zero-dependency in-memory pub/sub for multi-agent communication.
|
|
1293
|
+
* Supports NATS wildcard patterns: `*` (single token) and `>` (trailing tokens).
|
|
1294
|
+
*/
|
|
1295
|
+
|
|
1296
|
+
/**
|
|
1297
|
+
* Convert a NATS subject pattern to a RegExp.
|
|
1298
|
+
*
|
|
1299
|
+
* NATS wildcards:
|
|
1300
|
+
* `*` matches exactly one token (segment between dots)
|
|
1301
|
+
* `>` matches one or more trailing tokens (must be the last segment)
|
|
1302
|
+
*/
|
|
1303
|
+
declare function subjectToRegex(pattern: string): RegExp;
|
|
1304
|
+
/**
|
|
1305
|
+
* Test whether a subject matches a NATS-style pattern.
|
|
1306
|
+
*/
|
|
1307
|
+
declare function matchSubject(pattern: string, subject: string): boolean;
|
|
1308
|
+
/**
|
|
1309
|
+
* Zero-dependency in-process transport with NATS-compatible wildcards.
|
|
1310
|
+
*
|
|
1311
|
+
* All messaging is synchronous within the process -- no network I/O.
|
|
1312
|
+
* `connect()` and `ensureStream()` are no-ops.
|
|
1313
|
+
*/
|
|
1314
|
+
declare class InProcessTransport implements Transport {
|
|
1315
|
+
private _subscriptions;
|
|
1316
|
+
private _connected;
|
|
1317
|
+
connect(): Promise<void>;
|
|
1318
|
+
close(): Promise<void>;
|
|
1319
|
+
ensureStream(_name: string, _subjects: string[]): Promise<void>;
|
|
1320
|
+
publish(subject: string, data: Uint8Array): Promise<void>;
|
|
1321
|
+
subscribe(subject: string, callback: (msg: TransportMessage) => void | Promise<void>, _durable?: string): Promise<void>;
|
|
1322
|
+
request(subject: string, data: Uint8Array, _timeout?: number): Promise<Uint8Array>;
|
|
1323
|
+
/** Whether the transport is currently connected. */
|
|
1324
|
+
get connected(): boolean;
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
/**
|
|
1328
|
+
* MessagingToolbox - inter-agent communication tools over shared transport.
|
|
1329
|
+
*
|
|
1330
|
+
* Provides send_message, broadcast, and list_team tools that publish
|
|
1331
|
+
* SandboxEvents to the bus, enabling fully event-driven agent conversations.
|
|
1332
|
+
*/
|
|
1333
|
+
|
|
1334
|
+
/**
|
|
1335
|
+
* Tools for inter-agent communication within an agency.
|
|
1336
|
+
*
|
|
1337
|
+
* Each tool publishes a SandboxEvent to the bus, which then dispatches
|
|
1338
|
+
* both locally and over transport.
|
|
1339
|
+
*/
|
|
1340
|
+
declare class MessagingToolbox extends Toolbox {
|
|
1341
|
+
readonly name = "Messaging";
|
|
1342
|
+
readonly description = "Tools for sending messages to other agents on the team.";
|
|
1343
|
+
private readonly _bus;
|
|
1344
|
+
private readonly _address;
|
|
1345
|
+
private readonly _agencyId;
|
|
1346
|
+
private readonly _runId;
|
|
1347
|
+
private readonly _roster;
|
|
1348
|
+
readonly tools: Record<string, ToolDefinition>;
|
|
1349
|
+
constructor(bus: SandboxEventBus, address: AgentAddress, agencyId: string, runId: string, roster: Record<string, AgentAddress>);
|
|
1350
|
+
private _sendMessage;
|
|
1351
|
+
private _broadcast;
|
|
1352
|
+
private _listTeam;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/**
|
|
1356
|
+
* SSE (Server-Sent Events) formatter for agent events.
|
|
1357
|
+
*
|
|
1358
|
+
* Converts internal AgentEvent types to SSE-formatted strings for streaming
|
|
1359
|
+
* to clients over HTTP. Maps all 20 canonical events via a single typed
|
|
1360
|
+
* discriminated-union switch (`toSSEMapping`) so event name, payload, and
|
|
1361
|
+
* exhaustiveness live in one place.
|
|
1362
|
+
*/
|
|
1363
|
+
|
|
1364
|
+
/**
|
|
1365
|
+
* Client-facing SSE event name. Matches the 20 canonical events defined in
|
|
1366
|
+
* the admin-observability spec. Used anywhere an SSE frame is produced so
|
|
1367
|
+
* the compiler catches typos like `"thinking.complete"` vs `"thinking"`.
|
|
1368
|
+
*/
|
|
1369
|
+
type SSEEventName = "conversation.start" | "conversation.end" | "message.start" | "message.delta" | "message.complete" | "message.cancel" | "thinking.start" | "thinking" | "thinking.complete" | "tool.intent" | "tool.start" | "tool.progress" | "tool.end" | "tool.rejected" | "iteration.start" | "iteration.end" | "llm.start" | "llm.end" | "error" | "claude_code.hook" | "done";
|
|
1370
|
+
/** Result of mapping an AgentEvent to its canonical SSE shape. */
|
|
1371
|
+
interface SSEMapping {
|
|
1372
|
+
readonly name: SSEEventName;
|
|
1373
|
+
readonly payload: Record<string, unknown>;
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* Map an `AgentEvent` to its canonical SSE wire name and payload. The
|
|
1377
|
+
* discriminated-union switch narrows `event` automatically so field access
|
|
1378
|
+
* is fully typed without casts. The `never` default is a compile-time
|
|
1379
|
+
* exhaustiveness check — adding a new variant to `AgentEvent` fails
|
|
1380
|
+
* typechecking here until a branch is added.
|
|
1381
|
+
*
|
|
1382
|
+
* Returns `null` only when a non-AgentEvent slips through at runtime
|
|
1383
|
+
* (e.g., a hand-constructed event with an unrecognised `type`).
|
|
1384
|
+
*/
|
|
1385
|
+
declare function toSSEMapping(event: AgentEvent): SSEMapping | null;
|
|
1386
|
+
/**
|
|
1387
|
+
* Map from internal `AgentEvent.type` to canonical SSE wire name. Useful
|
|
1388
|
+
* when a consumer only needs the name (routing, logging) and not the
|
|
1389
|
+
* payload. For `agent.reasoning` the default entry is `"thinking"`; the
|
|
1390
|
+
* `isComplete=true` variant produces `"thinking.complete"` via
|
|
1391
|
+
* `toSSEMapping` — consumers that care should use that directly.
|
|
1392
|
+
*/
|
|
1393
|
+
declare const SSE_EVENT_NAMES: Readonly<Record<AgentEventType, SSEEventName>>;
|
|
1394
|
+
/**
|
|
1395
|
+
* Formats `AgentEvent`s as SSE frames with canonical event names.
|
|
1396
|
+
*
|
|
1397
|
+
* Delegates all mapping to `toSSEMapping`; this class exists to carry the
|
|
1398
|
+
* trace-context enrichment (traceId + timestamp) onto the payload so the
|
|
1399
|
+
* runtime's admin SSE broadcast stays self-describing.
|
|
1400
|
+
*/
|
|
1401
|
+
declare class SSEFormatter {
|
|
1402
|
+
/** Format an AgentEvent as an SSE frame string, or `null` if unmappable. */
|
|
1403
|
+
format(event: AgentEvent): string | null;
|
|
1404
|
+
/**
|
|
1405
|
+
* Extract the payload from an event using canonical snake_case field
|
|
1406
|
+
* names. Static so StdioAdapter and other consumers can reuse it without
|
|
1407
|
+
* instantiating a formatter. Returns `null` if the event has no mapping.
|
|
1408
|
+
*/
|
|
1409
|
+
static extractPayload(event: AgentEvent): Record<string, unknown> | null;
|
|
1410
|
+
/** Format a stream-terminator "done" event. */
|
|
1411
|
+
static formatDone(): string;
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Format an AgentEvent as an SSE frame string.
|
|
1415
|
+
*
|
|
1416
|
+
* @deprecated Use `new SSEFormatter().format(event)` instead.
|
|
1417
|
+
*/
|
|
1418
|
+
declare function formatSSE(event: AgentEvent): string | null;
|
|
1419
|
+
|
|
1420
|
+
/**
|
|
1421
|
+
* AgentNode - event-driven agent wrapper for multi-agent systems.
|
|
1422
|
+
*
|
|
1423
|
+
* Wraps an Agent with a message queue and worker loop that listens to
|
|
1424
|
+
* SandboxEventBus events, batches incoming messages, and runs them through
|
|
1425
|
+
* a runner (LLM or mock).
|
|
1426
|
+
*
|
|
1427
|
+
* Architecture: Bus -> Queue -> Worker -> Runner -> Tools -> Bus
|
|
1428
|
+
*/
|
|
1429
|
+
|
|
1430
|
+
declare const DEFAULT_IDLE_TIMEOUT = 10000;
|
|
1431
|
+
declare const DEFAULT_GLOBAL_TIMEOUT = 120000;
|
|
1432
|
+
declare const DEFAULT_MAX_TURNS = 20;
|
|
1433
|
+
declare const BATCH_WINDOW = 100;
|
|
1434
|
+
interface AgentNodeOptions {
|
|
1435
|
+
readonly name: string;
|
|
1436
|
+
readonly agent: Agent;
|
|
1437
|
+
readonly bus: SandboxEventBus;
|
|
1438
|
+
readonly address: AgentAddress;
|
|
1439
|
+
readonly toolbox: MessagingToolbox;
|
|
1440
|
+
readonly runner: RunnerProtocol;
|
|
1441
|
+
readonly traceId?: string;
|
|
1442
|
+
readonly maxTurns?: number;
|
|
1443
|
+
readonly idleTimeout?: number;
|
|
1444
|
+
readonly globalTimeout?: number;
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Event-driven agent wrapper. Bus -> Queue -> Worker -> Runner -> Bus.
|
|
1448
|
+
*
|
|
1449
|
+
* Each node owns its own SandboxEventBus (wired to a shared transport)
|
|
1450
|
+
* and listens for messages addressed to its AgentAddress.
|
|
1451
|
+
*
|
|
1452
|
+
* Lifecycle events emitted on the bus:
|
|
1453
|
+
* - node.started: when the node begins listening
|
|
1454
|
+
* - node.stopped: when the worker exits
|
|
1455
|
+
* - node.message_received: when messages are dequeued for processing
|
|
1456
|
+
* - node.response_sent: after the runner produces a response
|
|
1457
|
+
*/
|
|
1458
|
+
declare class AgentNode {
|
|
1459
|
+
readonly name: string;
|
|
1460
|
+
readonly agent: Agent;
|
|
1461
|
+
readonly address: AgentAddress;
|
|
1462
|
+
private readonly _bus;
|
|
1463
|
+
private readonly _toolbox;
|
|
1464
|
+
private readonly _runner;
|
|
1465
|
+
private readonly _traceId;
|
|
1466
|
+
private readonly _maxTurns;
|
|
1467
|
+
private readonly _idleTimeout;
|
|
1468
|
+
private readonly _globalTimeout;
|
|
1469
|
+
private _queue;
|
|
1470
|
+
private _queueResolve?;
|
|
1471
|
+
private _conversation;
|
|
1472
|
+
private _turnsTaken;
|
|
1473
|
+
private _workerPromise;
|
|
1474
|
+
private _stopped;
|
|
1475
|
+
readonly transcript: string[];
|
|
1476
|
+
constructor(options: AgentNodeOptions);
|
|
1477
|
+
/**
|
|
1478
|
+
* Subscribe to bus events and start the worker loop.
|
|
1479
|
+
*/
|
|
1480
|
+
start(): Promise<void>;
|
|
1481
|
+
/**
|
|
1482
|
+
* Stop the worker loop.
|
|
1483
|
+
*/
|
|
1484
|
+
stop(): Promise<void>;
|
|
1485
|
+
/**
|
|
1486
|
+
* Seed a message into the queue from the orchestrator.
|
|
1487
|
+
*/
|
|
1488
|
+
inject(content: string): Promise<void>;
|
|
1489
|
+
/** Number of turns the worker has completed. */
|
|
1490
|
+
get turnsTaken(): number;
|
|
1491
|
+
/** Whether the worker is done (stopped or completed). */
|
|
1492
|
+
get isDone(): boolean;
|
|
1493
|
+
private _shouldHandle;
|
|
1494
|
+
private _onMessage;
|
|
1495
|
+
private _onBroadcast;
|
|
1496
|
+
private _enqueue;
|
|
1497
|
+
private _waitForMessage;
|
|
1498
|
+
private _drainQueue;
|
|
1499
|
+
private _worker;
|
|
1500
|
+
private _formatIncoming;
|
|
1501
|
+
private _emitLifecycle;
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
/**
|
|
1505
|
+
* AgencyRuntime - takes an Agency atom and produces a running system of AgentNode instances.
|
|
1506
|
+
*
|
|
1507
|
+
* Bridges the declarative Agency definition (atoms layer) to the runtime systems layer
|
|
1508
|
+
* by creating transport, building agents with roles/capabilities, and wiring up
|
|
1509
|
+
* event-driven communication between nodes.
|
|
1510
|
+
*
|
|
1511
|
+
* Architecture:
|
|
1512
|
+
* Agency (atom) -> AgencyRuntime -> [AgentNode, AgentNode, ...] on shared transport
|
|
1513
|
+
*/
|
|
1514
|
+
|
|
1515
|
+
/**
|
|
1516
|
+
* Takes an Agency atom and creates an AgentNode swarm with transport wiring.
|
|
1517
|
+
*
|
|
1518
|
+
* Lifecycle:
|
|
1519
|
+
* const runtime = new AgencyRuntime(agency, runner);
|
|
1520
|
+
* await runtime.start(); // creates transport, builds nodes, starts all
|
|
1521
|
+
* await runtime.injectCoordinator("Go!");
|
|
1522
|
+
* ...
|
|
1523
|
+
* await runtime.stop(); // stops all nodes and transport
|
|
1524
|
+
*/
|
|
1525
|
+
declare class AgencyRuntime {
|
|
1526
|
+
private readonly _agency;
|
|
1527
|
+
private readonly _runner;
|
|
1528
|
+
private readonly _runId;
|
|
1529
|
+
private _transport;
|
|
1530
|
+
private _nodes;
|
|
1531
|
+
private _buses;
|
|
1532
|
+
private _addresses;
|
|
1533
|
+
private _started;
|
|
1534
|
+
constructor(agency: Agency, runner: RunnerProtocol, runId?: string);
|
|
1535
|
+
/**
|
|
1536
|
+
* Create transport, build nodes, start all.
|
|
1537
|
+
*/
|
|
1538
|
+
start(): Promise<void>;
|
|
1539
|
+
/**
|
|
1540
|
+
* Stop all nodes and transport.
|
|
1541
|
+
*/
|
|
1542
|
+
stop(): Promise<void>;
|
|
1543
|
+
/**
|
|
1544
|
+
* Inject a message to a specific agent by role.
|
|
1545
|
+
*/
|
|
1546
|
+
inject(role: string, content: string): Promise<void>;
|
|
1547
|
+
/**
|
|
1548
|
+
* Inject a message to the coordinator agent.
|
|
1549
|
+
*/
|
|
1550
|
+
injectCoordinator(content: string): Promise<void>;
|
|
1551
|
+
/**
|
|
1552
|
+
* Get the coordinator's address.
|
|
1553
|
+
*/
|
|
1554
|
+
get coordinatorAddress(): AgentAddress | undefined;
|
|
1555
|
+
/**
|
|
1556
|
+
* Return role -> state mapping for all nodes.
|
|
1557
|
+
*/
|
|
1558
|
+
status(): Record<string, "running" | "stopped">;
|
|
1559
|
+
/**
|
|
1560
|
+
* Access the underlying nodes (read-only view).
|
|
1561
|
+
*/
|
|
1562
|
+
get nodes(): Record<string, AgentNode>;
|
|
1563
|
+
/**
|
|
1564
|
+
* The run ID for this runtime instance.
|
|
1565
|
+
*/
|
|
1566
|
+
get runId(): string;
|
|
1567
|
+
/**
|
|
1568
|
+
* Build a single AgentNode from an AgentSpec.
|
|
1569
|
+
*/
|
|
1570
|
+
private _buildNode;
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
/**
|
|
1574
|
+
* ConversationStoreProtocol — structured persistence for conversations.
|
|
1575
|
+
*
|
|
1576
|
+
* Ported from Python: systems/stores/base.py
|
|
1577
|
+
*/
|
|
1578
|
+
/** A stored conversation record. */
|
|
1579
|
+
interface StoredConversation {
|
|
1580
|
+
readonly id: string;
|
|
1581
|
+
readonly agentName: string;
|
|
1582
|
+
readonly model: string;
|
|
1583
|
+
readonly createdAt: Date;
|
|
1584
|
+
readonly updatedAt: Date;
|
|
1585
|
+
readonly metadata: Record<string, unknown>;
|
|
1586
|
+
}
|
|
1587
|
+
/** A stored message within a conversation. */
|
|
1588
|
+
interface StoredMessage {
|
|
1589
|
+
readonly id: string;
|
|
1590
|
+
readonly conversationId: string;
|
|
1591
|
+
readonly kind: "request" | "response";
|
|
1592
|
+
readonly runId?: string;
|
|
1593
|
+
readonly inputTokens: number;
|
|
1594
|
+
readonly outputTokens: number;
|
|
1595
|
+
readonly createdAt: Date;
|
|
1596
|
+
readonly parts: StoredMessagePart[];
|
|
1597
|
+
}
|
|
1598
|
+
/** A part of a stored message. */
|
|
1599
|
+
interface StoredMessagePart {
|
|
1600
|
+
readonly id: string;
|
|
1601
|
+
readonly messageId: string;
|
|
1602
|
+
readonly type: string;
|
|
1603
|
+
readonly content?: string;
|
|
1604
|
+
readonly metadata: Record<string, unknown>;
|
|
1605
|
+
}
|
|
1606
|
+
/** Structured conversation persistence protocol. */
|
|
1607
|
+
interface ConversationStoreProtocol {
|
|
1608
|
+
createConversation(agentName: string, model: string): Promise<StoredConversation>;
|
|
1609
|
+
getConversation(conversationId: string): Promise<StoredConversation | null>;
|
|
1610
|
+
updateConversation(conversationId: string, updates: Record<string, unknown>): Promise<StoredConversation>;
|
|
1611
|
+
addMessage(conversationId: string, kind: "request" | "response", parts: Array<{
|
|
1612
|
+
type: string;
|
|
1613
|
+
content?: string;
|
|
1614
|
+
metadata?: Record<string, unknown>;
|
|
1615
|
+
}>, options?: {
|
|
1616
|
+
runId?: string;
|
|
1617
|
+
inputTokens?: number;
|
|
1618
|
+
outputTokens?: number;
|
|
1619
|
+
}): Promise<StoredMessage>;
|
|
1620
|
+
getMessages(conversationId: string, limit?: number): Promise<StoredMessage[]>;
|
|
1621
|
+
getMessageParts(messageId: string): Promise<StoredMessagePart[]>;
|
|
1622
|
+
}
|
|
1623
|
+
/** In-memory implementation of ConversationStoreProtocol. */
|
|
1624
|
+
declare class MemoryStore implements ConversationStoreProtocol {
|
|
1625
|
+
private _conversations;
|
|
1626
|
+
private _messages;
|
|
1627
|
+
private _parts;
|
|
1628
|
+
createConversation(agentName: string, model: string): Promise<StoredConversation>;
|
|
1629
|
+
getConversation(conversationId: string): Promise<StoredConversation | null>;
|
|
1630
|
+
updateConversation(conversationId: string, updates: Record<string, unknown>): Promise<StoredConversation>;
|
|
1631
|
+
addMessage(conversationId: string, kind: "request" | "response", parts: Array<{
|
|
1632
|
+
type: string;
|
|
1633
|
+
content?: string;
|
|
1634
|
+
metadata?: Record<string, unknown>;
|
|
1635
|
+
}>, options?: {
|
|
1636
|
+
runId?: string;
|
|
1637
|
+
inputTokens?: number;
|
|
1638
|
+
outputTokens?: number;
|
|
1639
|
+
}): Promise<StoredMessage>;
|
|
1640
|
+
getMessages(conversationId: string, limit?: number): Promise<StoredMessage[]>;
|
|
1641
|
+
getMessageParts(messageId: string): Promise<StoredMessagePart[]>;
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/**
|
|
1645
|
+
* Conversation runtime - stateful multi-turn conversation management.
|
|
1646
|
+
*
|
|
1647
|
+
* Ported from Python: systems/conversation.py
|
|
1648
|
+
*/
|
|
1649
|
+
|
|
1650
|
+
/** A single tool call record within an exchange. */
|
|
1651
|
+
interface ToolCallRecord {
|
|
1652
|
+
readonly name: string;
|
|
1653
|
+
readonly id?: string;
|
|
1654
|
+
readonly arguments?: Record<string, unknown>;
|
|
1655
|
+
}
|
|
1656
|
+
/** A complete user->assistant exchange in a conversation. */
|
|
1657
|
+
interface Exchange {
|
|
1658
|
+
readonly number: number;
|
|
1659
|
+
readonly invocationId: string;
|
|
1660
|
+
readonly user: string;
|
|
1661
|
+
readonly assistant: string;
|
|
1662
|
+
readonly toolCalls: ToolCallRecord[];
|
|
1663
|
+
readonly inputTokens: number;
|
|
1664
|
+
readonly outputTokens: number;
|
|
1665
|
+
readonly timestamp: Date;
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Total tokens for an exchange.
|
|
1669
|
+
*/
|
|
1670
|
+
declare function exchangeTotalTokens(exchange: Exchange): number;
|
|
1671
|
+
/**
|
|
1672
|
+
* A live conversation that can be continued.
|
|
1673
|
+
*
|
|
1674
|
+
* Core runtime abstraction for multi-turn conversations.
|
|
1675
|
+
* Tracks state, history, and manages execution.
|
|
1676
|
+
*
|
|
1677
|
+
* Example:
|
|
1678
|
+
* const conversation = new Conversation(agent, runner);
|
|
1679
|
+
* const exchange = await conversation.send("Hello!");
|
|
1680
|
+
* console.log(exchange.assistant);
|
|
1681
|
+
*/
|
|
1682
|
+
declare class Conversation {
|
|
1683
|
+
readonly id: string;
|
|
1684
|
+
readonly agent: AgentLike;
|
|
1685
|
+
readonly runner: RunnerProtocol;
|
|
1686
|
+
private _store;
|
|
1687
|
+
private _storeConversationId;
|
|
1688
|
+
private _toolExecutor;
|
|
1689
|
+
private _state;
|
|
1690
|
+
private _history;
|
|
1691
|
+
private _exchangeCount;
|
|
1692
|
+
constructor(agent: AgentLike, runner: RunnerProtocol, options?: {
|
|
1693
|
+
id?: string;
|
|
1694
|
+
store?: ConversationStoreProtocol;
|
|
1695
|
+
toolExecutor?: ToolExecutor;
|
|
1696
|
+
state?: Record<string, unknown>;
|
|
1697
|
+
history?: Exchange[];
|
|
1698
|
+
});
|
|
1699
|
+
/** String session ID for SDK compatibility. */
|
|
1700
|
+
get sessionId(): string;
|
|
1701
|
+
/** Number of completed exchanges. */
|
|
1702
|
+
get exchangeCount(): number;
|
|
1703
|
+
/** All completed exchanges (copy). */
|
|
1704
|
+
get history(): Exchange[];
|
|
1705
|
+
/** Alias for history — matches spec's `exchanges` getter. */
|
|
1706
|
+
get exchanges(): Exchange[];
|
|
1707
|
+
/** Working state. */
|
|
1708
|
+
get state(): Record<string, unknown>;
|
|
1709
|
+
/** Aggregate token usage across all exchanges. */
|
|
1710
|
+
get totalTokens(): {
|
|
1711
|
+
input: number;
|
|
1712
|
+
output: number;
|
|
1713
|
+
total: number;
|
|
1714
|
+
};
|
|
1715
|
+
/** Most recent exchange, or undefined if no history. */
|
|
1716
|
+
get lastExchange(): Exchange | undefined;
|
|
1717
|
+
/** Clear conversation history. */
|
|
1718
|
+
clear(): void;
|
|
1719
|
+
/** Rollback conversation to a specific exchange (inclusive). */
|
|
1720
|
+
rollback(toExchange: number): void;
|
|
1721
|
+
/**
|
|
1722
|
+
* Send a message and get a response.
|
|
1723
|
+
*/
|
|
1724
|
+
send(message: string): Promise<Exchange>;
|
|
1725
|
+
/**
|
|
1726
|
+
* Send a message and stream the response.
|
|
1727
|
+
*
|
|
1728
|
+
* Yields AgentEvents as they arrive. After streaming completes,
|
|
1729
|
+
* the exchange is recorded in history.
|
|
1730
|
+
*/
|
|
1731
|
+
stream(message: string, options?: {
|
|
1732
|
+
eventBus?: AgentEventBus;
|
|
1733
|
+
}): AsyncGenerator<AgentEvent>;
|
|
1734
|
+
/**
|
|
1735
|
+
* Create a new conversation branch.
|
|
1736
|
+
*
|
|
1737
|
+
* @param atExchange - Exchange number to branch from (undefined = current)
|
|
1738
|
+
*/
|
|
1739
|
+
fork(atExchange?: number): Promise<Conversation>;
|
|
1740
|
+
/**
|
|
1741
|
+
* Persist an exchange to the store using the new protocol.
|
|
1742
|
+
*/
|
|
1743
|
+
private _persistExchange;
|
|
1744
|
+
/**
|
|
1745
|
+
* Convert history to canonical message format for runners.
|
|
1746
|
+
*/
|
|
1747
|
+
private _toMessageHistory;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
/**
|
|
1751
|
+
* Base exporter protocol and class for event-driven observability.
|
|
1752
|
+
*
|
|
1753
|
+
* Exporters subscribe to EventBus profiles and handle events for
|
|
1754
|
+
* rendering, tracing, or metrics collection.
|
|
1755
|
+
*
|
|
1756
|
+
* Ported from Python: systems/exporters/base.py
|
|
1757
|
+
*/
|
|
1758
|
+
|
|
1759
|
+
/** Protocol for event exporters. */
|
|
1760
|
+
interface Exporter {
|
|
1761
|
+
attach(bus: EventBus): void;
|
|
1762
|
+
detach(bus: EventBus): void;
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Base class with profile-based subscription.
|
|
1766
|
+
*
|
|
1767
|
+
* Subclasses set `profile` and implement `_on<Suffix>` methods.
|
|
1768
|
+
* The `handleEvent` dispatcher converts event_type to method name:
|
|
1769
|
+
* "agent.message.start" -> "_onMessageStart"
|
|
1770
|
+
* "agent.tool.end" -> "_onToolEnd"
|
|
1771
|
+
* "agent.reasoning" -> "_onReasoning"
|
|
1772
|
+
* "agent.error" -> "_onError"
|
|
1773
|
+
*/
|
|
1774
|
+
declare abstract class BaseExporter implements Exporter {
|
|
1775
|
+
profile: EventProfile;
|
|
1776
|
+
/** Subscribe to all event types in this exporter's profile. */
|
|
1777
|
+
attach(bus: EventBus): void;
|
|
1778
|
+
/** Unsubscribe from all event types in this exporter's profile. */
|
|
1779
|
+
detach(bus: EventBus): void;
|
|
1780
|
+
/**
|
|
1781
|
+
* Dispatch to _on<Suffix> methods by event type.
|
|
1782
|
+
*
|
|
1783
|
+
* Converts event type (e.g. "agent.message.start") to handler
|
|
1784
|
+
* method name (e.g. "_onMessageStart") by stripping the "agent."
|
|
1785
|
+
* prefix and converting dot-separated segments to camelCase.
|
|
1786
|
+
*/
|
|
1787
|
+
handleEvent(event: BaseEvent): Promise<void>;
|
|
1788
|
+
/** Bound reference for subscribe/unsubscribe identity. */
|
|
1789
|
+
private _boundHandleEvent;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
/**
|
|
1793
|
+
* Console exporter - plain text output for agent execution.
|
|
1794
|
+
*
|
|
1795
|
+
* Provides terminal output via EventBus subscription.
|
|
1796
|
+
* Uses a Logger interface to avoid hard dependency on Node globals.
|
|
1797
|
+
*
|
|
1798
|
+
* Ported from Python: systems/exporters/console.py
|
|
1799
|
+
*/
|
|
1800
|
+
|
|
1801
|
+
/** Logger interface for console output. */
|
|
1802
|
+
interface ConsoleLogger {
|
|
1803
|
+
log(message: string): void;
|
|
1804
|
+
error(message: string): void;
|
|
1805
|
+
write(text: string): void;
|
|
1806
|
+
}
|
|
1807
|
+
/**
|
|
1808
|
+
* Console exporter that prints agent events to stdout.
|
|
1809
|
+
*
|
|
1810
|
+
* Subscribes to UX profile events and renders them as plain text.
|
|
1811
|
+
*/
|
|
1812
|
+
declare class ConsoleExporter extends BaseExporter {
|
|
1813
|
+
profile: "ux";
|
|
1814
|
+
private _verbose;
|
|
1815
|
+
private _logger;
|
|
1816
|
+
private _contentBuffer;
|
|
1817
|
+
private _toolNames;
|
|
1818
|
+
constructor(options?: {
|
|
1819
|
+
verbose?: boolean;
|
|
1820
|
+
logger?: ConsoleLogger;
|
|
1821
|
+
});
|
|
1822
|
+
/** @internal */
|
|
1823
|
+
_onMessageStart(_event: MessageStartEvent): Promise<void>;
|
|
1824
|
+
/** @internal */
|
|
1825
|
+
_onMessageChunk(event: MessageChunkEvent): Promise<void>;
|
|
1826
|
+
/** @internal */
|
|
1827
|
+
_onMessageComplete(event: MessageCompleteEvent): Promise<void>;
|
|
1828
|
+
/** @internal */
|
|
1829
|
+
_onReasoning(event: ReasoningEvent): Promise<void>;
|
|
1830
|
+
/** @internal */
|
|
1831
|
+
_onToolStart(event: ToolCallStartEvent): Promise<void>;
|
|
1832
|
+
/** @internal */
|
|
1833
|
+
_onToolEnd(event: ToolCallEndEvent): Promise<void>;
|
|
1834
|
+
/** @internal */
|
|
1835
|
+
_onError(event: ErrorEvent): Promise<void>;
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* Factory function for console exporter.
|
|
1839
|
+
*/
|
|
1840
|
+
declare function createConsoleExporter(options?: {
|
|
1841
|
+
verbose?: boolean;
|
|
1842
|
+
logger?: ConsoleLogger;
|
|
1843
|
+
}): ConsoleExporter;
|
|
1844
|
+
|
|
1845
|
+
/**
|
|
1846
|
+
* Langfuse exporter - LLM observability with traces and generations.
|
|
1847
|
+
*
|
|
1848
|
+
* Exports agent events to Langfuse for LLM-specific observability
|
|
1849
|
+
* including traces, generations (LLM calls), and spans (tool calls).
|
|
1850
|
+
*
|
|
1851
|
+
* Requires @langfuse/langfuse as an optional peer dependency.
|
|
1852
|
+
*
|
|
1853
|
+
* Ported from Python: systems/exporters/langfuse.py
|
|
1854
|
+
*/
|
|
1855
|
+
|
|
1856
|
+
/**
|
|
1857
|
+
* Minimal interface for Langfuse client.
|
|
1858
|
+
*
|
|
1859
|
+
* Users provide the real Langfuse client from @langfuse/langfuse.
|
|
1860
|
+
* We define this interface to avoid a hard dependency.
|
|
1861
|
+
*/
|
|
1862
|
+
interface LangfuseClient {
|
|
1863
|
+
startSpan(params: Record<string, unknown>): LangfuseSpan;
|
|
1864
|
+
flush(): void;
|
|
1865
|
+
}
|
|
1866
|
+
/** Minimal Langfuse span interface. */
|
|
1867
|
+
interface LangfuseSpan {
|
|
1868
|
+
startSpan(params: Record<string, unknown>): LangfuseSpan;
|
|
1869
|
+
startObservation(params: Record<string, unknown>): LangfuseObservation;
|
|
1870
|
+
update(params: Record<string, unknown>): void;
|
|
1871
|
+
updateTrace(params: Record<string, unknown>): void;
|
|
1872
|
+
end(): void;
|
|
1873
|
+
}
|
|
1874
|
+
/** Minimal Langfuse observation interface. */
|
|
1875
|
+
interface LangfuseObservation {
|
|
1876
|
+
update(params: Record<string, unknown>): void;
|
|
1877
|
+
end(): void;
|
|
1878
|
+
}
|
|
1879
|
+
/**
|
|
1880
|
+
* Export agent events to Langfuse for LLM observability.
|
|
1881
|
+
*
|
|
1882
|
+
* Maps the agent event hierarchy to Langfuse concepts:
|
|
1883
|
+
* - MessageStart -> Root span (creates trace implicitly)
|
|
1884
|
+
* - LLM calls -> Generation (nested under root/iteration span)
|
|
1885
|
+
* - Tool calls -> Generation (nested under root/iteration span)
|
|
1886
|
+
* - MessageComplete -> Trace update with final output
|
|
1887
|
+
*/
|
|
1888
|
+
declare class LangfuseExporter extends BaseExporter {
|
|
1889
|
+
profile: "obs";
|
|
1890
|
+
private langfuse;
|
|
1891
|
+
private captureContent;
|
|
1892
|
+
private _rootSpans;
|
|
1893
|
+
private _iterationSpans;
|
|
1894
|
+
private _generations;
|
|
1895
|
+
private _spans;
|
|
1896
|
+
private _traceInputSet;
|
|
1897
|
+
private _iterToolNames;
|
|
1898
|
+
private _iterOutputTokens;
|
|
1899
|
+
private _iterUserMessage;
|
|
1900
|
+
private _prevIterToolNames;
|
|
1901
|
+
constructor(options: {
|
|
1902
|
+
client: LangfuseClient;
|
|
1903
|
+
captureContent?: boolean;
|
|
1904
|
+
});
|
|
1905
|
+
private _toHexId;
|
|
1906
|
+
/** @internal */
|
|
1907
|
+
_onMessageStart(event: MessageStartEvent): Promise<void>;
|
|
1908
|
+
/** @internal */
|
|
1909
|
+
_onIterationStart(event: IterationStartEvent): Promise<void>;
|
|
1910
|
+
/** @internal */
|
|
1911
|
+
_onIterationEnd(event: IterationEndEvent): Promise<void>;
|
|
1912
|
+
/** @internal */
|
|
1913
|
+
_onLlmStart(event: LLMCallStartEvent): Promise<void>;
|
|
1914
|
+
/** @internal */
|
|
1915
|
+
_onLlmEnd(event: LLMCallEndEvent): Promise<void>;
|
|
1916
|
+
/** @internal */
|
|
1917
|
+
_onToolStart(event: ToolCallStartEvent): Promise<void>;
|
|
1918
|
+
/** @internal */
|
|
1919
|
+
_onToolEnd(event: ToolCallEndEvent): Promise<void>;
|
|
1920
|
+
/** @internal */
|
|
1921
|
+
_onReasoning(event: ReasoningEvent): Promise<void>;
|
|
1922
|
+
/** @internal */
|
|
1923
|
+
_onError(event: ErrorEvent): Promise<void>;
|
|
1924
|
+
/** @internal */
|
|
1925
|
+
_onMessageComplete(event: MessageCompleteEvent): Promise<void>;
|
|
1926
|
+
/** Flush pending events to Langfuse. */
|
|
1927
|
+
flush(): void;
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/**
|
|
1931
|
+
* OpenTelemetry exporter - spans to OTLP collector.
|
|
1932
|
+
*
|
|
1933
|
+
* Exports agent events as OpenTelemetry spans following Gen AI
|
|
1934
|
+
* semantic conventions for LLM observability.
|
|
1935
|
+
*
|
|
1936
|
+
* Requires @opentelemetry/api as an optional peer dependency.
|
|
1937
|
+
*
|
|
1938
|
+
* Ported from Python: systems/exporters/otel.py
|
|
1939
|
+
*/
|
|
1940
|
+
|
|
1941
|
+
/** Minimal OTel Span interface. */
|
|
1942
|
+
interface OTelSpan {
|
|
1943
|
+
setAttribute(key: string, value: string | number | boolean): void;
|
|
1944
|
+
setStatus(status: {
|
|
1945
|
+
code: number;
|
|
1946
|
+
message?: string;
|
|
1947
|
+
}): void;
|
|
1948
|
+
recordException(error: Error): void;
|
|
1949
|
+
end(): void;
|
|
1950
|
+
}
|
|
1951
|
+
/** Minimal OTel Tracer interface. */
|
|
1952
|
+
interface OTelTracer {
|
|
1953
|
+
startSpan(name: string, options?: Record<string, unknown>): OTelSpan;
|
|
1954
|
+
}
|
|
1955
|
+
/** OTel StatusCode constants. */
|
|
1956
|
+
declare const OTelStatusCode: {
|
|
1957
|
+
readonly OK: 1;
|
|
1958
|
+
readonly ERROR: 2;
|
|
1959
|
+
};
|
|
1960
|
+
/**
|
|
1961
|
+
* Export agent events as OpenTelemetry spans.
|
|
1962
|
+
*
|
|
1963
|
+
* Maps the agent event hierarchy to OTel spans:
|
|
1964
|
+
* agent.run (root) -> iteration -> llm_call / tool_call
|
|
1965
|
+
*
|
|
1966
|
+
* Follows Gen AI semantic conventions:
|
|
1967
|
+
* - gen_ai.system = "vercel-ai-sdk"
|
|
1968
|
+
* - gen_ai.request.model = model name
|
|
1969
|
+
* - gen_ai.usage.input_tokens / output_tokens
|
|
1970
|
+
*/
|
|
1971
|
+
declare class OTelExporter extends BaseExporter {
|
|
1972
|
+
profile: "obs";
|
|
1973
|
+
private tracer;
|
|
1974
|
+
/** Whether to capture prompt/completion content in spans. */
|
|
1975
|
+
readonly captureContent: boolean;
|
|
1976
|
+
private _spans;
|
|
1977
|
+
constructor(options: {
|
|
1978
|
+
tracer: OTelTracer;
|
|
1979
|
+
captureContent?: boolean;
|
|
1980
|
+
});
|
|
1981
|
+
/** @internal */
|
|
1982
|
+
_onMessageStart(event: MessageStartEvent): Promise<void>;
|
|
1983
|
+
/** @internal */
|
|
1984
|
+
_onIterationStart(event: IterationStartEvent): Promise<void>;
|
|
1985
|
+
/** @internal */
|
|
1986
|
+
_onIterationEnd(event: IterationEndEvent): Promise<void>;
|
|
1987
|
+
/** @internal */
|
|
1988
|
+
_onLlmStart(event: LLMCallStartEvent): Promise<void>;
|
|
1989
|
+
/** @internal */
|
|
1990
|
+
_onLlmEnd(event: LLMCallEndEvent): Promise<void>;
|
|
1991
|
+
/** @internal */
|
|
1992
|
+
_onToolStart(event: ToolCallStartEvent): Promise<void>;
|
|
1993
|
+
/** @internal */
|
|
1994
|
+
_onToolEnd(event: ToolCallEndEvent): Promise<void>;
|
|
1995
|
+
/** @internal */
|
|
1996
|
+
_onError(event: ErrorEvent): Promise<void>;
|
|
1997
|
+
/** @internal */
|
|
1998
|
+
_onMessageComplete(event: MessageCompleteEvent): Promise<void>;
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
/**
|
|
2002
|
+
* SSE Exporter — Fan-out broadcast to connected admin dashboard clients.
|
|
2003
|
+
*
|
|
2004
|
+
* Extends BaseExporter with UX profile. Formats events using SSEFormatter
|
|
2005
|
+
* and broadcasts to all connected ReadableStream clients.
|
|
2006
|
+
*/
|
|
2007
|
+
|
|
2008
|
+
/**
|
|
2009
|
+
* Broadcasts agent events as SSE frames to connected clients.
|
|
2010
|
+
*
|
|
2011
|
+
* Usage:
|
|
2012
|
+
* const exporter = new SSEExporter();
|
|
2013
|
+
* exporter.attach(eventBus);
|
|
2014
|
+
* const stream = exporter.connect(); // return to HTTP response
|
|
2015
|
+
* // Later:
|
|
2016
|
+
* exporter.disconnect(stream);
|
|
2017
|
+
*/
|
|
2018
|
+
declare class SSEExporter extends BaseExporter {
|
|
2019
|
+
profile: "ux";
|
|
2020
|
+
private _clients;
|
|
2021
|
+
private _formatter;
|
|
2022
|
+
private _encoder;
|
|
2023
|
+
/** Connect a new client. Returns a ReadableStream to pipe to the HTTP response. */
|
|
2024
|
+
connect(): ReadableStream<Uint8Array>;
|
|
2025
|
+
/** Disconnect a client stream. */
|
|
2026
|
+
disconnect(stream: ReadableStream<Uint8Array>): void;
|
|
2027
|
+
/** Number of connected clients. */
|
|
2028
|
+
get clientCount(): number;
|
|
2029
|
+
/** Handle any event by broadcasting to all connected clients. */
|
|
2030
|
+
handleEvent(event: BaseEvent): Promise<void>;
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
/**
|
|
2034
|
+
* Coordinator role preset - orchestrates specialist agents within an agency.
|
|
2035
|
+
*
|
|
2036
|
+
* Ported from Python: library/orchestration/archetypes.py
|
|
2037
|
+
*/
|
|
2038
|
+
|
|
2039
|
+
/**
|
|
2040
|
+
* Role that orchestrates specialist agents within an agency.
|
|
2041
|
+
*
|
|
2042
|
+
* A coordinator routes work to specialists, manages execution
|
|
2043
|
+
* sequence, and reviews output quality. It never performs
|
|
2044
|
+
* specialist work directly.
|
|
2045
|
+
*/
|
|
2046
|
+
declare function coordinatorRole(options?: {
|
|
2047
|
+
capability?: Capability;
|
|
2048
|
+
}): Role;
|
|
2049
|
+
|
|
2050
|
+
/**
|
|
2051
|
+
* Orchestrator role preset - conversational routing agent.
|
|
2052
|
+
*
|
|
2053
|
+
* Ported from Python: library/orchestration/archetypes.py
|
|
2054
|
+
*/
|
|
2055
|
+
|
|
2056
|
+
/**
|
|
2057
|
+
* Role that understands user intent and routes to agencies/agents.
|
|
2058
|
+
*
|
|
2059
|
+
* An orchestrator is the chat-facing agent that interprets what
|
|
2060
|
+
* users want, routes to the right specialist team, and synthesizes
|
|
2061
|
+
* responses. It maintains conversational context across turns.
|
|
2062
|
+
*/
|
|
2063
|
+
declare function orchestratorRole(options?: {
|
|
2064
|
+
capability?: Capability;
|
|
2065
|
+
}): Role;
|
|
2066
|
+
|
|
2067
|
+
/**
|
|
2068
|
+
* Analyst role preset - specialized judgment for evidence-based assessments.
|
|
2069
|
+
*
|
|
2070
|
+
* Ported from Python: library/orchestration/archetypes.py
|
|
2071
|
+
*/
|
|
2072
|
+
|
|
2073
|
+
/**
|
|
2074
|
+
* Role that applies specialized judgment to produce typed assessments.
|
|
2075
|
+
*
|
|
2076
|
+
* An analyst receives pre-gathered context and applies domain-specific
|
|
2077
|
+
* judgment heuristics to produce a structured, evidence-backed
|
|
2078
|
+
* assessment. Analysts do not gather data -- they reason over it.
|
|
2079
|
+
*/
|
|
2080
|
+
declare function analystRole(options?: {
|
|
2081
|
+
domain?: string;
|
|
2082
|
+
capability?: Capability;
|
|
2083
|
+
extraJudgments?: Judgment[];
|
|
2084
|
+
}): Role;
|
|
2085
|
+
|
|
2086
|
+
/**
|
|
2087
|
+
* Retrieval role preset - knowledge researcher.
|
|
2088
|
+
*
|
|
2089
|
+
* Ported from Python: library/orchestration/archetypes.py
|
|
2090
|
+
*/
|
|
2091
|
+
|
|
2092
|
+
/**
|
|
2093
|
+
* Role that finds and organizes relevant evidence from data sources.
|
|
2094
|
+
*
|
|
2095
|
+
* A retrieval agent decomposes information requests into targeted
|
|
2096
|
+
* search queries, executes them systematically, and organizes results
|
|
2097
|
+
* by the requester's stated dimensions.
|
|
2098
|
+
*/
|
|
2099
|
+
declare function retrievalRole(options?: {
|
|
2100
|
+
capability?: Capability;
|
|
2101
|
+
extraJudgments?: Judgment[];
|
|
2102
|
+
}): Role;
|
|
2103
|
+
|
|
2104
|
+
/**
|
|
2105
|
+
* Judgments for orchestration archetypes.
|
|
2106
|
+
*
|
|
2107
|
+
* Ported from Python: library/orchestration/judgments.py
|
|
2108
|
+
*/
|
|
2109
|
+
|
|
2110
|
+
declare const ROUTING: Judgment;
|
|
2111
|
+
declare const QUALITY_REVIEW: Judgment;
|
|
2112
|
+
declare const INTENT_CLASSIFICATION: Judgment;
|
|
2113
|
+
declare const RETRIEVAL_STRATEGY: Judgment;
|
|
2114
|
+
declare const EVIDENCE_QUALITY: Judgment;
|
|
2115
|
+
|
|
2116
|
+
/**
|
|
2117
|
+
* Responsibilities for orchestration archetypes.
|
|
2118
|
+
*
|
|
2119
|
+
* Ported from Python: library/orchestration/responsibilities.py
|
|
2120
|
+
*/
|
|
2121
|
+
|
|
2122
|
+
declare const ORCHESTRATION: Responsibility;
|
|
2123
|
+
declare const QUALITY_GATE: Responsibility;
|
|
2124
|
+
declare const INTENT_ROUTING: Responsibility;
|
|
2125
|
+
declare const RESPONSE_SYNTHESIS: Responsibility;
|
|
2126
|
+
declare const INFORMATION_RETRIEVAL: Responsibility;
|
|
2127
|
+
declare const ANALYSIS: Responsibility;
|
|
2128
|
+
|
|
2129
|
+
declare class CalculatorToolbox extends Toolbox {
|
|
2130
|
+
readonly name = "calculator_operations";
|
|
2131
|
+
readonly description = "Arithmetic and algebraic calculator operations";
|
|
2132
|
+
readonly tools: Record<string, ToolDefinition>;
|
|
2133
|
+
}
|
|
2134
|
+
declare function buildCalculatorAgent(): _agentic_patterns_core.Agent;
|
|
2135
|
+
|
|
2136
|
+
declare class TodoToolbox extends Toolbox {
|
|
2137
|
+
readonly name = "task_management";
|
|
2138
|
+
readonly description = "In-memory task list management";
|
|
2139
|
+
readonly tools: Record<string, ToolDefinition>;
|
|
2140
|
+
}
|
|
2141
|
+
declare function buildTodoAgent(): _agentic_patterns_core.Agent;
|
|
2142
|
+
|
|
2143
|
+
/**
|
|
2144
|
+
* Writing Coach — a tools-free agent preset that demonstrates
|
|
2145
|
+
* pure persona + reasoning without any toolbox or capability.
|
|
2146
|
+
*/
|
|
2147
|
+
declare function buildWritingCoachAgent(): _agentic_patterns_core.Agent;
|
|
2148
|
+
|
|
2149
|
+
/**
|
|
2150
|
+
* Workflow base types — shared types, events, hooks, and helpers
|
|
2151
|
+
* that all workflow patterns depend on.
|
|
2152
|
+
*
|
|
2153
|
+
* Ported from Python: workflows/base.py
|
|
2154
|
+
*/
|
|
2155
|
+
|
|
2156
|
+
/** Shared context passed through workflow steps. */
|
|
2157
|
+
type PatternContext = Record<string, unknown>;
|
|
2158
|
+
/** A message template: either a static string or a function that builds one. */
|
|
2159
|
+
type MessageTemplate = string | ((context: PatternContext) => string);
|
|
2160
|
+
/** A single step in a workflow pattern. */
|
|
2161
|
+
interface Step {
|
|
2162
|
+
readonly agent: AgentLike;
|
|
2163
|
+
readonly messageTemplate: MessageTemplate;
|
|
2164
|
+
readonly name?: string;
|
|
2165
|
+
readonly outputKey?: string;
|
|
2166
|
+
readonly contextExtractor?: (result: StepResult, context: PatternContext) => PatternContext;
|
|
2167
|
+
}
|
|
2168
|
+
/** Result of executing a single step. */
|
|
2169
|
+
interface StepResult {
|
|
2170
|
+
readonly stepName: string;
|
|
2171
|
+
readonly runResult: RunResult;
|
|
2172
|
+
/** Shortcut for `runResult.response`. */
|
|
2173
|
+
readonly content: string;
|
|
2174
|
+
readonly inputTokens: number;
|
|
2175
|
+
readonly outputTokens: number;
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Create a frozen StepResult from a RunResult.
|
|
2179
|
+
*/
|
|
2180
|
+
declare function createStepResult(stepName: string, runResult: RunResult): StepResult;
|
|
2181
|
+
/** Aggregate result of a workflow pattern execution. */
|
|
2182
|
+
interface PatternResult {
|
|
2183
|
+
readonly totalInputTokens: number;
|
|
2184
|
+
readonly totalOutputTokens: number;
|
|
2185
|
+
readonly succeeded: boolean;
|
|
2186
|
+
readonly finalContent: string;
|
|
2187
|
+
}
|
|
2188
|
+
interface PatternStartEvent {
|
|
2189
|
+
readonly type: "pattern.start";
|
|
2190
|
+
readonly patternName: string;
|
|
2191
|
+
readonly timestamp: Date;
|
|
2192
|
+
}
|
|
2193
|
+
interface PatternStepStartEvent {
|
|
2194
|
+
readonly type: "pattern.step.start";
|
|
2195
|
+
readonly stepName: string;
|
|
2196
|
+
readonly stepIndex: number;
|
|
2197
|
+
readonly timestamp: Date;
|
|
2198
|
+
}
|
|
2199
|
+
interface PatternStepCompleteEvent {
|
|
2200
|
+
readonly type: "pattern.step.complete";
|
|
2201
|
+
readonly stepName: string;
|
|
2202
|
+
readonly stepIndex: number;
|
|
2203
|
+
readonly result: StepResult;
|
|
2204
|
+
readonly timestamp: Date;
|
|
2205
|
+
}
|
|
2206
|
+
interface PatternStepErrorEvent {
|
|
2207
|
+
readonly type: "pattern.step.error";
|
|
2208
|
+
readonly stepName: string;
|
|
2209
|
+
readonly stepIndex: number;
|
|
2210
|
+
readonly error: Error;
|
|
2211
|
+
readonly timestamp: Date;
|
|
2212
|
+
}
|
|
2213
|
+
interface PatternIterationStartEvent {
|
|
2214
|
+
readonly type: "pattern.iteration.start";
|
|
2215
|
+
readonly iteration: number;
|
|
2216
|
+
readonly timestamp: Date;
|
|
2217
|
+
}
|
|
2218
|
+
interface PatternIterationCompleteEvent {
|
|
2219
|
+
readonly type: "pattern.iteration.complete";
|
|
2220
|
+
readonly iteration: number;
|
|
2221
|
+
readonly timestamp: Date;
|
|
2222
|
+
}
|
|
2223
|
+
interface PatternCompleteEvent {
|
|
2224
|
+
readonly type: "pattern.complete";
|
|
2225
|
+
readonly patternName: string;
|
|
2226
|
+
readonly result: PatternResult;
|
|
2227
|
+
readonly timestamp: Date;
|
|
2228
|
+
}
|
|
2229
|
+
type PatternEvent = PatternStartEvent | PatternStepStartEvent | PatternStepCompleteEvent | PatternStepErrorEvent | PatternIterationStartEvent | PatternIterationCompleteEvent | PatternCompleteEvent;
|
|
2230
|
+
/**
|
|
2231
|
+
* Callbacks for pattern lifecycle events.
|
|
2232
|
+
*
|
|
2233
|
+
* NOTE: These are workflow-level hooks for pattern orchestration.
|
|
2234
|
+
* They are NOT the same as the deprecated runner-level Hooks interface.
|
|
2235
|
+
*/
|
|
2236
|
+
interface PatternHooks {
|
|
2237
|
+
onPatternStart?: (event: PatternStartEvent) => void | Promise<void>;
|
|
2238
|
+
onStepStart?: (event: PatternStepStartEvent) => void | Promise<void>;
|
|
2239
|
+
onStepComplete?: (event: PatternStepCompleteEvent) => void | Promise<void>;
|
|
2240
|
+
onStepError?: (event: PatternStepErrorEvent) => void | Promise<void>;
|
|
2241
|
+
onIterationStart?: (event: PatternIterationStartEvent) => void | Promise<void>;
|
|
2242
|
+
onIterationComplete?: (event: PatternIterationCompleteEvent) => void | Promise<void>;
|
|
2243
|
+
onPatternComplete?: (event: PatternCompleteEvent) => void | Promise<void>;
|
|
2244
|
+
}
|
|
2245
|
+
/** Options passed to pattern.run(). */
|
|
2246
|
+
interface PatternRunOptions {
|
|
2247
|
+
readonly runner: RunnerProtocol;
|
|
2248
|
+
readonly hooks?: PatternHooks;
|
|
2249
|
+
readonly toolExecutor?: ToolExecutor;
|
|
2250
|
+
readonly traceId?: string;
|
|
2251
|
+
}
|
|
2252
|
+
/** Interface that all workflow patterns implement. */
|
|
2253
|
+
interface PatternProtocol {
|
|
2254
|
+
run(context?: PatternContext, options?: PatternRunOptions): Promise<PatternResult>;
|
|
2255
|
+
}
|
|
2256
|
+
/** Result tuple: [achieved, reason, confident]. */
|
|
2257
|
+
type GoalEvaluationResult = readonly [achieved: boolean, reason: string, confident: boolean];
|
|
2258
|
+
/** Protocol for evaluating whether a goal has been achieved. */
|
|
2259
|
+
interface GoalEvaluatorProtocol {
|
|
2260
|
+
evaluate(goal: string, output: string, context?: PatternContext): Promise<GoalEvaluationResult>;
|
|
2261
|
+
}
|
|
2262
|
+
/**
|
|
2263
|
+
* Resolve a message template to a string.
|
|
2264
|
+
*/
|
|
2265
|
+
declare function resolveMessage(template: MessageTemplate, context: PatternContext): string;
|
|
2266
|
+
/**
|
|
2267
|
+
* Generate a step name, falling back to `step_<index>` if none provided.
|
|
2268
|
+
*/
|
|
2269
|
+
declare function makeStepName(name: string | undefined, index: number): string;
|
|
2270
|
+
/**
|
|
2271
|
+
* Execute a single step: resolve message, run agent, return result.
|
|
2272
|
+
*/
|
|
2273
|
+
declare function executeStep(step: Step, context: PatternContext, runner: RunnerProtocol, toolExecutor?: ToolExecutor): Promise<StepResult>;
|
|
2274
|
+
|
|
2275
|
+
/**
|
|
2276
|
+
* Sequential — Chain agents in sequence, threading context through the pipeline.
|
|
2277
|
+
*
|
|
2278
|
+
* Ported from Python: workflows/compositions/sequential.py
|
|
2279
|
+
*/
|
|
2280
|
+
|
|
2281
|
+
interface SequentialResult extends PatternResult {
|
|
2282
|
+
readonly steps: ReadonlyArray<StepResult | PatternResult>;
|
|
2283
|
+
readonly finalContext: Readonly<PatternContext>;
|
|
2284
|
+
}
|
|
2285
|
+
interface SequentialOptions {
|
|
2286
|
+
readonly continueOnError?: boolean;
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* Chain agents in sequence, threading context through the pipeline.
|
|
2290
|
+
*
|
|
2291
|
+
* Each step reads context, writes via `outputKey` and `contextExtractor`.
|
|
2292
|
+
* Supports nested patterns (any PatternProtocol) as steps.
|
|
2293
|
+
*
|
|
2294
|
+
* Example:
|
|
2295
|
+
* const seq = new Sequential([
|
|
2296
|
+
* { agent: writer, messageTemplate: "Write about {topic}" },
|
|
2297
|
+
* { agent: reviewer, messageTemplate: (ctx) => `Review: ${ctx.draft}` },
|
|
2298
|
+
* ]);
|
|
2299
|
+
*/
|
|
2300
|
+
declare class Sequential implements PatternProtocol {
|
|
2301
|
+
private readonly steps;
|
|
2302
|
+
private readonly continueOnError;
|
|
2303
|
+
constructor(steps: Array<Step | PatternProtocol>, options?: SequentialOptions);
|
|
2304
|
+
run(context?: PatternContext, options?: PatternRunOptions): Promise<SequentialResult>;
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
/**
|
|
2308
|
+
* Parallel — Fan-out agents in parallel with optional concurrency limiting.
|
|
2309
|
+
*
|
|
2310
|
+
* Ported from Python: workflows/compositions/parallel.py
|
|
2311
|
+
*/
|
|
2312
|
+
|
|
2313
|
+
/** Consolidator: reduce step results to a single value. */
|
|
2314
|
+
type Consolidator = (results: StepResult[]) => unknown;
|
|
2315
|
+
/** Collect all step contents into an array. */
|
|
2316
|
+
declare function collectContents(results: StepResult[]): string[];
|
|
2317
|
+
/** Collect step contents keyed by step name. */
|
|
2318
|
+
declare function collectByName(results: StepResult[]): Record<string, string>;
|
|
2319
|
+
interface ParallelResult extends PatternResult {
|
|
2320
|
+
readonly results: ReadonlyArray<StepResult | Error>;
|
|
2321
|
+
readonly successful: ReadonlyArray<StepResult>;
|
|
2322
|
+
readonly failed: ReadonlyArray<readonly [number, Error]>;
|
|
2323
|
+
readonly consolidatedOutput: Readonly<Record<string, unknown>>;
|
|
2324
|
+
readonly allSucceeded: boolean;
|
|
2325
|
+
}
|
|
2326
|
+
interface ParallelOptions {
|
|
2327
|
+
readonly outputKey?: string;
|
|
2328
|
+
readonly consolidator?: Consolidator;
|
|
2329
|
+
readonly returnExceptions?: boolean;
|
|
2330
|
+
readonly maxConcurrency?: number;
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* Fan-out agents in parallel with optional concurrency limiting.
|
|
2334
|
+
*
|
|
2335
|
+
* All steps receive the same context snapshot.
|
|
2336
|
+
* Results preserve input order.
|
|
2337
|
+
*
|
|
2338
|
+
* Example:
|
|
2339
|
+
* const par = new Parallel([
|
|
2340
|
+
* { agent: analyst1, messageTemplate: "Analyze data" },
|
|
2341
|
+
* { agent: analyst2, messageTemplate: "Analyze data" },
|
|
2342
|
+
* ], { maxConcurrency: 2 });
|
|
2343
|
+
*/
|
|
2344
|
+
declare class Parallel implements PatternProtocol {
|
|
2345
|
+
private readonly steps;
|
|
2346
|
+
private readonly outputKey;
|
|
2347
|
+
private readonly consolidator;
|
|
2348
|
+
private readonly returnExceptions;
|
|
2349
|
+
private readonly maxConcurrency;
|
|
2350
|
+
constructor(steps: Step[], options?: ParallelOptions);
|
|
2351
|
+
run(context?: PatternContext, options?: PatternRunOptions): Promise<ParallelResult>;
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
/**
|
|
2355
|
+
* RetryLoop — Generic async retry wrapper with pluggable backoff strategies.
|
|
2356
|
+
*
|
|
2357
|
+
* Not agent-specific — wraps any `() => Promise<T>`.
|
|
2358
|
+
*
|
|
2359
|
+
* Ported from Python: workflows/loops/retry.py
|
|
2360
|
+
*/
|
|
2361
|
+
|
|
2362
|
+
/** Backoff strategy: given an attempt number (0-based), return delay in ms. */
|
|
2363
|
+
interface BackoffStrategy {
|
|
2364
|
+
getDelay(attempt: number): number;
|
|
2365
|
+
}
|
|
2366
|
+
/** Fixed delay between retries. */
|
|
2367
|
+
declare class FixedBackoff implements BackoffStrategy {
|
|
2368
|
+
private readonly delayMs;
|
|
2369
|
+
constructor(delayMs: number);
|
|
2370
|
+
getDelay(_attempt: number): number;
|
|
2371
|
+
}
|
|
2372
|
+
/** Exponential backoff: baseMs * 2^attempt, capped at maxMs. */
|
|
2373
|
+
declare class ExponentialBackoff implements BackoffStrategy {
|
|
2374
|
+
private readonly baseMs;
|
|
2375
|
+
private readonly maxMs;
|
|
2376
|
+
constructor(baseMs?: number, maxMs?: number);
|
|
2377
|
+
getDelay(attempt: number): number;
|
|
2378
|
+
}
|
|
2379
|
+
/** Jittered exponential backoff: adds random jitter to exponential delay. */
|
|
2380
|
+
declare class JitteredBackoff implements BackoffStrategy {
|
|
2381
|
+
private readonly exponential;
|
|
2382
|
+
constructor(baseMs?: number, maxMs?: number);
|
|
2383
|
+
getDelay(attempt: number): number;
|
|
2384
|
+
}
|
|
2385
|
+
/** Exit reason for a retry loop. */
|
|
2386
|
+
type RetryExitReason = "success" | "max_attempts" | "fatal_error" | "timeout";
|
|
2387
|
+
/** Result of a retry loop execution. */
|
|
2388
|
+
interface RetryResult<T> extends PatternResult {
|
|
2389
|
+
readonly exitReason: RetryExitReason;
|
|
2390
|
+
readonly attempts: number;
|
|
2391
|
+
readonly value?: T;
|
|
2392
|
+
readonly lastError?: Error;
|
|
2393
|
+
}
|
|
2394
|
+
interface RetryLoopOptions {
|
|
2395
|
+
readonly maxAttempts?: number;
|
|
2396
|
+
readonly backoff?: BackoffStrategy;
|
|
2397
|
+
readonly timeoutMs?: number;
|
|
2398
|
+
readonly fatalErrors?: ReadonlyArray<abstract new (...args: never[]) => Error>;
|
|
2399
|
+
readonly onRetry?: (attempt: number, error: Error) => void | Promise<void>;
|
|
2400
|
+
readonly hooks?: PatternHooks;
|
|
2401
|
+
}
|
|
2402
|
+
interface RetryRunOptions {
|
|
2403
|
+
readonly hooks?: PatternHooks;
|
|
2404
|
+
}
|
|
2405
|
+
/**
|
|
2406
|
+
* Generic async retry wrapper with pluggable backoff.
|
|
2407
|
+
*
|
|
2408
|
+
* Example:
|
|
2409
|
+
* const loop = new RetryLoop<string>({ maxAttempts: 3 });
|
|
2410
|
+
* const result = await loop.run(async () => fetchData());
|
|
2411
|
+
*/
|
|
2412
|
+
declare class RetryLoop<T> {
|
|
2413
|
+
private readonly maxAttempts;
|
|
2414
|
+
private readonly backoff;
|
|
2415
|
+
private readonly timeoutMs;
|
|
2416
|
+
private readonly fatalErrors;
|
|
2417
|
+
private readonly onRetry;
|
|
2418
|
+
private readonly defaultHooks;
|
|
2419
|
+
constructor(options?: RetryLoopOptions);
|
|
2420
|
+
run(fn: () => Promise<T>, options?: RetryRunOptions): Promise<RetryResult<T>>;
|
|
2421
|
+
private isFatal;
|
|
2422
|
+
private buildResult;
|
|
2423
|
+
}
|
|
2424
|
+
|
|
2425
|
+
/**
|
|
2426
|
+
* Goal Evaluators — Four implementations of GoalEvaluatorProtocol,
|
|
2427
|
+
* ranked cheapest to most expensive.
|
|
2428
|
+
*
|
|
2429
|
+
* Ported from Python: workflows/evaluators.py
|
|
2430
|
+
*/
|
|
2431
|
+
|
|
2432
|
+
interface SimpleGoalEvaluatorOptions {
|
|
2433
|
+
readonly successPatterns?: readonly string[];
|
|
2434
|
+
readonly failurePatterns?: readonly string[];
|
|
2435
|
+
}
|
|
2436
|
+
/**
|
|
2437
|
+
* Pattern-matching evaluator: checks output for success/failure substrings.
|
|
2438
|
+
* Returns not-confident if no patterns match.
|
|
2439
|
+
*/
|
|
2440
|
+
declare class SimpleGoalEvaluator implements GoalEvaluatorProtocol {
|
|
2441
|
+
private readonly successPatterns;
|
|
2442
|
+
private readonly failurePatterns;
|
|
2443
|
+
constructor(options?: SimpleGoalEvaluatorOptions);
|
|
2444
|
+
evaluate(_goal: string, output: string, _context?: PatternContext): Promise<GoalEvaluationResult>;
|
|
2445
|
+
}
|
|
2446
|
+
/**
|
|
2447
|
+
* Parses agent output for structured markers:
|
|
2448
|
+
* GOAL_STATUS: ACHIEVED|NOT_ACHIEVED
|
|
2449
|
+
* PROGRESS: <text>
|
|
2450
|
+
*/
|
|
2451
|
+
declare class SelfEvalGoalEvaluator implements GoalEvaluatorProtocol {
|
|
2452
|
+
evaluate(_goal: string, output: string, _context?: PatternContext): Promise<GoalEvaluationResult>;
|
|
2453
|
+
}
|
|
2454
|
+
interface LLMGoalEvaluatorOptions {
|
|
2455
|
+
readonly agent: AgentLike;
|
|
2456
|
+
readonly runner: RunnerProtocol;
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
* Sends goal + output to an evaluator agent, parses GOAL_STATUS from response.
|
|
2460
|
+
*/
|
|
2461
|
+
declare class LLMGoalEvaluator implements GoalEvaluatorProtocol {
|
|
2462
|
+
private readonly agent;
|
|
2463
|
+
private readonly runner;
|
|
2464
|
+
constructor(options: LLMGoalEvaluatorOptions);
|
|
2465
|
+
evaluate(goal: string, output: string, _context?: PatternContext): Promise<GoalEvaluationResult>;
|
|
2466
|
+
}
|
|
2467
|
+
/**
|
|
2468
|
+
* Tries evaluators in order, stops on first confident result.
|
|
2469
|
+
* Falls back to last result if none are confident.
|
|
2470
|
+
*/
|
|
2471
|
+
declare class EvaluatorChain implements GoalEvaluatorProtocol {
|
|
2472
|
+
private readonly evaluators;
|
|
2473
|
+
constructor(evaluators: GoalEvaluatorProtocol[]);
|
|
2474
|
+
evaluate(goal: string, output: string, context?: PatternContext): Promise<GoalEvaluationResult>;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
/**
|
|
2478
|
+
* TaskLoop — Goal-driven iterative loop.
|
|
2479
|
+
*
|
|
2480
|
+
* Runs an agent toward a goal, evaluating progress each iteration.
|
|
2481
|
+
*
|
|
2482
|
+
* Ported from Python: workflows/loops/task.py
|
|
2483
|
+
*/
|
|
2484
|
+
|
|
2485
|
+
type TaskExitReason = "goal_achieved" | "max_iterations" | "explicit_stop" | "error";
|
|
2486
|
+
interface TaskState {
|
|
2487
|
+
readonly iteration: number;
|
|
2488
|
+
readonly history: readonly string[];
|
|
2489
|
+
getHistorySummary(): string;
|
|
2490
|
+
}
|
|
2491
|
+
interface TaskResult extends PatternResult {
|
|
2492
|
+
readonly exitReason: TaskExitReason;
|
|
2493
|
+
readonly iterations: number;
|
|
2494
|
+
readonly state: TaskState;
|
|
2495
|
+
}
|
|
2496
|
+
interface TaskLoopOptions {
|
|
2497
|
+
readonly maxIterations?: number;
|
|
2498
|
+
readonly stopPhrases?: readonly string[];
|
|
2499
|
+
readonly includeHistory?: boolean;
|
|
2500
|
+
readonly hooks?: PatternHooks;
|
|
2501
|
+
}
|
|
2502
|
+
interface TaskRunOptions {
|
|
2503
|
+
readonly runner: RunnerProtocol;
|
|
2504
|
+
readonly toolExecutor?: ToolExecutor;
|
|
2505
|
+
readonly hooks?: PatternHooks;
|
|
2506
|
+
}
|
|
2507
|
+
/**
|
|
2508
|
+
* Iterative loop that runs an agent toward a goal, evaluating progress.
|
|
2509
|
+
*
|
|
2510
|
+
* Example:
|
|
2511
|
+
* const loop = new TaskLoop(agent, evaluator, { maxIterations: 5 });
|
|
2512
|
+
* const result = await loop.run("Write a poem about TypeScript", {}, { runner });
|
|
2513
|
+
*/
|
|
2514
|
+
declare class TaskLoop {
|
|
2515
|
+
private readonly agent;
|
|
2516
|
+
private readonly goalEvaluator;
|
|
2517
|
+
private readonly maxIterations;
|
|
2518
|
+
private readonly stopPhrases;
|
|
2519
|
+
private readonly includeHistory;
|
|
2520
|
+
private readonly defaultHooks;
|
|
2521
|
+
constructor(agent: AgentLike, goalEvaluator: GoalEvaluatorProtocol, options?: TaskLoopOptions);
|
|
2522
|
+
run(goal: string, context?: PatternContext, options?: TaskRunOptions): Promise<TaskResult>;
|
|
2523
|
+
private buildPrompt;
|
|
2524
|
+
private containsStopPhrase;
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
/**
|
|
2528
|
+
* EvaluatorLoop — Producer-Evaluator Refinement Loop.
|
|
2529
|
+
*
|
|
2530
|
+
* Producer generates output → evaluator scores + critiques → producer refines.
|
|
2531
|
+
* Tracks best output by score, exits on quality/max/plateau/error.
|
|
2532
|
+
*
|
|
2533
|
+
* Ported from Python: workflows/loops/evaluator.py
|
|
2534
|
+
*/
|
|
2535
|
+
|
|
2536
|
+
type RefinementExitReason = "quality_met" | "max_refinements" | "no_improvement" | "error";
|
|
2537
|
+
/** A single evaluation of produced output. */
|
|
2538
|
+
interface Refinement {
|
|
2539
|
+
readonly iteration: number;
|
|
2540
|
+
readonly content: string;
|
|
2541
|
+
readonly score: number;
|
|
2542
|
+
readonly feedback: string;
|
|
2543
|
+
}
|
|
2544
|
+
/** Protocol for evaluating produced output and providing refinement feedback. */
|
|
2545
|
+
interface RefinementEvaluator {
|
|
2546
|
+
evaluate(input: string, output: string, context?: PatternContext): Promise<{
|
|
2547
|
+
score: number;
|
|
2548
|
+
feedback: string;
|
|
2549
|
+
qualityMet: boolean;
|
|
2550
|
+
}>;
|
|
2551
|
+
}
|
|
2552
|
+
/** Result of the evaluator loop. */
|
|
2553
|
+
interface RefinementResult extends PatternResult {
|
|
2554
|
+
readonly exitReason: RefinementExitReason;
|
|
2555
|
+
readonly refinements: readonly Refinement[];
|
|
2556
|
+
readonly bestOutput: string;
|
|
2557
|
+
readonly bestScore: number;
|
|
2558
|
+
readonly iterations: number;
|
|
2559
|
+
}
|
|
2560
|
+
interface EvaluatorLoopOptions {
|
|
2561
|
+
readonly maxRefinements?: number;
|
|
2562
|
+
readonly minImprovement?: number;
|
|
2563
|
+
readonly hooks?: PatternHooks;
|
|
2564
|
+
}
|
|
2565
|
+
interface EvaluatorRunOptions {
|
|
2566
|
+
readonly runner: RunnerProtocol;
|
|
2567
|
+
readonly toolExecutor?: ToolExecutor;
|
|
2568
|
+
readonly hooks?: PatternHooks;
|
|
2569
|
+
}
|
|
2570
|
+
/**
|
|
2571
|
+
* Self-critique refinement loop: producer generates, evaluator scores,
|
|
2572
|
+
* producer refines until quality is met or exit conditions are reached.
|
|
2573
|
+
*
|
|
2574
|
+
* Example:
|
|
2575
|
+
* const loop = new EvaluatorLoop(writerAgent, evaluator, { maxRefinements: 3 });
|
|
2576
|
+
* const result = await loop.run("Write a haiku", { runner });
|
|
2577
|
+
*/
|
|
2578
|
+
declare class EvaluatorLoop {
|
|
2579
|
+
private readonly producer;
|
|
2580
|
+
private readonly evaluator;
|
|
2581
|
+
private readonly maxRefinements;
|
|
2582
|
+
private readonly minImprovement;
|
|
2583
|
+
private readonly defaultHooks;
|
|
2584
|
+
constructor(producer: AgentLike, evaluator: RefinementEvaluator, options?: EvaluatorLoopOptions);
|
|
2585
|
+
run(input: string, options?: EvaluatorRunOptions): Promise<RefinementResult>;
|
|
2586
|
+
private buildPrompt;
|
|
2587
|
+
}
|
|
2588
|
+
interface LLMRefinementEvaluatorOptions {
|
|
2589
|
+
readonly qualityThreshold?: number;
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* Uses an LLM agent to evaluate output quality, parse score and feedback.
|
|
2593
|
+
*/
|
|
2594
|
+
declare class LLMRefinementEvaluator implements RefinementEvaluator {
|
|
2595
|
+
private readonly agent;
|
|
2596
|
+
private readonly runner;
|
|
2597
|
+
private readonly qualityThreshold;
|
|
2598
|
+
constructor(agent: AgentLike, runner: RunnerProtocol, options?: LLMRefinementEvaluatorOptions);
|
|
2599
|
+
evaluate(input: string, output: string): Promise<{
|
|
2600
|
+
score: number;
|
|
2601
|
+
feedback: string;
|
|
2602
|
+
qualityMet: boolean;
|
|
2603
|
+
}>;
|
|
2604
|
+
}
|
|
2605
|
+
/** A single rubric criterion with name, weight, and scoring function. */
|
|
2606
|
+
interface RubricCriterion {
|
|
2607
|
+
readonly name: string;
|
|
2608
|
+
readonly weight: number;
|
|
2609
|
+
readonly score: (input: string, output: string) => number | Promise<number>;
|
|
2610
|
+
}
|
|
2611
|
+
/**
|
|
2612
|
+
* Scores output against a set of weighted rubric criteria.
|
|
2613
|
+
*/
|
|
2614
|
+
declare class RubricEvaluator implements RefinementEvaluator {
|
|
2615
|
+
private readonly criteria;
|
|
2616
|
+
private readonly qualityThreshold;
|
|
2617
|
+
constructor(criteria: readonly RubricCriterion[], qualityThreshold?: number);
|
|
2618
|
+
evaluate(input: string, output: string): Promise<{
|
|
2619
|
+
score: number;
|
|
2620
|
+
feedback: string;
|
|
2621
|
+
qualityMet: boolean;
|
|
2622
|
+
}>;
|
|
2623
|
+
}
|
|
2624
|
+
/** An evaluator with an associated weight for compositing. */
|
|
2625
|
+
interface WeightedEvaluator {
|
|
2626
|
+
readonly evaluator: RefinementEvaluator;
|
|
2627
|
+
readonly weight: number;
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* Combines multiple evaluators into a weighted average score.
|
|
2631
|
+
*/
|
|
2632
|
+
declare class CompositeRefinementEvaluator implements RefinementEvaluator {
|
|
2633
|
+
private readonly evaluators;
|
|
2634
|
+
private readonly qualityThreshold;
|
|
2635
|
+
constructor(evaluators: readonly WeightedEvaluator[], qualityThreshold?: number);
|
|
2636
|
+
evaluate(input: string, output: string, context?: PatternContext): Promise<{
|
|
2637
|
+
score: number;
|
|
2638
|
+
feedback: string;
|
|
2639
|
+
qualityMet: boolean;
|
|
2640
|
+
}>;
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
/**
|
|
2644
|
+
* ConversationLoop — Multi-turn conversation orchestration.
|
|
2645
|
+
*
|
|
2646
|
+
* Wraps the Conversation class, driving exchanges via external
|
|
2647
|
+
* inputFn/outputFn callbacks. Exits on exit phrase, max exchanges, or error.
|
|
2648
|
+
*
|
|
2649
|
+
* Ported from Python: workflows/loops/conversation.py
|
|
2650
|
+
*/
|
|
2651
|
+
|
|
2652
|
+
type ConversationExitReason = "exit_phrase" | "max_exchanges" | "input_closed" | "error";
|
|
2653
|
+
interface ConversationResult extends PatternResult {
|
|
2654
|
+
readonly exitReason: ConversationExitReason;
|
|
2655
|
+
readonly exchangeCount: number;
|
|
2656
|
+
readonly conversation: Conversation;
|
|
2657
|
+
}
|
|
2658
|
+
interface ConversationLoopOptions {
|
|
2659
|
+
readonly maxExchanges?: number;
|
|
2660
|
+
readonly exitPhrases?: readonly string[];
|
|
2661
|
+
readonly store?: ConversationStoreProtocol;
|
|
2662
|
+
readonly toolExecutor?: ToolExecutor;
|
|
2663
|
+
readonly hooks?: PatternHooks;
|
|
2664
|
+
}
|
|
2665
|
+
interface ConversationRunOptions {
|
|
2666
|
+
readonly runner: RunnerProtocol;
|
|
2667
|
+
readonly inputFn: () => string | null | Promise<string | null>;
|
|
2668
|
+
readonly outputFn?: (response: string) => void | Promise<void>;
|
|
2669
|
+
readonly hooks?: PatternHooks;
|
|
2670
|
+
}
|
|
2671
|
+
/**
|
|
2672
|
+
* Multi-turn conversation loop with external I/O callbacks.
|
|
2673
|
+
*
|
|
2674
|
+
* Example:
|
|
2675
|
+
* const loop = new ConversationLoop(agent, { maxExchanges: 10 });
|
|
2676
|
+
* const result = await loop.run({
|
|
2677
|
+
* runner,
|
|
2678
|
+
* inputFn: () => readLine(),
|
|
2679
|
+
* outputFn: (r) => console.log(r),
|
|
2680
|
+
* });
|
|
2681
|
+
*/
|
|
2682
|
+
declare class ConversationLoop {
|
|
2683
|
+
private readonly agent;
|
|
2684
|
+
private readonly maxExchanges;
|
|
2685
|
+
private readonly exitPhrases;
|
|
2686
|
+
private readonly store;
|
|
2687
|
+
private readonly toolExecutor;
|
|
2688
|
+
private readonly defaultHooks;
|
|
2689
|
+
constructor(agent: AgentLike, options?: ConversationLoopOptions);
|
|
2690
|
+
run(options: ConversationRunOptions): Promise<ConversationResult>;
|
|
2691
|
+
private isExitPhrase;
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
/**
|
|
2695
|
+
* Admin Zod schemas for dashboard and observability.
|
|
2696
|
+
*
|
|
2697
|
+
* Defines validated data shapes for agent statistics,
|
|
2698
|
+
* token usage, conversations, and trace data.
|
|
2699
|
+
*/
|
|
2700
|
+
|
|
2701
|
+
declare const TokenUsageRowSchema: z.ZodObject<{
|
|
2702
|
+
timestamp: z.ZodDate;
|
|
2703
|
+
inputTokens: z.ZodNumber;
|
|
2704
|
+
outputTokens: z.ZodNumber;
|
|
2705
|
+
totalTokens: z.ZodNumber;
|
|
2706
|
+
model: z.ZodString;
|
|
2707
|
+
agentName: z.ZodString;
|
|
2708
|
+
}, "strip", z.ZodTypeAny, {
|
|
2709
|
+
timestamp: Date;
|
|
2710
|
+
agentName: string;
|
|
2711
|
+
inputTokens: number;
|
|
2712
|
+
outputTokens: number;
|
|
2713
|
+
model: string;
|
|
2714
|
+
totalTokens: number;
|
|
2715
|
+
}, {
|
|
2716
|
+
timestamp: Date;
|
|
2717
|
+
agentName: string;
|
|
2718
|
+
inputTokens: number;
|
|
2719
|
+
outputTokens: number;
|
|
2720
|
+
model: string;
|
|
2721
|
+
totalTokens: number;
|
|
2722
|
+
}>;
|
|
2723
|
+
type TokenUsageRow = z.infer<typeof TokenUsageRowSchema>;
|
|
2724
|
+
declare const ToolStatsSchema: z.ZodObject<{
|
|
2725
|
+
toolName: z.ZodString;
|
|
2726
|
+
callCount: z.ZodNumber;
|
|
2727
|
+
errorCount: z.ZodNumber;
|
|
2728
|
+
totalDurationMs: z.ZodNumber;
|
|
2729
|
+
avgDurationMs: z.ZodNumber;
|
|
2730
|
+
lastUsed: z.ZodOptional<z.ZodDate>;
|
|
2731
|
+
}, "strip", z.ZodTypeAny, {
|
|
2732
|
+
toolName: string;
|
|
2733
|
+
callCount: number;
|
|
2734
|
+
errorCount: number;
|
|
2735
|
+
totalDurationMs: number;
|
|
2736
|
+
avgDurationMs: number;
|
|
2737
|
+
lastUsed?: Date | undefined;
|
|
2738
|
+
}, {
|
|
2739
|
+
toolName: string;
|
|
2740
|
+
callCount: number;
|
|
2741
|
+
errorCount: number;
|
|
2742
|
+
totalDurationMs: number;
|
|
2743
|
+
avgDurationMs: number;
|
|
2744
|
+
lastUsed?: Date | undefined;
|
|
2745
|
+
}>;
|
|
2746
|
+
type ToolStats = z.infer<typeof ToolStatsSchema>;
|
|
2747
|
+
declare const AgentStatsSchema: z.ZodObject<{
|
|
2748
|
+
agentName: z.ZodString;
|
|
2749
|
+
status: z.ZodEnum<["idle", "running", "error", "completed"]>;
|
|
2750
|
+
totalIterations: z.ZodNumber;
|
|
2751
|
+
totalToolCalls: z.ZodNumber;
|
|
2752
|
+
totalInputTokens: z.ZodNumber;
|
|
2753
|
+
totalOutputTokens: z.ZodNumber;
|
|
2754
|
+
totalErrors: z.ZodNumber;
|
|
2755
|
+
startedAt: z.ZodOptional<z.ZodDate>;
|
|
2756
|
+
lastEventAt: z.ZodOptional<z.ZodDate>;
|
|
2757
|
+
toolStats: z.ZodArray<z.ZodObject<{
|
|
2758
|
+
toolName: z.ZodString;
|
|
2759
|
+
callCount: z.ZodNumber;
|
|
2760
|
+
errorCount: z.ZodNumber;
|
|
2761
|
+
totalDurationMs: z.ZodNumber;
|
|
2762
|
+
avgDurationMs: z.ZodNumber;
|
|
2763
|
+
lastUsed: z.ZodOptional<z.ZodDate>;
|
|
2764
|
+
}, "strip", z.ZodTypeAny, {
|
|
2765
|
+
toolName: string;
|
|
2766
|
+
callCount: number;
|
|
2767
|
+
errorCount: number;
|
|
2768
|
+
totalDurationMs: number;
|
|
2769
|
+
avgDurationMs: number;
|
|
2770
|
+
lastUsed?: Date | undefined;
|
|
2771
|
+
}, {
|
|
2772
|
+
toolName: string;
|
|
2773
|
+
callCount: number;
|
|
2774
|
+
errorCount: number;
|
|
2775
|
+
totalDurationMs: number;
|
|
2776
|
+
avgDurationMs: number;
|
|
2777
|
+
lastUsed?: Date | undefined;
|
|
2778
|
+
}>, "many">;
|
|
2779
|
+
}, "strip", z.ZodTypeAny, {
|
|
2780
|
+
agentName: string;
|
|
2781
|
+
status: "completed" | "error" | "running" | "idle";
|
|
2782
|
+
totalInputTokens: number;
|
|
2783
|
+
totalOutputTokens: number;
|
|
2784
|
+
totalIterations: number;
|
|
2785
|
+
totalToolCalls: number;
|
|
2786
|
+
totalErrors: number;
|
|
2787
|
+
toolStats: {
|
|
2788
|
+
toolName: string;
|
|
2789
|
+
callCount: number;
|
|
2790
|
+
errorCount: number;
|
|
2791
|
+
totalDurationMs: number;
|
|
2792
|
+
avgDurationMs: number;
|
|
2793
|
+
lastUsed?: Date | undefined;
|
|
2794
|
+
}[];
|
|
2795
|
+
startedAt?: Date | undefined;
|
|
2796
|
+
lastEventAt?: Date | undefined;
|
|
2797
|
+
}, {
|
|
2798
|
+
agentName: string;
|
|
2799
|
+
status: "completed" | "error" | "running" | "idle";
|
|
2800
|
+
totalInputTokens: number;
|
|
2801
|
+
totalOutputTokens: number;
|
|
2802
|
+
totalIterations: number;
|
|
2803
|
+
totalToolCalls: number;
|
|
2804
|
+
totalErrors: number;
|
|
2805
|
+
toolStats: {
|
|
2806
|
+
toolName: string;
|
|
2807
|
+
callCount: number;
|
|
2808
|
+
errorCount: number;
|
|
2809
|
+
totalDurationMs: number;
|
|
2810
|
+
avgDurationMs: number;
|
|
2811
|
+
lastUsed?: Date | undefined;
|
|
2812
|
+
}[];
|
|
2813
|
+
startedAt?: Date | undefined;
|
|
2814
|
+
lastEventAt?: Date | undefined;
|
|
2815
|
+
}>;
|
|
2816
|
+
type AgentStats = z.infer<typeof AgentStatsSchema>;
|
|
2817
|
+
declare const DashboardStatsSchema: z.ZodObject<{
|
|
2818
|
+
agents: z.ZodArray<z.ZodObject<{
|
|
2819
|
+
agentName: z.ZodString;
|
|
2820
|
+
status: z.ZodEnum<["idle", "running", "error", "completed"]>;
|
|
2821
|
+
totalIterations: z.ZodNumber;
|
|
2822
|
+
totalToolCalls: z.ZodNumber;
|
|
2823
|
+
totalInputTokens: z.ZodNumber;
|
|
2824
|
+
totalOutputTokens: z.ZodNumber;
|
|
2825
|
+
totalErrors: z.ZodNumber;
|
|
2826
|
+
startedAt: z.ZodOptional<z.ZodDate>;
|
|
2827
|
+
lastEventAt: z.ZodOptional<z.ZodDate>;
|
|
2828
|
+
toolStats: z.ZodArray<z.ZodObject<{
|
|
2829
|
+
toolName: z.ZodString;
|
|
2830
|
+
callCount: z.ZodNumber;
|
|
2831
|
+
errorCount: z.ZodNumber;
|
|
2832
|
+
totalDurationMs: z.ZodNumber;
|
|
2833
|
+
avgDurationMs: z.ZodNumber;
|
|
2834
|
+
lastUsed: z.ZodOptional<z.ZodDate>;
|
|
2835
|
+
}, "strip", z.ZodTypeAny, {
|
|
2836
|
+
toolName: string;
|
|
2837
|
+
callCount: number;
|
|
2838
|
+
errorCount: number;
|
|
2839
|
+
totalDurationMs: number;
|
|
2840
|
+
avgDurationMs: number;
|
|
2841
|
+
lastUsed?: Date | undefined;
|
|
2842
|
+
}, {
|
|
2843
|
+
toolName: string;
|
|
2844
|
+
callCount: number;
|
|
2845
|
+
errorCount: number;
|
|
2846
|
+
totalDurationMs: number;
|
|
2847
|
+
avgDurationMs: number;
|
|
2848
|
+
lastUsed?: Date | undefined;
|
|
2849
|
+
}>, "many">;
|
|
2850
|
+
}, "strip", z.ZodTypeAny, {
|
|
2851
|
+
agentName: string;
|
|
2852
|
+
status: "completed" | "error" | "running" | "idle";
|
|
2853
|
+
totalInputTokens: number;
|
|
2854
|
+
totalOutputTokens: number;
|
|
2855
|
+
totalIterations: number;
|
|
2856
|
+
totalToolCalls: number;
|
|
2857
|
+
totalErrors: number;
|
|
2858
|
+
toolStats: {
|
|
2859
|
+
toolName: string;
|
|
2860
|
+
callCount: number;
|
|
2861
|
+
errorCount: number;
|
|
2862
|
+
totalDurationMs: number;
|
|
2863
|
+
avgDurationMs: number;
|
|
2864
|
+
lastUsed?: Date | undefined;
|
|
2865
|
+
}[];
|
|
2866
|
+
startedAt?: Date | undefined;
|
|
2867
|
+
lastEventAt?: Date | undefined;
|
|
2868
|
+
}, {
|
|
2869
|
+
agentName: string;
|
|
2870
|
+
status: "completed" | "error" | "running" | "idle";
|
|
2871
|
+
totalInputTokens: number;
|
|
2872
|
+
totalOutputTokens: number;
|
|
2873
|
+
totalIterations: number;
|
|
2874
|
+
totalToolCalls: number;
|
|
2875
|
+
totalErrors: number;
|
|
2876
|
+
toolStats: {
|
|
2877
|
+
toolName: string;
|
|
2878
|
+
callCount: number;
|
|
2879
|
+
errorCount: number;
|
|
2880
|
+
totalDurationMs: number;
|
|
2881
|
+
avgDurationMs: number;
|
|
2882
|
+
lastUsed?: Date | undefined;
|
|
2883
|
+
}[];
|
|
2884
|
+
startedAt?: Date | undefined;
|
|
2885
|
+
lastEventAt?: Date | undefined;
|
|
2886
|
+
}>, "many">;
|
|
2887
|
+
activeAgentCount: z.ZodNumber;
|
|
2888
|
+
totalTokensUsed: z.ZodNumber;
|
|
2889
|
+
totalToolCalls: z.ZodNumber;
|
|
2890
|
+
totalErrors: z.ZodNumber;
|
|
2891
|
+
activeConversationCount: z.ZodNumber;
|
|
2892
|
+
uptimeMs: z.ZodNumber;
|
|
2893
|
+
}, "strip", z.ZodTypeAny, {
|
|
2894
|
+
agents: {
|
|
2895
|
+
agentName: string;
|
|
2896
|
+
status: "completed" | "error" | "running" | "idle";
|
|
2897
|
+
totalInputTokens: number;
|
|
2898
|
+
totalOutputTokens: number;
|
|
2899
|
+
totalIterations: number;
|
|
2900
|
+
totalToolCalls: number;
|
|
2901
|
+
totalErrors: number;
|
|
2902
|
+
toolStats: {
|
|
2903
|
+
toolName: string;
|
|
2904
|
+
callCount: number;
|
|
2905
|
+
errorCount: number;
|
|
2906
|
+
totalDurationMs: number;
|
|
2907
|
+
avgDurationMs: number;
|
|
2908
|
+
lastUsed?: Date | undefined;
|
|
2909
|
+
}[];
|
|
2910
|
+
startedAt?: Date | undefined;
|
|
2911
|
+
lastEventAt?: Date | undefined;
|
|
2912
|
+
}[];
|
|
2913
|
+
totalToolCalls: number;
|
|
2914
|
+
totalErrors: number;
|
|
2915
|
+
activeAgentCount: number;
|
|
2916
|
+
totalTokensUsed: number;
|
|
2917
|
+
activeConversationCount: number;
|
|
2918
|
+
uptimeMs: number;
|
|
2919
|
+
}, {
|
|
2920
|
+
agents: {
|
|
2921
|
+
agentName: string;
|
|
2922
|
+
status: "completed" | "error" | "running" | "idle";
|
|
2923
|
+
totalInputTokens: number;
|
|
2924
|
+
totalOutputTokens: number;
|
|
2925
|
+
totalIterations: number;
|
|
2926
|
+
totalToolCalls: number;
|
|
2927
|
+
totalErrors: number;
|
|
2928
|
+
toolStats: {
|
|
2929
|
+
toolName: string;
|
|
2930
|
+
callCount: number;
|
|
2931
|
+
errorCount: number;
|
|
2932
|
+
totalDurationMs: number;
|
|
2933
|
+
avgDurationMs: number;
|
|
2934
|
+
lastUsed?: Date | undefined;
|
|
2935
|
+
}[];
|
|
2936
|
+
startedAt?: Date | undefined;
|
|
2937
|
+
lastEventAt?: Date | undefined;
|
|
2938
|
+
}[];
|
|
2939
|
+
totalToolCalls: number;
|
|
2940
|
+
totalErrors: number;
|
|
2941
|
+
activeAgentCount: number;
|
|
2942
|
+
totalTokensUsed: number;
|
|
2943
|
+
activeConversationCount: number;
|
|
2944
|
+
uptimeMs: number;
|
|
2945
|
+
}>;
|
|
2946
|
+
type DashboardStats = z.infer<typeof DashboardStatsSchema>;
|
|
2947
|
+
declare const ConversationSummarySchema: z.ZodObject<{
|
|
2948
|
+
conversationId: z.ZodString;
|
|
2949
|
+
agentName: z.ZodString;
|
|
2950
|
+
messageCount: z.ZodNumber;
|
|
2951
|
+
tokenCount: z.ZodNumber;
|
|
2952
|
+
startedAt: z.ZodDate;
|
|
2953
|
+
lastMessageAt: z.ZodOptional<z.ZodDate>;
|
|
2954
|
+
status: z.ZodEnum<["active", "completed", "error"]>;
|
|
2955
|
+
}, "strip", z.ZodTypeAny, {
|
|
2956
|
+
agentName: string;
|
|
2957
|
+
messageCount: number;
|
|
2958
|
+
conversationId: string;
|
|
2959
|
+
status: "completed" | "error" | "active";
|
|
2960
|
+
startedAt: Date;
|
|
2961
|
+
tokenCount: number;
|
|
2962
|
+
lastMessageAt?: Date | undefined;
|
|
2963
|
+
}, {
|
|
2964
|
+
agentName: string;
|
|
2965
|
+
messageCount: number;
|
|
2966
|
+
conversationId: string;
|
|
2967
|
+
status: "completed" | "error" | "active";
|
|
2968
|
+
startedAt: Date;
|
|
2969
|
+
tokenCount: number;
|
|
2970
|
+
lastMessageAt?: Date | undefined;
|
|
2971
|
+
}>;
|
|
2972
|
+
type ConversationSummary = z.infer<typeof ConversationSummarySchema>;
|
|
2973
|
+
declare const TraceEventSchema: z.ZodObject<{
|
|
2974
|
+
type: z.ZodString;
|
|
2975
|
+
timestamp: z.ZodDate;
|
|
2976
|
+
spanId: z.ZodString;
|
|
2977
|
+
parentSpanId: z.ZodOptional<z.ZodString>;
|
|
2978
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
2979
|
+
}, "strip", z.ZodTypeAny, {
|
|
2980
|
+
type: string;
|
|
2981
|
+
timestamp: Date;
|
|
2982
|
+
spanId: string;
|
|
2983
|
+
data: Record<string, unknown>;
|
|
2984
|
+
parentSpanId?: string | undefined;
|
|
2985
|
+
}, {
|
|
2986
|
+
type: string;
|
|
2987
|
+
timestamp: Date;
|
|
2988
|
+
spanId: string;
|
|
2989
|
+
data: Record<string, unknown>;
|
|
2990
|
+
parentSpanId?: string | undefined;
|
|
2991
|
+
}>;
|
|
2992
|
+
type TraceEvent = z.infer<typeof TraceEventSchema>;
|
|
2993
|
+
declare const TraceIterationSchema: z.ZodObject<{
|
|
2994
|
+
iteration: z.ZodNumber;
|
|
2995
|
+
events: z.ZodArray<z.ZodObject<{
|
|
2996
|
+
type: z.ZodString;
|
|
2997
|
+
timestamp: z.ZodDate;
|
|
2998
|
+
spanId: z.ZodString;
|
|
2999
|
+
parentSpanId: z.ZodOptional<z.ZodString>;
|
|
3000
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
3001
|
+
}, "strip", z.ZodTypeAny, {
|
|
3002
|
+
type: string;
|
|
3003
|
+
timestamp: Date;
|
|
3004
|
+
spanId: string;
|
|
3005
|
+
data: Record<string, unknown>;
|
|
3006
|
+
parentSpanId?: string | undefined;
|
|
3007
|
+
}, {
|
|
3008
|
+
type: string;
|
|
3009
|
+
timestamp: Date;
|
|
3010
|
+
spanId: string;
|
|
3011
|
+
data: Record<string, unknown>;
|
|
3012
|
+
parentSpanId?: string | undefined;
|
|
3013
|
+
}>, "many">;
|
|
3014
|
+
toolCalls: z.ZodNumber;
|
|
3015
|
+
inputTokens: z.ZodNumber;
|
|
3016
|
+
outputTokens: z.ZodNumber;
|
|
3017
|
+
}, "strip", z.ZodTypeAny, {
|
|
3018
|
+
inputTokens: number;
|
|
3019
|
+
outputTokens: number;
|
|
3020
|
+
iteration: number;
|
|
3021
|
+
toolCalls: number;
|
|
3022
|
+
events: {
|
|
3023
|
+
type: string;
|
|
3024
|
+
timestamp: Date;
|
|
3025
|
+
spanId: string;
|
|
3026
|
+
data: Record<string, unknown>;
|
|
3027
|
+
parentSpanId?: string | undefined;
|
|
3028
|
+
}[];
|
|
3029
|
+
}, {
|
|
3030
|
+
inputTokens: number;
|
|
3031
|
+
outputTokens: number;
|
|
3032
|
+
iteration: number;
|
|
3033
|
+
toolCalls: number;
|
|
3034
|
+
events: {
|
|
3035
|
+
type: string;
|
|
3036
|
+
timestamp: Date;
|
|
3037
|
+
spanId: string;
|
|
3038
|
+
data: Record<string, unknown>;
|
|
3039
|
+
parentSpanId?: string | undefined;
|
|
3040
|
+
}[];
|
|
3041
|
+
}>;
|
|
3042
|
+
type TraceIteration = z.infer<typeof TraceIterationSchema>;
|
|
3043
|
+
declare const TraceResponseSchema: z.ZodObject<{
|
|
3044
|
+
traceId: z.ZodString;
|
|
3045
|
+
agentName: z.ZodString;
|
|
3046
|
+
iterations: z.ZodArray<z.ZodObject<{
|
|
3047
|
+
iteration: z.ZodNumber;
|
|
3048
|
+
events: z.ZodArray<z.ZodObject<{
|
|
3049
|
+
type: z.ZodString;
|
|
3050
|
+
timestamp: z.ZodDate;
|
|
3051
|
+
spanId: z.ZodString;
|
|
3052
|
+
parentSpanId: z.ZodOptional<z.ZodString>;
|
|
3053
|
+
data: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
3054
|
+
}, "strip", z.ZodTypeAny, {
|
|
3055
|
+
type: string;
|
|
3056
|
+
timestamp: Date;
|
|
3057
|
+
spanId: string;
|
|
3058
|
+
data: Record<string, unknown>;
|
|
3059
|
+
parentSpanId?: string | undefined;
|
|
3060
|
+
}, {
|
|
3061
|
+
type: string;
|
|
3062
|
+
timestamp: Date;
|
|
3063
|
+
spanId: string;
|
|
3064
|
+
data: Record<string, unknown>;
|
|
3065
|
+
parentSpanId?: string | undefined;
|
|
3066
|
+
}>, "many">;
|
|
3067
|
+
toolCalls: z.ZodNumber;
|
|
3068
|
+
inputTokens: z.ZodNumber;
|
|
3069
|
+
outputTokens: z.ZodNumber;
|
|
3070
|
+
}, "strip", z.ZodTypeAny, {
|
|
3071
|
+
inputTokens: number;
|
|
3072
|
+
outputTokens: number;
|
|
3073
|
+
iteration: number;
|
|
3074
|
+
toolCalls: number;
|
|
3075
|
+
events: {
|
|
3076
|
+
type: string;
|
|
3077
|
+
timestamp: Date;
|
|
3078
|
+
spanId: string;
|
|
3079
|
+
data: Record<string, unknown>;
|
|
3080
|
+
parentSpanId?: string | undefined;
|
|
3081
|
+
}[];
|
|
3082
|
+
}, {
|
|
3083
|
+
inputTokens: number;
|
|
3084
|
+
outputTokens: number;
|
|
3085
|
+
iteration: number;
|
|
3086
|
+
toolCalls: number;
|
|
3087
|
+
events: {
|
|
3088
|
+
type: string;
|
|
3089
|
+
timestamp: Date;
|
|
3090
|
+
spanId: string;
|
|
3091
|
+
data: Record<string, unknown>;
|
|
3092
|
+
parentSpanId?: string | undefined;
|
|
3093
|
+
}[];
|
|
3094
|
+
}>, "many">;
|
|
3095
|
+
totalDurationMs: z.ZodNumber;
|
|
3096
|
+
status: z.ZodEnum<["running", "completed", "error"]>;
|
|
3097
|
+
}, "strip", z.ZodTypeAny, {
|
|
3098
|
+
traceId: string;
|
|
3099
|
+
agentName: string;
|
|
3100
|
+
status: "completed" | "error" | "running";
|
|
3101
|
+
iterations: {
|
|
3102
|
+
inputTokens: number;
|
|
3103
|
+
outputTokens: number;
|
|
3104
|
+
iteration: number;
|
|
3105
|
+
toolCalls: number;
|
|
3106
|
+
events: {
|
|
3107
|
+
type: string;
|
|
3108
|
+
timestamp: Date;
|
|
3109
|
+
spanId: string;
|
|
3110
|
+
data: Record<string, unknown>;
|
|
3111
|
+
parentSpanId?: string | undefined;
|
|
3112
|
+
}[];
|
|
3113
|
+
}[];
|
|
3114
|
+
totalDurationMs: number;
|
|
3115
|
+
}, {
|
|
3116
|
+
traceId: string;
|
|
3117
|
+
agentName: string;
|
|
3118
|
+
status: "completed" | "error" | "running";
|
|
3119
|
+
iterations: {
|
|
3120
|
+
inputTokens: number;
|
|
3121
|
+
outputTokens: number;
|
|
3122
|
+
iteration: number;
|
|
3123
|
+
toolCalls: number;
|
|
3124
|
+
events: {
|
|
3125
|
+
type: string;
|
|
3126
|
+
timestamp: Date;
|
|
3127
|
+
spanId: string;
|
|
3128
|
+
data: Record<string, unknown>;
|
|
3129
|
+
parentSpanId?: string | undefined;
|
|
3130
|
+
}[];
|
|
3131
|
+
}[];
|
|
3132
|
+
totalDurationMs: number;
|
|
3133
|
+
}>;
|
|
3134
|
+
type TraceResponse = z.infer<typeof TraceResponseSchema>;
|
|
3135
|
+
declare const TraceSummarySchema: z.ZodObject<{
|
|
3136
|
+
traceId: z.ZodString;
|
|
3137
|
+
agentName: z.ZodString;
|
|
3138
|
+
startedAt: z.ZodDate;
|
|
3139
|
+
durationMs: z.ZodOptional<z.ZodNumber>;
|
|
3140
|
+
status: z.ZodEnum<["running", "completed", "error"]>;
|
|
3141
|
+
iterationCount: z.ZodNumber;
|
|
3142
|
+
totalTokens: z.ZodNumber;
|
|
3143
|
+
}, "strip", z.ZodTypeAny, {
|
|
3144
|
+
traceId: string;
|
|
3145
|
+
agentName: string;
|
|
3146
|
+
status: "completed" | "error" | "running";
|
|
3147
|
+
totalTokens: number;
|
|
3148
|
+
startedAt: Date;
|
|
3149
|
+
iterationCount: number;
|
|
3150
|
+
durationMs?: number | undefined;
|
|
3151
|
+
}, {
|
|
3152
|
+
traceId: string;
|
|
3153
|
+
agentName: string;
|
|
3154
|
+
status: "completed" | "error" | "running";
|
|
3155
|
+
totalTokens: number;
|
|
3156
|
+
startedAt: Date;
|
|
3157
|
+
iterationCount: number;
|
|
3158
|
+
durationMs?: number | undefined;
|
|
3159
|
+
}>;
|
|
3160
|
+
type TraceSummary = z.infer<typeof TraceSummarySchema>;
|
|
3161
|
+
declare const DateFiltersSchema: z.ZodObject<{
|
|
3162
|
+
from: z.ZodOptional<z.ZodDate>;
|
|
3163
|
+
to: z.ZodOptional<z.ZodDate>;
|
|
3164
|
+
}, "strip", z.ZodTypeAny, {
|
|
3165
|
+
to?: Date | undefined;
|
|
3166
|
+
from?: Date | undefined;
|
|
3167
|
+
}, {
|
|
3168
|
+
to?: Date | undefined;
|
|
3169
|
+
from?: Date | undefined;
|
|
3170
|
+
}>;
|
|
3171
|
+
type DateFilters = z.infer<typeof DateFiltersSchema>;
|
|
3172
|
+
declare const ToolAnalyticsSchema: z.ZodObject<{
|
|
3173
|
+
toolName: z.ZodString;
|
|
3174
|
+
totalCalls: z.ZodNumber;
|
|
3175
|
+
totalErrors: z.ZodNumber;
|
|
3176
|
+
totalDurationMs: z.ZodNumber;
|
|
3177
|
+
avgDurationMs: z.ZodNumber;
|
|
3178
|
+
agentBreakdown: z.ZodArray<z.ZodObject<{
|
|
3179
|
+
agentName: z.ZodString;
|
|
3180
|
+
callCount: z.ZodNumber;
|
|
3181
|
+
}, "strip", z.ZodTypeAny, {
|
|
3182
|
+
agentName: string;
|
|
3183
|
+
callCount: number;
|
|
3184
|
+
}, {
|
|
3185
|
+
agentName: string;
|
|
3186
|
+
callCount: number;
|
|
3187
|
+
}>, "many">;
|
|
3188
|
+
}, "strip", z.ZodTypeAny, {
|
|
3189
|
+
toolName: string;
|
|
3190
|
+
totalDurationMs: number;
|
|
3191
|
+
avgDurationMs: number;
|
|
3192
|
+
totalErrors: number;
|
|
3193
|
+
totalCalls: number;
|
|
3194
|
+
agentBreakdown: {
|
|
3195
|
+
agentName: string;
|
|
3196
|
+
callCount: number;
|
|
3197
|
+
}[];
|
|
3198
|
+
}, {
|
|
3199
|
+
toolName: string;
|
|
3200
|
+
totalDurationMs: number;
|
|
3201
|
+
avgDurationMs: number;
|
|
3202
|
+
totalErrors: number;
|
|
3203
|
+
totalCalls: number;
|
|
3204
|
+
agentBreakdown: {
|
|
3205
|
+
agentName: string;
|
|
3206
|
+
callCount: number;
|
|
3207
|
+
}[];
|
|
3208
|
+
}>;
|
|
3209
|
+
type ToolAnalytics = z.infer<typeof ToolAnalyticsSchema>;
|
|
3210
|
+
declare const TokenUsageGroupSchema: z.ZodObject<{
|
|
3211
|
+
key: z.ZodString;
|
|
3212
|
+
inputTokens: z.ZodNumber;
|
|
3213
|
+
outputTokens: z.ZodNumber;
|
|
3214
|
+
totalTokens: z.ZodNumber;
|
|
3215
|
+
conversationCount: z.ZodNumber;
|
|
3216
|
+
}, "strip", z.ZodTypeAny, {
|
|
3217
|
+
inputTokens: number;
|
|
3218
|
+
outputTokens: number;
|
|
3219
|
+
key: string;
|
|
3220
|
+
totalTokens: number;
|
|
3221
|
+
conversationCount: number;
|
|
3222
|
+
}, {
|
|
3223
|
+
inputTokens: number;
|
|
3224
|
+
outputTokens: number;
|
|
3225
|
+
key: string;
|
|
3226
|
+
totalTokens: number;
|
|
3227
|
+
conversationCount: number;
|
|
3228
|
+
}>;
|
|
3229
|
+
type TokenUsageGroup = z.infer<typeof TokenUsageGroupSchema>;
|
|
3230
|
+
|
|
3231
|
+
/**
|
|
3232
|
+
* In-memory event collector for admin observability.
|
|
3233
|
+
*
|
|
3234
|
+
* Extends BaseExporter to subscribe to agent events and maintain
|
|
3235
|
+
* live statistics, ring-buffered recent events, and per-agent state.
|
|
3236
|
+
*/
|
|
3237
|
+
|
|
3238
|
+
/**
|
|
3239
|
+
* Collects agent events in memory for admin dashboard queries.
|
|
3240
|
+
*
|
|
3241
|
+
* Subscribes to the UX event profile and maintains:
|
|
3242
|
+
* - Per-agent statistics (iterations, tokens, tool calls, errors)
|
|
3243
|
+
* - Per-tool statistics (call count, duration, errors)
|
|
3244
|
+
* - Ring buffer of recent trace events (capped at 1000)
|
|
3245
|
+
* - Trace summaries by traceId
|
|
3246
|
+
* - Token usage by model
|
|
3247
|
+
* - Active conversation tracking
|
|
3248
|
+
*/
|
|
3249
|
+
declare class InMemoryEventCollector extends BaseExporter {
|
|
3250
|
+
profile: "ux";
|
|
3251
|
+
private _startedAt;
|
|
3252
|
+
private _agents;
|
|
3253
|
+
private _recentEvents;
|
|
3254
|
+
/** Bounded log of individual tool calls, used for date-filtered analytics. */
|
|
3255
|
+
private _toolCallLog;
|
|
3256
|
+
private _traces;
|
|
3257
|
+
private _tokensByModel;
|
|
3258
|
+
private _activeConversations;
|
|
3259
|
+
/** Get dashboard-level aggregate statistics. */
|
|
3260
|
+
getDashboardStats(): DashboardStats;
|
|
3261
|
+
/** Get statistics for a specific agent. */
|
|
3262
|
+
getAgentStats(agentName: string): AgentStats | undefined;
|
|
3263
|
+
/** Get all agent statistics. */
|
|
3264
|
+
getAllAgentStats(): AgentStats[];
|
|
3265
|
+
/** Get recent trace events from the ring buffer. */
|
|
3266
|
+
getRecentEvents(limit?: number): TraceEvent[];
|
|
3267
|
+
/** Get all trace summaries. */
|
|
3268
|
+
getTraceSummaries(): TraceSummary[];
|
|
3269
|
+
/** Get conversations (derived from traces). */
|
|
3270
|
+
getConversations(): ConversationSummary[];
|
|
3271
|
+
/**
|
|
3272
|
+
* Get cross-agent tool analytics.
|
|
3273
|
+
*
|
|
3274
|
+
* When `filters` specify a date range, aggregation runs over the
|
|
3275
|
+
* per-call log (bounded to the most recent 10,000 calls). Without
|
|
3276
|
+
* filters, uses the lifetime aggregates on each agent.
|
|
3277
|
+
*/
|
|
3278
|
+
getToolAnalytics(filters?: DateFilters): ToolAnalytics[];
|
|
3279
|
+
/** Get token usage grouped by agent or model. */
|
|
3280
|
+
getTokenUsage(params: {
|
|
3281
|
+
groupBy: "agent" | "model";
|
|
3282
|
+
}): TokenUsageGroup[];
|
|
3283
|
+
handleEvent(event: BaseEvent): Promise<void>;
|
|
3284
|
+
/** @internal */
|
|
3285
|
+
_onConversationStart(event: ConversationStartEvent): Promise<void>;
|
|
3286
|
+
/** @internal */
|
|
3287
|
+
_onConversationEnd(event: ConversationEndEvent): Promise<void>;
|
|
3288
|
+
/** @internal */
|
|
3289
|
+
_onMessageStart(event: MessageStartEvent): Promise<void>;
|
|
3290
|
+
/** @internal */
|
|
3291
|
+
_onMessageComplete(event: MessageCompleteEvent): Promise<void>;
|
|
3292
|
+
/** @internal */
|
|
3293
|
+
_onMessageCancel(event: MessageCancelEvent): Promise<void>;
|
|
3294
|
+
/** @internal */
|
|
3295
|
+
_onIterationStart(event: IterationStartEvent): Promise<void>;
|
|
3296
|
+
/** @internal */
|
|
3297
|
+
_onIterationEnd(event: IterationEndEvent): Promise<void>;
|
|
3298
|
+
/** @internal */
|
|
3299
|
+
_onToolStart(event: ToolCallStartEvent): Promise<void>;
|
|
3300
|
+
/** @internal */
|
|
3301
|
+
_onToolEnd(event: ToolCallEndEvent): Promise<void>;
|
|
3302
|
+
/** @internal */
|
|
3303
|
+
_onLlmEnd(event: LLMCallEndEvent): Promise<void>;
|
|
3304
|
+
/** @internal */
|
|
3305
|
+
_onError(event: ErrorEvent): Promise<void>;
|
|
3306
|
+
private _ensureAgent;
|
|
3307
|
+
private _recordEvent;
|
|
3308
|
+
private _toAgentStats;
|
|
3309
|
+
private _getAgentStatsList;
|
|
3310
|
+
private _getToolAnalyticsFromLog;
|
|
3311
|
+
}
|
|
3312
|
+
|
|
3313
|
+
/**
|
|
3314
|
+
* Admin service protocol and in-memory implementation.
|
|
3315
|
+
*
|
|
3316
|
+
* AdminServiceProtocol defines the async interface for admin queries.
|
|
3317
|
+
* InMemoryAdminService delegates to an InMemoryEventCollector.
|
|
3318
|
+
*/
|
|
3319
|
+
|
|
3320
|
+
/** Async interface for admin dashboard queries. */
|
|
3321
|
+
interface AdminServiceProtocol {
|
|
3322
|
+
getDashboardStats(): Promise<DashboardStats>;
|
|
3323
|
+
getAgentStats(agentName: string): Promise<AgentStats | undefined>;
|
|
3324
|
+
getAllAgentStats(): Promise<AgentStats[]>;
|
|
3325
|
+
getRecentEvents(limit?: number): Promise<TraceEvent[]>;
|
|
3326
|
+
getTraceSummaries(): Promise<TraceSummary[]>;
|
|
3327
|
+
getConversations(): Promise<ConversationSummary[]>;
|
|
3328
|
+
getToolAnalytics(filters?: DateFilters): Promise<ToolAnalytics[]>;
|
|
3329
|
+
getTokenUsage(params: {
|
|
3330
|
+
groupBy: "agent" | "model";
|
|
3331
|
+
}): Promise<TokenUsageGroup[]>;
|
|
3332
|
+
}
|
|
3333
|
+
/**
|
|
3334
|
+
* In-memory admin service backed by an InMemoryEventCollector.
|
|
3335
|
+
*
|
|
3336
|
+
* All methods delegate directly to the collector's synchronous query
|
|
3337
|
+
* methods, wrapped in Promise resolution for protocol compliance.
|
|
3338
|
+
*/
|
|
3339
|
+
declare class InMemoryAdminService implements AdminServiceProtocol {
|
|
3340
|
+
private _collector;
|
|
3341
|
+
constructor(collector: InMemoryEventCollector);
|
|
3342
|
+
getDashboardStats(): Promise<DashboardStats>;
|
|
3343
|
+
getAgentStats(agentName: string): Promise<AgentStats | undefined>;
|
|
3344
|
+
getAllAgentStats(): Promise<AgentStats[]>;
|
|
3345
|
+
getRecentEvents(limit?: number): Promise<TraceEvent[]>;
|
|
3346
|
+
getTraceSummaries(): Promise<TraceSummary[]>;
|
|
3347
|
+
getConversations(): Promise<ConversationSummary[]>;
|
|
3348
|
+
getToolAnalytics(filters?: DateFilters): Promise<ToolAnalytics[]>;
|
|
3349
|
+
getTokenUsage(params: {
|
|
3350
|
+
groupBy: "agent" | "model";
|
|
3351
|
+
}): Promise<TokenUsageGroup[]>;
|
|
3352
|
+
}
|
|
3353
|
+
|
|
3354
|
+
/**
|
|
3355
|
+
* StdioAdapter — JSON-RPC 2.0 over stdin/stdout for subprocess mode.
|
|
3356
|
+
*
|
|
3357
|
+
* Handles methods: listAgents, createConversation, sendMessage,
|
|
3358
|
+
* listConversations, getConversation. Uses SSEFormatter.extractPayload()
|
|
3359
|
+
* for event data in stream.event notifications.
|
|
3360
|
+
*/
|
|
3361
|
+
|
|
3362
|
+
interface JSONRPCRequest {
|
|
3363
|
+
jsonrpc: "2.0";
|
|
3364
|
+
id?: number | string;
|
|
3365
|
+
method: string;
|
|
3366
|
+
params?: Record<string, unknown>;
|
|
3367
|
+
}
|
|
3368
|
+
interface JSONRPCResponse {
|
|
3369
|
+
jsonrpc: "2.0";
|
|
3370
|
+
id: number | string | null;
|
|
3371
|
+
result?: unknown;
|
|
3372
|
+
error?: {
|
|
3373
|
+
code: number;
|
|
3374
|
+
message: string;
|
|
3375
|
+
data?: unknown;
|
|
3376
|
+
};
|
|
3377
|
+
}
|
|
3378
|
+
interface JSONRPCNotification {
|
|
3379
|
+
jsonrpc: "2.0";
|
|
3380
|
+
method: string;
|
|
3381
|
+
params: unknown;
|
|
3382
|
+
}
|
|
3383
|
+
type NotificationCallback = (notification: JSONRPCNotification) => void;
|
|
3384
|
+
declare class StdioAdapter {
|
|
3385
|
+
private _agents;
|
|
3386
|
+
private _agentMap;
|
|
3387
|
+
private _runner;
|
|
3388
|
+
private _store;
|
|
3389
|
+
private _conversations;
|
|
3390
|
+
constructor(opts: {
|
|
3391
|
+
agents: AgentLike[];
|
|
3392
|
+
runner: RunnerProtocol;
|
|
3393
|
+
store?: ConversationStoreProtocol;
|
|
3394
|
+
});
|
|
3395
|
+
/** Start reading JSON-RPC from stdin, writing to stdout. */
|
|
3396
|
+
start(): Promise<void>;
|
|
3397
|
+
/** Handle a single JSON-RPC request. Testable without stdin/stdout. */
|
|
3398
|
+
handleRequest(request: JSONRPCRequest, onNotification?: NotificationCallback): Promise<JSONRPCResponse>;
|
|
3399
|
+
private _listAgents;
|
|
3400
|
+
private _createConversation;
|
|
3401
|
+
private _sendMessage;
|
|
3402
|
+
private _listConversations;
|
|
3403
|
+
private _getConversation;
|
|
3404
|
+
}
|
|
3405
|
+
|
|
3406
|
+
export { ANALYSIS, type AdminServiceProtocol, AgencyRuntime, type AgentAddress, type AgentBroadcastEvent, type AgentEvent, AgentEventBus, type AgentEventType, type AgentJoinEvent, type AgentLeaveEvent, type AgentLike, type AgentLikeForBridge, type AgentMessageEvent, AgentNode, type AgentNodeOptions, AgentRunner, type AgentStats, AgentStatsSchema, type ApprovalCallback, AuditGate, type AuditLogger, BATCH_WINDOW, type BackoffStrategy, type BaseEvent, BaseExporter, BaseGate, type BaseSandboxEvent, CLAUDE_CODE_HOOK_EVENTS, CalculatorToolbox, type CanonicalMessage, type CanonicalMessagePart, ClaudeCodeAPIRunner, type ClaudeCodeHookEvent, type ClaudeCodeHookName, ClaudeCodeLanguageModel, type ClaudeCodeProviderOptions, ClaudeCodeRunner, type ClaudeCodeRunnerOptions, CompositeRefinementEvaluator, ConsoleExporter, type ConsoleLogger, type Consolidator, Conversation, type ConversationEndEvent, type ConversationExitReason, ConversationLoop, type ConversationLoopOptions, type ConversationResult, type ConversationRunOptions, type ConversationStartEvent, type ConversationStoreProtocol, type ConversationSummary, ConversationSummarySchema, type CreateRunnerOptions, DEFAULT_GLOBAL_TIMEOUT, DEFAULT_IDLE_TIMEOUT, DEFAULT_MAX_TURNS, type DashboardStats, DashboardStatsSchema, type DateFilters, DateFiltersSchema, EVIDENCE_QUALITY, type ErrorEvent, EvaluatorChain, EvaluatorLoop, type EvaluatorLoopOptions, type EvaluatorRunOptions, EventBus, type EventHandlerFn, EventProfile, type Exchange, ExponentialBackoff, type Exporter, FixedBackoff, GATE_CATEGORY_NAMES, type Gate, GateAllow, GateBlock, GateCategory, GateModify, type GateResult, type GoalEvaluationResult, type GoalEvaluatorProtocol, type HealthPingEvent, type HealthPongEvent, HumanApprovalGate, INFORMATION_RETRIEVAL, INTENT_CLASSIFICATION, INTENT_ROUTING, InMemoryAdminService, InMemoryEventCollector, InProcessTransport, type IterationEndEvent, type IterationStartEvent, JitteredBackoff, type LLMCallEndEvent, type LLMCallStartEvent, LLMGoalEvaluator, type LLMGoalEvaluatorOptions, LLMRefinementEvaluator, type LLMRefinementEvaluatorOptions, type LangfuseClient, LangfuseExporter, type LangfuseObservation, type LangfuseSpan, MemoryStore, type MessageCancelEvent, type MessageChunkEvent, type MessageCompleteEvent, type MessageStartEvent, type MessageTemplate, MessagingToolbox, type MiddlewareFn, type MockCall, type MockResponse, MockRunner, type NodeLifecycleEvent, ORCHESTRATION, OTelExporter, type OTelSpan, OTelStatusCode, type OTelTracer, PROFILE_EVENT_TYPES, PROVIDERS, PROVIDER_PRIORITY, Parallel, type ParallelOptions, type ParallelResult, type PatternCompleteEvent, type PatternContext, type PatternEvent, type PatternHooks, type PatternIterationCompleteEvent, type PatternIterationStartEvent, type PatternProtocol, type PatternResult, type PatternRunOptions, type PatternStartEvent, type PatternStepCompleteEvent, type PatternStepErrorEvent, type PatternStepStartEvent, type ProviderProtocol, type ProviderTier, QUALITY_GATE, QUALITY_REVIEW, RESPONSE_SYNTHESIS, RETRIEVAL_STRATEGY, ROUTING, RateLimitGate, type ReasoningEvent, type Refinement, type RefinementEvaluator, type RefinementExitReason, type RefinementResult, type RetryExitReason, RetryLoop, type RetryLoopOptions, type RetryResult, type RetryRunOptions, type RubricCriterion, RubricEvaluator, type RunOptions, type RunResult, type RunnerProtocol, type RunnerSelection, type RunnerSource, type SSEEventName, SSEExporter, SSEFormatter, type SSEMapping, SSE_EVENT_NAMES, SafetyGate, type SandboxEvent, SandboxEventBus, type SandboxEventType, SelfEvalGoalEvaluator, Sequential, type SequentialOptions, type SequentialResult, SimpleGoalEvaluator, type SimpleGoalEvaluatorOptions, StdioAdapter, type Step, type StepResult, type StoredConversation, type StoredMessage, type StoredMessagePart, type StreamEvent, type SupportedProvider, type TaskAssignEvent, type TaskCreateEvent, type TaskExitReason, TaskLoop, type TaskLoopOptions, type TaskResult, type TaskRunOptions, type TaskState, type TaskUpdateEvent, type ThinkingStartEvent, TodoToolbox, type TokenUsageGroup, TokenUsageGroupSchema, type TokenUsageRow, TokenUsageRowSchema, type ToolAnalytics, ToolAnalyticsSchema, ToolCallBlocked, type ToolCallEndEvent, type ToolCallIntent, type ToolCallRecord, type ToolCallRejectedEvent, type ToolCallStartEvent, type ToolExecutor, type ToolProgressEvent, type ToolStats, ToolStatsSchema, type TraceEvent, TraceEventSchema, type TraceIteration, TraceIterationSchema, type TraceResponse, TraceResponseSchema, type TraceSummary, TraceSummarySchema, type Transport, type TransportMessage, type WeightedEvaluator, agentAddressToString, analystRole, anthropicProvider, buildAgentServers, buildCalculatorAgent, buildCapabilityServer, buildTodoAgent, buildWritingCoachAgent, claudeCode, collectByName, collectContents, convertHistory, coordinatorRole, createAgentAddress, createConsoleExporter, createEvent, createRunner, createStepResult, createToolboxExecutor, deepseekProvider, deserializeSandboxEvent, deserializeSandboxEventFromString, exchangeTotalTokens, executeStep, formatSSE, getAgentEventBus, getEventBus, googleProvider, groqProvider, isClaudeCodeHookName, makeStepName, mapClaudeCodeHookToAgentEvents, matchSubject, mistralProvider, ollamaProvider, openaiProvider, openrouterProvider, orchestratorRole, resolveMessage, resolveModelId, retrievalRole, serializeSandboxEvent, serializeSandboxEventToString, setAgentEventBus, setEventBus, subjectToRegex, subscribeProfile, subscribeProfiles, toSSEMapping, unsubscribeProfile, xaiProvider };
|