@gakr-gakr/codex 0.1.0

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 (86) hide show
  1. package/autobot.plugin.json +374 -0
  2. package/doctor-contract-api.ts +68 -0
  3. package/harness.ts +72 -0
  4. package/index.ts +124 -0
  5. package/media-understanding-provider.ts +521 -0
  6. package/package.json +40 -0
  7. package/prompt-overlay.ts +21 -0
  8. package/provider-catalog.ts +83 -0
  9. package/provider-discovery.ts +45 -0
  10. package/provider.ts +243 -0
  11. package/src/app-server/app-inventory-cache.ts +324 -0
  12. package/src/app-server/approval-bridge.ts +1211 -0
  13. package/src/app-server/auth-bridge.ts +614 -0
  14. package/src/app-server/capabilities.ts +27 -0
  15. package/src/app-server/client-factory.ts +24 -0
  16. package/src/app-server/client.ts +715 -0
  17. package/src/app-server/compact.ts +512 -0
  18. package/src/app-server/computer-use.ts +683 -0
  19. package/src/app-server/config.ts +1038 -0
  20. package/src/app-server/context-engine-projection.ts +403 -0
  21. package/src/app-server/dynamic-tool-diagnostics.ts +73 -0
  22. package/src/app-server/dynamic-tool-profile.ts +70 -0
  23. package/src/app-server/dynamic-tools.ts +623 -0
  24. package/src/app-server/elicitation-bridge.ts +783 -0
  25. package/src/app-server/event-projector.ts +2065 -0
  26. package/src/app-server/image-payload-sanitizer.ts +167 -0
  27. package/src/app-server/local-runtime-attribution.ts +39 -0
  28. package/src/app-server/managed-binary.ts +193 -0
  29. package/src/app-server/models.ts +172 -0
  30. package/src/app-server/native-hook-relay.ts +150 -0
  31. package/src/app-server/native-subagent-task-mirror.ts +497 -0
  32. package/src/app-server/plugin-activation.ts +283 -0
  33. package/src/app-server/plugin-app-cache-key.ts +74 -0
  34. package/src/app-server/plugin-approval-roundtrip.ts +122 -0
  35. package/src/app-server/plugin-inventory.ts +357 -0
  36. package/src/app-server/plugin-thread-config.ts +455 -0
  37. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +33 -0
  38. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +199 -0
  39. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +102 -0
  40. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +227 -0
  41. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +2630 -0
  42. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +2630 -0
  43. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +1659 -0
  44. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +1655 -0
  45. package/src/app-server/protocol-validators.ts +203 -0
  46. package/src/app-server/protocol.ts +520 -0
  47. package/src/app-server/rate-limit-cache.ts +48 -0
  48. package/src/app-server/rate-limits.ts +583 -0
  49. package/src/app-server/request.ts +73 -0
  50. package/src/app-server/run-attempt.ts +4862 -0
  51. package/src/app-server/session-binding.ts +398 -0
  52. package/src/app-server/session-history.ts +44 -0
  53. package/src/app-server/shared-client.ts +289 -0
  54. package/src/app-server/side-question.ts +1009 -0
  55. package/src/app-server/test-support.ts +48 -0
  56. package/src/app-server/thread-lifecycle.ts +959 -0
  57. package/src/app-server/timeout.ts +9 -0
  58. package/src/app-server/tool-progress-normalization.ts +77 -0
  59. package/src/app-server/trajectory.ts +368 -0
  60. package/src/app-server/transcript-mirror.ts +208 -0
  61. package/src/app-server/transport-stdio.ts +107 -0
  62. package/src/app-server/transport-websocket.ts +90 -0
  63. package/src/app-server/transport.ts +117 -0
  64. package/src/app-server/user-input-bridge.ts +316 -0
  65. package/src/app-server/version.ts +4 -0
  66. package/src/app-server/vision-tools.ts +12 -0
  67. package/src/command-account.ts +544 -0
  68. package/src/command-formatters.ts +426 -0
  69. package/src/command-handlers.ts +2021 -0
  70. package/src/command-plugins-management.ts +137 -0
  71. package/src/command-rpc.ts +142 -0
  72. package/src/commands.ts +65 -0
  73. package/src/conversation-binding-data.ts +124 -0
  74. package/src/conversation-binding.ts +561 -0
  75. package/src/conversation-control.ts +303 -0
  76. package/src/conversation-turn-collector.ts +186 -0
  77. package/src/conversation-turn-input.ts +106 -0
  78. package/src/migration/apply.ts +501 -0
  79. package/src/migration/helpers.ts +55 -0
  80. package/src/migration/plan.ts +461 -0
  81. package/src/migration/provider.ts +41 -0
  82. package/src/migration/source.ts +643 -0
  83. package/src/migration/targets.ts +25 -0
  84. package/src/node-cli-sessions.ts +711 -0
  85. package/test-api.ts +95 -0
  86. package/tsconfig.json +16 -0
