atlarix 15.13.3 → 15.14.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.
@@ -12403,6 +12403,7 @@ __export(texts_exports, {
12403
12403
  CORE_TIER_NEWER_BUILD: () => CORE_TIER_NEWER_BUILD,
12404
12404
  SAFETY_FILTER_BLOCKED_MESSAGE: () => SAFETY_FILTER_BLOCKED_MESSAGE,
12405
12405
  UserFacingRefusal: () => UserFacingRefusal,
12406
+ byokLimitKind: () => byokLimitKind,
12406
12407
  byokLimitUserMessage: () => byokLimitUserMessage,
12407
12408
  modelFailureUserMessage: () => modelFailureUserMessage
12408
12409
  });
@@ -12419,19 +12420,25 @@ function providerSaid(reason) {
12419
12420
  const word = cut.lastIndexOf(" ");
12420
12421
  return `${cut.slice(0, word > 80 ? word : 200)}\u2026`;
12421
12422
  }
12422
- function byokLimitUserMessage(reason, providerId) {
12423
+ function byokLimitKind(reason) {
12424
+ if (CREDIT_RE.test(reason)) return "credit";
12425
+ if (KEY_RE.test(reason)) return "key";
12426
+ if (RATE_RE.test(reason)) return "rate";
12427
+ return null;
12428
+ }
12429
+ function byokLimitUserMessage(reason, providerId, status) {
12423
12430
  const who = providerId ? `Your ${providerId} account` : "Your provider account";
12424
12431
  const said = providerSaid(reason);
12425
- if (CREDIT_RE.test(reason)) {
12426
- return `${who} ${BYOK_CREDIT_MARKER}, so it refused this request. Add credit on the provider's billing page, or switch model: Atlarix Auto is free. (It said: "${said}")`;
12427
- }
12428
- if (KEY_RE.test(reason)) {
12429
- return `${providerId ?? "The provider"} ${BYOK_KEY_MARKER}. Check the key (it may have been revoked or mistyped), or switch model. (It said: "${said}")`;
12430
- }
12431
- if (RATE_RE.test(reason)) {
12432
- return `${providerId ?? "The provider"} ${BYOK_RATE_MARKER} right now. Wait a moment and resend, or switch model. (It said: "${said}")`;
12432
+ switch (byokLimitKind(reason) ?? (status === 429 ? "rate" : null)) {
12433
+ case "credit":
12434
+ return `${who} ${BYOK_CREDIT_MARKER}, so it refused this request. Add credit on the provider's billing page, or switch model: Atlarix Auto is free. (It said: "${said}")`;
12435
+ case "key":
12436
+ return `${providerId ?? "The provider"} ${BYOK_KEY_MARKER}. Check the key (it may have been revoked or mistyped), or switch model. (It said: "${said}")`;
12437
+ case "rate":
12438
+ return `${providerId ?? "The provider"} ${BYOK_RATE_MARKER} right now. Wait a moment and resend, or switch model. (It said: "${said}")`;
12439
+ default:
12440
+ return null;
12433
12441
  }
12434
- return null;
12435
12442
  }
12436
12443
  function modelFailureUserMessage(reason) {
12437
12444
  if (reason.includes(CORE_TIER_NEWER_BUILD)) return CORE_TIER_NEWER_BUILD;
@@ -12569,9 +12576,6 @@ function coreRateLimitedMessage(retryAfterSeconds) {
12569
12576
  const when = s3 == null ? "in a moment" : s3 < 60 ? `in ${s3}s` : `in ${formatResetsIn(Date.now() + s3 * 1e3)}`;
12570
12577
  return `${CORE_RATE_LIMIT_MARKER}. Try again ${when}, or pick another model.`;
12571
12578
  }
12572
- function autoConsentRequiredUserMessage() {
12573
- return `Atlarix Auto is free once you OK sharing its prompts with the AI providers that serve it, to improve their models. Review and accept to keep going. ${UPGRADE_LINE}`;
12574
- }
12575
12579
  function coreUnavailableUserMessage() {
12576
12580
  return "This Atlarix Core model is temporarily unavailable. Atlarix has been informed and is working on it \u2014 we apologise for the inconvenience. In the meantime, pick another Core model above, or add your own API key in Settings.";
12577
12581
  }
@@ -12634,7 +12638,6 @@ var init_billing_copy = __esm({
12634
12638
  // src/ipc/shared/compass_constants.ts
12635
12639
  var compass_constants_exports = {};
12636
12640
  __export(compass_constants_exports, {
12637
- ATLARIX_AUTO_CONSENT_VERSION: () => ATLARIX_AUTO_CONSENT_VERSION,
12638
12641
  COMPASS_PROVIDER_ID: () => COMPASS_PROVIDER_ID,
12639
12642
  COMPASS_REACHABILITY_ERROR: () => COMPASS_REACHABILITY_ERROR,
12640
12643
  CORE_TIER_1: () => CORE_TIER_1,
@@ -12650,8 +12653,6 @@ __export(compass_constants_exports, {
12650
12653
  DEFAULT_PAID_CORE_TIER: () => DEFAULT_PAID_CORE_TIER,
12651
12654
  __setDevCoreKeyProvider: () => __setDevCoreKeyProvider,
12652
12655
  accountBannedUserMessage: () => accountBannedUserMessage,
12653
- autoConsentAccepted: () => autoConsentAccepted,
12654
- autoConsentHeader: () => autoConsentHeader,
12655
12656
  compassAuthExpiredUserMessage: () => compassAuthExpiredUserMessage,
12656
12657
  compassBadRequestUserMessage: () => compassBadRequestUserMessage,
12657
12658
  compassExhaustedUserMessage: () => compassExhaustedUserMessage,
@@ -12672,16 +12673,6 @@ __export(compass_constants_exports, {
12672
12673
  normalizeCoreTierId: () => normalizeCoreTierId,
12673
12674
  resolveConfiguredCoreTier: () => resolveConfiguredCoreTier
12674
12675
  });
12675
- function autoConsentAccepted(now2 = /* @__PURE__ */ new Date()) {
12676
- return {
12677
- atlarixAutoConsentAt: now2.toISOString(),
12678
- atlarixAutoConsentVersion: ATLARIX_AUTO_CONSENT_VERSION
12679
- };
12680
- }
12681
- function autoConsentHeader(settings) {
12682
- if (!settings.atlarixAutoConsentAt) return null;
12683
- return (settings.atlarixAutoConsentVersion ?? 1) >= 2 ? "2" : "1";
12684
- }
12685
12676
  function normalizeCoreTierId(internalTierId) {
12686
12677
  return LEGACY_COMPASS_TIER_ALIASES[internalTierId] ?? internalTierId;
12687
12678
  }
@@ -12832,7 +12823,7 @@ function isCompassBuildConfigured() {
12832
12823
  function compassExhaustedUserMessage(_tier) {
12833
12824
  return coreExhaustedUserMessage();
12834
12825
  }
12835
- var COMPASS_PROVIDER_ID, CORE_TIER_1, CORE_TIER_2, CORE_TIER_3, CORE_TIER_4, CORE_TIER_5, CORE_TIER_6, CORE_TIER_AUTO, CORE_TIER_ZENITH, ATLARIX_AUTO_CONSENT_VERSION, CORE_TIER_ORDER, LEGACY_COMPASS_TIER_ALIASES, EMPTY_SLOT_SENTINELS, devCoreKeyProvider, getOpenRouterModelIdForCoreTier, DEFAULT_CORE_TIER_ORDER, DEFAULT_PAID_CORE_TIER, DEFAULT_NEW_USER_CORE_TIER;
12826
+ var COMPASS_PROVIDER_ID, CORE_TIER_1, CORE_TIER_2, CORE_TIER_3, CORE_TIER_4, CORE_TIER_5, CORE_TIER_6, CORE_TIER_AUTO, CORE_TIER_ZENITH, CORE_TIER_ORDER, LEGACY_COMPASS_TIER_ALIASES, EMPTY_SLOT_SENTINELS, devCoreKeyProvider, getOpenRouterModelIdForCoreTier, DEFAULT_CORE_TIER_ORDER, DEFAULT_PAID_CORE_TIER, DEFAULT_NEW_USER_CORE_TIER;
12836
12827
  var init_compass_constants = __esm({
12837
12828
  "src/ipc/shared/compass_constants.ts"() {
12838
12829
  init_format_openrouter_model_label();
@@ -12850,7 +12841,6 @@ var init_compass_constants = __esm({
12850
12841
  CORE_TIER_6 = "core-6";
12851
12842
  CORE_TIER_AUTO = "core-auto";
12852
12843
  CORE_TIER_ZENITH = "core-zenith";
12853
- ATLARIX_AUTO_CONSENT_VERSION = 2;
12854
12844
  CORE_TIER_ORDER = [
12855
12845
  CORE_TIER_1,
12856
12846
  CORE_TIER_2,
@@ -28180,25 +28170,6 @@ var init_schemas3 = __esm({
28180
28170
  */
28181
28171
  telemetryConsent: external_exports.enum(["opted_in", "opted_out", "unset"]).optional(),
28182
28172
  telemetryUserId: external_exports.string().optional(),
28183
- /**
28184
- * When the user accepted Atlarix Auto's terms (ISO time), or absent.
28185
- *
28186
- * Auto is served from OpenAI's complimentary tokens and from free models on
28187
- * OpenRouter and Requesty, all of which exist only for traffic shared with
28188
- * the providers to improve their models — so a user must say yes to that
28189
- * ONCE, knowingly, before their first Auto turn. Checked in MAIN at dispatch
28190
- * (get_model_client), not only in the picker: a saved selection or a synced
28191
- * setting must never send a prompt the user did not agree to share.
28192
- */
28193
- atlarixAutoConsentAt: external_exports.string().optional(),
28194
- /**
28195
- * Which wording that yes was given to. 1 (or absent) = "shared with OpenAI";
28196
- * 2 = "shared with the AI providers that serve it". The proxy offers the free
28197
- * gateways only on 2, so a v1 yes keeps the OpenAI-only Auto it agreed to.
28198
- */
28199
- atlarixAutoConsentVersion: external_exports.number().int().optional(),
28200
- /** When a v1 user was shown the v2 wording once (accepted or not), so it is asked only once. */
28201
- atlarixAutoConsentV2AskedAt: external_exports.string().optional(),
28202
28173
  /**
28203
28174
  * The MCP servers every workspace offers in the composer's menu, by registry
28204
28175
  * name. Absent = the Verified five. Changed from the marketplace or by the
@@ -32966,7 +32937,8 @@ __export(work_mode_exports, {
32966
32937
  resolveEffectiveWorkMode: () => resolveEffectiveWorkMode,
32967
32938
  resolveSelectedWorkMode: () => resolveSelectedWorkMode,
32968
32939
  settingsPatchForWorkMode: () => settingsPatchForWorkMode,
32969
- toolExecutionChatMode: () => toolExecutionChatMode
32940
+ toolExecutionChatMode: () => toolExecutionChatMode,
32941
+ workModeChosenInAnswers: () => workModeChosenInAnswers
32970
32942
  });
32971
32943
  function chatModeForWorkMode(mode) {
32972
32944
  return mode === "build" ? "build" : "ask";
@@ -33019,9 +32991,18 @@ function labelForWorkMode(mode) {
33019
32991
  return "Review";
33020
32992
  }
33021
32993
  }
33022
- var BUILD_FROM_PLAN_PROMPT;
32994
+ function workModeChosenInAnswers(answers) {
32995
+ const picked = /* @__PURE__ */ new Set();
32996
+ for (const a2 of answers) {
32997
+ const m3 = SWITCH_ANSWER.exec(a2 ?? "");
32998
+ if (m3) picked.add(m3[1].toLowerCase());
32999
+ }
33000
+ return picked.size === 1 ? [...picked][0] : null;
33001
+ }
33002
+ var SWITCH_ANSWER, BUILD_FROM_PLAN_PROMPT;
33023
33003
  var init_work_mode = __esm({
33024
33004
  "src/lib/work-mode.ts"() {
33005
+ SWITCH_ANSWER = /^\s*(?:yes\b[\s,.!:-]*)?(?:please\s+)?switch\s+to\s+(?:the\s+)?(build|debug)(?:\s+mode)?(?:\s*\(recommended\))?\s*[.!]?\s*$/i;
33025
33006
  BUILD_FROM_PLAN_PROMPT = "Implement the plan in the Plan panel step by step. Follow the phases and items in order.";
33026
33007
  }
33027
33008
  });
@@ -97512,6 +97493,7 @@ __export(supabase_client_exports, {
97512
97493
  SUPABASE_REQUEST_TIMEOUT_MS: () => SUPABASE_REQUEST_TIMEOUT_MS,
97513
97494
  __resetUserRowForTests: () => __resetUserRowForTests,
97514
97495
  cancelPendingOAuthTimeout: () => cancelPendingOAuthTimeout,
97496
+ cancelSignInFlow: () => cancelSignInFlow,
97515
97497
  fetchPlanSnapshot: () => fetchPlanSnapshot,
97516
97498
  fetchWithTimeout: () => fetchWithTimeout,
97517
97499
  getEffectiveTier: () => getEffectiveTier,
@@ -97578,11 +97560,11 @@ function getSupabaseClient() {
97578
97560
  function markAuthFlowStarted() {
97579
97561
  _authFlowStartedAt = Date.now();
97580
97562
  }
97581
- function consumeActiveAuthFlow() {
97563
+ function consumeActiveAuthFlow(maxAgeMs) {
97582
97564
  const startedAt = _authFlowStartedAt;
97583
97565
  _authFlowStartedAt = null;
97584
- if (startedAt == null) return false;
97585
- return Date.now() - startedAt <= AUTH_FLOW_MAX_AGE_MS;
97566
+ if (startedAt == null) return "none";
97567
+ return Date.now() - startedAt <= maxAgeMs ? "active" : "expired";
97586
97568
  }
97587
97569
  function cancelPendingOAuthTimeout() {
97588
97570
  if (_oauthTimeoutHandle !== null) {
@@ -97593,7 +97575,12 @@ function cancelPendingOAuthTimeout() {
97593
97575
  );
97594
97576
  }
97595
97577
  }
97596
- async function openSignInUrl(url2, fallbackAfterMs = 6e4) {
97578
+ function cancelSignInFlow() {
97579
+ cancelPendingOAuthTimeout();
97580
+ if (_pendingAuthState === null) _authFlowStartedAt = null;
97581
+ }
97582
+ async function openSignInUrl(url2, method = "oauth") {
97583
+ const fallbackAfterMs = method === "email" ? 18e4 : 6e4;
97597
97584
  cancelPendingOAuthTimeout();
97598
97585
  markAuthFlowStarted();
97599
97586
  logger15.log(`[Supabase] Opening OAuth URL in browser`);
@@ -97615,8 +97602,8 @@ async function openSignInUrl(url2, fallbackAfterMs = 6e4) {
97615
97602
  const linuxCommands = process.platform === "linux" ? "\n\nTo register the deep link handler on Linux, run in Terminal:\n xdg-mime default atlarix.desktop x-scheme-handler/atlarix\n update-desktop-database ~/.local/share/applications\n\nThen try signing in again." : "";
97616
97603
  const { response } = await dialog.showMessageBox({
97617
97604
  type: "info",
97618
- title: "Sign-in not completing?",
97619
- message: `Atlarix has been waiting ${fallbackAfterMs / 1e3} seconds for the sign-in to come back.
97605
+ title: method === "email" ? "Still signing in?" : "Sign-in not completing?",
97606
+ message: method === "email" ? "Finish signing in from your browser. If it already says you're done, open the link below." : `Atlarix has been waiting ${fallbackAfterMs / 1e3} seconds for the sign-in to come back.
97620
97607
 
97621
97608
  The deep link handler may not be registered on your system.`,
97622
97609
  detail: `Sign-in URL (open this in your browser if the redirect didn't work):
@@ -97628,10 +97615,10 @@ ${oauthUrlForFallback}${linuxCommands}`,
97628
97615
  if (response === 0) {
97629
97616
  clipboard.writeText(oauthUrlForFallback);
97630
97617
  logger15.log(
97631
- "[Supabase] OAuth URL copied via 60s inbound timeout fallback"
97618
+ "[Supabase] OAuth URL copied via inbound timeout fallback"
97632
97619
  );
97633
97620
  }
97634
- }, 6e4);
97621
+ }, fallbackAfterMs);
97635
97622
  }
97636
97623
  if (!browserOpened && process.platform === "linux") {
97637
97624
  logger15.warn(
@@ -97660,7 +97647,7 @@ async function startEmailSignIn() {
97660
97647
  const url2 = `${EMAIL_SIGN_IN_URL}?client=desktop&state=${state2}`;
97661
97648
  logger15.log("[Supabase] Starting email sign-in via atlarix.dev");
97662
97649
  try {
97663
- await openSignInUrl(url2, 18e4);
97650
+ await openSignInUrl(url2, "email");
97664
97651
  return { error: null };
97665
97652
  } catch (err2) {
97666
97653
  _pendingAuthState = null;
@@ -97712,7 +97699,15 @@ async function handleAuthCallback(url2) {
97712
97699
  try {
97713
97700
  const supabase = getSupabaseClient();
97714
97701
  logger15.log(`[Supabase] Handling auth callback`);
97715
- if (!consumeActiveAuthFlow()) {
97702
+ const urlObj = new URL(url2);
97703
+ const hashParams = new URLSearchParams(urlObj.hash.substring(1));
97704
+ const expectedState = _pendingAuthState;
97705
+ _pendingAuthState = null;
97706
+ const stateMatches = expectedState !== null && hashParams.get("state") === expectedState;
97707
+ const flow = consumeActiveAuthFlow(
97708
+ stateMatches ? EMAIL_AUTH_FLOW_MAX_AGE_MS : AUTH_FLOW_MAX_AGE_MS
97709
+ );
97710
+ if (flow === "none") {
97716
97711
  logger15.warn(
97717
97712
  "[Supabase] Rejected auth callback \u2014 no sign-in flow was in progress (possible CSRF)."
97718
97713
  );
@@ -97724,10 +97719,14 @@ async function handleAuthCallback(url2) {
97724
97719
  )
97725
97720
  };
97726
97721
  }
97727
- const urlObj = new URL(url2);
97728
- const hashParams = new URLSearchParams(urlObj.hash.substring(1));
97729
- const expectedState = _pendingAuthState;
97730
- _pendingAuthState = null;
97722
+ if (flow === "expired") {
97723
+ logger15.warn("[Supabase] Rejected auth callback \u2014 sign-in flow expired.");
97724
+ return {
97725
+ session: null,
97726
+ user: null,
97727
+ error: new Error("That sign-in took too long. Start signing in again.")
97728
+ };
97729
+ }
97731
97730
  if (expectedState !== null && hashParams.get("state") !== expectedState) {
97732
97731
  logger15.warn("[Supabase] Rejected auth callback \u2014 state mismatch.");
97733
97732
  return {
@@ -98108,7 +98107,7 @@ async function fetchPlanSnapshot(userEmail, fresh = true) {
98108
98107
  return null;
98109
98108
  }
98110
98109
  }
98111
- var import_electron_log17, logger15, DEEP_LINK_PROTOCOL, AUTH_CALLBACK_PATH, AUTH_CALLBACK_URL, supabaseClient, fileStorage, SUPABASE_REQUEST_TIMEOUT_MS, _oauthTimeoutHandle, _authFlowStartedAt, AUTH_FLOW_MAX_AGE_MS, EMAIL_SIGN_IN_URL, _pendingAuthState, sleep4, USER_ROW_SELECT, _userRow, _userRowInFlight, PLAN_ROW_SELECT_BASE, PLAN_ROW_SELECT_WITH_VARIANT, EFFECTIVE_TIER_TTL_MS, _tierCache, _subDetailCache;
98110
+ var import_electron_log17, logger15, DEEP_LINK_PROTOCOL, AUTH_CALLBACK_PATH, AUTH_CALLBACK_URL, supabaseClient, fileStorage, SUPABASE_REQUEST_TIMEOUT_MS, _oauthTimeoutHandle, _authFlowStartedAt, AUTH_FLOW_MAX_AGE_MS, EMAIL_AUTH_FLOW_MAX_AGE_MS, EMAIL_SIGN_IN_URL, _pendingAuthState, sleep4, USER_ROW_SELECT, _userRow, _userRowInFlight, PLAN_ROW_SELECT_BASE, PLAN_ROW_SELECT_WITH_VARIANT, EFFECTIVE_TIER_TTL_MS, _tierCache, _subDetailCache;
98112
98111
  var init_supabase_client = __esm({
98113
98112
  "src/lib/auth/supabase-client.ts"() {
98114
98113
  init_dist13();
@@ -98126,6 +98125,7 @@ var init_supabase_client = __esm({
98126
98125
  _oauthTimeoutHandle = null;
98127
98126
  _authFlowStartedAt = null;
98128
98127
  AUTH_FLOW_MAX_AGE_MS = 10 * 6e4;
98128
+ EMAIL_AUTH_FLOW_MAX_AGE_MS = 60 * 6e4;
98129
98129
  EMAIL_SIGN_IN_URL = "https://atlarix.dev/auth/app";
98130
98130
  _pendingAuthState = null;
98131
98131
  sleep4 = (ms2) => new Promise((r3) => setTimeout(r3, ms2));
@@ -98143,6 +98143,7 @@ var init_supabase_client = __esm({
98143
98143
  // src/lib/context/auto-context-window.ts
98144
98144
  var auto_context_window_exports = {};
98145
98145
  __export(auto_context_window_exports, {
98146
+ FREE_AUTO_WORKING_WINDOW: () => FREE_AUTO_WORKING_WINDOW,
98146
98147
  __resetAutoBilling: () => __resetAutoBilling,
98147
98148
  __setAccountForTests: () => __setAccountForTests,
98148
98149
  autoContextWindow: () => autoContextWindow,
@@ -98203,12 +98204,7 @@ function __resetAutoBilling(account = "test-account") {
98203
98204
  loaded = true;
98204
98205
  accountOverride = account;
98205
98206
  }
98206
- async function autoContextWindow() {
98207
- loadOnce();
98208
- const auto = getCoreAuto();
98209
- const account = await currentAccount();
98210
- const billing = account ? byAccount[account] : void 0;
98211
- const models = billing === "paid" ? auto?.paidModels : auto?.freeModels ?? auto?.paidModels;
98207
+ async function smallestWindow(models) {
98212
98208
  if (!models?.length) return null;
98213
98209
  const { getModelsDevLimits: getModelsDevLimits2 } = await Promise.resolve().then(() => (init_models_dev(), models_dev_exports));
98214
98210
  let min3 = null;
@@ -98219,13 +98215,25 @@ async function autoContextWindow() {
98219
98215
  }
98220
98216
  return min3;
98221
98217
  }
98222
- var byAccount, loaded, accountOverride;
98218
+ async function autoContextWindow() {
98219
+ loadOnce();
98220
+ const auto = getCoreAuto();
98221
+ const account = await currentAccount();
98222
+ const billing = account ? byAccount[account] : void 0;
98223
+ const paid = billing === "paid";
98224
+ const min3 = await smallestWindow(paid ? auto?.paidModels : auto?.freeModels ?? auto?.paidModels);
98225
+ if (paid || !auto) return min3;
98226
+ const cap2 = auto.freeWorkingWindowTokens ?? FREE_AUTO_WORKING_WINDOW;
98227
+ return min3 == null ? cap2 : Math.min(min3, cap2);
98228
+ }
98229
+ var byAccount, loaded, accountOverride, FREE_AUTO_WORKING_WINDOW;
98223
98230
  var init_auto_context_window = __esm({
98224
98231
  "src/lib/context/auto-context-window.ts"() {
98225
98232
  init_core_model_override_store();
98226
98233
  init_paths();
98227
98234
  byAccount = {};
98228
98235
  loaded = false;
98236
+ FREE_AUTO_WORKING_WINDOW = 2e5;
98229
98237
  }
98230
98238
  });
98231
98239
 
@@ -187505,6 +187513,8 @@ function oneLine(p2, operation) {
187505
187513
  function detailOf(p2) {
187506
187514
  if (p2.command) {
187507
187515
  return [
187516
+ // The asking session's own words (the whole summary is framed as its data).
187517
+ p2.reason && `reason: ${p2.reason}`,
187508
187518
  p2.description && `what: ${p2.description}`,
187509
187519
  p2.dangerExplanation && `risk: ${p2.dangerExplanation}`,
187510
187520
  p2.systemScopeExplanation && `outside the project: ${p2.systemScopeExplanation}`
@@ -188127,6 +188137,20 @@ var init_plan_artifacts = __esm({
188127
188137
  }
188128
188138
  });
188129
188139
 
188140
+ // src/lib/provider-label.ts
188141
+ function providerLabel(p2) {
188142
+ if (p2.id === "compass") return null;
188143
+ const name30 = p2.name?.trim() || "";
188144
+ if (p2.type === "custom" || p2.id.startsWith("custom::") || p2.id.startsWith("atlarix-cli-dev")) {
188145
+ return name30 || p2.id.replace(/^custom::/, "");
188146
+ }
188147
+ return (name30 || p2.id).replace(/\s*\([^()]*\)\s*$/, "") || name30 || p2.id;
188148
+ }
188149
+ var init_provider_label = __esm({
188150
+ "src/lib/provider-label.ts"() {
188151
+ }
188152
+ });
188153
+
188130
188154
  // src/cli/agent/ipc.ts
188131
188155
  async function handler(channel) {
188132
188156
  const electron = await Promise.resolve().then(() => (init_electron_stub(), electron_stub_exports));
@@ -201852,10 +201876,19 @@ var init_oauth_loopback_server = __esm({
201852
201876
  });
201853
201877
 
201854
201878
  // src/lib/mcp/oauth-error-message.ts
201855
- function describeMcpOAuthError(error51, guideUrl = MCP_CONNECTOR_GUIDE_URL) {
201879
+ function isSlack(serverUrl) {
201880
+ if (!serverUrl) return false;
201881
+ try {
201882
+ const host = new URL(serverUrl).hostname.toLowerCase();
201883
+ return host === "slack.com" || host.endsWith(".slack.com");
201884
+ } catch {
201885
+ return false;
201886
+ }
201887
+ }
201888
+ function describeMcpOAuthError(error51, serverUrl, guideUrl = MCP_CONNECTOR_GUIDE_URL) {
201856
201889
  const message = error51 instanceof Error ? error51.message : String(error51);
201857
201890
  if (NO_REGISTRATION.test(message)) {
201858
- return `This server needs a pre-registered app. Set it up once on atlarix.dev: ${guideUrl}`;
201891
+ return isSlack(serverUrl) ? `Use Atlarix in Slack instead: ${guideUrl}` : "Atlarix can't sign in to this server. If it offers an API key, add it with the key instead.";
201859
201892
  }
201860
201893
  return message;
201861
201894
  }
@@ -202122,7 +202155,7 @@ async function startMcpOAuthFlow(serverId, opts) {
202122
202155
  clearPendingMcpOAuthSession(serverId);
202123
202156
  logger48.error("startMcpOAuthFlow failed", error51);
202124
202157
  if (needsPreRegisteredClient(error51)) {
202125
- throw new McpOAuthError(describeMcpOAuthError(error51), "needs_registration");
202158
+ throw new McpOAuthError(describeMcpOAuthError(error51, row.url ?? void 0), "needs_registration");
202126
202159
  }
202127
202160
  throw error51;
202128
202161
  }
@@ -202145,7 +202178,8 @@ async function finishMcpOAuthCallback(code, state2) {
202145
202178
  return { serverId: pending6.serverId, serverName: pending6.serverName };
202146
202179
  } catch (error51) {
202147
202180
  clearPendingMcpOAuthSession(pending6.serverId);
202148
- const message = describeMcpOAuthError(error51);
202181
+ const serverUrl = needsPreRegisteredClient(error51) ? await db2.query.mcpServers.findFirst({ where: eq(mcpServers.id, pending6.serverId) }).then((r3) => r3?.url ?? void 0, () => void 0) : void 0;
202182
+ const message = describeMcpOAuthError(error51, serverUrl);
202149
202183
  broadcastMcpOAuthEvent("mcp:oauth-error", {
202150
202184
  serverId: pending6.serverId,
202151
202185
  serverName: pending6.serverName,
@@ -208848,13 +208882,16 @@ function parseCoreAuto(raw) {
208848
208882
  ].filter((x4) => !!x4)
208849
208883
  )
208850
208884
  ];
208885
+ const freeWindow = a2.freeWorkingWindowTokens;
208886
+ const freeWorkingWindowTokens = typeof freeWindow === "number" && Number.isInteger(freeWindow) && freeWindow > 0 ? freeWindow : null;
208851
208887
  return {
208852
208888
  id,
208853
208889
  label: label2,
208854
208890
  ...providerId && modelId ? { capability: { providerId, modelId } } : {},
208855
208891
  ...freeModels.length ? { freeModels } : {},
208856
208892
  ...paidModels.length ? { paidModels } : {},
208857
- ...nameableModels.length ? { nameableModels } : {}
208893
+ ...nameableModels.length ? { nameableModels } : {},
208894
+ ...freeWorkingWindowTokens ? { freeWorkingWindowTokens } : {}
208858
208895
  };
208859
208896
  }
208860
208897
  function parseCoreZenith(raw) {
@@ -210599,6 +210636,7 @@ __export(models_exports, {
210599
210636
  readCliState: () => readCliState,
210600
210637
  rememberChoice: () => rememberChoice,
210601
210638
  savedModelLabel: () => savedModelLabel,
210639
+ savedProviderName: () => savedProviderName,
210602
210640
  settableModelOptions: () => settableModelOptions,
210603
210641
  toggleFavorite: () => toggleFavorite,
210604
210642
  turnModelFor: () => turnModelFor,
@@ -210613,6 +210651,7 @@ async function loadModelOptions() {
210613
210651
  getLanguageModelProviders2()
210614
210652
  ]);
210615
210653
  const names = new Map(providers.map((p2) => [p2.id, p2.name]));
210654
+ const labels = new Map(providers.map((p2) => [p2.id, providerLabel(p2)]));
210616
210655
  const { isCoreAutoTier: isCoreAutoTier2, isCoreRouterTier: isCoreRouterTier2 } = await Promise.resolve().then(() => (init_compass_constants(), compass_constants_exports));
210617
210656
  const off = await disabledProviders();
210618
210657
  const entries2 = Object.entries(byProvider).filter(([id, models]) => (models?.length ?? 0) > 0 && !off.has(id));
@@ -210622,6 +210661,7 @@ async function loadModelOptions() {
210622
210661
  const out = [];
210623
210662
  for (const [provider, models] of entries2) {
210624
210663
  const providerName = provider === COMPASS ? "Atlarix" : names.get(provider) ?? provider;
210664
+ const shownProvider = provider === COMPASS ? null : labels.get(provider) ?? providerLabel({ id: provider });
210625
210665
  for (const m3 of models) {
210626
210666
  const window2 = provider === COMPASS ? await coreContextWindow(m3.apiName, m3.contextWindow) : m3.contextWindow;
210627
210667
  const ctx = window2 ? `${formatWindow(window2)} context` : "";
@@ -210631,7 +210671,8 @@ async function loadModelOptions() {
210631
210671
  name: m3.apiName,
210632
210672
  label: m3.displayName || m3.apiName,
210633
210673
  providerName,
210634
- detail: [provider === COMPASS ? m3.description : providerName, ctx].filter(Boolean).join(" \xB7 "),
210674
+ ...shownProvider ? { providerLabel: shownProvider } : {},
210675
+ detail: [provider === COMPASS ? m3.description : shownProvider, ctx].filter(Boolean).join(" \xB7 "),
210635
210676
  deepThinking: Boolean(m3.supportsDeepThinking),
210636
210677
  // Auto and Zenith pick the model per turn: no effort control (owner, 2026-10-29).
210637
210678
  effortChoices: provider === COMPASS && isCoreRouterTier2(m3.apiName) ? void 0 : m3.effortChoices,
@@ -210732,7 +210773,12 @@ function readCliState(file2 = statePath()) {
210732
210773
  notifications: s3.notifications,
210733
210774
  planModel: s3.planModel && typeof s3.planModel.provider === "string" && typeof s3.planModel.name === "string" ? s3.planModel : void 0,
210734
210775
  starredSessions: Array.isArray(s3.starredSessions) ? s3.starredSessions.filter((x4) => typeof x4 === "string") : void 0,
210735
- modelLabel: s3.modelLabel && typeof s3.modelLabel.provider === "string" && typeof s3.modelLabel.name === "string" && typeof s3.modelLabel.label === "string" ? s3.modelLabel : void 0
210776
+ modelLabel: s3.modelLabel && typeof s3.modelLabel.provider === "string" && typeof s3.modelLabel.name === "string" && typeof s3.modelLabel.label === "string" ? {
210777
+ provider: s3.modelLabel.provider,
210778
+ name: s3.modelLabel.name,
210779
+ label: s3.modelLabel.label,
210780
+ ...typeof s3.modelLabel.providerName === "string" ? { providerName: s3.modelLabel.providerName } : {}
210781
+ } : void 0
210736
210782
  };
210737
210783
  } catch {
210738
210784
  return { recent: [], favorites: [] };
@@ -210750,6 +210796,11 @@ function savedModelLabel(state2) {
210750
210796
  const l3 = state2.modelLabel;
210751
210797
  return l3 && same(l3, m3) ? l3.label : m3.name;
210752
210798
  }
210799
+ function savedProviderName(state2) {
210800
+ const m3 = state2.model;
210801
+ const l3 = state2.modelLabel;
210802
+ return m3 && l3 && same(l3, m3) ? l3.providerName : void 0;
210803
+ }
210753
210804
  function rememberChoice(state2, ref) {
210754
210805
  return {
210755
210806
  ...state2,
@@ -210768,6 +210819,7 @@ var COMPASS, same;
210768
210819
  var init_models = __esm({
210769
210820
  "src/cli/agent/models.ts"() {
210770
210821
  init_atlarix_home();
210822
+ init_provider_label();
210771
210823
  COMPASS = "compass";
210772
210824
  same = (a2, b3) => a2.provider === b3.provider && a2.name === b3.name;
210773
210825
  }
@@ -212859,8 +212911,8 @@ var init_compaction = __esm({
212859
212911
  });
212860
212912
 
212861
212913
  // src/lib/analytics/turn-end.ts
212862
- function gateOf(kind, httpStatus, body = "") {
212863
- if (kind === "consent_required") return "consent_required";
212914
+ function gateOf(kind, httpStatus, body = "", opts) {
212915
+ if (opts?.byok) return void 0;
212864
212916
  if (/free_usage_limit/.test(body) || kind === "quota" && httpStatus === 429) return "free_usage_limit";
212865
212917
  if (/free_busy/.test(body) || kind === "rate_limit" && httpStatus === 503) return "free_busy";
212866
212918
  if (/insufficient_credit/.test(body) || kind === "quota" && httpStatus === 402) return "insufficient_credit";
@@ -212895,16 +212947,61 @@ function messageOf(err2) {
212895
212947
  function nameOf(err2) {
212896
212948
  return String(err2?.name ?? "");
212897
212949
  }
212898
- function classifyTurnError(err2) {
212950
+ function wordsOf(err2) {
212951
+ return layers(err2).flatMap((l3) => [l3.message, l3.responseBody, l3.code, l3.type]).filter((v2) => typeof v2 === "string").join("\n");
212952
+ }
212953
+ function asProviderCode(v2) {
212954
+ if (typeof v2 !== "string" || v2.length === 0 || v2.length > PROVIDER_CODE_MAX) return null;
212955
+ const code = /^[A-Z][A-Z0-9_.-]*$/.test(v2) ? v2.toLowerCase() : v2;
212956
+ if (!/^[a-z][a-z0-9_.-]*$/.test(code)) return null;
212957
+ if ((code.match(/[0-9]/g)?.length ?? 0) > 4) return null;
212958
+ if (/^(sk|pk|rk)[-_]/.test(code)) return null;
212959
+ return code;
212960
+ }
212961
+ function providerCodeOf(err2) {
212962
+ const fromObject = (e3) => {
212963
+ if (!e3 || typeof e3 !== "object") return null;
212964
+ const o2 = e3;
212965
+ if (o2.type === "atlarix_late_error") return null;
212966
+ return asProviderCode(o2.code) ?? asProviderCode(o2.type) ?? asProviderCode(o2.status);
212967
+ };
212968
+ for (const l3 of layers(err2)) {
212969
+ if (typeof l3.responseBody === "string" && l3.responseBody.trimStart().startsWith("{")) {
212970
+ try {
212971
+ const parsed = JSON.parse(l3.responseBody);
212972
+ const code = fromObject(parsed?.error);
212973
+ if (code) return code;
212974
+ } catch {
212975
+ }
212976
+ }
212977
+ }
212978
+ for (const l3 of layers(err2)) {
212979
+ if (l3 instanceof Error || "statusCode" in l3 || "responseBody" in l3) continue;
212980
+ if (typeof l3.message !== "string" && l3.code === void 0 && l3.type === void 0) continue;
212981
+ const code = fromObject(l3);
212982
+ if (code) return code;
212983
+ }
212984
+ return void 0;
212985
+ }
212986
+ function providerCodeField(err2) {
212987
+ const providerCode = providerCodeOf(err2);
212988
+ return providerCode ? { providerCode } : {};
212989
+ }
212990
+ function classifyTurnError(err2, opts) {
212899
212991
  const httpStatus = statusOf(err2);
212900
212992
  const at2 = (kind) => httpStatus ? { kind, httpStatus } : { kind };
212901
212993
  const body = bodyOf(err2);
212902
212994
  const name30 = nameOf(err2);
212903
212995
  if (messageOf(err2).includes(ATLARIX_AUTH_REQUIRED_PREFIX) || /account_banned/.test(body)) return at2("auth");
212904
- if (/"consent_required"\s*:\s*true/.test(body)) return at2("consent_required");
212905
212996
  if (/free_usage_limit|insufficient_credit/.test(body) || httpStatus === 402) return at2("quota");
212906
212997
  if (/free_busy/.test(body)) return at2("rate_limit");
212907
212998
  if (isContextOverflowError(err2)) return at2("context_overflow");
212999
+ if (opts?.byok) {
213000
+ const limit = byokLimitKind(wordsOf(err2));
213001
+ if (limit === "credit") return at2("quota");
213002
+ if (limit === "key") return at2("auth");
213003
+ if (limit === "rate" && (httpStatus === void 0 || httpStatus < 500)) return at2("rate_limit");
213004
+ }
212908
213005
  if (httpStatus === 401 || httpStatus === 403) return at2("auth");
212909
213006
  if (err2 instanceof ProviderRefusedRequestError || name30 === "ProviderRefusedRequestError") return at2("provider_refused");
212910
213007
  if (name30 === "ChatPromptSafetyError") return at2("content_rejected");
@@ -212916,7 +213013,7 @@ function classifyTurnError(err2) {
212916
213013
  if (err2 instanceof EmptyModelOutputAfterRetryError || isNoUsableModelOutputError(err2)) return at2("no_output");
212917
213014
  return at2("other");
212918
213015
  }
212919
- function classifyTurnEnd(error51, signal) {
213016
+ function classifyTurnEnd(error51, signal, opts) {
212920
213017
  if (signal.aborted) {
212921
213018
  const sentinel = abortReasonSentinel(signal.reason);
212922
213019
  if (sentinel === ASK_USER_STREAM_STOP) return { outcome: "ask_user" };
@@ -212926,12 +213023,15 @@ function classifyTurnEnd(error51, signal) {
212926
213023
  }
212927
213024
  if (error51 === void 0) return { outcome: "ok" };
212928
213025
  if (error51 instanceof UserFacingRefusal) return { outcome: "gate", gateKind: "rule", errorKind: error51.rule };
212929
- const c2 = classifyTurnError(error51);
213026
+ const byok = opts?.provider != null && opts.provider !== "compass";
213027
+ const c2 = classifyTurnError(error51, { byok });
212930
213028
  const status = c2.httpStatus ? { httpStatus: c2.httpStatus } : {};
212931
- const gate = gateOf(c2.kind, c2.httpStatus, bodyOf(error51));
212932
- if (gate) return { outcome: "gate", gateKind: gate, errorKind: c2.kind, ...status };
212933
- return { outcome: "error", errorKind: c2.kind, ...status };
213029
+ const code = providerCodeField(error51);
213030
+ const gate = gateOf(c2.kind, c2.httpStatus, bodyOf(error51), { byok });
213031
+ if (gate) return { outcome: "gate", gateKind: gate, errorKind: c2.kind, ...status, ...code };
213032
+ return { outcome: "error", errorKind: c2.kind, ...status, ...code };
212934
213033
  }
213034
+ var PROVIDER_CODE_MAX;
212935
213035
  var init_turn_end = __esm({
212936
213036
  "src/lib/analytics/turn-end.ts"() {
212937
213037
  init_texts();
@@ -212940,6 +213040,7 @@ var init_turn_end = __esm({
212940
213040
  init_no_usable_model_output();
212941
213041
  init_compaction();
212942
213042
  init_auth_ipc();
213043
+ PROVIDER_CODE_MAX = 40;
212943
213044
  }
212944
213045
  });
212945
213046
 
@@ -213189,28 +213290,33 @@ function trackTurnCompleted(r3, providerTypeOf) {
213189
213290
  lastChoice.set(r3.chatId, choice2);
213190
213291
  const n2 = (turnsInProcess.get(r3.chatId) ?? 0) + 1;
213191
213292
  turnsInProcess.set(r3.chatId, n2);
213192
- let { outcome, errorKind, httpStatus, gateKind } = r3.end;
213293
+ let { outcome, errorKind, httpStatus, gateKind, providerCode } = r3.end;
213193
213294
  const se2 = stats.streamError;
213194
213295
  if (se2 && outcome === "error" && (errorKind === "no_output" || errorKind === "other")) {
213195
213296
  errorKind = se2.kind;
213196
213297
  httpStatus = se2.httpStatus;
213298
+ providerCode = se2.providerCode ?? providerCode;
213197
213299
  } else if (se2 && outcome === "ok" && r3.outputTokens === 0) {
213198
213300
  outcome = "error";
213199
213301
  errorKind = se2.kind;
213200
213302
  httpStatus = se2.httpStatus;
213303
+ providerCode = se2.providerCode;
213201
213304
  }
213305
+ const byok = !!r3.provider && r3.provider !== "compass" && !r3.fellBackToCore;
213202
213306
  if (outcome === "error") {
213203
- const gate = gateOf(errorKind, httpStatus);
213307
+ const gate = gateOf(errorKind, httpStatus, "", { byok });
213204
213308
  if (gate) {
213205
213309
  outcome = "gate";
213206
213310
  gateKind = gate;
213207
213311
  }
213208
213312
  }
213313
+ if (outcome === "ok") providerCode = void 0;
213209
213314
  resolved2 = {
213210
213315
  outcome,
213211
213316
  ...errorKind ? { errorKind } : {},
213212
213317
  ...httpStatus ? { httpStatus } : {},
213213
213318
  ...gateKind ? { gateKind } : {},
213319
+ ...providerCode ? { providerCode } : {},
213214
213320
  ...stats.autoBilling ? { autoBilling: stats.autoBilling } : {}
213215
213321
  };
213216
213322
  if (!isOptedIn()) return resolved2;
@@ -213232,6 +213338,7 @@ function trackTurnCompleted(r3, providerTypeOf) {
213232
213338
  ...gateKind ? { gate_kind: gateKind } : {},
213233
213339
  ...errorKind ? { error_kind: errorKind } : {},
213234
213340
  ...httpStatus ? { http_status: httpStatus } : {},
213341
+ ...providerCode ? { provider_code: providerCode } : {},
213235
213342
  ...se2 && outcome === "ok" ? { recovered_error_kind: se2.kind } : {},
213236
213343
  ...r3.mode ? { mode: modeName(r3.mode) } : {},
213237
213344
  ...provider ? { provider } : {},
@@ -213776,6 +213883,9 @@ var init_SubscriptionManager = __esm({
213776
213883
  static async handleOAuthCallback(url2) {
213777
213884
  const result2 = await handleAuthCallback(url2);
213778
213885
  if (result2.error) {
213886
+ broadcastToAllWindows("auth:sign-in-failed", {
213887
+ message: result2.error.message
213888
+ });
213779
213889
  return { success: false, user: null, error: result2.error };
213780
213890
  }
213781
213891
  if (result2.session) {
@@ -222003,7 +222113,7 @@ var require_bignumber = __commonJS({
222003
222113
  "use strict";
222004
222114
  var BigNumber, isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil = Math.ceil, mathfloor = Math.floor, bignumberError = "[BigNumber Error] ", tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ", BASE = 1e14, LOG_BASE = 14, MAX_SAFE_INTEGER = 9007199254740991, POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], SQRT_BASE = 1e7, MAX2 = 1e9;
222005
222115
  function clone4(configObject) {
222006
- var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
222116
+ var div, convertBase, parseNumeric, P2 = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT2 = {
222007
222117
  prefix: "",
222008
222118
  groupSize: 3,
222009
222119
  secondaryGroupSize: 0,
@@ -222210,7 +222320,7 @@ var require_bignumber = __commonJS({
222210
222320
  }
222211
222321
  if (obj2.hasOwnProperty(p2 = "FORMAT")) {
222212
222322
  v2 = obj2[p2];
222213
- if (typeof v2 == "object") FORMAT = v2;
222323
+ if (typeof v2 == "object") FORMAT2 = v2;
222214
222324
  else throw Error(bignumberError + p2 + " not an object: " + v2);
222215
222325
  }
222216
222326
  if (obj2.hasOwnProperty(p2 = "ALPHABET")) {
@@ -222234,7 +222344,7 @@ var require_bignumber = __commonJS({
222234
222344
  CRYPTO,
222235
222345
  MODULO_MODE,
222236
222346
  POW_PRECISION,
222237
- FORMAT,
222347
+ FORMAT: FORMAT2,
222238
222348
  ALPHABET
222239
222349
  };
222240
222350
  };
@@ -223164,7 +223274,7 @@ var require_bignumber = __commonJS({
223164
223274
  format3 = dp;
223165
223275
  dp = rm4 = null;
223166
223276
  } else {
223167
- format3 = FORMAT;
223277
+ format3 = FORMAT2;
223168
223278
  }
223169
223279
  } else if (typeof format3 != "object") {
223170
223280
  throw Error(bignumberError + "Argument not an object: " + format3);
@@ -271038,11 +271148,6 @@ function autoRequestHeaders(settings, options2) {
271038
271148
  };
271039
271149
  if (options2?.workMode) out["X-Atlarix-Mode"] = options2.workMode;
271040
271150
  if (options2?.escalate) out["X-Atlarix-Escalate"] = "1";
271041
- const consent = autoConsentHeader(settings);
271042
- if (consent) {
271043
- out["X-Atlarix-Free-Consent"] = "1";
271044
- out["X-Atlarix-Free-Consent-Version"] = consent;
271045
- }
271046
271151
  return out;
271047
271152
  }
271048
271153
  function isLoopbackUrl(url2) {
@@ -271246,10 +271351,7 @@ async function getRegularModelClient(model, settings, providerConfig, options2)
271246
271351
  retryPending = false;
271247
271352
  }
271248
271353
  if (isAutoTier || isZenithTier) {
271249
- for (const [k2, v2] of Object.entries(autoHeaders)) {
271250
- if (isZenithTier && /free-consent/i.test(k2)) continue;
271251
- headers.set(k2, v2);
271252
- }
271354
+ for (const [k2, v2] of Object.entries(autoHeaders)) headers.set(k2, v2);
271253
271355
  }
271254
271356
  const send2 = () => coreProxyFetch(input, { ...init2, headers });
271255
271357
  const res = isAutoTier && !pinnedToken ? await throughFreeAutoGate(send2) : await send2();
@@ -273441,15 +273543,21 @@ async function enforceContextBudget(params) {
273441
273543
  if (!overBudget()) break;
273442
273544
  const entries2 = nonSystemEntries(limitedMessageHistory);
273443
273545
  const pStart = protectedEntryStartIndex(entries2);
273444
- const firstProtectedOriginalIndex = pStart < entries2.length ? entries2[pStart].i : limitedMessageHistory.length;
273546
+ let firstProtectedOriginalIndex = pStart < entries2.length ? entries2[pStart].i : limitedMessageHistory.length;
273547
+ while (firstProtectedOriginalIndex > 0 && firstProtectedOriginalIndex < limitedMessageHistory.length && limitedMessageHistory[firstProtectedOriginalIndex]?.role === "tool") {
273548
+ firstProtectedOriginalIndex--;
273549
+ }
273445
273550
  const head2 = limitedMessageHistory.slice(0, firstProtectedOriginalIndex);
273446
273551
  const tail2 = limitedMessageHistory.slice(firstProtectedOriginalIndex);
273447
- const headConversation = head2.filter(
273448
- (m3) => m3.role === "user" || m3.role === "assistant"
273449
- );
273450
- if (headConversation.length === 0) break;
273451
- const kept = headConversation.slice(2);
273452
- droppedMessageCount += headConversation.length - kept.length;
273552
+ const headConversation = head2.filter((m3) => m3.role !== "system");
273553
+ if (!headConversation.some((m3) => m3.role === "user" || m3.role === "assistant")) break;
273554
+ let cut = 0;
273555
+ for (let n2 = 0; cut < headConversation.length && n2 < 2; cut++) {
273556
+ if (headConversation[cut].role !== "tool") n2++;
273557
+ }
273558
+ while (cut < headConversation.length && headConversation[cut].role === "tool") cut++;
273559
+ const kept = headConversation.slice(cut);
273560
+ droppedMessageCount += cut;
273453
273561
  limitedMessageHistory = [
273454
273562
  ...head2.filter((m3) => m3.role === "system"),
273455
273563
  ...kept,
@@ -275324,9 +275432,7 @@ ${formatSmallRepoInventory(paths)}`;
275324
275432
  effectiveModel?.name
275325
275433
  );
275326
275434
  let lastStepInputTokens = 0;
275327
- let roundEndedForCompaction = false;
275328
275435
  const runRound = async () => {
275329
- roundEndedForCompaction = false;
275330
275436
  let retryAbove;
275331
275437
  const rolling = makeRollingEmitter(emit, delegationId, round);
275332
275438
  currentRolling = rolling;
@@ -275343,6 +275449,12 @@ ${formatSmallRepoInventory(paths)}`;
275343
275449
  placement: cacheMarkerPlacement
275344
275450
  }),
275345
275451
  tools: toolSet,
275452
+ // Explicitly NO stop condition: the round runs until the model stops
275453
+ // calling tools, like the main turn (simple-stream-text.ts). Leaving
275454
+ // `stopWhen` out is not the same thing: the AI SDK then applies
275455
+ // `stepCountIs(1)`, and every sub-agent ended after its first tool call
275456
+ // and reported "completed" (W10, 15.12.0–15.13.3).
275457
+ stopWhen: [],
275346
275458
  // 0j: the round no longer ENDS at the compaction point — a long scout
275347
275459
  // compacts in place in `prepareStep` (below) from the ONE complete count
275348
275460
  // (system + tools + messages). The provider's input count is kept only
@@ -275443,29 +275555,22 @@ ${formatSmallRepoInventory(paths)}`;
275443
275555
  attemptCount: lengthAttempts,
275444
275556
  maxAttempts: SUBAGENT_LENGTH_CONTINUATION_MAX
275445
275557
  });
275446
- let compactionContinuations = 0;
275447
- while (lengthTruncated || roundEndedForCompaction) {
275448
- if (lengthTruncated) {
275449
- lengthAttempts++;
275450
- msgs = [
275451
- ...msgs,
275452
- ...result2.response.messages,
275453
- {
275454
- role: "user",
275455
- content: buildContinuationPrompt({
275456
- chatId: args2.chatId ?? 0,
275457
- turnId: args2.turnId ?? "subagent",
275458
- attemptCount: lengthAttempts,
275459
- maxAttempts: SUBAGENT_LENGTH_CONTINUATION_MAX,
275460
- lastContent: result2.text ?? ""
275461
- })
275462
- }
275463
- ];
275464
- } else {
275465
- compactionContinuations++;
275466
- if (compactionContinuations > SUBAGENT_COMPACTION_CONTINUATION_MAX) break;
275467
- msgs = [...msgs, ...result2.response.messages];
275468
- }
275558
+ while (lengthTruncated) {
275559
+ lengthAttempts++;
275560
+ msgs = [
275561
+ ...msgs,
275562
+ ...result2.response.messages,
275563
+ {
275564
+ role: "user",
275565
+ content: buildContinuationPrompt({
275566
+ chatId: args2.chatId ?? 0,
275567
+ turnId: args2.turnId ?? "subagent",
275568
+ attemptCount: lengthAttempts,
275569
+ maxAttempts: SUBAGENT_LENGTH_CONTINUATION_MAX,
275570
+ lastContent: result2.text ?? ""
275571
+ })
275572
+ }
275573
+ ];
275469
275574
  const compaction = await runMidLoopCompaction({
275470
275575
  messages: msgs,
275471
275576
  systemPromptEstimate: systemEstimate,
@@ -275538,7 +275643,7 @@ ${formatSmallRepoInventory(paths)}`;
275538
275643
  };
275539
275644
  }
275540
275645
  }
275541
- var import_electron_log79, logger76, SUBAGENT_LENGTH_CONTINUATION_MAX, SUBAGENT_COMPACTION_CONTINUATION_MAX, SUBAGENT_TOOL_NAMES, WRITER_SUBAGENT_TOOL_NAMES, SUBAGENT_NESTED_EXPAND_TOOLS, THOUGHT_EMIT_INTERVAL_MS, THOUGHT_SEGMENT_CHAR_CAP;
275646
+ var import_electron_log79, logger76, SUBAGENT_LENGTH_CONTINUATION_MAX, SUBAGENT_TOOL_NAMES, WRITER_SUBAGENT_TOOL_NAMES, SUBAGENT_NESTED_EXPAND_TOOLS, THOUGHT_EMIT_INTERVAL_MS, THOUGHT_SEGMENT_CHAR_CAP;
275542
275647
  var init_run_subagent = __esm({
275543
275648
  "src/lib/agents/run-subagent.ts"() {
275544
275649
  init_turn_stats();
@@ -275568,7 +275673,6 @@ var init_run_subagent = __esm({
275568
275673
  init_subagent_proposals();
275569
275674
  logger76 = import_electron_log79.default.scope("run-subagent");
275570
275675
  SUBAGENT_LENGTH_CONTINUATION_MAX = 3;
275571
- SUBAGENT_COMPACTION_CONTINUATION_MAX = 4;
275572
275676
  SUBAGENT_TOOL_NAMES = [
275573
275677
  "read_file",
275574
275678
  "glob",
@@ -280955,6 +281059,22 @@ Read the file first \u2014 \`replace\` matches its current bytes, and you'll be
280955
281059
  }
280956
281060
  });
280957
281061
 
281062
+ // src/lib/tools/approval-reason.ts
281063
+ function approvalReason(raw) {
281064
+ if (typeof raw !== "string") return void 0;
281065
+ const text5 = raw.replace(CONTROL, "").replace(FORMAT, "").replace(/\s+/g, " ").trim();
281066
+ if (!text5) return void 0;
281067
+ return text5.length > APPROVAL_REASON_CAP ? `${text5.slice(0, APPROVAL_REASON_CAP - 1).trimEnd()}\u2026` : text5;
281068
+ }
281069
+ var APPROVAL_REASON_CAP, CONTROL, FORMAT;
281070
+ var init_approval_reason = __esm({
281071
+ "src/lib/tools/approval-reason.ts"() {
281072
+ APPROVAL_REASON_CAP = 200;
281073
+ CONTROL = /[\x00-\x08\x0e-\x1f\x7f-\x9f]/g;
281074
+ FORMAT = new RegExp("\\p{Cf}", "gu");
281075
+ }
281076
+ });
281077
+
280958
281078
  // src/lib/tools/shell.ts
280959
281079
  import * as os24 from "node:os";
280960
281080
  function resolveDescriptionShell() {
@@ -280971,6 +281091,7 @@ var init_shell = __esm({
280971
281091
  "src/lib/tools/shell.ts"() {
280972
281092
  init_registry();
280973
281093
  init_resolve_shell();
281094
+ init_approval_reason();
280974
281095
  init_dangerous_commands();
280975
281096
  ToolRegistry.register({
280976
281097
  name: "run_command",
@@ -280993,6 +281114,9 @@ var init_shell = __esm({
280993
281114
  "Working directory (default: workspace root). Prefer this over 'cd <dir> && command'."
280994
281115
  ),
280995
281116
  description: stringParam("What this command does"),
281117
+ reason: stringParam(
281118
+ 'Shown to the user if this needs their approval: a short question, e.g. "Can I check whether the PR has merge conflicts?"'
281119
+ ),
280996
281120
  timeout_ms: numberParam(
280997
281121
  "Max wall-clock time in ms (default 120000, max 1800000). Dev-server commands still use a short start timeout.",
280998
281122
  12e4,
@@ -281024,6 +281148,7 @@ var init_shell = __esm({
281024
281148
  command,
281025
281149
  cwd = ".",
281026
281150
  description,
281151
+ reason,
281027
281152
  timeout_ms = 12e4,
281028
281153
  max_output_bytes = 8e4,
281029
281154
  background = false,
@@ -281033,6 +281158,7 @@ var init_shell = __esm({
281033
281158
  }) => {
281034
281159
  const dangerous = isDangerousCommand(command);
281035
281160
  const dangerExplanation = dangerous ? getDangerExplanation(command) : void 0;
281161
+ const why = approvalReason(reason);
281036
281162
  return {
281037
281163
  __permission_required: true,
281038
281164
  operation: "run_command",
@@ -281040,6 +281166,7 @@ var init_shell = __esm({
281040
281166
  command,
281041
281167
  workingDirectory: cwd,
281042
281168
  description,
281169
+ ...why ? { reason: why } : {},
281043
281170
  isDangerous: dangerous,
281044
281171
  dangerExplanation,
281045
281172
  timeout_ms: Math.min(
@@ -348894,7 +349021,9 @@ function reportTurnFailure(f5, capture3, providerTypeOf) {
348894
349021
  surface: atlarixSurface(),
348895
349022
  ...editor ? { editor } : {},
348896
349023
  error_kind: kind,
348897
- ...f5.end.httpStatus ? { http_status: String(f5.end.httpStatus) } : {}
349024
+ ...f5.end.httpStatus ? { http_status: String(f5.end.httpStatus) } : {},
349025
+ // The provider's machine code (allowlisted in turn-end.ts), never its text.
349026
+ ...f5.end.providerCode ? { provider_code: f5.end.providerCode } : {}
348898
349027
  },
348899
349028
  fingerprint: ["turn-failed", kind, provider_type]
348900
349029
  });
@@ -348921,7 +349050,6 @@ var init_turn_failure_report = __esm({
348921
349050
  EXPECTED = /* @__PURE__ */ new Set([
348922
349051
  "auth",
348923
349052
  "quota",
348924
- "consent_required",
348925
349053
  "rate_limit",
348926
349054
  "context_overflow",
348927
349055
  "content_rejected",
@@ -351690,11 +351818,20 @@ async function runStreamRoundWithEmptyOutputRetry(ctx, deps, params) {
351690
351818
  }
351691
351819
  throw recordedFault;
351692
351820
  }
351821
+ const producedNothing = fullResponse === initialFullResponse && (bundle.getResumeMessages?.() ?? []).length === 0;
351822
+ if (producedNothing) {
351823
+ const refused = bundle.getRecordedRefusal?.();
351824
+ if (refused != null) throw new ProviderRefusedRequestError(refused);
351825
+ if (bundle.getRecordedBusy?.() != null && bundle.getRecordedLimit?.() != null) {
351826
+ throw new NoOutputGeneratedError({ message: "The provider sent a rate limit in place of a reply." });
351827
+ }
351828
+ }
351693
351829
  return { bundle, fullResponse, finishReason };
351694
351830
  } catch (caught) {
351695
351831
  if (params.abortController.signal.aborted) {
351696
351832
  throw caught;
351697
351833
  }
351834
+ if (caught instanceof ProviderRefusedRequestError) throw caught;
351698
351835
  const recordedNetworkError = bundle?.getRecordedNetworkError?.();
351699
351836
  const err2 = recordedNetworkError != null && isEmptyOutputStreamError(caught) ? recordedNetworkError : caught;
351700
351837
  if (err2 !== caught) {
@@ -351719,6 +351856,10 @@ async function runStreamRoundWithEmptyOutputRetry(ctx, deps, params) {
351719
351856
  if (params.abortController.signal.aborted) throw new Error("aborted");
351720
351857
  continue;
351721
351858
  }
351859
+ if (busy != null && isEmptyOutputStreamError(err2)) {
351860
+ const limited = bundle?.reportRecordedLimit?.();
351861
+ if (limited != null) throw new ProviderRefusedRequestError(limited);
351862
+ }
351722
351863
  const refusal = bundle?.getRecordedRefusal?.();
351723
351864
  if (refusal != null && isEmptyOutputStreamError(err2)) {
351724
351865
  throw new ProviderRefusedRequestError(refusal);
@@ -351806,7 +351947,8 @@ async function runStreamRoundWithEmptyOutputRetry(ctx, deps, params) {
351806
351947
  chatId: params.chatId,
351807
351948
  phase: "thinking",
351808
351949
  retry: true,
351809
- label: `Couldn't connect, retrying in ${Math.max(1, Math.round(delay3 / 1e3))}s (${networkAttempt}/${RECONNECT_DELAYS_MS.length})\u2026`
351950
+ // Your own key's 429 connected fine: it is a rate limit.
351951
+ label: `${bundle?.getRecordedLimit?.() != null ? "Rate-limited" : "Couldn't connect"}, retrying in ${Math.max(1, Math.round(delay3 / 1e3))}s (${networkAttempt}/${RECONNECT_DELAYS_MS.length})\u2026`
351810
351952
  });
351811
351953
  fullResponse = initialFullResponse;
351812
351954
  partialResponses.delete(params.chatId);
@@ -351817,6 +351959,9 @@ async function runStreamRoundWithEmptyOutputRetry(ctx, deps, params) {
351817
351959
  continue;
351818
351960
  }
351819
351961
  if (isNetworkStreamError(err2)) {
351962
+ const nothingToKeep = (bundle?.getResumeMessages?.() ?? []).length === 0;
351963
+ const limited = nothingToKeep ? bundle?.reportRecordedLimit?.() : null;
351964
+ if (limited != null) throw new ProviderRefusedRequestError(limited);
351820
351965
  throw new NetworkStreamDisconnectedError(fullResponse, err2);
351821
351966
  }
351822
351967
  throw err2;
@@ -351832,6 +351977,7 @@ var init_round_retry = __esm({
351832
351977
  init_turn_stats();
351833
351978
  init_lane();
351834
351979
  import_electron_log110 = __toESM(require_src());
351980
+ init_dist16();
351835
351981
  init_stream_chunk_tags();
351836
351982
  init_safe_sender();
351837
351983
  init_no_usable_model_output();
@@ -351910,9 +352056,6 @@ function classifyCompassFailure(statusCode, bodyStr) {
351910
352056
  const secs = /"retry_after_seconds"\s*:\s*(\d+)/.exec(bodyStr)?.[1];
351911
352057
  return { message: coreRateLimitedMessage(secs ? Number(secs) : null), isCompassInfraError: false };
351912
352058
  }
351913
- if (/"consent_required"\s*:\s*true/.test(bodyStr)) {
351914
- return { message: autoConsentRequiredUserMessage(), isCompassInfraError: false };
351915
- }
351916
352059
  if (statusCode === 402 || /insufficient_credit/.test(bodyStr)) {
351917
352060
  return {
351918
352061
  message: coreRefusalMessage(parseCreditRefusal(bodyStr)),
@@ -351995,6 +352138,89 @@ var init_native_web_search = __esm({
351995
352138
  }
351996
352139
  });
351997
352140
 
352141
+ // src/lib/ai/tool-pairing.ts
352142
+ function partsOf(m3) {
352143
+ return Array.isArray(m3.content) ? m3.content : [];
352144
+ }
352145
+ function isPaired(messages) {
352146
+ let open = null;
352147
+ const answered = /* @__PURE__ */ new Set();
352148
+ const unanswered = () => open != null && [...open].some((id) => !answered.has(id));
352149
+ for (const m3 of messages) {
352150
+ if (m3.role === "tool") {
352151
+ for (const p2 of partsOf(m3)) {
352152
+ if (!isResult(p2)) continue;
352153
+ if (!open?.has(p2.toolCallId)) return false;
352154
+ answered.add(p2.toolCallId);
352155
+ }
352156
+ continue;
352157
+ }
352158
+ if (unanswered()) return false;
352159
+ open = null;
352160
+ answered.clear();
352161
+ if (m3.role === "assistant") {
352162
+ const calls = partsOf(m3).filter(isLocalCall).map((p2) => p2.toolCallId);
352163
+ if (calls.length) open = new Set(calls);
352164
+ }
352165
+ }
352166
+ return !unanswered();
352167
+ }
352168
+ function pairToolMessages(messages) {
352169
+ if (isPaired(messages)) return { messages, repaired: false, droppedCalls: 0, droppedResults: 0 };
352170
+ const callAt = /* @__PURE__ */ new Map();
352171
+ messages.forEach((m3, i4) => {
352172
+ if (m3.role === "assistant") {
352173
+ for (const p2 of partsOf(m3)) if (isLocalCall(p2) && !callAt.has(p2.toolCallId)) callAt.set(p2.toolCallId, i4);
352174
+ }
352175
+ });
352176
+ const resultFor = /* @__PURE__ */ new Map();
352177
+ messages.forEach((m3, i4) => {
352178
+ if (m3.role !== "tool") return;
352179
+ for (const p2 of partsOf(m3)) {
352180
+ const at2 = isResult(p2) ? callAt.get(p2.toolCallId) : void 0;
352181
+ if (at2 !== void 0 && at2 < i4 && !resultFor.has(p2.toolCallId)) resultFor.set(p2.toolCallId, p2);
352182
+ }
352183
+ });
352184
+ let droppedCalls = 0;
352185
+ let droppedResults = 0;
352186
+ const out = [];
352187
+ const placed = /* @__PURE__ */ new Set();
352188
+ messages.forEach((m3, i4) => {
352189
+ const parts = partsOf(m3);
352190
+ if (m3.role === "assistant" && parts.some(isLocalCall)) {
352191
+ const kept = parts.filter((p2) => {
352192
+ if (!isLocalCall(p2)) return true;
352193
+ const ok = resultFor.has(p2.toolCallId) && callAt.get(p2.toolCallId) === i4 && !placed.has(p2.toolCallId);
352194
+ if (ok) placed.add(p2.toolCallId);
352195
+ else droppedCalls++;
352196
+ return ok;
352197
+ });
352198
+ if (kept.length) out.push({ ...m3, content: kept });
352199
+ const results2 = kept.filter(isLocalCall).map((p2) => resultFor.get(p2.toolCallId));
352200
+ if (results2.length) out.push({ role: "tool", content: results2 });
352201
+ return;
352202
+ }
352203
+ if (m3.role === "tool") {
352204
+ const rest2 = parts.filter((p2) => {
352205
+ if (!isResult(p2)) return true;
352206
+ if (resultFor.get(p2.toolCallId) !== p2) droppedResults++;
352207
+ return false;
352208
+ });
352209
+ if (rest2.length) out.push({ ...m3, content: rest2 });
352210
+ return;
352211
+ }
352212
+ out.push(m3);
352213
+ });
352214
+ return { messages: out, repaired: true, droppedCalls, droppedResults };
352215
+ }
352216
+ var isLocalCall, isResult;
352217
+ var init_tool_pairing = __esm({
352218
+ "src/lib/ai/tool-pairing.ts"() {
352219
+ isLocalCall = (p2) => p2?.type === "tool-call" && p2.providerExecuted !== true && typeof p2.toolCallId === "string";
352220
+ isResult = (p2) => p2?.type === "tool-result" && typeof p2.toolCallId === "string";
352221
+ }
352222
+ });
352223
+
351998
352224
  // src/lib/chat/image-embed-gate.ts
351999
352225
  var image_embed_gate_exports = {};
352000
352226
  __export(image_embed_gate_exports, {
@@ -352486,6 +352712,7 @@ async function simpleStreamText(ctx, deps, {
352486
352712
  let recordedNetworkError = null;
352487
352713
  let recordedRefusal = null;
352488
352714
  let recordedBusy = null;
352715
+ let recordedLimit = null;
352489
352716
  let recordedOverflow = null;
352490
352717
  let recordedNativeComputerRejection = null;
352491
352718
  const turnBuckets = {
@@ -352676,7 +352903,13 @@ async function simpleStreamText(ctx, deps, {
352676
352903
  interjections,
352677
352904
  tag: systemReminder
352678
352905
  });
352679
- const stepMessages = assembled.messages;
352906
+ const pairing = pairToolMessages(assembled.messages);
352907
+ if (pairing.repaired) {
352908
+ logger111.warn(
352909
+ `[tool-pairing] step ${stepNumber}: repaired the request's tool pairing (dropped ${pairing.droppedCalls} call(s) without a result, ${pairing.droppedResults} result(s) without a call) for chat ${req.chatId}`
352910
+ );
352911
+ }
352912
+ const stepMessages = pairing.messages;
352680
352913
  if (freshInterjections?.length) {
352681
352914
  void deliverInterjectionsToTranscript({
352682
352915
  chatId: req.chatId,
@@ -352687,7 +352920,7 @@ async function simpleStreamText(ctx, deps, {
352687
352920
  });
352688
352921
  }
352689
352922
  const forceCollect = forceCollectOnWake && stepNumber === 0;
352690
- const changedMessages = assembled.changed || baseMessages !== messages;
352923
+ const changedMessages = assembled.changed || baseMessages !== messages || pairing.repaired;
352691
352924
  const base = cacheMarkerPlacement !== "none" && (stepNumber > 0 || changedMessages) ? {
352692
352925
  messages: advanceCacheBreakpointsForStep(
352693
352926
  stepMessages,
@@ -352830,13 +353063,32 @@ async function simpleStreamText(ctx, deps, {
352830
353063
  );
352831
353064
  return;
352832
353065
  }
352833
- noteTurnStreamError(req.chatId, classifyTurnError(error51));
353066
+ const byok = modelClient.builtinProviderId !== "compass";
353067
+ noteTurnStreamError(req.chatId, {
353068
+ ...classifyTurnError(error51, { byok }),
353069
+ ...providerCodeField(error51)
353070
+ });
353071
+ const providerName = providerDisplayName(modelClient.builtinProviderId);
353072
+ const reason = providerReason(error51);
353073
+ const status = httpStatusOf(error51);
353074
+ const creditRefusal = byok && status === 429 && byokLimitKind(reason) === "credit";
353075
+ const rateLimit = () => ({
353076
+ error: error51,
353077
+ text: turnErrorText(byokLimitUserMessage(reason, providerName, 429) ?? modelFailureUserMessage(reason))
353078
+ });
352834
353079
  if (isProviderBusyError(error51)) {
352835
353080
  recordedBusy = error51;
353081
+ if (byok) recordedLimit = rateLimit();
352836
353082
  logger111.warn("[stream] onError: provider busy / rate-limited (will wait and retry)", error51);
352837
353083
  return;
352838
353084
  }
352839
- if (isNetworkStreamError(error51)) {
353085
+ if (byok && status === 429 && !creditRefusal) {
353086
+ recordedNetworkError = error51;
353087
+ recordedLimit = rateLimit();
353088
+ logger111.warn("[stream] onError: your provider is rate-limiting (will retry, then say so)", error51);
353089
+ return;
353090
+ }
353091
+ if (!creditRefusal && isNetworkStreamError(error51)) {
352840
353092
  recordedNetworkError = error51;
352841
353093
  logger111.warn(
352842
353094
  "[stream] onError: network/transport failure (will retry silently)",
@@ -352899,9 +353151,9 @@ async function simpleStreamText(ctx, deps, {
352899
353151
  }
352900
353152
  }
352901
353153
  } else {
352902
- message = byokLimitUserMessage(message, providerDisplayName(modelClient.builtinProviderId)) ?? modelFailureUserMessage(message);
353154
+ message = byokLimitUserMessage(message, providerName, status) ?? modelFailureUserMessage(message);
352903
353155
  }
352904
- if (isProviderRefusal(error51)) recordedRefusal = error51;
353156
+ if (isProviderRefusal(error51) || creditRefusal || byok && status === void 0) recordedRefusal = error51;
352905
353157
  logger111.error(
352906
353158
  `AI stream text error for request: errorMessage=${errorMessage} error=`,
352907
353159
  error51
@@ -352967,6 +353219,19 @@ async function simpleStreamText(ctx, deps, {
352967
353219
  /** A refusal `onError` already reported; see `recordedRefusal`. */
352968
353220
  getRecordedRefusal: () => recordedRefusal,
352969
353221
  getRecordedBusy: () => recordedBusy,
353222
+ /** Your own provider's rate limit this round saw, or null; see `recordedLimit`. */
353223
+ getRecordedLimit: () => recordedLimit?.error ?? null,
353224
+ /**
353225
+ * Shows that rate limit's message, once, and returns its error (null when
353226
+ * there is none): round-retry calls it when the waits have run out.
353227
+ */
353228
+ reportRecordedLimit: () => {
353229
+ if (!recordedLimit) return null;
353230
+ const { error: error51, text: text5 } = recordedLimit;
353231
+ recordedLimit = null;
353232
+ safeSend(event.sender, "chat:response:error", { chatId: req.chatId, streamId, error: text5 });
353233
+ return error51;
353234
+ },
352970
353235
  /** A too-long request `onError` held back for the turn's compact-and-retry; see `recordedOverflow`. */
352971
353236
  getRecordedOverflow: () => recordedOverflow,
352972
353237
  /** The provider refused its own computer tool; see `recordedNativeComputerRejection`. */
@@ -352976,10 +353241,25 @@ async function simpleStreamText(ctx, deps, {
352976
353241
  function isProviderRefusal(error51) {
352977
353242
  const body = error51 ?? null;
352978
353243
  if (/"error"\s*:\s*"(free_usage_limit|free_busy|core_rate_limited)"/.test(String(body?.responseBody ?? body?.error?.responseBody ?? ""))) return true;
352979
- const e3 = error51;
352980
- const status = [e3?.statusCode, e3?.status, e3?.error?.statusCode, e3?.error?.status].find((x4) => typeof x4 === "number");
353244
+ const status = httpStatusOf(error51);
352981
353245
  return status != null && status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429;
352982
353246
  }
353247
+ function httpStatusOf(error51) {
353248
+ const e3 = error51;
353249
+ return [e3?.statusCode, e3?.status, e3?.error?.statusCode, e3?.error?.status].find((x4) => typeof x4 === "number");
353250
+ }
353251
+ function providerReason(error51) {
353252
+ const inner = error51?.error;
353253
+ const m3 = typeof inner?.message === "string" ? inner.message : "";
353254
+ if (m3) return typeof inner?.responseBody === "string" && inner.responseBody ? `${m3}
353255
+
353256
+ Details: ${inner.responseBody}` : m3;
353257
+ try {
353258
+ return JSON.stringify(error51) ?? "";
353259
+ } catch {
353260
+ return String(error51);
353261
+ }
353262
+ }
352983
353263
  async function maxOutputTokensForTurn(deps) {
352984
353264
  return getMaxTokensWithFloor(deps.effectiveModel, {
352985
353265
  reasoningCapable: deps.enableNativeReasoning
@@ -353012,6 +353292,7 @@ var init_simple_stream_text = __esm({
353012
353292
  init_safe_sender();
353013
353293
  init_native_history();
353014
353294
  init_tier_context_budget();
353295
+ init_tool_pairing();
353015
353296
  init_model_reasoning_profile();
353016
353297
  init_thinking_utils();
353017
353298
  init_token_utils();
@@ -361784,7 +362065,9 @@ ${hookContext.join("\n\n")}`
361784
362065
  const ended = trackTurnCompleted(
361785
362066
  {
361786
362067
  chatId: req.chatId,
361787
- end: turnRefused ?? (ctx.askUserEndedTurn ? { outcome: "ask_user" } : classifyTurnEnd(turnError, abortController.signal)),
362068
+ end: turnRefused ?? (ctx.askUserEndedTurn ? { outcome: "ask_user" } : classifyTurnEnd(turnError, abortController.signal, {
362069
+ provider: ctx.analyticsTurn.fellBackToCore ? "compass" : ctx.analyticsTurn.provider
362070
+ })),
361788
362071
  ...ctx.analyticsTurn,
361789
362072
  hadHistory: ctx.analyticsTurn.hadHistory === true,
361790
362073
  automation: !!req.automation,
@@ -362679,7 +362962,7 @@ ${err2.stack}` : "";
362679
362962
  }
362680
362963
 
362681
362964
  // src/headless/atlarix-headless.mts
362682
- var VERSION15 = false ? "dev" : "15.13.3";
362965
+ var VERSION15 = false ? "dev" : "15.14.0";
362683
362966
  if (process.argv[2] === "run") process.argv.splice(2, 1);
362684
362967
  var RUN_HELP = `atlarix run: one turn without the UI, for scripts and CI
362685
362968
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "atlarix",
3
- "version": "15.13.3",
3
+ "version": "15.14.0",
4
4
  "description": "Atlarix CLI: an AI coding agent in your terminal. Works with any model (Atlarix Auto, your own API key, or a local model) and runs unattended with `atlarix run` for CI.",
5
5
  "license": "PROPRIETARY",
6
6
  "author": {
@@ -65,12 +65,12 @@
65
65
  "provenance": false
66
66
  },
67
67
  "optionalDependencies": {
68
- "atlarix-darwin-arm64": "15.13.3",
69
- "atlarix-darwin-x64": "15.13.3",
70
- "atlarix-linux-x64": "15.13.3",
71
- "atlarix-linux-arm64": "15.13.3",
72
- "atlarix-linux-x64-musl": "15.13.3",
73
- "atlarix-linux-arm64-musl": "15.13.3",
74
- "atlarix-windows-x64": "15.13.3"
68
+ "atlarix-darwin-arm64": "15.14.0",
69
+ "atlarix-darwin-x64": "15.14.0",
70
+ "atlarix-linux-x64": "15.14.0",
71
+ "atlarix-linux-arm64": "15.14.0",
72
+ "atlarix-linux-x64-musl": "15.14.0",
73
+ "atlarix-linux-arm64-musl": "15.14.0",
74
+ "atlarix-windows-x64": "15.14.0"
75
75
  }
76
76
  }