tuxevil-rotator 4.1.0 → 4.2.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.
@@ -216,14 +216,16 @@ export async function fetchProviderQuota(
216
216
  const errorText = await response.text();
217
217
  if (!isCurrentGeneration()) return;
218
218
  ctx.log(
219
- `${account.config.email}: quota API returned ${response.status}, flagging account`,
219
+ `${account.config.email}: quota API returned ${response.status}, invalidating provider credential`,
220
220
  );
221
221
  ctx.reportQuotaPollFlag(account, response.status, errorText);
222
- ctx.markFlagged(
223
- account,
224
- `Quota API ${response.status}: ${errorText}`,
225
- { triggerProtectivePause: false },
226
- );
222
+ if (ctx.markProviderInvalid) {
223
+ ctx.markProviderInvalid(
224
+ account,
225
+ DEFAULT_PROVIDER,
226
+ `Quota API ${response.status}: ${errorText}`,
227
+ );
228
+ }
227
229
  }
228
230
  return;
229
231
  }
@@ -1,5 +1,9 @@
1
1
  import { logger, redactSensitive } from "../../logger.js";
2
2
  import { applyModelAlias, getEffortRoutingRule } from "../../types.js";
3
+ import {
4
+ CLAUDE_THINKING_BUDGET_EFFORTS,
5
+ CLAUDE_THINKING_DISABLED_EFFORT,
6
+ } from "../../effort-levels.js";
3
7
  import type { RequestBody } from "../../proxy.js";
