@cortexkit/opencode-antigravity-auth 3.0.28 → 3.0.30

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 (179) hide show
  1. package/dist/cli.js +689 -183
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +131 -68
  4. package/dist/index.js +844 -199
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +173 -76
  7. package/dist/server.js +855 -213
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +1 -0
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +22 -2
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +36 -0
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +74 -9
  18. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  19. package/dist/src/common-auth-embedded/claustrum/hub.js +8 -0
  20. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  21. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +2 -0
  23. package/dist/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  24. package/dist/src/common-auth-embedded/claustrum/usage.js +145 -0
  25. package/dist/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  26. package/dist/src/common-auth-embedded/commands/builtins.js +38 -0
  27. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  28. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  29. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  30. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  31. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  32. package/dist/src/common-auth-embedded/limits/axes.d.ts +63 -0
  33. package/dist/src/common-auth-embedded/limits/decide.d.ts +141 -0
  34. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  35. package/dist/src/common-auth-embedded/limits/families.d.ts +57 -0
  36. package/dist/src/common-auth-embedded/limits/marker.d.ts +64 -0
  37. package/dist/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  38. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  39. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  40. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  41. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  42. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  43. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  44. package/dist/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  45. package/dist/src/common-auth-embedded/opencode2/install.js +161 -18
  46. package/dist/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  47. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  48. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  49. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  50. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  51. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  52. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  53. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  54. package/dist/src/common-auth-embedded/source-output.json +254 -118
  55. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  56. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  57. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  58. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  59. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  60. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  61. package/dist/src/common-auth-embedded/store/limits-namespace.js +34 -0
  62. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  63. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  64. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  65. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  66. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  67. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  68. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  69. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  70. package/dist/src/plugin/shared/request-services.d.ts +14 -18
  71. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  72. package/dist/src/plugin/shared/request-services.js +127 -7
  73. package/dist/src/plugin/shared/request-services.js.map +1 -1
  74. package/dist/src/runtime-layout.d.ts +9 -2
  75. package/dist/src/runtime-layout.d.ts.map +1 -1
  76. package/dist/src/runtime-layout.js +8 -8
  77. package/dist/src/runtime-layout.js.map +1 -1
  78. package/dist/src/setup.d.ts.map +1 -1
  79. package/dist/src/setup.js +29 -40
  80. package/dist/src/setup.js.map +1 -1
  81. package/dist/tui-build-map.json +9 -9
  82. package/dist/tui-ga-build-map.json +1 -1
  83. package/dist/types/src/cli.d.ts +1 -0
  84. package/dist/types/src/cli.d.ts.map +1 -1
  85. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  86. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  87. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  88. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  89. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  90. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  91. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  92. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  93. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +63 -0
  94. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +141 -0
  95. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  96. package/dist/types/src/common-auth-embedded/limits/families.d.ts +57 -0
  97. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +64 -0
  98. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  99. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  100. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  101. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  102. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  103. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  104. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  105. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  106. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  107. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  108. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  109. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  110. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  111. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  112. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  113. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  114. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  115. package/dist/types/src/plugin/shared/request-services.d.ts +14 -18
  116. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  117. package/dist/types/src/runtime-layout.d.ts +9 -2
  118. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  119. package/dist/types/src/setup.d.ts.map +1 -1
  120. package/package.json +2 -2
  121. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  122. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  123. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  124. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  125. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  126. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  127. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  128. package/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  129. package/src/common-auth-embedded/claustrum/roster.js +2 -0
  130. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  131. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  132. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  133. package/src/common-auth-embedded/commands/builtins.js +38 -0
  134. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  135. package/src/common-auth-embedded/fs/private-files.js +7 -0
  136. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  137. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  138. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  139. package/src/common-auth-embedded/limits/axes.d.ts +63 -0
  140. package/src/common-auth-embedded/limits/decide.d.ts +141 -0
  141. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  142. package/src/common-auth-embedded/limits/families.d.ts +57 -0
  143. package/src/common-auth-embedded/limits/marker.d.ts +64 -0
  144. package/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  145. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  146. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  147. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  148. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  149. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  150. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  151. package/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  152. package/src/common-auth-embedded/opencode2/install.js +161 -18
  153. package/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  154. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  155. package/src/common-auth-embedded/routing/admission.js +17 -7
  156. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  157. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  158. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  159. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  160. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  161. package/src/common-auth-embedded/source-output.json +254 -118
  162. package/src/common-auth-embedded/store/attribution.js +3 -2
  163. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  164. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  165. package/src/common-auth-embedded/store/hooks.js +20 -5
  166. package/src/common-auth-embedded/store/index.d.ts +1 -0
  167. package/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  168. package/src/common-auth-embedded/store/limits-namespace.js +34 -0
  169. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  170. package/src/common-auth-embedded/store/pool.js +2 -0
  171. package/src/common-auth-embedded/store/provider-state.js +5 -5
  172. package/src/common-auth-embedded/store/refresh.js +1 -1
  173. package/src/common-auth-embedded/store/schema.js +9 -4
  174. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  175. package/src/common-auth-embedded/store/settings.js +11 -4
  176. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  177. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  178. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  179. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +46 -4
