@chatpanel/gateway 0.40.0 → 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/package.json +2 -2
- 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/retrieval/search.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/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,7 +22,7 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@anthropic-ai/sandbox-runtime": "^0.0.77",
|
|
25
|
-
"@chatpanel/bridge": "^0.
|
|
25
|
+
"@chatpanel/bridge": "^0.21.0",
|
|
26
26
|
"@chatpanel/events": "^0.190.0",
|
|
27
27
|
"@chatpanel/pii": "^0.11.0",
|
|
28
28
|
"@huggingface/transformers": "^4.2.0",
|
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};
|
package/src/mcp.js
CHANGED
|
@@ -1,34 +1,42 @@
|
|
|
1
|
-
import{loadConfig as
|
|
2
|
-
`);let u="unknown";function $(n){try{const e=S();fetch(`${p()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function p(){const n=process.env.CHATPANEL_GATEWAY_URL;if(n)return n.replace(/\/+$/,"");let e=4320;try{e=f().port||4320}catch{}return`http://127.0.0.1:${e}`}function v(){try{return String(f().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function M(){try{return b(f().bridge?.token||"")}catch{return b("")}}async function y(n){const e=M(),s=await fetch(v()+n,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),t=await s.json().catch(()=>({}));if(!s.ok||t.ok===!1)throw new Error(t?.error||`bridge ${s.status}`);return t}const D=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:k,description:k.map(n=>`${n}: ${N[n].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],x={[R]:" To have one: ChatPanel › Settings › Runtime › OpenDecision › Start (or a server that provides `decide` under Models).",[q]:" To have one: ChatPanel › Settings › Runtime › Reranker › Start (or a server that provides `rerank` under Models)."};function _(){const n=p(),e=r=>[{id:"gateway",name:"the gateway",url:`${n}${r}`,where:"this device"}],s=j({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(r,o)=>fetch(r,o)}),t=P({search:async r=>{const o=await h("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:r,limit:8,read:E.aliasRead})});return{query:r,engines:o.engines||[],results:(o.results||[]).map((i,a)=>({rank:a+1,title:i.title||i.url,url:i.url,engine:i.engine||"",text:i.read?.markdown||i.read?.text||i.snippet||""}))}}});return[s,t]}const U=_().flatMap(n=>n.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function B(n,e){const s=_().find(o=>o.specs.some(i=>i.name===n));if(!s)return null;const t=await s.execute(n,e);let r=typeof t=="string"?t:String(t?.text??t);return x[n]&&/^No (decision model|reranker) answered/.test(r)&&(r+=x[n]),r}function g(n,e){if(!n)return`Index: ${e} records (warm copy synced from ChatPanel).`;const s=new Date(n),t=`${s.getFullYear()}-${String(s.getMonth()+1).padStart(2,"0")}-${String(s.getDate()).padStart(2,"0")} ${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${t} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function O(){try{const n=S();return n?{Authorization:`Bearer ${n}`}:{}}catch{return{}}}async function h(n,e){let s;try{s=await fetch(p()+n,e)}catch(r){throw new Error(`the ChatPanel gateway is not running at ${p()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${r.message}]`)}const t=await s.json().catch(()=>({}));if(!s.ok)throw new Error(t?.error?.message||`the gateway returned HTTP ${s.status} for ${n}`);return t}function m(n){if(n==null||n==="")return null;if(typeof n=="number")return n;const e=String(n).trim().toLowerCase(),s=864e5;if(e==="today")return Date.now()-s;if(e==="yesterday")return Date.now()-2*s;const t=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(t){const o=Number(t[1]),i=t[2][0],a=i==="d"?s:i==="w"?7*s:i==="m"?30*s:365*s;return Date.now()-o*a}const r=Date.parse(e);return Number.isNaN(r)?null:r}const w=(n,e)=>`${e+1}. [${n.id}] ${n.title||"(untitled)"} · ${n.type}${n.date?" · "+new Date(n.date).toISOString().slice(0,10):""}${n.snippet?`
|
|
3
|
-
${n.snippet}`:""}`;async function F(n,e={}){const s=await B(n,e);if(s!=null)return s;if(n==="smart_search"){const t={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(t.type=String(e.type));const r=m(e.since);r!=null&&(t.since=r);const o=m(e.before);o!=null&&(t.before=o);const i=await h("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}),a=i.results||[],c=g(i.newest,i.size),l=(i.queries||[]).map(d=>`"${d}"`).join(", ");return a.length?[c,"",`${a.length} result(s) for "${e.question}" — searched ${i.queries.length} way(s): ${l}`,...a.map((d,C)=>`${w(d,C)}${d.foundBy?.length>1?`
|
|
4
|
-
(
|
|
1
|
+
import{loadConfig as y}from"./config.js";import{VERSION as w}from"./version.js";import{readBridgeToken as x}from"./bridge.js";import{ensureGatewayToken as b}from"./gateway-token.js";import{MEMORY_KINDS as j,MEMORY_KIND_NAMES as _}from"./memory.js";import{parseBriefText as A}from"./knowledge.js";import{capabilityToolsProvider as q,DECIDE_TOOL_NAME as I,RERANK_TOOL_NAME as L}from"./capability-tools.js";import{webSearchToolProvider as M}from"./web-search-tool.js";import{SEARCH_DEFAULTS as D}from"./retrieval/search.js";import{askToolsFor as T,callAsk as U}from"./mcp-ask.js";import{CAPABILITY_TOOLS as B,callCapability as H}from"./mcp-capabilities.js";const Y="2024-11-05",F={name:"chatpanel-history",version:w},W=["ChatPanel holds the USER'S OWN meetings, notes and past chats — transcripts, decisions,","action items, summaries — which usually are NOT in the working directory.","","Keep using all your normal tools. ADDITIONALLY, whenever the user's question touches a",'meeting, call, demo, note, or past conversation ("outcome of the meeting", "what did we','decide", "action items", "notes from yesterday", a person/day/topic in their history),',"ALSO consult ChatPanel — it is the source of truth for that personal history:"," • smart_search — START HERE: give it the question plus 2-4 of your own keyword"," phrasings; it runs them all and fuses the rankings, finding what one query misses."," • search_history — one exact keyword query, when you already know the terms. Search by"," CONTENT (not the generic meeting title). Supports filters:",' type (chat|meeting|note), since/before (dates or relative like "7d", "yesterday"),'," and limit/offset paging. Returns compact snippets, not full bodies."," • get_record — the full text of one result id; use maxChars/offset to page a long"," transcript instead of pulling it all into context."," • find_related — follow the graph: given a record id, the records most connected to it.","","ChatPanel also holds the user's MEMORY — a short list of durable facts about them (their","name, how they want answers written, what they are working on) that applies to EVERY task,","not just ones about their history:"," • recall — call it EARLY in a session, and whenever the user states a preference, to see"," what is already known. Then simply follow it; do not tell them you looked.",' • remember — save a new durable fact when they state one ("call me Alex", "always use',' pnpm"). One short sentence. Not for task details or anything true only today.'," • forget — remove one when they say it no longer holds.","Prefer these for the user's history and combine them with your other tools as you see fit.","Every result states how fresh the local copy is; if something recent is missing it may not","have synced yet — say so rather than concluding it does not exist.","","ChatPanel also runs SMALL LOCAL MODELS and a private web search on this machine:"," • decide — a sentiment, tone, urgency, spam/complaint, yes/no or pick-one judgement over"," text you already hold, answered with a probability per option in milliseconds. Call it"," instead of judging the text yourself."," • rerank — order many candidates (search hits, comments, sections) by relevance to a"," question, best first with a score, instead of reading them all."," • web_search — the user's own search (their SearXNG when one runs here), results with"," the top pages already read. Nothing leaves this machine but the query."," • redact_check — what is personal or secret in a piece of text, found by the detector on"," THIS machine. Call it before you put someone else's data into your own context, a"," commit message, an issue or a message to a third party — and whenever the user asks"," what is sensitive in something. It tells you what it could not see, so read that line."," • read_document — a URL as clean markdown through the user's own reader and cache,"," for a fraction of the context raw HTML would cost.","","ChatPanel can also hand a question to ANOTHER MODEL on this machine and give you its answer:"," • list_models — what can answer, and WHERE each one runs (on this device / a cloud)."," • ask_model — ask one. Use it for a second opinion on your own reasoning, for a model",' stronger in some domain, when the user names a model ("ask Claude what it thinks"), or'," when they want a question kept on-device — pick a `device` model and nothing leaves the"," machine. The model you ask sees your prompt and NOTHING else: no files, no shell, no web."," So paste in the code or context it needs. A slow answer returns a job id for ask_status."].join(`
|
|
2
|
+
`);async function z(){try{const t=await fetch(`${f()}/health`,{signal:AbortSignal.timeout(600)}),e=String((await t.json())?.version||"");return!e||e===w?"":["",`IMPORTANT — VERSION MISMATCH. This MCP server is ChatPanel ${w}, but the gateway`,`running on this machine is ${e}. They are different installs: your client launched`,"whichever `chatpanel-gateway` is on its PATH, and it is not the one the user is running.","The practical effect is that TOOLS MAY BE MISSING here — a newer gateway has tools this","server does not advertise. If a ChatPanel tool the user expects is not in your list, this","is why. Tell them, and tell them the fix: point the MCP config at the newer executable","(or update the older install so both are the same version)."].join(`
|
|
3
|
+
`)}catch{return""}}function k(){try{return y().mcp?.ask||{}}catch{return{}}}let m="unknown";function C(t){try{const e=b();fetch(`${f()}/v1/observability/access`,{method:"POST",headers:{"content-type":"application/json",...e?{Authorization:`Bearer ${e}`}:{}},body:JSON.stringify(t)}).catch(()=>{})}catch{}}function f(){const t=process.env.CHATPANEL_GATEWAY_URL;if(t)return t.replace(/\/+$/,"");let e=4320;try{e=y().port||4320}catch{}return`http://127.0.0.1:${e}`}function O(){try{return String(y().bridge?.url||"http://127.0.0.1:4319").replace(/\/+$/,"")}catch{return"http://127.0.0.1:4319"}}function J(){try{return x(y().bridge?.token||"")}catch{return x("")}}async function S(t){const e=J(),i=await fetch(O()+t,{headers:{Accept:"application/json",...e?{Authorization:`Bearer ${e}`}:{}}}),a=await i.json().catch(()=>({}));if(!i.ok||a.ok===!1)throw new Error(a?.error||`bridge ${i.status}`);return a}const G=[{name:"smart_search",description:'BEST first choice for a question about the user\'s ChatPanel history (meetings, notes, past chats). Ask it a natural-language QUESTION and it expands that into several complementary keyword queries, runs them all, and fuses the rankings — which finds things a single query misses, in one round trip instead of several probes. You know the domain, so pass 2-4 of your own phrasings in `queries` too (e.g. for "what did we decide in the Ben demo": ["Ben demo decisions", "tooling demo action items", "demo outcome next steps"]). Supports the same filters as search_history (type, since, before) and returns snippets with each result\'s id; follow up with get_record for the full text or find_related to expand around a hit. BRIEFS come first when they match: a brief is a maintained page about one person, project or topic, derived from ALL the records that mention it, with every claim citing its record — so for "what do we know about X" read the brief, then open only the records it cites.',inputSchema:{type:"object",properties:{question:{type:"string",description:"The user's question, in natural language."},queries:{type:"array",items:{type:"string"},description:"Your own 2-4 keyword formulations of it — these lead the search."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a window like "7d"/"yesterday".'},before:{type:"string",description:"Latest date: a date or window like `since`."},limit:{type:"number",description:"Max fused results (default 10)."}},required:["question"]}},{name:"search_history",description:'Search the user\'s ChatPanel history — their past chats, meeting/call transcripts, and notes — by keyword relevance. Consult this (in ADDITION to your other tools) whenever the question touches a meeting, call, demo, note, or past conversation: "outcome of the meeting", "what did we decide", "action items", "what did <person> say", "notes from yesterday". Filters: `type` (chat|meeting|note), `since`/`before` (a date like 2026-08-01 or a relative window like "7d"/"yesterday"), and `limit`/`offset` for paging. Returns compact SNIPPETS (the matching excerpt) with each record\'s id/title/type/date — token-friendly; call get_record for the full text and find_related to follow connections. This is a LOCAL WARM COPY that syncs from ChatPanel; very recent items may not be here yet — results report how current the index is, so if something is missing it likely has not synced. Meeting titles are often generic ("Zoom Meeting"), so search by CONTENT, not the title.',inputSchema:{type:"object",properties:{query:{type:"string",description:"Content keywords (topics, names, decisions) — not the meeting title."},type:{type:"string",enum:["brief","chat","meeting","note"],description:'Only this kind of record. `brief` = a maintained page about one person/project/topic, with every claim cited — start there for "what do we know about X".'},since:{type:"string",description:'Earliest date: 2026-08-01, or a relative window like "7d", "2 weeks", "yesterday".'},before:{type:"string",description:"Latest date: a date or relative window like `since`."},limit:{type:"number",description:"Max results (default 10)."},offset:{type:"number",description:"Skip N results for paging (default 0)."}},required:["query"]}},{name:"get_record",description:"Fetch one history record's full text by id (chat:<id>, meeting:<id>, note:<id> from search_history). For a long transcript, page it with maxChars + offset instead of pulling it all into context — the result says how many chars remain.",inputSchema:{type:"object",properties:{id:{type:"string",description:"Record id such as chat:abc, meeting:imp_123, or note:xyz."},maxChars:{type:"number",description:"Return at most this many characters (token management for long transcripts)."},offset:{type:"number",description:"Start at this character offset — page through with the offset the previous call reports."}},required:["id"]}},{name:"find_related",description:"Graph navigation: given a record id (from search_history), return the records most connected to it by shared content — the meetings/notes/chats about the same topic, people or thread. Use it to expand from one hit to the surrounding context instead of re-searching.",inputSchema:{type:"object",properties:{id:{type:"string",description:"The record id to find neighbours of."},limit:{type:"number",description:"Max related records (default 5)."}},required:["id"]}},{name:"list_history",description:"List history records (newest first) with their id, title, type and date — no bodies. Reports how current this warm copy is (its newest record). Use to see the index horizon and browse/page the corpus.",inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max items (default 50)."},offset:{type:"number",description:"Skip N items for paging (default 0)."}}}},{name:"list_briefs",description:`The BRIEFS ChatPanel maintains — one page per person, project or topic that appears across enough records, each claim citing the record it came from. This is the index of what the user's corpus KNOWS, as opposed to what it merely contains: read it before asking "what do we know about X", then get_brief for the one you need. Briefs are rebuilt from the records, so they are as current as the last rebuild (dates shown).`,inputSchema:{type:"object",properties:{limit:{type:"number",description:"Max briefs (default 50)."},offset:{type:"number",description:"Skip N for paging (default 0)."}}}},{name:"get_brief",description:"One brief as STRUCTURE: the subject, its other spellings, and each claim with the record ids it cites — so you can cite the record rather than the synthesis, and open only what you need with get_record. Prefer this over get_record for a brief:… id; get_record returns the same text as prose.",inputSchema:{type:"object",properties:{id:{type:"string",description:"A brief id (brief:…) from list_briefs or search results."}},required:["id"]}},{name:"recall",description:"What ChatPanel already knows about the USER — their name, how they want answers written, their ongoing work and environment. Short and cheap; call it at the START of a session and whenever the user states a preference, then just FOLLOW what it returns without announcing that you checked. Pass the current task in `text` and it also returns the facts relevant to that task, not only the always-on ones. This is memory, not history: for what was said in a meeting or a past chat use smart_search instead.",inputSchema:{type:"object",properties:{text:{type:"string",description:"What the user is asking about right now, so task-relevant facts come back too. Omit for just the always-on ones."}}}},{name:"remember",description:`Save a durable fact about the USER to ChatPanel, carried into every future session on every model and agent — the side panel, other CLIs, everything. Use it the moment they state a standing preference ("always use pnpm"), an identity fact ("call me Alex") or a constraint that will still be true next week. Do NOT use it for task details, anything obvious from the current work, or notes about a codebase — those belong in the repo. One short self-contained sentence, written in the third person. Saving is a change to the user's own data, so say in a short clause what you saved.`,inputSchema:{type:"object",properties:{text:{type:"string",description:'The fact, one short sentence in the third person ("Prefers pnpm over npm"). Max 280 characters.'},kind:{type:"string",enum:_,description:_.map(t=>`${t}: ${j[t].hint}`).join(" ")},tags:{type:"array",items:{type:"string"},description:"Optional short tags for grouping."}},required:["text"]}},{name:"forget",description:'Remove a memory from ChatPanel when the user says it no longer holds. Name it however they did ("the Frankfurt thing") or pass the id from recall — it matches on meaning, and tells you exactly what it removed.',inputSchema:{type:"object",properties:{query:{type:"string",description:"The memory to remove: its text, roughly how the user named it, or its id."}},required:["query"]}},{name:"list_skills",description:"List the reusable skills installed on this machine (via the ChatPanel bridge) — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes) and any configured folder. Returns each skill's name and one-line description. Call open_skill to load the one that fits the task.",inputSchema:{type:"object",properties:{}}},{name:"open_skill",description:"Load one skill's full instructions by name (from list_skills), then follow them. If the instructions point at reference files, read one with read_skill_file.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name from list_skills."}},required:["name"]}},{name:"read_skill_file",description:"Read one reference file a skill's instructions point at (any path inside the skill's own folder). Use only when the task needs it.",inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill name."},path:{type:"string",description:"The reference path as written in the instructions, e.g. references/auth.md."}},required:["name","path"]}}],N={[I]:" To have one: ChatPanel › Settings › Runtime › OpenDecision › Start (or a server that provides `decide` under Models).",[L]:" To have one: ChatPanel › Settings › Runtime › Reranker › Start (or a server that provides `rerank` under Models)."};function E(){const t=f(),e=c=>[{id:"gateway",name:"the gateway",url:`${t}${c}`,where:"this device"}],i=q({providers:{decide:e("/v1/decide"),rerank:e("/v1/rerank")},fetch:(c,o)=>fetch(c,o)}),a=M({search:async c=>{const o=await l("/v1/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({q:c,limit:8,read:D.aliasRead})});return{query:c,engines:o.engines||[],results:(o.results||[]).map((n,r)=>({rank:r+1,title:n.title||n.url,url:n.url,engine:n.engine||"",text:n.read?.markdown||n.read?.text||n.snippet||""}))}}});return[i,a]}const V=E().flatMap(t=>t.specs.map(e=>({name:e.name,description:e.description,inputSchema:e.parameters})));async function K(t,e){const i=E().find(o=>o.specs.some(n=>n.name===t));if(!i)return null;const a=await i.execute(t,e);let c=typeof a=="string"?a:String(a?.text??a);return N[t]&&/^No (decision model|reranker) answered/.test(c)&&(c+=N[t]),c}function $(t,e){if(!t)return`Index: ${e} records (warm copy synced from ChatPanel).`;const i=new Date(t),a=`${i.getFullYear()}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")} ${String(i.getHours()).padStart(2,"0")}:${String(i.getMinutes()).padStart(2,"0")}`;return`Index: ${e} records, current through ${a} (local warm copy — items newer than this may not have synced from ChatPanel yet).`}function R(){try{const t=b();return t?{Authorization:`Bearer ${t}`}:{}}catch{return{}}}async function l(t,e){let i;try{i=await fetch(f()+t,e)}catch(c){throw new Error(`the ChatPanel gateway is not running at ${f()} — start it with "chatpanel-gateway --install" (or run "chatpanel-gateway"), then retry. [${c.message}]`)}const a=await i.json().catch(()=>({}));if(!i.ok)throw new Error(a?.error?.message||`the gateway returned HTTP ${i.status} for ${t}`);return a}function g(t){if(t==null||t==="")return null;if(typeof t=="number")return t;const e=String(t).trim().toLowerCase(),i=864e5;if(e==="today")return Date.now()-i;if(e==="yesterday")return Date.now()-2*i;const a=/^(\d+)\s*(d|day|days|w|week|weeks|m|month|months|y|year|years)$/.exec(e);if(a){const o=Number(a[1]),n=a[2][0],r=n==="d"?i:n==="w"?7*i:n==="m"?30*i:365*i;return Date.now()-o*r}const c=Date.parse(e);return Number.isNaN(c)?null:c}const v=(t,e)=>`${e+1}. [${t.id}] ${t.title||"(untitled)"} · ${t.type}${t.date?" · "+new Date(t.date).toISOString().slice(0,10):""}${t.snippet?`
|
|
4
|
+
${t.snippet}`:""}`;async function X(t,e={}){const i=await K(t,e);if(i!=null)return i;const a=await H(t,e,{gatewayJson:l});if(a!=null)return a;const c=await U(t,e,{baseUrl:f,gatewayJson:l,token:()=>{try{return b()}catch{return""}},client:()=>m,askConfig:k});if(c!=null)return c;if(t==="smart_search"){const o={question:String(e.question||""),queries:Array.isArray(e.queries)?e.queries.map(String):[],limit:Number(e.limit)||10};e.type&&(o.type=String(e.type));const n=g(e.since);n!=null&&(o.since=n);const r=g(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/smart-search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=(s.queries||[]).map(p=>`"${p}"`).join(", ");return h.length?[d,"",`${h.length} result(s) for "${e.question}" — searched ${s.queries.length} way(s): ${u}`,...h.map((p,P)=>`${v(p,P)}${p.foundBy?.length>1?`
|
|
5
|
+
(matched ${p.foundBy.length} of the queries)`:""}`)].join(`
|
|
5
6
|
`)+`
|
|
6
7
|
|
|
7
8
|
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.question}".
|
|
8
|
-
Searched ${
|
|
9
|
-
${
|
|
10
|
-
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(
|
|
9
|
+
Searched ${s.queries?.length||0} way(s): ${u}.
|
|
10
|
+
${d}
|
|
11
|
+
If you expected a recent item it may not have synced yet — check ChatPanel directly, or try different keywords (meeting titles are often generic).`}if(t==="search_history"){const o={query:String(e.query||""),limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0)};e.type&&(o.type=String(e.type));const n=g(e.since);n!=null&&(o.since=n);const r=g(e.before);r!=null&&(o.before=r);const s=await l("/v1/history/search",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o)}),h=s.results||[],d=$(s.newest,s.size),u=[e.type&&`type=${e.type}`,e.since&&`since=${e.since}`,e.before&&`before=${e.before}`].filter(Boolean).join(", "),p=u?` (${u})`:"";return h.length?[d,"",`${h.length} result(s) for "${e.query}"${p}:`,...h.map(v)].join(`
|
|
11
12
|
`)+`
|
|
12
13
|
|
|
13
|
-
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${
|
|
14
|
-
${
|
|
15
|
-
If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(
|
|
14
|
+
get_record <id> for full text (maxChars/offset to page) · find_related <id> to follow connections.`:`No match for "${e.query}"${p}.
|
|
15
|
+
${d}
|
|
16
|
+
If you expected a recent item, it may not have synced yet — check ChatPanel directly, or broaden the query (titles are often generic; try content keywords, or drop a filter).`}if(t==="get_record"){const o=new URLSearchParams({id:String(e.id||"")});e.maxChars!=null&&o.set("maxChars",String(Math.max(1,Number(e.maxChars)||0))),e.offset!=null&&o.set("offset",String(Math.max(0,Number(e.offset)||0)));const r=(await l(`/v1/history/get?${o}`)).record,s=`[${r.id}] ${r.title||"(untitled)"} · ${r.type}${r.date?" · "+new Date(r.date).toISOString().slice(0,10):""}`,h=r.truncated?`
|
|
16
17
|
|
|
17
|
-
[showing ${
|
|
18
|
+
[showing ${r.text.length} of ${r.totalChars} chars (from offset ${r.offset}). For the next part call get_record again with offset=${r.offset+r.text.length}.]`:"";return`${s}
|
|
18
19
|
|
|
19
|
-
${
|
|
20
|
+
${r.text||"(empty)"}${h}`}if(t==="find_related"){const n=(await l(`/v1/history/related?id=${encodeURIComponent(String(e.id||""))}&limit=${Number(e.limit)||5}`)).results||[];return n.length?[`Records related to ${e.id}:`,...n.map(v)].join(`
|
|
20
21
|
`)+`
|
|
21
22
|
|
|
22
|
-
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(
|
|
23
|
-
`)}if(
|
|
23
|
+
get_record <id> for full text.`:`Nothing related to ${e.id} found (or that id isn't in the warm index — run search_history first to get a valid id).`}if(t==="list_history"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0)}),n=await l(`/v1/history/list?${o}`),r=n.items||[];if(!r.length)return"History is empty (or the gateway has not been seeded yet — open ChatPanel with warm sync enabled).";const s=r[0]?.date||null;return[$(s,n.total),"",`${r.length} of ${n.total} records:`,...r.map(h=>`[${h.id}] ${h.title||"(untitled)"} · ${h.type}${h.date?" · "+new Date(h.date).toISOString().slice(0,10):""} · ${h.chars} chars`)].join(`
|
|
24
|
+
`)}if(t==="list_briefs"){const o=new URLSearchParams({limit:String(Number(e.limit)||50),offset:String(Number(e.offset)||0),type:"brief"}),n=await l(`/v1/history/list?${o}`),r=n.items||[];return r.length?[`${r.length} of ${n.total} briefs (each is a page about one subject, with every claim cited):`,...r.map(s=>`[${s.id}] ${s.title||"(untitled)"}${s.date?" · rebuilt "+new Date(s.date).toISOString().slice(0,10):""}`)].join(`
|
|
24
25
|
`)+`
|
|
25
26
|
|
|
26
|
-
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(
|
|
27
|
-
`)}if(
|
|
27
|
+
get_brief <id> for its claims and the records they cite.`:`No briefs yet. ChatPanel builds them from the user's records on the Briefs page; if that has run, the user may have "share briefs with local agents" switched off.`}if(t==="get_brief"){const o=String(e.id||""),r=(await l(`/v1/history/get?${new URLSearchParams({id:o})}`)).record,s=A(r?.text);if(!s)return`${o} is not a brief (type ${r?.type||"unknown"}). Use get_record for it, or list_briefs for the brief ids.`;const h=[`BRIEF ${o} — ${s.name} (${s.kind})${s.aliases.length?` · also known as ${s.aliases.join(", ")}`:""}`,""];h.push(`${s.claims.length} claim(s), each with the records it cites:`);for(const d of s.claims)h.push(`• ${d.text}`),d.refs.length&&h.push(` cites: ${d.refs.map(u=>`${u.kind}:${u.id}`).join(", ")}`);return s.records.length&&h.push("",`Built from ${s.records.length} record(s) (most recent first): ${s.records.slice(0,12).map(d=>d.title).join(" · ")}${s.records.length>12?" …":""}`),h.push("","get_record <kind:id> opens a cited record; find_related <id> follows its connections."),h.join(`
|
|
28
|
+
`)}if(t==="recall"){const o=await l("/v1/memory/recall",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:String(e.text||"")})});return o.memories?.length?o.block:o.size?"Nothing in ChatPanel memory applies here.":"ChatPanel memory is empty — nothing is known about this user yet. Use `remember` when they state something durable about themselves or how they want to work."}if(t==="remember"){const o=String(e.text||"").trim();if(!o)return"remember needs `text` — one short sentence about the user.";const n=await l("/v1/memory/remember",{method:"POST",headers:{"content-type":"application/json",...R()},body:JSON.stringify({text:o,kind:e.kind?String(e.kind):"fact",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:"mcp",surface:"mcp",agent:m}})});return n.action==="duplicate"?`Already known: "${n.record.text}" — nothing changed.`:n.action==="update"?`Updated memory to "${n.record.text}" (was "${n.replaced?.text}"). It applies to every future session.`:`Remembered: "${n.record.text}". It applies to every future ChatPanel session, on every model.`}if(t==="forget"){const o=String(e.query||"").trim();if(!o)return"forget needs `query` — the memory to remove.";const n=await l("/v1/memory/forget",{method:"POST",headers:{"content-type":"application/json",...R()},body:JSON.stringify({query:o})});return n.removed?.length?`Forgot: ${n.removed.map(r=>`"${r.text}"`).join(", ")}.`:`No memory matches "${o}". Call recall to see what is stored.`}if(t==="list_skills"){let o;try{o=await S("/skills")}catch(r){return`Installed skills are unavailable because the ChatPanel bridge is not running at ${O()}. Install/start it with:
|
|
28
29
|
curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash
|
|
29
|
-
Then retry. History tools work without the bridge. [${
|
|
30
|
+
Then retry. History tools work without the bridge. [${r.message}]`}const n=o.skills||[];return n.length?[`${n.length} skill(s) installed:`,...n.map(r=>`- ${r.command||r.id}: ${r.description||r.name}${r.origin?.source?` (from ${r.origin.source})`:""}`)].join(`
|
|
30
31
|
`)+`
|
|
31
32
|
|
|
32
|
-
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
Use open_skill with a name to load its instructions.`:"No skills installed on this machine yet."}if(t==="open_skill"){let o;try{o=await S(`/skills/${encodeURIComponent(String(e.name||"").trim())}`)}catch(n){return`Could not open "${e.name}": ${n.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return o.skill?.prompt||"(this skill has no extra instructions — just apply it.)"}if(t==="read_skill_file"){const o=encodeURIComponent(String(e.name||"").trim()),n=String(e.path||"").trim().split("/").map(encodeURIComponent).join("/");let r;try{r=await S(`/skills/${o}/file/${n}`)}catch(s){return`Could not read ${e.path}: ${s.message}. If the bridge isn't running, start it: curl -fsSL https://dl.chatpanel.net/bridge/install.sh | bash`}return r.text||"(empty)"}throw new Error(`unknown tool: ${t}`)}async function Q(t){const{id:e,method:i,params:a}=t||{},c=n=>({jsonrpc:"2.0",id:e,result:n}),o=(n,r)=>({jsonrpc:"2.0",id:e,error:{code:n,message:r}});try{switch(i){case"initialize":{m=a?.clientInfo?.name||m;const n=await z(),r=T(k()).some(s=>s.name==="delegate_task")?`
|
|
34
|
+
|
|
35
|
+
ChatPanel can also DELEGATE a whole piece of work to one of the user's coding agents,
|
|
36
|
+
running here with its own tools in a directory they have allowed:
|
|
37
|
+
• delegate_task — a refactor across many files, a test suite to run and fix, a build to
|
|
38
|
+
diagnose. Unlike ask_model it reads and EDITS files and runs commands, so use it for work
|
|
39
|
+
that belongs on this machine, tell the user what you delegated and where, and expect
|
|
40
|
+
minutes — it returns a job id for ask_status.`:"";return c({protocolVersion:Y,capabilities:{tools:{}},serverInfo:F,instructions:W+r+n})}case"tools/list":return c({tools:[...G,...V,...B,...T(k())]});case"tools/call":{const n=Date.now();try{const r=await X(a?.name,a?.arguments||{});return C({client:m,tool:a?.name,ok:!0,ms:Date.now()-n,args:a?.arguments||{}}),c({content:[{type:"text",text:r}]})}catch(r){throw C({client:m,tool:a?.name,ok:!1,ms:Date.now()-n,args:a?.arguments||{},error:r.message}),r}}case"ping":return c({});default:return typeof i=="string"&&i.startsWith("notifications/")||e===void 0?null:o(-32601,`method not found: ${i}`)}}catch(n){return i==="tools/call"?c({content:[{type:"text",text:`Error: ${n.message}`}],isError:!0}):o(-32603,n.message)}}async function de(){let t="";process.stdin.setEncoding("utf8");const e=i=>process.stdout.write(JSON.stringify(i)+`
|
|
41
|
+
`);for await(const i of process.stdin){t+=i;let a;for(;(a=t.indexOf(`
|
|
42
|
+
`))>=0;){const c=t.slice(0,a).trim();if(t=t.slice(a+1),!c)continue;let o;try{o=JSON.parse(c)}catch{continue}const n=await Q(o);n&&e(n)}}}export{Q as handleRpc,de as runMcpServer};
|
package/src/retrieval/search.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{validateSearchRequest as
|
|
1
|
+
import{validateSearchRequest as j,validateSearchResponse as B,overBudget as I}from"../capability-endpoints.js";import{createReadStats as x}from"./read.js";import{searchSerp as C,PROVIDER_ID as _}from"./search-serp.js";import{PROVIDER_ID as l}from"./search-searxng.js";const S=Object.freeze({timeoutMs:15e3,readConcurrency:4,readBudgetMs:8e3,aliasRead:5}),L=/\[\[[A-Z][A-Z0-9_]*_\d+\]\]/g,c=(r,t,n)=>({status:r,body:{error:{type:t,message:n}}});function N(r){const t=String(r||"").replace(L," ").replace(/\s+/g," ").trim();return{q:t,stripped:t!==String(r||"").trim()}}async function J(r,t,n){const p=new Array(r.length);let y=0;const v=Array.from({length:Math.min(t,r.length)},async()=>{for(;;){const s=y++;if(s>=r.length)return;p[s]=await n(r[s],s)}});return await Promise.all(v),p}function H({reader:r=null,redact:t=async h=>h,searxng:n=null,defaultProvider:p="auto",fetchFn:y=void 0,engines:v=void 0,now:s=()=>Date.now(),stats:q={serp:x(),searxng:x()},timeoutMs:w=S.timeoutMs}={}){const h=()=>[_,...n?.url?[l]:[]];async function $(g){if(g.provider)return g.provider;if(p===l||p===_)return p;if(n?.url){const e=await n.health();if(e.state==="ready"||e.state==="unknown")return l}return _}return{providers:h,stats:()=>Object.fromEntries(Object.entries(q).map(([g,e])=>[g,e.stats()])),searxng:n,async search(g){let e;try{e=j(g)}catch(a){return c(400,"invalid_request",a.message)}if(e.provider&&!h().includes(e.provider))return c(404,"provider_not_found",`no search provider ${JSON.stringify(e.provider)} here (have ${h().join(", ")})`);if(e.read&&!r)return c(400,"invalid_request","read: no reader is available here");const R=s();let E=!1;try{const a=await t(e.q),{q:o,stripped:m}=N(a);m&&(E=!0,e.q=o)}catch(a){return c(500,"redaction_failed",a.message)}if(!e.q)return c(400,"unsafe_query","the query was only private values (an email, a card, a key…) and nothing searchable remains");const d=await $(e),T=I(q[d]?.stats(),0,e.budgetMs);if(T)return{status:503,body:{...T,provider:d}};const M=new AbortController,O=setTimeout(()=>M.abort(),Math.min(w,e.budgetMs>0?e.budgetMs:w));let i;try{i=d===l?await n.search(e,{signal:M.signal}):await C(e,{fetchFn:y,signal:M.signal,engines:v})}catch(a){return clearTimeout(O),M.signal.aborted?c(504,"fetch_timeout",`${d} did not answer within the budget`):c(502,"provider_failed",`${d}: ${a.message}`)}clearTimeout(O);let A=d;if(!i.results.length&&!e.provider&&h().length>1){const a=d===l?_:l,o=new AbortController,m=setTimeout(()=>o.abort(),Math.min(w,e.budgetMs>0?Math.max(1e3,e.budgetMs-(s()-R)):w));try{const u=a===l?await n.search(e,{signal:o.signal}):await C(e,{fetchFn:y,signal:o.signal,engines:v});u?.results?.length&&(i=u,A=a)}catch{}clearTimeout(m)}const k=Math.round(s()-R);q[A]?.record(k,e.q.length);let b=i.results;if(e.read>0&&b.length){const a=e.budgetMs>0?Math.max(1e3,e.budgetMs-k):S.readBudgetMs,o=b.slice(0,e.read),m=await J(o,S.readConcurrency,async u=>{const f=await r.read({url:u.url,snippet:u.snippet,budgetMs:Math.min(a,S.readBudgetMs)});return f.status===200?f.body:null});b=b.map((u,f)=>f<o.length&&m[f]?{...u,read:m[f]}:u)}const D={results:b,answers:i.answers||[],suggestions:i.suggestions||[],engines:i.engines||[],...i.unresponsive?.length?{unresponsive:i.unresponsive}:{},...E?{redacted:!0,query:e.q}:{},provider:A,ms:Math.round(s()-R)};try{B(D)}catch(a){return c(500,"bad_shape",a.message)}return{status:200,body:D}}}}function K(r){return{code:200,status:2e4,data:(r.results||[]).map(t=>({url:t.url,title:t.title,description:t.snippet||"",content:t.read?.markdown||t.read?.text||t.snippet||"",...t.read?.published?{publishedTime:t.read.published}:{}}))}}export{S as SEARCH_DEFAULTS,H as createSearcher,N as queryWithoutTokens,K as toJinaSearch};
|
package/src/server.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import{createServer as
|
|
1
|
+
import{createServer as Wt}from"node:http";import{loadConfig as nt}from"./config.js";import{startEntitlementRefresh as Kt,maybeRevalidate as Qt}from"./entitlement-refresh.js";import{redactSegments as $e,segment as Re}from"./redact.js";import{pipeRestoredStream as Zt,pipeRestoredOpenAIStream as Yt,makeTokenRestorer as st,restoreDeep as Xt}from"./stream.js";import{restoreText as qt,gatedDictionary as eo,narrowSpecs as to,makeToolHarness as oo,placeholderToolNote as ro,placeholderNote as no,assertEndpointUrl as so,capRunOptions as ao,isPaired as io}from"@chatpanel/pii";import{ensureGatewayToken as Ie,currentGatewayToken as lo,isAdminAuthorized as X,callerTrustOf as Pe,setPinnedExtensionIds as co,issuePairingCode as uo,claimPairingCode as mo}from"./gateway-token.js";import{installEgressLedger as po,egressAudit as ho}from"./egress.js";import{initPolicy as yo,activePolicy as fo,applyPolicyToConfig as at,managedSummary as ke,PolicyLoadError as go}from"./policy.js";import{routeAllowed as it,agentAllowed as wo,egressAllowed as bo}from"@chatpanel/events/policy.js";import{resolveBridgeUrl as ye}from"./bridge.js";import{secureFetch as Ee}from"./secure-fetch.js";import{streamBridgeChat as lt,readBridgeToken as de,openBridgeChat as vo}from"./bridge.js";import{createRelaySession as ko,getRelaySession as ct,endRelaySession as Se,pumpBridgeStream as So,deliverToolResult as To,toolsToSpecs as xo,wantsApprovals as _o,parseToolCallId as dt,touchRelaySession as Le}from"./toolrelay.js";import{shaperFor as Je}from"./shape.js";import{startNer as Oo,ensureNer as Ae,unionForThisMachine as $o,skippedCompanions as Po}from"./ner.js";import{recommendDetector as ut}from"@chatpanel/pii/detector-router.js";import{installTimestampedConsole as Eo}from"./log.js";import{saveBackupSecret as Ao,clearBackupSecret as No,loadBackupSecret as ze,hasBackupSecret as mt}from"./history-store.js";import{createMemoryStore as Bo}from"./memory-store.js";import{createPrefsStore as Do}from"./prefs-store.js";import{createTeamStore as Mo,loadOrCreateKey as Ge}from"./team-store.js";import{createScorecardStore as Co}from"./scorecard-store.js";import{createEngineLedgerStore as jo}from"./engine-ledger-store.js";import{createProjectStore as Ro}from"./project-store.js";import{applicationsFor as Io,recruitPass as Lo}from"./recruiting.js";import{ensureBridge as Jo}from"./bridge-supervisor.js";import{checkForUpdate as zo,updateStatus as Go,startUpdate as Ho,updateJob as Vo}from"./update.js";import{createHistoryStore as Uo}from"./sqlite-store.js";import{createEventStore as Fo}from"./event-store.js";import{ingestCloudEvents as Wo,cursorOf as pt}from"./event-sync.js";import{eventStats as Ko,projectYear as Qo}from"./event-stats.js";import{toCloudEvent as He}from"./cloudevents.js";import{fusionsDocument as Zo,resolveFusionModel as Yo}from"./fusions.js";import{ingestBackups as Ve}from"./backup-ingest.js";import{toSearchRecord as Xo}from"@chatpanel/events/library.js";import{deriveBackupKey as qo,openRecord as er,keyCache as tr,nodeCodec as or}from"@chatpanel/events/backup-envelope.js";import rr from"node:zlib";import*as E from"./ner-engine.js";import ht from"node:os";import{capabilitiesDocument as nr,handleDetect as sr}from"./capabilities.js";import{createExtractService as ar}from"./extract/service.js";import{workerSandbox as ir,disposeWorkerSandbox as lr}from"./worker-sandbox.js";import{createRuntime as cr}from"./runtime.js";import{createCapabilityProxy as dr}from"./capability-proxy.js";import{handleExtract as ur}from"./extract/handler.js";import{MAX_DOCUMENT_BYTES as mr}from"./extract-capability.js";import{createReader as pr}from"./retrieval/read.js";import{createSearcher as hr,toJinaSearch as yr,SEARCH_DEFAULTS as fr}from"./retrieval/search.js";import{createSearxng as gr}from"./retrieval/search-searxng.js";import{toJinaText as wr}from"./read-document.js";import*as A from"./stt-engine.js";import*as j from"./diarize-engine.js";import{providerOf as yt}from"./providers.js";import{createRemoteTranscriber as ft}from"./stt-remote.js";import{parseMultipart as br,decodeAudioFile as vr}from"./audio-file.js";import{MODEL_CATALOG as gt,isKnownModel as wt,isValidCustomModelId as bt,recommendFor as kr}from"./models.js";import{STT_MODEL_CATALOG as Sr,isKnownSttModel as Tr,isValidCustomSttId as xr,DEFAULT_STT_MODEL as Ne,STT_DTYPES as _r,isValidDtype as Or}from"./stt-models.js";import*as P from"./tts-engine.js";import{TTS_MODEL_CATALOG as vt,TTS_VOICES as $r,isKnownTtsModel as Pr,isValidCustomTtsId as Er,isKnownVoice as kt,isValidVoiceId as St,DEFAULT_TTS_MODEL as Tt,DEFAULT_TTS_VOICE as ue,TTS_DTYPES as Ar,isValidTtsDtype as Nr,MAX_TTS_CHARS as xt,ttsModelHasCustomVoices as Br,resolveDefaultModel as _t,POCKET_VOICES as Dr,DEFAULT_POCKET_VOICE as Be,isPocketVoice as De,ttsModelEngine as Me}from"./tts-models.js";import{ttsDestination as Mr,synthesizeRemote as Cr,isValidRemoteVoice as jr}from"./tts-remote.js";import{rawOrtAvailable as Ue}from"./ort.js";import*as K from"./tts-voices.js";import{resolveTtsVoice as Rr}from"./tts-voice-resolve.js";import{resolvePro as fe,checkQuota as Ir,consume as Lr,usage as Jr}from"./freegate.js";import{publicConfig as Ot,applyConfigPatch as zr,applyNerModelSelection as $t,persistConfig as me,configPath as se,bridgeAgentOptions as Pt,PERMISSION_MODES as Gr,sandboxEnvFor as Hr}from"./configstore.js";import Et from"node:path";import{resolveDestination as At,aggregateModelsAsync as Vr,listDestinations as Ur}from"./router.js";import{makeAccessEvent as Nt}from"./observability.js";import{createPersistentAccessLog as Fr}from"./access-log-store.js";import{planQueries as Wr,multiSearch as Kr}from"./rrf.js";import*as Fe from"./openai.js";import*as Bt from"./responses.js";import*as We from"./anthropic.js";import{closeAndExit as Qr}from"./shutdown.js";import{VERSION as ee}from"./version.js";import{VERSION as Is}from"./version.js";const N=await Uo(),ae=new Set;function Ce({ids:t=[]}={}){const c=N.lossless;if(!c||!ae.size)return;const d=JSON.stringify({newest:c.newest,size:c.size,ids:t.slice(0,50),at:Date.now()});for(const m of ae)try{m.write(`event: records
|
|
2
2
|
data: ${d}
|
|
3
3
|
|
|
4
4
|
`)}catch{ae.delete(m)}}setInterval(()=>{for(const t of ae)try{t.write(`: ping
|
|
5
5
|
|
|
6
|
-
`)}catch{ae.delete(t)}},25e3).unref?.();const z=await
|
|
7
|
-
data: ${JSON.stringify(
|
|
6
|
+
`)}catch{ae.delete(t)}},25e3).unref?.();const z=await Fo(),ge=new Set;z?.watch(t=>{if(!ge.size)return;const c=`event: cloudevent
|
|
7
|
+
data: ${JSON.stringify(He(t))}
|
|
8
8
|
|
|
9
9
|
`;for(const d of ge)try{d.write(c)}catch{ge.delete(d)}}),setInterval(()=>{for(const t of ge)try{t.write(`: ping
|
|
10
10
|
|
|
11
|
-
`)}catch{ge.delete(t)}},25e3).unref?.();const te=await
|
|
11
|
+
`)}catch{ge.delete(t)}},25e3).unref?.();const te=await Bo(),oe=Do(),we=Co({key:Ge()}),be=jo({key:Ge()}),Q=Ro({key:Ge()}),G=Mo({scorecards:we,engines:be}),Ke=new Set,Dt=(t,c)=>{for(const m of Ke)try{m({applied:t,by:c,revision:oe.revision})}catch{}const d=JSON.stringify({revision:oe.revision,applied:(t||[]).slice(0,50),by:c||"",at:Date.now()});for(const m of ae)try{m.write(`event: prefs
|
|
12
12
|
data: ${d}
|
|
13
13
|
|
|
14
|
-
`)}catch{ae.delete(m)}},
|
|
14
|
+
`)}catch{ae.delete(m)}},Qe=Fr(),Mt=new Set(["codex","claude","opencode","pi","kiro","antigravity","hermes"]),Zr=16,Yr=/^mcp[_-]/i,Ct=t=>t&&t.function&&t.function.name||t&&t.name||"",Xr=t=>t&&t.function&&t.function.description||t&&t.description||"";function jt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(c=>typeof c=="string"?c:c&&(c.text||c.content)||"").join(" "):""}function qr(t,c){if(!t)return"";if(c==="responses"){const m=t.input;return typeof m=="string"?m:Array.isArray(m)?m.map(f=>jt(f&&(f.content??f))).join(" "):""}const d=Array.isArray(t.messages)?t.messages:[];for(let m=d.length-1;m>=0;m--)if(d[m]&&d[m].role==="user")return jt(d[m].content);return""}const Rt=new Set(["host","connection","content-length","transfer-encoding","accept-encoding","content-encoding","keep-alive"]);function It(t){if(!t)return!1;const c=t.replace(/:\d+$/,"").replace(/^\[|\]$/g,"");return c==="localhost"||c==="127.0.0.1"||c==="::1"}function en(t,c){return!t||/^chrome-extension:\/\//.test(t)||/^moz-extension:\/\//.test(t)||/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/.test(t)?!0:Array.isArray(c.allowedOrigins)&&c.allowedOrigins.includes(t)}function tn(t,c){t.setHeader("Access-Control-Allow-Origin",c||"*"),t.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-ChatPanel-Token"),t.setHeader("Vary","Origin")}const Lt=Date.now();function on(t){if(!t)return"";const c={redact:"redact",upstream:"model",stream:"stream",restore:"restore",total:"total"};return Object.keys(t).map(d=>`${c[d]||d} ${t[d]}ms`).join(" · ")}function rn(t){const c=/^(model|harness):([^/]+)(?:\/(.+))?$/.exec(String(t||""));return c?{kind:c[1],id:c[2],...c[3]?{model:c[3]}:{}}:null}function nn(t){const c=performance.now(),d={};let m=!1;const f=(g,$)=>{d[g]=Math.round($*10)/10};return{meta:{},timings:d,mark:f,lap(g,$){f(g,performance.now()-$)},clock(){return performance.now()},commit(){if(m)return;m=!0,f("total",performance.now()-c);const g={...this.meta,timings:d};setImmediate(()=>{t(g),console.log(`[gateway] model=${g.model||"-"} → ${g.dest?`${g.dest}(${g.type})`:"none"} · ${g.redaction==="off"?"redaction OFF (client request)":`redacted ${g.redacted||0}`}${g.sanitized?` · scrubbed ${g.sanitized} hidden`:""}${g.narrowed?` · narrowed -${g.narrowed}`:""} · ${on(d)}`)})}}}function Jt(t,c){if(!t||!t.byToken||c!=="types"&&c!=="values")return;const d=[];for(const[m,f]of t.byToken){const g=/^\[\[([A-Z][A-Z0-9]*)_\d+\]\]$/.exec(m),$=g?g[1]:"PII",S=m.replace(/^\[\[|\]\]$/g,"");d.push(c==="values"?{token:S,type:$,value:f}:{token:S,type:$})}return d}function sn(t,c,d){return We.matches(t)||"anthropic-version"in c?{kind:"anthropic",adapter:We,redactable:We.matches(t),base:d.upstreams?.anthropic?.baseUrl}:Bt.matches(t)?{kind:"responses",adapter:Bt,redactable:!0,base:d.upstreams?.openai?.baseUrl}:{kind:"openai",adapter:Fe,redactable:Fe.matches(t),base:d.upstreams?.openai?.baseUrl}}function Ze(t,c){const d=String(t||"");if(Mt.has(d))return{agent:d,agentModel:""};const m=d.indexOf("/");if(m>0){const f=d.slice(0,m);if(Mt.has(f))return{agent:f,agentModel:d.slice(m+1)}}return{agent:c.bridge.agent,agentModel:""}}function zt(t,c){return Ze(t,c).agent}function an(t,c){if(c!=="openai"||!t)return!1;const d=Fe.extractLatestToolResult(t);if(!d)return!1;const m=dt(d.tool_call_id);return!!(m&&ct(m.gwId))}function ln(t,c){try{const d=new URL(t),m=d.hostname.replace(/^\[|\]$/g,""),f=m==="127.0.0.1"||m==="localhost"||m==="::1",g=d.port||(d.protocol==="https:"?"443":"80");return f&&String(g)===String(c.port)}catch{return!1}}async function T(t,c){const d=[];let m=0;for await(const f of t){if(m+=f.length,c&&m>c){const g=new Error("payload too large");throw g.code=413,g}d.push(f)}return Buffer.concat(d)}function s(t,c,d){t.writeHead(c,{"content-type":"application/json"}),t.end(JSON.stringify(d))}function Gt(t){const c=t.redaction?.detection?.url;return!c||t.redaction?.detection?.backend==="off"?null:c}function Ye(t){const c=t?.redaction?.detection,d=t?.redaction?.tier==="full"?"full":"basic";if(c&&c.backend&&c.backend!=="off")return{source:"external",backend:c.backend,state:"external",model:c.model||null,ready:!0,tier:d,coverage:d==="full"?"names":"patterns"};const m=E.health(),f=m.ok&&d==="full";return{source:"bundled",state:m.state,model:m.model||t?.ner?.model||null,installed:E.modelOnDisk(t?.ner?.model||void 0),error:m.error||null,ready:f,tier:d,coverage:f?"names":"patterns"}}async function Ht(t){if(E.state()!=="off"){const d=E.health();return{configured:d.configured,ok:d.ok,state:d.state,model:d.model,error:d.error||null,url:d.configured?`http://${t.host}:${t.port}/ner`:null,stats:d.stats,companions:d.companions}}const c=Gt(t);if(!c)return{configured:!1,ok:!1,url:null,model:null};try{const d=await Ee(c.replace(/\/ner\/?$/,"")+"/health",{signal:AbortSignal.timeout(2e3)});if(!d.ok)return{configured:!0,ok:!1,url:c,model:null};const m=await d.json().catch(()=>({}));return{configured:!0,ok:!0,url:c,model:m.model||null}}catch{return{configured:!0,ok:!1,url:c,model:null}}}function cn(t,c){const d={};for(const[m,f]of Object.entries(t)){const g=m.toLowerCase();g.startsWith("x-chatpanel-")||Rt.has(g)||(d[m]=f)}d["accept-encoding"]="identity";try{d.host=new URL(c).host}catch{}return d}async function Vt(t,c,d,m){const f=st(c.vault);t.on("close",()=>{t.writableFinished||Se(c.id)});const g=m?m.clock():0;let $=g,S=!0;const x=()=>{m&&S&&(m.lap("upstream",g),$=m.clock(),S=!1)};await So(c,{onText:D=>{x(),Le(c.id);const _=f.push(D);_&&t.write(d.sseDelta(_))},onToolRequest:({name:D,restoredArgs:_,toolId:F})=>{x(),Le(c.id);const R=f.flush();R&&t.write(d.sseDelta(R)),t.write(d.sseToolCalls([{id:F,name:D,arguments:JSON.stringify(_)}])),t.write(d.sseToolFinish()),m&&m.lap("stream",$),t.end(),m?.commit()},onDone:()=>{const D=f.flush();D&&t.write(d.sseDelta(D)),t.write(d.sseTail()),m&&m.lap("stream",$),t.end(),Se(c.id),m?.commit()},onError:D=>{t.write(`data: ${JSON.stringify({error:{message:D.message,type:"bridge_error"}})}
|
|
15
15
|
|
|
16
|
-
`),t.end(),Se(c.id),m?.commit()}})}async function
|
|
16
|
+
`),t.end(),Se(c.id),m?.commit()}})}async function dn(t,c,{kind:d,adapter:m,agent:f,run:g=null},$,S,x,D,_,F=null,R=null){const{messages:L,system:ie}=m.toTurn($),{agentModel:re}=Ze($?.model,x),n=Pt(x,{...re?{model:re}:{},...g||{}}),o=de(x.bridge.token),p=Je(d,$?.model||f),l={tier:x.redaction.tier==="full"?"full":"basic",dictionary:eo(x.redaction,D),entities:[]},C=await ye(x),Z=ko({vault:S,redactOpts:l,bridgeUrl:C,token:o,harness:F});let q;try{q=await vo({bridgeUrl:C,agent:f,token:o,messages:L,system:ie,specs:xo(_),options:n,signal:void 0,approvals:_o(_)})}catch(v){return Se(Z.id),R?.commit(),s(c,502,{error:{message:`bridge: ${v.message}`,type:"bridge_error"}})}return Z.reader=q.body.getReader(),c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(p.sseHead()),Vt(c,Z,p,R)}async function un(t,c,d,m,f=null){Le(c.id),c.rounds=(c.rounds||0)+1;try{const $=f?f.clock():0;await To(c,d),f&&f.lap("redact",$)}catch($){return Se(c.id),f?.commit(),s(t,502,{error:{message:`tool-result: ${$.message}`,type:"bridge_error"}})}const g=Je("openai",m||"codex");return t.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),t.write(g.sseHead()),Vt(t,c,g,f)}async function mn(t,c,{kind:d,adapter:m,redactable:f,pathname:g,agentOverride:$,harness:S,trace:x,run:D=null},_,F,R,L){if(!f)return x?.commit(),s(c,404,{error:`endpoint ${g} not supported by the bridge backend`});if(d==="openai"){const V=m.extractLatestToolResult(_);if(V){const U=dt(V.tool_call_id),Y=U&&ct(U.gwId);if(Y)return un(c,Y,V.content,_?.model,x)}const ne=m.extractTools(_);if(ne.length&&_?.stream===!0)return dn(t,c,{kind:d,adapter:m,agent:$||zt(_?.model,R),run:D},_,F,R,L,ne,S,x)}const{messages:ie,system:re}=m.toTurn(_),n=$||zt(_?.model,R),o=_?.stream===!0,p=Je(d,_?.model||n),l=de(R.bridge.token),C=new AbortController;c.on("close",()=>{c.writableFinished||C.abort()});const{agentModel:Z}=Ze(_?.model,R),q={bridgeUrl:await ye(R),agent:n,token:l,messages:ie,system:re,signal:C.signal,options:Pt(R,{...Z?{model:Z}:{},...D||{}})};if(!o)try{let V="";const ne=x?x.clock():0;await lt(q,H=>{V+=H}),x&&x.lap("upstream",ne);const U=x?x.clock():0,Y=p.full(qt(V,F));return x&&x.lap("restore",U),c.writeHead(200,{"content-type":p.contentType}),c.end(Y),x?.commit()}catch(V){return x?.commit(),s(c,502,{error:{message:`bridge backend failed: ${V.message}`,type:"bridge_error"}})}c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(p.sseHead());const v=st(F),le=x?x.clock():0;let ve=le;try{let V=!0;await lt(q,U=>{x&&V&&(x.lap("upstream",le),ve=x.clock(),V=!1);const Y=v.push(U);Y&&c.write(p.sseDelta(Y))},p.sseActivity?U=>{try{c.write(p.sseActivity(Xt(U,F)))}catch{}}:null);const ne=v.flush();ne&&c.write(p.sseDelta(ne)),c.write(p.sseTail())}catch(V){c.write(`data: ${JSON.stringify({error:{message:V.message,type:"bridge_error"}})}
|
|
17
17
|
|
|
18
|
-
`)}x&&x.lap("stream",ve),c.end(),x?.commit()}function
|
|
18
|
+
`)}x&&x.lap("stream",ve),c.end(),x?.commit()}function pn(t,c,d=""){const m=String(t||"").replace(/\/+$/,""),f=String(c||"").split("/")[1];return f&&m.endsWith(`/${f}`)?m.slice(0,-(f.length+1))+c+d:m+c+d}const hn=9e4;function yn(t,c,d){if(c===d)return t;const m=c/d,f=new Float32Array(Math.floor(t.length/m));for(let g=0;g<f.length;g++){const $=g*m,S=Math.floor($),x=Math.min(t.length-1,S+1),D=$-S;f[g]=t[S]*(1-D)+t[x]*D}return f}const fn=["/tts","/stt","/ner","/diarize","/skills","/redact","/config","/logs","/status","/admin"];function Xe(t,c){const d=new URLSearchParams;for(const g of t.searchParams.getAll("dir"))g&&d.append("dir",g);const m=t.searchParams.get("workdir")||String(c?.bridge?.workingDir||"").trim();m&&d.set("workdir",m);const f=d.toString();return f?`?${f}`:""}async function gn(t,c,{adapter:d,kind:m,pathname:f,search:g,base:$,destKey:S,destProtocol:x,harness:D,trace:_},F,R){let L;const ie=_?_.clock():0;try{const p=cn(t.headers,$);S&&(x==="anthropic"?(p["x-api-key"]=S,delete p.authorization):p.authorization=`Bearer ${S}`);const l=so(pn($,f,g)).toString();L=await fetch(l,{method:t.method,headers:p,body:["GET","HEAD"].includes(t.method)?void 0:F})}catch(p){return _?.commit(),s(c,502,{error:`upstream fetch failed: ${p.message}`})}const re=L.headers.get("content-type")||"",n={};if(L.headers.forEach((p,l)=>{Rt.has(l.toLowerCase())||(n[l]=p)}),re.includes("text/event-stream")&&L.body){_&&_.lap("upstream",ie);const p=_?_.clock():0;c.writeHead(L.status,n);const l=m==="openai"?Yt(L.body,c,R,D):Zt(L.body,c,R);return Promise.resolve(l).finally(()=>{_&&_.lap("stream",p),_?.commit()})}const o=Buffer.from(await L.arrayBuffer());if(_&&_.lap("upstream",ie),R&&re.includes("application/json"))try{const p=_?_.clock():0,l=d.restoreResponse(JSON.parse(o.toString("utf8")),R,D);return _&&_.lap("restore",p),c.writeHead(L.status,{...n,"content-type":"application/json"}),c.end(Buffer.from(JSON.stringify(l),"utf8")),_?.commit()}catch{}c.writeHead(L.status,n),c.end(o),_?.commit()}function wn(t=nt()){let c=null;const d=()=>{if(!c){const n=t.read||{};c=pr({remote:n.remote?.url?{url:n.remote.url,key:n.remote.key||""}:null,defaultProvider:n.provider||"defuddle"})}return c};let m=null;const f=()=>(m||(m=ar({wrap:(n,o,p,l)=>ir().wrap(n,o,p,l),onLog:n=>console.warn(`[extract worker] ${n}`)})),m);let g={at:0,fn:()=>"unknown"},$=null;async function S(){if(Date.now()-g.at<1e4)return g.fn;let n=new Map;try{const l=await D().health();for(const[C,Z]of Object.entries(l)){const q=(t.destinations||[]).filter(v=>v?.service===C).flatMap(v=>[v.id,...v.models||[]]);for(const v of[C,...q])n.set(v,Z)}}catch{n=new Map}const o=l=>n.get(l)||"unknown",p=new Map((t.destinations||[]).filter(l=>l?.service).map(l=>[l.id,l.service]));return o.window=l=>{try{return D().contextWindow(p.get(l)||l)}catch{return null}},o.card=l=>{try{return D().modelCard(p.get(l)||l)}catch{return null}},o.sig=JSON.stringify([...n.entries()].sort()),g={at:Date.now(),fn:o},g.fn}let x=null;const D=()=>(x||(x=cr({cfg:t,bridgeHealth:async()=>{const n=await ye(t);if(!n)return null;const o=de(t.bridge?.token),p=await fetch(`${n}/health`,{headers:{Accept:"application/json",...o?{Authorization:`Bearer ${o}`}:{}},signal:AbortSignal.timeout(4e3)});return p.ok?p.json():null},persist:()=>{try{me(t,se())}catch(n){console.warn(`[runtime] could not persist config: ${n.message}`)}},stateDir:Et.join(Et.dirname(se()),"runtime"),workers:()=>{const n=m?.status();return n?.running?[{id:"extract",kind:"worker",engine:"extract",command:"extract worker",label:"document extractor",pid:n.pid,sandbox:n.sandbox,refused:[]}]:[]},log:n=>console.log(n)})),x),_=dr({cfg:t});let F=null;const R=()=>{if(!F){const n=t.search||{},o=n.searxng?.url?gr({url:n.searxng.url,token:n.searxng.token||"",engines:n.searxng.engines||"",safesearch:n.searxng.safesearch??null}):null;F=hr({reader:d(),searxng:o,defaultProvider:n.provider||"auto",redact:async p=>{let l=p;return await $e([Re(()=>l,C=>{l=C})],{...t.redaction,tier:"basic"},{isPro:!0}),l}})}return F};co(t.allowedExtensionIds||[]);const L=[],ie=n=>{L.push(n),L.length>50&&L.shift()},re=Wt(async(n,o)=>{const p=new URL(n.url,"http://127.0.0.1"),l=p.pathname;if(!It(n.headers.host))return s(o,403,{error:"loopback only"});if(!en(n.headers.origin,t))return s(o,403,{error:"origin not allowed"});if(n.headers.origin&&tn(o,n.headers.origin),n.method==="OPTIONS")return o.writeHead(204),o.end();if(l==="/admin/token"&&n.method==="POST")return X(n)?s(o,200,{token:Ie()}):s(o,403,{error:"admin: extension origin or gateway token required"});if(l==="/pair/code"&&n.method==="POST"){if(!X(n))return s(o,403,{error:"pair/code: extension origin or gateway token required"});const e=uo();return console.log("[gateway] pairing code issued — valid for 5 minutes, one use"),s(o,200,{ok:!0,...e})}if(l==="/pair"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=mo(e?.code);if(!r.ok)return console.log(`[gateway] pairing refused (${r.reason}) from ${Pe(n)} caller`),s(o,403,{error:r.reason});console.log(`[gateway] paired a ${Pe(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`);const a=de(t.bridge?.token);return s(o,200,{ok:!0,token:lo()||Ie(),...a?{bridgeToken:a}:{}})}if(l==="/whoami"&&n.method==="POST"){const e=Pe(n);return s(o,200,{ok:!0,trust:e,paired:io(e),version:ee})}if(l==="/audit"&&n.method==="GET")return X(n)?s(o,200,ho(t,{version:ee,startedAt:Lt,managed:ke()})):s(o,403,{error:"audit: extension origin or gateway token required"});if((l==="/config"||l==="/logs"||l==="/update"&&n.method!=="GET")&&!X(n))return s(o,403,{error:"admin route: extension origin or gateway token required"});if(l==="/update"&&n.method==="GET"){const e=await zo(ee,{force:p.searchParams.get("force")==="1"}).catch(r=>({current:ee,updateAvailable:!1,error:String(r?.message||r)}));return s(o,200,{ok:!0,update:e,job:Vo()})}if(l==="/update"&&n.method==="POST"){const e=Ho(ee);return s(o,e.already?409:202,{ok:!0,job:e})}if((l==="/v1/history/key"||l==="/v1/history/ingest-backup")&&n.method==="POST"&&!X(n))return s(o,403,{error:{message:"history key route: extension origin or gateway token required",type:"forbidden"}});if(l==="/v1/history/records"&&n.method==="PUT"&&!X(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/history/ingest"||l==="/v1/history/clear")&&n.method==="POST"&&!X(n))return s(o,403,{error:{message:"history write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/memory/remember"||l==="/v1/memory/forget"||l==="/v1/memory/sync"||l==="/v1/memory/clear")&&n.method==="POST"&&!X(n))return s(o,403,{error:{message:"memory write — extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/prefs"||l.startsWith("/v1/prefs/")||l.startsWith("/v1/teams")||l.startsWith("/v1/agents")||l.startsWith("/v1/projects"))&&!X(n))return s(o,403,{error:{message:"prefs: extension origin or gateway token required",type:"forbidden"}});if((l==="/v1/events"||l.startsWith("/v1/events/"))&&!X(n))return s(o,403,{error:{message:"events: extension origin or gateway token required",type:"forbidden"}});if(l.startsWith("/v1/observability")&&!X(n))return s(o,403,{error:{message:"observability: extension origin or gateway token required",type:"forbidden"}});if(n.method==="GET"&&l==="/health"){const e=A.health(),r=P.health();return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,pairing:!0,...ke()?{managed:ke()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...Te?{bridge:Te.status()}:{},search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},stt:{enabled:t.stt?.enabled!==!1,state:e.state,ready:e.ok,model:e.model||t.stt?.model||Ne,runtime:e.runtime,dtype:e.dtype},tts:{enabled:t.tts?.enabled!==!1,state:r.state,ready:r.ok,model:r.model||t.tts?.model||Tt,voice:t.tts?.voice||ue,runtime:r.runtime,dtype:r.dtype},events:z?{count:z.count(),hosts:z.hosts().length}:null})}if(l==="/status"&&n.method==="GET"){Qt(t);const e=await fe(t.pro?.entitlementToken),r=await Ht(t);return s(o,200,{ok:!0,version:ee,backend:t.backend,tier:t.redaction.tier,search:{provider:t.search?.provider||"auto",searxng:!!t.search?.searxng?.url},...ke()?{managed:ke()}:{},...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},ner:{autostart:!!t.ner?.autostart,configured:r.configured,ready:r.ok,model:r.model,url:r.url},detector:Ye(t),pro:{unlocked:e},usage:Jr(t),uptimeSeconds:Math.floor((Date.now()-Lt)/1e3),update:Go(ee)})}if(l==="/v1/history/ingest"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,size:r})}catch(e){return s(o,400,{error:{message:`ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/v1/prefs"&&n.method==="GET"){const e=String(p.searchParams.get("section")||"");return p.searchParams.get("stamps")?s(o,200,{ok:!0,revision:oe.revision,stamps:oe.stamps()}):s(o,200,{ok:!0,revision:oe.revision,sections:oe.get(e)})}if(l==="/v1/prefs"&&(n.method==="POST"||n.method==="PUT"))try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=oe.put(e.sections||{},{by:e.by||""});return r.applied.length&&Dt(r.applied,e.by||""),s(o,200,{ok:!0,...r})}catch(e){return s(o,400,{error:{message:`prefs write failed: ${e.message}`,type:"prefs_error"}})}if(l==="/v1/prefs"&&n.method==="DELETE"){const e=String(p.searchParams.get("section")||""),r=e?oe.remove(e):!1;return r&&Dt([e],""),s(o,200,{ok:!0,removed:r})}if(l==="/v1/prefs/events"&&n.method==="GET"){o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const e=i=>o.write(`data: ${JSON.stringify(i)}
|
|
19
19
|
|
|
20
|
-
`);e({type:"hello",revision:oe.revision,stamps:oe.stamps()});const r=i=>e({type:"changed",...i});
|
|
20
|
+
`);e({type:"hello",revision:oe.revision,stamps:oe.stamps()});const r=i=>e({type:"changed",...i});Ke.add(r);const a=setInterval(()=>{try{o.write(`: keep-alive
|
|
21
21
|
|
|
22
|
-
`)}catch{}},25e3);o.on("close",()=>{
|
|
22
|
+
`)}catch{}},25e3);o.on("close",()=>{Ke.delete(r),clearInterval(a)});return}if(l==="/v1/projects"&&n.method==="GET")return s(o,200,{ok:!0,projects:Q.list({limit:p.searchParams.get("limit")||50,status:p.searchParams.get("status")||""})});if(l==="/v1/projects/jobs"&&n.method==="GET")return s(o,200,{ok:!0,jobs:Q.openJobs()});if(l==="/v1/projects"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,project:Q.create({id:e.id||e.project?.id,project:e.project||null,by:e.by})})}catch(e){return s(o,400,{error:{message:`project: ${e.message}`,type:"project_error"}})}{const e=/^\/v1\/projects\/([a-zA-Z0-9_-]{1,64})(\/events|\/jobs(?:\/([a-zA-Z0-9_-]{1,64})(\/applications|\/recruit)?)?)?$/.exec(l);if(e){const r=e[1],a=e[2]||"",i=e[3]||"",u=e[4]||"",w=()=>s(o,404,{error:{message:`no project ${r}`,type:"not_found"}});if(u){const y=Q.get(r);if(!y)return w();const k=y.jobs.find(h=>h.id===i);if(!k)return s(o,404,{error:{message:`no job ${i}`,type:"not_found"}});const b={cfg:t,prefsStore:oe,scorecards:we,engines:be};if(u==="/applications"&&n.method==="GET"){const h=await Io(k,{...b,reach:p.searchParams.get("reach")||"any",chatModel:p.searchParams.get("chatModel")||null});return s(o,200,{ok:!0,job:k,...h})}if(u==="/recruit"&&n.method==="POST"){if(!["open","evaluating"].includes(k.status))return s(o,400,{error:{message:`job ${i} is ${k.status}; only an open job is recruited`,type:"project_error"}});try{const h=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},O=String(h.by||"evaluator").slice(0,80),I=await Lo(k,{...b,record:y,reach:h.reach||"any",chatModel:h.chatModel||null,evaluation:h.evaluation||null,text:h.text??null,by:O});let M=null;for(const W of I.events)W.type==="job.updated"?M=Q.updateJob(r,i,W.job,{by:W.by||O}):M=Q.append(r,[W]);return s(o,200,{ok:!0,project:M,decision:I.decision,applications:I.applications,evaluation:I.evaluation})}catch(h){return s(o,400,{error:{message:`recruit: ${h.message}`,type:"project_error"}})}}return s(o,405,{error:{message:"method not allowed",type:"project_error"}})}if(!a&&n.method==="GET"){const y=Q.get(r,{events:p.searchParams.get("events")==="1"});return y?s(o,200,{ok:!0,project:y}):w()}if(!a&&n.method==="DELETE")return s(o,200,{ok:!0,removed:Q.remove(r)});if(n.method==="POST"&&(a==="/events"||a.startsWith("/jobs")))try{const y=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},k=String(y.by||"person").slice(0,80),b=a==="/events"?Q.append(r,y.events||[]):i?Q.updateJob(r,i,y.patch||y,{by:k}):Q.postJob(r,y.job||y,{by:k});return s(o,200,{ok:!0,project:b})}catch(y){return s(o,y.message.startsWith("no ")?404:400,{error:{message:`project: ${y.message}`,type:"project_error"}})}if(a==="/events"&&n.method==="GET"){if(!Q.get(r))return w();o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const y=O=>o.write(`data: ${JSON.stringify(O)}
|
|
23
23
|
|
|
24
24
|
`);let k=p.searchParams.has("after")?Number(p.searchParams.get("after")):-1;y({seq:-1,type:"hello",at:Date.now(),payload:{project:Q.get(r),after:k}});const b=Q.watch(r,O=>{O.seq>k&&(k=O.seq,y(O))});for(const O of Q.eventsSince(r,k))k=O.seq,y(O);const h=setInterval(()=>{try{o.write(`: keep
|
|
25
25
|
|
|
26
|
-
`)}catch{}},25e3);n.on("close",()=>{clearInterval(h),b()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:we.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(l);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await we.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await we.append({agentId:r,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return be.fromRating(we.chains.get(r)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(l==="/v1/capabilities"&&n.method==="GET")return s(o,200,
|
|
26
|
+
`)}catch{}},25e3);n.on("close",()=>{clearInterval(h),b()});return}}}if(l==="/v1/agents/scorecards"&&n.method==="GET")return s(o,200,{ok:!0,agents:we.list()});{const e=/^\/v1\/agents\/([a-zA-Z0-9_.:@+-]{1,120})\/scorecard$/.exec(l);if(e){const r=decodeURIComponent(e[1]);if(n.method==="GET")return s(o,200,{ok:!0,...await we.get(r)});if(n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=await we.append({agentId:r,kind:"rating",runId:a.runId,taskId:a.taskId,jobId:a.jobId,rating:{by:String(a.by||"person").slice(0,40),score:a.score,note:a.note,about:a.about},refs:a.refs});return be.fromRating(we.chains.get(r)||[],{...i,jobKind:a.jobKind?String(a.jobKind).slice(0,60):void 0}),s(o,200,{ok:!0,entry:i})}catch(a){return s(o,400,{error:{message:`scorecard: ${a.message}`,type:"scorecard_error"}})}}}if(l==="/v1/capabilities"&&n.method==="GET")return s(o,200,nr(t,{version:ee,reader:c,searcher:F,extract:f(),proxy:_}));if(l==="/v1/fusions"&&n.method==="GET"){const e={active:E.health().model||t.ner?.model||null,companions:E.companions()};let r=null;try{r=await D().status()}catch{r=null}return s(o,200,Zo({cfg:t,ner:e,runtimeDoc:r}))}if(l==="/v1/runtime"&&n.method==="GET")return s(o,200,await D().status());{const e=/^\/v1\/runtime\/(engines|services)\/([a-z0-9-]+)$/.exec(l);if(e&&n.method==="POST"){if(!X(n))return s(o,403,{error:"runtime: extension origin or gateway token required"});let r={};try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{r={}}const a=String(r.action||"start"),i=D(),u=e[1]==="engines"?a==="start"?await i.startEngine(e[2]):{ok:!1,error:`unknown action ${a}`}:a==="start"?await i.startService(e[2]):a==="stop"?await i.stopService(e[2]):a==="model"?await i.setModel(e[2],r.model):a==="tune"?await i.setTunings(e[2],r.tunings):a==="profile"?await i.setProfile(e[2],r.profile):a==="pull"?await i.pullModel(e[2]):a==="install"?await i.installRunner(e[2]):a==="cancel"?i.cancelJob(e[2]):{ok:!1,error:`unknown action ${a}`};return s(o,u.ok?200:400,u)}}if((l==="/v1/rerank"||l==="/v1/decide")&&n.method==="POST"){const e=l.slice(4);let r;try{r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:`${e}: body must be JSON`,type:"invalid_request"}})}const a=await _.call(e,r);return s(o,a.status,a.body)}if(l==="/v1/detect"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"detect: body must be JSON",type:"invalid_request"}})}try{const r=await sr(e,{ensure:()=>Ae(t),model:E.health().model});return s(o,r.status,r.body)}catch(r){return s(o,500,{error:{message:`detect: ${r.message}`,type:"detector_error"}})}}if(l==="/v1/extract"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,Math.max(t.maxBodyBytes,Math.ceil(mr*4/3)+1024))).toString("utf8"))}catch{return s(o,400,{error:{message:"extract: body must be JSON",type:"invalid_request"}})}const r=await ur(e,{service:f()});return s(o,r.status,r.body)}if(l==="/v1/read"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"read: body must be JSON",type:"invalid_request"}})}const r=await d().read(e);return s(o,r.status,r.body)}if(l==="/v1/search"&&n.method==="POST"){let e;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{return s(o,400,{error:{message:"search: body must be JSON",type:"invalid_request"}})}const r=await R().search(e);return s(o,r.status,r.body)}if(/^\/v1\/search\/./.test(l)&&n.method==="GET"){let e;try{e=decodeURIComponent(l.slice(11))}catch{e=l.slice(11)}const r=p.searchParams.has("read")?Math.max(0,Math.min(10,Number(p.searchParams.get("read"))||0)):fr.aliasRead,a=await R().search({q:e,read:r,limit:Math.max(r,5)});return s(o,a.status,a.status===200?yr(a.body):a.body)}if(/^\/v1\/read\/./.test(l)&&n.method==="GET"){const e=String(n.url||"").slice(9),r=/^https?:\/\//i.test(e)?e:decodeURIComponent(e),a=/application\/json/i.test(n.headers.accept||""),i=/^text$/i.test(n.headers["x-return-format"]||"")?"text":"markdown",u=await d().read({url:r,format:i});return u.status!==200||a?s(o,u.status,u.status===200?{code:200,status:2e4,data:u.body}:u.body):(o.writeHead(200,{"content-type":"text/plain; charset=utf-8","x-chatpanel-provider":u.body.provider}),o.end(wr(u.body)))}if(l==="/v1/engines"&&n.method==="GET"){const e=Number(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,engines:be.list({minCalls:e})})}{const e=/^\/v1\/engines\/(.+)\/(card|entries)$/.exec(l);if(e){const r=decodeURIComponent(e[1]).slice(0,300);if(e[2]==="card"&&n.method==="GET"){const a=Number(p.searchParams.get("minCalls"))||void 0;return s(o,200,{ok:!0,...await be.get(r,{entries:p.searchParams.get("entries")==="1",minCalls:a})})}if(e[2]==="entries"&&n.method==="POST")try{const a=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},i=a.engine||rn(r);if(!i)return s(o,400,{error:{message:"model-ledger: engine required",type:"model_ledger_error"}});const u=await be.append({...a,engine:i,kind:a.kind||"call"});return u.key!==r?s(o,400,{error:{message:`model-ledger: entry is for ${u.key}, not ${r}`,type:"model_ledger_error"}}):s(o,200,{ok:!0,entry:u})}catch(a){return s(o,400,{error:{message:`model-ledger: ${a.message}`,type:"model_ledger_error"}})}}}if(l==="/v1/teams/runs"&&n.method==="GET")return s(o,200,{ok:!0,runs:G.list({limit:p.searchParams.get("limit")||50,team:p.searchParams.get("team")||""})});if(l==="/v1/teams/runs"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:G.create({id:e.id,client:e.client,team:e.team,request:e.request})})}catch(e){return s(o,400,{error:{message:`team run: ${e.message}`,type:"team_error"}})}{const e=/^\/v1\/teams\/runs\/([a-zA-Z0-9_-]{4,64})(\/events|\/stop|\/answer|\/decide|\/post|\/handoff|\/checkpoint|\/claim|\/threads\/[a-zA-Z0-9_:-]{1,80})?$/.exec(l);if(e){const r=e[1],a=e[2]||"";if(!a&&n.method==="GET"){const i=G.get(r,{events:p.searchParams.get("events")==="1"});return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(!a&&n.method==="DELETE")return G.stop(r),s(o,200,{ok:!0,removed:G.remove(r)});if(a==="/stop"&&n.method==="POST"){const i=G.stop(r);return i?s(o,200,{ok:!0,run:i}):s(o,404,{error:{message:`no run ${r}`,type:"not_found"}})}if(a==="/checkpoint"&&n.method==="GET")try{return s(o,200,{ok:!0,checkpoint:G.checkpoint(r)})}catch(i){return s(o,404,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/handoff"||a==="/claim")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=a==="/handoff"?G.handoff(r,{taskId:i.taskId,model:i.model,by:i.by,reason:i.reason}):G.claim(r,{client:i.client});return s(o,200,{ok:!0,run:u})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a.startsWith("/threads/")&&n.method==="DELETE")try{return s(o,200,{ok:!0,run:G.removeThread(r,{threadId:a.slice(9),by:"person"})})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if((a==="/answer"||a==="/decide"||a==="/post")&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},u=String(i.by||"person").slice(0,40),w=a==="/answer"?G.answer(r,{threadId:i.threadId,text:i.text,by:u}):a==="/decide"?G.decide(r,{postId:i.postId,status:i.status,by:u}):G.post(r,{threadId:i.threadId,text:i.text,by:u,kind:i.kind,replyTo:i.replyTo});return s(o,200,{ok:!0,run:w})}catch(i){return s(o,i.message.startsWith("no ")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="POST")try{const i=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};return s(o,200,{ok:!0,run:G.append(r,i.events||[])})}catch(i){return s(o,i.message.startsWith("no run")?404:400,{error:{message:`team run: ${i.message}`,type:"team_error"}})}if(a==="/events"&&n.method==="GET"){if(!G.get(r))return s(o,404,{error:{message:`no run ${r}`,type:"not_found"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=b=>o.write(`data: ${JSON.stringify(b)}
|
|
27
27
|
|
|
28
28
|
`),u=p.searchParams.has("after")?Number(p.searchParams.get("after")):NaN;let w=Number.isFinite(u)?u:-1;i({seq:-1,type:"hello",at:Date.now(),payload:{run:G.get(r),after:w}});const y=G.watch(r,b=>{b.seq==null?i(b):b.seq>w&&(w=b.seq,i(b))});for(const b of G.eventsSince(r,w))w=b.seq,i(b);const k=setInterval(()=>{try{o.write(`: keep-alive
|
|
29
29
|
|
|
30
|
-
`)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:te.size,memories:te.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:te.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:te.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=te.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:te.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:te.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:te.clear(),size:te.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=
|
|
30
|
+
`)}catch{}},25e3);o.on("close",()=>{y(),clearInterval(k)});return}}}if(l==="/v1/memory/list"&&n.method==="GET")return s(o,200,{ok:!0,size:te.size,memories:te.list()});if(l==="/v1/memory/recall"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.recall({text:String(e.text||""),scopes:Array.isArray(e.scopes)&&e.scopes.length?e.scopes.map(String):["global"],limit:Number(e.limit)||0,maxChars:Number(e.maxChars)||0});return s(o,200,{ok:!0,size:te.size,...r})}catch(e){return s(o,400,{error:{message:`recall failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/remember"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.remember({text:String(e.text||""),kind:e.kind?String(e.kind):"fact",scope:e.scope?String(e.scope):"global",tags:Array.isArray(e.tags)?e.tags.map(String):[],source:{via:String(e.source?.via||"mcp"),surface:String(e.source?.surface||"mcp"),agent:String(e.source?.agent||""),ref:String(e.source?.ref||"")}});return s(o,200,{ok:!0,action:r.action,record:r.record,replaced:r.replaces||null,size:te.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/forget"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},{removed:r}=te.forget(String(e.query||""));return s(o,200,{ok:!0,removed:r,size:te.size})}catch(e){return s(o,400,{error:{message:e.message,type:"memory_error"}})}if(l==="/v1/memory/sync"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=te.bulk({upserts:Array.isArray(e.upserts)?e.upserts:[],removes:Array.isArray(e.removes)?e.removes:[]});return s(o,200,{ok:!0,...r,memories:te.list()})}catch(e){return s(o,400,{error:{message:`memory sync failed: ${e.message}`,type:"memory_error"}})}if(l==="/v1/memory/clear"&&n.method==="POST")return s(o,200,{ok:!0,dropped:te.clear(),size:te.size});if(l==="/v1/history/clear"&&n.method==="POST"){const e=N.clear();return s(o,200,{ok:!0,dropped:e,size:N.size})}if(l==="/v1/history/search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=N.search(String(e.query||""),{limit:Number(e.limit)||10,offset:Math.max(0,Number(e.offset)||0),type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null});return s(o,200,{ok:!0,size:N.size,newest:N.newest,results:r})}catch(e){return s(o,400,{error:{message:`search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/smart-search"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=String(e.question||e.query||""),a=Wr(r,{extra:Array.isArray(e.queries)?e.queries.map(String):[],max:Math.min(6,Math.max(1,Number(e.maxQueries)||4))}),i={type:e.type?String(e.type):null,since:e.since!=null?Number(e.since):null,before:e.before!=null?Number(e.before):null},u=Math.min(30,Math.max(5,Number(e.limit)||10)*2),w=await Kr(a,k=>N.search(k,{limit:u,...i}),{limit:Math.min(50,Math.max(1,Number(e.limit)||10))}),y=i.type?w:[...w.filter(k=>k.type==="brief"),...w.filter(k=>k.type!=="brief")];return s(o,200,{ok:!0,size:N.size,newest:N.newest,queries:a,results:y})}catch(e){return s(o,400,{error:{message:`smart search failed: ${e.message}`,type:"search_error"}})}if(l==="/v1/history/related"&&n.method==="GET"){const e=String(p.searchParams.get("id")||""),r=Math.min(30,Math.max(1,Number(p.searchParams.get("limit"))||5));return s(o,200,{ok:!0,results:N.related(e,{limit:r})})}if(l==="/v1/history/status"&&n.method==="GET")return s(o,200,{ok:!0,size:N.size,newest:N.newest,bytes:N.bytes,lossless:N.lossless?{records:N.lossless.size,newest:N.lossless.newest}:null});if(l==="/v1/observability"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||200));return s(o,200,{ok:!0,storage:{warm:{records:N.size,bytes:N.bytes,newest:N.newest}},access:Qe.snapshot(e)})}if(l==="/v1/observability/access"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Qe.push(Nt({ts:Date.now(),...e}));return s(o,200,{ok:!0,event:r})}catch(e){return s(o,400,{error:{message:`access log failed: ${e.message}`,type:"observability_error"}})}if(l==="/v1/history/records"&&n.method==="PUT"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});try{const r=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},a=String(r.host||"").slice(0,80),i=Number(r.at)||Date.now(),u=[];let w=0;const y={upserts:[],removes:[]},k=b=>{if(!b||b.deletedAt){b?.id&&y.removes.push(b.id);return}try{const h=Xo(b);h&&y.upserts.push(h)}catch{}};if(Array.isArray(r.records)){const b=e.upsert(r.records,{host:a,at:i});u.push(...b);for(const h of r.records)b.includes(h?.id)&&k(h)}if(Array.isArray(r.entries)){const b=ze(),h=b?tr((M,W)=>qo(b,{salt:M,iterations:W})):null,O=async M=>{if(!h||!M.blob)return null;const W=await h(M.blob),he=M.blob.compression&&M.blob.compression!=="none"?or(rr,M.blob.compression):null;return er(M.blob,W,{codec:he})},I=await e.upsertEntries(r.entries,{open:O});u.push(...I.written),w+=I.sealed;for(const M of I.written)k(e.get(M))}return(y.upserts.length||y.removes.length)&&N.bulk(y),u.length&&Ce({ids:u}),s(o,200,{ok:!0,written:u.length,ids:u,sealed:w,size:e.size})}catch(r){return s(o,400,{error:{message:`records failed: ${r.message}`,type:"ingest_error"}})}}if(l==="/v1/events"&&n.method==="POST"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{},r=Array.isArray(e)?e:e.events;if(!Array.isArray(r))return s(o,400,{error:{message:"events: an array of CloudEvents (or { events: [...] }) required",type:"invalid_request_error"}});if(r.length>2e3)return s(o,413,{error:{message:"events: at most 2000 per batch",type:"invalid_request_error"}});const a=Wo(z,r);return s(o,200,{ok:!0,appended:a.appended,duplicates:a.duplicates,rejected:a.rejected,cursor:z.cursor()})}catch(e){return s(o,400,{error:{message:`events: ${e?.message||e}`,type:"invalid_request_error"}})}}if(l==="/v1/events/cursor"&&n.method==="GET")return z?s(o,200,{ok:!0,cursor:z.cursor(),count:z.count()}):s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});if(l==="/v1/events/stats"&&n.method==="GET"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});const e=Ko(z.all());return s(o,200,{ok:!0,stats:e,year:Qo(e)})}if(l==="/v1/events"&&n.method==="GET"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e={};try{e=pt(JSON.parse(p.searchParams.get("cursor")||"{}"))}catch{return s(o,400,{error:{message:"events: cursor must be JSON { host: seq }",type:"invalid_request_error"}})}const r=z.since(e,{limit:Number(p.searchParams.get("limit"))||void 0,host:p.searchParams.get("host")||null});return s(o,200,{ok:!0,events:r.events.map(a=>He(a)),cursor:r.cursor,more:r.more})}if(l==="/v1/events/stream"&&n.method==="GET"){if(!z)return s(o,501,{error:{message:"the event log needs SQLite",type:"unavailable"}});let e=null;if(p.searchParams.has("cursor"))try{e=pt(JSON.parse(p.searchParams.get("cursor")||"{}"))}catch{e={}}if(o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
31
31
|
data: ${JSON.stringify({cursor:z.cursor(),count:z.count(),version:ee})}
|
|
32
32
|
|
|
33
33
|
`),ge.add(o),n.on("close",()=>ge.delete(o)),e){let r={cursor:e,more:!0};for(;r.more;){r=z.since(r.cursor);for(const a of r.events)o.write(`event: cloudevent
|
|
34
|
-
data: ${JSON.stringify(
|
|
34
|
+
data: ${JSON.stringify(He(a))}
|
|
35
35
|
|
|
36
36
|
`)}}return}if(l==="/v1/history/stream"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),o.write(`event: hello
|
|
37
37
|
data: ${JSON.stringify({newest:e.newest,size:e.size,version:ee,prefsRevision:oe.revision})}
|
|
38
38
|
|
|
39
|
-
`),ae.add(o),n.on("close",()=>ae.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(p.searchParams.get("since"))||0,cursor:p.searchParams.get("cursor")||"",limit:Number(p.searchParams.get("limit"))||200,kind:p.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(l==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||50)),r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=p.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=p.searchParams.get("maxChars")!=null?Math.max(1,Number(p.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=N.get(String(p.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:ut()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Eo(String(e.passphrase)):Ao();const r=e.passphrase?await He(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Me(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(l==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await He(N,Je());return e.ok&&e.whole&&Me(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Gt(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ee(t),E.state()!=="off"){if(!E.isReady()){const r=E.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await E.detect(a);return s(o,200,{entities:i})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=zt(t);if(!e){const r=E.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:E.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await Pe(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(l==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ze(t)});try{let r=e;const a=await fe(t.pro?.entitlementToken);await Ee(t);const i=await Oe([je(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Lt(i.vault,"types")||[],detector:Ze(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=E.health().model||t.ner?.model||null,r=Math.round(pt.totalmem()/1048576),a=vr(ft,{totalRamMB:r}).map(i=>({...i,installed:E.modelOnDisk(i.id)}));for(const i of[e,...E.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:E.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:E.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:$o(),recommendation:dt(a,{totalRamMB:r},[]),state:E.state(),progress:E.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(pt.totalmem()/1048576),i=dt(ft.map(u=>({...u,installed:E.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(gt(u)||wt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||E.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&Ot(t,r);try{me(t,se())}catch{}return(async()=>{r&&await E.setModel(r,{onLog:w=>console.log(w)});const u=Oo(t.ner,{log:w=>console.log(w)});for(const w of E.companions())u.includes(w.model)||await E.removeCompanion(w.model);for(const w of u)await E.addCompanion(w,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});E.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:E.companions(),state:E.state()})}if(!r||!(gt(r)||wt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});Ot(t,r);try{me(t,se())}catch{}return E.setModel(r,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:r,state:E.state(),progress:E.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Ae,r=kr.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:xr})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Sr(r)||Tr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&_r(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{me(t,se())}catch{}return A.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=j.health();return s(o,200,{active:j.DIARIZE_MODEL,state:e.state,progress:j.progress(),available:[{id:j.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:j.modelOnDisk()}]})}if(n.method==="POST")return j.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:j.DIARIZE_MODEL,state:j.state(),progress:j.progress()})}if(l==="/tts/models"){if(n.method==="GET"){const e=P.health().model||t.tts?.model||xt(Ve()),r=Ve(),a=bt.find(u=>u.id===e)||null,i=bt.map(u=>({...u,installed:P.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(u=>u.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:P.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:P.state(),progress:P.progress(),available:i,voice:t.tts?.voice||(De(e)==="pocket-tts"?Ne:ue),arch:P.arch(),supportsVoices:P.arch()?P.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:P.arch()?P.supportsCustomVoices():!!a?.customVoices,sampleRate:P.sampleRate(),voices:P.isPocket()||!P.arch()&&De(e)==="pocket-tts"?(P.builtinVoices().length?P.builtinVoices():Br).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:P.builtinVoices().includes(u)})):P.arch()&&P.arch()!=="style-tts2"?[]:Or.map(u=>({...u,installed:P.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:Er})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!($r(r)||Pr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const u=K.parseCustomVoice(a);if(!(u?!!K.getVoice(u):Be(a)||vt(a)&&kt(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&Ar(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:St,voice:ue,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=Nr(r),w=K.parseCustomVoice(t.tts.voice||""),y=!!(w&&K.getVoice(w));if(u&&!y)if(De(r)==="pocket-tts")t.tts.voice=Ne;else{const b=K.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=ue);const k=De(r)==="pocket-tts";k&&!K.parseCustomVoice(t.tts.voice||"")&&!Be(t.tts.voice)&&(t.tts.voice=Ne),!k&&Be(t.tts.voice)&&(t.tts.voice=ue)}i&&(t.tts.dtype=i==="auto"?null:i);try{me(t,se())}catch{}return r&&P.setModel(r,{onLog:u=>console.log(u),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:P.state(),progress:P.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:K.listVoices(),usable:P.supportsCustomVoices(),embedder:j.DIARIZE_MODEL,embedderReady:j.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!K.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...K.renameVoice(i,r),usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!j.isReady()){const h=j.download({onLog:M=>console.log(M)}),O=Symbol("timeout"),I=await Promise.race([h.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(O),pn))]);if(I===O||!j.isReady())return s(o,503,{error:{message:I===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${j.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:j.progress()})}const u=Float32Array.from(a),w=await j.embed(u);let y=null;try{const h=await P.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});h&&(y=await h.encodeVoice(hn(u,16e3,24e3)))}catch(h){console.log(`[tts] pocket conditioning unavailable for this voice (${h.message})`)}const k=i?K.replaceVoice(i,{vec:w,pocket:y}):K.saveVoice({name:r,vec:w,pocket:y}),b=i&&r&&r!==k.name?K.renameVoice(i,r):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${b.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...b,usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=p.searchParams.get("id")||"",r=K.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=K.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ue;try{me(t,se())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>Tt)return s(o,413,{error:{message:`text too long (max ${Tt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Dr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ue);if(i&&!Cr(w))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:ce,contentType:J,redacted:Ce}=await Mr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await fe(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":J,"Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(Ce)}),o.end(ce)}if(!await P.ready({onLog:ce=>console.log(ce),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||xt(Ve()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:P.health().error||"tts model not ready",type:"tts_unavailable"}});const b=jr({requested:u,configured:w,engine:P,voices:K,isPocketVoice:Be,isKnownVoice:vt,isValidVoiceId:kt,defaultVoice:ue,defaultPocketVoice:Ne});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:h,customId:O,speakerEmbedding:I}=b,M=await P.synth(r,{voice:h,speed:a,speakerEmbedding:I}),W=P.sampleRate(),he=y==="pcm"?Buffer.from(new Float32Array(M).buffer):P.toWav(M,W);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(he.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),...O||P.isPocket()||P.supportsVoices()?{"X-Tts-Voice":h}:{}}),o.end(he)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=wr(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(h){return s(o,h.code===413?413:415,{error:{message:h.message,type:"bad_request"}})}const r=h=>e.find(O=>O.name===h&&!O.filename)?.data.toString("utf8").trim()||"",a=e.find(h=>h.name==="file"&&h.filename)||e.find(h=>h.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await br(a.data)}catch(h){return s(o,h.code===415?415:500,{error:{message:h.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",w=ht(t,"stt");let y=null;if(w.kind==="remote"||w.kind==="container")try{y=yt(w,{fetchImpl:Pe})}catch(h){return s(o,500,{error:{message:`stt provider: ${h.message}`,type:"bad_provider"}})}!y&&!A.isReady()&&A.init({model:t.stt?.model||Ae,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const k=r("diarize")==="true"&&t.stt?.diarize!==!1;k&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const b=Date.now();try{const{id:h}=A.createSession({lang:r("language")||void 0,diarize:k,interims:!1,remote:y}),O=[];let I=null;A.subscribe(h,J=>{J.type==="final"&&J.text?O.push(J):J.type==="language"&&(I=J.lang)});const M=16e3*5;for(let J=0;J<i.pcm.length;J+=M)A.pushAudio(h,i.pcm.subarray(J,Math.min(i.pcm.length,J+M)));await A.endSession(h);let W=0;const he=O.map((J,Ce)=>{const Vt=W,Ut=(J.durationMs||0)/1e3;return W+=Ut,{id:Ce,start:Math.round(Vt*100)/100,end:Math.round(W*100)/100,text:J.text,...J.speaker?{speaker:J.speaker}:{}}}),ce=he.map(J=>J.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ce)):u==="verbose_json"?s(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(i.seconds*100)/100,text:ce,segments:he,provider:w.kind,took_ms:Date.now()-b}):s(o,200,{text:ce})}catch(h){return s(o,h.code==="too_many_sessions"?429:500,{error:{message:h.message,type:h.code||"stt_error"}})}}if(l==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=ht(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=yt(r,{fetchImpl:Pe})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!A.isReady()&&A.init({model:t.stt?.model||Ae,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:A.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await T(n,t.maxBodyBytes);return A.pushAudio(r,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=A.getSession(r);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=h=>o.write(`data: ${JSON.stringify(h)}
|
|
39
|
+
`),ae.add(o),n.on("close",()=>ae.delete(o));return}if(l==="/v1/history/records"&&n.method==="GET"){const e=N.lossless;if(!e)return s(o,501,{error:{message:"lossless records need the SQLite warm store",type:"unavailable"}});const r=e.since({since:Number(p.searchParams.get("since"))||0,cursor:p.searchParams.get("cursor")||"",limit:Number(p.searchParams.get("limit"))||200,kind:p.searchParams.get("kind")||null});return s(o,200,{ok:!0,...r,size:e.size,newest:e.newest})}if(l==="/v1/history/list"&&n.method==="GET"){const e=Math.min(500,Math.max(1,Number(p.searchParams.get("limit"))||50)),r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=p.searchParams.get("type")||null;return s(o,200,{ok:!0,...N.list({limit:e,offset:r,type:a})})}if(l==="/v1/history/get"&&n.method==="GET"){const e=p.searchParams.get("maxChars")!=null?Math.max(1,Number(p.searchParams.get("maxChars"))||0):null,r=Math.max(0,Number(p.searchParams.get("offset"))||0),a=N.get(String(p.searchParams.get("id")||""),{maxChars:e,offset:r});return a?s(o,200,{ok:!0,record:a}):s(o,404,{error:{message:"no such record",type:"not_found"}})}if(l==="/v1/history/key"&&n.method==="GET")return s(o,200,{ok:!0,hasKey:mt()});if(l==="/v1/history/key"&&n.method==="POST")try{const e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))||{};e.passphrase?Ao(String(e.passphrase)):No();const r=e.passphrase?await Ve(N,String(e.passphrase)):{ok:!0,ingested:0};return r.ok&&r.whole&&Ce(),s(o,200,{ok:!0,hasKey:!!e.passphrase,...r})}catch(e){return s(o,400,{error:{message:`key handoff failed: ${e.message}`,type:"key_error"}})}if(l==="/v1/history/ingest-backup"&&n.method==="POST")try{const e=await Ve(N,ze());return e.ok&&e.whole&&Ce(),s(o,e.ok?200:409,e)}catch(e){return s(o,400,{error:{message:`backup ingest failed: ${e.message}`,type:"ingest_error"}})}if(l==="/ner"){if(n.method==="GET"){const e=await Ht(t);return s(o,e.ok?200:503,e)}if(n.method==="POST"){if(await Ae(t),E.state()!=="off"){if(!E.isReady()){const r=E.health();return s(o,503,{error:{message:r.state==="error"?`NER model failed to load: ${r.error||"unknown error"}`:`NER model is ${r.state} — not ready yet`,type:r.state==="error"?"ner_error":"ner_loading"},state:r.state,model:r.model})}try{const r=await T(n,t.maxBodyBytes);let a="";try{a=JSON.parse(r.toString("utf8"))?.text||""}catch{}const i=await E.detect(a);return s(o,200,{entities:i})}catch(r){return s(o,500,{error:{message:`NER error: ${r.message}`,type:"ner_error"}})}}const e=Gt(t);if(!e){const r=E.modelOnDisk(t.ner?.model||void 0);return s(o,503,{error:{message:r?"the bundled detector could not start — deterministic-only redaction":"no entity detector is installed — deterministic-only redaction (install one from Gateway settings)",type:r?"ner_error":"ner_not_installed"},state:E.state(),model:t.ner?.model||null})}try{const r=await T(n,t.maxBodyBytes),a=await Ee(e,{method:"POST",headers:{"content-type":"application/json"},body:r,signal:AbortSignal.timeout(8e3)}),i=await a.text();return o.writeHead(a.status,{"content-type":"application/json"}),o.end(i)}catch(r){return s(o,502,{error:{message:`NER unreachable: ${r.message}`,type:"ner_unreachable"}})}}}if(l==="/redact"&&n.method==="POST"){let e="";try{e=String(JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))?.text||"")}catch{e=""}if(!e)return s(o,200,{text:"",count:0,sanitized:0,entities:[],detector:Ye(t)});try{let r=e;const a=await fe(t.pro?.entitlementToken);await Ae(t);const i=await $e([Re(()=>r,u=>{r=u})],t.redaction,{isPro:a});return s(o,200,{text:r,count:i.count||0,sanitized:i.sanitized||0,tier:t.redaction?.tier==="full"?"full":"basic",entities:Jt(i.vault,"types")||[],detector:Ye(t)})}catch(r){return s(o,500,{error:{message:`redaction preview failed: ${r.message}`,type:"redact_error"}})}}if(l==="/ner/models"){if(n.method==="GET"){const e=E.health().model||t.ner?.model||null,r=Math.round(ht.totalmem()/1048576),a=kr(gt,{totalRamMB:r}).map(i=>({...i,installed:E.modelOnDisk(i.id)}));for(const i of[e,...E.modelsOnDisk()])!i||a.some(u=>u.id===i)||a.push({id:i,label:i,lang:"—",custom:!0,installed:E.modelOnDisk(i),note:"Custom model (from Hugging Face)."});return s(o,200,{active:e,companions:E.companions(),union:Array.isArray(t.ner?.union)?t.ner.union:[],machine:{totalRamMB:r},skipped:Po(),recommendation:ut(a,{totalRamMB:r},[]),state:E.state(),progress:E.progress(),available:a})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(e&&e.recommended===!0){const a=Math.round(ht.totalmem()/1048576),i=ut(gt.map(u=>({...u,installed:E.modelOnDisk(u.id)})),{totalRamMB:a},[]);e={id:i.primary,union:i.union}}const r=e&&typeof e.id=="string"?e.id.trim():null;if(e&&Array.isArray(e.union)){const a=[...new Set(e.union.map(u=>String(u||"").trim()).filter(Boolean))];for(const u of a)if(!(wt(u)||bt(u)))return s(o,400,{error:{message:`unknown or invalid model id in union: ${u}`,type:"bad_model"}});const i=r||t.ner?.model||E.health().model;t.ner=t.ner||{allowDownload:!0,enableFullTier:!0},t.ner.union=a.filter(u=>u!==i),r&&$t(t,r);try{me(t,se())}catch{}return(async()=>{r&&await E.setModel(r,{onLog:w=>console.log(w)});const u=$o(t.ner,{log:w=>console.log(w)});for(const w of E.companions())u.includes(w.model)||await E.removeCompanion(w.model);for(const w of u)await E.addCompanion(w,{onLog:y=>console.log(y),allowDownload:t.ner.allowDownload!==!1});E.setUnionOrder(u)})().catch(u=>console.log(`[ner] union update failed: ${u.message}`)),s(o,202,{accepted:!0,active:i,union:t.ner.union,companions:E.companions(),state:E.state()})}if(!r||!(wt(r)||bt(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});$t(t,r);try{me(t,se())}catch{}return E.setModel(r,{onLog:a=>console.log(a)}).then(a=>{a&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")}),s(o,202,{accepted:!0,active:r,state:E.state(),progress:E.progress()})}}if(l==="/stt/models"){if(n.method==="GET"){const e=A.health().model||t.stt?.model||Ne,r=Sr.map(a=>({...a,installed:A.modelOnDisk(a.id)}));return e&&!r.some(a=>a.id===e)&&r.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:A.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:A.state(),progress:A.progress(),available:r,dtype:t.stt?.dtype||"auto",loadedDtype:A.health().dtype,runtime:A.health().runtime,dtypes:_r})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(!r||!(Tr(r)||xr(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=typeof e.dtype=="string"&&Or(e.dtype)?e.dtype:void 0;t.stt?t.stt.model=r:t.stt={enabled:!0,model:r,allowDownload:!0},a&&(t.stt.dtype=a==="auto"?null:a);try{me(t,se())}catch{}return A.setModel(r,{onLog:i=>console.log(i),dtype:a||t.stt.dtype||"auto",warmMs:t.stt.warmMs}),s(o,202,{accepted:!0,active:r,dtype:t.stt.dtype||"auto",state:A.state(),progress:A.progress()})}}if(l==="/diarize/model"){if(n.method==="GET"){const e=j.health();return s(o,200,{active:j.DIARIZE_MODEL,state:e.state,progress:j.progress(),available:[{id:j.DIARIZE_MODEL,label:"Speaker embeddings (wavlm)",lang:"any",approxMB:100,note:"Tells voices apart for meeting transcription (who said what).",installed:j.modelOnDisk()}]})}if(n.method==="POST")return j.download({onLog:e=>console.log(e)}),s(o,202,{accepted:!0,active:j.DIARIZE_MODEL,state:j.state(),progress:j.progress()})}if(l==="/tts/models"){if(n.method==="GET"){const e=P.health().model||t.tts?.model||_t(Ue()),r=Ue(),a=vt.find(u=>u.id===e)||null,i=vt.map(u=>({...u,installed:P.modelOnDisk(u.id),unavailable:u.requiresNative&&!r?"needs the npm gateway — the standalone binary cannot load this engine":void 0}));return e&&!i.some(u=>u.id===e)&&i.push({id:e,label:e,lang:"—",tier:"custom",custom:!0,installed:P.modelOnDisk(e),note:"Custom model (from Hugging Face)."}),s(o,200,{active:e,state:P.state(),progress:P.progress(),available:i,voice:t.tts?.voice||(Me(e)==="pocket-tts"?Be:ue),arch:P.arch(),supportsVoices:P.arch()?P.supportsVoices():a?a.arch==="style-tts2"&&!!a.voices:!0,supportsCustomVoices:P.arch()?P.supportsCustomVoices():!!a?.customVoices,sampleRate:P.sampleRate(),voices:P.isPocket()||!P.arch()&&Me(e)==="pocket-tts"?(P.builtinVoices().length?P.builtinVoices():Dr).map(u=>({id:u,label:u[0].toUpperCase()+u.slice(1),lang:"en",installed:P.builtinVoices().includes(u)})):P.arch()&&P.arch()!=="style-tts2"?[]:$r.map(u=>({...u,installed:P.voiceOnDisk(u.id,e)})),dtype:t.tts?.dtype||"auto",loadedDtype:P.health().dtype,runtime:P.health().runtime,dtypes:Ar})}if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.id=="string"?e.id.trim():null;if(r&&!(Pr(r)||Er(r)))return s(o,400,{error:{message:"unknown or invalid model id",type:"bad_model"}});const a=e&&typeof e.voice=="string"?e.voice.trim():null;if(a){const u=K.parseCustomVoice(a);if(!(u?!!K.getVoice(u):De(a)||kt(a)&&St(a)))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}})}const i=e&&typeof e.dtype=="string"&&Nr(e.dtype)?e.dtype:void 0;if(t.tts||(t.tts={enabled:!0,model:Tt,voice:ue,allowDownload:!0}),r&&(t.tts.model=r),a&&(t.tts.voice=a),r&&!a){const u=Br(r),w=K.parseCustomVoice(t.tts.voice||""),y=!!(w&&K.getVoice(w));if(u&&!y)if(Me(r)==="pocket-tts")t.tts.voice=Be;else{const b=K.listVoices();t.tts.voice=b.length?`custom:${b[0].id}`:""}else!u&&y&&(t.tts.voice=ue);const k=Me(r)==="pocket-tts";k&&!K.parseCustomVoice(t.tts.voice||"")&&!De(t.tts.voice)&&(t.tts.voice=Be),!k&&De(t.tts.voice)&&(t.tts.voice=ue)}i&&(t.tts.dtype=i==="auto"?null:i);try{me(t,se())}catch{}return r&&P.setModel(r,{onLog:u=>console.log(u),dtype:i||t.tts.dtype||"auto"}),s(o,202,{accepted:!0,active:t.tts.model,voice:t.tts.voice,dtype:t.tts.dtype||"auto",state:P.state(),progress:P.progress()})}}if(l==="/tts/voices"){if(n.method==="GET")return s(o,200,{voices:K.listVoices(),usable:P.supportsCustomVoices(),embedder:j.DIARIZE_MODEL,embedderReady:j.isReady()});if(n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof e.name=="string"?e.name.trim():"",a=e&&Array.isArray(e.pcm)?e.pcm:null,i=e&&typeof e.id=="string"?e.id.trim():"";if(i){if(!K.getVoice(i))return s(o,404,{error:{message:"no such saved voice",type:"bad_voice"}});if(!a){if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});try{return s(o,200,{...K.renameVoice(i,r),usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"rename_failed"}})}}if(a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}})}else if(!r)return s(o,400,{error:{message:"a name is required",type:"bad_request"}});if(!a||a.length<16e3)return s(o,400,{error:{message:"need at least 1 second of 16 kHz mono audio",type:"sample_too_short"}});try{if(!j.isReady()){const h=j.download({onLog:M=>console.log(M)}),O=Symbol("timeout"),I=await Promise.race([h.then(()=>null).catch(M=>M),new Promise(M=>setTimeout(()=>M(O),hn))]);if(I===O||!j.isReady())return s(o,503,{error:{message:I===O?"the speaker model is still downloading (~100 MB) — your recording was kept, press Save again shortly":`the speaker model failed to load: ${j.health().error||"unknown error"}`,type:"embedder_not_ready"},progress:j.progress()})}const u=Float32Array.from(a),w=await j.embed(u);let y=null;try{const h=await P.pocketForEncoding({allowDownload:t.tts?.allowDownload!==!1,log:O=>console.log(O)});h&&(y=await h.encodeVoice(yn(u,16e3,24e3)))}catch(h){console.log(`[tts] pocket conditioning unavailable for this voice (${h.message})`)}const k=i?K.replaceVoice(i,{vec:w,pocket:y}):K.saveVoice({name:r,vec:w,pocket:y}),b=i&&r&&r!==k.name?K.renameVoice(i,r):k;return console.log(`[tts] ${i?"re-recorded":"saved"} custom voice "${b.name}" (${(k.kinds||[]).join(" + ")}, sample discarded)`),s(o,i?200:201,{...k,...b,usable:P.supportsCustomVoices()})}catch(u){return s(o,400,{error:{message:u.message,type:"save_failed"}})}}if(n.method==="DELETE"){const e=p.searchParams.get("id")||"",r=K.deleteVoice(e);if(r&&t.tts?.voice===`custom:${e}`){const a=K.listVoices();t.tts.voice=a.length?`custom:${a[0].id}`:ue;try{me(t,se())}catch{}}return s(o,200,{deleted:r,voice:t.tts?.voice})}}if((l==="/tts"||l==="/v1/audio/speech")&&n.method==="POST"){if(t.tts?.enabled===!1)return s(o,503,{error:{message:"tts is disabled in gateway config",type:"tts_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}const r=e&&typeof(e.input??e.text)=="string"?String(e.input??e.text).trim():"";if(!r)return s(o,400,{error:{message:"text is required",type:"bad_request"}});if(r.length>xt)return s(o,413,{error:{message:`text too long (max ${xt} chars)`,type:"too_long"}});const a=Number.isFinite(e.speed)?Math.min(2,Math.max(.5,e.speed)):1,i=Mr(t),u=e&&typeof e.voice=="string"&&e.voice.trim()?e.voice.trim():null,w=u||(i?i.voice:t.tts?.voice||ue);if(i&&!jr(w))return s(o,400,{error:{message:"unknown or invalid voice",type:"bad_voice"}});const y=e&&typeof e.response_format=="string"?e.response_format.toLowerCase():"wav";if(y!=="wav"&&y!=="pcm")return s(o,400,{error:{message:`unsupported response_format "${y}" — this gateway synthesizes wav`,type:"bad_format"}});try{if(i){const{audio:ce,contentType:J,redacted:je}=await Cr({dest:i,text:r,voice:w,speed:a,auth:n.headers.authorization||n.headers["xi-api-key"]||"",redaction:t.redaction,isPro:await fe(t.pro?.entitlementToken)});return o.writeHead(200,{"Content-Type":J,"Content-Length":String(ce.length),"Cache-Control":"no-store","X-Tts-Provider":i.kind,"X-Tts-Redacted":String(je)}),o.end(ce)}if(!await P.ready({onLog:ce=>console.log(ce),allowDownload:t.tts?.allowDownload!==!1,model:t.tts?.model||_t(Ue()),dtype:t.tts?.dtype||"auto"}))return s(o,503,{error:{message:P.health().error||"tts model not ready",type:"tts_unavailable"}});const b=Rr({requested:u,configured:w,engine:P,voices:K,isPocketVoice:De,isKnownVoice:kt,isValidVoiceId:St,defaultVoice:ue,defaultPocketVoice:Be});if(!b.ok)return s(o,b.status,{error:{message:b.message,type:b.type}});const{voice:h,customId:O,speakerEmbedding:I}=b,M=await P.synth(r,{voice:h,speed:a,speakerEmbedding:I}),W=P.sampleRate(),he=y==="pcm"?Buffer.from(new Float32Array(M).buffer):P.toWav(M,W);return o.writeHead(200,{"Content-Type":y==="pcm"?"application/octet-stream":"audio/wav","Content-Length":String(he.length),"Cache-Control":"no-store","X-Tts-Sample-Rate":String(W),...O||P.isPocket()||P.supportsVoices()?{"X-Tts-Voice":h}:{}}),o.end(he)}catch(k){return s(o,500,{error:{message:k.message,type:"tts_failed"}})}}if(l==="/v1/audio/transcriptions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e;try{e=br(await T(n,Math.max(t.maxBodyBytes||0,64*1024*1024)),n.headers["content-type"])}catch(h){return s(o,h.code===413?413:415,{error:{message:h.message,type:"bad_request"}})}const r=h=>e.find(O=>O.name===h&&!O.filename)?.data.toString("utf8").trim()||"",a=e.find(h=>h.name==="file"&&h.filename)||e.find(h=>h.filename);if(!a?.data?.length)return s(o,400,{error:{message:"a `file` part is required",type:"bad_request"}});let i;try{i=await vr(a.data)}catch(h){return s(o,h.code===415?415:500,{error:{message:h.message,type:"unsupported_media"}})}const u=["json","text","verbose_json"].includes(r("response_format"))?r("response_format"):"json",w=yt(t,"stt");let y=null;if(w.kind==="remote"||w.kind==="container")try{y=ft(w,{fetchImpl:Ee})}catch(h){return s(o,500,{error:{message:`stt provider: ${h.message}`,type:"bad_provider"}})}!y&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const k=r("diarize")==="true"&&t.stt?.diarize!==!1;k&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:h=>console.log(h)});const b=Date.now();try{const{id:h}=A.createSession({lang:r("language")||void 0,diarize:k,interims:!1,remote:y}),O=[];let I=null;A.subscribe(h,J=>{J.type==="final"&&J.text?O.push(J):J.type==="language"&&(I=J.lang)});const M=16e3*5;for(let J=0;J<i.pcm.length;J+=M)A.pushAudio(h,i.pcm.subarray(J,Math.min(i.pcm.length,J+M)));await A.endSession(h);let W=0;const he=O.map((J,je)=>{const Ut=W,Ft=(J.durationMs||0)/1e3;return W+=Ft,{id:je,start:Math.round(Ut*100)/100,end:Math.round(W*100)/100,text:J.text,...J.speaker?{speaker:J.speaker}:{}}}),ce=he.map(J=>J.text).join(" ").replace(/\s+/g," ").trim();return u==="text"?(o.writeHead(200,{"content-type":"text/plain; charset=utf-8"}),o.end(ce)):u==="verbose_json"?s(o,200,{task:"transcribe",language:I||r("language")||null,duration:Math.round(i.seconds*100)/100,text:ce,segments:he,provider:w.kind,took_ms:Date.now()-b}):s(o,200,{text:ce})}catch(h){return s(o,h.code==="too_many_sessions"?429:500,{error:{message:h.message,type:h.code||"stt_error"}})}}if(l==="/stt/sessions"&&n.method==="POST"){if(t.stt?.enabled===!1)return s(o,403,{error:{message:"STT disabled in gateway config",type:"stt_disabled"}});let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8")||"{}")}catch{e=null}const r=yt(t,"stt");let a=null;if(r.kind==="remote"||r.kind==="container")try{a=ft(r,{fetchImpl:Ee})}catch(u){return s(o,500,{error:{message:`stt provider: ${u.message}`,type:"bad_provider"}})}!a&&!A.isReady()&&A.init({model:t.stt?.model||Ne,allowDownload:t.stt?.allowDownload!==!1,dtype:t.stt?.dtype||void 0,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});const i=e?.diarize===!0&&t.stt?.diarize!==!1;i&&!j.isReady()&&j.init({allowDownload:t.stt?.allowDownload!==!1,warmMs:t.stt?.warmMs,onLog:u=>console.log(u)});try{const{id:u}=A.createSession({lang:e?.lang,redact:e?.redact===!0,diarize:i,speakerLabel:e?.speakerLabel,endSilenceMs:e?.endSilenceMs,interims:e?.interims!==!1,remote:a});return s(o,201,{id:u,state:A.state()})}catch(u){return s(o,u.code==="too_many_sessions"?429:500,{error:{message:u.message,type:u.code||"stt_error"}})}}{const e=l.match(/^\/stt\/sessions\/([0-9a-f-]{36})(\/audio|\/events)?$/);if(e){const r=e[1];if(e[2]==="/audio"&&n.method==="POST")try{const a=await T(n,t.maxBodyBytes);return A.pushAudio(r,A.toFloat32(a)),s(o,200,{ok:!0,state:A.state()})}catch(a){return s(o,a.code==="no_session"?404:400,{error:{message:a.message,type:a.code||"stt_error"}})}if(e[2]==="/events"&&n.method==="GET"){const a=A.getSession(r);if(!a)return s(o,404,{error:{message:"no such session",type:"no_session"}});o.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});const i=h=>o.write(`data: ${JSON.stringify(h)}
|
|
40
40
|
|
|
41
|
-
`),u=a.redact?await fe(t.pro?.entitlementToken):!0,w=async h=>{if(h.type!=="final"||!a.redact)return h;try{let O=h.text;return await Oe([je(()=>O,I=>{O=I})],t.redaction,{isPro:u}),{...h,text:O}}catch{return h}};i({type:"state",state:a.remote?"ready":A.state()});const y=setInterval(()=>{const h=a.remote?"ready":A.state();if(h==="downloading"||h==="loading"){i({type:"progress",state:h,...A.progress()||{}});return}if(h==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const O=j.state();if(O==="downloading"||O==="loading"){i({type:"diarize-progress",state:O,...j.progress()||{}});return}}i({type:"state",state:h}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const b=A.subscribe(r,h=>{k=k.then(async()=>{i(await w(h)),h.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await A.endSession(r),s(o,200,{ok:!0})}}if(l==="/logs"&&n.method==="GET")return s(o,200,{entries:[...L].reverse()});if(l==="/config"&&n.method==="GET"){const e=await fe(t.pro?.entitlementToken);return s(o,200,_t(t,{proUnlocked:e}))}if(l==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{Jr(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}st(t),JSON.stringify(t.sandbox||null)!==r&&Te?.restart("sandbox settings changed");try{me(t,se())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=E.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&E.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await fe(t.pro?.entitlementToken);return s(o,200,_t(t,{proUnlocked:w}))}if(n.method==="GET"&&l==="/skills"){const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=await fetch(`${e}/skills${Ye(p,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ye(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=de(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Ye(p,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!X(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(l==="/channels"&&n.method==="GET"||l!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${l}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await i.json().catch(()=>({}));return s(o,i.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),a=e[2];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ye(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=de(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Ye(p,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),y=await w.json().catch(()=>({}));return w.ok?s(o,200,y):s(o,w.status,{error:{message:y?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(l)){const e=await S(),r=e.sig!==void 0&&e.sig!==$;return $=e.sig,s(o,200,await Hr(t,{serviceHealth:async()=>e,fresh:r}))}if(yn.some(e=>l===e||l.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${ee}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const C=nn(l,n.headers,t);let Z;try{Z=await T(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let q=null,v=null,le=Z,ve=0,V=0,ne=0,U=!1,Y=!0;const H=t.logRequests&&C.redactable&&n.method==="POST"?rn(ie):null;if(C.redactable&&n.method==="POST"&&Z.length){try{v=JSON.parse(Z.toString("utf8"))}catch{v=null}if(v&&sn(v,C.kind))le=Z;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Qr,h=e.narrowAll?null:I=>!Zr.test(Mt(I)),O=v.tools.length;v.tools=eo(v.tools,Xr(v,C.kind),{cap:b,keep:h,name:Mt,description:Yr}),ne=O-v.tools.length}Y=await fe(t.pro?.entitlementToken);const r=Rr(t,Y);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});U=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&X(n),U||await Ee(t);const a=U?[]:C.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=H?H.clock():0,{vault:w,count:y,sanitized:k}=U?{vault:null,count:0,sanitized:0}:await Oe(a,t.redaction,{signal:i.signal,isPro:Y,onEgress:b=>Ke.push(At({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(H&&H.lap("redact",u),q=w,ve=y,V=k||0,!Y&&y>0){Ir(t,Y);try{me(t,se())}catch{}}if(!U&&Array.isArray(v.tools)&&v.tools.length&&typeof C.adapter.injectSystemNote=="function"){const b=Et(v?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:O=>!!O.service&&g.fn(O.id)==="down"}),h=!(b&&b.type==="api");C.adapter.injectSystemNote(v,oo({toolData:t.tools?.toolData,ownTools:h}))}else!U&&y>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(v,ro());le=Buffer.from(JSON.stringify(v),"utf8")}}const Xe=to({vault:q,toolData:t.tools?.toolData}),xe=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(xe&&(delete v.chatpanel,le=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=Zo(v.model,t,await S());if(e?.error)return H?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,le=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const pe={destination:String(n.headers["x-chatpanel-destination"]||xe?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||xe?.reach||"").trim(),run:wn(n.headers["x-chatpanel-run"],xe?.run)},qe=await S(),B=Et(v?.model,t,C.kind,{destination:pe.destination,down:e=>!!e.service&&qe(e.id)==="down"});if(B?.service&&qe(B.id)==="down")return H?.commit(),s(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(pe.destination&&(!B||B.id!==pe.destination))return H?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:Vr(t).map(e=>e.id)}});H&&(H.meta={t:Date.now(),model:v?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ve,sanitized:V,narrowed:ne,detail:Lt(q,t.logDetail),redaction:U?"off":t.redaction.tier||"basic"});const _e=yo();if(_e&&B){const e=B.type==="api"?at(_e,{model:v?.model||"",endpoint:B.baseUrl||""}):go(_e,B.agent||B.id)?at(_e,{model:v?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return H?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?an(B.baseUrl,t)?(H?.commit(),s(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):fn(n,o,{...C,pathname:l,search:p.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:Xe,trace:H},le,q):(H?.commit(),s(o,502,{error:`destination "${B.id}" has no baseUrl`}));const et=$e(n),tt=et==="local"&&t.bridge?.openAgentLane?"token":et;if(tt==="local")return H?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const ot=so({...pe.run||{},...pe.reach?{reach:pe.reach}:{}},tt);return un(n,o,{...C,pathname:l,agentOverride:B?.agent,harness:Xe,trace:H,run:Object.keys(ot).length?ot:null},v,q,t,Y)});return re.on("close",()=>{m?.stop("closed"),ir()}),re}function wn(t,c){let d=c&&typeof c=="object"?c:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(f=>String(f).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const f=d.workspace;m.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),zr.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),d.sandbox&&typeof d.sandbox=="object"){const f=(Array.isArray(d.sandbox.hosts)?d.sandbox.hosts:String(d.sandbox.hosts||"").split(/[\s,;]+/)).map($=>String($).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(d.sandbox.write)?d.sandbox.write:[]).map($=>String($).slice(0,1024)).filter(Boolean).slice(0,32);(f.length||g.length)&&(m.sandbox={...f.length?{hosts:f}:{},...g.length?{write:g}:{}})}return Object.keys(m).length?m:null}let Te=null;async function Ds(t=rt()){Po();let c=null;try{c=await ho()}catch(S){throw S instanceof fo&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const d=c?.policy||null;d&&(st(t,d),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),mo(globalThis,{allow:d?.egress?(S,{local:x})=>wo(d,S,{local:x}):null}),Re();const m=gn(t),f=_o(t),g=Wt(t);m.on("error",S=>{S&&S.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${ee} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),Lo(t,{childEnv:()=>Gr(t)}).then(S=>{Te=S}).catch(S=>console.log(` bridge : not supervised (${S?.message||S})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),Rt(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),ut()&&He(N,Je()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Me())}).catch(()=>{});const $=()=>{f?.stop(),g.stop(),Te?.stop(),Kr(m)};return process.on("SIGINT",$),process.on("SIGTERM",$),m}export{ee as VERSION,gn as createGateway,mn as joinUpstream,Qe as parseAgentModel,Ds as start};
|
|
41
|
+
`),u=a.redact?await fe(t.pro?.entitlementToken):!0,w=async h=>{if(h.type!=="final"||!a.redact)return h;try{let O=h.text;return await $e([Re(()=>O,I=>{O=I})],t.redaction,{isPro:u}),{...h,text:O}}catch{return h}};i({type:"state",state:a.remote?"ready":A.state()});const y=setInterval(()=>{const h=a.remote?"ready":A.state();if(h==="downloading"||h==="loading"){i({type:"progress",state:h,...A.progress()||{}});return}if(h==="error"){i({type:"error",code:"model_failed",message:A.health().error||"model failed to load",fatal:!0}),clearInterval(y);return}if(a.diarize){const O=j.state();if(O==="downloading"||O==="loading"){i({type:"diarize-progress",state:O,...j.progress()||{}});return}}i({type:"state",state:h}),clearInterval(y)},500);y.unref?.();let k=Promise.resolve();const b=A.subscribe(r,h=>{k=k.then(async()=>{i(await w(h)),h.type==="end"&&(clearInterval(y),o.end())}).catch(()=>{})});n.on("close",()=>{clearInterval(y),b?.()});return}if(!e[2]&&n.method==="DELETE")return await A.endSession(r),s(o,200,{ok:!0})}}if(l==="/logs"&&n.method==="GET")return s(o,200,{entries:[...L].reverse()});if(l==="/config"&&n.method==="GET"){const e=await fe(t.pro?.entitlementToken);return s(o,200,Ot(t,{proUnlocked:e}))}if(l==="/config"&&n.method==="POST"){let e=null;try{e=JSON.parse((await T(n,t.maxBodyBytes)).toString("utf8"))}catch{e=null}if(!e||typeof e!="object")return s(o,400,{error:"invalid config patch"});const r=JSON.stringify(t.sandbox||null);try{zr(t,e)}catch(y){if(y?.code==="SHAPE")return s(o,400,{error:y.message});throw y}at(t),JSON.stringify(t.sandbox||null)!==r&&Te?.restart("sandbox settings changed");try{me(t,se())}catch(y){return s(o,500,{error:`could not persist config: ${y.message}`})}const a=t.redaction?.detection,i=!a||!a.backend||a.backend==="off",u=E.state();t.ner?.autostart&&i&&u!=="ready"&&u!=="loading"&&u!=="downloading"&&E.setModel(t.ner.model,{onLog:y=>console.log(y)}).then(y=>{y&&t.ner?.enableFullTier&&t.redaction.tier!=="full"&&(t.redaction.tier="full")});const w=await fe(t.pro?.entitlementToken);return s(o,200,Ot(t,{proUnlocked:w}))}if(n.method==="GET"&&l==="/skills"){const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=await fetch(`${e}/skills${Xe(p,t)}`,{headers:{Accept:"application/json",...r?{Authorization:`Bearer ${r}`}:{}},signal:AbortSignal.timeout(8e3)}),i=await a.json().catch(()=>({}));return a.ok?s(o,200,{skills:Array.isArray(i?.skills)?i.skills:[]}):s(o,a.status,{error:{message:i?.error||`bridge ${a.status}`,type:"bridge_error"}})}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+$/.test(l)){const e=decodeURIComponent(l.slice(8));if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\"))return s(o,400,{error:{message:"not a skill id",type:"invalid_request"}});const r=await ye(t);if(!r)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const a=de(t.bridge?.token);try{const i=await fetch(`${r}/skills/${encodeURIComponent(e)}${Xe(p,t)}`,{headers:{Accept:"application/json",...a?{Authorization:`Bearer ${a}`}:{}},signal:AbortSignal.timeout(8e3)}),u=await i.json().catch(()=>({}));return i.ok?s(o,200,{skill:u?.skill||null}):s(o,i.status,{error:{message:u?.error||`bridge ${i.status}`,type:"bridge_error"}})}catch(i){return s(o,502,{error:{message:`bridge unreachable: ${i.message}`,type:"bridge_unreachable"}})}}if(l==="/channels"||/^\/channels\/(connect|pair|unpair|settings|disconnect)$/.test(l)){if(!X(n))return s(o,403,{error:{message:"channels: extension origin or gateway token required",type:"forbidden"}});if(!(l==="/channels"&&n.method==="GET"||l!=="/channels"&&n.method==="POST"))return s(o,405,{error:{message:"method not allowed",type:"invalid_request"}});const e=await ye(t);if(!e)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const r=de(t.bridge?.token);try{const a=n.method==="POST"?(await T(n,t.maxBodyBytes)).toString("utf8"):"",i=await fetch(`${e}${l}`,{method:n.method,headers:{Accept:"application/json",...n.method==="POST"?{"content-type":"application/json"}:{},...r?{Authorization:`Bearer ${r}`}:{}},...n.method==="POST"?{body:a||"{}"}:{},signal:AbortSignal.timeout(15e3)}),u=await i.json().catch(()=>({}));return s(o,i.status,u)}catch(a){return s(o,502,{error:{message:`bridge unreachable: ${a.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/^\/skills\/[^/]+\/file\/.+/.test(l)){const e=/^\/skills\/([^/]+)\/file\/(.+)$/.exec(l),r=decodeURIComponent(e[1]),a=e[2];if(!r||r==="."||r===".."||r.includes("/")||r.includes("\\")||/(^|\/)\.\.(\/|$)/.test(decodeURIComponent(a)))return s(o,400,{error:{message:"not a skill file",type:"invalid_request"}});const i=await ye(t);if(!i)return s(o,503,{error:{message:"no bridge is configured",type:"no_bridge"}});const u=de(t.bridge?.token);try{const w=await fetch(`${i}/skills/${encodeURIComponent(r)}/file/${a}${Xe(p,t)}`,{headers:{Accept:"application/json",...u?{Authorization:`Bearer ${u}`}:{}},signal:AbortSignal.timeout(8e3)}),y=await w.json().catch(()=>({}));return w.ok?s(o,200,y):s(o,w.status,{error:{message:y?.error||`bridge ${w.status}`,type:"bridge_error"}})}catch(w){return s(o,502,{error:{message:`bridge unreachable: ${w.message}`,type:"bridge_unreachable"}})}}if(n.method==="GET"&&/\/models$/.test(l)){const e=await S(),r=e.sig!==void 0&&e.sig!==$;return $=e.sig,s(o,200,await Vr(t,{serviceHealth:async()=>e,fresh:r}))}if(fn.some(e=>l===e||l.startsWith(`${e}/`)))return s(o,404,{error:{message:`this gateway (${ee}) has no ${l} — update it to use this feature`,type:"unknown_endpoint"}});const C=sn(l,n.headers,t);let Z;try{Z=await T(n,t.maxBodyBytes)}catch(e){s(o,e.code===413?413:400,{error:e.code===413?"payload too large":"bad request"}),n.destroy();return}let q=null,v=null,le=Z,ve=0,V=0,ne=0,U=!1,Y=!0;const H=t.logRequests&&C.redactable&&n.method==="POST"?nn(ie):null;if(C.redactable&&n.method==="POST"&&Z.length){try{v=JSON.parse(Z.toString("utf8"))}catch{v=null}if(v&&an(v,C.kind))le=Z;else if(v){const e=t.tools||{};if(e.autoNarrow!==!1&&Array.isArray(v.tools)&&v.tools.length){const b=Number(e.maxPerTurn)>0?Number(e.maxPerTurn):Zr,h=e.narrowAll?null:I=>!Yr.test(Ct(I)),O=v.tools.length;v.tools=to(v.tools,qr(v,C.kind),{cap:b,keep:h,name:Ct,description:Xr}),ne=O-v.tools.length}Y=await fe(t.pro?.entitlementToken);const r=Ir(t,Y);if(!r.allowed)return s(o,402,{error:{message:`ChatPanel Gateway free trial used up (${r.cap} redactions). Add a ChatPanel Pro entitlement token to unlock unlimited full-tier redaction (names/orgs).`,type:"free_limit_reached"}});U=String(n.headers["x-chatpanel-redaction"]||"").trim().toLowerCase()==="off"&&X(n),U||await Ae(t);const a=U?[]:C.adapter.collectSegments(v,t.redaction),i=new AbortController;o.on("close",()=>{o.writableFinished||i.abort()});const u=H?H.clock():0,{vault:w,count:y,sanitized:k}=U?{vault:null,count:0,sanitized:0}:await $e(a,t.redaction,{signal:i.signal,isPro:Y,onEgress:b=>Qe.push(Nt({ts:Date.now(),client:"redaction",tool:`detect:${b.backend}@${b.host||"local"}`,ok:b.ok,ms:b.ms,error:b.error}))});if(H&&H.lap("redact",u),q=w,ve=y,V=k||0,y>0&&o.setHeader("x-chatpanel-redacted",String(y)),!Y&&y>0){Lr(t,Y);try{me(t,se())}catch{}}if(!U&&Array.isArray(v.tools)&&v.tools.length&&typeof C.adapter.injectSystemNote=="function"){const b=At(v?.model,t,C.kind,{destination:String(n.headers["x-chatpanel-destination"]||v?.chatpanel?.destination||"").trim(),down:O=>!!O.service&&g.fn(O.id)==="down"}),h=!(b&&b.type==="api");C.adapter.injectSystemNote(v,ro({toolData:t.tools?.toolData,ownTools:h}))}else!U&&y>0&&typeof C.adapter.injectSystemNote=="function"&&C.adapter.injectSystemNote(v,no());le=Buffer.from(JSON.stringify(v),"utf8")}}const qe=oo({vault:q,toolData:t.tools?.toolData}),xe=v&&typeof v.chatpanel=="object"&&v.chatpanel||null;if(xe&&(delete v.chatpanel,le=Buffer.from(JSON.stringify(v),"utf8")),typeof v?.model=="string"&&v.model.startsWith("fusion:")){const e=Yo(v.model,t,await S());if(e?.error)return H?.commit(),s(o,400,{error:{message:e.error,type:"fusion"}});e&&(v.model=e.model,le=Buffer.from(JSON.stringify(v),"utf8"),o.setHeader("x-chatpanel-fusion",`${e.fusion.id} -> ${e.model}`))}const pe={destination:String(n.headers["x-chatpanel-destination"]||xe?.destination||"").trim(),reach:String(n.headers["x-chatpanel-reach"]||xe?.reach||"").trim(),run:bn(n.headers["x-chatpanel-run"],xe?.run)},et=await S(),B=At(v?.model,t,C.kind,{destination:pe.destination,down:e=>!!e.service&&et(e.id)==="down"});if(B?.service&&et(B.id)==="down")return H?.commit(),s(o,503,{error:{message:`${B.id} is not running — the model ${JSON.stringify(v?.model||"")} is served by an engine the Runtime has stopped; start it under Settings › Runtime`,type:"engine_down",service:B.service}});if(pe.destination&&(!B||B.id!==pe.destination))return H?.commit(),s(o,404,{error:{message:`no destination "${pe.destination}" is configured on this gateway`,type:"unknown_destination",known:Ur(t).map(e=>e.id)}});H&&(H.meta={t:Date.now(),model:v?.model||null,dest:B?B.id:null,type:B?B.type:null,redacted:ve,sanitized:V,narrowed:ne,detail:Jt(q,t.logDetail),redaction:U?"off":t.redaction.tier||"basic"});const _e=fo();if(_e&&B){const e=B.type==="api"?it(_e,{model:v?.model||"",endpoint:B.baseUrl||""}):wo(_e,B.agent||B.id)?it(_e,{model:v?.model||""}):{ok:!1,reason:`agent "${B.agent||B.id}" is not allowed by your organisation’s policy`};if(!e.ok)return H?.commit(),s(o,403,{error:{message:e.reason,type:"policy",code:"org_policy"}})}if(B&&B.type==="api")return B.baseUrl?ln(B.baseUrl,t)?(H?.commit(),s(o,508,{error:{message:`destination "${B.id}" points back at the gateway (${B.baseUrl}) — refusing to forward (would loop).`,type:"loop_detected"}})):gn(n,o,{...C,pathname:l,search:p.search,base:B.baseUrl,destKey:B.apiKey,destProtocol:B.protocol,harness:qe,trace:H},le,q):(H?.commit(),s(o,502,{error:`destination "${B.id}" has no baseUrl`}));const tt=Pe(n),ot=tt==="local"&&t.bridge?.openAgentLane?"token":tt;if(ot==="local")return H?.commit(),s(o,401,{error:{message:"agent destinations require the gateway token: send `Authorization: Bearer $(cat ~/.chatpanel/gateway-token)`, or pair this client with `chatpanel-gateway pair`",type:"auth",code:"agent_lane_token_required"}});const rt=Math.max(0,Math.min(8,Number(n.headers["x-chatpanel-ask-depth"])||0)),Oe=ao({...pe.run||{},...pe.reach?{reach:pe.reach}:{},...rt?{askDepth:rt}:{}},ot);return Oe.reach&&o.setHeader("x-chatpanel-reach-used",Oe.reach),mn(n,o,{...C,pathname:l,agentOverride:B?.agent,harness:qe,trace:H,run:Object.keys(Oe).length?Oe:null},v,q,t,Y)});return re.on("close",()=>{m?.stop("closed"),lr()}),re}function bn(t,c){let d=c&&typeof c=="object"?c:null;if(!d&&t)try{d=JSON.parse(decodeURIComponent(String(t)))}catch{d=null}if(!d||typeof d!="object")return null;const m={};if(Array.isArray(d.grants)&&(m.grants=d.grants.map(f=>String(f).slice(0,80)).slice(0,32)),d.workspace&&typeof d.workspace=="object"&&d.workspace.repo){const f=d.workspace;m.workspace={repo:String(f.repo).slice(0,400),projectId:String(f.projectId||"").slice(0,120),jobId:String(f.jobId||"").slice(0,120),...f.base?{base:String(f.base).slice(0,120)}:{}}}if(d.connectionId&&(m.connectionId=String(d.connectionId).slice(0,64)),typeof d.workingDir=="string"&&d.workingDir.trim()&&/^([A-Za-z]:[\\/]|\/)/.test(d.workingDir.trim())&&(m.workingDir=d.workingDir.trim().slice(0,1024)),Gr.includes(d.permissionMode)&&d.permissionMode!=="default"&&(m.permissionMode=d.permissionMode),d.sandbox&&typeof d.sandbox=="object"){const f=(Array.isArray(d.sandbox.hosts)?d.sandbox.hosts:String(d.sandbox.hosts||"").split(/[\s,;]+/)).map($=>String($).trim().toLowerCase().slice(0,253)).filter(Boolean).slice(0,64),g=(Array.isArray(d.sandbox.write)?d.sandbox.write:[]).map($=>String($).slice(0,1024)).filter(Boolean).slice(0,32);(f.length||g.length)&&(m.sandbox={...f.length?{hosts:f}:{},...g.length?{write:g}:{}})}return Object.keys(m).length?m:null}let Te=null;async function Cs(t=nt()){Eo();let c=null;try{c=await yo()}catch(S){throw S instanceof go&&(console.error(`[chatpanel-gateway] org policy: ${S.message}`),process.exit(78)),S}const d=c?.policy||null;d&&(at(t,d),console.log(`[chatpanel-gateway] ${c.label} — ${c.signed?"signed":"unsigned"} policy from ${c.source}`)),po(globalThis,{allow:d?.egress?(S,{local:x})=>bo(d,S,{local:x}):null}),Ie();const m=wn(t),f=Oo(t),g=Kt(t);m.on("error",S=>{S&&S.code==="EADDRINUSE"&&(console.error(`Port ${t.port} is already in use — another app (or a second gateway) has it.`),console.error(`Fix: free the port, or set a different one — edit "port" in ${se()} (or the extension's Gateway tab) and restart. The extension must point at the same port.`),process.exit(1)),console.error(`Gateway server error: ${S?.message||S}`),process.exit(1)}),m.listen(t.port,t.host,()=>{console.log(`ChatPanel Privacy Gateway v${ee} on http://${t.host}:${t.port}`),console.log(` backend : ${t.backend}`+(t.backend==="bridge"?` (agent: ${t.bridge.agent}, via ${t.bridge.url})`:"")),t.bridge?.openAgentLane&&console.log(" ⚠ agents : bridge.openAgentLane is ON — any local process may drive a CLI agent through this gateway without a token"),Jo(t,{childEnv:()=>Hr(t)}).then(S=>{Te=S}).catch(S=>console.log(` bridge : not supervised (${S?.message||S})`)),console.log(` redaction: ${t.redaction.tier}`+(t.redaction.detection?.backend&&t.redaction.detection.backend!=="off"?` + ${t.redaction.detection.backend} detector`:t.ner?.autostart?" (+ NER starting…)":"")),It(t.host)||console.error(`⚠ SECURITY: gateway bound to NON-LOOPBACK host ${t.host}. It is reachable off-machine, and the loopback Host-header check is spoofable from the LAN. Admin routes still need the token/extension, but prefer binding 127.0.0.1 unless you intend LAN exposure on a trusted network.`)}),mt()&&Ve(N,ze()).then(S=>{S?.ok&&(console.log(` warm : seeded ${S.ingested} records from ${S.file}`),S.whole&&Ce())}).catch(()=>{});const $=()=>{f?.stop(),g.stop(),Te?.stop(),Qr(m)};return process.on("SIGINT",$),process.on("SIGTERM",$),m}export{Is as VERSION,wn as createGateway,pn as joinUpstream,Ze as parseAgentModel,Cs as start};
|
package/src/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const o="0.44.3";export{o as VERSION};
|