@chatpanel/gateway 0.39.11 → 0.44.3
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 +171 -12
- package/bin/chatpanel-gateway.js +4 -4
- package/package.json +3 -3
- package/src/config.js +1 -1
- package/src/configstore.js +1 -1
- package/src/connect-agents.js +10 -10
- package/src/mcp-ask.js +18 -0
- package/src/mcp-capabilities.js +10 -0
- package/src/mcp.js +28 -20
- package/src/recruiting.js +1 -1
- package/src/retrieval/search.js +1 -1
- package/src/router.js +1 -1
- package/src/server.js +14 -14
- package/src/version.js +1 -0
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
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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
|
-
| `
|
|
319
|
-
| `
|
|
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
|
-
| `
|
|
322
|
-
| `
|
|
323
|
-
| `
|
|
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
|
|
package/bin/chatpanel-gateway.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
const
|
|
3
|
-
`)}process.argv.includes("--json")?console.log(JSON.stringify(
|
|
2
|
+
const o=process.argv[2],u={"--bridge":"chatpanel-bridge","--mcp-stdio":"chatpanel-bridge-mcp",mcp:"chatpanel-history-mcp","--extract-worker":"chatpanel-extract"};try{process.title=u[o]||"chatpanel-gateway"}catch{}try{if(o==="--extract-worker"){process.env.CHATPANEL_EXTRACT_WORKER_IMPORTED="1";const{runExtractWorker:e}=await import("../src/extract/worker.js");e()}else if(o==="--bridge")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",process.argv.splice(2,1),await import("@chatpanel/bridge/src/server.js");else if(o==="--mcp-stdio")process.env.CHATPANEL_BRIDGE_EMBEDDED="1",await import("@chatpanel/bridge/src/server.js");else if(o==="mcp"){const{runMcpServer:e}=await import("../src/mcp.js");await e()}else if(o==="tools"||o==="call"){const{runMcpCli:e}=await import("../src/mcp-cli.js");process.exit(await e(process.argv.slice(2)))}else if(o==="policy"){const{loadPolicy:e,formatPolicy:s,PolicyLoadError:i}=await import("../src/policy.js");try{const r=await e();process.argv.includes("--json")?console.log(JSON.stringify(r?{...r,label:void 0}:null,null,2)):console.log(s(r))}catch(r){throw r instanceof i&&(console.error(`org policy: ${r.message}`),process.exit(78)),r}}else if(o==="--audit"){const{egressAudit:e,formatAudit:s}=await import("../src/egress.js"),{loadConfig:i}=await import("../src/config.js"),{readFileSync:r}=await import("node:fs"),{join:h}=await import("node:path"),l=await import("node:os"),c=i(),t=`http://127.0.0.1:${c.port||4320}`;let a=null,n=`no gateway running at ${t}`;try{const g=r(process.env.CHATPANEL_GATEWAY_TOKEN_PATH||h(l.homedir(),".chatpanel","gateway-token"),"utf8").trim(),p=await fetch(`${t}/audit`,{headers:{authorization:`Bearer ${g}`},signal:AbortSignal.timeout(2500)});if(p.ok)a=await p.json();else if(p.status===404){const d=await fetch(`${t}/health`,{signal:AbortSignal.timeout(2500)}).then(w=>w.json()).catch(()=>null);n=`the gateway running at ${t}${d?.version?` (${d.version})`:""} predates --audit (0.7.0) — restart it after updating`}else n=`the gateway at ${t} refused the audit (HTTP ${p.status}) — is ~/.chatpanel/gateway-token readable?`}catch{}if(!a){const{VERSION:g}=await import("../src/server.js");a={...e(c,{ledger:null,version:g}),observed:[]},console.log(`(${n}; showing what the current config allows)
|
|
3
|
+
`)}process.argv.includes("--json")?console.log(JSON.stringify(a,null,2)):console.log(s(a))}else if(o==="sandbox"){const{srtModuleUrl:e}=await import("../src/worker-sandbox.js");!process.env.CHATPANEL_SRT_MODULE&&e()&&(process.env.CHATPANEL_SRT_MODULE=e());const{runSandboxCli:s}=await import("@chatpanel/bridge/src/sandbox.js");process.exit(await s(process.argv.slice(3)))}else if(o==="pair"){const{loadConfig:e}=await import("../src/config.js"),{readFileSync:s}=await import("node:fs"),{join:i}=await import("node:path"),r=await import("node:os"),l=`http://127.0.0.1:${e().port||4320}`,c=process.env.CHATPANEL_GATEWAY_TOKEN_PATH||i(r.homedir(),".chatpanel","gateway-token");try{const t=s(c,"utf8").trim(),a=await fetch(`${l}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),n=await a.json().catch(()=>({}));if(a.status===404)throw new Error(`the gateway at ${l} predates pairing (0.9.0) — update and restart it`);if(!a.ok)throw new Error(n.error||`HTTP ${a.status}`);console.log(`Pairing code: ${n.display||n.code} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Agent Tools → "Pairing code".')}catch(t){console.error(`could not get a pairing code from the gateway at ${l}: ${t?.message||t}${/ENOENT/.test(String(t?.message))?` (no token at ${c} — has the gateway started once?)`:""}`),process.exit(1)}}else if(o==="local"){const{localStatus:e,formatLocalStatus:s}=await import("../src/local-status.js");process.stdout.write(s(await e()))}else if(o==="connect"){const{connectAgents:e,formatConnect:s}=await import("../src/connect-agents.js"),i=process.argv.includes("--dry-run")||process.argv.includes("-n");process.stdout.write(s(e({dryRun:i}),{dryRun:i}))}else{const{start:e,VERSION:s}=await import("../src/server.js"),{installService:i,uninstallService:r,serviceReport:h,stopService:l,pathWithDir:c}=await import("../src/service.js");switch(o){case"--stop":l(),console.log("ChatPanel Gateway: stopped (auto-start is still registered; `--install` or a login starts it again).");break;case"--version":case"-v":console.log(s);break;case"--install":{const t=await i(),a=t.health;if(a.ok){const n=a.managedBy&&a.managedBy!=="gateway"?` — the ${a.managedBy} app's gateway is the one answering right now; this install takes over at the next login`:"";console.log(`ChatPanel Privacy Gateway v${a.version}: running at ${a.url}, starts at login${t.wsl?" (Windows login, through wsl.exe)":""}${n}.`)}else console.error(`ChatPanel Privacy Gateway: login auto-start is registered, but nothing answered at ${a.url} after 40 s.`),t.errLog&&console.error(` last of the error log:
|
|
4
4
|
${t.errLog.split(`
|
|
5
|
-
`).map(
|
|
6
|
-
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");try{const{pruneForeignPrebuilds:
|
|
5
|
+
`).map(n=>` ${n}`).join(`
|
|
6
|
+
`)}`),console.error(" `chatpanel-gateway --status` shows what is registered; running `chatpanel-gateway` in a terminal shows the start-up itself.");try{const{pruneForeignPrebuilds:n,pruneLine:g}=await import("../src/prune-install.js"),p=g(n({log:d=>console.error(d)}));p&&console.log(p)}catch{}t.launcher==="powershell"&&console.log(" (VBScript is not installed here, so the login launcher is PowerShell — a console flashes for an instant at login.)"),t.path?.added?console.log(` Added ${t.path.dir} to your PATH — \`chatpanel-gateway\` works in a NEW terminal.`):t.path?.error?console.log(` Could not add ${t.path.dir} to your PATH (${t.path.error}) — add it yourself to run \`chatpanel-gateway\` by name.`):t.path?.dir&&t.wsl&&c(process.env.PATH||"",t.path.dir)!==null&&console.log(` Tip: add it to your PATH -> export PATH="${t.path.dir}:$PATH"`),a.ok||process.exit(1);break}case"--uninstall":r(),console.log("ChatPanel Privacy Gateway: removed login auto-start.");break;case"--status":console.log(await h());break;case void 0:await e();break;default:console.error(`unknown option: ${o}
|
|
7
7
|
Usage: chatpanel-gateway [mcp|tools list|tools schema <tool>|call <tool> '<json>'|local|connect|pair|policy|--audit|--install|--uninstall|--stop|--status|--version|--bridge]`),process.exit(2)}}}catch(e){console.error(`error: ${e.message}`),process.exit(1)}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/gateway",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.44.3",
|
|
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.
|
|
26
|
-
"@chatpanel/events": "^0.
|
|
25
|
+
"@chatpanel/bridge": "^0.21.0",
|
|
26
|
+
"@chatpanel/events": "^0.190.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
|
|
1
|
+
import{readFileSync as n,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},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: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(n(i,"utf8")))}catch(s){throw new Error(`bad config file ${i}: ${s.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};
|
package/src/configstore.js
CHANGED
|
@@ -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{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,mcp:e.mcp};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};
|
package/src/connect-agents.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync as f,writeFileSync as g,existsSync as c,copyFileSync as v,mkdirSync as
|
|
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(
|
|
12
|
-
${i}`),{id:"codex",status:"configured",path:n,backup:
|
|
13
|
-
`),{id:"gemini",status:"configured",path:n,backup:
|
|
14
|
-
"mcp": { "chatpanel": { "type": "local", "command": [${JSON.stringify(t)}, "mcp"], "enabled": true } }`)),e.push(l("copilot",c(u(
|
|
15
|
-
${(
|
|
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
|
-
`)}`):
|
|
18
|
-
${
|
|
17
|
+
`)}`):s.status==="manual"?e.push(`${d} — add it yourself:
|
|
18
|
+
${s.snippet.split(`
|
|
19
19
|
`).join(`
|
|
20
|
-
`)}`):
|
|
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/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};
|