@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.
Files changed (62) hide show
  1. package/README.md +7 -7
  2. package/package.json +1 -13
  3. package/scripts/sync-channels.mjs +8 -90
  4. package/scripts/sync-events.mjs +7 -78
  5. package/scripts/sync-pii.mjs +7 -68
  6. package/src/api-compat.js +5 -294
  7. package/src/channels/adapters/telegram.js +3 -298
  8. package/src/channels/bridge.js +1 -59
  9. package/src/channels/eventlog.js +3 -57
  10. package/src/channels/gateway.js +1 -114
  11. package/src/channels/invoke.js +1 -172
  12. package/src/channels/normalize.js +1 -58
  13. package/src/channels/pairing.js +1 -95
  14. package/src/channels/service.js +1 -329
  15. package/src/channels/stream.js +5 -104
  16. package/src/cli-errors.js +3 -136
  17. package/src/connections.js +1 -160
  18. package/src/connectors.js +1 -100
  19. package/src/engines/antigravity.js +5 -235
  20. package/src/engines/args.js +1 -47
  21. package/src/engines/claude.js +6 -586
  22. package/src/engines/cli-agents.js +7 -312
  23. package/src/engines/codex.js +6 -481
  24. package/src/engines/custom.js +17 -577
  25. package/src/engines/prompt.js +6 -32
  26. package/src/engines/stream-formats.js +2 -222
  27. package/src/entitlement.js +1 -77
  28. package/src/env.js +3 -628
  29. package/src/events/capability.js +1 -134
  30. package/src/events/event.js +1 -183
  31. package/src/events/reach.js +1 -31
  32. package/src/events/ref.js +1 -63
  33. package/src/events/scm-connection.js +1 -188
  34. package/src/events/scopes.js +1 -20
  35. package/src/events/skill-manifest.js +1 -338
  36. package/src/events/skill-scan.js +3 -217
  37. package/src/events/view.js +1 -96
  38. package/src/mcp-capabilities.js +2 -139
  39. package/src/mcp-local.js +0 -0
  40. package/src/mcp-quarantine.js +1 -110
  41. package/src/net.js +1 -107
  42. package/src/pii/index.js +1 -29
  43. package/src/pii/net.js +1 -111
  44. package/src/pii/pii-detect.js +2 -296
  45. package/src/pii/pii-redact.js +1 -470
  46. package/src/pii/pipeline.js +1 -137
  47. package/src/pii/sanitize.js +2 -179
  48. package/src/pii/tool-harness.js +1 -184
  49. package/src/pii/tool-rank.js +1 -110
  50. package/src/proc.js +2 -91
  51. package/src/relay-timeout.js +1 -21
  52. package/src/runs.js +1 -49
  53. package/src/sanitize.js +1 -7
  54. package/src/scm.js +1 -76
  55. package/src/server.js +10 -1492
  56. package/src/service.js +11 -176
  57. package/src/sign-in.js +1 -91
  58. package/src/skills.js +1 -399
  59. package/src/ssrf.js +1 -70
  60. package/src/update.js +1 -216
  61. package/src/workdir.js +1 -108
  62. package/src/worktree.js +3 -125
