@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
@@ -18,7 +18,7 @@ export interface RequestScope {
18
18
  /** Where a reading or a refusal was seen. */
19
19
  export type Transport = 'http' | 'ws';
20
20
  /**
21
- * A provider refusal that should move the request to another account: a rate
21
+ * A provider refusal that should wait or move the request to another account: a rate
22
22
  * limit, an exhausted usage window, or anything else the adapter decides is
23
23
  * tied to the account rather than to the request.
24
24
  */
@@ -53,6 +53,8 @@ export interface EventVerdict<Q> {
53
53
  */
54
54
  export type HeaderEdits = Readonly<Record<string, string | null>>;
55
55
  export interface ChooseAccountInput extends RequestScope {
56
+ /** The retry hook's advance choice (which may hold), or a request's own choice. */
57
+ readonly phase: 'retry' | 'request';
56
58
  /**
57
59
  * The account of the attempt this one retries, when the retry hook just
58
60
  * asked the host to retry an attempt of this session and kind; otherwise
@@ -61,8 +63,9 @@ export interface ChooseAccountInput extends RequestScope {
61
63
  readonly previousAccountId?: string;
62
64
  /**
63
65
  * Set when the attempt this one retries was refused for a limit before any
64
- * output and the retry hook asked the host to try again. The adapter
65
- * should not pick `accountId` again unless it has nothing else.
66
+ * output. The adapter should not pick `accountId` again unless it has
67
+ * nothing else; returning it, or `undefined`, keeps the host's own retry
68
+ * decision. An explicit hold instead retains this account with its own wait.
66
69
  */
67
70
  readonly rerouteFrom?: {
68
71
  readonly accountId: string;
@@ -72,6 +75,19 @@ export interface ChooseAccountInput extends RequestScope {
72
75
  export interface AccountRequest extends RequestScope {
73
76
  readonly accountId: string;
74
77
  }
78
+ /** An explicit retry on the refused account, without moving its routing pin. */
79
+ export interface RetryHold {
80
+ readonly hold: {
81
+ /**
82
+ * 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.
85
+ */
86
+ readonly delayMs: number;
87
+ };
88
+ }
89
+ /** Holds are valid only in phase `retry`, with a recognised account limit. */
90
+ export type ChooseAccountResult = string | RetryHold | undefined;
75
91
  /**
76
92
  * One physical send: created when an account is chosen for a request, and
77
93
  * handed back on every hook call and event that belongs to that send, so a
@@ -161,16 +177,44 @@ export interface HostError {
161
177
  * Everything provider-specific the installer needs. `Q` is the plugin's own
162
178
  * quota reading type; the installer only carries it to the `quota` event.
163
179
  * `A` is the plugin's per-attempt value (see `Attempt`).
180
+ * `Choice` defaults to the legacy ID-only result so existing adapters' direct
181
+ * callers still see IDs. Opt into holds with `ChooseAccountResult`.
164
182
  */
165
- export interface OpenCode2AuthAdapter<Q = unknown, A = unknown> {
183
+ export interface OpenCode2AuthAdapter<Q = unknown, A = unknown, Choice extends ChooseAccountResult = string | undefined> {
166
184
  /** Every hook is scoped to this provider; other providers are untouched. */
167
185
  readonly providerID: string;
168
186
  /**
169
- * Picks the account for one model request. Called again for every retry,
170
- * so a refused account can be skipped. Returning `undefined` stops the
171
- * request with `OpenCode2AuthError` kind `no-account`.
187
+ * Commits an account for one attempt. An undefined answer commits nothing
188
+ * to routing state: no consumed retry entry, no queued choice, and no session
189
+ * pin created, moved or deleted. Idempotent maintenance (credential refresh
190
+ * to check usability and recording quota readings) is allowed. On a request,
191
+ * undefined stops with kind `no-account`.
192
+ *
193
+ * After a limit before any output, the retry hook makes this call itself,
194
+ * with `phase: 'retry'` and `rerouteFrom` set. Every returned account,
195
+ * including the refused one, is kept for the next attempt of that session
196
+ * and kind: it does not choose again. Another account retries at once;
197
+ * the refused account keeps the host's decision and wait. `{ hold: { delayMs } }`
198
+ * commits the refused account without changing its pin and replaces the host's
199
+ * wait, even its no-retry decision, only for a recognised account limit before
200
+ * output in an untainted session. Holds returned in phase `request` cannot
201
+ * select an account and are treated as undefined. `undefined` or a
202
+ * throw commits nothing: the host decides, and the next attempt chooses
203
+ * with `phase: 'request'`, `previousAccountId` and no `rerouteFrom`.
172
204
  */
173
- chooseAccount(input: ChooseAccountInput): Promise<string | undefined> | string | undefined;
205
+ chooseAccount(input: ChooseAccountInput): Promise<Choice> | Choice;
206
+ /**
207
+ * Releases a kept retry choice that will not be used: no retry, a changed
208
+ * model or agent, cancellation of a queued retry (session idle), session forgetting/deletion,
209
+ * disposal or record eviction. A hold releases the refused account's choice.
210
+ * Called once with the original choose input plus its returned accountId,
211
+ * never for a used choice. Awaited before any later chooseAccount for the
212
+ * same session; errors are logged and swallowed. A model/agent change
213
+ * releases the old choice before choosing afresh.
214
+ */
215
+ dropChoice?(input: ChooseAccountInput & {
216
+ readonly accountId: string;
217
+ }): Promise<void> | void;
174
218
  /**
175
219
  * The credential and per-account headers for an account, applied in
176
220
  * `model.request`, `http.request` and `experimental.ws.handshake`. The last
@@ -325,6 +369,13 @@ export interface InstallOpenCode2AuthOptions {
325
369
  */
326
370
  readonly gateOnPlaceholder?: {
327
371
  readonly credential: (headers: Headers) => string | undefined;
372
+ /**
373
+ * Refuse misplaced placeholders before selecting an account. The placeholder
374
+ * must occur in exactly one header and be the extracted secret. Receives a
375
+ * carrier header name for the refusal message. Also runs the handshake URL
376
+ * rewrite before applying account headers to the draft. Opt-in only.
377
+ */
378
+ readonly refuseMisplaced?: (header: string) => string;
328
379
  };
329
380
  /**
330
381
  * Values that must never reach the wire, normally the placeholder the host
@@ -337,7 +388,23 @@ export interface InstallOpenCode2AuthOptions {
337
388
  readonly maxRecords?: number;
338
389
  readonly logger?: OpenCode2AuthLogger;
339
390
  }
340
- export type RetryReason = 'reroute' | 'output-started' | 'no-account' | 'host-decides';
391
+ /**
392
+ * Why the retry hook decided as it did:
393
+ *
394
+ * - `reroute`: refused for a limit before any output, and `chooseAccount`
395
+ * named another account for the next attempt, so the host retries at once;
396
+ * - `output-started`: output had reached the user, so no retry;
397
+ * - `no-account`: the attempt had no account, so no retry;
398
+ * - `host-decides-last-account`: refused for a limit before any output, but
399
+ * no other account can serve the next attempt, so the host's own decision
400
+ * (its wait, or its refusal to retry) stands and the next attempt may go
401
+ * to the refused account again;
402
+ * - `hold`: an explicit adapter wait on the refused account, before output;
403
+ * - `host-decides`: no limit was recognised, or the failing call cannot be
404
+ * attributed safely (ambiguous attempts or mixed ownership in a gated
405
+ * session), so the host's decision stands.
406
+ */
407
+ export type RetryReason = 'reroute' | 'hold' | 'output-started' | 'no-account' | 'host-decides-last-account' | 'host-decides';
341
408
  /**
342
409
  * The hook that picked an account. Normally `model.request`; a transport hook
343
410
  * picks only when the host skipped `model.request` for that request, which a
@@ -404,6 +471,8 @@ export interface OpenCode2AuthInstallation<Q, A = unknown> {
404
471
  /**
405
472
  * Drops every attempt and revokes in-flight auth selections of a session.
406
473
  * Session deletion does this itself. Later requests may reuse the session id.
474
+ * Foreign transport history survives until dispose: an old foreign call can
475
+ * still retry under that reused id, so forgetting cannot clear retry taint.
407
476
  */
408
477
  forgetSession(sessionID: string): void;
409
478
  /** Number of attempts held. */
@@ -0,0 +1,9 @@
1
+ export declare const QUOTA_COMMIT_INTERVAL_MS = 30000;
2
+ export interface QuotaCommitTimer {
3
+ now(): number;
4
+ schedule(delayMs: number, run: () => Promise<void>): {
5
+ cancel(): void;
6
+ unref?(): void;
7
+ };
8
+ }
9
+ export declare const quotaCommitTimer: QuotaCommitTimer;
@@ -0,0 +1,18 @@
1
+ // Atomic quota commits create locks, markers and a renamed temp file. Keep
2
+ // those filesystem events at least 30 s apart under normal load; routing sees
3
+ // pending readings immediately, while other processes may lag by one interval.
4
+ // Shutdown drains and a full bounded pool queue can commit sooner.
5
+ // The vault shares one gate per resolved path; each pool handle has its own.
6
+ // N pool handles on one file can therefore make N normal commits per interval
7
+ // in one process. These gates do not coordinate with other processes.
8
+ export const QUOTA_COMMIT_INTERVAL_MS = 30_000;
9
+ export const quotaCommitTimer = {
10
+ now: () => performance.now(),
11
+ schedule(delayMs, run) {
12
+ const timer = setTimeout(() => void run(), delayMs);
13
+ return {
14
+ cancel: () => clearTimeout(timer),
15
+ unref: () => timer.unref?.(),
16
+ };
17
+ },
18
+ };
@@ -0,0 +1,48 @@
1
+ // Use the same independently dated parts as mergeQuotaObservation. A header
2
+ // reading cannot erase a poll-only window, counter, credits record or budget.
3
+ export function quotaFields(publication, witness = '') {
4
+ const result = new Map();
5
+ const { observation } = publication;
6
+ const add = (key, at, part) => result.set(`${witness}:${key}`, {
7
+ at,
8
+ order: 0,
9
+ publication: { ...publication, observation: part },
10
+ });
11
+ const keyFor = (scope, label) => JSON.stringify([scope ?? 'all', label]);
12
+ const read = new Set();
13
+ for (const reading of observation.readings ?? []) {
14
+ const key = keyFor(reading.scope, reading.label);
15
+ read.add(key);
16
+ add(key, observation.checkedAt, {
17
+ checkedAt: observation.checkedAt,
18
+ readings: [{ ...reading }],
19
+ });
20
+ }
21
+ for (const pair of observation.coverage ?? []) {
22
+ const key = keyFor(pair.scope, pair.label);
23
+ if (!read.has(key))
24
+ add(key, observation.checkedAt, {
25
+ checkedAt: observation.checkedAt,
26
+ coverage: [{ ...pair }],
27
+ });
28
+ }
29
+ if (observation.budget)
30
+ add('budget', observation.checkedAt, {
31
+ checkedAt: observation.checkedAt,
32
+ budget: { ...observation.budget },
33
+ });
34
+ for (const [name, counter] of Object.entries(observation.counters ?? {})) {
35
+ add(`counter:${name}`, counter.checkedAt, {
36
+ checkedAt: observation.checkedAt,
37
+ counters: { [name]: { ...counter } },
38
+ });
39
+ }
40
+ if (observation.credits)
41
+ add('credits', observation.credits.checkedAt, {
42
+ checkedAt: observation.checkedAt,
43
+ credits: { ...observation.credits },
44
+ });
45
+ if (!result.size)
46
+ add('empty', observation.checkedAt, { checkedAt: observation.checkedAt });
47
+ return result;
48
+ }
@@ -34,12 +34,8 @@ class BodyTooLargeError extends Error {
34
34
  function readBody(req) {
35
35
  return new Promise((resolve, reject) => {
36
36
  const tooLarge = (declaredOversize = false) => {
37
- // Streamed overflow drains without closing at response finish: doing so
38
- // caused EPIPE on a Bun 1.4.2 uploader. Declared oversize also drains, but
39
- // half-closes after the 413: Bun 1.3.14 reused refused fetch connections
40
- // despite Connection: close. Half-close preserved complete 413 JSON for
41
- // tested fetch and slow declared-length uploaders on both runtimes (see
42
- // research/load-probe/RPC-413-CLOSE.md for the delivery/lifecycle samples).
37
+ // Keep draining refused uploads so the client can finish sending after
38
+ // receiving the 413. The response path controls when the socket closes.
43
39
  req.removeAllListeners('data');
44
40
  req.on('data', () => { });
45
41
  req.resume();
@@ -143,20 +139,34 @@ export async function startRpcServer(options) {
143
139
  catch (error) {
144
140
  if (!(error instanceof BodyTooLargeError))
145
141
  throw error;
146
- if (error.declaredOversize) {
147
- const socket = req.socket;
148
- res.once('finish', () => {
149
- socket.end();
150
- // Bound an abandoned upload to two seconds, matching the server's
151
- // default request-delivery timeout. end() alone left Bun 1.3.14
152
- // compatibility sockets open.
153
- const timer = setTimeout(() => socket.destroy(), 2_000);
154
- timer.unref();
155
- req.once('end', () => socket.destroy());
156
- socket.once('close', () => clearTimeout(timer));
157
- if (req.complete)
158
- socket.destroy();
142
+ const socket = req.socket;
143
+ res.once('finish', () => {
144
+ socket.end();
145
+ // Bound an abandoned declared upload to two seconds, matching the
146
+ // default request-delivery timeout. On Bun 1.3.14, end() alone left
147
+ // the connection open while the client was still uploading.
148
+ const timer = setTimeout(() => socket.destroy(), 2_000);
149
+ timer.unref();
150
+ req.once('end', () => socket.destroy());
151
+ socket.once('close', () => clearTimeout(timer));
152
+ if (req.complete)
153
+ socket.destroy();
154
+ });
155
+ if (!error.declaredOversize && !req.complete) {
156
+ if (res.headersSent || res.writableEnded || res.destroyed)
157
+ return;
158
+ // Bun 1.4.4 closes Connection: close sockets at response finish even
159
+ // while an upload is in flight. Content-Length delivers complete 413
160
+ // JSON now; defer finish (and socket closure) until the body drains.
161
+ const body = JSON.stringify({ error: 'body too large' });
162
+ res.writeHead(413, {
163
+ 'content-type': 'application/json',
164
+ 'content-length': Buffer.byteLength(body),
165
+ connection: 'close',
159
166
  });
167
+ res.write(body);
168
+ req.once('end', () => res.end());
169
+ return;
160
170
  }
161
171
  return json(413, { error: 'body too large' }, { connection: 'close' });
162
172
  }
@@ -10,6 +10,7 @@ import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, Pro
10
10
  import { selectSetupHosts } from './prompts.js';
11
11
  import { planOpenCodeRegistration, registerOpenCode, registerPi, } from './register.js';
12
12
  export const AMBIGUOUS_OPENCODE_MESSAGE = 'Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.';
13
+ const UNAVAILABLE_HOST_MESSAGE = 'Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.';
13
14
  function flags(argv) {
14
15
  const result = {
15
16
  yes: false,
@@ -17,6 +18,8 @@ function flags(argv) {
17
18
  claustrum: false,
18
19
  noClaustrum: false,
19
20
  login: false,
21
+ enrollOnly: false,
22
+ hosts: [],
20
23
  opencode: undefined,
21
24
  };
22
25
  for (const arg of argv) {
@@ -30,6 +33,14 @@ function flags(argv) {
30
33
  result.noClaustrum = true;
31
34
  else if (arg === '--login')
32
35
  result.login = true;
36
+ else if (arg === '--enroll-only')
37
+ result.enrollOnly = true;
38
+ else if (arg.startsWith('--host=')) {
39
+ const host = arg.slice('--host='.length);
40
+ if (host !== 'opencode' && host !== 'pi')
41
+ throw new Error(UNAVAILABLE_HOST_MESSAGE);
42
+ result.hosts.push(host);
43
+ }
33
44
  else if (/^--opencode=(1|2|both)$/.test(arg))
34
45
  result.opencode = arg.slice('--opencode='.length);
35
46
  else
@@ -39,6 +50,10 @@ function flags(argv) {
39
50
  throw new Error('--claustrum and --no-claustrum cannot be used together.');
40
51
  if (result.login && result.claustrum)
41
52
  throw new Error('--login and --claustrum cannot be used together.');
53
+ if (result.enrollOnly && result.login)
54
+ throw new Error('--enroll-only and --login cannot be used together.');
55
+ if (result.enrollOnly && result.noClaustrum)
56
+ throw new Error('--enroll-only and --no-claustrum cannot be used together.');
42
57
  return result;
43
58
  }
44
59
  function validatePlugin(plugin) {
@@ -96,14 +111,18 @@ export async function runSetup(plugin, argv = [], io = {}) {
96
111
  if (piWithoutCli)
97
112
  printLine(terminal, 'Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.');
98
113
  const found = ['opencode', 'pi'].filter((host) => detection[host].installed && !(host === 'pi' && piWithoutCli));
114
+ if (options.hosts.some((host) => !found.includes(host)))
115
+ throw new Error(UNAVAILABLE_HOST_MESSAGE);
99
116
  // A dry run changes nothing, so without a terminal it plans the --yes path
100
117
  // instead of refusing; scripts and CI can preview setup with --dry-run alone.
101
118
  const assumeYes = options.yes || (options.dryRun && !isInteractive(terminal));
102
119
  if (!assumeYes && !isInteractive(terminal))
103
120
  throw new Error('Setup requires a TTY or --yes.');
104
- const hosts = assumeYes
105
- ? found
106
- : ((await selectSetupHosts(terminal, found)) ?? []);
121
+ const hosts = options.hosts.length
122
+ ? found.filter((host) => options.hosts.includes(host))
123
+ : assumeYes
124
+ ? found
125
+ : ((await selectSetupHosts(terminal, found)) ?? []);
107
126
  let generation = options.opencode ??
108
127
  (detection.opencode.generation === 'ambiguous'
109
128
  ? '1'
@@ -160,9 +179,10 @@ export async function runSetup(plugin, argv = [], io = {}) {
160
179
  }
161
180
  else
162
181
  await stopped();
163
- if (options.claustrum && !detection.claustrum.available)
164
- throw new Error('Claustrum is not available. Start ck or use --no-claustrum for local sign-in.');
165
- let useVault = Boolean(options.claustrum);
182
+ if ((options.claustrum || options.enrollOnly) &&
183
+ !detection.claustrum.available)
184
+ throw new Error('Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.');
185
+ let useVault = options.claustrum || options.enrollOnly;
166
186
  if (!useVault &&
167
187
  !options.login &&
168
188
  !options.noClaustrum &&
@@ -182,10 +202,20 @@ export async function runSetup(plugin, argv = [], io = {}) {
182
202
  useVault = choice === true;
183
203
  }
184
204
  const mode = useVault ? 'claustrum' : 'local';
185
- // Validate every config before login or enrollment can change credential state.
186
- const writes = hosts.includes('opencode')
205
+ // Validate configs before changing credentials; enrollment-only needs no registration plan.
206
+ const writes = !options.enrollOnly && hosts.includes('opencode')
187
207
  ? planOpenCodeRegistration(plugin, generation, io)
188
208
  : [];
209
+ for (const write of writes) {
210
+ for (const entry of write.existingLocalEntries ?? [])
211
+ printLine(terminal, `OpenCode: already registered from ${entry} in ${write.path}.`);
212
+ const entries = [
213
+ ...(write.existingLocalEntries ?? []),
214
+ ...(write.existingNpmEntries ?? []),
215
+ ];
216
+ if (entries.length > 1)
217
+ printLine(terminal, `Warning: ${plugin.displayName} may load twice in ${write.path}: ${entries.join(', ')}. Entries were left unchanged.`);
218
+ }
189
219
  if (options.dryRun) {
190
220
  printLine(terminal, 'Dry run: no registrations, enrollment, sign-in or migration will be performed.');
191
221
  for (const host of hosts) {
@@ -197,15 +227,16 @@ export async function runSetup(plugin, argv = [], io = {}) {
197
227
  }
198
228
  else
199
229
  printLine(terminal, `Would sign in locally for ${host}.`);
200
- if (plugin.beforeRegister)
230
+ if (!options.enrollOnly && plugin.beforeRegister)
201
231
  printLine(terminal, `Would run beforeRegister(${host}, ${mode}).`);
202
232
  }
203
233
  for (const write of writes)
204
234
  printLine(terminal, `${write.changed ? 'Would write' : 'Unchanged'} ${write.path}:\n${write.content}`);
205
- if (hosts.includes('pi'))
235
+ if (!options.enrollOnly && hosts.includes('pi'))
206
236
  printLine(terminal, `Would run ${detection.pi.executable} install npm:${plugin.packages.pi}@${plugin.version}`);
207
- for (const host of hosts)
208
- printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
237
+ if (!options.enrollOnly)
238
+ for (const host of hosts)
239
+ printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
209
240
  }
210
241
  else {
211
242
  const context = {
@@ -237,6 +268,8 @@ export async function runSetup(plugin, argv = [], io = {}) {
237
268
  else
238
269
  await plugin.signInLocal(host, context);
239
270
  await stopped();
271
+ if (options.enrollOnly)
272
+ continue;
240
273
  await plugin.beforeRegister?.(host, mode, context);
241
274
  await stopped();
242
275
  if (host === 'opencode')
@@ -265,7 +298,12 @@ export async function runSetup(plugin, argv = [], io = {}) {
265
298
  throw error;
266
299
  }
267
300
  }
268
- printLine(terminal, `${options.dryRun ? 'Planned' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
269
- printLine(terminal, `Next: ${hosts.includes('opencode') ? 'start OpenCode' : 'start Pi'} and run ${plugin.slashCommand}.`);
301
+ printLine(terminal, `${options.dryRun ? 'Planned' : options.enrollOnly ? 'Enrolled' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
302
+ if (options.enrollOnly) {
303
+ printLine(terminal, `Enroll-only: no host config or plugin registration ${options.dryRun ? 'will be' : 'was'} written.`);
304
+ printLine(terminal, 'Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.');
305
+ }
306
+ else
307
+ printLine(terminal, `Next: ${hosts.includes('opencode') ? 'start OpenCode' : 'start Pi'} and run ${plugin.slashCommand}.`);
270
308
  return { hosts, dryRun: options.dryRun, mode, detection };
271
309
  }
@@ -1,7 +1,7 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
2
  import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
3
3
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
4
- export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.";
4
+ export declare const UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read \"Upgrading from v0.1.3\" in its release notes first), or run setup without --claustrum to use local accounts.";
5
5
  /**
6
6
  * The longest setup waits, in total, for the vault to create the enrollment
7
7
  * request and for an operator to approve it. It matches the wait setup always
@@ -5,7 +5,7 @@ import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrol
5
5
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
6
  const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
7
7
  /** Fixed text: no version, host or account detail, so it is safe to print anywhere. */
8
- export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.';
8
+ export const UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
9
9
  /**
10
10
  * The longest setup waits, in total, for the vault to create the enrollment
11
11
  * request and for an operator to approve it. It matches the wait setup always
@@ -3,6 +3,8 @@ export interface PlannedWrite {
3
3
  path: string;
4
4
  content: string;
5
5
  changed: boolean;
6
+ existingLocalEntries?: string[];
7
+ existingNpmEntries?: string[];
6
8
  }
7
9
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
8
10
  export declare function updatePluginConfig(text: string, key: 'plugin' | 'plugins', pkg: string, version: string): string;
@@ -1,10 +1,11 @@
1
+ import { domainToUnicode } from 'node:url';
1
2
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
2
3
  import { SetupCommandError } from './command-error.js';
3
4
  import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
4
5
  import { writeHostConfigAtomic } from './config-write.js';
5
6
  import { defaultSetupFileSystem } from './detect.js';
6
7
  import { setupPaths } from './paths.js';
7
- function packageOf(value) {
8
+ function specifierOf(value) {
8
9
  const entry = typeof value === 'string'
9
10
  ? value
10
11
  : Array.isArray(value)
@@ -12,11 +13,72 @@ function packageOf(value) {
12
13
  : value && typeof value === 'object' && 'package' in value
13
14
  ? value.package
14
15
  : null;
15
- if (typeof entry !== 'string')
16
+ return typeof entry === 'string' ? entry : null;
17
+ }
18
+ function packageOf(value) {
19
+ const entry = specifierOf(value);
20
+ if (entry === null)
16
21
  return null;
17
22
  const at = entry.indexOf('@', entry.startsWith('@') ? 1 : 0);
18
23
  return at < 0 ? entry : entry.slice(0, at);
19
24
  }
25
+ function localFileURL(entry, windows) {
26
+ const url = new URL(entry);
27
+ if (/%2f/i.test(url.pathname) || (windows && /%5c/i.test(url.pathname)))
28
+ throw new Error('Encoded path separators are not valid in a file URL.');
29
+ const decoded = decodeURIComponent(url.pathname);
30
+ if (!windows) {
31
+ if (url.hostname)
32
+ throw new Error('A POSIX file URL must be local.');
33
+ return decoded;
34
+ }
35
+ const pathname = decoded.replaceAll('/', '\\');
36
+ if (url.hostname)
37
+ return `\\\\${domainToUnicode(url.hostname)}${pathname}`;
38
+ if (!/^\\[a-z]:/i.test(pathname))
39
+ throw new Error('A Windows file URL must have an absolute drive path.');
40
+ return pathname.slice(1);
41
+ }
42
+ function localPackageOf(entry, configFile, io) {
43
+ const { path, platform } = setupPaths(io);
44
+ try {
45
+ // Relative paths use the declaring config's directory, not setup's working directory:
46
+ // https://github.com/anomalyco/opencode/blob/b6478dce/packages/opencode/src/config/plugin.ts#L40-L60
47
+ // https://github.com/anomalyco/opencode/blob/v2.0.22/packages/core/src/config/plugin/source.ts#L139-L145
48
+ // Decode file URLs explicitly: Bun 1.3 ignores fileURLToPath's Windows override.
49
+ // The requested platform, not the OS running setup's tests, determines path rules.
50
+ const directory = /^file:\/\//i.test(entry)
51
+ ? localFileURL(entry, platform === 'win32')
52
+ : path.isAbsolute(entry) || entry.startsWith('.')
53
+ ? path.resolve(path.dirname(configFile), entry)
54
+ : null;
55
+ if (directory === null)
56
+ return null;
57
+ const manifest = JSON.parse((io.fs ?? defaultSetupFileSystem).readText(path.join(directory, 'package.json')));
58
+ return manifest &&
59
+ typeof manifest === 'object' &&
60
+ 'name' in manifest &&
61
+ typeof manifest.name === 'string'
62
+ ? manifest.name
63
+ : null;
64
+ }
65
+ catch {
66
+ // A missing, unreadable or invalid local package is not a registration of this plugin.
67
+ return null;
68
+ }
69
+ }
70
+ function pluginConfig(text, key) {
71
+ const errors = [];
72
+ const value = parse(text, errors, { allowTrailingComma: true });
73
+ if (errors.length ||
74
+ !value ||
75
+ typeof value !== 'object' ||
76
+ Array.isArray(value))
77
+ throw new Error('Invalid OpenCode config; refusing to overwrite it.');
78
+ if (value[key] !== undefined && !Array.isArray(value[key]))
79
+ throw new Error(`OpenCode ${key} must be an array.`);
80
+ return value;
81
+ }
20
82
  function removeArrayEntry(text, key, index) {
21
83
  const tree = parseTree(text);
22
84
  const array = tree && findNodeAtLocation(tree, [key]);
@@ -48,13 +110,7 @@ function removeArrayEntry(text, key, index) {
48
110
  }
49
111
  /** Edit only array entries so unrelated JSONC text, including comments, survives. */
50
112
  export function updatePluginConfig(text, key, pkg, version) {
51
- const errors = [];
52
- const value = parse(text, errors, { allowTrailingComma: true });
53
- if (errors.length ||
54
- !value ||
55
- typeof value !== 'object' ||
56
- Array.isArray(value))
57
- throw new Error('Invalid OpenCode config; refusing to overwrite it.');
113
+ const value = pluginConfig(text, key);
58
114
  const options = {
59
115
  formattingOptions: {
60
116
  insertSpaces: !/^\t+/m.test(text),
@@ -64,8 +120,6 @@ export function updatePluginConfig(text, key, pkg, version) {
64
120
  };
65
121
  let output = text;
66
122
  const array = value[key];
67
- if (array !== undefined && !Array.isArray(array))
68
- throw new Error(`OpenCode ${key} must be an array.`);
69
123
  const entries = Array.isArray(array) ? [...array] : [];
70
124
  const matches = entries.flatMap((entry, index) => packageOf(entry) === pkg ? [index] : []);
71
125
  const entry = `${pkg}@${version}`;
@@ -109,6 +163,31 @@ export function planOpenCodeRegistration(plugin, generation, io = {}) {
109
163
  const before = exists
110
164
  ? fs.readText(file)
111
165
  : `${JSON.stringify({ $schema: `https://opencode.ai/${name === 'tui' ? 'tui' : 'config'}.json` }, null, 2)}\n`;
166
+ const config = pluginConfig(before, key);
167
+ const existingLocalEntries = [];
168
+ const existingNpmEntries = [];
169
+ for (const field of ['plugin', 'plugins']) {
170
+ if (!Array.isArray(config[field]))
171
+ continue;
172
+ for (const entry of config[field]) {
173
+ const spec = specifierOf(entry);
174
+ if (spec === null)
175
+ continue;
176
+ if (localPackageOf(spec, file, io) === plugin.packages.opencode)
177
+ existingLocalEntries.push(JSON.stringify(entry));
178
+ else if (packageOf(entry) === plugin.packages.opencode)
179
+ existingNpmEntries.push(JSON.stringify(entry));
180
+ }
181
+ }
182
+ // A local build is deliberate: do not replace it, deduplicate it or migrate its key.
183
+ if (existingLocalEntries.length > 0)
184
+ return {
185
+ path: file,
186
+ content: before,
187
+ changed: false,
188
+ existingLocalEntries,
189
+ existingNpmEntries,
190
+ };
112
191
  const content = updatePluginConfig(before, key, plugin.packages.opencode, plugin.version);
113
192
  return { path: file, content, changed: !exists || content !== before };
114
193
  });