@askalf/dario 6.22.2 → 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.
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).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@askalf/dario",
3
- "version": "6.22.2",
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": {