johns-harness 2026.11.6 → 2026.11.7

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.11.7
4
+
5
+ - Refresh Claude subscription OAuth proactively at gateway startup and every five minutes when less than one hour remains. Retry early with persisted exponential backoff and Retry-After support; no model turn required.
6
+ - Share Anthropic refresh ownership, cross-process locks and generation CAS across timer and lazy resolution. Protect rotated credentials from stale snapshot writes, preserve local-agent accounts and publish refreshed auth into running sessions.
7
+ - Apply the same early schedule to ChatGPT/Codex through its existing native ownership manager. Keep lazy fallback and visible API-fallback reasons unchanged.
8
+ - Validate startup/idle renewal and recovery in an isolated real gateway without using live tokens or paid inference. No live gateway restart during publication. Run `/update`; rollback: `npm i -g johns-harness@2026.11.6`.
9
+
3
10
  ## 2026.11.6
4
11
 
5
12
  ### Latest Sunburst edits, highest requested quality
@@ -0,0 +1,139 @@
1
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
+ // One rotating-token owner for both the gateway timer and every lazy Anthropic resolver.
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ import { canonicalPath, readAuthStore, sameCredential, profileLockPath, queued, acquireOwnedLock, transactAuthStore } from './auth-store-transactions.js';
8
+ import { refreshRuntimeAuthStores } from './subscription-login.js';
9
+
10
+ export const isAnthropicOAuth = c => c?.type === 'oauth' && c.provider === 'anthropic';
11
+ const valid = c => isAnthropicOAuth(c) && typeof c.access === 'string' && c.access && Number.isFinite(c.expires);
12
+ const generation = c => createHash('sha256').update(JSON.stringify(c)).digest('hex');
13
+ // Retain a successfully rotated result if disk persistence transiently fails. Retrying the
14
+ // write must never spend the now-consumed refresh token again in this gateway process.
15
+ const pendingCommits = globalThis[Symbol.for('johnness.anthropicPendingCommit.95')] ??= new Map();
16
+ const reasons = new Set(['network_error', 'invalid_response', 'auth_rejected', 'rate_limit', 'server_error', 'request_rejected', 'missing_refresh', 'owner_conflict', 'credential_changed', 'persist_failed', 'lock_contention']);
17
+ export class AnthropicRefreshError extends Error {
18
+ constructor(reason, retryAt) { super(`Claude subscription refresh: ${reasons.has(reason) ? reason : 'request_rejected'}`); this.reason = reasons.has(reason) ? reason : 'request_rejected'; this.retryAt = retryAt; }
19
+ }
20
+ export function anthropicRefreshContext(params = {}) {
21
+ const stateDir = canonicalPath(params.stateDir ?? process.env.JOHNNESS_STATE_DIR ?? path.join(os.homedir(), '.johnness'));
22
+ const mainAgentDir = canonicalPath(params.mainAgentDir ?? process.env.JOHNNESS_AGENT_DIR ?? process.env.PI_CODING_AGENT_DIR ?? path.join(stateDir, 'agents/main/agent'));
23
+ const agentDir = canonicalPath(params.agentDir ?? mainAgentDir);
24
+ return { ...params, stateDir, mainAgentDir, agentDir };
25
+ }
26
+ export function anthropicOwner(params) {
27
+ const ctx = anthropicRefreshContext(params), mainFile = path.join(ctx.mainAgentDir, 'auth-profiles.json'), localFile = path.join(ctx.agentDir, 'auth-profiles.json');
28
+ const local = readAuthStore(localFile);
29
+ const file = Object.hasOwn(local.profiles, ctx.profileId) ? localFile : mainFile;
30
+ const store = file === localFile ? local : readAuthStore(file);
31
+ return { ...ctx, file, store, credential: store.profiles[ctx.profileId] };
32
+ }
33
+ // Never spend a cloned rotating refresh token from a second owner or alias. Distinct local
34
+ // accounts remain local. Inherited profiles resolve to the main file and share its lock.
35
+ function assertUniqueOwner(ctx, credential) {
36
+ const dirs = new Set([ctx.mainAgentDir, ctx.agentDir, ...(ctx.agentDirs ?? [])]);
37
+ try { for (const entry of fs.readdirSync(path.join(ctx.stateDir, 'agents'), { withFileTypes: true })) if (entry.isDirectory()) dirs.add(path.join(ctx.stateDir, 'agents', entry.name, 'agent')); }
38
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
39
+ for (const dir of dirs) {
40
+ const file = canonicalPath(path.join(dir, 'auth-profiles.json'));
41
+ for (const [id, c] of Object.entries(readAuthStore(file).profiles)) {
42
+ if (file === ctx.file && id === ctx.profileId) continue;
43
+ if (isAnthropicOAuth(c) && c.refresh === credential.refresh) throw new AnthropicRefreshError('owner_conflict');
44
+ }
45
+ }
46
+ }
47
+ export function anthropicRetryAt(store, profileId, credential) {
48
+ const failure = store.oauthRefresh95?.[profileId];
49
+ return failure?.generation === generation(credential) && Number.isFinite(failure.nextAttemptAt) ? failure.nextAttemptAt : 0;
50
+ }
51
+ async function requestToken(credential, params) {
52
+ let response;
53
+ try { response = await (params.fetch ?? globalThis.fetch)('https://platform.claude.com/v1/oauth/token', {
54
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
55
+ body: JSON.stringify({ grant_type: 'refresh_token', client_id: '9d1c250a-e61b-44d9-88ed-5944d1962f5e', refresh_token: credential.refresh }),
56
+ signal: AbortSignal.timeout(30000)
57
+ }); } catch { throw new AnthropicRefreshError('network_error'); }
58
+ if (!response.ok) {
59
+ const retry = response.headers.get('retry-after');
60
+ const retryAt = retry && (/^\d+(?:\.\d+)?$/.test(retry) ? Date.now() + Number(retry) * 1000 : Date.parse(retry));
61
+ await response.body?.cancel().catch(() => {});
62
+ throw new AnthropicRefreshError(response.status === 429 ? 'rate_limit' : response.status >= 500 ? 'server_error' : [400, 401, 403].includes(response.status) ? 'auth_rejected' : 'request_rejected', Number.isFinite(retryAt) ? retryAt : undefined);
63
+ }
64
+ let data;
65
+ try { data = await response.json(); } catch { throw new AnthropicRefreshError('invalid_response'); }
66
+ const refresh = data.refresh_token ?? credential.refresh;
67
+ if (typeof data.access_token !== 'string' || !data.access_token || typeof refresh !== 'string' || !refresh || !Number.isFinite(data.expires_in) || data.expires_in <= 0) throw new AnthropicRefreshError('invalid_response');
68
+ // Match the login adapter's five-minute safety cushion without invalidating short-lived tokens.
69
+ return { ...credential, access: data.access_token, refresh, expires: Date.now() + data.expires_in * 1000 - Math.min(300000, data.expires_in * 100) };
70
+ }
71
+ function safeLog(ctx, outcome, extra = {}) {
72
+ // Profile IDs and paths are user-controlled; only provider, outcome and numeric timing are logged.
73
+ try { ctx.log?.({ provider: 'anthropic', outcome, ...extra }); } catch {}
74
+ }
75
+ export async function refreshAnthropicProfile(params = {}) {
76
+ const initial = anthropicOwner(params), profileId = params.profileId, marginMs = params.marginMs ?? 0;
77
+ const result = credential => ({ apiKey: credential.access, newCredentials: structuredClone(credential) });
78
+ if (!isAnthropicOAuth(initial.credential)) return null;
79
+ if (valid(initial.credential) && initial.credential.expires > Date.now() + marginMs) return result(initial.credential);
80
+ const lock = profileLockPath(initial.stateDir, 'anthropic', `${initial.file}\0${profileId}`);
81
+ return queued(lock, async () => {
82
+ const release = await acquireOwnedLock(lock, { waitMs: 60000 });
83
+ try {
84
+ const ctx = anthropicOwner(params), attempted = ctx.credential;
85
+ if (ctx.file !== initial.file) throw new AnthropicRefreshError('credential_changed');
86
+ if (!isAnthropicOAuth(attempted)) return null;
87
+ // Re-read AFTER acquiring the lock. A completed timer/lazy refresh is adopted, even if
88
+ // the endpoint issued a shorter-than-margin lifetime. Never spend its successor twice.
89
+ if (valid(attempted) && (attempted.expires > Date.now() + marginMs || (!sameCredential(initial.credential, attempted) && attempted.expires > Date.now()))) return result(attempted);
90
+ const retryAt = anthropicRetryAt(ctx.store, profileId, attempted);
91
+ if (retryAt > Date.now()) {
92
+ if (valid(attempted) && attempted.expires > Date.now() && marginMs === 0) return result(attempted);
93
+ throw new AnthropicRefreshError(ctx.store.oauthRefresh95[profileId].reason, retryAt);
94
+ }
95
+ const pending = pendingCommits.get(lock);
96
+ if (pending && !sameCredential(pending.attempted, attempted)) pendingCommits.delete(lock);
97
+ let next = pending && sameCredential(pending.attempted, attempted) ? pending.next : undefined;
98
+ try {
99
+ if (!next) {
100
+ if (typeof attempted.refresh !== 'string' || !attempted.refresh) throw new AnthropicRefreshError('missing_refresh');
101
+ assertUniqueOwner(ctx, attempted);
102
+ next = await requestToken(attempted, params);
103
+ }
104
+ } catch (error) {
105
+ const reason = error instanceof AnthropicRefreshError ? error.reason : 'request_rejected';
106
+ let nextAttemptAt;
107
+ const saved = await transactAuthStore(ctx.file, store => {
108
+ if (!sameCredential(store.profiles[profileId], attempted)) return false;
109
+ const previous = store.oauthRefresh95?.[profileId];
110
+ const failures = Math.min(20, (previous?.generation === generation(attempted) ? previous.failures ?? 0 : 0) + 1);
111
+ const backoff = Math.min(15 * 60000, 60000 * 2 ** (failures - 1));
112
+ nextAttemptAt = Math.max(Date.now() + backoff + Math.floor((params.random ?? Math.random)() * backoff * 0.1), error.retryAt ?? 0);
113
+ store.oauthRefresh95 ??= {};
114
+ store.oauthRefresh95[profileId] = { generation: generation(attempted), failures, reason, nextAttemptAt };
115
+ });
116
+ const changed = saved.store.profiles[profileId];
117
+ if (saved.result === false && valid(changed) && changed.expires > Date.now()) return result(changed);
118
+ safeLog(ctx, 'retry_scheduled', { reason, retryAt: nextAttemptAt ?? 0 });
119
+ throw new AnthropicRefreshError(reason, nextAttemptAt);
120
+ }
121
+ let saved;
122
+ try { saved = await transactAuthStore(ctx.file, store => {
123
+ if (!sameCredential(store.profiles[profileId], attempted)) return false;
124
+ store.profiles[profileId] = next;
125
+ delete store.oauthRefresh95?.[profileId];
126
+ // Refresh recovery clears authentication cooldown only, never quota/rate-limit cooldown.
127
+ const stats = store.usageStats?.[profileId];
128
+ if (stats?.failureCounts?.auth && !Object.keys(stats.failureCounts).some(k => k !== 'auth' && stats.failureCounts[k] > 0) && !stats.disabledUntil) delete store.usageStats[profileId];
129
+ }); } catch { pendingCommits.set(lock, { attempted, next }); safeLog(ctx, 'persist_failed'); throw new AnthropicRefreshError('persist_failed'); }
130
+ pendingCommits.delete(lock);
131
+ const current = saved.store.profiles[profileId];
132
+ if (!valid(current) || current.expires <= Date.now()) throw new AnthropicRefreshError('credential_changed');
133
+ if (params.store) params.store.profiles[profileId] = structuredClone(current);
134
+ const published = await refreshRuntimeAuthStores({ rpc: false, refreshRuntime: params.refreshRuntime });
135
+ safeLog(ctx, saved.result === false ? 'adopted' : 'refreshed', { expires: current.expires, runtimePublished: published === 'in-process' });
136
+ return result(current);
137
+ } finally { await release(); }
138
+ });
139
+ }
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "./anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "./anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "./subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "./catalog-refresh.js";
@@ -16459,6 +16460,7 @@ async function refreshOAuthTokenWithLock(params) {
16459
16460
  profileId: params.profileId,
16460
16461
  store: params.store
16461
16462
  });
