@chatpanel/bridge 0.49.0 → 0.51.1
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/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/agent-mcp.js +1 -0
- package/src/cli-errors.js +7 -6
- package/src/engines/cli-agents.js +4 -4
- package/src/engines/custom.js +8 -8
- package/src/engines/stream-formats.js +2 -2
- package/src/events/agent-mcp-host.js +1 -0
- package/src/events/agent-mcp.js +1 -0
- package/src/events/compaction.js +7 -5
- package/src/events/context-window.js +1 -1
- package/src/events/file-write.js +11 -0
- package/src/events/harness-cards.js +1 -1
- package/src/events/mcp-config-import.js +2 -2
- package/src/mcp-capabilities.js +2 -2
- package/src/server.js +10 -10
- package/src/skills.js +1 -1
- package/src/warm-pool.js +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chatpanel/bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.51.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local bridge that exposes the AI coding agents installed on your machine — Claude Code (CLI), Codex (CLI), and Antigravity CLI (formerly Gemini CLI, which remains available for business/enterprise) — to the ChatPanel Chrome extension over a localhost SSE endpoint. Bring your own agent.",
|
|
6
6
|
"keywords": [
|
package/scripts/sync-events.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync as r,writeFileSync as
|
|
2
|
+
import{readFileSync as r,writeFileSync as d,existsSync as i,mkdirSync as p}from"node:fs";import{fileURLToPath as m}from"node:url";import{dirname as h,join as s}from"node:path";const c=s(h(m(import.meta.url)),".."),f=["scopes.js","skill-manifest.js","skill-scan.js","ref.js","event.js","view.js","capability.js","reach.js","scm-connection.js","sandbox-policy.js","secret-names.js","sandbox-grant.js","runtime-host.js","sandbox-choice.js","harness-cards.js","agent-thread.js","compaction.js","context-window.js","mcp-errors.js","registries.js","mcp-signin.js","context-breakdown.js","mcp-config-import.js","agent-mcp.js","agent-mcp-host.js","file-write.js","toml-lite.js","frontmatter.js","skill-package.js","agent-portability.js","agent-dialects.js","agent-card.js","dialect-claude.js","dialect-codex.js","dialect-a2a.js","dialect-chatpanel.js","agent.js","team.js","engine.js","budget.js","mcp-args-env.js","mcp-launcher.js","agent-permission.js","access-request.js","policy.js","service-standby.js"];function u(){return[s(c,"node_modules","@chatpanel","events"),s(c,"..","chatpanel-events")].find(e=>i(s(e,"skill-manifest.js")))}const n=process.argv.includes("--check"),a=u();if(!a){const e="chatpanel-events not found (check out ../chatpanel-events).";n&&(console.error(`sync-events --check: ${e}`),process.exit(1)),console.warn(`sync-events: ${e} Leaving src/events as-is.`),process.exit(0)}const l=s(c,"src","events");n||p(l,{recursive:!0});const v=e=>`// GENERATED — do not edit.
|
|
3
3
|
// Source of truth: chatpanel-events/${e} (npm @chatpanel/events).
|
|
4
4
|
// Edit there, then run: npm run sync:events
|
|
5
5
|
//
|
|
@@ -7,4 +7,4 @@ import{readFileSync as r,writeFileSync as j,existsSync as i,mkdirSync as p}from"
|
|
|
7
7
|
// curl one-liner install cannot fail on someone's registry, and so the compiled
|
|
8
8
|
// single-file binary has nothing to resolve.
|
|
9
9
|
|
|
10
|
-
`;let
|
|
10
|
+
`;let j=0;for(const e of f){const o=v(e)+r(s(a,e),"utf8"),t=s(l,e);if((i(t)?r(t,"utf8"):null)!==o){if(n){console.error(`sync-events --check: src/events/${e} differs from chatpanel-events`),j+=1;continue}d(t,o),console.log(`sync-events: updated src/events/${e}`)}}n&&(j&&(console.error("Run `npm run sync:events` and commit the result."),process.exit(1)),console.log("sync-events --check: src/events matches chatpanel-events ✓"));
|
package/src/agent-mcp.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFile as f,realpath as m}from"node:fs/promises";import p from"node:os";import t from"node:path";import{BUILTIN_SERVER as g,AGENT_SERVER_LABELS as v,agentServerRef as y,agentServerList as E,builtinServer as h}from"./events/agent-mcp.js";import{agentServerEntries as S,builtinToolsList as j,builtinCallRefusal as b,builtinFenceWhy as $}from"./events/agent-mcp-host.js";import{writablePath as R}from"./events/file-write.js";const i=()=>p.homedir(),x=()=>process.env.XDG_CONFIG_HOME||t.join(i(),".config");async function c(e){try{return JSON.parse(await f(e,"utf8"))}catch{return null}}async function C(e){try{return await f(e,"utf8")}catch{return""}}const L={claude:async()=>({json:[await c(t.join(process.cwd(),".mcp.json")),await c(t.join(i(),".claude.json"))]}),codex:async()=>({toml:[await C(t.join(process.env.CODEX_HOME||t.join(i(),".codex"),"config.toml"))]}),opencode:async()=>({json:[await c(t.join(x(),"opencode","opencode.json")),await c(t.join(i(),"Library","Application Support","opencode","opencode.jsonc"))]})};async function w(e){const r=L[e];if(!r)return[];try{return S(await r())}catch{return[]}}async function N(e,{available:r=!1}={}){return E(e,await w(e),{builtin:r})}async function B(e){const r=y(e);if(!r)throw new Error("not a server reference");const n=v[r.agent]||r.agent,o=`agent:${r.agent}:${r.server}`;if(r.server===g){const a=h(r.agent);if(!a)throw new Error(`${n} has no built-in tools to offer`);return{key:o,command:a.command,args:[...a.args],cwd:i(),builtin:r.agent}}const s=(await w(r.agent)).find(a=>a.server===r.server);if(!s)throw new Error(`${r.server} is no longer in ${n}'s config — switch it off in Settings › MCP, or add it back in ${n}`);if(s.kind!=="local")throw new Error(`${r.server} in ${n} is a remote server — add it under MCP servers in Chap to sign in to it there`);return{key:o,command:s.spec.command,args:s.spec.args,env:s.spec.env}}async function k(e){let r=t.resolve(e);const n=[];for(;;){try{return t.join(await m(r),...n.reverse())}catch{}const o=t.dirname(r);if(o===r)return t.resolve(e);n.push(t.basename(r)),r=o}}async function G(e,r){const{name:n,arguments:o={}}=r?.params||{},s=b(e,n,o,{home:i()});if(s)return s;for(const a of h(e).paths){if(o[a]==null)continue;const d=String(o[a]).replace(/^~(?=\/|$)/,i()),u=await k(d),l=R(u,{home:await m(i()).catch(()=>i())});if(!l.ok)return`${o[a]} leads to ${u}, which is out of reach: ${$(e,n,l.why)}`}return null}function H(e,r){return!r?.result||!Array.isArray(r.result.tools)?r:{...r,result:{...r.result,tools:j(e,r.result.tools)}}}export{N as agentServersFor,G as builtinRefusal,H as narrowBuiltinList,B as resolveAgentServer};
|
package/src/cli-errors.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import{loginRequired as
|
|
2
|
-
`).some(
|
|
3
|
-
`).some(
|
|
4
|
-
${s||""}
|
|
5
|
-
|
|
1
|
+
import{loginRequired as b,signInMessage as v}from"./sign-in.js";const f=[/^\s*$/,/^\s*at\s+/,/^\s*[.#]?[\w-]+\s*\{/,/^\s*[\w-]+:\s*[^;]+;$/,/^\s*<\//];function p(e){return String(e||"").replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<svg[\s\S]*?<\/svg>/gi," ").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/[ \t]+/g," ")}const $=[/(?:refresh OAuth tokens|refresh tools) for (?:MCP )?server ['"`]?([\w.-]+)['"`]?/i,/MCP server ['"`]([\w.-]+)['"`]/i,/server ['"]?([\w.-]+)['"]? (?:requires|failed) auth/i];function g(e){for(const t of $){const r=t.exec(String(e||""))?.[1];if(r)return r}return null}const m=/api error|authentication_error|invalid (?:x-)?api[- ]key|bearer token|anthropic|openai|x-api-key|\baws\b|bedrock|security token/i,x=e=>/\b401\b/.test(e)&&!m.test(e)&&(/\bmcp\b/i.test(e)||!!g(e)),w=e=>/HTTP 403|\b403\b/.test(e)&&!m.test(e),y=[{kind:"expired",test:/refresh token (?:does not exist|was rejected)|invalid_grant/i,short:"its saved login has expired",say:e=>`${e} needs re-authentication — its saved OAuth token has expired or been revoked. Re-login to that server in the agent's own config; ChatPanel can't refresh it.`},{kind:"unauthorized",test:e=>/invalid_token|AuthRequired|www-authenticate/i.test(e)||e.split(`
|
|
2
|
+
`).some(x),short:"it rejected the agent's token",say:e=>`${e} rejected the agent's token (401/invalid_token). Re-authenticate that server in the agent, then retry.`},{kind:"refused",test:e=>e.split(`
|
|
3
|
+
`).some(w),short:"it is refusing requests",say:e=>`${e} returned 403 and an error page — that server is refusing requests or is temporarily down. This is outside ChatPanel; retry when it recovers.`},{kind:"unreachable",requiresMcpContext:!0,test:/handshaking with MCP server failed|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|dns error|connection (?:refused|reset)|failed to start and is unavailable|network is unreachable/i,short:"it could not be reached",say:e=>`${e} could not be reached — it is offline, or needs a network (VPN) this machine is not on. ChatPanel can't reach it either; retry when it is available.`}];function A(e){const t=String(e||""),r=g(t),s=/\bmcp\b/i.test(t)||!!r;for(const i of y)if(!(i.requiresMcpContext&&!s)&&(typeof i.test=="function"?i.test(t):i.test.test(t)))return{server:r,kind:i.kind,short:i.short,say:i.say(r?`its MCP server "${r}"`:"one of its MCP servers")};return null}function C(e){const t=A(e);return t?t.say:/ENOENT|command not found/i.test(e)?"the command could not be found on PATH.":null}const E={"claude code":"claude",claude:"claude",codex:"codex","github copilot":"copilot",copilot:"copilot",opencode:"opencode",kiro:"kiro",hermes:"hermes",antigravity:"antigravity",pi:"pi"};function S(e,t,r,s="",{agentId:i=null,reported:n=""}={}){const o=`${r||""}
|
|
4
|
+
${s||""}
|
|
5
|
+
${n||""}`;if(b(o))return v(e,i||E[String(e).toLowerCase()]||null);const u=C(o);if(u)return`${e} exited ${t}: ${u}`;const a=p(String(n||"")).replace(/\s+/g," ").trim();if(a)return`${e}: ${a.length>400?`${a.slice(0,400)}…`:a}`;const l=p(o).split(`
|
|
6
|
+
`).map(c=>c.trim()).filter(c=>c&&!f.some(k=>k.test(c))),h=l.filter(c=>/error|fail|fatal|panic|refused|denied|timeout/i.test(c)),d=(h.length?h:l).pop()||"failed";return`${e} exited ${t}: ${d.length>300?`${d.slice(0,300)}…`:d}`}const _=[[/(bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,"$1…"],[/\b(sk-|sk_|ghp_|gho_|xox[abpr]-|AKIA)[A-Za-z0-9_-]{6,}/g,"$1…"],[/\b[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/g,"…"],[/\b[A-Za-z0-9+/_-]{40,}={0,2}/g,"…"]];function P(e,t="",{lines:r=6,width:s=300}={}){return p(`${e||""}
|
|
6
7
|
${t||""}`).split(`
|
|
7
|
-
`).map(
|
|
8
|
+
`).map(n=>n.trim()).filter(n=>n&&!f.some(o=>o.test(n))&&/error|fail|fatal|panic|refused|denied|timeout|unauthori[sz]ed|\b40[13]\b/i.test(n)).slice(-r).map(n=>_.reduce((o,[u,a])=>o.replace(u,a),n)).map(n=>n.length>s?`${n.slice(0,s)}…`:n).join(" ⏎ ")}function M(e,t,r,s="",i={}){return Object.assign(new Error(S(e,t,r,s,i)),{detail:P(r,s)})}export{M as cliError,P as errorTail,A as mcpFailure,g as mcpServerName,p as stripMarkup,S as summarizeCliError};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function
|
|
2
|
-
`)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const
|
|
1
|
+
import{runSpec as h,listSpecModels as A,runForStdout as d,CHATPANEL_STABLE_MCP_URL as m}from"./custom.js";import{agentAvailable as b,selfMcpStdio as u}from"../env.js";function i(e,o,a,t={}){let r=!1,s=0;const n={sandboxEngine:e,...o,command:e};return{spec:n,async available(){if(Date.now()-s>(r?3e4:4e3)){s=Date.now();try{r=b(e)}catch{r=!1}}return r?{ok:!0}:{ok:!1,reason:a}},listModels(l={}){return t.listModels?t.listModels(e,l):A(e,o.listModelsArgs,l.workingDir)},chat(l,c,p){return h(n,l,c,p)}}}const _=i("pi",{args:"-p",promptVia:"stdin",modelArg:"--model {model}",imageArg:"@{path}",toolAdapter:"pi-extension",listModelsArgs:"--list-models",label:"Pi"},"pi not found on PATH. Install Pi, then run `pi` once to sign in."),D=i("opencode",{args:"run --format json --dangerously-skip-permissions",promptVia:"stdin",modelArg:"-m {model}",imageArg:"-f {path}",format:"opencode-json",mcpViaEnv:{env:"OPENCODE_CONFIG_CONTENT",args:["--standalone"]},listModelsArgs:"models",label:"OpenCode"},"opencode not found on PATH. Install opencode, then sign in."),H=i("kiro-cli",{args:"chat --no-interactive --require-mcp-startup",promptVia:"stdin",modelArg:"--model {model}",trustAllToolsForMcp:!0,trustAllToolsArg:"--trust-all-tools",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"kiro",stableMcpSetupArgs:["mcp","add","--scope","global","--name","chatpanel_browser","--url","http://127.0.0.1:4319/mcp","--force"],stableMcpSetupCommand:"kiro-cli mcp add --scope global --name chatpanel_browser --url http://127.0.0.1:4319/mcp --force",listModelsArgs:"--list-models",label:"Kiro"},"kiro-cli not found on PATH. Install Kiro CLI, then sign in."),S=["--output-format","json","--no-color","--log-level","none","--no-ask-user","--no-auto-update","--no-remote","--no-remote-export"],P=i("copilot",{args:S,promptVia:"stdin",modelArg:"--model {model}",imageArg:"--attachment {path}",format:"copilot-json",mcpArg:"--additional-mcp-config @{file}",permissionArgs:{default:["--allow-all-tools"],acceptEdits:["--allow-all-tools","--allow-all-paths"],bypassPermissions:["--allow-all"]},forbidden:"copilot",label:"GitHub Copilot"},"copilot not found on PATH. Install GitHub Copilot CLI, then run `copilot login`.",{listModels:(e,o)=>M(e,o.workingDir)});async function M(e="copilot",o){const a=await d(e,["help","config"],o),t=[],r=new Set;let s=!1;for(const n of String(a||"").split(`
|
|
2
|
+
`)){const l=/^\s*`([A-Za-z][\w.]*)`\s*:/.exec(n);if(l){s=l[1]==="model";continue}if(!s)continue;const c=/^\s*-\s*"([^"]+)"\s*$/.exec(n);if(!c)continue;const p=c[1];if(!r.has(p)&&(r.add(p),t.push(p),t.length>=200))break}return t.length?["auto",...t]:[]}const E=i("dsh",{args:["--profile","headless","{prompt}"],promptVia:"arg",format:"text",modelPatch:{arg:"--patch {file}",build:e=>`- id: ${g}
|
|
3
3
|
config:
|
|
4
4
|
provider: ${k}
|
|
5
5
|
model: ${JSON.stringify(e)}
|
|
6
|
-
`},label:"DeepSeek Harness"},'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',{listModels:(e,o)=>w(e,o.workingDir)}),g="agent-default-model",k="deepseek-official",f=["deepseek-v4-flash","deepseek-v4-pro"];async function w(e="dsh",o){const
|
|
7
|
-
`),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const
|
|
6
|
+
`},label:"DeepSeek Harness"},'dsh not found on PATH. Install DeepSeek Harness, then run `dsh --profile headless "hi"` once to check the profile.',{listModels:(e,o)=>w(e,o.workingDir)}),g="agent-default-model",k="deepseek-official",f=["deepseek-v4-flash","deepseek-v4-pro"];async function w(e="dsh",o){const a=await d(e,["--profile","headless","--dump-config"],o,6e4),t=String(a||"").split(`
|
|
7
|
+
`),r=new RegExp(`^-\\s*id:\\s*${g}\\s*$`);for(let s=0;s<t.length;s++)if(r.test(t[s]))for(let n=s+1;n<t.length&&!/^-\s*id:/.test(t[n]);n++){const l=/^\s*model:\s*['"]?([\w.:-]+)['"]?\s*$/.exec(t[n]);if(l)return[...new Set([l[1],...f])]}return[...f]}const O=i("hermes",{args:"-z {prompt}",promptVia:"arg",modelArg:"-m {model}",requiresStableMcp:!0,autoSetupStableMcp:!0,stableMcpConfigCheck:"hermes",stableMcpSetupArgs:()=>{const{command:e,args:o}=u(m);return["mcp","add","chatpanel_browser","--command",e,"--args",...o]},stableMcpSetupCommand:(()=>{const{command:e,args:o}=u(m);return`hermes mcp add chatpanel_browser --command ${e} --args ${o.join(" ")}`})(),label:"Hermes"},"hermes not found on PATH. Install Hermes Agent, then run `hermes setup` to sign in.",{listModels:async(e,o={})=>{try{const a=await d(e,["config","get","model"],o.workingDir),t=/^\s*default:\s*(\S+)/m.exec(a||"");return t?[t[1]]:[]}catch{return[]}}});export{P as copilot,E as deepseek,O as hermes,H as kiro,M as listCopilotModels,w as listDshModels,D as opencode,_ as pi};
|
package/src/engines/custom.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function
|
|
1
|
+
import{spawn as L}from"node:child_process";import{readFile as et,writeFile as _,unlink as rt}from"node:fs/promises";import T from"node:os";import x from"node:path";import{resolveCommand as I,buildSpawnSpec as N,selfMcpStdio as H}from"../env.js";import{missingCommandMessage as J}from"../events/mcp-errors.js";import{sandbox as F,noteSandbox as nt,track as R,grantedWriteRoots as ot}from"../sandbox.js";import{harnessDirArgs as it,harnessOwnModel as st}from"../events/harness-cards.js";import{readFileSync as at}from"node:fs";import{isProEntitled as V}from"../entitlement.js";import{killOnAbort as lt}from"../proc.js";import{buildCliPrompt as ct,fitCliPrompt as mt,argvPromptBudget as ut}from"./prompt.js";import{pushExtraArgs as pt,FORBIDDEN as z}from"./args.js";import{createStreamParser as dt,STREAM_FORMATS as ft}from"./stream-formats.js";import{resolveWorkdir as gt}from"../workdir.js";import{cliError as ht}from"../cli-errors.js";async function wt(t,n){const e=[];for(let r=0;r<(t?.length||0);r++){const o=/^data:([^;]+);base64,(.+)$/s.exec(t[r]?.dataUrl||"");if(!o)continue;const s=(o[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",f=x.join(T.tmpdir(),`chatpanel-custom-img-${n}-${r}.${s}`);await _(f,Buffer.from(o[2],"base64")),e.push(f)}return e}function St(t,n){const e=String(t||"").trim();if(!e||!n.length)return[];const r=[];for(const o of n)r.push(...e.includes("{path}")?e.replaceAll("{path}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]);return r}const G=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,yt="http://127.0.0.1:4319/mcp",D="http://127.0.0.1:4319/mcp";async function ee(){return{ok:!0}}function bt(t){const n=[],e=new Set;for(const r of String(t||"").split(`
|
|
2
|
+
`)){const o=r.trim().split(/\s+/)[0]||"";if(/^[A-Za-z0-9][\w./:-]{1,79}$/.test(o)&&!/^(name|model|models|id|provider|available|usage|options|commands)$/i.test(o)&&!e.has(o)&&(e.add(o),n.push(o),n.length>=200))break}return n}async function re(t={}){if(!await V(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return Ct(n.command,n.listModelsArgs,t.workingDir)}async function Ct(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await $t(t,r.split(/\s+/).filter(Boolean),e);return bt(o)}async function $t(t,n,e,r=2e4){if(!t)return"";const o=I(t);if(!o)throw new Error(J(t,{platform:process.platform}));const s=e?x.resolve(e):null,[f,h,w]=N(o,n,s);w.env={...w.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const y=await F().wrap(f,h,w,{engine:"custom",cwd:s}),{bin:m,argv:b,opts:d}=y;return new Promise((i,S)=>{let g;try{g=R(L(m,b,d),y,{kind:"probe"})}catch(A){return S(new Error(`Failed to start ${t}: ${A.message}`))}let u="";const v=setTimeout(()=>{g.kill("SIGKILL"),S(new Error(`${t} timed out.`))},r);g.stdout.on("data",A=>u+=A.toString()),g.on("error",A=>{clearTimeout(v),S(new Error(`Failed to start ${t}: ${A.message}`))}),g.on("close",()=>{clearTimeout(v),i(u)});try{g.stdin.end()}catch{}})}function K(t){return(t?.specs||[]).filter(n=>n?.name)}function Z(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function At(t,n){return["--extension",t]}function xt(t,n){const e=String(t||"").trim(),r=K(n).map(s=>s.name).filter(Boolean);if(!e||!r.length)return[];const o=r.join(",");return e.includes("{tools}")?e.replaceAll("{tools}",o).split(/\s+/).filter(Boolean):[...e.split(/\s+/).filter(Boolean),o]}function vt(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?xt(t.trustToolsArg,n):[]}function Et(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${D}`}function Mt(t={}){const n=typeof t.stableMcpSetupArgs=="function"?t.stableMcpSetupArgs():t.stableMcpSetupArgs,e=Array.isArray(n)?n.filter(r=>r!=null).map(String):null;return e?.length?{command:t.stableMcpSetupCommandName||t.command,args:e}:null}function Tt(t){const n=K(t),e=n.map((o,s)=>{const f=Z(o.name,s),h=o.parameters||{type:"object",properties:{}};return`const ${f}Tool = {
|
|
3
3
|
name: ${JSON.stringify(o.name)},
|
|
4
4
|
label: ${JSON.stringify(o.name)},
|
|
5
5
|
description: ${JSON.stringify(o.description||o.name)},
|
|
6
|
-
parameters: ${JSON.stringify(
|
|
6
|
+
parameters: ${JSON.stringify(h)},
|
|
7
7
|
async execute(toolCallId, params, signal) {
|
|
8
8
|
return callMcpTool(${JSON.stringify(o.name)}, toolCallId, params, signal);
|
|
9
9
|
},
|
|
10
10
|
};`}).join(`
|
|
11
11
|
|
|
12
|
-
`),r=n.map((o,s)=>` pi.registerTool(${
|
|
12
|
+
`),r=n.map((o,s)=>` pi.registerTool(${Z(o.name,s)}Tool);`).join(`
|
|
13
13
|
`);return`import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
14
14
|
|
|
15
15
|
const MCP_URL = ${JSON.stringify(t.url)};
|
|
@@ -65,7 +65,7 @@ ${e}
|
|
|
65
65
|
export default function (pi: ExtensionAPI) {
|
|
66
66
|
${r}
|
|
67
67
|
}
|
|
68
|
-
`}async function
|
|
69
|
-
${i}`.trim())
|
|
70
|
-
`).pop()||"failed"}`))});try{
|
|
71
|
-
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${
|
|
68
|
+
`}async function Ot(t,n){const e=x.join(T.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await _(e,Tt(t)),e}async function Pt(){const t=process.env.XDG_CONFIG_HOME||x.join(T.homedir(),".config"),n=[x.join(t,"opencode","opencode.jsonc"),x.join(T.homedir(),"Library","Application Support","opencode","opencode.jsonc")];for(const e of n)try{if((await et(e,"utf8")).includes(yt))return!0}catch{}return!1}async function q(t,n,e){const r=I(t);if(!r)return"";const[o,s,f]=N(r,n,e||null),h=await F().wrap(o,s,f,{engine:"custom",cwd:e||null}),{bin:w,argv:y,opts:m}=h;return new Promise(b=>{const d=R(L(w,y,m),h,{kind:"probe"});let i="",S="";const g=setTimeout(()=>{d.kill("SIGKILL"),b(i+S)},4e3);d.stdout.on("data",u=>i+=u.toString()),d.stderr.on("data",u=>S+=u.toString()),d.on("error",()=>{clearTimeout(g),b(i+S)}),d.on("close",()=>{clearTimeout(g),b(i+S)});try{d.stdin.end()}catch{}})}async function kt(t,n){for(const e of["workspace","global","default"]){const r=await q(t,["mcp","list",e],n);if(r.includes(D)||/chatpanel_browser/i.test(r))return!0}return!1}async function Lt(t,n){const e=await q(t,["mcp","list"],n);return e.includes(D)||/chatpanel_browser/i.test(e)}async function _t(t,n){return t.stableMcpConfigCheck==="kiro"?kt(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Pt():t.stableMcpConfigCheck==="hermes"?Lt(t.command||"hermes",n):!1}async function It(t,n){const e=I(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,s]=N(e,t.args,n||null);s.env={...s.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const f=await F().wrap(r,o,s,{engine:"custom",cwd:n||null}),{bin:h,argv:w,opts:y}=f;await new Promise((m,b)=>{let d;try{d=R(L(h,w,y),f,{kind:"probe"})}catch(u){return b(new Error(`Failed to start ${t.command}: ${u.message}`))}let i="",S="";const g=setTimeout(()=>{d.kill("SIGKILL"),b(new Error(`${t.command} MCP setup timed out.`))},2e4);d.stderr.on("data",u=>i+=u.toString()),d.stdout?.on("data",u=>S+=u.toString()),d.on("error",u=>{clearTimeout(g),b(new Error(`Failed to start ${t.command}: ${u.message}`))}),d.on("close",u=>{if(clearTimeout(g),u===0)return m(`${S}
|
|
69
|
+
${i}`.trim());b(new Error(`${t.command} MCP setup exited ${u}: ${i.trim().split(`
|
|
70
|
+
`).pop()||"failed"}`))});try{d.stdin.end()}catch{}})}function Nt(t,n){const e=String(n?.message||n||"");return/mcp['" ]* Python SDK|No module named ['"]?mcp|MCP support/i.test(e)?`${t} has no MCP support installed. Run \`hermes setup\` (or install the \`mcp\` package in its environment), then retry.`:/streamable_http|HTTP transport/i.test(e)?`${t}'s MCP client has no HTTP transport; ChatPanel registers a stdio server instead. Upgrade its \`mcp\` package if this persists.`:e.slice(0,200)||"the CLI could not register the tools"}async function Ft(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||_t,f=o.runSetup||It;if(await s(t,n))return!0;const h=Et(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${h}`;throw r({type:"status",text:m}),new Error(m)}const w=Mt(t);if(!w?.command){const m=`${e} needs one-time browser-tool setup: ${h}`;throw r({type:"status",text:m}),new Error(m)}r({type:"status",text:`${e} is setting up one-time browser tools...`});const y=String(await f(w,n)||"").trim();if(await s(t,n))return!0;throw new Error(`${e} browser-tool setup did not register the server.`+(y?` ${y.split(`
|
|
71
|
+
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${h}`)}async function ne({messages:t,system:n,options:e,images:r},o,{signal:s}={}){if(!await V(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return Rt(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function Rt(t,{messages:n,system:e,options:r={},images:o},s,{signal:f}={}){if(!t.command)throw new Error("This agent has no command configured.");const h=I(t.command);if(!h)throw new Error(J(t.command,{platform:process.platform}));let w=ct(n,e),y=gt(r.workingDir);const m=t.label||t.command,b=Object.hasOwn(ft,t.format)?t.format:"text",d=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];pt(i,r.extraArgs,z[t.forbidden]||z.custom,s);const S=r.model||(t.modelArg?st({harness:t.dirsHarness||t.command,env:process.env,home:T.homedir(),readFile:a=>{try{return at(a,"utf8")}catch{return null}}}):"");if(S&&t.modelArg){const a=String(t.modelArg),l=a.includes("{model}")?a.replaceAll("{model}",S).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),S];i=[...i,...l]}if(t.permissionArgs){const a=String(r.permissionMode||"default"),l=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...l.map(String)]}i=[...i,...it({harness:t.dirsHarness||t.command,roots:ot(y),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const g=`${Date.now()}-${Math.random().toString(36).slice(2)}`,u=t.imageArg?await wt(o,g):[],v=[];let A=null;const P=()=>[...u,...v].forEach(a=>rt(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await Ot(r.mcp,g);v.push(a),i=[...At(a,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const a=r.mcp.serverName||"chatpanel_browser",{command:l,args:p}=H(r.mcp.url),c=x.join(T.tmpdir(),`chatpanel-mcp-${g}.json`);await _(c,JSON.stringify({mcpServers:{[a]:{command:l,args:p}}})),v.push(c);const C=String(t.mcpArg);i=[...C.includes("{file}")?C.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...C.split(/\s+/).filter(Boolean),c],...i]}else if(r.mcp?.url&&t.mcpViaEnv?.env){const a=r.mcp.serverName||"chatpanel_browser",{command:l,args:p}=H(r.mcp.url);let c={};try{c=JSON.parse(process.env[t.mcpViaEnv.env]||"{}")||{}}catch{c={}}const C={...c.mcp?.servers||{},[a]:{type:"local",command:[l,...p]}};A={[t.mcpViaEnv.env]:JSON.stringify({...c,mcp:{...c.mcp||{},servers:C}})},t.mcpViaEnv.args?.length&&(i=[i[0],...t.mcpViaEnv.args,...i.slice(1)].filter(M=>M!==void 0))}if(r.mcp?.url&&!t.mcpViaEnv?.env)try{await Ft(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${Nt(m,a)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...vt(t,r.mcp)),r.model&&typeof t.modelPatch?.build=="function"){const a=/^[A-Za-z0-9][\w.:-]{0,79}$/.test(String(r.model))?String(r.model):"";if(a){const l=x.join(T.tmpdir(),`chatpanel-modelpatch-${g}.yml`);await _(l,t.modelPatch.build(a)),v.push(l);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",l).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),l],...i]}}const E=St(t.imageArg,u);let B=!1;if(E.length&&(i=i.flatMap(a=>a==="{images}"?(B=!0,E):[a])),d==="arg"){const a=i.reduce((c,C)=>c+String(C).length+3,0)+E.reduce((c,C)=>c+String(C).length+3,0),l=mt(n,e,ut({viaCmdExe:h.kind==="cmd",otherArgsChars:a}));(l.dropped||l.prompt!==w)&&(w=l.prompt,s({type:"status",text:`${m} takes the prompt as a command-line argument, which this system caps — the oldest ${l.dropped||"part of the"} turn${l.dropped===1?"":"s"} of this conversation ${l.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(c=>c.includes("{prompt}")?(p=!0,c.replaceAll("{prompt}",w)):c),p||(E.length&&!B&&i.push(...E),i.push(w))}else E.length&&!B&&i.push(...E);const[W,X,j]=N(h,i,y,r.runEnv||null);j.env={...j.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb",...A||{}};const O=await F().wrap(W,X,j,{engine:t.sandboxEngine||"custom",cwd:y});nt(s,O.record);const[Q,Y,tt]=[O.bin,O.argv,O.opts];await new Promise((a,l)=>{let p;try{p=R(L(Q,Y,tt),O,{kind:"agent"})}catch($){return P(),l(new Error(`Failed to start ${m}: ${$.message}`))}const c=lt(p,f);let C="";const M=dt(b,s);let k;const U=()=>{clearTimeout(k),k=setTimeout(()=>{p.kill("SIGKILL"),P(),l(new Error(`${m} timed out — no output for ${Math.round(G/1e3)}s.`))},G)};U(),p.stdout.on("data",$=>{U(),M.push($.toString())}),p.stderr.on("data",$=>{U(),C+=$.toString()}),p.on("error",$=>{clearTimeout(k),c(),P(),l(new Error(`Failed to start ${m}: ${$.message}`))}),p.on("close",$=>{if(clearTimeout(k),c(),P(),f?.aborted){a();return}$===0?(s({type:"done",text:M.streamed?"":M.finish()}),a()):l(ht(m,$,C,"",{reported:M.error||""}))}),d==="stdin"&&p.stdin.write(w),p.stdin.end()})}export{D as CHATPANEL_STABLE_MCP_URL,ee as available,Tt as buildPiExtensionSource,ne as chat,q as commandOutput,Ft as ensureStableMcpConfig,re as listModels,Ct as listSpecModels,Nt as mcpSetupHint,vt as mcpTrustArgs,At as piToolArgs,$t as runForStdout,Rt as runSpec,Et as stableMcpSetupCommand,Mt as stableMcpSetupPlan,xt as trustToolArgs};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{handleMessage as d}from"./claude.js";const m=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,f=
|
|
2
|
-
`))>=0;){const o=
|
|
1
|
+
import{handleMessage as d}from"./claude.js";const m=/\u001b\[[0-9;?]*[ -/]*[@-~]/g,f=t=>String(t).replace(m,"");function c(t){let r="";return n=>{r+=n;let i;for(;(i=r.indexOf(`
|
|
2
|
+
`))>=0;){const o=r.slice(0,i).trim();if(r=r.slice(i+1),!o.startsWith("{"))continue;let s;try{s=JSON.parse(o)}catch{continue}t(s)}}}function g(t){let r=!1;return{push(n){r=!0,t({type:"delta",text:f(n)})},finish:()=>"",get streamed(){return r}}}function y(t){let r=!1,n="";return{push:c(o=>{const s=d(o,t,r);s.streamed&&(r=!0),s.result!=null&&(n=s.result)}),finish:()=>n,get streamed(){return r}}}function x(t){let r=!1,n="";return{push:c(o=>{if(o.type==="text"&&o.part?.text)r=!0,t({type:"delta",text:o.part.text});else if(o.type==="tool"||o.type==="tool_use"){const s=o.part||{},a=s.tool||s.name||s.type||"tool",u=s.callID||s.callId||s.id||void 0,e=s.state||{},l=String(e.status||"").toLowerCase();t(l==="completed"||l==="error"?{type:"tool",name:a,phase:"done",callId:u,status:l==="error"?"error":"ok",result:String(e.output||e.error||"").slice(0,4e3)}:{type:"tool",name:a,phase:"start",callId:u,input:e.input||s.input,summary:""})}else if(o.type==="error"){const s=String(o.error?.data?.message||o.error?.message||o.error?.name||"error");n=o.error?.type==="provider.quota"||o.error?.status===402||/insufficient balance|quota/i.test(s)?`${s} — or pick a model your plan or keys cover for OpenCode (the model menu in Chap; \`opencode models\` lists them).`:s,t({type:"status",text:s.slice(0,300)})}}),finish:()=>"",get streamed(){return r},get error(){return n}}}const h=/permission denied|could not request permission|not allowed|denied by|requires approval/i;function S(t){let r=!1,n="",i=!1;const o=a=>{i||!h.test(String(a||""))||(i=!0,t({type:"status",text:"Copilot was denied a tool/URL — raise this agent’s Permission mode in Settings."}))};return{push:c(a=>{const u=a?.type||"",e=a?.data||{};switch(u){case"assistant.message_delta":e.deltaContent&&(r=!0,t({type:"delta",text:e.deltaContent}));break;case"assistant.message":typeof e.content=="string"&&e.content&&(n=e.content);break;case"assistant.reasoning":e.content&&t({type:"reasoning",text:String(e.content)});break;case"tool.execution_start":t({type:"tool",name:e.toolName||"tool",summary:""});break;case"tool.execution_complete":if(e.success===!1){const l=typeof e.result=="string"?e.result:e.result?.error||e.result?.message||"";l&&t({type:"status",text:String(l).slice(0,300)}),o(l)}else o(typeof e.result=="string"?e.result:"");break;case"session.auto_mode_resolved":e.chosenModel&&t({type:"status",text:`model: ${e.chosenModel}`});break;case"session.mcp_server_status_changed":e.status==="failed"&&e.error&&t({type:"status",text:`MCP ${e.serverName}: ${String(e.error).slice(0,160)}`});break;case"result":a.exitCode&&t({type:"status",text:`copilot exited ${a.exitCode}`});break;default:break}}),finish:()=>n,get streamed(){return r}}}const p={text:g,"claude-stream-json":y,"opencode-json":x,"copilot-json":S};function b(t,r){return(p[t]||p.text)(r)}export{p as STREAM_FORMATS,b as createStreamParser,f as stripAnsi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{parseMcpConfig as u}from"./mcp-config-import.js";import{writablePath as l}from"./file-write.js";import{builtinServer as a,AGENT_SERVER_LABELS as p}from"./agent-mcp.js";const m=/^[A-Za-z0-9@][A-Za-z0-9_.@-]{0,63}$/;function d(r){const s=r&&typeof r=="object"&&r.mcp&&typeof r.mcp=="object"?r.mcp:null;if(!s)return[];const n=[];for(const[o,e]of Object.entries(s)){if(!e||typeof e!="object"||e.enabled===!1)continue;const t=Array.isArray(e.command)?e.command.map(String):typeof e.command=="string"?[e.command]:[];if(t[0]){const i=e.environment&&typeof e.environment=="object"?Object.fromEntries(Object.entries(e.environment).map(([c,f])=>[c,String(f)])):{};n.push({key:o,transport:"stdio",command:t[0],args:t.slice(1),env:i})}else typeof e.url=="string"&&n.push({key:o,transport:"http",url:e.url})}return n}function k({json:r=[],toml:s=[]}={}){const n=[];for(const t of r){if(!t||typeof t!="object")continue;const i=t.mcpServers||t.mcp_servers;i&&typeof i=="object"&&n.push(...u(JSON.stringify({mcpServers:i}),{keys:!0})),n.push(...d(t))}for(const t of s)n.push(...u(String(t||""),{keys:!0}).filter(i=>i.key));const o=new Set,e=[];for(const t of n)!t||!m.test(t.key||"")||o.has(t.key)||t.enabled===!1||(o.add(t.key),e.push({server:t.key,kind:t.transport==="stdio"?"local":"remote",spec:t.transport==="stdio"?{command:t.command,args:t.args||[],env:t.env||{}}:{url:t.url}}));return e}function v(r,s=[]){const n=a(r);return n?(Array.isArray(s)?s:[]).filter(o=>o&&Object.hasOwn(n.tools,o.name)).map(o=>{const e=n.tools[o.name]==="write";return{...o,annotations:{...o.annotations||{},readOnlyHint:!e,destructiveHint:e,openWorldHint:!1}}}):[]}function S(r,s,n={},{home:o=""}={}){const e=a(r);if(!e)return"this agent offers no built-in tools here";if(!Object.hasOwn(e.tools,String(s||"")))return`${s} is not offered from ${p[r]||r} — only ${Object.keys(e.tools).join(", ")}`;let t=0;for(const i of e.paths){if(n?.[i]==null)continue;t+=1;const c=String(n[i]);if(!c.startsWith("/")&&!c.startsWith("~"))return`${i} must be an absolute path`;const f=l(c,{home:o});if(!f.ok)return`${c} is out of reach: ${y(r,s,f.why)}`}return t?null:"no file path was given"}function y(r,s,n=""){return a(r)?.tools?.[s]==="write"?n:String(n).replace(/\bwritten\b/g,"read").replace(/\bwrite\b/g,"read")}export{k as agentServerEntries,S as builtinCallRefusal,y as builtinFenceWhy,v as builtinToolsList};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const l="@builtin",p=Object.freeze({claude:"Claude Code",codex:"Codex",opencode:"OpenCode"}),v=Object.freeze({claude:Object.freeze({label:"file tools",command:"claude",args:Object.freeze(["mcp","serve"]),tools:Object.freeze({Read:"read",Edit:"write",Write:"write",NotebookEdit:"write"}),paths:Object.freeze(["file_path","notebook_path"])})}),u=/^[A-Za-z0-9@][A-Za-z0-9_.@-]{0,63}$/;function f(e){const t=e&&typeof e=="object"?e.from:null;if(!t||typeof t!="object")return null;const n=String(t.agent||""),o=String(t.server||"");return u.test(n)&&u.test(o)?{agent:n,server:o}:null}function a(e,t){return`agent:${e}:${t}`}function d(e){return v[String(e||"")]||null}function S({agent:e,server:t}){const n=p[e]||e,o=t===l?`${n} ${d(e)?.label||"tools"}`:`${t} (${n})`;return{id:a(e,t),name:o,enabled:!0,from:{agent:e,server:t}}}function g(e,t=[],{builtin:n=!1}={}){const o=t.filter(i=>!/^chatpanel/i.test(i.server)).map(i=>({server:i.server,kind:i.kind})).sort((i,r)=>i.server.localeCompare(r.server));return n&&d(e)&&o.unshift({server:l,kind:"builtin"}),o}function b(e=[],t=[]){const n=new Set((t||[]).map(f).filter(Boolean).map(r=>a(r.agent,r.server))),o=[],i=new Set;for(const r of e||[])for(const s of r.mcpServers||[]){const c=a(r.id,s.server);i.add(c),o.push({agent:r.id,server:s.server,kind:s.kind,on:n.has(c)})}for(const r of(t||[]).map(f).filter(Boolean)){const s=a(r.agent,r.server);i.has(s)||o.push({agent:r.agent,server:r.server,kind:"missing",on:!0})}return o}function m(e=[],{agent:t,server:n},o){const i=a(t,n),r=(e||[]).filter(s=>{const c=f(s);return!c||a(c.agent,c.server)!==i});return o?[...r,S({agent:t,server:n})]:r}function x(e=[],t=""){return t?(Array.isArray(e)?e:[]).filter(n=>f(n)?.agent!==t):e}export{p as AGENT_SERVER_LABELS,l as BUILTIN_SERVER,a as agentServerId,g as agentServerList,S as agentServerRecord,f as agentServerRef,b as agentServerRows,d as builtinServer,m as toggleAgentServer,x as withoutOwnServers};
|
package/src/events/compaction.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import{keepRecentFor as
|
|
1
|
+
import{keepRecentFor as p}from"./context-window.js";const g="You compress a conversation into a compact but COMPLETE summary for continuation. Preserve: the user’s goals, key facts, decisions made, current task/automation state, open questions, and specifics needed to keep going. Terse bullet points. No preamble.",h=4e3;function c(e=[]){return(Array.isArray(e)?e:[]).filter(n=>n&&!n.pending&&(n.role==="user"||n.role==="assistant")&&(n.content||n.attachments?.length))}function x({messages:e=[],keepRecent:n=4,budget:t=0,tokensOf:o=null}={}){const r=c(e);let i=Math.max(1,Math.floor(Number(n)||4));if(t>0&&typeof o=="function")for(;i>1&&r.slice(r.length-i).reduce((a,m)=>a+(o(m)||0),0)>t;)i-=1;if(r.length<=i+1)return null;const s=r.slice(0,r.length-i),l=r.slice(r.length-i),u=s.map(a=>`${a.role==="user"?"User":"Assistant"}: ${String(a.content||"").slice(0,h)}`).join(`
|
|
2
2
|
|
|
3
|
-
`);return{fold:s,keep:l,uptoId:s[s.length-1].id,transcript:u}}function
|
|
4
|
-
|
|
3
|
+
`);return{fold:s,keep:l,uptoId:s[s.length-1].id,transcript:u}}function y({window:e=0,reasoning:n=!1}={}){const t=Number(e)||0,o=t?Math.min(1200,Math.max(256,Math.round(t/10))):1200,r=n?t?Math.min(4096,Math.max(1024,Math.round(t*.25))):2048:0,i=o+r,s=t?Math.max(512,Math.floor(t*.9)-i-300):0;return{summaryTokens:o,maxTokens:i,transcriptTokens:s}}function M(e="",n=0){const t=String(e||""),o=Math.max(0,Number(n)||0)*4;return!o||t.length<=o?t:`(earlier messages are in the earlier summary)
|
|
4
|
+
|
|
5
|
+
${t.slice(t.length-o).replace(/^[^\n]*\n/,"")}`}function S({transcript:e="",previousSummary:n=""}={}){return`${n?`Earlier summary to fold in:
|
|
6
|
+
${n}
|
|
5
7
|
|
|
6
8
|
`:""}Summarize the conversation so far:
|
|
7
9
|
|
|
8
|
-
${e}`}function
|
|
10
|
+
${e}`}function k({summary:e,uptoId:n,now:t=Date.now()}={}){return{summary:String(e||"").trim(),uptoId:n,ts:t}}function A(e=[],n=null){const t=c(e);if(!n?.uptoId)return t;const o=t.findIndex(r=>r.id===n.uptoId);return o>=0?t.slice(o+1):t}function E(e="",n=null){const t=String(n?.summary||"").trim();return t?`${e?`${e}
|
|
9
11
|
|
|
10
12
|
`:""}[Summary of the earlier part of this conversation — continue seamlessly; do not mention this summary]
|
|
11
|
-
${
|
|
13
|
+
${t}`:e||""}const f=36e4;function $(e=[],{maxChars:n=f}={}){const t=Array.isArray(e)?e:[];let o=0,r=t.length;for(;r>0;){const i=String(t[r-1]?.content??"").length+16;if(o+i>n&&r<t.length)break;o+=i,r-=1}return{kept:t.slice(r),elided:r}}export{g as COMPACTION_SYSTEM,f as SEED_MAX_CHARS,M as boundTranscript,c as compactable,y as compactionBudget,S as compactionPrompt,k as compactionRecord,p as keepRecentFor,A as messagesAfter,x as planCompaction,$ as seedWithin,E as systemWithSummary};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const a=[[/^apple-on-device$|apple[-_ ]?foundation/,4096],[/gemini-?nano/,4096]],d=[[/gpt-4\.1/,1e6],[/gpt-5|o3|o4|o1/,2e5],[/gpt-4o|gpt-4-turbo/,128e3],[/claude-(3|4|5|opus|sonnet|haiku|fable)/,2e5],[/gemini-(1\.5|2|2\.5|3)/,1e6],[/gemini/,1e6],[/deepseek/,128e3],[/mistral-large|mixtral|codestral/,128e3],[/grok/,128e3],[/llama-3\.[1-3]|llama-4/,128e3]];function x(t={},n=null){const r=String(t.id||""),e=String(t.model||t.id||"").toLowerCase(),u=n&&(n[l(t)]||n[e]||n[String(t.model||"")]||(t.gateway?0:n[r]));if(Number(u)>0)return Number(u);const i=Number(t.window||t.contextLength||t.contextWindow||0);if(i>0)return i;for(const[o,c]of a)if(o.test(e))return c;if(t.reach==="device"||t.kind==="webllm")return 0;for(const[o,c]of d)if(o.test(e))return c;return 0}function l(t={}){const n=String(t.id||""),r=String(t.model||"");return r?`${n}:${r}`:n}const m=.85,f=8192,p=t=>Number(t)>0&&Number(t)<=f,w=2;function _({promptTokens:t=0,floorTokens:n=0,window:r=0,reserve:e=1024,headroom:u=m}={}){const i=Number(r)||0;if(!i)return{status:"unknown",budget:0,over:0,window:0};const o=Math.max(0,Math.floor(i*u)-Math.max(0,Number(e)||0)),c=Math.max(0,Number(t)||0),s=Math.max(0,Number(n)||0);return c<=o?{status:"ok",budget:o,over:0,window:i}:s<=o?{status:"compact",budget:o,over:c-o,window:i}:{status:"too-big",budget:o,over:s-o,window:i}}function h({maxTokens:t=0,window:n=0,reasoning:r=!1}={}){const e=Math.max(0,Number(t)||0);if(!r)return e||1024;const u=Number(n)||0,i=u?Math.min(8192,Math.max(2048,Math.round(u*.3))):4096;return Math.max(e,i)}function b(t=0){const n=Number(t)||0;return n?n<=8e3?2:n<=32768?4:n<=128e3?8:12:4}function N({floorTokens:t=0,reserve:n=1024,headroom:r=m}={}){const e=Math.max(0,Number(t)||0);return e?Math.ceil((e+Math.max(0,Number(n)||0))/r):0}function g(t){return/context.{0,8}(length|window|size)|context_length_exceeded|prompt is too long|too many tokens|maximum context|exceed.{0,20}context|reduce the (length|number|size)|input is too long|token limit|n_ctx|kv cache|longer than .{0,80}\bwindow\b|exceed.{0,30}\bwindow\b/i.test(String(t?.message||t||""))}export{m as FIT_HEADROOM,f as SMALL_WINDOW,w as SMALL_WINDOW_ROUNDS,h as answerReserve,_ as fitFor,g as isContextLimitError,p as isSmallWindow,b as keepRecentFor,N as minWindowFor,l as observedKey,x as windowOf};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{SECRET_DIR_NAMES as R,SECRET_DIR_PAIRS as I,SECRET_FILE_RES as C,SECRET_FILE_ALLOW as k}from"./secret-names.js";const S="write_file",T="edit_file",_=1024*1024,$=1200,L=new Set(["library","appdata"]),m=r=>String(r).split(/[\\/]+/).filter(Boolean),E=r=>/^[a-z]:[\\/]/i.test(r);function b(r,{home:a=""}={}){const h=String(r??"").trim();if(!h)return{ok:!1,why:"no path was given"};if(!a)return{ok:!1,why:"the home folder is not known here"};if(/\0/.test(h))return{ok:!1,why:"the path is not a valid file name"};const l=E(a),d=l?E(h):h.startsWith("/"),f=h==="~"?a:/^~[\\/]/.test(h)?`${a}/${h.slice(2)}`:d?h:`${a}/${h}`,c=m(f),y=m(a);if(c.some(n=>n===".."||n==="."))return{ok:!1,why:'the path may not contain "." or ".."'};const g=(n,o)=>l?n.toLowerCase()===o.toLowerCase():n===o;if(c.length<=y.length||!y.every((n,o)=>g(n,c[o])))return{ok:!1,why:"files can only be written inside your home folder"};const t=c.slice(y.length);if(t.some(n=>n.startsWith(".")&&!k.test(n)))return{ok:!1,why:"hidden files and folders (settings, keys, shell and git config) are not written from the chat"};if(L.has(t[0].toLowerCase()))return{ok:!1,why:`${t[0]} holds what runs at login and app settings — not written from the chat`};if(t.some(n=>R.has(n)))return{ok:!1,why:"that folder holds credentials"};if(I.some(([n,o])=>t.some((i,s)=>i===n&&t[s+1]===o)))return{ok:!1,why:"that folder holds credentials"};const e=t.at(-1);if(!k.test(e)&&C.some(n=>n.test(e)))return{ok:!1,why:`"${e}" is a credential file name`};const w=l?"\\":"/";return{ok:!0,path:l?c.join(w):`/${c.join(w)}`}}function D({home:r,lstatSync:a,mkdirSync:h,writeFileSync:l,renameSync:d,rmSync:f,readFileSync:c=null,random:y=()=>Math.random().toString(36).slice(2,10)}={}){const g=E(String(r||"")),t=g?"\\":"/",e=o=>g?o.join(t):`/${o.join(t)}`,w=o=>{try{return a(o)}catch{return null}},n=o=>{const i=b(o,{home:r});if(!i.ok)throw new Error(i.why);const s=m(i.path);for(let p=m(r).length+1;p<=s.length;p++){const u=w(e(s.slice(0,p)));if(!u)break;if(u.isSymbolicLink())throw new Error(`${e(s.slice(0,p))} is a link, and a link is never followed`)}return{abs:i.path,parent:e(s.slice(0,-1))}};return{async exists(o){try{return!!w(n(o).abs)}catch{return!1}},...typeof c=="function"?{async read(o){const{abs:i}=n(o),s=w(i);if(!s)throw new Error(`${i} does not exist`);if(s.isDirectory())throw new Error(`${i} is a folder`);if(s.size>_)throw new Error("the file is too large to edit from the chat");return String(c(i,"utf8"))}}:{},async write(o,i){const{parent:s}=n(o);h(s,{recursive:!0});const{abs:p}=n(o);if(w(p)?.isDirectory())throw new Error(`${p} is a folder`);const u=`${s}${t}.chatpanel-${y()}.tmp`;l(u,i);try{d(u,p)}catch(x){try{f(u,{force:!0})}catch{}throw x}return{path:p}}}}function v(r){if(typeof r!="string")return{ok:!1,why:"the content must be text"};const a=new TextEncoder().encode(r).length;return a>_?{ok:!1,why:`the content is ${a} bytes; at most ${_} are written from the chat`}:{ok:!0,bytes:a}}function W({path:r,content:a="",replaces:h=!1}){const l=String(a),d=l.length>$?`${l.slice(0,$)}
|
|
2
|
+
… (${l.length-$} more characters)`:l;return{title:h?"Replace this file?":"Create this file?",detail:`${r}${h?`
|
|
3
|
+
It exists; its contents will be replaced.`:""}
|
|
4
|
+
|
|
5
|
+
${d||"(empty file)"}`}}const N={name:S,description:"Create or replace a text file on the person's computer, inside their home folder (~). The person sees the path and content and approves each write.",parameters:{type:"object",properties:{path:{type:"string",description:"Where, ~ for the home folder — e.g. ~/projects/hello.txt. Missing folders are created."},content:{type:"string",description:"The whole text of the file; leave it out for an empty file."}},required:["path"]}},j={name:T,description:"Change part of a text file on the person's computer: replace old_text, copied exactly from the file (read it first), with new_text. The person approves each edit.",parameters:{type:"object",properties:{path:{type:"string",description:"The file, ~ for the home folder."},old_text:{type:"string",description:"The exact text there now — enough lines to be found once."},new_text:{type:"string",description:"What replaces it; empty to delete it."},replace_all:{type:"boolean",description:"Replace every occurrence, not just one."}},required:["path","old_text","new_text"]}};function A(r,a,h,{all:l=!1}={}){const d=String(a??""),f=String(h??"");if(!d)return{ok:!1,why:"old_text is empty — copy the exact text to change from the file"};if(d===f)return{ok:!1,why:"old_text and new_text are the same — nothing would change"};const c=String(r).split(d).length-1;return c?c>1&&!l?{ok:!1,why:`old_text is in the file ${c} times — include more of the surrounding lines so it is found once, or set replace_all`}:{ok:!0,text:l?String(r).split(d).join(f):String(r).replace(d,()=>f),count:l?c:1}:{ok:!1,why:"old_text is not in the file — read the file again and copy the text exactly, spaces and line breaks included"}}function P({path:r,oldText:a="",newText:h="",count:l=1}){const d=c=>c.length>$/2?`${c.slice(0,$/2)}
|
|
6
|
+
… (${c.length-$/2} more characters)`:c,f=(c,y)=>d(String(c)).split(`
|
|
7
|
+
`).map(g=>`${y} ${g}`).join(`
|
|
8
|
+
`);return{title:"Edit this file?",detail:`${r}${l>1?` — ${l} places`:""}
|
|
9
|
+
|
|
10
|
+
${f(a,"−")}
|
|
11
|
+
${h?f(h,"+"):"+ (removed)"}`}}function O({fs:r,confirm:a,home:h,named:l=[]}={}){if(typeof r?.write!="function")throw new Error("fileWriteProvider: fs.write required");const d=typeof r.resolve=="function"?t=>r.resolve(t).catch(e=>({ok:!1,why:e?.message||String(e)})):async t=>{const e=b(t,{home:h});return e.ok?{...e,exists:typeof r.exists=="function"?!!await r.exists(e.path).catch(()=>!1):!1}:e},f=typeof r.read=="function";async function c(t){const e=await d(t?.path);if(!e?.ok)return`Not edited: ${e?.why||"the path was refused"}.`;if(!e.exists)return`Not edited: ${e.path} does not exist — write_file creates a file.`;let w;try{w=String(await r.read(e.path))}catch(u){return`Not edited: could not read ${e.path} (${u?.message||u}).`}const n=t?.old_text??t?.oldText??t?.old_string,o=t?.new_text??t?.newText??t?.new_string??"",i=A(w,n,o,{all:t?.replace_all===!0});if(!i.ok)return`Not edited: ${i.why}.`;const s=v(i.text);if(!s.ok)return`Not edited: ${s.why}.`;if(typeof a!="function")return"Not edited: there is no way to ask the person here, and nothing is changed without them.";if(await Promise.resolve(a({path:e.path,content:i.text,replaces:!0,edit:!0,...P({path:e.path,oldText:String(n),newText:String(o),count:i.count})})).catch(()=>"deny")!=="allow")return`Not edited: the person declined. Nothing was changed at ${e.path}.`;try{if(String(await r.read(e.path))!==w)return`Not edited: ${e.path} changed while the person was deciding — read it again and redo the edit.`;await r.write(e.path,i.text)}catch(u){return`Not edited: ${u?.message||u}`}return`Edited ${e.path}: ${i.count} place${i.count>1?"s":""} changed.`}const y=(Array.isArray(l)?l:[]).filter(t=>typeof t=="string"&&t);return{...y.length?{quiet:!0,hint:()=>`[Chap] This conversation names ${y.slice(0,3).map(t=>t.split(/[\\/]/).pop()).join(", ")} — listed under ATTACHED PATHS. Read it with \`files\` (action "read")${f?', then change it through `tools`: {"action":"edit_file","args":{"path":"…","old_text":"exact text from the file","new_text":"…"}} — or write_file for a whole new file':", then write_file to replace it"}. The person approves each change on a card.`}:{},specs:f?[N,j]:[N],async execute(t,e,w={}){if(t===T&&f)return c(e);if(t!==S)return null;const n=e?.content==null?["text","query"].find(x=>typeof e?.[x]=="string"&&e[x].trim()):null;n&&w?.shims?.fire?.("write.content-alias",{from:n});const o=e?.content??(n?e[n]:""),i=v(o);if(!i.ok)return`Not written: ${i.why}.`;const s=await d(e?.path);if(!s?.ok)return`Not written: ${s?.why||"the path was refused"}.`;if(typeof a!="function")return"Not written: there is no way to ask the person here, and nothing is written without them.";const p=!!s.exists;if(await Promise.resolve(a({path:s.path,content:o,replaces:p,...W({path:s.path,content:o,replaces:p})})).catch(()=>"deny")!=="allow")return`Not written: the person declined. Nothing was changed at ${s.path}.`;try{await r.write(s.path,o)}catch(x){return`Not written: ${x?.message||x}`}return`${p?"Replaced":"Created"} ${s.path} (${i.bytes} bytes).`}}}export{j as EDIT_FILE_SPEC,T as EDIT_FILE_TOOL,N as WRITE_FILE_SPEC,S as WRITE_FILE_TOOL,_ as WRITE_MAX_BYTES,$ as WRITE_PREVIEW_CHARS,A as applyEdit,P as describeEdit,W as describeWrite,D as diskWriter,O as fileWriteProvider,v as writableContent,b as writablePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as
|
|
1
|
+
import{EventError as c}from"./event.js";const u=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--resume","{id}"],off:["--no-session-persistence"],name:["--name","{name}"]},envFrom:["~/.claude/settings.json","/etc/claude-code/managed-settings.json","/Library/Application Support/ClaudeCode/managed-settings.json"]},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",ownSandbox:"computer use (controlling the browser and other apps)",session:{resume:["resume","{id}"],off:["--ephemeral"]}},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--session-id","{id}"],off:null,name:["--name","{name}"]}},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable",ownModel:{state:"opencode/model.json",config:["opencode/opencode.json","opencode/opencode.jsonc"]},session:{resume:["--session","{id}"],off:null,name:["--title","{name}"]}},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),A=n=>String(n||"").toLowerCase().replace(/[^a-z]/g,""),g={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function s(n){const o=A(n);if(u[o])return{id:o,...u[o]};if(g[o])return{id:g[o],...u[g[o]]};const e=Object.entries(u).find(([i,t])=>o.includes(i)||o.includes(A(t.label)));return e?{id:e[0],...e[1]}:null}function S(n,{repointed:o=null}={}){const e=s(n);return e?o?{egress:"configurable",where:`a coding agent · model at ${o}`,note:`Re-pointed by you; ${e.how||"its own setting"}.`}:e.repoint==="yes"?{egress:"configurable",where:"a coding agent · model of your choosing",note:`Its model is a setting of its own — ${e.how}. Until you set one, whatever it defaults to.`}:e.repoint==="limited"?{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login. It can be re-pointed: ${e.how}.`}:{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login; this agent cannot be pointed elsewhere.`}:{egress:"internet",where:"a coding agent · its own model, elsewhere",note:"No card for this agent — assume its model is a vendor’s until you know otherwise."}}function m(n){if(n==null)return null;if(typeof n=="string")return m({flag:n,repeat:!0});if(typeof n!="object"||Array.isArray(n))throw new c("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const o=String(n.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(o))throw new c("SHAPE",`dirs: not a flag: ${JSON.stringify(n.flag)}`);const e=n.separator==null?null:String(n.separator);if(e!=null&&(e.length===0||/\s/.test(e)))throw new c("SHAPE","dirs: separator must be a non-empty run of non-space characters");return e!=null?{flag:o,separator:e}:{flag:o,repeat:!0}}function v({harness:n,roots:o=[],dirs:e}={}){const i=(Array.isArray(o)?o:[]).map(r=>String(r||"").trim()).filter(Boolean);if(!i.length)return[];const t=m(e!==void 0?e:s(n)?.dirs??null);return t?t.separator?[t.flag,i.join(t.separator)]:i.flatMap(r=>[t.flag,r]):[]}function $({harness:n,env:o={},home:e="",readFile:i=()=>null}={}){const t=s(n)?.ownModel;if(!t||!e&&!o.XDG_STATE_HOME)return"";const r=p=>{try{const d=i(p);return d?JSON.parse(String(d).replace(/^\s*\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")):null}catch{return null}},a=[o.XDG_CONFIG_HOME||`${e}/.config`,...e?[`${e}/Library/Application Support`]:[]];for(const p of a)for(const d of t.config||[]){const f=r(`${p}/${d}`);if(f&&typeof f.model=="string"&&f.model.trim())return""}const h=r(`${o.XDG_STATE_HOME||`${e}/.local/state`}/${t.state}`),l=Array.isArray(h?.recent)?h.recent[0]:null,w=l?.providerID&&l?.modelID?`${l.providerID}/${l.modelID}`:"";return/^[\w.-]+\/[\w./:@-]+$/.test(w)?w:""}function O(n,o){try{return!!m(o!==void 0?o:s(n)?.dirs??null)}catch{return!1}}const y=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function E({harness:n,mode:o,id:e="",name:i=""}={}){const t=s(n)?.session;if(!t)return[];if(o==="off")return Array.isArray(t.off)?[...t.off]:[];if(o==="name"){const r=String(i??"").replace(/\s+/g," ").trim().slice(0,120);return!r||r.startsWith("-")||!Array.isArray(t.name)?[]:t.name.map(a=>a==="{name}"?r:a)}if(o!=="resume"||!Array.isArray(t.resume))return[];if(!y.test(String(e)))throw new c("SHAPE",`harness session: ${JSON.stringify(String(e).slice(0,40))} is not a session id`);return t.resume.map(r=>r==="{id}"?String(e):r)}const I=n=>Array.isArray(s(n)?.session?.resume);export{u as HARNESS_CARDS,s as harnessCard,v as harnessDirArgs,S as harnessEgress,$ as harnessOwnModel,I as harnessResumes,E as harnessSessionArgs,O as harnessTakesDirs,m as normalizeDirsSpec};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{tomlValue as o,parseArray as d,parseInlineTable as l,parseScalar as m}from"./toml-lite.js";import{parseArgsInput as h}from"./mcp-args-env.js";import{parseArgsInput as b,argsToText as j,parseEnvInput as z,envToText as
|
|
2
|
-
`,r[
|
|
1
|
+
import{tomlValue as o,parseArray as d,parseInlineTable as l,parseScalar as m}from"./toml-lite.js";import{parseArgsInput as h}from"./mcp-args-env.js";import{parseArgsInput as b,argsToText as j,parseEnvInput as z,envToText as B,envLikeArgs as _}from"./mcp-args-env.js";function I(e,{keys:r=!1}={}){const t=String(e||"").trim();if(!t)return[];const n=v(t),s=n?g(n):y(t);return r?s:s.map(({key:a,...i})=>i)}function v(e){try{return JSON.parse(e)}catch{return null}}function g(e){const r=e?.mcpServers||e?.mcp_servers||e?.servers||e;return!r||typeof r!="object"?[]:r.command||r.url?[u("Imported MCP server",r)].filter(Boolean):Object.entries(r).map(([t,n])=>u(t,n)).filter(Boolean)}function y(e){const r=[],t=/^\s*\[(mcp_servers|mcpServers)\.([^\]]+)\]\s*$/gm;let n;for(;n=t.exec(e);)r.push({name:n[2].trim().replace(/^["']|["']$/g,""),start:t.lastIndex});return r.map((s,a)=>{const i=r[a+1]?.start?e.lastIndexOf(`
|
|
2
|
+
`,r[a+1].start-r[a+1].name.length-15):e.length,p=e.slice(s.start,i<s.start?e.length:i);return u(s.name,S(p))}).filter(Boolean)}function S(e){const r={};for(const i of["type","transport","command","url"]){const p=o(e,i);p!=null&&(r[i]=m(p))}const t=o(e,"args");t!=null&&(r.args=d(t));const n=o(e,"env")??o(e,"environment")??o(e,"environmentVariables");n!=null&&(r.env=l(n));const s=o(e,"headers");s!=null&&(r.headers=l(s));const a=o(e,"authorization")??o(e,"auth_header");return a!=null&&(r.headers={...r.headers||{},Authorization:m(a)}),r}function u(e,r={}){if(!r||typeof r!="object")return null;const t=f(r.command),n=f(r.url),s=String(r.type||r.transport||(t?"stdio":"http")).toLowerCase(),a={key:String(e||""),name:x(e),enabled:r.enabled!==!1};return t||s==="stdio"?t?{...a,transport:"stdio",command:t,args:h(r.args),env:c(r.env||r.environment||r.environmentVariables)}:null:n?{...a,transport:"http",url:n,headers:c(r.headers)}:null}function c(e){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).map(([r,t])=>[r,String(t)]))}function x(e){return String(e||"MCP server").replace(/[_-]+/g," ").replace(/\b[a-z]/g,r=>r.toUpperCase())}function f(e){return typeof e=="string"?e.trim():""}export{j as argsToText,_ as envLikeArgs,B as envToText,b as parseArgsInput,z as parseEnvInput,I as parseMcpConfig};
|
package/src/mcp-capabilities.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{skillIndex as
|
|
1
|
+
import{skillIndex as a,listRecords as d,readRecord as h,readPackageFile as p,preferredIndex as s}from"./skills.js";import{sanitizeUnicode as m,hasHiddenChars as u}from"./sanitize.js";const o=24e3;function l(){return[{name:"chatpanel_skill_list",description:"List the skills installed on this machine that ChatPanel can see — across every agent harness (Claude Code, Codex, Copilot, Gemini, Hermes, ~/.agents) and any configured folder. Returns each skill's name and one-line description. Call this first, then chatpanel_skill_open to load the instructions of the one that fits.",schema:{type:"object",properties:{}},async run(){const t=d(s(await a())).map(e=>({name:e.command||e.id,title:e.name,description:e.description||"",from:e.origin?.source||"local",...e.alsoIn?.length?{alsoIn:e.alsoIn}:{},references:(e.files?.references||[]).length||void 0}));return n(JSON.stringify({skills:t},null,2))}},{name:"chatpanel_skill_open",description:"Load one skill's full instructions by name (from chatpanel_skill_list). Follow what it returns. If the instructions point at reference files, read one with chatpanel_skill_read.",schema:{type:"object",properties:{name:{type:"string",description:"The skill name from chatpanel_skill_list."},from:{type:"string",description:"Optional: another agent's copy (claude, codex, opencode, copilot, gemini…) when the person asked for that one."}},required:["name"]},async run(t){const e=h(s(await a(),{source:String(t?.from||"")}),String(t?.name||"").trim());return e?n(e.prompt||"(this skill has no extra instructions — just apply it.)"):n(`No such skill "${t?.name}". Use chatpanel_skill_list to see what is available.`,!0)}},{name:"chatpanel_skill_read",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.",schema:{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."},from:{type:"string",description:"The same `from` the skill was opened with, if any."}},required:["name","path"]},async run(t){const e=await p(s(await a(),{source:String(t?.from||"")}),String(t?.name||"").trim(),String(t?.path||"").trim());if(e.error)return n(`Could not read it: ${e.error}`,!0);const i=e.text.length>o?`${e.text.slice(0,o)}
|
|
2
2
|
|
|
3
|
-
…[truncated]`:e.text;return
|
|
3
|
+
…[truncated]`:e.text;return n(i)}},{name:"chatpanel_sanitize_text",description:"Remove hidden and look-alike Unicode characters from text (zero-width joiners, bidirectional overrides, the tag block, homoglyphs) — the tricks used to hide instructions from a human while a model still sees them. Returns the cleaned text and what was removed. Use before trusting text pasted or fetched from an untrusted source. This is not full PII redaction (names, emails) — that lives in the ChatPanel gateway.",schema:{type:"object",properties:{text:{type:"string",description:"The text to sanitize."}},required:["text"]},async run(t){const e=String(t?.text??""),{clean:i,removed:r,findings:c}=m(e);return n(JSON.stringify({clean:i,hadHiddenCharacters:u(e),removed:r||0,findings:c||{}},null,2))}}]}function n(t,e=!1){return{content:[{type:"text",text:String(t)}],...e?{isError:!0}:{}}}function g(){return l().map(t=>({name:t.name,description:t.description,inputSchema:t.schema}))}async function k(t,e){const i=l().find(r=>r.name===t);if(!i)return null;try{return await i.run(e||{})}catch(r){return n(`error: ${r?.message||r}`,!0)}}export{g as capabilityToolSpecs,l as capabilityTools,k as runCapabilityTool};
|
package/src/server.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createServer as
|
|
3
|
-
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:
|
|
2
|
+
import{createServer as Le}from"node:http";import O from"node:os";import{randomBytes as We,randomInt as je,timingSafeEqual as Fe}from"node:crypto";import{mkdirSync as Je,writeFileSync as Xe,readFileSync as ae,existsSync as Ke}from"node:fs";import{join as M}from"node:path";import*as ze from"./engines/claude.js";import*as Ye from"./engines/codex.js";import*as Ve from"./engines/antigravity.js";import{pi as Qe,opencode as Ze,kiro as qe,copilot as et,deepseek as tt,hermes as nt}from"./engines/cli-agents.js";import{connectorsFor as ot}from"./connectors.js";import{agentServersFor as rt,resolveAgentServer as ie,builtinRefusal as at,narrowBuiltinList as it}from"./agent-mcp.js";import*as st from"./engines/custom.js";import{installService as ct,uninstallService as lt,serviceStatus as dt,restartService as se}from"./service.js";import{skillIndex as J,listRecords as ut,readRecord as ht,readPackageFile as pt,skillsHealth as ft,quarantinedSkills as mt,clearSkillCache as X,preferredIndex as K}from"./skills.js";import{writeSkillPackage as gt,writeSkillFile as wt,deleteSkillPackage as yt,SkillWriteError as bt}from"./skill-write.js";import{agentDefRoots as St,scanAgentDefs as kt,listAgentDefs as Tt,readAgentDef as vt,planAgentExport as xt,exportAgentDef as Et,agentDefsHealth as At,AgentDefError as Ot}from"./agent-defs.js";import{capabilityToolSpecs as Ct,runCapabilityTool as Pt}from"./mcp-capabilities.js";import{createSession as $t,deleteSession as ce,getSession as le,activeSession as Rt,relayToolCall as It}from"./mcp-sessions.js";import{DEFAULT_WORKSPACE as Nt,isDefaultWorkdir as Dt,resolveWorkdir as _t,writeScopeNote as Ht}from"./workdir.js";import{sandbox as z,runSandboxCli as Mt,withGrant as de,withAgentGrant as Bt,withoutOutsideWhenCapped as Gt,grantedWriteRoots as ue,acceptRefusalReport as Ut,liveProcesses as Lt,sandboxConfigFromEnv as Wt}from"./sandbox.js";import{createAccessGate as jt,chatKeyOf as Ft,chatFolders as Jt}from"./access-gate.js";import{signInDenial as Xt}from"./events/sandbox-policy.js";import{gitState as Kt,gitDelta as zt}from"./scm.js";import{listConnections as Yt,putConnection as Vt,removeConnection as Qt,runEnvFor as Zt,testConnection as qt,secretBackend as he}from"./connections.js";import{worktreeFor as pe,listWorktrees as en,removeWorktree as tn,withHook as nn,WORKTREE_ROOT as fe}from"./worktree.js";import{AGENT_CLIS as on,agentAvailable as rn,agentInstallDirs as an,enrichPath as sn,enrichAgentEnv as cn,findAgentBin as ln,forgetMisses as dn,primeAgentLookups as un,resolveCommand as me,isCompiledBinary as hn}from"./env.js";import"./sanitize.js";import{checkForUpdate as pn,selfUpdate as ge,isEmbedded as we}from"./update.js";import{callLocalMcp as fn,localMcpStatus as mn,signInLocalMcp as gn,signInStatusLocalMcp as wn}from"./mcp-local.js";import{assertPublicHttpUrl as ye,assertPublicWebUrl as be}from"./ssrf.js";import{startRun as Se,endRun as Y,cancelRun as yn,cancelAll as bn}from"./runs.js";import{closeWarmPools as Sn,warmStatus as kn}from"./warm.js";import{SESSION_AGENTS as ke,listSessions as Tn,readSession as vn,adoptSession as xn,catchUp as En}from"./agent-sessions.js";import{agentContext as An}from"./agent-context.js";import{normalizeThread as Te}from"./events/agent-thread.js";import{portClashPlan as On,serviceManagerOf as Cn,STANDBY_POLL_MS as Pn}from"./events/service-standby.js";import{holdThread as ve}from"./threads.js";import{oneReply as $n}from"./one-reply.js";import{createSnapshot as Rn}from"./health-snapshot.js";import{CompatError as P,anthropicError as V,anthropicStream as In,chatCompletionStream as Nn,completionStream as Dn,createAnthropicMessage as _n,createChatCompletion as Hn,createCompletion as Mn,createResponse as Bn,openAIError as S,parseAnthropicMessage as Gn,parseChatCompletion as Un,parseCompletion as Ln,parseResponse as Wn,responseStream as jn}from"./api-compat.js";import{callerTrust as Fn,isPaired as I,parseExtensionIds as Jn,capRunOptions as Xn,engineHonoursReach as Kn,createPairingStore as zn,formatPairingCode as Yn}from"./pii/trust.js";const y="0.51.1",v=process.env.CHATPANEL_BRIDGE_HOST||"127.0.0.1",k=Number(process.env.CHATPANEL_BRIDGE_PORT)||4319,x={claude:{engine:ze,label:"Claude Code"},codex:{engine:Ye,label:"Codex"},antigravity:{engine:Ve,label:"Antigravity",tools:!1},pi:{engine:Qe,label:"Pi"},opencode:{engine:Ze,label:"OpenCode"},hermes:{engine:nt,label:"Hermes"},kiro:{engine:qe,label:"Kiro"},copilot:{engine:et,label:"GitHub Copilot"},deepseek:{engine:tt,label:"DeepSeek Harness"},custom:{engine:st,label:"Custom",hidden:!0}};function xe(n){return!n||n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}const Vn=Jn(process.env.CHATPANEL_BRIDGE_EXTENSION_IDS);function N(n){return n.chatpanelTrust||(n.chatpanelTrust=Fn({origin:n.headers.origin||"",hasToken:Ce(n),extensionIds:Vn})),n.chatpanelTrust}function Qn(n){return n.startsWith("chrome-extension://")||n.startsWith("moz-extension://")||n.startsWith("http://localhost")||n.startsWith("http://127.0.0.1")||n.startsWith("http://[::1]")}function Zn(n,e){const t=n.headers.origin||"",r=xe(t);e.setHeader("Access-Control-Allow-Origin",r?t||"*":"null"),e.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Api-Key, Anthropic-Version, X-ChatPanel-Token"),e.setHeader("Vary","Origin")}const Q=new Set(["127.0.0.1","localhost","::1"]);function qn(n){if(!Q.has(v))return!0;const e=String(n.headers.host||"");if(!e)return!1;const t=e.replace(/:\d+$/,"").replace(/^\[|\]$/g,"").toLowerCase();return Q.has(t)}const D=M(O.homedir(),".chatpanel","bridge-token");let E="";function eo(){try{Ke(D)&&(E=ae(D,"utf8").trim()),E||(E=We(32).toString("hex"),Je(M(O.homedir(),".chatpanel"),{recursive:!0}),Xe(D,E,{mode:384}))}catch(n){u("error",`could not initialise bridge token: ${n?.message||n}`)}}const Ee=zn({random:()=>je(0,1e6)/1e6});function to(n){if(!E)return i(n,503,{error:"the bridge has no token to pair with (could not write ~/.chatpanel/bridge-token)"});const e=Ee.issue();return u("info","pairing code issued — valid for 5 minutes, one use"),i(n,200,{ok:!0,code:e.code,display:e.display,expiresAt:e.expiresAt})}async function no(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=Ee.claim(t?.code);return r.ok?(u("info",`paired a ${N(n)} client${n.headers.origin?` (${n.headers.origin})`:""}`),i(e,200,{ok:!0,token:E})):(u("info",`pairing refused (${r.reason}) from ${N(n)} caller`),i(e,403,{error:r.reason}))}function oo(n,e){const t=N(n);return i(e,200,{ok:!0,trust:t,paired:I(t),version:y})}let B=null;async function Ae(){if(B)return B;const{createChannelService:n}=await import("./channels/service.js");return B=n({home:M(O.homedir(),".chatpanel"),dataDir:M(O.homedir(),".chatpanel","channels"),bridge:{baseUrl:`http://127.0.0.1:${k}`,token:E},logger:{log:e=>u("info",e),warn:e=>u("info",e),error:e=>u("error",e)}}),B}async function Oe(n,e,t){try{const r=await Ae(),o=n.method==="POST"?await m(n):{};if(t==="status")return i(e,200,await r.status());if(t==="connect"){const a=await r.connect(o);return i(e,200,{ok:!0,...a})}return t==="pair"?i(e,200,await r.pair()):t==="unpair"?i(e,200,await r.unpair(String(o.actorId||""))):t==="settings"?i(e,200,await r.update(o)):t==="disconnect"?i(e,200,await r.stop({forget:!!o.forget})):i(e,404,{error:"unknown channel action"})}catch(r){return i(e,400,{error:r?.message||String(r)})}}function Ce(n){if(!E)return!1;const e=String(n.headers.authorization||""),t=(e.startsWith("Bearer ")?e.slice(7):String(n.headers["x-api-key"]||n.headers["x-chatpanel-token"]||"")).trim();if(!t)return!1;const r=Buffer.from(t),o=Buffer.from(E);return r.length===o.length&&Fe(r,o)}const ro=new Set(["/agent-context","/agent-sessions","/agent-sessions/read","/agent-sessions/adopt","/agent-sessions/catchup","/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/mcp-local","/mcp-local/signin","/mcp-remote","/fetch-title","/complete","/list-models","/agent-check","/update","/tool-result","/cancel","/channels/connect","/channels/pair","/channels/unpair","/channels/settings","/channels/disconnect","/connections","/worktrees","/pair/code"]),ao=new Set(["/debug"]),io=n=>ao.has(n),so=(n,e)=>n!=="GET"&&n!=="HEAD"&&(e==="/skills"||e.startsWith("/skills/")||e.startsWith("/agent-defs"));function co(n,e){if(!qn(n))return"forbidden host";const t=n.headers.origin||"";if(t&&!xe(t))return"forbidden origin";const r=n.method==="POST"&&ro.has(e)||n.method==="GET"&&io(e)||so(n.method,e);return r&&!(Qn(t)||Ce(n))?"forbidden: this endpoint requires the ChatPanel extension or a valid bridge token":r&&!I(N(n))&&!uo.has(e)?lo:null}const Pe=()=>we()?"chatpanel-gateway pair":"chatpanel-bridge pair",lo=`forbidden: this client is not paired with the bridge — run \`${Pe()}\` and enter the code in ChatPanel Settings`,uo=new Set(["/chat","/v1/chat/completions","/v1/completions","/v1/responses","/v1/messages","/complete","/list-models","/agent-check","/cancel","/tool-result"]);function Z(n,e,t){const r=N(n),o=Bt(e,Gt(Xn(t,r)));if(!Kn(e,o.reach))return{error:`${I(r)?"this caller's reach tier":"an unpaired client"} may only run the Claude engine (it is the one that enforces the tool ceiling) — ${I(r)?"raise the tier":`pair this client (${Pe()})`} to use ${e}`};const a=o.reach,c=I(r)?a==="device"?"Capped to plain chat by the caller's trust tier — no file, shell, web or MCP tools.":a==="trusted"?"Capped to read-only by the caller's trust tier — no writes, shell or web.":"":"Unpaired client: this run is plain chat — no file, shell, web or MCP tools. Pair this browser in ChatPanel → Settings → Coding Agents to unlock them.";return{options:o,note:c}}async function $e(n,e,t){const r=e?.message||String(e);try{const o=await z().status(),a=!!(o.enabled&&o.runtime)&&t?.outside!==!0,c=Xt(`${r}
|
|
3
|
+
${e?.detail||""}`,{grant:t,sandboxed:a,agent:n,agentLabel:x[n]?.label||n||"This agent"});if(c)return c.line}catch{}return r}function i(n,e,t){n.writeHead(e,{"Content-Type":"application/json"}),n.end(JSON.stringify(t))}function m(n){return new Promise((e,t)=>{let r="";n.on("data",o=>{r+=o,r.length>50*1024*1024&&t(new Error("Body too large"))}),n.on("end",()=>{try{e(r?JSON.parse(r):{})}catch(o){t(o)}}),n.on("error",t)})}const Re=Rn({compute:ho});async function ho(){await un();const n=await Promise.all(Object.entries(x).filter(([,a])=>!a.hidden).map(async([a,{engine:c,label:l,tools:s}])=>{const d=await c.available().catch(f=>({ok:!1,reason:String(f?.message||f)})),p=await ot(a).catch(()=>[]),w=await rt(a,{available:d.ok}).catch(()=>[]);return{id:a,label:l,available:d.ok,reason:d.reason,connectors:p,...w.length?{mcpServers:w}:{},...s===!1?{tools:!1}:{}}})),e=we()?{current:y,updateAvailable:!1,embedded:"gateway"}:await pn(y).catch(()=>({current:y,updateAvailable:!1})),t=await ft().catch(()=>null),r=await At().catch(()=>null),o=await z().status().catch(a=>({enabled:!1,reason:a.message}));return{agents:n,update:e,skills:t,agentDefs:r,sandboxStatus:o}}async function po(n,{fresh:e=!1}={}){e&&dn();const{at:t,value:{agents:r,update:o,skills:a,agentDefs:c,sandboxStatus:l}}=await Re.get({fresh:e});i(n,200,{ok:!0,version:y,agents:r,update:o,checkedAt:t,workspace:Nt,sandbox:l,localMcp:mn(),processes:Lt(),worktrees:fe,secretBackend:he(),warm:kn(),pairing:!0,...process.env.CHATPANEL_MANAGED_BY?{managedBy:String(process.env.CHATPANEL_MANAGED_BY).slice(0,32)}:{},...a?{skills:a}:{},...c?{agentDefs:c}:{}})}async function fo(n,e,t,r={}){const o=await J({extraDirs:e,workdir:t});i(n,200,{ok:!0,skills:ut(K(o,r)),problems:o.problems})}async function mo(n,e,t){i(n,200,{ok:!0,quarantined:await mt(e,t)})}async function go(n,e,t,r,o={}){const a=ht(K(await J({extraDirs:t,workdir:r}),o),e);if(!a)return i(n,404,{ok:!1,error:"unknown skill"});i(n,200,{ok:!0,skill:a})}async function wo(n,e,t,r,o,a={}){const c=await pt(K(await J({extraDirs:r,workdir:o}),a),e,t);if(c.error)return i(n,c.error==="unknown skill"?404:400,{ok:!1,error:c.error});i(n,200,{ok:!0,...c})}async function yo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{const r=await gt({skill:t?.skill,files:t?.files||[],overwrite:!!t?.overwrite});return X(),i(e,200,r)}catch(r){return i(e,q(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function bo(n,e,t,r){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}try{const a=await wt({name:t,path:r,text:o?.text??""});return X(),i(e,200,a)}catch(a){return i(e,q(a),{ok:!1,error:a.message,code:a.code||"ERROR"})}}async function So(n,e){try{const t=await yt({name:e});return X(),i(n,200,t)}catch(t){return i(n,q(t),{ok:!1,error:t.message,code:t.code||"ERROR"})}}function q(n){return n instanceof bt?n.code==="NOT_FOUND"?404:n.code==="EXISTS"||n.code==="FULL"?409:n.code==="REFUSED"||n.code==="OUTSIDE"?403:400:400}async function Ie(n,e){return kt({roots:St(process.env,O.homedir(),n,e)})}async function ko(n,e,t){const{index:r,quarantined:o,problems:a}=await Ie(e,t);i(n,200,{ok:!0,agents:Tt(r),...o.length?{quarantined:o.map(c=>({id:c.agent.id,path:c.relPath,source:c.source,verdict:c.scan.verdict}))}:{},...a.length?{problems:a}:{}})}async function To(n,e,t,r){const{index:o}=await Ie(t,r),a=vt(o,e);if(!a)return i(n,404,{ok:!1,error:"unknown agent definition"});i(n,200,{ok:!0,...a})}async function vo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,{ok:!0,...await xt({agent:t?.agent,to:t?.to})})}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}async function xo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}try{return i(e,200,await Et({agent:t?.agent,to:t?.to,overwrite:!!t?.overwrite}))}catch(r){return i(e,Ne(r),{ok:!1,error:r.message,code:r.code||"ERROR"})}}function Ne(n){if(n instanceof Ot){if(n.code==="NOT_OURS")return 409;if(n.code==="TARGET")return 400}return 400}async function Eo(){return(await Promise.all(Object.entries(x).filter(([,e])=>!e.hidden).map(async([e,t])=>({id:e,object:"model",created:0,owned_by:"chatpanel",available:!!(await t.engine.available().catch(()=>({ok:!1}))).ok})))).filter(e=>e.available).map(({available:e,...t})=>t)}async function De(n,e=""){const t=await Eo();if(e){const r=t.find(o=>o.id===e);return r?i(n,200,r):i(n,404,S(new P(`Model "${e}" not found`,404,"model")))}return i(n,200,{object:"list",data:t})}async function Ao(n){try{const e=await ge(y);i(n,200,{ok:!0,updated:!0,from:e.from,to:e.to}),n.on("finish",()=>setTimeout(()=>se(),400))}catch(e){i(n,400,{ok:!1,error:String(e?.message||e)})}}async function Oo(n,e){let t;try{t=await m(n)}catch(h){return i(e,400,{error:"Bad JSON: "+h.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=Z(n,t.agent,t.options||{});if(o.error)return i(e,403,{error:o.error});t.options=o.options,Array.isArray(t.images)&&t.images.length&&u("info",`chat: ${t.agent} received ${t.images.length} image(s)`),e.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});const a=h=>{e.writableEnded||e.write(`data: ${JSON.stringify(h)}
|
|
4
4
|
|
|
5
|
-
`)};let
|
|
5
|
+
`)};let c=!1;const l=`run_${Math.random().toString(36).slice(2,10)}`,s=Se(l),d={signal:s.signal,abort:()=>s.cancel("client")},p=()=>{c=!0,s.cancel("disconnected")};n.on("close",p),e.on("close",p),e.on("error",p);const w=h=>{c||a(h)};a({type:"run",id:l}),o.note&&a({type:"status",text:o.note});let f=null;if(t.options?.workspace&&typeof t.options.workspace=="object"){const h=t.options.workspace;if(f=await pe({repo:h.repo,projectId:h.projectId,jobId:h.jobId,base:h.base||null}),f.error){a({type:"error",error:`workspace: ${f.error}`}),Y(l),e.writableEnded||e.end();return}}const _=f?f.path:_t(t.options?.workingDir),W=Ft(t.agent,t.options),te=W?Jt(W):[];te.length&&(t.options={...t.options,sandbox:{...t.options.sandbox||{},write:[...new Set([...Array.isArray(t.options.sandbox?.write)?t.options.sandbox.write:[],...te])]}});let C=null;{const h=_,T=!!f||!Dt(t.options?.workingDir),g=Ht(t.agent,t.options?.permissionMode,h,ue(h,{grant:t.options?.sandbox}));a({type:"workdir",path:h,isDefault:!T,writeScope:g||void 0}),a({type:"status",text:`Working in ${h}${T?"":" (default)"}`}),g&&a({type:"status",text:g}),C=await Kt(h),C&&a({type:"scm",phase:"before",...C})}let j=null;if(C||f){const h=Array.isArray(t.options?.grants)?t.options.grants:[],{env:T,connection:g}=Zt({remote:C?.remote||null,grants:h,branch:f?.branch||null,connectionId:t.options?.connectionId||null});j=nn(T),f&&a({type:"workspace",path:f.path,branch:f.branch,base:f.base,created:f.created,repo:f.repo,...g?{connection:g}:{}}),g&&a({type:"status",text:`Git credential: ${g.kind} · ${g.host}${g.hasSecret?"":" (no token stored)"} · push: ${T.CHATPANEL_SCM_PUSH==="own"?`${f?.branch} only`:T.CHATPANEL_SCM_PUSH}`})}const F=t.approvals===!0,b={...t.options||{},...f?{workingDir:f.path}:{},...j?{runEnv:j}:{},approvals:F};let R=null;(t.pageTools?.specs?.length||F)&&(R=$t(w,t.pageTools?.specs||[]),b.permissionSession=R,t.pageTools?.specs?.length&&(b.mcp={url:`http://${v}:${k}/mcp/${R.id}`,serverName:"chatpanel_browser",specs:t.pageTools.specs}));const Ge=Wt();let ne=b.sandbox||null;F&&Ge.enabled&&(process.env.CHATPANEL_SANDBOX_RUNTIME||"srt")==="srt"&&b.sandbox?.outside!==!0&&(b.accessGate=jt({agent:t.agent,label:x[t.agent]?.label||t.agent,key:W,cwd:_,roots:()=>ue(_,{grant:ne})}));try{const h=$n(w),T=(g,H)=>de(g.sandbox,()=>r.engine.chat({messages:Array.isArray(t.messages)?t.messages:[],system:H,options:g,images:Array.isArray(t.images)?t.images:[]},h.emit,{signal:d.signal}));await ve(t.agent,b,d.signal,async()=>{await T(b,t.system||"");let g=b;for(let H=0;H<2&&b.accessGate?.restart().length&&!d.signal.aborted;H++){const oe=b.accessGate.take();g={...g,sandbox:{...g.sandbox||{},write:[...new Set([...Array.isArray(g.sandbox?.write)?g.sandbox.write:[],...oe])]}},ne=g.sandbox;const re=oe.map(Ue=>b.accessGate.short(Ue)).join(", ");h.seam(),w({type:"status",text:`Restarted with write access to ${re} — carrying on`}),await T(g,`${t.system||""}
|
|
6
6
|
|
|
7
|
-
[ChatPanel] The person has just allowed writing in ${
|
|
7
|
+
[ChatPanel] The person has just allowed writing in ${re}, and you were restarted with that access. Carry on with their request: do the step that was blocked. Do not ask again.`.trim())}h.finish()})}catch(h){u("error",`${t.agent} chat failed: ${h?.message||h}`),h?.detail&&u("error",`${t.agent} said: ${h.detail}`),a({type:"error",error:await $e(t.agent,h,b.sandbox)})}finally{if(!c){const h=await zt(_,C).catch(()=>null);h&&w({type:"scm",phase:"after",...h})}Y(l),R&&ce(R.id),e.writableEnded||e.end()}}async function Co(n,e,t){if(n.method==="GET"&&t==="/connections")return i(e,200,{ok:!0,connections:Yt(),secretBackend:he()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/connections")try{return i(e,200,{ok:!0,connection:Vt(r.connection||r,{token:r.token||null})})}catch(a){return i(e,400,{error:String(a?.message||a)})}const o=/^\/connections\/([a-zA-Z0-9_-]{1,64})\/(test|delete)$/.exec(t);return o?o[2]==="delete"?i(e,200,{ok:Qt(o[1])}):i(e,200,qt(o[1],r.remote||"")):i(e,404,{error:"Not found"})}async function Po(n,e,t){if(n.method==="GET"&&t==="/worktrees")return i(e,200,{ok:!0,root:fe,worktrees:await en()});if(n.method!=="POST")return i(e,405,{error:"method not allowed"});const r=await m(n);if(t==="/worktrees"){const o=await pe({repo:r.repo,projectId:r.projectId,jobId:r.jobId,base:r.base||null});return i(e,o.error?400:200,o.error?{error:o.error}:{ok:!0,...o})}if(t==="/worktrees/remove"){const o=await tn({projectId:r.projectId,jobId:r.jobId,force:!!r.force});return i(e,o.ok?200:400,o)}return i(e,404,{error:"Not found"})}async function A(n,e,t){const r=x[n.agent];if(!r||r.hidden)throw new P(`Unknown ChatPanel agent "${n.agent}"`,400,"model");const o=await r.engine.available().catch(d=>({ok:!1,reason:d?.message||String(d)}));if(!o.ok)throw new P(o.reason||`${n.agent} is unavailable`,503,"model");const a=`run_${Math.random().toString(36).slice(2,10)}`,c=Se(a),l=()=>c.cancel("disconnected");t.on("close",l);let s="";try{return await de(n.options?.sandbox,()=>ve(n.agent,n.options,c.signal,()=>r.engine.chat({messages:n.messages,system:n.system,options:n.options,images:[]},d=>{d?.type==="delta"&&d.text?(s+=d.text,e(d.text)):d?.type==="done"&&d.text&&!s&&(s=d.text,e(d.text))},{signal:c.signal}))),s}catch(d){throw d instanceof Error&&!(d instanceof P)&&(d.message=await $e(n.agent,d,n.options?.sandbox)),d}finally{t.off("close",l),Y(a)}}function G(n){n.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"})}function $(n,e){n.writableEnded||n.write(`data: ${typeof e=="string"?e:JSON.stringify(e)}
|
|
8
8
|
|
|
9
9
|
`)}function U(n,e,t){n.writableEnded||n.write(`event: ${e}
|
|
10
10
|
data: ${JSON.stringify(t)}
|
|
11
11
|
|
|
12
|
-
`)}async function L(n,e,t,o){try{const r=t(await m(n)),a=Q(n,r.agent,r.options||{});if(a.error)throw new P(a.error,403,"permission");return r.options=a.options,r}catch(r){return i(e,r?.status||400,o(r?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${r.message}`):r)),null}}async function vo(n,e){const t=await L(n,e,_n,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Rn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Cn(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function Ao(n,e){const t=await L(n,e,Hn,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,In(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Pn(t.requestedModel,r=>$(e,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){$(e,S(r))}$(e,"[DONE]"),e.end()}async function Oo(n,e){const t=await L(n,e,Mn,S);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,Nn(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,S(r))}G(e);const o=Bn(t.requestedModel,r=>U(e,r.type,r));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){const a={type:"error",sequence_number:0,...S(r)};U(e,"error",a)}e.end()}async function Co(n,e){const t=await L(n,e,Dn,Y);if(!t)return;if(!t.stream)try{const r=await A(t,()=>{},e);return i(e,200,$n(t.requestedModel,r))}catch(r){return e.writableEnded?void 0:i(e,r?.status||500,Y(r))}G(e);const o=On(t.requestedModel,(r,a)=>U(e,r,a));try{await A(t,r=>o.delta(r),e),o.done()}catch(r){U(e,"error",Y(r))}e.end()}async function Po(n,e){let t={};try{t=await m(n)||{}}catch{}const o=String(t.id||"").trim(),r=o?pn(o,"stopped"):!1;return r&&u("info",`cancel: ${o} stopped by client`),i(e,200,{ok:!0,cancelled:r})}async function Ne(n,e,t){let o;try{o=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const r=t?se(t):At(),a=d=>{r&&e.setHeader("Mcp-Session-Id",r.id),i(e,200,{jsonrpc:"2.0",id:o.id??null,result:d})},s=(d,l)=>i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:d,message:l}});if(o.id==null)return e.writeHead(202),e.end();if(o.method==="initialize")return a({protocolVersion:o.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:y}});const c=xt();if(o.method==="tools/list"){const d=r?r.specs.map(l=>({name:l.name,description:l.description,inputSchema:l.parameters||{type:"object",properties:{}}})):[];return a({tools:[...c,...d]})}if(o.method==="tools/call"){const d=await Et(o.params?.name,o.params?.arguments||{});if(d)return a(d);if(!r)return s(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await Ot(r,o.params?.name,o.params?.arguments||{}))}catch(l){return a({content:[{type:"text",text:`error: ${l?.message||l}`}],isError:!0})}}return s(-32601,`Method not found: ${o.method}`)}async function $o(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{},r=t.message;if(!o.command||!r)return i(e,400,{error:"need server.command and message"});try{const a=await ln({key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox},r);return r.id==null?(e.writeHead(202),e.end()):i(e,200,a)}catch(a){return i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ro(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=t.server||{};if(!o.command)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});const r={key:o.id,command:o.command,args:o.args,env:o.env,cwd:o.cwd,sandbox:o.sandbox};try{return i(e,200,t.status?hn(r):await un(r))}catch(a){return i(e,200,{state:"failed",error:String(a?.message||a)})}}async function Io(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:o,headers:r,message:a}=t||{};if(!o||!a)return i(e,400,{error:"need url and message"});let s;try{s=ge(o)}catch(p){return i(e,400,{error:String(p?.message||p)})}const c={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(r&&typeof r=="object")for(const[p,w]of Object.entries(r)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(c[p]=String(w))}const d=new AbortController,l=setTimeout(()=>d.abort(),3e4);try{const p=await fetch(s.href,{method:"POST",headers:c,body:JSON.stringify(a),redirect:"follow",signal:d.signal});try{p.url&&ge(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${s.host}: ${w}`})}finally{clearTimeout(l)}}const De=256*1024,No=5,Do=8e3;async function _o(n){let e=we(n);const t=new AbortController,o=setTimeout(()=>t.abort(),Do);try{for(let r=0;r<=No;r++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=we(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const s=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(s)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:Bo(await Ho(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(o)}}async function Ho(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,De);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let o="",r=0;try{for(;;){const{done:a,value:s}=await e.read();if(a||(r+=s.byteLength,o+=t.decode(s,{stream:!0}),/<\/title\s*>/i.test(o)||r>=De))break}}finally{try{await e.cancel()}catch{}}return o}function Mo(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function Bo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Mo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Go(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=t&&t.url;if(!o||typeof o!="string")return i(e,400,{error:"need url"});try{const r=await _o(o);return i(e,200,{title:r.title||null,url:r.url||o})}catch(r){const a=r?.name==="AbortError"?"timed out":String(r?.message||r);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Uo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=se(t.session);if(!o)return i(e,404,{error:"no such session"});const r=o.pending.get(t.id);return r?(o.pending.delete(t.id),r.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Lo(n,e){let t;try{t=await m(n)}catch(d){return i(e,400,{error:"Bad JSON: "+d.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});const r=String(t.prompt||"").slice(0,6e3);if(!r)return i(e,400,{error:"Empty prompt"});const a=t.model||"",s=Q(n,t.agent,{model:a});if(s.error)return i(e,403,{error:s.error});const c=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let d="";return typeof o.engine.complete=="function"?d=await o.engine.complete({prompt:r,system:c,model:a}):await o.engine.chat({messages:[{role:"user",content:r}],system:c,options:s.options},l=>{l.type==="delta"?d+=l.text||"":l.type==="done"&&l.text&&(d+=l.text)}),i(e,200,{text:(d||"").trim()})}catch(d){return i(e,502,{error:d?.message||String(d)})}}async function Wo(n,e){let t;try{t=await m(n)}catch(r){return i(e,400,{error:"Bad JSON: "+r.message})}const o=E[t.agent];if(!o)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof o.engine.listModels!="function")return i(e,200,{models:[]});try{const r=await o.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(r)?r:[]})}catch(r){return i(e,502,{error:r?.message||String(r)})}}async function jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(t.command||"").trim();if(!o)return i(e,400,{error:"No command"});let r=null;try{r=pe(o)}catch{r=null}return i(e,200,{ok:!!r,via:r?r.kind:null})}async function Fo(n,e,t){let o;try{o=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(o?.agent||"");if(!be.includes(r))return i(e,404,{error:`${r||"that agent"} keeps no sessions Chap can read (it can: ${be.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await wn(r,{limit:o.limit})});if(t==="/agent-sessions/read"){const a=await yn(r,String(o.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=Se({id:o.thread?.id??o.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const s=await bn(r,String(o.id||""),a.id);return s?i(e,200,{session:s}):i(e,404,{error:`no ${r} session ${String(o.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=Se({id:o.thread?.id??o.thread});return a?i(e,200,await Sn(r,a.id,Array.isArray(o.messages)?o.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const q=Ge(async(n,e)=>{if(Kn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const o=oo(n,t.pathname);if(o)return i(e,403,{error:o});try{if(n.method==="GET"&&t.pathname==="/health")return so(e,{fresh:t.searchParams.get("fresh")==="1"});const r=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"";if(n.method==="GET"&&t.pathname==="/skills")return co(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-context"){const s=await m(n).catch(()=>({})),c=s?.options&&typeof s.options=="object"?s.options:{},d={...c.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof c.permissionMode=="string"?{permissionMode:c.permissionMode}:{},...typeof c.workingDir=="string"&&c.workingDir?{workingDir:c.workingDir}:{},...typeof c.model=="string"&&c.model?{model:c.model}:{}};return i(e,200,await kn({agent:typeof s?.agent=="string"?s.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return lo(e,r,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return go(e,r,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return yo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return bo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return wo(e,decodeURIComponent(t.pathname.slice(12)),r,a);if(n.method==="POST"&&t.pathname==="/skills")return po(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?n.method==="DELETE"?mo(e,decodeURIComponent(s)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):fo(n,e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const s=t.pathname.slice(8),c=s.indexOf("/file/");return c===-1?uo(e,decodeURIComponent(s),r,a):ho(e,decodeURIComponent(s.slice(0,c)),decodeURIComponent(s.slice(c+6)),r,a)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return xo(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Eo(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return Ie(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return Ie(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const s=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(Zt.map(c=>[c,s?on(c)||pe(c)?.kind||null:qt(c)])),...s?{home:O.homedir(),path:process.env.PATH,installDirs:en(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Fo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return To(n,e);if(n.method==="POST"&&t.pathname==="/pair")return Qn(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return Vn(e);if(n.method==="POST"&&t.pathname==="/whoami")return Zn(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return vo(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ao(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return Co(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return Ne(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const s=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return Ne(n,e,s);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ie(s),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return ve(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return ve(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Po(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Uo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let s=null;try{s=await m(n)}catch{s=null}const c=_t(s||{});return e.writeHead(c?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return $o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Io(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Go(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Lo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Wo(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return jo(n,e);if(n.method==="POST"&&t.pathname==="/update")return ko(e);i(e,404,{error:"Not found"})}catch(r){i(e,500,{error:r?.message||String(r)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Jo(n){let e="";const t=[];let o=!1,r=!1;const a=()=>{r&&!o&&!t.length&&process.exit(0)},s=async()=>{if(!o){for(o=!0;t.length;){const c=t.shift();let d;try{d=JSON.parse(c)}catch{continue}try{const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:c});if(d.id==null)continue;const p=(await l.text()).trim();p&&process.stdout.write(p+`
|
|
13
|
-
`)}catch(
|
|
14
|
-
`)}}
|
|
15
|
-
`))>=0;){const
|
|
12
|
+
`)}async function L(n,e,t,r){try{const o=t(await m(n)),a=Z(n,o.agent,o.options||{});if(a.error)throw new P(a.error,403,"permission");return o.options=a.options,o}catch(o){return i(e,o?.status||400,r(o?.message?.startsWith("Unexpected")?new P(`Bad JSON: ${o.message}`):o)),null}}async function $o(n,e){const t=await L(n,e,Un,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Hn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Nn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Ro(n,e){const t=await L(n,e,Ln,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Mn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=Dn(t.requestedModel,o=>$(e,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){$(e,S(o))}$(e,"[DONE]"),e.end()}async function Io(n,e){const t=await L(n,e,Wn,S);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,Bn(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,S(o))}G(e);const r=jn(t.requestedModel,o=>U(e,o.type,o));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){const a={type:"error",sequence_number:0,...S(o)};U(e,"error",a)}e.end()}async function No(n,e){const t=await L(n,e,Gn,V);if(!t)return;if(!t.stream)try{const o=await A(t,()=>{},e);return i(e,200,_n(t.requestedModel,o))}catch(o){return e.writableEnded?void 0:i(e,o?.status||500,V(o))}G(e);const r=In(t.requestedModel,(o,a)=>U(e,o,a));try{await A(t,o=>r.delta(o),e),r.done()}catch(o){U(e,"error",V(o))}e.end()}async function Do(n,e){let t={};try{t=await m(n)||{}}catch{}const r=String(t.id||"").trim(),o=r?yn(r,"stopped"):!1;return o&&u("info",`cancel: ${r} stopped by client`),i(e,200,{ok:!0,cancelled:o})}async function _e(n,e,t){let r;try{r=await m(n)}catch{return i(e,200,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Parse error"}})}const o=t?le(t):Rt(),a=s=>{o&&e.setHeader("Mcp-Session-Id",o.id),i(e,200,{jsonrpc:"2.0",id:r.id??null,result:s})},c=(s,d)=>i(e,200,{jsonrpc:"2.0",id:r.id??null,error:{code:s,message:d}});if(r.id==null)return e.writeHead(202),e.end();if(r.method==="initialize")return a({protocolVersion:r.params?.protocolVersion||"2025-06-18",capabilities:{tools:{listChanged:!1}},serverInfo:{name:"chatpanel-browser",version:y}});const l=Ct();if(r.method==="tools/list"){const s=o?o.specs.map(d=>({name:d.name,description:d.description,inputSchema:d.parameters||{type:"object",properties:{}}})):[];return a({tools:[...l,...s]})}if(r.method==="tools/call"){const s=await Pt(r.params?.name,r.params?.arguments||{});if(s)return a(s);if(!o)return c(-32001,"That tool needs an active ChatPanel chat with “Act on page” on. ChatPanel's own tools (chatpanel_*) work without one.");try{return a(await It(o,r.params?.name,r.params?.arguments||{}))}catch(d){return a({content:[{type:"text",text:`error: ${d?.message||d}`}],isError:!0})}}return c(-32601,`Method not found: ${r.method}`)}async function _o(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=t.server||{},o=t.message;if(!r.command&&!r.from||!o)return i(e,400,{error:"need server.command (or server.from) and message"});try{let a;if(r.from){if(a=await ie(r),a.builtin&&o.method==="tools/call"){const l=await at(a.builtin,o);if(l)return i(e,200,{jsonrpc:"2.0",id:o.id??null,result:{content:[{type:"text",text:`Refused: ${l}`}],isError:!0}})}}else a={key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};let c=await fn(a,o);return a.builtin&&o.method==="tools/list"&&(c=it(a.builtin,c)),o.id==null?(e.writeHead(202),e.end()):i(e,200,c)}catch(a){return i(e,200,{jsonrpc:"2.0",id:o.id??null,error:{code:-32e3,message:String(a?.message||a)}})}}async function Ho(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t.server||{};if(!r.command&&!r.from)return i(e,400,{error:"need server.command (OAuth for a remote server is the client's own — see events/mcp-oauth.js)"});try{const o=r.from?await ie(r):{key:r.id,command:r.command,args:r.args,env:r.env,cwd:r.cwd,sandbox:r.sandbox};return i(e,200,t.status?wn(o):await gn(o))}catch(o){return i(e,200,{state:"failed",error:String(o?.message||o)})}}async function Mo(n,e){let t;try{t=await m(n)}catch(p){return i(e,400,{error:"Bad JSON: "+p.message})}const{url:r,headers:o,message:a}=t||{};if(!r||!a)return i(e,400,{error:"need url and message"});let c;try{c=ye(r)}catch(p){return i(e,400,{error:String(p?.message||p)})}const l={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};if(o&&typeof o=="object")for(const[p,w]of Object.entries(o)){const f=p.toLowerCase();(["authorization","mcp-session-id","mcp-protocol-version","x-api-key"].includes(f)||f.startsWith("x-"))&&(l[p]=String(w))}const s=new AbortController,d=setTimeout(()=>s.abort(),3e4);try{const p=await fetch(c.href,{method:"POST",headers:l,body:JSON.stringify(a),redirect:"follow",signal:s.signal});try{p.url&&ye(p.url)}catch(f){return i(e,400,{error:String(f?.message||f)})}const w=await p.text().catch(()=>"");return i(e,200,{status:p.status,sessionId:p.headers.get("Mcp-Session-Id")||null,contentType:p.headers.get("Content-Type")||"",authenticate:p.headers.get("WWW-Authenticate")||"",body:w})}catch(p){const w=p?.name==="AbortError"?"timed out":String(p?.message||p);return i(e,502,{error:`couldn't reach MCP server ${c.host}: ${w}`})}finally{clearTimeout(d)}}const He=256*1024,Bo=5,Go=8e3;async function Uo(n){let e=be(n);const t=new AbortController,r=setTimeout(()=>t.abort(),Go);try{for(let o=0;o<=Bo;o++){const a=await fetch(e.href,{method:"GET",redirect:"manual",signal:t.signal,headers:{Accept:"text/html,application/xhtml+xml","Accept-Language":"en","User-Agent":`chatpanel-bridge/${y} (+link-title)`}});if(a.status>=300&&a.status<400&&a.headers.get("location")){if(e=be(new URL(a.headers.get("location"),e).href),a.body)try{await a.body.cancel()}catch{}continue}if(!a.ok){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}const c=a.headers.get("content-type")||"";if(!/text\/html|application\/xhtml/i.test(c)){if(a.body)try{await a.body.cancel()}catch{}return{title:null}}return{title:jo(await Lo(a)),url:e.href}}throw new Error("too many redirects")}finally{clearTimeout(r)}}async function Lo(n){if(!n.body?.getReader)return(await n.text().catch(()=>"")).slice(0,He);const e=n.body.getReader(),t=new TextDecoder("utf-8",{fatal:!1});let r="",o=0;try{for(;;){const{done:a,value:c}=await e.read();if(a||(o+=c.byteLength,r+=t.decode(c,{stream:!0}),/<\/title\s*>/i.test(r)||o>=He))break}}finally{try{await e.cancel()}catch{}}return r}function Wo(n){return String(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&(?:apos|#0*39|#x0*27);/gi,"'").replace(/ /g," ").replace(/&#(\d+);/g,(e,t)=>{try{return String.fromCodePoint(+t)}catch{return""}}).replace(/&#x([0-9a-f]+);/gi,(e,t)=>{try{return String.fromCodePoint(parseInt(t,16))}catch{return""}})}function jo(n){const e=/<title[^>]*>([\s\S]*?)<\/title\s*>/i.exec(n);return e?Wo(e[1]).replace(/\s+/g," ").trim().slice(0,200):""}async function Fo(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=t&&t.url;if(!r||typeof r!="string")return i(e,400,{error:"need url"});try{const o=await Uo(r);return i(e,200,{title:o.title||null,url:o.url||r})}catch(o){const a=o?.name==="AbortError"?"timed out":String(o?.message||o);return i(e,400,{error:`couldn't fetch title: ${a}`})}}async function Jo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=le(t.session);if(!r)return i(e,404,{error:"no such session"});const o=r.pending.get(t.id);return o?(r.pending.delete(t.id),o.resolve(t.result),i(e,200,{ok:!0})):i(e,404,{error:"no such pending call"})}async function Xo(n,e){let t;try{t=await m(n)}catch(s){return i(e,400,{error:"Bad JSON: "+s.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});const o=String(t.prompt||"").slice(0,6e3);if(!o)return i(e,400,{error:"Empty prompt"});const a=t.model||"",c=Z(n,t.agent,{model:a});if(c.error)return i(e,403,{error:c.error});const l=String(t.system||"").slice(0,2e3)||"You autocomplete an unfinished message the user is typing. Output ONLY the few words that come next. Do not answer it. No quotes, no repetition.";try{let s="";return typeof r.engine.complete=="function"?s=await r.engine.complete({prompt:o,system:l,model:a}):await r.engine.chat({messages:[{role:"user",content:o}],system:l,options:c.options},d=>{d.type==="delta"?s+=d.text||"":d.type==="done"&&d.text&&(s+=d.text)}),i(e,200,{text:(s||"").trim()})}catch(s){return i(e,502,{error:s?.message||String(s)})}}async function Ko(n,e){let t;try{t=await m(n)}catch(o){return i(e,400,{error:"Bad JSON: "+o.message})}const r=x[t.agent];if(!r)return i(e,404,{error:`Unknown agent "${t.agent}"`});if(typeof r.engine.listModels!="function")return i(e,200,{models:[]});try{const o=await r.engine.listModels(t.options||{});return i(e,200,{models:Array.isArray(o)?o:[]})}catch(o){return i(e,502,{error:o?.message||String(o)})}}async function zo(n,e){let t;try{t=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const r=String(t.command||"").trim();if(!r)return i(e,400,{error:"No command"});let o=null;try{o=me(r)}catch{o=null}return i(e,200,{ok:!!o,via:o?o.kind:null})}async function Yo(n,e,t){let r;try{r=await m(n)}catch(a){return i(e,400,{error:"Bad JSON: "+a.message})}const o=String(r?.agent||"");if(!ke.includes(o))return i(e,404,{error:`${o||"that agent"} keeps no sessions Chap can read (it can: ${ke.join(", ")})`});try{if(t==="/agent-sessions")return i(e,200,{sessions:await Tn(o,{limit:r.limit})});if(t==="/agent-sessions/read"){const a=await vn(o,String(r.id||""));return a?i(e,200,{session:a}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/adopt"){const a=Te({id:r.thread?.id??r.thread});if(!a)return i(e,400,{error:"adopt needs the Chap conversation it becomes: { thread: { id } }"});const c=await xn(o,String(r.id||""),a.id);return c?i(e,200,{session:c}):i(e,404,{error:`no ${o} session ${String(r.id||"").slice(0,64)}`})}if(t==="/agent-sessions/catchup"){const a=Te({id:r.thread?.id??r.thread});return a?i(e,200,await En(o,a.id,Array.isArray(r.messages)?r.messages:[])):i(e,400,{error:"catchup needs the Chap conversation: { thread: { id } }"})}return i(e,404,{error:"Not found"})}catch(a){return i(e,a?.status||500,{error:a?.message||String(a)})}}const ee=Le(async(n,e)=>{if(Zn(n,e),n.method==="OPTIONS")return e.writeHead(204),e.end();let t;try{t=new URL(n.url,`http://${n.headers.host||"127.0.0.1"}`)}catch{return i(e,400,{error:"bad request"})}const r=co(n,t.pathname);if(r)return i(e,403,{error:r});try{if(n.method==="GET"&&t.pathname==="/health")return po(e,{fresh:t.searchParams.get("fresh")==="1"});const o=t.searchParams.getAll("dir"),a=t.searchParams.get("workdir")||"",c={agent:t.searchParams.get("agent")||"",source:t.searchParams.get("source")||""};if(n.method==="GET"&&t.pathname==="/skills")return fo(e,o,a,c);if(n.method==="POST"&&t.pathname==="/agent-context"){const l=await m(n).catch(()=>({})),s=l?.options&&typeof l.options=="object"?l.options:{},d={...s.useLocalConfig===!1?{useLocalConfig:!1}:{},...typeof s.permissionMode=="string"?{permissionMode:s.permissionMode}:{},...typeof s.workingDir=="string"&&s.workingDir?{workingDir:s.workingDir}:{},...typeof s.model=="string"&&s.model?{model:s.model}:{}};return i(e,200,await An({agent:typeof l?.agent=="string"?l.agent:"claude",options:d}))}if(n.method==="GET"&&t.pathname==="/skills-quarantined")return mo(e,o,a);if(n.method==="GET"&&t.pathname==="/agent-defs")return ko(e,o,a);if(n.method==="POST"&&t.pathname==="/agent-defs/export-plan")return vo(n,e);if(n.method==="POST"&&t.pathname==="/agent-defs/export")return xo(n,e);if(n.method==="GET"&&t.pathname.startsWith("/agent-defs/"))return To(e,decodeURIComponent(t.pathname.slice(12)),o,a);if(n.method==="POST"&&t.pathname==="/skills")return yo(n,e);if((n.method==="PUT"||n.method==="POST"||n.method==="DELETE")&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?n.method==="DELETE"?So(e,decodeURIComponent(l)):i(e,405,{ok:!1,error:"use POST /skills to save a skill"}):n.method==="DELETE"?i(e,405,{ok:!1,error:"deleting one file is not supported — save the skill"}):bo(n,e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)))}if(n.method==="GET"&&t.pathname.startsWith("/skills/")){const l=t.pathname.slice(8),s=l.indexOf("/file/");return s===-1?go(e,decodeURIComponent(l),o,a,c):wo(e,decodeURIComponent(l.slice(0,s)),decodeURIComponent(l.slice(s+6)),o,a,c)}if(t.pathname==="/connections"||t.pathname.startsWith("/connections/"))return Co(n,e,t.pathname);if(t.pathname==="/worktrees"||t.pathname.startsWith("/worktrees/"))return Po(n,e,t.pathname);if(n.method==="GET"&&t.pathname==="/v1/models")return De(e);if(n.method==="GET"&&t.pathname.startsWith("/v1/models/"))return De(e,decodeURIComponent(t.pathname.slice(11)));if(n.method==="GET"&&t.pathname==="/debug"){const l=/^(1|true|yes|on)$/i.test(process.env.CHATPANEL_BRIDGE_DEBUG||"");return i(e,200,{version:y,agents:Object.fromEntries(on.map(s=>[s,l?ln(s)||me(s)?.kind||null:rn(s)])),...l?{home:O.homedir(),path:process.env.PATH,installDirs:an(O.homedir())}:{}})}if(n.method==="POST"&&t.pathname.startsWith("/agent-sessions"))return Yo(n,e,t.pathname);if(n.method==="POST"&&t.pathname==="/chat")return Oo(n,e);if(n.method==="POST"&&t.pathname==="/pair")return no(n,e);if(n.method==="POST"&&t.pathname==="/pair/code")return to(e);if(n.method==="POST"&&t.pathname==="/whoami")return oo(n,e);if(n.method==="POST"&&t.pathname==="/v1/chat/completions")return $o(n,e);if(n.method==="POST"&&t.pathname==="/v1/completions")return Ro(n,e);if(n.method==="POST"&&t.pathname==="/v1/responses")return Io(n,e);if(n.method==="POST"&&t.pathname==="/v1/messages")return No(n,e);if(t.pathname==="/mcp"){if(n.method==="POST")return _e(n,e,null);if(n.method==="GET")return e.writeHead(405),e.end()}if(t.pathname.startsWith("/mcp/")){const l=decodeURIComponent(t.pathname.slice(5));if(n.method==="POST")return _e(n,e,l);if(n.method==="GET")return e.writeHead(405),e.end();if(n.method==="DELETE")return ce(l),e.writeHead(204),e.end()}if(n.method==="GET"&&t.pathname==="/channels")return Oe(n,e,"status");if(n.method==="POST"&&t.pathname.startsWith("/channels/"))return Oe(n,e,t.pathname.slice(10));if(n.method==="POST"&&t.pathname==="/cancel")return Do(n,e);if(n.method==="POST"&&t.pathname==="/tool-result")return Jo(n,e);if(n.method==="POST"&&t.pathname==="/sandbox/refused"){let l=null;try{l=await m(n)}catch{l=null}const s=Ut(l||{});return e.writeHead(s?204:403),e.end()}if(n.method==="POST"&&t.pathname==="/mcp-local")return _o(n,e);if(n.method==="POST"&&t.pathname==="/mcp-local/signin")return Ho(n,e);if(n.method==="POST"&&t.pathname==="/mcp-remote")return Mo(n,e);if(n.method==="POST"&&t.pathname==="/fetch-title")return Fo(n,e);if(n.method==="POST"&&t.pathname==="/complete")return Xo(n,e);if(n.method==="POST"&&t.pathname==="/list-models")return Ko(n,e);if(n.method==="POST"&&t.pathname==="/agent-check")return zo(n,e);if(n.method==="POST"&&t.pathname==="/update")return Ao(e);i(e,404,{error:"Not found"})}catch(o){i(e,500,{error:o?.message||String(o)})}});function u(n,e){(n==="error"?console.error:console.log)(`[chatpanel-bridge] ${e}`)}function Vo(n){let e="";const t=[];let r=!1,o=!1;const a=()=>{o&&!r&&!t.length&&process.exit(0)},c=async()=>{if(!r){for(r=!0;t.length;){const l=t.shift();let s;try{s=JSON.parse(l)}catch{continue}try{const d=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:l});if(s.id==null)continue;const p=(await d.text()).trim();p&&process.stdout.write(p+`
|
|
13
|
+
`)}catch(d){s.id!=null&&process.stdout.write(JSON.stringify({jsonrpc:"2.0",id:s.id,error:{code:-32e3,message:String(d?.message||d)}})+`
|
|
14
|
+
`)}}r=!1,a()}};process.stdin.setEncoding("utf8"),process.stdin.on("data",l=>{e+=l;let s;for(;(s=e.indexOf(`
|
|
15
|
+
`))>=0;){const d=e.slice(0,s).trim();e=e.slice(s+1),d&&t.push(d)}c()}),process.stdin.on("end",()=>{o=!0,a()}),process.stdin.resume()}function Qo(){sn(),cn(),eo();let n=!1;ee.on("error",e=>{if(e&&e.code==="EADDRINUSE"){fetch(`http://127.0.0.1:${k}/health`,{signal:AbortSignal.timeout(1500)}).then(t=>t.ok?t.json():null).catch(()=>null).then(t=>{const r=!!(t?.version&&Array.isArray(t.agents)),o=On({name:"bridge",self:y,holder:r?{ours:r,version:t.version}:null,managedBy:Cn(process.env),port:k});if(o.action==="standby"||n&&!t){if(!n)for(const a of o.lines)u("info",a);n=!0,setTimeout(()=>ee.listen(k,v),Pn);return}if(r)for(const a of o.lines)u("error",a);else u("error",`Port ${k} is already in use — another app (or a second bridge) has it.`),u("error","Fix: free the port, or run with CHATPANEL_BRIDGE_PORT=<port> and set the same Bridge URL in the extension's settings.");process.exit(1)});return}u("error",`bridge server error: ${e?.message||e}`),process.exit(1)});for(const e of["SIGINT","SIGTERM"])process.on(e,()=>{const t=bn("shutdown");t&&u("info",`shutdown: stopped ${t} running agent${t===1?"":"s"}`);const r=Sn("shutdown");r&&u("info",`shutdown: closed ${r} warm agent process${r===1?"":"es"}`),z().close(),setTimeout(()=>process.exit(0),t||r?300:0).unref?.(),!t&&!r&&process.exit(0)});ee.listen(k,v,async()=>{n&&u("info","standby: the other bridge is gone — this copy has the port now"),n=!1,u("info",`listening on http://${v}:${k}`),Re.warm(),Q.has(v)||u("error",`⚠ SECURITY: bound to NON-LOOPBACK host ${v}. The anti-rebinding Host check is OFF, so any device that reaches this port (and any web page via a spoofed Host header) can drive local agents — gated only by the bridge token. Only do this on a trusted, firewalled network; prefer 127.0.0.1.`);for(const[,{engine:e,label:t,hidden:r}]of Object.entries(x)){if(r)continue;const o=await e.available().catch(()=>({ok:!1}));u("info",` ${o.ok?"✓":"✕"} ${t}${o.ok?"":" — "+(o.reason||"unavailable")}`)}u("info","Open the ChatPanel side panel; installed agents (Claude Code, Codex, Antigravity) appear automatically."),Ae().then(e=>e.startIfConfigured()).then(e=>{e?.skipped||(e?.ok?u("info","channels: telegram connected — polling for messages"):u("error",`channels: telegram not started — ${e?.error||"unknown error"}`))}).catch(e=>u("error",`channels: ${e?.message||e}`))})}function Zo(){console.log(`ChatPanel Bridge v${y}
|
|
16
16
|
|
|
17
17
|
Usage:
|
|
18
|
-
chatpanel-bridge start the bridge (foreground) on ${
|
|
18
|
+
chatpanel-bridge start the bridge (foreground) on ${v}:${k}
|
|
19
19
|
chatpanel-bridge --install run automatically at login, in the background
|
|
20
20
|
chatpanel-bridge --uninstall remove the login auto-start
|
|
21
21
|
chatpanel-bridge --status show whether auto-start is set up
|
|
@@ -24,4 +24,4 @@ Usage:
|
|
|
24
24
|
chatpanel-bridge pair print a one-time code that pairs a client (Firefox, a dev build)
|
|
25
25
|
chatpanel-bridge sandbox status of the process sandbox; \`sandbox install\` is Windows' one-time account setup
|
|
26
26
|
|
|
27
|
-
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function
|
|
27
|
+
Env: CHATPANEL_BRIDGE_HOST, CHATPANEL_BRIDGE_PORT, CHATPANEL_SANDBOX (open|allowlist|off), CHATPANEL_SANDBOX_WINDOWS=1`)}function qo(){const n=process.argv,e=(...t)=>t.some(r=>n.includes(r));if(e("--help","-h"))return Zo(),!0;if(e("--version","-v"))return console.log(y),!0;if(e("pair","--pair"))return(async()=>{let t="";try{t=ae(D,"utf8").trim()}catch{}const r=`http://${v}:${k}`;try{if(!t)throw new Error(`no token at ${D} — is the bridge running?`);const o=await fetch(`${r}/pair/code`,{method:"POST",headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(2500)}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error(a.error||`HTTP ${o.status}`);console.log(`Pairing code: ${Yn(a.code)} (one use, expires in 5 minutes)`),console.log('Enter it in ChatPanel → Settings → Coding Agents → "Pairing code".')}catch(o){u("error",`could not get a pairing code from the bridge at ${r}: ${o?.message||o}`),process.exitCode=1}})(),!0;if(n.includes("sandbox"))return Mt(n.slice(n.indexOf("sandbox")+1)).then(t=>{process.exitCode=t}),!0;if(e("--install")){try{ct(),u("info","Installed. The bridge now starts automatically at login and is running in the background.")}catch(t){u("error","Install failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--uninstall")){try{lt(),u("info","Removed the login auto-start.")}catch(t){u("error","Uninstall failed: "+(t?.message||t)),process.exitCode=1}return!0}if(e("--status")){let t=!1;try{t=dt()}catch(r){u("error",String(r?.message||r))}return u("info",`auto-start: ${t?"installed":"not installed"}`),!0}return!1}const Me=process.argv.indexOf("--mcp-stdio"),Be=process.argv.indexOf("--sandbox-host");if(Be>=0){const{runSandboxHost:n}=await import("./sandbox-host.js");await n(process.argv[Be+1],{compiled:hn()})}else if(Me>=0){const n=process.argv[Me+1];n||(console.error("--mcp-stdio requires a URL"),process.exit(1)),Vo(n)}else process.argv.includes("--update")?(async()=>{try{const n=await ge(y);u("info",`Updated v${n.from} → v${n.to}. Restarting the background service…`),se()}catch(n){u("error","Update failed: "+(n?.message||n)),process.exitCode=1}})():qo()||Qo();
|
package/src/skills.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFile as
|
|
1
|
+
import{readFile as _,readdir as q,stat as A,realpath as C}from"node:fs/promises";import{createHash as N}from"node:crypto";import x from"node:os";import{delimiter as O,isAbsolute as j,join as d,resolve as S,sep as G}from"node:path";import{isSafeSkillPath as R,SKILL_FILE_KINDS as P}from"./events/skill-manifest.js";import{skillFromPackage as X}from"./events/skill-package.js";import{parseFrontmatter as F}from"./events/frontmatter.js";import{scanSkill as B,admits as W}from"./events/skill-scan.js";const U=512*1024,J=4*1024*1024,K=500,Q=3,V=new Set([".git",".svn",".hg",".cache",".DS_Store","node_modules"]),M=Object.freeze([{source:"local",label:"ChatPanel",segments:[".chatpanel","skills"],writable:!0},{source:"agents-dir",label:"Shared (~/.agents)",segments:[".agents","skills"]},{source:"claude",label:"Claude Code",segments:[".claude","skills"]},{source:"codex",label:"Codex",segments:[".codex","skills"]},{source:"copilot",label:"GitHub Copilot",segments:[".copilot","skills"],projectSegments:[".github","skills"]},{source:"gemini",label:"Antigravity / Gemini",segments:[".gemini","skills"]},{source:"opencode",label:"OpenCode",segments:[".config","opencode","skills"],alsoHome:[[".opencode","skills"]],projectSegments:[".opencode","skills"]},{source:"kiro",label:"Kiro",segments:[".kiro","skills"]},{source:"pi",label:"Pi",segments:[".pi","skills"]},{source:"hermes",label:"Hermes",segments:[".hermes","skills"]}]);function z(t){return(Array.isArray(t)?t:[]).map(e=>String(e||"").trim()).filter(Boolean).filter(e=>j(e)).slice(0,16)}function D(t){const e=String(t||"").trim();if(!e||!j(e))return[];const n=S(e);return M.map(r=>({dir:d(n,...r.projectSegments||r.segments),source:r.source,label:r.label,writable:!1,project:n}))}function E(t=process.env,e=x.homedir(),n=[],r=""){const i=String(t.CHATPANEL_SKILL_DIRS||"").split(/\r?\n/).flatMap(o=>o.split(O)).map(o=>o.trim()).filter(Boolean),s=[...new Set([...i,...z(n)])];return[...D(r),...M.flatMap(o=>[o.segments,...o.alsoHome||[]].map(l=>({dir:d(e,...l),source:o.source,label:o.label,writable:!!o.writable}))),...s.map(o=>({dir:S(o),source:"external",label:"Custom folder",writable:!1}))]}const fe=/^[a-z0-9][a-z0-9_-]*$/,Y=X;function Z(t,e=process.platform){const n=t?.platforms;if(!Array.isArray(n)||!n.length)return!0;const r=e==="darwin"?"macos":e==="win32"?"windows":"linux";return n.includes(r)}async function H(t){try{return await q(t,{withFileTypes:!0})}catch{return[]}}async function ee(t){const e=[];for(const n of P)for(const r of await H(d(t,n))){if(!r.isFile())continue;const i=`${n}/${r.name}`;if(R(i)&&e.push(i),e.length>=200)return e}return e}async function te(t,e,n){let r;try{const c=await A(d(t,"SKILL.md"));if(!c.isFile()||c.size>U)return null;r=await _(d(t,"SKILL.md"),"utf8")}catch{return null}const{meta:i,body:s}=F(r),o=`sha256-${N("sha256").update(r).digest("hex").slice(0,32)}`,l=e.split("/").pop(),p=await ee(t),a=Y({meta:i,body:s,dirName:l,relPath:e,source:n,files:p,hash:o}),m=B({name:a.name,prompt:a.prompt,files:p||[]});return a.origin={...a.origin,scanned:{verdict:m.verdict,scanner:m.scanner,findings:m.findings.length}},{skill:a,dir:t,scan:m}}async function ne({roots:t,extraDirs:e=[],workdir:n="",platform:r=process.platform}={}){t=t||E(process.env,x.homedir(),e,n);const i=new Map,s=new Map,o=[],l=[];for(const{dir:p,source:a,project:m}of t){const c=async(b,y,L)=>{if(!(i.size>=K||L>Q))for(const f of await H(b)){if(i.size>=K)return;if(!f.isDirectory()||V.has(f.name))continue;const k=y?`${y}/${f.name}`:f.name,v=d(b,f.name),u=f.name.startsWith(".")?null:await te(v,k,a).catch(h=>(o.push({path:k,reason:String(h?.message||h)}),null));if(u){if(!W(u.scan?.verdict))l.push({id:u.skill.id,path:k,verdict:u.scan.verdict,findings:u.scan.findings});else if(Z(u.skill,r)){m&&(u.skill.origin={...u.skill.origin,project:m});const h={...u,root:p,source:a},w=s.get(u.skill.id)||[];w.some(I=>I.source===a&&I.root===p)||w.push(h),s.set(u.skill.id,w),i.has(u.skill.id)||i.set(u.skill.id,h)}}else await c(v,k,L+1)}};await c(p,"",1)}return{index:i,copies:s,problems:o,quarantined:l}}const T=Object.freeze({claude:"claude",codex:"codex",opencode:"opencode",copilot:"copilot",antigravity:"gemini",gemini:"gemini",kiro:"kiro",pi:"pi",hermes:"hermes"});function de(t,{agent:e="",source:n=""}={}){const r=T[String(e||"").toLowerCase()]||"",i=T[String(n||"").toLowerCase()]||String(n||"").toLowerCase(),s=new Map;for(const[o,l]of t.index){const p=t.copies?.get(o)||[l],a=i&&p.find(c=>c.source===i)||r&&p.find(c=>c.source===r)||l,m=[...new Set(p.filter(c=>c!==a).map(c=>c.source))];s.set(o,m.length?{...a,skill:{...a.skill,alsoIn:m}}:a)}return s}function ge(t){return[...t.values()].map(({skill:e})=>{const{prompt:n,...r}=e;return{...r,promptChars:(n||"").length}})}function he(t,e){const n=t.get(String(e||""));return n?n.skill:null}async function ke(t,e,n){const r=t.get(String(e||""));if(!r)return{error:"unknown skill"};if(!R(n))return{error:"unsafe path"};if(String(n).split("/")[0]==="scripts")return{error:"scripts are not readable as text"};const i=S(r.dir,n);let s;try{s=await C(i)}catch{return{error:"not found"}}const o=await C(r.dir).catch(()=>r.dir);if(s!==o&&!s.startsWith(o+G))return{error:"outside package"};const l=await A(s).catch(()=>null);return l?.isFile()?l.size>J?{error:"file too large"}:{path:n,text:await _(s,"utf8")}:{error:"not found"}}const re=5e3;let g=null;async function $({force:t=!1,now:e=Date.now,extraDirs:n=[],workdir:r=""}={}){const i=e(),o=[D(r)[0]?.project||"",...z(n).map(p=>S(p)).sort()].join("|");if(!t&&g&&g.key===o&&i-g.at<re)return g.value;const l=await ne({extraDirs:n,workdir:r});return g={at:i,key:o,value:l},l}function Se(){g=null}async function we(t=[]){const{index:e,problems:n,quarantined:r}=await $({extraDirs:t}),i=new Set([...e.values()].map(s=>s.root));return{count:e.size,roots:E(process.env,x.homedir(),t).filter(s=>i.has(s.dir)).map(s=>s.dir),sources:[...new Set([...e.values()].map(s=>s.source))].sort(),...n.length?{problems:n.length}:{},...r?.length?{quarantined:r.length}:{}}}async function xe(t=[],e=""){const{quarantined:n}=await $({extraDirs:t,workdir:e});return n||[]}export{M as AGENT_SKILL_DIRS,T as AGENT_SKILL_SOURCE,Se as clearSkillCache,ge as listRecords,F as parseFrontmatter,Z as platformOk,de as preferredIndex,D as projectSkillRoots,xe as quarantinedSkills,ke as readPackageFile,he as readRecord,ne as scanSkills,$ as skillIndex,Y as skillRecord,E as skillRoots,we as skillsHealth};
|
package/src/warm-pool.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as k,userTextMatches as D,idsSeen as z,idsExtension as g}from"./events/agent-thread.js";const w=1024**3,x=B(),F=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(x>=16*w?10*6e4:5*6e4),U=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(x*.2),3*w),N=400*1024**2;function G(u,l,a=N){const c=Math.floor(l/a),d=u>=48*w?4:u>=24*w?3:u>=12*w?2:1;return Math.max(1,Math.min(c,d))}const P=Number(process.env.CHATPANEL_WARM_MAX)||G(x,U),C=new Set;function W(u,l){if(u.answers!==l.answers||u.users.length!==l.users.length)return!1;const a=u.users.length;for(let c=0;c<a-1;c++)if(u.users[c]!==l.users[c])return!1;return a===0||D(u.users[a-1],l.users[a-1])}const H=2*6e4;function Y({max:u=P,idleMs:l=F,budgetBytes:a=U,group:c=C,now:d=Date.now,measure:I=
|
|
1
|
+
import{treeRssBytes as L,totalMemoryBytes as B}from"./proc.js";import{historyShape as k,userTextMatches as D,idsSeen as z,idsExtension as g}from"./events/agent-thread.js";const w=1024**3,x=B(),F=Number(process.env.CHATPANEL_WARM_IDLE_MS)||(x>=16*w?10*6e4:5*6e4),U=Number(process.env.CHATPANEL_WARM_BUDGET_MB)*1024**2||Math.min(Math.floor(x*.2),3*w),N=400*1024**2;function G(u,l,a=N){const c=Math.floor(l/a),d=u>=48*w?4:u>=24*w?3:u>=12*w?2:1;return Math.max(1,Math.min(c,d))}const P=Number(process.env.CHATPANEL_WARM_MAX)||G(x,U),C=new Set;function W(u,l){if(u.answers!==l.answers||u.users.length!==l.users.length)return!1;const a=u.users.length;for(let c=0;c<a-1;c++)if(u.users[c]!==l.users[c])return!1;return a===0||D(u.users[a-1],l.users[a-1])}const H=2*6e4;function Y({max:u=P,idleMs:l=F,budgetBytes:a=U,group:c=C,now:d=Date.now,measure:I=i=>L(i?.pid),log:m=()=>{}}={}){const i=new Set;let b=null;const $=()=>{let e=0;for(const s of c)e+=s.bytes;return e};let M=0;const h=e=>`${Math.round(e/1024**2)} MB`,v=new Set;function T(e){for(const s of[...v])s.key===e&&(v.delete(s),s.resolve())}function p(e,s="dropped"){if(i.has(e)){i.delete(e),e.alive=!1;try{e.session?.close?.(s)}catch{}m(`warm ${e.label}: ${s} (${i.size} live)`),!i.size&&b&&(clearInterval(b),b=null),e.worker&&T(e.key)}}const _=e=>Number(e.session?.expiresAt)>0&&d()>=e.session.expiresAt-H;function S(){const e=d();for(const s of[...i])!s.busy&&e-s.lastUsed>l&&p(s,"idle")}function R(){b||!Number.isFinite(l)||l<=0||(b=setInterval(S,Math.min(l,6e4)),b.unref?.())}const A={get size(){return i.size},get bytes(){let e=0;for(const s of i)e+=s.bytes||0;return e},peek({key:e,messages:s}){const n=k(s);for(const r of i)if(!r.busy&&r.alive&&!r.worker&&r.key===e&&!_(r)&&W(r.shape,n))return!0;return!1},acquire({key:e,messages:s,thread:n=null}){const r=k(s);for(const t of i){if(t.busy||!t.alive||t.worker||t.key!==e)continue;if(_(t)){p(t,"its sign-in is about to expire");continue}const o=n?.id&&t.thread===n.id&&t.seenIds?g(s,n,t.seenIds):null;if(!o&&!W(t.shape,r)){m(`warm ${t.label}: shape differs (have ${t.shape.users.length}u/${t.shape.answers}a, asked ${r.users.length}u/${r.answers}a)`);continue}return t.busy=!0,t.lastUsed=d(),t.unseen=o&&o.tail.length>1?o.tail:null,m(`warm ${t.label}: reused${o?` by id (${o.tail.length} unseen)`:""}`),t}return null},reserve({key:e,label:s=e,evict:n=!0}){const r=()=>{let f=null;for(const E of i)!E.busy&&(!f||E.lastUsed<f.lastUsed)&&(f=E);return f};if(i.size>=u){const f=n?r():null;if(!f)return null;p(f,"evicted")}const t=M||N;for(;$()+t>a;){const f=n?r():null;if(!f)return m(`warm ${s}: not kept — ${h($())} warm + ~${h(t)} would pass the ${h(a)} budget`),null;p(f,`evicted for memory (${h($())} warm)`)}const o={key:e,label:s,session:null,shape:{users:[],answers:0},busy:!0,alive:!0,lastUsed:d(),bytes:t};return i.add(o),m(`warm ${s}: starting (${i.size} live, ~${h($())} of ${h(a)})`),R(),o},holds(e,s){return e.shape=k(s),e},attach(e,s){return e.session=s,s.onExit?.(()=>{e.alive&&p(e,"process exited")}),e},release(e,{user:s,answered:n,messages:r=null,thread:t=null}){if(e.alive){if(typeof s=="string"){e.shape={users:[...e.shape.users,s.trim()],answers:e.shape.answers+(n?1:0)};const o=t?.id?z(r,t,{answered:n}):null;o&&(e.thread=t.id,e.seenIds=o)}e.unseen=null,e.busy=!1,e.lastUsed=d(),setImmediate(()=>{if(!e.alive)return;const o=I(e.session);o>0&&(e.bytes=o,M=o,m(`warm ${e.label}: ${h(o)} resident`))})}},acquireWorker({key:e,thread:s=null}){let n=null;for(const r of i){if(r.busy||!r.alive||!r.worker||r.key!==e)continue;if(_(r)){p(r,"its sign-in is about to expire");continue}const t=(s&&r.thread===s?-1e6:0)+(r.uses||0);(!n||t<n.rank)&&(n={e:r,rank:t})}return n?(n.e.busy=!0,n.e.lastUsed=d(),m(`warm ${n.e.label}: worker reused (${n.e.uses||0} turns so far)`),n.e):null},reserveWorker({key:e,label:s=e,cap:n=2}){let r=0;for(const o of i)o.worker&&o.key===e&&r++;if(r>=n)return null;const t=A.reserve({key:e,label:`${s} (worker)`,evict:!1});return t&&(t.worker=!0),t},workerFree(e,s){return new Promise(n=>{const r={key:e,resolve:()=>{clearTimeout(r.timer),n(!0)}};r.timer=setTimeout(()=>{v.delete(r),n(!1)},s),v.add(r)})},releaseWorker(e,{thread:s=null,maxUses:n=12}={}){if(e.alive){if(e.uses=(e.uses||0)+1,e.thread=s,e.busy=!1,e.lastUsed=d(),e.uses>=n){p(e,`worker retired after ${e.uses} turns`);return}setImmediate(()=>{if(!e.alive)return;const r=I(e.session);r>0&&(e.bytes=r,M=r,m(`warm ${e.label}: ${h(r)} resident`))}),T(e.key)}},drop:p,closeAll(e="shutdown"){for(const s of[...i])p(s,e)},keys(){return[...i].map(e=>e.key)},reap:S};return c.add(A),A}export{U as WARM_BUDGET_BYTES,Y as createWarmPool,k as historyShape,G as warmMaxFor};
|