@gakr-gakr/codex 0.1.0 → 0.1.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 (115) hide show
  1. package/dist/client-DNN2uyJW.js +642 -0
  2. package/dist/client-factory-Bu9OClHJ.js +9 -0
  3. package/dist/command-formatters-BpPOTePl.js +520 -0
  4. package/dist/command-handlers-BBs7Vws9.js +1533 -0
  5. package/dist/compact-CDboBy7o.js +329 -0
  6. package/dist/computer-use-DCZB46Sw.js +367 -0
  7. package/dist/config-CLMSw0p2.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1171 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-jLA2SIvd.js +110 -0
  13. package/dist/node-cli-sessions-BLRDs_US.js +1216 -0
  14. package/dist/plugin-activation-CEy_oYpx.js +452 -0
  15. package/dist/prompt-overlay.js +12 -0
  16. package/dist/protocol-C9UWI98H.js +9 -0
  17. package/dist/protocol-validators-BGBspNmF.js +5988 -0
  18. package/dist/provider-catalog.js +84 -0
  19. package/dist/provider-discovery.js +33 -0
  20. package/dist/provider.js +150 -0
  21. package/dist/rate-limit-cache-9LxQdE0K.js +24 -0
  22. package/dist/request-DbSPeTcV.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-BoEwzQCv.js +5463 -0
  25. package/dist/session-binding-e2GFp9VH.js +222 -0
  26. package/dist/shared-client-D7Vy0glq.js +631 -0
  27. package/dist/side-question-BDLuEzFP.js +668 -0
  28. package/dist/test-api.js +49 -0
  29. package/dist/thread-lifecycle-Clo0EHMk.js +1565 -0
  30. package/dist/vision-tools-Cofrv35p.js +1379 -0
  31. package/package.json +16 -1
  32. package/doctor-contract-api.ts +0 -68
  33. package/harness.ts +0 -72
  34. package/index.ts +0 -124
  35. package/media-understanding-provider.ts +0 -521
  36. package/prompt-overlay.ts +0 -21
  37. package/provider-catalog.ts +0 -83
  38. package/provider-discovery.ts +0 -45
  39. package/provider.ts +0 -243
  40. package/src/app-server/app-inventory-cache.ts +0 -324
  41. package/src/app-server/approval-bridge.ts +0 -1211
  42. package/src/app-server/auth-bridge.ts +0 -614
  43. package/src/app-server/capabilities.ts +0 -27
  44. package/src/app-server/client-factory.ts +0 -24
  45. package/src/app-server/client.ts +0 -715
  46. package/src/app-server/compact.ts +0 -512
  47. package/src/app-server/computer-use.ts +0 -683
  48. package/src/app-server/config.ts +0 -1038
  49. package/src/app-server/context-engine-projection.ts +0 -403
  50. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  51. package/src/app-server/dynamic-tool-profile.ts +0 -70
  52. package/src/app-server/dynamic-tools.ts +0 -623
  53. package/src/app-server/elicitation-bridge.ts +0 -783
  54. package/src/app-server/event-projector.ts +0 -2065
  55. package/src/app-server/image-payload-sanitizer.ts +0 -167
  56. package/src/app-server/local-runtime-attribution.ts +0 -39
  57. package/src/app-server/managed-binary.ts +0 -193
  58. package/src/app-server/models.ts +0 -172
  59. package/src/app-server/native-hook-relay.ts +0 -150
  60. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  61. package/src/app-server/plugin-activation.ts +0 -283
  62. package/src/app-server/plugin-app-cache-key.ts +0 -74
  63. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  64. package/src/app-server/plugin-inventory.ts +0 -357
  65. package/src/app-server/plugin-thread-config.ts +0 -455
  66. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  67. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  68. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  69. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  70. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  71. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  72. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  73. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  74. package/src/app-server/protocol-validators.ts +0 -203
  75. package/src/app-server/protocol.ts +0 -520
  76. package/src/app-server/rate-limit-cache.ts +0 -48
  77. package/src/app-server/rate-limits.ts +0 -583
  78. package/src/app-server/request.ts +0 -73
  79. package/src/app-server/run-attempt.ts +0 -4862
  80. package/src/app-server/session-binding.ts +0 -398
  81. package/src/app-server/session-history.ts +0 -44
  82. package/src/app-server/shared-client.ts +0 -289
  83. package/src/app-server/side-question.ts +0 -1009
  84. package/src/app-server/test-support.ts +0 -48
  85. package/src/app-server/thread-lifecycle.ts +0 -959
  86. package/src/app-server/timeout.ts +0 -9
  87. package/src/app-server/tool-progress-normalization.ts +0 -77
  88. package/src/app-server/trajectory.ts +0 -368
  89. package/src/app-server/transcript-mirror.ts +0 -208
  90. package/src/app-server/transport-stdio.ts +0 -107
  91. package/src/app-server/transport-websocket.ts +0 -90
  92. package/src/app-server/transport.ts +0 -117
  93. package/src/app-server/user-input-bridge.ts +0 -316
  94. package/src/app-server/version.ts +0 -4
  95. package/src/app-server/vision-tools.ts +0 -12
  96. package/src/command-account.ts +0 -544
  97. package/src/command-formatters.ts +0 -426
  98. package/src/command-handlers.ts +0 -2021
  99. package/src/command-plugins-management.ts +0 -137
  100. package/src/command-rpc.ts +0 -142
  101. package/src/commands.ts +0 -65
  102. package/src/conversation-binding-data.ts +0 -124
  103. package/src/conversation-binding.ts +0 -561
  104. package/src/conversation-control.ts +0 -303
  105. package/src/conversation-turn-collector.ts +0 -186
  106. package/src/conversation-turn-input.ts +0 -106
  107. package/src/migration/apply.ts +0 -501
  108. package/src/migration/helpers.ts +0 -55
  109. package/src/migration/plan.ts +0 -461
  110. package/src/migration/provider.ts +0 -41
  111. package/src/migration/source.ts +0 -643
  112. package/src/migration/targets.ts +0 -25
  113. package/src/node-cli-sessions.ts +0 -711
  114. package/test-api.ts +0 -95
  115. package/tsconfig.json +0 -16
package/provider.ts DELETED
@@ -1,243 +0,0 @@
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
- }
@@ -1,324 +0,0 @@
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
- }