16463
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
16462
16464
  return await refreshUnmanagedOAuthTokenWithLock(params);
16463
16465
  }
16464
16466
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -16518,6 +16520,12 @@ async function tryResolveOAuthProfile(params) {
16518
16520
  if (!result) return null;
16519
16521
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
16520
16522
  }
16523
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
16524
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
16525
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
16526
+ if (!result) return null;
16527
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
16528
+ }
16521
16529
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
16522
16530
  provider: cred.provider,
16523
16531
  credentials: cred,
@@ -16586,6 +16594,12 @@ async function resolveApiKeyForProfile(params) {
16586
16594
  if (!result) return null;
16587
16595
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
16588
16596
  }
16597
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
16598
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
16599
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
16600
+ if (!result) return null;
16601
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
16602
+ }
16589
16603
  const refResolveCache = {};
16590
16604
  const configForRefResolution = cfg ?? loadConfig();
16591
16605
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -217,9 +217,11 @@ export async function saveAuthStoreSnapshot(params={}) {
217
217
  const {store}=await transactAuthStore(ctx.localPath,fresh=>{
218
218
  // A snapshot is never credential authority for managed Codex, including absent,
219
219
  // deleted, switched or inherited entries. Explicit changes use mutateAuthProfile.
220
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: snapshots cannot overwrite rotated Anthropic credentials either.
221
+ const rotating=c=>isManagedCodexCredential(c)||(c?.type==='oauth'&&c.provider==='anthropic');
220
222
  const profiles={};
221
- for(const [id,c]of Object.entries(input.profiles??{}))if(!isManagedCodexCredential(c))profiles[id]=clone(c);
222
- for(const [id,c]of Object.entries(fresh.profiles))if(isManagedCodexCredential(c)||isManagedCodexCredential(input.profiles?.[id]))profiles[id]=c;
223
+ for(const [id,c]of Object.entries(input.profiles??{}))if(!rotating(c))profiles[id]=clone(c);
224
+ for(const [id,c]of Object.entries(fresh.profiles))if(rotating(c)||rotating(input.profiles?.[id]))profiles[id]=c;
223
225
  fresh.profiles=profiles;
224
226
  for(const key of ['usageStats','lastGood','order'])if(Object.hasOwn(input,key))fresh[key]=clone(input[key]);
225
227
  },ctx);
@@ -1,3 +1,4 @@
1
+ import { startOAuthRefreshTimer } from "./oauth-refresh-timer.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
1
2
  // JOHNNESS_PATCH_SAFE_VOLUME_UPDATE_65_1
2
3
  import { readInstalledVersion as readUpdatedRuntimeVersion } from "./update-command.js";
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
@@ -23870,6 +23871,12 @@ async function startGatewayServer(port = 18789, opts = {}) {
23870
23871
  /* JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: a subscription login inside this process (chat /login) refreshes the
23871
23872
  runtime auth snapshot through this hook, the same path as the secrets.reload RPC. */
23872
23873
  globalThis[Symbol.for('johnness.authRuntimeRefresh.v1')] = reloadRuntimeSecrets;
23874
+ const oauthRefreshTimer = startOAuthRefreshTimer({
23875
+ stateDir: resolveStateDir(),
23876
+ getAgentDirs: () => { const cfg = loadConfig(); return listAgentIds(cfg).map(id => resolveAgentDir(cfg, id)); },
23877
+ refreshRuntime: reloadRuntimeSecrets,
23878
+ log: event => event.outcome === "refreshed" || event.outcome === "checked" ? log.info("OAuth refresh timer", event) : log.warn("OAuth refresh timer", event)
23879
+ }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
23873
23880
  const secretsHandlers = createSecretsHandlers({
23874
23881
  reloadSecrets: reloadRuntimeSecrets,
23875
23882
  resolveSecrets: async ({ commandName, targetIds }) => {
@@ -24096,6 +24103,7 @@ async function startGatewayServer(port = 18789, opts = {}) {
24096
24103
  });
24097
24104
  return { close: async (opts) => {
24098
24105
  stopGatewayEventLoopLagMonitor();
24106
+ await oauthRefreshTimer.stop(); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
24099
24107
  await runGlobalGatewayStopSafely({
24100
24108
  event: { reason: opts?.reason ?? "gateway stopping" },
24101
24109
  ctx: { port },
@@ -1,3 +1,4 @@
1
+ import { startOAuthRefreshTimer } from "./oauth-refresh-timer.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
1
2
  // JOHNNESS_PATCH_SAFE_VOLUME_UPDATE_65_1
2
3
  import { readInstalledVersion as readUpdatedRuntimeVersion } from "./update-command.js";
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
@@ -23872,6 +23873,12 @@ async function startGatewayServer(port = 18789, opts = {}) {
23872
23873
  /* JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: a subscription login inside this process (chat /login) refreshes the
23873
23874
  runtime auth snapshot through this hook, the same path as the secrets.reload RPC. */
23874
23875
  globalThis[Symbol.for('johnness.authRuntimeRefresh.v1')] = reloadRuntimeSecrets;
23876
+ const oauthRefreshTimer = startOAuthRefreshTimer({
23877
+ stateDir: resolveStateDir(),
23878
+ getAgentDirs: () => { const cfg = loadConfig(); return listAgentIds(cfg).map(id => resolveAgentDir(cfg, id)); },
23879
+ refreshRuntime: reloadRuntimeSecrets,
23880
+ log: event => event.outcome === "refreshed" || event.outcome === "checked" ? log.info("OAuth refresh timer", event) : log.warn("OAuth refresh timer", event)
23881
+ }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
23875
23882
  const secretsHandlers = createSecretsHandlers({
23876
23883
  reloadSecrets: reloadRuntimeSecrets,
23877
23884
  resolveSecrets: async ({ commandName, targetIds }) => {
@@ -24098,6 +24105,7 @@ async function startGatewayServer(port = 18789, opts = {}) {
24098
24105
  });
24099
24106
  return { close: async (opts) => {
24100
24107
  stopGatewayEventLoopLagMonitor();
24108
+ await oauthRefreshTimer.stop(); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
24101
24109
  await runGlobalGatewayStopSafely({
24102
24110
  event: { reason: opts?.reason ?? "gateway stopping" },
24103
24111
  ctx: { port },
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "./anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "./anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "./subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "./catalog-refresh.js";
@@ -14674,6 +14675,7 @@ async function refreshOAuthTokenWithLock(params) {
14674
14675
  profileId: params.profileId,
14675
14676
  store: params.store
14676
14677
  });
14678
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
14677
14679
  return await refreshUnmanagedOAuthTokenWithLock(params);
14678
14680
  }
14679
14681
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -14733,6 +14735,12 @@ async function tryResolveOAuthProfile(params) {
14733
14735
  if (!result) return null;
14734
14736
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
14735
14737
  }
14738
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
14739
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
14740
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
14741
+ if (!result) return null;
14742
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
14743
+ }
14736
14744
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
14737
14745
  provider: cred.provider,
14738
14746
  credentials: cred,
@@ -14801,6 +14809,12 @@ async function resolveApiKeyForProfile(params) {
14801
14809
  if (!result) return null;
14802
14810
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
14803
14811
  }
14812
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
14813
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
14814
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
14815
+ if (!result) return null;
14816
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
14817
+ }
14804
14818
  const refResolveCache = {};
14805
14819
  const configForRefResolution = cfg ?? loadConfig();
14806
14820
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "./anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "./anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "./subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "./catalog-refresh.js";
@@ -14563,6 +14564,7 @@ async function refreshOAuthTokenWithLock(params) {
14563
14564
  profileId: params.profileId,
14564
14565
  store: params.store
14565
14566
  });
14567
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
14566
14568
  return await refreshUnmanagedOAuthTokenWithLock(params);
14567
14569
  }
14568
14570
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -14622,6 +14624,12 @@ async function tryResolveOAuthProfile(params) {
14622
14624
  if (!result) return null;
14623
14625
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
14624
14626
  }
14627
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
14628
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
14629
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
14630
+ if (!result) return null;
14631
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
14632
+ }
14625
14633
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
14626
14634
  provider: cred.provider,
14627
14635
  credentials: cred,
@@ -14690,6 +14698,12 @@ async function resolveApiKeyForProfile(params) {
14690
14698
  if (!result) return null;
14691
14699
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
14692
14700
  }
14701
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
14702
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
14703
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
14704
+ if (!result) return null;
14705
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
14706
+ }
14693
14707
  const refResolveCache = {};
14694
14708
  const configForRefResolution = cfg ?? loadConfig();
14695
14709
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "./anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "./anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "./subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "./catalog-refresh.js";
@@ -12936,6 +12937,7 @@ async function refreshOAuthTokenWithLock(params) {
12936
12937
  profileId: params.profileId,
12937
12938
  store: params.store
12938
12939
  });
12940
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
12939
12941
  return await refreshUnmanagedOAuthTokenWithLock(params);
12940
12942
  }
12941
12943
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -12995,6 +12997,12 @@ async function tryResolveOAuthProfile(params) {
12995
12997
  if (!result) return null;
12996
12998
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
12997
12999
  }
13000
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
13001
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
13002
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
13003
+ if (!result) return null;
13004
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
13005
+ }
12998
13006
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
12999
13007
  provider: cred.provider,
13000
13008
  credentials: cred,
@@ -13063,6 +13071,12 @@ async function resolveApiKeyForProfile(params) {
13063
13071
  if (!result) return null;
13064
13072
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
13065
13073
  }
13074
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
13075
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
13076
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
13077
+ if (!result) return null;
13078
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
13079
+ }
13066
13080
  const refResolveCache = {};
13067
13081
  const configForRefResolution = cfg ?? loadConfig();
13068
13082
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -0,0 +1,80 @@
1
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
+ // Gateway-owned, not a cron job. No model calls, credential logging, or live-config mutations.
3
+ import path from 'node:path';
4
+ import { canonicalPath, readAuthStore } from './auth-store-transactions.js';
5
+ import { anthropicRefreshContext, anthropicRetryAt, refreshAnthropicProfile } from './anthropic-oauth-refresh.js';
6
+ import { refreshManagedCodexProfile, resolveCodexProfileOwner } from './codex-oauth-owner.js';
7
+ import { refreshRuntimeAuthStores } from './subscription-login.js';
8
+ export const OAUTH_CHECK_MS = 5 * 60000;
9
+ export const OAUTH_MARGIN_MS = 60 * 60000;
10
+
11
+ export function startOAuthRefreshTimer(options = {}) {
12
+ const ctx = anthropicRefreshContext(options);
13
+ const checkMs = options.checkMs ?? OAUTH_CHECK_MS, marginMs = options.marginMs ?? OAUTH_MARGIN_MS;
14
+ const schedule = options.setTimeout ?? setTimeout, cancel = options.clearTimeout ?? clearTimeout;
15
+ let stopped = false, timer, running, snapshotPending = false;
16
+ const codexRetries = new Map();
17
+ const log = event => { try { options.log?.(event); } catch {} };
18
+ async function sweep() {
19
+ let nextDelay = checkMs;
20
+ let dirs;
21
+ try { dirs = [...new Set([ctx.mainAgentDir, ...(options.getAgentDirs?.() ?? [])].map(canonicalPath))]; }
22
+ catch { log({ outcome: 'scan_failed' }); return nextDelay; }
23
+ const seen = new Set();
24
+ for (const agentDir of dirs) {
25
+ if (stopped) break;
26
+ let store;
27
+ try { store = readAuthStore(path.join(agentDir, 'auth-profiles.json')); }
28
+ catch { log({ outcome: 'store_unavailable' }); continue; }
29
+ for (const [profileId, c] of Object.entries(store.profiles)) {
30
+ if (stopped) break;
31
+ if (c?.type !== 'oauth' || !['anthropic', 'openai-codex'].includes(c.provider) || !c.refresh || !Number.isFinite(c.expires) || c.expires > Date.now() + marginMs) continue;
32
+ try {
33
+ const params = { ...ctx, agentDir, agentDirs: dirs, profileId };
34
+ if (c.provider === 'anthropic') {
35
+ const retryAt = anthropicRetryAt(store, profileId, c);
36
+ if (retryAt > Date.now()) { nextDelay = Math.min(nextDelay, retryAt - Date.now()); continue; }
37
+ const result = await refreshAnthropicProfile({ ...params, marginMs, log });
38
+ if (result) snapshotPending = true;
39
+ } else {
40
+ // Reuse Family 58's canonical-owner locks/CAS and fail-closed Codex policy.
41
+ // Do NOT introduce a second Codex refresh implementation or retry a spent token.
42
+ const owner = resolveCodexProfileOwner(params), key = `${owner.agentDir}\0${profileId}`;
43
+ if (seen.has(key)) continue;
44
+ seen.add(key);
45
+ const retry = codexRetries.get(key);
46
+ if (retry?.expires === c.expires && retry.at > Date.now()) { nextDelay = Math.min(nextDelay, retry.at - Date.now()); continue; }
47
+ try {
48
+ await refreshManagedCodexProfile({ ...params, skewMs: marginMs });
49
+ codexRetries.delete(key); snapshotPending = true;
50
+ log({ provider: c.provider, outcome: 'checked' });
51
+ } catch {
52
+ const failures = Math.min(5, (retry?.failures ?? 0) + 1), delay = Math.min(15 * 60000, 60000 * 2 ** (failures - 1));
53
+ codexRetries.set(key, { expires: c.expires, at: Date.now() + delay, failures });
54
+ nextDelay = Math.min(nextDelay, delay);
55
+ log({ provider: c.provider, outcome: 'retry_scheduled' });
56
+ }
57
+ }
58
+ } catch (error) {
59
+ if (Number.isFinite(error?.retryAt)) nextDelay = Math.min(nextDelay, Math.max(1000, error.retryAt - Date.now()));
60
+ // The Anthropic owner reports structured outcomes. Never stringify unknown errors.
61
+ else log({ provider: c.provider, outcome: 'refresh_unavailable' });
62
+ }
63
+ }
64
+ }
65
+ if (snapshotPending && !stopped) snapshotPending = (await refreshRuntimeAuthStores({ rpc: false, refreshRuntime: options.refreshRuntime })) === 'unavailable';
66
+ return nextDelay;
67
+ }
68
+ function tick() {
69
+ if (stopped) return Promise.resolve();
70
+ if (running) return running;
71
+ running = sweep().catch(() => { log({ outcome: 'sweep_failed' }); return checkMs; }).then(delay => {
72
+ running = undefined;
73
+ if (!stopped) { timer = schedule(tick, Math.max(1000, delay)); timer.unref?.(); }
74
+ });
75
+ return running;
76
+ }
77
+ // Immediate startup sweep includes expired tokens. Recurring checks discover later logins.
78
+ void tick();
79
+ return { async stop() { stopped = true; cancel(timer); await running; codexRetries.clear(); } };
80
+ }
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "../anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -2752,6 +2753,7 @@ async function refreshOAuthTokenWithLock(params) {
2752
2753
  profileId: params.profileId,
2753
2754
  store: params.store
2754
2755
  });
2756
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2755
2757
  return await refreshUnmanagedOAuthTokenWithLock(params);
2756
2758
  }
2757
2759
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -2811,6 +2813,12 @@ async function tryResolveOAuthProfile(params) {
2811
2813
  if (!result) return null;
2812
2814
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
2813
2815
  }
2816
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
2817
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
2818
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
2819
+ if (!result) return null;
2820
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
2821
+ }
2814
2822
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
2815
2823
  provider: cred.provider,
2816
2824
  credentials: cred,
@@ -2879,6 +2887,12 @@ async function resolveApiKeyForProfile(params) {
2879
2887
  if (!result) return null;
2880
2888
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
2881
2889
  }
2890
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
2891
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
2892
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
2893
+ if (!result) return null;
2894
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
2895
+ }
2882
2896
  const refResolveCache = {};
