@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.
- package/dist/bin.js +9 -9
- package/dist/{codex-request-Cl6zEfsR.d.ts → codex-request-DYqSE0ti.d.ts} +373 -2
- package/dist/{index-wma2ggn9.js → index-14x5shtc.js} +2 -2
- package/dist/{index-gkye2xh1.js → index-1scvhkyy.js} +2 -2
- package/dist/index-1wcg7g9d.js +2 -0
- package/dist/index-50p400eg.js +8 -0
- package/dist/{index-k5av4j8p.js → index-dzpjz8hv.js} +2 -2
- package/dist/{index-cxnrd85v.js → index-f7kmsdfk.js} +1 -1
- package/dist/index-fkgd5yv6.js +76 -0
- package/dist/{index-z9cj13z7.js → index-hnfqppx9.js} +1 -1
- package/dist/index-j2qfnmth.js +64 -0
- package/dist/{index-2f330s35.js → index-m8m7rakq.js} +2 -2
- package/dist/{index-94b345dw.js → index-t65axpta.js} +1 -1
- package/dist/{index-yygzbxjk.js → index-tes6vn59.js} +1 -1
- package/dist/index-xjtbg7sx.js +101 -0
- package/dist/index.d.ts +1 -372
- package/dist/index.js +1 -1
- package/dist/openai-auth.schema.json +400 -0
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-sgwxn4xg.js → token-j34j1zhm.js} +1 -1
- package/dist/token-util-bf619nmg.js +1 -0
- package/dist/tui-preferences.js +3 -3
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +3 -3
- package/src/tui-compiled/raw/logger.js +8 -1
- package/src/tui-compiled/raw/shared/061e741c052de9c1-paths.js +48 -0
- package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +41 -18
- package/src/tui-compiled/raw/shared/23300c068d0b2ffc-parse.js +65 -0
- package/src/tui-compiled/raw/shared/3000be4f79f20eb6-write.js +88 -0
- package/src/tui-compiled/raw/shared/44449e891fab9fbc-edit.js +229 -0
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +1 -1
- package/src/tui-compiled/raw/shared/5803fadb30af0ec0-descriptors.js +81 -0
- package/src/tui-compiled/raw/shared/58bc35a3cd459085-define.js +52 -0
- package/src/tui-compiled/raw/shared/5f4bc45522ab9bc6-update.js +139 -0
- package/src/tui-compiled/raw/shared/6948d70969aa7a55-fs.js +19 -0
- package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +28 -12
- package/src/tui-compiled/raw/shared/81758f9fe7c2a576-handle.js +228 -0
- package/src/tui-compiled/raw/shared/87f6e22d4fc34918-resolve.js +51 -0
- package/src/tui-compiled/raw/shared/8a18abe4fa2977c8-menu.js +1 -0
- package/src/tui-compiled/raw/shared/8ab1f5794e677151-move.js +351 -0
- package/src/tui-compiled/raw/shared/92e38944b51b2405-file-read-cache.js +9 -5
- package/src/tui-compiled/raw/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
- package/src/tui-compiled/raw/shared/cc0f2d1963547799-index.js +7 -0
- package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +48 -5
- package/src/tui-compiled/raw/shared/e0ed4a490e4eaa4f-schema.js +81 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
- package/src/tui-compiled/raw/shared/eac0bed49f3d4110-lock-errors.js +15 -0
- package/src/tui-compiled/raw/shared/facfd8afc431d68a-refusal.js +15 -0
- package/src/tui-compiled/raw/shared/fc7db0c5aa764565-settings-install.js +85 -0
- package/src/tui-compiled/raw/shared/fcd26e77bc538838-snapshot.js +150 -0
- package/src/tui-compiled/runtime/logger.js +8 -1
- package/src/tui-compiled/runtime/shared/061e741c052de9c1-paths.js +48 -0
- package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +41 -18
- package/src/tui-compiled/runtime/shared/23300c068d0b2ffc-parse.js +65 -0
- package/src/tui-compiled/runtime/shared/3000be4f79f20eb6-write.js +88 -0
- package/src/tui-compiled/runtime/shared/44449e891fab9fbc-edit.js +229 -0
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +1 -1
- package/src/tui-compiled/runtime/shared/5803fadb30af0ec0-descriptors.js +81 -0
- package/src/tui-compiled/runtime/shared/58bc35a3cd459085-define.js +52 -0
- package/src/tui-compiled/runtime/shared/5f4bc45522ab9bc6-update.js +139 -0
- package/src/tui-compiled/runtime/shared/6948d70969aa7a55-fs.js +19 -0
- package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +28 -12
- package/src/tui-compiled/runtime/shared/81758f9fe7c2a576-handle.js +228 -0
- package/src/tui-compiled/runtime/shared/87f6e22d4fc34918-resolve.js +51 -0
- package/src/tui-compiled/runtime/shared/8a18abe4fa2977c8-menu.js +1 -0
- package/src/tui-compiled/runtime/shared/8ab1f5794e677151-move.js +351 -0
- package/src/tui-compiled/runtime/shared/92e38944b51b2405-file-read-cache.js +9 -5
- package/src/tui-compiled/runtime/shared/9865a4fa45882c6f-settings-decisions.js +13 -0
- package/src/tui-compiled/runtime/shared/cc0f2d1963547799-index.js +7 -0
- package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +48 -5
- package/src/tui-compiled/runtime/shared/e0ed4a490e4eaa4f-schema.js +81 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +146 -2
- package/src/tui-compiled/runtime/shared/eac0bed49f3d4110-lock-errors.js +15 -0
- package/src/tui-compiled/runtime/shared/facfd8afc431d68a-refusal.js +15 -0
- package/src/tui-compiled/runtime/shared/fc7db0c5aa764565-settings-install.js +85 -0
- package/src/tui-compiled/runtime/shared/fcd26e77bc538838-snapshot.js +150 -0
- package/dist/index-3mbw88h7.js +0 -91
- package/dist/index-999nwa9p.js +0 -76
- package/dist/index-pc4vrrex.js +0 -2
- package/dist/index-snq7bwr6.js +0 -8
- package/dist/index-xk7f1aef.js +0 -64
- package/dist/token-util-8mrnmkge.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { gt as QuotaMap } from "./sidebar-state-CrRiE9hw.js";
|
|
2
|
-
import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
|
|
3
2
|
import "@cortexkit/private-files";
|
|
3
|
+
import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
|
|
4
4
|
import { Plugin } from "@opencode/plugin";
|
|
5
5
|
import "@opencode/plugin/promise/session";
|
|
6
6
|
type OAuthCredential = {
|
|
@@ -313,6 +313,182 @@ interface OpenPoolStoreOptions {
|
|
|
313
313
|
onLockStep?: LockEnvironment['onLockStep'];
|
|
314
314
|
onRenewalTimer?: LockEnvironment['onRenewalTimer'];
|
|
315
315
|
}
|
|
316
|
+
type QuotaWindowName = string;
|
|
317
|
+
type ProviderQuotaFn = (input: {
|
|
318
|
+
accessToken: string;
|
|
319
|
+
fetchImpl: typeof fetch;
|
|
320
|
+
now: () => number;
|
|
321
|
+
}) => Promise<OAuthQuotaSnapshot>;
|
|
322
|
+
type QuotaEntry = {
|
|
323
|
+
quota: OAuthQuotaSnapshot;
|
|
324
|
+
refreshAfter: number;
|
|
325
|
+
checkedAt: number;
|
|
326
|
+
accountId?: string;
|
|
327
|
+
};
|
|
328
|
+
type QuotaManagerOptions = {
|
|
329
|
+
storage: AccountStorage | null;
|
|
330
|
+
fetchImpl?: typeof fetch;
|
|
331
|
+
/**
|
|
332
|
+
* Account config file this manager's cross-process refresh locks are named
|
|
333
|
+
* after. Host-resolved and required, so two hosts pointing at different
|
|
334
|
+
* stores never contend on one another's lock.
|
|
335
|
+
*/
|
|
336
|
+
configPath: string;
|
|
337
|
+
now?: () => number;
|
|
338
|
+
/** Injected quota-fetch function — replaces the hard-imported Anthropic fetchOAuthQuotaSnapshot */
|
|
339
|
+
fetchQuotaFn?: ProviderQuotaFn;
|
|
340
|
+
onMainQuotaFetched?: (quota: OAuthQuotaSnapshot, checkedAt: number, fingerprint: string, fetchStartedAt: number) => void;
|
|
341
|
+
onApiError?: (error: AccountOperationError) => void;
|
|
342
|
+
};
|
|
343
|
+
declare class QuotaManager {
|
|
344
|
+
private main;
|
|
345
|
+
private mainTokenFp;
|
|
346
|
+
private mainQuotaAccountId;
|
|
347
|
+
private fallbacks;
|
|
348
|
+
private fallbackTokenFps;
|
|
349
|
+
private inflightMain;
|
|
350
|
+
private inflightMainFp;
|
|
351
|
+
private inflightFallbacks;
|
|
352
|
+
private mainLastApiError;
|
|
353
|
+
private fallbackApiErrors;
|
|
354
|
+
private fallbackErrorTokenFps;
|
|
355
|
+
private rateLimitedUntilMap;
|
|
356
|
+
private apiGate;
|
|
357
|
+
private lastApiCallAt;
|
|
358
|
+
private storage;
|
|
359
|
+
private readonly fetchImpl;
|
|
360
|
+
private readonly now;
|
|
361
|
+
private readonly fetchQuotaFn;
|
|
362
|
+
private readonly onMainQuotaFetched;
|
|
363
|
+
private readonly onApiError;
|
|
364
|
+
private readonly configPath;
|
|
365
|
+
constructor(opts: QuotaManagerOptions);
|
|
366
|
+
/**
|
|
367
|
+
* Cached main quota entry. Pass the live access token to enforce token
|
|
368
|
+
* binding: if the cached entry was produced by a different token (main
|
|
369
|
+
* account switched), it is dropped and null is returned so the caller
|
|
370
|
+
* refetches for the current account. Called without a token (e.g. for
|
|
371
|
+
* display) it returns whatever is cached.
|
|
372
|
+
*/
|
|
373
|
+
getMain(accessToken?: string): QuotaEntry | null;
|
|
374
|
+
/**
|
|
375
|
+
* Cached fallback quota entry. Pass the live access token to enforce token
|
|
376
|
+
* binding: if the entry was produced by a different token (account re-login),
|
|
377
|
+
* it is dropped and null is returned so the caller refetches.
|
|
378
|
+
*/
|
|
379
|
+
getFallback(accountId: string, accessToken?: string): QuotaEntry | null;
|
|
380
|
+
getAllFallbacks(): Map<string, QuotaEntry>;
|
|
381
|
+
setMain(accessToken: string, entry: QuotaEntry, accountId?: string, completeSnapshot?: boolean): void;
|
|
382
|
+
/**
|
|
383
|
+
* Non-invalidating read of the cached main quota for POLICY decisions
|
|
384
|
+
* (killswitch). Unlike getMain(token), a token mismatch does NOT drop the
|
|
385
|
+
* cache — an access-token refresh is a same-account event and must not turn a
|
|
386
|
+
* known-exhausted account into "unknown" (which would fail open and spend).
|
|
387
|
+
*
|
|
388
|
+
* Pass the live ChatGPT accountId to still drop on a genuine account SWITCH:
|
|
389
|
+
* if the cached entry's account identity is known and differs, return null so
|
|
390
|
+
* the killswitch treats it as unknown rather than judging account A by account
|
|
391
|
+
* B's quota. When identity is unknown on either side, the cached snapshot is
|
|
392
|
+
* returned (best-effort) — the same fail-open-on-unknown stance as elsewhere.
|
|
393
|
+
*/
|
|
394
|
+
peekMainForPolicy(accountId?: string): QuotaEntry | null;
|
|
395
|
+
/**
|
|
396
|
+
* Non-invalidating read of a cached fallback quota for POLICY decisions
|
|
397
|
+
* (killswitch, admission). Keyed by the stable internal account id, so a
|
|
398
|
+
* token refresh for the same account does not drop it (getFallback(id, token)
|
|
399
|
+
* would).
|
|
400
|
+
*
|
|
401
|
+
* Pass the live ChatGPT identity to still drop on a genuine re-login: if the
|
|
402
|
+
* cached entry's identity is known and differs, return null so the previous
|
|
403
|
+
* identity's (possibly exhausted) quota is never judged against its
|
|
404
|
+
* replacement. Unknown on either side fails open, matching peekMainForPolicy.
|
|
405
|
+
*/
|
|
406
|
+
peekFallbackForPolicy(accountId: string, identity?: string): QuotaEntry | null;
|
|
407
|
+
setFallback(accountId: string, entry: QuotaEntry, accessToken?: string, completeSnapshot?: boolean, identity?: string): void;
|
|
408
|
+
/**
|
|
409
|
+
* Mark accountId ('main' or a fallback id) rate-limited until resetAtMs.
|
|
410
|
+
* Keeps the LATER reset: skips only when an existing mark is strictly
|
|
411
|
+
* later than resetAtMs, so an equal-reset re-mark still applies (idempotent)
|
|
412
|
+
* instead of being silently dropped by a stale `>=` comparison.
|
|
413
|
+
*/
|
|
414
|
+
markRateLimited(accountId: string, resetAtMs: number): void;
|
|
415
|
+
/** True iff accountId has a mark whose reset has not yet passed. */
|
|
416
|
+
isRateLimited(accountId: string): boolean;
|
|
417
|
+
/**
|
|
418
|
+
* Raw stored reset for accountId's mark, or undefined if none. Unlike
|
|
419
|
+
* isRateLimited, this does NOT apply read-time expiry — callers on the
|
|
420
|
+
* block path already know the mark is live (isRateLimited just returned
|
|
421
|
+
* true) and want its exact reset estimate for a Retry-After computation.
|
|
422
|
+
*/
|
|
423
|
+
rateLimitedUntil(accountId: string): number | undefined;
|
|
424
|
+
/** Explicit early clear — read-time expiry in isRateLimited is primary. */
|
|
425
|
+
clearRateLimited(accountId: string): void;
|
|
426
|
+
refreshMain(accessToken: string): Promise<OAuthQuotaSnapshot>;
|
|
427
|
+
refreshFallback(accountId: string, accessToken: string): Promise<OAuthQuotaSnapshot>;
|
|
428
|
+
refreshAllFallbacks(accounts: OAuthAccount[]): Promise<void>;
|
|
429
|
+
/**
|
|
430
|
+
* Fire-and-forget refresh. Does not await, swallows errors.
|
|
431
|
+
*/
|
|
432
|
+
refreshMainInBackground(accessToken: string): void;
|
|
433
|
+
isMainStale(): boolean;
|
|
434
|
+
isFallbackStale(accountId: string, accessToken?: string): boolean;
|
|
435
|
+
shouldRefreshOnRequestCount(requestCount: number): boolean;
|
|
436
|
+
/**
|
|
437
|
+
* Combined check: should a refresh happen right now?
|
|
438
|
+
* True if main is stale by time OR triggered by request count.
|
|
439
|
+
*/
|
|
440
|
+
needsRefresh(requestCount: number): boolean;
|
|
441
|
+
updateStorage(storage: AccountStorage | null): void;
|
|
442
|
+
/**
|
|
443
|
+
* Seed/update the main quota cache from persisted state. This is deliberately
|
|
444
|
+
* callable after every disk load so another plugin process's fresh quota write
|
|
445
|
+
* can stop this process from showing "checking…" or making a redundant quota
|
|
446
|
+
* API call.
|
|
447
|
+
*/
|
|
448
|
+
seedMainFromStorage(storage: AccountStorage | null, accessToken?: string): void;
|
|
449
|
+
private seedMainBackoffFromStorage;
|
|
450
|
+
/**
|
|
451
|
+
* Seed fallback cache entries from persisted account.quota data.
|
|
452
|
+
* Updates older in-memory entries so a fresh quota write from another plugin
|
|
453
|
+
* process prevents redundant checks and stale sidebar writes.
|
|
454
|
+
*/
|
|
455
|
+
seedFallbacksFromAccounts(accounts: OAuthAccount[]): void;
|
|
456
|
+
/**
|
|
457
|
+
* Whether the MAIN quota API is currently in backoff. Scoped to the main
|
|
458
|
+
* account — a fallback account's 429 never reports here.
|
|
459
|
+
*/
|
|
460
|
+
isBackedOff(): boolean;
|
|
461
|
+
/**
|
|
462
|
+
* Whether a specific fallback account's quota API is in backoff.
|
|
463
|
+
*/
|
|
464
|
+
isFallbackBackedOff(accountId: string, accessToken?: string): boolean;
|
|
465
|
+
getLastApiError(): AccountOperationError | undefined;
|
|
466
|
+
/** Minimum gap between consecutive quota API calls (ms). */
|
|
467
|
+
private static readonly API_CALL_GAP_MS;
|
|
468
|
+
private static fallbackInflightKey;
|
|
469
|
+
private static quotaLockName;
|
|
470
|
+
/**
|
|
471
|
+
* Serialize API calls through a shared gate so only one
|
|
472
|
+
* quota API request runs at a time, with a minimum gap
|
|
473
|
+
* between calls. Prevents concurrent and rapid-fire calls
|
|
474
|
+
* from triggering rate limits.
|
|
475
|
+
*/
|
|
476
|
+
private _enqueueApiFetch;
|
|
477
|
+
private _fetchMain;
|
|
478
|
+
private _fetchFallback;
|
|
479
|
+
/** Route through injected fetchQuotaFn, or throw if unset. */
|
|
480
|
+
private _fetchQuota;
|
|
481
|
+
private static isAuthError;
|
|
482
|
+
/** Main quota failure: arms main-only backoff and persists via onApiError. */
|
|
483
|
+
private _handleMainFetchError;
|
|
484
|
+
/**
|
|
485
|
+
* Fallback quota failure: arms backoff for THIS account only. Never touches
|
|
486
|
+
* main backoff state and never calls onApiError (which persists the main
|
|
487
|
+
* quota error) — the per-account error is recorded by the caller via the
|
|
488
|
+
* account's lastQuotaRefreshError.
|
|
489
|
+
*/
|
|
490
|
+
private _handleFallbackFetchError;
|
|
491
|
+
}
|
|
316
492
|
/**
|
|
317
493
|
* The config file and the runtime-state file a store operation reads and writes.
|
|
318
494
|
*
|
|
@@ -324,6 +500,201 @@ interface AccountPaths {
|
|
|
324
500
|
configPath: string;
|
|
325
501
|
statePath: string;
|
|
326
502
|
}
|
|
503
|
+
type AccountQuotaWindow = {
|
|
504
|
+
usedPercent: number;
|
|
505
|
+
remainingPercent: number;
|
|
506
|
+
resetsAt?: string;
|
|
507
|
+
checkedAt: number;
|
|
508
|
+
windowMinutes?: number;
|
|
509
|
+
};
|
|
510
|
+
interface OAuthQuotaSnapshot {
|
|
511
|
+
primary?: AccountQuotaWindow;
|
|
512
|
+
secondary?: AccountQuotaWindow;
|
|
513
|
+
resetCreditsAvailable?: number;
|
|
514
|
+
resetCreditsApplicable?: number;
|
|
515
|
+
spendControl?: OAuthSpendControlReading;
|
|
516
|
+
/**
|
|
517
|
+
* Set when the source explicitly reported that the account has no credit
|
|
518
|
+
* budget (wham's `spend_control` or `individual_limit` is null). An absent
|
|
519
|
+
* `spendControl` alone only means the source did not carry the field: header
|
|
520
|
+
* and WebSocket pushes never do, so merges keep the previous budget for them.
|
|
521
|
+
* This marker is what lets a merge drop a budget that no longer exists.
|
|
522
|
+
*/
|
|
523
|
+
spendControlCleared?: true;
|
|
524
|
+
credits?: OAuthCredits;
|
|
525
|
+
}
|
|
526
|
+
interface OAuthSpendControlReading {
|
|
527
|
+
limit: number;
|
|
528
|
+
used: number;
|
|
529
|
+
remaining: number;
|
|
530
|
+
usedPercent: number;
|
|
531
|
+
remainingPercent: number;
|
|
532
|
+
resetsAt?: string;
|
|
533
|
+
unit?: string;
|
|
534
|
+
source?: string;
|
|
535
|
+
reached: boolean;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Prepaid workspace credits as the Codex backend reports them, in the usage
|
|
539
|
+
* poll's `credits` object or the `x-codex-credits-*` response headers. The
|
|
540
|
+
* headers carry no overage verdict, so `overageLimitReached` is optional.
|
|
541
|
+
* `checkedAt` is when the source was read. It is optional because accounts
|
|
542
|
+
* files written by older versions hold credits without it.
|
|
543
|
+
*/
|
|
544
|
+
interface OAuthCredits {
|
|
545
|
+
hasCredits: boolean;
|
|
546
|
+
unlimited: boolean;
|
|
547
|
+
overageLimitReached?: boolean;
|
|
548
|
+
balance?: number;
|
|
549
|
+
checkedAt?: number;
|
|
550
|
+
}
|
|
551
|
+
type AccountBase = {
|
|
552
|
+
id: string;
|
|
553
|
+
label?: string;
|
|
554
|
+
enabled?: boolean;
|
|
555
|
+
addedAt?: number;
|
|
556
|
+
lastUsed?: number;
|
|
557
|
+
/** Stable ChatGPT account identifier extracted from the OAuth token claims. */
|
|
558
|
+
accountId?: string;
|
|
559
|
+
};
|
|
560
|
+
type AccountOperationError = {
|
|
561
|
+
message: string;
|
|
562
|
+
checkedAt: number;
|
|
563
|
+
nextRetryAt?: number;
|
|
564
|
+
retryCount?: number;
|
|
565
|
+
tokenHash?: string;
|
|
566
|
+
};
|
|
567
|
+
type OAuthAccount = AccountBase & {
|
|
568
|
+
type: 'oauth';
|
|
569
|
+
corrupt?: false;
|
|
570
|
+
access?: string;
|
|
571
|
+
refresh: string;
|
|
572
|
+
expires?: number;
|
|
573
|
+
lastRefreshedAt?: number;
|
|
574
|
+
lastRefreshError?: AccountOperationError;
|
|
575
|
+
lastQuotaRefreshError?: AccountOperationError;
|
|
576
|
+
quota?: OAuthQuotaSnapshot;
|
|
577
|
+
};
|
|
578
|
+
type CorruptOAuthAccount = AccountBase & {
|
|
579
|
+
type: 'oauth';
|
|
580
|
+
corrupt: true;
|
|
581
|
+
access?: undefined;
|
|
582
|
+
refresh?: undefined;
|
|
583
|
+
expires?: undefined;
|
|
584
|
+
lastRefreshedAt?: undefined;
|
|
585
|
+
lastRefreshError?: undefined;
|
|
586
|
+
lastQuotaRefreshError?: undefined;
|
|
587
|
+
quota?: undefined;
|
|
588
|
+
};
|
|
589
|
+
type ApiKeyAccount = AccountBase & {
|
|
590
|
+
type: 'api';
|
|
591
|
+
apiKey?: string;
|
|
592
|
+
baseURL: string;
|
|
593
|
+
authHeader?: 'authorization-bearer' | 'x-api-key';
|
|
594
|
+
};
|
|
595
|
+
type FallbackAccount = OAuthAccount | CorruptOAuthAccount | ApiKeyAccount;
|
|
596
|
+
/**
|
|
597
|
+
* `ordered` is the shared command menu's name for plain roster order; it is
|
|
598
|
+
* written only from that menu, which needs a migrated install.
|
|
599
|
+
*/
|
|
600
|
+
type RoutingMode = 'ordered' | 'main-first' | 'fallback-first' | 'sticky-balanced';
|
|
601
|
+
type KillswitchThresholds = Partial<Record<QuotaWindowName | '5h' | '1w', number>>;
|
|
602
|
+
type KillswitchConfig = {
|
|
603
|
+
enabled?: boolean;
|
|
604
|
+
main?: KillswitchThresholds;
|
|
605
|
+
accounts?: Record<string, KillswitchThresholds>;
|
|
606
|
+
/**
|
|
607
|
+
* In a `KILLSWITCH_FLOORS_SCHEMA` block, the floors of every account the
|
|
608
|
+
* block has no entry for, so an account added after the block was written
|
|
609
|
+
* is protected without anything writing floors for it.
|
|
610
|
+
*/
|
|
611
|
+
defaults?: KillswitchThresholds;
|
|
612
|
+
/**
|
|
613
|
+
* `KILLSWITCH_FLOORS_SCHEMA` once the block holds explicit per-account
|
|
614
|
+
* floors; see that constant for how the two formats differ.
|
|
615
|
+
*/
|
|
616
|
+
schema?: string;
|
|
617
|
+
};
|
|
618
|
+
/** The cache keep-warm settings; see `cacheKeepSettings`. */
|
|
619
|
+
type CacheKeepSettings = {
|
|
620
|
+
enabled?: boolean;
|
|
621
|
+
subagents?: boolean;
|
|
622
|
+
sustain?: boolean;
|
|
623
|
+
/** Clock-hour window start (0-23, inclusive) — keeps cachekeep idle warming
|
|
624
|
+
* inside `[startHour, endHour)` local hours. Omit to warm unconditionally. */
|
|
625
|
+
startHour?: number;
|
|
626
|
+
/** Clock-hour window end (0-23, exclusive) — must differ from startHour
|
|
627
|
+
* to be honored; an unset or equal hour falls back to "always warm". */
|
|
628
|
+
endHour?: number;
|
|
629
|
+
};
|
|
630
|
+
interface ResetInFlight {
|
|
631
|
+
redeemRequestId: string;
|
|
632
|
+
creditId: string;
|
|
633
|
+
startedAt: number;
|
|
634
|
+
}
|
|
635
|
+
interface ResetLastOutcome {
|
|
636
|
+
code: string;
|
|
637
|
+
at: number;
|
|
638
|
+
previousOutcome?: {
|
|
639
|
+
code: string;
|
|
640
|
+
at: number;
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
interface ResetAccountState {
|
|
644
|
+
inFlight?: ResetInFlight | Record<string, unknown>;
|
|
645
|
+
lastOutcome?: ResetLastOutcome;
|
|
646
|
+
cooldownUntil?: number;
|
|
647
|
+
}
|
|
648
|
+
type ResetStateByAccount = Record<string, ResetAccountState>;
|
|
649
|
+
type AccountStorage = {
|
|
650
|
+
version: 1;
|
|
651
|
+
main?: {
|
|
652
|
+
type: 'opencode';
|
|
653
|
+
provider: 'openai';
|
|
654
|
+
};
|
|
655
|
+
routing?: {
|
|
656
|
+
mode?: RoutingMode;
|
|
657
|
+
maxSameAccountWait?: 0 | 15 | 'max';
|
|
658
|
+
};
|
|
659
|
+
fallbackOn?: number[];
|
|
660
|
+
refresh?: {
|
|
661
|
+
enabled?: boolean;
|
|
662
|
+
refreshBeforeExpiryMinutes?: number;
|
|
663
|
+
mainLastRefreshError?: AccountOperationError;
|
|
664
|
+
mainRefreshLeaseId?: string;
|
|
665
|
+
mainRefreshLeaseUntil?: number;
|
|
666
|
+
mainRefreshLeaseTokenHash?: string;
|
|
667
|
+
};
|
|
668
|
+
quota?: {
|
|
669
|
+
enabled?: boolean;
|
|
670
|
+
checkIntervalMinutes?: number;
|
|
671
|
+
refreshEveryNRequests?: number;
|
|
672
|
+
minimumRemaining?: Partial<Record<QuotaWindowName | '5h' | '1w', number>>;
|
|
673
|
+
failClosedOnUnknownQuota?: boolean;
|
|
674
|
+
mainQuota?: OAuthQuotaSnapshot;
|
|
675
|
+
mainQuotaCheckedAt?: number;
|
|
676
|
+
mainQuotaToken?: string;
|
|
677
|
+
mainLastQuotaApiError?: AccountOperationError;
|
|
678
|
+
};
|
|
679
|
+
reset?: ResetStateByAccount;
|
|
680
|
+
dump?: {
|
|
681
|
+
enabled?: boolean;
|
|
682
|
+
};
|
|
683
|
+
costZeroing?: {
|
|
684
|
+
enabled?: boolean;
|
|
685
|
+
};
|
|
686
|
+
killswitch?: KillswitchConfig;
|
|
687
|
+
logging?: {
|
|
688
|
+
level?: string;
|
|
689
|
+
};
|
|
690
|
+
/** The older name of `cacheKeep`; read only until a settings write renames it. */
|
|
691
|
+
cachekeep?: CacheKeepSettings;
|
|
692
|
+
cacheKeep?: CacheKeepSettings;
|
|
693
|
+
/** Stable ChatGPT account identifier of the main account (extracted from OAuth token). */
|
|
694
|
+
mainAccountId?: string;
|
|
695
|
+
accounts: FallbackAccount[];
|
|
696
|
+
};
|
|
697
|
+
declare function loadAccounts(paths: AccountPaths): Promise<AccountStorage | null>;
|
|
327
698
|
interface IdTokenClaims {
|
|
328
699
|
chatgpt_account_id?: string;
|
|
329
700
|
email?: string;
|
|
@@ -1249,4 +1620,4 @@ interface CodexRequestRuntime {
|
|
|
1249
1620
|
now: () => number;
|
|
1250
1621
|
uuid: () => string;
|
|
1251
1622
|
}
|
|
1252
|
-
export { parseJwtClaims as _, RESPONSES_LITE_MODELS as a, HostSlotAdapter as c, OpenAiVaultOptions as d, BeginAccountLoginOptions as f, extractAccountIdFromClaims as g, TokenResponse as h, CodexSessionMetadata as i, ResetTargetIdentity as l, IdTokenClaims as m, CODEX_VERSION as n, RuntimeLayoutOptions as o, BeginAccountLoginResult as p, CodexRequestRuntime as r, PoolLifecycleDeps as s, CODEX_USER_AGENT as t, OpenAiVault as u,
|
|
1623
|
+
export { AccountPaths as C, loadAccounts as S, parseJwtClaims as _, RESPONSES_LITE_MODELS as a, OAuthAccount as b, HostSlotAdapter as c, OpenAiVaultOptions as d, BeginAccountLoginOptions as f, extractAccountIdFromClaims as g, TokenResponse as h, CodexSessionMetadata as i, ResetTargetIdentity as l, IdTokenClaims as m, CODEX_VERSION as n, RuntimeLayoutOptions as o, BeginAccountLoginResult as p, CodexRequestRuntime as r, PoolLifecycleDeps as s, CODEX_USER_AGENT as t, OpenAiVault as u, AccountStorage as v, QuotaManager as w, OAuthQuotaSnapshot as x, FallbackAccount as y };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Gg as U,Hg as E,Lg as F,Mg as p,Ng as L,Rg as c}from"./index-m8m7rakq.js";import{createHash as Cz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as b,rename as Kz,rmdir as Nz,stat as S,unlink as T}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as R,resolve as g}from"node:path";function x(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function k(z,G,Q){let V=z.startedAt===void 0?G?.mtimeMs:z.startedAt;return typeof V==="number"&&Number.isFinite(V)&&V<Q}async function Vz(z,G,Q,V){if(!Q)return;await V?.(z);try{let J=await L(z),K=await S(z);if(J===G&&K.dev===Q.dev&&K.ino===Q.ino&&K.mtimeMs===Q.mtimeMs&&K.size===Q.size)await T(z).catch(()=>{})}catch(J){if(J instanceof E&&J.code!=="ENOENT")throw J}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function u(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(G){return G.code==="EPERM"}}function Uz(z){return(G)=>Wz(G,z)}function Wz(z,G){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(G)&&/^[0-9a-f]{16}$/.test(z.slice(G.length))}function Xz(z){let G=/^port-(\d+)\.json$/.exec(z);return G?Number(G[1]):void 0}function s(z,G){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:V,token:J}=z;return a(Q)&&Xz(G)===Q&&typeof V==="number"&&Number.isInteger(V)&&V>=1&&V<=65535&&typeof J==="string"&&J.length>0}async function l(z,G){G?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await T(z).catch(()=>{})}async function Ez(z,G,Q={}){let V=async()=>{let J=R(z,`port-${G.pid}.json`);if(U)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(J,JSON.stringify({...G,startedAt:Date.now()}),{stagePath:`${J}.${(Q.stageName??y)()}.tmp`}),J;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let K={...G,startedAt:Date.now()},Y=`${J}.${(Q.stageName??y)()}.tmp`,W,N=!1;try{W=await Jz(Y,"wx",384),N=!0,await W.writeFile(JSON.stringify(K),"utf8"),await W.chmod(384),await W.close(),W=void 0,await Kz(Y,J),N=!1}finally{if(await W?.close().catch(()=>{}),N)await T(Y).catch(()=>{})}return J};try{return await V()}catch(J){if(J.code==="ENOENT")return await V();throw J}}async function Lz(z,G,Q,V,J={}){let K=x(J),Y;try{Y=await b(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let W=g(G);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let X=R(z,N.name),Z;try{Z=await b(X)}catch($){if($.code==="ENOENT")continue;throw $}for(let $ of Z){if(!$.startsWith("port-")||!$.endsWith(".json"))continue;let H=R(X,$),C=await S(H).catch(()=>{return}),q;try{q=await L(H)}catch(O){if(O instanceof E&&O.code!=="ENOENT")throw O;continue}if(q===void 0)continue;let A;try{A=JSON.parse(q)}catch{await l(H,V);continue}if(!s(A,$)){await l(H,V);continue}let I=A;if(!u(I.pid))await T(H).catch(()=>{});else if(k(I,C,K))await Vz(H,q,C,J.beforeRemove)}if(g(X)!==W)await Nz(X).catch(()=>{})}}async function d(z,G,Q={}){let V=x(Q);if(!u(G.pid))return null;let J=R(g(z),`port-${G.pid}.json`);try{if(U)await F(J,"file");let K=await S(J);if(k(G,K,V))return null;return`${J}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch(K){if(K instanceof E&&K.code!=="ENOENT")throw K;return null}}async function n(z,G,Q={}){let V=x(Q),J;try{if(U)await F(z,"directory");J=await b(z)}catch(X){if(X instanceof E&&X.code!=="ENOENT")throw X;return null}let K=[];for(let X of J){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;try{let Z=JSON.parse(await L(R(z,X)));if(s(Z,X))if(u(Z.pid)){let $=Z.startedAt===void 0?await S(R(z,X)).catch(()=>{return}):void 0;if(!k(Z,$,V))K.push(Z)}else await T(R(z,X)).catch(()=>{})}catch(Z){if(Z instanceof E&&Z.code!=="ENOENT")throw Z}}if(K.length===0)return null;let Y=G!==void 0&&G>=1?K.filter((X)=>X.pid===G):[];if(Q.exactPid===!0&&Y.length===0)return null;let W=Y.length>0?Y:K,N=(X)=>typeof X.startedAt==="number"&&Number.isFinite(X.startedAt)?X.startedAt:-1/0;return W.sort((X,Z)=>N(Z)-N(X))[0]??null}import{open as Yz}from"node:fs/promises";import{connect as Zz}from"node:net";import{join as $z,resolve as t}from"node:path";var e=2000,_=new Map,B=new Map;async function Hz(z,G){let Q=$z(t(z),`port-${G.pid}.json`);if(U){let J=JSON.parse(await L(Q));if(J.pid!==G.pid||J.port!==G.port||J.token!==G.token)return null;return null}let V;try{V=await Yz(Q,"r");let J=await V.stat(),K=JSON.parse(await V.readFile("utf8"));if(K.pid!==G.pid||K.port!==G.port||K.token!==G.token)return null;return`${Q}:${J.dev}:${J.ino}:${J.mtimeMs}:${J.size}`}catch{return null}finally{await V?.close().catch(()=>{})}}async function i(z,G,Q,V){let J=_.get(z);if(!U&&J&&await d(G,J.entry)===J.identity)return J;_.delete(z);let K=B.get(z);if(K)return K;let Y=(async()=>{let W=await(V.discover??n)(G,Q,V);if(!W)return null;let N=await Hz(G,W);if(!N)return{entry:W,identity:""};let X={entry:W,identity:N};return _.set(z,X),X})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,G,Q,V=e){return new Promise((J)=>{let K,Y=!1,W=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(X),K?.destroy(),J({value:Z,stale:$})},X=setTimeout(()=>N(null),V);try{let Z=JSON.stringify(Q);K=Zz({host:"127.0.0.1",port:z.port}),K.on("connect",()=>{W=!0,K?.write(`POST /rpc/${G} HTTP/1.0\r
|
|
2
2
|
Host: 127.0.0.1:${z.port}\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
Content-Type: application/json\r
|
|
@@ -9,4 +9,4 @@ Authorization: Bearer ${z.token}\r
|
|
|
9
9
|
\r
|
|
10
10
|
`);if(D>=0)C=D+4;if((C??A.length)>16384)return N(null);if(C!==void 0){let P=A.subarray(0,D).toString("latin1").split(`\r
|
|
11
11
|
`),f=/^HTTP\/1\.[01] (\d{3})(?: |$)/.exec(P[0]??"");if(!f)return N(null);let j=Number(f[1]);if(j<200||j>=300)return N(null,[401,403,404,410].includes(j));for(let w of P.slice(1)){let v=w.indexOf(":"),h=w.slice(0,v).toLowerCase(),m=w.slice(v+1).trim();if(h==="transfer-encoding")return N(null);if(h==="content-length"){if(q!==void 0||!/^\d+$/.test(m))return N(null);if(q=Number(m),!Number.isSafeInteger(q)||q>8388608)return N(null)}}A=Buffer.alloc(0)}}let M=H-(C??H);if(M>8388608)return N(null);if(q!==void 0){if(M>q)return N(null);if(M===q)I()}}),K.on("end",()=>{if(q!==void 0&&H-(C??0)!==q)return N(null);I()}),K.on("error",()=>N(null,!W)),K.on("close",()=>N(null))}catch{N(null,!W)}})}async function r(z,G,Q,V,J,K,Y=e){let W=JSON.stringify([t(z),G??null,Q.exactPid===!0]),N=await i(W,z,G,Q);if(V(N?.entry??null),!N)return null;let X=Date.now()+Y,Z=await o(N.entry,J,K,Y);if(!Z.stale)return Z.value;if(_.get(W)===N)_.delete(W);let $=await i(W,z,G,Q);if(!$||Date.now()>=X)return null;if($.entry.port===N.entry.port&&$.entry.pid===N.entry.pid&&$.entry.token===N.entry.token){if(_.get(W)===$)_.delete(W);return null}let H=await o($.entry,J,K,X-Date.now());if(H.stale&&_.get(W)===$)_.delete(W);return H.value}function jz(z,G,Q,V={}){let J={exactPid:V.exactPid,discover:V.discover},K=!1,Y=(W)=>{if(K)return;Q?.(W),K=!0};return{async pending(W,N,X){return(await r(z,G,J,Y,"pending-notifications",{lastReceivedId:W,sessionId:N},X))?.messages??[]},async apply(W,N){return await r(z,G,J,Y,"apply",{...W},N)??{text:"apply failed",knobs:{}}}}}
|
|
12
|
-
export{Uz as
|
|
12
|
+
export{Uz as ng,Ez as og,Lz as pg,n as qg,e as rg,jz as sg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{i as
|
|
1
|
+
import{ng as w,og as O,pg as k}from"./index-14x5shtc.js";import{Hg as h,Ng as D}from"./index-m8m7rakq.js";import{Tg as j}from"./index-t65axpta.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.15.1";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
|
|
2
|
+
export{i as fg,n as gg,a as hg,Bf as ig,Hf as jg,R as kg,bf as lg,Cf as mg};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Gg as q,Jg as _,Lg as A,Mg as w,Og as k,Qg as p}from"./index-m8m7rakq.js";import{appendFileSync as QJ,chmodSync as ZJ,existsSync as W,renameSync as g,statSync as $J}from"node:fs";import{open as UJ}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function $(G){let Z=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||Z.includes("apikey")||Z.endsWith("secret")||Z.endsWith("password")||Z.endsWith("token")&&!Z.endsWith("tokens")||!!J.extraSecretKeys?.(Z)}function U(G){let Z=G,V=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(Z[j]!==void 0)V.push([j,Z[j]]);let Y=new Set(V.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))V.push(j);return V}function B(G,Z,V,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(V.has(G))return"[Circular]";V.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,Z,V,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?U(G):Object.entries(G)).map(([N,z])=>[N,Z&&$(N)?"***REDACTED***":B(z,Z,V,C)]))}finally{V.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var E=T(),GJ=E.redact,HJ=E.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{ZJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&$J(J).size>=h))return;for(let $=m-1;$>=1;$--)if(W(`${J}.${$}`)){let U=`${J}.${$+1}`;g(`${J}.${$}`,U),b(U)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:$}=J;if(J.file=void 0,J.handle=void 0,H&&$)await _(H,"log-close",()=>$.close())}async function y(J,H){await w(VJ(H));try{await A(H,"file",!0)}catch($){if($.code!=="ENOENT")throw $;try{await k(H,"")}catch(U){if(U.code!=="EEXIST")throw U;await A(H,"file",!0)}}return J.handle=await _(H,"log-open",()=>UJ(H,"a")),J.file=H,J.handle}async function XJ(J,H,$){H=IJ(H);try{if(J.file!==H)await M(J);let U=J.handle??await y(J,H);if((await _(H,"log-stat",()=>U.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let Z=G===0?H:`${H}.${G}`,V=`${H}.${G+1}`;try{await A(Z,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A(V,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await p(Z,V),await A(V,"file")}U=await y(J,H)}await _(H,"log-append",()=>U.appendFile($,"utf8"))}catch(U){throw await M(J).catch(()=>{}),U}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,$,U,B=T(),G,Z=[],V,Y=Promise.resolve(),j,C={};function N(Q){let I=Y.then(Q);return Y=I.catch((X)=>{j=X}),I}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,$=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)U=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if(U)return U;let Q=typeof $==="function"?$():$;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if(V)clearTimeout(V),V=void 0;if(!Z.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let I;try{I=o()}catch{if(Z=[],q&&Q)return N(()=>M(C));return}let X=Z.join("");if(Z=[],!I){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,I,X)}finally{if(Q)await M(C)}});try{if(jJ(I),W(I))b(I);QJ(I,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!V)V=setTimeout(()=>{V=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function x(Q,I,X,P){if(H===void 0&&G===void 0)return;try{if(D[I]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${I.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
|
|
2
|
+
`;try{G?.({channel:Q,level:I,message:S,data:K})}catch{}if(H===void 0)return;if(Z.push(r),Z.length>=50){let F=R(!1);if(F instanceof Promise)F.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(I,X)=>x(Q,"error",I,X),warn:(I,X)=>x(Q,"warn",I,X),info:(I,X)=>x(Q,"info",I,X),debug:(I,X)=>x(Q,"debug",I,X),trace:(I,X)=>x(Q,"trace",I,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,Z=[],V)clearTimeout(V),V=void 0;H=void 0,$=void 0,U=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var O=BJ();function L(J){O.configure(J);let{configure:H,createLogger:$,setLogLevel:U,flushLogs:B}=O;return{configure:H,createLogger:$,setLogLevel:U,flushLogs:B}}function v(J){O.setLogLevel(J)}function u(){return O.flushLogs()}function c(J){return O.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,pJ=d.redactStrings;function hJ(J){L({...J,extraSecretKeys:f})}function uJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function fJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",xJ="openai-auth-state.json";function oJ(J){return MJ(J)===AJ?qJ(TJ(J),xJ):`${J}.state.json`}import{spawn as _J}from"node:child_process";function nJ(J,H=process.platform,$=_J){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),Z=$("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return Z.on("error",()=>{}),Z.unref(),Z.pid!==void 0}let U=$(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore"});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}catch{return!1}}export{T as tg,GJ as ug,v as vg,u as wg,c as xg,pJ as yg,hJ as zg,AJ as Ag,xJ as Bg,oJ as Cg,uJ as Dg,fJ as Eg,nJ as Fg};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{Gg as X,Hg as M,Ig as B0,Jg as u0,Lg as w,Mg as X0,Ng as P,Og as N0,Pg as g0,Rg as H0}from"./index-m8m7rakq.js";import{randomUUID as t}from"node:crypto";import{link as e0,lstat as u,mkdir as O0,open as K0,readdir as zz,readFile as f0,rename as b0,rm as c,stat as a,unlink as Bz}from"node:fs/promises";import{basename as Gz,dirname as G0,join as U0}from"node:path";import{resolve as M0}from"node:path";class n extends Error{path;code="ENOENT";constructor(z,B){super(`Lock record disappeared: ${z}`,{cause:B});this.path=z}}function m(z,B){return z instanceof M&&z.reason==="io-error"&&z.win32Code===5&&(z.stage==="read"||z.stage==="verify")&&B.some((K)=>M0(K)===z.path)}function p(z,B,K){return z instanceof M&&z.reason==="io-error"&&z.win32Code===5&&z.stage===K&&B.some((Y)=>M0(Y)===z.path)}async function L(z,B){try{return await B()}catch(K){if(!m(K,[z]))throw K;try{return await B()}catch(Y){if(Y.code==="ENOENT")throw new n(z,K);throw K}}}import{join as t0,resolve as o0}from"node:path";function J0(z,B){return`${z}.${B}.lock`}class L0 extends Error{details;constructor(z){super(`Timed out acquiring ${z.name} lock for ${z.target}`);this.name="LockContentionError",this.details=z}}class i extends Error{details;constructor(z){super(`Lost ${z.name} lock for ${z.target}`);this.name="LockOwnershipError",this.details=z}}function r0(z,B,K){let Y=o0(J0(B,K)),J=[Y,t0(Y,"owner.json")];return(B0(z)||m(z,J))&&(z.stage==="read"||z.stage==="verify")&&J.includes(z.path)||X&&(p(z,[Y],"create")||p(z,[`${Y}.evicting`],"directory-create"))}async function kz(z,B,K){let Y=performance.now(),J;for(;;){B.signal?.throwIfAborted();let _;try{_=await R0({path:z,name:B.name,ttlMs:B.ttlMs,renew:B.renew??!1,...B.onStep?{onStep:B.onStep}:{},...B.onRenewalTimer?{onRenewalTimer:B.onRenewalTimer}:{}}),J=void 0}catch(N){if(!r0(N,z,B.name))throw N;_=null,J??=N}if(_)try{return B.signal?.throwIfAborted(),await K(_)}finally{await _.release(B.signal)}let V=B.timeoutMs-(performance.now()-Y);if(V<=0){if(J)throw J;throw new L0({target:z,name:B.name,timeoutMs:B.timeoutMs})}await new Promise((N)=>setTimeout(N,Math.min(25,Math.ceil(V))))}}var l;async function Hz(z,B){let K=`${z}.${t()}.tmp`,Y;try{Y=await K0(K,"wx",384);try{if(l?.beforeWrite)await l.beforeWrite(K);await Y.writeFile(B,"utf8")}finally{await Y.close()}try{if(l?.beforeLink)await l.beforeLink(K,z);await e0(K,z)}catch(J){let _=J.code;if(_!=="EPERM"&&_!=="ENOTSUP"&&_!=="EOPNOTSUPP"&&_!=="EXDEV")throw J;await m0(z,B)}}finally{if(Y)await c(K,{force:!0}).catch(()=>{})}}async function m0(z,B){let K=await K0(z,"wx",384),Y;try{Y=await K.stat()}catch{Y=void 0}try{if(l?.beforeWrite)await l.beforeWrite(z);await K.writeFile(B,"utf8")}catch(J){try{let _=await u(z).catch(()=>{return});if(Y&&_&&_.dev===Y.dev&&_.ino===Y.ino)await c(z,{force:!0}).catch(()=>{})}catch{}throw J}finally{await K.close()}}var w0=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Kz=600000,Qz=256,Yz=4096,E0=new Set,y0=new Set,Zz;function $z(z,B){let K=`${B}.`,Y=".tmp";if(!z.startsWith(K)||!z.endsWith(".tmp"))return!1;return w0.test(z.slice(K.length,-4))}function v0(z,B){return z.dev===B.dev&&z.ino===B.ino&&z.size===B.size&&z.mtimeMs===B.mtimeMs&&z.birthtimeMs===B.birthtimeMs}async function k0(z){let B=await u(z);if(!B.isFile()||B.isSymbolicLink())return;if(B.size>Yz)return;let K=await K0(z,"r"),Y;try{if(!v0(B,await K.stat()))return;Y=await K.readFile("utf8")}finally{await K.close()}let J;try{J=JSON.parse(Y)}catch{return}if(!J||typeof J!=="object"||Array.isArray(J))return;let _=Object.keys(J).sort();if(_.length!==2||_[0]!=="expiresAt"||_[1]!=="ownerId")return;let{ownerId:V,expiresAt:N}=J;if(typeof V!=="string"||!w0.test(V))return;if(typeof N!=="number"||!Number.isFinite(N))return;return{identity:B,expiresAt:N}}async function Jz(z,B,K){let Y=G0(z),J=Gz(z),_=Zz,N=(await(_?.readdir??zz)(Y)).filter((O)=>$z(O,J)).slice(0,Qz),W=Math.max(Number.isFinite(B)?B:0,Kz);for(let O of N){let f=U0(Y,O);try{if(K()-(await u(f)).mtimeMs<W)continue;let y=await k0(f);if(!y||!(y.expiresAt<K()-W))continue;if(_?.beforeUnlink)await _.beforeUnlink(f);let S=await k0(f);if(!S||!v0(y.identity,S.identity)||!(S.expiresAt<K()-W))continue;await(_?.unlink??Bz)(f)}catch{}}}function _z(z,B,K){if(E0.has(z))return;E0.add(z);let Y=Promise.resolve().then(()=>Jz(z,B,K)).catch(()=>{});y0.add(Y),Y.finally(()=>y0.delete(Y))}var Xz=globalThis.setTimeout.bind(globalThis),Nz=globalThis.clearTimeout.bind(globalThis);function Uz(z){let B=z?.code;return B==="ENOENT"||!X&&(B==="EINVAL"||B==="ENOTDIR")}var P0;function _0(z,B){if(z.dev!==B.dev||z.ino!==B.ino)return!1;if(z.ino===0&&z.birthtimeMs!==B.birthtimeMs)return!1;return!0}var Vz=1000;function R0(z){return Wz({...z,now:Date.now})}async function Wz(z){let B=J0(z.path,z.name),K=U0(B,"owner.json"),Y=t(),J=z.now??Date.now,_=null,V=!1,N=!1,W,O,f=new Promise((G)=>{O=G});function y(G){try{let H=z.onRenewalTimer?.(G);if(H&&(typeof H==="object"||typeof H==="function")&&"then"in H&&typeof H.then==="function")Promise.resolve(H).catch(()=>{})}catch{}}function S(){if(!_)return;Nz(_),_=null,y("cancelled")}function j(G,H){if(W||V)return;W=Object.freeze({reason:G,expectedOwnerId:Y,...typeof H?.ownerId==="string"?{observedOwnerId:H.ownerId}:{},...typeof H?.expiresAt==="number"?{observedExpiresAt:H.expiresAt}:{}}),S(),O(W)}let b,E=null,U=`${B}.evicting`,q=U0(U,"owner.json"),d=t(),g=5000,s=8;function v(G){return X&&(p(G,[B],"create")||p(G,[U],"directory-create"))}async function F(){if(X)try{return JSON.parse(await L(B,()=>P(B,!0)))}catch(G){if(G.code!=="EISDIR"&&G.reason!=="wrong-kind")throw G;return await L(B,()=>w(B,"directory",!0)),JSON.parse(await L(K,()=>P(K,!0)))}try{return JSON.parse(await f0(B,"utf8"))}catch(G){if(G.code!=="EISDIR")throw G;return JSON.parse(await f0(K,"utf8"))}}async function o(){if(X){let Z=await F(),$=Number(Z?.expiresAt)-J();await H0(B,`${JSON.stringify({ownerId:Y,expiresAt:J()+z.ttlMs})}
|
|
2
|
+
`,{deadline:performance.now()+Math.max(0,$),beforeRename:async()=>{let D=await F();if(D?.ownerId!==Y||!(Number(D?.expiresAt)>J())||!await R())throw new i({target:z.path,name:z.name})}});return}let G=`${B}.${t()}.tmp`,H,Q=!1;try{H=await K0(G,"wx",384),Q=!0,await H.writeFile(`${JSON.stringify({ownerId:Y,expiresAt:J()+z.ttlMs})}
|
|
3
|
+
`,"utf8"),await H.chmod(384),await H.close(),H=void 0;let Z=await F();if(Z?.ownerId!==Y||!(Number(Z?.expiresAt)>J())||!await R())throw new i({target:z.path,name:z.name});await b0(G,B),Q=!1}finally{if(await H?.close().catch(()=>{}),Q)await c(G,{force:!0}).catch(()=>{})}}async function h(){let G=`${JSON.stringify({ownerId:Y,expiresAt:J()+z.ttlMs})}
|
|
4
|
+
`;if(X)await N0(B,G);else await Hz(B,G)}async function I(G){let H=G.code;if(H!=="EEXIST"&&H!=="EISDIR")return!1;if(X){if(z.onStep)await z.onStep("lease-contention-read-ready");try{if(H==="EISDIR")await L(B,()=>w(B,"directory",!0)),await L(K,()=>P(K,!0));else await F()}catch(Q){if(Q.code!=="ENOENT")throw Q}}return!0}async function A(){if(X)await X0(G0(B));try{return await h(),!0}catch(G){let H=G.code;if(await I(G))return!1;if(H==="ENOENT"){if(X)await X0(G0(B));else await O0(G0(B),{recursive:!0});try{return await h(),!0}catch(Q){if(await I(Q))return!1;throw Q}}throw G}}async function T(){await new Promise((G)=>setTimeout(G,Math.floor(Math.random()*4)))}async function C(G=!0){if(G&&z.onStep)await z.onStep("lock-read-ready");let H;try{H=await F()}catch(Z){if(Z instanceof n)return{status:"missing"};if(X&&Z.code!=="ENOENT")throw Z}let Q=Number(H?.expiresAt);if(Number.isFinite(Q)&&Q>J())return{status:"live"};if(typeof H?.ownerId==="string"&&Number.isFinite(Q))return{status:"stale",identity:{kind:"owner",ownerId:H.ownerId,expiresAt:Q}};try{let Z=await a(B),$=Number.isFinite(Q)?Q:Z.mtimeMs+z.ttlMs;if($>J())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:Z.dev,ino:Z.ino,mtimeMs:Z.mtimeMs,expiresAt:$}}}catch(Z){if(Z.code==="ENOENT"){if(z.onStep)await z.onStep("lock-missing");return{status:"missing"}}throw Z}}function x0(G,H){if(H.status!=="stale")return!1;let Q=H.identity;if(G.kind==="owner"&&Q.kind==="owner")return G.ownerId===Q.ownerId&&G.expiresAt===Q.expiresAt;return G.kind==="stat"&&Q.kind==="stat"&&G.dev===Q.dev&&G.ino===Q.ino&&G.mtimeMs===Q.mtimeMs&&G.expiresAt===Q.expiresAt}async function R(){try{return JSON.parse(await L(q,()=>P(q,X)))?.ownerId===d}catch(G){if(X&&G.code!=="ENOENT")throw G;return!1}}async function Y0(G){if(X)await u0(G,"remove",()=>c(G,{recursive:!0,force:!0}));else await c(G,{recursive:!0,force:!0}).catch(()=>{})}function r(G,H){if(!X||!(G instanceof M)||G.stage!=="remove"||G.path!==H)return!1;return B0(G)||G.win32Code===void 0&&G.reason===void 0&&(G.code==="EBUSY"||G.code==="EPERM")}async function Z0(G,H,Q=performance.now()+g+1000){let Z,$=5;while(await H()){try{await Y0(G);return}catch(x){if(!r(x,G))throw x;Z??=x}let D=Q-performance.now();if(D<=0)throw Z;if(await new Promise((x)=>setTimeout(x,Math.min($,D))),performance.now()>=Q)throw Z;$=Math.min($*2,50)}}async function $0(G){let H;await Z0(U,async()=>{if(!X)return R();let Q=await u(U).catch((Z)=>{if(Z.code!=="ENOENT")throw Z;return});if(!Q||H&&!_0(H,Q))return!1;if(await R())return H=Q,!0;if(!H)return!1;try{return await a(q),!1}catch(Z){if(Z.code!=="ENOENT")throw Z;return!0}},G)}async function a0(G,H){if(!G)return!1;let Q=!1;try{await Z0(U,async()=>{Q=!1;let Z=await u(U).catch(()=>{return});if(!Z||!_0(G,Z))return!1;Q=!0;try{return await a(q),!1}catch($){return $.code==="ENOENT"}},H)}catch{}return Q}async function D0(G){if(X)await g0(U);else await O0(U);let H;try{let Q=await u(U);H={dev:Q.dev,ino:Q.ino,birthtimeMs:Q.birthtimeMs}}catch{H=void 0}try{await P0?.beforeOwnerWrite?.(U,q);let Q=await P0?.failOwnerWrite?.(U,q);if(Q!==void 0)throw Q;let Z=`${JSON.stringify({ownerId:d,createdAt:J()})}
|
|
5
|
+
`;if(X)await N0(q,Z);else await m0(q,Z)}catch(Q){let Z=await a0(H,G);if(Uz(Q)&&!Z)return!1;try{await $0(G)}catch{}throw Q}if(z.onStep)await z.onStep("eviction-marker-acquired");return!0}async function j0(G){let H;try{H=await a(U)}catch($){if($.code==="ENOENT")return"missing";throw $}if(X)try{await L(U,()=>w(U,"directory",!0))}catch($){if($.code==="ENOENT")return"missing";throw $}if(H.mtimeMs+g>J()){let $=!0;try{await a(q)}catch(D){if(D.code==="ENOENT")$=!1;else return"fresh"}if($)return"fresh";if(H.mtimeMs+Vz>J())return"fresh"}if(z.onStep)await z.onStep("stale-marker-stat");let Q=`${U}.${t()}`;try{await b0(U,Q)}catch($){if($.code==="ENOENT")return"missing";throw $}if(z.onStep)await z.onStep("stale-marker-claimed");let Z=X?await u(Q):void 0;return await Z0(Q,async()=>{if(!Z)return!0;let $=await u(Q).catch((D)=>{if(D.code!=="ENOENT")throw D;return});return!!$&&_0(Z,$)},G),"recovered"}async function F0(G,H){try{if(!await D0(H))return!1}catch($){if($.code==="EEXIST"){if(X)try{await L(U,()=>w(U,"directory",!0)),await L(q,()=>P(q,!0))}catch(D){if(D.code!=="ENOENT")throw D}return!1}throw $}let Q=!1,Z;try{await G()}catch($){Q=!0,Z=$}try{await $0(H)}catch($){if((r(Z,B)||m(Z,[B,K,q]))&&(r($,U)||m($,[q])))throw Z;throw $}if(Q)throw Z;return!0}async function I0(){for(let G=0;G<s;G++){if(z.onStep)await z.onStep("relinquish-read");let H;try{H=await F()}catch(Q){if(X&&!(Q instanceof n))throw Q;return}if(H?.ownerId!==Y)return;try{await c(B,{recursive:!0,force:!0});return}catch(Q){if(X)throw Q;await T()}}}function A0(){if(!z.renew||V||W)return;let G=z.renewIntervalMs??Math.max(1000,Math.floor(z.ttlMs/3));if(_=Xz(()=>{_=null;let H=(async()=>{let Q=!V;try{if(!await F0(async()=>{let $=await F(),D=J();if(V||W){Q=!1;return}if($?.ownerId!==Y){j("taken-over",$),Q=!1;return}if(!(Number($?.expiresAt)>D)){j("expired",$),Q=!1;return}if(z.onStep)await z.onStep("renewal-owner-confirmed");if(V||W){Q=!1;return}if(!await R())return;if(z.onStep)await z.onStep("renewal-write-fenced");if(V||W){Q=!1;return}if(!await R())return;if(z.onStep)await z.onStep("renewal-write-ready");if(V||W){Q=!1;return}if(await o(),z.onStep)await z.onStep("renewal-write-finished");if(!await R()){j("marker-lost"),Q=!1,await I0();return}})&&z.onStep)await z.onStep("renewal-marker-unavailable")}catch(Z){if(X&&Z instanceof M&&!v(Z))b=Z,j("renewal-failed"),Q=!1;try{let $=await F();if($?.ownerId!==Y)j("taken-over",$);else if(!(Number($?.expiresAt)>J()))j("expired",$)}catch{j("renewal-failed")}}finally{if(z.onStep)try{await z.onStep("renewal-finished")}catch{}if(Q&&!V&&!W)A0()}})();E=H,H.finally(()=>{if(E===H)E=null})},G),"unref"in _)_.unref();y("scheduled")}function S0(){try{let G=z.onContended?.();if(G&&(typeof G==="object"||typeof G==="function")&&"then"in G&&typeof G.then==="function")Promise.resolve(G).catch(()=>{})}catch{}return null}let k=!1,e;try{k=await A()}catch(G){if(!v(G))throw G;e=G}if(!k)for(let G=0;G<s;G++)try{if(k=await A(),k)break;let H=await C();if(H.status==="live")return S0();if(H.status==="missing")continue;if(z.onStep)await z.onStep("stale-lock-observed");try{if(!await D0()){await T();continue}}catch(Q){if(Q.code!=="EEXIST")throw Q;if(await j0()==="fresh")return null;await T();continue}try{let Q=await C();if(Q.status==="live")return S0();if(!x0(H.identity,Q))continue;if(!await R())return null;if(z.onStep)await z.onStep("stale-lock-confirmed");if(!await R())return null;let Z=await C(!1);if(!x0(H.identity,Z))continue;if(await Y0(B),!await R())return null;if(z.onStep)await z.onStep("stale-lock-removed");if(k=await A(),!k)return null;if(z.onStep)await z.onStep("stale-lock-recreated");if(!await R())return await I0(),k=!1,null;break}finally{await $0()}}catch(H){if(!v(H))throw H;e??=H,await T()}if(!k){if(e)throw e;return null}return A0(),_z(B,z.ttlMs,J),{ownerId:Y,whenLost:()=>f,hasLost:()=>W!==void 0,assertOwned:async()=>{if(b)throw b;let G;try{let H=await F();if(G=H,!V&&!W&&H?.ownerId===Y&&Number(H?.expiresAt)>J())return;j(H?.ownerId!==Y?"taken-over":"expired",H)}catch(H){if(j("unreadable"),X&&H instanceof M)throw H}throw new i({target:z.path,name:z.name,expectedOwnerId:Y,...typeof G?.ownerId==="string"?{observedOwnerId:G.ownerId}:{},...typeof G?.expiresAt==="number"?{observedExpiresAt:G.expiresAt}:{}})},release:async(G)=>{if(X&&N)return;V=!0,S(),await E;let H=performance.now()+g+1000,Q=5,Z,$;for(;;){try{let x=!1,z0=await F0(async()=>{let T0;try{T0=await F()}catch(C0){if(X&&C0.code==="ENOENT"){x=!0;return}throw C0}if(T0?.ownerId!==Y){x=!0;return}if(z.onStep)await z.onStep("release-owner-confirmed");if(!await R())return;await Y0(B),x=!0},H);if($=void 0,z0){if(X&&!x)throw new M(B,"release-not-confirmed",{code:"EIO"});N=x;return}if(G?.aborted)return;await j0(H)}catch(x){let z0=X&&(v(x)||m(x,[B,K,U,q]));if(!r(x,B)&&!z0){if(X)throw x;return}if(z0)$??=x;else Z??=x}let D=H-performance.now();if(D<=0)break;if(await new Promise((x)=>setTimeout(x,Math.min(Q,D))),X&&performance.now()>=H)break;Q=Math.min(Q*2,50)}if(X)throw $??Z??new M(B,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{readFileSync as qz,realpathSync as xz,statSync as Dz,watch as jz}from"node:fs";import{readFile as Fz,stat as Iz}from"node:fs/promises";import{basename as c0,dirname as l0,join as Az,resolve as d0}from"node:path";import{clearTimeout as V0,setTimeout as h0}from"node:timers";function s0(z){let B=d0(z);if(X)return B;try{return xz(B)}catch{let K=l0(B);return K===B?B:Az(s0(K),c0(B))}}function p0(z,B){if(!z)return null;let K=`${z.dev}:${z.ino}:${z.mtimeMs}:${z.size}`;return B?`${K}:${z.ctimeMs}`:K}function iz(z,B,K={}){return n0(z,B,K,!1)}function az(z,B,K={}){return n0(z,B,K,!0)}function n0(z,B,K,Y){let J=globalThis,_=Symbol.for(Y?"cortexkit.common-auth.settings.watchers.v1":"cortexkit.common-auth.tui-prefs.watchers.v1"),V=J[_]??new Map;J[_]=V;let N=Y?d0(z):s0(z),W=V.get(N);if(W)return W.subscribe(B);let O=c0(N),f=X&&!Y?(I)=>P(I):K.fs?.readFile??((I)=>Fz(I,"utf8")),y=K.fs?.stat??Iz,S=null,j=null,b=null,E=null;if(Y||!X)try{let I=p0((K.fs?.statSync??Dz)(N),Y);E=(K.fs?.readFileSync??((A)=>qz(A,"utf8")))(N),b=I}catch{}let U=!1,q=new Set,d=()=>{for(let I of[...q]){if(!q.has(I))continue;try{I.notify()}catch{}}},g=Promise.resolve(),s=(I)=>{return g=g.then(async()=>{if(U)return;let A=p0(await y(N).catch(()=>null),Y);if(U)return;if(!I&&A===b)return;if(A===null){let C=b!==null;if(b=null,Y&&C)E=null,d();return}let T=await f(N).catch((C)=>{if(C instanceof M&&C.code!=="ENOENT")if(K.onError)K.onError(C);else process.emitWarning(C.message,C.name);return null});if(U)return;if(T===null)return;if(b=A,T===E)return;E=T,d()}),g},v=()=>{if(U)return;if(S)V0(S);S=h0(()=>{S=null,s(!0)},150)},F=null;try{F=(K.watchDirectory??jz)(l0(N),(I,A)=>{let T=A?.toString(),C=T===O||T?.startsWith(`${O}.`)&&T.endsWith(".tmp");if(T!=null&&!C)return;v()}),F.on("error",()=>{F?.close(),F=null})}catch{}let o=()=>{if(U||j)return;j=h0(()=>{if(j=null,U)return;s(!1).finally(o)},1000),j.unref()},h={subscribe:(I)=>{let A={notify:I};return q.add(A),()=>{if(!q.delete(A)||q.size>0)return;if(U=!0,S)V0(S);if(j)V0(j);if(F?.close(),V.get(N)===h)V.delete(N)}}};return V.set(N,h),o(),h.subscribe(B)}import{randomUUID as i0}from"node:crypto";import{mkdir as Sz,open as Q0,rename as Tz,rm as Cz}from"node:fs/promises";import{dirname as W0}from"node:path";class q0 extends Error{constructor(z){super("file or directory sync failed",{cause:z});this.name="AtomicSyncError"}}async function B1(z,B,K={}){await Mz(z,B,K)}async function Mz(z,B,K,Y){if(X)return H0(z,K.serialize?K.serialize(B):`${JSON.stringify(B,null,2)}
|
|
6
|
+
`,{beforeRename:K.beforeRename,stagePath:`${z}.${(K.stageName??i0)()}.tmp`,onRenamed:Y,durable:K.durable,durability:K.durability,onOutcome:K.onOutcome});await Sz(W0(z),{recursive:!0});let J=`${z}.${(K.stageName??i0)()}.tmp`,_,V=!1;try{if(_=await Q0(J,"wx",384),V=!0,await _.writeFile(K.serialize?K.serialize(B):`${JSON.stringify(B,null,2)}
|
|
7
|
+
`,"utf8"),await _.chmod(384),K.durable)try{await _.sync()}catch(N){throw new q0(N)}if(await _.close(),_=void 0,await K.beforeRename?.(),await Tz(J,z),V=!1,Y?.(),K.durable){let N=await Q0(W0(z),"r");try{await N.sync()}catch(W){throw new q0(W)}finally{await N.close()}}}finally{if(await _?.close().catch(()=>{}),V)await Cz(J,{force:!0}).catch(()=>{})}}async function G1(z){if(X){await w(z,"file");let Y=new M(z,"directory-sync-unsupported",{code:"ENOTSUP"});throw Y.published=!0,Y}let B=await Q0(z,"r");try{await B.sync()}finally{await B.close()}let K=await Q0(W0(z),"r");try{await K.sync()}finally{await K.close()}}var K1=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
|
|
8
|
+
export{q0 as Uf,B1 as Vf,Mz as Wf,G1 as Xf,R0 as Yf,J0 as Zf,L0 as _f,i as $f,r0 as ag,kz as bg,K1 as cg,iz as dg,az as eg};
|