johns-harness 2026.11.5 → 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,31 @@
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
+
10
+ ## 2026.11.6
11
+
12
+ ### Latest Sunburst edits, highest requested quality
13
+ - Default image edits now request the newest subscription Sunburst at its highest supported rendering quality: currently `gpt-image-2.6-sunburst` / `max`. Single-image, multi-image and masked edits share the same path. Explicit tool/config model and explicit quality overrides, including `auto`, remain exact. Generation quality defaults are unchanged.
14
+ - Move `image`, `image-sunburst` and `image-flare` into numeric latest-family rules in the master. The master default primary now references `image`; sync resolves it for the shipped runtime. Registering a newer model moves generation and editing together. Preserve versioned aliases and the subscription-only 2.5 Sunburst then GPT Image2 fallbacks. No implicit paid OpenAI API fallback.
15
+ - Select implicit quality per candidate: 2.6/2.5 use max; legacy Image2 uses high. Explicit max is never silently lowered for an incompatible fallback. Configured model aliases now resolve before candidate selection. Master validation rejects implicit paid or non-editable image defaults.
16
+
17
+ ### Fix the subscription edit transport
18
+ - Real testing found that the previous multipart request fails on Codex `/images/edits` with HTTP400 Unsupported content type. Use the native JSON `images: [{image_url: dataURL}]` and optional `mask: {image_url: dataURL}` shape instead. Keep explicit OpenAI API multipart editing unchanged. Input MIME types are sniffed from bytes. No file upload or API billing workaround.
19
+ - Three real subscription edits succeeded: omitted-quality max, explicit-high diagnostic, and omitted-quality max with a PNG mask. Every request used exact `gpt-image-2.6-sunburst` on `chatgpt.com/backend-api/codex/images/edits`, with no fallback. **Provider caveat:** all three accepted the requested quality but reported `quality: low`; all returned 1254x1254 (the input size), not requested 1024x1024. Max is the correct requested model quality, but these responses do not prove max rendering. High showed the same deviation, so silently reducing the default would not solve it.
20
+ - Tool details expose requested `quality`, `responseQuality`, `responseSize` and a visible quality-disagreement warning. No provider downgrade is silently presented as verified max output.
21
+ - Add executable release guards for the actual single/multiple/masked tool path and a regenerated future-version fixture, including numeric latest selection, a new highest quality, paid/Flare exclusion, fallback quality, explicit overrides and transport bytes. No live credentials or inference in automated tests. Verifier: **580/580**. Full suite: **1,335 passed, zero failed/cancelled, 5 existing skips** (1,340 tests), including 22 new regressions.
22
+
23
+ Transport sources checked 2026-11-05:
24
+ - https://github.com/openai/codex/blob/main/codex-rs/codex-api/src/endpoint/images.rs
25
+ - https://developers.openai.com/api/reference/resources/images/methods/edit
26
+
27
+ Rollback: `npm i -g johns-harness@2026.11.5`. John runs `/update` when ready; this release does not install or restart the running gateway.
28
+
3
29
  ## 2026.11.5
4
30
 
5
31
  ### GPT Image 2.6 Sunburst and Flare
package/README.md CHANGED
@@ -60,7 +60,7 @@ In a terminal, run `johnness login` to list choices, `johnness login chatgpt` or
60
60
 
61
61
  <!-- JOHNNESS_PATCH_DEFAULTS_61 -->
62
62
  ### Batteries included
