@cortexkit/opencode-openai-auth 1.19.0 → 1.20.0

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 (42) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-Bj3F3fFg.d.ts → codex-request-Dvj28zFK.d.ts} +9 -2
  3. package/dist/{index-gqnca0gh.js → index-0jknjejt.js} +2 -2
  4. package/dist/index-2dxas810.js +64 -0
  5. package/dist/index-3898z307.js +101 -0
  6. package/dist/{index-hrv1msdb.js → index-62xhtkv8.js} +1 -1
  7. package/dist/{index-raj3tyyz.js → index-663p60em.js} +1 -1
  8. package/dist/{index-3b9e26wv.js → index-74mg470w.js} +2 -2
  9. package/dist/{index-v2wvavef.js → index-7tkppvqd.js} +2 -2
  10. package/dist/index-asjkhkty.js +2 -0
  11. package/dist/index-d5er9yht.js +75 -0
  12. package/dist/{index-12gxtre8.js → index-pdsqgqng.js} +1 -1
  13. package/dist/{index-h7xxfm12.js → index-r6k6hh93.js} +1 -1
  14. package/dist/{index-6tgra34y.js → index-wy84wezx.js} +2 -2
  15. package/dist/{index-cawk490s.js → index-xbh03w1v.js} +2 -2
  16. package/dist/{index-hnb97ydy.js → index-z1hz7e5y.js} +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +1 -1
  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-util-kwahm03g.js +1 -0
  25. package/dist/{token-kdjmv82a.js → token-y3kre94n.js} +1 -1
  26. package/dist/tui-preferences.js +1 -1
  27. package/dist/v2/server.d.ts +1 -1
  28. package/dist/v2/server.js +4 -4
  29. package/package.json +8 -8
  30. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +31 -14
  31. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +8 -3
  32. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +34 -13
  33. package/src/tui-compiled/raw/shared/a75d0d866c227b3f-index.tsx +129 -18
  34. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +31 -14
  35. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +8 -3
  36. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +34 -13
  37. package/src/tui-compiled/runtime/shared/a75d0d866c227b3f-index.js +324 -187
  38. package/dist/index-7ztbemxe.js +0 -64
  39. package/dist/index-a4cgsngv.js +0 -101
  40. package/dist/index-aew7mcfy.js +0 -2
  41. package/dist/index-r3vc66vz.js +0 -76
  42. package/dist/token-util-71r7z2vr.js +0 -1
@@ -145,22 +145,38 @@ function credentialTypeOf(row, family) {
145
145
  }
146
146
  return { kind: 'refused', code: 'unclassified' };
147
147
  }
148
- if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
148
+ const type = row.credentialType;
149
+ if (type === 'oauth') {
150
+ if (row.refreshAdapter !== family.refreshAdapter)
151
+ return notMine;
152
+ }
153
+ else if (type === 'api_key') {
154
+ if (!family.apiKeys || row.refreshAdapter !== undefined)
155
+ return notMine;
156
+ }
157
+ else {
149
158
  return notMine;
150
- if (row.credentialType === 'oauth')
151
- return row.refreshAdapter === family.refreshAdapter
152
- ? { kind: 'mine', type: 'oauth' }
153
- : notMine;
154
- if (row.credentialType === 'api_key' && family.apiKeys)
155
- return row.refreshAdapter === undefined
156
- ? { kind: 'mine', type: 'api_key' }
157
- : notMine;
158
- return notMine;
159
+ }
160
+ const { authMethod } = rowFactsOf(row, { includeProviderIds: false });
161
+ // Older vaults omit the method. If present, it must match the serving type.
162
+ if (authMethod !== undefined) {
163
+ const matchesType = type === 'oauth'
164
+ ? authMethod === 'chatgpt' ||
165
+ authMethod === 'antigravity' ||
166
+ authMethod === 'oauth'
167
+ : authMethod === 'apikey';
168
+ if (!matchesType)
169
+ return { kind: 'refused', code: 'unknown-auth-method' };
170
+ }
171
+ return { kind: 'mine', type };
159
172
  }
