gestalt-mobile 0.75.3 → 0.76.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.
@@ -8141,6 +8141,9 @@ describe('production composition', () => {
8141
8141
  ['HEAD', '/api/bootstrap', '/api/bootstrap', 'protected'],
8142
8142
  ['GET', '/api/codex/allowance', '/api/codex/allowance', 'protected'],
8143
8143
  ['HEAD', '/api/codex/allowance', '/api/codex/allowance', 'protected'],
8144
+ ['GET', '/api/codex/allowance/auto-reset', '/api/codex/allowance/auto-reset', 'protected'],
8145
+ ['HEAD', '/api/codex/allowance/auto-reset', '/api/codex/allowance/auto-reset', 'protected'],
8146
+ ['PUT', '/api/codex/allowance/auto-reset', '/api/codex/allowance/auto-reset', 'protected'],
8144
8147
  ['GET', '/api/session-defaults', '/api/session-defaults', 'protected'],
8145
8148
  ['HEAD', '/api/session-defaults', '/api/session-defaults', 'protected'],
8146
8149
  ['PUT', '/api/session-defaults', '/api/session-defaults', 'protected'],
@@ -8532,6 +8535,98 @@ describe('production composition', () => {
8532
8535
  });
8533
8536
  });
8534
8537
  describeCompositionConcern('sessions', () => {
8538
+ it('redeems one weekly reset credit on a matched terminal Codex failure and records a receipt', async () => {
8539
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-weekly-reset-root-'));
8540
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-weekly-reset-state-'));
8541
+ ownTemporaryPaths(root, dataDir);
8542
+ await mkdir(join(root, 'workspace'));
8543
+ const handles = [];
8544
+ const app = await composeAuthorizedApp({
8545
+ root,
8546
+ dataDir,
8547
+ relyingParty,
8548
+ installedCodexVersion: 'codex-cli 0.170.0',
8549
+ startAppServers: true,
8550
+ launchAppServer: liveAppServer(handles),
8551
+ profiles: {
8552
+ list: async () => [],
8553
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
8554
+ },
8555
+ });
8556
+ onTestFinished(() => app.close());
8557
+ const policy = '/api/codex/allowance/auto-reset';
8558
+ expect((await app.inject({ method: 'PUT', url: policy, payload: { enabled: true } })).statusCode).toBe(200);
8559
+ const id = await createComposedSession(app);
8560
+ await vi.waitFor(async () => {
8561
+ expect((await app.inject(`/api/sessions/${id}`)).json().state).toBe('ready');
8562
+ });
8563
+ expect((await app.inject({
8564
+ method: 'POST',
8565
+ url: `/api/sessions/${id}/turns`,
8566
+ payload: { text: 'fixture' },
8567
+ })).statusCode).toBe(202);
8568
+ const session = (await app.inject(`/api/sessions/${id}`)).json();
8569
+ const handle = handles.find((candidate) => candidate.calls.includes('turn/start'));
8570
+ handle.respond = (method) => {
8571
+ if (method === 'account/rateLimits/read')
8572
+ return {
8573
+ rateLimits: {
8574
+ secondary: {
8575
+ windowDurationMins: 10_080,
8576
+ usedPercent: 100,
8577
+ resetsAt: Math.floor(Date.now() / 1000) + 1_200,
8578
+ },
8579
+ },
8580
+ rateLimitResetCredits: {
8581
+ availableCount: 1,
8582
+ credits: [
8583
+ { id: 'fixture-credit', status: 'available', resetType: 'codexRateLimits' },
8584
+ ],
8585
+ },
8586
+ };
8587
+ if (method === 'account/rateLimitResetCredit/consume')
8588
+ return { outcome: 'reset' };
8589
+ };
8590
+ const error = { codexErrorInfo: 'usageLimitExceeded' };
8591
+ handle.notify({
8592
+ method: 'error',
8593
+ params: {
8594
+ threadId: 'unknown-thread',
8595
+ turnId: 'unknown-turn',
8596
+ error,
8597
+ willRetry: false,
8598
+ },
8599
+ });
8600
+ expect(handle.calls).not.toContain('account/rateLimits/read');
8601
+ handle.notify({
8602
+ method: 'error',
8603
+ params: {
8604
+ threadId: session.threadId,
8605
+ turnId: session.activeTurnId,
8606
+ error,
8607
+ willRetry: false,
8608
+ },
8609
+ });
8610
+ handle.notify({
8611
+ method: 'turn/completed',
8612
+ params: {
8613
+ threadId: session.threadId,
8614
+ turn: { id: session.activeTurnId, status: 'failed', error },
8615
+ },
8616
+ });
8617
+ await vi.waitFor(async () => {
8618
+ expect((await app.inject(policy)).json().resets).toEqual([
8619
+ { id: expect.any(String), occurredAt: expect.any(Number) },
8620
+ ]);
8621
+ });
8622
+ expect(handle.requests.filter((call) => call.method === 'account/rateLimitResetCredit/consume')).toEqual([
8623
+ {
8624
+ method: 'account/rateLimitResetCredit/consume',
8625
+ params: { creditId: 'fixture-credit', idempotencyKey: expect.any(String) },
8626
+ },
8627
+ ]);
8628
+ expect(handle.calls.filter((method) => method === 'turn/start')).toHaveLength(1);
8629
+ });
8535
8630
  it('does not return retained display history as current when an in-flight plan refresh is superseded by mandatory rejection', async () => {
8536
8631
  const { app, sessionId, workspacePath } = await createProductionAutopilotFixture();
8537
8632
  const url = `/api/sessions/${sessionId}/plan`;
@@ -34,6 +34,8 @@ import { protocolCompatibility } from './platform/codex/protocol-compatibility.j
34
34
  import { launchCodexAppServer } from './platform/codex/codex-process-launcher.js';
35
35
  import { CodexModelCatalog } from './platform/codex/codex-model-catalog.js';
36
36
  import { CodexAllowanceReader } from './platform/codex/codex-allowance.js';
37
+ import { CodexAutoReset } from './features/catalog/application/codex-auto-reset.js';
38
+ import { SqliteCodexResetStore } from './platform/persistence/sqlite-codex-reset-store.js';
37
39
  import { ProviderModelCatalog } from './platform/catalog/provider-model-catalog.js';
38
40
  import { createRecentThreadLister } from './platform/codex/recent-thread-lister.js';
39
41
  import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
@@ -566,6 +568,8 @@ export async function composeRelayApp(options) {
566
568
  const debugHome = options.homeDirectory ?? homedir();
567
569
  const debugWorkspace = new SelfDebugWorkspace(join(debugHome, '.gestalt', 'self-debug'), join(process.env.CODEX_HOME ?? join(debugHome, '.codex'), 'agents', 'org-plan-executor.toml'), databasePath);
568
570
  const homeDirectory = options.homeDirectory ?? homedir();
571
+ const codexResetStore = new SqliteCodexResetStore(homeDirectory);
572
+ const codexAutoReset = new CodexAutoReset(codexResetStore, randomUUID);
569
573
  const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id), ({ id }) => {
570
574
  forgetOperations.assertAvailable(id);
571
575
  const current = sessions.find(id);
@@ -1086,15 +1090,27 @@ export async function composeRelayApp(options) {
1086
1090
  (settledFailure?.providerFailureTurnId === completionTurnId
1087
1091
  ? settledFailure?.providerFailure
1088
1092
  : undefined);
1093
+ const failureTurnId = completionTurnId ??
1094
+ (typeof notification.params?.turnId === 'string'
1095
+ ? notification.params.turnId
1096
+ : resolvedOrigin.physicalTurnId);
1089
1097
  if (resolvedOrigin.kind !== 'unknown' && providerFailure)
1090
1098
  autopilot.providerFailed(sessionId, providerFailure, {
1091
1099
  actor: resolvedOrigin.kind === 'root' ? 'root' : 'child',
1092
- turnId: completionTurnId ??
1093
- (typeof notification.params?.turnId === 'string'
1094
- ? notification.params.turnId
1095
- : resolvedOrigin.physicalTurnId),
1100
+ turnId: failureTurnId,
1096
1101
  settled: notification.method === 'turn/completed',
1097
1102
  });
1103
+ if (providerFailure?.code === 'usageLimitExceeded' &&
1104
+ currentSession?.provider === 'codex' &&
1105
+ currentSession.activeTurnId &&
1106
+ currentSession.desiredState === 'active' &&
1107
+ resolvedOrigin.runtimeId &&
1108
+ (resolvedOrigin.kind === 'child' ||
1109
+ (resolvedOrigin.kind === 'root' && failureTurnId === currentSession.activeTurnId))) {
1110
+ const account = runtime?.weeklyResetAccount(sessionId, resolvedOrigin.runtimeId, () => !closing && sessions.find(sessionId)?.desiredState === 'active');
1111
+ if (account)
1112
+ void codexAutoReset.blocked(account);
1113
+ }
1098
1114
  const rootCommandId = resolvedOrigin.kind === 'root' ? completedCommandId(notification) : null;
1099
1115
  if (rootCommandId)
1100
1116
  autopilot.rootProcessCompleted(sessionId, rootCommandId);
@@ -1776,6 +1792,7 @@ export async function composeRelayApp(options) {
1776
1792
  authorization.initializeOwner(ownerHandle);
1777
1793
  }
1778
1794
  catch (error) {
1795
+ authorization?.close();
1779
1796
  database.close();
1780
1797
  throw error;
1781
1798
  }
@@ -2282,6 +2299,7 @@ export async function composeRelayApp(options) {
2282
2299
  pwaIcon: options.pwaIcon,
2283
2300
  recentThreads: recentThreadsForRelay,
2284
2301
  sessionDefaults,
2302
+ codexAutoReset: codexResetStore,
2285
2303
  codexAllowance: options.installedCodexVersion === null
2286
2304
  ? {
2287
2305
  read: async () => ({
@@ -0,0 +1,58 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ export const resetCreditCooldownMs = 10 * 60_000;
7
+ const providerTimeoutMs = 10_000;
8
+ async function bounded(operation) {
9
+ let timer;
10
+ try {
11
+ return await Promise.race([
12
+ operation,
13
+ new Promise((_, reject) => {
14
+ timer = setTimeout(() => reject(new Error('CODEX_RESET_CREDIT_TIMED_OUT')), providerTimeoutMs);
15
+ }),
16
+ ]);
17
+ }
18
+ finally {
19
+ clearTimeout(timer);
20
+ }
21
+ }
22
+ export class CodexAutoReset {
23
+ store;
24
+ createId;
25
+ now;
26
+ checking = false;
27
+ constructor(store, createId, now = Date.now) {
28
+ this.store = store;
29
+ this.createId = createId;
30
+ this.now = now;
31
+ }
32
+ async blocked(account) {
33
+ if (this.checking)
34
+ return;
35
+ this.checking = true;
36
+ try {
37
+ if (!this.store.enabled())
38
+ return;
39
+ const candidate = await bounded(account.readCandidate(this.now()));
40
+ if (!candidate)
41
+ return;
42
+ const now = this.now();
43
+ const id = this.createId();
44
+ if (candidate.weeklyResetsAt * 1000 <= now + 60_000 ||
45
+ !this.store.claim(id, now, candidate.weeklyResetsAt))
46
+ return;
47
+ if (await bounded(account.redeem(candidate.creditId, id)))
48
+ this.store.recordReset(id, this.now());
49
+ }
50
+ catch {
51
+ // An unconfirmed redemption keeps its durable claim. Never spend another
52
+ // credit to retry this window or retain opaque provider diagnostics.
53
+ }
54
+ finally {
55
+ this.checking = false;
56
+ }
57
+ }
58
+ }
@@ -0,0 +1,19 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { z } from 'zod';
7
+ export function registerCodexAutoReset(app, preferences) {
8
+ app.get('/api/codex/allowance/auto-reset', async (_request, reply) => {
9
+ reply.header('Cache-Control', 'no-store');
10
+ return preferences.status();
11
+ });
12
+ app.put('/api/codex/allowance/auto-reset', async (request, reply) => {
13
+ const parsed = z.strictObject({ enabled: z.boolean() }).safeParse(request.body);
14
+ if (!parsed.success)
15
+ return reply.code(400).send({ code: 'INVALID_CODEX_AUTO_RESET' });
16
+ preferences.setEnabled(parsed.data.enabled);
17
+ return preferences.status();
18
+ });
19
+ }
@@ -5,12 +5,15 @@
5
5
  */
6
6
  import { registerGetBootstrap } from './get-bootstrap/endpoint.js';
7
7
  import { registerSessionDefaults } from './session-defaults/endpoint.js';
8
+ import { registerCodexAutoReset, } from './codex-auto-reset/endpoint.js';
8
9
  import { registerGetCodexAllowance, } from './get-codex-allowance/endpoint.js';
9
10
  export function registerCatalogRoutes(app, deps) {
10
11
  if (deps.bootstrap)
11
12
  registerGetBootstrap(app, deps.bootstrap);
12
13
  if (deps.codexAllowance)
13
14
  registerGetCodexAllowance(app, deps.codexAllowance);
15
+ if (deps.codexAutoReset)
16
+ registerCodexAutoReset(app, deps.codexAutoReset);
14
17
  if (deps.sessionDefaults)
15
18
  registerSessionDefaults(app, deps.sessionDefaults);
16
19
  }
@@ -3,8 +3,60 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- import { createHash } from 'node:crypto';
7
- import { mkdirSync, chmodSync } from 'node:fs';
6
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
7
+ if (value !== null && value !== void 0) {
8
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
9
+ var dispose, inner;
10
+ if (async) {
11
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
12
+ dispose = value[Symbol.asyncDispose];
13
+ }
14
+ if (dispose === void 0) {
15
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
16
+ dispose = value[Symbol.dispose];
17
+ if (async) inner = dispose;
18
+ }
19
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
20
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
21
+ env.stack.push({ value: value, dispose: dispose, async: async });
22
+ }
23
+ else if (async) {
24
+ env.stack.push({ async: true });
25
+ }
26
+ return value;
27
+ };
28
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
29
+ return function (env) {
30
+ function fail(e) {
31
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
32
+ env.hasError = true;
33
+ }
34
+ var r, s = 0;
35
+ function next() {
36
+ while (r = env.stack.pop()) {
37
+ try {
38
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
39
+ if (r.dispose) {
40
+ var result = r.dispose.call(r.value);
41
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
42
+ }
43
+ else s |= 1;
44
+ }
45
+ catch (e) {
46
+ fail(e);
47
+ }
48
+ }
49
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
50
+ if (env.hasError) throw env.error;
51
+ }
52
+ return next();
53
+ };
54
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
55
+ var e = new Error(message);
56
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
57
+ });
58
+ import { createHash, randomBytes } from 'node:crypto';
59
+ import { mkdirSync, chmodSync, statSync } from 'node:fs';
8
60
  import { dirname, join, resolve } from 'node:path';
9
61
  import { DatabaseSync } from 'node:sqlite';
10
62
  import { authorizedDeviceId, localOwnerId, passkeyCeremonyId, webAuthnCredentialId, } from '../../features/auth/domain/identifiers.js';
@@ -21,6 +73,75 @@ const startupLockWaiter = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_
21
73
  export function authorizationDatabasePath(homeDirectory) {
22
74
  return join(resolve(homeDirectory), '.codex-gestalt', 'gestalt-mobile', 'auth.sqlite');
23
75
  }
76
+ export class AuthorizationHostnameMismatchError extends Error {
77
+ constructor() {
78
+ super('WebAuthn RP ID hostname changed while credentials exist');
79
+ }
80
+ }
81
+ function storedRpId(db) {
82
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'auth_settings'").get())
83
+ return undefined;
84
+ const settings = db.prepare('SELECT rp_id FROM auth_settings WHERE singleton = 1').get();
85
+ return settings?.rp_id;
86
+ }
87
+ export function checkAuthorizationHostname(homeDirectory, rpId) {
88
+ const env_1 = { stack: [], error: void 0, hasError: false };
89
+ try {
90
+ const path = authorizationDatabasePath(homeDirectory);
91
+ if (!statSync(path, { throwIfNoEntry: false }))
92
+ return;
93
+ const db = __addDisposableResource(env_1, new DatabaseSync(path, { readOnly: true, timeout: SQLITE_STARTUP_BUSY_TIMEOUT_MS }), false);
94
+ db.exec('BEGIN');
95
+ const stored = storedRpId(db);
96
+ if (stored !== undefined &&
97
+ stored !== rpId &&
98
+ db.prepare('SELECT 1 FROM auth_devices LIMIT 1').get())
99
+ throw new AuthorizationHostnameMismatchError();
100
+ }
101
+ catch (e_1) {
102
+ env_1.error = e_1;
103
+ env_1.hasError = true;
104
+ }
105
+ finally {
106
+ __disposeResources(env_1);
107
+ }
108
+ }
109
+ export function resetAuthorizationHostname(homeDirectory, rpId) {
110
+ const env_2 = { stack: [], error: void 0, hasError: false };
111
+ try {
112
+ const path = authorizationDatabasePath(homeDirectory);
113
+ if (!statSync(path, { throwIfNoEntry: false }))
114
+ return 'uninitialized';
115
+ const db = __addDisposableResource(env_2, new DatabaseSync(path, { timeout: SQLITE_STARTUP_BUSY_TIMEOUT_MS }), false);
116
+ // An exclusive WAL connection cannot acquire its lock while another relay
117
+ // has the shared auth database open. Keep the lock until the reset commits.
118
+ db.exec('PRAGMA locking_mode = EXCLUSIVE;');
119
+ try {
120
+ return withImmediateTransaction(db, () => {
121
+ const stored = storedRpId(db);
122
+ if (stored === undefined)
123
+ return 'uninitialized';
124
+ if (stored === rpId)
125
+ return 'alreadyConfigured';
126
+ db.exec('DELETE FROM auth_sessions; DELETE FROM auth_tickets; DELETE FROM auth_ceremonies; DELETE FROM auth_devices;');
127
+ db.prepare('UPDATE auth_settings SET rp_id = ?, user_handle = ? WHERE singleton = 1').run(rpId, randomBytes(32));
128
+ return 'reset';
129
+ });
130
+ }
131
+ catch (error) {
132
+ if (isLocked(error))
133
+ throw new Error('Stop every Gestalt Mobile relay using this authorization database, then retry.');
134
+ throw error;
135
+ }
136
+ }
137
+ catch (e_2) {
138
+ env_2.error = e_2;
139
+ env_2.hasError = true;
140
+ }
141
+ finally {
142
+ __disposeResources(env_2);
143
+ }
144
+ }
24
145
  /** SQLite adapter for the auth bounded context. No SQLite types escape this file. */
25
146
  export class SqliteAuthorizationStore {
26
147
  path;
@@ -86,7 +207,7 @@ CREATE TABLE IF NOT EXISTS auth_sessions (token_hash TEXT PRIMARY KEY, device_id
86
207
  .prepare('SELECT rp_id FROM auth_settings WHERE singleton = 1')
87
208
  .get();
88
209
  if (settings && settings.rp_id !== this.relyingParty.rpId && this.deviceCount() > 0)
89
- throw new Error('WebAuthn RP ID hostname changed while credentials exist');
210
+ throw new AuthorizationHostnameMismatchError();
90
211
  });
91
212
  }
92
213
  initializeOwner(userHandle) {
@@ -101,7 +222,7 @@ CREATE TABLE IF NOT EXISTS auth_sessions (token_hash TEXT PRIMARY KEY, device_id
101
222
  .prepare('INSERT INTO auth_settings (singleton, schema_version, rp_id, user_handle) VALUES (1, ?, ?, ?)')
102
223
  .run(SCHEMA_VERSION, this.relyingParty.rpId, userHandle);
103
224
  else if (current.rp_id !== this.relyingParty.rpId && this.deviceCount() > 0)
104
- throw new Error('WebAuthn RP ID hostname changed while credentials exist');
225
+ throw new AuthorizationHostnameMismatchError();
105
226
  else if (current.rp_id !== this.relyingParty.rpId)
106
227
  this.statements
107
228
  .prepare('UPDATE auth_settings SET rp_id = ? WHERE singleton = 1')
@@ -11,8 +11,7 @@ const windowSchema = z.object({
11
11
  resetsAt: z.unknown().optional(),
12
12
  });
13
13
  const recordSchema = z.record(z.string(), z.unknown());
14
- /** Return only account-wide counters, never account identifiers or credit details. */
15
- export function decodeCodexAllowance(value) {
14
+ function readCodexLimits(value) {
16
15
  const response = recordSchema.safeParse(value);
17
16
  const data = response.success ? response.data : {};
18
17
  const buckets = recordSchema.safeParse(data.rateLimitsByLimitId);
@@ -23,23 +22,57 @@ export function decodeCodexAllowance(value) {
23
22
  const weekly = [limits.primary, limits.secondary]
24
23
  .map((window) => windowSchema.safeParse(window))
25
24
  .find((window) => window.success);
25
+ return {
26
+ limits,
27
+ weekly: weekly?.success ? weekly.data : undefined,
28
+ credits: data.rateLimitResetCredits,
29
+ };
30
+ }
31
+ /** Return only account-wide counters, never account identifiers or credit details. */
32
+ export function decodeCodexAllowance(value) {
33
+ const { weekly, credits: rawCredits } = readCodexLimits(value);
26
34
  const credits = z
27
35
  .object({ availableCount: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) })
28
- .safeParse(data.rateLimitResetCredits);
29
- const reset = z
30
- .number()
31
- .int()
32
- .nonnegative()
33
- .max(8_640_000_000_000)
34
- .safeParse(weekly?.success ? weekly.data.resetsAt : null);
36
+ .safeParse(rawCredits);
37
+ const reset = z.number().int().nonnegative().max(8_640_000_000_000).safeParse(weekly?.resetsAt);
35
38
  return {
36
- weeklyRemainingPercent: weekly?.success
37
- ? Math.round(Math.max(0, Math.min(100, 100 - weekly.data.usedPercent)))
39
+ weeklyRemainingPercent: weekly
40
+ ? Math.round(Math.max(0, Math.min(100, 100 - weekly.usedPercent)))
38
41
  : null,
39
42
  resetsAvailable: credits.success ? credits.data.availableCount : null,
40
43
  weeklyResetsAt: reset.success ? reset.data : null,
41
44
  };
42
45
  }
46
+ const availableCreditSchema = z.object({
47
+ id: z.string().min(1).max(512),
48
+ status: z.literal('available'),
49
+ resetType: z.literal('codexRateLimits'),
50
+ expiresAt: z.number().int().nonnegative().nullish(),
51
+ });
52
+ export function decodeWeeklyResetCandidate(value, now) {
53
+ const { limits, weekly, credits } = readCodexLimits(value);
54
+ const reached = limits.rateLimitReachedType;
55
+ if (!weekly ||
56
+ weekly.usedPercent < 100 ||
57
+ limits.spendControlReached === true ||
58
+ (reached != null && reached !== 'rate_limit_reached'))
59
+ return null;
60
+ const resetsAt = z.number().int().positive().max(8_640_000_000_000).safeParse(weekly.resetsAt);
61
+ if (!resetsAt.success || resetsAt.data * 1000 <= now + 60_000)
62
+ return null;
63
+ const summary = z
64
+ .object({ availableCount: z.number().int().positive(), credits: z.array(z.unknown()) })
65
+ .safeParse(credits);
66
+ if (!summary.success)
67
+ return null;
68
+ for (const row of summary.data.credits) {
69
+ const credit = availableCreditSchema.safeParse(row);
70
+ if (credit.success &&
71
+ (credit.data.expiresAt == null || credit.data.expiresAt * 1000 > now + 10_000))
72
+ return { creditId: credit.data.id, weeklyResetsAt: resetsAt.data };
73
+ }
74
+ return null;
75
+ }
43
76
  /** A bounded account read also works before a user has opened a session. */
44
77
  export class CodexAllowanceReader {
45
78
  cwd;
@@ -9,6 +9,7 @@ import { readExecutorConfiguration } from './executor-configuration.js';
9
9
  import { decodeCodexPolicyCatalog } from './codex-model-catalog.js';
10
10
  import { RelaySession, } from '../../features/sessions/model/relay-session.js';
11
11
  import { randomUUID } from 'node:crypto';
12
+ import { decodeWeeklyResetCandidate } from './codex-allowance.js';
12
13
  import { createPlanMeasurementSnapshot, } from '../../features/plans/application/measurement-snapshot.js';
13
14
  import { canRebindMissingRollout, rebindMissingRollout, } from '../../features/sessions/restore-session/use-case.js';
14
15
  import { gestaltQuizDynamicTool } from '../../../shared/contracts/quiz.js';
@@ -825,6 +826,26 @@ export class CodexSessionRuntime {
825
826
  ...(clientUserMessageId ? { clientUserMessageId } : {}),
826
827
  });
827
828
  }
829
+ weeklyResetAccount(sessionId, runtimeId, allowed) {
830
+ const resource = this.sessions.get(sessionId);
831
+ if (!resource?.active || resource.mcpStartup.runtimeId !== runtimeId)
832
+ return null;
833
+ const request = (method, params) => {
834
+ if (!allowed() || !resource.active || this.sessions.get(sessionId) !== resource)
835
+ throw new Error('CODEX_RESET_SESSION_CHANGED');
836
+ return resource.process.rpc.request(method, params);
837
+ };
838
+ return {
839
+ readCandidate: async (now) => decodeWeeklyResetCandidate(await request('account/rateLimits/read', {}), now),
840
+ redeem: async (creditId, idempotencyKey) => {
841
+ const result = asRecord(await request('account/rateLimitResetCredit/consume', {
842
+ creditId,
843
+ idempotencyKey,
844
+ }));
845
+ return result?.outcome === 'reset' || result?.outcome === 'alreadyRedeemed';
846
+ },
847
+ };
848
+ }
828
849
  async readPlanMeasurement(session) {
829
850
  const resource = this.sessions.get(session.id);
830
851
  if (!resource || !session.threadId)