2883
2897
  const configForRefResolution = cfg ?? loadConfig();
2884
2898
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "../anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -3753,6 +3754,7 @@ async function refreshOAuthTokenWithLock(params) {
3753
3754
  profileId: params.profileId,
3754
3755
  store: params.store
3755
3756
  });
3757
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
3756
3758
  return await refreshUnmanagedOAuthTokenWithLock(params);
3757
3759
  }
3758
3760
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -3812,6 +3814,12 @@ async function tryResolveOAuthProfile(params) {
3812
3814
  if (!result) return null;
3813
3815
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
3814
3816
  }
3817
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
3818
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
3819
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
3820
+ if (!result) return null;
3821
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
3822
+ }
3815
3823
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
3816
3824
  provider: cred.provider,
3817
3825
  credentials: cred,
@@ -3880,6 +3888,12 @@ async function resolveApiKeyForProfile(params) {
3880
3888
  if (!result) return null;
3881
3889
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
3882
3890
  }
3891
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
3892
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
3893
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
3894
+ if (!result) return null;
3895
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
3896
+ }
3883
3897
  const refResolveCache = {};
3884
3898
  const configForRefResolution = cfg ?? loadConfig();
3885
3899
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "../anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -17938,6 +17939,7 @@ async function refreshOAuthTokenWithLock(params) {
17938
17939
  profileId: params.profileId,
