@cortexkit/opencode-openai-auth 1.14.1 → 1.15.1

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 (87) hide show
  1. package/dist/bin.js +9 -9
  2. package/dist/{codex-request-Cl6zEfsR.d.ts → codex-request-DYqSE0ti.d.ts} +373 -2
  3. package/dist/{index-wma2ggn9.js → index-14x5shtc.js} +2 -2
  4. package/dist/{index-gkye2xh1.js → index-1scvhkyy.js} +2 -2
  5. package/dist/index-1wcg7g9d.js +2 -0
  6. package/dist/index-50p400eg.js +8 -0
  7. package/dist/{index-k5av4j8p.js → index-dzpjz8hv.js} +2 -2
  8. package/dist/{index-cxnrd85v.js → index-f7kmsdfk.js} +1 -1
  9. package/dist/index-fkgd5yv6.js +76 -0
  10. package/dist/{index-z9cj13z7.js → index-hnfqppx9.js} +1 -1
  11. package/dist/index-j2qfnmth.js +64 -0
  12. package/dist/{index-2f330s35.js → index-m8m7rakq.js} +2 -2
  13. package/dist/{index-94b345dw.js → index-t65axpta.js} +1 -1
  14. package/dist/{index-yygzbxjk.js → index-tes6vn59.js} +1 -1
  15. package/dist/index-xjtbg7sx.js +101 -0
  16. package/dist/index.d.ts +1 -372
  17. package/dist/index.js +1 -1
  18. package/dist/openai-auth.schema.json +400 -0
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.js +1 -1
  21. package/dist/rpc/rpc-client.js +1 -1
  22. package/dist/rpc/rpc-dir.js +1 -1
  23. package/dist/sidebar-state.js +1 -1
  24. package/dist/{token-sgwxn4xg.js → token-j34j1zhm.js} +1 -1
  25. package/dist/token-util-bf619nmg.js +1 -0
  26. package/dist/tui-preferences.js +3 -3
  27. package/dist/v2/server.d.ts +1 -1
  28. package/dist/v2/server.js +2 -2
  29. package/package.json +3 -3
  30. package/src/tui-compiled/raw/logger.js +8 -1
  31. package/src/tui-compiled/raw/shared/061e741c052de9c1-paths.js +48 -0
  32. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +41 -18
  33. package/src/tui-compiled/raw/shared/23300c068d0b2ffc-parse.js +65 -0
  34. package/src/tui-compiled/raw/shared/3000be4f79f20eb6-write.js +88 -0
  35. package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +229 -0
  36. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
  37. package/src/tui-compiled/raw/shared/5803fadb30af0ec0-descriptors.js +81 -0
  38. package/src/tui-compiled/raw/shared/58bc35a3cd459085-define.js +52 -0
  39. package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +139 -0
  40. package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +19 -0
  41. package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +28 -12
  42. package/src/tui-compiled/raw/shared/81758f9fe7c2a576-handle.js +228 -0
  43. package/src/tui-compiled/raw/shared/87f6e22d4fc34918-resolve.js +51 -0
  44. package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +1 -0
  45. package/src/tui-compiled/raw/shared/8ab1f5794e677151-move.js +351 -0
  46. package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +9 -5
  47. package/src/tui-compiled/raw/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  48. package/src/tui-compiled/raw/shared/cc0f2d1963547799-index.js +7 -0
  49. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +48 -5
  50. package/src/tui-compiled/raw/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  51. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  52. package/src/tui-compiled/raw/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  53. package/src/tui-compiled/raw/shared/facfd8afc431d68a-refusal.js +15 -0
  54. package/src/tui-compiled/raw/shared/fc7db0c5aa764565-settings-install.js +85 -0
  55. package/src/tui-compiled/raw/shared/fcd26e77bc538838-snapshot.js +150 -0
  56. package/src/tui-compiled/runtime/logger.js +8 -1
  57. package/src/tui-compiled/runtime/shared/061e741c052de9c1-paths.js +48 -0
  58. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +41 -18
  59. package/src/tui-compiled/runtime/shared/23300c068d0b2ffc-parse.js +65 -0
  60. package/src/tui-compiled/runtime/shared/3000be4f79f20eb6-write.js +88 -0
  61. package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +229 -0
  62. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
  63. package/src/tui-compiled/runtime/shared/5803fadb30af0ec0-descriptors.js +81 -0
  64. package/src/tui-compiled/runtime/shared/58bc35a3cd459085-define.js +52 -0
  65. package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +139 -0
  66. package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +19 -0
  67. package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +28 -12
  68. package/src/tui-compiled/runtime/shared/81758f9fe7c2a576-handle.js +228 -0
  69. package/src/tui-compiled/runtime/shared/87f6e22d4fc34918-resolve.js +51 -0
  70. package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +1 -0
  71. package/src/tui-compiled/runtime/shared/8ab1f5794e677151-move.js +351 -0
  72. package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +9 -5
  73. package/src/tui-compiled/runtime/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
  74. package/src/tui-compiled/runtime/shared/cc0f2d1963547799-index.js +7 -0
  75. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +48 -5
  76. package/src/tui-compiled/runtime/shared/e0ed4a490e4eaa4f-schema.js +81 -0
  77. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
  78. package/src/tui-compiled/runtime/shared/eac0bed49f3d4110-lock-errors.js +15 -0
  79. package/src/tui-compiled/runtime/shared/facfd8afc431d68a-refusal.js +15 -0
  80. package/src/tui-compiled/runtime/shared/fc7db0c5aa764565-settings-install.js +85 -0
  81. package/src/tui-compiled/runtime/shared/fcd26e77bc538838-snapshot.js +150 -0
  82. package/dist/index-3mbw88h7.js +0 -91
  83. package/dist/index-999nwa9p.js +0 -76
  84. package/dist/index-pc4vrrex.js +0 -2
  85. package/dist/index-snq7bwr6.js +0 -8
  86. package/dist/index-xk7f1aef.js +0 -64
  87. package/dist/token-util-8mrnmkge.js +0 -1
