@cortexkit/opencode-antigravity-auth 3.0.29 → 3.0.31

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 (188) hide show
  1. package/dist/cli.js +783 -254
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +145 -77
  4. package/dist/index.js +842 -297
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +177 -85
  7. package/dist/server.js +842 -300
  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 +4 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +34 -8
  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/file-read-cache.js +10 -5
  28. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  29. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  30. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  31. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  32. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  33. package/dist/src/common-auth-embedded/limits/axes.d.ts +69 -0
  34. package/dist/src/common-auth-embedded/limits/decide.d.ts +146 -0
  35. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  36. package/dist/src/common-auth-embedded/limits/families.d.ts +59 -0
  37. package/dist/src/common-auth-embedded/limits/marker.d.ts +69 -0
  38. package/dist/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  39. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  40. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  41. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  42. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  43. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  44. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  45. package/dist/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  46. package/dist/src/common-auth-embedded/opencode2/install.js +219 -27
  47. package/dist/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  48. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  49. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  50. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  51. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  52. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  53. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  54. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  55. package/dist/src/common-auth-embedded/setup/enroll.js +7 -1
  56. package/dist/src/common-auth-embedded/source-output.json +260 -124
  57. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  58. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  59. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  60. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  61. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  62. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  63. package/dist/src/common-auth-embedded/store/limits-namespace.js +46 -0
  64. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  65. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  66. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  67. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  68. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  69. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  70. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  71. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  72. package/dist/src/plugin/__fixtures__/release-model-ids.js +0 -1
  73. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  74. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  75. package/dist/src/plugin/account-access.js +1 -1
  76. package/dist/src/plugin/request.d.ts.map +1 -1
  77. package/dist/src/plugin/request.js +3 -2
  78. package/dist/src/plugin/request.js.map +1 -1
  79. package/dist/src/plugin/shared/request-services.d.ts +1 -1
  80. package/dist/src/plugin/shared/request-services.js +1 -1
  81. package/dist/src/runtime-layout.d.ts +9 -2
  82. package/dist/src/runtime-layout.d.ts.map +1 -1
  83. package/dist/src/runtime-layout.js +8 -8
  84. package/dist/src/runtime-layout.js.map +1 -1
  85. package/dist/src/setup.d.ts.map +1 -1
  86. package/dist/src/setup.js +29 -40
  87. package/dist/src/setup.js.map +1 -1
  88. package/dist/tui-build-map.json +9 -9
  89. package/dist/tui-ga-build-map.json +1 -1
  90. package/dist/types/src/cli.d.ts +1 -0
  91. package/dist/types/src/cli.d.ts.map +1 -1
  92. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  93. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  94. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  95. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  96. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  97. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  98. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  99. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  100. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +69 -0
  101. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +146 -0
  102. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  103. package/dist/types/src/common-auth-embedded/limits/families.d.ts +59 -0
  104. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +69 -0
  105. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  106. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  107. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  108. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  109. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  110. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  111. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  112. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  113. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  114. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  115. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  116. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  117. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  118. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  119. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  120. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  121. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  122. package/dist/types/src/plugin/request.d.ts.map +1 -1
  123. package/dist/types/src/plugin/shared/request-services.d.ts +1 -1
  124. package/dist/types/src/runtime-layout.d.ts +9 -2
  125. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  126. package/dist/types/src/setup.d.ts.map +1 -1
  127. package/package.json +3 -3
  128. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  129. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  130. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  131. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  132. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  133. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  134. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  135. package/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  136. package/src/common-auth-embedded/claustrum/roster.js +34 -8
  137. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  138. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  139. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  140. package/src/common-auth-embedded/commands/builtins.js +38 -0
  141. package/src/common-auth-embedded/fs/file-read-cache.js +10 -5
  142. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  143. package/src/common-auth-embedded/fs/private-files.js +7 -0
  144. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  145. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  146. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  147. package/src/common-auth-embedded/limits/axes.d.ts +69 -0
  148. package/src/common-auth-embedded/limits/decide.d.ts +146 -0
  149. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  150. package/src/common-auth-embedded/limits/families.d.ts +59 -0
  151. package/src/common-auth-embedded/limits/marker.d.ts +69 -0
  152. package/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  153. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  154. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  155. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  156. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  157. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  158. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  159. package/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  160. package/src/common-auth-embedded/opencode2/install.js +219 -27
  161. package/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  162. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  163. package/src/common-auth-embedded/routing/admission.js +17 -7
  164. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  165. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  166. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  167. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  168. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  169. package/src/common-auth-embedded/setup/enroll.js +7 -1
  170. package/src/common-auth-embedded/source-output.json +260 -124
  171. package/src/common-auth-embedded/store/attribution.js +3 -2
  172. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  173. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  174. package/src/common-auth-embedded/store/hooks.js +20 -5
  175. package/src/common-auth-embedded/store/index.d.ts +1 -0
  176. package/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  177. package/src/common-auth-embedded/store/limits-namespace.js +46 -0
  178. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  179. package/src/common-auth-embedded/store/pool.js +2 -0
  180. package/src/common-auth-embedded/store/provider-state.js +5 -5
  181. package/src/common-auth-embedded/store/refresh.js +1 -1
  182. package/src/common-auth-embedded/store/schema.js +9 -4
  183. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  184. package/src/common-auth-embedded/store/settings.js +11 -4
  185. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  186. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  187. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  188. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +46 -4
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from '@opencode/plugin';
2
2
  import type { SessionRequestKind, SessionRetryDecision } from '@opencode/plugin/promise/session';
