@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
@@ -0,0 +1,77 @@
1
+ import type { Scope } from './scope.js';
2
+ import type { AccountKey } from './signal.js';
3
+ export declare function sameAccount(a: AccountKey, b: AccountKey): boolean;
4
+ export interface RequestExclusion {
5
+ readonly account: AccountKey;
6
+ readonly scope: Scope;
7
+ }
8
+ export interface RetainHistory {
9
+ readonly account: AccountKey;
10
+ readonly count: number;
11
+ readonly startedAt: number;
12
+ readonly lastRetainedAt: number;
13
+ }
14
+ export interface RequestHistory {
15
+ /** A request/turn token, not a session id. */
16
+ readonly requestId: string;
17
+ readonly originalUrl: string;
18
+ readonly requestStartedAt: number;
19
+ readonly saw429: boolean;
20
+ readonly lastStatus?: number;
21
+ readonly tried: readonly RequestExclusion[];
22
+ readonly excludedForRequest: readonly RequestExclusion[];
23
+ readonly retains: readonly RetainHistory[];
24
+ readonly retainedAttempts: readonly string[];
25
+ readonly excludedAttempts: readonly string[];
26
+ readonly switchedAttempts: readonly string[];
27
+ readonly switches: number;
28
+ readonly blockedSince?: number;
29
+ }
30
+ export declare function createRequestHistory(input: {
31
+ readonly requestId: string;
32
+ readonly originalUrl: string;
33
+ readonly clockNow: number;
34
+ }): RequestHistory;
35
+ export declare function isRequestExcluded(history: RequestHistory, account: AccountKey, scope: Scope): boolean;
36
+ export type RequestHistoryEvent = {
37
+ readonly type: 'response';
38
+ readonly account: AccountKey;
39
+ readonly scope: Scope;
40
+ readonly status?: number;
41
+ } | {
42
+ readonly type: 'retain';
43
+ readonly account: AccountKey;
44
+ readonly attemptId: string;
45
+ readonly clockNow: number;
46
+ readonly cause: 'unconfirmed-limit' | 'credential-recovery';
47
+ } | {
48
+ readonly type: 'exclude';
49
+ readonly account: AccountKey;
50
+ readonly scope: Scope;
51
+ readonly attemptId: string;
52
+ } | {
53
+ readonly type: 'switch';
54
+ readonly attemptId: string;
55
+ } | {
56
+ readonly type: 'blocked';
57
+ readonly clockNow: number;
58
+ } | {
59
+ readonly type: 'selected';
60
+ };
61
+ /** Retain/exclude/switch events are committed by the executor, not by polling. */
62
+ export declare function reduceRequestHistory(history: RequestHistory, event: RequestHistoryEvent): RequestHistory;
63
+ export declare const REQUEST_EXCLUSION_EFFECTS: Readonly<{
64
+ readonly refundHybridToken: true;
65
+ readonly cancelDiscardedBody: true;
66
+ readonly addMark: false;
67
+ readonly addCooldown: false;
68
+ readonly penalizeHealth: false;
69
+ readonly chargeSwitch: false;
70
+ }>;
71
+ /** Run the returned effects once, then reselect with the returned history. */
72
+ export declare function commitRequestExclusion(history: RequestHistory, entry: RequestExclusion & {
73
+ readonly attemptId: string;
74
+ }): {
75
+ readonly history: RequestHistory;
76
+ readonly effects?: typeof REQUEST_EXCLUSION_EFFECTS;
77
+ };
@@ -0,0 +1,12 @@
1
+ /** Applicability is a plugin fact, never a substring match on a model id. */
2
+ export type Scope = {
3
+ readonly kind: 'pool';
4
+ } | {
5
+ readonly kind: 'family';
6
+ readonly family: string;
7
+ } | {
8
+ readonly kind: 'model';
9
+ readonly model: string;
10
+ };
11
+ export type FamilyOf = (model: string) => string | undefined;
12
+ export declare function scopeCovers(scope: Scope, model: string, familyOf: FamilyOf): boolean;
@@ -0,0 +1,41 @@
1
+ import type { Scope } from './scope.js';
2
+ /** Refreshing credentials preserves this key; replacing an identity does not. */
3
+ export interface AccountKey {
4
+ readonly namespace: string;
5
+ readonly accountId: string;
6
+ readonly incarnation: string;
7
+ }
8
+ export type LimitKind = 'quota-exhausted' | 'rate-limit' | 'capacity' | 'payment-balance' | 'payment-cap' | 'auth' | 'account-access' | 'model-unavailable';
9
+ export interface LimitWindow {
10
+ readonly window: string;
11
+ readonly confirmed: boolean;
12
+ readonly confirmedByReading: boolean;
13
+ readonly resetAt?: number;
14
+ readonly resetSource?: string;
15
+ readonly observedAt: number;
16
+ readonly provenance: string;
17
+ }
18
+ /** A retry hint does not by itself confirm any exhausted window. */
19
+ export interface LimitSignal {
20
+ readonly account: AccountKey;
21
+ readonly kind: LimitKind;
22
+ readonly reason: string;
23
+ readonly status?: number;
24
+ readonly scope: Scope;
25
+ readonly windows: readonly LimitWindow[];
26
+ readonly observedAt: number;
27
+ readonly retryAfterMs?: number;
28
+ readonly retryAfterSource?: string;
29
+ }
30
+ export interface ClassifierInput {
31
+ readonly account: AccountKey;
32
+ readonly status: number;
33
+ readonly headers: Headers;
34
+ readonly body?: unknown;
35
+ readonly firstEvent?: unknown;
36
+ readonly effectiveModel: string;
37
+ readonly readings: readonly LimitWindow[];
38
+ readonly now: number;
39
+ }
40
+ /** Returning nothing must not manufacture an exhaustion mark. */
41
+ export type LimitClassifier = (input: ClassifierInput) => LimitSignal | undefined;
@@ -0,0 +1,52 @@
1
+ import type { SessionActivity } from './activity.js';
2
+ import type { LimitAxes } from './axes.js';
3
+ import type { LimitDecision, PolicyFacts, TerminalFacts, WaitCheckpoint } from './decide.js';
4
+ import type { RequestHistory } from './request-history.js';
5
+ import type { FamilyOf, Scope } from './scope.js';
6
+ import type { AccountKey } from './signal.js';
7
+ export interface TerminalWindow {
8
+ readonly window: string;
9
+ readonly scope: Scope;
10
+ /** The caller evaluates quota thresholds, not just provider exhaustion. */
11
+ readonly blockedBy?: 'exhausted' | 'floor' | 'killswitch-floor';
12
+ readonly reset?: {
13
+ readonly at: number;
14
+ /** Provenance of this reset field, never the enclosing row's update time. */
15
+ readonly observedAt?: number;
16
+ readonly checkedAt?: number;
17
+ };
18
+ }
19
+ export interface TerminalCandidate {
20
+ readonly account: AccountKey;
21
+ readonly readingAccount: AccountKey;
22
+ readonly identity?: string;
23
+ readonly readingIdentity?: string;
24
+ readonly windows: readonly TerminalWindow[];
25
+ }
26
+ export interface TerminalScanFacts {
27
+ /** Candidate keys come from the caller's scoped/general terminal scan. */
28
+ readonly candidates: readonly TerminalCandidate[];
29
+ readonly effectiveModel: string;
30
+ readonly familyOf: FamilyOf;
31
+ readonly maxAgeMs: number;
32
+ readonly maxSameAccountWait?: unknown;
33
+ readonly activity?: SessionActivity;
34
+ /** Current session account, used to reject another account's cache record. */
35
+ readonly accountKey?: AccountKey;
36
+ }
37
+ export interface TerminalReset {
38
+ readonly account: AccountKey;
39
+ readonly resetAt: number;
40
+ readonly checkpoint: WaitCheckpoint;
41
+ }
42
+ /**
43
+ * Take each account's latest blocking reset, then the earliest across accounts.
44
+ * A missing identity is compatible, but readings from before re-login are not.
45
+ */
46
+ export declare function scanTerminalReset(input: TerminalScanFacts, now: number): TerminalReset | undefined;
47
+ export declare function terminalWaitDisabled(metadata: TerminalFacts, axes: LimitAxes): boolean;
48
+ /**
49
+ * When no account is ready, cap the wait by the setting rather than cache expiry.
50
+ * Unlike a same-account hold, this wait may proceed without a cache activity record.
51
+ */
52
+ export declare function terminalRefusalDecision(facts: PolicyFacts, axes: LimitAxes, history: RequestHistory, metadata: TerminalFacts): LimitDecision | undefined;
@@ -0,0 +1,21 @@
1
+ import type { WaitCheckpoint } from './decide.js';
2
+ import type { AccountKey, LimitWindow } from './signal.js';
3
+ export interface WakeFacts {
4
+ readonly checkpoint: WaitCheckpoint;
5
+ readonly target: number;
6
+ /**
7
+ * Ordinary holds require this session/account's provider prompt cache to
8
+ * remain valid; terminal waits instead wait for pool quota, without a cache.
9
+ */
10
+ readonly kind?: 'hold' | 'terminal';
11
+ }
12
+ /**
13
+ * Snapshot exhaustion blockers only. A wait caused by a minimum-remaining quota
14
+ * threshold supplies no windows: elapsed time cannot prove renewed headroom.
15
+ */
16
+ export declare function waitCheckpoint(accountKey: AccountKey, decidedAt: number, windows: readonly LimitWindow[]): WaitCheckpoint;
17
+ /**
18
+ * Match exhaustion evidence for one wake dispatch, without refreshing quota.
19
+ * The caller must still check admission, other blockers and any cache bound.
20
+ */
21
+ export declare function liftedWindowsForWake(wake: WakeFacts, account: AccountKey, windows: readonly LimitWindow[], now: number): readonly string[];
@@ -0,0 +1,25 @@
1
+ import type { ResetFormatter } from './duration.js';
2
+ export declare function hasUnsafeWording(text: string): boolean;
3
+ export interface MessageParameters {
4
+ readonly labels: readonly string[];
5
+ readonly retryIn?: string;
6
+ readonly reset?: string;
7
+ }
8
+ /** Templates return text only; they cannot replace a family's wire envelope. */
9
+ export type MessageTemplate = (parameters: MessageParameters) => string;
10
+ export declare class UnsafeWordingError extends Error {
11
+ readonly messageKey: string;
12
+ readonly code = "unsafe-wording";
13
+ constructor(messageKey: string);
14
+ }
15
+ export interface LimitMessageOptions {
16
+ readonly refusals?: Readonly<Record<string, MessageTemplate>>;
17
+ readonly retryable?: Readonly<Record<string, MessageTemplate>>;
18
+ readonly formatReset?: ResetFormatter;
19
+ }
20
+ export interface LimitMessages {
21
+ readonly formatReset?: ResetFormatter;
22
+ readonly render: (messageKey: string, parameters: MessageParameters, nonRetryable: boolean) => string | undefined;
23
+ }
24
+ /** Registration rejects unsafe fixed text; actual substitutions are checked again. */
25
+ export declare function registerLimitMessages(options: LimitMessageOptions): LimitMessages;
@@ -5,4 +5,4 @@ export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, Regi
5
5
  export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
6
6
  export type { ServerSentEvent } from './sse.js';
7
7
  export { watchServerSentEvents } from './sse.js';
8
- export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryHold, RetryReason, SameAccountRetryInput, SameAccountRetryResult, SelectingHook, Transport, } from './types.js';
8
+ export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryDisposition, RetryHold, RetryReason, RetryWaitThenReselect, RetryWake, SameAccountRetryInput, SameAccountRetryResult, SelectingHook, Transport, } from './types.js';
@@ -1,7 +1,7 @@
1
1
  import type { ChooseAccountResult, HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
2
2
  export declare const DEFAULT_MAX_RECORDS = 512;
3
- /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
4
- export declare const MAX_RETRY_HOLD_MS: number;
3
+ /** Allow a one-hour cache lifetime plus the maximum session jitter. */
4
+ export declare const MAX_RETRY_HOLD_MS = 3621000;
5
5
  /**
6
6
  * The request header `model.request` sets to the attempt it started. The
7
7
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -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
  }