relay-opencode 0.0.0-stage → 0.2.0

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/dist/artificial-analysis.d.ts +50 -0
  4. package/dist/artificial-analysis.js +153 -0
  5. package/dist/chat-facts.d.ts +26 -0
  6. package/dist/chat-facts.js +96 -0
  7. package/dist/contract.d.ts +2727 -0
  8. package/dist/contract.js +111 -0
  9. package/dist/costs.d.ts +14 -0
  10. package/dist/costs.js +47 -0
  11. package/dist/decider.d.ts +73 -0
  12. package/dist/decider.js +199 -0
  13. package/dist/gui-experimental.cjs +92 -0
  14. package/dist/gui-styles.d.ts +5 -0
  15. package/dist/gui-styles.js +95 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +62 -0
  18. package/dist/intelligence.d.ts +38 -0
  19. package/dist/intelligence.js +123 -0
  20. package/dist/inventory.d.ts +34 -0
  21. package/dist/inventory.js +28 -0
  22. package/dist/ranking.d.ts +31 -0
  23. package/dist/ranking.js +78 -0
  24. package/dist/relay-auto.d.ts +39 -0
  25. package/dist/relay-auto.js +96 -0
  26. package/dist/relay-command.d.ts +74 -0
  27. package/dist/relay-command.js +211 -0
  28. package/dist/relay-store.d.ts +124 -0
  29. package/dist/relay-store.js +196 -0
  30. package/dist/relay-view.d.ts +124 -0
  31. package/dist/relay-view.js +189 -0
  32. package/dist/review-helper.d.ts +8 -0
  33. package/dist/review-helper.js +68 -0
  34. package/dist/router.d.ts +122 -0
  35. package/dist/router.js +209 -0
  36. package/dist/rpc.d.ts +2725 -0
  37. package/dist/rpc.js +116 -0
  38. package/dist/settings.d.ts +16 -0
  39. package/dist/settings.js +22 -0
  40. package/dist/standings.d.ts +18 -0
  41. package/dist/standings.js +34 -0
  42. package/dist/tui.d.ts +3 -0
  43. package/dist/tui.js +26 -0
  44. package/dist/usage-log.d.ts +135 -0
  45. package/dist/usage-log.js +210 -0
  46. package/dist/usage-view.d.ts +70 -0
  47. package/dist/usage-view.js +104 -0
  48. package/package.json +46 -4