@@ -0,0 +1,351 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { ensurePrivateDirectory, PrivateFileError, } from "./375d9cca2def037d-private-files.js";
5
+ import { LockContentionError, LockOwnershipError, lockPathFor, withLock, } from "./4825e03209d6ae3e-with-lock.js";
6
+ import { LockStack, POOL_LOCK_DEFAULTS, } from "./43fc9e6b994519c7-refresh-lock.js";
7
+ import { validateValue } from "./5803fadb30af0ec0-descriptors.js";
8
+ import { SettingsFs } from "./6948d70969aa7a55-fs.js";
9
+ import { rethrowSettingsLockError } from "./eac0bed49f3d4110-lock-errors.js";
10
+ import { SettingsRefusal } from "./facfd8afc431d68a-refusal.js";
11
+ let stepHook;
12
+ /** Internal test hook, not part of the settings subpath's public exports. */
13
+ export function setSettingsMoveStepHookForTest(hook) {
14
+ stepHook = hook;
15
+ }
16
+ function emptyResult(outcome) {
17
+ return {
18
+ outcome,
19
+ unmapped: [],
20
+ differing: [],
21
+ noteFailures: [],
22
+ postPublishFailures: [],
23
+ };
24
+ }
25
+ function hasCode(error, code) {
26
+ return (error !== null &&
27
+ typeof error === 'object' &&
28
+ 'code' in error &&
29
+ error.code === code);
30
+ }
31
+ async function exists(path) {
32
+ try {
33
+ await SettingsFs.lstat(path);
34
+ return true;
35
+ }
36
+ catch (error) {
37
+ if (hasCode(error, 'ENOENT'))
38
+ return false;
39
+ throw error;
40
+ }
41
+ }
42
+ function log(options, level, message, data) {
43
+ try {
44
+ options.log[level](message, data);
45
+ }
46
+ catch {
47
+ // Diagnostics must not turn a completed publication into a failure.
48
+ }
49
+ }
50
+ function lockFailure(error, path, name) {
51
+ let original = error;
52
+ const seen = new Set();
53
+ while (original !== null &&
54
+ typeof original === 'object' &&
55
+ !seen.has(original)) {
56
+ seen.add(original);
57
+ if (original instanceof LockContentionError ||
58
+ original instanceof LockOwnershipError ||
59
+ original instanceof PrivateFileError) {
60
+ break;
61
+ }
62
+ if (!('cause' in original))
63
+ break;
64
+ original = original.cause;
65
+ }
66
+ try {
67
+ rethrowSettingsLockError(original, path, name);
68
+ }
69
+ catch (mapped) {
70
+ return {
71
+ ...emptyResult(mapped instanceof SettingsRefusal && mapped.code === 'settings-busy'
72
+ ? 'busy'
73
+ : 'failed'),
74
+ cause: error,
75
+ };
76
+ }
77
+ }
78
+ function merge(options, legacy, mapped, result) {
79
+ result.unmapped = [...mapped.unmapped];
80
+ const bySetting = new Map();
81
+ for (const entry of mapped.entries) {
82
+ const source = legacy[entry.source];
83
+ if (!Number.isInteger(entry.source) || !source?.present) {
84
+ throw new TypeError(`Move entry has no present source: ${entry.source}`);
85
+ }
86
+ const declaration = Object.hasOwn(options.definition.settings, entry.setting)
87
+ ? options.definition.settings[entry.setting]
88
+ : undefined;
89
+ const reason = !declaration
90
+ ? 'unknown-setting'
91
+ : !validateValue(declaration.value, entry.value)
92
+ ? 'invalid-value'
93
+ : undefined;
94
+ if (reason) {
95
+ result.unmapped.push({ source: entry.source, key: entry.setting, reason });
96
+ continue;
97
+ }
98
+ const entries = bySetting.get(entry.setting) ?? [];
99
+ entries.push({ ...entry, host: source.host });
100
+ bySetting.set(entry.setting, entries);
101
+ }
102
+ const document = { schema_version: 1 };
103
+ for (const [setting, declaration] of Object.entries(options.definition.settings)) {
104
+ const entries = bySetting.get(setting)?.sort((a, b) => a.source - b.source);
105
+ const primary = entries?.[0];
106
+ if (!entries || !primary)
107
+ continue;
108
+ const hosts = new Map();
109
+ if (declaration.overrides?.host) {
110
+ for (const host of ['opencode', 'pi']) {
111
+ const first = entries.find((entry) => entry.host === host);
112
+ if (first && !isDeepStrictEqual(first.value, primary.value)) {
113
+ hosts.set(host, first.value);
114
+ }
115
+ }
116
+ }
117
+ Object.defineProperty(document, setting, {
118
+ value: hosts.size
119
+ ? { default: primary.value, ...Object.fromEntries(hosts) }
120
+ : primary.value,
121
+ enumerable: true,
122
+ });
123
+ const values = entries.map((entry) => ({
124
+ source: entry.source,
125
+ host: entry.host,
126
+ value: entry.value,
127
+ }));
128
+ if (values.some(({ host, value }) => !isDeepStrictEqual(hosts.has(host) ? hosts.get(host) : primary.value, value))) {
129
+ result.differing.push({ setting, values });
130
+ log(options, 'info', `Differing legacy settings: ${setting}`, { values });
131
+ }
132
+ }
133
+ return document;
134
+ }
135
+ async function removeStaleTemps(target) {
136
+ const prefix = `${basename(target)}.move-`;
137
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/i;
138
+ for (const name of await SettingsFs.readdir(dirname(target))) {
139
+ if (name.startsWith(prefix) && uuid.test(name.slice(prefix.length))) {
140
+ await SettingsFs.unlink(join(dirname(target), name));
141
+ }
142
+ }
143
+ }
144
+ async function writeNotes(options, legacy, result) {
145
+ for (const source of legacy) {
146
+ if (!source.present)
147
+ continue;
148
+ const path = `${source.path}.MOVED_READPLEASE`;
149
+ try {
150
+ let file;
151
+ try {
152
+ file = await SettingsFs.open(path, 'wx');
153
+ }
154
+ catch (error) {
155
+ if (hasCode(error, 'EEXIST'))
156
+ continue;
157
+ throw error;
158
+ }
159
+ try {
160
+ await file.writeFile(`Settings moved to ${options.target}.\nA rollback loses changes made after the move.\n`, 'utf8');
161
+ }
162
+ finally {
163
+ await file.close();
164
+ }
165
+ }
166
+ catch (error) {
167
+ result.noteFailures.push({ path, error });
168
+ log(options, 'warn', 'Could not write settings move note', {
169
+ path,
170
+ error,
171
+ });
172
+ }
173
+ }
174
+ }
175
+ async function publish(options, legacy, document, moveLock, stack, result) {
176
+ const { target } = options;
177
+ const temp = `${target}.move-${randomUUID()}.tmp`;
178
+ let staged = false;
179
+ try {
180
+ const file = await SettingsFs.open(temp, 'wx', 0o644);
181
+ staged = true;
182
+ try {
183
+ const header = [
184
+ `// Settings moved on ${new Date().toISOString().slice(0, 10)} (UTC) from:`,
185
+ ...options.sources.map((source) => `// ${JSON.stringify(source.path)}`),
186
+ ].join('\n');
187
+ await file.writeFile(`${header}\n${JSON.stringify(document, null, 2)}\n`, 'utf8');
188
+ await file.sync();
189
+ }
190
+ finally {
191
+ await file.close();
192
+ }
193
+ await stepHook?.('staged', { target, temp });
194
+ await stepHook?.('before-publish', { target, temp });
195
+ await moveLock.assertOwned();
196
+ await stack.assertAll();
197
+ try {
198
+ await SettingsFs.link(temp, target);
199
+ }
200
+ catch (error) {
201
+ if (!hasCode(error, 'EEXIST'))
202
+ throw error;
203
+ result.outcome = 'aborted-target-appeared';
204
+ return result;
205
+ }
206
+ result.outcome = 'moved';
207
+ try {
208
+ await SettingsFs.unlink(temp);
209
+ staged = false;
210
+ }
211
+ catch (error) {
212
+ result.postPublishFailures.push({ step: 'temp-unlink', error });
213
+ log(options, 'warn', 'Settings move temp cleanup failed', { temp, error });
214
+ }
215
+ if (process.platform !== 'win32') {
216
+ try {
217
+ const folder = await SettingsFs.open(dirname(target), 'r');
218
+ try {
219
+ await folder.sync();
220
+ }
221
+ finally {
222
+ await folder.close();
223
+ }
224
+ }
225
+ catch (error) {
226
+ result.postPublishFailures.push({ step: 'directory-sync', error });
227
+ log(options, 'warn', 'Settings move directory sync failed', {
228
+ target,
229
+ error,
230
+ });
231
+ }
232
+ }
233
+ await writeNotes(options, legacy, result);
234
+ return result;
235
+ }
236
+ finally {
237
+ if (staged && result.outcome !== 'moved') {
238
+ await SettingsFs.unlink(temp).catch(() => { });
239
+ }
240
+ }
241
+ }
242
+ /** Move legacy settings without replacing an existing target or changing a source. */
243
+ export async function moveSettingsOnce(options) {
244
+ try {
245
+ if (options.separateInstall)
246
+ return emptyResult('separate-install');
247
+ if (await exists(options.target))
248
+ return emptyResult('done-already');
249
+ if (!(await options.fence()))
250
+ return emptyResult('fence-closed');
251
+ const folder = dirname(options.target);
252
+ if (process.platform === 'win32')
253
+ await ensurePrivateDirectory(folder);
254
+ else
255
+ await SettingsFs.mkdir(folder, { recursive: true, mode: 0o700 });
256
+ let settled;
257
+ try {
258
+ return await withLock(options.target, { name: 'settings-move', ...POOL_LOCK_DEFAULTS }, async (moveLock) => {
259
+ const stack = new LockStack(POOL_LOCK_DEFAULTS, {});
260
+ try {
261
+ const skipped = new Set();
262
+ const seen = new Map();
263
+ for (const source of options.sources) {
264
+ for (const spec of source.locks) {
265
+ const path = resolve(spec.path);
266
+ const names = seen.get(path) ?? new Set();
267
+ if (names.has(spec.name))
268
+ continue;
269
+ names.add(spec.name);
270
+ seen.set(path, names);
271
+ const lockFolder = dirname(lockPathFor(spec.path, spec.name));
272
+ if (!(await exists(lockFolder))) {
273
+ skipped.add(lockFolder);
274
+ continue;
275
+ }
276
+ try {
277
+ await stack.acquire(spec);
278
+ }
279
+ catch (error) {
280
+ settled = lockFailure(error, spec.path, spec.name);
281
+ return settled;
282
+ }
283
+ }
284
+ }
285
+ if (await exists(options.target)) {
286
+ settled = emptyResult('done-already');
287
+ }
288
+ else if (!(await options.fence())) {
289
+ settled = emptyResult('fence-closed');
290
+ }
291
+ else {
292
+ await removeStaleTemps(options.target);
293
+ await stepHook?.('locked', { target: options.target });
294
+ const legacy = [];
295
+ for (const source of options.sources) {
296
+ let text;
297
+ try {
298
+ text = await SettingsFs.readFile(source.path, 'utf8');
299
+ }
300
+ catch (error) {
301
+ if (!hasCode(error, 'ENOENT'))
302
+ throw error;
303
+ legacy.push({
304
+ host: source.host,
305
+ path: source.path,
306
+ present: false,
307
+ });
308
+ continue;
309
+ }
310
+ legacy.push({
311
+ host: source.host,
312
+ path: source.path,
313
+ present: true,
314
+ value: source.read(text),
315
+ });
316
+ }
317
+ const mapped = await options.map(legacy);
318
+ for (const path of skipped) {
319
+ if (await exists(path)) {
320
+ settled = emptyResult('busy');
321
+ return settled;
322
+ }
323
+ }
324
+ const result = emptyResult('failed');
325
+ const document = merge(options, legacy, mapped, result);
326
+ settled = await publish(options, legacy, document, moveLock, stack, result);
327
+ }
328
+ }
329
+ catch (cause) {
330
+ settled = { ...emptyResult('failed'), cause };
331
+ }
332
+ finally {
333
+ await stack.releaseAll();
334
+ }
335
+ return settled;
336
+ });
337
+ }
338
+ catch (error) {
339
+ if (!settled)
340
+ return lockFailure(error, options.target, 'settings-move');
341
+ if (settled.outcome === 'moved') {
342
+ settled.postPublishFailures.push({ step: 'lock-release', error });
343
+ }
344
+ log(options, 'warn', 'Settings move lock release failed', { error });
345
+ return settled;
346
+ }
347
+ }
348
+ catch (cause) {
349
+ return { ...emptyResult('failed'), cause };
350
+ }
351
+ }
@@ -1,10 +1,10 @@
1
1
  import { lstat, stat } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
