relay-opencode 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/dist/artificial-analysis.d.ts +50 -0
  4. package/dist/artificial-analysis.js +153 -0
  5. package/dist/chat-facts.d.ts +26 -0
  6. package/dist/chat-facts.js +96 -0
  7. package/dist/contract.d.ts +2727 -0
  8. package/dist/contract.js +111 -0
  9. package/dist/costs.d.ts +14 -0
  10. package/dist/costs.js +47 -0
  11. package/dist/decider.d.ts +73 -0
  12. package/dist/decider.js +199 -0
  13. package/dist/gui-experimental.cjs +92 -0
  14. package/dist/gui-styles.d.ts +5 -0
  15. package/dist/gui-styles.js +95 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +62 -0
  18. package/dist/intelligence.d.ts +38 -0
  19. package/dist/intelligence.js +123 -0
  20. package/dist/inventory.d.ts +34 -0
  21. package/dist/inventory.js +28 -0
  22. package/dist/ranking.d.ts +31 -0
  23. package/dist/ranking.js +78 -0
  24. package/dist/relay-auto.d.ts +39 -0
  25. package/dist/relay-auto.js +96 -0
  26. package/dist/relay-command.d.ts +74 -0
  27. package/dist/relay-command.js +211 -0
  28. package/dist/relay-store.d.ts +124 -0
  29. package/dist/relay-store.js +196 -0
  30. package/dist/relay-view.d.ts +124 -0
  31. package/dist/relay-view.js +189 -0
  32. package/dist/review-helper.d.ts +8 -0
  33. package/dist/review-helper.js +68 -0
  34. package/dist/router.d.ts +122 -0
  35. package/dist/router.js +209 -0
  36. package/dist/rpc.d.ts +2725 -0
  37. package/dist/rpc.js +116 -0
  38. package/dist/settings.d.ts +16 -0
  39. package/dist/settings.js +22 -0
  40. package/dist/standings.d.ts +18 -0
  41. package/dist/standings.js +34 -0
  42. package/dist/tui.d.ts +3 -0
  43. package/dist/tui.js +26 -0
  44. package/dist/usage-log.d.ts +135 -0
  45. package/dist/usage-log.js +210 -0
  46. package/dist/usage-view.d.ts +70 -0
  47. package/dist/usage-view.js +104 -0
  48. package/package.json +46 -4
