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,123 @@
|
|
|
1
|
+
// The intelligence index beside each model: Artificial Analysis's number, as OpenRouter's public model list carries it. No key is needed and
|
|
2
|
+
// nothing about the person is sent: one plain GET of the public list. OpenCode's model records share no id with that list, so a model is
|
|
3
|
+
// matched by its id, its API id or its name, after both sides are put in one form; a key two different models would share matches nothing.
|
|
4
|
+
export const INDEX_SOURCE = 'Artificial Analysis Intelligence Index, from OpenRouter\'s public model list';
|
|
5
|
+
const LIST_URL = 'https://openrouter.ai/api/v1/models';
|
|
6
|
+
const MAX_CHARS = 8_000_000;
|
|
7
|
+
/** OpenRouter lists some models again under a suffix (":batch", ":free" …), and OpenCode marks free copies with "-free"; they are the same model. */
|
|
8
|
+
const VARIANT = /(:(batch|free|extended|thinking|beta|nitro|floor|exacto)|-free)$/;
|
|
9
|
+
/** One form for a model's id or name: no vendor, lower case, no variant suffix, and dashes for dots, colons, underscores and spaces. */
|
|
10
|
+
export function modelKey(text) {
|
|
11
|
+
return (text.toLowerCase().split('/').pop() ?? '').trim().replace(VARIANT, '').replace(/[._:\s]+/g, '-').replace(/^-+|-+$/g, '');
|
|
12
|
+
}
|
|
13
|
+
/** The models in OpenRouter's reply that carry an index, by key. A key that two different models would share is left out. */
|
|
14
|
+
export function indexTable(reply) {
|
|
15
|
+
const table = new Map(), clash = new Set();
|
|
16
|
+
const data = reply?.data;
|
|
17
|
+
if (!Array.isArray(data))
|
|
18
|
+
return table;
|
|
19
|
+
for (const item of data) {
|
|
20
|
+
const index = item?.benchmarks?.artificial_analysis?.intelligence_index;
|
|
21
|
+
if (typeof item?.id !== 'string' || typeof index !== 'number' || !Number.isFinite(index))
|
|
22
|
+
continue;
|
|
23
|
+
const id = item.id.replace(VARIANT, '');
|
|
24
|
+
for (const name of [item.id, item.canonical_slug]) {
|
|
25
|
+
if (typeof name !== 'string')
|
|
26
|
+
continue;
|
|
27
|
+
const key = modelKey(name), found = table.get(key);
|
|
28
|
+
if (!key || clash.has(key))
|
|
29
|
+
continue;
|
|
30
|
+
if (found && found.id !== id) {
|
|
31
|
+
table.delete(key);
|
|
32
|
+
clash.add(key);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
table.set(key, { id, index });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return table;
|
|
39
|
+
}
|
|
40
|
+
/** A model's index: by its id or its name, then by the one listed model whose key ends in its key. Null when none fits clearly. */
|
|
41
|
+
export function indexFor(model, table) {
|
|
42
|
+
const keys = [model.id, model.name].map(modelKey).filter(Boolean);
|
|
43
|
+
for (const key of keys) {
|
|
44
|
+
const found = table.get(key);
|
|
45
|
+
if (found)
|
|
46
|
+
return { index: found.index, matched: found.id };
|
|
47
|
+
}
|
|
48
|
+
for (const key of keys) {
|
|
49
|
+
if (key.length < 5)
|
|
50
|
+
continue;
|
|
51
|
+
const ends = new Map();
|
|
52
|
+
for (const [listed, found] of table)
|
|
53
|
+
if (listed.endsWith(`-${key}`))
|
|
54
|
+
ends.set(found.id, found.index);
|
|
55
|
+
if (ends.size === 1) {
|
|
56
|
+
const [[matched, index]] = [...ends];
|
|
57
|
+
return { index: index, matched: matched };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/** Fetches OpenRouter's public model list (one GET, no key, nothing about the person) and keeps the models that carry an index. */
|
|
63
|
+
export async function fetchIndexTable(fetcher = fetch, ms = 15_000) {
|
|
64
|
+
const response = await fetcher(LIST_URL, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(ms) });
|
|
65
|
+
if (!response.ok)
|
|
66
|
+
throw new Error(`OpenRouter answered ${response.status}`);
|
|
67
|
+
const text = await response.text();
|
|
68
|
+
if (text.length > MAX_CHARS)
|
|
69
|
+
throw new Error('the model list is too big');
|
|
70
|
+
let reply;
|
|
71
|
+
try {
|
|
72
|
+
reply = JSON.parse(text);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw new Error('the reply is not a model list');
|
|
76
|
+
}
|
|
77
|
+
if (!Array.isArray(reply?.data))
|
|
78
|
+
throw new Error('the reply is not a model list');
|
|
79
|
+
const table = indexTable(reply);
|
|
80
|
+
// A list with no index at all is more likely a change on OpenRouter's side than a fact, so it never replaces a stored copy.
|
|
81
|
+
if (!table.size)
|
|
82
|
+
throw new Error('the list carries no index');
|
|
83
|
+
return table;
|
|
84
|
+
}
|
|
85
|
+
const CACHE_KEY = 'relay/intelligence', DAY_MS = 24 * 3600_000;
|
|
86
|
+
const decodeCache = (value) => {
|
|
87
|
+
const cache = value;
|
|
88
|
+
return cache && typeof cache.fetchedAt === 'string' && Number.isFinite(Date.parse(cache.fetchedAt)) && Array.isArray(cache.rows)
|
|
89
|
+
&& cache.rows.every(row => Array.isArray(row) && row.length === 3 && typeof row[0] === 'string' && typeof row[1] === 'string' && typeof row[2] === 'number') ? cache : null;
|
|
90
|
+
};
|
|
91
|
+
const fromRows = (rows) => new Map(rows.map(([key, id, index]) => [key, { id, index }]));
|
|
92
|
+
/** The stored table at any age, from storage alone and never the network, for Relay's own choice while a message is placed. Empty when there is no readable copy. */
|
|
93
|
+
export async function storedIndexTable(store) {
|
|
94
|
+
try {
|
|
95
|
+
const saved = decodeCache(await store.get(CACHE_KEY));
|
|
96
|
+
return saved ? fromRows(saved.rows) : new Map();
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return new Map();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** The index table: the stored copy while it is under a day old, else a fresh fetch, stored; when that fails, the older copy with a note. */
|
|
103
|
+
export async function loadIndexTable(store, fetcher, now) {
|
|
104
|
+
let saved = null;
|
|
105
|
+
try {
|
|
106
|
+
saved = decodeCache(await store.get(CACHE_KEY));
|
|
107
|
+
}
|
|
108
|
+
catch { /* read as no copy */ }
|
|
109
|
+
if (saved && now - Date.parse(saved.fetchedAt) < DAY_MS)
|
|
110
|
+
return { table: fromRows(saved.rows), fetchedAt: saved.fetchedAt, note: null };
|
|
111
|
+
try {
|
|
112
|
+
const table = await fetchIndexTable(fetcher), fetchedAt = new Date(now).toISOString();
|
|
113
|
+
try {
|
|
114
|
+
await store.set(CACHE_KEY, { fetchedAt, rows: [...table].map(([key, found]) => [key, found.id, found.index]) });
|
|
115
|
+
}
|
|
116
|
+
catch { /* shown anyway, fetched again next time */ }
|
|
117
|
+
return { table, fetchedAt, note: null };
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
121
|
+
return saved ? { table: fromRows(saved.rows), fetchedAt: saved.fetchedAt, note: `could not refresh the index: ${reason}` } : { table: new Map(), fetchedAt: null, note: `could not load the index: ${reason}` };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Plugin } from '@opencode/plugin';
|
|
2
|
+
/** The prices that apply once a chat is over `above` tokens. */
|
|
3
|
+
export type PriceStep = {
|
|
4
|
+
above: number;
|
|
5
|
+
inputPerMillion: string | null;
|
|
6
|
+
outputPerMillion: string | null;
|
|
7
|
+
cacheReadPerMillion: string | null;
|
|
8
|
+
cacheWritePerMillion: string | null;
|
|
9
|
+
};
|
|
10
|
+
/** USD for one million tokens, as the host lists it. `null` is unknown; `'0'` can mean free or not listed. `steps` are the prices for longer chats, smallest first. */
|
|
11
|
+
export type ModelCostView = Omit<PriceStep, 'above'> & {
|
|
12
|
+
tiered: boolean;
|
|
13
|
+
steps: PriceStep[];
|
|
14
|
+
};
|
|
15
|
+
export type ListedModel = {
|
|
16
|
+
providerID: string;
|
|
17
|
+
id: string;
|
|
18
|
+
name: string;
|
|
19
|
+
enabled: boolean;
|
|
20
|
+
status: string;
|
|
21
|
+
variants: string[];
|
|
22
|
+
capabilities: {
|
|
23
|
+
input: string[];
|
|
24
|
+
output: string[];
|
|
25
|
+
tools: boolean;
|
|
26
|
+
};
|
|
27
|
+
limit: {
|
|
28
|
+
context: number;
|
|
29
|
+
output: number;
|
|
30
|
+
};
|
|
31
|
+
cost: ModelCostView;
|
|
32
|
+
};
|
|
33
|
+
/** Project host records can contain credentials; return only explicit display fields. Without a type the host lists chat models. */
|
|
34
|
+
export declare function listProjectModels(context: Pick<Plugin.Context, 'location' | 'model'>, type?: 'chat' | 'decision'): Promise<ListedModel[]>;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { usdString } from './costs.js';
|
|
2
|
+
const prices = (entry) => ({ inputPerMillion: usdString(entry?.input), outputPerMillion: usdString(entry?.output), cacheReadPerMillion: usdString(entry?.cache?.read), cacheWritePerMillion: usdString(entry?.cache?.write) });
|
|
3
|
+
function costView(cost) {
|
|
4
|
+
const entries = Array.isArray(cost) ? cost : [];
|
|
5
|
+
const base = entries.find(entry => entry?.tier === undefined) ?? entries[0];
|
|
6
|
+
// The host prices a request by the size of its context: the largest step below it, else the base price (2.3.0).
|
|
7
|
+
const steps = entries.flatMap(entry => { const size = entry?.tier?.type === 'context' ? entry.tier.size : null; return typeof size === 'number' && size > 0 ? [{ above: size, ...prices(entry) }] : []; }).sort((a, b) => a.above - b.above);
|
|
8
|
+
return { ...prices(base), tiered: entries.length > 1, steps };
|
|
9
|
+
}
|
|
10
|
+
/** Project host records can contain credentials; return only explicit display fields. Without a type the host lists chat models. */
|
|
11
|
+
export async function listProjectModels(context, type) {
|
|
12
|
+
const result = await context.model.list({ location: { directory: context.location.directory }, ...(type ? { types: [type] } : {}) });
|
|
13
|
+
return result.data.map(model => ({
|
|
14
|
+
providerID: model.providerID,
|
|
15
|
+
id: model.id,
|
|
16
|
+
name: model.name,
|
|
17
|
+
enabled: model.enabled,
|
|
18
|
+
status: model.status,
|
|
19
|
+
variants: model.variants.map(variant => variant.id),
|
|
20
|
+
capabilities: {
|
|
21
|
+
input: [...model.capabilities.input],
|
|
22
|
+
output: [...model.capabilities.output],
|
|
23
|
+
tools: model.capabilities.tools,
|
|
24
|
+
},
|
|
25
|
+
limit: { context: model.limit.context, output: model.limit.output },
|
|
26
|
+
cost: costView(model.cost),
|
|
27
|
+
}));
|
|
28
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type Mode, type ModeChoice } from './relay-store.js';
|
|
2
|
+
import type { ModelChoice } from './settings.js';
|
|
3
|
+
/** The efforts Relay can order, weakest first. A model's default effort is not on it: providers differ on what the default means. */
|
|
4
|
+
export declare const EFFORTS: readonly ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
5
|
+
/** A typical request until a model has replies of its own: tokens read new and tokens written (the cost check's own guess), and how many of its replies make an average. */
|
|
6
|
+
export declare const TYPICAL_IN = 1500, TYPICAL_OUT = 500, OWN_REPLIES = 3;
|
|
7
|
+
/** What Relay knows of one model at one effort, from its stored copies: the Intelligence and Coding indexes, its prices in USD a million tokens, and its own output and reasoning a request. */
|
|
8
|
+
export type Standing = {
|
|
9
|
+
index: number | null;
|
|
10
|
+
coding: number | null;
|
|
11
|
+
inputPerMillion: string | null;
|
|
12
|
+
outputPerMillion: string | null;
|
|
13
|
+
outPerRequest: number | null;
|
|
14
|
+
};
|
|
15
|
+
/** By `modelName(choice)`. */
|
|
16
|
+
export type Standings = ReadonlyMap<string, Standing>;
|
|
17
|
+
export type Size = 'small' | 'big';
|
|
18
|
+
export type SizeAnswer = {
|
|
19
|
+
size: Size;
|
|
20
|
+
confidence: number;
|
|
21
|
+
};
|
|
22
|
+
export type Ranked = {
|
|
23
|
+
kind: 'ranked';
|
|
24
|
+
strongest: ModelChoice;
|
|
25
|
+
cheapest: ModelChoice;
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'unranked';
|
|
28
|
+
reason: string;
|
|
29
|
+
};
|
|
30
|
+
/** Relay's own choice for a mode, or null when it is not Relay's to make: a line is written, or fewer than two models can be used now. */
|
|
31
|
+
export declare function rank(mode: Mode, list: readonly ModeChoice[], usable: readonly ModeChoice[], standings: Standings, writer: ModelChoice | null): Ranked | null;
|
package/dist/ranking.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { parseUsd } from './costs.js';
|
|
2
|
+
import { modelName } from './relay-store.js';
|
|
3
|
+
// Relay's own choice inside a mode (docs/superpowers/specs/2026-11-23-relay-own-choice-by-index-and-price-design.md). When a mode has two or
|
|
4
|
+
// more usable models and no "use it for" lines, Relay ranks them itself: the highest index takes big work, the cheapest typical request takes
|
|
5
|
+
// small work. Pure rules over what Relay has stored; the decider never sees any of it. Nothing here may import from `node:` (the panel bundles it).
|
|
6
|
+
/** The efforts Relay can order, weakest first. A model's default effort is not on it: providers differ on what the default means. */
|
|
7
|
+
export const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
8
|
+
/** A typical request until a model has replies of its own: tokens read new and tokens written (the cost check's own guess), and how many of its replies make an average. */
|
|
9
|
+
export const TYPICAL_IN = 1500, TYPICAL_OUT = 500, OWN_REPLIES = 3;
|
|
10
|
+
const plain = ({ providerID, id, variant }) => ({ providerID, id, variant });
|
|
11
|
+
const sameModel = (a, b) => a.providerID === b.providerID && a.id === b.id;
|
|
12
|
+
/** The place of an effort on the scale, or -1 for the default effort and any other name. */
|
|
13
|
+
const onScale = (variant) => variant === null ? -1 : EFFORTS.indexOf(variant);
|
|
14
|
+
const MEDIUM = EFFORTS.indexOf('medium');
|
|
15
|
+
/** Relay's own choice for a mode, or null when it is not Relay's to make: a line is written, or fewer than two models can be used now. */
|
|
16
|
+
export function rank(mode, list, usable, standings, writer) {
|
|
17
|
+
if (list.some(choice => choice.useFor !== '') || usable.length < 2)
|
|
18
|
+
return null;
|
|
19
|
+
const unranked = (reason) => ({ kind: 'unranked', reason });
|
|
20
|
+
// Rows of one model differ only by their effort, so both must be on the scale to be told apart.
|
|
21
|
+
for (const [at, row] of usable.entries()) {
|
|
22
|
+
if (usable.slice(at + 1).some(other => sameModel(row, other) && (onScale(row.variant) < 0 || onScale(other.variant) < 0)))
|
|
23
|
+
return unranked(`choose an effort for each ${row.id} row`);
|
|
24
|
+
}
|
|
25
|
+
const standingOf = (choice) => standings.get(modelName(choice));
|
|
26
|
+
// One index for the whole comparison: Execute's Coding index only when every model has one.
|
|
27
|
+
const coding = mode === 'execute' && usable.every(row => typeof standingOf(row)?.coding === 'number');
|
|
28
|
+
const scoreOf = (choice) => { const standing = standingOf(choice), score = coding ? standing?.coding : standing?.index; return typeof score === 'number' ? score : null; };
|
|
29
|
+
const missingIndex = usable.find(row => scoreOf(row) === null);
|
|
30
|
+
if (missingIndex)
|
|
31
|
+
return unranked(`no index for ${missingIndex.id}`);
|
|
32
|
+
const priceOf = (choice) => {
|
|
33
|
+
const standing = standingOf(choice);
|
|
34
|
+
if (!standing || standing.inputPerMillion === null || standing.outputPerMillion === null)
|
|
35
|
+
return null;
|
|
36
|
+
try {
|
|
37
|
+
const input = parseUsd(standing.inputPerMillion), output = parseUsd(standing.outputPerMillion);
|
|
38
|
+
return input === 0n && output === 0n ? null : { input, output }; // $0 can mean "not listed", so it is no price
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
const missingPrice = usable.find(row => priceOf(row) === null);
|
|
45
|
+
if (missingPrice)
|
|
46
|
+
return unranked(`no price for ${missingPrice.id}`);
|
|
47
|
+
/** The model whose best row scores highest (a tie goes to the model met first), then that model's highest effort. */
|
|
48
|
+
const strongestOf = (rows) => {
|
|
49
|
+
let best = rows[0], bestScore = -Infinity;
|
|
50
|
+
for (const row of rows) {
|
|
51
|
+
const score = Math.max(...rows.filter(other => sameModel(other, row)).map(other => scoreOf(other) ?? -Infinity));
|
|
52
|
+
if (score > bestScore) {
|
|
53
|
+
best = row;
|
|
54
|
+
bestScore = score;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return rows.filter(row => sameModel(row, best)).reduce((top, row) => onScale(row.variant) > onScale(top.variant) ? row : top);
|
|
58
|
+
};
|
|
59
|
+
/** A typical request: TYPICAL_IN read at the input price, and the model's own output and reasoning (TYPICAL_OUT until it has its own) at the output price. */
|
|
60
|
+
const costOf = (row) => {
|
|
61
|
+
const price = priceOf(row), own = standingOf(row)?.outPerRequest;
|
|
62
|
+
const out = typeof own === 'number' && Number.isFinite(own) && own >= 0 ? Math.round(own) : TYPICAL_OUT;
|
|
63
|
+
return BigInt(TYPICAL_IN) * price.input + BigInt(out) * price.output;
|
|
64
|
+
};
|
|
65
|
+
const tie = (row) => { const place = onScale(row.variant); return place < 0 ? MEDIUM : place; };
|
|
66
|
+
const cheapestOf = (rows) => rows.reduce((low, row) => {
|
|
67
|
+
const cost = costOf(row), lowest = costOf(low);
|
|
68
|
+
return cost < lowest || (cost === lowest && tie(row) < tie(low)) ? row : low;
|
|
69
|
+
});
|
|
70
|
+
let rows = usable;
|
|
71
|
+
// A reviewer weaker than the writer made results worse (docs/research/2026-11-17-relay-cost-and-model-choice.md), so none is kept below it.
|
|
72
|
+
const bar = mode === 'review' && writer ? standingOf(writer)?.index : null;
|
|
73
|
+
if (typeof bar === 'number') {
|
|
74
|
+
const kept = usable.filter(row => (standingOf(row)?.index ?? -Infinity) >= bar);
|
|
75
|
+
rows = kept.length ? kept : [strongestOf(usable)];
|
|
76
|
+
}
|
|
77
|
+
return { kind: 'ranked', strongest: plain(strongestOf(rows)), cheapest: plain(cheapestOf(rows)) };
|
|
78
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { PromptInput } from '@opencode/schema/prompt-input';
|
|
2
|
+
import type { AaModel } from './artificial-analysis.js';
|
|
3
|
+
import { type RelayDeps } from './relay-command.js';
|
|
4
|
+
import { type LogStore } from './usage-log.js';
|
|
5
|
+
/** How long a chat may take to show it is idle before it counts as busy and is left as it is. */
|
|
6
|
+
export declare const BUSY_CHECK_MS = 300;
|
|
7
|
+
type PromptEvent = {
|
|
8
|
+
readonly sessionID: string;
|
|
9
|
+
readonly messageID?: string;
|
|
10
|
+
readonly prompt?: PromptInput.Prompt;
|
|
11
|
+
readonly metadata?: Record<string, unknown>;
|
|
12
|
+
};
|
|
13
|
+
export declare function relayAutoHook(deps: RelayDeps): (event: PromptEvent) => Promise<void>;
|
|
14
|
+
/**
|
|
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.
|
|
20
|
+
*/
|
|
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: {
|
|
37
|
+
readonly sessionID: string;
|
|
38
|
+
}) => Promise<void>;
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { LATE, within } from './decider.js';
|
|
2
|
+
import { replyOf } from './chat-facts.js';
|
|
3
|
+
import { placeMessage, recordPlaced, timingOf, uploadsOf } from './relay-command.js';
|
|
4
|
+
import { chatSwitch, decisionsOf, saveReplies, waitingReplies } from './relay-store.js';
|
|
5
|
+
import { buildRecords, saveRecords } from './usage-log.js';
|
|
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,
|
|
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
|
|
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.
|
|
9
|
+
/** How long a chat may take to show it is idle before it counts as busy and is left as it is. */
|
|
10
|
+
export const BUSY_CHECK_MS = 300;
|
|
11
|
+
export function relayAutoHook(deps) {
|
|
12
|
+
const timing = { ...timingOf(deps), waitMs: BUSY_CHECK_MS };
|
|
13
|
+
// The switch is read for every message in every chat, so a slow store must not hold them all for long.
|
|
14
|
+
const flagMs = Math.min(timing.readMs, 1000);
|
|
15
|
+
return async (event) => {
|
|
16
|
+
try {
|
|
17
|
+
// `/relay` placed this message already and marked its send.
|
|
18
|
+
if (event.metadata?.relay !== undefined || !event.prompt?.text?.trim())
|
|
19
|
+
return;
|
|
20
|
+
const sessionID = event.sessionID, prompt = event.prompt;
|
|
21
|
+
if (await within(() => chatSwitch(deps.store, sessionID), flagMs) !== true)
|
|
22
|
+
return;
|
|
23
|
+
// shortcut: the hook holds a message for at most three read limits; work still running then goes on without it, so a host call that
|
|
24
|
+
// answers very late could switch the chat during the reply. The hook also does not wait for a `/relay` of the same chat that is still running.
|
|
25
|
+
await within(async () => {
|
|
26
|
+
const placed = await placeMessage(deps, timing, { sessionID, prompt, unsure: 'stay', uploads: uploadsOf(event.metadata) });
|
|
27
|
+
// The record is for the panel; the message does not wait for it. recordPlaced never rejects.
|
|
28
|
+
void recordPlaced(deps, sessionID, placed, typeof event.messageID === 'string' ? event.messageID : null);
|
|
29
|
+
}, timing.readMs * 3);
|
|
30
|
+
}
|
|
31
|
+
catch { /* never fail the person's message */ }
|
|
32
|
+
};
|
|
33
|
+
}
|
|
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
|
+
}
|
|
57
|
+
export function relayReplyHook(deps) {
|
|
58
|
+
const limitMs = Math.min(timingOf(deps).readMs, 1000), chat = chatReader(deps, limitMs);
|
|
59
|
+
return async (event) => {
|
|
60
|
+
try {
|
|
61
|
+
await within(async () => {
|
|
62
|
+
const waiting = await waitingReplies(deps.store, event.sessionID);
|
|
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)
|
|
65
|
+
return;
|
|
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]] : []; }));
|
|
68
|
+
if (replies.size)
|
|
69
|
+
await saveReplies(deps.store, event.sessionID, replies);
|
|
70
|
+
if (deps.log)
|
|
71
|
+
await chat.keep(deps.log, event.sessionID, messages, listed, borrowed);
|
|
72
|
+
}, limitMs);
|
|
73
|
+
}
|
|
74
|
+
catch { /* the record is for the panel; the chat goes idle whatever happens here */ }
|
|
75
|
+
};
|
|
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
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Plugin } from '@opencode/plugin';
|
|
2
|
+
import type { PromptInput } from '@opencode/schema/prompt-input';
|
|
3
|
+
import type { Session } from '@opencode/schema/session';
|
|
4
|
+
import { type DecideInput } from './decider.js';
|
|
5
|
+
import type { ListedModel } from './inventory.js';
|
|
6
|
+
import { type Decision, type RelayStore } from './relay-store.js';
|
|
7
|
+
import { type DeciderAnswer } from './router.js';
|
|
8
|
+
import type { ModelChoice } from './settings.js';
|
|
9
|
+
export type RelayDeps = {
|
|
10
|
+
session: Pick<Plugin.Context['session'], 'get' | 'wait' | 'switchAgent' | 'switchModel' | 'prompt' | 'instructions' | 'context'>;
|
|
11
|
+
store: RelayStore;
|
|
12
|
+
chatModels: () => Promise<ListedModel[]>;
|
|
13
|
+
decide: (decider: ModelChoice | null, input: DecideInput) => Promise<DeciderAnswer>;
|
|
14
|
+
/** A file's size in bytes, or null when it is not a file on this machine. */
|
|
15
|
+
fileSize: (uri: string) => Promise<number | null>;
|
|
16
|
+
/** How long a busy chat is waited for before the message goes out unchanged. Default: two minutes. */
|
|
17
|
+
waitMs?: number;
|
|
18
|
+
/** How long reading one file's size may take. Default: one second. */
|
|
19
|
+
sizeMs?: number;
|
|
20
|
+
/** How long the settings, the chat or the model list may take before Relay gives up on them. Default: five seconds. */
|
|
21
|
+
readMs?: number;
|
|
22
|
+
};
|
|
23
|
+
type Invocation = {
|
|
24
|
+
readonly sessionID: Session.ID;
|
|
25
|
+
readonly prompt: PromptInput.Prompt;
|
|
26
|
+
readonly delivery: 'steer' | 'queue';
|
|
27
|
+
};
|
|
28
|
+
type AttachedFile = {
|
|
29
|
+
readonly uri?: string;
|
|
30
|
+
readonly name?: string;
|
|
31
|
+
};
|
|
32
|
+
/** The host gives no type for an attached file, so a picture is told by its address or its name. */
|
|
33
|
+
export declare function isPicture(file: AttachedFile): boolean;
|
|
34
|
+
export type Upload = {
|
|
35
|
+
readonly name: string;
|
|
36
|
+
readonly mime: string;
|
|
37
|
+
readonly path: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* 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
|
|
41
|
+
* file part (seen on 17 Nov). Only well-formed entries count; the metadata comes from the client.
|
|
42
|
+
*/
|
|
43
|
+
export declare function uploadsOf(metadata: unknown): Upload[];
|
|
44
|
+
/** 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. */
|
|
45
|
+
export declare function localPath(uri: string): string | null;
|
|
46
|
+
export declare function fileSize(uri: string): Promise<number | null>;
|
|
47
|
+
export type Timing = {
|
|
48
|
+
readonly waitMs: number;
|
|
49
|
+
readonly sizeMs: number;
|
|
50
|
+
readonly readMs: number;
|
|
51
|
+
};
|
|
52
|
+
export type Placed = {
|
|
53
|
+
outcome: Pick<Decision, 'mode' | 'confidence' | 'fit' | 'model' | 'ms' | 'costUsd'>;
|
|
54
|
+
notes: string[];
|
|
55
|
+
};
|
|
56
|
+
export declare const timingOf: (deps: Pick<RelayDeps, "waitMs" | "sizeMs" | "readMs">) => Timing;
|
|
57
|
+
/**
|
|
58
|
+
* 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
|
|
59
|
+
* 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.
|
|
60
|
+
*/
|
|
61
|
+
export declare function placeMessage(deps: RelayDeps, timing: Timing, input: {
|
|
62
|
+
readonly sessionID: Session.ID;
|
|
63
|
+
readonly prompt: PromptInput.Prompt;
|
|
64
|
+
readonly unsure: 'plan' | 'stay';
|
|
65
|
+
readonly uploads?: readonly Upload[];
|
|
66
|
+
}): Promise<Placed>;
|
|
67
|
+
/** 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. */
|
|
68
|
+
export declare function recordPlaced(deps: Pick<RelayDeps, 'store'>, sessionID: string, { outcome, notes }: Placed, messageID?: string | null): Promise<void>;
|
|
69
|
+
export declare function relayCommand(deps: RelayDeps): {
|
|
70
|
+
name: string;
|
|
71
|
+
description: string;
|
|
72
|
+
execute(input: Invocation): Promise<void>;
|
|
73
|
+
};
|
|
74
|
+
export {};
|