opencode-anthropic-multi-account 0.2.22 → 0.2.24

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/index.js CHANGED
@@ -25,7 +25,7 @@ import {
25
25
  showToast,
26
26
  sleep,
27
27
  updateConfigField
28
- } from "./chunk-TOCJ3XJM.js";
28
+ } from "./chunk-2SN3UVSM.js";
29
29
  import "./chunk-RAX4SFCO.js";
30
30
 
31
31
  // src/index.ts
@@ -1394,6 +1394,7 @@ function getModelOverride(modelId) {
1394
1394
 
1395
1395
  // src/betas.ts
1396
1396
  var LONG_CONTEXT_BETAS = config.longContextBetas;
1397
+ var OAUTH_BETA = "oauth-2025-04-20";
1397
1398
  var excludedBetas = /* @__PURE__ */ new Map();
1398
1399
  var lastBetaFlagsEnv = process.env.ANTHROPIC_BETA_FLAGS;
1399
1400
  var lastModelId;
@@ -1417,6 +1418,19 @@ function addExcludedBeta(modelId, beta) {
1417
1418
  function isLongContextError(responseBody) {
1418
1419
  return responseBody.includes("Extra usage is required for long context requests") || responseBody.includes("long context beta is not yet available");
1419
1420
  }
1421
+ function isUnexpectedBetaError(responseBody) {
1422
+ return responseBody.includes("Unexpected value") && responseBody.includes("anthropic-beta");
1423
+ }
1424
+ function extractRejectedBetas(responseBody) {
1425
+ const match = /Unexpected value\(s\):\s*([^\n]+?)\s*for the anthropic-beta header/i.exec(responseBody);
1426
+ if (!match?.[1]) {
1427
+ return [];
1428
+ }
1429
+ return match[1].split(",").map((value) => value.trim().replace(/^['"]|['"]$/g, "")).filter(Boolean);
1430
+ }
1431
+ function ensureOauthBeta(betas) {
1432
+ return betas.includes(OAUTH_BETA) ? betas : [OAUTH_BETA, ...betas];
1433
+ }
1420
1434
  function getNextBetaToExclude(modelId) {
1421
1435
  const excluded = getExcludedBetas(modelId);
1422
1436
  for (const beta of LONG_CONTEXT_BETAS) {
@@ -1576,7 +1590,7 @@ var SESSION_IDLE_ROTATE_MS = 15 * 60 * 1e3;
1576
1590
  var MAX_TOOL_RESULT_TEXT_LENGTH = 30 * 1024;
1577
1591
  var TRUNCATION_SUFFIX = "[...truncated]";
1578
1592
  var DEFAULT_CONTEXT_MANAGEMENT = {};
1579
- var DEFAULT_OUTPUT_CONFIG = {};
1593
+ var DEFAULT_OUTPUT_CONFIG = { effort: "high" };
1580
1594
  var ORCHESTRATION_TAG_NAMES = [
1581
1595
  "system-reminder",
1582
1596
  "env",
@@ -1703,7 +1717,7 @@ function hasMeaningfulContent(content) {
1703
1717
  if (!isRecord2(block)) {
1704
1718
  return false;
1705
1719
  }
1706
- if (block.type === "tool_use") {
1720
+ if (block.type === "tool_use" || block.type === "tool_result") {
1707
1721
  return true;
1708
1722
  }
1709
1723
  if (typeof block.text === "string" && block.text.trim().length > 0) {
@@ -1736,13 +1750,46 @@ function compactMessageContent(messages) {
1736
1750
  if (block.type === "text") {
1737
1751
  return typeof block.text !== "string" || block.text.trim().length > 0;
1738
1752
  }
1739
- if (block.type === "tool_result" && Array.isArray(block.content)) {
1740
- return block.content.length > 0;
1741
- }
1742
1753
  return true;
1743
1754
  });
1744
1755
  }
1745
1756
  }
1757
+ function collectToolUseIds(message) {
1758
+ if (!Array.isArray(message.content)) {
1759
+ return [];
1760
+ }
1761
+ return message.content.filter((block) => isRecord2(block) && block.type === "tool_use" && typeof block.id === "string").map((block) => String(block.id));
1762
+ }
1763
+ function collectToolResultIds(message) {
1764
+ if (!Array.isArray(message.content)) {
1765
+ return /* @__PURE__ */ new Set();
1766
+ }
1767
+ return new Set(
1768
+ message.content.filter((block) => isRecord2(block) && block.type === "tool_result" && typeof block.tool_use_id === "string").map((block) => String(block.tool_use_id))
1769
+ );
1770
+ }
1771
+ function getDanglingToolUseError(messages) {
1772
+ for (let index = 0; index < messages.length; index += 1) {
1773
+ const current = messages[index];
1774
+ if (!current || current.role !== "assistant") {
1775
+ continue;
1776
+ }
1777
+ const toolUseIds = collectToolUseIds(current);
1778
+ if (toolUseIds.length === 0) {
1779
+ continue;
1780
+ }
1781
+ const next = messages[index + 1];
1782
+ if (!next || next.role !== "user") {
1783
+ return `Dangling tool_use after assistant turn ${index}: ${toolUseIds.join(", ")}`;
1784
+ }
1785
+ const toolResultIds = collectToolResultIds(next);
1786
+ const missing = toolUseIds.filter((toolUseId) => !toolResultIds.has(toolUseId));
1787
+ if (missing.length > 0) {
1788
+ return `Missing tool_result for assistant turn ${index}: ${missing.join(", ")}`;
1789
+ }
1790
+ }
1791
+ return null;
1792
+ }
1746
1793
  function stripUnsupportedSamplingFields(body) {
1747
1794
  delete body.temperature;
1748
1795
  delete body.top_p;
@@ -1758,7 +1805,7 @@ var ADAPTIVE_THINKING_MODEL_MATCHERS = [
1758
1805
  (modelId) => modelId.includes("claude-opus-4-6") || modelId.includes("claude-opus-4.6"),
1759
1806
  (modelId) => /claude-opus-4[-._]([7-9]|\d{2,})/.test(modelId)
1760
1807
  ];
1761
- var DEFAULT_MAX_OUTPUT_TOKENS = 64e3;
1808
+ var DEFAULT_MAX_OUTPUT_TOKENS = 32e3;
1762
1809
  function normalizeModelId2(modelId) {
1763
1810
  return modelId.trim().toLowerCase();
1764
1811
  }
@@ -1865,7 +1912,7 @@ function getCcVersion(template) {
1865
1912
  function buildBillingHeader(firstUserMessage, template) {
1866
1913
  const version = getCcVersion(template);
1867
1914
  const buildTag = computeBuildTag(firstUserMessage, version);
1868
- return `x-anthropic-billing-header: cc_version=${version}.${buildTag}; cc_entrypoint=cli; cch=00000;`;
1915
+ return `x-anthropic-billing-header: cc_version=${version}.${buildTag}; cc_entrypoint=sdk-cli; cch=00000;`;
1869
1916
  }
1870
1917
  function truncateToolResultText(text) {
1871
1918
  if (text.length <= MAX_TOOL_RESULT_TEXT_LENGTH) {
@@ -1934,6 +1981,9 @@ function sanitizeMessages(body) {
1934
1981
  block.text = sanitizeContent(block.text);
1935
1982
  }
1936
1983
  }
1984
+ message.content = message.content.filter((block) => {
1985
+ return !isRecord2(block) || block.type !== "text" || block.text !== "";
1986
+ });
1937
1987
  }
1938
1988
  }
1939
1989
  function scrubFrameworkIdentifiers(text) {
@@ -2112,25 +2162,8 @@ function shouldMaskToolName(name, claudeToolNames) {
2112
2162
  }
2113
2163
  return !claudeToolNames.has(name) && !name.startsWith("mcp__") && !name.startsWith(TOOL_MASK_PREFIX);
2114
2164
  }
2115
- function extractFirstUserText(parsed) {
2116
- if (!Array.isArray(parsed.messages)) {
2117
- return "";
2118
- }
2119
- const firstUser = parsed.messages.find((message) => message.role === "user");
2120
- if (!isRecord3(firstUser)) {
2121
- return "";
2122
- }
2123
- const content = firstUser.content;
2124
- if (typeof content === "string") {
2125
- return content.trim();
2126
- }
2127
- if (!Array.isArray(content)) {
2128
- return "";
2129
- }
2130
- return content.filter((block) => isRecord3(block) && block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join("\n\n").trim();
2131
- }
2132
- function buildMaskedToolName(seed, toolName, length = 8) {
2133
- const digest = createHash3("sha256").update(`tool-mask:${seed}:${toolName}`).digest("hex").slice(0, length);
2165
+ function buildMaskedToolName(toolName, length = 8) {
2166
+ const digest = createHash3("sha256").update(`tool-mask:${toolName}`).digest("hex").slice(0, length);
2134
2167
  return `${TOOL_MASK_PREFIX}${digest}`;
2135
2168
  }
2136
2169
  function collectToolNames(parsed) {
@@ -2165,7 +2198,6 @@ function buildClaudeToolNameSet(claudeToolNames) {
2165
2198
  function buildRequestScopedToolLookup(parsed, claudeToolNames) {
2166
2199
  const lookup = /* @__PURE__ */ new Map();
2167
2200
  const usedOutgoing = /* @__PURE__ */ new Set();
2168
- const seed = extractFirstUserText(parsed);
2169
2201
  const claudeToolSet = buildClaudeToolNameSet(claudeToolNames);
2170
2202
  for (const originalName of collectToolNames(parsed)) {
2171
2203
  if (!shouldMaskToolName(originalName, claudeToolSet)) {
@@ -2174,10 +2206,10 @@ function buildRequestScopedToolLookup(parsed, claudeToolNames) {
2174
2206
  continue;
2175
2207
  }
2176
2208
  let length = 8;
2177
- let masked = buildMaskedToolName(seed, originalName, length);
2209
+ let masked = buildMaskedToolName(originalName, length);
2178
2210
  while (usedOutgoing.has(masked)) {
2179
2211
  length += 2;
2180
- masked = buildMaskedToolName(seed, originalName, length);
2212
+ masked = buildMaskedToolName(originalName, length);
2181
2213
  }
2182
2214
  lookup.set(masked, originalName);
2183
2215
  usedOutgoing.add(masked);
@@ -2542,7 +2574,7 @@ function transformBodyToUpstream(body, identity, sessionId2) {
2542
2574
  try {
2543
2575
  const parsed = JSON.parse(body);
2544
2576
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
2545
- return { body, reverseLookup: /* @__PURE__ */ new Map() };
2577
+ return { body, reverseLookup: /* @__PURE__ */ new Map(), validationError: null };
2546
2578
  }
2547
2579
  const template = loadTemplate();
2548
2580
  const upstreamRequest = buildUpstreamRequest(
@@ -2551,9 +2583,16 @@ function transformBodyToUpstream(body, identity, sessionId2) {
2551
2583
  template,
2552
2584
  { sessionId: sessionId2 }
2553
2585
  );
2554
- return applyRequestToolMasking(upstreamRequest, template.tool_names);
2586
+ const validationError = getDanglingToolUseError(
2587
+ Array.isArray(upstreamRequest.messages) ? upstreamRequest.messages : []
2588
+ );
2589
+ const maskedRequest = applyRequestToolMasking(upstreamRequest, template.tool_names);
2590
+ return {
2591
+ ...maskedRequest,
2592
+ validationError
2593
+ };
2555
2594
  } catch {
2556
- return { body, reverseLookup: /* @__PURE__ */ new Map() };
2595
+ return { body, reverseLookup: /* @__PURE__ */ new Map(), validationError: null };
2557
2596
  }
2558
2597
  }
2559
2598
  async function applyResponseReverseLookup(response, reverseLookup) {
@@ -2665,11 +2704,11 @@ var AccountRuntimeFactory = class {
2665
2704
  return { accessToken: refreshed.patch.accessToken, expiresAt: refreshed.patch.expiresAt };
2666
2705
  }
2667
2706
  buildOutboundHeaders(incomingHeaders, sessionId2, accessToken, modelId, excludedBetas2) {
2668
- const mergedBetas = deduplicateBetas([
2707
+ const mergedBetas = deduplicateBetas(ensureOauthBeta([
2669
2708
  ...excludeBetas(splitBetaValues(getBetaHeader()), excludedBetas2),
2670
2709
  ...getModelBetas(modelId, excludedBetas2),
2671
2710
  ...excludeBetas(splitBetaValues(incomingHeaders["anthropic-beta"]), excludedBetas2)
2672
- ]).join(",");
2711
+ ])).join(",");
2673
2712
  const outbound = {
2674
2713
  ...incomingHeaders,
2675
2714
  ...getStaticHeaders(),
@@ -2697,7 +2736,18 @@ var AccountRuntimeFactory = class {
2697
2736
  void recordObservedToolNames(extractToolNamesFromRequestBody(init.body)).catch(() => {
2698
2737
  });
2699
2738
  }
2700
- const transformedRequest = typeof init?.body === "string" ? transformBodyToUpstream(init.body, this.identity, sessionId2) : { body: init?.body, reverseLookup: /* @__PURE__ */ new Map() };
2739
+ const transformedRequest = typeof init?.body === "string" ? transformBodyToUpstream(init.body, this.identity, sessionId2) : { body: init?.body, reverseLookup: /* @__PURE__ */ new Map(), validationError: null };
2740
+ if (transformedRequest.validationError) {
2741
+ return new Response(JSON.stringify({
2742
+ error: {
2743
+ message: transformedRequest.validationError,
2744
+ type: "invalid_request_error"
2745
+ }
2746
+ }), {
2747
+ status: 400,
2748
+ headers: { "content-type": "application/json" }
2749
+ });
2750
+ }
2701
2751
  const pacingCfg = resolvePacingConfig();
2702
2752
  const getNow = this.pacingTestOverrides.now ?? Date.now;
2703
2753
  const sleepFn = this.pacingTestOverrides.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
@@ -2740,14 +2790,24 @@ var AccountRuntimeFactory = class {
2740
2790
  break;
2741
2791
  }
2742
2792
  const responseBody = await response.clone().text();
2743
- if (!isLongContextError(responseBody)) {
2793
+ if (!isLongContextError(responseBody) && !isUnexpectedBetaError(responseBody)) {
2744
2794
  break;
2745
2795
  }
2746
- const betaToExclude = getNextBetaToExclude(modelId);
2747
- if (!betaToExclude) {
2748
- break;
2796
+ if (isUnexpectedBetaError(responseBody)) {
2797
+ const rejectedBetas = extractRejectedBetas(responseBody);
2798
+ if (rejectedBetas.length === 0) {
2799
+ break;
2800
+ }
2801
+ for (const rejectedBeta of rejectedBetas) {
2802
+ addExcludedBeta(modelId, rejectedBeta);
2803
+ }
2804
+ } else {
2805
+ const betaToExclude = getNextBetaToExclude(modelId);
2806
+ if (!betaToExclude) {
2807
+ break;
2808
+ }
2809
+ addExcludedBeta(modelId, betaToExclude);
2749
2810
  }
2750
- addExcludedBeta(modelId, betaToExclude);
2751
2811
  const retryHeaders = this.buildOutboundHeaders(
2752
2812
  incomingHeaders,
2753
2813
  sessionId2,
@@ -2932,7 +2992,7 @@ var EMPTY_OAUTH_CREDENTIALS = {
2932
2992
  if (process.env.CLAUDE_MULTI_ACCOUNT_TRACE_PLUGIN === "1") {
2933
2993
  console.error("[anthropic-multi-account] module loaded");
2934
2994
  }
2935
- function extractFirstUserText2(input) {
2995
+ function extractFirstUserText(input) {
2936
2996
  try {
2937
2997
  const raw = input;
2938
2998
  const messages = raw.messages ?? raw.request?.messages;
@@ -2952,7 +3012,7 @@ function extractFirstUserText2(input) {
2952
3012
  }
2953
3013
  function composeBillingSystemEntry(firstUserMessage, version) {
2954
3014
  const buildTag = computeBuildTag(firstUserMessage, version);
2955
- return `x-anthropic-billing-header: cc_version=${version}.${buildTag}; cc_entrypoint=cli; cch=00000;`;
3015
+ return `x-anthropic-billing-header: cc_version=${version}.${buildTag}; cc_entrypoint=sdk-cli; cch=00000;`;
2956
3016
  }
2957
3017
  function prependMissingSystemEntries(output, entries) {
2958
3018
  output.system ??= [];
@@ -3141,7 +3201,7 @@ var ClaudeMultiAuthPlugin = async (ctx) => {
3141
3201
  });
3142
3202
  return {
3143
3203
  "experimental.chat.system.transform": (input, output) => {
3144
- const billingHeader = composeBillingSystemEntry(extractFirstUserText2(input), claudeCodeVersion);
3204
+ const billingHeader = composeBillingSystemEntry(extractFirstUserText(input), claudeCodeVersion);
3145
3205
  prependMissingSystemEntries(output, [
3146
3206
  billingHeader,
3147
3207
  upstreamAgentIdentity,