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,113 @@
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 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. */
93
+ export async function loadIndexTable(store, fetcher, now) {
94
+ let saved = null;
95
+ try {
96
+ saved = decodeCache(await store.get(CACHE_KEY));
97
+ }
98
+ catch { /* read as no copy */ }
99
+ if (saved && now - Date.parse(saved.fetchedAt) < DAY_MS)
100
+ return { table: fromRows(saved.rows), fetchedAt: saved.fetchedAt, note: null };
101
+ try {
102
+ const table = await fetchIndexTable(fetcher), fetchedAt = new Date(now).toISOString();
103
+ try {
104
+ await store.set(CACHE_KEY, { fetchedAt, rows: [...table].map(([key, found]) => [key, found.id, found.index]) });
105
+ }
106
+ catch { /* shown anyway, fetched again next time */ }
107
+ return { table, fetchedAt, note: null };
108
+ }
109
+ catch (error) {
110
+ const reason = error instanceof Error ? error.message : String(error);
111
+ 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}` };
112
+ }
113
+ }
@@ -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,20 @@
1
+ import type { PromptInput } from '@opencode/schema/prompt-input';
2
+ import { type RelayDeps } from './relay-command.js';
3
+ /** How long a chat may take to show it is idle before it counts as busy and is left as it is. */
4
+ export declare const BUSY_CHECK_MS = 300;
5
+ type PromptEvent = {
6
+ readonly sessionID: string;
7
+ readonly messageID?: string;
8
+ readonly prompt?: PromptInput.Prompt;
9
+ readonly metadata?: Record<string, unknown>;
10
+ };
11
+ export declare function relayAutoHook(deps: RelayDeps): (event: PromptEvent) => Promise<void>;
12
+ /**
13
+ * What a reply took. When a chat has finished its work, the host runs this just before the chat goes idle. For each record of that chat
14
+ * that still waits, the reply is read from the chat's own messages and kept with the record. No model is asked. It never throws, and it
15
+ * holds the chat for one second at most; a chat with no waiting record costs one read of storage.
16
+ */
17
+ export declare function relayReplyHook(deps: Pick<RelayDeps, 'session' | 'store' | 'readMs'>): (event: {
18
+ readonly sessionID: string;
19
+ }) => Promise<void>;
20
+ export {};
@@ -0,0 +1,54 @@
1
+ import { within } from './decider.js';
2
+ import { replyOf } from './chat-facts.js';
3
+ import { placeMessage, recordPlaced, timingOf, uploadsOf } from './relay-command.js';
4
+ import { chatSwitch, saveReplies, waitingReplies } from './relay-store.js';
5
+ // The switch. In a chat where `/relay on` (or the pill) turned it on, every message the person sends is placed the way `/relay` places one,
6
+ // inside the host's `prompt` hook, before the message goes out (a switch made there serves that message: probe, 16 Nov). The host sends the
7
+ // message; this never does. It never throws, because a throw fails the person's message; what goes wrong becomes a note in the record.
8
+ /** How long a chat may take to show it is idle before it counts as busy and is left as it is. */
9
+ export const BUSY_CHECK_MS = 300;
10
+ export function relayAutoHook(deps) {
11
+ const timing = { ...timingOf(deps), waitMs: BUSY_CHECK_MS };
12
+ // The switch is read for every message in every chat, so a slow store must not hold them all for long.
13
+ const flagMs = Math.min(timing.readMs, 1000);
14
+ return async (event) => {
15
+ try {
16
+ // `/relay` placed this message already and marked its send.
17
+ if (event.metadata?.relay !== undefined || !event.prompt?.text?.trim())
18
+ return;
19
+ const sessionID = event.sessionID, prompt = event.prompt;
20
+ if (await within(() => chatSwitch(deps.store, sessionID), flagMs) !== true)
21
+ return;
22
+ // 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
23
+ // 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.
24
+ await within(async () => {
25
+ const placed = await placeMessage(deps, timing, { sessionID, prompt, unsure: 'stay', uploads: uploadsOf(event.metadata) });
26
+ // The record is for the panel; the message does not wait for it. recordPlaced never rejects.
27
+ void recordPlaced(deps, sessionID, placed, typeof event.messageID === 'string' ? event.messageID : null);
28
+ }, timing.readMs * 3);
29
+ }
30
+ catch { /* never fail the person's message */ }
31
+ };
32
+ }
33
+ /**
34
+ * What a reply took. When a chat has finished its work, the host runs this just before the chat goes idle. For each record of that chat
35
+ * that still waits, the reply is read from the chat's own messages and kept with the record. No model is asked. It never throws, and it
36
+ * holds the chat for one second at most; a chat with no waiting record costs one read of storage.
37
+ */
38
+ export function relayReplyHook(deps) {
39
+ const limitMs = Math.min(timingOf(deps).readMs, 1000);
40
+ return async (event) => {
41
+ try {
42
+ await within(async () => {
43
+ const waiting = await waitingReplies(deps.store, event.sessionID);
44
+ if (!waiting.length)
45
+ return;
46
+ const messages = await deps.session.context({ sessionID: event.sessionID });
47
+ const replies = new Map(waiting.flatMap(messageID => { const reply = replyOf(messages, messageID); return reply ? [[messageID, reply]] : []; }));
48
+ if (replies.size)
49
+ await saveReplies(deps.store, event.sessionID, replies);
50
+ }, limitMs);
51
+ }
52
+ catch { /* the record is for the panel; the chat goes idle whatever happens here */ }
53
+ };
54
+ }
@@ -0,0 +1,79 @@
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
+ /**
33
+ * A variant as the host reports it, in a choice's terms. The host names "no variant requested" `default` (seen on 2.2.7, even for a model that has
34
+ * no variants), while a choice uses `null`; compared raw, a chat on its default variant would never match a choice.
35
+ */
36
+ export declare const hostVariant: (variant: string | null | undefined) => string | null;
37
+ /** The host gives no type for an attached file, so a picture is told by its address or its name. */
38
+ export declare function isPicture(file: AttachedFile): boolean;
39
+ export type Upload = {
40
+ readonly name: string;
41
+ readonly mime: string;
42
+ readonly path: string;
43
+ };
44
+ /**
45
+ * 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
46
+ * file part (seen on 17 Nov). Only well-formed entries count; the metadata comes from the client.
47
+ */
48
+ export declare function uploadsOf(metadata: unknown): Upload[];
49
+ /** 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. */
50
+ export declare function localPath(uri: string): string | null;
51
+ export declare function fileSize(uri: string): Promise<number | null>;
52
+ export type Timing = {
53
+ readonly waitMs: number;
54
+ readonly sizeMs: number;
55
+ readonly readMs: number;
56
+ };
57
+ export type Placed = {
58
+ outcome: Pick<Decision, 'mode' | 'confidence' | 'fit' | 'model' | 'ms' | 'costUsd'>;
59
+ notes: string[];
60
+ };
61
+ export declare const timingOf: (deps: Pick<RelayDeps, "waitMs" | "sizeMs" | "readMs">) => Timing;
62
+ /**
63
+ * 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
64
+ * 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.
65
+ */
66
+ export declare function placeMessage(deps: RelayDeps, timing: Timing, input: {
67
+ readonly sessionID: Session.ID;
68
+ readonly prompt: PromptInput.Prompt;
69
+ readonly unsure: 'plan' | 'stay';
70
+ readonly uploads?: readonly Upload[];
71
+ }): Promise<Placed>;
72
+ /** 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. */
73
+ export declare function recordPlaced(deps: Pick<RelayDeps, 'store'>, sessionID: string, { outcome, notes }: Placed, messageID?: string | null): Promise<void>;
74
+ export declare function relayCommand(deps: RelayDeps): {
75
+ name: string;
76
+ description: string;
77
+ execute(input: Invocation): Promise<void>;
78
+ };
79
+ export {};
@@ -0,0 +1,209 @@
1
+ import { stat } from 'node:fs/promises';
2
+ import { fileURLToPath, pathToFileURL } from 'node:url';
3
+ import { LATE, within } from './decider.js';
4
+ import { chatFacts } from './chat-facts.js';
5
+ import { getRelaySettings, modelName, recentDecisions, recordDecision, setChatSwitch } from './relay-store.js';
6
+ import { brief, linesFor, REVIEW_RULES_KEY, reviewRules, route } from './router.js';
7
+ /**
8
+ * A variant as the host reports it, in a choice's terms. The host names "no variant requested" `default` (seen on 2.2.7, even for a model that has
9
+ * no variants), while a choice uses `null`; compared raw, a chat on its default variant would never match a choice.
10
+ */
11
+ // shortcut: a model with a real variant literally named `default` is treated as having none, because the host reports both the same way.
12
+ export const hostVariant = (variant) => (variant === undefined || variant === 'default' ? null : variant);
13
+ const PICTURE = /\.(png|jpe?g|gif|webp|bmp)$/i;
14
+ const bare = (uri) => uri.replace(/[?#].*$/, '');
15
+ /** The host gives no type for an attached file, so a picture is told by its address or its name. */
16
+ export function isPicture(file) {
17
+ const uri = file.uri ?? '';
18
+ return uri.startsWith('data:image/') || PICTURE.test(file.name ?? '') || (!uri.startsWith('data:') && PICTURE.test(bare(uri)));
19
+ }
20
+ /**
21
+ * 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
22
+ * file part (seen on 17 Nov). Only well-formed entries count; the metadata comes from the client.
23
+ */
24
+ export function uploadsOf(metadata) {
25
+ const list = metadata?.attachments;
26
+ return Array.isArray(list) ? list.filter((item) => !!item && typeof item === 'object' && typeof item.name === 'string' && typeof item.mime === 'string' && typeof item.path === 'string') : [];
27
+ }
28
+ const isImage = (upload) => upload.mime.startsWith('image/');
29
+ /** What the decider may be told of a file: its name, else its address without what follows a ? or #. Never the content that a `data:` address holds. */
30
+ const nameOf = (file) => file.name ?? (file.uri && !file.uri.startsWith('data:') ? bare(file.uri) : '');
31
+ /** 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. */
32
+ export function localPath(uri) {
33
+ try {
34
+ const url = new URL(uri);
35
+ return url.protocol === 'file:' && !url.host ? fileURLToPath(url) : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ export async function fileSize(uri) {
42
+ const path = localPath(uri);
43
+ return path === null ? null : (await stat(path)).size;
44
+ }
45
+ export const timingOf = (deps) => ({ waitMs: deps.waitMs ?? 120_000, sizeMs: deps.sizeMs ?? 1000, readMs: deps.readMs ?? 5000 });
46
+ /**
47
+ * 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
48
+ * 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.
49
+ */
50
+ export async function placeMessage(deps, timing, input) {
51
+ const { sessionID, prompt } = input, { waitMs, sizeMs, readMs } = timing;
52
+ const outcome = { mode: null, confidence: null, fit: null, model: null, ms: 0, costUsd: null };
53
+ const notes = [];
54
+ const attempt = async (what, work) => {
55
+ try {
56
+ await work();
57
+ return true;
58
+ }
59
+ catch (error) {
60
+ notes.push(`${what}: ${brief(error)}`);
61
+ return false;
62
+ }
63
+ };
64
+ const sized = async (uri) => {
65
+ try {
66
+ const bytes = await within(() => deps.fileSize(uri), sizeMs);
67
+ return typeof bytes === 'number' && Number.isFinite(bytes) && bytes >= 0 ? bytes : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ };
73
+ /** Null when the chat is idle, else why it cannot be switched now. */
74
+ const idle = async () => {
75
+ try {
76
+ return await within(() => deps.session.wait({ sessionID }), waitMs) === LATE ? `the chat was still busy after ${waitMs / 1000} seconds` : null;
77
+ }
78
+ catch (error) {
79
+ return `could not wait for the chat: ${brief(error)}`;
80
+ }
81
+ };
82
+ const reading = async (what, work) => {
83
+ try {
84
+ return await work();
85
+ }
86
+ catch (error) {
87
+ throw new Error(`${what} could not be read: ${brief(error)}`);
88
+ }
89
+ };
90
+ /** For the cost check only: the chat's messages and Relay's earlier records. Null when they fail or take longer than the other reads may, and then the line is simply followed. */
91
+ const spare = async (work) => {
92
+ try {
93
+ const value = await within(work, Math.min(readMs / 2, 1000));
94
+ return value === LATE ? null : value;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ };
100
+ const place = async () => {
101
+ const read = await within(() => Promise.all([
102
+ reading('the settings', () => getRelaySettings(deps.store)), reading('the chat', () => deps.session.get({ sessionID })), reading('the model list', deps.chatModels),
103
+ spare(() => deps.session.context({ sessionID })), spare(() => recentDecisions(deps.store)),
104
+ ]), readMs);
105
+ if (read === LATE) {
106
+ notes.push(`Relay's settings, the chat or the model list did not answer within ${readMs / 1000} seconds`);
107
+ return;
108
+ }
109
+ const [settings, chat, models, messages, past] = read;
110
+ const files = prompt.files ?? [], uploads = input.uploads ?? [];
111
+ const pictures = files.filter(isPicture).length + uploads.filter(isImage).length;
112
+ const facts = await Promise.all([
113
+ ...files.filter(file => !isPicture(file)).map(async (file) => ({ name: nameOf(file), bytes: file.uri ? await sized(file.uri) : null })),
114
+ ...uploads.filter(upload => !isImage(upload)).map(async (upload) => ({ name: upload.name, bytes: await sized(pathToFileURL(upload.path).href) })),
115
+ ]);
116
+ // shortcut: four bytes to a token. Dense text takes more, so a file close to a model's size can still be too big for it.
117
+ const attachment = { needsImage: pictures > 0, tokens: Math.ceil(facts.reduce((sum, file) => sum + (file.bytes ?? 0), 0) / 4), chat: messages === null ? null : chatFacts(messages, Date.now()), past: past ?? [] };
118
+ const current = chat.model ? { providerID: chat.model.providerID, id: chat.model.id, variant: hostVariant(chat.model.variant) } : null;
119
+ const answer = await deps.decide(settings.decider, { kind: 'chat', text: prompt.text, agent: chat.agent ?? null, files: facts, images: pictures, lines: linesFor(settings, models, attachment, current) });
120
+ const result = route(answer, settings, models, attachment, current, input.unsure);
121
+ Object.assign(outcome, { mode: result.mode, ms: answer.ms }, answer.kind === 'answer' ? { confidence: answer.confidence, costUsd: answer.costUsd } : {});
122
+ if (result.note !== null)
123
+ notes.push(result.note);
124
+ if (!result.switch)
125
+ return;
126
+ const { providerID, id, variant } = result.model;
127
+ const agentChanges = chat.agent !== result.agent;
128
+ const modelChanges = !(current !== null && current.providerID === providerID && current.id === id && current.variant === variant);
129
+ if (agentChanges || modelChanges) {
130
+ // Nothing about a chat is changed while it is working, and nothing needs changing here unless the agent or the model actually differs.
131
+ const busy = await idle();
132
+ if (busy !== null) {
133
+ notes.push(busy);
134
+ return;
135
+ }
136
+ }
137
+ if (agentChanges)
138
+ await attempt('agent not switched', () => deps.session.switchAgent({ sessionID, agent: result.agent }));
139
+ const on = !modelChanges || await attempt('model not switched', () => deps.session.switchModel({ sessionID, model: { providerID, id, ...(variant === null ? {} : { variant }) } }));
140
+ if (on)
141
+ Object.assign(outcome, { model: modelName(result.model), fit: result.fit });
142
+ if (result.mode === 'review')
143
+ await attempt('review rules not set', () => deps.session.instructions.entry.put({ sessionID, key: REVIEW_RULES_KEY, value: reviewRules }));
144
+ // shortcut: a failed remove is not reported. Rules that stay only say how to review, and there may be none to remove.
145
+ else
146
+ try {
147
+ await deps.session.instructions.entry.remove({ sessionID, key: REVIEW_RULES_KEY });
148
+ }
149
+ catch { /* see the shortcut above */ }
150
+ };
151
+ try {
152
+ await place();
153
+ }
154
+ catch (error) {
155
+ notes.push(brief(error));
156
+ }
157
+ return { outcome, notes };
158
+ }
159
+ /** 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. */
160
+ export async function recordPlaced(deps, sessionID, { outcome, notes }, messageID = null) {
161
+ try {
162
+ await recordDecision(deps.store, { at: new Date().toISOString(), sessionID, kind: 'chat', ...outcome, note: notes.length ? notes.join('; ') : null, messageID });
163
+ }
164
+ catch { /* not recorded */ }
165
+ }
166
+ export function relayCommand(deps) {
167
+ const timing = timingOf(deps), { readMs } = timing;
168
+ const turns = new Map();
169
+ async function relay({ sessionID, prompt, delivery }) {
170
+ const placed = await placeMessage(deps, timing, { sessionID, prompt, unsure: 'plan' });
171
+ let failure, sent;
172
+ // The marker tells the hook of a chat whose switch is on that this message is placed already. The host keeps it with the message and does not send it to the model.
173
+ try {
174
+ sent = await deps.session.prompt({ ...prompt, sessionID, delivery, metadata: { relay: 'sent' } });
175
+ }
176
+ catch (error) {
177
+ failure = { error };
178
+ placed.notes.push(`the message could not be sent: ${brief(error)}`);
179
+ }
180
+ // The send gives back the new message's entry; its id is the message's id in the chat (seen on 2.3.0, 18 Nov).
181
+ const messageID = sent?.id;
182
+ await recordPlaced(deps, sessionID, placed, typeof messageID === 'string' ? messageID : null);
183
+ if (failure)
184
+ throw failure.error;
185
+ }
186
+ return {
187
+ name: 'relay',
188
+ description: 'Relay: pick the model for this message (plan, execute or review) and send it. /relay on or /relay off: do it for every message in this chat',
189
+ async execute(input) {
190
+ if (!input.prompt.text.trim())
191
+ throw new Error('Relay: type your message after /relay.');
192
+ const word = input.prompt.text.trim().toLowerCase(), toggle = word === 'on' ? true : word === 'off' ? false : null;
193
+ // One at a time in a chat: the next message waits for this one, whether this one works or not.
194
+ // The queue is joined here, before anything is awaited, so two calls join it in the order they were made, not in the order their own checks happen to answer.
195
+ const turn = (turns.get(input.sessionID) ?? Promise.resolve()).then(async () => {
196
+ if (toggle === null)
197
+ return relay(input);
198
+ // `/relay on` or `/relay off`: the switch for this chat. Nothing is sent, and nothing is decided.
199
+ if (await within(() => setChatSwitch(deps.store, input.sessionID, toggle), readMs) === LATE)
200
+ throw new Error(`Relay: the switch could not be saved within ${readMs / 1000} seconds.`);
201
+ });
202
+ const settled = turn.then(() => undefined, () => undefined);
203
+ turns.set(input.sessionID, settled);
204
+ void settled.then(() => { if (turns.get(input.sessionID) === settled)
205
+ turns.delete(input.sessionID); });
206
+ return turn;
207
+ },
208
+ };
209
+ }
@@ -0,0 +1,64 @@
1
+ import { type ModelChoice, type OfferedModel } from './settings.js';
2
+ export declare const modes: readonly ["plan", "execute", "review"];
3
+ export type Mode = typeof modes[number];
4
+ export declare const USE_FOR_MAX = 200;
5
+ /** A model chosen for a mode, with the person's own words for the kind of work it suits. An empty line means nothing was written. */
6
+ export type ModeChoice = ModelChoice & {
7
+ useFor: string;
8
+ };
9
+ export type RelaySettings = {
10
+ revision: number;
11
+ modes: Record<Mode, ModeChoice[]>;
12
+ decider: ModelChoice | null;
13
+ };
14
+ /**
15
+ * What the reply to a placed message took, read from the chat afterwards: the tokens its first request read new (not from a cache) and from
16
+ * a cache, that request's cost, the seconds until its first word, and how many requests the whole reply made.
17
+ */
18
+ export type Reply = {
19
+ requests: number;
20
+ fresh: number;
21
+ cached: number;
22
+ costUsd: string | null;
23
+ seconds: number | null;
24
+ };
25
+ /**
26
+ * One routing decision. It never holds the message text or a file name. `fit` is how sure the decider was about the "use it for" line.
27
+ * `messageID` names the message the decision was made for, so that `reply` can be read once the chat has answered it.
28
+ */
29
+ export type Decision = {
30
+ at: string;
31
+ sessionID: string;
32
+ kind: 'chat' | 'helper';
33
+ mode: Mode | null;
34
+ confidence: number | null;
35
+ fit: number | null;
36
+ model: string | null;
37
+ ms: number;
38
+ costUsd: string | null;
39
+ note: string | null;
40
+ messageID: string | null;
41
+ reply: Reply | null;
42
+ };
43
+ export type RelayStore = {
44
+ get(key: string): Promise<unknown>;
45
+ set(key: string, value: RelaySettings | Decision[] | boolean): Promise<void>;
46
+ compareAndSet?(key: string, expected: unknown, value: RelaySettings | Decision[]): Promise<boolean>;
47
+ };
48
+ export declare const modelName: (choice: ModelChoice) => string;
49
+ export declare function getRelaySettings(store: Pick<RelayStore, 'get'>): Promise<RelaySettings>;
50
+ /** A choice that was already saved may stay when it is no longer offered; a new one must be offered now. Only a decision model can be the decider. */
51
+ export declare function saveRelaySettings(store: RelayStore, revision: number, input: unknown, chatModels: readonly OfferedModel[], decisionModels: readonly OfferedModel[]): Promise<RelaySettings>;
52
+ /** A new record has no reply yet; one made for a message of a chat names that message. */
53
+ export declare function recordDecision(store: RelayStore, decision: Omit<Decision, 'messageID' | 'reply'> & {
54
+ messageID?: string | null;
55
+ }): Promise<void>;
56
+ /** The messages of one chat whose records still wait for what the reply took. */
57
+ export declare function waitingReplies(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<string[]>;
58
+ /** Keeps what the replies took, by message, with the records of one chat that still wait for it. A reply that was kept once is not replaced. */
59
+ export declare function saveReplies(store: RelayStore, sessionID: string, replies: ReadonlyMap<string, Reply>): Promise<void>;
60
+ /** Newest first, at most 20. */
61
+ export declare function recentDecisions(store: Pick<RelayStore, 'get'>): Promise<Decision[]>;
62
+ /** Only a stored `true` counts as on. */
63
+ export declare function chatSwitch(store: Pick<RelayStore, 'get'>, sessionID: string): Promise<boolean>;
64
+ export declare function setChatSwitch(store: Pick<RelayStore, 'set'>, sessionID: string, on: boolean): Promise<void>;