johns-harness 2026.10.19 → 2026.10.21

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -1
  3. package/dist/auth-profiles-5CHn7vq1.js +7 -5
  4. package/dist/compact-B247y5Qt.js +14 -5
  5. package/dist/config-koj5M_EO.js +7 -5
  6. package/dist/daemon-cli.js +7 -5
  7. package/dist/gateway-cli-B7fBU7gD.js +13 -8
  8. package/dist/gateway-cli-BCNMwzNq.js +13 -8
  9. package/dist/model-selection-BGlGpPgM.js +7 -5
  10. package/dist/model-selection-BU6wl1le.js +7 -5
  11. package/dist/model-selection-L7RMwsG-.js +7 -5
  12. package/dist/pi-embedded-C6ITuRXf.js +14 -5
  13. package/dist/pi-embedded-DoQsYfIY.js +14 -5
  14. package/dist/plugin-sdk/config-4Fgm-yEH.js +7 -5
  15. package/dist/plugin-sdk/config-Di-lyCdh.js +7 -5
  16. package/dist/plugin-sdk/discord.js +7 -5
  17. package/dist/plugin-sdk/dispatch-BP0viZiL.js +14 -5
  18. package/dist/plugin-sdk/dispatch-CQsjmw7g.js +14 -5
  19. package/dist/plugin-sdk/dispatch-Cerq29sy.js +14 -5
  20. package/dist/plugin-sdk/dispatch-Cndjtt0g.js +14 -5
  21. package/dist/plugin-sdk/dispatch-UogiJYul.js +14 -5
  22. package/dist/plugin-sdk/model-auth-CX9cPHdC.js +7 -5
  23. package/dist/plugin-sdk/model-auth-Ciehz0x5.js +7 -5
  24. package/dist/plugin-sdk/model-auth-DVyo6JSX.js +7 -5
  25. package/dist/plugin-sdk/model-auth-kiHYHGrs.js +7 -5
  26. package/dist/plugin-sdk/model-selection-Dbj4jDYM.js +7 -5
  27. package/dist/plugin-sdk/reply-DbZnH8-h.js +14 -5
  28. package/dist/reply-C5LKjXcC.js +14 -5
  29. package/dist/subscription-login.js +19 -2
  30. package/docs/PATCHES.md +65 -1
  31. package/docs/concepts/session-pruning.md +1 -1
  32. package/docs/providers/anthropic.md +7 -4
  33. package/node_modules/@mariozechner/pi-ai/dist/providers/anthropic.js +24 -12
  34. package/package.json +1 -1
  35. package/vendor/patched-deps/@mariozechner/pi-ai/dist/providers/anthropic.js +24 -12
@@ -29358,7 +29358,9 @@ function resolveModelAuthLabel(params) {
29358
29358
  const providerKey = normalizeProviderId(resolvedProvider);
29359
29359
  const store = ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false });
29360
29360
  const profileOverride = params.sessionEntry?.authProfileOverride?.trim();
