The best way to control Claude Code, Codex and more from any computer or phone

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