@cortexkit/opencode-antigravity-auth 3.1.8 → 3.1.9

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 (101) hide show
  1. package/dist/cli.js +111 -77
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +71 -32
  4. package/dist/index.js +5072 -4519
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +315 -256
  7. package/dist/server.js +1018 -395
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/fs/private-files.js +8 -3
  11. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  12. package/dist/src/common-auth-embedded/opencode2/index.js +1 -1
  13. package/dist/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  14. package/dist/src/common-auth-embedded/opencode2/install.js +14 -4
  15. package/dist/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  16. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  17. package/dist/src/common-auth-embedded/routing-accessor/index.js +123 -17
  18. package/dist/src/common-auth-embedded/source-output.json +35 -35
  19. package/dist/src/common-auth-embedded/store/mutate.js +34 -13
  20. package/dist/src/ga/server/index.d.ts +1 -1
  21. package/dist/src/ga/server/index.d.ts.map +1 -1
  22. package/dist/src/ga/server/index.js +58 -19
  23. package/dist/src/ga/server/index.js.map +1 -1
  24. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  25. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  26. package/dist/src/plugin/auth-loader.js +102 -80
  27. package/dist/src/plugin/auth-loader.js.map +1 -1
  28. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  29. package/dist/src/plugin/fetch-interceptor.js +27 -13
  30. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  31. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  32. package/dist/src/plugin/ga-location-services.js +21 -11
  33. package/dist/src/plugin/ga-location-services.js.map +1 -1
  34. package/dist/src/plugin/index.d.ts.map +1 -1
  35. package/dist/src/plugin/index.js +13 -5
  36. package/dist/src/plugin/index.js.map +1 -1
  37. package/dist/src/plugin/request.d.ts.map +1 -1
  38. package/dist/src/plugin/request.js +2 -2
  39. package/dist/src/plugin/request.js.map +1 -1
  40. package/dist/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  41. package/dist/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  42. package/dist/src/plugin/shared/opencode-retry-hints.js +22 -0
  43. package/dist/src/plugin/shared/opencode-retry-hints.js.map +1 -0
  44. package/dist/src/plugin/shared/request-services.d.ts +2 -0
  45. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  46. package/dist/src/plugin/shared/request-services.js +410 -112
  47. package/dist/src/plugin/shared/request-services.js.map +1 -1
  48. package/dist/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  49. package/dist/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  50. package/dist/src/plugin/shared/vault-routing-purpose.js +13 -7
  51. package/dist/src/plugin/shared/vault-routing-purpose.js.map +1 -1
  52. package/dist/src/plugin/shared/vault-routing.d.ts +8 -1
  53. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  54. package/dist/src/plugin/shared/vault-routing.js +12 -4
  55. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  56. package/dist/src/plugin/storage.d.ts +1 -0
  57. package/dist/src/plugin/storage.d.ts.map +1 -1
  58. package/dist/src/plugin/storage.js +3 -3
  59. package/dist/src/plugin/storage.js.map +1 -1
  60. package/dist/src/plugin/vault-custody.d.ts +6 -13
  61. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  62. package/dist/src/plugin/vault-custody.js +19 -16
  63. package/dist/src/plugin/vault-custody.js.map +1 -1
  64. package/dist/tui-build-map.json +5 -5
  65. package/dist/tui-ga-build-map.json +1 -1
  66. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  67. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  68. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  69. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  70. package/dist/types/src/ga/server/index.d.ts +1 -1
  71. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  72. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  73. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  74. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  75. package/dist/types/src/plugin/index.d.ts.map +1 -1
  76. package/dist/types/src/plugin/request.d.ts.map +1 -1
  77. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  78. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  79. package/dist/types/src/plugin/shared/request-services.d.ts +2 -0
  80. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  81. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  82. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  83. package/dist/types/src/plugin/shared/vault-routing.d.ts +8 -1
  84. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  85. package/dist/types/src/plugin/storage.d.ts +1 -0
  86. package/dist/types/src/plugin/storage.d.ts.map +1 -1
  87. package/dist/types/src/plugin/vault-custody.d.ts +6 -13
  88. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  89. package/package.json +2 -2
  90. package/src/common-auth-embedded/fs/private-files.js +8 -3
  91. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  92. package/src/common-auth-embedded/opencode2/index.js +1 -1
  93. package/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  94. package/src/common-auth-embedded/opencode2/install.js +14 -4
  95. package/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  96. package/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  97. package/src/common-auth-embedded/routing-accessor/index.js +123 -17
  98. package/src/common-auth-embedded/source-output.json +35 -35
  99. package/src/common-auth-embedded/store/mutate.js +34 -13
  100. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +8 -3
  101. package/src/tui-raw/common-auth-embedded/fs/private-files.js +8 -3
@@ -70,6 +70,10 @@ function loadBackend() {
70
70
  });
71
71
  return backend;
72
72
  }
