@askalf/dario 6.0.12 → 6.0.14

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.
@@ -60,6 +60,12 @@ export interface CodexForwardOutcome {
60
60
  model: string;
61
61
  alias: string;
62
62
  }
63
+ /** Why a forward DECLINED, for the caller's cool-down bookkeeping. `status` is
64
+ * the upstream status, or 0 when the request never got one (transport). */
65
+ export interface CodexDecline {
66
+ status: number;
67
+ retryAfterMs: number | null;
68
+ }
63
69
  /** The cached slug list for an alias WITHOUT fetching. For the admin surface:
64
70
  * a status read must never cost an upstream call or a token refresh. */
65
71
  export declare function peekCodexModelSlugs(alias: string): readonly string[] | null;
@@ -216,4 +222,4 @@ export declare function buildCodexHeaders(creds: CodexAccountCredentials): Recor
216
222
  * testable without network (test/codex-backend.mjs), matching the pattern
217
223
  * test/codex-oauth.mjs already uses.
218
224
  */
219
- export declare function forwardToCodex(req: IncomingMessage, res: ServerResponse, body: Buffer, creds: CodexAccountCredentials, corsOrigin: string, securityHeaders: Record<string, string>, upstreamTimeoutMs: number, verbose: boolean, shape?: CodexRequestShape, fetchImpl?: typeof fetch, deferOnUnavailable?: boolean, onDone?: (outcome: CodexForwardOutcome) => void): Promise<boolean>;
225
+ export declare function forwardToCodex(req: IncomingMessage, res: ServerResponse, body: Buffer, creds: CodexAccountCredentials, corsOrigin: string, securityHeaders: Record<string, string>, upstreamTimeoutMs: number, verbose: boolean, shape?: CodexRequestShape, fetchImpl?: typeof fetch, deferOnUnavailable?: boolean, onDone?: (outcome: CodexForwardOutcome) => void, onDecline?: (info: CodexDecline) => void): Promise<boolean>;
@@ -1,6 +1,7 @@
1
1
  import { anthropicToResponsesRequest, createResponsesSSEParser, formatResponsesAnthropicSSE, createAnthropicMessageAssembler, responsesStreamToAnthropicSSE, } from './anthropic-responses-translate.js';
2
2
  import { resolveClaudeTarget } from './claude-model.js';
3
3
  import { BAKED_BASE_MODELS } from './model-catalog.js';
4
+ import { parseRetryAfterMs } from './provider-cooldown.js';
4
5
  export const CODEX_BACKEND_BASE_URL = process.env.DARIO_CODEX_BASE_URL || 'https://chatgpt.com/backend-api/codex';
5
6
  /** Originator string the codex CLI identifies itself with. */
6
7
  const CODEX_ORIGINATOR = 'codex_cli_rs';
