@chatpanel/bridge 0.32.3 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/agent-context.js +1 -0
- package/src/agent-sessions.js +16 -0
- package/src/channels/adapters/telegram.js +3 -3
- package/src/cli-errors.js +6 -3
- package/src/engines/antigravity.js +4 -4
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +8 -8
- package/src/engines/codex-appserver.js +11 -11
- package/src/engines/codex.js +6 -6
- package/src/engines/custom.js +5 -5
- package/src/engines/prompt.js +8 -6
- package/src/events/agent-permission.js +2 -2
- package/src/events/agent-thread.js +5 -0
- package/src/events/compaction.js +11 -0
- package/src/events/context-breakdown.js +5 -0
- package/src/events/context-window.js +1 -0
- package/src/events/dialect-a2a.js +1 -1
- package/src/events/dialect-claude.js +1 -1
- package/src/events/harness-cards.js +1 -1
- package/src/events/mcp-signin.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/events/service-standby.js +1 -0
- package/src/health-snapshot.js +1 -0
- package/src/pii/pii-detect.js +2 -2
- package/src/sandbox-srt.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +10 -10
- package/src/service.js +10 -5
- package/src/threads.js +1 -0
- package/src/warm-pool.js +1 -1
package/src/engines/codex.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawn as
|
|
2
|
-
`))>=0;){const
|
|
1
|
+
import{spawn as R}from"node:child_process";import{killOnAbort as W,spawnGroupOpts as q}from"../proc.js";import{track as z,sandbox as G,noteSandbox as K,grantedWriteRoots as U}from"../sandbox.js";import{harnessDirArgs as Z,harnessSessionArgs as j}from"../events/harness-cards.js";import{threadTurn as Q}from"../threads.js";import{readFile as V,unlink as T,writeFile as Y}from"node:fs/promises";import{existsSync as P,mkdirSync as ee,symlinkSync as te,readFileSync as M}from"node:fs";import $ from"node:os";import g from"node:path";import{agentAvailable as re,selfMcpStdio as oe,resolveCommand as se}from"../env.js";import{relayTimeoutMax as ne}from"../relay-timeout.js";import{buildCliPrompt as ae}from"./prompt.js";import{pushExtraArgs as ce,FORBIDDEN as ie}from"./args.js";import{resolveWorkdir as B}from"../workdir.js";import{cliError as de}from"../cli-errors.js";import{signInStatus as le,signInMessage as pe}from"../sign-in.js";import{disabledMcpServers as ue,planMcpRetry as fe,quarantine as me}from"../mcp-quarantine.js";import{chatWarm as he}from"./codex-appserver.js";const F=Number(process.env.CHATPANEL_CODEX_TIMEOUT_MS)||18e4,H=process.env.CHATPANEL_CODEX_EFFORT??"low",ge=["gpt-5-codex","gpt-5","o3","o4-mini"];let O=!1;function We(){O=!1}async function qe(){const s=new Set;try{const o=process.env.CODEX_HOME||g.join($.homedir(),".codex"),t=M(g.join(o,"config.toml"),"utf8");for(const c of t.matchAll(/(?:^|\n)\s*model\s*=\s*["']([^"'\n]+)["']/g))s.add(c[1].trim())}catch{}for(const o of ge)s.add(o);return[...s]}const N=g.join($.homedir(),".chatpanel","codex-home");let L=!1;function ye(){if(!L)try{ee(N,{recursive:!0});const s=g.join($.homedir(),".codex","auth.json"),o=g.join(N,"auth.json");if(P(s)&&!P(o))try{te(s,o)}catch{}L=!0}catch{return null}return N}let E=!1,X=0;async function ze(){if(Date.now()-X>(E?3e4:4e3)){X=Date.now();try{E=re("codex")}catch{E=!1}}return E?await le("codex",se("codex")).catch(()=>null)===!1?{ok:!1,signedIn:!1,reason:pe("Codex","codex")}:{ok:!0}:{ok:!1,reason:"codex not found on PATH. Install it and run `codex login`."}}function xe(s){if(!s?.url)return[];const o=s.serverName||"chatpanel_browser",{command:t,args:c}=oe(s.url),e=["-c",`mcp_servers.${o}.command=${JSON.stringify(t)}`,"-c",`mcp_servers.${o}.args=${JSON.stringify(c)}`,"-c",`mcp_servers.${o}.default_tools_approval_mode="approve"`,"-c",`mcp_servers.${o}.startup_timeout_sec=30`,"-c",`mcp_servers.${o}.tool_timeout_sec=${Math.ceil(ne(s.specs)/1e3)}`],n=[...new Set((s.specs||[]).map(i=>i?.name).filter(Boolean))];return n.length&&e.push("-c",`mcp_servers.${o}.enabled_tools=${JSON.stringify(n)}`),e}function we(s){try{const o=M(g.join(s,"config.toml"),"utf8"),t=new Set;for(const c of o.matchAll(/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*[.\]]/gm))t.add(c[1]);return t}catch{return new Set}}function _e(s){const o=new Set;try{const t=M(g.join(s,"config.toml"),"utf8"),c=/^\s*\[mcp_servers\.([A-Za-z0-9_-]+)\s*\]\s*$([\s\S]*?)(?=^\s*\[|$(?![\r\n]))/gm;for(const e of t.matchAll(c)){const n=e[2]||"",i=/^\s*command\s*=\s*"([^"]*)"/m.exec(n)?.[1]||"",r=/^\s*url\s*=\s*"([^"]*)"/m.exec(n)?.[1]||"";(/chatpanel-(gateway|bridge)(\.js|\.cmd|\.exe)?$/.test(i)||/^https?:\/\/(127\.0\.0\.1|localhost):43(19|20)\//.test(r))&&o.add(e[1])}}catch{}return o}function Se(s=[]){return s.flatMap(o=>["-c",`mcp_servers.${o}.enabled=false`])}async function $e(s,o){const t=[];for(let c=0;c<(s?.length||0);c++){const e=/^data:([^;]+);base64,(.+)$/s.exec(s[c]?.dataUrl||"");if(!e)continue;const n=(e[1].split("/")[1]||"png").replace(/[^a-z0-9]/gi,"").slice(0,5)||"png",i=g.join($.tmpdir(),`chatpanel-codex-img-${o}-${c}.${n}`);await Y(i,Buffer.from(e[2],"base64")),t.push(i)}return t}async function ve({argsFor:s,readOnly:o=!1,cwd:t,env:c,prompt:e,outFile:n,emit:i,signal:r}){const a=await G().wrapOwn("codex",s,{cwd:t,stdio:["pipe","pipe","pipe"],env:c,...q},{engine:"codex",cwd:t,readOnly:o});return K(i,a.record),new Promise((l,u)=>{let f;try{f=z(R(a.bin,a.argv,a.opts),a,{kind:"agent"})}catch(m){return u(new Error(`Failed to start codex: ${m.message}`))}const v=W(f,r);let y="",I="",k=!1;const b=m=>{m?.type!=="status"&&(k=!0),i(m)},w={started:new Set,reasoned:new Set,n:0};let _;const S=()=>{clearTimeout(_),_=setTimeout(()=>{f.kill("SIGKILL"),u(new Error(`Codex timed out — no output for ${Math.round(F/1e3)}s.`))},F)};S(),f.stdout.on("data",m=>{S(),y+=m.toString();let h;for(;(h=y.indexOf(`
|
|
2
|
+
`))>=0;){const A=y.slice(0,h).trim();if(y=y.slice(h+1),!!A.startsWith("{"))try{be(JSON.parse(A),b,w)}catch{}}}),f.stderr.on("data",m=>{S(),I+=m.toString()}),f.on("error",m=>{clearTimeout(_),v(),u(m)}),f.on("close",async m=>{clearTimeout(_),v();let h="";try{h=(await V(n,"utf8")).trim()}catch{}T(n).catch(()=>{}),l({code:m,stderr:I,text:h,streamed:k,said:!!w.saidAny,policyBlocked:!!w.policyBlocked,threadId:w.threadId||null})}),f.stdin.write(e),f.stdin.end()})}async function Ge({messages:s,system:o,options:t,images:c},e,{signal:n}={}){const i=Q("codex",s,t,{cwd:B(t.workingDir)}),r=await he({messages:s,system:o,options:t,images:c,thread:i},e,{signal:n}).catch(l=>({handled:!1,reason:l?.message||String(l),thrown:!0}));if(r.handled){r.completed&&(r.thread||i)?.record(r.sessionId);return}if(n?.aborted)return;if(r.thrown)throw new Error(r.reason);const a=await J({messages:s,system:o,options:t,images:c,thread:i},e,{signal:n});a?.completed&&a.thread?.record(a.sessionId)}async function J({messages:s,system:o,options:t,images:c,thread:e=null},n,{signal:i}={}){const r=e?.plan.mode==="resume"?e.plan.sessionId:null,a=`${Date.now()}-${Math.random().toString(36).slice(2)}`,l=g.join($.tmpdir(),`chatpanel-codex-${a}.txt`),u=await $e(c,a),f=()=>u.forEach(d=>T(d).catch(()=>{})),v=B(t.workingDir),y=[];ce(y,t.extraArgs,ie.codex,n);const I=(d,x=!0)=>{const p=["exec","--json","--skip-git-repo-check","-o",l];if(t.permissionMode==="bypassPermissions")p.push("--dangerously-bypass-approvals-and-sandbox");else if(!x)p.push("-s","danger-full-access"),O||p.push("-c","approval_policy=never");else{const C=t.permissionMode==="acceptEdits"?"workspace-write":"read-only";p.push("-s",C),p.push(...Z({harness:"codex",roots:U(v),dirs:t.dirs})),O||p.push("-c","approval_policy=never")}H&&p.push("-c",`model_reasoning_effort=${H}`),p.push("-c","model_reasoning_summary=auto"),p.push(...xe(t.mcp)),p.push(...Se(d)),t.model&&p.push("-m",t.model),p.push(...y);for(const C of u)p.push("-i",C);return r?p.push(...j({harness:"codex",mode:"resume",id:r})):t.ephemeral===!0&&p.splice(1,0,...j({harness:"codex",mode:"off"})),p.push("-"),p},k=t.useLocalConfig!==!1,b={...process.env,...t.runEnv||{}};if(!k){const d=ye();d&&(b.CODEX_HOME=d)}const w=t.mcp?.serverName||"chatpanel_browser",_=b.CODEX_HOME||process.env.CODEX_HOME||g.join($.homedir(),".codex"),S=we(_),m=(t.mcp?.specs||[]).length>0;let h=[...new Set([...ue("codex",t,[w]),...m?_e(_):[]])].filter(d=>S.has(d));const A=ae(r?e.plan.tail||s.slice(-1):s,o),D=()=>ve({argsFor:d=>I(h,d),readOnly:t.permissionMode!=="acceptEdits"&&t.permissionMode!=="bypassPermissions",cwd:v,env:b,prompt:A,outFile:l,emit:n,signal:i});try{let d=await D();if(d.policyBlocked&&(O=!0),!i?.aborted&&d.code!==0&&!d.streamed){const x=fe({agent:"codex",text:d.stderr,protect:[w],already:h});x&&S.has(x.server)&&(me("codex",x.server),n({type:"status",text:`MCP server "${x.server}" failed to load — ${x.short}. Skipping it and retrying.`}),h=[...h,x.server],d=await D())}if(i?.aborted)return null;if(r&&d.code!==0&&!d.streamed)return e.forget(),f(),J({messages:s,system:o,options:t,images:c,thread:e.restart()},n,{signal:i});if(d.code!==0)throw de("Codex",d.code,d.stderr,"",{agentId:"codex"});return d.said||n({type:"delta",text:d.text||"(no output)"}),n({type:"done",text:""}),{completed:!0,sessionId:d.threadId||r,thread:e}}finally{f()}}function be(s,o,t={started:new Set,reasoned:new Set,n:0}){const c=s.type||"";c==="thread.started"&&typeof s.thread_id=="string"&&(t.threadId=s.thread_id);const e=s.item||{},n=e.type||"",i=c==="item.completed"||e.status==="completed"||e.status==="failed";if(n==="agent_message"&&i){const r=e.id||`msg_${t.n++}`,a=String(e.text||"");a&&!t.said?.has(r)&&((t.said||=new Set).add(r),o({type:"delta",text:`${t.saidAny?`
|
|
3
3
|
|
|
4
|
-
`:""}${
|
|
5
|
-
`);t.lastTodo!==
|
|
6
|
-
${
|
|
7
|
-
`}));return}(
|
|
4
|
+
`:""}${a}`}),t.saidAny=!0);return}if(n==="command_execution"||!n&&c.includes("command")){const r=e.id||`cmd_${t.n++}`;if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:"shell",phase:"start",callId:r,input:{command:e.command||""}})),i){const a=e.exit_code===0||e.exit_code==null;o({type:"tool",name:"shell",phase:"done",callId:r,status:a?"ok":`exit ${e.exit_code}`,result:String(e.aggregated_output||"").slice(0,4e3)})}return}if(n==="file_change"||!n&&c.includes("patch")){const r=e.id||`edit_${t.n++}`,a=Array.isArray(e.changes)?e.changes.map(l=>l.path||l.file).filter(Boolean):[];t.started.has(r)||(t.started.add(r),o({type:"tool",name:"edit",phase:"start",callId:r,input:{files:a}})),i&&o({type:"tool",name:"edit",phase:"done",callId:r,status:"ok"});return}if(n==="web_search"){const r=e.id||`ws_${t.n++}`,a=e.action&&typeof e.action=="object"?e.action:{},l=e.query||a.query||"",u=a.url||"";t.started.has(r)||(t.started.add(r),o({type:"tool",name:"web_search",phase:"start",callId:r,input:{query:l,...u?{url:u}:{}}})),(i||c==="item.completed")&&o({type:"tool",name:"web_search",phase:"done",callId:r,status:"ok",result:u?`Opened ${u}`:l?`Searched the web for ${l}`:"Searched the web"});return}if(n==="mcp_tool_call"){const r=e.id||`mcp_${t.n++}`,a=e.server?`${e.server}/${e.tool||"tool"}`:e.tool||"mcp";if(t.started.has(r)||(t.started.add(r),o({type:"tool",name:a,phase:"start",callId:r,input:e.arguments&&typeof e.arguments=="object"?e.arguments:{}})),i){const l=e.status==="failed"||e.error!=null,u=e.error&&typeof e.error=="object"?e.error.message||JSON.stringify(e.error):e.error,f=e.result==null?"":typeof e.result=="string"?e.result:JSON.stringify(e.result);o({type:"tool",name:a,phase:"done",callId:r,status:l?`error: ${String(u||"failed").slice(0,80)}`:"ok",result:String(l?u||"":f).slice(0,4e3)})}return}if(n==="todo_list"&&Array.isArray(e.items)&&e.items.length){const r=e.items.map(a=>`${a.completed?"☑":"☐"} ${a.text||""}`).join(`
|
|
5
|
+
`);t.lastTodo!==r&&(t.lastTodo=r,o({type:"status",text:`Plan:
|
|
6
|
+
${r}`}));return}if(n==="error"||c==="error"){const r=String(e.message||s.message||"");if(!r)return;if(/approval_policy.*(disallowed|not in the allowed set)/i.test(r)){t.policyBlocked=!0,t.policyNoted||(t.policyNoted=!0,o({type:"status",text:"Codex: your organisation pins approval_policy, so Codex will ask before actions it cannot run on its own. ChatPanel will stop passing its own setting."}));return}o({type:"status",text:`Codex: ${r.slice(0,300)}`});return}if(n==="reasoning"||!n&&c.includes("reasoning")){const r=e.id||`r_${t.n++}`,a=e.text||e.summary||"";a&&!t.reasoned.has(r)&&(t.reasoned.add(r),o({type:"reasoning",text:`${a}
|
|
7
|
+
`}));return}(c==="turn.started"||c==="thread.started")&&o({type:"status",text:"Codex working"})}export{ze as available,Ge as chat,J as chatCold,Se as codexDisableArgs,xe as codexMcpConfigArgs,we as configuredMcpServers,ye as ensureIsolatedHome,be as forwardEvent,qe as listModels,_e as redundantChatpanelServers,We as resetApprovalPolicy,$e as writeImages};
|
package/src/engines/custom.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{spawn as v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import x from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as tt}from"../env.js";import{missingCommandMessage as U}from"../events/mcp-errors.js";import{sandbox as I,noteSandbox as et,track as F,grantedWriteRoots as rt}from"../sandbox.js";import{harnessDirArgs as nt}from"../events/harness-cards.js";import{isProEntitled as D}from"../entitlement.js";import{killOnAbort as ot}from"../proc.js";import{buildCliPrompt as it,fitCliPrompt as st,argvPromptBudget as at}from"./prompt.js";import{pushExtraArgs as lt,FORBIDDEN as H}from"./args.js";import{createStreamParser as ct,STREAM_FORMATS as mt}from"./stream-formats.js";import{resolveWorkdir as ut}from"../workdir.js";async function
|
|
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 v}from"node:child_process";import{readFile as Q,writeFile as k,unlink as Y}from"node:fs/promises";import T from"node:os";import x from"node:path";import{resolveCommand as L,buildSpawnSpec as _,selfMcpStdio as tt}from"../env.js";import{missingCommandMessage as U}from"../events/mcp-errors.js";import{sandbox as I,noteSandbox as et,track as F,grantedWriteRoots as rt}from"../sandbox.js";import{harnessDirArgs as nt}from"../events/harness-cards.js";import{isProEntitled as D}from"../entitlement.js";import{killOnAbort as ot}from"../proc.js";import{buildCliPrompt as it,fitCliPrompt as st,argvPromptBudget as at}from"./prompt.js";import{pushExtraArgs as lt,FORBIDDEN as H}from"./args.js";import{createStreamParser as ct,STREAM_FORMATS as mt}from"./stream-formats.js";import{resolveWorkdir as ut}from"../workdir.js";import{cliError as pt}from"../cli-errors.js";async function dt(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",d=x.join(T.tmpdir(),`chatpanel-custom-img-${n}-${r}.${s}`);await k(d,Buffer.from(o[2],"base64")),e.push(d)}return e}function ft(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 J=Number(process.env.CHATPANEL_CUSTOM_TIMEOUT_MS)||18e4,gt="http://127.0.0.1:4319/mcp",j="http://127.0.0.1:4319/mcp";async function Wt(){return{ok:!0}}function ht(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 Xt(t={}){if(!await D(t.entitlement))throw new Error("Custom agents require ChatPanel Pro.");const n=t.custom||{};return wt(n.command,n.listModelsArgs,t.workingDir)}async function wt(t,n,e){const r=String(n||"").trim();if(!t||!r)return[];const o=await St(t,r.split(/\s+/).filter(Boolean),e);return ht(o)}async function St(t,n,e,r=2e4){if(!t)return"";const o=L(t);if(!o)throw new Error(U(t,{platform:process.platform}));const s=e?x.resolve(e):null,[d,f,g]=_(o,n,s);g.env={...g.env||process.env,NO_COLOR:"1",CLICOLOR:"0"};const y=await I().wrap(d,f,g,{engine:"custom",cwd:s}),{bin:m,argv:$,opts:u}=y;return new Promise((i,h)=>{let S;try{S=F(v(m,$,u),y,{kind:"probe"})}catch(C){return h(new Error(`Failed to start ${t}: ${C.message}`))}let l="";const M=setTimeout(()=>{S.kill("SIGKILL"),h(new Error(`${t} timed out.`))},r);S.stdout.on("data",C=>l+=C.toString()),S.on("error",C=>{clearTimeout(M),h(new Error(`Failed to start ${t}: ${C.message}`))}),S.on("close",()=>{clearTimeout(M),i(l)});try{S.stdin.end()}catch{}})}function z(t){return(t?.specs||[]).filter(n=>n?.name)}function G(t,n){const e=String(t).replace(/[^A-Za-z0-9_$]/g,"_");return/^[A-Za-z_$]/.test(e)?e:`tool_${n}_${e}`}function yt(t,n){return["--extension",t]}function Ct(t,n){const e=String(t||"").trim(),r=z(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 $t(t={},n){return t.trustAllToolsForMcp?[t.trustAllToolsArg||"--trust-all-tools"]:t.trustToolsArg?Ct(t.trustToolsArg,n):[]}function bt(t={}){return t.stableMcpSetupCommand?t.stableMcpSetupCommand:`opencode mcp add chatpanel --url ${j}`}function At(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 xt(t){const n=z(t),e=n.map((o,s)=>{const d=G(o.name,s),f=o.parameters||{type:"object",properties:{}};return`const ${d}Tool = {
|
|
3
3
|
name: ${JSON.stringify(o.name)},
|
|
4
4
|
label: ${JSON.stringify(o.name)},
|
|
5
5
|
description: ${JSON.stringify(o.description||o.name)},
|
|
@@ -65,7 +65,7 @@ ${e}
|
|
|
65
65
|
export default function (pi: ExtensionAPI) {
|
|
66
66
|
${r}
|
|
67
67
|
}
|
|
68
|
-
`}async function
|
|
68
|
+
`}async function Mt(t,n){const e=x.join(T.tmpdir(),`chatpanel-pi-tools-${n}.ts`);return await k(e,xt(t)),e}async function Tt(){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 Q(e,"utf8")).includes(gt))return!0}catch{}return!1}async function K(t,n,e){const r=L(t);if(!r)return"";const[o,s,d]=_(r,n,e||null),f=await I().wrap(o,s,d,{engine:"custom",cwd:e||null}),{bin:g,argv:y,opts:m}=f;return new Promise($=>{const u=F(v(g,y,m),f,{kind:"probe"});let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(i+h)},4e3);u.stdout.on("data",l=>i+=l.toString()),u.stderr.on("data",l=>h+=l.toString()),u.on("error",()=>{clearTimeout(S),$(i+h)}),u.on("close",()=>{clearTimeout(S),$(i+h)});try{u.stdin.end()}catch{}})}async function Et(t,n){for(const e of["workspace","global","default"]){const r=await K(t,["mcp","list",e],n);if(r.includes(j)||/chatpanel_browser/i.test(r))return!0}return!1}async function Ot(t,n){const e=await K(t,["mcp","list"],n);return e.includes(j)||/chatpanel_browser/i.test(e)}async function Pt(t,n){return t.stableMcpConfigCheck==="kiro"?Et(t.command||"kiro-cli",n):t.stableMcpConfigCheck==="opencode"?Tt():t.stableMcpConfigCheck==="hermes"?Ot(t.command||"hermes",n):!1}async function vt(t,n){const e=L(t.command);if(!e)throw new Error(`Couldn't find "${t.command}" to set up browser tools.`);const[r,o,s]=_(e,t.args,n||null);s.env={...s.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const d=await I().wrap(r,o,s,{engine:"custom",cwd:n||null}),{bin:f,argv:g,opts:y}=d;await new Promise((m,$)=>{let u;try{u=F(v(f,g,y),d,{kind:"probe"})}catch(l){return $(new Error(`Failed to start ${t.command}: ${l.message}`))}let i="",h="";const S=setTimeout(()=>{u.kill("SIGKILL"),$(new Error(`${t.command} MCP setup timed out.`))},2e4);u.stderr.on("data",l=>i+=l.toString()),u.stdout?.on("data",l=>h+=l.toString()),u.on("error",l=>{clearTimeout(S),$(new Error(`Failed to start ${t.command}: ${l.message}`))}),u.on("close",l=>{if(clearTimeout(S),l===0)return m(`${h}
|
|
69
69
|
${i}`.trim());$(new Error(`${t.command} MCP setup exited ${l}: ${i.trim().split(`
|
|
70
|
-
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function
|
|
71
|
-
`).filter(Boolean).slice(-3).join(" ")}`:"")+` Run: ${f}`)}async function
|
|
70
|
+
`).pop()||"failed"}`))});try{u.stdin.end()}catch{}})}function kt(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 Lt(t,n,e,r,o={}){if(!t.requiresStableMcp)return!0;const s=o.hasConfig||Pt,d=o.runSetup||vt;if(await s(t,n))return!0;const f=bt(t);if(!t.autoSetupStableMcp){const m=`${e} needs one-time browser-tool setup: ${f}`;throw r({type:"status",text:m}),new Error(m)}const g=At(t);if(!g?.command){const m=`${e} needs one-time browser-tool setup: ${f}`;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 d(g,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: ${f}`)}async function Qt({messages:t,system:n,options:e,images:r},o,{signal:s}={}){if(!await D(e.entitlement))throw new Error("Custom agents require ChatPanel Pro. Upgrade in Settings to bring your own CLI agent.");return _t(e.custom||{},{messages:t,system:n,options:e,images:r},o,{signal:s})}async function _t(t,{messages:n,system:e,options:r={},images:o},s,{signal:d}={}){if(!t.command)throw new Error("This agent has no command configured.");const f=L(t.command);if(!f)throw new Error(U(t.command,{platform:process.platform}));let g=it(n,e),y=ut(r.workingDir);const m=t.label||t.command,$=Object.hasOwn(mt,t.format)?t.format:"text",u=t.promptVia==="arg"?"arg":"stdin";let i=Array.isArray(t.args)?t.args.slice():t.args?String(t.args).split(/\s+/).filter(Boolean):[];if(lt(i,r.extraArgs,H[t.forbidden]||H.custom,s),r.model&&t.modelArg){const a=String(t.modelArg),c=a.includes("{model}")?a.replaceAll("{model}",r.model).split(/\s+/).filter(Boolean):[...a.split(/\s+/).filter(Boolean),r.model];i=[...i,...c]}if(t.permissionArgs){const a=String(r.permissionMode||"default"),c=t.permissionArgs[a]||t.permissionArgs.default||[];i=[...i,...c.map(String)]}i=[...i,...nt({harness:t.dirsHarness||t.command,roots:rt(y),dirs:t.dirs!==void 0?t.dirs:r.dirs})];const h=`${Date.now()}-${Math.random().toString(36).slice(2)}`,S=t.imageArg?await dt(o,h):[],l=[],M=()=>[...S,...l].forEach(a=>Y(a).catch(()=>{}));if(r.mcp?.url&&t.toolAdapter==="pi-extension"){const a=await Mt(r.mcp,h);l.push(a),i=[...yt(a,r.mcp),...i]}else if(r.mcp?.url&&t.mcpArg){const a=r.mcp.serverName||"chatpanel_browser",{command:c,args:p}=tt(r.mcp.url),w=x.join(T.tmpdir(),`chatpanel-mcp-${h}.json`);await k(w,JSON.stringify({mcpServers:{[a]:{command:c,args:p}}})),l.push(w);const b=String(t.mcpArg);i=[...b.includes("{file}")?b.replaceAll("{file}",w).split(/\s+/).filter(Boolean):[...b.split(/\s+/).filter(Boolean),w],...i]}if(r.mcp?.url)try{await Lt(t,y,m,s)}catch(a){s({type:"status",text:`${m}: continuing without ChatPanel's browser tools — ${kt(m,a)}`}),r={...r,mcp:null}}if(r.mcp?.url&&i.push(...$t(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 c=x.join(T.tmpdir(),`chatpanel-modelpatch-${h}.yml`);await k(c,t.modelPatch.build(a)),l.push(c);const p=String(t.modelPatch.arg||"--patch {file}");i=[...p.includes("{file}")?p.replaceAll("{file}",c).split(/\s+/).filter(Boolean):[...p.split(/\s+/).filter(Boolean),c],...i]}}const C=ft(t.imageArg,S);let N=!1;if(C.length&&(i=i.flatMap(a=>a==="{images}"?(N=!0,C):[a])),u==="arg"){const a=i.reduce((w,b)=>w+String(b).length+3,0)+C.reduce((w,b)=>w+String(b).length+3,0),c=st(n,e,at({viaCmdExe:f.kind==="cmd",otherArgsChars:a}));(c.dropped||c.prompt!==g)&&(g=c.prompt,s({type:"status",text:`${m} takes the prompt as a command-line argument, which this system caps — the oldest ${c.dropped||"part of the"} turn${c.dropped===1?"":"s"} of this conversation ${c.dropped?"were":"was"} left out to fit.`}));let p=!1;i=i.map(w=>w.includes("{prompt}")?(p=!0,w.replaceAll("{prompt}",g)):w),p||(C.length&&!N&&i.push(...C),i.push(g))}else C.length&&!N&&i.push(...C);const[Z,q,R]=_(f,i,y,r.runEnv||null);R.env={...R.env||process.env,NO_COLOR:"1",FORCE_COLOR:"0",CLICOLOR:"0",TERM:"dumb"};const E=await I().wrap(Z,q,R,{engine:"custom",cwd:y});et(s,E.record);const[V,W,X]=[E.bin,E.argv,E.opts];await new Promise((a,c)=>{let p;try{p=F(v(V,W,X),E,{kind:"agent"})}catch(A){return M(),c(new Error(`Failed to start ${m}: ${A.message}`))}const w=ot(p,d);let b="";const O=ct($,s);let P;const B=()=>{clearTimeout(P),P=setTimeout(()=>{p.kill("SIGKILL"),M(),c(new Error(`${m} timed out — no output for ${Math.round(J/1e3)}s.`))},J)};B(),p.stdout.on("data",A=>{B(),O.push(A.toString())}),p.stderr.on("data",A=>{B(),b+=A.toString()}),p.on("error",A=>{clearTimeout(P),w(),M(),c(new Error(`Failed to start ${m}: ${A.message}`))}),p.on("close",A=>{if(clearTimeout(P),w(),M(),d?.aborted){a();return}A===0?(s({type:"done",text:O.streamed?"":O.finish()}),a()):c(pt(m,A,b))}),u==="stdin"&&p.stdin.write(g),p.stdin.end()})}export{j as CHATPANEL_STABLE_MCP_URL,Wt as available,xt as buildPiExtensionSource,Qt as chat,K as commandOutput,Lt as ensureStableMcpConfig,Xt as listModels,wt as listSpecModels,kt as mcpSetupHint,$t as mcpTrustArgs,yt as piToolArgs,St as runForStdout,_t as runSpec,bt as stableMcpSetupCommand,At as stableMcpSetupPlan,Ct as trustToolArgs};
|
package/src/engines/prompt.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import{stripHidden as
|
|
1
|
+
import{stripHidden as c}from"../sanitize.js";import{seedWithin as g}from"../events/compaction.js";function h(n){return n==="assistant"?"Assistant":"User"}function p(n=[],o=""){const r=String(o||"").trim(),e=Array.isArray(n)?n:[],s=e.slice(0,-1),t=e[e.length-1];if(!s.length&&!r&&t)return c(String(t.content||"").trim());const i=[];if(r&&i.push(r),s.length){const{kept:m,elided:l}=g(s),f=m.map(a=>`${h(a.role)}: ${String(a.content||"").trim()}`).join(`
|
|
2
2
|
|
|
3
|
-
`)
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
`),u=l?`(${l} earlier message${l===1?"":"s"} of this conversation are not repeated here, to fit — ask the user, or look them up, if they matter.)
|
|
4
|
+
|
|
5
|
+
`:"";i.push(`Conversation history (context only; do not answer these prior turns):
|
|
6
|
+
${u}${f}`)}return t&&i.push(`Current ${h(t.role).toLowerCase()} message (answer this message now; use the history above only as context):
|
|
7
|
+
${String(t.content||"").trim()}`),c(i.join(`
|
|
6
8
|
|
|
7
9
|
---
|
|
8
10
|
|
|
9
|
-
`))}function
|
|
10
|
-
`;t=i+t.slice(t.length-(
|
|
11
|
+
`))}function $({platform:n=process.platform,viaCmdExe:o=!1,otherArgsChars:r=0}={}){return Math.max(2e3,(o?8191:n==="win32"?32767:n==="linux"?131072:262144)-1500-r)}function x(n=[],o="",r=1/0){let e=Array.isArray(n)?n:[],s=0,t=p(e,o);for(;t.length>r&&e.length>1;)e=e.slice(1),s+=1,t=p(e,o);if(t.length>r){const i=`[…earlier part of the message omitted to fit the command line…]
|
|
12
|
+
`;t=i+t.slice(t.length-(r-i.length))}return{prompt:t,dropped:s}}export{$ as argvPromptBudget,p as buildCliPrompt,x as fitCliPrompt};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
`);let
|
|
1
|
+
const $="permission_request",p=Object.freeze({ALLOW:"allow",ALLOW_CHAT:"allow_chat",DENY:"deny"}),W=600*1e3,_="permission_prompt";function N(){return{name:_,description:"Chap-internal: the person answers the agent's permission prompt. Not for the model.",parameters:{type:"object",properties:{tool:{type:"string"},input:{type:"object"},description:{type:"string"},path:{type:"string"},rules:{type:"array"}}}}}const T=t=>t===_,u=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),a=t=>typeof t=="string"?t:t==null?"":String(t);function k(t={}){const e=u(t)?t:{},o=a(e.tool_name||e.toolName||e.tool),n=[];for(const s of Array.isArray(e.permission_suggestions)?e.permission_suggestions:[])if(!(!u(s)||s.type!=="addRules"||s.behavior==="deny"))for(const r of Array.isArray(s.rules)?s.rules:[]){if(!u(r))continue;const c=a(r.toolName||o),i=a(r.ruleContent);c&&!n.some(f=>f.tool===c&&f.content===i)&&n.push({tool:c,content:i})}return{tool:o,displayName:a(e.display_name||e.displayName)||o,input:u(e.input)?e.input:{},description:a(e.description),path:a(e.blocked_path||e.path)||null,rules:n,toolUseId:a(e.tool_use_id||e.toolUseId)||null}}function g(t={}){const e=Array.isArray(t.rules)?t.rules.filter(o=>o&&o.tool):[];return e.length?e.map(o=>o.content?`${o.tool}(${o.content})`:o.tool):t.tool?[String(t.tool)]:[]}function L(t={}){const e=a(t.tool),o=u(t.input)?t.input:{},n=(l,d=240)=>l.length>d?`${l.slice(0,d-1)}…`:l;let s,r;if(e==="Bash")s="Run a command",r=n(a(o.command).trim()||a(t.description)||"a shell command");else if(e==="Edit"||e==="MultiEdit"||e==="NotebookEdit")s="Edit a file",r=a(o.file_path||o.notebook_path||t.path)||"a file";else if(e==="Write"){s="Write a file";const l=a(o.file_path||t.path)||"a file",d=a(o.content).length;r=d?`${l} (${d.toLocaleString()} chars)`:l}else if(/^mcp__/.test(e))s="Use a connected server",r=e.replace(/^mcp__/,"").replace(/__/," › ");else{s=`Use ${t.displayName||e||"a tool"}`;let l="";try{l=JSON.stringify(o)}catch{l=""}r=a(t.description)||(l&&l!=="{}"?n(l,200):e)}const c=g(t),i=Array.isArray(t.rules)?t.rules.filter(l=>l?.content):[],f=i.length&&i.some(l=>l.content!==r)?i.map(l=>l.content).join(", "):c.length&&!i.length?`every ${e} call`:null;return{title:s,detail:r,scope:f,description:a(t.description)||null}}function h(t,e=""){return t===p.ALLOW?{behavior:"allow",scope:"once"}:t===p.ALLOW_CHAT?{behavior:"allow",scope:"chat"}:{behavior:"deny",scope:"once",...e?{message:String(e)}:{}}}function w(t){return u(t)&&t.behavior==="allow"}function E(t,e){const o=new Set(Array.isArray(t)?t:[]);for(const n of g(e))o.add(n);return[...o].sort()}const b="*";function O(t,e){const o=new Set(Array.isArray(t)?t:[]);if(o.has(b))return h(p.ALLOW);const n=g(e);return n.length&&n.every(s=>o.has(s))?h(p.ALLOW):null}function R(t,e,o={}){const n=u(o)?o:{},s=w(e);let r;if(s){if(r={behavior:"allow",updatedInput:u(n.input)?n.input:{}},e.scope==="chat"){const c=(Array.isArray(n.permission_suggestions)?n.permission_suggestions:[]).filter(i=>u(i)&&i.type==="addRules"&&i.behavior!=="deny"&&Array.isArray(i.rules)&&i.rules.length).map(i=>({type:"addRules",rules:i.rules,behavior:"allow",destination:"session"}));c.length&&(r.updatedPermissions=c)}}else r={behavior:"deny",message:a(e?.message)||"The user declined this action in Chap. Continue without it, or explain what it was for and ask."};return{type:"control_response",response:{subtype:"success",request_id:String(t),response:r}}}function C(t,e){const{detail:o}=L(t),n=w(e),s=n&&e.scope==="chat"?" for this chat":"";return`${n?"Allowed":"Declined"}${s}: ${o}`}function x(t){return t==="Bash"?"code":/^(Edit|MultiEdit|NotebookEdit)$/.test(String(t))?"pencil":t==="Write"?"file":/^mcp__/.test(String(t))?"plug":"bot"}function P({memory:t=new Map}={}){const e=t;async function o(n,{convId:s=null,confirm:r,agentName:c="The agent"}={}){const i=O(await e.get(s)||[],n);if(i)return i;const{title:f,detail:l,scope:d,description:y}=L(n),S=[l,y&&y!==l?y:"",d?`“Allow for this chat” also covers: ${d}`:""].filter(Boolean).join(`
|
|
2
|
+
`);let m;try{if(typeof r!="function")throw new Error("no card");m=await r(S,{title:`${c} asks — ${f.toLowerCase()}?`,iconName:x(n.tool),scopeLabel:"Allow for this chat",allLabel:"Allow all in this chat"})}catch(A){return h(p.DENY,`Chap could not show the permission card (${A?.message||A}).`)}return m==="all"?(await e.set(s,[b]),h(p.ALLOW_CHAT)):m==="site"||m==="always"?(await e.set(s,E(await e.get(s)||[],n)),h(p.ALLOW_CHAT)):h(m==="allow"?p.ALLOW:p.DENY)}return{ask:o,forget(n){e.delete(n)},standing(n){return e.get(n)||[]},provider({convId:n=null,confirm:s,agentName:r="The agent"}={}){return{id:"permission",specs:[N()],execute:async(c,i)=>JSON.stringify(await o(i&&typeof i=="object"?i:{},{convId:n,confirm:s,agentName:r}))}}}}export{b as ALLOW_ALL,p as PERMISSION_ANSWERS,$ as PERMISSION_EVENT,W as PERMISSION_TIMEOUT_MS,_ as PERMISSION_TOOL_NAME,R as claudePermissionResponse,P as createPermissionDesk,L as describePermission,T as isPermissionTool,w as permissionAllowed,h as permissionAnswer,x as permissionIcon,g as permissionKeys,C as permissionLine,k as permissionRequestFromClaude,N as permissionToolSpec,O as recallPermission,E as rememberPermission};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{EventError as p}from"./event.js";const y=(t,r)=>{if(!t)throw new p("SHAPE",r)},m=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function I(t){if(!t||typeof t!="object")return null;const r=String(t.id??"").trim().replace(/^chat:/,"");if(!m.test(r))return null;const n=String(t.title??"").replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim().slice(0,120);return{id:r,...n?{title:n}:{}}}function E(t){return t?[`chat:${t}`]:[]}function x(t=[]){const n=(Array.isArray(t)?t:[]).slice(0,-1);return{users:n.filter(e=>e?.role==="user").map(e=>l(e.content).trim()),answers:n.filter(e=>e?.role==="assistant").length}}function A(t=[],{answered:r=!0}={}){const n=Array.isArray(t)?t:[];return{users:n.filter(e=>e?.role==="user").map(e=>l(e.content).trim()),answers:n.filter(e=>e?.role==="assistant").length+(r?1:0)}}const g=8;function h(t,r=g){const n=String(t??"").trim(),e=[n];let s=n;for(let i=0;i<r;i++){const o=s.lastIndexOf(`
|
|
2
|
+
|
|
3
|
+
`);if(o<0)break;s=s.slice(0,o).trim(),s&&e.push(s)}return[...new Set(e)]}function w(t,r){const n=String(r??"").trim();return h(t).includes(n)}function b(t=[],{answered:r=!0}={}){const n=A(t,{answered:r});return{users:n.users.slice(0,-1),answers:n.answers,last:h(n.users.at(-1)??"")}}function P(t=[]){const r=x(t);return{users:r.users.slice(0,-1),answers:r.answers,last:r.users.at(-1)??null}}function T(t=[],{n:r,answers:n}={}){const e=Array.isArray(t)?t:[];if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return null;const s=[];let i=0,o=-1;for(let f=0;f<e.length;f++){const c=e[f];if(c?.role==="user"){if(s.length===r){o=f;break}s.push(l(c.content).trim())}else c?.role==="assistant"&&i++}if(o<0)return null;const u=n-i;if(u!==0&&u!==1)return null;let a=o+1;if(u===1){for(;a<e.length&&e[a]?.role!=="assistant";){if(e[a]?.role==="user")return null;a++}if(a>=e.length)return null;a++}const d=e.slice(a);return d.at(-1)?.role!=="user"?null:{prefix:{users:s,answers:n},last:l(e[o].content).trim(),tail:d,answered:u===1}}function D(t=[],r=()=>!1,{answered:n=!0}={}){const e=Array.isArray(t)?t:[];for(let s=e.length-1;s>=0;s--){if(e[s]?.role!=="user"||!r(l(e[s].content).trim()))continue;let i=s+1;n&&e[i]?.role==="assistant"&&i++;const o=e.slice(i).filter(u=>u?.role==="user"||u?.role==="assistant");return o.at(-1)?.role==="user"&&o.pop(),o}return[]}function _(t=[],r=[]){let n=Array.isArray(t)?t:[];for(const e of Array.isArray(r)?r:[]){if(e?.role!=="user")continue;const s=n.findIndex(i=>i?.role==="user"&&w(l(i.content),l(e.content)));s>=0&&(n=[...n.slice(0,s),...n.slice(s+1)])}return n}function z(t=[]){const r=Array.isArray(t)?t:[],n=r.filter(e=>e?.role==="user").map(e=>l(e.content).trim());return{users:n.slice(0,-1),answers:r.filter(e=>e?.role==="assistant").length,last:h(n.at(-1)??"")}}function l(t){return typeof t=="string"?t:Array.isArray(t)?t.map(r=>typeof r=="string"?r:r?.text||"").filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`):String(t??"")}function N({link:t=null,digest:r="",cwd:n="",hasHistory:e=!1}={}){return y(typeof r=="string","threadPlan: digest must be a string"),!t||!t.sessionId?{mode:"start",sessionId:null,seed:!!e,why:"no session holds this thread yet"}:String(t.cwd||"")!==String(n||"")?{mode:"start",sessionId:null,seed:!!e,why:"the thread moved to another folder"}:!r||t.digest!==r?{mode:"start",sessionId:null,seed:!!e,why:"the history differs from what the session saw (edited or regenerated)"}:{mode:"resume",sessionId:String(t.sessionId),seed:!1,why:"the session has seen exactly this history"}}export{T as historyExtension,x as historyShape,P as historySplit,E as legacyThreadIds,A as nextShape,I as normalizeThread,_ as outsideBeyond,D as outsideTurns,z as seenOf,h as sentVariants,N as threadPlan,b as turnSeen,w as userTextMatches};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{keepRecentFor as m}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.",f=4e3;function a(e=[]){return(Array.isArray(e)?e:[]).filter(t=>t&&!t.pending&&(t.role==="user"||t.role==="assistant")&&(t.content||t.attachments?.length))}function y({messages:e=[],keepRecent:t=4,budget:n=0,tokensOf:o=null}={}){const r=a(e);let i=Math.max(1,Math.floor(Number(t)||4));if(n>0&&typeof o=="function")for(;i>1&&r.slice(r.length-i).reduce((c,p)=>c+(o(p)||0),0)>n;)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(c=>`${c.role==="user"?"User":"Assistant"}: ${String(c.content||"").slice(0,f)}`).join(`
|
|
2
|
+
|
|
3
|
+
`);return{fold:s,keep:l,uptoId:s[s.length-1].id,transcript:u}}function x({transcript:e="",previousSummary:t=""}={}){return`${t?`Earlier summary to fold in:
|
|
4
|
+
${t}
|
|
5
|
+
|
|
6
|
+
`:""}Summarize the conversation so far:
|
|
7
|
+
|
|
8
|
+
${e}`}function S({summary:e,uptoId:t,now:n=Date.now()}={}){return{summary:String(e||"").trim(),uptoId:t,ts:n}}function A(e=[],t=null){const n=a(e);if(!t?.uptoId)return n;const o=n.findIndex(r=>r.id===t.uptoId);return o>=0?n.slice(o+1):n}function E(e="",t=null){const n=String(t?.summary||"").trim();return n?`${e?`${e}
|
|
9
|
+
|
|
10
|
+
`:""}[Summary of the earlier part of this conversation — continue seamlessly; do not mention this summary]
|
|
11
|
+
${n}`:e||""}const d=36e4;function k(e=[],{maxChars:t=d}={}){const n=Array.isArray(e)?e:[];let o=0,r=n.length;for(;r>0;){const i=String(n[r-1]?.content??"").length+16;if(o+i>t&&r<n.length)break;o+=i,r-=1}return{kept:n.slice(r),elided:r}}export{g as COMPACTION_SYSTEM,d as SEED_MAX_CHARS,a as compactable,x as compactionPrompt,S as compactionRecord,m as keepRecentFor,A as messagesAfter,y as planCompaction,k as seedWithin,E as systemWithSummary};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const u=t=>t==null?0:Math.round((typeof t=="string"?t:JSON.stringify(t)).length/4),k=t=>typeof t=="string"?t:Array.isArray(t)?t.map(o=>o?.type==="text"&&o.text||"").join(`
|
|
2
|
+
`):"",L=t=>Array.isArray(t)?t.filter(o=>o&&o.type!=="text").length:0,K=/<context source="[^"]*">\n# \[([\w-]+)\][^\n]*\n[\s\S]*?\n<\/context>/g,W=/<presence>\n[\s\S]*?\n<\/presence>/g,j=/\n*\[Chap\] Likely useful for this message[^\n]*/g;function M(t){const o=String(t||""),c=[];let r=o.replace(K,(l,a)=>(c.push({kind:a==="prefetch"?"fetched":"attached",of:a,tokens:u(l)}),""));r=r.replace(W,l=>(c.push({kind:"presence",tokens:u(l)}),""));let d=0;return r=r.replace(j,l=>(d+=u(l),"")),{words:u(r.trim()),blocks:c,hint:d}}function B(t){const o=String(t||"");return o.trim()?o.split(/\n(?=## )/).map(r=>{const d=(r.match(/^## ([^\n]+)/)||[])[1];return{label:d?d.trim().slice(0,60):"Instructions",tokens:u(r)}}).filter(r=>r.tokens>0):[]}const v=Object.freeze({instructions:"The system prompt: who the assistant is, how to answer, what it may use. Sent on every turn so the model behaves the same way each time.",toolText:"The tools' rules and catalog: which actions exist and when to use them. Sent every turn; the provider caches it.",toolSchemas:"The tool definitions the model can call — kept to one tool (`tools`) so a turn carries one schema, not one per action.",history:'The earlier messages of this conversation, so a follow-up ("how many in south?") is read against what came before.',historyCarried:"Context that rode on earlier messages — fetched results, attachments, presence — kept with them so the model can refer back.",toolExchange:"Tool calls and their results from earlier rounds.",fetched:"Looked up before the model ran (the weather, a search, the page), so it answers instead of calling a tool.",attached:"What the person attached to this message, or the client added as context.",presence:"What exists around the turn (the open page, notes, what was fetched before) — names, not contents.",hint:"The actions likely useful for this message — appended to the message, not the system prompt, so the prompt cache holds.",words:"The person's own words.",agentOwn:"The agent's own context: its system prompt, its built-in tools, its skills and MCP servers, its session. Not sent by us; it reads it every turn.",cached:"Read from the provider's prompt cache — already there, billed at a fraction, and fast."});function H({messages:t=[],tools:o=null,usage:c=null,agent:r=!1,agentContext:d=null}={}){const l=Array.isArray(t)?t:[],a=[],i=(e,n,s,h={})=>{(s>0||h.always)&&a.push({id:e,label:n,tokens:s,why:v[e]||"",...h})},y=l.filter(e=>e?.role==="system").map(e=>k(e.content)).join(`
|
|
3
|
+
|
|
4
|
+
`),b=String(o?.system||""),E=b&&y.includes(b)?y.replace(b,""):y,S=B(E);i("instructions","Instructions (system prompt)",S.reduce((e,n)=>e+n.tokens,0),S.length>1?{items:S}:{}),i("toolText","Tool rules & catalog",u(b));const C=Array.isArray(o?.specs)?o.specs:[];i("toolSchemas",`Tool definitions (${C.length})`,u(C),{count:C.length});const g=l.filter(e=>e&&e.role!=="system");let p=-1;for(let e=g.length-1;e>=0;e--)if(g[e].role==="user"){p=e;break}const q=p>=0?g.slice(0,p):g,I=p>=0?g.slice(p+1):[];let N=0,O=0,A=0,x=0;const T=new Map;for(const e of q){if((e.role==="tool"||e.tool_calls)&&(A+=u(k(e.content))+u(e.tool_calls),e.role==="tool")||e.role!=="user"&&e.role!=="assistant")continue;e.role==="user"&&(x+=1);const n=M(k(e.content));N+=n.words+n.hint;for(const s of n.blocks)O+=s.tokens,T.set(s.of||s.kind,(T.get(s.of||s.kind)||0)+s.tokens)}i("history",`Conversation history (${x} earlier ${x===1?"question":"questions"})`,N,{count:x}),i("historyCarried","Context carried in the history",O,T.size?{items:[...T].map(([e,n])=>({label:e,tokens:n}))}:{});for(const e of I)A+=u(k(e.content))+u(e.tool_calls);if(i("toolExchange","Tool calls & results",A),p>=0){const e=g[p],n=M(k(e.content)),s=m=>n.blocks.filter(f=>f.kind===m),h=m=>m.reduce((f,$)=>f+$.tokens,0);i("fetched","Fetched for this message",h(s("fetched")),{count:s("fetched").length}),i("attached","Attached to this message",h(s("attached")),{count:s("attached").length,...s("attached").length?{items:s("attached").map(m=>({label:m.of,tokens:m.tokens}))}:{}}),i("presence","Presence (what is around the turn)",h(s("presence"))),i("hint","Hint (likely actions)",n.hint),i("words","Your message",n.words,{always:!0,...L(e.content)?{images:L(e.content)}:{}})}const _=a.reduce((e,n)=>e+n.tokens,0),w={rows:a,ours:_};if(c){const e=h=>Math.max(0,Number(h)||0),n=e(c.cacheReadTokens),s=e(c.inputTokens)+n+e(c.cacheWriteTokens);if(s>0&&(w.reported=s,w.cached=n,w.requests=e(c.requests)||e(c.calls)||1,r)){const h=Math.max(0,s-_*w.requests),m=Array.isArray(d)?d.filter(f=>f&&Number(f.tokens)>0).map(f=>({label:String(f.label),tokens:Math.round(Number(f.tokens))})):null;w.agentOwn=h,a.push({id:"agentOwn",label:"The agent's own context",tokens:h,why:v.agentOwn,...m?.length?{items:m}:{}})}}return w}function P(t){const o=[],c=String(t||""),r=c.match(/\*\*Tokens:\*\*\s*([\d.]+)(k|m)?\s*\//i)||[];for(const l of c.split(`
|
|
5
|
+
`)){const a=l.match(/^\|\s*([^|]+?)\s*\|\s*([\d.,]+)\s*(k|m)?\s*\|\s*[\d.]+%\s*\|$/i);if(!a)continue;const i=a[1].trim();if(/deferred|free space|autocompact|^category$/i.test(i))continue;const y=Number(a[2].replace(/,/g,""))*(a[3]?.toLowerCase()==="k"?1e3:a[3]?.toLowerCase()==="m"?1e6:1);y>0&&o.push({label:i,tokens:Math.round(y)})}if(!o.length)return null;const d=r[1]?Math.round(Number(r[1])*(r[2]?.toLowerCase()==="k"?1e3:r[2]?.toLowerCase()==="m"?1e6:1)):o.reduce((l,a)=>l+a.tokens,0);return{items:o,total:d}}export{H as contextBreakdown,P as parseAgentContext,M as splitMessage,B as systemSections};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=[[/^apple-on-device$|apple[-_ ]?foundation/,4096],[/gemini-?nano/,4096]],l=[[/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(n={},t=null){const e=String(n.id||""),r=String(n.model||n.id||"").toLowerCase(),c=t&&(t[a(n)]||t[r]||t[String(n.model||"")]||(n.gateway?0:t[e]));if(Number(c)>0)return Number(c);const i=Number(n.window||n.contextLength||n.contextWindow||0);if(i>0)return i;for(const[o,u]of d)if(o.test(r))return u;if(n.reach==="device"||n.kind==="webllm")return 0;for(const[o,u]of l)if(o.test(r))return u;return 0}function a(n={}){const t=String(n.id||""),e=String(n.model||"");return e?`${t}:${e}`:t}const s=.85,f=8192,p=n=>Number(n)>0&&Number(n)<=f,w=2;function _({promptTokens:n=0,floorTokens:t=0,window:e=0,reserve:r=1024,headroom:c=s}={}){const i=Number(e)||0;if(!i)return{status:"unknown",budget:0,over:0,window:0};const o=Math.max(0,Math.floor(i*c)-Math.max(0,Number(r)||0)),u=Math.max(0,Number(n)||0),m=Math.max(0,Number(t)||0);return u<=o?{status:"ok",budget:o,over:0,window:i}:m<=o?{status:"compact",budget:o,over:u-o,window:i}:{status:"too-big",budget:o,over:m-o,window:i}}function b(n=0){const t=Number(n)||0;return t?t<=8e3?2:t<=32768?4:t<=128e3?8:12:4}function h({floorTokens:n=0,reserve:t=1024,headroom:e=s}={}){const r=Math.max(0,Number(n)||0);return r?Math.ceil((r+Math.max(0,Number(t)||0))/e):0}function N(n){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(n?.message||n||""))}export{s as FIT_HEADROOM,f as SMALL_WINDOW,w as SMALL_WINDOW_ROUNDS,_ as fitFor,N as isContextLimitError,p as isSmallWindow,b as keepRecentFor,h as minWindowFor,a as observedKey,x as windowOf};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{normalizeCard as s,cardToProfile as p,A2A_VERSION as u}from"./agent-card.js";import{defineAgentDialect as h}from"./agent-dialects.js";const a=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),y=h({id:"a2a",label:"A2A agent card",filename:t=>`${t?.id||"agent"}.agent-card.json`,detect(t,{filename:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return 0}if(!n||typeof n!="object"||Array.isArray(n))return 0;const i=!!a(n.name)&&!!a(n.description),e=Array.isArray(n.supportedInterfaces)||!!a(n.url)||!!n.capabilities;return/agent-card\.json$/i.test(r)&&i?.99:i&&e&&Array.isArray(n.skills)?.9:i&&e?.6:0},parse(t,{name:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return{form:{},extras:{},warnings:["not JSON"]}}const i=s(n),e=[];return i.supportedInterfaces.length||e.push("this card names no endpoint, so there is nowhere to reach the agent"),e.push("a card advertises a remote agent: its engine is a placeholder until
|
|
1
|
+
import{normalizeCard as s,cardToProfile as p,A2A_VERSION as u}from"./agent-card.js";import{defineAgentDialect as h}from"./agent-dialects.js";const a=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),y=h({id:"a2a",label:"A2A agent card",filename:t=>`${t?.id||"agent"}.agent-card.json`,detect(t,{filename:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return 0}if(!n||typeof n!="object"||Array.isArray(n))return 0;const i=!!a(n.name)&&!!a(n.description),e=Array.isArray(n.supportedInterfaces)||!!a(n.url)||!!n.capabilities;return/agent-card\.json$/i.test(r)&&i?.99:i&&e&&Array.isArray(n.skills)?.9:i&&e?.6:0},parse(t,{name:r=""}={}){let n;try{n=JSON.parse(String(t??""))}catch{return{form:{},extras:{},warnings:["not JSON"]}}const i=s(n),e=[];return i.supportedInterfaces.length||e.push("this card names no endpoint, so there is nowhere to reach the agent"),e.push("a card advertises a remote agent: its engine is a placeholder until Chap can call an A2A endpoint"),{form:{id:"",name:i.name||a(r),purpose:i.description,prompt:m(i),engine:{kind:"auto",policy:{prefer:"balanced"}},grants:["none"],skills:i.skills.map(o=>o.id)},extras:{card:i},warnings:e}},render(t){return`${JSON.stringify(g(t),null,2)}
|
|
2
2
|
`},carries:["id","name","purpose","skills","provider","version","iconUrl","documentationUrl","tags","examples","inputModes","outputModes"],notes:{prompt:"a card is served to strangers — an agent's own instructions are never published in one",engine:"a card says where to reach an agent, never what model is behind it",grants:"what a remote agent may touch is its own operator's business, not ours to declare",tools:"a card advertises skills, not the tools behind them",denyTools:"a card advertises skills, not the tools behind them",mcpServers:"an agent's own connections are not published",permissionMode:"no equivalent — authorization is expressed with security schemes",sandboxMode:"no equivalent — how a remote agent is contained is its operator's business",maxTurns:"no equivalent in a card",effort:"no equivalent in a card",isolation:"no equivalent in a card",color:"no equivalent in a card",background:"no equivalent in a card",hooks:"no equivalent in a card",memoryScope:"no equivalent in a card",workdir:"a local path has no meaning to whoever reads the card"}});function m(t){const r=s(t),n=[];if(r.description&&n.push(r.description),r.skills.length){n.push("","What it offers:");for(const e of r.skills)n.push(`- ${e.name||e.id}${e.description?` — ${e.description}`:""}`)}const i=r.supportedInterfaces[0];return i&&n.push("",`Reached over A2A at ${i.url} (${i.protocolBinding}).`),r.provider?.organization&&n.push(`Published by ${r.provider.organization}.`),n.join(`
|
|
3
3
|
`).trim()}function g(t,{interfaces:r=[],profile:n=u,skills:i=[]}={}){const e=t||{},o=e.dialectExtras?.a2a?.card,c=i.length?i:(e.skills||[]).map(l=>f(l,e)),d=s({...o||{},name:e.name||e.id||"",description:e.purpose||"",version:e.version||o?.version||"0.1.0",...e.provider?{provider:e.provider}:{},...e.iconUrl?{iconUrl:e.iconUrl}:{},...e.documentationUrl?{documentationUrl:e.documentationUrl}:{},supportedInterfaces:r.length?r:o?.supportedInterfaces||[],capabilities:{streaming:!0,pushNotifications:!1,...o?.capabilities||{}},defaultInputModes:e.inputModes?.length?e.inputModes:o?.defaultInputModes,defaultOutputModes:e.outputModes?.length?e.outputModes:o?.defaultOutputModes,skills:c});return delete d.signatures,p(d,n)}function f(t,r){const n=String(t||"").trim();return{id:n,name:n,description:`${n}, as performed by ${r?.name||r?.id||"this agent"}`,tags:r?.tags?.length?[...r.tags]:[]}}export{y as a2aDialect,m as briefFromCard,g as cardFromAgent};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{parseFrontmatter as p,renderFrontmatter as k}from"./frontmatter.js";import{defineAgentDialect as w,grantsFromTools as S,toolsFromGrants as b,toNameList as d}from"./agent-dialects.js";const T=Object.freeze(["name","description","tools","disallowedTools","model","permissionMode","maxTurns","skills","mcpServers","hooks","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental"]),x=Object.freeze(["tools","disallowedTools","model","permissionMode","maxTurns","isolation","color","hooks","initialPrompt"]),m=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),A=w({id:"claude",label:"Claude Code",filename:t=>`${t?.id||"agent"}.md`,detect(t,{filename:o=""}={}){const{meta:e,body:n}=p(t);if(!e.name&&!e.description)return 0;const i=/(^|\/)agents\//.test(o)&&/\.md$/i.test(o),r=x.some(s=>e[s]!==void 0);return/(^|\/)SKILL\.md$/i.test(o)||!i&&/(^|\/)skills\//.test(o)?0:i&&r?.95:i?.8:r?.7:n.trim()?.35:.2},parse(t,{name:o=""}={}){const{meta:e,body:n}=p(t),i=[],r=d(e.tools),{grants:s,mcpServers:c,unmapped:u}=S(r);u.length&&i.push(`tools with no
|
|
1
|
+
import{parseFrontmatter as p,renderFrontmatter as k}from"./frontmatter.js";import{defineAgentDialect as w,grantsFromTools as S,toolsFromGrants as b,toNameList as d}from"./agent-dialects.js";const T=Object.freeze(["name","description","tools","disallowedTools","model","permissionMode","maxTurns","skills","mcpServers","hooks","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental"]),x=Object.freeze(["tools","disallowedTools","model","permissionMode","maxTurns","isolation","color","hooks","initialPrompt"]),m=t=>typeof t=="string"?t.trim():t==null?"":String(t).trim(),A=w({id:"claude",label:"Claude Code",filename:t=>`${t?.id||"agent"}.md`,detect(t,{filename:o=""}={}){const{meta:e,body:n}=p(t);if(!e.name&&!e.description)return 0;const i=/(^|\/)agents\//.test(o)&&/\.md$/i.test(o),r=x.some(s=>e[s]!==void 0);return/(^|\/)SKILL\.md$/i.test(o)||!i&&/(^|\/)skills\//.test(o)?0:i&&r?.95:i?.8:r?.7:n.trim()?.35:.2},parse(t,{name:o=""}={}){const{meta:e,body:n}=p(t),i=[],r=d(e.tools),{grants:s,mcpServers:c,unmapped:u}=S(r);u.length&&i.push(`tools with no Chap equivalent, left ungranted rather than guessed at: ${u.join(", ")}`);const f=d(e.mcpServers),h={id:"",name:m(e.name)||m(o),purpose:m(e.description),prompt:n.trim(),engine:y(e.model),grants:s.length?s:["none"],skills:d(e.skills)},a={raw:{}};for(const[l,g]of Object.entries(e))T.includes(l)||(a.raw[l]=g);Object.keys(a.raw).length||delete a.raw,r.length&&(a.tools=r),d(e.disallowedTools).length&&(a.disallowedTools=d(e.disallowedTools)),f.length&&(a.mcpServers=f);for(const l of["permissionMode","maxTurns","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental","hooks"])e[l]!==void 0&&(a[l]=e[l]);return m(e.model)&&(a.model=m(e.model)),{form:h,extras:a,warnings:i}},render(t){const o=t||{},e=o.dialectExtras?.claude||{},n={name:o.id||o.name||"agent",description:o.purpose||o.name||""},i=o.grants?.length?b(o.grants,{dialect:"claude"}):d(e.tools);i.length&&(n.tools=i),e.disallowedTools&&(n.disallowedTools=e.disallowedTools);const r=v(o,e);r&&(n.model=r),o.skills?.length&&(n.skills=[...o.skills]),e.mcpServers&&(n.mcpServers=e.mcpServers);for(const s of["permissionMode","maxTurns","memory","background","omitClaudeMd","effort","isolation","color","initialPrompt","experimental","hooks"])e[s]!==void 0&&(n[s]=e[s]);for(const[s,c]of Object.entries(e.raw||{}))n[s]===void 0&&(n[s]=c);return k(n,`
|
|
2
2
|
${String(o.prompt||"").trim()}
|
|
3
3
|
`)},carries:["id","name","purpose","prompt","engine","grants","skills","mcpServers","tools","denyTools","permissionMode","maxTurns","effort","isolation","color","background","hooks"],notes:{sandboxMode:"Claude Code has no sandbox_mode; its equivalent is permissionMode plus the tools allowed",memoryScope:"Claude Code scopes memory to user, project or local — not to a named namespace",workdir:"a Claude Code agent runs wherever the session runs; a working directory is not part of its definition",provider:"a definition file describes an agent, not who publishes it — that is A2A card territory",version:"a definition file carries no version of its own",iconUrl:"no icon in the format",documentationUrl:"no documentation link in the format",tags:"no tags in the format",examples:'no examples in the format — the description is where the "use this when" goes',inputModes:"media types are an A2A idea",outputModes:"media types are an A2A idea"}});function y(t){const o=m(t);return!o||o==="inherit"?o==="inherit"?{kind:"assistant"}:{kind:"harness",harnessId:"claude"}:{kind:"harness",harnessId:"claude",model:o}}function v(t,o){const e=t?.engine;return e?.kind==="assistant"?"inherit":e?.kind==="harness"&&e.harnessId==="claude"&&e.model||e?.kind==="model"&&e.model&&/claude|sonnet|opus|haiku/i.test(String(e.model))?String(e.model):o.model?String(o.model):""}export{A as claudeDialect};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as
|
|
1
|
+
import{EventError as a}from"./event.js";const l=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}"]}},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",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"}}),p=n=>String(n||"").toLowerCase().replace(/[^a-z]/g,""),d={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function s(n){const o=p(n);if(l[o])return{id:o,...l[o]};if(d[o])return{id:d[o],...l[d[o]]};const e=Object.entries(l).find(([i,t])=>o.includes(i)||o.includes(p(t.label)));return e?{id:e[0],...e[1]}:null}function m(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 u(n){if(n==null)return null;if(typeof n=="string")return u({flag:n,repeat:!0});if(typeof n!="object"||Array.isArray(n))throw new a("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const o=String(n.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(o))throw new a("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 a("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 h({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=u(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 w(n,o){try{return!!u(o!==void 0?o:s(n)?.dirs??null)}catch{return!1}}const f=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function A({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(c=>c==="{name}"?r:c)}if(o!=="resume"||!Array.isArray(t.resume))return[];if(!f.test(String(e)))throw new a("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 y=n=>Array.isArray(s(n)?.session?.resume);export{l as HARNESS_CARDS,s as harnessCard,h as harnessDirArgs,m as harnessEgress,y as harnessResumes,A as harnessSessionArgs,w as harnessTakesDirs,u as normalizeDirsSpec};
|
package/src/events/mcp-signin.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const m=-32011,d=/https?:\/\/[^\s"'<>)\]]+/,w=/\b(?:code|passcode)\b[:\s]+([A-Z0-9][A-Z0-9-]{3,}[A-Z0-9])\b/,g=/sign[ -]?in|log[ -]?in|authenticate|authoriz|verify|devicelogin|login\/device|oauth/i,b=/opening (?:your |the |a )?browser|open(?:ed|ing)? .*browser .*sign/i,_=/[?&]redirect_uri=https?%3A%2F%2F(?:localhost|127\.0\.0\.1)|[?&]redirect_uri=https?:\/\/(?:localhost|127\.0\.0\.1)/i;function I(n){const e=String(n||"");return/response_type=code/i.test(e)?_.test(e):!1}function A(n){const e=String(n||"");if(!e.trim())return null;const o=e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),c=o.join(" "),a=w.exec(c)?.[1]||null,u=o.filter(t=>g.test(t)||d.test(t)),s=u.find(t=>d.test(t)&&g.test(t))||u.find(t=>d.test(t)),i=s?d.exec(s)[0].replace(/[.,;]+$/,""):null;if(i&&(a||g.test(c))){const t=(u.find(r=>g.test(r))||s).slice(0,300);return!a&&I(i)?{url:i,code:null,message:t,browser:!0,interactive:!0}:{url:i,code:a,message:t,browser:!1,interactive:!1}}const l=o.find(t=>b.test(t));return l?{url:null,code:null,message:l.slice(0,300),browser:!0,interactive:!0}:null}function E(n){const e=n.url?` Open ${n.url}${n.code?` and enter the code ${n.code}`:""}.`:"";return{code:-32011,message:`Sign-in required: ${n.message}${e}`,data:{signIn:{url:n.url,code:n.code,message:n.message,browser:!!n.browser,interactive:!!n.interactive}}}}function N(n){if(!n||n.code!==-32011)return null;const e=n.data?.signIn;return e?{url:e.url||null,code:e.code||null,message:e.message||"",browser:!!e.browser,interactive:!!e.interactive}:{url:null,code:null,message:String(n.message||""),browser:!1,interactive:!1}}function x(n,e){return{error:"sign_in_required",server:n,...e.url&&!e.interactive?{url:e.url}:{},...e.code?{code:e.code}:{},...e.browser?{browser:!0}:{},next:e.interactive?"The server opened its own browser window for the user to sign in, and any link it printed works only in that window, right now. Tell them to finish signing in there and then ask again. Do NOT paste the link, and do not invent a result.":"The user has been shown this sign-in prompt. Give them the url and the code exactly, ask them to complete it, then call this tool again. Do not invent a result."}}const y=/"error"\s*:\s*"sign_in_failed"|\bAADSTS\d{5,}\b|could not obtain an? [\w ]{0,20}token|\binvalid_grant\b|\bsign[- ]?in (?:failed|was declined)\b/i;function S(n){const e=typeof n=="string"?n:n&&typeof n.text=="string"?n.text:"";return!!e&&y.test(e)}const v=1440*60*1e3;function h(n){const e=n||{};return JSON.stringify([e.url||"",e.command||"",Array.isArray(e.args)?e.args:[],Object.keys(e.env||{}).sort(),Object.keys(e.headers||{}).sort()])}function C(n,e,{text:o="",now:c=Date.now(),ttlMs:a=v}={}){const u=Array.isArray(n)?n:[],s=e&&typeof e=="object"?e:{},i=new Set(String(o||"").toLowerCase().match(/[a-z][a-z0-9]+/g)||[]),l=t=>String(t?.name||"").toLowerCase().match(/[a-z][a-z0-9]+/g)?.some(r=>r.length>1&&!["mcp","server","the","my"].includes(r)&&i.has(r));return u.filter(t=>{const r=s[t?.name];return!r||c-Number(r.at||0)>a||r.fingerprint&&r.fingerprint!==h(t)?!0:!!l(t)})}function D(n,e,o,{prefixOf:c}={}){if(!n||!o||typeof c!="function")return n;const a=Array.isArray(e)?e:[],u=s=>a.find(i=>String(s||"").startsWith(c(i.name)))||null;return{...n,async execute(s,i,l){const t=await n.execute(s,i,l),r=u(i?.action||s);if(r)try{const f=S(t)?o.failed(r.name,h(r)):o.recovered(r.name);f&&typeof f.catch=="function"&&f.catch(()=>{})}catch{}return t}}}export{m as MCP_SIGN_IN_CODE,v as SIGN_IN_FAILED_TTL_MS,A as parseSignInPrompt,h as serverFingerprint,E as signInError,S as signInFailedIn,N as signInFromError,x as signInToolResult,D as watchSignIns,C as withoutFailedSignIns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as L}from"./event.js";import{normalizeGrant as x}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as P,SECRET_DIR_PAIRS as N}from"./secret-names.js";const R=Object.freeze(["none","process","container","kubernetes"]),S=Object.freeze(["open","allowlist","none","gateway"]),E=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},_=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),b=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},v=E.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function I(e,t=""){const n=m(g(_(g(e),t)));if(!n)return!1;for(const o of E)if(b(n,o)||t&&b(n,_(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return v.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((c,l)=>c.toLowerCase()===r[s+l]))return!0;return!1})}const $=Object.freeze([...[...P].map(e=>`~/**/${e}`),...N.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]);function J(e,{home:t="",globs:n=[...E,...$]}={}){const r=m(g(_(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const c of n){const l=m(g(c));if(l){if(l.startsWith("~/**/")){if(s&&!b(r,s))continue;const a=l.slice(5).split("/").filter(Boolean).map(z);for(let i=0;i+a.length<=o.length;i+=1)if(a.every((f,p)=>f.test(o[i+p])))return c;continue}if(b(r,_(l,t)))return c}}return null}function z(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const W=".cache/chatpanel/ca-bundle.crt",ee=".cache/chatpanel/ca-bundle.pem";function te(e=""){const t=m(g(e));return t?`${t}/${W}`:`~/${W}`}const H=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),D=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),C=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"],keychain:!0}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),T="~/Library/Keychains",K=/(^|\/)Keychains\/?$/,k=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),O=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),d=(e,t)=>{if(!e)throw new L("SHAPE",t)},u=e=>[...new Set(e)];function j(e){d(h(e),"kit: must be an object"),d(typeof e.id=="string"&&e.id.length>0,"kit: id required"),d(h(e.network)&&S.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${S.join(", ")}`),d(O(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),d(O(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),d(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])d(O(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return d(O(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),e.image!=null&&d(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&d(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:u(e.network.allowedDomains||[]),deniedDomains:u(e.network.deniedDomains||[])},filesystem:{allowWrite:u(e.filesystem.allowWrite),denyWrite:u(e.filesystem.denyWrite||[]),allowRead:u(e.filesystem.allowRead||[]),denyRead:u(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as pe,mergeGrants as ge,parseHostList as me}from"./sandbox-grant.js";const Y=e=>String(e).replace(/([\\/])\*$/,"$1**");function ne({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:c=null,home:l="",reads:a="enumerated",readOnly:i=!1}={}){const f=C[e]||C.custom;d(typeof t=="string"&&t.length>0,"kit: cwd required");const p=x(c);return j({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:u([...f.hosts,...k,...r,...p.hosts]),deniedDomains:[]},filesystem:{allowWrite:u(i?[...D,...f.write]:[t,...D,...f.write,...[...o,...p.write].filter(A=>!I(A,l)).map(Y)]),denyWrite:[],allowRead:a==="inverted"?u([t,...H,...f.write,...f.keychain?[T]:[],...B({grant:p,extraWrite:o,cwd:t,home:l})]):[t],denyRead:u([...a==="inverted"?["~",...l?[l]:[]]:[],...[...E,...$].filter(A=>!(f.keychain&&K.test(A))),...s])}})}function U(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function B({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let f=String(i||"").trim();for(;f.length>1&&(f.endsWith("/")||f.endsWith("\\"));)f=f.slice(0,-1);return f},c=(i,f)=>i===f||i.startsWith(`${f}/`)||i.startsWith(`${f}\\`),l=s(o(n)),a=[];for(const i of[...x(e).write,...Array.isArray(t)?t:[]]){const f=U(s(o(s(i))));if(f&&!I(f,r)&&!(l&&c(f,l))&&!a.some(p=>c(f,p))){for(let p=a.length-1;p>=0;p--)c(a[p],f)&&a.splice(p,1);a.push(f)}}return a}function oe(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=j(e),s=l=>n&&l.startsWith("~")?n+l.slice(1):l,c=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:u([...o.network.allowedDomains,...c]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&c.length>0},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function re({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return d(R.includes(e),`sandbox record: layer must be one of ${R.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:u(s)}:{}}}function G(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){d(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const M=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function se(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of M)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function ie(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>G(r,{platform:n})).join(" ")}const ae=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),q=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function y(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function F(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function ce({kit:e,files:t=[],home:n}){d(typeof n=="string"&&n.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?n+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(d(!q(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),y(i,n)&&o.push(i))}const s=(a,i)=>i.some(f=>w(a)===w(f)||y(a,f)),c=[];for(const a of t){const i=F(a);i&&y(i,n)&&c.push(i)}for(const a of e?.filesystem?.allowRead||[]){const i=r(a);y(i,n)&&c.push(i)}const l=u(c).filter(a=>!s(a,o));return{read:l.filter(a=>!l.some(i=>i!==a&&y(a,i))),write:u(o)}}const X=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function le({engine:e="custom",home:t,env:n={},base:r={},carry:o=X}={}){d(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),c=/^[a-z]:/i.test(s)?s.slice(0,2):"",l={USERPROFILE:s,...c?{HOMEDRIVE:c,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(l[a]=i);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=s+"\\.codex"),l}function fe(e,t){d(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;d(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let c=n+1;c<r;c++)e[c]==="--env"&&typeof e[c+1]=="string"&&o.add(e[c+1].split("=")[0].toUpperCase());const s=[];for(const[c,l]of Object.entries(t||{}))d(/^[A-Za-z_][A-Za-z0-9_]*$/.test(c),`srt-win env: bad key ${c}`),d(!/[\r\n]/.test(l),`srt-win env: ${c} holds a newline`),o.has(c.toUpperCase())||s.push("--env",`${c}=${l}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{W as CA_BUNDLE_RELPATH,ee as CA_BUNDLE_RELPATH_LEGACY,D as COMMON_WRITE,k as DEVELOPER_HOSTS,C as ENGINE_KITS,S as NETWORK_MODES,R as SANDBOX_LAYERS,E as SECRET_PATHS,$ as SECRET_READ_GLOBS,H as TOOLCHAIN_READ,X as WINDOWS_CARRY_KEYS,te as caBundlePath,I as isSecretWritePath,ne as kitFor,ge as mergeGrants,pe as normalizeGrant,me as parseHostList,J as readDenialFor,se as sandboxEnvOverlay,re as sandboxRecord,ie as shellJoin,G as shellQuote,oe as toSrtSettings,y as underWindowsHome,j as validateKit,ce as windowsGrantsFor,F as windowsInstallRoot,le as windowsSandboxEnv,fe as withSrtWinEnv,B as writableRoots};
|
|
1
|
+
import{EventError as L}from"./event.js";import{normalizeGrant as S}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as P,SECRET_DIR_PAIRS as v}from"./secret-names.js";const R=Object.freeze(["none","process","container","kubernetes"]),$=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},x=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),b=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},N=_.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function I(e,t=""){const n=m(g(x(g(e),t)));if(!n)return!1;for(const o of _)if(b(n,o)||t&&b(n,x(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return N.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((a,l)=>a.toLowerCase()===r[s+l]))return!0;return!1})}const W=Object.freeze([...[...P].map(e=>`~/**/${e}`),...v.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]);function ee(e,{home:t="",globs:n=[..._,...W]}={}){const r=m(g(x(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const a of n){const l=m(g(a));if(l){if(l.startsWith("~/**/")){if(s&&!b(r,s))continue;const c=l.slice(5).split("/").filter(Boolean).map(z);for(let i=0;i+c.length<=o.length;i+=1)if(c.every((d,u)=>d.test(o[i+u])))return a;continue}if(b(r,x(l,t)))return a}}return null}function z(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const D=".cache/chatpanel/ca-bundle.crt",te=".cache/chatpanel/ca-bundle.pem";function ne(e=""){const t=m(g(e));return t?`${t}/${D}`:`~/${D}`}const H=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),k=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),C=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"],keychain:!0,sockets:["/tmp/cc-socks","/private/tmp/cc-socks"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),T="~/Library/Keychains",K=/(^|\/)Keychains\/?$/,Y=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),y=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),f=(e,t)=>{if(!e)throw new L("SHAPE",t)},p=e=>[...new Set(e)];function j(e){f(h(e),"kit: must be an object"),f(typeof e.id=="string"&&e.id.length>0,"kit: id required"),f(h(e.network)&&$.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${$.join(", ")}`),f(y(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),f(y(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),f(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])f(y(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return f(y(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),f(y(e.network.unixSockets||[])&&(e.network.unixSockets||[]).every(t=>t.startsWith("/")&&t.replace(/\/+$/,"")!==""),`kit ${e.id}: network.unixSockets must be absolute folders, never /`),e.image!=null&&f(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&f(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:p(e.network.allowedDomains||[]),deniedDomains:p(e.network.deniedDomains||[]),...(e.network.unixSockets||[]).length?{unixSockets:p(e.network.unixSockets)}:{}},filesystem:{allowWrite:p(e.filesystem.allowWrite),denyWrite:p(e.filesystem.denyWrite||[]),allowRead:p(e.filesystem.allowRead||[]),denyRead:p(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ge,mergeGrants as me,parseHostList as we}from"./sandbox-grant.js";const U=e=>String(e).replace(/([\\/])\*$/,"$1**");function oe({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:a=null,home:l="",reads:c="enumerated",readOnly:i=!1,peers:d=!0}={}){const u=C[e]||C.custom;f(typeof t=="string"&&t.length>0,"kit: cwd required");const O=S(a);return j({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:p([...u.hosts,...Y,...r,...O.hosts]),deniedDomains:[],unixSockets:d?[...u.sockets||[]]:[]},filesystem:{allowWrite:p(i?[...k,...u.write]:[t,...k,...u.write,...[...o,...O.write].filter(A=>!I(A,l)).map(U)]),denyWrite:[],allowRead:c==="inverted"?p([t,...H,...u.write,...u.keychain?[T]:[],...G({grant:O,extraWrite:o,cwd:t,home:l})]):[t],denyRead:p([...c==="inverted"?["~",...l?[l]:[]]:[],...[..._,...W].filter(A=>!(u.keychain&&K.test(A))),...s])}})}function B(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function G({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let d=String(i||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},a=(i,d)=>i===d||i.startsWith(`${d}/`)||i.startsWith(`${d}\\`),l=s(o(n)),c=[];for(const i of[...S(e).write,...Array.isArray(t)?t:[]]){const d=B(s(o(s(i))));if(d&&!I(d,r)&&!(l&&a(d,l))&&!c.some(u=>a(d,u))){for(let u=c.length-1;u>=0;u--)a(c[u],d)&&c.splice(u,1);c.push(d)}}return c}function re(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=j(e),s=l=>n&&l.startsWith("~")?n+l.slice(1):l,a=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:p([...o.network.allowedDomains,...a]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&a.length>0,...r==="darwin"&&o.network.unixSockets?.length?{allowUnixSockets:o.network.unixSockets}:{}},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function se({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return f(R.includes(e),`sandbox record: layer must be one of ${R.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:p(s)}:{}}}function M(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){f(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const q=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ie(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of q)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function ce(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>M(r,{platform:n})).join(" ")}const ae=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),F=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function E(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function X(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function le({kit:e,files:t=[],home:n}){f(typeof n=="string"&&n.length>0,"windows grants: home required");const r=c=>(c.startsWith("~")?n+c.slice(1):c).replace(/\//g,"\\"),o=[];for(const c of e?.filesystem?.allowWrite||[]){const i=r(c);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(f(!F(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),E(i,n)&&o.push(i))}const s=(c,i)=>i.some(d=>w(c)===w(d)||E(c,d)),a=[];for(const c of t){const i=X(c);i&&E(i,n)&&a.push(i)}for(const c of e?.filesystem?.allowRead||[]){const i=r(c);E(i,n)&&a.push(i)}const l=p(a).filter(c=>!s(c,o));return{read:l.filter(c=>!l.some(i=>i!==c&&E(c,i))),write:p(o)}}const V=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function de({engine:e="custom",home:t,env:n={},base:r={},carry:o=V}={}){f(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),a=/^[a-z]:/i.test(s)?s.slice(0,2):"",l={USERPROFILE:s,...a?{HOMEDRIVE:a,HOMEPATH:s.slice(2)}:{}};for(const[c,i]of Object.entries(n))typeof i=="string"&&(r[c]!==i||o.includes(c))&&(l[c]=i);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=s+"\\.codex"),l}function fe(e,t){f(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;f(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let a=n+1;a<r;a++)e[a]==="--env"&&typeof e[a+1]=="string"&&o.add(e[a+1].split("=")[0].toUpperCase());const s=[];for(const[a,l]of Object.entries(t||{}))f(/^[A-Za-z_][A-Za-z0-9_]*$/.test(a),`srt-win env: bad key ${a}`),f(!/[\r\n]/.test(l),`srt-win env: ${a} holds a newline`),o.has(a.toUpperCase())||s.push("--env",`${a}=${l}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{D as CA_BUNDLE_RELPATH,te as CA_BUNDLE_RELPATH_LEGACY,k as COMMON_WRITE,Y as DEVELOPER_HOSTS,C as ENGINE_KITS,$ as NETWORK_MODES,R as SANDBOX_LAYERS,_ as SECRET_PATHS,W as SECRET_READ_GLOBS,H as TOOLCHAIN_READ,V as WINDOWS_CARRY_KEYS,ne as caBundlePath,I as isSecretWritePath,oe as kitFor,me as mergeGrants,ge as normalizeGrant,we as parseHostList,ee as readDenialFor,ie as sandboxEnvOverlay,se as sandboxRecord,ce as shellJoin,M as shellQuote,re as toSrtSettings,E as underWindowsHome,j as validateKit,le as windowsGrantsFor,X as windowsInstallRoot,de as windowsSandboxEnv,fe as withSrtWinEnv,G as writableRoots};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=15e3,h=Object.freeze({CHATPANEL_SERVICE:"1"});function p(e={},{labels:s=["net.chatpanel.gateway","net.chatpanel.bridge"]}={}){return e.CHATPANEL_MANAGED_BY==="desktop"?"desktop":e.XPC_SERVICE_NAME&&s.includes(e.XPC_SERVICE_NAME)?"launchd":e.CHATPANEL_SERVICE==="1"?"service":null}function u({name:e,self:s,holder:n,managedBy:i,port:t}){const o=e==="bridge"?"Bridge":"Gateway";if(n?.ours&&i){const r=a(s,n.version);return{action:"standby",lines:[`ChatPanel ${o} v${n.version||"?"} already answers on ${t}; this copy (v${s}, started by ${i}) is standing by and takes over the moment the port is free.`,...r>0?[`This copy is newer. To switch now, stop the other one (\`chatpanel-${e} --status\` shows where it runs).`]:[]]}}if(n?.ours){const r=a(s,n.version);return{action:"exit",lines:[`ChatPanel ${o} v${n.version||"?"} is already running on ${t} — this one (v${s}) did not start.`,r>0?`To replace it with this version and keep it starting at login: chatpanel-${e} --install`:r<0?`The running one is NEWER. Nothing to do — this copy (v${s}) is the stale one; \`which -a chatpanel-${e}\` shows where it comes from.`:`It is this same version: nothing to do. \`chatpanel-${e} --status\` shows how it is started.`]}}return{action:"exit",lines:[]}}function a(e,s){const n=String(e||"").split(".").map(t=>parseInt(t,10)),i=String(s||"").split(".").map(t=>parseInt(t,10));if(n.length<3||i.length<3||n.some(Number.isNaN)||i.some(Number.isNaN))return 0;for(let t=0;t<3;t+=1)if(n[t]!==i[t])return n[t]>i[t]?1:-1;return 0}export{h as SERVICE_ENV,c as STANDBY_POLL_MS,a as compareVersions,u as portClashPlan,p as serviceManagerOf};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function c({compute:l,freshMs:u=1e4,now:a=()=>Date.now()}={}){let e=null,n=null;const t=()=>(n||=Promise.resolve().then(l).then(r=>(e={at:a(),value:r},e)).finally(()=>{n=null}),n);return{async get({fresh:r=!1}={}){return!e||r?t():(a()-e.at>u&&t().catch(()=>{}),e)},warm(){e||t().catch(()=>{})}}}export{c as createSnapshot};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function
|
|
1
|
+
import{assertEndpointUrl as D}from"./net.js";const A=new Map,m=300;function G(){A.clear()}function T(e,t){let o=5381;const r=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${e}`;for(let n=0;n<r.length;n++)o=(o<<5)+o+r.charCodeAt(n)|0;return`${r.length}:${o}`}function p(e,t,o){return new Promise((r,n)=>{const a=setTimeout(()=>n(new Error("detect timeout")),Math.max(200,t||1500)),i=()=>{clearTimeout(a),n(new Error("aborted"))};o&&o.addEventListener?.("abort",i,{once:!0}),e.then(s=>{clearTimeout(a),r(s)},s=>{clearTimeout(a),n(s)})})}function y(e){const t=String(e||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",PRIVATEPERSON:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",PRIVATEADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PRIVATEEMAIL:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PRIVATEPHONE:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",PRIVATEDATE:"ID",PRIVATEURL:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const w=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),C=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]),d=/(?:^|[\s$€£])\$?\d+(?:[.,]\d+)?\s?(?:[kmb]n?|mm|million|billion|thousand|%)(?=[\s.,;:!?)]|$)/i,P=/(?:^|\s)\d{1,6}(?=\s|,|$)/;function g(e){const t=String(e||"").trim();return d.test(t)&&!P.test(t)}const Y=Object.freeze(["balanced","strict"]),L=e=>e?.strictness==="strict"||e?.detection?.strictness==="strict"?"strict":"balanced";function b(e,t,o,r="balanced"){const n=i=>!o||o[i]!==!1;return r!=="strict"&&t==="ADDRESS"&&g(e)?!1:w.has(t)?!0:t==="PERSON"?n("person"):t==="ORG"?n("org"):C.has(t)?n("location"):(String(e).match(/\d/g)||[]).length>=7?n("number"):!1}function R(e,t,{strictness:o="balanced"}={}){let r=[];Array.isArray(e)?r=e:e&&Array.isArray(e.entities)?r=e.entities:e&&Array.isArray(e.ents)?r=e.ents:e&&Array.isArray(e.results)&&(r=e.results);const n=[],a=new Set;for(const i of r){if(!i)continue;const s=String(i.value??i.text??i.entity??i.word??"").trim(),l=y(i.type??i.label??i.entity_group??i.entity_type??i.tag);if(!s||s.length>200||!b(s,l,t,o))continue;const c=`${l}:${s.toLowerCase()}`;a.has(c)||(a.add(c),n.push({value:s,type:l}))}return n}const M=new Set("a an the i am is are was were be been being to of in on at for and or but if so not no yes ok okay hi hello hey you your yours me my mine we us our ours they them their he him his she her it its this that these those what where when who whom why how which do does did done have has had having will would can could should may might must shall there here now then last next first time day days week month year today tomorrow yesterday see saw seen say said tell told go went gone come came get got give gave take took make made know knew think thought want need like just also very really with from into onto over under about after before between through during without within up down out off again still used use using live lived move moved work worked help please thanks thank sorry new old good bad more most some any all each because as than too so such only own same other another much many few both either neither every never always often".split(/\s+/));function V(e){const t=String(e||"");let o=!1;return{text:t.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(n,a,i,s)=>{const l=i+s;if(M.has(l))return n;const c=i.toUpperCase();return c.length!==1||c===i?n:(o=!0,a+c+s)}),changed:o}}function U(e){if(!e)return null;const t=String(e).indexOf("{"),o=String(e).lastIndexOf("}");if(t<0||o<=t)return null;try{return JSON.parse(String(e).slice(t,o+1))}catch{return null}}const k="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",$='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',f=Object.freeze({block:"",format:null,parse:null});async function x(e,t,o,r){const n=await r(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:e,...t.strictness==="strict"?{strict:!0}:{}}),signal:o});if(!n.ok)throw new Error(`detect HTTP ${n.status}`);return R(await n.json(),t.types,{strictness:t.strictness})}async function v(e,t,o,r,n=f){const a=String(t.url||"").replace(/\/$/,""),i=/\/chat\/completions$/.test(a)?a:/\/v\d+$/.test(a)?`${a}/chat/completions`:`${a}/v1/chat/completions`,s=`${k}
|
|
2
2
|
|
|
3
|
-
${
|
|
3
|
+
${n.block||$}`,l=async E=>{const u=n.format?n.format(E):null,h=await r(i,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:s},{role:"user",content:e}],...u||{}}),signal:o});if(!h.ok){const O=new Error(`detect HTTP ${h.status}`);throw O.status=h.status,O}return h.json()};let c=null;if(n.format)for(const E of["schema","object","none"])try{c=await l(E);break}catch(u){if(E==="none"||u.status!==400&&u.status!==422)throw u}else c=await l("none");const S=c?.choices?.[0]?.message?.content??c?.content??"",N=n.parse?n.parse(S):U(S);return R(N,t.types,{strictness:t.strictness})}function I(e,t,o,r,n,a){if(typeof e=="function")try{e({backend:t.backend||"",host:H(t.url),chars:o.length,entities:n,ms:Date.now()-r,ok:!a,error:a?String(a.message||a).slice(0,200):""})}catch{}}const H=e=>{try{return new URL(String(e)).host}catch{return""}};async function _(e,t,{signal:o,fetchImpl:r=globalThis.fetch,strict:n=!1,structured:a=f,onEgress:i=null}={}){const s=t?.detection?{...t.detection,strictness:L(t)}:null;if(!s||!s.backend||s.backend==="off"||!s.url||typeof r!="function")return[];const l=s.transport==="in-process";if(l&&r===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const c=String(e||"").slice(0,s.maxChars||8e3);if(c.trim().length<8)return[];const S=T(c,s);if(!n&&A.has(S))return A.get(S);const N=s.backend==="endpoint"?x:v;let E=[];try{l||D(s.url);const u=Date.now();try{E=await p(N(c,s,o,r,a),s.timeoutMs||1500,o),l||I(i,s,c,u,E.length,null)}catch(h){throw l||I(i,s,c,u,0,h),h}}catch(u){if(n)throw u;E=[]}return A.size>=m&&A.clear(),n||A.set(S,E),E}export{k as EXTRACT_SYS,Y as REDACTION_STRICTNESS,G as clearDetectCache,_ as detectEntities,y as normType,R as normalizeEntities,U as parseJsonLoose,g as quantityNotAddress,V as recaseForDetection,L as strictnessOf,p as withTimeout};
|