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,111 @@
1
+ import { Rpc } from '@opencode/plugin/rpc';
2
+ const choice = { type: 'object', properties: { providerID: { type: 'string' }, id: { type: 'string' }, variant: { anyOf: [{ type: 'string' }, { type: 'null' }] } }, required: ['providerID', 'id', 'variant'], additionalProperties: false };
3
+ const nullableString = { anyOf: [{ type: 'string' }, { type: 'null' }] };
4
+ const prices = { inputPerMillion: nullableString, outputPerMillion: nullableString, cacheReadPerMillion: nullableString, cacheWritePerMillion: nullableString };
5
+ const priceNames = ['inputPerMillion', 'outputPerMillion', 'cacheReadPerMillion', 'cacheWritePerMillion'];
6
+ /** One model as the panel sees it: display fields only, never the host's record. Prices are USD for one million tokens; null is unknown. `steps` are the prices for chats over a size. */
7
+ const modelItem = {
8
+ type: 'object', properties: {
9
+ providerID: { type: 'string' }, id: { type: 'string' }, name: { type: 'string' }, enabled: { type: 'boolean' }, status: { type: 'string' },
10
+ variants: { type: 'array', items: { type: 'string' } },
11
+ capabilities: { type: 'object', properties: { input: { type: 'array', items: { type: 'string' } }, output: { type: 'array', items: { type: 'string' } }, tools: { type: 'boolean' } }, required: ['input', 'output', 'tools'], additionalProperties: false },
12
+ limit: { type: 'object', properties: { context: { type: 'number' }, output: { type: 'number' } }, required: ['context', 'output'], additionalProperties: false },
13
+ cost: { type: 'object', properties: { ...prices, tiered: { type: 'boolean' }, steps: { type: 'array', items: { type: 'object', properties: { above: { type: 'number' }, ...prices }, required: ['above', ...priceNames], additionalProperties: false } } }, required: [...priceNames, 'tiered', 'steps'], additionalProperties: false },
14
+ }, required: ['providerID', 'id', 'name', 'enabled', 'status', 'variants', 'capabilities', 'limit', 'cost'], additionalProperties: false,
15
+ };
16
+ // One set of settings for every project (the host shares plugin storage), the last decisions, and the panel's test box.
17
+ const nullableNumber = { anyOf: [{ type: 'number' }, { type: 'null' }] };
18
+ const nullableMode = { anyOf: [{ type: 'string', enum: ['plan', 'execute', 'review'] }, { type: 'null' }] };
19
+ const nullableChoice = { anyOf: [choice, { type: 'null' }] };
20
+ /** A model chosen for a mode, with the person's "use it for" line. The line is optional in what the panel sends and always present in what comes back. */
21
+ const modeChoice = { type: 'object', properties: { ...choice.properties, useFor: { type: 'string' } }, required: ['providerID', 'id', 'variant', 'useFor'], additionalProperties: false };
22
+ const modeChoiceInput = { type: 'object', properties: { ...choice.properties, useFor: { type: 'string' } }, required: ['providerID', 'id', 'variant'], additionalProperties: false };
23
+ const modeLists = { type: 'object', properties: { plan: { type: 'array', items: modeChoice }, execute: { type: 'array', items: modeChoice }, review: { type: 'array', items: modeChoice } }, required: ['plan', 'execute', 'review'], additionalProperties: false };
24
+ const modeListsInput = { type: 'object', properties: { plan: { type: 'array', items: modeChoiceInput }, execute: { type: 'array', items: modeChoiceInput }, review: { type: 'array', items: modeChoiceInput } }, required: ['plan', 'execute', 'review'], additionalProperties: false };
25
+ /** Where a reply's prices came from: OpenCode's own list, or Artificial Analysis's when OpenCode lists none. */
26
+ const priceSource = { anyOf: [{ type: 'string', enum: ['opencode', 'artificial-analysis'] }, { type: 'null' }] };
27
+ const priceList = { type: 'object', properties: prices, required: [...priceNames], additionalProperties: false };
28
+ const totals = { type: 'object', properties: { input: { type: 'number' }, output: { type: 'number' }, reasoning: { type: 'number' }, cacheRead: { type: 'number' }, cacheWrite: { type: 'number' }, costUsd: nullableString }, required: ['input', 'output', 'reasoning', 'cacheRead', 'cacheWrite', 'costUsd'], additionalProperties: false };
29
+ /** What the reply to a placed message took; null until the chat has answered it. `total` and `prices` are null in a reply kept before 19 Nov 2026. */
30
+ const reply = {
31
+ type: 'object', properties: { requests: { type: 'number' }, fresh: { type: 'number' }, cached: { type: 'number' }, costUsd: nullableString, seconds: nullableNumber, model: nullableString, total: { anyOf: [totals, { type: 'null' }] }, prices: { anyOf: [priceList, { type: 'null' }] }, pricesFrom: priceSource },
32
+ required: ['requests', 'fresh', 'cached', 'costUsd', 'seconds', 'model', 'total', 'prices', 'pricesFrom'], additionalProperties: false,
33
+ };
34
+ /** One model and effort in Usage by model: every reply Relay counted, added up. `byPrice` is tokens times each reply's price, by kind. */
35
+ const usageRow = { type: 'object', properties: {
36
+ model: { type: 'string' }, messages: { type: 'number' }, requests: { type: 'number' }, input: { type: 'number' }, output: { type: 'number' }, reasoning: { type: 'number' }, cacheRead: { type: 'number' }, cacheWrite: { type: 'number' }, openCodeUsd: nullableString,
37
+ byPrice: { type: 'object', properties: { input: nullableString, output: nullableString, cacheRead: nullableString, cacheWrite: nullableString }, required: ['input', 'output', 'cacheRead', 'cacheWrite'], additionalProperties: false },
38
+ prices: { anyOf: [priceList, { type: 'null' }] }, pricesFrom: priceSource,
39
+ }, required: ['model', 'messages', 'requests', 'input', 'output', 'reasoning', 'cacheRead', 'cacheWrite', 'openCodeUsd', 'byPrice', 'prices', 'pricesFrom'], additionalProperties: false };
40
+ const decision = { type: 'object', properties: { at: { type: 'string' }, sessionID: { type: 'string' }, kind: { type: 'string', enum: ['chat', 'helper'] }, mode: nullableMode, confidence: nullableNumber, fit: nullableNumber, model: nullableString, ms: { type: 'number' }, costUsd: nullableString, note: nullableString, messageID: nullableString, reply: { anyOf: [reply, { type: 'null' }] } }, required: ['at', 'sessionID', 'kind', 'mode', 'confidence', 'fit', 'model', 'ms', 'costUsd', 'note', 'messageID', 'reply'], additionalProperties: false };
41
+ const relayOutput = { type: 'object', properties: {
42
+ directory: { type: 'string' },
43
+ settings: { type: 'object', properties: { revision: { type: 'integer', minimum: 0 }, modes: modeLists, decider: nullableChoice }, required: ['revision', 'modes', 'decider'], additionalProperties: false },
44
+ decisions: { type: 'array', items: decision }, deciders: { type: 'array', items: modelItem },
45
+ checks: { type: 'object', properties: { active: { type: 'boolean' }, note: nullableString }, required: ['active', 'note'], additionalProperties: false },
46
+ priceKey: { type: 'boolean' },
47
+ }, required: ['directory', 'settings', 'decisions', 'deciders', 'checks', 'priceKey'], additionalProperties: false };
48
+ /** The host reports any exception thrown by a handler as an opaque "RPC call failed", so a refusal the panel must show is returned as this declared error instead. */
49
+ const errors = { rejected: { type: 'object', properties: {}, additionalProperties: false } };
50
+ const nothing = { type: 'object', properties: {}, additionalProperties: false };
51
+ /** One usage record (src/usage-log.ts): numbers, models, ids and the project's folder, never text. */
52
+ const usageRecord = { type: 'object', properties: {
53
+ at: { type: 'string' }, sessionID: { type: 'string' }, messageID: { type: 'string' }, project: { type: 'string' }, kind: { type: 'string', enum: ['chat', 'helper', 'summary'] },
54
+ agent: nullableString, model: nullableString, requests: { type: 'number' }, input: { type: 'number' }, output: { type: 'number' }, reasoning: { type: 'number' }, cacheRead: { type: 'number' }, cacheWrite: { type: 'number' },
55
+ costByPrice: nullableString, openCodeUsd: nullableString, pricesFrom: priceSource,
56
+ relay: { anyOf: [{ type: 'object', properties: { mode: nullableMode, note: nullableString }, required: ['mode', 'note'], additionalProperties: false }, { type: 'null' }] },
57
+ }, required: ['at', 'sessionID', 'messageID', 'project', 'kind', 'agent', 'model', 'requests', 'input', 'output', 'reasoning', 'cacheRead', 'cacheWrite', 'costByPrice', 'openCodeUsd', 'pricesFrom', 'relay'], additionalProperties: false };
58
+ const usageTotal = { type: 'object', properties: {
59
+ model: { type: 'string' }, replies: { type: 'number' }, requests: { type: 'number' }, input: { type: 'number' }, output: { type: 'number' }, reasoning: { type: 'number' }, cacheRead: { type: 'number' }, cacheWrite: { type: 'number' },
60
+ cost: nullableString, aaPriced: { type: 'boolean' }, unpriced: { type: 'number' },
61
+ }, required: ['model', 'replies', 'requests', 'input', 'output', 'reasoning', 'cacheRead', 'cacheWrite', 'cost', 'aaPriced', 'unpriced'], additionalProperties: false };
62
+ /** What the usage tab asks for: a range of at most 92 days, the panel's offset from UTC, the filters, and a page of at most 200 records. */
63
+ const usageQuery = { type: 'object', properties: {
64
+ from: { type: 'string' }, to: { type: 'string' }, tzOffsetMinutes: { type: 'integer', minimum: -840, maximum: 840 }, timeZone: { anyOf: [{ type: 'string', maxLength: 64 }, { type: 'null' }] }, search: { type: 'string', maxLength: 200 },
65
+ provider: nullableString, effort: nullableString, mode: nullableString, relay: { type: 'string', enum: ['any', 'on', 'off'] }, kind: { type: 'string', enum: ['any', 'chat', 'helper', 'summary'] },
66
+ project: nullableString, offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 200 },
67
+ }, required: ['from', 'to', 'tzOffsetMinutes', 'search', 'provider', 'effort', 'mode', 'relay', 'kind', 'project', 'offset', 'limit'], additionalProperties: false };
68
+ const strings = { type: 'array', items: { type: 'string' } };
69
+ const usageDay = { type: 'object', properties: { day: { type: 'string' }, models: { type: 'array', items: { type: 'object', properties: { model: { type: 'string' }, cost: nullableString, tokens: { type: 'number' }, requests: { type: 'number' } }, required: ['model', 'cost', 'tokens', 'requests'], additionalProperties: false } } }, required: ['day', 'models'], additionalProperties: false };
70
+ const usageLog = { type: 'object', properties: {
71
+ directory: { type: 'string' }, days: { type: 'array', items: usageDay }, totals: { type: 'array', items: usageTotal },
72
+ options: { type: 'object', properties: { providers: strings, efforts: strings, modes: strings, projects: strings }, required: ['providers', 'efforts', 'modes', 'projects'], additionalProperties: false },
73
+ records: { type: 'array', items: usageRecord }, matching: { type: 'number' }, first: nullableString,
74
+ before: { type: 'object', properties: { since: nullableString, rows: { type: 'array', items: usageRow } }, required: ['since', 'rows'], additionalProperties: false },
75
+ credit: nullableString, removed: { type: 'number' },
76
+ }, required: ['directory', 'days', 'totals', 'options', 'records', 'matching', 'first', 'before', 'credit', 'removed'], additionalProperties: false };
77
+ /** Relay's own choice for one mode (src/ranking.ts): null when the mode is not Relay's to choose, else the models by name, or why it can't rank them. */
78
+ const ownPart = { anyOf: [
79
+ { type: 'null' },
80
+ { type: 'object', properties: { kind: { type: 'string', enum: ['unranked'] }, reason: { type: 'string' } }, required: ['kind', 'reason'], additionalProperties: false },
81
+ { type: 'object', properties: { kind: { type: 'string', enum: ['ranked'] }, strongest: { type: 'string' }, cheapest: { type: 'string' } }, required: ['kind', 'strongest', 'cheapest'], additionalProperties: false },
82
+ ] };
83
+ export const RelayRpc = Rpc.define({
84
+ id: 'relay-opencode',
85
+ events: {},
86
+ methods: {
87
+ getRelay: { errors, input: nothing, output: relayOutput },
88
+ saveRelay: { errors, input: { type: 'object', properties: { revision: { type: 'integer', minimum: 0 }, modes: modeListsInput, decider: nullableChoice }, required: ['revision', 'modes', 'decider'], additionalProperties: false }, output: relayOutput },
89
+ /** The pill: one chat's switch, that chat's newest record, and whether a decider is chosen at all. */
90
+ getRelayChat: { errors, input: { type: 'object', properties: { sessionID: { type: 'string' } }, required: ['sessionID'], additionalProperties: false }, output: { type: 'object', properties: { on: { type: 'boolean' }, last: { anyOf: [decision, { type: 'null' }] }, decider: { type: 'boolean' } }, required: ['on', 'last', 'decider'], additionalProperties: false } },
91
+ /** The panel's Recent choices, newest first. Storage only, so the panel can ask every few seconds. */
92
+ getRelayDecisions: { errors, input: nothing, output: { type: 'object', properties: { directory: { type: 'string' }, decisions: { type: 'array', items: decision } }, required: ['directory', 'decisions'], additionalProperties: false } },
93
+ setRelayChat: { errors, input: { type: 'object', properties: { sessionID: { type: 'string' }, on: { type: 'boolean' } }, required: ['sessionID', 'on'], additionalProperties: false }, output: { type: 'object', properties: { on: { type: 'boolean' } }, required: ['on'], additionalProperties: false } },
94
+ /** What Relay would do with a sample message: the mode after the 0.6 rule, the model it would pick, and the note. Nothing is switched, sent or recorded. */
95
+ testDecider: { errors, input: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false }, output: { type: 'object', properties: { directory: { type: 'string' }, mode: nullableMode, confidence: nullableNumber, model: nullableString, fit: nullableNumber, ms: { type: 'number' }, costUsd: nullableString, note: nullableString }, required: ['directory', 'mode', 'confidence', 'model', 'fit', 'ms', 'costUsd', 'note'], additionalProperties: false } },
96
+ /** Usage by model: the totals of every reply Relay counted, and the credit Artificial Analysis asks for when its prices are used. Storage only. */
97
+ getRelayUsage: { errors, input: nothing, output: { type: 'object', properties: { directory: { type: 'string' }, since: nullableString, rows: { type: 'array', items: usageRow }, credit: nullableString }, required: ['directory', 'since', 'rows', 'credit'], additionalProperties: false } },
98
+ /** For the panel: which model of each mode Relay gives big work and small work by itself, from the saved settings and the stored copies only. */
99
+ /** The usage tab (Relay usage): every reply of every chat in a time range, added up and filtered on the server. Storage only; it also removes records past 90 days. */
100
+ getUsageLog: { errors, input: usageQuery, output: usageLog },
101
+ getOwnChoice: { errors, input: nothing, output: { type: 'object', properties: { directory: { type: 'string' }, modes: { type: 'object', properties: { plan: ownPart, execute: ownPart, review: ownPart }, required: ['plan', 'execute', 'review'], additionalProperties: false } }, required: ['directory', 'modes'], additionalProperties: false } },
102
+ /** Saves the Artificial Analysis key, or with null removes it, and never returns it. `note` says why the list could not be loaded with it. */
103
+ setPriceKey: { errors, input: { type: 'object', properties: { key: nullableString }, required: ['key'], additionalProperties: false }, output: { type: 'object', properties: { saved: { type: 'boolean' }, note: nullableString }, required: ['saved', 'note'], additionalProperties: false } },
104
+ listModels: { errors, input: nothing, output: { type: 'object', properties: { directory: { type: 'string' }, models: { type: 'array', items: modelItem } }, required: ['directory', 'models'], additionalProperties: false } },
105
+ /** The intelligence index of each listed model that could be matched, with where it came from, when it was fetched, and why it may be old or missing. */
106
+ listIntelligence: { errors, input: nothing, output: { type: 'object', properties: {
107
+ directory: { type: 'string' }, source: { type: 'string' }, fetchedAt: nullableString, note: nullableString,
108
+ scores: { type: 'array', items: { type: 'object', properties: { providerID: { type: 'string' }, id: { type: 'string' }, index: { type: 'number' }, matched: { type: 'string' } }, required: ['providerID', 'id', 'index', 'matched'], additionalProperties: false } },
109
+ }, required: ['directory', 'source', 'fetchedAt', 'note', 'scores'], additionalProperties: false } },
110
+ },
111
+ });
@@ -0,0 +1,14 @@
1
+ import type { ModelCostView, PriceStep } from './inventory.js';
2
+ /** The prices of a request that reads `tokens`: the largest step below that size, else the base price, as the host prices a request (2.3.0). */
3
+ export declare function pricesAt(cost: ModelCostView, tokens: number): Omit<PriceStep, 'above'>;
4
+ /** A price as the host reports it (a number of USD) becomes a USD string. Anything that is not a plain amount, or is too small to show in six decimals, is unknown. */
5
+ export declare function usdString(value: unknown): string | null;
6
+ /** A USD string as a whole number of trillionths of a dollar, so that prices compare exactly. Money is never a float. */
7
+ export declare function parseUsd(value: string): bigint;
8
+ /** A USD string read back from storage, or null when it is not one. */
9
+ export declare function storedUsd(value: unknown): string | null;
10
+ /** What `tokens` cost at a price for a million tokens, in trillionths of a dollar; null when there is no price. */
11
+ export declare function costOf(tokens: number, perMillion: string | null): bigint | null;
12
+ export declare function formatUsd(value: bigint): string;
13
+ /** An amount for a sentence: rounded to the cent, and "under $0.01" when that leaves nothing. */
14
+ export declare function aboutUsd(value: bigint): string;
package/dist/costs.js ADDED
@@ -0,0 +1,47 @@
1
+ const SCALE = 1000000000000n;
2
+ /** The prices of a request that reads `tokens`: the largest step below that size, else the base price, as the host prices a request (2.3.0). */
3
+ export function pricesAt(cost, tokens) {
4
+ const { inputPerMillion, outputPerMillion, cacheReadPerMillion, cacheWritePerMillion } = [...cost.steps].reverse().find(step => tokens > step.above) ?? cost;
5
+ return { inputPerMillion, outputPerMillion, cacheReadPerMillion, cacheWritePerMillion };
6
+ }
7
+ /** A price as the host reports it (a number of USD) becomes a USD string. Anything that is not a plain amount, or is too small to show in six decimals, is unknown. */
8
+ export function usdString(value) {
9
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value >= 1e21)
10
+ return null;
11
+ const text = value.toFixed(6).replace(/\.?0+$/, '');
12
+ return text === '0' && value !== 0 ? null : text;
13
+ }
14
+ /** A USD string as a whole number of trillionths of a dollar, so that prices compare exactly. Money is never a float. */
15
+ export function parseUsd(value) {
16
+ if (!/^(?:0|[1-9]\d*)(?:\.\d{1,12})?$/.test(value))
17
+ throw new Error('Invalid USD amount');
18
+ const [whole, fraction = ''] = value.split('.');
19
+ return BigInt(whole) * SCALE + BigInt(fraction.padEnd(12, '0'));
20
+ }
21
+ /** A USD string read back from storage, or null when it is not one. */
22
+ export function storedUsd(value) {
23
+ if (typeof value !== 'string')
24
+ return null;
25
+ try {
26
+ parseUsd(value);
27
+ return value;
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /** What `tokens` cost at a price for a million tokens, in trillionths of a dollar; null when there is no price. */
34
+ export function costOf(tokens, perMillion) {
35
+ const price = storedUsd(perMillion);
36
+ return price === null ? null : BigInt(Math.max(0, Math.round(tokens))) * parseUsd(price) / 1000000n;
37
+ }
38
+ export function formatUsd(value) {
39
+ const whole = value / SCALE;
40
+ const fraction = (value % SCALE).toString().padStart(12, '0').replace(/0+$/, '');
41
+ return fraction ? `${whole}.${fraction}` : `${whole}`;
42
+ }
43
+ /** An amount for a sentence: rounded to the cent, and "under $0.01" when that leaves nothing. */
44
+ export function aboutUsd(value) {
45
+ const cents = (value + SCALE / 200n) / (SCALE / 100n);
46
+ return cents === 0n ? 'under $0.01' : `about $${cents / 100n}.${(cents % 100n).toString().padStart(2, '0')}`;
47
+ }
@@ -0,0 +1,73 @@
1
+ import { type Mode } from './relay-store.js';
2
+ import { type DeciderAnswer } from './router.js';
3
+ import type { ModelChoice } from './settings.js';
4
+ export declare const MAX_CHARS = 4000;
5
+ export declare const MAX_REPLY_CHARS = 1500;
6
+ /** How much of the chat's first message the size question sees: its start, where a task is stated. */
7
+ export declare const MAX_TASK_CHARS = 1500;
8
+ export declare const TIMEOUT_MS = 5000;
9
+ export declare const MAX_FILE_NAMES = 10;
10
+ export type FileFact = {
11
+ name: string;
12
+ bytes: number | null;
13
+ };
14
+ /** `reply` is the end of the chat's last reply, for a chat message (see `lastReply`). `sizes` are the modes Relay chooses for by itself, asked how big the work is. */
15
+ /** `task` is the chat's first message (see `firstRequest`): told only with a size question, since a short follow-up says nothing of how hard the task is. */
16
+ export type DecideInput = {
17
+ kind: 'chat' | 'helper';
18
+ text: string;
19
+ agent: string | null;
20
+ files: readonly FileFact[];
21
+ images: number;
22
+ lines: Partial<Record<Mode, readonly string[]>>;
23
+ reply?: string | null;
24
+ sizes?: readonly Mode[];
25
+ task?: string | null;
26
+ };
27
+ export type DecisionsRequest = {
28
+ model: {
29
+ providerID: string;
30
+ id: string;
31
+ variant?: string;
32
+ };
33
+ input: {
34
+ type: 'text';
35
+ text: string;
36
+ }[];
37
+ questions: {
38
+ type: 'choice';
39
+ name: string;
40
+ instructions: string;
41
+ choices: {
42
+ value: string;
43
+ description: string;
44
+ }[];
45
+ }[];
46
+ };
47
+ export type DecisionsHost = {
48
+ decisions(request: DecisionsRequest): Promise<unknown>;
49
+ };
50
+ /** Text over the limit keeps its first and last half, and is never cut inside a two-unit character. */
51
+ export declare function capText(text: string): string;
52
+ /** `text` with every mention of the folder `home` as `~`: with either slash, in any case, and never inside a longer folder name. */
53
+ export declare function withoutHome(text: string, home: string): string;
54
+ /**
55
+ * The task a chat is working on: the text of its first person's message as `session.context` lists it, at most its first MAX_TASK_CHARS
56
+ * characters, with `home` hidden first. Null when there is none, or when that message is `current`, the message being placed: compared before
57
+ * hiding and the cap, so the message is never sent again as its own task.
58
+ * shortcut: a compacted chat is listed from its summary on, so its task is the first message after the summary, not the one that began it.
59
+ */
60
+ export declare function firstRequest(messages: unknown, home?: string | null, current?: string | null): string | null;
61
+ /**
62
+ * The end of the chat's latest reply, from `session.context`: the text the model wrote over all of that reply's requests, joined, at most its
63
+ * last MAX_REPLY_CHARS characters. Never its reasoning, tool calls or tool output, and never an earlier reply: a latest reply with no text
64
+ * gives null. The person's new message may already be listed after the reply. `home` is hidden as `~` before the cut, so a cut can never
65
+ * leave part of it.
66
+ */
67
+ export declare function lastReply(messages: unknown, home?: string | null): string | null;
68
+ export declare function buildDecisionRequest(decider: ModelChoice, input: DecideInput): DecisionsRequest;
69
+ export declare const LATE: unique symbol;
70
+ /** What the work gives, or LATE when it takes longer than `ms`. Work that is given up on cannot be stopped; the race keeps a handler on it, so its late failure is not an unhandled rejection. */
71
+ export declare function within<T>(work: () => T | Promise<T>, ms: number): Promise<T | typeof LATE>;
72
+ /** Asks the decider once and never throws. A late answer and a late failure are both dropped. */
73
+ export declare function decide(host: DecisionsHost, decider: ModelChoice | null, input: DecideInput, timeoutMs?: number): Promise<DeciderAnswer>;
@@ -0,0 +1,199 @@
1
+ import { usdString } from './costs.js';
2
+ import { modes } from './relay-store.js';
3
+ import { brief, safeHead, MAX_LINES } from './router.js';
4
+ // One request to a decision model: which mode fits the text, and, for each mode that has a choice to make, which "use it for" line fits it.
5
+ // The decider is given the text, the names and sizes of attached files and the lines, and for a chat message the end of the chat's last reply
6
+ // (its text only; the owner chose this on 19 Nov, so that "Implement it." can be placed by the plan before it). With a size question it also
7
+ // gets the start of the chat's first message, the task (25 Nov). Never file contents, pictures, other earlier messages, the model's reasoning or tools, model names or prices.
8
+ // Its requests are not reserved in the budget ledger (the owner, 2026-11-14); what is sent is capped instead. Nothing here may import from `node:`.
9
+ export const MAX_CHARS = 4000;
10
+ export const MAX_REPLY_CHARS = 1500;
11
+ /** How much of the chat's first message the size question sees: its start, where a task is stated. */
12
+ export const MAX_TASK_CHARS = 1500;
13
+ export const TIMEOUT_MS = 5000;
14
+ export const MAX_FILE_NAMES = 10;
15
+ const MAX_NAME = 80;
16
+ /** The last `max` characters of `text`, never starting with half a two-unit character. */
17
+ const endOf = (text, max) => { const tail = text.slice(-max); return /^[\uDC00-\uDFFF]/.test(tail) ? tail.slice(1) : tail; };
18
+ /** Text over the limit keeps its first and last half, and is never cut inside a two-unit character. */
19
+ export function capText(text) {
20
+ if (text.length <= MAX_CHARS)
21
+ return text;
22
+ return `${safeHead(text, MAX_CHARS / 2)}\n[...]\n${endOf(text, MAX_CHARS / 2)}`;
23
+ }
24
+ /** `text` with every mention of the folder `home` as `~`: with either slash, in any case, and never inside a longer folder name. */
25
+ export function withoutHome(text, home) {
26
+ const parts = home.replace(/[\\/]+$/, '').split(/[\\/]+/);
27
+ if (!parts.some(part => /\w/.test(part)))
28
+ return text;
29
+ const escape = (part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
30
+ // A Windows home (C:\Users\x) is also written /c/Users/x in Git Bash and /mnt/c/Users/x in WSL.
31
+ const drive = /^([a-z]):$/i.exec(parts[0]), first = drive ? `(?:${drive[1]}:|/(?:mnt/)?${drive[1]})` : escape(parts[0]);
32
+ // Not followed by more of a folder name: a letter, digit, "_" or "-", or a "." that a name goes on after ("me.old"; "me." ends a sentence).
33
+ return text.replace(new RegExp(`${[first, ...parts.slice(1).map(escape)].join('[\\\\/]+')}(?![\\w-]|\\.\\w)`, 'gi'), '~');
34
+ }
35
+ /**
36
+ * The task a chat is working on: the text of its first person's message as `session.context` lists it, at most its first MAX_TASK_CHARS
37
+ * characters, with `home` hidden first. Null when there is none, or when that message is `current`, the message being placed: compared before
38
+ * hiding and the cap, so the message is never sent again as its own task.
39
+ * shortcut: a compacted chat is listed from its summary on, so its task is the first message after the summary, not the one that began it.
40
+ */
41
+ export function firstRequest(messages, home = null, current = null) {
42
+ const first = (Array.isArray(messages) ? messages : []).find((item) => item !== null && typeof item === 'object' && item.type === 'user' && typeof item.text === 'string' && item.text.trim() !== '');
43
+ if (!first)
44
+ return null;
45
+ const text = first.text.trim();
46
+ if (current !== null && text === current.trim())
47
+ return null;
48
+ return safeHead(home ? withoutHome(text, home) : text, MAX_TASK_CHARS);
49
+ }
50
+ /**
51
+ * The end of the chat's latest reply, from `session.context`: the text the model wrote over all of that reply's requests, joined, at most its
52
+ * last MAX_REPLY_CHARS characters. Never its reasoning, tool calls or tool output, and never an earlier reply: a latest reply with no text
53
+ * gives null. The person's new message may already be listed after the reply. `home` is hidden as `~` before the cut, so a cut can never
54
+ * leave part of it.
55
+ */
56
+ export function lastReply(messages, home = null) {
57
+ const all = Array.isArray(messages) ? messages.filter((item) => item !== null && typeof item === 'object') : [];
58
+ let newest = all.length - 1;
59
+ while (newest >= 0 && all[newest].type !== 'assistant')
60
+ newest--;
61
+ if (newest < 0)
62
+ return null;
63
+ let start = newest;
64
+ while (start > 0 && all[start - 1].type !== 'user')
65
+ start--;
66
+ const parts = all.slice(start, newest + 1).filter(entry => entry.type === 'assistant').flatMap(entry => (Array.isArray(entry.content) ? entry.content : []));
67
+ const joined = parts.flatMap(part => part !== null && typeof part === 'object' && part.type === 'text' && typeof part.text === 'string' ? [part.text] : []).join('\n').trim();
68
+ const text = home ? withoutHome(joined, home) : joined;
69
+ return text ? endOf(text, MAX_REPLY_CHARS) : null;
70
+ }
71
+ /**
72
+ * Whether a reply goes to the decider: only for a chat message with text, and only when the decider is asked to choose a line or a size. The
73
+ * reply is there to tell a mode's models apart (19 Nov); with one model a mode the request stays word for word as measured (the 23 Nov review).
74
+ */
75
+ const replied = (input) => input.kind === 'chat' && typeof input.reply === 'string' && input.reply.trim() !== '' && (modes.some(mode => (input.lines[mode]?.length ?? 0) > 0) || sized(input).length > 0);
76
+ /** The modes asked about the size of the work: those Relay chooses for by itself, which never have lines. */
77
+ const sized = (input) => modes.filter(mode => input.sizes?.includes(mode) && !input.lines[mode]?.length);
78
+ /** Whether the task goes to the decider: only with a size question, and only when it is not the message itself (a chat's first message). */
79
+ const tasked = (input) => input.kind === 'chat' && sized(input).length > 0 && typeof input.task === 'string' && input.task.trim() !== '' && input.task.trim() !== input.text.trim();
80
+ const flat = (text, max) => safeHead(text.replace(/[\s\x00-\x1f\x7f]+/g, ' ').trim(), max);
81
+ /** Only the last part of a path is sent, so the name of a home folder never leaves the machine. */
82
+ const fileName = (name) => flat(name.split(/[\\/]/).pop() ?? '', MAX_NAME) || 'file';
83
+ const size = (bytes) => bytes === null ? 'size unknown' : bytes < 1000 ? `${bytes} B` : bytes < 1_000_000 ? `${Math.round(bytes / 1000)} kB` : `${Math.round(bytes / 1_000_000)} MB`;
84
+ /** What the chat's agent can do, so that "ok, do it" after a plan reads as a go-ahead. Never its name: "plan" is also an answer, and told
85
+ * "The chat is on the agent: plan" a real decider hedged on clear fix requests (16 Nov). Other agents are unknown here, so nothing is said. */
86
+ const agentLine = (agent) => agent === 'plan' ? 'Before this message the chat was on a read-only agent, which explains and plans and cannot change files. '
87
+ : agent === 'build' ? 'Before this message the chat was on an agent that can change files. ' : '';
88
+ function describe(input) {
89
+ const text = capText(input.text);
90
+ if (input.kind === 'helper')
91
+ return `A task that a model is handing to a helper: "${text}"`;
92
+ const shown = input.files.slice(0, MAX_FILE_NAMES).map(file => `${fileName(file.name)} (${size(file.bytes)})`).join(', '), more = input.files.length - MAX_FILE_NAMES;
93
+ const files = input.files.length ? `${shown}${more > 0 ? ` and ${more} more` : ''}` : 'none';
94
+ const reply = replied(input) ? `The end of the chat's last reply: "${endOf(input.reply.trim(), MAX_REPLY_CHARS)}"\n` : '';
95
+ const task = tasked(input) ? `The task the chat is working on: "${safeHead(input.task.trim(), MAX_TASK_CHARS)}"\n` : '';
96
+ return `The person's message: "${text}"\n${reply}${task}${agentLine(input.agent)}Attached files: ${files}. Attached pictures: ${input.images}.`;
97
+ }
98
+ // With a reply in the input, the questions say which text to judge, so the reply cannot pull the mode (a plan that says "I will change"
99
+ // is not a request to change). Without one, they are word for word what the decider was measured with before (14 to 19 Nov).
100
+ const modeQuestion = (reply) => ({
101
+ type: 'choice', name: 'mode',
102
+ instructions: reply
103
+ ? "Which mode fits the person's message? The end of the chat's last reply only shows what the message refers to. Choose execute only when the message clearly asks to change, create, fix or run something now. Choose review when it asks to check existing work and report, with nothing to change. Otherwise choose plan."
104
+ : 'Which mode fits the text? Choose execute only when it clearly asks to change, create, fix or run something now. Choose review when it asks to check existing work and report, with nothing to change. Otherwise choose plan.',
105
+ choices: [
106
+ { value: 'plan', description: 'Think, explain, investigate, design or plan. Nothing is changed.' },
107
+ { value: 'execute', description: 'Write, change, create, fix or run something now.' },
108
+ { value: 'review', description: 'Check existing work for mistakes and risks, and report them.' },
109
+ ],
110
+ });
111
+ const lineQuestion = (mode, lines, reply) => ({
112
+ type: 'choice', name: `${mode}_line`,
113
+ instructions: reply
114
+ ? "Which description of work fits best? Judge the kind and size of the work by the person's message and the end of the chat's last reply. Choose none when no description fits clearly."
115
+ : 'Which description of work fits the text best? Choose none when no description fits clearly.',
116
+ choices: [...lines.slice(0, MAX_LINES).map((line, index) => ({ value: String(index + 1), description: line })), { value: 'none', description: 'None of these fits clearly.' }],
117
+ });
118
+ // Both instructions word for word as measured on 23 Nov: the first for the 15 cases with the end of a reply, the second for the 15 first
119
+ // messages (27 of 30 right in all, docs/compatibility.md). A change is measured again with scripts/decider-size.ts before it ships.
120
+ // The decider is asked about the work, never about models, prices or scores.
121
+ // With the task (25 Nov), the size is judged by it too. The answers count a one-file task with many rules as big (25 Nov), measured again with
122
+ // scripts/decider-size.ts on the 30 cases of 23 Nov and the 10 with a task.
123
+ const sizeQuestion = (mode, reply, task) => ({
124
+ type: 'choice', name: `${mode}_size`,
125
+ instructions: task
126
+ ? (reply ? "How big is the work? Judge by the task the chat is working on, the person's message and the end of the chat's last reply." : "How big is the work? Judge by the task the chat is working on and the person's message.")
127
+ : reply ? "How big is the work? Judge by the person's message and the end of the chat's last reply." : 'How big is the work the text asks for?',
128
+ choices: [
129
+ { value: 'small', description: 'Small and clear. A quick question or a simple edit in one or two files, with nothing tricky to get right.' },
130
+ { value: 'big', description: 'Big, unclear or risky. Several files, a new feature, a hard bug, many rules or edge cases to get right, data, money or security, or the last reply shows a failed try.' },
131
+ ],
132
+ });
133
+ export function buildDecisionRequest(decider, input) {
134
+ const reply = replied(input);
135
+ return {
136
+ model: { providerID: decider.providerID, id: decider.id, ...(decider.variant === null ? {} : { variant: decider.variant }) },
137
+ input: [{ type: 'text', text: describe(input) }],
138
+ questions: [modeQuestion(reply), ...modes.flatMap(mode => input.lines[mode]?.length ? [lineQuestion(mode, input.lines[mode], reply)] : []), ...sized(input).map(mode => sizeQuestion(mode, reply, tasked(input)))],
139
+ };
140
+ }
141
+ const sure = (value) => typeof value === 'number' && value >= 0 && value <= 1;
142
+ /** The mode answer must be exactly right, or there is no answer. A line answer that cannot be used is left out, and the router then falls back by its rule. */
143
+ function read(result, input, ms) {
144
+ const unreadable = { kind: 'none', reason: "the decider's answer could not be read", ms };
145
+ const answers = result?.answers;
146
+ if (!Array.isArray(answers))
147
+ return unreadable;
148
+ const named = (name) => answers.find(item => item !== null && typeof item === 'object' && item.name === name);
149
+ const mode = named('mode');
150
+ if (mode?.type === 'error')
151
+ return { kind: 'none', reason: `the decider gave no answer: ${brief(typeof mode.reason === 'string' && mode.reason.trim() ? mode.reason : mode.message)}`, ms };
152
+ const found = modes.find(item => item === mode?.choice);
153
+ if (mode?.type !== 'choice' || !found || !sure(mode.confidence))
154
+ return unreadable;
155
+ const lines = {};
156
+ for (const item of modes) {
157
+ const sent = Math.min(input.lines[item]?.length ?? 0, MAX_LINES), line = named(`${item}_line`);
158
+ if (!sent || line?.type !== 'choice' || !sure(line.confidence))
159
+ continue;
160
+ if (line.choice === 'none')
161
+ lines[item] = { index: null, confidence: line.confidence };
162
+ else if (typeof line.choice === 'string' && /^[1-8]$/.test(line.choice) && Number(line.choice) <= sent)
163
+ lines[item] = { index: Number(line.choice) - 1, confidence: line.confidence };
164
+ }
165
+ // A size answer counts only for a mode that was asked, and only as small or big with a confidence; anything else is left out.
166
+ const asked = sized(input), sizes = {};
167
+ for (const item of asked) {
168
+ const size = named(`${item}_size`);
169
+ if (size?.type === 'choice' && (size.choice === 'small' || size.choice === 'big') && sure(size.confidence))
170
+ sizes[item] = { size: size.choice, confidence: size.confidence };
171
+ }
172
+ return { kind: 'answer', mode: found, confidence: mode.confidence, lines, ...(asked.length ? { sizes } : {}), ms, costUsd: usdString(result.cost) };
173
+ }
174
+ export const LATE = Symbol('late');
175
+ /** What the work gives, or LATE when it takes longer than `ms`. Work that is given up on cannot be stopped; the race keeps a handler on it, so its late failure is not an unhandled rejection. */
176
+ export async function within(work, ms) {
177
+ let timer;
178
+ try {
179
+ return await Promise.race([Promise.resolve().then(work), new Promise(done => { timer = setTimeout(() => done(LATE), ms); })]);
180
+ }
181
+ finally {
182
+ clearTimeout(timer);
183
+ }
184
+ }
185
+ /** Asks the decider once and never throws. A late answer and a late failure are both dropped. */
186
+ export async function decide(host, decider, input, timeoutMs = TIMEOUT_MS) {
187
+ if (!decider)
188
+ return { kind: 'none', reason: 'no decider chosen', ms: 0 };
189
+ const started = Date.now();
190
+ try {
191
+ const result = await within(() => host.decisions(buildDecisionRequest(decider, input)), timeoutMs);
192
+ if (result === LATE)
193
+ return { kind: 'none', reason: `the decider took longer than ${timeoutMs / 1000} seconds`, ms: Date.now() - started };
194
+ return read(result, input, Date.now() - started);
195
+ }
196
+ catch (error) {
197
+ return { kind: 'none', reason: `the decider gave no answer: ${brief(error)}`, ms: Date.now() - started };
198
+ }
199
+ }