@chatpanel/gateway 0.6.110 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +24 -4
  2. package/bin/chatpanel-gateway-bin.mjs +1 -24
  3. package/bin/chatpanel-gateway.js +3 -97
  4. package/package.json +1 -7
  5. package/src/access-log-store.js +1 -45
  6. package/src/agent.js +2 -256
  7. package/src/anthropic.js +3 -83
  8. package/src/backup-decrypt.js +1 -45
  9. package/src/backup-ingest.js +6 -120
  10. package/src/bridge-supervisor.js +3 -212
  11. package/src/bridge.js +4 -252
  12. package/src/budget.js +1 -117
  13. package/src/config.js +1 -209
  14. package/src/configstore.js +1 -181
  15. package/src/connect-agents.js +22 -179
  16. package/src/diarize-engine.js +1 -188
  17. package/src/egress.js +2 -0
  18. package/src/engine-ledger-store.js +1 -150
  19. package/src/engine.js +1 -132
  20. package/src/entitlement-refresh.js +1 -84
  21. package/src/entitlement.js +1 -76
  22. package/src/extraction.js +4 -294
  23. package/src/freegate.js +1 -47
  24. package/src/gate.js +1 -75
  25. package/src/gateway-token.js +1 -60
  26. package/src/history-store.js +1 -251
  27. package/src/job.js +3 -148
  28. package/src/knowledge.js +3 -215
  29. package/src/local-status.js +6 -102
  30. package/src/log.js +1 -21
  31. package/src/mcp-cli.js +19 -113
  32. package/src/mcp.js +34 -546
  33. package/src/memory-store.js +1 -176
  34. package/src/memory.js +2 -642
  35. package/src/model-integrity.js +1 -82
  36. package/src/model-ledger.js +1 -229
  37. package/src/model-runtime.js +1 -37
  38. package/src/models.js +1 -92
  39. package/src/ner-engine.js +1 -318
  40. package/src/ner.js +1 -113
  41. package/src/observability.js +1 -123
  42. package/src/openai.js +2 -84
  43. package/src/ort.js +1 -52
  44. package/src/parakeet-engine.js +2 -228
  45. package/src/pocket-tts-engine.js +1 -520
  46. package/src/prefs-store.js +1 -149
  47. package/src/project-store.js +1 -139
  48. package/src/project.js +1 -171
  49. package/src/recruit.js +3 -424
  50. package/src/recruiting.js +1 -93
  51. package/src/redact.js +2 -123
  52. package/src/responses.js +2 -80
  53. package/src/router.js +1 -292
  54. package/src/rrf.js +1 -93
  55. package/src/scorecard-store.js +1 -92
  56. package/src/scorecard.js +1 -336
  57. package/src/search-index.js +2 -134
  58. package/src/secure-fetch.js +1 -58
  59. package/src/sentencepiece.js +1 -184
  60. package/src/server.js +10 -2296
  61. package/src/service.js +11 -189
  62. package/src/shape.js +5 -121
  63. package/src/sqlite-store.js +3 -212
  64. package/src/stream.js +5 -182
  65. package/src/structured.js +4 -902
  66. package/src/stt-engine.js +1 -486
  67. package/src/stt-models.js +1 -144
  68. package/src/subject-kinds.js +1 -6
  69. package/src/subject-name.js +1 -97
  70. package/src/team-board.js +6 -338
  71. package/src/team-record.js +1 -226
  72. package/src/team-store.js +1 -261
  73. package/src/team.js +1 -303
  74. package/src/toolrelay.js +3 -122
  75. package/src/tts-engine.js +1 -453
  76. package/src/tts-models.js +1 -254
  77. package/src/tts-remote.js +1 -109
  78. package/src/tts-voice-resolve.js +1 -78
  79. package/src/tts-voices.js +1 -192
  80. package/src/update.js +1 -305
