replicas-engine 0.1.740 → 0.1.742

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.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getCodexAspHost,
4
+ restartCodexAspHost,
5
+ restartCodexAspHostIfRunning
6
+ } from "./chunk-K5IXJ5WS.js";
7
+ import "./chunk-OGIXPGJ6.js";
8
+ import "./chunk-6X53Z7IV.js";
9
+ import "./chunk-2RB7SIP3.js";
10
+ import "./chunk-RYGOTMEM.js";
11
+ export {
12
+ getCodexAspHost,
13
+ restartCodexAspHost,
14
+ restartCodexAspHostIfRunning
15
+ };
@@ -2,40 +2,7 @@
2
2
  import {
3
3
  HOOK_EXEC_MAX_BUFFER_BYTES,
4
4
  isVersionBelow
5
- } from "./chunk-YPAI4W4G.js";
6
-
7
- // src/utils/presigned-upload.ts
8
- import { createReadStream } from "fs";
9
- import { request as httpRequest } from "http";
10
- import { request as httpsRequest } from "https";
11
- async function putPresignedFile(urlValue, filePath, size, contentType) {
12
- await new Promise((resolve, reject) => {
13
- const url = new URL(urlValue);
14
- const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, {
15
- method: "PUT",
16
- headers: {
17
- "content-length": String(size),
18
- "content-type": contentType
19
- }
20
- }, (response) => {
21
- response.setEncoding("utf8");
22
- let body = "";
23
- response.on("data", (chunk) => {
24
- body += chunk;
25
- });
26
- response.on("end", () => {
27
- const status = response.statusCode ?? 0;
28
- if (status >= 200 && status < 300) resolve();
29
- else reject(new Error(`upload failed: ${status} ${body}`));
30
- });
31
- response.on("error", reject);
32
- });
33
- request.on("error", reject);
34
- const file = size > 0 ? createReadStream(filePath, { start: 0, end: size - 1 }) : createReadStream(filePath);
35
- file.on("error", (error) => request.destroy(error));
36
- file.pipe(request);
37
- });
38
- }
5
+ } from "./chunk-RYGOTMEM.js";
39
6
 
40
7
  // src/utils/codex-agent-env.ts
