relay-opencode 0.0.0-stage → 0.1.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.
@@ -0,0 +1,111 @@
1
+ import { offered, validateChoices } from './settings.js';
2
+ // What Relay keeps in plugin storage. The host shares plugin storage between projects, so there is one set of settings and one list of decisions.
3
+ // shortcut: one queue for this loaded module, so its own reads and writes never interleave. A second process writing the same keys is not
4
+ // 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.
5
+ let queue = Promise.resolve();
6
+ function serial(task) {
7
+ const result = queue.then(task);
8
+ queue = result.then(() => undefined, () => undefined);
9
+ return result;
10
+ }
11
+ export const modes = ['plan', 'execute', 'review'];
12
+ export const USE_FOR_MAX = 200;
13
+ const SETTINGS = 'relay/settings', DECISIONS = 'relay/decisions', KEEP = 20;
14
+ const same = (a, b) => a.providerID === b.providerID && a.id === b.id && a.variant === b.variant;
15
+ export const modelName = (choice) => `${choice.providerID}/${choice.id}${choice.variant === null ? '' : `#${choice.variant}`}`;
16
+ function entries(value) {
17
+ if (!Array.isArray(value))
18
+ throw new Error('Invalid mode choices');
19
+ const parts = value.map(item => {
20
+ if (!item || typeof item !== 'object' || Array.isArray(item))
21
+ throw new Error('Invalid model choice');
22
+ const { useFor = '', ...choice } = item;
23
+ if (typeof useFor !== 'string')
24
+ throw new Error('Invalid "use it for" line');
25
+ const line = useFor.replace(/\s+/g, ' ').trim();
26
+ if (line.length > USE_FOR_MAX)
27
+ throw new Error(`A "use it for" line can have at most ${USE_FOR_MAX} characters`);
28
+ return { choice, line };
29
+ });
30
+ return validateChoices(parts.map(part => part.choice)).map((choice, index) => ({ ...choice, useFor: parts[index].line }));
31
+ }
32
+ function shape(value, keys) {
33
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== keys)
34
+ throw new Error('Invalid Relay settings');
35
+ const { modes: lists, decider } = value;
36
+ if (!lists || typeof lists !== 'object' || Array.isArray(lists) || Object.keys(lists).sort().join(',') !== 'execute,plan,review')
37
+ throw new Error('Invalid modes');
38
+ return { modes: { plan: entries(lists.plan), execute: entries(lists.execute), review: entries(lists.review) }, decider: decider === null ? null : validateChoices([decider])[0] };
39
+ }
40
+ function decode(value) {
41
+ if (value === undefined)
42
+ return { revision: 0, modes: { plan: [], execute: [], review: [] }, decider: null };
43
+ const revision = value?.revision;
44
+ if (typeof revision !== 'number' || !Number.isSafeInteger(revision) || revision < 0)
45
+ throw new Error('Invalid Relay settings');
46
+ return { revision, ...shape(value, 'decider,modes,revision') };
47
+ }
48
+ export function getRelaySettings(store) { return serial(async () => decode(await store.get(SETTINGS))); }
49
+ /** 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. */
50
+ export function saveRelaySettings(store, revision, input, chatModels, decisionModels) {
51
+ return serial(async () => {
52
+ const next = shape(input, 'decider,modes'), raw = await store.get(SETTINGS), previous = decode(raw);
53
+ if (!Number.isSafeInteger(revision) || revision !== previous.revision || revision === Number.MAX_SAFE_INTEGER)
54
+ throw new Error('Stale settings revision');
55
+ for (const mode of modes)
56
+ for (const choice of next.modes[mode]) {
57
+ if (!previous.modes[mode].some(old => same(old, choice)) && !offered(chatModels, choice))
58
+ throw new Error('Selected model or variant is unavailable');
59
+ }
60
+ if (next.decider && !(previous.decider && same(previous.decider, next.decider)) && !offered(decisionModels, next.decider))
61
+ throw new Error('The decider must be a decision model that is offered');
62
+ const saved = { revision: revision + 1, ...next };
63
+ if (typeof store.compareAndSet === 'function') {
64
+ const updated = await store.compareAndSet(SETTINGS, raw, saved);
65
+ if (updated === false)
66
+ throw new Error('Stale settings revision');
67
+ if (updated !== true)
68
+ throw new Error('Invalid compare-and-set response');
69
+ }
70
+ else
71
+ await store.set(SETTINGS, saved);
72
+ return structuredClone(saved);
73
+ });
74
+ }
75
+ /** A stored record as the panel may show it, or null when it cannot be read. A field this version does not know is dropped, and a missing one reads as unknown. */
76
+ function readable(value) {
77
+ const item = value;
78
+ if (!item || typeof item !== 'object' || typeof item.at !== 'string' || typeof item.sessionID !== 'string' || (item.kind !== 'chat' && item.kind !== 'helper') || typeof item.ms !== 'number')
79
+ return null;
80
+ const number = (field) => typeof field === 'number' && Number.isFinite(field) ? field : null, text = (field) => typeof field === 'string' ? field : null;
81
+ const took = (item.reply && typeof item.reply === 'object' ? item.reply : {}), requests = number(took.requests), fresh = number(took.fresh), cached = number(took.cached);
82
+ const reply = requests === null || fresh === null || cached === null ? null : { requests, fresh, cached, costUsd: text(took.costUsd), seconds: number(took.seconds) };
83
+ return { at: item.at, sessionID: item.sessionID, kind: item.kind, mode: modes.find(mode => mode === item.mode) ?? null, confidence: number(item.confidence), fit: number(item.fit), model: text(item.model), ms: item.ms, costUsd: text(item.costUsd), note: text(item.note), messageID: text(item.messageID), reply };
84
+ }
85
+ const stored = async (store) => {
86
+ const value = await store.get(DECISIONS);
87
+ return Array.isArray(value) ? value.map(readable).filter(item => item !== null) : [];
88
+ };
89
+ /** A new record has no reply yet; one made for a message of a chat names that message. */
90
+ export function recordDecision(store, decision) {
91
+ // shortcut: one stored list. Two project folders deciding in the same instant can lose one record; give each record its own key if that ever matters.
92
+ return serial(async () => store.set(DECISIONS, [...await stored(store), { messageID: null, ...decision, reply: null }].slice(-KEEP)));
93
+ }
94
+ const waits = (item, sessionID) => item.sessionID === sessionID && item.messageID !== null && item.reply === null;
95
+ /** The messages of one chat whose records still wait for what the reply took. */
96
+ export function waitingReplies(store, sessionID) {
97
+ return serial(async () => (await stored(store)).flatMap(item => waits(item, sessionID) ? [item.messageID] : []));
98
+ }
99
+ /** Keeps what the replies took, by message, with the records of one chat that still wait for it. A reply that was kept once is not replaced. */
100
+ // shortcut: a record whose reply can never be read (an answer that was stopped, a message that was taken back or compacted away before
101
+ // its reply was read) waits until it leaves the list of 20, so its chat is read once more each time it goes idle.
102
+ export function saveReplies(store, sessionID, replies) {
103
+ return serial(async () => store.set(DECISIONS, (await stored(store)).map(item => waits(item, sessionID) ? { ...item, reply: replies.get(item.messageID) ?? null } : item)));
104
+ }
105
+ /** Newest first, at most 20. */
106
+ export function recentDecisions(store) { return serial(async () => (await stored(store)).reverse()); }
107
+ // The switch: whether every message in one chat goes through Relay. One key per chat, so turning it on or off is one write and needs no queue.
108
+ const switchKey = (sessionID) => `relay/on/${encodeURIComponent(sessionID)}`;
109
+ /** Only a stored `true` counts as on. */
110
+ export async function chatSwitch(store, sessionID) { return (await store.get(switchKey(sessionID))) === true; }
111
+ export function setChatSwitch(store, sessionID, on) { return store.set(switchKey(sessionID), on); }
@@ -0,0 +1,88 @@
1
+ import type { ModelCostView } from './inventory.js';
2
+ import type { Decision, Reply } 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
+ /** What the test box shows for one try: what Relay would do with the sample message. */
51
+ export declare function tryLine(result: Shown & Pick<Decision, 'costUsd'>): string;
52
+ /** What leaves the machine to make a choice, and to whom. It names everything `describe` in `decider.ts` puts in a request, with that file's own limits. */
53
+ export declare const privacyNote: (providerID: string | null) => string;
54
+ /**
55
+ * 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
56
+ * 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.
57
+ */
58
+ export declare function pickerModel(decision: Pick<Decision, 'kind' | 'model'>): {
59
+ providerID: string;
60
+ modelID: string;
61
+ variant?: string;
62
+ } | null;
63
+ 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.";
64
+ type PillRow = {
65
+ id: 'toggle' | 'decider' | 'last';
66
+ label: string;
67
+ tone?: 'warning';
68
+ };
69
+ /**
70
+ * 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.
71
+ * With no decider chosen Relay switches nothing, so the pill says so; switched on, its capsule says it too, with a warning icon.
72
+ */
73
+ export declare function pillView(state: {
74
+ on: boolean;
75
+ last: (Shown & Pick<Decision, 'kind'>) | null;
76
+ decider: boolean;
77
+ }): {
78
+ label: string;
79
+ icon?: 'circle-exclamation';
80
+ tone: 'success' | 'warning' | undefined;
81
+ rows: PillRow[];
82
+ };
83
+ 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.";
84
+ export declare const checksLine: (checks: {
85
+ active: boolean;
86
+ note: string | null;
87
+ }) => string;
88
+ export {};
@@ -0,0 +1,129 @@
1
+ import { modeLabel } from './router.js';
2
+ import { MAX_CHARS, MAX_FILE_NAMES } from './decider.js';
3
+ import { parseUsd } from './costs.js';
4
+ // What the Modes tab says in words. Pure, so it runs under node:test; the panel bundles it, so nothing here may import from `node:`.
5
+ const usd = (value) => value === null ? 'not listed' : `$${value}`;
6
+ /** A listed price of 0 can mean free or not known, so it is never called free. */
7
+ export function priceLabel(cost) {
8
+ const { inputPerMillion: input, outputPerMillion: output } = cost;
9
+ if (input === null && output === null)
10
+ return 'price not listed';
11
+ if (input === '0' && output === '0')
12
+ return '$0 or not listed';
13
+ return `${usd(input)} in / ${usd(output)} out per 1M tokens${cost.tiered ? ' (base tier)' : ''}`;
14
+ }
15
+ const exact = (value) => { if (value === null)
16
+ return null; try {
17
+ return parseUsd(value);
18
+ }
19
+ catch {
20
+ return null;
21
+ } };
22
+ const known = (a, b) => a === b ? 0 : a === null ? 1 : b === null ? -1 : a < b ? -1 : 1;
23
+ /** 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. */
24
+ export function cheapestFirst(a, b) {
25
+ return known(exact(a.cost.inputPerMillion), exact(b.cost.inputPerMillion)) || known(exact(a.cost.outputPerMillion), exact(b.cost.outputPerMillion)) || a.name.localeCompare(b.name);
26
+ }
27
+ /** A price in the model table, whose column header says it is per 1M tokens, input / output. */
28
+ export function priceCell(cost) {
29
+ const { inputPerMillion: input, outputPerMillion: output } = cost;
30
+ if (input === null && output === null)
31
+ return 'not listed';
32
+ if (input === '0' && output === '0')
33
+ return '$0 or not listed';
34
+ return `${usd(input)} / ${usd(output)}${cost.tiered ? ' (base tier)' : ''}`;
35
+ }
36
+ /** 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). */
37
+ export function contextLabel(tokens) {
38
+ if (!(tokens > 0))
39
+ return '—';
40
+ if (tokens < 1000)
41
+ return String(tokens);
42
+ const thousands = Math.round(tokens / 1000);
43
+ return thousands < 1000 ? `${thousands}K` : `${+(tokens / 1_000_000).toFixed(1)}M`;
44
+ }
45
+ /** An intelligence index as the table shows it: one decimal at most, and a dash when no index was found for the model. */
46
+ export const indexLabel = (index) => index === null || index === undefined ? '—' : String(Math.round(index * 10) / 10);
47
+ const orders = {
48
+ provider: (a, b) => a.providerID.localeCompare(b.providerID) || a.name.localeCompare(b.name),
49
+ price: cheapestFirst,
50
+ context: (a, b) => b.limit.context - a.limit.context || a.name.localeCompare(b.name),
51
+ index: (a, b) => (b.index ?? -1) - (a.index ?? -1) || a.name.localeCompare(b.name),
52
+ };
53
+ /** 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. */
54
+ export function modelRows(models, view) {
55
+ const words = view.query.toLowerCase().split(/\s+/).filter(Boolean);
56
+ 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]);
57
+ }
58
+ /** 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. */
59
+ export function nextEffort(chosen, model) {
60
+ return [null, ...model.variants].find(variant => !chosen.some(choice => choice.providerID === model.providerID && choice.id === model.id && choice.variant === variant));
61
+ }
62
+ const percent = (value) => `${Math.round(value * 100)}%`;
63
+ 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(', ');
64
+ const noted = (text, note) => `${text}${note === null ? '' : ` (${note})`}.`;
65
+ /** What one decision did. A chat or helper that stayed on its own model is said to be left alone. */
66
+ const outcome = (decision) => {
67
+ const { mode, model } = decision;
68
+ return mode !== null && model !== null ? facts({ ...decision, mode }, model) : decision.kind === 'helper' ? 'left as it was' : 'nothing switched';
69
+ };
70
+ /** The newest decision as one line, with the reason when nothing was switched. */
71
+ export function decisionLine(decision) {
72
+ if (!decision)
73
+ return 'No /relay message yet.';
74
+ return noted(`Last choice${decision.kind === 'helper' ? ' (a helper)' : ''}: ${outcome(decision)}`, decision.note);
75
+ }
76
+ const amount = (tokens) => Math.round(tokens).toLocaleString('en-US');
77
+ /** What the reply took, once it is known. A cost of 0 can mean "not listed", so it is left out, like a cost that was not reported. */
78
+ const took = (reply) => !reply ? '' : ` First request of the reply: ${[
79
+ `${amount(reply.fresh)} tokens read new`, `${amount(reply.cached)} from cache`,
80
+ ...(reply.costUsd === null || reply.costUsd === '0' ? [] : [`$${reply.costUsd}`]), ...(reply.seconds === null ? [] : [`first word after ${reply.seconds} s`]),
81
+ ].join(', ')}. Requests in the reply: ${reply.requests}.`;
82
+ /** One row of Recent choices. The time is left out: the panel shows it in the viewer's own clock. */
83
+ export const recentLine = (decision) => `${noted(`${decision.kind === 'helper' ? 'Helper' : 'Chat'}: ${outcome(decision)}`, decision.note)}${took(decision.reply)}`;
84
+ /** What the test box shows for one try: what Relay would do with the sample message. */
85
+ export function tryLine(result) {
86
+ const { mode } = result;
87
+ if (mode === null)
88
+ return noted('No answer', result.note);
89
+ return noted(`${facts({ ...result, mode }, result.model ?? 'no model')}, cost ${result.costUsd === null ? 'not reported' : `$${result.costUsd}`}`, result.note);
90
+ }
91
+ /** What leaves the machine to make a choice, and to whom. It names everything `describe` in `decider.ts` puts in a request, with that file's own limits. */
92
+ export const privacyNote = (providerID) => `To choose, Relay sends to ${providerID ?? "the decider's provider"}: your message text (at most ${MAX_CHARS.toLocaleString('en-US')} characters), the names and sizes of attached files (the first ${MAX_FILE_NAMES}), how many pictures are attached, whether the chat's agent can change files, and the lines you wrote above. Never the contents of files, pictures or earlier messages. While a decider and a Review model are chosen, the task text of each helper that a model starts is sent the same way — written by the calling model, so it may itself quote code, files or earlier chat, and the person does not see it before it goes out.`;
93
+ /**
94
+ * The model to put in Desktop's model picker after Relay switched a chat. Desktop sends the picker's model with every message (seen on
95
+ * 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.
96
+ */
97
+ // 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 "#".
98
+ export function pickerModel(decision) {
99
+ if (decision.kind !== 'chat' || decision.model === null)
100
+ return null;
101
+ const slash = decision.model.indexOf('/');
102
+ if (slash <= 0)
103
+ return null;
104
+ const rest = decision.model.slice(slash + 1), hash = rest.lastIndexOf('#');
105
+ const modelID = hash < 0 ? rest : rest.slice(0, hash), variant = hash < 0 ? undefined : rest.slice(hash + 1);
106
+ if (!modelID || variant === '')
107
+ return null;
108
+ return { providerID: decision.model.slice(0, slash), modelID, ...(variant === undefined ? {} : { variant }) };
109
+ }
110
+ 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.";
111
+ /**
112
+ * 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.
113
+ * With no decider chosen Relay switches nothing, so the pill says so; switched on, its capsule says it too, with a warning icon.
114
+ */
115
+ export function pillView(state) {
116
+ const { on, last, decider } = state, unswitched = last !== null && last.model === null, warn = on && !decider;
117
+ return {
118
+ label: on ? (decider ? 'Relay on' : 'Relay on · no decider') : 'Relay off',
119
+ ...(warn ? { icon: 'circle-exclamation' } : {}),
120
+ tone: warn ? 'warning' : on ? 'success' : undefined,
121
+ rows: [
122
+ { id: 'toggle', label: on ? 'Turn Relay off for this chat' : 'Turn Relay on for this chat' },
123
+ ...(decider ? [] : [{ id: 'decider', label: 'No decider chosen, so Relay switches nothing. Open Relay to choose one.', tone: 'warning' }]),
124
+ { id: 'last', label: last === null ? 'No choice in this chat yet.' : decisionLine(last), ...(unswitched ? { tone: 'warning' } : {}) },
125
+ ],
126
+ };
127
+ }
128
+ 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.';
129
+ 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'>): (event: ToolCall) => Promise<void>;
8
+ export {};
@@ -0,0 +1,49 @@
1
+ import { LATE, within } from './decider.js';
2
+ import { getRelaySettings, modelName, recordDecision } from './relay-store.js';
3
+ import { brief, candidates, checksStatus, linesFor, pickModel, reviewRules, UNSURE_BELOW } from './router.js';
4
+ const nothingAttached = { needsImage: false, tokens: 0 };
5
+ const given = (value) => value !== undefined && value !== null && value !== '';
6
+ export function reviewHelperHook(deps) {
7
+ const readMs = deps.readMs ?? 5000;
8
+ /** The record is for the panel; losing it must never fail a helper. */
9
+ const record = async (sessionID, fields) => {
10
+ try {
11
+ 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 });
12
+ }
13
+ catch { /* not recorded */ }
14
+ };
15
+ return async (event) => {
16
+ if (event.tool !== 'subagent')
17
+ return;
18
+ try {
19
+ const input = event.input;
20
+ // A call that continues an earlier helper keeps that helper as it was.
21
+ if (!input || typeof input !== 'object' || typeof input.prompt !== 'string' || !input.prompt.trim() || given(input.sessionID))
22
+ return;
23
+ const read = await within(() => Promise.all([getRelaySettings(deps.store), deps.chatModels()]), readMs);
24
+ if (read === LATE)
25
+ throw new Error(`did not answer within ${readMs / 1000} seconds`);
26
+ const [settings, models] = read;
27
+ if (!checksStatus(settings, models).active)
28
+ return;
29
+ const lines = linesFor(settings, models, nothingAttached).review;
30
+ const answer = await deps.decide(settings.decider, { kind: 'helper', text: input.prompt, agent: null, files: [], images: 0, lines: lines ? { review: lines } : {} });
31
+ if (answer.kind === 'none')
32
+ return await record(event.sessionID, { ms: answer.ms, note: answer.reason });
33
+ const decided = { mode: answer.mode, confidence: answer.confidence, ms: answer.ms, costUsd: answer.costUsd };
34
+ if (answer.mode !== 'review')
35
+ return await record(event.sessionID, { ...decided, note: 'not a check' });
36
+ if (answer.confidence < UNSURE_BELOW)
37
+ return await record(event.sessionID, { ...decided, note: 'not sure it is a check' });
38
+ // A helper has no model of its own to keep, so with no clear line the first usable Review model is used.
39
+ const picked = pickModel(candidates('review', settings.modes.review, models, nothingAttached).usable, answer.lines.review, null), model = modelName(picked.model);
40
+ event.input = { ...input, model, prompt: `${input.prompt}\n\n${reviewRules}` };
41
+ const asked = typeof input.model === 'string' && input.model.trim() !== model ? `its caller asked for ${input.model.trim()}` : null;
42
+ const notes = [asked, picked.note].filter(Boolean);
43
+ await record(event.sessionID, { ...decided, model, fit: picked.fit, note: notes.length ? notes.join('; ') : null });
44
+ }
45
+ catch (error) {
46
+ await record(event.sessionID, { note: `helper left alone: ${brief(error)}` });
47
+ }
48
+ };
49
+ }
@@ -0,0 +1,97 @@
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
+ /** The error's own message when it has one, so a person sees why something was refused; else the fallback. */
5
+ export declare function describeError(error: unknown, fallback: string): string;
6
+ /** Below this the decider is not sure of the mode, and the mode is Plan. */
7
+ export declare const UNSURE_BELOW = 0.6;
8
+ /** Below this the decider is not sure of the line, and no line counts as chosen. */
9
+ export declare const LINE_UNSURE_BELOW = 0.5;
10
+ export declare const MAX_LINES = 8;
11
+ export declare const REVIEW_RULES_KEY = "relay-review-rules";
12
+ export declare const reviewRules: string;
13
+ export declare const modeLabel: (mode: Mode) => "Plan" | "Execute" | "Review";
14
+ /** Cuts text to at most `max` characters without ending inside a two-unit character (a surrogate pair). */
15
+ export declare function safeHead(text: string, max: number): string;
16
+ /** A failure's message as part of a note: one line, at most 200 characters. */
17
+ export declare const brief: (error: unknown) => string;
18
+ /** The decider's answer about one mode's lines. `index` points into `described(usable)`; null means it chose "none of these". */
19
+ export type LineAnswer = {
20
+ index: number | null;
21
+ confidence: number;
22
+ };
23
+ export type DeciderAnswer = {
24
+ kind: 'answer';
25
+ mode: Mode;
26
+ confidence: number;
27
+ lines: Partial<Record<Mode, LineAnswer>>;
28
+ ms: number;
29
+ costUsd: string | null;
30
+ } | {
31
+ kind: 'none';
32
+ reason: string;
33
+ ms: number;
34
+ };
35
+ export type RoutableModel = OfferedModel & {
36
+ capabilities: {
37
+ input: readonly string[];
38
+ };
39
+ limit: {
40
+ context: number;
41
+ };
42
+ cost?: ModelCostView;
43
+ };
44
+ /** 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 it was. */
45
+ export type ChatFacts = {
46
+ tokens: number;
47
+ answered: readonly {
48
+ providerID: string;
49
+ id: string;
50
+ tokens: number;
51
+ agoMs: number;
52
+ }[];
53
+ };
54
+ /**
55
+ * 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
56
+ * 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.
57
+ */
58
+ export type Attachment = {
59
+ needsImage: boolean;
60
+ tokens: number;
61
+ chat?: ChatFacts | null;
62
+ past?: readonly Pick<Decision, 'mode' | 'model' | 'reply'>[];
63
+ };
64
+ export type RouteResult = {
65
+ switch: true;
66
+ mode: Mode;
67
+ agent: 'plan' | 'build';
68
+ model: ModelChoice;
69
+ fit: number | null;
70
+ note: string | null;
71
+ } | {
72
+ switch: false;
73
+ mode: Mode | null;
74
+ note: string;
75
+ };
76
+ /** 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. */
77
+ export declare function candidates(mode: Mode, list: readonly ModeChoice[], models: readonly RoutableModel[], attachment: Attachment, current?: ModelChoice | null): {
78
+ usable: ModeChoice[];
79
+ note: string | null;
80
+ };
81
+ /** The usable models the decider is asked about: those with a line, at most eight. A line answer's index points into this list. */
82
+ export declare const described: (usable: readonly ModeChoice[]) => ModeChoice[];
83
+ /** 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. */
84
+ export declare function linesFor(settings: Pick<RelaySettings, 'modes'>, models: readonly RoutableModel[], attachment: Attachment, current?: ModelChoice | null): Partial<Record<Mode, string[]>>;
85
+ /** One model out of a mode's usable ones (never empty). `current` is the model the chat is on, when that is known. */
86
+ export declare function pickModel(usable: readonly ModeChoice[], line: LineAnswer | undefined, current: ModelChoice | null): {
87
+ model: ModelChoice;
88
+ fit: number | null;
89
+ note: string | null;
90
+ };
91
+ /** `unsure` says what an answer under UNSURE_BELOW means: Plan for `/relay`, no change for a chat whose switch is on. */
92
+ export declare function route(answer: DeciderAnswer, settings: Pick<RelaySettings, 'modes'>, models: readonly RoutableModel[], attachment: Attachment, current: ModelChoice | null, unsure?: 'plan' | 'stay'): RouteResult;
93
+ /** Whether a helper that checks work can be given a Review model at all, and if not, why. */
94
+ export declare function checksStatus(settings: Pick<RelaySettings, 'modes' | 'decider'>, models: readonly RoutableModel[]): {
95
+ active: boolean;
96
+ note: string | null;
97
+ };