17939
17940
  store: params.store
17940
17941
  });
17942
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
17941
17943
  return await refreshUnmanagedOAuthTokenWithLock(params);
17942
17944
  }
17943
17945
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -17997,6 +17999,12 @@ async function tryResolveOAuthProfile(params) {
17997
17999
  if (!result) return null;
17998
18000
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
17999
18001
  }
18002
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18003
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18004
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18005
+ if (!result) return null;
18006
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18007
+ }
18000
18008
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
18001
18009
  provider: cred.provider,
18002
18010
  credentials: cred,
@@ -18065,6 +18073,12 @@ async function resolveApiKeyForProfile(params) {
18065
18073
  if (!result) return null;
18066
18074
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18067
18075
  }
18076
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18077
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18078
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18079
+ if (!result) return null;
18080
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18081
+ }
18068
18082
  const refResolveCache = {};
18069
18083
  const configForRefResolution = cfg ?? loadConfig();
18070
18084
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "../anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -17948,6 +17949,7 @@ async function refreshOAuthTokenWithLock(params) {
17948
17949
  profileId: params.profileId,
17949
17950
  store: params.store
17950
17951
  });
17952
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
17951
17953
  return await refreshUnmanagedOAuthTokenWithLock(params);
17952
17954
  }
17953
17955
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -18007,6 +18009,12 @@ async function tryResolveOAuthProfile(params) {
18007
18009
  if (!result) return null;
18008
18010
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18009
18011
  }