@@ -1,59 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/bridge.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
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. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // The transport to the local agent: POST /chat (SSE) and POST /cancel on the bridge. The
11
- // bridge binds 127.0.0.1:4319 and runs Claude Code / Codex / etc. as CLIs — so this is the ONE
12
- // hop where the (already-redacted) conversation reaches the agent, and it never leaves the
13
- // machine. A channel adapter is a non-browser local client, so it presents the per-install
14
- // bridge token, exactly like any privileged caller.
15
-
16
- import { parseSse, foldEvent, initialState } from './stream.js';
17
-
18
- /**
19
- * Drive one turn. Streams bridge events to onEvent(ev, state) as they arrive AND folds them
20
- * into a final reply state it returns. `agent` is a bridge engine id ('claude','codex',…).
21
- */
22
- export async function chat({ agent = 'claude', system = '', messages, images = [], options = {} }, {
23
- baseUrl, token, signal, onEvent = () => {},
24
- } = {}) {
25
- const res = await fetch(`${baseUrl}/chat`, {
26
- method: 'POST',
27
- headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
28
- body: JSON.stringify({ agent, system, messages, images, options }),
29
- signal,
30
- });
31
- if (!res.ok || !res.body) {
32
- const detail = await res.text().catch(() => '');
33
- throw new Error(`bridge /chat ${res.status}${detail ? `: ${detail.slice(0, 300)}` : ''}`);
34
- }
35
- let state = initialState();
36
- let buffer = '';
37
- const decoder = new TextDecoder();
38
- for await (const chunk of res.body) {
39
- buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
40
- const { events, rest } = parseSse(buffer);
41
- buffer = rest;
42
- for (const ev of events) { state = foldEvent(state, ev); onEvent(ev, state); }
43
- }
44
- return state;
45
- }
46
-
47
- /** Stop a run by the id the bridge emitted as its first {type:'run'} event. Best-effort. */
48
- export async function cancel(runId, { baseUrl, token } = {}) {
49
- if (!runId) return false;
50
- try {
51
- const res = await fetch(`${baseUrl}/cancel`, {
52
- method: 'POST',
53
- headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
54
- body: JSON.stringify({ id: runId }),
55
- });
56
- const out = await res.json().catch(() => ({}));
57
- return !!out.cancelled;
58
- } catch { return false; }
59
- }
1
+ import{parseSse as $,foldEvent as b,initialState as S}from"./stream.js";async function g({agent:o="claude",system:n="",messages:r,images:s=[],options:i={}},{baseUrl:d,token:h,signal:l,onEvent:u=()=>{}}={}){const e=await fetch(`${d}/chat`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${h}`},body:JSON.stringify({agent:o,system:n,messages:r,images:s,options:i}),signal:l});if(!e.ok||!e.body){const t=await e.text().catch(()=>"");throw new Error(`bridge /chat ${e.status}${t?`: ${t.slice(0,300)}`:""}`)}let a=S(),c="";const y=new TextDecoder;for await(const t of e.body){c+=typeof t=="string"?t:y.decode(t,{stream:!0});const{events:p,rest:w}=$(c);c=w;for(const f of p)a=b(a,f),u(f,a)}return a}async function x(o,{baseUrl:n,token:r}={}){if(!o)return!1;try{return!!(await(await fetch(`${n}/cancel`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({id:o})})).json().catch(()=>({}))).cancelled}catch{return!1}}export{x as cancel,g as chat};
@@ -1,57 +1,3 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/eventlog.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
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. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // A file-backed sink for the capability/privacy events a channel run produces — the audit
11
- // trail neither Claude Code Remote nor Hermes has. Events are metadata only (counts, ids;
12
- // never message content — see chatpanel-events/event.js), so this JSONL is safe to keep and
13
- // replicate. One line per event, append-only. seq is owned by the appender and recovered from
14
- // the file on restart so ordering survives a bounce.
15
-
16
- import { appendFile, readFile, mkdir } from 'node:fs/promises';
17
- import path from 'node:path';
18
- import { createAppender } from '../events/event.js';
19
-
20
- async function nextSeq(file) {
21
- try {
22
- const txt = await readFile(file, 'utf8');
23
- let max = -1;
24
- for (const l of txt.split('\n')) {
25
- if (!l) continue;
26
- try { const e = JSON.parse(l); if (Number.isInteger(e.seq)) max = Math.max(max, e.seq); } catch { /* skip */ }
27
- }
28
- return max + 1;
29
- } catch { return 0; }
30
- }
31
-
32
- export async function createEventLog({ file, host = 'channel' }) {
33
- await mkdir(path.dirname(file), { recursive: true });
34
- const seq = await nextSeq(file);
35
- const appender = createAppender({ host, seq, newId: () => globalThis.crypto.randomUUID() });
36
- return {
37
- host,
38
- get seq() { return appender.seq; },
39
- // Same signature as the raw appender, but persists. Returns the validated event.
40
- async append(type, payload, causes = []) {
41
- const e = appender.append(type, payload, causes);
42
- await appendFile(file, JSON.stringify(e) + '\n');
43
- return e;
44
- },
45
- };
46
- }
47
-
48
- // A no-op sink for the allow-list prototype or tests — same interface, writes nothing but
49
- // still builds + validates each event, so a bad payload fails loudly here too.
50
- export function nullEventLog({ host = 'channel' } = {}) {
51
- const appender = createAppender({ host, seq: 0, newId: () => globalThis.crypto.randomUUID() });
52
- return {
53
- host,
54
- get seq() { return appender.seq; },
55
- async append(type, payload, causes = []) { return appender.append(type, payload, causes); },
56
- };
57
- }
1
+ import{appendFile as i,readFile as u,mkdir as d}from"node:fs/promises";import m from"node:path";import{createAppender as c}from"../events/event.js";async function l(e){try{const n=await u(e,"utf8");let t=-1;for(const r of n.split(`
2
+ `))if(r)try{const a=JSON.parse(r);Number.isInteger(a.seq)&&(t=Math.max(t,a.seq))}catch{}return t+1}catch{return 0}}async function g({file:e,host:n="channel"}){await d(m.dirname(e),{recursive:!0});const t=await l(e),r=c({host:n,seq:t,newId:()=>globalThis.crypto.randomUUID()});return{host:n,get seq(){return r.seq},async append(a,p,s=[]){const o=r.append(a,p,s);return await i(e,JSON.stringify(o)+`
3
+ `),o}}}function h({host:e="channel"}={}){const n=c({host:e,seq:0,newId:()=>globalThis.crypto.randomUUID()});return{host:e,get seq(){return n.seq},async append(t,r,a=[]){return n.append(t,r,a)}}}export{g as createEventLog,h as nullEventLog};
@@ -1,114 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/gateway.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
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. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // Gateway backend: reach ANY configured destination — an API provider or a CLI agent —
11
- // through the ChatPanel gateway's OpenAI-compatible endpoint.
12
- //
13
- // channel → POST http://127.0.0.1:4320/v1/chat/completions { model, messages, stream }
14
- //
15
- // WHY THIS EXISTS ALONGSIDE bridge.js. The bridge runs CLI agents, and that is all it can
16
- // answer with — so a phone could only ever talk to Claude Code or Codex, never to the OpenAI,
17
- // Anthropic or local-model endpoints the same user already configured. Those live in the
18
- // gateway, which persists its `destinations` (0600, keys included) and routes a model id to
19
- // an API provider OR back to the bridge for an agent. So the gateway is the superset, and
20
- // pointing a channel at it is what makes "answer from my phone" work with every target the
21
- // user has rather than a subset.
22
- //
23
- // NO NEW SECRET. The alternative was teaching the bridge to hold provider API keys, which
24
- // would have put them on disk a second time, in a second format, with a second thing to
25
- // rotate. The gateway already holds them and already guards them; this borrows the routing
26
- // instead of copying the credentials.
27
- //
28
- // The /v1 data plane is deliberately unauthenticated for local clients — that is the
29
- // gateway's product — so there is no token to present here, and none to leak.
30
-
31
- import { parseSse, foldOpenAiEvent, initialState } from './stream.js';
32
-
33
- // Per-turn aborts, so /stop can cancel a gateway turn the way it cancels a bridge run. The
34
- // bridge hands out a run id for this; OpenAI's API has no such handle, so we mint one and
35
- // keep the controller behind it rather than leaving /stop silently broken on this transport.
36
- const inflight = new Map();
37
-
38
- /**
39
- * Drive one turn against a gateway destination. Same shape as bridge.chat so the adapter does
40
- * not know which transport it has: streams events to onEvent(ev, state) and returns the folded
41
- * final state.
42
- */
43
- export async function chat({ model = '', provider = '', system = '', messages = [], options = {} }, {
44
- baseUrl, signal, onEvent = () => {},
45
- } = {}) {
46
- const runId = `gw_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
47
- const ac = new AbortController();
48
- inflight.set(runId, ac);
49
- // The caller's signal (the poll loop shutting down) must still abort the turn.
50
- const relay = () => ac.abort();
51
- signal?.addEventListener?.('abort', relay, { once: true });
52
-
53
- let state = initialState();
54
- const emit = (ev) => { state = foldOpenAiEvent(state, ev); onEvent(ev, state); };
55
- emit({ type: 'run', id: runId });
56
-
57
- try {
58
- const res = await fetch(`${String(baseUrl).replace(/\/$/, '')}/v1/chat/completions`, {
59
- method: 'POST',
60
- headers: {
61
- 'content-type': 'application/json',
62
- // ChatPanel's routing metadata goes in HEADERS, never in the request body. It rode the
63
- // body first and NVIDIA answered "unsupported parameters": OpenAI-compatible providers
64
- // validate the body strictly and reject unknown fields, while ignoring unknown headers.
65
- // The gateway strips x-chatpanel-* before forwarding, so the provider never sees it.
66
- ...(options?.reach ? { 'x-chatpanel-reach': options.reach } : {}),
67
- // WHICH provider, not just which model. A model id is not a unique key — two providers
68
- // can serve the same one — so without this the gateway picks whichever destination it
69
- // lists first and the call goes out on a key the user never chose.
70
- ...(provider ? { 'x-chatpanel-destination': provider } : {}),
71
- },
72
- body: JSON.stringify({
73
- model,
74
- stream: true,
75
- messages: [
76
- ...(system ? [{ role: 'system', content: system }] : []),
77
- ...messages.map((m) => ({ role: m.role, content: String(m.content ?? '') })),
78
- ],
79
- }),
80
- signal: ac.signal,
81
- });
82
- if (!res.ok || !res.body) {
83
- const detail = await res.text().catch(() => '');
84
- throw new Error(`gateway ${res.status}${detail ? `: ${detail.slice(0, 300)}` : ''}`);
85
- }
86
- let buffer = '';
87
- const decoder = new TextDecoder();
88
- for await (const chunk of res.body) {
89
- buffer += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
90
- const { events, rest } = parseSse(buffer);
91
- buffer = rest;
92
- for (const ev of events) emit(ev);
93
- }
94
- // OpenAI streams end with `data: [DONE]`, which is not JSON and is dropped by parseSse —
95
- // so a stream that ended cleanly still has to be marked done here.
96
- if (!state.done) state = { ...state, done: true };
97
- return state;
98
- } catch (e) {
99
- if (ac.signal.aborted) return { ...state, done: true };
100
- return { ...state, done: true, error: e?.message || String(e) };
101
- } finally {
102
- inflight.delete(runId);
103
- signal?.removeEventListener?.('abort', relay);
104
- }
105
- }
106
-
107
- /** Stop a run by the id emitted as the first {type:'run'} event. Best-effort, like the bridge's. */
108
- export async function cancel(runId) {
109
- const ac = runId && inflight.get(runId);
110
- if (!ac) return false;
111
- ac.abort();
112
- inflight.delete(runId);
113
- return true;
114
- }
1
+ import{parseSse as $,foldOpenAiEvent as x,initialState as v}from"./stream.js";const c=new Map;async function O({model:r="",provider:o="",system:l="",messages:g=[],options:d={}},{baseUrl:p,signal:f,onEvent:y=()=>{}}={}){const s=`gw_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,a=new AbortController;c.set(s,a);const u=()=>a.abort();f?.addEventListener?.("abort",u,{once:!0});let e=v();const h=t=>{e=x(e,t),y(t,e)};h({type:"run",id:s});try{const t=await fetch(`${String(p).replace(/\/$/,"")}/v1/chat/completions`,{method:"POST",headers:{"content-type":"application/json",...d?.reach?{"x-chatpanel-reach":d.reach}:{},...o?{"x-chatpanel-destination":o}:{}},body:JSON.stringify({model:r,stream:!0,messages:[...l?[{role:"system",content:l}]:[],...g.map(n=>({role:n.role,content:String(n.content??"")}))]}),signal:a.signal});if(!t.ok||!t.body){const n=await t.text().catch(()=>"");throw new Error(`gateway ${t.status}${n?`: ${n.slice(0,300)}`:""}`)}let i="";const m=new TextDecoder;for await(const n of t.body){i+=typeof n=="string"?n:m.decode(n,{stream:!0});const{events:w,rest:b}=$(i);i=b;for(const S of w)h(S)}return e.done||(e={...e,done:!0}),e}catch(t){return a.signal.aborted?{...e,done:!0}:{...e,done:!0,error:t?.message||String(t)}}finally{c.delete(s),f?.removeEventListener?.("abort",u)}}async function k(r){const o=r&&c.get(r);return o?(o.abort(),c.delete(r),!0):!1}export{k as cancel,O as chat};
@@ -1,172 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/invoke.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
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. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // The invariant core: an inbound message becomes ONE capability invocation with
11
- // actor.kind:'channel', its text is redacted before it can leave for the agent, and both facts
12
- // are written to the event log. Everything here is pure given a vault + an appender — the
13
- // adapter owns the network, this owns the contract.
14
-
15
- import { validateInvocation } from '../events/capability.js';
16
- import { createVault, redactText, restoreText, redactionSummary } from '../pii/index.js';
17
-
18
- // One capability every channel message invokes: "run an agent turn on the user's behalf".
19
- // Effects are non-replayable — a turn runs shell/filesystem tools, so replaying it would
20
- // repeat side effects; that is exactly why validateInvocation demands an idempotencyKey.
21
- export const CHANNEL_CAPABILITY = 'channel.chat';
22
- export const CHANNEL_EFFECTS = 'non-replayable';
23
-
24
- /** Build + validate the invocation for one inbound message. Throws EventError on a bad shape. */
25
- export function buildInvocation({ platform, chatId, messageId }, causes = []) {
26
- const id = `${platform}:${chatId}`;
27
- const inv = {
28
- capability: CHANNEL_CAPABILITY,
29
- actor: { kind: 'channel', id },
30
- scope: { kind: 'session', id },
31
- causes,
32
- effects: CHANNEL_EFFECTS,
33
- // Same platform + chat + message = same turn. Retried delivery must not run it twice.
34
- idempotencyKey: `${platform}:${chatId}:${messageId}`,
35
- };
36
- return validateInvocation(inv);
37
- }
38
-
39
- // Entries per entity type in a vault, so we can diff before/after and report how many NEW
40
- // values a turn redacted — never the values (privacy.redacted is counts-only, by contract).
41
- function countsByType(vault) {
42
- const counts = {};
43
- for (const t of redactionSummary(vault).types) counts[t.type] = t.count;
44
- return counts;
45
- }
46
-
47
- /**
48
- * Redact inbound text into the chat's vault. Returns the redacted text plus the per-turn
49
- * counts delta (for a privacy.redacted event). The vault persists across turns, so PERSON_1
50
- * means the same person every message.
51
- *
52
- * `tier:'basic'` (regex: emails, phones, cards, keys, IPs) is the safe default with no roster;
53
- * pass `tier:'full'` + `entities` to also pseudonymize known people/orgs.
54
- */
55
- export function redactInbound(text, vault, { tier = 'basic', entities = [], dictionary = [] } = {}) {
56
- const before = countsByType(vault);
57
- const redacted = redactText(text ?? '', vault, { tier, entities, dictionary });
58
- const after = countsByType(vault);
59
- const counts = {};
60
- for (const type of Object.keys(after)) {
61
- const d = after[type] - (before[type] || 0);
62
- if (d > 0) counts[type] = d;
63
- }
64
- return { redacted, counts };
65
- }
66
-
67
- /**
68
- * Restore the agent's reply for the user. Two honest modes:
69
- * - 'standard' (default): swap placeholders back to real values. The user reads their own
70
- * data on their own phone — but Telegram/Meta bot traffic is NOT end-to-end encrypted, so
71
- * the provider carries it in the clear. That is the accepted trade for a readable reply.
72
- * - 'strict': leave placeholders in the outbound message. The provider never sees a real
73
- * value; the user sees [[PERSON_1]]. Choose per deployment.
74
- */
75
- export function restoreOutbound(text, vault, { privacy = 'standard' } = {}) {
76
- return privacy === 'strict' ? String(text ?? '') : restoreText(text ?? '', vault);
77
- }
78
-
79
- // A [[TYPE_n]] placeholder token; the capture is the entity TYPE.
80
- const TOKEN_MARKER_RE = /\[\[([A-Z][A-Z0-9]*)_\d+\]\]/g;
81
-
82
- // Hard credentials: catastrophic if they reach a third-party provider, and a user practically
83
- // never types their own into a chat — so we mask these on EVERY egress regardless of privacy
84
- // mode. Contact PII (EMAIL/PHONE/IP) is deliberately NOT here: re-masking it would gut standard
85
- // mode (the user could never read their own data back), so it follows the privacy mode instead.
86
- export const EGRESS_SECRET_TYPES = new Set(['SECRET', 'KEY', 'CARD', 'SSN']);
87
-
88
- /**
89
- * EGRESS SCRUB. Inbound redaction only covers the user's typed message — but the agent can
90
- * surface a NEW secret the vault never saw: a key/token/card it read from a file or a tool and
91
- * echoed into the reply. The reply itself is an egress to a provider (Telegram/Meta) that is NOT
92
- * end-to-end encrypted, so that fresh secret would transit in the clear. This runs a fresh
93
- * detector pass into a THROWAWAY vault and permanently masks the hard-credential types to a
94
- * readable '‹type redacted›' marker.
95
- *
96
- * Run this AFTER restore: at that point no real chat-vault tokens remain, so the single throwaway
97
- * vault numbers cleanly (no [[TYPE_n]] collision) and non-secret detections can be re-expanded to
98
- * the value the user is allowed to read. `restoreNonSecret:false` (strict mode) keeps everything
99
- * tokenized so no real value — fresh or otherwise — is emitted.
100
- */
101
- export function scrubEgress(text, { secretTypes = EGRESS_SECRET_TYPES, restoreNonSecret = true } = {}) {
102
- if (text == null || text === '') return text ?? '';
103
- const tv = createVault();
104
- const masked = redactText(String(text), tv, { tier: 'basic' });
105
- return masked.replace(TOKEN_MARKER_RE, (full, type) => {
106
- if (secretTypes.has(type.toUpperCase())) return `‹${type.toLowerCase()} redacted›`;
107
- return restoreNonSecret ? (tv.byToken.get(full) ?? full) : full;
108
- });
109
- }
110
-
111
- /**
112
- * The single outbound transform: what to actually SEND to the provider for one reply.
113
- * - 'standard': restore the user's own values (they read their own data back), THEN scrub — so
114
- * contact PII the user typed survives, but any hard credential the agent surfaced is masked.
115
- * - 'strict': keep the user's values as placeholders AND still mask fresh credentials, so
116
- * 'strict' is never weaker than 'standard'.
117
- */
118
- export function outboundText(text, vault, { privacy = 'standard' } = {}) {
119
- const restored = restoreOutbound(text, vault, { privacy });
120
- return scrubEgress(restored, { restoreNonSecret: privacy !== 'strict' });
121
- }
122
-
123
- // Conversation memory. The adapter keeps ONE array of REDACTED turns per chat and replays it
124
- // as context, so "…and the second one?" resolves against the prior answer. The bridge's
125
- // buildCliPrompt already renders all-but-last as a labelled history transcript and the last as
126
- // the live message — so multi-turn just works once the array is threaded through.
127
- //
128
- // We store the redacted user text and the agent's (already-placeholdered) reply — never real
129
- // values — so history is exactly as safe to hold as the event log, and the vault stays the one
130
- // source of truth for what PERSON_1 means. The window is bounded so a long chat can't grow the
131
- // prompt without end.
132
- export const DEFAULT_HISTORY_MESSAGES = 16;
133
-
134
- /**
135
- * Append one exchange to a chat's history and return the new, bounded array (never mutates).
136
- * `assistantText` is optional — a failed turn stores nothing, so history never implies the
137
- * agent answered when it didn't.
138
- */
139
- export function appendTurn(history, userText, assistantText, { maxMessages = DEFAULT_HISTORY_MESSAGES } = {}) {
140
- const next = Array.isArray(history) ? history.slice() : [];
141
- next.push({ role: 'user', content: String(userText ?? '') });
142
- const reply = assistantText == null ? '' : String(assistantText);
143
- if (reply) next.push({ role: 'assistant', content: reply });
144
- // Keep only the last maxMessages, and never let the window open on an assistant turn — a
145
- // transcript that starts with "Assistant:" reads as if the agent spoke first.
146
- let windowed = maxMessages > 0 ? next.slice(-maxMessages) : next;
147
- while (windowed.length && windowed[0].role === 'assistant') windowed = windowed.slice(1);
148
- return windowed;
149
- }
150
-
151
- // Event builders — thin, so the adapter appends without knowing payload shapes. Each returns
152
- // whatever the appender's append() returns (a validated event, or a promise of one).
153
- export function appendInvoked(appender, invocation, causes = []) {
154
- return appender.append('capability.invoked', {
155
- capability: invocation.capability,
156
- actor: invocation.actor,
157
- scope: invocation.scope,
158
- effects: invocation.effects,
159
- idempotencyKey: invocation.idempotencyKey,
160
- }, causes);
161
- }
162
-
163
- export function appendRedacted(appender, counts, causes = []) {
164
- // Nothing redacted → nothing to record. An empty privacy.redacted still validates, but a
165
- // log line that says "0 of nothing" is noise.
166
- if (!counts || !Object.keys(counts).length) return null;
167
- return appender.append('privacy.redacted', { counts }, causes);
168
- }
169
-
170
- export function appendEgress(appender, { host, redacted, controlled }, causes = []) {
171
- return appender.append('privacy.egress', { host, redacted: !!redacted, controlled: !!controlled }, causes);
172
- }
1
+ import{validateInvocation as l}from"../events/capability.js";import{createVault as y,redactText as u,restoreText as E,redactionSummary as S}from"../pii/index.js";const b="channel.chat",T="non-replayable";function _({platform:t,chatId:e,messageId:n},r=[]){const o=`${t}:${e}`,c={capability:b,actor:{kind:"channel",id:o},scope:{kind:"session",id:o},causes:r,effects:T,idempotencyKey:`${t}:${e}:${n}`};return l(c)}function f(t){const e={};for(const n of S(t).types)e[n.type]=n.count;return e}function h(t,e,{tier:n="basic",entities:r=[],dictionary:o=[]}={}){const c=f(e),s=u(t??"",e,{tier:n,entities:r,dictionary:o}),i=f(e),a={};for(const p of Object.keys(i)){const d=i[p]-(c[p]||0);d>0&&(a[p]=d)}return{redacted:s,counts:a}}function A(t,e,{privacy:n="standard"}={}){return n==="strict"?String(t??""):E(t??"",e)}const x=/\[\[([A-Z][A-Z0-9]*)_\d+\]\]/g,g=new Set(["SECRET","KEY","CARD","SSN"]);function k(t,{secretTypes:e=g,restoreNonSecret:n=!0}={}){if(t==null||t==="")return t??"";const r=y();return u(String(t),r,{tier:"basic"}).replace(x,(c,s)=>e.has(s.toUpperCase())?`‹${s.toLowerCase()} redacted›`:n?r.byToken.get(c)??c:c)}function N(t,e,{privacy:n="standard"}={}){const r=A(t,e,{privacy:n});return k(r,{restoreNonSecret:n!=="strict"})}const m=16;function I(t,e,n,{maxMessages:r=m}={}){const o=Array.isArray(t)?t.slice():[];o.push({role:"user",content:String(e??"")});const c=n==null?"":String(n);c&&o.push({role:"assistant",content:c});let s=r>0?o.slice(-r):o;for(;s.length&&s[0].role==="assistant";)s=s.slice(1);return s}function K(t,e,n=[]){return t.append("capability.invoked",{capability:e.capability,actor:e.actor,scope:e.scope,effects:e.effects,idempotencyKey:e.idempotencyKey},n)}function $(t,e,n=[]){return!e||!Object.keys(e).length?null:t.append("privacy.redacted",{counts:e},n)}function w(t,{host:e,redacted:n,controlled:r},o=[]){return t.append("privacy.egress",{host:e,redacted:!!n,controlled:!!r},o)}export{b as CHANNEL_CAPABILITY,T as CHANNEL_EFFECTS,m as DEFAULT_HISTORY_MESSAGES,g as EGRESS_SECRET_TYPES,w as appendEgress,K as appendInvoked,$ as appendRedacted,I as appendTurn,_ as buildInvocation,N as outboundText,h as redactInbound,A as restoreOutbound,k as scrubEgress};
@@ -1,58 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/normalize.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
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. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // Platform message → one normalized shape the invoke/stream core understands. PURE: no
11
- // network, no token — a Telegram update object in, a plain record out — so the whole gate
12
- // (pairing, redaction, command routing) is unit-testable without a bot.
13
- //
14
- // One shape for every platform is the same discipline capability.js keeps for actors: the
15
- // adapters are dumb transport, and everything above them speaks 'normalized message'.
16
-
17
- export const CHANNEL_ACTOR_KIND = 'channel';
18
-
19
- /** The actor id a paired surface invokes under: '<platform>:<chatId>'. Stable per chat. */
20
- export function actorId(platform, chatId) {
21
- return `${platform}:${chatId}`;
22
- }
23
-
24
- // A leading "/word" is a command to US (pair/stop/new/help), not a prompt for the agent.
25
- // Telegram appends "@BotName" to commands in groups; strip it so "/stop@mybot" === "/stop".
26
- function parseCommand(text) {
27
- const m = /^\/([a-zA-Z0-9_]+)(?:@\w+)?(?:\s+([\s\S]*))?$/.exec(text.trim());
28
- if (!m) return null;
29
- return { name: m[1].toLowerCase(), args: (m[2] || '').trim() };
30
- }
31
-
32
- /**
33
- * Normalize a Telegram getUpdates result item. Returns null for updates we don't act on
34
- * (edited messages, channel posts, join/leave events) so the caller skips them uniformly.
35
- * A photo's caption is treated as its text, matching how a person reads the message.
36
- */
37
- export function normalizeTelegram(update) {
38
- const msg = update?.message;
39
- if (!msg || !msg.chat) return null;
40
- const text = typeof msg.text === 'string' ? msg.text
41
- : typeof msg.caption === 'string' ? msg.caption : '';
42
- // Largest photo variant only — Telegram sends a size ladder, last is the biggest.
43
- const photos = Array.isArray(msg.photo) && msg.photo.length
44
- ? [{ fileId: msg.photo[msg.photo.length - 1].file_id }]
45
- : [];
46
- const command = text.startsWith('/') ? parseCommand(text) : null;
47
- return {
48
- platform: 'telegram',
49
- chatId: String(msg.chat.id),
50
- chatType: msg.chat.type || 'private',
51
- messageId: String(msg.message_id),
52
- from: { id: String(msg.from?.id ?? msg.chat.id), name: msg.from?.first_name || msg.from?.username || '' },
53
- text,
54
- command,
55
- photos,
56
- replyToMessageId: msg.reply_to_message ? String(msg.reply_to_message.message_id) : null,
57
- };
58
- }
1
+ const s="channel";function i(e,t){return`${e}:${t}`}function a(e){const t=/^\/([a-zA-Z0-9_]+)(?:@\w+)?(?:\s+([\s\S]*))?$/.exec(e.trim());return t?{name:t[1].toLowerCase(),args:(t[2]||"").trim()}:null}function m(e){const t=e?.message;if(!t||!t.chat)return null;const r=typeof t.text=="string"?t.text:typeof t.caption=="string"?t.caption:"",n=Array.isArray(t.photo)&&t.photo.length?[{fileId:t.photo[t.photo.length-1].file_id}]:[],o=r.startsWith("/")?a(r):null;return{platform:"telegram",chatId:String(t.chat.id),chatType:t.chat.type||"private",messageId:String(t.message_id),from:{id:String(t.from?.id??t.chat.id),name:t.from?.first_name||t.from?.username||""},text:r,command:o,photos:n,replyToMessageId:t.reply_to_message?String(t.reply_to_message.message_id):null}}export{s as CHANNEL_ACTOR_KIND,i as actorId,m as normalizeTelegram};
@@ -1,95 +1 @@
1
- // GENERATED — do not edit.
2
- // Source of truth: chatpanel-channels/src/pairing.js (npm @chatpanel/channels).
3
- // Edit there, then run: npm run sync:channels
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. Package imports are rewritten to the
8
- // vendored engines (src/pii, src/events) by the sync script.
9
-
10
- // Pairing — who may drive an agent from a phone, and how far their requests may travel.
11
- //
12
- // This is the AUTHENTICATION half of §7: it proves WHO sent a message (Telegram authenticates
13
- // the sender's chat id; a one-time code makes enrollment deliberate, not silent). It says
14
- // nothing about WHAT a message may do — a paired-but-injected message is still injected, so
15
- // `reach` is a ceiling, never a licence. Tool authorization is the next layer up.
16
- //
17
- // Reach reuses the router's tiers verbatim (device < trusted < any), so "a paired phone is
18
- // trusted" means the exact same thing here as it does to the model router downstream.
19
-
20
- import { REACH } from '../events/reach.js';
21
-
22
- export { REACH };
23
-
24
- // 6 digits: enough entropy for a short-lived, single-use enrollment code shown on a screen,
25
- // short enough to thumb into a phone. It is NOT a password — it expires and burns on first use.
26
- // A display name from a remote platform is untrusted text that lands in the owner's settings
27
- // screen: strip control characters and bidi overrides (which can make one name render as
28
- // another), collapse whitespace, and cap it. The UI escapes too — this is the other half.
29
- function cleanLabel(value) {
30
- return String(value || '')
31
- .replace(/[\u0000-\u001f\u007f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, '')
32
- .replace(/\s+/g, ' ')
33
- .trim()
34
- .slice(0, 48);
35
- }
36
-
37
- function sixDigits(randomInt) {
38
- return String(randomInt(0, 1_000_000)).padStart(6, '0');
39
- }
40
-
41
- /**
42
- * A pairing store over a plain-JSON state object, with clock and RNG injected so enrollment
43
- * is deterministic in tests. Persistence is the caller's job: load the JSON at start, call
44
- * toJSON() after a mutation, write it back — the same shape as pii's createVault/vaultToJSON.
45
- *
46
- * state: { paired: { [actorId]: { reach, at } }, pending: { [code]: { at, ttlMs } } }
47
- */
48
- export function createPairingStore(state = {}, {
49
- now = () => Date.now(),
50
- randomInt = (min, max) => min + Math.floor(Math.random() * (max - min)),
51
- } = {}) {
52
- const paired = new Map(Object.entries(state.paired || {}));
53
- const pending = new Map(Object.entries(state.pending || {}));
54
-
55
- const prune = () => {
56
- const t = now();
57
- for (const [code, p] of pending) if (t - p.at > (p.ttlMs || 0)) pending.delete(code);
58
- };
59
-
60
- return {
61
- /** Owner-side: mint a one-time code to read out to the phone. Shown in the extension/CLI. */
62
- requestCode({ ttlMs = 10 * 60_000 } = {}) {
63
- prune();
64
- let code;
65
- do { code = sixDigits(randomInt); } while (pending.has(code));
66
- pending.set(code, { at: now(), ttlMs });
67
- return code;
68
- },
69
- /** Phone-side: "/pair 123456". Burns the code and pairs the actor at 'trusted'.
70
- * `label` is whatever the platform calls the person (a Telegram first name or @handle) —
71
- * stored so the owner's screen can say WHICH phone it just enrolled. An opaque
72
- * 'telegram:789795542' is not something anyone can recognise, and the whole point of the
73
- * list is deciding whether to revoke one. Display only: authorization is by actorId. */
74
- redeem(actorId, code, { reach = 'trusted', label = '' } = {}) {
75
- prune();
76
- const c = String(code || '').trim();
77
- if (!pending.has(c)) return { ok: false, reason: 'unknown or expired code' };
78
- if (!REACH.includes(reach)) return { ok: false, reason: `unknown reach '${reach}'` };
79
- pending.delete(c);
80
- paired.set(actorId, { reach, at: now(), label: cleanLabel(label) });
81
- return { ok: true, reach };
82
- },
83
- /** Bootstrap without a code — for an operator-supplied allow list. Explicit, not silent. */
84
- allow(actorId, { reach = 'trusted', label = '' } = {}) {
85
- if (!REACH.includes(reach)) throw new Error(`unknown reach '${reach}'`);
86
- paired.set(actorId, { reach, at: now(), label: cleanLabel(label) });
87
- },
88
- revoke(actorId) { return paired.delete(actorId); },
89
- isPaired(actorId) { return paired.has(actorId); },
90
- /** The reach ceiling for this actor, or null when it isn't paired (→ refuse the message). */
91
- reachOf(actorId) { return paired.get(actorId)?.reach || null; },
92
- list() { return [...paired.entries()].map(([id, v]) => ({ actorId: id, ...v })); },
93
- toJSON() { return { paired: Object.fromEntries(paired), pending: Object.fromEntries(pending) }; },
94
- };
95
- }
1
+ import{REACH as a}from"../events/reach.js";function c(i){return String(i||"").replace(/[\u0000-\u001f\u007f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g,"").replace(/\s+/g," ").trim().slice(0,48)}function p(i){return String(i(0,1e6)).padStart(6,"0")}function b(i={},{now:u=()=>Date.now(),randomInt:d=(r,n)=>r+Math.floor(Math.random()*(n-r))}={}){const r=new Map(Object.entries(i.paired||{})),n=new Map(Object.entries(i.pending||{})),s=()=>{const e=u();for(const[t,o]of n)e-o.at>(o.ttlMs||0)&&n.delete(t)};return{requestCode({ttlMs:e=10*6e4}={}){s();let t;do t=p(d);while(n.has(t));return n.set(t,{at:u(),ttlMs:e}),t},redeem(e,t,{reach:o="trusted",label:f=""}={}){s();const l=String(t||"").trim();return n.has(l)?a.includes(o)?(n.delete(l),r.set(e,{reach:o,at:u(),label:c(f)}),{ok:!0,reach:o}):{ok:!1,reason:`unknown reach '${o}'`}:{ok:!1,reason:"unknown or expired code"}},allow(e,{reach:t="trusted",label:o=""}={}){if(!a.includes(t))throw new Error(`unknown reach '${t}'`);r.set(e,{reach:t,at:u(),label:c(o)})},revoke(e){return r.delete(e)},isPaired(e){return r.has(e)},reachOf(e){return r.get(e)?.reach||null},list(){return[...r.entries()].map(([e,t])=>({actorId:e,...t}))},toJSON(){return{paired:Object.fromEntries(r),pending:Object.fromEntries(n)}}}}export{a as REACH,b as createPairingStore};