@askalf/dario 4.8.145 → 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.
@@ -501,6 +501,16 @@ export declare function applyCcPromptCaching(ccRequest: Record<string, unknown>,
501
501
  export declare function dedupeToolsByName<T extends {
502
502
  name?: unknown;
503
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;
504
514
  export declare function buildCCRequest(clientBody: Record<string, unknown>, billingTag: string, cacheControl: CacheControl, identity: {
505
515
  deviceId: string;
506
516
  accountUuid: string;
@@ -521,6 +531,7 @@ export declare function buildCCRequest(clientBody: Record<string, unknown>, bill
521
531
  toolMap: Map<string, ToolMapping>;
522
532
  unmappedTools: string[];
523
533
  detectedClient?: string;
534
+ genuineCC?: boolean;
524
535
  };
525
536
  /**
526
537
  * Reverse-map CC tool calls in a non-streaming response back to the
@@ -1329,12 +1329,84 @@ export function dedupeToolsByName(tools) {
1329
1329
  }
1330
1330
  return out;
1331
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
+ }
1332
1353
  export function buildCCRequest(clientBody, billingTag, cacheControl, identity, opts = {}) {
1333
1354
  const model = clientBody.model || 'claude-sonnet-5';
1334
1355
  const isHaiku = model.toLowerCase().includes('haiku');
1335
1356
  const messages = clientBody.messages || [];
1336
1357
  const clientTools = clientBody.tools;
1337
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
+ }
1338
1410
  // ── Detect text-tool-protocol clients up-front ──
1339
1411
  // Cline / Kilo Code / Roo Code (and forks) ship an XML tool-invocation
1340
1412
  // protocol in the system prompt. Peek at it before scrubbing so the
@@ -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.
package/dist/proxy.js CHANGED
@@ -898,6 +898,8 @@ export async function startProxy(opts = {}) {
898
898
  const toolSubLogged = new Set();
899
899
  // Same de-dup contract for the verbose-only MCP-passthrough note.
900
900
  const mcpPassthroughLogged = new Set();
901
+ // One-shot log for the genuine-CC byte-faithful passthrough path.
902
+ let ccPassthroughLogged = false;
901
903
  // Body-dump mode: set via --verbose=2 / -vv or DARIO_LOG_BODIES=1.
902
904
  // When on, every request emits a redacted JSON body to stderr so
903
905
  // operators can see exactly what dario forwards upstream. Default
@@ -2095,7 +2097,7 @@ export async function startProxy(opts = {}) {
2095
2097
  const bodyIdentity = poolAccount
2096
2098
  ? poolAccount.identity
2097
2099
  : { deviceId: identity.deviceId, accountUuid: identity.accountUuid, sessionId: preBodySessionId };
2098
- 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, {
2099
2101
  preserveTools: opts.preserveTools ?? false,
2100
2102
  hybridTools: opts.hybridTools ?? false,
2101
2103
  mergeTools: opts.mergeTools ?? false,
@@ -2117,8 +2119,15 @@ export async function startProxy(opts = {}) {
2117
2119
  applyCcPromptCaching(ccBody, CACHE_EPHEMERAL);
2118
2120
  }
2119
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.
2120
2124
  preserveToolsEffective = Boolean(opts.preserveTools)
2125
+ || Boolean(genuineCC)
2121
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
+ }
2122
2131
  // Log the auto-preserve-tools switch once per text-tool
2123
2132
  // client family. Skip when the operator already opted into
2124
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.145",
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": {