opencode-model-router 2.2.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +35 -3
- package/package.json +4 -1
- package/src/commands/output.ts +4 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +118 -31
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +484 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/index.ts +486 -38
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1365 -19
- package/src/router/protocol.ts +47 -0
- package/src/router/sessions.ts +441 -9
- package/src/routing/advisor/findings.ts +706 -0
- package/src/routing/advisor/index.ts +606 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +576 -0
- package/src/routing/classify/route-line.ts +298 -0
- package/src/routing/classify/rules.ts +607 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1280 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +131 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +597 -0
- package/src/routing/engine/ladders.ts +561 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +133 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +270 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +141 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +172 -0
- package/src/routing/outcomes/ingest.ts +812 -0
- package/src/routing/outcomes/persist.ts +1058 -0
- package/src/routing/outcomes/stats.ts +602 -0
- package/src/routing/outcomes/store.ts +653 -0
- package/src/routing/outcomes/types.ts +954 -0
- package/src/routing/wire/dispatch.ts +799 -0
- package/src/routing/wire/hint.ts +208 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +259 -0
- package/src/v2.ts +15 -1
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cost doctor (M8, Phase 2.4.2): `runAdvisor`, the `/router` rendering and the throttled notice.
|
|
3
|
+
*
|
|
4
|
+
* The notice is the only part with state, and only when it goes to the orchestrator's context (advise/enforce): then a small JSON
|
|
5
|
+
* file next to the outcome store (D15 directory, `advisor-notice.<project hash>.json`: one per project) holds the throttle, the findings
|
|
6
|
+
* the user was last told about and a notice that is waiting for delivery, and a lock file (`advisor-notice.<project hash>.lock`,
|
|
7
|
+
* exclusive create, a stale one taken over by rename) makes two processes agree on who delivers it. A notice goes out only when the
|
|
8
|
+
* notice-worthy findings contain one the user was not told about yet (a reminder after 7 days; a set that only shrank is not news), a
|
|
9
|
+
* check runs at most once per `routing.advisor.noticeIntervalHours` (never more often than hourly), and a notice produced by one
|
|
10
|
+
* process is delivered by the next one if the first never got to, once that process's own check has confirmed that the findings it
|
|
11
|
+
* was about are still the current ones (otherwise it is dropped). In log mode (static/shadow) the throttle
|
|
12
|
+
* is in memory and NO file is read or written. Nothing runs on OpenCode v1, with `routing.advisor.enabled: false` or `notify: false`,
|
|
13
|
+
* or when the config has no `routing` block at all (§1.2: today's behaviour, no new files, no new log lines). `/router` runs
|
|
14
|
+
* `runAdvisor` on demand and writes nothing.
|
|
15
|
+
*
|
|
16
|
+
* Failure policy (§0.10.10): everything here is best effort. A failing host call, a throwing check, an unreadable or
|
|
17
|
+
* unwritable state file is logged and swallowed; the notifier backs off for ten minutes after an error so a broken host
|
|
18
|
+
* is not asked again on every turn.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { createHash } from "node:crypto";
|
|
22
|
+
import { withLock as withFileLock } from "../file-lock";
|
|
23
|
+
import { homedir, tmpdir } from "node:os";
|
|
24
|
+
import { join, resolve } from "node:path";
|
|
25
|
+
import { resolveRouting, type RouterConfig } from "../../router/config";
|
|
26
|
+
import { nodePersistFs, renameWithRetry, resolveOutcomesDir } from "../outcomes/persist";
|
|
27
|
+
import type { PersistFs } from "../outcomes/types";
|
|
28
|
+
import { agentModelRef } from "../wire/host-info";
|
|
29
|
+
import { runChecks } from "./findings";
|
|
30
|
+
import type { AdvisorCatalogModel, Finding, FindingTarget, HostAgentView, HostConfigView } from "./findings";
|
|
31
|
+
|
|
32
|
+
export { FINDING_IDS, FINDING_TARGET, HOST_SMALL_MODEL_FAMILIES, SUBSCRIPTION_PROVIDERS, cheapestTitleModel, hostSmallModel, splitModelRef } from "./findings";
|
|
33
|
+
export type { AdvisorCatalogModel, Finding, FindingId, FindingSeverity, FindingTarget, HostAgentView, HostConfigView } from "./findings";
|
|
34
|
+
|
|
35
|
+
export interface AdvisorLogger {
|
|
36
|
+
warn(message: string, extra?: Record<string, unknown>): void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function describeError(error: unknown): string {
|
|
40
|
+
return error instanceof Error ? error.message : String(error);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
44
|
+
return typeof value === "object" && value !== null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ---------------------------------------------------------------------------
|
|
48
|
+
// runAdvisor
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The findings for `cfg` against what the host reports. `hostConfig` = `null` and `catalog` = `null` mean "unknown": the checks
|
|
53
|
+
* that need them stay silent. Never throws: a throwing check is logged and skipped.
|
|
54
|
+
*/
|
|
55
|
+
export function runAdvisor(
|
|
56
|
+
cfg: RouterConfig,
|
|
57
|
+
hostConfig: HostConfigView | null,
|
|
58
|
+
catalog: readonly AdvisorCatalogModel[] | null,
|
|
59
|
+
logger?: AdvisorLogger,
|
|
60
|
+
): Finding[] {
|
|
61
|
+
try {
|
|
62
|
+
return runChecks(cfg, hostConfig, catalog, (check, error) => {
|
|
63
|
+
logger?.warn(`[router] cost doctor: check ${check} failed`, { error: describeError(error) });
|
|
64
|
+
});
|
|
65
|
+
} catch (error) {
|
|
66
|
+
logger?.warn("[router] cost doctor: the advisor failed", { error: describeError(error) });
|
|
67
|
+
return [];
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The view of `ctx.agent.list().data` the advisor reads (entries without a string id are skipped), plus the session's own model when the
|
|
73
|
+
* caller knows it (the host's title pick depends on its provider).
|
|
74
|
+
*/
|
|
75
|
+
export function hostConfigFromAgents(raw: readonly unknown[], primary: HostConfigView["primary"] = null): HostConfigView {
|
|
76
|
+
const agents: HostAgentView[] = [];
|
|
77
|
+
for (const entry of raw) {
|
|
78
|
+
if (!isRecord(entry) || typeof entry.id !== "string" || entry.id === "") continue;
|
|
79
|
+
agents.push({
|
|
80
|
+
id: entry.id,
|
|
81
|
+
model: agentModelRef(entry.model),
|
|
82
|
+
mode: entry.mode === "subagent" || entry.mode === "primary" || entry.mode === "all" ? entry.mode : null,
|
|
83
|
+
hidden: entry.hidden === true,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
return { agents, primary };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The advisor's view of `ctx.model.list().data` (host `Model.Info` records). Read defensively, field by field: a record without a
|
|
91
|
+
* string `providerID`/`id` is skipped, and a missing field stays missing (the checks treat an unknown `enabled`/`tools` as "not
|
|
92
|
+
* usable", never as usable).
|
|
93
|
+
*/
|
|
94
|
+
export function catalogFromModels(raw: readonly unknown[]): AdvisorCatalogModel[] {
|
|
95
|
+
const models: AdvisorCatalogModel[] = [];
|
|
96
|
+
for (const entry of raw) {
|
|
97
|
+
if (!isRecord(entry) || typeof entry.providerID !== "string" || typeof entry.id !== "string" || entry.providerID === "" || entry.id === "") continue;
|
|
98
|
+
const strings = (value: unknown): string[] | undefined => (Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : undefined);
|
|
99
|
+
const capabilities = isRecord(entry.capabilities)
|
|
100
|
+
? {
|
|
101
|
+
tools: typeof entry.capabilities.tools === "boolean" ? entry.capabilities.tools : undefined,
|
|
102
|
+
input: strings(entry.capabilities.input),
|
|
103
|
+
output: strings(entry.capabilities.output),
|
|
104
|
+
}
|
|
105
|
+
: null;
|
|
106
|
+
const limit = isRecord(entry.limit) ? { context: entry.limit.context, input: entry.limit.input, output: entry.limit.output } : null;
|
|
107
|
+
models.push({
|
|
108
|
+
providerID: entry.providerID,
|
|
109
|
+
id: entry.id,
|
|
110
|
+
...(typeof entry.enabled === "boolean" ? { enabled: entry.enabled } : {}),
|
|
111
|
+
...(typeof entry.status === "string" ? { status: entry.status } : {}),
|
|
112
|
+
...(typeof entry.family === "string" ? { family: entry.family } : {}),
|
|
113
|
+
capabilities,
|
|
114
|
+
variants: Array.isArray(entry.variants) ? (entry.variants as ReadonlyArray<{ readonly id?: unknown } | null | undefined>) : null,
|
|
115
|
+
cost: entry.cost,
|
|
116
|
+
limit,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
return models;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The advisor's catalog from a `config.providers()` payload (`{ providers: [{ id, models: { <id>: Model.Info-like } }] }`, which the v2
|
|
124
|
+
* adapter fills with `enabled`, `status`, `family`, `capabilities`, `cost`, `variants` and `limit`). The host lists only enabled models
|
|
125
|
+
* there, so a model of the router's ladder that is missing is "not in the catalog".
|
|
126
|
+
*/
|
|
127
|
+
export function catalogFromProviders(raw: unknown): AdvisorCatalogModel[] | null {
|
|
128
|
+
if (!isRecord(raw) || !Array.isArray(raw.providers)) return null;
|
|
129
|
+
const records: unknown[] = [];
|
|
130
|
+
for (const provider of raw.providers) {
|
|
131
|
+
if (!isRecord(provider) || typeof provider.id !== "string" || !isRecord(provider.models)) continue;
|
|
132
|
+
for (const [key, model] of Object.entries(provider.models)) {
|
|
133
|
+
if (!isRecord(model)) continue;
|
|
134
|
+
records.push({ ...model, providerID: provider.id, id: typeof model.id === "string" ? model.id : key });
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return catalogFromModels(records);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
// Rendering
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
export interface DoctorContext {
|
|
145
|
+
readonly hostKnown: boolean;
|
|
146
|
+
readonly catalogKnown: boolean;
|
|
147
|
+
/** The session's model is known (the title check needs its provider); absent = not asked about. */
|
|
148
|
+
readonly primaryKnown?: boolean;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The file each finding target's snippet belongs in. */
|
|
152
|
+
const FIX_FILE: Readonly<Record<FindingTarget, string>> = {
|
|
153
|
+
host: "opencode.json",
|
|
154
|
+
router: "opencode-model-router.overrides.jsonc",
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
/** The `/router` section "Cost doctor": a header, then one block per finding with its optional fix snippet. */
|
|
158
|
+
export function formatFindings(findings: readonly Finding[], context: DoctorContext = { hostKnown: true, catalogKnown: true }): string[] {
|
|
159
|
+
const base =
|
|
160
|
+
!context.hostKnown && !context.catalogKnown
|
|
161
|
+
? "the host's agent list and model catalog were unavailable, so those checks were skipped"
|
|
162
|
+
: !context.hostKnown
|
|
163
|
+
? "the host's agent list was unavailable, so those checks were skipped"
|
|
164
|
+
: !context.catalogKnown
|
|
165
|
+
? "the host's model catalog was unavailable, so those checks were skipped"
|
|
166
|
+
: null;
|
|
167
|
+
const skipped =
|
|
168
|
+
context.hostKnown && context.catalogKnown && context.primaryKnown === false
|
|
169
|
+
? "the session's model is not known yet, so the title-model check was skipped (ask again after the first turn)"
|
|
170
|
+
: base;
|
|
171
|
+
if (findings.length === 0) return [`Cost doctor: no findings${skipped === null ? "" : ` (${skipped})`}.`];
|
|
172
|
+
const count = (severity: Finding["severity"]): number => findings.filter((f) => f.severity === severity).length;
|
|
173
|
+
const header = `Cost doctor: ${findings.length} finding${findings.length === 1 ? "" : "s"} (${count("warning")} warning, ${count("saving")} saving, ${count("info")} info)${skipped === null ? "" : `; ${skipped}`}`;
|
|
174
|
+
const lines = [header];
|
|
175
|
+
for (const finding of findings) {
|
|
176
|
+
const quiet = finding.bundledTier && finding.severity !== "info" ? " (a tier of the bundled preset you have not modified: listed here, never in a notice)" : "";
|
|
177
|
+
lines.push(` [${finding.severity}] ${finding.id}${finding.subject === "" ? "" : ` (${finding.subject})`}: ${finding.message}${quiet}`);
|
|
178
|
+
// QA-2.4-2: say whose file the fix belongs to; a host fix also has a v1 spelling.
|
|
179
|
+
if (finding.snippet !== null) lines.push(` fix (${FIX_FILE[finding.target]}): ${finding.snippet}`);
|
|
180
|
+
if (finding.snippet !== null && finding.snippetV1 !== null) lines.push(` v1 form (opencode.json): ${finding.snippetV1}`);
|
|
181
|
+
}
|
|
182
|
+
return lines;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* A finding the user should hear about unprompted: a misconfiguration or a concrete saving; plain explanations stay in `/router`, and so
|
|
187
|
+
* do findings on unmodified tiers of a bundled preset (QA-2.4-5: the user did not write those).
|
|
188
|
+
*/
|
|
189
|
+
export function noticeWorthy(findings: readonly Finding[]): boolean {
|
|
190
|
+
return findings.some((f) => f.notify);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const NOTICE_EXCERPT_CHARS = 140;
|
|
194
|
+
|
|
195
|
+
/** One line for the orchestrator's context or the log. `null` when nothing is worth a notice. */
|
|
196
|
+
export function formatNotice(findings: readonly Finding[]): string | null {
|
|
197
|
+
const worth = findings.filter((f) => f.notify);
|
|
198
|
+
const first = worth[0];
|
|
199
|
+
if (first === undefined) return null;
|
|
200
|
+
const warnings = worth.filter((f) => f.severity === "warning").length;
|
|
201
|
+
const savings = worth.length - warnings;
|
|
202
|
+
const excerpt = first.message.length > NOTICE_EXCERPT_CHARS ? `${first.message.slice(0, NOTICE_EXCERPT_CHARS - 1).trimEnd()}…` : first.message;
|
|
203
|
+
return `[model-router] Cost doctor: ${worth.length} finding${worth.length === 1 ? "" : "s"} worth a look (${warnings} warning, ${savings} saving). First: ${excerpt} Run /router for details and config snippets.`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
// Settings
|
|
208
|
+
// ---------------------------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
/** The state and lock file names of one project: the project directory is part of the name (QA-2.4-R2-5), so projects never share a notice. */
|
|
211
|
+
export function noticeFiles(project: string): { readonly state: string; readonly lock: string } {
|
|
212
|
+
const normalized = process.platform === "win32" ? resolve(project).toLowerCase() : resolve(project);
|
|
213
|
+
const id = createHash("sha256").update(normalized).digest("hex").slice(0, 12);
|
|
214
|
+
return { state: `advisor-notice.${id}.json`, lock: `advisor-notice.${id}.lock` };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const STATE_VERSION = 3;
|
|
218
|
+
/** A check never runs more often than this, whatever the configuration says (QA-2.4-7). */
|
|
219
|
+
export const MIN_INTERVAL_MS = 3_600_000;
|
|
220
|
+
/** An unchanged set of findings is mentioned again after this long at the earliest (QA-2.4-5). */
|
|
221
|
+
export const REMINDER_MS = 7 * 24 * 3_600_000;
|
|
222
|
+
/** Wait before checking again when another process holds the notice lock. */
|
|
223
|
+
const BUSY_BACKOFF_MS = 30_000;
|
|
224
|
+
const BACKOFF_AFTER_ERROR_MS = 10 * 60_000;
|
|
225
|
+
|
|
226
|
+
export interface AdvisorSettings {
|
|
227
|
+
/** The D15 directory (`routing.outcomes.path` or the default): the state and lock files live here (context delivery only). */
|
|
228
|
+
readonly dir: string;
|
|
229
|
+
/** The project directory the notice belongs to: it names the state and lock files, so a notice is never delivered into another project. */
|
|
230
|
+
readonly project: string;
|
|
231
|
+
/** Time between checks, at least {@link MIN_INTERVAL_MS}. */
|
|
232
|
+
readonly intervalMs: number;
|
|
233
|
+
/** `context`: handed to the orchestrator's next user turn (advise/enforce; persisted); `log`: written to the log (static/shadow; memory only). */
|
|
234
|
+
readonly deliver: "context" | "log";
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* `null` = the advisor never notifies: v1, `routing.advisor.enabled: false`, `routing.advisor.notify: false`, or no `routing` block at all
|
|
239
|
+
* (today's behaviour, byte for byte: no file, no log line, no host call).
|
|
240
|
+
*/
|
|
241
|
+
export function advisorSettings(
|
|
242
|
+
cfg: RouterConfig,
|
|
243
|
+
host: "v1" | "v2",
|
|
244
|
+
env: { tmpdir?: string; homedir?: string; project?: string } = {},
|
|
245
|
+
): AdvisorSettings | null {
|
|
246
|
+
if (host !== "v2" || cfg.routing === undefined) return null;
|
|
247
|
+
const routing = resolveRouting(cfg, "v2");
|
|
248
|
+
if (!routing.advisor.enabled || !routing.advisor.notify) return null;
|
|
249
|
+
const hours = routing.advisor.noticeIntervalHours;
|
|
250
|
+
return {
|
|
251
|
+
dir: resolveOutcomesDir(routing.outcomes.path, { tmpdir: env.tmpdir ?? tmpdir(), homedir: env.homedir ?? homedir() }),
|
|
252
|
+
project: env.project ?? "",
|
|
253
|
+
intervalMs: Math.max(MIN_INTERVAL_MS, Number.isFinite(hours) ? hours * 3_600_000 : 24 * 3_600_000),
|
|
254
|
+
deliver: routing.engine === "advise" || routing.engine === "enforce" ? "context" : "log",
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ---------------------------------------------------------------------------
|
|
259
|
+
// The persisted state (context delivery only)
|
|
260
|
+
// ---------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
export interface NoticeState {
|
|
263
|
+
readonly version: 3;
|
|
264
|
+
/** The project directory this state is for (also in the file name). */
|
|
265
|
+
readonly project: string;
|
|
266
|
+
/** ISO time of the last completed check. */
|
|
267
|
+
readonly lastRunAt: string;
|
|
268
|
+
/** ISO time the last notice was delivered, or `null`. */
|
|
269
|
+
readonly lastNoticeAt: string | null;
|
|
270
|
+
/** The notice-worthy findings (`id:subject`) the user was last told about, narrowed to those still found at the last check. */
|
|
271
|
+
readonly noticedKeys: readonly string[];
|
|
272
|
+
/** A notice produced and not yet delivered: the next process to take it delivers it, once a check has confirmed it is still current. */
|
|
273
|
+
readonly pendingText: string | null;
|
|
274
|
+
/** The findings that notice was about. */
|
|
275
|
+
readonly pendingKeys: readonly string[] | null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function parseState(text: string): NoticeState | null {
|
|
279
|
+
try {
|
|
280
|
+
const raw: unknown = JSON.parse(text);
|
|
281
|
+
if (!isRecord(raw) || raw.version !== STATE_VERSION || typeof raw.project !== "string") return null;
|
|
282
|
+
if (typeof raw.lastRunAt !== "string" || !Number.isFinite(Date.parse(raw.lastRunAt))) return null;
|
|
283
|
+
const str = (value: unknown): string | null => (typeof value === "string" ? value : null);
|
|
284
|
+
const keys = (value: unknown): string[] | null => (Array.isArray(value) && value.every((key) => typeof key === "string") ? (value as string[]) : null);
|
|
285
|
+
return {
|
|
286
|
+
version: STATE_VERSION,
|
|
287
|
+
project: raw.project,
|
|
288
|
+
lastRunAt: raw.lastRunAt,
|
|
289
|
+
lastNoticeAt: str(raw.lastNoticeAt),
|
|
290
|
+
noticedKeys: keys(raw.noticedKeys) ?? [],
|
|
291
|
+
pendingText: str(raw.pendingText),
|
|
292
|
+
pendingKeys: keys(raw.pendingKeys),
|
|
293
|
+
};
|
|
294
|
+
} catch {
|
|
295
|
+
return null; // not JSON: the caller reports the file as unreadable
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** The notice-worthy findings, as a stable list: the same set always gives the same keys, in any order. */
|
|
300
|
+
function keysOf(findings: readonly Finding[]): string[] {
|
|
301
|
+
return [...new Set(findings.filter((f) => f.notify).map((f) => `${f.id}:${f.subject}`))].sort();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const sameKeys = (a: readonly string[], b: readonly string[]): boolean => a.length === b.length && a.every((key, i) => key === b[i]);
|
|
305
|
+
|
|
306
|
+
/** What the notifier needs of a file system: `PersistFs` plus an exclusive create (the lock). */
|
|
307
|
+
export interface AdvisorFs extends PersistFs {
|
|
308
|
+
/** Create `path` with `data` only if it does not exist yet; `false` when it does. Any other failure rejects. */
|
|
309
|
+
createExclusive(path: string, data: string): Promise<boolean>;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function nodeAdvisorFs(): AdvisorFs {
|
|
313
|
+
return nodePersistFs();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export interface AdvisorNotifierDeps {
|
|
317
|
+
/** Re-read on every poll (hot reload): `null` = inactive. */
|
|
318
|
+
readonly settings: () => AdvisorSettings | null;
|
|
319
|
+
readonly config: () => RouterConfig;
|
|
320
|
+
/** The host's agents and catalog; either may be `null` (unknown). May reject. */
|
|
321
|
+
readonly gather: () => Promise<{ readonly host: HostConfigView | null; readonly catalog: readonly AdvisorCatalogModel[] | null }>;
|
|
322
|
+
readonly logger: AdvisorLogger;
|
|
323
|
+
readonly now?: () => number;
|
|
324
|
+
readonly fs?: AdvisorFs;
|
|
325
|
+
readonly sleep?: (ms: number) => Promise<void>;
|
|
326
|
+
/** Back-off after an error (default 10 minutes). */
|
|
327
|
+
readonly backoffMs?: number;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export interface AdvisorNotifier {
|
|
331
|
+
/**
|
|
332
|
+
* Cheap and synchronous (call it on every orchestrator turn). Starts a background check when one is due (or when a notice a previous
|
|
333
|
+
* process left has still to be confirmed); in log mode the check logs its notice. Never throws.
|
|
334
|
+
*/
|
|
335
|
+
poll(): void;
|
|
336
|
+
/** A context notice may be waiting: one is in memory, or the persisted state has not been read yet. Synchronous, no I/O. */
|
|
337
|
+
maybePending(): boolean;
|
|
338
|
+
/**
|
|
339
|
+
* Hand over the pending context notice, once: across processes the one that claims it (under the lock) delivers it, the others get
|
|
340
|
+
* `null`. Reads the persisted state on its first call. A notice a previous process left is delivered only after a check of this
|
|
341
|
+
* process has confirmed that the findings it was about are still the current ones (otherwise it is dropped). `null` in log mode.
|
|
342
|
+
* Never throws.
|
|
343
|
+
*/
|
|
344
|
+
take(): Promise<string | null>;
|
|
345
|
+
/** Resolves when checks and notice claims in flight have finished, including lock release. */
|
|
346
|
+
settled(): Promise<void>;
|
|
347
|
+
/** Stop accepting work and await every outstanding check/claim. Idempotent. */
|
|
348
|
+
dispose(): Promise<void>;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export function createAdvisorNotifier(deps: AdvisorNotifierDeps): AdvisorNotifier {
|
|
352
|
+
const now = deps.now ?? (() => Date.now());
|
|
353
|
+
const fs = deps.fs ?? nodeAdvisorFs();
|
|
354
|
+
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
|
355
|
+
const backoffMs = deps.backoffMs ?? BACKOFF_AFTER_ERROR_MS;
|
|
356
|
+
/** `null` = not decided yet (context: the state is not read; log: no check has run). */
|
|
357
|
+
let nextDueAt: number | null = null;
|
|
358
|
+
let blockedUntil = 0;
|
|
359
|
+
let inFlight: Promise<void> | null = null;
|
|
360
|
+
const claims = new Set<Promise<string | null>>();
|
|
361
|
+
let disposed = false;
|
|
362
|
+
let disposal: Promise<void> | undefined;
|
|
363
|
+
let loaded: Promise<void> | null = null;
|
|
364
|
+
/** `verified`: produced by a check of this process, or confirmed by one; a notice read from the state file is not, until then. */
|
|
365
|
+
let pending: { readonly text: string; readonly keys: readonly string[]; readonly verified: boolean } | null = null;
|
|
366
|
+
/** The pending notice is in the state file (so claiming it under the lock is meaningful). */
|
|
367
|
+
let pendingPersisted = false;
|
|
368
|
+
/** Log mode, memory only: what was last logged and when. */
|
|
369
|
+
let loggedKeys: ReadonlySet<string> = new Set();
|
|
370
|
+
let loggedAt = 0;
|
|
371
|
+
|
|
372
|
+
const pathsOf = (settings: AdvisorSettings): { readonly dir: string; readonly project: string; readonly state: string; readonly lock: string } => {
|
|
373
|
+
const names = noticeFiles(settings.project);
|
|
374
|
+
return { dir: settings.dir, project: settings.project, state: join(settings.dir, names.state), lock: join(settings.dir, names.lock) };
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
const readState = async (settings: AdvisorSettings): Promise<{ state: NoticeState | null; failed: boolean }> => {
|
|
378
|
+
try {
|
|
379
|
+
const text = await fs.readText(pathsOf(settings).state);
|
|
380
|
+
if (text === null) return { state: null, failed: false };
|
|
381
|
+
const state = parseState(text);
|
|
382
|
+
if (state === null) deps.logger.warn("[router] cost doctor: the notice state file is unreadable or of another version; it is rewritten at the next check");
|
|
383
|
+
else if (state.project !== settings.project) {
|
|
384
|
+
deps.logger.warn("[router] cost doctor: the notice state file belongs to another project; it is ignored and rewritten at the next check");
|
|
385
|
+
return { state: null, failed: false };
|
|
386
|
+
}
|
|
387
|
+
return { state, failed: false };
|
|
388
|
+
} catch (error) {
|
|
389
|
+
deps.logger.warn("[router] cost doctor: could not read the notice state", { error: describeError(error) });
|
|
390
|
+
return { state: null, failed: true };
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const writeState = async (settings: AdvisorSettings, state: NoticeState): Promise<boolean> => {
|
|
395
|
+
try {
|
|
396
|
+
const { dir, state: target } = pathsOf(settings);
|
|
397
|
+
await fs.mkdirp(dir);
|
|
398
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
399
|
+
await fs.writeDurable(temp, `${JSON.stringify(state)}\n`);
|
|
400
|
+
await renameWithRetry(fs, temp, target, sleep);
|
|
401
|
+
return true;
|
|
402
|
+
} catch (error) {
|
|
403
|
+
deps.logger.warn("[router] cost doctor: could not save the notice state; the notice may repeat after a restart", { error: describeError(error) });
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
/** Advisor alone may fall back unlocked: a duplicate notice beats a lost one. */
|
|
409
|
+
const withLock = async <T>(settings: AdvisorSettings, run: () => Promise<T>): Promise<{ status: "ran"; value: T } | { status: "busy" }> => {
|
|
410
|
+
const { dir, lock: lockPath } = pathsOf(settings);
|
|
411
|
+
let started = false;
|
|
412
|
+
try {
|
|
413
|
+
return await withFileLock(fs, dir, lockPath, now, deps.logger, async () => {
|
|
414
|
+
started = true;
|
|
415
|
+
return run();
|
|
416
|
+
});
|
|
417
|
+
} catch (error) {
|
|
418
|
+
if (started) throw error;
|
|
419
|
+
deps.logger.warn("[router] cost doctor: could not lock the notice state; going on without the lock", { error: describeError(error) });
|
|
420
|
+
}
|
|
421
|
+
return { status: "ran", value: await run() };
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
/** Context mode: read the persisted state once per process; a notice a previous process left becomes pending, unverified. */
|
|
425
|
+
const ensureLoaded = (settings: AdvisorSettings): Promise<void> => {
|
|
426
|
+
loaded ??= (async () => {
|
|
427
|
+
const { state } = await readState(settings);
|
|
428
|
+
nextDueAt = state === null ? 0 : Date.parse(state.lastRunAt) + settings.intervalMs;
|
|
429
|
+
if (state?.pendingText != null) {
|
|
430
|
+
pending = { text: state.pendingText, keys: state.pendingKeys ?? [], verified: false };
|
|
431
|
+
pendingPersisted = true;
|
|
432
|
+
}
|
|
433
|
+
})();
|
|
434
|
+
return loaded;
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
const produce = async (): Promise<{ text: string | null; keys: string[] }> => {
|
|
438
|
+
const { host, catalog } = await deps.gather();
|
|
439
|
+
const findings = runAdvisor(deps.config(), host, catalog, deps.logger);
|
|
440
|
+
return { text: noticeWorthy(findings) ? formatNotice(findings) : null, keys: keysOf(findings) };
|
|
441
|
+
};
|
|
442
|
+
|
|
443
|
+
const checkContext = async (settings: AdvisorSettings): Promise<void> => {
|
|
444
|
+
await ensureLoaded(settings);
|
|
445
|
+
if (pending?.verified === true) return; // a notice waits for delivery: no host call
|
|
446
|
+
if (pending === null && now() < (nextDueAt ?? 0)) return;
|
|
447
|
+
// With a notice left by a previous process this check is not throttled: it is what confirms (or drops) it.
|
|
448
|
+
const { text, keys } = await produce();
|
|
449
|
+
const outcome = await withLock(settings, async () => {
|
|
450
|
+
// Decide on the state as it is NOW: another process may have checked or produced a notice meanwhile.
|
|
451
|
+
const { state: fresh } = await readState(settings);
|
|
452
|
+
const t = now();
|
|
453
|
+
const stored = fresh !== null && fresh.pendingText !== null ? fresh : null;
|
|
454
|
+
if (stored !== null && stored.pendingText !== null && sameKeys(stored.pendingKeys ?? [], keys)) {
|
|
455
|
+
// A notice about exactly the findings found now (another process's, or the one a previous process left): current, deliverable.
|
|
456
|
+
pending = { text: stored.pendingText, keys, verified: true };
|
|
457
|
+
pendingPersisted = true;
|
|
458
|
+
nextDueAt = Date.parse(stored.lastRunAt) + settings.intervalMs;
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (stored === null && fresh !== null && t < Date.parse(fresh.lastRunAt) + settings.intervalMs) {
|
|
462
|
+
pending = null; // whoever held it has delivered it
|
|
463
|
+
nextDueAt = Date.parse(fresh.lastRunAt) + settings.intervalMs;
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
// A stored notice about findings that are not the current ones is dropped here (QA-2.4-R2-5): what follows decides afresh.
|
|
467
|
+
const lastNotice = fresh?.lastNoticeAt == null ? null : Date.parse(fresh.lastNoticeAt);
|
|
468
|
+
const noticed = new Set(fresh?.noticedKeys ?? []);
|
|
469
|
+
const hasNew = keys.some((key) => !noticed.has(key));
|
|
470
|
+
const reminder = lastNotice !== null && t - lastNotice >= REMINDER_MS;
|
|
471
|
+
// QA-2.4-R2-6: only a finding not told about yet, or the weekly reminder, is news; a set that merely shrank is not.
|
|
472
|
+
const notify = text !== null && (hasNew || reminder);
|
|
473
|
+
const next: NoticeState = {
|
|
474
|
+
version: STATE_VERSION,
|
|
475
|
+
project: settings.project,
|
|
476
|
+
lastRunAt: new Date(t).toISOString(),
|
|
477
|
+
lastNoticeAt: fresh?.lastNoticeAt ?? null,
|
|
478
|
+
noticedKeys: keys.filter((key) => noticed.has(key)), // what went away and comes back is news again
|
|
479
|
+
pendingText: notify ? text : null,
|
|
480
|
+
pendingKeys: notify ? keys : null,
|
|
481
|
+
};
|
|
482
|
+
const saved = await writeState(settings, next);
|
|
483
|
+
nextDueAt = t + settings.intervalMs;
|
|
484
|
+
pending = notify && text !== null ? { text, keys, verified: true } : null;
|
|
485
|
+
pendingPersisted = notify && saved;
|
|
486
|
+
});
|
|
487
|
+
if (outcome.status === "busy") {
|
|
488
|
+
loaded = null; // read the state again next time: the other process is writing it
|
|
489
|
+
pending = null;
|
|
490
|
+
blockedUntil = now() + BUSY_BACKOFF_MS;
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
/** Log mode: the throttle lives in memory only and no file is read or written. */
|
|
495
|
+
const checkLog = async (settings: AdvisorSettings): Promise<void> => {
|
|
496
|
+
const { text, keys } = await produce();
|
|
497
|
+
const t = now();
|
|
498
|
+
nextDueAt = t + settings.intervalMs;
|
|
499
|
+
if (text === null) {
|
|
500
|
+
loggedKeys = new Set();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (keys.some((key) => !loggedKeys.has(key)) || t - loggedAt >= REMINDER_MS) {
|
|
504
|
+
deps.logger.warn(text);
|
|
505
|
+
loggedAt = t;
|
|
506
|
+
}
|
|
507
|
+
loggedKeys = new Set(keys);
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
const start = (settings: AdvisorSettings): void => {
|
|
511
|
+
if (inFlight !== null) return;
|
|
512
|
+
const run = (settings.deliver === "context" ? checkContext(settings) : checkLog(settings))
|
|
513
|
+
.catch((error: unknown) => {
|
|
514
|
+
blockedUntil = now() + backoffMs;
|
|
515
|
+
deps.logger.warn("[router] cost doctor: the check failed; trying again later", { error: describeError(error) });
|
|
516
|
+
})
|
|
517
|
+
.finally(() => {
|
|
518
|
+
if (inFlight === run) inFlight = null;
|
|
519
|
+
});
|
|
520
|
+
inFlight = run;
|
|
521
|
+
};
|
|
522
|
+
|
|
523
|
+
const settled = async (): Promise<void> => {
|
|
524
|
+
while (inFlight !== null || claims.size > 0) {
|
|
525
|
+
await Promise.all([inFlight, ...claims]);
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
return {
|
|
530
|
+
poll(): void {
|
|
531
|
+
if (disposed) return;
|
|
532
|
+
try {
|
|
533
|
+
const settings = deps.settings();
|
|
534
|
+
if (settings === null || inFlight !== null || now() < blockedUntil) return;
|
|
535
|
+
if (settings.deliver === "context" && pending?.verified === true) return;
|
|
536
|
+
const confirming = settings.deliver === "context" && pending !== null; // a notice from a previous process, not yet confirmed
|
|
537
|
+
if (!confirming && nextDueAt !== null && now() < nextDueAt) return;
|
|
538
|
+
start(settings);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
deps.logger.warn("[router] cost doctor: poll failed", { error: describeError(error) });
|
|
541
|
+
}
|
|
542
|
+
},
|
|
543
|
+
|
|
544
|
+
maybePending(): boolean {
|
|
545
|
+
if (disposed) return false;
|
|
546
|
+
try {
|
|
547
|
+
const settings = deps.settings();
|
|
548
|
+
return settings !== null && settings.deliver === "context" && (pending !== null || loaded === null);
|
|
549
|
+
} catch {
|
|
550
|
+
return false; // a throwing settings reader means nothing is deliverable now; poll reports it
|
|
551
|
+
}
|
|
552
|
+
},
|
|
553
|
+
|
|
554
|
+
take(): Promise<string | null> {
|
|
555
|
+
if (disposed) return Promise.resolve(null);
|
|
556
|
+
const run = (async (): Promise<string | null> => {
|
|
557
|
+
try {
|
|
558
|
+
const settings = deps.settings();
|
|
559
|
+
if (settings === null || settings.deliver !== "context") return null;
|
|
560
|
+
await ensureLoaded(settings);
|
|
561
|
+
const mine = pending;
|
|
562
|
+
if (mine === null || !mine.verified) return null;
|
|
563
|
+
if (!pendingPersisted) {
|
|
564
|
+
pending = null; // it never reached the state file (no coordination possible): deliver it
|
|
565
|
+
return mine.text;
|
|
566
|
+
}
|
|
567
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
568
|
+
const claim = await withLock(settings, async (): Promise<string | null> => {
|
|
569
|
+
const { state: fresh, failed } = await readState(settings);
|
|
570
|
+
if (failed) return mine.text; // the state cannot be read: no coordination, deliver
|
|
571
|
+
if (fresh === null || fresh.pendingText === null) return null; // another process delivered it
|
|
572
|
+
await writeState(settings, {
|
|
573
|
+
...fresh,
|
|
574
|
+
lastNoticeAt: new Date(now()).toISOString(),
|
|
575
|
+
noticedKeys: fresh.pendingKeys ?? fresh.noticedKeys,
|
|
576
|
+
pendingText: null,
|
|
577
|
+
pendingKeys: null,
|
|
578
|
+
});
|
|
579
|
+
return fresh.pendingText;
|
|
580
|
+
});
|
|
581
|
+
if (claim.status === "ran") {
|
|
582
|
+
pending = null;
|
|
583
|
+
return claim.value;
|
|
584
|
+
}
|
|
585
|
+
await sleep(25); // another process holds the lock for a few milliseconds
|
|
586
|
+
}
|
|
587
|
+
return null; // still busy: the notice stays pending for the next turn
|
|
588
|
+
} catch (error) {
|
|
589
|
+
deps.logger.warn("[router] cost doctor: could not take the notice", { error: describeError(error) });
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
})();
|
|
593
|
+
claims.add(run);
|
|
594
|
+
// Use both handlers rather than an ignored rejecting finally() promise.
|
|
595
|
+
void run.then(() => { claims.delete(run); }, () => { claims.delete(run); });
|
|
596
|
+
return run;
|
|
597
|
+
},
|
|
598
|
+
|
|
599
|
+
settled,
|
|
600
|
+
dispose(): Promise<void> {
|
|
601
|
+
disposed = true;
|
|
602
|
+
disposal ??= settled();
|
|
603
|
+
return disposal;
|
|
604
|
+
},
|
|
605
|
+
};
|
|
606
|
+
}
|