@toddzheng024/dscode-bundle 0.7.6 → 0.7.7
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/THIRD_PARTY_NOTICES.md +3 -3
- package/cordis.patch.yml +26 -5
- package/package.json +4 -4
- package/plugins/auto-review/index.mjs +6 -1
- package/plugins/compaction/tetris.mjs +65 -0
- package/plugins/compaction/threshold.mjs +46 -0
- package/plugins/credentials/index.mjs +2 -2
- package/plugins/i18n/messages.mjs +18 -0
- package/plugins/openrouter/adapter.mjs +157 -0
- package/plugins/openrouter/index.mjs +112 -0
- package/plugins/openrouter/models.mjs +151 -0
- package/plugins/openrouter/search.mjs +109 -0
- package/plugins/openrouter/wire.mjs +413 -0
- package/plugins/providers/catalog.mjs +18 -68
- package/plugins/providers/openrouter-account.mjs +171 -0
- package/plugins/session-metrics/balance.mjs +29 -19
- package/plugins/session-metrics/index.mjs +19 -9
- package/plugins/session-metrics/pricing.mjs +26 -6
- package/plugins/session-metrics/view.mjs +1 -1
- package/plugins/ultra/policy.mjs +0 -16
- package/presets/dscode/agent.cordis.yml +1 -1
- package/vendor/compaction-basic/index.js +983 -0
- package/vendor/compaction-basic/types/config.d.ts +37 -0
- package/vendor/compaction-basic/types/index.d.ts +84 -0
- package/vendor/compaction-basic/types/region.d.ts +65 -0
- package/vendor/compaction-basic/types/summarizer.d.ts +64 -0
- package/vendor/compaction-basic/types/types.d.ts +73 -0
- package/vendor/tui/dscode-providers/catalog.mjs +18 -68
- package/vendor/tui/dscode-providers/openrouter-account.mjs +171 -0
- package/vendor/tui/index.mjs +390 -165
- package/plugins/session-metrics/openrouter-prices.mjs +0 -96
- package/vendor/pi-ai/index.js +0 -2701
- package/vendor/pi-ai/types/adapter.d.ts +0 -105
- package/vendor/pi-ai/types/auth.d.ts +0 -60
- package/vendor/pi-ai/types/catalog.d.ts +0 -355
- package/vendor/pi-ai/types/config.d.ts +0 -208
- package/vendor/pi-ai/types/context.d.ts +0 -42
- package/vendor/pi-ai/types/discovery.d.ts +0 -43
- package/vendor/pi-ai/types/index.d.ts +0 -69
- package/vendor/pi-ai/types/login.d.ts +0 -21
- package/vendor/pi-ai/types/provider.d.ts +0 -59
- package/vendor/pi-ai/types/replay.d.ts +0 -63
- package/vendor/pi-ai/types/stream.d.ts +0 -43
- /package/vendor/{pi-ai → compaction-basic}/LICENSE +0 -0
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
// OpenRouter account facts for /openrouter and the footer balance. The inference key
|
|
2
|
+
// reads the account credits and its own limit and usage; an optional management key,
|
|
3
|
+
// which cannot call models, adds every key's usage and the last 30 days of spend.
|
|
4
|
+
// This directory also ships beside the TUI, so the module imports nothing.
|
|
5
|
+
export const OPENROUTER_API = 'https://openrouter.ai/api/v1';
|
|
6
|
+
export const MANAGEMENT_REF = 'OPENROUTER_MANAGEMENT_KEY';
|
|
7
|
+
|
|
8
|
+
const finite = value => {
|
|
9
|
+
const number = Number(value);
|
|
10
|
+
return value !== null && value !== undefined && value !== '' && Number.isFinite(number) ? number : undefined;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export class OpenRouterAccountError extends Error {
|
|
14
|
+
constructor(message, status) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'OpenRouterAccountError';
|
|
17
|
+
this.status = status;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function get(path, key, { fetch: fetchImpl = globalThis.fetch, signal } = {}) {
|
|
22
|
+
let response;
|
|
23
|
+
try {
|
|
24
|
+
response = await fetchImpl(`${OPENROUTER_API}${path}`, { headers: { authorization: `Bearer ${key}`, accept: 'application/json' }, signal });
|
|
25
|
+
} catch (error) {
|
|
26
|
+
throw new OpenRouterAccountError(`OpenRouter is unreachable: ${error instanceof Error ? error.message : String(error)}`);
|
|
27
|
+
}
|
|
28
|
+
let body;
|
|
29
|
+
try { body = await response.json(); } catch { body = undefined; }
|
|
30
|
+
if (!response.ok) throw new OpenRouterAccountError(typeof body?.error?.message === 'string' ? body.error.message : `HTTP ${response.status}`, response.status);
|
|
31
|
+
return body;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Account credits from a `/credits` body, or undefined when it carries none. */
|
|
35
|
+
export function creditsOf(body) {
|
|
36
|
+
const total = finite(body?.data?.total_credits), used = finite(body?.data?.total_usage);
|
|
37
|
+
if (total === undefined || used === undefined || total < 0 || used < 0) return undefined;
|
|
38
|
+
return { total, used, remaining: Math.max(0, total - used) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Remaining USD account credits from a `/credits` body: purchased minus used. */
|
|
42
|
+
export function parseOpenRouterCredits(body) {
|
|
43
|
+
return creditsOf(body)?.remaining ?? null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Remaining USD credit limit from a `/key` body; null when the key has no limit. */
|
|
47
|
+
export function parseOpenRouterKeyRemaining(body) {
|
|
48
|
+
const remaining = body?.data?.limit_remaining;
|
|
49
|
+
if (remaining == null) return null;
|
|
50
|
+
const value = Number(remaining);
|
|
51
|
+
return Number.isFinite(value) ? Math.max(0, value) : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function keyOf(raw) {
|
|
55
|
+
return {
|
|
56
|
+
label: typeof raw?.label === 'string' ? raw.label : undefined,
|
|
57
|
+
name: typeof raw?.name === 'string' && raw.name.length > 0 ? raw.name : undefined,
|
|
58
|
+
disabled: raw?.disabled === true,
|
|
59
|
+
limit: finite(raw?.limit),
|
|
60
|
+
limitRemaining: finite(raw?.limit_remaining),
|
|
61
|
+
usage: finite(raw?.usage),
|
|
62
|
+
usageDaily: finite(raw?.usage_daily),
|
|
63
|
+
usageWeekly: finite(raw?.usage_weekly),
|
|
64
|
+
usageMonthly: finite(raw?.usage_monthly),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Verify a management key before it is stored. Account activity is the reading OpenRouter
|
|
70
|
+
* refuses an inference key; `/credits`, though documented as management-only, serves both.
|
|
71
|
+
* @throws OpenRouterAccountError with a message fit for the key prompt.
|
|
72
|
+
*/
|
|
73
|
+
export async function verifyManagementKey(key, options) {
|
|
74
|
+
try {
|
|
75
|
+
await get('/activity', key, options);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (error instanceof OpenRouterAccountError && (error.status === 401 || error.status === 403)) {
|
|
78
|
+
throw new OpenRouterAccountError('This is not a management key: OpenRouter refused it for account data. Create one under Settings → Management keys.', error.status);
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The `/activity` rows (last 30 completed UTC days) as totals and the top models with the providers that served them. */
|
|
85
|
+
export function summarizeActivity(rows, top = 5) {
|
|
86
|
+
const models = new Map(), days = new Set();
|
|
87
|
+
let usage = 0, requests = 0;
|
|
88
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
89
|
+
if (typeof row?.model !== 'string') continue;
|
|
90
|
+
const cost = finite(row.usage) ?? 0, count = finite(row.requests) ?? 0;
|
|
91
|
+
usage += cost;
|
|
92
|
+
requests += count;
|
|
93
|
+
if (typeof row.date === 'string') days.add(row.date);
|
|
94
|
+
const entry = models.get(row.model) ?? { model: row.model, usage: 0, requests: 0, providers: new Map() };
|
|
95
|
+
entry.usage += cost;
|
|
96
|
+
entry.requests += count;
|
|
97
|
+
const name = typeof row.provider_name === 'string' && row.provider_name.length > 0 ? row.provider_name : 'unknown';
|
|
98
|
+
const served = entry.providers.get(name) ?? { name, usage: 0, requests: 0 };
|
|
99
|
+
served.usage += cost;
|
|
100
|
+
served.requests += count;
|
|
101
|
+
entry.providers.set(name, served);
|
|
102
|
+
models.set(row.model, entry);
|
|
103
|
+
}
|
|
104
|
+
const ranked = [...models.values()].sort((left, right) => right.usage - left.usage || right.requests - left.requests).slice(0, top)
|
|
105
|
+
.map(entry => ({ ...entry, providers: [...entry.providers.values()].sort((left, right) => right.usage - left.usage) }));
|
|
106
|
+
return { usage, requests, days: days.size, modelCount: models.size, models: ranked };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Everything /openrouter shows. Each section settles on its own: `{ value }`, `{ error }`,
|
|
111
|
+
* or undefined when the key it needs is missing.
|
|
112
|
+
*/
|
|
113
|
+
export async function loadOpenRouterAccount({ apiKey, managementKey, fetch, signal } = {}) {
|
|
114
|
+
const options = { fetch, signal };
|
|
115
|
+
const section = (key, run) => key ? run().then(value => ({ value }), error => ({ error: error instanceof Error ? error.message : String(error) })) : Promise.resolve(undefined);
|
|
116
|
+
const [key, credits, keys, activity] = await Promise.all([
|
|
117
|
+
section(apiKey, async () => keyOf((await get('/key', apiKey, options))?.data)),
|
|
118
|
+
section(managementKey ?? apiKey, async () => {
|
|
119
|
+
const credits = creditsOf(await get('/credits', managementKey ?? apiKey, options));
|
|
120
|
+
if (!credits) throw new Error('OpenRouter returned no account credits');
|
|
121
|
+
return credits;
|
|
122
|
+
}),
|
|
123
|
+
section(managementKey, async () => {
|
|
124
|
+
const body = await get('/keys', managementKey, options);
|
|
125
|
+
return (Array.isArray(body?.data) ? body.data : []).map(keyOf);
|
|
126
|
+
}),
|
|
127
|
+
section(managementKey, async () => summarizeActivity((await get('/activity', managementKey, options))?.data)),
|
|
128
|
+
]);
|
|
129
|
+
return { hasApiKey: Boolean(apiKey), hasManagementKey: Boolean(managementKey), key, credits, keys, activity };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const money = value => Number.isFinite(value) ? `$${value.toFixed(2)}` : '$--';
|
|
133
|
+
const limitText = key => key.limit === undefined ? 'no limit' : `limit ${money(key.limit)}, ${money(key.limitRemaining)} left`;
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The panel's lines for a loaded account.
|
|
137
|
+
* @returns `{ text, tone }` rows; tone is `title`, `value`, `dim` or `error`.
|
|
138
|
+
*/
|
|
139
|
+
export function openRouterAccountLines(account, { maxKeys = 5 } = {}) {
|
|
140
|
+
const lines = [];
|
|
141
|
+
const push = (text, tone = 'value') => lines.push({ text, tone });
|
|
142
|
+
if (!account.hasApiKey) push('No OpenRouter API key: run /login openrouter.', 'error');
|
|
143
|
+
if (account.credits?.value) {
|
|
144
|
+
const { remaining, total, used } = account.credits.value;
|
|
145
|
+
push(`Account balance ${money(remaining)} · credits ${money(total)} · used ${money(used)}`, 'title');
|
|
146
|
+
} else if (account.credits?.error) push(`Account balance unavailable: ${account.credits.error}`, 'error');
|
|
147
|
+
else push('Account balance $--', 'dim');
|
|
148
|
+
if (account.key?.value) {
|
|
149
|
+
const key = account.key.value;
|
|
150
|
+
push(`This key ${key.label ?? 'unnamed'} · ${limitText(key)}`, 'title');
|
|
151
|
+
push(` today ${money(key.usageDaily)} · week ${money(key.usageWeekly)} · month ${money(key.usageMonthly)}`, 'dim');
|
|
152
|
+
} else if (account.key?.error) push(`This key unavailable: ${account.key.error}`, 'error');
|
|
153
|
+
if (!account.hasManagementKey) push('API keys and 30-day spend press m to add a management key', 'dim');
|
|
154
|
+
if (account.keys?.value) {
|
|
155
|
+
const keys = [...account.keys.value].sort((left, right) => (right.usageMonthly ?? 0) - (left.usageMonthly ?? 0));
|
|
156
|
+
push(`API keys (${keys.length})`, 'title');
|
|
157
|
+
for (const key of keys.slice(0, maxKeys)) {
|
|
158
|
+
const current = account.key?.value?.label !== undefined && key.label === account.key.value.label;
|
|
159
|
+
push(` ${key.name ?? key.label ?? 'unnamed'}${current ? ' (this key)' : ''}${key.disabled ? ' · disabled' : ''} · today ${money(key.usageDaily)} · month ${money(key.usageMonthly)} · ${limitText(key)}`, key.disabled ? 'dim' : 'value');
|
|
160
|
+
}
|
|
161
|
+
if (keys.length > maxKeys) push(` +${keys.length - maxKeys} more`, 'dim');
|
|
162
|
+
} else if (account.keys?.error) push(`API keys unavailable: ${account.keys.error}`, 'error');
|
|
163
|
+
if (account.activity?.value) {
|
|
164
|
+
const activity = account.activity.value;
|
|
165
|
+
push(`Last 30 days ${money(activity.usage)} · ${activity.requests} requests · ${activity.modelCount} models`, 'title');
|
|
166
|
+
for (const model of activity.models) {
|
|
167
|
+
push(` ${model.model} · ${money(model.usage)} · ${model.requests} req · ${model.providers.map(provider => `${provider.name} ${money(provider.usage)}`).join(', ')}`);
|
|
168
|
+
}
|
|
169
|
+
} else if (account.activity?.error) push(`Activity unavailable: ${account.activity.error}`, 'error');
|
|
170
|
+
return lines;
|
|
171
|
+
}
|
|
@@ -1,10 +1,18 @@
|
|
|
1
|
+
import { OPENROUTER_API, parseOpenRouterCredits, parseOpenRouterKeyRemaining } from '../providers/openrouter-account.mjs';
|
|
2
|
+
|
|
3
|
+
export { parseOpenRouterCredits, parseOpenRouterKeyRemaining };
|
|
4
|
+
|
|
1
5
|
// Remaining provider balance, refreshed on a long cache. DeepSeek's response
|
|
2
6
|
// also carries the trusted clock: its `Date` header anchors peak/off-peak pricing
|
|
3
|
-
// without a second network call. OpenRouter has no peak window
|
|
4
|
-
//
|
|
7
|
+
// without a second network call. OpenRouter has no peak window. Its account
|
|
8
|
+
// credits (`/credits`) are documented as management-only but are served to
|
|
9
|
+
// inference keys too; a key refused them falls back to its own remaining limit (`/key`).
|
|
5
10
|
const SOURCES = {
|
|
6
|
-
'deepseek-official': { url: 'https://api.deepseek.com/user/balance',
|
|
7
|
-
openrouter: {
|
|
11
|
+
'deepseek-official': { env: 'DEEPSEEK_API_KEY', clock: true, requests: ({ key }) => [{ url: 'https://api.deepseek.com/user/balance', key, parse: body => parseBalance(body) }] },
|
|
12
|
+
openrouter: { env: 'OPENROUTER_API_KEY', managementEnv: 'OPENROUTER_MANAGEMENT_KEY', clock: false, requests: ({ key, managementKey }) => [
|
|
13
|
+
{ url: `${OPENROUTER_API}/credits`, key: managementKey ?? key, parse: parseOpenRouterCredits },
|
|
14
|
+
{ url: `${OPENROUTER_API}/key`, key, parse: parseOpenRouterKeyRemaining },
|
|
15
|
+
] },
|
|
8
16
|
};
|
|
9
17
|
export const BALANCE_PROVIDERS = Object.freeze(Object.keys(SOURCES));
|
|
10
18
|
const CACHE_MS = 5 * 60 * 1000;
|
|
@@ -22,14 +30,6 @@ export function parseBalance(body) {
|
|
|
22
30
|
return body?.is_available === false ? null : total;
|
|
23
31
|
}
|
|
24
32
|
|
|
25
|
-
/** Remaining USD credits from an OpenRouter `/credits` body: purchased minus used. */
|
|
26
|
-
export function parseOpenRouterCredits(body) {
|
|
27
|
-
const credits = Number(body?.data?.total_credits), used = Number(body?.data?.total_usage);
|
|
28
|
-
if (body?.data?.total_credits == null || body?.data?.total_usage == null) return null;
|
|
29
|
-
if (!Number.isFinite(credits) || !Number.isFinite(used) || credits < 0 || used < 0) return null;
|
|
30
|
-
return Math.max(0, credits - used);
|
|
31
|
-
}
|
|
32
|
-
|
|
33
33
|
export function balanceNow(provider = 'deepseek-official') { return snapshotOf(provider).balance; }
|
|
34
34
|
/** Clock anchored to the last DeepSeek balance response's `Date` header, else the local one. */
|
|
35
35
|
export function trustedNow() {
|
|
@@ -43,29 +43,39 @@ export async function refreshBalance(options = {}) {
|
|
|
43
43
|
const source = SOURCES[provider];
|
|
44
44
|
if (!source) return null;
|
|
45
45
|
const snapshot = snapshotOf(provider);
|
|
46
|
+
const key = options.key ?? process.env[source.env];
|
|
47
|
+
const managementKey = options.managementKey ?? (source.managementEnv ? process.env[source.managementEnv] : undefined);
|
|
48
|
+
const requests = source.requests({ key, managementKey }).filter(request => request.key);
|
|
49
|
+
const mode = managementKey ? 'management' : 'key';
|
|
46
50
|
const now = Date.now();
|
|
47
|
-
|
|
51
|
+
// A newly added (or removed) management key changes the source; it is read at once.
|
|
52
|
+
if (snapshot.pending || snapshot.mode === mode && now - snapshot.fetchedAt < CACHE_MS) return snapshot.balance;
|
|
48
53
|
const retrySoon = () => Date.now() - (CACHE_MS - RETRY_MS);
|
|
49
|
-
|
|
50
|
-
if (!key) { snapshots.set(provider, { ...snapshot, fetchedAt: retrySoon(), pending: false }); return snapshot.balance; }
|
|
54
|
+
if (requests.length === 0) { snapshots.set(provider, { ...snapshot, mode, fetchedAt: retrySoon(), pending: false }); return snapshot.balance; }
|
|
51
55
|
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
52
56
|
if (typeof fetchImpl !== 'function') return snapshot.balance;
|
|
53
57
|
snapshots.set(provider, { ...snapshot, pending: true });
|
|
54
58
|
try {
|
|
55
|
-
|
|
59
|
+
let response, body, request;
|
|
60
|
+
for (request of requests) {
|
|
61
|
+
response = await fetchImpl(request.url, { headers: { Authorization: `Bearer ${request.key}`, Accept: 'application/json' } });
|
|
62
|
+
body = await response.json();
|
|
63
|
+
// A key refused this reading falls through to the next source.
|
|
64
|
+
if (response.ok || (response.status !== 401 && response.status !== 403)) break;
|
|
65
|
+
}
|
|
56
66
|
const header = source.clock ? response.headers?.get?.('date') : null;
|
|
57
67
|
const anchor = header ? Date.parse(header) : NaN;
|
|
58
|
-
const
|
|
59
|
-
const parsed = response.ok ? source.parse(body) : null;
|
|
68
|
+
const parsed = response.ok ? request.parse(body) : null;
|
|
60
69
|
if (Number.isFinite(anchor)) clock = { anchor, skewMs: anchor - Date.now() };
|
|
61
70
|
snapshots.set(provider, {
|
|
71
|
+
mode,
|
|
62
72
|
balance: parsed === null && response.ok ? null : parsed ?? snapshot.balance,
|
|
63
73
|
fetchedAt: parsed === null ? retrySoon() : Date.now(),
|
|
64
74
|
pending: false,
|
|
65
75
|
});
|
|
66
76
|
} catch {
|
|
67
77
|
// A transient failure keeps the last known balance and retries sooner.
|
|
68
|
-
snapshots.set(provider, { ...snapshot, fetchedAt: retrySoon(), pending: false });
|
|
78
|
+
snapshots.set(provider, { ...snapshot, mode, fetchedAt: retrySoon(), pending: false });
|
|
69
79
|
}
|
|
70
80
|
return snapshotOf(provider).balance;
|
|
71
81
|
}
|
|
@@ -3,7 +3,8 @@ import { appendMetric } from './store.mjs';
|
|
|
3
3
|
import { estimateCost, priceVersionFor } from './pricing.mjs';
|
|
4
4
|
import { setMetricSource } from './view.mjs';
|
|
5
5
|
import { BALANCE_PROVIDERS, refreshBalance } from './balance.mjs';
|
|
6
|
-
import {
|
|
6
|
+
import { refreshOpenRouterModels } from '../openrouter/models.mjs';
|
|
7
|
+
import { REPLAY_KIND } from '../openrouter/wire.mjs';
|
|
7
8
|
import { providerSpec } from '../providers/catalog.mjs';
|
|
8
9
|
import { createWindowRate } from './rate.mjs';
|
|
9
10
|
import { currentCharge } from './attribution.mjs';
|
|
@@ -34,12 +35,17 @@ export function apply(ctx) {
|
|
|
34
35
|
const credentials = ctx.get?.('credentials');
|
|
35
36
|
const refresh = () => Promise.all(BALANCE_PROVIDERS.map(async provider => {
|
|
36
37
|
try {
|
|
37
|
-
const
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
38
|
+
const spec = providerSpec(provider);
|
|
39
|
+
const secret = async ref => {
|
|
40
|
+
if (!ref) return undefined;
|
|
41
|
+
const resolved = await credentials?.resolve?.(ref);
|
|
42
|
+
return (typeof resolved === 'string' ? resolved : resolved?.value) || process.env[ref] || undefined;
|
|
43
|
+
};
|
|
44
|
+
// An OpenRouter management key, when stored, turns the balance into the account's credits.
|
|
45
|
+
const [key, managementKey] = await Promise.all([secret(spec.credentialRef), secret(spec.managementRef)]);
|
|
46
|
+
await refreshBalance({ provider, key, managementKey });
|
|
47
|
+
// The listing needs no key, but only a user with an OpenRouter key uses it; the adapter waits for it before its first call.
|
|
48
|
+
if (provider === 'openrouter' && key) await refreshOpenRouterModels({ home });
|
|
43
49
|
} catch {
|
|
44
50
|
/* balance stays unknown */
|
|
45
51
|
}
|
|
@@ -64,19 +70,23 @@ export function apply(ctx) {
|
|
|
64
70
|
}
|
|
65
71
|
const save = entry => { for (const recipient of recipients) record(recipient, { ...entry, sessionId }); };
|
|
66
72
|
save({ kind: 'start', id, time, provider: options.provider, model: options.model, purpose });
|
|
67
|
-
let usage, firstTokenTime;
|
|
73
|
+
let usage, firstTokenTime, billed;
|
|
68
74
|
const liveSession = purpose === 'agent' ? ctx.agents.get(sessionId)?.session : undefined;
|
|
69
75
|
try {
|
|
70
76
|
for await (const chunk of next()) {
|
|
71
77
|
if (chunk.type === 'usage') usage = chunk.usage;
|
|
72
78
|
else if (firstTokenTime === undefined && OUTPUT_CHUNKS.has(chunk.type)) firstTokenTime = Date.now();
|
|
79
|
+
// OpenRouter reports what it charged; the finish of its response carries it.
|
|
80
|
+
if (chunk.type === 'finish' && chunk.replayState?.response?.kind === REPLAY_KIND && Number.isFinite(chunk.replayState.response.cost)) billed = chunk.replayState.response.cost;
|
|
73
81
|
if (liveSession) liveRate.add(liveSession, chunk);
|
|
74
82
|
yield chunk;
|
|
75
83
|
}
|
|
76
84
|
} finally {
|
|
77
85
|
if (liveSession) liveRate.calibrate(liveSession, usage?.outputTokens);
|
|
78
86
|
// `time` stays the start (it prices the call); `endTime` and `firstTokenTime` time it.
|
|
79
|
-
save({ kind: 'end', id, time, endTime: Date.now(), ...(firstTokenTime === undefined ? {} : { firstTokenTime }), usage: usage ?? null,
|
|
87
|
+
save({ kind: 'end', id, time, endTime: Date.now(), ...(firstTokenTime === undefined ? {} : { firstTokenTime }), usage: usage ?? null, ...(billed === undefined
|
|
88
|
+
? { cost: estimateCost(options.provider, options.model, usage, time), priceVersion: priceVersionFor(options.provider, options.model) }
|
|
89
|
+
: { cost: billed, priceVersion: 'openrouter-billed' }) });
|
|
80
90
|
}
|
|
81
91
|
});
|
|
82
92
|
}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { openRouterPriceVersion, openRouterRates } from '
|
|
1
|
+
import { openRouterPriceVersion, openRouterRates } from '../openrouter/models.mjs';
|
|
2
2
|
|
|
3
3
|
// USD per million tokens. Snapshot of the official page opened 2026-09-11.
|
|
4
4
|
// https://api-docs.deepseek.com/quick_start/pricing/
|
|
5
5
|
export const PRICE_SOURCE = 'https://api-docs.deepseek.com/quick_start/pricing/';
|
|
6
6
|
export const PRICE_VERSION = 'deepseek-2026-09-11';
|
|
7
|
-
// OpenRouter calls
|
|
7
|
+
// OpenRouter calls carry their billed cost; an unbilled one is estimated from the live model listing (plugins/openrouter/models.mjs).
|
|
8
8
|
// Until that table loads, the DeepSeek models keep these list prices from the pinned
|
|
9
9
|
// pi-ai 0.85.1 catalog. OpenRouter bills no peak window. [cache read, input, output].
|
|
10
10
|
export const OPENROUTER_PRICE_VERSION = 'openrouter-pi-ai-0.85.1';
|
|
@@ -31,13 +31,33 @@ export function estimateCost(provider, model, usage, time) {
|
|
|
31
31
|
return OPENROUTER_PRICES[model] ? charge(usage, OPENROUTER_PRICES[model]) : null;
|
|
32
32
|
}
|
|
33
33
|
if (provider !== 'deepseek-official') return null;
|
|
34
|
+
const rates = deepSeekRates(model, time);
|
|
35
|
+
if (!rates) return null;
|
|
36
|
+
const cost = charge(usage, rates);
|
|
37
|
+
return cost === null ? null : cost * (isPeak(time) ? 2 : 1);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** DeepSeek list prices [cache read, input, output] at `time`, before the peak multiplier. */
|
|
41
|
+
function deepSeekRates(model, time) {
|
|
34
42
|
// Earlier requests require an older price table; never back-price them at today's rate.
|
|
35
|
-
if (time < Date.UTC(2026, 8, 11)) return
|
|
43
|
+
if (time < Date.UTC(2026, 8, 11)) return undefined;
|
|
36
44
|
const flash = ['deepseek-flash', 'deepseek-v4-flash', 'deepseek-v4-flash-vision-exp'].includes(model)
|
|
37
45
|
|| model === 'deepseek-v4-pro' && time >= Date.UTC(2026, 8, 14, 4);
|
|
38
|
-
if (!flash && model !== 'deepseek-v4-pro') return
|
|
39
|
-
|
|
40
|
-
|
|
46
|
+
if (!flash && model !== 'deepseek-v4-pro') return undefined;
|
|
47
|
+
return flash ? [0.003, 0.15, 0.6] : [0.022, 0.66, 1.98];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Cache-read price over input price for a route, or undefined when the route is unpriced.
|
|
52
|
+
* A model that lists no cache-read price bills cached input at the input rate (1).
|
|
53
|
+
*/
|
|
54
|
+
export function cacheReadRatio(provider, model, time = Date.now()) {
|
|
55
|
+
let rates;
|
|
56
|
+
if (provider === 'openrouter') {
|
|
57
|
+
const live = openRouterRates(model);
|
|
58
|
+
rates = live ? [live.cacheRead ?? live.input, live.input] : OPENROUTER_PRICES[model];
|
|
59
|
+
} else if (provider === 'deepseek-official') rates = deepSeekRates(model, time);
|
|
60
|
+
return rates && rates[1] > 0 ? rates[0] / rates[1] : undefined;
|
|
41
61
|
}
|
|
42
62
|
|
|
43
63
|
/** Cost in USD; cache writes need a write price, or the call stays unpriced. */
|
|
@@ -34,7 +34,7 @@ export function summarize(rows, events = [], corrupt = false) {
|
|
|
34
34
|
const u = row.usage;
|
|
35
35
|
if (!u || !Number.isFinite(u.inputTokens) || !Number.isFinite(u.outputTokens)) { cacheUnknown = true; continue; }
|
|
36
36
|
const total = u.inputTokens + (u.cacheReadTokens ?? 0) + (u.cacheWriteTokens ?? 0);
|
|
37
|
-
//
|
|
37
|
+
// OpenRouter reports cache reads only when there are some: a missing count is zero, not unknown.
|
|
38
38
|
input += total; hit += u.cacheReadTokens ?? 0;
|
|
39
39
|
}
|
|
40
40
|
return { cost, unknown, calls, pending, cache: input > 0 && !cacheUnknown ? Math.min(100, hit / input * 100) : null };
|
package/plugins/ultra/policy.mjs
CHANGED
|
@@ -16,22 +16,6 @@ export function flashRequest(options, messages) {
|
|
|
16
16
|
return copy;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
/**
|
|
20
|
-
* The same shaping for pi-ai routes (OpenRouter), on harness-format options:
|
|
21
|
-
* Ultra sends max and adds the collaboration policy. Delegation tools are offered
|
|
22
|
-
* at every effort (the shell policy keeps delegation rare below Ultra); workflow
|
|
23
|
-
* and ralph never are. Returns a copy; the logged input is never mutated.
|
|
24
|
-
*/
|
|
25
|
-
export function piAiRequest(options) {
|
|
26
|
-
const ultra = options.reasoningEffort === 'ultra';
|
|
27
|
-
const next = { ...options, ...(options.tools ? { tools: options.tools.filter(tool => tool.name !== 'workflow' && tool.name !== 'ralph') } : {}), ...(ultra ? { reasoningEffort: 'max' } : {}) };
|
|
28
|
-
if (!ultra || options.purpose || !options.tools?.some(t => t.name === 'subagent' || t.name === 'subagent_fork')) return next;
|
|
29
|
-
if (typeof next.system === 'string') return { ...next, system: next.system + '\n\n' + ULTRA_POLICY };
|
|
30
|
-
const [first, ...rest] = next.messages ?? [];
|
|
31
|
-
if (first?.role === 'system' && Array.isArray(first.content)) return { ...next, messages: [{ ...first, content: [...first.content, { type: 'text', text: '\n\n' + ULTRA_POLICY }] }, ...rest] };
|
|
32
|
-
return { ...next, messages: [{ role: 'system', content: [{ type: 'text', text: ULTRA_POLICY }] }, ...(next.messages ?? [])] };
|
|
33
|
-
}
|
|
34
|
-
|
|
35
19
|
export function ultraRequest(options, messages) {
|
|
36
20
|
if (options.reasoningEffort !== 'ultra' || options.purpose || !options.tools?.some(t => t.name === 'subagent' || t.name === 'subagent_fork')) return messages;
|
|
37
21
|
const copy = messages.map(m => ({ ...m }));
|