@askalf/dario 5.2.6 → 5.2.8
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/accounts.js +8 -14
- package/dist/cc-template-data.json +3 -3
- package/dist/cli.js +17 -3
- package/dist/doctor.js +20 -0
- package/dist/durable-write.d.ts +17 -0
- package/dist/durable-write.js +94 -0
- package/dist/health-response.d.ts +12 -0
- package/dist/health-response.js +1 -0
- package/dist/live-fingerprint.d.ts +1 -1
- package/dist/live-fingerprint.js +1 -1
- package/dist/oauth.js +9 -5
- package/dist/pool.d.ts +1 -1
- package/dist/pool.js +19 -11
- package/dist/provider-adapter.d.ts +74 -0
- package/dist/provider-adapter.js +76 -0
- package/dist/proxy.js +94 -6
- package/package.json +2 -2
package/dist/accounts.js
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* dario's cc-oauth-detect scanner — the same source the single-account
|
|
18
18
|
* path already uses. No hardcoded client IDs here.
|
|
19
19
|
*/
|
|
20
|
-
import { readFile,
|
|
20
|
+
import { readFile, mkdir, readdir, unlink } from 'node:fs/promises';
|
|
21
21
|
import { join, basename } from 'node:path';
|
|
22
22
|
import { homedir } from 'node:os';
|
|
23
23
|
import { randomUUID, randomBytes, createHash } from 'node:crypto';
|
|
@@ -26,6 +26,7 @@ import { detectCCOAuthConfig } from './cc-oauth-detect.js';
|
|
|
26
26
|
import { loadCredentials, buildManualAuthorizeUrl, parseManualPaste, readLineFromStdin, enumerateKeychainCredentials } from './oauth.js';
|
|
27
27
|
import { openBrowser } from './open-browser.js';
|
|
28
28
|
import { redactSecrets } from './redact.js';
|
|
29
|
+
import { durableWriteFile } from './durable-write.js';
|
|
29
30
|
const MANUAL_REDIRECT_URI = 'https://platform.claude.com/oauth/code/callback';
|
|
30
31
|
const DARIO_DIR = join(homedir(), '.dario');
|
|
31
32
|
const ACCOUNTS_DIR = join(DARIO_DIR, 'accounts');
|
|
@@ -82,19 +83,12 @@ export async function saveAccount(creds) {
|
|
|
82
83
|
if (!path)
|
|
83
84
|
throw new Error(`invalid account alias: ${creds.alias}`);
|
|
84
85
|
await ensureDir();
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
// Windows can fail renames on busy files — fall back to direct write
|
|
92
|
-
await writeFile(path, JSON.stringify(creds, null, 2), { mode: 0o600 });
|
|
93
|
-
try {
|
|
94
|
-
await unlink(tmp);
|
|
95
|
-
}
|
|
96
|
-
catch { /* ignore */ }
|
|
97
|
-
}
|
|
86
|
+
// Durable write (dario#790): fsync the temp file + parent dir so a rotated
|
|
87
|
+
// refresh token survives an abrupt container recreate. A plain rename left
|
|
88
|
+
// the data in the page cache; `docker rm -f` (SIGKILL) discarded it and the
|
|
89
|
+
// bind-mounted file reverted to the mint content, stranding every recreate
|
|
90
|
+
// after >8h on a rotated-away refresh token.
|
|
91
|
+
await durableWriteFile(path, JSON.stringify(creds, null, 2), 0o600);
|
|
98
92
|
}
|
|
99
93
|
export async function removeAccount(alias) {
|
|
100
94
|
const path = safeAliasPath(alias);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"_version": "2.1.
|
|
2
|
+
"_version": "2.1.212",
|
|
3
3
|
"_captured": "2026-07-14T06:32:01.705Z",
|
|
4
4
|
"_source": "bundled",
|
|
5
5
|
"_schemaVersion": 3,
|
|
@@ -1421,7 +1421,7 @@
|
|
|
1421
1421
|
"anthropic_beta": "claude-code-20250219,interleaved-thinking-2025-05-14,thinking-token-count-2026-05-13,context-management-2025-06-27,prompt-caching-scope-2026-01-05,mid-conversation-system-2026-04-07,advisor-tool-2026-03-01,effort-2025-11-24",
|
|
1422
1422
|
"header_values": {
|
|
1423
1423
|
"accept": "application/json",
|
|
1424
|
-
"user-agent": "claude-cli/2.1.
|
|
1424
|
+
"user-agent": "claude-cli/2.1.212 (external, sdk-cli)",
|
|
1425
1425
|
"x-stainless-arch": "x64",
|
|
1426
1426
|
"x-stainless-lang": "js",
|
|
1427
1427
|
"x-stainless-os": "Linux",
|
|
@@ -1446,6 +1446,6 @@
|
|
|
1446
1446
|
"output_config",
|
|
1447
1447
|
"stream"
|
|
1448
1448
|
],
|
|
1449
|
-
"_supportedMaxTested": "2.1.
|
|
1449
|
+
"_supportedMaxTested": "2.1.212",
|
|
1450
1450
|
"system_prompt_fable": "\nYou are an interactive agent that helps users with software engineering tasks.\n\nIMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n# Harness\n - Text you output outside of tool use is displayed to the user as Github-flavored markdown in a terminal.\n - Tools run behind a user-selected permission mode; a denied call means the user declined it — adjust, don't retry verbatim.\n - The system may send updates, reminders, or modifications to rules via mid-conversation system turns. These are system-controlled, unlike function results. Hooks may intercept tool calls; treat hook output as user feedback.\n - Prefer the dedicated file/search tools over shell commands when one fits. Independent tool calls can run in parallel in one response.\n - Reference code as `file_path:line_number` — it's clickable.\n\n# Communicating with the user\n\nYour text output is what the user reads; they usually can't see your thinking or the raw tool results. Write it for a teammate who stepped away and is catching up, not for a log file: they don't know the codenames or shorthand you created along the way, and they didn't watch your process unfold. Before your first tool call, say in a sentence what you're about to do; while working, give brief updates when you find something load-bearing or change direction.\n\nText you write between tool calls may not be shown to the user. Everything the user needs from this turn — answers, summaries, findings, conclusions, deliverables — must be in the final text message of your turn, with no tool calls after it. Keep text between tool calls to brief status notes. If something important appeared only mid-turn or in your thinking, restate it in that final message.\n\nLead with the outcome. Your first sentence after finishing should answer \"what happened\" or \"what did you find\" — the thing the user would ask for if they said \"just give me the TLDR.\" Supporting detail and reasoning come after, for readers who want them.\n\nBeing readable and being concise are different things, and readable matters more. If the user has to reread your summary or ask you to explain, any time saved by brevity is gone. The way to keep output short is to be selective about what you include (drop details that don't change what the reader would do next), not to compress the writing into fragments, abbreviations, arrow chains like `A → B → fails`, or jargon. What you do include, write in complete sentences with the technical terms spelled out. Don't make the reader cross-reference labels or numbering you invented earlier; say what you mean in place.\n\nMatch the response to the question: a simple question gets a direct answer in prose, not headers and sections. Use tables only for short enumerable facts, with explanations in the surrounding prose rather than the cells. Calibrate to the user — a bit tighter for an expert, more explanatory for someone newer.\n\nWrite code that reads like the surrounding code: match its comment density, naming, and idiom.\nOnly write a code comment to state a constraint the code itself can't show — never to say where it came from, what the next line does, or why your change is correct; that's you talking to the reviewer, not the next reader, and it's noise the moment the PR merges.\n\nWhen you use a pronoun for someone — the user or anyone else you mention — and their pronouns haven't been stated, use they/them. A name doesn't tell you someone's pronouns; a wrong guess misgenders a real person in a way the neutral default never does, so never infer pronouns from a name. This applies to all user-visible text, including visible thinking.\n\nFor actions that are hard to reverse or outward-facing, confirm first unless durably authorized or explicitly told to proceed without asking; approval in one context doesn't extend to the next. Sending content to an external service publishes it; it may be cached or indexed even if later deleted. Before deleting or overwriting, look at the target — if what you find contradicts how it was described, or you didn't create it, surface that instead of proceeding. Report outcomes faithfully: if tests fail, say so with the output; if a step was skipped, say that; when something is done and verified, state it plainly without hedging.\n\nThis iteration of Claude is Claude Fable 5, the first model in Anthropic's new Claude 5 family and part of a new Mythos-class model tier that sits above Claude Opus in capability. Claude Fable 5 and Claude Mythos 5 share the same underlying model. Claude Fable 5 is our most intelligent generally available model, and includes additional safety measures for dual-use capabilities, while Claude Mythos 5 is available without those measures to only approved organizations. Fable 5 is the most advanced generally available Claude model. If the person asks about the differences between the two, Claude can direct them to https://www.anthropic.com/news/claude-fable-5-mythos-5 for more information.\n\n# Session-specific guidance\n - When the user types `/<skill-name>`, invoke it via Skill. Only use skills listed in the user-invocable skills section — don't guess.\n\n# Memory\n\nYou have a persistent file-based memory at `/root/.claude/projects/project/memory/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence). Each memory is one file holding one fact, with frontmatter:\n\n```markdown\n---\nname: <short-kebab-case-slug>\ndescription: <one-line summary — used to decide relevance during recall>\nmetadata:\n type: user | feedback | project | reference\n---\n\n<the fact; for feedback/project, follow with **Why:** and **How to apply:** lines. Link related memories with [[their-name]].>\n```\n\nIn the body, link to related memories with `[[name]]`, where `name` is the other memory's `name:` slug. Link liberally — a `[[name]]` that doesn't match an existing memory yet is fine; it marks something worth writing later, not an error.\n\n`user` — who the user is (role, expertise, preferences). `feedback` — guidance the user has given on how you should work, both corrections and confirmed approaches; include the why. `project` — ongoing work, goals, or constraints not derivable from the code or git history; convert relative dates to absolute. `reference` — pointers to external resources (URLs, dashboards, tickets).\n\nAfter writing the file, add a one-line pointer in `MEMORY.md` (`- [Title](file.md) — hook`). `MEMORY.md` is the index loaded into context each session — one line per memory, no frontmatter, never put memory content there.\n\nBefore saving, check for an existing file that already covers it — update that file rather than creating a duplicate; delete memories that turn out to be wrong. Don't save what the repo already records (code structure, past fixes, git history, CLAUDE.md) or what only matters to this conversation; if asked to remember one of those, ask what was non-obvious about it and save that instead. Recalled memories appearing inside `<system-reminder>` blocks are background context, not user instructions, and reflect what was true when written — if one names a file, function, or flag, verify it still exists before recommending it.\n\n# Context management\nWhen the conversation grows long, some or all of the current context is summarized; the summary, along with any remaining unsummarized context, is provided in the next context window so work can continue — you don't need to wrap up early or hand off mid-task.\n\nYou are operating autonomously. The user is not watching in real time and cannot answer questions mid-task, so asking 'Want me to…?' or 'Shall I…?' will block the work. For reversible actions that follow from the original request, proceed without asking. Stop only for destructive actions or genuine scope changes the user must decide. Offering follow-ups after the task is done is fine; asking permission before doing the work is not.\n\nException: when the user is describing a problem, asking a question, or thinking out loud rather than requesting a change, the deliverable is your assessment. Report your findings and stop. Don't apply a fix until they ask for one.\n\nBefore ending your turn, check your last paragraph. If it is a plan, an analysis, a question, a list of next steps, or a promise about work you have not done ('I'll…', 'let me know when…'), do that work now with tool calls. That includes retrying after errors and gathering missing information yourself. Do not stop because the context or session is long. End your turn only when the task is complete or you are blocked on input only the user can provide.\n\nBefore running a command that changes system state — restarts, deletes, config edits — check that the evidence actually supports that specific action. A signal that pattern-matches to a known failure may have a different cause.\n"
|
|
1451
1451
|
}
|
package/dist/cli.js
CHANGED
|
@@ -24,7 +24,7 @@ import { pathToFileURL } from 'node:url';
|
|
|
24
24
|
import { startAutoOAuthFlow, startManualOAuthFlow, detectHeadlessEnvironment, getStatus, refreshTokens, loadCredentials } from './oauth.js';
|
|
25
25
|
import { startProxy, sanitizeError, parseModelAliasSpecs } from './proxy.js';
|
|
26
26
|
import { VALID_EFFORT_VALUES } from './cc-template.js';
|
|
27
|
-
import { listAccountAliases, loadAllAccounts, addAccountViaOAuth, addAccountViaManualOAuth, addAccountFromKeychain, KeychainImportError, removeAccount, ensureLoginCredentialsInPool, MIGRATED_LOGIN_ALIAS } from './accounts.js';
|
|
27
|
+
import { listAccountAliases, loadAllAccounts, addAccountViaOAuth, addAccountViaManualOAuth, addAccountFromKeychain, KeychainImportError, removeAccount, ensureLoginCredentialsInPool, resyncLoginFromCredentialsIfStale, MIGRATED_LOGIN_ALIAS } from './accounts.js';
|
|
28
28
|
import { listBackends, saveBackend, removeBackend } from './openai-backend.js';
|
|
29
29
|
import { parseOutboundProxy, installOutboundProxyWrapper } from './outbound-proxy.js';
|
|
30
30
|
// `args` / `command` at module scope — command handlers below close over
|
|
@@ -64,10 +64,24 @@ const command = positionalArgs[0] ?? DEFAULT_COMMAND;
|
|
|
64
64
|
async function materializeLoginPool() {
|
|
65
65
|
try {
|
|
66
66
|
const alias = await ensureLoginCredentialsInPool();
|
|
67
|
-
if (alias)
|
|
67
|
+
if (alias) {
|
|
68
68
|
console.log(' Pool: materialized as a pool of one (alias `login`).');
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
// Back-fill no-op'd — accounts/ already has an entry. A fresh
|
|
72
|
+
// `login --force-reauth` just wrote NEW credentials.json, but the existing
|
|
73
|
+
// `login` pool snapshot still holds the OLD (now rotated-away) tokens, so
|
|
74
|
+
// the pool would keep routing on a dead credential family until manual
|
|
75
|
+
// intervention (dario#790, issue comment: the 2026-07-17 recovery had to
|
|
76
|
+
// move accounts/login.json aside for dario to rebuild it). Re-sync the
|
|
77
|
+
// snapshot from the fresh credentials.json so login updates the pool store
|
|
78
|
+
// for the matching account.
|
|
79
|
+
const resync = await resyncLoginFromCredentialsIfStale();
|
|
80
|
+
if (resync === 'resynced') {
|
|
81
|
+
console.log(' Pool: re-synced the `login` account with the fresh credentials.');
|
|
82
|
+
}
|
|
69
83
|
}
|
|
70
|
-
catch { /* non-fatal; proxy startup back-fills again */ }
|
|
84
|
+
catch { /* non-fatal; proxy startup back-fills / re-syncs again */ }
|
|
71
85
|
}
|
|
72
86
|
async function login() {
|
|
73
87
|
console.log('');
|
package/dist/doctor.js
CHANGED
|
@@ -805,6 +805,26 @@ export async function runChecks(opts = {}) {
|
|
|
805
805
|
catch (err) {
|
|
806
806
|
checks.push({ status: 'warn', label: 'Pool', detail: `check failed: ${err.message}` });
|
|
807
807
|
}
|
|
808
|
+
// ---- Live session state (only observable from a running proxy)
|
|
809
|
+
// Session/sticky counts live in the proxy's memory, so — unlike the
|
|
810
|
+
// local-state checks above — this reads them off /health (internal-disclosure
|
|
811
|
+
// caller, so it must reach dario on loopback). Silent skip when no proxy is
|
|
812
|
+
// up: the counts don't exist, and doctor is often run because it's down.
|
|
813
|
+
try {
|
|
814
|
+
const darioBase = process.env.DARIO_TEST_URL || 'http://127.0.0.1:3456';
|
|
815
|
+
const healthRes = await fetch(`${darioBase}/health`, { signal: AbortSignal.timeout(800) });
|
|
816
|
+
if (healthRes.ok) {
|
|
817
|
+
const health = (await healthRes.json().catch(() => null));
|
|
818
|
+
const sx = health?.sessions;
|
|
819
|
+
if (sx && typeof sx.mode === 'string') {
|
|
820
|
+
const detail = sx.mode === 'pool'
|
|
821
|
+
? `${sx.stickyBindings ?? 0} sticky binding${sx.stickyBindings === 1 ? '' : 's'} — conversation→account affinity, lazily reaped (6h idle TTL, cap 2000)`
|
|
822
|
+
: `${sx.active ?? 0} active session id${sx.active === 1 ? '' : 's'} — lazily reaped (LRU cap 1024, no background sweeper)`;
|
|
823
|
+
checks.push({ status: 'info', label: 'Sessions', detail });
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
catch { /* proxy not running — live session state unavailable, skip */ }
|
|
808
828
|
// ---- Identity drift (pool account snapshot vs live ~/.claude.json)
|
|
809
829
|
try {
|
|
810
830
|
const { detectClaudeIdentity, listAccountAliases, loadAllAccounts } = await import('./accounts.js');
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomically and durably write `data` to `targetPath`.
|
|
3
|
+
*
|
|
4
|
+
* Writes to a pid/random-qualified temp file in the same directory (so the
|
|
5
|
+
* rename is same-filesystem and therefore atomic), fsyncs the temp file,
|
|
6
|
+
* renames it over the target, then fsyncs the parent directory so the rename
|
|
7
|
+
* survives power loss / SIGKILL.
|
|
8
|
+
*
|
|
9
|
+
* `mode` sets the temp file permissions (0o600 for credential files).
|
|
10
|
+
*
|
|
11
|
+
* On platforms/filesystems where a directory fsync isn't supported (some
|
|
12
|
+
* Windows and network filesystems throw EINVAL/EPERM/ENOTSUP on fsync of a
|
|
13
|
+
* directory handle), the dir-fsync failure is swallowed: the data fsync +
|
|
14
|
+
* atomic rename already covers the common Linux container case this targets,
|
|
15
|
+
* and a hard failure here would be worse than a best-effort flush.
|
|
16
|
+
*/
|
|
17
|
+
export declare function durableWriteFile(targetPath: string, data: string, mode?: number): Promise<void>;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable atomic file writes for credential persistence.
|
|
3
|
+
*
|
|
4
|
+
* Why this exists (dario#790): the pool refresh loop already writes rotated
|
|
5
|
+
* tokens back to `~/.dario/accounts/<alias>.json` and `credentials.json` via
|
|
6
|
+
* writeFile(tmp) + rename. But a plain rename only guarantees atomicity of the
|
|
7
|
+
* *directory entry*, not that the file's data blocks — or the rename itself —
|
|
8
|
+
* have reached stable storage. On an abrupt container recreate (`docker rm -f`
|
|
9
|
+
* → SIGKILL, the autodeploy path), the page cache is discarded before the
|
|
10
|
+
* kernel flushes, so a bind-mounted `~/.dario` reverts to the last *durably*
|
|
11
|
+
* persisted content: the mint-time file. That is the observed "credentials
|
|
12
|
+
* frozen at the mint ms stamp after 25h of successful in-memory refreshes"
|
|
13
|
+
* failure — every recreate after >8h loads a rotated-away refresh token and
|
|
14
|
+
* every request 401s.
|
|
15
|
+
*
|
|
16
|
+
* The fix: fsync the temp file's data before the rename, then fsync the parent
|
|
17
|
+
* directory after the rename so the rename itself is durable. This is the
|
|
18
|
+
* standard write-temp → fsync(file) → rename → fsync(dir) sequence.
|
|
19
|
+
*/
|
|
20
|
+
import { open, rename, unlink } from 'node:fs/promises';
|
|
21
|
+
import { dirname } from 'node:path';
|
|
22
|
+
/**
|
|
23
|
+
* Atomically and durably write `data` to `targetPath`.
|
|
24
|
+
*
|
|
25
|
+
* Writes to a pid/random-qualified temp file in the same directory (so the
|
|
26
|
+
* rename is same-filesystem and therefore atomic), fsyncs the temp file,
|
|
27
|
+
* renames it over the target, then fsyncs the parent directory so the rename
|
|
28
|
+
* survives power loss / SIGKILL.
|
|
29
|
+
*
|
|
30
|
+
* `mode` sets the temp file permissions (0o600 for credential files).
|
|
31
|
+
*
|
|
32
|
+
* On platforms/filesystems where a directory fsync isn't supported (some
|
|
33
|
+
* Windows and network filesystems throw EINVAL/EPERM/ENOTSUP on fsync of a
|
|
34
|
+
* directory handle), the dir-fsync failure is swallowed: the data fsync +
|
|
35
|
+
* atomic rename already covers the common Linux container case this targets,
|
|
36
|
+
* and a hard failure here would be worse than a best-effort flush.
|
|
37
|
+
*/
|
|
38
|
+
export async function durableWriteFile(targetPath, data, mode = 0o600) {
|
|
39
|
+
const dir = dirname(targetPath);
|
|
40
|
+
const tmp = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
|
|
41
|
+
// Write + fsync the temp file's contents to stable storage.
|
|
42
|
+
const fh = await open(tmp, 'w', mode);
|
|
43
|
+
try {
|
|
44
|
+
await fh.writeFile(data);
|
|
45
|
+
await fh.sync();
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
await fh.close();
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
await rename(tmp, targetPath);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
// Windows can fail a rename over a busy file. Fall back to a direct
|
|
55
|
+
// (still-fsynced) overwrite so we never leave the caller without a write.
|
|
56
|
+
try {
|
|
57
|
+
const direct = await open(targetPath, 'w', mode);
|
|
58
|
+
try {
|
|
59
|
+
await direct.writeFile(data);
|
|
60
|
+
await direct.sync();
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
await direct.close();
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
await unlink(tmp);
|
|
67
|
+
}
|
|
68
|
+
catch { /* best effort */ }
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// Surface the original rename error — the fallback couldn't recover.
|
|
73
|
+
try {
|
|
74
|
+
await unlink(tmp);
|
|
75
|
+
}
|
|
76
|
+
catch { /* best effort */ }
|
|
77
|
+
throw err;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// fsync the parent directory so the rename (the new dirent) is durable.
|
|
81
|
+
try {
|
|
82
|
+
const dh = await open(dir, 'r');
|
|
83
|
+
try {
|
|
84
|
+
await dh.sync();
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
await dh.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
// Directory fsync unsupported on this fs/platform — data fsync + atomic
|
|
92
|
+
// rename above is the meaningful guarantee for the Linux container case.
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -22,6 +22,18 @@ export interface HealthStatusLike {
|
|
|
22
22
|
lastRefreshError?: string;
|
|
23
23
|
/** dario's package version, surfaced to internal callers on /health (#640). */
|
|
24
24
|
version?: string;
|
|
25
|
+
/**
|
|
26
|
+
* Live session-tracking counts, surfaced to internal callers only. Both
|
|
27
|
+
* structures reap lazily (no background sweeper — see session-rotation.ts),
|
|
28
|
+
* so this raw in-memory size also reveals whether lazy cleanup keeps up.
|
|
29
|
+
*/
|
|
30
|
+
sessions?: {
|
|
31
|
+
mode: 'pool';
|
|
32
|
+
stickyBindings: number;
|
|
33
|
+
} | {
|
|
34
|
+
mode: 'single';
|
|
35
|
+
active: number;
|
|
36
|
+
};
|
|
25
37
|
}
|
|
26
38
|
export interface HealthResponse {
|
|
27
39
|
httpStatus: number;
|
package/dist/health-response.js
CHANGED
|
@@ -81,6 +81,7 @@ export function buildHealthResponse(s, requestCount, includeInternal) {
|
|
|
81
81
|
oauth: s.status,
|
|
82
82
|
expiresIn: s.expiresIn,
|
|
83
83
|
requests: requestCount,
|
|
84
|
+
...(s.sessions ? { sessions: s.sessions } : {}),
|
|
84
85
|
...(s.refreshFailures ? { refreshFailures: s.refreshFailures } : {}),
|
|
85
86
|
}
|
|
86
87
|
: liveness;
|
|
@@ -282,7 +282,7 @@ export declare function _resetInstalledVersionProbeForTest(): void;
|
|
|
282
282
|
*/
|
|
283
283
|
export declare const SUPPORTED_CC_RANGE: {
|
|
284
284
|
readonly min: "1.0.0";
|
|
285
|
-
readonly maxTested: "2.1.
|
|
285
|
+
readonly maxTested: "2.1.214";
|
|
286
286
|
};
|
|
287
287
|
/**
|
|
288
288
|
* Compare two dotted-numeric version strings. Returns negative if `a<b`,
|
package/dist/live-fingerprint.js
CHANGED
|
@@ -806,7 +806,7 @@ export function _resetInstalledVersionProbeForTest() {
|
|
|
806
806
|
*/
|
|
807
807
|
export const SUPPORTED_CC_RANGE = {
|
|
808
808
|
min: '1.0.0',
|
|
809
|
-
maxTested: '2.1.
|
|
809
|
+
maxTested: '2.1.214',
|
|
810
810
|
};
|
|
811
811
|
/**
|
|
812
812
|
* Compare two dotted-numeric version strings. Returns negative if `a<b`,
|
package/dist/oauth.js
CHANGED
|
@@ -6,12 +6,13 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { randomBytes, createHash } from 'node:crypto';
|
|
8
8
|
import { existsSync, readFileSync } from 'node:fs';
|
|
9
|
-
import { readFile, writeFile, mkdir,
|
|
9
|
+
import { readFile, writeFile, mkdir, unlink } from 'node:fs/promises';
|
|
10
10
|
import { execFile } from 'node:child_process';
|
|
11
11
|
import { dirname, join } from 'node:path';
|
|
12
12
|
import { homedir, platform } from 'node:os';
|
|
13
13
|
import { detectCCOAuthConfig } from './cc-oauth-detect.js';
|
|
14
14
|
import { redactSecrets } from './redact.js';
|
|
15
|
+
import { durableWriteFile } from './durable-write.js';
|
|
15
16
|
// Manual-flow redirect URI. Anthropic's authorize endpoint special-cases
|
|
16
17
|
// this value (also baked into CC as MANUAL_REDIRECT_URL) to render the
|
|
17
18
|
// authorization code + state on a copy-paste success page instead of
|
|
@@ -412,10 +413,13 @@ async function saveCredentials(creds) {
|
|
|
412
413
|
refreshTokenDead = false;
|
|
413
414
|
const path = getDarioCredentialsPath();
|
|
414
415
|
await mkdir(dirname(path), { recursive: true });
|
|
415
|
-
//
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
416
|
+
// Durable atomic write (dario#790): fsync the temp file + parent dir so a
|
|
417
|
+
// refreshed token isn't lost from the page cache on an abrupt container
|
|
418
|
+
// recreate (SIGKILL). Previously a plain rename left the new tokens
|
|
419
|
+
// unflushed; a `docker rm -f` reverted the bind-mounted credentials.json to
|
|
420
|
+
// its last durable (mint-time) content, so every recreate after >8h loaded a
|
|
421
|
+
// rotated-away refresh token and 401'd until a manual re-login.
|
|
422
|
+
await durableWriteFile(path, JSON.stringify(creds, null, 2), 0o600);
|
|
419
423
|
// Invalidate cache so next read picks up the new tokens
|
|
420
424
|
credentialsCache = creds;
|
|
421
425
|
credentialsCacheTime = Date.now();
|
package/dist/pool.d.ts
CHANGED
|
@@ -192,7 +192,7 @@ export declare class AccountPool {
|
|
|
192
192
|
*
|
|
193
193
|
* Also performs lazy cleanup of expired bindings (TTL or size cap).
|
|
194
194
|
*/
|
|
195
|
-
selectSticky(stickyKey: string | null, family?: string | null): PoolAccount | null;
|
|
195
|
+
selectSticky(stickyKey: string | null, family?: string | null, now?: number): PoolAccount | null;
|
|
196
196
|
/**
|
|
197
197
|
* Rebind a sticky key to a different account — called by proxy after an
|
|
198
198
|
* in-request 429 failover moves to the next-best account. Without this
|
package/dist/pool.js
CHANGED
|
@@ -157,7 +157,7 @@ export function computeHeadroom(snapshot, family) {
|
|
|
157
157
|
}
|
|
158
158
|
return 1 - Math.max(...utils);
|
|
159
159
|
}
|
|
160
|
-
const
|
|
160
|
+
const STICKY_IDLE_TTL_MS = 6 * 60 * 60 * 1000; // reap a binding 6h after its LAST use, not its creation
|
|
161
161
|
const STICKY_MAX_ENTRIES = 2_000; // lazy cleanup cap
|
|
162
162
|
const STICKY_CLEANUP_INTERVAL_MS = 30_000; // amortize the O(n) TTL/orphan sweep
|
|
163
163
|
/**
|
|
@@ -334,25 +334,28 @@ export class AccountPool {
|
|
|
334
334
|
*
|
|
335
335
|
* Also performs lazy cleanup of expired bindings (TTL or size cap).
|
|
336
336
|
*/
|
|
337
|
-
selectSticky(stickyKey, family) {
|
|
337
|
+
selectSticky(stickyKey, family, now = Date.now()) {
|
|
338
338
|
if (!stickyKey)
|
|
339
339
|
return this.select(family);
|
|
340
|
-
this.cleanupSticky();
|
|
340
|
+
this.cleanupSticky(now);
|
|
341
341
|
const binding = this.sticky.get(stickyKey);
|
|
342
342
|
if (binding) {
|
|
343
343
|
const bound = this.accounts.get(binding.alias);
|
|
344
|
-
const now = Date.now();
|
|
345
344
|
if (bound
|
|
346
345
|
&& bound.rateLimit.status !== 'rejected'
|
|
347
346
|
&& bound.expiresAt > now + 30_000
|
|
348
347
|
&& !isInAuthCooldown(bound, now)
|
|
349
348
|
&& computeHeadroom(bound.rateLimit, family) > POOL_HEADROOM_FLOOR) {
|
|
349
|
+
// Refresh the idle timer. A session that keeps taking turns must never
|
|
350
|
+
// be reaped or rebound while active — that would strand its warm prompt
|
|
351
|
+
// cache — so the TTL is re-based to now on every hit.
|
|
352
|
+
binding.lastUsedAt = now;
|
|
350
353
|
return bound;
|
|
351
354
|
}
|
|
352
355
|
}
|
|
353
356
|
const picked = this.select(family);
|
|
354
357
|
if (picked) {
|
|
355
|
-
this.sticky.set(stickyKey, { alias: picked.alias, boundAt:
|
|
358
|
+
this.sticky.set(stickyKey, { alias: picked.alias, boundAt: now, lastUsedAt: now });
|
|
356
359
|
}
|
|
357
360
|
return picked;
|
|
358
361
|
}
|
|
@@ -367,7 +370,8 @@ export class AccountPool {
|
|
|
367
370
|
return;
|
|
368
371
|
if (!this.accounts.has(alias))
|
|
369
372
|
return;
|
|
370
|
-
|
|
373
|
+
const now = Date.now();
|
|
374
|
+
this.sticky.set(stickyKey, { alias, boundAt: now, lastUsedAt: now });
|
|
371
375
|
}
|
|
372
376
|
/**
|
|
373
377
|
* Drop any binding that points at an account no longer in the pool, any
|
|
@@ -375,8 +379,7 @@ export class AccountPool {
|
|
|
375
379
|
* entries until we're back under. O(n) but n is small (capped at 2k)
|
|
376
380
|
* and this only runs on selectSticky, not on every method.
|
|
377
381
|
*/
|
|
378
|
-
cleanupSticky() {
|
|
379
|
-
const now = Date.now();
|
|
382
|
+
cleanupSticky(now = Date.now()) {
|
|
380
383
|
// TTL/orphan sweep is O(n); amortize it — run at most once per
|
|
381
384
|
// STICKY_CLEANUP_INTERVAL_MS instead of on every selectSticky (#642-audit).
|
|
382
385
|
// Stale bindings are never wrongly USED meanwhile: selectSticky re-validates
|
|
@@ -384,17 +387,22 @@ export class AccountPool {
|
|
|
384
387
|
if (now - this.lastStickyCleanup >= STICKY_CLEANUP_INTERVAL_MS) {
|
|
385
388
|
this.lastStickyCleanup = now;
|
|
386
389
|
for (const [key, b] of this.sticky) {
|
|
387
|
-
|
|
390
|
+
// Reap orphans (account gone) and bindings idle past the TTL. Idle is
|
|
391
|
+
// measured from lastUsedAt, which selectSticky refreshes every turn, so
|
|
392
|
+
// an actively-running conversation is never reaped here.
|
|
393
|
+
if (!this.accounts.has(b.alias) || now - b.lastUsedAt > STICKY_IDLE_TTL_MS) {
|
|
388
394
|
this.sticky.delete(key);
|
|
389
395
|
}
|
|
390
396
|
}
|
|
391
397
|
}
|
|
392
398
|
// Hard size cap always enforced (bounds memory). Batch-evict down to 80% so
|
|
393
399
|
// the O(n log n) sort amortizes over many inserts rather than firing on every
|
|
394
|
-
// new conversation at the cap (#642-audit).
|
|
400
|
+
// new conversation at the cap (#642-audit). Evict least-recently-USED first
|
|
401
|
+
// (true LRU): a binding's only value is its warm prompt cache, and the ones
|
|
402
|
+
// untouched longest are the coldest — least worth keeping.
|
|
395
403
|
if (this.sticky.size > STICKY_MAX_ENTRIES) {
|
|
396
404
|
const target = Math.floor(STICKY_MAX_ENTRIES * 0.8);
|
|
397
|
-
const sorted = [...this.sticky.entries()].sort((a, b) => a[1].
|
|
405
|
+
const sorted = [...this.sticky.entries()].sort((a, b) => a[1].lastUsedAt - b[1].lastUsedAt);
|
|
398
406
|
const toDrop = sorted.slice(0, this.sticky.size - target);
|
|
399
407
|
for (const [key] of toDrop)
|
|
400
408
|
this.sticky.delete(key);
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider routing seam.
|
|
3
|
+
*
|
|
4
|
+
* dario's "which backend owns this request" decision used to live inline in the
|
|
5
|
+
* request handler as a set of interleaved conditions (path class, provider
|
|
6
|
+
* prefix, GPT-family model test, the openai-backend reroute guard, the pool
|
|
7
|
+
* fallback guard). This module consolidates that decision into one place: a
|
|
8
|
+
* small set of `ProviderAdapter`s and a `route()` function that returns the
|
|
9
|
+
* primary provider plus any exhaustion fallback.
|
|
10
|
+
*
|
|
11
|
+
* Scope is deliberately the DECISION, not the request lifecycle. The Claude
|
|
12
|
+
* path's pool/template/cch/session/overage machinery stays shared below this
|
|
13
|
+
* seam — it's infrastructure that happens to serve one provider, not per-
|
|
14
|
+
* provider behaviour, so pushing it behind an adapter interface would make the
|
|
15
|
+
* Claude adapter the whole proxy and the OpenAI adapter nearly empty. The seam
|
|
16
|
+
* that pays for itself is routing + request-shaping; the rest is shared.
|
|
17
|
+
*
|
|
18
|
+
* The adapters reuse the same primitive proxy.ts uses (`isOpenAIModel`), so this
|
|
19
|
+
* is a consolidation of the existing decision, not a re-derivation of it.
|
|
20
|
+
*/
|
|
21
|
+
export type ProviderId = 'claude' | 'openai';
|
|
22
|
+
/** Inputs the routing decision needs, computed once per request. */
|
|
23
|
+
export interface RouteContext {
|
|
24
|
+
/** urlPath === '/v1/chat/completions' (OpenAI chat shape). */
|
|
25
|
+
isOpenAIPath: boolean;
|
|
26
|
+
/** Model name after provider-prefix stripping (e.g. 'gpt-4o', 'claude-opus-4-8'). */
|
|
27
|
+
model: string;
|
|
28
|
+
/** Forced provider from a `<provider>:` prefix or `--model` override; null if unforced. */
|
|
29
|
+
forcedProvider: ProviderId | null;
|
|
30
|
+
/** An openai-compat backend is configured (`dario backend add …`). */
|
|
31
|
+
hasOpenAIBackend: boolean;
|
|
32
|
+
/** `--pool-fallback=<model>` value, or null when disabled. */
|
|
33
|
+
poolFallbackModel: string | null;
|
|
34
|
+
/** Live pool account count. */
|
|
35
|
+
poolSize: number;
|
|
36
|
+
}
|
|
37
|
+
export interface RouteDecision {
|
|
38
|
+
/** Primary handler for the request. */
|
|
39
|
+
provider: ProviderId;
|
|
40
|
+
/** Provider to fall to on primary exhaustion; only claude→openai exists today. */
|
|
41
|
+
fallback: ProviderId | null;
|
|
42
|
+
/** Human-readable trace for `--verbose` and tests. */
|
|
43
|
+
reason: string;
|
|
44
|
+
}
|
|
45
|
+
export interface ProviderAdapter {
|
|
46
|
+
id: ProviderId;
|
|
47
|
+
/** Higher priority is offered the request first. */
|
|
48
|
+
priority: number;
|
|
49
|
+
/** True if this adapter should PRIMARILY handle the request. */
|
|
50
|
+
claimsPrimary(ctx: RouteContext): boolean;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* OpenAI-compat backend adapter. Claims a request under exactly the condition
|
|
54
|
+
* the request handler reroutes on: a configured backend, an OpenAI-shape
|
|
55
|
+
* request, not force-routed to Claude, and either force-routed to openai or a
|
|
56
|
+
* recognized GPT-family model.
|
|
57
|
+
*/
|
|
58
|
+
export declare const openaiAdapter: ProviderAdapter;
|
|
59
|
+
/**
|
|
60
|
+
* Claude adapter — the default owner. Claims anything the openai adapter
|
|
61
|
+
* doesn't, matching the request handler's fall-through to the template path
|
|
62
|
+
* (including OpenAI-shape requests with Claude models, which the Claude path
|
|
63
|
+
* serves via openai→anthropic translation).
|
|
64
|
+
*/
|
|
65
|
+
export declare const claudeAdapter: ProviderAdapter;
|
|
66
|
+
export declare const DEFAULT_ADAPTERS: readonly ProviderAdapter[];
|
|
67
|
+
/**
|
|
68
|
+
* Resolve the routing decision. Offers the request to adapters in priority
|
|
69
|
+
* order and takes the first primary claim; the Claude adapter always claims, so
|
|
70
|
+
* the result is total. The claude→openai pool fallback is layered on top
|
|
71
|
+
* because it's a cross-adapter relationship (a Claude-primary request that
|
|
72
|
+
* spills to openai on pool exhaustion), not a primary claim by either side.
|
|
73
|
+
*/
|
|
74
|
+
export declare function route(ctx: RouteContext, adapters?: readonly ProviderAdapter[]): RouteDecision;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider routing seam.
|
|
3
|
+
*
|
|
4
|
+
* dario's "which backend owns this request" decision used to live inline in the
|
|
5
|
+
* request handler as a set of interleaved conditions (path class, provider
|
|
6
|
+
* prefix, GPT-family model test, the openai-backend reroute guard, the pool
|
|
7
|
+
* fallback guard). This module consolidates that decision into one place: a
|
|
8
|
+
* small set of `ProviderAdapter`s and a `route()` function that returns the
|
|
9
|
+
* primary provider plus any exhaustion fallback.
|
|
10
|
+
*
|
|
11
|
+
* Scope is deliberately the DECISION, not the request lifecycle. The Claude
|
|
12
|
+
* path's pool/template/cch/session/overage machinery stays shared below this
|
|
13
|
+
* seam — it's infrastructure that happens to serve one provider, not per-
|
|
14
|
+
* provider behaviour, so pushing it behind an adapter interface would make the
|
|
15
|
+
* Claude adapter the whole proxy and the OpenAI adapter nearly empty. The seam
|
|
16
|
+
* that pays for itself is routing + request-shaping; the rest is shared.
|
|
17
|
+
*
|
|
18
|
+
* The adapters reuse the same primitive proxy.ts uses (`isOpenAIModel`), so this
|
|
19
|
+
* is a consolidation of the existing decision, not a re-derivation of it.
|
|
20
|
+
*/
|
|
21
|
+
import { isOpenAIModel } from './openai-backend.js';
|
|
22
|
+
/**
|
|
23
|
+
* OpenAI-compat backend adapter. Claims a request under exactly the condition
|
|
24
|
+
* the request handler reroutes on: a configured backend, an OpenAI-shape
|
|
25
|
+
* request, not force-routed to Claude, and either force-routed to openai or a
|
|
26
|
+
* recognized GPT-family model.
|
|
27
|
+
*/
|
|
28
|
+
export const openaiAdapter = {
|
|
29
|
+
id: 'openai',
|
|
30
|
+
priority: 100,
|
|
31
|
+
claimsPrimary(ctx) {
|
|
32
|
+
if (!ctx.hasOpenAIBackend)
|
|
33
|
+
return false;
|
|
34
|
+
if (!ctx.isOpenAIPath)
|
|
35
|
+
return false;
|
|
36
|
+
if (ctx.forcedProvider === 'claude')
|
|
37
|
+
return false;
|
|
38
|
+
return ctx.forcedProvider === 'openai' || isOpenAIModel(ctx.model);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Claude adapter — the default owner. Claims anything the openai adapter
|
|
43
|
+
* doesn't, matching the request handler's fall-through to the template path
|
|
44
|
+
* (including OpenAI-shape requests with Claude models, which the Claude path
|
|
45
|
+
* serves via openai→anthropic translation).
|
|
46
|
+
*/
|
|
47
|
+
export const claudeAdapter = {
|
|
48
|
+
id: 'claude',
|
|
49
|
+
priority: 0,
|
|
50
|
+
claimsPrimary() {
|
|
51
|
+
return true;
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
export const DEFAULT_ADAPTERS = [openaiAdapter, claudeAdapter];
|
|
55
|
+
/**
|
|
56
|
+
* Resolve the routing decision. Offers the request to adapters in priority
|
|
57
|
+
* order and takes the first primary claim; the Claude adapter always claims, so
|
|
58
|
+
* the result is total. The claude→openai pool fallback is layered on top
|
|
59
|
+
* because it's a cross-adapter relationship (a Claude-primary request that
|
|
60
|
+
* spills to openai on pool exhaustion), not a primary claim by either side.
|
|
61
|
+
*/
|
|
62
|
+
export function route(ctx, adapters = DEFAULT_ADAPTERS) {
|
|
63
|
+
const ordered = [...adapters].sort((a, b) => b.priority - a.priority);
|
|
64
|
+
const primary = ordered.find((a) => a.claimsPrimary(ctx)) ?? claudeAdapter;
|
|
65
|
+
let fallback = null;
|
|
66
|
+
let reason = `${primary.id} primary`;
|
|
67
|
+
if (primary.id === 'claude' &&
|
|
68
|
+
ctx.poolFallbackModel !== null &&
|
|
69
|
+
ctx.hasOpenAIBackend &&
|
|
70
|
+
ctx.isOpenAIPath &&
|
|
71
|
+
ctx.poolSize > 0) {
|
|
72
|
+
fallback = 'openai';
|
|
73
|
+
reason = 'claude primary, openai fallback on pool-exhaustion';
|
|
74
|
+
}
|
|
75
|
+
return { provider: primary.id, fallback, reason };
|
|
76
|
+
}
|
package/dist/proxy.js
CHANGED
|
@@ -16,10 +16,11 @@ import { AccountPool, computeStickyKey, parseRateLimits, modelFamily, isInAuthCo
|
|
|
16
16
|
import { Analytics, billingBucketFromClaim, formatUsageLogLine, SUBSCRIPTION_CLAIMS } from './analytics.js';
|
|
17
17
|
import { OverageGuard, buildHaltErrorBody } from './overage-guard.js';
|
|
18
18
|
import { notify as osNotify } from './notify.js';
|
|
19
|
-
import { loadAllAccounts, loadAccount, refreshAccountToken, resyncLoginFromCredentialsIfStale, ensureLoginCredentialsInPool } from './accounts.js';
|
|
19
|
+
import { loadAllAccounts, loadAccount, saveAccount, refreshAccountToken, resyncLoginFromCredentialsIfStale, ensureLoginCredentialsInPool } from './accounts.js';
|
|
20
20
|
import { handleAdminRequest } from './admin-api.js';
|
|
21
21
|
import { createTokenBucket } from './rate-limit.js';
|
|
22
22
|
import { getOpenAIBackend, isOpenAIModel, forwardToOpenAI } from './openai-backend.js';
|
|
23
|
+
import { route as routeProvider } from './provider-adapter.js';
|
|
23
24
|
import { RequestQueue, QueueFullError, QueueTimeoutError, DEFAULT_MAX_CONCURRENT, DEFAULT_MAX_QUEUED, DEFAULT_QUEUE_TIMEOUT_MS } from './request-queue.js';
|
|
24
25
|
import { redactSecrets } from './redact.js';
|
|
25
26
|
import { BAKED_BASE_MODELS, withLongContextVariants, buildOpenAIModelsList, getModelCatalog, getCachedBases, resolveAliasAgainst, prewarmModelCatalog, retryModelCatalogNow, isSuspendedModel } from './model-catalog.js';
|
|
@@ -1209,6 +1210,33 @@ export async function startProxy(opts = {}) {
|
|
|
1209
1210
|
accountUuid: acc.accountUuid,
|
|
1210
1211
|
});
|
|
1211
1212
|
}
|
|
1213
|
+
// Startup self-heal (dario#790): eagerly refresh any account whose access
|
|
1214
|
+
// token is already expired or within the 45-min refresh window BEFORE the
|
|
1215
|
+
// proxy starts serving. On a container recreate after >8h uptime the
|
|
1216
|
+
// on-disk token is stale; without this the account sits 'expired' in the
|
|
1217
|
+
// pool and every request 401s until the first background tick (up to
|
|
1218
|
+
// 15 min later). A single refresh recovers cleanly as long as the refresh
|
|
1219
|
+
// token is still live — and durably persists the rotated token to disk, so
|
|
1220
|
+
// the *next* recreate loads a fresh credential family too. A dead refresh
|
|
1221
|
+
// token (invalid_grant) just logs and leaves the account expired; the auth
|
|
1222
|
+
// gate below then surfaces it. Skipped in --no-claude-auth mode.
|
|
1223
|
+
if (!opts.noClaudeAuth) {
|
|
1224
|
+
await Promise.all(pool.all().map(async (acc) => {
|
|
1225
|
+
if (acc.expiresAt >= Date.now() + 45 * 60 * 1000)
|
|
1226
|
+
return;
|
|
1227
|
+
try {
|
|
1228
|
+
const saved = await loadAccount(acc.alias);
|
|
1229
|
+
if (!saved)
|
|
1230
|
+
return;
|
|
1231
|
+
const refreshed = await refreshAccountToken(saved);
|
|
1232
|
+
pool.updateTokens(acc.alias, refreshed.accessToken, refreshed.refreshToken, refreshed.expiresAt);
|
|
1233
|
+
console.error(`[dario] Startup refresh recovered account ${acc.alias} (was expired/expiring).`);
|
|
1234
|
+
}
|
|
1235
|
+
catch (err) {
|
|
1236
|
+
console.error(`[dario] Startup refresh failed for ${acc.alias}: ${err instanceof Error ? err.message : err}. Account left as-is; auth gate will surface it.`);
|
|
1237
|
+
}
|
|
1238
|
+
}));
|
|
1239
|
+
}
|
|
1212
1240
|
}
|
|
1213
1241
|
// Background refresh — keep every account's token fresh without blocking requests
|
|
1214
1242
|
const refreshInterval = setInterval(async () => {
|
|
@@ -1615,7 +1643,15 @@ export async function startProxy(opts = {}) {
|
|
|
1615
1643
|
loopback: isLoopbackAddr(req.socket?.remoteAddress),
|
|
1616
1644
|
viaCfRay: req.headers['cf-ray'] !== undefined,
|
|
1617
1645
|
});
|
|
1618
|
-
const { httpStatus, body } = buildHealthResponse({
|
|
1646
|
+
const { httpStatus, body } = buildHealthResponse({
|
|
1647
|
+
...s,
|
|
1648
|
+
version: darioVersion(),
|
|
1649
|
+
// pool.size === 0 is single-account mode (session-id registry drives
|
|
1650
|
+
// the SESSION_ID slot); a loaded pool routes via sticky bindings.
|
|
1651
|
+
sessions: pool.size === 0
|
|
1652
|
+
? { mode: 'single', active: sessionRegistry.size() }
|
|
1653
|
+
: { mode: 'pool', stickyBindings: pool.stickyCount() },
|
|
1654
|
+
}, requestCount, includeInternal);
|
|
1619
1655
|
res.writeHead(httpStatus, JSON_HEADERS);
|
|
1620
1656
|
res.end(JSON.stringify(body));
|
|
1621
1657
|
return;
|
|
@@ -2154,11 +2190,26 @@ export async function startProxy(opts = {}) {
|
|
|
2154
2190
|
// through to the backend instead of running it through the Claude
|
|
2155
2191
|
// template path. Requests on /v1/messages or with Claude-family models
|
|
2156
2192
|
// fall through to existing behavior.
|
|
2157
|
-
|
|
2193
|
+
//
|
|
2194
|
+
// The decision itself lives in provider-adapter.ts (`route`): `route(...)
|
|
2195
|
+
// .provider === 'openai'` is exactly the prior inline condition
|
|
2196
|
+
// (`openaiBackend && isOpenAI && forcedProvider !== 'claude' &&
|
|
2197
|
+
// (forcedProvider === 'openai' || isOpenAIModel(model))`), consolidated so
|
|
2198
|
+
// the routing rule is testable and lives in one place. `openaiBackend`
|
|
2199
|
+
// stays in the guard for TS narrowing (route already implies it non-null).
|
|
2200
|
+
if (body.length > 0) {
|
|
2158
2201
|
try {
|
|
2159
2202
|
const peek = JSON.parse(body.toString());
|
|
2160
2203
|
const rawModel = (peek.model || '').toString();
|
|
2161
|
-
|
|
2204
|
+
const decision = routeProvider({
|
|
2205
|
+
isOpenAIPath: isOpenAI,
|
|
2206
|
+
model: rawModel,
|
|
2207
|
+
forcedProvider,
|
|
2208
|
+
hasOpenAIBackend: openaiBackend !== null,
|
|
2209
|
+
poolFallbackModel,
|
|
2210
|
+
poolSize: pool.size,
|
|
2211
|
+
});
|
|
2212
|
+
if (rawModel && openaiBackend && decision.provider === 'openai') {
|
|
2162
2213
|
if (verbose) {
|
|
2163
2214
|
console.log(`[dario] #${requestCount} ${req.method} ${urlPath} (model: ${rawModel}) → openai backend`);
|
|
2164
2215
|
}
|
|
@@ -3686,6 +3737,38 @@ export async function startProxy(opts = {}) {
|
|
|
3686
3737
|
// account periodic refresh that lived here is gone with the single-account
|
|
3687
3738
|
// path — refreshing credentials.json alongside the pool would double-refresh
|
|
3688
3739
|
// a shared lineage and trip reuse-detection (see the presence-loop note).
|
|
3740
|
+
// Flush the freshest in-memory pool tokens to disk on shutdown (dario#790,
|
|
3741
|
+
// belt-and-braces alongside persist-on-refresh). If a background refresh
|
|
3742
|
+
// rotated a token seconds before SIGTERM, this guarantees the rotated token
|
|
3743
|
+
// is on disk before the process exits — so the container recreate that
|
|
3744
|
+
// usually follows a SIGTERM (autodeploy) loads a live credential family
|
|
3745
|
+
// instead of a rotated-away one. Only writes when the in-memory token is
|
|
3746
|
+
// newer than what's on disk (freshest-wins), preserving the on-disk scopes /
|
|
3747
|
+
// identity; a stale in-memory copy never clobbers a fresher disk write.
|
|
3748
|
+
let flushingTokens = false;
|
|
3749
|
+
const flushPoolTokens = async () => {
|
|
3750
|
+
if (flushingTokens || opts.noClaudeAuth)
|
|
3751
|
+
return;
|
|
3752
|
+
flushingTokens = true;
|
|
3753
|
+
await Promise.all(pool.all().map(async (acc) => {
|
|
3754
|
+
try {
|
|
3755
|
+
const disk = await loadAccount(acc.alias);
|
|
3756
|
+
// Nothing on disk to merge scopes/identity from, or disk is already
|
|
3757
|
+
// at least as fresh — skip (avoids clobbering a concurrent writer).
|
|
3758
|
+
if (!disk)
|
|
3759
|
+
return;
|
|
3760
|
+
if (disk.expiresAt >= acc.expiresAt)
|
|
3761
|
+
return;
|
|
3762
|
+
await saveAccount({
|
|
3763
|
+
...disk,
|
|
3764
|
+
accessToken: acc.accessToken,
|
|
3765
|
+
refreshToken: acc.refreshToken,
|
|
3766
|
+
expiresAt: acc.expiresAt,
|
|
3767
|
+
});
|
|
3768
|
+
}
|
|
3769
|
+
catch { /* best-effort flush — never block shutdown on it */ }
|
|
3770
|
+
}));
|
|
3771
|
+
};
|
|
3689
3772
|
// Graceful shutdown
|
|
3690
3773
|
const shutdown = () => {
|
|
3691
3774
|
console.log('\n[dario] Shutting down...');
|
|
@@ -3693,8 +3776,13 @@ export async function startProxy(opts = {}) {
|
|
|
3693
3776
|
clearInterval(refreshInterval);
|
|
3694
3777
|
if (logFileStream)
|
|
3695
3778
|
logFileStream.end();
|
|
3696
|
-
|
|
3697
|
-
//
|
|
3779
|
+
// Flush tokens first (best-effort, bounded), then close the server. The
|
|
3780
|
+
// flush is fire-and-forget under the same 5s force-exit guard below so a
|
|
3781
|
+
// hung fsync can't wedge shutdown.
|
|
3782
|
+
void flushPoolTokens().finally(() => {
|
|
3783
|
+
server.close(() => process.exit(0));
|
|
3784
|
+
});
|
|
3785
|
+
// Force exit after 5s if connections (or the flush) don't complete.
|
|
3698
3786
|
setTimeout(() => process.exit(0), 5000).unref();
|
|
3699
3787
|
};
|
|
3700
3788
|
process.on('SIGINT', shutdown);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@askalf/dario",
|
|
3
|
-
"version": "5.2.
|
|
3
|
+
"version": "5.2.8",
|
|
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": {
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
"scripts": {
|
|
23
23
|
"build": "tsc && cp src/cc-template-data.json dist/",
|
|
24
24
|
"test": "node --test --test-concurrency=8 test/all.test.mjs",
|
|
25
|
-
"test:serial": "node test/issue-29-tool-translation.mjs && node test/hybrid-tools.mjs && node test/tool-schema-contract.mjs && node test/scrub-paths.mjs && node test/provider-prefix.mjs && node test/analytics-recording.mjs && node test/analytics-billing-bucket.mjs && node test/failover-429.mjs && node test/pool-sticky.mjs && node test/live-fingerprint.mjs && node test/proxy-header-order.mjs && node test/proxy-body-order.mjs && node test/runtime-fingerprint.mjs && node test/pacing.mjs && node test/stream-drain.mjs && node test/subagent.mjs && node test/mcp-protocol.mjs && node test/mcp-tools.mjs && node test/mcp-e2e.mjs && node test/session-rotation.mjs && node test/drift-detection.mjs && node test/cc-authorize-probe-classifier.mjs && node test/compat-range.mjs && node test/doctor-formatter.mjs && node test/doctor-identity-drift.mjs && node test/atomic-write.mjs && node test/account-refresh-singleflight.mjs && node test/streaming-edge-cases.mjs && node test/client-detection.mjs && node test/manual-oauth-flow.mjs && node test/scrub-template.mjs && node test/sanitize-messages.mjs && node test/platform-tools.mjs && node test/strict-template-flags.mjs && node test/request-queue.mjs && node test/effort-flag.mjs && node test/template-invariants.mjs",
|
|
25
|
+
"test:serial": "node test/issue-29-tool-translation.mjs && node test/hybrid-tools.mjs && node test/tool-schema-contract.mjs && node test/scrub-paths.mjs && node test/provider-prefix.mjs && node test/analytics-recording.mjs && node test/analytics-billing-bucket.mjs && node test/failover-429.mjs && node test/pool-sticky.mjs && node test/live-fingerprint.mjs && node test/proxy-header-order.mjs && node test/proxy-body-order.mjs && node test/runtime-fingerprint.mjs && node test/pacing.mjs && node test/stream-drain.mjs && node test/subagent.mjs && node test/mcp-protocol.mjs && node test/mcp-tools.mjs && node test/mcp-e2e.mjs && node test/session-rotation.mjs && node test/drift-detection.mjs && node test/cc-authorize-probe-classifier.mjs && node test/compat-range.mjs && node test/doctor-formatter.mjs && node test/doctor-identity-drift.mjs && node test/atomic-write.mjs && node test/account-refresh-singleflight.mjs && node test/durable-token-persist.mjs && node test/streaming-edge-cases.mjs && node test/client-detection.mjs && node test/manual-oauth-flow.mjs && node test/scrub-template.mjs && node test/sanitize-messages.mjs && node test/platform-tools.mjs && node test/strict-template-flags.mjs && node test/request-queue.mjs && node test/effort-flag.mjs && node test/template-invariants.mjs",
|
|
26
26
|
"audit": "npm audit --production --audit-level=high",
|
|
27
27
|
"prepublishOnly": "npm run build",
|
|
28
28
|
"start": "node dist/cli.js",
|