gestalt-mobile 0.75.4 → 0.76.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.
@@ -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);
@@ -2283,6 +2299,7 @@ export async function composeRelayApp(options) {
2283
2299
  pwaIcon: options.pwaIcon,
2284
2300
  recentThreads: recentThreadsForRelay,
2285
2301
  sessionDefaults,
2302
+ codexAutoReset: codexResetStore,
2286
2303
  codexAllowance: options.installedCodexVersion === null
2287
2304
  ? {
2288
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
  }
@@ -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)
@@ -0,0 +1,181 @@
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
+ 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 { closeSync, mkdirSync, openSync, statSync } from 'node:fs';
59
+ import { dirname, join } from 'node:path';
60
+ import { DatabaseSync } from 'node:sqlite';
61
+ import { resetCreditCooldownMs, } from '../../features/catalog/application/codex-auto-reset.js';
62
+ /** All workspaces share this account-level ledger, independent of relay.sqlite. */
63
+ export class SqliteCodexResetStore {
64
+ path;
65
+ constructor(homeDirectory) {
66
+ this.path = join(homeDirectory, '.gestalt', 'codex-reset-credits.sqlite');
67
+ }
68
+ open() {
69
+ if (!statSync(this.path, { throwIfNoEntry: false }))
70
+ return undefined;
71
+ const db = new DatabaseSync(this.path, { timeout: 1_000 });
72
+ try {
73
+ if (db
74
+ .prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'codex_reset_settings'")
75
+ .get())
76
+ return db;
77
+ }
78
+ catch (error) {
79
+ db.close();
80
+ throw error;
81
+ }
82
+ db.close();
83
+ return undefined;
84
+ }
85
+ enabled() {
86
+ const env_1 = { stack: [], error: void 0, hasError: false };
87
+ try {
88
+ const db = __addDisposableResource(env_1, this.open(), false);
89
+ return (db?.prepare('SELECT enabled FROM codex_reset_settings WHERE id = 1').get()?.enabled === 1);
90
+ }
91
+ catch (e_1) {
92
+ env_1.error = e_1;
93
+ env_1.hasError = true;
94
+ }
95
+ finally {
96
+ __disposeResources(env_1);
97
+ }
98
+ }
99
+ status() {
100
+ const env_2 = { stack: [], error: void 0, hasError: false };
101
+ try {
102
+ const db = __addDisposableResource(env_2, this.open(), false);
103
+ if (!db)
104
+ return { enabled: false, resets: [] };
105
+ return {
106
+ enabled: db.prepare('SELECT enabled FROM codex_reset_settings WHERE id = 1').get()?.enabled === 1,
107
+ resets: db
108
+ .prepare('SELECT id, reset_at AS occurredAt FROM codex_reset_attempts WHERE reset_at IS NOT NULL ORDER BY reset_at DESC LIMIT 50')
109
+ .all(),
110
+ };
111
+ }
112
+ catch (e_2) {
113
+ env_2.error = e_2;
114
+ env_2.hasError = true;
115
+ }
116
+ finally {
117
+ __disposeResources(env_2);
118
+ }
119
+ }
120
+ setEnabled(enabled) {
121
+ const env_3 = { stack: [], error: void 0, hasError: false };
122
+ try {
123
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
124
+ closeSync(openSync(this.path, 'a', 0o600));
125
+ const db = __addDisposableResource(env_3, new DatabaseSync(this.path, { timeout: 1_000 }), false);
126
+ db.exec(`BEGIN IMMEDIATE;
127
+ CREATE TABLE IF NOT EXISTS codex_reset_settings (id INTEGER PRIMARY KEY CHECK (id = 1), enabled INTEGER NOT NULL);
128
+ CREATE TABLE IF NOT EXISTS codex_reset_attempts (
129
+ id TEXT PRIMARY KEY, attempted_at INTEGER NOT NULL, weekly_resets_at INTEGER NOT NULL, reset_at INTEGER
130
+ );
131
+ COMMIT;`);
132
+ db.prepare(`INSERT INTO codex_reset_settings (id, enabled) VALUES (1, ?)
133
+ ON CONFLICT(id) DO UPDATE SET enabled = excluded.enabled`).run(Number(enabled));
134
+ }
135
+ catch (e_3) {
136
+ env_3.error = e_3;
137
+ env_3.hasError = true;
138
+ }
139
+ finally {
140
+ __disposeResources(env_3);
141
+ }
142
+ }
143
+ claim(id, now, weeklyResetsAt) {
144
+ const env_4 = { stack: [], error: void 0, hasError: false };
145
+ try {
146
+ const db = __addDisposableResource(env_4, this.open(), false);
147
+ // One atomic write across processes checks opt-in, cooldown and original
148
+ // window. Keeping attempted windows fences stale reads and uncertain replies.
149
+ return (db
150
+ ?.prepare(`INSERT INTO codex_reset_attempts (id, attempted_at, weekly_resets_at)
151
+ SELECT ?, ?, ?
152
+ WHERE EXISTS (SELECT 1 FROM codex_reset_settings WHERE id = 1 AND enabled = 1)
153
+ AND NOT EXISTS (
154
+ SELECT 1 FROM codex_reset_attempts
155
+ WHERE attempted_at > ? OR reset_at > ? OR weekly_resets_at >= ?
156
+ )`)
157
+ .run(id, now, weeklyResetsAt, now - resetCreditCooldownMs, now - resetCreditCooldownMs, weeklyResetsAt).changes === 1);
158
+ }
159
+ catch (e_4) {
160
+ env_4.error = e_4;
161
+ env_4.hasError = true;
162
+ }
163
+ finally {
164
+ __disposeResources(env_4);
165
+ }
166
+ }
167
+ recordReset(id, occurredAt) {
168
+ const env_5 = { stack: [], error: void 0, hasError: false };
169
+ try {
170
+ const db = __addDisposableResource(env_5, this.open(), false);
171
+ db?.prepare('UPDATE codex_reset_attempts SET reset_at = ? WHERE id = ? AND reset_at IS NULL').run(occurredAt, id);
172
+ }
173
+ catch (e_5) {
174
+ env_5.error = e_5;
175
+ env_5.hasError = true;
176
+ }
177
+ finally {
178
+ __disposeResources(env_5);
179
+ }
180
+ }
181
+ }
@@ -3,4 +3,13 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export {};
6
+ import { z } from 'zod';
7
+ export const codexAutoResetStatusSchema = z.object({
8
+ enabled: z.boolean(),
9
+ resets: z
10
+ .array(z.object({
11
+ id: z.string().min(1).max(80),
12
+ occurredAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
13
+ }))
14
+ .max(50),
15
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.75.4",
3
+ "version": "0.76.1",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",