- async function identity(path, followSymlinks) {
3
+ async function identity(path, probe) {
4
4
  try {
5
5
  // Match the reader: private readers reject links, while readFile follows
6
6
  // them and needs the target's identity, not the link's identity.
7
- const metadata = await (followSymlinks ? stat(path) : lstat(path));
7
+ const metadata = await probe(path);
8
8
  return metadata.isFile() ? metadata : undefined;
9
9
  }
10
10
  catch (error) {
@@ -24,15 +24,19 @@ function sameIdentity(left, right) {
24
24
  }
25
25
  /** Process-local reads, capped at 64 path sets with one value per resolved set. */
26
26
  export class FileReadCache {
27
- #followSymlinks;
27
+ #probe;
28
28
  #entries = new Map();
29
29
  constructor(options = {}) {
30
- this.#followSymlinks = options.followSymlinks ?? false;
30
+ // Look the probe up on every call, not once here: tests replace the
31
+ // node:fs/promises functions (and SettingsFs methods) after caches exist.
32
+ this.#probe = options.followSymlinks
33
+ ? (path) => (options.stat ?? stat)(path)
34
+ : (path) => (options.lstat ?? lstat)(path);
31
35
  }
32
36
  async read(paths, read, validateHit) {
33
37
  const resolvedPaths = paths.map((path) => resolve(path));
34
38
  const key = JSON.stringify(resolvedPaths);
35
- const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
39
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#probe)));
36
40
  const identities = probed.every((entry) => entry !== undefined)
37
41
  ? probed
38
42
  : undefined;
@@ -0,0 +1,13 @@
1
+ import { settingsIdentity } from "./fc7db0c5aa764565-settings-install.js";
2
+ const decisionsKey = Symbol.for("@cortexkit/openai-auth/settings-decisions"), processState = globalThis, decisions = processState[decisionsKey] ?? new Map;
3
+ processState[decisionsKey] = decisions;
4
+ export function getSettingsDecision(configPath) {
5
+ return decisions.get(settingsIdentity(configPath));
6
+ }
7
+ export function recordSettingsDecision(configPath, decision) {
8
+ const identity = settingsIdentity(configPath), existing = decisions.get(identity);
9
+ if (existing !== void 0)
10
+ return existing;
11
+ decisions.set(identity, decision);
12
+ return decision;
13
+ }
@@ -0,0 +1,7 @@
1
+ export { defineSettings, } from "./58bc35a3cd459085-define.js";
2
+ export { boolean, integer, list, number, object, oneOf, record, string, } from "./5803fadb30af0ec0-descriptors.js";
3
+ export { openSettings, } from "./81758f9fe7c2a576-handle.js";
4
+ export { moveSettingsOnce, } from "./8ab1f5794e677151-move.js";
5
+ export { cortexkitConfigDir, isAbsoluteForPlatform, settingsFilePath, } from "./061e741c052de9c1-paths.js";
6
+ export { SETTINGS_REFUSAL_CODES, SettingsRefusal, } from "./facfd8afc431d68a-refusal.js";
7
+ export { settingsJsonSchema } from "./e0ed4a490e4eaa4f-schema.js";
@@ -21,6 +21,7 @@ import {
21
21
  } from "./b85c5301fddcb98a-paths.js";
22
22
  import { PRIMARY, SECONDARY } from "./85512cc5263ba259-provider.js";
23
23
  import { quotaWindowResetIsPast } from "./2dce6e9613993329-quota-manager.js";
24
+ import { getSettingsDecision } from "./9865a4fa45882c6f-settings-decisions.js";
24
25
  import {
25
26
  assertNotTombstoneRefresh,
26
27
  HOST_SLOT_TOMBSTONE_REFRESH,
@@ -517,6 +518,48 @@ function configFromStorage(storage) {
517
518
  accounts: storage.accounts.map(accountConfig)
518
519
  });
519
520
  }
521
+ function keepSharedConfigPreferences(config, raw, storage, configPath) {
522
+ if (getSettingsDecision(configPath) !== "shared")
523
+ return config;
524
+ const next = { ...config };
525
+ for (const key of [
526
+ "routing",
527
+ "fallbackOn",
528
+ "refresh",
529
+ "quota",
530
+ "dump",
531
+ "costZeroing",
532
+ "killswitch",
533
+ "logging",
534
+ "cachekeep",
535
+ "cacheKeep",
536
+ "dumpDir",
537
+ "dumpMaxBytes",
538
+ "webSockets",
539
+ "rawWebSocket",
540
+ "responsesLite",
541
+ "codexApiEndpoint"
542
+ ]) {
543
+ delete next[key];
544
+ if (Object.hasOwn(raw, key))
545
+ next[key] = raw[key];
546
+ }
547
+ const refresh = isRecord(raw.refresh) ? { ...raw.refresh } : {};
548
+ for (const key of [
549
+ "mainLastRefreshError",
550
+ "mainRefreshLeaseId",
551
+ "mainRefreshLeaseUntil",
552
+ "mainRefreshLeaseTokenHash"
553
+ ]) {
554
+ delete refresh[key];
555
+ const value = storage.refresh?.[key];
556
+ if (value !== void 0)
557
+ refresh[key] = value;
558
+ }
559
+ if (isRecord(raw.refresh) || Object.keys(refresh).length > 0)
560
+ next.refresh = refresh;
561
+ return next;
562
+ }
520
563
  const CREDENTIAL_FIELDS = [
521
564
  "access",
522
565
  "refresh",
@@ -553,7 +596,7 @@ function mergeStorageForSave(latest, incoming) {
553
596
  accounts: [...accounts.values()]
554
597
  };
555
598
  }
556
- async function acquireSaveAccountsLock(path, renew = !1) {
599
+ export async function acquireSaveAccountsLock(path, renew = !1) {
557
600
  const startedAt = Date.now(), deadline = startedAt + SAVE_ACCOUNTS_LOCK_WAIT_MS;
558
601
  let attempts = 0;
559
602
  while (Date.now() <= deadline) {
@@ -615,7 +658,7 @@ export async function saveAccounts(storage, paths, canWrite = void 0) {
615
658
  };
616
659
  if (canWrite && !canWrite())
617
660
  return;
618
- await writeJsonAtomic(path, nextConfig);
661
+ await writeJsonAtomic(path, keepSharedConfigPreferences(nextConfig, existing, merged, path));
619
662
  if (canWrite && !canWrite())
620
663
  return;
621
664
  await writeJsonAtomic(statePath, stateFromStorage(merged));
@@ -685,7 +728,7 @@ export async function mutateAccounts(mutate, paths, options = {}) {
685
728
  try {
686
729
  const stateLock = await acquireSaveAccountsLock(statePath);
687
730
  try {
688
- const configJson = await readJsonIfPresent(path), stateJson = await readJsonIfPresent(statePath), current = (configJson.exists ? normalizeStorage(mergeConfigAndState(configJson.value, stateJson.value)) : null) ?? emptyAccountStorage(), currentAccountIds = new Set(current.accounts.map((a) => a.id)), rawRosterIds = collectConfigRosterIds(configJson.value) ?? new Set, next = mutate(current, {
731
+ const configJson = await readJsonIfPresent(path), stateJson = await readJsonIfPresent(statePath), existing = isRecord(configJson.value) ? structuredClone(configJson.value) : {}, current = (configJson.exists ? normalizeStorage(mergeConfigAndState(configJson.value, stateJson.value)) : null) ?? emptyAccountStorage(), currentAccountIds = new Set(current.accounts.map((a) => a.id)), rawRosterIds = collectConfigRosterIds(configJson.value) ?? new Set, next = mutate(current, {
689
732
  rawRosterIds: [...rawRosterIds],
690
733
  loadedRosterIds: [...currentAccountIds]
691
734
  }) ?? current, allowDrop = new Set(options.allowDrop ?? []), preserved = buildPreservedAdditions(configJson.value, currentAccountIds, allowDrop), baseConfig = configFromStorage(next), writtenIds = new Set((Array.isArray(baseConfig.accounts) ? baseConfig.accounts : []).map((e) => isRecord(e) && typeof e.id === "string" ? e.id.trim() : "").filter(Boolean)), additions = preserved.filter((raw) => {
@@ -694,7 +737,7 @@ export async function mutateAccounts(mutate, paths, options = {}) {
694
737
  if (typeof raw.id !== "string")
695
738
  return !1;
696
739
  return !writtenIds.has(raw.id.trim());
697
- }), existing = isRecord(configJson.value) ? configJson.value : {}, nextConfig = {
740
+ }), nextConfig = {
698
741
  ...withoutRetiredSettings(existing),
699
742
  ...baseConfig,
700
743
  accounts: [
@@ -704,7 +747,7 @@ export async function mutateAccounts(mutate, paths, options = {}) {
704
747
  };
705
748
  if (options.canWrite && !options.canWrite())
706
749
  return current;
707
- await writeJsonAtomic(path, nextConfig);
750
+ await writeJsonAtomic(path, keepSharedConfigPreferences(nextConfig, existing, next, path));
708
751
  if (options.canWrite && !options.canWrite())
709
752
  return current;
710
753
  await writeJsonAtomic(statePath, stateFromStorage(next));
@@ -0,0 +1,81 @@
1
+ function descriptorSchema(descriptor, completeObjects = false) {
2
+ switch (descriptor.kind) {
3
+ case 'boolean':
4
+ case 'string':
5
+ return { type: descriptor.kind };
6
+ case 'integer':
7
+ case 'number':
8
+ return {
9
+ type: descriptor.kind,
10
+ ...(descriptor.min !== undefined ? { minimum: descriptor.min } : {}),
11
+ ...(descriptor.max !== undefined ? { maximum: descriptor.max } : {}),
12
+ };
13
+ case 'oneOf':
14
+ return { enum: [...descriptor.values] };
15
+ case 'list':
16
+ return { type: 'array', items: descriptorSchema(descriptor.item, true) };
17
+ case 'object':
18
+ return {
19
+ type: 'object',
20
+ properties: Object.fromEntries(Object.entries(descriptor.fields).map(([name, field]) => [
21
+ name,
22
+ descriptorSchema(field, completeObjects),
23
+ ])),
24
+ additionalProperties: false,
25
+ // Objects merge field by field, except in lists and records, which replace whole values.
26
+ ...(completeObjects
27
+ ? { required: Object.keys(descriptor.fields) }
28
+ : {}),
29
+ };
30
+ case 'record':
31
+ return {
32
+ type: 'object',
33
+ additionalProperties: descriptorSchema(descriptor.value, true),
34
+ };
35
+ }
36
+ }
37
+ function settingSchema(declaration) {
38
+ const value = descriptorSchema(declaration.value);
39
+ if (declaration.overrides === undefined)
40
+ return value;
41
+ const { host, model } = declaration.overrides;
42
+ const properties = { default: value };
43
+ if (host) {
44
+ properties.opencode = value;
45
+ properties.pi = value;
46
+ }
47
+ return {
48
+ anyOf: [
49
+ value,
50
+ {
51
+ type: 'object',
52
+ properties,
53
+ additionalProperties: model ? value : false,
54
+ ...(model && !host
55
+ ? { propertyNames: { not: { enum: ['opencode', 'pi'] } } }
56
+ : {}),
57
+ },
58
+ ],
59
+ };
60
+ }
61
+ /**
62
+ * Generate the plugin's JSON Schema deterministically from its settings definition.
63
+ * Plugins ship the generated schema and check their parsed shipped file with:
64
+ * `expect(shippedSchema).toEqual(settingsJsonSchema(definition))`.
65
+ */
66
+ export function settingsJsonSchema(definition) {
67
+ const properties = {
68
+ schema_version: { type: 'integer', minimum: 1 },
69
+ $schema: { type: 'string' },
70
+ ...Object.fromEntries(Object.entries(definition.settings).map(([name, declaration]) => [
71
+ name,
72
+ settingSchema(declaration),
73
+ ])),
74
+ };
75
+ return {
76
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
77
+ type: 'object',
78
+ properties,
79
+ additionalProperties: false,
80
+ };
81
+ }