forked from Lilly-Protocol/agentlily-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction-executor.ts
More file actions
73 lines (62 loc) · 2.21 KB
/
Copy pathaction-executor.ts
File metadata and controls
73 lines (62 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import type { RuntimeEventBus } from "../events/runtime-events.js";
import { assertMaxToolCalls } from "../guards/runtime-guards.js";
import type { RuntimeLogger } from "../logger/runtime-logger.js";
import type { RuntimeContext } from "../runtime/context.js";
import { ToolRegistry } from "../tools/tool-registry.js";
function resolveAgentId(
agent: { agentId?: string; id?: string } | undefined
): string {
return agent?.agentId ?? agent?.id ?? "";
}
export class ActionExecutor {
private readonly toolCallCounts = new Map<string, number>();
private readonly logger: RuntimeLogger | undefined;
private readonly eventBus: RuntimeEventBus | undefined;
private readonly maxToolCallsPerTask: number | undefined;
public constructor(
private readonly toolRegistry: ToolRegistry,
maxToolCallsPerTaskOrLogger?: number | RuntimeLogger,
eventBus?: RuntimeEventBus
) {
if (typeof maxToolCallsPerTaskOrLogger === "number") {
this.maxToolCallsPerTask = maxToolCallsPerTaskOrLogger;
this.logger = undefined;
} else {
this.logger = maxToolCallsPerTaskOrLogger;
}
this.eventBus = eventBus;
}
public getToolCallCount(taskId: string): number {
return this.toolCallCounts.get(taskId) ?? 0;
}
public async execute<TPayload, TResult>(
toolName: string,
payload: TPayload,
context: RuntimeContext
): Promise<TResult> {
const currentCount = this.getToolCallCount(context.taskId);
if (this.maxToolCallsPerTask !== undefined) {
assertMaxToolCalls(currentCount, this.maxToolCallsPerTask);
}
this.toolCallCounts.set(context.taskId, currentCount + 1);
const tool = this.toolRegistry.get(toolName);
const startedAt = Date.now();
this.eventBus?.emit({
name: "runtime.tool.invoked",
payload: {
runtimeId: context.runtimeId,
taskId: context.taskId,
agentId: resolveAgentId(context.agent),
toolName,
invokedAt: new Date().toISOString()
}
});
const result = (await tool.execute({
payload,
context
})) as TResult;
const durationMs = Math.max(0, Date.now() - startedAt);
this.logger?.info("Tool invocation completed.", { toolName, durationMs });
return result;
}
}