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.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/dist/artificial-analysis.d.ts +50 -0
- package/dist/artificial-analysis.js +153 -0
- package/dist/chat-facts.d.ts +26 -0
- package/dist/chat-facts.js +96 -0
- package/dist/contract.d.ts +2727 -0
- package/dist/contract.js +111 -0
- package/dist/costs.d.ts +14 -0
- package/dist/costs.js +47 -0
- package/dist/decider.d.ts +73 -0
- package/dist/decider.js +199 -0
- package/dist/gui-experimental.cjs +92 -0
- package/dist/gui-styles.d.ts +5 -0
- package/dist/gui-styles.js +95 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +62 -0
- package/dist/intelligence.d.ts +38 -0
- package/dist/intelligence.js +123 -0
- package/dist/inventory.d.ts +34 -0
- package/dist/inventory.js +28 -0
- package/dist/ranking.d.ts +31 -0
- package/dist/ranking.js +78 -0
- package/dist/relay-auto.d.ts +39 -0
- package/dist/relay-auto.js +96 -0
- package/dist/relay-command.d.ts +74 -0
- package/dist/relay-command.js +211 -0
- package/dist/relay-store.d.ts +124 -0
- package/dist/relay-store.js +196 -0
- package/dist/relay-view.d.ts +124 -0
- package/dist/relay-view.js +189 -0
- package/dist/review-helper.d.ts +8 -0
- package/dist/review-helper.js +68 -0
- package/dist/router.d.ts +122 -0
- package/dist/router.js +209 -0
- package/dist/rpc.d.ts +2725 -0
- package/dist/rpc.js +116 -0
- package/dist/settings.d.ts +16 -0
- package/dist/settings.js +22 -0
- 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 +46 -4
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
|
+
import { firstRequest, LATE, lastReply, within } from './decider.js';
|
|
5
|
+
import { chatFacts } from './chat-facts.js';
|
|
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';
|
|
9
|
+
const PICTURE = /\.(png|jpe?g|gif|webp|bmp)$/i;
|
|
10
|
+
const bare = (uri) => uri.replace(/[?#].*$/, '');
|
|
11
|
+
/** The host gives no type for an attached file, so a picture is told by its address or its name. */
|
|
12
|
+
export function isPicture(file) {
|
|
13
|
+
const uri = file.uri ?? '';
|
|
14
|
+
return uri.startsWith('data:image/') || PICTURE.test(file.name ?? '') || (!uri.startsWith('data:') && PICTURE.test(bare(uri)));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Desktop 2.3.0 sends a pasted picture or file as an upload: a line with its path in the text, an entry in the message's metadata, and no
|
|
18
|
+
* file part (seen on 17 Nov). Only well-formed entries count; the metadata comes from the client.
|
|
19
|
+
*/
|
|
20
|
+
export function uploadsOf(metadata) {
|
|
21
|
+
const list = metadata?.attachments;
|
|
22
|
+
return Array.isArray(list) ? list.filter((item) => !!item && typeof item === 'object' && typeof item.name === 'string' && typeof item.mime === 'string' && typeof item.path === 'string') : [];
|
|
23
|
+
}
|
|
24
|
+
const isImage = (upload) => upload.mime.startsWith('image/');
|
|
25
|
+
/** What the decider may be told of a file: its name, else its address without what follows a ? or #. Never the content that a `data:` address holds. */
|
|
26
|
+
const nameOf = (file) => file.name ?? (file.uri && !file.uri.startsWith('data:') ? bare(file.uri) : '');
|
|
27
|
+
/** The path of a file on this machine, or null. A `file:` address that names another machine is never opened: on Windows that would be a network call. */
|
|
28
|
+
export function localPath(uri) {
|
|
29
|
+
try {
|
|
30
|
+
const url = new URL(uri);
|
|
31
|
+
return url.protocol === 'file:' && !url.host ? fileURLToPath(url) : null;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export async function fileSize(uri) {
|
|
38
|
+
const path = localPath(uri);
|
|
39
|
+
return path === null ? null : (await stat(path)).size;
|
|
40
|
+
}
|
|
41
|
+
export const timingOf = (deps) => ({ waitMs: deps.waitMs ?? 120_000, sizeMs: deps.sizeMs ?? 1000, readMs: deps.readMs ?? 5000 });
|
|
42
|
+
/**
|
|
43
|
+
* Decides which mode and model fit one message and puts the chat on them. It never throws: what goes wrong becomes a note, and the chat
|
|
44
|
+
* stays as it is from there on. `unsure` is what an answer under 0.6 means; `timing.waitMs` is how long a busy chat is waited for.
|
|
45
|
+
*/
|
|
46
|
+
export async function placeMessage(deps, timing, input) {
|
|
47
|
+
const { sessionID, prompt } = input, { waitMs, sizeMs, readMs } = timing;
|
|
48
|
+
const outcome = { mode: null, confidence: null, fit: null, model: null, ms: 0, costUsd: null };
|
|
49
|
+
const notes = [];
|
|
50
|
+
const attempt = async (what, work) => {
|
|
51
|
+
try {
|
|
52
|
+
await work();
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
notes.push(`${what}: ${brief(error)}`);
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const sized = async (uri) => {
|
|
61
|
+
try {
|
|
62
|
+
const bytes = await within(() => deps.fileSize(uri), sizeMs);
|
|
63
|
+
return typeof bytes === 'number' && Number.isFinite(bytes) && bytes >= 0 ? bytes : null;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
/** Null when the chat is idle, else why it cannot be switched now. */
|
|
70
|
+
const idle = async () => {
|
|
71
|
+
try {
|
|
72
|
+
return await within(() => deps.session.wait({ sessionID }), waitMs) === LATE ? `the chat was still busy after ${waitMs / 1000} seconds` : null;
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
return `could not wait for the chat: ${brief(error)}`;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const reading = async (what, work) => {
|
|
79
|
+
try {
|
|
80
|
+
return await work();
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
throw new Error(`${what} could not be read: ${brief(error)}`);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/** For the cost check only: the chat's messages and Relay's earlier records. Null when they fail or take longer than the other reads may, and then the line is simply followed. */
|
|
87
|
+
const spare = async (work) => {
|
|
88
|
+
try {
|
|
89
|
+
const value = await within(work, Math.min(readMs / 2, 1000));
|
|
90
|
+
return value === LATE ? null : value;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
const place = async () => {
|
|
97
|
+
const read = await within(() => Promise.all([
|
|
98
|
+
reading('the settings', () => getRelaySettings(deps.store)), reading('the chat', () => deps.session.get({ sessionID })), reading('the model list', deps.chatModels),
|
|
99
|
+
spare(() => deps.session.context({ sessionID })), spare(() => recentDecisions(deps.store)), spare(() => readStored(deps.store)),
|
|
100
|
+
]), readMs);
|
|
101
|
+
if (read === LATE) {
|
|
102
|
+
notes.push(`Relay's settings, the chat or the model list did not answer within ${readMs / 1000} seconds`);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const [settings, chat, models, messages, past, stored] = read;
|
|
106
|
+
const files = prompt.files ?? [], uploads = input.uploads ?? [];
|
|
107
|
+
const pictures = files.filter(isPicture).length + uploads.filter(isImage).length;
|
|
108
|
+
const facts = await Promise.all([
|
|
109
|
+
...files.filter(file => !isPicture(file)).map(async (file) => ({ name: nameOf(file), bytes: file.uri ? await sized(file.uri) : null })),
|
|
110
|
+
...uploads.filter(upload => !isImage(upload)).map(async (upload) => ({ name: upload.name, bytes: await sized(pathToFileURL(upload.path).href) })),
|
|
111
|
+
]);
|
|
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.
|
|
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 ?? [] };
|
|
114
|
+
const current = chat.model ? { providerID: chat.model.providerID, id: chat.model.id, variant: hostVariant(chat.model.variant) } : null;
|
|
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);
|
|
123
|
+
Object.assign(outcome, { mode: result.mode, ms: answer.ms }, answer.kind === 'answer' ? { confidence: answer.confidence, costUsd: answer.costUsd } : {});
|
|
124
|
+
if (result.note !== null)
|
|
125
|
+
notes.push(result.note);
|
|
126
|
+
if (!result.switch)
|
|
127
|
+
return;
|
|
128
|
+
const { providerID, id, variant } = result.model;
|
|
129
|
+
const agentChanges = chat.agent !== result.agent;
|
|
130
|
+
const modelChanges = !(current !== null && current.providerID === providerID && current.id === id && current.variant === variant);
|
|
131
|
+
if (agentChanges || modelChanges) {
|
|
132
|
+
// Nothing about a chat is changed while it is working, and nothing needs changing here unless the agent or the model actually differs.
|
|
133
|
+
const busy = await idle();
|
|
134
|
+
if (busy !== null) {
|
|
135
|
+
notes.push(busy);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (agentChanges)
|
|
140
|
+
await attempt('agent not switched', () => deps.session.switchAgent({ sessionID, agent: result.agent }));
|
|
141
|
+
const on = !modelChanges || await attempt('model not switched', () => deps.session.switchModel({ sessionID, model: { providerID, id, ...(variant === null ? {} : { variant }) } }));
|
|
142
|
+
if (on)
|
|
143
|
+
Object.assign(outcome, { model: modelName(result.model), fit: result.fit });
|
|
144
|
+
if (result.mode === 'review')
|
|
145
|
+
await attempt('review rules not set', () => deps.session.instructions.entry.put({ sessionID, key: REVIEW_RULES_KEY, value: reviewRules }));
|
|
146
|
+
// shortcut: a failed remove is not reported. Rules that stay only say how to review, and there may be none to remove.
|
|
147
|
+
else
|
|
148
|
+
try {
|
|
149
|
+
await deps.session.instructions.entry.remove({ sessionID, key: REVIEW_RULES_KEY });
|
|
150
|
+
}
|
|
151
|
+
catch { /* see the shortcut above */ }
|
|
152
|
+
};
|
|
153
|
+
try {
|
|
154
|
+
await place();
|
|
155
|
+
}
|
|
156
|
+
catch (error) {
|
|
157
|
+
notes.push(brief(error));
|
|
158
|
+
}
|
|
159
|
+
return { outcome, notes };
|
|
160
|
+
}
|
|
161
|
+
/** The record is for the panel; losing it must not fail a message that was sent. `messageID` is the message's id in the chat, when the host gave one. */
|
|
162
|
+
export async function recordPlaced(deps, sessionID, { outcome, notes }, messageID = null) {
|
|
163
|
+
try {
|
|
164
|
+
await recordDecision(deps.store, { at: new Date().toISOString(), sessionID, kind: 'chat', ...outcome, note: notes.length ? notes.join('; ') : null, messageID });
|
|
165
|
+
}
|
|
166
|
+
catch { /* not recorded */ }
|
|
167
|
+
}
|
|
168
|
+
export function relayCommand(deps) {
|
|
169
|
+
const timing = timingOf(deps), { readMs } = timing;
|
|
170
|
+
const turns = new Map();
|
|
171
|
+
async function relay({ sessionID, prompt, delivery }) {
|
|
172
|
+
const placed = await placeMessage(deps, timing, { sessionID, prompt, unsure: 'plan' });
|
|
173
|
+
let failure, sent;
|
|
174
|
+
// The marker tells the hook of a chat whose switch is on that this message is placed already. The host keeps it with the message and does not send it to the model.
|
|
175
|
+
try {
|
|
176
|
+
sent = await deps.session.prompt({ ...prompt, sessionID, delivery, metadata: { relay: 'sent' } });
|
|
177
|
+
}
|
|
178
|
+
catch (error) {
|
|
179
|
+
failure = { error };
|
|
180
|
+
placed.notes.push(`the message could not be sent: ${brief(error)}`);
|
|
181
|
+
}
|
|
182
|
+
// The send gives back the new message's entry; its id is the message's id in the chat (seen on 2.3.0, 18 Nov).
|
|
183
|
+
const messageID = sent?.id;
|
|
184
|
+
await recordPlaced(deps, sessionID, placed, typeof messageID === 'string' ? messageID : null);
|
|
185
|
+
if (failure)
|
|
186
|
+
throw failure.error;
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
name: 'relay',
|
|
190
|
+
description: 'Relay: pick the model for this message (plan, execute or review) and send it. /relay on or /relay off: do it for every message in this chat',
|
|
191
|
+
async execute(input) {
|
|
192
|
+
if (!input.prompt.text.trim())
|
|
193
|
+
throw new Error('Relay: type your message after /relay.');
|
|
194
|
+
const word = input.prompt.text.trim().toLowerCase(), toggle = word === 'on' ? true : word === 'off' ? false : null;
|
|
195
|
+
// One at a time in a chat: the next message waits for this one, whether this one works or not.
|
|
196
|
+
// The queue is joined here, before anything is awaited, so two calls join it in the order they were made, not in the order their own checks happen to answer.
|
|
197
|
+
const turn = (turns.get(input.sessionID) ?? Promise.resolve()).then(async () => {
|
|
198
|
+
if (toggle === null)
|
|
199
|
+
return relay(input);
|
|
200
|
+
// `/relay on` or `/relay off`: the switch for this chat. Nothing is sent, and nothing is decided.
|
|
201
|
+
if (await within(() => setChatSwitch(deps.store, input.sessionID, toggle), readMs) === LATE)
|
|
202
|
+
throw new Error(`Relay: the switch could not be saved within ${readMs / 1000} seconds.`);
|
|
203
|
+
});
|
|
204
|
+
const settled = turn.then(() => undefined, () => undefined);
|
|
205
|
+
turns.set(input.sessionID, settled);
|
|
206
|
+
void settled.then(() => { if (turns.get(input.sessionID) === settled)
|
|
207
|
+
turns.delete(input.sessionID); });
|
|
208
|
+
return turn;
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { PriceStep } from './inventory.js';
|
|
2
|
+
import { type ModelChoice, type OfferedModel } from './settings.js';
|
|
3
|
+
export declare const modes: readonly ["plan", "execute", "review"];
|
|
4
|
+
export type Mode = typeof modes[number];
|
|
5
|
+
export declare const USE_FOR_MAX = 200;
|
|
6
|
+
/** A model chosen for a mode, with the person's own words for the kind of work it suits. An empty line means nothing was written. */
|
|
7
|
+
export type ModeChoice = ModelChoice & {
|
|
8
|
+
useFor: string;
|
|
9
|
+
};
|
|
10
|
+
export type RelaySettings = {
|
|
11
|
+
revision: number;
|
|
12
|
+
modes: Record<Mode, ModeChoice[]>;
|
|
13
|
+
decider: ModelChoice | null;
|
|
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
|
+
};
|
|
26
|
+
/**
|
|
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
|
|
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.
|
|
31
|
+
*/
|
|
32
|
+
export type Reply = {
|
|
33
|
+
requests: number;
|
|
34
|
+
fresh: number;
|
|
35
|
+
cached: number;
|
|
36
|
+
costUsd: string | null;
|
|
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[];
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
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.
|
|
77
|
+
* `messageID` names the message the decision was made for, so that `reply` can be read once the chat has answered it.
|
|
78
|
+
*/
|
|
79
|
+
export type Decision = {
|
|
80
|
+
at: string;
|
|
81
|
+
sessionID: string;
|
|
82
|
+
kind: 'chat' | 'helper';
|
|
83
|
+
mode: Mode | null;
|
|
84
|
+
confidence: number | null;
|
|
85
|
+
fit: number | null;
|
|
86
|
+
model: string | null;
|
|
87
|
+
ms: number;
|
|
88
|
+
costUsd: string | null;
|
|
89
|
+
note: string | null;
|
|
90
|
+
messageID: string | null;
|
|
91
|
+
reply: Reply | null;
|
|
92
|
+
};
|
|
93
|
+
export type RelayStore = {
|
|
94
|
+
get(key: string): Promise<unknown>;
|
|
95
|
+
set(key: string, value: RelaySettings | Decision[] | Usage | boolean): Promise<void>;
|
|
96
|
+
compareAndSet?(key: string, expected: unknown, value: RelaySettings | Decision[]): Promise<boolean>;
|
|
97
|
+
};
|
|
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;
|
|
104
|
+
export declare function getRelaySettings(store: Pick<RelayStore, 'get'>): Promise<RelaySettings>;
|
|
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. */
|
|
106
|
+
export declare function saveRelaySettings(store: RelayStore, revision: number, input: unknown, chatModels: readonly OfferedModel[], decisionModels: readonly OfferedModel[]): Promise<RelaySettings>;
|
|
107
|
+
/** A new record has no reply yet; one made for a message of a chat names that message. */
|
|
108
|
+
export declare function recordDecision(store: RelayStore, decision: Omit<Decision, 'messageID' | 'reply'> & {
|
|
109
|
+
messageID?: string | null;
|
|
110
|
+
}): Promise<void>;
|
|
111
|
+
/** The messages of one chat whose records still wait for what the reply took. */
|
|
112
|
+
export declare function waitingReplies(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<string[]>;
|
|
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. */
|
|
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. */
|
|
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[]>;
|
|
121
|
+
/** Only a stored `true` counts as on. */
|
|
122
|
+
export declare function chatSwitch(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<boolean>;
|
|
123
|
+
export declare function setChatSwitch(store: Pick<RelayStore, 'set'>, sessionID: string, on: boolean): Promise<void>;
|
|
124
|
+
export {};
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { costOf, formatUsd, parseUsd, storedUsd } from './costs.js';
|
|
2
|
+
import { offered, validateChoices } from './settings.js';
|
|
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.
|
|
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
|
|
5
|
+
// held back by it; with no compare-and-set in stock storage, a save from two OpenCode processes in the same instant can still lose one.
|
|
6
|
+
let queue = Promise.resolve();
|
|
7
|
+
function serial(task) {
|
|
8
|
+
const result = queue.then(task);
|
|
9
|
+
queue = result.then(() => undefined, () => undefined);
|
|
10
|
+
return result;
|
|
11
|
+
}
|
|
12
|
+
export const modes = ['plan', 'execute', 'review'];
|
|
13
|
+
export const USE_FOR_MAX = 200;
|
|
14
|
+
const sources = ['opencode', 'artificial-analysis'];
|
|
15
|
+
const SETTINGS = 'relay/settings', DECISIONS = 'relay/decisions', USAGE = 'relay/usage', KEEP = 20, WAITING_KEEP = 30;
|
|
16
|
+
const same = (a, b) => a.providerID === b.providerID && a.id === b.id && a.variant === b.variant;
|
|
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);
|
|
24
|
+
function entries(value) {
|
|
25
|
+
if (!Array.isArray(value))
|
|
26
|
+
throw new Error('Invalid mode choices');
|
|
27
|
+
const parts = value.map(item => {
|
|
28
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
29
|
+
throw new Error('Invalid model choice');
|
|
30
|
+
const { useFor = '', ...choice } = item;
|
|
31
|
+
if (typeof useFor !== 'string')
|
|
32
|
+
throw new Error('Invalid "use it for" line');
|
|
33
|
+
const line = useFor.replace(/\s+/g, ' ').trim();
|
|
34
|
+
if (line.length > USE_FOR_MAX)
|
|
35
|
+
throw new Error(`A "use it for" line can have at most ${USE_FOR_MAX} characters`);
|
|
36
|
+
return { choice, line };
|
|
37
|
+
});
|
|
38
|
+
return validateChoices(parts.map(part => part.choice)).map((choice, index) => ({ ...choice, useFor: parts[index].line }));
|
|
39
|
+
}
|
|
40
|
+
function shape(value, keys) {
|
|
41
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== keys)
|
|
42
|
+
throw new Error('Invalid Relay settings');
|
|
43
|
+
const { modes: lists, decider } = value;
|
|
44
|
+
if (!lists || typeof lists !== 'object' || Array.isArray(lists) || Object.keys(lists).sort().join(',') !== 'execute,plan,review')
|
|
45
|
+
throw new Error('Invalid modes');
|
|
46
|
+
return { modes: { plan: entries(lists.plan), execute: entries(lists.execute), review: entries(lists.review) }, decider: decider === null ? null : validateChoices([decider])[0] };
|
|
47
|
+
}
|
|
48
|
+
function decode(value) {
|
|
49
|
+
if (value === undefined)
|
|
50
|
+
return { revision: 0, modes: { plan: [], execute: [], review: [] }, decider: null };
|
|
51
|
+
const revision = value?.revision;
|
|
52
|
+
if (typeof revision !== 'number' || !Number.isSafeInteger(revision) || revision < 0)
|
|
53
|
+
throw new Error('Invalid Relay settings');
|
|
54
|
+
return { revision, ...shape(value, 'decider,modes,revision') };
|
|
55
|
+
}
|
|
56
|
+
export function getRelaySettings(store) { return serial(async () => decode(await store.get(SETTINGS))); }
|
|
57
|
+
/** 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. */
|
|
58
|
+
export function saveRelaySettings(store, revision, input, chatModels, decisionModels) {
|
|
59
|
+
return serial(async () => {
|
|
60
|
+
const next = shape(input, 'decider,modes'), raw = await store.get(SETTINGS), previous = decode(raw);
|
|
61
|
+
if (!Number.isSafeInteger(revision) || revision !== previous.revision || revision === Number.MAX_SAFE_INTEGER)
|
|
62
|
+
throw new Error('Stale settings revision');
|
|
63
|
+
for (const mode of modes)
|
|
64
|
+
for (const choice of next.modes[mode]) {
|
|
65
|
+
if (!previous.modes[mode].some(old => same(old, choice)) && !offered(chatModels, choice))
|
|
66
|
+
throw new Error('Selected model or variant is unavailable');
|
|
67
|
+
}
|
|
68
|
+
if (next.decider && !(previous.decider && same(previous.decider, next.decider)) && !offered(decisionModels, next.decider))
|
|
69
|
+
throw new Error('The decider must be a decision model that is offered');
|
|
70
|
+
const saved = { revision: revision + 1, ...next };
|
|
71
|
+
if (typeof store.compareAndSet === 'function') {
|
|
72
|
+
const updated = await store.compareAndSet(SETTINGS, raw, saved);
|
|
73
|
+
if (updated === false)
|
|
74
|
+
throw new Error('Stale settings revision');
|
|
75
|
+
if (updated !== true)
|
|
76
|
+
throw new Error('Invalid compare-and-set response');
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
await store.set(SETTINGS, saved);
|
|
80
|
+
return structuredClone(saved);
|
|
81
|
+
});
|
|
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
|
+
}
|
|
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. */
|
|
90
|
+
function readable(value) {
|
|
91
|
+
const item = value;
|
|
92
|
+
if (!item || typeof item !== 'object' || typeof item.at !== 'string' || typeof item.sessionID !== 'string' || (item.kind !== 'chat' && item.kind !== 'helper') || typeof item.ms !== 'number')
|
|
93
|
+
return null;
|
|
94
|
+
const took = (item.reply && typeof item.reply === 'object' ? item.reply : {}), requests = number(took.requests), fresh = number(took.fresh), cached = number(took.cached);
|
|
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) };
|
|
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 };
|
|
100
|
+
}
|
|
101
|
+
const stored = async (store) => {
|
|
102
|
+
const value = await store.get(DECISIONS);
|
|
103
|
+
return Array.isArray(value) ? value.map(readable).filter(item => item !== null) : [];
|
|
104
|
+
};
|
|
105
|
+
/** A new record has no reply yet; one made for a message of a chat names that message. */
|
|
106
|
+
export function recordDecision(store, decision) {
|
|
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.
|
|
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
|
+
});
|
|
114
|
+
}
|
|
115
|
+
const waits = (item, sessionID) => item.sessionID === sessionID && item.messageID !== null && item.reply === null;
|
|
116
|
+
/** The messages of one chat whose records still wait for what the reply took. */
|
|
117
|
+
export function waitingReplies(store, sessionID) {
|
|
118
|
+
return serial(async () => (await stored(store)).flatMap(item => waits(item, sessionID) ? [item.messageID] : []));
|
|
119
|
+
}
|
|
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. */
|
|
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
|
|
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) }; });
|
|
187
|
+
}
|
|
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)); }
|
|
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.
|
|
193
|
+
const switchKey = (sessionID) => `relay/on/${encodeURIComponent(sessionID)}`;
|
|
194
|
+
/** Only a stored `true` counts as on. */
|
|
195
|
+
export async function chatSwitch(store, sessionID) { return (await store.get(switchKey(sessionID))) === true; }
|
|
196
|
+
export function setChatSwitch(store, sessionID, on) { return store.set(switchKey(sessionID), on); }
|