@cortexkit/opencode-antigravity-auth 3.1.8 → 3.1.10

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 (118) hide show
  1. package/README.md +4 -0
  2. package/dist/cli.js +256 -179
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +88 -44
  5. package/dist/index.js +5466 -4823
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +333 -269
  8. package/dist/server.js +1321 -608
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -5
  12. package/dist/src/common-auth-embedded/claustrum/custody.js +31 -14
  13. package/dist/src/common-auth-embedded/fs/private-files.js +8 -3
  14. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/opencode2/index.js +1 -1
  16. package/dist/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  17. package/dist/src/common-auth-embedded/opencode2/install.js +14 -4
  18. package/dist/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  19. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +71 -16
  20. package/dist/src/common-auth-embedded/routing-accessor/index.js +123 -17
  21. package/dist/src/common-auth-embedded/setup/process-fence.js +20 -3
  22. package/dist/src/common-auth-embedded/source-output.json +44 -44
  23. package/dist/src/common-auth-embedded/store/mutate.js +34 -13
  24. package/dist/src/ga/server/index.d.ts +1 -1
  25. package/dist/src/ga/server/index.d.ts.map +1 -1
  26. package/dist/src/ga/server/index.js +58 -19
  27. package/dist/src/ga/server/index.js.map +1 -1
  28. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  29. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  30. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  31. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  32. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  33. package/dist/src/plugin/auth-loader.js +102 -80
  34. package/dist/src/plugin/auth-loader.js.map +1 -1
  35. package/dist/src/plugin/config/models.d.ts +1 -1
  36. package/dist/src/plugin/config/models.d.ts.map +1 -1
  37. package/dist/src/plugin/config/models.js +10 -5
  38. package/dist/src/plugin/config/models.js.map +1 -1
  39. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  40. package/dist/src/plugin/fetch-interceptor.js +27 -13
  41. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  42. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  43. package/dist/src/plugin/ga-location-services.js +21 -11
  44. package/dist/src/plugin/ga-location-services.js.map +1 -1
  45. package/dist/src/plugin/index.d.ts.map +1 -1
  46. package/dist/src/plugin/index.js +13 -5
  47. package/dist/src/plugin/index.js.map +1 -1
  48. package/dist/src/plugin/request.d.ts.map +1 -1
  49. package/dist/src/plugin/request.js +8 -8
  50. package/dist/src/plugin/request.js.map +1 -1
  51. package/dist/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  52. package/dist/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  53. package/dist/src/plugin/shared/opencode-retry-hints.js +22 -0
  54. package/dist/src/plugin/shared/opencode-retry-hints.js.map +1 -0
  55. package/dist/src/plugin/shared/request-services.d.ts +2 -0
  56. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  57. package/dist/src/plugin/shared/request-services.js +410 -112
  58. package/dist/src/plugin/shared/request-services.js.map +1 -1
  59. package/dist/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  60. package/dist/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  61. package/dist/src/plugin/shared/vault-routing-purpose.js +13 -7
  62. package/dist/src/plugin/shared/vault-routing-purpose.js.map +1 -1
  63. package/dist/src/plugin/shared/vault-routing.d.ts +8 -1
  64. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  65. package/dist/src/plugin/shared/vault-routing.js +12 -4
  66. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  67. package/dist/src/plugin/storage.d.ts +1 -0
  68. package/dist/src/plugin/storage.d.ts.map +1 -1
  69. package/dist/src/plugin/storage.js +3 -3
  70. package/dist/src/plugin/storage.js.map +1 -1
  71. package/dist/src/plugin/vault-custody.d.ts +6 -13
  72. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  73. package/dist/src/plugin/vault-custody.js +19 -16
  74. package/dist/src/plugin/vault-custody.js.map +1 -1
  75. package/dist/tui-build-map.json +5 -5
  76. package/dist/tui-ga-build-map.json +1 -1
  77. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -5
  78. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  79. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  80. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  81. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +71 -16
  82. package/dist/types/src/ga/server/index.d.ts +1 -1
  83. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  84. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  85. package/dist/types/src/plugin/config/models.d.ts +1 -1
  86. package/dist/types/src/plugin/config/models.d.ts.map +1 -1
  87. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  88. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  89. package/dist/types/src/plugin/index.d.ts.map +1 -1
  90. package/dist/types/src/plugin/request.d.ts.map +1 -1
  91. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  92. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  93. package/dist/types/src/plugin/shared/request-services.d.ts +2 -0
  94. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  95. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  96. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  97. package/dist/types/src/plugin/shared/vault-routing.d.ts +8 -1
  98. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  99. package/dist/types/src/plugin/storage.d.ts +1 -0
  100. package/dist/types/src/plugin/storage.d.ts.map +1 -1
  101. package/dist/types/src/plugin/vault-custody.d.ts +6 -13
  102. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  103. package/package.json +2 -2
  104. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -5
  105. package/src/common-auth-embedded/claustrum/custody.js +31 -14
  106. package/src/common-auth-embedded/fs/private-files.js +8 -3
  107. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  108. package/src/common-auth-embedded/opencode2/index.js +1 -1
  109. package/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  110. package/src/common-auth-embedded/opencode2/install.js +14 -4
  111. package/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  112. package/src/common-auth-embedded/routing-accessor/index.d.ts +71 -16
  113. package/src/common-auth-embedded/routing-accessor/index.js +123 -17
  114. package/src/common-auth-embedded/setup/process-fence.js +20 -3
  115. package/src/common-auth-embedded/source-output.json +44 -44
  116. package/src/common-auth-embedded/store/mutate.js +34 -13
  117. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +8 -3
  118. package/src/tui-raw/common-auth-embedded/fs/private-files.js +8 -3
