This repository has been archived on 2026-08-23. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
pi-web/src/server/sessions/sessionNameGenerator.ts
T
Federico Jaramillo Martinez ad74ea4da7 refactor: generate session names via agent.streamFn instead of pi-ai compat
Rewrite sessionNameGenerator.ts to consume a StreamFn-shaped dependency
(sourced from PiAgentSession.agent.streamFn, wired in leg B) instead of
ModelRegistry plus a dynamic @earendil-works/pi-ai/compat import.

streamFn resolves auth/headers/retry internally, so the explicit
modelRegistry.getApiKeyAndHeaders(model) call and apiKey/headers stream
options are no longer needed.

Deletes now-dead compat-loading machinery: getPiAiProviderRegistryModule,
loadPiAiProviderRegistryModule, importOptionalPiAiModule,
isModuleUnavailableError, hasGetApiProvider, PI_AI_COMPAT_MODULE,
ModuleImporter, SessionNameApiProvider, PiAiProviderRegistryModule, and
the module-level provider registry cache.

Updates the maybeGenerateSessionName call site in piSessionService.ts to
pass session.agent.streamFn instead of this.modelRegistry, and updates
both test files: sessionNameGenerator.test.ts gains coverage for the new
streamFn-driven generateShortSessionName signature (success and error
paths), and piSessionService.test.ts gains an end-to-end test proving a
first prompt generates a session name through the wired agent.streamFn
fake.

sessionNameGenerator.ts no longer imports @earendil-works/pi-ai/compat
or references getApiProvider anywhere.
2026-07-02 11:42:30 +02:00

72 lines
2.4 KiB
TypeScript

import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
import type { StreamFn } from "@earendil-works/pi-agent-core";
const SESSION_NAME_TIMEOUT_MS = 10_000;
const SESSION_NAME_MAX_INPUT_CHARS = 4_000;
const SESSION_NAME_MAX_LENGTH = 60;
const FALLBACK_SESSION_NAME_MAX_WORDS = 6;
export async function generateShortSessionName<TApi extends Api>(streamFn: StreamFn, model: Model<TApi>, firstMessage: string): Promise<string | undefined> {
const stream = await streamFn(
model,
{
systemPrompt: "Generate a concise title for a coding-agent chat session. Return only the title, with no quotes or punctuation wrapper.",
messages: [{
role: "user",
content: `Create a 2-6 word title for this request:\n\n${truncateInput(firstMessage)}`,
timestamp: Date.now(),
}],
},
{
maxTokens: 24,
reasoning: "minimal",
signal: AbortSignal.timeout(SESSION_NAME_TIMEOUT_MS),
},
);
let streamedText = "";
let finalMessage: AssistantMessage | undefined;
for await (const event of stream) {
if (event.type === "text_delta") streamedText += event.delta;
if (event.type === "done") finalMessage = event.message;
if (event.type === "error") return undefined;
}
return cleanSessionName(finalMessage === undefined ? streamedText : textFromAssistant(finalMessage));
}
export function fallbackSessionName(firstMessage: unknown): string | undefined {
if (typeof firstMessage !== "string") return undefined;
return cleanSessionName(firstMessage
.replace(/<skill name="[^"]+" location="[^"]+">[\s\S]*?<\/skill>/g, "")
.replace(/```[\s\S]*?```/g, " ")
.replace(/[`*_#[\](){}<>]/g, " ")
.split(/\s+/)
.filter(Boolean)
.slice(0, FALLBACK_SESSION_NAME_MAX_WORDS)
.join(" "));
}
export function cleanSessionName(value: string): string | undefined {
const title = (value.split("\n", 1)[0] ?? "")
.replace(/^\s*(title|session title)\s*:\s*/i, "")
.replace(/^\s*["'`]+|["'`.]+\s*$/g, "")
.replace(/\s+/g, " ")
.trim()
.slice(0, SESSION_NAME_MAX_LENGTH)
.trim();
return title === "" ? undefined : title;
}
function textFromAssistant(message: AssistantMessage): string {
return message.content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("");
}
function truncateInput(value: string): string {
return value.length <= SESSION_NAME_MAX_INPUT_CHARS ? value : `${value.slice(0, SESSION_NAME_MAX_INPUT_CHARS)}…`;
}