18012
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18013
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18014
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18015
+ if (!result) return null;
18016
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18017
+ }
18010
18018
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
18011
18019
  provider: cred.provider,
18012
18020
  credentials: cred,
@@ -18075,6 +18083,12 @@ async function resolveApiKeyForProfile(params) {
18075
18083
  if (!result) return null;
18076
18084
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18077
18085
  }
18086
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18087
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18088
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18089
+ if (!result) return null;
18090
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18091
+ }
18078
18092
  const refResolveCache = {};
18079
18093
  const configForRefResolution = cfg ?? loadConfig();
18080
18094
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "../anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -17955,6 +17956,7 @@ async function refreshOAuthTokenWithLock(params) {
17955
17956
  profileId: params.profileId,
17956
17957
  store: params.store
17957
17958
  });
17959
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
17958
17960
  return await refreshUnmanagedOAuthTokenWithLock(params);
17959
17961
  }
17960
17962
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -18014,6 +18016,12 @@ async function tryResolveOAuthProfile(params) {
18014
18016
  if (!result) return null;
18015
18017
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18016
18018
  }
18019
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18020
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18021
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18022
+ if (!result) return null;
18023
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18024
+ }
18017
18025
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
18018
18026
  provider: cred.provider,
18019
18027
  credentials: cred,
