surface: envelope inbound messages for agent

This commit is contained in:
Peter Steinberger
2025-12-09 18:43:21 +00:00
parent 55bffeba4a
commit ffc930b871
8 changed files with 149 additions and 28 deletions

View File

@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { formatAgentEnvelope } from "./envelope.js";
describe("formatAgentEnvelope", () => {
it("includes surface, from, ip, host, and timestamp", () => {
const ts = Date.UTC(2025, 0, 2, 3, 4); // 2025-01-02T03:04:00Z
const body = formatAgentEnvelope({
surface: "WebChat",
from: "user1",
host: "mac-mini",
ip: "10.0.0.5",
timestamp: ts,
body: "hello",
});
expect(body).toBe("[WebChat user1 mac-mini 10.0.0.5 2025-01-02 03:04] hello");
});
it("handles missing optional fields", () => {
const body = formatAgentEnvelope({ surface: "Telegram", body: "hi" });
expect(body).toBe("[Telegram] hi");
});
});

View File

@@ -0,0 +1,28 @@
export type AgentEnvelopeParams = {
surface: string;
from?: string;
timestamp?: number | Date;
host?: string;
ip?: string;
body: string;
};
function formatTimestamp(ts?: number | Date): string | undefined {
if (!ts) return undefined;
const date = ts instanceof Date ? ts : new Date(ts);
if (Number.isNaN(date.getTime())) return undefined;
// Compact ISO-like format with minutes precision.
return date.toISOString().slice(0, 16).replace("T", " ");
}
export function formatAgentEnvelope(params: AgentEnvelopeParams): string {
const surface = params.surface?.trim() || "Surface";
const parts: string[] = [surface];
if (params.from?.trim()) parts.push(params.from.trim());
if (params.host?.trim()) parts.push(params.host.trim());
if (params.ip?.trim()) parts.push(params.ip.trim());
const ts = formatTimestamp(params.timestamp);
if (ts) parts.push(ts);
const header = `[${parts.join(" ")}]`;
return `${header} ${params.body}`;
}