relay-opencode 0.1.0 → 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.
- package/README.md +82 -115
- package/dist/artificial-analysis.d.ts +50 -0
- package/dist/artificial-analysis.js +153 -0
- package/dist/chat-facts.d.ts +19 -3
- package/dist/chat-facts.js +67 -12
- package/dist/contract.d.ts +1172 -6
- package/dist/contract.js +57 -3
- package/dist/costs.d.ts +7 -0
- package/dist/costs.js +22 -0
- package/dist/decider.d.ts +24 -0
- package/dist/decider.js +104 -14
- package/dist/gui-experimental.cjs +32 -6
- package/dist/gui-styles.d.ts +1 -1
- package/dist/gui-styles.js +29 -3
- package/dist/index.js +9 -3
- package/dist/intelligence.d.ts +4 -0
- package/dist/intelligence.js +10 -0
- package/dist/ranking.d.ts +31 -0
- package/dist/ranking.js +78 -0
- package/dist/relay-auto.d.ts +23 -4
- package/dist/relay-auto.js +53 -11
- package/dist/relay-command.d.ts +0 -5
- package/dist/relay-command.js +15 -13
- package/dist/relay-store.d.ts +64 -4
- package/dist/relay-store.js +94 -9
- package/dist/relay-view.d.ts +37 -1
- package/dist/relay-view.js +68 -8
- package/dist/review-helper.d.ts +1 -1
- package/dist/review-helper.js +26 -7
- package/dist/router.d.ts +30 -5
- package/dist/router.js +54 -10
- package/dist/rpc.d.ts +1168 -6
- package/dist/rpc.js +59 -16
- package/dist/standings.d.ts +18 -0
- package/dist/standings.js +34 -0
- package/dist/tui.d.ts +3 -0
- package/dist/tui.js +26 -0
- package/dist/usage-log.d.ts +135 -0
- package/dist/usage-log.js +210 -0
- package/dist/usage-view.d.ts +70 -0
- package/dist/usage-view.js +104 -0
- package/package.json +3 -2
package/dist/relay-auto.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { PromptInput } from '@opencode/schema/prompt-input';
|
|
2
|
+
import type { AaModel } from './artificial-analysis.js';
|
|
2
3
|
import { type RelayDeps } from './relay-command.js';
|
|
4
|
+
import { type LogStore } from './usage-log.js';
|
|
3
5
|
/** How long a chat may take to show it is idle before it counts as busy and is left as it is. */
|
|
4
6
|
export declare const BUSY_CHECK_MS = 300;
|
|
5
7
|
type PromptEvent = {
|
|
@@ -10,11 +12,28 @@ type PromptEvent = {
|
|
|
10
12
|
};
|
|
11
13
|
export declare function relayAutoHook(deps: RelayDeps): (event: PromptEvent) => Promise<void>;
|
|
12
14
|
/**
|
|
13
|
-
* What a reply took. When a chat has finished its work, the host runs this just before the chat goes idle.
|
|
14
|
-
*
|
|
15
|
-
*
|
|
15
|
+
* What a reply took. When a chat has finished its work, the host runs this just before the chat goes idle. With `log`, it writes or grows the
|
|
16
|
+
* usage records of the chat's newest messages (src/usage-log.ts), for every chat. For each record of that chat
|
|
17
|
+
* that still waits, the reply is read from the chat's own messages and kept with the record, with the prices the model list gives for the
|
|
18
|
+
* model that answered, or else Artificial Analysis's from the copy kept in storage (`borrowedPrices`; never a request). No model is asked.
|
|
19
|
+
* It never throws, and it holds the chat for one second at most; one read of the chat serves both jobs.
|
|
16
20
|
*/
|
|
17
|
-
|
|
21
|
+
type ReplyDeps = Pick<RelayDeps, 'session' | 'store' | 'readMs' | 'chatModels'> & {
|
|
22
|
+
borrowedPrices?: () => Promise<AaModel[]>;
|
|
23
|
+
/** Plugin storage for the usage records; without it, only replies to placed messages are read. */
|
|
24
|
+
log?: LogStore;
|
|
25
|
+
/** The folder Relay was loaded for, kept with each usage record. */
|
|
26
|
+
project?: string;
|
|
27
|
+
};
|
|
28
|
+
export declare function relayReplyHook(deps: ReplyDeps): (event: {
|
|
29
|
+
readonly sessionID: string;
|
|
30
|
+
}) => Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Before the host summarizes a long chat (a compaction), the usage records of its newest messages are written or grown, so the part of a
|
|
33
|
+
* reply made before the cut is kept: afterwards the host lists the chat from the compaction on. It only reads the chat and writes Relay's
|
|
34
|
+
* storage, never touches the request, waits half a second at most, and never throws. Not yet seen on a real host.
|
|
35
|
+
*/
|
|
36
|
+
export declare function relayCompactionHook(deps: ReplyDeps): (event: {
|
|
18
37
|
readonly sessionID: string;
|
|
19
38
|
}) => Promise<void>;
|
|
20
39
|
export {};
|
package/dist/relay-auto.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { within } from './decider.js';
|
|
1
|
+
import { LATE, within } from './decider.js';
|
|
2
2
|
import { replyOf } from './chat-facts.js';
|
|
3
3
|
import { placeMessage, recordPlaced, timingOf, uploadsOf } from './relay-command.js';
|
|
4
|
-
import { chatSwitch, saveReplies, waitingReplies } from './relay-store.js';
|
|
4
|
+
import { chatSwitch, decisionsOf, saveReplies, waitingReplies } from './relay-store.js';
|
|
5
|
+
import { buildRecords, saveRecords } from './usage-log.js';
|
|
5
6
|
// The switch. In a chat where `/relay on` (or the pill) turned it on, every message the person sends is placed the way `/relay` places one,
|
|
6
7
|
// inside the host's `prompt` hook, before the message goes out (a switch made there serves that message: probe, 16 Nov). The host sends the
|
|
7
8
|
// message; this never does. It never throws, because a throw fails the person's message; what goes wrong becomes a note in the record.
|
|
@@ -30,25 +31,66 @@ export function relayAutoHook(deps) {
|
|
|
30
31
|
catch { /* never fail the person's message */ }
|
|
31
32
|
};
|
|
32
33
|
}
|
|
33
|
-
/**
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
/** Reading a chat for the two hooks below, within `limitMs`. */
|
|
35
|
+
function chatReader(deps, limitMs) {
|
|
36
|
+
/** A list that fails, or takes more than half the time, is no list; the reply is kept all the same. */
|
|
37
|
+
const spare = async (read) => {
|
|
38
|
+
if (!read)
|
|
39
|
+
return null;
|
|
40
|
+
const value = await within(read, limitMs / 2).catch(() => null);
|
|
41
|
+
return Array.isArray(value) ? value : null;
|
|
42
|
+
};
|
|
43
|
+
/** A helper's chat has a parent chat. One that cannot be read in half the time counts as a chat of its own. */
|
|
44
|
+
const isHelper = async (sessionID) => {
|
|
45
|
+
const chat = await within(() => deps.session.get({ sessionID: sessionID }), limitMs / 2).catch(() => null);
|
|
46
|
+
return !!chat && chat !== LATE && typeof chat.parentID === 'string' && chat.parentID !== '';
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
read: (sessionID) => Promise.all([deps.session.context({ sessionID: sessionID }), spare(deps.chatModels), spare(deps.borrowedPrices)]),
|
|
50
|
+
/** Writes or grows the usage records of the chat's newest messages (src/usage-log.ts). */
|
|
51
|
+
async keep(log, sessionID, messages, models, borrowed) {
|
|
52
|
+
const [helper, decisions] = await Promise.all([isHelper(sessionID), decisionsOf(deps.store, sessionID)]);
|
|
53
|
+
await saveRecords(log, buildRecords(messages, { sessionID, project: deps.project ?? '', helper }, { models, borrowed }, decisions));
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
38
57
|
export function relayReplyHook(deps) {
|
|
39
|
-
const limitMs = Math.min(timingOf(deps).readMs, 1000);
|
|
58
|
+
const limitMs = Math.min(timingOf(deps).readMs, 1000), chat = chatReader(deps, limitMs);
|
|
40
59
|
return async (event) => {
|
|
41
60
|
try {
|
|
42
61
|
await within(async () => {
|
|
43
62
|
const waiting = await waitingReplies(deps.store, event.sessionID);
|
|
44
|
-
|
|
63
|
+
// With usage records every chat is read when it goes idle, once for both jobs; without, only a chat with a waiting record.
|
|
64
|
+
if (!waiting.length && !deps.log)
|
|
45
65
|
return;
|
|
46
|
-
const messages = await
|
|
47
|
-
const replies = new Map(waiting.flatMap(messageID => { const reply = replyOf(messages, messageID); return reply ? [[messageID, reply]] : []; }));
|
|
66
|
+
const [messages, listed, borrowed] = await chat.read(event.sessionID);
|
|
67
|
+
const replies = new Map(waiting.flatMap(messageID => { const reply = replyOf(messages, messageID, listed, borrowed); return reply ? [[messageID, reply]] : []; }));
|
|
48
68
|
if (replies.size)
|
|
49
69
|
await saveReplies(deps.store, event.sessionID, replies);
|
|
70
|
+
if (deps.log)
|
|
71
|
+
await chat.keep(deps.log, event.sessionID, messages, listed, borrowed);
|
|
50
72
|
}, limitMs);
|
|
51
73
|
}
|
|
52
74
|
catch { /* the record is for the panel; the chat goes idle whatever happens here */ }
|
|
53
75
|
};
|
|
54
76
|
}
|
|
77
|
+
/**
|
|
78
|
+
* Before the host summarizes a long chat (a compaction), the usage records of its newest messages are written or grown, so the part of a
|
|
79
|
+
* reply made before the cut is kept: afterwards the host lists the chat from the compaction on. It only reads the chat and writes Relay's
|
|
80
|
+
* storage, never touches the request, waits half a second at most, and never throws. Not yet seen on a real host.
|
|
81
|
+
*/
|
|
82
|
+
export function relayCompactionHook(deps) {
|
|
83
|
+
const limitMs = Math.min(timingOf(deps).readMs, 500), chat = chatReader(deps, limitMs);
|
|
84
|
+
return async (event) => {
|
|
85
|
+
const log = deps.log;
|
|
86
|
+
if (!log)
|
|
87
|
+
return;
|
|
88
|
+
try {
|
|
89
|
+
await within(async () => {
|
|
90
|
+
const [messages, listed, borrowed] = await chat.read(event.sessionID);
|
|
91
|
+
await chat.keep(log, event.sessionID, messages, listed, borrowed);
|
|
92
|
+
}, limitMs);
|
|
93
|
+
}
|
|
94
|
+
catch { /* the summary goes ahead whatever happens here */ }
|
|
95
|
+
};
|
|
96
|
+
}
|
package/dist/relay-command.d.ts
CHANGED
|
@@ -29,11 +29,6 @@ type AttachedFile = {
|
|
|
29
29
|
readonly uri?: string;
|
|
30
30
|
readonly name?: string;
|
|
31
31
|
};
|
|
32
|
-
/**
|
|
33
|
-
* A variant as the host reports it, in a choice's terms. The host names "no variant requested" `default` (seen on 2.2.7, even for a model that has
|
|
34
|
-
* no variants), while a choice uses `null`; compared raw, a chat on its default variant would never match a choice.
|
|
35
|
-
*/
|
|
36
|
-
export declare const hostVariant: (variant: string | null | undefined) => string | null;
|
|
37
32
|
/** The host gives no type for an attached file, so a picture is told by its address or its name. */
|
|
38
33
|
export declare function isPicture(file: AttachedFile): boolean;
|
|
39
34
|
export type Upload = {
|
package/dist/relay-command.js
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
2
3
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
3
|
-
import { LATE, within } from './decider.js';
|
|
4
|
+
import { firstRequest, LATE, lastReply, within } from './decider.js';
|
|
4
5
|
import { chatFacts } from './chat-facts.js';
|
|
5
|
-
import { getRelaySettings, modelName, recentDecisions, recordDecision, setChatSwitch } from './relay-store.js';
|
|
6
|
-
import { brief, linesFor, REVIEW_RULES_KEY, reviewRules, route } from './router.js';
|
|
7
|
-
|
|
8
|
-
* A variant as the host reports it, in a choice's terms. The host names "no variant requested" `default` (seen on 2.2.7, even for a model that has
|
|
9
|
-
* no variants), while a choice uses `null`; compared raw, a chat on its default variant would never match a choice.
|
|
10
|
-
*/
|
|
11
|
-
// shortcut: a model with a real variant literally named `default` is treated as having none, because the host reports both the same way.
|
|
12
|
-
export const hostVariant = (variant) => (variant === undefined || variant === 'default' ? null : variant);
|
|
6
|
+
import { getRelaySettings, hostVariant, modelName, modes, recentDecisions, recordDecision, setChatSwitch } from './relay-store.js';
|
|
7
|
+
import { brief, linesFor, REVIEW_RULES_KEY, reviewRules, route, sizesFor } from './router.js';
|
|
8
|
+
import { readStored, standingsOf } from './standings.js';
|
|
13
9
|
const PICTURE = /\.(png|jpe?g|gif|webp|bmp)$/i;
|
|
14
10
|
const bare = (uri) => uri.replace(/[?#].*$/, '');
|
|
15
11
|
/** The host gives no type for an attached file, so a picture is told by its address or its name. */
|
|
@@ -100,13 +96,13 @@ export async function placeMessage(deps, timing, input) {
|
|
|
100
96
|
const place = async () => {
|
|
101
97
|
const read = await within(() => Promise.all([
|
|
102
98
|
reading('the settings', () => getRelaySettings(deps.store)), reading('the chat', () => deps.session.get({ sessionID })), reading('the model list', deps.chatModels),
|
|
103
|
-
spare(() => deps.session.context({ sessionID })), spare(() => recentDecisions(deps.store)),
|
|
99
|
+
spare(() => deps.session.context({ sessionID })), spare(() => recentDecisions(deps.store)), spare(() => readStored(deps.store)),
|
|
104
100
|
]), readMs);
|
|
105
101
|
if (read === LATE) {
|
|
106
102
|
notes.push(`Relay's settings, the chat or the model list did not answer within ${readMs / 1000} seconds`);
|
|
107
103
|
return;
|
|
108
104
|
}
|
|
109
|
-
const [settings, chat, models, messages, past] = read;
|
|
105
|
+
const [settings, chat, models, messages, past, stored] = read;
|
|
110
106
|
const files = prompt.files ?? [], uploads = input.uploads ?? [];
|
|
111
107
|
const pictures = files.filter(isPicture).length + uploads.filter(isImage).length;
|
|
112
108
|
const facts = await Promise.all([
|
|
@@ -116,8 +112,14 @@ export async function placeMessage(deps, timing, input) {
|
|
|
116
112
|
// shortcut: four bytes to a token. Dense text takes more, so a file close to a model's size can still be too big for it.
|
|
117
113
|
const attachment = { needsImage: pictures > 0, tokens: Math.ceil(facts.reduce((sum, file) => sum + (file.bytes ?? 0), 0) / 4), chat: messages === null ? null : chatFacts(messages, Date.now()), past: past ?? [] };
|
|
118
114
|
const current = chat.model ? { providerID: chat.model.providerID, id: chat.model.id, variant: hostVariant(chat.model.variant) } : null;
|
|
119
|
-
|
|
120
|
-
const
|
|
115
|
+
// The end of the last reply lets the decider place a short follow-up ("Implement it.") by the plan or review before it; the home folder is hidden.
|
|
116
|
+
const reply = messages === null ? null : lastReply(messages, homedir());
|
|
117
|
+
// The chat's first message tells the size question how hard the task is, when a short follow-up does not (25 Nov).
|
|
118
|
+
const task = messages === null ? null : firstRequest(messages, homedir(), prompt.text);
|
|
119
|
+
// Relay's own choice in a mode with no lines reads only stored copies; when they are late, the mode gets its first model and a note.
|
|
120
|
+
const standings = stored === null ? null : standingsOf(stored, models, [...modes.flatMap(mode => settings.modes[mode]), ...(current ? [current] : [])]);
|
|
121
|
+
const answer = await deps.decide(settings.decider, { kind: 'chat', text: prompt.text, agent: chat.agent ?? null, files: facts, images: pictures, lines: linesFor(settings, models, attachment, current), reply, task, sizes: sizesFor(settings, models, attachment, current, standings) });
|
|
122
|
+
const result = route(answer, settings, models, attachment, current, input.unsure, standings);
|
|
121
123
|
Object.assign(outcome, { mode: result.mode, ms: answer.ms }, answer.kind === 'answer' ? { confidence: answer.confidence, costUsd: answer.costUsd } : {});
|
|
122
124
|
if (result.note !== null)
|
|
123
125
|
notes.push(result.note);
|
package/dist/relay-store.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PriceStep } from './inventory.js';
|
|
1
2
|
import { type ModelChoice, type OfferedModel } from './settings.js';
|
|
2
3
|
export declare const modes: readonly ["plan", "execute", "review"];
|
|
3
4
|
export type Mode = typeof modes[number];
|
|
@@ -11,9 +12,22 @@ export type RelaySettings = {
|
|
|
11
12
|
modes: Record<Mode, ModeChoice[]>;
|
|
12
13
|
decider: ModelChoice | null;
|
|
13
14
|
};
|
|
15
|
+
/** USD for one million tokens, as the host lists them; null is unknown. */
|
|
16
|
+
export type Prices = Omit<PriceStep, 'above'>;
|
|
17
|
+
/** Every request of a reply added up, as the host counts tokens (`input` is read new and not written to a cache), and the host's own cost. */
|
|
18
|
+
export type Totals = {
|
|
19
|
+
input: number;
|
|
20
|
+
output: number;
|
|
21
|
+
reasoning: number;
|
|
22
|
+
cacheRead: number;
|
|
23
|
+
cacheWrite: number;
|
|
24
|
+
costUsd: string | null;
|
|
25
|
+
};
|
|
14
26
|
/**
|
|
15
27
|
* What the reply to a placed message took, read from the chat afterwards: the tokens its first request read new (not from a cache) and from
|
|
16
|
-
* a cache, that request's cost, the seconds until its first word, and how many requests the whole reply made
|
|
28
|
+
* a cache, that request's cost, the seconds until its first word, and how many requests the whole reply made; the model and effort that
|
|
29
|
+
* answered, the whole reply added up, and that model's listed prices for the size of the first request. A reply kept before 19 Nov 2026 has
|
|
30
|
+
* no model, totals or prices.
|
|
17
31
|
*/
|
|
18
32
|
export type Reply = {
|
|
19
33
|
requests: number;
|
|
@@ -21,6 +35,42 @@ export type Reply = {
|
|
|
21
35
|
cached: number;
|
|
22
36
|
costUsd: string | null;
|
|
23
37
|
seconds: number | null;
|
|
38
|
+
model: string | null;
|
|
39
|
+
total: Totals | null;
|
|
40
|
+
prices: Prices | null;
|
|
41
|
+
pricesFrom: PriceSource | null;
|
|
42
|
+
};
|
|
43
|
+
/** Where a reply's prices came from: OpenCode's own list (what is paid), or Artificial Analysis's when OpenCode lists none. */
|
|
44
|
+
export type PriceSource = 'opencode' | 'artificial-analysis';
|
|
45
|
+
type Kinds<T> = {
|
|
46
|
+
input: T;
|
|
47
|
+
output: T;
|
|
48
|
+
cacheRead: T;
|
|
49
|
+
cacheWrite: T;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* The totals of one model and effort over every reply Relay counted. `byPrice` is tokens times each reply's own price, by kind (output with
|
|
53
|
+
* its reasoning), and null for a kind no reply had a price for. `prices` are the last ones a reply had; `pricesFrom` is Artificial
|
|
54
|
+
* Analysis once any reply was priced by it.
|
|
55
|
+
*/
|
|
56
|
+
export type UsageRow = {
|
|
57
|
+
model: string;
|
|
58
|
+
messages: number;
|
|
59
|
+
requests: number;
|
|
60
|
+
input: number;
|
|
61
|
+
output: number;
|
|
62
|
+
reasoning: number;
|
|
63
|
+
cacheRead: number;
|
|
64
|
+
cacheWrite: number;
|
|
65
|
+
openCodeUsd: string | null;
|
|
66
|
+
byPrice: Kinds<string | null>;
|
|
67
|
+
prices: Prices | null;
|
|
68
|
+
pricesFrom: PriceSource | null;
|
|
69
|
+
};
|
|
70
|
+
/** `since` is when the first reply was counted. */
|
|
71
|
+
export type Usage = {
|
|
72
|
+
since: string | null;
|
|
73
|
+
rows: UsageRow[];
|
|
24
74
|
};
|
|
25
75
|
/**
|
|
26
76
|
* One routing decision. It never holds the message text or a file name. `fit` is how sure the decider was about the "use it for" line.
|
|
@@ -42,10 +92,15 @@ export type Decision = {
|
|
|
42
92
|
};
|
|
43
93
|
export type RelayStore = {
|
|
44
94
|
get(key: string): Promise<unknown>;
|
|
45
|
-
set(key: string, value: RelaySettings | Decision[] | boolean): Promise<void>;
|
|
95
|
+
set(key: string, value: RelaySettings | Decision[] | Usage | boolean): Promise<void>;
|
|
46
96
|
compareAndSet?(key: string, expected: unknown, value: RelaySettings | Decision[]): Promise<boolean>;
|
|
47
97
|
};
|
|
48
98
|
export declare const modelName: (choice: ModelChoice) => string;
|
|
99
|
+
/**
|
|
100
|
+
* A variant as the host reports it, in a choice's terms. The host names "no variant requested" `default` (seen on 2.2.7, even for a model that has
|
|
101
|
+
* no variants), while a choice uses `null`; compared raw, a chat on its default variant would never match a choice.
|
|
102
|
+
*/
|
|
103
|
+
export declare const hostVariant: (variant: string | null | undefined) => string | null;
|
|
49
104
|
export declare function getRelaySettings(store: Pick<RelayStore, 'get'>): Promise<RelaySettings>;
|
|
50
105
|
/** A choice that was already saved may stay when it is no longer offered; a new one must be offered now. Only a decision model can be the decider. */
|
|
51
106
|
export declare function saveRelaySettings(store: RelayStore, revision: number, input: unknown, chatModels: readonly OfferedModel[], decisionModels: readonly OfferedModel[]): Promise<RelaySettings>;
|
|
@@ -56,9 +111,14 @@ export declare function recordDecision(store: RelayStore, decision: Omit<Decisio
|
|
|
56
111
|
/** The messages of one chat whose records still wait for what the reply took. */
|
|
57
112
|
export declare function waitingReplies(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<string[]>;
|
|
58
113
|
/** Keeps what the replies took, by message, with the records of one chat that still wait for it. A reply that was kept once is not replaced. */
|
|
59
|
-
export declare function saveReplies(store: RelayStore, sessionID: string, replies: ReadonlyMap<string, Reply
|
|
60
|
-
/**
|
|
114
|
+
export declare function saveReplies(store: RelayStore, sessionID: string, replies: ReadonlyMap<string, Reply>, now?: number): Promise<void>;
|
|
115
|
+
/** The totals of every reply Relay counted, by model and effort, in the order of their names. */
|
|
116
|
+
export declare function getUsage(store: Pick<RelayStore, 'get'>): Promise<Usage>;
|
|
117
|
+
/** Newest first, at most 20. Older records that still wait for their reply are kept for the totals and not shown. */
|
|
61
118
|
export declare function recentDecisions(store: Pick<RelayStore, 'get'>): Promise<Decision[]>;
|
|
119
|
+
/** Every stored record of one chat, so its usage records can carry the Relay part of the messages Relay placed. */
|
|
120
|
+
export declare function decisionsOf(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<Decision[]>;
|
|
62
121
|
/** Only a stored `true` counts as on. */
|
|
63
122
|
export declare function chatSwitch(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<boolean>;
|
|
64
123
|
export declare function setChatSwitch(store: Pick<RelayStore, 'set'>, sessionID: string, on: boolean): Promise<void>;
|
|
124
|
+
export {};
|
package/dist/relay-store.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { costOf, formatUsd, parseUsd, storedUsd } from './costs.js';
|
|
1
2
|
import { offered, validateChoices } from './settings.js';
|
|
2
3
|
// What Relay keeps in plugin storage. The host shares plugin storage between projects, so there is one set of settings and one list of decisions.
|
|
3
4
|
// shortcut: one queue for this loaded module, so its own reads and writes never interleave. A second process writing the same keys is not
|
|
@@ -10,9 +11,16 @@ function serial(task) {
|
|
|
10
11
|
}
|
|
11
12
|
export const modes = ['plan', 'execute', 'review'];
|
|
12
13
|
export const USE_FOR_MAX = 200;
|
|
13
|
-
const
|
|
14
|
+
const sources = ['opencode', 'artificial-analysis'];
|
|
15
|
+
const SETTINGS = 'relay/settings', DECISIONS = 'relay/decisions', USAGE = 'relay/usage', KEEP = 20, WAITING_KEEP = 30;
|
|
14
16
|
const same = (a, b) => a.providerID === b.providerID && a.id === b.id && a.variant === b.variant;
|
|
15
17
|
export const modelName = (choice) => `${choice.providerID}/${choice.id}${choice.variant === null ? '' : `#${choice.variant}`}`;
|
|
18
|
+
/**
|
|
19
|
+
* A variant as the host reports it, in a choice's terms. The host names "no variant requested" `default` (seen on 2.2.7, even for a model that has
|
|
20
|
+
* no variants), while a choice uses `null`; compared raw, a chat on its default variant would never match a choice.
|
|
21
|
+
*/
|
|
22
|
+
// shortcut: a model with a real variant literally named `default` is treated as having none, because the host reports both the same way.
|
|
23
|
+
export const hostVariant = (variant) => (variant === undefined || variant === 'default' ? null : variant);
|
|
16
24
|
function entries(value) {
|
|
17
25
|
if (!Array.isArray(value))
|
|
18
26
|
throw new Error('Invalid mode choices');
|
|
@@ -72,14 +80,22 @@ export function saveRelaySettings(store, revision, input, chatModels, decisionMo
|
|
|
72
80
|
return structuredClone(saved);
|
|
73
81
|
});
|
|
74
82
|
}
|
|
83
|
+
const number = (field) => typeof field === 'number' && Number.isFinite(field) ? field : null, text = (field) => typeof field === 'string' ? field : null;
|
|
84
|
+
const sourceOf = (field) => sources.find(source => source === field) ?? null;
|
|
85
|
+
function pricesOf(field) {
|
|
86
|
+
const listed = field && typeof field === 'object' ? field : null;
|
|
87
|
+
return listed && { inputPerMillion: text(listed.inputPerMillion), outputPerMillion: text(listed.outputPerMillion), cacheReadPerMillion: text(listed.cacheReadPerMillion), cacheWritePerMillion: text(listed.cacheWritePerMillion) };
|
|
88
|
+
}
|
|
75
89
|
/** A stored record as the panel may show it, or null when it cannot be read. A field this version does not know is dropped, and a missing one reads as unknown. */
|
|
76
90
|
function readable(value) {
|
|
77
91
|
const item = value;
|
|
78
92
|
if (!item || typeof item !== 'object' || typeof item.at !== 'string' || typeof item.sessionID !== 'string' || (item.kind !== 'chat' && item.kind !== 'helper') || typeof item.ms !== 'number')
|
|
79
93
|
return null;
|
|
80
|
-
const number = (field) => typeof field === 'number' && Number.isFinite(field) ? field : null, text = (field) => typeof field === 'string' ? field : null;
|
|
81
94
|
const took = (item.reply && typeof item.reply === 'object' ? item.reply : {}), requests = number(took.requests), fresh = number(took.fresh), cached = number(took.cached);
|
|
82
|
-
const
|
|
95
|
+
const sum = (took.total && typeof took.total === 'object' ? took.total : {});
|
|
96
|
+
const [input, output, reasoning, cacheRead, cacheWrite] = [sum.input, sum.output, sum.reasoning, sum.cacheRead, sum.cacheWrite].map(number);
|
|
97
|
+
const total = input === null || output === null || reasoning === null || cacheRead === null || cacheWrite === null ? null : { input, output, reasoning, cacheRead, cacheWrite, costUsd: text(sum.costUsd) };
|
|
98
|
+
const reply = requests === null || fresh === null || cached === null ? null : { requests, fresh, cached, costUsd: text(took.costUsd), seconds: number(took.seconds), model: text(took.model), total, prices: pricesOf(took.prices), pricesFrom: sourceOf(took.pricesFrom) };
|
|
83
99
|
return { at: item.at, sessionID: item.sessionID, kind: item.kind, mode: modes.find(mode => mode === item.mode) ?? null, confidence: number(item.confidence), fit: number(item.fit), model: text(item.model), ms: item.ms, costUsd: text(item.costUsd), note: text(item.note), messageID: text(item.messageID), reply };
|
|
84
100
|
}
|
|
85
101
|
const stored = async (store) => {
|
|
@@ -89,7 +105,12 @@ const stored = async (store) => {
|
|
|
89
105
|
/** A new record has no reply yet; one made for a message of a chat names that message. */
|
|
90
106
|
export function recordDecision(store, decision) {
|
|
91
107
|
// shortcut: one stored list. Two project folders deciding in the same instant can lose one record; give each record its own key if that ever matters.
|
|
92
|
-
return serial(async () =>
|
|
108
|
+
return serial(async () => {
|
|
109
|
+
const all = [...await stored(store), { messageID: null, ...decision, reply: null }];
|
|
110
|
+
// A record still waiting for its reply stays behind the newest twenty (thirty such at most), so a long reply is still counted.
|
|
111
|
+
const waiting = all.slice(0, -KEEP).filter(item => item.messageID !== null && item.reply === null).slice(-WAITING_KEEP);
|
|
112
|
+
await store.set(DECISIONS, [...waiting, ...all.slice(-KEEP)]);
|
|
113
|
+
});
|
|
93
114
|
}
|
|
94
115
|
const waits = (item, sessionID) => item.sessionID === sessionID && item.messageID !== null && item.reply === null;
|
|
95
116
|
/** The messages of one chat whose records still wait for what the reply took. */
|
|
@@ -98,12 +119,76 @@ export function waitingReplies(store, sessionID) {
|
|
|
98
119
|
}
|
|
99
120
|
/** Keeps what the replies took, by message, with the records of one chat that still wait for it. A reply that was kept once is not replaced. */
|
|
100
121
|
// shortcut: a record whose reply can never be read (an answer that was stopped, a message that was taken back or compacted away before
|
|
101
|
-
// its reply was read) waits until
|
|
102
|
-
|
|
103
|
-
|
|
122
|
+
// its reply was read) waits until thirty newer waiting records push it out, so its chat is read once more each time it goes idle.
|
|
123
|
+
// Each reply kept here is also added to the totals of its model and effort. The record is written first, so a reply is counted at most once.
|
|
124
|
+
// shortcut: two OpenCode processes that keep the same reply in the same instant can each count it; give each count a key of its own if that ever matters.
|
|
125
|
+
export function saveReplies(store, sessionID, replies, now = Date.now()) {
|
|
126
|
+
return serial(async () => {
|
|
127
|
+
const kept = [];
|
|
128
|
+
await store.set(DECISIONS, (await stored(store)).map(item => {
|
|
129
|
+
if (!waits(item, sessionID))
|
|
130
|
+
return item;
|
|
131
|
+
const reply = replies.get(item.messageID) ?? null;
|
|
132
|
+
if (reply)
|
|
133
|
+
kept.push(reply);
|
|
134
|
+
return { ...item, reply };
|
|
135
|
+
}));
|
|
136
|
+
if (kept.length)
|
|
137
|
+
await store.set(USAGE, counted(await storedUsage(store), kept, now));
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
const kinds = [['input', 'inputPerMillion'], ['output', 'outputPerMillion'], ['cacheRead', 'cacheReadPerMillion'], ['cacheWrite', 'cacheWritePerMillion']];
|
|
141
|
+
const plus = (sum, more) => more === null ? sum : formatUsd((sum === null ? 0n : parseUsd(sum)) + more);
|
|
142
|
+
/** The totals with these replies added; a reply with no totals (kept before 19 Nov 2026) adds nothing. */
|
|
143
|
+
function counted(usage, replies, now) {
|
|
144
|
+
const rows = new Map(usage.rows.map(row => [row.model, row]));
|
|
145
|
+
for (const reply of replies) {
|
|
146
|
+
const { total } = reply;
|
|
147
|
+
if (!total)
|
|
148
|
+
continue;
|
|
149
|
+
const model = reply.model ?? 'unknown model', none = { input: null, output: null, cacheRead: null, cacheWrite: null };
|
|
150
|
+
const row = rows.get(model) ?? { model, messages: 0, requests: 0, input: 0, output: 0, reasoning: 0, cacheRead: 0, cacheWrite: 0, openCodeUsd: '0', byPrice: none, prices: null, pricesFrom: null };
|
|
151
|
+
// Reasoning is billed at the output price, as in scripts/bench/lib.ts.
|
|
152
|
+
const tokens = { input: total.input, output: total.output + total.reasoning, cacheRead: total.cacheRead, cacheWrite: total.cacheWrite };
|
|
153
|
+
const byPrice = Object.fromEntries(kinds.map(([kind, price]) => [kind, plus(row.byPrice[kind], costOf(tokens[kind], reply.prices?.[price] ?? null))]));
|
|
154
|
+
const cost = storedUsd(total.costUsd);
|
|
155
|
+
rows.set(model, {
|
|
156
|
+
model, messages: row.messages + 1, requests: row.requests + reply.requests, input: row.input + total.input, output: row.output + total.output, reasoning: row.reasoning + total.reasoning,
|
|
157
|
+
cacheRead: row.cacheRead + total.cacheRead, cacheWrite: row.cacheWrite + total.cacheWrite, openCodeUsd: cost === null ? row.openCodeUsd : plus(row.openCodeUsd, parseUsd(cost)),
|
|
158
|
+
byPrice, prices: reply.prices && Object.values(reply.prices).some(price => price !== null) ? reply.prices : row.prices,
|
|
159
|
+
pricesFrom: row.pricesFrom === 'artificial-analysis' ? row.pricesFrom : reply.pricesFrom ?? row.pricesFrom,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return { since: usage.since ?? new Date(now).toISOString(), rows: [...rows.values()] };
|
|
163
|
+
}
|
|
164
|
+
function usageRow(value) {
|
|
165
|
+
const row = value;
|
|
166
|
+
if (!row || typeof row !== 'object' || typeof row.model !== 'string')
|
|
167
|
+
return null;
|
|
168
|
+
const [messages, requests, input, output, reasoning, cacheRead, cacheWrite] = [row.messages, row.requests, row.input, row.output, row.reasoning, row.cacheRead, row.cacheWrite].map(number);
|
|
169
|
+
if (messages === null || requests === null || input === null || output === null || reasoning === null || cacheRead === null || cacheWrite === null)
|
|
170
|
+
return null;
|
|
171
|
+
const byPrice = (row.byPrice && typeof row.byPrice === 'object' ? row.byPrice : {});
|
|
172
|
+
return {
|
|
173
|
+
model: row.model, messages, requests, input, output, reasoning, cacheRead, cacheWrite, openCodeUsd: storedUsd(row.openCodeUsd),
|
|
174
|
+
byPrice: { input: storedUsd(byPrice.input), output: storedUsd(byPrice.output), cacheRead: storedUsd(byPrice.cacheRead), cacheWrite: storedUsd(byPrice.cacheWrite) },
|
|
175
|
+
prices: pricesOf(row.prices), pricesFrom: sourceOf(row.pricesFrom),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
async function storedUsage(store) {
|
|
179
|
+
const value = await store.get(USAGE);
|
|
180
|
+
if (!value || typeof value !== 'object' || !Array.isArray(value.rows))
|
|
181
|
+
return { since: null, rows: [] };
|
|
182
|
+
return { since: text(value.since), rows: value.rows.map(usageRow).filter(row => row !== null) };
|
|
183
|
+
}
|
|
184
|
+
/** The totals of every reply Relay counted, by model and effort, in the order of their names. */
|
|
185
|
+
export function getUsage(store) {
|
|
186
|
+
return serial(async () => { const usage = await storedUsage(store); return { ...usage, rows: usage.rows.sort((a, b) => a.model < b.model ? -1 : a.model > b.model ? 1 : 0) }; });
|
|
104
187
|
}
|
|
105
|
-
/** Newest first, at most 20. */
|
|
106
|
-
export function recentDecisions(store) { return serial(async () => (await stored(store)).reverse()); }
|
|
188
|
+
/** Newest first, at most 20. Older records that still wait for their reply are kept for the totals and not shown. */
|
|
189
|
+
export function recentDecisions(store) { return serial(async () => (await stored(store)).slice(-KEEP).reverse()); }
|
|
190
|
+
/** Every stored record of one chat, so its usage records can carry the Relay part of the messages Relay placed. */
|
|
191
|
+
export function decisionsOf(store, sessionID) { return serial(async () => (await stored(store)).filter(item => item.sessionID === sessionID)); }
|
|
107
192
|
// The switch: whether every message in one chat goes through Relay. One key per chat, so turning it on or off is one write and needs no queue.
|
|
108
193
|
const switchKey = (sessionID) => `relay/on/${encodeURIComponent(sessionID)}`;
|
|
109
194
|
/** Only a stored `true` counts as on. */
|
package/dist/relay-view.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ModelCostView } from './inventory.js';
|
|
2
|
-
import type
|
|
2
|
+
import { type Decision, type Reply, type UsageRow } from './relay-store.js';
|
|
3
3
|
import type { ModelChoice } from './settings.js';
|
|
4
4
|
/** A listed price of 0 can mean free or not known, so it is never called free. */
|
|
5
5
|
export declare function priceLabel(cost: Pick<ModelCostView, 'inputPerMillion' | 'outputPerMillion' | 'tiered'>): string;
|
|
@@ -47,8 +47,44 @@ export declare function decisionLine(decision: (Shown & Pick<Decision, 'kind'>)
|
|
|
47
47
|
export declare const recentLine: (decision: Shown & Pick<Decision, "kind"> & {
|
|
48
48
|
reply?: Reply | null;
|
|
49
49
|
}) => string;
|
|
50
|
+
/**
|
|
51
|
+
* One row of Usage by model: the model and its effort, the counts, the cost by price (marked * when Artificial Analysis gave the prices), and
|
|
52
|
+
* how each kind of token was priced. Output is priced with its reasoning. OpenCode's own cost is added when it is more than $0.
|
|
53
|
+
*/
|
|
54
|
+
export declare function usageCells(row: UsageRow): {
|
|
55
|
+
model: string;
|
|
56
|
+
effort: string;
|
|
57
|
+
requests: string;
|
|
58
|
+
input: string;
|
|
59
|
+
output: string;
|
|
60
|
+
cacheRead: string;
|
|
61
|
+
cacheWrite: string;
|
|
62
|
+
cost: string;
|
|
63
|
+
byPrice: string[];
|
|
64
|
+
};
|
|
65
|
+
/** What `/relay-stats` shows: a table of every model and effort, how each one's cost was worked out, and the credit Artificial Analysis asks for. */
|
|
66
|
+
export declare function usageText(view: {
|
|
67
|
+
since: string | null;
|
|
68
|
+
rows: readonly UsageRow[];
|
|
69
|
+
credit: string | null;
|
|
70
|
+
}): string;
|
|
50
71
|
/** What the test box shows for one try: what Relay would do with the sample message. */
|
|
51
72
|
export declare function tryLine(result: Shown & Pick<Decision, 'costUsd'>): string;
|
|
73
|
+
/** Under a list of several models. Lines win; with none, Relay chooses by itself (src/ranking.ts): an unsure size takes the highest index (25 Nov), no size the first model. */
|
|
74
|
+
export declare const severalModelsHint = "Several models: write a line for each and the decider follows your lines. Write none and Relay chooses by itself: the highest index for big, unclear or risky work, the cheapest for small, clear work. When it is not sure how big the work is, the highest index is used; when the decider gives no size, the first model in this list.";
|
|
75
|
+
/** Relay's own choice for one mode, as `getOwnChoice` gives it: null when the mode is not Relay's to choose (it has lines, or one usable model). */
|
|
76
|
+
export type OwnChoicePart = null | {
|
|
77
|
+
kind: 'unranked';
|
|
78
|
+
reason: string;
|
|
79
|
+
} | {
|
|
80
|
+
kind: 'ranked';
|
|
81
|
+
strongest: string;
|
|
82
|
+
cheapest: string;
|
|
83
|
+
};
|
|
84
|
+
/** The line under one chosen model: which work Relay gives it by itself, or null when it gets none. */
|
|
85
|
+
export declare function ownChoicePart(part: OwnChoicePart, choice: ModelChoice): string | null;
|
|
86
|
+
/** The line under a list Relay would choose for by itself but cannot rank, saying what is missing. */
|
|
87
|
+
export declare const ownChoiceNote: (part: OwnChoicePart) => string | null;
|
|
52
88
|
/** What leaves the machine to make a choice, and to whom. It names everything `describe` in `decider.ts` puts in a request, with that file's own limits. */
|
|
53
89
|
export declare const privacyNote: (providerID: string | null) => string;
|
|
54
90
|
/**
|
package/dist/relay-view.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { modelName } from './relay-store.js';
|
|
1
2
|
import { modeLabel } from './router.js';
|
|
2
|
-
import { MAX_CHARS, MAX_FILE_NAMES } from './decider.js';
|
|
3
|
-
import { parseUsd } from './costs.js';
|
|
3
|
+
import { MAX_CHARS, MAX_FILE_NAMES, MAX_REPLY_CHARS, MAX_TASK_CHARS } from './decider.js';
|
|
4
|
+
import { costOf, formatUsd, parseUsd } from './costs.js';
|
|
4
5
|
// What the Modes tab says in words. Pure, so it runs under node:test; the panel bundles it, so nothing here may import from `node:`.
|
|
5
6
|
const usd = (value) => value === null ? 'not listed' : `$${value}`;
|
|
6
7
|
/** A listed price of 0 can mean free or not known, so it is never called free. */
|
|
@@ -74,13 +75,61 @@ export function decisionLine(decision) {
|
|
|
74
75
|
return noted(`Last choice${decision.kind === 'helper' ? ' (a helper)' : ''}: ${outcome(decision)}`, decision.note);
|
|
75
76
|
}
|
|
76
77
|
const amount = (tokens) => Math.round(tokens).toLocaleString('en-US');
|
|
77
|
-
/**
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
].
|
|
78
|
+
/** A cost of 0 can mean "not listed", so it is left out, like a cost that was not reported. */
|
|
79
|
+
const cost = (usd) => usd === null || usd === '0' ? [] : [`$${usd}`];
|
|
80
|
+
/** $0 for both input and output can mean "not listed", as with no price at all. A price that is not listed is left out. */
|
|
81
|
+
const priced = (prices) => (prices.inputPerMillion ?? '0') === '0' && (prices.outputPerMillion ?? '0') === '0' ? ' Price: $0 or not listed.'
|
|
82
|
+
: ` Prices for a million tokens: ${[[prices.inputPerMillion, 'in'], [prices.outputPerMillion, 'out'], [prices.cacheReadPerMillion, 'cache read'], [prices.cacheWritePerMillion, 'cache write']].flatMap(([usd, what]) => usd === null ? [] : [`$${usd} ${what}`]).join(', ')}.`;
|
|
83
|
+
/** What the reply took, once it is known: the whole reply and the model that gave it, that model's prices, then the reply's first request. */
|
|
84
|
+
const took = (reply) => {
|
|
85
|
+
if (!reply)
|
|
86
|
+
return '';
|
|
87
|
+
const { total, requests } = reply;
|
|
88
|
+
const whole = total === null ? ` Requests in the reply: ${requests}.` : ` Reply${reply.model === null ? '' : ` from ${reply.model}`}: ${[
|
|
89
|
+
`${requests} request${requests === 1 ? '' : 's'}`, `${amount(total.input)} tokens in`, `${amount(total.output)} out`, ...(total.reasoning > 0 ? [`${amount(total.reasoning)} reasoning`] : []),
|
|
90
|
+
`${amount(total.cacheRead)} read from cache`, `${amount(total.cacheWrite)} written to cache`, ...cost(total.costUsd),
|
|
91
|
+
].join(', ')}.`;
|
|
92
|
+
return `${whole}${reply.prices === null ? '' : priced(reply.prices)} First request: ${[
|
|
93
|
+
`${amount(reply.fresh)} tokens read new`, `${amount(reply.cached)} from cache`, ...cost(reply.costUsd), ...(reply.seconds === null ? [] : [`first word after ${reply.seconds} s`]),
|
|
94
|
+
].join(', ')}.`;
|
|
95
|
+
};
|
|
82
96
|
/** One row of Recent choices. The time is left out: the panel shows it in the viewer's own clock. */
|
|
83
97
|
export const recentLine = (decision) => `${noted(`${decision.kind === 'helper' ? 'Helper' : 'Chat'}: ${outcome(decision)}`, decision.note)}${took(decision.reply)}`;
|
|
98
|
+
const kinds = [['input', 'in', 'inputPerMillion'], ['output', 'out', 'outputPerMillion'], ['cacheRead', 'cache read', 'cacheReadPerMillion'], ['cacheWrite', 'cache write', 'cacheWritePerMillion']];
|
|
99
|
+
/**
|
|
100
|
+
* One row of Usage by model: the model and its effort, the counts, the cost by price (marked * when Artificial Analysis gave the prices), and
|
|
101
|
+
* how each kind of token was priced. Output is priced with its reasoning. OpenCode's own cost is added when it is more than $0.
|
|
102
|
+
*/
|
|
103
|
+
export function usageCells(row) {
|
|
104
|
+
const hash = row.model.lastIndexOf('#'), costs = kinds.flatMap(([kind]) => { const usd = row.byPrice[kind]; return usd === null ? [] : [parseUsd(usd)]; });
|
|
105
|
+
const byPrice = !costs.length ? [] : kinds.flatMap(([kind, label, price]) => {
|
|
106
|
+
const tokens = kind === 'output' ? `${amount(row.output)}${row.reasoning > 0 ? ` + ${amount(row.reasoning)} reasoning` : ''}` : amount(row[kind]);
|
|
107
|
+
const usd = row.byPrice[kind], per = row.prices?.[price] ?? null, count = kind === 'output' ? row.output + row.reasoning : row[kind];
|
|
108
|
+
if (usd !== null && per !== null && costOf(count, per) === parseUsd(usd))
|
|
109
|
+
return [`${label} ${tokens} x $${per} a million = $${usd}`];
|
|
110
|
+
if (usd !== null)
|
|
111
|
+
return [`${label} ${tokens}: $${usd} by each reply's own price${per === null ? '' : ` (the last was $${per} a million)`}`];
|
|
112
|
+
return count > 0 ? [`${label} ${tokens}: no price listed`] : [];
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
model: hash < 0 ? row.model : row.model.slice(0, hash), effort: hash < 0 ? '-' : row.model.slice(hash + 1), requests: amount(row.requests), input: amount(row.input), output: amount(row.output),
|
|
116
|
+
cacheRead: amount(row.cacheRead), cacheWrite: amount(row.cacheWrite), cost: costs.length ? `$${formatUsd(costs.reduce((sum, usd) => sum + usd, 0n))}${row.pricesFrom === 'artificial-analysis' ? '*' : ''}` : 'not listed',
|
|
117
|
+
byPrice: [...byPrice, ...(row.openCodeUsd !== null && row.openCodeUsd !== '0' ? [`OpenCode's own cost: $${row.openCodeUsd}`] : [])],
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** What `/relay-stats` shows: a table of every model and effort, how each one's cost was worked out, and the credit Artificial Analysis asks for. */
|
|
121
|
+
export function usageText(view) {
|
|
122
|
+
if (!view.rows.length)
|
|
123
|
+
return 'No reply counted yet. Relay counts every message it places: /relay, or any message in a chat with Relay on.';
|
|
124
|
+
const cells = view.rows.map(usageCells);
|
|
125
|
+
const table = [['model', 'effort', 'requests', 'in', 'out', 'cache read', 'cache write', 'cost'], ...cells.map(cell => [cell.model, cell.effort, cell.requests, cell.input, cell.output, cell.cacheRead, cell.cacheWrite, cell.cost])];
|
|
126
|
+
const widths = table[0].map((_, column) => Math.max(...table.map(line => line[column].length)));
|
|
127
|
+
const lines = table.map(line => line.map((cell, column) => column < 2 ? cell.padEnd(widths[column]) : cell.padStart(widths[column])).join(' ').trimEnd());
|
|
128
|
+
const blocks = view.rows.flatMap((row, at) => cells[at].byPrice.length ? [`${row.model}, cost by price:`, ...cells[at].byPrice.map(line => ` ${line}`)] : []);
|
|
129
|
+
const footer = [...(view.rows.some(row => row.pricesFrom === 'artificial-analysis') ? ['* at Artificial Analysis prices, all or in part'] : []), ...(view.credit ? [view.credit] : [])];
|
|
130
|
+
const since = view.since ? `, since ${view.since.slice(0, 10)} ${view.since.slice(11, 16)} UTC` : '';
|
|
131
|
+
return [`Relay: usage by model${since}`, '', ...lines, ...(blocks.length ? ['', ...blocks] : []), ...(footer.length ? ['', ...footer] : [])].join('\n');
|
|
132
|
+
}
|
|
84
133
|
/** What the test box shows for one try: what Relay would do with the sample message. */
|
|
85
134
|
export function tryLine(result) {
|
|
86
135
|
const { mode } = result;
|
|
@@ -88,8 +137,19 @@ export function tryLine(result) {
|
|
|
88
137
|
return noted('No answer', result.note);
|
|
89
138
|
return noted(`${facts({ ...result, mode }, result.model ?? 'no model')}, cost ${result.costUsd === null ? 'not reported' : `$${result.costUsd}`}`, result.note);
|
|
90
139
|
}
|
|
140
|
+
/** Under a list of several models. Lines win; with none, Relay chooses by itself (src/ranking.ts): an unsure size takes the highest index (25 Nov), no size the first model. */
|
|
141
|
+
export const severalModelsHint = 'Several models: write a line for each and the decider follows your lines. Write none and Relay chooses by itself: the highest index for big, unclear or risky work, the cheapest for small, clear work. When it is not sure how big the work is, the highest index is used; when the decider gives no size, the first model in this list.';
|
|
142
|
+
/** The line under one chosen model: which work Relay gives it by itself, or null when it gets none. */
|
|
143
|
+
export function ownChoicePart(part, choice) {
|
|
144
|
+
if (part?.kind !== 'ranked')
|
|
145
|
+
return null;
|
|
146
|
+
const name = modelName(choice), big = part.strongest === name, small = part.cheapest === name;
|
|
147
|
+
return big && small ? 'Relay: all work (highest index and cheapest)' : big ? 'Relay: big work (highest index)' : small ? 'Relay: small work (cheapest)' : null;
|
|
148
|
+
}
|
|
149
|
+
/** The line under a list Relay would choose for by itself but cannot rank, saying what is missing. */
|
|
150
|
+
export const ownChoiceNote = (part) => part?.kind === 'unranked' ? `Relay can't rank this list: ${part.reason}. The first model is used.` : null;
|
|
91
151
|
/** What leaves the machine to make a choice, and to whom. It names everything `describe` in `decider.ts` puts in a request, with that file's own limits. */
|
|
92
|
-
export const privacyNote = (providerID) => `To choose, Relay sends to ${providerID ?? "the decider's provider"}: your message text (at most ${MAX_CHARS.toLocaleString('en-US')} characters), the names and sizes of attached files (the first ${MAX_FILE_NAMES}), how many pictures are attached, whether the chat's agent can change files, and the lines you wrote above. Never the contents of files, pictures or earlier messages. While a decider and a Review model are chosen, the task text of each helper that a model starts is sent the same way — written by the calling model, so it may itself quote code, files or earlier chat, and the person does not see it before it goes out.`;
|
|
152
|
+
export const privacyNote = (providerID) => `To choose, Relay sends to ${providerID ?? "the decider's provider"}: your message text (at most ${MAX_CHARS.toLocaleString('en-US')} characters), the end of the chat's last reply when it must choose between your models (at most ${MAX_REPLY_CHARS.toLocaleString('en-US')} characters of its text, with your home folder as ~), the start of the chat's first message when Relay asks how big the work is (at most ${MAX_TASK_CHARS.toLocaleString('en-US')} characters, with your home folder as ~), the names and sizes of attached files (the first ${MAX_FILE_NAMES}), how many pictures are attached, whether the chat's agent can change files, and the lines you wrote above. Never the contents of files, pictures, the model's reasoning or tool output, other earlier messages, or model names, prices or scores. While a decider and a Review model are chosen, the task text of each helper that a model starts is sent the same way — written by the calling model, so it may itself quote code, files or earlier chat, and the person does not see it before it goes out.`;
|
|
93
153
|
/**
|
|
94
154
|
* The model to put in Desktop's model picker after Relay switched a chat. Desktop sends the picker's model with every message (seen on
|
|
95
155
|
* 2.3.0, 17 Nov), so a picker left on the old model would undo the switch on the next one. Null for a helper's record and when nothing was switched.
|
package/dist/review-helper.d.ts
CHANGED
|
@@ -4,5 +4,5 @@ type ToolCall = {
|
|
|
4
4
|
sessionID: string;
|
|
5
5
|
input: unknown;
|
|
6
6
|
};
|
|
7
|
-
export declare function reviewHelperHook(deps: Pick<RelayDeps, 'store' | 'chatModels' | 'decide' | 'readMs'>): (event: ToolCall) => Promise<void>;
|
|
7
|
+
export declare function reviewHelperHook(deps: Pick<RelayDeps, 'store' | 'chatModels' | 'decide' | 'readMs' | 'session'>): (event: ToolCall) => Promise<void>;
|
|
8
8
|
export {};
|