@cortexkit/opencode-antigravity-auth 3.0.11 → 3.0.13

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 (253) hide show
  1. package/dist/cli.js +5120 -2863
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +581 -211
  4. package/dist/index.js +4806 -2343
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +618 -244
  7. package/dist/server.js +14300 -11649
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +15 -0
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +27 -1
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +83 -2
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +337 -37
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +36 -1
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +95 -11
  18. package/dist/src/common-auth-embedded/claustrum/enrollment.js +37 -12
  19. package/dist/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  20. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +195 -0
  21. package/dist/src/common-auth-embedded/claustrum/hub.js +988 -0
  22. package/dist/src/common-auth-embedded/claustrum/index.d.ts +13 -3
  23. package/dist/src/common-auth-embedded/claustrum/index.js +37 -4
  24. package/dist/src/common-auth-embedded/claustrum/quota-writer.d.ts +8 -1
  25. package/dist/src/common-auth-embedded/claustrum/quota-writer.js +38 -66
  26. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +80 -1
  27. package/dist/src/common-auth-embedded/claustrum/roster.js +259 -12
  28. package/dist/src/common-auth-embedded/claustrum/shutdown.js +42 -0
  29. package/dist/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  30. package/dist/src/common-auth-embedded/commands/builtins.js +95 -13
  31. package/dist/src/common-auth-embedded/commands/index.d.ts +1 -1
  32. package/dist/src/common-auth-embedded/fs/file-read-cache.js +57 -0
  33. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +1 -1
  34. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +20 -11
  35. package/dist/src/common-auth-embedded/opencode2/errors.d.ts +4 -1
  36. package/dist/src/common-auth-embedded/opencode2/index.d.ts +2 -2
  37. package/dist/src/common-auth-embedded/opencode2/index.js +1 -1
  38. package/dist/src/common-auth-embedded/opencode2/install.d.ts +10 -7
  39. package/dist/src/common-auth-embedded/opencode2/install.js +318 -71
  40. package/dist/src/common-auth-embedded/opencode2/types.d.ts +78 -9
  41. package/dist/src/common-auth-embedded/quota/commit-interval.d.ts +9 -0
  42. package/dist/src/common-auth-embedded/quota/commit-interval.js +18 -0
  43. package/dist/src/common-auth-embedded/quota/pending.js +48 -0
  44. package/dist/src/common-auth-embedded/rpc/rpc-server.js +29 -19
  45. package/dist/src/common-auth-embedded/setup/command.js +52 -14
  46. package/dist/src/common-auth-embedded/setup/enroll.d.ts +1 -1
  47. package/dist/src/common-auth-embedded/setup/enroll.js +1 -1
  48. package/dist/src/common-auth-embedded/setup/register.d.ts +2 -0
  49. package/dist/src/common-auth-embedded/setup/register.js +90 -11
  50. package/dist/src/common-auth-embedded/source-output.json +188 -124
  51. package/dist/src/common-auth-embedded/store/attribution.d.ts +5 -0
  52. package/dist/src/common-auth-embedded/store/attribution.js +39 -25
  53. package/dist/src/common-auth-embedded/store/mutate.d.ts +2 -0
  54. package/dist/src/common-auth-embedded/store/mutate.js +4 -0
  55. package/dist/src/common-auth-embedded/store/pool.d.ts +22 -0
  56. package/dist/src/common-auth-embedded/store/pool.js +18 -3
  57. package/dist/src/common-auth-embedded/store/pull.js +3 -1
  58. package/dist/src/common-auth-embedded/store/quota-writer.js +312 -0
  59. package/dist/src/common-auth-embedded/store/runtime.d.ts +2 -0
  60. package/dist/src/common-auth-embedded/store/settings.d.ts +1 -1
  61. package/dist/src/common-auth-embedded/store/settings.js +16 -6
  62. package/dist/src/ga/rpc/protocol.d.ts +2 -0
  63. package/dist/src/ga/rpc/protocol.d.ts.map +1 -1
  64. package/dist/src/ga/rpc/protocol.js +2 -2
  65. package/dist/src/ga/rpc/protocol.js.map +1 -1
  66. package/dist/src/ga/server/index.d.ts.map +1 -1
  67. package/dist/src/ga/server/index.js +11 -0
  68. package/dist/src/ga/server/index.js.map +1 -1
  69. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  70. package/dist/src/ga/tui/host-ga.js +2 -1
  71. package/dist/src/ga/tui/host-ga.js.map +1 -1
  72. package/dist/src/plugin/background-vault-quota-refresh.d.ts +10 -0
  73. package/dist/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  74. package/dist/src/plugin/background-vault-quota-refresh.js +33 -5
  75. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  76. package/dist/src/plugin/command-data.d.ts +2 -2
  77. package/dist/src/plugin/command-data.d.ts.map +1 -1
  78. package/dist/src/plugin/command-data.js +2 -0
  79. package/dist/src/plugin/command-data.js.map +1 -1
  80. package/dist/src/plugin/config/operator-settings-schema.d.ts +1 -1
  81. package/dist/src/plugin/config/schema.d.ts +1 -1
  82. package/dist/src/plugin/ga-location-services.d.ts +28 -2
  83. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  84. package/dist/src/plugin/ga-location-services.js +80 -16
  85. package/dist/src/plugin/ga-location-services.js.map +1 -1
  86. package/dist/src/plugin/ga-shared-vault-custody.d.ts +64 -0
  87. package/dist/src/plugin/ga-shared-vault-custody.d.ts.map +1 -0
  88. package/dist/src/plugin/ga-shared-vault-custody.js +169 -0
  89. package/dist/src/plugin/ga-shared-vault-custody.js.map +1 -0
  90. package/dist/src/plugin/index.d.ts.map +1 -1
  91. package/dist/src/plugin/index.js +11 -1
  92. package/dist/src/plugin/index.js.map +1 -1
  93. package/dist/src/plugin/killswitch.d.ts.map +1 -1
  94. package/dist/src/plugin/killswitch.js +13 -7
  95. package/dist/src/plugin/killswitch.js.map +1 -1
  96. package/dist/src/plugin/oauth-methods.d.ts.map +1 -1
  97. package/dist/src/plugin/oauth-methods.js +3 -0
  98. package/dist/src/plugin/oauth-methods.js.map +1 -1
  99. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  100. package/dist/src/plugin/shared/request-services.js +3 -3
  101. package/dist/src/plugin/shared/request-services.js.map +1 -1
  102. package/dist/src/plugin/shared/vault-request-credentials.d.ts +8 -1
  103. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  104. package/dist/src/plugin/shared/vault-request-credentials.js +38 -5
  105. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  106. package/dist/src/plugin/ui/auth-menu.d.ts.map +1 -1
  107. package/dist/src/plugin/ui/auth-menu.js +3 -0
  108. package/dist/src/plugin/ui/auth-menu.js.map +1 -1
  109. package/dist/src/plugin/ui/quota-status.d.ts.map +1 -1
  110. package/dist/src/plugin/ui/quota-status.js +4 -2
  111. package/dist/src/plugin/ui/quota-status.js.map +1 -1
  112. package/dist/src/plugin/vault-custody.d.ts +28 -7
  113. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  114. package/dist/src/plugin/vault-custody.js +200 -37
  115. package/dist/src/plugin/vault-custody.js.map +1 -1
  116. package/dist/src/plugin/vault-insula-quota.d.ts.map +1 -1
  117. package/dist/src/plugin/vault-insula-quota.js +4 -0
  118. package/dist/src/plugin/vault-insula-quota.js.map +1 -1
  119. package/dist/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  120. package/dist/src/process-heartbeat.d.ts +76 -0
  121. package/dist/src/process-heartbeat.d.ts.map +1 -0
  122. package/dist/src/process-heartbeat.js +248 -0
  123. package/dist/src/process-heartbeat.js.map +1 -0
  124. package/dist/src/setup.d.ts.map +1 -1
  125. package/dist/src/setup.js +3 -0
  126. package/dist/src/setup.js.map +1 -1
  127. package/dist/src/sidebar-projection.d.ts +3 -1
  128. package/dist/src/sidebar-projection.d.ts.map +1 -1
  129. package/dist/src/sidebar-projection.js +10 -1
  130. package/dist/src/sidebar-projection.js.map +1 -1
  131. package/dist/src/sidebar-state.d.ts +10 -1
  132. package/dist/src/sidebar-state.d.ts.map +1 -1
  133. package/dist/src/sidebar-state.js +12 -2
  134. package/dist/src/sidebar-state.js.map +1 -1
  135. package/dist/src/tui/quota-layout.d.ts +3 -1
  136. package/dist/src/tui/quota-layout.d.ts.map +1 -1
  137. package/dist/src/tui/quota-layout.js +6 -1
  138. package/dist/src/tui/quota-layout.js.map +1 -1
  139. package/dist/tui-build-map.json +9 -9
  140. package/dist/tui-ga-build-map.json +13 -13
  141. package/dist/types/src/cli.d.ts +15 -0
  142. package/dist/types/src/cli.d.ts.map +1 -1
  143. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +83 -2
  144. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +36 -1
  145. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  146. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +195 -0
  147. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +13 -3
  148. package/dist/types/src/common-auth-embedded/claustrum/quota-writer.d.ts +8 -1
  149. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +80 -1
  150. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  151. package/dist/types/src/common-auth-embedded/commands/index.d.ts +1 -1
  152. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +1 -1
  153. package/dist/types/src/common-auth-embedded/opencode2/errors.d.ts +4 -1
  154. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +2 -2
  155. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +10 -7
  156. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +78 -9
  157. package/dist/types/src/common-auth-embedded/quota/commit-interval.d.ts +9 -0
  158. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +1 -1
  159. package/dist/types/src/common-auth-embedded/setup/register.d.ts +2 -0
  160. package/dist/types/src/common-auth-embedded/store/attribution.d.ts +5 -0
  161. package/dist/types/src/common-auth-embedded/store/mutate.d.ts +2 -0
  162. package/dist/types/src/common-auth-embedded/store/pool.d.ts +22 -0
  163. package/dist/types/src/common-auth-embedded/store/runtime.d.ts +2 -0
  164. package/dist/types/src/common-auth-embedded/store/settings.d.ts +1 -1
  165. package/dist/types/src/ga/rpc/protocol.d.ts +2 -0
  166. package/dist/types/src/ga/rpc/protocol.d.ts.map +1 -1
  167. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  168. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts +10 -0
  169. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  170. package/dist/types/src/plugin/command-data.d.ts +2 -2
  171. package/dist/types/src/plugin/command-data.d.ts.map +1 -1
  172. package/dist/types/src/plugin/ga-location-services.d.ts +28 -2
  173. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  174. package/dist/types/src/plugin/ga-shared-vault-custody.d.ts +64 -0
  175. package/dist/types/src/plugin/ga-shared-vault-custody.d.ts.map +1 -0
  176. package/dist/types/src/plugin/index.d.ts.map +1 -1
  177. package/dist/types/src/plugin/killswitch.d.ts.map +1 -1
  178. package/dist/types/src/plugin/oauth-methods.d.ts.map +1 -1
  179. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  180. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +8 -1
  181. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  182. package/dist/types/src/plugin/ui/auth-menu.d.ts.map +1 -1
  183. package/dist/types/src/plugin/ui/quota-status.d.ts.map +1 -1
  184. package/dist/types/src/plugin/vault-custody.d.ts +28 -7
  185. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  186. package/dist/types/src/plugin/vault-insula-quota.d.ts.map +1 -1
  187. package/dist/types/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  188. package/dist/types/src/process-heartbeat.d.ts +76 -0
  189. package/dist/types/src/process-heartbeat.d.ts.map +1 -0
  190. package/dist/types/src/setup.d.ts.map +1 -1
  191. package/dist/types/src/sidebar-state.d.ts +10 -1
  192. package/dist/types/src/sidebar-state.d.ts.map +1 -1
  193. package/package.json +2 -2
  194. package/src/common-auth-embedded/claustrum/consumer.d.ts +83 -2
  195. package/src/common-auth-embedded/claustrum/consumer.js +337 -37
  196. package/src/common-auth-embedded/claustrum/custody.d.ts +36 -1
  197. package/src/common-auth-embedded/claustrum/custody.js +95 -11
  198. package/src/common-auth-embedded/claustrum/enrollment.js +37 -12
  199. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  200. package/src/common-auth-embedded/claustrum/hub.d.ts +195 -0
  201. package/src/common-auth-embedded/claustrum/hub.js +988 -0
  202. package/src/common-auth-embedded/claustrum/index.d.ts +13 -3
  203. package/src/common-auth-embedded/claustrum/index.js +37 -4
  204. package/src/common-auth-embedded/claustrum/quota-writer.d.ts +8 -1
  205. package/src/common-auth-embedded/claustrum/quota-writer.js +38 -66
  206. package/src/common-auth-embedded/claustrum/roster.d.ts +80 -1
  207. package/src/common-auth-embedded/claustrum/roster.js +259 -12
  208. package/src/common-auth-embedded/claustrum/shutdown.js +42 -0
  209. package/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  210. package/src/common-auth-embedded/commands/builtins.js +95 -13
  211. package/src/common-auth-embedded/commands/index.d.ts +1 -1
  212. package/src/common-auth-embedded/fs/file-read-cache.js +57 -0
  213. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +1 -1
  214. package/src/common-auth-embedded/fs/refresh-file-lock.js +20 -11
  215. package/src/common-auth-embedded/opencode2/errors.d.ts +4 -1
  216. package/src/common-auth-embedded/opencode2/index.d.ts +2 -2
  217. package/src/common-auth-embedded/opencode2/index.js +1 -1
  218. package/src/common-auth-embedded/opencode2/install.d.ts +10 -7
  219. package/src/common-auth-embedded/opencode2/install.js +318 -71
  220. package/src/common-auth-embedded/opencode2/types.d.ts +78 -9
  221. package/src/common-auth-embedded/quota/commit-interval.d.ts +9 -0
  222. package/src/common-auth-embedded/quota/commit-interval.js +18 -0
  223. package/src/common-auth-embedded/quota/pending.js +48 -0
  224. package/src/common-auth-embedded/rpc/rpc-server.js +29 -19
  225. package/src/common-auth-embedded/setup/command.js +52 -14
  226. package/src/common-auth-embedded/setup/enroll.d.ts +1 -1
  227. package/src/common-auth-embedded/setup/enroll.js +1 -1
  228. package/src/common-auth-embedded/setup/register.d.ts +2 -0
  229. package/src/common-auth-embedded/setup/register.js +90 -11
  230. package/src/common-auth-embedded/source-output.json +188 -124
  231. package/src/common-auth-embedded/store/attribution.d.ts +5 -0
  232. package/src/common-auth-embedded/store/attribution.js +39 -25
  233. package/src/common-auth-embedded/store/mutate.d.ts +2 -0
  234. package/src/common-auth-embedded/store/mutate.js +4 -0
  235. package/src/common-auth-embedded/store/pool.d.ts +22 -0
  236. package/src/common-auth-embedded/store/pool.js +18 -3
  237. package/src/common-auth-embedded/store/pull.js +3 -1
  238. package/src/common-auth-embedded/store/quota-writer.js +312 -0
  239. package/src/common-auth-embedded/store/runtime.d.ts +2 -0
  240. package/src/common-auth-embedded/store/settings.d.ts +1 -1
  241. package/src/common-auth-embedded/store/settings.js +16 -6
  242. package/src/plugin/command-data.ts +4 -2
  243. package/src/sidebar-state.ts +23 -3
  244. package/src/tui-compiled/sidebar-state.js +4 -3
  245. package/src/tui-compiled/tui/quota-layout.js +3 -2
  246. package/src/tui-ga-compiled/host-ga.js +2 -1
  247. package/src/tui-ga-compiled/shared/8ae1927e5910ea81-sidebar-projection.js +9 -2
  248. package/src/tui-ga-compiled/shared/dd4c9e1a907f8ef0-quota-layout.js +3 -2
  249. package/src/tui-ga-raw/host-ga.tsx +12 -1
  250. package/src/tui-ga-raw/shared/8ae1927e5910ea81-sidebar-projection.js +9 -2
  251. package/src/tui-ga-raw/shared/dd4c9e1a907f8ef0-quota-layout.tsx +9 -2
  252. package/src/tui-raw/sidebar-state.js +4 -3
  253. package/src/tui-raw/tui/quota-layout.tsx +9 -2
