@scopeide/cli 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +166 -167
- package/package.json +11 -10
package/dist/index.js
CHANGED
|
@@ -1,210 +1,209 @@
|
|
|
1
|
-
import
|
|
1
|
+
import Hs from"dns";import zs from"net";import{Command as Li,Option as Fi}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.12"};var O={maxSteps:100,hardMaxSteps:500,maxToolOutputBytes:12e3,maxContextTokens:32e3,warnContextTokens:24e3,maxRunTokens:0,charsPerToken:4};var It={strings:{}},tr=["maxSteps","hardMaxSteps","maxToolOutputBytes","maxContextTokens","warnContextTokens","maxRunTokens"];function kn(e){if(!e)return;let t=O;for(let n of tr){let o=e.limits?.[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&(t[n]=o)}if(e.strings&&typeof e.strings=="object"){It.strings={};for(let[n,o]of Object.entries(e.strings))/^(cli|agent|desktop)\./.test(n)&&typeof o=="string"&&(It.strings[n]=o.slice(0,4e3))}}function l(e,t,...n){let o=It.strings[e]??t;return n.length?o.replace(/\{(\d+)\}/g,(s,r)=>Number(r)<n.length?String(n[Number(r)]):s):o}var fe={maxBytes:5*1024*1024,maxPerMessage:6,keepInRequest:3,maxRequestBytes:6*1024*1024};import Oe from"os";import vt from"path";import{execFile as ks,spawn as ki}from"child_process";import T from"fs/promises";import lr from"fs";import yo from"os";import cr from"crypto";import M from"path";import{spawn as dr}from"child_process";import{z as j}from"zod";import{zodToJsonSchema as ur}from"zod-to-json-schema";import Ze from"path";function he(e,t){let n=Ze.resolve(e,t),o=Ze.relative(e,n),s=o===""||!o.startsWith("..")&&!Ze.isAbsolute(o);return{abs:n,inside:s}}function Be(e,t){let n=Ze.posix.resolve(e,t),o=Ze.posix.relative(e,n),s=o===""||!o.startsWith("..")&&!Ze.posix.isAbsolute(o);return{abs:n,inside:s}}import Me from"path";function ue(e,t){if(e.length<=t)return e;let n=Math.floor(t*.6),o=t-n;return`${e.slice(0,n)}
|
|
2
2
|
\u2026[${e.length-t} chars omitted]\u2026
|
|
3
|
-
${e.slice(e.length-o)}`}import
|
|
4
|
-
`).length;async function
|
|
3
|
+
${e.slice(e.length-o)}`}import $n from"path";var nr=[[/(^|[\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"]],or=/^(\/|\/\*|~|~\/|~\/\*|\$HOME|\$\{HOME\}|\$HOME\/|\$HOME\/\*|\*|\/(usr|etc|bin|sbin|var|lib|opt|home|Users|System|Library|Applications)\/?\*?)$/;function sr(e){let t=e.trim().split(/\s+/),n=t.findIndex(c=>$n.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=>or.test(c));return a?`recursive delete of "${a}"`:null}function Ot(e,t){for(let[n,o]of nr)if(n.test(e))return{ok:!1,reason:`blocked: ${o}`};for(let n of e.split(/&&|\|\||[;|\n]/)){let o=sr(n);if(o)return{ok:!1,reason:`blocked: ${o}`}}if(!t.allowAll){let n=t.posix?$n.posix:$n,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 rr=/(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i;function Lt(e){let t={};for(let[n,o]of Object.entries(e))rr.test(n)||n.startsWith("FORGE_")||n==="DATABASE_URL"||(t[n]=o);return t}var ir=1e6,vn=(e,t=O.maxToolOutputBytes)=>ue(e,t);function Ee(e,t,n){let{abs:o,inside:s}=Be(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&&Me.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 fo(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>ir)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 ar=(e,t)=>e.slice(0,t).split(`
|
|
4
|
+
`).length;async function ho(e,t,n){let o=n.remote;switch(e){case"read_file":return vn(await fo(o,Ee(n,t.path,!1),t.path));case"write_file":{let s=Ee(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=Ee(n,t.path,!0),r=await fo(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})",t.path,
|
|
8
|
-
`)||"(empty)"}case"grep":{let s=
|
|
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,ar(r,d))}case"list_dir":{let s=Ee(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)&&!We(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=Ee(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?wt(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=Me.posix.resolve(s,d[1]),p=Me.posix.relative(n.root,u);if(!We(Me.posix.basename(u))&&!(r&&!r.test(p)&&!r.test(Me.posix.basename(u)))&&(a.push(`${p}:${d[2]}: ${d[3].slice(0,300)}`),a.length>=200))return vn(a.join(`
|
|
9
9
|
`)+`
|
|
10
10
|
\u2026[200 match limit]`)}return a.join(`
|
|
11
|
-
`)||"no matches"}case"run_shell":{let s=
|
|
11
|
+
`)||"no matches"}case"run_shell":{let s=Ee(n,t.cwd??".",!1),r=Ot(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)`:"","",
|
|
16
|
-
`)||"no matching files found"}case"read_multiple_files":{let s=[];for(let r of t.paths)try{let a=await o.readFile(
|
|
17
|
-
${a.toString("utf8")}`)}catch(a){s.push(`=== ${r} (error: ${a.message}) ===`)}return
|
|
15
|
+
{4}`,c.code??"?",c.timedOut?` (timed out after ${a}ms)`:"","",ue(c.stdout,Math.floor(O.maxToolOutputBytes*.65)),ue(c.stderr,Math.floor(O.maxToolOutputBytes*.3)))}case"glob":{let s=Ee(n,t.path??".",!1),r=wt(t.pattern),a=[];for(let c of await o.walk(s)){if(We(Me.posix.basename(c)))continue;let d=Me.posix.relative(n.root,c);if((r.test(d)||r.test(Me.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(Ee(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 vn(s.join(`
|
|
18
18
|
|
|
19
|
-
`))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var
|
|
19
|
+
`))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var bo=new Set([".git","node_modules",".next","dist",".turbo",".forge",".command"]),Ft=new Set;function mr(){if(globalThis.__forgeCleanupRegistered)return;globalThis.__forgeCleanupRegistered=!0;let e=()=>{for(let t of Ft)try{lr.unlinkSync(t)}catch{}Ft.clear()};process.once("exit",e),process.once("SIGINT",()=>{e(),process.exit(130)}),process.once("SIGTERM",()=>{e(),process.exit(143)})}function We(e){return e.endsWith(".tmp")||e.includes(".tmp.")||e.includes(".cc-edit.tmp")||e.endsWith(".swp")||e.endsWith("~")||e.startsWith(".#")}async function pr(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
|
|
25
|
-
`).length}async function
|
|
24
|
+
`;await T.appendFile(s,a,"utf8")}}catch{}}async function xo(e){let t=0;try{let n=await T.readdir(e,{withFileTypes:!0});for(let o of n)if(o.isFile()&&We(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 pr(e).catch(()=>{});try{let n=M.join(yo.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 _o(e,t,n){mr();let o=M.join(yo.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`);Ft.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=cr.createHash("sha256").update(n).digest("hex").slice(0,8),p=M.join(o,"backups",`${d}-${u}`);await T.mkdir(p,{recursive:!0});let h=M.join(p,`${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{Ft.delete(r);try{await T.unlink(r)}catch{}}}var Qe={read_file:j.object({path:j.string().min(1)}),write_file:j.object({path:j.string().min(1),content:j.string()}),edit_file:j.object({path:j.string().min(1),old_string:j.string().min(1),new_string:j.string()}),list_dir:j.object({path:j.string().default(".")}),grep:j.object({pattern:j.string().min(1),path:j.string().optional(),glob:j.string().optional()}),run_shell:j.object({command:j.string().min(1),cwd:j.string().optional()}),glob:j.object({pattern:j.string().min(1),path:j.string().optional()}),read_multiple_files:j.object({paths:j.array(j.string().min(1)).min(1)}),think:j.object({thought:j.string().min(1)})},yt=Object.keys(Qe),gr={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 Rn(){return yt.map(e=>{let t=ur(Qe[e],{target:"openApi3",$refStrategy:"none"});return delete t.$schema,{name:e,description:l(`agent.tool.${e}.description`,gr[e]),parameters:t}})}var Sn=(e,t=O.maxToolOutputBytes)=>ue(e,t),ko=1e6;async function fr(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 Ce(e,t,n){let{abs:o,inside:s}=he(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 fr(o);if(!he(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 $o(e,t){return!(e.remote?Be:he)(e.root,t).inside}function wt(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*Tn(e){for(let t of await T.readdir(e,{withFileTypes:!0}))t.isDirectory()?bo.has(t.name)||(yield*Tn(M.join(e,t.name))):t.isFile()&&!We(t.name)&&(yield M.join(e,t.name))}async function wo(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>ko)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 hr(e,t){return e.slice(0,t).split(`
|
|
25
|
+
`).length}async function et(e,t,n){if(n.remote)return ho(e,t,n);switch(e){case"read_file":{let o=await Ce(n,t.path,!1);return Sn(await wo(o,t.path))}case"write_file":{let o=await Ce(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 _o(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 Ce(n,t.path,!0),s=await wo(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
|
|
29
|
-
`)||"(empty)"}case"grep":{let o=await
|
|
30
|
-
`);for(let v=0;v<R.length;v++)if(s.test(R[v])&&d.push(`${
|
|
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 _o(o,s.slice(0,c)+a+s.slice(c+r.length),n.root),l("agent.tools.edited_file","edited {0} (line {1})",t.path,hr(s,c))}case"list_dir":{let o=await Ce(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=>!bo.has(a.name)&&!We(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 Ce(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?wt(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]:Tn(o),d=[];for await(let u of c){let p=M.relative(n.root,u);if(r&&!r.test(p)&&!r.test(M.basename(u)))continue;let h;try{if((await T.stat(u)).size>ko)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(`${p}:${v+1}: ${R[v].slice(0,300)}`),d.length>=200)return Sn(d.join(`
|
|
31
31
|
`)+`
|
|
32
32
|
\u2026[200 match limit]`)}return d.join(`
|
|
33
|
-
`)||"no matches"}case"run_shell":{let o=await
|
|
34
|
-
`)||"no matching files found"}case"read_multiple_files":{let o=[];for(let s of t.paths)try{let r=await
|
|
35
|
-
${a.toString("utf8")}`)}catch(r){o.push(`=== ${s} (error: ${r.message}) ===`)}return
|
|
33
|
+
`)||"no matches"}case"run_shell":{let o=await Ce(n,t.cwd??".",!1),s=Ot(t.command,{root:n.root,cwd:o,allowAll:n.allowAll});if(!s.ok)throw new Error(s.reason);return await _r(t.command,o,n.shellTimeoutMs??12e4)}case"glob":{let o=await Ce(n,t.path??".",!1),s=wt(t.pattern),r=[];for await(let a of Tn(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 Ce(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 Sn(o.join(`
|
|
36
36
|
|
|
37
|
-
`))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var
|
|
37
|
+
`))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var Dt=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
|
|
39
|
+
${this.tail}`:this.head+this.tail}};function _r(e,t,n){return new Promise(o=>{let s=dr("/bin/sh",["-c",e],{cwd:t,env:Lt(process.env),detached:!0,stdio:["ignore","pipe","pipe"]}),r=!1,a=new Dt,c=new Dt;s.stdout.on("data",p=>a.add(p)),s.stderr.on("data",p=>c.add(p));let d=setTimeout(()=>{r=!0;try{process.kill(-s.pid,"SIGKILL")}catch{}},n),u=(p,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}`,
|
|
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
|
|
45
|
-
\u2026[truncated]`:t}catch{return null}}function
|
|
43
|
+
{4}`,p??"?",r?` (timed out after ${n}ms)`:"",h,ue(a.text(),Math.floor(O.maxToolOutputBytes*.65)),ue(c.text(),Math.floor(O.maxToolOutputBytes*.3))))};s.on("error",p=>u(127,` (${p.message})`)),s.on("close",p=>u(p))})}var vo={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"},So={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 wr(e){if(yt.includes(e))return e;let t=e.trim().toLowerCase().replace(/[-\s]/g,"_");return yt.includes(t)?t:vo[t]??vo[t.replace(/_/g,"")]??null}function To(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 yr(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 br(e){try{return JSON.parse(e)}catch{return}}function Ro(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":'),To(o),s>=0&&r>s?o.slice(s,r+1):o,s>=0?yr(To(o.slice(s)).replace(/,\s*$/,"")):o],c;for(let d of a)if(c=br(d),c!==void 0)break;if(c===void 0)return;t=c}return t}function xr(e,t){if(Object.keys(e).some(n=>n in t))return e;for(let n of["arguments","parameters","params","input","args"]){let o=Ro(e[n]);if(o&&typeof o=="object"&&!Array.isArray(o))return o}return e}function Ut(e,t){let n=wr(e);if(!n)return{ok:!1,error:`unknown tool "${e}". Available: ${yt.join(", ")}`};let o=Ro(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=Qe[n].shape,r=xr(o,s),a=Qe[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:So[h]??So[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=Qe[n].safeParse(d);if(u.success)return{ok:!0,name:n,args:u.data,repaired:!0};let p=u.error.issues.map(h=>`${h.path.join(".")||"(root)"}: ${h.message}`).join("; ");return{ok:!1,error:`invalid arguments for ${n}: ${p}. Expected: ${Object.keys(s).join(", ")}`}}import Mn from"fs/promises";import En from"path";var kr=12e3,Eo=500,Mo=8e3;async function Co(e,t){try{return he(await Mn.realpath(e),await Mn.realpath(t)).inside}catch{return!0}}async function Cn(e){try{let t=await Mn.readFile(e,"utf8");return t.length>Mo?t.slice(0,Mo)+`
|
|
45
|
+
\u2026[truncated]`:t}catch{return null}}function tt(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 Po(e,t){let n=[`Project root: ${e}`],o=async c=>await Co(e,c)?Cn(c):null,s=await o(En.join(e,_.dirName,"skills.md")),r=await o(En.join(e,_.dirName,"memory.md")),a=t?await Cn(En.join(t,_.dirName,"memory.md")):null;return tt(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
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
47
|
+
${tt(s)}`),tt(r)&&n.push(`## Project memory \u2014 facts about this project
|
|
48
|
+
${tt(r)}`),tt(a)&&n.push(`## Personal preferences \u2014 apply to all projects
|
|
49
|
+
${tt(a)}`),n.join(`
|
|
50
50
|
|
|
51
|
-
`)}async function
|
|
51
|
+
`)}async function Ao(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}=he(e,s);if(!a||!await Co(e,r))continue;let c=await Cn(r);if(c!==null){let d=ue(c,kr);o.push(`<file path="${s}">
|
|
52
52
|
${d}
|
|
53
53
|
</file>`)}}return o.length?`${t}
|
|
54
54
|
|
|
55
55
|
${o.join(`
|
|
56
56
|
|
|
57
|
-
`)}`:t}function
|
|
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
|
|
57
|
+
`)}`:t}function Bt(e){return ue(e,O.maxToolOutputBytes)}function Wt(e,t=O.maxContextTokens*O.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>Eo?{...r,content:r.content.slice(0,Eo)+`
|
|
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 nt(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/O.charsPerToken)}import Er from"fs/promises";import{spawn as $r}from"child_process";import qt from"fs/promises";import{createHash as vr}from"crypto";import ot from"path";var No=1e4,jo=2e3,Ht=["PreToolUse","PostToolUse"],Sr=e=>ot.join(e,_.dirName,"hooks.json"),Io=()=>({PreToolUse:[],PostToolUse:[]});async function Oo(e){let t=Io();try{let n=JSON.parse(await qt.readFile(e,"utf8"));for(let o of Ht){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 zt=e=>Oo(Sr(e)),qe=e=>Ht.reduce((t,n)=>t+e[n].length,0),Pn=e=>ot.join(e,_.dirName,"trusted-hooks.json"),Lo=e=>vr("sha256").update(JSON.stringify(e)).digest("hex");async function Fo(e){try{return JSON.parse(await qt.readFile(Pn(e),"utf8"))}catch{return{}}}async function Do(e,t){let n=await Fo(t);n[ot.resolve(e)]=Lo(await zt(e)),await qt.mkdir(ot.dirname(Pn(t)),{recursive:!0}),await qt.writeFile(Pn(t),JSON.stringify(n,null,2),{mode:384})}async function bt(e,t){let n=await Oo(ot.join(t,_.dirName,"hooks.json")),o=await zt(e),s=qe(o)===0||(await Fo(t))[ot.resolve(e)]===Lo(o),r={...Io(),untrusted:s?[]:Ht.flatMap(a=>o[a])};for(let a of Ht)r[a]=[...n[a],...s?o[a]:[]];return r}function Tr(e,t,n){return new Promise(o=>{let s="",r="",a=!1,c=p=>{a||(a=!0,clearTimeout(u),o(p))},d=$r("/bin/sh",["-c",e.command],{cwd:n,env:Lt(process.env),stdio:["pipe","pipe","pipe"]}),u=setTimeout(()=>{d.kill("SIGKILL"),c({code:null,text:"",error:`timed out after ${No/1e3}s`})},No);d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),d.stdout.on("data",p=>{s=(s+p).slice(0,jo)}),d.stderr.on("data",p=>{r=(r+p).slice(0,jo)}),d.on("error",p=>c({code:null,text:"",error:`cannot start: ${p.message}`})),d.on("close",p=>c({code:p,text:r.trim()||s.trim()})),d.stdin.on("error",()=>{}),d.stdin.end(JSON.stringify(t))})}var Rr=(e,t)=>{if(!e.matcher)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!1}};async function An(e,t,n,o){let s={warnings:[]},r=e?.[t]?.filter(c=>Rr(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 Tr(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 zo=new Set(["read_file","list_dir","grep","glob","read_multiple_files","think"]),Uo=`
|
|
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
|
|
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 Mr(e,t,n){return e==="run_shell"?`run shell command: ${t.command}${t.cwd?` (in ${t.cwd})`:""}`:(e==="write_file"||e==="edit_file")&&$o(n,t.path)?`${e} OUTSIDE project root: ${t.path}`:null}var Go=(e,t=O.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,Bo=!!process.env.FORGE_TIMING,Wo=new Set(["read_file","list_dir","grep","glob","read_multiple_files"]);function Cr(e,t){if(e.length<2)return!1;let n=t.opts.hooks;return n&&(n.PreToolUse.length||n.PostToolUse.length)?!1:e.every(o=>{if(!Wo.has(o.name)||t.opts.mcp?.has(o.name))return!1;let s=Ut(o.name,o.arguments);return s.ok&&Wo.has(s.name)})}async function st(e){let{client:t,model:n,messages:o,onEvent:s}=e,r={opts:e,specs:e.plan?Rn().filter(h=>zo.has(h.name)):[...Rn(),...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??O.maxSteps),O.hardMaxSteps),c=e.maxRunTokens??O.maxRunTokens,d="",u=!1;if(e.plan){let h=o[o.length-1];h?.role==="user"&&!h.content.endsWith(Uo)&&(h.content+=Uo)}let p=(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 p(h-1,"interrupted");if(c>0&&r.usage.promptTokens+r.usage.completionTokens>=c)return p(h-1,"token_budget");let R=Wt(o),v=nt(R);if(!u&&v>=O.warnContextTokens&&(u=!0,s?.({type:"context_warning",tokens:v})),e.signal?.aborted)return p(h-1,"interrupted");let B=!1,Q=e.stream?ee=>{B=!0,s?.({type:"token",text:ee})}:void 0,Y=Date.now(),q=await t.chat({model:n,messages:R,tools:r.specs,onToken:Q});if(Bo&&console.error(`[forge-timing] step ${h}: model ${Date.now()-Y}ms, ~${v} prompt tokens, ${q.toolCalls.length} tool call(s)`),e.signal?.aborted)return p(h,"interrupted");if(Jo(r,q.usage),o.push({role:"assistant",content:q.content,tool_calls:q.toolCalls.length?q.toolCalls:void 0}),q.content&&(d=q.content,s?.({type:"assistant",text:q.content,streamed:B})),!q.toolCalls.length)return p(h,"done");let ae=Date.now();if(Cr(q.toolCalls,r)){let ee=q.toolCalls.map(()=>[]),ve=await Promise.all(q.toolCalls.map((pt,gt)=>Ho(pt,r,oe=>ee[gt].push(oe))));if(e.signal?.aborted)return p(h,"interrupted");q.toolCalls.forEach((pt,gt)=>{for(let oe of ee[gt])s?.(oe);o.push({role:"tool",tool_call_id:pt.id,content:Bt(ve[gt])})})}else for(let ee of q.toolCalls){if(e.signal?.aborted)return p(h,"interrupted");let ve=await Ho(ee,r);o.push({role:"tool",tool_call_id:ee.id,content:Bt(ve)})}Bo&&console.error(`[forge-timing] step ${h}: tools ${q.toolCalls.map(ee=>ee.name).join(",")} ${Date.now()-ae}ms`)}return p(a,"max_steps")}var Jo=(e,t)=>{e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.cacheReadTokens=(e.usage.cacheReadTokens??0)+(t.cacheReadTokens??0)};async function Pr(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
61
|
Tool: ${e.name}
|
|
62
62
|
Arguments: ${e.arguments.slice(0,2e3)}
|
|
63
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:
|
|
65
|
-
`))>=0;)u(r.slice(0,R).replace(/\r$/,"")),r=r.slice(R+1)}r.trim()&&u(r.trim())}catch(
|
|
66
|
-
[${s.images.length} earlier image(s) omitted]`}:s)}function
|
|
67
|
-
`})}}]}}]}}var
|
|
64
|
+
Re-issue exactly that action as ONE corrected tool call with valid JSON arguments.`;try{let u=await o.chat({model:s,messages:Wt([...c,{role:"user",content:d}]),tools:n.specs});Jo(n,u.usage);let p=u.toolCalls[0];return p?Ut(p.name,p.arguments):{ok:!1,error:t}}catch{return{ok:!1,error:t}}}async function Ar(e,t){let{abs:n,inside:o}=(e.remote?Be:he)(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 Er.stat(n);return s.isFile()?{abs:n,sig:`${s.mtimeMs}:${s.size}`}:null}catch{return null}}function Nr(e,t){return Wt(e.opts.messages).some(n=>n.role==="tool"&&n.tool_call_id===t.callId&&n.content===t.content)}var qo=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 Ko(e,t,n,o=s=>n.opts.onEvent?.(s)){let s=await An(n.opts.hooks,"PreToolUse",n.opts.ctx.root,{tool:e,args:t});for(let a of s.warnings)o({type:"hook_warning",name:e,message:a});if(s.blocked===void 0)return null;let r=`BLOCKED by hook: ${s.blocked}`;return o({type:"tool_result",name:e,ok:!1,output:r}),r}async function Gt(e,t,n,o,s,r=a=>s.opts.onEvent?.(a)){let a=await An(s.opts.hooks,"PostToolUse",s.opts.ctx.root,{tool:e,args:t,ok:n,output:o});for(let c of a.warnings)r({type:"hook_warning",name:e,message:c})}async function jr(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 Ko(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 Gt(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 Gt(e.name,s,!1,c,t),`ERROR: ${c}`}}async function Ho(e,t,n=o=>t.opts.onEvent?.(o)){if(t.opts.plan&&!zo.has(e.name))return n({type:"tool_result",name:e.name,ok:!1,output:qo(e.name)}),qo(e.name);if(t.opts.mcp?.has(e.name))return jr(e,t);let o=Ut(e.name,e.arguments);if(o.ok&&o.repaired&&n({type:"repair",name:o.name,via:"normalize"}),!o.ok){let p=await Pr(e,o.error,t);p.ok&&n({type:"repair",name:p.name,via:"model"}),o=p.ok?p: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 Ko(s,r,t,n);if(a)return a;let c={...t.opts.ctx},d=null;if(s==="read_file"){d=await Ar(c,r.path);let p=d&&t.reads.get(d.abs);if(p&&d&&p.sig===d.sig&&Nr(t,p)){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=Mr(s,r,c);if(u&&!t.opts.yolo&&!t.alwaysAllow.has(s)){let p=t.opts.approve?await t.opts.approve({name:s,args:r,reason:u}):!1;if(!p)return n({type:"denied",name:s}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";p==="always"&&t.alwaysAllow.add(s)}u&&(s==="write_file"||s==="edit_file")&&(c.allowOutside=!0);try{let p=await et(s,r,c);return s==="write_file"||s==="edit_file"?(t.changed.add(r.path),t.reads.delete((c.remote?Be:he)(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:Bt(p)}),n({type:"tool_result",name:s,ok:!0,output:p}),await Gt(s,r,!0,p,t,n),p}catch(p){let h=p instanceof Error?p.message:String(p);return t.toolErrors++,n({type:"tool_result",name:s,ok:!1,output:h}),await Gt(s,r,!1,h,t,n),`ERROR: ${h}`}}var re=class extends Error{constructor(n,o,s){super(o);this.status=n;this.body=s}status;body;get code(){return this.body?.error?.code}},Ir="The selected model is temporarily unavailable. Please try again shortly, or switch models with /model.";function Yo(e,t){return[401,402,403,429].includes(e)?t:e>=500?Ir:t}var Pe=class extends Error{constructor(n,o){super(`cannot reach server (${o})`);this.url=n;this.reason=o}url;reason},Or=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","ETIMEDOUT","EAI_AGAIN","ECONNRESET","ENETUNREACH"]),Lr=3,Fr=new Set([429,500,502,503,504]),Dr=1e4;function Ur(e,t=1e3){let n=e?Number(e):NaN;return Math.min(Dr,Number.isFinite(n)&&n>=0?n*1e3:t)}var Jt=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:qr(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(Or.has(R)&&a<=Lr){let v=1e3*2**(a-1);this.cfg.onRetry?.({status:0,attempt:a,delayMs:v}),await r(v);continue}throw new Pe(n,R??h?.name??h?.message??"network error")}if(c.ok)return t.onToken&&c.body?await Wr(c.body,t.onToken,n):Br(await c.json());let d=await c.text();if(Fr.has(c.status)&&a===1){let h=Ur(c.headers.get("retry-after"));this.cfg.onRetry?.({status:c.status,attempt:a,delayMs:h}),await r(h);continue}let u,p=d;try{u=JSON.parse(d),p=u.error?.message??u.error??d}catch{}throw new re(c.status,Yo(c.status,typeof p=="string"?p:JSON.stringify(p)),u)}}};function Br(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:Vo(e.usage)}}}function Vo(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 Wr(e,t,n="stream"){let o=e.getReader(),s=new TextDecoder,r="",a="",c,d=new Map,u=p=>{if(!p.startsWith("data:"))return;let h=p.slice(5).trim();if(!h||h==="[DONE]")return;let R;try{R=JSON.parse(h)}catch{return}if(R.error)throw new re(502,Yo(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 B of v.tool_calls??[]){let Q=B.index??0,Y=d.get(Q)??{id:"",name:"",arguments:""};B.id&&(Y.id=B.id),B.function?.name&&(Y.name+=B.function.name),typeof B.function?.arguments=="string"&&(Y.arguments+=B.function.arguments),d.set(Q,Y)}}};try{for(;;){let{done:p,value:h}=await o.read();if(p)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(p){throw p instanceof re?p:new Pe(n,p?.cause?.code??p?.name??p?.message??"stream interrupted")}return{content:a||null,toolCalls:[...d.entries()].sort((p,h)=>p[0]-h[0]).map(([p,h])=>({id:h.id||`call_${p}`,name:h.name,arguments:h.arguments||"{}"})),usage:{promptTokens:c?.prompt_tokens??0,completionTokens:c?.completion_tokens??0,cacheReadTokens:Vo(c)}}}function qr(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(-fe.keepInRequest).reverse()){let r=e[s].images.reduce((a,c)=>a+c.data.length,0);if(n.size>0&&o+r>fe.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 Hr(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)?"":";",p=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(${p.includes(d)?JSON.stringify(p):d+p+d})${u}
|
|
67
|
+
`})}}]}}]}}var He=class{async chat(t){let n=Hr(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 Nn from"fs/promises";import Xo from"path";async function xt(e,t){let n=t.replace(/\s+/g," ").trim().replace(/^[-*]\s*/,"").slice(0,300);if(!n)throw new Error("empty learning");let o=Xo.join(e,_.dirName,"memory.md");await Nn.mkdir(Xo.dirname(o),{recursive:!0});let s="";try{s=await Nn.readFile(o,"utf8")}catch{}let r=s===""?`# Project memory
|
|
68
68
|
|
|
69
69
|
`:s.endsWith(`
|
|
70
70
|
`)?"":`
|
|
71
|
-
`;return await
|
|
72
|
-
`),o}import
|
|
71
|
+
`;return await Nn.appendFile(o,`${r}- ${n}
|
|
72
|
+
`),o}import rt from"fs/promises";import Kt from"path";var Zo=300,it=e=>Kt.join(e,_.dirName,"skills.md"),kt=e=>Kt.join(e,_.dirName,"memory.md");function jn(e){return e.replace(/<!--[\s\S]*?-->/g,"").split(/\r?\n/).map(t=>t.match(/^\s*[-*]\s+(.+?)\s*$/)?.[1]).filter(t=>!!t)}function zr(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>Zo)throw new Error(`skill is too long (${t.length} > ${Zo} chars); keep it to one short rule`);return t}var Ae=e=>e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();async function In(e){try{return await rt.readFile(e,"utf8")}catch{return""}}async function ze(e){return jn(await In(it(e)))}async function Ne(e){return jn(await In(kt(e)))}var Qo=`# Project skills
|
|
73
73
|
|
|
74
|
-
`;async function
|
|
74
|
+
`;async function at(e,t){let n=zr(t),o=it(e),s=await In(o);if(jn(s).some(a=>Ae(a)===Ae(n)))return{added:!1,skill:n,file:o};await rt.mkdir(Kt.dirname(o),{recursive:!0});let r=s===""?Qo:s.endsWith(`
|
|
75
75
|
`)?"":`
|
|
76
|
-
`;return await
|
|
77
|
-
`),{added:!0,skill:n,file:o}}async function
|
|
76
|
+
`;return await rt.appendFile(o,`${r}- ${n}
|
|
77
|
+
`),{added:!0,skill:n,file:o}}async function On(e){let t=[],n=[[it(e),`${Qo}<!-- One rule per bullet, e.g.
|
|
78
78
|
- Use pnpm, not npm
|
|
79
79
|
-->
|
|
80
|
-
`],[
|
|
80
|
+
`],[kt(e),`# Project memory
|
|
81
81
|
|
|
82
82
|
<!-- Facts worth remembering, one per bullet. -->
|
|
83
|
-
`]];for(let[o,s]of n)try{await
|
|
84
|
-
`),n}var
|
|
83
|
+
`]];for(let[o,s]of n)try{await rt.access(o)}catch{await rt.mkdir(Kt.dirname(o),{recursive:!0}),await rt.writeFile(o,s),t.push(o)}return t}var Gr=[/^\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],Jr=/\b(again|i (told|said|already)|as i (said|mentioned)|every time|always|never|from now on|once more)\b/i,Kr=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 es(e){return new Set(e.toLowerCase().replace(/[^a-z0-9+#.\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!Kr.has(t)))}function ts(e,t){let n=es(e),o=es(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 Yr(e){let t=e.trim();return!t||t.length>400||t.startsWith("/")||t.endsWith("?")?!1:Gr.some(n=>n.test(t))}function Vr(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 Xr=.4,Yt=class{seen=[];known;constructor(t=[]){this.known=[...t]}observe(t){if(!Yr(t))return null;let n=Vr(t);if(!n)return null;let o=this.seen.some(r=>ts(r,t)>=Xr);this.seen.push(t);let s=Jr.test(t);return!o&&!s||this.known.some(r=>Ae(r)===Ae(n)||ts(r,n)>=.6)?null:(this.known.push(n),{rule:n,reason:o?"repeated":"explicit"})}};async function ns(e){let{cheap:t,strong:n,verify:o,maxToolErrors:s=3,...r}=e,a=await st({...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 st({...r,client:n.client,model:n.model,maxRunTokens:(r.maxRunTokens??O.maxRunTokens)<=0?0:Math.max(5e4,(r.maxRunTokens??O.maxRunTokens)-d)}),p={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:p,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 Zr}from"child_process";import lt from"fs/promises";import{createHash as Qr}from"crypto";import Ge from"path";var ei="2025-03-26",ti=6e4,os=2e4,ss=1e5,Xt=e=>Ge.join(e,_.dirName,"mcp.json");async function Vt(e){try{let t=JSON.parse(await lt.readFile(e,"utf8"));return{servers:t&&typeof t.servers=="object"&&t.servers?t.servers:{}}}catch{return{servers:{}}}}var Ln=e=>Ge.join(e,_.dirName,"trusted-mcp.json"),is=e=>Qr("sha256").update(JSON.stringify(e.servers)).digest("hex");async function as(e){try{return JSON.parse(await lt.readFile(Ln(e),"utf8"))}catch{return{}}}async function Zt(e,t){let n=await as(t);n[Ge.resolve(e)]=is(await Vt(Xt(e))),await lt.mkdir(Ge.dirname(Ln(t)),{recursive:!0}),await lt.writeFile(Ln(t),JSON.stringify(n,null,2),{mode:384})}async function $t(e,t){let n=await Vt(Ge.join(t,_.dirName,"mcp.json")),o=await Vt(Xt(e)),s=Object.keys(o.servers).length===0||(await as(t))[Ge.resolve(e)]===is(o);return{servers:{...n.servers,...s?o.servers:{}},untrusted:s?[]:Object.keys(o.servers)}}async function Un(e,t){let n=Xt(e);return await lt.mkdir(Ge.dirname(n),{recursive:!0}),await lt.writeFile(n,JSON.stringify(t,null,2)+`
|
|
84
|
+
`),n}var Qt=e=>Vt(Xt(e)),Fn=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=Zr(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
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
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
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{}}},
|
|
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(){}},
|
|
90
|
-
`),a=r.length>
|
|
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
|
|
88
|
+
`)}close(){try{this.child.kill()}catch{}}},Dn=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(){}},rs=e=>e.replace(/[^a-zA-Z0-9_-]+/g,"_"),ni=(e,t)=>`mcp__${rs(e)}__${rs(t)}`.slice(0,64),ct=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 Dn(n);else if(n.command)s=new Fn(n,o);else throw new Error('needs "command" or "url"');await s.request("initialize",{protocolVersion:ei,capabilities:{},clientInfo:{name:_.bin,version:"0.1.0"}},os),await s.notify("notifications/initialized");let r;do{let a=await s.request("tools/list",r?{cursor:r}:{},os);for(let c of a.tools??[]){let d=ni(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??{}},ti),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>ss?r.slice(0,ss)+`
|
|
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 oi}from"child_process";import en from"fs/promises";import ls from"os";import _e from"path";var si={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function ri(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 ii(e){if(process.platform!=="darwin")return Promise.resolve(null);let t=_e.join(ls.tmpdir(),`forge-shrink-${process.pid}-${Date.now()}.jpg`);return new Promise(n=>{oi("sips",["-Z","1600","-s","format","jpeg","-s","formatOptions","80",e,"--out",t],async o=>{if(o)return n(null);try{n(await en.readFile(t))}catch{n(null)}finally{en.rm(t,{force:!0}).catch(()=>{})}})})}async function ai(e,t=ii){let n=_e.extname(e).toLowerCase();if(!(n in si))throw new Error(`${_e.basename(e)}: not a supported image type (png, jpg, gif, webp)`);let o=await en.readFile(e),s=ri(o);if(!s)throw new Error(`${_e.basename(e)}: file content is not a valid ${n.slice(1)} image`);if(o.length>fe.maxBytes/2&&s!=="image/gif"){let r=await t(e);r&&r.length<o.length&&(o=r,s="image/jpeg")}if(o.length>fe.maxBytes)throw new Error(`${_e.basename(e)}: image is ${(o.length/1048576).toFixed(1)} MB (max ${fe.maxBytes/1048576} MB)`);return{mediaType:s,data:o.toString("base64"),name:_e.basename(e)}}var Bn="(?:png|jpe?g|gif|webp)",li=new RegExp(`(^|\\s)(@?)(?:"([^"\\n]+\\.${Bn})"|'([^'\\n]+\\.${Bn})'|((?:\\\\ |[^\\s"'])+\\.${Bn}))(?=\\s|$|[.,;:!?)]$)`,"gi");async function cs(e,t,n=ls.homedir()){let o=[],s=[],r=new Map,a=[...t.matchAll(li)],c="",d=0;for(let u of a){let p=(u[3]??u[4]??u[5]??"").replace(/\\ /g," "),h=p.startsWith("~/")?_e.join(n,p.slice(2)):_e.resolve(e,p),R=(u.index??0)+u[1].length,v=(u.index??0)+u[0].length,B=r.get(h);if(B===void 0){try{await en.access(h)}catch{continue}if(o.length>=fe.maxPerMessage){s.push(`only ${fe.maxPerMessage} images per message; skipped ${_e.basename(h)}`);continue}try{o.push(await ai(h)),B=o.length,r.set(h,B)}catch(Q){s.push(Q instanceof Error?Q.message:String(Q));continue}}c+=t.slice(d,R)+`[Image #${B}: ${_e.basename(h)}]`,d=v}return{text:c+t.slice(d),images:o,errors:s}}import tn from"fs/promises";import ci from"os";import ds from"path";var us=()=>ds.join(ci.homedir(),_.dirName),Wn=()=>ds.join(us(),"config.json");async function ie(){let e={};try{e=JSON.parse(await tn.readFile(Wn(),"utf8"))}catch{}return{apiUrl:_.defaultApiUrl,token:process.env.SCOPE_API_KEY??process.env.FORGE_API_KEY??e.token,defaultModel:e.defaultModel}}async function Je(e){let t={};try{t=JSON.parse(await tn.readFile(Wn(),"utf8"))}catch{}let n={...t,...e};delete n.apiUrl;for(let o of Object.keys(n))n[o]===void 0&&delete n[o];await tn.mkdir(us(),{recursive:!0}),await tn.writeFile(Wn(),JSON.stringify(n,null,2),{mode:384})}async function Z(e,t={}){let n=await ie(),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 Pe("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 re(r.status,d,a)}return a}import ui from"fs/promises";import ms from"path";import{spawn as _s}from"child_process";import{StringDecoder as mi}from"string_decoder";import{createRequire as di}from"module";var $e=di(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 sn(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 pi=`
|
|
92
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
|
|
93
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
|
|
94
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
|
|
95
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
|
|
96
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
|
|
97
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
|
|
98
|
-
`.trim(),
|
|
99
|
-
`).map((e,t)=>{let[n,o,s]=
|
|
100
|
-
`)}function
|
|
101
|
-
${i.bold}${_.name}${i.reset} ${i.dim}v${
|
|
98
|
+
`.trim(),ps=[[255,214,120],[255,190,90],[255,165,70],[255,140,62],[245,115,55],[225,95,48]];function gi(){return pi.split(`
|
|
99
|
+
`).map((e,t)=>{let[n,o,s]=ps[Math.min(t,ps.length-1)];return`\x1B[38;2;${n};${o};${s}m${e}${i.reset}`}).join(`
|
|
100
|
+
`)}function Gn(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?gi():`${i.userPointer}${i.bold}${_.name}${i.reset}`),console.log(`
|
|
101
|
+
${i.bold}${_.name}${i.reset} ${i.dim}v${$e}${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(`
|
|
102
102
|
${i.dim} / commands \xB7 @ files \xB7 ! shell \xB7 esc interrupts \xB7 ? shortcuts${i.reset}
|
|
103
|
-
`)}var
|
|
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
|
|
103
|
+
`)}var fi=["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 nn(){let e=l("cli.ui.status_words",fi.join("|")).split("|").map(t=>t.trim()).filter(Boolean);return e[Math.floor(Math.random()*e.length)]??"Working\u2026"}var qn=["\xB7","\u2727","\u2726","\u2736","\u2737","\u2736","\u2726","\u2727","\xB7"],gs=[12,5,4,4,4,4,4,5,16],fs=[5,4,4,4,4,4,5];function hi(e){let t=e%88,n=0;for(let s=0;s<gs.length;s++)if(n+=gs[s],t<n)return qn[s];let o=t-58;n=0;for(let s=0;s<fs.length;s++)if(n+=fs[s],o<n)return qn[7-s];return qn[0]}var hs=["#E5733A","#FF9A52","#FFB347","#FFD08A","#FFF1DC","#FFD08A","#FFB347","#FF9A52","#E5733A"],_i="#9A5A3A";function wi(e){let t=parseInt(e.replace("#",""),16);return`\x1B[38;2;${t>>16&255};${t>>8&255};${t&255}m`}function yi(e,t,n,o){let s=hi(4*t),r=t%(e.length+10),a="";for(let u=0;u<e.length;u++){let p=u-(r-5),h=p>=0&&p<hs.length?hs[p]:_i;a+=wi(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 bi=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Ke=e=>Array.from(bi.segment(e),t=>t.segment);function we(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 xi(e,t){let n=Ke(e),o=0;for(;o<n.length&&we(n.slice(o).join(""))>t;)o++;return n.slice(o).join("")}function rn(e,t){let n=Ke(e.slice(0,t));return n.pop(),n.join("").length}function Jn(e,t){let n=Ke(e.slice(t));return t+(n[0]?.length??0)}var on=class{constructor(t,n){this.onInterrupt=t;this.input=n}onInterrupt;input;frame=0;startTime=Date.now();status=nn();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=nn()),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 mi("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,rn(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=[yi(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(we(d)<=u)return d;let p="";for(let h of Ke(d)){if(we(p+h)>u-1)break;p+=h}return p+"\u2026"};o.queue.forEach((d,u)=>{let p=u===this.selected,h=r(`${u+1}. ${d}`,s-4);n.push(p?`${i.accent}${i.bold}\u276F ${h}${i.reset}`:`${i.gray}\u23F3 ${h}${i.reset}`)});let a=xi(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))}},zn=[{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 plan allowance (requests and dollars) and usage")}},{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")}}],Zl=zn.map(e=>e.command);function Ye(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 dt(e){let t=e.trim().toLowerCase();return t?zn.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):[...zn]}function ws(){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,$e)),console.log(l("cli.ui.0_ai_agent_that_pairs",`{0}{2}{1}
|
|
106
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
|
|
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 plan allowance: requests, dollars, 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",`
|
|
108
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",`
|
|
109
109
|
{0}\u276F{1} {2}Tip: Type {3}@{4} followed by a path or {5}/{6} for commands and press Tab to complete.{7}
|
|
110
|
-
`,i.cyan,i.reset,i.gray,i.cyan,i.reset,i.cyan,i.reset,i.reset))}function
|
|
111
|
-
\u2022 Please check your internet connection and try again.`}if(e instanceof
|
|
110
|
+
`,i.cyan,i.reset,i.gray,i.cyan,i.reset,i.cyan,i.reset,i.reset))}function Kn(){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 Yn(){console.log("");for(let e of Kn())console.log(e);console.log("")}async function ys(e){let n=process.platform==="darwin"?"pbcopy":"wl-copy";return new Promise(o=>{try{let s=_s(n,[],{stdio:["pipe","ignore","ignore"]});s.stdin.write(e),s.stdin.end(),s.on("close",r=>{if(r===0)return o(!0);Hn(e).then(o)}),s.on("error",()=>{Hn(e).then(o)})}catch{Hn(e).then(o)}})}function Hn(e){return new Promise(t=>{try{let n=_s("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 bs(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 ui.readdir(r,{withFileTypes:!0});for(let c of a){if(n.length>=t)break;if(o.has(c.name))continue;let d=ms.join(r,c.name),u=ms.relative(e,d);c.isDirectory()?(n.push(u+"/"),await s(d)):n.push(u)}}catch{}}return await s(e),n}var je=[];async function Vn(){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 xs=e=>e.replace(/https?:\/\/[^\s"'<>]+/gi,"server").trim();function Ie(e,t){if(e instanceof Pe){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 re){let o=e.body?.error??{},s=xs(e.message);switch(e.status){case 401:return s.includes("login")?s:`Not authorized: ${s}.
|
|
112
112
|
Run \`/login\` or \`${_.bin} login\` to authenticate.`;case 402:return`${s}
|
|
113
113
|
See \`${_.bin} usage\`. Upgrade in the dashboard (/app/billing) or wait for the reset.`;case 403:return`${s}
|
|
114
114
|
Run \`${_.bin} models\` to see what your plan includes.`;case 404:return`${s}
|
|
115
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=
|
|
117
|
-
\u2022 Try again after 00:00 UTC.`:n.includes("Insufficient Balance")?"The service is temporarily unavailable. Please try again shortly.":n}function
|
|
116
|
+
It was retried once. Try again shortly.`;default:return`${s} (HTTP ${e.status})`}}let n=xs(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 $i(e){if(process.env.FORGE_NO_BROWSER)return;let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{ki(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}async function an(){let e=await Z("/v1/auth/device/code",{method:"POST",auth:!1});console.log(l("cli.commands.open_0_and_confirm_code",`
|
|
118
118
|
Open {0}
|
|
119
119
|
and confirm code: {1}
|
|
120
|
-
`,e.verificationUrl,e.userCode))
|
|
120
|
+
`,e.verificationUrl,e.userCode)),$i(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 Z("/v1/auth/device/token",{method:"POST",auth:!1,body:JSON.stringify({deviceCode:e.deviceCode})}).catch(o=>{throw o});if(n.status==="approved"){await Je({token:n.apiKey});let o=await Z("/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 ln(){await Je({token:void 0}),console.log(l("cli.commands.logged_out","Logged out."))}async function cn(e){let t=await ie();if(e){await Je({defaultModel:e}),console.log(l("cli.commands.default_model_set_to_0","Default model set to: {0}",e));return}let n=await Z("/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
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
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
\u2192 ${g}`:""}`);console.log(l("cli.commands.0_doctor",`
|
|
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 dn(){let e=await Z("/v1/usage"),t=c=>c.toLocaleString(),n=(e.promptTokens??0)+(e.completionTokens??0),o=sn(n),s=!!e.monthlyOff,r=e.estimatedRequests??0,a=e.virtualCreditsUsd??0;console.log(l("cli.commands.plan_usage",`Plan: {0}
|
|
123
|
+
Requests: {1} of {2} used
|
|
124
|
+
Dollars: {3} of {4} used
|
|
125
|
+
Tokens: {5}`,e.plan,t(e.requests),s||!r?"no cap":t(r),`$${(e.usedUsd??0).toFixed(2)}`,s||!a?"no cap":`$${a.toFixed(2)}`,o))}async function un(){let e=await On(process.cwd());for(let t of[it(process.cwd()),kt(process.cwd())])console.log(`${e.includes(t)?"created":"exists "} ${vt.relative(process.cwd(),t)}`);console.log(l("cli.commands.add_a_rule_0_skills",`
|
|
126
|
+
Add a rule: {0} skills add "Use pnpm, not npm"`,_.bin))}async function $s(){let e=process.cwd(),[t,n]=[await ze(e),await Ne(e)];t.length?(console.log(l("cli.commands.skills_0_applied_to_every","Skills ({0}) \u2014 applied to every run:",vt.relative(e,it(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",`
|
|
127
|
+
Memory notes: {0} ({1})`,n.length,vt.relative(e,kt(e))))}async function vs(e){let t=await at(process.cwd(),e.join(" "));console.log(t.added?`Added skill: ${t.skill}
|
|
128
|
+
It will be used on the next run.`:`Already a skill: ${t.skill}`)}var vi=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);async function Ss(e,t){let n=process.cwd(),[o,s]=[await ze(n),await Ne(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 Z("/v1/taste",{method:"POST",body:JSON.stringify({name:vi(e??vt.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 Ts(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 Z(`/v1/taste/${e}`);await On(t);let o=0,s=0;for(let a of n.skills)(await at(t,a)).added&&(o++,console.log(l("cli.commands.skill_0"," + skill: {0}",a)));let r=new Set((await Ne(t)).map(Ae));for(let a of n.memory)r.has(Ae(a))||(await xt(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 Rs(e){let t=await Z(`/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 Es(){let e=process.cwd(),t=await $t(e,Oe.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
|
|
129
|
+
`,t.untrusted.join(", "),_.dirName,_.bin));let o=await ct.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(`
|
|
130
|
+
`)[0].slice(0,80)}`)}}finally{o.close()}}async function Ms(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 Qt(process.cwd());n.servers[e]=/^https?:\/\//.test(t[0])?{url:t[0]}:{command:t[0],args:t.slice(1)};let o=await Un(process.cwd(),n);await Zt(process.cwd(),Oe.homedir()),console.log(l("cli.commands.saved_0_to_1_check",'Saved "{0}" to {1}. Check it: {2} mcp list',e,vt.relative(process.cwd(),o),_.bin))}async function Cs(e){let t=await Qt(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 Un(process.cwd(),t),await Zt(process.cwd(),Oe.homedir()),console.log(l("cli.commands.removed_0",'Removed "{0}".',e))}async function Ps(){let e=await Qt(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 Zt(process.cwd(),Oe.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 As=(e,t=" ")=>{for(let n of["PreToolUse","PostToolUse"])for(let o of e[n])console.log(`${t}${n} [${o.matcher??"*"}]: ${o.command}`)};async function Ns(){let e=await bt(process.cwd(),Oe.homedir());if(!qe(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(qe(e)&&(console.log(l("cli.commands.effective_hooks","Effective hooks:")),As(e)),e.untrusted.length){console.log(l("cli.commands.not_run_untrusted_project_hooks",`
|
|
131
|
+
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 js(){let e=await zt(process.cwd());if(!qe(e))return console.log(l("cli.commands.no_project_hooks_in_0","No project hooks in {0}/hooks.json.",_.dirName));As(e),await Do(process.cwd(),Oe.homedir()),console.log(l("cli.commands.trusted_0_hook_s_they","Trusted {0} hook(s). They run until the file changes.",qe(e)))}async function mn(){let e=await ie(),t=process.cwd(),n=u=>console.log(` \x1B[32m\u2713\x1B[0m ${u}`),o=(u,p)=>console.log(` \x1B[31m\u2717\x1B[0m ${u}${p?`
|
|
132
|
+
\u2192 ${p}`:""}`);console.log(l("cli.commands.0_doctor",`
|
|
134
133
|
{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=>
|
|
134
|
+
`,_.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=>ks("git",["--version"],(p,h)=>u(p?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=>ks("git",["rev-parse","--is-inside-work-tree"],{cwd:t},p=>u(!p))):!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 Z("/v1/me");n(`logged in as ${u.email??"user"}`)}catch(u){o(`connection error: ${Ie(u)}`,`run \`${_.bin} login\` again`)}else o("not logged in",`run \`${_.bin} login\` (or set FORGE_API_KEY)`);let c=await $t(t,Oe.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 bt(t,Oe.homedir());console.log(l("cli.commands.0_hook_s_active_1"," - {0} hook(s) active{1}",qe(d),d.untrusted.length?`, ${d.untrusted.length} untrusted (run \`${_.bin} hooks trust\`)`:"")),console.log("")}import Rt from"fs/promises";import Qn from"os";import{execFile as Ai}from"child_process";import mt from"readline/promises";import{StringDecoder as Ni}from"string_decoder";import Le from"path";import Is from"crypto";import St from"fs/promises";import ut from"os";import pn from"path";var Si=/^[A-Za-z0-9_-]{6,64}$/,Ti=e=>Is.createHash("sha256").update(pn.resolve(e)).digest("hex").slice(0,16),Os=(e,t=ut.homedir())=>pn.join(t,_.dirName,"sessions",Ti(e)),gn=(e,t,n=ut.homedir())=>{if(!Si.test(t))throw new Error(l("cli.sessions.invalid_session_id","invalid session id"));return pn.join(Os(e,n),`${t}.json`)},fn=()=>Is.randomUUID().replace(/-/g,"").slice(0,12);function Tt(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 Ls(e,t,n=ut.homedir()){let o=gn(e,t.id,n);await St.mkdir(pn.dirname(o),{recursive:!0});let s=`${o}.${process.pid}.tmp`;return await St.writeFile(s,JSON.stringify(t),{mode:384}),await St.rename(s,o),o}async function Fs(e,t,n=ut.homedir()){try{return JSON.parse(await St.readFile(gn(e,t,n),"utf8"))}catch(o){if(o?.code==="ENOENT"||o instanceof SyntaxError)return null;throw o}}async function Xn(e,t=ut.homedir()){let n;try{n=await St.readdir(Os(e,t))}catch{return[]}let o=[];for(let s of n){if(!s.endsWith(".json"))continue;let r=await Fs(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 Zn(e,t,n=ut.homedir()){let o=await Xn(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?Fs(e,s.id,n):null}var hn=e=>e.flatMap((t,n)=>t.role==="user"?[n]:[]),_n=(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 Ri from"fs";import Ei from"os";import Ds from"path";function Mi(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 Ci=new Set(["FORGE_API_KEY","FORGE_API_URL"]),Pi=new Set(["FORGE_API_URL"]);function Us(e=process.cwd()){let t=Ds.join(Ei.homedir(),_.dirName,".env");for(let n of[Ds.join(e,".env"),t]){let o;try{o=Ri.readFileSync(n,"utf8")}catch{continue}for(let[s,r]of Object.entries(Mi(o)))Pi.has(s)&&n!==t||Ci.has(s)&&process.env[s]===void 0&&(process.env[s]=r)}}var $=e=>`\x1B[2m${e}\x1B[0m`,Bs=(e,t=200)=>(e.length>t?e.slice(0,t)+"\u2026":e).replace(/\n/g,"\u23CE ");function ji(e){e.type==="token"?process.stdout.write(e.text):e.type==="assistant"?console.log(`
|
|
136
135
|
${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} ${$(
|
|
136
|
+
`):e.type==="tool_start"?console.log(`${i.userPointer}\u2692${i.reset} ${i.bold}${e.name.replace(/_/g," ")}${i.reset} ${$(Bs(JSON.stringify(e.args),120))}`):e.type==="tool_result"?console.log($(` ${e.ok?"\u2713":"\u2717"} ${Bs(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 Ii=e=>console.error($(` \u21BB ${e.status?`server returned ${e.status}`:"connection problem"}; retrying in ${(e.delayMs/1e3).toFixed(1)}s\u2026`));async function eo(e){Us();let t=await ie(),n=e.model==="mock-model"||e.model==="mock";if(!!t.token){let s=e.model??t.defaultModel??"default";try{kn(await Z("/v1/models"))}catch{}if(!e.model)try{let r=await Z("/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 Je({defaultModel:d})}}catch{}return{client:new Jt({baseUrl:`${t.apiUrl.replace(/\/$/,"")}/v1`,apiKey:t.token,onRetry:Ii}),model:s,label:"gateway",apiUrl:t.apiUrl}}if(n)return{client:new He,model:"mock-model",label:"local mock"};if(!t.token){if(e.prompt)throw new re(401,"Not logged in \u2014 run `forge login` to authenticate.",{});return{client:{chat:async()=>{throw new re(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 to(e,t,n){let o=e.escalateTo??process.env.FORGE_ESCALATION_MODEL;if(o)return o;if(t!=="gateway")return null;let r=(await Z("/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 Ws(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??mt.createInterface({input:process.stdin,output:process.stdout}),r=(await s.question(`
|
|
138
137
|
? Allow ${o.reason}
|
|
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
|
|
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
|
|
138
|
+
[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 qs(e,t){if(!process.stdin.isTTY)return;let n=t??mt.createInterface({input:process.stdin,output:process.stdout});try{if(!(await n.question(`
|
|
139
|
+
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 xt(e,o);console.log(l("cli.run.saved_to_0","Saved to {0}",Le.relative(e,s)))}finally{t||n.close()}}async function Oi(e,t,n){if(!n||!process.stdin.isTTY)return!1;let o=e??mt.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
140
|
${s}. Save as a project skill?
|
|
142
141
|
\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
|
|
142
|
+
[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 at(t,a);return console.log(c.added?`Saved to ${Le.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 no(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 xo(t);let{client:n,model:o,label:s,apiUrl:r}=await eo(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 Po(t,Qn.homedir())+(e.appendSystemPrompt?`
|
|
144
143
|
|
|
145
|
-
${e.appendSystemPrompt}`:""),u=[{role:"system",content:await d()}],
|
|
144
|
+
${e.appendSystemPrompt}`:""),u=[{role:"system",content:await d()}],p={root:t,allowAll:e.allowAll},h=e.maxSteps??0,R=e.maxTokens??0,v=null;(e.cascade||e.effort==="high"&&!e.model)&&(v=await to(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 B=e.effort==="high"&&!e.model&&v?v:o,Q=await $t(t,Qn.homedir());Q.untrusted.length&&console.error($(`mcp: ${Q.untrusted.length} project server(s) in ${_.dirName}/mcp.json not started (untrusted). Review the file, then run \`${_.bin} mcp trust\`.`));let Y=await ct.fromConfig(Q,t);process.on("exit",()=>Y.close());for(let[S,g]of Y.errors)console.error($(`mcp: server "${S}" unavailable: ${g}`));Y.tools.length&&c($(`mcp: ${Y.tools.length} tool(s) from ${Y.serverCount} server(s) (each call asks for approval)`));let q=await bt(t,Qn.homedir());q.untrusted.length&&console.error($(`hooks: ${q.untrusted.length} project hook(s) in ${_.dirName}/hooks.json not run (untrusted). Review the file, then run \`${_.bin} hooks trust\`.`));let ae=!!e.plan,ee=await ze(t),ve=(await Ne(t)).length,pt=new Yt(ee),gt=Ws(null),oe=0,me=fn(),Fe,Et=Date.now(),Mt=B,ft=async()=>{u.length<=1||await Ls(t,{id:me,title:Fe??Tt(u.slice(1)),model:Mt,createdAt:Et,updatedAt:Date.now(),messages:u.slice(1)}).catch(()=>{})},so=async S=>{let g=mt.createInterface({input:process.stdin,output:process.stdout});try{return(await g.question(S)).trim()}finally{g.close()}},ro=S=>{u.length=1,u.push(...S.messages),me=S.id,Fe=S.title,Et=S.createdAt,oe=S.messages.filter(g=>g.role==="user").length},io=async()=>{let S=(await Xn(t)).filter(z=>z.id!==me).slice(0,15);if(!S.length)return console.log($(`
|
|
146
145
|
No previous sessions for this project.
|
|
147
146
|
`)),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,
|
|
149
|
-
Resume which? (number, Enter to cancel): `),10);return
|
|
150
|
-
(${w.length} image(s) were attached, but this model cannot view images.)`,w=[]}u.push({role:"user",content:await
|
|
151
|
-
${
|
|
152
|
-
`).slice(1).join(" ").trim()}}:void 0
|
|
147
|
+
{0}Sessions for this project:{1}`,i.bold,i.reset)),S.forEach((z,G)=>console.log(` ${String(G+1).padStart(2)}. ${z.title} ${$(`${z.turns} turn(s) \xB7 ${z.model} \xB7 ${_n(z.updatedAt)} \xB7 ${z.id}`)}`));let g=Number.parseInt(await so(`
|
|
148
|
+
Resume which? (number, Enter to cancel): `),10);return g>=1&&g<=S.length?S[g-1].id:null};if(e.continue||e.resume){let S=e.resume===!0&&process.stdin.isTTY?await io()??void 0:e.resume===!0?void 0:e.resume,g=e.resume===!0&&!S?null:await Zn(t,S);g?(ro(g),console.error($(`resumed "${g.title}" (${g.messages.filter(z=>z.role==="user").length} turn(s), ${_n(g.updatedAt)})`))):console.error($(e.continue||e.resume!==!0?"no matching previous session; starting fresh.":"starting fresh."))}let ye=null,ao=async()=>{if(ye)return ye;if(ye=new Map,s==="gateway")try{for(let S of(await Z("/v1/models")).data)ye.set(S.id,!!S.vision)}catch{}return ye},lo=async S=>(await ao()).get(S)??!1,be=[],co=0,Vs=15e3,yn=async()=>{if(be.length>0&&Date.now()-co<Vs)return be;try{if((await ie()).token){let G=await Z("/v1/models");if(Array.isArray(G.data)&&G.data.length>0)return be=G.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":""}`})),co=Date.now(),ye=null,be}}catch{}let S=[],g=[{id:"mock-model",provider:"mock",description:"offline test mock"}];for(let z of g)S.some(G=>G.id===z.id)||S.push(z);return be=S,be},Ct={queue:[],draft:""},Pt=async(S,g=B,z=ae)=>{let G=je.splice(0),m=await cs(t,G.length?`${S} ${G.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 lo(g))c($(`\u{1F4CE} ${w.map((y,F)=>`#${F+1} ${y.name} (${Math.round(y.data.length*.75/1024)} KB)`).join(", ")}`));else{let y=[...await ao()].filter(([,F])=>F).map(([F])=>F).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",g,w.length,y.length?` Try: /model ${y[0]} (vision models: ${y.join(", ")})`:" Switch to a vision-capable model with /model <id>.")),b=`
|
|
149
|
+
(${w.length} image(s) were attached, but this model cannot view images.)`,w=[]}u.push({role:"user",content:await Ao(t,m.text+b),...w.length?{images:w}:{}});let L=new AbortController,C=new on(()=>{L.abort()},Ct),D=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 F=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(`${F}\u2026`)}else y.type==="tool_result"&&C.setStatus(nn());ji(y),C.draw()}},f=Ws(null,()=>C.suspend(),()=>C.resume());try{!e.prompt&&process.stdout.isTTY&&C.start();let y={messages:u,ctx:p,yolo:e.yolo,approve:f,onEvent:D,maxSteps:h,maxRunTokens:R,signal:L.signal,mcp:Y,hooks:q,plan:z,stream:e.outputFormat==="stream-json"},F=e.verify?async()=>{let pe=await et("run_shell",{command:e.verify},p).catch(De=>`exit code: 1
|
|
150
|
+
${De.message}`);return{ok:/^exit code: 0\b/.test(pe),detail:pe.split(`
|
|
151
|
+
`).slice(1).join(" ").trim()}}:void 0,Se=g==="mock-model"&&s!=="gateway"?new He:n,x=e.cascade&&v&&e.effort!=="high"?await ns({...y,cheap:{client:Se,model:g},strong:{client:n,model:v},verify:F}):await st({...y,client:Se,model:g});C.stop();let E=C.getElapsedSec();if(x.stopReason==="interrupted")return console.log(l("cli.run.0_1_esc_2_3",`
|
|
153
152
|
{0}{1}esc{2} {3}Interrupted by user{4}
|
|
154
|
-
`,i.bold,i.gray,i.reset,i.dim,i.reset)),!1;if(a){let
|
|
153
|
+
`,i.bold,i.gray,i.reset,i.dim,i.reset)),!1;if(a){let pe=x.stopReason==="done"&&x.toolErrors===0;return console.log(JSON.stringify({type:"result",ok:pe,stopReason:x.stopReason,result:x.finalText,model:g,sessionId:me,usage:x.usage,changedFiles:x.changedFiles})),pe||(process.exitCode=1),pe}let J=x.changedFiles.length?` \xB7 changed: ${x.changedFiles.join(", ")}`:"",se=x.cachedReads?` \xB7 ${x.cachedReads} repeat read(s) skipped`:"",ce="finalModel"in x&&x.escalated?`${g} \u2192 ${x.finalModel}`:g,ht=(x.usage?.promptTokens??0)+(x.usage?.completionTokens??0),xe=sn(ht),xn=`${$(`[${ce}]`)} ${i.tokenBlue}${xe}${i.reset}${$(`${J}${se}`)}`;console.log(l("cli.run.0_worked_for_1_s",`
|
|
155
154
|
{0}\u2713 Done in {1}s{2}
|
|
156
|
-
{3}`,i.workedPrefix,E,i.reset,
|
|
155
|
+
{3}`,i.workedPrefix,E,i.reset,xn));let Ve=Go(x,R);return Ve&&console.log(`\x1B[33m${Ve}\x1B[0m`),x.stopReason==="done"&&x.toolErrors===0}catch(y){return C.stop(),L.signal.aborted?(console.log(l("cli.run.0_1_esc_2_3_2",`
|
|
157
156
|
{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:
|
|
157
|
+
`,i.bold,i.gray,i.reset,i.dim,i.reset)),!1):(a?console.log(JSON.stringify({type:"result",ok:!1,error:Ie(y,r),sessionId:me})):console.error(l("cli.run.error_0",`
|
|
159
158
|
error: {0}
|
|
160
|
-
`,
|
|
159
|
+
`,Ie(y,r))),process.exitCode=1,!1)}finally{C.stop(),Mt=g,await ft()}};(ee.length||ve)&&c($(`using ${ee.length} skill(s) and ${ve} memory note(s) from ${_.dirName}/`));async function Xs(S,g){if(!!!(process.stdin.isTTY&&process.stdout.isTTY)){let G=mt.createInterface({input:process.stdin,output:process.stdout});try{return(await G.question("\u203A ")).trim()}finally{G.close()}}return new Promise(G=>{let m="\x1B[2m",w="\x1B[0m",b="\x1B[38;2;255;179;71m",L=()=>Math.max(process.stdout.columns||80,20),C=()=>"\u2500".repeat(L()),D=()=>`? for shortcuts \xB7 ${b}taste on${w}${je.length?` \xB7 ${b}\u{1F4CE} ${je.length} image(s) attached${w}`:""}`,f=Ct.draft;Ct.draft="";let y=f.length,F=g.length,Se="",x=!1,E=0,J=0,se=2,ce=!1,ht=0;process.stdout.write(`\x1B[38;2;255;122;61m\u276F\x1B[0m ${m}Ask ${_.name} anything\u2026${w}
|
|
161
160
|
`),process.stdout.write(`${m}${C()}${w}
|
|
162
|
-
`),process.stdout.write(`${
|
|
163
|
-
\x1B[2K`);
|
|
161
|
+
`),process.stdout.write(`${D()}`),process.stdout.write("\x1B[2A\x1B[3G"),f&&setImmediate(()=>N());let xe=process.stdin,xn=xe.isRaw;xe.setRawMode(!0),xe.resume();let Ve=()=>{xe.removeListener("data",mo),process.stdout.removeListener("resize",uo),xe.setRawMode&&xe.setRawMode(xn)},pe=Te=>{Ve();for(let le=0;le<se;le++)process.stdout.write(`
|
|
162
|
+
\x1B[2K`);se>0&&process.stdout.write(`\x1B[${se}A`),process.stdout.write("\x1B[2K\r");let k=Te.trim();k&&!k.startsWith("/")&&k!=="?"&&process.stdout.write(`
|
|
164
163
|
${i.userMsgBg} ${i.userPointer}${i.bold}\u276F${i.reset}${i.userMsgBg} ${i.userFg}${k} ${i.reset}
|
|
165
164
|
|
|
166
|
-
`),
|
|
167
|
-
\x1B[2K${
|
|
168
|
-
\x1B[2K`);let
|
|
165
|
+
`),G(k)},De=Te=>{let k=be.length>0?be:[{id:"mock-model",provider:"mock",description:"offline test mock"}],le=Te.trim().toLowerCase();return k.filter(W=>le?W.id.toLowerCase().includes(le):!0).map(W=>{let I=W.id===A,U=I?`\u2713 ${W.id}`:W.id,V=`${I?"(active) ":""}${W.description||"model"}`;return{command:`/model ${W.id}`,displayCommand:U,description:V}})},N=()=>{let Te=L(),k=Math.max(10,Te-8),le=f,P=we(f.slice(0,y));if(!f)le=`${m}Ask ${_.name} anything\u2026${w}`,P=0;else if(we(f)>k){let X=Ke(f),Xe=Ke(f.slice(0,y)).length,Re=0;for(;Re<Xe&&we(X.slice(Re,Xe).join(""))>=k;)Re++;let de="";for(let ge=Re;ge<X.length&&we(de+X[ge])<=k;ge++)de+=X[ge];le=de,P=we(X.slice(Re,Xe).join(""))}let W=Ye(f),I=W.showMenu&&!x,U=I?dt(W.query):[],V=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x,Ue=V?f.replace(/^\/model[:\s]*/,"").trim().toLowerCase():"",Nt=V?De(Ue):[],ke=I&&U.length>0||V&&Nt.length>0,te=V?Nt:U;te.length>0&&(E>=te.length&&(E=Math.max(0,te.length-1)),E<0&&(E=0),E<J&&(J=E),E>=J+8&&(J=Math.max(0,E-8+1)));let K=[];if(ke&&te.length>0){K.push(`\x1B[38;2;90;66;50m${C()}\x1B[0m`);let X=te.slice(J,J+8),Xe=Math.min(38,Math.max(...X.map(de=>we(de.displayCommand??de.command)),18)),Re=Math.max(10,Te-Xe-4);for(let de=0;de<X.length;de++){let ge=X[de],er=J+de===E,po=(ge.displayCommand??ge.command).padEnd(Xe),go=ge.description.length>Re?ge.description.slice(0,Re-1)+"\u2026":ge.description;er?K.push(`${i.accent}${i.bold}${po}${i.reset} ${i.accent}${go}${i.reset}`):K.push(`${i.bannerText}${po}${i.reset} ${i.gray}${go}${i.reset}`)}}else if(ce||f.trim()==="?"){K.push("");for(let X of Kn())K.push(X);K.push(""),K.push(`${m}${C()}${w}`),K.push(`${D()}`)}else K.push(`${m}${C()}${w}`),K.push(`${D()}`);process.stdout.write(`\x1B[1G\x1B[2K\x1B[38;2;255;122;61m\u276F\x1B[0m ${le}`);for(let X of K)process.stdout.write(`
|
|
166
|
+
\x1B[2K${X}`);let _t=Math.max(0,se-K.length);for(let X=0;X<_t;X++)process.stdout.write(`
|
|
167
|
+
\x1B[2K`);let jt=K.length+_t;jt>0&&process.stdout.write(`\x1B[${jt}A`),process.stdout.write(`\x1B[${3+P}G`),se=K.length},uo=()=>{N()};process.stdout.on("resize",uo);let Qs=new Ni("utf8"),mo=Te=>{let k=Qs.write(Te);if(!k)return;if(k==="\r"||k===`
|
|
169
168
|
`||k.endsWith("\r")||k.endsWith(`
|
|
170
169
|
`)){if(f.endsWith("\\")){f=f.slice(0,-1)+`
|
|
171
|
-
`,y=f.length,
|
|
172
|
-
\x1B[2K`);
|
|
173
|
-
`),process.exit(0);return}if(k===""&&!f){
|
|
174
|
-
\x1B[2K`);
|
|
175
|
-
`),process.exit(0);return}if(k==="\x7F"||k==="\b"){if(y>0){let P=
|
|
176
|
-
`);;){let S=
|
|
170
|
+
`,y=f.length,ce=!1,N();return}ce=!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 U=De(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(U.length>0){let V=U[E]??U[0];pe(V.command);return}}let I=Ye(f);if(I.showMenu&&!x){let U=dt(I.query);if(U.length>0){let V=U[E]??U[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(V.command)){pe(V.command);return}else{f=V.command+" ",y=f.length,x=!1,E=0,J=0,N();return}}}pe(f);return}if(k===" "){if((f.startsWith("/model ")||f.startsWith("/model:"))&&!x){let I=De(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(I.length>0){f=(I[E]??I[0]).command,y=f.length,x=!0,N();return}}let W=Ye(f);if(W.showMenu&&!x){let I=dt(W.query);if(I.length>0){f=(I[E]??I[0]).command+" ",y=f.length,x=!1,E=0,J=0,N();return}}else{let I=f.slice(0,y),U=I.match(/@([a-zA-Z0-9_\-\.\/]*)$/);if(U){let V=U[1],Ue=I.lastIndexOf("@");bs(t).then(Nt=>{let ke=Nt.filter(te=>te.startsWith(V));if(ke.length===1){let te=ke[0]+(ke[0].endsWith("/")?"":" ");f=f.slice(0,Ue+1)+te+f.slice(y),y=Ue+1+te.length,N()}else if(ke.length>1){let te=V;for(let K=V.length+1;K<=ke[0].length;K++){let _t=ke[0].slice(0,K);if(ke.every(jt=>jt.startsWith(_t)))te=_t;else break}te.length>V.length&&(f=f.slice(0,Ue+1)+te+f.slice(y),y=Ue+1+te.length,N())}}).catch(()=>{});return}}return}if(k===""){if(f.length>0){f="",y=0,x=!1,E=0,J=0,N();return}Ve();for(let P=0;P<se;P++)process.stdout.write(`
|
|
171
|
+
\x1B[2K`);se>0&&process.stdout.write(`\x1B[${se}A`),process.stdout.write(`\x1B[2K\r
|
|
172
|
+
`),process.exit(0);return}if(k===""&&!f){Ve();for(let P=0;P<se;P++)process.stdout.write(`
|
|
173
|
+
\x1B[2K`);se>0&&process.stdout.write(`\x1B[${se}A`),process.stdout.write(`\x1B[2K\r
|
|
174
|
+
`),process.exit(0);return}if(k==="\x7F"||k==="\b"){if(y>0){let P=rn(f,y);f=f.slice(0,P)+f.slice(y),y=P,x=!1,E=0,J=0,N()}return}if(k==="\x1B"){if(ce){ce=!1,N();return}let P=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x,W=Ye(f);if((P||W.showMenu)&&!x){x=!0,N();return}let I=Date.now();if(I-ht<400&&f.length>0){f="",y=0,ce=!1,N(),ht=0;return}ht=I;return}if(k.startsWith("\x1B")){if(k==="\x1B[D")y>0&&(y=rn(f,y),N());else if(k==="\x1B[C")y<f.length&&(y=Jn(f,y),N());else if(k==="\x1B[A"){let P=Ye(f),W=P.showMenu&&!x;if(((f.startsWith("/model ")||f.startsWith("/model:"))&&!x?De(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):W?dt(P.query):[]).length>0){E=Math.max(0,E-1),E<J&&(J=E),N();return}g.length>0&&F>0&&(F===g.length&&(Se=f),F--,f=g[F],y=f.length,x=!0,N())}else if(k==="\x1B[B"){let P=Ye(f),W=P.showMenu&&!x,U=(f.startsWith("/model ")||f.startsWith("/model:"))&&!x?De(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):W?dt(P.query):[];if(U.length>0){E=Math.min(U.length-1,E+1),E>=J+8&&(J=Math.max(0,E-8+1)),N();return}F<g.length&&(F++,f=F===g.length?Se:g[F],y=f.length,x=!0,N())}else k==="\x1B[H"||k==="\x1B[1~"||k===""?(y=0,N()):k==="\x1B[F"||k==="\x1B[4~"||k===""?(y=f.length,N()):k==="\x1B[3~"&&y<f.length&&(f=f.slice(0,y)+f.slice(Jn(f,y)),N());return}if(k===""){y=0,N();return}if(k===""){y=f.length,N();return}if(k===""){Vn().then(P=>{P&&je.push(P),N()});return}if(k.charCodeAt(0)<32&&k!==" ")return;if(k==="?"&&!f){ce=!ce,N();return}ce=!1;let le=k.replace(/\r?\n/g," ");f=f.slice(0,y)+le+f.slice(y),y+=le.length,x=!1,E=0,J=0,N()};xe.on("data",mo)})}if(e.prompt){await Pt(e.prompt,B)&&await qs(t,null);return}let bn=ee.length+ve,A=B,At=[];await yn().catch(()=>{});let Zs=s==="not logged in"?`${A} (not logged in)`:A;for(Gn(Zs,bn,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}
|
|
175
|
+
`);;){let S=Ct.queue.shift();S&&!S.startsWith("/")&&console.log(`
|
|
177
176
|
${i.userMsgBg} ${i.userPointer}${i.bold}\u276F${i.reset}${i.userMsgBg} ${i.userFg}${S} ${i.reset}
|
|
178
|
-
`),S||await Promise.race([
|
|
179
|
-
`,i.assistantPrefix,i.reset));continue}if(
|
|
177
|
+
`),S||await Promise.race([yn().catch(()=>{}),new Promise(m=>setTimeout(m,1500))]);let g=S??await Xs(bn,At);if(!g)continue;if(At[At.length-1]!==g&&At.push(g),g==="/exit"||g==="/quit")break;if(g==="/clear"||g==="/new"){u.length=0,u.push({role:"system",content:await d()}),oe=0,me=fn(),Fe=void 0,Et=Date.now(),console.clear(),Gn(A,bn,t),console.log(l("cli.run.0_new_session_started_1",`{0}\u2713 New session started.{1}
|
|
178
|
+
`,i.assistantPrefix,i.reset));continue}if(g==="?"||g==="/shortcuts"||g==="/hotkeys"){Yn();continue}if(g==="/help"){ws();continue}if(g==="/taste"){let m=await ze(t),w=await Ne(t);console.log(l("cli.run.0_taste_learning_status_1",`
|
|
180
179
|
{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(
|
|
180
|
+
`,w.length));continue}if(g.startsWith("/skills")){let m=g.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();if(w){let b=await at(t,w);console.log(`
|
|
182
181
|
${b.added?`\u2713 Added skill: "${b.skill}"`:"Skill already exists."}
|
|
183
|
-
`)}}else{let w=await
|
|
184
|
-
{0}Project Skills (.forge/skills.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,
|
|
182
|
+
`)}}else{let w=await ze(t);console.log(l("cli.run.0_project_skills_forge_skills",`
|
|
183
|
+
{0}Project Skills (.forge/skills.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,L)=>console.log(` ${L+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(g.startsWith("/memory")){let m=g.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();w&&(await xt(t,w),console.log(l("cli.run.saved_to_forge_memory_md",`
|
|
185
184
|
\u2713 Saved to .forge/memory.md: "{0}"
|
|
186
|
-
`,w)))}else{let w=await
|
|
187
|
-
{0}Project Memory (.forge/memory.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,
|
|
185
|
+
`,w)))}else{let w=await Ne(t);console.log(l("cli.run.0_project_memory_forge_memory",`
|
|
186
|
+
{0}Project Memory (.forge/memory.md):{1}`,i.bold,i.reset)),w.length?w.forEach((b,L)=>console.log(` ${L+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(g==="/models"){console.log(""),await cn(),console.log("");continue}if(g==="/paste"||g.startsWith("/image")){let m=g.startsWith("/image")?g.slice(6).trim():"";if(m){je.push(Le.resolve(t,m.replace(/^["']|["']$/g,""))),console.log(l("cli.run.queued_0_it_goes_with",`
|
|
188
187
|
\u{1F4CE} queued {0}; it goes with your next message.
|
|
189
|
-
`,m));continue}let w=await
|
|
188
|
+
`,m));continue}let w=await Vn();w?(je.push(w),console.log(l("cli.run.clipboard_image_attached_0_queued",`
|
|
190
189
|
\u{1F4CE} clipboard image attached ({0} queued); it goes with your next message.
|
|
191
|
-
`,
|
|
190
|
+
`,je.length))):console.log($(`
|
|
192
191
|
No image on the clipboard (copy or screenshot one first, e.g. Cmd+Ctrl+Shift+4 on macOS).
|
|
193
|
-
`));continue}if(
|
|
192
|
+
`));continue}if(g.startsWith("/model")){let m=g.split(/\s+/);m[1]?(A=m[1],await Je({defaultModel:A}).catch(()=>{}),console.log(l("cli.run.switched_active_model_to_0",`
|
|
194
193
|
\u2713 Switched active model to: {0}{1}{2}{3}
|
|
195
|
-
`,i.bold,A,i.reset,await
|
|
194
|
+
`,i.bold,A,i.reset,await lo(A)?$(" [reads images]"):$(" [text only]")))):(console.log(`
|
|
196
195
|
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(
|
|
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}",
|
|
196
|
+
`,i.cyan,i.reset,i.cyan,i.reset)));continue}if(g==="/context"){let m=nt(u);if(console.log(l("cli.run.0_context_window_usage_1",`
|
|
197
|
+
{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}",oe)),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
198
|
`,R.toLocaleString(),w))}else console.log(` \u2022 Budget limit: Unlimited
|
|
200
|
-
`);continue}if(
|
|
199
|
+
`);continue}if(g==="/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
200
|
{0}No assistant response to copy yet.{1}
|
|
202
|
-
`,i.dim,i.reset));else{let w=m.content;if(await
|
|
201
|
+
`,i.dim,i.reset));else{let w=m.content;if(await ys(w))console.log(l("cli.run.0_copied_last_response_to",`
|
|
203
202
|
{0}\u2713 Copied last response to clipboard.{1}
|
|
204
|
-
`,i.assistantPrefix,i.reset));else{let
|
|
203
|
+
`,i.assistantPrefix,i.reset));else{let L=Le.join(t,_.dirName,"last_response.txt");await Rt.mkdir(Le.dirname(L),{recursive:!0}),await Rt.writeFile(L,w,"utf8"),console.log(l("cli.run.0_saved_last_response_to",`
|
|
205
204
|
{0}\u2713 Saved last response to {1}{2}
|
|
206
|
-
`,i.assistantPrefix,
|
|
207
|
-
`);await
|
|
205
|
+
`,i.assistantPrefix,Le.relative(t,L),i.reset))}}continue}if(g.startsWith("/export")){let m=g.includes("jsonl"),w=m?"jsonl":"md",b=`forge-session-${new Date().toISOString().replace(/[:.]/g,"-")}.${w}`,L=Le.join(t,b);if(m){let C=u.map(D=>JSON.stringify(D)).join(`
|
|
206
|
+
`);await Rt.writeFile(L,C,"utf8")}else{let C=`# Session Transcript
|
|
208
207
|
|
|
209
208
|
- **Model**: ${A}
|
|
210
209
|
- **Date**: ${new Date().toLocaleString()}
|
|
@@ -212,123 +211,123 @@ Active model: ${i.bold}${A}${i.reset} via ${i.cyan}${s}${i.reset}`),console.log(
|
|
|
212
211
|
|
|
213
212
|
---
|
|
214
213
|
|
|
215
|
-
`;for(let
|
|
214
|
+
`;for(let D of u)D.role==="user"?C+=`### \u276F User
|
|
216
215
|
|
|
217
|
-
${
|
|
216
|
+
${D.content}
|
|
218
217
|
|
|
219
|
-
`:
|
|
218
|
+
`:D.role==="assistant"&&D.content&&(C+=`### Assistant
|
|
220
219
|
|
|
221
|
-
${
|
|
220
|
+
${D.content}
|
|
222
221
|
|
|
223
|
-
`);await
|
|
222
|
+
`);await Rt.writeFile(L,C,"utf8")}console.log(l("cli.run.0_exported_session_to_1",`
|
|
224
223
|
{0}\u2713 Exported session to {1}{2}
|
|
225
|
-
`,i.assistantPrefix,b,i.reset));continue}if(
|
|
224
|
+
`,i.assistantPrefix,b,i.reset));continue}if(g==="/usage"){console.log(""),await dn().catch(m=>console.log($(`could not load usage: ${m.message}`))),console.log("");continue}if(g.startsWith("/effort")){let m=g.split(/\s+/);m[1]&&["low","high"].includes(m[1])?(e.effort=m[1],console.log(l("cli.run.effort_set_to_0_1",`
|
|
226
225
|
\u2713 Effort set to: {0}{1}{2}
|
|
227
226
|
`,i.bold,e.effort,i.reset))):(e.effort=e.effort==="high"?"low":"high",console.log(l("cli.run.effort_toggled_to_0_1",`
|
|
228
227
|
\u2713 Effort toggled to: {0}{1}{2}
|
|
229
|
-
`,i.bold,e.effort,i.reset)));continue}if(
|
|
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}",
|
|
231
|
-
`,
|
|
228
|
+
`,i.bold,e.effort,i.reset)));continue}if(g==="/status"){console.log(l("cli.run.0_session_status_1",`
|
|
229
|
+
{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}",oe)),console.log(l("cli.run.taste_0_skill_s_1",` \u2022 Taste: {0} skill(s), {1} memory note(s)
|
|
230
|
+
`,ee.length,ve));continue}if(g==="/init"){console.log(""),await un(),console.log("");continue}if(g.startsWith("/theme")){let w=g.slice(6).trim().toLowerCase()==="light"?"light":"dark";console.log(l("cli.run.color_theme_0_1_2",`
|
|
232
231
|
\u2713 Color theme: {0}{1}{2}
|
|
233
|
-
`,i.bold,w,i.reset));continue}if(
|
|
232
|
+
`,i.bold,w,i.reset));continue}if(g.startsWith("/language")){let m=g.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
233
|
\u2713 Interface language set to: {0}{1}{2}
|
|
235
|
-
`,i.bold,w,i.reset));continue}if(
|
|
234
|
+
`,i.bold,w,i.reset));continue}if(g.startsWith("/add-dir")){let m=g.slice(8).trim();if(!m)console.log(l("cli.run.0_workspace_directories_1",`
|
|
236
235
|
{0}Workspace Directories:{1}`,i.bold,i.reset)),console.log(l("cli.run.root_0",` \u2022 Root: {0}
|
|
237
|
-
`,t));else{let w=
|
|
236
|
+
`,t));else{let w=Le.resolve(t,m);try{(await Rt.stat(w)).isDirectory()?console.log(l("cli.run.added_directory_scope_0_1",`
|
|
238
237
|
\u2713 Added directory scope: {0}{1}{2}
|
|
239
238
|
`,i.bold,w,i.reset)):console.log(l("cli.run.0_path_is_not_a",`
|
|
240
239
|
{0}Path is not a directory: {1}{2}
|
|
241
240
|
`,i.dim,w,i.reset))}catch(b){console.log(l("cli.run.0_could_not_access_directory",`
|
|
242
241
|
{0}Could not access directory: {1}{2}
|
|
243
|
-
`,i.dim,b.message,i.reset))}}continue}if(
|
|
242
|
+
`,i.dim,b.message,i.reset))}}continue}if(g.startsWith("/worktree")){let m=g.slice(9).trim();console.log($(`$ git worktree ${m||"list"}`));let w=await et("run_shell",{command:`git worktree ${m||"list"}`},p).catch(b=>b.message);console.log(w);continue}if(g==="/agents"){console.log(l("cli.run.0_active_agent_configuration_1",`
|
|
244
243
|
{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
|
-
`));continue}if(
|
|
244
|
+
`));continue}if(g.startsWith("/goal")){let m=g.slice(5).trim();m==="clear"?console.log(l("cli.run.session_goal_cleared",`
|
|
246
245
|
\u2713 Session goal cleared.
|
|
247
246
|
`)):!m||m==="status"?console.log(l("cli.run.0_session_goal_1_2",`
|
|
248
247
|
{0}Session Goal:{1} {2}(No explicit goal active. Set with: /goal <objective>){3}
|
|
249
248
|
`,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
249
|
\u2713 Set active session goal: "{0}"
|
|
251
|
-
`,m)));continue}if(
|
|
250
|
+
`,m)));continue}if(g==="/plan"){ae=!ae,console.log(l("cli.run.plan_mode_0_1_2",`
|
|
252
251
|
\u2713 Plan mode {0}{1}{2}{3}.
|
|
253
|
-
`,i.bold,
|
|
252
|
+
`,i.bold,ae?"ON":"OFF",i.reset,ae?" (read-only: the agent will explore and propose a plan, no edits or commands)":""));continue}if(g.startsWith("/mode")){let m=g.replace(/^\/mode:?/,"").trim();m==="accept-edits"?(e.yolo=!0,ae=!1,console.log(l("cli.run.switched_to_0_accept_edits",`
|
|
254
253
|
\u2713 Switched to {0}accept-edits{1} mode (edits accepted automatically).
|
|
255
|
-
`,i.bold,i.reset))):m==="plan"?(
|
|
254
|
+
`,i.bold,i.reset))):m==="plan"?(ae=!0,console.log(l("cli.run.switched_to_0_plan_1",`
|
|
256
255
|
\u2713 Switched to {0}plan{1} mode (read-only reasoning).
|
|
257
|
-
`,i.bold,i.reset))):(e.yolo=!1,
|
|
256
|
+
`,i.bold,i.reset))):(e.yolo=!1,ae=!1,console.log(l("cli.run.switched_to_0_default_1",`
|
|
258
257
|
\u2713 Switched to {0}default{1} mode (prompt before major edits).
|
|
259
|
-
`,i.bold,i.reset)));continue}if(
|
|
258
|
+
`,i.bold,i.reset)));continue}if(g.startsWith("/btw")){let m=g.slice(4).trim();if(!m)console.log(l("cli.run.usage_btw_question_ask_a",`
|
|
260
259
|
Usage: /btw <question> (ask a quick side question that does not enter history)
|
|
261
260
|
`));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
|
|
261
|
+
{0}[btw side question]{1}`,i.gray,i.reset)),await st({messages:w,ctx:p,yolo:!0,maxSteps:1,maxRunTokens:2e3,client:A==="mock-model"&&s!=="gateway"?new He:n,model:A,onEvent:b=>{b.type==="assistant"&&console.log(`
|
|
263
262
|
${i.assistantPrefix}\u25C6${i.reset} ${b.text}
|
|
264
|
-
`)}}).catch(b=>console.log(l("cli.run.error_0_2","error: {0}",b.message)))}continue}if(
|
|
265
|
-
{0}{2} v{3} changelog:{1}`,i.bold,i.reset,_.name
|
|
266
|
-
`));continue}if(
|
|
263
|
+
`)}}).catch(b=>console.log(l("cli.run.error_0_2","error: {0}",b.message)))}continue}if(g==="/hotkeys"||g==="/shortcuts"){Yn();continue}if(g==="/changelog"){console.log(l("cli.run.0_command_code_v1_87",`
|
|
264
|
+
{0}{2} v{3} changelog:{1}`,i.bold,i.reset,_.name,$e)),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
|
+
`));continue}if(g==="/todos"){console.log(l("cli.run.0_session_todos_1",`
|
|
267
266
|
{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
|
-
`,i.dim,i.reset));continue}if(
|
|
267
|
+
`,i.dim,i.reset));continue}if(g.startsWith("/feedback")||g.startsWith("/issue")){console.log(l("cli.run.share_feedback_or_report_an",`
|
|
269
268
|
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(
|
|
269
|
+
`,i.cyan,i.reset));continue}if(g==="/compact"||g.startsWith("/compact ")){let m=hn(u);if(m.length<2){console.log(l("cli.run.0_nothing_to_compact_yet",`
|
|
271
270
|
{0}Nothing to compact yet ({1} turn).{2}
|
|
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??"",
|
|
273
|
-
`).slice(-6e4),C=
|
|
271
|
+
`,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??"",L=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(`
|
|
272
|
+
`).slice(-6e4),C=g.slice(8).trim(),D=nt(u);console.log($("compacting conversation\u2026"));try{let y=(await(A==="mock-model"&&s!=="gateway"?new He: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
273
|
|
|
275
274
|
`:""}Conversation to summarize:
|
|
276
275
|
|
|
277
|
-
${
|
|
278
|
-
${y}`},{role:"assistant",content:"Understood. I have the context from that summary and will continue from here."},...
|
|
276
|
+
${L}`}]})).content?.trim();if(!y)throw new Error(l("cli.run.the_model_returned_an_empty","the model returned an empty summary"));let F=u.slice(w);u.length=1,u.push({role:"user",content:`[Summary of the earlier conversation]
|
|
277
|
+
${y}`},{role:"assistant",content:"Understood. I have the context from that summary and will continue from here."},...F),await ft(),console.log(l("cli.run.0_conversation_compacted_1_tokens",`
|
|
279
278
|
{0}\u2713 Conversation compacted{1}
|
|
280
279
|
\u2022 Tokens: ~{2} \u2192 ~{3}
|
|
281
|
-
`,i.assistantPrefix,i.reset,
|
|
280
|
+
`,i.assistantPrefix,i.reset,D.toLocaleString(),nt(u).toLocaleString()))}catch(f){console.log(l("cli.run.0_could_not_compact_1",`
|
|
282
281
|
{0}Could not compact: {1}{2}
|
|
283
|
-
`,i.dim,
|
|
282
|
+
`,i.dim,Ie(f,r),i.reset))}continue}if(g==="/resume"||g==="/sessions"||g.startsWith("/resume ")){let m=g.startsWith("/resume ")?g.slice(8).trim():await io(),w=m?await Zn(t,m):null;if(!w){m&&console.log($(`
|
|
284
283
|
No session matches "${m}".
|
|
285
|
-
`));continue}
|
|
284
|
+
`));continue}ro(w),console.log(l("cli.run.0_resumed_1_2_3",`
|
|
286
285
|
{0}\u2713 Resumed "{1}"{2} {3}
|
|
287
|
-
`,i.assistantPrefix,w.title,i.reset,$(`(${
|
|
286
|
+
`,i.assistantPrefix,w.title,i.reset,$(`(${oe} turn(s), ${_n(w.updatedAt)})`)));continue}if(g==="/fork"||g==="/clone"){if(u.length<=1){console.log($(`
|
|
288
287
|
Nothing to fork yet.
|
|
289
|
-
`));continue}
|
|
288
|
+
`));continue}Fe=`${Fe??Tt(u.slice(1))} (fork)`,me=fn(),Et=Date.now(),await ft(),console.log(l("cli.run.0_forked_into_a_new",`
|
|
290
289
|
{0}\u2713 Forked into a new session{1} {2}
|
|
291
|
-
`,i.assistantPrefix,i.reset,$(
|
|
292
|
-
Usage: /rename <new title> (current: ${
|
|
293
|
-
`));continue}
|
|
290
|
+
`,i.assistantPrefix,i.reset,$(me)));continue}if(g.startsWith("/rename")){let m=g.slice(7).trim();if(!m){console.log($(`
|
|
291
|
+
Usage: /rename <new title> (current: ${Fe??Tt(u.slice(1))})
|
|
292
|
+
`));continue}Fe=m.slice(0,120),await ft(),console.log(l("cli.run.0_session_renamed_1",`
|
|
294
293
|
{0}\u2713 Session renamed{1}
|
|
295
|
-
`,i.assistantPrefix,i.reset));continue}if(
|
|
294
|
+
`,i.assistantPrefix,i.reset));continue}if(g==="/session-file"){console.log(l("cli.run.session_0_file_1_2",`
|
|
296
295
|
\u2022 Session: {0}
|
|
297
296
|
\u2022 File: {1}{2}
|
|
298
|
-
`,
|
|
297
|
+
`,me,gn(t,me),u.length<=1?$(" (saved after your first message)"):""));continue}if(g==="/rewind"){let m=hn(u);if(!m.length){console.log($(`
|
|
299
298
|
Nothing to rewind.
|
|
300
299
|
`));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((
|
|
302
|
-
Number (Enter to cancel): `),10);if(!(b>=1&&b<=w.length))continue;u.length=w[b-1],
|
|
300
|
+
{0}Rewind to before which message?{1}`,i.bold,i.reset)),w.forEach((L,C)=>console.log(` ${String(C+1).padStart(2)}. ${Tt([u[L]])}`));let b=Number.parseInt(await so(`
|
|
301
|
+
Number (Enter to cancel): `),10);if(!(b>=1&&b<=w.length))continue;u.length=w[b-1],oe=hn(u).length,await ft(),console.log(l("cli.run.0_conversation_rewound_1_2",`
|
|
303
302
|
{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(
|
|
303
|
+
`,i.assistantPrefix,i.reset,$("File edits were not undone \u2014 use git (e.g. `git restore`) for that.")));continue}if(g.startsWith("/review")){let m=g.slice(7).trim(),w=(D,f)=>new Promise((y,F)=>Ai(D,f,{cwd:t,maxBuffer:16*1024*1024},(Se,x,E)=>Se?F(new Error(String(E||Se.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(D){console.log(l("cli.run.0_could_not_get_the",`
|
|
305
304
|
{0}Could not get the diff: {1}{2}
|
|
306
|
-
`,i.dim,
|
|
305
|
+
`,i.dim,D instanceof Error?D.message:D,i.reset));continue}if(!b.trim()){console.log($(`
|
|
307
306
|
No changes to review.
|
|
308
|
-
`));continue}let
|
|
307
|
+
`));continue}let L=b.length>6e4,C=`Review the following code changes${m?` (PR #${m})`:""}. Look for correctness bugs, regressions, security problems and missing tests. Cite file and line, order findings by severity, be concise, and say so if the change looks good. Do not edit any files.
|
|
309
308
|
|
|
310
309
|
<diff>
|
|
311
|
-
${
|
|
310
|
+
${L?b.slice(0,6e4)+`
|
|
312
311
|
\u2026 (diff truncated)`:b}
|
|
313
|
-
</diff>`;await
|
|
314
|
-
{0}MCP servers:{1}`,i.bold,i.reset));let m=new Map;for(let w of
|
|
312
|
+
</diff>`;await Pt(C,A,!0),console.log("");continue}if(g==="/mcp"){console.log(l("cli.run.0_mcp_servers_1",`
|
|
313
|
+
{0}MCP servers:{1}`,i.bold,i.reset));let m=new Map;for(let w of Y.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 Y.errors)console.log(l("cli.run.0_unavailable_1"," \u2022 {0} \x1B[31munavailable\x1B[0m {1}",w,$(b)));Q.untrusted.length&&console.log(` \u2022 ${Q.untrusted.join(", ")} ${$(`untrusted \u2014 run \`${_.bin} mcp trust\``)}`),!Y.serverCount&&!Y.errors.size&&!Q.untrusted.length&&console.log($(` none. Add one: ${_.bin} mcp add <name> <command\u2026|url>`)),console.log("");continue}if(g==="/login"){try{await an();let m=await eo(e);n=m.client,s=m.label,r=m.apiUrl,A=e.model??(await ie()).defaultModel??m.model,Mt=A,(e.cascade||e.effort==="high"&&!e.model)&&(v=await to(e,s,A)),ye=null,be=[],await yn().catch(()=>{}),console.log(`
|
|
315
314
|
${i.assistantPrefix}\u2713 Active session updated: ${i.bold}${s}${i.reset} (${i.cyan}${A}${i.reset}). You can now continue chatting.
|
|
316
315
|
`)}catch(m){console.error(`
|
|
317
316
|
\x1B[31merror: Login failed:\x1B[0m ${m?.message??m}
|
|
318
|
-
`)}continue}if(
|
|
317
|
+
`)}continue}if(g==="/logout"){try{await ln(),s="not logged in",n={chat:async()=>{throw new re(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},v=null,ye=null,console.log($(`Token removed. Run /login to authenticate.
|
|
319
318
|
`))}catch(m){console.error(`
|
|
320
319
|
\x1B[31merror: Logout failed:\x1B[0m ${m?.message??m}
|
|
321
|
-
`)}continue}if(
|
|
320
|
+
`)}continue}if(g==="/reload"){try{let m=await eo(e);n=m.client,s=m.label,r=m.apiUrl,A=e.model??(await ie()).defaultModel??m.model,Mt=A,(e.cascade||e.effort==="high"&&!e.model)&&(v=await to(e,s,A)),ye=null,console.log(`
|
|
322
321
|
${i.assistantPrefix}\u2713 Reloaded configuration: ${i.bold}${s}${i.reset} (${i.cyan}${A}${i.reset}).
|
|
323
322
|
`)}catch(m){console.error($(`
|
|
324
323
|
Failed to reload configuration: ${m?.message??m}
|
|
325
|
-
`))}continue}if(
|
|
324
|
+
`))}continue}if(g==="/doctor"){await mn();continue}if(g==="/config"){let m=await ie();console.log(`
|
|
326
325
|
${i.bold}Config:${i.reset}
|
|
327
326
|
\u2022 Token: ${m.token?m.token.slice(0,6)+"\u2026"+m.token.slice(-4):"(not logged in)"}
|
|
328
327
|
\u2022 Default model: ${m.defaultModel??"(none)"}
|
|
329
328
|
\u2022 Backend: ${s} Model: ${A}
|
|
330
|
-
`);continue}if(
|
|
329
|
+
`);continue}if(g.startsWith("!")){let m=g.slice(1).trim();if(m){console.log($(`$ ${m}`));let w=await et("run_shell",{command:m},p).catch(b=>b.message);console.log(w)}continue}let z=ae,G=await Pt(g,A);if(G&&oe++,console.log(""),z&&G&&process.stdin.isTTY){let m=mt.createInterface({input:process.stdin,output:process.stdout}),w=(await m.question("? Execute this plan? [y/n]: ")).trim().toLowerCase();m.close(),(w==="y"||w==="yes")&&(ae=!1,await Pt("Proceed with the plan above.",A,!1)&&oe++,console.log(""))}await Oi(null,t,pt.observe(g))&&(u[0]={role:"system",content:await d()})}oe>0&&await qs(t,null)}typeof Hs.setDefaultResultOrder=="function"&&Hs.setDefaultResultOrder("ipv4first");typeof zs.setDefaultAutoSelectFamily=="function"&&zs.setDefaultAutoSelectFamily(!1);var ne=new Li(_.bin).description(`${_.name} \u2014 CLI coding agent`).version($e,"-v, --version","output the current version").option("-V","output the current version",()=>{console.log($e),process.exit(0)});ne.command("version").description("output the current version").action(()=>{console.log($e)});function Gs(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 Fi("--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}",Ie(n,(await ie()).apiUrl))),process.exit(1)}},Js=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 Di(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 Ui(e){if(process.stdin.isTTY)return e;let t=(await Di()).trim();return t?{...e,prompt:e.prompt?`${e.prompt}
|
|
331
330
|
|
|
332
331
|
<stdin>
|
|
333
332
|
${t}
|
|
334
|
-
</stdin>`:t}:e}
|
|
333
|
+
</stdin>`:t}:e}Gs(ne).action(H(async e=>no(await Ui(Js(e)))));Gs(ne.command("chat").description("interactive session in the current directory")).action(H(async e=>no(Js(e))));ne.command("doctor").description("check your environment (node, git, login, MCP, hooks)").action(H(mn));ne.command("login").description("log in via browser").action(H(an));ne.command("logout").description("remove the stored token").action(H(ln));ne.command("models").description("list available models or set default").argument("[model]","model id to set as default").action(H(async e=>cn(e)));ne.command("usage").description("show remaining requests and dollars").action(H(dn));ne.command("init").description(`create ${_.dirName}/skills.md and memory.md`).action(H(un));var Ks=ne.command("skills").description(`project skills (${_.dirName}/skills.md) applied to every run`);Ks.command("list").description("show current skills").action(H($s));Ks.command("add").description('add a rule, e.g. skills add "Prefer pnpm"').argument("<text...>").action(H(async e=>vs(e)));var oo=ne.command("taste").description("share skills and memory with your team");oo.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)=>Ss(e,t)));oo.command("pull").description("merge a package into this project").argument("<package>","namespace/name").action(H(async e=>Ts(e)));oo.command("list").description("browse public packages").argument("[query]").action(H(async e=>Rs(e)));var wn=ne.command("mcp").description("MCP servers whose tools the agent can use");wn.command("list").description("connect and list tools").action(H(Es));wn.command("add").description("add a stdio command or HTTP URL").argument("<name>").argument("<command...>").action(H(async(e,t)=>Ms(e,t)));wn.command("remove").description("remove a server").argument("<name>").action(H(async e=>Cs(e)));wn.command("trust").description("approve this project's MCP servers after reviewing them").action(H(Ps));var Ys=ne.command("hooks").description(`PreToolUse/PostToolUse hook commands (${_.dirName}/hooks.json)`);Ys.command("list").description("show effective hooks").action(H(Ns));Ys.command("trust").description("approve this project's hooks after reviewing them").action(H(js));ne.parseAsync();
|