@@ -0,0 +1,70 @@
1
+ import type { UsageDay, UsageRecord, UsageTotal } from './usage-log.js';
2
+ export type Range = 'today' | '7d' | '30d' | '90d';
3
+ export declare const RANGES: readonly {
4
+ id: Range;
5
+ label: string;
6
+ }[];
7
+ /** A range in the panel's own days: from local midnight (today, or that many days before) to now, with the offset the server counts days by. */
8
+ export declare function rangeOf(range: Range, now: Date): {
9
+ from: string;
10
+ to: string;
11
+ tzOffsetMinutes: number;
12
+ timeZone: string;
13
+ };
14
+ /** The records one page holds, and how many a refresh asks for: as many as are shown (up to the server's 200), so a refresh keeps Show more. */
15
+ export declare const PAGE = 50, PAGE_MAX = 200;
16
+ export declare const refreshLimit: (shown: number) => number;
17
+ /** The cost the tab shows: by price when the model has one, else OpenCode's own when it is more than $0, else none. */
18
+ export declare function shownCost(record: Pick<UsageRecord, 'costByPrice' | 'openCodeUsd'>): string | null;
19
+ /** Money as the tab shows it: to the cent from $0.10 up, else two significant digits ($0.069, $0.0021); rounded with bigint, never a float. */
20
+ export declare function money(usd: string | null): string;
21
+ /** A count as the tab shows it: 950, 15.8K, 2.3M. */
22
+ export declare const short: (count: number) => string;
23
+ export type Metric = 'cost' | 'tokens' | 'requests';
24
+ /** The chart's top value, the tallest bar's; `max` is in millionths of a dollar for cost, as `chartOf` gives it. */
25
+ export declare const scaleLabel: (metric: Metric, max: number) => string;
26
+ /** The names under the chart's bars (days as YYYY-MM-DD): a weekday and date each for up to ten days, else the first, middle and last dates. */
27
+ export declare function dayLabels(days: readonly string[]): string[];
28
+ /** One model's row in By model: its name and cost, then its provider, replies, every kind of token, and how many replies the cost leaves out. */
29
+ export declare function totalCells(total: UsageTotal): {
30
+ name: string;
31
+ provider: string;
32
+ cost: string;
33
+ tokens: string;
34
+ detail: string;
35
+ };
36
+ export declare const METRICS: readonly {
37
+ id: Metric;
38
+ label: string;
39
+ }[];
40
+ type Part = {
41
+ model: string;
42
+ value: number;
43
+ color: string;
44
+ };
45
+ /** One bar a day, split by model: the `top` largest models of the range by `metric`, and the rest as "other". `max` is the tallest bar. */
46
+ export declare function chartOf(days: readonly UsageDay[], metric: Metric, top?: number): {
47
+ bars: {
48
+ day: string;
49
+ total: number;
50
+ title: string;
51
+ parts: Part[];
52
+ }[];
53
+ legend: {
54
+ model: string;
55
+ color: string;
56
+ }[];
57
+ max: number;
58
+ };
59
+ /** One row of the records list: time, model and cost, then provider, kind and chat, mode, tokens, project and what Relay did. In counts what was read
60
+ * new, from a cache and into a cache; out counts reasoning too. */
61
+ export declare function recordCells(record: UsageRecord): {
62
+ time: string;
63
+ model: string;
64
+ name: string;
65
+ cost: string;
66
+ detail: string;
67
+ };
68
+ /** Show more's rows: the next page without those already shown, since a reply that arrives meanwhile moves every offset by one. */
69
+ export declare function appendNew(shown: readonly UsageRecord[], next: readonly UsageRecord[]): UsageRecord[];
70
+ export {};
@@ -0,0 +1,104 @@
1
+ import { formatUsd, parseUsd } from './costs.js';
2
+ export const RANGES = [{ id: 'today', label: 'Today' }, { id: '7d', label: '7 days' }, { id: '30d', label: '30 days' }, { id: '90d', label: '90 days' }];
3
+ const DAYS_BACK = { today: 0, '7d': 6, '30d': 29, '90d': 89 };
4
+ /** A range in the panel's own days: from local midnight (today, or that many days before) to now, with the offset the server counts days by. */
5
+ export function rangeOf(range, now) {
6
+ const start = new Date(now.getFullYear(), now.getMonth(), now.getDate() - DAYS_BACK[range]);
7
+ return { from: start.toISOString(), to: now.toISOString(), tzOffsetMinutes: -now.getTimezoneOffset(), timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone };
8
+ }
9
+ /** The records one page holds, and how many a refresh asks for: as many as are shown (up to the server's 200), so a refresh keeps Show more. */
10
+ export const PAGE = 50, PAGE_MAX = 200;
11
+ export const refreshLimit = (shown) => Math.min(PAGE_MAX, Math.max(PAGE, shown));
12
+ /** The cost the tab shows: by price when the model has one, else OpenCode's own when it is more than $0, else none. */
13
+ export function shownCost(record) {
14
+ if (record.costByPrice !== null)
15
+ return record.costByPrice;
16
+ return record.openCodeUsd !== null && parseUsd(record.openCodeUsd) > 0n ? record.openCodeUsd : null;
17
+ }
18
+ const amount = (count) => Math.round(count).toLocaleString('en-US');
19
+ const SCALE = parseUsd('1'), DIME = SCALE / 10n;
20
+ /** Money as the tab shows it: to the cent from $0.10 up, else two significant digits ($0.069, $0.0021); rounded with bigint, never a float. */
21
+ export function money(usd) {
22
+ if (usd === null)
23
+ return 'no price';
24
+ const value = parseUsd(usd);
25
+ if (value === 0n)
26
+ return '$0';
27
+ if (value < DIME) {
28
+ const decimals = Math.min(12, 14 - value.toString().length), unit = 10n ** BigInt(12 - decimals), rounded = (value + unit / 2n) / unit;
29
+ if (rounded * unit < DIME)
30
+ return `$0.${rounded.toString().padStart(decimals, '0').replace(/0+$/, '').padEnd(2, '0')}`;
31
+ }
32
+ const cents = (value + SCALE / 200n) / (SCALE / 100n);
33
+ return `$${(cents / 100n).toLocaleString('en-US')}.${(cents % 100n).toString().padStart(2, '0')}`;
34
+ }
35
+ const SHORT = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 });
36
+ /** A count as the tab shows it: 950, 15.8K, 2.3M. */
37
+ export const short = (count) => SHORT.format(Math.round(count));
38
+ /** The chart's top value, the tallest bar's; `max` is in millionths of a dollar for cost, as `chartOf` gives it. */
39
+ export const scaleLabel = (metric, max) => metric === 'cost' ? money(formatUsd(BigInt(Math.round(max)) * 1000000n)) : short(max);
40
+ const WEEKDAYS = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
41
+ /** The names under the chart's bars (days as YYYY-MM-DD): a weekday and date each for up to ten days, else the first, middle and last dates. */
42
+ export function dayLabels(days) {
43
+ const at = (day) => new Date(`${day}T12:00:00Z`);
44
+ if (days.length <= 10)
45
+ return days.map(day => `${WEEKDAYS[at(day).getUTCDay()]} ${at(day).getUTCDate()}`);
46
+ const kept = new Set([0, Math.floor(days.length / 2), days.length - 1]);
47
+ return days.map((day, n) => kept.has(n) ? `${at(day).getUTCDate()} ${MONTHS[at(day).getUTCMonth()]}` : '');
48
+ }
49
+ const nameOf = (model) => model.slice(model.indexOf('/') + 1);
50
+ /** One model's row in By model: its name and cost, then its provider, replies, every kind of token, and how many replies the cost leaves out. */
51
+ export function totalCells(total) {
52
+ const slash = total.model.indexOf('/'), provider = slash < 0 ? '' : total.model.slice(0, slash);
53
+ const tokens = short(total.input + total.output + total.reasoning + total.cacheRead + total.cacheWrite);
54
+ return { name: nameOf(total.model), provider, cost: `${money(total.cost)}${total.cost !== null && total.aaPriced ? '*' : ''}`, tokens,
55
+ detail: [provider, `${amount(total.replies)} ${total.replies === 1 ? 'reply' : 'replies'}`, `${tokens} tokens`, total.cost !== null && total.unpriced ? `${amount(total.unpriced)} without a price` : ''].filter(Boolean).join(' · ') };
56
+ }
57
+ export const METRICS = [{ id: 'cost', label: 'Cost' }, { id: 'tokens', label: 'Tokens' }, { id: 'requests', label: 'Requests' }];
58
+ const COLORS = ['#4f7cff', '#2ea36a', '#d99a1c', '#9b6bff', '#e05a8a'], OTHER = '#8b949e';
59
+ /** A cost in millionths of a dollar: a whole number, for bar heights only. Labels come from the USD strings. */
60
+ const micro = (cost) => cost === null ? 0 : Number(parseUsd(cost) / 1000000n);
61
+ const valueOf = (metric, model) => metric === 'cost' ? micro(model.cost) : metric === 'tokens' ? model.tokens : model.requests;
62
+ const labelOf = (metric, models) => {
63
+ if (metric === 'cost') {
64
+ const known = models.flatMap(model => model.cost === null ? [] : [parseUsd(model.cost)]);
65
+ return known.length ? money(formatUsd(known.reduce((sum, cost) => sum + cost, 0n))) : 'no price';
66
+ }
67
+ return metric === 'tokens' ? `${short(models.reduce((sum, model) => sum + model.tokens, 0))} tokens` : `${short(models.reduce((sum, model) => sum + model.requests, 0))} requests`;
68
+ };
69
+ /** One bar a day, split by model: the `top` largest models of the range by `metric`, and the rest as "other". `max` is the tallest bar. */
70
+ export function chartOf(days, metric, top = 5) {
71
+ const sums = new Map();
72
+ for (const day of days)
73
+ for (const model of day.models)
74
+ sums.set(model.model, (sums.get(model.model) ?? 0) + valueOf(metric, model));
75
+ const ranked = [...sums].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([model]) => model), kept = ranked.slice(0, top), rest = ranked.length > top;
76
+ const colorOf = (model) => kept.includes(model) ? COLORS[kept.indexOf(model) % COLORS.length] : OTHER;
77
+ const bars = days.map(day => {
78
+ const parts = kept.flatMap(model => { const mine = day.models.find(item => item.model === model); return mine ? [{ model, value: valueOf(metric, mine), color: colorOf(model) }] : []; });
79
+ const others = day.models.filter(item => !kept.includes(item.model));
80
+ if (others.length)
81
+ parts.push({ model: 'other', value: others.reduce((sum, item) => sum + valueOf(metric, item), 0), color: OTHER });
82
+ const shares = [...kept.flatMap(model => { const mine = day.models.find(item => item.model === model); return mine ? [`${model} ${labelOf(metric, [mine])}`] : []; }), ...(others.length ? [`other ${labelOf(metric, others)}`] : [])];
83
+ return { day: day.day, total: parts.reduce((sum, part) => sum + part.value, 0), title: `${day.day}: ${shares.length ? shares.join(', ') : 'no use'}`, parts };
84
+ });
85
+ return { bars, legend: [...kept.map(model => ({ model, color: colorOf(model) })), ...(rest ? [{ model: 'other', color: OTHER }] : [])], max: bars.reduce((most, bar) => Math.max(most, bar.total), 0) };
86
+ }
87
+ /** One row of the records list: time, model and cost, then provider, kind and chat, mode, tokens, project and what Relay did. In counts what was read
88
+ * new, from a cache and into a cache; out counts reasoning too. */
89
+ export function recordCells(record) {
90
+ const cost = shownCost(record), folder = record.project.split(/[\\/]/).filter(Boolean).at(-1) ?? record.project, model = record.model ?? 'unknown model';
91
+ const provider = model.includes('/') ? model.slice(0, model.indexOf('/')) : '', mode = record.relay?.mode ?? record.agent ?? '';
92
+ const relay = record.relay ? (record.relay.note ? `Relay: ${record.relay.note}` : 'Relay on') : 'Relay off';
93
+ const tokens = `${short(record.input + record.cacheRead + record.cacheWrite)} in · ${short(record.output + record.reasoning)} out`;
94
+ return {
95
+ time: new Date(record.at).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }), model, name: record.model ? nameOf(record.model) : model,
96
+ cost: cost === null ? 'no price' : `${money(cost)}${record.costByPrice !== null && record.pricesFrom === 'artificial-analysis' ? '*' : ''}`,
97
+ detail: [provider, `${record.kind} ${record.sessionID.slice(-6)}`, mode, tokens, folder, relay].filter(Boolean).join(' · '),
98
+ };
99
+ }
100
+ /** Show more's rows: the next page without those already shown, since a reply that arrives meanwhile moves every offset by one. */
101
+ export function appendNew(shown, next) {
102
+ const key = (record) => `${record.sessionID}/${record.messageID}`, seen = new Set(shown.map(key));
103
+ return [...shown, ...next.filter(record => !seen.has(key(record)))];
104
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "relay-opencode",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Relay for OpenCode: picks the model for each message (plan, execute or review), switches the chat to it, and sends the message.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AsadKhalil/relay-opencode.git"
9
+ },
10
+ "homepage": "https://github.com/AsadKhalil/relay-opencode#readme",
11
+ "bugs": "https://github.com/AsadKhalil/relay-opencode/issues",
12
+ "keywords": [
13
+ "opencode",
14
+ "opencode-plugin",
15
+ "relay",
16
+ "model-routing"
17
+ ],
18
+ "type": "module",
19
+ "scripts": {
20
+ "test": "tsx --test tests/*.test.ts",
21
+ "typecheck": "tsc --noEmit",
22
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && vite build",
23
+ "smoke:host:model": "node scripts/smoke-host-model.mjs",
24
+ "examples:decider": "tsx scripts/decider-examples.ts",
25
+ "prepublishOnly": "npm run typecheck && npm test && npm run build && node scripts/check-package.mjs"
26
+ },
27
+ "dependencies": {
28
+ "@opencode/plugin": "2.3.0"
29
+ },
30
+ "devDependencies": {
31
+ "@opencode/client": "2.3.0",
32
+ "@opencode/schema": "2.3.0",
33
+ "@types/node": "^24.0.0",
34
+ "solid-js": "^1.9.17",
35
+ "tsx": "^4.0.0",
36
+ "typescript": "^5.9.0",
37
+ "vite": "^7.3.7",
38
+ "vite-plugin-solid": "^2.11.10"
39
+ },
40
+ "exports": {
41
+ ".": "./dist/index.js",
42
+ "./gui-experimental": "./dist/gui-experimental.cjs",
43
+ "./tui": "./dist/tui.js"
44
+ },
45
+ "files": [
46
+ "dist"
47
+ ]
48
+ }