@askalf/dario 4.8.144 → 4.8.146

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.
@@ -490,6 +490,27 @@ export declare const CC_CACHE_CONTROL: CacheControl;
490
490
  * Exported for unit testing.
491
491
  */
492
492
  export declare function applyCcPromptCaching(ccRequest: Record<string, unknown>, cacheControl: CacheControl): void;
493
+ /**
494
+ * Drop later tools whose exact name already appeared. Upstream rejects the
495
+ * whole request with 400 "tools: Tool names must be unique" on any repeat,
496
+ * so this is the last-line guard on the assembled advertise array — a
497
+ * polluted live template (see the mcp__ exclusion at the availableCC build)
498
+ * or a client double-declare degrades to first-wins instead of a hard
499
+ * request failure. Exported for tests.
500
+ */
501
+ export declare function dedupeToolsByName<T extends {
502
+ name?: unknown;
503
+ }>(tools: T[]): T[];
504
+ /**
505
+ * A genuine Claude Code client is identified by TWO markers together:
506
+ * the `x-anthropic-billing-header:` system block at [0] (the discriminator
507
+ * extractSystemText and extractTemplate key on) AND CC's own identity block
508
+ * at [1] ("You are Claude Code…" / the Claude Agent SDK variant). Requiring
509
+ * both keeps a non-CC framework that replays a billing-tagged body (e.g. a
510
+ * Kilo client behind a second proxy hop) on the detector path instead of
511
+ * passthrough. Exported for tests.
512
+ */
513
+ export declare function isGenuineCCClient(clientBody: Record<string, unknown>): boolean;
493
514
  export declare function buildCCRequest(clientBody: Record<string, unknown>, billingTag: string, cacheControl: CacheControl, identity: {
494
515
  deviceId: string;
495
516
  accountUuid: string;
@@ -510,6 +531,7 @@ export declare function buildCCRequest(clientBody: Record<string, unknown>, bill
510
531
  toolMap: Map<string, ToolMapping>;
511
532
  unmappedTools: string[];
512
533
  detectedClient?: string;
534
+ genuineCC?: boolean;
513
535
  };
514
536
  /**
515
537
  * Reverse-map CC tool calls in a non-streaming response back to the
@@ -1308,12 +1308,105 @@ export function applyCcPromptCaching(ccRequest, cacheControl) {
1308
1308
  }
1309
1309
  }
1310
1310
  }
1311
+ /**
1312
+ * Drop later tools whose exact name already appeared. Upstream rejects the
1313
+ * whole request with 400 "tools: Tool names must be unique" on any repeat,
1314
+ * so this is the last-line guard on the assembled advertise array — a
1315
+ * polluted live template (see the mcp__ exclusion at the availableCC build)
1316
+ * or a client double-declare degrades to first-wins instead of a hard
1317
+ * request failure. Exported for tests.
1318
+ */
1319
+ export function dedupeToolsByName(tools) {
1320
+ const seen = new Set();
1321
+ const out = [];
1322
+ for (const t of tools) {
1323
+ const name = typeof t.name === 'string' ? t.name : '';
1324
+ if (name && seen.has(name))
1325
+ continue;
1326
+ if (name)
1327
+ seen.add(name);
1328
+ out.push(t);
1329
+ }
1330
+ return out;
1331
+ }
1332
+ /**
1333
+ * A genuine Claude Code client is identified by TWO markers together:
1334
+ * the `x-anthropic-billing-header:` system block at [0] (the discriminator
1335
+ * extractSystemText and extractTemplate key on) AND CC's own identity block
1336
+ * at [1] ("You are Claude Code…" / the Claude Agent SDK variant). Requiring
1337
+ * both keeps a non-CC framework that replays a billing-tagged body (e.g. a
1338
+ * Kilo client behind a second proxy hop) on the detector path instead of
1339
+ * passthrough. Exported for tests.
1340
+ */
1341
+ export function isGenuineCCClient(clientBody) {
1342
+ const sys = clientBody.system;
1343
+ if (!Array.isArray(sys) || sys.length < 2)
1344
+ return false;
1345
+ const first = sys[0];
1346
+ if (typeof first?.text !== 'string' || !first.text.includes('x-anthropic-billing-header:'))
1347
+ return false;
1348
+ const second = sys[1];
1349
+ if (typeof second?.text !== 'string')
1350
+ return false;
1351
+ return second.text.startsWith('You are Claude Code') || second.text.includes('Claude Agent SDK');
1352
+ }
1311
1353
  export function buildCCRequest(clientBody, billingTag, cacheControl, identity, opts = {}) {
1312
1354
  const model = clientBody.model || 'claude-sonnet-5';
1313
1355
  const isHaiku = model.toLowerCase().includes('haiku');
1314
1356
  const messages = clientBody.messages || [];
1315
1357
  const clientTools = clientBody.tools;
1316
1358
  const stream = clientBody.stream ?? false;
1359
+ // ── Genuine Claude Code client → byte-faithful passthrough ──
1360
+ // A real CC request already IS the CC wire shape. Replacing its system
1361
+ // prompt with the template (prepending ~25KB per request shape) and
1362
+ // substituting template tool defs was pure duplication: it re-billed the
1363
+ // doubled prompt per shape per cache window (the residual +5%-vs-direct in
1364
+ // the dario#678 re-test), drifted the tool schemas whenever the client's CC
1365
+ // version differed from the template's, and round-robin-mangled natives the
1366
+ // `--print`-mode template capture never sees (AskUserQuestion, plan-mode
1367
+ // tools). Forward system blocks and tools verbatim. dario still owns:
1368
+ // - system[0]: dario's billing tag (consistent with dario's headers),
1369
+ // - metadata.user_id: dario's identity (the OAuth account is dario's,
1370
+ // not the client's),
1371
+ // - cache breakpoints: client stamps are stripped and re-placed (system
1372
+ // here, conversation in applyCcPromptCaching) so the 4-breakpoint
1373
+ // budget stays deterministic.
1374
+ // Messages, thinking, effort, max_tokens, top-level key order: untouched —
1375
+ // the client is the authority on its own wire shape. Outranks the
1376
+ // tool-mode flags: those configure how NON-CC clients are dressed up as
1377
+ // CC, which a genuine CC client doesn't need.
1378
+ if (isGenuineCCClient(clientBody)) {
1379
+ const clientSystem = clientBody.system;
1380
+ const system = clientSystem.map((b, i) => {
1381
+ const copy = { ...b };
1382
+ delete copy.cache_control;
1383
+ if (i === 0)
1384
+ copy.text = billingTag;
1385
+ return copy;
1386
+ });
1387
+ // Mirror CC's own placement: the identity + prompt blocks carry the
1388
+ // stamps (the last two non-billing blocks; a 2-block system stamps just
1389
+ // the last one).
1390
+ for (let i = Math.max(1, system.length - 2); i < system.length; i++) {
1391
+ system[i] = { ...system[i], cache_control: cacheControl };
1392
+ }
1393
+ for (const msg of messages) {
1394
+ if (Array.isArray(msg.content)) {
1395
+ for (const block of msg.content) {
1396
+ delete block.cache_control;
1397
+ }
1398
+ }
1399
+ }
1400
+ const body = { ...clientBody, system };
1401
+ body.metadata = {
1402
+ user_id: JSON.stringify({
1403
+ device_id: identity.deviceId,
1404
+ account_uuid: identity.accountUuid,
1405
+ session_id: identity.sessionId,
1406
+ }),
1407
+ };
1408
+ return { body, toolMap: new Map(), unmappedTools: [], genuineCC: true };
1409
+ }
1317
1410
  // ── Detect text-tool-protocol clients up-front ──
1318
1411
  // Cline / Kilo Code / Roo Code (and forks) ship an XML tool-invocation
1319
1412
  // protocol in the system prompt. Peek at it before scrubbing so the
@@ -1648,10 +1741,20 @@ export function buildCCRequest(clientBody, billingTag, cacheControl, identity, o
1648
1741
  // declaration encodes the client's platform, so a win32 CC declaring
1649
1742
  // PowerShell/Glob/Grep gets their canonical defs even from a Linux-hosted
1650
1743
  // dario. The host filter only governs the no-declaration fallbacks.
1651
- const availableCC = CC_TOOL_DEFINITIONS_UNION.filter((t) => clientToolNames.has(t.name.toLowerCase()));
1744
+ //
1745
+ // mcp__* entries are EXCLUDED from the template side: a live capture on
1746
+ // a machine with MCP servers configured absorbs the capture session's
1747
+ // mcp__* tools into the template (the dario#678 reporter's doctor showed
1748
+ // 138 tool defs — ~111 of them MCP pollution), and any client-declared
1749
+ // MCP tool whose name also sat in the polluted union then went out
1750
+ // TWICE (template def + verbatim client schema) — upstream rejects the
1751
+ // whole request with 400 "tools: Tool names must be unique". MCP
1752
+ // schemas are operator-supplied; the client's declaration is the only
1753
+ // authoritative source, never the template.
1754
+ const availableCC = CC_TOOL_DEFINITIONS_UNION.filter((t) => !isMcpToolName(t.name) && clientToolNames.has(t.name.toLowerCase()));
1652
1755
  const mcpTools = clientTools.filter((t) => isMcpToolName(t.name));
1653
1756
  ccRequest.tools = availableCC.length > 0 || mcpTools.length > 0
1654
- ? [...availableCC, ...mcpTools]
1757
+ ? dedupeToolsByName([...availableCC, ...mcpTools])
1655
1758
  : CC_TOOL_DEFINITIONS;
1656
1759
  }
1657
1760
  }
@@ -220,6 +220,17 @@ function readLiveCache() {
220
220
  quarantineCorruptCache('missing required fields (system_prompt / tools)');
221
221
  return null;
222
222
  }
223
+ // Pre-4.8.145 captures baked the operator's mcp__* tools into the template
224
+ // (dario#678 regression: duplicate tool names → upstream 400). The capture
225
+ // path filters them now, but a polluted cache written by an older dario
226
+ // sits on disk until something rewrites it — its junk union and inflated
227
+ // doctor Overhead numbers persist (the #678 reporter's cache showed 138
228
+ // tool defs, ~111 of them MCP). Quarantine on load; the background refresh
229
+ // re-captures clean.
230
+ if (parsed.tools.some((t) => typeof t?.name === 'string' && t.name.startsWith('mcp__'))) {
231
+ quarantineCorruptCache('mcp__ tool pollution (pre-4.8.145 capture)');
232
+ return null;
233
+ }
223
234
  // Schema version mismatch is NOT corruption — it's an expected event on
224
235
  // dario upgrade or downgrade. Skip the cache silently; the background
225
236
  // refresh will rewrite it in the new shape.
@@ -550,9 +561,18 @@ export function extractTemplate(captured) {
550
561
  const systemPrompt = pickTextBlock(systemBlocks[2]);
551
562
  if (!agentIdentity || !systemPrompt)
552
563
  return null;
564
+ // mcp__* tools are EXCLUDED from the template: the capture spawns the
565
+ // operator's own CC, and on a machine with MCP servers configured the
566
+ // captured request declares their mcp__<server>__<tool> schemas — session
567
+ // config, not CC wire shape. Baking them poisoned CC_TOOL_DEFINITIONS_UNION
568
+ // and duplicated any client-declared MCP tool on the advertise path
569
+ // (template def + verbatim client schema), which upstream rejects with
570
+ // 400 "tools: Tool names must be unique" (dario#678 follow-up). Local
571
+ // startsWith mirror of cc-template's isMcpToolName — importing it here
572
+ // would cycle (cc-template imports loadTemplate from this module).
553
573
  const tools = Array.isArray(body.tools)
554
574
  ? body.tools
555
- .filter((t) => typeof t.name === 'string')
575
+ .filter((t) => typeof t.name === 'string' && !t.name.startsWith('mcp__'))
556
576
  .map((t) => ({
557
577
  name: t.name,
558
578
  description: t.description ?? '',
package/dist/proxy.d.ts CHANGED
@@ -64,8 +64,10 @@ export declare const CLAUDE_CODE_BETA = "claude-code-20250219";
64
64
  * it, ORDER included:
65
65
  *
66
66
  * opus-4-8 = base (unchanged)
67
- * sonnet-5 = base − {mid-conversation-system} (CC 2.1.201 dropped it
68
- * from sonnet; 2.1.199 sonnet == opus and still kept it — #667)
67
+ * sonnet-5 = base (== opus wire-drift
68
+ * live capture, CC 2.1.204: mid-conversation-system included)
69
+ * sonnet-4-x = base − {mid-conversation-system} (CC 2.1.201 dropped it
70
+ * from sonnet 4.6; 2.1.199 sonnet == opus and still kept it — #667)
69
71
  * haiku-4-5 = base − {mid-conversation-system, effort, afk-mode}, and
70
72
  * claude-code-20250219 MOVED to position 5 (before advisor-tool)
71
73
  * fable-5 = base + fallback-credit-2026-06-01 inserted BEFORE afk-mode
package/dist/proxy.js CHANGED
@@ -323,8 +323,10 @@ function moveBetaBefore(flags, flag, anchor) {
323
323
  * it, ORDER included:
324
324
  *
325
325
  * opus-4-8 = base (unchanged)
326
- * sonnet-5 = base − {mid-conversation-system} (CC 2.1.201 dropped it
327
- * from sonnet; 2.1.199 sonnet == opus and still kept it — #667)
326
+ * sonnet-5 = base (== opus wire-drift
327
+ * live capture, CC 2.1.204: mid-conversation-system included)
328
+ * sonnet-4-x = base − {mid-conversation-system} (CC 2.1.201 dropped it
329
+ * from sonnet 4.6; 2.1.199 sonnet == opus and still kept it — #667)
328
330
  * haiku-4-5 = base − {mid-conversation-system, effort, afk-mode}, and
329
331
  * claude-code-20250219 MOVED to position 5 (before advisor-tool)
330
332
  * fable-5 = base + fallback-credit-2026-06-01 inserted BEFORE afk-mode
@@ -353,9 +355,11 @@ export function betaForModel(base, model, skipContext1m = false) {
353
355
  flags = flags.filter((f) => !drop.has(f));
354
356
  flags = moveBetaBefore(flags, CLAUDE_CODE_BETA, ADVISOR_TOOL_BETA);
355
357
  }
356
- else if (m.includes('sonnet')) {
357
- // CC 2.1.201 dropped mid-conversation-system from sonnet's beta set (2.1.199
358
- // sonnet == opus and still carried it — live capture #667). opus + fable keep it.
358
+ else if (/sonnet-4/.test(m)) {
359
+ // CC 2.1.201 dropped mid-conversation-system from SONNET 4.6's beta set
360
+ // (2.1.199 sonnet == opus and still carried it — live capture #667).
361
+ // Scoped to the sonnet-4 line: Sonnet 5 carries it again — the wire-drift
362
+ // runner's live capture on CC 2.1.204 shows sonnet-5's set equal to opus's.
359
363
  flags = flags.filter((f) => f !== MID_CONVERSATION_SYSTEM_BETA);
360
364
  }
361
365
  else if (m.includes('fable')) {
@@ -894,6 +898,8 @@ export async function startProxy(opts = {}) {
894
898
  const toolSubLogged = new Set();
895
899
  // Same de-dup contract for the verbose-only MCP-passthrough note.
896
900
  const mcpPassthroughLogged = new Set();
901
+ // One-shot log for the genuine-CC byte-faithful passthrough path.
902
+ let ccPassthroughLogged = false;
897
903
  // Body-dump mode: set via --verbose=2 / -vv or DARIO_LOG_BODIES=1.
898
904
  // When on, every request emits a redacted JSON body to stderr so
899
905
  // operators can see exactly what dario forwards upstream. Default
@@ -2091,7 +2097,7 @@ export async function startProxy(opts = {}) {
2091
2097
  const bodyIdentity = poolAccount
2092
2098
  ? poolAccount.identity
2093
2099
  : { deviceId: identity.deviceId, accountUuid: identity.accountUuid, sessionId: preBodySessionId };
2094
- const { body: ccBody, toolMap, detectedClient, unmappedTools } = buildCCRequest(r, billingTag, CACHE_EPHEMERAL, bodyIdentity, {
2100
+ const { body: ccBody, toolMap, detectedClient, unmappedTools, genuineCC } = buildCCRequest(r, billingTag, CACHE_EPHEMERAL, bodyIdentity, {
2095
2101
  preserveTools: opts.preserveTools ?? false,
2096
2102
  hybridTools: opts.hybridTools ?? false,
2097
2103
  mergeTools: opts.mergeTools ?? false,
@@ -2113,8 +2119,15 @@ export async function startProxy(opts = {}) {
2113
2119
  applyCcPromptCaching(ccBody, CACHE_EPHEMERAL);
2114
2120
  }
2115
2121
  detectedClientForLog = detectedClient;
2122
+ // genuineCC → the client's own tool schemas went out verbatim, so
2123
+ // the response path must not rewrite tool names either.
2116
2124
  preserveToolsEffective = Boolean(opts.preserveTools)
2125
+ || Boolean(genuineCC)
2117
2126
  || (Boolean(detectedClient) && !opts.hybridTools && !opts.mergeTools);
2127
+ if (genuineCC && !ccPassthroughLogged) {
2128
+ ccPassthroughLogged = true;
2129
+ console.log('[dario] genuine Claude Code client — system + tools forwarded verbatim (byte-faithful passthrough)');
2130
+ }
2118
2131
  // Log the auto-preserve-tools switch once per text-tool
2119
2132
  // client family. Skip when the operator already opted into
2120
2133
  // --preserve-tools or --hybrid-tools — they know what they
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@askalf/dario",
3
- "version": "4.8.144",
3
+ "version": "4.8.146",
4
4
  "description": "Use your Claude Pro/Max subscription in any tool — Cursor, Cline, Aider, the Agent SDK, your scripts — at subscription pricing, not per-token API bills. One local Anthropic + OpenAI-compatible endpoint.",
5
5
  "type": "module",
6
6
  "bin": {