@scopeide/cli 0.1.5 → 0.1.7

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.
Files changed (2) hide show
  1. package/dist/index.js +165 -165
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,214 +1,214 @@
1
- import Ls from"dns";import Fs from"net";import{createRequire as Ci}from"module";import{Command as Pi,Option as Ai}from"commander";var h={name:"Scope",shortName:"Scope",bin:"scope",dirName:".scope",keyPrefix:"sc_",sessionPrefix:"scs_",defaultApiUrl:"https://api.scopeide.com",installSnippet:"npm i -g @scopeide/cli",domain:"scopeide.com",supportEmail:"support@scopeide.com",salesEmail:"sales@scopeide.com",tagline:"The AI-First Code Editor Built for Flow & Speed.",version:"v0.1.1"};var L={maxSteps:100,hardMaxSteps:500,maxToolOutputBytes:12e3,maxContextTokens:32e3,warnContextTokens:24e3,maxRunTokens:0,charsPerToken:4};var Ct={strings:{}},Ys=["maxSteps","hardMaxSteps","maxToolOutputBytes","maxContextTokens","warnContextTokens","maxRunTokens"];function hn(t){if(!t)return;let e=L;for(let n of Ys){let o=t.limits?.[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&(e[n]=o)}if(t.strings&&typeof t.strings=="object"){Ct.strings={};for(let[n,o]of Object.entries(t.strings))/^(cli|agent|desktop)\./.test(n)&&typeof o=="string"&&(Ct.strings[n]=o.slice(0,4e3))}}function l(t,e,...n){let o=Ct.strings[t]??e;return n.length?o.replace(/\{(\d+)\}/g,(s,r)=>Number(r)<n.length?String(n[Number(r)]):s):o}var me={maxBytes:5*1024*1024,maxPerMessage:6,keepInRequest:3,maxRequestBytes:6*1024*1024};import Pe from"os";import wt from"path";import{execFile as is,spawn as si}from"child_process";import T from"fs/promises";import nr from"fs";import fo from"os";import or from"crypto";import M from"path";import{spawn as sr}from"child_process";import{z as N}from"zod";import{zodToJsonSchema as rr}from"zod-to-json-schema";import Ge from"path";function pe(t,e){let n=Ge.resolve(t,e),o=Ge.relative(t,n),s=o===""||!o.startsWith("..")&&!Ge.isAbsolute(o);return{abs:n,inside:s}}function Oe(t,e){let n=Ge.posix.resolve(t,e),o=Ge.posix.relative(t,n),s=o===""||!o.startsWith("..")&&!Ge.posix.isAbsolute(o);return{abs:n,inside:s}}import Se from"path";function ce(t,e){if(t.length<=e)return t;let n=Math.floor(e*.6),o=e-n;return`${t.slice(0,n)}
2
- \u2026[${t.length-e} chars omitted]\u2026
3
- ${t.slice(t.length-o)}`}import _n from"path";var Vs=[[/(^|[\s;&|(`])(sudo|doas)\b/,"sudo is not allowed"],[/(^|[\s;&|(`])su\s+(-|root\b)/,"su is not allowed"],[/:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/,"fork bomb"],[/\bmkfs(\.\w+)?\b/,"filesystem format"],[/\b(wipefs|shred|fdisk|parted|diskutil\s+(erase|zero|secure))/,"disk wipe/partition command"],[/\bdd\b[^|;&]*\bof=\/dev\//,"raw disk write"],[/>\s*\/dev\/(sd|nvme|disk|rdisk|hd)/,"raw disk write"],[/(^|[\s;&|(`])(shutdown|reboot|halt|poweroff)\b/,"system power command"],[/\bchmod\s+(-\w+\s+)*[0-7]*777\s+\/(\s|$)/,"chmod 777 on root path"],[/\b(curl|wget|nc|ncat|scp|rsync|ftp|sftp)\b[^\n]*(\.env\b|id_rsa|id_ed25519|\.ssh\b|\.aws\b|\.npmrc|\.netrc|credentials|\.forge\/config)/,"possible secret exfiltration"],[/\b(cat|less|more|head|tail|base64|printenv|env)\b[^\n]*\|\s*(curl|wget|nc|ncat)\b/,"possible secret exfiltration"],[/\b(cat|head|tail|base64)\b[^\n|]*(\.env\b|id_rsa|\.ssh\/|\.aws\/|\.netrc)[^\n]*\|\s*(curl|wget|nc|ncat)\b/,"possible secret exfiltration"],[/\b(curl|wget)\b[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD)\w*/i,"possible secret exfiltration"],[/\b(printenv|env)\b[^\n]*\|\s*(curl|wget|nc|ncat)\b/,"possible secret exfiltration"],[/\b(curl|wget)\b[^\n]*\|\s*(sudo\s+)?(sh|bash|zsh|python3?|node)\b/,"piping a remote script to an interpreter"]],Xs=/^(\/|\/\*|~|~\/|~\/\*|\$HOME|\$\{HOME\}|\$HOME\/|\$HOME\/\*|\*|\/(usr|etc|bin|sbin|var|lib|opt|home|Users|System|Library|Applications)\/?\*?)$/;function Zs(t){let e=t.trim().split(/\s+/),n=e.findIndex(c=>_n.basename(c.replace(/^["']|["']$/g,""))==="rm");if(n<0)return null;let o=e.slice(n+1);if(!o.some(c=>/^-[a-zA-Z]*[rR][a-zA-Z]*$/.test(c)||c==="--recursive"))return null;if(o.includes("--no-preserve-root"))return"rm --no-preserve-root";let a=o.filter(c=>!c.startsWith("-")).map(c=>c.replace(/^["']|["']$/g,"")).find(c=>Xs.test(c));return a?`recursive delete of "${a}"`:null}function Pt(t,e){for(let[n,o]of Vs)if(n.test(t))return{ok:!1,reason:`blocked: ${o}`};for(let n of t.split(/&&|\|\||[;|\n]/)){let o=Zs(n);if(o)return{ok:!1,reason:`blocked: ${o}`}}if(!e.allowAll){let n=e.posix?_n.posix:_n,o=n.relative(e.root,e.cwd);if(o.startsWith("..")||n.isAbsolute(o))return{ok:!1,reason:"blocked: cwd is outside the project root"}}return{ok:!0}}var Qs=/(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i;function At(t){let e={};for(let[n,o]of Object.entries(t))Qs.test(n)||n.startsWith("FORGE_")||n==="DATABASE_URL"||(e[n]=o);return e}var er=1e6,wn=(t,e=L.maxToolOutputBytes)=>ce(t,e);function ve(t,e,n){let{abs:o,inside:s}=Oe(t.root,e);if(t.allowAll)return o;if(!s){if(n&&t.allowOutside)return o;throw new Error(l("agent.tools.path_0_is_outside_the",'path "{0}" is outside the project root',e))}if(n&&Se.posix.relative(t.root,o).split("/").includes(".git"))throw new Error(l("agent.tools.modifying_git_is_not_allowed","modifying .git is not allowed"));return o}async function uo(t,e,n){let o=await t.stat(e);if(!o)throw new Error(l("agent.tools.file_not_found_0","file not found: {0}",n));if(o.isDir)throw new Error(l("agent.tools.0_is_a_directory_use","{0} is a directory; use list_dir",n));if(o.size>er)throw new Error(l("agent.tools.0_is_too_large_1","{0} is too large ({1} bytes); use grep to find the relevant part",n,o.size));let s=await t.readFile(e);if(s.includes(0))throw new Error(l("agent.tools.0_looks_like_a_binary","{0} looks like a binary file",n));return s.toString("utf8")}var tr=(t,e)=>t.slice(0,e).split(`
4
- `).length;async function mo(t,e,n){let o=n.remote;switch(t){case"read_file":return wn(await uo(o,ve(n,e.path,!1),e.path));case"write_file":{let s=ve(n,e.path,!0),r=await o.stat(s);if(r?.isDir)throw new Error(l("agent.tools.0_is_a_directory","{0} is a directory",e.path));return await o.writeFile(s,e.content),l("agent.tools.wrote_file","{0} {1} ({2} chars)",r?"overwrote":"created",e.path,e.content.length)}case"edit_file":{let s=ve(n,e.path,!0),r=await uo(o,s,e.path),{old_string:a,new_string:c}=e;if(a===c)throw new Error(l("agent.tools.old_string_and_new_string","old_string and new_string are identical"));!r.includes(a)&&r.includes(`\r
1
+ import Ds from"dns";import Us from"net";import{Command as ji,Option as Ni}from"commander";var _={name:"Scope",shortName:"Scope",bin:"scope",dirName:".scope",keyPrefix:"sc_",sessionPrefix:"scs_",defaultApiUrl:"https://api.scopeide.com",installSnippet:"npm i -g @scopeide/cli",domain:"scopeide.com",supportEmail:"support@scopeide.com",salesEmail:"sales@scopeide.com",tagline:"The AI-First Code Editor Built for Flow & Speed.",version:"v0.1.7"};var L={maxSteps:100,hardMaxSteps:500,maxToolOutputBytes:12e3,maxContextTokens:32e3,warnContextTokens:24e3,maxRunTokens:0,charsPerToken:4};var jt={strings:{}},Xs=["maxSteps","hardMaxSteps","maxToolOutputBytes","maxContextTokens","warnContextTokens","maxRunTokens"];function wn(e){if(!e)return;let t=L;for(let n of Xs){let o=e.limits?.[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&(t[n]=o)}if(e.strings&&typeof e.strings=="object"){jt.strings={};for(let[n,o]of Object.entries(e.strings))/^(cli|agent|desktop)\./.test(n)&&typeof o=="string"&&(jt.strings[n]=o.slice(0,4e3))}}function l(e,t,...n){let o=jt.strings[e]??t;return n.length?o.replace(/\{(\d+)\}/g,(s,r)=>Number(r)<n.length?String(n[Number(r)]):s):o}var me={maxBytes:5*1024*1024,maxPerMessage:6,keepInRequest:3,maxRequestBytes:6*1024*1024};import Ne from"os";import xt from"path";import{execFile as _s,spawn as wi}from"child_process";import T from"fs/promises";import sr from"fs";import _o from"os";import rr from"crypto";import M from"path";import{spawn as ir}from"child_process";import{z as N}from"zod";import{zodToJsonSchema as ar}from"zod-to-json-schema";import Ve from"path";function pe(e,t){let n=Ve.resolve(e,t),o=Ve.relative(e,n),s=o===""||!o.startsWith("..")&&!Ve.isAbsolute(o);return{abs:n,inside:s}}function De(e,t){let n=Ve.posix.resolve(e,t),o=Ve.posix.relative(e,n),s=o===""||!o.startsWith("..")&&!Ve.posix.isAbsolute(o);return{abs:n,inside:s}}import Re from"path";function le(e,t){if(e.length<=t)return e;let n=Math.floor(t*.6),o=t-n;return`${e.slice(0,n)}
2
+ \u2026[${e.length-t} chars omitted]\u2026
3
+ ${e.slice(e.length-o)}`}import yn from"path";var Zs=[[/(^|[\s;&|(`])(sudo|doas)\b/,"sudo is not allowed"],[/(^|[\s;&|(`])su\s+(-|root\b)/,"su is not allowed"],[/:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/,"fork bomb"],[/\bmkfs(\.\w+)?\b/,"filesystem format"],[/\b(wipefs|shred|fdisk|parted|diskutil\s+(erase|zero|secure))/,"disk wipe/partition command"],[/\bdd\b[^|;&]*\bof=\/dev\//,"raw disk write"],[/>\s*\/dev\/(sd|nvme|disk|rdisk|hd)/,"raw disk write"],[/(^|[\s;&|(`])(shutdown|reboot|halt|poweroff)\b/,"system power command"],[/\bchmod\s+(-\w+\s+)*[0-7]*777\s+\/(\s|$)/,"chmod 777 on root path"],[/\b(curl|wget|nc|ncat|scp|rsync|ftp|sftp)\b[^\n]*(\.env\b|id_rsa|id_ed25519|\.ssh\b|\.aws\b|\.npmrc|\.netrc|credentials|\.forge\/config)/,"possible secret exfiltration"],[/\b(cat|less|more|head|tail|base64|printenv|env)\b[^\n]*\|\s*(curl|wget|nc|ncat)\b/,"possible secret exfiltration"],[/\b(cat|head|tail|base64)\b[^\n|]*(\.env\b|id_rsa|\.ssh\/|\.aws\/|\.netrc)[^\n]*\|\s*(curl|wget|nc|ncat)\b/,"possible secret exfiltration"],[/\b(curl|wget)\b[^\n]*\$\{?\w*(KEY|TOKEN|SECRET|PASSWORD)\w*/i,"possible secret exfiltration"],[/\b(printenv|env)\b[^\n]*\|\s*(curl|wget|nc|ncat)\b/,"possible secret exfiltration"],[/\b(curl|wget)\b[^\n]*\|\s*(sudo\s+)?(sh|bash|zsh|python3?|node)\b/,"piping a remote script to an interpreter"]],Qs=/^(\/|\/\*|~|~\/|~\/\*|\$HOME|\$\{HOME\}|\$HOME\/|\$HOME\/\*|\*|\/(usr|etc|bin|sbin|var|lib|opt|home|Users|System|Library|Applications)\/?\*?)$/;function er(e){let t=e.trim().split(/\s+/),n=t.findIndex(c=>yn.basename(c.replace(/^["']|["']$/g,""))==="rm");if(n<0)return null;let o=t.slice(n+1);if(!o.some(c=>/^-[a-zA-Z]*[rR][a-zA-Z]*$/.test(c)||c==="--recursive"))return null;if(o.includes("--no-preserve-root"))return"rm --no-preserve-root";let a=o.filter(c=>!c.startsWith("-")).map(c=>c.replace(/^["']|["']$/g,"")).find(c=>Qs.test(c));return a?`recursive delete of "${a}"`:null}function Nt(e,t){for(let[n,o]of Zs)if(n.test(e))return{ok:!1,reason:`blocked: ${o}`};for(let n of e.split(/&&|\|\||[;|\n]/)){let o=er(n);if(o)return{ok:!1,reason:`blocked: ${o}`}}if(!t.allowAll){let n=t.posix?yn.posix:yn,o=n.relative(t.root,t.cwd);if(o.startsWith("..")||n.isAbsolute(o))return{ok:!1,reason:"blocked: cwd is outside the project root"}}return{ok:!0}}var tr=/(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i;function It(e){let t={};for(let[n,o]of Object.entries(e))tr.test(n)||n.startsWith("FORGE_")||n==="DATABASE_URL"||(t[n]=o);return t}var nr=1e6,bn=(e,t=L.maxToolOutputBytes)=>le(e,t);function Te(e,t,n){let{abs:o,inside:s}=De(e.root,t);if(e.allowAll)return o;if(!s){if(n&&e.allowOutside)return o;throw new Error(l("agent.tools.path_0_is_outside_the",'path "{0}" is outside the project root',t))}if(n&&Re.posix.relative(e.root,o).split("/").includes(".git"))throw new Error(l("agent.tools.modifying_git_is_not_allowed","modifying .git is not allowed"));return o}async function po(e,t,n){let o=await e.stat(t);if(!o)throw new Error(l("agent.tools.file_not_found_0","file not found: {0}",n));if(o.isDir)throw new Error(l("agent.tools.0_is_a_directory_use","{0} is a directory; use list_dir",n));if(o.size>nr)throw new Error(l("agent.tools.0_is_too_large_1","{0} is too large ({1} bytes); use grep to find the relevant part",n,o.size));let s=await e.readFile(t);if(s.includes(0))throw new Error(l("agent.tools.0_looks_like_a_binary","{0} looks like a binary file",n));return s.toString("utf8")}var or=(e,t)=>e.slice(0,t).split(`
4
+ `).length;async function go(e,t,n){let o=n.remote;switch(e){case"read_file":return bn(await po(o,Te(n,t.path,!1),t.path));case"write_file":{let s=Te(n,t.path,!0),r=await o.stat(s);if(r?.isDir)throw new Error(l("agent.tools.0_is_a_directory","{0} is a directory",t.path));return await o.writeFile(s,t.content),l("agent.tools.wrote_file","{0} {1} ({2} chars)",r?"overwrote":"created",t.path,t.content.length)}case"edit_file":{let s=Te(n,t.path,!0),r=await po(o,s,t.path),{old_string:a,new_string:c}=t;if(a===c)throw new Error(l("agent.tools.old_string_and_new_string","old_string and new_string are identical"));!r.includes(a)&&r.includes(`\r
5
5
  `)&&!a.includes("\r")&&(a=a.replace(/\n/g,`\r
6
6
  `),c=c.replace(/\n/g,`\r
7
- `));let d=r.indexOf(a);if(d<0)throw new Error(l("agent.tools.old_string_not_found_in","old_string not found in file (it must match exactly, including whitespace); read_file again and copy it verbatim"));let u=r.split(a).length-1;if(u>1)throw new Error(l("agent.tools.old_string_is_not_unique","old_string is not unique ({0} matches); include more surrounding context",u));return await o.writeFile(s,r.slice(0,d)+c+r.slice(d+a.length)),l("agent.tools.edited_file","edited {0} (line {1})",e.path,tr(r,d))}case"list_dir":{let s=ve(n,e.path??".",!1),r=await o.stat(s);if(!r)throw new Error(`directory not found: ${e.path}`);if(!r.isDir)throw new Error(`${e.path} is a file; use read_file`);let a=(await o.readdir(s)).filter(d=>![".git","node_modules",".next","dist",".turbo",".forge",".command"].includes(d.name)&&!Le(d.name));a.sort((d,u)=>Number(u.isDir)-Number(d.isDir)||d.name.localeCompare(u.name));let c=a.slice(0,500).map(d=>d.name+(d.isDir?"/":""));return a.length>500&&c.push(`\u2026[${a.length-500} more]`),c.join(`
8
- `)||"(empty)"}case"grep":{let s=ve(n,e.path??".",!1);try{new RegExp(e.pattern)}catch{throw new Error(l("agent.tools.invalid_regular_expression","invalid regular expression"))}if(!await o.stat(s))throw new Error(l("agent.tools.path_not_found_0","path not found: {0}",e.path));let r=e.glob?mt(e.glob):null,a=[];for(let c of await o.grep(e.pattern,s,2e3)){let d=/^(.*?):(\d+):(.*)$/.exec(c);if(!d)continue;let u=Se.posix.resolve(s,d[1]),g=Se.posix.relative(n.root,u);if(!Le(Se.posix.basename(u))&&!(r&&!r.test(g)&&!r.test(Se.posix.basename(u)))&&(a.push(`${g}:${d[2]}: ${d[3].slice(0,300)}`),a.length>=200))return wn(a.join(`
7
+ `));let d=r.indexOf(a);if(d<0)throw new Error(l("agent.tools.old_string_not_found_in","old_string not found in file (it must match exactly, including whitespace); read_file again and copy it verbatim"));let u=r.split(a).length-1;if(u>1)throw new Error(l("agent.tools.old_string_is_not_unique","old_string is not unique ({0} matches); include more surrounding context",u));return await o.writeFile(s,r.slice(0,d)+c+r.slice(d+a.length)),l("agent.tools.edited_file","edited {0} (line {1})",t.path,or(r,d))}case"list_dir":{let s=Te(n,t.path??".",!1),r=await o.stat(s);if(!r)throw new Error(`directory not found: ${t.path}`);if(!r.isDir)throw new Error(`${t.path} is a file; use read_file`);let a=(await o.readdir(s)).filter(d=>![".git","node_modules",".next","dist",".turbo",".forge",".command"].includes(d.name)&&!Ue(d.name));a.sort((d,u)=>Number(u.isDir)-Number(d.isDir)||d.name.localeCompare(u.name));let c=a.slice(0,500).map(d=>d.name+(d.isDir?"/":""));return a.length>500&&c.push(`\u2026[${a.length-500} more]`),c.join(`
8
+ `)||"(empty)"}case"grep":{let s=Te(n,t.path??".",!1);try{new RegExp(t.pattern)}catch{throw new Error(l("agent.tools.invalid_regular_expression","invalid regular expression"))}if(!await o.stat(s))throw new Error(l("agent.tools.path_not_found_0","path not found: {0}",t.path));let r=t.glob?ft(t.glob):null,a=[];for(let c of await o.grep(t.pattern,s,2e3)){let d=/^(.*?):(\d+):(.*)$/.exec(c);if(!d)continue;let u=Re.posix.resolve(s,d[1]),g=Re.posix.relative(n.root,u);if(!Ue(Re.posix.basename(u))&&!(r&&!r.test(g)&&!r.test(Re.posix.basename(u)))&&(a.push(`${g}:${d[2]}: ${d[3].slice(0,300)}`),a.length>=200))return bn(a.join(`
9
9
  `)+`
10
10
  \u2026[200 match limit]`)}return a.join(`
11
- `)||"no matches"}case"run_shell":{let s=ve(n,e.cwd??".",!1),r=Pt(e.command,{root:n.root,cwd:s,allowAll:n.allowAll,posix:!0});if(!r.ok)throw new Error(r.reason);let a=n.shellTimeoutMs??12e4,c=await o.exec(e.command,s,a);return l("agent.tools.shell_result",`exit code: {0}{1}{2}
11
+ `)||"no matches"}case"run_shell":{let s=Te(n,t.cwd??".",!1),r=Nt(t.command,{root:n.root,cwd:s,allowAll:n.allowAll,posix:!0});if(!r.ok)throw new Error(r.reason);let a=n.shellTimeoutMs??12e4,c=await o.exec(t.command,s,a);return l("agent.tools.shell_result",`exit code: {0}{1}{2}
12
12
  --- stdout ---
13
13
  {3}
14
14
  --- stderr ---
15
- {4}`,c.code??"?",c.timedOut?` (timed out after ${a}ms)`:"","",ce(c.stdout,Math.floor(L.maxToolOutputBytes*.65)),ce(c.stderr,Math.floor(L.maxToolOutputBytes*.3)))}case"glob":{let s=ve(n,e.path??".",!1),r=mt(e.pattern),a=[];for(let c of await o.walk(s)){if(Le(Se.posix.basename(c)))continue;let d=Se.posix.relative(n.root,c);if((r.test(d)||r.test(Se.posix.basename(c)))&&(a.push(d),a.length>=200))break}return a.join(`
16
- `)||"no matching files found"}case"read_multiple_files":{let s=[];for(let r of e.paths)try{let a=await o.readFile(ve(n,r,!1));s.push(a.includes(0)?`=== ${r} (binary file skipped) ===`:`=== ${r} ===
17
- ${a.toString("utf8")}`)}catch(a){s.push(`=== ${r} (error: ${a.message}) ===`)}return wn(s.join(`
15
+ {4}`,c.code??"?",c.timedOut?` (timed out after ${a}ms)`:"","",le(c.stdout,Math.floor(L.maxToolOutputBytes*.65)),le(c.stderr,Math.floor(L.maxToolOutputBytes*.3)))}case"glob":{let s=Te(n,t.path??".",!1),r=ft(t.pattern),a=[];for(let c of await o.walk(s)){if(Ue(Re.posix.basename(c)))continue;let d=Re.posix.relative(n.root,c);if((r.test(d)||r.test(Re.posix.basename(c)))&&(a.push(d),a.length>=200))break}return a.join(`
16
+ `)||"no matching files found"}case"read_multiple_files":{let s=[];for(let r of t.paths)try{let a=await o.readFile(Te(n,r,!1));s.push(a.includes(0)?`=== ${r} (binary file skipped) ===`:`=== ${r} ===
17
+ ${a.toString("utf8")}`)}catch(a){s.push(`=== ${r} (error: ${a.message}) ===`)}return bn(s.join(`
18
18
 
19
- `))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var ho=new Set([".git","node_modules",".next","dist",".turbo",".forge",".command"]),jt=new Set;function ir(){if(globalThis.__forgeCleanupRegistered)return;globalThis.__forgeCleanupRegistered=!0;let t=()=>{for(let e of jt)try{nr.unlinkSync(e)}catch{}jt.clear()};process.once("exit",t),process.once("SIGINT",()=>{t(),process.exit(130)}),process.once("SIGTERM",()=>{t(),process.exit(143)})}function Le(t){return t.endsWith(".tmp")||t.includes(".tmp.")||t.includes(".cc-edit.tmp")||t.endsWith(".swp")||t.endsWith("~")||t.startsWith(".#")}async function ar(t){try{let e=M.join(t,".git"),n=await T.stat(e).catch(()=>null);if(!n)return;let o=M.join(e,"info");if(!n.isDirectory()){let a=await T.readFile(e,"utf8").catch(()=>""),c=/^gitdir:\s*(.+)$/m.exec(a);if(c){let d=M.resolve(t,c[1].trim());o=M.join(d,"info")}}let s=M.join(o,"exclude"),r=await T.readFile(s,"utf8").catch(()=>"");if(!r.includes(".forge")){await T.mkdir(o,{recursive:!0});let a=(r.endsWith(`
19
+ `))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var wo=new Set([".git","node_modules",".next","dist",".turbo",".forge",".command"]),Ot=new Set;function lr(){if(globalThis.__forgeCleanupRegistered)return;globalThis.__forgeCleanupRegistered=!0;let e=()=>{for(let t of Ot)try{sr.unlinkSync(t)}catch{}Ot.clear()};process.once("exit",e),process.once("SIGINT",()=>{e(),process.exit(130)}),process.once("SIGTERM",()=>{e(),process.exit(143)})}function Ue(e){return e.endsWith(".tmp")||e.includes(".tmp.")||e.includes(".cc-edit.tmp")||e.endsWith(".swp")||e.endsWith("~")||e.startsWith(".#")}async function cr(e){try{let t=M.join(e,".git"),n=await T.stat(t).catch(()=>null);if(!n)return;let o=M.join(t,"info");if(!n.isDirectory()){let a=await T.readFile(t,"utf8").catch(()=>""),c=/^gitdir:\s*(.+)$/m.exec(a);if(c){let d=M.resolve(e,c[1].trim());o=M.join(d,"info")}}let s=M.join(o,"exclude"),r=await T.readFile(s,"utf8").catch(()=>"");if(!r.includes(".forge")){await T.mkdir(o,{recursive:!0});let a=(r.endsWith(`
20
20
  `)||r.length===0?"":`
21
21
  `)+`# Forge internal files
22
22
  .forge
23
23
  .forge/**
24
- `;await T.appendFile(s,a,"utf8")}}catch{}}async function _o(t){let e=0;try{let n=await T.readdir(t,{withFileTypes:!0});for(let o of n)if(o.isFile()&&Le(o.name))try{await T.unlink(M.join(t,o.name)),e++}catch{}}catch{}try{let n=M.join(t,".forge"),o=M.join(n,"tmp"),s=M.join(n,"backups");await T.rm(o,{recursive:!0,force:!0}).catch(()=>{}),await T.rm(s,{recursive:!0,force:!0}).catch(()=>{}),(await T.readdir(n).catch(()=>["err"])).length===0&&await T.rmdir(n).catch(()=>{})}catch{}await ar(t).catch(()=>{});try{let n=M.join(fo.homedir(),".forge","tmp"),o=await T.readdir(n,{withFileTypes:!0}).catch(()=>[]),s=Date.now();for(let r of o)if(r.isFile()){let a=M.join(n,r.name),c=await T.stat(a).catch(()=>null);c&&s-c.mtimeMs>36e5&&(await T.unlink(a).catch(()=>{}),e++)}}catch{}return e}async function po(t,e,n){ir();let o=M.join(fo.homedir(),".forge"),s=M.join(o,"tmp");await T.mkdir(s,{recursive:!0});let r=M.join(s,`${M.basename(t)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.tmp`);jt.add(r);let a;try{let c=await T.stat(t);if(a=c.mode,c.isFile()){let d=M.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_")||"project",u=or.createHash("sha256").update(n).digest("hex").slice(0,8),g=M.join(o,"backups",`${d}-${u}`);await T.mkdir(g,{recursive:!0});let _=M.join(g,`${M.basename(t)}.${Date.now()}.bak`);await T.copyFile(t,_).catch(()=>{})}}catch{}try{await T.mkdir(M.dirname(t),{recursive:!0}),await T.writeFile(r,e,{encoding:"utf8",mode:a}),await T.rename(r,t)}catch(c){if(c?.code==="EXDEV")try{await T.copyFile(r,t)}catch{await T.writeFile(t,e,{encoding:"utf8",mode:a})}else await T.writeFile(t,e,{encoding:"utf8",mode:a})}finally{jt.delete(r);try{await T.unlink(r)}catch{}}}var Ke={read_file:N.object({path:N.string().min(1)}),write_file:N.object({path:N.string().min(1),content:N.string()}),edit_file:N.object({path:N.string().min(1),old_string:N.string().min(1),new_string:N.string()}),list_dir:N.object({path:N.string().default(".")}),grep:N.object({pattern:N.string().min(1),path:N.string().optional(),glob:N.string().optional()}),run_shell:N.object({command:N.string().min(1),cwd:N.string().optional()}),glob:N.object({pattern:N.string().min(1),path:N.string().optional()}),read_multiple_files:N.object({paths:N.array(N.string().min(1)).min(1)}),think:N.object({thought:N.string().min(1)})},pt=Object.keys(Ke),lr={read_file:"Read a UTF-8 text file relative to the project root.",write_file:"Create or overwrite a file with the given content.",edit_file:"Replace one exact occurrence of old_string with new_string. Fails if old_string is not found or not unique.",list_dir:"List entries of a directory (directories end with /).",grep:"Search file contents with a regular expression. Optional path and glob (e.g. **/*.ts).",run_shell:"Run a shell command in the project (user approval required unless --yolo).",glob:"Find files matching a glob pattern (e.g. **/*.ts, src/**/*.tsx).",read_multiple_files:"Read multiple files at once to inspect codebase context efficiently.",think:"Record internal reasoning, plan, or analysis before executing actions."};function xn(){return pt.map(t=>{let e=rr(Ke[t],{target:"openApi3",$refStrategy:"none"});return delete e.$schema,{name:t,description:l(`agent.tool.${t}.description`,lr[t]),parameters:e}})}var yn=(t,e=L.maxToolOutputBytes)=>ce(t,e),wo=1e6;async function cr(t){let e=t,n=[];for(;;)try{return M.join(await T.realpath(e),...n.reverse())}catch{let o=M.dirname(e);if(o===e)return t;n.push(M.basename(e)),e=o}}async function Te(t,e,n){let{abs:o,inside:s}=pe(t.root,e);if(t.allowAll)return o;if(!s){if(n&&t.allowOutside)return o;throw new Error(l("agent.tools.path_0_is_outside_the",'path "{0}" is outside the project root',e))}let r=await T.realpath(t.root),a=await cr(o);if(!pe(r,a).inside)throw new Error(l("agent.tools.path_0_resolves_outside_the",'path "{0}" resolves outside the project root (symlink)',e));if(n&&M.relative(t.root,o).split(M.sep).includes(".git"))throw new Error(l("agent.tools.modifying_git_is_not_allowed","modifying .git is not allowed"));return o}function yo(t,e){return!(t.remote?Oe:pe)(t.root,e).inside}function mt(t){let e="";for(let n=0;n<t.length;n++){let o=t[n];if(o==="*")t[n+1]==="*"?(n++,t[n+1]==="/"&&n++,e+="(?:.*/)?"):e+="[^/]*";else if(o==="?")e+="[^/]";else if(o==="{"){let s=t.indexOf("}",n);s>n?(e+="(?:"+t.slice(n+1,s).split(",").map(r=>r.replace(/[.+^$()|[\]\\]/g,"\\$&")).join("|")+")",n=s):e+="\\{"}else e+=o.replace(/[.+^$()|[\]\\]/g,"\\$&")}return new RegExp(`^${e}$`)}async function*bn(t){for(let e of await T.readdir(t,{withFileTypes:!0}))e.isDirectory()?ho.has(e.name)||(yield*bn(M.join(t,e.name))):e.isFile()&&!Le(e.name)&&(yield M.join(t,e.name))}async function go(t,e){let n;try{n=await T.stat(t)}catch{throw new Error(l("agent.tools.file_not_found_0","file not found: {0}",e))}if(n.isDirectory())throw new Error(l("agent.tools.0_is_a_directory_use","{0} is a directory; use list_dir",e));if(n.size>wo)throw new Error(l("agent.tools.0_is_too_large_1","{0} is too large ({1} bytes); use grep to find the relevant part",e,n.size));let o=await T.readFile(t);if(o.includes(0))throw new Error(l("agent.tools.0_looks_like_a_binary","{0} looks like a binary file",e));return o.toString("utf8")}function dr(t,e){return t.slice(0,e).split(`
25
- `).length}async function Ye(t,e,n){if(n.remote)return mo(t,e,n);switch(t){case"read_file":{let o=await Te(n,e.path,!1);return yn(await go(o,e.path))}case"write_file":{let o=await Te(n,e.path,!0),s=!1;try{if((await T.stat(o)).isDirectory())throw new Error(l("agent.tools.0_is_a_directory","{0} is a directory",e.path));s=!0}catch(r){if(r instanceof Error&&r.message.endsWith("is a directory"))throw r}return await po(o,e.content,n.root),l("agent.tools.wrote_file","{0} {1} ({2} chars)",s?"overwrote":"created",e.path,e.content.length)}case"edit_file":{let o=await Te(n,e.path,!0),s=await go(o,e.path),{old_string:r,new_string:a}=e;if(r===a)throw new Error(l("agent.tools.old_string_and_new_string","old_string and new_string are identical"));!s.includes(r)&&s.includes(`\r
24
+ `;await T.appendFile(s,a,"utf8")}}catch{}}async function yo(e){let t=0;try{let n=await T.readdir(e,{withFileTypes:!0});for(let o of n)if(o.isFile()&&Ue(o.name))try{await T.unlink(M.join(e,o.name)),t++}catch{}}catch{}try{let n=M.join(e,".forge"),o=M.join(n,"tmp"),s=M.join(n,"backups");await T.rm(o,{recursive:!0,force:!0}).catch(()=>{}),await T.rm(s,{recursive:!0,force:!0}).catch(()=>{}),(await T.readdir(n).catch(()=>["err"])).length===0&&await T.rmdir(n).catch(()=>{})}catch{}await cr(e).catch(()=>{});try{let n=M.join(_o.homedir(),".forge","tmp"),o=await T.readdir(n,{withFileTypes:!0}).catch(()=>[]),s=Date.now();for(let r of o)if(r.isFile()){let a=M.join(n,r.name),c=await T.stat(a).catch(()=>null);c&&s-c.mtimeMs>36e5&&(await T.unlink(a).catch(()=>{}),t++)}}catch{}return t}async function fo(e,t,n){lr();let o=M.join(_o.homedir(),".forge"),s=M.join(o,"tmp");await T.mkdir(s,{recursive:!0});let r=M.join(s,`${M.basename(e)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.tmp`);Ot.add(r);let a;try{let c=await T.stat(e);if(a=c.mode,c.isFile()){let d=M.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_")||"project",u=rr.createHash("sha256").update(n).digest("hex").slice(0,8),g=M.join(o,"backups",`${d}-${u}`);await T.mkdir(g,{recursive:!0});let h=M.join(g,`${M.basename(e)}.${Date.now()}.bak`);await T.copyFile(e,h).catch(()=>{})}}catch{}try{await T.mkdir(M.dirname(e),{recursive:!0}),await T.writeFile(r,t,{encoding:"utf8",mode:a}),await T.rename(r,e)}catch(c){if(c?.code==="EXDEV")try{await T.copyFile(r,e)}catch{await T.writeFile(e,t,{encoding:"utf8",mode:a})}else await T.writeFile(e,t,{encoding:"utf8",mode:a})}finally{Ot.delete(r);try{await T.unlink(r)}catch{}}}var Xe={read_file:N.object({path:N.string().min(1)}),write_file:N.object({path:N.string().min(1),content:N.string()}),edit_file:N.object({path:N.string().min(1),old_string:N.string().min(1),new_string:N.string()}),list_dir:N.object({path:N.string().default(".")}),grep:N.object({pattern:N.string().min(1),path:N.string().optional(),glob:N.string().optional()}),run_shell:N.object({command:N.string().min(1),cwd:N.string().optional()}),glob:N.object({pattern:N.string().min(1),path:N.string().optional()}),read_multiple_files:N.object({paths:N.array(N.string().min(1)).min(1)}),think:N.object({thought:N.string().min(1)})},ht=Object.keys(Xe),dr={read_file:"Read a UTF-8 text file relative to the project root.",write_file:"Create or overwrite a file with the given content.",edit_file:"Replace one exact occurrence of old_string with new_string. Fails if old_string is not found or not unique.",list_dir:"List entries of a directory (directories end with /).",grep:"Search file contents with a regular expression. Optional path and glob (e.g. **/*.ts).",run_shell:"Run a shell command in the project (user approval required unless --yolo).",glob:"Find files matching a glob pattern (e.g. **/*.ts, src/**/*.tsx).",read_multiple_files:"Read multiple files at once to inspect codebase context efficiently.",think:"Record internal reasoning, plan, or analysis before executing actions."};function $n(){return ht.map(e=>{let t=ar(Xe[e],{target:"openApi3",$refStrategy:"none"});return delete t.$schema,{name:e,description:l(`agent.tool.${e}.description`,dr[e]),parameters:t}})}var xn=(e,t=L.maxToolOutputBytes)=>le(e,t),bo=1e6;async function ur(e){let t=e,n=[];for(;;)try{return M.join(await T.realpath(t),...n.reverse())}catch{let o=M.dirname(t);if(o===t)return e;n.push(M.basename(t)),t=o}}async function Ee(e,t,n){let{abs:o,inside:s}=pe(e.root,t);if(e.allowAll)return o;if(!s){if(n&&e.allowOutside)return o;throw new Error(l("agent.tools.path_0_is_outside_the",'path "{0}" is outside the project root',t))}let r=await T.realpath(e.root),a=await ur(o);if(!pe(r,a).inside)throw new Error(l("agent.tools.path_0_resolves_outside_the",'path "{0}" resolves outside the project root (symlink)',t));if(n&&M.relative(e.root,o).split(M.sep).includes(".git"))throw new Error(l("agent.tools.modifying_git_is_not_allowed","modifying .git is not allowed"));return o}function xo(e,t){return!(e.remote?De:pe)(e.root,t).inside}function ft(e){let t="";for(let n=0;n<e.length;n++){let o=e[n];if(o==="*")e[n+1]==="*"?(n++,e[n+1]==="/"&&n++,t+="(?:.*/)?"):t+="[^/]*";else if(o==="?")t+="[^/]";else if(o==="{"){let s=e.indexOf("}",n);s>n?(t+="(?:"+e.slice(n+1,s).split(",").map(r=>r.replace(/[.+^$()|[\]\\]/g,"\\$&")).join("|")+")",n=s):t+="\\{"}else t+=o.replace(/[.+^$()|[\]\\]/g,"\\$&")}return new RegExp(`^${t}$`)}async function*kn(e){for(let t of await T.readdir(e,{withFileTypes:!0}))t.isDirectory()?wo.has(t.name)||(yield*kn(M.join(e,t.name))):t.isFile()&&!Ue(t.name)&&(yield M.join(e,t.name))}async function ho(e,t){let n;try{n=await T.stat(e)}catch{throw new Error(l("agent.tools.file_not_found_0","file not found: {0}",t))}if(n.isDirectory())throw new Error(l("agent.tools.0_is_a_directory_use","{0} is a directory; use list_dir",t));if(n.size>bo)throw new Error(l("agent.tools.0_is_too_large_1","{0} is too large ({1} bytes); use grep to find the relevant part",t,n.size));let o=await T.readFile(e);if(o.includes(0))throw new Error(l("agent.tools.0_looks_like_a_binary","{0} looks like a binary file",t));return o.toString("utf8")}function mr(e,t){return e.slice(0,t).split(`
25
+ `).length}async function Ze(e,t,n){if(n.remote)return go(e,t,n);switch(e){case"read_file":{let o=await Ee(n,t.path,!1);return xn(await ho(o,t.path))}case"write_file":{let o=await Ee(n,t.path,!0),s=!1;try{if((await T.stat(o)).isDirectory())throw new Error(l("agent.tools.0_is_a_directory","{0} is a directory",t.path));s=!0}catch(r){if(r instanceof Error&&r.message.endsWith("is a directory"))throw r}return await fo(o,t.content,n.root),l("agent.tools.wrote_file","{0} {1} ({2} chars)",s?"overwrote":"created",t.path,t.content.length)}case"edit_file":{let o=await Ee(n,t.path,!0),s=await ho(o,t.path),{old_string:r,new_string:a}=t;if(r===a)throw new Error(l("agent.tools.old_string_and_new_string","old_string and new_string are identical"));!s.includes(r)&&s.includes(`\r
26
26
  `)&&!r.includes("\r")&&(r=r.replace(/\n/g,`\r
27
27
  `),a=a.replace(/\n/g,`\r
28
- `));let c=s.indexOf(r);if(c<0)throw new Error(l("agent.tools.old_string_not_found_in","old_string not found in file (it must match exactly, including whitespace); read_file again and copy it verbatim"));let d=s.split(r).length-1;if(d>1)throw new Error(l("agent.tools.old_string_is_not_unique","old_string is not unique ({0} matches); include more surrounding context",d));return await po(o,s.slice(0,c)+a+s.slice(c+r.length),n.root),l("agent.tools.edited_file","edited {0} (line {1})",e.path,dr(s,c))}case"list_dir":{let o=await Te(n,e.path??".",!1),s;try{s=await T.readdir(o,{withFileTypes:!0})}catch(a){throw new Error(a.code==="ENOTDIR"?`${e.path} is a file; use read_file`:`directory not found: ${e.path}`)}s=s.filter(a=>!ho.has(a.name)&&!Le(a.name)),s.sort((a,c)=>Number(c.isDirectory())-Number(a.isDirectory())||a.name.localeCompare(c.name));let r=s.slice(0,500).map(a=>a.name+(a.isDirectory()?"/":""));return s.length>500&&r.push(`\u2026[${s.length-500} more]`),r.join(`
29
- `)||"(empty)"}case"grep":{let o=await Te(n,e.path??".",!1),s;try{s=new RegExp(e.pattern)}catch{throw new Error(l("agent.tools.invalid_regular_expression","invalid regular expression"))}let r=e.glob?mt(e.glob):null,a;try{a=await T.stat(o)}catch{throw new Error(l("agent.tools.path_not_found_0","path not found: {0}",e.path))}let c=a.isFile()?[o]:bn(o),d=[];for await(let u of c){let g=M.relative(n.root,u);if(r&&!r.test(g)&&!r.test(M.basename(u)))continue;let _;try{if((await T.stat(u)).size>wo)continue;let v=await T.readFile(u);if(v.includes(0))continue;_=v.toString("utf8")}catch{continue}let R=_.split(`
30
- `);for(let v=0;v<R.length;v++)if(s.test(R[v])&&d.push(`${g}:${v+1}: ${R[v].slice(0,300)}`),d.length>=200)return yn(d.join(`
28
+ `));let c=s.indexOf(r);if(c<0)throw new Error(l("agent.tools.old_string_not_found_in","old_string not found in file (it must match exactly, including whitespace); read_file again and copy it verbatim"));let d=s.split(r).length-1;if(d>1)throw new Error(l("agent.tools.old_string_is_not_unique","old_string is not unique ({0} matches); include more surrounding context",d));return await fo(o,s.slice(0,c)+a+s.slice(c+r.length),n.root),l("agent.tools.edited_file","edited {0} (line {1})",t.path,mr(s,c))}case"list_dir":{let o=await Ee(n,t.path??".",!1),s;try{s=await T.readdir(o,{withFileTypes:!0})}catch(a){throw new Error(a.code==="ENOTDIR"?`${t.path} is a file; use read_file`:`directory not found: ${t.path}`)}s=s.filter(a=>!wo.has(a.name)&&!Ue(a.name)),s.sort((a,c)=>Number(c.isDirectory())-Number(a.isDirectory())||a.name.localeCompare(c.name));let r=s.slice(0,500).map(a=>a.name+(a.isDirectory()?"/":""));return s.length>500&&r.push(`\u2026[${s.length-500} more]`),r.join(`
29
+ `)||"(empty)"}case"grep":{let o=await Ee(n,t.path??".",!1),s;try{s=new RegExp(t.pattern)}catch{throw new Error(l("agent.tools.invalid_regular_expression","invalid regular expression"))}let r=t.glob?ft(t.glob):null,a;try{a=await T.stat(o)}catch{throw new Error(l("agent.tools.path_not_found_0","path not found: {0}",t.path))}let c=a.isFile()?[o]:kn(o),d=[];for await(let u of c){let g=M.relative(n.root,u);if(r&&!r.test(g)&&!r.test(M.basename(u)))continue;let h;try{if((await T.stat(u)).size>bo)continue;let v=await T.readFile(u);if(v.includes(0))continue;h=v.toString("utf8")}catch{continue}let R=h.split(`
30
+ `);for(let v=0;v<R.length;v++)if(s.test(R[v])&&d.push(`${g}:${v+1}: ${R[v].slice(0,300)}`),d.length>=200)return xn(d.join(`
31
31
  `)+`
32
32
  \u2026[200 match limit]`)}return d.join(`
33
- `)||"no matches"}case"run_shell":{let o=await Te(n,e.cwd??".",!1),s=Pt(e.command,{root:n.root,cwd:o,allowAll:n.allowAll});if(!s.ok)throw new Error(s.reason);return await ur(e.command,o,n.shellTimeoutMs??12e4)}case"glob":{let o=await Te(n,e.path??".",!1),s=mt(e.pattern),r=[];for await(let a of bn(o)){let c=M.relative(n.root,a);if((s.test(c)||s.test(M.basename(a)))&&(r.push(c),r.length>=200))break}return r.join(`
34
- `)||"no matching files found"}case"read_multiple_files":{let o=[];for(let s of e.paths)try{let r=await Te(n,s,!1),a=await T.readFile(r);a.includes(0)?o.push(`=== ${s} (binary file skipped) ===`):o.push(`=== ${s} ===
35
- ${a.toString("utf8")}`)}catch(r){o.push(`=== ${s} (error: ${r.message}) ===`)}return yn(o.join(`
33
+ `)||"no matches"}case"run_shell":{let o=await Ee(n,t.cwd??".",!1),s=Nt(t.command,{root:n.root,cwd:o,allowAll:n.allowAll});if(!s.ok)throw new Error(s.reason);return await pr(t.command,o,n.shellTimeoutMs??12e4)}case"glob":{let o=await Ee(n,t.path??".",!1),s=ft(t.pattern),r=[];for await(let a of kn(o)){let c=M.relative(n.root,a);if((s.test(c)||s.test(M.basename(a)))&&(r.push(c),r.length>=200))break}return r.join(`
34
+ `)||"no matching files found"}case"read_multiple_files":{let o=[];for(let s of t.paths)try{let r=await Ee(n,s,!1),a=await T.readFile(r);a.includes(0)?o.push(`=== ${s} (binary file skipped) ===`):o.push(`=== ${s} ===
35
+ ${a.toString("utf8")}`)}catch(r){o.push(`=== ${s} (error: ${r.message}) ===`)}return xn(o.join(`
36
36
 
37
- `))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var Nt=class{head="";tail="";dropped=0;add(e){let n=e.toString("utf8");if(this.head.length<5e4){this.head+=n;return}this.tail+=n,this.tail.length>5e4&&(this.dropped+=this.tail.length-5e4,this.tail=this.tail.slice(-5e4))}text(){return this.dropped?`${this.head}
37
+ `))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var Lt=class{head="";tail="";dropped=0;add(t){let n=t.toString("utf8");if(this.head.length<5e4){this.head+=n;return}this.tail+=n,this.tail.length>5e4&&(this.dropped+=this.tail.length-5e4,this.tail=this.tail.slice(-5e4))}text(){return this.dropped?`${this.head}
38
38
  \u2026[${this.dropped} chars omitted]\u2026
39
- ${this.tail}`:this.head+this.tail}};function ur(t,e,n){return new Promise(o=>{let s=sr("/bin/sh",["-c",t],{cwd:e,env:At(process.env),detached:!0,stdio:["ignore","pipe","pipe"]}),r=!1,a=new Nt,c=new Nt;s.stdout.on("data",g=>a.add(g)),s.stderr.on("data",g=>c.add(g));let d=setTimeout(()=>{r=!0;try{process.kill(-s.pid,"SIGKILL")}catch{}},n),u=(g,_="")=>{clearTimeout(d),o(l("agent.tools.shell_result",`exit code: {0}{1}{2}
39
+ ${this.tail}`:this.head+this.tail}};function pr(e,t,n){return new Promise(o=>{let s=ir("/bin/sh",["-c",e],{cwd:t,env:It(process.env),detached:!0,stdio:["ignore","pipe","pipe"]}),r=!1,a=new Lt,c=new Lt;s.stdout.on("data",g=>a.add(g)),s.stderr.on("data",g=>c.add(g));let d=setTimeout(()=>{r=!0;try{process.kill(-s.pid,"SIGKILL")}catch{}},n),u=(g,h="")=>{clearTimeout(d),o(l("agent.tools.shell_result",`exit code: {0}{1}{2}
40
40
  --- stdout ---
41
41
  {3}
42
42
  --- stderr ---
43
- {4}`,g??"?",r?` (timed out after ${n}ms)`:"",_,ce(a.text(),Math.floor(L.maxToolOutputBytes*.65)),ce(c.text(),Math.floor(L.maxToolOutputBytes*.3))))};s.on("error",g=>u(127,` (${g.message})`)),s.on("close",g=>u(g))})}var bo={read:"read_file",readfile:"read_file",cat:"read_file",open_file:"read_file",write:"write_file",writefile:"write_file",create_file:"write_file",edit:"edit_file",editfile:"edit_file",str_replace:"edit_file",replace:"edit_file",ls:"list_dir",list:"list_dir",listdir:"list_dir",list_directory:"list_dir",search:"grep",rg:"grep",find_in_files:"grep",shell:"run_shell",bash:"run_shell",exec:"run_shell",run:"run_shell",run_command:"run_shell",find:"glob",find_files:"glob",file_search:"glob",read_files:"read_multiple_files",read_multiple:"read_multiple_files",batch_read:"read_multiple_files",reason:"think",plan:"think",thinking:"think"},xo={file_path:"path",filepath:"path",file:"path",filename:"path",dir:"path",directory:"path",folder:"path",contents:"content",text:"content",body:"content",old:"old_string",oldstring:"old_string",old_str:"old_string",oldtext:"old_string",search:"old_string",new:"new_string",newstring:"new_string",new_str:"new_string",newtext:"new_string",replacement:"new_string",regex:"pattern",query:"pattern",search_pattern:"pattern",cmd:"command",script:"command",workdir:"cwd",working_directory:"cwd"};function mr(t){if(pt.includes(t))return t;let e=t.trim().toLowerCase().replace(/[-\s]/g,"_");return pt.includes(e)?e:bo[e]??bo[e.replace(/_/g,"")]??null}function ko(t){let e="",n=!1,o=!1;for(let s of t)if(n){if(o){e+=s,o=!1;continue}if(s==="\\"){e+=s,o=!0;continue}if(s==='"'){n=!1,e+=s;continue}if(s===`
44
- `){e+="\\n";continue}if(s==="\r"){e+="\\r";continue}if(s===" "){e+="\\t";continue}e+=s}else s==='"'&&(n=!0),e+=s;return e}function pr(t){let e=[],n=!1,o=!1;for(let s of t){if(n){o?o=!1:s==="\\"?o=!0:s==='"'&&(n=!1);continue}s==='"'?n=!0:s==="{"?e.push("}"):s==="["?e.push("]"):(s==="}"||s==="]")&&e.pop()}return t+(n?'"':"")+e.reverse().join("")}function gr(t){try{return JSON.parse(t)}catch{return}}function $o(t){let e=t;for(let n=0;n<3&&typeof e=="string";n++){let o=e.trim();if(o=o.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/,""),o==="")return{};let s=o.indexOf("{"),r=o.lastIndexOf("}"),a=[o,o.replace(/,\s*([}\]])/g,"$1").replace(/([{,]\s*)'([^']+)'\s*:/g,'$1"$2":'),ko(o),s>=0&&r>s?o.slice(s,r+1):o,s>=0?pr(ko(o.slice(s)).replace(/,\s*$/,"")):o],c;for(let d of a)if(c=gr(d),c!==void 0)break;if(c===void 0)return;e=c}return e}function fr(t,e){if(Object.keys(t).some(n=>n in e))return t;for(let n of["arguments","parameters","params","input","args"]){let o=$o(t[n]);if(o&&typeof o=="object"&&!Array.isArray(o))return o}return t}function kn(t,e){let n=mr(t);if(!n)return{ok:!1,error:`unknown tool "${t}". Available: ${pt.join(", ")}`};let o=$o(e);if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:`arguments for ${n} are not a valid JSON object`};let s=Ke[n].shape,r=fr(o,s),a=Ke[n].safeParse(r),c=n!==t;if(a.success)return{ok:!0,name:n,args:a.data,repaired:c};let d={};for(let[_,R]of Object.entries(r)){let v=_ in s?_:xo[_]??xo[_.toLowerCase()]??_;v in s&&!(v in d)&&(d[v]=R)}n==="grep"&&d.pattern===void 0&&typeof d.path=="string"&&r.query&&(d.pattern=r.query);for(let _ of["path","cwd"])typeof d[_]=="number"&&(d[_]=String(d[_]));n==="run_shell"&&Array.isArray(d.command)&&(d.command=d.command.join(" "));let u=Ke[n].safeParse(d);if(u.success)return{ok:!0,name:n,args:u.data,repaired:!0};let g=u.error.issues.map(_=>`${_.path.join(".")||"(root)"}: ${_.message}`).join("; ");return{ok:!1,error:`invalid arguments for ${n}: ${g}. Expected: ${Object.keys(s).join(", ")}`}}import vn from"fs/promises";import $n from"path";var hr=12e3,vo=500,So=8e3;async function To(t,e){try{return pe(await vn.realpath(t),await vn.realpath(e)).inside}catch{return!0}}async function Sn(t){try{let e=await vn.readFile(t,"utf8");return e.length>So?e.slice(0,So)+`
45
- \u2026[truncated]`:e}catch{return null}}function Ve(t){if(!t)return null;let e=t.replace(/<!--[\s\S]*?-->/g,"").trim();return e.split(/\r?\n/).some(n=>n.trim()&&!n.trim().startsWith("#"))?e:null}async function Ro(t,e){let n=[`Project root: ${t}`],o=async c=>await To(t,c)?Sn(c):null,s=await o($n.join(t,h.dirName,"skills.md")),r=await o($n.join(t,h.dirName,"memory.md")),a=e?await Sn($n.join(e,h.dirName,"memory.md")):null;return Ve(s)&&n.push(`## Project skills \u2014 conventions you MUST follow in this repo
43
+ {4}`,g??"?",r?` (timed out after ${n}ms)`:"",h,le(a.text(),Math.floor(L.maxToolOutputBytes*.65)),le(c.text(),Math.floor(L.maxToolOutputBytes*.3))))};s.on("error",g=>u(127,` (${g.message})`)),s.on("close",g=>u(g))})}var ko={read:"read_file",readfile:"read_file",cat:"read_file",open_file:"read_file",write:"write_file",writefile:"write_file",create_file:"write_file",edit:"edit_file",editfile:"edit_file",str_replace:"edit_file",replace:"edit_file",ls:"list_dir",list:"list_dir",listdir:"list_dir",list_directory:"list_dir",search:"grep",rg:"grep",find_in_files:"grep",shell:"run_shell",bash:"run_shell",exec:"run_shell",run:"run_shell",run_command:"run_shell",find:"glob",find_files:"glob",file_search:"glob",read_files:"read_multiple_files",read_multiple:"read_multiple_files",batch_read:"read_multiple_files",reason:"think",plan:"think",thinking:"think"},$o={file_path:"path",filepath:"path",file:"path",filename:"path",dir:"path",directory:"path",folder:"path",contents:"content",text:"content",body:"content",old:"old_string",oldstring:"old_string",old_str:"old_string",oldtext:"old_string",search:"old_string",new:"new_string",newstring:"new_string",new_str:"new_string",newtext:"new_string",replacement:"new_string",regex:"pattern",query:"pattern",search_pattern:"pattern",cmd:"command",script:"command",workdir:"cwd",working_directory:"cwd"};function gr(e){if(ht.includes(e))return e;let t=e.trim().toLowerCase().replace(/[-\s]/g,"_");return ht.includes(t)?t:ko[t]??ko[t.replace(/_/g,"")]??null}function vo(e){let t="",n=!1,o=!1;for(let s of e)if(n){if(o){t+=s,o=!1;continue}if(s==="\\"){t+=s,o=!0;continue}if(s==='"'){n=!1,t+=s;continue}if(s===`
44
+ `){t+="\\n";continue}if(s==="\r"){t+="\\r";continue}if(s===" "){t+="\\t";continue}t+=s}else s==='"'&&(n=!0),t+=s;return t}function fr(e){let t=[],n=!1,o=!1;for(let s of e){if(n){o?o=!1:s==="\\"?o=!0:s==='"'&&(n=!1);continue}s==='"'?n=!0:s==="{"?t.push("}"):s==="["?t.push("]"):(s==="}"||s==="]")&&t.pop()}return e+(n?'"':"")+t.reverse().join("")}function hr(e){try{return JSON.parse(e)}catch{return}}function So(e){let t=e;for(let n=0;n<3&&typeof t=="string";n++){let o=t.trim();if(o=o.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/,""),o==="")return{};let s=o.indexOf("{"),r=o.lastIndexOf("}"),a=[o,o.replace(/,\s*([}\]])/g,"$1").replace(/([{,]\s*)'([^']+)'\s*:/g,'$1"$2":'),vo(o),s>=0&&r>s?o.slice(s,r+1):o,s>=0?fr(vo(o.slice(s)).replace(/,\s*$/,"")):o],c;for(let d of a)if(c=hr(d),c!==void 0)break;if(c===void 0)return;t=c}return t}function _r(e,t){if(Object.keys(e).some(n=>n in t))return e;for(let n of["arguments","parameters","params","input","args"]){let o=So(e[n]);if(o&&typeof o=="object"&&!Array.isArray(o))return o}return e}function vn(e,t){let n=gr(e);if(!n)return{ok:!1,error:`unknown tool "${e}". Available: ${ht.join(", ")}`};let o=So(t);if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:`arguments for ${n} are not a valid JSON object`};let s=Xe[n].shape,r=_r(o,s),a=Xe[n].safeParse(r),c=n!==e;if(a.success)return{ok:!0,name:n,args:a.data,repaired:c};let d={};for(let[h,R]of Object.entries(r)){let v=h in s?h:$o[h]??$o[h.toLowerCase()]??h;v in s&&!(v in d)&&(d[v]=R)}n==="grep"&&d.pattern===void 0&&typeof d.path=="string"&&r.query&&(d.pattern=r.query);for(let h of["path","cwd"])typeof d[h]=="number"&&(d[h]=String(d[h]));n==="run_shell"&&Array.isArray(d.command)&&(d.command=d.command.join(" "));let u=Xe[n].safeParse(d);if(u.success)return{ok:!0,name:n,args:u.data,repaired:!0};let g=u.error.issues.map(h=>`${h.path.join(".")||"(root)"}: ${h.message}`).join("; ");return{ok:!1,error:`invalid arguments for ${n}: ${g}. Expected: ${Object.keys(s).join(", ")}`}}import Tn from"fs/promises";import Sn from"path";var wr=12e3,To=500,Ro=8e3;async function Eo(e,t){try{return pe(await Tn.realpath(e),await Tn.realpath(t)).inside}catch{return!0}}async function Rn(e){try{let t=await Tn.readFile(e,"utf8");return t.length>Ro?t.slice(0,Ro)+`
45
+ \u2026[truncated]`:t}catch{return null}}function Qe(e){if(!e)return null;let t=e.replace(/<!--[\s\S]*?-->/g,"").trim();return t.split(/\r?\n/).some(n=>n.trim()&&!n.trim().startsWith("#"))?t:null}async function Mo(e,t){let n=[`Project root: ${e}`],o=async c=>await Eo(e,c)?Rn(c):null,s=await o(Sn.join(e,_.dirName,"skills.md")),r=await o(Sn.join(e,_.dirName,"memory.md")),a=t?await Rn(Sn.join(t,_.dirName,"memory.md")):null;return Qe(s)&&n.push(`## Project skills \u2014 conventions you MUST follow in this repo
46
46
  (Set by the user in .forge/skills.md; they override your defaults.)
47
- ${Ve(s)}`),Ve(r)&&n.push(`## Project memory \u2014 facts about this project
48
- ${Ve(r)}`),Ve(a)&&n.push(`## Personal preferences \u2014 apply to all projects
49
- ${Ve(a)}`),n.join(`
47
+ ${Qe(s)}`),Qe(r)&&n.push(`## Project memory \u2014 facts about this project
48
+ ${Qe(r)}`),Qe(a)&&n.push(`## Personal preferences \u2014 apply to all projects
49
+ ${Qe(a)}`),n.join(`
50
50
 
51
- `)}async function Eo(t,e){let n=[...new Set([...e.matchAll(/(?:^|\s)@([^\s]+)/g)].map(s=>s[1]))],o=[];for(let s of n){let{abs:r,inside:a}=pe(t,s);if(!a||!await To(t,r))continue;let c=await Sn(r);if(c!==null){let d=ce(c,hr);o.push(`<file path="${s}">
51
+ `)}async function Co(e,t){let n=[...new Set([...t.matchAll(/(?:^|\s)@([^\s]+)/g)].map(s=>s[1]))],o=[];for(let s of n){let{abs:r,inside:a}=pe(e,s);if(!a||!await Eo(e,r))continue;let c=await Rn(r);if(c!==null){let d=le(c,wr);o.push(`<file path="${s}">
52
52
  ${d}
53
- </file>`)}}return o.length?`${e}
53
+ </file>`)}}return o.length?`${t}
54
54
 
55
55
  ${o.join(`
56
56
 
57
- `)}`:e}function Tn(t){return ce(t,L.maxToolOutputBytes)}function It(t,e=L.maxContextTokens*L.charsPerToken){let n=r=>r.reduce((a,c)=>a+(c.content?.length??0)+(c.role==="assistant"?c.tool_calls?.reduce((d,u)=>d+u.arguments.length,0)??0:0),0),o=t.slice();if(n(o)<=e)return o;let s=o.map(r=>r.role).lastIndexOf("user");for(o=o.map((r,a)=>r.role==="tool"&&a<s&&r.content.length>vo?{...r,content:r.content.slice(0,vo)+`
58
- \u2026[older output truncated]`}:r);n(o)>e;){let r=o.findIndex((c,d)=>d>0&&c.role==="user"),a=o.findIndex((c,d)=>d>r&&c.role==="user");if(r<0||a<0)break;o.splice(r,a-r)}return o}function Xe(t){let e=0;for(let n of t)if(e+=n.content?.length??0,n.role==="user"&&(e+=(n.images?.length??0)*6e3),n.role==="assistant")for(let o of n.tool_calls??[])e+=o.name.length+o.arguments.length;return Math.ceil(e/L.charsPerToken)}import kr from"fs/promises";import{spawn as _r}from"child_process";import Ot from"fs/promises";import{createHash as wr}from"crypto";import Ze from"path";var Mo=1e4,Co=2e3,Lt=["PreToolUse","PostToolUse"],yr=t=>Ze.join(t,h.dirName,"hooks.json"),Po=()=>({PreToolUse:[],PostToolUse:[]});async function Ao(t){let e=Po();try{let n=JSON.parse(await Ot.readFile(t,"utf8"));for(let o of Lt){let s=n?.hooks?.[o];if(Array.isArray(s))for(let r of s)r&&typeof r.command=="string"&&r.command.trim()&&e[o].push({command:r.command,...typeof r.matcher=="string"&&r.matcher?{matcher:r.matcher}:{}})}}catch{}return e}var Ft=t=>Ao(yr(t)),Fe=t=>Lt.reduce((e,n)=>e+t[n].length,0),Rn=t=>Ze.join(t,h.dirName,"trusted-hooks.json"),jo=t=>wr("sha256").update(JSON.stringify(t)).digest("hex");async function No(t){try{return JSON.parse(await Ot.readFile(Rn(t),"utf8"))}catch{return{}}}async function Io(t,e){let n=await No(e);n[Ze.resolve(t)]=jo(await Ft(t)),await Ot.mkdir(Ze.dirname(Rn(e)),{recursive:!0}),await Ot.writeFile(Rn(e),JSON.stringify(n,null,2),{mode:384})}async function gt(t,e){let n=await Ao(Ze.join(e,h.dirName,"hooks.json")),o=await Ft(t),s=Fe(o)===0||(await No(e))[Ze.resolve(t)]===jo(o),r={...Po(),untrusted:s?[]:Lt.flatMap(a=>o[a])};for(let a of Lt)r[a]=[...n[a],...s?o[a]:[]];return r}function br(t,e,n){return new Promise(o=>{let s="",r="",a=!1,c=g=>{a||(a=!0,clearTimeout(u),o(g))},d=_r("/bin/sh",["-c",t.command],{cwd:n,env:At(process.env),stdio:["pipe","pipe","pipe"]}),u=setTimeout(()=>{d.kill("SIGKILL"),c({code:null,text:"",error:`timed out after ${Mo/1e3}s`})},Mo);d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),d.stdout.on("data",g=>{s=(s+g).slice(0,Co)}),d.stderr.on("data",g=>{r=(r+g).slice(0,Co)}),d.on("error",g=>c({code:null,text:"",error:`cannot start: ${g.message}`})),d.on("close",g=>c({code:g,text:r.trim()||s.trim()})),d.stdin.on("error",()=>{}),d.stdin.end(JSON.stringify(e))})}var xr=(t,e)=>{if(!t.matcher)return!0;try{return new RegExp(t.matcher).test(e)}catch{return!1}};async function En(t,e,n,o){let s={warnings:[]},r=t?.[e]?.filter(c=>xr(c,o.tool))??[];if(!r.length)return s;let a={event:e,tool:o.tool,args:o.args,...e==="PostToolUse"?{ok:o.ok,output:o.output}:{}};for(let c of r){let d=await br(c,a,n);if(d.error)s.warnings.push(`hook "${c.command}" ${d.error}`);else{if(d.code===2&&e==="PreToolUse")return s.blocked=d.text||`hook "${c.command}" blocked this call`,s;d.code!==0&&s.warnings.push(`hook "${c.command}" exited ${d.code}${d.text?`: ${d.text}`:""}`)}}return s}var Fo=new Set(["read_file","list_dir","grep","glob","read_multiple_files","think"]),Oo=`
57
+ `)}`:t}function En(e){return le(e,L.maxToolOutputBytes)}function Ft(e,t=L.maxContextTokens*L.charsPerToken){let n=r=>r.reduce((a,c)=>a+(c.content?.length??0)+(c.role==="assistant"?c.tool_calls?.reduce((d,u)=>d+u.arguments.length,0)??0:0),0),o=e.slice();if(n(o)<=t)return o;let s=o.map(r=>r.role).lastIndexOf("user");for(o=o.map((r,a)=>r.role==="tool"&&a<s&&r.content.length>To?{...r,content:r.content.slice(0,To)+`
58
+ \u2026[older output truncated]`}:r);n(o)>t;){let r=o.findIndex((c,d)=>d>0&&c.role==="user"),a=o.findIndex((c,d)=>d>r&&c.role==="user");if(r<0||a<0)break;o.splice(r,a-r)}return o}function et(e){let t=0;for(let n of e)if(t+=n.content?.length??0,n.role==="user"&&(t+=(n.images?.length??0)*6e3),n.role==="assistant")for(let o of n.tool_calls??[])t+=o.name.length+o.arguments.length;return Math.ceil(t/L.charsPerToken)}import vr from"fs/promises";import{spawn as yr}from"child_process";import Dt from"fs/promises";import{createHash as br}from"crypto";import tt from"path";var Po=1e4,Ao=2e3,Ut=["PreToolUse","PostToolUse"],xr=e=>tt.join(e,_.dirName,"hooks.json"),jo=()=>({PreToolUse:[],PostToolUse:[]});async function No(e){let t=jo();try{let n=JSON.parse(await Dt.readFile(e,"utf8"));for(let o of Ut){let s=n?.hooks?.[o];if(Array.isArray(s))for(let r of s)r&&typeof r.command=="string"&&r.command.trim()&&t[o].push({command:r.command,...typeof r.matcher=="string"&&r.matcher?{matcher:r.matcher}:{}})}}catch{}return t}var Bt=e=>No(xr(e)),Be=e=>Ut.reduce((t,n)=>t+e[n].length,0),Mn=e=>tt.join(e,_.dirName,"trusted-hooks.json"),Io=e=>br("sha256").update(JSON.stringify(e)).digest("hex");async function Oo(e){try{return JSON.parse(await Dt.readFile(Mn(e),"utf8"))}catch{return{}}}async function Lo(e,t){let n=await Oo(t);n[tt.resolve(e)]=Io(await Bt(e)),await Dt.mkdir(tt.dirname(Mn(t)),{recursive:!0}),await Dt.writeFile(Mn(t),JSON.stringify(n,null,2),{mode:384})}async function _t(e,t){let n=await No(tt.join(t,_.dirName,"hooks.json")),o=await Bt(e),s=Be(o)===0||(await Oo(t))[tt.resolve(e)]===Io(o),r={...jo(),untrusted:s?[]:Ut.flatMap(a=>o[a])};for(let a of Ut)r[a]=[...n[a],...s?o[a]:[]];return r}function kr(e,t,n){return new Promise(o=>{let s="",r="",a=!1,c=g=>{a||(a=!0,clearTimeout(u),o(g))},d=yr("/bin/sh",["-c",e.command],{cwd:n,env:It(process.env),stdio:["pipe","pipe","pipe"]}),u=setTimeout(()=>{d.kill("SIGKILL"),c({code:null,text:"",error:`timed out after ${Po/1e3}s`})},Po);d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),d.stdout.on("data",g=>{s=(s+g).slice(0,Ao)}),d.stderr.on("data",g=>{r=(r+g).slice(0,Ao)}),d.on("error",g=>c({code:null,text:"",error:`cannot start: ${g.message}`})),d.on("close",g=>c({code:g,text:r.trim()||s.trim()})),d.stdin.on("error",()=>{}),d.stdin.end(JSON.stringify(t))})}var $r=(e,t)=>{if(!e.matcher)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!1}};async function Cn(e,t,n,o){let s={warnings:[]},r=e?.[t]?.filter(c=>$r(c,o.tool))??[];if(!r.length)return s;let a={event:t,tool:o.tool,args:o.args,...t==="PostToolUse"?{ok:o.ok,output:o.output}:{}};for(let c of r){let d=await kr(c,a,n);if(d.error)s.warnings.push(`hook "${c.command}" ${d.error}`);else{if(d.code===2&&t==="PreToolUse")return s.blocked=d.text||`hook "${c.command}" blocked this call`,s;d.code!==0&&s.warnings.push(`hook "${c.command}" exited ${d.code}${d.text?`: ${d.text}`:""}`)}}return s}var Uo=new Set(["read_file","list_dir","grep","glob","read_multiple_files","think"]),Fo=`
59
59
 
60
- [Plan mode: read-only. Explore with the read tools if needed, but do NOT edit files or run commands. Reply with a concrete numbered step-by-step plan naming the files to change and how.]`;function $r(t,e,n){return t==="run_shell"?`run shell command: ${e.command}${e.cwd?` (in ${e.cwd})`:""}`:(t==="write_file"||t==="edit_file")&&yo(n,e.path)?`${t} OUTSIDE project root: ${e.path}`:null}var Do=(t,e=L.maxRunTokens)=>t.stopReason==="max_steps"?l("agent.agent.stopped_max_steps",'Stopped after {0} steps (the per-run step limit). Say "continue" to go on, or raise it with --max-steps.',t.steps):t.stopReason==="token_budget"?l("agent.agent.stopped_token_budget",'Stopped: this run used its {0}-token budget. Say "continue" to go on, or raise it with --max-tokens.',e.toLocaleString()):t.stopReason==="interrupted"?l("agent.agent.interrupted","Interrupted by user."):null;async function Qe(t){let{client:e,model:n,messages:o,onEvent:s}=t,r={opts:t,specs:t.plan?xn().filter(_=>Fo.has(_.name)):[...xn(),...t.mcp?.specs()??[]],usage:{promptTokens:0,completionTokens:0,cacheReadTokens:0},alwaysAllow:new Set,toolErrors:0,changed:new Set,reads:new Map,cachedReads:0},a=t.maxSteps===0?1/0:Math.min(Math.max(1,t.maxSteps??L.maxSteps),L.hardMaxSteps),c=t.maxRunTokens??L.maxRunTokens,d="",u=!1;if(t.plan){let _=o[o.length-1];_?.role==="user"&&!_.content.endsWith(Oo)&&(_.content+=Oo)}let g=(_,R)=>({finalText:d,usage:r.usage,steps:_,hitStepLimit:R==="max_steps",stopReason:R,toolErrors:r.toolErrors,changedFiles:[...r.changed],cachedReads:r.cachedReads});for(let _=1;_<=a;_++){if(t.signal?.aborted)return g(_-1,"interrupted");if(c>0&&r.usage.promptTokens+r.usage.completionTokens>=c)return g(_-1,"token_budget");let R=It(o),v=Xe(R);if(!u&&v>=L.warnContextTokens&&(u=!0,s?.({type:"context_warning",tokens:v})),t.signal?.aborted)return g(_-1,"interrupted");let W=!1,Z=t.stream?be=>{W=!0,s?.({type:"token",text:be})}:void 0,I=await e.chat({model:n,messages:R,tools:r.specs,onToken:Z});if(t.signal?.aborted)return g(_,"interrupted");if(Uo(r,I.usage),o.push({role:"assistant",content:I.content,tool_calls:I.toolCalls.length?I.toolCalls:void 0}),I.content&&(d=I.content,s?.({type:"assistant",text:I.content,streamed:W})),!I.toolCalls.length)return g(_,"done");for(let be of I.toolCalls){if(t.signal?.aborted)return g(_,"interrupted");let re=await Er(be,r);o.push({role:"tool",tool_call_id:be.id,content:Tn(re)})}}return g(a,"max_steps")}var Uo=(t,e)=>{t.usage.promptTokens+=e.promptTokens,t.usage.completionTokens+=e.completionTokens,t.usage.cacheReadTokens=(t.usage.cacheReadTokens??0)+(e.cacheReadTokens??0)};async function vr(t,e,n){let{client:o,model:s,messages:r}=n.opts,a=r.map(u=>u.role).lastIndexOf("assistant"),c=r.slice(0,a),d=`Your previous tool call was invalid and was not executed.
61
- Tool: ${t.name}
62
- Arguments: ${t.arguments.slice(0,2e3)}
63
- Problem: ${e}
64
- Re-issue exactly that action as ONE corrected tool call with valid JSON arguments.`;try{let u=await o.chat({model:s,messages:It([...c,{role:"user",content:d}]),tools:n.specs});Uo(n,u.usage);let g=u.toolCalls[0];return g?kn(g.name,g.arguments):{ok:!1,error:e}}catch{return{ok:!1,error:e}}}async function Sr(t,e){let{abs:n,inside:o}=(t.remote?Oe:pe)(t.root,e);if(!o)return null;try{if(t.remote){let r=await t.remote.stat(n);return r?.isFile?{abs:n,sig:`${r.mtimeMs}:${r.size}`}:null}let s=await kr.stat(n);return s.isFile()?{abs:n,sig:`${s.mtimeMs}:${s.size}`}:null}catch{return null}}function Tr(t,e){return It(t.opts.messages).some(n=>n.role==="tool"&&n.tool_call_id===e.callId&&n.content===e.content)}var Lo=t=>`ERROR: plan mode is read-only; ${t} is not available. Use read_file, list_dir, grep or glob to explore, then present the plan as text.`;async function Bo(t,e,n){let o=await En(n.opts.hooks,"PreToolUse",n.opts.ctx.root,{tool:t,args:e});for(let r of o.warnings)n.opts.onEvent?.({type:"hook_warning",name:t,message:r});if(o.blocked===void 0)return null;let s=`BLOCKED by hook: ${o.blocked}`;return n.opts.onEvent?.({type:"tool_result",name:t,ok:!1,output:s}),s}async function Dt(t,e,n,o,s){let r=await En(s.opts.hooks,"PostToolUse",s.opts.ctx.root,{tool:t,args:e,ok:n,output:o});for(let a of r.warnings)s.opts.onEvent?.({type:"hook_warning",name:t,message:a})}async function Rr(t,e){let{onEvent:n,mcp:o}=e.opts,s={};try{s=t.arguments.trim()?JSON.parse(t.arguments):{}}catch{e.toolErrors++;let a="arguments are not valid JSON";return n?.({type:"tool_result",name:t.name,ok:!1,output:a}),`ERROR: ${a}`}n?.({type:"tool_start",name:t.name,args:s});let r=await Bo(t.name,s,e);if(r)return r;if(!e.opts.yolo&&!e.alwaysAllow.has(t.name)){let a=e.opts.approve?await e.opts.approve({name:t.name,args:s,reason:`call MCP tool ${t.name}`}):!1;if(!a)return n?.({type:"denied",name:t.name}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";a==="always"&&e.alwaysAllow.add(t.name)}try{let a=await o.call(t.name,s);return n?.({type:"tool_result",name:t.name,ok:!0,output:a}),await Dt(t.name,s,!0,a,e),a}catch(a){let c=a instanceof Error?a.message:String(a);return e.toolErrors++,n?.({type:"tool_result",name:t.name,ok:!1,output:c}),await Dt(t.name,s,!1,c,e),`ERROR: ${c}`}}async function Er(t,e){let{onEvent:n}=e.opts;if(e.opts.plan&&!Fo.has(t.name))return n?.({type:"tool_result",name:t.name,ok:!1,output:Lo(t.name)}),Lo(t.name);if(e.opts.mcp?.has(t.name))return Rr(t,e);let o=kn(t.name,t.arguments);if(o.ok&&o.repaired&&n?.({type:"repair",name:o.name,via:"normalize"}),!o.ok){let g=await vr(t,o.error,e);g.ok&&n?.({type:"repair",name:g.name,via:"model"}),o=g.ok?g:o}if(!o.ok)return e.toolErrors++,n?.({type:"tool_result",name:t.name,ok:!1,output:o.error}),`ERROR: ${o.error}`;let{name:s,args:r}=o;n?.({type:"tool_start",name:s,args:r});let a=await Bo(s,r,e);if(a)return a;let c={...e.opts.ctx},d=null;if(s==="read_file"){d=await Sr(c,r.path);let g=d&&e.reads.get(d.abs);if(g&&d&&g.sig===d.sig&&Tr(e,g)){e.cachedReads++;let _=`(unchanged: "${r.path}" has not changed since you read it earlier in this conversation; use that earlier result.)`;return n?.({type:"tool_result",name:s,ok:!0,output:_}),_}}let u=$r(s,r,c);if(u&&!e.opts.yolo&&!e.alwaysAllow.has(s)){let g=e.opts.approve?await e.opts.approve({name:s,args:r,reason:u}):!1;if(!g)return n?.({type:"denied",name:s}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";g==="always"&&e.alwaysAllow.add(s)}u&&(s==="write_file"||s==="edit_file")&&(c.allowOutside=!0);try{let g=await Ye(s,r,c);return s==="write_file"||s==="edit_file"?(e.changed.add(r.path),e.reads.delete((c.remote?Oe:pe)(c.root,r.path).abs)):s==="run_shell"?e.reads.clear():s==="read_file"&&d&&e.reads.set(d.abs,{sig:d.sig,callId:t.id,content:Tn(g)}),n?.({type:"tool_result",name:s,ok:!0,output:g}),await Dt(s,r,!0,g,e),g}catch(g){let _=g instanceof Error?g.message:String(g);return e.toolErrors++,n?.({type:"tool_result",name:s,ok:!1,output:_}),await Dt(s,r,!1,_,e),`ERROR: ${_}`}}var ne=class extends Error{constructor(n,o,s){super(o);this.status=n;this.body=s}status;body;get code(){return this.body?.error?.code}},Mr="The selected model is temporarily unavailable. Please try again shortly, or switch models with /model.";function Wo(t,e){return[401,402,403,429].includes(t)?e:t>=500?Mr:e}var Re=class extends Error{constructor(n,o){super(`cannot reach server (${o})`);this.url=n;this.reason=o}url;reason},Cr=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","ETIMEDOUT","EAI_AGAIN","ECONNRESET","ENETUNREACH"]),Pr=3,Ar=new Set([429,500,502,503,504]),jr=1e4;function Nr(t,e=1e3){let n=t?Number(t):NaN;return Math.min(jr,Number.isFinite(n)&&n>=0?n*1e3:e)}var Ut=class{constructor(e){this.cfg=e}cfg;async chat(e){let n=`${this.cfg.baseUrl.replace(/\/$/,"")}/chat/completions`,o=JSON.stringify({model:e.model,messages:Lr(e.messages),tools:e.tools.map(a=>({type:"function",function:a})),...e.onToken?{stream:!0,stream_options:{include_usage:!0}}:{}}),s=this.cfg.fetch??fetch,r=this.cfg.sleep??(a=>new Promise(c=>setTimeout(c,a)));for(let a=1;;a++){let c;try{c=await s(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`},body:o,signal:AbortSignal.timeout(this.cfg.timeoutMs??18e4)})}catch(_){let R=_?.cause?.code;if(Cr.has(R)&&a<=Pr){let v=1e3*2**(a-1);this.cfg.onRetry?.({status:0,attempt:a,delayMs:v}),await r(v);continue}throw new Re(n,R??_?.name??_?.message??"network error")}if(c.ok)return e.onToken&&c.body?await Or(c.body,e.onToken,n):Ir(await c.json());let d=await c.text();if(Ar.has(c.status)&&a===1){let _=Nr(c.headers.get("retry-after"));this.cfg.onRetry?.({status:c.status,attempt:a,delayMs:_}),await r(_);continue}let u,g=d;try{u=JSON.parse(d),g=u.error?.message??u.error??d}catch{}throw new ne(c.status,Wo(c.status,typeof g=="string"?g:JSON.stringify(g)),u)}}};function Ir(t){let e=t.choices?.[0]?.message??{};return{content:e.content??null,toolCalls:(e.tool_calls??[]).map((n,o)=>({id:n.id??`call_${o}`,name:n.function?.name??"",arguments:typeof n.function?.arguments=="string"?n.function.arguments:JSON.stringify(n.function?.arguments??{})})),usage:{promptTokens:t.usage?.prompt_tokens??0,completionTokens:t.usage?.completion_tokens??0,cacheReadTokens:qo(t.usage)}}}function qo(t){let e=t?.prompt_cache_hit_tokens??t?.prompt_tokens_details?.cached_tokens??t?.cache_read_input_tokens??0;return Number.isFinite(e)&&e>0?e:0}async function Or(t,e,n="stream"){let o=t.getReader(),s=new TextDecoder,r="",a="",c,d=new Map,u=g=>{if(!g.startsWith("data:"))return;let _=g.slice(5).trim();if(!_||_==="[DONE]")return;let R;try{R=JSON.parse(_)}catch{return}if(R.error)throw new ne(502,Wo(502,R.error.message??"stream error"),R);R.usage&&(c=R.usage);let v=R.choices?.[0]?.delta;if(v){typeof v.content=="string"&&v.content&&(a+=v.content,e(v.content));for(let W of v.tool_calls??[]){let Z=W.index??0,I=d.get(Z)??{id:"",name:"",arguments:""};W.id&&(I.id=W.id),W.function?.name&&(I.name+=W.function.name),typeof W.function?.arguments=="string"&&(I.arguments+=W.function.arguments),d.set(Z,I)}}};try{for(;;){let{done:g,value:_}=await o.read();if(g)break;r+=s.decode(_,{stream:!0});let R;for(;(R=r.indexOf(`
65
- `))>=0;)u(r.slice(0,R).replace(/\r$/,"")),r=r.slice(R+1)}r.trim()&&u(r.trim())}catch(g){throw g instanceof ne?g:new Re(n,g?.cause?.code??g?.name??g?.message??"stream interrupted")}return{content:a||null,toolCalls:[...d.entries()].sort((g,_)=>g[0]-_[0]).map(([g,_])=>({id:_.id||`call_${g}`,name:_.name,arguments:_.arguments||"{}"})),usage:{promptTokens:c?.prompt_tokens??0,completionTokens:c?.completion_tokens??0,cacheReadTokens:qo(c)}}}function Lr(t){let e=t.flatMap((s,r)=>s.role==="user"&&s.images?.length?[r]:[]),n=new Set,o=0;for(let s of e.slice(-me.keepInRequest).reverse()){let r=t[s].images.reduce((a,c)=>a+c.data.length,0);if(n.size>0&&o+r>me.maxRequestBytes)break;n.add(s),o+=r}return t.map((s,r)=>s.role==="assistant"&&s.tool_calls?{role:"assistant",content:s.content,tool_calls:s.tool_calls.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:a.arguments}}))}:s.role==="user"&&s.images?.length?n.has(r)?{role:"user",content:[{type:"text",text:s.content},...s.images.map(a=>({type:"image_url",image_url:{url:`data:${a.mediaType};base64,${a.data}`}}))]}:{role:"user",content:`${s.content}
66
- [${s.images.length} earlier image(s) omitted]`}:s)}function Fr(t){let e=t[t.length-1],n={id:"mock-1",object:"chat.completion",model:"mock-model"},o={prompt_tokens:50,completion_tokens:20,total_tokens:70,prompt_tokens_details:{cached_tokens:t.length>2?40:0}},s=_=>({...n,usage:o,choices:[{index:0,finish_reason:"stop",message:{role:"assistant",content:_}}]});if(e?.role==="tool")return s(String(e.content).startsWith("ERROR")?`That failed: ${e.content}`:"Done.");let r=String([...t].reverse().find(_=>_.role==="user")?.content??""),a=r.match(/create (?:a |an )?([\w./-]+\.\w+)/i)?.[1];if(!a)return s("Mock model: try `create hello.ts that logs hi`.");let c=String(t.find(_=>_.role==="system")?.content??""),d=/single quotes?/i.test(c)?"'":'"',u=/no semicolons|semicolon-free|without semicolons/i.test(c)?"":";",g=r.match(/logs?\s+["']?([^"'\n]+?)["']?\s*(?:\n|$)/i)?.[1]??"hi";return{...n,usage:o,choices:[{index:0,finish_reason:"tool_calls",message:{role:"assistant",content:null,tool_calls:[{id:"call_mock",type:"function",function:{name:"write_file",arguments:JSON.stringify({path:a,content:`console.log(${g.includes(d)?JSON.stringify(g):d+g+d})${u}
67
- `})}}]}}]}}var De=class{async chat(e){let n=Fr(e.messages).choices[0].message;return{content:n.content,toolCalls:(n.tool_calls??[]).map(o=>({id:o.id,name:o.function.name,arguments:o.function.arguments})),usage:{promptTokens:50,completionTokens:20}}}};import Mn from"fs/promises";import Ho from"path";async function ft(t,e){let n=e.replace(/\s+/g," ").trim().replace(/^[-*]\s*/,"").slice(0,300);if(!n)throw new Error("empty learning");let o=Ho.join(t,h.dirName,"memory.md");await Mn.mkdir(Ho.dirname(o),{recursive:!0});let s="";try{s=await Mn.readFile(o,"utf8")}catch{}let r=s===""?`# Project memory
60
+ [Plan mode: read-only. Explore with the read tools if needed, but do NOT edit files or run commands. Reply with a concrete numbered step-by-step plan naming the files to change and how.]`;function Sr(e,t,n){return e==="run_shell"?`run shell command: ${t.command}${t.cwd?` (in ${t.cwd})`:""}`:(e==="write_file"||e==="edit_file")&&xo(n,t.path)?`${e} OUTSIDE project root: ${t.path}`:null}var Bo=(e,t=L.maxRunTokens)=>e.stopReason==="max_steps"?l("agent.agent.stopped_max_steps",'Stopped after {0} steps (the per-run step limit). Say "continue" to go on, or raise it with --max-steps.',e.steps):e.stopReason==="token_budget"?l("agent.agent.stopped_token_budget",'Stopped: this run used its {0}-token budget. Say "continue" to go on, or raise it with --max-tokens.',t.toLocaleString()):e.stopReason==="interrupted"?l("agent.agent.interrupted","Interrupted by user."):null;async function nt(e){let{client:t,model:n,messages:o,onEvent:s}=e,r={opts:e,specs:e.plan?$n().filter(h=>Uo.has(h.name)):[...$n(),...e.mcp?.specs()??[]],usage:{promptTokens:0,completionTokens:0,cacheReadTokens:0},alwaysAllow:new Set,toolErrors:0,changed:new Set,reads:new Map,cachedReads:0},a=e.maxSteps===0?1/0:Math.min(Math.max(1,e.maxSteps??L.maxSteps),L.hardMaxSteps),c=e.maxRunTokens??L.maxRunTokens,d="",u=!1;if(e.plan){let h=o[o.length-1];h?.role==="user"&&!h.content.endsWith(Fo)&&(h.content+=Fo)}let g=(h,R)=>({finalText:d,usage:r.usage,steps:h,hitStepLimit:R==="max_steps",stopReason:R,toolErrors:r.toolErrors,changedFiles:[...r.changed],cachedReads:r.cachedReads});for(let h=1;h<=a;h++){if(e.signal?.aborted)return g(h-1,"interrupted");if(c>0&&r.usage.promptTokens+r.usage.completionTokens>=c)return g(h-1,"token_budget");let R=Ft(o),v=et(R);if(!u&&v>=L.warnContextTokens&&(u=!0,s?.({type:"context_warning",tokens:v})),e.signal?.aborted)return g(h-1,"interrupted");let W=!1,Z=e.stream?ke=>{W=!0,s?.({type:"token",text:ke})}:void 0,I=await t.chat({model:n,messages:R,tools:r.specs,onToken:Z});if(e.signal?.aborted)return g(h,"interrupted");if(Wo(r,I.usage),o.push({role:"assistant",content:I.content,tool_calls:I.toolCalls.length?I.toolCalls:void 0}),I.content&&(d=I.content,s?.({type:"assistant",text:I.content,streamed:W})),!I.toolCalls.length)return g(h,"done");for(let ke of I.toolCalls){if(e.signal?.aborted)return g(h,"interrupted");let se=await Cr(ke,r);o.push({role:"tool",tool_call_id:ke.id,content:En(se)})}}return g(a,"max_steps")}var Wo=(e,t)=>{e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.cacheReadTokens=(e.usage.cacheReadTokens??0)+(t.cacheReadTokens??0)};async function Tr(e,t,n){let{client:o,model:s,messages:r}=n.opts,a=r.map(u=>u.role).lastIndexOf("assistant"),c=r.slice(0,a),d=`Your previous tool call was invalid and was not executed.
61
+ Tool: ${e.name}
62
+ Arguments: ${e.arguments.slice(0,2e3)}
63
+ Problem: ${t}
64
+ Re-issue exactly that action as ONE corrected tool call with valid JSON arguments.`;try{let u=await o.chat({model:s,messages:Ft([...c,{role:"user",content:d}]),tools:n.specs});Wo(n,u.usage);let g=u.toolCalls[0];return g?vn(g.name,g.arguments):{ok:!1,error:t}}catch{return{ok:!1,error:t}}}async function Rr(e,t){let{abs:n,inside:o}=(e.remote?De:pe)(e.root,t);if(!o)return null;try{if(e.remote){let r=await e.remote.stat(n);return r?.isFile?{abs:n,sig:`${r.mtimeMs}:${r.size}`}:null}let s=await vr.stat(n);return s.isFile()?{abs:n,sig:`${s.mtimeMs}:${s.size}`}:null}catch{return null}}function Er(e,t){return Ft(e.opts.messages).some(n=>n.role==="tool"&&n.tool_call_id===t.callId&&n.content===t.content)}var Do=e=>`ERROR: plan mode is read-only; ${e} is not available. Use read_file, list_dir, grep or glob to explore, then present the plan as text.`;async function qo(e,t,n){let o=await Cn(n.opts.hooks,"PreToolUse",n.opts.ctx.root,{tool:e,args:t});for(let r of o.warnings)n.opts.onEvent?.({type:"hook_warning",name:e,message:r});if(o.blocked===void 0)return null;let s=`BLOCKED by hook: ${o.blocked}`;return n.opts.onEvent?.({type:"tool_result",name:e,ok:!1,output:s}),s}async function Wt(e,t,n,o,s){let r=await Cn(s.opts.hooks,"PostToolUse",s.opts.ctx.root,{tool:e,args:t,ok:n,output:o});for(let a of r.warnings)s.opts.onEvent?.({type:"hook_warning",name:e,message:a})}async function Mr(e,t){let{onEvent:n,mcp:o}=t.opts,s={};try{s=e.arguments.trim()?JSON.parse(e.arguments):{}}catch{t.toolErrors++;let a="arguments are not valid JSON";return n?.({type:"tool_result",name:e.name,ok:!1,output:a}),`ERROR: ${a}`}n?.({type:"tool_start",name:e.name,args:s});let r=await qo(e.name,s,t);if(r)return r;if(!t.opts.yolo&&!t.alwaysAllow.has(e.name)){let a=t.opts.approve?await t.opts.approve({name:e.name,args:s,reason:`call MCP tool ${e.name}`}):!1;if(!a)return n?.({type:"denied",name:e.name}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";a==="always"&&t.alwaysAllow.add(e.name)}try{let a=await o.call(e.name,s);return n?.({type:"tool_result",name:e.name,ok:!0,output:a}),await Wt(e.name,s,!0,a,t),a}catch(a){let c=a instanceof Error?a.message:String(a);return t.toolErrors++,n?.({type:"tool_result",name:e.name,ok:!1,output:c}),await Wt(e.name,s,!1,c,t),`ERROR: ${c}`}}async function Cr(e,t){let{onEvent:n}=t.opts;if(t.opts.plan&&!Uo.has(e.name))return n?.({type:"tool_result",name:e.name,ok:!1,output:Do(e.name)}),Do(e.name);if(t.opts.mcp?.has(e.name))return Mr(e,t);let o=vn(e.name,e.arguments);if(o.ok&&o.repaired&&n?.({type:"repair",name:o.name,via:"normalize"}),!o.ok){let g=await Tr(e,o.error,t);g.ok&&n?.({type:"repair",name:g.name,via:"model"}),o=g.ok?g:o}if(!o.ok)return t.toolErrors++,n?.({type:"tool_result",name:e.name,ok:!1,output:o.error}),`ERROR: ${o.error}`;let{name:s,args:r}=o;n?.({type:"tool_start",name:s,args:r});let a=await qo(s,r,t);if(a)return a;let c={...t.opts.ctx},d=null;if(s==="read_file"){d=await Rr(c,r.path);let g=d&&t.reads.get(d.abs);if(g&&d&&g.sig===d.sig&&Er(t,g)){t.cachedReads++;let h=`(unchanged: "${r.path}" has not changed since you read it earlier in this conversation; use that earlier result.)`;return n?.({type:"tool_result",name:s,ok:!0,output:h}),h}}let u=Sr(s,r,c);if(u&&!t.opts.yolo&&!t.alwaysAllow.has(s)){let g=t.opts.approve?await t.opts.approve({name:s,args:r,reason:u}):!1;if(!g)return n?.({type:"denied",name:s}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";g==="always"&&t.alwaysAllow.add(s)}u&&(s==="write_file"||s==="edit_file")&&(c.allowOutside=!0);try{let g=await Ze(s,r,c);return s==="write_file"||s==="edit_file"?(t.changed.add(r.path),t.reads.delete((c.remote?De:pe)(c.root,r.path).abs)):s==="run_shell"?t.reads.clear():s==="read_file"&&d&&t.reads.set(d.abs,{sig:d.sig,callId:e.id,content:En(g)}),n?.({type:"tool_result",name:s,ok:!0,output:g}),await Wt(s,r,!0,g,t),g}catch(g){let h=g instanceof Error?g.message:String(g);return t.toolErrors++,n?.({type:"tool_result",name:s,ok:!1,output:h}),await Wt(s,r,!1,h,t),`ERROR: ${h}`}}var ne=class extends Error{constructor(n,o,s){super(o);this.status=n;this.body=s}status;body;get code(){return this.body?.error?.code}},Pr="The selected model is temporarily unavailable. Please try again shortly, or switch models with /model.";function Ho(e,t){return[401,402,403,429].includes(e)?t:e>=500?Pr:t}var Me=class extends Error{constructor(n,o){super(`cannot reach server (${o})`);this.url=n;this.reason=o}url;reason},Ar=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","ETIMEDOUT","EAI_AGAIN","ECONNRESET","ENETUNREACH"]),jr=3,Nr=new Set([429,500,502,503,504]),Ir=1e4;function Or(e,t=1e3){let n=e?Number(e):NaN;return Math.min(Ir,Number.isFinite(n)&&n>=0?n*1e3:t)}var qt=class{constructor(t){this.cfg=t}cfg;async chat(t){let n=`${this.cfg.baseUrl.replace(/\/$/,"")}/chat/completions`,o=JSON.stringify({model:t.model,messages:Dr(t.messages),tools:t.tools.map(a=>({type:"function",function:a})),...t.onToken?{stream:!0,stream_options:{include_usage:!0}}:{}}),s=this.cfg.fetch??fetch,r=this.cfg.sleep??(a=>new Promise(c=>setTimeout(c,a)));for(let a=1;;a++){let c;try{c=await s(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`},body:o,signal:AbortSignal.timeout(this.cfg.timeoutMs??18e4)})}catch(h){let R=h?.cause?.code;if(Ar.has(R)&&a<=jr){let v=1e3*2**(a-1);this.cfg.onRetry?.({status:0,attempt:a,delayMs:v}),await r(v);continue}throw new Me(n,R??h?.name??h?.message??"network error")}if(c.ok)return t.onToken&&c.body?await Fr(c.body,t.onToken,n):Lr(await c.json());let d=await c.text();if(Nr.has(c.status)&&a===1){let h=Or(c.headers.get("retry-after"));this.cfg.onRetry?.({status:c.status,attempt:a,delayMs:h}),await r(h);continue}let u,g=d;try{u=JSON.parse(d),g=u.error?.message??u.error??d}catch{}throw new ne(c.status,Ho(c.status,typeof g=="string"?g:JSON.stringify(g)),u)}}};function Lr(e){let t=e.choices?.[0]?.message??{};return{content:t.content??null,toolCalls:(t.tool_calls??[]).map((n,o)=>({id:n.id??`call_${o}`,name:n.function?.name??"",arguments:typeof n.function?.arguments=="string"?n.function.arguments:JSON.stringify(n.function?.arguments??{})})),usage:{promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,cacheReadTokens:zo(e.usage)}}}function zo(e){let t=e?.prompt_cache_hit_tokens??e?.prompt_tokens_details?.cached_tokens??e?.cache_read_input_tokens??0;return Number.isFinite(t)&&t>0?t:0}async function Fr(e,t,n="stream"){let o=e.getReader(),s=new TextDecoder,r="",a="",c,d=new Map,u=g=>{if(!g.startsWith("data:"))return;let h=g.slice(5).trim();if(!h||h==="[DONE]")return;let R;try{R=JSON.parse(h)}catch{return}if(R.error)throw new ne(502,Ho(502,R.error.message??"stream error"),R);R.usage&&(c=R.usage);let v=R.choices?.[0]?.delta;if(v){typeof v.content=="string"&&v.content&&(a+=v.content,t(v.content));for(let W of v.tool_calls??[]){let Z=W.index??0,I=d.get(Z)??{id:"",name:"",arguments:""};W.id&&(I.id=W.id),W.function?.name&&(I.name+=W.function.name),typeof W.function?.arguments=="string"&&(I.arguments+=W.function.arguments),d.set(Z,I)}}};try{for(;;){let{done:g,value:h}=await o.read();if(g)break;r+=s.decode(h,{stream:!0});let R;for(;(R=r.indexOf(`
65
+ `))>=0;)u(r.slice(0,R).replace(/\r$/,"")),r=r.slice(R+1)}r.trim()&&u(r.trim())}catch(g){throw g instanceof ne?g:new Me(n,g?.cause?.code??g?.name??g?.message??"stream interrupted")}return{content:a||null,toolCalls:[...d.entries()].sort((g,h)=>g[0]-h[0]).map(([g,h])=>({id:h.id||`call_${g}`,name:h.name,arguments:h.arguments||"{}"})),usage:{promptTokens:c?.prompt_tokens??0,completionTokens:c?.completion_tokens??0,cacheReadTokens:zo(c)}}}function Dr(e){let t=e.flatMap((s,r)=>s.role==="user"&&s.images?.length?[r]:[]),n=new Set,o=0;for(let s of t.slice(-me.keepInRequest).reverse()){let r=e[s].images.reduce((a,c)=>a+c.data.length,0);if(n.size>0&&o+r>me.maxRequestBytes)break;n.add(s),o+=r}return e.map((s,r)=>s.role==="assistant"&&s.tool_calls?{role:"assistant",content:s.content,tool_calls:s.tool_calls.map(a=>({id:a.id,type:"function",function:{name:a.name,arguments:a.arguments}}))}:s.role==="user"&&s.images?.length?n.has(r)?{role:"user",content:[{type:"text",text:s.content},...s.images.map(a=>({type:"image_url",image_url:{url:`data:${a.mediaType};base64,${a.data}`}}))]}:{role:"user",content:`${s.content}
66
+ [${s.images.length} earlier image(s) omitted]`}:s)}function Ur(e){let t=e[e.length-1],n={id:"mock-1",object:"chat.completion",model:"mock-model"},o={prompt_tokens:50,completion_tokens:20,total_tokens:70,prompt_tokens_details:{cached_tokens:e.length>2?40:0}},s=h=>({...n,usage:o,choices:[{index:0,finish_reason:"stop",message:{role:"assistant",content:h}}]});if(t?.role==="tool")return s(String(t.content).startsWith("ERROR")?`That failed: ${t.content}`:"Done.");let r=String([...e].reverse().find(h=>h.role==="user")?.content??""),a=r.match(/create (?:a |an )?([\w./-]+\.\w+)/i)?.[1];if(!a)return s("Mock model: try `create hello.ts that logs hi`.");let c=String(e.find(h=>h.role==="system")?.content??""),d=/single quotes?/i.test(c)?"'":'"',u=/no semicolons|semicolon-free|without semicolons/i.test(c)?"":";",g=r.match(/logs?\s+["']?([^"'\n]+?)["']?\s*(?:\n|$)/i)?.[1]??"hi";return{...n,usage:o,choices:[{index:0,finish_reason:"tool_calls",message:{role:"assistant",content:null,tool_calls:[{id:"call_mock",type:"function",function:{name:"write_file",arguments:JSON.stringify({path:a,content:`console.log(${g.includes(d)?JSON.stringify(g):d+g+d})${u}
67
+ `})}}]}}]}}var We=class{async chat(t){let n=Ur(t.messages).choices[0].message;return{content:n.content,toolCalls:(n.tool_calls??[]).map(o=>({id:o.id,name:o.function.name,arguments:o.function.arguments})),usage:{promptTokens:50,completionTokens:20}}}};import Pn from"fs/promises";import Jo from"path";async function wt(e,t){let n=t.replace(/\s+/g," ").trim().replace(/^[-*]\s*/,"").slice(0,300);if(!n)throw new Error("empty learning");let o=Jo.join(e,_.dirName,"memory.md");await Pn.mkdir(Jo.dirname(o),{recursive:!0});let s="";try{s=await Pn.readFile(o,"utf8")}catch{}let r=s===""?`# Project memory
68
68
 
69
69
  `:s.endsWith(`
70
70
  `)?"":`
71
- `;return await Mn.appendFile(o,`${r}- ${n}
72
- `),o}import et from"fs/promises";import Bt from"path";var zo=300,tt=t=>Bt.join(t,h.dirName,"skills.md"),ht=t=>Bt.join(t,h.dirName,"memory.md");function Cn(t){return t.replace(/<!--[\s\S]*?-->/g,"").split(/\r?\n/).map(e=>e.match(/^\s*[-*]\s+(.+?)\s*$/)?.[1]).filter(e=>!!e)}function Dr(t){let e=t.replace(/\s+/g," ").trim().replace(/^[-*]\s+/,"").replace(/^(["'“”`])(.*)\1$/,"$2").trim();if(!e)throw new Error("skill text is empty");if(e.length>zo)throw new Error(`skill is too long (${e.length} > ${zo} chars); keep it to one short rule`);return e}var Ee=t=>t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();async function Pn(t){try{return await et.readFile(t,"utf8")}catch{return""}}async function Ue(t){return Cn(await Pn(tt(t)))}async function Me(t){return Cn(await Pn(ht(t)))}var Jo=`# Project skills
71
+ `;return await Pn.appendFile(o,`${r}- ${n}
72
+ `),o}import ot from"fs/promises";import Ht from"path";var Go=300,st=e=>Ht.join(e,_.dirName,"skills.md"),yt=e=>Ht.join(e,_.dirName,"memory.md");function An(e){return e.replace(/<!--[\s\S]*?-->/g,"").split(/\r?\n/).map(t=>t.match(/^\s*[-*]\s+(.+?)\s*$/)?.[1]).filter(t=>!!t)}function Br(e){let t=e.replace(/\s+/g," ").trim().replace(/^[-*]\s+/,"").replace(/^(["'“”`])(.*)\1$/,"$2").trim();if(!t)throw new Error("skill text is empty");if(t.length>Go)throw new Error(`skill is too long (${t.length} > ${Go} chars); keep it to one short rule`);return t}var Ce=e=>e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();async function jn(e){try{return await ot.readFile(e,"utf8")}catch{return""}}async function qe(e){return An(await jn(st(e)))}async function Pe(e){return An(await jn(yt(e)))}var Ko=`# Project skills
73
73
 
74
- `;async function nt(t,e){let n=Dr(e),o=tt(t),s=await Pn(o);if(Cn(s).some(a=>Ee(a)===Ee(n)))return{added:!1,skill:n,file:o};await et.mkdir(Bt.dirname(o),{recursive:!0});let r=s===""?Jo:s.endsWith(`
74
+ `;async function rt(e,t){let n=Br(t),o=st(e),s=await jn(o);if(An(s).some(a=>Ce(a)===Ce(n)))return{added:!1,skill:n,file:o};await ot.mkdir(Ht.dirname(o),{recursive:!0});let r=s===""?Ko:s.endsWith(`
75
75
  `)?"":`
76
- `;return await et.appendFile(o,`${r}- ${n}
77
- `),{added:!0,skill:n,file:o}}async function An(t){let e=[],n=[[tt(t),`${Jo}<!-- One rule per bullet, e.g.
76
+ `;return await ot.appendFile(o,`${r}- ${n}
77
+ `),{added:!0,skill:n,file:o}}async function Nn(e){let t=[],n=[[st(e),`${Ko}<!-- One rule per bullet, e.g.
78
78
  - Use pnpm, not npm
79
79
  -->
80
- `],[ht(t),`# Project memory
80
+ `],[yt(e),`# Project memory
81
81
 
82
82
  <!-- Facts worth remembering, one per bullet. -->
83
- `]];for(let[o,s]of n)try{await et.access(o)}catch{await et.mkdir(Bt.dirname(o),{recursive:!0}),await et.writeFile(o,s),e.push(o)}return e}var Ur=[/^\s*(no|nope|wrong|stop|wait|actually)\b[\s,.!:-]/i,/\b(don'?t|do not|never|stop (using|adding|doing|writing))\b/i,/\binstead\b/i,/\b(use|using|prefer)\b[^.!]*\b(not|over)\b/i,/\b(should|must|need to) (use|be|not|have)\b/i,/\bprefer\b/i,/\brather than\b/i,/\bthat'?s (wrong|not (what|right|how))\b/i,/\bplease (use|don'?t|do not|always|never|keep|avoid)\b/i,/\b(always|avoid)\b/i],Br=/\b(again|i (told|said|already)|as i (said|mentioned)|every time|always|never|from now on|once more)\b/i,Wr=new Set("the a an and or but to of in on for with it is are be this that these those i you we my your me please just so do not dont don't no nope actually wait again as at by from use using".split(" "));function Go(t){return new Set(t.toLowerCase().replace(/[^a-z0-9+#.\s-]/g," ").split(/\s+/).filter(e=>e.length>1&&!Wr.has(e)))}function Ko(t,e){let n=Go(t),o=Go(e);if(!n.size||!o.size)return 0;let s=0;for(let r of n)o.has(r)&&s++;return s<1?0:s/(n.size+o.size-s)}function qr(t){let e=t.trim();return!e||e.length>400||e.startsWith("/")||e.endsWith("?")?!1:Ur.some(n=>n.test(e))}function Hr(t){let e=t.replace(/\s+/g," ").trim();return e=e.replace(/^(no|nope|wrong|stop|wait|actually|ok|okay|hey|please)\b[\s,.!:-]*/i,"").replace(/^(no|actually|please)\b[\s,.!:-]*/i,""),e=e.replace(/\b(again|once more)\b[\s,.!]*/gi,"").replace(/\b(as )?i (already )?(told you|said|mentioned)( so| already| before)?( to| not to)?\b[\s,.:-]*/gi,""),e=(e.match(/[^.!]+[.!]?/g)??[e]).slice(0,2).join(" ").replace(/[!,;:\s]+$/g,"").replace(/\s+([,.])/g,"$1").trim(),e.length>160&&(e=e.slice(0,157).trimEnd()+"\u2026"),e.charAt(0).toUpperCase()+e.slice(1)}var zr=.4,Wt=class{seen=[];known;constructor(e=[]){this.known=[...e]}observe(e){if(!qr(e))return null;let n=Hr(e);if(!n)return null;let o=this.seen.some(r=>Ko(r,e)>=zr);this.seen.push(e);let s=Br.test(e);return!o&&!s||this.known.some(r=>Ee(r)===Ee(n)||Ko(r,n)>=.6)?null:(this.known.push(n),{rule:n,reason:o?"repeated":"explicit"})}};async function Yo(t){let{cheap:e,strong:n,verify:o,maxToolErrors:s=3,...r}=t,a=await Qe({...r,client:e.client,model:e.model}),c;if(a.stopReason!=="done")c=a.stopReason==="max_steps"?"the cheap model hit the step limit":"the cheap model used the run's token budget";else if(a.toolErrors>=s)c=`${a.toolErrors} tool calls failed`;else if(o){let _=await o();_.ok||(c=`verification failed${_.detail?`: ${_.detail.slice(0,200)}`:""}`)}if(!c)return{...a,escalated:!1,finalModel:e.model,cheapUsage:a.usage};r.onEvent?.({type:"escalate",from:e.model,to:n.model,reason:c}),r.messages.push({role:"user",content:`The previous attempt did not succeed (${c}). Review what was done, fix any problems, and finish the task.`});let d=a.usage.promptTokens+a.usage.completionTokens,u=await Qe({...r,client:n.client,model:n.model,maxRunTokens:(r.maxRunTokens??L.maxRunTokens)<=0?0:Math.max(5e4,(r.maxRunTokens??L.maxRunTokens)-d)}),g={promptTokens:a.usage.promptTokens+u.usage.promptTokens,completionTokens:a.usage.completionTokens+u.usage.completionTokens,cacheReadTokens:(a.usage.cacheReadTokens??0)+(u.usage.cacheReadTokens??0)};return{...u,usage:g,steps:a.steps+u.steps,toolErrors:a.toolErrors+u.toolErrors,changedFiles:[...new Set([...a.changedFiles,...u.changedFiles])],cachedReads:a.cachedReads+u.cachedReads,escalated:!0,reason:c,finalModel:n.model,cheapUsage:a.usage,strongUsage:u.usage}}import{spawn as Jr}from"child_process";import ot from"fs/promises";import{createHash as Gr}from"crypto";import Be from"path";var Kr="2025-03-26",Yr=6e4,Vo=2e4,Xo=1e5,Ht=t=>Be.join(t,h.dirName,"mcp.json");async function qt(t){try{let e=JSON.parse(await ot.readFile(t,"utf8"));return{servers:e&&typeof e.servers=="object"&&e.servers?e.servers:{}}}catch{return{servers:{}}}}var jn=t=>Be.join(t,h.dirName,"trusted-mcp.json"),Qo=t=>Gr("sha256").update(JSON.stringify(t.servers)).digest("hex");async function es(t){try{return JSON.parse(await ot.readFile(jn(t),"utf8"))}catch{return{}}}async function zt(t,e){let n=await es(e);n[Be.resolve(t)]=Qo(await qt(Ht(t))),await ot.mkdir(Be.dirname(jn(e)),{recursive:!0}),await ot.writeFile(jn(e),JSON.stringify(n,null,2),{mode:384})}async function _t(t,e){let n=await qt(Be.join(e,h.dirName,"mcp.json")),o=await qt(Ht(t)),s=Object.keys(o.servers).length===0||(await es(e))[Be.resolve(t)]===Qo(o);return{servers:{...n.servers,...s?o.servers:{}},untrusted:s?[]:Object.keys(o.servers)}}async function On(t,e){let n=Ht(t);return await ot.mkdir(Be.dirname(n),{recursive:!0}),await ot.writeFile(n,JSON.stringify(e,null,2)+`
84
- `),n}var Jt=t=>qt(Ht(t)),Nn=class{child;nextId=1;pending=new Map;buf="";stderr="";dead=null;constructor(e,n){let o={};for(let s of["PATH","HOME","USER","LANG","TMPDIR","SHELL"])process.env[s]&&(o[s]=process.env[s]);this.child=Jr(e.command,e.args??[],{cwd:n,env:{...o,...e.env},stdio:["pipe","pipe","pipe"]}),this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",s=>this.onData(s)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",s=>{this.stderr=(this.stderr+s).slice(-2e3)}),this.child.on("error",s=>this.fail(new Error(`cannot start "${e.command}": ${s.message}`))),this.child.on("exit",s=>this.fail(new Error(`server exited (code ${s})${this.stderr?`: ${this.stderr.trim().split(`
85
- `).pop()}`:""}`)))}fail(e){this.dead??=e;for(let n of this.pending.values())n.reject(this.dead);this.pending.clear()}onData(e){this.buf+=e;let n;for(;(n=this.buf.indexOf(`
86
- `))>=0;){let o=this.buf.slice(0,n).trim();if(this.buf=this.buf.slice(n+1),!o)continue;let s;try{s=JSON.parse(o)}catch{continue}if(s.id!==void 0&&this.pending.has(s.id)){let r=this.pending.get(s.id);this.pending.delete(s.id),s.error?r.reject(new Error(s.error.message??"MCP error")):r.resolve(s.result)}}}request(e,n,o){if(this.dead)return Promise.reject(this.dead);let s=this.nextId++;return new Promise((r,a)=>{let c=setTimeout(()=>{this.pending.delete(s),a(new Error(`${e} timed out after ${o/1e3}s`))},o);this.pending.set(s,{resolve:d=>{clearTimeout(c),r(d)},reject:d=>{clearTimeout(c),a(d)}}),this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,method:e,params:n})+`
87
- `)})}async notify(e,n){this.dead||this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",method:e,params:n})+`
88
- `)}close(){try{this.child.kill()}catch{}}},In=class{constructor(e){this.cfg=e}cfg;nextId=1;session=null;async post(e,n){return fetch(this.cfg.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream",...this.session?{"mcp-session-id":this.session}:{},...this.cfg.headers},body:JSON.stringify(e),signal:AbortSignal.timeout(n)})}async request(e,n,o){let s=this.nextId++,r=await this.post({jsonrpc:"2.0",id:s,method:e,params:n},o);if(!r.ok)throw new Error(`HTTP ${r.status} from MCP server`);this.session=r.headers.get("mcp-session-id")??this.session;let a=await r.text(),c;if((r.headers.get("content-type")??"").includes("text/event-stream")){for(let d of a.split(`
89
- `))if(d.startsWith("data:"))try{let u=JSON.parse(d.slice(5));if(u.id===s){c=u;break}}catch{}}else c=JSON.parse(a);if(!c)throw new Error("no response from MCP server");if(c.error)throw new Error(c.error.message??"MCP error");return c.result}async notify(e,n){await this.post({jsonrpc:"2.0",method:e,params:n},1e4).catch(()=>{})}close(){}},Zo=t=>t.replace(/[^a-zA-Z0-9_-]+/g,"_"),Vr=(t,e)=>`mcp__${Zo(t)}__${Zo(e)}`.slice(0,64),st=class t{clients=new Map;byName=new Map;errors=new Map;static async fromConfig(e,n){let o=new t;return await Promise.all(Object.entries(e.servers).map(([s,r])=>o.connect(s,r,n))),o}async connect(e,n,o){let s;try{if(n.url)s=new In(n);else if(n.command)s=new Nn(n,o);else throw new Error('needs "command" or "url"');await s.request("initialize",{protocolVersion:Kr,capabilities:{},clientInfo:{name:h.bin,version:"0.1.0"}},Vo),await s.notify("notifications/initialized");let r;do{let a=await s.request("tools/list",r?{cursor:r}:{},Vo);for(let c of a.tools??[]){let d=Vr(e,c.name);this.byName.set(d,{server:e,name:c.name,fullName:d,description:c.description??"",inputSchema:c.inputSchema??{type:"object",properties:{}}})}r=a.nextCursor}while(r);this.clients.set(e,s)}catch(r){s?.close(),this.errors.set(e,r?.message??String(r))}}get tools(){return[...this.byName.values()]}get serverCount(){return this.clients.size}has(e){return this.byName.has(e)}info(e){return this.byName.get(e)}specs(){return this.tools.map(e=>({name:e.fullName,description:`[MCP ${e.server}] ${e.description}`.slice(0,1e3),parameters:e.inputSchema}))}async call(e,n){let o=this.byName.get(e);if(!o)throw new Error(`unknown MCP tool ${e}`);let s=await this.clients.get(o.server).request("tools/call",{name:o.name,arguments:n??{}},Yr),r=(s?.content??[]).map(c=>c.type==="text"?c.text:c.type==="resource"?c.resource?.text??`[resource ${c.resource?.uri}]`:`[${c.type} content omitted]`).join(`
90
- `),a=r.length>Xo?r.slice(0,Xo)+`
91
- \u2026[truncated]`:r;if(s?.isError)throw new Error(a||"tool reported an error");return a||"(no output)"}close(){for(let e of this.clients.values())e.close();this.clients.clear()}};import{execFile as Xr}from"child_process";import Gt from"fs/promises";import ts from"os";import ge from"path";var Zr={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function Qr(t){return t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=6&&/^GIF8[79]a$/.test(t.subarray(0,6).toString("latin1"))?"image/gif":t.length>=12&&t.subarray(0,4).toString("latin1")==="RIFF"&&t.subarray(8,12).toString("latin1")==="WEBP"?"image/webp":null}function ei(t){if(process.platform!=="darwin")return Promise.resolve(null);let e=ge.join(ts.tmpdir(),`forge-shrink-${process.pid}-${Date.now()}.jpg`);return new Promise(n=>{Xr("sips",["-Z","1600","-s","format","jpeg","-s","formatOptions","80",t,"--out",e],async o=>{if(o)return n(null);try{n(await Gt.readFile(e))}catch{n(null)}finally{Gt.rm(e,{force:!0}).catch(()=>{})}})})}async function ti(t,e=ei){let n=ge.extname(t).toLowerCase();if(!(n in Zr))throw new Error(`${ge.basename(t)}: not a supported image type (png, jpg, gif, webp)`);let o=await Gt.readFile(t),s=Qr(o);if(!s)throw new Error(`${ge.basename(t)}: file content is not a valid ${n.slice(1)} image`);if(o.length>me.maxBytes/2&&s!=="image/gif"){let r=await e(t);r&&r.length<o.length&&(o=r,s="image/jpeg")}if(o.length>me.maxBytes)throw new Error(`${ge.basename(t)}: image is ${(o.length/1048576).toFixed(1)} MB (max ${me.maxBytes/1048576} MB)`);return{mediaType:s,data:o.toString("base64"),name:ge.basename(t)}}var Ln="(?:png|jpe?g|gif|webp)",ni=new RegExp(`(^|\\s)(@?)(?:"([^"\\n]+\\.${Ln})"|'([^'\\n]+\\.${Ln})'|((?:\\\\ |[^\\s"'])+\\.${Ln}))(?=\\s|$|[.,;:!?)]$)`,"gi");async function ns(t,e,n=ts.homedir()){let o=[],s=[],r=new Map,a=[...e.matchAll(ni)],c="",d=0;for(let u of a){let g=(u[3]??u[4]??u[5]??"").replace(/\\ /g," "),_=g.startsWith("~/")?ge.join(n,g.slice(2)):ge.resolve(t,g),R=(u.index??0)+u[1].length,v=(u.index??0)+u[0].length,W=r.get(_);if(W===void 0){try{await Gt.access(_)}catch{continue}if(o.length>=me.maxPerMessage){s.push(`only ${me.maxPerMessage} images per message; skipped ${ge.basename(_)}`);continue}try{o.push(await ti(_)),W=o.length,r.set(_,W)}catch(Z){s.push(Z instanceof Error?Z.message:String(Z));continue}}c+=e.slice(d,R)+`[Image #${W}: ${ge.basename(_)}]`,d=v}return{text:c+e.slice(d),images:o,errors:s}}import Kt from"fs/promises";import oi from"os";import os from"path";var ss=()=>os.join(oi.homedir(),h.dirName),Fn=()=>os.join(ss(),"config.json");async function oe(){let t={};try{t=JSON.parse(await Kt.readFile(Fn(),"utf8"))}catch{}return{apiUrl:h.defaultApiUrl,token:process.env.SCOPE_API_KEY??process.env.FORGE_API_KEY??t.token,defaultModel:t.defaultModel}}async function We(t){let e={};try{e=JSON.parse(await Kt.readFile(Fn(),"utf8"))}catch{}let n={...e,...t};delete n.apiUrl;for(let o of Object.keys(n))n[o]===void 0&&delete n[o];await Kt.mkdir(ss(),{recursive:!0}),await Kt.writeFile(Fn(),JSON.stringify(n,null,2),{mode:384})}async function X(t,e={}){let n=await oe(),o={"content-type":"application/json",...e.headers};if(e.auth!==!1){if(!n.token)throw new Error(l("cli.api.not_logged_in_run_forge","Not logged in \u2014 run `scope login` (or set SCOPE_API_KEY)."));o.authorization=`Bearer ${n.token}`}let s=`${n.apiUrl.replace(/\/$/,"")}${t}`,r;try{r=await fetch(s,{...e,headers:o,signal:AbortSignal.timeout(3e4)})}catch(c){throw new Re("server",c?.cause?.code??c?.name??"network error")}let a=await r.json().catch(()=>({}));if(!r.ok){let c=a?.error?.message??`request failed (${r.status})`,d=typeof c=="string"?c.replace(/https?:\/\/[^\s"'<>]+/gi,"server"):"request failed";throw new ne(r.status,d,a)}return a}var rs=t=>t.replace(/https?:\/\/[^\s"'<>]+/gi,"server").trim();function Ce(t,e){if(t instanceof Re){let o=t.reason||"network error",s="Unable to connect to the server.";return/timeout/i.test(o)?s="Connection timed out.":/ENOTFOUND|EAI_AGAIN/i.test(o)?s="DNS resolution failed. Please check your internet connection.":/ECONNREFUSED/i.test(o)&&(s="Server connection refused or unreachable."),`Network error: ${s} (${o})
92
- \u2022 Please check your internet connection and try again.`}if(t instanceof ne){let o=t.body?.error??{},s=rs(t.message);switch(t.status){case 401:return s.includes("login")?s:`Not authorized: ${s}.
93
- Run \`/login\` or \`${h.bin} login\` to authenticate.`;case 402:return`${s}
94
- See \`${h.bin} usage\`. Upgrade in the dashboard (/app/billing) or wait for the reset.`;case 403:return`${s}
95
- Run \`${h.bin} models\` to see what your plan includes.`;case 404:return`${s}
96
- Run \`${h.bin} models\` to list valid model ids.`;case 429:{let r=s;return r.includes("daily limit of 60 free-model requests")&&(r="You reached the daily limit of 60 free-model requests for this account. Tip: switch to mock-model with `/model mock-model` or try again after UTC 00:00."),`Rate limited${o.retryAfterSec?` \u2014 try again in ${o.retryAfterSec}s`:""}. ${r}`}case 500:case 502:case 503:case 504:return`${s}
97
- It was retried once. Try again shortly.`;default:return`${s} (HTTP ${t.status})`}}let n=rs(t instanceof Error?t.message:String(t));return n.includes("daily limit of 60 free-model requests")||n.includes("free_daily_limit")?`Daily limit of 60 free-model requests reached.
98
- \u2022 Try again after 00:00 UTC.`:n.includes("Insufficient Balance")?"The service is temporarily unavailable. Please try again shortly.":n}function ri(t){if(process.env.FORGE_NO_BROWSER)return;let e=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{si(e,[t],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}async function Yt(){let t=await X("/v1/auth/device/code",{method:"POST",auth:!1});console.log(l("cli.commands.open_0_and_confirm_code",`
99
- Open {0}
100
- and confirm code: {1}
101
- `,t.verificationUrl,t.userCode)),ri(t.verificationUrl);let e=Date.now()+t.expiresIn*1e3;for(;Date.now()<e;){await new Promise(o=>setTimeout(o,t.interval*1e3));let n=await X("/v1/auth/device/token",{method:"POST",auth:!1,body:JSON.stringify({deviceCode:t.deviceCode})}).catch(o=>{throw o});if(n.status==="approved"){await We({token:n.apiKey});let o=await X("/v1/me");return console.log(l("cli.commands.logged_in_as_0_1","Logged in as {0} ({1} plan).",o.email,o.plan)),o}}throw new Error(l("cli.commands.login_timed_out","login timed out"))}async function Vt(){await We({token:void 0}),console.log(l("cli.commands.logged_out","Logged out."))}async function Xt(t){let e=await oe();if(t){await We({defaultModel:t}),console.log(l("cli.commands.default_model_set_to_0","Default model set to: {0}",t));return}let n=await X("/v1/models");console.log(l("cli.commands.models_on_your_0_plan","Models on your {0} plan:",n.plan));let o=e.defaultModel||n.default;for(let s of n.data){let r=s.id===o,c=s.id===n.default?" [default]":"";console.log(l("cli.commands.0_1_2_x_3","{0} {1} x{2} credits/token {3}",r?"*":" ",(s.id+c).padEnd(32),s.multiplier,s.vision?"[images]":""))}n.default&&console.log(`
102
- Server default: ${n.default}`),n.data.some(s=>s.vision)&&console.log(l("cli.commands.images_can_read_images_attach",`
103
- [images] = can read images (attach with @file.png, drag a file in, or Ctrl+V)`)),n.data.length||console.log(l("cli.commands.no_models_available_the_server","No models are available for your account right now."))}async function Zt(){let t=await X("/v1/usage"),e=o=>o.toLocaleString();console.log(l("cli.commands.plan_0_credits_1_of",`Plan: {0}
104
- Credits: {1} of {2} used this month
105
- Remaining: {3}
106
- Requests: {4} Tokens: {5} in / {6} out`,t.plan,e(t.usedCredits),t.monthlyOff?"no cap":e(t.limitCredits),t.monthlyOff?"unlimited":e(t.remainingCredits),t.requests,e(t.promptTokens),e(t.completionTokens)));let n=o=>o?`${e(o.usedCredits)} / ${o.limitCredits?e(o.limitCredits):"no cap"}`:"";t.windows&&console.log(`5-hour: ${n(t.windows.fiveHour)}
107
- Weekly: ${n(t.windows.weekly)}`)}async function Qt(){let t=await An(process.cwd());for(let e of[tt(process.cwd()),ht(process.cwd())])console.log(`${t.includes(e)?"created":"exists "} ${wt.relative(process.cwd(),e)}`);console.log(l("cli.commands.add_a_rule_0_skills",`
108
- Add a rule: {0} skills add "Use pnpm, not npm"`,h.bin))}async function as(){let t=process.cwd(),[e,n]=[await Ue(t),await Me(t)];e.length?(console.log(l("cli.commands.skills_0_applied_to_every","Skills ({0}) \u2014 applied to every run:",wt.relative(t,tt(t)))),e.forEach((o,s)=>console.log(` ${s+1}. ${o}`))):console.log(l("cli.commands.no_skills_yet_add_one",'No skills yet. Add one: {0} skills add "Prefer pnpm"',h.bin)),console.log(l("cli.commands.memory_notes_0_1",`
109
- Memory notes: {0} ({1})`,n.length,wt.relative(t,ht(t))))}async function ls(t){let e=await nt(process.cwd(),t.join(" "));console.log(e.added?`Added skill: ${e.skill}
110
- It will be used on the next run.`:`Already a skill: ${e.skill}`)}var ii=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);async function cs(t,e){let n=process.cwd(),[o,s]=[await Ue(n),await Me(n)];if(!o.length&&!s.length)throw new Error(l("cli.commands.nothing_to_push_0_skills",'nothing to push: {0}/skills.md and memory.md have no bullets. Run `{1} skills add "..."` first.',h.dirName,h.bin));let r=await X("/v1/taste",{method:"POST",body:JSON.stringify({name:ii(t??wt.basename(n)),description:e.description??"",skills:o,memory:s,isPublic:!e.private})});console.log(l("cli.commands.0_1_2_skill_s","{0} {1} ({2} skill(s), {3} memory note(s), {4}).",r.created?"Published":"Updated",r.slug,r.rules,r.memoryNotes,r.isPublic?"public":"private")),console.log(l("cli.commands.teammates_can_run_0_taste","Teammates can run: {0} taste pull {1}",h.bin,r.slug))}async function ds(t){let e=process.cwd();if(!/^[\w.-]+\/[\w.-]+$/.test(t))throw new Error(l("cli.commands.expected_namespace_name_e_g","expected <namespace>/<name>, e.g. {0} taste pull acme/frontend",h.bin));let n=await X(`/v1/taste/${t}`);await An(e);let o=0,s=0;for(let a of n.skills)(await nt(e,a)).added&&(o++,console.log(l("cli.commands.skill_0"," + skill: {0}",a)));let r=new Set((await Me(e)).map(Ee));for(let a of n.memory)r.has(Ee(a))||(await ft(e,a),s++,console.log(l("cli.commands.memory_0"," + memory: {0}",a)));console.log(l("cli.commands.pulled_0_1_new_skill","Pulled {0}: {1} new skill(s), {2} new memory note(s) ({3} skill(s) already present).",n.slug,o,s,n.rules-o))}async function us(t){let e=await X(`/v1/taste${t?`?q=${encodeURIComponent(t)}`:""}`,{auth:!1});if(!e.data.length)return console.log(l("cli.commands.no_taste_packages_found","No taste packages found."));for(let n of e.data)console.log(l("cli.commands.0_1_rules_2_pulls","{0} {1} rules {2} pulls {3}",n.slug.padEnd(36),String(n.rules).padStart(3),String(n.downloads).padStart(5),n.description))}async function ms(){let t=process.cwd(),e=await _t(t,Pe.homedir()),n=Object.keys(e.servers);if(!n.length)return console.log(l("cli.commands.no_mcp_servers_configured_add","No MCP servers configured. Add one: {0} mcp add fs npx -y @modelcontextprotocol/server-filesystem .",h.bin));e.untrusted.length&&console.log(l("cli.commands.not_started_untrusted_project_servers",`Not started (untrusted project servers: {0}). Review {1}/mcp.json, then run: {2} mcp trust
111
- `,e.untrusted.join(", "),h.dirName,h.bin));let o=await st.fromConfig(e,t);try{for(let s of n){let r=o.errors.get(s),a=o.tools.filter(c=>c.server===s);console.log(r?`\u2717 ${s} ${r}`:`\u2713 ${s} ${a.length} tool(s)`);for(let c of a)console.log(` ${c.fullName} ${c.description.split(`
112
- `)[0].slice(0,80)}`)}}finally{o.close()}}async function ps(t,e){if(!/^[\w-]+$/.test(t))throw new Error(l("cli.commands.server_name_may_only_contain","server name may only contain letters, digits, _ and -"));if(!e.length)throw new Error(l("cli.commands.give_a_command_e_g","give a command (e.g. npx -y @modelcontextprotocol/server-filesystem .) or an https:// URL"));let n=await Jt(process.cwd());n.servers[t]=/^https?:\/\//.test(e[0])?{url:e[0]}:{command:e[0],args:e.slice(1)};let o=await On(process.cwd(),n);await zt(process.cwd(),Pe.homedir()),console.log(l("cli.commands.saved_0_to_1_check",'Saved "{0}" to {1}. Check it: {2} mcp list',t,wt.relative(process.cwd(),o),h.bin))}async function gs(t){let e=await Jt(process.cwd());if(!(t in e.servers))throw new Error(l("cli.commands.no_mcp_server_0_in",'no MCP server "{0}" in {1}/mcp.json',t,h.dirName));delete e.servers[t],await On(process.cwd(),e),await zt(process.cwd(),Pe.homedir()),console.log(l("cli.commands.removed_0",'Removed "{0}".',t))}async function fs(){let t=await Jt(process.cwd()),e=Object.keys(t.servers);if(!e.length)return console.log(l("cli.commands.no_project_mcp_servers_in","No project MCP servers in {0}/mcp.json.",h.dirName));for(let[n,o]of Object.entries(t.servers))console.log(` ${n}: ${o.url??[o.command,...o.args??[]].join(" ")}`);await zt(process.cwd(),Pe.homedir()),console.log(l("cli.commands.trusted_0_server_s_they","Trusted {0} server(s). They start on the next run until the file changes.",e.length))}var hs=(t,e=" ")=>{for(let n of["PreToolUse","PostToolUse"])for(let o of t[n])console.log(`${e}${n} [${o.matcher??"*"}]: ${o.command}`)};async function _s(){let t=await gt(process.cwd(),Pe.homedir());if(!Fe(t)&&!t.untrusted.length)return console.log(l("cli.commands.no_hooks_configured_add_them","No hooks configured. Add them to {0}/hooks.json (project) or ~/{1}/hooks.json (user).",h.dirName,h.dirName));if(Fe(t)&&(console.log(l("cli.commands.effective_hooks","Effective hooks:")),hs(t)),t.untrusted.length){console.log(l("cli.commands.not_run_untrusted_project_hooks",`
113
- Not run (untrusted project hooks in {0}/hooks.json); review, then run: {1} hooks trust`,h.dirName,h.bin));for(let e of t.untrusted)console.log(` [${e.matcher??"*"}]: ${e.command}`)}}async function ws(){let t=await Ft(process.cwd());if(!Fe(t))return console.log(l("cli.commands.no_project_hooks_in_0","No project hooks in {0}/hooks.json.",h.dirName));hs(t),await Io(process.cwd(),Pe.homedir()),console.log(l("cli.commands.trusted_0_hook_s_they","Trusted {0} hook(s). They run until the file changes.",Fe(t)))}async function en(){let t=await oe(),e=process.cwd(),n=u=>console.log(` \x1B[32m\u2713\x1B[0m ${u}`),o=(u,g)=>console.log(` \x1B[31m\u2717\x1B[0m ${u}${g?`
114
- \u2192 ${g}`:""}`);console.log(l("cli.commands.0_doctor",`
115
- {0} doctor
116
- `,h.name));let s=Number(process.versions.node.split(".")[0]);(s>=18?n:o)(`node ${process.versions.node}`,s>=18?void 0:"use Node 18 or newer");let r=await new Promise(u=>is("git",["--version"],(g,_)=>u(g?null:String(_).trim())));if(r?n(r):o("git not found","install git (the Changes/review features need it)"),(r?await new Promise(u=>is("git",["rev-parse","--is-inside-work-tree"],{cwd:e},g=>u(!g))):!1)?n("inside a git repository"):console.log(l("cli.commands.not_inside_a_git_repository"," - not inside a git repository (optional)")),t.token)try{let u=await X("/v1/me");n(`logged in as ${u.email??"user"}`)}catch(u){o(`connection error: ${Ce(u)}`,`run \`${h.bin} login\` again`)}else o("not logged in",`run \`${h.bin} login\` (or set FORGE_API_KEY)`);let c=await _t(e,Pe.homedir());console.log(l("cli.commands.0_mcp_server_s_configured"," - {0} MCP server(s) configured{1}",Object.keys(c.servers).length,c.untrusted.length?`, ${c.untrusted.length} untrusted (run \`${h.bin} mcp trust\`)`:""));let d=await gt(e,Pe.homedir());console.log(l("cli.commands.0_hook_s_active_1"," - {0} hook(s) active{1}",Fe(d),d.untrusted.length?`, ${d.untrusted.length} untrusted (run \`${h.bin} hooks trust\`)`:"")),console.log("")}import xt from"fs/promises";import Yn from"os";import{execFile as Si}from"child_process";import at from"readline/promises";import{StringDecoder as Ti}from"string_decoder";import je from"path";import ys from"crypto";import yt from"fs/promises";import rt from"os";import tn from"path";var ai=/^[A-Za-z0-9_-]{6,64}$/,li=t=>ys.createHash("sha256").update(tn.resolve(t)).digest("hex").slice(0,16),bs=(t,e=rt.homedir())=>tn.join(e,h.dirName,"sessions",li(t)),nn=(t,e,n=rt.homedir())=>{if(!ai.test(e))throw new Error(l("cli.sessions.invalid_session_id","invalid session id"));return tn.join(bs(t,n),`${e}.json`)},on=()=>ys.randomUUID().replace(/-/g,"").slice(0,12);function bt(t){let n=(t.find(o=>o.role==="user")?.content??"").replace(/<file[\s\S]*$/m,"").replace(/\s+/g," ").trim();return n.length>60?n.slice(0,59)+"\u2026":n||"Untitled session"}async function xs(t,e,n=rt.homedir()){let o=nn(t,e.id,n);await yt.mkdir(tn.dirname(o),{recursive:!0});let s=`${o}.${process.pid}.tmp`;return await yt.writeFile(s,JSON.stringify(e),{mode:384}),await yt.rename(s,o),o}async function ks(t,e,n=rt.homedir()){try{return JSON.parse(await yt.readFile(nn(t,e,n),"utf8"))}catch(o){if(o?.code==="ENOENT"||o instanceof SyntaxError)return null;throw o}}async function Dn(t,e=rt.homedir()){let n;try{n=await yt.readdir(bs(t,e))}catch{return[]}let o=[];for(let s of n){if(!s.endsWith(".json"))continue;let r=await ks(t,s.slice(0,-5),e);r&&o.push({id:r.id,title:r.title,model:r.model,createdAt:r.createdAt,updatedAt:r.updatedAt,turns:r.messages.filter(a=>a.role==="user").length})}return o.sort((s,r)=>r.updatedAt-s.updatedAt)}async function Un(t,e,n=rt.homedir()){let o=await Dn(t,n);if(!o.length)return null;let s=e===void 0||e===!0||e==="latest"?o[0]:o.find(r=>r.id===e)??(o.filter(r=>r.id.startsWith(String(e))).length===1?o.find(r=>r.id.startsWith(String(e))):void 0);return s?ks(t,s.id,n):null}var sn=t=>t.flatMap((e,n)=>e.role==="user"?[n]:[]),rn=(t,e=Date.now())=>{let n=Math.max(0,Math.round((e-t)/1e3));return n<60?`${n}s ago`:n<3600?`${Math.round(n/60)}m ago`:n<86400?`${Math.round(n/3600)}h ago`:`${Math.round(n/86400)}d ago`};import ci from"fs";import di from"os";import $s from"path";function ui(t){let e={};for(let n of t.split(/\r?\n/)){let o=n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);if(!o||o[1].startsWith("#"))continue;let s=o[2];/^(["']).*\1$/.test(s)?s=s.slice(1,-1):s=s.replace(/\s+#.*$/,""),s!==""&&(e[o[1]]=s)}return e}var mi=new Set(["FORGE_API_KEY","FORGE_API_URL"]),pi=new Set(["FORGE_API_URL"]);function vs(t=process.cwd()){let e=$s.join(di.homedir(),h.dirName,".env");for(let n of[$s.join(t,".env"),e]){let o;try{o=ci.readFileSync(n,"utf8")}catch{continue}for(let[s,r]of Object.entries(ui(o)))pi.has(s)&&n!==e||mi.has(s)&&process.env[s]===void 0&&(process.env[s]=r)}}import gi from"fs/promises";import Ss from"path";import{spawn as Cs}from"child_process";import{StringDecoder as fi}from"string_decoder";var i={bannerBg:"\x1B[48;2;34;24;20m",bannerText:"\x1B[38;2;255;179;71m",statusPillBg:"\x1B[48;2;52;34;24m",statusPillFg:"\x1B[38;2;255;214;170m",userMsgBg:"\x1B[48;2;44;32;26m",userPointer:"\x1B[38;2;255;122;61m",userFg:"\x1B[38;2;240;232;224m",accent:"\x1B[38;2;255;179;71m",assistantPrefix:"\x1B[38;2;255;122;61m",workedPrefix:"\x1B[38;2;120;200;140m",gray:"\x1B[38;2;150;146;142m",dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m",cyan:"\x1B[38;2;255;179;71m"},hi=`
83
+ `]];for(let[o,s]of n)try{await ot.access(o)}catch{await ot.mkdir(Ht.dirname(o),{recursive:!0}),await ot.writeFile(o,s),t.push(o)}return t}var Wr=[/^\s*(no|nope|wrong|stop|wait|actually)\b[\s,.!:-]/i,/\b(don'?t|do not|never|stop (using|adding|doing|writing))\b/i,/\binstead\b/i,/\b(use|using|prefer)\b[^.!]*\b(not|over)\b/i,/\b(should|must|need to) (use|be|not|have)\b/i,/\bprefer\b/i,/\brather than\b/i,/\bthat'?s (wrong|not (what|right|how))\b/i,/\bplease (use|don'?t|do not|always|never|keep|avoid)\b/i,/\b(always|avoid)\b/i],qr=/\b(again|i (told|said|already)|as i (said|mentioned)|every time|always|never|from now on|once more)\b/i,Hr=new Set("the a an and or but to of in on for with it is are be this that these those i you we my your me please just so do not dont don't no nope actually wait again as at by from use using".split(" "));function Yo(e){return new Set(e.toLowerCase().replace(/[^a-z0-9+#.\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!Hr.has(t)))}function Vo(e,t){let n=Yo(e),o=Yo(t);if(!n.size||!o.size)return 0;let s=0;for(let r of n)o.has(r)&&s++;return s<1?0:s/(n.size+o.size-s)}function zr(e){let t=e.trim();return!t||t.length>400||t.startsWith("/")||t.endsWith("?")?!1:Wr.some(n=>n.test(t))}function Jr(e){let t=e.replace(/\s+/g," ").trim();return t=t.replace(/^(no|nope|wrong|stop|wait|actually|ok|okay|hey|please)\b[\s,.!:-]*/i,"").replace(/^(no|actually|please)\b[\s,.!:-]*/i,""),t=t.replace(/\b(again|once more)\b[\s,.!]*/gi,"").replace(/\b(as )?i (already )?(told you|said|mentioned)( so| already| before)?( to| not to)?\b[\s,.:-]*/gi,""),t=(t.match(/[^.!]+[.!]?/g)??[t]).slice(0,2).join(" ").replace(/[!,;:\s]+$/g,"").replace(/\s+([,.])/g,"$1").trim(),t.length>160&&(t=t.slice(0,157).trimEnd()+"\u2026"),t.charAt(0).toUpperCase()+t.slice(1)}var Gr=.4,zt=class{seen=[];known;constructor(t=[]){this.known=[...t]}observe(t){if(!zr(t))return null;let n=Jr(t);if(!n)return null;let o=this.seen.some(r=>Vo(r,t)>=Gr);this.seen.push(t);let s=qr.test(t);return!o&&!s||this.known.some(r=>Ce(r)===Ce(n)||Vo(r,n)>=.6)?null:(this.known.push(n),{rule:n,reason:o?"repeated":"explicit"})}};async function Xo(e){let{cheap:t,strong:n,verify:o,maxToolErrors:s=3,...r}=e,a=await nt({...r,client:t.client,model:t.model}),c;if(a.stopReason!=="done")c=a.stopReason==="max_steps"?"the cheap model hit the step limit":"the cheap model used the run's token budget";else if(a.toolErrors>=s)c=`${a.toolErrors} tool calls failed`;else if(o){let h=await o();h.ok||(c=`verification failed${h.detail?`: ${h.detail.slice(0,200)}`:""}`)}if(!c)return{...a,escalated:!1,finalModel:t.model,cheapUsage:a.usage};r.onEvent?.({type:"escalate",from:t.model,to:n.model,reason:c}),r.messages.push({role:"user",content:`The previous attempt did not succeed (${c}). Review what was done, fix any problems, and finish the task.`});let d=a.usage.promptTokens+a.usage.completionTokens,u=await nt({...r,client:n.client,model:n.model,maxRunTokens:(r.maxRunTokens??L.maxRunTokens)<=0?0:Math.max(5e4,(r.maxRunTokens??L.maxRunTokens)-d)}),g={promptTokens:a.usage.promptTokens+u.usage.promptTokens,completionTokens:a.usage.completionTokens+u.usage.completionTokens,cacheReadTokens:(a.usage.cacheReadTokens??0)+(u.usage.cacheReadTokens??0)};return{...u,usage:g,steps:a.steps+u.steps,toolErrors:a.toolErrors+u.toolErrors,changedFiles:[...new Set([...a.changedFiles,...u.changedFiles])],cachedReads:a.cachedReads+u.cachedReads,escalated:!0,reason:c,finalModel:n.model,cheapUsage:a.usage,strongUsage:u.usage}}import{spawn as Kr}from"child_process";import it from"fs/promises";import{createHash as Yr}from"crypto";import He from"path";var Vr="2025-03-26",Xr=6e4,Zo=2e4,Qo=1e5,Gt=e=>He.join(e,_.dirName,"mcp.json");async function Jt(e){try{let t=JSON.parse(await it.readFile(e,"utf8"));return{servers:t&&typeof t.servers=="object"&&t.servers?t.servers:{}}}catch{return{servers:{}}}}var In=e=>He.join(e,_.dirName,"trusted-mcp.json"),ts=e=>Yr("sha256").update(JSON.stringify(e.servers)).digest("hex");async function ns(e){try{return JSON.parse(await it.readFile(In(e),"utf8"))}catch{return{}}}async function Kt(e,t){let n=await ns(t);n[He.resolve(e)]=ts(await Jt(Gt(e))),await it.mkdir(He.dirname(In(t)),{recursive:!0}),await it.writeFile(In(t),JSON.stringify(n,null,2),{mode:384})}async function bt(e,t){let n=await Jt(He.join(t,_.dirName,"mcp.json")),o=await Jt(Gt(e)),s=Object.keys(o.servers).length===0||(await ns(t))[He.resolve(e)]===ts(o);return{servers:{...n.servers,...s?o.servers:{}},untrusted:s?[]:Object.keys(o.servers)}}async function Fn(e,t){let n=Gt(e);return await it.mkdir(He.dirname(n),{recursive:!0}),await it.writeFile(n,JSON.stringify(t,null,2)+`
84
+ `),n}var Yt=e=>Jt(Gt(e)),On=class{child;nextId=1;pending=new Map;buf="";stderr="";dead=null;constructor(t,n){let o={};for(let s of["PATH","HOME","USER","LANG","TMPDIR","SHELL"])process.env[s]&&(o[s]=process.env[s]);this.child=Kr(t.command,t.args??[],{cwd:n,env:{...o,...t.env},stdio:["pipe","pipe","pipe"]}),this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",s=>this.onData(s)),this.child.stderr.setEncoding("utf8"),this.child.stderr.on("data",s=>{this.stderr=(this.stderr+s).slice(-2e3)}),this.child.on("error",s=>this.fail(new Error(`cannot start "${t.command}": ${s.message}`))),this.child.on("exit",s=>this.fail(new Error(`server exited (code ${s})${this.stderr?`: ${this.stderr.trim().split(`
85
+ `).pop()}`:""}`)))}fail(t){this.dead??=t;for(let n of this.pending.values())n.reject(this.dead);this.pending.clear()}onData(t){this.buf+=t;let n;for(;(n=this.buf.indexOf(`
86
+ `))>=0;){let o=this.buf.slice(0,n).trim();if(this.buf=this.buf.slice(n+1),!o)continue;let s;try{s=JSON.parse(o)}catch{continue}if(s.id!==void 0&&this.pending.has(s.id)){let r=this.pending.get(s.id);this.pending.delete(s.id),s.error?r.reject(new Error(s.error.message??"MCP error")):r.resolve(s.result)}}}request(t,n,o){if(this.dead)return Promise.reject(this.dead);let s=this.nextId++;return new Promise((r,a)=>{let c=setTimeout(()=>{this.pending.delete(s),a(new Error(`${t} timed out after ${o/1e3}s`))},o);this.pending.set(s,{resolve:d=>{clearTimeout(c),r(d)},reject:d=>{clearTimeout(c),a(d)}}),this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,method:t,params:n})+`
87
+ `)})}async notify(t,n){this.dead||this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",method:t,params:n})+`
88
+ `)}close(){try{this.child.kill()}catch{}}},Ln=class{constructor(t){this.cfg=t}cfg;nextId=1;session=null;async post(t,n){return fetch(this.cfg.url,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream",...this.session?{"mcp-session-id":this.session}:{},...this.cfg.headers},body:JSON.stringify(t),signal:AbortSignal.timeout(n)})}async request(t,n,o){let s=this.nextId++,r=await this.post({jsonrpc:"2.0",id:s,method:t,params:n},o);if(!r.ok)throw new Error(`HTTP ${r.status} from MCP server`);this.session=r.headers.get("mcp-session-id")??this.session;let a=await r.text(),c;if((r.headers.get("content-type")??"").includes("text/event-stream")){for(let d of a.split(`
89
+ `))if(d.startsWith("data:"))try{let u=JSON.parse(d.slice(5));if(u.id===s){c=u;break}}catch{}}else c=JSON.parse(a);if(!c)throw new Error("no response from MCP server");if(c.error)throw new Error(c.error.message??"MCP error");return c.result}async notify(t,n){await this.post({jsonrpc:"2.0",method:t,params:n},1e4).catch(()=>{})}close(){}},es=e=>e.replace(/[^a-zA-Z0-9_-]+/g,"_"),Zr=(e,t)=>`mcp__${es(e)}__${es(t)}`.slice(0,64),at=class e{clients=new Map;byName=new Map;errors=new Map;static async fromConfig(t,n){let o=new e;return await Promise.all(Object.entries(t.servers).map(([s,r])=>o.connect(s,r,n))),o}async connect(t,n,o){let s;try{if(n.url)s=new Ln(n);else if(n.command)s=new On(n,o);else throw new Error('needs "command" or "url"');await s.request("initialize",{protocolVersion:Vr,capabilities:{},clientInfo:{name:_.bin,version:"0.1.0"}},Zo),await s.notify("notifications/initialized");let r;do{let a=await s.request("tools/list",r?{cursor:r}:{},Zo);for(let c of a.tools??[]){let d=Zr(t,c.name);this.byName.set(d,{server:t,name:c.name,fullName:d,description:c.description??"",inputSchema:c.inputSchema??{type:"object",properties:{}}})}r=a.nextCursor}while(r);this.clients.set(t,s)}catch(r){s?.close(),this.errors.set(t,r?.message??String(r))}}get tools(){return[...this.byName.values()]}get serverCount(){return this.clients.size}has(t){return this.byName.has(t)}info(t){return this.byName.get(t)}specs(){return this.tools.map(t=>({name:t.fullName,description:`[MCP ${t.server}] ${t.description}`.slice(0,1e3),parameters:t.inputSchema}))}async call(t,n){let o=this.byName.get(t);if(!o)throw new Error(`unknown MCP tool ${t}`);let s=await this.clients.get(o.server).request("tools/call",{name:o.name,arguments:n??{}},Xr),r=(s?.content??[]).map(c=>c.type==="text"?c.text:c.type==="resource"?c.resource?.text??`[resource ${c.resource?.uri}]`:`[${c.type} content omitted]`).join(`
90
+ `),a=r.length>Qo?r.slice(0,Qo)+`
91
+ \u2026[truncated]`:r;if(s?.isError)throw new Error(a||"tool reported an error");return a||"(no output)"}close(){for(let t of this.clients.values())t.close();this.clients.clear()}};import{execFile as Qr}from"child_process";import Vt from"fs/promises";import os from"os";import ge from"path";var ei={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function ti(e){return e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=6&&/^GIF8[79]a$/.test(e.subarray(0,6).toString("latin1"))?"image/gif":e.length>=12&&e.subarray(0,4).toString("latin1")==="RIFF"&&e.subarray(8,12).toString("latin1")==="WEBP"?"image/webp":null}function ni(e){if(process.platform!=="darwin")return Promise.resolve(null);let t=ge.join(os.tmpdir(),`forge-shrink-${process.pid}-${Date.now()}.jpg`);return new Promise(n=>{Qr("sips",["-Z","1600","-s","format","jpeg","-s","formatOptions","80",e,"--out",t],async o=>{if(o)return n(null);try{n(await Vt.readFile(t))}catch{n(null)}finally{Vt.rm(t,{force:!0}).catch(()=>{})}})})}async function oi(e,t=ni){let n=ge.extname(e).toLowerCase();if(!(n in ei))throw new Error(`${ge.basename(e)}: not a supported image type (png, jpg, gif, webp)`);let o=await Vt.readFile(e),s=ti(o);if(!s)throw new Error(`${ge.basename(e)}: file content is not a valid ${n.slice(1)} image`);if(o.length>me.maxBytes/2&&s!=="image/gif"){let r=await t(e);r&&r.length<o.length&&(o=r,s="image/jpeg")}if(o.length>me.maxBytes)throw new Error(`${ge.basename(e)}: image is ${(o.length/1048576).toFixed(1)} MB (max ${me.maxBytes/1048576} MB)`);return{mediaType:s,data:o.toString("base64"),name:ge.basename(e)}}var Dn="(?:png|jpe?g|gif|webp)",si=new RegExp(`(^|\\s)(@?)(?:"([^"\\n]+\\.${Dn})"|'([^'\\n]+\\.${Dn})'|((?:\\\\ |[^\\s"'])+\\.${Dn}))(?=\\s|$|[.,;:!?)]$)`,"gi");async function ss(e,t,n=os.homedir()){let o=[],s=[],r=new Map,a=[...t.matchAll(si)],c="",d=0;for(let u of a){let g=(u[3]??u[4]??u[5]??"").replace(/\\ /g," "),h=g.startsWith("~/")?ge.join(n,g.slice(2)):ge.resolve(e,g),R=(u.index??0)+u[1].length,v=(u.index??0)+u[0].length,W=r.get(h);if(W===void 0){try{await Vt.access(h)}catch{continue}if(o.length>=me.maxPerMessage){s.push(`only ${me.maxPerMessage} images per message; skipped ${ge.basename(h)}`);continue}try{o.push(await oi(h)),W=o.length,r.set(h,W)}catch(Z){s.push(Z instanceof Error?Z.message:String(Z));continue}}c+=t.slice(d,R)+`[Image #${W}: ${ge.basename(h)}]`,d=v}return{text:c+t.slice(d),images:o,errors:s}}import Xt from"fs/promises";import ri from"os";import rs from"path";var is=()=>rs.join(ri.homedir(),_.dirName),Un=()=>rs.join(is(),"config.json");async function oe(){let e={};try{e=JSON.parse(await Xt.readFile(Un(),"utf8"))}catch{}return{apiUrl:_.defaultApiUrl,token:process.env.SCOPE_API_KEY??process.env.FORGE_API_KEY??e.token,defaultModel:e.defaultModel}}async function ze(e){let t={};try{t=JSON.parse(await Xt.readFile(Un(),"utf8"))}catch{}let n={...t,...e};delete n.apiUrl;for(let o of Object.keys(n))n[o]===void 0&&delete n[o];await Xt.mkdir(is(),{recursive:!0}),await Xt.writeFile(Un(),JSON.stringify(n,null,2),{mode:384})}async function X(e,t={}){let n=await oe(),o={"content-type":"application/json",...t.headers};if(t.auth!==!1){if(!n.token)throw new Error(l("cli.api.not_logged_in_run_forge","Not logged in \u2014 run `scope login` (or set SCOPE_API_KEY)."));o.authorization=`Bearer ${n.token}`}let s=`${n.apiUrl.replace(/\/$/,"")}${e}`,r;try{r=await fetch(s,{...t,headers:o,signal:AbortSignal.timeout(3e4)})}catch(c){throw new Me("server",c?.cause?.code??c?.name??"network error")}let a=await r.json().catch(()=>({}));if(!r.ok){let c=a?.error?.message??`request failed (${r.status})`,d=typeof c=="string"?c.replace(/https?:\/\/[^\s"'<>]+/gi,"server"):"request failed";throw new ne(r.status,d,a)}return a}import ai from"fs/promises";import as from"path";import{spawn as ms}from"child_process";import{StringDecoder as li}from"string_decoder";import{createRequire as ii}from"module";var xe=ii(import.meta.url)("../package.json").version;var i={bannerBg:"\x1B[48;2;34;24;20m",bannerText:"\x1B[38;2;255;179;71m",statusPillBg:"\x1B[48;2;52;34;24m",statusPillFg:"\x1B[38;2;255;214;170m",userMsgBg:"\x1B[48;2;44;32;26m",userPointer:"\x1B[38;2;255;122;61m",userFg:"\x1B[38;2;240;232;224m",accent:"\x1B[38;2;255;179;71m",assistantPrefix:"\x1B[38;2;255;122;61m",workedPrefix:"\x1B[38;2;120;200;140m",gray:"\x1B[38;2;150;146;142m",dim:"\x1B[2m",bold:"\x1B[1m",reset:"\x1B[0m",cyan:"\x1B[38;2;255;179;71m",tokenBlue:"\x1B[38;2;88;166;255m"};function en(e){return!e||e<=0?"0 tokens":e>=1e6?`${(e/1e6).toFixed(1)}k tokens`.replace("000.0k","M"):e>=1e3?`${(e/1e3).toFixed(1)}k tokens`:`${e} tokens`}var ci=`
117
92
  \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
118
93
  \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D
119
94
  \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557
120
95
  \u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D
121
96
  \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
122
97
  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D
123
- `.trim(),Ts=[[255,214,120],[255,190,90],[255,165,70],[255,140,62],[245,115,55],[225,95,48]];function _i(){return hi.split(`
124
- `).map((t,e)=>{let[n,o,s]=Ts[Math.min(e,Ts.length-1)];return`\x1B[38;2;${n};${o};${s}m${t}${i.reset}`}).join(`
125
- `)}function Hn(t,e,n){let o=(process.stdout.columns||80)>=50,s=process.env.HOME,r=s&&n.startsWith(s)?"~"+n.slice(s.length):n;console.log(""),console.log(o?_i():`${i.userPointer}${i.bold}${h.name}${i.reset}`),console.log(`
126
- ${i.bold}${h.name}${i.reset} ${i.dim}${h.version}${i.reset} ${i.gray}\xB7 ${h.tagline}${i.reset}`);let a=(c,d)=>console.log(` ${i.gray}${c.padEnd(8)}${i.reset}${d}`);a("model",`${i.accent}${t}${i.reset}`),a("taste",`${e} ${e===1?"rule":"rules"} loaded`),a("folder",r),console.log(`
98
+ `.trim(),ls=[[255,214,120],[255,190,90],[255,165,70],[255,140,62],[245,115,55],[225,95,48]];function di(){return ci.split(`
99
+ `).map((e,t)=>{let[n,o,s]=ls[Math.min(t,ls.length-1)];return`\x1B[38;2;${n};${o};${s}m${e}${i.reset}`}).join(`
100
+ `)}function Hn(e,t,n){let o=(process.stdout.columns||80)>=50,s=process.env.HOME,r=s&&n.startsWith(s)?"~"+n.slice(s.length):n;console.log(""),console.log(o?di():`${i.userPointer}${i.bold}${_.name}${i.reset}`),console.log(`
101
+ ${i.bold}${_.name}${i.reset} ${i.dim}v${xe}${i.reset} ${i.gray}\xB7 ${_.tagline}${i.reset}`);let a=(c,d)=>console.log(` ${i.gray}${c.padEnd(8)}${i.reset}${d}`);a("model",`${i.accent}${e}${i.reset}`),a("taste",`${t} ${t===1?"rule":"rules"} loaded`),a("folder",r),console.log(`
127
102
  ${i.dim} / commands \xB7 @ files \xB7 ! shell \xB7 esc interrupts \xB7 ? shortcuts${i.reset}
128
- `)}var wi=["Visualizing\u2026","Demystifying\u2026","Contemplating\u2026","Reasoning\u2026","Reflecting\u2026","Pondering\u2026","Analyzing\u2026","Evaluating\u2026","Examining\u2026","Inspecting\u2026","Investigating\u2026","Reviewing\u2026","Researching\u2026","Studying\u2026","Exploring\u2026","Mapping\u2026","Tracing\u2026","Parsing\u2026","Processing\u2026","Calculating\u2026","Computing\u2026","Synthesizing\u2026","Planning\u2026","Outlining\u2026","Sketching\u2026","Drafting\u2026","Composing\u2026","Crafting\u2026","Building\u2026","Assembling\u2026","Constructing\u2026","Designing\u2026","Formulating\u2026","Structuring\u2026","Organizing\u2026","Preparing\u2026","Refining\u2026","Polishing\u2026","Honing\u2026","Tuning\u2026","Aligning\u2026","Connecting\u2026","Resolving\u2026","Weaving\u2026","Threading\u2026","Sculpting\u2026","Crystallizing\u2026","Channeling\u2026","Conjuring\u2026","Brewing\u2026","Working\u2026","Cogitating\u2026","Ruminating\u2026","Hypothesizing\u2026","Conceptualizing\u2026","Philosophizing\u2026","Deciphering\u2026","Articulating\u2026","Illuminating\u2026","Elaborating\u2026","Orchestrating\u2026","Choreographing\u2026","Architecting\u2026","Calibrating\u2026","Materializing\u2026","Harmonizing\u2026","Contemplificating\u2026"];function an(){let t=l("cli.ui.status_words",wi.join("|")).split("|").map(e=>e.trim()).filter(Boolean);return t[Math.floor(Math.random()*t.length)]??"Working\u2026"}var Bn=["\xB7","\u2727","\u2726","\u2736","\u2737","\u2736","\u2726","\u2727","\xB7"],Rs=[12,5,4,4,4,4,4,5,16],Es=[5,4,4,4,4,4,5];function yi(t){let e=t%88,n=0;for(let s=0;s<Rs.length;s++)if(n+=Rs[s],e<n)return Bn[s];let o=e-58;n=0;for(let s=0;s<Es.length;s++)if(n+=Es[s],o<n)return Bn[7-s];return Bn[0]}var Ms=["#E5733A","#FF9A52","#FFB347","#FFD08A","#FFF1DC","#FFD08A","#FFB347","#FF9A52","#E5733A"],bi="#9A5A3A";function xi(t){let e=parseInt(t.replace("#",""),16);return`\x1B[38;2;${e>>16&255};${e>>8&255};${e&255}m`}function ki(t,e,n,o){let s=yi(4*e),r=e%(t.length+10),a="";for(let u=0;u<t.length;u++){let g=u-(r-5),_=g>=0&&g<Ms.length?Ms[g]:bi;a+=xi(_)+t[u]}let c=`${i.statusPillBg} ${i.statusPillFg}${i.bold}${s} ${a}${i.statusPillBg} ${i.reset}`,d=` ${i.bold}${i.gray}esc${i.reset} ${i.dim}${i.gray}to interrupt${i.reset} ${i.dim}${i.gray}\u2022${i.reset} ${i.dim}${i.gray}${n}s${i.reset} ${i.dim}${i.gray}\u2022${i.reset} ${i.gray}\u2193${i.reset} ${i.dim}${i.gray}${o}${i.reset}`;return c+d}var $i=new Intl.Segmenter(void 0,{granularity:"grapheme"}),qe=t=>Array.from($i.segment(t),e=>e.segment);function fe(t){let e=0;for(let n of t){let o=n.codePointAt(0);new RegExp("\\p{M}","u").test(n)||o>=8203&&o<=8207||o===65039||(e+=o>=4352&&o<=4447||o>=11904&&o<=42191||o>=44032&&o<=55203||o>=63744&&o<=64255||o>=65072&&o<=65135||o>=65280&&o<=65376||o>=65504&&o<=65510||o>=127744&&o<=129791?2:1)}return e}function vi(t,e){let n=qe(t),o=0;for(;o<n.length&&fe(n.slice(o).join(""))>e;)o++;return n.slice(o).join("")}function cn(t,e){let n=qe(t.slice(0,e));return n.pop(),n.join("").length}function zn(t,e){let n=qe(t.slice(e));return e+(n[0]?.length??0)}var ln=class{constructor(e,n){this.onInterrupt=e;this.input=n}onInterrupt;input;frame=0;startTime=Date.now();status=an();tokens=0;timer=null;drawnLines=0;isRunning=!1;isSuspended=!1;stdinListener=null;prevRaw=!1;resizeListener=()=>{this.clear(),this.draw()};selected=-1;start(){process.stdout.isTTY&&(this.isRunning=!0,this.isSuspended=!1,this.startTime=Date.now(),this.frame=0,this.attachInput(),process.stdout.on("resize",this.resizeListener),this.timer=setInterval(()=>{this.frame++,this.frame%35===0&&!this.status.includes("Running")&&!this.status.includes("Reading")&&!this.status.includes("Editing")&&(this.status=an()),this.draw()},80),this.draw())}suspend(){this.isSuspended=!0,this.clear(),this.detachInput(),process.stdout.isTTY&&process.stdout.write("\x1B[?25h")}resume(){this.isRunning&&(this.isSuspended=!1,this.attachInput(),this.draw())}attachInput(){let e=process.stdin;if(!e.isTTY||this.stdinListener)return;this.prevRaw=e.isRaw,e.setRawMode(!0),e.resume();let n=new fi("utf8");this.stdinListener=o=>{let s=n.write(o);s&&this.onKey(s)},e.on("data",this.stdinListener)}detachInput(){let e=process.stdin;e.isTTY&&this.stdinListener&&(e.removeListener("data",this.stdinListener),this.stdinListener=null,e.setRawMode&&e.setRawMode(this.prevRaw))}removeSelected(){let e=this.input?.queue;!e||this.selected<0||this.selected>=e.length||(e.splice(this.selected,1),this.selected=e.length?Math.min(this.selected,e.length-1):-1)}onKey(e){let n=this.input;if(e==="\x1B"||e===""){this.onInterrupt?.();return}if(!n)return;let o=n.queue;if(e==="\x1B[A")o.length&&(this.selected=this.selected<0?o.length-1:Math.max(0,this.selected-1));else if(e==="\x1B[B")this.selected>=0&&(this.selected=this.selected+1>=o.length?-1:this.selected+1);else if(e==="\x1B[3~"||e==="")this.removeSelected();else if(e==="\x7F"||e==="\b")this.selected>=0?this.removeSelected():n.draft=n.draft.slice(0,cn(n.draft,n.draft.length));else{if(e.startsWith("\x1B"))return;{let s=/[\r\n]$/.test(e),r=e.replace(/[\x00-\x1f\x7f]/g," ").replace(/\s+$/,s?"":" ");if(r&&(n.draft+=r,this.selected=-1),s){let a=n.draft.trim();a&&o.push(a),n.draft="",this.selected=-1}}}this.clear(),this.draw()}setStatus(e){this.status=e,this.draw()}setTokens(e){this.tokens=e,this.draw()}clear(){this.drawnLines>0&&process.stdout.isTTY&&(process.stdout.write(`\r${this.drawnLines>1?`\x1B[${this.drawnLines-1}A`:""}\x1B[J`),this.drawnLines=0)}regionLines(){let e=Math.floor((Date.now()-this.startTime)/1e3),n=[ki(this.status,this.frame,e,this.tokens)],o=this.input;if(!o)return n;let s=Math.max(process.stdout.columns||80,20),r=(d,u)=>{if(fe(d)<=u)return d;let g="";for(let _ of qe(d)){if(fe(g+_)>u-1)break;g+=_}return g+"\u2026"};o.queue.forEach((d,u)=>{let g=u===this.selected,_=r(`${u+1}. ${d}`,s-4);n.push(g?`${i.accent}${i.bold}\u276F ${_}${i.reset}`:`${i.gray}\u23F3 ${_}${i.reset}`)});let a=vi(o.draft,s-5),c=this.selected<0;return n.push(o.draft||!c?`${i.userPointer}\u276F${i.reset} ${a}${c?"\x1B[7m \x1B[0m":""}`:`${i.userPointer}\u276F${i.reset} \x1B[7m \x1B[0m${i.dim}Type to queue the next task\u2026${i.reset}`),n.push(`${i.dim}${"\u2500".repeat(s)}${i.reset}`),n.push(o.queue.length?`${i.dim}esc interrupt \xB7 enter queue \xB7 \u2191/\u2193 select queued \xB7 backspace/del remove${i.reset}`:`${i.dim}esc interrupt \xB7 enter queues a task to run next${i.reset}`),n}draw(){if(!this.isRunning||this.isSuspended||!process.stdout.isTTY)return;this.clear();let e=this.regionLines();process.stdout.write(`\x1B[?25l${e.map(n=>`\x1B[2K${n}`).join(`
129
- `)}`),this.drawnLines=e.length}isActive(){return this.isRunning}stop(){this.isRunning&&(this.isRunning=!1,this.isSuspended=!1,this.timer&&(clearInterval(this.timer),this.timer=null),this.clear(),process.stdout.off("resize",this.resizeListener),this.detachInput(),process.stdout.isTTY&&process.stdout.write("\x1B[?25h"))}getElapsedSec(){return Math.max(1,Math.round((Date.now()-this.startTime)/1e3))}},qn=[{command:"/add-dir",get description(){return l("cli.ui.add_directory_to_workspace_context","Add directory to workspace context")}},{command:"/worktree",get description(){return l("cli.ui.create_list_or_switch_git","Create, list, or switch git worktrees \u2014 /worktree [name|list|remove <name>]")}},{command:"/agents",get description(){return l("cli.ui.manage_agent_configurations","Manage agent configurations")}},{command:"/clear",displayCommand:"/clear (new)",get description(){return l("cli.ui.start_a_new_session_with","Start a new session with empty context; previous stays on disk, resumable with /resume")}},{command:"/clone",get description(){return l("cli.ui.clone_the_current_branch_into","Clone the current branch into a new session and switch to it")}},{command:"/theme",get description(){return l("cli.ui.switch_between_dark_and_light","Switch between dark and light themes")}},{command:"/language",get description(){return l("cli.ui.switch_the_interface_language_english","Switch the interface language (English / \u7B80\u4F53\u4E2D\u6587 / \u09AC\u09BE\u0982\u09B2\u09BE)")}},{command:"/compact",get description(){return l("cli.ui.compact_the_conversation_history","Compact the conversation history")}},{command:"/compact-mode",get description(){return l("cli.ui.select_a_compact_mode_to","Select a compact mode to compact sessions")}},{command:"/config",get description(){return l("cli.ui.search_and_change_settings","Search and change settings")}},{command:"/context",get description(){return l("cli.ui.show_context_window_usage_and","Show context window usage and breakdown")}},{command:"/design",get description(){return l("cli.ui.design_partner_audit_build_compose","Design partner: audit, build, compose, and ship UI \u2014 type /design to browse modes")}},{command:"/effort",get description(){return l("cli.ui.set_reasoning_effort_for_the","Set reasoning effort for the current model")}},{command:"/exit",get description(){return l("cli.ui.exit_command_code","Exit "+h.name)}},{command:"/fork",get description(){return l("cli.ui.fork_the_conversation_into_a","Fork the conversation into a new session \u2014 /fork [name]")}},{command:"/quit",get description(){return l("cli.ui.exit_command_code_alias_of","Exit "+h.name+" (alias of /exit)")}},{command:"/feedback",displayCommand:"/feedback (issue)",get description(){return l("cli.ui.report_a_bug_or_share","Report a bug or share feedback on GitHub \u2014 /feedback [title]")}},{command:"/goal",get description(){return l("cli.ui.set_an_objective_for_the","Set an objective for the agent to work towards - /goal <objective>|clear|status")}},{command:"/help",get description(){return l("cli.ui.show_available_shortcuts","Show available shortcuts")}},{command:"/init",get description(){return l("cli.ui.initialize_agents_md_for_this","Initialize AGENTS.md for this project")}},{command:"/import",get description(){return l("cli.ui.import_your_setup_from_another","Import your setup from another coding agent \u2014 /import <agent>")}},{command:"/learn-taste",get description(){return l("cli.ui.learn_taste_from_sessions_with","Learn taste from sessions with other coding agents")}},{command:"/login",get description(){return l("cli.ui.log_in_to_command_code","Log in to "+h.name)}},{command:"/logout",get description(){return l("cli.ui.log_out_of_command_code","Log out of "+h.name)}},{command:"/mcp",get description(){return l("cli.ui.manage_mcp_server_connections","Manage MCP server connections")}},{command:"/memory",get description(){return l("cli.ui.manage_command_code_memory","Manage "+h.name+" memory")}},{command:"/model",get description(){return l("cli.ui.switch_between_command_code_models","Switch between "+h.name+" models")}},{command:"/models",get description(){return l("cli.ui.list_available_models_on_your","List available models on your plan")}},{command:"/mods",get description(){return l("cli.ui.list_loaded_mods_hot_reload","List loaded mods, hot-reload them (/mods reload [name]), or open a pane (/mods open <pane>)")}},{command:"/name",get description(){return l("cli.ui.alias_of_rename_bare_name","Alias of /rename; bare /name shows the current name")}},{command:"/plan",get description(){return l("cli.ui.enter_plan_mode_plan_task","Enter plan mode; /plan <task> plans that task")}},{command:"/plan",get description(){return l("cli.ui.toggle_plan_mode_read_only","Toggle plan mode (read-only: the agent proposes a step-by-step plan, then asks to execute)")}},{command:"/mode",get description(){return l("cli.ui.show_or_switch_the_permission","Show or switch the permission mode \u2014 /mode [default|accept-edits|plan]")}},{command:"/mode:default",get description(){return l("cli.ui.switch_to_default_mode_prompt","Switch to default mode (prompt before edits/commands)")}},{command:"/mode:accept-edits",get description(){return l("cli.ui.switch_to_accept_edits_mode","Switch to accept edits mode (accept edits automatically)")}},{command:"/mode:plan",get description(){return l("cli.ui.switch_to_plan_mode_read","Switch to plan mode (read-only, no side effects)")}},{command:"/plans",get description(){return l("cli.ui.browse_review_and_annotate_saved","Browse, review, and annotate saved plans \u2014 /plans [name]")}},{command:"/plan-review",get description(){return l("cli.ui.review_this_session_s_latest","Review this session's latest plan")}},{command:"/paste",get description(){return l("cli.ui.attach_the_clipboard_image_to","Attach the clipboard image to your next message (or press Ctrl+V)")}},{command:"/image",get description(){return l("cli.ui.attach_an_image_file_to","Attach an image file to your next message \u2014 /image <path> (or use @file.png)")}},{command:"/pr-comments",get description(){return l("cli.ui.fetch_all_pr_comments_for","Fetch all PR comments for current branch")}},{command:"/reload",get description(){return l("cli.ui.restart_command_code_and_resume","Restart "+h.name+" and resume this session")}},{command:"/rename",get description(){return l("cli.ui.rename_the_current_session","Rename the current session")}},{command:"/resume",get description(){return l("cli.ui.resume_a_past_conversation","Resume a past conversation")}},{command:"/sessions",get description(){return l("cli.ui.resume_a_past_conversation_alias","Resume a past conversation (alias of /resume)")}},{command:"/review",get description(){return l("cli.ui.review_a_pull_request_optional","Review a pull request (optional PR number)")}},{command:"/rewind",get description(){return l("cli.ui.restore_to_a_previous_checkpoint","Restore to a previous checkpoint (Press Esc twice)")}},{command:"/tree",get description(){return l("cli.ui.browse_the_session_tree_and","Browse the session tree and jump to any point in it")}},{command:"/share",get description(){return l("cli.ui.share_as_a_github_gist","Share as a GitHub gist \u2014 /share gist [html|jsonl|md]")}},{command:"/skills",get description(){return l("cli.ui.browse_and_open_agent_skills","Browse and open agent skills")}},{command:"/status",get description(){return l("cli.ui.show_comprehensive_environment_status","Show comprehensive environment status")}},{command:"/statusline",get description(){return l("cli.ui.configure_command_code_s_statusline","Configure "+h.name+"'s statusline UI")}},{command:"/taste",get description(){return l("cli.ui.manage_taste_learning_and_usage","Manage Taste learning and usage")}},{command:"/terminal-setup",get description(){return l("cli.ui.setup_vscode_keybindings","Setup VSCode keybindings")}},{command:"/unshare",get description(){return l("cli.ui.stop_sharing_conversation","Stop sharing conversation")}},{command:"/update",get description(){return l("cli.ui.update_command_code_to_the","Update "+h.name+" to the latest version")}},{command:"/usage",get description(){return l("cli.ui.display_credits_plan_and_usage","Display credits, plan, and usage metrics")}},{command:"/upgrade",get description(){return l("cli.ui.open_billing_page_to_upgrade","Open billing page to upgrade your plan")}},{command:"/extra",get description(){return l("cli.ui.buy_extra_usage_at_api","Buy extra usage at API cost, zero markup")}},{command:"/trace",get description(){return l("cli.ui.copy_the_current_trace_id","Copy the current trace id; required for support debugging")}},{command:"/session-file",get description(){return l("cli.ui.show_the_current_session_id","Show the current session id and session file path")}},{command:"/copy",get description(){return l("cli.ui.copy_the_last_response_to","Copy the last response to the clipboard")}},{command:"/export",get description(){return l("cli.ui.export_session_export_html_jsonl","Export session \u2014 /export [html|jsonl|md] or a file path")}},{command:"/changelog",get description(){return l("cli.ui.see_what_s_new_in","See what's new in "+h.name)}},{command:"/hotkeys",get description(){return l("cli.ui.show_all_keyboard_shortcuts","Show all keyboard shortcuts")}},{command:"/shortcuts",get description(){return l("cli.ui.show_all_keyboard_shortcuts","Show all keyboard shortcuts")}},{command:"/todos",get description(){return l("cli.ui.manage_the_session_todo_list","Manage the session todo list \u2014 c completes an item, x removes it, a completes all")}},{command:"/rc",get description(){return l("cli.ui.remote_control_this_session_from","Remote-control this session from Telegram or Discord")}},{command:"/btw",get description(){return l("cli.ui.ask_a_quick_side_question","Ask a quick side question mid-turn")}}],gc=qn.map(t=>t.command);function He(t){if(!t.startsWith("/"))return{showMenu:!1,query:""};let e=t.slice(1);return/[\s/]/.test(e)?{showMenu:!1,query:""}:{showMenu:!0,query:e}}function it(t){let e=t.trim().toLowerCase();return e?qn.map(n=>{let o=n.command.toLowerCase(),s=(n.displayCommand??n.command).toLowerCase(),r=n.description.toLowerCase(),a=0;return o===`/${e}`?a+=200:o.startsWith(`/${e}`)?a+=100:o.includes(e)&&(a+=50),s!==o&&s.includes(e)&&(a+=60),r.includes(e)&&(a+=25),{item:n,score:a}}).filter(n=>n.score>0).sort((n,o)=>o.score-n.score).map(n=>n.item):[...qn]}function Ps(){console.log(l("cli.ui.0_command_code_1_2",`
130
- {0}{4}{1} {2}{5}{3}`,i.bold,i.reset,i.dim,i.reset,h.name,h.version)),console.log(l("cli.ui.0_ai_agent_that_pairs",`{0}{2}{1}
131
- `,i.gray,i.reset,h.tagline)),console.log(l("cli.ui.0_usage_1","{0}Usage:{1}",i.bold,i.reset)),console.log(` ${i.cyan}${h.bin}${i.reset} [options] [prompt]
132
- `),console.log(l("cli.ui.0_slash_commands_1","{0}Slash Commands:{1}",i.bold,i.reset));let e=[{cmd:"/clear, /new",desc:"Start a fresh session with clean context"},{cmd:"/model [id]",desc:"Switch active model (see /models)"},{cmd:"/models",desc:"List all available models on your plan"},{cmd:"/status",desc:"Show current session info, plan, and model"},{cmd:"/context",desc:"Show token usage breakdown in current context"},{cmd:"/skills [add <r>]",desc:"Browse project skills or add a standing rule"},{cmd:"/memory [add <n>]",desc:"Browse project memory or save a learning"},{cmd:"/taste",desc:"Show taste status (loaded skills and memories)"},{cmd:"/usage",desc:"Show monthly credits, requests, and token usage"},{cmd:"/copy",desc:"Copy the last response to clipboard"},{cmd:"/export [format]",desc:"Export session transcript (markdown or jsonl)"},{cmd:"/effort [low|high]",desc:"Set or toggle reasoning effort level"},{cmd:"/init",desc:`Create ${h.dirName}/skills.md and memory.md`},{cmd:"/exit, /quit",desc:"Exit session"}];for(let o of e)console.log(` ${i.cyan}${o.cmd.padEnd(24)}${i.reset} ${i.gray}${o.desc}${i.reset}`);console.log(l("cli.ui.0_keyboard_shortcuts_modes_1",`
103
+ `)}var ui=["Visualizing\u2026","Demystifying\u2026","Contemplating\u2026","Reasoning\u2026","Reflecting\u2026","Pondering\u2026","Analyzing\u2026","Evaluating\u2026","Examining\u2026","Inspecting\u2026","Investigating\u2026","Reviewing\u2026","Researching\u2026","Studying\u2026","Exploring\u2026","Mapping\u2026","Tracing\u2026","Parsing\u2026","Processing\u2026","Calculating\u2026","Computing\u2026","Synthesizing\u2026","Planning\u2026","Outlining\u2026","Sketching\u2026","Drafting\u2026","Composing\u2026","Crafting\u2026","Building\u2026","Assembling\u2026","Constructing\u2026","Designing\u2026","Formulating\u2026","Structuring\u2026","Organizing\u2026","Preparing\u2026","Refining\u2026","Polishing\u2026","Honing\u2026","Tuning\u2026","Aligning\u2026","Connecting\u2026","Resolving\u2026","Weaving\u2026","Threading\u2026","Sculpting\u2026","Crystallizing\u2026","Channeling\u2026","Conjuring\u2026","Brewing\u2026","Working\u2026","Cogitating\u2026","Ruminating\u2026","Hypothesizing\u2026","Conceptualizing\u2026","Philosophizing\u2026","Deciphering\u2026","Articulating\u2026","Illuminating\u2026","Elaborating\u2026","Orchestrating\u2026","Choreographing\u2026","Architecting\u2026","Calibrating\u2026","Materializing\u2026","Harmonizing\u2026","Contemplificating\u2026"];function Zt(){let e=l("cli.ui.status_words",ui.join("|")).split("|").map(t=>t.trim()).filter(Boolean);return e[Math.floor(Math.random()*e.length)]??"Working\u2026"}var Bn=["\xB7","\u2727","\u2726","\u2736","\u2737","\u2736","\u2726","\u2727","\xB7"],cs=[12,5,4,4,4,4,4,5,16],ds=[5,4,4,4,4,4,5];function mi(e){let t=e%88,n=0;for(let s=0;s<cs.length;s++)if(n+=cs[s],t<n)return Bn[s];let o=t-58;n=0;for(let s=0;s<ds.length;s++)if(n+=ds[s],o<n)return Bn[7-s];return Bn[0]}var us=["#E5733A","#FF9A52","#FFB347","#FFD08A","#FFF1DC","#FFD08A","#FFB347","#FF9A52","#E5733A"],pi="#9A5A3A";function gi(e){let t=parseInt(e.replace("#",""),16);return`\x1B[38;2;${t>>16&255};${t>>8&255};${t&255}m`}function fi(e,t,n,o){let s=mi(4*t),r=t%(e.length+10),a="";for(let u=0;u<e.length;u++){let g=u-(r-5),h=g>=0&&g<us.length?us[g]:pi;a+=gi(h)+e[u]}let c=`${i.statusPillBg} ${i.statusPillFg}${i.bold}${s} ${a}${i.statusPillBg} ${i.reset}`,d=` ${i.bold}${i.gray}esc${i.reset} ${i.dim}${i.gray}to interrupt${i.reset} ${i.dim}${i.gray}\u2022${i.reset} ${i.dim}${i.gray}${n}s${i.reset} ${i.dim}${i.gray}\u2022${i.reset} ${i.gray}\u2193${i.reset} ${i.dim}${i.gray}${o}${i.reset}`;return c+d}var hi=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Je=e=>Array.from(hi.segment(e),t=>t.segment);function fe(e){let t=0;for(let n of e){let o=n.codePointAt(0);new RegExp("\\p{M}","u").test(n)||o>=8203&&o<=8207||o===65039||(t+=o>=4352&&o<=4447||o>=11904&&o<=42191||o>=44032&&o<=55203||o>=63744&&o<=64255||o>=65072&&o<=65135||o>=65280&&o<=65376||o>=65504&&o<=65510||o>=127744&&o<=129791?2:1)}return t}function _i(e,t){let n=Je(e),o=0;for(;o<n.length&&fe(n.slice(o).join(""))>t;)o++;return n.slice(o).join("")}function tn(e,t){let n=Je(e.slice(0,t));return n.pop(),n.join("").length}function zn(e,t){let n=Je(e.slice(t));return t+(n[0]?.length??0)}var Qt=class{constructor(t,n){this.onInterrupt=t;this.input=n}onInterrupt;input;frame=0;startTime=Date.now();status=Zt();tokens=0;timer=null;drawnLines=0;isRunning=!1;isSuspended=!1;stdinListener=null;prevRaw=!1;resizeListener=()=>{this.clear(),this.draw()};selected=-1;start(){process.stdout.isTTY&&(this.isRunning=!0,this.isSuspended=!1,this.startTime=Date.now(),this.frame=0,this.attachInput(),process.stdout.on("resize",this.resizeListener),this.timer=setInterval(()=>{this.frame++,this.frame%35===0&&!this.status.includes("Running")&&!this.status.includes("Reading")&&!this.status.includes("Editing")&&(this.status=Zt()),this.draw()},80),this.draw())}suspend(){this.isSuspended=!0,this.clear(),this.detachInput(),process.stdout.isTTY&&process.stdout.write("\x1B[?25h")}resume(){this.isRunning&&(this.isSuspended=!1,this.attachInput(),this.draw())}attachInput(){let t=process.stdin;if(!t.isTTY||this.stdinListener)return;this.prevRaw=t.isRaw,t.setRawMode(!0),t.resume();let n=new li("utf8");this.stdinListener=o=>{let s=n.write(o);s&&this.onKey(s)},t.on("data",this.stdinListener)}detachInput(){let t=process.stdin;t.isTTY&&this.stdinListener&&(t.removeListener("data",this.stdinListener),this.stdinListener=null,t.setRawMode&&t.setRawMode(this.prevRaw))}removeSelected(){let t=this.input?.queue;!t||this.selected<0||this.selected>=t.length||(t.splice(this.selected,1),this.selected=t.length?Math.min(this.selected,t.length-1):-1)}onKey(t){let n=this.input;if(t==="\x1B"||t===""){this.onInterrupt?.();return}if(!n)return;let o=n.queue;if(t==="\x1B[A")o.length&&(this.selected=this.selected<0?o.length-1:Math.max(0,this.selected-1));else if(t==="\x1B[B")this.selected>=0&&(this.selected=this.selected+1>=o.length?-1:this.selected+1);else if(t==="\x1B[3~"||t==="")this.removeSelected();else if(t==="\x7F"||t==="\b")this.selected>=0?this.removeSelected():n.draft=n.draft.slice(0,tn(n.draft,n.draft.length));else{if(t.startsWith("\x1B"))return;{let s=/[\r\n]$/.test(t),r=t.replace(/[\x00-\x1f\x7f]/g," ").replace(/\s+$/,s?"":" ");if(r&&(n.draft+=r,this.selected=-1),s){let a=n.draft.trim();a&&o.push(a),n.draft="",this.selected=-1}}}this.clear(),this.draw()}setStatus(t){this.status=t,this.draw()}setTokens(t){this.tokens=t,this.draw()}clear(){this.drawnLines>0&&process.stdout.isTTY&&(process.stdout.write(`\r${this.drawnLines>1?`\x1B[${this.drawnLines-1}A`:""}\x1B[J`),this.drawnLines=0)}regionLines(){let t=Math.floor((Date.now()-this.startTime)/1e3),n=[fi(this.status,this.frame,t,this.tokens)],o=this.input;if(!o)return n;let s=Math.max(process.stdout.columns||80,20),r=(d,u)=>{if(fe(d)<=u)return d;let g="";for(let h of Je(d)){if(fe(g+h)>u-1)break;g+=h}return g+"\u2026"};o.queue.forEach((d,u)=>{let g=u===this.selected,h=r(`${u+1}. ${d}`,s-4);n.push(g?`${i.accent}${i.bold}\u276F ${h}${i.reset}`:`${i.gray}\u23F3 ${h}${i.reset}`)});let a=_i(o.draft,s-5),c=this.selected<0;return n.push(o.draft||!c?`${i.userPointer}\u276F${i.reset} ${a}${c?"\x1B[7m \x1B[0m":""}`:`${i.userPointer}\u276F${i.reset} \x1B[7m \x1B[0m${i.dim}Type to queue the next task\u2026${i.reset}`),n.push(`${i.dim}${"\u2500".repeat(s)}${i.reset}`),n.push(o.queue.length?`${i.dim}esc interrupt \xB7 enter queue \xB7 \u2191/\u2193 select queued \xB7 backspace/del remove${i.reset}`:`${i.dim}esc interrupt \xB7 enter queues a task to run next${i.reset}`),n}draw(){if(!this.isRunning||this.isSuspended||!process.stdout.isTTY)return;this.clear();let t=this.regionLines();process.stdout.write(`\x1B[?25l${t.map(n=>`\x1B[2K${n}`).join(`
104
+ `)}`),this.drawnLines=t.length}isActive(){return this.isRunning}stop(){this.isRunning&&(this.isRunning=!1,this.isSuspended=!1,this.timer&&(clearInterval(this.timer),this.timer=null),this.clear(),process.stdout.off("resize",this.resizeListener),this.detachInput(),process.stdout.isTTY&&process.stdout.write("\x1B[?25h"))}getElapsedSec(){return Math.max(1,Math.round((Date.now()-this.startTime)/1e3))}},qn=[{command:"/add-dir",get description(){return l("cli.ui.add_directory_to_workspace_context","Add directory to workspace context")}},{command:"/worktree",get description(){return l("cli.ui.create_list_or_switch_git","Create, list, or switch git worktrees \u2014 /worktree [name|list|remove <name>]")}},{command:"/agents",get description(){return l("cli.ui.manage_agent_configurations","Manage agent configurations")}},{command:"/clear",displayCommand:"/clear (new)",get description(){return l("cli.ui.start_a_new_session_with","Start a new session with empty context; previous stays on disk, resumable with /resume")}},{command:"/clone",get description(){return l("cli.ui.clone_the_current_branch_into","Clone the current branch into a new session and switch to it")}},{command:"/theme",get description(){return l("cli.ui.switch_between_dark_and_light","Switch between dark and light themes")}},{command:"/language",get description(){return l("cli.ui.switch_the_interface_language_english","Switch the interface language (English / \u7B80\u4F53\u4E2D\u6587 / \u09AC\u09BE\u0982\u09B2\u09BE)")}},{command:"/compact",get description(){return l("cli.ui.compact_the_conversation_history","Compact the conversation history")}},{command:"/compact-mode",get description(){return l("cli.ui.select_a_compact_mode_to","Select a compact mode to compact sessions")}},{command:"/config",get description(){return l("cli.ui.search_and_change_settings","Search and change settings")}},{command:"/context",get description(){return l("cli.ui.show_context_window_usage_and","Show context window usage and breakdown")}},{command:"/design",get description(){return l("cli.ui.design_partner_audit_build_compose","Design partner: audit, build, compose, and ship UI \u2014 type /design to browse modes")}},{command:"/effort",get description(){return l("cli.ui.set_reasoning_effort_for_the","Set reasoning effort for the current model")}},{command:"/exit",get description(){return l("cli.ui.exit_command_code","Exit "+_.name)}},{command:"/fork",get description(){return l("cli.ui.fork_the_conversation_into_a","Fork the conversation into a new session \u2014 /fork [name]")}},{command:"/quit",get description(){return l("cli.ui.exit_command_code_alias_of","Exit "+_.name+" (alias of /exit)")}},{command:"/feedback",displayCommand:"/feedback (issue)",get description(){return l("cli.ui.report_a_bug_or_share","Report a bug or share feedback on GitHub \u2014 /feedback [title]")}},{command:"/goal",get description(){return l("cli.ui.set_an_objective_for_the","Set an objective for the agent to work towards - /goal <objective>|clear|status")}},{command:"/help",get description(){return l("cli.ui.show_available_shortcuts","Show available shortcuts")}},{command:"/init",get description(){return l("cli.ui.initialize_agents_md_for_this","Initialize AGENTS.md for this project")}},{command:"/import",get description(){return l("cli.ui.import_your_setup_from_another","Import your setup from another coding agent \u2014 /import <agent>")}},{command:"/learn-taste",get description(){return l("cli.ui.learn_taste_from_sessions_with","Learn taste from sessions with other coding agents")}},{command:"/login",get description(){return l("cli.ui.log_in_to_command_code","Log in to "+_.name)}},{command:"/logout",get description(){return l("cli.ui.log_out_of_command_code","Log out of "+_.name)}},{command:"/mcp",get description(){return l("cli.ui.manage_mcp_server_connections","Manage MCP server connections")}},{command:"/memory",get description(){return l("cli.ui.manage_command_code_memory","Manage "+_.name+" memory")}},{command:"/model",get description(){return l("cli.ui.switch_between_command_code_models","Switch between "+_.name+" models")}},{command:"/models",get description(){return l("cli.ui.list_available_models_on_your","List available models on your plan")}},{command:"/mods",get description(){return l("cli.ui.list_loaded_mods_hot_reload","List loaded mods, hot-reload them (/mods reload [name]), or open a pane (/mods open <pane>)")}},{command:"/name",get description(){return l("cli.ui.alias_of_rename_bare_name","Alias of /rename; bare /name shows the current name")}},{command:"/plan",get description(){return l("cli.ui.enter_plan_mode_plan_task","Enter plan mode; /plan <task> plans that task")}},{command:"/plan",get description(){return l("cli.ui.toggle_plan_mode_read_only","Toggle plan mode (read-only: the agent proposes a step-by-step plan, then asks to execute)")}},{command:"/mode",get description(){return l("cli.ui.show_or_switch_the_permission","Show or switch the permission mode \u2014 /mode [default|accept-edits|plan]")}},{command:"/mode:default",get description(){return l("cli.ui.switch_to_default_mode_prompt","Switch to default mode (prompt before edits/commands)")}},{command:"/mode:accept-edits",get description(){return l("cli.ui.switch_to_accept_edits_mode","Switch to accept edits mode (accept edits automatically)")}},{command:"/mode:plan",get description(){return l("cli.ui.switch_to_plan_mode_read","Switch to plan mode (read-only, no side effects)")}},{command:"/plans",get description(){return l("cli.ui.browse_review_and_annotate_saved","Browse, review, and annotate saved plans \u2014 /plans [name]")}},{command:"/plan-review",get description(){return l("cli.ui.review_this_session_s_latest","Review this session's latest plan")}},{command:"/paste",get description(){return l("cli.ui.attach_the_clipboard_image_to","Attach the clipboard image to your next message (or press Ctrl+V)")}},{command:"/image",get description(){return l("cli.ui.attach_an_image_file_to","Attach an image file to your next message \u2014 /image <path> (or use @file.png)")}},{command:"/pr-comments",get description(){return l("cli.ui.fetch_all_pr_comments_for","Fetch all PR comments for current branch")}},{command:"/reload",get description(){return l("cli.ui.restart_command_code_and_resume","Restart "+_.name+" and resume this session")}},{command:"/rename",get description(){return l("cli.ui.rename_the_current_session","Rename the current session")}},{command:"/resume",get description(){return l("cli.ui.resume_a_past_conversation","Resume a past conversation")}},{command:"/sessions",get description(){return l("cli.ui.resume_a_past_conversation_alias","Resume a past conversation (alias of /resume)")}},{command:"/review",get description(){return l("cli.ui.review_a_pull_request_optional","Review a pull request (optional PR number)")}},{command:"/rewind",get description(){return l("cli.ui.restore_to_a_previous_checkpoint","Restore to a previous checkpoint (Press Esc twice)")}},{command:"/tree",get description(){return l("cli.ui.browse_the_session_tree_and","Browse the session tree and jump to any point in it")}},{command:"/share",get description(){return l("cli.ui.share_as_a_github_gist","Share as a GitHub gist \u2014 /share gist [html|jsonl|md]")}},{command:"/skills",get description(){return l("cli.ui.browse_and_open_agent_skills","Browse and open agent skills")}},{command:"/status",get description(){return l("cli.ui.show_comprehensive_environment_status","Show comprehensive environment status")}},{command:"/statusline",get description(){return l("cli.ui.configure_command_code_s_statusline","Configure "+_.name+"'s statusline UI")}},{command:"/taste",get description(){return l("cli.ui.manage_taste_learning_and_usage","Manage Taste learning and usage")}},{command:"/terminal-setup",get description(){return l("cli.ui.setup_vscode_keybindings","Setup VSCode keybindings")}},{command:"/unshare",get description(){return l("cli.ui.stop_sharing_conversation","Stop sharing conversation")}},{command:"/update",get description(){return l("cli.ui.update_command_code_to_the","Update "+_.name+" to the latest version")}},{command:"/usage",get description(){return l("cli.ui.display_credits_plan_and_usage","Display credits, plan, and usage metrics")}},{command:"/upgrade",get description(){return l("cli.ui.open_billing_page_to_upgrade","Open billing page to upgrade your plan")}},{command:"/extra",get description(){return l("cli.ui.buy_extra_usage_at_api","Buy extra usage at API cost, zero markup")}},{command:"/trace",get description(){return l("cli.ui.copy_the_current_trace_id","Copy the current trace id; required for support debugging")}},{command:"/session-file",get description(){return l("cli.ui.show_the_current_session_id","Show the current session id and session file path")}},{command:"/copy",get description(){return l("cli.ui.copy_the_last_response_to","Copy the last response to the clipboard")}},{command:"/export",get description(){return l("cli.ui.export_session_export_html_jsonl","Export session \u2014 /export [html|jsonl|md] or a file path")}},{command:"/changelog",get description(){return l("cli.ui.see_what_s_new_in","See what's new in "+_.name)}},{command:"/hotkeys",get description(){return l("cli.ui.show_all_keyboard_shortcuts","Show all keyboard shortcuts")}},{command:"/shortcuts",get description(){return l("cli.ui.show_all_keyboard_shortcuts","Show all keyboard shortcuts")}},{command:"/todos",get description(){return l("cli.ui.manage_the_session_todo_list","Manage the session todo list \u2014 c completes an item, x removes it, a completes all")}},{command:"/rc",get description(){return l("cli.ui.remote_control_this_session_from","Remote-control this session from Telegram or Discord")}},{command:"/btw",get description(){return l("cli.ui.ask_a_quick_side_question","Ask a quick side question mid-turn")}}],Yl=qn.map(e=>e.command);function Ge(e){if(!e.startsWith("/"))return{showMenu:!1,query:""};let t=e.slice(1);return/[\s/]/.test(t)?{showMenu:!1,query:""}:{showMenu:!0,query:t}}function lt(e){let t=e.trim().toLowerCase();return t?qn.map(n=>{let o=n.command.toLowerCase(),s=(n.displayCommand??n.command).toLowerCase(),r=n.description.toLowerCase(),a=0;return o===`/${t}`?a+=200:o.startsWith(`/${t}`)?a+=100:o.includes(t)&&(a+=50),s!==o&&s.includes(t)&&(a+=60),r.includes(t)&&(a+=25),{item:n,score:a}}).filter(n=>n.score>0).sort((n,o)=>o.score-n.score).map(n=>n.item):[...qn]}function ps(){console.log(l("cli.ui.0_command_code_1_2",`
105
+ {0}{4}{1} {2}v{5}{3}`,i.bold,i.reset,i.dim,i.reset,_.name,xe)),console.log(l("cli.ui.0_ai_agent_that_pairs",`{0}{2}{1}
106
+ `,i.gray,i.reset,_.tagline)),console.log(l("cli.ui.0_usage_1","{0}Usage:{1}",i.bold,i.reset)),console.log(` ${i.cyan}${_.bin}${i.reset} [options] [prompt]
107
+ `),console.log(l("cli.ui.0_slash_commands_1","{0}Slash Commands:{1}",i.bold,i.reset));let t=[{cmd:"/clear, /new",desc:"Start a fresh session with clean context"},{cmd:"/model [id]",desc:"Switch active model (see /models)"},{cmd:"/models",desc:"List all available models on your plan"},{cmd:"/status",desc:"Show current session info, plan, and model"},{cmd:"/context",desc:"Show token usage breakdown in current context"},{cmd:"/skills [add <r>]",desc:"Browse project skills or add a standing rule"},{cmd:"/memory [add <n>]",desc:"Browse project memory or save a learning"},{cmd:"/taste",desc:"Show taste status (loaded skills and memories)"},{cmd:"/usage",desc:"Show monthly credits, requests, and token usage"},{cmd:"/copy",desc:"Copy the last response to clipboard"},{cmd:"/export [format]",desc:"Export session transcript (markdown or jsonl)"},{cmd:"/effort [low|high]",desc:"Set or toggle reasoning effort level"},{cmd:"/init",desc:`Create ${_.dirName}/skills.md and memory.md`},{cmd:"/exit, /quit",desc:"Exit session"}];for(let o of t)console.log(` ${i.cyan}${o.cmd.padEnd(24)}${i.reset} ${i.gray}${o.desc}${i.reset}`);console.log(l("cli.ui.0_keyboard_shortcuts_modes_1",`
133
108
  {0}Keyboard Shortcuts & Modes:{1}`,i.bold,i.reset));let n=[{key:"Tab",desc:"Autocomplete slash commands and @file paths"},{key:"Esc",desc:"Interrupt in-flight model turn"},{key:"\u2191 / \u2193",desc:"Browse prompt history"},{key:"@<path>",desc:"Attach file contents into context (e.g. @src/index.ts)"},{key:"!<cmd>",desc:"Bash mode \u2014 run a shell command directly (e.g. !git status)"},{key:"Ctrl+C",desc:"Cancel current input prompt"},{key:"Ctrl+D",desc:"Exit session when input is empty"}];for(let o of n)console.log(` ${i.accent}${o.key.padEnd(24)}${i.reset} ${i.gray}${o.desc}${i.reset}`);console.log(l("cli.ui.0_1_2_tip_type",`
134
109
  {0}\u276F{1} {2}Tip: Type {3}@{4} followed by a path or {5}/{6} for commands and press Tab to complete.{7}
135
- `,i.cyan,i.reset,i.gray,i.cyan,i.reset,i.cyan,i.reset,i.reset))}function Jn(){return[`${i.bold}Available Shortcuts:${i.reset}`,` ${i.accent}!${i.reset} for bash mode ${i.cyan}double tap esc${i.reset} to clear input`,` ${i.accent}/${i.reset} for commands ${i.cyan}\\ + \u21B5 or ctrl + j${i.reset} for newline`,` ${i.accent}@${i.reset} for file paths ${i.cyan}ctrl + v${i.reset} to paste image`,` ${i.accent}Tab${i.reset} for autocomplete ${i.cyan}\u2191 / \u2193${i.reset} to browse history`,` ${i.accent}Esc${i.reset} to interrupt agent ${i.cyan}ctrl + c${i.reset} cancel \xB7 ${i.cyan}ctrl + d${i.reset} exit`]}function Gn(){console.log("");for(let t of Jn())console.log(t);console.log("")}async function As(t){let n=process.platform==="darwin"?"pbcopy":"wl-copy";return new Promise(o=>{try{let s=Cs(n,[],{stdio:["pipe","ignore","ignore"]});s.stdin.write(t),s.stdin.end(),s.on("close",r=>{if(r===0)return o(!0);Wn(t).then(o)}),s.on("error",()=>{Wn(t).then(o)})}catch{Wn(t).then(o)}})}function Wn(t){return new Promise(e=>{try{let n=Cs("xclip",["-selection","clipboard"],{stdio:["pipe","ignore","ignore"]});n.stdin.write(t),n.stdin.end(),n.on("close",o=>e(o===0)),n.on("error",()=>e(!1))}catch{e(!1)}})}async function js(t,e=200){let n=[],o=new Set([".git","node_modules","dist",".next",".turbo",".gemini"]);async function s(r){if(!(n.length>=e))try{let a=await gi.readdir(r,{withFileTypes:!0});for(let c of a){if(n.length>=e)break;if(o.has(c.name))continue;let d=Ss.join(r,c.name),u=Ss.relative(t,d);c.isDirectory()?(n.push(u+"/"),await s(d)):n.push(u)}}catch{}}return await s(t),n}var Ae=[];async function Kn(){let{execFile:t}=await import("child_process"),e=await import("fs/promises"),o=`${(await import("os")).tmpdir()}/forge-paste-${Date.now()}.png`,s=(r,a)=>new Promise(c=>t(r,a,{encoding:"buffer",maxBuffer:32*1024*1024},(d,u)=>c(d?null:u)));try{if(process.platform==="darwin"){if(!await new Promise(c=>t("osascript",["-e",`set f to open for access POSIX file "${o}" with write permission`,"-e","set eof f to 0","-e","write (the clipboard as \xABclass PNGf\xBB) to f","-e","close access f"],d=>c(!d))))return await e.rm(o,{force:!0}),null}else{let a=await s("wl-paste",["--type","image/png"])??await s("xclip",["-selection","clipboard","-t","image/png","-o"]);if(!a||a.length<8)return null;await e.writeFile(o,a)}let r=await e.readFile(o).then(a=>a.subarray(0,4)).catch(()=>null);return!r||r[0]!==137||r[1]!==80?(await e.rm(o,{force:!0}),null):o}catch{return null}}var $=t=>`\x1B[2m${t}\x1B[0m`,Ns=(t,e=200)=>(t.length>e?t.slice(0,e)+"\u2026":t).replace(/\n/g,"\u23CE ");function Ri(t){t.type==="token"?process.stdout.write(t.text):t.type==="assistant"?console.log(`
136
- ${i.assistantPrefix}\u25C6${i.reset} ${t.text}
137
- `):t.type==="tool_start"?console.log(`${i.userPointer}\u2692${i.reset} ${i.bold}${t.name.replace(/_/g," ")}${i.reset} ${$(Ns(JSON.stringify(t.args),120))}`):t.type==="tool_result"?console.log($(` ${t.ok?"\u2713":"\u2717"} ${Ns(t.output,160)}`)):t.type==="repair"?console.log($(` \u21BA repaired ${t.name} call (${t.via})`)):t.type==="denied"?console.log($(" \u2717 denied")):t.type==="hook_warning"?console.error(`\x1B[33m \u26A0 ${t.message}\x1B[0m`):t.type==="context_warning"?console.error(l("cli.run.large_context_0_tokens_per","\x1B[33m\u26A0 large context: ~{0} tokens per request. Long contexts cost more; consider a fresh session or narrower @mentions.\x1B[0m",t.tokens.toLocaleString())):t.type==="escalate"&&console.log(l("cli.run.escalating_0_1_2","\x1B[33m\u2191 escalating {0} \u2192 {1}: {2}\x1B[0m",t.from,t.to,t.reason))}var Ei=t=>console.error($(` \u21BB ${t.status?`server returned ${t.status}`:"connection problem"}; retrying in ${(t.delayMs/1e3).toFixed(1)}s\u2026`));async function Vn(t){vs();let e=await oe(),n=t.model==="mock-model"||t.model==="mock";if(!!e.token){let s=t.model??e.defaultModel??"default";try{hn(await X("/v1/models"))}catch{}if(!t.model)try{let r=await X("/v1/models"),a=r.data.map(d=>d.id),c=typeof r.default=="string"&&a.includes(r.default)?r.default:null;if(!e.defaultModel&&c&&(s=c),a.length>0&&!a.includes(s)){let d=c||a[0];console.error($(`model "${s}" is not available on this server; switching to "${d}".`)),s=d,await We({defaultModel:d})}}catch{}return{client:new Ut({baseUrl:`${e.apiUrl.replace(/\/$/,"")}/v1`,apiKey:e.token,onRetry:Ei}),model:s,label:"gateway",apiUrl:e.apiUrl}}if(n)return{client:new De,model:"mock-model",label:"local mock"};if(!e.token){if(t.prompt)throw new ne(401,"Not logged in \u2014 run `forge login` to authenticate.",{});return{client:{chat:async()=>{throw new ne(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},model:t.model??e.defaultModel??"default",label:"not logged in",apiUrl:e.apiUrl}}throw new Error(l("cli.run.no_backend_available","Not logged in. Run `{0} login` to get started.",h.bin))}async function Xn(t,e,n){let o=t.escalateTo??process.env.FORGE_ESCALATION_MODEL;if(o)return o;if(e!=="gateway")return null;let r=(await X("/v1/models")).data.filter(a=>a.provider!=="mock"&&a.id!==n);return r.sort((a,c)=>c.multiplier-a.multiplier),r[0]?.id??null}function Is(t,e,n){return async o=>{if(!process.stdin.isTTY)return console.error($(` (not a terminal) refusing: ${o.reason} \u2014 rerun with --yolo to auto-approve`)),!1;e?.();let s=t??at.createInterface({input:process.stdin,output:process.stdout}),r=(await s.question(`
110
+ `,i.cyan,i.reset,i.gray,i.cyan,i.reset,i.cyan,i.reset,i.reset))}function Jn(){return[`${i.bold}Available Shortcuts:${i.reset}`,` ${i.accent}!${i.reset} for bash mode ${i.cyan}double tap esc${i.reset} to clear input`,` ${i.accent}/${i.reset} for commands ${i.cyan}\\ + \u21B5 or ctrl + j${i.reset} for newline`,` ${i.accent}@${i.reset} for file paths ${i.cyan}ctrl + v${i.reset} to paste image`,` ${i.accent}Tab${i.reset} for autocomplete ${i.cyan}\u2191 / \u2193${i.reset} to browse history`,` ${i.accent}Esc${i.reset} to interrupt agent ${i.cyan}ctrl + c${i.reset} cancel \xB7 ${i.cyan}ctrl + d${i.reset} exit`]}function Gn(){console.log("");for(let e of Jn())console.log(e);console.log("")}async function gs(e){let n=process.platform==="darwin"?"pbcopy":"wl-copy";return new Promise(o=>{try{let s=ms(n,[],{stdio:["pipe","ignore","ignore"]});s.stdin.write(e),s.stdin.end(),s.on("close",r=>{if(r===0)return o(!0);Wn(e).then(o)}),s.on("error",()=>{Wn(e).then(o)})}catch{Wn(e).then(o)}})}function Wn(e){return new Promise(t=>{try{let n=ms("xclip",["-selection","clipboard"],{stdio:["pipe","ignore","ignore"]});n.stdin.write(e),n.stdin.end(),n.on("close",o=>t(o===0)),n.on("error",()=>t(!1))}catch{t(!1)}})}async function fs(e,t=200){let n=[],o=new Set([".git","node_modules","dist",".next",".turbo",".gemini"]);async function s(r){if(!(n.length>=t))try{let a=await ai.readdir(r,{withFileTypes:!0});for(let c of a){if(n.length>=t)break;if(o.has(c.name))continue;let d=as.join(r,c.name),u=as.relative(e,d);c.isDirectory()?(n.push(u+"/"),await s(d)):n.push(u)}}catch{}}return await s(e),n}var Ae=[];async function Kn(){let{execFile:e}=await import("child_process"),t=await import("fs/promises"),o=`${(await import("os")).tmpdir()}/forge-paste-${Date.now()}.png`,s=(r,a)=>new Promise(c=>e(r,a,{encoding:"buffer",maxBuffer:32*1024*1024},(d,u)=>c(d?null:u)));try{if(process.platform==="darwin"){if(!await new Promise(c=>e("osascript",["-e",`set f to open for access POSIX file "${o}" with write permission`,"-e","set eof f to 0","-e","write (the clipboard as \xABclass PNGf\xBB) to f","-e","close access f"],d=>c(!d))))return await t.rm(o,{force:!0}),null}else{let a=await s("wl-paste",["--type","image/png"])??await s("xclip",["-selection","clipboard","-t","image/png","-o"]);if(!a||a.length<8)return null;await t.writeFile(o,a)}let r=await t.readFile(o).then(a=>a.subarray(0,4)).catch(()=>null);return!r||r[0]!==137||r[1]!==80?(await t.rm(o,{force:!0}),null):o}catch{return null}}var hs=e=>e.replace(/https?:\/\/[^\s"'<>]+/gi,"server").trim();function je(e,t){if(e instanceof Me){let o=e.reason||"network error",s="Unable to connect to the server.";return/timeout/i.test(o)?s="Connection timed out.":/ENOTFOUND|EAI_AGAIN/i.test(o)?s="DNS resolution failed. Please check your internet connection.":/ECONNREFUSED/i.test(o)&&(s="Server connection refused or unreachable."),`Network error: ${s} (${o})
111
+ \u2022 Please check your internet connection and try again.`}if(e instanceof ne){let o=e.body?.error??{},s=hs(e.message);switch(e.status){case 401:return s.includes("login")?s:`Not authorized: ${s}.
112
+ Run \`/login\` or \`${_.bin} login\` to authenticate.`;case 402:return`${s}
113
+ See \`${_.bin} usage\`. Upgrade in the dashboard (/app/billing) or wait for the reset.`;case 403:return`${s}
114
+ Run \`${_.bin} models\` to see what your plan includes.`;case 404:return`${s}
115
+ Run \`${_.bin} models\` to list valid model ids.`;case 429:{let r=s;return r.includes("daily limit of 60 free-model requests")&&(r="You reached the daily limit of 60 free-model requests for this account. Tip: switch to mock-model with `/model mock-model` or try again after UTC 00:00."),`Rate limited${o.retryAfterSec?` \u2014 try again in ${o.retryAfterSec}s`:""}. ${r}`}case 500:case 502:case 503:case 504:return`${s}
116
+ It was retried once. Try again shortly.`;default:return`${s} (HTTP ${e.status})`}}let n=hs(e instanceof Error?e.message:String(e));return n.includes("daily limit of 60 free-model requests")||n.includes("free_daily_limit")?`Daily limit of 60 free-model requests reached.
117
+ \u2022 Try again after 00:00 UTC.`:n.includes("Insufficient Balance")?"The service is temporarily unavailable. Please try again shortly.":n}function yi(e){if(process.env.FORGE_NO_BROWSER)return;let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{wi(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}async function nn(){let e=await X("/v1/auth/device/code",{method:"POST",auth:!1});console.log(l("cli.commands.open_0_and_confirm_code",`
118
+ Open {0}
119
+ and confirm code: {1}
120
+ `,e.verificationUrl,e.userCode)),yi(e.verificationUrl);let t=Date.now()+e.expiresIn*1e3;for(;Date.now()<t;){await new Promise(o=>setTimeout(o,e.interval*1e3));let n=await X("/v1/auth/device/token",{method:"POST",auth:!1,body:JSON.stringify({deviceCode:e.deviceCode})}).catch(o=>{throw o});if(n.status==="approved"){await ze({token:n.apiKey});let o=await X("/v1/me");return console.log(l("cli.commands.logged_in_as_0_1","Logged in as {0} ({1} plan).",o.email,o.plan)),o}}throw new Error(l("cli.commands.login_timed_out","login timed out"))}async function on(){await ze({token:void 0}),console.log(l("cli.commands.logged_out","Logged out."))}async function sn(e){let t=await oe();if(e){await ze({defaultModel:e}),console.log(l("cli.commands.default_model_set_to_0","Default model set to: {0}",e));return}let n=await X("/v1/models");console.log(l("cli.commands.models_on_your_0_plan","Models on your {0} plan:",n.plan));let o=t.defaultModel||n.default;for(let s of n.data){let r=s.id===o,c=s.id===n.default?" [default]":"";console.log(l("cli.commands.0_1_2_x_3","{0} {1} x{2} credits/token {3}",r?"*":" ",(s.id+c).padEnd(32),s.multiplier,s.vision?"[images]":""))}n.default&&console.log(`
121
+ Server default: ${n.default}`),n.data.some(s=>s.vision)&&console.log(l("cli.commands.images_can_read_images_attach",`
122
+ [images] = can read images (attach with @file.png, drag a file in, or Ctrl+V)`)),n.data.length||console.log(l("cli.commands.no_models_available_the_server","No models are available for your account right now."))}async function rn(){let e=await X("/v1/usage"),t=r=>r.toLocaleString(),n=(e.promptTokens??0)+(e.completionTokens??0),o=en(n);console.log(l("cli.commands.plan_0_credits_1_of",`Plan: {0}
123
+ Credits: {1} of {2} used this month
124
+ Remaining: {3}
125
+ Requests: {4} Tokens: {5}`,e.plan,t(e.usedCredits),e.monthlyOff?"no cap":t(e.limitCredits),e.monthlyOff?"unlimited":t(e.remainingCredits),e.requests,o));let s=r=>r?`${t(r.usedCredits)} / ${r.limitCredits?t(r.limitCredits):"no cap"}`:"";e.windows&&console.log(`5-hour: ${s(e.windows.fiveHour)}
126
+ Weekly: ${s(e.windows.weekly)}`)}async function an(){let e=await Nn(process.cwd());for(let t of[st(process.cwd()),yt(process.cwd())])console.log(`${e.includes(t)?"created":"exists "} ${xt.relative(process.cwd(),t)}`);console.log(l("cli.commands.add_a_rule_0_skills",`
127
+ Add a rule: {0} skills add "Use pnpm, not npm"`,_.bin))}async function ws(){let e=process.cwd(),[t,n]=[await qe(e),await Pe(e)];t.length?(console.log(l("cli.commands.skills_0_applied_to_every","Skills ({0}) \u2014 applied to every run:",xt.relative(e,st(e)))),t.forEach((o,s)=>console.log(` ${s+1}. ${o}`))):console.log(l("cli.commands.no_skills_yet_add_one",'No skills yet. Add one: {0} skills add "Prefer pnpm"',_.bin)),console.log(l("cli.commands.memory_notes_0_1",`
128
+ Memory notes: {0} ({1})`,n.length,xt.relative(e,yt(e))))}async function ys(e){let t=await rt(process.cwd(),e.join(" "));console.log(t.added?`Added skill: ${t.skill}
129
+ It will be used on the next run.`:`Already a skill: ${t.skill}`)}var bi=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);async function bs(e,t){let n=process.cwd(),[o,s]=[await qe(n),await Pe(n)];if(!o.length&&!s.length)throw new Error(l("cli.commands.nothing_to_push_0_skills",'nothing to push: {0}/skills.md and memory.md have no bullets. Run `{1} skills add "..."` first.',_.dirName,_.bin));let r=await X("/v1/taste",{method:"POST",body:JSON.stringify({name:bi(e??xt.basename(n)),description:t.description??"",skills:o,memory:s,isPublic:!t.private})});console.log(l("cli.commands.0_1_2_skill_s","{0} {1} ({2} skill(s), {3} memory note(s), {4}).",r.created?"Published":"Updated",r.slug,r.rules,r.memoryNotes,r.isPublic?"public":"private")),console.log(l("cli.commands.teammates_can_run_0_taste","Teammates can run: {0} taste pull {1}",_.bin,r.slug))}async function xs(e){let t=process.cwd();if(!/^[\w.-]+\/[\w.-]+$/.test(e))throw new Error(l("cli.commands.expected_namespace_name_e_g","expected <namespace>/<name>, e.g. {0} taste pull acme/frontend",_.bin));let n=await X(`/v1/taste/${e}`);await Nn(t);let o=0,s=0;for(let a of n.skills)(await rt(t,a)).added&&(o++,console.log(l("cli.commands.skill_0"," + skill: {0}",a)));let r=new Set((await Pe(t)).map(Ce));for(let a of n.memory)r.has(Ce(a))||(await wt(t,a),s++,console.log(l("cli.commands.memory_0"," + memory: {0}",a)));console.log(l("cli.commands.pulled_0_1_new_skill","Pulled {0}: {1} new skill(s), {2} new memory note(s) ({3} skill(s) already present).",n.slug,o,s,n.rules-o))}async function ks(e){let t=await X(`/v1/taste${e?`?q=${encodeURIComponent(e)}`:""}`,{auth:!1});if(!t.data.length)return console.log(l("cli.commands.no_taste_packages_found","No taste packages found."));for(let n of t.data)console.log(l("cli.commands.0_1_rules_2_pulls","{0} {1} rules {2} pulls {3}",n.slug.padEnd(36),String(n.rules).padStart(3),String(n.downloads).padStart(5),n.description))}async function $s(){let e=process.cwd(),t=await bt(e,Ne.homedir()),n=Object.keys(t.servers);if(!n.length)return console.log(l("cli.commands.no_mcp_servers_configured_add","No MCP servers configured. Add one: {0} mcp add fs npx -y @modelcontextprotocol/server-filesystem .",_.bin));t.untrusted.length&&console.log(l("cli.commands.not_started_untrusted_project_servers",`Not started (untrusted project servers: {0}). Review {1}/mcp.json, then run: {2} mcp trust
130
+ `,t.untrusted.join(", "),_.dirName,_.bin));let o=await at.fromConfig(t,e);try{for(let s of n){let r=o.errors.get(s),a=o.tools.filter(c=>c.server===s);console.log(r?`\u2717 ${s} ${r}`:`\u2713 ${s} ${a.length} tool(s)`);for(let c of a)console.log(` ${c.fullName} ${c.description.split(`
131
+ `)[0].slice(0,80)}`)}}finally{o.close()}}async function vs(e,t){if(!/^[\w-]+$/.test(e))throw new Error(l("cli.commands.server_name_may_only_contain","server name may only contain letters, digits, _ and -"));if(!t.length)throw new Error(l("cli.commands.give_a_command_e_g","give a command (e.g. npx -y @modelcontextprotocol/server-filesystem .) or an https:// URL"));let n=await Yt(process.cwd());n.servers[e]=/^https?:\/\//.test(t[0])?{url:t[0]}:{command:t[0],args:t.slice(1)};let o=await Fn(process.cwd(),n);await Kt(process.cwd(),Ne.homedir()),console.log(l("cli.commands.saved_0_to_1_check",'Saved "{0}" to {1}. Check it: {2} mcp list',e,xt.relative(process.cwd(),o),_.bin))}async function Ss(e){let t=await Yt(process.cwd());if(!(e in t.servers))throw new Error(l("cli.commands.no_mcp_server_0_in",'no MCP server "{0}" in {1}/mcp.json',e,_.dirName));delete t.servers[e],await Fn(process.cwd(),t),await Kt(process.cwd(),Ne.homedir()),console.log(l("cli.commands.removed_0",'Removed "{0}".',e))}async function Ts(){let e=await Yt(process.cwd()),t=Object.keys(e.servers);if(!t.length)return console.log(l("cli.commands.no_project_mcp_servers_in","No project MCP servers in {0}/mcp.json.",_.dirName));for(let[n,o]of Object.entries(e.servers))console.log(` ${n}: ${o.url??[o.command,...o.args??[]].join(" ")}`);await Kt(process.cwd(),Ne.homedir()),console.log(l("cli.commands.trusted_0_server_s_they","Trusted {0} server(s). They start on the next run until the file changes.",t.length))}var Rs=(e,t=" ")=>{for(let n of["PreToolUse","PostToolUse"])for(let o of e[n])console.log(`${t}${n} [${o.matcher??"*"}]: ${o.command}`)};async function Es(){let e=await _t(process.cwd(),Ne.homedir());if(!Be(e)&&!e.untrusted.length)return console.log(l("cli.commands.no_hooks_configured_add_them","No hooks configured. Add them to {0}/hooks.json (project) or ~/{1}/hooks.json (user).",_.dirName,_.dirName));if(Be(e)&&(console.log(l("cli.commands.effective_hooks","Effective hooks:")),Rs(e)),e.untrusted.length){console.log(l("cli.commands.not_run_untrusted_project_hooks",`
132
+ Not run (untrusted project hooks in {0}/hooks.json); review, then run: {1} hooks trust`,_.dirName,_.bin));for(let t of e.untrusted)console.log(` [${t.matcher??"*"}]: ${t.command}`)}}async function Ms(){let e=await Bt(process.cwd());if(!Be(e))return console.log(l("cli.commands.no_project_hooks_in_0","No project hooks in {0}/hooks.json.",_.dirName));Rs(e),await Lo(process.cwd(),Ne.homedir()),console.log(l("cli.commands.trusted_0_hook_s_they","Trusted {0} hook(s). They run until the file changes.",Be(e)))}async function ln(){let e=await oe(),t=process.cwd(),n=u=>console.log(` \x1B[32m\u2713\x1B[0m ${u}`),o=(u,g)=>console.log(` \x1B[31m\u2717\x1B[0m ${u}${g?`
133
+ \u2192 ${g}`:""}`);console.log(l("cli.commands.0_doctor",`
134
+ {0} doctor
135
+ `,_.name));let s=Number(process.versions.node.split(".")[0]);(s>=18?n:o)(`node ${process.versions.node}`,s>=18?void 0:"use Node 18 or newer");let r=await new Promise(u=>_s("git",["--version"],(g,h)=>u(g?null:String(h).trim())));if(r?n(r):o("git not found","install git (the Changes/review features need it)"),(r?await new Promise(u=>_s("git",["rev-parse","--is-inside-work-tree"],{cwd:t},g=>u(!g))):!1)?n("inside a git repository"):console.log(l("cli.commands.not_inside_a_git_repository"," - not inside a git repository (optional)")),e.token)try{let u=await X("/v1/me");n(`logged in as ${u.email??"user"}`)}catch(u){o(`connection error: ${je(u)}`,`run \`${_.bin} login\` again`)}else o("not logged in",`run \`${_.bin} login\` (or set FORGE_API_KEY)`);let c=await bt(t,Ne.homedir());console.log(l("cli.commands.0_mcp_server_s_configured"," - {0} MCP server(s) configured{1}",Object.keys(c.servers).length,c.untrusted.length?`, ${c.untrusted.length} untrusted (run \`${_.bin} mcp trust\`)`:""));let d=await _t(t,Ne.homedir());console.log(l("cli.commands.0_hook_s_active_1"," - {0} hook(s) active{1}",Be(d),d.untrusted.length?`, ${d.untrusted.length} untrusted (run \`${_.bin} hooks trust\`)`:"")),console.log("")}import vt from"fs/promises";import Xn from"os";import{execFile as Ei}from"child_process";import dt from"readline/promises";import{StringDecoder as Mi}from"string_decoder";import Ie from"path";import Cs from"crypto";import kt from"fs/promises";import ct from"os";import cn from"path";var xi=/^[A-Za-z0-9_-]{6,64}$/,ki=e=>Cs.createHash("sha256").update(cn.resolve(e)).digest("hex").slice(0,16),Ps=(e,t=ct.homedir())=>cn.join(t,_.dirName,"sessions",ki(e)),dn=(e,t,n=ct.homedir())=>{if(!xi.test(t))throw new Error(l("cli.sessions.invalid_session_id","invalid session id"));return cn.join(Ps(e,n),`${t}.json`)},un=()=>Cs.randomUUID().replace(/-/g,"").slice(0,12);function $t(e){let n=(e.find(o=>o.role==="user")?.content??"").replace(/<file[\s\S]*$/m,"").replace(/\s+/g," ").trim();return n.length>60?n.slice(0,59)+"\u2026":n||"Untitled session"}async function As(e,t,n=ct.homedir()){let o=dn(e,t.id,n);await kt.mkdir(cn.dirname(o),{recursive:!0});let s=`${o}.${process.pid}.tmp`;return await kt.writeFile(s,JSON.stringify(t),{mode:384}),await kt.rename(s,o),o}async function js(e,t,n=ct.homedir()){try{return JSON.parse(await kt.readFile(dn(e,t,n),"utf8"))}catch(o){if(o?.code==="ENOENT"||o instanceof SyntaxError)return null;throw o}}async function Yn(e,t=ct.homedir()){let n;try{n=await kt.readdir(Ps(e,t))}catch{return[]}let o=[];for(let s of n){if(!s.endsWith(".json"))continue;let r=await js(e,s.slice(0,-5),t);r&&o.push({id:r.id,title:r.title,model:r.model,createdAt:r.createdAt,updatedAt:r.updatedAt,turns:r.messages.filter(a=>a.role==="user").length})}return o.sort((s,r)=>r.updatedAt-s.updatedAt)}async function Vn(e,t,n=ct.homedir()){let o=await Yn(e,n);if(!o.length)return null;let s=t===void 0||t===!0||t==="latest"?o[0]:o.find(r=>r.id===t)??(o.filter(r=>r.id.startsWith(String(t))).length===1?o.find(r=>r.id.startsWith(String(t))):void 0);return s?js(e,s.id,n):null}var mn=e=>e.flatMap((t,n)=>t.role==="user"?[n]:[]),pn=(e,t=Date.now())=>{let n=Math.max(0,Math.round((t-e)/1e3));return n<60?`${n}s ago`:n<3600?`${Math.round(n/60)}m ago`:n<86400?`${Math.round(n/3600)}h ago`:`${Math.round(n/86400)}d ago`};import $i from"fs";import vi from"os";import Ns from"path";function Si(e){let t={};for(let n of e.split(/\r?\n/)){let o=n.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);if(!o||o[1].startsWith("#"))continue;let s=o[2];/^(["']).*\1$/.test(s)?s=s.slice(1,-1):s=s.replace(/\s+#.*$/,""),s!==""&&(t[o[1]]=s)}return t}var Ti=new Set(["FORGE_API_KEY","FORGE_API_URL"]),Ri=new Set(["FORGE_API_URL"]);function Is(e=process.cwd()){let t=Ns.join(vi.homedir(),_.dirName,".env");for(let n of[Ns.join(e,".env"),t]){let o;try{o=$i.readFileSync(n,"utf8")}catch{continue}for(let[s,r]of Object.entries(Si(o)))Ri.has(s)&&n!==t||Ti.has(s)&&process.env[s]===void 0&&(process.env[s]=r)}}var $=e=>`\x1B[2m${e}\x1B[0m`,Os=(e,t=200)=>(e.length>t?e.slice(0,t)+"\u2026":e).replace(/\n/g,"\u23CE ");function Ci(e){e.type==="token"?process.stdout.write(e.text):e.type==="assistant"?console.log(`
136
+ ${i.assistantPrefix}\u25C6${i.reset} ${e.text}
137
+ `):e.type==="tool_start"?console.log(`${i.userPointer}\u2692${i.reset} ${i.bold}${e.name.replace(/_/g," ")}${i.reset} ${$(Os(JSON.stringify(e.args),120))}`):e.type==="tool_result"?console.log($(` ${e.ok?"\u2713":"\u2717"} ${Os(e.output,160)}`)):e.type==="repair"?console.log($(` \u21BA repaired ${e.name} call (${e.via})`)):e.type==="denied"?console.log($(" \u2717 denied")):e.type==="hook_warning"?console.error(`\x1B[33m \u26A0 ${e.message}\x1B[0m`):e.type==="context_warning"?console.error(l("cli.run.large_context_0_tokens_per","\x1B[33m\u26A0 large context: ~{0} tokens per request. Long contexts cost more; consider a fresh session or narrower @mentions.\x1B[0m",e.tokens.toLocaleString())):e.type==="escalate"&&console.log(l("cli.run.escalating_0_1_2","\x1B[33m\u2191 escalating {0} \u2192 {1}: {2}\x1B[0m",e.from,e.to,e.reason))}var Pi=e=>console.error($(` \u21BB ${e.status?`server returned ${e.status}`:"connection problem"}; retrying in ${(e.delayMs/1e3).toFixed(1)}s\u2026`));async function Zn(e){Is();let t=await oe(),n=e.model==="mock-model"||e.model==="mock";if(!!t.token){let s=e.model??t.defaultModel??"default";try{wn(await X("/v1/models"))}catch{}if(!e.model)try{let r=await X("/v1/models"),a=r.data.map(d=>d.id),c=typeof r.default=="string"&&a.includes(r.default)?r.default:null;if(!t.defaultModel&&c&&(s=c),a.length>0&&!a.includes(s)){let d=c||a[0];console.error($(`model "${s}" is not available on this server; switching to "${d}".`)),s=d,await ze({defaultModel:d})}}catch{}return{client:new qt({baseUrl:`${t.apiUrl.replace(/\/$/,"")}/v1`,apiKey:t.token,onRetry:Pi}),model:s,label:"gateway",apiUrl:t.apiUrl}}if(n)return{client:new We,model:"mock-model",label:"local mock"};if(!t.token){if(e.prompt)throw new ne(401,"Not logged in \u2014 run `forge login` to authenticate.",{});return{client:{chat:async()=>{throw new ne(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},model:e.model??t.defaultModel??"default",label:"not logged in",apiUrl:t.apiUrl}}throw new Error(l("cli.run.no_backend_available","Not logged in. Run `{0} login` to get started.",_.bin))}async function Qn(e,t,n){let o=e.escalateTo??process.env.FORGE_ESCALATION_MODEL;if(o)return o;if(t!=="gateway")return null;let r=(await X("/v1/models")).data.filter(a=>a.provider!=="mock"&&a.id!==n);return r.sort((a,c)=>c.multiplier-a.multiplier),r[0]?.id??null}function Ls(e,t,n){return async o=>{if(!process.stdin.isTTY)return console.error($(` (not a terminal) refusing: ${o.reason} \u2014 rerun with --yolo to auto-approve`)),!1;t?.();let s=e??dt.createInterface({input:process.stdin,output:process.stdout}),r=(await s.question(`
138
138
  ? Allow ${o.reason}
139
- [y]es / [n]o / [a]lways for ${o.name} this run: `)).trim().toLowerCase();return t||s.close(),n?.(),r==="a"||r==="always"?"always":r==="y"||r==="yes"}}async function Os(t,e){if(!process.stdin.isTTY)return;let n=e??at.createInterface({input:process.stdin,output:process.stdout});try{if(!(await n.question(`
140
- Save a learning to memory? (y/n) `)).trim().toLowerCase().startsWith("y"))return;let o=(await n.question("Learning (one short line): ")).trim();if(!o)return;let s=await ft(t,o);console.log(l("cli.run.saved_to_0","Saved to {0}",je.relative(t,s)))}finally{e||n.close()}}async function Mi(t,e,n){if(!n||!process.stdin.isTTY)return!1;let o=t??at.createInterface({input:process.stdin,output:process.stdout});try{let s=n.reason==="repeated"?"You've corrected this more than once":"That sounds like a standing rule",r=(await o.question(`
139
+ [y]es / [n]o / [a]lways for ${o.name} this run: `)).trim().toLowerCase();return e||s.close(),n?.(),r==="a"||r==="always"?"always":r==="y"||r==="yes"}}async function Fs(e,t){if(!process.stdin.isTTY)return;let n=t??dt.createInterface({input:process.stdin,output:process.stdout});try{if(!(await n.question(`
140
+ Save a learning to memory? (y/n) `)).trim().toLowerCase().startsWith("y"))return;let o=(await n.question("Learning (one short line): ")).trim();if(!o)return;let s=await wt(e,o);console.log(l("cli.run.saved_to_0","Saved to {0}",Ie.relative(e,s)))}finally{t||n.close()}}async function Ai(e,t,n){if(!n||!process.stdin.isTTY)return!1;let o=e??dt.createInterface({input:process.stdin,output:process.stdout});try{let s=n.reason==="repeated"?"You've corrected this more than once":"That sounds like a standing rule",r=(await o.question(`
141
141
  ${s}. Save as a project skill?
142
142
  \u201C${n.rule}\u201D
143
- [y]es / [n]o / [e]dit: `)).trim().toLowerCase(),a=n.rule;if(r.startsWith("e"))a=(await o.question("Skill text: ")).trim();else if(!r.startsWith("y"))return!1;if(!a)return!1;try{let c=await nt(e,a);return console.log(c.added?`Saved to ${je.relative(e,c.file)} \u2014 applies from your next message.`:"Already saved."),c.added}catch(c){return console.error(l("cli.run.could_not_save_0","could not save: {0}",c instanceof Error?c.message:c)),!1}}finally{t||o.close()}}async function Zn(t){if(t.effort&&!["low","high"].includes(t.effort))throw new Error(l("cli.run.effort_must_be_low_or",'--effort must be "low" or "high", not "{0}"',t.effort));let e=process.cwd();await _o(e);let{client:n,model:o,label:s,apiUrl:r}=await Vn(t);if(t.outputFormat&&!["text","json","stream-json"].includes(t.outputFormat))throw new Error(l("cli.run.output_format_must_be_text",'--output-format must be text, json or stream-json, not "{0}"',t.outputFormat));let a=t.outputFormat==="json"||t.outputFormat==="stream-json",c=a?console.error:console.log,d=async()=>await Ro(e,Yn.homedir())+(t.appendSystemPrompt?`
143
+ [y]es / [n]o / [e]dit: `)).trim().toLowerCase(),a=n.rule;if(r.startsWith("e"))a=(await o.question("Skill text: ")).trim();else if(!r.startsWith("y"))return!1;if(!a)return!1;try{let c=await rt(t,a);return console.log(c.added?`Saved to ${Ie.relative(t,c.file)} \u2014 applies from your next message.`:"Already saved."),c.added}catch(c){return console.error(l("cli.run.could_not_save_0","could not save: {0}",c instanceof Error?c.message:c)),!1}}finally{e||o.close()}}async function eo(e){if(e.effort&&!["low","high"].includes(e.effort))throw new Error(l("cli.run.effort_must_be_low_or",'--effort must be "low" or "high", not "{0}"',e.effort));let t=process.cwd();await yo(t);let{client:n,model:o,label:s,apiUrl:r}=await Zn(e);if(e.outputFormat&&!["text","json","stream-json"].includes(e.outputFormat))throw new Error(l("cli.run.output_format_must_be_text",'--output-format must be text, json or stream-json, not "{0}"',e.outputFormat));let a=e.outputFormat==="json"||e.outputFormat==="stream-json",c=a?console.error:console.log,d=async()=>await Mo(t,Xn.homedir())+(e.appendSystemPrompt?`
144
144
 
145
- ${t.appendSystemPrompt}`:""),u=[{role:"system",content:await d()}],g={root:e,allowAll:t.allowAll},_=t.maxSteps??0,R=t.maxTokens??0,v=null;(t.cascade||t.effort==="high"&&!t.model)&&(v=await Xn(t,s,o),(!v||v===o)&&(console.error($(`no stronger model available${s==="gateway"?" on your plan":" (pass --escalate-to <id>)"}; using ${o}.`)),v=null));let W=t.effort==="high"&&!t.model&&v?v:o,Z=await _t(e,Yn.homedir());Z.untrusted.length&&console.error($(`mcp: ${Z.untrusted.length} project server(s) in ${h.dirName}/mcp.json not started (untrusted). Review the file, then run \`${h.bin} mcp trust\`.`));let I=await st.fromConfig(Z,e);process.on("exit",()=>I.close());for(let[S,p]of I.errors)console.error($(`mcp: server "${S}" unavailable: ${p}`));I.tools.length&&c($(`mcp: ${I.tools.length} tool(s) from ${I.serverCount} server(s) (each call asks for approval)`));let be=await gt(e,Yn.homedir());be.untrusted.length&&console.error($(`hooks: ${be.untrusted.length} project hook(s) in ${h.dirName}/hooks.json not run (untrusted). Review the file, then run \`${h.bin} hooks trust\`.`));let re=!!t.plan,lt=await Ue(e),kt=(await Me(e)).length,qs=new Wt(lt),Oi=Is(null),he=0,de=on(),Ne,$t=Date.now(),vt=W,ct=async()=>{u.length<=1||await xs(e,{id:de,title:Ne??bt(u.slice(1)),model:vt,createdAt:$t,updatedAt:Date.now(),messages:u.slice(1)}).catch(()=>{})},eo=async S=>{let p=at.createInterface({input:process.stdin,output:process.stdout});try{return(await p.question(S)).trim()}finally{p.close()}},to=S=>{u.length=1,u.push(...S.messages),de=S.id,Ne=S.title,$t=S.createdAt,he=S.messages.filter(p=>p.role==="user").length},no=async()=>{let S=(await Dn(e)).filter(z=>z.id!==de).slice(0,15);if(!S.length)return console.log($(`
145
+ ${e.appendSystemPrompt}`:""),u=[{role:"system",content:await d()}],g={root:t,allowAll:e.allowAll},h=e.maxSteps??0,R=e.maxTokens??0,v=null;(e.cascade||e.effort==="high"&&!e.model)&&(v=await Qn(e,s,o),(!v||v===o)&&(console.error($(`no stronger model available${s==="gateway"?" on your plan":" (pass --escalate-to <id>)"}; using ${o}.`)),v=null));let W=e.effort==="high"&&!e.model&&v?v:o,Z=await bt(t,Xn.homedir());Z.untrusted.length&&console.error($(`mcp: ${Z.untrusted.length} project server(s) in ${_.dirName}/mcp.json not started (untrusted). Review the file, then run \`${_.bin} mcp trust\`.`));let I=await at.fromConfig(Z,t);process.on("exit",()=>I.close());for(let[S,p]of I.errors)console.error($(`mcp: server "${S}" unavailable: ${p}`));I.tools.length&&c($(`mcp: ${I.tools.length} tool(s) from ${I.serverCount} server(s) (each call asks for approval)`));let ke=await _t(t,Xn.homedir());ke.untrusted.length&&console.error($(`hooks: ${ke.untrusted.length} project hook(s) in ${_.dirName}/hooks.json not run (untrusted). Review the file, then run \`${_.bin} hooks trust\`.`));let se=!!e.plan,ut=await qe(t),St=(await Pe(t)).length,zs=new zt(ut),Li=Ls(null),he=0,ce=un(),Oe,Tt=Date.now(),Rt=W,mt=async()=>{u.length<=1||await As(t,{id:ce,title:Oe??$t(u.slice(1)),model:Rt,createdAt:Tt,updatedAt:Date.now(),messages:u.slice(1)}).catch(()=>{})},no=async S=>{let p=dt.createInterface({input:process.stdin,output:process.stdout});try{return(await p.question(S)).trim()}finally{p.close()}},oo=S=>{u.length=1,u.push(...S.messages),ce=S.id,Oe=S.title,Tt=S.createdAt,he=S.messages.filter(p=>p.role==="user").length},so=async()=>{let S=(await Yn(t)).filter(z=>z.id!==ce).slice(0,15);if(!S.length)return console.log($(`
146
146
  No previous sessions for this project.
147
147
  `)),null;console.log(l("cli.run.0_sessions_for_this_project",`
148
- {0}Sessions for this project:{1}`,i.bold,i.reset)),S.forEach((z,J)=>console.log(` ${String(J+1).padStart(2)}. ${z.title} ${$(`${z.turns} turn(s) \xB7 ${z.model} \xB7 ${rn(z.updatedAt)} \xB7 ${z.id}`)}`));let p=Number.parseInt(await eo(`
149
- Resume which? (number, Enter to cancel): `),10);return p>=1&&p<=S.length?S[p-1].id:null};if(t.continue||t.resume){let S=t.resume===!0&&process.stdin.isTTY?await no()??void 0:t.resume===!0?void 0:t.resume,p=t.resume===!0&&!S?null:await Un(e,S);p?(to(p),console.error($(`resumed "${p.title}" (${p.messages.filter(z=>z.role==="user").length} turn(s), ${rn(p.updatedAt)})`))):console.error($(t.continue||t.resume!==!0?"no matching previous session; starting fresh.":"starting fresh."))}let _e=null,oo=async()=>{if(_e)return _e;if(_e=new Map,s==="gateway")try{for(let S of(await X("/v1/models")).data)_e.set(S.id,!!S.vision)}catch{}return _e},so=async S=>(await oo()).get(S)??!1,we=[],ro=0,Hs=15e3,un=async()=>{if(we.length>0&&Date.now()-ro<Hs)return we;try{if((await oe()).token){let J=await X("/v1/models");if(Array.isArray(J.data)&&J.data.length>0)return we=J.data.map(m=>({id:m.id,provider:m.provider,multiplier:m.multiplier,vision:m.vision,description:`${m.multiplier?`${m.multiplier}x`:""}${m.vision?" \xB7 images":""}`})),ro=Date.now(),_e=null,we}}catch{}let S=[],p=[{id:"mock-model",provider:"mock",description:"offline test mock"}];for(let z of p)S.some(J=>J.id===z.id)||S.push(z);return we=S,we},St={queue:[],draft:""},Tt=async(S,p=W,z=re)=>{let J=Ae.splice(0),m=await ns(e,J.length?`${S} ${J.map(y=>`"${y}"`).join(" ")}`:S);for(let y of m.errors)console.error(`\x1B[33m\u26A0 ${y}\x1B[0m`);let w=m.images,b="";if(w.length)if(await so(p))c($(`\u{1F4CE} ${w.map((y,D)=>`#${D+1} ${y.name} (${Math.round(y.data.length*.75/1024)} KB)`).join(", ")}`));else{let y=[...await oo()].filter(([,D])=>D).map(([D])=>D).slice(0,5);console.error(l("cli.run.0_can_t_read_images","\x1B[33m\u26A0 {0} can't read images, so {1} image(s) were not sent.{2}\x1B[0m",p,w.length,y.length?` Try: /model ${y[0]} (vision models: ${y.join(", ")})`:" Switch to a vision-capable model with /model <id>.")),b=`
150
- (${w.length} image(s) were attached, but this model cannot view images.)`,w=[]}u.push({role:"user",content:await Eo(e,m.text+b),...w.length?{images:w}:{}});let F=new AbortController,C=new ln(()=>{F.abort()},St),U=y=>{if(a){t.outputFormat==="stream-json"&&console.log(JSON.stringify(y));return}if(y.type!=="token"){if(C.clear(),y.type==="tool_start"){let D=y.name==="run_shell"?"Running command":y.name==="read_file"||y.name==="list_dir"?"Reading files":y.name==="edit_file"||y.name==="write_file"?"Editing file":y.name.replace(/_/g," ");C.setStatus(`${D}\u2026`)}else y.type==="tool_result"&&C.setStatus(an());Ri(y),C.draw()}},f=Is(null,()=>C.suspend(),()=>C.resume());try{!t.prompt&&process.stdout.isTTY&&C.start();let y={messages:u,ctx:g,yolo:t.yolo,approve:f,onEvent:U,maxSteps:_,maxRunTokens:R,signal:F.signal,mcp:I,hooks:be,plan:z,stream:t.outputFormat==="stream-json"},D=t.verify?async()=>{let ee=await Ye("run_shell",{command:t.verify},g).catch(pn=>`exit code: 1
151
- ${pn.message}`);return{ok:/^exit code: 0\b/.test(ee),detail:ee.split(`
152
- `).slice(1).join(" ").trim()}}:void 0,xe=p==="mock-model"&&s!=="gateway"?new De:n,x=t.cascade&&v&&t.effort!=="high"?await Yo({...y,cheap:{client:xe,model:p},strong:{client:n,model:v},verify:D}):await Qe({...y,client:xe,model:p});C.stop();let E=C.getElapsedSec();if(x.stopReason==="interrupted")return console.log(l("cli.run.0_1_esc_2_3",`
148
+ {0}Sessions for this project:{1}`,i.bold,i.reset)),S.forEach((z,J)=>console.log(` ${String(J+1).padStart(2)}. ${z.title} ${$(`${z.turns} turn(s) \xB7 ${z.model} \xB7 ${pn(z.updatedAt)} \xB7 ${z.id}`)}`));let p=Number.parseInt(await no(`
149
+ Resume which? (number, Enter to cancel): `),10);return p>=1&&p<=S.length?S[p-1].id:null};if(e.continue||e.resume){let S=e.resume===!0&&process.stdin.isTTY?await so()??void 0:e.resume===!0?void 0:e.resume,p=e.resume===!0&&!S?null:await Vn(t,S);p?(oo(p),console.error($(`resumed "${p.title}" (${p.messages.filter(z=>z.role==="user").length} turn(s), ${pn(p.updatedAt)})`))):console.error($(e.continue||e.resume!==!0?"no matching previous session; starting fresh.":"starting fresh."))}let _e=null,ro=async()=>{if(_e)return _e;if(_e=new Map,s==="gateway")try{for(let S of(await X("/v1/models")).data)_e.set(S.id,!!S.vision)}catch{}return _e},io=async S=>(await ro()).get(S)??!1,we=[],ao=0,Js=15e3,fn=async()=>{if(we.length>0&&Date.now()-ao<Js)return we;try{if((await oe()).token){let J=await X("/v1/models");if(Array.isArray(J.data)&&J.data.length>0)return we=J.data.map(m=>({id:m.id,provider:m.provider,multiplier:m.multiplier,vision:m.vision,description:`${m.multiplier?`${m.multiplier}x`:""}${m.vision?" \xB7 images":""}`})),ao=Date.now(),_e=null,we}}catch{}let S=[],p=[{id:"mock-model",provider:"mock",description:"offline test mock"}];for(let z of p)S.some(J=>J.id===z.id)||S.push(z);return we=S,we},Et={queue:[],draft:""},Mt=async(S,p=W,z=se)=>{let J=Ae.splice(0),m=await ss(t,J.length?`${S} ${J.map(y=>`"${y}"`).join(" ")}`:S);for(let y of m.errors)console.error(`\x1B[33m\u26A0 ${y}\x1B[0m`);let w=m.images,b="";if(w.length)if(await io(p))c($(`\u{1F4CE} ${w.map((y,D)=>`#${D+1} ${y.name} (${Math.round(y.data.length*.75/1024)} KB)`).join(", ")}`));else{let y=[...await ro()].filter(([,D])=>D).map(([D])=>D).slice(0,5);console.error(l("cli.run.0_can_t_read_images","\x1B[33m\u26A0 {0} can't read images, so {1} image(s) were not sent.{2}\x1B[0m",p,w.length,y.length?` Try: /model ${y[0]} (vision models: ${y.join(", ")})`:" Switch to a vision-capable model with /model <id>.")),b=`
150
+ (${w.length} image(s) were attached, but this model cannot view images.)`,w=[]}u.push({role:"user",content:await Co(t,m.text+b),...w.length?{images:w}:{}});let F=new AbortController,C=new Qt(()=>{F.abort()},Et),U=y=>{if(a){e.outputFormat==="stream-json"&&console.log(JSON.stringify(y));return}if(y.type!=="token"){if(C.clear(),y.type==="tool_start"){let D=y.name==="run_shell"?"Running command":y.name==="read_file"||y.name==="list_dir"?"Reading files":y.name==="edit_file"||y.name==="write_file"?"Editing file":y.name.replace(/_/g," ");C.setStatus(`${D}\u2026`)}else y.type==="tool_result"&&C.setStatus(Zt());Ci(y),C.draw()}},f=Ls(null,()=>C.suspend(),()=>C.resume());try{!e.prompt&&process.stdout.isTTY&&C.start();let y={messages:u,ctx:g,yolo:e.yolo,approve:f,onEvent:U,maxSteps:h,maxRunTokens:R,signal:F.signal,mcp:I,hooks:ke,plan:z,stream:e.outputFormat==="stream-json"},D=e.verify?async()=>{let de=await Ze("run_shell",{command:e.verify},g).catch(Le=>`exit code: 1
151
+ ${Le.message}`);return{ok:/^exit code: 0\b/.test(de),detail:de.split(`
152
+ `).slice(1).join(" ").trim()}}:void 0,$e=p==="mock-model"&&s!=="gateway"?new We:n,x=e.cascade&&v&&e.effort!=="high"?await Xo({...y,cheap:{client:$e,model:p},strong:{client:n,model:v},verify:D}):await nt({...y,client:$e,model:p});C.stop();let E=C.getElapsedSec();if(x.stopReason==="interrupted")return console.log(l("cli.run.0_1_esc_2_3",`
153
153
  {0}{1}esc{2} {3}Interrupted by user{4}
154
- `,i.bold,i.gray,i.reset,i.dim,i.reset)),!1;if(a){let ee=x.stopReason==="done"&&x.toolErrors===0;return console.log(JSON.stringify({type:"result",ok:ee,stopReason:x.stopReason,result:x.finalText,model:p,sessionId:de,usage:x.usage,changedFiles:x.changedFiles})),ee||(process.exitCode=1),ee}let G=x.changedFiles.length?` \xB7 changed: ${x.changedFiles.join(", ")}`:"",te=x.cachedReads?` \xB7 ${x.cachedReads} repeat read(s) skipped`:"",ae="finalModel"in x&&x.escalated?`${p} \u2192 ${x.finalModel}`:p;console.log(l("cli.run.0_worked_for_1_s",`
154
+ `,i.bold,i.gray,i.reset,i.dim,i.reset)),!1;if(a){let de=x.stopReason==="done"&&x.toolErrors===0;return console.log(JSON.stringify({type:"result",ok:de,stopReason:x.stopReason,result:x.finalText,model:p,sessionId:ce,usage:x.usage,changedFiles:x.changedFiles})),de||(process.exitCode=1),de}let G=x.changedFiles.length?` \xB7 changed: ${x.changedFiles.join(", ")}`:"",te=x.cachedReads?` \xB7 ${x.cachedReads} repeat read(s) skipped`:"",ie="finalModel"in x&&x.escalated?`${p} \u2192 ${x.finalModel}`:p,pt=(x.usage?.promptTokens??0)+(x.usage?.completionTokens??0),ye=en(pt),_n=`${$(`[${ie}]`)} ${i.tokenBlue}${ye}${i.reset}${$(`${G}${te}`)}`;console.log(l("cli.run.0_worked_for_1_s",`
155
155
  {0}\u2713 Done in {1}s{2}
156
- {3}`,i.workedPrefix,E,i.reset,$(`[${ae}] ${x.usage.promptTokens} in / ${x.usage.completionTokens} out${G}${te}`)));let ze=Do(x,R);return ze&&console.log(`\x1B[33m${ze}\x1B[0m`),x.stopReason==="done"&&x.toolErrors===0}catch(y){return C.stop(),F.signal.aborted?(console.log(l("cli.run.0_1_esc_2_3_2",`
156
+ {3}`,i.workedPrefix,E,i.reset,_n));let Ke=Bo(x,R);return Ke&&console.log(`\x1B[33m${Ke}\x1B[0m`),x.stopReason==="done"&&x.toolErrors===0}catch(y){return C.stop(),F.signal.aborted?(console.log(l("cli.run.0_1_esc_2_3_2",`
157
157
  {0}{1}esc{2} {3}Interrupted by user{4}
158
- `,i.bold,i.gray,i.reset,i.dim,i.reset)),!1):(a?console.log(JSON.stringify({type:"result",ok:!1,error:Ce(y,r),sessionId:de})):console.error(l("cli.run.error_0",`
158
+ `,i.bold,i.gray,i.reset,i.dim,i.reset)),!1):(a?console.log(JSON.stringify({type:"result",ok:!1,error:je(y,r),sessionId:ce})):console.error(l("cli.run.error_0",`
159
159
  error: {0}
160
- `,Ce(y,r))),process.exitCode=1,!1)}finally{C.stop(),vt=p,await ct()}};(lt.length||kt)&&c($(`using ${lt.length} skill(s) and ${kt} memory note(s) from ${h.dirName}/`));async function zs(S,p){if(!!!(process.stdin.isTTY&&process.stdout.isTTY)){let J=at.createInterface({input:process.stdin,output:process.stdout});try{return(await J.question("\u203A ")).trim()}finally{J.close()}}return new Promise(J=>{let m="\x1B[2m",w="\x1B[0m",b="\x1B[38;2;255;179;71m",F=()=>Math.max(process.stdout.columns||80,20),C=()=>"\u2500".repeat(F()),U=()=>`? for shortcuts \xB7 ${b}taste on${w}${Ae.length?` \xB7 ${b}\u{1F4CE} ${Ae.length} image(s) attached${w}`:""}`,f=St.draft;St.draft="";let y=f.length,D=p.length,xe="",x=!1,E=0,G=0,te=2,ae=!1,ze=0;process.stdout.write(`\x1B[38;2;255;122;61m\u276F\x1B[0m ${m}Ask ${h.name} anything\u2026${w}
160
+ `,je(y,r))),process.exitCode=1,!1)}finally{C.stop(),Rt=p,await mt()}};(ut.length||St)&&c($(`using ${ut.length} skill(s) and ${St} memory note(s) from ${_.dirName}/`));async function Gs(S,p){if(!!!(process.stdin.isTTY&&process.stdout.isTTY)){let J=dt.createInterface({input:process.stdin,output:process.stdout});try{return(await J.question("\u203A ")).trim()}finally{J.close()}}return new Promise(J=>{let m="\x1B[2m",w="\x1B[0m",b="\x1B[38;2;255;179;71m",F=()=>Math.max(process.stdout.columns||80,20),C=()=>"\u2500".repeat(F()),U=()=>`? for shortcuts \xB7 ${b}taste on${w}${Ae.length?` \xB7 ${b}\u{1F4CE} ${Ae.length} image(s) attached${w}`:""}`,f=Et.draft;Et.draft="";let y=f.length,D=p.length,$e="",x=!1,E=0,G=0,te=2,ie=!1,pt=0;process.stdout.write(`\x1B[38;2;255;122;61m\u276F\x1B[0m ${m}Ask ${_.name} anything\u2026${w}
161
161
  `),process.stdout.write(`${m}${C()}${w}
162
- `),process.stdout.write(`${U()}`),process.stdout.write("\x1B[2A\x1B[3G"),f&&setImmediate(()=>j());let ee=process.stdin,pn=ee.isRaw;ee.setRawMode(!0),ee.resume();let gn=()=>{ee.removeListener("data",ao),process.stdout.removeListener("resize",io),ee.setRawMode&&ee.setRawMode(pn)},fn=ke=>{gn();for(let ie=0;ie<te;ie++)process.stdout.write(`
163
- \x1B[2K`);te>0&&process.stdout.write(`\x1B[${te}A`),process.stdout.write("\x1B[2K\r");let k=ke.trim();k&&!k.startsWith("/")&&k!=="?"&&process.stdout.write(`
162
+ `),process.stdout.write(`${U()}`),process.stdout.write("\x1B[2A\x1B[3G"),f&&setImmediate(()=>j());let ye=process.stdin,_n=ye.isRaw;ye.setRawMode(!0),ye.resume();let Ke=()=>{ye.removeListener("data",co),process.stdout.removeListener("resize",lo),ye.setRawMode&&ye.setRawMode(_n)},de=ve=>{Ke();for(let re=0;re<te;re++)process.stdout.write(`
163
+ \x1B[2K`);te>0&&process.stdout.write(`\x1B[${te}A`),process.stdout.write("\x1B[2K\r");let k=ve.trim();k&&!k.startsWith("/")&&k!=="?"&&process.stdout.write(`
164
164
  ${i.userMsgBg} ${i.userPointer}${i.bold}\u276F${i.reset}${i.userMsgBg} ${i.userFg}${k} ${i.reset}
165
165
 
166
- `),J(k)},dt=ke=>{let k=we.length>0?we:[{id:"mock-model",provider:"mock",description:"offline test mock"}],ie=ke.trim().toLowerCase();return k.filter(q=>ie?q.id.toLowerCase().includes(ie):!0).map(q=>{let O=q.id===A,B=O?`\u2713 ${q.id}`:q.id,Y=`${O?"(active) ":""}${q.description||"model"}`;return{command:`/model ${q.id}`,displayCommand:B,description:Y}})},j=()=>{let ke=F(),k=Math.max(10,ke-8),ie=f,P=fe(f.slice(0,y));if(!f)ie=`${m}Ask ${h.name} anything\u2026${w}`,P=0;else if(fe(f)>k){let V=qe(f),Je=qe(f.slice(0,y)).length,$e=0;for(;$e<Je&&fe(V.slice($e,Je).join(""))>=k;)$e++;let le="";for(let ue=$e;ue<V.length&&fe(le+V[ue])<=k;ue++)le+=V[ue];ie=le,P=fe(V.slice($e,Je).join(""))}let q=He(f),O=q.showMenu&&!x,B=O?it(q.query):[],Y=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x,Ie=Y?f.replace(/^\/model[:\s]*/,"").trim().toLowerCase():"",Et=Y?dt(Ie):[],ye=O&&B.length>0||Y&&Et.length>0,Q=Y?Et:B;Q.length>0&&(E>=Q.length&&(E=Math.max(0,Q.length-1)),E<0&&(E=0),E<G&&(G=E),E>=G+8&&(G=Math.max(0,E-8+1)));let K=[];if(ye&&Q.length>0){K.push(`\x1B[38;2;90;66;50m${C()}\x1B[0m`);let V=Q.slice(G,G+8),Je=Math.min(38,Math.max(...V.map(le=>fe(le.displayCommand??le.command)),18)),$e=Math.max(10,ke-Je-4);for(let le=0;le<V.length;le++){let ue=V[le],Ks=G+le===E,lo=(ue.displayCommand??ue.command).padEnd(Je),co=ue.description.length>$e?ue.description.slice(0,$e-1)+"\u2026":ue.description;Ks?K.push(`${i.accent}${i.bold}${lo}${i.reset} ${i.accent}${co}${i.reset}`):K.push(`${i.bannerText}${lo}${i.reset} ${i.gray}${co}${i.reset}`)}}else if(ae||f.trim()==="?"){K.push("");for(let V of Jn())K.push(V);K.push(""),K.push(`${m}${C()}${w}`),K.push(`${U()}`)}else K.push(`${m}${C()}${w}`),K.push(`${U()}`);process.stdout.write(`\x1B[1G\x1B[2K\x1B[38;2;255;122;61m\u276F\x1B[0m ${ie}`);for(let V of K)process.stdout.write(`
167
- \x1B[2K${V}`);let ut=Math.max(0,te-K.length);for(let V=0;V<ut;V++)process.stdout.write(`
168
- \x1B[2K`);let Mt=K.length+ut;Mt>0&&process.stdout.write(`\x1B[${Mt}A`),process.stdout.write(`\x1B[${3+P}G`),te=K.length},io=()=>{j()};process.stdout.on("resize",io);let Gs=new Ti("utf8"),ao=ke=>{let k=Gs.write(ke);if(!k)return;if(k==="\r"||k===`
166
+ `),J(k)},Le=ve=>{let k=we.length>0?we:[{id:"mock-model",provider:"mock",description:"offline test mock"}],re=ve.trim().toLowerCase();return k.filter(q=>re?q.id.toLowerCase().includes(re):!0).map(q=>{let O=q.id===A,B=O?`\u2713 ${q.id}`:q.id,Y=`${O?"(active) ":""}${q.description||"model"}`;return{command:`/model ${q.id}`,displayCommand:B,description:Y}})},j=()=>{let ve=F(),k=Math.max(10,ve-8),re=f,P=fe(f.slice(0,y));if(!f)re=`${m}Ask ${_.name} anything\u2026${w}`,P=0;else if(fe(f)>k){let V=Je(f),Ye=Je(f.slice(0,y)).length,Se=0;for(;Se<Ye&&fe(V.slice(Se,Ye).join(""))>=k;)Se++;let ae="";for(let ue=Se;ue<V.length&&fe(ae+V[ue])<=k;ue++)ae+=V[ue];re=ae,P=fe(V.slice(Se,Ye).join(""))}let q=Ge(f),O=q.showMenu&&!x,B=O?lt(q.query):[],Y=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x,Fe=Y?f.replace(/^\/model[:\s]*/,"").trim().toLowerCase():"",Pt=Y?Le(Fe):[],be=O&&B.length>0||Y&&Pt.length>0,Q=Y?Pt:B;Q.length>0&&(E>=Q.length&&(E=Math.max(0,Q.length-1)),E<0&&(E=0),E<G&&(G=E),E>=G+8&&(G=Math.max(0,E-8+1)));let K=[];if(be&&Q.length>0){K.push(`\x1B[38;2;90;66;50m${C()}\x1B[0m`);let V=Q.slice(G,G+8),Ye=Math.min(38,Math.max(...V.map(ae=>fe(ae.displayCommand??ae.command)),18)),Se=Math.max(10,ve-Ye-4);for(let ae=0;ae<V.length;ae++){let ue=V[ae],Vs=G+ae===E,uo=(ue.displayCommand??ue.command).padEnd(Ye),mo=ue.description.length>Se?ue.description.slice(0,Se-1)+"\u2026":ue.description;Vs?K.push(`${i.accent}${i.bold}${uo}${i.reset} ${i.accent}${mo}${i.reset}`):K.push(`${i.bannerText}${uo}${i.reset} ${i.gray}${mo}${i.reset}`)}}else if(ie||f.trim()==="?"){K.push("");for(let V of Jn())K.push(V);K.push(""),K.push(`${m}${C()}${w}`),K.push(`${U()}`)}else K.push(`${m}${C()}${w}`),K.push(`${U()}`);process.stdout.write(`\x1B[1G\x1B[2K\x1B[38;2;255;122;61m\u276F\x1B[0m ${re}`);for(let V of K)process.stdout.write(`
167
+ \x1B[2K${V}`);let gt=Math.max(0,te-K.length);for(let V=0;V<gt;V++)process.stdout.write(`
168
+ \x1B[2K`);let At=K.length+gt;At>0&&process.stdout.write(`\x1B[${At}A`),process.stdout.write(`\x1B[${3+P}G`),te=K.length},lo=()=>{j()};process.stdout.on("resize",lo);let Ys=new Mi("utf8"),co=ve=>{let k=Ys.write(ve);if(!k)return;if(k==="\r"||k===`
169
169
  `||k.endsWith("\r")||k.endsWith(`
170
170
  `)){if(f.endsWith("\\")){f=f.slice(0,-1)+`
171
- `,y=f.length,ae=!1,j();return}ae=!1;let P=k.replace(/[\r\n]+$/,"");if(P&&(f=f.slice(0,y)+P+f.slice(y),y+=P.length,x=!1,E=0),(f.startsWith("/model ")||f.startsWith("/model:"))&&!x){let B=dt(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(B.length>0){let Y=B[E]??B[0];fn(Y.command);return}}let O=He(f);if(O.showMenu&&!x){let B=it(O.query);if(B.length>0){let Y=B[E]??B[0];if(new Set(["/clear","/new","/status","/plan","/taste","/help","/exit","/quit","/init","/models","/compact","/theme","/language","/copy","/tree","/rewind","/pr-comments","/reload","/changelog","/hotkeys","/shortcuts","/todos","/unshare","/agents","/clone","/paste","/fork","/resume","/sessions","/review","/mcp","/config","/doctor","/session-file","/login","/logout"]).has(Y.command)){fn(Y.command);return}else{f=Y.command+" ",y=f.length,x=!1,E=0,G=0,j();return}}}fn(f);return}if(k===" "){if((f.startsWith("/model ")||f.startsWith("/model:"))&&!x){let O=dt(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(O.length>0){f=(O[E]??O[0]).command,y=f.length,x=!0,j();return}}let q=He(f);if(q.showMenu&&!x){let O=it(q.query);if(O.length>0){f=(O[E]??O[0]).command+" ",y=f.length,x=!1,E=0,G=0,j();return}}else{let O=f.slice(0,y),B=O.match(/@([a-zA-Z0-9_\-\.\/]*)$/);if(B){let Y=B[1],Ie=O.lastIndexOf("@");js(e).then(Et=>{let ye=Et.filter(Q=>Q.startsWith(Y));if(ye.length===1){let Q=ye[0]+(ye[0].endsWith("/")?"":" ");f=f.slice(0,Ie+1)+Q+f.slice(y),y=Ie+1+Q.length,j()}else if(ye.length>1){let Q=Y;for(let K=Y.length+1;K<=ye[0].length;K++){let ut=ye[0].slice(0,K);if(ye.every(Mt=>Mt.startsWith(ut)))Q=ut;else break}Q.length>Y.length&&(f=f.slice(0,Ie+1)+Q+f.slice(y),y=Ie+1+Q.length,j())}}).catch(()=>{});return}}return}if(k===""){if(f.length>0){f="",y=0,x=!1,E=0,G=0,j();return}gn();for(let P=0;P<te;P++)process.stdout.write(`
171
+ `,y=f.length,ie=!1,j();return}ie=!1;let P=k.replace(/[\r\n]+$/,"");if(P&&(f=f.slice(0,y)+P+f.slice(y),y+=P.length,x=!1,E=0),(f.startsWith("/model ")||f.startsWith("/model:"))&&!x){let B=Le(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(B.length>0){let Y=B[E]??B[0];de(Y.command);return}}let O=Ge(f);if(O.showMenu&&!x){let B=lt(O.query);if(B.length>0){let Y=B[E]??B[0];if(new Set(["/clear","/new","/status","/plan","/taste","/help","/exit","/quit","/init","/models","/compact","/theme","/language","/copy","/tree","/rewind","/pr-comments","/reload","/changelog","/hotkeys","/shortcuts","/todos","/unshare","/agents","/clone","/paste","/fork","/resume","/sessions","/review","/mcp","/config","/doctor","/session-file","/login","/logout"]).has(Y.command)){de(Y.command);return}else{f=Y.command+" ",y=f.length,x=!1,E=0,G=0,j();return}}}de(f);return}if(k===" "){if((f.startsWith("/model ")||f.startsWith("/model:"))&&!x){let O=Le(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(O.length>0){f=(O[E]??O[0]).command,y=f.length,x=!0,j();return}}let q=Ge(f);if(q.showMenu&&!x){let O=lt(q.query);if(O.length>0){f=(O[E]??O[0]).command+" ",y=f.length,x=!1,E=0,G=0,j();return}}else{let O=f.slice(0,y),B=O.match(/@([a-zA-Z0-9_\-\.\/]*)$/);if(B){let Y=B[1],Fe=O.lastIndexOf("@");fs(t).then(Pt=>{let be=Pt.filter(Q=>Q.startsWith(Y));if(be.length===1){let Q=be[0]+(be[0].endsWith("/")?"":" ");f=f.slice(0,Fe+1)+Q+f.slice(y),y=Fe+1+Q.length,j()}else if(be.length>1){let Q=Y;for(let K=Y.length+1;K<=be[0].length;K++){let gt=be[0].slice(0,K);if(be.every(At=>At.startsWith(gt)))Q=gt;else break}Q.length>Y.length&&(f=f.slice(0,Fe+1)+Q+f.slice(y),y=Fe+1+Q.length,j())}}).catch(()=>{});return}}return}if(k===""){if(f.length>0){f="",y=0,x=!1,E=0,G=0,j();return}Ke();for(let P=0;P<te;P++)process.stdout.write(`
172
172
  \x1B[2K`);te>0&&process.stdout.write(`\x1B[${te}A`),process.stdout.write(`\x1B[2K\r
173
- `),process.exit(0);return}if(k===""&&!f){gn();for(let P=0;P<te;P++)process.stdout.write(`
173
+ `),process.exit(0);return}if(k===""&&!f){Ke();for(let P=0;P<te;P++)process.stdout.write(`
174
174
  \x1B[2K`);te>0&&process.stdout.write(`\x1B[${te}A`),process.stdout.write(`\x1B[2K\r
175
- `),process.exit(0);return}if(k==="\x7F"||k==="\b"){if(y>0){let P=cn(f,y);f=f.slice(0,P)+f.slice(y),y=P,x=!1,E=0,G=0,j()}return}if(k==="\x1B"){if(ae){ae=!1,j();return}let P=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x,q=He(f);if((P||q.showMenu)&&!x){x=!0,j();return}let O=Date.now();if(O-ze<400&&f.length>0){f="",y=0,ae=!1,j(),ze=0;return}ze=O;return}if(k.startsWith("\x1B")){if(k==="\x1B[D")y>0&&(y=cn(f,y),j());else if(k==="\x1B[C")y<f.length&&(y=zn(f,y),j());else if(k==="\x1B[A"){let P=He(f),q=P.showMenu&&!x;if(((f.startsWith("/model ")||f.startsWith("/model:"))&&!x?dt(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):q?it(P.query):[]).length>0){E=Math.max(0,E-1),E<G&&(G=E),j();return}p.length>0&&D>0&&(D===p.length&&(xe=f),D--,f=p[D],y=f.length,x=!0,j())}else if(k==="\x1B[B"){let P=He(f),q=P.showMenu&&!x,B=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x?dt(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):q?it(P.query):[];if(B.length>0){E=Math.min(B.length-1,E+1),E>=G+8&&(G=Math.max(0,E-8+1)),j();return}D<p.length&&(D++,f=D===p.length?xe:p[D],y=f.length,x=!0,j())}else k==="\x1B[H"||k==="\x1B[1~"||k===""?(y=0,j()):k==="\x1B[F"||k==="\x1B[4~"||k===""?(y=f.length,j()):k==="\x1B[3~"&&y<f.length&&(f=f.slice(0,y)+f.slice(zn(f,y)),j());return}if(k===""){y=0,j();return}if(k===""){y=f.length,j();return}if(k===""){Kn().then(P=>{P&&Ae.push(P),j()});return}if(k.charCodeAt(0)<32&&k!==" ")return;if(k==="?"&&!f){ae=!ae,j();return}ae=!1;let ie=k.replace(/\r?\n/g," ");f=f.slice(0,y)+ie+f.slice(y),y+=ie.length,x=!1,E=0,G=0,j()};ee.on("data",ao)})}if(t.prompt){await Tt(t.prompt,W)&&await Os(e,null);return}let mn=lt.length+kt,A=W,Rt=[];await un().catch(()=>{});let Js=s==="not logged in"?`${A} (not logged in)`:A;for(Hn(Js,mn,e),s==="not logged in"&&console.log(`${i.dim} You are not logged in. Type ${i.bold}/login${i.reset}${i.dim} to authenticate.${i.reset}
176
- `);;){let S=St.queue.shift();S&&!S.startsWith("/")&&console.log(`
175
+ `),process.exit(0);return}if(k==="\x7F"||k==="\b"){if(y>0){let P=tn(f,y);f=f.slice(0,P)+f.slice(y),y=P,x=!1,E=0,G=0,j()}return}if(k==="\x1B"){if(ie){ie=!1,j();return}let P=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x,q=Ge(f);if((P||q.showMenu)&&!x){x=!0,j();return}let O=Date.now();if(O-pt<400&&f.length>0){f="",y=0,ie=!1,j(),pt=0;return}pt=O;return}if(k.startsWith("\x1B")){if(k==="\x1B[D")y>0&&(y=tn(f,y),j());else if(k==="\x1B[C")y<f.length&&(y=zn(f,y),j());else if(k==="\x1B[A"){let P=Ge(f),q=P.showMenu&&!x;if(((f.startsWith("/model ")||f.startsWith("/model:"))&&!x?Le(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):q?lt(P.query):[]).length>0){E=Math.max(0,E-1),E<G&&(G=E),j();return}p.length>0&&D>0&&(D===p.length&&($e=f),D--,f=p[D],y=f.length,x=!0,j())}else if(k==="\x1B[B"){let P=Ge(f),q=P.showMenu&&!x,B=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x?Le(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):q?lt(P.query):[];if(B.length>0){E=Math.min(B.length-1,E+1),E>=G+8&&(G=Math.max(0,E-8+1)),j();return}D<p.length&&(D++,f=D===p.length?$e:p[D],y=f.length,x=!0,j())}else k==="\x1B[H"||k==="\x1B[1~"||k===""?(y=0,j()):k==="\x1B[F"||k==="\x1B[4~"||k===""?(y=f.length,j()):k==="\x1B[3~"&&y<f.length&&(f=f.slice(0,y)+f.slice(zn(f,y)),j());return}if(k===""){y=0,j();return}if(k===""){y=f.length,j();return}if(k===""){Kn().then(P=>{P&&Ae.push(P),j()});return}if(k.charCodeAt(0)<32&&k!==" ")return;if(k==="?"&&!f){ie=!ie,j();return}ie=!1;let re=k.replace(/\r?\n/g," ");f=f.slice(0,y)+re+f.slice(y),y+=re.length,x=!1,E=0,G=0,j()};ye.on("data",co)})}if(e.prompt){await Mt(e.prompt,W)&&await Fs(t,null);return}let hn=ut.length+St,A=W,Ct=[];await fn().catch(()=>{});let Ks=s==="not logged in"?`${A} (not logged in)`:A;for(Hn(Ks,hn,t),s==="not logged in"&&console.log(`${i.dim} You are not logged in. Type ${i.bold}/login${i.reset}${i.dim} to authenticate.${i.reset}
176
+ `);;){let S=Et.queue.shift();S&&!S.startsWith("/")&&console.log(`
177
177
  ${i.userMsgBg} ${i.userPointer}${i.bold}\u276F${i.reset}${i.userMsgBg} ${i.userFg}${S} ${i.reset}
178
- `),S||await Promise.race([un().catch(()=>{}),new Promise(m=>setTimeout(m,1500))]);let p=S??await zs(mn,Rt);if(!p)continue;if(Rt[Rt.length-1]!==p&&Rt.push(p),p==="/exit"||p==="/quit")break;if(p==="/clear"||p==="/new"){u.length=0,u.push({role:"system",content:await d()}),he=0,de=on(),Ne=void 0,$t=Date.now(),console.clear(),Hn(A,mn,e),console.log(l("cli.run.0_new_session_started_1",`{0}\u2713 New session started.{1}
179
- `,i.assistantPrefix,i.reset));continue}if(p==="?"||p==="/shortcuts"||p==="/hotkeys"){Gn();continue}if(p==="/help"){Ps();continue}if(p==="/taste"){let m=await Ue(e),w=await Me(e);console.log(l("cli.run.0_taste_learning_status_1",`
178
+ `),S||await Promise.race([fn().catch(()=>{}),new Promise(m=>setTimeout(m,1500))]);let p=S??await Gs(hn,Ct);if(!p)continue;if(Ct[Ct.length-1]!==p&&Ct.push(p),p==="/exit"||p==="/quit")break;if(p==="/clear"||p==="/new"){u.length=0,u.push({role:"system",content:await d()}),he=0,ce=un(),Oe=void 0,Tt=Date.now(),console.clear(),Hn(A,hn,t),console.log(l("cli.run.0_new_session_started_1",`{0}\u2713 New session started.{1}
179
+ `,i.assistantPrefix,i.reset));continue}if(p==="?"||p==="/shortcuts"||p==="/hotkeys"){Gn();continue}if(p==="/help"){ps();continue}if(p==="/taste"){let m=await qe(t),w=await Pe(t);console.log(l("cli.run.0_taste_learning_status_1",`
180
180
  {0}Taste Learning Status:{1}`,i.bold,i.reset)),console.log(l("cli.run.status_0_on_1"," \u2022 Status: {0}ON{1}",i.cyan,i.reset)),console.log(l("cli.run.active_skills_0_rule_s"," \u2022 Active Skills: {0} rule(s) in .forge/skills.md",m.length)),console.log(l("cli.run.memory_notes_0_item_s",` \u2022 Memory Notes: {0} item(s) in .forge/memory.md
181
- `,w.length));continue}if(p.startsWith("/skills")){let m=p.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();if(w){let b=await nt(e,w);console.log(`
181
+ `,w.length));continue}if(p.startsWith("/skills")){let m=p.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();if(w){let b=await rt(t,w);console.log(`
182
182
  ${b.added?`\u2713 Added skill: "${b.skill}"`:"Skill already exists."}
183
- `)}}else{let w=await Ue(e);console.log(l("cli.run.0_project_skills_forge_skills",`
184
- {0}Project Skills (.forge/skills.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,F)=>console.log(` ${F+1}. ${b}`)):console.log(l("cli.run.0_no_skills_yet_add",' {0}(No skills yet. Add one with: /skills add "Prefer pnpm"){1}',i.dim,i.reset)),console.log("")}continue}if(p.startsWith("/memory")){let m=p.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();w&&(await ft(e,w),console.log(l("cli.run.saved_to_forge_memory_md",`
183
+ `)}}else{let w=await qe(t);console.log(l("cli.run.0_project_skills_forge_skills",`
184
+ {0}Project Skills (.forge/skills.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,F)=>console.log(` ${F+1}. ${b}`)):console.log(l("cli.run.0_no_skills_yet_add",' {0}(No skills yet. Add one with: /skills add "Prefer pnpm"){1}',i.dim,i.reset)),console.log("")}continue}if(p.startsWith("/memory")){let m=p.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();w&&(await wt(t,w),console.log(l("cli.run.saved_to_forge_memory_md",`
185
185
  \u2713 Saved to .forge/memory.md: "{0}"
186
- `,w)))}else{let w=await Me(e);console.log(l("cli.run.0_project_memory_forge_memory",`
187
- {0}Project Memory (.forge/memory.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,F)=>console.log(` ${F+1}. ${b}`)):console.log(l("cli.run.0_no_memory_notes_yet",' {0}(No memory notes yet. Add one with: /memory add "..."){1}',i.dim,i.reset)),console.log("")}continue}if(p==="/models"){console.log(""),await Xt(),console.log("");continue}if(p==="/paste"||p.startsWith("/image")){let m=p.startsWith("/image")?p.slice(6).trim():"";if(m){Ae.push(je.resolve(e,m.replace(/^["']|["']$/g,""))),console.log(l("cli.run.queued_0_it_goes_with",`
186
+ `,w)))}else{let w=await Pe(t);console.log(l("cli.run.0_project_memory_forge_memory",`
187
+ {0}Project Memory (.forge/memory.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,F)=>console.log(` ${F+1}. ${b}`)):console.log(l("cli.run.0_no_memory_notes_yet",' {0}(No memory notes yet. Add one with: /memory add "..."){1}',i.dim,i.reset)),console.log("")}continue}if(p==="/models"){console.log(""),await sn(),console.log("");continue}if(p==="/paste"||p.startsWith("/image")){let m=p.startsWith("/image")?p.slice(6).trim():"";if(m){Ae.push(Ie.resolve(t,m.replace(/^["']|["']$/g,""))),console.log(l("cli.run.queued_0_it_goes_with",`
188
188
  \u{1F4CE} queued {0}; it goes with your next message.
189
189
  `,m));continue}let w=await Kn();w?(Ae.push(w),console.log(l("cli.run.clipboard_image_attached_0_queued",`
190
190
  \u{1F4CE} clipboard image attached ({0} queued); it goes with your next message.
191
191
  `,Ae.length))):console.log($(`
192
192
  No image on the clipboard (copy or screenshot one first, e.g. Cmd+Ctrl+Shift+4 on macOS).
193
- `));continue}if(p.startsWith("/model")){let m=p.split(/\s+/);m[1]?(A=m[1],await We({defaultModel:A}).catch(()=>{}),console.log(l("cli.run.switched_active_model_to_0",`
193
+ `));continue}if(p.startsWith("/model")){let m=p.split(/\s+/);m[1]?(A=m[1],await ze({defaultModel:A}).catch(()=>{}),console.log(l("cli.run.switched_active_model_to_0",`
194
194
  \u2713 Switched active model to: {0}{1}{2}{3}
195
- `,i.bold,A,i.reset,await so(A)?$(" [reads images]"):$(" [text only]")))):(console.log(`
195
+ `,i.bold,A,i.reset,await io(A)?$(" [reads images]"):$(" [text only]")))):(console.log(`
196
196
  Active model: ${i.bold}${A}${i.reset} via ${i.cyan}${s}${i.reset}`),console.log(l("cli.run.to_switch_run_0_model",`To switch, run: {0}/model <id>{1} or type {2}/models{3} to list all.
197
- `,i.cyan,i.reset,i.cyan,i.reset)));continue}if(p==="/context"){let m=Xe(u);if(console.log(l("cli.run.0_context_window_usage_1",`
197
+ `,i.cyan,i.reset,i.cyan,i.reset)));continue}if(p==="/context"){let m=et(u);if(console.log(l("cli.run.0_context_window_usage_1",`
198
198
  {0}Context Window Usage:{1}`,i.bold,i.reset)),console.log(l("cli.run.messages_in_session_0"," \u2022 Messages in session: {0}",u.length)),console.log(l("cli.run.turns_completed_0"," \u2022 Turns completed: {0}",he)),console.log(l("cli.run.estimated_tokens_0_tokens"," \u2022 Estimated tokens: ~{0} tokens",m.toLocaleString())),R>0){let w=Math.round(m/R*100);console.log(l("cli.run.budget_limit_0_tokens_1",` \u2022 Budget limit: {0} tokens ({1}% used)
199
199
  `,R.toLocaleString(),w))}else console.log(` \u2022 Budget limit: Unlimited
200
200
  `);continue}if(p==="/copy"){let m=[...u].reverse().find(w=>w.role==="assistant"&&typeof w.content=="string");if(!m||!m.content)console.log(l("cli.run.0_no_assistant_response_to",`
201
201
  {0}No assistant response to copy yet.{1}
202
- `,i.dim,i.reset));else{let w=m.content;if(await As(w))console.log(l("cli.run.0_copied_last_response_to",`
202
+ `,i.dim,i.reset));else{let w=m.content;if(await gs(w))console.log(l("cli.run.0_copied_last_response_to",`
203
203
  {0}\u2713 Copied last response to clipboard.{1}
204
- `,i.assistantPrefix,i.reset));else{let F=je.join(e,h.dirName,"last_response.txt");await xt.mkdir(je.dirname(F),{recursive:!0}),await xt.writeFile(F,w,"utf8"),console.log(l("cli.run.0_saved_last_response_to",`
204
+ `,i.assistantPrefix,i.reset));else{let F=Ie.join(t,_.dirName,"last_response.txt");await vt.mkdir(Ie.dirname(F),{recursive:!0}),await vt.writeFile(F,w,"utf8"),console.log(l("cli.run.0_saved_last_response_to",`
205
205
  {0}\u2713 Saved last response to {1}{2}
206
- `,i.assistantPrefix,je.relative(e,F),i.reset))}}continue}if(p.startsWith("/export")){let m=p.includes("jsonl"),w=m?"jsonl":"md",b=`forge-session-${new Date().toISOString().replace(/[:.]/g,"-")}.${w}`,F=je.join(e,b);if(m){let C=u.map(U=>JSON.stringify(U)).join(`
207
- `);await xt.writeFile(F,C,"utf8")}else{let C=`# Session Transcript
206
+ `,i.assistantPrefix,Ie.relative(t,F),i.reset))}}continue}if(p.startsWith("/export")){let m=p.includes("jsonl"),w=m?"jsonl":"md",b=`forge-session-${new Date().toISOString().replace(/[:.]/g,"-")}.${w}`,F=Ie.join(t,b);if(m){let C=u.map(U=>JSON.stringify(U)).join(`
207
+ `);await vt.writeFile(F,C,"utf8")}else{let C=`# Session Transcript
208
208
 
209
209
  - **Model**: ${A}
210
210
  - **Date**: ${new Date().toLocaleString()}
211
- - **Workspace**: ${e}
211
+ - **Workspace**: ${t}
212
212
 
213
213
  ---
214
214
 
@@ -220,27 +220,27 @@ ${U.content}
220
220
 
221
221
  ${U.content}
222
222
 
223
- `);await xt.writeFile(F,C,"utf8")}console.log(l("cli.run.0_exported_session_to_1",`
223
+ `);await vt.writeFile(F,C,"utf8")}console.log(l("cli.run.0_exported_session_to_1",`
224
224
  {0}\u2713 Exported session to {1}{2}
225
- `,i.assistantPrefix,b,i.reset));continue}if(p==="/usage"){console.log(""),await Zt().catch(m=>console.log($(`could not load usage: ${m.message}`))),console.log("");continue}if(p.startsWith("/effort")){let m=p.split(/\s+/);m[1]&&["low","high"].includes(m[1])?(t.effort=m[1],console.log(l("cli.run.effort_set_to_0_1",`
225
+ `,i.assistantPrefix,b,i.reset));continue}if(p==="/usage"){console.log(""),await rn().catch(m=>console.log($(`could not load usage: ${m.message}`))),console.log("");continue}if(p.startsWith("/effort")){let m=p.split(/\s+/);m[1]&&["low","high"].includes(m[1])?(e.effort=m[1],console.log(l("cli.run.effort_set_to_0_1",`
226
226
  \u2713 Effort set to: {0}{1}{2}
227
- `,i.bold,t.effort,i.reset))):(t.effort=t.effort==="high"?"low":"high",console.log(l("cli.run.effort_toggled_to_0_1",`
227
+ `,i.bold,e.effort,i.reset))):(e.effort=e.effort==="high"?"low":"high",console.log(l("cli.run.effort_toggled_to_0_1",`
228
228
  \u2713 Effort toggled to: {0}{1}{2}
229
- `,i.bold,t.effort,i.reset)));continue}if(p==="/status"){console.log(l("cli.run.0_session_status_1",`
230
- {0}Session Status:{1}`,i.bold,i.reset)),console.log(l("cli.run.model_0_1_2_3"," \u2022 Model: {0}{1}{2} ({3})",i.cyan,A,i.reset,s)),console.log(l("cli.run.workspace_0"," \u2022 Workspace: {0}",e)),console.log(l("cli.run.turns_completed_0_2"," \u2022 Turns completed: {0}",he)),console.log(l("cli.run.taste_0_skill_s_1",` \u2022 Taste: {0} skill(s), {1} memory note(s)
231
- `,lt.length,kt));continue}if(p==="/init"){console.log(""),await Qt(),console.log("");continue}if(p.startsWith("/theme")){let w=p.slice(6).trim().toLowerCase()==="light"?"light":"dark";console.log(l("cli.run.color_theme_0_1_2",`
229
+ `,i.bold,e.effort,i.reset)));continue}if(p==="/status"){console.log(l("cli.run.0_session_status_1",`
230
+ {0}Session Status:{1}`,i.bold,i.reset)),console.log(l("cli.run.model_0_1_2_3"," \u2022 Model: {0}{1}{2} ({3})",i.cyan,A,i.reset,s)),console.log(l("cli.run.workspace_0"," \u2022 Workspace: {0}",t)),console.log(l("cli.run.turns_completed_0_2"," \u2022 Turns completed: {0}",he)),console.log(l("cli.run.taste_0_skill_s_1",` \u2022 Taste: {0} skill(s), {1} memory note(s)
231
+ `,ut.length,St));continue}if(p==="/init"){console.log(""),await an(),console.log("");continue}if(p.startsWith("/theme")){let w=p.slice(6).trim().toLowerCase()==="light"?"light":"dark";console.log(l("cli.run.color_theme_0_1_2",`
232
232
  \u2713 Color theme: {0}{1}{2}
233
233
  `,i.bold,w,i.reset));continue}if(p.startsWith("/language")){let m=p.slice(9).trim().toLowerCase(),w=m.includes("bn")||m.includes("\u09AC\u09BE\u0982\u09B2\u09BE")?"\u09AC\u09BE\u0982\u09B2\u09BE (Bengali)":m.includes("zh")?"\u7B80\u4F53\u4E2D\u6587 (Chinese)":"English";console.log(l("cli.run.interface_language_set_to_0",`
234
234
  \u2713 Interface language set to: {0}{1}{2}
235
235
  `,i.bold,w,i.reset));continue}if(p.startsWith("/add-dir")){let m=p.slice(8).trim();if(!m)console.log(l("cli.run.0_workspace_directories_1",`
236
236
  {0}Workspace Directories:{1}`,i.bold,i.reset)),console.log(l("cli.run.root_0",` \u2022 Root: {0}
237
- `,e));else{let w=je.resolve(e,m);try{(await xt.stat(w)).isDirectory()?console.log(l("cli.run.added_directory_scope_0_1",`
237
+ `,t));else{let w=Ie.resolve(t,m);try{(await vt.stat(w)).isDirectory()?console.log(l("cli.run.added_directory_scope_0_1",`
238
238
  \u2713 Added directory scope: {0}{1}{2}
239
239
  `,i.bold,w,i.reset)):console.log(l("cli.run.0_path_is_not_a",`
240
240
  {0}Path is not a directory: {1}{2}
241
241
  `,i.dim,w,i.reset))}catch(b){console.log(l("cli.run.0_could_not_access_directory",`
242
242
  {0}Could not access directory: {1}{2}
243
- `,i.dim,b.message,i.reset))}}continue}if(p.startsWith("/worktree")){let m=p.slice(9).trim();console.log($(`$ git worktree ${m||"list"}`));let w=await Ye("run_shell",{command:`git worktree ${m||"list"}`},g).catch(b=>b.message);console.log(w);continue}if(p==="/agents"){console.log(l("cli.run.0_active_agent_configuration_1",`
243
+ `,i.dim,b.message,i.reset))}}continue}if(p.startsWith("/worktree")){let m=p.slice(9).trim();console.log($(`$ git worktree ${m||"list"}`));let w=await Ze("run_shell",{command:`git worktree ${m||"list"}`},g).catch(b=>b.message);console.log(w);continue}if(p==="/agents"){console.log(l("cli.run.0_active_agent_configuration_1",`
244
244
  {0}Active Agent Configuration:{1}`,i.bold,i.reset)),console.log(l("cli.run.model_0_1_2_3_2"," \u2022 Model: {0}{1}{2} ({3})",i.cyan,A,i.reset,s)),console.log(l("cli.run.available_tools_run_shell_read"," \u2022 Available Tools: run_shell, read_file, edit_file, write_file, list_dir, glob, read_multiple_files, think")),console.log(l("cli.run.tool_repair_automatic_alias_redirection",` \u2022 Tool Repair: Automatic alias redirection enabled
245
245
  `));continue}if(p.startsWith("/goal")){let m=p.slice(5).trim();m==="clear"?console.log(l("cli.run.session_goal_cleared",`
246
246
  \u2713 Session goal cleared.
@@ -248,60 +248,60 @@ ${U.content}
248
248
  {0}Session Goal:{1} {2}(No explicit goal active. Set with: /goal <objective>){3}
249
249
  `,i.bold,i.reset,i.dim,i.reset)):(u.push({role:"system",content:`CURRENT GOAL: ${m}`}),console.log(l("cli.run.set_active_session_goal_0",`
250
250
  \u2713 Set active session goal: "{0}"
251
- `,m)));continue}if(p==="/plan"){re=!re,console.log(l("cli.run.plan_mode_0_1_2",`
251
+ `,m)));continue}if(p==="/plan"){se=!se,console.log(l("cli.run.plan_mode_0_1_2",`
252
252
  \u2713 Plan mode {0}{1}{2}{3}.
253
- `,i.bold,re?"ON":"OFF",i.reset,re?" (read-only: the agent will explore and propose a plan, no edits or commands)":""));continue}if(p.startsWith("/mode")){let m=p.replace(/^\/mode:?/,"").trim();m==="accept-edits"?(t.yolo=!0,re=!1,console.log(l("cli.run.switched_to_0_accept_edits",`
253
+ `,i.bold,se?"ON":"OFF",i.reset,se?" (read-only: the agent will explore and propose a plan, no edits or commands)":""));continue}if(p.startsWith("/mode")){let m=p.replace(/^\/mode:?/,"").trim();m==="accept-edits"?(e.yolo=!0,se=!1,console.log(l("cli.run.switched_to_0_accept_edits",`
254
254
  \u2713 Switched to {0}accept-edits{1} mode (edits accepted automatically).
255
- `,i.bold,i.reset))):m==="plan"?(re=!0,console.log(l("cli.run.switched_to_0_plan_1",`
255
+ `,i.bold,i.reset))):m==="plan"?(se=!0,console.log(l("cli.run.switched_to_0_plan_1",`
256
256
  \u2713 Switched to {0}plan{1} mode (read-only reasoning).
257
- `,i.bold,i.reset))):(t.yolo=!1,re=!1,console.log(l("cli.run.switched_to_0_default_1",`
257
+ `,i.bold,i.reset))):(e.yolo=!1,se=!1,console.log(l("cli.run.switched_to_0_default_1",`
258
258
  \u2713 Switched to {0}default{1} mode (prompt before major edits).
259
259
  `,i.bold,i.reset)));continue}if(p.startsWith("/btw")){let m=p.slice(4).trim();if(!m)console.log(l("cli.run.usage_btw_question_ask_a",`
260
260
  Usage: /btw <question> (ask a quick side question that does not enter history)
261
261
  `));else{let w=[...u,{role:"user",content:m}];console.log(l("cli.run.0_btw_side_question_1",`
262
- {0}[btw side question]{1}`,i.gray,i.reset)),await Qe({messages:w,ctx:g,yolo:!0,maxSteps:1,maxRunTokens:2e3,client:A==="mock-model"&&s!=="gateway"?new De:n,model:A,onEvent:b=>{b.type==="assistant"&&console.log(`
262
+ {0}[btw side question]{1}`,i.gray,i.reset)),await nt({messages:w,ctx:g,yolo:!0,maxSteps:1,maxRunTokens:2e3,client:A==="mock-model"&&s!=="gateway"?new We:n,model:A,onEvent:b=>{b.type==="assistant"&&console.log(`
263
263
  ${i.assistantPrefix}\u25C6${i.reset} ${b.text}
264
264
  `)}}).catch(b=>console.log(l("cli.run.error_0_2","error: {0}",b.message)))}continue}if(p==="/hotkeys"||p==="/shortcuts"){Gn();continue}if(p==="/changelog"){console.log(l("cli.run.0_command_code_v1_87",`
265
- {0}{2} {3} changelog:{1}`,i.bold,i.reset,h.name,h.version)),console.log(l("cli.run.instant_live_slash_command_dropdown"," \u2022 Live slash command menu, Bangla-aware input editing")),console.log(l("cli.run.exact_command_code_truecolor_theme"," \u2022 Forge ember theme, gradient banner and spark status line")),console.log(l("cli.run.task_queue"," \u2022 Task queue: type while a task runs, remove waiting tasks with backspace")),console.log(l("cli.run.extended_tool_suite_glob_read",` \u2022 Extended tool suite: glob, read_multiple_files, think
265
+ {0}{2} v{3} changelog:{1}`,i.bold,i.reset,_.name,xe)),console.log(l("cli.run.instant_live_slash_command_dropdown"," \u2022 Live slash command menu, Bangla-aware input editing")),console.log(l("cli.run.exact_command_code_truecolor_theme"," \u2022 Forge ember theme, gradient banner and spark status line")),console.log(l("cli.run.task_queue"," \u2022 Task queue: type while a task runs, remove waiting tasks with backspace")),console.log(l("cli.run.extended_tool_suite_glob_read",` \u2022 Extended tool suite: glob, read_multiple_files, think
266
266
  `));continue}if(p==="/todos"){console.log(l("cli.run.0_session_todos_1",`
267
267
  {0}Session Todos:{1}`,i.bold,i.reset)),console.log(l("cli.run.0_no_pending_todos_in",` {0}(No pending todos in this session){1}
268
268
  `,i.dim,i.reset));continue}if(p.startsWith("/feedback")||p.startsWith("/issue")){console.log(l("cli.run.share_feedback_or_report_an",`
269
269
  Share feedback or report an issue on GitHub:`)),console.log(l("cli.run.0_https_github_com_command",` {0}https://github.com/command-code/command-code/issues/new{1}
270
- `,i.cyan,i.reset));continue}if(p==="/compact"||p.startsWith("/compact ")){let m=sn(u);if(m.length<2){console.log(l("cli.run.0_nothing_to_compact_yet",`
270
+ `,i.cyan,i.reset));continue}if(p==="/compact"||p.startsWith("/compact ")){let m=mn(u);if(m.length<2){console.log(l("cli.run.0_nothing_to_compact_yet",`
271
271
  {0}Nothing to compact yet ({1} turn).{2}
272
272
  `,i.dim,m.length,i.reset));continue}let w=m[m.length-1],b=(f,y=1500)=>(f??"").length>y?(f??"").slice(0,y)+"\u2026":f??"",F=u.slice(1,w).map(f=>f.role==="tool"?`[tool result] ${b(f.content,400)}`:f.role==="assistant"?`assistant: ${b(f.content)}${f.tool_calls?.length?` [tools: ${f.tool_calls.map(y=>y.name).join(", ")}]`:""}`:`${f.role}: ${b(f.content)}`).join(`
273
- `).slice(-6e4),C=p.slice(8).trim(),U=Xe(u);console.log($("compacting conversation\u2026"));try{let y=(await(A==="mock-model"&&s!=="gateway"?new De:n).chat({model:A,tools:[],messages:[{role:"system",content:"You compress coding-agent conversations into a briefing that lets the work continue. Keep: the user's goals and constraints, decisions made, files created/changed (paths), commands run and their outcomes, errors still unresolved, and next steps. Be factual and compact (under 400 words). No preamble."},{role:"user",content:`${C?`Focus especially on: ${C}
273
+ `).slice(-6e4),C=p.slice(8).trim(),U=et(u);console.log($("compacting conversation\u2026"));try{let y=(await(A==="mock-model"&&s!=="gateway"?new We:n).chat({model:A,tools:[],messages:[{role:"system",content:"You compress coding-agent conversations into a briefing that lets the work continue. Keep: the user's goals and constraints, decisions made, files created/changed (paths), commands run and their outcomes, errors still unresolved, and next steps. Be factual and compact (under 400 words). No preamble."},{role:"user",content:`${C?`Focus especially on: ${C}
274
274
 
275
275
  `:""}Conversation to summarize:
276
276
 
277
277
  ${F}`}]})).content?.trim();if(!y)throw new Error(l("cli.run.the_model_returned_an_empty","the model returned an empty summary"));let D=u.slice(w);u.length=1,u.push({role:"user",content:`[Summary of the earlier conversation]
278
- ${y}`},{role:"assistant",content:"Understood. I have the context from that summary and will continue from here."},...D),await ct(),console.log(l("cli.run.0_conversation_compacted_1_tokens",`
278
+ ${y}`},{role:"assistant",content:"Understood. I have the context from that summary and will continue from here."},...D),await mt(),console.log(l("cli.run.0_conversation_compacted_1_tokens",`
279
279
  {0}\u2713 Conversation compacted{1}
280
280
  \u2022 Tokens: ~{2} \u2192 ~{3}
281
- `,i.assistantPrefix,i.reset,U.toLocaleString(),Xe(u).toLocaleString()))}catch(f){console.log(l("cli.run.0_could_not_compact_1",`
281
+ `,i.assistantPrefix,i.reset,U.toLocaleString(),et(u).toLocaleString()))}catch(f){console.log(l("cli.run.0_could_not_compact_1",`
282
282
  {0}Could not compact: {1}{2}
283
- `,i.dim,Ce(f,r),i.reset))}continue}if(p==="/resume"||p==="/sessions"||p.startsWith("/resume ")){let m=p.startsWith("/resume ")?p.slice(8).trim():await no(),w=m?await Un(e,m):null;if(!w){m&&console.log($(`
283
+ `,i.dim,je(f,r),i.reset))}continue}if(p==="/resume"||p==="/sessions"||p.startsWith("/resume ")){let m=p.startsWith("/resume ")?p.slice(8).trim():await so(),w=m?await Vn(t,m):null;if(!w){m&&console.log($(`
284
284
  No session matches "${m}".
285
- `));continue}to(w),console.log(l("cli.run.0_resumed_1_2_3",`
285
+ `));continue}oo(w),console.log(l("cli.run.0_resumed_1_2_3",`
286
286
  {0}\u2713 Resumed "{1}"{2} {3}
287
- `,i.assistantPrefix,w.title,i.reset,$(`(${he} turn(s), ${rn(w.updatedAt)})`)));continue}if(p==="/fork"||p==="/clone"){if(u.length<=1){console.log($(`
287
+ `,i.assistantPrefix,w.title,i.reset,$(`(${he} turn(s), ${pn(w.updatedAt)})`)));continue}if(p==="/fork"||p==="/clone"){if(u.length<=1){console.log($(`
288
288
  Nothing to fork yet.
289
- `));continue}Ne=`${Ne??bt(u.slice(1))} (fork)`,de=on(),$t=Date.now(),await ct(),console.log(l("cli.run.0_forked_into_a_new",`
289
+ `));continue}Oe=`${Oe??$t(u.slice(1))} (fork)`,ce=un(),Tt=Date.now(),await mt(),console.log(l("cli.run.0_forked_into_a_new",`
290
290
  {0}\u2713 Forked into a new session{1} {2}
291
- `,i.assistantPrefix,i.reset,$(de)));continue}if(p.startsWith("/rename")){let m=p.slice(7).trim();if(!m){console.log($(`
292
- Usage: /rename <new title> (current: ${Ne??bt(u.slice(1))})
293
- `));continue}Ne=m.slice(0,120),await ct(),console.log(l("cli.run.0_session_renamed_1",`
291
+ `,i.assistantPrefix,i.reset,$(ce)));continue}if(p.startsWith("/rename")){let m=p.slice(7).trim();if(!m){console.log($(`
292
+ Usage: /rename <new title> (current: ${Oe??$t(u.slice(1))})
293
+ `));continue}Oe=m.slice(0,120),await mt(),console.log(l("cli.run.0_session_renamed_1",`
294
294
  {0}\u2713 Session renamed{1}
295
295
  `,i.assistantPrefix,i.reset));continue}if(p==="/session-file"){console.log(l("cli.run.session_0_file_1_2",`
296
296
  \u2022 Session: {0}
297
297
  \u2022 File: {1}{2}
298
- `,de,nn(e,de),u.length<=1?$(" (saved after your first message)"):""));continue}if(p==="/rewind"){let m=sn(u);if(!m.length){console.log($(`
298
+ `,ce,dn(t,ce),u.length<=1?$(" (saved after your first message)"):""));continue}if(p==="/rewind"){let m=mn(u);if(!m.length){console.log($(`
299
299
  Nothing to rewind.
300
300
  `));continue}let w=m.slice(-10);console.log(l("cli.run.0_rewind_to_before_which",`
301
- {0}Rewind to before which message?{1}`,i.bold,i.reset)),w.forEach((F,C)=>console.log(` ${String(C+1).padStart(2)}. ${bt([u[F]])}`));let b=Number.parseInt(await eo(`
302
- Number (Enter to cancel): `),10);if(!(b>=1&&b<=w.length))continue;u.length=w[b-1],he=sn(u).length,await ct(),console.log(l("cli.run.0_conversation_rewound_1_2",`
301
+ {0}Rewind to before which message?{1}`,i.bold,i.reset)),w.forEach((F,C)=>console.log(` ${String(C+1).padStart(2)}. ${$t([u[F]])}`));let b=Number.parseInt(await no(`
302
+ Number (Enter to cancel): `),10);if(!(b>=1&&b<=w.length))continue;u.length=w[b-1],he=mn(u).length,await mt(),console.log(l("cli.run.0_conversation_rewound_1_2",`
303
303
  {0}\u2713 Conversation rewound.{1} {2}
304
- `,i.assistantPrefix,i.reset,$("File edits were not undone \u2014 use git (e.g. `git restore`) for that.")));continue}if(p.startsWith("/review")){let m=p.slice(7).trim(),w=(U,f)=>new Promise((y,D)=>Si(U,f,{cwd:e,maxBuffer:16*1024*1024},(xe,x,E)=>xe?D(new Error(String(E||xe.message).trim())):y(String(x)))),b="";try{/^\d+$/.test(m)?b=await w("gh",["pr","diff",m]):b=await w("git",["diff","HEAD"]).catch(()=>w("git",["diff"]))}catch(U){console.log(l("cli.run.0_could_not_get_the",`
304
+ `,i.assistantPrefix,i.reset,$("File edits were not undone \u2014 use git (e.g. `git restore`) for that.")));continue}if(p.startsWith("/review")){let m=p.slice(7).trim(),w=(U,f)=>new Promise((y,D)=>Ei(U,f,{cwd:t,maxBuffer:16*1024*1024},($e,x,E)=>$e?D(new Error(String(E||$e.message).trim())):y(String(x)))),b="";try{/^\d+$/.test(m)?b=await w("gh",["pr","diff",m]):b=await w("git",["diff","HEAD"]).catch(()=>w("git",["diff"]))}catch(U){console.log(l("cli.run.0_could_not_get_the",`
305
305
  {0}Could not get the diff: {1}{2}
306
306
  `,i.dim,U instanceof Error?U.message:U,i.reset));continue}if(!b.trim()){console.log($(`
307
307
  No changes to review.
@@ -310,25 +310,25 @@ No changes to review.
310
310
  <diff>
311
311
  ${F?b.slice(0,6e4)+`
312
312
  \u2026 (diff truncated)`:b}
313
- </diff>`;await Tt(C,A,!0),console.log("");continue}if(p==="/mcp"){console.log(l("cli.run.0_mcp_servers_1",`
314
- {0}MCP servers:{1}`,i.bold,i.reset));let m=new Map;for(let w of I.tools)m.set(w.server,[...m.get(w.server)??[],w.name]);for(let[w,b]of m)console.log(` \u2022 ${i.cyan}${w}${i.reset} ${$(`${b.length} tool(s): ${b.slice(0,6).join(", ")}${b.length>6?", \u2026":""}`)}`);for(let[w,b]of I.errors)console.log(l("cli.run.0_unavailable_1"," \u2022 {0} \x1B[31munavailable\x1B[0m {1}",w,$(b)));Z.untrusted.length&&console.log(` \u2022 ${Z.untrusted.join(", ")} ${$(`untrusted \u2014 run \`${h.bin} mcp trust\``)}`),!I.serverCount&&!I.errors.size&&!Z.untrusted.length&&console.log($(` none. Add one: ${h.bin} mcp add <name> <command\u2026|url>`)),console.log("");continue}if(p==="/login"){try{await Yt();let m=await Vn(t);n=m.client,s=m.label,r=m.apiUrl,A=t.model??(await oe()).defaultModel??m.model,vt=A,(t.cascade||t.effort==="high"&&!t.model)&&(v=await Xn(t,s,A)),_e=null,we=[],await un().catch(()=>{}),console.log(`
313
+ </diff>`;await Mt(C,A,!0),console.log("");continue}if(p==="/mcp"){console.log(l("cli.run.0_mcp_servers_1",`
314
+ {0}MCP servers:{1}`,i.bold,i.reset));let m=new Map;for(let w of I.tools)m.set(w.server,[...m.get(w.server)??[],w.name]);for(let[w,b]of m)console.log(` \u2022 ${i.cyan}${w}${i.reset} ${$(`${b.length} tool(s): ${b.slice(0,6).join(", ")}${b.length>6?", \u2026":""}`)}`);for(let[w,b]of I.errors)console.log(l("cli.run.0_unavailable_1"," \u2022 {0} \x1B[31munavailable\x1B[0m {1}",w,$(b)));Z.untrusted.length&&console.log(` \u2022 ${Z.untrusted.join(", ")} ${$(`untrusted \u2014 run \`${_.bin} mcp trust\``)}`),!I.serverCount&&!I.errors.size&&!Z.untrusted.length&&console.log($(` none. Add one: ${_.bin} mcp add <name> <command\u2026|url>`)),console.log("");continue}if(p==="/login"){try{await nn();let m=await Zn(e);n=m.client,s=m.label,r=m.apiUrl,A=e.model??(await oe()).defaultModel??m.model,Rt=A,(e.cascade||e.effort==="high"&&!e.model)&&(v=await Qn(e,s,A)),_e=null,we=[],await fn().catch(()=>{}),console.log(`
315
315
  ${i.assistantPrefix}\u2713 Active session updated: ${i.bold}${s}${i.reset} (${i.cyan}${A}${i.reset}). You can now continue chatting.
316
316
  `)}catch(m){console.error(`
317
317
  \x1B[31merror: Login failed:\x1B[0m ${m?.message??m}
318
- `)}continue}if(p==="/logout"){try{await Vt(),s="not logged in",n={chat:async()=>{throw new ne(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},v=null,_e=null,console.log($(`Token removed. Run /login to authenticate.
318
+ `)}continue}if(p==="/logout"){try{await on(),s="not logged in",n={chat:async()=>{throw new ne(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},v=null,_e=null,console.log($(`Token removed. Run /login to authenticate.
319
319
  `))}catch(m){console.error(`
320
320
  \x1B[31merror: Logout failed:\x1B[0m ${m?.message??m}
321
- `)}continue}if(p==="/reload"){try{let m=await Vn(t);n=m.client,s=m.label,r=m.apiUrl,A=t.model??(await oe()).defaultModel??m.model,vt=A,(t.cascade||t.effort==="high"&&!t.model)&&(v=await Xn(t,s,A)),_e=null,console.log(`
321
+ `)}continue}if(p==="/reload"){try{let m=await Zn(e);n=m.client,s=m.label,r=m.apiUrl,A=e.model??(await oe()).defaultModel??m.model,Rt=A,(e.cascade||e.effort==="high"&&!e.model)&&(v=await Qn(e,s,A)),_e=null,console.log(`
322
322
  ${i.assistantPrefix}\u2713 Reloaded configuration: ${i.bold}${s}${i.reset} (${i.cyan}${A}${i.reset}).
323
323
  `)}catch(m){console.error($(`
324
324
  Failed to reload configuration: ${m?.message??m}
325
- `))}continue}if(p==="/doctor"){await en();continue}if(p==="/config"){let m=await oe();console.log(`
325
+ `))}continue}if(p==="/doctor"){await ln();continue}if(p==="/config"){let m=await oe();console.log(`
326
326
  ${i.bold}Config:${i.reset}
327
327
  \u2022 Token: ${m.token?m.token.slice(0,6)+"\u2026"+m.token.slice(-4):"(not logged in)"}
328
328
  \u2022 Default model: ${m.defaultModel??"(none)"}
329
329
  \u2022 Backend: ${s} Model: ${A}
330
- `);continue}if(p.startsWith("!")){let m=p.slice(1).trim();if(m){console.log($(`$ ${m}`));let w=await Ye("run_shell",{command:m},g).catch(b=>b.message);console.log(w)}continue}let z=re,J=await Tt(p,A);if(J&&he++,console.log(""),z&&J&&process.stdin.isTTY){let m=at.createInterface({input:process.stdin,output:process.stdout}),w=(await m.question("? Execute this plan? [y/n]: ")).trim().toLowerCase();m.close(),(w==="y"||w==="yes")&&(re=!1,await Tt("Proceed with the plan above.",A,!1)&&he++,console.log(""))}await Mi(null,e,qs.observe(p))&&(u[0]={role:"system",content:await d()})}he>0&&await Os(e,null)}typeof Ls.setDefaultResultOrder=="function"&&Ls.setDefaultResultOrder("ipv4first");typeof Fs.setDefaultAutoSelectFamily=="function"&&Fs.setDefaultAutoSelectFamily(!1);var{version:ji}=Ci(import.meta.url)("../package.json"),se=new Pi(h.bin).description(`${h.name} \u2014 CLI coding agent`).version(ji);function Ds(t){return t.option("-p, --prompt <text>","run a single prompt headlessly").option("--model <id>","model id (see `models`)").option("--max-steps <n>","model calls per run (default 25, max 100)",e=>Number.parseInt(e,10)).option("--max-tokens <n>","soft token budget for one run (default 300000)",e=>Number.parseInt(e,10)).option("--cascade","start with the cheap default model; escalate to a stronger one only if the attempt fails").option("--effort <level>","low (default) or high: high goes straight to the strongest model your plan allows").option("--escalate-to <id>","model to escalate to (default: strongest on your plan, or SCOPE_ESCALATION_MODEL)").option("--verify <cmd>","with --cascade: a shell command (e.g. 'pnpm test'); if it fails the strong model takes over").option("--plan","plan mode: read-only exploration; prints a step-by-step plan instead of editing").option("-c, --continue","continue the most recent session of this project").option("-r, --resume [id]","resume a session by id (or pick one from a list)").option("--output-format <fmt>","headless output: text (default), json (one result object) or stream-json (event lines)").option("--append-system-prompt <text>","extra instructions added to the system prompt").option("--yolo","auto-approve tool calls (dangerous shell is still blocked)").addOption(new Ai("--allow-all","dev only: disable project-root restrictions").hideHelp())}var H=t=>async(...e)=>{try{await t(...e)}catch(n){console.error(l("cli.index.error_0","error: {0}",Ce(n,(await oe()).apiUrl))),process.exit(1)}},Us=t=>({prompt:t.prompt,model:t.model,yolo:t.yolo,allowAll:t.allowAll,maxSteps:t.maxSteps,maxTokens:t.maxTokens,cascade:t.cascade,effort:t.effort,escalateTo:t.escalateTo,verify:t.verify,plan:t.plan,continue:t.continue,resume:t.resume,outputFormat:t.outputFormat,appendSystemPrompt:t.appendSystemPrompt});function Ni(t=1500){return new Promise(e=>{let n="",o=!1,s=process.stdin,r=()=>{clearTimeout(c),s.off("data",a),s.off("end",r),s.off("error",r),s.pause(),e(n)},a=d=>{o=!0,n+=d},c=setTimeout(()=>{o||r()},t);s.setEncoding("utf8"),s.on("data",a),s.on("end",r),s.on("error",r)})}async function Ii(t){if(process.stdin.isTTY)return t;let e=(await Ni()).trim();return e?{...t,prompt:t.prompt?`${t.prompt}
330
+ `);continue}if(p.startsWith("!")){let m=p.slice(1).trim();if(m){console.log($(`$ ${m}`));let w=await Ze("run_shell",{command:m},g).catch(b=>b.message);console.log(w)}continue}let z=se,J=await Mt(p,A);if(J&&he++,console.log(""),z&&J&&process.stdin.isTTY){let m=dt.createInterface({input:process.stdin,output:process.stdout}),w=(await m.question("? Execute this plan? [y/n]: ")).trim().toLowerCase();m.close(),(w==="y"||w==="yes")&&(se=!1,await Mt("Proceed with the plan above.",A,!1)&&he++,console.log(""))}await Ai(null,t,zs.observe(p))&&(u[0]={role:"system",content:await d()})}he>0&&await Fs(t,null)}typeof Ds.setDefaultResultOrder=="function"&&Ds.setDefaultResultOrder("ipv4first");typeof Us.setDefaultAutoSelectFamily=="function"&&Us.setDefaultAutoSelectFamily(!1);var ee=new ji(_.bin).description(`${_.name} \u2014 CLI coding agent`).version(xe,"-v, --version","output the current version").option("-V","output the current version",()=>{console.log(xe),process.exit(0)});ee.command("version").description("output the current version").action(()=>{console.log(xe)});function Bs(e){return e.option("-p, --prompt <text>","run a single prompt headlessly").option("--model <id>","model id (see `models`)").option("--max-steps <n>","model calls per run (default 25, max 100)",t=>Number.parseInt(t,10)).option("--max-tokens <n>","soft token budget for one run (default 300000)",t=>Number.parseInt(t,10)).option("--cascade","start with the cheap default model; escalate to a stronger one only if the attempt fails").option("--effort <level>","low (default) or high: high goes straight to the strongest model your plan allows").option("--escalate-to <id>","model to escalate to (default: strongest on your plan, or SCOPE_ESCALATION_MODEL)").option("--verify <cmd>","with --cascade: a shell command (e.g. 'pnpm test'); if it fails the strong model takes over").option("--plan","plan mode: read-only exploration; prints a step-by-step plan instead of editing").option("-c, --continue","continue the most recent session of this project").option("-r, --resume [id]","resume a session by id (or pick one from a list)").option("--output-format <fmt>","headless output: text (default), json (one result object) or stream-json (event lines)").option("--append-system-prompt <text>","extra instructions added to the system prompt").option("--yolo","auto-approve tool calls (dangerous shell is still blocked)").addOption(new Ni("--allow-all","dev only: disable project-root restrictions").hideHelp())}var H=e=>async(...t)=>{try{await e(...t)}catch(n){console.error(l("cli.index.error_0","error: {0}",je(n,(await oe()).apiUrl))),process.exit(1)}},Ws=e=>({prompt:e.prompt,model:e.model,yolo:e.yolo,allowAll:e.allowAll,maxSteps:e.maxSteps,maxTokens:e.maxTokens,cascade:e.cascade,effort:e.effort,escalateTo:e.escalateTo,verify:e.verify,plan:e.plan,continue:e.continue,resume:e.resume,outputFormat:e.outputFormat,appendSystemPrompt:e.appendSystemPrompt});function Ii(e=1500){return new Promise(t=>{let n="",o=!1,s=process.stdin,r=()=>{clearTimeout(c),s.off("data",a),s.off("end",r),s.off("error",r),s.pause(),t(n)},a=d=>{o=!0,n+=d},c=setTimeout(()=>{o||r()},e);s.setEncoding("utf8"),s.on("data",a),s.on("end",r),s.on("error",r)})}async function Oi(e){if(process.stdin.isTTY)return e;let t=(await Ii()).trim();return t?{...e,prompt:e.prompt?`${e.prompt}
331
331
 
332
332
  <stdin>
333
- ${e}
334
- </stdin>`:e}:t}Ds(se).action(H(async t=>Zn(await Ii(Us(t)))));Ds(se.command("chat").description("interactive session in the current directory")).action(H(async t=>Zn(Us(t))));se.command("doctor").description("check your environment (node, git, login, MCP, hooks)").action(H(en));se.command("login").description("log in via browser").action(H(Yt));se.command("logout").description("remove the stored token").action(H(Vt));se.command("models").description("list available models or set default").argument("[model]","model id to set as default").action(H(async t=>Xt(t)));se.command("usage").description("show remaining credits").action(H(Zt));se.command("init").description(`create ${h.dirName}/skills.md and memory.md`).action(H(Qt));var Bs=se.command("skills").description(`project skills (${h.dirName}/skills.md) applied to every run`);Bs.command("list").description("show current skills").action(H(as));Bs.command("add").description('add a rule, e.g. skills add "Prefer pnpm"').argument("<text...>").action(H(async t=>ls(t)));var Qn=se.command("taste").description("share skills and memory with your team");Qn.command("push").description("publish this project's skills and memory").argument("[name]","package name (default: folder name)").option("--private","only you can pull it").option("-d, --description <text>","short description").action(H(async(t,e)=>cs(t,e)));Qn.command("pull").description("merge a package into this project").argument("<package>","namespace/name").action(H(async t=>ds(t)));Qn.command("list").description("browse public packages").argument("[query]").action(H(async t=>us(t)));var dn=se.command("mcp").description("MCP servers whose tools the agent can use");dn.command("list").description("connect and list tools").action(H(ms));dn.command("add").description("add a stdio command or HTTP URL").argument("<name>").argument("<command...>").action(H(async(t,e)=>ps(t,e)));dn.command("remove").description("remove a server").argument("<name>").action(H(async t=>gs(t)));dn.command("trust").description("approve this project's MCP servers after reviewing them").action(H(fs));var Ws=se.command("hooks").description(`PreToolUse/PostToolUse hook commands (${h.dirName}/hooks.json)`);Ws.command("list").description("show effective hooks").action(H(_s));Ws.command("trust").description("approve this project's hooks after reviewing them").action(H(ws));se.parseAsync();
333
+ ${t}
334
+ </stdin>`:t}:e}Bs(ee).action(H(async e=>eo(await Oi(Ws(e)))));Bs(ee.command("chat").description("interactive session in the current directory")).action(H(async e=>eo(Ws(e))));ee.command("doctor").description("check your environment (node, git, login, MCP, hooks)").action(H(ln));ee.command("login").description("log in via browser").action(H(nn));ee.command("logout").description("remove the stored token").action(H(on));ee.command("models").description("list available models or set default").argument("[model]","model id to set as default").action(H(async e=>sn(e)));ee.command("usage").description("show remaining credits").action(H(rn));ee.command("init").description(`create ${_.dirName}/skills.md and memory.md`).action(H(an));var qs=ee.command("skills").description(`project skills (${_.dirName}/skills.md) applied to every run`);qs.command("list").description("show current skills").action(H(ws));qs.command("add").description('add a rule, e.g. skills add "Prefer pnpm"').argument("<text...>").action(H(async e=>ys(e)));var to=ee.command("taste").description("share skills and memory with your team");to.command("push").description("publish this project's skills and memory").argument("[name]","package name (default: folder name)").option("--private","only you can pull it").option("-d, --description <text>","short description").action(H(async(e,t)=>bs(e,t)));to.command("pull").description("merge a package into this project").argument("<package>","namespace/name").action(H(async e=>xs(e)));to.command("list").description("browse public packages").argument("[query]").action(H(async e=>ks(e)));var gn=ee.command("mcp").description("MCP servers whose tools the agent can use");gn.command("list").description("connect and list tools").action(H($s));gn.command("add").description("add a stdio command or HTTP URL").argument("<name>").argument("<command...>").action(H(async(e,t)=>vs(e,t)));gn.command("remove").description("remove a server").argument("<name>").action(H(async e=>Ss(e)));gn.command("trust").description("approve this project's MCP servers after reviewing them").action(H(Ts));var Hs=ee.command("hooks").description(`PreToolUse/PostToolUse hook commands (${_.dirName}/hooks.json)`);Hs.command("list").description("show effective hooks").action(H(Es));Hs.command("trust").description("approve this project's hooks after reviewing them").action(H(Ms));ee.parseAsync();