@psnext/slingcli 2.4.20260523-3 → 2.4.20260525-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/slingshot/index.js +22 -22
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@psnext/slingcli",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.20260525-1",
|
|
4
4
|
"description": "Connects Sling CLI to Publicis Sapient Slingshot enterprise LLM gateway. Bundles the pi coding-agent runtime.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"type": "git",
|
|
30
30
|
"url": "git+https://pscode.lioncloud.net/psaiproducts/slingcli.git"
|
|
31
31
|
},
|
|
32
|
-
"slingVersion": "2.4.
|
|
32
|
+
"slingVersion": "2.4.20260525-1",
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@earendil-works/pi-tui": "file:../.sling-pack/earendil-works-pi-tui-0.75.4.tgz",
|
|
35
35
|
"@earendil-works/pi-ai": "file:../.sling-pack/earendil-works-pi-ai-0.75.4.tgz",
|
package/slingshot/index.js
CHANGED
|
@@ -175,20 +175,20 @@ ${n.map(o=>` ${o}`).join(`
|
|
|
175
175
|
${s?`<div class="details">${s}</div>`:""}
|
|
176
176
|
</main>
|
|
177
177
|
</body>
|
|
178
|
-
</html>`}function Jd(t){return kT({title:"Authentication successful",heading:"Authentication successful",message:t})}function di(t,e){return kT({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}function MT(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Qd(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e=MT(t),i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",i),r=MT(new Uint8Array(s));return{verifier:e,challenge:r}}var Yd=null,bf=null,vU=t=>atob(t),yf=vU("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),wU="https://claude.ai/oauth/authorize",xa="https://platform.claude.com/v1/oauth/token",SU=process.env.PI_OAUTH_CALLBACK_HOST||"127.0.0.1",IT=53692,RT="/callback",ba=`http://localhost:${IT}${RT}`,CU="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";async function TU(){if(Yd)return Yd;if(!bf){if(typeof process>"u"||!process.versions?.node&&!process.versions?.bun)throw new Error("Anthropic OAuth is only available in Node.js environments");bf=import("node:http").then(t=>({createServer:t.createServer}))}return Yd=await bf,Yd}function xf(t){let e=t.trim();if(!e)return{};try{let n=new URL(e);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(e.includes("#")){let[n,i]=e.split("#",2);return{code:n,state:i}}if(e.includes("code=")){let n=new URLSearchParams(e);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:e}}function gl(t){if(t instanceof Error){let e=[`${t.name}: ${t.message}`],n=t;return n.code&&e.push(`code=${n.code}`),typeof n.errno<"u"&&e.push(`errno=${String(n.errno)}`),typeof t.cause<"u"&&e.push(`cause=${gl(t.cause)}`),t.stack&&e.push(`stack=${t.stack}`),e.join("; ")}return String(t)}async function kU(t){let{createServer:e}=await TU();return new Promise((n,i)=>{let s,r=new Promise(a=>{let c=!1;s=l=>{c||(c=!0,a(l))}}),o=e((a,c)=>{try{let l=new URL(a.url||"","http://localhost");if(l.pathname!==RT){c.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("Callback route not found."));return}let d=l.searchParams.get("code"),u=l.searchParams.get("state"),p=l.searchParams.get("error");if(p){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("Anthropic authentication did not complete.",`Error: ${p}`));return}if(!d||!u){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("Missing code or state parameter."));return}if(u!==t){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("State mismatch."));return}c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(Jd("Anthropic authentication completed. You can close this window.")),s?.({code:d,state:u})}catch{c.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),c.end("Internal error")}});o.on("error",a=>{i(a)}),o.listen(IT,SU,()=>{n({server:o,redirectUri:ba,cancelWait:()=>{s?.(null)},waitForCode:()=>r})})})}async function PT(t,e){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(3e4)}),i=await n.text();if(!n.ok)throw new Error(`HTTP request failed. status=${n.status}; url=${t}; body=${i}`);return i}async function MU(t,e,n,i){let s;try{s=await PT(xa,{grant_type:"authorization_code",client_id:yf,code:t,state:e,redirect_uri:i,code_verifier:n})}catch(o){throw new Error(`Token exchange request failed. url=${xa}; redirect_uri=${i}; response_type=authorization_code; details=${gl(o)}`)}let r;try{r=JSON.parse(s)}catch(o){throw new Error(`Token exchange returned invalid JSON. url=${xa}; body=${s}; details=${gl(o)}`)}return{refresh:r.refresh_token,access:r.access_token,expires:Date.now()+r.expires_in*1e3-300*1e3}}async function _T(t){let{verifier:e,challenge:n}=await Qd(),i=await kU(e),s,r,o=ba;try{let a=new URLSearchParams({code:"true",client_id:yf,response_type:"code",redirect_uri:ba,scope:CU,code_challenge:n,code_challenge_method:"S256",state:e});if(t.onAuth({url:`${wU}?${a.toString()}`,instructions:"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."}),t.onManualCodeInput){let c,l,d=t.onManualCodeInput().then(p=>{c=p,i.cancelWait()}).catch(p=>{l=p instanceof Error?p:new Error(String(p)),i.cancelWait()}),u=await i.waitForCode();if(l)throw l;if(u?.code)s=u.code,r=u.state,o=ba;else if(c){let p=xf(c);if(p.state&&p.state!==e)throw new Error("OAuth state mismatch");s=p.code,r=p.state??e}if(!s){if(await d,l)throw l;if(c){let p=xf(c);if(p.state&&p.state!==e)throw new Error("OAuth state mismatch");s=p.code,r=p.state??e}}}else{let c=await i.waitForCode();c?.code&&(s=c.code,r=c.state,o=ba)}if(!s){let c=await t.onPrompt({message:"Paste the authorization code or full redirect URL:",placeholder:ba}),l=xf(c);if(l.state&&l.state!==e)throw new Error("OAuth state mismatch");s=l.code,r=l.state??e}if(!s)throw new Error("Missing authorization code");if(!r)throw new Error("Missing OAuth state");return t.onProgress?.("Exchanging authorization code for tokens..."),MU(s,r,e,o)}finally{i.server.close()}}async function ET(t){let e;try{e=await PT(xa,{grant_type:"refresh_token",client_id:yf,refresh_token:t})}catch(i){throw new Error(`Anthropic token refresh request failed. url=${xa}; details=${gl(i)}`)}let n;try{n=JSON.parse(e)}catch(i){throw new Error(`Anthropic token refresh returned invalid JSON. url=${xa}; body=${e}; details=${gl(i)}`)}return{refresh:n.refresh_token,access:n.access_token,expires:Date.now()+n.expires_in*1e3-300*1e3}}var vf={id:"anthropic",name:"Anthropic (Claude Pro/Max)",usesCallbackServer:!0,async login(t){return _T({onAuth:t.onAuth,onPrompt:t.onPrompt,onProgress:t.onProgress,onManualCodeInput:t.onManualCodeInput})},async refreshToken(t){return ET(t.refresh)},getApiKey(t){return t.access}};In();var IU=t=>atob(t),AT=IU("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),OT={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},RU=1.2,PU=1.4;function wf(t){let e=t.trim();if(!e)return null;try{return(e.includes("://")?new URL(e):new URL(`https://${e}`)).hostname}catch{return null}}function Sf(t){return{deviceCodeUrl:`https://${t}/login/device/code`,accessTokenUrl:`https://${t}/login/oauth/access_token`,copilotTokenUrl:`https://api.${t}/copilot_internal/v2/token`}}function _U(t){let e=t.match(/proxy-ep=([^;]+)/);return e?`https://${e[1].replace(/^proxy\./,"api.")}`:null}function Cf(t,e){if(t){let n=_U(t);if(n)return n}return e?`https://copilot-api.${e}`:"https://api.individual.githubcopilot.com"}async function Tf(t,e){let n=await fetch(t,e);if(!n.ok){let i=await n.text();throw new Error(`${n.status} ${n.statusText}: ${i}`)}return n.json()}async function EU(t){let e=Sf(t),n=await Tf(e.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:AT,scope:"read:user"})});if(!n||typeof n!="object")throw new Error("Invalid device code response");let i=n.device_code,s=n.user_code,r=n.verification_uri,o=n.interval,a=n.expires_in;if(typeof i!="string"||typeof s!="string"||typeof r!="string"||typeof o!="number"||typeof a!="number")throw new Error("Invalid device code response fields");return{device_code:i,user_code:s,verification_uri:r,interval:o,expires_in:a}}function AU(t,e){return new Promise((n,i)=>{if(e?.aborted){i(new Error("Login cancelled"));return}let s=setTimeout(n,t);e?.addEventListener("abort",()=>{clearTimeout(s),i(new Error("Login cancelled"))},{once:!0})})}async function OU(t,e,n,i,s){let r=Sf(t),o=Date.now()+i*1e3,a=Math.max(1e3,Math.floor(n*1e3)),c=RU,l=0;for(;Date.now()<o;){if(s?.aborted)throw new Error("Login cancelled");let d=o-Date.now(),u=Math.min(Math.ceil(a*c),d);await AU(u,s);let p=await Tf(r.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:AT,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(p&&typeof p=="object"&&typeof p.access_token=="string")return p.access_token;if(p&&typeof p=="object"&&typeof p.error=="string"){let{error:m,error_description:g,interval:h}=p;if(m==="authorization_pending")continue;if(m==="slow_down"){l+=1,a=typeof h=="number"&&h>0?h*1e3:Math.max(1e3,a+5e3),c=PU;continue}let f=g?`: ${g}`:"";throw new Error(`Device flow failed: ${m}${f}`)}}throw l>0?new Error("Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again."):new Error("Device flow timed out")}async function kf(t,e){let i=Sf(e||"github.com"),s=await Tf(i.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${t}`,...OT}});if(!s||typeof s!="object")throw new Error("Invalid Copilot token response");let r=s.token,o=s.expires_at;if(typeof r!="string"||typeof o!="number")throw new Error("Invalid Copilot token response fields");return{refresh:t,access:r,expires:o*1e3-300*1e3,enterpriseUrl:e}}async function LU(t,e,n){let s=`${Cf(t,n)}/models/${e}/policy`;try{return(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...OT,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function WU(t,e,n){let i=pg("github-copilot");await Promise.all(i.map(async s=>{let r=await LU(t,s.id,e);n?.(s.id,r)}))}async function LT(t){let e=await t.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(t.signal?.aborted)throw new Error("Login cancelled");let n=e.trim(),i=wf(e);if(n&&!i)throw new Error("Invalid GitHub Enterprise URL/domain");let s=i||"github.com",r=await EU(s);t.onAuth(r.verification_uri,`Enter code: ${r.user_code}`);let o=await OU(s,r.device_code,r.interval,r.expires_in,t.signal),a=await kf(o,i??void 0);return t.onProgress?.("Enabling models..."),await WU(a.access,i??void 0),a}var Mf={id:"github-copilot",name:"GitHub Copilot",async login(t){return LT({onAuth:(e,n)=>t.onAuth({url:e,instructions:n}),onPrompt:t.onPrompt,onProgress:t.onProgress,signal:t.signal})},async refreshToken(t){let e=t;return kf(e.refresh,e.enterpriseUrl)},getApiKey(t){return t.access},modifyModels(t,e){let n=e,i=n.enterpriseUrl?wf(n.enterpriseUrl)??void 0:void 0,s=Cf(n.access,i);return t.map(r=>r.provider==="github-copilot"?{...r,baseUrl:s}:r)}};var Rf=null,Pf=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(import("node:crypto").then(t=>{Rf=t.randomBytes}),import("node:http").then(t=>{Pf=t}));var UU=process.env.PI_OAUTH_CALLBACK_HOST||"127.0.0.1",_f="app_EMoamEEZ73f0CkXaXp7hrann",FU="https://auth.openai.com/oauth/authorize",WT="https://auth.openai.com/oauth/token",UT="http://localhost:1455/auth/callback",DU="openid profile email offline_access",$U="https://api.openai.com/auth";function BU(){if(!Rf)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");return Rf(16).toString("hex")}function If(t){let e=t.trim();if(!e)return{};try{let n=new URL(e);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(e.includes("#")){let[n,i]=e.split("#",2);return{code:n,state:i}}if(e.includes("code=")){let n=new URLSearchParams(e);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:e}}function NU(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1]??"",i=atob(n);return JSON.parse(i)}catch{return null}}async function jU(t,e,n=UT){let i=await fetch(WT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:_f,code:t,code_verifier:e,redirect_uri:n})});if(!i.ok){let r=await i.text().catch(()=>"");return{type:"failed",status:i.status,message:`OpenAI Codex token exchange failed (${i.status}): ${r||i.statusText}`}}let s=await i.json();return!s.access_token||!s.refresh_token||typeof s.expires_in!="number"?{type:"failed",message:`OpenAI Codex token exchange response missing fields: ${JSON.stringify(s)}`}:{type:"success",access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3}}async function qU(t){try{let e=await fetch(WT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:_f})});if(!e.ok){let i=await e.text().catch(()=>"");return{type:"failed",status:e.status,message:`OpenAI Codex token refresh failed (${e.status}): ${i||e.statusText}`}}let n=await e.json();return!n.access_token||!n.refresh_token||typeof n.expires_in!="number"?{type:"failed",message:`OpenAI Codex token refresh response missing fields: ${JSON.stringify(n)}`}:{type:"success",access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3}}catch(e){return{type:"failed",message:`OpenAI Codex token refresh error: ${e instanceof Error?e.message:String(e)}`}}}async function GU(t="pi"){let{verifier:e,challenge:n}=await Qd(),i=BU(),s=new URL(FU);return s.searchParams.set("response_type","code"),s.searchParams.set("client_id",_f),s.searchParams.set("redirect_uri",UT),s.searchParams.set("scope",DU),s.searchParams.set("code_challenge",n),s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("state",i),s.searchParams.set("id_token_add_organizations","true"),s.searchParams.set("codex_cli_simplified_flow","true"),s.searchParams.set("originator",t),{verifier:e,state:i,url:s.toString()}}function KU(t){if(!Pf)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");let e,n=new Promise(s=>{let r=!1;e=o=>{r||(r=!0,s(o))}}),i=Pf.createServer((s,r)=>{try{let o=new URL(s.url||"","http://localhost");if(o.pathname!=="/auth/callback"){r.statusCode=404,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("Callback route not found."));return}if(o.searchParams.get("state")!==t){r.statusCode=400,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("State mismatch."));return}let a=o.searchParams.get("code");if(!a){r.statusCode=400,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("Missing authorization code."));return}r.statusCode=200,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(Jd("OpenAI authentication completed. You can close this window.")),e?.({code:a})}catch{r.statusCode=500,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("Internal error while processing OAuth callback."))}});return new Promise(s=>{i.listen(1455,UU,()=>{s({close:()=>i.close(),cancelWait:()=>{e?.(null)},waitForCode:()=>n})}).on("error",r=>{e?.(null),s({close:()=>{try{i.close()}catch{}},cancelWait:()=>{},waitForCode:async()=>null})})})}function FT(t){let i=NU(t)?.[$U]?.chatgpt_account_id;return typeof i=="string"&&i.length>0?i:null}async function DT(t){let{verifier:e,state:n,url:i}=await GU(t.originator),s=await KU(n);t.onAuth({url:i,instructions:"A browser window should open. Complete login to finish."});let r;try{if(t.onManualCodeInput){let c,l,d=t.onManualCodeInput().then(p=>{c=p,s.cancelWait()}).catch(p=>{l=p instanceof Error?p:new Error(String(p)),s.cancelWait()}),u=await s.waitForCode();if(l)throw l;if(u?.code)r=u.code;else if(c){let p=If(c);if(p.state&&p.state!==n)throw new Error("State mismatch");r=p.code}if(!r){if(await d,l)throw l;if(c){let p=If(c);if(p.state&&p.state!==n)throw new Error("State mismatch");r=p.code}}}else{let c=await s.waitForCode();c?.code&&(r=c.code)}if(!r){let c=await t.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),l=If(c);if(l.state&&l.state!==n)throw new Error("State mismatch");r=l.code}if(!r)throw new Error("Missing authorization code");let o=await jU(r,e);if(o.type!=="success")throw new Error(o.message);let a=FT(o.access);if(!a)throw new Error("Failed to extract accountId from token");return{access:o.access,refresh:o.refresh,expires:o.expires,accountId:a}}finally{s.close()}}async function $T(t){let e=await qU(t);if(e.type!=="success")throw new Error(e.message);let n=FT(e.access);if(!n)throw new Error("Failed to extract accountId from token");return{access:e.access,refresh:e.refresh,expires:e.expires,accountId:n}}var Ef={id:"openai-codex",name:"ChatGPT Plus/Pro (Codex Subscription)",usesCallbackServer:!0,async login(t){return DT({onAuth:t.onAuth,onPrompt:t.onPrompt,onProgress:t.onProgress,onManualCodeInput:t.onManualCodeInput})},async refreshToken(t){return $T(t.refresh)},getApiKey(t){return t.access}};var HU=[vf,Mf,Ef],zU=new Map(HU.map(t=>[t.id,t]));function Af(){return Array.from(zU.values())}import{createJiti as ime}from"jiti/static";import*as sme from"typebox";import*as rme from"typebox/compile";import*as ome from"typebox/value";var dme=JU(import.meta.url);function Zd(t){return t.toolName==="edit"}function ep(t){return t.toolName==="write"}function fl(t,e){return e.toolName===t}import Lme from"ignore";import{realpathSync as a3}from"node:fs";import{isAbsolute as KT,relative as c3,resolve as Of,sep as HT}from"node:path";function ya(t){try{return a3(t)}catch{return t}}function tp(t){let e=t.trim();return!(e.startsWith("npm:")||e.startsWith("git:")||e.startsWith("github:")||e.startsWith("http:")||e.startsWith("https:")||e.startsWith("ssh:"))}function zT(t,e){return KT(t)?Of(t):Of(e,t)}function np(t,e){let n=Of(e),i=zT(t,n),s=c3(n,i);return s===""||s!==".."&&!s.startsWith(`..${HT}`)&&!KT(s)?s||".":void 0}function VT(t,e){let n=zT(t,e);return(np(n,e)??n).split(HT).join("/")}function JT(t){let e=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let n of e)process.platform==="darwin"?zo("xattr",["-w",n,"1",t],{encoding:"utf-8",stdio:"ignore"}):zo("setfattr",["-n",n,"-v","1",t],{encoding:"utf-8",stdio:"ignore"})}import{existsSync as f3}from"node:fs";import{spawn as b3}from"child_process";import{Type as sp}from"typebox";function u3(t,e){let n=process.platform==="darwin"&&t.toLowerCase()==="alt"?"option":t;return e.capitalize?n.charAt(0).toUpperCase()+n.slice(1):n}function bl(t,e={}){return t.split("/").map(n=>n.split("+").map(i=>u3(i,e)).join("+")).join("/")}function QT(t,e={}){return t.length===0?"":bl(t.join("/"),e)}function he(t){return QT(ve().getKeys(t))}function xl(t){return QT(ve().getKeys(t),{capitalize:!0})}function ce(t,e){return b.fg("dim",he(t))+b.fg("muted",` ${e}`)}function pt(t,e){return b.fg("dim",bl(t))+b.fg("muted",` ${e}`)}function va(t,e,n,i=0){if(!t)return{visualLines:[],skippedCount:0};let r=new A(t,i,0).render(n);if(r.length<=e)return{visualLines:r,skippedCount:0};let o=r.slice(-e),a=r.length-e;return{visualLines:o,skippedCount:a}}import{randomBytes as d3}from"node:crypto";import{createWriteStream as p3}from"node:fs";import{tmpdir as m3}from"node:os";import{join as h3}from"node:path";function g3(t){let e=d3(8).toString("hex");return h3(m3(),`${t}-${e}.log`)}function Lf(t){return Buffer.byteLength(t,"utf-8")}var ip=class{constructor(e={}){this.decoder=new TextDecoder;this.rawChunks=[];this.tailText="";this.tailBytes=0;this.tailStartsAtLineBoundary=!0;this.totalRawBytes=0;this.totalDecodedBytes=0;this.totalLines=1;this.currentLineBytes=0;this.finished=!1;this.maxLines=e.maxLines??2e3,this.maxBytes=e.maxBytes??51200,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=e.tempFilePrefix??"pi-output"}append(e){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=e.length,this.appendDecodedText(this.decoder.decode(e,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(e)):e.length>0&&this.rawChunks.push(e)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(e={}){let n=vr(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),i=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,s=i?n.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,r={...n,truncated:i,truncatedBy:s,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return e.persistIfTruncated&&r.truncated&&this.ensureTempFile(),{content:r.content,truncation:r,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;let e=this.tempFileStream;this.tempFileStream=void 0,await new Promise((n,i)=>{let s=o=>{e.off("finish",r),i(o)},r=()=>{e.off("error",s),n()};e.once("error",s),e.once("finish",r),e.end()})}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(e){if(e.length===0)return;let n=Lf(e);this.totalDecodedBytes+=n,this.tailText+=e,this.tailBytes+=n,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let i=0,s=-1;for(let r=e.indexOf(`
|
|
178
|
+
</html>`}function Jd(t){return kT({title:"Authentication successful",heading:"Authentication successful",message:t})}function di(t,e){return kT({title:"Authentication failed",heading:"Authentication failed",message:t,details:e})}function MT(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function Qd(){let t=new Uint8Array(32);crypto.getRandomValues(t);let e=MT(t),i=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",i),r=MT(new Uint8Array(s));return{verifier:e,challenge:r}}var Yd=null,bf=null,vU=t=>atob(t),yf=vU("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),wU="https://claude.ai/oauth/authorize",xa="https://platform.claude.com/v1/oauth/token",SU=process.env.PI_OAUTH_CALLBACK_HOST||"127.0.0.1",IT=53692,RT="/callback",ba=`http://localhost:${IT}${RT}`,CU="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";async function TU(){if(Yd)return Yd;if(!bf){if(typeof process>"u"||!process.versions?.node&&!process.versions?.bun)throw new Error("Anthropic OAuth is only available in Node.js environments");bf=import("node:http").then(t=>({createServer:t.createServer}))}return Yd=await bf,Yd}function xf(t){let e=t.trim();if(!e)return{};try{let n=new URL(e);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(e.includes("#")){let[n,i]=e.split("#",2);return{code:n,state:i}}if(e.includes("code=")){let n=new URLSearchParams(e);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:e}}function gl(t){if(t instanceof Error){let e=[`${t.name}: ${t.message}`],n=t;return n.code&&e.push(`code=${n.code}`),typeof n.errno<"u"&&e.push(`errno=${String(n.errno)}`),typeof t.cause<"u"&&e.push(`cause=${gl(t.cause)}`),t.stack&&e.push(`stack=${t.stack}`),e.join("; ")}return String(t)}async function kU(t){let{createServer:e}=await TU();return new Promise((n,i)=>{let s,r=new Promise(a=>{let c=!1;s=l=>{c||(c=!0,a(l))}}),o=e((a,c)=>{try{let l=new URL(a.url||"","http://localhost");if(l.pathname!==RT){c.writeHead(404,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("Callback route not found."));return}let d=l.searchParams.get("code"),u=l.searchParams.get("state"),p=l.searchParams.get("error");if(p){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("Anthropic authentication did not complete.",`Error: ${p}`));return}if(!d||!u){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("Missing code or state parameter."));return}if(u!==t){c.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),c.end(di("State mismatch."));return}c.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),c.end(Jd("Anthropic authentication completed. You can close this window.")),s?.({code:d,state:u})}catch{c.writeHead(500,{"Content-Type":"text/plain; charset=utf-8"}),c.end("Internal error")}});o.on("error",a=>{i(a)}),o.listen(IT,SU,()=>{n({server:o,redirectUri:ba,cancelWait:()=>{s?.(null)},waitForCode:()=>r})})})}async function PT(t,e){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(3e4)}),i=await n.text();if(!n.ok)throw new Error(`HTTP request failed. status=${n.status}; url=${t}; body=${i}`);return i}async function MU(t,e,n,i){let s;try{s=await PT(xa,{grant_type:"authorization_code",client_id:yf,code:t,state:e,redirect_uri:i,code_verifier:n})}catch(o){throw new Error(`Token exchange request failed. url=${xa}; redirect_uri=${i}; response_type=authorization_code; details=${gl(o)}`)}let r;try{r=JSON.parse(s)}catch(o){throw new Error(`Token exchange returned invalid JSON. url=${xa}; body=${s}; details=${gl(o)}`)}return{refresh:r.refresh_token,access:r.access_token,expires:Date.now()+r.expires_in*1e3-300*1e3}}async function _T(t){let{verifier:e,challenge:n}=await Qd(),i=await kU(e),s,r,o=ba;try{let a=new URLSearchParams({code:"true",client_id:yf,response_type:"code",redirect_uri:ba,scope:CU,code_challenge:n,code_challenge_method:"S256",state:e});if(t.onAuth({url:`${wU}?${a.toString()}`,instructions:"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."}),t.onManualCodeInput){let c,l,d=t.onManualCodeInput().then(p=>{c=p,i.cancelWait()}).catch(p=>{l=p instanceof Error?p:new Error(String(p)),i.cancelWait()}),u=await i.waitForCode();if(l)throw l;if(u?.code)s=u.code,r=u.state,o=ba;else if(c){let p=xf(c);if(p.state&&p.state!==e)throw new Error("OAuth state mismatch");s=p.code,r=p.state??e}if(!s){if(await d,l)throw l;if(c){let p=xf(c);if(p.state&&p.state!==e)throw new Error("OAuth state mismatch");s=p.code,r=p.state??e}}}else{let c=await i.waitForCode();c?.code&&(s=c.code,r=c.state,o=ba)}if(!s){let c=await t.onPrompt({message:"Paste the authorization code or full redirect URL:",placeholder:ba}),l=xf(c);if(l.state&&l.state!==e)throw new Error("OAuth state mismatch");s=l.code,r=l.state??e}if(!s)throw new Error("Missing authorization code");if(!r)throw new Error("Missing OAuth state");return t.onProgress?.("Exchanging authorization code for tokens..."),MU(s,r,e,o)}finally{i.server.close()}}async function ET(t){let e;try{e=await PT(xa,{grant_type:"refresh_token",client_id:yf,refresh_token:t})}catch(i){throw new Error(`Anthropic token refresh request failed. url=${xa}; details=${gl(i)}`)}let n;try{n=JSON.parse(e)}catch(i){throw new Error(`Anthropic token refresh returned invalid JSON. url=${xa}; body=${e}; details=${gl(i)}`)}return{refresh:n.refresh_token,access:n.access_token,expires:Date.now()+n.expires_in*1e3-300*1e3}}var vf={id:"anthropic",name:"Anthropic (Claude Pro/Max)",usesCallbackServer:!0,async login(t){return _T({onAuth:t.onAuth,onPrompt:t.onPrompt,onProgress:t.onProgress,onManualCodeInput:t.onManualCodeInput})},async refreshToken(t){return ET(t.refresh)},getApiKey(t){return t.access}};In();var IU=t=>atob(t),AT=IU("SXYxLmI1MDdhMDhjODdlY2ZlOTg="),OT={"User-Agent":"GitHubCopilotChat/0.35.0","Editor-Version":"vscode/1.107.0","Editor-Plugin-Version":"copilot-chat/0.35.0","Copilot-Integration-Id":"vscode-chat"},RU=1.2,PU=1.4;function wf(t){let e=t.trim();if(!e)return null;try{return(e.includes("://")?new URL(e):new URL(`https://${e}`)).hostname}catch{return null}}function Sf(t){return{deviceCodeUrl:`https://${t}/login/device/code`,accessTokenUrl:`https://${t}/login/oauth/access_token`,copilotTokenUrl:`https://api.${t}/copilot_internal/v2/token`}}function _U(t){let e=t.match(/proxy-ep=([^;]+)/);return e?`https://${e[1].replace(/^proxy\./,"api.")}`:null}function Cf(t,e){if(t){let n=_U(t);if(n)return n}return e?`https://copilot-api.${e}`:"https://api.individual.githubcopilot.com"}async function Tf(t,e){let n=await fetch(t,e);if(!n.ok){let i=await n.text();throw new Error(`${n.status} ${n.statusText}: ${i}`)}return n.json()}async function EU(t){let e=Sf(t),n=await Tf(e.deviceCodeUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:AT,scope:"read:user"})});if(!n||typeof n!="object")throw new Error("Invalid device code response");let i=n.device_code,s=n.user_code,r=n.verification_uri,o=n.interval,a=n.expires_in;if(typeof i!="string"||typeof s!="string"||typeof r!="string"||typeof o!="number"||typeof a!="number")throw new Error("Invalid device code response fields");return{device_code:i,user_code:s,verification_uri:r,interval:o,expires_in:a}}function AU(t,e){return new Promise((n,i)=>{if(e?.aborted){i(new Error("Login cancelled"));return}let s=setTimeout(n,t);e?.addEventListener("abort",()=>{clearTimeout(s),i(new Error("Login cancelled"))},{once:!0})})}async function OU(t,e,n,i,s){let r=Sf(t),o=Date.now()+i*1e3,a=Math.max(1e3,Math.floor(n*1e3)),c=RU,l=0;for(;Date.now()<o;){if(s?.aborted)throw new Error("Login cancelled");let d=o-Date.now(),u=Math.min(Math.ceil(a*c),d);await AU(u,s);let p=await Tf(r.accessTokenUrl,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"GitHubCopilotChat/0.35.0"},body:new URLSearchParams({client_id:AT,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})});if(p&&typeof p=="object"&&typeof p.access_token=="string")return p.access_token;if(p&&typeof p=="object"&&typeof p.error=="string"){let{error:m,error_description:g,interval:h}=p;if(m==="authorization_pending")continue;if(m==="slow_down"){l+=1,a=typeof h=="number"&&h>0?h*1e3:Math.max(1e3,a+5e3),c=PU;continue}let f=g?`: ${g}`:"";throw new Error(`Device flow failed: ${m}${f}`)}}throw l>0?new Error("Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again."):new Error("Device flow timed out")}async function kf(t,e){let i=Sf(e||"github.com"),s=await Tf(i.copilotTokenUrl,{headers:{Accept:"application/json",Authorization:`Bearer ${t}`,...OT}});if(!s||typeof s!="object")throw new Error("Invalid Copilot token response");let r=s.token,o=s.expires_at;if(typeof r!="string"||typeof o!="number")throw new Error("Invalid Copilot token response fields");return{refresh:t,access:r,expires:o*1e3-300*1e3,enterpriseUrl:e}}async function LU(t,e,n){let s=`${Cf(t,n)}/models/${e}/policy`;try{return(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`,...OT,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"})})).ok}catch{return!1}}async function WU(t,e,n){let i=pg("github-copilot");await Promise.all(i.map(async s=>{let r=await LU(t,s.id,e);n?.(s.id,r)}))}async function LT(t){let e=await t.onPrompt({message:"GitHub Enterprise URL/domain (blank for github.com)",placeholder:"company.ghe.com",allowEmpty:!0});if(t.signal?.aborted)throw new Error("Login cancelled");let n=e.trim(),i=wf(e);if(n&&!i)throw new Error("Invalid GitHub Enterprise URL/domain");let s=i||"github.com",r=await EU(s);t.onAuth(r.verification_uri,`Enter code: ${r.user_code}`);let o=await OU(s,r.device_code,r.interval,r.expires_in,t.signal),a=await kf(o,i??void 0);return t.onProgress?.("Enabling models..."),await WU(a.access,i??void 0),a}var Mf={id:"github-copilot",name:"GitHub Copilot",async login(t){return LT({onAuth:(e,n)=>t.onAuth({url:e,instructions:n}),onPrompt:t.onPrompt,onProgress:t.onProgress,signal:t.signal})},async refreshToken(t){let e=t;return kf(e.refresh,e.enterpriseUrl)},getApiKey(t){return t.access},modifyModels(t,e){let n=e,i=n.enterpriseUrl?wf(n.enterpriseUrl)??void 0:void 0,s=Cf(n.access,i);return t.map(r=>r.provider==="github-copilot"?{...r,baseUrl:s}:r)}};var Rf=null,Pf=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(import("node:crypto").then(t=>{Rf=t.randomBytes}),import("node:http").then(t=>{Pf=t}));var UU=process.env.PI_OAUTH_CALLBACK_HOST||"127.0.0.1",_f="app_EMoamEEZ73f0CkXaXp7hrann",FU="https://auth.openai.com/oauth/authorize",WT="https://auth.openai.com/oauth/token",UT="http://localhost:1455/auth/callback",DU="openid profile email offline_access",$U="https://api.openai.com/auth";function BU(){if(!Rf)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");return Rf(16).toString("hex")}function If(t){let e=t.trim();if(!e)return{};try{let n=new URL(e);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(e.includes("#")){let[n,i]=e.split("#",2);return{code:n,state:i}}if(e.includes("code=")){let n=new URLSearchParams(e);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:e}}function NU(t){try{let e=t.split(".");if(e.length!==3)return null;let n=e[1]??"",i=atob(n);return JSON.parse(i)}catch{return null}}async function jU(t,e,n=UT){let i=await fetch(WT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:_f,code:t,code_verifier:e,redirect_uri:n})});if(!i.ok){let r=await i.text().catch(()=>"");return{type:"failed",status:i.status,message:`OpenAI Codex token exchange failed (${i.status}): ${r||i.statusText}`}}let s=await i.json();return!s.access_token||!s.refresh_token||typeof s.expires_in!="number"?{type:"failed",message:`OpenAI Codex token exchange response missing fields: ${JSON.stringify(s)}`}:{type:"success",access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3}}async function qU(t){try{let e=await fetch(WT,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:_f})});if(!e.ok){let i=await e.text().catch(()=>"");return{type:"failed",status:e.status,message:`OpenAI Codex token refresh failed (${e.status}): ${i||e.statusText}`}}let n=await e.json();return!n.access_token||!n.refresh_token||typeof n.expires_in!="number"?{type:"failed",message:`OpenAI Codex token refresh response missing fields: ${JSON.stringify(n)}`}:{type:"success",access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3}}catch(e){return{type:"failed",message:`OpenAI Codex token refresh error: ${e instanceof Error?e.message:String(e)}`}}}async function GU(t="pi"){let{verifier:e,challenge:n}=await Qd(),i=BU(),s=new URL(FU);return s.searchParams.set("response_type","code"),s.searchParams.set("client_id",_f),s.searchParams.set("redirect_uri",UT),s.searchParams.set("scope",DU),s.searchParams.set("code_challenge",n),s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("state",i),s.searchParams.set("id_token_add_organizations","true"),s.searchParams.set("codex_cli_simplified_flow","true"),s.searchParams.set("originator",t),{verifier:e,state:i,url:s.toString()}}function KU(t){if(!Pf)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");let e,n=new Promise(s=>{let r=!1;e=o=>{r||(r=!0,s(o))}}),i=Pf.createServer((s,r)=>{try{let o=new URL(s.url||"","http://localhost");if(o.pathname!=="/auth/callback"){r.statusCode=404,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("Callback route not found."));return}if(o.searchParams.get("state")!==t){r.statusCode=400,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("State mismatch."));return}let a=o.searchParams.get("code");if(!a){r.statusCode=400,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("Missing authorization code."));return}r.statusCode=200,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(Jd("OpenAI authentication completed. You can close this window.")),e?.({code:a})}catch{r.statusCode=500,r.setHeader("Content-Type","text/html; charset=utf-8"),r.end(di("Internal error while processing OAuth callback."))}});return new Promise(s=>{i.listen(1455,UU,()=>{s({close:()=>i.close(),cancelWait:()=>{e?.(null)},waitForCode:()=>n})}).on("error",r=>{e?.(null),s({close:()=>{try{i.close()}catch{}},cancelWait:()=>{},waitForCode:async()=>null})})})}function FT(t){let i=NU(t)?.[$U]?.chatgpt_account_id;return typeof i=="string"&&i.length>0?i:null}async function DT(t){let{verifier:e,state:n,url:i}=await GU(t.originator),s=await KU(n);t.onAuth({url:i,instructions:"A browser window should open. Complete login to finish."});let r;try{if(t.onManualCodeInput){let c,l,d=t.onManualCodeInput().then(p=>{c=p,s.cancelWait()}).catch(p=>{l=p instanceof Error?p:new Error(String(p)),s.cancelWait()}),u=await s.waitForCode();if(l)throw l;if(u?.code)r=u.code;else if(c){let p=If(c);if(p.state&&p.state!==n)throw new Error("State mismatch");r=p.code}if(!r){if(await d,l)throw l;if(c){let p=If(c);if(p.state&&p.state!==n)throw new Error("State mismatch");r=p.code}}}else{let c=await s.waitForCode();c?.code&&(r=c.code)}if(!r){let c=await t.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),l=If(c);if(l.state&&l.state!==n)throw new Error("State mismatch");r=l.code}if(!r)throw new Error("Missing authorization code");let o=await jU(r,e);if(o.type!=="success")throw new Error(o.message);let a=FT(o.access);if(!a)throw new Error("Failed to extract accountId from token");return{access:o.access,refresh:o.refresh,expires:o.expires,accountId:a}}finally{s.close()}}async function $T(t){let e=await qU(t);if(e.type!=="success")throw new Error(e.message);let n=FT(e.access);if(!n)throw new Error("Failed to extract accountId from token");return{access:e.access,refresh:e.refresh,expires:e.expires,accountId:n}}var Ef={id:"openai-codex",name:"ChatGPT Plus/Pro (Codex Subscription)",usesCallbackServer:!0,async login(t){return DT({onAuth:t.onAuth,onPrompt:t.onPrompt,onProgress:t.onProgress,onManualCodeInput:t.onManualCodeInput})},async refreshToken(t){return $T(t.refresh)},getApiKey(t){return t.access}};var HU=[vf,Mf,Ef],zU=new Map(HU.map(t=>[t.id,t]));function Af(){return Array.from(zU.values())}import{createJiti as ime}from"jiti/static";import*as sme from"typebox";import*as rme from"typebox/compile";import*as ome from"typebox/value";var dme=JU(import.meta.url);function Zd(t){return t.toolName==="edit"}function ep(t){return t.toolName==="write"}function fl(t,e){return e.toolName===t}import Lme from"ignore";import{realpathSync as aF}from"node:fs";import{isAbsolute as KT,relative as cF,resolve as Of,sep as HT}from"node:path";function ya(t){try{return aF(t)}catch{return t}}function tp(t){let e=t.trim();return!(e.startsWith("npm:")||e.startsWith("git:")||e.startsWith("github:")||e.startsWith("http:")||e.startsWith("https:")||e.startsWith("ssh:"))}function zT(t,e){return KT(t)?Of(t):Of(e,t)}function np(t,e){let n=Of(e),i=zT(t,n),s=cF(n,i);return s===""||s!==".."&&!s.startsWith(`..${HT}`)&&!KT(s)?s||".":void 0}function VT(t,e){let n=zT(t,e);return(np(n,e)??n).split(HT).join("/")}function JT(t){let e=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let n of e)process.platform==="darwin"?zo("xattr",["-w",n,"1",t],{encoding:"utf-8",stdio:"ignore"}):zo("setfattr",["-n",n,"-v","1",t],{encoding:"utf-8",stdio:"ignore"})}import{existsSync as fF}from"node:fs";import{spawn as bF}from"child_process";import{Type as sp}from"typebox";function uF(t,e){let n=process.platform==="darwin"&&t.toLowerCase()==="alt"?"option":t;return e.capitalize?n.charAt(0).toUpperCase()+n.slice(1):n}function bl(t,e={}){return t.split("/").map(n=>n.split("+").map(i=>uF(i,e)).join("+")).join("/")}function QT(t,e={}){return t.length===0?"":bl(t.join("/"),e)}function he(t){return QT(ve().getKeys(t))}function xl(t){return QT(ve().getKeys(t),{capitalize:!0})}function ce(t,e){return b.fg("dim",he(t))+b.fg("muted",` ${e}`)}function pt(t,e){return b.fg("dim",bl(t))+b.fg("muted",` ${e}`)}function va(t,e,n,i=0){if(!t)return{visualLines:[],skippedCount:0};let r=new A(t,i,0).render(n);if(r.length<=e)return{visualLines:r,skippedCount:0};let o=r.slice(-e),a=r.length-e;return{visualLines:o,skippedCount:a}}import{randomBytes as dF}from"node:crypto";import{createWriteStream as pF}from"node:fs";import{tmpdir as mF}from"node:os";import{join as hF}from"node:path";function gF(t){let e=dF(8).toString("hex");return hF(mF(),`${t}-${e}.log`)}function Lf(t){return Buffer.byteLength(t,"utf-8")}var ip=class{constructor(e={}){this.decoder=new TextDecoder;this.rawChunks=[];this.tailText="";this.tailBytes=0;this.tailStartsAtLineBoundary=!0;this.totalRawBytes=0;this.totalDecodedBytes=0;this.totalLines=1;this.currentLineBytes=0;this.finished=!1;this.maxLines=e.maxLines??2e3,this.maxBytes=e.maxBytes??51200,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=e.tempFilePrefix??"pi-output"}append(e){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=e.length,this.appendDecodedText(this.decoder.decode(e,{stream:!0})),this.tempFileStream||this.shouldUseTempFile()?(this.ensureTempFile(),this.tempFileStream?.write(e)):e.length>0&&this.rawChunks.push(e)}finish(){this.finished||(this.finished=!0,this.appendDecodedText(this.decoder.decode()),this.shouldUseTempFile()&&this.ensureTempFile())}snapshot(e={}){let n=vr(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),i=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,s=i?n.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,r={...n,truncated:i,truncatedBy:s,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return e.persistIfTruncated&&r.truncated&&this.ensureTempFile(),{content:r.content,truncation:r,fullOutputPath:this.tempFilePath}}async closeTempFile(){if(!this.tempFileStream)return;let e=this.tempFileStream;this.tempFileStream=void 0,await new Promise((n,i)=>{let s=o=>{e.off("finish",r),i(o)},r=()=>{e.off("error",s),n()};e.once("error",s),e.once("finish",r),e.end()})}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(e){if(e.length===0)return;let n=Lf(e);this.totalDecodedBytes+=n,this.tailText+=e,this.tailBytes+=n,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let i=0,s=-1;for(let r=e.indexOf(`
|
|
179
179
|
`);r!==-1;r=e.indexOf(`
|
|
180
180
|
`,r+1))i++,s=r;i===0?this.currentLineBytes+=n:(this.totalLines+=i,this.currentLineBytes=Lf(e.slice(s+1)))}trimTail(){let e=Buffer.from(this.tailText,"utf-8");if(e.length<=this.maxRollingBytes){this.tailBytes=e.length;return}let n=e.length-this.maxRollingBytes;for(;n<e.length&&(e[n]&192)===128;)n++;this.tailStartsAtLineBoundary=n===0?this.tailStartsAtLineBoundary:e[n-1]===10,this.tailText=e.subarray(n).toString("utf-8"),this.tailBytes=Lf(this.tailText)}getSnapshotText(){if(this.tailStartsAtLineBoundary)return this.tailText;let e=this.tailText.indexOf(`
|
|
181
|
-
`);return e===-1?this.tailText:this.tailText.slice(e+1)}shouldUseTempFile(){return this.totalRawBytes>this.maxBytes||this.totalDecodedBytes>this.maxBytes||this.totalLines>this.maxLines}ensureTempFile(){if(!this.tempFilePath){this.tempFilePath=
|
|
181
|
+
`);return e===-1?this.tailText:this.tailText.slice(e+1)}shouldUseTempFile(){return this.totalRawBytes>this.maxBytes||this.totalDecodedBytes>this.maxBytes||this.totalLines>this.maxLines}ensureTempFile(){if(!this.tempFilePath){this.tempFilePath=gF(this.tempFilePrefix),this.tempFileStream=pF(this.tempFilePath);for(let e of this.rawChunks)this.tempFileStream.write(e);this.rawChunks=[]}}};import*as YT from"node:os";function An(t){if(typeof t!="string")return"";let e=YT.homedir();return t.startsWith(e)?`~${t.slice(e.length)}`:t}function Xe(t){return typeof t=="string"?t:t==null?"":null}function $i(t){return t.replace(/\t/g," ")}function yl(t){return t.replace(/\r/g,"")}function On(t,e){if(!t)return"";let n=t.content.filter(o=>o.type==="text"),i=t.content.filter(o=>o.type==="image"),s=n.map(o=>uf(pl(o.text||"")).replace(/\r/g,"")).join(`
|
|
182
182
|
`),r=dt();if(i.length>0&&(!r.images||!e)){let o=i.map(a=>{let c=a.mimeType??"image/unknown",l=a.data&&a.mimeType?il(a.data,a.mimeType)??void 0:void 0;return ra(c,l)}).join(`
|
|
183
183
|
`);s=s?`${s}
|
|
184
|
-
${o}`:o}return s}function Xt(t){return t.fg("error","[invalid arg]")}var
|
|
185
|
-
Cannot execute bash commands.`));return}let u=
|
|
184
|
+
${o}`:o}return s}function Xt(t){return t.fg("error","[invalid arg]")}var xF=sp.Object({command:sp.String({description:"Bash command to execute"}),timeout:sp.Optional(sp.Number({description:"Timeout in seconds (optional, no default timeout)"}))});function rp(t){return{exec:(e,n,{onData:i,signal:s,timeout:r,env:o})=>new Promise((a,c)=>{let{shell:l,args:d}=jd(t?.shellPath);if(!fF(n)){c(new Error(`Working directory does not exist: ${n}
|
|
185
|
+
Cannot execute bash commands.`));return}let u=bF(l,[...d,e],{cwd:n,detached:process.platform!=="win32",env:o??lf(),stdio:["ignore","pipe","pipe"],windowsHide:!0});u.pid&&yT(u.pid);let p=!1,m;r!==void 0&&r>0&&(m=setTimeout(()=>{p=!0,u.pid&&qd(u.pid)},r*1e3)),u.stdout?.on("data",i),u.stderr?.on("data",i);let g=()=>{u.pid&&qd(u.pid)};s&&(s.aborted?g():s.addEventListener("abort",g,{once:!0})),eg(u).then(h=>{if(u.pid&&df(u.pid),m&&clearTimeout(m),s&&s.removeEventListener("abort",g),s?.aborted){c(new Error("aborted"));return}if(p){c(new Error(`timeout:${r}`));return}a({exitCode:h})}).catch(h=>{u.pid&&df(u.pid),m&&clearTimeout(m),s&&s.removeEventListener("abort",g),c(h)})})}}function yF(t,e,n){let i={command:t,cwd:e,env:{...lf()}};return n?n(i):i}var vF=5,wF=100,Wf=class extends K{constructor(){super(...arguments);this.state={cachedWidth:void 0,cachedLines:void 0,cachedSkipped:void 0}}};function SF(t){return`${(t/1e3).toFixed(1)}s`}function CF(t){let e=Xe(t?.command),n=t?.timeout,i=n?b.fg("muted",` (timeout ${n}s)`):"",s=e===null?Xt(b):e||b.fg("toolOutput","...");return b.fg("toolTitle",b.bold(`$ ${s}`))+i}function TF(t,e,n,i,s,r){let o=t.state;t.clear();let a=On(e,i).trim();if(a){let d=a.split(`
|
|
186
186
|
`).map(u=>b.fg("toolOutput",u)).join(`
|
|
187
187
|
`);n.expanded?t.addChild(new A(`
|
|
188
|
-
${d}`,0,0)):t.addChild({render:u=>{if(o.cachedLines===void 0||o.cachedWidth!==u){let p=va(d,
|
|
188
|
+
${d}`,0,0)):t.addChild({render:u=>{if(o.cachedLines===void 0||o.cachedWidth!==u){let p=va(d,vF,u);o.cachedLines=p.visualLines,o.cachedSkipped=p.skippedCount,o.cachedWidth=u}if(o.cachedSkipped&&o.cachedSkipped>0){let p=b.fg("muted",`... (${o.cachedSkipped} earlier lines,`)+` ${ce("app.tools.expand","to expand")})`;return["",X(p,u,"..."),...o.cachedLines??[]]}return["",...o.cachedLines??[]]},invalidate:()=>{o.cachedWidth=void 0,o.cachedLines=void 0,o.cachedSkipped=void 0}})}let c=e.details?.truncation,l=e.details?.fullOutputPath;if(c?.truncated||l){let d=[];l&&d.push(`Full output: ${l}`),c?.truncated&&(c.truncatedBy==="lines"?d.push(`Truncated: showing ${c.outputLines} of ${c.totalLines} lines`):d.push(`Truncated: ${c.outputLines} lines shown (${Ye(c.maxBytes??51200)} limit)`)),t.addChild(new A(`
|
|
189
189
|
${b.fg("warning",`[${d.join(". ")}]`)}`,0,0))}if(s!==void 0){let d=n.isPartial?"Elapsed":"Took",u=r??Date.now();t.addChild(new A(`
|
|
190
|
-
${b.fg("muted",`${d} ${
|
|
191
|
-
${o}`:o,p=
|
|
190
|
+
${b.fg("muted",`${d} ${SF(u-s)}`)}`,0,0))}}function op(t,e){let n=e?.operations??rp({shellPath:e?.shellPath}),i=e?.commandPrefix,s=e?.spawnHook;return{name:"bash",label:"bash",description:`Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${2e3} lines or ${51200/1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,promptSnippet:"Execute bash commands (ls, grep, find, etc.)",parameters:xF,async execute(r,{command:o,timeout:a},c,l,d){let u=i?`${i}
|
|
191
|
+
${o}`:o,p=yF(u,t,s),m=new ip({tempFilePrefix:"pi-bash"}),g,h=!1,f=0,x=()=>{if(!l||!h)return;h=!1,f=Date.now();let E=m.snapshot({persistIfTruncated:!0});l({content:[{type:"text",text:E.content||""}],details:{truncation:E.truncation.truncated?E.truncation:void 0,fullOutputPath:E.fullOutputPath}})},y=()=>{g&&(clearTimeout(g),g=void 0)},w=()=>{if(!l)return;h=!0;let E=wF-(Date.now()-f);if(E<=0){y(),x();return}g??=setTimeout(()=>{g=void 0,x()},E)};l&&l({content:[],details:void 0});let P=E=>{m.append(E),w()},_=async()=>{m.finish(),y(),x();let E=m.snapshot({persistIfTruncated:!0});return await m.closeTempFile(),E},R=(E,W="(no output)")=>{let M=E.truncation,I=E.content||W,O;if(M.truncated){O={truncation:M,fullOutputPath:E.fullOutputPath};let F=M.totalLines-M.outputLines+1,N=M.totalLines;if(M.lastLinePartial){let H=Ye(m.getLastLineBytes());I+=`
|
|
192
192
|
|
|
193
193
|
[Showing last ${Ye(M.outputBytes)} of line ${N} (line is ${H}). Full output: ${E.fullOutputPath}]`}else M.truncatedBy==="lines"?I+=`
|
|
194
194
|
|
|
@@ -196,9 +196,9 @@ ${o}`:o,p=y3(u,t,s),m=new ip({tempFilePrefix:"pi-bash"}),g,h=!1,f=0,x=()=>{if(!l
|
|
|
196
196
|
|
|
197
197
|
[Showing lines ${F}-${N} of ${M.totalLines} (${Ye(51200)} limit). Full output: ${E.fullOutputPath}]`}return{text:I,details:O}},L=(E,W)=>`${E?`${E}
|
|
198
198
|
|
|
199
|
-
`:""}${W}`;try{let E;try{E=(await n.exec(p.command,p.cwd,{onData:P,signal:c,timeout:a,env:p.env})).exitCode}catch(O){let F=await _(),{text:N}=R(F,"");if(O instanceof Error&&O.message==="aborted")throw new Error(L(N,"Command aborted"));if(O instanceof Error&&O.message.startsWith("timeout:")){let H=O.message.split(":")[1];throw new Error(L(N,`Command timed out after ${H} seconds`))}throw O}let W=await _(),{text:M,details:I}=R(W);if(E!==0&&E!==null)throw new Error(L(M,`Command exited with code ${E}`));return{content:[{type:"text",text:M}],details:I}}finally{y()}},renderCall(r,o,a){let c=a.state;a.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);let l=a.lastComponent??new A("",0,0);return l.setText(
|
|
200
|
-
`),i=[],s=0;for(;s<n.length;){let r=n[s],o=Uf(r);if(!o){i.push(b.fg("toolDiffContext",r)),s++;continue}if(o.prefix==="-"){let a=[];for(;s<n.length;){let l=Uf(n[s]);if(!l||l.prefix!=="-")break;a.push({lineNum:l.lineNum,content:l.content}),s++}let c=[];for(;s<n.length;){let l=Uf(n[s]);if(!l||l.prefix!=="+")break;c.push({lineNum:l.lineNum,content:l.content}),s++}if(a.length===1&&c.length===1){let l=a[0],d=c[0],{removedLine:u,addedLine:p}=
|
|
201
|
-
`)}import*as tk from"diff";import{constants as
|
|
199
|
+
`:""}${W}`;try{let E;try{E=(await n.exec(p.command,p.cwd,{onData:P,signal:c,timeout:a,env:p.env})).exitCode}catch(O){let F=await _(),{text:N}=R(F,"");if(O instanceof Error&&O.message==="aborted")throw new Error(L(N,"Command aborted"));if(O instanceof Error&&O.message.startsWith("timeout:")){let H=O.message.split(":")[1];throw new Error(L(N,`Command timed out after ${H} seconds`))}throw O}let W=await _(),{text:M,details:I}=R(W);if(E!==0&&E!==null)throw new Error(L(M,`Command exited with code ${E}`));return{content:[{type:"text",text:M}],details:I}}finally{y()}},renderCall(r,o,a){let c=a.state;a.executionStarted&&c.startedAt===void 0&&(c.startedAt=Date.now(),c.endedAt=void 0);let l=a.lastComponent??new A("",0,0);return l.setText(CF(r)),l},renderResult(r,o,a,c){let l=c.state;l.startedAt!==void 0&&o.isPartial&&!l.interval&&(l.interval=setInterval(()=>c.invalidate(),1e3)),(!o.isPartial||c.isError)&&(l.endedAt??=Date.now(),l.interval&&(clearInterval(l.interval),l.interval=void 0));let d=c.lastComponent??new Wf;return TF(d,r,o,c.showImages,l.startedAt,l.endedAt),d.invalidate(),d}}}import{constants as rk}from"fs";import{access as VF,readFile as JF,writeFile as QF}from"fs/promises";import{Type as Sa}from"typebox";import*as XT from"diff";function Uf(t){let e=t.match(/^([+-\s])(\s*\d*)\s(.*)$/);return e?{prefix:e[1],lineNum:e[2],content:e[3]}:null}function wa(t){return t.replace(/\t/g," ")}function kF(t,e){let n=XT.diffWords(t,e),i="",s="",r=!0,o=!0;for(let a of n)if(a.removed){let c=a.value;if(r){let l=c.match(/^(\s*)/)?.[1]||"";c=c.slice(l.length),i+=l,r=!1}c&&(i+=b.inverse(c))}else if(a.added){let c=a.value;if(o){let l=c.match(/^(\s*)/)?.[1]||"";c=c.slice(l.length),s+=l,o=!1}c&&(s+=b.inverse(c))}else i+=a.value,s+=a.value;return{removedLine:i,addedLine:s}}function vl(t,e={}){let n=t.split(`
|
|
200
|
+
`),i=[],s=0;for(;s<n.length;){let r=n[s],o=Uf(r);if(!o){i.push(b.fg("toolDiffContext",r)),s++;continue}if(o.prefix==="-"){let a=[];for(;s<n.length;){let l=Uf(n[s]);if(!l||l.prefix!=="-")break;a.push({lineNum:l.lineNum,content:l.content}),s++}let c=[];for(;s<n.length;){let l=Uf(n[s]);if(!l||l.prefix!=="+")break;c.push({lineNum:l.lineNum,content:l.content}),s++}if(a.length===1&&c.length===1){let l=a[0],d=c[0],{removedLine:u,addedLine:p}=kF(wa(l.content),wa(d.content));i.push(b.fg("toolDiffRemoved",`-${l.lineNum} ${u}`)),i.push(b.fg("toolDiffAdded",`+${d.lineNum} ${p}`))}else{for(let l of a)i.push(b.fg("toolDiffRemoved",`-${l.lineNum} ${wa(l.content)}`));for(let l of c)i.push(b.fg("toolDiffAdded",`+${l.lineNum} ${wa(l.content)}`))}}else o.prefix==="+"?(i.push(b.fg("toolDiffAdded",`+${o.lineNum} ${wa(o.content)}`)),s++):(i.push(b.fg("toolDiffContext",` ${o.lineNum} ${wa(o.content)}`)),s++)}return i.join(`
|
|
201
|
+
`)}import*as tk from"diff";import{constants as FF}from"fs";import{access as DF,readFile as $F}from"fs/promises";import{accessSync as MF,constants as IF}from"node:fs";import*as Ff from"node:os";import{isAbsolute as RF,resolve as PF}from"node:path";var _F=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g,EF="\u202F";function AF(t){return t.replace(_F," ")}function OF(t){return t.replace(/ (AM|PM)\./gi,`${EF}$1.`)}function LF(t){return t.normalize("NFD")}function ZT(t){return t.replace(/'/g,"\u2019")}function wl(t){try{return MF(t,IF.F_OK),!0}catch{return!1}}function WF(t){return t.startsWith("@")?t.slice(1):t}function UF(t){let e=AF(WF(t));return e==="~"?Ff.homedir():e.startsWith("~/")?Ff.homedir()+e.slice(1):e}function yn(t,e){let n=UF(t);return RF(n)?n:PF(e,n)}function ap(t,e){let n=yn(t,e);if(wl(n))return n;let i=OF(n);if(i!==n&&wl(i))return i;let s=LF(n);if(s!==n&&wl(s))return s;let r=ZT(n);if(r!==n&&wl(r))return r;let o=ZT(s);return o!==n&&wl(o)?o:n}function nk(t){let e=t.indexOf(`\r
|
|
202
202
|
`),n=t.indexOf(`
|
|
203
203
|
`);return n===-1||e===-1?`
|
|
204
204
|
`:e<n?`\r
|
|
@@ -209,44 +209,44 @@ ${o}`:o,p=y3(u,t,s),m=new ip({tempFilePrefix:"pi-bash"}),g,h=!1,f=0,x=()=>{if(!l
|
|
|
209
209
|
`?t.replace(/\n/g,`\r
|
|
210
210
|
`):t}function Cl(t){return t.normalize("NFKC").split(`
|
|
211
211
|
`).map(e=>e.trimEnd()).join(`
|
|
212
|
-
`).replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function ek(t,e){let n=t.indexOf(e);if(n!==-1)return{found:!0,index:n,matchLength:e.length,usedFuzzyMatch:!1,contentForReplacement:t};let i=Cl(t),s=Cl(e),r=i.indexOf(s);return r===-1?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:t}:{found:!0,index:r,matchLength:s.length,usedFuzzyMatch:!0,contentForReplacement:i}}function Df(t){return t.startsWith("\uFEFF")?{bom:"\uFEFF",text:t.slice(1)}:{bom:"",text:t}}function
|
|
212
|
+
`).replace(/[\u2018\u2019\u201A\u201B]/g,"'").replace(/[\u201C\u201D\u201E\u201F]/g,'"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function ek(t,e){let n=t.indexOf(e);if(n!==-1)return{found:!0,index:n,matchLength:e.length,usedFuzzyMatch:!1,contentForReplacement:t};let i=Cl(t),s=Cl(e),r=i.indexOf(s);return r===-1?{found:!1,index:-1,matchLength:0,usedFuzzyMatch:!1,contentForReplacement:t}:{found:!0,index:r,matchLength:s.length,usedFuzzyMatch:!0,contentForReplacement:i}}function Df(t){return t.startsWith("\uFEFF")?{bom:"\uFEFF",text:t.slice(1)}:{bom:"",text:t}}function BF(t,e){let n=Cl(t),i=Cl(e);return n.split(i).length-1}function NF(t,e,n){return n===1?new Error(`Could not find the exact text in ${t}. The old text must match exactly including all whitespace and newlines.`):new Error(`Could not find edits[${e}] in ${t}. The oldText must match exactly including all whitespace and newlines.`)}function jF(t,e,n,i){return n===1?new Error(`Found ${i} occurrences of the text in ${t}. The text must be unique. Please provide more context to make it unique.`):new Error(`Found ${i} occurrences of edits[${e}] in ${t}. Each oldText must be unique. Please provide more context to make it unique.`)}function qF(t,e,n){return n===1?new Error(`oldText must not be empty in ${t}.`):new Error(`edits[${e}].oldText must not be empty in ${t}.`)}function GF(t,e){return e===1?new Error(`No changes made to ${t}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`):new Error(`No changes made to ${t}. The replacements produced identical content.`)}function $f(t,e,n){let i=e.map(c=>({oldText:Sl(c.oldText),newText:Sl(c.newText)}));for(let c=0;c<i.length;c++)if(i[c].oldText.length===0)throw qF(n,c,i.length);let r=i.map(c=>ek(t,c.oldText)).some(c=>c.usedFuzzyMatch)?Cl(t):t,o=[];for(let c=0;c<i.length;c++){let l=i[c],d=ek(r,l.oldText);if(!d.found)throw NF(n,c,i.length);let u=BF(r,l.oldText);if(u>1)throw jF(n,c,i.length,u);o.push({editIndex:c,matchIndex:d.index,matchLength:d.matchLength,newText:l.newText})}o.sort((c,l)=>c.matchIndex-l.matchIndex);for(let c=1;c<o.length;c++){let l=o[c-1],d=o[c];if(l.matchIndex+l.matchLength>d.matchIndex)throw new Error(`edits[${l.editIndex}] and edits[${d.editIndex}] overlap in ${n}. Merge them into one edit or target disjoint regions.`)}let a=r;for(let c=o.length-1;c>=0;c--){let l=o[c];a=a.substring(0,l.matchIndex)+l.newText+a.substring(l.matchIndex+l.matchLength)}if(r===a)throw GF(n,i.length);return{baseContent:r,newContent:a}}function Bf(t,e,n=4){let i=tk.diffLines(t,e),s=[],r=t.split(`
|
|
213
213
|
`),o=e.split(`
|
|
214
214
|
`),a=Math.max(r.length,o.length),c=String(a).length,l=1,d=1,u=!1,p;for(let m=0;m<i.length;m++){let g=i[m],h=g.value.split(`
|
|
215
215
|
`);if(h[h.length-1]===""&&h.pop(),g.added||g.removed){p===void 0&&(p=d);for(let f of h)if(g.added){let x=String(d).padStart(c," ");s.push(`+${x} ${f}`),d++}else{let x=String(l).padStart(c," ");s.push(`-${x} ${f}`),l++}u=!0}else{let f=m<i.length-1&&(i[m+1].added||i[m+1].removed),x=u,y=f;if(x&&y)if(h.length<=n*2)for(let w of h){let P=String(l).padStart(c," ");s.push(` ${P} ${w}`),l++,d++}else{let w=h.slice(0,n),P=h.slice(h.length-n),_=h.length-w.length-P.length;for(let R of w){let L=String(l).padStart(c," ");s.push(` ${L} ${R}`),l++,d++}s.push(` ${"".padStart(c," ")} ...`),l+=_,d+=_;for(let R of P){let L=String(l).padStart(c," ");s.push(` ${L} ${R}`),l++,d++}}else if(x){let w=h.slice(0,n),P=h.length-w.length;for(let _ of w){let R=String(l).padStart(c," ");s.push(` ${R} ${_}`),l++,d++}P>0&&(s.push(` ${"".padStart(c," ")} ...`),l+=P,d+=P)}else if(y){let w=Math.max(0,h.length-n);w>0&&(s.push(` ${"".padStart(c," ")} ...`),l+=w,d+=w);for(let P of h.slice(w)){let _=String(l).padStart(c," ");s.push(` ${_} ${P}`),l++,d++}}else l+=h.length,d+=h.length;u=!1}}return{diff:s.join(`
|
|
216
|
-
`),firstChangedLine:p}}async function sk(t,e,n){let i=yn(t,n);try{try{await
|
|
217
|
-
`);return!l||l===a?void 0:i.fg("error",l)}let c=n.details?.diff;if(c&&c!==o)return vl(c,{filePath:r??void 0})}function
|
|
216
|
+
`),firstChangedLine:p}}async function sk(t,e,n){let i=yn(t,n);try{try{await DF(i,FF.R_OK)}catch(l){let d=l instanceof Error&&"code"in l?`Error code: ${l.code}`:String(l);return{error:`Could not edit file: ${t}. ${d}.`}}let s=await $F(i,"utf-8"),{text:r}=Df(s),o=Sl(r),{baseContent:a,newContent:c}=$f(o,e,t);return Bf(a,c)}catch(s){return{error:s instanceof Error?s.message:String(s)}}}import{realpathSync as KF}from"node:fs";import{resolve as HF}from"node:path";var cp=new Map;function zF(t){let e=HF(t);try{return KF.native(e)}catch{return e}}async function Cr(t,e){let n=zF(t),i=cp.get(n)??Promise.resolve(),s,r=new Promise(a=>{s=a}),o=i.then(()=>r);cp.set(n,o),await i;try{return await e()}finally{s(),cp.get(n)===o&&cp.delete(n)}}var YF=Sa.Object({oldText:Sa.String({description:"Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."}),newText:Sa.String({description:"Replacement text for this targeted edit."})},{additionalProperties:!1}),XF=Sa.Object({path:Sa.String({description:"Path to the file to edit (relative or absolute)"}),edits:Sa.Array(YF,{description:"One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."})},{additionalProperties:!1}),ZF={readFile:t=>JF(t),writeFile:(t,e)=>QF(t,e,"utf-8"),access:t=>VF(t,rk.R_OK|rk.W_OK)};function e3(t){if(!t||typeof t!="object")return t;let e=t;if(typeof e.edits=="string")try{let a=JSON.parse(e.edits);Array.isArray(a)&&(e.edits=a)}catch{}let n=e;if(typeof n.oldText!="string"||typeof n.newText!="string")return e;let i=Array.isArray(n.edits)?[...n.edits]:[];i.push({oldText:n.oldText,newText:n.newText});let{oldText:s,newText:r,...o}=n;return{...o,edits:i}}function t3(t){if(!Array.isArray(t.edits)||t.edits.length===0)throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");return{path:t.path,edits:t.edits}}function n3(){return Object.assign(new ut(1,1,t=>t),{preview:void 0,previewArgsKey:void 0,previewPending:!1,settledError:!1})}function i3(t,e){if(e instanceof ut){let i=e;return t.callComponent=i,i}if(t.callComponent)return t.callComponent;let n=n3();return t.callComponent=n,n}function ok(t){if(!t)return null;let e=typeof t.path=="string"?t.path:typeof t.file_path=="string"?t.file_path:null;return e?Array.isArray(t.edits)&&t.edits.length>0&&t.edits.every(n=>typeof n?.oldText=="string"&&typeof n?.newText=="string")?{path:e,edits:t.edits}:typeof t.oldText=="string"&&typeof t.newText=="string"?{path:e,edits:[{oldText:t.oldText,newText:t.newText}]}:null:null}function s3(t,e){let n=Xt(e),i=Xe(t?.file_path??t?.path),s=i!==null?An(i):null,r=s===null?n:s?e.fg("accent",s):e.fg("toolOutput","...");return`${e.fg("toolTitle",e.bold("edit"))} ${r}`}function r3(t,e,n,i,s){let r=Xe(t?.file_path??t?.path),o=e&&!("error"in e)?e.diff:void 0,a=e&&"error"in e?e.error:void 0;if(s){let l=n.content.filter(d=>d.type==="text").map(d=>d.text||"").join(`
|
|
217
|
+
`);return!l||l===a?void 0:i.fg("error",l)}let c=n.details?.diff;if(c&&c!==o)return vl(c,{filePath:r??void 0})}function o3(t,e,n){return t?"error"in t?i=>n.bg("toolErrorBg",i):i=>n.bg("toolSuccessBg",i):e?i=>n.bg("toolErrorBg",i):i=>n.bg("toolPendingBg",i)}function ak(t,e,n){if(t.setBgFn(o3(t.preview,t.settledError,n)),t.clear(),t.addChild(new A(s3(e,n),0,0)),!t.preview)return t;let i="error"in t.preview?n.fg("error",t.preview.error):vl(t.preview.diff);return t.addChild(new U(1)),t.addChild(new A(i,0,0)),t}function ck(t,e,n){let i=t.preview,s=i===void 0||("error"in i&&"error"in e?i.error!==e.error:"error"in i!="error"in e)||!("error"in i)&&!("error"in e)&&(i.diff!==e.diff||i.firstChangedLine!==e.firstChangedLine);return t.preview=e,t.previewArgsKey=n,t.previewPending=!1,s}function lp(t,e){let n=e?.operations??ZF;return{name:"edit",label:"edit",description:"Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",promptSnippet:"Make precise file edits with exact text replacement, including multiple disjoint edits in one call",promptGuidelines:["Use edit for precise changes (edits[].oldText must match exactly)","When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls","Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.","Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions."],parameters:XF,renderShell:"self",prepareArguments:e3,async execute(i,s,r,o,a){let{path:c,edits:l}=t3(s),d=yn(c,t);return Cr(d,()=>new Promise((u,p)=>{if(r?.aborted){p(new Error("Operation aborted"));return}let m=!1,g=()=>{m=!0,p(new Error("Operation aborted"))};r&&r.addEventListener("abort",g,{once:!0}),(async()=>{try{try{await n.access(d)}catch(W){let M=W instanceof Error&&"code"in W?`Error code: ${W.code}`:String(W);r&&r.removeEventListener("abort",g),p(new Error(`Could not edit file: ${c}. ${M}.`));return}if(m)return;let f=(await n.readFile(d)).toString("utf-8");if(m)return;let{bom:x,text:y}=Df(f),w=nk(y),P=Sl(y),{baseContent:_,newContent:R}=$f(P,l,c);if(m)return;let L=x+ik(R,w);if(await n.writeFile(d,L),m)return;r&&r.removeEventListener("abort",g);let E=Bf(_,R);u({content:[{type:"text",text:`Successfully replaced ${l.length} block(s) in ${c}.`}],details:{diff:E.diff,firstChangedLine:E.firstChangedLine}})}catch(h){r&&r.removeEventListener("abort",g),m||p(h instanceof Error?h:new Error(String(h)))}})()}))},renderCall(i,s,r){let o=i3(r.state,r.lastComponent),a=ok(i),c=a?JSON.stringify({path:a.path,edits:a.edits}):void 0;if(o.previewArgsKey!==c&&(o.preview=void 0,o.previewArgsKey=c,o.previewPending=!1,o.settledError=!1),r.argsComplete&&a&&!o.preview&&!o.previewPending){o.previewPending=!0;let l=c;sk(a.path,a.edits,r.cwd).then(d=>{o.previewArgsKey===l&&(ck(o,d,l),r.invalidate())})}return ak(o,i,s)},renderResult(i,s,r,o){let a=o.state.callComponent,c=ok(o.args),l=c?JSON.stringify({path:c.path,edits:c.edits}):void 0,d=i,u=o.isError?void 0:d.details?.diff,p=!1;a&&(typeof u=="string"&&(p=ck(a,{diff:u,firstChangedLine:d.details?.firstChangedLine},l)||p),a.settledError!==o.isError&&(a.settledError=o.isError,p=!0),p&&ak(a,o.args,r));let m=r3(o.args,a?.preview,d,r,o.isError),g=o.lastComponent??new K;return g.clear(),m&&(g.addChild(new U(1)),g.addChild(new A(m,1,0))),g}}}import{createInterface as R3}from"node:readline";import{spawn as P3}from"child_process";import{existsSync as _3}from"fs";import Gf from"path";import{Type as Ca}from"typebox";import Tl from"chalk";import{spawnSync as dk}from"child_process";import{chmodSync as a3,createWriteStream as c3,existsSync as Nf,mkdirSync as lk,readdirSync as l3,renameSync as u3,rmSync as uk}from"fs";import{arch as d3,platform as up}from"os";import{join as Bi}from"path";import{Readable as p3}from"stream";import{pipeline as m3}from"stream/promises";var kl=Bc(),h3=1e4,g3=12e4;function f3(){let t=process.env.PI_OFFLINE;return t?t==="1"||t.toLowerCase()==="true"||t.toLowerCase()==="yes":!1}var jf={fd:{name:"fd",repo:"sharkdp/fd",binaryName:"fd",systemBinaryNames:["fd","fdfind"],tagPrefix:"v",getAssetName:(t,e,n)=>e==="darwin"?`fd-v${t}-${n==="arm64"?"aarch64":"x86_64"}-apple-darwin.tar.gz`:e==="linux"?`fd-v${t}-${n==="arm64"?"aarch64":"x86_64"}-unknown-linux-gnu.tar.gz`:e==="win32"?`fd-v${t}-${n==="arm64"?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null},rg:{name:"ripgrep",repo:"BurntSushi/ripgrep",binaryName:"rg",tagPrefix:"",getAssetName:(t,e,n)=>e==="darwin"?`ripgrep-${t}-${n==="arm64"?"aarch64":"x86_64"}-apple-darwin.tar.gz`:e==="linux"?n==="arm64"?`ripgrep-${t}-aarch64-unknown-linux-gnu.tar.gz`:`ripgrep-${t}-x86_64-unknown-linux-musl.tar.gz`:e==="win32"?`ripgrep-${t}-${n==="arm64"?"aarch64":"x86_64"}-pc-windows-msvc.zip`:null}};function b3(t){try{let e=dk(t,["--version"],{stdio:"pipe"});return e.error===void 0||e.error===null}catch{return!1}}function x3(t){let e=jf[t];if(!e)return null;let n=Bi(kl,e.binaryName+(up()==="win32"?".exe":""));if(Nf(n))return n;let i=e.systemBinaryNames??[e.binaryName];for(let s of i)if(b3(s))return s;return null}async function y3(t){let e=await fetch(`https://api.github.com/repos/${t}/releases/latest`,{headers:{"User-Agent":`${Ot}-coding-agent`},signal:AbortSignal.timeout(h3)});if(!e.ok)throw new Error(`GitHub API error: ${e.status}`);return(await e.json()).tag_name.replace(/^v/,"")}async function v3(t,e){let n=await fetch(t,{signal:AbortSignal.timeout(g3)});if(!n.ok)throw new Error(`Failed to download: ${n.status}`);if(!n.body)throw new Error("No response body");let i=c3(e);await m3(p3.fromWeb(n.body),i)}function w3(t,e){let n=[t];for(;n.length>0;){let i=n.pop();if(!i)continue;let s=l3(i,{withFileTypes:!0});for(let r of s){let o=Bi(i,r.name);if(r.isFile()&&r.name===e)return o;r.isDirectory()&&n.push(o)}}return null}function S3(t){if(t.error?.message)return t.error.message;let e=t.stderr?.toString().trim();if(e)return e;let n=t.stdout?.toString().trim();return n||`exit status ${t.status??"unknown"}`}function Ml(t,e){let n=dk(t,e,{stdio:"pipe"});return!n.error&&n.status===0?null:`${t}: ${S3(n)}`}function C3(t,e,n){let i=Ml("tar",["xzf",t,"-C",e]);if(i)throw new Error(`Failed to extract ${n}: ${i}`)}function T3(){let t=process.env.SystemRoot??process.env.WINDIR;if(t){let e=Bi(t,"System32","tar.exe");if(Nf(e))return e}return"tar.exe"}function k3(t,e,n){let i=[];if(up()==="win32"){let s=Ml(T3(),["xf",t,"-C",e]);if(!s)return;i.push(s);let o=Ml("powershell.exe",["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command","& { param($archive, $destination) $ErrorActionPreference = 'Stop'; Expand-Archive -LiteralPath $archive -DestinationPath $destination -Force }",t,e]);if(!o)return;i.push(o)}else{let s=Ml("unzip",["-q",t,"-d",e]);if(!s)return;i.push(s);let r=Ml("tar",["xf",t,"-C",e]);if(!r)return;i.push(r)}throw new Error(`Failed to extract ${n}: ${i.join("; ")}`)}async function M3(t){let e=jf[t];if(!e)throw new Error(`Unknown tool: ${t}`);let n=up(),i=d3(),s=await y3(e.repo);t==="fd"&&n==="darwin"&&i==="x64"&&(s="10.3.0");let r=e.getAssetName(s,n,i);if(!r)throw new Error(`Unsupported platform: ${n}/${i}`);lk(kl,{recursive:!0});let o=`https://github.com/${e.repo}/releases/download/${e.tagPrefix}${s}/${r}`,a=Bi(kl,r),c=n==="win32"?".exe":"",l=Bi(kl,e.binaryName+c);await v3(o,a);let d=Bi(kl,`extract_tmp_${e.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2,10)}`);lk(d,{recursive:!0});try{if(r.endsWith(".tar.gz"))C3(a,d,r);else if(r.endsWith(".zip"))k3(a,d,r);else throw new Error(`Unsupported archive format: ${r}`);let u=e.binaryName+c,p=Bi(d,r.replace(/\.(tar\.gz|zip)$/,"")),g=[Bi(p,u),Bi(d,u)].find(h=>Nf(h));if(g||(g=w3(d,u)??void 0),g)u3(g,l);else throw new Error(`Binary not found in archive: expected ${u} under ${d}`);n!=="win32"&&a3(l,493)}finally{uk(a,{force:!0}),uk(d,{recursive:!0,force:!0})}return l}var I3={fd:"fd",rg:"ripgrep"};async function Tr(t,e=!1){let n=x3(t);if(n)return n;let i=jf[t];if(i){if(f3()){e||console.log(Tl.yellow(`${i.name} not found. Offline mode enabled, skipping download.`));return}if(up()==="android"){let s=I3[t]??t;e||console.log(Tl.yellow(`${i.name} not found. Install with: pkg install ${s}`));return}e||console.log(Tl.dim(`${i.name} not found. Downloading...`));try{let s=await M3(t);return e||console.log(Tl.dim(`${i.name} installed to ${s}`)),s}catch(s){e||console.log(Tl.yellow(`Failed to download ${i.name}: ${s instanceof Error?s.message:s}`));return}}}function qf(t){return t.split(Gf.sep).join("/")}var E3=Ca.Object({pattern:Ca.String({description:"Glob pattern to match files, e.g. '*.ts', '**/*.json', or 'src/**/*.spec.ts'"}),path:Ca.Optional(Ca.String({description:"Directory to search in (default: current directory)"})),limit:Ca.Optional(Ca.Number({description:"Maximum number of results (default: 1000)"}))}),pk=1e3,A3={exists:_3,glob:()=>[]};function O3(t,e){let n=Xe(t?.pattern),i=Xe(t?.path),s=i!==null?An(i||"."):null,r=t?.limit,o=Xt(e),a=e.fg("toolTitle",e.bold("find"))+" "+(n===null?o:e.fg("accent",n||""))+e.fg("toolOutput",` in ${s===null?o:s}`);return r!==void 0&&(a+=e.fg("toolOutput",` (limit ${r})`)),a}function L3(t,e,n,i){let s=On(t,i).trim(),r="";if(s){let c=s.split(`
|
|
218
218
|
`),l=e.expanded?c.length:20,d=c.slice(0,l),u=c.length-l;r+=`
|
|
219
219
|
${d.map(p=>n.fg("toolOutput",p)).join(`
|
|
220
220
|
`)}`,u>0&&(r+=`${n.fg("muted",`
|
|
221
221
|
... (${u} more lines,`)} ${ce("app.tools.expand","to expand")})`)}let o=t.details?.resultLimitReached,a=t.details?.truncation;if(o||a?.truncated){let c=[];o&&c.push(`${o} results limit`),a?.truncated&&c.push(`${Ye(a.maxBytes??51200)} limit`),r+=`
|
|
222
|
-
${n.fg("warning",`[Truncated: ${c.join(", ")}]`)}`}return r}function dp(t,e){let n=e?.operations;return{name:"find",label:"find",description:`Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${pk} results or ${51200/1024}KB (whichever is hit first).`,promptSnippet:"Find files by glob pattern (respects .gitignore)",parameters:
|
|
222
|
+
${n.fg("warning",`[Truncated: ${c.join(", ")}]`)}`}return r}function dp(t,e){let n=e?.operations;return{name:"find",label:"find",description:`Search for files by glob pattern. Returns matching file paths relative to the search directory. Respects .gitignore. Output is truncated to ${pk} results or ${51200/1024}KB (whichever is hit first).`,promptSnippet:"Find files by glob pattern (respects .gitignore)",parameters:E3,async execute(i,{pattern:s,path:r,limit:o},a,c,l){return new Promise((d,u)=>{if(a?.aborted){u(new Error("Operation aborted"));return}let p=!1,m,g=f=>{p||(p=!0,a?.removeEventListener("abort",h),m=void 0,f())},h=()=>{m?.(),g(()=>u(new Error("Operation aborted")))};a?.addEventListener("abort",h,{once:!0}),(async()=>{try{let f=yn(r||".",t),x=o??pk,y=n??A3;if(n?.glob){if(!await y.exists(f)){g(()=>u(new Error(`Path not found: ${f}`)));return}if(a?.aborted){g(()=>u(new Error("Operation aborted")));return}let I=await y.glob(s,f,{ignore:["**/node_modules/**","**/.git/**"],limit:x});if(a?.aborted){g(()=>u(new Error("Operation aborted")));return}if(I.length===0){g(()=>d({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}let O=I.map(Te=>Te.startsWith(f)?qf(Te.slice(f.length+1)):qf(Gf.relative(f,Te))),F=O.length>=x,N=O.join(`
|
|
223
223
|
`),H=Qn(N,{maxLines:Number.MAX_SAFE_INTEGER}),G=H.content,Z={},de=[];F&&(de.push(`${x} results limit reached`),Z.resultLimitReached=x),H.truncated&&(de.push(`${Ye(51200)} limit reached`),Z.truncation=H),de.length>0&&(G+=`
|
|
224
224
|
|
|
225
|
-
[${de.join(". ")}]`),g(()=>d({content:[{type:"text",text:G}],details:Object.keys(Z).length>0?Z:void 0}));return}let w=await Tr("fd",!0);if(a?.aborted){g(()=>u(new Error("Operation aborted")));return}if(!w){g(()=>u(new Error("fd is not available and could not be downloaded")));return}let P=["--glob","--color=never","--hidden","--no-require-git","--max-results",String(x)],_=s;s.includes("/")&&(P.push("--full-path"),!s.startsWith("/")&&!s.startsWith("**/")&&s!=="**"&&(_=`**/${s}`)),P.push("--",_,f);let R=
|
|
225
|
+
[${de.join(". ")}]`),g(()=>d({content:[{type:"text",text:G}],details:Object.keys(Z).length>0?Z:void 0}));return}let w=await Tr("fd",!0);if(a?.aborted){g(()=>u(new Error("Operation aborted")));return}if(!w){g(()=>u(new Error("fd is not available and could not be downloaded")));return}let P=["--glob","--color=never","--hidden","--no-require-git","--max-results",String(x)],_=s;s.includes("/")&&(P.push("--full-path"),!s.startsWith("/")&&!s.startsWith("**/")&&s!=="**"&&(_=`**/${s}`)),P.push("--",_,f);let R=P3(w,P,{stdio:["ignore","pipe","pipe"]}),L=R3({input:R.stdout}),E="",W=[];m=()=>{R.killed||R.kill()};let M=()=>{L.close()};R.stderr?.on("data",I=>{E+=I.toString()}),L.on("line",I=>{W.push(I)}),R.on("error",I=>{M(),g(()=>u(new Error(`Failed to run fd: ${I.message}`)))}),R.on("close",I=>{if(M(),a?.aborted){g(()=>u(new Error("Operation aborted")));return}let O=W.join(`
|
|
226
226
|
`);if(I!==0){let pe=E.trim()||`fd exited with code ${I}`;if(!O){g(()=>u(new Error(pe)));return}}if(!O){g(()=>d({content:[{type:"text",text:"No files found matching pattern"}],details:void 0}));return}let F=[];for(let pe of W){let Ie=pe.replace(/\r$/,"").trim();if(!Ie)continue;let tt=Ie.endsWith("/")||Ie.endsWith("\\"),De=Ie;Ie.startsWith(f)?De=Ie.slice(f.length+1):De=Gf.relative(f,Ie),tt&&!De.endsWith("/")&&(De+="/"),F.push(qf(De))}let N=F.length>=x,H=F.join(`
|
|
227
227
|
`),G=Qn(H,{maxLines:Number.MAX_SAFE_INTEGER}),Z=G.content,de={},Te=[];N&&(Te.push(`${x} results limit reached. Use limit=${x*2} for more, or refine pattern`),de.resultLimitReached=x),G.truncated&&(Te.push(`${Ye(51200)} limit reached`),de.truncation=G),Te.length>0&&(Z+=`
|
|
228
228
|
|
|
229
|
-
[${Te.join(". ")}]`),g(()=>d({content:[{type:"text",text:Z}],details:Object.keys(de).length>0?de:void 0}))})}catch(f){if(a?.aborted){g(()=>u(new Error("Operation aborted")));return}let x=f instanceof Error?f:new Error(String(f));g(()=>u(x))}})()})},renderCall(i,s,r){let o=r.lastComponent??new A("",0,0);return o.setText(
|
|
229
|
+
[${Te.join(". ")}]`),g(()=>d({content:[{type:"text",text:Z}],details:Object.keys(de).length>0?de:void 0}))})}catch(f){if(a?.aborted){g(()=>u(new Error("Operation aborted")));return}let x=f instanceof Error?f:new Error(String(f));g(()=>u(x))}})()})},renderCall(i,s,r){let o=r.lastComponent??new A("",0,0);return o.setText(O3(i,s)),o},renderResult(i,s,r,o){let a=o.lastComponent??new A("",0,0);return a.setText(L3(i,s,r,o.showImages)),a}}}import{createInterface as W3}from"node:readline";import{spawn as U3}from"child_process";import{readFileSync as F3,statSync as D3}from"fs";import hk from"path";import{Type as Zt}from"typebox";var $3=Zt.Object({pattern:Zt.String({description:"Search pattern (regex or literal string)"}),path:Zt.Optional(Zt.String({description:"Directory or file to search (default: current directory)"})),glob:Zt.Optional(Zt.String({description:"Filter files by glob pattern, e.g. '*.ts' or '**/*.spec.ts'"})),ignoreCase:Zt.Optional(Zt.Boolean({description:"Case-insensitive search (default: false)"})),literal:Zt.Optional(Zt.Boolean({description:"Treat pattern as literal string instead of regex (default: false)"})),context:Zt.Optional(Zt.Number({description:"Number of lines to show before and after each match (default: 0)"})),limit:Zt.Optional(Zt.Number({description:"Maximum number of matches to return (default: 100)"}))}),gk=100,B3={isDirectory:t=>D3(t).isDirectory(),readFile:t=>F3(t,"utf-8")};function N3(t,e){let n=Xe(t?.pattern),i=Xe(t?.path),s=i!==null?An(i||"."):null,r=Xe(t?.glob),o=t?.limit,a=Xt(e),c=e.fg("toolTitle",e.bold("grep"))+" "+(n===null?a:e.fg("accent",`/${n||""}/`))+e.fg("toolOutput",` in ${s===null?a:s}`);return r&&(c+=e.fg("toolOutput",` (${r})`)),o!==void 0&&(c+=e.fg("toolOutput",` limit ${o}`)),c}function j3(t,e,n,i){let s=On(t,i).trim(),r="";if(s){let l=s.split(`
|
|
230
230
|
`),d=e.expanded?l.length:15,u=l.slice(0,d),p=l.length-d;r+=`
|
|
231
231
|
${u.map(m=>n.fg("toolOutput",m)).join(`
|
|
232
232
|
`)}`,p>0&&(r+=`${n.fg("muted",`
|
|
233
233
|
... (${p} more lines,`)} ${ce("app.tools.expand","to expand")})`)}let o=t.details?.matchLimitReached,a=t.details?.truncation,c=t.details?.linesTruncated;if(o||a?.truncated||c){let l=[];o&&l.push(`${o} matches limit`),a?.truncated&&l.push(`${Ye(a.maxBytes??51200)} limit`),c&&l.push("some lines truncated"),r+=`
|
|
234
|
-
${n.fg("warning",`[Truncated: ${l.join(", ")}]`)}`}return r}function pp(t,e){let n=e?.operations;return{name:"grep",label:"grep",description:`Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${gk} matches or ${51200/1024}KB (whichever is hit first). Long lines are truncated to ${500} chars.`,promptSnippet:"Search file contents for patterns (respects .gitignore)",parameters:$
|
|
234
|
+
${n.fg("warning",`[Truncated: ${l.join(", ")}]`)}`}return r}function pp(t,e){let n=e?.operations;return{name:"grep",label:"grep",description:`Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Output is truncated to ${gk} matches or ${51200/1024}KB (whichever is hit first). Long lines are truncated to ${500} chars.`,promptSnippet:"Search file contents for patterns (respects .gitignore)",parameters:$3,async execute(i,{pattern:s,path:r,glob:o,ignoreCase:a,literal:c,context:l,limit:d},u,p,m){return new Promise((g,h)=>{if(u?.aborted){h(new Error("Operation aborted"));return}let f=!1,x=y=>{f||(f=!0,y())};(async()=>{try{let y=await Tr("rg",!0);if(!y){x(()=>h(new Error("ripgrep (rg) is not available and could not be downloaded")));return}let w=yn(r||".",t),P=n??B3,_;try{_=await P.isDirectory(w)}catch{x(()=>h(new Error(`Path not found: ${w}`)));return}let R=l&&l>0?l:0,L=Math.max(1,d??gk),E=ne=>{if(_){let be=hk.relative(w,ne);if(be&&!be.startsWith(".."))return be.replace(/\\/g,"/")}return hk.basename(ne)},W=new Map,M=async ne=>{let be=W.get(ne);if(!be){try{be=(await P.readFile(ne)).replace(/\r\n/g,`
|
|
235
235
|
`).replace(/\r/g,`
|
|
236
236
|
`).split(`
|
|
237
|
-
`)}catch{be=[]}W.set(ne,be)}return be},I=["--json","--line-number","--color=never","--hidden"];a&&I.push("--ignore-case"),c&&I.push("--fixed-strings"),o&&I.push("--glob",o),I.push("--",s,w);let O=
|
|
237
|
+
`)}catch{be=[]}W.set(ne,be)}return be},I=["--json","--line-number","--color=never","--hidden"];a&&I.push("--ignore-case"),c&&I.push("--fixed-strings"),o&&I.push("--glob",o),I.push("--",s,w);let O=U3(y,I,{stdio:["ignore","pipe","pipe"]}),F=W3({input:O.stdout}),N="",H=0,G=!1,Z=!1,de=!1,Te=!1,pe=[],Ie=()=>{F.close(),u?.removeEventListener("abort",De)},tt=(ne=!1)=>{O.killed||(Te=ne,O.kill())},De=()=>{de=!0,tt()};u?.addEventListener("abort",De,{once:!0}),O.stderr?.on("data",ne=>{N+=ne.toString()});let ri=async(ne,be)=>{let ye=E(ne),nt=await M(ne);if(!nt.length)return[`${ye}:${be}: (unable to read file)`];let At=[],Ii=R>0?Math.max(1,be-R):be,qt=R>0?Math.min(nt.length,be+R):be;for(let Tn=Ii;Tn<=qt;Tn++){let Lc=(nt[Tn-1]??"").replace(/\r/g,""),er=Tn===be,{text:Wc,wasTruncated:Hh}=ml(Lc);Hh&&(Z=!0),er?At.push(`${ye}:${Tn}: ${Wc}`):At.push(`${ye}-${Tn}- ${Wc}`)}return At},jt=[];F.on("line",ne=>{if(!ne.trim()||H>=L)return;let be;try{be=JSON.parse(ne)}catch{return}if(be.type==="match"){H++;let ye=be.data?.path?.text,nt=be.data?.line_number,At=be.data?.lines?.text;ye&&typeof nt=="number"&&jt.push({filePath:ye,lineNumber:nt,lineText:At}),H>=L&&(G=!0,tt(!0))}}),O.on("error",ne=>{Ie(),x(()=>h(new Error(`Failed to run ripgrep: ${ne.message}`)))}),O.on("close",async ne=>{if(Ie(),de){x(()=>h(new Error("Operation aborted")));return}if(!Te&&ne!==0&&ne!==1){let qt=N.trim()||`ripgrep exited with code ${ne}`;x(()=>h(new Error(qt)));return}if(H===0){x(()=>g({content:[{type:"text",text:"No matches found"}],details:void 0}));return}for(let qt of jt)if(R===0&&qt.lineText!==void 0){let Tn=E(qt.filePath),Ri=qt.lineText.replace(/\r\n/g,`
|
|
238
238
|
`).replace(/\r/g,"").replace(/\n$/,""),{text:Lc,wasTruncated:er}=ml(Ri);er&&(Z=!0),pe.push(`${Tn}:${qt.lineNumber}: ${Lc}`)}else{let Tn=await ri(qt.filePath,qt.lineNumber);pe.push(...Tn)}let be=pe.join(`
|
|
239
239
|
`),ye=Qn(be,{maxLines:Number.MAX_SAFE_INTEGER}),nt=ye.content,At={},Ii=[];G&&(Ii.push(`${L} matches limit reached. Use limit=${L*2} for more, or refine pattern`),At.matchLimitReached=L),ye.truncated&&(Ii.push(`${Ye(51200)} limit reached`),At.truncation=ye),Z&&(Ii.push(`Some lines truncated to ${500} chars. Use read tool to see full lines`),At.linesTruncated=!0),Ii.length>0&&(nt+=`
|
|
240
240
|
|
|
241
|
-
[${Ii.join(". ")}]`),x(()=>g({content:[{type:"text",text:nt}],details:Object.keys(At).length>0?At:void 0}))})}catch(y){x(()=>h(y))}})()})},renderCall(i,s,r){let o=r.lastComponent??new A("",0,0);return o.setText(
|
|
241
|
+
[${Ii.join(". ")}]`),x(()=>g({content:[{type:"text",text:nt}],details:Object.keys(At).length>0?At:void 0}))})}catch(y){x(()=>h(y))}})()})},renderCall(i,s,r){let o=r.lastComponent??new A("",0,0);return o.setText(N3(i,s)),o},renderResult(i,s,r,o){let a=o.lastComponent??new A("",0,0);return a.setText(j3(i,s,r,o.showImages)),a}}}import{existsSync as q3,readdirSync as G3,statSync as K3}from"fs";import H3 from"path";import{Type as Il}from"typebox";var z3=Il.Object({path:Il.Optional(Il.String({description:"Directory to list (default: current directory)"})),limit:Il.Optional(Il.Number({description:"Maximum number of entries to return (default: 500)"}))}),fk=500,V3={exists:q3,stat:K3,readdir:G3};function J3(t,e){let n=Xe(t?.path),i=n!==null?An(n||"."):null,s=t?.limit,r=Xt(e),o=`${e.fg("toolTitle",e.bold("ls"))} ${i===null?r:e.fg("accent",i)}`;return s!==void 0&&(o+=e.fg("toolOutput",` (limit ${s})`)),o}function Q3(t,e,n,i){let s=On(t,i).trim(),r="";if(s){let c=s.split(`
|
|
242
242
|
`),l=e.expanded?c.length:20,d=c.slice(0,l),u=c.length-l;r+=`
|
|
243
243
|
${d.map(p=>n.fg("toolOutput",p)).join(`
|
|
244
244
|
`)}`,u>0&&(r+=`${n.fg("muted",`
|
|
245
245
|
... (${u} more lines,`)} ${ce("app.tools.expand","to expand")})`)}let o=t.details?.entryLimitReached,a=t.details?.truncation;if(o||a?.truncated){let c=[];o&&c.push(`${o} entries limit`),a?.truncated&&c.push(`${Ye(a.maxBytes??51200)} limit`),r+=`
|
|
246
|
-
${n.fg("warning",`[Truncated: ${c.join(", ")}]`)}`}return r}function mp(t,e){let n=e?.operations??
|
|
246
|
+
${n.fg("warning",`[Truncated: ${c.join(", ")}]`)}`}return r}function mp(t,e){let n=e?.operations??V3;return{name:"ls",label:"ls",description:`List directory contents. Returns entries sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Output is truncated to ${fk} entries or ${51200/1024}KB (whichever is hit first).`,promptSnippet:"List directory contents",parameters:z3,async execute(i,{path:s,limit:r},o,a,c){return new Promise((l,d)=>{if(o?.aborted){d(new Error("Operation aborted"));return}let u=()=>d(new Error("Operation aborted"));o?.addEventListener("abort",u,{once:!0}),(async()=>{try{let p=yn(s||".",t),m=r??fk;if(!await n.exists(p)){d(new Error(`Path not found: ${p}`));return}if(!(await n.stat(p)).isDirectory()){d(new Error(`Not a directory: ${p}`));return}let h;try{h=await n.readdir(p)}catch(L){d(new Error(`Cannot read directory: ${L.message}`));return}h.sort((L,E)=>L.toLowerCase().localeCompare(E.toLowerCase()));let f=[],x=!1;for(let L of h){if(f.length>=m){x=!0;break}let E=H3.join(p,L),W="";try{(await n.stat(E)).isDirectory()&&(W="/")}catch{continue}f.push(L+W)}if(o?.removeEventListener("abort",u),f.length===0){l({content:[{type:"text",text:"(empty directory)"}],details:void 0});return}let y=f.join(`
|
|
247
247
|
`),w=Qn(y,{maxLines:Number.MAX_SAFE_INTEGER}),P=w.content,_={},R=[];x&&(R.push(`${m} entries limit reached. Use limit=${m*2} for more`),_.entryLimitReached=m),w.truncated&&(R.push(`${Ye(51200)} limit reached`),_.truncation=w),R.length>0&&(P+=`
|
|
248
248
|
|
|
249
|
-
[${R.join(". ")}]`),l({content:[{type:"text",text:P}],details:Object.keys(_).length>0?_:void 0})}catch(p){o?.removeEventListener("abort",u),d(p)}})()})},renderCall(i,s,r){let o=r.lastComponent??new A("",0,0);return o.setText(
|
|
249
|
+
[${R.join(". ")}]`),l({content:[{type:"text",text:P}],details:Object.keys(_).length>0?_:void 0})}catch(p){o?.removeEventListener("abort",u),d(p)}})()})},renderCall(i,s,r){let o=r.lastComponent??new A("",0,0);return o.setText(J3(i,s)),o},renderResult(i,s,r,o){let a=o.lastComponent??new A("",0,0);return a.setText(Q3(i,s,r,o.showImages)),a}}}import{basename as Sk,dirname as Tk,isAbsolute as mD,relative as hD,resolve as Ck,sep as kk}from"node:path";import{constants as gD}from"fs";import{access as fD,readFile as bD}from"fs/promises";import{Type as Pa}from"typebox";function Y3(t,e){if(e+8>t.length)return 1;let i=(t[e]<<8|t[e+1])===18761,s=l=>i?t[l]|t[l+1]<<8:t[l]<<8|t[l+1],o=(l=>i?t[l]|t[l+1]<<8|t[l+2]<<16|t[l+3]<<24:(t[l]<<24|t[l+1]<<16|t[l+2]<<8|t[l+3])>>>0)(e+4),a=e+o;if(a+2>t.length)return 1;let c=s(a);for(let l=0;l<c;l++){let d=a+2+l*12;if(d+12>t.length)return 1;if(s(d)===274){let u=s(d+8);return u>=1&&u<=8?u:1}}return 1}function X3(t){let e=2;for(;e<t.length-1;){if(t[e]!==255)return-1;let n=t[e+1];if(n===255){e++;continue}if(n===225){if(e+4>=t.length)return-1;let s=e+4;return s+6>t.length||!bk(t,s)?-1:s+6}if(e+4>t.length)return-1;let i=t[e+2]<<8|t[e+3];e+=2+i}return-1}function Z3(t){let e=12;for(;e+8<=t.length;){let n=String.fromCharCode(t[e],t[e+1],t[e+2],t[e+3]),i=t[e+4]|t[e+5]<<8|t[e+6]<<16|t[e+7]<<24,s=e+8;if(n==="EXIF")return s+i>t.length?-1:i>=6&&bk(t,s)?s+6:s;e=s+i+i%2}return-1}function bk(t,e){return t[e]===69&&t[e+1]===120&&t[e+2]===105&&t[e+3]===102&&t[e+4]===0&&t[e+5]===0}function eD(t){let e=-1;return t.length>=2&&t[0]===255&&t[1]===216?e=X3(t):t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80&&(e=Z3(t)),e===-1?1:Y3(t,e)}function hp(t,e,n){let i=e.get_width(),s=e.get_height(),r=e.get_raw_pixels(),o=new Uint8Array(r.length);for(let a=0;a<s;a++)for(let c=0;c<i;c++){let l=(a*i+c)*4,d=n(c,a,i,s)*4;o[d]=r[l],o[d+1]=r[l+1],o[d+2]=r[l+2],o[d+3]=r[l+3]}return new t.PhotonImage(o,s,i)}function gp(t,e,n){let i=eD(n);if(i===1)return e;switch(i){case 2:return t.fliph(e),e;case 3:return t.fliph(e),t.flipv(e),e;case 4:return t.flipv(e),e;case 5:{let s=hp(t,e,(r,o,a,c)=>r*c+(c-1-o));return t.fliph(s),s}case 6:return hp(t,e,(s,r,o,a)=>s*a+(a-1-r));case 7:{let s=hp(t,e,(r,o,a,c)=>(a-1-r)*c+o);return t.fliph(s),s}case 8:return hp(t,e,(s,r,o,a)=>(o-1-s)*a+r);default:return e}}import{createRequire as tD}from"module";import*as Ma from"path";import{fileURLToPath as nD}from"url";var iD=tD(import.meta.url),Ta=iD("fs"),bp="photon_rs_bg.wasm",ka=null,fp=null;function sD(t){return typeof t=="string"?t:t instanceof URL?nD(t):null}function rD(){let t=Ma.dirname(process.execPath);return[Ma.join(t,bp),Ma.join(t,"photon",bp),Ma.join(process.cwd(),bp)]}function oD(){let t=Ta.readFileSync.bind(Ta),e=rD(),n=Ta,i=((...s)=>{let[r,o]=s;if(sD(r)?.endsWith(bp))try{return t(...s)}catch(c){let l=c;if(l?.code&&l.code!=="ENOENT")throw c;for(let d of e)if(Ta.existsSync(d))return o===void 0?t(d):t(d,o);throw c}return t(...s)});try{n.readFileSync=i}catch{Object.defineProperty(Ta,"readFileSync",{value:i,writable:!0,configurable:!0})}return()=>{try{n.readFileSync=t}catch{Object.defineProperty(Ta,"readFileSync",{value:t,writable:!0,configurable:!0})}}}async function Ia(){return ka||fp||(fp=(async()=>{let t=oD();try{return ka=await import("@silvia-odwyer/photon-node"),ka}catch{return ka=null,ka}finally{t()}})(),fp)}var aD=4.5*1024*1024,cD={maxWidth:2e3,maxHeight:2e3,maxBytes:aD,jpegQuality:80};function xk(t,e){let n=Buffer.from(t).toString("base64");return{data:n,encodedSize:Buffer.byteLength(n,"utf-8"),mimeType:e}}async function xp(t,e){let n={...cD,...e},i=Buffer.from(t.data,"base64"),s=Buffer.byteLength(t.data,"utf-8"),r=await Ia();if(!r)return null;let o;try{let h=function(w,P,_){let R=r.resize(o,w,P,r.SamplingFilter.Lanczos3);try{let L=[xk(R.get_bytes(),"image/png")];for(let E of _)L.push(xk(R.get_bytes_jpeg(E),"image/jpeg"));return L}finally{R.free()}};var a=h;let c=new Uint8Array(i),l=r.PhotonImage.new_from_byteslice(c);o=gp(r,l,c),o!==l&&l.free();let d=o.get_width(),u=o.get_height(),p=t.mimeType?.split("/")[1]??"png";if(d<=n.maxWidth&&u<=n.maxHeight&&s<n.maxBytes)return{data:t.data,mimeType:t.mimeType??`image/${p}`,originalWidth:d,originalHeight:u,width:d,height:u,wasResized:!1};let m=d,g=u;m>n.maxWidth&&(g=Math.round(g*n.maxWidth/m),m=n.maxWidth),g>n.maxHeight&&(m=Math.round(m*n.maxHeight/g),g=n.maxHeight);let f=Array.from(new Set([n.jpegQuality,85,70,55,40])),x=m,y=g;for(;;){let w=h(x,y,f);for(let R of w)if(R.encodedSize<n.maxBytes)return{data:R.data,mimeType:R.mimeType,originalWidth:d,originalHeight:u,width:x,height:y,wasResized:!0};if(x===1&&y===1)break;let P=x===1?1:Math.max(1,Math.floor(x*.75)),_=y===1?1:Math.max(1,Math.floor(y*.75));if(P===x&&_===y)break;x=P,y=_}return null}catch{return null}finally{o&&o.free()}}function yp(t){if(!t.wasResized)return;let e=t.originalWidth/t.width;return`[Image: original ${t.originalWidth}x${t.originalHeight}, displayed at ${t.width}x${t.height}. Multiply coordinates by ${e.toFixed(2)} to map to original image.]`}import{open as lD}from"node:fs/promises";var yk=4100,Kf=[137,80,78,71,13,10,26,10];function uD(t){return vk(t,[255,216,255])?t[3]===247?null:"image/jpeg":vk(t,Kf)?dD(t)&&!pD(t)?"image/png":null:Ra(t,0,"GIF")?"image/gif":Ra(t,0,"RIFF")&&Ra(t,8,"WEBP")?"image/webp":null}async function Hf(t){let e=await lD(t,"r");try{let n=Buffer.alloc(yk),{bytesRead:i}=await e.read(n,0,yk,0);return uD(n.subarray(0,i))}finally{await e.close()}}function dD(t){return t.length>=16&&wk(t,Kf.length)===13&&Ra(t,12,"IHDR")}function pD(t){let e=Kf.length;for(;e+8<=t.length;){let n=wk(t,e),i=e+4;if(Ra(t,i,"acTL"))return!0;if(Ra(t,i,"IDAT"))return!1;let s=e+8+n+4;if(s<=e||s>t.length)return!1;e=s}return!1}function wk(t,e){return(t[e]??0)*16777216+((t[e+1]??0)<<16)+((t[e+2]??0)<<8)+(t[e+3]??0)}function vk(t,e){return t.length<e.length?!1:e.every((n,i)=>t[i]===n)}function Ra(t,e,n){if(t.length<e+n.length)return!1;for(let i=0;i<n.length;i++)if(t[e+i]!==n.charCodeAt(i))return!1;return!0}var xD=Pa.Object({path:Pa.String({description:"Path to the file to read (relative or absolute)"}),offset:Pa.Optional(Pa.Number({description:"Line number to start reading from (1-indexed)"})),limit:Pa.Optional(Pa.Number({description:"Maximum number of lines to read"}))}),yD=new Set(["AGENTS.md","AGENTS.MD","CLAUDE.md","CLAUDE.MD"]),vD={readFile:t=>bD(t),access:t=>fD(t,gD.R_OK),detectImageMimeType:Hf};function zf(t,e){if(t?.offset===void 0&&t?.limit===void 0)return"";let n=t.offset??1,i=t.limit!==void 0?n+t.limit-1:"";return e.fg("warning",`:${n}${i?`-${i}`:""}`)}function wD(t,e){let n=Xe(t?.file_path??t?.path),i=n!==null?An(n):null,s=Xt(e),r=i===null?s:i?e.fg("accent",i):e.fg("toolOutput","...");return`${e.fg("toolTitle",e.bold("read"))} ${r}${zf(t,e)}`}function SD(t){let e=t.length;for(;e>0&&t[e-1]==="";)e--;return t.slice(0,e)}function CD(t){if(!(!t||t.input.includes("image")))return"[Current model does not support images. The image will be omitted from this request.]"}function TD(t){return t.split(kk).join("/")}function kD(t){let e=Tk(sg()),n=hD(Ck(e),Ck(t));if(n===""||n===".."||n.startsWith(`..${kk}`)||mD(n))return;let i=TD(n);if(i==="README.md"||i.startsWith("docs/")||i.startsWith("examples/"))return{kind:"docs",label:i}}function Mk(t,e){let n=Xe(t?.file_path??t?.path);if(!n)return;let i=ap(n,e),s=Sk(i);if(s==="SKILL.md")return{kind:"skill",label:Sk(Tk(i))||s};let r=kD(i);if(r)return r;if(yD.has(s))return{kind:"resource",label:VT(i,e)}}function MD(t,e,n){let i=n.fg("dim",` (${he("app.tools.expand")} to expand)`);return t.kind==="skill"?n.fg("customMessageLabel","\x1B[1m[skill]\x1B[22m ")+n.fg("customMessageText",t.label)+zf(e,n)+i:n.fg("toolTitle",n.bold(`read ${t.kind}`))+" "+n.fg("accent",t.label)+zf(e,n)+i}function ID(t,e,n,i,s,r,o){if(!n.expanded&&!o&&Mk(t,r))return"";let a=Xe(t?.file_path??t?.path),c=On(e,s),l=a?xr(a):void 0,d=l?Ms($i(c),l):c.split(`
|
|
250
250
|
`),u=SD(d),p=n.expanded?u.length:10,m=u.slice(0,p),g=u.length-p,h=`
|
|
251
251
|
${m.map(x=>l?$i(x):i.fg("toolOutput",$i(x))).join(`
|
|
252
252
|
`)}`;g>0&&(h+=`${i.fg("muted",`
|
|
@@ -441,7 +441,7 @@ Log file: ${Ki}
|
|
|
441
441
|
`;Ls.appendFileSync(Ki,n)}catch{}}function Je(t,e){if(!(!Ki||!Ls||!jl))try{let i=`[${new Date().toISOString()}] ${t}:
|
|
442
442
|
${JSON.stringify(e,null,2)}
|
|
443
443
|
|
|
444
|
-
`;Ls.appendFileSync(Ki,i)}catch{}}var Ws=null;function $1(t){if(!t)return;let e=t.trim();if(e)return e.replace(/\/+$/,"")}var we=class t{static{this.BASE_URL="base_url"}static{this.ANALYTICS_DOMAIN="analytics_domain"}static{this.CLIENT_ID="client_id"}static{this.PROJECT_ID="project_id"}static{this.WORKSPACE_ID="workspace_id"}static{this.defaultValues={[t.BASE_URL]:"https://sapientaiproducts.com",[t.ANALYTICS_DOMAIN]:"https://slingshot.sapientaiproducts.com",[t.CLIENT_ID]:"b97fbef7-cad9-4e56-9850-39e86c8fdf61",[t.PROJECT_ID]:"fa8121c4-e2fc-48f1-9478-8949c04e13cc",[t.WORKSPACE_ID]:"6e5756eb-d7e2-4d80-ad07-9d7a51600d85"}}static{this.LOGIN_PATH="/web/v1/studio-auth/login"}static{this.EXCHANGE_PATH="/api/v1/studio-auth/auth/desktop/exchange"}static{this.REFRESH_PATH="/api/v3/auth/refreshtoken"}static{this.REFRESH_CLIENT_NAME="machine"}static{this.API_BASE_PATH="/api/v1/llm"}static{this.SAGE_EVENTS_PATH="/api/v1/ai-portal/sage_events"}static{this.APP_TOKEN_PATH="/api/v3/auth/app-token"}static{this.CONFIG_SERVICE_PATH="/api/v2/configservice/client"}static{this.APP_TOKEN_REFRESH_BUFFER_MS=60*1e3}static{this.SLINGSHOT_APP_TOKEN_ENV="SLINGSHOT_APP_TOKEN_HEADER"}static{this.TOKEN_EXPIRY_BUFFER_MS=300*1e3}static{this.SAPI="/save/api/v1"}static{this.CLIENT_NAME="desktop"}static defaults(e){return this.defaultValues[e]}static getSettingsPath(){let e=Gl.resolve(process.cwd(),".sling","sling.settings.json");if(Hi.existsSync(e))return e;let n=_e();return Gl.resolve(n,"sling.settings.json")}static getSettings(){if(!Ws){let i=this.getSettingsPath();try{if(Hi.existsSync(i)){let s=Hi.readFileSync(i,"utf-8"),r=JSON.parse(s)||{};Ws={...this.defaultValues,...r}}else{let s=Gl.dirname(i);Hi.existsSync(s)||Hi.mkdirSync(s,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(this.defaultValues,null,2),"utf-8"),Ws={...this.defaultValues}}}catch(s){Je("Error reading/writing sling.settings.json: ",s),Ws={...this.defaultValues}}}let e=$1(process.env.SLINGSHOT_API_DOMAIN),n=$1(process.env.SLINGSHOT_ANALYTICS_DOMAIN);return{...Ws,[t.BASE_URL]:e||Ws[t.BASE_URL],[t.ANALYTICS_DOMAIN]:n||Ws[t.ANALYTICS_DOMAIN]}}static updateSettings(e){let n=_e(),i=Gl.resolve(n,"sling.settings.json");try{let r={...this.getSettings()||{},...e},o=Gl.dirname(i);Hi.existsSync(o)||Hi.mkdirSync(o,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(r,null,2),"utf-8"),Ws=r}catch(s){Je("Error updating sling.settings.json: ",s)}}static getLoginUrl(e){let n=this.getSettings(),i=new URLSearchParams({client:this.CLIENT_NAME,port:String(e.port),localState:e.localState});return e.clientId&&i.set("clientId",e.clientId),`${n[t.BASE_URL]}${this.LOGIN_PATH}?${i.toString()}`}static getExchangeUrl(){return`${this.getSettings()[t.BASE_URL]}${this.EXCHANGE_PATH}`}static getRefreshUrl(){let e=this.getSettings(),n=new URLSearchParams({client:this.REFRESH_CLIENT_NAME});return`${e[t.BASE_URL]}${this.REFRESH_PATH}?${n.toString()}`}static getApiBaseUrl(){return`${this.getSettings()[t.BASE_URL]}${this.API_BASE_PATH}`}static getSageEventsUrl(){return`${this.getSettings()[t.ANALYTICS_DOMAIN]}${this.SAGE_EVENTS_PATH}`}static getTokenExpiryBuffer(){return this.TOKEN_EXPIRY_BUFFER_MS}static getDefaultProjectId(){let e=this.getSettings();return process.env.SLINGSHOT_PROJECT_ID||e[t.PROJECT_ID]}static getDefaultWorkspaceId(){let e=this.getSettings();return process.env.SLINGSHOT_WORKSPACE_ID||e[t.WORKSPACE_ID]}static getDefaultClientId(){let e=this.getSettings();return process.env.CLIENT_ID||e[t.CLIENT_ID]}static getUserActivityUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users/activity`}static getUserUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users`}static getAppTokenUrl(){return`${this.getSettings()[t.BASE_URL]}${this.APP_TOKEN_PATH}`}static getConfigServiceUrl(e){let n=this.getSettings(),i=this.getDefaultClientId(),s=new URLSearchParams({keys:e});return`${n[t.BASE_URL]}${this.CONFIG_SERVICE_PATH}/${i}?${s.toString()}`}static getAppTokenRefreshBuffer(){return this.APP_TOKEN_REFRESH_BUFFER_MS}};function Kl(t){try{let e=t.split(".");if(e.length!==3)return 0;let n=JSON.parse(atob(e[1]));return n.exp?n.exp*1e3:0}catch{return 0}}function jp(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function B1(){return`user_${jp()}`}var q0="Xq7Wm2zR9pLkVbN4cD8fH3jT6yG1sA5",kB=BigInt(q0.length);function MB(t){if(t.length===0)return"";let e=0n;for(let i of t){let s=q0.indexOf(i);if(s===-1)throw new Error(`Cannot decode app_key: character "${i}" is not in the expected alphabet`);e=e*kB+BigInt(s)}let n=[];for(;e>0n;)n.unshift(Number(e&0xffn)),e>>=8n;for(let i of t)if(i===q0[0])n.unshift(0);else break;return new TextDecoder().decode(new Uint8Array(n))}var G0=new Map,qp=new Map;async function IB(t,e){let n=we.getConfigServiceUrl(t);Pe(`sling-config: fetching ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e}`}})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Cannot reach config service: ${a}`)}if(!i.ok){let o=`${i.status} ${i.statusText}`;try{let a=await i.json();a.message?o=String(a.message):a.error&&(o=String(a.error))}catch{}throw new Error(`Config service request failed: ${o}`)}let r=(await i.json())?.data?.config;if(!r||typeof r!="object")throw new Error("Config service response missing data.config");return r}async function N1(t,e){let n=G0.get(t);if(n)return n;let i=qp.get(t);if(i)return i;if(!e)throw new Error("Cannot reach config service: no Slingshot user token provided");let s=IB(t,e).then(r=>(G0.set(t,r),r)).finally(()=>{qp.delete(t)});return qp.set(t,s),s}var tc=class{static async getSlingcliConfig(e){let n=await N1("slingcli",e),i=n.slingcli;if(!i||typeof i.app_id!="string"||typeof i.app_key!="string"||!i.app_id||!i.app_key)throw Je("sling-config: missing slingcli block",n),new Error("Config service did not return slingcli.app_id / slingcli.app_key for this client");return{app_id:i.app_id,app_key:MB(i.app_key)}}static async getRemoteConfig(e,n){return N1(e,n)}static clearCache(){G0.clear(),qp=new Map}};import j1 from"node:path";import Us from"node:fs";var RB="sling.app-creds.json";function K0(){return j1.resolve(_e(),RB)}function q1(){let t=K0();if(!Us.existsSync(t))return null;try{let e=Us.readFileSync(t,"utf-8"),n=JSON.parse(e);return typeof n.app_id!="string"||typeof n.app_key!="string"||!n.app_id||!n.app_key?(Je("app-creds-store: invalid creds file, ignoring",n),null):{app_id:n.app_id,app_key:n.app_key}}catch(e){return Je("app-creds-store: failed to read creds file",e),null}}function H0(t){let e=K0(),n=j1.dirname(e);try{Us.existsSync(n)||Us.mkdirSync(n,{recursive:!0});let i={...t,savedAt:Date.now()};Us.writeFileSync(e,JSON.stringify(i,null,2),{encoding:"utf-8",mode:384});try{Us.chmodSync(e,384)}catch{}Pe(`app-creds-store: persisted to ${e}`)}catch(i){Je("app-creds-store: failed to persist creds",i)}}function G1(){let t=K0();try{Us.existsSync(t)&&(Us.unlinkSync(t),Pe(`app-creds-store: cleared ${t}`))}catch(e){Je("app-creds-store: failed to clear creds file",e)}}var Kp=class extends Error{constructor(n,i){super(i);this.status=n;this.name="AppTokenHttpError"}},Hl=null,zl=null,Gp=null,nc=null;function K1(t){process.env[we.SLINGSHOT_APP_TOKEN_ENV]=`Bearer ${t}`}function PB(t){nc&&(clearTimeout(nc),nc=null);let e=t.expiresAt-Date.now();e<=0||(nc=setTimeout(()=>{nc=null,zi().catch(n=>{Je("app-token: scheduled refresh failed",n)})},e),nc.unref?.())}async function H1(t){let e=Buffer.from(`${t.app_id}:${t.app_key}`).toString("base64"),n=we.getAppTokenUrl();Pe(`app-token: minting from ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${e}`}})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach app-token service: ${c}`)}if(!i.ok){let a=`${i.status} ${i.statusText}`;try{let c=await i.text()||"";c&&(a=c)}catch{}throw new Kp(i.status,`App token request failed: ${a}`)}let s=await i.json();if(!s.app_token||typeof s.expires_in!="number")throw new Error("App token response missing app_token or expires_in");let r=we.getAppTokenRefreshBuffer(),o=Date.now()+s.expires_in*1e3-r;return Pe(`app-token: minted, expires at ${new Date(o).toISOString()}`),{token:s.app_token,expiresAt:o}}async function _B(){let t=q1();if(t)return{creds:t,fromDisk:!0};if(!zl)throw new Error("Cannot mint app token: no on-disk app credentials and no Slingshot user token available (please /login slingshot first)");let e=await tc.getSlingcliConfig(zl);return H0(e),{creds:e,fromDisk:!1}}async function EB(){let{creds:t,fromDisk:e}=await _B();try{return await H1(t)}catch(n){let i=n instanceof Kp&&(n.status===401||n.status===403);if(!e||!i)throw n;if(Je("app-token: disk creds rejected (likely rotated), refetching from config service",{status:n.status}),G1(),!zl)throw new Error("Cannot rotate app credentials: on-disk creds rejected and no Slingshot user token available (please /login slingshot)");let s=await tc.getSlingcliConfig(zl);return H0(s),await H1(s)}}async function zi(t){if(t&&(zl=t),Hl&&Hl.expiresAt>Date.now())return K1(Hl.token),Hl.token;if(Gp)return(await Gp).token;let e=EB().then(i=>(Hl=i,K1(i.token),PB(i),i)).finally(()=>{Gp=null});return Gp=e,(await e).token}var Vl=null,z0=null;typeof process<"u"&&process.versions?.node&&(z0=import("node:http").then(t=>{Vl=t.createServer}));async function AB(){if(Vl||(z0&&await z0,Vl))return Vl;throw new Error("Slingshot OAuth requires Node.js")}async function V0(t){let e=await AB(),n,i,s,r=!1,o=new Promise((d,u)=>{i=d,s=u}),a=d=>{if(!r){r=!0;try{n.close()}catch{}d()}};n=e((d,u)=>{let p=new URL(d.url||"","http://127.0.0.1"),m=p.searchParams.get("code"),g=p.searchParams.get("state"),h=p.searchParams.get("clientId"),f=p.searchParams.get("error"),x=p.searchParams.get("error_description");if(f){u.writeHead(400,{"Content-Type":"text/html"}),u.end(`<html><body><h1>Login Failed</h1><p>${x||f}</p><p>You can close this window.</p></body></html>`),a(()=>s(new Error(`Login failed: ${x||f}`)));return}if(!m||!g){u.writeHead(400,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Failed</h1><p>Missing code or state in callback.</p><p>You can close this window.</p></body></html>"),a(()=>s(new Error("Missing code or state in callback")));return}u.writeHead(200,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Successful</h1><p>You can close this window and return to your terminal.</p><script>setTimeout(()=>window.close(),3000)</script></body></html>"),a(()=>i({code:m,state:g,clientId:h||""}))}),n.on("error",d=>{a(()=>s(d))});let c=setTimeout(()=>{a(()=>s(new Error("Login timeout - no callback received within 5 minutes")))},300*1e3);return n.on("close",()=>clearTimeout(c)),t&&t.addEventListener("abort",()=>{a(()=>s(new Error("Login cancelled")))}),{port:await new Promise((d,u)=>{n.once("error",u),n.listen(0,"127.0.0.1",()=>{let p=n.address();p&&typeof p=="object"?d(p.port):u(new Error("Failed to obtain loopback server port"))})}),result:o}}async function J0(t,e){if(!t)throw new Error("Missing exchange code");if(!e)throw new Error("Missing clientId for exchange");let n=we.getExchangeUrl(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",accept:"application/json"},body:JSON.stringify({code:t,clientId:e})})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Cannot reach Studio Auth: ${o}`)}if(!i.ok){let r,o=`${i.status} ${i.statusText}`;try{let a=await i.json();r=a.error?.code,a.error?.message?o=a.error.message:a.message?o=a.message:r&&(o=r)}catch{}throw r==="INVALID_CALLBACK"?new Error("Login failed: exchange code is expired, already used, or bound to a different tenant. Please log in again."):new Error(`Code exchange failed: ${o}`)}let s=await i.json();if(!s.accessToken||!s.refreshToken)throw new Error("Exchange response missing accessToken or refreshToken");return s}function LB(){return OB(16).toString("hex")}function WB(t){let e=new URL(t),n=e.searchParams.get("code"),i=e.searchParams.get("state"),s=e.searchParams.get("clientId");if(!n||!i)throw new Error("Pasted URL is missing code or state");return{code:n,state:i,clientId:s||""}}async function Q0(t){let e=process.env.SLINGSHOT_TOKEN;if(e){let d=Kl(e);return Pe("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),await zi(e),{refresh:"",access:e,expires:d>0?d-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:process.env.SLINGSHOT_PROJECT_ID,workspaceId:process.env.SLINGSHOT_WORKSPACE_ID}}let{port:n,result:i}=await V0(t.signal),s=LB(),r=we.getDefaultClientId(),o=we.getLoginUrl({port:n,localState:s,clientId:r||void 0});t.onAuth({url:o});let a;if(t.onManualCodeInput){let d=t.onManualCodeInput().then(WB);a=await Promise.race([i,d])}else a=await i;if(a.state!==s)throw new Error("CSRF check failed - state does not match localState");if(!a.clientId)throw new Error("Login callback did not include clientId");let c=await J0(a.code,a.clientId),l=Kl(c.accessToken);return await zi(c.accessToken),{refresh:c.refreshToken,access:c.accessToken,expires:l>0?l-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:void 0,workspaceId:void 0}}import{randomUUID as UB}from"node:crypto";async function Hp(t){if(!t.refresh)throw new Error("No refresh token available. Please login again.");let e;try{e=await zi()}catch(a){throw Je("auth/refresh: app token unavailable for refresh call",a),new Error(`Cannot refresh Slingshot token: app token unavailable (${a instanceof Error?a.message:String(a)}). Please /login slingshot.`)}let n=UB(),i={accept:"application/json",rt:t.refresh,"trace-id":n,Authorization:`Bearer ${e}`},s;try{let a=we.getRefreshUrl();s=await fetch(a,{headers:i})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach Slingshot server: ${c}`)}if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();c.message?a=String(c.message):c.error&&(a=String(c.error))}catch{}throw new Error(`Token refresh failed: ${a}`)}let r=await s.json();if(!r.accessToken)throw new Error("No access token in refresh response");let o=Kl(r.accessToken);try{await zi(r.accessToken)}catch(a){throw Je("auth/refresh: app token refresh failed",a),a}return{refresh:r.refreshToken||t.refresh,access:r.accessToken,expires:o>0?o-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:t.projectId,workspaceId:t.workspaceId}}var z1=[{id:"gpt-5.4-nano",name:"GPT-5.4 nano",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-4.1",name:"GPT-4.1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768,provider:"slingshot",api:"openai-completions"},{id:"gpt-5",name:"GPT-5",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-mini",name:"GPT-5 Mini",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-nano",name:"GPT-5 Nano",reasoning:!0,input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.1",name:"GPT-5.1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.2",name:"GPT-5.2",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.4",name:"GPT-5.4",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.5",name:"GPT-5.5",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"claude-opus-4@20250514",name:"Claude Opus 4",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4@20250514",name:"Claude Sonnet 4",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-5@20250929",name:"Claude Sonnet 4.5",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-opus-4-6",name:"Claude Opus 4.6",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"o3",name:"O3",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o3-mini",name:"o3-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o4-mini",name:"o4-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536,provider:"slingshot",api:"openai-completions"}];var _r={name:"slingshot.cli",private:!0,type:"module",workspaces:["packages/*","packages/web-ui/example","packages/coding-agent/examples/extensions/with-deps","packages/coding-agent/examples/extensions/custom-provider-anthropic","packages/coding-agent/examples/extensions/custom-provider-gitlab-duo"],scripts:{clean:"npm run clean --workspaces",build:"cd packages/tui && npm run build && cd ../ai && npm run build && cd ../agent && npm run build && cd ../coding-agent && npm run build && cd ../web-ui && npm run build",dev:'concurrently --names "ai,agent,coding-agent,web-ui,tui" --prefix-colors "cyan,yellow,red,white,green,magenta" "cd packages/ai && npm run dev" "cd packages/agent && npm run dev" "cd packages/coding-agent && npm run dev" "cd packages/web-ui && npm run dev" "cd packages/tui && npm run dev"',"dev:tsc":'concurrently --names "ai,web-ui" --prefix-colors "cyan,green" "cd packages/ai && npm run dev:tsc" "cd packages/web-ui && npm run dev:tsc"',check:"","check:browser-smoke":"","profile:tui":"node scripts/profile-coding-agent-node.mjs --mode tui","profile:rpc":"node scripts/profile-coding-agent-node.mjs --mode rpc",test:"npm run test --workspaces --if-present","version:patch":"npm version patch -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:minor":"npm version minor -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:major":"npm version major -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:set":"npm version -ws",prepublishOnly:"npm run clean && npm run build && npm run check",publish:"npm run prepublishOnly && npm publish -ws --access public","publish:dry":"npm run prepublishOnly && npm publish -ws --access public --dry-run","release:patch":"node scripts/release.mjs patch","release:minor":"node scripts/release.mjs minor","release:major":"node scripts/release.mjs major",prepare:"husky"},devDependencies:{"@anthropic-ai/sandbox-runtime":"0.0.26","@biomejs/biome":"2.3.5","@types/node":"22.19.19","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",esbuild:"0.28.0",husky:"9.1.7",jiti:"2.7.0",shx:"0.4.0",tsx:"4.22.1",typescript:"5.9.3"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260523-3",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","@mozilla/readability":"^0.6.0","compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0",linkedom:"^0.18.12",turndown:"^7.2.4",unpdf:"^1.6.2"}};var q1e=we.getRefreshUrl(),G1e=we.getApiBaseUrl(),K1e=we.getSageEventsUrl(),H1e=we.getTokenExpiryBuffer(),V1=we.getDefaultProjectId(),J1=we.getDefaultWorkspaceId(),Q1=we.getDefaultClientId();async function zp(t,e,n){let i=B1(),s=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!s){Pe("ERROR: No API key found");return}let r=s.startsWith("Bearer ")?s:`Bearer ${s}`,o=process.env.SLINGSHOT_PROJECT_ID||V1,a=process.env.SLINGSHOT_WORKSPACE_ID||J1,c=process.env.CLIENT_ID||Q1,l={"Content-Type":"application/json",accept:"application/json","access-token":r,"x-project-id":o,"x-workspace-id":a,"x-client-id":c,"sage-trace-id":i,"User-Agent":"pi-slingshot/1.0.0"},d=parseFloat(process.env.SLINGSHOT_TEMPERATURE||"0.2"),u=parseFloat(process.env.SLINGSHOT_TOP_P||"0.8"),p={source:_r.name||"sling",ai_model_info:{ai_provider_name:e.model?.provider||"slingshot",sage_modl_name:e.model?.id||"unknown",sage_modl_option:{temperature:String(d),max_token_size:String(e.model?.maxTokens||16834),top_p:String(u)}},rag_info:{type:null,account_name:"dummy",project_names:[],repository_names:[],programming_language:null},tab_data:{tab_count:"1"},tags:null,slingshot_version:_r.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:l,sageCommonData:p}}async function Vp(t,e,n,i){let s={eventName:t,sageCommonData:n,eventData:i};Pe(`Sending analytics event: ${t} : `+we.getSageEventsUrl());try{let r=await fetch(we.getSageEventsUrl(),{method:"POST",headers:e,body:JSON.stringify(s)});if(r.ok){let o=await r.json().catch(()=>{});if(o.error_code)throw new Error(`Analytics API error: ${o.error_code} - ${o.error_message||"No message"}`);Pe(`'SUCCESS: Event sent: ${t}`),Pe(`Response: ${JSON.stringify(o)}`),Pe("\u2500".repeat(66))}else{let o=await r.text().catch(()=>""),a={status:r.status,statusText:r.statusText,responseBody:o,requestHeaders:e};throw Pe(`ERROR: ${r.status} ${r.statusText}`),Je("Error Details",a),Je("Failed Request Body",s),new Error(`Analytics API error: ${r.status} ${r.statusText}`)}}catch(r){let o=r instanceof Error?r.message:String(r);console.warn("[Slingshot Analytics] Request that caused error:",o),Pe(`EXCEPTION: ${o}`),r instanceof Error&&r.stack&&Pe(`Stack trace: ${r.stack}`),Je("Request that caused exception",s)}}import Jl from"chalk";function Y1(t,e){return{render(n){let i=` \u26AC _______. __ __ .__ __. _______
|
|
444
|
+
`;Ls.appendFileSync(Ki,i)}catch{}}var Ws=null;function $1(t){if(!t)return;let e=t.trim();if(e)return e.replace(/\/+$/,"")}var we=class t{static{this.BASE_URL="base_url"}static{this.ANALYTICS_DOMAIN="analytics_domain"}static{this.CLIENT_ID="client_id"}static{this.PROJECT_ID="project_id"}static{this.WORKSPACE_ID="workspace_id"}static{this.defaultValues={[t.BASE_URL]:"https://sapientaiproducts.com",[t.ANALYTICS_DOMAIN]:"https://slingshot.sapientaiproducts.com",[t.CLIENT_ID]:"b97fbef7-cad9-4e56-9850-39e86c8fdf61",[t.PROJECT_ID]:"fa8121c4-e2fc-48f1-9478-8949c04e13cc",[t.WORKSPACE_ID]:"6e5756eb-d7e2-4d80-ad07-9d7a51600d85"}}static{this.LOGIN_PATH="/web/v1/studio-auth/login"}static{this.EXCHANGE_PATH="/api/v1/studio-auth/auth/desktop/exchange"}static{this.REFRESH_PATH="/api/v3/auth/refreshtoken"}static{this.REFRESH_CLIENT_NAME="machine"}static{this.API_BASE_PATH="/api/v1/llm"}static{this.SAGE_EVENTS_PATH="/api/v1/ai-portal/sage_events"}static{this.APP_TOKEN_PATH="/api/v3/auth/app-token"}static{this.CONFIG_SERVICE_PATH="/api/v2/configservice/client"}static{this.APP_TOKEN_REFRESH_BUFFER_MS=60*1e3}static{this.SLINGSHOT_APP_TOKEN_ENV="SLINGSHOT_APP_TOKEN_HEADER"}static{this.TOKEN_EXPIRY_BUFFER_MS=300*1e3}static{this.SAPI="/save/api/v1"}static{this.CLIENT_NAME="desktop"}static defaults(e){return this.defaultValues[e]}static getSettingsPath(){let e=Gl.resolve(process.cwd(),".sling","sling.settings.json");if(Hi.existsSync(e))return e;let n=_e();return Gl.resolve(n,"sling.settings.json")}static getSettings(){if(!Ws){let i=this.getSettingsPath();try{if(Hi.existsSync(i)){let s=Hi.readFileSync(i,"utf-8"),r=JSON.parse(s)||{};Ws={...this.defaultValues,...r}}else{let s=Gl.dirname(i);Hi.existsSync(s)||Hi.mkdirSync(s,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(this.defaultValues,null,2),"utf-8"),Ws={...this.defaultValues}}}catch(s){Je("Error reading/writing sling.settings.json: ",s),Ws={...this.defaultValues}}}let e=$1(process.env.SLINGSHOT_API_DOMAIN),n=$1(process.env.SLINGSHOT_ANALYTICS_DOMAIN);return{...Ws,[t.BASE_URL]:e||Ws[t.BASE_URL],[t.ANALYTICS_DOMAIN]:n||Ws[t.ANALYTICS_DOMAIN]}}static updateSettings(e){let n=_e(),i=Gl.resolve(n,"sling.settings.json");try{let r={...this.getSettings()||{},...e},o=Gl.dirname(i);Hi.existsSync(o)||Hi.mkdirSync(o,{recursive:!0}),Hi.writeFileSync(i,JSON.stringify(r,null,2),"utf-8"),Ws=r}catch(s){Je("Error updating sling.settings.json: ",s)}}static getLoginUrl(e){let n=this.getSettings(),i=new URLSearchParams({client:this.CLIENT_NAME,port:String(e.port),localState:e.localState});return e.clientId&&i.set("clientId",e.clientId),`${n[t.BASE_URL]}${this.LOGIN_PATH}?${i.toString()}`}static getExchangeUrl(){return`${this.getSettings()[t.BASE_URL]}${this.EXCHANGE_PATH}`}static getRefreshUrl(){let e=this.getSettings(),n=new URLSearchParams({client:this.REFRESH_CLIENT_NAME});return`${e[t.BASE_URL]}${this.REFRESH_PATH}?${n.toString()}`}static getApiBaseUrl(){return`${this.getSettings()[t.BASE_URL]}${this.API_BASE_PATH}`}static getSageEventsUrl(){return`${this.getSettings()[t.ANALYTICS_DOMAIN]}${this.SAGE_EVENTS_PATH}`}static getTokenExpiryBuffer(){return this.TOKEN_EXPIRY_BUFFER_MS}static getDefaultProjectId(){let e=this.getSettings();return process.env.SLINGSHOT_PROJECT_ID||e[t.PROJECT_ID]}static getDefaultWorkspaceId(){let e=this.getSettings();return process.env.SLINGSHOT_WORKSPACE_ID||e[t.WORKSPACE_ID]}static getDefaultClientId(){let e=this.getSettings();return process.env.CLIENT_ID||e[t.CLIENT_ID]}static getUserActivityUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users/activity`}static getUserUrl(){return`${this.getSettings()[t.BASE_URL]}${this.SAPI}/users`}static getAppTokenUrl(){return`${this.getSettings()[t.BASE_URL]}${this.APP_TOKEN_PATH}`}static getConfigServiceUrl(e){let n=this.getSettings(),i=this.getDefaultClientId(),s=new URLSearchParams({keys:e});return`${n[t.BASE_URL]}${this.CONFIG_SERVICE_PATH}/${i}?${s.toString()}`}static getAppTokenRefreshBuffer(){return this.APP_TOKEN_REFRESH_BUFFER_MS}};function Kl(t){try{let e=t.split(".");if(e.length!==3)return 0;let n=JSON.parse(atob(e[1]));return n.exp?n.exp*1e3:0}catch{return 0}}function jp(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function B1(){return`user_${jp()}`}var q0="Xq7Wm2zR9pLkVbN4cD8fH3jT6yG1sA5",kB=BigInt(q0.length);function MB(t){if(t.length===0)return"";let e=0n;for(let i of t){let s=q0.indexOf(i);if(s===-1)throw new Error(`Cannot decode app_key: character "${i}" is not in the expected alphabet`);e=e*kB+BigInt(s)}let n=[];for(;e>0n;)n.unshift(Number(e&0xffn)),e>>=8n;for(let i of t)if(i===q0[0])n.unshift(0);else break;return new TextDecoder().decode(new Uint8Array(n))}var G0=new Map,qp=new Map;async function IB(t,e){let n=we.getConfigServiceUrl(t);Pe(`sling-config: fetching ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e}`}})}catch(o){let a=o instanceof Error?o.message:String(o);throw new Error(`Cannot reach config service: ${a}`)}if(!i.ok){let o=`${i.status} ${i.statusText}`;try{let a=await i.json();a.message?o=String(a.message):a.error&&(o=String(a.error))}catch{}throw new Error(`Config service request failed: ${o}`)}let r=(await i.json())?.data?.config;if(!r||typeof r!="object")throw new Error("Config service response missing data.config");return r}async function N1(t,e){let n=G0.get(t);if(n)return n;let i=qp.get(t);if(i)return i;if(!e)throw new Error("Cannot reach config service: no Slingshot user token provided");let s=IB(t,e).then(r=>(G0.set(t,r),r)).finally(()=>{qp.delete(t)});return qp.set(t,s),s}var tc=class{static async getSlingcliConfig(e){let n=await N1("slingcli",e),i=n.slingcli;if(!i||typeof i.app_id!="string"||typeof i.app_key!="string"||!i.app_id||!i.app_key)throw Je("sling-config: missing slingcli block",n),new Error("Config service did not return slingcli.app_id / slingcli.app_key for this client");return{app_id:i.app_id,app_key:MB(i.app_key)}}static async getRemoteConfig(e,n){return N1(e,n)}static clearCache(){G0.clear(),qp=new Map}};import j1 from"node:path";import Us from"node:fs";var RB="sling.app-creds.json";function K0(){return j1.resolve(_e(),RB)}function q1(){let t=K0();if(!Us.existsSync(t))return null;try{let e=Us.readFileSync(t,"utf-8"),n=JSON.parse(e);return typeof n.app_id!="string"||typeof n.app_key!="string"||!n.app_id||!n.app_key?(Je("app-creds-store: invalid creds file, ignoring",n),null):{app_id:n.app_id,app_key:n.app_key}}catch(e){return Je("app-creds-store: failed to read creds file",e),null}}function H0(t){let e=K0(),n=j1.dirname(e);try{Us.existsSync(n)||Us.mkdirSync(n,{recursive:!0});let i={...t,savedAt:Date.now()};Us.writeFileSync(e,JSON.stringify(i,null,2),{encoding:"utf-8",mode:384});try{Us.chmodSync(e,384)}catch{}Pe(`app-creds-store: persisted to ${e}`)}catch(i){Je("app-creds-store: failed to persist creds",i)}}function G1(){let t=K0();try{Us.existsSync(t)&&(Us.unlinkSync(t),Pe(`app-creds-store: cleared ${t}`))}catch(e){Je("app-creds-store: failed to clear creds file",e)}}var Kp=class extends Error{constructor(n,i){super(i);this.status=n;this.name="AppTokenHttpError"}},Hl=null,zl=null,Gp=null,nc=null;function K1(t){process.env[we.SLINGSHOT_APP_TOKEN_ENV]=`Bearer ${t}`}function PB(t){nc&&(clearTimeout(nc),nc=null);let e=t.expiresAt-Date.now();e<=0||(nc=setTimeout(()=>{nc=null,zi().catch(n=>{Je("app-token: scheduled refresh failed",n)})},e),nc.unref?.())}async function H1(t){let e=Buffer.from(`${t.app_id}:${t.app_key}`).toString("base64"),n=we.getAppTokenUrl();Pe(`app-token: minting from ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${e}`}})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach app-token service: ${c}`)}if(!i.ok){let a=`${i.status} ${i.statusText}`;try{let c=await i.text()||"";c&&(a=c)}catch{}throw new Kp(i.status,`App token request failed: ${a}`)}let s=await i.json();if(!s.app_token||typeof s.expires_in!="number")throw new Error("App token response missing app_token or expires_in");let r=we.getAppTokenRefreshBuffer(),o=Date.now()+s.expires_in*1e3-r;return Pe(`app-token: minted, expires at ${new Date(o).toISOString()}`),{token:s.app_token,expiresAt:o}}async function _B(){let t=q1();if(t)return{creds:t,fromDisk:!0};if(!zl)throw new Error("Cannot mint app token: no on-disk app credentials and no Slingshot user token available (please /login slingshot first)");let e=await tc.getSlingcliConfig(zl);return H0(e),{creds:e,fromDisk:!1}}async function EB(){let{creds:t,fromDisk:e}=await _B();try{return await H1(t)}catch(n){let i=n instanceof Kp&&(n.status===401||n.status===403);if(!e||!i)throw n;if(Je("app-token: disk creds rejected (likely rotated), refetching from config service",{status:n.status}),G1(),!zl)throw new Error("Cannot rotate app credentials: on-disk creds rejected and no Slingshot user token available (please /login slingshot)");let s=await tc.getSlingcliConfig(zl);return H0(s),await H1(s)}}async function zi(t){if(t&&(zl=t),Hl&&Hl.expiresAt>Date.now())return K1(Hl.token),Hl.token;if(Gp)return(await Gp).token;let e=EB().then(i=>(Hl=i,K1(i.token),PB(i),i)).finally(()=>{Gp=null});return Gp=e,(await e).token}var Vl=null,z0=null;typeof process<"u"&&process.versions?.node&&(z0=import("node:http").then(t=>{Vl=t.createServer}));async function AB(){if(Vl||(z0&&await z0,Vl))return Vl;throw new Error("Slingshot OAuth requires Node.js")}async function V0(t){let e=await AB(),n,i,s,r=!1,o=new Promise((d,u)=>{i=d,s=u}),a=d=>{if(!r){r=!0;try{n.close()}catch{}d()}};n=e((d,u)=>{let p=new URL(d.url||"","http://127.0.0.1"),m=p.searchParams.get("code"),g=p.searchParams.get("state"),h=p.searchParams.get("clientId"),f=p.searchParams.get("error"),x=p.searchParams.get("error_description");if(f){u.writeHead(400,{"Content-Type":"text/html"}),u.end(`<html><body><h1>Login Failed</h1><p>${x||f}</p><p>You can close this window.</p></body></html>`),a(()=>s(new Error(`Login failed: ${x||f}`)));return}if(!m||!g){u.writeHead(400,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Failed</h1><p>Missing code or state in callback.</p><p>You can close this window.</p></body></html>"),a(()=>s(new Error("Missing code or state in callback")));return}u.writeHead(200,{"Content-Type":"text/html"}),u.end("<html><body><h1>Login Successful</h1><p>You can close this window and return to your terminal.</p><script>setTimeout(()=>window.close(),3000)</script></body></html>"),a(()=>i({code:m,state:g,clientId:h||""}))}),n.on("error",d=>{a(()=>s(d))});let c=setTimeout(()=>{a(()=>s(new Error("Login timeout - no callback received within 5 minutes")))},300*1e3);return n.on("close",()=>clearTimeout(c)),t&&t.addEventListener("abort",()=>{a(()=>s(new Error("Login cancelled")))}),{port:await new Promise((d,u)=>{n.once("error",u),n.listen(0,"127.0.0.1",()=>{let p=n.address();p&&typeof p=="object"?d(p.port):u(new Error("Failed to obtain loopback server port"))})}),result:o}}async function J0(t,e){if(!t)throw new Error("Missing exchange code");if(!e)throw new Error("Missing clientId for exchange");let n=we.getExchangeUrl(),i;try{i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",accept:"application/json"},body:JSON.stringify({code:t,clientId:e})})}catch(r){let o=r instanceof Error?r.message:String(r);throw new Error(`Cannot reach Studio Auth: ${o}`)}if(!i.ok){let r,o=`${i.status} ${i.statusText}`;try{let a=await i.json();r=a.error?.code,a.error?.message?o=a.error.message:a.message?o=a.message:r&&(o=r)}catch{}throw r==="INVALID_CALLBACK"?new Error("Login failed: exchange code is expired, already used, or bound to a different tenant. Please log in again."):new Error(`Code exchange failed: ${o}`)}let s=await i.json();if(!s.accessToken||!s.refreshToken)throw new Error("Exchange response missing accessToken or refreshToken");return s}function LB(){return OB(16).toString("hex")}function WB(t){let e=new URL(t),n=e.searchParams.get("code"),i=e.searchParams.get("state"),s=e.searchParams.get("clientId");if(!n||!i)throw new Error("Pasted URL is missing code or state");return{code:n,state:i,clientId:s||""}}async function Q0(t){let e=process.env.SLINGSHOT_TOKEN;if(e){let d=Kl(e);return Pe("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),await zi(e),{refresh:"",access:e,expires:d>0?d-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:process.env.SLINGSHOT_PROJECT_ID,workspaceId:process.env.SLINGSHOT_WORKSPACE_ID}}let{port:n,result:i}=await V0(t.signal),s=LB(),r=we.getDefaultClientId(),o=we.getLoginUrl({port:n,localState:s,clientId:r||void 0});t.onAuth({url:o});let a;if(t.onManualCodeInput){let d=t.onManualCodeInput().then(WB);a=await Promise.race([i,d])}else a=await i;if(a.state!==s)throw new Error("CSRF check failed - state does not match localState");if(!a.clientId)throw new Error("Login callback did not include clientId");let c=await J0(a.code,a.clientId),l=Kl(c.accessToken);return await zi(c.accessToken),{refresh:c.refreshToken,access:c.accessToken,expires:l>0?l-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:void 0,workspaceId:void 0}}import{randomUUID as UB}from"node:crypto";async function Hp(t){if(!t.refresh)throw new Error("No refresh token available. Please login again.");let e;try{e=await zi()}catch(a){throw Je("auth/refresh: app token unavailable for refresh call",a),new Error(`Cannot refresh Slingshot token: app token unavailable (${a instanceof Error?a.message:String(a)}). Please /login slingshot.`)}let n=UB(),i={accept:"application/json",rt:t.refresh,"trace-id":n,Authorization:`Bearer ${e}`},s;try{let a=we.getRefreshUrl();s=await fetch(a,{headers:i})}catch(a){let c=a instanceof Error?a.message:String(a);throw new Error(`Cannot reach Slingshot server: ${c}`)}if(!s.ok){let a=`${s.status} ${s.statusText}`;try{let c=await s.json();c.message?a=String(c.message):c.error&&(a=String(c.error))}catch{}throw new Error(`Token refresh failed: ${a}`)}let r=await s.json();if(!r.accessToken)throw new Error("No access token in refresh response");let o=Kl(r.accessToken);try{await zi(r.accessToken)}catch(a){throw Je("auth/refresh: app token refresh failed",a),a}return{refresh:r.refreshToken||t.refresh,access:r.accessToken,expires:o>0?o-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:t.projectId,workspaceId:t.workspaceId}}var z1=[{id:"gpt-5.4-nano",name:"GPT-5.4 nano",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.2,output:1.25,cacheRead:.02,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-4.1",name:"GPT-4.1",reasoning:!1,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:1047576,maxTokens:32768,provider:"slingshot",api:"openai-completions"},{id:"gpt-5",name:"GPT-5",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.125,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-mini",name:"GPT-5 Mini",reasoning:!0,input:["text","image"],cost:{input:.25,output:2,cacheRead:.025,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5-nano",name:"GPT-5 Nano",reasoning:!0,input:["text","image"],cost:{input:.05,output:.4,cacheRead:.005,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.1",name:"GPT-5.1",reasoning:!0,input:["text","image"],cost:{input:1.25,output:10,cacheRead:.13,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.2",name:"GPT-5.2",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:.75,output:4.5,cacheRead:.075,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.4",name:"GPT-5.4",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:.25,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.5",name:"GPT-5.5",reasoning:!0,thinkingLevelMap:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:"xhigh"},input:["text","image"],cost:{input:5,output:30,cacheRead:.5,cacheWrite:0},contextWindow:272e3,maxTokens:128e3,api:"openai-completions",provider:"slingshot"},{id:"gpt-5.2-codex",name:"GPT-5.2 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"gpt-5.3-codex",name:"GPT-5.3 Codex",reasoning:!0,input:["text","image"],cost:{input:1.75,output:14,cacheRead:.175,cacheWrite:0},contextWindow:4e5,maxTokens:128e3,provider:"slingshot",api:"openai-codex-responses"},{id:"claude-opus-4@20250514",name:"Claude Opus 4",reasoning:!0,input:["text","image"],cost:{input:15,output:75,cacheRead:1.5,cacheWrite:18.75},contextWindow:2e5,maxTokens:32e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4@20250514",name:"Claude Sonnet 4",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-5@20250929",name:"Claude Sonnet 4.5",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:2e5,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",reasoning:!0,input:["text","image"],cost:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},contextWindow:1e6,maxTokens:64e3,provider:"slingshot",api:"openai-completions"},{id:"claude-opus-4-6",name:"Claude Opus 4.6",reasoning:!0,input:["text","image"],cost:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},contextWindow:1e6,maxTokens:128e3,provider:"slingshot",api:"openai-completions"},{id:"o3",name:"O3",reasoning:!0,input:["text","image"],cost:{input:2,output:8,cacheRead:.5,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o3-mini",name:"o3-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.55,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"o4-mini",name:"o4-mini",reasoning:!0,input:["text"],cost:{input:1.1,output:4.4,cacheRead:.28,cacheWrite:0},contextWindow:2e5,maxTokens:1e5,provider:"slingshot",api:"openai-completions"},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",reasoning:!0,input:["text","image"],cost:{input:.3,output:2.5,cacheRead:.075,cacheWrite:0},contextWindow:1048576,maxTokens:65536,provider:"slingshot",api:"openai-completions"}];var _r={name:"slingshot.cli",private:!0,type:"module",workspaces:["packages/*","packages/web-ui/example","packages/coding-agent/examples/extensions/with-deps","packages/coding-agent/examples/extensions/custom-provider-anthropic","packages/coding-agent/examples/extensions/custom-provider-gitlab-duo"],scripts:{clean:"npm run clean --workspaces",build:"cd packages/tui && npm run build && cd ../ai && npm run build && cd ../agent && npm run build && cd ../coding-agent && npm run build && cd ../web-ui && npm run build",dev:'concurrently --names "ai,agent,coding-agent,web-ui,tui" --prefix-colors "cyan,yellow,red,white,green,magenta" "cd packages/ai && npm run dev" "cd packages/agent && npm run dev" "cd packages/coding-agent && npm run dev" "cd packages/web-ui && npm run dev" "cd packages/tui && npm run dev"',"dev:tsc":'concurrently --names "ai,web-ui" --prefix-colors "cyan,green" "cd packages/ai && npm run dev:tsc" "cd packages/web-ui && npm run dev:tsc"',check:"","check:browser-smoke":"","profile:tui":"node scripts/profile-coding-agent-node.mjs --mode tui","profile:rpc":"node scripts/profile-coding-agent-node.mjs --mode rpc",test:"npm run test --workspaces --if-present","version:patch":"npm version patch -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:minor":"npm version minor -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:major":"npm version major -ws --no-git-tag-version && node scripts/sync-versions.js && shx rm -rf node_modules packages/*/node_modules package-lock.json && npm install","version:set":"npm version -ws",prepublishOnly:"npm run clean && npm run build && npm run check",publish:"npm run prepublishOnly && npm publish -ws --access public","publish:dry":"npm run prepublishOnly && npm publish -ws --access public --dry-run","release:patch":"node scripts/release.mjs patch","release:minor":"node scripts/release.mjs minor","release:major":"node scripts/release.mjs major",prepare:"husky"},devDependencies:{"@anthropic-ai/sandbox-runtime":"0.0.26","@biomejs/biome":"2.3.5","@types/node":"22.19.19","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",esbuild:"0.28.0",husky:"9.1.7",jiti:"2.7.0",shx:"0.4.0",tsx:"4.22.1",typescript:"5.9.3"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260525-1",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","@mozilla/readability":"^0.6.0","compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0",linkedom:"^0.18.12",turndown:"^7.2.4",unpdf:"^1.6.2"}};var q1e=we.getRefreshUrl(),G1e=we.getApiBaseUrl(),K1e=we.getSageEventsUrl(),H1e=we.getTokenExpiryBuffer(),V1=we.getDefaultProjectId(),J1=we.getDefaultWorkspaceId(),Q1=we.getDefaultClientId();async function zp(t,e,n){let i=B1(),s=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!s){Pe("ERROR: No API key found");return}let r=s.startsWith("Bearer ")?s:`Bearer ${s}`,o=process.env.SLINGSHOT_PROJECT_ID||V1,a=process.env.SLINGSHOT_WORKSPACE_ID||J1,c=process.env.CLIENT_ID||Q1,l={"Content-Type":"application/json",accept:"application/json","access-token":r,"x-project-id":o,"x-workspace-id":a,"x-client-id":c,"sage-trace-id":i,"User-Agent":"pi-slingshot/1.0.0"},d=parseFloat(process.env.SLINGSHOT_TEMPERATURE||"0.2"),u=parseFloat(process.env.SLINGSHOT_TOP_P||"0.8"),p={source:_r.name||"sling",ai_model_info:{ai_provider_name:e.model?.provider||"slingshot",sage_modl_name:e.model?.id||"unknown",sage_modl_option:{temperature:String(d),max_token_size:String(e.model?.maxTokens||16834),top_p:String(u)}},rag_info:{type:null,account_name:"dummy",project_names:[],repository_names:[],programming_language:null},tab_data:{tab_count:"1"},tags:null,slingshot_version:_r.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:l,sageCommonData:p}}async function Vp(t,e,n,i){let s={eventName:t,sageCommonData:n,eventData:i};Pe(`Sending analytics event: ${t} : `+we.getSageEventsUrl());try{let r=await fetch(we.getSageEventsUrl(),{method:"POST",headers:e,body:JSON.stringify(s)});if(r.ok){let o=await r.json().catch(()=>{});if(o.error_code)throw new Error(`Analytics API error: ${o.error_code} - ${o.error_message||"No message"}`);Pe(`'SUCCESS: Event sent: ${t}`),Pe(`Response: ${JSON.stringify(o)}`),Pe("\u2500".repeat(66))}else{let o=await r.text().catch(()=>""),a={status:r.status,statusText:r.statusText,responseBody:o,requestHeaders:e};throw Pe(`ERROR: ${r.status} ${r.statusText}`),Je("Error Details",a),Je("Failed Request Body",s),new Error(`Analytics API error: ${r.status} ${r.statusText}`)}}catch(r){let o=r instanceof Error?r.message:String(r);console.warn("[Slingshot Analytics] Request that caused error:",o),Pe(`EXCEPTION: ${o}`),r instanceof Error&&r.stack&&Pe(`Stack trace: ${r.stack}`),Je("Request that caused exception",s)}}import Jl from"chalk";function Y1(t,e){return{render(n){let i=` \u26AC _______. __ __ .__ __. _______
|
|
445
445
|
\u274D \xB7 \u274D / || | | | | \\ | | / _____|
|
|
446
446
|
\u2726 \u26AC \u2726 | (----\`| | | | | \\| | | | __
|
|
447
447
|
\u26AC \xB7 \u26AC \u26AC \xB7 \u26AC \\ \\ | | | | | . \` | | | |_ |
|