@@ -1,13 +1,20 @@
1
- import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
1
+ import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile, type ScopedInventoryRow } from '@cortexkit/claustrum-client';
2
2
  import { type ClaustrumLogger } from './errors.js';
3
3
  import type { InsulaUsageTransport } from './insula.js';
4
4
  import { type ClaustrumUsageReading, type ClaustrumUsageReportState, type ScopedUsageSource } from './usage.js';
5
5
  import { type ScopedWatchSource, type WatchMode } from './watch.js';
6
+ type ScopedRow = Omit<ScopedInventoryRow, 'authMethod'> & {
7
+ readonly authMethod?: string;
8
+ };
9
+ type ScopedInventory = Omit<Awaited<ReturnType<ClaustrumClient['listScoped']>>, 'rows'> & {
10
+ readonly rows: readonly ScopedRow[];
11
+ };
6
12
  /**
7
13
  * claustrum-client adds watchScoped in 0.12.0 and reportUsageScoped in 0.14.0.
8
14
  * Older clients keep polling and simply do not send reply quota readings.
9
15
  */
10
- export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
16
+ export type ClaustrumScopedClient = Pick<ClaustrumClient, 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
17
+ listScoped(enrollmentToken?: string): Promise<ScopedInventory>;
11
18
  insula?: InsulaUsageTransport;
12
19
  } & ScopedWatchSource & ScopedUsageSource;
13
20
  /** The two credential types a plugin's family can hold; routing differs by type. */
@@ -16,7 +23,8 @@ export type VaultCredentialType = 'oauth' | 'api_key';
16
23
  * Which vault rows belong to this plugin. `refreshAdapter` classifies an OAuth
17
24
  * row by the protocol it speaks; `category` is the grant that authorizes this
18
25
  * consumer to read it. Static API keys carry no refresh adapter, so they are
19
- * admitted only when `apiKeys` is set and only by category.
26
+ * admitted only when `apiKeys` is set. If a row declares an auth method, it
27
+ * must agree with the credential type.
20
28
  */