63
- The harness ships the current model catalog and the short aliases `opus`, `sonnet`, `fable`, `astra`, `sol`, `luna`, `terra`, `gpt`, `grok`, `flash`, `banana`, `image`, `deepseek`, `deepseek-pro`, `muse`, and `gemini-lite`, so `/model opus` works on a fresh install with no `models.providers` block. Channels you configure load without a `plugins.allow` list; only an explicit `enabled: false` or `plugins.deny` turns one off. Updating the harness updates the catalog and aliases for every agent. Any `openai-codex/<model>` primary that hits its ChatGPT usage limit fails over to `openai/<model>` on the API key first, then to your configured fallbacks, with no config (the sibling is skipped when no OpenAI API key is present). Image generation and editing go through the `image_generate` tool. The default chain is subscription only: GPT Image 2.5 Sunburst (`openai-codex/gpt-image-2.5-sunburst`, alias `image`) on the ChatGPT subscription, then GPT Image 2 on the subscription (`image2`); API-key image models are never an implicit fallback, only an explicit `model` or `agents.defaults.imageGenerationModel`. Also selectable: GPT Image 2.5 Flare (`image-flare`), Nano Banana 2.1 (`google/gemini-nano-banana-2.1`, `nano-banana`/`banana`, `aspectRatio`, `imageSize` 1K/2K/4K, up to 14 reference images), Nano Banana Pro GA (`google/gemini-3-pro-image`, `nano-banana-pro`; the preview stays on `nano-banana-pro-preview`), Nano Banana 2 Lite (`nano-banana-lite`, 1K only) and xAI Grok Imagine Image 2.0 (`grok-image`, native xAI JSON generation and editing). GPT Image 2.5 adds `quality` `xhigh`/`max` and custom sizes; per-model rules come from `models/models.json`.
63
+ The harness ships the current model catalog and the short aliases `opus`, `sonnet`, `fable`, `astra`, `sol`, `luna`, `terra`, `gpt`, `grok`, `flash`, `banana`, `image`, `deepseek`, `deepseek-pro`, `muse`, and `gemini-lite`, so `/model opus` works on a fresh install with no `models.providers` block. Channels you configure load without a `plugins.allow` list; only an explicit `enabled: false` or `plugins.deny` turns one off. Updating the harness updates the catalog and aliases for every agent. Any `openai-codex/<model>` primary that hits its ChatGPT usage limit fails over to `openai/<model>` on the API key first, then to your configured fallbacks, with no config (the sibling is skipped when no OpenAI API key is present). Image generation and editing go through the `image_generate` tool. The default chain is subscription only: the latest GPT Image Sunburst (currently `openai-codex/gpt-image-2.6-sunburst`, alias `image`), then 2.5 Sunburst, then GPT Image 2 (`image2`); API-key image models are never an implicit fallback, only an explicit `model` or `agents.defaults.imageGenerationModel`. Also selectable: GPT Image 2.6 Flare (`image-flare`), with 2.5 retained as `image-sunburst25` / `image-flare25`, Nano Banana 2.1 (`google/gemini-nano-banana-2.1`, `nano-banana`/`banana`, `aspectRatio`, `imageSize` 1K/2K/4K, up to 14 reference images), Nano Banana Pro GA (`google/gemini-3-pro-image`, `nano-banana-pro`; the preview stays on `nano-banana-pro-preview`), Nano Banana 2 Lite (`nano-banana-lite`, 1K only) and xAI Grok Imagine Image 2.0 (`grok-image`, native xAI JSON generation and editing). GPT Image 2.5 adds `quality` `xhigh`/`max` and custom sizes; per-model rules come from `models/models.json`. Image edits request the highest quality for the actual GPT candidate (`max` on 2.6/2.5, `high` on Image2); explicit model/config/quality overrides remain exact, and generation quality is unchanged. Latest-family master rules move generation and editing together. Codex edits use JSON image/mask references rather than multipart. Tool output warns when the provider reports a different quality: live max and high requests currently report low, so the harness does not claim verified max rendering.
64
64
 
65
65
  **The alias contract.** Every shipped alias points at the newest model in its line, so an install or an `/update` moves every agent forward with zero per-instance config. Your own `agents.defaults.models[*].alias` entries are still consulted first and still win. Every catalog bump must move the matching alias; the verifier fails the release if it does not. `/model deepseek` always selects the newest DeepSeek model (currently V4.1 Flash); `deepseek-pro` the newest Pro.
66
66
 
@@ -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";
@@ -5161,7 +5162,7 @@ Object.assign(DEFAULT_MODEL_ALIASES, {
5161
5162
  grok46: "xai/grok-4.6"
5162
5163
  });
5163
5164
  /* JOHNNESS_MODELS_MASTER:BEGIN aliases (generated from models/models.json by scripts/models-sync.mjs; edit the master, not this block) */
5164
- const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
5165
+ const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
5165
5166
  for (const [alias, ref] of Object.entries(JOHNNESS_MASTER_ALIASES)) DEFAULT_MODEL_ALIASES[alias] = ref;