73
+ function isSharingIoError(detail) {
74
+ return (detail?.reason === 'io-error' &&
75
+ (detail.win32Code === 32 || detail.win32Code === 303));
76
+ }
73
77
  export class PrivateFileError extends Error {
74
78
  path;
75
79
  stage;
@@ -88,7 +92,9 @@ export class PrivateFileError extends Error {
88
92
  ? // The reason stays on `.reason`: its word "unavailable" would make
89
93
  // OpenCode 1 retry a plain error carrying this message.
90
94
  `Private file refused at ${stage}: ${path}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
91
- : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
95
+ : isSharingIoError(detail)
96
+ ? `Private file busy at ${stage}: ${path}. Another process was replacing or deleting this file at the same moment (Windows error ${detail.win32Code}).`
97
+ : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
92
98
  this.path = path;
93
99
  this.stage = stage;
94
100
  this.name = 'PrivateFileError';
@@ -101,8 +107,7 @@ export class PrivateFileError extends Error {
101
107
  export function isWindowsSharingViolation(error) {
102
108
  return (windowsPrivateFiles &&
103
109
  error instanceof PrivateFileError &&
104
- error.reason === 'io-error' &&
105
- (error.win32Code === 32 || error.win32Code === 303));
110
+ isSharingIoError(error));
106
111
  }
107
112
  export async function privateOperation(path, stage, operation) {
108
113
  try {
@@ -1,6 +1,6 @@
1
1
  export type { OpenCode2AuthFailureKind } from './errors.js';
2
2
  export { OpenCode2AuthError } from './errors.js';
3
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, } from './install.js';
3
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, MAX_TERMINAL_HOLD_MS, } from './install.js';
4
4
  export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, VaultActivationMethod, } from './integration.js';
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';
@@ -1,4 +1,4 @@
1
1
  export { OpenCode2AuthError } from './errors.js';
2
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, } from './install.js';
2
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_HOLD_MS, MAX_TERMINAL_HOLD_MS, } from './install.js';
3
3
  export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
4
4
  export { watchServerSentEvents } from './sse.js';
@@ -1,7 +1,12 @@
1
1
  import type { ChooseAccountResult, HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
2
2
  export declare const DEFAULT_MAX_RECORDS = 512;
3
- /** Allow a one-hour cache lifetime plus the maximum session jitter. */
3
+ /** Cache-bound holds allow a one-hour cache lifetime plus maximum session jitter. */
4
4
  export declare const MAX_RETRY_HOLD_MS = 3621000;
5
+ /**
6
+ * Terminal quota waits allow a seven-day reset plus margin while staying below
7
+ * the signed 32-bit millisecond timer limit (2^31 - 1 ms).
8
+ */
9
+ export declare const MAX_TERMINAL_HOLD_MS = 691200000;
5
10
  /**
6
11
  * The request header `model.request` sets to the attempt it started. The
7
12
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -2,8 +2,13 @@ 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
- /** Allow a one-hour cache lifetime plus the maximum session jitter. */
5
+ /** Cache-bound holds allow a one-hour cache lifetime plus maximum session jitter. */
6
6
  export const MAX_RETRY_HOLD_MS = 3_621_000;
7
+ /**
8
+ * Terminal quota waits allow a seven-day reset plus margin while staying below
9
+ * the signed 32-bit millisecond timer limit (2^31 - 1 ms).
10
+ */
11
+ export const MAX_TERMINAL_HOLD_MS = 691_200_000;
7
12
  /**
8
13
  * The request header `model.request` sets to the attempt it started. The
9
14
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -136,6 +141,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
136
141
  const logger = options.logger;
137
142
  const maxRecords = Math.max(1, options.maxRecords ?? DEFAULT_MAX_RECORDS);
138
143
  const hostRetryLimit = options.hostRetryLimit ?? 10;
144
+ // Retry labels start at 2; count the retry being decided as still available.
145
+ const remainingHostRetries = (attempt) => hostRetryLimit + 2 - attempt;
139
146
  const forbidden = [
140
147
  ...(options.hostCredentials ?? [placeholderSecret(providerID)]),
141
148
  // An owned request must replace its placeholder even if a caller customizes
@@ -1002,7 +1009,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1002
1009
  const canContinue = () => rec.readFailed === true &&
1003
1010
  draft.error.type === 'provider.transport' &&
1004
1011
  hostDecision.retry &&
1005
- hostRetryLimit - draft.attempt >= 1 &&
1012
+ remainingHostRetries(draft.attempt) >= 1 &&
1006
1013
  !rec.limit &&
1007
1014
  !(rec.status !== undefined && rec.status >= 400) &&
1008
1015
  !(draft.error.status !== undefined && draft.error.status >= 400) &&
@@ -1266,7 +1273,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1266
1273
  decision = { retry: false };
1267
1274
  reason = 'adapter-veto';
1268
1275
  }
1269
- else if (!(hostRetryLimit - draft.attempt >= 1)) {
1276
+ else if (!(remainingHostRetries(draft.attempt) >= 1)) {
1270
1277
  if (next)
1271
1278
  await releaseChoice(next);
1272
1279
  next = undefined;
@@ -1284,7 +1291,10 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
1284
1291
  else if (hold &&
1285
1292
  Number.isFinite(hold.delayMs) &&
1286
1293
  hold.delayMs >= 0 &&
1287
- hold.delayMs <= MAX_RETRY_HOLD_MS) {
1294
+ hold.delayMs <=
1295
+ (hold.kind === 'terminal'
1296
+ ? MAX_TERMINAL_HOLD_MS
1297
+ : MAX_RETRY_HOLD_MS)) {
1288
1298
  // A recognised account limit can be recoverable even when
1289
1299
  // the host treats its provider error as final.
1290
1300
  decision = {
@@ -58,7 +58,7 @@ export type HeaderEdits = Readonly<Record<string, string | null>>;
58
58
  export interface ChooseAccountInput extends RequestScope {
59
59
  /** The retry hook's advance choice (which may hold), or a request's own choice. */
60
60
  readonly phase: 'retry' | 'request';
61
- /** Retry hook draft's attempt count; also carried by a consumed hold's wake. */
61
+ /** Next-attempt label (first retry is 2); also carried by a consumed hold's wake. */
62
62
  readonly hostAttempt?: number;
63
63
  /** Revalidate the held account before dispatch, even if the target is not due. */
64
64
  readonly wake?: RetryWake;
@@ -101,14 +101,15 @@ export interface RetryHold {
101
101
  /**
102
102
  * Adapter-computed wait in milliseconds, including per-session jitter.
103
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.
104
+ * accepted, or up to MAX_TERMINAL_HOLD_MS (691_200_000) for kind 'terminal'.
105
+ * Larger or invalid values keep the host's decision and release the choice
106
+ * rather than dispatching before the requested wait has elapsed.
106
107
  */
107
108
  readonly delayMs: number;
108
109
  /** An absolute wake target; its presence forces a request-phase re-check. */
109
110
  readonly target?: number;
110
111
  readonly checkpoint?: WaitCheckpoint;
111
- /** Forwarded to wake.kind so terminal quota waits omit the cache bound. */
112
+ /** Terminal quota waits use the longer delay bound and omit the cache bound at wake. */
112
113
  readonly kind?: RetryWake['kind'];
113
114
  };
114
115
  }
@@ -119,7 +120,7 @@ export interface RetryDisposition {
119
120
  /** Wait through one host retry, then choose afresh without reserving an account. */
120
121
  export interface RetryWaitThenReselect {
121
122
  readonly waitThenReselect: {
122
- /** Same finite, non-negative delay bound as RetryHold.hold.delayMs. */
123
+ /** Finite, non-negative delay up to MAX_RETRY_HOLD_MS (3_621_000). */
123
124
  readonly delayMs: number;
124
125
  };
125
126
  }
@@ -518,8 +519,10 @@ export interface InstallOpenCode2AuthOptions {
518
519
  /** Most attempts kept before the oldest is abandoned and dropped. */
519
520
  readonly maxRecords?: number;
520
521
  /**
521
- * Host retry budget, default 10. When hostAttempt leaves no retry available,
522
- * limit holds and reroutes keep the host's decision and release their choice.
522
+ * Number of host retries, default 10 (next-attempt labels 2 through 11).
523
+ * Remaining retries, including the one being decided, are
524
+ * hostRetryLimit + 2 - hostAttempt. With none available, limit holds and
525
+ * reroutes keep the host's decision and release their choice.
523
526
  */
524
527
  readonly hostRetryLimit?: number;
525
528
  /**
@@ -13,11 +13,31 @@ export interface RoutingCandidate {
13
13
  accountId: string;
14
14
  credentialId: string;
15
15
  }
16
- export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCandidate, Refusals extends boolean = false> {
16
+ type ContinueExhaustion = {
17
+ /** Vault account id, not the plugin's route id. */
18
+ accountId: string;
19
+ credentialId: string;
20
+ /** When the limit or sign-in signal was observed, in Unix milliseconds. */
21
+ observedAtMs: number;
22
+ } & ({
23
+ limitWindow: 'five_hour' | 'seven_day';
24
+ /** Scoped quota group matching `^[a-z0-9._-]{1,64}$`. */
25
+ pool?: string;
26
+ /** Reset time in Unix milliseconds. */
27
+ resetsAtMs?: number;
28
+ /** Non-negative seconds until retry, rounded down. */
29
+ retryAfterS?: number;
30
+ } | {
31
+ limitWindow: 'signed_out';
32
+ pool?: never;
33
+ resetsAtMs?: never;
34
+ retryAfterS?: never;
35
+ });
36
+ export type AskRoutingInput<Candidate extends RoutingCandidate = RoutingCandidate, Refusals extends boolean = false> = {
17
37
  sessionId: string;
18
38
  provider: string;
19
39
  modelId: string;
20
- /** Only routes already eligible under the plugin's vault and killswitch rules. */
40
+ /** Only routes eligible under the vault and the user's configured rules. */
21
41
  candidates: readonly Candidate[];
22
42
  /** Defaults to 1500 ms, above routing's normal tail; clamped to 1–2000 ms. */
23
43
  deadlineMs?: number;
@@ -33,7 +53,24 @@ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCan
33
53
  holdWaitMaxS?: number;
34
54
  /** Plugin sticky choice's vault credential id; an eligible-account hint, not a pin. */
35
55
  warmCredentialId?: string;
36
- }
56
+ } & ({
57
+ mode?: never;
58
+ requestId?: never;
59
+ exhausted?: never;
60
+ } | {
61
+ /**
62
+ * Ask routing whether a run should move off its pinned account. Send to
63
+ * the selected account, or wait on it if the answer includes a hold.
64
+ * With `refusals: true`, a `{refused}` answer means keep the run paused
65
+ * on its account until the reset or, for `signed_out`, until the user
66
+ * signs in. Do not ask again while paused.
67
+ */
68
+ mode: 'continue';
69
+ /** One id per question (e.g. a fresh UUID); reuse it only to retry that same question. */
70
+ requestId: string;
71
+ /** Required on a continue: a proved usage limit or a definite sign-in signal. */
72
+ exhausted: ContinueExhaustion;
73
+ });
37
74
  export interface RoutingHold {
38
75
  /** Uncapped advice from routing. The plugin must apply its own hold cap. */
39
76
  retry_after_ms: number;
@@ -47,6 +84,7 @@ export type RoutingRefusal = {
47
84
  refused: {
48
85
  code: 'account_limit_exhausted' | 'account_selection_refused' | 'account_selection_final';
49
86
  routingCode?: string;
87
+ reason?: string;
50
88
  retryAfterSecs?: number;
51
89
  resetsAtMs?: number;
52
90
  };
@@ -110,7 +148,21 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
110
148
  * as 403 or 429. Must match `^[a-z0-9._-]{1,64}$`.
111
149
  */
112
150
  providerCode: string;
113
- })) | {
151
+ })) | (RoutingReportIdentity & {
152
+ /**
153
+ * Report a 429 or similar response that isn't a proved quota limit. With
154
+ * no provider retry time, use the final attempt's receipt time + 5,000 ms.
155
+ * Routing blocks only new admissions on the account until `retryAtMs`.
156
+ * The session's pin stays: wait until `retryAtMs` and retry the run on
157
+ * the same account. For a proved quota limit, report `exhausted` and ask
158
+ * routing to continue with the exhausted window. Use `credential_refused`
159
+ * for an API key refused for any use.
160
+ */
161
+ kind: 'transient_backoff';
162
+ /** Absolute retry time in Unix milliseconds. */
163
+ retryAtMs: number;
164
+ providerCode?: string;
165
+ }) | {
114
166
  sessionId: string;
115
167
  kind: 'turn_notes_supported';
116
168
  model: string;
@@ -175,20 +227,18 @@ export declare function turnNotes(sessionId: string): readonly {
175
227
  * Ask routing for an eligible vault route. Any failure or unfamiliar answer
176
228
  * yields undefined so the plugin can keep its own choice. Opted-in routing
177
229
  * refusals instead stop the request. This does not admit routes. Callers never
178
- * pass an account the vault refused. A plugin may also leave out accounts its
179
- * user's own eligibility rules exclude, such as a per-model account list. Each
180
- * plugin decides whether its quota floors (a minimum share of a quota window
181
- * an account must keep) also filter candidates; routing keeps its own reserve
182
- * of each window.
183
- * Routing's pick among the candidates is final. Don't reject it under a local
184
- * floor, and don't add floors of the plugin's own that duplicate routing's
185
- * reserves.
230
+ * pass an account the vault refused. Beyond that, a plugin may leave accounts
231
+ * out only under a user-configured eligibility rule, such as a killswitch floor
232
+ * the user turned on (the minimum share of a quota window an account must keep
233
+ * to be offered) or a per-model account list. Plugins ship no floors of
234
+ * their own by default. Routing's pick is final: never reject it under a local
235
+ * floor or choose another account afterwards.
186
236
  */
187
237
  export declare function askRouting<Candidate extends RoutingCandidate, Refusals extends boolean = false>(input: AskRoutingInput<Candidate, Refusals>): Promise<RoutingSelection<Candidate> | (Refusals extends true ? RoutingRefusal : never) | undefined>;
188
238
  /**
189
- * Report a vault request, billing result, plugin wait or turn-note event without
190
- * waiting for routing. Only contract fields are sent, and all accessor failures
191
- * are ignored. Headers must already be limited to rate-limit headers by the
192
- * caller; values are not filtered or redacted here.
239
+ * Report a vault request, account backoff, billing result, plugin wait or
240
+ * turn-note event without waiting for routing. Only contract fields are sent,
241
+ * and all accessor failures are ignored. Headers must already be limited to
242
+ * rate-limit headers by the caller; values are not filtered or redacted here.
193
243
  */
194
244
  export declare function reportRouting(input: ReportRoutingInput): void;
@@ -4,6 +4,7 @@
4
4
  * rows. Nothing is persisted here; plugins on routes the runner does not serve
5
5
  * get no turn notes.
6
6
  */
7
+ import { createHash } from 'node:crypto';
7
8
  import { isCacheWarmStopReason, } from './cache-policy.js';
8
9
  import { routingHandle } from './handle.js';
9
10
  export { CACHE_WARM_STOP_REASONS, isCacheWarmStopReason, reportCacheTouch, reportCacheWarmStopped, sessionCachePolicy, sessionToolWait, } from './cache-policy.js';
@@ -22,6 +23,58 @@ function isObject(value) {
22
23
  function isNonEmptyString(value) {
23
24
  return typeof value === 'string' && value.length > 0;
24
25
  }
26
+ function isBoundedControlFreeString(value, maxLength) {
27
+ return (isNonEmptyString(value) &&
28
+ value.length <= maxLength &&
29
+ !/\p{Cc}/u.test(value));
30
+ }
31
+ function isRoutingCode(value) {
32
+ return typeof value === 'string' && /^[a-z0-9._-]{1,64}$/.test(value);
33
+ }
34
+ function continueExhaustion(value) {
35
+ if (!isObject(value) || Array.isArray(value))
36
+ return undefined;
37
+ const { accountId, credentialId, limitWindow, observedAtMs } = value;
38
+ if (!isBoundedControlFreeString(accountId, 256) ||
39
+ !isBoundedControlFreeString(credentialId, 256) ||
40
+ typeof observedAtMs !== 'number' ||
41
+ !Number.isSafeInteger(observedAtMs) ||
42
+ observedAtMs <= 0 ||
43
+ (limitWindow !== 'five_hour' &&
44
+ limitWindow !== 'seven_day' &&
45
+ limitWindow !== 'signed_out'))
46
+ return undefined;
47
+ const exhausted = {
48
+ account: accountId,
49
+ credential_id: credentialId,
50
+ limit_window: limitWindow,
51
+ observed_at_ms: observedAtMs,
52
+ };
53
+ if (limitWindow === 'signed_out') {
54
+ if ('pool' in value || 'resetsAtMs' in value || 'retryAfterS' in value)
55
+ return undefined;
56
+ return exhausted;
57
+ }
58
+ const { pool, resetsAtMs, retryAfterS } = value;
59
+ if ((pool !== undefined && !isRoutingCode(pool)) ||
60
+ (resetsAtMs !== undefined &&
61
+ (typeof resetsAtMs !== 'number' ||
62
+ !Number.isSafeInteger(resetsAtMs) ||
63
+ resetsAtMs <= 0)) ||
64
+ (retryAfterS !== undefined &&
65
+ (typeof retryAfterS !== 'number' ||
66
+ !Number.isFinite(retryAfterS) ||
67
+ retryAfterS < 0)))
68
+ return undefined;
69
+ return {
70
+ ...exhausted,
71
+ ...(pool !== undefined ? { pool } : {}),
72
+ ...(resetsAtMs !== undefined ? { resets_at_ms: resetsAtMs } : {}),
73
+ ...(retryAfterS !== undefined
74
+ ? { retry_after_s: Math.floor(retryAfterS) }
75
+ : {}),
76
+ };
77
+ }
25
78
  function billingCache(value) {
26
79
  if (!isObject(value) || Array.isArray(value))
27
80
  return;
@@ -123,6 +176,24 @@ export function turnNotes(sessionId) {
123
176
  return [];
124
177
  }
125
178
  }
179
+ function candidateView(candidates) {
180
+ const accounts = [];
181
+ for (const { accountId, credentialId } of candidates) {
182
+ if (isNonEmptyString(accountId) &&
183
+ isBoundedControlFreeString(credentialId, 256)) {
184
+ accounts.push({ account_id: accountId, credential_id: credentialId });
185
+ }
186
+ }
187
+ if (accounts.length === 0)
188
+ return undefined;
189
+ const lines = accounts
190
+ .map(({ account_id, credential_id }) => Buffer.from(`${account_id}\t${credential_id}\n`, 'utf8'))
191
+ .sort(Buffer.compare);
192
+ const hash = createHash('sha256');
193
+ for (const line of lines)
194
+ hash.update(line);
195
+ return { view_digest: hash.digest('hex'), accounts };
196
+ }
126
197
  function selectionFor(answer, candidates) {
127
198
  if (!isObject(answer))
128
199
  return undefined;
@@ -156,11 +227,11 @@ function refusalFor(value) {
156
227
  return undefined;
157
228
  }
158
229
  const refused = { code };
159
- const routingCode = value.routing_code;
160
- if (typeof routingCode === 'string' &&
161
- /^[a-z0-9._-]{1,64}$/.test(routingCode)) {
230
+ const { routing_code: routingCode, reason } = value;
231
+ if (isRoutingCode(routingCode))
162
232
  refused.routingCode = routingCode;
163
- }
233
+ if (isRoutingCode(reason))
234
+ refused.reason = reason;
164
235
  const retryAfterSecs = value.retry_after_secs;
165
236
  if (typeof retryAfterSecs === 'number' &&
166
237
  Number.isFinite(retryAfterSecs) &&
@@ -178,6 +249,21 @@ function refusalFor(value) {
178
249
  export async function askRouting(input) {
179
250
  let timer;
180
251
  try {
252
+ const request = {
253
+ provider: input.provider,
254
+ modelId: input.modelId,
255
+ };
256
+ if (input.mode === 'continue') {
257
+ const { requestId } = input;
258
+ if (!isBoundedControlFreeString(requestId, 128))
259
+ return undefined;
260
+ const exhausted = continueExhaustion(input.exhausted);
261
+ if (!exhausted)
262
+ return undefined;
263
+ request.mode = 'continue';
264
+ request.request_id = requestId;
265
+ request.exhausted = exhausted;
266
+ }
181
267
  const handle = routingHandle(input.sessionId);
182
268
  if (!handle)
183
269
  return undefined;
@@ -192,10 +278,6 @@ export async function askRouting(input) {
192
278
  timer = setTimeout(() => resolve(undefined), deadlineMs);
193
279
  timer.unref();
194
280
  });
195
- const request = {
196
- provider: input.provider,
197
- modelId: input.modelId,
198
- };
199
281
  const cap = input.holdWaitMaxS;
200
282
  if (typeof cap === 'number' && Number.isFinite(cap)) {
201
283
  request.hold_wait_max_s = Math.max(0, Math.floor(cap));
@@ -203,12 +285,13 @@ export async function askRouting(input) {
203
285
  if (input.refusals === true)
204
286
  request.refusals = true;
205
287
  const warmCredentialId = input.warmCredentialId;
206
- if (isNonEmptyString(warmCredentialId) &&
207
- warmCredentialId.length <= 256 &&
208
- !/\p{Cc}/u.test(warmCredentialId) &&
288
+ if (isBoundedControlFreeString(warmCredentialId, 256) &&
209
289
  input.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
210
290
  request.warm_credential = warmCredentialId;
211
291
  }
292
+ const candidates = candidateView(input.candidates);
293
+ if (candidates)
294
+ request.candidates = candidates;
212
295
  const pending = accountFor.call(handle, request, { deadlineMs });
213
296
  if (!isObject(pending) || typeof pending.then !== 'function')
214
297
  return undefined;
@@ -227,10 +310,10 @@ export async function askRouting(input) {
227
310
  }
228
311
  }
229
312
  /**
230
- * Report a vault request, billing result, plugin wait or turn-note event without
231
- * waiting for routing. Only contract fields are sent, and all accessor failures
232
- * are ignored. Headers must already be limited to rate-limit headers by the
233
- * caller; values are not filtered or redacted here.
313
+ * Report a vault request, account backoff, billing result, plugin wait or
314
+ * turn-note event without waiting for routing. Only contract fields are sent,
315
+ * and all accessor failures are ignored. Headers must already be limited to
316
+ * rate-limit headers by the caller; values are not filtered or redacted here.
234
317
  */
235
318
  export function reportRouting(input) {
236
319
  try {
@@ -244,6 +327,30 @@ export function reportRouting(input) {
244
327
  let payload;
245
328
  if ('kind' in input) {
246
329
  switch (input.kind) {
330
+ case 'transient_backoff': {
331
+ const { accountId, credentialId, retryAtMs, providerCode } = input;
332
+ if (!isNonEmptyString(sessionId) ||
333
+ !isNonEmptyString(accountId) ||
334
+ !Number.isSafeInteger(retryAtMs) ||
335
+ retryAtMs <= 0 ||
336
+ (credentialId !== undefined &&
337
+ !isBoundedControlFreeString(credentialId, 256)) ||
338
+ (providerCode !== undefined &&
339
+ !isBoundedControlFreeString(providerCode, 128)))
340
+ return;
341
+ payload = {
342
+ kind: 'transient_backoff',
343
+ account_id: accountId,
344
+ ...(credentialId !== undefined
345
+ ? { credential_id: credentialId }
346
+ : {}),
347
+ retry_at_ms: retryAtMs,
348
+ ...(providerCode !== undefined
349
+ ? { provider_code: providerCode }
350
+ : {}),
351
+ };
352
+ break;
353
+ }
247
354
  case 'wait': {
248
355
  const { phase, waitId, reason, nextMs, attempt, message, outcome } = input;
249
356
  if (!isNonEmptyString(sessionId) ||
@@ -406,8 +513,7 @@ export function reportRouting(input) {
406
513
  if (window !== '5h' && window !== '7d')
407
514
  return;
408
515
  // An undefined pool means the whole account, as an omitted one does.
409
- if (pool !== undefined &&
410
- (typeof pool !== 'string' || !/^[a-z0-9._-]{1,64}$/.test(pool)))
516
+ if (pool !== undefined && !isRoutingCode(pool))
411
517
  return;
412
518
  payload = {
413
519
  ...identity,
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "package": "@cortexkit/common-auth",
4
- "version": "0.53.0",
4
+ "version": "0.55.0",
5
5
  "artifactStatus": "published",
6
- "archiveBytes": 500371,
6
+ "archiveBytes": 502568,
7
7
  "publicRoots": {
8
8
  "./rpc": {
9
9
  "types": "./dist/rpc/index.d.ts",
@@ -74,16 +74,16 @@
74
74
  "import": "./src/quota-sidebar/index.tsx"
75
75
  }
76
76
  },
77
- "input": "tools/common-auth-build/inputs/cortexkit-common-auth-0.53.0.tgz",
78
- "tarballSha256": "f9ffedd0b1fdfbb689c6eb1cae27561228b6e80a52d26ec5e6fa4dd1fe47e7ab",
79
- "sri": "sha512-WwIae25lpa6W07Rw0JTS45eZohHj9ZSa9Yyc62Z9098lP+ztzEt4zJjDsz5KgbX8Ew/SEfRT4s4buXAnoUrA5Q==",
80
- "shasum": "0198ecd60e908146221ea5ab1436ea47077fc212",
77
+ "input": "tools/common-auth-build/inputs/cortexkit-common-auth-0.55.0.tgz",
78
+ "tarballSha256": "b629e10e9a39c5b1e6dc7576c2d5814a23a5bbb2dad8d6c1ccddb759c14d200c",
79
+ "sri": "sha512-EScwmEDdxSdW/z+6n1v630bsTdAUSQYBuG4l16yziRqptG4MhjCAoH6aNelSy/I3hIJ2j6bV3IcqteoGWBLpSg==",
80
+ "shasum": "8a5d3a07ec72662120305388d051c0bdcee416f4",
81
81
  "canonicalFiles": 257,
82
- "canonicalBytes": 1514096,
82
+ "canonicalBytes": 1522655,
83
83
  "generator": {
84
84
  "path": "packages/opencode/scripts/embed-common-auth.ts",
85
85
  "version": 4,
86
- "sha256": "f54aa9e14e1cac3ba0f2158002f58f50ef592638e507fbc4d6302ad4322757da"
86
+ "sha256": "d4f9c099ec2dd6a53cd0b7a35e5571be94e24176c7e01347e4ea20b92eed13fd"
87
87
  },
88
88
  "files": [
89
89
  {
@@ -681,9 +681,9 @@
681
681
  {
682
682
  "source": "package/dist/fs/private-files.js",
683
683
  "output": "fs/private-files.js",
684
- "bytes": 15235,
685
- "sourceSha256": "4fd7ca5b40dbdcc27044be3d73eaf6910dd75572cf199aea049fd658bcadf64c",
686
- "outputSha256": "4fd7ca5b40dbdcc27044be3d73eaf6910dd75572cf199aea049fd658bcadf64c",
684
+ "bytes": 15526,
685
+ "sourceSha256": "8456644c921d76d1946c9c04a6784308dfbc4c22be19d88d5b15bf629d5f4226",
686
+ "outputSha256": "8456644c921d76d1946c9c04a6784308dfbc4c22be19d88d5b15bf629d5f4226",
687
687
  "transform": "verbatim"
688
688
  },
689
689
  {
@@ -897,33 +897,33 @@
897
897
  {
898
898
  "source": "package/dist/opencode2/index.d.ts",
899
899
  "output": "opencode2/index.d.ts",
900
- "bytes": 1303,
901
- "sourceSha256": "50f4352606062af68347bc73ae0765ba44537928cb49db3b739d6e76daeebd53",
902
- "outputSha256": "50f4352606062af68347bc73ae0765ba44537928cb49db3b739d6e76daeebd53",
900
+ "bytes": 1325,
901
+ "sourceSha256": "03baf6a3ea7b26545ec20a03588ac7f30830c84e15f4bbde51d268218ff3e284",
902
+ "outputSha256": "03baf6a3ea7b26545ec20a03588ac7f30830c84e15f4bbde51d268218ff3e284",
903
903
  "transform": "verbatim"
904
904
  },
905
905
  {
906
906
  "source": "package/dist/opencode2/index.js",
907
907
  "output": "opencode2/index.js",
908
- "bytes": 463,
909
- "sourceSha256": "a626e6a4f3511e07f1e52a0969b855884bd521f0f1382ad28ed35ca83b46fc1e",
910
- "outputSha256": "a626e6a4f3511e07f1e52a0969b855884bd521f0f1382ad28ed35ca83b46fc1e",
908
+ "bytes": 485,
909
+ "sourceSha256": "0a68a5e9af890954e96172fd475ea20e6e137ad20feb0c5ad014d4ea33dfd198",
910
+ "outputSha256": "0a68a5e9af890954e96172fd475ea20e6e137ad20feb0c5ad014d4ea33dfd198",
911
911
  "transform": "verbatim"
912
912
  },
913
913
  {
914
914
  "source": "package/dist/opencode2/install.d.ts",
915
915
  "output": "opencode2/install.d.ts",
916
- "bytes": 3995,
917
- "sourceSha256": "484ac235de953920bc30164f2b4e814d565b1fe0beca6847c0f65e1d1d42ec08",
918
- "outputSha256": "484ac235de953920bc30164f2b4e814d565b1fe0beca6847c0f65e1d1d42ec08",
916
+ "bytes": 4212,
917
+ "sourceSha256": "edb14a4f60ef24c85b5e4f41f94b66b5594f38628c65145841fa4bcf1bf319f6",
918
+ "outputSha256": "edb14a4f60ef24c85b5e4f41f94b66b5594f38628c65145841fa4bcf1bf319f6",
919
919
  "transform": "verbatim"
920
920
  },
921
921
  {
922
922
  "source": "package/dist/opencode2/install.js",
923
923
  "output": "opencode2/install.js",
924
- "bytes": 65057,
925
- "sourceSha256": "823040b7d0fc4b0199fdbaa68583180338b040ea1200d611c645ba9a3b22538d",
926
- "outputSha256": "823040b7d0fc4b0199fdbaa68583180338b040ea1200d611c645ba9a3b22538d",
924
+ "bytes": 65592,
925
+ "sourceSha256": "fc98e6bd26a6835d118666b1f27fc0598dbe9f929d793b2fe619d3be7375b988",
926
+ "outputSha256": "fc98e6bd26a6835d118666b1f27fc0598dbe9f929d793b2fe619d3be7375b988",
927
927
  "transform": "verbatim"
928
928
  },
929
929
  {
@@ -961,9 +961,9 @@
961
961
  {
962
962
  "source": "package/dist/opencode2/types.d.ts",
963
963
  "output": "opencode2/types.d.ts",
964
- "bytes": 32757,
965
- "sourceSha256": "d9e94ff62857ad062770ad64e30456c39fafbea57c488099cf06dade301120e1",
966
- "outputSha256": "d9e94ff62857ad062770ad64e30456c39fafbea57c488099cf06dade301120e1",
964
+ "bytes": 32971,
965
+ "sourceSha256": "955be769b8aacbc13f51d16a94639658424b3e02e29c2a252b4b872bfde9096f",
966
+ "outputSha256": "955be769b8aacbc13f51d16a94639658424b3e02e29c2a252b4b872bfde9096f",
967
967
  "transform": "verbatim"
968
968
  },
969
969
  {
@@ -1857,9 +1857,9 @@
1857
1857
  {
1858
1858
  "source": "package/dist/store/mutate.js",
1859
1859
  "output": "store/mutate.js",
1860
- "bytes": 20171,
1861
- "sourceSha256": "d61d08f2caed6d7a803ca4c67511e5133d28f21a90a7417f76e23b49ed00591d",
1862
- "outputSha256": "d61d08f2caed6d7a803ca4c67511e5133d28f21a90a7417f76e23b49ed00591d",
1860
+ "bytes": 21075,
1861
+ "sourceSha256": "e2b69c850dface416ff3ebc54e2f57fd5c36b5346055b90195493cada75b6901",
1862
+ "outputSha256": "e2b69c850dface416ff3ebc54e2f57fd5c36b5346055b90195493cada75b6901",
1863
1863
  "transform": "verbatim"
1864
1864
  },
1865
1865
  {
@@ -2129,17 +2129,17 @@
2129
2129
  {
2130
2130
  "source": "package/dist/routing-accessor/index.d.ts",
2131
2131
  "output": "routing-accessor/index.d.ts",
2132
- "bytes": 8159,
2133
- "sourceSha256": "be4ee94f1f7ebcc587388df1c4c7744d2f15d6f1cabe08734fdec91012b0946f",
2134
- "outputSha256": "be4ee94f1f7ebcc587388df1c4c7744d2f15d6f1cabe08734fdec91012b0946f",
2132
+ "bytes": 10161,
2133
+ "sourceSha256": "9a53d387aea7a3423225372bd8a61000838e1c7bb5818c93a32455f2037c315f",
2134
+ "outputSha256": "9a53d387aea7a3423225372bd8a61000838e1c7bb5818c93a32455f2037c315f",
2135
2135
  "transform": "verbatim"
2136
2136
  },
2137
2137
  {
2138
2138
  "source": "package/dist/routing-accessor/index.js",
2139
2139
  "output": "routing-accessor/index.js",
2140
- "bytes": 18496,
2141
- "sourceSha256": "e4b90716dfc490aa2abca9062b46f2da30b49d8478d101888efbb6b93de63662",
2142
- "outputSha256": "e4b90716dfc490aa2abca9062b46f2da30b49d8478d101888efbb6b93de63662",
2140
+ "bytes": 22848,
2141
+ "sourceSha256": "13f13701391958c2e1f52d614a78da8d276594a90ee54b4f6af33bf81b4ca669",
2142
+ "outputSha256": "13f13701391958c2e1f52d614a78da8d276594a90ee54b4f6af33bf81b4ca669",
2143
2143
  "transform": "verbatim"
2144
2144
  }
2145
2145
  ],