@cortexkit/common-auth 0.34.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ type FailureStage = 'authorization' | 'send' | 'response';
2
+ /** Keep diagnostics useful without retaining provider text, credentials or error causes. */
3
+ export declare function classifyFailure(error: unknown, stage: FailureStage, status?: number): {
4
+ stage: 'response';
5
+ class: number;
6
+ } | {
7
+ stage: FailureStage;
8
+ class: string;
9
+ };
10
+ export type Failure = ReturnType<typeof classifyFailure>;
11
+ export {};
@@ -0,0 +1,59 @@
1
+ const ERROR_NAMES = ['AbortError', 'TimeoutError', 'TypeError'];
2
+ const NETWORK_CODES = [
3
+ 'ECONNRESET',
4
+ 'ECONNREFUSED',
5
+ 'ETIMEDOUT',
6
+ 'EPIPE',
7
+ 'ENOTFOUND',
8
+ 'EAI_AGAIN',
9
+ 'UND_ERR_CONNECT_TIMEOUT',
10
+ 'UND_ERR_HEADERS_TIMEOUT',
11
+ 'UND_ERR_HEADERS_OVERFLOW',
12
+ 'UND_ERR_BODY_TIMEOUT',
13
+ 'UND_ERR_RESPONSE_STATUS_CODE',
14
+ 'UND_ERR_INVALID_ARG',
15
+ 'UND_ERR_INVALID_RETURN_VALUE',
16
+ 'UND_ERR_ABORTED',
17
+ 'UND_ERR_CLIENT_DESTROYED',
18
+ 'UND_ERR_CLIENT_CLOSED',
19
+ 'UND_ERR_SOCKET',
20
+ 'UND_ERR_NOT_SUPPORTED',
21
+ 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH',
22
+ 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH',
23
+ 'UND_ERR_INFO',
24
+ 'UND_ERR_RES_EXCEEDED_MAX_SIZE',
25
+ 'UND_ERR_PRX_TLS',
26
+ ];
27
+ function allowed(values, value) {
28
+ return typeof value === 'string' && values.includes(value);
29
+ }
30
+ /** Keep diagnostics useful without retaining provider text, credentials or error causes. */
31
+ export function classifyFailure(error, stage, status) {
32
+ try {
33
+ if (status !== undefined &&
34
+ Number.isInteger(status) &&
35
+ status >= 100 &&
36
+ status <= 599 &&
37
+ (status < 200 || status >= 300)) {
38
+ return { stage: 'response', class: status };
39
+ }
40
+ if (typeof error === 'object' && error !== null) {
41
+ const fields = error;
42
+ const name = fields.name;
43
+ if (name === 'AbortError' || name === 'TimeoutError')
44
+ return { stage, class: name };
45
+ const code = fields.code;
46
+ if (allowed(NETWORK_CODES, code))
47
+ return { stage, class: code };
48
+ const causeCode = fields.cause?.code;
49
+ if (allowed(NETWORK_CODES, causeCode))
50
+ return { stage, class: causeCode };
51
+ if (allowed(ERROR_NAMES, name))
52
+ return { stage, class: name };
53
+ }
54
+ }
55
+ catch {
56
+ // Host errors can have throwing accessors; never inspect or stringify them further.
57
+ }
58
+ return { stage, class: 'unknown' };
59
+ }
@@ -94,7 +94,7 @@ export interface CacheKeepManagerOptions<M> {
94
94
  maxBytes?: number;
95
95
  /** One deadline for credential resolution and the send. Default 30 s. */
96
96
  warmTimeoutMs?: number;
97
- /** Delay after a failed warm, fixed or by consecutive failures. Default 10 minutes. */
97
+ /** Override failure delays, fixed or by consecutive failures. Defaults to expiry-bounded transient retries, otherwise 10 minutes. */
98
98
  backoffMs?: CacheKeepBackoff;
99
99
  /** The configured clock window; undefined means always warm. Read on every call. */
100
100
  getWindow?: () => CacheKeepWindow | undefined;
@@ -160,9 +160,11 @@ export interface CacheKeepStatus {
160
160
  * session stopped using (`sustain` lifts only the main-session idle cap, not
161
161
  * the lifetime); the target-count and byte caps evict the least recently
162
162
  * touched target; a per-target warm cap retires short-lived sessions; and a
163
- * failed warm backs that target off without touching the others. A retry
164
- * after a failure is sent only while the lifetime lasts, so a backoff that
165
- * runs past it retires the target instead.
163
+ * failed warm backs that target off without touching the others. Default
164
+ * transient retries use 20/40/60-second delays, clipped to the last safe start
165
+ * (expiry minus the warm timeout and 5 seconds). Only default-policy retries
166
+ * observe that deadline: first attempts and explicit backoff policies retain
167
+ * their existing lead-time scheduling, bounded by the cache lifetime.
166
168
  */
167
169
  export declare class CacheKeepManager<M = undefined> {
168
170
  private readonly targets;
@@ -218,6 +220,10 @@ export declare class CacheKeepManager<M = undefined> {
218
220
  private isCurrent;
219
221
  private view;
220
222
  private fail;
223
+ private lastRetryStart;
224
+ private canRetry;
225
+ private clearRetry;
226
+ private scheduleRetry;
221
227
  private warm;
222
228
  private idleDefault;
223
229
  private pruneStale;
@@ -1,4 +1,5 @@
1
1
  import { combineAbortSignals } from '../util/any-signal.js';
2
+ import { classifyFailure } from './failure.js';
2
3
  import { isWithinCacheKeepWindow } from './window.js';
3
4
  const DEFAULT_TTL_MS = 5 * 60_000;
4
5
  const DEFAULT_MAX_IDLE_WARM_MS = 60 * 60_000;
@@ -8,14 +9,14 @@ const DEFAULT_MAX_TARGETS = 32;
8
9
  const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
9
10
  const DEFAULT_WARM_TIMEOUT_MS = 30_000;
10
11
  const DEFAULT_BACKOFF_MS = 10 * 60_000;
12
+ const TRANSIENT_RETRY_STEP_MS = 20_000;
13
+ const TRANSIENT_RETRY_MAX_MS = 60_000;
14
+ const EXPIRY_SAFETY_MS = 5_000;
11
15
  function positive(value, fallback) {
12
16
  return typeof value === 'number' && Number.isFinite(value) && value > 0
13
17
  ? value
14
18
  : fallback;
15
19
  }
16
- function errorMessage(error) {
17
- return error instanceof Error ? error.message : String(error);
18
- }
19
20
  /**
20
21
  * Keeps idle prompt caches warm: one target per session holding the latest
21
22
  * request body, replayed just before the provider's cache would expire.
@@ -29,9 +30,11 @@ function errorMessage(error) {
29
30
  * session stopped using (`sustain` lifts only the main-session idle cap, not
30
31
  * the lifetime); the target-count and byte caps evict the least recently
31
32
  * touched target; a per-target warm cap retires short-lived sessions; and a
32
- * failed warm backs that target off without touching the others. A retry
33
- * after a failure is sent only while the lifetime lasts, so a backoff that
34
- * runs past it retires the target instead.
33
+ * failed warm backs that target off without touching the others. Default
34
+ * transient retries use 20/40/60-second delays, clipped to the last safe start
35
+ * (expiry minus the warm timeout and 5 seconds). Only default-policy retries
36
+ * observe that deadline: first attempts and explicit backoff policies retain
37
+ * their existing lead-time scheduling, bounded by the cache lifetime.
35
38
  */
36
39
  export class CacheKeepManager {
37
40
  targets = new Map();
@@ -71,7 +74,7 @@ export class CacheKeepManager {
71
74
  this.maxTargets = positive(options.maxTargets, DEFAULT_MAX_TARGETS);
72
75
  this.maxBytes = positive(options.maxBytes, DEFAULT_MAX_BYTES);
73
76
  this.warmTimeoutMs = positive(options.warmTimeoutMs, DEFAULT_WARM_TIMEOUT_MS);
74
- this.backoff = options.backoffMs ?? DEFAULT_BACKOFF_MS;
77
+ this.backoff = options.backoffMs;
75
78
  this.getWindow = options.getWindow;
76
79
  this.getSustain = options.getSustain;
77
80
  this.setIntervalImpl = options.setIntervalImpl ?? globalThis.setInterval;
@@ -163,7 +166,7 @@ export class CacheKeepManager {
163
166
  this.startedAt = this.now();
164
167
  this.timer = this.setIntervalImpl(() => {
165
168
  void this.tick().catch((error) => {
166
- this.log?.warn('cachekeep tick failed', { error: errorMessage(error) });
169
+ this.log?.warn('cachekeep tick failed', classifyFailure(error, 'send'));
167
170
  });
168
171
  }, this.tickIntervalMs);
169
172
  if (typeof this.timer === 'object' && 'unref' in this.timer) {
@@ -185,6 +188,8 @@ export class CacheKeepManager {
185
188
  this.timer = null;
186
189
  }
187
190
  this.startedAt = null;
191
+ for (const target of this.targets.values())
192
+ this.clearRetry(target);
188
193
  this.targets.clear();
189
194
  this.totalBytes = 0;
190
195
  this.log?.debug('cachekeep stopped');
@@ -247,17 +252,18 @@ export class CacheKeepManager {
247
252
  if (window && !isWithinCacheKeepWindow(window, new Date(this.now()))) {
248
253
  return;
249
254
  }
250
- const now = this.now();
251
- const leadBound = now + this.leadMs;
252
255
  for (const [sessionKey, target] of [...this.targets]) {
253
256
  if (this.disposed)
254
257
  return;
255
258
  if (this.targets.get(sessionKey) !== target)
256
259
  continue;
260
+ const now = this.now();
257
261
  if (target.backoffUntil !== undefined && now < target.backoffUntil) {
258
262
  continue;
259
263
  }
260
- if (target.cacheExpiresAt > leadBound)
264
+ if (target.cacheExpiresAt > now + this.leadMs)
265
+ continue;
266
+ if (!this.canRetry(target))
261
267
  continue;
262
268
  await this.warm(sessionKey, target);
263
269
  }
@@ -293,26 +299,72 @@ export class CacheKeepManager {
293
299
  ttlMs: target.ttlMs,
294
300
  };
295
301
  }
296
- fail(sessionKey, target, message, fields = {}) {
302
+ fail(sessionKey, target, message, failure, transient = false, status) {
297
303
  if (!this.isCurrent(sessionKey, target))
298
304
  return;
299
305
  target.failures += 1;
300
- const delay = typeof this.backoff === 'function'
306
+ const now = this.now();
307
+ let delay = typeof this.backoff === 'function'
301
308
  ? this.backoff({ sessionKey, failures: target.failures })
302
- : this.backoff;
309
+ : (this.backoff ?? DEFAULT_BACKOFF_MS);
310
+ const deadline = this.lastRetryStart(target);
311
+ const fastRetry = this.backoff === undefined && transient && now < deadline;
312
+ if (fastRetry) {
313
+ delay = Math.min(TRANSIENT_RETRY_STEP_MS * target.failures, TRANSIENT_RETRY_MAX_MS, deadline - now);
314
+ }
303
315
  target.backoffUntil =
304
- this.now() + (Number.isFinite(delay) && delay > 0 ? delay : 0);
316
+ now + (Number.isFinite(delay) && delay > 0 ? delay : 0);
317
+ this.clearRetry(target);
318
+ if (fastRetry)
319
+ this.scheduleRetry(sessionKey, target, delay);
305
320
  this.log?.warn(message, {
306
321
  sessionKey,
307
322
  accountId: target.accountId,
308
323
  failures: target.failures,
309
324
  backoffUntil: target.backoffUntil,
310
- ...fields,
325
+ ...failure,
326
+ ...(status !== undefined && { status }),
311
327
  });
312
328
  }
329
+ lastRetryStart(target) {
330
+ return target.cacheExpiresAt - this.warmTimeoutMs - EXPIRY_SAFETY_MS;
331
+ }
332
+ canRetry(target) {
333
+ return (this.backoff !== undefined ||
334
+ target.failures === 0 ||
335
+ this.now() <= this.lastRetryStart(target));
336
+ }
337
+ clearRetry(target) {
338
+ if (target.retryTimer === undefined)
339
+ return;
340
+ this.clearIntervalImpl(target.retryTimer);
341
+ target.retryTimer = undefined;
342
+ }
343
+ scheduleRetry(sessionKey, target, delay) {
344
+ // Use the same injected timer pair as the regular tick, but clear this
345
+ // interval before dispatch so it acts as a one-shot retry timer.
346
+ target.retryTimer = this.setIntervalImpl(() => {
347
+ this.clearRetry(target);
348
+ return (async () => {
349
+ // A different target can still be warming. Wait for that tick before
350
+ // rechecking eligibility, rather than losing this wake-up to coalescing.
351
+ await this.tickPromise;
352
+ if (this.isCurrent(sessionKey, target))
353
+ await this.tick();
354
+ })().catch((error) => {
355
+ this.log?.warn('cachekeep tick failed', classifyFailure(error, 'send'));
356
+ });
357
+ }, delay);
358
+ if (typeof target.retryTimer === 'object' && 'unref' in target.retryTimer) {
359
+ target.retryTimer.unref();
360
+ }
361
+ }
313
362
  async warm(sessionKey, target) {
314
363
  if (this.retireIfExpired(sessionKey, target))
315
364
  return;
365
+ if (!this.canRetry(target))
366
+ return;
367
+ this.clearRetry(target);
316
368
  const view = this.view(sessionKey, target);
317
369
  if (this.adapter.activeAccount) {
318
370
  let active;
@@ -320,9 +372,7 @@ export class CacheKeepManager {
320
372
  active = await this.adapter.activeAccount(sessionKey, view);
321
373
  }
322
374
  catch (error) {
323
- this.fail(sessionKey, target, 'cachekeep skip (active account unknown)', {
324
- error: errorMessage(error),
325
- });
375
+ this.fail(sessionKey, target, 'cachekeep skip (active account unknown)', classifyFailure(error, 'authorization'), true);
326
376
  return;
327
377
  }
328
378
  if (!this.isCurrent(sessionKey, target))
@@ -342,15 +392,15 @@ export class CacheKeepManager {
342
392
  body = await this.adapter.buildBody(view);
343
393
  }
344
394
  catch (error) {
345
- this.fail(sessionKey, target, 'cachekeep skip (replay body unbuildable)', {
346
- error: errorMessage(error),
347
- });
395
+ this.fail(sessionKey, target, 'cachekeep skip (replay body unbuildable)', classifyFailure(error, 'authorization'));
348
396
  return;
349
397
  }
350
398
  if (!this.isCurrent(sessionKey, target))
351
399
  return;
352
400
  if (this.retireIfExpired(sessionKey, target))
353
401
  return;
402
+ if (!this.canRetry(target))
403
+ return;
354
404
  const combined = combineAbortSignals([
355
405
  AbortSignal.timeout(this.warmTimeoutMs),
356
406
  this.abortController.signal,
@@ -358,16 +408,21 @@ export class CacheKeepManager {
358
408
  const signal = combined.signal;
359
409
  let response;
360
410
  let text = '';
411
+ let stage = 'send';
412
+ let status;
361
413
  try {
362
414
  response = await this.adapter.send({ target: view, body, signal });
363
- // Drain the body so the connection is released; its text is only
364
- // diagnostic.
365
- text = await response.text().catch(() => '');
415
+ stage = 'response';
416
+ status = response.status;
417
+ // Drain the body to release the connection and let the adapter read usage.
418
+ text = await response.text();
366
419
  }
367
420
  catch (error) {
368
- this.fail(sessionKey, target, 'cachekeep failed', {
369
- error: errorMessage(error),
370
- });
421
+ this.fail(sessionKey, target, 'cachekeep failed', classifyFailure(error, stage, status), status === undefined ||
422
+ (status >= 200 && status < 300) ||
423
+ status === 408 ||
424
+ status === 429 ||
425
+ status >= 500, status);
371
426
  return;
372
427
  }
373
428
  finally {
@@ -376,10 +431,9 @@ export class CacheKeepManager {
376
431
  if (!this.isCurrent(sessionKey, target))
377
432
  return;
378
433
  if (!response.ok) {
379
- this.fail(sessionKey, target, 'cachekeep failed', {
380
- status: response.status,
381
- responseBody: text.slice(0, 600),
382
- });
434
+ this.fail(sessionKey, target, 'cachekeep failed', classifyFailure(undefined, 'response', response.status), response.status === 408 ||
435
+ response.status === 429 ||
436
+ response.status >= 500, response.status);
383
437
  return;
384
438
  }
385
439
  let usage;
@@ -393,6 +447,7 @@ export class CacheKeepManager {
393
447
  target.cacheExpiresAt = now + target.ttlMs;
394
448
  target.lastWarmedAt = now;
395
449
  target.backoffUntil = undefined;
450
+ this.clearRetry(target);
396
451
  target.failures = 0;
397
452
  target.warmCount += 1;
398
453
  this.log?.debug('cachekeep fired', {
@@ -452,6 +507,7 @@ export class CacheKeepManager {
452
507
  const target = this.targets.get(sessionKey);
453
508
  if (!target)
454
509
  return false;
510
+ this.clearRetry(target);
455
511
  this.totalBytes -= target.bodyBytes;
456
512
  this.targets.delete(sessionKey);
457
513
  return true;
@@ -29,8 +29,10 @@ export interface LimitAxes {
29
29
  readonly preference: 'same-account-first' | 'ready-alternative-first';
30
30
  readonly jitter: 'session-sha256' | 'none';
31
31
  };
32
- /** Bounded retention is not an adopted policy. */
32
+ /** Legacy uncounted retention remains unbounded. */
33
33
  readonly retainBound: 'none';
34
+ /** Opt-in turn/account budget when the caller supplies unconfirmedRetainCount. */
35
+ readonly unconfirmedRetainLimit?: number;
34
36
  readonly poolWaiting: {
35
37
  readonly kind: 'off';
36
38
  } | {
@@ -56,6 +58,10 @@ export interface LimitAxes {
56
58
  readonly terminalStatusHistory?: {
57
59
  readonly minRetryMs: number;
58
60
  readonly defaultRetryMs: number;
61
+ readonly paymentBalance?: {
62
+ readonly family: RefusalFamily;
63
+ readonly messageKey: string;
64
+ };
59
65
  };
60
66
  readonly refusals: Readonly<Record<RefusalReason, HostValues<RefusalPolicy>>>;
61
67
  }
@@ -9,6 +9,7 @@ import type { WakeFacts } from './wake.js';
9
9
  export interface TimedBlocker {
10
10
  readonly kind: 'hard' | 'cooldown' | 'soft';
11
11
  readonly until?: number;
12
+ readonly cause?: import('./marker.js').LimitMarkCause;
12
13
  }
13
14
  /**
14
15
  * Admission includes the caller's minimum quota thresholds, access checks,
@@ -80,6 +81,8 @@ export interface PolicyFacts {
80
81
  readonly retryMs?: number;
81
82
  };
82
83
  readonly retryHintsMs?: readonly number[];
84
+ /** Committed unconfirmed retains for the current session, turn and account. */
85
+ readonly unconfirmedRetainCount?: number;
83
86
  readonly hold?: HoldFacts;
84
87
  readonly wake?: WakeFacts;
85
88
  readonly remainingRetries?: number;
@@ -110,6 +113,8 @@ export type LimitDecision = DecisionBase & ({
110
113
  readonly action: 'retain';
111
114
  readonly account: AccountKey;
112
115
  readonly retryMs?: number;
116
+ /** Commit once when executing this retain, never when polling the decision. */
117
+ readonly incrementUnconfirmedRetain?: true;
113
118
  /** Exhaustion windows waived for this dispatch only, never persisted. */
114
119
  readonly liftedWindows?: readonly string[];
115
120
  } | {
@@ -147,6 +147,12 @@ export function decideAfterLimit(facts, axes) {
147
147
  account: facts.attempted,
148
148
  scope: facts.requestScope,
149
149
  status,
150
+ kind: axes.terminalStatusHistory?.paymentBalance &&
151
+ facts.signalApplicable !== false &&
152
+ facts.signal &&
153
+ sameAccount(facts.signal.account, facts.attempted)
154
+ ? facts.signal.kind
155
+ : undefined,
150
156
  });
151
157
  if (facts.phase === 'after-limit' && !facts.delivery.replayable)
152
158
  return pass('unsafe-output', false, 'veto');
@@ -240,9 +246,20 @@ export function decideAfterLimit(facts, axes) {
240
246
  history,
241
247
  };
242
248
  }
249
+ // Supplying the count opts into the turn-scoped rule across all hosts;
250
+ // callers without it keep their existing host-specific unknown-limit policy.
251
+ const retainLimit = axes.unconfirmedRetainLimit;
252
+ const retainCount = facts.unconfirmedRetainCount;
253
+ const counted = status === 429 && retainLimit !== undefined && retainCount !== undefined;
243
254
  const advance = axes.advance[facts.host];
255
+ if (facts.phase === 'after-limit' &&
256
+ axes.terminalStatusHistory?.paymentBalance &&
257
+ (signal?.kind === 'payment-cap' ||
258
+ (status === 402 && signal?.kind !== 'payment-balance')))
259
+ return pass('unhandled-failure');
244
260
  if (facts.phase === 'after-limit' &&
245
261
  !signal &&
262
+ !counted &&
246
263
  !facts.terminal &&
247
264
  (advance.attributedLimitOnly ||
248
265
  status === undefined ||
@@ -262,11 +279,11 @@ export function decideAfterLimit(facts, axes) {
262
279
  (!facts.attempted || !sameAccount(selected.account, facts.attempted))
263
280
  ? selected
264
281
  : undefined;
265
- const reroute = (candidate) => ({
282
+ const reroute = (candidate, reason = 'ready-alternative') => ({
266
283
  action: 'reroute',
267
284
  account: candidate.account,
268
285
  pin: facts.selection?.pin ?? 'preserve',
269
- reason: 'ready-alternative',
286
+ reason,
270
287
  retryable: true,
271
288
  hostRetry: continuationRetry(facts, axes),
272
289
  history: reduceRequestHistory(history, { type: 'selected' }),
@@ -295,28 +312,39 @@ export function decideAfterLimit(facts, axes) {
295
312
  signal?.kind === 'rate-limit' ||
296
313
  signal?.kind === 'quota-exhausted' ||
297
314
  signal?.kind === 'capacity');
315
+ const retainLimitReached = counted && retainCount >= retainLimit;
298
316
  if (unconfirmed &&
299
317
  current &&
300
318
  (unknown.affinity === 'always' || facts.affinity === 'sticky')) {
301
- if (unknown.action === 'pass')
302
- return pass('unconfirmed-limit');
303
- if (unknown.action === 'retain') {
319
+ if (counted && retainLimitReached) {
320
+ if (alternative)
321
+ return reroute(alternative, 'unconfirmed-retry-limit');
322
+ // With no ready replacement, use the ordinary exhausted-pool outcome.
323
+ }
324
+ else if (counted || unknown.action === 'retain') {
304
325
  const hints = [
305
326
  ...(facts.retryHintsMs ?? []),
306
327
  signal?.retryAfterMs,
307
- ].filter((hint) => hint !== undefined && Number.isFinite(hint) && hint >= 0);
328
+ ].filter((hint) => hint !== undefined && Number.isFinite(hint) && (counted || hint >= 0));
308
329
  return {
309
330
  action: 'retain',
310
331
  account: current.account,
311
332
  reason: 'unconfirmed-limit',
312
- ...(unknown.hint === 'minimum'
313
- ? { retryMs: Math.min(unknown.defaultMs, ...hints) }
314
- : {}),
333
+ ...(counted
334
+ ? {
335
+ retryMs: Math.min(60_000, ...hints.map((hint) => Math.max(0, hint))),
336
+ incrementUnconfirmedRetain: true,
337
+ }
338
+ : unknown.hint === 'minimum'
339
+ ? { retryMs: Math.min(unknown.defaultMs, ...hints) }
340
+ : {}),
315
341
  retryable: true,
316
342
  hostRetry: continuationRetry(facts, axes),
317
343
  history,
318
344
  };
319
345
  }
346
+ else if (unknown.action === 'pass')
347
+ return pass('unconfirmed-limit');
320
348
  }
321
349
  if (alternative)
322
350
  return reroute(alternative);
@@ -357,13 +385,27 @@ export function decideAfterLimit(facts, axes) {
357
385
  const allMarked = facts.phase === 'pre-send' &&
358
386
  candidates.length > 0 &&
359
387
  candidates.every((candidate) => !candidate.ready);
360
- if (allMarked || (status === 401 && history.saw429)) {
361
- const deadlines = candidates
388
+ const eligible = candidates.filter((candidate) => candidate.placementEligible);
389
+ const allBalance = facts.phase === 'pre-send' &&
390
+ axes.terminalStatusHistory.paymentBalance &&
391
+ eligible.length > 0 &&
392
+ eligible.every((candidate) => !candidate.ready &&
393
+ candidate.blockers.length > 0 &&
394
+ candidate.blockers.every((blocker) => blocker.cause === 'payment-balance' &&
395
+ finiteFuture(blocker.until, facts.now)));
396
+ if (allBalance ||
397
+ allMarked ||
398
+ (status === 401 && history.saw429) ||
399
+ (axes.terminalStatusHistory.paymentBalance &&
400
+ history.saw429 &&
401
+ history.sawPaymentBalance)) {
402
+ const deadlines = (allBalance ? eligible : candidates)
362
403
  .flatMap((candidate) => candidate.blockers.map((blocker) => blocker.until))
363
404
  .filter((until) => finiteFuture(until, facts.now));
364
405
  return refusal(facts, axes, history, 'quota', {
365
406
  source: 'pool',
366
407
  reason: 'quota',
408
+ ...(allBalance ? axes.terminalStatusHistory.paymentBalance : {}),
367
409
  retryAfterMs: deadlines.length
368
410
  ? Math.max(axes.terminalStatusHistory.minRetryMs, Math.min(...deadlines) - facts.now)
369
411
  : axes.terminalStatusHistory.defaultRetryMs,
@@ -1,9 +1,11 @@
1
1
  import { type LimitMessages } from './wording.js';
2
- export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claude-econnreset';
2
+ export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claustrum-402' | 'claude-econnreset';
3
3
  export type RefusalFamily = OpenCode1Family | 'pi-final';
4
4
  export type HostRetry = 'leave' | 'veto';
5
5
  export interface RefusalInput {
6
6
  readonly family: RefusalFamily;
7
+ /** Local responses formatted for OpenCode 2 must not be replayed by the host. */
8
+ readonly host?: 'opencode1' | 'opencode2' | 'pi';
7
9
  readonly messageKey: string;
8
10
  readonly messages?: LimitMessages;
9
11
  readonly parameters?: {
@@ -31,7 +33,7 @@ interface RefusalAttributes {
31
33
  }
32
34
  export interface HttpRefusal extends RefusalAttributes {
33
35
  readonly kind: 'http';
34
- readonly status: 412 | 429;
36
+ readonly status: 402 | 412 | 429;
35
37
  readonly headers: Headers;
36
38
  readonly body: string;
37
39
  }
@@ -97,6 +97,8 @@ function bodyFor(family, message) {
97
97
  });
98
98
  case 'claustrum-429':
99
99
  return JSON.stringify({ error: 'claustrum-auth: accounts-rate-limited' });
100
+ case 'claustrum-402':
101
+ return JSON.stringify({ error: 'claustrum-auth: insufficient balance' });
100
102
  default:
101
103
  return message;
102
104
  }
@@ -108,7 +110,7 @@ export function buildRefusal(input) {
108
110
  family: input.family,
109
111
  disposition: 'refuse',
110
112
  retryable: !nonRetryable,
111
- hostRetry: nonRetryable ? 'veto' : 'leave',
113
+ hostRetry: nonRetryable || input.host === 'opencode2' ? 'veto' : 'leave',
112
114
  };
113
115
  let body = bodyFor(input.family, textFor(input, nonRetryable));
114
116
  if (nonRetryable && (hasUnsafeWording(body) || containsEmail(body))) {
@@ -136,7 +138,11 @@ export function buildRefusal(input) {
136
138
  return {
137
139
  ...attributes,
138
140
  kind: 'http',
139
- status: input.family === 'json-412' ? 412 : 429,
141
+ status: input.family === 'json-412'
142
+ ? 412
143
+ : input.family === 'claustrum-402'
144
+ ? 402
145
+ : 429,
140
146
  headers,
141
147
  body,
142
148
  };
@@ -16,7 +16,7 @@ export type { AuthorizeCredentialEpoch, IdentityBinding, } from './identity.js';
16
16
  export { isIdentityCompatible, retainVerifiedIdentity, validateIdentityFence, } from './identity.js';
17
17
  export { holdDelayMs } from './jitter.js';
18
18
  export { sanitizeRefusalLabel } from './labels.js';
19
- export type { FailureEvent, FailureHistory, FailureLadderAxes, FailureStreak, LimitMark, MarkerAxes, MarkerHistory, MergeLaw, } from './marker.js';
19
+ export type { FailureEvent, FailureHistory, FailureLadderAxes, FailureStreak, LimitMark, LimitMarkCause, MarkerAxes, MarkerHistory, MergeLaw, } from './marker.js';
20
20
  export { ANTIGRAVITY_FAILURE_LADDER, markFromSignal, markIsActive, reduceFailureHistory, } from './marker.js';
21
21
  export type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
22
22
  export { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
@@ -28,8 +28,8 @@ export type { PiWaitOptions, PiWaitResult } from './pi-wait.js';
28
28
  export { waitForPi } from './pi-wait.js';
29
29
  export { createPoolLimitsAdapter, type PoolLimitsAdapterOptions, } from './pool-adapter.js';
30
30
  export { confirmedAffinity, earliestPoolEngine, limitPresets, statusVaultOrder, windowRouter, } from './presets.js';
31
- export type { LimitsClock, LimitsDispatchView, LimitsRegistry, LimitsRegistryEvent, LimitsRegistryOptions, } from './registry.js';
32
- export { acquireLimitsRegistry, LIMITS_REGISTRY_KEY } from './registry.js';
31
+ export type { LimitsClock, LimitsDispatchView, LimitsRegistry, LimitsRegistryEvent, LimitsRegistryOptions, SuccessfulProbeClear, } from './registry.js';
32
+ export { acquireLimitsRegistry, clearLimitsAfterProbe, LIMITS_REGISTRY_KEY, } from './registry.js';
33
33
  export type { RequestExclusion, RequestHistory, RequestHistoryEvent, RetainHistory, } from './request-history.js';
34
34
  export { commitRequestExclusion, createRequestHistory, isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
35
35
  export type { ResetSource, ResolvedReset } from './reset.js';
@@ -40,5 +40,6 @@ export { scopeCovers } from './scope.js';
40
40
  export type { AccountKey, ClassifierInput, LimitClassifier, LimitKind, LimitSignal, LimitWindow, } from './signal.js';
41
41
  export type { TerminalCandidate, TerminalReset, TerminalScanFacts, TerminalWindow, } from './terminal.js';
42
42
  export { scanTerminalReset } from './terminal.js';
43
+ export { UnconfirmedRetainCounter } from './unconfirmed-retain-counter.js';
43
44
  export type { LimitMessageOptions, LimitMessages, MessageParameters, MessageTemplate, } from './wording.js';
44
45
  export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
@@ -16,10 +16,11 @@ export { LimitsPersistenceRefusal } from './persistence.js';
16
16
  export { waitForPi } from './pi-wait.js';
17
17
  export { createPoolLimitsAdapter, } from './pool-adapter.js';
18
18
  export { confirmedAffinity, earliestPoolEngine, limitPresets, statusVaultOrder, windowRouter, } from './presets.js';
19
- export { acquireLimitsRegistry, LIMITS_REGISTRY_KEY } from './registry.js';
19
+ export { acquireLimitsRegistry, clearLimitsAfterProbe, LIMITS_REGISTRY_KEY, } from './registry.js';
20
20
  export { commitRequestExclusion, createRequestHistory, isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
21
21
  export { resolveNamedWindowReset, resolveReset } from './reset.js';
22
22
  export { holdWaitMaxS } from './routing-hold.js';
23
23
  export { scopeCovers } from './scope.js';
24
24
  export { scanTerminalReset } from './terminal.js';
25
+ export { UnconfirmedRetainCounter } from './unconfirmed-retain-counter.js';
25
26
  export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
@@ -1,10 +1,12 @@
1
1
  import type { Scope } from './scope.js';
2
2
  import type { AccountKey, LimitKind, LimitSignal } from './signal.js';
3
3
  export type MergeLaw = 'latest-evidence' | 'max-until' | 'overwrite';
4
+ export type LimitMarkCause = 'rate-limit' | 'payment-balance';
4
5
  export interface LimitMark {
5
6
  readonly scope: Scope;
6
7
  readonly until: number;
7
8
  readonly mergeLaw: MergeLaw;
9
+ readonly cause?: LimitMarkCause;
8
10
  }
9
11
  export interface FailureLadderAxes {
10
12
  readonly kind: 'failure-ladder';
@@ -27,6 +29,9 @@ export type MarkerAxes = {
27
29
  readonly kind: 'hint';
28
30
  readonly mergeLaw: MergeLaw;
29
31
  readonly defaultMs: number;
32
+ readonly defaultMsByKind?: Readonly<Partial<Record<LimitSignal['kind'], number>>>;
33
+ readonly causes?: readonly LimitMarkCause[];
34
+ readonly ignoredKinds?: readonly LimitSignal['kind'][];
30
35
  readonly minimumMs: number;
31
36
  readonly zero: 'accept' | 'skip';
32
37
  /** Core absolute dates and host event-relative hints use different samples. */
@@ -61,6 +61,8 @@ function ladderMs(signal, axes, history) {
61
61
  export function markFromSignal(signal, axes, history) {
62
62
  if (!signal || axes.kind === 'off')
63
63
  return undefined;
64
+ if (axes.kind === 'hint' && axes.ignoredKinds?.includes(signal.kind))
65
+ return undefined;
64
66
  let until;
65
67
  switch (axes.kind) {
66
68
  case 'failure-ladder':
@@ -68,13 +70,14 @@ export function markFromSignal(signal, axes, history) {
68
70
  break;
69
71
  case 'hint': {
70
72
  const hint = signal.retryAfterMs;
73
+ const clock = axes.hintClock === 'signal' ? signal.observedAt : history.now;
71
74
  const usable = hint !== undefined &&
72
75
  Number.isFinite(hint) &&
73
- (hint > 0 || (hint === 0 && axes.zero === 'accept'));
76
+ (hint > 0 || (hint === 0 && axes.zero === 'accept')) &&
77
+ Number.isFinite(clock + Math.max(axes.minimumMs, hint));
74
78
  until = usable
75
- ? (axes.hintClock === 'signal' ? signal.observedAt : history.now) +
76
- Math.max(axes.minimumMs, hint)
77
- : history.now + axes.defaultMs;
79
+ ? clock + Math.max(axes.minimumMs, hint)
80
+ : history.now + (axes.defaultMsByKind?.[signal.kind] ?? axes.defaultMs);
78
81
  break;
79
82
  }
80
83
  case 'reset': {
@@ -88,7 +91,15 @@ export function markFromSignal(signal, axes, history) {
88
91
  }
89
92
  }
90
93
  return Number.isFinite(until)
91
- ? { scope: signal.scope, until, mergeLaw: axes.mergeLaw }
94
+ ? {
95
+ scope: signal.scope,
96
+ until,
97
+ mergeLaw: axes.mergeLaw,
98
+ ...(axes.kind === 'hint' &&
99
+ axes.causes?.some((cause) => cause === signal.kind)
100
+ ? { cause: signal.kind }
101
+ : {}),
102
+ }
92
103
  : undefined;
93
104
  }
94
105
  export function markIsActive(mark, now) {
@@ -1,5 +1,6 @@
1
1
  import type { MergeLaw } from './marker.js';
2
2
  export interface TimedMarkEntry {
3
+ readonly cause?: import('./marker.js').LimitMarkCause;
3
4
  readonly until: number;
4
5
  readonly evidenceAt: number;
5
6
  readonly baseRevision: number;
@@ -1,5 +1,5 @@
1
1
  import type { AuthorizeCredentialEpoch, IdentityBinding } from './identity.js';
2
- import type { MergeLaw } from './marker.js';
2
+ import type { LimitMarkCause, MergeLaw } from './marker.js';
3
3
  import type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
4
4
  import type { Scope } from './scope.js';
5
5
  import type { AccountKey } from './signal.js';
@@ -52,11 +52,14 @@ export type LimitsCommand<T = unknown> = CommandBase & (({
52
52
  readonly until: number;
53
53
  readonly evidenceAt: number;
54
54
  readonly mergeLaw: MergeLaw;
55
+ readonly cause?: LimitMarkCause;
55
56
  } & MarkTarget) | {
56
57
  readonly type: 'clear';
57
58
  readonly keys: readonly MarkTarget[];
58
59
  /** Absent for explicit user clears; automatic clears carry their evidence time. */
59
60
  readonly evidenceAt?: number;
61
+ /** A successful probe clears only this cause, but fences absent/expired keys too. */
62
+ readonly cause?: LimitMarkCause;
60
63
  } | {
61
64
  readonly type: 'access';
62
65
  readonly state: T;
@@ -130,6 +130,10 @@ export function applyLimitsCommands(initial, commands, context) {
130
130
  evidenceAt: command.evidenceAt,
131
131
  baseRevision: command.baseRevision,
132
132
  committedRevision: revision,
133
+ ...(command.cause === 'rate-limit' ||
134
+ command.cause === 'payment-balance'
135
+ ? { cause: command.cause }
136
+ : {}),
133
137
  },
134
138
  ], context.now, clear?.revision);
135
139
  marks = marks.filter((m) => timedMarkKeyId(m.key) !== id);
@@ -137,7 +141,11 @@ export function applyLimitsCommands(initial, commands, context) {
137
141
  marks.push({ key, mergeLaw: command.mergeLaw, entries });
138
142
  }
139
143
  else if (command.type === 'clear') {
140
- const keys = command.keys.map((key) => ({ ...key, account }));
144
+ const keys = command.keys
145
+ .map((key) => ({ ...key, account }))
146
+ .filter((key) => command.cause === undefined ||
147
+ !marks.some((mark) => timedMarkKeyId(mark.key) === timedMarkKeyId(key) &&
148
+ mark.entries.some((entry) => entry.cause !== command.cause)));
141
149
  const ids = new Set(keys.map(timedMarkKeyId));
142
150
  const evidenceAt = command.evidenceAt;
143
151
  if (evidenceAt !== undefined &&
@@ -50,6 +50,7 @@ const engineQuota = {
50
50
  hostRetry: 'veto',
51
51
  };
52
52
  export const confirmedAffinity = immutable({
53
+ unconfirmedRetainLimit: 2,
53
54
  evidence: 'per-field-overlay',
54
55
  markers: hosts({
55
56
  kind: 'reset',
@@ -163,6 +164,9 @@ export const statusVaultOrder = immutable({
163
164
  kind: 'hint',
164
165
  mergeLaw: 'overwrite',
165
166
  defaultMs: 60000,
167
+ defaultMsByKind: { 'payment-balance': 300000 },
168
+ causes: ['rate-limit', 'payment-balance'],
169
+ ignoredKinds: ['payment-cap'],
166
170
  minimumMs: 0,
167
171
  zero: 'accept',
168
172
  hintClock: 'signal',
@@ -171,6 +175,9 @@ export const statusVaultOrder = immutable({
171
175
  kind: 'hint',
172
176
  mergeLaw: 'overwrite',
173
177
  defaultMs: 60000,
178
+ defaultMsByKind: { 'payment-balance': 300000 },
179
+ causes: ['rate-limit', 'payment-balance'],
180
+ ignoredKinds: ['payment-cap'],
174
181
  minimumMs: 0,
175
182
  zero: 'accept',
176
183
  hintClock: 'marker',
@@ -179,6 +186,9 @@ export const statusVaultOrder = immutable({
179
186
  kind: 'hint',
180
187
  mergeLaw: 'overwrite',
181
188
  defaultMs: 60000,
189
+ defaultMsByKind: { 'payment-balance': 300000 },
190
+ causes: ['rate-limit', 'payment-balance'],
191
+ ignoredKinds: ['payment-cap'],
182
192
  minimumMs: 0,
183
193
  zero: 'accept',
184
194
  hintClock: 'signal',
@@ -207,7 +217,14 @@ export const statusVaultOrder = immutable({
207
217
  },
208
218
  terminalMetadata: 'baseline',
209
219
  terminalPolicy: 'status-history',
210
- terminalStatusHistory: { minRetryMs: 1000, defaultRetryMs: 60000 },
220
+ terminalStatusHistory: {
221
+ minRetryMs: 1000,
222
+ defaultRetryMs: 60000,
223
+ paymentBalance: {
224
+ family: 'claustrum-402',
225
+ messageKey: 'payment.insufficient-balance',
226
+ },
227
+ },
211
228
  refusals: refusals({
212
229
  family: 'claustrum-429',
213
230
  messageKey: 'quota.accounts-rate-limited',
@@ -1,5 +1,6 @@
1
1
  import type { SessionActivityStore } from './activity.js';
2
2
  import type { IdentityBinding } from './identity.js';
3
+ import type { LimitMarkCause } from './marker.js';
3
4
  import type { LimitsCommand, LimitsNamespace } from './namespace.js';
4
5
  import type { LimitsPersistenceOutcome, PersistenceAdapter } from './persistence.js';
5
6
  export declare const LIMITS_REGISTRY_KEY: unique symbol;
@@ -45,5 +46,16 @@ export interface LimitsRegistry {
45
46
  reload(): Promise<void>;
46
47
  dispose(): Promise<void>;
47
48
  }
49
+ export type SuccessfulProbeClear = Omit<Extract<LimitsCommand, {
50
+ type: 'clear';
51
+ }>, 'type'> & {
52
+ readonly cause: LimitMarkCause;
53
+ readonly evidenceAt: number;
54
+ };
55
+ /** Publish a recovery fence even when expiry already removed the observed timer.
56
+ * Capture binding/baseRevision with observe before the probe; dispatch to that
57
+ * account joins the clear acknowledgment through beforeDispatch, not here.
58
+ */
59
+ export declare function clearLimitsAfterProbe(registry: LimitsRegistry, input: SuccessfulProbeClear): void;
48
60
  /** Shared owners use one journal/listener; a last-owner replacement waits for handoff. */
49
61
  export declare function acquireLimitsRegistry(options: LimitsRegistryOptions): Promise<LimitsRegistry>;
@@ -20,6 +20,13 @@ const clock = {
20
20
  },
21
21
  clearTimeout: (timer) => clearTimeout(timer),
22
22
  };
23
+ /** Publish a recovery fence even when expiry already removed the observed timer.
24
+ * Capture binding/baseRevision with observe before the probe; dispatch to that
25
+ * account joins the clear acknowledgment through beforeDispatch, not here.
26
+ */
27
+ export function clearLimitsAfterProbe(registry, input) {
28
+ registry.enqueue({ ...input, type: 'clear' }, 'success');
29
+ }
23
30
  function schemaRegistry() {
24
31
  for (const symbol of Object.getOwnPropertySymbols(globalThis)) {
25
32
  const key = Symbol.keyFor(symbol);
@@ -1,5 +1,5 @@
1
1
  import type { Scope } from './scope.js';
2
- import type { AccountKey } from './signal.js';
2
+ import type { AccountKey, LimitKind } from './signal.js';
3
3
  export declare function sameAccount(a: AccountKey, b: AccountKey): boolean;
4
4
  export interface RequestExclusion {
5
5
  readonly account: AccountKey;
@@ -17,6 +17,7 @@ export interface RequestHistory {
17
17
  readonly originalUrl: string;
18
18
  readonly requestStartedAt: number;
19
19
  readonly saw429: boolean;
20
+ readonly sawPaymentBalance?: boolean;
20
21
  readonly lastStatus?: number;
21
22
  readonly tried: readonly RequestExclusion[];
22
23
  readonly excludedForRequest: readonly RequestExclusion[];
@@ -38,6 +39,7 @@ export type RequestHistoryEvent = {
38
39
  readonly account: AccountKey;
39
40
  readonly scope: Scope;
40
41
  readonly status?: number;
42
+ readonly kind?: LimitKind;
41
43
  } | {
42
44
  readonly type: 'retain';
43
45
  readonly account: AccountKey;
@@ -45,6 +45,9 @@ export function reduceRequestHistory(history, event) {
45
45
  ...history,
46
46
  tried,
47
47
  saw429: history.saw429 || event.status === 429,
48
+ ...(event.kind === 'payment-balance'
49
+ ? { sawPaymentBalance: true }
50
+ : {}),
48
51
  lastStatus: event.status,
49
52
  };
50
53
  }
@@ -0,0 +1,13 @@
1
+ import type { AccountKey } from './signal.js';
2
+ /** Plugin-owned turn budgets, independent of individual logical request histories. */
3
+ export declare class UnconfirmedRetainCounter {
4
+ private readonly maxSessions;
5
+ private readonly sessions;
6
+ constructor(maxSessions?: number);
7
+ count(sessionId: string, turnId: string, account: AccountKey): number;
8
+ /** Call once after accepting a decision with incrementUnconfirmedRetain. */
9
+ increment(sessionId: string, turnId: string, account: AccountKey): void;
10
+ /** Clear on moves, API fallback and session lifecycle boundaries. */
11
+ clear(sessionId: string): void;
12
+ clearAll(): void;
13
+ }
@@ -0,0 +1,41 @@
1
+ import { sameAccount } from './request-history.js';
2
+ /** Plugin-owned turn budgets, independent of individual logical request histories. */
3
+ export class UnconfirmedRetainCounter {
4
+ maxSessions;
5
+ sessions = new Map();
6
+ constructor(maxSessions = 4096) {
7
+ this.maxSessions = maxSessions;
8
+ if (!Number.isSafeInteger(maxSessions) || maxSessions < 1)
9
+ throw new RangeError('maxSessions must be a positive safe integer');
10
+ }
11
+ count(sessionId, turnId, account) {
12
+ const entry = this.sessions.get(sessionId);
13
+ return entry?.turnId === turnId && sameAccount(entry.account, account)
14
+ ? entry.count
15
+ : 0;
16
+ }
17
+ /** Call once after accepting a decision with incrementUnconfirmedRetain. */
18
+ increment(sessionId, turnId, account) {
19
+ const count = this.count(sessionId, turnId, account);
20
+ if (!count) {
21
+ this.sessions.delete(sessionId);
22
+ if (this.sessions.size >= this.maxSessions) {
23
+ const oldest = this.sessions.keys().next().value;
24
+ if (oldest !== undefined)
25
+ this.sessions.delete(oldest);
26
+ }
27
+ }
28
+ this.sessions.set(sessionId, {
29
+ turnId,
30
+ account: { ...account },
31
+ count: count + 1,
32
+ });
33
+ }
34
+ /** Clear on moves, API fallback and session lifecycle boundaries. */
35
+ clear(sessionId) {
36
+ this.sessions.delete(sessionId);
37
+ }
38
+ clearAll() {
39
+ this.sessions.clear();
40
+ }
41
+ }
@@ -30,7 +30,8 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
30
30
  * - `retry` asks the host to retry at once when an account was refused
31
31
  * before any output and `chooseAccount` names another account for the
32
32
  * next attempt, keeps the host's decision when the refused account was the
33
- * last one that can serve, and refuses to retry once output has started.
33
+ * last one that can serve. After output, only a witnessed HTTP read failure
34
+ * with adapter-approved same-account continuation can keep the host's retry.
34
35
  *
35
36
  * Attribution. A send belongs to the attempt named by the mark
36
37
  * `model.request` left on it, so several attempts of one session and kind
@@ -101,7 +101,8 @@ function applyHeaderEditsTo(target, edits) {
101
101
  * - `retry` asks the host to retry at once when an account was refused
102
102
  * before any output and `chooseAccount` names another account for the
103
103
  * next attempt, keeps the host's decision when the refused account was the
104
- * last one that can serve, and refuses to retry once output has started.
104
+ * last one that can serve. After output, only a witnessed HTTP read failure
105
+ * with adapter-approved same-account continuation can keep the host's retry.
105
106
  *
106
107
  * Attribution. A send belongs to the attempt named by the mark
107
108
  * `model.request` left on it, so several attempts of one session and kind
@@ -471,6 +472,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
471
472
  await inChoiceOrder(scope.sessionID, () => releaseSameAccount(sameAccount));
472
473
  assertActive();
473
474
  }
475
+ if (sameAccount?.continuation &&
476
+ (!sameRoute || mixed(scope.sessionID))) {
477
+ if (sameRoute)
478
+ await inChoiceOrder(scope.sessionID, () => releaseSameAccount(sameAccount));
479
+ throw noAccount(scope);
480
+ }
474
481
  const choice = sameRoute
475
482
  ? sameAccount.accountId
476
483
  : matches && wake === undefined
@@ -796,7 +803,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
796
803
  error: describe(error),
797
804
  })));
798
805
  }
799
- response = new Response(trackBody(body, (error) => finish(rec, error)), {
806
+ response = new Response(trackBody(body, (error) => {
807
+ if (error?.reason === 'failed')
808
+ rec.httpReadFailed = true;
809
+ finish(rec, error);
810
+ }), {
800
811
  status: original.status,
801
812
  statusText: original.statusText,
802
813
  headers: original.headers,
@@ -936,9 +947,38 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
936
947
  const checkRetryActive = assertActive;
937
948
  const retrySameAccount = adapter.retrySameAccount?.bind(adapter);
938
949
  const handle = rec.attempt;
950
+ const afterOutput = rec.outputStarted;
951
+ if (afterOutput &&
952
+ rec.httpReadFailed &&
953
+ retrySameAccount &&
954
+ handle &&
955
+ !mixed(draft.sessionID)) {
956
+ if (!rec.limit) {
957
+ const signal = adapter.limitFromError?.(draft.error, handle);
958
+ if (signal)
959
+ noteLimit(rec, signal, 'error');
960
+ }
961
+ if (rec.ended)
962
+ await rec.ended;
963
+ if (rec.limit)
964
+ await rec.limit.delivered;
965
+ checkRetryActive();
966
+ }
967
+ // The host drops read-operation metadata from its retry error. Only
968
+ // our attributed body reader can prove a read failed; wording cannot.
969
+ const canContinue = () => rec.httpReadFailed === true &&
970
+ draft.error.type === 'provider.transport' &&
971
+ hostDecision.retry &&
972
+ hostRetryLimit - draft.attempt >= 1 &&
973
+ !rec.limit &&
974
+ !(rec.status !== undefined && rec.status >= 400) &&
975
+ !(draft.error.status !== undefined && draft.error.status >= 400) &&
976
+ !handle?.reboundFrom &&
977
+ !vetoed() &&
978
+ !mixed(draft.sessionID);
939
979
  if (retrySameAccount &&
940
980
  handle &&
941
- !rec.outputStarted &&
981
+ (!afterOutput || canContinue()) &&
942
982
  (!vetoed() || mixed(draft.sessionID)) &&
943
983
  !rec.sameAccountRetry) {
944
984
  if (rec.ended)
@@ -951,7 +991,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
951
991
  const active = () => attempts.has(rec.id) &&
952
992
  rec.accountId === accountId &&
953
993
  pickForRetry(draft.sessionID) === rec &&
954
- !rec.outputStarted &&
994
+ rec.outputStarted === afterOutput &&
995
+ (!afterOutput || canContinue()) &&
955
996
  (!vetoed() || mixed(draft.sessionID)) &&
956
997
  (!ownership ||
957
998
  latestTransportOwned.get(draft.sessionID) === true);
@@ -964,6 +1005,9 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
964
1005
  error: draft.error,
965
1006
  attempt: draft.attempt,
966
1007
  ...(rec.limit ? { limit: rec.limit.signal } : {}),
1008
+ ...(afterOutput
1009
+ ? { continuation: 'interrupted-read' }
1010
+ : {}),
967
1011
  };
968
1012
  let result;
969
1013
  try {
@@ -979,7 +1023,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
979
1023
  checkRetryActive();
980
1024
  return false;
981
1025
  }
982
- const sameAccount = { accountId: result.accountId, input };
1026
+ const sameAccount = {
1027
+ accountId: result.accountId,
1028
+ input,
1029
+ ...(afterOutput ? { continuation: true } : {}),
1030
+ };
983
1031
  try {
984
1032
  checkRetryActive();
985
1033
  }
@@ -1017,7 +1065,9 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1017
1065
  sameAccount,
1018
1066
  });
1019
1067
  rec.judged = true;
1020
- draft.decision = { retry: true, delay: 0 };
1068
+ draft.decision = afterOutput
1069
+ ? hostDecision
1070
+ : { retry: true, delay: 0 };
1021
1071
  return true;
1022
1072
  });
1023
1073
  checkRetryActive();
@@ -1027,7 +1077,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1027
1077
  accountId: rec.accountId,
1028
1078
  kind: rec.scope.kind,
1029
1079
  attempt: draft.attempt,
1030
- reason: 'same-account',
1080
+ reason: afterOutput ? 'continue-same-account' : 'same-account',
1031
1081
  hostDecision,
1032
1082
  decision: draft.decision,
1033
1083
  handle: rec.attempt,
@@ -1082,8 +1132,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1082
1132
  reason = 'no-account';
1083
1133
  }
1084
1134
  else if (rec.outputStarted) {
1085
- // The user has already seen part of this answer; a retry would
1086
- // send it again.
1135
+ // Only the guarded same-account path above may continue partial output.
1087
1136
  decision = { retry: false };
1088
1137
  reason = 'output-started';
1089
1138
  }
@@ -221,6 +221,14 @@ export interface SameAccountRetryInput extends AccountRequest {
221
221
  * limitFromError is not called before this callback in a mixed session.
222
222
  */
223
223
  readonly limit?: LimitSignal;
224
+ /**
225
+ * Set only when output had already started and our own HTTP body reader saw
226
+ * the read fail, so the host is offering to continue the step rather than
227
+ * retry it. The adapter approves by returning the same accountId when the
228
+ * account and identity are still usable; it has no prepared recovery state
229
+ * to consume, and `limit` is always absent here.
230
+ */
231
+ readonly continuation?: 'interrupted-read';
224
232
  }
225
233
  /** Request an immediate retry; a different account ID is ignored. */
226
234
  export interface SameAccountRetryResult {
@@ -437,7 +445,7 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
437
445
  * A different accountId is ignored. Never move a routing pin or select another
438
446
  * account here: use chooseAccount for failover and holds.
439
447
  *
440
- * Runs only for an attributable attempt before output, and, when gated, only
448
+ * Runs for an attributable attempt before output, and, when gated, only
441
449
  * while the latest transport is owned. Unlike failover and holds, it also runs
442
450
  * in mixed-ownership sessions. The next matching owned request skips selection
443
451
  * and calls accountHeaders again for this account, so newer credentials or a
@@ -449,6 +457,12 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
449
457
  * No choice was committed through chooseAccount; unused recovery state is
450
458
  * released through dropSameAccountRetry instead of dropChoice.
451
459
  * Errors are logged and treated as declining the retry.
460
+ * After output it also gates a host-approved continuation when the attributed
461
+ * HTTP body reader failed, no limit or veto exists, ownership is unmixed and
462
+ * the host retry budget remains. The host's decision and delay are preserved;
463
+ * the callback must decline if the account is no longer usable or its identity
464
+ * changed. Native WebSocket failures and clean but incomplete streams lack
465
+ * the structured host error fields needed to allow this exception.
452
466
  */
453
467
  retrySameAccount?(input: SameAccountRetryInput): Promise<SameAccountRetryResult | undefined> | SameAccountRetryResult | undefined;
454
468
  /**
@@ -526,7 +540,9 @@ export interface InstallOpenCode2AuthOptions {
526
540
  *
527
541
  * - `reroute`: refused for a limit before any output, and `chooseAccount`
528
542
  * named another account for the next attempt, so the host retries at once;
529
- * - `output-started`: output had reached the user, so no retry;
543
+ * - `output-started`: output reached the user without a safe continuation, so no retry;
544
+ * - `continue-same-account`: a witnessed HTTP read failure after output, with
545
+ * adapter-approved identity preservation; keeps the host's continuation and delay;
530
546
  * - `no-account`: the attempt had no account, so no retry;
531
547
  * - `host-decides-last-account`: refused for a limit before any output, but
532
548
  * no other account can serve the next attempt, so the host's own decision
@@ -541,7 +557,7 @@ export interface InstallOpenCode2AuthOptions {
541
557
  * attributed safely (ambiguous attempts or mixed ownership in a gated
542
558
  * session), so the host's decision stands.
543
559
  */
544
- export type RetryReason = 'reroute' | 'hold' | 'wait-then-reselect' | 'adapter-veto' | 'same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
560
+ export type RetryReason = 'reroute' | 'hold' | 'wait-then-reselect' | 'adapter-veto' | 'same-account' | 'continue-same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
545
561
  /**
546
562
  * The hook that picked an account. Normally `model.request`; a transport hook
547
563
  * picks only when the host skipped `model.request` for that request, which a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.34.0",
3
+ "version": "0.36.0",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {