-
-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathcodexGateway.ts
More file actions
3531 lines (3215 loc) · 121 KB
/
Copy pathcodexGateway.ts
File metadata and controls
3531 lines (3215 loc) · 121 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 {
fetchRpcMethodCatalog,
fetchRpcNotificationCatalog,
fetchPendingServerRequests,
rpcCall,
respondServerRequest,
subscribeRpcNotifications,
type RpcNotification,
} from './codexRpcClient'
import type {
CollaborationModeListResponse,
ConfigReadResponse,
GetAccountRateLimitsResponse,
ModelListResponse,
ReasoningEffort,
ThreadForkResponse,
ThreadListResponse,
ThreadReadResponse,
ThreadResumeResponse,
ThreadStartResponse,
Turn,
} from './appServerDtos'
import { extractErrorMessage, normalizeCodexApiError } from './codexErrors'
import {
readActiveTurnIdFromResponse,
normalizeThreadGroupsV2,
normalizeThreadMessagesV2,
normalizeThreadSummaryV2,
readThreadInProgressFromResponse,
} from './normalizers/v2'
import type {
SpeedMode,
UiAccountEntry,
UiAccountQuotaStatus,
UiAccountUnavailableReason,
CollaborationModeKind,
CollaborationModeOption,
UiCreditsSnapshot,
UiFileChange,
UiMessage,
UiProjectGroup,
UiThread,
UiReviewAction,
UiReviewActionLevel,
UiReviewFile,
UiReviewFinding,
UiReviewHunk,
UiReviewLine,
UiReviewResult,
UiReviewScope,
UiReviewSnapshot,
UiReviewSummary,
UiReviewWorkspaceView,
UiRateLimitSnapshot,
UiRateLimitWindow,
UiThreadAutomation,
UiThreadAutomationStatus,
} from '../types/codex'
import { normalizePathForUi } from '../pathUtils.js'
type CurrentModelConfig = {
model: string
providerId: string
reasoningEffort: ReasoningEffort | ''
speedMode: SpeedMode
}
export type DirectoryPluginSummary = {
id: string
name: string
displayName: string
description: string
longDescription: string
developerName: string
category: string
marketplaceName: string
marketplaceDisplayName: string
marketplacePath: string | null
remoteMarketplaceName: string | null
sourceType: string
sourceUrl: string
installed: boolean
enabled: boolean
installPolicy: string
authPolicy: string
logoUrl: string
logoPath: string
composerIconUrl: string
composerIconPath: string
brandColor: string
capabilities: string[]
defaultPrompt: string[]
screenshotUrls: string[]
screenshots: string[]
websiteUrl: string
privacyPolicyUrl: string
termsOfServiceUrl: string
}
export type DirectoryPluginDetail = {
summary: DirectoryPluginSummary
description: string
apps: DirectoryPluginAppSummary[]
skills: DirectoryPluginSkillSummary[]
mcpServers: string[]
}
export type DirectoryPluginAppSummary = {
id: string
name: string
description: string
installUrl: string
needsAuth: boolean
}
export type DirectoryPluginSkillSummary = {
name: string
description: string
path: string
enabled: boolean
displayName: string
shortDescription: string
}
export type DirectoryPluginInstallResult = {
authPolicy: string
appsNeedingAuth: DirectoryPluginAppSummary[]
}
export type DirectoryAppInfo = {
id: string
name: string
description: string
logoUrl: string
logoUrlDark: string
distributionChannel: string
installUrl: string
isAccessible: boolean
isEnabled: boolean
pluginDisplayNames: string[]
category: string
developer: string
website: string
privacyPolicy: string
termsOfService: string
catalogRank: number
}
export type DirectoryMcpServerStatus = {
name: string
authStatus: string
tools: Array<{ name: string; title: string; description: string }>
resources: Array<{ name: string; title: string; uri: string; description: string }>
resourceTemplates: Array<{ name: string; title: string; uriTemplate: string; description: string }>
}
export type DirectoryMcpLoginResult = {
authorizationUrl: string
}
export type DirectoryComposioStatus = {
available: boolean
authenticated: boolean
cliVersion: string
email: string
defaultOrgName: string
defaultOrgId: string
webUrl: string
baseUrl: string
testUserId: string
}
export type DirectoryComposioConnection = {
id: string
wordId: string
alias: string
status: string
authScheme: string
createdAt: string
updatedAt: string
isComposioManaged: boolean
isDisabled: boolean
}
export type DirectoryComposioConnector = {
slug: string
name: string
description: string
logoUrl: string
latestVersion: string
toolsCount: number
triggersCount: number
isNoAuth: boolean
enabled: boolean
authModes: string[]
activeCount: number
totalConnections: number
connectionStatuses: string[]
}
export type DirectoryComposioTool = {
slug: string
name: string
description: string
}
export type DirectoryComposioConnectorDetail = {
connector: DirectoryComposioConnector
connections: DirectoryComposioConnection[]
tools: DirectoryComposioTool[]
dashboardUrl: string
}
export type DirectoryComposioLinkResult = {
status: string
message: string
connectedAccountId: string
redirectUrl: string
toolkit: string
projectType: string
}
export type DirectoryComposioLoginResult = {
status: string
message: string
loginUrl: string
cliKey: string
expiresAt: string
}
export type ComposerPromptInfo = {
name: string
path: string
content: string
description: string
}
export type DirectoryComposioInstallResult = {
ok: boolean
command: string
output: string
}
export type DirectoryComposioLogoutResult = {
ok: boolean
command: string
output: string
}
type DirectoryComposioConnectorPage = {
data: DirectoryComposioConnector[]
nextCursor: string | null
total: number
}
type ProviderModelsResponse = {
data?: unknown
exclusive?: unknown
}
const PROVIDER_MODELS_FETCH_TIMEOUT_MS = 5_000
type ResolvedCollaborationModeSettings = {
model: string
reasoningEffort: ReasoningEffort | null
}
function normalizePlanModeReasoningEffort(value: ReasoningEffort | '' | null | undefined): ReasoningEffort | null {
return value && value.length > 0 ? value : null
}
function normalizeCollaborationModeReasoningEffort(value: ReasoningEffort | '' | null | undefined): ReasoningEffort | null {
return value && value.length > 0 ? value : null
}
export type WorkspaceRootsState = {
order: string[]
labels: Record<string, string>
active: string[]
projectOrder: string[]
remoteProjects?: Array<{
id: string
hostId: string
remotePath: string
label: string
}>
}
let workspaceRootsStatePromise: Promise<WorkspaceRootsState> | null = null
let cachedWorkspaceRootsState: WorkspaceRootsState | null = null
export type StoredQueuedMessage = {
id: string
text: string
imageUrls: string[]
skills: Array<{ name: string; path: string }>
fileAttachments: Array<{ label: string; path: string; fsPath: string }>
collaborationMode: CollaborationModeKind
}
export type ThreadQueueState = Record<string, StoredQueuedMessage[]>
export type ComposerFileSuggestion = {
path: string
}
const DEFAULT_COLLABORATION_MODE_OPTIONS: CollaborationModeOption[] = [
{ value: 'default', label: 'Default' },
{ value: 'plan', label: 'Plan' },
]
export type WorktreeCreateResult = {
cwd: string
branch: string | null
gitRoot: string
}
export type WorktreeBranchOption = {
value: string
label: string
isCurrent?: boolean
isRemote?: boolean
}
export type GitBranchState = {
currentBranch: string | null
headSha: string | null
headSubject: string | null
headDate: string | null
detached: boolean
dirty: boolean
gitRoot: string
options: WorktreeBranchOption[]
}
export type GitCommitOption = {
sha: string
shortSha: string
subject: string
date: string
}
export type GitCommitFileChange = {
path: string
previousPath: string | null
status: string
label: string
addedLineCount: number | null
removedLineCount: number | null
}
export type GitRepositoryStatus = {
isGitRepo: boolean
gitRoot: string
}
export type ThreadSearchResult = {
threadIds: string[]
indexedThreadCount: number
}
export type TelegramStatus = {
configured: boolean
active: boolean
mappedChats: number
mappedThreads: number
allowedUsers: number
allowAllUsers: boolean
lastError: string
}
export type TelegramConfig = {
botToken: string
allowedUserIds: Array<number | '*'>
}
export type LocalDirectoryEntry = {
name: string
path: string
}
export type LocalDirectoryListing = {
path: string
parentPath: string
entries: LocalDirectoryEntry[]
}
export type ThreadTerminalSession = {
id: string
threadId: string
cwd: string
shell: string
buffer: string
truncated: boolean
}
export type ThreadTerminalAttachInput = {
threadId: string
cwd: string
sessionId?: string
cols?: number
rows?: number
newSession?: boolean
}
export type ThreadTerminalQuickCommand = {
label: string
value: string
source: 'package' | 'script' | 'make'
}
export type AccountsListResult = {
activeAccountId: string | null
accounts: UiAccountEntry[]
importedAccountId?: string
}
type ThreadFileChangeFallbackEntry = {
turnId: string
turnIndex: number
fileChanges: UiFileChange[]
}
type ThreadTurnIndexById = Record<string, number>
function asRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: null
}
function readString(value: unknown): string | null {
return typeof value === 'string' && value.length > 0 ? value : null
}
function readNumber(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
function readBoolean(value: unknown): boolean | null {
return typeof value === 'boolean' ? value : null
}
function readStringArray(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string' && item.length > 0) : []
}
function normalizeAccountUnavailableReason(value: unknown): UiAccountUnavailableReason | null {
return value === 'payment_required' ? value : null
}
function isPaymentRequiredErrorMessage(value: string | null): boolean {
if (!value) return false
const normalized = value.toLowerCase()
return normalized.includes('payment required') || /\b402\b/.test(normalized)
}
function normalizeRateLimitWindow(value: unknown): UiRateLimitWindow | null {
const record = asRecord(value)
if (!record) return null
const usedPercent = readNumber(record.usedPercent ?? record.used_percent)
if (usedPercent === null) return null
const windowValue = readNumber(record.windowDurationMins ?? record.window_minutes)
return {
usedPercent,
windowDurationMins: windowValue,
windowMinutes: windowValue,
resetsAt: readNumber(record.resetsAt ?? record.resets_at),
}
}
function normalizeCreditsSnapshot(value: unknown): UiCreditsSnapshot | null {
const record = asRecord(value)
if (!record) return null
const hasCredits = readBoolean(record.hasCredits ?? record.has_credits)
const unlimited = readBoolean(record.unlimited)
if (hasCredits === null || unlimited === null) return null
return {
hasCredits,
unlimited,
balance: readString(record.balance),
}
}
function normalizeRateLimitSnapshot(value: unknown): UiRateLimitSnapshot | null {
const record = asRecord(value)
if (!record) return null
const primary = normalizeRateLimitWindow(record.primary)
const secondary = normalizeRateLimitWindow(record.secondary)
const credits = normalizeCreditsSnapshot(record.credits)
if (!primary && !secondary && !credits) return null
return {
limitId: readString(record.limitId ?? record.limit_id),
limitName: readString(record.limitName ?? record.limit_name),
primary,
secondary,
credits,
planType: readString(record.planType ?? record.plan_type),
}
}
function normalizeAccountEntry(value: unknown, activeAccountId: string | null = null): UiAccountEntry | null {
const record = asRecord(value)
if (!record) return null
const accountId = readString(record.accountId)
const quotaStatusRaw = readString(record.quotaStatus)
const quotaStatus: UiAccountQuotaStatus =
quotaStatusRaw === 'loading' || quotaStatusRaw === 'ready' || quotaStatusRaw === 'error' ? quotaStatusRaw : 'idle'
if (!accountId) return null
return {
accountId,
authMode: readString(record.authMode),
email: readString(record.email),
planType: readString(record.planType),
lastRefreshedAtIso: readString(record.lastRefreshedAtIso) ?? '',
lastActivatedAtIso: readString(record.lastActivatedAtIso),
quotaSnapshot: normalizeRateLimitSnapshot(record.quotaSnapshot),
quotaUpdatedAtIso: readString(record.quotaUpdatedAtIso),
quotaStatus,
quotaError: readString(record.quotaError),
unavailableReason: normalizeAccountUnavailableReason(record.unavailableReason)
?? (isPaymentRequiredErrorMessage(readString(record.quotaError)) ? 'payment_required' : null),
isActive: readBoolean(record.isActive) ?? accountId === activeAccountId,
}
}
export function pickCodexRateLimitSnapshot(payload: unknown): UiRateLimitSnapshot | null {
const record = asRecord(payload)
if (!record) return null
const rateLimitsByLimitId = asRecord(record.rateLimitsByLimitId ?? record.rate_limits_by_limit_id)
const codexBucket = normalizeRateLimitSnapshot(rateLimitsByLimitId?.codex)
if (codexBucket) return codexBucket
return normalizeRateLimitSnapshot(record.rateLimits ?? record.rate_limits)
}
async function callRpc<T>(method: string, params?: unknown): Promise<T> {
try {
return await rpcCall<T>(method, params)
} catch (error) {
throw normalizeCodexApiError(error, `RPC ${method} failed`, method)
}
}
function normalizeFallbackFileChange(value: unknown): UiFileChange | null {
const record = asRecord(value)
if (!record) return null
const path = readString(record.path)
const operation = readString(record.operation)
if (!path || (operation !== 'add' && operation !== 'delete' && operation !== 'update')) {
return null
}
return {
path,
operation,
movedToPath: readString(record.movedToPath) ?? null,
diff: readString(record.diff) ?? '',
addedLineCount: readNumber(record.addedLineCount) ?? 0,
removedLineCount: readNumber(record.removedLineCount) ?? 0,
}
}
function normalizeThreadFileChangeFallback(value: unknown): ThreadFileChangeFallbackEntry[] {
const payload = asRecord(value)
const rows = Array.isArray(payload?.data) ? payload.data : []
const normalized: ThreadFileChangeFallbackEntry[] = []
for (const row of rows) {
const record = asRecord(row)
if (!record) continue
const turnId = readString(record.turnId)
const turnIndex = readNumber(record.turnIndex)
const fileChanges = Array.isArray(record.fileChanges)
? record.fileChanges
.map((entry) => normalizeFallbackFileChange(entry))
.filter((entry): entry is UiFileChange => entry !== null)
: []
if (!turnId || turnIndex === null || fileChanges.length === 0) continue
normalized.push({ turnId, turnIndex, fileChanges })
}
return normalized
}
function buildTurnIndexByTurnId(payload: ThreadReadResponse, baseTurnIndex = 0): ThreadTurnIndexById {
const turns = Array.isArray(payload.thread.turns) ? payload.thread.turns : []
const lookup: ThreadTurnIndexById = {}
for (let turnOffset = 0; turnOffset < turns.length; turnOffset += 1) {
const turnIndex = baseTurnIndex + turnOffset
const turn = turns[turnOffset]
if (typeof turn?.id !== 'string' || turn.id.length === 0) continue
lookup[turn.id] = turnIndex
}
return lookup
}
function readThreadTurnStartIndex(payload: ThreadReadResponse): number {
const record = asRecord(payload)
const raw = record?.threadTurnStartIndex
return Math.max(0, Math.floor(typeof raw === 'number' ? raw : 0))
}
async function fetchThreadFileChangeFallback(threadId: string): Promise<ThreadFileChangeFallbackEntry[]> {
const response = await fetch(`/codex-api/thread-file-change-fallback?threadId=${encodeURIComponent(threadId)}`)
if (!response.ok) {
throw new Error(`Fallback request failed with ${response.status}`)
}
return normalizeThreadFileChangeFallback(await response.json())
}
function mergeRecoveredFileChangeMessages(messages: UiMessage[], fallbackEntries: ThreadFileChangeFallbackEntry[]): UiMessage[] {
if (fallbackEntries.length === 0) return messages
const localTurnIndexByTurnId = new Map<string, number>()
const coveredTurnIds = new Set<string>()
for (const message of messages) {
const tid = typeof message.turnId === 'string' && message.turnId.length > 0 ? message.turnId : undefined
const tIdx = typeof message.turnIndex === 'number' ? message.turnIndex : undefined
if (tid && tIdx !== undefined) localTurnIndexByTurnId.set(tid, tIdx)
const hasFileData =
message.messageType === 'fileChange' ||
(Array.isArray(message.fileChanges) && message.fileChanges.length > 0)
if (hasFileData && tid) coveredTurnIds.add(tid)
}
const extraMessages = fallbackEntries
.filter((entry) => localTurnIndexByTurnId.has(entry.turnId) && !coveredTurnIds.has(entry.turnId))
.map<UiMessage>((entry) => ({
id: `session-file-change:${entry.turnId}`,
role: 'system',
text: '',
messageType: 'fileChange',
fileChangeStatus: 'completed',
fileChanges: entry.fileChanges,
turnId: entry.turnId,
turnIndex: localTurnIndexByTurnId.get(entry.turnId) ?? entry.turnIndex,
}))
if (extraMessages.length === 0) return messages
const extrasByTurnIndex = new Map<number, UiMessage[]>()
for (const message of extraMessages) {
const turnIndex = message.turnIndex
if (typeof turnIndex !== 'number') continue
const current = extrasByTurnIndex.get(turnIndex)
if (current) current.push(message)
else extrasByTurnIndex.set(turnIndex, [message])
}
const insertedTurnIndices = new Set<number>()
const merged: UiMessage[] = []
for (let index = 0; index < messages.length; index += 1) {
const message = messages[index]
merged.push(message)
const turnIndex = message.turnIndex
if (typeof turnIndex !== 'number' || insertedTurnIndices.has(turnIndex)) continue
const nextTurnIndex = messages[index + 1]?.turnIndex
if (nextTurnIndex === turnIndex) continue
const extras = extrasByTurnIndex.get(turnIndex)
if (!extras || extras.length === 0) continue
merged.push(...extras)
insertedTurnIndices.add(turnIndex)
}
return merged
}
async function enrichThreadMessagesWithFallback(threadId: string, messages: UiMessage[]): Promise<UiMessage[]> {
try {
const fallbackEntries = await fetchThreadFileChangeFallback(threadId)
return mergeRecoveredFileChangeMessages(messages, fallbackEntries)
} catch {
return messages
}
}
function normalizeReasoningEffort(value: unknown): ReasoningEffort | '' {
const allowed: ReasoningEffort[] = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh']
return typeof value === 'string' && allowed.includes(value as ReasoningEffort)
? (value as ReasoningEffort)
: ''
}
function normalizeSpeedMode(value: unknown): SpeedMode {
return typeof value === 'string' && value.trim().toLowerCase() === 'fast'
? 'fast'
: 'standard'
}
const INITIAL_THREAD_LIST_LIMIT = 50
const BACKGROUND_THREAD_LIST_LIMIT = 100
export type ThreadGroupsPage = {
groups: UiProjectGroup[]
nextCursor: string | null
}
export type ThreadTurnPage = {
messages: UiMessage[]
inProgress: boolean
activeTurnId: string
hasMoreOlder: boolean
startTurnIndex: number
turnIndexByTurnId: ThreadTurnIndexById
}
async function getThreadGroupsPageV2(cursor: string | null, limit: number): Promise<ThreadGroupsPage> {
const payload = await callRpc<ThreadListResponse>('thread/list', {
archived: false,
limit,
sortKey: 'updated_at',
modelProviders: [],
cursor,
})
return {
groups: normalizeThreadGroupsV2(payload),
nextCursor: typeof payload.nextCursor === 'string' && payload.nextCursor.length > 0
? payload.nextCursor
: null,
}
}
async function getThreadMessagesV2(threadId: string): Promise<UiMessage[]> {
const payload = await callRpc<ThreadReadResponse>('thread/read', {
threadId,
includeTurns: true,
})
return normalizeThreadMessagesV2(payload, readThreadTurnStartIndex(payload))
}
async function getThreadSummaryV2(threadId: string): Promise<UiThread> {
const payload = await callRpc<ThreadReadResponse>('thread/read', {
threadId,
includeTurns: false,
})
return normalizeThreadSummaryV2(payload)
}
async function getThreadDetailV2(threadId: string): Promise<{
model: string
modelProvider: string
messages: UiMessage[]
inProgress: boolean
activeTurnId: string
hasMoreOlder: boolean
turnIndexByTurnId: ThreadTurnIndexById
}> {
const payload = await callRpc<ThreadReadResponse>('thread/read', {
threadId,
includeTurns: true,
})
const startTurnIndex = readThreadTurnStartIndex(payload)
const normalized = normalizeThreadMessagesV2(payload, startTurnIndex)
return {
model: normalizeThreadModelFromPayload(payload),
modelProvider: normalizeThreadModelProviderFromPayload(payload),
messages: normalized,
inProgress: readThreadInProgressFromResponse(payload),
activeTurnId: readActiveTurnIdFromResponse(payload),
hasMoreOlder: startTurnIndex > 0,
turnIndexByTurnId: buildTurnIndexByTurnId(payload, startTurnIndex),
}
}
async function getOlderThreadMessagesV2(threadId: string, beforeTurnId: string, limit = 10): Promise<ThreadTurnPage> {
const params = new URLSearchParams({
threadId,
beforeTurnId,
limit: String(limit),
})
const response = await fetch(`/codex-api/thread-turn-page?${params.toString()}`)
if (!response.ok) {
throw new Error(`Older thread page request failed with ${response.status}`)
}
const payload = await response.json() as {
result?: ThreadReadResponse
hasMoreOlder?: unknown
startTurnIndex?: unknown
}
if (!payload.result) {
throw new Error('Older thread page response did not include a thread result')
}
const startTurnIndex = Math.max(0, Math.floor(typeof payload.startTurnIndex === 'number' ? payload.startTurnIndex : 0))
return {
messages: normalizeThreadMessagesV2(payload.result, startTurnIndex),
inProgress: readThreadInProgressFromResponse(payload.result),
activeTurnId: readActiveTurnIdFromResponse(payload.result),
hasMoreOlder: payload.hasMoreOlder === true,
startTurnIndex,
turnIndexByTurnId: buildTurnIndexByTurnId(payload.result, startTurnIndex),
}
}
export async function getThreadGroups(): Promise<UiProjectGroup[]> {
try {
return (await getThreadGroupsPageV2(null, INITIAL_THREAD_LIST_LIMIT)).groups
} catch (error) {
throw normalizeCodexApiError(error, 'Failed to load thread groups', 'thread/list')
}
}
export async function getThreadGroupsPage(
cursor: string | null = null,
limit = INITIAL_THREAD_LIST_LIMIT,
): Promise<ThreadGroupsPage> {
try {
return await getThreadGroupsPageV2(cursor, limit)
} catch (error) {
throw normalizeCodexApiError(error, 'Failed to load thread groups', 'thread/list')
}
}
export function getBackgroundThreadListLimit(): number {
return BACKGROUND_THREAD_LIST_LIMIT
}
export async function getThreadMessages(threadId: string): Promise<UiMessage[]> {
try {
return await getThreadMessagesV2(threadId)
} catch (error) {
throw normalizeCodexApiError(error, `Failed to load thread ${threadId}`, 'thread/read')
}
}
export async function getThreadSummary(threadId: string): Promise<UiThread> {
try {
return await getThreadSummaryV2(threadId)
} catch (error) {
throw normalizeCodexApiError(error, `Failed to load thread ${threadId}`, 'thread/read')
}
}
export async function getThreadDetail(threadId: string): Promise<{
model: string
modelProvider: string
messages: UiMessage[]
inProgress: boolean
activeTurnId: string
hasMoreOlder: boolean
turnIndexByTurnId: ThreadTurnIndexById
}> {
try {
return await getThreadDetailV2(threadId)
} catch (error) {
throw normalizeCodexApiError(error, `Failed to load thread ${threadId}`, 'thread/read')
}
}
export async function getOlderThreadMessages(threadId: string, beforeTurnId: string, limit?: number): Promise<ThreadTurnPage> {
try {
return await getOlderThreadMessagesV2(threadId, beforeTurnId, limit)
} catch (error) {
throw normalizeCodexApiError(error, `Failed to load earlier messages for thread ${threadId}`, 'thread/read')
}
}
function normalizeReviewLine(value: unknown): UiReviewLine | null {
const record = asRecord(value)
if (!record) return null
const key = readString(record.key)
const text = typeof record.text === 'string' ? record.text : ''
const kind = readString(record.kind)
if (!key || !kind) return null
if (kind !== 'meta' && kind !== 'hunk' && kind !== 'add' && kind !== 'remove' && kind !== 'context') {
return null
}
return {
key,
kind,
text,
oldLine: readNumber(record.oldLine),
newLine: readNumber(record.newLine),
}
}
function normalizeReviewHunk(value: unknown): UiReviewHunk | null {
const record = asRecord(value)
if (!record) return null
const id = readString(record.id)
const header = typeof record.header === 'string' ? record.header : ''
const patch = typeof record.patch === 'string' ? record.patch : ''
if (!id) return null
return {
id,
header,
patch,
addedLineCount: readNumber(record.addedLineCount) ?? 0,
removedLineCount: readNumber(record.removedLineCount) ?? 0,
oldStart: readNumber(record.oldStart),
oldLineCount: readNumber(record.oldLineCount) ?? 0,
newStart: readNumber(record.newStart),
newLineCount: readNumber(record.newLineCount) ?? 0,
lines: Array.isArray(record.lines)
? record.lines
.map((entry) => normalizeReviewLine(entry))
.filter((entry): entry is UiReviewLine => entry !== null)
: [],
}
}
function normalizeReviewFile(value: unknown): UiReviewFile | null {
const record = asRecord(value)
if (!record) return null
const id = readString(record.id)
const path = readString(record.path)
const absolutePath = readString(record.absolutePath)
const operation = readString(record.operation)
if (!id || !path || !absolutePath || !operation) return null
if (operation !== 'add' && operation !== 'delete' && operation !== 'update' && operation !== 'rename') {
return null
}
return {
id,
path,
absolutePath,
previousPath: readString(record.previousPath),
previousAbsolutePath: readString(record.previousAbsolutePath),
operation,
addedLineCount: readNumber(record.addedLineCount) ?? 0,
removedLineCount: readNumber(record.removedLineCount) ?? 0,
diff: typeof record.diff === 'string' ? record.diff : '',
hunks: Array.isArray(record.hunks)
? record.hunks
.map((entry) => normalizeReviewHunk(entry))
.filter((entry): entry is UiReviewHunk => entry !== null)
: [],
}
}
function normalizeReviewSnapshot(payload: unknown): UiReviewSnapshot {
const envelope = asRecord(payload)
const data = asRecord(envelope?.data)
const summaryRecord = asRecord(data?.summary)
const rawScope = readString(data?.scope)
const scope = rawScope === 'baseBranch' || rawScope === 'commit' ? rawScope : 'workspace'
const workspaceView = readString(data?.workspaceView) === 'staged' ? 'staged' : 'unstaged'
return {
cwd: readString(data?.cwd) ?? '',
gitRoot: readString(data?.gitRoot),
isGitRepo: readBoolean(data?.isGitRepo) ?? false,
scope,
workspaceView,
baseBranch: readString(data?.baseBranch),
baseBranchOptions: Array.isArray(data?.baseBranchOptions)
? data.baseBranchOptions
.map((entry) => readString(entry))
.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)
: [],
commitSha: readString(data?.commitSha),
headBranch: readString(data?.headBranch),
mergeBaseSha: readString(data?.mergeBaseSha),
generatedAtIso: readString(data?.generatedAtIso) ?? '',
summary: {
fileCount: readNumber(summaryRecord?.fileCount) ?? 0,
addedLineCount: readNumber(summaryRecord?.addedLineCount) ?? 0,
removedLineCount: readNumber(summaryRecord?.removedLineCount) ?? 0,
},
files: Array.isArray(data?.files)
? data.files
.map((entry) => normalizeReviewFile(entry))
.filter((entry): entry is UiReviewFile => entry !== null)
: [],
}
}
function normalizeReviewSummary(payload: unknown): UiReviewSummary {
const envelope = asRecord(payload)
const data = asRecord(envelope?.data)
return {
fileCount: readNumber(data?.fileCount) ?? 0,