@@ -18082,6 +18090,12 @@ async function resolveApiKeyForProfile(params) {
18082
18090
  if (!result) return null;
18083
18091
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18084
18092
  }
18093
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18094
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18095
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18096
+ if (!result) return null;
18097
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18098
+ }
18085
18099
  const refResolveCache = {};
18086
18100
  const configForRefResolution = cfg ?? loadConfig();
18087
18101
  const refDefaults = configForRefResolution.secrets?.defaults;
@@ -1,4 +1,5 @@
1
1
  import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { refreshAnthropicProfile } from "../anthropic-oauth-refresh.js"; // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
2
3
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
3
4
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
4
5
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -17945,6 +17946,7 @@ async function refreshOAuthTokenWithLock(params) {
17945
17946
  profileId: params.profileId,
17946
17947
  store: params.store
17947
17948
  });
17949
+ if (cred?.provider === "anthropic" && cred.type === "oauth") return await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId: params.profileId, store: params.store }); // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95
17948
17950
  return await refreshUnmanagedOAuthTokenWithLock(params);
17949
17951
  }
17950
17952
  async function refreshUnmanagedOAuthTokenWithLock(params) {
@@ -18004,6 +18006,12 @@ async function tryResolveOAuthProfile(params) {
18004
18006
  if (!result) return null;
18005
18007
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18006
18008
  }
18009
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18010
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18011
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18012
+ if (!result) return null;
18013
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18014
+ }
18007
18015
  if (Date.now() < cred.expires) return buildOAuthProfileResult({
18008
18016
  provider: cred.provider,
18009
18017
  credentials: cred,
@@ -18072,6 +18080,12 @@ async function resolveApiKeyForProfile(params) {
18072
18080
  if (!result) return null;
18073
18081
  return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "openai-codex", email: result.newCredentials?.email ?? cred.email });
18074
18082
  }
