@askalf/dario 6.22.1 → 6.22.3

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.
@@ -46,6 +46,14 @@ export function isAdvertisableToolDefinition(def) {
46
46
  const schema = def.input_schema;
47
47
  return !!schema && typeof schema === 'object' && typeof schema.type === 'string';
48
48
  }
49
+ /**
50
+ * A client entry for a tool Anthropic defines (`advisor_20260301`): it carries a
51
+ * `type` other than `custom` and no `input_schema`, because the definition lives
52
+ * on the server. Nothing can be remapped onto it and nothing can stand in for it.
53
+ */
54
+ function isAnthropicDefinedTool(def) {
55
+ return typeof def.type === 'string' && def.type !== 'custom';
56
+ }
49
57
  /** Names in the bundle whose definition is not advertisable (see above). Empty on a clean bake. */
50
58
  export const CC_TOOL_DEFINITIONS_UNADVERTISABLE = new Set(TEMPLATE.tools.filter((t) => !isAdvertisableToolDefinition(t)).map((t) => String(t.name)));
51
59
  /** CC's exact tool definitions for the current platform — filtered from the bundled union. */
@@ -765,6 +773,18 @@ export function detectNonCCByTools(clientTools) {
765
773
  // Union set, not the host-filtered one: a win32 client's PowerShell is
766
774
  // native regardless of the platform dario itself runs on (v4.8.136).
767
775
  if (CC_NATIVE_NAMES_UNION.has(rawName)) {
776
+ // A union name whose bundled definition is not advertisable is a server
777
+ // tool: CC never carries a client-callable schema for it (dario#1376).
778
+ // A client entry of that name that DOES declare an advertisable schema
779
+ // is the client's own tool wearing a CC name — count it unmapped and
780
+ // withhold native evidence, or one such entry suppresses every preserve
781
+ // route (`unmapped > 0 && !native`, and the skipped entry keeps the
782
+ // ratio below 0.8) and the whole surface goes to remap (#1812).
783
+ const foreignWearingCCName = CC_TOOL_DEFINITIONS_UNADVERTISABLE.has(rawName) && isAdvertisableToolDefinition(tool);
784
+ if (foreignWearingCCName) {
785
+ unmapped++;
786
+ continue;
787
+ }
768
788
  native = true;
769
789
  continue;
770
790
  }
@@ -1996,7 +2016,11 @@ export function buildCCRequest(clientBody, billingTag, cacheControl, identity, o
1996
2016
  // name, arguments untouched, renamed back on the response. A tool that
1997
2017
  // cannot be carried that way fails the request with its name.
1998
2018
  const CC_FALLBACK_TOOLS = ['Bash', 'Read', 'Grep', 'Glob', 'WebSearch', 'WebFetch'];
1999
- const namesCCTool = clientTools.some((t) => typeof t.name === 'string' && !isMcpToolName(t.name) && CC_TOOL_NAMES_LOWER.has(t.name.toLowerCase()));
2019
+ // An Anthropic-defined entry for a bundled name counts: it goes out on its
2020
+ // own, so the advertise step never reaches the template and a tool beside it
2021
+ // needs the MCP shape to be seen at all (#1812).
2022
+ const namesCCTool = clientTools.some((t) => typeof t.name === 'string' && !isMcpToolName(t.name) && (CC_TOOL_NAMES_LOWER.has(t.name.toLowerCase())
2023
+ || (CC_TOOL_DEFINITIONS_UNADVERTISABLE.has(t.name) && isAnthropicDefinedTool(t))));
2000
2024
  const declaredNames = new Set(clientTools.map((t) => t.name));
2001
2025
  const uncarried = [];
2002
2026
  for (const tool of clientTools) {
@@ -2246,12 +2270,19 @@ export function buildCCRequest(clientBody, billingTag, cacheControl, identity, o
2246
2270
  // `advisor` captured with an empty schema) is still identity-mapped
2247
2271
  // above; the only usable definition is the client's own, so it goes out
2248
2272
  // verbatim, as MCP tools do. The client's schema is what its parser
2249
- // expects back in any case.
2250
- const clientOwnNative = clientTools.filter((t) => typeof t.name === 'string' && CC_TOOL_DEFINITIONS_UNADVERTISABLE.has(t.name) && isAdvertisableToolDefinition(t));
2273
+ // expects back in any case. An Anthropic-defined entry has no schema, so
2274
+ // it is forwarded as declared; dropping it loses the declaration with no
2275
+ // error the client can see (#1812).
2276
+ const clientOwnNative = clientTools.filter((t) => typeof t.name === 'string' && CC_TOOL_DEFINITIONS_UNADVERTISABLE.has(t.name)
2277
+ && (isAdvertisableToolDefinition(t) || isAnthropicDefinedTool(t)));
2278
+ // CC sends its own tools in name order, so a client's definition of one
2279
+ // takes its place among them: `advisor` goes first, not after `Read`.
2280
+ const natives = [...availableCC, ...clientOwnNative]
2281
+ .sort((a, b) => String(a.name).localeCompare(String(b.name)));
2251
2282
  // Client tools outside CC's set follow the MCP tools, under the
2252
2283
  // MCP-shaped names the tool map gave them.
2253
- ccRequest.tools = availableCC.length > 0 || mcpTools.length > 0 || clientOwnNative.length > 0 || mcpShapedTools.length > 0
2254
- ? dedupeToolsByName([...availableCC, ...clientOwnNative, ...mcpTools, ...mcpShapedTools])
2284
+ ccRequest.tools = natives.length > 0 || mcpTools.length > 0 || mcpShapedTools.length > 0
2285
+ ? dedupeToolsByName([...natives, ...mcpTools, ...mcpShapedTools])
2255
2286
  : CC_TOOL_DEFINITIONS;
2256
2287
  }
2257
2288
  }
package/dist/proxy.js CHANGED
@@ -68,6 +68,7 @@ import { waitForIdle, drainThenClose, shutdownTimers, DEFAULT_SHUTDOWN_GRACE_MS
68
68
  import { clampTimerMs } from './timer-ms.js';
69
69
  import { upstreamDeadline } from './upstream-deadline.js';
70
70
  import { redactSecrets } from './redact.js';
71
+ import { parseRequestLogQuery, readRequestLog } from './request-log.js';
71
72
  import { BAKED_BASE_MODELS, withLongContextVariants, buildOpenAIModelsList, getModelCatalog, getCachedBases, resolveAliasAgainst, prewarmModelCatalog, retryModelCatalogNow, isSuspendedModel } from './model-catalog.js';
72
73
  import { classifyUpstreamRejection, diagnosticSnippet, POOL_PARKED } from './upstream-rejection.js';
73
74
  import { ProviderCooldowns, canAttempt, allProvidersCooled, cooldownRetryAfterMs, parseRetryAfterMs, ALL_PROVIDERS_RATE_LIMITED, } from './provider-cooldown.js';
@@ -1146,7 +1147,7 @@ export function sanitizeError(err) {
1146
1147
  * inherit read-only auth by accident.
1147
1148
  */
1148
1149
  export const ANALYTICS_READ_PATHS = [
1149
- '/analytics', '/analytics/ledger', '/analytics/stream', '/analytics/view', '/analytics/donuts.svg', '/metrics',
1150
+ '/analytics', '/analytics/ledger', '/analytics/requests', '/analytics/stream', '/analytics/view', '/analytics/donuts.svg', '/metrics',
1150
1151
  ];
1151
1152
  export function isAnalyticsReadPath(urlPath) {
1152
1153
  return ANALYTICS_READ_PATHS.includes(urlPath);
@@ -3369,6 +3370,27 @@ export async function startProxy(opts = {}) {
3369
3370
  res.end(JSON.stringify({ path: ledger.path, ...ledger.snapshot(), priced: ledger.priced() }));
3370
3371
  return;
3371
3372
  }
3373
+ // The request log read back by byte offset (request-log.ts), for a reader
3374
+ // that cannot share the file. A 404 says the log is off, as the ledger's does.
3375
+ if (urlPath === '/analytics/requests' && req.method === 'GET') {
3376
+ if (!logFilePath) {
3377
+ res.writeHead(404, JSON_HEADERS);
3378
+ res.end(JSON.stringify({ error: 'request log disabled', hint: 'start with --log-file=<path> / DARIO_LOG_FILE' }));
3379
+ return;
3380
+ }
3381
+ const { after, mark } = parseRequestLogQuery(req.url ?? '/');
3382
+ try {
3383
+ const page = await readRequestLog(logFilePath, after, mark);
3384
+ res.writeHead(200, JSON_HEADERS);
3385
+ res.end(JSON.stringify(page));
3386
+ }
3387
+ catch (err) {
3388
+ console.error(`[dario] request log read failed: ${sanitizeError(err)}`);
3389
+ res.writeHead(500, JSON_HEADERS);
3390
+ res.end(JSON.stringify({ error: 'request log unreadable' }));
3391
+ }
3392
+ return;
3393
+ }
3372
3394
  // Analytics live stream — SSE of new RequestRecord JSON, one event
3373
3395
  // per record as it lands. Drives the v4 TUI's Hits tab. Sends a
3374
3396
  // backlog of the most-recent 50 records on connect so a freshly-
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The `--log-file` request log by byte offset, for GET /analytics/requests.
3
+ *
4
+ * A page is whole lines. The last line of a read may still be on its way to
5
+ * disk, so anything after the final newline waits for the next read. A line too
6
+ * long for a page can never be served, so once it is complete it is passed over
7
+ * and counted, or a reader would stop there for good.
8
+ *
9
+ * An offset means nothing in a different file, and a replacement can be longer
10
+ * than the reader's offset, so the size alone cannot show it. Each page carries
11
+ * a mark, a hash of the first and last KiB of what has been read. A reader hands
12
+ * it back with the offset, and a mark that no longer matches sends it to the
13
+ * start. Every line opens with its own timestamp, so a different log differs at
14
+ * the head: that covers a rename, a truncation and a reused inode alike, where a
15
+ * file identity would miss a log truncated in place and grown past the offset.
16
+ *
17
+ * The log is append-only, and the mark is built on that. Hashing all of what has
18
+ * been read would cost a pass over the whole file per page, so an edit to the
19
+ * middle of it that keeps both ends is the one change this cannot see. Nothing in
20
+ * dario rewrites the file, and a rotation does not leave its first line in place.
21
+ */
22
+ export declare const REQUEST_LOG_PAGE_BYTES: number;
23
+ export interface RequestLogPage {
24
+ /** The file's size at this read. `size - next` is what is still unread. */
25
+ size: number;
26
+ /** The offset to ask for next. Equal to `after` when no whole line is ready. */
27
+ next: number;
28
+ /** Hand this back with `next`. Empty at the start of the file, where there is nothing to check. */
29
+ mark: string;
30
+ records: unknown[];
31
+ /** Whole lines that did not parse. They are passed over, and counted here so that is visible. */
32
+ unreadable: number;
33
+ }
34
+ /** `?after=` and `?mark=` from a request URL. Anything unusable reads as the start of the file. */
35
+ export declare function parseRequestLogQuery(url: string): {
36
+ after: number;
37
+ mark: string;
38
+ };
39
+ /**
40
+ * One page of the log from byte `after`. A log with nothing in it yet is an
41
+ * empty page, not an error. `pageBytes` is the caller's, never the request's.
42
+ */
43
+ export declare function readRequestLog(path: string, after?: number, mark?: string, pageBytes?: number): Promise<RequestLogPage>;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The `--log-file` request log by byte offset, for GET /analytics/requests.
3
+ *
4
+ * A page is whole lines. The last line of a read may still be on its way to
5
+ * disk, so anything after the final newline waits for the next read. A line too
6
+ * long for a page can never be served, so once it is complete it is passed over
7
+ * and counted, or a reader would stop there for good.
8
+ *
9
+ * An offset means nothing in a different file, and a replacement can be longer
10
+ * than the reader's offset, so the size alone cannot show it. Each page carries
11
+ * a mark, a hash of the first and last KiB of what has been read. A reader hands
12
+ * it back with the offset, and a mark that no longer matches sends it to the
13
+ * start. Every line opens with its own timestamp, so a different log differs at
14
+ * the head: that covers a rename, a truncation and a reused inode alike, where a
15
+ * file identity would miss a log truncated in place and grown past the offset.
16
+ *
17
+ * The log is append-only, and the mark is built on that. Hashing all of what has
18
+ * been read would cost a pass over the whole file per page, so an edit to the
19
+ * middle of it that keeps both ends is the one change this cannot see. Nothing in
20
+ * dario rewrites the file, and a rotation does not leave its first line in place.
21
+ */
22
+ import { createHash } from 'node:crypto';
23
+ import { open } from 'node:fs/promises';
24
+ export const REQUEST_LOG_PAGE_BYTES = 1024 * 1024;
25
+ /** Longer than a log line, so each end of a mark takes in a line's timestamp and request number. */
26
+ const MARK_BYTES = 1024;
27
+ /** `?after=` and `?mark=` from a request URL. Anything unusable reads as the start of the file. */
28
+ export function parseRequestLogQuery(url) {
29
+ const params = new URL(url, 'http://dario.invalid').searchParams;
30
+ const after = Number(params.get('after'));
31
+ return {
32
+ after: Number.isSafeInteger(after) && after > 0 ? after : 0,
33
+ mark: params.get('mark') ?? '',
34
+ };
35
+ }
36
+ async function markAt(file, offset) {
37
+ const length = Math.min(MARK_BYTES, offset);
38
+ if (length <= 0)
39
+ return '';
40
+ const hash = createHash('sha256');
41
+ const window = Buffer.alloc(MARK_BYTES);
42
+ for (const start of [0, offset - length]) {
43
+ const { bytesRead } = await file.read(window, 0, length, start);
44
+ hash.update(window.subarray(0, bytesRead));
45
+ }
46
+ return hash.digest('hex').slice(0, 32);
47
+ }
48
+ /** The offset just past the next newline at or after `from`, or null when none has reached disk yet. */
49
+ async function pastNextNewline(file, from, scratch) {
50
+ let at = from;
51
+ for (;;) {
52
+ const { bytesRead } = await file.read(scratch, 0, scratch.length, at);
53
+ if (bytesRead === 0)
54
+ return null;
55
+ const newline = scratch.subarray(0, bytesRead).indexOf(0x0a);
56
+ if (newline >= 0)
57
+ return at + newline + 1;
58
+ at += bytesRead;
59
+ }
60
+ }
61
+ /**
62
+ * One page of the log from byte `after`. A log with nothing in it yet is an
63
+ * empty page, not an error. `pageBytes` is the caller's, never the request's.
64
+ */
65
+ export async function readRequestLog(path, after = 0, mark = '', pageBytes = REQUEST_LOG_PAGE_BYTES) {
66
+ let file;
67
+ try {
68
+ file = await open(path, 'r');
69
+ }
70
+ catch (err) {
71
+ if (err.code === 'ENOENT')
72
+ return { size: 0, next: 0, mark: '', records: [], unreadable: 0 };
73
+ throw err;
74
+ }
75
+ try {
76
+ const { size } = await file.stat();
77
+ if (after > size || (after > 0 && mark && await markAt(file, after) !== mark)) {
78
+ return { size, next: 0, mark: '', records: [], unreadable: 0 };
79
+ }
80
+ const page = Buffer.alloc(pageBytes);
81
+ const { bytesRead } = await file.read(page, 0, pageBytes, after);
82
+ const end = page.subarray(0, bytesRead).lastIndexOf(0x0a);
83
+ if (end < 0) {
84
+ const past = bytesRead === pageBytes ? await pastNextNewline(file, after + pageBytes, page) : null;
85
+ if (past !== null)
86
+ return { size, next: past, mark: await markAt(file, past), records: [], unreadable: 1 };
87
+ return { size, next: after, mark: await markAt(file, after), records: [], unreadable: 0 };
88
+ }
89
+ const records = [];
90
+ let unreadable = 0;
91
+ for (const line of page.subarray(0, end).toString('utf-8').split('\n')) {
92
+ if (!line)
93
+ continue;
94
+ try {
95
+ records.push(JSON.parse(line));
96
+ }
97
+ catch {
98
+ unreadable++;
99
+ }
100
+ }
101
+ const next = after + end + 1;
102
+ return { size, next, mark: await markAt(file, next), records, unreadable };
103
+ }
104
+ finally {
105
+ await file.close();
106
+ }
107
+ }
package/docs/analytics.md CHANGED
@@ -11,6 +11,7 @@ Every surface below is a view over those two. Nothing here collects anything new
11
11
  | `GET /analytics` | window summary (with `window.perFiveMinutes`, the hour in twelve bins) + `queue` snapshot + `overage` (the halt state, for a reader who cannot open `/admin/resume`) + `lifetime` ledger summary | JSON |
12
12
  | `GET /analytics/ledger` | the ledger's per-day table, with `priced`: the same rows as USD at each day's rate | JSON |
13
13
  | `GET /analytics/stream` | live tail of request records (drives the TUI) | SSE |
14
+ | `GET /analytics/requests` | the `--log-file` request log by byte offset: `?after=<next>&mark=<mark>` gives `{ size, next, mark, records, unreadable }`, up to 1 MiB of whole lines. Hand back `next` and `mark` together. The mark covers the first and last KiB of what has been read: when it no longer matches, the file was replaced or truncated and `next` is 0. The log is append-only, so an edit to the middle of what was read that keeps both ends is not detected. Survives a restart, which the stream does not. 404 when the log is off | JSON |
14
15
  | `GET /metrics` | the same state as Prometheus text exposition | text/plain 0.0.4 |
15
16
  | `GET /analytics/donuts.svg` | spend by model / by key / by billing | SVG |
16
17
  | `GET /analytics/view` | the server-rendered summary (the page before 6.17; still served) | HTML fragment |
@@ -22,7 +22,7 @@
22
22
  | `GET /health` · `GET /livez` | Serviceability (503 when not) · liveness. `/health?probe=1` sends one real request |
23
23
  | `GET /status` · `GET /accounts` · `GET /analytics` | OAuth detail · per-seat utilization and grant age · per-account / per-model stats and burn rate |
24
24
  | `POST /v1/messages/count_tokens` · `POST /v1/complete` | Token counting and the legacy Text Completions shape |
25
- | `GET /analytics/stream` · `GET /analytics/ledger` · `GET /codex` | Live analytics over SSE · the ledger's per-day table · ChatGPT-seat status and utilisation (used %, window, reset, headroom), read without spending or exposing a token |
25
+ | `GET /analytics/stream` · `GET /analytics/requests` · `GET /analytics/ledger` · `GET /codex` | Live analytics over SSE · the `--log-file` request log by byte offset · the ledger's per-day table · ChatGPT-seat status and utilisation (used %, window, reset, headroom), read without spending or exposing a token |
26
26
  | `/admin/*` | Provisioning, `GET /admin/accounts`, `/admin/keys`, `POST /admin/resume`; only with `DARIO_ADMIN=1` ([admin API](admin-api.md)) |
27
27
 
28
28
  Flags: [commands.md](commands.md), plus `dario --help --all` for the ones it doesn't list yet (`--effort`, `--max-tokens`, `--model-alias`, `--fast-model`, session rotation, concurrency caps, the pacing knobs behind `--stealth`) · env vars grouped by task, for Docker / k8s / systemd: [configuration.md](configuration.md) · SDK examples: [usage.md](usage.md).
@@ -27,6 +27,8 @@ MCP tools take a third path: anything named `mcp__<server>__<tool>` is neither r
27
27
 
28
28
  A request that names Claude Code tools and also declares a tool outside `TOOL_MAP` (`Grep`, `Read`, `submit_review`) stays in remap, and the extra tool gets the MCP treatment: it goes out as `mcp__client__<name>` with the client's own schema, after the CC tools, and the model's calls come back under the client's name. Remap advertises only the CC tools such a request declares, so the fallback slot it used to ride was never on the wire. A tool that cannot be carried that way (an Anthropic-defined tool such as `computer_20251124`, a tool with no `input_schema`, or a name longer than 51 characters) fails the request with a 400 that names it. `--preserve-tools` forwards all of them verbatim instead.
29
29
 
30
+ Anthropic's `advisor` tool (`advisor_20260301`) is the exception. Its name is in Claude Code's own tool list and the bundle holds only a stub for it, so dario forwards the client's entry as declared and leaves any `server_tool_use` and `advisor_tool_result` blocks in the response untouched. This has not been verified against the live API. An Anthropic-defined entry whose name is in `TOOL_MAP` takes the mapped tool instead: `bash_20250124` becomes `Bash`, and `web_search_20250305` becomes Claude Code's client-side `WebSearch`, so that call comes back for the client to run (#1812).
31
+
30
32
  If your agent's tool names aren't pre-mapped and its tools carry fields CC's schema doesn't have, there are two escape hatches: **`--preserve-tools`** (forward your schema verbatim, lose the CC wire shape) or **`--hybrid-tools`** (keep the CC wire shape, fill request-context fields from headers). See [Custom tool schemas](#custom-tool-schemas).
31
33
 
32
34
  The OpenAI-compat backend forwards tool definitions byte-for-byte and doesn't need any of this.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@askalf/dario",
3
- "version": "6.22.1",
3
+ "version": "6.22.3",
4
4
  "description": "Use your Claude and ChatGPT subscriptions in Cursor, Cline, Aider, Claude Code and the Agent SDK at subscription pricing, not per-token API bills. One local Anthropic + OpenAI-compatible endpoint: either plan answers either wire shape, opt-in failover when one hits its limit, and a ledger of what each plan absorbed.",
5
5
  "type": "module",
6
6
  "bin": {