@chatpanel/gateway 0.40.0 → 0.46.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -216,6 +216,10 @@ env vars. See [`gateway.config.example.json`](gateway.config.example.json).
216
216
  | `ner.model` | — | `Xenova/bert-base-NER` | model id under `~/.chatpanel/models` |
217
217
  | `ner.allowDownload` | — | `true` | download the model on first run if absent |
218
218
 
219
+ `mcp.ask` governs what an MCP client may do with your models — the ceiling for `ask_model`
220
+ and the switch for `delegate_task`. See
221
+ [Ask another model](#ask-another-model-and-delegate-real-work).
222
+
219
223
  ## Endpoints
220
224
 
221
225
  | Route | Behavior |
@@ -259,14 +263,16 @@ it stands.
259
263
 
260
264
  ## Use it as an MCP server (Codex, Claude Code, any MCP client)
261
265
 
262
- Point one MCP server at the gateway and any CLI agent can reach your **local history**
263
- (past chats, meeting transcripts, notes — redacted on the way out) **and every skill
264
- installed on your machine** — across Claude Code, Codex, Copilot, Gemini, Hermes,
265
- `~/.agents/skills` and any folder you configure. History is served by the gateway; skills
266
- are proxied from the [bridge](https://github.com/chatpanel/chatpanel-bridge) (optional — if
267
- it is not running, the history tools still work and the skill tools say so).
266
+ Add one MCP server and any agent — Copilot in VS Code, Cursor, Claude Code, Codex —
267
+ gets **this machine** as tools: your local history, the skills installed here, the small
268
+ models that answer in milliseconds, the privacy detector, and the coding agents you are
269
+ already signed in to. Work that belongs on your machine stops having to be pasted into a
270
+ cloud agent's context.
268
271
 
269
- It is a stdio MCP server: `chatpanel-gateway mcp`.
272
+ It is a stdio MCP server: `chatpanel-gateway mcp`. History, memory and capabilities are
273
+ served by the gateway; skills and coding agents are proxied from the
274
+ [bridge](https://github.com/chatpanel/chatpanel-bridge) (optional — without it the rest
275
+ still works and those tools say so).
270
276
 
271
277
  **Codex** — add to `~/.codex/config.toml`:
272
278
 
@@ -305,27 +311,166 @@ args = ["mcp"]
305
311
  claude mcp add --scope user chatpanel chatpanel-gateway mcp
306
312
  ```
307
313
 
314
+ **VS Code (GitHub Copilot)** — `.mcp.json` in the project, or `mcp.json` in your user
315
+ profile for every project:
316
+
317
+ ```json
318
+ {
319
+ "servers": {
320
+ "chatpanel": { "type": "stdio", "command": "chatpanel-gateway", "args": ["mcp"] }
321
+ }
322
+ }
323
+ ```
324
+
325
+ **Cursor** — the same shape in `~/.cursor/mcp.json` (or `.cursor/mcp.json` per project),
326
+ under `mcpServers` rather than `servers`.
327
+
308
328
  **Any other MCP client** — run the stdio server `chatpanel-gateway mcp`, or point at it the
309
329
  way your client configures a `command` + `args` stdio server.
310
330
 
311
331
  > If your client launches with a stripped `PATH` and cannot find `chatpanel-gateway`, use
312
332
  > the absolute path (find it with `which chatpanel-gateway`).
313
333
 
334
+ > **If a tool is missing, you are probably running two ChatPanels.** Your client launches
335
+ > whichever `chatpanel-gateway` is on its `PATH`, and an older one starts a server that simply
336
+ > has fewer tools — no error, nothing in a log. The server now detects this itself: it reports
337
+ > its real build as `serverInfo.version` (your client's MCP panel shows it) and, when the
338
+ > gateway running on this machine is a different version, says so in its instructions so the
339
+ > agent can tell you. To fix it, point the MCP config at the newer executable — `which
340
+ > chatpanel-gateway` against `curl -s 127.0.0.1:4320/health` — or update the older install.
341
+
314
342
  ### Tools it exposes
315
343
 
344
+ **Your history and memory** — what you said, and what ChatPanel knows about you.
345
+
316
346
  | Tool | What it does |
317
347
  |------|--------------|
318
- | `search_history` | Full-text search your chats, meetings and notes by relevance |
319
- | `get_record` | Fetch one record's full text by id (`chat:…`, `meeting:…`, `note:…`) |
348
+ | `smart_search` | Best first stop: asks your question several ways at once and fuses the rankings |
349
+ | `search_history` | One exact keyword query, with `type` / `since` / `before` filters |
350
+ | `get_record` | One record's full text by id (`chat:…`, `meeting:…`, `note:…`), pageable |
351
+ | `find_related` | Given a record, the ones most connected to it |
320
352
  | `list_history` | Browse/page the corpus (newest first, no bodies) |
321
- | `list_skills` | List every installed skill (name + one-line description, and where it came from) |
322
- | `open_skill` | Load one skill's full instructions by name |
323
- | `read_skill_file` | Read a reference file a skill's instructions point at |
353
+ | `list_briefs` / `get_brief` | The maintained page about a person, project or topic — every claim citing its record |
354
+ | `recall` | The durable facts about you, so an agent follows them without being told |
355
+ | `remember` / `forget` | Save or drop one such fact. Writes are stamped with which agent made them |
356
+
357
+ **Skills** — every skill installed on this machine, across Claude Code, Codex, Copilot,
358
+ Gemini, Hermes, `~/.agents/skills` and any folder you configure.
359
+
360
+ | Tool | What it does |
361
+ |------|--------------|
362
+ | `list_skills` | Name + one-line description, and where each came from |
363
+ | `open_skill` | One skill's full instructions |
364
+ | `read_skill_file` | A reference file those instructions point at |
365
+
366
+ **This machine's capabilities** — things your box can do that a remote agent cannot.
367
+
368
+ | Tool | What it does |
369
+ |------|--------------|
370
+ | `redact_check` | What is personal or secret in a piece of text, found by the detector here. Call it **before** pasting someone's data anywhere |
371
+ | `read_document` | A URL as clean markdown through your reader and cache — a fraction of the context raw HTML costs |
372
+ | `decide` | A sentiment / urgency / yes-no / pick-one judgement with a probability per option, in milliseconds |
373
+ | `rerank` | Order many candidates by relevance, best first, instead of reading them all |
374
+ | `web_search` | Your own search (your SearXNG when one runs here), top pages already read |
375
+
376
+ **Your models** — see [Ask another model](#ask-another-model-and-delegate-real-work) below.
377
+
378
+ | Tool | What it does |
379
+ |------|--------------|
380
+ | `list_models` | What can answer, grouped by **where each one runs** |
381
+ | `ask_model` | Hand a question to one and get the answer. The model answers from your prompt alone |
382
+ | `delegate_task` | Hand a whole piece of work to a coding agent here, in a directory you allow. **Off by default** |
383
+ | `ask_status` | Collect the result of a slow `ask_model` or `delegate_task` |
324
384
 
325
385
  Everything a history tool returns is **redacted** with the same engine
326
386
  ([`@chatpanel/pii`](https://github.com/chatpanel/chatpanel-pii)) the gateway uses for model
327
387
  traffic — the real values never leave your device. Skill scripts are never served as text.
328
388
 
389
+ ### Ask another model, and delegate real work
390
+
391
+ `ask_model` hands a question to any model this machine can reach — a coding agent you are
392
+ signed in to, a local engine, an API key you configured — and returns the answer as text.
393
+
394
+ ```
395
+ ask_model(prompt: "Does this migration lose data? <paste>", model: "claude")
396
+ → …the answer…
397
+ — answered by claude · a cloud provider — this text left the machine (redacted first) · 2 values redacted before it was sent · 6.4s
398
+ ```
399
+
400
+ Every answer says **which model produced it, whether the text left this machine, and what
401
+ redaction replaced on the way out**. You asked a server on localhost; that line is the only
402
+ way to know the question went to a cloud. `list_models` groups by the same fact, so an
403
+ agent can keep sensitive text on the box by picking a `device` model.
404
+
405
+ The model you ask is **blind**: no filesystem, no shell, no web, no tools. It answers from
406
+ the prompt and nothing else, so an `ask_model` call cannot read anything the caller could
407
+ not already read. That is the default and it is not the caller's to change — see
408
+ [What the caller may and may not do](#what-the-caller-may-and-may-not-do).
409
+
410
+ `delegate_task` is the other half: one of your coding agents running **here, with its real
411
+ tools, in a real directory** — the refactor a remote agent would need forty file reads to
412
+ attempt, the test suite it cannot run, the build it cannot see.
413
+
414
+ ```
415
+ delegate_task(task: "The tests in src/auth fail since the token change. Fix them.",
416
+ workingDir: "~/code/app")
417
+ → claude has started work in /Users/you/code/app.
418
+ Call ask_status with job id "ask_1" in 15-30 seconds…
419
+ ```
420
+
421
+ It takes minutes, so it returns a job id you collect with `ask_status`; pass `wait: 0` to
422
+ get the id immediately and carry on with your own work.
423
+
424
+ **`delegate_task` does not exist until you switch it on.** With no directories configured
425
+ it is not listed, not callable and not mentioned to the model — a default install has no
426
+ delegation surface at all. To enable it, name the directories an agent may work in:
427
+
428
+ ```jsonc
429
+ // ~/.chatpanel/gateway.config.json
430
+ {
431
+ "mcp": {
432
+ "ask": {
433
+ "maxReach": "device", // the ceiling for ask_model (below)
434
+ "defaultModel": "", // answers a call that names no model
435
+ "delegate": {
436
+ "roots": ["/Users/you/code/app"], // the on-switch AND the boundary
437
+ "permissionMode": "acceptEdits" // what a delegated run may do
438
+ }
439
+ }
440
+ }
441
+ }
442
+ ```
443
+
444
+ `permissionMode` is `acceptEdits` by default: a delegated agent may **edit files in that
445
+ directory**, and the shell still asks — which is denied, because nobody is there to answer.
446
+ `"default"` makes it read-only (good for "survey this codebase"); `"bypassPermissions"`
447
+ also gives it the shell. Restart the gateway after editing this file.
448
+
449
+ A path outside every root is refused with the list of what is allowed, and containment is
450
+ checked on the resolved path — `/srv/app-secrets` is not inside `/srv/app`, and `..` cannot
451
+ climb out.
452
+
453
+ ### What the caller may and may not do
454
+
455
+ The agent calling these tools reads web pages and repo files for a living, so it is treated
456
+ as capable of being prompt-injected. Three things hold regardless of what it asks for:
457
+
458
+ 1. **An asked model is conversational only.** `reach: device` means no filesystem, shell,
459
+ web, writes or subagent — enforced where the process is spawned, not by asking it nicely.
460
+ 2. **The caller cannot raise its own ceiling.** `reach` is a tool argument, so a model will
461
+ eventually ask for more; it gets the stricter of what it asked and your `mcp.ask.maxReach`.
462
+ An unrecognised value caps to `device`. Privilege comes from your config file, never from
463
+ the conversation.
464
+ 3. **No tool here opens a local file by path.** `read_document` takes a URL only. The one
465
+ exception is `delegate_task`, which is off until you name its directories.
466
+
467
+ Raising `maxReach` to `"any"` lets `ask_model` run an agent at its configured permission
468
+ mode. Only Claude Code turns a reach tier into a tool policy, so the other agents are
469
+ *refused* under a capped tier rather than quietly running uncapped — the refusal says so.
470
+
471
+ Every tool call is attributed to the client that made it (`clientInfo` from the MCP
472
+ handshake) in the gateway's access log, so ChatPanel can tell you which agent read what.
473
+
329
474
  ### One local view
330
475
 
331
476
  ```bash
@@ -390,6 +535,20 @@ agent's own multi-turn loop is blinded, not just the first prompt.
390
535
  - Everything returned is **redacted** at the configured tier. A tool result may contain a
391
536
  placeholder like `[[EMAIL_1]]` where a value was blinded — that is the privacy guarantee
392
537
  working, not a bug.
538
+ - **`redact_check` tells you what it could not see.** With the entity detector off or the
539
+ tier at `basic`, patterns (emails, phones, cards, keys) are still checked but names and
540
+ organisations are not — and a text full of names then looks exactly like a clean one. The
541
+ result carries a `CAUTION` line whenever that is the case. Read it: "no findings" under a
542
+ patterns-only pass means *no patterns found*, not *nothing personal here*.
543
+ - **`ask_model` and `delegate_task` need a model to reach.** `ask_model` with no coding
544
+ agent signed in, no local engine and no API destination has nothing to ask — run
545
+ `list_models` first, and it says so plainly when the list is empty.
546
+ - **A slow answer is normal, not a hang.** A coding agent on a real question takes minutes.
547
+ Past `wait` seconds you get a job id instead of a failure; poll `ask_status` every 15–30
548
+ seconds. The work continues whether or not you poll, and the job id lives as long as the
549
+ MCP session — a client that reconnects gets a fresh server and the id is gone.
550
+ - **`delegate_task` is absent unless you configured `mcp.ask.delegate.roots`** and restarted
551
+ the gateway. If you expected it and do not see it, that is why.
393
552
 
394
553
  ## License
395
554
 
@@ -1 +1,2 @@
1
- import{pathToFileURL as i}from"node:url";import m from"../assets/ort-wasm-simd-threaded.wasm";import t from"../assets/ort-wasm-simd-threaded.mjs";globalThis.__CHATPANEL_WASM_PATHS__={wasm:i(m).href,mjs:i(t).href},await import("./chatpanel-gateway.js");
1
+ import{pathToFileURL as s}from"node:url";import{createRequire as m}from"node:module";import{existsSync as l,readFileSync as c}from"node:fs";import{join as f}from"node:path";import{homedir as p}from"node:os";import{normalizeRegistries as u}from"@chatpanel/events/registries.js";import d from"../assets/ort-wasm-simd-threaded.wasm";import g from"../assets/ort-wasm-simd-threaded.mjs";import{findNativeBinding as _,ensureNativeOrt as h}from"../src/ort-native.js";function A(){try{const e=process.env.CHATPANEL_GATEWAY_CONFIG||f(p(),".chatpanel","gateway.config.json"),i=l(e)?JSON.parse(c(e,"utf8")):{},r={npm:process.env.CHATPANEL_REGISTRY_NPM,models:process.env.CHATPANEL_REGISTRY_MODELS};return u({...i.registries||{},...r.npm?{npm:r.npm}:{},...r.models?{models:r.models}:{}})}catch{return{}}}const t=e=>{try{process.stderr.write(`[ort] ${e}
2
+ `)}catch{}};let n=null,a=!1;function N(e){if(a)return n;a=!0;try{n=m(import.meta.url)(e),t(`native runtime loaded — ${e}`)}catch(i){t(`native runtime would not load (${String(i?.message||i).slice(0,120)}) — falling back to WASM`),n=null}return n}let o=_();o||h({registries:A(),onProgress:e=>{e.phase==="download"&&t(`fetching the native runtime once (~108 MB) from ${new URL(e.url).host} — WASM answers until it lands`)}}).then(e=>t(`native runtime ready — ${e} (restart to use it)`)).catch(e=>t(`no native runtime (${String(e?.message||e).slice(0,120)}) — staying on WASM`)),o?globalThis.__CHATPANEL_ORT_BINDING__=()=>N(o):globalThis.__CHATPANEL_WASM_PATHS__={wasm:s(d).href,mjs:s(g).href},await import("./chatpanel-gateway.js");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chatpanel/gateway",
3
- "version": "0.40.0",
3
+ "version": "0.46.4",
4
4
  "description": "Local privacy gateway — redacts PII out of OpenAI/Anthropic API traffic before it reaches a model, then restores it in the reply. Point opencode, codex, aider, Claude Code, etc. at it.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -22,8 +22,8 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@anthropic-ai/sandbox-runtime": "^0.0.77",
25
- "@chatpanel/bridge": "^0.20.1",
26
- "@chatpanel/events": "^0.190.0",
25
+ "@chatpanel/bridge": "^0.24.0",
26
+ "@chatpanel/events": "^0.193.0",
27
27
  "@chatpanel/pii": "^0.11.0",
28
28
  "@huggingface/transformers": "^4.2.0",
29
29
  "defuddle": "^0.19.4",
package/src/config.js CHANGED
@@ -1 +1 @@
1
- import{readFileSync as s,existsSync as d}from"node:fs";import{join as l}from"node:path";import p from"node:os";import{DEFAULT_MODEL as c}from"./models.js";import{DEFAULT_STT_MODEL as u}from"./stt-models.js";const a={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:c,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:u,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function _(t=process.env){let e=a;const i=t.CHATPANEL_GATEWAY_CONFIG||l(p.homedir(),".chatpanel","gateway.config.json");if(d(i))try{e=r(e,JSON.parse(s(i,"utf8")))}catch(n){throw new Error(`bad config file ${i}: ${n.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==a.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${a.port}`),e=r(e,{port:a.port})),e}export{a as DEFAULTS,_ as loadConfig};
1
+ import{readFileSync as d,existsSync as p}from"node:fs";import{join as c}from"node:path";import l from"node:os";import{DEFAULT_MODEL as A}from"./models.js";import{DEFAULT_STT_MODEL as E}from"./stt-models.js";const s={host:"127.0.0.1",port:4320,backend:"bridge",destinations:[],allowedOrigins:[],allowedExtensionIds:[],maxBodyBytes:26214400,pro:{entitlementToken:"",free:{used:0}},sandbox:{mode:"open",hosts:[],write:[],denyRead:[]},bridge:{url:"http://127.0.0.1:4319",agent:"codex",token:"",permissionMode:"default",workingDir:"",openAgentLane:!1},mcp:{ask:{maxReach:"device",defaultModel:"",delegate:{roots:[],permissionMode:"acceptEdits"}}},upstreams:{openai:{baseUrl:"https://api.openai.com"},anthropic:{baseUrl:"https://api.anthropic.com"}},redaction:{tier:"basic",dictionary:[],detection:{backend:"off"},redactSystem:!0},ner:{autostart:!0,model:A,union:[],warmMs:15*6e4,caseRecovery:!0,allowDownload:!0,enableFullTier:!0},stt:{enabled:!0,model:E,allowDownload:!0,diarize:!0,warmMs:15*6e4},read:{provider:"defuddle",remote:{url:"",key:""}},search:{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},capabilities:{},runtime:{services:{}},registries:{},fusions:[],tts:{enabled:!0,warmMs:15*6e4,provider:"local",model:"",voice:"",allowDownload:!0,remote:{baseUrl:"",model:"",voice:"",redact:!0}},logRequests:!0,logDetail:"off"};function r(t,e){if(Array.isArray(e))return e;if(e&&typeof e=="object"&&t&&typeof t=="object"){const i={...t};for(const o of Object.keys(e))i[o]=r(t[o],e[o]);return i}return e===void 0?t:e}function g(t=process.env){let e=s;const i=t.CHATPANEL_GATEWAY_CONFIG||c(l.homedir(),".chatpanel","gateway.config.json");if(p(i))try{e=r(e,JSON.parse(d(i,"utf8")))}catch(a){throw new Error(`bad config file ${i}: ${a.message}`)}t.CHATPANEL_GATEWAY_HOST&&(e=r(e,{host:t.CHATPANEL_GATEWAY_HOST})),t.CHATPANEL_GATEWAY_PORT&&(e=r(e,{port:Number(t.CHATPANEL_GATEWAY_PORT)})),t.OPENAI_BASE_URL&&(e=r(e,{upstreams:{openai:{baseUrl:t.OPENAI_BASE_URL}}})),t.ANTHROPIC_BASE_URL&&(e=r(e,{upstreams:{anthropic:{baseUrl:t.ANTHROPIC_BASE_URL}}})),t.CHATPANEL_REDACTION_TIER&&(e=r(e,{redaction:{tier:t.CHATPANEL_REDACTION_TIER}}));for(const[a,n]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])t[n]&&(e=r(e,{registries:{[a]:t[n]}}));if(e.registries?.models&&!t.CHATPANEL_REGISTRY_MODELS)try{process.env.CHATPANEL_REGISTRY_MODELS=e.registries.models}catch{}const o=Number(e.port);return(!Number.isInteger(o)||o<1||o>65535)&&(e.port!==s.port&&console.warn(`[gateway] ignoring invalid port ${JSON.stringify(e.port)} — using ${s.port}`),e=r(e,{port:s.port})),e}export{s as DEFAULTS,g as loadConfig};
@@ -1 +1 @@
1
- import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as D}from"@chatpanel/bridge/src/events/sandbox-policy.js";const v=["open","allowlist","off"],l=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=v.includes(r.mode)?r.mode:"open",{hosts:i}=D({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function P(e){const r=d(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function R(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function L(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...n}=o;return{...n,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:n,...t}=i||{};return[o,{...t,hasToken:!!n}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function C(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function E(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),n=Number(o.port)||(o.protocol==="https:"?443:80);return i&&n===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function M(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function I(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const n=E(i,e);return n&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!n}).map(i=>{const n={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(n.agent=i.agent||i.id),i.type==="api"){n.baseUrl=String(i.baseUrl||""),n.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(n.apiKey=s)}const t=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return t&&(n.service=t),n})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),m.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=d({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=f(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const t={...e.capabilities[o]||{}};if(i.provider==="embedded"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),t.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(t.adapter=i.adapter),typeof i.model=="string"&&(t.model=i.model.trim()),typeof i.token=="string"&&(t.token=i.token),typeof i.calibrated=="boolean"&&(t.calibrated=i.calibrated),typeof i.redact=="boolean"&&(t.redact=i.redact),!t.url){delete e.capabilities[o];continue}t.provider="remote",delete t.service,e.capabilities[o]=t,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:t.url,...t.token?{apiKey:t.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{m as PERMISSION_MODES,I as applyConfigPatch,C as applyNerModelSelection,M as bridgeAgentOptions,u as configPath,E as isSelfDestination,d as normalizeSandboxConfig,R as persistConfig,L as publicConfig,P as sandboxEnvFor};
1
+ import{writeFileSync as b,mkdirSync as y,chmodSync as p}from"node:fs";import{join as A,dirname as w}from"node:path";import x from"node:os";import{usage as k}from"./freegate.js";import{applyFusionsPatch as f}from"./fusions.js";import{normalizeRegistries as E,REGISTRY_KINDS as D}from"@chatpanel/events/registries.js";import{assertEndpointUrl as a}from"@chatpanel/pii";import{normalizeGrant as S}from"@chatpanel/bridge/src/events/sandbox-policy.js";const T=["open","allowlist","off"],l=e=>(Array.isArray(e)?e:String(e||"").split(/[\n,]+/)).map(r=>String(r).trim()).filter(r=>r&&r.length<1024&&!r.includes("\0"));function d(e={}){const r=e&&typeof e=="object"?e:{},o=T.includes(r.mode)?r.mode:"open",{hosts:i}=S({hosts:r.hosts??[]});return{mode:o,hosts:i,write:l(r.write),denyRead:l(r.denyRead)}}function L(e){const r=d(e?.sandbox);return{CHATPANEL_SANDBOX:r.mode,CHATPANEL_SANDBOX_ALLOW_HOSTS:r.hosts.join(","),CHATPANEL_SANDBOX_ALLOW_WRITE:r.write.join(","),CHATPANEL_SANDBOX_DENY_READ:r.denyRead.join(",")}}function u(e=process.env){return e.CHATPANEL_GATEWAY_CONFIG||A(x.homedir(),".chatpanel","gateway.config.json")}function C(e){const r=e?.registries||{},o={};for(const[i,t]of[["npm","CHATPANEL_REGISTRY_NPM"],["pypi","CHATPANEL_REGISTRY_PYPI"],["models","CHATPANEL_REGISTRY_MODELS"],["github","CHATPANEL_REGISTRY_GITHUB"]])r[i]&&(o[t]=r[i]);return o}function M(e,r=u()){if(process.env.NODE_TEST_CONTEXT&&!process.env.CHATPANEL_GATEWAY_CONFIG&&r===u({}))throw new Error(`refusing to persist the real gateway config (${r}) from a test — set CHATPANEL_GATEWAY_CONFIG to a temp file`);y(w(r),{recursive:!0,mode:448});const o={host:e.host,port:e.port,backend:e.backend,destinations:e.destinations,bridge:e.bridge,upstreams:e.upstreams,redaction:e.redaction,ner:e.ner,stt:e.stt,tts:e.tts,read:e.read,search:e.search,capabilities:e.capabilities,runtime:e.runtime,fusions:e.fusions,allowedOrigins:e.allowedOrigins,allowedExtensionIds:e.allowedExtensionIds,maxBodyBytes:e.maxBodyBytes,pro:e.pro,logRequests:e.logRequests,logDetail:e.logDetail,tools:e.tools,sandbox:e.sandbox,registries:e.registries,mcp:e.mcp};b(r,JSON.stringify(o,null,2),{mode:384});try{p(r,384)}catch{}}function H(e,{proUnlocked:r=!1}={}){return{backend:e.backend,destinations:(Array.isArray(e.destinations)?e.destinations:[]).map(o=>{const{apiKey:i,...t}=o;return{...t,hasKey:!!i}}),bridge:{url:e.bridge?.url,agent:e.bridge?.agent,hasToken:!!e.bridge?.token,permissionMode:e.bridge?.permissionMode||"default",workingDir:e.bridge?.workingDir||""},upstreams:e.upstreams,redaction:{tier:e.redaction?.tier,redactSystem:e.redaction?.redactSystem!==!1,detection:(()=>{const{apiKey:o,...i}=e.redaction?.detection||{backend:"off"};return i})(),dictionary:Array.isArray(e.redaction?.dictionary)?e.redaction.dictionary:[]},ner:e.ner,stt:e.stt,sandbox:d(e.sandbox),read:{provider:e.read?.provider||"defuddle",remote:{url:e.read?.remote?.url||"",hasKey:!!e.read?.remote?.key}},registries:{...e.registries||{}},search:{provider:e.search?.provider||"auto",searxng:{url:e.search?.searxng?.url||"",hasToken:!!e.search?.searxng?.token,engines:e.search?.searxng?.engines||"",safesearch:e.search?.searxng?.safesearch??0}},runtime:{services:e.runtime?.services||{}},fusions:Array.isArray(e.fusions)?e.fusions:[],capabilities:Object.fromEntries(Object.entries(e.capabilities||{}).map(([o,i])=>{const{token:t,...n}=i||{};return[o,{...n,hasToken:!!t}]})),allowedOrigins:Array.isArray(e.allowedOrigins)?e.allowedOrigins:[],allowedExtensionIds:Array.isArray(e.allowedExtensionIds)?e.allowedExtensionIds:[],pro:{unlocked:r,hasToken:!!e.pro?.entitlementToken,free:k(e)},logRequests:!!e.logRequests,logDetail:["types","values"].includes(e.logDetail)?e.logDetail:"off",tools:{autoNarrow:e.tools?.autoNarrow!==!1,maxPerTurn:Number(e.tools?.maxPerTurn)>0?Number(e.tools.maxPerTurn):8,narrowAll:!!e.tools?.narrowAll,toolData:e.tools?.toolData==="redactRemote"?"redactRemote":"real"}}}function G(e,r){return e.ner=e.ner||{allowDownload:!0,enableFullTier:!0},e.ner.model=r,e.ner.autostart=!0,e.ner}function N(e,r={}){if(!e||e.type!=="api")return!1;let o;try{o=new URL(String(e.baseUrl||""))}catch{return!1}const i=/^(127\.0\.0\.1|localhost|\[::1\]|0\.0\.0\.0)$/i.test(o.hostname),t=Number(o.port)||(o.protocol==="https:"?443:80);return i&&t===(Number(r.port)||4320)}const m=["default","acceptEdits","bypassPermissions"];function g(e,r={}){const o=e?.bridge||{};return{...m.includes(o.permissionMode)&&o.permissionMode!=="default"?{permissionMode:o.permissionMode}:{},...typeof o.workingDir=="string"&&o.workingDir.trim()?{workingDir:o.workingDir.trim()}:{},...r}}function K(e,r={}){if((r.backend==="bridge"||r.backend==="api")&&(e.backend=r.backend),Array.isArray(r.destinations)){const o=new Map((Array.isArray(e.destinations)?e.destinations:[]).map(i=>[i.id,i]));e.destinations=r.destinations.filter(i=>i&&typeof i.id=="string"&&(i.type==="agent"||i.type==="api")).filter(i=>{const t=N(i,e);return t&&console.log(`[gateway] refusing destination "${i.id}": ${i.baseUrl} is this gateway — a loop`),!t}).map(i=>{const t={id:i.id,type:i.type,models:Array.isArray(i.models)?i.models.filter(s=>typeof s=="string"&&s):[]};if(i.type==="agent"&&(t.agent=i.agent||i.id),i.type==="api"){t.baseUrl=String(i.baseUrl||""),t.protocol=i.protocol==="anthropic"?"anthropic":"openai";const s=typeof i.apiKey=="string"&&i.apiKey?i.apiKey:o.get(i.id)?.apiKey;s&&(t.apiKey=s)}const n=typeof i.service=="string"&&i.service?i.service:o.get(i.id)?.service;return n&&(t.service=n),t})}if(r.bridge&&typeof r.bridge=="object"&&(typeof r.bridge.url=="string"&&(e.bridge.url=r.bridge.url),typeof r.bridge.agent=="string"&&(e.bridge.agent=r.bridge.agent),m.includes(r.bridge.permissionMode)&&(e.bridge.permissionMode=r.bridge.permissionMode),typeof r.bridge.workingDir=="string"&&(e.bridge.workingDir=r.bridge.workingDir.trim().slice(0,1024)),typeof r.bridge.openAgentLane=="boolean"&&(e.bridge.openAgentLane=r.bridge.openAgentLane)),Array.isArray(r.allowedExtensionIds)&&(e.allowedExtensionIds=r.allowedExtensionIds.map(o=>String(o).trim()).filter(o=>/^[a-p]{32}$/.test(o))),r.upstreams&&typeof r.upstreams=="object")for(const o of["openai","anthropic"]){const i=r.upstreams[o];i&&typeof i.baseUrl=="string"&&i.baseUrl.trim()&&(e.upstreams[o]={...e.upstreams[o],baseUrl:i.baseUrl.trim()})}if(r.redaction&&typeof r.redaction=="object"){const o=r.redaction;(o.tier==="basic"||o.tier==="full")&&(e.redaction.tier=o.tier),"redactSystem"in o&&(e.redaction.redactSystem=!!o.redactSystem),Array.isArray(o.dictionary)&&(e.redaction.dictionary=o.dictionary),o.detection&&typeof o.detection=="object"&&(e.redaction.detection=o.detection)}if(Array.isArray(r.allowedOrigins)&&(e.allowedOrigins=r.allowedOrigins),r.sandbox&&typeof r.sandbox=="object"&&(e.sandbox=d({...e.sandbox||{},...r.sandbox})),r.pro&&typeof r.pro=="object"&&typeof r.pro.entitlementToken=="string"&&(e.pro.entitlementToken=r.pro.entitlementToken),r.stt&&typeof r.stt=="object"&&(e.stt=e.stt||{enabled:!0,model:"onnx-community/whisper-base",allowDownload:!0},"enabled"in r.stt&&(e.stt.enabled=!!r.stt.enabled),"allowDownload"in r.stt&&(e.stt.allowDownload=!!r.stt.allowDownload)),r.read&&typeof r.read=="object"){if(e.read=e.read||{provider:"defuddle",remote:{url:"",key:""}},e.read.remote=e.read.remote||{url:"",key:""},r.read.remote&&typeof r.read.remote=="object"){if("url"in r.read.remote){const o=String(r.read.remote.url||"").trim();o&&a(o),e.read.remote.url=o}typeof r.read.remote.key=="string"&&(e.read.remote.key=r.read.remote.key)}["defuddle","text","remote"].includes(r.read.provider)&&(e.read.provider=r.read.provider==="remote"&&!e.read.remote.url?e.read.provider:r.read.provider)}if(r.registries&&typeof r.registries=="object"){const o=E(r.registries),i={...e.registries||{}};for(const t of D)t in r.registries&&(o[t]?i[t]=o[t]:delete i[t]);e.registries=i}if(r.search&&typeof r.search=="object"){e.search=e.search||{provider:"auto",searxng:{url:"",token:"",engines:"",safesearch:0}},e.search.searxng=e.search.searxng||{url:"",token:"",engines:"",safesearch:0};const o=r.search.searxng;if(o&&typeof o=="object"){if("url"in o){const i=String(o.url||"").trim();i&&a(i),e.search.searxng.url=i}typeof o.token=="string"&&(e.search.searxng.token=o.token),typeof o.engines=="string"&&(e.search.searxng.engines=o.engines.replace(/[^a-z0-9_,-]/gi,"")),[0,1,2].includes(o.safesearch)&&(e.search.searxng.safesearch=o.safesearch)}["auto","serp","searxng"].includes(r.search.provider)&&(e.search.provider=r.search.provider==="searxng"&&!e.search.searxng.url?e.search.provider:r.search.provider)}if("fusions"in r){const o=f(e,r.fusions);if(o){const i=new Error(o);throw i.code="SHAPE",i}}if(r.capabilities&&typeof r.capabilities=="object"){e.capabilities=e.capabilities||{};for(const o of["rerank","decide","stt","tts","detect","embed"]){if(!(o in r.capabilities))continue;const i=r.capabilities[o];if(i===null){delete e.capabilities[o],o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if(!i||typeof i!="object")continue;const n={...e.capabilities[o]||{}};if(i.provider==="embedded"){e.capabilities[o]={provider:"embedded"},o==="detect"&&e.redaction?.detection?.backend==="endpoint"&&(e.redaction.detection={backend:"off"});continue}if("url"in i){const s=String(i.url||"").trim();s&&a(s),n.url=s}if(typeof i.adapter=="string"&&/^[a-z-]+$/.test(i.adapter)&&(n.adapter=i.adapter),typeof i.model=="string"&&(n.model=i.model.trim()),typeof i.token=="string"&&(n.token=i.token),typeof i.calibrated=="boolean"&&(n.calibrated=i.calibrated),typeof i.redact=="boolean"&&(n.redact=i.redact),!n.url){delete e.capabilities[o];continue}n.provider="remote",delete n.service,e.capabilities[o]=n,o==="detect"&&(e.redaction=e.redaction||{},e.redaction.detection={...e.redaction.detection||{},backend:"endpoint",url:n.url,...n.token?{apiKey:n.token}:{}})}}if(typeof r.logRequests=="boolean"&&(e.logRequests=r.logRequests),["off","types","values"].includes(r.logDetail)&&(e.logDetail=r.logDetail),r.tools&&typeof r.tools=="object"){e.tools=e.tools||{},"autoNarrow"in r.tools&&(e.tools.autoNarrow=!!r.tools.autoNarrow),"narrowAll"in r.tools&&(e.tools.narrowAll=!!r.tools.narrowAll),(r.tools.toolData==="real"||r.tools.toolData==="redactRemote")&&(e.tools.toolData=r.tools.toolData);const o=Number(r.tools.maxPerTurn);Number.isFinite(o)&&o>=1&&(e.tools.maxPerTurn=Math.floor(o))}return e}export{m as PERMISSION_MODES,K as applyConfigPatch,G as applyNerModelSelection,g as bridgeAgentOptions,u as configPath,N as isSelfDestination,d as normalizeSandboxConfig,M as persistConfig,H as publicConfig,C as registryChildEnv,L as sandboxEnvFor};
@@ -1,4 +1,4 @@
1
- import{readFileSync as f,writeFileSync as g,existsSync as c,copyFileSync as v,mkdirSync as $}from"node:fs";import{execFileSync as m}from"node:child_process";import{join as u}from"node:path";import b from"node:os";const C=["smart_search","search_history","get_record","find_related","list_history","recall","list_skills","open_skill","read_skill_file"];function S(t=h){return t("chatpanel-gateway")||"chatpanel-gateway"}function h(t){try{return m("which",[t],{encoding:"utf8"}).trim()||null}catch{return null}}function y(t){const s=`${t}.bak.chatpanel`;try{return v(t,s),s}catch{return null}}function w({cmd:t,dryRun:s,home:a}){const e=u(a,".codex"),n=u(e,"config.toml");if(!c(e))return{id:"codex",status:"absent"};const o=c(n)?f(n,"utf8"):"";if(/\[mcp_servers\.chatpanel\]/.test(o))return{id:"codex",status:"already",path:n};let i=`
1
+ import{readFileSync as f,writeFileSync as g,existsSync as c,copyFileSync as v,mkdirSync as b}from"node:fs";import{execFileSync as m}from"node:child_process";import{join as u}from"node:path";import $ from"node:os";const C=["smart_search","search_history","get_record","find_related","list_history","list_briefs","get_brief","recall","list_skills","open_skill","read_skill_file","decide","rerank","redact_check","list_models"];function S(t=h){return t("chatpanel-gateway")||"chatpanel-gateway"}function h(t){try{return m("which",[t],{encoding:"utf8"}).trim()||null}catch{return null}}function y(t){const r=`${t}.bak.chatpanel`;try{return v(t,r),r}catch{return null}}function k({cmd:t,dryRun:r,home:a}){const e=u(a,".codex"),n=u(e,"config.toml");if(!c(e))return{id:"codex",status:"absent"};const o=c(n)?f(n,"utf8"):"";if(/\[mcp_servers\.chatpanel\]/.test(o))return{id:"codex",status:"already",path:n};let i=`
2
2
  # ChatPanel — local history (redacted) + your installed skills, via one MCP server.
3
3
  `;i+=`[mcp_servers.chatpanel]
4
4
  command = ${JSON.stringify(t)}
@@ -8,15 +8,15 @@ args = ["mcp"]
8
8
  `;for(const p of C)i+=`[mcp_servers.chatpanel.tools.${p}]
9
9
  approval_mode = "approve"
10
10
 
11
- `;if(s)return{id:"codex",status:"would",path:n,preview:i.trim()};const r=y(n);return g(n,`${o.replace(/\s*$/,"")}
12
- ${i}`),{id:"codex",status:"configured",path:n,backup:r}}function k({cmd:t,dryRun:s,which:a}){const e=a("claude");if(!e)return{id:"claude-code",status:"absent"};try{return m(e,["mcp","get","chatpanel"],{stdio:"ignore"}),{id:"claude-code",status:"already"}}catch{}if(s)return{id:"claude-code",status:"would",preview:`claude mcp add --scope user chatpanel ${t} mcp`};try{return m(e,["mcp","add","--scope","user","chatpanel",t,"mcp"],{stdio:"ignore"}),{id:"claude-code",status:"configured"}}catch(n){return{id:"claude-code",status:"error",message:n.message}}}function x({cmd:t,dryRun:s,home:a}){const e=u(a,".gemini"),n=u(e,"settings.json");if(!c(e))return{id:"gemini",status:"absent"};let o={};if(c(n))try{o=JSON.parse(f(n,"utf8"))}catch{return{id:"gemini",status:"error",message:"settings.json is not valid JSON — left untouched",path:n}}if(o.mcpServers=o.mcpServers||{},o.mcpServers.chatpanel)return{id:"gemini",status:"already",path:n};const i={command:t,args:["mcp"]};if(s)return{id:"gemini",status:"would",path:n,preview:JSON.stringify({mcpServers:{chatpanel:i}},null,2)};const r=c(n)?y(n):null;return o.mcpServers.chatpanel=i,$(e,{recursive:!0}),g(n,`${JSON.stringify(o,null,2)}
13
- `),{id:"gemini",status:"configured",path:n,backup:r}}function l(t,s,a){return s?{id:t,status:"manual",snippet:a}:{id:t,status:"absent"}}function _({cmd:t,home:s,which:a}){const e=[];return e.push(l("opencode",c(u(s,".opencode"))||c(u(s,".config","opencode")),`Add to your opencode config (opencode.json):
14
- "mcp": { "chatpanel": { "type": "local", "command": [${JSON.stringify(t)}, "mcp"], "enabled": true } }`)),e.push(l("copilot",c(u(s,".copilot")),`Copilot CLI: add an MCP server named "chatpanel" running: ${t} mcp`)),e.push(l("hermes",c(u(s,".hermes"))||!!a("hermes"),`Hermes: register an MCP server "chatpanel" with command ${t} mcp (see Hermes' MCP docs).`)),e.push(l("pi",c(u(s,".pi"))||!!a("pi"),`Pi: add an MCP server "chatpanel" running: ${t} mcp`)),e}function N({dryRun:t=!1,cmd:s,home:a=b.homedir(),which:e=h}={}){const n=s||S(e),o=[w({cmd:n,dryRun:t,home:a}),k({cmd:n,dryRun:t,which:e}),x({cmd:n,dryRun:t,home:a}),..._({cmd:n,home:a,which:e})];return{cmd:n,results:o}}const P={codex:"Codex","claude-code":"Claude Code",gemini:"Gemini / Antigravity",opencode:"OpenCode",copilot:"GitHub Copilot",hermes:"Hermes",pi:"Pi"};function J({cmd:t,results:s},{dryRun:a=!1}={}){const e=[`ChatPanel MCP — connecting your agents to: ${t} mcp`,""],n={configured:"✓",already:"•",would:"→",manual:"✎",absent:"·",error:"✕"};for(const r of s){const p=P[r.id]||r.id;if(r.status==="absent")continue;const d=` ${n[r.status]||"?"} ${p}`;r.status==="configured"?e.push(`${d} — configured${r.backup?` (backup: ${r.backup})`:""}`):r.status==="already"?e.push(`${d} — already connected`):r.status==="would"?e.push(`${d} — would configure:
15
- ${(r.preview||"").split(`
11
+ `;if(r)return{id:"codex",status:"would",path:n,preview:i.trim()};const s=y(n);return g(n,`${o.replace(/\s*$/,"")}
12
+ ${i}`),{id:"codex",status:"configured",path:n,backup:s}}function w({cmd:t,dryRun:r,which:a}){const e=a("claude");if(!e)return{id:"claude-code",status:"absent"};try{return m(e,["mcp","get","chatpanel"],{stdio:"ignore"}),{id:"claude-code",status:"already"}}catch{}if(r)return{id:"claude-code",status:"would",preview:`claude mcp add --scope user chatpanel ${t} mcp`};try{return m(e,["mcp","add","--scope","user","chatpanel",t,"mcp"],{stdio:"ignore"}),{id:"claude-code",status:"configured"}}catch(n){return{id:"claude-code",status:"error",message:n.message}}}function _({cmd:t,dryRun:r,home:a}){const e=u(a,".gemini"),n=u(e,"settings.json");if(!c(e))return{id:"gemini",status:"absent"};let o={};if(c(n))try{o=JSON.parse(f(n,"utf8"))}catch{return{id:"gemini",status:"error",message:"settings.json is not valid JSON — left untouched",path:n}}if(o.mcpServers=o.mcpServers||{},o.mcpServers.chatpanel)return{id:"gemini",status:"already",path:n};const i={command:t,args:["mcp"]};if(r)return{id:"gemini",status:"would",path:n,preview:JSON.stringify({mcpServers:{chatpanel:i}},null,2)};const s=c(n)?y(n):null;return o.mcpServers.chatpanel=i,b(e,{recursive:!0}),g(n,`${JSON.stringify(o,null,2)}
13
+ `),{id:"gemini",status:"configured",path:n,backup:s}}function l(t,r,a){return r?{id:t,status:"manual",snippet:a}:{id:t,status:"absent"}}function x({cmd:t,home:r,which:a}){const e=[];return e.push(l("opencode",c(u(r,".opencode"))||c(u(r,".config","opencode")),`Add to your opencode config (opencode.json):
14
+ "mcp": { "chatpanel": { "type": "local", "command": [${JSON.stringify(t)}, "mcp"], "enabled": true } }`)),e.push(l("copilot",c(u(r,".copilot")),`Copilot CLI: add an MCP server named "chatpanel" running: ${t} mcp`)),e.push(l("hermes",c(u(r,".hermes"))||!!a("hermes"),`Hermes: register an MCP server "chatpanel" with command ${t} mcp (see Hermes' MCP docs).`)),e.push(l("pi",c(u(r,".pi"))||!!a("pi"),`Pi: add an MCP server "chatpanel" running: ${t} mcp`)),e}function N({dryRun:t=!1,cmd:r,home:a=$.homedir(),which:e=h}={}){const n=r||S(e),o=[k({cmd:n,dryRun:t,home:a}),w({cmd:n,dryRun:t,which:e}),_({cmd:n,dryRun:t,home:a}),...x({cmd:n,home:a,which:e})];return{cmd:n,results:o}}const P={codex:"Codex","claude-code":"Claude Code",gemini:"Gemini / Antigravity",opencode:"OpenCode",copilot:"GitHub Copilot",hermes:"Hermes",pi:"Pi"};function J({cmd:t,results:r},{dryRun:a=!1}={}){const e=[`ChatPanel MCP — connecting your agents to: ${t} mcp`,""],n={configured:"✓",already:"•",would:"→",manual:"✎",absent:"·",error:"✕"};for(const s of r){const p=P[s.id]||s.id;if(s.status==="absent")continue;const d=` ${n[s.status]||"?"} ${p}`;s.status==="configured"?e.push(`${d} — configured${s.backup?` (backup: ${s.backup})`:""}`):s.status==="already"?e.push(`${d} — already connected`):s.status==="would"?e.push(`${d} — would configure:
15
+ ${(s.preview||"").split(`
16
16
  `).join(`
17
- `)}`):r.status==="manual"?e.push(`${d} — add it yourself:
18
- ${r.snippet.split(`
17
+ `)}`):s.status==="manual"?e.push(`${d} — add it yourself:
18
+ ${s.snippet.split(`
19
19
  `).join(`
20
- `)}`):r.status==="error"&&e.push(`${d} — ${r.message}`)}const o=s.filter(r=>r.status==="configured").length;return e.push(""),a?e.push(" (dry run — nothing was written. Re-run without --dry-run to apply.)"):o?e.push(" Done. Restart the configured agent(s) to pick up the new server."):e.push(" Nothing to change."),s.some(r=>r.status==="manual")&&e.push(" Agents marked ✎ use a config format best edited by hand — the snippet above is exact."),`${e.join(`
20
+ `)}`):s.status==="error"&&e.push(`${d} — ${s.message}`)}const o=r.filter(s=>s.status==="configured").length;return e.push(""),a?e.push(" (dry run — nothing was written. Re-run without --dry-run to apply.)"):o?e.push(" Done. Restart the configured agent(s) to pick up the new server."):e.push(" Nothing to change."),r.some(s=>s.status==="manual")&&e.push(" Agents marked ✎ use a config format best edited by hand — the snippet above is exact."),`${e.join(`
21
21
  `)}
22
- `}export{N as connectAgents,J as formatConnect,S as resolveServerCommand};
22
+ `}export{C as TOOLS,N as connectAgents,J as formatConnect,S as resolveServerCommand};
package/src/egress.js CHANGED
@@ -1,2 +1,2 @@
1
- import{isBlockedHost as f}from"@chatpanel/pii";const y=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=y}={}){const t=new Map;return{record(r){const s=g(r);if(!s||!s.host)return;const h=`${s.scheme}://${s.host}:${s.port}`,c=e(),o=t.get(h);if(o){o.count+=1,o.lastAt=c;return}t.set(h,{host:s.host,port:s.port,scheme:s.scheme,local:u(s.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,s)=>r.local===s.local?s.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function x(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let s=t;r.setGate=c=>{s=c},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(o,p){let a=null;try{a=g(o),r.record(o)}catch{}if(s&&a?.host){let i=!0;try{i=s(`${a.scheme}://${a.host}:${a.port}`,{local:u(a.host)})}catch{i=!0}if(!i){const n=`${a.host}:${a.port}`;r.blocked.includes(n)||r.blocked.push(n);const l=new Error(`egress to ${a.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",Promise.reject(l)}}return h.call(this,o,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function $(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function k(e={},t=process.env){const r=[],s=(a,i,{when:n="always",off:l=null,local:m=!1,data:b=""}={})=>{a&&r.push({host:a,purpose:i,when:n,off:l,local:m,data:b})};s("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),s("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),s("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),s("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let a=h;try{a=new URL(h).host}catch{}s(a,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(a)})}if(e.search?.provider!=="searxng"&&(s("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),s("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let a=e.read.remote.url;try{a=new URL(e.read.remote.url).host}catch{}s(a,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(a)})}const c={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[a,i]of Object.entries(c)){const n=e.capabilities?.[a];if(!n?.url||n.provider==="embedded")continue;let l=n.url;try{l=new URL(n.url).host}catch{}s(l,`${i.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${a}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${a} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(l)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(s("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),s("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[a,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&s(d(i.baseUrl),`model upstream "${a}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a}`,off:`upstreams.${a}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const a of e.destinations||[])a?.baseUrl&&s(d(a.baseUrl),`destination "${a.id||a.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${a.id||"it"}`,off:"destinations[]",local:u(d(a.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});s("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&s(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const o=e.tts||{};if(o.provider==="openai"||o.provider==="elevenlabs"){const a=o.remote?.baseUrl?d(o.remote.baseUrl):o.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";s(a,`remote read-aloud voice (${o.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:o.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return s(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function L(e,{ledger:t=$(),version:r="",startedAt:s=null,env:h=process.env,managed:c=null}={}){return{ok:!0,version:r,since:s?new Date(s).toISOString():null,...c?{managed:c,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:k(e,h)}}function S(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,s])=>s===!0?r:`${r}=${s}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
- `)}export{v as createEgressLedger,k as declaredEgress,L as egressAudit,$ as egressLedger,S as formatAudit,x as installEgressLedger};
1
+ import{isBlockedHost as f}from"@chatpanel/pii";const y=()=>new Date().toISOString();function g(e){try{const t=typeof e=="string"?new URL(e):e instanceof URL?e:new URL(e?.url);return{host:t.hostname,port:t.port||(t.protocol==="https:"?"443":t.protocol==="http:"?"80":""),scheme:t.protocol.replace(":","")}}catch{return null}}const u=e=>{const t=String(e||"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="[::1]"?!0:f(t,{allowLoopback:!1,allowPrivate:!1})&&!f(t,{allowLoopback:!0,allowPrivate:!0})};function v({clock:e=y}={}){const t=new Map;return{record(r){const a=g(r);if(!a||!a.host)return;const h=`${a.scheme}://${a.host}:${a.port}`,c=e(),s=t.get(h);if(s){s.count+=1,s.lastAt=c;return}t.set(h,{host:a.host,port:a.port,scheme:a.scheme,local:u(a.host),count:1,firstAt:c,lastAt:c})},snapshot(){return[...t.values()].sort((r,a)=>r.local===a.local?a.count-r.count:r.local?1:-1)},reset(){t.clear()}}}let w=null;function L(e=globalThis,{allow:t=null}={}){if(e.__chatpanelEgress)return t&&e.__chatpanelEgress.setGate(t),e.__chatpanelEgress;const r=v();let a=t;r.setGate=c=>{a=c},r.blocked=[];const h=e.fetch;return typeof h=="function"&&(e.fetch=function(s,p){let o=null;try{o=g(s),r.record(s)}catch{}if(a&&o?.host){let i=!0;try{i=a(`${o.scheme}://${o.host}:${o.port}`,{local:u(o.host)})}catch{i=!0}if(!i){const n=`${o.host}:${o.port}`;r.blocked.includes(n)||r.blocked.push(n);const l=new Error(`egress to ${o.host} is blocked by your organisation’s policy`);return l.code="EGRESS_POLICY",Promise.reject(l)}}return h.call(this,s,p)}),e.__chatpanelEgress=r,e===globalThis&&(w=r),r}function $(){return w||(globalThis.__chatpanelEgress??null)}function d(e){try{return new URL(e).host}catch{return String(e||"")}}function k(e={},t=process.env){const r=[],a=(o,i,{when:n="always",off:l=null,local:m=!1,data:b=""}={})=>{o&&r.push({host:o,purpose:i,when:n,off:l,local:m,data:b})};a("api.chatpanel.net","Pro entitlement: issues and refreshes the signed licence token",{when:"when a Pro token is present (pro.entitlementToken)",off:"free tier — no token, no call",data:"the install id and the current token; never chat content"}),a("dl.chatpanel.net","model weights (NER, dictation, read-aloud) and the installer",{when:"first use of a local model, or an update",off:"ner.enabled / stt.enabled / tts.enabled = false",data:"the model id being downloaded"}),a("huggingface.co","model weights when dl.chatpanel.net does not carry the model",{when:"a custom model id, or a mirror miss",off:"the same switches as dl.chatpanel.net",data:"the model id being downloaded"}),t.CHATPANEL_ORT_DIR||a("registry.npmjs.org","the native ONNX runtime the standalone binary loads, fetched once",{when:"first start of a binary install that has no native runtime yet; never on npm/Node",off:"CHATPANEL_ORT_DIR=<dir> — point it at a copy you placed yourself, and nothing is fetched",data:"nothing — a versioned package tarball"}),a("the page you ask to read","web retrieval: POST /v1/read fetches ONE public page as Markdown, on request",{when:"a client calls /v1/read (the extension’s reader slot, the desktop, the CLI)",off:"nothing to switch off — no read happens unless a client asks for that page",data:"a GET of that page with a browser User-Agent; never a cookie, never a token, never chat content"});const h=e.search?.searxng?.url||"";if(h){let o=h;try{o=new URL(h).host}catch{}a(o,"web search: your SearXNG (POST /v1/search) — the query, after layer-1 redaction",{when:"a client searches and search.provider is auto (SearXNG up) or searxng",off:'search.searxng.url = ""',data:"the search query with emails, cards, keys and dictionary terms removed; never chat content",local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(o)})}if(e.search?.provider!=="searxng"&&(a("www.startpage.com","web search: the built-in results-page search, first engine",{when:"a client searches and no SearXNG answers (search.provider auto) or search.provider is serp",off:'search.provider = "searxng" with a SearXNG configured',data:"the search query with emails, cards, keys and dictionary terms removed"}),a("html.duckduckgo.com","web search: the built-in results-page search, fallback engine",{when:"Startpage returned nothing",off:"the same switch as www.startpage.com",data:"the same query"})),e.read?.remote?.url){let o=e.read.remote.url;try{o=new URL(e.read.remote.url).host}catch{}a(o,"web retrieval: the remote reader (r.jina.ai-shaped) for pages a fetch cannot render",{when:'a read names provider "remote", or read.provider is "remote"',off:'read.remote.url = ""',data:"the URL of the page being read; the key you configured",local:/^(localhost|127\.|\[::1\])/.test(o)})}const c={rerank:{what:"ranking: POST /v1/rerank — the query and the candidate texts",data:"the query and the documents to order; layer-1 redaction is the client’s duty before they reach here; never chat history"},decide:{what:"decisions: POST /v1/decide — the text judged and the typed questions",data:"the state text and the questions; never chat history"},stt:{what:"transcription: every committed segment of audio, as a WAV, to POST /audio/transcriptions",data:"the audio itself — what was said, by whom; the text that comes back is what the redaction hop sees"},embed:{what:"embeddings: POST /v1/embeddings — the text being indexed or searched",data:"the text embedded — notes, chats, meetings when semantic search indexes them; the query when it searches"}};for(const[o,i]of Object.entries(c)){const n=e.capabilities?.[o];if(!n?.url||n.provider==="embedded")continue;let l=n.url;try{l=new URL(n.url).host}catch{}a(l,`${i.what}${n.service?` (the ${n.service} container, started under Settings › Runtime)`:` (${n.adapter} at the address you configured)`}`,{when:`a client calls /v1/${o}`,off:n.service?`stop the ${n.service} service under Settings › Runtime`:`capabilities.${o} = null`,data:`${i.data}${n.token?"; the token you configured":""}`,local:/^(localhost|127\.|\[::1\]|10\.|192\.168\.)/.test(l)})}t.CHATPANEL_SELF_UPDATE!=="off"&&(a("registry.npmjs.org","update check: is a newer gateway published?",{when:"on /status, throttled; npm installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the package manifest"}),a("api.github.com","update check for the standalone binary",{when:"on /status, throttled; binary installs only",off:"CHATPANEL_SELF_UPDATE=off",data:"nothing — a read of the latest release"}));for(const[o,i]of Object.entries(e.upstreams||{}))i?.baseUrl&&a(d(i.baseUrl),`model upstream "${o}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o}`,off:`upstreams.${o}.baseUrl`,local:u(d(i.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});for(const o of e.destinations||[])o?.baseUrl&&a(d(o.baseUrl),`destination "${o.id||o.type}" — chat requests (after redaction) go here`,{when:`a request addressed to ${o.id||"it"}`,off:"destinations[]",local:u(d(o.baseUrl).split(":")[0]),data:"the conversation, with PII replaced by placeholders when redaction is on"});a("(the endpoint the client passes through)","a client can address any endpoint per request (BYO); the gateway proxies to it after redaction",{when:"the extension or desktop sends a request with its own endpoint",off:"the client’s own endpoint settings",data:"the conversation, with PII replaced by placeholders when redaction is on"}),e.ner?.url&&a(d(e.ner.url),"external NER detector (redaction) — a sidecar you configured",{when:"every redacted request",off:"ner.url",local:u(d(e.ner.url).split(":")[0]),data:"the text being redacted"});const s=e.tts||{};if(s.provider==="openai"||s.provider==="elevenlabs"){const o=s.remote?.baseUrl?d(s.remote.baseUrl):s.provider==="elevenlabs"?"api.elevenlabs.io":"api.openai.com";a(o,`remote read-aloud voice (${s.provider})`,{when:"a read-aloud request",off:"tts.provider = local",data:s.remote?.redact===!1?"the text being spoken, unredacted (tts.remote.redact = false)":"the text being spoken, with PII replaced by placeholders"})}const p=e.bridge?.url||"http://127.0.0.1:4319";return a(d(p),"the local bridge — your CLI agents (Claude Code, Codex, …)",{when:"a request addressed to an agent",off:"bridge.url",local:!0,data:"the conversation; the agent then reaches its own vendor with your own login"}),r}function x(e,{ledger:t=$(),version:r="",startedAt:a=null,env:h=process.env,managed:c=null}={}){return{ok:!0,version:r,since:a?new Date(a).toISOString():null,...c?{managed:c,blocked:t?.blocked||[]}:{},scope:"this gateway process’s own outbound requests. Not covered: the embedded bridge (a separate process), the CLI agents it runs (they reach their vendors with your logins), and a client’s direct calls that bypass the gateway.",observed:t?t.snapshot():[],declared:k(e,h)}}function S(e){const t=[];t.push(`ChatPanel Gateway ${e.version||""} — egress audit`.trim()),e.since&&t.push(`observed since ${e.since}`),t.push(""),t.push("OBSERVED — hosts this process has actually contacted"),e.observed?.length||t.push(" (none yet)");for(const r of e.observed||[])t.push(` ${r.local?"[local] ":""}${r.scheme}://${r.host}:${r.port} ×${r.count} last ${r.lastAt}`);t.push(""),t.push("DECLARED — hosts this configuration allows, and why");for(const r of e.declared||[])t.push(` ${r.local?"[local] ":""}${r.host}`),t.push(` ${r.purpose}`),t.push(` when: ${r.when}${r.off?` · off: ${r.off}`:""}`),r.data&&t.push(` sends: ${r.data}`);return e.managed&&(t.push(""),t.push(`POLICY — ${e.managed.name||e.managed.org||"managed"} (${e.managed.signed?"signed":"unsigned file"}, hash ${String(e.managed.policyHash||"").slice(0,12)}…)`),t.push(` enforcing: ${Object.entries(e.managed.enforces||{}).filter(([,r])=>r).map(([r,a])=>a===!0?r:`${r}=${a}`).join(", ")||"nothing yet"}`),t.push(` refused this session: ${e.blocked?.length?e.blocked.join(", "):"none"}`)),t.push(""),t.push(`Scope: ${e.scope}`),t.push("Verify it yourself: any hostname not listed above that appears in your firewall or proxy log for this process is a bug — report it (security@chatpanel.net)."),t.join(`
2
+ `)}export{v as createEgressLedger,k as declaredEgress,x as egressAudit,$ as egressLedger,S as formatAudit,L as installEgressLedger};
package/src/mcp-ask.js ADDED
@@ -0,0 +1,18 @@
1
+ import{minReach as b}from"@chatpanel/pii";const w=Math.max(0,Math.min(8,Number(process.env.CHATPANEL_ASK_DEPTH)||0)),R=1;function _(){return w<R}function z(e){if(!_())return[];const t=$(e?.delegate).length>0;return x.filter(n=>n.name!=="delegate_task"||t)}const v=1e5,D=9e4,j=6e5,N=32,S=Object.freeze({device:"on this device — nothing left the machine",trusted:"on your private network — did not leave it",any:"a cloud provider — this text left the machine (redacted first)"}),q=e=>S[e]||"destination unknown — assume it left the machine";function $(e){return(Array.isArray(e?.roots)?e.roots:[]).map(n=>String(n||"").trim()).filter(n=>/^([A-Za-z]:[\\/]|\/)/.test(n))}const I=["default","acceptEdits","bypassPermissions"];function U(e){const t=e?.permissionMode;return I.includes(t)?t:"acceptEdits"}function H(e,t){if(!t.length)return null;if(!e)return t[0];const n=i=>{const r=String(i).replace(/\\/g,"/").split("/"),l=[];for(const o of r)o==="."||o===""||(o===".."?l.pop():l.push(o));return(String(i).startsWith("/")?"/":"")+l.join("/")},a=n(e);for(const i of t){const r=n(i);if(a===r||a.startsWith(r.endsWith("/")?r:`${r}/`))return a}return null}const x=[{name:"list_models",description:"The models this machine can answer with, and WHERE each one runs. Call it before ask_model when the choice matters — picking by reach is how you keep sensitive text on the box: `device` never leaves it, `any` is a cloud provider. Rows include the user's signed-in coding agents (Claude Code, Codex, …), any local engine that is running (Ollama, vLLM, llama.cpp), and any API destination they configured. Only models that can actually answer right now are listed.",inputSchema:{type:"object",properties:{reach:{type:"string",enum:["device","trusted","any"],description:"Only models at most this far away. `device` = on this machine only."}}}},{name:"ask_model",description:'Ask ANOTHER model a question and get its answer back as text — a second opinion from a different model than the one you are, without the user leaving their editor. Good for: a check on your own reasoning, a domain where another model is stronger, a question the user explicitly wants a named model to answer ("ask Claude what it thinks"), or work the user would rather keep on-device. The sub-model answers from the prompt ALONE: it has no filesystem, shell, web or tool access, so include everything it needs in `prompt` and never assume it can see the repo. Slow calls do not fail — if it is still thinking after `wait` seconds you get a job id to poll with ask_status. Every answer states which model produced it and whether the text left the machine.',inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The full question, self-contained. Paste in any code or context the model needs — it can see nothing else."},model:{type:"string",description:`A model id from list_models (e.g. "claude", "codex", "opencode/llama3.1", "gpt-4o"). Omit for the gateway's default.`},system:{type:"string",description:'Optional system prompt — the role or output shape you want ("Answer only with the corrected SQL").'},reach:{type:"string",enum:["device","trusted","any"],description:"How much the sub-model may reach. Default and recommended is `device`: it answers from the prompt only. The user's configured ceiling applies — asking for more than they allow is capped, not refused."},wait:{type:"number",description:"Seconds to wait before handing back a job id instead (default 90, max 600). Pass 0 to get the id immediately and poll with ask_status while you carry on with your own work. The work continues either way."}},required:["prompt"]}},{name:"delegate_task",description:"Hand a whole PIECE OF WORK to one of the user's coding agents — Claude Code, Codex, OpenCode — running on this machine with its own tools, in a real directory. Unlike ask_model (which gets you an answer from a blind model), the agent here reads and edits real files and reports what it did — how much it may do is the USER's setting, and the result says which was in force, so if it reports being unable to write, that is their configuration and not something to work around. Use it to delegate work that belongs on this machine rather than in your own context: a refactor across files you would have to read one by one, a test suite to run and fix, a build to diagnose, a codebase to survey. It runs under the permissions the USER configured for that agent, in the directory they allow. Expect minutes, not seconds — it returns a job id you collect with ask_status.",inputSchema:{type:"object",properties:{task:{type:"string",description:"What to do, as you would brief a competent colleague: the goal, the constraints, how to tell it worked. The agent can read the directory, so describe the outcome rather than pasting the files."},agent:{type:"string",description:`Which agent (from list_models — "claude", "codex", "opencode"). Omit for the user's default.`},workingDir:{type:"string",description:"Absolute path to work in. Must be inside a directory the user allowed; omit to use the one they configured."},wait:{type:"number",description:"Seconds to wait before handing back a job id (default 90, max 600). Pass 0 to get the id at once and poll."}},required:["task"]}},{name:"ask_status",description:"Collect the answer to an ask_model call that was still running when it handed you a job id. Returns the answer if it has finished, or how long it has been going if not — poll it every 15-30 seconds rather than in a tight loop.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The job id ask_model returned."}},required:["id"]}}],u=new Map;let T=0;function V(){u.clear(),T=0}function A(e){if(u.size>=N){const a=[...u.values()].filter(i=>i.state!=="running").sort((i,r)=>i.started-r.started)[0];a?u.delete(a.id):u.delete([...u.keys()][0])}const t=`ask_${++T}`,n={id:t,model:e,started:Date.now(),state:"running",text:"",error:"",reach:"",redacted:0};return u.set(t,n),n}const y=e=>`${(e/1e3).toFixed(1)}s`,C=e=>`Call ask_status with job id "${e.id}" in 15-30 seconds to collect the result. The work continues in the background whether or not you poll.`;function P(e){const t=e.wait==null||e.wait===""?null:Number(e.wait);return Number.isFinite(t)?Math.min(j,Math.max(0,t*1e3)):D}async function E(e,t){if(t===0)return!1;let n;const a=Symbol("expired"),i=await Promise.race([e.then(()=>"settled"),new Promise(r=>{n=setTimeout(()=>r(a),t)})]);return clearTimeout(n),i!==a}function k(e){const t=[`${e.delegated?"done by":"answered by"} ${e.model}`];return e.delegated?t.push(`working in ${e.workingDir}`,e.mode==="bypassPermissions"?"full access":e.mode==="acceptEdits"?"may edit files, not run shell":"read-only"):t.push(q(e.reach)),e.redacted>0&&t.push(`${e.redacted} value${e.redacted===1?"":"s"} redacted before it was sent`),t.push(y(Date.now()-e.started)),`${e.text}
2
+
3
+ — ${t.join(" · ")}`}async function O({baseUrl:e,token:t,client:n,prompt:a,model:i,system:r,reach:l,workingDir:o,permissionMode:d,signal:c}){const m=[];r&&m.push({role:"system",content:r}),m.push({role:"user",content:a});const s=await fetch(`${e}/v1/chat/completions`,{method:"POST",signal:c,headers:{"content-type":"application/json",...t?{Authorization:`Bearer ${t}`}:{},"X-ChatPanel-Reach":l,"X-ChatPanel-Ask-Depth":String(w+1),"X-ChatPanel-Client":n||"unknown",...o?{"X-ChatPanel-Run":encodeURIComponent(JSON.stringify({workingDir:o,...d?{permissionMode:d}:{}}))}:{}},body:JSON.stringify({model:i,messages:m,stream:!1})}),h=await s.json().catch(()=>({}));if(!s.ok){const g=String(h?.error?.message||h?.error||`HTTP ${s.status}`),f=new Error(g);throw f.type=h?.error?.type||"",f.status=s.status,f}const p=h?.choices?.[0]?.message?.content;return{text:(typeof p=="string"?p:Array.isArray(p)?p.map(g=>typeof g=="string"?g:g?.text||"").join(""):"").trim(),redacted:Number(s.headers?.get?.("x-chatpanel-redacted"))||0,reach:s.headers?.get?.("x-chatpanel-reach-used")||""}}function M(e,t,n,a){return/may only run the Claude engine/i.test(n)?`"${e}" cannot run under the ${t} ceiling — Claude Code is the only agent that turns a reach tier into a tool policy, so capping the others would be a promise this gateway could not keep.
4
+
5
+ Either ask "claude" instead, or, if you genuinely want ${e} running with its own configured permissions, the user must raise the ceiling: set mcp.ask.maxReach to "any" in ~/.chatpanel/gateway.config.json. That is their decision, not yours — do not ask them to do it just to get past this message.`:a==="policy"?`Refused by the organisation's policy: ${n}`:a==="auth"||/token/i.test(n)?`The gateway refused the agent lane: ${n}
6
+
7
+ This usually means this MCP server cannot read ~/.chatpanel/gateway-token — check it is running as the same user as the gateway.`:/not signed in|\/login|sign in/i.test(n)?`${e} is installed but not signed in: ${n}`:`${e} could not answer: ${n}`}async function B(e,t={},n={}){return x.some(a=>a.name===e)?_()?e==="list_models"?L(t,n):e==="ask_status"?X(t):e==="delegate_task"?W(t,n):F(t,n):`ask_model is not available inside an ask_model call (depth ${w}) — you are already the model being asked. Answer the question yourself.`:null}async function W(e,t){const n=String(e.task||"").trim();if(!n)return"delegate_task needs `task` — what the agent should do, briefed as you would brief a colleague.";const a=t.askConfig?.()||{},i=$(a.delegate);if(!i.length)return`Delegation is not enabled on this machine. The user has not named a directory an agent may work in, so ChatPanel will not start one on behalf of an MCP client.
8
+
9
+ Only they can change that, by setting mcp.delegate.roots in ~/.chatpanel/gateway.config.json to the project directories they are happy for a delegated agent to work in. Use ask_model instead for anything that is really a question.`;const r=H(String(e.workingDir||"").trim(),i);if(!r)return`"${e.workingDir}" is outside every directory the user allows a delegated agent to work in.
10
+
11
+ Allowed: ${i.join(", ")}. Pass a path inside one of those, or omit workingDir to use the first.`;const l=String(e.agent||a.defaultModel||"").trim()||void 0,o=A(l||"the default agent");o.reach="any",o.delegated=!0,o.workingDir=r;const d=U(a.delegate);o.mode=d;const c=O({baseUrl:t.baseUrl(),token:t.token(),client:t.client(),prompt:n,model:l,system:"",reach:"any",workingDir:r,permissionMode:d}).then(s=>(o.state="done",o.text=s.text||"(the agent finished without a closing message — check the directory for what changed)",o.redacted=s.redacted,s)).catch(s=>(o.state="error",o.error=M(o.model,"any",s.message,s.type),null));return await E(c,P(e))?o.state==="error"?`Error: ${o.error}`:k(o):`${o.model} has started work in ${r}.
12
+
13
+ A real task takes minutes: it is reading files, running commands and editing as it goes. ${C(o)}
14
+
15
+ Tell the user what you delegated and where — they should know an agent is working in their directory.`}async function L(e,t){const n=await t.gatewayJson("/v1/models"),a=String(e.reach||"").trim();let i=(n?.data||[]).filter(d=>d.available!==!1);if(a&&(i=i.filter(d=>b(d.reach||"any",a)===(d.reach||"any"))),!i.length)return a?`No model on this machine runs at reach "${a}" (or none is available right now). Call list_models with no filter to see everything, or ask the user to start a local engine: ChatPanel › Settings › Runtime.`:"No models are available. The user has no coding agent signed in, no local engine running and no API destination configured — ChatPanel › Settings › Models is where they add one.";const r=[["device","ON THIS DEVICE — nothing leaves the machine"],["trusted","ON YOUR PRIVATE NETWORK"],["any","A CLOUD PROVIDER — text leaves the machine (redacted first)"]],l=[`${i.length} model(s) this gateway can answer with:`];for(const[d,c]of r){const m=i.filter(s=>(s.reach||"any")===d);if(m.length){l.push("",c);for(const s of m){const h=[];s.owned_by==="chatpanel-bridge"&&h.push("coding agent"),s.context_window&&h.push(`${Math.round(s.context_window/1e3)}k context`),l.push(` ${s.id}${h.length?` · ${h.join(" · ")}`:""}`)}}}const o=i.filter(d=>!S[d.reach||"any"]);return o.length&&l.push("",`Reach unknown (assume the text leaves the machine): ${o.map(d=>d.id).join(", ")}`),l.push("","ask_model with one of these ids. The sub-model answers from your prompt alone — it cannot see files, the web or your tools."),l.join(`
16
+ `)}function X(e){const t=String(e.id||"").trim(),n=u.get(t);if(!n)return`No ask job "${t}". Either it was never started, or this MCP session restarted since — ids do not survive a reconnect. Call ask_model again.`;if(n.state==="done")return k(n);if(n.state==="error")return`Error: ${n.error}`;const a=Date.now()-n.started;return`Still running — ${n.model} has been working for ${y(a)}. Poll ask_status again in 15-30 seconds; a coding agent on a hard question can take several minutes. The work continues whether or not you poll.`}async function F(e,t){const n=String(e.prompt||"").trim();if(!n)return"ask_model needs `prompt` — the full, self-contained question for the other model.";if(n.length>v)return`That prompt is ${n.length} characters; the cap is ${v}. Send the part the model actually needs — it has no way to fetch the rest, but a shorter question is usually a better one anyway.`;const a=t.askConfig?.()||{},i=a.maxReach||"device",r=b(String(e.reach||i),i),l=String(e.model||a.defaultModel||"").trim()||void 0,o=A(l||"the gateway default");o.reach=r;const d=O({baseUrl:t.baseUrl(),token:t.token(),client:t.client(),prompt:n,model:l,system:String(e.system||"").trim(),reach:r}).then(c=>(o.state="done",o.text=c.text||"(the model returned an empty answer)",o.redacted=c.redacted,c.reach&&(o.reach=c.reach),c)).catch(c=>(o.state="error",o.error=M(o.model,r,c.message,c.type),null));return await E(d,P(e))?o.state==="error"?`Error: ${o.error}`:k(o):`${o.model} is still working (${y(Date.now()-o.started)} so far) — this is normal for a coding agent on a hard question.
17
+
18
+ ${C(o)}`}export{w as ASK_DEPTH,x as ASK_TOOLS,R as MAX_ASK_DEPTH,_ as askAvailable,z as askToolsFor,B as callAsk,U as delegateMode,$ as delegateRoots,V as resetAskJobs,H as resolveWorkingDir};
@@ -0,0 +1,10 @@
1
+ const u=[{name:"redact_check",description:"Find the personal and secret data in a piece of text BEFORE it goes anywhere — names, emails, phones, cards, national ids, API keys, IPs — using the detector running on the user's own machine. Call it whenever you are about to put someone else's data into your own context, a commit message, an issue, a PR description or a message to a third party, and whenever the user asks what is sensitive in something. You get back the text with each value replaced by a typed placeholder, a count, and the kinds found — and, honestly, how much of it the local detector could actually see. The text you pass is checked here and not stored.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The text to check. Pass it exactly as it would be sent — a redaction preview of something you have already edited proves nothing."}},required:["text"]}},{name:"read_document",description:"Fetch a web page or document and get it back as clean, readable markdown with its sections — through the user's own reader, so it uses their cache, their rate budget and their network, and the result is the same one ChatPanel itself would work from. Better than fetching raw HTML yourself: the boilerplate, navigation and scripts are gone, so it costs a fraction of the context. Takes a URL only; it cannot open local files.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The http(s) URL to read."},maxChars:{type:"number",description:"Stop after this many characters (default 20000). The result says how much was left."}},required:["url"]}}],p=2e4,l=2e5;async function f(o,r={},t={}){return u.some(n=>n.name===o)?o==="redact_check"?y(r,t):m(r,t):null}async function y(o,r){const t=String(o.text||"");if(!t.trim())return"redact_check needs `text` — the text to check.";if(t.length>l)return`That text is ${t.length} characters; the cap is ${l}. Check the part you are actually about to send.`;const n=await r.gatewayJson("/redact",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:t})}),e=Array.isArray(n.entities)?n.entities:[],s=e.length||Number(n.count)||0,i=[...new Set(e.map(c=>typeof c=="string"?c:c?.type).filter(Boolean))],h=n.detector||{},d=h.coverage!=="names",a=[];return s===0?a.push("No personal or secret values found in that text."):(a.push(`${s} value(s) to redact${i.length?` — ${i.join(", ")}`:""}.`,""),a.push("The text with each one replaced by a typed placeholder:","",n.text||"")),d&&a.push("",`CAUTION — this was a ${n.tier||"basic"}-tier pass and the local entity detector is ${h.state||"not running"}, so PATTERNS (emails, phone numbers, card numbers, keys) were checked but NAMES and ORGANISATIONS were not. Treat "no findings" as "no patterns found", not as "nothing personal here", and say so if you report this to the user.`),a.push("","The placeholders are stable within one text, so `[[PERSON_1]]` is the same person throughout. ChatPanel restores them automatically on its own model calls; if you send this text yourself, it stays redacted."),a.join(`
2
+ `)}async function m(o,r){const t=String(o.url||"").trim();if(!t)return"read_document needs `url`.";if(!/^https?:\/\//i.test(t))return`read_document takes an http(s) URL, and "${t}" is not one. It cannot open local files — if you need a file on this machine, read it with your own tools, or delegate the work with delegate_task if that is enabled.`;const n=Math.max(500,Math.min(l,Number(o.maxChars)||p)),e=await r.gatewayJson("/v1/read",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({url:t,format:"markdown"})}),s=String(e.markdown??e.text??"");if(e.restricted&&!s)return`${t} could not be read: ${e.restricted.reason||e.restricted}. The site refused the fetch — a paywall, a bot check or a robots rule.`;const i=s.slice(0,n),h=[`${e.title||"(untitled)"} — ${e.site||t}`,e.cached?"from the local cache":"fetched now"].join(" · "),d=s.length>i.length?`
3
+
4
+ [showing ${i.length} of ${e.chars??s.length} characters. Raise maxChars for more, or use the section headings above to decide whether you need it.]`:e.truncated?`
5
+
6
+ [the reader truncated this page — it is longer than what is shown.]`:"",a=Array.isArray(e.sections)&&e.sections.length?`
7
+
8
+ Sections: ${e.sections.slice(0,20).map(c=>c.title||c.heading).filter(Boolean).join(" · ")}`:"";return`${h}${a}
9
+
10
+ ${i||"(the page had no readable text)"}${d}`}export{u as CAPABILITY_TOOLS,f as callCapability};