@@ -2,8 +2,8 @@ import { OpenCode2AuthError } from './errors.js';
2
2
  import { placeholderSecret } from './integration.js';
3
3
  import { watchServerSentEvents } from './sse.js';
4
4
  export const DEFAULT_MAX_RECORDS = 512;
5
- /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
6
- export const MAX_RETRY_HOLD_MS = 20 * 60 * 1000;
5
+ /** Allow a one-hour cache lifetime plus the maximum session jitter. */
6
+ export const MAX_RETRY_HOLD_MS = 3_621_000;
7
7
  /**
8
8
  * The request header `model.request` sets to the attempt it started. The
9
9
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -134,6 +134,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
134
134
  ownership.credential(headers) === placeholderSecret(providerID);
135
135
  const logger = options.logger;
136
136
  const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
137
+ const hostRetryLimit = options.hostRetryLimit ?? 10;
137
138
  const forbidden = [
138
139
  ...(options.hostCredentials ?? [placeholderSecret(providerID)]),
139
140
  // An owned request must replace its placeholder even if a caller customizes
@@ -203,6 +204,21 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
203
204
  catch { }
204
205
  };
205
206
  const describe = (error) => error instanceof Error ? error.message : String(error);
207
+ const retireRequest = (request) => request.excluded.clear();
208
+ const exclusions = (request) => request.excluded.size === 0 ? {} : { excluded: [...request.excluded] };
209
+ const rejectsExcluded = (accountId, input, request) => {
210
+ if (!options.enforceRequestExclusion ||
211
+ accountId === undefined ||
212
+ !request.excluded.has(accountId))
213
+ return false;
214
+ warn('opencode2 auth ignored a chooser result for a request-excluded account', {
215
+ sessionID: input.sessionID,
216
+ kind: input.kind,
217
+ phase: input.phase,
218
+ accountId,
219
+ });
220
+ return true;
221
+ };
206
222
  // Adapter choices may enqueue work by session. Serialize their consumption
207
223
  // and release so a new choice cannot overtake cleanup, even after forgetting.
208
224
  const choiceWork = new Map();
@@ -296,6 +312,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
296
312
  };
297
313
  if (error)
298
314
  rec.endError = error;
315
+ // An error status can end before retry runs, and a limit may have arrived
316
+ // on an earlier event. Neither is a successful logical request.
317
+ if (error?.reason === 'cancelled' ||
318
+ (!error && !rec.limit && (rec.status === undefined || rec.status < 400)))
319
+ retireRequest(rec.request);
299
320
  rec.ended = deliverEnd(rec.attempt, outcome);
300
321
  };
301
322
  const abandon = (rec, message) => finish(rec, { reason: 'abandoned', message });
@@ -399,10 +420,28 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
399
420
  };
400
421
  const select = async (scope, hook, assertActive, transport) => {
401
422
  const key = keyOf(scope.sessionID, scope.kind);
402
- const { input, accountId, sameAccountRetry } = await afterChoiceWork(scope.sessionID, async () => {
423
+ const { input, accountId, sameAccountRetry, request } = await afterChoiceWork(scope.sessionID, async () => {
403
424
  assertActive();
404
425
  const retried = pendingRetries.get(key);
405
426
  pendingRetries.delete(key);
427
+ const others = attemptsOf(key);
428
+ if (retried &&
429
+ others.some((rec) => rec.id !== retried.attemptId && rec.attempt && !rec.ended))
430
+ warn('opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions', {
431
+ sessionID: scope.sessionID,
432
+ kind: scope.kind,
433
+ });
434
+ if (!retried) {
435
+ // A failed attempt that the host never retried must not seed the next
436
+ // logical request. Live attempts keep their own independent tokens.
437
+ const live = new Set(others
438
+ .filter((rec) => rec.attempt && !rec.ended)
439
+ .map((rec) => rec.request));
440
+ for (const rec of others)
441
+ if (!live.has(rec.request))
442
+ retireRequest(rec.request);
443
+ }
444
+ const request = retried?.request ?? { excluded: new Set() };
406
445
  const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
407
446
  supersede(key);
408
447
  const next = retried?.next;
@@ -413,13 +452,18 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
413
452
  const matches = next !== undefined &&
414
453
  next.input.modelID === scope.modelID &&
415
454
  next.input.agent === scope.agent;
455
+ const wake = retried?.wake;
416
456
  const input = {
417
457
  ...scope,
418
458
  phase: 'request',
459
+ ...exclusions(request),
419
460
  ...(previousAccountId === undefined ? {} : { previousAccountId }),
420
461
  ...(retried?.rerouteFrom ? { rerouteFrom: retried.rerouteFrom } : {}),
462
+ ...(wake === undefined
463
+ ? {}
464
+ : { wake, hostAttempt: next?.input.hostAttempt }),
421
465
  };
422
- if (next && !matches) {
466
+ if (next && (!matches || wake !== undefined)) {
423
467
  await inChoiceOrder(scope.sessionID, () => releaseChoice(next));
424
468
  assertActive();
425
469
  }
@@ -429,11 +473,20 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
429
473
  }
430
474
  const choice = sameRoute
431
475
  ? sameAccount.accountId
432
- : matches
476
+ : matches && wake === undefined
433
477
  ? next.accountId
434
478
  : await adapter.chooseAccount(input);
435
- const accountId = typeof choice === 'string' ? choice : undefined;
436
- return { input, accountId, sameAccountRetry: sameRoute };
479
+ let accountId = typeof choice === 'string' ? choice : undefined;
480
+ if (rejectsExcluded(accountId, input, request)) {
481
+ const denied = accountId;
482
+ if (sameRoute && sameAccount)
483
+ await inChoiceOrder(scope.sessionID, () => releaseSameAccount(sameAccount));
484
+ else if (denied !== undefined)
485
+ await inChoiceOrder(scope.sessionID, () => releaseChoice(matches && next ? next : { accountId: denied, input }));
486
+ accountId = undefined;
487
+ assertActive();
488
+ }
489
+ return { input, accountId, sameAccountRetry: sameRoute, request };
437
490
  });
438
491
  assertActive();
439
492
  let headers = {};
@@ -454,6 +507,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
454
507
  id,
455
508
  key,
456
509
  scope,
510
+ request,
457
511
  accountId,
458
512
  headers,
459
513
  attempt: accountId === undefined
@@ -577,6 +631,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
577
631
  noteQuota(rec, transport, verdict.quota);
578
632
  if (verdict.outputStarted)
579
633
  rec.outputStarted = true;
634
+ if (verdict.hostRetry === 'veto')
635
+ rec.hostRetry = 'veto';
580
636
  if (verdict.limit)
581
637
  noteLimit(rec, verdict.limit, transport);
582
638
  if (verdict.error !== undefined)
@@ -747,13 +803,23 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
747
803
  });
748
804
  }
749
805
  if (adapter.rewriteResponse) {
750
- response =
751
- (await adapter.rewriteResponse({
752
- ...account,
753
- request: draft.request,
754
- response,
755
- attempt,
756
- })) ?? response;
806
+ const rewritten = await adapter.rewriteResponse({
807
+ ...account,
808
+ request: draft.request,
809
+ response,
810
+ attempt,
811
+ });
812
+ response = rewritten ?? response;
813
+ }
814
+ if (adapter.responseRetry) {
815
+ const disposition = await adapter.responseRetry({
816
+ ...account,
817
+ request: draft.request,
818
+ response,
819
+ attempt,
820
+ });
821
+ if (disposition === 'veto')
822
+ rec.hostRetry = 'veto';
757
823
  }
758
824
  if (response !== original)
759
825
  draft.response = response;
@@ -865,6 +931,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
865
931
  return;
866
932
  }
867
933
  const rec = picked;
934
+ const vetoed = () => rec.hostRetry === 'veto';
868
935
  await withSelection(rec.scope, async (assertActive) => {
869
936
  const checkRetryActive = assertActive;
870
937
  const retrySameAccount = adapter.retrySameAccount?.bind(adapter);
@@ -872,6 +939,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
872
939
  if (retrySameAccount &&
873
940
  handle &&
874
941
  !rec.outputStarted &&
942
+ (!vetoed() || mixed(draft.sessionID)) &&
875
943
  !rec.sameAccountRetry) {
876
944
  if (rec.ended)
877
945
  await rec.ended;
@@ -884,6 +952,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
884
952
  rec.accountId === accountId &&
885
953
  pickForRetry(draft.sessionID) === rec &&
886
954
  !rec.outputStarted &&
955
+ (!vetoed() || mixed(draft.sessionID)) &&
887
956
  (!ownership ||
888
957
  latestTransportOwned.get(draft.sessionID) === true);
889
958
  if (!active() || rec.sameAccountRetry)
@@ -940,6 +1009,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
940
1009
  // Pin only this retry's route: choosing afresh could turn a token
941
1010
  // refresh or path recovery into an account switch in a mixed session.
942
1011
  pendingRetries.set(rec.key, {
1012
+ request: rec.request,
943
1013
  attemptId: rec.id,
944
1014
  sessionID: rec.scope.sessionID,
945
1015
  order: ++retryOrder,
@@ -1006,6 +1076,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1006
1076
  let reason;
1007
1077
  let rerouteFrom;
1008
1078
  let next;
1079
+ let wake;
1009
1080
  if (rec.accountId === undefined || !attempt) {
1010
1081
  decision = { retry: false };
1011
1082
  reason = 'no-account';
@@ -1016,6 +1087,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1016
1087
  decision = { retry: false };
1017
1088
  reason = 'output-started';
1018
1089
  }
1090
+ else if (vetoed()) {
1091
+ // Refusals formatted by the adapter carry policy on the attributed attempt,
1092
+ // not in message wording or a session-wide flag.
1093
+ decision = { retry: false };
1094
+ reason = 'adapter-veto';
1095
+ }
1019
1096
  else {
1020
1097
  if (rec.limit) {
1021
1098
  const refused = {
@@ -1032,6 +1109,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1032
1109
  const input = {
1033
1110
  ...rec.scope,
1034
1111
  phase: 'retry',
1112
+ ...exclusions(rec.request),
1113
+ hostAttempt: draft.attempt,
1035
1114
  previousAccountId: rec.accountId,
1036
1115
  rerouteFrom: refused,
1037
1116
  };
@@ -1046,7 +1125,25 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1046
1125
  error: describe(error),
1047
1126
  });
1048
1127
  }
1049
- const hold = typeof choice === 'object' ? choice.hold : undefined;
1128
+ const chosenAccount = typeof choice === 'string'
1129
+ ? choice
1130
+ : typeof choice === 'object' && 'hold' in choice
1131
+ ? rec.accountId
1132
+ : undefined;
1133
+ if (rejectsExcluded(chosenAccount, input, rec.request)) {
1134
+ if (chosenAccount !== undefined)
1135
+ await releaseChoice({ accountId: chosenAccount, input });
1136
+ choice = undefined;
1137
+ }
1138
+ const hold = typeof choice === 'object' && 'hold' in choice
1139
+ ? choice.hold
1140
+ : undefined;
1141
+ const wait = typeof choice === 'object' && 'waitThenReselect' in choice
1142
+ ? choice.waitThenReselect
1143
+ : undefined;
1144
+ const disposition = typeof choice === 'object' && 'hostRetry' in choice
1145
+ ? choice.hostRetry
1146
+ : undefined;
1050
1147
  const accountId = typeof choice === 'string'
1051
1148
  ? choice
1052
1149
  : hold
@@ -1073,21 +1170,61 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1073
1170
  reason: 'host-decides',
1074
1171
  };
1075
1172
  }
1076
- if (hold &&
1173
+ if (vetoed() || disposition === 'veto') {
1174
+ if (next)
1175
+ await releaseChoice(next);
1176
+ next = undefined;
1177
+ checkRetryActive();
1178
+ if (mixed(draft.sessionID))
1179
+ return {
1180
+ decision: hostDecision,
1181
+ reason: 'host-decides',
1182
+ };
1183
+ rec.hostRetry = 'veto';
1184
+ decision = { retry: false };
1185
+ reason = 'adapter-veto';
1186
+ }
1187
+ else if (!(hostRetryLimit - draft.attempt >= 1)) {
1188
+ if (next)
1189
+ await releaseChoice(next);
1190
+ next = undefined;
1191
+ reason = 'host-decides-last-account';
1192
+ }
1193
+ else if (wait &&
1194
+ Number.isFinite(wait.delayMs) &&
1195
+ wait.delayMs >= 0 &&
1196
+ wait.delayMs <= MAX_RETRY_HOLD_MS) {
1197
+ // Only the failed attempt's context is kept. No next choice
1198
+ // exists to dispatch or release when the host wakes or cancels.
1199
+ decision = { retry: true, delay: Math.ceil(wait.delayMs) };
1200
+ reason = 'wait-then-reselect';
1201
+ }
1202
+ else if (hold &&
1077
1203
  Number.isFinite(hold.delayMs) &&
1078
- hold.delayMs >= 0) {
1204
+ hold.delayMs >= 0 &&
1205
+ hold.delayMs <= MAX_RETRY_HOLD_MS) {
1079
1206
  // A recognised account limit can be recoverable even when
1080
1207
  // the host treats its provider error as final.
1081
1208
  decision = {
1082
1209
  retry: true,
1083
- delay: Math.min(hold.delayMs, MAX_RETRY_HOLD_MS),
1210
+ delay: Math.ceil(hold.delayMs),
1084
1211
  };
1212
+ if (hold.target !== undefined) {
1213
+ wake = {
1214
+ target: hold.target,
1215
+ ...(hold.checkpoint === undefined
1216
+ ? {}
1217
+ : { checkpoint: hold.checkpoint }),
1218
+ ...(hold.kind === undefined ? {} : { kind: hold.kind }),
1219
+ };
1220
+ }
1085
1221
  reason = 'hold';
1086
1222
  }
1087
1223
  else if (!hold &&
1088
1224
  accountId !== undefined &&
1089
1225
  accountId !== rec.accountId) {
1090
1226
  rec.rerouted = true;
1227
+ rec.request.excluded.add(rec.accountId);
1091
1228
  rerouteFrom = refused;
1092
1229
  // The next attempt takes this choice rather than asking
1093
1230
  // again, so an account limited between here and the host's
@@ -1121,12 +1258,14 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1121
1258
  rec.accountId !== undefined &&
1122
1259
  attempts.has(rec.id)) {
1123
1260
  pendingRetries.set(rec.key, {
1261
+ request: rec.request,
1124
1262
  attemptId: rec.id,
1125
1263
  sessionID: rec.scope.sessionID,
1126
1264
  order: ++retryOrder,
1127
1265
  accountId: rec.accountId,
1128
1266
  ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
1129
1267
  ...(next === undefined ? {} : { next }),
1268
+ ...(wake === undefined ? {} : { wake }),
1130
1269
  });
1131
1270
  }
1132
1271
  else if (next) {
@@ -1134,6 +1273,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1134
1273
  // have been overridden by a reroute to another account.
1135
1274
  await releaseChoice(next);
1136
1275
  }
1276
+ if (!decision.retry)
1277
+ retireRequest(rec.request);
1137
1278
  return { decision, reason };
1138
1279
  });
1139
1280
  checkRetryActive();
@@ -1166,6 +1307,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1166
1307
  if (rec.scope.sessionID !== sessionID)
1167
1308
  continue;
1168
1309
  abandon(rec, 'its session was forgotten');
1310
+ retireRequest(rec.request);
1169
1311
  attempts.delete(rec.id);
1170
1312
  }
1171
1313
  for (const [key, pending] of pendingRetries) {
@@ -1192,6 +1334,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1192
1334
  if (pending.sessionID === sessionID &&
1193
1335
  pending.order < idleOrder) {
1194
1336
  pendingRetries.delete(key);
1337
+ retireRequest(pending.request);
1195
1338
  await releaseRetry(pending);
1196
1339
  }
1197
1340
  }
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from '@opencode/plugin';
2
2
  import type { SessionRequestKind, SessionRetryDecision } from '@opencode/plugin/promise/session';
3
+ import type { WaitCheckpoint } from '../limits/decide.js';
3
4
  /** The parts of the OpenCode 2 plugin context the installer uses. */
