Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ReplayRuntimeInstructions.ts

350 lines13.5 KB

1import type { ProviderDriverKind, ProviderReplayTranscript } from "@t3tools/contracts";
2​
3import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
4​
5export function materializeReplayTranscriptRuntimeInstructions(
6 transcript: ProviderReplayTranscript,
7 runtime: { readonly driver: ProviderDriverKind; readonly model: string },
8): ProviderReplayTranscript {
9 const harness =
10 runtime.driver === "cursor"
11 ? "Cursor"
12 : runtime.driver === "kiro"
13 ? "Kiro"
14 : runtime.driver === "acpRegistry"
15 ? "acpRegistry"
16 : runtime.driver === "fx"
17 ? "fx"
18 : undefined;
19 if (harness === undefined) return transcript;
20 const instructions = buildRuntimeInstructions({ harness, model: runtime.model });
21 // The notes name the model, so each prompt expects the ones for its session's current model.
22 const sessionModels = new Map<unknown, string>();
23 const notesFor = (sessionId: unknown) => {
24 const model = sessionModels.get(sessionId) ?? runtime.model;
25 return model === runtime.model ? instructions : buildRuntimeInstructions({ harness, model });
26 };
27 // Like the adapter: notes go out until a prompt carrying that text succeeds, and a new runtime
28 // or compaction resets that. Not mirrored, as no recording has them: Copilot compaction events,
29 // child-session compactions, and ACP v2 prompts that settle through an idle `state_update`.
30 const deliveredNotes = new Map<unknown, string>();
31 // A prompt's success records delivery only if no compaction completed after it was sent.
32 const compactionCounts = new Map<unknown, number>();
33 const completedCompactionIds = new Set<string>();
34 // A turn that completes with a compaction still open projects it as completed.
35 const openCompactions = new Map<unknown, Set<unknown>>();
36 const markCompacted = (sessionId: unknown, compactionId?: unknown) => {
37 if (typeof compactionId === "string") {
38 const key = `${String(sessionId)}\u0000${compactionId}`;
39 if (completedCompactionIds.has(key)) return;
40 completedCompactionIds.add(key);
41 }
42 deliveredNotes.delete(sessionId);
43 compactionCounts.set(sessionId, (compactionCounts.get(sessionId) ?? 0) + 1);
44 };
45 let pendingPrompt:
46 | {
47 readonly sessionId: unknown;
48 /** The runtime notes the prompt carried, if any. */
49 readonly notes: string | undefined;
50 readonly compactionsAtSend: number;
51 }
52 | undefined;
53 let pendingKiroCompact: { readonly sessionId: unknown } | undefined;
54 const cursorSessionKey = "cursor";
55 let cursorAgentId: string | undefined;
56 let interruptedCursorNotes:
57 | {
58 readonly agentId: string | undefined;
59 readonly notes: string;
60 }
61 | undefined;
62 let pendingCursorRun:
63 | {
64 readonly notes: string | undefined;
65 readonly compact: boolean;
66 compacted: boolean;
67 }
68 | undefined;
69​
70 return {
71 ...transcript,
72 entries: transcript.entries.map((entry) => {
73 if (entry.type === "emit_inbound") {
74 const frame = asFrame(entry.frame);
75 if (runtime.driver === "cursor") {
76 if (
77 (frame?.type === "agent.opened" || frame?.type === "run.started") &&
78 typeof frame.agentId === "string"
79 ) {
80 cursorAgentId = frame.agentId;
81 }
82 const cursorUpdate =
83 frame?.type === "interaction.update" && isRecord(frame.update)
84 ? frame.update
85 : undefined;
86 if (cursorUpdate?.type === "summary-completed" && cursorUpdate.failed !== true) {
87 deliveredNotes.delete(cursorSessionKey);
88 if (interruptedCursorNotes?.agentId === cursorAgentId) {
89 interruptedCursorNotes = undefined;
90 }
91 if (pendingCursorRun !== undefined) pendingCursorRun.compacted = true;
92 }
93 if (frame?.type === "run.completed" && pendingCursorRun !== undefined) {
94 const status = isRecord(frame.result) ? frame.result.status : undefined;
95 if (pendingCursorRun.compact) {
96 deliveredNotes.delete(cursorSessionKey);
97 } else if (
98 status === "finished" &&
99 !pendingCursorRun.compacted &&
100 pendingCursorRun.notes !== undefined
101 ) {
102 deliveredNotes.set(cursorSessionKey, pendingCursorRun.notes);
103 interruptedCursorNotes = undefined;
104 } else if (status !== "finished") {
105 if (pendingCursorRun.notes !== undefined) {
106 deliveredNotes.delete(cursorSessionKey);
107 }
108 interruptedCursorNotes =
109 status === "cancelled" &&
110 !pendingCursorRun.compacted &&
111 pendingCursorRun.notes !== undefined
112 ? { agentId: cursorAgentId, notes: pendingCursorRun.notes }
113 : undefined;
114 }
115 pendingCursorRun = undefined;
116 }
117 return entry;
118 }
119 if (frame?.kind === "response" && frame.method === "session/prompt" && pendingPrompt) {
120 const stopReason = isRecord(frame.result) ? frame.result.stopReason : undefined;
121 const delivered =
122 frame.error === undefined &&
123 stopReason !== "cancelled" &&
124 stopReason !== "refusal" &&
125 stopReason !== "error";
126 const open = openCompactions.get(pendingPrompt.sessionId);
127 if (delivered && open !== undefined && open.size > 0) {
128 openCompactions.delete(pendingPrompt.sessionId);
129 markCompacted(pendingPrompt.sessionId);
130 }
131 if (
132 delivered &&
133 pendingPrompt.notes !== undefined &&
134 (compactionCounts.get(pendingPrompt.sessionId) ?? 0) === pendingPrompt.compactionsAtSend
135 ) {
136 deliveredNotes.set(pendingPrompt.sessionId, pendingPrompt.notes);
137 }
138 pendingPrompt = undefined;
139 }
140 if (
141 frame?.kind === "response" &&
142 frame.method === "_kiro/session/compact" &&
143 pendingKiroCompact
144 ) {
145 // Kiro's adapter accepts only `{ success: true }`.
146 if (isRecord(frame.result) && frame.result.success === true) {
147 markCompacted(pendingKiroCompact.sessionId);
148 }
149 pendingKiroCompact = undefined;
150 }
151 const update =
152 frame?.method === "session/update" && isRecord(frame.params)
153 ? frame.params.update
154 : undefined;
155 if (
156 isRecord(update) &&
157 update.sessionUpdate === "compaction_update" &&
158 isRecord(frame?.params)
159 ) {
160 const sessionId = frame.params.sessionId;
161 const open = openCompactions.get(sessionId) ?? new Set<unknown>();
162 if (update.status === "in_progress") {
163 openCompactions.set(sessionId, open.add(update.compactionId));
164 } else {
165 open.delete(update.compactionId);
166 }
167 if (update.status === "completed") markCompacted(sessionId, update.compactionId);
168 }
169 return entry;
170 }
171 if (entry.type !== "expect_outbound") return entry;
172 const frame = entry.frame;
173 if (typeof frame !== "object" || frame === null) return entry;
174 if (runtime.driver === "cursor" && "type" in frame) {
175 if (frame.type === "agent.close") {
176 deliveredNotes.clear();
177 cursorAgentId = undefined;
178 interruptedCursorNotes = undefined;
179 pendingCursorRun = undefined;
180 return entry;
181 }
182 if (frame.type === "run.resume") {
183 pendingCursorRun = {
184 notes:
185 interruptedCursorNotes !== undefined &&
186 interruptedCursorNotes.agentId === cursorAgentId
187 ? interruptedCursorNotes.notes
188 : undefined,
189 compact: false,
190 compacted: false,
191 };
192 return entry;
193 }
194 if (frame.type === "run.start") {
195 if (
196 ("summarize" in frame && frame.summarize === true) ||
197 ("message" in frame &&
198 typeof frame.message === "string" &&
199 frame.message.trim() === "/compress")
200 ) {
201 deliveredNotes.delete(cursorSessionKey);
202 pendingCursorRun = { notes: undefined, compact: true, compacted: false };
203 return entry;
204 }
205 if ("message" in frame && typeof frame.message === "string") {
206 const options =
207 "options" in frame && isRecord(frame.options) ? frame.options : undefined;
208 const model =
209 isRecord(options?.model) && typeof options.model.id === "string"
210 ? options.model.id
211 : runtime.model;
212 const expected =
213 model === runtime.model ? instructions : buildRuntimeInstructions({ harness, model });
214 const recorded = frame.message.endsWith(expected);
215 const resend = !recorded && deliveredNotes.get(cursorSessionKey) !== expected;
216 interruptedCursorNotes = undefined;
217 pendingCursorRun = {
218 notes: recorded || resend ? expected : undefined,
219 compact: false,
220 compacted: false,
221 };
222 if (!resend) return entry;
223 return {
224 ...entry,
225 frame: {
226 ...frame,
227 message: frame.message.length === 0 ? expected : `${frame.message}\n\n${expected}`,
228 },
229 };
230 }
231 }
232 return entry;
233 }
234 if (
235 "method" in frame &&
236 (frame.method === "session/close" || frame.method === "initialize")
237 ) {
238 // A closed or restarted session comes back in a new runtime, which resends the instructions.
239 deliveredNotes.clear();
240 completedCompactionIds.clear();
241 openCompactions.clear();
242 pendingPrompt = undefined;
243 pendingKiroCompact = undefined;
244 return entry;
245 }
246 const params = "params" in frame && isRecord(frame.params) ? frame.params : undefined;
247 const selectedModel =
248 "method" in frame && frame.method === "session/set_config_option"
249 ? params?.configId === "model"
250 ? params.value
251 : undefined
252 : "method" in frame && frame.method === "session/set_model"
253 ? params?.modelId
254 : undefined;
255 if (typeof selectedModel === "string") {
256 sessionModels.set(params?.sessionId, selectedModel);
257 return entry;
258 }
259 if (
260 "method" in frame &&
261 frame.method === "_kiro/session/compact" &&
262 "params" in frame &&
263 typeof frame.params === "object" &&
264 frame.params !== null &&
265 "sessionId" in frame.params
266 ) {
267 // Once it succeeds, Kiro's native compaction makes the next prompt resend them.
268 pendingKiroCompact = { sessionId: frame.params.sessionId };
269 return entry;
270 }
271 if (
272 "method" in frame &&
273 frame.method === "session/prompt" &&
274 "params" in frame &&
275 typeof frame.params === "object" &&
276 frame.params !== null &&
277 "prompt" in frame.params &&
278 Array.isArray(frame.params.prompt)
279 ) {
280 const promptSessionId = "sessionId" in frame.params ? frame.params.sessionId : undefined;
281 const prompt: ReadonlyArray<unknown> = frame.params.prompt;
282 const firstText = promptPartText(prompt[0])?.trim();
283 // Like the adapter, native slash commands go out without instructions.
284 if (firstText?.startsWith("/") === true) {
285 pendingPrompt = {
286 sessionId: promptSessionId,
287 notes: undefined,
288 compactionsAtSend: compactionCounts.get(promptSessionId) ?? 0,
289 };
290 return entry;
291 }
292 const lastText = promptPartText(prompt.at(-1));
293 const expected = notesFor(promptSessionId);
294 // A recording that switched models mid-thread already carries the
295 // instructions for the model each prompt ran on.
296 const recordedNotes =
297 lastText === expected || lastText?.startsWith("<runtime_info>") === true
298 ? lastText
299 : undefined;
300 const resend =
301 recordedNotes === undefined && deliveredNotes.get(promptSessionId) !== expected;
302 pendingPrompt = {
303 sessionId: promptSessionId,
304 // Recorders normalize the notes they keep, so a recorded block stands for this model's.
305 notes: recordedNotes !== undefined || resend ? expected : undefined,
306 compactionsAtSend: compactionCounts.get(promptSessionId) ?? 0,
307 };
308 if (!resend) return entry;
309 return {
310 ...entry,
311 frame: {
312 ...frame,
313 params: { ...frame.params, prompt: [...prompt, { type: "text", text: expected }] },
314 },
315 };
316 }
317 return entry;
318 }),
319 };
321​
322function promptPartText(part: unknown): string | undefined {
323 return typeof part === "object" &&
324 part !== null &&
325 "type" in part &&
326 part.type === "text" &&
327 "text" in part &&
328 typeof part.text === "string"
329 ? part.text
330 : undefined;
332​
333type ReplayFrame = {
334 readonly kind?: unknown;
335 readonly type?: unknown;
336 readonly agentId?: unknown;
337 readonly method?: unknown;
338 readonly params?: unknown;
339 readonly update?: unknown;
340 readonly result?: unknown;
341 readonly error?: unknown;
342};
343​
344function isRecord(value: unknown): value is Record<string, unknown> {
345 return typeof value === "object" && value !== null;
347​
348function asFrame(value: unknown): ReplayFrame | undefined {
349 return isRecord(value) ? value : undefined;