@psnext/slingcli 2.4.20260520-2 → 2.4.20260520-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@psnext/slingcli",
3
- "version": "2.4.20260520-2",
3
+ "version": "2.4.20260520-3",
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.20260520-2",
32
+ "slingVersion": "2.4.20260520-3",
33
33
  "dependencies": {
34
34
  "@earendil-works/pi-tui": "file:../.sling-pack/earendil-works-pi-tui-0.74.0.tgz",
35
35
  "@earendil-works/pi-ai": "file:../.sling-pack/earendil-works-pi-ai-0.74.0.tgz",
@@ -437,7 +437,7 @@ Log file: ${qi}
437
437
  `;Os.appendFileSync(qi,n)}catch{}}function gt(t,e){if(!(!qi||!Os||!Al))try{let i=`[${new Date().toISOString()}] ${t}:
438
438
  ${JSON.stringify(e,null,2)}
439
439
 
440
- `;Os.appendFileSync(qi,i)}catch{}}var Ls=null;function f1(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=Ll.resolve(process.cwd(),".sling","sling.settings.json");if(Gi.existsSync(e))return e;let n=Le();return Ll.resolve(n,"sling.settings.json")}static getSettings(){if(!Ls){let i=this.getSettingsPath();try{if(Gi.existsSync(i)){let s=Gi.readFileSync(i,"utf-8"),o=JSON.parse(s)||{};Ls={...this.defaultValues,...o}}else{let s=Ll.dirname(i);Gi.existsSync(s)||Gi.mkdirSync(s,{recursive:!0}),Gi.writeFileSync(i,JSON.stringify(this.defaultValues,null,2),"utf-8"),Ls={...this.defaultValues}}}catch(s){gt("Error reading/writing sling.settings.json: ",s),Ls={...this.defaultValues}}}let e=f1(process.env.SLINGSHOT_API_DOMAIN),n=f1(process.env.SLINGSHOT_ANALYTICS_DOMAIN);return{...Ls,[t.BASE_URL]:e||Ls[t.BASE_URL],[t.ANALYTICS_DOMAIN]:n||Ls[t.ANALYTICS_DOMAIN]}}static updateSettings(e){let n=Le(),i=Ll.resolve(n,"sling.settings.json");try{let o={...this.getSettings()||{},...e},r=Ll.dirname(i);Gi.existsSync(r)||Gi.mkdirSync(r,{recursive:!0}),Gi.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),Ls=o}catch(s){gt("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}/user-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 Wl(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 Sp(){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_${Sp()}`}var w0="Xq7Wm2zR9pLkVbN4cD8fH3jT6yG1sA5",O$=BigInt(w0.length);function L$(t){if(t.length===0)return"";let e=0n;for(let i of t){let s=w0.indexOf(i);if(s===-1)throw new Error(`Cannot decode app_key: character "${i}" is not in the expected alphabet`);e=e*O$+BigInt(s)}let n=[];for(;e>0n;)n.unshift(Number(e&0xffn)),e>>=8n;for(let i of t)if(i===w0[0])n.unshift(0);else break;return new TextDecoder().decode(new Uint8Array(n))}var S0=new Map,Cp=new Map;async function W$(t,e){let n=we.getConfigServiceUrl(t);Ne(`sling-config: fetching ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e}`}})}catch(r){let a=r instanceof Error?r.message:String(r);throw new Error(`Cannot reach config service: ${a}`)}if(!i.ok){let r=`${i.status} ${i.statusText}`;try{let a=await i.json();a.message?r=String(a.message):a.error&&(r=String(a.error))}catch{}throw new Error(`Config service request failed: ${r}`)}let o=(await i.json())?.data?.config;if(!o||typeof o!="object")throw new Error("Config service response missing data.config");return o}async function x1(t,e){let n=S0.get(t);if(n)return n;let i=Cp.get(t);if(i)return i;if(!e)throw new Error("Cannot reach config service: no Slingshot user token provided");let s=W$(t,e).then(o=>(S0.set(t,o),o)).finally(()=>{Cp.delete(t)});return Cp.set(t,s),s}var Ul=class{static async getSlingcliConfig(e){let n=await x1("slingcli",e),i=n.slingcli;if(!i||typeof i.app_id!="string"||typeof i.app_key!="string"||!i.app_id||!i.app_key)throw gt("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:L$(i.app_key)}}static async getRemoteConfig(e,n){return x1(e,n)}static clearCache(){S0.clear(),Cp=new Map}};var Fl=null,C0=null,Tp=null,Qa=null;function v1(t){process.env[we.SLINGSHOT_APP_TOKEN_ENV]=`Bearer ${t}`}function U$(t){Qa&&(clearTimeout(Qa),Qa=null);let e=t.expiresAt-Date.now();e<=0||(Qa=setTimeout(()=>{Qa=null,Ki().catch(n=>{gt("app-token: scheduled refresh failed",n)})},e),Qa.unref?.())}async function F$(t){let{app_id:e,app_key:n}=await Ul.getSlingcliConfig(t),i=Buffer.from(`${e}:${n}`).toString("base64"),s=we.getAppTokenUrl();Ne(`app-token: minting from ${s}`);let o;try{o=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}})}catch(l){let d=l instanceof Error?l.message:String(l);throw new Error(`Cannot reach app-token service: ${d}`)}if(!o.ok){let l=`${o.status} ${o.statusText}`;try{let d=await o.text()||"";d&&(l=d)}catch{}throw new Error(`App token request failed: ${l}`)}let r=await o.json();if(!r.app_token||typeof r.expires_in!="number")throw new Error("App token response missing app_token or expires_in");let a=we.getAppTokenRefreshBuffer(),c=Date.now()+r.expires_in*1e3-a;return Ne(`app-token: minted, expires at ${new Date(c).toISOString()}`),{token:r.app_token,expiresAt:c}}async function Ki(t){if(t&&(C0=t),Fl&&Fl.expiresAt>Date.now())return v1(Fl.token),Fl.token;if(Tp)return(await Tp).token;if(!C0)throw new Error("Cannot mint app token: no Slingshot user token available (please /login slingshot first)");let n=F$(C0).then(s=>(Fl=s,v1(s.token),U$(s),s)).finally(()=>{Tp=null});return Tp=n,(await n).token}var Dl=null,T0=null;typeof process<"u"&&process.versions?.node&&(T0=import("node:http").then(t=>{Dl=t.createServer}));async function D$(){if(Dl||(T0&&await T0,Dl))return Dl;throw new Error("Slingshot OAuth requires Node.js")}async function k0(t){let e=await D$(),n,i,s,o=!1,r=new Promise((d,u)=>{i=d,s=u}),a=d=>{if(!o){o=!0;try{n.close()}catch{}d()}};n=e((d,u)=>{let p=new URL(d.url||"","http://127.0.0.1"),h=p.searchParams.get("code"),g=p.searchParams.get("state"),m=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(!h||!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:h,state:g,clientId:m||""}))}),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:r}}async function M0(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(o){let r=o instanceof Error?o.message:String(o);throw new Error(`Cannot reach Studio Auth: ${r}`)}if(!i.ok){let o,r=`${i.status} ${i.statusText}`;try{let a=await i.json();o=a.error?.code,a.error?.message?r=a.error.message:a.message?r=a.message:o&&(r=o)}catch{}throw o==="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: ${r}`)}let s=await i.json();if(!s.accessToken||!s.refreshToken)throw new Error("Exchange response missing accessToken or refreshToken");return s}function B$(){return $$(16).toString("hex")}function N$(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 I0(t){let e=process.env.SLINGSHOT_TOKEN;if(e){let d=Wl(e);return console.log("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),await Ki(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 k0(t.signal),s=B$(),o=we.getDefaultClientId(),r=we.getLoginUrl({port:n,localState:s,clientId:o||void 0});t.onAuth({url:r});let a;if(t.onManualCodeInput){let d=t.onManualCodeInput().then(N$);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 M0(a.code,a.clientId),l=Wl(c.accessToken);return await Ki(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 j$}from"node:crypto";async function kp(t){if(!t.refresh)throw new Error("No refresh token available. Please login again.");let e;try{e=await Ki()}catch(a){throw gt("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=j$(),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 o=await s.json();if(!o.accessToken)throw new Error("No access token in refresh response");let r=Wl(o.accessToken);try{await Ki(o.accessToken)}catch(a){throw gt("auth/refresh: app token refresh failed",a),a}return{refresh:o.refreshToken||t.refresh,access:o.accessToken,expires:r>0?r-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:t.projectId,workspaceId:t.workspaceId}}var y1=[{id:"gpt-5.4-nano",name:"GPT-5.4 nano",reasoning:!0,thinkingLevelMap:{off: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,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,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,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-completions"},{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-completions"},{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 _o={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","packages/coding-agent/examples/extensions/custom-provider-qwen-cli"],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.18","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",esbuild:"^0.25.0",husky:"^9.1.7",jiti:"^2.7.0",shx:"^0.4.0",tsx:"^4.20.3",typescript:"^5.9.2"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260520-2",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0"}};var wke=we.getRefreshUrl(),Ske=we.getApiBaseUrl(),Cke=we.getSageEventsUrl(),Tke=we.getTokenExpiryBuffer(),w1=we.getDefaultProjectId(),S1=we.getDefaultWorkspaceId(),C1=we.getDefaultClientId();async function Mp(t,e,n){let i=b1(),s=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!s){Ne("ERROR: No API key found");return}let o=s.startsWith("Bearer ")?s:`Bearer ${s}`,r=process.env.SLINGSHOT_PROJECT_ID||w1,a=process.env.SLINGSHOT_WORKSPACE_ID||S1,c=process.env.CLIENT_ID||C1,l={"Content-Type":"application/json",accept:"application/json","access-token":o,"x-project-id":r,"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:_o.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:_o.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:l,sageCommonData:p}}async function Ip(t,e,n,i){let s={eventName:t,sageCommonData:n,eventData:i};Ne(`Sending analytics event: ${t} : `+we.getSageEventsUrl());try{let o=await fetch(we.getSageEventsUrl(),{method:"POST",headers:e,body:JSON.stringify(s)});if(o.ok){let r=await o.json().catch(()=>{});if(r.error_code)throw new Error(`Analytics API error: ${r.error_code} - ${r.error_message||"No message"}`);Ne(`'SUCCESS: Event sent: ${t}`),Ne(`Response: ${JSON.stringify(r)}`),Ne("\u2500".repeat(66))}else{let r=await o.text().catch(()=>""),a={status:o.status,statusText:o.statusText,responseBody:r,requestHeaders:e};throw Ne(`ERROR: ${o.status} ${o.statusText}`),gt("Error Details",a),gt("Failed Request Body",s),new Error(`Analytics API error: ${o.status} ${o.statusText}`)}}catch(o){let r=o instanceof Error?o.message:String(o);console.warn("[Slingshot Analytics] Request that caused error:",r),Ne(`EXCEPTION: ${r}`),o instanceof Error&&o.stack&&Ne(`Stack trace: ${o.stack}`),gt("Request that caused exception",s)}}import $l from"chalk";function T1(t,e){return{render(n){let i=` \u26AC _______. __ __ .__ __. _______
440
+ `;Os.appendFileSync(qi,i)}catch{}}var Ls=null;function f1(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=Ll.resolve(process.cwd(),".sling","sling.settings.json");if(Gi.existsSync(e))return e;let n=Le();return Ll.resolve(n,"sling.settings.json")}static getSettings(){if(!Ls){let i=this.getSettingsPath();try{if(Gi.existsSync(i)){let s=Gi.readFileSync(i,"utf-8"),o=JSON.parse(s)||{};Ls={...this.defaultValues,...o}}else{let s=Ll.dirname(i);Gi.existsSync(s)||Gi.mkdirSync(s,{recursive:!0}),Gi.writeFileSync(i,JSON.stringify(this.defaultValues,null,2),"utf-8"),Ls={...this.defaultValues}}}catch(s){gt("Error reading/writing sling.settings.json: ",s),Ls={...this.defaultValues}}}let e=f1(process.env.SLINGSHOT_API_DOMAIN),n=f1(process.env.SLINGSHOT_ANALYTICS_DOMAIN);return{...Ls,[t.BASE_URL]:e||Ls[t.BASE_URL],[t.ANALYTICS_DOMAIN]:n||Ls[t.ANALYTICS_DOMAIN]}}static updateSettings(e){let n=Le(),i=Ll.resolve(n,"sling.settings.json");try{let o={...this.getSettings()||{},...e},r=Ll.dirname(i);Gi.existsSync(r)||Gi.mkdirSync(r,{recursive:!0}),Gi.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),Ls=o}catch(s){gt("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 Wl(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 Sp(){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_${Sp()}`}var w0="Xq7Wm2zR9pLkVbN4cD8fH3jT6yG1sA5",O$=BigInt(w0.length);function L$(t){if(t.length===0)return"";let e=0n;for(let i of t){let s=w0.indexOf(i);if(s===-1)throw new Error(`Cannot decode app_key: character "${i}" is not in the expected alphabet`);e=e*O$+BigInt(s)}let n=[];for(;e>0n;)n.unshift(Number(e&0xffn)),e>>=8n;for(let i of t)if(i===w0[0])n.unshift(0);else break;return new TextDecoder().decode(new Uint8Array(n))}var S0=new Map,Cp=new Map;async function W$(t,e){let n=we.getConfigServiceUrl(t);Ne(`sling-config: fetching ${n}`);let i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${e}`}})}catch(r){let a=r instanceof Error?r.message:String(r);throw new Error(`Cannot reach config service: ${a}`)}if(!i.ok){let r=`${i.status} ${i.statusText}`;try{let a=await i.json();a.message?r=String(a.message):a.error&&(r=String(a.error))}catch{}throw new Error(`Config service request failed: ${r}`)}let o=(await i.json())?.data?.config;if(!o||typeof o!="object")throw new Error("Config service response missing data.config");return o}async function x1(t,e){let n=S0.get(t);if(n)return n;let i=Cp.get(t);if(i)return i;if(!e)throw new Error("Cannot reach config service: no Slingshot user token provided");let s=W$(t,e).then(o=>(S0.set(t,o),o)).finally(()=>{Cp.delete(t)});return Cp.set(t,s),s}var Ul=class{static async getSlingcliConfig(e){let n=await x1("slingcli",e),i=n.slingcli;if(!i||typeof i.app_id!="string"||typeof i.app_key!="string"||!i.app_id||!i.app_key)throw gt("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:L$(i.app_key)}}static async getRemoteConfig(e,n){return x1(e,n)}static clearCache(){S0.clear(),Cp=new Map}};var Fl=null,C0=null,Tp=null,Qa=null;function v1(t){process.env[we.SLINGSHOT_APP_TOKEN_ENV]=`Bearer ${t}`}function U$(t){Qa&&(clearTimeout(Qa),Qa=null);let e=t.expiresAt-Date.now();e<=0||(Qa=setTimeout(()=>{Qa=null,Ki().catch(n=>{gt("app-token: scheduled refresh failed",n)})},e),Qa.unref?.())}async function F$(t){let{app_id:e,app_key:n}=await Ul.getSlingcliConfig(t),i=Buffer.from(`${e}:${n}`).toString("base64"),s=we.getAppTokenUrl();Ne(`app-token: minting from ${s}`);let o;try{o=await fetch(s,{method:"GET",headers:{Accept:"application/json",Authorization:`Basic ${i}`}})}catch(l){let d=l instanceof Error?l.message:String(l);throw new Error(`Cannot reach app-token service: ${d}`)}if(!o.ok){let l=`${o.status} ${o.statusText}`;try{let d=await o.text()||"";d&&(l=d)}catch{}throw new Error(`App token request failed: ${l}`)}let r=await o.json();if(!r.app_token||typeof r.expires_in!="number")throw new Error("App token response missing app_token or expires_in");let a=we.getAppTokenRefreshBuffer(),c=Date.now()+r.expires_in*1e3-a;return Ne(`app-token: minted, expires at ${new Date(c).toISOString()}`),{token:r.app_token,expiresAt:c}}async function Ki(t){if(t&&(C0=t),Fl&&Fl.expiresAt>Date.now())return v1(Fl.token),Fl.token;if(Tp)return(await Tp).token;if(!C0)throw new Error("Cannot mint app token: no Slingshot user token available (please /login slingshot first)");let n=F$(C0).then(s=>(Fl=s,v1(s.token),U$(s),s)).finally(()=>{Tp=null});return Tp=n,(await n).token}var Dl=null,T0=null;typeof process<"u"&&process.versions?.node&&(T0=import("node:http").then(t=>{Dl=t.createServer}));async function D$(){if(Dl||(T0&&await T0,Dl))return Dl;throw new Error("Slingshot OAuth requires Node.js")}async function k0(t){let e=await D$(),n,i,s,o=!1,r=new Promise((d,u)=>{i=d,s=u}),a=d=>{if(!o){o=!0;try{n.close()}catch{}d()}};n=e((d,u)=>{let p=new URL(d.url||"","http://127.0.0.1"),h=p.searchParams.get("code"),g=p.searchParams.get("state"),m=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(!h||!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:h,state:g,clientId:m||""}))}),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:r}}async function M0(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(o){let r=o instanceof Error?o.message:String(o);throw new Error(`Cannot reach Studio Auth: ${r}`)}if(!i.ok){let o,r=`${i.status} ${i.statusText}`;try{let a=await i.json();o=a.error?.code,a.error?.message?r=a.error.message:a.message?r=a.message:o&&(r=o)}catch{}throw o==="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: ${r}`)}let s=await i.json();if(!s.accessToken||!s.refreshToken)throw new Error("Exchange response missing accessToken or refreshToken");return s}function B$(){return $$(16).toString("hex")}function N$(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 I0(t){let e=process.env.SLINGSHOT_TOKEN;if(e){let d=Wl(e);return console.log("Using Slingshot token from SLINGSHOT_TOKEN environment variable"),await Ki(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 k0(t.signal),s=B$(),o=we.getDefaultClientId(),r=we.getLoginUrl({port:n,localState:s,clientId:o||void 0});t.onAuth({url:r});let a;if(t.onManualCodeInput){let d=t.onManualCodeInput().then(N$);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 M0(a.code,a.clientId),l=Wl(c.accessToken);return await Ki(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 j$}from"node:crypto";async function kp(t){if(!t.refresh)throw new Error("No refresh token available. Please login again.");let e;try{e=await Ki()}catch(a){throw gt("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=j$(),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 o=await s.json();if(!o.accessToken)throw new Error("No access token in refresh response");let r=Wl(o.accessToken);try{await Ki(o.accessToken)}catch(a){throw gt("auth/refresh: app token refresh failed",a),a}return{refresh:o.refreshToken||t.refresh,access:o.accessToken,expires:r>0?r-we.getTokenExpiryBuffer():Date.now()+10800*1e3,projectId:t.projectId,workspaceId:t.workspaceId}}var y1=[{id:"gpt-5.4-nano",name:"GPT-5.4 nano",reasoning:!0,thinkingLevelMap:{off: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,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,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,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-completions"},{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-completions"},{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 _o={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","packages/coding-agent/examples/extensions/custom-provider-qwen-cli"],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.18","@typescript/native-preview":"7.0.0-dev.20260120.1",concurrently:"^9.2.1",esbuild:"^0.25.0",husky:"^9.1.7",jiti:"^2.7.0",shx:"^0.4.0",tsx:"^4.20.3",typescript:"^5.9.2"},engines:{node:">=20.0.0"},slingVersion:"2.4.20260520-3",overrides:{rimraf:"6.1.3","fast-xml-parser":"5.7.2",gaxios:{rimraf:"6.1.3"}},dependencies:{"@modelcontextprotocol/sdk":"^1.29.0","compound-engineering-pi":"^0.2.4","get-east-asian-width":"^1.4.0"}};var wke=we.getRefreshUrl(),Ske=we.getApiBaseUrl(),Cke=we.getSageEventsUrl(),Tke=we.getTokenExpiryBuffer(),w1=we.getDefaultProjectId(),S1=we.getDefaultWorkspaceId(),C1=we.getDefaultClientId();async function Mp(t,e,n){let i=b1(),s=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot");if(!s){Ne("ERROR: No API key found");return}let o=s.startsWith("Bearer ")?s:`Bearer ${s}`,r=process.env.SLINGSHOT_PROJECT_ID||w1,a=process.env.SLINGSHOT_WORKSPACE_ID||S1,c=process.env.CLIENT_ID||C1,l={"Content-Type":"application/json",accept:"application/json","access-token":o,"x-project-id":r,"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:_o.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:_o.slingVersion||"2.3.2",chat_type:"agent",...n||{}};return{headers:l,sageCommonData:p}}async function Ip(t,e,n,i){let s={eventName:t,sageCommonData:n,eventData:i};Ne(`Sending analytics event: ${t} : `+we.getSageEventsUrl());try{let o=await fetch(we.getSageEventsUrl(),{method:"POST",headers:e,body:JSON.stringify(s)});if(o.ok){let r=await o.json().catch(()=>{});if(r.error_code)throw new Error(`Analytics API error: ${r.error_code} - ${r.error_message||"No message"}`);Ne(`'SUCCESS: Event sent: ${t}`),Ne(`Response: ${JSON.stringify(r)}`),Ne("\u2500".repeat(66))}else{let r=await o.text().catch(()=>""),a={status:o.status,statusText:o.statusText,responseBody:r,requestHeaders:e};throw Ne(`ERROR: ${o.status} ${o.statusText}`),gt("Error Details",a),gt("Failed Request Body",s),new Error(`Analytics API error: ${o.status} ${o.statusText}`)}}catch(o){let r=o instanceof Error?o.message:String(o);console.warn("[Slingshot Analytics] Request that caused error:",r),Ne(`EXCEPTION: ${r}`),o instanceof Error&&o.stack&&Ne(`Stack trace: ${o.stack}`),gt("Request that caused exception",s)}}import $l from"chalk";function T1(t,e){return{render(n){let i=` \u26AC _______. __ __ .__ __. _______
441
441
  \u274D \xB7 \u274D / || | | | | \\ | | / _____|
442
442
  \u2726 \u26AC \u2726 | (----\`| | | | | \\| | | | __
443
443
  \u26AC \xB7 \u26AC \u26AC \xB7 \u26AC \\ \\ | | | | | . \` | | | |_ |
@@ -522,7 +522,7 @@ Output only the message, nothing else.`;var C6="You generate short themed loadin
522
522
  ${i.message}`,h=await a.branchWithSummary(c,p);return hn=i,hn.nid=h,hn.tid=c,hn.enrichedMessage=p,{content:[{type:"text",text:"checkout start"}],details:{}}}}),t.on("turn_end",async(n,i)=>{hn&&i.abort()}),t.on("agent_end",async(n,i)=>{hn&&wm&&(await wm.navigateTree(hn.nid,{summarize:!1}),i.ui.notify(`Checked out ${hn.target}${hn.target===hn.tid?"":`(${hn.tid})`}
523
523
  Backup tag created: ${hn.backupTag||"none"}
524
524
  message: ${hn.enrichedMessage}`,"info"),hn=null,t.sendMessage({customType:"ss-context",content:"context_checkout complete. A summary of your previous branch was injected above. Read it to understand your new state. Execute the 'Next Step' from the summary",display:!1},{triggerTurn:!0}))})}function xA(t){t.registerCommand("ss:context",{description:"Show context usage visualization",handler:async(e,n)=>{let i=await n.getContextUsage();if(!i){n.ui.notify("Context usage info not available.","warning");return}let o=n.sessionManager.getBranch(),r=n.getSystemPrompt(),a=t.getActiveTools(),l=t.getAllTools().filter(M=>a.includes(M.name)),d=M=>Math.ceil(M.length/4),u=0,p=0,h=0;for(let M of o)if(M.type==="message"){let I=M.message;if(I.role==="user"){if(typeof I.content=="string")u+=d(I.content);else if(Array.isArray(I.content))for(let R of I.content)R.type==="text"&&(u+=d(R.text))}else if(I.role==="assistant"){if(typeof I.content=="string")u+=d(I.content);else if(Array.isArray(I.content))for(let R of I.content)R.type==="text"&&(u+=d(R.text)),R.type==="toolCall"&&(p+=d(JSON.stringify(R)))}else if(I.role==="toolResult"){if(Array.isArray(I.content))for(let R of I.content)R.type==="text"&&(h+=d(R.text))}else I.role==="bashExecution"&&(p+=d(I.command||""))}else(M.type==="branch_summary"||M.type==="compaction")&&(u+=d(M.summary||""));let g=d(r),m=d(JSON.stringify(l)),f=i.tokens,x=i.contextWindow;if(f==null||x==null||i.percent==null){n.ui.notify("Context usage info not available.","warning");return}let v=g+m+u+p+h,w=v>0?f/v:1,P=Math.round(g*w),E=Math.round(m*w),_=Math.round(u*w),L=Math.round(p*w),A=Math.round(h*w);await n.ui.custom((M,I,R,F)=>{let W=new H;W.addChild(new V(te=>I.fg("accent",te))),W.addChild(new O(I.fg("accent",I.bold(" Context Usage")),1,0)),W.addChild(new U(1));let N=[{label:"System Prompt",value:P,color:"muted"},{label:"System Tools",value:E,color:"dim"},{label:"Tool Call",value:L+A,color:"success"},{label:"Messages",value:_,color:"accent"}],j=Math.max(0,f-(P+E+_+L+A));j>10&&N.push({label:"Other",value:j,color:"dim"}),N.push({label:"Available",value:Math.max(0,x-f),color:"borderMuted"});let K=10,ue=5,be=K*ue,Te=[];for(N.forEach(te=>{if(te.label==="Available")return;let fe=Math.round(te.value/x*be);fe===0&&te.value>0&&(fe=1);for(let xe=0;xe<fe&&Te.length<be;xe++)Te.push({color:te.color,filled:!0})});Te.length<be;)Te.push({color:"borderMuted",filled:!1});let de=[];for(let te=0;te<ue;te++){let fe="";for(let xe=0;xe<K;xe++){let tt=Te[te*K+xe];fe+=I.fg(tt.color,tt.filled?"\u25A0 ":"\u25A1 ")}de.push(fe.trimEnd())}let Ie=`${I.fg("text",I.bold("Total Usage".padEnd(16)))} ${I.fg("text",I.bold(Mc(f).padStart(7)))} ${I.fg("text",I.bold(`(${i.percent.toFixed(1).padStart(5)}%)`))}`,et=N.map(te=>{let fe=te.label.padEnd(14),xe=Mc(te.value).padStart(7),tt=(te.value/x*100).toFixed(1).padStart(5),At=te.label==="Available"?"\u25A1":"\u25A0";return`${I.fg(te.color,At)} ${I.fg("text",fe)} ${I.fg("accent",xe)} (${tt}%)`}),Fe=[Ie,"",...et],oi=20,jt=Math.max(de.length,Fe.length);for(let te=0;te<jt;te++){let fe=(de[te]||"").padEnd(oi),xe=Fe[te]||"";W.addChild(new O(` ${fe} ${xe}`,1,0))}return W.addChild(new U(1)),W.addChild(new O(I.fg("dim"," Press any key to close"),1,0)),W.addChild(new V(te=>I.fg("accent",te))),{render:te=>W.render(te),invalidate:()=>W.invalidate(),handleInput:te=>F(void 0)}},{overlay:!0})}})}import{basename as vA,dirname as wA,join as coe,relative as SA}from"node:path";var _y=["by-source","a-z","active-first"],loe={"by-source":"By source","a-z":"A\u2013Z","active-first":"Active first"};function uoe(t){let e=_y.indexOf(t);return _y[(e+1)%_y.length]??"by-source"}function doe(t){return t.origin==="package"?`${t.source} (${t.scope})`:t.source==="auto"?t.scope==="user"?"User (~/.sling/agent/)":"Project (.sling/)":t.scope==="user"?"User settings":"Project settings"}function poe(t){let e=new Map;for(let i of t){let{path:s,enabled:o,metadata:r}=i,a=`${r.origin}:${r.scope}:${r.source}`;e.has(a)||e.set(a,{key:a,label:doe(r),scope:r.scope,origin:r.origin,source:r.source,items:[]});let c=vA(s),l=vA(wA(s)),d=c==="SKILL.md"?l:c.endsWith(".md")?c.replace(/\.md$/,""):c;e.get(a)?.items.push({path:s,enabled:o,metadata:r,displayName:d,groupKey:a})}let n=Array.from(e.values());n.sort((i,s)=>i.origin!==s.origin?i.origin==="package"?-1:1:i.scope!==s.scope?i.scope==="user"?-1:1:i.source.localeCompare(s.source));for(let i of n)i.items.sort((s,o)=>s.displayName.localeCompare(o.displayName));return n}function hoe(t){let e=[];for(let n of t){e.push({type:"group",group:n});for(let i of n.items)e.push({type:"item",item:i})}return e}function moe(t){let e=t.flatMap(n=>n.items);return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)),e.map(n=>({type:"item",item:n}))}function goe(t){let e=t.flatMap(n=>n.items);return e.sort((n,i)=>n.enabled!==i.enabled?n.enabled?-1:1:n.displayName.localeCompare(i.displayName)),e.map(n=>({type:"item",item:n}))}function yA(t,e){switch(e){case"by-source":return hoe(t);case"a-z":return moe(t);case"active-first":return goe(t)}}function foe(t){let e=t.trim();if(e.length===0)return;if(e.startsWith("/")){let i=e.slice(1).toLowerCase();return i.length===0?void 0:s=>s.path.toLowerCase().includes(i)}if(e.startsWith("@")){let i=e.slice(1).toLowerCase();return i.length===0?void 0:s=>s.metadata.source.toLowerCase().includes(i)}let n=e.toLowerCase();return i=>i.displayName.toLowerCase().includes(n)}function boe(t,e){let n=Le(),i=coe(e,".sling"),s=t.metadata.scope==="project"?i:n;return SA(s,t.path)}function xoe(t){let e=t.metadata.baseDir??wA(t.path);return SA(e,t.path)}function CA(t){return t.startsWith("!")||t.startsWith("+")||t.startsWith("-")?t.slice(1):t}function voe(t,e,n,i){let s=t.metadata.scope,r=[...(s==="project"?n.getProjectSettings():n.getGlobalSettings()).skills??[]],a=boe(t,i),c=r.filter(l=>CA(l)!==a);c.push(e?`+${a}`:`-${a}`),s==="project"?n.setProjectSkillPaths(c):n.setSkillPaths(c)}function yoe(t,e,n){let i=t.metadata.scope,o=[...(i==="project"?n.getProjectSettings():n.getGlobalSettings()).packages??[]],r=o.findIndex(p=>(typeof p=="string"?p:p.source)===t.metadata.source);if(r===-1)return;let a=o[r];if(a===void 0)return;typeof a=="string"&&(a={source:a},o[r]=a);let c=[...a.skills??[]],l=xoe(t),d=c.filter(p=>CA(p)!==l);d.push(e?`+${l}`:`-${l}`),d.length>0?a.skills=d:delete a.skills,a.extensions!==void 0||a.skills!==void 0||a.prompts!==void 0||a.themes!==void 0||(o[r]=a.source),i==="project"?n.setProjectPackages(o):n.setPackages(o)}function woe(t,e,n,i){t.metadata.origin==="top-level"?voe(t,e,n,i):yoe(t,e,n)}function Py(t){t.registerCommand("ss:skills-manager",{description:"Enable/disable skills",getArgumentCompletions:e=>{let n=[{value:"list",description:"List skills with enabled/disabled state"}],i=(e??"").toLowerCase(),s=n.filter(o=>o.value.startsWith(i)||o.description.toLowerCase().includes(i));return s.length>0?s.map(o=>({value:o.value,label:`${o.value} - ${o.description}`})):null},handler:async(e,n)=>{let i=n.cwd,s=Le(),o=hi.create(i,s),c=(await new $i({cwd:i,agentDir:s,settingsManager:o}).resolve()).skills;if(c.length===0){n.ui.notify("No skills found.","info");return}let l=poe(c);if(e.trim().toLowerCase()==="list"||!n.hasUI){let p=[];for(let h of l){p.push(`${h.label}`);for(let g of h.items){let m=g.enabled?"[x]":"[ ]";p.push(` ${m} ${g.displayName}`)}}n.ui.notify(p.join(`
525
- `),"info");return}let u=0;if(await n.ui.custom((p,h,g,m)=>{let f="by-source",x=yA(l,f),v=[...x],w=v.findIndex(W=>W.type==="item");w<0&&(w=0);let P=new Je;function E(W,N){let j=W+N;for(;j>=0&&j<v.length;){if(v[j]?.type==="item")return j;j+=N}return W}function _(W){let N=foe(W);if(!N){v=[...x],A();return}let j=new Set,K=new Set;for(let ue of x)ue.type==="item"&&N(ue.item)&&j.add(ue.item);for(let ue of l)for(let be of ue.items)j.has(be)&&K.add(ue);v=[];for(let ue of x)(ue.type==="group"&&K.has(ue.group)||ue.type==="item"&&j.has(ue.item))&&v.push(ue);A()}function L(){x=yA(l,f),_(P.getValue())}function A(){let W=v.findIndex(N=>N.type==="item");w=W>=0?W:0}let M={invalidate(){},render(W){let N=h.bold("Skill Configuration"),j=h.fg("muted"," \xB7 "),K=ut("space","toggle")+j+ut("tab","view")+j+ut("esc","close"),ue=q(K),be=q(N),Te=Math.max(1,W-be-ue);return[X(`${N}${" ".repeat(Te)}${K}`,W,""),h.fg("muted","Filter: name \xB7 /path \xB7 @source")]}},I=15,R={invalidate(){},render(W){let N=[];if(N.push(...P.render(W)),N.push(""),v.length===0)return N.push(h.fg("muted"," No skills found")),N;let j=Math.max(0,Math.min(w-Math.floor(I/2),v.length-I)),K=Math.min(j+I,v.length);for(let de=j;de<K;de++){let Ie=v[de];if(!Ie)continue;let et=de===w;if(Ie.type==="group"){let Fe=h.fg("accent",h.bold(Ie.group.label));N.push(X(` ${Fe}`,W,""))}else{let Fe=et?"> ":" ",oi=Ie.item.enabled?h.fg("success","[x]"):h.fg("dim","[ ]"),jt=et?h.bold(Ie.item.displayName):Ie.item.displayName;N.push(X(`${Fe} ${oi} ${jt}`,W,"..."))}}let ue=v.filter(de=>de.type==="item").length,be=v[w]?.type==="item"?v.slice(0,w+1).filter(de=>de.type==="item").length:0,Te=loe[f];return j>0||K<v.length?N.push(h.fg("dim",` ${be}/${ue} ${Te}`)):N.push(h.fg("dim",` ${Te}`)),N}},F=new H;return F.addChild(new U(1)),F.addChild(new V),F.addChild(new U(1)),F.addChild(M),F.addChild(new U(1)),F.addChild(R),F.addChild(new U(1)),F.addChild(new V),{render(W){return F.render(W)},invalidate(){F.invalidate()},handleInput(W){let N=ve();if(N.matches(W,"tui.select.up")){w=E(w,-1),p.requestRender();return}if(N.matches(W,"tui.select.down")){w=E(w,1),p.requestRender();return}if(N.matches(W,"tui.select.pageUp")){let j=Math.max(0,w-I);for(;j<v.length&&v[j]?.type!=="item";)j++;j<v.length&&(w=j),p.requestRender();return}if(N.matches(W,"tui.select.pageDown")){let j=Math.min(v.length-1,w+I);for(;j>=0&&v[j]?.type!=="item";)j--;j>=0&&(w=j),p.requestRender();return}if(N.matches(W,"tui.select.cancel")){m(void 0);return}if(_e(W,"ctrl+c")){m(void 0);return}if(_e(W,"tab")){f=uoe(f),L(),p.requestRender();return}if(W===" "||N.matches(W,"tui.select.confirm")){let j=v[w];if(j?.type==="item"){let K=!j.item.enabled;woe(j.item,K,o,i),j.item.enabled=K;for(let ue of l){let be=ue.items.find(Te=>Te.path===j.item.path);be&&(be.enabled=K)}u++,f==="active-first"&&L()}p.requestRender();return}P.handleInput(W),_(P.getValue()),p.requestRender()}}}),u>0){if(await n.ui.confirm("Reload Required",`${u} skill change(s) saved. Reload pi now?`)){await n.reload();return}n.ui.notify("Changes saved to settings. Use /reload to apply.","info")}}})}async function Ey(t,e){let n=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot"),i=new Date;return fetch(`${we.getUserActivityUrl()}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||""}`,Accept:"application/json"},body:JSON.stringify({...t,activity_entity_type:"slingcli",activity_entity_id:_o.slingVersion||"dev",activity_startdate:t.activity_startdate?.toISOString()||i.toISOString(),activity_enddate:t.activity_enddate?.toISOString()||i.toISOString(),metadata:t.metadata||{}})}).then(s=>s.json()).then(s=>{Ne("User activity posted successfully, credits used: "+t.credits_used)}).catch(s=>{gt("Error posting user activity:",s)}),{}}import kA from"node:path";var Cm=null,Ay=0,TA=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Oy(t){let e=kA.basename(process.cwd());return t?`\u2B55\uFE0F - ${t} - ${e}`:`\u2B55\uFE0F - ${e}`}function Ly(t){Cm&&(clearInterval(Cm),Cm=null),Ay=0;let e=t.sessionManager.getSessionName();t.ui.setTitle(Oy(e))}function MA(t){Ly(t),Cm=setInterval(()=>{let e=TA[Ay%TA.length],n=kA.basename(process.cwd()),i=t.sessionManager.getSessionName(),s=i?`${e} ${Oy(i)}`:`${e} ${Oy()}`;t.ui.setTitle(s),Ay++},80)}var Tm=null;function jr(t){t.ui.setWorkingMessage(Soe.magenta(R0[Math.floor(Math.random()*R0.length)]+"..."))}function Coe(t){y0(),_1(t),SI(t,()=>Tm),Py(t),fb(t),bA(t),xA(t),t.on("resources_discover",async s=>{let o=Ic.join(IA(),".pi","agent"),r=Ic.join(IA(),".agents"),c=[Ic.join(s.cwd,".sling","agent"),r,o],l=[],d=[],u=[];for(let p of c){let h=Ic.join(p,"skills");Wy(h)&&l.push(h);let g=Ic.join(p,"prompts");Wy(g)&&d.push(g);let m=Ic.join(p,"themes");Wy(m)&&u.push(m)}return{skillPaths:l,promptPaths:d,themePaths:u}});let e=new WeakSet;t.on("session_start",async(s,o)=>{o.ui.setStatus("ss-credit","0");let r=o.modelRegistry.authStorage;if(!e.has(r)){let c=r.getOAuthProviders.bind(r);r.getOAuthProviders=()=>c().filter(l=>l.id==="slingshot"),e.add(r)}o.hasUI&&o.ui.setHeader(T1);let a=o.modelRegistry.authStorage.get("slingshot");if(a?.type==="oauth"&&typeof a.access=="string"&&a.access)try{await Ki(a.access)}catch(c){Ne(`session_start: app-token fetch failed: ${c instanceof Error?c.message:String(c)}`)}});let n=!1;t.registerProvider("slingshot",{baseUrl:we.getApiBaseUrl(),api:"openai-completions",apiKey:"SLINGSHOT_API_KEY",models:y1,headers:{"X-App-Authorization":we.SLINGSHOT_APP_TOKEN_ENV},oauth:{name:"Slingshot",login:I0,refreshToken:kp,getApiKey:s=>(Tm=s,t.appendEntry("slingshot_credentials",s),s.access)}}),t.registerCommand("ss:settings",{description:"slingshot specific settings",handler:async(s,o)=>{let r=we.getSettings();t.sendMessage({customType:"slingshot-settings",content:JSON.stringify(r,null,2),display:!0})}}),t.registerCommand("ss:debug",{description:"Toggle Slingshot debug logging",handler:async(s,o)=>{let r=!Ol();if(m1(r),r){let a="Slingshot Debug: ENABLED \u2705",c=g1();c&&(a+=`
525
+ `),"info");return}let u=0;if(await n.ui.custom((p,h,g,m)=>{let f="by-source",x=yA(l,f),v=[...x],w=v.findIndex(W=>W.type==="item");w<0&&(w=0);let P=new Je;function E(W,N){let j=W+N;for(;j>=0&&j<v.length;){if(v[j]?.type==="item")return j;j+=N}return W}function _(W){let N=foe(W);if(!N){v=[...x],A();return}let j=new Set,K=new Set;for(let ue of x)ue.type==="item"&&N(ue.item)&&j.add(ue.item);for(let ue of l)for(let be of ue.items)j.has(be)&&K.add(ue);v=[];for(let ue of x)(ue.type==="group"&&K.has(ue.group)||ue.type==="item"&&j.has(ue.item))&&v.push(ue);A()}function L(){x=yA(l,f),_(P.getValue())}function A(){let W=v.findIndex(N=>N.type==="item");w=W>=0?W:0}let M={invalidate(){},render(W){let N=h.bold("Skill Configuration"),j=h.fg("muted"," \xB7 "),K=ut("space","toggle")+j+ut("tab","view")+j+ut("esc","close"),ue=q(K),be=q(N),Te=Math.max(1,W-be-ue);return[X(`${N}${" ".repeat(Te)}${K}`,W,""),h.fg("muted","Filter: name \xB7 /path \xB7 @source")]}},I=15,R={invalidate(){},render(W){let N=[];if(N.push(...P.render(W)),N.push(""),v.length===0)return N.push(h.fg("muted"," No skills found")),N;let j=Math.max(0,Math.min(w-Math.floor(I/2),v.length-I)),K=Math.min(j+I,v.length);for(let de=j;de<K;de++){let Ie=v[de];if(!Ie)continue;let et=de===w;if(Ie.type==="group"){let Fe=h.fg("accent",h.bold(Ie.group.label));N.push(X(` ${Fe}`,W,""))}else{let Fe=et?"> ":" ",oi=Ie.item.enabled?h.fg("success","[x]"):h.fg("dim","[ ]"),jt=et?h.bold(Ie.item.displayName):Ie.item.displayName;N.push(X(`${Fe} ${oi} ${jt}`,W,"..."))}}let ue=v.filter(de=>de.type==="item").length,be=v[w]?.type==="item"?v.slice(0,w+1).filter(de=>de.type==="item").length:0,Te=loe[f];return j>0||K<v.length?N.push(h.fg("dim",` ${be}/${ue} ${Te}`)):N.push(h.fg("dim",` ${Te}`)),N}},F=new H;return F.addChild(new U(1)),F.addChild(new V),F.addChild(new U(1)),F.addChild(M),F.addChild(new U(1)),F.addChild(R),F.addChild(new U(1)),F.addChild(new V),{render(W){return F.render(W)},invalidate(){F.invalidate()},handleInput(W){let N=ve();if(N.matches(W,"tui.select.up")){w=E(w,-1),p.requestRender();return}if(N.matches(W,"tui.select.down")){w=E(w,1),p.requestRender();return}if(N.matches(W,"tui.select.pageUp")){let j=Math.max(0,w-I);for(;j<v.length&&v[j]?.type!=="item";)j++;j<v.length&&(w=j),p.requestRender();return}if(N.matches(W,"tui.select.pageDown")){let j=Math.min(v.length-1,w+I);for(;j>=0&&v[j]?.type!=="item";)j--;j>=0&&(w=j),p.requestRender();return}if(N.matches(W,"tui.select.cancel")){m(void 0);return}if(_e(W,"ctrl+c")){m(void 0);return}if(_e(W,"tab")){f=uoe(f),L(),p.requestRender();return}if(W===" "||N.matches(W,"tui.select.confirm")){let j=v[w];if(j?.type==="item"){let K=!j.item.enabled;woe(j.item,K,o,i),j.item.enabled=K;for(let ue of l){let be=ue.items.find(Te=>Te.path===j.item.path);be&&(be.enabled=K)}u++,f==="active-first"&&L()}p.requestRender();return}P.handleInput(W),_(P.getValue()),p.requestRender()}}}),u>0){if(await n.ui.confirm("Reload Required",`${u} skill change(s) saved. Reload pi now?`)){await n.reload();return}n.ui.notify("Changes saved to settings. Use /reload to apply.","info")}}})}async function Ey(t,e){let n=await e.modelRegistry.getApiKeyForProvider(e.model?.provider||"slingshot"),i=new Date;return fetch(`${we.getUserActivityUrl()}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n||""}`,Accept:"application/json"},body:JSON.stringify({...t,activity_entity_type:"slingcli",activity_entity_id:_o.slingVersion||"dev",activity_startdate:t.activity_startdate?.toISOString()||i.toISOString(),activity_enddate:t.activity_enddate?.toISOString()||i.toISOString(),metadata:t.metadata||{}})}).then(s=>s.json()).then(s=>{Ne("User activity posted successfully, credits used: "+s.credits_used+"/"+s.remainingCredits)}).catch(s=>{gt("Error posting user activity:",s)}),{}}import kA from"node:path";var Cm=null,Ay=0,TA=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function Oy(t){let e=kA.basename(process.cwd());return t?`\u2B55\uFE0F - ${t} - ${e}`:`\u2B55\uFE0F - ${e}`}function Ly(t){Cm&&(clearInterval(Cm),Cm=null),Ay=0;let e=t.sessionManager.getSessionName();t.ui.setTitle(Oy(e))}function MA(t){Ly(t),Cm=setInterval(()=>{let e=TA[Ay%TA.length],n=kA.basename(process.cwd()),i=t.sessionManager.getSessionName(),s=i?`${e} ${Oy(i)}`:`${e} ${Oy()}`;t.ui.setTitle(s),Ay++},80)}var Tm=null;function jr(t){t.ui.setWorkingMessage(Soe.magenta(R0[Math.floor(Math.random()*R0.length)]+"..."))}function Coe(t){y0(),_1(t),SI(t,()=>Tm),Py(t),fb(t),bA(t),xA(t),t.on("resources_discover",async s=>{let o=Ic.join(IA(),".pi","agent"),r=Ic.join(IA(),".agents"),c=[Ic.join(s.cwd,".sling","agent"),r,o],l=[],d=[],u=[];for(let p of c){let h=Ic.join(p,"skills");Wy(h)&&l.push(h);let g=Ic.join(p,"prompts");Wy(g)&&d.push(g);let m=Ic.join(p,"themes");Wy(m)&&u.push(m)}return{skillPaths:l,promptPaths:d,themePaths:u}});let e=new WeakSet;t.on("session_start",async(s,o)=>{o.ui.setStatus("ss-credit","0");let r=o.modelRegistry.authStorage;if(!e.has(r)){let c=r.getOAuthProviders.bind(r);r.getOAuthProviders=()=>c().filter(l=>l.id==="slingshot"),e.add(r)}o.hasUI&&o.ui.setHeader(T1);let a=o.modelRegistry.authStorage.get("slingshot");if(a?.type==="oauth"&&typeof a.access=="string"&&a.access)try{await Ki(a.access)}catch(c){Ne(`session_start: app-token fetch failed: ${c instanceof Error?c.message:String(c)}`)}});let n=!1;t.registerProvider("slingshot",{baseUrl:we.getApiBaseUrl(),api:"openai-completions",apiKey:"SLINGSHOT_API_KEY",models:y1,headers:{"X-App-Authorization":we.SLINGSHOT_APP_TOKEN_ENV},oauth:{name:"Slingshot",login:I0,refreshToken:kp,getApiKey:s=>(Tm=s,t.appendEntry("slingshot_credentials",s),s.access)}}),t.registerCommand("ss:settings",{description:"slingshot specific settings",handler:async(s,o)=>{let r=we.getSettings();t.sendMessage({customType:"slingshot-settings",content:JSON.stringify(r,null,2),display:!0})}}),t.registerCommand("ss:debug",{description:"Toggle Slingshot debug logging",handler:async(s,o)=>{let r=!Ol();if(m1(r),r){let a="Slingshot Debug: ENABLED \u2705",c=g1();c&&(a+=`
526
526
 
527
527
  Log file:
528
528
  ${c}`),t.sendMessage({customType:"slingshot-debug-status",content:a,display:!0})}else t.sendMessage({customType:"slingshot-debug-status",content:"Slingshot Debug: DISABLED \u274C",display:!0})}}),t.registerCommand("refresh-token",{description:"Manually refresh Slingshot OAuth token",handler:async(s,o)=>{try{let r=o.modelRegistry.authStorage,a=r.get("slingshot");if(!a||a.type!=="oauth"){o.ui.notify("No Slingshot OAuth credentials found. Please use /login slingshot first.","error");return}o.ui.setStatus("refresh","Refreshing Slingshot token...");let c=await kp(a);r.set("slingshot",{type:"oauth",...c}),Tm=c,t.appendEntry("slingshot_credentials",c),o.ui.setStatus("refresh",void 0),o.ui.notify("Slingshot token refreshed successfully!","info")}catch(r){o.ui.setStatus("refresh",void 0);let a=r instanceof Error?r.message:String(r);o.ui.notify(`Failed to refresh token: ${a}`,"error")}}});let i=Sp();t.on("before_agent_start",async(s,o)=>{try{MA(o),jr(o),P0(o,"random");let r=await Mp(s,o);if(!r?.headers||!r.sageCommonData)return;i=Sp(),Ip("agentExecutionStatus",r.headers,r.sageCommonData,{agent_id:i,agent_name:"Sling_Coding_Assistant",agent_execution_status:"Started",agent_correlation_id:i,agent_type:"Temp"})}catch(r){Ol()&&(Ne(`CRITICAL ERROR in event handler: ${r?.message||r}`),r?.stack&&Ne(r.stack))}}),t.on("agent_end",async(s,o)=>{try{Ly(o);let r=0,a=0,c=0,l=0,d=0;for(let p of o.sessionManager.getEntries())p.type==="message"&&p.message.role==="assistant"&&(r+=p.message.usage.input,a+=p.message.usage.output,c+=p.message.usage.cacheRead,l+=p.message.usage.cacheWrite,d+=p.message.usage.cost.total);Ey({activity_type:"slingcli:agent:execute",activity_entity_id:i,activity_entity_type:"coding_agent",total_tokens:r+a,credits_used:0,metadata:{correlation_id:i,cost:d}},o).then(p=>{p.credits_used&&o.ui.notify(`Credits used: ${p.credits_used.toFixed(4)}`,"info"),p.remainingCredits&&o.ui.setStatus("ss-credit",`${p.remainingCredits.toFixed(2)}`)});let u=await Mp(s,o);if(!u?.headers||!u.sageCommonData)return;Ip("agentExecutionStatus",u.headers,u.sageCommonData,{agent_id:i,agent_name:"Sling_Coding_Assistant",agent_execution_status:"Success",agent_correlation_id:i,agent_type:"Temp",tools_list:[]})}catch(r){t.sendMessage({customType:"slingshot-analytics-error",content:"[Slingshot] Analytics error. Run /slingshot-debug for details.",display:!0}),Ol()&&(Ne(`CRITICAL ERROR in event handler: ${r?.message||r}`),r?.stack&&Ne(r.stack))}}),t.on("tool_execution_start",async(s,o)=>{jr(o)}),t.on("tool_result",async(s,o)=>{if(jr(o),s.toolName==="write"||s.toolName==="edit")try{let r=await Mp(s,o,Tm);if(!r?.headers||!r.sageCommonData||s.isError)return;let a=s.input.path+"",l=a.split(".").pop()||"",d="";s.toolName==="write"?d=s.input.content+"":s.toolName==="edit"&&(d=(s.details?.diff+"").split(`