@chatpanel/pii 0.2.0 → 0.2.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/pii",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "The canonical ChatPanel privacy engine — reversible PII redaction + pseudonymization with local entity detection. Pure, dependency-free ESM shared by the ChatPanel extension, gateway, and bridge.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -16,6 +16,7 @@
16
16
  "pii-redact.js",
17
17
  "pii-detect.js",
18
18
  "pipeline.js",
19
+ "tool-rank.js",
19
20
  "LICENSE",
20
21
  "README.md"
21
22
  ],
package/pii-redact.js CHANGED
@@ -20,6 +20,14 @@
20
20
 
21
21
  const TOKEN_RE = /\[\[([A-Z][A-Z0-9]*)_(\d+)\]\]/g;
22
22
 
23
+ // Bracket-TOLERANT match of the same token. Smaller models routinely drop or mangle
24
+ // the [[ ]] when echoing a placeholder into tool-call JSON — e.g. they emit "ORG_1"
25
+ // or "[ORG_1]" instead of "[[ORG_1]]" — which the strict TOKEN_RE misses, leaving
26
+ // the tool to search the literal "ORG_1" (and get nothing). We match 0–2 brackets
27
+ // on each side and reconstruct the canonical token to look up; only ACTUAL vault
28
+ // tokens are swapped, so a coincidental "ABC_1" that isn't ours is left untouched.
29
+ const TOLERANT_TOKEN_RE = /\[{0,2}([A-Z][A-Z0-9]*_\d+)\]{0,2}/g;
30
+
23
31
  // A vault is the per-conversation mapping between placeholders and originals. Keep
24
32
  // one per conversation so PERSON_1 means the same entity across turns.
25
33
  export function createVault() {
@@ -168,7 +176,10 @@ export function redactText(text, vault, {
168
176
  // Swap placeholders back to their originals. Unknown tokens are left untouched.
169
177
  export function restoreText(text, vault) {
170
178
  if (text == null || !vault) return text;
171
- return String(text).replace(TOKEN_RE, (m) => (vault.byToken.has(m) ? vault.byToken.get(m) : m));
179
+ return String(text).replace(TOLERANT_TOKEN_RE, (m, inner) => {
180
+ const canonical = `[[${inner}]]`;
181
+ return vault.byToken.has(canonical) ? vault.byToken.get(canonical) : m;
182
+ });
172
183
  }
173
184
 
174
185
  // Restore for LOCAL use only — e.g. tool-call args that hit on-device history /
package/tool-rank.js ADDED
@@ -0,0 +1,62 @@
1
+ // Deterministic, model-free tool ranking — shared by the extension's side panel
2
+ // and the gateway, so "auto mode" narrows the same way everywhere (single source
3
+ // of truth, per the no-duplication rule).
4
+ //
5
+ // Ranks tool specs by lexical relevance to a query, weighting each query word by
6
+ // INVERSE DOCUMENT FREQUENCY across the toolset: a distinctive word like "wiki"
7
+ // (in 1–2 tools) counts far more than a common one like "search" (in many) — so
8
+ // "use wiki search" ranks the Wikipedia tool above generic search tools instead
9
+ // of tying them. Latency-sensitive: pure string ops, runs on every turn, no model
10
+ // call. Generic over the spec shape via name/description accessors (the extension
11
+ // uses { name, description }; the gateway uses OpenAI's { function: { name, … } }).
12
+
13
+ const STOP = new Set([
14
+ 'the', 'and', 'for', 'with', 'that', 'this', 'use', 'can', 'you', 'your', 'please',
15
+ 'about', 'from', 'what', 'who', 'how', 'are', 'was', 'will', 'just', 'tell', 'find',
16
+ 'get', 'into', 'them', 'they', 'their', 'name', 'one', 'but', 'not', 'all',
17
+ ]);
18
+
19
+ const defName = (s) => (s && s.name) || '';
20
+ const defDesc = (s) => (s && s.description) || '';
21
+
22
+ // Returns specs scored + sorted most-relevant first, as [{ s, i, n }] (i = original
23
+ // index, n = score). Stable for ties (preserves original order).
24
+ export function scoreToolSpecs(specs, query, { name = defName, description = defDesc } = {}) {
25
+ const q = String(query || '').toLowerCase();
26
+ const words = [...new Set(q.split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP.has(w)))];
27
+ const list = [...(specs || [])];
28
+ const names = list.map((s) => String(name(s) || '').toLowerCase());
29
+ const hays = list.map((s, i) => `${names[i]} ${String(description(s) || '').toLowerCase()}`);
30
+ const N = list.length || 1;
31
+ const df = {}; // how many tools mention each query word
32
+ for (const w of words) df[w] = hays.reduce((n, h) => n + (h.includes(w) ? 1 : 0), 0);
33
+ const idf = (w) => Math.log(1 + N / (1 + (df[w] || 0))); // rarer → higher weight
34
+ const score = (i) => {
35
+ let n = 0;
36
+ for (const w of words) if (hays[i].includes(w)) n += idf(w);
37
+ for (const part of names[i].split(/[^a-z0-9]+/)) {
38
+ if (part.length > 2 && q.includes(part)) n += 2 + idf(part); // tool explicitly named
39
+ }
40
+ return n;
41
+ };
42
+ return list.map((s, i) => ({ s, i, n: score(i) })).sort((a, b) => (b.n - a.n) || (a.i - b.i));
43
+ }
44
+
45
+ // Rank tool specs most-relevant first (stable for ties).
46
+ export function rankToolSpecs(specs, query, accessors) {
47
+ return scoreToolSpecs(specs, query, accessors).map((x) => x.s);
48
+ }
49
+
50
+ // Narrow a flat spec list to at most `cap` entries that DON'T match `keep`, always
51
+ // retaining everything that does (e.g. local page/history tools). `cap` therefore
52
+ // bounds the NARROWABLE (MCP) tools; kept tools ride along free. Returns the list
53
+ // unchanged when there's no cap or the narrowable set already fits.
54
+ export function narrowSpecs(specs, query, { cap = 0, keep, name = defName, description = defDesc } = {}) {
55
+ const list = specs || [];
56
+ if (!cap || cap < 1) return list;
57
+ const kept = keep ? list.filter(keep) : [];
58
+ const rest = keep ? list.filter((s) => !kept.includes(s)) : list;
59
+ if (rest.length <= cap) return list;
60
+ const top = new Set(rankToolSpecs(rest, query, { name, description }).slice(0, cap));
61
+ return list.filter((s) => kept.includes(s) || top.has(s)); // preserve original order
62
+ }