5166
5167
  /* JOHNNESS_MODELS_MASTER:END */
5167
5168
  const DEFAULT_MODEL_COST = {
@@ -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);
@@ -1852,7 +1852,7 @@ Object.assign(DEFAULT_MODEL_ALIASES, {
1852
1852
  grok46: "xai/grok-4.6"
1853
1853
  });
1854
1854
  /* JOHNNESS_MODELS_MASTER:BEGIN aliases (generated from models/models.json by scripts/models-sync.mjs; edit the master, not this block) */
1855
- const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
1855
+ const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
1856
1856
  for (const [alias, ref] of Object.entries(JOHNNESS_MASTER_ALIASES)) DEFAULT_MODEL_ALIASES[alias] = ref;
1857
1857
  /* JOHNNESS_MODELS_MASTER:END */
1858
1858
  const DEFAULT_MODEL_COST = {
@@ -5004,7 +5004,7 @@ Object.assign(DEFAULT_MODEL_ALIASES, {
5004
5004
  grok46: "xai/grok-4.6"
5005
5005
  });
5006
5006
  /* JOHNNESS_MODELS_MASTER:BEGIN aliases (generated from models/models.json by scripts/models-sync.mjs; edit the master, not this block) */
5007
- const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
5007
+ const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
5008
5008
  for (const [alias, ref] of Object.entries(JOHNNESS_MASTER_ALIASES)) DEFAULT_MODEL_ALIASES[alias] = ref;
5009
5009
  /* JOHNNESS_MODELS_MASTER:END */
5010
5010
  const DEFAULT_MODEL_COST = {
@@ -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 },
@@ -63,7 +63,7 @@ const IMAGE_MODEL_ALIAS_TABLE = {
63
63
  "gpt-image-2": "openai-codex/gpt-image-2",
64
64
  };
65
65
  /* JOHNNESS_MODELS_MASTER:BEGIN image aliases (generated from models/models.json by scripts/models-sync.mjs; edit the master, not this block) */
66
- for (const [alias, ref] of Object.entries({"banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2"})) IMAGE_MODEL_ALIAS_TABLE[alias] = ref;
66
+ for (const [alias, ref] of Object.entries({"banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare"})) IMAGE_MODEL_ALIAS_TABLE[alias] = ref;
67
67
  /* JOHNNESS_MODELS_MASTER:END */
68
68
  export const IMAGE_MODEL_ALIASES = Object.freeze(IMAGE_MODEL_ALIAS_TABLE);
69
69
 
@@ -91,7 +91,8 @@ export function coerceImageGenerationModelConfig(cfg) {
91
91
  export function listImageGenerationCandidates(cfg) {
92
92
  const { primary, fallbacks } = coerceImageGenerationModelConfig(cfg);
93
93
  const out = [];
94
- for (const ref of [primary, ...fallbacks]) {
94
+ for (const raw of [primary, ...fallbacks]) {
95
+ const ref = resolveImageModelRef(raw);
95
96
  if (!ref || out.some((c) => c.ref === ref)) continue;
96
97
  const slash = ref.indexOf("/");
97
98
  if (slash <= 0) continue;
@@ -187,6 +188,15 @@ export function extensionForMimeType(mimeType) {
187
188
 
188
189
  export function imageRulesFor(ref) { return IMAGE_MODEL_RULES[ref] ?? {}; }
189
190
 
191
+ /** GPT edit quality is resolved per candidate, never baked into caller params. The master lists
192
+ * qualities lowest to highest; auto is provider choice, not the highest rendering quality.
193
+ * Legacy GPT Image models without explicit rules retain their low/medium/high/auto ladder. */
194
+ export function defaultImageEditQuality(ref) {
195
+ if (!/^(openai|openai-codex)\//.test(ref)) return undefined;
196
+ const qualities = imageRulesFor(ref).qualities ?? ["low", "medium", "high", "auto"];
197
+ return qualities.findLast(quality => quality !== "auto");
198
+ }
199
+
190
200
  /** Image MIME type from the magic bytes (PNG, JPEG, WebP, GIF); `fallback` when unrecognised.
191
201
  * xAI rejects a data URI whose declared type disagrees with its bytes ("Invalid base64-encoded image"),
192
202
  * and xAI/Gemini return JPEG, so neither the request nor the written extension trusts a label alone. */
@@ -289,6 +299,12 @@ async function callProvider({ candidate, apiKey, params, images, mask, fetchImpl
289
299
  headers["content-type"] = "application/json";
290
300
  const sources = images.map(img => ({ url: `data:${sniffImageMimeType(img.buffer, img.mimeType)};base64,${Buffer.from(img.buffer).toString("base64")}`, type: "image_url" }));
291
301
  body = JSON.stringify({ model: candidate.model, prompt: params.prompt, n: params.count, response_format: "b64_json", quality: params.quality ?? "auto", resolution: (params.imageSize ?? "1K").toLowerCase(), ...(params.aspectRatio ? { aspect_ratio: params.aspectRatio } : {}), ...(sources.length === 1 ? { image: sources[0] } : sources.length > 1 ? { images: sources } : {}) });
302
+ } else if (edit && candidate.provider === "openai-codex") {
303
+ // Codex Images edits require JSON references. Multipart returns HTTP400 Unsupported content type.
304
+ // Inline local bytes, including mask, without file uploads or any paid API call.
305
+ headers["content-type"] = "application/json";
306
+ const inline = img => ({ image_url: `data:${sniffImageMimeType(img.buffer, img.mimeType)};base64,${Buffer.from(img.buffer).toString("base64")}` });
307
+ body = JSON.stringify({ model: candidate.model, prompt: params.prompt, n: params.count, images: images.map(inline), ...(mask ? { mask: inline(mask) } : {}), ...(params.size !== "auto" ? { size: params.size } : {}), ...(params.quality ? { quality: params.quality } : {}) });
292
308
  } else if (edit) {
293
309
  body = new FormData();
294
310
  body.set("model", candidate.model);
@@ -325,7 +341,7 @@ async function callProvider({ candidate, apiKey, params, images, mask, fetchImpl
325
341
  }
326
342
  }
327
343
  if (buffers.length === 0) throw new Error(`${candidate.provider}: response carried no image data`);
328
- return { buffers, usage: json?.usage ?? null, mode: edit ? "edit" : "generate", mimeType: sniffImageMimeType(buffers[0], typeof data[0]?.mime_type === "string" ? data[0].mime_type : "image/png") };
344
+ return { buffers, usage: json?.usage ?? null, responseQuality: json?.quality ?? null, responseSize: json?.size ?? null, mode: edit ? "edit" : "generate", mimeType: sniffImageMimeType(buffers[0], typeof data[0]?.mime_type === "string" ? data[0].mime_type : "image/png") };
329
345
  }
330
346
 
331
347
  /**
@@ -355,8 +371,11 @@ export async function generateWithFallback({ cfg, params, images, mask, resolveA
355
371
  continue;
356
372
  }
357
373
  try {
374
+ // Resolve only an omitted edit quality, after selecting this candidate. Explicit auto/low/max
375
+ // remain exact. A legacy fallback can use its own high without inheriting implicit max.
376
+ if (images.length > 0 && perCandidate.quality === undefined) perCandidate.quality = defaultImageEditQuality(candidate.ref);
358
377
  const result = await callProvider({ candidate, apiKey, params: perCandidate, images, mask, fetchImpl, userAgent });
359
- return { provider: candidate.provider, model: candidate.model, ...result, attempts };
378
+ return { provider: candidate.provider, model: candidate.model, quality: perCandidate.quality ?? null, ...result, attempts };
360
379
  } catch (error) {
361
380
  if (error instanceof ProviderUnsupported) {
362
381
  attempts.push({ provider: candidate.provider, skipped: error.message });
@@ -383,7 +402,7 @@ export function createImageGenerateTool(options, deps) {
383
402
  return {
384
403
  label: "Image Generate",
385
404
  name: "image_generate",
386
- description: "Generate or edit PNG images with GPT Image 2.6 (subscription Sunburst default, subscription 2.5 Sunburst then GPT Image 2 fallbacks), xAI Grok Imagine 2.0 (grok-image), Nano Banana 2.1 (nano-banana), Nano Banana Pro (nano-banana-pro) or Lite (nano-banana-lite). Give a prompt; add image (or images, up to 4, up to5 with xAI, or up to14 with Nano Banana) to edit, and an optional mask PNG. Writes image files under the workspace media/generated folder and returns their paths; send them with the message tool.",
405
+ description: "Generate or edit PNG images with the latest GPT Image Sunburst (subscription default, subscription 2.5 Sunburst then GPT Image 2 fallbacks). GPT edits default to the highest supported quality (currently max); explicit model and quality override the defaults. Also supports xAI Grok Imagine 2.0 (grok-image), Nano Banana 2.1 (nano-banana), Nano Banana Pro (nano-banana-pro) or Lite (nano-banana-lite). Give a prompt; add image (or images, up to 4, up to5 with xAI, or up to14 with Nano Banana) to edit, and an optional mask PNG. Writes image files under the workspace media/generated folder and returns their paths; send them with the message tool.",
387
406
  parameters: Type.Object({
388
407
  prompt: Type.String({ description: "What to draw or how to change the input image." }),
389
408
  image: Type.Optional(Type.String({ description: "Input image path to edit (workspace or allowed local root)." })),
@@ -391,7 +410,7 @@ export function createImageGenerateTool(options, deps) {
391
410
  mask: Type.Optional(Type.String({ description: "PNG mask path; transparent areas are edited." })),
392
411
  size: Type.Optional(Type.String({ description: "1024x1024, 1536x1024, 1024x1536, auto, or GPT Image2.5 custom size: multiples of16, ratio<=3, edges<=3840, pixels655360..8294400." })),
393
412
  count: Type.Optional(Type.Number({ description: "Number of images, 1..4 (default 1)." })),
394
- quality: Type.Optional(Type.String({ description: "GPT Image2.6/2.5: low, medium, high, xhigh, max, auto. Rendering quality, not planning complexity. Older GPT Image: low/medium/high/auto. xAI: low/medium/auto." })),
413
+ quality: Type.Optional(Type.String({ description: "GPT Image2.6/2.5: low, medium, high, xhigh, max, auto. GPT edits default to the highest supported quality (max on 2.6/2.5, high on older GPT Image); explicit auto uses provider choice. Generation quality is unchanged. Rendering quality, not planning complexity. Older GPT Image: low/medium/high/auto. xAI: low/medium/auto." })),
395
414
  output: Type.Optional(Type.String({ description: "Output path inside the workspace (default media/generated/gpt-image-<timestamp>.png)." })),
396
415
  model: Type.Optional(Type.String({ description: "Override provider/model, for example openai/gpt-image-2, or an alias: nano-banana or banana (Nano Banana 2.1), nano-banana-pro (GA Pro), nano-banana-pro-preview, nano-banana-lite, grok-image, image/image-sunburst (subscription Sunburst), image-flare, image2 (older subscription)." })),
397
416
  aspectRatio: Type.Optional(Type.String({ description: "Google/xAI: 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, or 21:9; Nano Banana 2.1 also takes 1:4, 4:1, 1:8 and 8:1. Ignored by the GPT Image 2 providers." })),
@@ -434,10 +453,11 @@ export function createImageGenerateTool(options, deps) {
434
453
  written.push(outputs[i]);
435
454
  }
436
455
  const served = `${result.provider}/${result.model}`;
437
- const text = [`${result.mode === "edit" ? "Edited" : "Generated"} ${written.length} image${written.length === 1 ? "" : "s"} with ${served}.`, ...written.map((p) => `MEDIA:${p}`)].join("\n");
456
+ const qualityWarning = result.quality && result.quality !== "auto" && result.responseQuality && result.responseQuality !== result.quality ? `Provider reported quality ${result.responseQuality} instead of requested ${result.quality}.` : null;
457
+ const text = [`${result.mode === "edit" ? "Edited" : "Generated"} ${written.length} image${written.length === 1 ? "" : "s"} with ${served}.`, ...(qualityWarning ? [qualityWarning] : []), ...written.map((p) => `MEDIA:${p}`)].join("\n");
438
458
  return {
439
459
  content: [{ type: "text", text }],
440
- details: { provider: result.provider, model: result.model, mode: result.mode, paths: written, usage: result.usage, attempts: result.attempts },
460
+ details: { provider: result.provider, model: result.model, quality: result.quality, responseQuality: result.responseQuality ?? null, responseSize: result.responseSize ?? null, qualityWarning, mode: result.mode, paths: written, usage: result.usage, attempts: result.attempts },
441
461
  };
442
462
  },
443
463
  };
@@ -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";
@@ -1713,7 +1714,7 @@ Object.assign(DEFAULT_MODEL_ALIASES, {
1713
1714
  grok46: "xai/grok-4.6"
1714
1715
  });
1715
1716
  /* JOHNNESS_MODELS_MASTER:BEGIN aliases (generated from models/models.json by scripts/models-sync.mjs; edit the master, not this block) */
1716
- const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
1717
+ const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
1717
1718
  for (const [alias, ref] of Object.entries(JOHNNESS_MASTER_ALIASES)) DEFAULT_MODEL_ALIASES[alias] = ref;
1718
1719
  /* JOHNNESS_MODELS_MASTER:END */
1719
1720
  const DEFAULT_MODEL_COST = {
@@ -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";
@@ -1688,7 +1689,7 @@ Object.assign(DEFAULT_MODEL_ALIASES, {
1688
1689
  grok46: "xai/grok-4.6"
1689
1690
  });
1690
1691
  /* JOHNNESS_MODELS_MASTER:BEGIN aliases (generated from models/models.json by scripts/models-sync.mjs; edit the master, not this block) */
1691
- const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
1692
+ const JOHNNESS_MASTER_ALIASES = {"deepseek":"deepseek/deepseek-flash","deepseek-pro":"deepseek/deepseek-v4-pro","gemini-lite":"google/gemini-3.5-flash-lite","muse":"meta/muse-spark-1.3","muse-spark":"meta/muse-spark-1.3","opus46":"anthropic/claude-opus-4-6","sonnet46":"anthropic/claude-sonnet-4-6","gpt-mini":"openai/gpt-5-mini","gemini":"google/gemini-4-argon","gemini31":"google/gemini-3.1-pro-preview","gemini-flash":"google/gemini-3.8-flash","gemini-flash-lite":"google/gemini-2.5-flash-lite","flash":"google/gemini-3.8-flash","banana":"google/gemini-nano-banana-2.1","nano-banana":"google/gemini-nano-banana-2.1","nano-banana-pro":"google/gemini-3-pro-image","nano-banana-pro-preview":"google/gemini-3-pro-image-preview","nano-banana-lite":"google/gemini-3.1-flash-lite-image","grok-image":"xai/grok-imagine-image-2.0","image-sunburst25":"openai-codex/gpt-image-2.5-sunburst","image-flare25":"openai-codex/gpt-image-2.5-flare","image2":"openai-codex/gpt-image-2","sonnet5":"anthropic/claude-sonnet-5","opus5":"anthropic/claude-opus-5","haiku45":"anthropic/claude-haiku-4-5","sol6":"openai-codex/gpt-6-sol","sol56":"openai-codex/gpt-5.6-sol","luna56":"openai-codex/gpt-5.6-luna","grok46":"xai/grok-4.6","terra56":"openai-codex/gpt-5.6-terra","image":"openai-codex/gpt-image-2.6-sunburst","image-sunburst":"openai-codex/gpt-image-2.6-sunburst","image-flare":"openai-codex/gpt-image-2.6-flare","opus":"anthropic/claude-opus-5-5","sonnet":"anthropic/claude-sonnet-5-5","fable":"anthropic/claude-fable-5-1","haiku":"anthropic/claude-haiku-5-5","gpt":"openai-codex/gpt-6.1-sol","sol":"openai-codex/gpt-6.1-sol","luna":"openai-codex/gpt-6-luna","astra":"openai-codex/gpt-6-astra","terra":"openai-codex/gpt-6.1-terra","grok":"xai/grok-4.7"};
1692
1693
  for (const [alias, ref] of Object.entries(JOHNNESS_MASTER_ALIASES)) DEFAULT_MODEL_ALIASES[alias] = ref;
1693
1694
  /* JOHNNESS_MODELS_MASTER:END */
1694
1695
  const DEFAULT_MODEL_COST = {
@@ -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;