@chatpanel/bridge 0.11.6 → 0.11.8
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 +1 -1
- package/src/channels/adapters/telegram.js +47 -4
- package/src/channels/service.js +24 -8
- package/src/pii/pii-detect.js +76 -18
- package/src/server.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine \u2014 Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) \u2014 to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
|
@@ -38,6 +38,29 @@ const HELP = [
|
|
|
38
38
|
* it needs is injected — a bot token, the bridge address+token, a pairing store, an event sink
|
|
39
39
|
* — so nothing here reads a secret or reaches for global state.
|
|
40
40
|
*/
|
|
41
|
+
// What a turn driven from a phone can actually DO, told to the agent up front.
|
|
42
|
+
//
|
|
43
|
+
// Without this the agent plans as if it were sitting at a terminal: asked to create a note it
|
|
44
|
+
// announced it would look for a notes folder, discovered writes were not enabled, said "let me
|
|
45
|
+
// check what notes tools are available" — and stopped mid-thought, having done nothing and
|
|
46
|
+
// explained nothing. The ceiling is real and enforced elsewhere (reach caps the toolset); the
|
|
47
|
+
// agent simply had no way to know about it, so it spent a turn discovering it and left the
|
|
48
|
+
// user staring at half a sentence.
|
|
49
|
+
export function channelSystem(userSystem, reach) {
|
|
50
|
+
const limits = !reach || reach === 'any' ? '' : [
|
|
51
|
+
"You are answering a message sent from the user's PHONE, relayed to this machine.",
|
|
52
|
+
reach === 'device'
|
|
53
|
+
? 'You cannot read files, run commands, browse the web, or change anything.'
|
|
54
|
+
: "You can READ files and search the user's ChatPanel history. You cannot write or edit "
|
|
55
|
+
+ 'files, run shell commands, or browse the web — those are switched off for messages '
|
|
56
|
+
+ 'from a phone, and no tool will grant them.',
|
|
57
|
+
'If a request needs something you cannot do, say so plainly in your FIRST reply and offer '
|
|
58
|
+
+ 'what you can do instead. Never begin work you cannot finish.',
|
|
59
|
+
'Answers are read on a phone: be brief, and put the answer first.',
|
|
60
|
+
].join(' ');
|
|
61
|
+
return [limits, userSystem].filter(Boolean).join('\n\n');
|
|
62
|
+
}
|
|
63
|
+
|
|
41
64
|
export function startTelegram({
|
|
42
65
|
botToken,
|
|
43
66
|
baseUrl,
|
|
@@ -54,6 +77,15 @@ export function startTelegram({
|
|
|
54
77
|
model = '',
|
|
55
78
|
provider = '',
|
|
56
79
|
system = '',
|
|
80
|
+
// Read at the START OF EACH MESSAGE rather than captured when the loop starts.
|
|
81
|
+
//
|
|
82
|
+
// `chats` below holds every conversation's history AND its privacy vault, and it lives only
|
|
83
|
+
// as long as this loop. Settings used to be baked in at start, so changing the model — or
|
|
84
|
+
// the privacy mode, or anything else — had to stop and respawn the loop, which silently threw
|
|
85
|
+
// all of that away: the next message arrived as "a fresh session with no prior conversation",
|
|
86
|
+
// and PERSON_1 stopped meaning the same person. Switching which model answers is not a
|
|
87
|
+
// reason to forget what you were talking about.
|
|
88
|
+
route = null,
|
|
57
89
|
redact = { tier: 'basic' },
|
|
58
90
|
privacy = 'standard',
|
|
59
91
|
logger = console,
|
|
@@ -120,7 +152,7 @@ export function startTelegram({
|
|
|
120
152
|
}
|
|
121
153
|
if (name === 'stop') {
|
|
122
154
|
const st = chatState(norm.chatId);
|
|
123
|
-
const ok = await transport.cancel(st.runId, { baseUrl, token });
|
|
155
|
+
const ok = await ((route && route().transport) || transport).cancel(st.runId, { baseUrl, token });
|
|
124
156
|
st.runId = null;
|
|
125
157
|
return void send(norm.chatId, ok ? '⏹ stopped.' : 'nothing running.');
|
|
126
158
|
}
|
|
@@ -157,11 +189,22 @@ export function startTelegram({
|
|
|
157
189
|
// on the bridge renders all-but-last as history and the last as "answer this now".
|
|
158
190
|
const messages = [...st.history, { role: 'user', content: redacted }];
|
|
159
191
|
|
|
192
|
+
// Whatever the settings say RIGHT NOW — see `route` above.
|
|
193
|
+
const live = (route && route()) || {};
|
|
194
|
+
const useTransport = live.transport || transport;
|
|
160
195
|
try {
|
|
161
|
-
const finalState = await
|
|
162
|
-
{
|
|
196
|
+
const finalState = await useTransport.chat(
|
|
197
|
+
{
|
|
198
|
+
agent: live.agent ?? agent,
|
|
199
|
+
model: live.model ?? model,
|
|
200
|
+
provider: live.provider ?? provider,
|
|
201
|
+
system: channelSystem(live.system ?? system, reach),
|
|
202
|
+
messages,
|
|
203
|
+
images,
|
|
204
|
+
options: { reach },
|
|
205
|
+
},
|
|
163
206
|
{
|
|
164
|
-
baseUrl, token, signal,
|
|
207
|
+
baseUrl: live.baseUrl || baseUrl, token, signal,
|
|
165
208
|
onEvent: (ev, state) => {
|
|
166
209
|
if (state.runId) st.runId = state.runId;
|
|
167
210
|
// Driven by the folded STATE, not by an event's `type`: the bridge emits
|
package/src/channels/service.js
CHANGED
|
@@ -132,14 +132,28 @@ export function createChannelService({
|
|
|
132
132
|
function spawnLoop(botToken) {
|
|
133
133
|
controller = new AbortController();
|
|
134
134
|
running = true;
|
|
135
|
-
//
|
|
136
|
-
|
|
135
|
+
// Resolved PER MESSAGE, not once at start. The loop owns every conversation's history and
|
|
136
|
+
// privacy vault, so restarting it to pick up a settings change threw away the thing the
|
|
137
|
+
// user came for. Now nothing needs a restart: the next message simply reads this.
|
|
138
|
+
const route = () => {
|
|
139
|
+
const viaGateway = !!settings.model;
|
|
140
|
+
return {
|
|
141
|
+
transport: viaGateway ? gateway : bridgeTransport,
|
|
142
|
+
agent: viaGateway ? '' : settings.agent,
|
|
143
|
+
model: viaGateway ? settings.model : '',
|
|
144
|
+
provider: viaGateway ? (settings.provider || '') : '',
|
|
145
|
+
baseUrl: viaGateway ? (settings.gatewayUrl || DEFAULT_GATEWAY_URL) : bridge.baseUrl,
|
|
146
|
+
system: settings.system || '',
|
|
147
|
+
privacy: settings.privacy,
|
|
148
|
+
};
|
|
149
|
+
};
|
|
137
150
|
const done = startAdapter({
|
|
138
151
|
botToken,
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
152
|
+
route,
|
|
153
|
+
transport: route().transport,
|
|
154
|
+
model: route().model,
|
|
155
|
+
provider: route().provider,
|
|
156
|
+
baseUrl: route().baseUrl,
|
|
143
157
|
token: bridge.token,
|
|
144
158
|
pairing,
|
|
145
159
|
savePairing,
|
|
@@ -258,8 +272,10 @@ export function createChannelService({
|
|
|
258
272
|
if (patch.model) next.agent = '';
|
|
259
273
|
settings = next;
|
|
260
274
|
await saveSettings();
|
|
261
|
-
//
|
|
262
|
-
|
|
275
|
+
// NO RESTART. The loop reads settings per message through `route`, and restarting it
|
|
276
|
+
// would discard every conversation's history and vault — which is exactly what made
|
|
277
|
+
// changing the model answer the next question with "this looks like a fresh session".
|
|
278
|
+
// The only change that still needs a restart is a new bot token, and connect() does that.
|
|
263
279
|
return { settings: { ...settings } };
|
|
264
280
|
},
|
|
265
281
|
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -109,10 +109,19 @@ export function parseJsonLoose(s) {
|
|
|
109
109
|
try { return JSON.parse(String(s).slice(a, b + 1)); } catch { return null; }
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
+
// The instruction WITHOUT the shape. The shape now comes from ENTITIES_SCHEMA in
|
|
113
|
+
// `@chatpanel/events` — the one object that renders the prompt block, builds the
|
|
114
|
+
// `response_format` a server enforces, and reads the reply. INJECTED, not imported: this
|
|
115
|
+
// package ships zero dependencies so the bridge can vendor it. A host without it still works.
|
|
112
116
|
export const EXTRACT_SYS = 'You extract sensitive entities from text for redaction. '
|
|
113
|
-
+ 'Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. '
|
|
114
117
|
+ 'Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.';
|
|
115
118
|
|
|
119
|
+
const FALLBACK_SHAPE = 'Return ONLY JSON: {"entities":[{"value":"<verbatim text>",'
|
|
120
|
+
+ '"type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.';
|
|
121
|
+
|
|
122
|
+
// The seam: { block, format(mode), parse(text) }. Absent, everything below behaves as before.
|
|
123
|
+
const NO_STRUCTURE = Object.freeze({ block: '', format: null, parse: null });
|
|
124
|
+
|
|
116
125
|
async function detectViaEndpoint(text, det, signal, fetchImpl) {
|
|
117
126
|
const res = await fetchImpl(det.url, {
|
|
118
127
|
method: 'POST',
|
|
@@ -124,7 +133,7 @@ async function detectViaEndpoint(text, det, signal, fetchImpl) {
|
|
|
124
133
|
return normalizeEntities(await res.json(), det.types);
|
|
125
134
|
}
|
|
126
135
|
|
|
127
|
-
async function detectViaOpenAI(text, det, signal, fetchImpl) {
|
|
136
|
+
async function detectViaOpenAI(text, det, signal, fetchImpl, structured = NO_STRUCTURE) {
|
|
128
137
|
const base = String(det.url || '').replace(/\/$/, '');
|
|
129
138
|
// Build the chat URL the SAME way the chat path does. An OpenAI-compatible baseUrl
|
|
130
139
|
// already ends in /v1 (Ollama, OpenRouter, NVIDIA, OpenAI…) → only add
|
|
@@ -133,25 +142,70 @@ async function detectViaOpenAI(text, det, signal, fetchImpl) {
|
|
|
133
142
|
const url = /\/chat\/completions$/.test(base) ? base
|
|
134
143
|
: /\/v\d+$/.test(base) ? `${base}/chat/completions`
|
|
135
144
|
: `${base}/v1/chat/completions`;
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
145
|
+
const sys = `${EXTRACT_SYS}\n\n${structured.block || FALLBACK_SHAPE}`;
|
|
146
|
+
const ask = async (mode) => {
|
|
147
|
+
const fmt = structured.format ? structured.format(mode) : null;
|
|
148
|
+
const res = await fetchImpl(url, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { 'Content-Type': 'application/json', ...(det.apiKey ? { Authorization: `Bearer ${det.apiKey}` } : {}) },
|
|
151
|
+
body: JSON.stringify({
|
|
152
|
+
model: det.model || 'local',
|
|
153
|
+
temperature: 0,
|
|
154
|
+
max_tokens: det.maxTokens || 256,
|
|
155
|
+
messages: [{ role: 'system', content: sys }, { role: 'user', content: text }],
|
|
156
|
+
...(fmt || {}),
|
|
157
|
+
}),
|
|
158
|
+
signal,
|
|
159
|
+
});
|
|
160
|
+
// 400/422 is the server saying it does not understand the body — a different thing from
|
|
161
|
+
// being down, and the only one worth retrying with a weaker one.
|
|
162
|
+
if (!res.ok) { const e = new Error(`detect HTTP ${res.status}`); e.status = res.status; throw e; }
|
|
163
|
+
return res.json();
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// Grammar first, then plain JSON mode, then nothing. `json_schema` constrains the decoder to
|
|
167
|
+
// this exact shape — the difference between a 3B local model that answers and one that
|
|
168
|
+
// writes a paragraph — but many servers reject the field, so each rung is tried once.
|
|
169
|
+
let json = null;
|
|
170
|
+
if (structured.format) {
|
|
171
|
+
for (const mode of ['schema', 'object', 'none']) {
|
|
172
|
+
try { json = await ask(mode); break; }
|
|
173
|
+
catch (e) { if (mode === 'none' || (e.status !== 400 && e.status !== 422)) throw e; }
|
|
174
|
+
}
|
|
175
|
+
} else {
|
|
176
|
+
json = await ask('none');
|
|
177
|
+
}
|
|
149
178
|
const content = json?.choices?.[0]?.message?.content ?? json?.content ?? '';
|
|
150
|
-
|
|
179
|
+
// The schema-aligned reader when the host has one; the loose slice otherwise.
|
|
180
|
+
const parsed = structured.parse ? structured.parse(content) : parseJsonLoose(content);
|
|
181
|
+
return normalizeEntities(parsed, det.types);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Never throws: an egress record that could break redaction is worse than no record.
|
|
185
|
+
function report(onEgress, det, sent, t0, count, err) {
|
|
186
|
+
if (typeof onEgress !== 'function') return;
|
|
187
|
+
try {
|
|
188
|
+
onEgress({
|
|
189
|
+
backend: det.backend || '',
|
|
190
|
+
host: hostOf(det.url),
|
|
191
|
+
chars: sent.length,
|
|
192
|
+
entities: count,
|
|
193
|
+
ms: Date.now() - t0,
|
|
194
|
+
ok: !err,
|
|
195
|
+
error: err ? String(err.message || err).slice(0, 200) : '',
|
|
196
|
+
});
|
|
197
|
+
} catch { /* observability must never be the reason detection fails */ }
|
|
151
198
|
}
|
|
152
199
|
|
|
153
200
|
// Returns [{value, type}] spans for `text`, or [] (fail-open) on any error/timeout.
|
|
154
|
-
|
|
201
|
+
// `onEgress` reports that RAW text left for a detector — the FACT, never the text. This is
|
|
202
|
+
// the one call that sends un-redacted content off the device (you cannot redact before you
|
|
203
|
+
// have detected); it is SSRF-guarded but was logged nowhere, and det.url accepts any public
|
|
204
|
+
// host. Injected, like `structured`: this package has no logger. The record carries the HOST
|
|
205
|
+
// (never the full URL, which can hold a token) and counts — never values.
|
|
206
|
+
const hostOf = (u) => { try { return new URL(String(u)).host; } catch { return ''; } };
|
|
207
|
+
|
|
208
|
+
export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis.fetch, strict = false, structured = NO_STRUCTURE, onEgress = null } = {}) {
|
|
155
209
|
const det = cfg?.detection;
|
|
156
210
|
if (!det || !det.backend || det.backend === 'off' || !det.url || typeof fetchImpl !== 'function') return [];
|
|
157
211
|
const capped = String(text || '').slice(0, det.maxChars || 8000);
|
|
@@ -166,7 +220,11 @@ export async function detectEntities(text, cfg, { signal, fetchImpl = globalThis
|
|
|
166
220
|
// is the normal case. A blocked URL fails open (deterministic-only), or surfaces
|
|
167
221
|
// to the Test button in strict mode.
|
|
168
222
|
assertEndpointUrl(det.url);
|
|
169
|
-
|
|
223
|
+
const t0 = Date.now();
|
|
224
|
+
try {
|
|
225
|
+
ents = await withTimeout(run(capped, det, signal, fetchImpl, structured), det.timeoutMs || 1500, signal);
|
|
226
|
+
report(onEgress, det, capped, t0, ents.length, null);
|
|
227
|
+
} catch (e) { report(onEgress, det, capped, t0, 0, e); throw e; }
|
|
170
228
|
} catch (e) {
|
|
171
229
|
if (strict) throw e; // surface errors to the Test button
|
|
172
230
|
ents = []; // otherwise fail open — deterministic redaction still applies
|
package/src/server.js
CHANGED
|
@@ -67,7 +67,7 @@ import {
|
|
|
67
67
|
// Hardcoded (not read from package.json) so it survives Bun's single-file
|
|
68
68
|
// --compile, where package.json isn't on a readable FS. CI fails the publish if
|
|
69
69
|
// this drifts from package.json, so the two can't silently diverge.
|
|
70
|
-
const VERSION = '0.11.
|
|
70
|
+
const VERSION = '0.11.8';
|
|
71
71
|
const HOST = process.env.CHATPANEL_BRIDGE_HOST || '127.0.0.1';
|
|
72
72
|
const PORT = Number(process.env.CHATPANEL_BRIDGE_PORT) || 4319;
|
|
73
73
|
|