4
8
  import {
5
9
  isRecord,
@@ -945,13 +949,55 @@ export function resolveEffortAliasModel(
945
949
  : null;
946
950
  }
947
951
 
952
+ function outputConfigEffort(value: unknown): string | undefined {
953
+ if (!isRecord(value)) return undefined;
954
+ const effort = value.effort;
955
+ return typeof effort === "string" && effort.trim() ? effort : undefined;
956
+ }
957
+
958
+ /**
959
+ * Effort level an Anthropic Messages request asks for, used to pick an effort
960
+ * alias's target. The latest per-message `output_config.effort` wins, then the
961
+ * top-level one. Without either, `thinking` decides: a `budget_tokens` maps to
962
+ * a level through CLAUDE_THINKING_BUDGET_EFFORTS, and thinking turned off asks
963
+ * for the lowest level. Adaptive or absent thinking asks for none, so the
964
+ * alias uses its default.
965
+ */
966
+ export function claudeRoutingEffort(
967
+ input: AnthropicMessagesRequest,
968
+ ): string | undefined {
969
+ const messages = Array.isArray(input.messages) ? input.messages : [];
970
+ for (let i = messages.length - 1; i >= 0; i--) {
971
+ const message: unknown = messages[i];
972
+ if (!isRecord(message) || message.role !== "system") continue;
973
+ const effort = outputConfigEffort(message.output_config);
974
+ if (effort) return effort;
975
+ }
976
+ const effort = outputConfigEffort(input.output_config);
977
+ if (effort) return effort;
978
+ const thinking = input.thinking;
979
+ if (!isRecord(thinking)) return undefined;
980
+ if (thinking.type === "disabled") return CLAUDE_THINKING_DISABLED_EFFORT;
981
+ const budget = thinking.budget_tokens;
982
+ if (thinking.type === "enabled" && typeof budget === "number" && Number.isFinite(budget)) {
983
+ return CLAUDE_THINKING_BUDGET_EFFORTS.find((bucket) => budget < bucket.below)?.effort;
984
+ }
985
+ return undefined;
986
+ }
987
+
948
988
  export function openAIToAntigravityBody(
949
989
  input: OpenAIChatCompletionRequest,
990
+ options: {
991
+ /** Picks an effort alias's target when the request has no reasoning_effort. */
992
+ routingEffort?: string;
993
+ } = {},
950
994
  ): RequestBody {
951
995
  const requestedModel = input.model;
952
996
  const effortTarget =
953
- resolveEffortAliasModel(requestedModel, input.reasoning_effort) ??
954
- requestedModel;
997
+ resolveEffortAliasModel(
998
+ requestedModel,
999
+ input.reasoning_effort ?? options.routingEffort,
1000
+ ) ?? requestedModel;
955
1001
 
956
1002
  const systemParts: string[] = [];
957
1003
  const conversationMessages = input.messages.filter((msg) => {
@@ -1501,18 +1547,21 @@ export function anthropicToAntigravityBody(
1501
1547
  const tools = convertAnthropicToolsToOpenAI(input.tools);
1502
1548
  const toolChoice = convertAnthropicToolChoice(input.tool_choice);
1503
1549
  const convertedMessages = convertAnthropicMessagesToOpenAI(input.messages);
1504
- return openAIToAntigravityBody({
1505
- model: input.model,
1506
- stream: input.stream,
1507
- temperature: input.temperature,
1508
- max_tokens: input.max_tokens,
1509
- tools,
1510
- tool_choice: toolChoice,
1511
- messages: [
1512
- ...(systemText ? [{ role: "system" as const, content: systemText }] : []),
1513
- ...convertedMessages,
1514
- ],
1515
- });
1550
+ return openAIToAntigravityBody(
1551
+ {
1552
+ model: input.model,
1553
+ stream: input.stream,
1554
+ temperature: input.temperature,
1555
+ max_tokens: input.max_tokens,
1556
+ tools,
1557
+ tool_choice: toolChoice,
1558
+ messages: [
1559
+ ...(systemText ? [{ role: "system" as const, content: systemText }] : []),
1560
+ ...convertedMessages,
1561
+ ],
1562
+ },
1563
+ { routingEffort: claudeRoutingEffort(input) },
1564
+ );
1516
1565
  }
1517
1566
 
1518
1567
  export function mapReasoningEffortToThinkingLevel(
@@ -50,14 +50,16 @@ export async function fetchProviderUsage(
50
50
  if (response.status === 401 || response.status === 403) {
51
51
  const errorText = await response.text().catch(() => "");
52
52
  ctx.log(
53
- `${account.config.email}: Ollama quota API returned ${response.status}, flagging account`,
53
+ `${account.config.email}: Ollama quota API returned ${response.status}, invalidating provider credential`,
54
54
  );
55
55
  ctx.reportQuotaPollFlag(account, response.status, errorText);
56
- ctx.markFlagged(
57
- account,
58
- `Ollama quota API ${response.status}: ${errorText}`,
59
- { triggerProtectivePause: false },
60
- );
56
+ if (ctx.markProviderInvalid) {
57
+ ctx.markProviderInvalid(
58
+ account,
59
+ "ollama",
60
+ `Ollama quota API ${response.status}: ${errorText}`,
61
+ );
62
+ }
61
63
  }
62
64
  return;
63
65
  }
@@ -14,7 +14,7 @@ export interface CodexModel {
14
14
  }
15
15
 
16
16
  // The base list contains OpenAI models published in the Codex model catalog.
17
- // Authenticated discovery can add provider-owned GPT-5 and GPT-6 IDs.
17
+ // Authenticated discovery can add versioned GPT IDs without a release allowlist.
18
18
  // The Codex /models endpoint can expose models from other ChatGPT-backed
19
19
  // providers (for example Claude), so model IDs alone must be filtered before
20
20
  // they influence routing.
@@ -24,7 +24,10 @@ const CODEX_CONTEXT_WINDOW = 1_050_000;
24
24
  // Hard cap to defend against `/models` upstream reporting absurd values for
25
25
  // discovered ids. 2M is comfortably above the published 1.05M baseline.
26
26
  const CODEX_DISCOVERED_MAX_CONTEXT_WINDOW = 2_000_000;
27
- const CODEX_DISCOVERED_ID_PATTERN = /^gpt-(?:5(?:\.\d+)?|6)(?:-[a-z0-9]+)+$/i;
27
+ // The upstream catalog requires a Codex protocol version, independent of our
28
+ // package version. Keep it configurable for deployments using a newer client.
29
+ const DEFAULT_CODEX_CLIENT_VERSION = "0.162.1";
30
+ const CODEX_DISCOVERED_ID_PATTERN = /^gpt-\d+(?:\.\d+)*(?:-[a-z0-9]+)+$/i;
28
31
  export const CODEX_BASE_MODELS: readonly CodexModel[] = [
29
32
  { id: "gpt-6-astra", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
30
33
  { id: "gpt-6-sol", contextWindow: CODEX_CONTEXT_WINDOW, reasoning: true, multimodal: true, tools: true, source: "allowlist" },
@@ -79,7 +82,7 @@ function parseModel(value: unknown): CodexModel | null {
79
82
  }
80
83
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
81
84
  const record = value as Record<string, unknown>;
82
- const id = record.id ?? record.model ?? record.name;
85
+ const id = record.id ?? record.slug ?? record.model ?? record.name;
83
86
  if (!isCodexProviderModelId(id)) return null;
84
87
  const contextWindow = [record.context_window, record.contextWindow, record.context_length]
85
88
  .find((candidate) => typeof candidate === "number" && Number.isFinite(candidate) && candidate > 0);
@@ -102,13 +105,15 @@ export async function fetchCodexCatalog(
102
105
  const base = codexBaseUrl();
103
106
  const endpoint = base.endsWith("/models") ? base : `${base}/models`;
104
107
  try {
108
+ const url = new URL(endpoint);
109
+ url.searchParams.set("client_version", process.env.CODEX_CLIENT_VERSION?.trim() || DEFAULT_CODEX_CLIENT_VERSION);
105
110
  const headers: Record<string, string> = {
106
111
  Authorization: `Bearer ${token}`,
107
112
  Accept: "application/json",
108
113
  };
109
114
  const accountId = getCodexAccountId(account.config);
110
115
  if (accountId) headers["chatgpt-account-id"] = accountId;
111
- const response = await fetch(endpoint, {
116
+ const response = await fetch(url.toString(), {
112
117
  headers,
113
118
  signal: signal ?? AbortSignal.timeout(8_000),
114
119
  dispatcher: getAccountProxyDispatcher(account, CODEX_PROVIDER_ID),
@@ -30,13 +30,15 @@ export async function fetchOpenCodeZenQuota(
30
30
  if (!response.ok) {
31
31
  if (response.status === 401 || response.status === 403) {
32
32
  const errorText = await response.text().catch(() => "");
33
- ctx.log(`${account.config.email}: OpenCode Zen API returned ${response.status}, flagging account`);
33
+ ctx.log(`${account.config.email}: OpenCode Zen API returned ${response.status}, invalidating provider credential`);
34
34
  ctx.reportQuotaPollFlag(account, response.status, errorText);
35
- ctx.markFlagged(
36
- account,
37
- `OpenCode Zen API ${response.status}: ${errorText}`,
38
- { triggerProtectivePause: false },
39
- );
35
+ if (ctx.markProviderInvalid) {
36
+ ctx.markProviderInvalid(
37
+ account,
38
+ OPENCODE_ZEN_PROVIDER_ID,
39
+ `OpenCode Zen API ${response.status}: ${errorText}`,
40
+ );
41
+ }
40
42
  }
41
43
  return;
42
44
  }
package/src/proxy.ts CHANGED
@@ -649,9 +649,12 @@ async function handleUpstreamAccountAction(
649
649
  uptimeSeconds: ctx401.uptimeSeconds,
650
650
  timeSinceLastFlagSeconds: -1,
651
651
  });
652
- rotator.markFlagged(
652
+ // Provider-scoped invalidation: only the failing provider is taken
653
+ // out of rotation; sibling providers on the same account remain active.
654
+ rotator.markProviderInvalid(
653
655
  account,
654
- `Account blocked (401): ${action.errorText.slice(0, 300)}`,
656
+ provider.id,
657
+ `Provider credential rejected (401): ${action.errorText.slice(0, 300)}`,
655
658
  );
656
659
  logRequestEnd(401, `endpoint=${action.endpoint}`);
657
660
  if (!options.canRetry) {
@@ -661,7 +664,7 @@ async function handleUpstreamAccountAction(
661
664
  if (!nextAccount) {
662
665
  return buildNoReplacementDecision(
663
666
  options,
664
- `no replacement account remained after ${label} was flagged with 401`,
667
+ `no replacement account remained after ${label} provider was invalidated with 401`,
665
668
  );
666
669
  }
667
670
  return { kind: "retry" };
@@ -691,7 +694,14 @@ async function handleUpstreamAccountAction(
691
694
  uptimeSeconds: ctx403.uptimeSeconds,
692
695
  timeSinceLastFlagSeconds: -1,
693
696
  });
694
- rotator.markFlagged(account, action.errorText.slice(0, 300));
697
+ // Provider-scoped invalidation: a 403 with flag patterns (suspended,
698
+ // banned, etc.) indicates the upstream provider rejected this credential.
699
+ // Only the failing provider is taken out; sibling providers remain active.
700
+ rotator.markProviderInvalid(
701
+ account,
702
+ provider.id,
703
+ `Provider flagged (403): ${action.errorText.slice(0, 300)}`,
704
+ );
695
705
  if (!options.canRetry) {
696
706
  return buildFailureDecision(options, 403, action.errorText);
697
707
  }
@@ -699,7 +709,7 @@ async function handleUpstreamAccountAction(
699
709
  if (!nextAccount) {
700
710
  return buildNoReplacementDecision(
701
711
  options,
702
- `no replacement account remained after ${label} was flagged with 403`,
712
+ `no replacement account remained after ${label} provider was invalidated with 403`,
703
713
  );
704
714
  }
705
715
  return { kind: "retry" };
package/src/rotator.ts CHANGED
@@ -78,6 +78,8 @@ import {
78
78
  type CatalogModel,
79
79
  } from "./model-catalog.js";
80
80
  import { getModelCatalogRevision } from "./model-catalog-revision.js";
81
+ import { applyConfigOverrides } from "./config-overrides.js";
82
+ import { planEffortRouteDelete, planEffortRouteSave, type EffortRoutePlan } from "./effort-routing.js";
81
83
  import { logger } from "./logger.js";
82
84
  import { getAccountProxyDispatcher } from "./providers/proxy-dispatcher.js";
83
85
  import {
@@ -85,6 +87,8 @@ import {
85
87
  getCodexModels,
86
88
  isCodexRequestModel,
87
89
  isCodexProviderModelId,
90
+ setDiscoveredCodexModels,
91
+ type CodexModel,
88
92
  } from "./providers/openai-codex/catalog.js";
89
93
  import { CodexOAuthError } from "./providers/openai-codex/oauth.js";
90
94
  import { CODEX_QUOTA_MODEL_KEY } from "./providers/openai-codex/quota.js";
@@ -283,6 +287,8 @@ export class AccountRotator {
283
287
  private codexModels = new Set<string>(getCodexModels().map((model) => model.id));
284
288
  private readonly usagePredictor = new UsagePredictor();
285
289
  private lastOllamaCatalogFetch = 0;
290
+ private lastCodexCatalogFetch = 0;
291
+ private codexCatalogFetch: Promise<void> | null = null;
286
292
 
287
293
  setOllamaModels(models: string[]): void {
288
294
  this.ollamaModels = new Set(models.map((m) => m.trim()).filter(Boolean));
@@ -369,18 +375,49 @@ export class AccountRotator {
369
375
  return [...this.codexModels];
370
376
  }
371
377
 
372
- async primeCodexCatalog(): Promise<void> {
373
- const account = this.accounts.find(
374
- (candidate) => hasCredential(candidate.config, "openai-codex") && !candidate.disabled && !candidate.flagged,
378
+ primeCodexCatalog(): Promise<void> {
379
+ return this.refreshCodexCatalogOnce(true);
380
+ }
381
+
382
+ private refreshCodexCatalogOnce(force = false): Promise<void> {
383
+ if (this.codexCatalogFetch) return this.codexCatalogFetch;
384
+ const now = Date.now();
385
+ if (!force && now - this.lastCodexCatalogFetch < TAGS_CACHE_TTL_MS) return Promise.resolve();
386
+ const accounts = this.accounts.filter(
387
+ (candidate) => hasCredential(candidate.config, "openai-codex") &&
388
+ !candidate.disabled && !candidate.flagged &&
389
+ !candidate.invalidProviders?.["openai-codex"] &&
390
+ !this.isProviderOffForAccount(candidate, "openai-codex"),
375
391
  );
376
- if (!account) return;
377
- try {
378
- await this.ensureValidTokenForProvider(account, "openai-codex");
379
- const models = await fetchCodexCatalog(account);
380
- this.setCodexModels(models.map((model) => model.id));
381
- } catch {
382
- // The verified base allowlist stays active when discovery is unavailable.
383
- }
392
+ if (accounts.length === 0) return Promise.resolve();
393
+ this.lastCodexCatalogFetch = now;
394
+ this.codexCatalogFetch = (async () => {
395
+ const merged = new Map<string, CodexModel>();
396
+ // Plans expose different catalogs. Query all eligible accounts, limiting
397
+ // concurrency so a large pool does not burst token refreshes or discovery.
398
+ for (let offset = 0; offset < accounts.length; offset += 4) {
399
+ const results = await Promise.allSettled(accounts.slice(offset, offset + 4).map(async (account) => {
400
+ await this.ensureValidTokenForProvider(account, "openai-codex");
401
+ return fetchCodexCatalog(account);
402
+ }));
403
+ for (const result of results) {
404
+ if (result.status !== "fulfilled") continue;
405
+ for (const model of result.value) {
406
+ // A restricted account's base fallback must not overwrite metadata
407
+ // discovered through another account with access to the model.
408
+ if (model.source === "discovered" || !merged.has(model.id)) merged.set(model.id, model);
409
+ }
410
+ }
411
+ }
412
+ if (merged.size > 0) {
413
+ const models = [...merged.values()];
414
+ setDiscoveredCodexModels(models.filter((model) => model.source === "discovered"));
415
+ this.setCodexModels(models.map((model) => model.id));
416
+ }
417
+ })().finally(() => {
418
+ this.codexCatalogFetch = null;
419
+ });
420
+ return this.codexCatalogFetch;
384
421
  }
385
422
 
386
423
  /** Fetch the Ollama Cloud catalog once at startup so provider-aware routing and /v1/models work before the first quota poll. */
@@ -1060,6 +1097,7 @@ export class AccountRotator {
1060
1097
 
1061
1098
  private async pollAllQuotasOnce(): Promise<void> {
1062
1099
  void this.refreshOllamaCatalogOnce().catch(() => {});
1100
+ void this.refreshCodexCatalogOnce().catch(() => {});
1063
1101
 
1064
1102
  const available = this.accounts.filter((a) => !a.disabled && !a.flagged);
1065
1103
  this.reconcileDynamicCatalog();
@@ -3544,6 +3582,33 @@ export class AccountRotator {
3544
3582
  return true;
3545
3583
  }
3546
3584
 
3585
+ /**
3586
+ * Create (`previousAlias` null), replace or rename an effort route from a
3587
+ * dashboard request body. Saved routes apply to new requests right away.
3588
+ */
3589
+ async saveEffortRoute(previousAlias: string | null, body: unknown): Promise<EffortRoutePlan> {
3590
+ const plan = planEffortRouteSave(this, previousAlias, body);
3591
+ if (plan.ok && (await this.updateModelSettings(plan.patch))) {
3592
+ applyConfigOverrides(this.config);
3593
+ this.log(
3594
+ previousAlias === null
3595
+ ? `Operator created effort model ${plan.alias}`
3596
+ : `Operator updated effort model ${previousAlias}${previousAlias === plan.alias ? "" : ` as ${plan.alias}`}`,
3597
+ "warn",
3598
+ );
3599
+ }
3600
+ return plan;
3601
+ }
3602
+
3603
+ async deleteEffortRoute(alias: string): Promise<EffortRoutePlan> {
3604
+ const plan = planEffortRouteDelete(this.config, alias);
3605
+ if (plan.ok && (await this.updateModelSettings(plan.patch))) {
3606
+ applyConfigOverrides(this.config);
3607
+ this.log(`Operator deleted effort model ${plan.alias}`, "warn");
3608
+ }
3609
+ return plan;
3610
+ }
3611
+
3547
3612
  /** Re-read the Ollama and Codex model lists now instead of on the next poll. */
3548
3613
  async refreshModelCatalogs(): Promise<void> {
3549
3614
  this.lastOllamaCatalogFetch = 0;
@@ -3647,13 +3712,13 @@ export class AccountRotator {
3647
3712
  await this.ensureValidTokenForProvider(account, adapter.id);
3648
3713
  } catch (err) {
3649
3714
  const msg = err instanceof Error ? err.message : String(err);
3650
- if (msg.startsWith("Token refresh failed") || msg.startsWith("Token refresh error:")) {
3651
- this.markError(account, msg);
3652
- throw err;
3653
- }
3654
- const wrapped = `Token refresh error: ${msg}`;
3655
- this.markError(account, wrapped);
3656
- throw new Error(wrapped, { cause: err });
3715
+ // Provider-scoped invalidation: token refresh failures only affect the
3716
+ // provider whose token could not be refreshed, not the whole account.
3717
+ const reason = msg.startsWith("Token refresh failed") || msg.startsWith("Token refresh error:")
3718
+ ? msg
3719
+ : `Token refresh error: ${msg}`;
3720
+ this.markProviderInvalid(account, adapter.id, reason);
3721
+ throw msg === reason ? err : new Error(reason, { cause: err });
3657
3722
  }
3658
3723
  }
3659
3724
 
@@ -4422,6 +4487,7 @@ export class AccountRotator {
4422
4487
  const mergedAccounts = normalized.accounts.map(matchAndReuseAccount);
4423
4488
  this.config = { ...normalized, accounts: mergedAccounts.map((account) => account.config) };
4424
4489
  this.accounts = mergedAccounts;
4490
+ applyConfigOverrides(this.config);
4425
4491
  this.reconcileDynamicCatalog();
4426
4492
  this.requestWaiterDrain();
4427
4493
  await saveAccountsConfig(this.config);
@@ -5076,8 +5142,11 @@ export class AccountRotator {
5076
5142
  if (target.providerId === "openai-codex") {
5077
5143
  this.markProviderInvalid(account, target.providerId, failure.description);
5078
5144
  } else if (failure.accountEnforcement) {
5145
+ // Provider-scoped invalidation: even with account-enforcement language
5146
+ // in the response, only the specific provider credential is invalidated.
5147
+ // Sibling providers on the same account remain routable.
5079
5148
  this.reportQuotaPollFlag(account, response.status, errorText, upstreamModel);
5080
- this.markFlagged(account, failure.description, { triggerProtectivePause: false });
5149
+ this.markProviderInvalid(account, target.providerId, failure.description);
5081
5150
  } else {
5082
5151
  account.lastError = failure.description;
5083
5152
  this.kickstartDeniedUntil.set(denialKey, Date.now() + 30 * 60 * 1000);
package/src/types.ts CHANGED
@@ -502,6 +502,10 @@ export function resolveDisplayModelKey(
502
502
  ) {
503
503
  return "gemini-3.7-flash-tiered";
504
504
  }
505
+ // Gemini 3.5 Flash Lite is its own model, not a Gemini 3 Flash variant.
506
+ if (lower.includes("gemini") && lower.includes("3.5") && lower.includes("flash-lite")) {
507
+ return "gemini-3.5-flash-lite";
508
+ }
505
509
  // Flash
506
510
  if (lower.includes("gemini") && lower.includes("flash"))
507
511
  return "gemini-3-flash";
package/src/validators.ts CHANGED
@@ -53,7 +53,8 @@ function isProviderModelKey(value: string): boolean {
53
53
  return slash > 0 && slash < value.length - 1 && PROVIDER_ORDER.includes(value.slice(0, slash));
54
54
  }
55
55
 
56
- function isKnownNonGoogleModel(model: string): boolean {
56
+ /** Whether a static Codex, OpenCode Zen or Ollama catalog ID claims this model id. */
57
+ export function isKnownNonGoogleModel(model: string): boolean {
57
58
  const trimmed = model.trim();
58
59
  if (!trimmed) return false;
59
60
  const lower = trimmed.toLowerCase();
package/src/web/app.tsx CHANGED
@@ -710,7 +710,8 @@ function LoginScreen(): JSX.Element {
710
710
  if (params.has("auth")) {
711
711
  params.delete("auth");
712
712
  const rest = params.toString();
713
- window.history.replaceState(null, "", window.location.pathname + (rest ? `?${rest}` : ""));
713
+ // Keep the router's state: it records the entry's position in history.
714
+ window.history.replaceState(window.history.state, "", window.location.pathname + (rest ? `?${rest}` : ""));
714
715
  }
715
716
  }, []);
716
717
 
@@ -76,23 +76,35 @@ export function Drawer({
76
76
  onClose,
77
77
  label,
78
78
  children,
79
+ confirmClose,
79
80
  }: {
80
81
  open: boolean;
81
82
  onClose: () => void;
82
83
  label: string;
83
84
  children?: ComponentChildren;
85
+ /** Asked before Escape or a backdrop click closes the drawer; false keeps it open. */
86
+ confirmClose?: () => boolean | Promise<boolean>;
84
87
  }): JSX.Element {
85
88
  const ref = useNativeDialog(open);
89
+ const requestClose = async () => {
90
+ if (confirmClose && !(await confirmClose())) return;
91
+ onClose();
92
+ };
86
93
  return (
87
94
  <dialog
88
95
  ref={ref}
89
96
  class="drawer"
90
97
  aria-label={label}
98
+ onCancel={(event) => {
99
+ if (!confirmClose) return;
100
+ event.preventDefault();
101
+ void requestClose();
102
+ }}
91
103
  onClose={() => {
92
104
  if (open) onClose();
93
105
  }}
94
106
  onClick={(event) => {
95
- if (event.target === ref.current) onClose();
107
+ if (event.target === ref.current) void requestClose();
96
108
  }}
97
109
  >
98
110
  {open && <div class="drawer-inner">{children}</div>}