29361
- const candidates = [profileOverride, ...resolveAuthProfileOrder({
29361
+ // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: the profile that served the last turn comes first, so /status shows what ran.
29362
+ const profileServed = params.sessionEntry?.authProfileServed?.trim();
29363
+ const candidates = [profileServed, profileOverride, ...resolveAuthProfileOrder({
29362
29364
  cfg: params.cfg,
29363
29365
  store,
29364
29366
  provider: providerKey,
@@ -38367,6 +38369,7 @@ async function updateSessionStoreAfterAgentRun(params) {
38367
38369
  provider: providerUsed,
38368
38370
  model: modelUsed
38369
38371
  });
38372
+ if (result.meta.agentMeta?.authProfileId) next.authProfileServed = result.meta.agentMeta.authProfileId; // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
38370
38373
  if (isCliProvider(providerUsed, cfg)) {
38371
38374
  const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
38372
38375
  if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
@@ -83940,7 +83943,7 @@ function resolveExtraParams(params) {
83940
83943
  * OpenRouter uses openai-completions API with hardcoded cache_control instead
83941
83944
  * of the cacheRetention stream option.
83942
83945
  *
83943
- * Defaults to "short" for direct Anthropic when not explicitly configured.
83946
+ * JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: defaults to "long" for direct Anthropic (both auth modes).
83944
83947
  */
83945
83948
  function resolveCacheRetention(extraParams, provider) {
83946
83949
  const isAnthropicDirect = provider === "anthropic";
@@ -83952,10 +83955,12 @@ function resolveCacheRetention(extraParams, provider) {
83952
83955
  if (legacy === "5m") return "short";
83953
83956
  if (legacy === "1h") return "long";
83954
83957
  if (!isAnthropicDirect) return;
83955
- return "short";
83958
+ return "long";
83956
83959
  }
83957
83960
  function createStreamFnWithExtraParams(baseStreamFn, extraParams, provider) {
83958
- if (!extraParams || Object.keys(extraParams).length === 0) return;
83961
+ // JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: apply the Anthropic default even with no model params.
83962
+ if ((!extraParams || Object.keys(extraParams).length === 0) && provider !== "anthropic") return;
83963
+ extraParams ??= {};
83959
83964
  const streamParams = {};
83960
83965
  if (typeof extraParams.temperature === "number") streamParams.temperature = extraParams.temperature;
83961
83966
  if (typeof extraParams.maxTokens === "number") streamParams.maxTokens = extraParams.maxTokens;
@@ -90552,7 +90557,8 @@ async function runEmbeddedPiAgent(params) {
90552
90557
  usage,
90553
90558
  lastCallUsage: lastCallUsage ?? void 0,
90554
90559
  promptTokens,
90555
- compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0
90560
+ compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0,
90561
+ authProfileId: lastProfileId // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: profile that served this turn
90556
90562
  };
90557
90563
  const payloads = buildEmbeddedRunPayloads({
90558
90564
  assistantTexts: attempt.assistantTexts,
@@ -101489,6 +101495,7 @@ async function persistSessionUsageUpdate(params) {
101489
101495
  const patch = {
101490
101496
  modelProvider: params.providerUsed ?? entry.modelProvider,
101491
101497
  model: params.modelUsed ?? entry.model,
101498
+ authProfileServed: params.authProfileServed ?? entry.authProfileServed, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
101492
101499
  contextTokens: resolvedContextTokens,
101493
101500
  systemPromptReport: params.systemPromptReport ?? entry.systemPromptReport,
101494
101501
  updatedAt: Date.now()
@@ -101768,6 +101775,7 @@ function createFollowupRunner(params) {
101768
101775
  promptTokens,
101769
101776
  modelUsed,
101770
101777
  providerUsed: fallbackProvider,
101778
+ authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
101771
101779
  contextTokensUsed,
101772
101780
  systemPromptReport: runResult.meta?.systemPromptReport,
101773
101781
  logLabel: "followup"
@@ -102105,6 +102113,7 @@ async function runReplyAgent(params) {
102105
102113
  promptTokens,
102106
102114
  modelUsed,
102107
102115
  providerUsed,
102116
+ authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
102108
102117
  contextTokensUsed,
102109
102118
  systemPromptReport: runResult.meta?.systemPromptReport,
102110
102119
  cliSessionId
@@ -25814,7 +25814,9 @@ function resolveModelAuthLabel(params) {
25814
25814
  const providerKey = normalizeProviderId(resolvedProvider);
25815
25815
  const store = ensureAuthProfileStore(params.agentDir, { allowKeychainPrompt: false });
25816
25816
  const profileOverride = params.sessionEntry?.authProfileOverride?.trim();
25817
- const candidates = [profileOverride, ...resolveAuthProfileOrder({
25817
+ // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: the profile that served the last turn comes first, so /status shows what ran.
25818
+ const profileServed = params.sessionEntry?.authProfileServed?.trim();
25819
+ const candidates = [profileServed, profileOverride, ...resolveAuthProfileOrder({
25818
25820
  cfg: params.cfg,
25819
25821
  store,
25820
25822
  provider: providerKey,
@@ -32088,6 +32090,7 @@ async function updateSessionStoreAfterAgentRun(params) {
32088
32090
  provider: providerUsed,
32089
32091
  model: modelUsed
32090
32092
  });
32093
+ if (result.meta.agentMeta?.authProfileId) next.authProfileServed = result.meta.agentMeta.authProfileId; // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
32091
32094
  if (isCliProvider(providerUsed, cfg)) {
32092
32095
  const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
32093
32096
  if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
@@ -75959,7 +75962,7 @@ function resolveExtraParams(params) {
75959
75962
  * OpenRouter uses openai-completions API with hardcoded cache_control instead
75960
75963
  * of the cacheRetention stream option.
75961
75964
  *
75962
- * Defaults to "short" for direct Anthropic when not explicitly configured.
75965
+ * JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: defaults to "long" for direct Anthropic (both auth modes).
75963
75966
  */
75964
75967
  function resolveCacheRetention(extraParams, provider) {
75965
75968
  const isAnthropicDirect = provider === "anthropic";
@@ -75971,10 +75974,12 @@ function resolveCacheRetention(extraParams, provider) {
75971
75974
  if (legacy === "5m") return "short";
75972
75975
  if (legacy === "1h") return "long";
75973
75976
  if (!isAnthropicDirect) return;
75974
- return "short";
75977
+ return "long";
75975
75978
  }
75976
75979
  function createStreamFnWithExtraParams(baseStreamFn, extraParams, provider) {
75977
- if (!extraParams || Object.keys(extraParams).length === 0) return;
75980
+ // JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: apply the Anthropic default even with no model params.
75981
+ if ((!extraParams || Object.keys(extraParams).length === 0) && provider !== "anthropic") return;
75982
+ extraParams ??= {};
75978
75983
  const streamParams = {};
75979
75984
  if (typeof extraParams.temperature === "number") streamParams.temperature = extraParams.temperature;
75980
75985
  if (typeof extraParams.maxTokens === "number") streamParams.maxTokens = extraParams.maxTokens;
@@ -82729,7 +82734,8 @@ async function runEmbeddedPiAgent(params) {
82729
82734
  usage,
82730
82735
  lastCallUsage: lastCallUsage ?? void 0,
82731
82736
  promptTokens,
82732
- compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0
82737
+ compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0,
82738
+ authProfileId: lastProfileId // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: profile that served this turn
82733
82739
  };
82734
82740
  const payloads = buildEmbeddedRunPayloads({
82735
82741
  assistantTexts: attempt.assistantTexts,
@@ -93374,6 +93380,7 @@ async function persistSessionUsageUpdate(params) {
93374
93380
  const patch = {
93375
93381
  modelProvider: params.providerUsed ?? entry.modelProvider,
93376
93382
  model: params.modelUsed ?? entry.model,
93383
+ authProfileServed: params.authProfileServed ?? entry.authProfileServed, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
93377
93384
  contextTokens: resolvedContextTokens,
93378
93385
  systemPromptReport: params.systemPromptReport ?? entry.systemPromptReport,
93379
93386
  updatedAt: Date.now()
@@ -93653,6 +93660,7 @@ function createFollowupRunner(params) {
93653
93660
  promptTokens,
93654
93661
  modelUsed,
93655
93662
  providerUsed: fallbackProvider,
93663
+ authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
93656
93664
  contextTokensUsed,
93657
93665
  systemPromptReport: runResult.meta?.systemPromptReport,
93658
93666
  logLabel: "followup"
@@ -93990,6 +93998,7 @@ async function runReplyAgent(params) {
93990
93998
  promptTokens,
93991
93999
  modelUsed,
93992
94000
  providerUsed,
94001
+ authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
93993
94002
  contextTokensUsed,
93994
94003
  systemPromptReport: runResult.meta?.systemPromptReport,
93995
94004
  cliSessionId
@@ -1,4 +1,5 @@
1
1
  // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
2
+ // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: a successful login refreshes the running gateway's auth snapshot.
2
3
  // Native subscription dispatch. Credentials never go through the model or the config file.
3
4
  import os from 'node:os';
4
5
  import path from 'node:path';
@@ -40,8 +41,24 @@ export async function saveClaudeCredential(credential, options = {}) {
40
41
  store.order ??= {};
41
42
  store.order.anthropic = [...new Set([CLAUDE_PROFILE_ID, ...(store.order.anthropic ?? []), ...Object.keys(store.profiles).filter(id => store.profiles[id].provider === 'anthropic')])];
42
43
  });
44
+ await refreshRuntimeAuthStores(options);
43
45
  return { profileId: CLAUDE_PROFILE_ID };
44
46
  }
47
+ // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: the gateway serves turns from an in-memory auth snapshot taken at start, so a
48
+ // credential written to disk is invisible until that snapshot is replaced. In process (chat login)
49
+ // call the refresh the gateway registers; from the CLI ask the running gateway over secrets.reload.
50
+ // No gateway running is normal: the next start loads the store from disk.
51
+ export const AUTH_RUNTIME_REFRESH = Symbol.for('johnness.authRuntimeRefresh.v1');
52
+ export async function refreshRuntimeAuthStores(options = {}) {
53
+ const inProcess = options.refreshRuntime ?? globalThis[AUTH_RUNTIME_REFRESH];
54
+ try {
55
+ if (typeof inProcess === 'function') { await inProcess(); return 'in-process'; }
56
+ if (options.rpc === false) return 'skipped';
57
+ const call = options.callGateway ?? (await import('./gateway-rpc-DB8opYdF.js')).n;
58
+ await call('secrets.reload', { timeout: options.rpcTimeoutMs ?? 5000 }, undefined, { expectFinal: false, progress: false });
59
+ return 'rpc';
60
+ } catch { return 'unavailable'; }
61
+ }
45
62
 
46
63
  export async function startClaudeLogin(options = {}) {
47
64
  const login = options.login ?? (await import('@mariozechner/pi-ai/dist/utils/oauth/anthropic.js')).loginAnthropic;
@@ -81,7 +98,7 @@ export async function handleSubscriptionLoginCommand(params, allowTextCommands,
81
98
  if (!provider) return reply(LOGIN_OPTIONS);
82
99
  if (provider === 'chatgpt') {
83
100
  if (match[2]) return reply('Use /login chatgpt to get a ChatGPT device code.');
84
- const result = await (options.handleChatgpt ?? handleDeviceLoginCommand)({ ...params, command: { ...params.command, commandBodyNormalized: '/login' } }, allowTextCommands, options);
101
+ const result = await (options.handleChatgpt ?? handleDeviceLoginCommand)({ ...params, command: { ...params.command, commandBodyNormalized: '/login' } }, allowTextCommands, { hooks: { publish: () => refreshRuntimeAuthStores(options) }, ...options });
85
102
  if (result?.reply?.text) result.reply.text = result.reply.text.replace(/Send \/login\b/g, 'Send /login chatgpt');
86
103
  return result;
87
104
  }
@@ -122,7 +139,7 @@ export function openLoginBrowser(url) {
122
139
  export async function runSubscriptionLoginCli(provider, opts = {}, runtime = console, options = {}) {
123
140
  const selected = normalizeLoginProvider(provider);
124
141
  if (!selected) { runtime.log(LOGIN_OPTIONS.replaceAll('/login', 'johnness login')); return; }
125
- if (selected === 'chatgpt') return (options.runChatgpt ?? runDeviceLoginCli)({ ...opts, provider: 'openai-codex' }, runtime, options);
142
+ if (selected === 'chatgpt') return (options.runChatgpt ?? runDeviceLoginCli)({ ...opts, provider: 'openai-codex' }, runtime, { hooks: { publish: () => refreshRuntimeAuthStores(options) }, ...options });
126
143
  if (selected !== 'claude') throw new Error('Unknown subscription. Choose chatgpt (or gpt) or claude.');
127
144
  const session = await (options.startClaude ?? startClaudeLogin)(options);
128
145
  runtime.log(`Open this URL and sign in to your Claude subscription:\n${session.url}`);
package/docs/PATCHES.md CHANGED
@@ -17,7 +17,7 @@ they predate ~2026-06-06).
17
17
 
18
18
  ## Index
19
19
 
20
- Current addition: [88 - Subscription plan limits](#88---subscription-plan-limits-2026-10-20).
20
+ Current addition: [89 - Subscription activates on the next turn](#89---subscription-activates-on-the-next-turn-2026-10-20).
21
21
 
22
22
  Family 01 is retired. Families 02 through 41, 43 through 81, including the 65.1 amendment, are live on `main`; the `latest` and `extended` release lines converged at 2026.9.24. Family 42 is omitted; native Codex OAuth ownership is Family 58.
23
23
 
@@ -114,6 +114,7 @@ Family 01 is retired. Families 02 through 41, 43 through 81, including the 65.1
114
114
  86. **86, named subscription login:** `/login chatgpt` preserves ChatGPT device sign-in; `/login claude` adds current Claude Code OAuth, subscription-first auth, API fallback and credential-specific $0 accounting. [Details](#86---named-subscription-login-2026-10-20)
115
115
  87. **87, subscription failover:** current Claude Code user-agent floor (`claude-cli/2.1.304`) for subscription tokens, and Anthropic's extra-usage and version rejections rotate the subscription profile to the paid API key instead of ending the turn. [Details](#87---subscription-failover-2026-10-20)
116
116
  88. **88, subscription plan limits:** subscription turns carry Claude Code's attribution system block (first, uncached, `cc_entrypoint=sdk-cli`, Claude Code's own `cc_version` hash) and the Agent SDK identity line, so Anthropic serves the full harness prompt and tools from the plan's included limits instead of billing third-party extra usage. API-key requests are unchanged. [Details](#88---subscription-plan-limits-2026-10-20)
117
+ 89. **89, subscription activates on the next turn:** a subscription login (chat or CLI, Claude or ChatGPT) refreshes the gateway's in-memory runtime auth snapshot, in process or over `secrets.reload`, so the matching subscription serves the very next turn of every existing session with no reload, `/new` or restart. `/status` names the profile that actually served the last turn. [Details](#89---subscription-activates-on-the-next-turn-2026-10-20)
117
118
 
118
119
  ---
119
120
 
@@ -2999,3 +3000,66 @@ NO_REPLY, failed sends, block streaming, exact replay, idempotence and drift ref
2999
3000
  **Replay:** `patches/subscription-plan-limits-88/changes.json`, `scripts/patch-subscription-plan-limits-88.py` (`--check`, `--present-only`, `--dependency-only`, `--record`). `scripts/subscription_login_layer.py` and `tests/helpers/subscription-login-layer.mjs` strip and re-layer Family 88 with 86 and 87 so Families 67, 78, 81 and 82 keep exact replay. Verifier checks 88.1 to 88.6.
3000
3001
 
3001
3002
  **Tests:** `tests/subscription-plan-limits-88.test.mjs` (manifest coverage, hash algorithm against the captured real request, block order and cache placement through the real adapter's SSE path, hash follows the first user message, API-key request unchanged, idempotent replay and drift refusal, strip/re-layer), Family 36 and 87 tests updated for the new first block and user-agent. Rollback: `npm i -g johns-harness@2026.10.18`.
3003
+
3004
+ ## 89 - Subscription activates on the next turn (2026-10-20)
3005
+
3006
+ **Intent:** John's requirement: after `/login claude` or `/login chatgpt`, the matching subscription is used by default on the very next turn, in existing sessions too, with no manual step (no `johnness secrets reload`, no `/new`, no restart).
3007
+
3008
+ **Root cause:** the gateway serves turns from an in-memory runtime auth snapshot taken at start (Family 58's secrets runtime). A login writes `auth-profiles.json` atomically and correctly, but nothing replaced that snapshot, so the Family 86 picker never saw `anthropic:subscription` in the order and every turn kept running on the API key until a reload or restart. Reproduced in isolated state: save the credential, next turn still `x-api-key`; `secrets.reload`, next turn `Authorization: Bearer sk-ant-oat...`. The picker branch itself was never the problem.
3009
+
3010
+ **Change:**
3011
+ - `dist/subscription-login.js` exports `refreshRuntimeAuthStores(options)`. Inside the gateway (chat `/login`) it calls the hook the gateway registers on `globalThis[Symbol.for('johnness.authRuntimeRefresh.v1')]`; from a CLI process it dynamic-imports the gateway RPC client and sends `secrets.reload` with a 5-second deadline (`rpcTimeoutMs`); `rpc: false` skips it. It never throws: no gateway running is normal, the next start reads the store from disk. Return values `in-process`, `rpc`, `skipped`, `unavailable` are for tests and logs only.
3012
+ - `saveClaudeCredential` calls it after the store transaction commits. Both ChatGPT paths (chat `handleDeviceLoginCommand`, CLI `runDeviceLoginCli`) receive `hooks.publish`, which the Family 58 credential owner invokes after it writes, so the device login refreshes the same way in chat and from the CLI.
3013
+ - Both gateway bundles hoist the `createSecretsHandlers` reload closure to `reloadRuntimeSecrets`, register it on the global symbol at start and delete it on close.
3014
+ - Ten reply bundles: `agentMeta.authProfileId` carries the profile that served the run (`lastProfileId`), `persistSessionUsageUpdate` and `updateSessionStoreAfterAgentRun` store it as `authProfileServed`, and `resolveModelAuthLabel` (the `/status` card) reads `authProfileServed` first, then the override, then the order, so the card names what actually ran.
3015
+ - Picker (Family 86 `claudeSubscriptionOrder`): unchanged. The test proves the subscription-first branch fires once the snapshot is fresh and that an explicit user profile lock still wins.
3016
+
3017
+ **Replay:** `patches/subscription-activate-89/changes.json`, `scripts/patch-subscription-activate-89.py` (`--check` read-only, `--present-only`, `--record`), 13 files: login module (4 hunks), 2 gateway bundles (2 hunks each, identical), 10 reply bundles (6 hunks each, identical). Replayed from a clean checkout of c4c017b in a scratch worktree: all 13 files byte-identical to the shipped tree. `scripts/subscription_login_layer.py` and `tests/helpers/subscription-login-layer.mjs` strip and re-layer Family 89 with 86, 87 and 88; `scripts/patch-subscription-login-86.py` strips the 89 layer before comparing its pinned `dist/subscription-login.js` content and re-layers after a write, so 86 `--check` keeps passing; `tests/helpers/replay-family-67.mjs` replays 89 after 86, and the 65.1 historical reconstruction of the two gateway bundles replays 89 after 76 and 79. Verifier checks 89.1 to 89.8 (557 checks).
3018
+
3019
+ **Tests:** `tests/subscription-activate-89.test.mjs` (19 tests): manifest coverage and uniform hunks; picker trigger in all ten copies (auto override re-picks the subscription once the snapshot has it, user override never does); in-process, RPC and unavailable refresh paths never throw; Claude save refreshes after commit; both ChatGPT paths hand `hooks.publish` to the owner; status label prefers the served profile across all ten copies; idempotent replay, drift refusal before any writes, read-only check; strip and re-layer with 86, 87, 88; and an end-to-end run: an isolated gateway on a free port (never 18789) in a `/tmp` state dir with a mock Anthropic SSE endpoint, turn one on `agent:main:main` served with `x-api-key`, then a control save with the refresh off (next turn still `x-api-key`, the live bug), then the real save in a separate process (the CLI shape), and the very next turn of the same session id served with `Authorization: Bearer sk-ant-oat-...` and `authProfileServed: anthropic:subscription` in `sessions.json`. Rollback: `npm i -g johns-harness@2026.10.19`.
3020
+
3021
+ ## 90. Direct Anthropic defaults to a one-hour prompt cache (2026-10-20)
3022
+
3023
+ **Why:** the five-minute default rewrote a large stable prompt after normal gaps between turns. A
3024
+ 250k-token context repeatedly incurred cold cache writes instead of cheap reads. Make the useful
3025
+ cache lifetime the default, without requiring per-model configuration, for API keys and subscriptions.
3026
+
3027
+ **Changes:**
3028
+ - All ten `resolveCacheRetention` copies default direct `anthropic` to `long`. Explicit
3029
+ `none`/`short`/`long` and legacy `cacheControlTtl` mappings still win. The stream wrapper applies
3030
+ the default even if model params are absent or empty.
3031
+ - All fourteen smart-default config loaders seed `long` for direct Anthropic instead of masking
3032
+ the runtime default with `short`. Legacy direct Anthropic TTLs are not overwritten. Claude on
3033
+ Bedrock retains its `short` smart default, and non-Anthropic Bedrock behavior is unchanged.
3034
+ - The vendored and installed pi-ai adapter defaults direct Anthropic to `long` and sends the
3035
+ existing `{ type: "ephemeral", ttl: "1h" }` breakpoints on the Anthropic API endpoint for both
3036
+ auth paths. It adds `extended-cache-ttl-2025-04-11` after header merging, so an explicit beta header
3037
+ cannot accidentally drop it. Other providers, explicit cache choices and custom-endpoint TTL
3038
+ behavior stay unchanged.
3039
+ - Family 36 system splitting and Family 88 attribution are intact: stable prefix cached, volatile
3040
+ memory tail uncached, subscription attribution first and uncached. Subscription accounting is $0.
3041
+
3042
+ **Claude Code evidence:** the Family 88 capture from 2.1.292 used ephemeral controls (one optional
3043
+ `scope: "global"`), without a TTL on that API-key request. The 2.1.304 binary's `Obe` selector returns
3044
+ `{ttl:"1h", reason:"subscriber"}` for eligible subscriber turns; `e5` emits `type:"ephemeral"`,
3045
+ optional `ttl`, and optional global scope. The harness uses the same one-hour shape without claiming
3046
+ that its private instructions are globally shareable. No Family 88 attribution changes are needed.
3047
+
3048
+ **Replay:** `scripts/patch-anthropic-cache-long-90.py [root] [--check|--present-only|--dependency-only]`,
3049
+ exact reviewed manifest `patches/anthropic-cache-long-90/changes.json`. All targets preflight before
3050
+ writes. Historical hash-pinned families strip/re-layer 90 with 86 to 89; fixture replay adds it last.
3051
+
3052
+ **Tests:** `tests/anthropic-cache-long-90.test.mjs`, 36 tests across every runtime and config copy,
3053
+ real-adapter SSE wire assertions for both auth paths and each retention mode, legacy mappings,
3054
+ empty params, header merging, stable/volatile breakpoints, Bedrock unchanged, drift rejection and
3055
+ historical layer round trips. Verifier checks 90.1 to 90.7.
3056
+
3057
+ **Live proof:** `plans/archive/2026-10-20-anthropic-cache-long-90.md`. Real isolated Sonnet 5.5
3058
+ gateway sessions with no cache configuration: API read/write 0/31,332 then 31,332/61 after 387s;
3059
+ subscription 0/31,407 then 31,407/61 after 369s. Both subscription responses HTTP 200,
3060
+ `anthropic-ratelimit-unified-5h-status: allowed`, overage rejected (extra usage disabled). Both
3061
+ paths report cache creation exclusively under `ephemeral_1h`. The initial subscription attempt hit
3062
+ the already-exhausted five-hour limit; the successful proof waited for its reset header. No live
3063
+ gateway restart, live state access or new login. Verifier 564/564; full suite 1,249 pass, 5 existing skips.
3064
+
3065
+ **Rollback:** `npm i -g johns-harness@2026.10.20`.
@@ -21,7 +21,7 @@ Session pruning trims **old tool results** from the in-memory context right befo
21
21
  ## Smart defaults (Anthropic)
22
22
 
23
23
  - **OAuth or setup-token** profiles: enable `cache-ttl` pruning and set heartbeat to `1h`.
24
- - **API key** profiles: enable `cache-ttl` pruning, set heartbeat to `30m`, and default `cacheRetention: "short"` on Anthropic models.
24
+ - **API key** profiles: enable `cache-ttl` pruning, set heartbeat to `30m`, and default `cacheRetention: "long"` on direct Anthropic models (Claude-on-Bedrock keeps `short`).
25
25
  - If you set any of these values explicitly, Johnness does **not** override them.
26
26
 
27
27
  ## What this improves (cost + cache behavior)
@@ -46,7 +46,7 @@ johnness onboard --anthropic-api-key "$ANTHROPIC_API_KEY"
46
46
 
47
47
  ## Prompt caching (Anthropic API)
48
48
 
49
- Johnness supports Anthropic's prompt caching feature. This is **API-only**; subscription auth does not honor cache settings.
49
+ Johnness supports Anthropic prompt caching with **both API-key and Claude subscription authentication**. Direct Anthropic requests default to a one-hour cache; no model configuration is required.
50
50
 
51
51
  ### Configuration
52
52
 
@@ -74,7 +74,11 @@ Use the `cacheRetention` parameter in your model config:
74
74
 
75
75
  ### Defaults
76
76
 
77
- When using Anthropic API Key authentication, Johnness automatically applies `cacheRetention: "short"` (5-minute cache) for all Anthropic models. You can override this by explicitly setting `cacheRetention` in your config.
77
+ For the direct `anthropic` provider, Johnness defaults to `cacheRetention: "long"` (1 hour) for both API-key and subscription requests, including models with no `params` entry. Explicit `none`, `short` and `long` values take priority, as does the legacy `cacheControlTtl` mapping when `cacheRetention` is absent.
78
+
79
+ On the Anthropic API endpoint, long retention sends `cache_control: { type: "ephemeral", ttl: "1h" }` at the existing cache breakpoints and adds `extended-cache-ttl-2025-04-11` to the beta header. The subscription envelope stays intact: the attribution block remains first and uncached, and changing memory context stays outside the stable system breakpoint. Custom proxy endpoints retain the adapter's existing TTL behavior.
80
+
81
+ One-hour API cache writes cost more than five-minute writes, but avoid rewriting the entire cached prefix after gaps longer than five minutes. Set `short` or `none` explicitly if that better fits your workload. Subscription requests keep subscription accounting and plan-limit routing; cache retention does not turn on extra usage.
78
82
 
79
83
  ### Per-agent cacheRetention overrides
80
84
 
@@ -121,8 +125,7 @@ The older `cacheControlTtl` parameter is still supported for backwards compatibi
121
125
 
122
126
  We recommend migrating to the new `cacheRetention` parameter.
123
127
 
124
- Johnness includes the `extended-cache-ttl-2025-04-11` beta flag for Anthropic API
125
- requests; keep it if you override provider headers (see [/gateway/configuration](/gateway/configuration)).
128
+ Johnness adds the `extended-cache-ttl-2025-04-11` beta flag whenever it sends a one-hour TTL, for both API-key and subscription requests. The adapter preserves this flag even when provider or request headers supply additional betas (see [/gateway/configuration](/gateway/configuration)).
126
129
 
127
130
  ## 1M context window (Anthropic beta)
128
131
 
@@ -41,19 +41,20 @@ buildParams = function johnnessMasterAnthropicBuildParams(model, context, isOAut
41
41
  /* JOHNNESS_MODELS_MASTER:END */
42
42
  /**
43
43
  * Resolve cache retention preference.
44
- * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.
44
+ * JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: direct Anthropic defaults to 1h for API keys and subscriptions.
45
+ * Other providers and the legacy PI_CACHE_RETENTION override keep their behavior.
45
46
  */
46
- function resolveCacheRetention(cacheRetention) {
47
+ function resolveCacheRetention(cacheRetention, provider) {
47
48
  if (cacheRetention) {
48
49
  return cacheRetention;
49
50
  }
50
51
  if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
51
52
  return "long";
52
53
  }
53
- return "short";
54
+ return provider === "anthropic" ? "long" : "short";
54
55
  }
55
- function getCacheControl(baseUrl, cacheRetention) {
56
- const retention = resolveCacheRetention(cacheRetention);
56
+ function getCacheControl(baseUrl, cacheRetention, provider) {
57
+ const retention = resolveCacheRetention(cacheRetention, provider);
57
58
  if (retention === "none") {
58
59
  return { retention };
59
60
  }
@@ -221,7 +222,7 @@ export const streamAnthropic = (model, context, options) => {
221
222
  hasImages,
222
223
  });
223
224
  }
224
- const { client, isOAuthToken } = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders);
225
+ const { client, isOAuthToken } = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders, options?.cacheRetention);
225
226
  // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86: zero cost on subscription attempts only.
226
227
  const billingModel = isOAuthToken ? { ...model, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } : model;
227
228
  const params = buildParams(model, context, isOAuthToken, options);
@@ -483,7 +484,18 @@ export const streamSimpleAnthropic = (model, context, options) => {
483
484
  function isOAuthToken(apiKey) {
484
485
  return apiKey.includes("sk-ant-oat");
485
486
  }
486
- function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders) {
487
+ // JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: keep the extended-cache beta on both auth paths, including
488
+ // explicit provider/request beta overrides. Claude Code 2.1.304 uses this same ephemeral ttl shape.
489
+ function withAnthropicCacheBeta(headers, model, cacheRetention) {
490
+ if (getCacheControl(model.baseUrl, cacheRetention, model.provider).cacheControl?.ttl !== "1h") return headers;
491
+ const merged = { ...headers };
492
+ const keys = Object.keys(merged).filter((key) => key.toLowerCase() === "anthropic-beta");
493
+ const betas = keys.flatMap((key) => String(merged[key] ?? "").split(",").map((value) => value.trim()).filter(Boolean));
494
+ for (const key of keys) delete merged[key];
495
+ merged["anthropic-beta"] = [...new Set([...betas, "extended-cache-ttl-2025-04-11"])].join(",");
496
+ return merged;
497
+ }
498
+ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders, cacheRetention) {
487
499
  // Adaptive thinking models (Opus 4.6, Sonnet 4.6) have interleaved thinking built-in.
488
500
  // The beta header is deprecated on Opus 4.6 and redundant on Sonnet 4.6, so skip it.
489
501
  const needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model.id);
@@ -519,13 +531,13 @@ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynami
519
531
  baseURL: model.baseUrl,
520
532
  maxRetries: 0,
521
533
  dangerouslyAllowBrowser: true,
522
- defaultHeaders: mergeHeaders({
534
+ defaultHeaders: withAnthropicCacheBeta(mergeHeaders({
523
535
  accept: "application/json",
524
536
  "anthropic-dangerous-direct-browser-access": "true",
525
537
  "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`,
526
538
  "user-agent": claudeCodeUserAgent(), // JOHNNESS_PATCH_SUBSCRIPTION_PLAN_LIMITS_88
527
539
  "x-app": "cli",
528
- }, model.headers, optionsHeaders),
540
+ }, model.headers, optionsHeaders), model, cacheRetention),
529
541
  });
530
542
  return { client, isOAuthToken: true };
531
543
  }
@@ -535,11 +547,11 @@ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynami
535
547
  baseURL: model.baseUrl,
536
548
  maxRetries: 0,
537
549
  dangerouslyAllowBrowser: true,
538
- defaultHeaders: mergeHeaders({
550
+ defaultHeaders: withAnthropicCacheBeta(mergeHeaders({
539
551
  accept: "application/json",
540
552
  "anthropic-dangerous-direct-browser-access": "true",
541
553
  "anthropic-beta": betaFeatures.join(","),
542
- }, model.headers, optionsHeaders),
554
+ }, model.headers, optionsHeaders), model, cacheRetention),
543
555
  });
544
556
  return { client, isOAuthToken: false };
545
557
  }
@@ -586,7 +598,7 @@ function buildAnthropicSystemBlocks(systemPrompt, cacheControl) {
586
598
  ];
587
599
  }
588
600
  function buildParams(model, context, isOAuthToken, options) {
589
- const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);
601
+ const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention, model.provider);
590
602
  const params = {
591
603
  model: model.id,
592
604
  messages: convertMessages(context.messages, model, isOAuthToken, cacheControl),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "johns-harness",
3
- "version": "2026.10.19",
3
+ "version": "2026.10.21",
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",
@@ -41,19 +41,20 @@ buildParams = function johnnessMasterAnthropicBuildParams(model, context, isOAut
41
41
  /* JOHNNESS_MODELS_MASTER:END */
42
42
  /**
43
43
  * Resolve cache retention preference.
44
- * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.
44
+ * JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: direct Anthropic defaults to 1h for API keys and subscriptions.
45
+ * Other providers and the legacy PI_CACHE_RETENTION override keep their behavior.
45
46
  */
46
- function resolveCacheRetention(cacheRetention) {
47
+ function resolveCacheRetention(cacheRetention, provider) {
47
48
  if (cacheRetention) {
48
49
  return cacheRetention;
49
50
  }
50
51
  if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
51
52
  return "long";
52
53
  }
53
- return "short";
54
+ return provider === "anthropic" ? "long" : "short";
54
55
  }
55
- function getCacheControl(baseUrl, cacheRetention) {
56
- const retention = resolveCacheRetention(cacheRetention);
56
+ function getCacheControl(baseUrl, cacheRetention, provider) {
57
+ const retention = resolveCacheRetention(cacheRetention, provider);
57
58
  if (retention === "none") {
58
59
  return { retention };
59
60
  }
@@ -221,7 +222,7 @@ export const streamAnthropic = (model, context, options) => {
221
222
  hasImages,
222
223
  });
223
224
  }
224
- const { client, isOAuthToken } = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders);
225
+ const { client, isOAuthToken } = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders, options?.cacheRetention);
225
226
  // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86: zero cost on subscription attempts only.
226
227
  const billingModel = isOAuthToken ? { ...model, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } } : model;
227
228
  const params = buildParams(model, context, isOAuthToken, options);
@@ -483,7 +484,18 @@ export const streamSimpleAnthropic = (model, context, options) => {
483
484
  function isOAuthToken(apiKey) {
484
485
  return apiKey.includes("sk-ant-oat");
485
486
  }
486
- function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders) {
487
+ // JOHNNESS_PATCH_ANTHROPIC_CACHE_LONG_90: keep the extended-cache beta on both auth paths, including
488
+ // explicit provider/request beta overrides. Claude Code 2.1.304 uses this same ephemeral ttl shape.
489
+ function withAnthropicCacheBeta(headers, model, cacheRetention) {
490
+ if (getCacheControl(model.baseUrl, cacheRetention, model.provider).cacheControl?.ttl !== "1h") return headers;
491
+ const merged = { ...headers };
492
+ const keys = Object.keys(merged).filter((key) => key.toLowerCase() === "anthropic-beta");
493
+ const betas = keys.flatMap((key) => String(merged[key] ?? "").split(",").map((value) => value.trim()).filter(Boolean));
494
+ for (const key of keys) delete merged[key];
495
+ merged["anthropic-beta"] = [...new Set([...betas, "extended-cache-ttl-2025-04-11"])].join(",");
496
+ return merged;
497
+ }
498
+ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders, cacheRetention) {
487
499
  // Adaptive thinking models (Opus 4.6, Sonnet 4.6) have interleaved thinking built-in.
488
500
  // The beta header is deprecated on Opus 4.6 and redundant on Sonnet 4.6, so skip it.
489
501
  const needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model.id);
@@ -519,13 +531,13 @@ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynami
519
531
  baseURL: model.baseUrl,
520
532
  maxRetries: 0,
521
533
  dangerouslyAllowBrowser: true,
522
- defaultHeaders: mergeHeaders({
534
+ defaultHeaders: withAnthropicCacheBeta(mergeHeaders({
523
535
  accept: "application/json",
524
536
  "anthropic-dangerous-direct-browser-access": "true",
525
537
  "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`,
526
538
  "user-agent": claudeCodeUserAgent(), // JOHNNESS_PATCH_SUBSCRIPTION_PLAN_LIMITS_88
527
539
  "x-app": "cli",
528
- }, model.headers, optionsHeaders),
540
+ }, model.headers, optionsHeaders), model, cacheRetention),
529
541
  });
530
542
  return { client, isOAuthToken: true };
531
543
  }
@@ -535,11 +547,11 @@ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynami
535
547
  baseURL: model.baseUrl,
536
548
  maxRetries: 0,
537
549
  dangerouslyAllowBrowser: true,
538
- defaultHeaders: mergeHeaders({
550
+ defaultHeaders: withAnthropicCacheBeta(mergeHeaders({
539
551
  accept: "application/json",
540
552
  "anthropic-dangerous-direct-browser-access": "true",
541
553
  "anthropic-beta": betaFeatures.join(","),
542
- }, model.headers, optionsHeaders),
554
+ }, model.headers, optionsHeaders), model, cacheRetention),
543
555
  });
544
556
  return { client, isOAuthToken: false };
545
557
  }
@@ -586,7 +598,7 @@ function buildAnthropicSystemBlocks(systemPrompt, cacheControl) {
586
598
  ];
587
599
  }
588
600
  function buildParams(model, context, isOAuthToken, options) {
589
- const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);
601
+ const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention, model.provider);
590
602
  const params = {
591
603
  model: model.id,
592
604
  messages: convertMessages(context.messages, model, isOAuthToken, cacheControl),