@askalf/dario 6.0.11 → 6.0.13

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.
@@ -0,0 +1,7 @@
1
+ import type { Check } from './doctor.js';
2
+ import type { ProbeResult } from './serving-probe.js';
3
+ /**
4
+ * Apply the authoritative can-it-serve verdict to doctor's structural rows.
5
+ * Token freshness remains visible, but cannot stay green when the probe failed.
6
+ */
7
+ export declare function applyServingVerdict(checks: readonly Check[], probe: ProbeResult): Check[];
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Apply the authoritative can-it-serve verdict to doctor's structural rows.
3
+ * Token freshness remains visible, but cannot stay green when the probe failed.
4
+ */
5
+ export function applyServingVerdict(checks, probe) {
6
+ if (probe.ok) {
7
+ return [{ status: 'ok', label: 'Serving', detail: 'seat served the synthetic probe' }, ...checks];
8
+ }
9
+ const detail = `${probe.reason}: ${probe.detail ?? 'the seat cannot serve a request'}`;
10
+ const structural = new Set(['OAuth', 'Pool', 'Pool routing', 'Identity']);
11
+ return [
12
+ { status: 'fail', label: 'Serving', detail },
13
+ ...checks.map((check) => structural.has(check.label)
14
+ ? { ...check, status: 'fail', detail: `${check.detail}; NOT SERVING (${probe.reason})` }
15
+ : check),
16
+ ];
17
+ }
package/dist/doctor.d.ts CHANGED
@@ -1,239 +1,22 @@
1
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;
2
+ * Public doctor execution path.
3
+ *
4
+ * The structural collector stays isolated in doctor-core so the opt-in live
5
+ * serving verdict can be applied once, at the boundary shared by the CLI and
6
+ * MCP callers.
7
+ */
8
+ export * from './doctor-core.js';
9
+ import { type Check, type RunChecksOptions } from './doctor-core.js';
10
+ import { type ProbeResult } from './serving-probe.js';
11
+ interface DoctorDependencies {
12
+ collect: (opts: RunChecksOptions) => Promise<Check[]>;
13
+ probe: () => Promise<ProbeResult>;
21
14
  }
22
15
  /**
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.
16
+ * Collect doctor rows and, when --probe is requested, make the live serving
17
+ * result authoritative over structural OAuth/pool/identity conclusions.
193
18
  */
19
+ export declare function runDoctorChecks(opts?: RunChecksOptions, dependencies?: DoctorDependencies): Promise<Check[]>;
20
+ /** Production entry point shared by the CLI and MCP callers. */
194
21
  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>;
22
+ export { applyServingVerdict } from './doctor-serving.js';