@aria-framework/ai 0.3.0 → 0.4.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 (3) hide show
  1. package/health.js +219 -0
  2. package/index.js +2 -0
  3. package/package.json +3 -3
package/health.js ADDED
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Is a provider actually usable right now — and if not, why not.
3
+ *
4
+ * NOTHING IN ANY APP DOES THIS TODAY. A provider is configured and then discovered to be broken by
5
+ * a user pressing a button, which is the worst possible detector: it is slow, it is intermittent,
6
+ * and the person who finds out is the person least able to fix it.
7
+ *
8
+ * ── "UP" AND "LOADED" ARE DIFFERENT FAILURES ────────────────────────────────────────────────────
9
+ * The distinction most tools collapse into one green dot, and the one that matters most for a local
10
+ * model server. LM Studio will happily answer `/models` while the model itself has been evicted —
11
+ * the server is up, and the next completion pays a multi-second reload before it does anything.
12
+ * Reporting that as "healthy" hides the only fact worth knowing. So `reachable` and `modelPresent`
13
+ * are separate, and the UI shows them separately.
14
+ *
15
+ * `modelPresent` is NULL, not false, where residency has no meaning — a hosted API does not load
16
+ * models on demand, and flagging one as "not resident" would be a false alarm on a working
17
+ * provider. Null means "not applicable", false means "we asked and it is not there".
18
+ *
19
+ * ── THE CIRCUIT BREAKER IS WHY THIS IS NOT JUST A PING ──────────────────────────────────────────
20
+ * Without one, every call to a dead provider pays the full timeout before failing over. Annoying at
21
+ * helpdesk volume; fatal at log-triage volume, where it adds the timeout to every request in the
22
+ * queue. After N consecutive failures a provider is marked down and calls skip it entirely until a
23
+ * cooldown expires; one success clears it.
24
+ *
25
+ * STATE IS IN MEMORY, deliberately. A restart re-probes, which is correct — knowledge of what was
26
+ * down five minutes before a restart is not knowledge worth acting on, and persisting it would mean
27
+ * booting into a breaker that trips on stale evidence. `snapshot()` exposes it for an app that
28
+ * wants to render "last good 3h ago" across a restart; nothing here requires that.
29
+ */
30
+
31
+ 'use strict';
32
+
33
+ const DEFAULT_TIMEOUT_MS = 8000;
34
+
35
+ /** Kinds that load models on demand, where residency is a real question. */
36
+ const RESIDENT_KINDS = new Set(['lmstudio', 'openai-compatible']);
37
+
38
+ /** Strip a trailing slash so `${base}/models` never becomes `//models`. */
39
+ const apiRoot = (baseUrl) => String(baseUrl || '').replace(/\/+$/, '');
40
+
41
+ /**
42
+ * The default probe: ask the endpoint what models it has.
43
+ *
44
+ * Distinguishes three outcomes that `listModels()` collapses into an empty array — it returns []
45
+ * for a dead host and [] for a live host with nothing loaded, which is exactly the difference this
46
+ * module exists to report.
47
+ */
48
+ async function defaultProbe(cfg, { fetchImpl = fetch, timeoutMs } = {}) {
49
+ const url = `${apiRoot(cfg.baseUrl)}/models`;
50
+ const started = Date.now();
51
+ let res;
52
+ try {
53
+ res = await fetchImpl(url, {
54
+ headers: cfg.apiKey ? { Authorization: `Bearer ${cfg.apiKey}` } : {},
55
+ signal: AbortSignal.timeout(timeoutMs || cfg.timeoutMs || DEFAULT_TIMEOUT_MS)
56
+ });
57
+ } catch (e) {
58
+ // No answer at all: refused, DNS, TLS, or the timeout fired.
59
+ const timedOut = e && (e.name === 'TimeoutError' || e.name === 'AbortError');
60
+ // `e.message` is a bare "fetch failed" for every connection-level problem — measured against a
61
+ // closed port. Useless to an operator: refused, DNS and TLS all read identically. The reason
62
+ // lives in `e.cause.code`, so lead with that and keep the message as context.
63
+ const cause = (e && e.cause) || {};
64
+ const detail = cause.code || (e && e.message) || 'unreachable';
65
+ return {
66
+ reachable: false, models: [], ms: Date.now() - started,
67
+ error: timedOut
68
+ ? `no response within ${timeoutMs || cfg.timeoutMs || DEFAULT_TIMEOUT_MS}ms`
69
+ : (cause.code ? `${cause.code}${cause.message ? ' — ' + cause.message : ''}` : detail)
70
+ };
71
+ }
72
+ const ms = Date.now() - started;
73
+ if (!res.ok) {
74
+ // It ANSWERED, so the host is reachable — the failure is auth, quota or a bad path, and saying
75
+ // "unreachable" would send an operator to check the network instead of the key.
76
+ return { reachable: true, models: [], ms, error: `HTTP ${res.status}` };
77
+ }
78
+ let payload = null;
79
+ try { payload = await res.json(); } catch (_) { payload = null; }
80
+ const models = Array.isArray(payload && payload.data)
81
+ ? payload.data.map((m) => (m && (m.id || m.name)) || '').filter(Boolean)
82
+ : [];
83
+ return { reachable: true, models, ms, error: null };
84
+ }
85
+
86
+ /**
87
+ * @param {object} opts
88
+ * probe async (cfg) => {reachable, models, ms, error}. Default: GET {baseUrl}/models
89
+ * now () => number, epoch ms. Injected so tests need no timers.
90
+ * cooldownMs how long a provider stays skipped after tripping. Default 60_000.
91
+ * failureThreshold consecutive failures before it trips. Default 3.
92
+ */
93
+ function createHealthChecker(opts = {}) {
94
+ const probe = typeof opts.probe === 'function' ? opts.probe : defaultProbe;
95
+ const now = typeof opts.now === 'function' ? opts.now : () => Date.now();
96
+ const cooldownMs = Number(opts.cooldownMs) || 60000;
97
+ const threshold = Math.max(1, Number(opts.failureThreshold) || 3);
98
+
99
+ /** id -> { failures, downUntil, lastGoodAt, lastError, lastMs, lastCheckedAt, modelPresent } */
100
+ const state = new Map();
101
+ const entry = (id) => {
102
+ if (!state.has(id)) {
103
+ state.set(id, {
104
+ failures: 0, downUntil: 0, lastGoodAt: null,
105
+ lastError: null, lastMs: null, lastCheckedAt: null, modelPresent: null
106
+ });
107
+ }
108
+ return state.get(id);
109
+ };
110
+
111
+ /** Fold one outcome into the breaker. Exposed because a real CALL is better evidence than a probe. */
112
+ function report(id, ok, info = {}) {
113
+ const e = entry(id);
114
+ e.lastCheckedAt = now();
115
+ if (info.ms != null) e.lastMs = info.ms;
116
+ if (ok) {
117
+ e.failures = 0;
118
+ e.downUntil = 0;
119
+ e.lastGoodAt = now();
120
+ e.lastError = null;
121
+ } else {
122
+ e.failures += 1;
123
+ e.lastError = info.error || 'failed';
124
+ // Trip on the Nth failure and re-arm the cooldown on every failure after it, so a provider
125
+ // that keeps failing its probe is not retried the instant the first cooldown lapses.
126
+ if (e.failures >= threshold) e.downUntil = now() + cooldownMs;
127
+ }
128
+ return e;
129
+ }
130
+
131
+ return {
132
+ /**
133
+ * Is this provider currently being skipped?
134
+ *
135
+ * The question a router asks before spending a timeout. Note it does NOT probe — a breaker
136
+ * that probes on every check is the timeout cost it was built to avoid.
137
+ */
138
+ isDown(id) {
139
+ const e = state.get(id);
140
+ return !!(e && e.downUntil && now() < e.downUntil);
141
+ },
142
+
143
+ /** Milliseconds until a downed provider is eligible again; 0 when it is not down. */
144
+ cooldownRemaining(id) {
145
+ const e = state.get(id);
146
+ if (!e || !e.downUntil) return 0;
147
+ return Math.max(0, e.downUntil - now());
148
+ },
149
+
150
+ report,
151
+
152
+ /**
153
+ * Probe one provider and fold the result into the breaker.
154
+ *
155
+ * @param {object} cfg a resolved provider config (see providerStore.resolve)
156
+ * @returns {{id, ok, reachable, modelPresent, models, ms, error, checkedAt}}
157
+ */
158
+ async check(cfg) {
159
+ const id = cfg.id || cfg.provider || 'unknown';
160
+ if (cfg.enabled === false) {
161
+ return {
162
+ id, ok: false, reachable: null, modelPresent: null, models: [], ms: 0,
163
+ error: 'disabled', checkedAt: now()
164
+ };
165
+ }
166
+
167
+ const r = await probe(cfg);
168
+ // Residency only means something where models are loaded on demand.
169
+ let modelPresent = null;
170
+ if (RESIDENT_KINDS.has(cfg.provider) && r.reachable && !r.error) {
171
+ modelPresent = cfg.model ? r.models.includes(cfg.model) : null;
172
+ }
173
+
174
+ // REACHABLE BUT NOT LOADED IS NOT A FAILURE. The call will still succeed; it will just be
175
+ // slow while the server loads the model. Tripping the breaker here would fail over away from
176
+ // a provider that works, which is worse than the latency it was avoiding.
177
+ const ok = r.reachable && !r.error;
178
+ const e = report(id, ok, r);
179
+ e.modelPresent = modelPresent;
180
+
181
+ return {
182
+ id, ok, reachable: r.reachable, modelPresent, models: r.models,
183
+ ms: r.ms, error: r.error, checkedAt: e.lastCheckedAt
184
+ };
185
+ },
186
+
187
+ /** Everything the UI needs for one provider, without probing. */
188
+ status(id) {
189
+ const e = state.get(id);
190
+ if (!e) return { id, status: 'unknown', failures: 0 };
191
+ const down = !!(e.downUntil && now() < e.downUntil);
192
+ return {
193
+ id,
194
+ status: down ? 'down' : (e.lastGoodAt ? 'up' : 'unknown'),
195
+ failures: e.failures,
196
+ lastGoodAt: e.lastGoodAt,
197
+ lastError: e.lastError,
198
+ lastMs: e.lastMs,
199
+ lastCheckedAt: e.lastCheckedAt,
200
+ modelPresent: e.modelPresent,
201
+ cooldownRemainingMs: down ? e.downUntil - now() : 0
202
+ };
203
+ },
204
+
205
+ /** All known state, for persisting across a restart if an app wants to. */
206
+ snapshot() {
207
+ const out = {};
208
+ for (const id of state.keys()) out[id] = this.status(id);
209
+ return out;
210
+ },
211
+
212
+ /** Forget everything — used by tests and by "recheck now" in a UI. */
213
+ reset(id) {
214
+ if (id) state.delete(id); else state.clear();
215
+ }
216
+ };
217
+ }
218
+
219
+ module.exports = { createHealthChecker, defaultProbe, RESIDENT_KINDS };
package/index.js CHANGED
@@ -175,6 +175,8 @@ module.exports = {
175
175
  // install a database package to require this one.
176
176
  get createUsageStore() { return require('./usageStore').createUsageStore; },
177
177
  get createProviderStore() { return require('./providerStore').createProviderStore; },
178
+ // No database behind health, so it loads eagerly like the rest of the seam.
179
+ ...require('./health'),
178
180
  get providerSchemaFor() { return require('./providerStore').schemaFor; },
179
181
  get usageSchemaFor() { return require('./usageStore').schemaFor; },
180
182
  createAiClient,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aria-framework/ai",
3
3
  "description": "Aria App Framework — AI module. A dependency-injected model seam (createAiClient) over several providers (LM Studio / OpenAI-compatible / Anthropic), with a fact-preservation guard, generic Polish and Generate writing engines, and a browser polish widget. Prompts and config stay in the consuming app.",
4
- "version": "0.3.0",
4
+ "version": "0.4.0",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
7
7
  "publishConfig": {
@@ -16,7 +16,7 @@
16
16
  "generate.js",
17
17
  "providers/openai-compatible.js",
18
18
  "providers/anthropic.js",
19
- "browser/ai-polish.js", "usageStore.js", "providerStore.js"
19
+ "browser/ai-polish.js", "usageStore.js", "providerStore.js", "health.js"
20
20
  ],
21
21
  "peerDependencies": {
22
22
  "@aria-framework/db-worker": ">=0.7.0"
@@ -25,6 +25,6 @@
25
25
  "@aria-framework/db-worker": { "optional": true }
26
26
  },
27
27
  "scripts": {
28
- "test": "node test/smoke.js && node test/usageStore.js && node test/providerStore.js"
28
+ "test": "node test/smoke.js && node test/usageStore.js && node test/providerStore.js && node test/health.js"
29
29
  }
30
30
  }