160
173
  /** Structural access keeps the public facts independent of client declarations. */
161
- function rowFactsOf(row) {
174
+ function rowFactsOf(row, { includeProviderIds = true } = {}) {
162
175
  const metadata = row;
163
- return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
176
+ return {
177
+ providerIds: includeProviderIds ? metadata.providerIds : undefined,
178
+ authMethod: metadata.authMethod,
179
+ };
164
180
  }
165
181
  /**
166
182
  * The grants named in the vault's list reply, or undefined when it names none.
@@ -513,14 +529,15 @@ export class ClaustrumScopedCustody {
513
529
  for (const record of skipped)
514
530
  this.#logger.warn('skipped malformed vault record', record);
515
531
  const grantReach = grantReachOf(inventory);
532
+ const classifying = 'classify' in this.#family;
516
533
  return {
517
534
  view: inventory.view,
518
535
  credentials: Object.freeze(credentials),
519
536
  skipped: Object.freeze(skipped),
520
- ...('classify' in this.#family && {
537
+ ...((classifying || refused.length > 0) && {
521
538
  refused: Object.freeze(refused),
522
- notMine,
523
539
  }),
540
+ ...(classifying && { notMine }),
524
541
  ...(grantReach && { grantReach }),
525
542
  };
526
543
  }
@@ -70,6 +70,10 @@ function loadBackend() {
70
70
  });
71
71
  return backend;
72
72
  }
73
+ function isSharingIoError(detail) {
74
+ return (detail?.reason === 'io-error' &&
75
+ (detail.win32Code === 32 || detail.win32Code === 303));
76
+ }
73
77
  export class PrivateFileError extends Error {
74
78
  path;
75
79
  stage;
@@ -88,7 +92,9 @@ export class PrivateFileError extends Error {
88
92
  ? // The reason stays on `.reason`: its word "unavailable" would make
89
93
  // OpenCode 1 retry a plain error carrying this message.
90
94
  `Private file refused at ${stage}: ${path}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
91
- : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
95
+ : isSharingIoError(detail)
96
+ ? `Private file busy at ${stage}: ${path}. Another process was replacing or deleting this file at the same moment (Windows error ${detail.win32Code}).`
97
+ : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
92
98
  this.path = path;
93
99
  this.stage = stage;
94
100
  this.name = 'PrivateFileError';
@@ -101,8 +107,7 @@ export class PrivateFileError extends Error {
101
107
  export function isWindowsSharingViolation(error) {
102
108
  return (windowsPrivateFiles &&
103
109
  error instanceof PrivateFileError &&
104
- error.reason === 'io-error' &&
105
- (error.win32Code === 32 || error.win32Code === 303));
110
+ isSharingIoError(error));
106
111
  }
107
112
  export async function privateOperation(path, stage, operation) {
108
113
  try {
@@ -1,6 +1,6 @@
1
- import { setTimeout as snapshotDelay } from "node:timers/promises";
1
+ import { setTimeout as delay } from "node:timers/promises";
2
2
  import { AtomicSyncError, syncJsonFile, writeJsonAtomic, writeJsonAtomicTracked, } from "./7211cfec06a298bc-atomic-write.js";
3
- import { readPrivateText, windowsPrivateFiles } from "./375d9cca2def037d-private-files.js";
3
+ import { isWindowsSharingViolation, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
4
4
  import { LockContentionError, LockOwnershipError } from "./4825e03209d6ae3e-with-lock.js";
5
5
  import { PoolOperationError, } from "./04a6357627de5ed0-errors.js";
6
6
  import { callFailureHook } from "./9deae3c4da4fd63b-hooks.js";
@@ -8,14 +8,25 @@ import { LockStack, } from "./43fc9e6b994519c7-refresh-lock.js";
8
8
  import { assertNotReserved } from "./08eef45626a94992-reserved.js";
9
9
  import { CREDENTIAL_STAMP_KEY, classifyConfig, classifyState, ensureEntries, entryIn, isRecord, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, retireEpochsIn, rosterOf, rosterRowIn, setEntryIn, } from "./cd94316a888b0a8e-schema.js";
10
10
  import { completeTornRows, loadRows } from "./fd45e82f2f9c0a0d-torn.js";
11
+ // About 1 s in total. A replace usually clears in milliseconds, but an
12
+ // OpenCode 2 turn ends if the first pool read of a request fails, and a
13
+ // scanner opening the new file can hold it longer.
14
+ const sharingRetryDelays = [5, 10, 20, 40, 80, 160, 320, 400];
11
15
  async function readText(path) {
12
- try {
13
- return await readPrivateText(path, windowsPrivateFiles);
14
- }
15
- catch (error) {
16
- if (error.code === 'ENOENT')
17
- return undefined;
18
- throw error;
16
+ for (let attempt = 0;; attempt++) {
17
+ try {
18
+ return await readPrivateText(path, windowsPrivateFiles);
19
+ }
20
+ catch (error) {
21
+ if (error.code === 'ENOENT')
22
+ return undefined;
23
+ const wait = sharingRetryDelays[attempt];
24
+ // An atomic replace can briefly block a Windows read. Permission
25
+ // refusals are not evidence of a replace and must still surface at once.
26
+ if (wait === undefined || !isWindowsSharingViolation(error))
27
+ throw error;
28
+ await delay(wait);
29
+ }
19
30
  }
20
31
  }
21
32
  function parseFile(text) {
@@ -39,12 +50,22 @@ export async function readPoolConfig(path) {
39
50
  */
40
51
  export async function readPool(ctx) {
41
52
  for (let attempt = 0; attempt < 3; attempt++) {
42
- const configText = await readText(ctx.configPath);
43
- const stateText = await readText(ctx.statePath);
44
- const checkedConfigText = await readText(ctx.configPath);
53
+ let configText;
54
+ let stateText;
55
+ let checkedConfigText;
56
+ try {
57
+ configText = await readText(ctx.configPath);
58
+ stateText = await readText(ctx.statePath);
59
+ checkedConfigText = await readText(ctx.configPath);
60
+ }
61
+ catch (error) {
62
+ if (isWindowsSharingViolation(error))
63
+ break;
64
+ throw error;
65
+ }
45
66
  if (configText !== checkedConfigText) {
46
67
  if (attempt < 2)
47
- await snapshotDelay(2 + Math.floor(Math.random() * 4));
68
+ await delay(2 + Math.floor(Math.random() * 4));
48
69
  continue;
49
70
  }
50
71
  const config = classifyConfig(parseFile(configText));
@@ -94,13 +94,14 @@ export interface AccountView {
94
94
  }
95
95
 
96
96
  export interface SidebarFrameProps {
97
- header: { badge: string; version?: string }
97
+ header: { badge: string; version?: string; afterBadge?: () => JSX.Element }
98
98
  accounts: readonly AccountView[]
99
99
  theme?: SidebarTheme
100
100
  appearance: SidebarAppearance
101
101
  showQuota: boolean
102
102
  now: number
103
103
  collapsed: boolean
104
+ collapsible?: boolean
104
105
  onToggle: () => void
105
106
  beforeQuota?: (account: AccountView) => JSX.Element
106
107
  afterQuota?: (account: AccountView) => JSX.Element
@@ -253,6 +254,107 @@ function barSegments(
253
254
  ]
254
255
  }
255
256
 
257
+ export interface SidebarGaugeRowProps {
258
+ label: string
259
+ used?: number
260
+ value?: string
261
+ warnAt?: number
262
+ errorAt?: number
263
+ }
264
+
265
+ export function SidebarGaugeRow(props: SidebarGaugeRowProps) {
266
+ const context = frameContext()
267
+ const [columns, setColumns] = createSignal(0)
268
+ let row: { width: number } | undefined
269
+ const known = () => props.used !== undefined && Number.isFinite(props.used)
270
+ const used = () => Math.max(0, Math.min(100, props.used ?? 0))
271
+ const figure = () =>
272
+ known() ? `${Math.round(100 - used())}% left` : 'no reading'
273
+ const appearance = () => ({
274
+ ...context.appearance,
275
+ warnThreshold: props.warnAt ?? context.appearance.warnThreshold,
276
+ errorThreshold: props.errorAt ?? context.appearance.errorThreshold,
277
+ })
278
+ const label = () =>
279
+ columns() <= 0
280
+ ? props.label
281
+ : fitText(props.label, columns() - displayWidth(figure()) - 1)
282
+ const barCells = () => {
283
+ if (!known()) return 0
284
+ const desired = context.appearance.barWidth
285
+ if (columns() <= 0) return desired
286
+ const room =
287
+ columns() - displayWidth(label()) - 1 - displayWidth(figure()) - 1
288
+ return room >= Math.min(4, desired) ? Math.min(desired, room) : 0
289
+ }
290
+ const segments = createMemo(
291
+ () => barSegments(used(), { ...appearance(), barWidth: barCells() }),
292
+ undefined,
293
+ {
294
+ equals: (previous, next) =>
295
+ previous.every(
296
+ (segment, index) =>
297
+ segment.text === next[index]?.text &&
298
+ segment.tone === next[index]?.tone,
299
+ ),
300
+ },
301
+ )
302
+ const value = () => {
303
+ if (!props.value) return ''
304
+ if (columns() <= 0) return props.value
305
+ const room =
306
+ columns() -
307
+ displayWidth(label()) -
308
+ 1 -
309
+ displayWidth(figure()) -
310
+ (barCells() > 0 ? barCells() + 1 : 0) -
311
+ 1
312
+ return room >= 2 ? fitText(props.value, room) : ''
313
+ }
314
+ const tone = () => (known() ? usageTone(used(), appearance()) : 'textMuted')
315
+ return (
316
+ <box
317
+ ref={(element: { width: number }) => {
318
+ row = element
319
+ }}
320
+ onSizeChange={() => setColumns(row?.width ?? 0)}
321
+ width='100%'
322
+ flexDirection='row'
323
+ justifyContent='space-between'
324
+ >
325
+ <box flexDirection='row' flexShrink={0}>
326
+ <text fg={context.theme.textMuted} wrapMode='none'>
327
+ {label()}{' '}
328
+ </text>
329
+ <Show when={barCells() > 0}>
330
+ {/* Explicit widths let empty slots grow on OpenTUI 0.4.5 and 0.5.11. */}
331
+ <Index each={segments()}>
332
+ {(segment) => (
333
+ <text
334
+ fg={context.theme[segment().tone]}
335
+ wrapMode='none'
336
+ width={displayWidth(segment().text)}
337
+ >
338
+ {segment().text}
339
+ </text>
340
+ )}
341
+ </Index>
342
+ <text wrapMode='none'> </text>
343
+ </Show>
344
+ <text fg={context.theme[tone()]} wrapMode='none'>
345
+ {figure()}
346
+ </text>
347
+ </box>
348
+ <Show when={value()}>
349
+ {/* The right-hand value reads like a stat row's: normal text, bold. */}
350
+ <text fg={context.theme.text} wrapMode='none'>
351
+ <b>{value()}</b>
352
+ </text>
353
+ </Show>
354
+ </box>
355
+ )
356
+ }
357
+
256
358
  function QuotaRow(props: {
257
359
  part: SidebarWindowPart
258
360
  pace?: PaceView
@@ -602,8 +704,9 @@ function AccountBlock(props: { account: AccountView; marginTop: number }) {
602
704
  /** Borderless, controlled presentation; host registration and provider policy stay in the plugin. */
603
705
  export function SidebarFrame(props: SidebarFrameProps) {
604
706
  const hasData = () => props.accounts.length > 0
707
+ const canCollapse = () => props.collapsible ?? hasData()
605
708
  const headerLabel = () =>
606
- !hasData()
709
+ !canCollapse()
607
710
  ? props.header.badge
608
711
  : `${props.collapsed ? '\u25b6' : '\u25bc'} ${props.header.badge}`
609
712
  // Missing semantic colors inherit normal text; an unset palette uses terminal defaults.
@@ -623,6 +726,21 @@ export function SidebarFrame(props: SidebarFrameProps) {
623
726
  // Inverting an incomplete badge palette can put light text on a light background.
624
727
  const invertBadge = () =>
625
728
  props.theme?.accent !== undefined && props.theme?.background !== undefined
729
+ function HeaderBadge() {
730
+ return (
731
+ <box
732
+ paddingLeft={1}
733
+ paddingRight={1}
734
+ backgroundColor={invertBadge() ? props.theme?.accent : undefined}
735
+ >
736
+ <text
737
+ fg={invertBadge() ? props.theme?.background : context.theme.accent}
738
+ >
739
+ <b>{headerLabel()}</b>
740
+ </text>
741
+ </box>
742
+ )
743
+ }
626
744
  return (
627
745
  <FrameContext.Provider value={context}>
628
746
  <box width='100%' flexDirection='column'>
@@ -634,33 +752,26 @@ export function SidebarFrame(props: SidebarFrameProps) {
634
752
  justifyContent='space-between'
635
753
  alignItems='center'
636
754
  onMouseDown={() => {
637
- if (hasData()) props.onToggle()
755
+ if (canCollapse()) props.onToggle()
638
756
  }}
639
757
  >
640
- <box
641
- paddingLeft={1}
642
- paddingRight={1}
643
- backgroundColor={invertBadge() ? props.theme?.accent : undefined}
644
- >
645
- <text
646
- fg={
647
- invertBadge() ? props.theme?.background : context.theme.accent
648
- }
649
- >
650
- <b>{headerLabel()}</b>
651
- </text>
652
- </box>
758
+ <Show when={props.header.afterBadge} fallback={<HeaderBadge />}>
759
+ <box flexDirection='row' alignItems='center'>
760
+ <HeaderBadge />
761
+ {props.header.afterBadge?.()}
762
+ </box>
763
+ </Show>
653
764
  <Show when={props.header.version}>
654
765
  <text fg={context.theme.textMuted}>{props.header.version}</text>
655
766
  </Show>
656
767
  </box>
657
- <Show when={props.collapsed && hasData()}>
768
+ <Show when={props.collapsed && canCollapse()}>
658
769
  <For each={props.accounts}>
659
770
  {(account) => <CollapsedAccountRow account={account} />}
660
771
  </For>
661
772
  {props.collapsedSections?.()}
662
773
  </Show>
663
- <Show when={!props.collapsed || !hasData()}>
774
+ <Show when={!props.collapsed || !canCollapse()}>
664
775
  <Show when={props.showQuota && hasData()}>
665
776
  <SidebarSection title='Quota'>
666
777
  <For each={props.accounts}>
@@ -145,22 +145,38 @@ function credentialTypeOf(row, family) {
145
145
  }
146
146
  return { kind: 'refused', code: 'unclassified' };
147
147
  }
148
- if (row.credentialType !== 'oauth' && row.credentialType !== 'api_key')
148
+ const type = row.credentialType;
149
+ if (type === 'oauth') {
150
+ if (row.refreshAdapter !== family.refreshAdapter)
151
+ return notMine;
152
+ }
153
+ else if (type === 'api_key') {
154
+ if (!family.apiKeys || row.refreshAdapter !== undefined)
155
+ return notMine;
156
+ }
157
+ else {
149
158
  return notMine;
150
- if (row.credentialType === 'oauth')
151
- return row.refreshAdapter === family.refreshAdapter
152
- ? { kind: 'mine', type: 'oauth' }
153
- : notMine;
154
- if (row.credentialType === 'api_key' && family.apiKeys)
155
- return row.refreshAdapter === undefined
156
- ? { kind: 'mine', type: 'api_key' }
157
- : notMine;
158
- return notMine;
159
+ }
160
+ const { authMethod } = rowFactsOf(row, { includeProviderIds: false });
161
+ // Older vaults omit the method. If present, it must match the serving type.
162
+ if (authMethod !== undefined) {
163
+ const matchesType = type === 'oauth'
164
+ ? authMethod === 'chatgpt' ||
165
+ authMethod === 'antigravity' ||
166
+ authMethod === 'oauth'
167
+ : authMethod === 'apikey';
168
+ if (!matchesType)
169
+ return { kind: 'refused', code: 'unknown-auth-method' };
170
+ }
171
+ return { kind: 'mine', type };
159
172
  }
160
173
  /** Structural access keeps the public facts independent of client declarations. */
161
- function rowFactsOf(row) {
174
+ function rowFactsOf(row, { includeProviderIds = true } = {}) {
162
175
  const metadata = row;
163
- return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
176
+ return {
177
+ providerIds: includeProviderIds ? metadata.providerIds : undefined,
178
+ authMethod: metadata.authMethod,
179
+ };
164
180
  }
165
181
  /**
166
182
  * The grants named in the vault's list reply, or undefined when it names none.
@@ -513,14 +529,15 @@ export class ClaustrumScopedCustody {
513
529
  for (const record of skipped)
514
530
  this.#logger.warn('skipped malformed vault record', record);
515
531
  const grantReach = grantReachOf(inventory);
532
+ const classifying = 'classify' in this.#family;
516
533
  return {
517
534
  view: inventory.view,
518
535
  credentials: Object.freeze(credentials),
519
536
  skipped: Object.freeze(skipped),
520
- ...('classify' in this.#family && {
537
+ ...((classifying || refused.length > 0) && {
521
538
  refused: Object.freeze(refused),
522
- notMine,
523
539
  }),
540
+ ...(classifying && { notMine }),
524
541
  ...(grantReach && { grantReach }),
525
542
  };
526
543
  }
@@ -70,6 +70,10 @@ function loadBackend() {
70
70
  });
71
71
  return backend;
72
72
  }
73
+ function isSharingIoError(detail) {
74
+ return (detail?.reason === 'io-error' &&
75
+ (detail.win32Code === 32 || detail.win32Code === 303));
76
+ }
73
77
  export class PrivateFileError extends Error {
74
78
  path;
75
79
  stage;
@@ -88,7 +92,9 @@ export class PrivateFileError extends Error {
88
92
  ? // The reason stays on `.reason`: its word "unavailable" would make
89
93
  // OpenCode 1 retry a plain error carrying this message.
90
94
  `Private file refused at ${stage}: ${path}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
91
- : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
95
+ : isSharingIoError(detail)
96
+ ? `Private file busy at ${stage}: ${path}. Another process was replacing or deleting this file at the same moment (Windows error ${detail.win32Code}).`
97
+ : `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
92
98
  this.path = path;
93
99
  this.stage = stage;
94
100
  this.name = 'PrivateFileError';
@@ -101,8 +107,7 @@ export class PrivateFileError extends Error {
101
107
  export function isWindowsSharingViolation(error) {
102
108
  return (windowsPrivateFiles &&
103
109
  error instanceof PrivateFileError &&
104
- error.reason === 'io-error' &&
105
- (error.win32Code === 32 || error.win32Code === 303));
110
+ isSharingIoError(error));
106
111
  }
107
112
  export async function privateOperation(path, stage, operation) {
108
113
  try {
@@ -1,6 +1,6 @@
1
- import { setTimeout as snapshotDelay } from "node:timers/promises";
1
+ import { setTimeout as delay } from "node:timers/promises";
2
2
  import { AtomicSyncError, syncJsonFile, writeJsonAtomic, writeJsonAtomicTracked, } from "./7211cfec06a298bc-atomic-write.js";
3
- import { readPrivateText, windowsPrivateFiles } from "./375d9cca2def037d-private-files.js";
3
+ import { isWindowsSharingViolation, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
4
4
  import { LockContentionError, LockOwnershipError } from "./4825e03209d6ae3e-with-lock.js";
5
5
  import { PoolOperationError, } from "./04a6357627de5ed0-errors.js";
6
6
  import { callFailureHook } from "./9deae3c4da4fd63b-hooks.js";
@@ -8,14 +8,25 @@ import { LockStack, } from "./43fc9e6b994519c7-refresh-lock.js";
8
8
  import { assertNotReserved } from "./08eef45626a94992-reserved.js";
9
9
  import { CREDENTIAL_STAMP_KEY, classifyConfig, classifyState, ensureEntries, entryIn, isRecord, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, retireEpochsIn, rosterOf, rosterRowIn, setEntryIn, } from "./cd94316a888b0a8e-schema.js";
10
10
  import { completeTornRows, loadRows } from "./fd45e82f2f9c0a0d-torn.js";
11
+ // About 1 s in total. A replace usually clears in milliseconds, but an
12
+ // OpenCode 2 turn ends if the first pool read of a request fails, and a
13
+ // scanner opening the new file can hold it longer.
14
+ const sharingRetryDelays = [5, 10, 20, 40, 80, 160, 320, 400];
11
15
  async function readText(path) {
12
- try {
13
- return await readPrivateText(path, windowsPrivateFiles);
14
- }
15
- catch (error) {
16
- if (error.code === 'ENOENT')
17
- return undefined;
18
- throw error;
16
+ for (let attempt = 0;; attempt++) {
17
+ try {
18
+ return await readPrivateText(path, windowsPrivateFiles);
19
+ }
20
+ catch (error) {
21
+ if (error.code === 'ENOENT')
22
+ return undefined;
23
+ const wait = sharingRetryDelays[attempt];
24
+ // An atomic replace can briefly block a Windows read. Permission
25
+ // refusals are not evidence of a replace and must still surface at once.
26
+ if (wait === undefined || !isWindowsSharingViolation(error))
27
+ throw error;
28
+ await delay(wait);
29
+ }
19
30
  }
20
31
  }
21
32
  function parseFile(text) {
@@ -39,12 +50,22 @@ export async function readPoolConfig(path) {
39
50
  */
40
51
  export async function readPool(ctx) {
41
52
  for (let attempt = 0; attempt < 3; attempt++) {
42
- const configText = await readText(ctx.configPath);
43
- const stateText = await readText(ctx.statePath);
44
- const checkedConfigText = await readText(ctx.configPath);
53
+ let configText;
54
+ let stateText;
55
+ let checkedConfigText;
56
+ try {
57
+ configText = await readText(ctx.configPath);
58
+ stateText = await readText(ctx.statePath);
59
+ checkedConfigText = await readText(ctx.configPath);
60
+ }
61
+ catch (error) {
62
+ if (isWindowsSharingViolation(error))
63
+ break;
64
+ throw error;
65
+ }
45
66
  if (configText !== checkedConfigText) {
46
67
  if (attempt < 2)
47
- await snapshotDelay(2 + Math.floor(Math.random() * 4));
68
+ await delay(2 + Math.floor(Math.random() * 4));
48
69
  continue;
49
70
  }
50
71
  const config = classifyConfig(parseFile(configText));