Repository navigation
Expand file tree
/
Copy pathCodexAdapterV2.ts
More file actions
7528 lines (7273 loc) · 304 KB
/
Copy pathCodexAdapterV2.ts
File metadata and controls
7528 lines (7273 loc) · 304 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { revertCodexThread } from "../../provider/CodexThreadRevert.ts";
import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget";
import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts";
import {
mcpToolPresentation,
type McpToolPresentation,
} from "../../provider/CodexToolPresentation.ts";
import {
makeCodexTurnTokenUsageState,
getCodexTurnAccumulator,
accumulateCodexTurnTokenUsage,
completeCodexTurnTokenUsage,
type CodexTurnTokenUsageState,
} from "../../provider/CodexTurnTokenUsage.ts";
import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot";
import type { CodexEffectiveRuntime } from "../../provider/CodexManagedRuntime.ts";
import {
buildCodexInitializeParams,
codexAppServerEnvironment,
codexDefaultReasoningEffortOverride,
} from "../../provider/CodexProvider.ts";
import {
codexRateLimitsToUpdate,
mergeCodexRateLimits,
codexUsageLimitResetAt,
type CodexRateLimitSnapshot,
} from "../../provider/codexUsageLimits.ts";
import {
CodexSettings,
defaultInstanceIdForDriver,
isOrchestrationV2WorkActive,
OrchestrationV2ProviderGoal,
ProviderDriverKind,
type ProviderSetupError,
} from "@t3tools/contracts";
import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
import { AgentScope } from "@t3tools/shared/AgentScope";
import * as HostProcess from "@t3tools/shared/HostProcess";
import {
COMPUTER_USE_TOOL_SOURCE,
dynamicToolSurface,
dynamicToolTitle,
} from "@t3tools/shared/toolActivity";
import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import type {
ChatAttachment,
OrchestrationV2AppThread,
OrchestrationV2ConversationMessage,
OrchestrationV2ExecutionNode,
ModelSelection,
OrchestrationV2PlanArtifact,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ProviderFailure,
OrchestrationV2ProviderRetry,
OrchestrationV2ProviderSession,
OrchestrationV2ProviderThread,
OrchestrationV2ProviderTurn,
OrchestrationV2PlanStep,
OrchestrationV2RuntimeRequest,
OrchestrationV2Subagent,
OrchestrationV2TurnItem,
ProviderUserInputAnswers,
ProviderApprovalDecision,
ProviderApprovalOption,
ProviderRequestKind,
ProviderThreadId,
ProviderTurnId,
ProviderInstanceId,
RuntimeMode,
RuntimeRequestId,
ThreadId,
} from "@t3tools/contracts";
import * as CodexClient from "effect-codex-app-server/client";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexSchema from "effect-codex-app-server/schema";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts";
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
import { ServerConfig } from "../../config.ts";
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import {
buildCodexAdditionalContext,
buildCodexDeveloperInstructions,
} from "../../provider/CodexDeveloperInstructions.ts";
import {
describeMcpElicitation,
toMcpElicitationResponse,
} from "../../provider/CodexMcpElicitation.ts";
import {
materializeCodexShadowHome,
resolveCodexHomeLayout,
} from "../../provider/Drivers/CodexHomeLayout.ts";
import {
boundProviderEventForLogging,
shouldPersistProviderEvent,
} from "../../provider/EventNdjsonLogger.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import { codexAppServerArgs, resolveCodexLaunchArgs } from "../../provider/codexLaunchArgs.ts";
import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import {
MCP_APP_EXTENSION_ID,
MCP_APP_MIME_TYPE,
MCP_APP_OUTPUT_KEY,
MCP_APP_RESOURCE_SCHEME,
} from "@t3tools/shared/mcpApp";
import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "@t3tools/provider-core/server/adapterDriver";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import { backgroundWorkNotification } from "@t3tools/provider-core/server/notification";
import {
makeProviderFailure,
makeProviderFailureTurnItem,
makeProviderRetryTurnItem,
} from "@t3tools/provider-core/server/failure";
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import {
isProviderNativeImageAttachment,
providerMessageTextWithAttachmentPaths,
} from "@t3tools/provider-core/server/attachmentPrompt";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
export const CODEX_DRIVER_KIND = CODEX_PROVIDER;
export const CODEX_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CODEX_DRIVER_KIND);
type CodexFileChangeKinds = Readonly<
Record<string, CodexSchema.V2ItemStartedNotification__PatchChangeKind>
>;
export function codexFileChangeApprovalPrompt(input: {
readonly reason?: string | null;
readonly grantRoot?: string | null;
readonly fileChanges?: CodexFileChangeKinds;
}): string | undefined {
const reason = input.reason?.trim();
if (reason) return reason;
const entries = Object.entries(input.fileChanges ?? {}).toSorted(([left], [right]) =>
left.localeCompare(right),
);
if (entries.length > 0) {
const described = entries.slice(0, 20).map(([path, change]) => {
const movePath = change.type === "update" ? change.move_path : undefined;
return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`;
});
const remaining = entries.length - described.length;
return remaining > 0 ? `${described.join("\n")}\n+${remaining} more` : described.join("\n");
}
return input.grantRoot?.trim() || undefined;
}
// Reasoning effort changes future generation, not the existing context's tokenizer
// or model window. All other option changes remain untrusted until new telemetry.
export function canReuseCodexContextUsage(previous: ModelSelection, next: ModelSelection): boolean {
return modelSelectionsEqual(
{
...previous,
options: (previous.options ?? []).filter((option) => option.id !== "reasoningEffort"),
},
{ ...next, options: (next.options ?? []).filter((option) => option.id !== "reasoningEffort") },
);
}
export function codexProviderTurnTokenUsage(
tokenUsage: CodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"],
updatedAt: string,
) {
return {
usedTokens: Math.max(0, tokenUsage.last.totalTokens),
maxTokens: tokenUsage.modelContextWindow ?? null,
inputTokens: Math.max(0, tokenUsage.last.inputTokens),
cachedInputTokens: Math.max(0, tokenUsage.last.cachedInputTokens),
outputTokens: Math.max(0, tokenUsage.last.outputTokens),
reasoningOutputTokens: Math.max(0, tokenUsage.last.reasoningOutputTokens),
updatedAt,
};
}
const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({});
const CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS = 50;
// Each plan flush stores the whole plan three times (node, plan, turn item), so
// flush at the cadence clients already see for assistant text.
const CODEX_PLAN_DELTA_FLUSH_INTERVAL_MS = 400;
const CodexBackgroundTerminalTerminateResponse = Schema.Struct({
terminated: Schema.Boolean,
});
const CodexBackgroundTerminalsListResponse = Schema.Struct({
data: Schema.Array(
Schema.Struct({
processId: Schema.String,
}),
),
nextCursor: Schema.NullOr(Schema.String),
});
type CodexBackgroundTerminalsListPage = typeof CodexBackgroundTerminalsListResponse.Type;
const decodeCodexBackgroundTerminalTerminateResponse = Schema.decodeUnknownEffect(
CodexBackgroundTerminalTerminateResponse,
);
const decodeCodexBackgroundTerminalsListResponse = Schema.decodeUnknownEffect(
CodexBackgroundTerminalsListResponse,
);
const CODEX_CLIENT_CAPABILITIES = {
experimentalApi: true,
optOutNotificationMethods: ["turn/diff/updated"],
extensions: { [MCP_APP_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME_TYPE] } },
} as const;
export const CodexProviderCapabilitiesV2 = {
sessions: {
supportsMultipleProviderThreadsPerSession: true,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: true,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: true,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: true,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: true,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
supportsSteeringByInterruptRestart: true,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: true,
streamsPlanText: true,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: true,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: true,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: true,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: true,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: true,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: true,
emitsSubagentLifecycle: true,
canWaitForSubagents: true,
canCloseSubagents: true,
canForkSubagentThread: true,
},
context: {
acceptsSystemContext: true,
acceptsDeveloperContext: true,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: true,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "strong",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
runtimePolicy: {
enforcement: "native",
},
} satisfies OrchestrationV2ProviderCapabilities;
function toProtocolError(
detail: string,
payload?: unknown,
): ProviderAdapter.ProviderAdapterProtocolError {
return new ProviderAdapter.ProviderAdapterProtocolError({
driver: CODEX_PROVIDER,
detail,
...(payload === undefined ? {} : { payload }),
});
}
function normalizeCodexCause(error: unknown): unknown {
return error;
}
function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {
return seconds === null || seconds === undefined
? DateTime.nowUnsafe()
: DateTime.makeUnsafe(seconds * 1000);
}
function codexUserMessageText(
content: ReadonlyArray<CodexSchema.V2ItemCompletedNotification__UserInput>,
): string {
return content
.flatMap((item) => (item.type === "text" ? [item.text] : []))
.join("\n")
.trim();
}
function mapCodexTurnStatus(
status: CodexSchema.V2TurnCompletedNotification__TurnStatus,
): OrchestrationV2ProviderTurn["status"] {
switch (status) {
case "completed":
return "completed";
case "interrupted":
return "interrupted";
case "failed":
return "failed";
case "inProgress":
return "running";
}
}
function providerTurnStatusToTerminal(
status: OrchestrationV2ProviderTurn["status"],
): Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }>["status"] {
switch (status) {
case "completed":
return "completed";
case "interrupted":
return "interrupted";
case "failed":
return "failed";
case "cancelled":
return "cancelled";
case "pending":
case "running":
return "failed";
}
}
function codexItemStatus(status: "inProgress" | "completed" | "failed" | "declined"): {
readonly node: OrchestrationV2ExecutionNode["status"];
readonly turnItem: OrchestrationV2TurnItem["status"];
readonly completed: boolean;
} {
switch (status) {
case "inProgress":
return { node: "running", turnItem: "running", completed: false };
case "completed":
return {
node: "completed",
turnItem: "completed",
completed: true,
};
case "failed":
return { node: "failed", turnItem: "failed", completed: true };
case "declined":
return {
node: "cancelled",
turnItem: "cancelled",
completed: true,
};
}
}
/**
* The composers let a skill be typed with any currency sigil (`€review`), but
* Codex only parses `$name` as a skill mention.
*/
export function codexSkillMentionText(text: string): string {
return text.replace(SKILL_MENTION_PATTERN, "$1$$$2");
}
const BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH = 200;
const BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH = 1_000;
export function codexBackgroundCommandDetail(item: {
readonly command: string;
readonly exitCode?: number | null | undefined;
readonly aggregatedOutput?: string | null | undefined;
}): string {
const command =
item.command.length > BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH
? `${item.command.slice(0, BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH)}...`
: item.command;
const exit =
item.exitCode === null || item.exitCode === undefined ? "" : ` (exit ${item.exitCode})`;
const output = (item.aggregatedOutput ?? "").trimEnd();
const outputTail =
output.length > BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH
? `...${output.slice(-BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH)}`
: output;
const header = `Background command completed${exit}: ${command}`;
return outputTail.length === 0 ? header : `${header}\n\nOutput tail:\n${outputTail}`;
}
export interface CodexDynamicToolProjection extends McpToolPresentation {
readonly toolName: string;
readonly title?: string;
readonly input: unknown;
readonly output?: unknown;
readonly status: OrchestrationV2TurnItem["status"];
}
function codexMcpToolOutput(
item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>,
): unknown | undefined {
const resultOutput =
item.result === null || item.result === undefined
? undefined
: item.result.structuredContent !== null && item.result.structuredContent !== undefined
? item.result.structuredContent
: item.result.content;
if (item.error === null || item.error === undefined) {
return resultOutput;
}
return resultOutput === undefined
? { error: item.error.message }
: { error: item.error.message, result: resultOutput };
}
// Reading an app's resource is one MCP round trip; a server that hangs must not
// hold the item (and the run's ingestion) open.
const MCP_APP_CAPTURE_TIMEOUT = "20 seconds";
function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined {
if (item.type !== "mcpToolCall") return undefined;
const uri = item.mcpAppUi?.resourceUri ?? item.mcpAppResourceUri ?? item.appContext?.resourceUri;
return typeof uri === "string" && uri.startsWith(MCP_APP_RESOURCE_SCHEME) ? uri : undefined;
}
function codexDynamicToolOutput(
item: Extract<CodexDynamicToolItem, { readonly type: "dynamicToolCall" }>,
): unknown | undefined {
if (item.contentItems !== null && item.contentItems !== undefined) {
return item.contentItems;
}
return item.success === false ? { success: false } : undefined;
}
export const projectCodexDynamicToolItem = Effect.fn("CodexAdapterV2.projectDynamicToolItem")(
function* (
item: CodexDynamicToolItem,
): Effect.fn.Return<CodexDynamicToolProjection, never, Crypto.Crypto> {
const output =
item.type === "mcpToolCall" ? codexMcpToolOutput(item) : codexDynamicToolOutput(item);
const toolName =
item.type === "mcpToolCall"
? `${item.server}.${item.tool}`
: [trimText(item.namespace), item.tool].filter(Boolean).join(".");
const presentation: McpToolPresentation =
item.type === "mcpToolCall" ? yield* mcpToolPresentation(item) : {};
const title =
dynamicToolTitle(toolName, item.arguments, presentation.title) ?? presentation.title;
const toolSurface = presentation.toolSurface ?? dynamicToolSurface(toolName, item.arguments);
const toolSource =
toolSurface === "computer" && presentation.toolSource?.kind !== "computer"
? COMPUTER_USE_TOOL_SOURCE
: presentation.toolSource;
const projection: CodexDynamicToolProjection = {
...presentation,
...(toolSurface ? { toolSurface } : {}),
...(toolSource ? { toolSource } : {}),
toolName,
...(title ? { title } : {}),
input: item.arguments,
status: codexItemStatus(item.status).turnItem,
};
return output === undefined ? projection : { ...projection, output };
},
);
function codexNativeItemRef(nativeItemId: string) {
return {
driver: CODEX_PROVIDER,
nativeId: nativeItemId,
strength: "strong" as const,
};
}
function trimText(value: string | null | undefined): string | undefined {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : undefined;
}
function nonEmptyText(value: string | null | undefined, fallback: string): string {
return trimText(value) ?? fallback;
}
function codexPlanStepStatus(
status: CodexSchema.V2TurnPlanUpdatedNotification__TurnPlanStepStatus,
): OrchestrationV2PlanStep["status"] {
switch (status) {
case "completed":
return "completed";
case "inProgress":
return "running";
case "pending":
return "pending";
}
}
function approvalDecisionToLegacyReviewDecision(
decision: ProviderApprovalDecision,
): CodexSchema.ExecCommandApprovalResponse__ReviewDecision {
switch (decision) {
case "accept":
return "approved";
case "acceptForSession":
case "acceptAlways":
return "approved_for_session";
case "decline":
return { denied: { rejection: "User declined the request." } };
case "cancel":
return "abort";
}
}
function providerRequestKindFromPermissions(
permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"],
): ProviderRequestKind {
if ((permissions.fileSystem?.write?.length ?? 0) > 0) {
return "file-change";
}
if ((permissions.fileSystem?.read?.length ?? 0) > 0) {
return "file-read";
}
return "command";
}
function permissionsResponseFromDecision(input: {
readonly decision: ProviderApprovalDecision;
readonly permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"];
}): CodexSchema.PermissionsRequestApprovalResponse {
if (input.decision !== "accept" && input.decision !== "acceptForSession") {
return { permissions: {}, scope: "turn" };
}
return {
permissions: input.permissions,
scope: input.decision === "acceptForSession" ? "session" : "turn",
};
}
function answerValueToStrings(value: unknown): ReadonlyArray<string> {
if (Array.isArray(value)) {
return value.map((item) => String(item));
}
if (typeof value === "string") {
return [value];
}
if (value === null || value === undefined) {
return [];
}
if (typeof value === "number" || typeof value === "boolean") {
return [String(value)];
}
return [JSON.stringify(value)];
}
function toCodexUserInputAnswers(
answers: ProviderUserInputAnswers,
allowedQuestionIds: ReadonlySet<string>,
): CodexSchema.ToolRequestUserInputResponse["answers"] {
return Object.fromEntries(
Object.entries(answers).flatMap(([questionId, value]) =>
allowedQuestionIds.has(questionId)
? [[questionId, { answers: [...answerValueToStrings(value)] }]]
: [],
),
);
}
function compactStrings(values: ReadonlyArray<string | null | undefined>): ReadonlyArray<string> {
return values.flatMap((value) => {
const trimmed = trimText(value);
return trimmed === undefined ? [] : [trimmed];
});
}
function webSearchPatterns(item: CodexWebSearchItem): ReadonlyArray<string> {
if (item.action === null || item.action === undefined) {
return compactStrings([item.query]);
}
switch (item.action.type) {
case "search":
return compactStrings([...(item.action.queries ?? []), item.action.query, item.query]);
case "openPage":
return compactStrings([item.action.url, item.query]);
case "findInPage":
return compactStrings([item.action.pattern, item.action.url, item.query]);
case "other":
return compactStrings([item.query]);
}
}
const decodeTurnApprovalPolicy = Schema.decodeUnknownEffect(
Schema.Union([CodexSchema.V2TurnStartParams__AskForApproval, Schema.Null]),
);
const decodeTurnSandboxPolicy = Schema.decodeUnknownEffect(
Schema.Union([CodexSchema.V2TurnStartParams__SandboxPolicy, Schema.Null]),
);
const decodeTurnReasoningEffort = Schema.decodeUnknownEffect(
Schema.Union([CodexSchema.V2TurnStartParams__ReasoningEffort, Schema.Null]),
);
const CodexTurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams.pipe(
Schema.fieldsAssign({
collaborationMode: Schema.optionalKey(CodexSchema.ClientRequest__CollaborationMode),
additionalContext: Schema.optionalKey(
Schema.Record(Schema.String, CodexSchema.V2TurnStartParams__AdditionalContextEntry),
),
}),
);
type CodexTurnStartParamsWithCollaborationMode =
typeof CodexTurnStartParamsWithCollaborationMode.Type;
const decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect(
CodexTurnStartParamsWithCollaborationMode,
);
const isProviderAdapterRuntimeRequestResponseError = Schema.is(
ProviderAdapter.ProviderAdapterRuntimeRequestResponseError,
);
function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): {
readonly approvalPolicy: CodexSchema.V2TurnStartParams__AskForApproval;
readonly approvalsReviewer: CodexSchema.V2TurnStartParams__ApprovalsReviewer;
readonly sandboxPolicy: CodexSchema.V2TurnStartParams__SandboxPolicy;
} {
switch (runtimeMode) {
case "approval-required":
return {
approvalPolicy: "untrusted",
approvalsReviewer: "user",
sandboxPolicy: {
type: "readOnly",
},
};
case "auto-accept-edits":
return {
approvalPolicy: "on-request",
approvalsReviewer: "user",
sandboxPolicy: {
type: "workspaceWrite",
},
};
case "auto":
return {
approvalPolicy: "on-request",
approvalsReviewer: "auto_review",
sandboxPolicy: {
type: "workspaceWrite",
},
};
case "full-access":
return {
approvalPolicy: "never",
approvalsReviewer: "user",
sandboxPolicy: {
type: "dangerFullAccess",
},
};
}
}
export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTurnStartParams")(
function* (input: {
readonly nativeThreadId: string;
readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly modelSelection: ModelSelection;
readonly hasT3Mcp?: boolean;
readonly browserToolsAvailable?: boolean;
readonly deviceToolsAvailable?: boolean;
/** ChatGPT token sharing does not accept service tiers. */
readonly omitServiceTier?: boolean;
readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"];
}) {
const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);
const approvalPolicy =
input.runtimePolicy.approvalPolicy === undefined
? runtimeModeDefaults.approvalPolicy
: yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);
const sandboxPolicy =
input.runtimePolicy.sandboxPolicy === undefined
? runtimeModeDefaults.sandboxPolicy
: yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);
const selectedEffort =
getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") ??
codexDefaultReasoningEffortOverride(input.modelSelection.model);
const effort =
selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort);
const serviceTier =
input.omitServiceTier === true
? undefined
: getCodexServiceTierOptionValue(input.modelSelection);
const developerInstructions =
input.hasT3Mcp !== true
? undefined
: buildCodexDeveloperInstructions(input.runtimePolicy.interactionMode);
// An app's context is text an MCP server wrote, so it goes in as untrusted
// context: Codex renders it as quoted user-side input, never as developer
// instructions.
const appContext = Object.fromEntries(
(input.appContext ?? []).map((entry) => [
entry.key,
{ kind: "untrusted" as const, value: entry.text },
]),
);
const t3Context =
input.hasT3Mcp === true
? buildCodexAdditionalContext(
{ model: input.modelSelection.model, reasoningEffort: effort ?? undefined },
{
browser: input.browserToolsAvailable ?? true,
device: input.deviceToolsAvailable ?? false,
},
)
: undefined;
const additionalContext =
t3Context === undefined && Object.keys(appContext).length === 0
? undefined
: { ...t3Context, ...appContext };
const collaborationMode: CodexSchema.ClientRequest__CollaborationMode | undefined =
input.runtimePolicy.interactionMode !== "plan" && developerInstructions === undefined
? undefined
: {
mode: input.runtimePolicy.interactionMode === "plan" ? "plan" : "default",
settings: {
model: input.modelSelection.model,
// Codex falls back to the model's default effort when this is left out.
...(effort === undefined ? {} : { reasoning_effort: effort }),
...(developerInstructions === undefined
? {}
: { developer_instructions: developerInstructions }),
},
};
return yield* decodeCodexTurnStartParamsWithCollaborationMode({
threadId: input.nativeThreadId,
input: input.codexInput,
...(additionalContext ? { additionalContext } : {}),
cwd: input.runtimePolicy.cwd,
model: input.modelSelection.model,
// Model catalogues can default summaries to "none". Request them on every
// turn, including resumed threads, for T3's reasoning timeline.
summary: "detailed",
// Always explicit: omitting this on resume leaves Codex's previous
// reviewer sticky after switching away from Auto mode.
approvalsReviewer: runtimeModeDefaults.approvalsReviewer,
...(approvalPolicy === undefined ? {} : { approvalPolicy }),
...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
...(effort === undefined ? {} : { effort }),
...(serviceTier === undefined ? {} : { serviceTier }),
...(collaborationMode === undefined ? {} : { collaborationMode }),
});
},
);
function providerSession(input: {
readonly providerSessionId: OrchestrationV2ProviderSession["id"];
readonly providerInstanceId: ProviderInstanceId;
readonly cwd: string | null;
readonly model: string;
readonly now: DateTime.Utc;
}): OrchestrationV2ProviderSession {
return {
id: input.providerSessionId,
driver: CODEX_PROVIDER,
providerInstanceId: input.providerInstanceId,
status: "ready",
cwd: input.cwd ?? process.cwd(),
model: input.model,
capabilities: CodexProviderCapabilitiesV2,
createdAt: input.now,
updatedAt: input.now,
lastError: null,
};
}
const getNativeThreadId = Effect.fn("CodexAdapterV2.getNativeThreadId")(function* (
providerThread: OrchestrationV2ProviderThread,
) {
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
if (nativeThreadId === undefined || nativeThreadId === null) {
return yield* toProtocolError(
`Provider thread ${providerThread.id} is missing a native Codex thread id.`,
);
}
return nativeThreadId;
});
function providerThreadFromCodexThread(input: {
readonly appThreadId: ThreadId | null;
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
readonly ownerNodeId: OrchestrationV2ProviderThread["ownerNodeId"];
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
readonly providerInstanceId: ProviderInstanceId;
readonly thread: {
readonly createdAt: number;
readonly forkedFromId?: string | null;
readonly id: string;
readonly updatedAt: number;
};
readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"];
}): OrchestrationV2ProviderThread {
return {
id: input.idAllocator.derive.providerThread({
driver: CODEX_PROVIDER,
nativeThreadId: input.thread.id,
}),
driver: CODEX_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId,
nativeThreadRef: {
driver: CODEX_PROVIDER,
nativeId: input.thread.id,
strength: "strong" as const,
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: input.forkedFrom ?? null,
createdAt: codexTimestamp(input.thread.createdAt),
updatedAt: codexTimestamp(input.thread.updatedAt),
};
}
// Counts toward native rollback. `/goal` control turns never reach Codex and
// carry no native ref, so they must not consume a native turn on revert.
const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
turn.nativeTurnRef !== null &&
(turn.status === "completed" ||
turn.status === "interrupted" ||
turn.status === "failed" ||
turn.status === "cancelled");
export type CodexGoalCommand =
| { readonly type: "show" }
| { readonly type: "clear" }
| { readonly type: "pause" }
| { readonly type: "resume" }
| { readonly type: "set"; readonly objective: string };
export function parseCodexGoalCommand(text: string): CodexGoalCommand | null {
const match = /^\/goal(?:\s+([\s\S]*))?$/u.exec(text.trim());
if (match === null) return null;
const argument = (match[1] ?? "").trim();
switch (argument.toLowerCase()) {
case "":
case "edit":
return { type: "show" };
case "clear":
return { type: "clear" };
case "pause":
return { type: "pause" };
case "resume":
return { type: "resume" };
default:
return { type: "set", objective: argument };
}
}
type CodexThreadGoal = CodexSchema.V2ThreadGoalUpdatedNotification["goal"];
const CODEX_GOAL_STATUSES = {
active: "active",
paused: "paused",
blocked: "blocked",
usageLimited: "usage_limited",
budgetLimited: "budget_limited",
complete: "complete",
} as const satisfies Record<CodexThreadGoal["status"], OrchestrationV2ProviderGoal["status"]>;
function providerGoalFromCodex(goal: CodexThreadGoal): OrchestrationV2ProviderGoal | null {
const objective = goal.objective.trim();
if (objective.length === 0) return null;
return {
objective,
status: CODEX_GOAL_STATUSES[goal.status],
tokensUsed: Math.max(0, goal.tokensUsed),
tokenBudget: goal.tokenBudget ?? null,
timeUsedSeconds: Math.max(0, goal.timeUsedSeconds),
};
}
const providerGoalsEqual = Schema.toEquivalence(Schema.NullOr(OrchestrationV2ProviderGoal));
function describeCodexGoal(goal: OrchestrationV2ProviderGoal): string {
return `Goal ${goal.status.replace("_", " ")}: ${goal.objective}`;
}
// Codex starts the next goal turn milliseconds after the last one completes.
const CODEX_GOAL_CONTINUATION_GRACE = "5 seconds";
const providerTurnsForThread = (
providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
providerThread: OrchestrationV2ProviderThread,
): ReadonlyArray<OrchestrationV2ProviderTurn> =>
providerTurns.filter((turn) => turn.providerThreadId === providerThread.id);
const countTerminalTurnsAfterBoundary = (
providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
providerTurnId: ProviderTurnId,
): number | null => {
const boundaryTurn = providerTurns.find((turn) => turn.id === providerTurnId);
if (boundaryTurn === undefined) {
return null;
}
return providerTurns.filter(
(turn) => turn.ordinal > boundaryTurn.ordinal && isTerminalProviderTurn(turn),
).length;
};
const resolveCodexForkRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveForkRollbackTurnCount")(
function* (input: ProviderAdapter.ProviderAdapterV2ForkThreadInput) {
if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) {
return 0;
}
const rollbackTurnCount = countTerminalTurnsAfterBoundary(
providerTurnsForThread(input.sourceProviderTurns, input.sourceProviderThread),
input.providerTurnId,
);
if (rollbackTurnCount === null) {
return yield* new ProviderAdapter.ProviderAdapterForkThreadError({
driver: CODEX_PROVIDER,
providerThreadId: input.sourceProviderThread.id,
cause: `Cannot fork Codex thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`,
});
}
return rollbackTurnCount;
},
);
/**
* `lastTurnId` is inclusive on the Codex side, so a fork requested at the
* selected turn omits every later turn atomically. That matters for paginated
* threads.
*/