claude-codex-proxy 1.0.5-beta.31 → 1.0.5-beta.32

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.5-beta.31",
3
+ "version": "1.0.5-beta.32",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Daily Anchor Ping
3
+ * Every day at a fixed local hour (default 09:00) this module sends a minimal
4
+ * "你好" message to every configured account so the upstream Codex five-hour
5
+ * usage window is re-anchored to that moment. Because the upstream window
6
+ * advances from the first usage of the window, an anchor ping at 09:00 local
7
+ * time makes the upstream reset time settle at 14:00 local time (09:00 + 5h).
8
+ *
9
+ * The scheduler uses a self-rescheduling setTimeout that targets the exact
10
+ * next anchor instant, so the ping lands at 09:00:00.000 even across long
11
+ * uptimes; on the first run after a restart it only fires if 09:00 has not
12
+ * passed yet today, so it never disturbs an already-active window.
13
+ */
14
+
15
+ import { loadAccounts } from './account-manager.js';
16
+ import { getCredentialsForAccount } from './middleware/credentials.js';
17
+ import { sendMessage } from './direct-api.js';
18
+ import { resolveModelRouting } from './model-mapper.js';
19
+ import { logger } from './utils/logger.js';
20
+
21
+ /** Local hour at which the anchor ping runs every day. */
22
+ export const ANCHOR_HOUR = 9;
23
+
24
+ /** Payload text sent upstream to advance the five-hour window start. */
25
+ export const PING_TEXT = '你好';
26
+
27
+ /** Maximum completion tokens for the anchor ping; only a single reply is needed. */
28
+ const PING_MAX_TOKENS = 16;
29
+
30
+ /**
31
+ * Hard cap for one anchor ping round. `sendMessage` has no built-in request
32
+ * timeout, so a hung upstream response could otherwise stall `pingAllAccounts`
33
+ * forever and break the self-rescheduling chain.
34
+ */
35
+ const PING_TIMEOUT_MS = 5 * 60 * 1000;
36
+
37
+ /** Sample Claude model used to resolve the active upstream Codex model. */
38
+ const SAMPLE_MODEL = 'claude-sonnet-4-5';
39
+
40
+ let anchorTimer = null;
41
+
42
+ /**
43
+ * Computes the next Date at the given local hour (minutes/seconds zeroed)
44
+ * that is strictly after `now`.
45
+ *
46
+ * @param {Date} now - current time
47
+ * @param {number} [anchorHour] - local hour of the anchor
48
+ * @returns {Date} the next anchor instant
49
+ */
50
+ export function getNextAnchorTime(now, anchorHour = ANCHOR_HOUR) {
51
+ const next = new Date(now);
52
+ next.setHours(anchorHour, 0, 0, 0);
53
+ if (next.getTime() <= now.getTime()) {
54
+ next.setDate(next.getDate() + 1);
55
+ }
56
+ return next;
57
+ }
58
+
59
+ /**
60
+ * Builds the minimal Anthropic-style request used for the anchor ping.
61
+ */
62
+ function buildAnchorRequest() {
63
+ const { upstreamModel } = resolveModelRouting(SAMPLE_MODEL);
64
+ return {
65
+ model: upstreamModel,
66
+ max_tokens: PING_MAX_TOKENS,
67
+ messages: [{ role: 'user', content: PING_TEXT }]
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Sends the anchor message to every configured account. Each account is
73
+ * handled independently so a single failure never aborts the rest.
74
+ */
75
+ async function pingAllAccounts() {
76
+ const data = loadAccounts();
77
+ const accounts = data.accounts || [];
78
+ if (accounts.length === 0) {
79
+ logger.info('[AnchorPing] No accounts configured; skipping daily ping');
80
+ return;
81
+ }
82
+
83
+ const request = buildAnchorRequest();
84
+ logger.info(`[AnchorPing] Sending "${PING_TEXT}" to ${accounts.length} account(s) to anchor the five-hour window`);
85
+
86
+ for (const account of accounts) {
87
+ try {
88
+ const creds = await getCredentialsForAccount(account.email);
89
+ if (!creds) {
90
+ logger.warn(`[AnchorPing] Skip ${account.email}: no valid credentials`);
91
+ continue;
92
+ }
93
+ await sendMessage(request, creds.accessToken, creds.accountId, {}, null, creds.email);
94
+ logger.info(`[AnchorPing] Sent "${PING_TEXT}" via ${account.email}`);
95
+ } catch (error) {
96
+ logger.warn(`[AnchorPing] Failed for ${account.email}: ${error.message}`);
97
+ }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Starts the daily anchor ping scheduler. Safe to call multiple times.
103
+ */
104
+ export function startDailyAnchorPing() {
105
+ if (anchorTimer) return;
106
+
107
+ const scheduleNext = () => {
108
+ const next = getNextAnchorTime(new Date());
109
+ const delay = next.getTime() - Date.now();
110
+ logger.info(`[AnchorPing] Next ping scheduled at ${next.toLocaleString()}`);
111
+ anchorTimer = setTimeout(async () => {
112
+ // Race the whole ping round against a hard cap: even if one `sendMessage`
113
+ // hangs upstream, `scheduleNext()` in the `finally` block still runs and
114
+ // tomorrow's ping is never lost. A stray hung request may linger in the
115
+ // background, but it can no longer break the daily chain.
116
+ const guard = new Promise(resolve => setTimeout(resolve, PING_TIMEOUT_MS));
117
+ try {
118
+ await Promise.race([pingAllAccounts(), guard]);
119
+ } catch (error) {
120
+ // Guard against any unforeseen error so the loop always reschedules.
121
+ logger.warn(`[AnchorPing] Unexpected ping error: ${error.message}`);
122
+ } finally {
123
+ scheduleNext();
124
+ }
125
+ }, delay);
126
+ };
127
+
128
+ scheduleNext();
129
+ logger.info(`[AnchorPing] Daily anchor ping enabled at local hour ${ANCHOR_HOUR}:00`);
130
+ }
131
+
132
+ /**
133
+ * Stops the daily anchor ping scheduler and clears any pending timer.
134
+ */
135
+ export function stopDailyAnchorPing() {
136
+ if (anchorTimer) {
137
+ clearTimeout(anchorTimer);
138
+ anchorTimer = null;
139
+ }
140
+ logger.info('[AnchorPing] Daily anchor ping stopped');
141
+ }
142
+
143
+ export default {
144
+ startDailyAnchorPing,
145
+ stopDailyAnchorPing,
146
+ getNextAnchorTime,
147
+ ANCHOR_HOUR,
148
+ PING_TEXT
149
+ };
package/src/server.js CHANGED
@@ -9,6 +9,7 @@ import cors from 'cors';
9
9
  import { ensureAccountsPersist, startAutoRefresh } from './account-manager.js';
10
10
  import { getServerHost } from './deployment.js';
11
11
  import { registerApiRoutes } from './routes/api-routes.js';
12
+ import { startDailyAnchorPing } from './daily-anchor-ping.js';
12
13
 
13
14
  export function createServer({ port, testMode = false, startBackgroundJobs = true, persistAccounts = true }) {
14
15
  if (!testMode && persistAccounts) {
@@ -16,6 +17,9 @@ export function createServer({ port, testMode = false, startBackgroundJobs = tru
16
17
  }
17
18
  if (!testMode && startBackgroundJobs) {
18
19
  startAutoRefresh();
20
+ // Every day at 09:00 local time, re-anchor each account's upstream
21
+ // five-hour usage window so its reset time settles at 14:00.
22
+ startDailyAnchorPing();
19
23
  }
20
24
 
21
25
  const app = express();