@@ -0,0 +1,45 @@
1
+ import type { ProviderCatalogContext } from "autobot/plugin-sdk/provider-catalog-shared";
2
+ import type { ProviderPlugin } from "autobot/plugin-sdk/provider-model-shared";
3
+ import {
4
+ buildCodexProviderConfig,
5
+ CODEX_APP_SERVER_AUTH_MARKER,
6
+ CODEX_PROVIDER_ID,
7
+ FALLBACK_CODEX_MODELS,
8
+ } from "./provider-catalog.js";
9
+
10
+ function resolveCodexPluginConfig(ctx: ProviderCatalogContext): unknown {
11
+ return (ctx.config.plugins?.entries as Record<string, { config?: unknown } | undefined>)?.codex
12
+ ?.config;
13
+ }
14
+
15
+ async function runCodexCatalog(ctx: ProviderCatalogContext) {
16
+ const { buildCodexProviderCatalog } = await import("./provider.js");
17
+ return await buildCodexProviderCatalog({
18
+ env: ctx.env,
19
+ pluginConfig: resolveCodexPluginConfig(ctx),
20
+ });
21
+ }
22
+
23
+ export const codexProviderDiscovery: ProviderPlugin = {
24
+ id: CODEX_PROVIDER_ID,
25
+ label: "Codex",
26
+ docsPath: "/providers/models",
27
+ auth: [],
28
+ catalog: {
29
+ order: "late",
30
+ run: runCodexCatalog,
31
+ },
32
+ staticCatalog: {
33
+ order: "late",
34
+ run: async () => ({
35
+ provider: buildCodexProviderConfig(FALLBACK_CODEX_MODELS),
36
+ }),
37
+ },
38
+ resolveSyntheticAuth: () => ({
39
+ apiKey: CODEX_APP_SERVER_AUTH_MARKER,
40
+ source: "codex-app-server",
41
+ mode: "token",
42
+ }),
43
+ };
44
+
45
+ export default codexProviderDiscovery;
package/provider.ts ADDED
@@ -0,0 +1,243 @@
1
+ import { createSubsystemLogger } from "autobot/plugin-sdk/core";
2
+ import { resolvePluginConfigObject } from "autobot/plugin-sdk/plugin-config-runtime";
3
+ import type { ProviderRuntimeModel } from "autobot/plugin-sdk/plugin-entry";
4
+ import {
5
+ normalizeModelCompat,
6
+ type ModelProviderConfig,
7
+ type ProviderPlugin,
8
+ } from "autobot/plugin-sdk/provider-model-shared";
9
+ import { resolveCodexSystemPromptContribution } from "./prompt-overlay.js";
10
+ import {
11
+ buildCodexModelDefinition,
12
+ buildCodexProviderConfig,
13
+ CODEX_APP_SERVER_AUTH_MARKER,
14
+ CODEX_BASE_URL,
15
+ CODEX_PROVIDER_ID,
16
+ FALLBACK_CODEX_MODELS,
17
+ } from "./provider-catalog.js";
18
+ import {
19
+ type CodexAppServerStartOptions,
20
+ readCodexPluginConfig,
21
+ resolveCodexAppServerRuntimeOptions,
22
+ } from "./src/app-server/config.js";
23
+ import type {
24
+ CodexAppServerModel,
25
+ CodexAppServerModelListResult,
26
+ } from "./src/app-server/models.js";
27
+
28
+ const DEFAULT_DISCOVERY_TIMEOUT_MS = 2500;
29
+ const LIVE_DISCOVERY_ENV = "AUTOBOT_CODEX_DISCOVERY_LIVE";
30
+ const MODEL_DISCOVERY_PAGE_LIMIT = 100;
31
+ const CODEX_APP_SERVER_SETUP_METHOD_ID = "app-server";
32
+ const CODEX_DEFAULT_MODEL_REF = `${CODEX_PROVIDER_ID}/${FALLBACK_CODEX_MODELS[0].id}`;
33
+ const codexCatalogLog = createSubsystemLogger("codex/catalog");
34
+
35
+ type CodexModelLister = (options: {
36
+ timeoutMs: number;
37
+ limit?: number;
38
+ cursor?: string;
39
+ startOptions?: CodexAppServerStartOptions;
40
+ sharedClient?: boolean;
41
+ }) => Promise<CodexAppServerModelListResult>;
42
+
43
+ type BuildCodexProviderOptions = {
44
+ pluginConfig?: unknown;
45
+ listModels?: CodexModelLister;
46
+ };
47
+
48
+ type BuildCatalogOptions = {
49
+ env?: NodeJS.ProcessEnv;
50
+ pluginConfig?: unknown;
51
+ listModels?: CodexModelLister;
52
+ onDiscoveryFailure?: (error: unknown) => void;
53
+ };
54
+
55
+ export function buildCodexProvider(options: BuildCodexProviderOptions = {}): ProviderPlugin {
56
+ return {
57
+ id: CODEX_PROVIDER_ID,
58
+ label: "Codex",
59
+ docsPath: "/providers/models",
60
+ auth: [
61
+ {
62
+ id: CODEX_APP_SERVER_SETUP_METHOD_ID,
63
+ label: "Codex app-server",
64
+ hint: "Use the Codex app-server runtime and managed model catalog.",
65
+ kind: "custom",
66
+ wizard: {
67
+ choiceId: CODEX_PROVIDER_ID,
68
+ choiceLabel: "Codex app-server",
69
+ choiceHint: "Use the Codex app-server runtime and managed model catalog.",
70
+ assistantPriority: -40,
71
+ groupId: CODEX_PROVIDER_ID,
72
+ groupLabel: "Codex",
73
+ groupHint: "Codex app-server model provider",
74
+ onboardingScopes: ["text-inference"],
75
+ },
76
+ run: async () => ({ profiles: [], defaultModel: CODEX_DEFAULT_MODEL_REF }),
77
+ },
78
+ ],
79
+ catalog: {
80
+ order: "late",
81
+ run: async (ctx) => {
82
+ const runtimePluginConfig = resolvePluginConfigObject(ctx.config, CODEX_PROVIDER_ID);
83
+ const pluginConfig = runtimePluginConfig ?? (ctx.config ? undefined : options.pluginConfig);
84
+ return await buildCodexProviderCatalog({
85
+ env: ctx.env,
86
+ pluginConfig,
87
+ listModels: options.listModels,
88
+ });
89
+ },
90
+ },
91
+ staticCatalog: {
92
+ order: "late",
93
+ run: async () => ({
94
+ provider: buildCodexProviderConfig(FALLBACK_CODEX_MODELS),
95
+ }),
96
+ },
97
+ resolveDynamicModel: (ctx) => resolveCodexDynamicModel(ctx.modelId),
98
+ resolveSyntheticAuth: () => ({
99
+ apiKey: CODEX_APP_SERVER_AUTH_MARKER,
100
+ source: "codex-app-server",
101
+ mode: "token",
102
+ }),
103
+ resolveThinkingProfile: ({ modelId }) => ({
104
+ levels: [
105
+ { id: "off" },
106
+ { id: "minimal" },
107
+ { id: "low" },
108
+ { id: "medium" },
109
+ { id: "high" },
110
+ ...(isKnownXHighCodexModel(modelId) ? [{ id: "xhigh" as const }] : []),
111
+ ],
112
+ }),
113
+ resolveSystemPromptContribution: ({ config, modelId }) =>
114
+ resolveCodexSystemPromptContribution({ config, modelId }),
115
+ isModernModelRef: ({ modelId }) => isModernCodexModel(modelId),
116
+ };
117
+ }
118
+
119
+ export async function buildCodexProviderCatalog(
120
+ options: BuildCatalogOptions = {},
121
+ ): Promise<{ provider: ModelProviderConfig }> {
122
+ const config = readCodexPluginConfig(options.pluginConfig);
123
+ const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig: options.pluginConfig });
124
+ const timeoutMs = normalizeTimeoutMs(config.discovery?.timeoutMs);
125
+ let discovered: CodexAppServerModel[] = [];
126
+ if (config.discovery?.enabled !== false && !shouldSkipLiveDiscovery(options.env)) {
127
+ discovered = await listModelsBestEffort({
128
+ listModels: options.listModels ?? listCodexAppServerModelsLazy,
129
+ timeoutMs,
130
+ startOptions: appServer.start,
131
+ onDiscoveryFailure: options.onDiscoveryFailure,
132
+ });
133
+ }
134
+ return {
135
+ provider: buildCodexProviderConfig(discovered.length > 0 ? discovered : FALLBACK_CODEX_MODELS),
136
+ };
137
+ }
138
+
139
+ function resolveCodexDynamicModel(modelId: string) {
140
+ const id = modelId.trim();
141
+ if (!id) {
142
+ return undefined;
143
+ }
144
+ const fallbackModel = FALLBACK_CODEX_MODELS.find((model) => model.id === id);
145
+ return normalizeModelCompat({
146
+ ...buildCodexModelDefinition({
147
+ id,
148
+ model: id,
149
+ inputModalities: fallbackModel?.inputModalities ?? ["text"],
150
+ supportedReasoningEfforts:
151
+ fallbackModel?.supportedReasoningEfforts ??
152
+ (shouldDefaultToReasoningModel(id) ? ["medium"] : []),
153
+ }),
154
+ provider: CODEX_PROVIDER_ID,
155
+ baseUrl: CODEX_BASE_URL,
156
+ } as ProviderRuntimeModel);
157
+ }
158
+
159
+ async function listModelsBestEffort(params: {
160
+ listModels: CodexModelLister;
161
+ timeoutMs: number;
162
+ startOptions: CodexAppServerStartOptions;
163
+ onDiscoveryFailure?: (error: unknown) => void;
164
+ }): Promise<CodexAppServerModel[]> {
165
+ try {
166
+ const models: CodexAppServerModel[] = [];
167
+ let cursor: string | undefined;
168
+ do {
169
+ const result = await params.listModels({
170
+ timeoutMs: params.timeoutMs,
171
+ limit: MODEL_DISCOVERY_PAGE_LIMIT,
172
+ cursor,
173
+ startOptions: params.startOptions,
174
+ sharedClient: false,
175
+ });
176
+ models.push(...result.models.filter((model) => !model.hidden));
177
+ cursor = result.nextCursor;
178
+ } while (cursor);
179
+ return models;
180
+ } catch (error) {
181
+ params.onDiscoveryFailure?.(error);
182
+ codexCatalogLog.debug("codex model discovery failed; using fallback catalog", {
183
+ error: error instanceof Error ? error.message : String(error),
184
+ });
185
+ return [];
186
+ }
187
+ }
188
+
189
+ async function listCodexAppServerModelsLazy(options: {
190
+ timeoutMs: number;
191
+ limit?: number;
192
+ cursor?: string;
193
+ startOptions?: CodexAppServerStartOptions;
194
+ sharedClient?: boolean;
195
+ }): Promise<CodexAppServerModelListResult> {
196
+ const { listCodexAppServerModels } = await import("./src/app-server/models.js");
197
+ return listCodexAppServerModels(options);
198
+ }
199
+
200
+ function normalizeTimeoutMs(value: unknown): number {
201
+ return typeof value === "number" && Number.isFinite(value) && value > 0
202
+ ? value
203
+ : DEFAULT_DISCOVERY_TIMEOUT_MS;
204
+ }
205
+
206
+ function shouldSkipLiveDiscovery(env: NodeJS.ProcessEnv = process.env): boolean {
207
+ const override = env[LIVE_DISCOVERY_ENV]?.trim().toLowerCase();
208
+ if (override === "0" || override === "false") {
209
+ return true;
210
+ }
211
+ return Boolean(env.VITEST) && override !== "1";
212
+ }
213
+
214
+ function shouldDefaultToReasoningModel(modelId: string): boolean {
215
+ const lower = modelId.toLowerCase();
216
+ return (
217
+ lower.startsWith("gpt-5") ||
218
+ lower.startsWith("o1") ||
219
+ lower.startsWith("o3") ||
220
+ lower.startsWith("o4")
221
+ );
222
+ }
223
+
224
+ function isKnownXHighCodexModel(modelId: string): boolean {
225
+ const lower = modelId.trim().toLowerCase();
226
+ return (
227
+ lower.startsWith("gpt-5") ||
228
+ lower.startsWith("o3") ||
229
+ lower.startsWith("o4") ||
230
+ lower.includes("codex")
231
+ );
232
+ }
233
+
234
+ // Exported so adapter request paths (thread-lifecycle.resolveReasoningEffort)
235
+ // can branch on model-family enum support: modern Codex models use the
236
+ // none/low/medium/high/xhigh effort enum and reject "minimal", which is the
237
+ // CLI default. (#71946)
238
+ export function isModernCodexModel(modelId: string): boolean {
239
+ const lower = modelId.trim().toLowerCase();
240
+ return (
241
+ lower === "gpt-5.5" || lower === "gpt-5.4" || lower === "gpt-5.4-mini" || lower === "gpt-5.2"
242
+ );
243
+ }
@@ -0,0 +1,324 @@
1
+ import { embeddedAgentLog } from "autobot/plugin-sdk/agent-harness-runtime";
2
+ import type { JsonValue, v2 } from "./protocol.js";
3
+
4
+ export const CODEX_APP_INVENTORY_CACHE_TTL_MS = 60 * 60 * 1_000;
5
+ const MAX_SERIALIZED_ERROR_MESSAGE_LENGTH = 500;
6
+
7
+ export type CodexAppInventoryRequest = (
8
+ method: "app/list",
9
+ params: v2.AppsListParams,
10
+ ) => Promise<v2.AppsListResponse>;
11
+
12
+ export type CodexAppInventoryCacheKeyInput = {
13
+ codexHome?: string;
14
+ endpoint?: string;
15
+ authProfileId?: string;
16
+ accountId?: string;
17
+ envApiKeyFingerprint?: string;
18
+ appServerVersion?: string;
19
+ };
20
+
21
+ export type CodexAppInventoryCacheDiagnostic = {
22
+ message: string;
23
+ atMs: number;
24
+ };
25
+
26
+ export type CodexAppInventorySnapshot = {
27
+ key: string;
28
+ apps: v2.AppInfo[];
29
+ fetchedAtMs: number;
30
+ expiresAtMs: number;
31
+ revision: number;
32
+ lastError?: CodexAppInventoryCacheDiagnostic;
33
+ };
34
+
35
+ export type CodexAppInventoryReadState = "fresh" | "stale" | "missing";
36
+
37
+ export type CodexAppInventoryCacheRead = {
38
+ state: CodexAppInventoryReadState;
39
+ key: string;
40
+ revision: number;
41
+ snapshot?: CodexAppInventorySnapshot;
42
+ refreshScheduled: boolean;
43
+ diagnostic?: CodexAppInventoryCacheDiagnostic;
44
+ };
45
+
46
+ type CacheEntry = CodexAppInventorySnapshot & {
47
+ invalidated: boolean;
48
+ };
49
+
50
+ type RefreshParams = {
51
+ key: string;
52
+ request: CodexAppInventoryRequest;
53
+ nowMs?: number;
54
+ forceRefetch?: boolean;
55
+ suppressRefresh?: boolean;
56
+ };
57
+
58
+ export class CodexAppInventoryCache {
59
+ private readonly ttlMs: number;
60
+ private readonly entries = new Map<string, CacheEntry>();
61
+ private readonly inFlight = new Map<string, Promise<CodexAppInventorySnapshot>>();
62
+ // Per-key refresh generation. Each refresh attempt claims the next token so
63
+ // an older request that finishes late cannot overwrite a newer snapshot.
64
+ private readonly refreshTokens = new Map<string, number>();
65
+ private readonly diagnostics = new Map<string, CodexAppInventoryCacheDiagnostic>();
66
+ private revision = 0;
67
+
68
+ constructor(options: { ttlMs?: number } = {}) {
69
+ this.ttlMs = options.ttlMs ?? CODEX_APP_INVENTORY_CACHE_TTL_MS;
70
+ }
71
+
72
+ read(params: RefreshParams): CodexAppInventoryCacheRead {
73
+ const nowMs = params.nowMs ?? Date.now();
74
+ const entry = this.entries.get(params.key);
75
+ if (!entry) {
76
+ const refreshScheduled = params.suppressRefresh ? false : this.scheduleRefresh(params);
77
+ return {
78
+ state: "missing",
79
+ key: params.key,
80
+ revision: this.revision,
81
+ refreshScheduled,
82
+ ...(this.diagnostics.get(params.key)
83
+ ? { diagnostic: this.diagnostics.get(params.key) }
84
+ : {}),
85
+ };
86
+ }
87
+
88
+ const state: CodexAppInventoryReadState =
89
+ entry.invalidated || entry.expiresAtMs <= nowMs ? "stale" : "fresh";
90
+ const refreshScheduled =
91
+ state === "fresh" && !params.forceRefetch ? false : this.scheduleRefresh(params);
92
+ return {
93
+ state,
94
+ key: params.key,
95
+ revision: entry.revision,
96
+ snapshot: stripEntryState(entry),
97
+ refreshScheduled,
98
+ ...(entry.lastError ? { diagnostic: entry.lastError } : {}),
99
+ };
100
+ }
101
+
102
+ refreshNow(params: RefreshParams): Promise<CodexAppInventorySnapshot> {
103
+ return this.refresh(params);
104
+ }
105
+
106
+ invalidate(key: string, reason: string, nowMs = Date.now()): number {
107
+ this.revision += 1;
108
+ const diagnostic = { message: reason, atMs: nowMs };
109
+ const entry = this.entries.get(key);
110
+ if (entry) {
111
+ entry.invalidated = true;
112
+ entry.lastError = diagnostic;
113
+ entry.revision = this.revision;
114
+ } else {
115
+ this.diagnostics.set(key, diagnostic);
116
+ }
117
+ return this.revision;
118
+ }
119
+
120
+ clear(): void {
121
+ this.entries.clear();
122
+ this.inFlight.clear();
123
+ this.refreshTokens.clear();
124
+ this.diagnostics.clear();
125
+ this.revision = 0;
126
+ }
127
+
128
+ getRevision(): number {
129
+ return this.revision;
130
+ }
131
+
132
+ private scheduleRefresh(params: RefreshParams): boolean {
133
+ if (this.inFlight.has(params.key) && !params.forceRefetch) {
134
+ return true;
135
+ }
136
+ const promise = this.refresh(params);
137
+ this.inFlight.set(params.key, promise);
138
+ promise.catch(() => undefined);
139
+ return true;
140
+ }
141
+
142
+ private async refresh(params: RefreshParams): Promise<CodexAppInventorySnapshot> {
143
+ const existing = this.inFlight.get(params.key);
144
+ if (existing && !params.forceRefetch) {
145
+ return existing;
146
+ }
147
+
148
+ const refreshToken = (this.refreshTokens.get(params.key) ?? 0) + 1;
149
+ this.refreshTokens.set(params.key, refreshToken);
150
+ const promise = this.refreshUncoalesced(params, refreshToken);
151
+ this.inFlight.set(params.key, promise);
152
+ try {
153
+ return await promise;
154
+ } finally {
155
+ if (this.inFlight.get(params.key) === promise) {
156
+ this.inFlight.delete(params.key);
157
+ }
158
+ }
159
+ }
160
+
161
+ private async refreshUncoalesced(
162
+ params: RefreshParams,
163
+ refreshToken: number,
164
+ ): Promise<CodexAppInventorySnapshot> {
165
+ const nowMs = params.nowMs ?? Date.now();
166
+ try {
167
+ const apps = await listAllApps(params.request, params.forceRefetch ?? false);
168
+ this.revision += 1;
169
+ const snapshot: CodexAppInventorySnapshot = {
170
+ key: params.key,
171
+ apps,
172
+ fetchedAtMs: nowMs,
173
+ expiresAtMs: nowMs + this.ttlMs,
174
+ revision: this.revision,
175
+ };
176
+ // Only publish this snapshot if no newer refresh started for the same key
177
+ // while this request was in flight.
178
+ if (this.refreshTokens.get(params.key) === refreshToken) {
179
+ this.entries.set(params.key, { ...snapshot, invalidated: false });
180
+ this.diagnostics.delete(params.key);
181
+ }
182
+ return snapshot;
183
+ } catch (error) {
184
+ const diagnostic = {
185
+ message: sanitizeErrorMessage(error instanceof Error ? error.message : String(error)),
186
+ atMs: nowMs,
187
+ };
188
+ this.diagnostics.set(params.key, diagnostic);
189
+ const entry = this.entries.get(params.key);
190
+ if (entry) {
191
+ entry.lastError = diagnostic;
192
+ }
193
+ embeddedAgentLog.warn("codex app inventory refresh failed", {
194
+ forceRefetch: params.forceRefetch === true,
195
+ keyFingerprint: fingerprintInventoryCacheKey(params.key),
196
+ error: serializeCodexAppInventoryError(error),
197
+ });
198
+ throw error;
199
+ }
200
+ }
201
+ }
202
+
203
+ export function serializeCodexAppInventoryError(error: unknown): Record<string, unknown> {
204
+ const record = isRecord(error) ? error : undefined;
205
+ const data = record && "data" in record ? redactErrorData(record.data) : undefined;
206
+ return {
207
+ name:
208
+ error instanceof Error
209
+ ? error.name
210
+ : typeof record?.name === "string"
211
+ ? record.name
212
+ : undefined,
213
+ message: sanitizeErrorMessage(error instanceof Error ? error.message : String(error)),
214
+ ...(typeof record?.code === "number" ? { code: record.code } : {}),
215
+ ...(data !== undefined ? { data } : {}),
216
+ };
217
+ }
218
+
219
+ export const defaultCodexAppInventoryCache = new CodexAppInventoryCache();
220
+
221
+ export function buildCodexAppInventoryCacheKey(input: CodexAppInventoryCacheKeyInput): string {
222
+ return JSON.stringify({
223
+ codexHome: input.codexHome ?? null,
224
+ endpoint: input.endpoint ?? null,
225
+ authProfileId: input.authProfileId ?? null,
226
+ accountId: input.accountId ?? null,
227
+ envApiKeyFingerprint: input.envApiKeyFingerprint ?? null,
228
+ appServerVersion: input.appServerVersion ?? null,
229
+ });
230
+ }
231
+
232
+ async function listAllApps(
233
+ request: CodexAppInventoryRequest,
234
+ forceRefetch: boolean,
235
+ ): Promise<v2.AppInfo[]> {
236
+ const apps: v2.AppInfo[] = [];
237
+ let cursor: string | null | undefined;
238
+ do {
239
+ const response = await request("app/list", {
240
+ cursor,
241
+ limit: 100,
242
+ forceRefetch,
243
+ });
244
+ apps.push(...response.data);
245
+ cursor = response.nextCursor;
246
+ } while (cursor);
247
+ return apps;
248
+ }
249
+
250
+ function stripEntryState(entry: CacheEntry): CodexAppInventorySnapshot {
251
+ const { invalidated: _invalidated, ...snapshot } = entry;
252
+ return snapshot;
253
+ }
254
+
255
+ function fingerprintInventoryCacheKey(key: string): string {
256
+ let hash = 0;
257
+ for (let index = 0; index < key.length; index += 1) {
258
+ hash = (hash * 31 + key.charCodeAt(index)) >>> 0;
259
+ }
260
+ return hash.toString(16).padStart(8, "0");
261
+ }
262
+
263
+ function isRecord(value: unknown): value is Record<string, unknown> {
264
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
265
+ }
266
+
267
+ function redactErrorData(value: unknown, depth = 0): JsonValue | undefined {
268
+ if (value === undefined) {
269
+ return undefined;
270
+ }
271
+ if (value === null || typeof value === "boolean" || typeof value === "number") {
272
+ return value;
273
+ }
274
+ if (depth > 6) {
275
+ return "[truncated]";
276
+ }
277
+ if (Array.isArray(value)) {
278
+ return value.map((entry) => redactErrorData(entry, depth + 1) ?? null);
279
+ }
280
+ if (isRecord(value)) {
281
+ const redacted: Record<string, JsonValue> = {};
282
+ for (const [key, entry] of Object.entries(value)) {
283
+ redacted[key] = isSensitiveErrorDataKey(key)
284
+ ? "<redacted>"
285
+ : (redactErrorData(entry, depth + 1) ?? null);
286
+ }
287
+ return redacted;
288
+ }
289
+ if (typeof value === "string" && value.length > 500) {
290
+ return `${value.slice(0, 500)}...`;
291
+ }
292
+ if (typeof value === "string") {
293
+ return value;
294
+ }
295
+ if (typeof value === "bigint") {
296
+ return value.toString();
297
+ }
298
+ if (typeof value === "symbol") {
299
+ return value.description ? `Symbol(${value.description})` : "Symbol()";
300
+ }
301
+ if (typeof value === "function") {
302
+ return value.name ? `[function ${value.name}]` : "[function]";
303
+ }
304
+ return "[unserializable]";
305
+ }
306
+
307
+ function sanitizeErrorMessage(message: string): string {
308
+ const htmlStart = message.search(/<html[\s>]/i);
309
+ const withoutHtml =
310
+ htmlStart >= 0
311
+ ? `${message.slice(0, htmlStart).trimEnd()} [HTML response body omitted]`
312
+ : message;
313
+ const redacted = withoutHtml.replace(
314
+ /([?&][^=\s"'<>]*(?:api[_-]?key|authorization|cookie|credential|password|secret|token|tk)[^=\s"'<>]*=)[^&\s"'<>]+/gi,
315
+ "$1<redacted>",
316
+ );
317
+ return redacted.length > MAX_SERIALIZED_ERROR_MESSAGE_LENGTH
318
+ ? `${redacted.slice(0, MAX_SERIALIZED_ERROR_MESSAGE_LENGTH)}...`
319
+ : redacted;
320
+ }
321
+
322
+ function isSensitiveErrorDataKey(key: string): boolean {
323
+ return /api[_-]?key|authorization|cookie|credential|password|secret|token/i.test(key);
324
+ }