18083
+ // JOHNNESS_PATCH_OAUTH_REFRESH_TIMER_95: same owner/lock/CAS as proactive refresh; local accounts never adopt main's login.
18084
+ if (cred.type === "oauth" && cred.provider === "anthropic") {
18085
+ const result = await refreshAnthropicProfile({ ...codexOwnershipContext(params.agentDir), log: undefined, profileId, store });
18086
+ if (!result) return null;
18087
+ return buildApiKeyProfileResult({ apiKey: result.apiKey, provider: "anthropic", email: result.newCredentials?.email ?? cred.email });
18088
+ }
18075
18089
  const refResolveCache = {};
18076
18090
  const configForRefResolution = cfg ?? loadConfig();
18077
18091
  const refDefaults = configForRefResolution.secrets?.defaults;
package/docs/PATCHES.md CHANGED
@@ -3170,3 +3170,41 @@ Verifier 94.current executes single/multi/masked edits offline. 94.future regene
3170
3170
  newer numeric version and higher quality, then executes that generated tool. It excludes newer paid
3171
3171
  and Flare siblings and leaves no files in the tested package. See tests/image-edit-defaults.test.mjs.
3172
3172
  Rollback: npm i -g johns-harness@2026.11.5. No activation or gateway restart is part of publication.
3173
+
3174
+ ## Family 95: Proactive subscription OAuth refresh (2026.11.7)
3175
+
3176
+ John's requirement: a gateway timer, not lazy-only renewal. Both gateway bundles now run an
3177
+ immediate startup sweep, then check every five minutes and refresh within one hour of expiry.
3178
+ The unref'd timer is gateway-owned and drained on shutdown (no external cron or daemon).
3179
+ Configured custom agent directories and the main credential owner are included. Missing,
3180
+ API-key-only and refreshless legacy profiles do not cause requests.
3181
+
3182
+ Anthropic now has one shared refresh implementation for the timer and all ten bundled lazy
3183
+ resolvers. It uses the existing transaction primitives: per-owner process queue and cross-process
3184
+ lock, durable reread after locking, generation compare-and-swap, fsync/atomic rename and 0600
3185
+ files. Inherited profiles share the main owner; distinct local logins never adopt main's account.
3186
+ Duplicated refresh-token aliases/owners fail closed instead of spending a cloned rotating token.
3187
+ Snapshot saves preserve on-disk Anthropic credentials (as they already did for Codex), so a late
3188
+ metadata write cannot restore an expired token or resurrect a removed login. A response that
3189
+ cannot be persisted is retained in-process for write retry without another token exchange.
3190
+
3191
+ Anthropic failures persist generation-bound exponential backoff: 1, 2, 4, 8, then 15 minutes,
3192
+ plus bounded jitter, honoring Retry-After. New logins bypass stale backoff. Successful refresh
3193
+ publishes the Family 89 runtime auth snapshot; unsuccessful snapshot publication is retried by
3194
+ the timer. The Family 92 served-profile and paid API fallback reason remain unchanged. Logs
3195
+ contain only whitelisted outcomes, provider and timing, not tokens, response bodies or IDs.
3196
+ Codex gets the same early scheduling via the existing Family 58 owner; its fail-closed handling
3197
+ of ambiguous/reused refresh tokens is intentionally unchanged.
3198
+
3199
+ Proof: offline focused tests cover startup/idle refresh, retry/backoff, 429, concurrent timer/lazy
3200
+ and separate-process refresh, owner isolation, concurrent login/logout, stale snapshot saves,
3201
+ Codex reuse and timer cleanup. An isolated real gateway with fake credentials, a loopback OAuth
3202
+ and inference endpoint, and external network blocked refreshed before any model request; its
3203
+ already-running session remained `oauth (anthropic:subscription)` after an idle retry/rotation.
3204
+ No live token was read, copied or rotated, no inference was billed, and the live gateway was not
3205
+ restarted. An unavailable provider, revoked login or persistent storage failure still requires
3206
+ recovery; this is early renewal and retries, not a guarantee against external outages.
3207
+
3208
+ Replay: scripts/patch-oauth-refresh-timer-95.py + patches/oauth-refresh-timer-95/changes.json.
3209
+ Older replays strip and re-layer exact reviewed hunks, never accept arbitrary new bundle hashes.
3210
+ Activation: /update. Rollback: npm i -g johns-harness@2026.11.6.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "johns-harness",
3
- "version": "2026.11.6",
3
+ "version": "2026.11.7",
4
4
  "description": "John's Harness: a production agent harness that runs autonomous coding agents as one cooperative swarm.",
5
5
  "keywords": [
6
6
  "ai-agents",