4
5
  export type OpenCode2HookContext = {
5
6
  readonly session: Pick<Plugin.Context['session'], 'hook'>;
@@ -35,6 +36,8 @@ export interface EventVerdict<Q> {
35
36
  readonly outputStarted?: boolean;
36
37
  readonly quota?: Q;
37
38
  readonly limit?: LimitSignal;
39
+ /** Applies only to this attempt, after ownership and attribution checks. */
40
+ readonly hostRetry?: RetryDisposition['hostRetry'];
38
41
  /**
39
42
  * This is the last event of the response (completed or failed); the
40
43
  * attempt ends here. On WebSocket this is the only way an attempt ends
@@ -55,6 +58,16 @@ export type HeaderEdits = Readonly<Record<string, string | null>>;
55
58
  export interface ChooseAccountInput extends RequestScope {
56
59
  /** The retry hook's advance choice (which may hold), or a request's own choice. */
57
60
  readonly phase: 'retry' | 'request';
61
+ /** Retry hook draft's attempt count; also carried by a consumed hold's wake. */
62
+ readonly hostAttempt?: number;
63
+ /** Revalidate the held account before dispatch, even if the target is not due. */
64
+ readonly wake?: RetryWake;
65
+ /**
66
+ * Accounts refused by earlier reroutes of this logical request. Absent means
67
+ * empty. Holds and wakes do not exclude the held account. A snapshot, not a
68
+ * live set; supplied whether or not enforcement is enabled.
69
+ */
70
+ readonly excluded?: readonly string[];
58
71
  /**
59
72
  * The account of the attempt this one retries, when the retry hook just
60
73
  * asked the host to retry an attempt of this session and kind; otherwise
@@ -75,19 +88,43 @@ export interface ChooseAccountInput extends RequestScope {
75
88
  export interface AccountRequest extends RequestScope {
76
89
  readonly accountId: string;
77
90
  }
91
+ /** The held account is ChooseAccountInput.previousAccountId. */
92
+ export interface RetryWake {
93
+ readonly target: number;
94
+ readonly checkpoint?: WaitCheckpoint;
95
+ /** Terminal quota waits do not require the session's provider prompt-cache TTL. */
96
+ readonly kind?: 'hold' | 'terminal';
97
+ }
78
98
  /** An explicit retry on the refused account, without moving its routing pin. */
79
99
  export interface RetryHold {
80
100
  readonly hold: {
81
101
  /**
82
102
  * Adapter-computed wait in milliseconds, including per-session jitter.
83
- * Finite, non-negative values are clamped to MAX_RETRY_HOLD_MS (20 minutes).
84
- * Invalid values keep the host's decision and release the choice.
103
+ * Finite, non-negative values up to MAX_RETRY_HOLD_MS (3_621_000) are
104
+ * accepted. Larger or invalid values keep the host's decision and release
105
+ * the choice rather than dispatching before the requested wait has elapsed.
85
106
  */
86
107
  readonly delayMs: number;
108
+ /** An absolute wake target; its presence forces a request-phase re-check. */
109
+ readonly target?: number;
110
+ readonly checkpoint?: WaitCheckpoint;
111
+ /** Forwarded to wake.kind so terminal quota waits omit the cache bound. */
112
+ readonly kind?: RetryWake['kind'];
87
113
  };
88
114
  }
89
- /** Holds are valid only in phase `retry`, with a recognised account limit. */
90
- export type ChooseAccountResult = string | RetryHold | undefined;
115
+ /** Leave the host's retry decision alone, or forbid replay of this attempt. */
116
+ export interface RetryDisposition {
117
+ readonly hostRetry: 'leave' | 'veto';
118
+ }
119
+ /** Wait through one host retry, then choose afresh without reserving an account. */
120
+ export interface RetryWaitThenReselect {
121
+ readonly waitThenReselect: {
122
+ /** Same finite, non-negative delay bound as RetryHold.hold.delayMs. */
123
+ readonly delayMs: number;
124
+ };
125
+ }
126
+ /** Non-string choices are valid only in phase `retry`, after an account limit. */
127
+ export type ChooseAccountResult = string | RetryHold | RetryDisposition | RetryWaitThenReselect | undefined;
91
128
  /**
92
129
  * One physical send: created when an account is chosen for a request, and
93
130
  * handed back on every hook call and event that belongs to that send, so a
@@ -194,7 +231,7 @@ export interface SameAccountRetryResult {
194
231
  * quota reading type; the installer only carries it to the `quota` event.
195
232
  * `A` is the plugin's per-attempt value (see `Attempt`).
196
233
  * `Choice` defaults to the legacy ID-only result so existing adapters' direct
197
- * callers still see IDs. Opt into holds with `ChooseAccountResult`.
234
+ * callers still see IDs. Opt into retry directives with `ChooseAccountResult`.
198
235
  */
199
236
  export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends ChooseAccountResult = string | undefined> {
200
237
  /** Every hook is scoped to this provider; other providers are untouched. */
@@ -209,11 +246,24 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
209
246
  * After a limit before any output, the retry hook makes this call itself,
210
247
  * with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
211
248
  * including the refused one, is kept for the next attempt of that session
212
- * and kind: it does not choose again. Another account retries at once;
249
+ * and kind: it does not choose again, except for a hold with a target.
250
+ * Another account retries at once;
213
251
  * the refused account keeps the host's decision and wait. `{ hold: { delayMs } }`
214
252
  * commits the refused account without changing its pin and replaces the host's
215
253
  * wait, even its no-retry decision, only for a recognised account limit before
216
- * output in an untainted session. Holds returned in phase `request` cannot
254
+ * output in a session with no foreign transport. A hold with a target releases its queued
255
+ * choice and calls again in phase `request` with `wake` and `hostAttempt`
256
+ * before fetching account headers. The adapter must check that the account
257
+ * is still eligible, still represents the same login, is still available
258
+ * from the credential store and has any required provider prompt-cache TTL
259
+ * remaining, then choose normally if invalid.
260
+ * A hold without a target takes the queued account as before.
261
+ * `{ hostRetry: 'veto' }` forbids replay; `'leave'` preserves the host's decision
262
+ * without reserving an account. `{ waitThenReselect: { delayMs } }` asks for one
263
+ * delayed host retry, then chooses afresh. It commits no account or routing pin.
264
+ * Like holds, its delay must fit MAX_RETRY_HOLD_MS and the host retry budget.
265
+ * These directives obey the same ownership, attribution and output fences.
266
+ * Non-string choices returned in phase `request` cannot
217
267
  * select an account and are treated as undefined. `undefined` or a
218
268
  * throw commits nothing: the host decides, and the next attempt chooses
219
269
  * with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
@@ -222,7 +272,8 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
222
272
  /**
223
273
  * Releases a kept retry choice that will not be used: no retry, a changed
224
274
  * model or agent, cancellation of a queued retry (session idle), session forgetting/deletion,
225
- * disposal or record eviction. A hold releases the refused account's choice.
275
+ * disposal, record eviction or a targeted hold's wake re-check. A hold
276
+ * releases the refused account's choice.
226
277
  * Called once with the original choose input plus its returned accountId,
227
278
  * never for a used choice. Awaited before any later chooseAccount for the
228
279
  * same session; errors are logged and swallowed. A model/agent change
@@ -264,6 +315,21 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
264
315
  readonly response: Response;
265
316
  readonly attempt: Attempt<A>;
266
317
  }): Promise<Response | undefined> | Response | undefined;
318
+ /**
319
+ * Optional retry policy for the final HTTP response. Runs immediately after
320
+ * `rewriteResponse` (or on the unchanged response when no rewrite is returned).
321
+ * Return `veto` to forbid host replay of a refusal the adapter formatted,
322
+ * even without a recognised limit. A veto is sticky for this attempt.
323
+ * Ownership and attribution checks still run first: a veto cannot affect a
324
+ * foreign request, a session with mixed ownership, or a retry whose attempt is
325
+ * ambiguous. `leave` or `undefined` preserves the existing retry policy,
326
+ * including an earlier veto.
327
+ */
328
+ responseRetry?(input: AccountRequest & {
329
+ readonly request: Request;
330
+ readonly response: Response;
331
+ readonly attempt: Attempt<A>;
332
+ }): Promise<'leave' | 'veto' | undefined> | 'leave' | 'veto' | undefined;
267
333
  /**
268
334
  * Optional. For an adapter whose own sender can move a request to another
269
335
  * account after `rewriteRequest` (a bridge that answers a 401 or 403 by
@@ -435,6 +501,24 @@ export interface InstallOpenCode2AuthOptions {
435
501
  readonly hostCredentials?: readonly string[];
436
502
  /** Most attempts kept before the oldest is abandoned and dropped. */
437
503
  readonly maxRecords?: number;
504
+ /**
505
+ * Host retry budget, default 10. When hostAttempt leaves no retry available,
506
+ * limit holds and reroutes keep the host's decision and release their choice.
507
+ */
508
+ readonly hostRetryLimit?: number;
509
+ /**
510
+ * Reject chooser results naming a request-excluded account (default false).
511
+ * A rejected choice warns and acts like undefined: the host decides in retry,
512
+ * and request selection stops with no-account. Without this option, chooser
513
+ * results retain their existing meaning.
514
+ *
515
+ * The host supplies no logical request id. The first later attempt of the
516
+ * same session and kind consumes a queued retry's exclusions. If another
517
+ * attempt is in flight, that binding warns but keeps the exclusions. A new
518
+ * concurrent request can therefore inherit them; if it consumes the retry
519
+ * first, the actual retry instead starts a fresh token without them.
520
+ */
521
+ readonly enforceRequestExclusion?: boolean;
438
522
  readonly logger?: OpenCode2AuthLogger;
439
523
  }
440
524
  /**
@@ -449,13 +533,15 @@ export interface InstallOpenCode2AuthOptions {
449
533
  * (its wait, or its refusal to retry) stands and the next attempt may go
450
534
  * to the refused account again;
451
535
  * - `hold`: an explicit adapter wait on the refused account, before output;
536
+ * - `wait-then-reselect`: wait without reserving the next account;
537
+ * - `adapter-veto`: the attributed adapter disposition forbids host replay;
452
538
  * - `same-account`: the adapter requested immediate recovery on the same route,
453
539
  * without account selection, before output;
454
540
  * - `host-decides`: no limit was recognised, or the failing call cannot be
455
541
  * attributed safely (ambiguous attempts or mixed ownership in a gated
456
542
  * session), so the host's decision stands.
457
543
  */
458
- export type RetryReason = 'reroute' | 'hold' | 'same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
544
+ export type RetryReason = 'reroute' | 'hold' | 'wait-then-reselect' | 'adapter-veto' | 'same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
459
545
  /**
460
546
  * The hook that picked an account. Normally `model.request`; a transport hook
461
547
  * picks only when the host skipped `model.request` for that request, which a
@@ -23,11 +23,16 @@ export interface AdmissionInput extends ExclusionInputs {
23
23
  scope?: string;
24
24
  /** Labels the scope requires an entry for; defaults to `['primary']`. */
25
25
  requiredLabels?: readonly string[];
26
+ /**
27
+ * One-dispatch exemptions keyed by row; waive only gate 4. The caller first
28
+ * validates the current account incarnation and checkpointed reset times.
29
+ */
30
+ liftedWindows?: ReadonlyMap<string, readonly WindowRef[]>;
26
31
  now: number;
27
32
  /**
28
- * Called synchronously, once per refusal at gates 2 to 4, with the row id.
33
+ * Called synchronously once per row needing a pull, including lifted windows.
29
34
  * Its return value is ignored and never awaited, so a pull the caller
30
- * starts from here cannot delay the refusal.
35
+ * starts from here cannot delay admission or a refusal.
31
36
  */
32
37
  requestPull?: (rowId: string) => void;
33
38
  }
@@ -14,7 +14,7 @@
14
14
  // 3. a required label with no entry is unknown: refused, pull requested;
15
15
  // 4. a reading at or beyond 100% whose reset is missing, unparsable or not
16
16
  // after `now` cannot confirm the exhaustion, so the window is unknown:
17
- // refused, pull requested;
17
+ // refused unless lifted for this wake dispatch; either way, pull requested;
18
18
  // 5. a reading at or beyond 100% with a future reset is exhausted: refused.
19
19
  // Gates 4 and 5 look at every projected limit, not only the required labels.
20
20
  // Stage 2 judges the credit budget across the stage-1 survivors: a row whose
@@ -36,7 +36,7 @@ export function exclusionFor(id, inputs, now) {
36
36
  }
37
37
  return undefined;
38
38
  }
