@chatpanel/bridge 0.11.24 → 0.11.25
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 +7 -7
- package/package.json +1 -13
- package/scripts/sync-channels.mjs +8 -90
- package/scripts/sync-events.mjs +7 -78
- package/scripts/sync-pii.mjs +7 -68
- package/src/api-compat.js +5 -294
- package/src/channels/adapters/telegram.js +3 -298
- package/src/channels/bridge.js +1 -59
- package/src/channels/eventlog.js +3 -57
- package/src/channels/gateway.js +1 -114
- package/src/channels/invoke.js +1 -172
- package/src/channels/normalize.js +1 -58
- package/src/channels/pairing.js +1 -95
- package/src/channels/service.js +1 -329
- package/src/channels/stream.js +5 -104
- package/src/cli-errors.js +3 -136
- package/src/connections.js +1 -160
- package/src/connectors.js +1 -100
- package/src/engines/antigravity.js +5 -235
- package/src/engines/args.js +1 -47
- package/src/engines/claude.js +6 -586
- package/src/engines/cli-agents.js +7 -312
- package/src/engines/codex.js +6 -481
- package/src/engines/custom.js +17 -577
- package/src/engines/prompt.js +6 -32
- package/src/engines/stream-formats.js +2 -222
- package/src/entitlement.js +1 -77
- package/src/env.js +3 -628
- package/src/events/capability.js +1 -134
- package/src/events/event.js +1 -183
- package/src/events/reach.js +1 -31
- package/src/events/ref.js +1 -63
- package/src/events/scm-connection.js +1 -188
- package/src/events/scopes.js +1 -20
- package/src/events/skill-manifest.js +1 -338
- package/src/events/skill-scan.js +3 -217
- package/src/events/view.js +1 -96
- package/src/mcp-capabilities.js +2 -139
- package/src/mcp-local.js +0 -0
- package/src/mcp-quarantine.js +1 -110
- package/src/net.js +1 -107
- package/src/pii/index.js +1 -29
- package/src/pii/net.js +1 -111
- package/src/pii/pii-detect.js +2 -296
- package/src/pii/pii-redact.js +1 -470
- package/src/pii/pipeline.js +1 -137
- package/src/pii/sanitize.js +2 -179
- package/src/pii/tool-harness.js +1 -184
- package/src/pii/tool-rank.js +1 -110
- package/src/proc.js +2 -91
- package/src/relay-timeout.js +1 -21
- package/src/runs.js +1 -49
- package/src/sanitize.js +1 -7
- package/src/scm.js +1 -76
- package/src/server.js +10 -1492
- package/src/service.js +11 -176
- package/src/sign-in.js +1 -91
- package/src/skills.js +1 -399
- package/src/ssrf.js +1 -70
- package/src/update.js +1 -216
- package/src/workdir.js +1 -108
- package/src/worktree.js +3 -125
package/src/pii/sanitize.js
CHANGED
|
@@ -1,179 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
// Edit there, then run: npm run sync:pii
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// Unicode de-steganography for text that flows through the privacy boundary.
|
|
10
|
-
//
|
|
11
|
-
// Invisible and format-control characters are a single vector with three abuses,
|
|
12
|
-
// all relevant to a redaction product:
|
|
13
|
-
//
|
|
14
|
-
// 1. Redaction bypass - splitting a value with zero-width chars (j<ZWSP>o<ZWSP>hn@x.com)
|
|
15
|
-
// hides it from the regex/NER detector, then the model reassembles the real
|
|
16
|
-
// value. The deterministic engine works on text, so the smuggled PII leaks.
|
|
17
|
-
// 2. Hidden prompt injection - Unicode Tag characters (U+E0000-E007F) render as
|
|
18
|
-
// nothing but encode a full ASCII instruction the model reads ("ASCII smuggling").
|
|
19
|
-
// 3. Fingerprinting / watermarking - steganographic markers injected into a prompt
|
|
20
|
-
// (e.g. a client classifying a custom gateway and encoding a bit into invisible
|
|
21
|
-
// punctuation). A privacy proxy should scrub these - and never emit its own.
|
|
22
|
-
//
|
|
23
|
-
// We strip the channels that have no legitimate place in plain prompt text, while
|
|
24
|
-
// PRESERVING the few legitimate uses (emoji ZWJ/variation sequences, normal accents).
|
|
25
|
-
//
|
|
26
|
-
// The patterns are BUILT FROM NUMERIC CODE POINTS below - there are deliberately no
|
|
27
|
-
// literal invisible characters anywhere in this source (auditable, and fitting for a
|
|
28
|
-
// de-steg module). Pure + dependency-free ESM. Call it BEFORE detection so obfuscated
|
|
29
|
-
// PII becomes matchable, and on model output before restoration so a token can't be
|
|
30
|
-
// split/spoofed with invisibles.
|
|
31
|
-
|
|
32
|
-
// Code-point ranges (inclusive) per category, by their abuse.
|
|
33
|
-
const RANGES = {
|
|
34
|
-
// Unicode Tag block - the ASCII-smuggling channel.
|
|
35
|
-
tags: [[0xE0000, 0xE007F]],
|
|
36
|
-
// Bidi controls - reorder/override visible text to hide reversed instructions.
|
|
37
|
-
bidi: [[0x061C, 0x061C], [0x200E, 0x200F], [0x202A, 0x202E], [0x2066, 0x2069]],
|
|
38
|
-
// Zero-width & assorted invisible format chars: soft hyphen, Hangul/Mongolian
|
|
39
|
-
// fillers, ZWSP, word/invisible joiners, deprecated format controls, BOM/ZWNBSP,
|
|
40
|
-
// interlinear annotation, object replacement.
|
|
41
|
-
zeroWidth: [
|
|
42
|
-
[0x00AD, 0x00AD], [0x115F, 0x1160], [0x180E, 0x180E], [0x200B, 0x200B],
|
|
43
|
-
[0x2060, 0x2064], [0x206A, 0x206F], [0x3164, 0x3164], [0xFEFF, 0xFEFF],
|
|
44
|
-
[0xFFA0, 0xFFA0], [0xFFF9, 0xFFFB], [0xFFFC, 0xFFFC],
|
|
45
|
-
],
|
|
46
|
-
// Supplementary variation selectors - the byte-smuggling range. Never legit in text.
|
|
47
|
-
supVS: [[0xE0100, 0xE01EF]],
|
|
48
|
-
// Line/paragraph separators - converted to '\n' (kill parser tricks, keep the break).
|
|
49
|
-
lineSep: [[0x2028, 0x2029]],
|
|
50
|
-
// ZWJ/ZWNJ + BMP variation selectors - legit ONLY next to an emoji base, so these
|
|
51
|
-
// are stripped contextually (see ANOMALOUS_JOIN_VS), not unconditionally.
|
|
52
|
-
joinVS: [[0x200C, 0x200D], [0xFE00, 0xFE0F]],
|
|
53
|
-
};
|
|
54
|
-
|
|
55
|
-
const u = (cp) => `\\u{${cp.toString(16).toUpperCase()}}`;
|
|
56
|
-
const cls = (ranges) => ranges.map(([a, b]) => (a === b ? u(a) : `${u(a)}-${u(b)}`)).join('');
|
|
57
|
-
|
|
58
|
-
const TAGS = new RegExp(`[${cls(RANGES.tags)}]`, 'gu');
|
|
59
|
-
const BIDI = new RegExp(`[${cls(RANGES.bidi)}]`, 'gu');
|
|
60
|
-
const ZERO_WIDTH = new RegExp(`[${cls(RANGES.zeroWidth)}]`, 'gu');
|
|
61
|
-
const SUP_VS = new RegExp(`[${cls(RANGES.supVS)}]`, 'gu');
|
|
62
|
-
const LINE_SEP = new RegExp(`[${cls(RANGES.lineSep)}]`, 'gu');
|
|
63
|
-
// Strip ZWJ/ZWNJ/VS only when NOT preceded by an emoji base (so emoji sequences and
|
|
64
|
-
// regional-indicator flags survive); supplementary VS are always stripped.
|
|
65
|
-
const ANOMALOUS_JOIN_VS = new RegExp(
|
|
66
|
-
`(?<![\\p{Extended_Pictographic}${u(0x1F1E6)}-${u(0x1F1FF)}])[${cls(RANGES.joinVS)}]|[${cls(RANGES.supVS)}]`,
|
|
67
|
-
'gu',
|
|
68
|
-
);
|
|
69
|
-
// Runs of combining marks (Zalgo / bit-stuffing). A real stacked diacritic is 1-3
|
|
70
|
-
// marks; anything past the cap is signalling, not language.
|
|
71
|
-
const COMBINING_RUN = /\p{M}+/gu;
|
|
72
|
-
|
|
73
|
-
// Cheap boolean for hot paths / UI ("does this contain anything hidden?"). Excludes
|
|
74
|
-
// the context-dependent joinVS so legitimate emoji aren't flagged - sanitizeUnicode()
|
|
75
|
-
// stays the source of truth for those.
|
|
76
|
-
const ANY_HIDDEN = new RegExp(
|
|
77
|
-
`[${cls(RANGES.bidi)}${cls(RANGES.zeroWidth)}]|[${cls(RANGES.tags)}]|[${cls(RANGES.supVS)}]`,
|
|
78
|
-
'u',
|
|
79
|
-
);
|
|
80
|
-
|
|
81
|
-
export function hasHiddenChars(text) {
|
|
82
|
-
return typeof text === 'string' && ANY_HIDDEN.test(text);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
// sanitizeUnicode(text, opts) -> { clean, removed, findings }
|
|
86
|
-
// clean - text with the smuggling channels stripped/normalized
|
|
87
|
-
// removed - total count of stripped/collapsed characters (0 = nothing hidden)
|
|
88
|
-
// findings - per-category counts (only non-zero keys), for transparent reporting
|
|
89
|
-
//
|
|
90
|
-
// opts.normalize: 'NFC' (default, appearance-preserving) | 'NFKC' (also folds
|
|
91
|
-
// fullwidth/homoglyph compatibility forms - stronger for detection, but rewrites
|
|
92
|
-
// some visible glyphs) | 'none'.
|
|
93
|
-
// opts.collapseCombiningOver: max combining marks kept per run (default 4).
|
|
94
|
-
export function sanitizeUnicode(text, { normalize = 'NFC', collapseCombiningOver = 4 } = {}) {
|
|
95
|
-
if (typeof text !== 'string' || text === '') return { clean: text ?? '', removed: 0, findings: {} };
|
|
96
|
-
let s = text;
|
|
97
|
-
const findings = {};
|
|
98
|
-
|
|
99
|
-
// Strip one category, counting by code point (spread iterates code points, so a
|
|
100
|
-
// supplementary char like a Tag counts as 1, not 2 UTF-16 units).
|
|
101
|
-
const strip = (re, key) => {
|
|
102
|
-
let n = 0;
|
|
103
|
-
s = s.replace(re, (m) => { n += [...m].length; return ''; });
|
|
104
|
-
if (n) findings[key] = n;
|
|
105
|
-
};
|
|
106
|
-
|
|
107
|
-
let lineSep = 0;
|
|
108
|
-
s = s.replace(LINE_SEP, () => { lineSep++; return '\n'; });
|
|
109
|
-
if (lineSep) findings.lineSep = lineSep;
|
|
110
|
-
|
|
111
|
-
strip(TAGS, 'tags');
|
|
112
|
-
strip(BIDI, 'bidi');
|
|
113
|
-
strip(ZERO_WIDTH, 'zeroWidth');
|
|
114
|
-
strip(ANOMALOUS_JOIN_VS, 'joinersVS');
|
|
115
|
-
|
|
116
|
-
// Compose canonically so split/decomposed forms can't dodge the detector.
|
|
117
|
-
if (normalize && normalize !== 'none') {
|
|
118
|
-
try { s = s.normalize(normalize); } catch { /* invalid form name -> skip */ }
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
let combining = 0;
|
|
122
|
-
s = s.replace(COMBINING_RUN, (run) => {
|
|
123
|
-
const marks = [...run];
|
|
124
|
-
if (marks.length <= collapseCombiningOver) return run;
|
|
125
|
-
combining += marks.length - collapseCombiningOver;
|
|
126
|
-
return marks.slice(0, collapseCombiningOver).join('');
|
|
127
|
-
});
|
|
128
|
-
if (combining) findings.combining = combining;
|
|
129
|
-
|
|
130
|
-
const removed = (findings.tags || 0) + (findings.bidi || 0) + (findings.zeroWidth || 0)
|
|
131
|
-
+ (findings.joinersVS || 0) + (findings.combining || 0);
|
|
132
|
-
return { clean: s, removed, findings };
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// Convenience for the common "just give me clean text" caller.
|
|
136
|
-
export function stripHidden(text, opts) {
|
|
137
|
-
return sanitizeUnicode(text, opts).clean;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// ── Confusables skeleton ─────────────────────────────────────────────────────
|
|
141
|
-
// Fold single-code-point Latin LOOK-ALIKES (Cyrillic / Greek / fullwidth) to their
|
|
142
|
-
// ASCII skeleton so a homoglyph-obfuscated value (jоhn@x.com with a Cyrillic 'о')
|
|
143
|
-
// becomes matchable by the ASCII regexes. STRICTLY 1:1 per code point — every mapping
|
|
144
|
-
// is one char → one char — so a match's indices in the skeleton line up exactly with
|
|
145
|
-
// the original text. Use it for DETECTION only and redact the ORIGINAL span, so
|
|
146
|
-
// legitimate Cyrillic/Greek/CJK text is never rewritten (only deceptively-Latin
|
|
147
|
-
// values that actually match a detector get touched). Built from numeric code points
|
|
148
|
-
// (no literal confusables in source, like the rest of this module).
|
|
149
|
-
const CONFUSABLE = new Map([
|
|
150
|
-
// Cyrillic lowercase → Latin
|
|
151
|
-
[0x0430, 'a'], [0x0435, 'e'], [0x043E, 'o'], [0x0440, 'p'], [0x0441, 'c'],
|
|
152
|
-
[0x0443, 'y'], [0x0445, 'x'], [0x0455, 's'], [0x0456, 'i'], [0x0458, 'j'],
|
|
153
|
-
[0x04BB, 'h'], [0x043C, 'm'], [0x043D, 'h'], [0x0442, 't'], [0x043A, 'k'],
|
|
154
|
-
// Cyrillic uppercase → Latin
|
|
155
|
-
[0x0410, 'A'], [0x0412, 'B'], [0x0415, 'E'], [0x041A, 'K'], [0x041C, 'M'],
|
|
156
|
-
[0x041D, 'H'], [0x041E, 'O'], [0x0420, 'P'], [0x0421, 'C'], [0x0422, 'T'],
|
|
157
|
-
[0x0425, 'X'], [0x0406, 'I'], [0x0408, 'J'], [0x0405, 'S'],
|
|
158
|
-
// Greek → Latin
|
|
159
|
-
[0x03BF, 'o'], [0x03C1, 'p'], [0x03B1, 'a'], [0x03BD, 'v'], [0x03B9, 'i'],
|
|
160
|
-
[0x0391, 'A'], [0x0392, 'B'], [0x0395, 'E'], [0x0396, 'Z'], [0x0397, 'H'],
|
|
161
|
-
[0x0399, 'I'], [0x039A, 'K'], [0x039C, 'M'], [0x039D, 'N'], [0x039F, 'O'],
|
|
162
|
-
[0x03A1, 'P'], [0x03A4, 'T'], [0x03A5, 'Y'], [0x03A7, 'X'],
|
|
163
|
-
]);
|
|
164
|
-
|
|
165
|
-
export function confusablesSkeleton(text) {
|
|
166
|
-
if (typeof text !== 'string' || text === '') return text ?? '';
|
|
167
|
-
let out = '';
|
|
168
|
-
for (const ch of text) {
|
|
169
|
-
const cp = ch.codePointAt(0);
|
|
170
|
-
if (cp >= 0xFF01 && cp <= 0xFF5E) { out += String.fromCharCode(cp - 0xFEE0); continue; } // fullwidth ASCII
|
|
171
|
-
const mapped = CONFUSABLE.get(cp);
|
|
172
|
-
out += mapped != null ? mapped : ch;
|
|
173
|
-
}
|
|
174
|
-
return out;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// Exposed for tests / external auditing.
|
|
178
|
-
export const SANITIZE_RANGES = RANGES;
|
|
179
|
-
export const CONFUSABLE_MAP = CONFUSABLE;
|
|
1
|
+
const o={tags:[[917504,917631]],bidi:[[1564,1564],[8206,8207],[8234,8238],[8294,8297]],zeroWidth:[[173,173],[4447,4448],[6158,6158],[8203,8203],[8288,8292],[8298,8303],[12644,12644],[65279,65279],[65440,65440],[65529,65531],[65532,65532]],supVS:[[917760,917999]],lineSep:[[8232,8233]],joinVS:[[8204,8205],[65024,65039]]},c=x=>`\\u{${x.toString(16).toUpperCase()}}`,i=x=>x.map(([e,r])=>e===r?c(e):`${c(e)}-${c(r)}`).join(""),f=new RegExp(`[${i(o.tags)}]`,"gu"),a=new RegExp(`[${i(o.bidi)}]`,"gu"),l=new RegExp(`[${i(o.zeroWidth)}]`,"gu"),I=new RegExp(`[${i(o.supVS)}]`,"gu"),h=new RegExp(`[${i(o.lineSep)}]`,"gu"),C=new RegExp(`(?<![\\p{Extended_Pictographic}${c(127462)}-${c(127487)}])[${i(o.joinVS)}]|[${i(o.supVS)}]`,"gu"),$=new RegExp("\\p{M}+","gu"),B=new RegExp(`[${i(o.bidi)}${i(o.zeroWidth)}]|[${i(o.tags)}]|[${i(o.supVS)}]`,"u");function D(x){return typeof x=="string"&&B.test(x)}function N(x,{normalize:e="NFC",collapseCombiningOver:r=4}={}){if(typeof x!="string"||x==="")return{clean:x??"",removed:0,findings:{}};let n=x;const t={},F=(p,s)=>{let u=0;n=n.replace(p,d=>(u+=[...d].length,"")),u&&(t[s]=u)};let E=0;if(n=n.replace(h,()=>(E++,`
|
|
2
|
+
`)),E&&(t.lineSep=E),F(f,"tags"),F(a,"bidi"),F(l,"zeroWidth"),F(C,"joinersVS"),e&&e!=="none")try{n=n.normalize(e)}catch{}let g=0;n=n.replace($,p=>{const s=[...p];return s.length<=r?p:(g+=s.length-r,s.slice(0,r).join(""))}),g&&(t.combining=g);const A=(t.tags||0)+(t.bidi||0)+(t.zeroWidth||0)+(t.joinersVS||0)+(t.combining||0);return{clean:n,removed:A,findings:t}}function R(x,e){return N(x,e).clean}const S=new Map([[1072,"a"],[1077,"e"],[1086,"o"],[1088,"p"],[1089,"c"],[1091,"y"],[1093,"x"],[1109,"s"],[1110,"i"],[1112,"j"],[1211,"h"],[1084,"m"],[1085,"h"],[1090,"t"],[1082,"k"],[1040,"A"],[1042,"B"],[1045,"E"],[1050,"K"],[1052,"M"],[1053,"H"],[1054,"O"],[1056,"P"],[1057,"C"],[1058,"T"],[1061,"X"],[1030,"I"],[1032,"J"],[1029,"S"],[959,"o"],[961,"p"],[945,"a"],[957,"v"],[953,"i"],[913,"A"],[914,"B"],[917,"E"],[918,"Z"],[919,"H"],[921,"I"],[922,"K"],[924,"M"],[925,"N"],[927,"O"],[929,"P"],[932,"T"],[933,"Y"],[935,"X"]]);function V(x){if(typeof x!="string"||x==="")return x??"";let e="";for(const r of x){const n=r.codePointAt(0);if(n>=65281&&n<=65374){e+=String.fromCharCode(n-65248);continue}const t=S.get(n);e+=t??r}return e}const _=o,w=S;export{w as CONFUSABLE_MAP,_ as SANITIZE_RANGES,V as confusablesSkeleton,D as hasHiddenChars,N as sanitizeUnicode,R as stripHidden};
|
package/src/pii/tool-harness.js
CHANGED
|
@@ -1,184 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-pii/tool-harness.js (npm @chatpanel/pii).
|
|
3
|
-
// Edit there, then run: npm run sync:pii
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// THE tool harness — one interception layer shared by every orchestrator
|
|
10
|
-
// (ChatPanel API + agent, gateway API + relay) so tool handling can't drift. It
|
|
11
|
-
// owns the boundaries around a model turn:
|
|
12
|
-
//
|
|
13
|
-
// ⓪ selectTools — inject + narrow the tools the model is offered (MCP-auto).
|
|
14
|
-
// ② toTool — what a tool RECEIVES: real values (so on-device / remote
|
|
15
|
-
// lookups work), or the redacted token for remote MCP tools
|
|
16
|
-
// when the user chose "redact remote".
|
|
17
|
-
// ③ toModelResult— what the MODEL sees back: the tool result re-redacted so it
|
|
18
|
-
// stays blinded.
|
|
19
|
-
// ④ toUser — the final reply: reversible tokens restored (pseudonyms stay).
|
|
20
|
-
//
|
|
21
|
-
// PRIVACY IS OPTIONAL. With no `vault` (redaction off), ②③④ are pass-throughs —
|
|
22
|
-
// no latency, no placeholder confusion — but ⓪ selectTools STILL narrows, because
|
|
23
|
-
// not every turn is privacy-sensitive yet every turn benefits from fewer tools.
|
|
24
|
-
//
|
|
25
|
-
// Self-contained on the SYNCED engine files (pii-redact.js, tool-rank.js), so the
|
|
26
|
-
// extension (browser ESM) and the gateway (npm) run the exact same code. The caller
|
|
27
|
-
// passes the already-gated `redactOpts` ({tier, entities, dictionary}) it computed
|
|
28
|
-
// from cfg+isPro — tier/dictionary selection stays out of the harness.
|
|
29
|
-
|
|
30
|
-
import { restoreText, restoreWithAliases, redactResultShape } from './pii-redact.js';
|
|
31
|
-
import { narrowSpecs } from './tool-rank.js';
|
|
32
|
-
|
|
33
|
-
// MCP / remote tools are server-prefixed (mcp_server__tool). Local tools
|
|
34
|
-
// (history/meeting/page, or a client's core bash/read) are not — they always get
|
|
35
|
-
// real values and are never narrowed away.
|
|
36
|
-
export const isRemoteToolName = (name) => /^mcp[_-]/i.test(String(name || ''));
|
|
37
|
-
|
|
38
|
-
// Deep restore of a tool-call argument value, undoing reversible tokens AND
|
|
39
|
-
// pseudonyms (tools run locally / on real data; only the model stays blinded).
|
|
40
|
-
export function restoreToolArgs(value, vault) {
|
|
41
|
-
if (!vault) return value;
|
|
42
|
-
if (typeof value === 'string') return restoreWithAliases(value, vault);
|
|
43
|
-
if (Array.isArray(value)) return value.map((v) => restoreToolArgs(v, vault));
|
|
44
|
-
if (value && typeof value === 'object') {
|
|
45
|
-
const out = {};
|
|
46
|
-
for (const k of Object.keys(value)) out[k] = restoreToolArgs(value[k], vault);
|
|
47
|
-
return out;
|
|
48
|
-
}
|
|
49
|
-
return value;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// System-prompt note that tells the model how to behave around placeholders when
|
|
53
|
-
// tools are armed. WITHOUT this, privacy-aware models (Codex, Claude) recognize a
|
|
54
|
-
// [[LOCATION_1]] token as redacted and REFUSE to use it for a lookup ("I can't see
|
|
55
|
-
// your real city") — the opposite of what we want. Weak models call the tool blindly
|
|
56
|
-
// and it works (the harness restores the real value), so the note levels them up.
|
|
57
|
-
//
|
|
58
|
-
// `ownTools`: the model is a relayed CLI agent that brings tools of ITS OWN (Codex's web
|
|
59
|
-
// search, a shell, files). Those run on the far side of the harness and receive the
|
|
60
|
-
// placeholder LITERALLY — a search for "[[ORG_1]] stock price" finds nothing, and the agent
|
|
61
|
-
// reports that "the lookup did not resolve the company". Seen exactly so, on the desktop:
|
|
62
|
-
// Codex chose its own web search over ChatPanel's `find` on one turn and answered from
|
|
63
|
-
// nothing. The extra sentence says which tools restore and which do not, so the choice is
|
|
64
|
-
// no longer a coin toss.
|
|
65
|
-
/**
|
|
66
|
-
* The note for a turn with NO tools armed. The model still meets `[[LOCATION_1]]` in the
|
|
67
|
-
* conversation, and a coding agent told nothing about it stops to ask what the "unresolved
|
|
68
|
-
* placeholder" means — exactly what a redaction layer must never cause. So: treat it as a
|
|
69
|
-
* concrete value, write around it, echo it exactly; the real value is restored on the way
|
|
70
|
-
* back. Short, because there is nothing to call.
|
|
71
|
-
*/
|
|
72
|
-
export function placeholderNote() {
|
|
73
|
-
return 'PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], '
|
|
74
|
-
+ '[[LOCATION_1]], [[ORG_1]] that stand in for the user\'s real private data. Treat each one as '
|
|
75
|
-
+ 'a CONCRETE, specific value you already have — not missing or unknown information. Do not ask '
|
|
76
|
-
+ 'what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason '
|
|
77
|
-
+ 'and write with the placeholder exactly as written; the real value is restored in your answer '
|
|
78
|
-
+ 'automatically.';
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function placeholderToolNote({ toolData = 'real', ownTools = false } = {}) {
|
|
82
|
-
const intro =
|
|
83
|
-
'PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], '
|
|
84
|
-
+ '[[LOCATION_1]], [[ORG_1]] that stand in for the user\'s real private data. ';
|
|
85
|
-
const remote = toolData === 'redactRemote'
|
|
86
|
-
? 'When you call a LOCAL tool the placeholder is automatically replaced with the real '
|
|
87
|
-
+ 'value before the tool runs; REMOTE (MCP) tools deliberately receive the placeholder '
|
|
88
|
-
+ 'to keep private data off third-party servers. '
|
|
89
|
-
: 'When you call ANY tool, these placeholders are AUTOMATICALLY replaced with the real '
|
|
90
|
-
+ 'values before the tool executes — the tool receives the TRUE value and returns correct '
|
|
91
|
-
+ 'results. ';
|
|
92
|
-
const rules =
|
|
93
|
-
'So: treat each placeholder as a CONCRETE, specific value you already have — it is enough to '
|
|
94
|
-
+ 'act on, NOT missing or unknown information. CALL THE TOOL using the placeholder exactly as '
|
|
95
|
-
+ 'written, as if it were the real value. '
|
|
96
|
-
// The common failure isn\'t a privacy refusal — it\'s the model deciding it "lacks data"
|
|
97
|
-
// because the value is a token, and answering from general knowledge instead of looking up.
|
|
98
|
-
+ 'If answering needs the real data behind a placeholder (e.g. which city [[LOCATION_1]] is, '
|
|
99
|
-
+ 'who [[PERSON_1]] is, what [[ORG_1]] does), do NOT reply that you lack information or cannot '
|
|
100
|
-
+ 'answer. Instead pick the most relevant available tool for that placeholder\'s TYPE — LOCATION '
|
|
101
|
-
+ '→ geography / place lookups, PERSON → people lookups, ORG → company/org lookups, dates/IDs → '
|
|
102
|
-
+ 'the matching lookup — and pass the placeholder straight through as the argument. The harness '
|
|
103
|
-
+ 'restores the true value before the tool runs, so the lookup returns correct results. Make your '
|
|
104
|
-
+ 'best-guess tool call FIRST; only conclude you lack data AFTER a tool has actually returned '
|
|
105
|
-
+ 'nothing useful. '
|
|
106
|
-
+ 'Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup '
|
|
107
|
-
+ 'will work. The real values are restored in your final answer automatically, so write your '
|
|
108
|
-
+ 'answer using the placeholders too.';
|
|
109
|
-
const own = ownTools
|
|
110
|
-
? ' ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. Any tool you bring '
|
|
111
|
-
+ 'yourself — your own web search, shell, file or code tools — receives the placeholder '
|
|
112
|
-
+ 'text literally and will find nothing. So for ANY lookup that involves a placeholder, '
|
|
113
|
-
+ 'call the listed tool (for example `find` with action `web_search` or `history_search`) '
|
|
114
|
-
+ 'rather than your own. Prefer the listed tools for lookups in general — the user sees '
|
|
115
|
-
+ 'those as steps — and keep your own tools for what the listed ones cannot do.'
|
|
116
|
-
: '';
|
|
117
|
-
return intro + remote + rules + own;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// Tools whose results come from the PUBLIC web rather than from the user's own machine or
|
|
121
|
-
// accounts. Deliberately a short, explicit allowlist rather than a heuristic: being wrong in
|
|
122
|
-
// the "public" direction would send real PII to a model, so a tool earns its place here only
|
|
123
|
-
// when its output is public by construction. Page tools are NOT here — the user's open tab
|
|
124
|
-
// may be an internal app.
|
|
125
|
-
const PUBLIC_SOURCE_TOOLS = new Set(['web_search', 'web_fetch', 'fetch_url']);
|
|
126
|
-
export function isPublicSourceTool(name) {
|
|
127
|
-
return PUBLIC_SOURCE_TOOLS.has(String(name || '').toLowerCase());
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
export function makeToolHarness({ vault = null, toolData = 'real', redactOpts = null, redactResults = true, remoteTools = null } = {}) {
|
|
131
|
-
const on = !!vault; // privacy enabled for this turn?
|
|
132
|
-
const redactRemote = toolData === 'redactRemote';
|
|
133
|
-
// How we decide a tool is REMOTE (must not receive real PII under redactRemote).
|
|
134
|
-
// Prefer an EXPLICIT set/predicate the caller derived from the toolset (a remote
|
|
135
|
-
// tool not named mcp_* would otherwise be misclassified as local and get real
|
|
136
|
-
// values); fall back to the mcp_* name heuristic when the caller passes nothing.
|
|
137
|
-
const isRemoteTool = typeof remoteTools === 'function' ? remoteTools
|
|
138
|
-
: (remoteTools instanceof Set ? (name) => remoteTools.has(name)
|
|
139
|
-
: isRemoteToolName);
|
|
140
|
-
return {
|
|
141
|
-
enabled: on,
|
|
142
|
-
isRemoteTool,
|
|
143
|
-
|
|
144
|
-
// ⓪ Always-on tool selection (privacy-independent). `available` is any spec
|
|
145
|
-
// list; `opts` forwards { cap, keep, name, description } to the shared ranker.
|
|
146
|
-
selectTools(available, query, opts = {}) {
|
|
147
|
-
return narrowSpecs(available, query, opts);
|
|
148
|
-
},
|
|
149
|
-
|
|
150
|
-
// ② What the tool receives.
|
|
151
|
-
toTool(name, args) {
|
|
152
|
-
if (!on) return args; // privacy off → already real
|
|
153
|
-
if (redactRemote && isRemoteTool(name)) return args; // keep PII off remote MCP
|
|
154
|
-
return restoreToolArgs(args, vault); // real values for the tool
|
|
155
|
-
},
|
|
156
|
-
|
|
157
|
-
// ③ What the model sees back (re-redacted). Walks string / { text } / array /
|
|
158
|
-
// MCP { content:[{text}] } shapes so a tool result can't leak PII to the model
|
|
159
|
-
// via a nested field the old string/{text}-only path skipped.
|
|
160
|
-
toModelResult(name, raw) {
|
|
161
|
-
if (!on || !redactResults || !redactOpts) return raw;
|
|
162
|
-
// PUBLIC RESULTS ARE NOT THE USER'S DATA.
|
|
163
|
-
//
|
|
164
|
-
// Redaction exists to stop the user's information LEAVING the device. Text coming back
|
|
165
|
-
// from a public web search never left it — the model's provider could fetch the same
|
|
166
|
-
// page itself — so rewriting it buys no privacy and actively corrupts facts: a
|
|
167
|
-
// dictionary pseudonym (a user's own name → a stand-in) renamed a same-named public
|
|
168
|
-
// figure inside search results, and the answer came back about a person who does not
|
|
169
|
-
// exist. The detectors
|
|
170
|
-
// (emails, phones, keys) also fire on unrelated strangers' details in fetched pages.
|
|
171
|
-
//
|
|
172
|
-
// So public-source results pass through intact. Everything local or private — history,
|
|
173
|
-
// meetings, notes, the user's own page, any MCP server — is redacted exactly as before,
|
|
174
|
-
// which is where a leak could actually happen.
|
|
175
|
-
if (isPublicSourceTool(name)) return raw;
|
|
176
|
-
return redactResultShape(raw, vault, redactOpts);
|
|
177
|
-
},
|
|
178
|
-
|
|
179
|
-
// ④ The final reply the user sees.
|
|
180
|
-
toUser(text) {
|
|
181
|
-
return on ? restoreText(text, vault) : text;
|
|
182
|
-
},
|
|
183
|
-
};
|
|
184
|
-
}
|
|
1
|
+
import{restoreText as d,restoreWithAliases as p,redactResultShape as f}from"./pii-redact.js";import{narrowSpecs as y}from"./tool-rank.js";const O=e=>/^mcp[_-]/i.test(String(e||""));function i(e,a){if(!a)return e;if(typeof e=="string")return p(e,a);if(Array.isArray(e))return e.map(t=>i(t,a));if(e&&typeof e=="object"){const t={};for(const s of Object.keys(e))t[s]=i(e[s],a);return t}return e}function m(){return"PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. Treat each one as a CONCRETE, specific value you already have — not missing or unknown information. Do not ask what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason and write with the placeholder exactly as written; the real value is restored in your answer automatically."}function g({toolData:e="real",ownTools:a=!1}={}){const t="PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. ",s=e==="redactRemote"?"When you call a LOCAL tool the placeholder is automatically replaced with the real value before the tool runs; REMOTE (MCP) tools deliberately receive the placeholder to keep private data off third-party servers. ":"When you call ANY tool, these placeholders are AUTOMATICALLY replaced with the real values before the tool executes — the tool receives the TRUE value and returns correct results. ",n="So: treat each placeholder as a CONCRETE, specific value you already have — it is enough to act on, NOT missing or unknown information. CALL THE TOOL using the placeholder exactly as written, as if it were the real value. If answering needs the real data behind a placeholder (e.g. which city [[LOCATION_1]] is, who [[PERSON_1]] is, what [[ORG_1]] does), do NOT reply that you lack information or cannot answer. Instead pick the most relevant available tool for that placeholder's TYPE — LOCATION → geography / place lookups, PERSON → people lookups, ORG → company/org lookups, dates/IDs → the matching lookup — and pass the placeholder straight through as the argument. The harness restores the true value before the tool runs, so the lookup returns correct results. Make your best-guess tool call FIRST; only conclude you lack data AFTER a tool has actually returned nothing useful. Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup will work. The real values are restored in your final answer automatically, so write your answer using the placeholders too.",l=a?" ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. Any tool you bring yourself — your own web search, shell, file or code tools — receives the placeholder text literally and will find nothing. So for ANY lookup that involves a placeholder, call the listed tool (for example `find` with action `web_search` or `history_search`) rather than your own. Prefer the listed tools for lookups in general — the user sees those as steps — and keep your own tools for what the listed ones cannot do.":"";return t+s+n+l}const T=new Set(["web_search","web_fetch","fetch_url"]);function w(e){return T.has(String(e||"").toLowerCase())}function N({vault:e=null,toolData:a="real",redactOpts:t=null,redactResults:s=!0,remoteTools:n=null}={}){const l=!!e,c=a==="redactRemote",h=typeof n=="function"?n:n instanceof Set?o=>n.has(o):O;return{enabled:l,isRemoteTool:h,selectTools(o,r,u={}){return y(o,r,u)},toTool(o,r){return!l||c&&h(o)?r:i(r,e)},toModelResult(o,r){return!l||!s||!t||w(o)?r:f(r,e,t)},toUser(o){return l?d(o,e):o}}}export{w as isPublicSourceTool,O as isRemoteToolName,N as makeToolHarness,m as placeholderNote,g as placeholderToolNote,i as restoreToolArgs};
|
package/src/pii/tool-rank.js
CHANGED
|
@@ -1,110 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// Source of truth: chatpanel-pii/tool-rank.js (npm @chatpanel/pii).
|
|
3
|
-
// Edit there, then run: npm run sync:pii
|
|
4
|
-
//
|
|
5
|
-
// Vendored rather than depended on: the bridge ships zero runtime dependencies so a
|
|
6
|
-
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
7
|
-
// single-file binary has nothing to resolve.
|
|
8
|
-
|
|
9
|
-
// Deterministic, model-free tool ranking — shared by the extension's side panel
|
|
10
|
-
// and the gateway, so "auto mode" narrows the same way everywhere (single source
|
|
11
|
-
// of truth, per the no-duplication rule).
|
|
12
|
-
//
|
|
13
|
-
// Ranks tool specs by lexical relevance to a query, weighting each query word by
|
|
14
|
-
// INVERSE DOCUMENT FREQUENCY across the toolset: a distinctive word like "wiki"
|
|
15
|
-
// (in 1–2 tools) counts far more than a common one like "search" (in many) — so
|
|
16
|
-
// "use wiki search" ranks the Wikipedia tool above generic search tools instead
|
|
17
|
-
// of tying them. Latency-sensitive: pure string ops, runs on every turn, no model
|
|
18
|
-
// call. Generic over the spec shape via name/description accessors (the extension
|
|
19
|
-
// uses { name, description }; the gateway uses OpenAI's { function: { name, … } }).
|
|
20
|
-
|
|
21
|
-
const STOP = new Set([
|
|
22
|
-
'the', 'and', 'for', 'with', 'that', 'this', 'use', 'can', 'you', 'your', 'please',
|
|
23
|
-
'about', 'from', 'what', 'who', 'how', 'are', 'was', 'will', 'just', 'tell', 'find',
|
|
24
|
-
'get', 'into', 'them', 'they', 'their', 'name', 'one', 'but', 'not', 'all',
|
|
25
|
-
]);
|
|
26
|
-
|
|
27
|
-
const defName = (s) => (s && s.name) || '';
|
|
28
|
-
const defDesc = (s) => (s && s.description) || '';
|
|
29
|
-
|
|
30
|
-
// Names of GENERAL entry-point tools — preferred when a query doesn't pin a specific
|
|
31
|
-
// tool. Matches the tool segment (after the server prefix): e.g. ...__wikipedia_search,
|
|
32
|
-
// ...__ask_pipeworx, ...__get_summary, ...__search_wikipedia.
|
|
33
|
-
const GENERAL_TOOL_RE = /(?:^|_)(search|ask|lookup|find|answer|summary|wiki)(?:_|$)/i;
|
|
34
|
-
|
|
35
|
-
// Returns specs scored + sorted most-relevant first, as [{ s, i, n }] (i = original
|
|
36
|
-
// index, n = score). Stable for ties (preserves original order).
|
|
37
|
-
export function scoreToolSpecs(specs, query, { name = defName, description = defDesc } = {}) {
|
|
38
|
-
const q = String(query || '').toLowerCase();
|
|
39
|
-
const words = [...new Set(q.split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP.has(w)))];
|
|
40
|
-
const list = [...(specs || [])];
|
|
41
|
-
const names = list.map((s) => String(name(s) || '').toLowerCase());
|
|
42
|
-
const hays = list.map((s, i) => `${names[i]} ${String(description(s) || '').toLowerCase()}`);
|
|
43
|
-
const N = list.length || 1;
|
|
44
|
-
const df = {}; // how many tools mention each query word
|
|
45
|
-
for (const w of words) df[w] = hays.reduce((n, h) => n + (h.includes(w) ? 1 : 0), 0);
|
|
46
|
-
const idf = (w) => Math.log(1 + N / (1 + (df[w] || 0))); // rarer → higher weight
|
|
47
|
-
const score = (i) => {
|
|
48
|
-
let n = 0;
|
|
49
|
-
for (const w of words) if (hays[i].includes(w)) n += idf(w);
|
|
50
|
-
for (const part of names[i].split(/[^a-z0-9]+/)) {
|
|
51
|
-
if (part.length > 2 && q.includes(part)) n += 2 + idf(part); // tool explicitly named
|
|
52
|
-
}
|
|
53
|
-
// General-purpose ENTRY-POINT tools (search / ask / lookup / get-summary / answer)
|
|
54
|
-
// are the right default when the query doesn't keyword-match a specific tool —
|
|
55
|
-
// e.g. "which state is Seattle in" → a wikipedia SEARCH/ASK tool, not one of 20
|
|
56
|
-
// dataset-query tools. A small tie-breaker boost (below a real keyword match) so
|
|
57
|
-
// those generic tools win when nothing else distinguishes them.
|
|
58
|
-
if (GENERAL_TOOL_RE.test(names[i])) n += 1.5;
|
|
59
|
-
return n;
|
|
60
|
-
};
|
|
61
|
-
return list.map((s, i) => ({ s, i, n: score(i) })).sort((a, b) => (b.n - a.n) || (a.i - b.i));
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// Rank tool specs most-relevant first (stable for ties).
|
|
65
|
-
export function rankToolSpecs(specs, query, accessors) {
|
|
66
|
-
return scoreToolSpecs(specs, query, accessors).map((x) => x.s);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Narrow a flat spec list to at most `cap` entries that DON'T match `keep`, always
|
|
70
|
-
// retaining everything that does (e.g. local page/history tools). `cap` therefore
|
|
71
|
-
// bounds the NARROWABLE (MCP) tools; kept tools ride along free. Returns the list
|
|
72
|
-
// unchanged when there's no cap or the narrowable set already fits.
|
|
73
|
-
// The MCP server a tool belongs to: mcp_<server>__<tool> → "mcp_<server>". Tools
|
|
74
|
-
// without that shape are their own "server" (never grouped together).
|
|
75
|
-
function serverKey(n) {
|
|
76
|
-
const s = String(n || '');
|
|
77
|
-
const i = s.indexOf('__');
|
|
78
|
-
return i > 0 ? s.slice(0, i) : s;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function narrowSpecs(specs, query, { cap = 0, keep, name = defName, description = defDesc } = {}) {
|
|
82
|
-
const list = specs || [];
|
|
83
|
-
if (!cap || cap < 1) return list;
|
|
84
|
-
const kept = keep ? list.filter(keep) : [];
|
|
85
|
-
const rest = keep ? list.filter((s) => !kept.includes(s)) : list;
|
|
86
|
-
if (rest.length <= cap) return list;
|
|
87
|
-
// SERVER-DIVERSE selection: rank all narrowable tools, then pick ROUND-ROBIN across
|
|
88
|
-
// servers — each server's best tool first, then seconds, … up to `cap`. This keeps
|
|
89
|
-
// a relevant server (e.g. wikipedia) from being crowded out of the top-K by another
|
|
90
|
-
// server that happens to have many tools. Servers are visited best-first (the order
|
|
91
|
-
// their top-ranked tool appears in the global ranking).
|
|
92
|
-
const ranked = rankToolSpecs(rest, query, { name, description });
|
|
93
|
-
const queues = new Map(); // serverKey -> [tools] in rank order (insertion = best-first)
|
|
94
|
-
for (const s of ranked) {
|
|
95
|
-
const k = serverKey(name(s));
|
|
96
|
-
if (!queues.has(k)) queues.set(k, []);
|
|
97
|
-
queues.get(k).push(s);
|
|
98
|
-
}
|
|
99
|
-
const lanes = [...queues.values()];
|
|
100
|
-
const chosen = new Set();
|
|
101
|
-
for (let round = 0; chosen.size < cap; round++) {
|
|
102
|
-
let advanced = false;
|
|
103
|
-
for (const lane of lanes) {
|
|
104
|
-
if (chosen.size >= cap) break;
|
|
105
|
-
if (lane.length > round) { chosen.add(lane[round]); advanced = true; }
|
|
106
|
-
}
|
|
107
|
-
if (!advanced) break;
|
|
108
|
-
}
|
|
109
|
-
return list.filter((s) => kept.includes(s) || chosen.has(s)); // preserve original order
|
|
110
|
-
}
|
|
1
|
+
const S=new Set(["the","and","for","with","that","this","use","can","you","your","please","about","from","what","who","how","are","was","will","just","tell","find","get","into","them","they","their","name","one","but","not","all"]),g=n=>n&&n.name||"",m=n=>n&&n.description||"",k=/(?:^|_)(search|ask|lookup|find|answer|summary|wiki)(?:_|$)/i;function y(n,i,{name:o=g,description:c=m}={}){const u=String(i||"").toLowerCase(),d=[...new Set(u.split(/[^a-z0-9]+/).filter(t=>t.length>2&&!S.has(t)))],s=[...n||[]],f=s.map(t=>String(o(t)||"").toLowerCase()),h=s.map((t,e)=>`${f[e]} ${String(c(t)||"").toLowerCase()}`),p=s.length||1,a={};for(const t of d)a[t]=h.reduce((e,r)=>e+(r.includes(t)?1:0),0);const w=t=>Math.log(1+p/(1+(a[t]||0))),l=t=>{let e=0;for(const r of d)h[t].includes(r)&&(e+=w(r));for(const r of f[t].split(/[^a-z0-9]+/))r.length>2&&u.includes(r)&&(e+=2+w(r));return k.test(f[t])&&(e+=1.5),e};return s.map((t,e)=>({s:t,i:e,n:l(e)})).sort((t,e)=>e.n-t.n||t.i-e.i)}function _(n,i,o){return y(n,i,o).map(c=>c.s)}function L(n){const i=String(n||""),o=i.indexOf("__");return o>0?i.slice(0,o):i}function x(n,i,{cap:o=0,keep:c,name:u=g,description:d=m}={}){const s=n||[];if(!o||o<1)return s;const f=c?s.filter(c):[],h=c?s.filter(t=>!f.includes(t)):s;if(h.length<=o)return s;const p=_(h,i,{name:u,description:d}),a=new Map;for(const t of p){const e=L(u(t));a.has(e)||a.set(e,[]),a.get(e).push(t)}const w=[...a.values()],l=new Set;for(let t=0;l.size<o;t++){let e=!1;for(const r of w){if(l.size>=o)break;r.length>t&&(l.add(r[t]),e=!0)}if(!e)break}return s.filter(t=>f.includes(t)||l.has(t))}export{x as narrowSpecs,_ as rankToolSpecs,y as scoreToolSpecs};
|
package/src/proc.js
CHANGED
|
@@ -1,91 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
// button aborts the /chat request; server.js turns that disconnect into an abort on
|
|
4
|
-
// this signal. Without this, the agent CLI (codex / claude / agy / custom) keeps
|
|
5
|
-
// running to completion in the background after Stop — burning tokens and holding the
|
|
6
|
-
// session — and only the 3-minute idle timer would eventually reap it.
|
|
7
|
-
//
|
|
8
|
-
// SIGTERM first so the CLI can flush + exit cleanly, then SIGKILL after a short grace if
|
|
9
|
-
// it's still alive. Returns a detach() to drop the listener once the child exits normally.
|
|
10
|
-
//
|
|
11
|
-
// THE SIGNAL MUST REACH THE GRANDCHILDREN. An agent CLI is not one process: codex runs shell
|
|
12
|
-
// commands, claude runs tools, and each of those is a child of the child. `child.kill()`
|
|
13
|
-
// signals exactly one pid, so Stop killed the CLI and left its shell running — a user pressed
|
|
14
|
-
// Stop, watched the panel go quiet, and found the process still going.
|
|
15
|
-
//
|
|
16
|
-
// Signalling the process GROUP fixes that, and only works if the child leads a group of its
|
|
17
|
-
// own — which is what spawnGroupOpts is for. Without that spawn option the child sits in the
|
|
18
|
-
// bridge's own group, and a group kill would signal the bridge.
|
|
19
|
-
|
|
20
|
-
/**
|
|
21
|
-
* Spawn options that make a child its own process-group leader, so the whole tree can be
|
|
22
|
-
* signalled together. No-op on Windows, which has no process groups in this sense — there
|
|
23
|
-
* the taskkill fallback in killTree covers it.
|
|
24
|
-
*/
|
|
25
|
-
export const spawnGroupOpts = process.platform === 'win32' ? {} : { detached: true };
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Every pid descended from `pid`, snapshotted from the process table.
|
|
29
|
-
*
|
|
30
|
-
* A process-group kill is not enough on its own. codex runs each shell step in its OWN
|
|
31
|
-
* process group (`sleep 90` came back with PGID == its own pid), so signalling the group we
|
|
32
|
-
* created deliberately misses it — and once its parent dies it reparents to init, where
|
|
33
|
-
* nothing connects it to the run that started it.
|
|
34
|
-
*
|
|
35
|
-
* So the tree is read BEFORE anything is signalled. Afterwards the links are gone.
|
|
36
|
-
*/
|
|
37
|
-
function descendantsOf(pid) {
|
|
38
|
-
if (!pid || process.platform === 'win32') return [];
|
|
39
|
-
let table = '';
|
|
40
|
-
try {
|
|
41
|
-
table = execFileSync('ps', ['-eo', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 });
|
|
42
|
-
} catch { return []; }
|
|
43
|
-
const kids = new Map();
|
|
44
|
-
for (const line of table.split('\n')) {
|
|
45
|
-
const [p, pp] = line.trim().split(/\s+/).map(Number);
|
|
46
|
-
if (!p || !pp) continue;
|
|
47
|
-
if (!kids.has(pp)) kids.set(pp, []);
|
|
48
|
-
kids.get(pp).push(p);
|
|
49
|
-
}
|
|
50
|
-
const out = [];
|
|
51
|
-
const walk = (root, depth = 0) => {
|
|
52
|
-
// A depth cap rather than a visited set: the table is a snapshot of a tree, and a cycle
|
|
53
|
-
// would mean the kernel lied. The cap is there so a malformed read cannot hang a Stop.
|
|
54
|
-
if (depth > 20) return;
|
|
55
|
-
for (const k of kids.get(root) || []) { out.push(k); walk(k, depth + 1); }
|
|
56
|
-
};
|
|
57
|
-
walk(pid);
|
|
58
|
-
return out;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** Signal a child and everything it spawned. Falls back to the single process. */
|
|
62
|
-
function killTree(child, sig, known = []) {
|
|
63
|
-
if (!child?.pid) return;
|
|
64
|
-
// Descendants first, while the parent is still alive to be traced through. Orphaned
|
|
65
|
-
// grandchildren are the ones the user cannot find or stop afterwards.
|
|
66
|
-
for (const pid of known.length ? known : descendantsOf(child.pid)) {
|
|
67
|
-
try { process.kill(pid, sig); } catch { /* already gone */ }
|
|
68
|
-
}
|
|
69
|
-
try {
|
|
70
|
-
// Negative pid = the whole group. Only valid for a detached child; the catch covers a
|
|
71
|
-
// child spawned without it, which is still better killed alone than not at all.
|
|
72
|
-
process.kill(-child.pid, sig);
|
|
73
|
-
return;
|
|
74
|
-
} catch { /* not a group leader, or already gone */ }
|
|
75
|
-
try { child.kill(sig); } catch { /* already exited */ }
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export function killOnAbort(child, signal, { graceMs = 1500 } = {}) {
|
|
79
|
-
if (!signal || !child) return () => {};
|
|
80
|
-
const onAbort = () => {
|
|
81
|
-
// Snapshot ONCE, up front: by the time the grace period expires the parent is gone and
|
|
82
|
-
// the tree cannot be walked, so the escalation would have nothing left to aim at.
|
|
83
|
-
const tree = descendantsOf(child.pid);
|
|
84
|
-
killTree(child, 'SIGTERM', tree);
|
|
85
|
-
const t = setTimeout(() => killTree(child, 'SIGKILL', tree), graceMs);
|
|
86
|
-
if (t.unref) t.unref(); // don't keep the event loop alive just for the grace timer
|
|
87
|
-
};
|
|
88
|
-
if (signal.aborted) { onAbort(); return () => {}; }
|
|
89
|
-
signal.addEventListener('abort', onAbort, { once: true });
|
|
90
|
-
return () => { try { signal.removeEventListener('abort', onAbort); } catch { /* noop */ } };
|
|
91
|
-
}
|
|
1
|
+
import{execFileSync as f}from"node:child_process";const l=process.platform==="win32"?{}:{detached:!0};function i(t){if(!t||process.platform==="win32")return[];let e="";try{e=f("ps",["-eo","pid=,ppid="],{encoding:"utf8",timeout:2e3})}catch{return[]}const r=new Map;for(const s of e.split(`
|
|
2
|
+
`)){const[p,o]=s.trim().split(/\s+/).map(Number);!p||!o||(r.has(o)||r.set(o,[]),r.get(o).push(p))}const n=[],c=(s,p=0)=>{if(!(p>20))for(const o of r.get(s)||[])n.push(o),c(o,p+1)};return c(t),n}function u(t,e,r=[]){if(t?.pid){for(const n of r.length?r:i(t.pid))try{process.kill(n,e)}catch{}try{process.kill(-t.pid,e);return}catch{}try{t.kill(e)}catch{}}}function m(t,e,{graceMs:r=1500}={}){if(!e||!t)return()=>{};const n=()=>{const c=i(t.pid);u(t,"SIGTERM",c);const s=setTimeout(()=>u(t,"SIGKILL",c),r);s.unref&&s.unref()};return e.aborted?(n(),()=>{}):(e.addEventListener("abort",n,{once:!0}),()=>{try{e.removeEventListener("abort",n)}catch{}})}export{m as killOnAbort,l as spawnGroupOpts};
|
package/src/relay-timeout.js
CHANGED
|
@@ -1,21 +1 @@
|
|
|
1
|
-
|
|
2
|
-
// MCP timeouts, so neither gives up before the other.
|
|
3
|
-
//
|
|
4
|
-
// A spec may declare `timeoutMs` (additive to the /chat contract — older extensions send
|
|
5
|
-
// none and keep the two-minute default): a team run declares its budget plus the merge. Before
|
|
6
|
-
// this, a 300 s team hit the relay's flat 120 s, Claude Code was handed "tool call timed out"
|
|
7
|
-
// while the extension was still working, and ran the team a SECOND time; the first run's
|
|
8
|
-
// result then had nowhere to go.
|
|
9
|
-
export const RELAY_TIMEOUT_DEFAULT_MS = 120_000;
|
|
10
|
-
export const RELAY_TIMEOUT_MAX_MS = 60 * 60_000;
|
|
11
|
-
|
|
12
|
-
/** The relay's timeout for one tool of a session. */
|
|
13
|
-
export function relayTimeoutFor(specs, name) {
|
|
14
|
-
const declared = Number((specs || []).find((s) => s?.name === name)?.timeoutMs) || 0;
|
|
15
|
-
return Math.min(RELAY_TIMEOUT_MAX_MS, Math.max(RELAY_TIMEOUT_DEFAULT_MS, declared));
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/** The longest any tool of a session may take — what a CLI's own MCP tool timeout is set to. */
|
|
19
|
-
export function relayTimeoutMax(specs) {
|
|
20
|
-
return Math.max(RELAY_TIMEOUT_DEFAULT_MS, ...(specs || []).map((s) => relayTimeoutFor(specs, s?.name)));
|
|
21
|
-
}
|
|
1
|
+
const n=12e4,o=36e5;function T(t,M){const _=Number((t||[]).find(e=>e?.name===M)?.timeoutMs)||0;return Math.min(36e5,Math.max(12e4,_))}function r(t){return Math.max(12e4,...(t||[]).map(M=>T(t,M?.name)))}export{n as RELAY_TIMEOUT_DEFAULT_MS,o as RELAY_TIMEOUT_MAX_MS,T as relayTimeoutFor,r as relayTimeoutMax};
|