feat: send session prompt once

This commit is contained in:
Peter Steinberger
2025-11-25 23:52:38 +01:00
parent d924b7d283
commit 2e3b8a03aa
7 changed files with 121 additions and 13 deletions

View File

@@ -134,10 +134,13 @@ export async function getReplyFromConfig(
);
const sessionScope = sessionCfg?.scope ?? "per-sender";
const storePath = resolveStorePath(sessionCfg?.store);
let sessionStore: ReturnType<typeof loadSessionStore> | undefined;
let sessionKey: string | undefined;
let sessionId: string | undefined;
let isNewSession = false;
let bodyStripped: string | undefined;
let systemSent = false;
if (sessionCfg) {
const trimmedBody = (ctx.Body ?? "").trim();
@@ -156,21 +159,23 @@ export async function getReplyFromConfig(
}
}
const sessionKey = deriveSessionKey(sessionScope, ctx);
const store = loadSessionStore(storePath);
const entry = store[sessionKey];
sessionKey = deriveSessionKey(sessionScope, ctx);
sessionStore = loadSessionStore(storePath);
const entry = sessionStore[sessionKey];
const idleMs = idleMinutes * 60_000;
const freshEntry = entry && Date.now() - entry.updatedAt <= idleMs;
if (!isNewSession && freshEntry) {
sessionId = entry.sessionId;
systemSent = entry.systemSent ?? false;
} else {
sessionId = crypto.randomUUID();
isNewSession = true;
systemSent = false;
}
store[sessionKey] = { sessionId, updatedAt: Date.now() };
await saveSessionStore(storePath, store);
sessionStore[sessionKey] = { sessionId, updatedAt: Date.now(), systemSent };
await saveSessionStore(storePath, sessionStore);
}
const sessionCtx: TemplateContext = {
@@ -193,12 +198,43 @@ export async function getReplyFromConfig(
}
// Optional prefix injected before Body for templating/command prompts.
const sendSystemOnce = sessionCfg?.sendSystemOnce === true;
const isFirstTurnInSession = isNewSession || !systemSent;
const sessionIntro =
isFirstTurnInSession && sessionCfg?.sessionIntro
? applyTemplate(sessionCfg.sessionIntro, sessionCtx)
: "";
const bodyPrefix = reply?.bodyPrefix
? applyTemplate(reply.bodyPrefix, sessionCtx)
: "";
const prefixedBodyBase = bodyPrefix
? `${bodyPrefix}${sessionCtx.BodyStripped ?? sessionCtx.Body ?? ""}`
: (sessionCtx.BodyStripped ?? sessionCtx.Body);
const baseBody = sessionCtx.BodyStripped ?? sessionCtx.Body ?? "";
const prefixedBodyBase = (() => {
let body = baseBody;
if (!sendSystemOnce || isFirstTurnInSession) {
body = bodyPrefix ? `${bodyPrefix}${body}` : body;
}
if (sessionIntro) {
body = `${sessionIntro}\n\n${body}`;
}
return body;
})();
if (
sessionCfg &&
sendSystemOnce &&
isFirstTurnInSession &&
sessionStore &&
sessionKey
) {
sessionStore[sessionKey] = {
...(sessionStore[sessionKey] ?? {}),
sessionId: sessionId ?? crypto.randomUUID(),
updatedAt: Date.now(),
systemSent: true,
};
await saveSessionStore(storePath, sessionStore);
systemSent = true;
}
const prefixedBody =
transcribedText && reply?.mode === "command"
? [prefixedBodyBase, `Transcript:\n${transcribedText}`]
@@ -241,9 +277,10 @@ export async function getReplyFromConfig(
if (reply.mode === "command" && reply.command?.length) {
await onReplyStart();
let argv = reply.command.map((part) => applyTemplate(part, templatingCtx));
const templatePrefix = reply.template
? applyTemplate(reply.template, templatingCtx)
: "";
const templatePrefix =
reply.template && (!sendSystemOnce || isFirstTurnInSession || !systemSent)
? applyTemplate(reply.template, templatingCtx)
: "";
if (templatePrefix && argv.length > 0) {
argv = [argv[0], templatePrefix, ...argv.slice(1)];
}

View File

@@ -17,6 +17,8 @@ export type SessionConfig = {
sessionArgNew?: string[];
sessionArgResume?: string[];
sessionArgBeforeBody?: boolean;
sendSystemOnce?: boolean;
sessionIntro?: string;
};
export type LoggingConfig = {
@@ -73,6 +75,8 @@ const ReplySchema = z
sessionArgNew: z.array(z.string()).optional(),
sessionArgResume: z.array(z.string()).optional(),
sessionArgBeforeBody: z.boolean().optional(),
sendSystemOnce: z.boolean().optional(),
sessionIntro: z.string().optional(),
})
.optional(),
claudeOutputFormat: z

View File

@@ -8,7 +8,11 @@ import { CONFIG_DIR, normalizeE164 } from "../utils.js";
export type SessionScope = "per-sender" | "global";
export type SessionEntry = { sessionId: string; updatedAt: number };
export type SessionEntry = {
sessionId: string;
updatedAt: number;
systemSent?: boolean;
};
export const SESSION_STORE_DEFAULT = path.join(CONFIG_DIR, "sessions.json");
export const DEFAULT_RESET_TRIGGER = "/new";

View File

@@ -1,5 +1,6 @@
import crypto from "node:crypto";
import net from "node:net";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { MessageInstance } from "twilio/lib/rest/api/v2010/account/message.js";
@@ -499,6 +500,64 @@ describe("config and templating", () => {
expect(argvSecond[2]).toBe("--resume");
});
it("only sends system prompt once per session when configured", async () => {
const tmpStore = path.join(os.tmpdir(), `warelay-store-${Date.now()}.json`);
vi.spyOn(crypto, "randomUUID").mockReturnValue("sid-1");
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({
stdout: "ok\n",
stderr: "",
code: 0,
signal: null,
killed: false,
});
const cfg = {
inbound: {
reply: {
mode: "command" as const,
command: ["echo", "{{Body}}"],
template: "[tmpl]",
bodyPrefix: "[pfx] ",
session: {
sendSystemOnce: true,
sessionIntro: "SYS",
store: tmpStore,
sessionArgNew: ["--sid", "{{SessionId}}"],
sessionArgResume: ["--resume", "{{SessionId}}"],
},
},
},
};
await index.getReplyFromConfig(
{ Body: "/new hi", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
await index.getReplyFromConfig(
{ Body: "next", From: "+1", To: "+2" },
undefined,
cfg,
runSpy,
);
const firstArgv = runSpy.mock.calls[0][0];
expect(firstArgv).toEqual([
"echo",
"[tmpl]",
"--sid",
"sid-1",
"SYS\n\n[pfx] hi",
]);
const secondArgv = runSpy.mock.calls[1][0];
expect(secondArgv).toEqual(["echo", "--resume", "sid-1", "next"]);
const persisted = JSON.parse(fs.readFileSync(tmpStore, "utf-8"));
const firstEntry = Object.values(persisted)[0] as { systemSent?: boolean };
expect(firstEntry.systemSent).toBe(true);
});
it("injects Claude output format + print flag when configured", async () => {
const runSpy = vi.spyOn(index, "runCommandWithTimeout").mockResolvedValue({
stdout: "ok",