41
8
  function buildCodexAgentEnv(source = process.env) {
@@ -269,10 +236,10 @@ var DEFAULT_CODEX_ARGS = [
269
236
  "-c",
270
237
  "memories.generate_memories=false"
271
238
  ];
272
- var MIN_CODEX_CLI_VERSION = "0.144.6";
239
+ var MIN_CODEX_CLI_VERSION = "0.153.3";
273
240
  var CODEX_UPGRADE_TIMEOUT_MS = 12e4;
274
241
  var codexCliVersionEnsured = null;
275
- var ENGINE_PACKAGE_VERSION = "0.1.740";
242
+ var ENGINE_PACKAGE_VERSION = "0.1.742";
276
243
  var INITIALIZE_METHOD = "initialize";
277
244
  var INITIALIZED_NOTIFICATION = "initialized";
278
245
  var ACCOUNT_LOGIN_START_METHOD = "account/login/start";
@@ -290,21 +257,37 @@ var AppServerProcess = class {
290
257
  invalidating = false;
291
258
  constructor(options) {
292
259
  this.binary = options.binary ?? DEFAULT_CODEX_BINARY;
293
- const baseArgs = options.args ?? (options.env.REPLICAS_CODEX_AUTH_METHOD === "foundry" ? [
294
- ...DEFAULT_CODEX_ARGS,
295
- "-c",
296
- `model=${JSON.stringify(options.env.CODEX_FOUNDRY_MODEL)}`,
297
- "-c",
298
- 'model_provider="azure"',
299
- "-c",
300
- 'model_providers.azure.name="Azure OpenAI"',
301
- "-c",
302
- `model_providers.azure.base_url=${JSON.stringify(options.env.CODEX_FOUNDRY_BASE_URL)}`,
303
- "-c",
304
- 'model_providers.azure.env_key="AZURE_OPENAI_API_KEY"',
305
- "-c",
306
- 'model_providers.azure.wire_api="responses"'
307
- ] : DEFAULT_CODEX_ARGS);
260
+ let baseArgs = options.args ?? DEFAULT_CODEX_ARGS;
261
+ if (!options.args && options.env.REPLICAS_CODEX_AUTH_METHOD === "foundry") {
262
+ baseArgs = [
263
+ ...DEFAULT_CODEX_ARGS,
264
+ "-c",
265
+ `model=${JSON.stringify(options.env.CODEX_FOUNDRY_MODEL)}`,
266
+ "-c",
267
+ 'model_provider="azure"',
268
+ "-c",
269
+ 'model_providers.azure.name="Azure OpenAI"',
270
+ "-c",
271
+ `model_providers.azure.base_url=${JSON.stringify(options.env.CODEX_FOUNDRY_BASE_URL)}`,
272
+ "-c",
273
+ 'model_providers.azure.env_key="AZURE_OPENAI_API_KEY"',
274
+ "-c",
275
+ 'model_providers.azure.wire_api="responses"'
276
+ ];
277
+ } else if (!options.args && options.env.REPLICAS_CODEX_AUTH_METHOD === "api_key" && options.env.CODEX_OPENAI_BASE_URL) {
278
+ baseArgs = [
279
+ ...DEFAULT_CODEX_ARGS,
280
+ "-c",
281
+ 'model_provider="replicas_openai_compatible"',
282
+ "-c",
283
+ 'model_providers.replicas_openai_compatible.name="OpenAI Compatible"',
284
+ "-c",
285
+ `model_providers.replicas_openai_compatible.base_url=${JSON.stringify(options.env.CODEX_OPENAI_BASE_URL)}`,
286
+ "-c",
287
+ 'model_providers.replicas_openai_compatible.wire_api="responses"',
288
+ ...options.env.CODEX_OPENAI_AUTHORIZATION_HEADER ? ["-c", 'model_providers.replicas_openai_compatible.env_http_headers={ Authorization = "CODEX_OPENAI_AUTHORIZATION_HEADER" }'] : ["-c", 'model_providers.replicas_openai_compatible.env_key="OPENAI_API_KEY"']
289
+ ];
290
+ }
308
291
  this.args = [...baseArgs, ...(options.configOverrides ?? []).flatMap((override) => ["-c", override])];
309
292
  this.env = options.env;
310
293
  this.cwd = options.cwd;
@@ -467,7 +450,7 @@ var AppServerProcess = class {
467
450
  await client.request(ACCOUNT_LOGIN_START_METHOD, params2);
468
451
  return;
469
452
  }
470
- if (this.env.REPLICAS_CODEX_AUTH_METHOD !== "api_key" || !this.env.OPENAI_API_KEY) return;
453
+ if (this.env.REPLICAS_CODEX_AUTH_METHOD !== "api_key" || this.env.CODEX_OPENAI_BASE_URL || !this.env.OPENAI_API_KEY) return;
471
454
  const params = {
472
455
  type: "apiKey",
473
456
  apiKey: this.env.OPENAI_API_KEY
@@ -489,69 +472,11 @@ var AppServerProcess = class {
489
472
  }
490
473
  };
491
474
 
492
- // src/managers/codex-asp/notification-dispatch.ts
493
- var TURN_STARTED_METHOD = "turn/started";
494
- var TURN_COMPLETED_METHOD = "turn/completed";
495
- var TURN_PLAN_UPDATED_METHOD = "turn/plan/updated";
496
- var THREAD_GOAL_UPDATED_METHOD = "thread/goal/updated";
497
- var THREAD_GOAL_CLEARED_METHOD = "thread/goal/cleared";
498
- var ITEM_STARTED_METHOD = "item/started";
499
- var ITEM_COMPLETED_METHOD = "item/completed";
500
- var AGENT_MESSAGE_DELTA_METHOD = "item/agentMessage/delta";
501
- var REASONING_SUMMARY_TEXT_DELTA_METHOD = "item/reasoning/summaryTextDelta";
502
- var REASONING_TEXT_DELTA_METHOD = "item/reasoning/textDelta";
503
- var REASONING_SUMMARY_PART_ADDED_METHOD = "item/reasoning/summaryPartAdded";
504
- var COMMAND_EXECUTION_OUTPUT_DELTA_METHOD = "item/commandExecution/outputDelta";
505
- var FILE_CHANGE_OUTPUT_DELTA_METHOD = "item/fileChange/outputDelta";
506
- var ACCOUNT_RATE_LIMITS_UPDATED_METHOD = "account/rateLimits/updated";
507
- var THREAD_TOKEN_USAGE_UPDATED_METHOD = "thread/tokenUsage/updated";
508
- var THREAD_COMPACTED_METHOD = "thread/compacted";
509
- var MODEL_REROUTED_METHOD = "model/rerouted";
510
- function dispatchAspNotification(notification, handlers) {
511
- const handler = handlers[notification.method];
512
- if (!handler) return;
513
- handler(notification);
514
- }
515
- function recoverCompletedTurn(turn, completedItems, agentMessageDeltas) {
516
- const items = turn.items.length > 0 ? [...turn.items] : [];
517
- const itemIds = new Set(items.map((item) => item.id));
518
- for (const item of completedItems) {
519
- if (itemIds.has(item.id)) continue;
520
- items.push(item);
521
- itemIds.add(item.id);
522
- }
523
- for (const [itemId, text] of agentMessageDeltas) {
524
- if (itemIds.has(itemId)) continue;
525
- items.push({ type: "agentMessage", id: itemId, text, phase: null, memoryCitation: null });
526
- }
527
- return items.length > 0 ? { ...turn, items, itemsView: "full" } : turn;
528
- }
529
-
530
475
  export {
531
- putPresignedFile,
532
476
  buildCodexAgentEnv,
533
477
  AspClient,
534
478
  execAsync,
535
479
  execFileAsync,
536
480
  SUBPROCESS_MAX_BUFFER,
537
- AppServerProcess,
538
- TURN_STARTED_METHOD,
539
- TURN_COMPLETED_METHOD,
540
- TURN_PLAN_UPDATED_METHOD,
541
- THREAD_GOAL_UPDATED_METHOD,
542
- THREAD_GOAL_CLEARED_METHOD,
543
- ITEM_STARTED_METHOD,
544
- ITEM_COMPLETED_METHOD,
545
- AGENT_MESSAGE_DELTA_METHOD,
546
- REASONING_SUMMARY_TEXT_DELTA_METHOD,
547
- REASONING_TEXT_DELTA_METHOD,
548
- REASONING_SUMMARY_PART_ADDED_METHOD,
549
- COMMAND_EXECUTION_OUTPUT_DELTA_METHOD,
550
- FILE_CHANGE_OUTPUT_DELTA_METHOD,
551
- ACCOUNT_RATE_LIMITS_UPDATED_METHOD,
552
- THREAD_TOKEN_USAGE_UPDATED_METHOD,
553
- THREAD_COMPACTED_METHOD,
554
- MODEL_REROUTED_METHOD,
555
- dispatchAspNotification,
556
- recoverCompletedTurn
481
+ AppServerProcess
557
482
  };
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ monolithRequest
4
+ } from "./chunk-OGIXPGJ6.js";
5
+ import {
6
+ extractCommandProtectionCommandText,
7
+ findGitCommitSignals,
8
+ findPrMergeSignals
9
+ } from "./chunk-RYGOTMEM.js";
10
+
11
+ // src/services/command-protection-service.ts
12
+ var DEFAULT_COMMAND_PROTECTION_BLOCK_MESSAGE = "Blocked by Replicas command protection.";
13
+ function asCommandProtectionResponse(value) {
14
+ if (typeof value !== "object" || value === null) return null;
15
+ const candidate = value;
16
+ return typeof candidate.allowed === "boolean" && typeof candidate.enabled === "boolean" ? candidate : null;
17
+ }
18
+ function failClosed(reason, matchedSignals) {
19
+ return {
20
+ allowed: false,
21
+ enabled: true,
22
+ reason,
23
+ matchedSignals
24
+ };
25
+ }
26
+ async function evaluateCommandProtection(request, signal) {
27
+ const matchedSignals = [...findGitCommitSignals(request), ...findPrMergeSignals(request)];
28
+ if (matchedSignals.length === 0) {
29
+ return { allowed: true, enabled: true };
30
+ }
31
+ let response;
32
+ try {
33
+ response = await monolithRequest("/v1/engine/command-protection/evaluate", {
34
+ body: request,
35
+ signal
36
+ });
37
+ } catch (error) {
38
+ const detail = error instanceof Error ? error.message : String(error);
39
+ return failClosed(`Command protection failed closed: ${detail}`, matchedSignals);
40
+ }
41
+ if (!response.ok) {
42
+ const detail = await response.text().catch(() => "");
43
+ return failClosed(`Command protection failed closed: ${response.status} ${detail}`, matchedSignals);
44
+ }
45
+ let payload;
46
+ try {
47
+ payload = await response.json();
48
+ } catch (error) {
49
+ const detail = error instanceof Error ? error.message : String(error);
50
+ return failClosed(`Command protection failed closed: ${detail}`, matchedSignals);
51
+ }
52
+ return asCommandProtectionResponse(payload) ?? failClosed("Command protection failed closed: invalid response from policy service", matchedSignals);
53
+ }
54
+ function extractToolCommand(input) {
55
+ return extractCommandProtectionCommandText({ toolInput: input }, { stringifyFallback: false });
56
+ }
57
+ function reportCommandProtectionBlock(options) {
58
+ const message = options.result.reason || DEFAULT_COMMAND_PROTECTION_BLOCK_MESSAGE;
59
+ console.warn(`[${options.managerName}] blocked ${options.action} by command protection: ${message}`);
60
+ options.recordHistoryEvent(options.eventType, {
61
+ type: "error",
62
+ message,
63
+ ...options.context,
64
+ command: options.command
65
+ }, options.historyFile);
66
+ return message;
67
+ }
68
+
69
+ export {
70
+ evaluateCommandProtection,
71
+ extractToolCommand,
72
+ reportCommandProtectionBlock
73
+ };
@@ -0,0 +1,419 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ENGINE_ENV,
4
+ monolithRequest,
5
+ setAgentCredentialSnapshot
6
+ } from "./chunk-OGIXPGJ6.js";
7
+ import {
8
+ AppServerProcess,
9
+ buildCodexAgentEnv
10
+ } from "./chunk-6X53Z7IV.js";
11
+ import {
12
+ CODEX_AUTH_ENV_KEYS,
13
+ CODEX_AUTH_ENV_KEYS_BY_METHOD,
14
+ codexAuthEnvFromResponse,
15
+ createErrorResult,
16
+ createSuccessResult
17
+ } from "./chunk-RYGOTMEM.js";
18
+
19
+ // src/managers/codex-token-manager.ts
20
+ import { promises as fs } from "fs";
21
+ import path from "path";
22
+
23
+ // src/managers/auth-env-transition.ts
24
+ function applyAuthEnvTransition(params) {
25
+ const newOwned = new Set(params.authKeysByMethod[params.newMethod]);
26
+ const prevOwned = new Set(params.authKeysByMethod[params.prevMethod]);
27
+ for (const key of params.authKeys) {
28
+ const value = params.newEnvVars[key];
29
+ if (value !== void 0) {
30
+ for (const env of params.envs) {
31
+ env[key] = value;
32
+ }
33
+ } else if (prevOwned.has(key) && !newOwned.has(key)) {
34
+ for (const env of params.envs) {
35
+ delete env[key];
36
+ }
37
+ }
38
+ }
39
+ }
40
+
41
+ // src/services/credential-fallbacks.ts
42
+ var fallbacksByAgent = /* @__PURE__ */ new Map();
43
+ var exhaustedByAgent = /* @__PURE__ */ new Map();
44
+ function recordCredentialFallback(notice) {
45
+ fallbacksByAgent.set(notice.provider, notice);
46
+ }
47
+ function listCredentialFallbacks() {
48
+ return [...fallbacksByAgent.values()].filter((notice) => {
49
+ const live = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS[notice.provider];
50
+ if (!live) return false;
51
+ return notice.status === "switched" ? live.method === notice.candidateMethod && live.scope === notice.candidateScope : live.method === notice.exhaustedMethod && live.scope === notice.exhaustedScope;
52
+ });
53
+ }
54
+ function listExhaustedCredentials(provider) {
55
+ return [...exhaustedByAgent.get(provider)?.values() ?? []];
56
+ }
57
+ function recordExhaustedCredential(provider, credential) {
58
+ const spent = exhaustedByAgent.get(provider) ?? /* @__PURE__ */ new Map();
59
+ spent.set(`${credential.method}|${credential.scope}`, credential);
60
+ exhaustedByAgent.set(provider, spent);
61
+ }
62
+
63
+ // src/managers/base-refresh-manager.ts
64
+ var BaseRefreshManager = class {
65
+ constructor(managerName, intervalMs = 15 * 60 * 1e3) {
66
+ this.managerName = managerName;
67
+ this.intervalMs = intervalMs;
68
+ this.health = {
69
+ isRunning: false,
70
+ intervalMs: this.intervalMs,
71
+ lastAttemptAt: null,
72
+ lastSuccessAt: null,
73
+ lastErrorAt: null,
74
+ lastErrorMessage: null
75
+ };
76
+ }
77
+ managerName;
78
+ intervalMs;
79
+ intervalHandle = null;
80
+ health;
81
+ async start() {
82
+ if (this.intervalHandle) {
83
+ return;
84
+ }
85
+ const skipReason = this.getSkipReason();
86
+ if (skipReason) {
87
+ console.log(`[${this.managerName}] Skipping: ${skipReason}`);
88
+ return;
89
+ }
90
+ console.log(`[${this.managerName}] Starting token refresh service`);
91
+ this.health.isRunning = true;
92
+ const config = this.getRuntimeConfig();
93
+ if (config) {
94
+ this.health.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
95
+ for (let attempt = 1; attempt <= 3; attempt++) {
96
+ try {
97
+ await this.doRefresh(config);
98
+ this.health.lastSuccessAt = (/* @__PURE__ */ new Date()).toISOString();
99
+ this.health.lastErrorAt = null;
100
+ this.health.lastErrorMessage = null;
101
+ break;
102
+ } catch (error) {
103
+ const message = error instanceof Error ? error.message : "Unknown error";
104
+ this.health.lastErrorAt = (/* @__PURE__ */ new Date()).toISOString();
105
+ this.health.lastErrorMessage = message;
106
+ if (attempt < 3) {
107
+ console.warn(`[${this.managerName}] Initial refresh attempt ${attempt} failed, retrying in 2s...`);
108
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
109
+ } else {
110
+ console.error(`[${this.managerName}] Initial refresh failed after 3 attempts:`, error);
111
+ }
112
+ }
113
+ }
114
+ }
115
+ this.scheduleNextRefresh();
116
+ }
117
+ async swapCredentials(params) {
118
+ if (!this.getRuntimeConfig()) {
119
+ return createErrorResult({ message: `${this.managerName} has no runtime config`, code: "not_configured" });
120
+ }
121
+ try {
122
+ console.log(`[${this.managerName}] Fetching fresh credentials from monolith (${params.failureKind})...`);
123
+ const excludeCredentials = listExhaustedCredentials(params.provider);
124
+ await params.refresh({
125
+ ...excludeCredentials.length > 0 ? { excludeCredentials } : {},
126
+ ...params.allowedMethods ? { allowedMethods: [...params.allowedMethods] } : {}
127
+ });
128
+ if (params.isOauthNow()) {
129
+ this.start().catch((error) => {
130
+ console.error(`[${this.managerName}] Failed to restart OAuth refresh service after fallback:`, error);
131
+ });
132
+ }
133
+ return createSuccessResult();
134
+ } catch (error) {
135
+ const message = error instanceof Error ? error.message : String(error);
136
+ console.error(`[${this.managerName}] Failed to fetch fresh credentials:`, error);
137
+ return createErrorResult({
138
+ message,
139
+ code: message.includes('"code":"no_credentials"') ? "no_credentials" : "refresh_failed"
140
+ });
141
+ }
142
+ }
143
+ stop() {
144
+ if (!this.intervalHandle) {
145
+ return;
146
+ }
147
+ clearTimeout(this.intervalHandle);
148
+ this.intervalHandle = null;
149
+ this.health.isRunning = false;
150
+ console.log(`[${this.managerName}] Stopped`);
151
+ }
152
+ getHealthStatus() {
153
+ return { ...this.health };
154
+ }
155
+ getSkipReason() {
156
+ return null;
157
+ }
158
+ getNextRefreshDelayMs() {
159
+ return this.intervalMs;
160
+ }
161
+ getRuntimeConfig() {
162
+ if (!ENGINE_ENV.REPLICAS_WORKSPACE_ID) {
163
+ return null;
164
+ }
165
+ return {
166
+ monolithUrl: ENGINE_ENV.REPLICAS_MONOLITH_URL,
167
+ workspaceId: ENGINE_ENV.REPLICAS_WORKSPACE_ID,
168
+ engineSecret: ENGINE_ENV.REPLICAS_ENGINE_SECRET
169
+ };
170
+ }
171
+ scheduleNextRefresh() {
172
+ const delayMs = this.getNextRefreshDelayMs();
173
+ this.health.intervalMs = delayMs;
174
+ this.intervalHandle = setTimeout(async () => {
175
+ await this.refreshOnce();
176
+ if (this.intervalHandle) this.scheduleNextRefresh();
177
+ }, delayMs);
178
+ console.log(`[${this.managerName}] Token refresh scheduled in ${Math.round(delayMs / 1e3)} seconds`);
179
+ }
180
+ async refreshOnce(force = false) {
181
+ if (!force && this.getSkipReason()) {
182
+ return createSuccessResult();
183
+ }
184
+ const config = this.getRuntimeConfig();
185
+ if (!config) return createSuccessResult();
186
+ this.health.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
187
+ try {
188
+ await this.doRefresh(config);
189
+ this.health.lastSuccessAt = (/* @__PURE__ */ new Date()).toISOString();
190
+ this.health.lastErrorAt = null;
191
+ this.health.lastErrorMessage = null;
192
+ return createSuccessResult();
193
+ } catch (error) {
194
+ const message = error instanceof Error ? error.message : "Unknown error";
195
+ this.health.lastErrorAt = (/* @__PURE__ */ new Date()).toISOString();
196
+ this.health.lastErrorMessage = message;
197
+ console.error(`[${this.managerName}] Failed to refresh credentials:`, error);
198
+ return createErrorResult({ message });
199
+ }
200
+ }
201
+ };
202
+
203
+ // src/managers/codex-token-manager.ts
204
+ var CodexAspAuthMethodChangedError = class extends Error {
205
+ name = "CodexAspAuthMethodChangedError";
206
+ };
207
+ var CodexTokenManager = class extends BaseRefreshManager {
208
+ constructor() {
209
+ super("CodexTokenManager");
210
+ }
211
+ getSkipReason() {
212
+ if (!ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD && ENGINE_ENV.OPENAI_API_KEY) {
213
+ return "OPENAI_API_KEY is set";
214
+ }
215
+ return null;
216
+ }
217
+ async doRefresh(_config) {
218
+ await this.refreshWithRequest(void 0, true);
219
+ }
220
+ async refreshWithRequest(request, restartOnChange = false) {
221
+ const previousEnv = CODEX_AUTH_ENV_KEYS.map((key) => process.env[key]);
222
+ console.log("[CodexTokenManager] Refreshing Codex credentials...");
223
+ const response = await monolithRequest("/v1/engine/codex/refresh-credentials", {
224
+ body: request
225
+ });
226
+ if (!response.ok) {
227
+ const errorText = await response.text();
228
+ throw new Error(`Credentials refresh failed: ${response.status} ${errorText}`);
229
+ }
230
+ const data = await response.json();
231
+ await this.applyCredentialsResponse(data);
232
+ if (restartOnChange && CODEX_AUTH_ENV_KEYS.some((key, index) => process.env[key] !== previousEnv[index])) {
233
+ const { restartCodexAspHostIfRunning: restartCodexAspHostIfRunning2 } = await import("./asp-host-X2J4FDK2.js");
234
+ await restartCodexAspHostIfRunning2();
235
+ }
236
+ if (data.scope) {
237
+ setAgentCredentialSnapshot("codex", {
238
+ method: data.type,
239
+ scope: data.scope,
240
+ ...data.revision ? { revision: data.revision } : {}
241
+ });
242
+ }
243
+ console.log(`[CodexTokenManager] Credentials refreshed (method=${data.type})`);
244
+ return data;
245
+ }
246
+ async prepareAspOauthOptions() {
247
+ if (ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD !== "oauth") return {};
248
+ const response = await this.refreshWithRequest();
249
+ if (response.type !== "oauth") return {};
250
+ const login = this.buildAspOauthLogin(response);
251
+ let credential = login.credential;
252
+ return {
253
+ chatgptAuthTokens: login.tokens,
254
+ refreshChatgptAuthTokens: async (params) => {
255
+ const refreshed = await this.refreshAspOauthCredentials(
256
+ credential,
257
+ `Codex ASP requested an external token refresh (${params.reason})`
258
+ );
259
+ if (!refreshed.ok) {
260
+ if (refreshed.error.code === "method_changed") {
261
+ throw new CodexAspAuthMethodChangedError(refreshed.error.message);
262
+ }
263
+ throw new Error(refreshed.error.message);
264
+ }
265
+ credential = refreshed.data.credential;
266
+ return refreshed.data.tokens;
267
+ }
268
+ };
269
+ }
270
+ async refreshAspOauthCredentials(failedCredential, failureReason) {
271
+ try {
272
+ const response = await this.refreshWithRequest({
273
+ failedMethod: "oauth",
274
+ ...failedCredential?.method === "oauth" ? { failedCredential } : {},
275
+ failureKind: "rejected",
276
+ failureReason
277
+ });
278
+ if (response.type !== "oauth") {
279
+ return createErrorResult({
280
+ message: `${failureReason}; credentials changed to ${response.type}, so the app server must restart`,
281
+ code: "method_changed"
282
+ });
283
+ }
284
+ return createSuccessResult(this.buildAspOauthLogin(response));
285
+ } catch (error) {
286
+ const message = error instanceof Error ? error.message : String(error);
287
+ return createErrorResult({
288
+ message,
289
+ code: message.includes('"code":"no_credentials"') ? "no_credentials" : "refresh_failed"
290
+ });
291
+ }
292
+ }
293
+ async fetchFreshCredentials(failureReason, failureKind = "rejected", failedCredential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex, allowedMethods) {
294
+ const failedMethod = failedCredential?.method === "oauth" || failedCredential?.method === "api_key" || failedCredential?.method === "foundry" ? failedCredential.method : ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD;
295
+ return this.swapCredentials({
296
+ provider: "codex",
297
+ failureKind,
298
+ allowedMethods,
299
+ refresh: async (exclusions) => {
300
+ await this.refreshWithRequest(
301
+ failedMethod === "oauth" || failedMethod === "api_key" || failedMethod === "foundry" ? {
302
+ failedMethod,
303
+ ...failedCredential?.method === failedMethod ? { failedCredential } : {},
304
+ failureReason,
305
+ failureKind,
306
+ ...exclusions
307
+ } : exclusions
308
+ );
309
+ },
310
+ isOauthNow: () => ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD === "oauth"
311
+ });
312
+ }
313
+ async applyCredentialsResponse(response) {
314
+ await this.removeOauthCredentialsFile();
315
+ const envVars = codexAuthEnvFromResponse(response);
316
+ applyAuthEnvTransition({
317
+ prevMethod: ENGINE_ENV.REPLICAS_CODEX_AUTH_METHOD ?? "none",
318
+ newMethod: envVars.REPLICAS_CODEX_AUTH_METHOD ?? "none",
319
+ authKeys: CODEX_AUTH_ENV_KEYS,
320
+ authKeysByMethod: CODEX_AUTH_ENV_KEYS_BY_METHOD,
321
+ newEnvVars: envVars,
322
+ envs: [ENGINE_ENV, process.env]
323
+ });
324
+ if (response.type === "api_key") {
325
+ for (const key of CODEX_AUTH_ENV_KEYS_BY_METHOD.api_key) {
326
+ if (envVars[key] !== void 0) continue;
327
+ delete ENGINE_ENV[key];
328
+ delete process.env[key];
329
+ }
330
+ }
331
+ }
332
+ buildAspOauthLogin(response) {
333
+ const credential = ENGINE_ENV.REPLICAS_AGENT_CREDENTIALS.codex;
334
+ return {
335
+ tokens: {
336
+ accessToken: response.accessToken,
337
+ chatgptAccountId: response.accountId,
338
+ chatgptPlanType: null
339
+ },
340
+ ...credential?.method === "oauth" ? { credential } : {}
341
+ };
342
+ }
343
+ async removeOauthCredentialsFile() {
344
+ const authPath = path.join(ENGINE_ENV.HOME_DIR, ".codex", "auth.json");
345
+ try {
346
+ await fs.unlink(authPath);
347
+ } catch (error) {
348
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
349
+ }
350
+ }
351
+ };
352
+ var codexTokenManager = new CodexTokenManager();
353
+
354
+ // src/managers/codex-asp/asp-host.ts
355
+ var hostPromise = null;
356
+ var activeProcess = null;
357
+ var restartPromise = null;
358
+ async function getCodexAspHost() {
359
+ if (restartPromise) {
360
+ await restartPromise;
361
+ }
362
+ hostPromise ??= (async () => {
363
+ try {
364
+ const oauthOptions = await codexTokenManager.prepareAspOauthOptions();
365
+ const process2 = new AppServerProcess({
366
+ cwd: ENGINE_ENV.WORKSPACE_ROOT,
367
+ env: buildCodexAgentEnv(),
368
+ ...oauthOptions
369
+ });
370
+ const { client } = await process2.start();
371
+ activeProcess = process2;
372
+ process2.on("exit", () => {
373
+ if (activeProcess === process2) {
374
+ activeProcess = null;
375
+ }
376
+ hostPromise = null;
377
+ });
378
+ return { client };
379
+ } catch (error) {
380
+ hostPromise = null;
381
+ throw error;
382
+ }
383
+ })();
384
+ return hostPromise;
385
+ }
386
+ async function restartCodexAspHost() {
387
+ if (restartPromise) {
388
+ return restartPromise;
389
+ }
390
+ restartPromise = (async () => {
391
+ const process2 = activeProcess;
392
+ hostPromise = null;
393
+ activeProcess = null;
394
+ if (process2) {
395
+ await process2.stop();
396
+ }
397
+ })();
398
+ try {
399
+ await restartPromise;
400
+ } finally {
401
+ restartPromise = null;
402
+ }
403
+ }
404
+ async function restartCodexAspHostIfRunning() {
405
+ if (activeProcess) await restartCodexAspHost();
406
+ }
407
+
408
+ export {
409
+ recordCredentialFallback,
410
+ listCredentialFallbacks,
411
+ recordExhaustedCredential,
412
+ BaseRefreshManager,
413
+ applyAuthEnvTransition,
414
+ getCodexAspHost,
415
+ restartCodexAspHost,
416
+ restartCodexAspHostIfRunning,
417
+ CodexAspAuthMethodChangedError,
418
+ codexTokenManager
419
+ };