@@ -28,7 +28,7 @@ type RefreshFileLockOptions = {
28
28
  onContended?: () => void;
29
29
  /** Synchronous, never awaited; throws and returned promise/thenable rejections are isolated. */
30
30
  onRenewalTimer?: (event: 'scheduled' | 'cancelled') => void;
31
- onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
31
+ onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lease-contention-read-ready' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
32
32
  };
33
33
  /** Filesystem leases share wall time across all callers and processes. */
34
34
  export declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
@@ -178,19 +178,28 @@ export async function acquireRefreshFileLockWithClock(options) {
178
178
  }
179
179
  async function leaseContention(error) {
180
180
  const code = error.code;
181
- if (code === 'EEXIST') {
182
- if (windowsPrivateFiles)
183
- await readOwner();
184
- return true;
185
- }
186
- if (code === 'EISDIR') {
187
- if (windowsPrivateFiles) {
188
- await verifyPrivate(lockPath, 'directory', true);
189
- await readPrivateText(legacyOwnerPath, true);
181
+ if (code !== 'EEXIST' && code !== 'EISDIR')
182
+ return false;
183
+ if (windowsPrivateFiles) {
184
+ if (options.onStep)
185
+ await options.onStep('lease-contention-read-ready');
186
+ try {
187
+ if (code === 'EISDIR') {
188
+ await verifyPrivate(lockPath, 'directory', true);
189
+ await readPrivateText(legacyOwnerPath, true);
190
+ }
191
+ else
192
+ await readOwner();
193
+ }
194
+ catch (readError) {
195
+ // The holder can release after exclusive creation reports a collision.
196
+ // Only absence permits another acquisition attempt; security and sharing
197
+ // refusals must still escape rather than being treated as contention.
198
+ if (readError.code !== 'ENOENT')
199
+ throw readError;
190
200
  }
191
- return true;
192
201
  }
193
- return false;
202
+ return true;
194
203
  }
195
204
  async function tryAcquire() {
196
205
  if (windowsPrivateFiles)
@@ -8,8 +8,11 @@
8
8
  * - `host-credential-on-wire`: after every rewrite, a header still carried
9
9
  * one of the host's placeholder credentials. Sending it would leak a
10
10
  * non-routable value to the provider and fail with a confusing error.
11
+ * - `placement-refused`: an opt-in placeholder gate found the placeholder in
12
+ * multiple headers or outside the credential location it can serve. No
13
+ * account has been selected and no account headers have been read.
11
14
  */
12
- export type OpenCode2AuthFailureKind = 'no-account' | 'host-credential-on-wire';
15
+ export type OpenCode2AuthFailureKind = 'no-account' | 'host-credential-on-wire' | 'placement-refused';
13
16
  export declare class OpenCode2AuthError extends Error {
14
17
  readonly kind: OpenCode2AuthFailureKind;
15
18
  readonly providerID: string;
@@ -1,8 +1,8 @@
1
1
  export type { OpenCode2AuthFailureKind } from './errors.js';
2
2
  export { OpenCode2AuthError } from './errors.js';
3
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
3
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_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';
7
7
  export { watchServerSentEvents } from './sse.js';
8
- export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryReason, SelectingHook, Transport, } from './types.js';
8
+ export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryHold, RetryReason, SelectingHook, Transport, } from './types.js';
@@ -1,4 +1,4 @@
1
1
  export { OpenCode2AuthError } from './errors.js';
2
- export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
2
+ export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, MAX_RETRY_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,5 +1,7 @@
1
- import type { HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
1
+ import type { ChooseAccountResult, HeaderEdits, InstallOpenCode2AuthOptions, OpenCode2AuthAdapter, OpenCode2AuthInstallation, OpenCode2HookContext } from './types.js';
2
2
  export declare const DEFAULT_MAX_RECORDS = 512;
3
+ /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
4
+ export declare const MAX_RETRY_HOLD_MS: number;
3
5
  /**
4
6
  * The request header `model.request` sets to the attempt it started. The
5
7
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -26,8 +28,9 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
26
28
  * whether output has started and when the response ended, attributed to
27
29
  * an attempt by the rules below;
28
30
  * - `retry` asks the host to retry at once when an account was refused
29
- * before any output, so `model.request` runs again and can pick another
30
- * account, and refuses to retry once output has started.
31
+ * before any output and `chooseAccount` names another account for the
32
+ * next attempt, keeps the host's decision when the refused account was the
33
+ * last one that can serve, and refuses to retry once output has started.
31
34
  *
32
35
  * Attribution. A send belongs to the attempt named by the mark
33
36
  * `model.request` left on it, so several attempts of one session and kind
@@ -48,8 +51,8 @@ export declare function applyHeaderEdits(target: Record<string, string>, edits:
48
51
  * compares the host-prepared secret exactly, then selects a fresh attempt only
49
52
  * for an owned send. Request-object attribution therefore needs no attempt
50
53
  * header. Frames are owned by the latest handshake of their session and kind;
51
- * retry runs only when the session's latest transport was owned. The host's
52
- * retry hook has no request identity, so concurrent mixed-ownership calls
53
- * cannot be distinguished there; owned retries retain the heuristic above.
54
+ * retry runs only when the session's latest transport was owned and the session
55
+ * has never mixed owned and foreign transports. The host's retry hook has no
56
+ * request identity, so a mixed session must keep the host's retry decision.
54
57
  */
55
- export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
58
+ export declare function installOpenCode2Auth<Q, A = unknown>(ctx: OpenCode2HookContext, adapter: OpenCode2AuthAdapter<Q, A, ChooseAccountResult>, options?: InstallOpenCode2AuthOptions): Promise<OpenCode2AuthInstallation<Q, A>>;
@@ -2,6 +2,8 @@ import { OpenCode2AuthError } from './errors.js';
2
2
  import { placeholderSecret } from './integration.js';
3
3
  import { watchServerSentEvents } from './sse.js';
4
4
  export const DEFAULT_MAX_RECORDS = 512;
5
+ /** Bound adapter waits while allowing a 15-minute reset plus session jitter. */
6
+ export const MAX_RETRY_HOLD_MS = 20 * 60 * 1000;
5
7
  /**
6
8
  * The request header `model.request` sets to the attempt it started. The
7
9
  * host builds the HTTP request and the WebSocket handshake from the headers
@@ -97,8 +99,9 @@ function applyHeaderEditsTo(target, edits) {
97
99
  * whether output has started and when the response ended, attributed to
98
100
  * an attempt by the rules below;
99
101
  * - `retry` asks the host to retry at once when an account was refused
100
- * before any output, so `model.request` runs again and can pick another
101
- * account, and refuses to retry once output has started.
102
+ * before any output and `chooseAccount` names another account for the
103
+ * next attempt, keeps the host's decision when the refused account was the
104
+ * last one that can serve, and refuses to retry once output has started.
102
105
  *
103
106
  * Attribution. A send belongs to the attempt named by the mark
104
107
  * `model.request` left on it, so several attempts of one session and kind
@@ -119,9 +122,9 @@ function applyHeaderEditsTo(target, edits) {
119
122
  * compares the host-prepared secret exactly, then selects a fresh attempt only
120
123
  * for an owned send. Request-object attribution therefore needs no attempt
121
124
  * header. Frames are owned by the latest handshake of their session and kind;
122
- * retry runs only when the session's latest transport was owned. The host's
123
- * retry hook has no request identity, so concurrent mixed-ownership calls
124
- * cannot be distinguished there; owned retries retain the heuristic above.
125
+ * retry runs only when the session's latest transport was owned and the session
126
+ * has never mixed owned and foreign transports. The host's retry hook has no
127
+ * request identity, so a mixed session must keep the host's retry decision.
125
128
  */
126
129
  export async function installOpenCode2Auth(ctx, adapter, options = {}) {
127
130
  const { providerID } = adapter;
@@ -141,10 +144,50 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
141
144
  const byRequest = new WeakMap();
142
145
  /** Retries the retry hook asked for, by `sessionID:kind`. */
143
146
  const pendingRetries = new Map();
147
+ // A shared clock orders each session's retries without retaining idle session state.
148
+ let retryOrder = 0;
144
149
  // The host names only session/kind for frames and only session for retry.
145
150
  // A transport's prepared credential, never global login state, owns these.
146
151
  const ownedSockets = new Set();
147
152
  const latestTransportOwned = new Map();
153
+ const transportSeen = new Map();
154
+ const mixed = (sessionID) => {
155
+ const seen = transportSeen.get(sessionID);
156
+ return seen?.ownedSeen === true && seen.foreignSeen;
157
+ };
158
+ const recordTransport = (sessionID, owned) => {
159
+ latestTransportOwned.set(sessionID, owned);
160
+ const seen = transportSeen.get(sessionID) ?? {
161
+ ownedSeen: false,
162
+ foreignSeen: false,
163
+ };
164
+ if (owned)
165
+ seen.ownedSeen = true;
166
+ else
167
+ seen.foreignSeen = true;
168
+ transportSeen.set(sessionID, seen);
169
+ };
170
+ const transportOwned = (scope, headers) => {
171
+ const refuse = ownership?.refuseMisplaced;
172
+ const carriers = refuse
173
+ ? [...headers].filter(([, value]) => value.includes(placeholderSecret(providerID)))
174
+ : [];
175
+ const owned = owns(headers) && (!refuse || carriers.length > 0);
176
+ if (refuse) {
177
+ if (carriers.length > 0 && (carriers.length !== 1 || !owned)) {
178
+ recordTransport(scope.sessionID, false);
179
+ throw new OpenCode2AuthError({
180
+ kind: 'placement-refused',
181
+ providerID,
182
+ sessionID: scope.sessionID,
183
+ requestKind: scope.kind,
184
+ message: refuse(carriers[0]?.[0] ?? ''),
185
+ });
186
+ }
187
+ }
188
+ recordTransport(scope.sessionID, owned);
189
+ return owned;
190
+ };
148
191
  let warnedUnprovenResponse = false;
149
192
  let warnedUnmarkedSend = false;
150
193
  const listeners = new Map();
@@ -159,6 +202,42 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
159
202
  catch { }
160
203
  };
161
204
  const describe = (error) => error instanceof Error ? error.message : String(error);
205
+ // Adapter choices may enqueue work by session. Serialize their consumption
206
+ // and release so a new choice cannot overtake cleanup, even after forgetting.
207
+ const choiceWork = new Map();
208
+ const inChoiceOrder = (sessionID, run) => {
209
+ const result = (choiceWork.get(sessionID) ?? Promise.resolve()).then(run);
210
+ const settled = result.then(() => { }, () => { });
211
+ choiceWork.set(sessionID, settled);
212
+ void settled.then(() => {
213
+ if (choiceWork.get(sessionID) === settled)
214
+ choiceWork.delete(sessionID);
215
+ });
216
+ return result;
217
+ };
218
+ const afterChoiceWork = (sessionID, run) => {
219
+ const pending = choiceWork.get(sessionID);
220
+ return pending ? pending.then(() => afterChoiceWork(sessionID, run)) : run();
221
+ };
222
+ const releaseChoice = async (next) => {
223
+ try {
224
+ await adapter.dropChoice?.({ ...next.input, accountId: next.accountId });
225
+ }
226
+ catch (error) {
227
+ warn('opencode2 auth dropChoice threw; the request is unaffected', {
228
+ sessionID: next.input.sessionID,
229
+ error: describe(error),
230
+ });
231
+ }
232
+ };
233
+ const discardPending = (key) => {
234
+ const pending = pendingRetries.get(key);
235
+ pendingRetries.delete(key);
236
+ if (pending?.next) {
237
+ const next = pending.next;
238
+ void inChoiceOrder(pending.sessionID, () => releaseChoice(next));
239
+ }
240
+ };
162
241
  const emit = async (event, payload) => {
163
242
  const set = listeners.get(event);
164
243
  if (!set || set.size === 0)
@@ -204,11 +283,12 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
204
283
  /** The attempts of one session and kind, oldest first. */
205
284
  const attemptsOf = (key) => [...attempts.values()].filter((rec) => rec.key === key);
206
285
  const newestOf = (key) => attemptsOf(key).at(-1);
207
- /** Forgets an attempt, and its key's pending retry once nothing else holds the key. */
286
+ /** Forgets an attempt and any pending retry it owns, or whose key is no longer held. */
208
287
  const drop = (rec) => {
209
288
  attempts.delete(rec.id);
210
- if (!attemptsOf(rec.key).length)
211
- pendingRetries.delete(rec.key);
289
+ if (pendingRetries.get(rec.key)?.attemptId === rec.id ||
290
+ !attemptsOf(rec.key).length)
291
+ discardPending(rec.key);
212
292
  };
213
293
  const remember = (rec) => {
214
294
  attempts.set(rec.id, rec);
@@ -300,18 +380,32 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
300
380
  };
301
381
  const select = async (scope, hook, assertActive, transport) => {
302
382
  const key = keyOf(scope.sessionID, scope.kind);
303
- const retried = pendingRetries.get(key);
304
- pendingRetries.delete(key);
305
- const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
306
- supersede(key);
307
- const input = {
308
- ...scope,
309
- ...(previousAccountId === undefined ? {} : { previousAccountId }),
310
- ...(retried?.rerouteFrom === undefined
311
- ? {}
312
- : { rerouteFrom: retried.rerouteFrom }),
313
- };
314
- const accountId = await adapter.chooseAccount(input);
383
+ const { input, accountId } = await afterChoiceWork(scope.sessionID, async () => {
384
+ assertActive();
385
+ const retried = pendingRetries.get(key);
386
+ pendingRetries.delete(key);
387
+ const previousAccountId = retried?.accountId ?? newestOf(key)?.accountId;
388
+ supersede(key);
389
+ const next = retried?.next;
390
+ const matches = next !== undefined &&
391
+ next.input.modelID === scope.modelID &&
392
+ next.input.agent === scope.agent;
393
+ const input = {
394
+ ...scope,
395
+ phase: 'request',
396
+ ...(previousAccountId === undefined ? {} : { previousAccountId }),
397
+ ...(retried?.rerouteFrom ? { rerouteFrom: retried.rerouteFrom } : {}),
398
+ };
399
+ if (next && !matches) {
400
+ await inChoiceOrder(scope.sessionID, () => releaseChoice(next));
401
+ assertActive();
402
+ }
403
+ const choice = matches
404
+ ? next.accountId
405
+ : await adapter.chooseAccount(input);
406
+ const accountId = typeof choice === 'string' ? choice : undefined;
407
+ return { input, accountId };
408
+ });
315
409
  assertActive();
316
410
  let headers = {};
317
411
  let data;
@@ -519,8 +613,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
519
613
  }, scoped));
520
614
  registrations.push(await ctx.session.hook('http.request', (draft) => {
521
615
  if (ownership) {
522
- const owned = owns(draft.request.headers);
523
- latestTransportOwned.set(draft.sessionID, owned);
616
+ const owned = transportOwned(scopeOf(draft), draft.request.headers);
524
617
  if (!owned)
525
618
  return;
526
619
  }
@@ -637,12 +730,11 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
637
730
  }, scoped));
638
731
  registrations.push(await ctx.session.hook('experimental.ws.handshake', (draft) => {
639
732
  if (ownership) {
640
- const owned = owns(new Headers(draft.headers));
641
733
  const key = keyOf(draft.sessionID, draft.kind);
642
- latestTransportOwned.set(draft.sessionID, owned);
643
734
  // Clear the previous handshake's ownership before selecting: if no
644
735
  // account can serve, subsequent frames must not use the old attempt.
645
736
  ownedSockets.delete(key);
737
+ const owned = transportOwned(scopeOf(draft), new Headers(draft.headers));
646
738
  if (!owned)
647
739
  return;
648
740
  }
@@ -663,7 +755,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
663
755
  if (!account || !attempt)
664
756
  throw noAccount(rec.scope);
665
757
  await failing(rec, async () => {
666
- applyHeaderEdits(draft.headers, rec.headers);
758
+ if (!ownership?.refuseMisplaced)
759
+ applyHeaderEdits(draft.headers, rec.headers);
667
760
  const url = adapter.rewriteHandshakeURL?.({
668
761
  ...account,
669
762
  url: draft.url,
@@ -671,6 +764,8 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
671
764
  });
672
765
  if (url !== undefined)
673
766
  draft.url = url;
767
+ if (ownership?.refuseMisplaced)
768
+ applyHeaderEdits(draft.headers, rec.headers);
674
769
  guard(rec.scope, Object.entries(draft.headers));
675
770
  if (ownership)
676
771
  ownedSockets.add(rec.key);
@@ -712,10 +807,21 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
712
807
  registrations.push(await ctx.session.hook('retry', async (draft) => {
713
808
  if (ownership && latestTransportOwned.get(draft.sessionID) !== true)
714
809
  return;
810
+ const hostDecision = draft.decision;
811
+ const hostDecides = () => emit('retry', {
812
+ sessionID: draft.sessionID,
813
+ attempt: draft.attempt,
814
+ reason: 'host-decides',
815
+ hostDecision,
816
+ decision: hostDecision,
817
+ });
818
+ if (mixed(draft.sessionID)) {
819
+ await hostDecides();
820
+ return;
821
+ }
715
822
  const picked = pickForRetry(draft.sessionID);
716
823
  if (!picked)
717
824
  return;
718
- const hostDecision = draft.decision;
719
825
  if (picked === 'ambiguous') {
720
826
  // Nothing tells which open attempt failed: keep the host's
721
827
  // decision and leave every attempt as it is.
@@ -730,62 +836,179 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
730
836
  }
731
837
  const rec = picked;
732
838
  await withSelection(rec.scope, async (assertActive) => {
839
+ const checkRetryActive = assertActive;
840
+ // Recheck after entering selection before attributing an identity-less error.
841
+ if (mixed(draft.sessionID)) {
842
+ await hostDecides();
843
+ return;
844
+ }
733
845
  rec.judged = true;
734
- let decision = hostDecision;
735
- let reason;
736
- let rerouteFrom;
737
846
  const attempt = rec.attempt;
738
- if (rec.accountId === undefined || !attempt) {
739
- decision = { retry: false };
740
- reason = 'no-account';
741
- }
742
- else if (rec.outputStarted) {
743
- // The user has already seen part of this answer; a retry would
744
- // send it again.
745
- decision = { retry: false };
746
- reason = 'output-started';
747
- }
748
- else {
847
+ if (attempt && !rec.outputStarted) {
749
848
  if (!rec.limit) {
750
849
  const signal = adapter.limitFromError?.(draft.error, attempt);
751
850
  if (signal)
752
851
  noteLimit(rec, signal, 'error');
753
852
  }
754
- // The next `chooseAccount` should see whatever the plugin learnt
755
- // from how this attempt ended.
756
- if (rec.ended) {
853
+ // Account selection must observe all feedback from the refused send.
854
+ if (rec.ended)
757
855
  await rec.ended;
758
- assertActive();
759
- }
760
- if (rec.limit) {
856
+ if (rec.limit)
761
857
  await rec.limit.delivered;
762
- assertActive();
763
- rec.rerouted = true;
764
- rerouteFrom = {
765
- accountId: rec.accountId,
766
- limit: rec.limit.signal,
858
+ }
859
+ checkRetryActive();
860
+ const { decision, reason } = await inChoiceOrder(rec.scope.sessionID, async () => {
861
+ checkRetryActive();
862
+ if (mixed(draft.sessionID))
863
+ return {
864
+ decision: hostDecision,
865
+ reason: 'host-decides',
767
866
  };
768
- // No delay: the next attempt goes to another account, and the
769
- // host would otherwise wait out the refused account's backoff,
770
- // or not retry at all for errors it deems final.
771
- decision = { retry: true, delay: 0 };
772
- reason = 'reroute';
867
+ const old = pendingRetries.get(rec.key);
868
+ pendingRetries.delete(rec.key);
869
+ if (old?.next)
870
+ await releaseChoice(old.next);
871
+ checkRetryActive();
872
+ if (mixed(draft.sessionID))
873
+ return {
874
+ decision: hostDecision,
875
+ reason: 'host-decides',
876
+ };
877
+ let decision = hostDecision;
878
+ let reason;
879
+ let rerouteFrom;
880
+ let next;
881
+ if (rec.accountId === undefined || !attempt) {
882
+ decision = { retry: false };
883
+ reason = 'no-account';
884
+ }
885
+ else if (rec.outputStarted) {
886
+ // The user has already seen part of this answer; a retry would
887
+ // send it again.
888
+ decision = { retry: false };
889
+ reason = 'output-started';
773
890
  }
774
891
  else {
775
- reason = 'host-decides';
892
+ if (rec.limit) {
893
+ const refused = {
894
+ accountId: rec.accountId,
895
+ limit: rec.limit.signal,
896
+ };
897
+ // Ask the adapter now, with the same input the next attempt
898
+ // would give it, which account serves that attempt. Rerouting
899
+ // is right only when that is another account: otherwise the
900
+ // next attempt would find no account (a `no-account` refusal
901
+ // the host treats as a defect and does not retry) or go back
902
+ // at once to the account that just refused.
903
+ let choice;
904
+ const input = {
905
+ ...rec.scope,
906
+ phase: 'retry',
907
+ previousAccountId: rec.accountId,
908
+ rerouteFrom: refused,
909
+ };
910
+ try {
911
+ choice = await adapter.chooseAccount(input);
912
+ }
913
+ catch (error) {
914
+ // Treated as no other account: the host's own decision
915
+ // stands, and the next attempt asks the adapter again.
916
+ warn('opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry', {
917
+ sessionID: rec.scope.sessionID,
918
+ error: describe(error),
919
+ });
920
+ }
921
+ const hold = typeof choice === 'object' ? choice.hold : undefined;
922
+ const accountId = typeof choice === 'string'
923
+ ? choice
924
+ : hold
925
+ ? rec.accountId
926
+ : undefined;
927
+ if (accountId !== undefined)
928
+ next = { accountId, input };
929
+ try {
930
+ checkRetryActive();
931
+ }
932
+ catch (error) {
933
+ // A selection revoked while the adapter was choosing cannot be used.
934
+ if (next)
935
+ await releaseChoice(next);
936
+ throw error;
937
+ }
938
+ // A foreign transport may have arrived while choosing. Do not
939
+ // publish or retain a retry choice for an unidentified call.
940
+ if (mixed(draft.sessionID)) {
941
+ if (next)
942
+ await releaseChoice(next);
943
+ return {
944
+ decision: hostDecision,
945
+ reason: 'host-decides',
946
+ };
947
+ }
948
+ if (hold &&
949
+ Number.isFinite(hold.delayMs) &&
950
+ hold.delayMs >= 0) {
951
+ // A recognised account limit can be recoverable even when
952
+ // the host treats its provider error as final.
953
+ decision = {
954
+ retry: true,
955
+ delay: Math.min(hold.delayMs, MAX_RETRY_HOLD_MS),
956
+ };
957
+ reason = 'hold';
958
+ }
959
+ else if (!hold &&
960
+ accountId !== undefined &&
961
+ accountId !== rec.accountId) {
962
+ rec.rerouted = true;
963
+ rerouteFrom = refused;
964
+ // The next attempt takes this choice rather than asking
965
+ // again, so an account limited between here and the host's
966
+ // retry costs one refused send, which this hook judges
967
+ // again, rather than a `no-account` refusal.
968
+ // No delay: the next attempt goes to another account, and the
969
+ // host would otherwise wait out the refused account's backoff,
970
+ // or not retry at all for errors it deems final.
971
+ decision = { retry: true, delay: 0 };
972
+ reason = 'reroute';
973
+ }
974
+ else {
975
+ if (hold && next) {
976
+ await releaseChoice(next);
977
+ next = undefined;
978
+ }
979
+ // The refused account keeps the host's wait and serves the
980
+ // retry. Undefined or a throw commits nothing: choose later.
981
+ reason = 'host-decides-last-account';
982
+ }
983
+ }
984
+ else {
985
+ reason = 'host-decides';
986
+ }
776
987
  }
777
- }
778
- draft.decision = decision;
779
- // The host's retry runs `model.request` again for this attempt's
780
- // session and kind; that next attempt, and no other attempt of the
781
- // session, is told what this one ended with.
782
- if (decision.retry && rec.accountId !== undefined) {
783
- pendingRetries.set(rec.key, {
784
- sessionID: rec.scope.sessionID,
785
- accountId: rec.accountId,
786
- ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
787
- });
788
- }
988
+ draft.decision = decision;
989
+ // The host's retry runs `model.request` again for this attempt's
990
+ // session and kind; that next attempt, and no other attempt of the
991
+ // session, is told what this one ended with.
992
+ if (decision.retry &&
993
+ rec.accountId !== undefined &&
994
+ attempts.has(rec.id)) {
995
+ pendingRetries.set(rec.key, {
996
+ attemptId: rec.id,
997
+ sessionID: rec.scope.sessionID,
998
+ order: ++retryOrder,
999
+ accountId: rec.accountId,
1000
+ ...(rerouteFrom === undefined ? {} : { rerouteFrom }),
1001
+ ...(next === undefined ? {} : { next }),
1002
+ });
1003
+ }
1004
+ else if (next) {
1005
+ // Only the computed decision is final here: an incoming veto may
1006
+ // have been overridden by a reroute to another account.
1007
+ await releaseChoice(next);
1008
+ }
1009
+ return { decision, reason };
1010
+ });
1011
+ checkRetryActive();
789
1012
  await emit('retry', {
790
1013
  sessionID: draft.sessionID,
791
1014
  ...(rec.accountId === undefined
@@ -803,6 +1026,10 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
803
1026
  const forgetSession = (sessionID) => {
804
1027
  revokeSelections(sessionID);
805
1028
  latestTransportOwned.delete(sessionID);
1029
+ // A foreign send can retry after forgetting and reuse of this session id.
1030
+ // Retain its ownership history until disposal; owned-only ids need no tombstone.
1031
+ if (!transportSeen.get(sessionID)?.foreignSeen)
1032
+ transportSeen.delete(sessionID);
806
1033
  for (const key of ownedSockets) {
807
1034
  if (JSON.parse(key)[0] === sessionID)
808
1035
  ownedSockets.delete(key);
@@ -815,7 +1042,7 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
815
1042
  }
816
1043
  for (const [key, pending] of pendingRetries) {
817
1044
  if (pending.sessionID === sessionID)
818
- pendingRetries.delete(key);
1045
+ discardPending(key);
819
1046
  }
820
1047
  };
821
1048
  const abort = new AbortController();
@@ -826,6 +1053,23 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
826
1053
  for await (const event of events.subscribe({ signal: abort.signal })) {
827
1054
  if (event.type === 'session.deleted')
828
1055
  forgetSession(event.data.sessionID);
1056
+ else if (event.type === 'session.status' &&
1057
+ event.data.status.type === 'idle') {
1058
+ const sessionID = event.data.sessionID;
1059
+ const idleOrder = ++retryOrder;
1060
+ // Idle can arrive late from an earlier turn. Release only choices
1061
+ // already queued when observed, never a selection still in flight.
1062
+ void inChoiceOrder(sessionID, async () => {
1063
+ for (const [key, pending] of pendingRetries) {
1064
+ if (pending.sessionID === sessionID &&
1065
+ pending.order < idleOrder) {
1066
+ pendingRetries.delete(key);
1067
+ if (pending.next)
1068
+ await releaseChoice(pending.next);
1069
+ }
1070
+ }
1071
+ });
1072
+ }
829
1073
  }
830
1074
  }
831
1075
  catch (error) {
@@ -867,10 +1111,13 @@ export async function installOpenCode2Auth(ctx, adapter, options = {}) {
867
1111
  for (const rec of attempts.values())
868
1112
  abandon(rec, 'the installation was disposed');
869
1113
  attempts.clear();
870
- pendingRetries.clear();
1114
+ for (const key of pendingRetries.keys())
1115
+ discardPending(key);
871
1116
  ownedSockets.clear();
872
1117
  latestTransportOwned.clear();
1118
+ transportSeen.clear();
873
1119
  listeners.clear();
1120
+ await Promise.all(choiceWork.values());
874
1121
  await Promise.all(registrations.map(async (registration) => {
875
1122
  try {
876
1123
  await registration.dispose();