@@ -518,7 +519,7 @@ export function buildCodexHeaders(creds) {
518
519
  * testable without network (test/codex-backend.mjs), matching the pattern
519
520
  * test/codex-oauth.mjs already uses.
520
521
  */
521
- export async function forwardToCodex(req, res, body, creds, corsOrigin, securityHeaders, upstreamTimeoutMs, verbose, shape = 'openai', fetchImpl = fetch, deferOnUnavailable = false, onDone) {
522
+ export async function forwardToCodex(req, res, body, creds, corsOrigin, securityHeaders, upstreamTimeoutMs, verbose, shape = 'openai', fetchImpl = fetch, deferOnUnavailable = false, onDone, onDecline) {
522
523
  void req;
523
524
  const isAnthropic = shape === 'anthropic';
524
525
  // Reported exactly once, on every exit that answered the client. Without
@@ -580,6 +581,14 @@ export async function forwardToCodex(req, res, body, creds, corsOrigin, security
580
581
  const unavailable = upstream.status === 429 || upstream.status >= 500;
581
582
  if (deferOnUnavailable && unavailable) {
582
583
  console.log(`[dario] codex account ${creds.alias} unavailable (${upstream.status}) — deferring to the next provider`);
584
+ // A decline is the only exit that tells the caller nothing was served,
585
+ // and until now it carried no WHY: a 429 and a 503 were the same false.
586
+ // The chain needs the status (to cool a rate limit but not an outage)
587
+ // and the upstream's own `retry-after` (to cool it for the right long).
588
+ try {
589
+ onDecline?.({ status: upstream.status, retryAfterMs: parseRetryAfterMs(upstream.headers.get('retry-after')) });
590
+ }
591
+ catch { /* a reporting failure must never break a declined request */ }
583
592
  return false;
584
593
  }
585
594
  res.writeHead(upstream.status, { 'Content-Type': 'application/json', ...securityHeaders });
@@ -737,6 +746,12 @@ export async function forwardToCodex(req, res, body, creds, corsOrigin, security
737
746
  // the request to anyone else.
738
747
  if (deferOnUnavailable && !res.headersSent) {
739
748
  console.log(`[dario] codex account ${creds.alias} unreachable (${detail}) — deferring to the next provider`);
749
+ // status 0: no HTTP status ever arrived. Reported so the caller can tell
750
+ // an outage from a rate limit — an unreachable backend is not quota.
751
+ try {
752
+ onDecline?.({ status: 0, retryAfterMs: null });
753
+ }
754
+ catch { /* as above */ }
740
755
  return false;
741
756
  }
742
757
  if (!res.headersSent) {
@@ -0,0 +1,239 @@
1
+ /**
2
+ * dario doctor — health report aggregator.
3
+ *
4
+ * Runs every check we know how to run and returns a list of labelled
5
+ * results. The CLI passes the result list through `formatChecks` for
6
+ * display; `runChecks` is the I/O-heavy collector, `formatChecks` is a
7
+ * pure function the tests exercise directly.
8
+ *
9
+ * Keep `runChecks` defensive: a check that throws must not take the
10
+ * rest of the report down — every check is wrapped so a broken sub-
11
+ * system surfaces as `fail` instead of crashing the CLI.
12
+ */
13
+ export type CheckStatus = 'ok' | 'warn' | 'fail' | 'info';
14
+ export interface Check {
15
+ /** 'ok' passes; 'warn' is advisory; 'fail' blocks (exit code 1); 'info' is neutral. */
16
+ status: CheckStatus;
17
+ /** Short left-column label, e.g. `"Node"`, `"CC binary"`. */
18
+ label: string;
19
+ /** Right-column detail — human readable, may include versions, paths, counts. */
20
+ detail: string;
21
+ }
22
+ /**
23
+ * Decide what `doctor` should say about pool-exhaustion failover, from
24
+ * configuration alone. Pure and exported so every branch is testable — the
25
+ * live box can only ever exercise the one that matches its own credentials,
26
+ * which is how the inert case went unnoticed in the first place.
27
+ *
28
+ * This check exists because of a specific outage. The box ran with
29
+ * --pool-fallback armed, no Codex account and no api-key backend, so failover
30
+ * was INERT: correctly configured by every check that existed, and incapable of
31
+ * doing anything. On 2026-08-29 the Claude pool filled twice and the fleet went
32
+ * dark beside an idle ChatGPT subscription. Nothing reported it, because
33
+ * nothing asked "armed" and "has somewhere to go" as a single question.
34
+ *
35
+ * It reports configuration, never reachability. Claiming a route WORKS needs a
36
+ * live request, and this release was built on the lesson that a green config is
37
+ * not a working path.
38
+ */
39
+ export declare function failoverReadiness(input: {
40
+ chain: readonly string[];
41
+ codexAccounts: number;
42
+ backends: readonly string[];
43
+ }): {
44
+ status: CheckStatus;
45
+ detail: string;
46
+ };
47
+ /**
48
+ * Format a epoch timestamp reset time relative to the current time.
49
+ * Returns a human-friendly string like "1h 9m", "45m", "2d 3h".
50
+ */
51
+ export declare function formatReset(resetEpochSecs: number, nowMs: number): string;
52
+ /**
53
+ * Pretty-print a list of Check results as aligned ASCII. No color codes —
54
+ * Windows cmd / CI logs render plain text reliably; colors are a downside
55
+ * not an upside for a report that's often piped or pasted.
56
+ */
57
+ export declare function formatChecks(checks: Check[]): string;
58
+ /**
59
+ * Derive a CLI exit code from a set of check results. Any `fail` → 1.
60
+ * `warn` alone does not fail — we don't want `dario doctor` to CI-fail
61
+ * a user's machine just because they're on an untested CC version.
62
+ */
63
+ export declare function exitCodeFor(checks: Check[]): number;
64
+ /**
65
+ * Serialize a check report as structured JSON. Lets other tools
66
+ * (claude-bridge's /status command, deepdive, CI scripts) consume
67
+ * dario's health programmatically instead of scraping the formatted
68
+ * text. Emitted by `dario doctor --json`.
69
+ */
70
+ export declare function formatChecksJson(checks: Check[]): string;
71
+ /**
72
+ * Pure function: compare each pool account's stored {deviceId, accountUuid}
73
+ * against the live `.claude.json` identity and return Check rows describing
74
+ * any drift. Factored out of runChecks so it's unit-testable without I/O.
75
+ *
76
+ * Drift surfaces when a user re-installs Claude Code (or switches the active
77
+ * account inside CC) AFTER `dario accounts add`, so the stored snapshot in
78
+ * `~/.dario/accounts/<alias>.json` no longer matches what the proxy reads
79
+ * live from `~/.claude.json` per request. Anthropic cross-validates the
80
+ * OAuth bearer against `metadata.user_id` (built from the live deviceId)
81
+ * and 401s with `authentication_error` on non-Haiku models when they
82
+ * disagree — Haiku is more permissive and may succeed despite the mismatch,
83
+ * which makes the failure mode look intermittent and account-tier-shaped
84
+ * even though it's an identity-staleness bug.
85
+ *
86
+ * Single-account mode (no pool, just `~/.dario/credentials.json`) is not
87
+ * covered here: the proxy reads identity live and dario never stored a
88
+ * baseline to compare against. Future: add `dario doctor --identity` for
89
+ * an opt-in network probe that hits Anthropic with the bearer and live
90
+ * deviceId to confirm they align.
91
+ */
92
+ export interface IdentityDriftInput {
93
+ /** Live `{deviceId, accountUuid}` from `~/.claude.json`, or null if absent. */
94
+ live: {
95
+ deviceId: string;
96
+ accountUuid: string;
97
+ } | null;
98
+ /** Pool account snapshots — `[]` when no pool accounts are materialized yet. */
99
+ poolAccounts: Array<{
100
+ alias: string;
101
+ deviceId: string;
102
+ accountUuid: string;
103
+ }>;
104
+ }
105
+ /**
106
+ * The OAuth doctor row, as a pure decision — mirrors checkIdentityDrift so the
107
+ * branch logic is unit-testable without touching the filesystem.
108
+ *
109
+ * WHY THIS EXISTS. The legacy `credentials.json` is not what serves once an
110
+ * account pool exists: dario#805 deliberately keeps a NEWER pool token and
111
+ * refuses to overwrite that file, so "credentials.json is stale" is an expected
112
+ * steady state — every recovery that restores a pool account leaves one behind.
113
+ * Reporting that as `OAuth expired` while the pool answers every request is a
114
+ * false alarm, and dario-doctor-watch opens an issue for it on EVERY run:
115
+ * dario#1105 was filed while a live probe was returning 200 on both Haiku and
116
+ * Sonnet. A watcher that cries wolf on a healthy proxy trains its reader to
117
+ * ignore it, which is the failure the watcher exists to prevent.
118
+ *
119
+ * So: a live pool overrides a dead legacy file (and says so, rather than hiding
120
+ * it), and only "nothing can serve" is reported as a failure.
121
+ */
122
+ export declare function oauthCheckRow(input: {
123
+ legacyStatus: string;
124
+ legacyCanRefresh: boolean;
125
+ poolHealthy: number;
126
+ poolTotal: number;
127
+ }): Check;
128
+ export declare function checkIdentityDrift(input: IdentityDriftInput): Check[];
129
+ export declare function probeNpmLatestCC(): string | null;
130
+ /**
131
+ * The client system prompt the `--obedience` probe sends. Deliberately
132
+ * trivial: any model that weighs client system text at all can comply,
133
+ * so a miss isolates "the client system prompt is being ignored" from
134
+ * "the instruction was too hard".
135
+ */
136
+ export declare const OBEDIENCE_SYSTEM_PROMPT = "Reply with ONLY the word PONG. No other words, no punctuation, no formatting.";
137
+ /**
138
+ * Join the text blocks of a `/v1/messages` response body. Thinking
139
+ * blocks are excluded — adaptive thinking may prepend them and they are
140
+ * not part of what the client-facing instruction governs. A refusal
141
+ * (empty content) or a malformed body yields ''.
142
+ */
143
+ export declare function extractMessageText(body: unknown): string;
144
+ /**
145
+ * Verdict for one obedience reply. Lenient on case and a single trailing
146
+ * `.`/`!` — the drift class this detects is "the model ignored the client
147
+ * system prompt entirely" (it answers as the CC persona instead), and a
148
+ * stray "Pong!" is obedient in substance. Strict equality would file
149
+ * 6-hourly drift issues over punctuation sampling.
150
+ */
151
+ export declare function isObedientReply(text: string): boolean;
152
+ export interface RunChecksOptions {
153
+ /**
154
+ * Opt-in: hit Anthropic's authorize endpoint with the scope set dario
155
+ * would use on `accounts add`, and surface the server's verdict as a
156
+ * check row. Default off — `dario doctor` without `--probe` is a
157
+ * read-only local scan, no outbound traffic beyond what the other
158
+ * checks already make (OAuth token refresh, CC binary version probe,
159
+ * npm drift check). Enable with `dario doctor --probe`; costs one
160
+ * GET to `claude.ai` and runs in parallel with the other checks.
161
+ */
162
+ probe?: boolean;
163
+ /**
164
+ * Opt-in: fire a minimal `POST /v1/messages` through the user's OAuth
165
+ * (Haiku, `max_tokens=1`) to capture the current rate-limit snapshot,
166
+ * including the unified buckets AND the per-model buckets Anthropic
167
+ * started carving in late April 2026 (`7d_sonnet-utilization` etc).
168
+ * Surfaces "All models X%, Sonnet only Y%" the way the user dashboard
169
+ * does. Enable with `dario doctor --usage`; costs ~1 subscription
170
+ * request.
171
+ */
172
+ usage?: boolean;
173
+ /**
174
+ * Opt-in: probe each model family THROUGH the running proxy with a
175
+ * client system prompt ("reply with ONLY the word PONG") and assert
176
+ * the reply obeys. Catches upstream behavioral drift in client-system
177
+ * steering — the 2026-06-12 class (dario#509) where sonnet silently
178
+ * stopped following client system text while every other signal
179
+ * (200s, subscription billing, template labels, model smoke) stayed
180
+ * green. Enable with `dario doctor --obedience`; costs at most
181
+ * `families × 3` tiny subscription requests.
182
+ */
183
+ obedience?: boolean;
184
+ }
185
+ /**
186
+ * Run every available health check. Never throws — each check is
187
+ * individually try/caught so a broken subsystem (e.g. unreadable accounts
188
+ * dir) shows up as a `fail` row instead of crashing the CLI.
189
+ *
190
+ * The order is curated — more fundamental checks first (Node, dario
191
+ * version, platform) so a reader scanning the output top-down sees
192
+ * the environment before the subsystems.
193
+ */
194
+ export declare function runChecks(opts?: RunChecksOptions): Promise<Check[]>;
195
+ export interface SeenHeader {
196
+ present: boolean;
197
+ /** Redacted preview: `"abcd...wxyz"` — first 4 + last 4 chars, or length tag if the value is too short to excerpt safely. */
198
+ redacted?: string;
199
+ length?: number;
200
+ /** For Authorization: whether the value started with "Bearer " (case-insensitive). */
201
+ bearerPrefix?: boolean;
202
+ /** Did this header's value (after any `Bearer ` strip) match DARIO_API_KEY? */
203
+ matches?: boolean;
204
+ }
205
+ export type AuthCheckVerdict = 'match' | 'mismatch' | 'no-auth-header' | 'timeout' | 'no-enforcement';
206
+ export interface AuthCheckResult {
207
+ received: boolean;
208
+ port?: number;
209
+ expected: string;
210
+ xApiKey?: SeenHeader;
211
+ authorization?: SeenHeader;
212
+ verdict: AuthCheckVerdict;
213
+ diagnosis: string;
214
+ }
215
+ export interface AuthCheckOptions {
216
+ /** Milliseconds to wait for an inbound request. Default 30,000. */
217
+ timeoutMs?: number;
218
+ /** Override the expected key. Default: `process.env.DARIO_API_KEY`. */
219
+ expectedKey?: string;
220
+ /** Test hook: called when the server is listening, with the port. */
221
+ onListening?: (port: number) => void;
222
+ }
223
+ export declare function redactSecret(value: string): string;
224
+ export declare function classifyAuthHeaders(headers: {
225
+ 'x-api-key'?: string | string[];
226
+ authorization?: string | string[];
227
+ }, expected: string): {
228
+ xApiKey: SeenHeader;
229
+ authorization: SeenHeader;
230
+ verdict: AuthCheckVerdict;
231
+ };
232
+ /**
233
+ * Listen for one inbound request on a random loopback port, classify
234
+ * whatever auth headers it carries against `DARIO_API_KEY`, return a
235
+ * structured result. Sends 200 / 401 to the inbound request so the
236
+ * client doesn't hang, then closes. This is a probe — it does not
237
+ * proxy, does not log, does not persist.
238
+ */
239
+ export declare function runAuthCheck(opts?: AuthCheckOptions): Promise<AuthCheckResult>;