39
- function judgeStageOne(id, projection, requiredLabels, now) {
39
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
40
40
  if (projection.limits.length === 0) {
41
41
  return {
42
42
  id,
@@ -60,7 +60,8 @@ function judgeStageOne(id, projection, requiredLabels, now) {
60
60
  }
61
61
  const exhausted = projection.limits.filter(readsExhausted);
62
62
  for (const limit of exhausted) {
63
- if (futureResetAt(limit, now) === undefined) {
63
+ if (futureResetAt(limit, now) === undefined &&
64
+ !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
64
65
  return {
65
66
  id,
66
67
  stage: 1,
@@ -94,6 +95,7 @@ export function admit(input) {
94
95
  const excluded = [];
95
96
  const refused = [];
96
97
  const survivors = [];
98
+ const needsPull = new Set();
97
99
  for (const row of input.rows) {
98
100
  const exclusion = exclusionFor(row.id, input, input.now);
99
101
  if (exclusion) {
@@ -105,7 +107,12 @@ export function admit(input) {
105
107
  continue;
106
108
  }
107
109
  const projection = projectQuota(row.quota, scope);
108
- const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now);
110
+ const lifted = input.liftedWindows?.get(row.id) ?? [];
111
+ if (projection.limits.some((limit) => readsExhausted(limit) &&
112
+ futureResetAt(limit, input.now) === undefined &&
113
+ lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
114
+ needsPull.add(row.id);
115
+ const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now, lifted);
109
116
  if (refusal) {
110
117
  refused.push(refusal);
111
118
  continue;
@@ -133,9 +140,12 @@ export function admit(input) {
133
140
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
134
141
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
135
142
  refused.sort(byInput);
136
- const pulls = refused
137
- .filter((refusal) => 'pullRequested' in refusal)
138
- .map((refusal) => refusal.id);
143
+ for (const refusal of refused)
144
+ if ('pullRequested' in refusal)
145
+ needsPull.add(refusal.id);
146
+ const pulls = input.rows
147
+ .filter((row) => needsPull.has(row.id))
148
+ .map((row) => row.id);
139
149
  for (const id of pulls)
140
150
  input.requestPull?.(id);
141
151
  return { admitted, refused, excluded, pulls };
@@ -0,0 +1,10 @@
1
+ export function routingHandle(sessionId) {
2
+ // The bridge can load after the auth plugin, so never cache the accessor.
3
+ const routing = Reflect.get(globalThis, Symbol.for('cortexkit.routing'));
4
+ if (typeof routing !== 'function')
5
+ return undefined;
6
+ const handle = routing(sessionId);
7
+ return typeof handle === 'object' && handle !== null
8
+ ? handle
9
+ : undefined;
10
+ }