@shuind/dsh-codex-connect 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/INSTALL.md +349 -0
  2. package/LICENSE +202 -0
  3. package/MIGRATION.md +101 -0
  4. package/NOTICE +26 -0
  5. package/README.md +71 -2
  6. package/VERSIONING.md +69 -0
  7. package/cordis.patch.yml +9 -0
  8. package/docs/README.zh.md +3 -0
  9. package/docs/assets/composer-capabilities.jpg +0 -0
  10. package/docs/assets/en/hero.jpg +0 -0
  11. package/docs/assets/en/image-generation.png +0 -0
  12. package/docs/assets/en/model-selector.jpg +0 -0
  13. package/docs/assets/en/oauth-status.jpg +0 -0
  14. package/docs/assets/en/plugin-configuration.jpg +0 -0
  15. package/docs/assets/en/plugin-entry.jpg +0 -0
  16. package/docs/assets/hero.jpg +0 -0
  17. package/docs/assets/model-selector.jpg +0 -0
  18. package/docs/assets/oauth-status.jpg +0 -0
  19. package/docs/assets/plugin-configuration.jpg +0 -0
  20. package/docs/assets/zh/hero.jpg +0 -0
  21. package/docs/assets/zh/image-generation.png +0 -0
  22. package/docs/assets/zh/model-selector.jpg +0 -0
  23. package/docs/assets/zh/oauth-status.jpg +0 -0
  24. package/docs/assets/zh/plugin-configuration.jpg +0 -0
  25. package/docs/assets/zh/plugin-entry.jpg +0 -0
  26. package/docs/design.md +61 -0
  27. package/docs/design.zh.md +39 -0
  28. package/docs/licenses/pi-ai-oauth.txt +21 -0
  29. package/docs/licenses/standalone-cli.txt +115 -0
  30. package/docs/preflight-activity.md +42 -0
  31. package/docs/preflight-activity.zh.md +42 -0
  32. package/docs/quota-tool.md +46 -0
  33. package/docs/reference.md +240 -0
  34. package/docs/reference.zh.md +240 -0
  35. package/docs/skills/codex-quota-awareness/SKILL.md +12 -0
  36. package/lib/bin.js +2442 -0
  37. package/lib/client.js +6752 -0
  38. package/lib/index.d.ts +631 -0
  39. package/lib/index.js +7162 -0
  40. package/lib/models-DUIoH1lI.js +1763 -0
  41. package/lib/openai-codex-responses-CzSuDkhU.js +3452 -0
  42. package/package.json +234 -4