package/src/redact.js CHANGED
@@ -1,124 +1,3 @@
1
- // Gateway-level redaction: blind an arbitrary set of text segments into one
2
- // shared vault, so [[PERSON_1]] means the same entity across every message in a
3
- // request. Protocol adapters (openai.js / anthropic.js) extract the text, call
4
- // redactSegments, and splice the redacted strings back in.
5
- //
6
- // A fresh vault per request is correct here: coding agents resend the full
7
- // history each turn and the engine assigns tokens by first-appearance, so the
8
- // mapping is self-consistent within the request. (Same reasoning as the
9
- // extension's pii-pipeline.)
1
+ import{createVault as I,redactText as S,detectEntities as v,gatedDictionary as T,sanitizeUnicode as z}from"@chatpanel/pii";import{ENTITIES_SCHEMA as y,entitiesFormat as A}from"./extraction.js";import{describeSchema as N,coerce as j}from"./structured.js";import*as w from"./ner-engine.js";async function R(r,s,{signal:b,isPro:h=!0,onEgress:x=null,fetchImpl:E=null,nerEngine:u=w}={}){const i=I();let a=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const{clean:n,removed:g}=z(e);g&&(t.set(n),a+=g)}const l=r.map(t=>t.get()).filter(t=>typeof t=="string"&&t);if(l.length===0)return{vault:i,count:0,sanitized:a};const m=s.tier==="full"?"full":"basic",M=T(s,h),o=s.detection,p=!!(o&&o.backend&&o.backend!=="off"),c=!p&&u.isReady();let f=[];if(m==="full"&&(p||c)){const t=c?{backend:"endpoint",url:"inproc:ner",transport:"in-process",timeoutMs:3e4,maxChars:8e3,types:o?.types}:{...o,timeoutMs:Math.max(Number(o.timeoutMs)||0,3e4)},e=c?u.fetchAdapter:E||void 0;try{f=await v(l.join(`
10
2
 
11
- import { createVault, redactText, detectEntities, gatedDictionary, sanitizeUnicode } from '@chatpanel/pii';
12
- import { ENTITIES_SCHEMA, entitiesFormat } from './extraction.js';
13
- import { describeSchema, coerce } from './structured.js';
14
- import * as engine from './ner-engine.js';
15
-
16
- // tier: 'basic' | 'full'. For 'full' we run the local detector over the combined
17
- // text to harvest names/orgs, then redact every segment against that entity set.
18
- //
19
- // Free use is bounded by a request quota (freegate.js), not by downgrading
20
- // quality — free requests get the full tier (names/orgs via NER) within their
21
- // allowance. The custom dictionary is capped for free: gatedDictionary limits it
22
- // to FREE_DICT_LIMIT via the shared chatpanel-pii gate.
23
- export async function redactSegments(segments, redactionCfg, {
24
- signal, isPro = true, onEgress = null, fetchImpl: fetchOverride = null,
25
- // The bundled detector, INJECTED rather than reached for. An ES module namespace cannot
26
- // be monkey-patched, so with a hard import there is no way to ask "does an entity the
27
- // engine found actually come out the other side as a token" without downloading a model.
28
- // That question went unasked for exactly that reason, and the answer was no.
29
- nerEngine = engine,
30
- } = {}) {
31
- const vault = createVault();
32
-
33
- // De-steganography FIRST (before detection). Invisible/format Unicode is a triple
34
- // threat at this boundary: it can split a value so the detector misses it and the
35
- // model reassembles real PII (redaction bypass), smuggle a hidden instruction via
36
- // Tag chars (ASCII smuggling), or carry a fingerprint/watermark a client injected.
37
- // We strip it in place so detection sees clean text and the forwarded request is
38
- // clean too. Counted (not silently dropped) so the server can report it.
39
- let sanitized = 0;
40
- for (const seg of segments) {
41
- const before = seg.get();
42
- if (typeof before !== 'string' || !before) continue;
43
- const { clean, removed } = sanitizeUnicode(before);
44
- if (removed) { seg.set(clean); sanitized += removed; }
45
- }
46
-
47
- const texts = segments.map((s) => s.get()).filter((t) => typeof t === 'string' && t);
48
- if (texts.length === 0) return { vault, count: 0, sanitized };
49
-
50
- // Use the configured tier as-is (no free downgrade — the quota bounds free use),
51
- // but keep the dictionary capped for free via the shared chatpanel-pii gate.
52
- const tier = redactionCfg.tier === 'full' ? 'full' : 'basic';
53
- const dictionary = gatedDictionary(redactionCfg, isPro);
54
-
55
- // Detection source: a USER-configured external detector takes precedence; else
56
- // the bundled in-process engine (no second port — we hand pii-detect a fetchImpl
57
- // that runs the model in-process instead of doing real HTTP). Either way we reuse
58
- // @chatpanel/pii's caching / timeout / type-gating — one source of truth.
59
- const det = redactionCfg.detection;
60
- const useExternal = !!(det && det.backend && det.backend !== 'off');
61
- const useEngine = !useExternal && nerEngine.isReady();
62
-
63
- let entities = [];
64
- if (tier === 'full' && (useExternal || useEngine)) {
65
- // One detection pass over the joined text — cached + fail-open, so a slow/broken
66
- // detector never blocks the request (the deterministic layer still runs). Give it
67
- // a generous CEILING (matching the extension): a fast detector returns in well
68
- // under a second, but a cold one must be allowed to finish; on timeout the turn
69
- // falls back to dictionary/deterministic-only redaction.
70
- const detection = useEngine
71
- // `transport: 'in-process'` is load-bearing, not decoration. Without it the sentinel
72
- // URL below fails @chatpanel/pii's SSRF scheme check, the throw is swallowed by the
73
- // fail-open path, and the bundled engine contributes NOTHING to any redaction while
74
- // reporting itself ready — names and organisations reach the model in full under a
75
- // config that says "full". The flag is only honoured alongside an injected fetch,
76
- // which is `engine.fetchAdapter` on the next line.
77
- ? { backend: 'endpoint', url: 'inproc:ner', transport: 'in-process', timeoutMs: 30000, maxChars: 8000, types: det?.types }
78
- : { ...det, timeoutMs: Math.max(Number(det.timeoutMs) || 0, 30000) };
79
- // The in-process engine is already injected this way; `fetchOverride` is the same seam
80
- // for a test, so the detector hop can be exercised without a network. Never used in
81
- // production — nothing passes it but tests.
82
- const fetchImpl = useEngine ? nerEngine.fetchAdapter : (fetchOverride || undefined);
83
- try {
84
- entities = await detectEntities(texts.join('\n\n'), { detection }, {
85
- signal,
86
- fetchImpl,
87
- // The one call that sends RAW, pre-redaction text somewhere. In-process NER never
88
- // leaves the machine (`inproc:ner`), but a configured detector URL can be any public
89
- // host — so the FACT of it is recorded, never the text. See @chatpanel/pii.
90
- onEgress: useEngine ? null : onEgress,
91
- // @chatpanel/pii ships zero dependencies, so the structured-output layer is handed IN.
92
- // What it buys: the detector asks an OpenAI-compatible server to ENFORCE the shape
93
- // (json_schema, then json_object, then nothing), and reads the reply with the
94
- // schema-aligned coercer instead of a slice between the first '{' and the last '}'.
95
- // A locally-served small model is exactly the case that needed it.
96
- structured: {
97
- block: describeSchema(ENTITIES_SCHEMA),
98
- format: (mode) => entitiesFormat(mode),
99
- parse: (text) => coerce(text, ENTITIES_SCHEMA)?.value ?? null,
100
- },
101
- });
102
- } catch {
103
- entities = [];
104
- }
105
- }
106
-
107
- const opts = { tier, entities, dictionary };
108
-
109
- let count = 0;
110
- for (const seg of segments) {
111
- const before = seg.get();
112
- if (typeof before !== 'string' || !before) continue;
113
- const after = redactText(before, vault, opts);
114
- if (after !== before) count++;
115
- seg.set(after);
116
- }
117
- return { vault, count, sanitized };
118
- }
119
-
120
- // A `segment` is a tiny getter/setter over wherever the text lives in the parsed
121
- // request body, so we can redact in place without rebuilding the structure.
122
- export function segment(getter, setter) {
123
- return { get: getter, set: setter };
124
- }
3
+ `),{detection:t},{signal:b,fetchImpl:e,onEgress:c?null:x,structured:{block:N(y),format:n=>A(n),parse:n=>j(n,y)?.value??null}})}catch{f=[]}}const k={tier:m,entities:f,dictionary:M};let d=0;for(const t of r){const e=t.get();if(typeof e!="string"||!e)continue;const n=S(e,i,k);n!==e&&d++,t.set(n)}return{vault:i,count:d,sanitized:a}}function U(r,s){return{get:r,set:s}}export{R as redactSegments,U as segment};
package/src/responses.js CHANGED
@@ -1,81 +1,3 @@
1
- // OpenAI Responses API adapter: /v1/responses (what the Codex CLI and newer
2
- // OpenAI SDKs use — a different body shape from chat/completions). Without this,
3
- // Codex traffic would pass through un-redacted. Forwarded to the OpenAI upstream.
1
+ import{segment as s}from"./redact.js";import{restoreDeep as u}from"./stream.js";function f(t){return/\/responses$/.test(t)}function c(t,r){return!r||!t||(t.instructions=t.instructions?`${t.instructions}
4
2
 
5
- import { segment } from './redact.js';
6
- import { restoreDeep } from './stream.js';
7
-
8
- export function matches(pathname) {
9
- return /\/responses$/.test(pathname);
10
- }
11
-
12
- // Append a (non-redacted) instruction to the Responses-API instructions field.
13
- export function injectSystemNote(body, note) {
14
- if (!note || !body) return body;
15
- body.instructions = body.instructions ? `${body.instructions}\n\n${note}` : note;
16
- return body;
17
- }
18
-
19
- // Redactable text in a Responses request lives in `instructions` (system) and
20
- // `input` (a string, or an array of items whose content parts carry text).
21
- function collectInputItem(item, segs) {
22
- if (!item || typeof item !== 'object') return;
23
- if (typeof item.content === 'string') {
24
- segs.push(segment(() => item.content, (v) => { item.content = v; }));
25
- } else if (Array.isArray(item.content)) {
26
- for (const part of item.content) {
27
- if (part && typeof part.text === 'string' && /text$/.test(part.type || 'text')) {
28
- segs.push(segment(() => part.text, (v) => { part.text = v; }));
29
- }
30
- }
31
- }
32
- // function_call_output items carry a plain `output` string.
33
- if (typeof item.output === 'string') {
34
- segs.push(segment(() => item.output, (v) => { item.output = v; }));
35
- }
36
- }
37
-
38
- export function collectSegments(body, redactionCfg) {
39
- const segs = [];
40
- if (redactionCfg.redactSystem !== false && typeof body?.instructions === 'string') {
41
- segs.push(segment(() => body.instructions, (v) => { body.instructions = v; }));
42
- }
43
- if (typeof body?.input === 'string') {
44
- segs.push(segment(() => body.input, (v) => { body.input = v; }));
45
- } else if (Array.isArray(body?.input)) {
46
- for (const item of body.input) collectInputItem(item, segs);
47
- }
48
- return segs;
49
- }
50
-
51
- // Extract the conversation for the bridge backend. Responses carries the system
52
- // prompt as `instructions` and the turn as `input` (string or item array).
53
- export function toTurn(body) {
54
- const system = typeof body?.instructions === 'string' ? body.instructions : '';
55
- let messages = [];
56
- if (typeof body?.input === 'string') {
57
- messages = [{ role: 'user', content: body.input }];
58
- } else if (Array.isArray(body?.input)) {
59
- messages = body.input.map((it) => ({
60
- role: it?.role || 'user',
61
- content: it?.content != null ? it.content : (typeof it?.output === 'string' ? it.output : ''),
62
- }));
63
- }
64
- return { messages, system };
65
- }
66
-
67
- // Restore a buffered response: output[].content[].text, function_call args, and
68
- // the `output_text` convenience field some SDKs add.
69
- export function restoreResponse(json, vault) {
70
- if (typeof json?.output_text === 'string') json.output_text = restoreDeep(json.output_text, vault);
71
- for (const item of json?.output || []) {
72
- if (!item) continue;
73
- if (Array.isArray(item.content)) {
74
- for (const part of item.content) {
75
- if (part && typeof part.text === 'string') part.text = restoreDeep(part.text, vault);
76
- }
77
- }
78
- if (typeof item.arguments === 'string') item.arguments = restoreDeep(item.arguments, vault);
79
- }
80
- return json;
81
- }
3
+ ${r}`:r),t}function o(t,r){if(!(!t||typeof t!="object")){if(typeof t.content=="string")r.push(s(()=>t.content,n=>{t.content=n}));else if(Array.isArray(t.content))for(const n of t.content)n&&typeof n.text=="string"&&/text$/.test(n.type||"text")&&r.push(s(()=>n.text,e=>{n.text=e}));typeof t.output=="string"&&r.push(s(()=>t.output,n=>{t.output=n}))}}function a(t,r){const n=[];if(r.redactSystem!==!1&&typeof t?.instructions=="string"&&n.push(s(()=>t.instructions,e=>{t.instructions=e})),typeof t?.input=="string")n.push(s(()=>t.input,e=>{t.input=e}));else if(Array.isArray(t?.input))for(const e of t.input)o(e,n);return n}function g(t){const r=typeof t?.instructions=="string"?t.instructions:"";let n=[];return typeof t?.input=="string"?n=[{role:"user",content:t.input}]:Array.isArray(t?.input)&&(n=t.input.map(e=>({role:e?.role||"user",content:e?.content!=null?e.content:typeof e?.output=="string"?e.output:""}))),{messages:n,system:r}}function x(t,r){typeof t?.output_text=="string"&&(t.output_text=u(t.output_text,r));for(const n of t?.output||[])if(n){if(Array.isArray(n.content))for(const e of n.content)e&&typeof e.text=="string"&&(e.text=u(e.text,r));typeof n.arguments=="string"&&(n.arguments=u(n.arguments,r))}return t}export{a as collectSegments,c as injectSystemNote,f as matches,x as restoreResponse,g as toTurn};
package/src/router.js CHANGED
@@ -1,292 +1 @@
1
- // Model router: the gateway exposes one localhost endpoint, and routes each
2
- // request to a DESTINATION by the model name the client asks for. A destination
3
- // is either a CLI agent (driven via the bridge, subscription login) or an API
4
- // (forwarded to a provider/local server, client brings the key).
5
- //
6
- // destination = {
7
- // id, unique name (also a valid model alias)
8
- // type: 'agent' | 'api',
9
- // agent, (agent) bridge agent id: codex/claude/opencode/pi
10
- // baseUrl, protocol, (api) where to forward + 'openai'|'anthropic'
11
- // models: [..], models this destination serves (for /v1/models)
12
- // }
13
-
14
- import { secureFetch } from './secure-fetch.js';
15
- import { readBridgeToken, resolveBridgeUrl } from './bridge.js';
16
- //
17
- // /v1/models aggregates every destination's models so clients can discover them.
18
-
19
- // The CLI agents the bridge can drive. A request for any of these ALWAYS routes to
20
- // the bridge relay — the agent runs under ITS OWN login (subscription / enterprise /
21
- // api, however it's configured), so the gateway never needs an API key for it. This
22
- // is the whole point: an OpenAI/Anthropic endpoint fronting already-logged-in
23
- // codex / claude code via the bridge.
24
- const KNOWN_AGENTS = ['codex', 'claude', 'opencode', 'pi', 'kiro', 'antigravity'];
25
-
26
- // Build the destination list: explicitly-configured destinations + the known agents
27
- // (always available as bridge destinations, even with zero saved config) + API
28
- // fallbacks for non-agent models on the api backend.
29
- export function listDestinations(cfg) {
30
- const configured = (Array.isArray(cfg.destinations) ? cfg.destinations : []).filter(Boolean);
31
- const haveId = new Set(configured.map((d) => d.id));
32
- // AGENTS FIRST. The model list de-duplicates by id in this order, and resolveDestination
33
- // takes the first destination that serves a model — so an API destination that happened to
34
- // list "codex" or "claude" (a gateway pointed at itself did exactly that) used to swallow
35
- // the agents: they vanished from the picker and a turn for one was proxied to the loop.
36
- const out = [
37
- ...configured.filter((d) => d.type === 'agent'),
38
- ...KNOWN_AGENTS.filter((a) => !haveId.has(a)).map((a) => ({ id: a, type: 'agent', agent: a, models: [a] })),
39
- ...configured.filter((d) => d.type !== 'agent'),
40
- ];
41
- if (cfg.backend === 'api' && !configured.some((d) => d.type === 'api')) {
42
- out.push({ id: 'openai', type: 'api', protocol: 'openai', baseUrl: cfg.upstreams?.openai?.baseUrl, models: [] });
43
- out.push({ id: 'anthropic', type: 'api', protocol: 'anthropic', baseUrl: cfg.upstreams?.anthropic?.baseUrl, models: [] });
44
- }
45
- return out;
46
- }
47
-
48
- // Pick the destination that serves `model` (explicit membership → id/agent match →
49
- // a same-protocol fallback → the first destination).
50
- export function resolveDestination(model, cfg, kind, { destination = '' } = {}) {
51
- const dests = listDestinations(cfg);
52
- const wantsAnthropic = kind === 'anthropic';
53
- const protoOk = (d) => (wantsAnthropic ? d.protocol === 'anthropic' : d.protocol !== 'anthropic');
54
- // An explicit destination wins outright and never falls through: the caller named the
55
- // provider it means, so guessing a different one would be worse than failing. The caller
56
- // checks that what came back is what it asked for.
57
- if (destination) return dests.find((d) => d.id === destination) || null;
58
- return (
59
- // Explicit: a destination that serves this exact model (a known agent like codex
60
- // matches its own agent destination here — so it ALWAYS goes to the bridge).
61
- (model && dests.find((d) => Array.isArray(d.models) && d.models.includes(model)))
62
- || (model && dests.find((d) => d.id === model || d.agent === model))
63
- // `claude/opus` names an agent AND the model it should run: the agent's own destination,
64
- // never the backend default — which is codex, and "Codex exited 1" on a model it has no
65
- // idea about was how a whole team came back empty.
66
- || (model && model.includes('/') && dests.find((d) => d.type === 'agent' && (d.agent === model.slice(0, model.indexOf('/')) || d.id === model.slice(0, model.indexOf('/')))))
67
- // No match: fall back to the BACKEND's natural default — an API destination on the
68
- // api backend, an agent on the bridge backend. Never silently send an unknown
69
- // model name to a CLI agent (that's why gemma must not hit codex).
70
- || dests.find((d) => (cfg.backend === 'bridge' ? d.type === 'agent' : (d.type === 'api' && protoOk(d))))
71
- || dests.find((d) => (cfg.backend === 'bridge' ? d.type === 'agent' : d.type === 'api'))
72
- || dests[0]
73
- || null
74
- );
75
- }
76
-
77
- // Aggregate every destination's models for GET /v1/models. Agents expose their
78
- // own name as the model; APIs expose ONLY real model ids (never the destination
79
- // id — that's a provider name, not a model).
80
- /**
81
- * WHICH API SHAPE A MODEL WANTS TO BE CALLED WITH.
82
- *
83
- * `owned_by` names the destination, which is a routing fact, not a calling convention — and
84
- * a client needs the second one to build a request. Anthropic models take the Messages API;
85
- * OpenAI-compatible ones take chat/completions (and the Responses API where the destination
86
- * offers it); an agent takes neither, because the gateway synthesises the response itself
87
- * from the bridge's stream.
88
- *
89
- * Stated here rather than inferred from the id in every client. Guessing from the name is
90
- * how `claude` the local CLI agent gets called as if it were Anthropic's hosted API.
91
- */
92
- function apiShapeOf(d) {
93
- if (d.type === 'agent') return { api: 'agent', endpoints: ['/v1/chat/completions'] };
94
- if (d.protocol === 'anthropic') return { api: 'anthropic', endpoints: ['/v1/messages'] };
95
- return { api: 'openai', endpoints: ['/v1/chat/completions', '/v1/responses'] };
96
- }
97
-
98
- /**
99
- * CAN THIS DESTINATION ANSWER AT ALL — before anyone sends a turn to it.
100
- *
101
- * This list is a ROUTING TABLE. It names every model the gateway would forward to, and a
102
- * provider that lists four hundred can be configured with no key at all — so the list is
103
- * mostly names that cannot answer. A user picks one, and finds out at 08:00 when a scheduled
104
- * job comes back `Missing Authentication header` or `upstream fetch failed`, quoting undici
105
- * about a destination they never knowingly chose.
106
- *
107
- * Local endpoints are the exception that must NOT be marked unconfigured: llama.cpp, Ollama
108
- * and LM Studio take no key, and greying them out would hide the one setup that needs
109
- * nothing. So this asks only the question it can answer honestly — "is a credential
110
- * required here, and is one saved" — and says nothing about whether the server is up.
111
- *
112
- * Returns `''` when there is nothing to report.
113
- */
114
- const LOCAL_HOST = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;
115
- function unconfiguredReason(d) {
116
- if (!d || d.type === 'agent') return '';
117
- const base = String(d.baseUrl || '');
118
- if (!base) return 'no endpoint URL is set for this provider';
119
- if (LOCAL_HOST.test(base)) return ''; // a local server needs no key
120
- if (d.apiKey || d.hasKey) return '';
121
- return `no API key is saved for ${d.id}`;
122
- }
123
-
124
- export function aggregateModels(cfg) {
125
- const data = [];
126
- const seen = new Set();
127
- const add = (id, owner, d) => {
128
- if (!id || seen.has(id)) return;
129
- seen.add(id);
130
- const shape = apiShapeOf(d);
131
- const blocked = unconfiguredReason(d);
132
- data.push({
133
- id,
134
- object: 'model',
135
- owned_by: owner,
136
- // `configured` is about SETUP, not liveness: false means a turn sent here is known to
137
- // fail for a reason the user can fix in Settings. Absent liveness is deliberate — the
138
- // gateway does not probe every provider to draw a list.
139
- ...(blocked ? { configured: false, reason: blocked } : {}),
140
- // Additive fields an OpenAI client ignores and a ChatPanel client uses to decide how
141
- // to call, and to group a picker by provider instead of by a flat list of ids.
142
- provider: d.id,
143
- provider_type: d.type === 'agent' ? 'agent' : (d.protocol === 'anthropic' ? 'anthropic' : 'openai'),
144
- api: shape.api,
145
- endpoints: shape.endpoints,
146
- });
147
- };
148
- for (const d of listDestinations(cfg)) {
149
- if (d.type === 'agent') for (const m of (d.models?.length ? d.models : [d.id])) add(m, 'chatpanel-bridge', d);
150
- else for (const m of (d.models || [])) add(m, d.id, d);
151
- }
152
- return { object: 'list', data };
153
- }
154
-
155
- /**
156
- * The models each installed agent can be asked for.
157
- *
158
- * A CLI agent is not one model — Claude Code takes opus/sonnet/haiku, others enumerate their
159
- * own — and listing only the agent id meant a user picked `claude` and got whatever default
160
- * the CLI had. When that default is newer than the installed CLI, the answer is a version
161
- * error about a model the user never chose.
162
- *
163
- * Asked of the bridge, which is the only thing that knows what each CLI supports, and only
164
- * for agents that are actually INSTALLED: enumerating models for a CLI that is not there
165
- * spends a subprocess per agent to describe something unusable.
166
- */
167
- async function bridgeAgentModels(cfg, installed, timeoutMs) {
168
- const base = await resolveBridgeUrl(cfg);
169
- if (!base || !installed) return new Map();
170
- const token = readBridgeToken(cfg.bridge?.token);
171
- const ids = [...installed.entries()].filter(([, ok]) => ok).map(([id]) => id);
172
- const out = new Map();
173
- await Promise.all(ids.map(async (id) => {
174
- try {
175
- const res = await fetch(`${base}/list-models`, {
176
- method: 'POST',
177
- headers: { 'content-type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
178
- body: JSON.stringify({ agent: id }),
179
- signal: AbortSignal.timeout(timeoutMs),
180
- });
181
- if (!res.ok) return;
182
- const body = await res.json();
183
- const models = (Array.isArray(body?.models) ? body.models : [])
184
- .map((m) => (typeof m === 'string' ? m : m?.id || m?.name || ''))
185
- .map((m) => String(m).trim())
186
- .filter(Boolean);
187
- if (models.length) out.set(id, models.slice(0, 40));
188
- } catch { /* an agent that will not enumerate still works under its bare id */ }
189
- }));
190
- return out;
191
- }
192
-
193
- /** id → installed, from the bridge's own /health. `null` when it could not be asked. */
194
- async function bridgeAgentAvailability(cfg, timeoutMs) {
195
- const base = await resolveBridgeUrl(cfg);
196
- if (!base) return null;
197
- try {
198
- const token = readBridgeToken(cfg.bridge?.token);
199
- const res = await fetch(`${base}/health`, {
200
- headers: { Accept: 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
201
- signal: AbortSignal.timeout(timeoutMs),
202
- });
203
- if (!res.ok) return null;
204
- const body = await res.json();
205
- if (!Array.isArray(body?.agents)) return null;
206
- return new Map(body.agents.map((a) => [a.id, !!a.available]));
207
- } catch {
208
- return null; // not reachable — say nothing rather than saying "none"
209
- }
210
- }
211
-
212
- // Async variant: also PROXIES each API destination's own /v1/models to discover
213
- // real model ids (using its saved key). Fail-open per destination.
214
- export async function aggregateModelsAsync(cfg, { timeoutMs = 4000 } = {}) {
215
- const base = aggregateModels(cfg);
216
- const seen = new Set(base.data.map((m) => m.id));
217
-
218
- // WHICH AGENTS ARE ACTUALLY ON THIS MACHINE.
219
- //
220
- // The list above is the ROUTING TABLE: it names every agent the gateway would route to,
221
- // whether or not that CLI is installed. On a fresh machine that is a model picker full of
222
- // names that all fail on first use, which is the worst possible first five minutes.
223
- //
224
- // Only the bridge knows what is on disk, so the gateway asks it — once, here — rather than
225
- // every client asking separately. A client that had to check for itself would need the
226
- // bridge's address and token as well as ours, and the direct-to-bridge path is the one
227
- // with no policy in front of it; making it necessary is how it becomes the habit.
228
- //
229
- // `available` is left UNDEFINED when the bridge cannot be reached. Absent means "we did not
230
- // find out", which is not the same as false, and a picker that greys out every agent
231
- // because one health check timed out is worse than one that says nothing.
232
- const agentAvailability = await bridgeAgentAvailability(cfg, timeoutMs);
233
- if (agentAvailability) {
234
- for (const m of base.data) {
235
- if (m.owned_by === 'chatpanel-bridge') m.available = agentAvailability.get(m.id) ?? false;
236
- }
237
- }
238
-
239
- // Each installed agent's own models, listed as `agent/model` beside the bare id. The bare
240
- // id stays and still means "the agent's default", so nothing that already works breaks.
241
- const agentModels = await bridgeAgentModels(cfg, agentAvailability, timeoutMs);
242
- for (const [agent, models] of agentModels) {
243
- const parent = base.data.find((m) => m.id === agent);
244
- if (!parent) continue;
245
- for (const model of models) {
246
- const id = `${agent}/${model}`;
247
- if (seen.has(id)) continue;
248
- seen.add(id);
249
- base.data.push({
250
- ...parent,
251
- id,
252
- // `model` is what the picker shows under the agent's heading; the agent stays the
253
- // provider, so the grouping puts them together without any id parsing.
254
- model,
255
- available: true,
256
- });
257
- }
258
- }
259
-
260
- const dests = listDestinations(cfg).filter((d) => d.type === 'api' && d.baseUrl);
261
- await Promise.all(dests.map(async (d) => {
262
- const ctrl = new AbortController();
263
- const t = setTimeout(() => ctrl.abort(), timeoutMs);
264
- try {
265
- const headers = { 'content-type': 'application/json' };
266
- if (d.apiKey) {
267
- if (d.protocol === 'anthropic') { headers['x-api-key'] = d.apiKey; headers['anthropic-version'] = '2023-06-01'; }
268
- else headers.authorization = `Bearer ${d.apiKey}`;
269
- }
270
- // secureFetch: SSRF guard (scheme/host + resolved-IP); a blocked dest throws → skipped via the catch.
271
- const res = await secureFetch(`${d.baseUrl.replace(/\/$/, '')}/models`, { headers, signal: ctrl.signal });
272
- if (!res.ok) return;
273
- const j = await res.json();
274
- const list = Array.isArray(j?.data) ? j.data : (Array.isArray(j?.models) ? j.models : []);
275
- for (const m of list) {
276
- const id = typeof m === 'string' ? m : m?.id;
277
- if (id && !seen.has(id)) {
278
- seen.add(id);
279
- const shape = apiShapeOf(d);
280
- const blocked = unconfiguredReason(d);
281
- base.data.push({
282
- id, object: 'model', owned_by: d.id, provider: d.id,
283
- provider_type: d.protocol === 'anthropic' ? 'anthropic' : 'openai',
284
- api: shape.api, endpoints: shape.endpoints,
285
- ...(blocked ? { configured: false, reason: blocked } : {}),
286
- });
287
- }
288
- }
289
- } catch { /* fail-open */ } finally { clearTimeout(t); }
290
- }));
291
- return base;
292
- }
1
+ import{secureFetch as S}from"./secure-fetch.js";import{readBridgeToken as m,resolveBridgeUrl as A}from"./bridge.js";const $=["codex","claude","opencode","pi","kiro","antigravity"];function h(n){const o=(Array.isArray(n.destinations)?n.destinations:[]).filter(Boolean),i=new Set(o.map(e=>e.id)),a=[...o.filter(e=>e.type==="agent"),...$.filter(e=>!i.has(e)).map(e=>({id:e,type:"agent",agent:e,models:[e]})),...o.filter(e=>e.type!=="agent")];return n.backend==="api"&&!o.some(e=>e.type==="api")&&(a.push({id:"openai",type:"api",protocol:"openai",baseUrl:n.upstreams?.openai?.baseUrl,models:[]}),a.push({id:"anthropic",type:"api",protocol:"anthropic",baseUrl:n.upstreams?.anthropic?.baseUrl,models:[]})),a}function K(n,o,i,{destination:a=""}={}){const e=h(o),s=i==="anthropic",r=t=>s?t.protocol==="anthropic":t.protocol!=="anthropic";return a?e.find(t=>t.id===a)||null:n&&e.find(t=>Array.isArray(t.models)&&t.models.includes(n))||n&&e.find(t=>t.id===n||t.agent===n)||n&&n.includes("/")&&e.find(t=>t.type==="agent"&&(t.agent===n.slice(0,n.indexOf("/"))||t.id===n.slice(0,n.indexOf("/"))))||e.find(t=>o.backend==="bridge"?t.type==="agent":t.type==="api"&&r(t))||e.find(t=>o.backend==="bridge"?t.type==="agent":t.type==="api")||e[0]||null}function w(n){return n.type==="agent"?{api:"agent",endpoints:["/v1/chat/completions"]}:n.protocol==="anthropic"?{api:"anthropic",endpoints:["/v1/messages"]}:{api:"openai",endpoints:["/v1/chat/completions","/v1/responses"]}}const j=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0|[^/]*\.local)(:|\/|$)/i;function v(n){if(!n||n.type==="agent")return"";const o=String(n.baseUrl||"");return o?j.test(o)||n.apiKey||n.hasKey?"":`no API key is saved for ${n.id}`:"no endpoint URL is set for this provider"}function O(n){const o=[],i=new Set,a=(e,s,r)=>{if(!e||i.has(e))return;i.add(e);const t=w(r),l=v(r);o.push({id:e,object:"model",owned_by:s,...l?{configured:!1,reason:l}:{},provider:r.id,provider_type:r.type==="agent"?"agent":r.protocol==="anthropic"?"anthropic":"openai",api:t.api,endpoints:t.endpoints})};for(const e of h(n))if(e.type==="agent")for(const s of e.models?.length?e.models:[e.id])a(s,"chatpanel-bridge",e);else for(const s of e.models||[])a(s,e.id,e);return{object:"list",data:o}}async function U(n,o,i){const a=await A(n);if(!a||!o)return new Map;const e=m(n.bridge?.token),s=[...o.entries()].filter(([,t])=>t).map(([t])=>t),r=new Map;return await Promise.all(s.map(async t=>{try{const l=await fetch(`${a}/list-models`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify({agent:t}),signal:AbortSignal.timeout(i)});if(!l.ok)return;const d=await l.json(),c=(Array.isArray(d?.models)?d.models:[]).map(p=>typeof p=="string"?p:p?.id||p?.name||"").map(p=>String(p).trim()).filter(Boolean);c.length&&r.set(t,c.slice(0,40))}catch{}})),r}async function x(n,o){const i=await A(n);if(!i)return null;try{const a=m(n.bridge?.token),e=await fetch(`${i}/health`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(o)});if(!e.ok)return null;const s=await e.json();return Array.isArray(s?.agents)?new Map(s.agents.map(r=>[r.id,!!r.available])):null}catch{return null}}async function T(n,{timeoutMs:o=4e3}={}){const i=O(n),a=new Set(i.data.map(t=>t.id)),e=await x(n,o);if(e)for(const t of i.data)t.owned_by==="chatpanel-bridge"&&(t.available=e.get(t.id)??!1);const s=await U(n,e,o);for(const[t,l]of s){const d=i.data.find(c=>c.id===t);if(d)for(const c of l){const p=`${t}/${c}`;a.has(p)||(a.add(p),i.data.push({...d,id:p,model:c,available:!0}))}}const r=h(n).filter(t=>t.type==="api"&&t.baseUrl);return await Promise.all(r.map(async t=>{const l=new AbortController,d=setTimeout(()=>l.abort(),o);try{const c={"content-type":"application/json"};t.apiKey&&(t.protocol==="anthropic"?(c["x-api-key"]=t.apiKey,c["anthropic-version"]="2023-06-01"):c.authorization=`Bearer ${t.apiKey}`);const p=await S(`${t.baseUrl.replace(/\/$/,"")}/models`,{headers:c,signal:l.signal});if(!p.ok)return;const f=await p.json(),k=Array.isArray(f?.data)?f.data:Array.isArray(f?.models)?f.models:[];for(const y of k){const u=typeof y=="string"?y:y?.id;if(u&&!a.has(u)){a.add(u);const g=w(t),b=v(t);i.data.push({id:u,object:"model",owned_by:t.id,provider:t.id,provider_type:t.protocol==="anthropic"?"anthropic":"openai",api:g.api,endpoints:g.endpoints,...b?{configured:!1,reason:b}:{}})}}}catch{}finally{clearTimeout(d)}})),i}export{O as aggregateModels,T as aggregateModelsAsync,h as listDestinations,K as resolveDestination};
package/src/rrf.js CHANGED
@@ -1,93 +1 @@
1
- // VENDORED from @chatpanel/events/rrf.js — edit there, then copy over.
2
- // Same pattern as observability.js: one pure module copied in rather than pulling the whole
3
- // events package. Source of truth: chatpanel-events/rrf.js.
4
- //
5
- // rrf.js — Reciprocal Rank Fusion, and the query planning that feeds it.
6
- //
7
- // One question rarely makes one good keyword query. "What was the outcome of the Ben tooling
8
- // demo?" and "Ben demo decisions action items" retrieve different things, and the answer is
9
- // usually in the union. RRF merges several ranked lists without needing their scores to be
10
- // comparable — each list contributes 1/(k+rank) — which is exactly the situation here: BM25
11
- // scores, vector distances and a hot/warm split are all on different scales.
12
- //
13
- // Pure and dependency-free, so the identical fusion runs in the extension (hot+warm), the
14
- // gateway (multi-query search) and any future client. The extension had this privately; it
15
- // lives here now so the gateway doesn't grow a second, subtly different copy.
16
-
17
- /**
18
- * Fuse ranked id lists. `lists` is an array of arrays of ids, each already in rank order.
19
- * k dampens the head of each list (60 is the standard default). limit 0 = everything.
20
- */
21
- export function fuseRRF(lists, { k = 60, limit = 0 } = {}) {
22
- const score = new Map();
23
- for (const list of lists || []) {
24
- if (!Array.isArray(list)) continue;
25
- list.forEach((id, rank) => {
26
- if (id == null) return;
27
- score.set(id, (score.get(id) || 0) + 1 / (k + rank));
28
- });
29
- }
30
- const out = [...score.entries()].map(([id, s]) => ({ id, score: s })).sort((a, b) => b.score - a.score);
31
- return limit > 0 ? out.slice(0, limit) : out;
32
- }
33
-
34
- // Words that carry no retrieval signal but do dilute BM25 — dropped to build a keyword-only
35
- // variant of a natural-language question.
36
- const STOP = new Set(('a an and are as at be been but by can could did do does for from had has have how i if in into is it its me my of on or our ought shall should '
37
- + 'so than that the their them then there these they this those to um was we were what when where which who whom why will with would you your about tell show give find get '
38
- + 'please could-you was-there did-we').split(/\s+/));
39
-
40
- /**
41
- * Turn one natural-language question into a small set of complementary queries — the cheap,
42
- * deterministic half of query expansion. No model call, so it costs nothing and cannot fail.
43
- *
44
- * A CALLING AGENT can do better (it understands the domain), which is why the tools accept an
45
- * explicit `queries` list; these variants are the floor, not the ceiling.
46
- */
47
- export function planQueries(question, { extra = [], max = 4 } = {}) {
48
- const q = String(question || '').trim();
49
- const out = [];
50
- const seen = new Set();
51
- const add = (s) => {
52
- const t = String(s || '').trim().replace(/\s+/g, ' ');
53
- const key = t.toLowerCase();
54
- if (t && !seen.has(key)) { seen.add(key); out.push(t); }
55
- };
56
-
57
- add(q); // the question as asked
58
- for (const e of extra) add(e); // whatever the agent proposed — it knows more
59
-
60
- const words = q.toLowerCase().match(/[a-z0-9][a-z0-9'’_+-]*/g) || [];
61
- const keywords = words.filter((w) => !STOP.has(w) && w.length > 2);
62
- if (keywords.length >= 2) add(keywords.join(' ')); // keyword-only: BM25's best shape
63
- // The rarest-looking terms (longest words are a decent proxy for specificity) — helps when
64
- // the full question is too broad to rank anything well.
65
- if (keywords.length > 3) add([...keywords].sort((a, b) => b.length - a.length).slice(0, 3).join(' '));
66
-
67
- return out.slice(0, Math.max(1, max));
68
- }
69
-
70
- /**
71
- * Run several queries through one `search(query, opts)` function and fuse the results by id.
72
- * `search` returns arrays of { id, ... }; the fused output keeps the richest record seen for
73
- * each id (so snippets survive) and reports which queries found it — the "why is this here"
74
- * a reader needs when a multi-query search surfaces something unexpected.
75
- */
76
- export async function multiSearch(queries, search, { limit = 10, k = 60 } = {}) {
77
- const lists = [];
78
- const byId = new Map();
79
- const foundBy = new Map();
80
- for (const q of queries || []) {
81
- let rows = [];
82
- try { rows = (await search(q)) || []; } catch { rows = []; } // one bad query must not sink the rest
83
- lists.push(rows.map((r) => r.id));
84
- for (const r of rows) {
85
- if (!byId.has(r.id) || (!byId.get(r.id).snippet && r.snippet)) byId.set(r.id, r);
86
- if (!foundBy.has(r.id)) foundBy.set(r.id, []);
87
- foundBy.get(r.id).push(q);
88
- }
89
- }
90
- return fuseRRF(lists, { k, limit }).map(({ id, score }) => ({
91
- ...byId.get(id), id, score, foundBy: foundBy.get(id) || [],
92
- }));
93
- }
1
+ function l(h,{k:c=60,limit:a=0}={}){const r=new Map;for(const o of h||[])Array.isArray(o)&&o.forEach((e,n)=>{e!=null&&r.set(e,(r.get(e)||0)+1/(c+n))});const i=[...r.entries()].map(([o,e])=>({id:o,score:e})).sort((o,e)=>e.score-o.score);return a>0?i.slice(0,a):i}const w=new Set("a an and are as at be been but by can could did do does for from had has have how i if in into is it its me my of on or our ought shall should so than that the their them then there these they this those to um was we were what when where which who whom why will with would you your about tell show give find get please could-you was-there did-we".split(/\s+/));function d(h,{extra:c=[],max:a=4}={}){const r=String(h||"").trim(),i=[],o=new Set,e=t=>{const u=String(t||"").trim().replace(/\s+/g," "),f=u.toLowerCase();u&&!o.has(f)&&(o.add(f),i.push(u))};e(r);for(const t of c)e(t);const s=(r.toLowerCase().match(/[a-z0-9][a-z0-9'’_+-]*/g)||[]).filter(t=>!w.has(t)&&t.length>2);return s.length>=2&&e(s.join(" ")),s.length>3&&e([...s].sort((t,u)=>u.length-t.length).slice(0,3).join(" ")),i.slice(0,Math.max(1,a))}async function p(h,c,{limit:a=10,k:r=60}={}){const i=[],o=new Map,e=new Map;for(const n of h||[]){let s=[];try{s=await c(n)||[]}catch{s=[]}i.push(s.map(t=>t.id));for(const t of s)(!o.has(t.id)||!o.get(t.id).snippet&&t.snippet)&&o.set(t.id,t),e.has(t.id)||e.set(t.id,[]),e.get(t.id).push(n)}return l(i,{k:r,limit:a}).map(({id:n,score:s})=>({...o.get(n),id:n,score:s,foundBy:e.get(n)||[]}))}export{l as fuseRRF,p as multiSearch,d as planQueries};