@@ -0,0 +1,124 @@
1
+ import type { ModelCostView } from './inventory.js';
2
+ import { type Decision, type Reply, type UsageRow } from './relay-store.js';
3
+ import type { ModelChoice } from './settings.js';
4
+ /** A listed price of 0 can mean free or not known, so it is never called free. */
5
+ export declare function priceLabel(cost: Pick<ModelCostView, 'inputPerMillion' | 'outputPerMillion' | 'tiered'>): string;
6
+ /** For the "Add a model" menu: the input price, then the output price, compared exactly; a price not listed sorts last. "$0 or not listed" counts as $0. */
7
+ export declare function cheapestFirst(a: {
8
+ name: string;
9
+ cost: Pick<ModelCostView, 'inputPerMillion' | 'outputPerMillion'>;
10
+ }, b: {
11
+ name: string;
12
+ cost: Pick<ModelCostView, 'inputPerMillion' | 'outputPerMillion'>;
13
+ }): number;
14
+ /** A price in the model table, whose column header says it is per 1M tokens, input / output. */
15
+ export declare function priceCell(cost: Pick<ModelCostView, 'inputPerMillion' | 'outputPerMillion' | 'tiered'>): string;
16
+ /** A context window the way people say it: 8K, 200K, 1M. Zero means the catalog does not list it, shown as a dash (the cell says why). */
17
+ export declare function contextLabel(tokens: number): string;
18
+ /** An intelligence index as the table shows it: one decimal at most, and a dash when no index was found for the model. */
19
+ export declare const indexLabel: (index: number | null | undefined) => string;
20
+ type TableModel = {
21
+ providerID: string;
22
+ id: string;
23
+ name: string;
24
+ cost: Pick<ModelCostView, 'inputPerMillion' | 'outputPerMillion'>;
25
+ limit: {
26
+ context: number;
27
+ };
28
+ index?: number | null;
29
+ };
30
+ export type TableOrder = 'provider' | 'price' | 'context' | 'index';
31
+ /** The rows of the "Add a model" table: models with every typed word in their provider, id or name, of one provider when one is chosen, in the order chosen. */
32
+ export declare function modelRows<M extends TableModel>(models: readonly M[], view: {
33
+ query: string;
34
+ provider: string;
35
+ order: TableOrder;
36
+ }): M[];
37
+ /** What "Add" puts in a mode's list for this model: the default effort when it is not in the list yet, else the first effort that is not; undefined when every one is. */
38
+ export declare function nextEffort(chosen: readonly ModelChoice[], model: {
39
+ providerID: string;
40
+ id: string;
41
+ variants: readonly string[];
42
+ }): string | null | undefined;
43
+ type Shown = Pick<Decision, 'mode' | 'model' | 'confidence' | 'fit' | 'ms' | 'note'>;
44
+ /** The newest decision as one line, with the reason when nothing was switched. */
45
+ export declare function decisionLine(decision: (Shown & Pick<Decision, 'kind'>) | undefined): string;
46
+ /** One row of Recent choices. The time is left out: the panel shows it in the viewer's own clock. */
47
+ export declare const recentLine: (decision: Shown & Pick<Decision, "kind"> & {
48
+ reply?: Reply | null;
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;
71
+ /** What the test box shows for one try: what Relay would do with the sample message. */
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;
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. */
89
+ export declare const privacyNote: (providerID: string | null) => string;
90
+ /**
91
+ * 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
92
+ * 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.
93
+ */
94
+ export declare function pickerModel(decision: Pick<Decision, 'kind' | 'model'>): {
95
+ providerID: string;
96
+ modelID: string;
97
+ variant?: string;
98
+ } | null;
99
+ export declare const noDeciderNote = "No decider chosen. Until you choose one below, /relay and Relay on send every message to the chat's current model without switching.";
100
+ type PillRow = {
101
+ id: 'toggle' | 'decider' | 'last';
102
+ label: string;
103
+ tone?: 'warning';
104
+ };
105
+ /**
106
+ * The pill above a chat box: whether every message in that chat goes through Relay, the row that turns it, and the chat's last choice.
107
+ * With no decider chosen Relay switches nothing, so the pill says so; switched on, its capsule says it too, with a warning icon.
108
+ */
109
+ export declare function pillView(state: {
110
+ on: boolean;
111
+ last: (Shown & Pick<Decision, 'kind'>) | null;
112
+ decider: boolean;
113
+ }): {
114
+ label: string;
115
+ icon?: 'circle-exclamation';
116
+ tone: 'success' | 'warning' | undefined;
117
+ rows: PillRow[];
118
+ };
119
+ export declare const switchHint = "To send every message in one chat through Relay, type /relay on in that chat or use the Relay pill above its chat box; /relay off turns it off. In the terminal app, /relay on and /relay off work the same way, without the pill.";
120
+ export declare const checksLine: (checks: {
121
+ active: boolean;
122
+ note: string | null;
123
+ }) => string;
124
+ export {};
@@ -0,0 +1,189 @@
1
+ import { modelName } from './relay-store.js';
2
+ import { modeLabel } from './router.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';
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:`.
6
+ const usd = (value) => value === null ? 'not listed' : `$${value}`;
7
+ /** A listed price of 0 can mean free or not known, so it is never called free. */
8
+ export function priceLabel(cost) {
9
+ const { inputPerMillion: input, outputPerMillion: output } = cost;
10
+ if (input === null && output === null)
11
+ return 'price not listed';
12
+ if (input === '0' && output === '0')
13
+ return '$0 or not listed';
14
+ return `${usd(input)} in / ${usd(output)} out per 1M tokens${cost.tiered ? ' (base tier)' : ''}`;
15
+ }
16
+ const exact = (value) => { if (value === null)
17
+ return null; try {
18
+ return parseUsd(value);
19
+ }
20
+ catch {
21
+ return null;
22
+ } };
23
+ const known = (a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1;
24
+ /** For the "Add a model" menu: the input price, then the output price, compared exactly; a price not listed sorts last. "$0 or not listed" counts as $0. */
25
+ export function cheapestFirst(a, b) {
26
+ return known(exact(a.cost.inputPerMillion), exact(b.cost.inputPerMillion)) || known(exact(a.cost.outputPerMillion), exact(b.cost.outputPerMillion)) || a.name.localeCompare(b.name);
27
+ }
28
+ /** A price in the model table, whose column header says it is per 1M tokens, input / output. */
29
+ export function priceCell(cost) {
30
+ const { inputPerMillion: input, outputPerMillion: output } = cost;
31
+ if (input === null && output === null)
32
+ return 'not listed';
33
+ if (input === '0' && output === '0')
34
+ return '$0 or not listed';
35
+ return `${usd(input)} / ${usd(output)}${cost.tiered ? ' (base tier)' : ''}`;
36
+ }
37
+ /** A context window the way people say it: 8K, 200K, 1M. Zero means the catalog does not list it, shown as a dash (the cell says why). */
38
+ export function contextLabel(tokens) {
39
+ if (!(tokens > 0))
40
+ return '—';
41
+ if (tokens < 1000)
42
+ return String(tokens);
43
+ const thousands = Math.round(tokens / 1000);
44
+ return thousands < 1000 ? `${thousands}K` : `${+(tokens / 1_000_000).toFixed(1)}M`;
45
+ }
46
+ /** An intelligence index as the table shows it: one decimal at most, and a dash when no index was found for the model. */
47
+ export const indexLabel = (index) => index === null || index === undefined ? '—' : String(Math.round(index * 10) / 10);
48
+ const orders = {
49
+ provider: (a, b) => a.providerID.localeCompare(b.providerID) || a.name.localeCompare(b.name),
50
+ price: cheapestFirst,
51
+ context: (a, b) => b.limit.context - a.limit.context || a.name.localeCompare(b.name),
52
+ index: (a, b) => (b.index ?? -1) - (a.index ?? -1) || a.name.localeCompare(b.name),
53
+ };
54
+ /** The rows of the "Add a model" table: models with every typed word in their provider, id or name, of one provider when one is chosen, in the order chosen. */
55
+ export function modelRows(models, view) {
56
+ const words = view.query.toLowerCase().split(/\s+/).filter(Boolean);
57
+ return models.filter(model => (!view.provider || model.providerID === view.provider) && words.every(word => `${model.providerID} ${model.id} ${model.name}`.toLowerCase().includes(word))).sort(orders[view.order]);
58
+ }
59
+ /** What "Add" puts in a mode's list for this model: the default effort when it is not in the list yet, else the first effort that is not; undefined when every one is. */
60
+ export function nextEffort(chosen, model) {
61
+ return [null, ...model.variants].find(variant => !chosen.some(choice => choice.providerID === model.providerID && choice.id === model.id && choice.variant === variant));
62
+ }
63
+ const percent = (value) => `${Math.round(value * 100)}%`;
64
+ const facts = (item, model) => [modeLabel(item.mode), model, ...(item.confidence === null ? [] : [`${percent(item.confidence)} sure`]), ...(item.fit === null ? [] : [`line fit ${percent(item.fit)}`]), `${Math.round(item.ms)} ms`].join(', ');
65
+ const noted = (text, note) => `${text}${note === null ? '' : ` (${note})`}.`;
66
+ /** What one decision did. A chat or helper that stayed on its own model is said to be left alone. */
67
+ const outcome = (decision) => {
68
+ const { mode, model } = decision;
69
+ return mode !== null && model !== null ? facts({ ...decision, mode }, model) : decision.kind === 'helper' ? 'left as it was' : 'nothing switched';
70
+ };
71
+ /** The newest decision as one line, with the reason when nothing was switched. */
72
+ export function decisionLine(decision) {
73
+ if (!decision)
74
+ return 'No /relay message yet.';
75
+ return noted(`Last choice${decision.kind === 'helper' ? ' (a helper)' : ''}: ${outcome(decision)}`, decision.note);
76
+ }
77
+ const amount = (tokens) => Math.round(tokens).toLocaleString('en-US');
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
+ };
96
+ /** One row of Recent choices. The time is left out: the panel shows it in the viewer's own clock. */
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
+ }
133
+ /** What the test box shows for one try: what Relay would do with the sample message. */
134
+ export function tryLine(result) {
135
+ const { mode } = result;
136
+ if (mode === null)
137
+ return noted('No answer', result.note);
138
+ return noted(`${facts({ ...result, mode }, result.model ?? 'no model')}, cost ${result.costUsd === null ? 'not reported' : `$${result.costUsd}`}`, result.note);
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;
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. */
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.`;
153
+ /**
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
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.
156
+ */
157
+ // shortcut: the record keeps the model as "provider/id#variant", so an id that itself holds a "#" and has no variant is cut at that "#".
158
+ export function pickerModel(decision) {
159
+ if (decision.kind !== 'chat' || decision.model === null)
160
+ return null;
161
+ const slash = decision.model.indexOf('/');
162
+ if (slash <= 0)
163
+ return null;
164
+ const rest = decision.model.slice(slash + 1), hash = rest.lastIndexOf('#');
165
+ const modelID = hash < 0 ? rest : rest.slice(0, hash), variant = hash < 0 ? undefined : rest.slice(hash + 1);
166
+ if (!modelID || variant === '')
167
+ return null;
168
+ return { providerID: decision.model.slice(0, slash), modelID, ...(variant === undefined ? {} : { variant }) };
169
+ }
170
+ export const noDeciderNote = "No decider chosen. Until you choose one below, /relay and Relay on send every message to the chat's current model without switching.";
171
+ /**
172
+ * The pill above a chat box: whether every message in that chat goes through Relay, the row that turns it, and the chat's last choice.
173
+ * With no decider chosen Relay switches nothing, so the pill says so; switched on, its capsule says it too, with a warning icon.
174
+ */
175
+ export function pillView(state) {
176
+ const { on, last, decider } = state, unswitched = last !== null && last.model === null, warn = on && !decider;
177
+ return {
178
+ label: on ? (decider ? 'Relay on' : 'Relay on · no decider') : 'Relay off',
179
+ ...(warn ? { icon: 'circle-exclamation' } : {}),
180
+ tone: warn ? 'warning' : on ? 'success' : undefined,
181
+ rows: [
182
+ { id: 'toggle', label: on ? 'Turn Relay off for this chat' : 'Turn Relay on for this chat' },
183
+ ...(decider ? [] : [{ id: 'decider', label: 'No decider chosen, so Relay switches nothing. Open Relay to choose one.', tone: 'warning' }]),
184
+ { id: 'last', label: last === null ? 'No choice in this chat yet.' : decisionLine(last), ...(unswitched ? { tone: 'warning' } : {}) },
185
+ ],
186
+ };
187
+ }
188
+ export const switchHint = 'To send every message in one chat through Relay, type /relay on in that chat or use the Relay pill above its chat box; /relay off turns it off. In the terminal app, /relay on and /relay off work the same way, without the pill.';
189
+ export const checksLine = (checks) => checks.active ? 'Helpers that check work start on a Review model.' : `Helpers that check work keep the chat's model: ${checks.note ?? 'not set up'}.`;
@@ -0,0 +1,8 @@
1
+ import type { RelayDeps } from './relay-command.js';
2
+ type ToolCall = {
3
+ tool: string;
4
+ sessionID: string;
5
+ input: unknown;
6
+ };
7
+ export declare function reviewHelperHook(deps: Pick<RelayDeps, 'store' | 'chatModels' | 'decide' | 'readMs' | 'session'>): (event: ToolCall) => Promise<void>;
8
+ export {};
@@ -0,0 +1,68 @@
1
+ import { LATE, within } from './decider.js';
2
+ import { getRelaySettings, hostVariant, modelName, recordDecision } from './relay-store.js';
3
+ import { brief, candidates, checksStatus, choose, linesFor, reviewRules, sizesFor, UNSURE_BELOW } from './router.js';
4
+ import { readStored, standingsOf } from './standings.js';
5
+ const nothingAttached = { needsImage: false, tokens: 0 };
6
+ const given = (value) => value !== undefined && value !== null && value !== '';
7
+ export function reviewHelperHook(deps) {
8
+ const readMs = deps.readMs ?? 5000;
9
+ /** For Relay's own choice only: what fails or takes more than half the time counts as unknown, and the helper is placed all the same. */
10
+ const spare = async (work) => {
11
+ try {
12
+ const value = await within(work, Math.min(readMs / 2, 1000));
13
+ return value === LATE ? null : value;
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ };
19
+ /** The calling chat's model wrote the work a check looks at, so no reviewer weaker than it is chosen (src/ranking.ts). */
20
+ const writerOf = async (sessionID) => {
21
+ const chat = await deps.session.get({ sessionID: sessionID });
22
+ return chat.model ? { providerID: chat.model.providerID, id: chat.model.id, variant: hostVariant(chat.model.variant) } : null;
23
+ };
24
+ /** The record is for the panel; losing it must never fail a helper. */
25
+ const record = async (sessionID, fields) => {
26
+ try {
27
+ await recordDecision(deps.store, { at: new Date().toISOString(), sessionID, kind: 'helper', mode: null, confidence: null, fit: null, model: null, ms: 0, costUsd: null, note: null, ...fields });
28
+ }
29
+ catch { /* not recorded */ }
30
+ };
31
+ return async (event) => {
32
+ if (event.tool !== 'subagent')
33
+ return;
34
+ try {
35
+ const input = event.input;
36
+ // A call that continues an earlier helper keeps that helper as it was.
37
+ if (!input || typeof input !== 'object' || typeof input.prompt !== 'string' || !input.prompt.trim() || given(input.sessionID))
38
+ return;
39
+ const read = await within(() => Promise.all([getRelaySettings(deps.store), deps.chatModels(), spare(() => readStored(deps.store)), spare(() => writerOf(event.sessionID))]), readMs);
40
+ if (read === LATE)
41
+ throw new Error(`did not answer within ${readMs / 1000} seconds`);
42
+ const [settings, models, stored, writer] = read;
43
+ if (!checksStatus(settings, models).active)
44
+ return;
45
+ const lines = linesFor(settings, models, nothingAttached).review;
46
+ const standings = stored === null ? null : standingsOf(stored, models, [...settings.modes.review, ...(writer ? [writer] : [])]);
47
+ const sizes = sizesFor(settings, models, nothingAttached, writer, standings).filter(mode => mode === 'review');
48
+ const answer = await deps.decide(settings.decider, { kind: 'helper', text: input.prompt, agent: null, files: [], images: 0, lines: lines ? { review: lines } : {}, sizes });
49
+ if (answer.kind === 'none')
50
+ return await record(event.sessionID, { ms: answer.ms, note: answer.reason });
51
+ const decided = { mode: answer.mode, confidence: answer.confidence, ms: answer.ms, costUsd: answer.costUsd };
52
+ if (answer.mode !== 'review')
53
+ return await record(event.sessionID, { ...decided, note: 'not a check' });
54
+ if (answer.confidence < UNSURE_BELOW)
55
+ return await record(event.sessionID, { ...decided, note: 'not sure it is a check' });
56
+ // A helper has no model of its own to keep, so with no clear line, or no clear size, the first usable Review model is used.
57
+ const usable = candidates('review', settings.modes.review, models, nothingAttached).usable;
58
+ const picked = choose('review', settings.modes.review, usable, answer, standings, writer), model = modelName(picked.model);
59
+ event.input = { ...input, model, prompt: `${input.prompt}\n\n${reviewRules}` };
60
+ const asked = typeof input.model === 'string' && input.model.trim() !== model ? `its caller asked for ${input.model.trim()}` : null;
61
+ const notes = [asked, picked.note].filter(Boolean);
62
+ await record(event.sessionID, { ...decided, model, fit: picked.fit, note: notes.length ? notes.join('; ') : null });
63
+ }
64
+ catch (error) {
65
+ await record(event.sessionID, { note: `helper left alone: ${brief(error)}` });
66
+ }
67
+ };
68
+ }
@@ -0,0 +1,122 @@
1
+ import { type ModelChoice, type OfferedModel } from './settings.js';
2
+ import { type Decision, type Mode, type ModeChoice, type RelaySettings } from './relay-store.js';
3
+ import type { ModelCostView } from './inventory.js';
4
+ import { type SizeAnswer, type Standings } from './ranking.js';
5
+ /** The error's own message when it has one, so a person sees why something was refused; else the fallback. */
6
+ export declare function describeError(error: unknown, fallback: string): string;
7
+ /** Below this the decider is not sure of the mode, and the mode is Plan. */
8
+ export declare const UNSURE_BELOW = 0.6;
9
+ /** Below this the decider is not sure of the line, and no line counts as chosen. */
10
+ export declare const LINE_UNSURE_BELOW = 0.5;
11
+ export declare const MAX_LINES = 8;
12
+ export declare const REVIEW_RULES_KEY = "relay-review-rules";
13
+ export declare const reviewRules: string;
14
+ export declare const modeLabel: (mode: Mode) => "Plan" | "Execute" | "Review";
15
+ /** Cuts text to at most `max` characters without ending inside a two-unit character (a surrogate pair). */
16
+ export declare function safeHead(text: string, max: number): string;
17
+ /** A failure's message as part of a note: one line, at most 200 characters. */
18
+ export declare const brief: (error: unknown) => string;
19
+ /** The decider's answer about one mode's lines. `index` points into `described(usable)`; null means it chose "none of these". */
20
+ export type LineAnswer = {
21
+ index: number | null;
22
+ confidence: number;
23
+ };
24
+ /** `sizes` holds the decider's answer about how big the work is, for the modes Relay chooses for by itself (src/ranking.ts). */
25
+ export type DeciderAnswer = {
26
+ kind: 'answer';
27
+ mode: Mode;
28
+ confidence: number;
29
+ lines: Partial<Record<Mode, LineAnswer>>;
30
+ sizes?: Partial<Record<Mode, SizeAnswer>>;
31
+ ms: number;
32
+ costUsd: string | null;
33
+ } | {
34
+ kind: 'none';
35
+ reason: string;
36
+ ms: number;
37
+ };
38
+ export type RoutableModel = OfferedModel & {
39
+ capabilities: {
40
+ input: readonly string[];
41
+ };
42
+ limit: {
43
+ context: number;
44
+ };
45
+ cost?: ModelCostView;
46
+ };
47
+ /** What is known of a chat: its size in tokens, and each model's latest answer in it, newest first, with the chat's size then and how long ago its request began. */
48
+ export type ChatFacts = {
49
+ tokens: number;
50
+ answered: readonly {
51
+ providerID: string;
52
+ id: string;
53
+ tokens: number;
54
+ agoMs: number;
55
+ }[];
56
+ };
57
+ /**
58
+ * What comes with the message: whether a picture does, and about how many tokens the attached files take. For a message that goes to a chat
59
+ * also what is known of that chat (null when it could not be read) and Relay's earlier records, for the usual number of requests.
60
+ */
61
+ export type Attachment = {
62
+ needsImage: boolean;
63
+ tokens: number;
64
+ chat?: ChatFacts | null;
65
+ past?: readonly Pick<Decision, 'mode' | 'model' | 'reply'>[];
66
+ };
67
+ export type RouteResult = {
68
+ switch: true;
69
+ mode: Mode;
70
+ agent: 'plan' | 'build';
71
+ model: ModelChoice;
72
+ fit: number | null;
73
+ note: string | null;
74
+ } | {
75
+ switch: false;
76
+ mode: Mode | null;
77
+ note: string;
78
+ };
79
+ /** The models of one mode's list that can be used now, in the person's order. When none can, the note says why. `current` is the model the chat is on, when that is known. */
80
+ export declare function candidates(mode: Mode, list: readonly ModeChoice[], models: readonly RoutableModel[], attachment: Attachment, current?: ModelChoice | null): {
81
+ usable: ModeChoice[];
82
+ note: string | null;
83
+ };
84
+ /** The usable models the decider is asked about: those with a line, at most eight. A line answer's index points into this list. */
85
+ export declare const described: (usable: readonly ModeChoice[]) => ModeChoice[];
86
+ /** The lines to ask about, for each mode where there is a choice to make: two or more usable models, and at least one line. */
87
+ export declare function linesFor(settings: Pick<RelaySettings, 'modes'>, models: readonly RoutableModel[], attachment: Attachment, current?: ModelChoice | null): Partial<Record<Mode, string[]>>;
88
+ /**
89
+ * One model out of a mode's usable ones (never empty). When no line fits clearly, the first model of the list is used, whatever the chat is
90
+ * on: the person's order is the default (the owner, 19 Nov). A short follow-up such as "Implement it." fits no line, and keeping the chat's
91
+ * model kept the plan's dearer model for all the work (docs/compatibility.md, 19 Nov). The cost check after this can still keep the chat's model.
92
+ */
93
+ export declare function pickModel(usable: readonly ModeChoice[], line: LineAnswer | undefined): {
94
+ model: ModelChoice;
95
+ fit: number | null;
96
+ note: string | null;
97
+ };
98
+ /**
99
+ * One model out of a mode's usable ones. With no line in the mode's list and two or more usable models, Relay chooses by itself
100
+ * (src/ranking.ts): big work goes to the highest index, small work to the cheapest, and an unsure size to the highest index, since unclear
101
+ * work counts as big (the owner, 25 Nov). The first model is used when Relay can't rank the list or the decider gives no size (19 Nov). Otherwise the decider's line decides, as `pickModel` says.
102
+ * `standings` undefined keeps that older rule for every mode; null means the stored copies could not be read in time.
103
+ */
104
+ export declare function choose(mode: Mode, list: readonly ModeChoice[], usable: readonly ModeChoice[], answer: Extract<DeciderAnswer, {
105
+ kind: 'answer';
106
+ }>, standings: Standings | null | undefined, writer: ModelChoice | null): {
107
+ model: ModelChoice;
108
+ fit: number | null;
109
+ note: string | null;
110
+ };
111
+ /** The modes whose size the decider is asked: those Relay ranks by itself, where the strongest is not also the cheapest. */
112
+ export declare function sizesFor(settings: Pick<RelaySettings, 'modes'>, models: readonly RoutableModel[], attachment: Attachment, current: ModelChoice | null, standings: Standings | null): Mode[];
113
+ /**
114
+ * `unsure` says what an answer under UNSURE_BELOW means: Plan for `/relay`, no change for a chat whose switch is on. `standings` lets Relay
115
+ * choose by itself in a mode with no lines (see `choose`); left out, every mode follows its lines as before.
116
+ */
117
+ export declare function route(answer: DeciderAnswer, settings: Pick<RelaySettings, 'modes'>, models: readonly RoutableModel[], attachment: Attachment, current: ModelChoice | null, unsure?: 'plan' | 'stay', standings?: Standings | null): RouteResult;
118
+ /** Whether a helper that checks work can be given a Review model at all, and if not, why. */
119
+ export declare function checksStatus(settings: Pick<RelaySettings, 'modes' | 'decider'>, models: readonly RoutableModel[]): {
120
+ active: boolean;
121
+ note: string | null;
122
+ };