package/lib/index.d.ts ADDED
@@ -0,0 +1,631 @@
1
+ import { AuthInteraction, Credential, CredentialInfo, CredentialStore, OAuthCredential } from "@earendil-works/pi-ai";
2
+ import { Context, Service, Volatile } from "@deepseek-ai/cordis";
3
+ import "@deepseek-ai/dsh-attachment";
4
+ import "@deepseek-ai/dsh-tools";
5
+ import { RetryPolicyConfig } from "@deepseek-ai/dsh-llm";
6
+ import { WebSearchProvider, WebSearchRequest, WebSearchResult } from "@deepseek-ai/dsh-web";
7
+ import z from "@deepseek-ai/schemastery";
8
+ declare module '@deepseek-ai/dsh-llm' {
9
+ interface MessageSourceMap {
10
+ 'dsh-codex-connect': {
11
+ kind: 'dsh-codex-connect';
12
+ plugin: string;
13
+ };
14
+ }
15
+ }
16
+ type OpenAICodexAccountProfileSource = 'oauth' | 'generated';
17
+ /** Provider route and pi-ai provider id owned by this bundle. */
18
+ export declare const OPENAI_CODEX_PROVIDER = "openai-codex";
19
+ /** Basename of the OAuth document inside the Harness home. */
20
+ export declare const OPENAI_CODEX_AUTH_FILENAME = ".openai-codex-auth.json";
21
+ /** Maximum number of stored OpenAI Codex accounts. */
22
+ export declare const OPENAI_CODEX_ACCOUNT_LIMIT = 16;
23
+ /** Maximum serialized credential document size. */
24
+ export declare const OPENAI_CODEX_AUTH_DOCUMENT_LIMIT: number;
25
+ /** Suffix used for the one-time version-1 rollback copy. */
26
+ export declare const OPENAI_CODEX_AUTH_V1_BACKUP_SUFFIX = ".v1-backup";
27
+ interface OpenAICodexAccountSummary {
28
+ accountKey: string;
29
+ displayName: string;
30
+ maskedEmail?: string;
31
+ profileSource: OpenAICodexAccountProfileSource;
32
+ active: boolean;
33
+ }
34
+ /** One request's credentials and browser labels from the same document read. */
35
+ interface CapturedOpenAICodexAccount extends CredentialStore {
36
+ accounts(): Promise<readonly OpenAICodexAccountSummary[]>;
37
+ captureActiveAccount(): Promise<CapturedOpenAICodexAccount>;
38
+ }
39
+ /** Resolve the default OAuth document path under `$DSH_HOME`. */
40
+ export declare function openAICodexAuthPath(dshHome?: string): string;
41
+ /** File-backed pi-ai store scoped to the single OpenAI Codex provider. */
42
+ export declare class OpenAICodexCredentialStore implements CredentialStore {
43
+ /** Absolute credential document path. */
44
+ readonly filename: string;
45
+ /** Owner-only version-1 rollback copy, created at the first migration write. */
46
+ readonly version1BackupFilename: string;
47
+ constructor(filename?: string);
48
+ private readDocument;
49
+ private readDocumentAt;
50
+ private writeDocument;
51
+ /** @inheritdoc */
52
+ read(providerId: string): Promise<Credential | undefined>;
53
+ /**
54
+ * Capture the current account for one request's complete auth resolution.
55
+ * Refreshes through the returned store update only that captured account and
56
+ * never change the user's current account selection.
57
+ */
58
+ captureActiveAccount(): Promise<CapturedOpenAICodexAccount>;
59
+ private modifyCapturedAccount;
60
+ /** @inheritdoc */
61
+ list(): Promise<readonly CredentialInfo[]>;
62
+ /** List browser-safe account summaries without exposing provider account ids. */
63
+ accounts(): Promise<readonly OpenAICodexAccountSummary[]>;
64
+ /** Resolve the account id stored with one exact access token. */
65
+ accountIdForAccess(access: string): Promise<string | undefined>;
66
+ /** Select a stored account using its browser-safe key. */
67
+ activate(selectedAccountKey: string): Promise<OAuthCredential>;
68
+ /** Remove one account; active removal requires an explicit stored replacement. */
69
+ removeAccount(selectedAccountKey: string, replacementAccountKey?: string): Promise<void>;
70
+ /** @inheritdoc */
71
+ modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>, options?: Parameters<CredentialStore['modify']>[2]): Promise<Credential | undefined>;
72
+ /** @inheritdoc */
73
+ delete(providerId: string): Promise<void>;
74
+ /** Allow the provider's 15-second refresh plus bounded filesystem completion. */
75
+ private withWriterLock;
76
+ }
77
+ type OpenAICodexBackendIdentity = 'plugin' | 'preserve' | 'probe';
78
+ interface OpenAICodexBackendResponseMeta {
79
+ readonly clientRequestId: string;
80
+ readonly httpStatus: number;
81
+ readonly httpRequestId?: string;
82
+ readonly retryAfterMs?: number;
83
+ }
84
+ type OpenAICodexBackendLane = 'model' | 'search' | 'quota' | 'image';
85
+ type BackendFetch = typeof globalThis.fetch;
86
+ interface OpenAICodexBackendRunOptions {
87
+ readonly lane: OpenAICodexBackendLane;
88
+ readonly signal?: AbortSignal | undefined;
89
+ readonly timeoutMs?: number | undefined;
90
+ }
91
+ interface OpenAICodexBackendFetchOptions {
92
+ readonly lane: OpenAICodexBackendLane;
93
+ readonly responseFormat?: 'sse';
94
+ readonly identity?: OpenAICodexBackendIdentity;
95
+ readonly fetch?: BackendFetch;
96
+ readonly onAttempt?: (meta: Pick<OpenAICodexBackendResponseMeta, 'clientRequestId'>) => void;
97
+ readonly onResponse?: (meta: OpenAICodexBackendResponseMeta) => void | Promise<void>;
98
+ }
99
+ interface OpenAICodexBackendRunContext {
100
+ readonly signal: AbortSignal;
101
+ fetch(input: string | URL | Request, init?: RequestInit, options?: Omit<OpenAICodexBackendFetchOptions, 'lane'>): Promise<Response>;
102
+ }
103
+ /** One plugin instance owns one governor; it never guesses account-level service policy. */
104
+ declare class OpenAICodexBackendRequests {
105
+ private readonly maxConcurrent;
106
+ private readonly beforeAuxiliaryAttempt?;
107
+ private readonly beforeAttempt?;
108
+ private active;
109
+ private readonly waiters;
110
+ private readonly cooldowns;
111
+ private readonly lifecycle;
112
+ private disposed;
113
+ constructor(maxConcurrent?: number, beforeAuxiliaryAttempt?: (() => Promise<void>) | undefined, beforeAttempt?: (() => Promise<void>) | undefined);
114
+ private combinedSignal;
115
+ private drain;
116
+ private release;
117
+ private acquire;
118
+ private beforeRequest;
119
+ private admit;
120
+ private recordResponse;
121
+ private fetchAttempt;
122
+ /** Own one logical deadline scope; each HTTP attempt acquires its own slot. */
123
+ run<T>(options: OpenAICodexBackendRunOptions, operation: (context: OpenAICodexBackendRunContext) => Promise<T>): Promise<T>;
124
+ /** Wrap provider-owned fetch while preserving provider identity. */
125
+ wrapFetch(options: OpenAICodexBackendFetchOptions): BackendFetch;
126
+ /** Run a provider stream operation. */
127
+ runStream<T extends {
128
+ result(): Promise<unknown>;
129
+ }>(operation: () => T): T;
130
+ /** Abort queued/in-flight managed requests and prevent new admission. */
131
+ dispose(): void;
132
+ }
133
+ /** Pure encoded-image header validation for PNG, JPEG, and WebP. */
134
+ type CodexImageMediaType = 'image/png' | 'image/jpeg' | 'image/webp';
135
+ /** Bytes must already have passed the caller's session/attachment authorization. */
136
+ interface ImageEditInputBytes {
137
+ readonly data: Uint8Array;
138
+ readonly mediaType: CodexImageMediaType;
139
+ }
140
+ /** A host-only request. Model-visible attachment IDs are never provider file IDs. */
141
+ interface ImageEditRequest {
142
+ readonly prompt: string;
143
+ readonly images: readonly ImageEditInputBytes[];
144
+ }
145
+ /** Cordis service name owned by the core plugin fiber. */
146
+ export declare const OPENAI_CODEX_TRANSPORT_SERVICE = "openaiCodexTransport";
147
+ /** Structured contract version used across the core and companion packages. */
148
+ export declare const OPENAI_CODEX_TRANSPORT_API_VERSION: 1;
149
+ /** Stage-zero verified image-generation endpoint. */
150
+ export declare const OPENAI_CODEX_IMAGE_GENERATION_URL = "https://chatgpt.com/backend-api/codex/images/generations";
151
+ /** Network deadline covering the request and bounded response read. */
152
+ export declare const OPENAI_CODEX_IMAGE_REQUEST_TIMEOUT_MS = 120000;
153
+ /** Maximum accepted success-body size: 48 MiB. */
154
+ export declare const OPENAI_CODEX_IMAGE_MAX_RESPONSE_BYTES: number;
155
+ /** Maximum error-body size read and discarded: 64 KiB. */
156
+ export declare const OPENAI_CODEX_IMAGE_MAX_ERROR_BYTES: number;
157
+ /** Defensive upper bound for unexpected multi-image responses. */
158
+ export declare const OPENAI_CODEX_IMAGE_MAX_COUNT = 4;
159
+ /** Local prompt limit enforced before any credential or network work. */
160
+ export declare const OPENAI_CODEX_IMAGE_PROMPT_MAX_LENGTH = 32000;
161
+ /** Stable, secret-free transport errors consumed structurally by companion packages. */
162
+ export declare const OPENAI_CODEX_TRANSPORT_ERROR_CODES: {
163
+ readonly invalidRequest: "OPENAI_CODEX_INVALID_REQUEST";
164
+ readonly signedOut: "OPENAI_CODEX_SIGNED_OUT";
165
+ readonly reauthRequired: "OPENAI_CODEX_REAUTH_REQUIRED";
166
+ readonly rateLimited: "OPENAI_CODEX_RATE_LIMITED";
167
+ readonly upstreamRejected: "OPENAI_CODEX_UPSTREAM_REJECTED";
168
+ readonly upstreamUnavailable: "OPENAI_CODEX_UPSTREAM_UNAVAILABLE";
169
+ readonly redirectRejected: "OPENAI_CODEX_REDIRECT_REJECTED";
170
+ readonly timeout: "OPENAI_CODEX_TIMEOUT";
171
+ readonly canceled: "OPENAI_CODEX_CANCELED";
172
+ readonly networkError: "OPENAI_CODEX_NETWORK_ERROR";
173
+ readonly responseTooLarge: "OPENAI_CODEX_RESPONSE_TOO_LARGE";
174
+ readonly malformedResponse: "OPENAI_CODEX_MALFORMED_RESPONSE";
175
+ };
176
+ /** Union of the stable transport error codes. */
177
+ type OpenAICodexTransportErrorCode = (typeof OPENAI_CODEX_TRANSPORT_ERROR_CODES)[keyof typeof OPENAI_CODEX_TRANSPORT_ERROR_CODES];
178
+ /** Fixed, secret-free transport failure. */
179
+ export declare class OpenAICodexTransportError extends Error {
180
+ readonly code: OpenAICodexTransportErrorCode;
181
+ readonly status?: number;
182
+ readonly retryAfterSeconds?: number;
183
+ constructor(code: OpenAICodexTransportErrorCode, options?: {
184
+ status?: number;
185
+ retryAfterSeconds?: number;
186
+ });
187
+ }
188
+ /** Identify transport failures structurally without relying on cross-package class identity. */
189
+ export declare function isOpenAICodexTransportError(error: unknown): error is OpenAICodexTransportError;
190
+ /** Only caller-controlled field accepted by the Host transport. */
191
+ interface ImageGenerationRequest {
192
+ readonly prompt: string;
193
+ }
194
+ /** Request lifecycle supplied by the Host tool in PR-3. */
195
+ interface ImageRequestContext {
196
+ readonly signal?: AbortSignal | undefined;
197
+ }
198
+ /** One encoded image awaiting PR-3 signature and attachment validation. */
199
+ interface GeneratedImagePayload {
200
+ readonly b64Json: string;
201
+ }
202
+ /** Bounded, structured success projection returned to the companion package. */
203
+ interface ImageGenerationResponse {
204
+ readonly apiVersion: 1;
205
+ readonly traceId: string;
206
+ readonly elapsedMs: number;
207
+ readonly responseBytes: number;
208
+ readonly images: readonly GeneratedImagePayload[];
209
+ }
210
+ /** Versioned Host-only API provided by the core plugin. */
211
+ interface OpenAICodexTransportV1 {
212
+ readonly apiVersion: 1;
213
+ generateImages(input: ImageGenerationRequest, context: ImageRequestContext): Promise<ImageGenerationResponse>;
214
+ /** Additive capability: an older v1 service may not support editing. Never fall back. */
215
+ editImages?(input: ImageEditRequest, context: ImageRequestContext): Promise<ImageGenerationResponse>;
216
+ }
217
+ /** Core-owned Cordis service for the optional image package. */
218
+ export declare class OpenAICodexTransport extends Service implements OpenAICodexTransportV1 {
219
+ private readonly credentials;
220
+ private readonly resolveImageModelHint;
221
+ private readonly backendRequests?;
222
+ readonly apiVersion: 1;
223
+ constructor(ctx: Context, credentials: OpenAICodexCredentialStore, resolveImageModelHint?: () => string, backendRequests?: OpenAICodexBackendRequests | undefined);
224
+ generateImages(input: ImageGenerationRequest, context: ImageRequestContext): Promise<ImageGenerationResponse>;
225
+ editImages(input: ImageEditRequest, context: ImageRequestContext): Promise<ImageGenerationResponse>;
226
+ private requestImages;
227
+ private executeImageRequest;
228
+ }
229
+ /** GET/POST endpoint for one conversation's process-local Fast Mode state. */
230
+ export declare const OPENAI_CODEX_FAST_MODE_PATH = "/plugins/dsh-openai-codex/fast-mode";
231
+ /** Optional profile reasoning policy; model support remains owned by the Host adapter. */
232
+ declare const OPENAI_CODEX_REASONING_EFFORTS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
233
+ /** Reasoning levels accepted by the public PiAiAdapter profile. */
234
+ type OpenAICodexReasoningEffort = typeof OPENAI_CODEX_REASONING_EFFORTS[number];
235
+ type OpenAICodexSpeedMode = 'standard' | 'fast';
236
+ /** Stable Harness settings namespace owned by this plugin. */
237
+ export declare const OPENAI_CODEX_SETTINGS_NAMESPACE = "llm-openai-codex";
238
+ /** Empty profile setting, which makes image requests use the default route hint. */
239
+ export declare const DEFAULT_OPENAI_CODEX_IMAGE_MODEL_HINT = "";
240
+ /** Validate an optional bounded ASCII image route model hint. */
241
+ export declare function isValidOpenAICodexImageModelHint(value: unknown): value is string;
242
+ /** Search modes accepted by the Codex standalone search endpoint. */
243
+ type OpenAICodexSearchMode = 'cached' | 'indexed' | 'live';
244
+ /** Search-context sizes accepted by the Codex standalone search endpoint. */
245
+ type OpenAICodexSearchContextSize = 'low' | 'medium' | 'high';
246
+ /**
247
+ * Whether a value is a bounded per-model context-window override map. Keys
248
+ * are nonempty, unpadded model ids; values are positive safe integers or null
249
+ * to restore that model's catalog default.
250
+ */
251
+ export declare function isValidOpenAICodexContextWindowOverrides(value: unknown): value is Readonly<Record<string, number | null>>;
252
+ /** Default model used by the standalone search endpoint. */
253
+ export declare const DEFAULT_OPENAI_CODEX_SEARCH_MODEL = "gpt-5.6-sol";
254
+ /** Default search mode, matching the official local Codex client. */
255
+ export declare const DEFAULT_OPENAI_CODEX_SEARCH_MODE: OpenAICodexSearchMode;
256
+ /** Default provider search-context size. */
257
+ export declare const DEFAULT_OPENAI_CODEX_SEARCH_CONTEXT_SIZE: OpenAICodexSearchContextSize;
258
+ /** Default output budget for the standalone search response. */
259
+ export declare const DEFAULT_OPENAI_CODEX_SEARCH_MAX_OUTPUT_TOKENS = 10000;
260
+ /** Fully resolved user-editable section presented by Plugin configuration. */
261
+ interface OpenAICodexSettingsConfig {
262
+ /** Model ids advertised in selectors; undefined advertises the full catalog. */
263
+ models: string[] | undefined;
264
+ /** Optional fallback when a request does not specify reasoning effort. */
265
+ reasoningEffort: OpenAICodexReasoningEffort | undefined;
266
+ /** Per-model context-window overrides keyed by catalog model id. */
267
+ contextWindowOverrides: Readonly<Record<string, number>> | undefined;
268
+ enableSearch: boolean;
269
+ /** Default Fast Mode for newly started top-level sessions; existing sessions are unchanged. */
270
+ enableNewSessionFastMode: boolean;
271
+ /** Explicit new top-level default; omission retains the legacy Fast preference. */
272
+ newSessionSpeedMode: OpenAICodexSpeedMode | undefined;
273
+ /** Independent new-subagent default, with the same legacy omission behavior. */
274
+ newSubagentSpeedMode: OpenAICodexSpeedMode | undefined;
275
+ /** Independent default for newly started subagent sessions. */
276
+ enableNewSubagentFastMode: boolean;
277
+ /** Use provider-native Responses V2 compaction when DSH requests compaction. */
278
+ enableNativeCompaction: boolean;
279
+ enableImageGeneration: boolean;
280
+ /** Optional profile-scoped model hint for image generation; empty uses the route default. */
281
+ imageModelHint: string;
282
+ searchModel: string;
283
+ searchMode: OpenAICodexSearchMode;
284
+ searchContextSize: OpenAICodexSearchContextSize;
285
+ searchMaxOutputTokens: number;
286
+ }
287
+ export declare const DEFAULT_OPENAI_CODEX_SETTINGS: Readonly<OpenAICodexSettingsConfig>;
288
+ /** Input settings allow null to disable overrides inherited from a lower settings layer. */
289
+ interface OpenAICodexSettingsInput extends Partial<Omit<OpenAICodexSettingsConfig, 'contextWindowOverrides' | 'reasoningEffort' | 'newSessionSpeedMode' | 'newSubagentSpeedMode'>> {
290
+ reasoningEffort?: OpenAICodexReasoningEffort | null | undefined;
291
+ newSessionSpeedMode?: OpenAICodexSpeedMode | null | undefined;
292
+ newSubagentSpeedMode?: OpenAICodexSpeedMode | null | undefined;
293
+ contextWindowOverrides?: Readonly<Record<string, number | null>> | null | undefined;
294
+ }
295
+ /** Fill the schema defaults even when called without Cordis validation. */
296
+ export declare function resolveOpenAICodexSettings(value: OpenAICodexSettingsInput): OpenAICodexSettingsConfig;
297
+ /** Narrow the redacted settings wire payload before it enters React state. */
298
+ export declare function decodeOpenAICodexSettings(value: unknown): OpenAICodexSettingsConfig | undefined;
299
+ /** Plain configuration accepted by direct Cordis composition and unit tests. */
300
+ export interface Config {
301
+ newSessionSpeedMode?: OpenAICodexSpeedMode | null | undefined;
302
+ newSubagentSpeedMode?: OpenAICodexSpeedMode | null | undefined;
303
+ reasoningEffort?: OpenAICodexReasoningEffort | null | undefined;
304
+ retryPolicy?: RetryPolicyConfig | undefined;
305
+ oauthTimeoutMs?: number;
306
+ models?: string[] | undefined;
307
+ contextWindowOverrides?: Record<string, number | null> | null | undefined;
308
+ enableSearch?: boolean;
309
+ enableNewSessionFastMode?: boolean;
310
+ enableNewSubagentFastMode?: boolean;
311
+ enableNativeCompaction?: boolean;
312
+ enableImageGeneration?: boolean;
313
+ imageHandleBridgeTools?: string[] | undefined;
314
+ imageModelHint?: string;
315
+ searchModel?: string;
316
+ searchMode?: OpenAICodexSearchMode;
317
+ searchContextSize?: OpenAICodexSearchContextSize;
318
+ searchMaxOutputTokens?: number;
319
+ }
320
+ /** Runtime configuration exposes each editable field through Cordis's public Volatile type. */
321
+ interface VolatileConfig {
322
+ newSessionSpeedMode: Volatile<OpenAICodexSpeedMode | null | undefined>;
323
+ newSubagentSpeedMode: Volatile<OpenAICodexSpeedMode | null | undefined>;
324
+ reasoningEffort: Volatile<OpenAICodexReasoningEffort | null | undefined>;
325
+ retryPolicy?: RetryPolicyConfig | undefined;
326
+ oauthTimeoutMs: number;
327
+ models: Volatile<string[] | undefined>;
328
+ contextWindowOverrides: Volatile<Record<string, number | null> | null | undefined>;
329
+ enableSearch: Volatile<boolean>;
330
+ enableNewSessionFastMode: Volatile<boolean>;
331
+ enableNewSubagentFastMode: Volatile<boolean>;
332
+ enableNativeCompaction: Volatile<boolean>;
333
+ enableImageGeneration: Volatile<boolean>;
334
+ imageHandleBridgeTools: Volatile<string[] | undefined>;
335
+ imageModelHint: Volatile<string>;
336
+ searchModel: Volatile<string>;
337
+ searchMode: Volatile<OpenAICodexSearchMode>;
338
+ searchContextSize: Volatile<OpenAICodexSearchContextSize>;
339
+ searchMaxOutputTokens: Volatile<number>;
340
+ }
341
+ export declare const Config: z<Config, VolatileConfig>;
342
+ /** Stable model-callable tool name. */
343
+ export declare const IMAGE_GENERATE_TOOL_NAME = "codex_connect_image_generate";
344
+ interface OpenAICodexDiagnosticOptions {
345
+ credentialPath?: string;
346
+ dshHome?: string;
347
+ providerIds?: readonly string[];
348
+ enableSearch?: boolean;
349
+ enableImageGeneration?: boolean;
350
+ }
351
+ interface OpenAICodexDiagnosticReport {
352
+ package: '@shuind/dsh-codex-connect';
353
+ version: string;
354
+ node: string;
355
+ credentialFile: {
356
+ path: string;
357
+ state: 'missing' | 'owner-only' | 'permissions-too-broad' | 'not-a-regular-file' | 'unreadable-metadata';
358
+ mode?: string;
359
+ };
360
+ capabilities: {
361
+ modelProvider: true;
362
+ search: boolean;
363
+ imageGeneration: boolean;
364
+ changesHarnessDefaultModel: false;
365
+ changesHarnessSearchRoute: boolean;
366
+ };
367
+ providerConflict: boolean;
368
+ hints: string[];
369
+ }
370
+ /** Actionable message for legacy/manual `openai-codex` adapter collisions. */
371
+ export declare function openAICodexConflictMessage(): string;
372
+ /** Fail before the generic registry error so the collision has a migration hint. */
373
+ export declare function assertNoOpenAICodexProviderConflict(providerIds: readonly string[]): void;
374
+ /** Inspect local OAuth file metadata without reading credential contents. */
375
+ export declare function diagnoseOpenAICodex(options?: OpenAICodexDiagnosticOptions): Promise<OpenAICodexDiagnosticReport>;
376
+ /** One quota window expressed as remaining capacity for direct UI rendering. */
377
+ interface OpenAICodexRateLimitWindow {
378
+ /** Percent still available in this window. */
379
+ readonly remainingPercent: number;
380
+ /** Server-declared rolling-window length in seconds. */
381
+ readonly windowSeconds: number;
382
+ /** Server-declared reset time as Unix seconds, when supplied and valid. */
383
+ readonly resetAt?: number;
384
+ }
385
+ /** One separately metered Codex quota bucket. */
386
+ interface OpenAICodexRateLimit {
387
+ /** Stable server feature id. */
388
+ readonly id: string;
389
+ /** Optional server-provided display name. */
390
+ readonly name?: string;
391
+ /** Available rolling windows for this bucket. */
392
+ readonly windows: readonly OpenAICodexRateLimitWindow[];
393
+ }
394
+ /** Optional exact prepaid-credit balance returned by ChatGPT. */
395
+ interface OpenAICodexCredits {
396
+ /** Whether the balance is unmetered. */
397
+ readonly unlimited: boolean;
398
+ /** Exact provider-formatted balance when finite and disclosed. */
399
+ readonly balance?: string;
400
+ }
401
+ /** Optional exact workspace member spend limit returned by ChatGPT. */
402
+ interface OpenAICodexIndividualLimit {
403
+ /** Exact configured limit. */
404
+ readonly limit: string;
405
+ /** Exact amount consumed. */
406
+ readonly used: string;
407
+ /** Exact amount still available. */
408
+ readonly remaining: string;
409
+ /** Percent still available for progress rendering. */
410
+ readonly remainingPercent: number;
411
+ }
412
+ /** Secret-free quota projection returned to the browser. */
413
+ interface OpenAICodexUsage {
414
+ /** Rolling Codex rate-limit buckets. */
415
+ readonly rateLimits: readonly OpenAICodexRateLimit[];
416
+ /** Exact prepaid-credit balance when supported for this account. */
417
+ readonly credits?: OpenAICodexCredits;
418
+ /** Exact workspace member limit when supported for this account. */
419
+ readonly individualLimit?: OpenAICodexIndividualLimit;
420
+ }
421
+ /** Fixed endpoint used by the official Codex client for ChatGPT rate limits. */
422
+ export declare const OPENAI_CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
423
+ /**
424
+ * Convert the provider response into the small secret-free object sent to the browser.
425
+ * @param value - opaque JSON returned by the ChatGPT usage endpoint.
426
+ * @returns core and additionally metered quota buckets with remaining percentages.
427
+ */
428
+ export declare function parseOpenAICodexUsage(value: unknown): OpenAICodexUsage;
429
+ /**
430
+ * Read current quota without issuing a model request. OAuth is refreshed through
431
+ * the same provider-native credential lifecycle used by normal Codex turns.
432
+ * @param store - plugin-owned OAuth credential store.
433
+ * @returns current rate-limit buckets safe to expose to the local browser page.
434
+ */
435
+ export declare function readOpenAICodexRateLimits(store: Pick<OpenAICodexCredentialStore, 'captureActiveAccount'>): Promise<OpenAICodexUsage>;
436
+ /** Non-secret login state shown by the launcher. */
437
+ interface OpenAICodexAuthStatus {
438
+ /** Whether a stored OAuth credential exists. */
439
+ authenticated: boolean;
440
+ /** Access-token expiry time; refresh is automatic on the next request. */
441
+ expiresAt?: Date;
442
+ }
443
+ /**
444
+ * Complete provider-native OAuth and persist the resulting credential.
445
+ * @param interaction - terminal or UI callbacks for the provider flow.
446
+ * @param store - credential store, defaulting under `$DSH_HOME`.
447
+ */
448
+ export declare function loginOpenAICodex(interaction: AuthInteraction, store?: OpenAICodexCredentialStore): Promise<void>;
449
+ /**
450
+ * Remove the stored OpenAI Codex credential.
451
+ * @param store - credential store, defaulting under `$DSH_HOME`.
452
+ */
453
+ export declare function logoutOpenAICodex(store?: OpenAICodexCredentialStore): Promise<void>;
454
+ /**
455
+ * Read non-secret OpenAI Codex login state without refreshing the token.
456
+ * @param store - credential store, defaulting under `$DSH_HOME`.
457
+ * @returns stored login state and expiry.
458
+ */
459
+ export declare function openAICodexAuthStatus(store?: CredentialStore): Promise<OpenAICodexAuthStatus>;
460
+ /** Process-local, per-session OpenAI Codex Fast Mode state. */
461
+ /** Maximum number of enabled sessions retained by one plugin instance. */
462
+ export declare const OPENAI_CODEX_FAST_MODE_MAX_SESSIONS = 256;
463
+ /** Maximum UTF-16 code units accepted for an opaque DSH session id. */
464
+ export declare const OPENAI_CODEX_FAST_MODE_MAX_SESSION_ID_LENGTH = 256;
465
+ /**
466
+ * Validate the opaque session identity used by the Fast Mode registry.
467
+ *
468
+ * The registry deliberately does not interpret or normalize session ids. It
469
+ * only rejects values that cannot safely serve as a bounded map key.
470
+ */
471
+ export declare function isFastModeSessionId(value: unknown): value is string;
472
+ /**
473
+ * In-memory Fast Mode registry. Entries are positive-only: disabling a
474
+ * session removes its key, and an insertion over the bound evicts the least
475
+ * recently touched key. A new plugin instance starts with an empty map.
476
+ */
477
+ export declare class FastModeRegistry {
478
+ private readonly maxSessions;
479
+ private readonly enabledSessions;
480
+ constructor(maxSessions?: number);
481
+ /** Number of currently enabled sessions. */
482
+ get size(): number;
483
+ /** Read one session without exposing the map or any credential state. */
484
+ isEnabled(sessionId: unknown): boolean;
485
+ /** Alias useful to callers that model this as a boolean setting. */
486
+ get(sessionId: unknown): boolean;
487
+ /** Enable or disable exactly one opaque session id. */
488
+ set(sessionId: unknown, enabled: boolean): void;
489
+ /** Explicitly named alias for callers that avoid boolean-setting verbs. */
490
+ setEnabled(sessionId: unknown, enabled: boolean): void;
491
+ /** Disable one session and forget its key. */
492
+ delete(sessionId: unknown): void;
493
+ /** Remove all process-local state during an explicit lifecycle teardown. */
494
+ clear(): void;
495
+ }
496
+ /** Node-free update route constants, version helpers, DSH range matching, and result validation. */
497
+ export declare const OPENAI_CODEX_UPDATE_PATH = "/openai-codex/update";
498
+ type OpenAICodexUpdateResult = {
499
+ status: 'up-to-date';
500
+ currentVersion: string;
501
+ latestVersion: string;
502
+ } | {
503
+ status: 'update-available';
504
+ currentVersion: string;
505
+ latestVersion: string;
506
+ releaseUrl: string;
507
+ dshVersion?: string;
508
+ requiredDsh?: string;
509
+ dshCompatible?: boolean;
510
+ } | {
511
+ status: 'unavailable';
512
+ currentVersion: string;
513
+ reason: 'invalid-current-version' | 'registry-unavailable' | 'invalid-registry-response';
514
+ };
515
+ interface ParsedVersion {
516
+ major: number;
517
+ minor: number;
518
+ patch: number;
519
+ prerelease: Array<number | string>;
520
+ }
521
+ /** Parse one exact package version, accepting the conventional leading `v`. */
522
+ export declare function parseOpenAICodexVersion(raw: string): ParsedVersion | undefined;
523
+ /** Compare two package versions using SemVer precedence (build metadata ignored). */
524
+ export declare function compareOpenAICodexVersions(left: string, right: string): number;
525
+ /** Validate a route response before it is rendered by the browser. */
526
+ export declare function parseOpenAICodexUpdateResult(value: unknown): OpenAICodexUpdateResult | undefined;
527
+ type FetchImpl = (input: string, init?: RequestInit) => Promise<Response>;
528
+ interface UpdateCheckOptions {
529
+ currentVersion: string;
530
+ /** Override detected DSH version, or pass null to skip DSH compatibility checking. */
531
+ dshVersion?: string | null;
532
+ fetchImpl?: FetchImpl;
533
+ timeoutMs?: number;
534
+ }
535
+ /** Check npm dist-tags first, falling back to GitHub Releases, and verify DSH version compatibility. */
536
+ export declare function checkForOpenAICodexUpdate(options: UpdateCheckOptions): Promise<OpenAICodexUpdateResult>;
537
+ /** Stable dsh web-provider id selected by the bundle patch. */
538
+ export declare const OPENAI_CODEX_SEARCH_PROVIDER = "openai-codex";
539
+ /** Trusted first-party Codex base; OAuth credentials never cross to a configured origin. */
540
+ export declare const OPENAI_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex";
541
+ /** Standalone search endpoint used by the official Codex client. */
542
+ export declare const OPENAI_CODEX_SEARCH_URL = "https://chatgpt.com/backend-api/codex/alpha/search";
543
+ interface SearchRequestBody {
544
+ readonly id: string;
545
+ readonly model: string;
546
+ readonly input: readonly [{
547
+ readonly type: 'message';
548
+ readonly role: 'user';
549
+ readonly content: readonly [{
550
+ readonly type: 'input_text';
551
+ readonly text: string;
552
+ }];
553
+ }];
554
+ readonly commands: {
555
+ readonly search_query: readonly [{
556
+ readonly q: string;
557
+ }];
558
+ };
559
+ readonly settings: {
560
+ readonly search_context_size: OpenAICodexSearchContextSize;
561
+ readonly allowed_callers: readonly ['direct'];
562
+ readonly external_web_access: boolean | 'indexed';
563
+ };
564
+ readonly max_output_tokens: number;
565
+ }
566
+ /** Exact secret-free request recorded before a standalone search dispatch. */
567
+ interface OpenAICodexSearchRequestRecord {
568
+ /** Fixed first-party endpoint. */
569
+ readonly endpoint: typeof OPENAI_CODEX_SEARCH_URL;
570
+ /** Exact JSON body sent to the provider. */
571
+ readonly body: SearchRequestBody;
572
+ }
573
+ /** Fully resolved provider options. */
574
+ interface OpenAICodexSearchProviderOptions {
575
+ /** Shared persistent OAuth store. */
576
+ readonly credentials: OpenAICodexCredentialStore;
577
+ /** Model sent to the standalone search endpoint. */
578
+ readonly model: string;
579
+ /** Cached, indexed, or live external-web policy. */
580
+ readonly mode: OpenAICodexSearchMode;
581
+ /** Provider-side search context size. */
582
+ readonly contextSize: OpenAICodexSearchContextSize;
583
+ /** Upper bound on the standalone endpoint's generated output. */
584
+ readonly maxOutputTokens: number;
585
+ /** Resolve the request identity, normally the initiating session id. */
586
+ readonly resolveRequestId: () => string;
587
+ /** Shared runtime request governor. */
588
+ readonly backendRequests?: OpenAICodexBackendRequests;
589
+ /** Record the exact secret-free request before dispatch. */
590
+ readonly recordRequest?: (request: OpenAICodexSearchRequestRecord) => void;
591
+ }
592
+ /**
593
+ * Map the standalone endpoint's forward-compatible result DTOs into the dsh
594
+ * web result. Unknown DTO types and fields are ignored; malformed envelope
595
+ * fields fail at the network boundary.
596
+ * @param value - parsed response JSON.
597
+ * @returns normalized answer and citeable sources.
598
+ */
599
+ export declare function mapOpenAICodexSearchResponse(value: unknown): WebSearchResult;
600
+ /** OpenAI Codex standalone-search provider using the same refreshable OAuth store as the LLM route. */
601
+ export declare class OpenAICodexSearchProvider implements WebSearchProvider {
602
+ private readonly options;
603
+ readonly id = "openai-codex";
604
+ /**
605
+ * @param options - fixed trusted endpoint policy and deployment tunables.
606
+ */
607
+ constructor(options: OpenAICodexSearchProviderOptions);
608
+ /** The local configuration is usable; credential presence is resolved per request. */
609
+ available(): boolean;
610
+ /** @inheritdoc */
611
+ search(request: WebSearchRequest, signal?: AbortSignal): Promise<WebSearchResult>;
612
+ private executeSearch;
613
+ }
614
+ declare module '@deepseek-ai/cordis' {
615
+ interface Context {
616
+ /** Host-only image transport owned by the Codex Connect core fiber. */
617
+ openaiCodexTransport: OpenAICodexTransportV1;
618
+ }
619
+ }
620
+ /** Stable Cordis plugin name. */
621
+ export declare const name = "llm-openai-codex";
622
+ /** The model registry required before the provider can register. */
623
+ export declare const inject: string[];
624
+ /** Branded Host settings namespace for Codex Connect capability configuration. */
625
+ export declare const OPENAI_CODEX_SETTINGS_NS = "llm-openai-codex";
626
+ /**
627
+ * Register the `openai-codex` LLM route with one provider-native OAuth store.
628
+ * Search and image tooling are added only when their config flags are true.
629
+ */
630
+ export declare function apply(ctx: Context, config: Config | VolatileConfig): void;
631
+ export { FastModeRegistry as OpenAICodexFastModeRegistry, type GeneratedImagePayload, type ImageGenerationRequest, type ImageGenerationResponse, type ImageRequestContext, type OpenAICodexAccountSummary, type OpenAICodexAuthStatus, type OpenAICodexCredits, type OpenAICodexDiagnosticOptions, type OpenAICodexDiagnosticReport, type OpenAICodexIndividualLimit, type OpenAICodexRateLimit, type OpenAICodexRateLimitWindow, type OpenAICodexSearchContextSize, type OpenAICodexSearchMode, type OpenAICodexSearchProviderOptions, type OpenAICodexSearchRequestRecord, type OpenAICodexSettingsConfig, type OpenAICodexTransportErrorCode, type OpenAICodexTransportV1, type OpenAICodexUpdateResult, type OpenAICodexUsage, type VolatileConfig };