@chatpanel/gateway 0.6.109 → 0.7.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/README.md +24 -4
- package/bin/chatpanel-gateway-bin.mjs +1 -24
- package/bin/chatpanel-gateway.js +3 -97
- package/package.json +1 -7
- package/src/access-log-store.js +1 -45
- package/src/agent.js +2 -256
- package/src/anthropic.js +3 -83
- package/src/backup-decrypt.js +1 -45
- package/src/backup-ingest.js +6 -120
- package/src/bridge-supervisor.js +3 -212
- package/src/bridge.js +4 -252
- package/src/budget.js +1 -117
- package/src/config.js +1 -209
- package/src/configstore.js +1 -181
- package/src/connect-agents.js +22 -179
- package/src/diarize-engine.js +1 -188
- package/src/egress.js +2 -0
- package/src/engine-ledger-store.js +1 -150
- package/src/engine.js +1 -132
- package/src/entitlement-refresh.js +1 -84
- package/src/entitlement.js +1 -76
- package/src/extraction.js +4 -294
- package/src/freegate.js +1 -47
- package/src/gate.js +1 -75
- package/src/gateway-token.js +1 -60
- package/src/history-store.js +1 -251
- package/src/job.js +3 -148
- package/src/knowledge.js +3 -215
- package/src/local-status.js +6 -102
- package/src/log.js +1 -21
- package/src/mcp-cli.js +19 -113
- package/src/mcp.js +34 -546
- package/src/memory-store.js +1 -176
- package/src/memory.js +2 -642
- package/src/model-integrity.js +1 -82
- package/src/model-ledger.js +1 -229
- package/src/model-runtime.js +1 -37
- package/src/models.js +1 -92
- package/src/ner-engine.js +1 -318
- package/src/ner.js +1 -113
- package/src/observability.js +1 -123
- package/src/openai.js +2 -84
- package/src/ort.js +1 -52
- package/src/parakeet-engine.js +2 -228
- package/src/pocket-tts-engine.js +1 -520
- package/src/prefs-store.js +1 -149
- package/src/project-store.js +1 -139
- package/src/project.js +1 -171
- package/src/recruit.js +3 -424
- package/src/recruiting.js +1 -93
- package/src/redact.js +2 -123
- package/src/responses.js +2 -80
- package/src/router.js +1 -292
- package/src/rrf.js +1 -93
- package/src/scorecard-store.js +1 -92
- package/src/scorecard.js +1 -336
- package/src/search-index.js +2 -134
- package/src/secure-fetch.js +1 -58
- package/src/sentencepiece.js +1 -184
- package/src/server.js +10 -2290
- package/src/service.js +11 -189
- package/src/shape.js +5 -121
- package/src/sqlite-store.js +3 -212
- package/src/stream.js +5 -182
- package/src/structured.js +4 -902
- package/src/stt-engine.js +1 -486
- package/src/stt-models.js +1 -144
- package/src/subject-kinds.js +1 -6
- package/src/subject-name.js +1 -97
- package/src/team-board.js +6 -338
- package/src/team-record.js +1 -226
- package/src/team-store.js +1 -261
- package/src/team.js +1 -303
- package/src/toolrelay.js +3 -122
- package/src/tts-engine.js +1 -453
- package/src/tts-models.js +1 -254
- package/src/tts-remote.js +1 -109
- package/src/tts-voice-resolve.js +1 -78
- package/src/tts-voices.js +1 -192
- package/src/update.js +1 -305
package/src/model-integrity.js
CHANGED
|
@@ -1,82 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// The gateway downloads ONNX model weights (NER / Whisper / Parakeet) from the
|
|
4
|
-
// dl.chatpanel.net mirror or Hugging Face and loads them straight into an ONNX
|
|
5
|
-
// runtime. A compromised mirror, an HF repo takeover, or a MITM on a downgraded
|
|
6
|
-
// connection could therefore feed a malicious model into native code. This module
|
|
7
|
-
// verifies a downloaded model's weight files against committed SHA-256 hashes.
|
|
8
|
-
//
|
|
9
|
-
// Design (deliberately non-breaking):
|
|
10
|
-
// • Hashes live in the committed `model-hashes.json` — a { modelId: { relPath:
|
|
11
|
-
// sha256 } } map generated on a TRUSTED host by `tools/gen-model-hashes.mjs`.
|
|
12
|
-
// • FAIL-CLOSED only on a genuine mismatch: a listed file whose hash differs is
|
|
13
|
-
// deleted and the load is refused (throws). That's the security event.
|
|
14
|
-
// • WARN-AND-ALLOW everywhere else: a model not in the manifest, or a listed file
|
|
15
|
-
// not yet on disk, logs loudly and proceeds — so an empty/partial manifest never
|
|
16
|
-
// bricks model loading, and shipping the mechanism before the hashes are
|
|
17
|
-
// populated is safe. (Populate on a trusted machine to switch protection on.)
|
|
18
|
-
// • Verified on the DOWNLOAD path (when weights first arrive from the network —
|
|
19
|
-
// the supply-chain moment), not on every offline load (avoids re-hashing 100s of
|
|
20
|
-
// MB each boot).
|
|
21
|
-
|
|
22
|
-
import { createHash } from 'node:crypto';
|
|
23
|
-
import { readFileSync, existsSync, rmSync } from 'node:fs';
|
|
24
|
-
import { join } from 'node:path';
|
|
25
|
-
import { fileURLToPath } from 'node:url';
|
|
26
|
-
|
|
27
|
-
const MANIFEST_PATH = fileURLToPath(new URL('./model-hashes.json', import.meta.url));
|
|
28
|
-
let _manifest = null;
|
|
29
|
-
|
|
30
|
-
// { modelId: { 'onnx/model_quantized.onnx': '<sha256>' , … } }. Keys starting with
|
|
31
|
-
// '_' are metadata (schema note) and ignored. Missing/invalid file → empty map
|
|
32
|
-
// (verification simply becomes warn-and-allow for everything).
|
|
33
|
-
export function loadHashManifest(path = MANIFEST_PATH) {
|
|
34
|
-
if (_manifest && path === MANIFEST_PATH) return _manifest;
|
|
35
|
-
let parsed = {};
|
|
36
|
-
try {
|
|
37
|
-
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
38
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
39
|
-
if (!k.startsWith('_') && v && typeof v === 'object') parsed[k] = v;
|
|
40
|
-
}
|
|
41
|
-
} catch { parsed = {}; }
|
|
42
|
-
if (path === MANIFEST_PATH) _manifest = parsed;
|
|
43
|
-
return parsed;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export function sha256File(path) {
|
|
47
|
-
return createHash('sha256').update(readFileSync(path)).digest('hex');
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Verify a model's weight files under `modelsDir`. Returns a result object; THROWS
|
|
51
|
-
// only on a real hash mismatch (fail-closed). `modelsDir` is the model cache root
|
|
52
|
-
// (e.g. ~/.chatpanel/models); the per-model dir is modelsDir/<org>/<name>.
|
|
53
|
-
/**
|
|
54
|
-
* @param {string} modelId
|
|
55
|
-
* @param {{ modelsDir?: string, log?: (msg: string) => void, manifest?: Record<string, Record<string, string>> }} [opts]
|
|
56
|
-
*/
|
|
57
|
-
export function verifyModelWeights(modelId, { modelsDir, log = () => {}, manifest = loadHashManifest() } = {}) {
|
|
58
|
-
const expected = manifest[modelId];
|
|
59
|
-
if (!expected || Object.keys(expected).length === 0) {
|
|
60
|
-
log(`[integrity] no recorded hashes for ${modelId} — skipping verification `
|
|
61
|
-
+ `(run tools/gen-model-hashes.mjs on a trusted host to enable)`);
|
|
62
|
-
return { verified: false, reason: 'unlisted', checked: 0 };
|
|
63
|
-
}
|
|
64
|
-
const dir = join(modelsDir, ...modelId.split('/'));
|
|
65
|
-
let checked = 0;
|
|
66
|
-
for (const [rel, wantSha] of Object.entries(expected)) {
|
|
67
|
-
const p = join(dir, ...rel.split('/'));
|
|
68
|
-
if (!existsSync(p)) { log(`[integrity] ${modelId}: listed file ${rel} not on disk — skipping`); continue; }
|
|
69
|
-
const gotSha = sha256File(p);
|
|
70
|
-
if (gotSha !== wantSha) {
|
|
71
|
-
try { rmSync(p); } catch { /* best effort */ }
|
|
72
|
-
throw new Error(
|
|
73
|
-
`[integrity] ${modelId}/${rel} SHA-256 mismatch `
|
|
74
|
-
+ `(expected ${wantSha.slice(0, 12)}…, got ${gotSha.slice(0, 12)}…) — `
|
|
75
|
-
+ `deleted the file and refusing to load a tampered model`,
|
|
76
|
-
);
|
|
77
|
-
}
|
|
78
|
-
checked++;
|
|
79
|
-
}
|
|
80
|
-
if (checked) log(`[integrity] ${modelId}: ${checked} weight file(s) verified ✓`);
|
|
81
|
-
return { verified: checked > 0, reason: checked ? 'ok' : 'no-files-present', checked };
|
|
82
|
-
}
|
|
1
|
+
import{createHash as m}from"node:crypto";import{readFileSync as p,existsSync as g,rmSync as y}from"node:fs";import{join as d}from"node:path";import{fileURLToPath as $}from"node:url";const f=$(new URL("./model-hashes.json",import.meta.url));let a=null;function k(e=f){if(a&&e===f)return a;let i={};try{const n=JSON.parse(p(e,"utf8"));for(const[s,t]of Object.entries(n))!s.startsWith("_")&&t&&typeof t=="object"&&(i[s]=t)}catch{i={}}return e===f&&(a=i),i}function S(e){return m("sha256").update(p(e)).digest("hex")}function b(e,{modelsDir:i,log:n=()=>{},manifest:s=k()}={}){const t=s[e];if(!t||Object.keys(t).length===0)return n(`[integrity] no recorded hashes for ${e} — skipping verification (run tools/gen-model-hashes.mjs on a trusted host to enable)`),{verified:!1,reason:"unlisted",checked:0};const u=d(i,...e.split("/"));let r=0;for(const[o,h]of Object.entries(t)){const c=d(u,...o.split("/"));if(!g(c)){n(`[integrity] ${e}: listed file ${o} not on disk — skipping`);continue}const l=S(c);if(l!==h){try{y(c)}catch{}throw new Error(`[integrity] ${e}/${o} SHA-256 mismatch (expected ${h.slice(0,12)}…, got ${l.slice(0,12)}…) — deleted the file and refusing to load a tampered model`)}r++}return r&&n(`[integrity] ${e}: ${r} weight file(s) verified ✓`),{verified:r>0,reason:r?"ok":"no-files-present",checked:r}}export{k as loadHashManifest,S as sha256File,b as verifyModelWeights};
|
package/src/model-ledger.js
CHANGED
|
@@ -1,229 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// The MODEL LEDGER — an engine's record, the scorecard pattern applied to engines
|
|
3
|
-
// (architecture-pillars.md §13.2).
|
|
4
|
-
//
|
|
5
|
-
// One chained, store-attested ledger per ENGINE — keyed like the scorecard's `byEngine`
|
|
6
|
-
// (`model:<provider>/<model>`, `harness:<id>`), because the same model at two providers is
|
|
7
|
-
// two records: availability, cost and latency are the provider's, not the model's. Entries
|
|
8
|
-
// are FACTS the runner and the gateway observe, never claims:
|
|
9
|
-
//
|
|
10
|
-
// call one turn: time to first token, total, tokens in/out, cost when priced, was
|
|
11
|
-
// the JSON valid, were the tool calls valid, did it come back empty / refused
|
|
12
|
-
// / truncated, did it succeed
|
|
13
|
-
// declined it did not answer, and why (unavailable · auth · rate · credits · timeout ·
|
|
14
|
-
// context) — the availability signal
|
|
15
|
-
// rotated-from a task left it for another engine mid-run
|
|
16
|
-
// rating a task's verdict, attributed to the engine that served it (and to the agent)
|
|
17
|
-
// capability a proof: it was asked for X and it did / did not deliver
|
|
18
|
-
// price what a token costs here — from the provider's list or typed by a person
|
|
19
|
-
//
|
|
20
|
-
// `summarizeEngine(entries)` → the ENGINE CARD: availability, reliability, latency, cost,
|
|
21
|
-
// capability proofs (a capability with three failed proofs is WITHDRAWN until a person
|
|
22
|
-
// re-enables it), quality by job kind, the last refs. model-candidates.js `applyCard` hands
|
|
23
|
-
// the card to `applyOverride`: observed quality / latency / cost replace the name-based
|
|
24
|
-
// guess wherever there is enough history (≥ `minCalls`), the guess stays as the prior until
|
|
25
|
-
// then, and the result says which it used (`observed[]`). Reach is never learned, only
|
|
26
|
-
// typed — a ledger cannot move a model closer than the URL says.
|
|
27
|
-
//
|
|
28
|
-
// Hashing, attestation and chain verification are scorecard.js's, unchanged: the same store
|
|
29
|
-
// marks both, the same `verifyChain` checks both.
|
|
30
|
-
|
|
31
|
-
import { canonical, sha256, engineKey, normalizeEngine } from './scorecard.js';
|
|
32
|
-
export { verifyChain, attest, verifyAttested } from './scorecard.js';
|
|
33
|
-
|
|
34
|
-
export const LEDGER_VERSION = 1;
|
|
35
|
-
export const LEDGER_ENTRY_KINDS = Object.freeze(['call', 'declined', 'rotated-from', 'rating', 'capability', 'price']);
|
|
36
|
-
export const DECLINE_REASONS = Object.freeze(['unavailable', 'auth', 'rate', 'credits', 'timeout', 'context', 'other']);
|
|
37
|
-
export const STRUCTURED = Object.freeze(['ok', 'bad', 'n/a']);
|
|
38
|
-
/** Failed proofs before a capability leaves the card. */
|
|
39
|
-
export const WITHDRAW_AFTER = 3;
|
|
40
|
-
/** Calls before an observed number outranks the name-based guess. Small; configurable. */
|
|
41
|
-
export const DEFAULT_MIN_CALLS = 5;
|
|
42
|
-
|
|
43
|
-
const n0 = (v) => Math.max(0, Math.round(Number(v) || 0));
|
|
44
|
-
const money = (v) => (v == null || v === '' || !Number.isFinite(Number(v)) ? undefined : Math.max(0, Number(v)));
|
|
45
|
-
const clamp01 = (n) => Math.max(0, Math.min(1, Number(n) || 0));
|
|
46
|
-
const bool = (v) => v === true;
|
|
47
|
-
const str = (v, n = 120) => (v == null || v === '' ? undefined : String(v).slice(0, n));
|
|
48
|
-
const strip = (o) => { for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k]; return o; };
|
|
49
|
-
|
|
50
|
-
/** The ledger's key for an engine — the scorecard's `engineKey`, so the two join. */
|
|
51
|
-
export function ledgerKey(engine) { return engineKey(engine); }
|
|
52
|
-
|
|
53
|
-
/** A call fact, normalized. Rates are computed later; here every field is a plain observation. */
|
|
54
|
-
export function normalizeCall(c) {
|
|
55
|
-
const src = c && typeof c === 'object' ? c : {};
|
|
56
|
-
return strip({
|
|
57
|
-
ok: src.ok !== false,
|
|
58
|
-
ttftMs: src.ttftMs != null ? n0(src.ttftMs) : undefined,
|
|
59
|
-
totalMs: src.totalMs != null ? n0(src.totalMs) : undefined,
|
|
60
|
-
tokensIn: src.tokensIn != null ? n0(src.tokensIn) : undefined,
|
|
61
|
-
tokensOut: src.tokensOut != null ? n0(src.tokensOut) : undefined,
|
|
62
|
-
// The total when the split is unknown (a harness reports one number, or none).
|
|
63
|
-
tokens: src.tokens != null && src.tokensIn == null && src.tokensOut == null ? n0(src.tokens) : undefined,
|
|
64
|
-
cost: money(src.cost),
|
|
65
|
-
structured: STRUCTURED.includes(src.structured) ? src.structured : 'n/a',
|
|
66
|
-
toolCalls: src.toolCalls && typeof src.toolCalls === 'object' ? { asked: n0(src.toolCalls.asked), valid: Math.min(n0(src.toolCalls.asked), n0(src.toolCalls.valid)) } : undefined,
|
|
67
|
-
empty: bool(src.empty) || undefined,
|
|
68
|
-
refused: bool(src.refused) || undefined,
|
|
69
|
-
truncated: bool(src.truncated) || undefined,
|
|
70
|
-
});
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* A new entry chained onto `prev`. `fact.engine` is required and keyed; the rest is by kind.
|
|
75
|
-
* Pure apart from the digest; the store attests.
|
|
76
|
-
*/
|
|
77
|
-
export async function makeLedgerEntry(fact, prev, { now = () => Date.now(), subtle } = {}) {
|
|
78
|
-
if (!fact || typeof fact !== 'object') throw new Error('model-ledger: an entry needs a fact');
|
|
79
|
-
if (!LEDGER_ENTRY_KINDS.includes(fact.kind)) throw new Error(`model-ledger: kind must be one of ${LEDGER_ENTRY_KINDS.join(', ')}`);
|
|
80
|
-
const engine = normalizeEngine(fact.engine);
|
|
81
|
-
if (!engine) throw new Error('model-ledger: engine required');
|
|
82
|
-
const key = engineKey(engine);
|
|
83
|
-
if (prev && prev.key !== key) throw new Error(`model-ledger: entry for ${key} chained onto ${prev.key}`);
|
|
84
|
-
const e = strip({
|
|
85
|
-
v: LEDGER_VERSION,
|
|
86
|
-
seq: prev ? prev.seq + 1 : 0,
|
|
87
|
-
key,
|
|
88
|
-
engine,
|
|
89
|
-
kind: fact.kind,
|
|
90
|
-
at: Number(fact.at) || now(),
|
|
91
|
-
runId: str(fact.runId), taskId: str(fact.taskId), agentId: str(fact.agentId), jobKind: str(fact.jobKind, 60),
|
|
92
|
-
call: fact.kind === 'call' ? normalizeCall(fact.call) : undefined,
|
|
93
|
-
declined: fact.kind === 'declined' ? { reason: DECLINE_REASONS.includes(fact.declined?.reason) ? fact.declined.reason : 'other', ...(fact.declined?.error ? { error: String(fact.declined.error).slice(0, 300) } : {}) } : undefined,
|
|
94
|
-
rotated: fact.kind === 'rotated-from' ? strip({ to: engineKey(fact.rotated?.to) || undefined, reason: str(fact.rotated?.reason, 300) }) : undefined,
|
|
95
|
-
rating: fact.kind === 'rating' ? strip({ by: String(fact.rating?.by || 'person').slice(0, 40), score: clamp01(fact.rating?.score), jobKind: str(fact.rating?.jobKind || fact.jobKind, 60), agentId: str(fact.rating?.agentId || fact.agentId) }) : undefined,
|
|
96
|
-
capability: fact.kind === 'capability' ? { id: String(fact.capability?.id || '').slice(0, 40), proved: bool(fact.capability?.proved) } : undefined,
|
|
97
|
-
price: fact.kind === 'price' ? strip({ per1kIn: money(fact.price?.per1kIn) ?? 0, per1kOut: money(fact.price?.per1kOut) ?? 0, source: fact.price?.source === 'user' ? 'user' : 'provider', currency: str(fact.price?.currency, 8) }) : undefined,
|
|
98
|
-
refs: Array.isArray(fact.refs) && fact.refs.length ? fact.refs.map(String).slice(0, 12) : undefined,
|
|
99
|
-
prev: prev ? prev.hash : null,
|
|
100
|
-
});
|
|
101
|
-
if (e.kind === 'capability' && !e.capability.id) throw new Error('model-ledger: capability.id required');
|
|
102
|
-
const { hash: _h, sig: _s, ...hashable } = e;
|
|
103
|
-
e.hash = await sha256(canonical(hashable), { subtle });
|
|
104
|
-
return e;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
const percentile = (xs, p) => {
|
|
108
|
-
if (!xs.length) return null;
|
|
109
|
-
const s = [...xs].sort((a, b) => a - b);
|
|
110
|
-
return s[Math.min(s.length - 1, Math.max(0, Math.ceil((p / 100) * s.length) - 1))];
|
|
111
|
-
};
|
|
112
|
-
const mean = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null);
|
|
113
|
-
const rate = (n, of) => (of ? Math.round((n / of) * 1000) / 1000 : null);
|
|
114
|
-
const r3 = (v) => (v == null ? null : Math.round(v * 1000) / 1000);
|
|
115
|
-
|
|
116
|
-
/**
|
|
117
|
-
* The engine card. `minCalls` marks it `observed` once there is enough history; `now`
|
|
118
|
-
* bounds the by-hour availability band (the last 24 h) and the "declining right now" check.
|
|
119
|
-
*/
|
|
120
|
-
export function summarizeEngine(entries, { minCalls = DEFAULT_MIN_CALLS, now = Date.now(), recent = 5 } = {}) {
|
|
121
|
-
const list = (entries || []).filter((e) => e && e.kind);
|
|
122
|
-
const calls = list.filter((e) => e.kind === 'call');
|
|
123
|
-
const declines = list.filter((e) => e.kind === 'declined');
|
|
124
|
-
const attempts = calls.length + declines.length;
|
|
125
|
-
// Availability: declines over attempts, and the last 24 hours in bands of one.
|
|
126
|
-
const byHour = Array.from({ length: 24 }, () => ({ calls: 0, declines: 0 }));
|
|
127
|
-
for (const e of [...calls, ...declines]) {
|
|
128
|
-
const h = Math.floor((now - e.at) / 3600000);
|
|
129
|
-
if (h >= 0 && h < 24) byHour[23 - h][e.kind === 'call' ? 'calls' : 'declines'] += 1;
|
|
130
|
-
}
|
|
131
|
-
const declinesBy = {};
|
|
132
|
-
for (const e of declines) declinesBy[e.declined.reason] = (declinesBy[e.declined.reason] || 0) + 1;
|
|
133
|
-
// Declining right now: the last three attempts all declined, within the last hour.
|
|
134
|
-
const lastThree = [...calls, ...declines].sort((a, b) => a.at - b.at).slice(-3);
|
|
135
|
-
const decliningNow = lastThree.length === 3 && lastThree.every((e) => e.kind === 'declined' && now - e.at < 3600000);
|
|
136
|
-
// Reliability: each a rate over the calls it applies to.
|
|
137
|
-
const withJson = calls.filter((e) => e.call.structured !== 'n/a');
|
|
138
|
-
const withTools = calls.filter((e) => e.call.toolCalls?.asked);
|
|
139
|
-
const reliability = {
|
|
140
|
-
failRate: rate(calls.filter((e) => !e.call.ok).length, calls.length),
|
|
141
|
-
empty: rate(calls.filter((e) => e.call.empty).length, calls.length),
|
|
142
|
-
refused: rate(calls.filter((e) => e.call.refused).length, calls.length),
|
|
143
|
-
truncated: rate(calls.filter((e) => e.call.truncated).length, calls.length),
|
|
144
|
-
badJson: rate(withJson.filter((e) => e.call.structured === 'bad').length, withJson.length),
|
|
145
|
-
badToolCall: rate(withTools.reduce((n, e) => n + (e.call.toolCalls.asked - e.call.toolCalls.valid), 0), withTools.reduce((n, e) => n + e.call.toolCalls.asked, 0)),
|
|
146
|
-
};
|
|
147
|
-
// Latency.
|
|
148
|
-
const ttft = calls.map((e) => e.call.ttftMs).filter((v) => v != null);
|
|
149
|
-
const total = calls.map((e) => e.call.totalMs).filter((v) => v != null);
|
|
150
|
-
const latency = { ttft: { p50: percentile(ttft, 50), p95: percentile(ttft, 95), n: ttft.length }, total: { p50: percentile(total, 50), p95: percentile(total, 95), n: total.length } };
|
|
151
|
-
// Cost: the latest price entry prices every call that reported tokens; a call that
|
|
152
|
-
// reported its own cost is taken as is; otherwise the mean tokens per call stands in.
|
|
153
|
-
const price = list.filter((e) => e.kind === 'price').at(-1)?.price || null;
|
|
154
|
-
const costs = calls.map((e) => (e.call.cost != null ? e.call.cost : price && (e.call.tokensIn != null || e.call.tokensOut != null) ? ((e.call.tokensIn || 0) * price.per1kIn + (e.call.tokensOut || 0) * price.per1kOut) / 1000 : null)).filter((v) => v != null);
|
|
155
|
-
const tokens = calls.map((e) => (e.call.tokensIn || 0) + (e.call.tokensOut || 0) + (e.call.tokens || 0)).filter((v) => v > 0);
|
|
156
|
-
const cost = { perTask: r3(mean(costs)), priced: costs.length, tokensPerTask: tokens.length ? Math.round(mean(tokens)) : null, ...(price ? { per1kIn: price.per1kIn, per1kOut: price.per1kOut, source: price.source } : {}) };
|
|
157
|
-
// Capability proofs: asked vs proved; withdrawn after WITHDRAW_AFTER failures unless a
|
|
158
|
-
// later proof succeeded (a person re-enabling it is a proof they record).
|
|
159
|
-
const proofs = {};
|
|
160
|
-
for (const e of list.filter((x) => x.kind === 'capability')) {
|
|
161
|
-
const p = proofs[e.capability.id] || (proofs[e.capability.id] = { asked: 0, proved: 0, failedSince: 0 });
|
|
162
|
-
p.asked += 1;
|
|
163
|
-
if (e.capability.proved) { p.proved += 1; p.failedSince = 0; } else p.failedSince += 1;
|
|
164
|
-
}
|
|
165
|
-
const capabilities = {
|
|
166
|
-
proved: Object.keys(proofs).filter((id) => proofs[id].proved > 0 && proofs[id].failedSince < WITHDRAW_AFTER).sort(),
|
|
167
|
-
withdrawn: Object.keys(proofs).filter((id) => proofs[id].failedSince >= WITHDRAW_AFTER).sort(),
|
|
168
|
-
proofs: Object.fromEntries(Object.entries(proofs).map(([id, p]) => [id, { asked: p.asked, proved: p.proved }])),
|
|
169
|
-
};
|
|
170
|
-
// Quality: mean rating, overall and by job kind.
|
|
171
|
-
const ratings = list.filter((e) => e.kind === 'rating');
|
|
172
|
-
const byJobKind = {};
|
|
173
|
-
for (const e of ratings) { const k = e.rating.jobKind || 'any'; (byJobKind[k] = byJobKind[k] || []).push(e.rating.score); }
|
|
174
|
-
const quality = {
|
|
175
|
-
overall: { avg: r3(mean(ratings.map((e) => e.rating.score))), count: ratings.length },
|
|
176
|
-
byJobKind: Object.fromEntries(Object.entries(byJobKind).map(([k, xs]) => [k, { avg: r3(mean(xs)), count: xs.length }])),
|
|
177
|
-
};
|
|
178
|
-
const rotatedFrom = list.filter((e) => e.kind === 'rotated-from').length;
|
|
179
|
-
return {
|
|
180
|
-
key: list[0]?.key || null,
|
|
181
|
-
engine: list[0]?.engine || null,
|
|
182
|
-
entries: list.length,
|
|
183
|
-
calls: calls.length,
|
|
184
|
-
declines: declines.length,
|
|
185
|
-
observed: calls.length >= minCalls,
|
|
186
|
-
availability: { rate: attempts ? r3(1 - declines.length / attempts) : null, attempts, declinesBy, byHour, decliningNow },
|
|
187
|
-
reliability,
|
|
188
|
-
latency,
|
|
189
|
-
cost,
|
|
190
|
-
capabilities,
|
|
191
|
-
quality,
|
|
192
|
-
rotatedFrom,
|
|
193
|
-
refs: [...new Set(list.flatMap((e) => e.refs || []))].slice(-recent),
|
|
194
|
-
since: list[0]?.at || null,
|
|
195
|
-
last: list.at(-1)?.at || null,
|
|
196
|
-
head: list.at(-1)?.hash || null,
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/**
|
|
201
|
-
* The override a card yields for model-candidates.js `applyOverride` — only the fields it
|
|
202
|
-
* has enough history for. `quality` is the mean rating (for `jobKind` when the card has
|
|
203
|
-
* ratings for it, else overall); `latencyMs` the observed p50 to first token (total when no
|
|
204
|
-
* ttft was recorded); `costPer1k` from the price when one is known; `available: false`
|
|
205
|
-
* only while it is declining right now. Returns `{ override, observed }`.
|
|
206
|
-
*
|
|
207
|
-
* Lives here, beside the card it reads, so recruit.js and a store without a router can use
|
|
208
|
-
* it; `applyCard` (the override over the guess) stays in model-candidates.js beside
|
|
209
|
-
* `applyOverride`, the seam it feeds.
|
|
210
|
-
*/
|
|
211
|
-
export function cardOverride(card, { minCalls = DEFAULT_MIN_CALLS, jobKind = null } = {}) {
|
|
212
|
-
const override = {}; const observed = [];
|
|
213
|
-
if (!card) return { override, observed };
|
|
214
|
-
const q = (jobKind && card.quality?.byJobKind?.[jobKind]?.count >= minCalls) ? card.quality.byJobKind[jobKind] : card.quality?.overall;
|
|
215
|
-
if (q && q.count >= minCalls && q.avg != null) { override.quality = q.avg; observed.push('quality'); }
|
|
216
|
-
const lat = card.latency?.ttft?.n >= minCalls ? card.latency.ttft.p50 : card.latency?.total?.n >= minCalls ? card.latency.total.p50 : null;
|
|
217
|
-
if (lat != null) { override.latencyMs = lat; observed.push('latencyMs'); }
|
|
218
|
-
// Six places, not three: a per-1k price is often 0.0004, and rounding it to 0 made a paid model read as free.
|
|
219
|
-
if (card.cost?.per1kIn != null && card.cost?.per1kOut != null) { override.costPer1k = Math.round(((card.cost.per1kIn + card.cost.per1kOut) / 2) * 1e6) / 1e6; observed.push('costPer1k'); }
|
|
220
|
-
if (card.availability?.decliningNow) { override.available = false; observed.push('available'); }
|
|
221
|
-
return { override, observed };
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// `applyCard` — the card over the name-based guess — lives in model-candidates.js beside
|
|
225
|
-
// `applyOverride`, the seam it feeds; this module stays importable by a store that has no
|
|
226
|
-
// router (the gateway vendors it with scorecard.js only).
|
|
227
|
-
// Agent scores normalised by engine (§13.3) live beside the card they adjust: scorecard.js
|
|
228
|
-
// `adjustSummary` and `fit(job, type, summary, { qualityOf })`.
|
|
229
|
-
export { adjustSummary } from './scorecard.js';
|
|
1
|
+
import{canonical as U,sha256 as $,engineKey as w,normalizeEngine as G}from"./scorecard.js";import{verifyChain as oe,attest as re,verifyAttested as ie}from"./scorecard.js";const H=1,T=Object.freeze(["call","declined","rotated-from","rating","capability","price"]),W=Object.freeze(["unavailable","auth","rate","credits","timeout","context","other"]),B=Object.freeze(["ok","bad","n/a"]),R=3,A=5,c=e=>Math.max(0,Math.round(Number(e)||0)),S=e=>e==null||e===""||!Number.isFinite(Number(e))?void 0:Math.max(0,Number(e)),V=e=>Math.max(0,Math.min(1,Number(e)||0)),y=e=>e===!0,u=(e,n=120)=>e==null||e===""?void 0:String(e).slice(0,n),h=e=>{for(const n of Object.keys(e))e[n]===void 0&&delete e[n];return e};function X(e){return w(e)}function Y(e){const n=e&&typeof e=="object"?e:{};return h({ok:n.ok!==!1,ttftMs:n.ttftMs!=null?c(n.ttftMs):void 0,totalMs:n.totalMs!=null?c(n.totalMs):void 0,tokensIn:n.tokensIn!=null?c(n.tokensIn):void 0,tokensOut:n.tokensOut!=null?c(n.tokensOut):void 0,tokens:n.tokens!=null&&n.tokensIn==null&&n.tokensOut==null?c(n.tokens):void 0,cost:S(n.cost),structured:B.includes(n.structured)?n.structured:"n/a",toolCalls:n.toolCalls&&typeof n.toolCalls=="object"?{asked:c(n.toolCalls.asked),valid:Math.min(c(n.toolCalls.asked),c(n.toolCalls.valid))}:void 0,empty:y(n.empty)||void 0,refused:y(n.refused)||void 0,truncated:y(n.truncated)||void 0})}async function Z(e,n,{now:s=()=>Date.now(),subtle:a}={}){if(!e||typeof e!="object")throw new Error("model-ledger: an entry needs a fact");if(!T.includes(e.kind))throw new Error(`model-ledger: kind must be one of ${T.join(", ")}`);const o=G(e.engine);if(!o)throw new Error("model-ledger: engine required");const l=w(o);if(n&&n.key!==l)throw new Error(`model-ledger: entry for ${l} chained onto ${n.key}`);const i=h({v:H,seq:n?n.seq+1:0,key:l,engine:o,kind:e.kind,at:Number(e.at)||s(),runId:u(e.runId),taskId:u(e.taskId),agentId:u(e.agentId),jobKind:u(e.jobKind,60),call:e.kind==="call"?Y(e.call):void 0,declined:e.kind==="declined"?{reason:W.includes(e.declined?.reason)?e.declined.reason:"other",...e.declined?.error?{error:String(e.declined.error).slice(0,300)}:{}}:void 0,rotated:e.kind==="rotated-from"?h({to:w(e.rotated?.to)||void 0,reason:u(e.rotated?.reason,300)}):void 0,rating:e.kind==="rating"?h({by:String(e.rating?.by||"person").slice(0,40),score:V(e.rating?.score),jobKind:u(e.rating?.jobKind||e.jobKind,60),agentId:u(e.rating?.agentId||e.agentId)}):void 0,capability:e.kind==="capability"?{id:String(e.capability?.id||"").slice(0,40),proved:y(e.capability?.proved)}:void 0,price:e.kind==="price"?h({per1kIn:S(e.price?.per1kIn)??0,per1kOut:S(e.price?.per1kOut)??0,source:e.price?.source==="user"?"user":"provider",currency:u(e.price?.currency,8)}):void 0,refs:Array.isArray(e.refs)&&e.refs.length?e.refs.map(String).slice(0,12):void 0,prev:n?n.hash:null});if(i.kind==="capability"&&!i.capability.id)throw new Error("model-ledger: capability.id required");const{hash:g,sig:O,...f}=i;return i.hash=await $(U(f),{subtle:a}),i}const b=(e,n)=>{if(!e.length)return null;const s=[...e].sort((a,o)=>a-o);return s[Math.min(s.length-1,Math.max(0,Math.ceil(n/100*s.length)-1))]},m=e=>e.length?e.reduce((n,s)=>n+s,0)/e.length:null,k=(e,n)=>n?Math.round(e/n*1e3)/1e3:null,I=e=>e==null?null:Math.round(e*1e3)/1e3;function ee(e,{minCalls:n=A,now:s=Date.now(),recent:a=5}={}){const o=(e||[]).filter(t=>t&&t.kind),l=o.filter(t=>t.kind==="call"),i=o.filter(t=>t.kind==="declined"),g=l.length+i.length,O=Array.from({length:24},()=>({calls:0,declines:0}));for(const t of[...l,...i]){const r=Math.floor((s-t.at)/36e5);r>=0&&r<24&&(O[23-r][t.kind==="call"?"calls":"declines"]+=1)}const f={};for(const t of i)f[t.declined.reason]=(f[t.declined.reason]||0)+1;const x=[...l,...i].sort((t,r)=>t.at-r.at).slice(-3),D=x.length===3&&x.every(t=>t.kind==="declined"&&s-t.at<36e5),N=l.filter(t=>t.call.structured!=="n/a"),C=l.filter(t=>t.call.toolCalls?.asked),_={failRate:k(l.filter(t=>!t.call.ok).length,l.length),empty:k(l.filter(t=>t.call.empty).length,l.length),refused:k(l.filter(t=>t.call.refused).length,l.length),truncated:k(l.filter(t=>t.call.truncated).length,l.length),badJson:k(N.filter(t=>t.call.structured==="bad").length,N.length),badToolCall:k(C.reduce((t,r)=>t+(r.call.toolCalls.asked-r.call.toolCalls.valid),0),C.reduce((t,r)=>t+r.call.toolCalls.asked,0))},M=l.map(t=>t.call.ttftMs).filter(t=>t!=null),E=l.map(t=>t.call.totalMs).filter(t=>t!=null),L={ttft:{p50:b(M,50),p95:b(M,95),n:M.length},total:{p50:b(E,50),p95:b(E,95),n:E.length}},p=o.filter(t=>t.kind==="price").at(-1)?.price||null,q=l.map(t=>t.call.cost!=null?t.call.cost:p&&(t.call.tokensIn!=null||t.call.tokensOut!=null)?((t.call.tokensIn||0)*p.per1kIn+(t.call.tokensOut||0)*p.per1kOut)/1e3:null).filter(t=>t!=null),K=l.map(t=>(t.call.tokensIn||0)+(t.call.tokensOut||0)+(t.call.tokens||0)).filter(t=>t>0),z={perTask:I(m(q)),priced:q.length,tokensPerTask:K.length?Math.round(m(K)):null,...p?{per1kIn:p.per1kIn,per1kOut:p.per1kOut,source:p.source}:{}},d={};for(const t of o.filter(r=>r.kind==="capability")){const r=d[t.capability.id]||(d[t.capability.id]={asked:0,proved:0,failedSince:0});r.asked+=1,t.capability.proved?(r.proved+=1,r.failedSince=0):r.failedSince+=1}const J={proved:Object.keys(d).filter(t=>d[t].proved>0&&d[t].failedSince<R).sort(),withdrawn:Object.keys(d).filter(t=>d[t].failedSince>=R).sort(),proofs:Object.fromEntries(Object.entries(d).map(([t,r])=>[t,{asked:r.asked,proved:r.proved}]))},v=o.filter(t=>t.kind==="rating"),j={};for(const t of v){const r=t.rating.jobKind||"any";(j[r]=j[r]||[]).push(t.rating.score)}const F={overall:{avg:I(m(v.map(t=>t.rating.score))),count:v.length},byJobKind:Object.fromEntries(Object.entries(j).map(([t,r])=>[t,{avg:I(m(r)),count:r.length}]))},P=o.filter(t=>t.kind==="rotated-from").length;return{key:o[0]?.key||null,engine:o[0]?.engine||null,entries:o.length,calls:l.length,declines:i.length,observed:l.length>=n,availability:{rate:g?I(1-i.length/g):null,attempts:g,declinesBy:f,byHour:O,decliningNow:D},reliability:_,latency:L,cost:z,capabilities:J,quality:F,rotatedFrom:P,refs:[...new Set(o.flatMap(t=>t.refs||[]))].slice(-a),since:o[0]?.at||null,last:o.at(-1)?.at||null,head:o.at(-1)?.hash||null}}function te(e,{minCalls:n=A,jobKind:s=null}={}){const a={},o=[];if(!e)return{override:a,observed:o};const l=s&&e.quality?.byJobKind?.[s]?.count>=n?e.quality.byJobKind[s]:e.quality?.overall;l&&l.count>=n&&l.avg!=null&&(a.quality=l.avg,o.push("quality"));const i=e.latency?.ttft?.n>=n?e.latency.ttft.p50:e.latency?.total?.n>=n?e.latency.total.p50:null;return i!=null&&(a.latencyMs=i,o.push("latencyMs")),e.cost?.per1kIn!=null&&e.cost?.per1kOut!=null&&(a.costPer1k=Math.round((e.cost.per1kIn+e.cost.per1kOut)/2*1e6)/1e6,o.push("costPer1k")),e.availability?.decliningNow&&(a.available=!1,o.push("available")),{override:a,observed:o}}import{adjustSummary as ae}from"./scorecard.js";export{W as DECLINE_REASONS,A as DEFAULT_MIN_CALLS,T as LEDGER_ENTRY_KINDS,H as LEDGER_VERSION,B as STRUCTURED,R as WITHDRAW_AFTER,ae as adjustSummary,re as attest,te as cardOverride,X as ledgerKey,Z as makeLedgerEntry,Y as normalizeCall,ee as summarizeEngine,ie as verifyAttested,oe as verifyChain};
|
package/src/model-runtime.js
CHANGED
|
@@ -1,37 +1 @@
|
|
|
1
|
-
|
|
2
|
-
//
|
|
3
|
-
// This is a fact about the RUNTIME, not about any one speech stage, so it lives in
|
|
4
|
-
// its own module rather than inside whichever engine needed it first. The voice
|
|
5
|
-
// pipeline's rule is that a stage never imports another stage (docs/voice-pipeline.md
|
|
6
|
-
// "Composable pipeline"), and stt-engine and tts-engine both have to answer this —
|
|
7
|
-
// so neither can own it.
|
|
8
|
-
//
|
|
9
|
-
// • native onnxruntime-node (the npm gateway) loads the small, fast `q8`
|
|
10
|
-
// (_quantized) exports — best size + speed.
|
|
11
|
-
// • onnxruntime-web WASM (the standalone binary — SAME wasm on macOS/Windows/
|
|
12
|
-
// Linux, so this is inherently cross-platform) CANNOT load the block-quantized
|
|
13
|
-
// exports (q8/int8/uint8 → MatMulNBits "missing scale"; fp16 → graph error);
|
|
14
|
-
// of the loadable ones only `fp32` is fast enough for real-time (q4/bnb4 are
|
|
15
|
-
// ~8× slower). Verified empirically against the bundled ORT-web build.
|
|
16
|
-
//
|
|
17
|
-
// The binary entry sets __CHATPANEL_WASM_PATHS__, so that global tells us which
|
|
18
|
-
// runtime we're on. A model may override the choice via `dtype` in its catalog.
|
|
19
|
-
export function runtimeDtype() {
|
|
20
|
-
return globalThis.__CHATPANEL_WASM_PATHS__ ? 'fp32' : 'q8';
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
// 'native' (npm, fast quantized) | 'wasm' (binary, slow fp32). The extension
|
|
24
|
-
// surfaces this so users on the slow WASM build know the native gateway is faster.
|
|
25
|
-
export function runtimeName() {
|
|
26
|
-
return globalThis.__CHATPANEL_WASM_PATHS__ ? 'wasm' : 'native';
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// transformers.js dtype → the ONNX filename suffix it loads. A presence check must
|
|
30
|
-
// target the EXACT file the current runtime will fetch — otherwise a q8 install
|
|
31
|
-
// (native) looks "present" to the WASM runtime, which actually needs the fp32 file,
|
|
32
|
-
// and the offline load fails. Checking the real target makes a runtime switch
|
|
33
|
-
// re-download rather than fail.
|
|
34
|
-
export const DTYPE_SUFFIX = {
|
|
35
|
-
fp32: '', q8: '_quantized', int8: '_int8', uint8: '_uint8',
|
|
36
|
-
fp16: '_fp16', q4: '_q4', bnb4: '_bnb4', q4f16: '_q4f16',
|
|
37
|
-
};
|
|
1
|
+
function _(){return globalThis.__CHATPANEL_WASM_PATHS__?"fp32":"q8"}function n(){return globalThis.__CHATPANEL_WASM_PATHS__?"wasm":"native"}const t={fp32:"",q8:"_quantized",int8:"_int8",uint8:"_uint8",fp16:"_fp16",q4:"_q4",bnb4:"_bnb4",q4f16:"_q4f16"};export{t as DTYPE_SUFFIX,_ as runtimeDtype,n as runtimeName};
|
package/src/models.js
CHANGED
|
@@ -1,92 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// settings so users can install a larger or multilingual detector. Sizes are the
|
|
3
|
-
// on-disk q8 footprint, approx.
|
|
4
|
-
//
|
|
5
|
-
// TWO THINGS TO CHECK WHEN ADDING A MODEL, and getting either wrong fails SILENTLY.
|
|
6
|
-
//
|
|
7
|
-
// 1. ITS LABELS MUST BE MAPPED. `@chatpanel/pii` `normalizeEntities` turns a model's
|
|
8
|
-
// labels into our placeholder types, and an unmapped label is dropped rather than
|
|
9
|
-
// passed through — so a model whose vocabulary it does not know detects entities
|
|
10
|
-
// perfectly and redacts none of them, while the UI still reads as on. Run one
|
|
11
|
-
// sentence through the model, look at the labels it returns, and map every one.
|
|
12
|
-
// This is not hypothetical: multilang-pii-ner emits the ai4privacy vocabulary
|
|
13
|
-
// (GIVENNAME, SURNAME, TELEPHONENUM…) and person redaction was silently off for
|
|
14
|
-
// anyone who selected it, until pii 0.6.0.
|
|
15
|
-
//
|
|
16
|
-
// 2. `mirrored` MUST BE TRUE ONLY IF IT REALLY IS. A catalogued model is fetched from
|
|
17
|
-
// ChatPanel's CDN so a clean install depends only on chatpanel.net; a model that is
|
|
18
|
-
// not there 404s at first use. `mirrored: false` says "catalogue it, but fetch it
|
|
19
|
-
// from Hugging Face" — which is what lets a model be a first-class, one-click
|
|
20
|
-
// choice before the mirror upload happens, instead of forcing users to paste a
|
|
21
|
-
// custom id and lose the label, the size and the note.
|
|
22
|
-
|
|
23
|
-
export const DEFAULT_MODEL = 'Xenova/bert-base-NER';
|
|
24
|
-
|
|
25
|
-
export const MODEL_CATALOG = [
|
|
26
|
-
{
|
|
27
|
-
id: 'Xenova/bert-base-NER',
|
|
28
|
-
label: 'English — standard',
|
|
29
|
-
lang: 'English',
|
|
30
|
-
approxMB: 105,
|
|
31
|
-
note: 'Default. Best English accuracy for people, organizations, and locations.',
|
|
32
|
-
},
|
|
33
|
-
{
|
|
34
|
-
id: 'Xenova/distilbert-base-multilingual-cased-ner-hrl',
|
|
35
|
-
label: 'Multilingual — compact',
|
|
36
|
-
lang: '10 languages',
|
|
37
|
-
approxMB: 150,
|
|
38
|
-
note: 'Covers en, es, fr, de, it, pt, nl, ar, zh, ru. Use for non-English text.',
|
|
39
|
-
},
|
|
40
|
-
{
|
|
41
|
-
id: 'Xenova/bert-base-multilingual-cased-ner-hrl',
|
|
42
|
-
label: 'Multilingual — large',
|
|
43
|
-
lang: '10 languages',
|
|
44
|
-
approxMB: 180,
|
|
45
|
-
note: 'Higher multilingual accuracy; larger download.',
|
|
46
|
-
},
|
|
47
|
-
{
|
|
48
|
-
// PURPOSE-BUILT FOR THIS JOB, where the three above are general newswire NER. It
|
|
49
|
-
// finds what redaction actually cares about — given and family names separately,
|
|
50
|
-
// street/building/postcode, phone, national-ID and account numbers, usernames and
|
|
51
|
-
// passwords — none of which a PER/ORG/LOC model emits at all. That makes it the
|
|
52
|
-
// better detector for a privacy product, not merely a bigger one.
|
|
53
|
-
//
|
|
54
|
-
// NOT the default yet, and the reason is written down rather than remembered: it is
|
|
55
|
-
// not on the CDN (see `mirrored`), so defaulting to it would make a clean install
|
|
56
|
-
// depend on Hugging Face, and it needs @chatpanel/pii >= 0.6.0 for its labels to be
|
|
57
|
-
// understood at all. Both are release chores, not code.
|
|
58
|
-
id: 'onnx-community/multilang-pii-ner-ONNX',
|
|
59
|
-
label: 'PII-specialised — multilingual',
|
|
60
|
-
lang: 'Multilingual',
|
|
61
|
-
approxMB: 282,
|
|
62
|
-
mirrored: false,
|
|
63
|
-
recommended: true,
|
|
64
|
-
note: 'Most thorough. Trained for PII rather than general entities: also finds addresses, postcodes, account and ID numbers, usernames and passwords. Larger download, fetched from Hugging Face.',
|
|
65
|
-
},
|
|
66
|
-
];
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Is this model on ChatPanel's CDN, or does it have to come from Hugging Face?
|
|
70
|
-
*
|
|
71
|
-
* Default TRUE for a catalogued model — the mirror is the norm and the point of the
|
|
72
|
-
* catalogue. An entry says `mirrored: false` when it is a first-class choice that has not
|
|
73
|
-
* been uploaded yet. A model that is not in the catalogue at all is a user's own id and is
|
|
74
|
-
* never mirrored.
|
|
75
|
-
*/
|
|
76
|
-
export function isMirroredModel(id) {
|
|
77
|
-
const m = MODEL_CATALOG.find((x) => x.id === id);
|
|
78
|
-
return !!m && m.mirrored !== false;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function isKnownModel(id) {
|
|
82
|
-
return MODEL_CATALOG.some((m) => m.id === id);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// Accept a user-supplied ("bring your own") NER model id. STRICT `org/name` shape,
|
|
86
|
-
// no path traversal. We can't verify it's token-classification from the id alone —
|
|
87
|
-
// the engine fails open if the download/labels don't fit. Custom ids fetch from
|
|
88
|
-
// Hugging Face directly (the engine points remoteHost there for the custom load).
|
|
89
|
-
export function isValidCustomModelId(id) {
|
|
90
|
-
const s = String(id || '');
|
|
91
|
-
return /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(s) && !s.includes('..');
|
|
92
|
-
}
|
|
1
|
+
const l="Xenova/bert-base-NER",a=[{id:"Xenova/bert-base-NER",label:"English — standard",lang:"English",approxMB:105,note:"Default. Best English accuracy for people, organizations, and locations."},{id:"Xenova/distilbert-base-multilingual-cased-ner-hrl",label:"Multilingual — compact",lang:"10 languages",approxMB:150,note:"Covers en, es, fr, de, it, pt, nl, ar, zh, ru. Use for non-English text."},{id:"Xenova/bert-base-multilingual-cased-ner-hrl",label:"Multilingual — large",lang:"10 languages",approxMB:180,note:"Higher multilingual accuracy; larger download."},{id:"onnx-community/multilang-pii-ner-ONNX",label:"PII-specialised — multilingual",lang:"Multilingual",approxMB:282,mirrored:!1,recommended:!0,note:"Most thorough. Trained for PII rather than general entities: also finds addresses, postcodes, account and ID numbers, usernames and passwords. Larger download, fetched from Hugging Face."}];function o(n){const e=a.find(r=>r.id===n);return!!e&&e.mirrored!==!1}function t(n){return a.some(e=>e.id===n)}function i(n){const e=String(n||"");return/^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(e)&&!e.includes("..")}export{l as DEFAULT_MODEL,a as MODEL_CATALOG,t as isKnownModel,o as isMirroredModel,i as isValidCustomModelId};
|