Files
lolympus-agent/src/agent/agent.ts
T

186 lines
5.7 KiB
TypeScript

import type { Msg } from "nats";
import type { ConversationStore } from "@conv/conversation-store";
import type { NatsClient } from "@common/nats";
import { getRequestLogger, runWithContext } from "@obs/context";
import { getLogger } from "@obs/logger";
import { withSkillSpan, withSpan } from "@obs/spans";
import type { Skill } from "@skills/skill";
import type { AgentRequest, AgentResponse } from "./types.js";
import { getRequestSubject } from "../config.js";
function isValidRequest(data: unknown): data is AgentRequest {
if (typeof data !== "object" || data === null) return false;
const obj = data as Record<string, unknown>;
return (
typeof obj["requestId"] === "string" &&
typeof obj["skill"] === "string" &&
typeof obj["chatroomId"] === "string" &&
typeof obj["userId"] === "string" &&
typeof obj["nickname"] === "string" &&
typeof obj["trigger"] === "string"
);
}
export class Agent {
private readonly skills: Skill[] = [];
private readonly logger = getLogger();
constructor(
private readonly natsClient: NatsClient,
private readonly conversationStore: ConversationStore,
) {}
registerSkill(skill: Skill): void {
this.skills.push(skill);
this.logger.info({ skill: skill.name }, "✓ Skill registered");
}
async start(): Promise<void> {
const subject = getRequestSubject();
await this.natsClient.subscribeRaw(subject, async (msg: Msg) => {
await this.handleRequest(msg);
});
this.logger.info({ subject }, "✓ Agent listening on subject");
}
private async handleRequest(msg: Msg): Promise<void> {
let request: AgentRequest;
try {
const raw = JSON.parse(
new TextDecoder().decode(msg.data),
) as unknown;
if (!isValidRequest(raw)) {
this.logger.warn("[Agent] Invalid request received, skipping");
return;
}
request = raw;
} catch {
this.logger.warn("[Agent] Failed to parse request, skipping");
return;
}
await runWithContext(
{
chatroomId: request.chatroomId,
requestId: request.requestId,
skill: request.skill,
startedAt: new Date().toISOString(),
trigger: request.trigger,
userId: request.userId,
},
async () => {
const logger = getRequestLogger();
await withSpan(
"agent.handle",
{
"agent.chatroom_id": request.chatroomId,
"agent.request_id": request.requestId,
"agent.skill": request.skill,
"agent.trigger": request.trigger,
"agent.user_id": request.userId,
},
async (rootSpan) => {
logger.info(
{
nickname: request.nickname,
},
"[Agent] Request received",
);
const skill = this.skills.find((candidate) => candidate.canHandle(request));
if (!skill) {
logger.info("[Agent] No skill found for request");
const response: AgentResponse = {
requestId: request.requestId,
text: "",
confidence: 0,
source: "template",
};
rootSpan.setAttribute("agent.source", "template");
await this.natsClient.respond(msg, response);
return;
}
try {
const history = await this.conversationStore.getHistory(
request.chatroomId,
request.userId,
);
if (request.userMessage?.trim()) {
await this.conversationStore.appendMessage(
request.chatroomId,
request.userId,
{
role: "user",
content: request.userMessage,
timestamp: new Date().toISOString(),
},
);
}
const response = await withSkillSpan(
skill.name,
{
"agent.skill": skill.name,
"agent.trigger": request.trigger,
},
() => skill.handle(request, history),
);
if (response.text.trim()) {
await this.conversationStore.appendMessage(
request.chatroomId,
request.userId,
{
role: "assistant",
content: response.text,
timestamp: new Date().toISOString(),
},
);
}
await this.natsClient.respond(msg, response);
rootSpan.setAttribute(
"agent.source",
response.text.trim() ? response.source : "empty",
);
logger.info(
{
confidence: response.confidence,
length: response.text.length,
source: response.source,
},
"[Agent] Response sent",
);
} catch (error) {
logger.error(
{
err: error,
},
`[Agent] Skill ${skill.name} failed`,
);
const errorResponse: AgentResponse = {
requestId: request.requestId,
text: "",
confidence: 0,
source: "template",
metadata: {
error:
error instanceof Error ? error.message : String(error),
},
};
rootSpan.setAttribute("agent.source", "template");
await this.natsClient.respond(msg, errorResponse);
}
},
);
},
);
}
}