21
29
  export interface ClaustrumFamily {
22
30
  refreshAdapter: string;
@@ -111,8 +119,10 @@ export interface VaultInventory {
111
119
  readonly credentials: readonly VaultCredential[];
112
120
  readonly skipped: readonly SkippedVaultRecord[];
113
121
  /**
114
- * Classifying families only: declared policy codes or the fixed library codes
115
- * `unknown-auth-method`, `unmapped` and `unclassified`, never classifier errors.
122
+ * Refused rows and their codes, never classifier errors. Category families
123
+ * omit this field if no rows were refused and use only `unknown-auth-method`.
124
+ * Classifying families can also use declared policy codes, `unmapped` and
125
+ * `unclassified`.
116
126
  */
117
127
  readonly refused?: readonly {
118
128
  credentialId?: string;
@@ -364,3 +374,4 @@ export declare class ClaustrumScopedCustody {
364
374
  /** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
365
375
  dispose(onTimeout?: (pendingOperations: number) => void): Promise<void>;
366
376
  }
377
+ export {};
@@ -145,22 +145,38 @@ function credentialTypeOf(row, family) {
145
145
  }
146
146
  return { kind: 'refused', code: 'unclassified' };
147
147
  }
148
- if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
148
+ const type = row.credentialType;
149
+ if (type === 'oauth') {
150
+ if (row.refreshAdapter !== family.refreshAdapter)
151
+ return notMine;
152
+ }
153
+ else if (type === 'api_key') {
154
+ if (!family.apiKeys || row.refreshAdapter !== undefined)
155
+ return notMine;
156
+ }
157
+ else {
149
158
  return notMine;
150
- if (row.credentialType === 'oauth')
151
- return row.refreshAdapter === family.refreshAdapter
152
- ? { kind: 'mine', type: 'oauth' }
153
- : notMine;
154
- if (row.credentialType === 'api_key' && family.apiKeys)
155
- return row.refreshAdapter === undefined
156
- ? { kind: 'mine', type: 'api_key' }
157
- : notMine;
158
- return notMine;
159
+ }
160
+ const { authMethod } = rowFactsOf(row, { includeProviderIds: false });
161
+ // Older vaults omit the method. If present, it must match the serving type.
162
+ if (authMethod !== undefined) {
163
+ const matchesType = type === 'oauth'
164
+ ? authMethod === 'chatgpt' ||
165
+ authMethod === 'antigravity' ||
166
+ authMethod === 'oauth'
167
+ : authMethod === 'apikey';
168
+ if (!matchesType)
169
+ return { kind: 'refused', code: 'unknown-auth-method' };
170
+ }
171
+ return { kind: 'mine', type };
159
172
  }
160
173
  /** Structural access keeps the public facts independent of client declarations. */
161
- function rowFactsOf(row) {
174
+ function rowFactsOf(row, { includeProviderIds = true } = {}) {
162
175
  const metadata = row;
163
- return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
176
+ return {
177
+ providerIds: includeProviderIds ? metadata.providerIds : undefined,
178
+ authMethod: metadata.authMethod,
179
+ };
164
180
  }
165
181
  /**
166
182
  * The grants named in the vault's list reply, or undefined when it names none.
@@ -513,14 +529,15 @@ export class ClaustrumScopedCustody {
513
529
  for (const record of skipped)
514
530
  this.#logger.warn('skipped malformed vault record', record);
515
531
  const grantReach = grantReachOf(inventory);
532
+ const classifying = 'classify' in this.#family;
516
533
  return {
517
534
  view: inventory.view,
518
535
  credentials: Object.freeze(credentials),
519
536
  skipped: Object.freeze(skipped),
520
- ...('classify' in this.#family && {
537
+ ...((classifying || refused.length > 0) && {
521
538
  refused: Object.freeze(refused),
522
- notMine,
523
539
  }),
540
+ ...(classifying && { notMine }),
524
541
  ...(grantReach && { grantReach }),
525
542
  };
526
543
  }
@@ -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,36 @@ 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
+ /**
41
+ * The routable set: routes the vault allows, minus any the user's own rules
42
+ * exclude. It is not the account the plugin's local selection would choose,
43
+ * so it can include routes that selection would skip for model or quota
44
+ * reasons; routing picks among them.
45
+ */
21
46
  candidates: readonly Candidate[];
22
47
  /** Defaults to 1500 ms, above routing's normal tail; clamped to 1–2000 ms. */
23
48
  deadlineMs?: number;
@@ -33,7 +58,24 @@ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCan
33
58
  holdWaitMaxS?: number;
34
59
  /** Plugin sticky choice's vault credential id; an eligible-account hint, not a pin. */
35
60
  warmCredentialId?: string;
36
- }
61
+ } & ({
62
+ mode?: never;
63
+ requestId?: never;
64
+ exhausted?: never;
65
+ } | {
66
+ /**
67
+ * Ask routing whether a run should move off its pinned account. Send to
68
+ * the selected account, or wait on it if the answer includes a hold.
69
+ * With `refusals: true`, a `{refused}` answer means keep the run paused
70
+ * on its account until the reset or, for `signed_out`, until the user
71
+ * signs in. Do not ask again while paused.
72
+ */
73
+ mode: 'continue';
74
+ /** One id per question (e.g. a fresh UUID); reuse it only to retry that same question. */
75
+ requestId: string;
76
+ /** Required on a continue: a proved usage limit or a definite sign-in signal. */
77
+ exhausted: ContinueExhaustion;
78
+ });
37
79
  export interface RoutingHold {
38
80
  /** Uncapped advice from routing. The plugin must apply its own hold cap. */
39
81
  retry_after_ms: number;
@@ -47,6 +89,7 @@ export type RoutingRefusal = {
47
89
  refused: {
48
90
  code: 'account_limit_exhausted' | 'account_selection_refused' | 'account_selection_final';
49
91
  routingCode?: string;
92
+ reason?: string;
50
93
  retryAfterSecs?: number;
51
94
  resetsAtMs?: number;
52
95
  };
@@ -110,7 +153,21 @@ export type ReportRoutingInput = (RoutingReportIdentity & ({
110
153
  * as 403 or 429. Must match `^[a-z0-9._-]{1,64}$`.
111
154
  */
112
155
  providerCode: string;
113
- })) | {
156
+ })) | (RoutingReportIdentity & {
157
+ /**
158
+ * Report a 429 or similar response that isn't a proved quota limit. With
159
+ * no provider retry time, use the final attempt's receipt time + 5,000 ms.
160
+ * Routing blocks only new admissions on the account until `retryAtMs`.
161
+ * The session's pin stays: wait until `retryAtMs` and retry the run on
162
+ * the same account. For a proved quota limit, report `exhausted` and ask
163
+ * routing to continue with the exhausted window. Use `credential_refused`
164
+ * for an API key refused for any use.
165
+ */
166
+ kind: 'transient_backoff';
167
+ /** Absolute retry time in Unix milliseconds. */
168
+ retryAtMs: number;
169
+ providerCode?: string;
170
+ }) | {
114
171
  sessionId: string;
115
172
  kind: 'turn_notes_supported';
116
173
  model: string;
@@ -175,20 +232,18 @@ export declare function turnNotes(sessionId: string): readonly {
175
232
  * Ask routing for an eligible vault route. Any failure or unfamiliar answer
176
233
  * yields undefined so the plugin can keep its own choice. Opted-in routing
177
234
  * 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.
235
+ * pass an account the vault refused. Beyond that, a plugin may leave accounts
236
+ * out only under a user-configured eligibility rule, such as a killswitch floor
237
+ * the user turned on (the minimum share of a quota window an account must keep
238
+ * to be offered) or a per-model account list. Plugins ship no floors of
239
+ * their own by default. Routing's pick is final: never reject it under a local
240
+ * floor or choose another account afterwards.
186
241
  */
187
242
  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
243
  /**
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.
244
+ * Report a vault request, account backoff, billing result, plugin wait or
245
+ * turn-note event without waiting for routing. Only contract fields are sent,
246
+ * and all accessor failures are ignored. Headers must already be limited to
247
+ * rate-limit headers by the caller; values are not filtered or redacted here.
193
248
  */
194
249
  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,