refactor(gateway): share agent prompt builder

This commit is contained in:
Peter Steinberger
2026-02-14 13:34:30 +00:00
parent e707a7bd36
commit 7fc1026746
4 changed files with 103 additions and 64 deletions

View File

@@ -1,12 +1,15 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { randomUUID } from "node:crypto";
import type { AuthRateLimiter } from "./auth-rate-limit.js";
import { buildHistoryContextFromEntries, type HistoryEntry } from "../auto-reply/reply/history.js";
import { createDefaultDeps } from "../cli/deps.js";
import { agentCommand } from "../commands/agent.js";
import { emitAgentEvent, onAgentEvent } from "../infra/agent-events.js";
import { logWarn } from "../logger.js";
import { defaultRuntime } from "../runtime.js";
import {
buildAgentMessageFromConversationEntries,
type ConversationEntry,
} from "./agent-prompt.js";
import { authorizeGatewayConnect, type ResolvedGatewayAuth } from "./auth.js";
import {
readJsonBodyOrError,
@@ -83,8 +86,7 @@ function buildAgentPrompt(messagesUnknown: unknown): {
const messages = asMessages(messagesUnknown);
const systemParts: string[] = [];
const conversationEntries: Array<{ role: "user" | "assistant" | "tool"; entry: HistoryEntry }> =
[];
const conversationEntries: ConversationEntry[] = [];
for (const msg of messages) {
if (!msg || typeof msg !== "object") {
@@ -121,34 +123,7 @@ function buildAgentPrompt(messagesUnknown: unknown): {
});
}
let message = "";
if (conversationEntries.length > 0) {
let currentIndex = -1;
for (let i = conversationEntries.length - 1; i >= 0; i -= 1) {
const entryRole = conversationEntries[i]?.role;
if (entryRole === "user" || entryRole === "tool") {
currentIndex = i;
break;
}
}
if (currentIndex < 0) {
currentIndex = conversationEntries.length - 1;
}
const currentEntry = conversationEntries[currentIndex]?.entry;
if (currentEntry) {
const historyEntries = conversationEntries.slice(0, currentIndex).map((entry) => entry.entry);
if (historyEntries.length === 0) {
message = currentEntry.body;
} else {
const formatEntry = (entry: HistoryEntry) => `${entry.sender}: ${entry.body}`;
message = buildHistoryContextFromEntries({
entries: [...historyEntries, currentEntry],
currentMessage: formatEntry(currentEntry),
formatEntry,
});
}
}
}
const message = buildAgentMessageFromConversationEntries(conversationEntries);
return {
message,