|
| 1 | +import { |
| 2 | + buildSessionObserverPrompt, |
| 3 | + normalizeSessionObserverModelOutput, |
| 4 | + SESSION_OBSERVER_MODEL_MAX_TOKENS, |
| 5 | + SESSION_OBSERVER_SYSTEM_PROMPT, |
| 6 | +} from "./session-observer-model.js"; |
| 7 | +import type { SessionObserverDeps, SessionObserverState } from "./session-observer-model.js"; |
| 8 | + |
| 9 | +const MODEL_TIMEOUT_MS = 10_000; |
| 10 | + |
| 11 | +type PrepareModel = NonNullable<SessionObserverDeps["prepareModel"]>; |
| 12 | +type CompleteModel = NonNullable<SessionObserverDeps["completeModel"]>; |
| 13 | + |
| 14 | +export function createSessionObserverCompletion(params: { |
| 15 | + getConfig: SessionObserverDeps["getConfig"]; |
| 16 | + prepareModel: PrepareModel; |
| 17 | + completeModel: CompleteModel; |
| 18 | + now: () => number; |
| 19 | + setTimeoutFn: typeof setTimeout; |
| 20 | + clearTimeoutFn: typeof clearTimeout; |
| 21 | + isCurrent: (state: SessionObserverState) => boolean; |
| 22 | +}) { |
| 23 | + const ensurePrepared = async (state: SessionObserverState) => { |
| 24 | + const modelRef = state.utilityModelRef; |
| 25 | + if (!modelRef) { |
| 26 | + throw new Error("session observer utility model is unavailable"); |
| 27 | + } |
| 28 | + state.preparedPromise ??= params.prepareModel({ |
| 29 | + cfg: params.getConfig(), |
| 30 | + agentId: state.agentId, |
| 31 | + modelRef, |
| 32 | + useUtilityModel: true, |
| 33 | + allowMissingApiKeyModes: ["aws-sdk"], |
| 34 | + }); |
| 35 | + return await state.preparedPromise; |
| 36 | + }; |
| 37 | + |
| 38 | + return async (state: SessionObserverState, notes: readonly string[]) => { |
| 39 | + const controller = new AbortController(); |
| 40 | + state.activeController = controller; |
| 41 | + const timeout = params.setTimeoutFn(() => controller.abort(), MODEL_TIMEOUT_MS); |
| 42 | + const aborted = new Promise<never>((_resolve, reject) => { |
| 43 | + controller.signal.addEventListener( |
| 44 | + "abort", |
| 45 | + () => reject(new Error("session observer model call timed out or was cancelled")), |
| 46 | + { once: true }, |
| 47 | + ); |
| 48 | + }); |
| 49 | + try { |
| 50 | + const execute = async () => { |
| 51 | + const prepared = await ensurePrepared(state); |
| 52 | + if (!params.isCurrent(state) || controller.signal.aborted) { |
| 53 | + throw new Error("session observer state is no longer active"); |
| 54 | + } |
| 55 | + if ("error" in prepared) { |
| 56 | + throw new Error(prepared.error); |
| 57 | + } |
| 58 | + for (let attempt = 0; attempt < 2; attempt += 1) { |
| 59 | + if (!params.isCurrent(state) || controller.signal.aborted) { |
| 60 | + throw new Error("session observer state is no longer active"); |
| 61 | + } |
| 62 | + const result = await params.completeModel({ |
| 63 | + model: prepared.model, |
| 64 | + auth: prepared.auth, |
| 65 | + cfg: params.getConfig(), |
| 66 | + context: { |
| 67 | + systemPrompt: SESSION_OBSERVER_SYSTEM_PROMPT, |
| 68 | + messages: [ |
| 69 | + { |
| 70 | + role: "user", |
| 71 | + content: buildSessionObserverPrompt(state, notes), |
| 72 | + timestamp: params.now(), |
| 73 | + }, |
| 74 | + ], |
| 75 | + }, |
| 76 | + options: { |
| 77 | + maxTokens: Math.min( |
| 78 | + SESSION_OBSERVER_MODEL_MAX_TOKENS, |
| 79 | + Math.floor(prepared.model.maxTokens), |
| 80 | + ), |
| 81 | + temperature: 0.2, |
| 82 | + signal: controller.signal, |
| 83 | + }, |
| 84 | + }); |
| 85 | + if (result.stopReason === "error") { |
| 86 | + throw new Error(result.errorMessage?.trim() || "session observer completion failed"); |
| 87 | + } |
| 88 | + const text = result.content |
| 89 | + .filter((block): block is { type: "text"; text: string } => block.type === "text") |
| 90 | + .map((block) => block.text) |
| 91 | + .join("") |
| 92 | + .trim(); |
| 93 | + const parsed = normalizeSessionObserverModelOutput(text); |
| 94 | + if (parsed) { |
| 95 | + return parsed; |
| 96 | + } |
| 97 | + } |
| 98 | + throw new Error("session observer returned invalid JSON twice"); |
| 99 | + }; |
| 100 | + return await Promise.race([execute(), aborted]); |
| 101 | + } finally { |
| 102 | + params.clearTimeoutFn(timeout); |
| 103 | + if (state.activeController === controller) { |
| 104 | + state.activeController = undefined; |
| 105 | + } |
| 106 | + } |
| 107 | + }; |
| 108 | +} |
0 commit comments