3
+ import type { WaitCheckpoint } from '../limits/decide.js';
3
4
  /** The parts of the OpenCode 2 plugin context the installer uses. */
4
5
  export type OpenCode2HookContext = {
5
6
  readonly session: Pick<Plugin.Context['session'], 'hook'>;
@@ -35,6 +36,8 @@ export interface EventVerdict<Q> {
35
36
  readonly outputStarted?: boolean;
36
37
  readonly quota?: Q;
37
38
  readonly limit?: LimitSignal;
39
+ /** Applies only to this attempt, after ownership and attribution checks. */
40
+ readonly hostRetry?: RetryDisposition['hostRetry'];
38
41
  /**
39
42
  * This is the last event of the response (completed or failed); the
40
43
  * attempt ends here. On WebSocket this is the only way an attempt ends
@@ -55,6 +58,16 @@ export type HeaderEdits = Readonly<Record<string, string | null>>;
55
58
  export interface ChooseAccountInput extends RequestScope {
56
59
  /** The retry hook's advance choice (which may hold), or a request's own choice. */
57
60
  readonly phase: 'retry' | 'request';
61
+ /** Retry hook draft's attempt count; also carried by a consumed hold's wake. */
62
+ readonly hostAttempt?: number;
63
+ /** Revalidate the held account before dispatch, even if the target is not due. */
64
+ readonly wake?: RetryWake;
65
+ /**
66
+ * Accounts refused by earlier reroutes of this logical request. Absent means
67
+ * empty. Holds and wakes do not exclude the held account. A snapshot, not a
68
+ * live set; supplied whether or not enforcement is enabled.
69
+ */
70
+ readonly excluded?: readonly string[];
58
71
  /**
59
72
  * The account of the attempt this one retries, when the retry hook just
60
73
  * asked the host to retry an attempt of this session and kind; otherwise
@@ -75,19 +88,43 @@ export interface ChooseAccountInput extends RequestScope {
75
88
  export interface AccountRequest extends RequestScope {
76
89
  readonly accountId: string;
77
90
  }
91
+ /** The held account is ChooseAccountInput.previousAccountId. */
92
+ export interface RetryWake {
93
+ readonly target: number;
94
+ readonly checkpoint?: WaitCheckpoint;
95
+ /** Terminal quota waits do not require the session's provider prompt-cache TTL. */
96
+ readonly kind?: 'hold' | 'terminal';
97
+ }
78
98
  /** An explicit retry on the refused account, without moving its routing pin. */
79
99
  export interface RetryHold {
80
100
  readonly hold: {
81
101
  /**
82
102
  * Adapter-computed wait in milliseconds, including per-session jitter.
83
- * Finite, non-negative values are clamped to MAX_RETRY_HOLD_MS (20 minutes).
84
- * Invalid values keep the host's decision and release the choice.
103
+ * Finite, non-negative values up to MAX_RETRY_HOLD_MS (3_621_000) are
104
+ * accepted. Larger or invalid values keep the host's decision and release
105
+ * the choice rather than dispatching before the requested wait has elapsed.
85
106
  */
86
107
  readonly delayMs: number;
108
+ /** An absolute wake target; its presence forces a request-phase re-check. */
109
+ readonly target?: number;
110
+ readonly checkpoint?: WaitCheckpoint;
111
+ /** Forwarded to wake.kind so terminal quota waits omit the cache bound. */
112
+ readonly kind?: RetryWake['kind'];
113
+ };
114
+ }
115
+ /** Leave the host's retry decision alone, or forbid replay of this attempt. */
116
+ export interface RetryDisposition {
117
+ readonly hostRetry: 'leave' | 'veto';
118
+ }
119
+ /** Wait through one host retry, then choose afresh without reserving an account. */
120
+ export interface RetryWaitThenReselect {
121
+ readonly waitThenReselect: {
122
+ /** Same finite, non-negative delay bound as RetryHold.hold.delayMs. */
123
+ readonly delayMs: number;
87
124
  };
88
125
  }
89
- /** Holds are valid only in phase `retry`, with a recognised account limit. */
90
- export type ChooseAccountResult = string | RetryHold | undefined;
126
+ /** Non-string choices are valid only in phase `retry`, after an account limit. */
127
+ export type ChooseAccountResult = string | RetryHold | RetryDisposition | RetryWaitThenReselect | undefined;
91
128
  /**
92
129
  * One physical send: created when an account is chosen for a request, and
93
130
  * handed back on every hook call and event that belongs to that send, so a
@@ -184,6 +221,14 @@ export interface SameAccountRetryInput extends AccountRequest {
184
221
  * limitFromError is not called before this callback in a mixed session.
185
222
  */
186
223
  readonly limit?: LimitSignal;
224
+ /**
225
+ * Set only when output had already started and our own HTTP body reader saw
226
+ * the read fail, so the host is offering to continue the step rather than
227
+ * retry it. The adapter approves by returning the same accountId when the
228
+ * account and identity are still usable; it has no prepared recovery state
229
+ * to consume, and `limit` is always absent here.
230
+ */
231
+ readonly continuation?: 'interrupted-read';
187
232
  }
188
233
  /** Request an immediate retry; a different account ID is ignored. */
189
234
  export interface SameAccountRetryResult {
@@ -194,7 +239,7 @@ export interface SameAccountRetryResult {
194
239
  * quota reading type; the installer only carries it to the `quota` event.
195
240
  * `A` is the plugin's per-attempt value (see `Attempt`).
196
241
  * `Choice` defaults to the legacy ID-only result so existing adapters' direct
197
- * callers still see IDs. Opt into holds with `ChooseAccountResult`.
242
+ * callers still see IDs. Opt into retry directives with `ChooseAccountResult`.
198
243
  */
199
244
  export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends ChooseAccountResult = string | undefined> {
200
245
  /** Every hook is scoped to this provider; other providers are untouched. */
@@ -209,11 +254,24 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
209
254
  * After a limit before any output, the retry hook makes this call itself,
210
255
  * with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
211
256
  * including the refused one, is kept for the next attempt of that session
212
- * and kind: it does not choose again. Another account retries at once;
257
+ * and kind: it does not choose again, except for a hold with a target.
258
+ * Another account retries at once;
213
259
  * the refused account keeps the host's decision and wait. `{ hold: { delayMs } }`
214
260
  * commits the refused account without changing its pin and replaces the host's
215
261
  * wait, even its no-retry decision, only for a recognised account limit before
216
- * output in an untainted session. Holds returned in phase `request` cannot
262
+ * output in a session with no foreign transport. A hold with a target releases its queued
263
+ * choice and calls again in phase `request` with `wake` and `hostAttempt`
264
+ * before fetching account headers. The adapter must check that the account
265
+ * is still eligible, still represents the same login, is still available
266
+ * from the credential store and has any required provider prompt-cache TTL
267
+ * remaining, then choose normally if invalid.
268
+ * A hold without a target takes the queued account as before.
269
+ * `{ hostRetry: 'veto' }` forbids replay; `'leave'` preserves the host's decision
270
+ * without reserving an account. `{ waitThenReselect: { delayMs } }` asks for one
271
+ * delayed host retry, then chooses afresh. It commits no account or routing pin.
272
+ * Like holds, its delay must fit MAX_RETRY_HOLD_MS and the host retry budget.
273
+ * These directives obey the same ownership, attribution and output fences.
274
+ * Non-string choices returned in phase `request` cannot
217
275
  * select an account and are treated as undefined. `undefined` or a
218
276
  * throw commits nothing: the host decides, and the next attempt chooses
219
277
  * with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
@@ -222,7 +280,8 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
222
280
  /**
223
281
  * Releases a kept retry choice that will not be used: no retry, a changed
224
282
  * model or agent, cancellation of a queued retry (session idle), session forgetting/deletion,
225
- * disposal or record eviction. A hold releases the refused account's choice.
283
+ * disposal, record eviction or a targeted hold's wake re-check. A hold
284
+ * releases the refused account's choice.
226
285
  * Called once with the original choose input plus its returned accountId,
227
286
  * never for a used choice. Awaited before any later chooseAccount for the
228
287
  * same session; errors are logged and swallowed. A model/agent change
@@ -264,6 +323,21 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
264
323
  readonly response: Response;
265
324
  readonly attempt: Attempt<A>;
266
325
  }): Promise<Response | undefined> | Response | undefined;
326
+ /**
327
+ * Optional retry policy for the final HTTP response. Runs immediately after
328
+ * `rewriteResponse` (or on the unchanged response when no rewrite is returned).
329
+ * Return `veto` to forbid host replay of a refusal the adapter formatted,
330
+ * even without a recognised limit. A veto is sticky for this attempt.
331
+ * Ownership and attribution checks still run first: a veto cannot affect a
332
+ * foreign request, a session with mixed ownership, or a retry whose attempt is
333
+ * ambiguous. `leave` or `undefined` preserves the existing retry policy,
334
+ * including an earlier veto.
335
+ */
336
+ responseRetry?(input: AccountRequest & {
337
+ readonly request: Request;
338
+ readonly response: Response;
339
+ readonly attempt: Attempt<A>;
340
+ }): Promise<'leave' | 'veto' | undefined> | 'leave' | 'veto' | undefined;
267
341
  /**
268
342
  * Optional. For an adapter whose own sender can move a request to another
269
343
  * account after `rewriteRequest` (a bridge that answers a 401 or 403 by
@@ -371,7 +445,7 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
371
445
  * A different accountId is ignored. Never move a routing pin or select another
372
446
  * account here: use chooseAccount for failover and holds.
373
447
  *
374
- * Runs only for an attributable attempt before output, and, when gated, only
448
+ * Runs for an attributable attempt before output, and, when gated, only
375
449
  * while the latest transport is owned. Unlike failover and holds, it also runs
376
450
  * in mixed-ownership sessions. The next matching owned request skips selection
377
451
  * and calls accountHeaders again for this account, so newer credentials or a
@@ -383,6 +457,12 @@ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends C
383
457
  * No choice was committed through chooseAccount; unused recovery state is
384
458
  * released through dropSameAccountRetry instead of dropChoice.
385
459
  * Errors are logged and treated as declining the retry.
460
+ * After output it also gates a host-approved continuation when the attributed
461
+ * HTTP body reader failed, no limit or veto exists, ownership is unmixed and
462
+ * the host retry budget remains. The host's decision and delay are preserved;
463
+ * the callback must decline if the account is no longer usable or its identity
464
+ * changed. Native WebSocket failures and clean but incomplete streams lack
465
+ * the structured host error fields needed to allow this exception.
386
466
  */
387
467
  retrySameAccount?(input: SameAccountRetryInput): Promise<SameAccountRetryResult | undefined> | SameAccountRetryResult | undefined;
388
468
  /**
@@ -435,6 +515,24 @@ export interface InstallOpenCode2AuthOptions {
435
515
  readonly hostCredentials?: readonly string[];
436
516
  /** Most attempts kept before the oldest is abandoned and dropped. */
437
517
  readonly maxRecords?: number;
518
+ /**
519
+ * Host retry budget, default 10. When hostAttempt leaves no retry available,
520
+ * limit holds and reroutes keep the host's decision and release their choice.
521
+ */
522
+ readonly hostRetryLimit?: number;
523
+ /**
524
+ * Reject chooser results naming a request-excluded account (default false).
525
+ * A rejected choice warns and acts like undefined: the host decides in retry,
526
+ * and request selection stops with no-account. Without this option, chooser
527
+ * results retain their existing meaning.
528
+ *
529
+ * The host supplies no logical request id. The first later attempt of the
530
+ * same session and kind consumes a queued retry's exclusions. If another
531
+ * attempt is in flight, that binding warns but keeps the exclusions. A new
532
+ * concurrent request can therefore inherit them; if it consumes the retry
533
+ * first, the actual retry instead starts a fresh token without them.
534
+ */
535
+ readonly enforceRequestExclusion?: boolean;
438
536
  readonly logger?: OpenCode2AuthLogger;
439
537
  }
440
538
  /**
@@ -442,20 +540,24 @@ export interface InstallOpenCode2AuthOptions {
442
540
  *
443
541
  * - `reroute`: refused for a limit before any output, and `chooseAccount`
444
542
  * named another account for the next attempt, so the host retries at once;
445
- * - `output-started`: output had reached the user, so no retry;
543
+ * - `output-started`: output reached the user without a safe continuation, so no retry;
544
+ * - `continue-same-account`: a witnessed HTTP read failure after output, with
545
+ * adapter-approved identity preservation; keeps the host's continuation and delay;
446
546
  * - `no-account`: the attempt had no account, so no retry;
447
547
  * - `host-decides-last-account`: refused for a limit before any output, but
448
548
  * no other account can serve the next attempt, so the host's own decision
449
549
  * (its wait, or its refusal to retry) stands and the next attempt may go
450
550
  * to the refused account again;
451
551
  * - `hold`: an explicit adapter wait on the refused account, before output;
552
+ * - `wait-then-reselect`: wait without reserving the next account;
553
+ * - `adapter-veto`: the attributed adapter disposition forbids host replay;
452
554
  * - `same-account`: the adapter requested immediate recovery on the same route,
453
555
  * without account selection, before output;
454
556
  * - `host-decides`: no limit was recognised, or the failing call cannot be
455
557
  * attributed safely (ambiguous attempts or mixed ownership in a gated
456
558
  * session), so the host's decision stands.
457
559
  */
458
- export type RetryReason = 'reroute' | 'hold' | 'same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
560
+ export type RetryReason = 'reroute' | 'hold' | 'wait-then-reselect' | 'adapter-veto' | 'same-account' | 'continue-same-account' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
459
561
  /**
460
562
  * The hook that picked an account. Normally `model.request`; a transport hook
461
563
  * picks only when the host skipped `model.request` for that request, which a
@@ -23,11 +23,16 @@ export interface AdmissionInput extends ExclusionInputs {
23
23
  scope?: string;
24
24
  /** Labels the scope requires an entry for; defaults to `['primary']`. */
25
25
  requiredLabels?: readonly string[];
26
+ /**
27
+ * One-dispatch exemptions keyed by row; waive only gate 4. The caller first
28
+ * validates the current account incarnation and checkpointed reset times.
29
+ */
30
+ liftedWindows?: ReadonlyMap<string, readonly WindowRef[]>;
26
31
  now: number;
27
32
  /**
28
- * Called synchronously, once per refusal at gates 2 to 4, with the row id.
33
+ * Called synchronously once per row needing a pull, including lifted windows.
29
34
  * Its return value is ignored and never awaited, so a pull the caller
30
- * starts from here cannot delay the refusal.
35
+ * starts from here cannot delay admission or a refusal.
31
36
  */
32
37
  requestPull?: (rowId: string) => void;
33
38
  }
@@ -14,7 +14,7 @@
14
14
  // 3. a required label with no entry is unknown: refused, pull requested;
15
15
  // 4. a reading at or beyond 100% whose reset is missing, unparsable or not
16
16
  // after `now` cannot confirm the exhaustion, so the window is unknown:
17
- // refused, pull requested;
17
+ // refused unless lifted for this wake dispatch; either way, pull requested;
18
18
  // 5. a reading at or beyond 100% with a future reset is exhausted: refused.
19
19
  // Gates 4 and 5 look at every projected limit, not only the required labels.
20
20
  // Stage 2 judges the credit budget across the stage-1 survivors: a row whose
@@ -36,7 +36,7 @@ export function exclusionFor(id, inputs, now) {
36
36
  }
37
37
  return undefined;
38
38
  }
39
- function judgeStageOne(id, projection, requiredLabels, now) {
39
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
40
40
  if (projection.limits.length === 0) {
41
41
  return {
42
42
  id,
@@ -60,7 +60,8 @@ function judgeStageOne(id, projection, requiredLabels, now) {
60
60
  }
61
61
  const exhausted = projection.limits.filter(readsExhausted);
62
62
  for (const limit of exhausted) {
63
- if (futureResetAt(limit, now) === undefined) {
63
+ if (futureResetAt(limit, now) === undefined &&
64
+ !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
64
65
  return {
65
66
  id,
66
67
  stage: 1,
@@ -94,6 +95,7 @@ export function admit(input) {
94
95
  const excluded = [];
95
96
  const refused = [];
96
97
  const survivors = [];
98
+ const needsPull = new Set();
97
99
  for (const row of input.rows) {
98
100
  const exclusion = exclusionFor(row.id, input, input.now);
99
101
  if (exclusion) {
@@ -105,7 +107,12 @@ export function admit(input) {
105
107
  continue;
106
108
  }
107
109
  const projection = projectQuota(row.quota, scope);
108
- const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now);
110
+ const lifted = input.liftedWindows?.get(row.id) ?? [];
111
+ if (projection.limits.some((limit) => readsExhausted(limit) &&
112
+ futureResetAt(limit, input.now) === undefined &&
113
+ lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
114
+ needsPull.add(row.id);
115
+ const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now, lifted);
109
116
  if (refusal) {
110
117
  refused.push(refusal);
111
118
  continue;
@@ -133,9 +140,12 @@ export function admit(input) {
133
140
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
134
141
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
135
142
  refused.sort(byInput);
136
- const pulls = refused
137
- .filter((refusal) => 'pullRequested' in refusal)
138
- .map((refusal) => refusal.id);
143
+ for (const refusal of refused)
144
+ if ('pullRequested' in refusal)
145
+ needsPull.add(refusal.id);
146
+ const pulls = input.rows
147
+ .filter((row) => needsPull.has(row.id))
148
+ .map((row) => row.id);
139
149
  for (const id of pulls)
140
150
  input.requestPull?.(id);
141
151
  return { admitted, refused, excluded, pulls };
@@ -0,0 +1,10 @@
1
+ export function routingHandle(sessionId) {
2
+ // The bridge can load after the auth plugin, so never cache the accessor.
3
+ const routing = Reflect.get(globalThis, Symbol.for('cortexkit.routing'));
4
+ if (typeof routing !== 'function')
5
+ return undefined;
6
+ const handle = routing(sessionId);
7
+ return typeof handle === 'object' && handle !== null
8
+ ? handle
9
+ : undefined;
10
+ }
@@ -12,6 +12,14 @@ export interface AskRoutingInput<Candidate extends RoutingCandidate = RoutingCan
12
12
  candidates: readonly Candidate[];
13
13
  /** Defaults to 500 ms, clamped to 1–2000 ms. */
14
14
  deadlineMs?: number;
15
+ /**
16
+ * Longest same-account hold, in seconds, that routing may advise. The
17
+ * holdWaitMaxS helper from `./limits` caps it by the setting and the current
18
+ * account's cache expiry, returning 0 when there is no accepted prompt cache
19
+ * worth waiting for. Fractions are floored and negatives become 0. Omit it to leave
20
+ * routing's default cap in force.
21
+ */
22
+ holdWaitMaxS?: number;
15
23
  }
16
24
  export interface RoutingHold {
17
25
  /** Uncapped advice from routing. The plugin must apply its own hold cap. */
@@ -39,9 +47,11 @@ export type ReportRoutingInput = RoutingReportIdentity & ({
39
47
  /** The exhausted quota window; keep scoped quota groups in `pool`. */
40
48
  window: '5h' | '7d';
41
49
  /**
42
- * Scoped quota group, such as `non-gemini`.
43
- * Must be a non-empty string without `:`. Omit to block the whole
44
- * account; include to block only this pool.
50
+ * Scoped quota group, such as Antigravity's `3p` or `gemini`.
51
+ * Must match `^[a-z0-9._-]{1,64}$`. Routing compares names exactly, so
52
+ * callers must lowercase names from elsewhere (e.g. `Fable` to `fable`).
53
+ * Names are never rewritten here. Omit or pass `undefined` to block the
54
+ * whole account; include to block only this pool.
45
55
  */
46
56
  pool?: string;
47
57
  /** Optional reset time in epoch milliseconds. */
@@ -1,16 +1,9 @@
1
1
  // Optional THALAMUS routing for vault mode only. Account ids here are vault
2
2
  // account ids; local pool rows are not known to the routing engine.
3
+ import { routingHandle } from './handle.js';
3
4
  function isObject(value) {
4
5
  return typeof value === 'object' && value !== null;
5
6
  }
6
- function routingHandle(sessionId) {
7
- // The bridge can load after the auth plugin, so never cache the accessor.
8
- const routing = Reflect.get(globalThis, Symbol.for('cortexkit.routing'));
9
- if (typeof routing !== 'function')
10
- return undefined;
11
- const handle = routing(sessionId);
12
- return isObject(handle) ? handle : undefined;
13
- }
14
7
  function selectionFor(answer, candidates) {
15
8
  if (!isObject(answer))
16
9
  return undefined;
@@ -56,7 +49,15 @@ export async function askRouting(input) {
56
49
  timer = setTimeout(() => resolve(undefined), deadlineMs);
57
50
  timer.unref();
58
51
  });
59
- const pending = accountFor.call(handle, { provider: input.provider, modelId: input.modelId }, { deadlineMs });
52
+ const request = {
53
+ provider: input.provider,
54
+ modelId: input.modelId,
55
+ };
56
+ const cap = input.holdWaitMaxS;
57
+ if (typeof cap === 'number' && Number.isFinite(cap)) {
58
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
59
+ }
60
+ const pending = accountFor.call(handle, request, { deadlineMs });
60
61
  if (!isObject(pending) || typeof pending.then !== 'function')
61
62
  return undefined;
62
63
  const answer = await Promise.race([pending, expired]);
@@ -100,7 +101,7 @@ export function reportRouting(input) {
100
101
  return;
101
102
  // An undefined pool means the whole account, as an omitted one does.
102
103
  if (pool !== undefined &&
103
- (typeof pool !== 'string' || pool.length === 0 || pool.includes(':')))
104
+ (typeof pool !== 'string' || !/^[a-z0-9._-]{1,64}$/.test(pool)))
104
105
  return;
105
106
  payload = {
106
107
  ...identity,
@@ -5,6 +5,11 @@ export interface PortFileEntry {
5
5
  pid: number;
6
6
  startedAt: number;
7
7
  }
8
+ interface PortFileClock {
9
+ /** Internal clock seams for deterministic boot-time checks. */
10
+ now?: () => number;
11
+ uptime?: () => number;
12
+ }
8
13
  export declare function createManagedRpcStateDirPredicate(directoryPrefix: string): (name: string) => boolean;
9
14
  export declare function isManagedRpcStateDir(name: string, directoryPrefix: string): boolean;
10
15
  export declare function getRpcDir(rpcRoot: string, directoryPrefix: string, projectDirectory: string): string;
@@ -18,8 +23,11 @@ export declare function writePortFile(dir: string, entry: {
18
23
  /** Test seam for forcing staging-name collisions; defaults to randomUUID. */
19
24
  stageName?: () => string;
20
25
  }): Promise<string>;
21
- export declare function sweepRpcState(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log?: RpcLogChannel): Promise<void>;
22
- export interface DiscoverPortFileOptions {
26
+ export declare function sweepRpcState(root: string, activeDir: string, isManagedDir: (name: string) => boolean, log?: RpcLogChannel, options?: PortFileClock & {
27
+ /** Internal seam for replacing a stale record before its identity recheck. */
28
+ beforeRemove?: (path: string) => void | Promise<void>;
29
+ }): Promise<void>;
30
+ export interface DiscoverPortFileOptions extends PortFileClock {
23
31
  /**
24
32
  * Return only the expected PID's entry, or null; never fall back to
25
33
  * another live server. Without an expected PID nothing matches, so the
@@ -29,5 +37,6 @@ export interface DiscoverPortFileOptions {
29
37
  exactPid?: boolean;
30
38
  }
31
39
  /** Internal cache validation: probe only the selected file and its PID. */
32
- export declare function portFileIdentity(dir: string, entry: PortFileEntry): Promise<string | null>;
40
+ export declare function portFileIdentity(dir: string, entry: PortFileEntry, options?: PortFileClock): Promise<string | null>;
33
41
  export declare function discoverPortFile(dir: string, expectedPid?: number, options?: DiscoverPortFileOptions): Promise<PortFileEntry | null>;
42
+ export {};
@@ -1,7 +1,36 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { chmod, mkdir, open, readdir, rename, rmdir, stat, unlink, } from 'node:fs/promises';
3
+ import { uptime } from 'node:os';
3
4
  import { join, resolve } from 'node:path';
4
5
  import { ensurePrivateDirectory, PrivateFileError, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
6
+ function staleBefore(clock) {
7
+ // A five-minute margin favors keeping a live record when clocks are uncertain.
8
+ return (clock.now ?? Date.now)() - (clock.uptime ?? uptime)() * 1000 - 300_000;
9
+ }
10
+ function isStalePortFile(entry, info, cutoff) {
11
+ const time = entry.startedAt === undefined ? info?.mtimeMs : entry.startedAt;
12
+ return typeof time === 'number' && Number.isFinite(time) && time < cutoff;
13
+ }
14
+ async function removeStalePortFile(path, raw, info, beforeRemove) {
15
+ if (!info)
16
+ return;
17
+ await beforeRemove?.(path);
18
+ try {
19
+ // A live PID may have replaced its old record while the sweep was reading it.
20
+ const current = await readPrivateText(path);
21
+ const identity = await stat(path);
22
+ if (current === raw &&
23
+ identity.dev === info.dev &&
24
+ identity.ino === info.ino &&
25
+ identity.mtimeMs === info.mtimeMs &&
26
+ identity.size === info.size)
27
+ await unlink(path).catch(() => { });
28
+ }
29
+ catch (error) {
30
+ if (error instanceof PrivateFileError && error.code !== 'ENOENT')
31
+ throw error;
32
+ }
33
+ }
5
34
  /**
6
35
  * A PID a liveness probe may address. `process.kill(0 | negative, 0)` signals
7
36
  * a process group rather than a process, and an unsafe integer cannot name a
@@ -117,7 +146,8 @@ export async function writePortFile(dir, entry, options = {}) {
117
146
  throw error;
118
147
  }
119
148
  }
120
- export async function sweepRpcState(root, activeDir, isManagedDir, log) {
149
+ export async function sweepRpcState(root, activeDir, isManagedDir, log, options = {}) {
150
+ const cutoff = staleBefore(options);
121
151
  let projectDirs;
122
152
  try {
123
153
  projectDirs = await readdir(root, { withFileTypes: true });
@@ -146,6 +176,7 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
146
176
  if (!name.startsWith('port-') || !name.endsWith('.json'))
147
177
  continue;
148
178
  const portFile = join(dir, name);
179
+ const info = await stat(portFile).catch(() => undefined);
149
180
  let raw;
150
181
  try {
151
182
  raw = await readPrivateText(portFile);
@@ -172,13 +203,16 @@ export async function sweepRpcState(root, activeDir, isManagedDir, log) {
172
203
  const entry = parsed;
173
204
  if (!pidAlive(entry.pid))
174
205
  await unlink(portFile).catch(() => { });
206
+ else if (isStalePortFile(entry, info, cutoff))
207
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
175
208
  }
176
209
  if (resolve(dir) !== active)
177
210
  await rmdir(dir).catch(() => { });
178
211
  }
179
212
  }
180
213
  /** Internal cache validation: probe only the selected file and its PID. */
181
- export async function portFileIdentity(dir, entry) {
214
+ export async function portFileIdentity(dir, entry, options = {}) {
215
+ const cutoff = staleBefore(options);
182
216
  if (!pidAlive(entry.pid))
183
217
  return null;
184
218
  const path = join(resolve(dir), `port-${entry.pid}.json`);
@@ -186,6 +220,8 @@ export async function portFileIdentity(dir, entry) {
186
220
  if (windowsPrivateFiles)
187
221
  await verifyPrivate(path, 'file');
188
222
  const info = await stat(path);
223
+ if (isStalePortFile(entry, info, cutoff))
224
+ return null;
189
225
  return `${path}:${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
190
226
  }
191
227
  catch (error) {
@@ -195,6 +231,7 @@ export async function portFileIdentity(dir, entry) {
195
231
  }
196
232
  }
197
233
  export async function discoverPortFile(dir, expectedPid, options = {}) {
234
+ const cutoff = staleBefore(options);
198
235
  let names;
199
236
  try {
200
237
  if (windowsPrivateFiles)
@@ -213,8 +250,13 @@ export async function discoverPortFile(dir, expectedPid, options = {}) {
213
250
  try {
214
251
  const parsed = JSON.parse(await readPrivateText(join(dir, name)));
215
252
  if (isUsablePortFileEntry(parsed, name)) {
216
- if (pidAlive(parsed.pid))
217
- live.push(parsed);
253
+ if (pidAlive(parsed.pid)) {
254
+ const info = parsed.startedAt === undefined
255
+ ? await stat(join(dir, name)).catch(() => undefined)
256
+ : undefined;
257
+ if (!isStalePortFile(parsed, info, cutoff))
258
+ live.push(parsed);
259
+ }
218
260
  else
219
261
  await unlink(join(dir, name)).catch(() => { });
220
262
  }
@@ -77,6 +77,12 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
77
77
  await writeEnrollmentTokenFile(path, file);
78
78
  },
79
79
  });
80
+ await fence();
81
+ const initial = await manager.status();
82
+ if (initial.state === 'approved') {
83
+ printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
84
+ return;
85
+ }
80
86
  printLine(terminal, `Asking the vault to connect ${name}…`);
81
87
  const deadline = now() + ENROLLMENT_WAIT_MS;
82
88
  let printedRequest;
@@ -84,7 +90,6 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
84
90
  let reportedCode;
85
91
  let failedProposals = 0;
86
92
  for (;;) {
87
- await fence();
88
93
  const status = await manager.reconcile();
89
94
  if (status.state === 'approved') {
90
95
  printLine(terminal, `Connected ${host} to Claustrum.`);
@@ -135,6 +140,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
135
140
  if (remaining <= 0)
136
141
  break;
137
142
  await wait(Math.min(pause, remaining));
143
+ await fence();
138
144
  }
139
145
  if (printedRequest)
140
146
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {