-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodexClient.cs
More file actions
1218 lines (1088 loc) · 53.5 KB
/
Copy pathCodexClient.cs
File metadata and controls
1218 lines (1088 loc) · 53.5 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
using System.Runtime.CompilerServices;
namespace Incursa.OpenAI.Codex;
// Traceability: REQ-CODEX-SDK-CATALOG-0301, REQ-CODEX-SDK-CATALOG-0302, REQ-CODEX-SDK-CATALOG-0303, REQ-CODEX-SDK-CATALOG-0304,
// REQ-CODEX-SDK-CATALOG-0307, REQ-CODEX-SDK-CATALOG-0308, REQ-CODEX-SDK-CATALOG-0309, REQ-CODEX-SDK-CATALOG-0311, REQ-CODEX-SDK-CATALOG-0312.
/// <summary>
/// Provides the high-level entry point for communicating with a Codex runtime.
/// </summary>
public sealed class CodexClient : IAsyncDisposable
{
private readonly SemaphoreSlim _initializationGate = new(1, 1);
private readonly CodexTurnConsumerGate _turnConsumerGate = new();
private readonly ICodexTransport _transport;
private bool _disposed;
private bool _initialized;
/// <summary>
/// Initializes a new instance of the <see cref="CodexClient"/> class with default options.
/// </summary>
public CodexClient()
: this(new CodexClientOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CodexClient"/> class.
/// </summary>
/// <param name="options">The client options to use, or <see langword="null"/> to use defaults.</param>
public CodexClient(CodexClientOptions? options)
{
Options = options ?? new CodexClientOptions();
Options.ProcessLauncher ??= new ProcessCodexProcessLauncher();
_transport = Options.BackendSelection switch
{
CodexBackendSelection.Exec => new CodexExecTransport(Options, _turnConsumerGate),
_ => new CodexAppServerTransport(Options, _turnConsumerGate),
};
}
/// <summary>
/// Gets the options used by this client.
/// </summary>
public CodexClientOptions Options { get; }
/// <summary>
/// Gets runtime metadata after the client has been initialized.
/// </summary>
public CodexRuntimeMetadata? Metadata { get; private set; }
/// <summary>
/// Gets runtime capabilities after the client has been initialized.
/// </summary>
public CodexRuntimeCapabilities? Capabilities { get; private set; }
/// <summary>
/// Observes all runtime events received by this client after subscription.
/// </summary>
/// <returns>An observable stream of raw runtime events from the selected backend.</returns>
public IObservable<CodexThreadEvent> ObserveEventsAsync()
{
ThrowIfDisposed();
return _transport.ObserveEventsAsync();
}
/// <summary>
/// Initializes the selected Codex backend and reads runtime metadata.
/// </summary>
/// <param name="cancellationToken">A token that cancels the initialization request.</param>
/// <returns>The metadata returned by the Codex runtime.</returns>
public async Task<CodexRuntimeMetadata> InitializeAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
if (_initialized)
{
return Metadata ?? throw new InvalidOperationException("CodexClient initialization completed without metadata.");
}
await _initializationGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (_initialized)
{
return Metadata ?? throw new InvalidOperationException("CodexClient initialization completed without metadata.");
}
Metadata = await _transport.InitializeAsync(cancellationToken).ConfigureAwait(false);
Capabilities = _transport.Capabilities;
_initialized = true;
return Metadata;
}
finally
{
_initializationGate.Release();
}
}
/// <summary>
/// Checks whether the configured Codex executable is available.
/// </summary>
/// <param name="cancellationToken">A token that cancels the availability check.</param>
/// <returns><see langword="true"/> when Codex can be resolved; otherwise, <see langword="false"/>.</returns>
public Task<bool> IsCodexAvailableAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(CodexExecutableResolver.IsAvailable(Options));
}
/// <summary>
/// Starts a new Codex thread.
/// </summary>
/// <param name="options">Thread defaults to apply when creating the thread.</param>
/// <param name="cancellationToken">A token that cancels the start request.</param>
/// <returns>A handle for the new Codex thread.</returns>
public async Task<CodexThread> StartThreadAsync(
CodexThreadOptions? options = null,
CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsStartThread == true, nameof(StartThreadAsync));
if (Options.BackendSelection == CodexBackendSelection.Exec)
{
return new CodexThread(this, options, started: false);
}
CodexThreadHandleState handle = await StartThreadHandleAsync(options, cancellationToken).ConfigureAwait(false);
return new CodexThread(this, handle.Defaults ?? options, handle.Snapshot.Id, started: true);
}
/// <summary>
/// Resumes an existing Codex thread.
/// </summary>
/// <param name="threadId">The identifier of the thread to resume.</param>
/// <param name="options">Thread defaults to apply after resuming the thread.</param>
/// <param name="cancellationToken">A token that cancels the resume request.</param>
/// <returns>A handle for the resumed Codex thread.</returns>
public async Task<CodexThread> ResumeThreadAsync(
string threadId,
CodexThreadOptions? options = null,
CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsResumeThread == true, nameof(ResumeThreadAsync));
if (Options.BackendSelection == CodexBackendSelection.Exec)
{
return new CodexThread(this, options, threadId, started: true);
}
CodexThreadHandleState handle = await ResumeThreadHandleAsync(threadId, options, cancellationToken).ConfigureAwait(false);
return new CodexThread(this, handle.Defaults ?? options, handle.Snapshot.Id, started: true);
}
/// <summary>
/// Forks an existing Codex thread.
/// </summary>
/// <param name="threadId">The identifier of the thread to fork.</param>
/// <param name="options">Fork options to apply to the new thread.</param>
/// <param name="cancellationToken">A token that cancels the fork request.</param>
/// <returns>A handle for the forked Codex thread.</returns>
public async Task<CodexThread> ForkThreadAsync(
string threadId,
CodexThreadForkOptions? options = null,
CancellationToken cancellationToken = default)
{
CodexThreadHandleState handle = await ForkThreadHandleAsync(threadId, options, cancellationToken).ConfigureAwait(false);
return new CodexThread(this, handle.Defaults ?? options, handle.Snapshot.Id, started: true);
}
/// <summary>
/// Lists Codex threads visible to the selected backend.
/// </summary>
/// <param name="options">Filters and paging options for the list request.</param>
/// <param name="cancellationToken">A token that cancels the list request.</param>
/// <returns>The page of matching Codex threads.</returns>
public async Task<CodexThreadListResult> ListThreadsAsync(
CodexThreadListOptions? options = null,
CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsListThreads == true, nameof(ListThreadsAsync));
return await _transport.ListThreadsAsync(options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reads a Codex thread snapshot.
/// </summary>
/// <param name="threadId">The identifier of the thread to read.</param>
/// <param name="options">Options that control how much thread data is returned.</param>
/// <param name="cancellationToken">A token that cancels the read request.</param>
/// <returns>The requested thread snapshot.</returns>
public async Task<CodexThreadSnapshot> ReadThreadAsync(
string threadId,
CodexThreadReadOptions? options = null,
CancellationToken cancellationToken = default)
{
return await ReadThreadSnapshotAsync(threadId, options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Archives a Codex thread.
/// </summary>
/// <param name="threadId">The identifier of the thread to archive.</param>
/// <param name="cancellationToken">A token that cancels the archive request.</param>
/// <returns>A task that completes when the archive request has finished.</returns>
public async Task ArchiveThreadAsync(string threadId, CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsArchiveThread == true, nameof(ArchiveThreadAsync));
await _transport.ArchiveThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Restores an archived Codex thread.
/// </summary>
/// <param name="threadId">The identifier of the thread to unarchive.</param>
/// <param name="cancellationToken">A token that cancels the unarchive request.</param>
/// <returns>A handle for the unarchived Codex thread.</returns>
public async Task<CodexThread> UnarchiveThreadAsync(string threadId, CancellationToken cancellationToken = default)
{
CodexThreadHandleState handle = await UnarchiveThreadHandleAsync(threadId, cancellationToken).ConfigureAwait(false);
return new CodexThread(this, handle.Defaults, handle.Snapshot.Id, started: true);
}
/// <summary>
/// Lists models available to the selected Codex backend.
/// </summary>
/// <param name="options">Options that control the model list request.</param>
/// <param name="cancellationToken">A token that cancels the list request.</param>
/// <returns>The page of available models.</returns>
public async Task<CodexModelListResult> ListModelsAsync(
CodexModelListOptions? options = null,
CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsListModels == true, nameof(ListModelsAsync));
return await _transport.ListModelsAsync(options, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reads the current Codex account rate-limit snapshot from the app-server backend.
/// </summary>
/// <param name="cancellationToken">A token that cancels the rate-limit request.</param>
/// <returns>The current account-level rate-limit buckets and reset windows.</returns>
public async Task<CodexAccountRateLimitsResult> GetAccountRateLimitsAsync(CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountRateLimits == true, nameof(GetAccountRateLimitsAsync));
return await _transport.GetAccountRateLimitsAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Authenticates the app-server backend with an OpenAI API key.
/// </summary>
/// <param name="apiKey">The API key to hand to the Codex runtime.</param>
/// <param name="cancellationToken">A token that cancels the login request.</param>
/// <returns>The login result returned by the runtime.</returns>
public async Task<CodexLoginResult> LoginWithApiKeyAsync(string apiKey, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new ArgumentException("API key must not be empty.", nameof(apiKey));
}
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogin == true, nameof(LoginWithApiKeyAsync));
return await _transport.LoginWithApiKeyAsync(apiKey, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Authenticates the app-server backend with externally supplied ChatGPT auth tokens.
/// </summary>
/// <param name="accessToken">The ChatGPT access token.</param>
/// <param name="chatGptAccountId">The ChatGPT account or workspace identifier.</param>
/// <param name="chatGptPlanType">Optional ChatGPT plan type supplied by the caller.</param>
/// <param name="cancellationToken">A token that cancels the login request.</param>
/// <returns>The login result returned by the runtime.</returns>
public async Task<CodexLoginResult> LoginWithChatGptAuthTokensAsync(
string accessToken,
string chatGptAccountId,
string? chatGptPlanType = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException("Access token must not be empty.", nameof(accessToken));
}
if (string.IsNullOrWhiteSpace(chatGptAccountId))
{
throw new ArgumentException("ChatGPT account id must not be empty.", nameof(chatGptAccountId));
}
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogin == true, nameof(LoginWithChatGptAuthTokensAsync));
return await _transport.LoginWithChatGptAuthTokensAsync(accessToken, chatGptAccountId, chatGptPlanType, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Starts browser-based ChatGPT login and returns a handle for the live attempt.
/// </summary>
/// <param name="codexStreamlinedLogin">Optional streamlined-login preference sent to the runtime.</param>
/// <param name="cancellationToken">A token that cancels the login-start request.</param>
/// <returns>A handle that can wait for completion or cancel the login attempt.</returns>
public async Task<CodexChatGptLoginHandle> StartChatGptLoginAsync(
bool? codexStreamlinedLogin = null,
CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogin == true, nameof(StartChatGptLoginAsync));
CodexChatGptLoginResult result = await _transport.StartChatGptLoginAsync(codexStreamlinedLogin, cancellationToken).ConfigureAwait(false);
return new CodexChatGptLoginHandle(this, result.LoginId, result.AuthUrl);
}
/// <summary>
/// Starts ChatGPT device-code login and returns a handle for the live attempt.
/// </summary>
/// <param name="cancellationToken">A token that cancels the login-start request.</param>
/// <returns>A handle that can wait for completion or cancel the login attempt.</returns>
public async Task<CodexChatGptDeviceCodeLoginHandle> StartChatGptDeviceCodeLoginAsync(CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogin == true, nameof(StartChatGptDeviceCodeLoginAsync));
CodexChatGptDeviceCodeLoginResult result = await _transport.StartChatGptDeviceCodeLoginAsync(cancellationToken).ConfigureAwait(false);
return new CodexChatGptDeviceCodeLoginHandle(this, result.LoginId, result.VerificationUrl, result.UserCode);
}
/// <summary>
/// Reads the current app-server account state.
/// </summary>
/// <param name="refreshToken">Whether to ask the runtime to refresh tokens before returning account state.</param>
/// <param name="cancellationToken">A token that cancels the account-read request.</param>
/// <returns>The current account state.</returns>
public async Task<CodexAccountReadResult> GetAccountAsync(bool refreshToken = false, CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountRead == true, nameof(GetAccountAsync));
return await _transport.GetAccountAsync(refreshToken, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Clears the current app-server account session.
/// </summary>
/// <param name="cancellationToken">A token that cancels the logout request.</param>
/// <returns>A task that completes when the logout request has finished.</returns>
public async Task LogoutAsync(CancellationToken cancellationToken = default)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogout == true, nameof(LogoutAsync));
await _transport.LogoutAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Releases resources held by the selected Codex transport.
/// </summary>
/// <returns>A task-like value that completes when disposal has finished.</returns>
public async ValueTask DisposeAsync()
{
if (_disposed)
{
return;
}
_disposed = true;
_initializationGate.Dispose();
await _transport.DisposeAsync().ConfigureAwait(false);
}
internal async Task<CodexThreadHandleState> StartThreadHandleAsync(
CodexThreadOptions? options,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsStartThread == true, nameof(StartThreadAsync));
return await _transport.StartThreadAsync(options, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadHandleState> ResumeThreadHandleAsync(
string threadId,
CodexThreadOptions? options,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsResumeThread == true, nameof(ResumeThreadAsync));
return await _transport.ResumeThreadAsync(threadId, options, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadHandleState> ForkThreadHandleAsync(
string threadId,
CodexThreadForkOptions? options,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsForkThread == true, nameof(ForkThreadAsync));
return await _transport.ForkThreadAsync(threadId, options, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadHandleState> UnarchiveThreadHandleAsync(
string threadId,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsUnarchiveThread == true, nameof(UnarchiveThreadAsync));
return await _transport.UnarchiveThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadSnapshot> ReadThreadSnapshotAsync(
string threadId,
CodexThreadReadOptions? options,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsReadThread == true, nameof(ReadThreadAsync));
return await _transport.ReadThreadAsync(threadId, options, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadSnapshot> SetThreadNameAsync(
string threadId,
string name,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsSetThreadName == true, nameof(CodexThread.SetNameAsync));
return await _transport.SetThreadNameAsync(threadId, name, cancellationToken).ConfigureAwait(false);
}
internal async Task CompactThreadAsync(string threadId, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsCompactThread == true, nameof(CodexThread.CompactAsync));
await _transport.CompactThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadGoal?> GetThreadGoalAsync(string threadId, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsThreadGoals == true, nameof(CodexThread.GetGoalAsync));
return await _transport.GetThreadGoalAsync(threadId, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadGoal> SetThreadGoalAsync(
string threadId,
string? objective,
CodexThreadGoalStatus? status,
long? tokenBudget,
bool tokenBudgetSpecified,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsThreadGoals == true, nameof(CodexThread.SetGoalAsync));
return await _transport.SetThreadGoalAsync(threadId, objective, status, tokenBudget, tokenBudgetSpecified, cancellationToken).ConfigureAwait(false);
}
internal async Task<bool> ClearThreadGoalAsync(string threadId, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsThreadGoals == true, nameof(CodexThread.ClearGoalAsync));
return await _transport.ClearThreadGoalAsync(threadId, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadSnapshot> RollbackThreadAsync(string threadId, int numTurns, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
return await _transport.RollbackThreadAsync(threadId, numTurns, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadUnsubscribeStatus> UnsubscribeThreadAsync(string threadId, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
return await _transport.UnsubscribeThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadSnapshot> UpdateThreadMetadataAsync(string threadId, CodexGitInfo? gitInfo, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
return await _transport.UpdateThreadMetadataAsync(threadId, gitInfo, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexThreadSnapshot> UpdateThreadMetadataAsync(
string threadId,
CodexThreadMetadataGitInfoUpdate gitInfo,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
return await _transport.UpdateThreadMetadataAsync(threadId, gitInfo, cancellationToken).ConfigureAwait(false);
}
internal async Task ShellCommandThreadAsync(string threadId, string command, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
await _transport.ShellCommandThreadAsync(threadId, command, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexTurnSession> StartTurnAsync(
string? threadId,
IReadOnlyList<CodexInputItem> input,
CodexThreadOptions? threadOptions,
CodexTurnOptions? options,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsThreadStreaming == true, nameof(CodexThread.StartTurnAsync));
return await _transport.StartTurnAsync(threadId, input, threadOptions, options, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexTurnSession> AttachTurnAsync(
string threadId,
string turnId,
CodexThreadOptions? threadOptions,
CodexTurnAttachOptions? options,
CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsResumeThread == true, nameof(CodexThread.AttachTurnAsync));
EnsureCapability(Capabilities?.SupportsThreadStreaming == true, nameof(CodexThread.AttachTurnAsync));
return await _transport.AttachTurnAsync(threadId, turnId, threadOptions, options, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexAccountLoginCompletedEvent> WaitForLoginCompletionAsync(string loginId, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogin == true, "account login completion");
return await _transport.WaitForLoginCompletionAsync(loginId, cancellationToken).ConfigureAwait(false);
}
internal async Task<CodexCancelLoginResult> CancelLoginAsync(string loginId, CancellationToken cancellationToken)
{
await EnsureInitializedAsync(cancellationToken).ConfigureAwait(false);
EnsureCapability(Capabilities?.SupportsAccountLogin == true, "account login cancellation");
return await _transport.CancelLoginAsync(loginId, cancellationToken).ConfigureAwait(false);
}
private async Task EnsureInitializedAsync(CancellationToken cancellationToken)
{
ThrowIfDisposed();
if (_initialized)
{
return;
}
await InitializeAsync(cancellationToken).ConfigureAwait(false);
}
private void EnsureCapability(bool supported, string operation)
{
if (supported)
{
return;
}
throw new CodexCapabilityNotSupportedException(operation, Options.BackendSelection);
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw new CodexTransportClosedException();
}
}
}
/// <summary>
/// Represents a live browser-based ChatGPT login attempt.
/// </summary>
public sealed class CodexChatGptLoginHandle
{
internal CodexChatGptLoginHandle(CodexClient client, string loginId, string authUrl)
{
Client = client;
LoginId = loginId;
AuthUrl = authUrl;
}
/// <summary>
/// Gets the client that owns this login attempt.
/// </summary>
public CodexClient Client { get; }
/// <summary>
/// Gets the login attempt identifier.
/// </summary>
public string LoginId { get; }
/// <summary>
/// Gets the URL the caller should open in a browser.
/// </summary>
public string AuthUrl { get; }
/// <summary>
/// Waits for the runtime to report that this login attempt completed.
/// </summary>
/// <param name="cancellationToken">A token that cancels the wait.</param>
/// <returns>The login completion notification.</returns>
public async Task<CodexAccountLoginCompletedEvent> WaitAsync(CancellationToken cancellationToken = default)
=> await Client.WaitForLoginCompletionAsync(LoginId, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Cancels this login attempt.
/// </summary>
/// <param name="cancellationToken">A token that cancels the cancel request.</param>
/// <returns>The cancellation result.</returns>
public async Task<CodexCancelLoginResult> CancelAsync(CancellationToken cancellationToken = default)
=> await Client.CancelLoginAsync(LoginId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Represents a live ChatGPT device-code login attempt.
/// </summary>
public sealed class CodexChatGptDeviceCodeLoginHandle
{
internal CodexChatGptDeviceCodeLoginHandle(CodexClient client, string loginId, string verificationUrl, string userCode)
{
Client = client;
LoginId = loginId;
VerificationUrl = verificationUrl;
UserCode = userCode;
}
/// <summary>
/// Gets the client that owns this login attempt.
/// </summary>
public CodexClient Client { get; }
/// <summary>
/// Gets the login attempt identifier.
/// </summary>
public string LoginId { get; }
/// <summary>
/// Gets the URL where the user enters the device code.
/// </summary>
public string VerificationUrl { get; }
/// <summary>
/// Gets the one-time device code.
/// </summary>
public string UserCode { get; }
/// <summary>
/// Waits for the runtime to report that this login attempt completed.
/// </summary>
/// <param name="cancellationToken">A token that cancels the wait.</param>
/// <returns>The login completion notification.</returns>
public async Task<CodexAccountLoginCompletedEvent> WaitAsync(CancellationToken cancellationToken = default)
=> await Client.WaitForLoginCompletionAsync(LoginId, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Cancels this login attempt.
/// </summary>
/// <param name="cancellationToken">A token that cancels the cancel request.</param>
/// <returns>The cancellation result.</returns>
public async Task<CodexCancelLoginResult> CancelAsync(CancellationToken cancellationToken = default)
=> await Client.CancelLoginAsync(LoginId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Represents a Codex conversation thread that can run turns and read thread state.
/// </summary>
public sealed class CodexThread
{
private readonly CodexClient _client;
private readonly CodexThreadOptions? _defaults;
private readonly SemaphoreSlim _idGate = new(1, 1);
private string? _id;
private bool _started;
internal CodexThread(CodexClient client, CodexThreadOptions? defaults, string? id = null, bool started = false)
{
_client = client;
_defaults = defaults;
_id = string.IsNullOrWhiteSpace(id) ? null : id;
_started = started || _id is not null;
}
/// <summary>
/// Gets the thread identifier when it is known.
/// </summary>
public string? Id => _id;
/// <summary>
/// Runs a turn with a single text input and waits for completion.
/// </summary>
/// <param name="input">The text input to send to Codex.</param>
/// <param name="options">Options that apply to this turn.</param>
/// <param name="cancellationToken">A token that cancels the run.</param>
/// <returns>The completed turn result.</returns>
public async Task<CodexRunResult> RunAsync(
string input,
CodexTurnOptions? options = null,
CancellationToken cancellationToken = default)
=> await RunAsync(NormalizeInput(input), options, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Runs a turn with structured input items and waits for completion.
/// </summary>
/// <param name="input">The input items to send to Codex.</param>
/// <param name="options">Options that apply to this turn.</param>
/// <param name="cancellationToken">A token that cancels the run.</param>
/// <returns>The completed turn result.</returns>
public async Task<CodexRunResult> RunAsync(
IReadOnlyList<CodexInputItem> input,
CodexTurnOptions? options = null,
CancellationToken cancellationToken = default)
{
CodexTurn turn = await StartTurnAsync(input, options, cancellationToken).ConfigureAwait(false);
return await turn.RunAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Runs a turn with a single text input and streams runtime events.
/// </summary>
/// <param name="input">The text input to send to Codex.</param>
/// <param name="options">Options that apply to this turn.</param>
/// <param name="cancellationToken">A token that cancels the stream.</param>
/// <returns>An asynchronous stream of thread events emitted by the turn.</returns>
public async IAsyncEnumerable<CodexThreadEvent> RunStreamedAsync(
string input,
CodexTurnOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (CodexThreadEvent item in RunStreamedAsync(NormalizeInput(input), options, cancellationToken).ConfigureAwait(false))
{
yield return item;
}
}
/// <summary>
/// Runs a turn with structured input items and streams runtime events.
/// </summary>
/// <param name="input">The input items to send to Codex.</param>
/// <param name="options">Options that apply to this turn.</param>
/// <param name="cancellationToken">A token that cancels the stream.</param>
/// <returns>An asynchronous stream of thread events emitted by the turn.</returns>
public async IAsyncEnumerable<CodexThreadEvent> RunStreamedAsync(
IReadOnlyList<CodexInputItem> input,
CodexTurnOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
CodexTurn turn = await StartTurnAsync(input, options, cancellationToken).ConfigureAwait(false);
await foreach (CodexThreadEvent item in turn.StreamAsync(cancellationToken).ConfigureAwait(false))
{
yield return item;
if (CodexTurnEventHelpers.IsTerminalTurnEvent(item))
{
yield break;
}
}
}
/// <summary>
/// Starts a turn with a single text input without waiting for completion.
/// </summary>
/// <param name="input">The text input to send to Codex.</param>
/// <param name="options">Options that apply to this turn.</param>
/// <param name="cancellationToken">A token that cancels the start request.</param>
/// <returns>A handle for the started Codex turn.</returns>
public async Task<CodexTurn> StartTurnAsync(
string input,
CodexTurnOptions? options = null,
CancellationToken cancellationToken = default)
=> await StartTurnAsync(NormalizeInput(input), options, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Starts a turn with structured input items without waiting for completion.
/// </summary>
/// <param name="input">The input items to send to Codex.</param>
/// <param name="options">Options that apply to this turn.</param>
/// <param name="cancellationToken">A token that cancels the start request.</param>
/// <returns>A handle for the started Codex turn.</returns>
public async Task<CodexTurn> StartTurnAsync(
IReadOnlyList<CodexInputItem> input,
CodexTurnOptions? options = null,
CancellationToken cancellationToken = default)
{
string? threadId = _id;
if (_client.Options.BackendSelection == CodexBackendSelection.AppServer && string.IsNullOrWhiteSpace(threadId))
{
threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
}
CodexTurnSession session = await _client.StartTurnAsync(threadId, input, _defaults, MergeTurnOptions(options), cancellationToken).ConfigureAwait(false);
_started = true;
if (!string.IsNullOrWhiteSpace(session.ThreadId))
{
_id = session.ThreadId;
}
return new CodexTurn(_client, session);
}
/// <summary>
/// Attaches a handle to an already-running turn on this thread.
/// </summary>
/// <param name="turnId">The identifier of the in-flight turn to attach.</param>
/// <param name="options">Options that control the thread resume used for the attach operation.</param>
/// <param name="cancellationToken">A token that cancels the attach request.</param>
/// <returns>A handle that streams subsequent events for the active turn.</returns>
public async Task<CodexTurn> AttachTurnAsync(
string turnId,
CodexTurnAttachOptions? options = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(turnId))
{
throw new ArgumentException("Turn id must not be empty.", nameof(turnId));
}
if (string.IsNullOrWhiteSpace(_id))
{
throw new InvalidOperationException("Cannot attach a turn until the thread id is known.");
}
CodexThreadOptions? resumeOptions = options?.ResumeOptions ?? _defaults;
CodexTurnSession session = await _client.AttachTurnAsync(_id!, turnId, resumeOptions, options, cancellationToken).ConfigureAwait(false);
_started = true;
if (!string.IsNullOrWhiteSpace(session.ThreadId))
{
_id = session.ThreadId;
}
return new CodexTurn(_client, session);
}
/// <summary>
/// Reads the latest snapshot for this thread.
/// </summary>
/// <param name="includeTurns">Whether to include turn records in the snapshot.</param>
/// <param name="cancellationToken">A token that cancels the read request.</param>
/// <returns>The requested thread snapshot.</returns>
public async Task<CodexThreadSnapshot> ReadAsync(
bool includeTurns = false,
CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.ReadThreadSnapshotAsync(threadId, new CodexThreadReadOptions { IncludeTurns = includeTurns }, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sets the display name for this thread.
/// </summary>
/// <param name="name">The display name to assign.</param>
/// <param name="cancellationToken">A token that cancels the rename request.</param>
/// <returns>The updated thread snapshot.</returns>
public async Task<CodexThreadSnapshot> SetNameAsync(string name, CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.SetThreadNameAsync(threadId, name, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Requests server-side compaction for this thread.
/// </summary>
/// <param name="cancellationToken">A token that cancels the compaction request.</param>
/// <returns>A task that completes when the compaction request has finished.</returns>
public async Task CompactAsync(CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
await _client.CompactThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Reads the current goal for this thread, if one is set.
/// </summary>
/// <param name="cancellationToken">A token that cancels the goal request.</param>
/// <returns>The current goal, or <see langword="null"/> when no goal is set.</returns>
public async Task<CodexThreadGoal?> GetGoalAsync(CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.GetThreadGoalAsync(threadId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Sets this thread's goal objective and marks it active.
/// </summary>
/// <param name="objective">The objective Codex should keep pursuing.</param>
/// <param name="tokenBudget">Optional token budget to assign to the goal.</param>
/// <param name="cancellationToken">A token that cancels the goal request.</param>
/// <returns>The updated thread goal.</returns>
public async Task<CodexThreadGoal> SetGoalAsync(
string objective,
long? tokenBudget = null,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(objective))
{
throw new ArgumentException("Goal objective cannot be blank.", nameof(objective));
}
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.SetThreadGoalAsync(
threadId,
objective.Trim(),
CodexThreadGoalStatus.Active,
tokenBudget,
tokenBudgetSpecified: tokenBudget.HasValue,
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates this thread's current goal status.
/// </summary>
/// <param name="status">The new goal status.</param>
/// <param name="cancellationToken">A token that cancels the goal request.</param>
/// <returns>The updated thread goal.</returns>
public async Task<CodexThreadGoal> SetGoalStatusAsync(
CodexThreadGoalStatus status,
CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.SetThreadGoalAsync(
threadId,
objective: null,
status,
tokenBudget: null,
tokenBudgetSpecified: false,
cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Clears this thread's goal.
/// </summary>
/// <param name="cancellationToken">A token that cancels the goal request.</param>
/// <returns><see langword="true"/> when a goal was cleared; otherwise, <see langword="false"/>.</returns>
public async Task<bool> ClearGoalAsync(CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.ClearThreadGoalAsync(threadId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Rolls back this thread by removing turns from the tail of its history.
/// </summary>
/// <param name="numTurns">The number of turns to drop from the end of the thread.</param>
/// <param name="cancellationToken">A token that cancels the rollback request.</param>
/// <returns>The updated thread snapshot.</returns>
public async Task<CodexThreadSnapshot> RollbackAsync(int numTurns = 1, CancellationToken cancellationToken = default)
{
if (numTurns < 1)
{
throw new ArgumentOutOfRangeException(nameof(numTurns));
}
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.RollbackThreadAsync(threadId, numTurns, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Unsubscribes this thread from live updates.
/// </summary>
/// <param name="cancellationToken">A token that cancels the unsubscribe request.</param>
/// <returns>The unsubscribe status returned by the runtime.</returns>
public async Task<CodexThreadUnsubscribeStatus> UnsubscribeAsync(CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.UnsubscribeThreadAsync(threadId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates the stored Git metadata associated with this thread.
/// </summary>
/// <param name="gitInfo">The Git metadata to apply, or <see langword="null"/> to clear the stored metadata.</param>
/// <param name="cancellationToken">A token that cancels the update request.</param>
/// <returns>The updated thread snapshot.</returns>
public async Task<CodexThreadSnapshot> UpdateMetadataAsync(CodexGitInfo? gitInfo, CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.UpdateThreadMetadataAsync(threadId, gitInfo, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates the stored Git metadata associated with this thread using the patch wrapper shape.
/// </summary>
/// <param name="gitInfo">The Git metadata patch to apply.</param>
/// <param name="cancellationToken">A token that cancels the update request.</param>
/// <returns>The updated thread snapshot.</returns>
public async Task<CodexThreadSnapshot> UpdateMetadataAsync(
CodexThreadMetadataGitInfoUpdate gitInfo,
CancellationToken cancellationToken = default)
{
string threadId = await EnsureThreadIdAsync(cancellationToken).ConfigureAwait(false);
return await _client.UpdateThreadMetadataAsync(threadId, gitInfo, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Runs a shell command attached to this thread.
/// </summary>
/// <param name="command">The shell command to execute.</param>
/// <param name="cancellationToken">A token that cancels the command request.</param>
/// <returns>A task that completes when the command request finishes.</returns>
public async Task ShellCommandAsync(string command, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(command))
{
throw new ArgumentException("Command must not be empty.", nameof(command));