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

codexEventMapping.ts

1,370 lines40.1 KB

1/**
2 * codexEventMapping - Pure event-mapping functions for the Codex provider.
3 *
4 * Extracted from CodexAdapter.ts so these functions can be reused by other
5 * adapters (e.g. HarnessClientAdapter) without pulling in the full adapter
6 * implementation.
7 *
8 * @module codexEventMapping
9 */
10import {
11 type CanonicalItemType,
12 type CanonicalRequestType,
13 type ProviderEvent,
14 type ProviderRuntimeEvent,
15 type ProviderUserInputAnswers,
16 RuntimeItemId,
17 RuntimeRequestId,
18 RuntimeTaskId,
19 ProviderApprovalDecision,
20 ProviderItemId,
21 ThreadId,
22 TurnId,
23} from "@t3tools/contracts";
24import { Schema } from "effect";
25​
26// ---------------------------------------------------------------------------
27// Primitive coercions
28// ---------------------------------------------------------------------------
29​
30export function asObject(value: unknown): Record<string, unknown> | undefined {
31 if (!value || typeof value !== "object") {
32 return undefined;
33 }
34 return value as Record<string, unknown>;
36​
37export function asString(value: unknown): string | undefined {
38 return typeof value === "string" ? value : undefined;
40​
41export function asArray(value: unknown): unknown[] | undefined {
42 return Array.isArray(value) ? value : undefined;
44​
45export function asNumber(value: unknown): number | undefined {
46 return typeof value === "number" && Number.isFinite(value) ? value : undefined;
48​
49// ---------------------------------------------------------------------------
50// Status / type normalisation
51// ---------------------------------------------------------------------------
52​
53export function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
54 switch (value) {
55 case "completed":
56 case "failed":
57 case "cancelled":
58 case "interrupted":
59 return value;
60 default:
61 return "completed";
62 }
64​
65export function normalizeItemType(raw: unknown): string {
66 const type = asString(raw);
67 if (!type) return "item";
68 return type
69 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
70 .replace(/[._/-]/g, " ")
71 .replace(/\s+/g, " ")
72 .trim()
73 .toLowerCase();
75​
76export function toCanonicalItemType(raw: unknown): CanonicalItemType {
77 const type = normalizeItemType(raw);
78 if (type.includes("user")) return "user_message";
79 if (type.includes("agent message") || type.includes("assistant")) return "assistant_message";
80 if (type.includes("reasoning") || type.includes("thought")) return "reasoning";
81 if (type.includes("plan") || type.includes("todo")) return "plan";
82 if (type.includes("command")) return "command_execution";
83 if (type.includes("file change") || type.includes("patch") || type.includes("edit"))
84 return "file_change";
85 if (type.includes("mcp")) return "mcp_tool_call";
86 if (type.includes("dynamic tool")) return "dynamic_tool_call";
87 if (type.includes("collab")) return "collab_agent_tool_call";
88 if (type.includes("web search")) return "web_search";
89 if (type.includes("image")) return "image_view";
90 if (type.includes("review entered")) return "review_entered";
91 if (type.includes("review exited")) return "review_exited";
92 if (type.includes("compact")) return "context_compaction";
93 if (type.includes("error")) return "error";
94 return "unknown";
96​
97// ---------------------------------------------------------------------------
98// Item display helpers
99// ---------------------------------------------------------------------------
100​
101export function itemTitle(itemType: CanonicalItemType): string | undefined {
102 switch (itemType) {
103 case "assistant_message":
104 return "Assistant message";
105 case "user_message":
106 return "User message";
107 case "reasoning":
108 return "Reasoning";
109 case "plan":
110 return "Plan";
111 case "command_execution":
112 return "Ran command";
113 case "file_change":
114 return "File change";
115 case "mcp_tool_call":
116 return "MCP tool call";
117 case "dynamic_tool_call":
118 return "Tool call";
119 case "web_search":
120 return "Web search";
121 case "image_view":
122 return "Image view";
123 case "error":
124 return "Error";
125 default:
126 return undefined;
127 }
129​
130export function itemDetail(
131 item: Record<string, unknown>,
132 payload: Record<string, unknown>,
133): string | undefined {
134 const nestedResult = asObject(item.result);
135 const candidates = [
136 asString(item.command),
137 asString(item.title),
138 asString(item.summary),
139 asString(item.text),
140 asString(item.path),
141 asString(item.prompt),
142 asString(nestedResult?.command),
143 asString(payload.command),
144 asString(payload.message),
145 asString(payload.prompt),
146 ];
147 for (const candidate of candidates) {
148 if (!candidate) continue;
149 const trimmed = candidate.trim();
150 if (trimmed.length === 0) continue;
151 return trimmed;
152 }
153 return undefined;
155​
156// ---------------------------------------------------------------------------
157// Request type resolution
158// ---------------------------------------------------------------------------
159​
160export function toRequestTypeFromMethod(method: string): CanonicalRequestType {
161 switch (method) {
162 case "item/commandExecution/requestApproval":
163 return "command_execution_approval";
164 case "item/fileRead/requestApproval":
165 return "file_read_approval";
166 case "item/fileChange/requestApproval":
167 return "file_change_approval";
168 case "applyPatchApproval":
169 return "apply_patch_approval";
170 case "execCommandApproval":
171 return "exec_command_approval";
172 case "item/tool/requestUserInput":
173 return "tool_user_input";
174 case "item/tool/call":
175 return "dynamic_tool_call";
176 case "account/chatgptAuthTokens/refresh":
177 return "auth_tokens_refresh";
178 default:
179 return "unknown";
180 }
182​
183export function toRequestTypeFromKind(kind: unknown): CanonicalRequestType {
184 switch (kind) {
185 case "command":
186 return "command_execution_approval";
187 case "file-read":
188 return "file_read_approval";
189 case "file-change":
190 return "file_change_approval";
191 default:
192 return "unknown";
193 }
195​
196export function toRequestTypeFromResolvedPayload(
197 payload: Record<string, unknown> | undefined,
198): CanonicalRequestType {
199 const request = asObject(payload?.request);
200 const method = asString(request?.method) ?? asString(payload?.method);
201 if (method) {
202 return toRequestTypeFromMethod(method);
203 }
204 const requestKind = asString(request?.kind) ?? asString(payload?.requestKind);
205 if (requestKind) {
206 return toRequestTypeFromKind(requestKind);
207 }
208 return "unknown";
210​
211// ---------------------------------------------------------------------------
212// User-input helpers
213// ---------------------------------------------------------------------------
214​
215export function toCanonicalUserInputAnswers(
216 answers: ProviderUserInputAnswers | undefined,
217): ProviderUserInputAnswers {
218 if (!answers) {
219 return {};
220 }
221​
222 return Object.fromEntries(
223 Object.entries(answers).flatMap(([questionId, value]) => {
224 if (typeof value === "string") {
225 return [[questionId, value] as const];
226 }
227​
228 if (Array.isArray(value)) {
229 const normalized = value.filter((entry): entry is string => typeof entry === "string");
230 return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const];
231 }
232​
233 const answerObject = asObject(value);
234 const answerList = asArray(answerObject?.answers)?.filter(
235 (entry): entry is string => typeof entry === "string",
236 );
237 if (!answerList) {
238 return [];
239 }
240 return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
241 }),
242 );
244​
245export function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
246 const questions = asArray(payload?.questions);
247 if (!questions) {
248 return undefined;
249 }
250​
251 const parsedQuestions = questions
252 .map((entry) => {
253 const question = asObject(entry);
254 if (!question) return undefined;
255 const options = asArray(question.options)
256 ?.map((option) => {
257 const optionRecord = asObject(option);
258 if (!optionRecord) return undefined;
259 const label = asString(optionRecord.label)?.trim();
260 const description = asString(optionRecord.description)?.trim();
261 if (!label || !description) {
262 return undefined;
263 }
264 return { label, description };
265 })
266 .filter((option): option is { label: string; description: string } => option !== undefined);
267 const id = asString(question.id)?.trim();
268 const header = asString(question.header)?.trim();
269 const prompt = asString(question.question)?.trim();
270 if (!id || !header || !prompt || !options || options.length === 0) {
271 return undefined;
272 }
273 return {
274 id,
275 header,
276 question: prompt,
277 options,
278 };
279 })
280 .filter(
281 (
282 question,
283 ): question is {
284 id: string;
285 header: string;
286 question: string;
287 options: Array<{ label: string; description: string }>;
288 } => question !== undefined,
289 );
290​
291 return parsedQuestions.length > 0 ? parsedQuestions : undefined;
293​
294// ---------------------------------------------------------------------------
295// Thread / content stream helpers
296// ---------------------------------------------------------------------------
297​
298export function toThreadState(
299 value: unknown,
300): "active" | "idle" | "archived" | "closed" | "compacted" | "error" {
301 switch (value) {
302 case "idle":
303 return "idle";
304 case "archived":
305 return "archived";
306 case "closed":
307 return "closed";
308 case "compacted":
309 return "compacted";
310 case "error":
311 case "failed":
312 return "error";
313 default:
314 return "active";
315 }
317​
318export function contentStreamKindFromMethod(
319 method: string,
320):
321 | "assistant_text"
322 | "reasoning_text"
323 | "reasoning_summary_text"
324 | "plan_text"
325 | "command_output"
326 | "file_change_output" {
327 switch (method) {
328 case "item/agentMessage/delta":
329 return "assistant_text";
330 case "item/reasoning/textDelta":
331 return "reasoning_text";
332 case "item/reasoning/summaryTextDelta":
333 return "reasoning_summary_text";
334 case "item/commandExecution/outputDelta":
335 return "command_output";
336 case "item/fileChange/outputDelta":
337 return "file_change_output";
338 default:
339 return "assistant_text";
340 }
342​
343// ---------------------------------------------------------------------------
344// Plan extraction
345// ---------------------------------------------------------------------------
346​
347const PROPOSED_PLAN_BLOCK_REGEX = /<proposed_plan>\s*([\s\S]*?)\s*<\/proposed_plan>/i;
348​
349export function extractProposedPlanMarkdown(text: string | undefined): string | undefined {
350 const match = text ? PROPOSED_PLAN_BLOCK_REGEX.exec(text) : null;
351 const planMarkdown = match?.[1]?.trim();
352 return planMarkdown && planMarkdown.length > 0 ? planMarkdown : undefined;
354​
355// ---------------------------------------------------------------------------
356// Branded ID helpers
357// ---------------------------------------------------------------------------
358​
359export function asRuntimeItemId(itemId: ProviderItemId): RuntimeItemId {
360 return RuntimeItemId.makeUnsafe(itemId);
362​
363export function asRuntimeRequestId(requestId: string): RuntimeRequestId {
364 return RuntimeRequestId.makeUnsafe(requestId);
366​
367export function asRuntimeTaskId(taskId: string): RuntimeTaskId {
368 return RuntimeTaskId.makeUnsafe(taskId);
370​
371// ---------------------------------------------------------------------------
372// Event base builders
373// ---------------------------------------------------------------------------
374​
375export function codexEventMessage(
376 payload: Record<string, unknown> | undefined,
377): Record<string, unknown> | undefined {
378 return asObject(payload?.msg);
380​
381export function codexEventBase(
382 event: ProviderEvent,
383 canonicalThreadId: ThreadId,
384): Omit<ProviderRuntimeEvent, "type" | "payload"> {
385 const payload = asObject(event.payload);
386 const msg = codexEventMessage(payload);
387 // Prefer event-level turn/item/request ids (set by the adapter manager)
388 // over msg-level ids (which may reference child/sub-agent ids)
389 const turnId = asString(event.turnId) ?? asString(msg?.turn_id) ?? asString(msg?.turnId);
390 const itemId = asString(event.itemId) ?? asString(msg?.item_id) ?? asString(msg?.itemId);
391 const requestId =
392 asString(event.requestId) ?? asString(msg?.request_id) ?? asString(msg?.requestId);
393 const base = runtimeEventBase(event, canonicalThreadId);
394 const providerRefs = base.providerRefs
395 ? {
396 ...base.providerRefs,
397 ...(turnId ? { providerTurnId: turnId } : {}),
398 ...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
399 ...(requestId ? { providerRequestId: requestId } : {}),
400 }
401 : {
402 ...(turnId ? { providerTurnId: turnId } : {}),
403 ...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
404 ...(requestId ? { providerRequestId: requestId } : {}),
405 };
406​
407 return {
408 ...base,
409 ...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
410 ...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
411 ...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
412 ...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
413 };
415​
416export function eventRawSource(
417 event: ProviderEvent,
418): NonNullable<ProviderRuntimeEvent["raw"]>["source"] {
419 return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification";
421​
422export function providerRefsFromEvent(
423 event: ProviderEvent,
424): ProviderRuntimeEvent["providerRefs"] | undefined {
425 const refs: Record<string, string> = {};
426 if (event.turnId) refs.providerTurnId = event.turnId;
427 if (event.itemId) refs.providerItemId = event.itemId;
428 if (event.requestId) refs.providerRequestId = event.requestId;
429​
430 return Object.keys(refs).length > 0 ? (refs as ProviderRuntimeEvent["providerRefs"]) : undefined;
432​
433export function runtimeEventBase(
434 event: ProviderEvent,
435 canonicalThreadId: ThreadId,
436): Omit<ProviderRuntimeEvent, "type" | "payload"> {
437 const refs = providerRefsFromEvent(event);
438 return {
439 eventId: event.id,
440 provider: event.provider,
441 threadId: canonicalThreadId,
442 createdAt: event.createdAt,
443 ...(event.turnId ? { turnId: event.turnId } : {}),
444 ...(event.itemId ? { itemId: asRuntimeItemId(event.itemId) } : {}),
445 ...(event.requestId ? { requestId: asRuntimeRequestId(event.requestId) } : {}),
446 ...(refs ? { providerRefs: refs } : {}),
447 raw: {
448 source: eventRawSource(event),
449 method: event.method,
450 payload: event.payload ?? {},
451 },
452 };
454​
455// ---------------------------------------------------------------------------
456// Item lifecycle mapper
457// ---------------------------------------------------------------------------
458​
459export function mapItemLifecycle(
460 event: ProviderEvent,
461 canonicalThreadId: ThreadId,
462 lifecycle: "item.started" | "item.updated" | "item.completed",
463): ProviderRuntimeEvent | undefined {
464 const payload = asObject(event.payload);
465 const item = asObject(payload?.item);
466 const source = item ?? payload;
467 if (!source) {
468 return undefined;
469 }
470​
471 const itemType = toCanonicalItemType(source.type ?? source.kind);
472 if (itemType === "unknown" && lifecycle !== "item.updated") {
473 return undefined;
474 }
475​
476 const detail = itemDetail(source, payload ?? {});
477 const status =
478 lifecycle === "item.started"
479 ? "inProgress"
480 : lifecycle === "item.completed"
481 ? "completed"
482 : undefined;
483​
484 return {
485 ...runtimeEventBase(event, canonicalThreadId),
486 type: lifecycle,
487 payload: {
488 itemType,
489 ...(status ? { status } : {}),
490 ...(itemTitle(itemType) ? { title: itemTitle(itemType) } : {}),
491 ...(detail ? { detail } : {}),
492 ...(event.payload !== undefined ? { data: event.payload } : {}),
493 },
494 };
496​
497// ---------------------------------------------------------------------------
498// Main mapping function
499// ---------------------------------------------------------------------------
500​
501/**
502 * Known non-critical events that fire frequently but don't need mapping.
503 * Defined at module level so the Set isn't recreated on every call.
504 */
505const QUIET_UNMAPPED_EVENTS = new Set([
506 "file.watcher.updated",
507 "session.diff",
508 "session.created",
509 "mcp_startup_update",
510 "mcp_startup_complete",
511 "rate_limit_event",
512 "stream_event",
513 "hook_started",
514 "hook_response",
515 "user",
516 "thinking",
517 "codex/event/agent_message_delta",
518 "codex/event/agent_message",
519 "codex/event/agent_message_content_delta",
520 "codex/event/user_message",
521]);
522​
523export function mapToRuntimeEvents(
524 event: ProviderEvent,
525 canonicalThreadId: ThreadId,
526): ReadonlyArray<ProviderRuntimeEvent> {
527 const payload = asObject(event.payload);
528 const turn = asObject(payload?.turn);
529​
530 if (event.kind === "error") {
531 if (!event.message) {
532 return [];
533 }
534 return [
535 {
536 ...runtimeEventBase(event, canonicalThreadId),
537 type: "runtime.error",
538 payload: {
539 message: event.message,
540 class: "provider_error",
541 ...(event.payload !== undefined ? { detail: event.payload } : {}),
542 },
543 },
544 ];
545 }
546​
547 if (event.kind === "request") {
548 if (event.method === "item/tool/requestUserInput") {
549 const questions = toUserInputQuestions(payload);
550 if (!questions) {
551 return [];
552 }
553 return [
554 {
555 ...runtimeEventBase(event, canonicalThreadId),
556 type: "user-input.requested",
557 payload: {
558 questions,
559 },
560 },
561 ];
562 }
563​
564 const detail =
565 asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt);
566 return [
567 {
568 ...runtimeEventBase(event, canonicalThreadId),
569 type: "request.opened",
570 payload: {
571 requestType: toRequestTypeFromMethod(event.method),
572 ...(detail ? { detail } : {}),
573 ...(event.payload !== undefined ? { args: event.payload } : {}),
574 },
575 },
576 ];
577 }
578​
579 if (event.method === "item/requestApproval/decision" && event.requestId) {
580 let decision: typeof ProviderApprovalDecision.Type | undefined;
581 try {
582 decision = Schema.decodeUnknownSync(ProviderApprovalDecision)(payload?.decision);
583 } catch {
584 decision = undefined;
585 }
586 const requestType =
587 event.requestKind !== undefined
588 ? toRequestTypeFromKind(event.requestKind)
589 : toRequestTypeFromMethod(event.method);
590 return [
591 {
592 ...runtimeEventBase(event, canonicalThreadId),
593 type: "request.resolved",
594 payload: {
595 requestType,
596 ...(decision ? { decision } : {}),
597 ...(event.payload !== undefined ? { resolution: event.payload } : {}),
598 },
599 },
600 ];
601 }
602​
603 if (event.method === "session/connecting") {
604 return [
605 {
606 ...runtimeEventBase(event, canonicalThreadId),
607 type: "session.state.changed",
608 payload: {
609 state: "starting",
610 ...(event.message ? { reason: event.message } : {}),
611 },
612 },
613 ];
614 }
615​
616 if (event.method === "session/ready") {
617 return [
618 {
619 ...runtimeEventBase(event, canonicalThreadId),
620 type: "session.state.changed",
621 payload: {
622 state: "ready",
623 ...(event.message ? { reason: event.message } : {}),
624 },
625 },
626 ];
627 }
628​
629 if (event.method === "session/started") {
630 return [
631 {
632 ...runtimeEventBase(event, canonicalThreadId),
633 type: "session.started",
634 payload: {
635 ...(event.message ? { message: event.message } : {}),
636 ...(event.payload !== undefined ? { resume: event.payload } : {}),
637 },
638 },
639 ];
640 }
641​
642 if (event.method === "session/exited" || event.method === "session/closed") {
643 return [
644 {
645 ...runtimeEventBase(event, canonicalThreadId),
646 type: "session.exited",
647 payload: {
648 ...(event.message ? { reason: event.message } : {}),
649 ...(event.method === "session/closed" ? { exitKind: "graceful" } : {}),
650 },
651 },
652 ];
653 }
654​
655 if (event.method === "thread/started") {
656 const payloadThreadId = asString(asObject(payload?.thread)?.id);
657 const providerThreadId = payloadThreadId ?? asString(payload?.threadId);
658 if (!providerThreadId) {
659 return [];
660 }
661 return [
662 {
663 ...runtimeEventBase(event, canonicalThreadId),
664 type: "thread.started",
665 payload: {
666 providerThreadId,
667 },
668 },
669 ];
670 }
671​
672 if (
673 event.method === "thread/status/changed" ||
674 event.method === "thread/archived" ||
675 event.method === "thread/unarchived" ||
676 event.method === "thread/closed" ||
677 event.method === "thread/compacted"
678 ) {
679 return [
680 {
681 type: "thread.state.changed",
682 ...runtimeEventBase(event, canonicalThreadId),
683 payload: {
684 state:
685 event.method === "thread/archived"
686 ? "archived"
687 : event.method === "thread/closed"
688 ? "closed"
689 : event.method === "thread/compacted"
690 ? "compacted"
691 : toThreadState(asObject(payload?.thread)?.state ?? payload?.state),
692 ...(event.payload !== undefined ? { detail: event.payload } : {}),
693 },
694 },
695 ];
696 }
697​
698 if (event.method === "thread/name/updated") {
699 return [
700 {
701 type: "thread.metadata.updated",
702 ...runtimeEventBase(event, canonicalThreadId),
703 payload: {
704 ...(asString(payload?.threadName) ? { name: asString(payload?.threadName) } : {}),
705 ...(event.payload !== undefined ? { metadata: asObject(event.payload) } : {}),
706 },
707 },
708 ];
709 }
710​
711 if (event.method === "thread/tokenUsage/updated") {
712 return [
713 {
714 type: "thread.token-usage.updated",
715 ...runtimeEventBase(event, canonicalThreadId),
716 payload: {
717 usage: event.payload ?? {},
718 },
719 },
720 ];
721 }
722​
723 if (event.method === "turn/started") {
724 const turnId = event.turnId;
725 if (!turnId) {
726 return [];
727 }
728 return [
729 {
730 ...runtimeEventBase(event, canonicalThreadId),
731 turnId,
732 type: "turn.started",
733 payload: {
734 ...(asString(turn?.model) ? { model: asString(turn?.model) } : {}),
735 ...(asString(turn?.effort) ? { effort: asString(turn?.effort) } : {}),
736 },
737 },
738 ];
739 }
740​
741 if (event.method === "turn/completed") {
742 const errorMessage = asString(asObject(turn?.error)?.message);
743 return [
744 {
745 ...runtimeEventBase(event, canonicalThreadId),
746 type: "turn.completed",
747 payload: {
748 state: toTurnStatus(turn?.status),
749 ...(asString(turn?.stopReason) ? { stopReason: asString(turn?.stopReason) } : {}),
750 ...(turn?.usage !== undefined ? { usage: turn.usage } : {}),
751 ...(asObject(turn?.modelUsage) ? { modelUsage: asObject(turn?.modelUsage) } : {}),
752 ...(asNumber(turn?.totalCostUsd) !== undefined
753 ? { totalCostUsd: asNumber(turn?.totalCostUsd) }
754 : {}),
755 ...(errorMessage ? { errorMessage } : {}),
756 },
757 },
758 ];
759 }
760​
761 if (event.method === "turn/aborted") {
762 return [
763 {
764 ...runtimeEventBase(event, canonicalThreadId),
765 type: "turn.aborted",
766 payload: {
767 reason: event.message ?? "Turn aborted",
768 },
769 },
770 ];
771 }
772​
773 if (event.method === "turn/plan/updated") {
774 const steps = Array.isArray(payload?.plan) ? payload.plan : [];
775 return [
776 {
777 ...runtimeEventBase(event, canonicalThreadId),
778 type: "turn.plan.updated",
779 payload: {
780 ...(asString(payload?.explanation)
781 ? { explanation: asString(payload?.explanation) }
782 : {}),
783 plan: steps
784 .map((entry) => asObject(entry))
785 .filter((entry): entry is Record<string, unknown> => entry !== undefined)
786 .map((entry) => ({
787 step: asString(entry.step) ?? "step",
788 status:
789 entry.status === "completed" || entry.status === "inProgress"
790 ? entry.status
791 : "pending",
792 })),
793 },
794 },
795 ];
796 }
797​
798 if (event.method === "turn/diff/updated") {
799 return [
800 {
801 ...runtimeEventBase(event, canonicalThreadId),
802 type: "turn.diff.updated",
803 payload: {
804 unifiedDiff:
805 asString(payload?.unifiedDiff) ??
806 asString(payload?.diff) ??
807 asString(payload?.patch) ??
808 "",
809 },
810 },
811 ];
812 }
813​
814 if (event.method === "item/started") {
815 const started = mapItemLifecycle(event, canonicalThreadId, "item.started");
816 return started ? [started] : [];
817 }
818​
819 if (event.method === "item/completed") {
820 const payload = asObject(event.payload);
821 const item = asObject(payload?.item);
822 const source = item ?? payload;
823 if (!source) {
824 return [];
825 }
826 const itemType = source ? toCanonicalItemType(source.type ?? source.kind) : "unknown";
827 if (itemType === "plan") {
828 const detail = itemDetail(source, payload ?? {});
829 if (!detail) {
830 return [];
831 }
832 return [
833 {
834 ...runtimeEventBase(event, canonicalThreadId),
835 type: "turn.proposed.completed",
836 payload: {
837 planMarkdown: detail,
838 },
839 },
840 ];
841 }
842 const completed = mapItemLifecycle(event, canonicalThreadId, "item.completed");
843 return completed ? [completed] : [];
844 }
845​
846 if (
847 event.method === "item/reasoning/summaryPartAdded" ||
848 event.method === "item/commandExecution/terminalInteraction"
849 ) {
850 const updated = mapItemLifecycle(event, canonicalThreadId, "item.updated");
851 return updated ? [updated] : [];
852 }
853​
854 if (event.method === "item/plan/delta") {
855 const delta =
856 event.textDelta ??
857 asString(payload?.delta) ??
858 asString(payload?.text) ??
859 asString(asObject(payload?.content)?.text);
860 if (!delta || delta.length === 0) {
861 return [];
862 }
863 return [
864 {
865 ...runtimeEventBase(event, canonicalThreadId),
866 type: "turn.proposed.delta",
867 payload: {
868 delta,
869 },
870 },
871 ];
872 }
873​
874 if (
875 event.method === "item/agentMessage/delta" ||
876 event.method === "item/commandExecution/outputDelta" ||
877 event.method === "item/fileChange/outputDelta" ||
878 event.method === "item/reasoning/summaryTextDelta" ||
879 event.method === "item/reasoning/textDelta"
880 ) {
881 const delta =
882 event.textDelta ??
883 asString(payload?.delta) ??
884 asString(payload?.text) ??
885 asString(asObject(payload?.content)?.text);
886 if (!delta || delta.length === 0) {
887 return [];
888 }
889 return [
890 {
891 ...runtimeEventBase(event, canonicalThreadId),
892 type: "content.delta",
893 payload: {
894 streamKind: contentStreamKindFromMethod(event.method),
895 delta,
896 ...(typeof payload?.contentIndex === "number"
897 ? { contentIndex: payload.contentIndex }
898 : {}),
899 ...(typeof payload?.summaryIndex === "number"
900 ? { summaryIndex: payload.summaryIndex }
901 : {}),
902 },
903 },
904 ];
905 }
906​
907 if (event.method === "item/mcpToolCall/progress") {
908 return [
909 {
910 ...runtimeEventBase(event, canonicalThreadId),
911 type: "tool.progress",
912 payload: {
913 ...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}),
914 ...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}),
915 ...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}),
916 ...(asNumber(payload?.elapsedSeconds) !== undefined
917 ? { elapsedSeconds: asNumber(payload?.elapsedSeconds) }
918 : {}),
919 },
920 },
921 ];
922 }
923​
924 if (event.method === "serverRequest/resolved") {
925 const requestType =
926 toRequestTypeFromResolvedPayload(payload) !== "unknown"
927 ? toRequestTypeFromResolvedPayload(payload)
928 : event.requestId && event.requestKind !== undefined
929 ? toRequestTypeFromKind(event.requestKind)
930 : "unknown";
931 return [
932 {
933 ...runtimeEventBase(event, canonicalThreadId),
934 type: "request.resolved",
935 payload: {
936 requestType,
937 ...(event.payload !== undefined ? { resolution: event.payload } : {}),
938 },
939 },
940 ];
941 }
942​
943 if (event.method === "item/tool/requestUserInput/answered") {
944 return [
945 {
946 ...runtimeEventBase(event, canonicalThreadId),
947 type: "user-input.resolved",
948 payload: {
949 answers: toCanonicalUserInputAnswers(
950 asObject(event.payload)?.answers as ProviderUserInputAnswers | undefined,
951 ),
952 },
953 },
954 ];
955 }
956​
957 if (event.method === "codex/event/task_started") {
958 const msg = codexEventMessage(payload);
959 const taskId = asString(payload?.id) ?? asString(msg?.turn_id);
960 if (!taskId) {
961 return [];
962 }
963 return [
964 {
965 ...codexEventBase(event, canonicalThreadId),
966 type: "task.started",
967 payload: {
968 taskId: asRuntimeTaskId(taskId),
969 ...(asString(msg?.collaboration_mode_kind)
970 ? { taskType: asString(msg?.collaboration_mode_kind) }
971 : {}),
972 },
973 },
974 ];
975 }
976​
977 if (event.method === "codex/event/task_complete") {
978 const msg = codexEventMessage(payload);
979 const taskId = asString(payload?.id) ?? asString(msg?.turn_id);
980 const proposedPlanMarkdown = extractProposedPlanMarkdown(asString(msg?.last_agent_message));
981 if (!taskId) {
982 if (!proposedPlanMarkdown) {
983 return [];
984 }
985 return [
986 {
987 ...codexEventBase(event, canonicalThreadId),
988 type: "turn.proposed.completed",
989 payload: {
990 planMarkdown: proposedPlanMarkdown,
991 },
992 },
993 ];
994 }
995 const events: ProviderRuntimeEvent[] = [
996 {
997 ...codexEventBase(event, canonicalThreadId),
998 type: "task.completed",
999 payload: {
1000 taskId: asRuntimeTaskId(taskId),
1001 status: "completed",
1002 ...(asString(msg?.last_agent_message)
1003 ? { summary: asString(msg?.last_agent_message) }
1004 : {}),
1005 },
1006 },
1007 ];
1008 if (proposedPlanMarkdown) {
1009 events.push({
1010 ...codexEventBase(event, canonicalThreadId),
1011 type: "turn.proposed.completed",
1012 payload: {
1013 planMarkdown: proposedPlanMarkdown,
1014 },
1015 });
1017 return events;
1019​
1020 if (event.method === "codex/event/agent_reasoning") {
1021 const msg = codexEventMessage(payload);
1022 const taskId = asString(payload?.id);
1023 const description = asString(msg?.text);
1024 if (!taskId || !description) {
1025 return [];
1027 return [
1029 ...codexEventBase(event, canonicalThreadId),
1030 type: "task.progress",
1031 payload: {
1032 taskId: asRuntimeTaskId(taskId),
1033 description,
1034 },
1035 },
1036 ];
1038​
1039 if (event.method === "codex/event/reasoning_content_delta") {
1040 const msg = codexEventMessage(payload);
1041 const delta = asString(msg?.delta);
1042 if (!delta) {
1043 return [];
1045 return [
1047 ...codexEventBase(event, canonicalThreadId),
1048 type: "content.delta",
1049 payload: {
1050 streamKind:
1051 asNumber(msg?.summary_index) !== undefined
1052 ? "reasoning_summary_text"
1053 : "reasoning_text",
1054 delta,
1055 ...(asNumber(msg?.summary_index) !== undefined
1056 ? { summaryIndex: asNumber(msg?.summary_index) }
1057 : {}),
1058 },
1059 },
1060 ];
1062​
1063 if (event.method === "model/rerouted") {
1064 return [
1066 type: "model.rerouted",
1067 ...runtimeEventBase(event, canonicalThreadId),
1068 payload: {
1069 fromModel: asString(payload?.fromModel) ?? "unknown",
1070 toModel: asString(payload?.toModel) ?? "unknown",
1071 reason: asString(payload?.reason) ?? "unknown",
1072 },
1073 },
1074 ];
1076​
1077 if (event.method === "deprecationNotice") {
1078 return [
1080 type: "deprecation.notice",
1081 ...runtimeEventBase(event, canonicalThreadId),
1082 payload: {
1083 summary: asString(payload?.summary) ?? "Deprecation notice",
1084 ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
1085 },
1086 },
1087 ];
1089​
1090 if (event.method === "configWarning") {
1091 return [
1093 type: "config.warning",
1094 ...runtimeEventBase(event, canonicalThreadId),
1095 payload: {
1096 summary: asString(payload?.summary) ?? "Configuration warning",
1097 ...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
1098 ...(asString(payload?.path) ? { path: asString(payload?.path) } : {}),
1099 ...(payload?.range !== undefined ? { range: payload.range } : {}),
1100 },
1101 },
1102 ];
1104​
1105 if (event.method === "account/updated") {
1106 return [
1108 type: "account.updated",
1109 ...runtimeEventBase(event, canonicalThreadId),
1110 payload: {
1111 account: event.payload ?? {},
1112 },
1113 },
1114 ];
1116​
1117 if (event.method === "account/rateLimits/updated") {
1118 return [
1120 type: "account.rate-limits.updated",
1121 ...runtimeEventBase(event, canonicalThreadId),
1122 payload: {
1123 rateLimits: event.payload ?? {},
1124 },
1125 },
1126 ];
1128​
1129 if (event.method === "mcpServer/oauthLogin/completed") {
1130 return [
1132 type: "mcp.oauth.completed",
1133 ...runtimeEventBase(event, canonicalThreadId),
1134 payload: {
1135 success: payload?.success === true,
1136 ...(asString(payload?.name) ? { name: asString(payload?.name) } : {}),
1137 ...(asString(payload?.error) ? { error: asString(payload?.error) } : {}),
1138 },
1139 },
1140 ];
1142​
1143 if (event.method === "thread/realtime/started") {
1144 const realtimeSessionId = asString(payload?.realtimeSessionId);
1145 return [
1147 type: "thread.realtime.started",
1148 ...runtimeEventBase(event, canonicalThreadId),
1149 payload: {
1150 realtimeSessionId,
1151 },
1152 },
1153 ];
1155​
1156 if (event.method === "thread/realtime/itemAdded") {
1157 return [
1159 type: "thread.realtime.item-added",
1160 ...runtimeEventBase(event, canonicalThreadId),
1161 payload: {
1162 item: event.payload ?? {},
1163 },
1164 },
1165 ];
1167​
1168 if (event.method === "thread/realtime/outputAudio/delta") {
1169 return [
1171 type: "thread.realtime.audio.delta",
1172 ...runtimeEventBase(event, canonicalThreadId),
1173 payload: {
1174 audio: event.payload ?? {},
1175 },
1176 },
1177 ];
1179​
1180 if (event.method === "thread/realtime/error") {
1181 const message = asString(payload?.message) ?? event.message ?? "Realtime error";
1182 return [
1184 type: "thread.realtime.error",
1185 ...runtimeEventBase(event, canonicalThreadId),
1186 payload: {
1187 message,
1188 },
1189 },
1190 ];
1192​
1193 if (event.method === "thread/realtime/closed") {
1194 return [
1196 type: "thread.realtime.closed",
1197 ...runtimeEventBase(event, canonicalThreadId),
1198 payload: {
1199 reason: event.message,
1200 },
1201 },
1202 ];
1204​
1205 if (event.method === "error") {
1206 const message =
1207 asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error";
1208 const willRetry = payload?.willRetry === true;
1209 return [
1211 type: willRetry ? "runtime.warning" : "runtime.error",
1212 ...runtimeEventBase(event, canonicalThreadId),
1213 payload: {
1214 message,
1215 ...(!willRetry ? { class: "provider_error" as const } : {}),
1216 ...(event.payload !== undefined ? { detail: event.payload } : {}),
1217 },
1218 },
1219 ];
1221​
1222 if (event.method === "windows/worldWritableWarning") {
1223 return [
1225 type: "runtime.warning",
1226 ...runtimeEventBase(event, canonicalThreadId),
1227 payload: {
1228 message: event.message ?? "Windows world-writable warning",
1229 ...(event.payload !== undefined ? { detail: event.payload } : {}),
1230 },
1231 },
1232 ];
1234​
1235 if (event.method === "windowsSandbox/setupCompleted") {
1236 const payloadRecord = asObject(event.payload);
1237 const success = payloadRecord?.success;
1238 const successMessage = event.message ?? "Windows sandbox setup completed";
1239 const failureMessage = event.message ?? "Windows sandbox setup failed";
1240​
1241 return [
1243 type: "session.state.changed",
1244 ...runtimeEventBase(event, canonicalThreadId),
1245 payload: {
1246 state: success === false ? "error" : "ready",
1247 reason: success === false ? failureMessage : successMessage,
1248 ...(event.payload !== undefined ? { detail: event.payload } : {}),
1249 },
1250 },
1251 ...(success === false
1252 ? [
1254 type: "runtime.warning" as const,
1255 ...runtimeEventBase(event, canonicalThreadId),
1256 payload: {
1257 message: failureMessage,
1258 ...(event.payload !== undefined ? { detail: event.payload } : {}),
1259 },
1260 },
1262 : []),
1263 ];
1265​
1266 // ---------------------------------------------------------------------------
1267 // Raw Codex events (codex/event/* prefix) — mapped to canonical runtime events
1268 // ---------------------------------------------------------------------------
1269​
1270 if (event.method === "codex/event/exec_command_begin") {
1271 const msg = asObject(payload?.msg) ?? payload;
1272 const command = asArray(msg?.command)?.join(" ") ?? asString(msg?.command);
1273 return [
1275 ...codexEventBase(event, canonicalThreadId),
1276 type: "item.started" as const,
1277 payload: {
1278 itemType: "command_execution" as CanonicalItemType,
1279 ...(command ? { title: command } : {}),
1280 ...(msg ? { data: { item: msg } } : {}),
1281 },
1282 },
1283 ];
1285​
1286 if (event.method === "codex/event/exec_command_end") {
1287 const msg = asObject(payload?.msg) ?? payload;
1288 const command = asArray(msg?.command)?.join(" ") ?? asString(msg?.command);
1289 const detail =
1290 asString(msg?.formatted_output) ?? asString(msg?.aggregated_output) ?? asString(msg?.stdout);
1291 return [
1293 ...codexEventBase(event, canonicalThreadId),
1294 type: "item.completed" as const,
1295 payload: {
1296 itemType: "command_execution" as CanonicalItemType,
1297 ...(command ? { title: command } : {}),
1298 ...(detail ? { detail } : {}),
1299 ...(msg ? { data: { item: msg } } : {}),
1300 },
1301 },
1302 ];
1304​
1305 if (event.method === "codex/event/exec_command_output_delta") {
1306 const msg = asObject(payload?.msg) ?? payload;
1307 const chunk = asString(msg?.chunk);
1308 if (!chunk) return [];
1309 // Codex sends base64-encoded output chunks
1310 let delta: string;
1311 try {
1312 delta = Buffer.from(chunk, "base64").toString("utf-8");
1313 } catch {
1314 return [];
1316 if (!delta) return [];
1317 return [
1319 ...codexEventBase(event, canonicalThreadId),
1320 type: "content.delta" as const,
1321 payload: {
1322 streamKind: "command_output" as const,
1323 delta,
1324 },
1325 },
1326 ];
1328​
1329 if (
1330 event.method === "codex/event/item_started" ||
1331 event.method === "codex/event/item_completed"
1332 ) {
1333 const msg = asObject(payload?.msg) ?? payload;
1334 const item = asObject(msg?.item);
1335 const itemType = toCanonicalItemType(item?.type);
1336 // Skip user messages and agent messages (handled elsewhere)
1337 if (itemType === "user_message" || itemType === "assistant_message") return [];
1338 const title = itemTitle(itemType);
1339 const runtimeType =
1340 event.method === "codex/event/item_started" ? "item.started" : "item.completed";
1341 return [
1343 ...codexEventBase(event, canonicalThreadId),
1344 type: runtimeType as "item.started" | "item.completed",
1345 payload: {
1346 itemType,
1347 ...(title ? { title } : {}),
1348 ...(item ? { data: { item } } : {}),
1349 },
1350 },
1351 ];
1353​
1354 if (event.method === "codex/event/token_count") {
1355 const msg = asObject(payload?.msg) ?? payload;
1356 return [
1358 ...codexEventBase(event, canonicalThreadId),
1359 type: "thread.token-usage.updated" as const,
1360 payload: { usage: msg?.info ?? msg ?? {} },
1361 },
1362 ];
1364​
1365 // Log unmapped events to aid debugging — skip known-noisy non-critical ones.
1366 if (event.method && !QUIET_UNMAPPED_EVENTS.has(event.method)) {
1367 console.debug(`[codexEventMapping] unmapped event: ${event.method}`, event.payload ?? "");
1369 return [];