@scopeide/cli 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +249 -209
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,341 +1,381 @@
1
- import Js from"dns";import Ks from"net";import{Command as qi,Option as Hi}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.22"};var D={maxSteps:100,hardMaxSteps:500,maxToolOutputBytes:12e3,maxContextTokens:32e3,warnContextTokens:24e3,maxRunTokens:0,charsPerToken:4};var Ot={strings:{}},sr=["maxSteps","hardMaxSteps","maxToolOutputBytes","maxContextTokens","warnContextTokens","maxRunTokens"];function Sn(e){if(!e)return;let t=D;for(let n of sr){let o=e.limits?.[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&(t[n]=o)}if(e.strings&&typeof e.strings=="object"){Ot.strings={};for(let[n,o]of Object.entries(e.strings))/^(cli|agent|desktop)\./.test(n)&&typeof o=="string"&&(Ot.strings[n]=o.slice(0,4e3))}}function l(e,t,...n){let o=Ot.strings[e]??t;return n.length?o.replace(/\{(\d+)\}/g,(s,r)=>Number(r)<n.length?String(n[Number(r)]):s):o}var he={maxBytes:5*1024*1024,maxPerMessage:6,keepInRequest:3,maxRequestBytes:6*1024*1024};import Oe from"os";import $t from"path";import{execFile as Ss,spawn as Ei}from"child_process";import E from"fs/promises";import ur from"fs";import yo from"os";import mr from"crypto";import M from"path";import{spawn as pr}from"child_process";import{z as O}from"zod";import{zodToJsonSchema as gr}from"zod-to-json-schema";import Ve from"path";function _e(e,t){let n=Ve.resolve(e,t),o=Ve.relative(e,n),s=o===""||!o.startsWith("..")&&!Ve.isAbsolute(o);return{abs:n,inside:s}}function Ue(e,t){let n=Ve.posix.resolve(e,t),o=Ve.posix.relative(e,n),s=o===""||!o.startsWith("..")&&!Ve.posix.isAbsolute(o);return{abs:n,inside:s}}import Me from"path";function ge(e,t){if(e.length<=t)return e;let n=Math.floor(t*.6),o=t-n;return`${e.slice(0,n)}
1
+ import qr from"dns";import Hr from"net";import{Command as kl,Option as xl}from"commander";var w={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.23"};var F={maxSteps:100,hardMaxSteps:500,maxToolOutputBytes:12e3,maxContextTokens:32e3,warnContextTokens:24e3,maxRunTokens:0,charsPerToken:4};var Kt={strings:{}},ei=["maxSteps","hardMaxSteps","maxToolOutputBytes","maxContextTokens","warnContextTokens","maxRunTokens"];function Fn(e){if(!e)return;let t=F;for(let n of ei){let o=e.limits?.[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&(t[n]=o)}if(e.strings&&typeof e.strings=="object"){Kt.strings={};for(let[n,o]of Object.entries(e.strings))/^(cli|agent|desktop)\./.test(n)&&typeof o=="string"&&(Kt.strings[n]=o.slice(0,4e3))}}function l(e,t,...n){let o=Kt.strings[e]??t;return n.length?o.replace(/\{(\d+)\}/g,(s,r)=>Number(r)<n.length?String(n[Number(r)]):s):o}var pe={maxBytes:5*1024*1024,maxPerMessage:6,keepInRequest:3,maxRequestBytes:6*1024*1024};import Je from"os";import Lt from"path";import{execFile as kr,spawn as il}from"child_process";import C from"fs/promises";import gi from"fs";import Ko from"os";import fi from"crypto";import P from"path";import{spawn as hi}from"child_process";import{z as E}from"zod";import{zodToJsonSchema as wi}from"zod-to-json-schema";import ct from"path";function ce(e,t){let n=ct.resolve(e,t),o=ct.relative(e,n),s=o===""||!o.startsWith("..")&&!ct.isAbsolute(o);return{abs:n,inside:s}}function Fe(e,t){let n=ct.posix.resolve(e,t),o=ct.posix.relative(e,n),s=o===""||!o.startsWith("..")&&!ct.posix.isAbsolute(o);return{abs:n,inside:s}}import Ue 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 Tn from"path";var rr=[[/(^|[\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"]],ir=/^(\/|\/\*|~|~\/|~\/\*|\$HOME|\$\{HOME\}|\$HOME\/|\$HOME\/\*|\*|\/(usr|etc|bin|sbin|var|lib|opt|home|Users|System|Library|Applications)\/?\*?)$/;function ar(e){let t=e.trim().split(/\s+/),n=t.findIndex(c=>Tn.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=>ir.test(c));return a?`recursive delete of "${a}"`:null}function Lt(e,t){for(let[n,o]of rr)if(n.test(e))return{ok:!1,reason:`blocked: ${o}`};for(let n of e.split(/&&|\|\||[;|\n]/)){let o=ar(n);if(o)return{ok:!1,reason:`blocked: ${o}`}}if(!t.allowAll){let n=t.posix?Tn.posix:Tn,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 lr=/(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i;function Ft(e){let t={};for(let[n,o]of Object.entries(e))lr.test(n)||n.startsWith("FORGE_")||n==="DATABASE_URL"||(t[n]=o);return t}var cr=1e6,Rn=(e,t=D.maxToolOutputBytes)=>ge(e,t);function Ee(e,t,n){let{abs:o,inside:s}=Ue(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>cr)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 dr=(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 Rn(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
- `)&&!a.includes("\r")&&(a=a.replace(/\n/g,`\r
3
+ ${e.slice(e.length-o)}`}import Dn from"path";var ti=[[/(^|[\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"]],ni=/^(\/|\/\*|~|~\/|~\/\*|\$HOME|\$\{HOME\}|\$HOME\/|\$HOME\/\*|\*|\/(usr|etc|bin|sbin|var|lib|opt|home|Users|System|Library|Applications)\/?\*?)$/;function oi(e){let t=e.trim().split(/\s+/),n=t.findIndex(c=>Dn.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 i=o.filter(c=>!c.startsWith("-")).map(c=>c.replace(/^["']|["']$/g,"")).find(c=>ni.test(c));return i?`recursive delete of "${i}"`:null}function Gt(e,t){for(let[n,o]of ti)if(n.test(e))return{ok:!1,reason:`blocked: ${o}`};for(let n of e.split(/&&|\|\||[;|\n]/)){let o=oi(n);if(o)return{ok:!1,reason:`blocked: ${o}`}}if(!t.allowAll){let n=t.posix?Dn.posix:Dn,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 si=/(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i;function Se(e){let t={};for(let[n,o]of Object.entries(e))si.test(n)||n.startsWith("FORGE_")||n==="DATABASE_URL"||(t[n]=o);return t}var No=3e6,Lo=2e4;function ri(e){if(typeof e!="string"||!e.trim())throw new Error("url is required");let t;try{t=new URL(e.trim())}catch{throw new Error(`not a valid URL: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new Error("only http and https URLs can be fetched");return t}var ii={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};function ai(e){let t=e.replace(/<(script|style|noscript|svg|iframe|head|nav|footer)[\s\S]*?<\/\1>/gi," ").replace(/<!--[\s\S]*?-->/g," ").replace(/<h([1-6])[^>]*>/gi,(n,o)=>`
4
+
5
+ ${"#".repeat(Number(o))} `).replace(/<li[^>]*>/gi,`
6
+ - `).replace(/<(br|\/p|\/div|\/tr|\/h[1-6]|\/li|\/pre|\/section|\/article)[^>]*>/gi,`
7
+ `).replace(/<a\s[^>]*href="([^"#][^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,(n,o,s)=>`${s} (${o})`).replace(/<[^>]+>/g,"").replace(/&(#\d+|#x[0-9a-f]+|[a-z]+);/gi,(n,o)=>o[0]==="#"?String.fromCodePoint(o[1]?.toLowerCase()==="x"?parseInt(o.slice(2),16):parseInt(o.slice(1),10)):ii[o.toLowerCase()]??n);return t=t.split(`
8
+ `).map(n=>n.replace(/[ \t\f\v]+/g," ").trim()).join(`
9
+ `).replace(/\n{3,}/g,`
10
+
11
+ `),t.trim()}async function Jt(e,t,n=fetch){let o=ri(e),s=await n(o,{redirect:"follow",headers:{"user-agent":"ScopeIDE-agent/1.0 (+https://scopeide.com)",accept:"text/html,text/plain,application/json,*/*;q=0.5"},signal:t?AbortSignal.any([t,AbortSignal.timeout(Lo)]):AbortSignal.timeout(Lo)}),r=s.headers.get("content-type")??"";if(!/text|json|xml|javascript/.test(r))return`${s.status} ${o} \u2014 ${r||"unknown type"}: not a text page (not read)`;let i=await s.arrayBuffer(),c=new TextDecoder().decode(i.byteLength>No?i.slice(0,No):i),u=/html/.test(r)?ai(c):c;return ue(`${s.status} ${s.url||o}
12
+
13
+ ${u}`,F.maxToolOutputBytes)}var li=1e6,Un=(e,t=F.maxToolOutputBytes)=>ue(e,t);function De(e,t,n){let{abs:o,inside:s}=Fe(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&&Ue.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>li)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 ci=(e,t)=>e.slice(0,t).split(`
14
+ `).length;async function Do(e,t,n){let o=n.remote;switch(e){case"read_file":return Un(await Fo(o,De(n,t.path,!1),t.path));case"write_file":{let s=De(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=De(n,t.path,!0),r=await Fo(o,s,t.path),{old_string:i,new_string:c}=t;if(i===c)throw new Error(l("agent.tools.old_string_and_new_string","old_string and new_string are identical"));!r.includes(i)&&r.includes(`\r
15
+ `)&&!i.includes("\r")&&(i=i.replace(/\n/g,`\r
6
16
  `),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,dr(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)&&!Be(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?_t(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]),g=Me.posix.relative(n.root,u);if(!Be(Me.posix.basename(u))&&!(r&&!r.test(g)&&!r.test(Me.posix.basename(u)))&&(a.push(`${g}:${d[2]}: ${d[3].slice(0,300)}`),a.length>=200))return Rn(a.join(`
17
+ `));let u=r.indexOf(i);if(u<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=r.split(i).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.writeFile(s,r.slice(0,u)+c+r.slice(u+i.length)),l("agent.tools.edited_file","edited {0} (line {1})",t.path,ci(r,u))}case"list_dir":{let s=De(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 i=(await o.readdir(s)).filter(u=>![".git","node_modules",".next","dist",".turbo",".forge",".command"].includes(u.name)&&!Ve(u.name));i.sort((u,d)=>Number(d.isDir)-Number(u.isDir)||u.name.localeCompare(d.name));let c=i.slice(0,500).map(u=>u.name+(u.isDir?"/":""));return i.length>500&&c.push(`\u2026[${i.length-500} more]`),c.join(`
18
+ `)||"(empty)"}case"grep":{let s=De(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?Tt(t.glob):null,i=[];for(let c of await o.grep(t.pattern,s,2e3)){let u=/^(.*?):(\d+):(.*)$/.exec(c);if(!u)continue;let d=Ue.posix.resolve(s,u[1]),p=Ue.posix.relative(n.root,d);if(!Ve(Ue.posix.basename(d))&&!(r&&!r.test(p)&&!r.test(Ue.posix.basename(d)))&&(i.push(`${p}:${u[2]}: ${u[3].slice(0,300)}`),i.length>=200))return Un(i.join(`
9
19
  `)+`
10
- \u2026[200 match limit]`)}return a.join(`
11
- `)||"no matches"}case"run_shell":{let s=Ee(n,t.cwd??".",!1),r=Lt(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}
20
+ \u2026[200 match limit]`)}return i.join(`
21
+ `)||"no matches"}case"run_shell":{let s=De(n,t.cwd??".",!1),r=Gt(t.command,{root:n.root,cwd:s,allowAll:n.allowAll,posix:!0});if(!r.ok)throw new Error(r.reason);if(t.background)throw new Error("background commands are not available in SSH workspaces; run it in the terminal instead");let i=t.timeout_ms??n.shellTimeoutMs??12e4,c=await o.exec(t.command,s,i);return l("agent.tools.shell_result",`exit code: {0}{1}{2}
12
22
  --- stdout ---
13
23
  {3}
14
24
  --- stderr ---
15
- {4}`,c.code??"?",c.timedOut?` (timed out after ${a}ms)`:"","",ge(c.stdout,Math.floor(D.maxToolOutputBytes*.65)),ge(c.stderr,Math.floor(D.maxToolOutputBytes*.3)))}case"glob":{let s=Ee(n,t.path??".",!1),r=_t(t.pattern),a=[];for(let c of await o.walk(s)){if(Be(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 Rn(s.join(`
25
+ {4}`,c.code??"?",c.timedOut?` (timed out after ${i}ms)`:"","",ue(c.stdout,Math.floor(F.maxToolOutputBytes*.65)),ue(c.stderr,Math.floor(F.maxToolOutputBytes*.3)))}case"glob":{let s=De(n,t.path??".",!1),r=Tt(t.pattern),i=[];for(let c of await o.walk(s)){if(Ve(Ue.posix.basename(c)))continue;let u=Ue.posix.relative(n.root,c);if((r.test(u)||r.test(Ue.posix.basename(c)))&&(i.push(u),i.length>=200))break}return i.join(`
26
+ `)||"no matching files found"}case"read_multiple_files":{let s=[];for(let r of t.paths)try{let i=await o.readFile(De(n,r,!1));s.push(i.includes(0)?`=== ${r} (binary file skipped) ===`:`=== ${r} ===
27
+ ${i.toString("utf8")}`)}catch(i){s.push(`=== ${r} (error: ${i.message}) ===`)}return Un(s.join(`
18
28
 
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"]),Dt=new Set;function fr(){if(globalThis.__forgeCleanupRegistered)return;globalThis.__forgeCleanupRegistered=!0;let e=()=>{for(let t of Dt)try{ur.unlinkSync(t)}catch{}Dt.clear()};process.once("exit",e),process.once("SIGINT",()=>{e(),process.exit(130)}),process.once("SIGTERM",()=>{e(),process.exit(143)})}function Be(e){return e.endsWith(".tmp")||e.includes(".tmp.")||e.includes(".cc-edit.tmp")||e.endsWith(".swp")||e.endsWith("~")||e.startsWith(".#")}async function hr(e){try{let t=M.join(e,".git"),n=await E.stat(t).catch(()=>null);if(!n)return;let o=M.join(t,"info");if(!n.isDirectory()){let a=await E.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 E.readFile(s,"utf8").catch(()=>"");if(!r.includes(".forge")){await E.mkdir(o,{recursive:!0});let a=(r.endsWith(`
29
+ `))}case"shell_output":throw new Error("background commands are not available in SSH workspaces");case"web_fetch":return Jt(t.url);case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.");case"todo_write":return Bn(t.todos)}}import{spawn as ui}from"child_process";import Wn from"fs";import di from"os";import mi from"path";var Et=new Map,pi=0,Uo=!1;function Bo(e){try{process.kill(-e.child.pid,"SIGTERM")}catch{}}function Wo(e,t){Uo||(Uo=!0,process.once("exit",()=>{for(let c of Et.values())c.exit===void 0&&Bo(c)}));let n=`bg${++pi}`,o=mi.join(di.tmpdir(),`scope-${process.pid}-${n}.log`),s=Wn.openSync(o,"a"),r=ui("/bin/sh",["-c",e],{cwd:t,env:Se(process.env),detached:!0,stdio:["ignore",s,s]});Wn.closeSync(s);let i={id:n,command:e,child:r,log:o,started:Date.now(),exit:void 0};return r.on("exit",c=>{i.exit=c}),r.on("error",()=>{i.exit=127}),Et.set(n,i),`Started in the background as ${n} (pid ${r.pid}). Read its output with shell_output {"id": "${n}"}; stop it with {"id": "${n}", "kill": true}.`}async function qo(e,t=!1){let n=Et.get(e);if(!n)throw new Error(`no background command "${e}"${Et.size?` (running: ${[...Et.keys()].join(", ")})`:""}`);t&&n.exit===void 0&&(Bo(n),await new Promise(i=>setTimeout(i,300)));let o="";try{o=Wn.readFileSync(n.log,"utf8")}catch{}let s=o.length>F.maxToolOutputBytes*.8?"\u2026"+o.slice(-Math.floor(F.maxToolOutputBytes*.8)):o,r=n.exit===void 0?`running for ${Math.round((Date.now()-n.started)/1e3)}s`:`exited with code ${n.exit??"?"}`;return ue(`${e}: ${r} \u2014 ${n.command}
30
+ --- output (end) ---
31
+ ${s}`,F.maxToolOutputBytes)}var Go=new Set([".git","node_modules",".next","dist",".turbo",".forge",".command"]),Yt=new Set;function _i(){if(globalThis.__forgeCleanupRegistered)return;globalThis.__forgeCleanupRegistered=!0;let e=()=>{for(let t of Yt)try{gi.unlinkSync(t)}catch{}Yt.clear()};process.once("exit",e),process.once("SIGINT",()=>{e(),process.exit(130)}),process.once("SIGTERM",()=>{e(),process.exit(143)})}function Ve(e){return e.endsWith(".tmp")||e.includes(".tmp.")||e.includes(".cc-edit.tmp")||e.endsWith(".swp")||e.endsWith("~")||e.startsWith(".#")}async function yi(e){try{let t=P.join(e,".git"),n=await C.stat(t).catch(()=>null);if(!n)return;let o=P.join(t,"info");if(!n.isDirectory()){let i=await C.readFile(t,"utf8").catch(()=>""),c=/^gitdir:\s*(.+)$/m.exec(i);if(c){let u=P.resolve(e,c[1].trim());o=P.join(u,"info")}}let s=P.join(o,"exclude"),r=await C.readFile(s,"utf8").catch(()=>"");if(!r.includes(".forge")){await C.mkdir(o,{recursive:!0});let i=(r.endsWith(`
20
32
  `)||r.length===0?"":`
21
33
  `)+`# Forge internal files
22
34
  .forge
23
35
  .forge/**
24
- `;await E.appendFile(s,a,"utf8")}}catch{}}async function xo(e){let t=0;try{let n=await E.readdir(e,{withFileTypes:!0});for(let o of n)if(o.isFile()&&Be(o.name))try{await E.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 E.rm(o,{recursive:!0,force:!0}).catch(()=>{}),await E.rm(s,{recursive:!0,force:!0}).catch(()=>{}),(await E.readdir(n).catch(()=>["err"])).length===0&&await E.rmdir(n).catch(()=>{})}catch{}await hr(e).catch(()=>{});try{let n=M.join(ko(),"tmp"),o=await E.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 E.stat(a).catch(()=>null);c&&s-c.mtimeMs>36e5&&(await E.unlink(a).catch(()=>{}),t++)}}catch{}return t}var ko=()=>M.join(yo.homedir(),_.dirName),_r=(e,t)=>{let n=M.relative(M.resolve(e),M.resolve(t));return!!n&&!n.startsWith("..")&&!M.isAbsolute(n)};async function _o(e,t,n){fr();let o=ko(),s=M.join(o,"tmp");await E.mkdir(s,{recursive:!0});let r=M.join(s,`${M.basename(e)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.tmp`);Dt.add(r);let a;try{let c=await E.stat(e);if(a=c.mode,c.isFile()&&!_r(yo.tmpdir(),e)){let d=M.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_")||"project",u=mr.createHash("sha256").update(n).digest("hex").slice(0,8),g=M.join(o,"backups",`${d}-${u}`);await E.mkdir(g,{recursive:!0});let h=M.join(g,`${M.basename(e)}.${Date.now()}.bak`);await E.copyFile(e,h).catch(()=>{})}}catch{}try{await E.mkdir(M.dirname(e),{recursive:!0}),await E.writeFile(r,t,{encoding:"utf8",mode:a}),await E.rename(r,e)}catch(c){if(c?.code==="EXDEV")try{await E.copyFile(r,e)}catch{await E.writeFile(e,t,{encoding:"utf8",mode:a})}else await E.writeFile(e,t,{encoding:"utf8",mode:a})}finally{Dt.delete(r);try{await E.unlink(r)}catch{}}}var Xe={read_file:O.object({path:O.string().min(1)}),write_file:O.object({path:O.string().min(1),content:O.string()}),edit_file:O.object({path:O.string().min(1),old_string:O.string().min(1),new_string:O.string()}),list_dir:O.object({path:O.string().default(".")}),grep:O.object({pattern:O.string().min(1),path:O.string().optional(),glob:O.string().optional()}),run_shell:O.object({command:O.string().min(1),cwd:O.string().optional()}),glob:O.object({pattern:O.string().min(1),path:O.string().optional()}),read_multiple_files:O.object({paths:O.array(O.string().min(1)).min(1)}),think:O.object({thought:O.string().min(1)})},wt=Object.keys(Xe),wr={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 Cn(){return wt.map(e=>{let t=gr(Xe[e],{target:"openApi3",$refStrategy:"none"});return delete t.$schema,{name:e,description:l(`agent.tool.${e}.description`,wr[e]),parameters:t}})}var En=(e,t=D.maxToolOutputBytes)=>ge(e,t),$o=1e6;async function yr(e){let t=e,n=[];for(;;)try{return M.join(await E.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}=_e(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 E.realpath(e.root),a=await yr(o);if(!_e(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 vo(e,t){return!(e.remote?Ue:_e)(e.root,t).inside}function _t(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*Mn(e){for(let t of await E.readdir(e,{withFileTypes:!0}))t.isDirectory()?bo.has(t.name)||(yield*Mn(M.join(e,t.name))):t.isFile()&&!Be(t.name)&&(yield M.join(e,t.name))}async function wo(e,t){let n;try{n=await E.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>$o)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 E.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 br(e,t){return e.slice(0,t).split(`
25
- `).length}async function Ze(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 En(await wo(o,t.path))}case"write_file":{let o=await Ce(n,t.path,!0),s=!1;try{if((await E.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
36
+ `;await C.appendFile(s,i,"utf8")}}catch{}}async function Jo(e){let t=0;try{let n=await C.readdir(e,{withFileTypes:!0});for(let o of n)if(o.isFile()&&Ve(o.name))try{await C.unlink(P.join(e,o.name)),t++}catch{}}catch{}try{let n=P.join(e,".forge"),o=P.join(n,"tmp"),s=P.join(n,"backups");await C.rm(o,{recursive:!0,force:!0}).catch(()=>{}),await C.rm(s,{recursive:!0,force:!0}).catch(()=>{}),(await C.readdir(n).catch(()=>["err"])).length===0&&await C.rmdir(n).catch(()=>{})}catch{}await yi(e).catch(()=>{});try{let n=P.join(Yo(),"tmp"),o=await C.readdir(n,{withFileTypes:!0}).catch(()=>[]),s=Date.now();for(let r of o)if(r.isFile()){let i=P.join(n,r.name),c=await C.stat(i).catch(()=>null);c&&s-c.mtimeMs>36e5&&(await C.unlink(i).catch(()=>{}),t++)}}catch{}return t}var Yo=()=>P.join(Ko.homedir(),w.dirName),bi=(e,t)=>{let n=P.relative(P.resolve(e),P.resolve(t));return!!n&&!n.startsWith("..")&&!P.isAbsolute(n)};async function Ho(e,t,n){_i();let o=Yo(),s=P.join(o,"tmp");await C.mkdir(s,{recursive:!0});let r=P.join(s,`${P.basename(e)}.${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.tmp`);Yt.add(r);let i;try{let c=await C.stat(e);if(i=c.mode,c.isFile()&&!bi(Ko.tmpdir(),e)){let u=P.basename(n).replace(/[^a-zA-Z0-9._-]/g,"_")||"project",d=fi.createHash("sha256").update(n).digest("hex").slice(0,8),p=P.join(o,"backups",`${u}-${d}`);await C.mkdir(p,{recursive:!0});let g=P.join(p,`${P.basename(e)}.${Date.now()}.bak`);await C.copyFile(e,g).catch(()=>{})}}catch{}try{await C.mkdir(P.dirname(e),{recursive:!0}),await C.writeFile(r,t,{encoding:"utf8",mode:i}),await C.rename(r,e)}catch(c){if(c?.code==="EXDEV")try{await C.copyFile(r,e)}catch{await C.writeFile(e,t,{encoding:"utf8",mode:i})}else await C.writeFile(e,t,{encoding:"utf8",mode:i})}finally{Yt.delete(r);try{await C.unlink(r)}catch{}}}function Bn(e){let t=e.filter(o=>o.status==="completed").length,n=e.filter(o=>o.status==="in_progress");return`Todo list updated: ${t}/${e.length} done${n[0]?`; now: ${n[0].content}`:""}.`+(n.length>1?" Keep only one item in_progress.":"")}var ut={read_file:E.object({path:E.string().min(1)}),write_file:E.object({path:E.string().min(1),content:E.string()}),edit_file:E.object({path:E.string().min(1),old_string:E.string().min(1),new_string:E.string()}),list_dir:E.object({path:E.string().default(".")}),grep:E.object({pattern:E.string().min(1),path:E.string().optional(),glob:E.string().optional()}),run_shell:E.object({command:E.string().min(1),cwd:E.string().optional(),timeout_ms:E.number().int().min(1e3).max(6e5).optional(),background:E.boolean().optional()}),shell_output:E.object({id:E.string().min(1),kill:E.boolean().optional()}),web_fetch:E.object({url:E.string().min(1)}),glob:E.object({pattern:E.string().min(1),path:E.string().optional()}),read_multiple_files:E.object({paths:E.array(E.string().min(1)).min(1)}),think:E.object({thought:E.string().min(1)}),todo_write:E.object({todos:E.array(E.object({content:E.string().min(1),status:E.enum(["pending","in_progress","completed"])})).max(30)})},Rt=Object.keys(ut),ki={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). Default timeout 120 s; pass timeout_ms (up to 600000) for a long build or render. For servers, watchers or anything that keeps running, pass background: true and read it later with shell_output.",web_fetch:"Fetch a web page (documentation, an error message's answer, an API reference) and read it as text. Needs the user's approval. Prefer official docs.",shell_output:"Read the status and the latest output of a background command started with run_shell background: true; kill: true stops it.",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.",todo_write:"Keep a short task list for work with 3 or more steps: send the WHOLE list each time (pending / in_progress / completed), exactly one in_progress while working. Update it as you finish steps; it keeps you on track and shows the user your progress. Skip it for small tasks."};function zn(){return Rt.map(e=>{let t=wi(ut[e],{target:"openApi3",$refStrategy:"none"});return delete t.$schema,{name:e,description:l(`agent.tool.${e}.description`,ki[e]),parameters:t}})}var qn=(e,t=F.maxToolOutputBytes)=>ue(e,t),Xo=1e6;async function xi(e){let t=e,n=[];for(;;)try{return P.join(await C.realpath(t),...n.reverse())}catch{let o=P.dirname(t);if(o===t)return e;n.push(P.basename(t)),t=o}}async function Be(e,t,n){let{abs:o,inside:s}=ce(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 C.realpath(e.root),i=await xi(o);if(!ce(r,i).inside)throw new Error(l("agent.tools.path_0_resolves_outside_the",'path "{0}" resolves outside the project root (symlink)',t));if(n&&P.relative(e.root,o).split(P.sep).includes(".git"))throw new Error(l("agent.tools.modifying_git_is_not_allowed","modifying .git is not allowed"));return o}function Vo(e,t){return!(e.remote?Fe:ce)(e.root,t).inside}function Tt(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*Hn(e){for(let t of await C.readdir(e,{withFileTypes:!0}))t.isDirectory()?Go.has(t.name)||(yield*Hn(P.join(e,t.name))):t.isFile()&&!Ve(t.name)&&(yield P.join(e,t.name))}async function zo(e,t){let n;try{n=await C.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>Xo)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 C.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 $i(e,t){return e.slice(0,t).split(`
37
+ `).length}async function dt(e,t,n){if(n.remote)return Do(e,t,n);switch(e){case"read_file":{let o=await Be(n,t.path,!1);return qn(await zo(o,t.path))}case"write_file":{let o=await Be(n,t.path,!0),s=!1;try{if((await C.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 Ho(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 Be(n,t.path,!0),s=await zo(o,t.path),{old_string:r,new_string:i}=t;if(r===i)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
38
  `)&&!r.includes("\r")&&(r=r.replace(/\n/g,`\r
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 _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,br(s,c))}case"list_dir":{let o=await Ce(n,t.path??".",!1),s;try{s=await E.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)&&!Be(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?_t(t.glob):null,a;try{a=await E.stat(o)}catch{throw new Error(l("agent.tools.path_not_found_0","path not found: {0}",t.path))}let c=a.isFile()?[o]:Mn(o),d=[];for await(let u of c){let g=M.relative(n.root,u);if(r&&!r.test(g)&&!r.test(M.basename(u)))continue;let h;try{if((await E.stat(u)).size>$o)continue;let x=await E.readFile(u);if(x.includes(0))continue;h=x.toString("utf8")}catch{continue}let y=h.split(`
30
- `);for(let x=0;x<y.length;x++)if(s.test(y[x])&&d.push(`${g}:${x+1}: ${y[x].slice(0,300)}`),d.length>=200)return En(d.join(`
39
+ `),i=i.replace(/\n/g,`\r
40
+ `));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 u=s.split(r).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 Ho(o,s.slice(0,c)+i+s.slice(c+r.length),n.root),l("agent.tools.edited_file","edited {0} (line {1})",t.path,$i(s,c))}case"list_dir":{let o=await Be(n,t.path??".",!1),s;try{s=await C.readdir(o,{withFileTypes:!0})}catch(i){throw new Error(i.code==="ENOTDIR"?`${t.path} is a file; use read_file`:`directory not found: ${t.path}`)}s=s.filter(i=>!Go.has(i.name)&&!Ve(i.name)),s.sort((i,c)=>Number(c.isDirectory())-Number(i.isDirectory())||i.name.localeCompare(c.name));let r=s.slice(0,500).map(i=>i.name+(i.isDirectory()?"/":""));return s.length>500&&r.push(`\u2026[${s.length-500} more]`),r.join(`
41
+ `)||"(empty)"}case"grep":{let o=await Be(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?Tt(t.glob):null,i;try{i=await C.stat(o)}catch{throw new Error(l("agent.tools.path_not_found_0","path not found: {0}",t.path))}let c=i.isFile()?[o]:Hn(o),u=[];for await(let d of c){let p=P.relative(n.root,d);if(r&&!r.test(p)&&!r.test(P.basename(d)))continue;let g;try{if((await C.stat(d)).size>Xo)continue;let b=await C.readFile(d);if(b.includes(0))continue;g=b.toString("utf8")}catch{continue}let k=g.split(`
42
+ `);for(let b=0;b<k.length;b++)if(s.test(k[b])&&u.push(`${p}:${b+1}: ${k[b].slice(0,300)}`),u.length>=200)return qn(u.join(`
31
43
  `)+`
32
- \u2026[200 match limit]`)}return d.join(`
33
- `)||"no matches"}case"run_shell":{let o=await Ce(n,t.cwd??".",!1),s=Lt(t.command,{root:n.root,cwd:o,allowAll:n.allowAll});if(!s.ok)throw new Error(s.reason);return await xr(t.command,o,n.shellTimeoutMs??12e4)}case"glob":{let o=await Ce(n,t.path??".",!1),s=_t(t.pattern),r=[];for await(let a of Mn(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 E.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 En(o.join(`
44
+ \u2026[200 match limit]`)}return u.join(`
45
+ `)||"no matches"}case"run_shell":{let o=await Be(n,t.cwd??".",!1),s=Gt(t.command,{root:n.root,cwd:o,allowAll:n.allowAll});if(!s.ok)throw new Error(s.reason);return t.background?Wo(t.command,o):await vi(t.command,o,t.timeout_ms??n.shellTimeoutMs??12e4,n.signal)}case"web_fetch":return await Jt(t.url,n.signal);case"shell_output":return await qo(t.id,!!t.kill);case"glob":{let o=await Be(n,t.path??".",!1),s=Tt(t.pattern),r=[];for await(let i of Hn(o)){let c=P.relative(n.root,i);if((s.test(c)||s.test(P.basename(i)))&&(r.push(c),r.length>=200))break}return r.join(`
46
+ `)||"no matching files found"}case"read_multiple_files":{let o=[];for(let s of t.paths)try{let r=await Be(n,s,!1),i=await C.readFile(r);i.includes(0)?o.push(`=== ${s} (binary file skipped) ===`):o.push(`=== ${s} ===
47
+ ${i.toString("utf8")}`)}catch(r){o.push(`=== ${s} (error: ${r.message}) ===`)}return qn(o.join(`
36
48
 
37
- `))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.")}}var Ut=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}
49
+ `))}case"think":return l("agent.tools.thought_recorded","Thought recorded. Proceed with actions.");case"todo_write":return Bn(t.todos)}}var Xt=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
50
  \u2026[${this.dropped} chars omitted]\u2026
39
- ${this.tail}`:this.head+this.tail}};function xr(e,t,n){return new Promise(o=>{let s=pr("/bin/sh",["-c",e],{cwd:t,env:Ft(process.env),detached:!0,stdio:["ignore","pipe","pipe"]}),r=!1,a=new Ut,c=new Ut;s.stdout.on("data",y=>a.add(y)),s.stderr.on("data",y=>c.add(y));let d=setTimeout(()=>{r=!0;try{process.kill(-s.pid,"SIGKILL")}catch{}},n),u=(y,x="")=>{clearTimeout(d),o(l("agent.tools.shell_result",`exit code: {0}{1}{2}
51
+ ${this.tail}`:this.head+this.tail}};function vi(e,t,n,o){return new Promise(s=>{if(o?.aborted){s("exit code: ? (stopped by the user)");return}let r=hi("/bin/sh",["-c",e],{cwd:t,env:Se(process.env),detached:!0,stdio:["ignore","pipe","pipe"]}),i=!1,c=new Xt,u=new Xt;r.stdout.on("data",_=>c.add(_)),r.stderr.on("data",_=>u.add(_));let d=setTimeout(()=>{i=!0;try{process.kill(-r.pid,"SIGKILL")}catch{}},n),p=()=>{try{process.kill(-r.pid,"SIGKILL")}catch{}};o?.addEventListener("abort",p,{once:!0});let g=(_,x="")=>{clearTimeout(d),o?.removeEventListener("abort",p),o?.aborted&&(x+=" (stopped by the user)"),s(l("agent.tools.shell_result",`exit code: {0}{1}{2}
40
52
  --- stdout ---
41
53
  {3}
42
54
  --- stderr ---
43
- {4}`,y??"?",r?` (timed out after ${n}ms)`:"",x,ge(a.text(),Math.floor(D.maxToolOutputBytes*.65)),ge(c.text(),Math.floor(D.maxToolOutputBytes*.3))))};s.on("error",y=>u(127,` (${y.message})`));let g=!1,h=(y,x="")=>{g||(g=!0,u(y,x))};s.on("close",y=>h(y)),s.on("exit",y=>{setTimeout(()=>{if(!g){try{process.kill(-s.pid,"SIGTERM")}catch{}setTimeout(()=>{try{process.kill(-s.pid,"SIGKILL")}catch{}},1e3).unref(),h(y," (background processes it started were stopped; run long-lived servers in the terminal instead)")}},400)})})}var So={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"},To={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 kr(e){if(wt.includes(e))return e;let t=e.trim().toLowerCase().replace(/[-\s]/g,"_");return wt.includes(t)?t:So[t]??So[t.replace(/_/g,"")]??null}function Ro(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 $r(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 vr(e){try{return JSON.parse(e)}catch{return}}function Eo(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":'),Ro(o),s>=0&&r>s?o.slice(s,r+1):o,s>=0?$r(Ro(o.slice(s)).replace(/,\s*$/,"")):o],c;for(let d of a)if(c=vr(d),c!==void 0)break;if(c===void 0)return;t=c}return t}function Sr(e,t){if(Object.keys(e).some(n=>n in t))return e;for(let n of["arguments","parameters","params","input","args"]){let o=Eo(e[n]);if(o&&typeof o=="object"&&!Array.isArray(o))return o}return e}function Bt(e,t){let n=kr(e);if(!n)return{ok:!1,error:`unknown tool "${e}". Available: ${wt.join(", ")}`};let o=Eo(t);if(o==null||typeof o!="object"||Array.isArray(o))return{ok:!1,error:`arguments for ${n} are not a valid JSON object`};let s=Xe[n].shape,r=Sr(o,s),a=Xe[n].safeParse(r),c=n!==e;if(a.success)return{ok:!0,name:n,args:a.data,repaired:c};let d={};for(let[h,y]of Object.entries(r)){let x=h in s?h:To[h]??To[h.toLowerCase()]??h;x in s&&!(x in d)&&(d[x]=y)}n==="grep"&&d.pattern===void 0&&typeof d.path=="string"&&r.query&&(d.pattern=r.query);for(let h of["path","cwd"])typeof d[h]=="number"&&(d[h]=String(d[h]));n==="run_shell"&&Array.isArray(d.command)&&(d.command=d.command.join(" "));let u=Xe[n].safeParse(d);if(u.success)return{ok:!0,name:n,args:u.data,repaired:!0};let g=u.error.issues.map(h=>`${h.path.join(".")||"(root)"}: ${h.message}`).join("; ");return{ok:!1,error:`invalid arguments for ${n}: ${g}. Expected: ${Object.keys(s).join(", ")}`}}import qt from"fs/promises";import Wt from"path";var Tr=12e3,Mo=500,Co=8e3;async function Po(e,t){try{return _e(await qt.realpath(e),await qt.realpath(t)).inside}catch{return!0}}async function Pn(e){try{let t=await qt.readFile(e,"utf8");return t.length>Co?t.slice(0,Co)+`
45
- \u2026[truncated]`:t}catch{return null}}function Qe(e){if(!e)return null;let t=e.replace(/<!--[\s\S]*?-->/g,"").trim();return t.split(/\r?\n/).some(n=>n.trim()&&!n.trim().startsWith("#"))?t:null}async function Ao(e,t){let n=[`Project root: ${e}`],o=async c=>await Po(e,c)?Pn(c):null,s=await o(Wt.join(e,_.dirName,"skills.md")),r=await o(Wt.join(e,_.dirName,"memory.md")),a=t?await Pn(Wt.join(t,_.dirName,"memory.md")):null;return Qe(s)&&n.push(`## Project skills \u2014 conventions you MUST follow in this repo
55
+ {4}`,_??"?",i?` (timed out after ${n}ms)`:"",x,ue(c.text(),Math.floor(F.maxToolOutputBytes*.65)),ue(u.text(),Math.floor(F.maxToolOutputBytes*.3))))};r.on("error",_=>g(127,` (${_.message})`));let k=!1,b=(_,x="")=>{k||(k=!0,g(_,x))};r.on("close",_=>b(_)),r.on("exit",_=>{setTimeout(()=>{if(!k){try{process.kill(-r.pid,"SIGTERM")}catch{}setTimeout(()=>{try{process.kill(-r.pid,"SIGKILL")}catch{}},1e3).unref(),b(_," (background processes it started were stopped; run long-lived servers in the terminal instead)")}},400)})})}var Zo={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"},Qo={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 Si(e){if(Rt.includes(e))return e;let t=e.trim().toLowerCase().replace(/[-\s]/g,"_");return Rt.includes(t)?t:Zo[t]??Zo[t.replace(/_/g,"")]??null}function es(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===`
56
+ `){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 Ti(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 Ei(e){try{return JSON.parse(e)}catch{return}}function ts(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("}"),i=[o,o.replace(/,\s*([}\]])/g,"$1").replace(/([{,]\s*)'([^']+)'\s*:/g,'$1"$2":'),es(o),s>=0&&r>s?o.slice(s,r+1):o,s>=0?Ti(es(o.slice(s)).replace(/,\s*$/,"")):o],c;for(let u of i)if(c=Ei(u),c!==void 0)break;if(c===void 0)return;t=c}return t}function Ri(e,t){if(Object.keys(e).some(n=>n in t))return e;for(let n of["arguments","parameters","params","input","args"]){let o=ts(e[n]);if(o&&typeof o=="object"&&!Array.isArray(o))return o}return e}function Vt(e,t){let n=Si(e);if(!n)return{ok:!1,error:`unknown tool "${e}". Available: ${Rt.join(", ")}`};let o=ts(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=ut[n].shape,r=Ri(o,s),i=ut[n].safeParse(r),c=n!==e;if(i.success)return{ok:!0,name:n,args:i.data,repaired:c};let u={};for(let[g,k]of Object.entries(r)){let b=g in s?g:Qo[g]??Qo[g.toLowerCase()]??g;b in s&&!(b in u)&&(u[b]=k)}n==="grep"&&u.pattern===void 0&&typeof u.path=="string"&&r.query&&(u.pattern=r.query);for(let g of["path","cwd"])typeof u[g]=="number"&&(u[g]=String(u[g]));n==="run_shell"&&Array.isArray(u.command)&&(u.command=u.command.join(" "));let d=ut[n].safeParse(u);if(d.success)return{ok:!0,name:n,args:d.data,repaired:!0};let p=d.error.issues.map(g=>`${g.path.join(".")||"(root)"}: ${g.message}`).join("; ");return{ok:!1,error:`invalid arguments for ${n}: ${p}. Expected: ${Object.keys(s).join(", ")}`}}import Qt from"fs/promises";import Zt from"path";import mt from"fs/promises";import Kn from"os";import Ze from"path";var Mi=50,Ai=300,ns=6e4,Mt="use_skill",Ci=(e,t=Kn.homedir())=>[{dir:Ze.join(e,w.dirName,"skills"),scope:"project"},...t?[{dir:Ze.join(t,w.dirName,"skills"),scope:"personal"}]:[]];function os(e){let t=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(e);if(!t)return{meta:{},body:e};let n={};for(let o of t[1].split(/\r?\n/)){let s=/^([A-Za-z0-9_-]+):\s*(.*)$/.exec(o);s&&(n[s[1]]=s[2].trim().replace(/^(["'])(.*)\1$/,"$2"))}return{meta:n,body:t[2]}}async function At(e,t=Kn.homedir()){let n=new Map;for(let{dir:o,scope:s}of Ci(e,t)){let r=[];try{r=await mt.readdir(o,{withFileTypes:!0})}catch{continue}for(let i of r.sort((c,u)=>c.name.localeCompare(u.name))){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let c=Ze.join(o,i.name),u;try{u=await mt.readFile(Ze.join(c,"SKILL.md"),"utf8")}catch{continue}let{meta:d}=os(u),p=(d.name||i.name).trim();if(n.has(p)||n.set(p,{name:p,description:(d.description||"").slice(0,Ai),dir:c,scope:s}),n.size>=Mi)break}}return[...n.values()]}function ss(e){return e.length?`## Skills (load one with use_skill before doing work it covers)
57
+ ${e.map(t=>`- ${t.name}: ${t.description||"(no description)"}`).join(`
58
+ `)}`:""}var rs={name:Mt,description:"Load a skill listed under 'Skills' in your instructions: returns its SKILL.md and folder path. With `file`, returns another file of that skill (e.g. references/captions.md). Run a skill's scripts with run_shell using the folder path.",parameters:{type:"object",properties:{name:{type:"string"},file:{type:"string",description:"optional: a file inside the skill folder"}},required:["name"]}};async function is(e,t,n=Kn.homedir()){let o;try{o=JSON.parse(t||"{}")}catch{throw new Error('arguments must be JSON like {"name": "edit-video"}')}let s=String(o.name??"").trim(),r=(await At(e,n)).find(k=>k.name===s);if(!r)throw new Error(`no skill named "${s}"`);let i=typeof o.file=="string"&&o.file.trim()?o.file.trim():"SKILL.md",c=await mt.realpath(r.dir),u=await mt.realpath(Ze.resolve(c,i)).catch(()=>{throw new Error(`${i}: not found in skill ${s}`)}),d=Ze.relative(c,u);if(d.startsWith("..")||Ze.isAbsolute(d))throw new Error(`${i} is outside the skill folder`);let p=await mt.readFile(u,"utf8");if(p.length>ns&&(p=p.slice(0,ns)+`
59
+ \u2026[truncated]`),i!=="SKILL.md")return`=== ${s}/${d} ===
60
+ ${p}`;let g=[];try{g=(await mt.readdir(c,{recursive:!0})).map(String).filter(k=>k!=="SKILL.md").slice(0,60)}catch{}return`Skill "${s}" (folder: ${c})
61
+ ${g.length?`Files: ${g.join(", ")}
62
+ `:""}
63
+ ${os(p).body}`}var Pi=12e3,as=8e3;async function us(e,t){try{return ce(await Qt.realpath(e),await Qt.realpath(t)).inside}catch{return!0}}async function Jn(e){try{let t=await Qt.readFile(e,"utf8");return t.length>as?t.slice(0,as)+`
64
+ \u2026[truncated]`:t}catch{return null}}function pt(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 ds(e,t){let n=[`Project root: ${e}`],o=async u=>await us(e,u)?Jn(u):null,s=await o(Zt.join(e,w.dirName,"skills.md")),r=await o(Zt.join(e,w.dirName,"memory.md")),i=t?await Jn(Zt.join(t,w.dirName,"memory.md")):null;pt(s)&&n.push(`## Project skills \u2014 conventions you MUST follow in this repo
46
65
  (Set by the user in .forge/skills.md; they override your defaults.)
47
- ${Qe(s)}`),Qe(r)&&n.push(`## Project memory \u2014 facts about this project
48
- ${Qe(r)}`),Qe(a)&&n.push(`## Personal preferences \u2014 apply to all projects
49
- ${Qe(a)}`),n.join(`
66
+ ${pt(s)}`),pt(r)&&n.push(`## Project memory \u2014 facts about this project
67
+ ${pt(r)}`),pt(i)&&n.push(`## Personal preferences \u2014 apply to all projects
68
+ ${pt(i)}`);let c=ss(await At(e,t??null).catch(()=>[]));return c&&n.push(c),n.join(`
50
69
 
51
- `)}var No="Work in as few steps as possible. Put independent tool calls in ONE response: read every file you need at once, and make edits to different files in the same response. Use the project file list you are given instead of list_dir. Verify with tests or a one-shot script; never start a long-running server or watcher from a tool call. When the task is done, stop and reply briefly.";async function jo(e,t){let n=await Er(e).catch(()=>"");return n?`${t}
70
+ `)}var ms="Work in as few steps as possible. Put independent tool calls in ONE response: read every file you need at once, and make edits to different files in the same response. Use the project file list you are given instead of list_dir. Explore only until you can act: once you know enough to do the task, do it, and do not re-probe or re-measure what you already checked. Prefer one script that does several steps over many small commands. Verify with tests or a one-shot script, check once, fix what is wrong, then stop; never start a long-running server or watcher from a tool call. Old tool output may be cleared from your context to save tokens: note the facts you need in your reply as you go. When the task is done, stop and reply briefly.";async function ps(e,t){let n=await ji(e).catch(()=>"");return n?`${t}
52
71
 
53
72
  <project_files>
54
73
  ${n}
55
- </project_files>`:t}var Rr=new Set([".git","node_modules","vendor","dist","build",".next",".nuxt",".turbo",".cache","coverage",".venv","venv","__pycache__","target",".idea",".forge","storage","bootstrap"]);async function Er(e,t=200,n=4){let o=[],s=!1,r=async(a,c,d)=>{let u;try{u=await qt.readdir(a,{withFileTypes:!0})}catch{return}u=u.filter(g=>!(g.isDirectory()&&Rr.has(g.name))&&!(g.name.startsWith(".")&&g.name!==".env.example"&&g.name!==".github")).sort((g,h)=>Number(h.isDirectory())-Number(g.isDirectory())||g.name.localeCompare(h.name));for(let g of u){if(o.length>=t){s=!0;return}let h=c?`${c}/${g.name}`:g.name;g.isDirectory()?(o.push(`${h}/`),d<n&&await r(Wt.join(a,g.name),h,d+1)):g.isFile()&&o.push(h)}};return await r(e,"",1),o.length?o.join(`
74
+ </project_files>`:t}var Ii=new Set([".git","node_modules","vendor","dist","build",".next",".nuxt",".turbo",".cache","coverage",".venv","venv","__pycache__","target",".idea",".forge","storage","bootstrap"]);async function ji(e,t=200,n=4){let o=[],s=!1,r=async(i,c,u)=>{let d;try{d=await Qt.readdir(i,{withFileTypes:!0})}catch{return}d=d.filter(p=>!(p.isDirectory()&&Ii.has(p.name))&&!(p.name.startsWith(".")&&p.name!==".env.example"&&p.name!==".github")).sort((p,g)=>Number(g.isDirectory())-Number(p.isDirectory())||p.name.localeCompare(g.name));for(let p of d){if(o.length>=t){s=!0;return}let g=c?`${c}/${p.name}`:p.name;p.isDirectory()?(o.push(`${g}/`),u<n&&await r(Zt.join(i,p.name),g,u+1)):p.isFile()&&o.push(g)}};return await r(e,"",1),o.length?o.join(`
56
75
  `)+(s?`
57
- \u2026 (more files: use list_dir / glob)`:""):""}async function Io(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}=_e(e,s);if(!a||!await Po(e,r))continue;let c=await Pn(r);if(c!==null){let d=ge(c,Tr);o.push(`<file path="${s}">
58
- ${d}
76
+ \u2026 (more files: use list_dir / glob)`:""):""}async function gs(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:i}=ce(e,s);if(!i||!await us(e,r))continue;let c=await Jn(r);if(c!==null){let u=ue(c,Pi);o.push(`<file path="${s}">
77
+ ${u}
59
78
  </file>`)}}return o.length?`${t}
60
79
 
61
80
  ${o.join(`
62
81
 
63
- `)}`:t}function Ht(e){return ge(e,D.maxToolOutputBytes)}function zt(e,t=D.maxContextTokens*D.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>Mo?{...r,content:r.content.slice(0,Mo)+`
64
- \u2026[older output truncated]`}:r);n(o)>t;){let r=o.findIndex((c,d)=>d>0&&c.role==="user"),a=o.findIndex((c,d)=>d>r&&c.role==="user");if(r<0||a<0)break;o.splice(r,a-r)}return o}function et(e){let t=0;for(let n of e)if(t+=n.content?.length??0,n.role==="user"&&(t+=(n.images?.length??0)*6e3),n.role==="assistant")for(let o of n.tool_calls??[])t+=o.name.length+o.arguments.length;return Math.ceil(t/D.charsPerToken)}import jr from"fs/promises";import{spawn as Mr}from"child_process";import Gt from"fs/promises";import{createHash as Cr}from"crypto";import tt from"path";var Oo=1e4,Lo=2e3,Jt=["PreToolUse","PostToolUse"],Pr=e=>tt.join(e,_.dirName,"hooks.json"),Fo=()=>({PreToolUse:[],PostToolUse:[]});async function Do(e){let t=Fo();try{let n=JSON.parse(await Gt.readFile(e,"utf8"));for(let o of Jt){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 Kt=e=>Do(Pr(e)),We=e=>Jt.reduce((t,n)=>t+e[n].length,0),An=e=>tt.join(e,_.dirName,"trusted-hooks.json"),Uo=e=>Cr("sha256").update(JSON.stringify(e)).digest("hex");async function Bo(e){try{return JSON.parse(await Gt.readFile(An(e),"utf8"))}catch{return{}}}async function Wo(e,t){let n=await Bo(t);n[tt.resolve(e)]=Uo(await Kt(e)),await Gt.mkdir(tt.dirname(An(t)),{recursive:!0}),await Gt.writeFile(An(t),JSON.stringify(n,null,2),{mode:384})}async function yt(e,t){let n=await Do(tt.join(t,_.dirName,"hooks.json")),o=await Kt(e),s=We(o)===0||(await Bo(t))[tt.resolve(e)]===Uo(o),r={...Fo(),untrusted:s?[]:Jt.flatMap(a=>o[a])};for(let a of Jt)r[a]=[...n[a],...s?o[a]:[]];return r}function Ar(e,t,n){return new Promise(o=>{let s="",r="",a=!1,c=g=>{a||(a=!0,clearTimeout(u),o(g))},d=Mr("/bin/sh",["-c",e.command],{cwd:n,env:Ft(process.env),stdio:["pipe","pipe","pipe"]}),u=setTimeout(()=>{d.kill("SIGKILL"),c({code:null,text:"",error:`timed out after ${Oo/1e3}s`})},Oo);d.stdout.setEncoding("utf8"),d.stderr.setEncoding("utf8"),d.stdout.on("data",g=>{s=(s+g).slice(0,Lo)}),d.stderr.on("data",g=>{r=(r+g).slice(0,Lo)}),d.on("error",g=>c({code:null,text:"",error:`cannot start: ${g.message}`})),d.on("close",g=>c({code:g,text:r.trim()||s.trim()})),d.stdin.on("error",()=>{}),d.stdin.end(JSON.stringify(t))})}var Nr=(e,t)=>{if(!e.matcher)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!1}};async function Nn(e,t,n,o){let s={warnings:[]},r=e?.[t]?.filter(c=>Nr(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 Ar(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 Ko=new Set(["read_file","list_dir","grep","glob","read_multiple_files","think"]),qo=`
82
+ `)}`:t}function Ct(e){return ue(e,F.maxToolOutputBytes)}var ls=6,Oi=.6,Ni=6e3,en="[older output cleared to save context; run the tool again if you still need it]",Yn=()=>({cleared:new WeakSet}),Li=e=>e.role==="user"&&e.content.startsWith("[view_image]"),Gn=e=>(e.content?.length??0)+(e.role==="assistant"?e.tool_calls?.reduce((t,n)=>t+n.arguments.length,0)??0:0)+(e.role==="user"?(e.images?.length??0)*Ni:0);function cs(e){return e.role==="tool"?{...e,content:en}:e.role==="user"&&e.images?.length?{role:"user",content:`${e.content} [image cleared]`}:e}function Pt(e,t=F.maxContextTokens*F.charsPerToken,n){let o=n?.cleared??new WeakSet,s=b=>b.map(_=>o.has(_)?cs(_):_),r=b=>b.reduce((_,x)=>_+Gn(x),0),i=e.filter(b=>b.role==="user"&&!!b.images?.length&&!o.has(b));if(i.length>pe.keepInRequest)for(let b of i.slice(0,-1))o.add(b);let c=r(s(e));if(c<=t)return s(e);let u=e.flatMap((b,_)=>b.role==="tool"?[_]:[]),d=u.length>ls?u[u.length-ls]:e.length,p=t*Oi;for(let b=0;b<d&&c>p;b++){let _=e[b];if(o.has(_)||!(_.role==="tool"&&_.content.length>en.length||_.role==="user"&&!!_.images?.length))continue;let W=Gn(_);o.add(_),c-=W-Gn(cs(_))}let g=s(e);n&&(n.overflow=r(g)>t);let k=(b,_)=>_>0&&b.role==="user"&&!Li(b);for(;r(g)>t;){let b=g.findIndex(k),_=g.findIndex((x,W)=>W>b&&k(x,W));if(b<0||_<0)break;g.splice(b,_-b)}return g}function We(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/F.charsPerToken)}import _a from"fs/promises";import{spawn as Fi}from"child_process";import tn from"fs/promises";import{createHash as Di}from"crypto";import gt from"path";var fs=1e4,hs=2e3,nn=["PreToolUse","PostToolUse"],Ui=e=>gt.join(e,w.dirName,"hooks.json"),ws=()=>({PreToolUse:[],PostToolUse:[]});async function _s(e){let t=ws();try{let n=JSON.parse(await tn.readFile(e,"utf8"));for(let o of nn){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 on=e=>_s(Ui(e)),Qe=e=>nn.reduce((t,n)=>t+e[n].length,0),Xn=e=>gt.join(e,w.dirName,"trusted-hooks.json"),ys=e=>Di("sha256").update(JSON.stringify(e)).digest("hex");async function bs(e){try{return JSON.parse(await tn.readFile(Xn(e),"utf8"))}catch{return{}}}async function ks(e,t){let n=await bs(t);n[gt.resolve(e)]=ys(await on(e)),await tn.mkdir(gt.dirname(Xn(t)),{recursive:!0}),await tn.writeFile(Xn(t),JSON.stringify(n,null,2),{mode:384})}async function It(e,t){let n=await _s(gt.join(t,w.dirName,"hooks.json")),o=await on(e),s=Qe(o)===0||(await bs(t))[gt.resolve(e)]===ys(o),r={...ws(),untrusted:s?[]:nn.flatMap(i=>o[i])};for(let i of nn)r[i]=[...n[i],...s?o[i]:[]];return r}function Bi(e,t,n){return new Promise(o=>{let s="",r="",i=!1,c=p=>{i||(i=!0,clearTimeout(d),o(p))},u=Fi("/bin/sh",["-c",e.command],{cwd:n,env:Se(process.env),stdio:["pipe","pipe","pipe"]}),d=setTimeout(()=>{u.kill("SIGKILL"),c({code:null,text:"",error:`timed out after ${fs/1e3}s`})},fs);u.stdout.setEncoding("utf8"),u.stderr.setEncoding("utf8"),u.stdout.on("data",p=>{s=(s+p).slice(0,hs)}),u.stderr.on("data",p=>{r=(r+p).slice(0,hs)}),u.on("error",p=>c({code:null,text:"",error:`cannot start: ${p.message}`})),u.on("close",p=>c({code:p,text:r.trim()||s.trim()})),u.stdin.on("error",()=>{}),u.stdin.end(JSON.stringify(t))})}var Wi=(e,t)=>{if(!e.matcher)return!0;try{return new RegExp(e.matcher).test(t)}catch{return!1}};async function Vn(e,t,n,o){let s={warnings:[]},r=e?.[t]?.filter(c=>Wi(c,o.tool))??[];if(!r.length)return s;let i={event:t,tool:o.tool,args:o.args,...t==="PostToolUse"?{ok:o.ok,output:o.output}:{}};for(let c of r){let u=await Bi(c,i,n);if(u.error)s.warnings.push(`hook "${c.command}" ${u.error}`);else{if(u.code===2&&t==="PreToolUse")return s.blocked=u.text||`hook "${c.command}" blocked this call`,s;u.code!==0&&s.warnings.push(`hook "${c.command}" exited ${u.code}${u.text?`: ${u.text}`:""}`)}}return s}var qi=new Set(["npm","pnpm","yarn","bun","npx","git","pip","pip3","uv","cargo","go","docker","kubectl","composer","php","python","python3","node","make","brew","apt","apt-get","gh","deno"]),Hi=/^(cd|export|set|source|\.|true|:|echo|printf|mkdir|test|\[)$/;function zi(e){let t=[],n="",o=null;for(let s=0;s<e.length;s++){let r=e[s];if(o){n+=r,r===o&&(o=null);continue}if(r==="'"||r==='"'){o=r,n+=r;continue}if(r===`
83
+ `||r===";"||r==="|"||r==="&"&&e[s+1]==="&"){n.trim()&&t.push(n.trim()),n="",(r==="&"||r==="|")&&e[s+1]===r&&s++;continue}n+=r}return n.trim()&&t.push(n.trim()),t}function xs(e,t=!1){let n=e.split(/\s+/).filter(Boolean),o=0;for(;o<n.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(n[o]);)o++;let s=n[o];if(!s)return"";let r=s.replace(/^["']|["']$/g,"").split("/").pop();if(Hi.test(r)&&!t)return"";let i=n[o+1];return qi.has(r)&&i&&!i.startsWith("-")?`${r} ${i}`:r}function $s(e){let t=zi(e),n=[...new Set(t.map(o=>xs(o)).filter(Boolean))];return n.length?n:[...new Set(t.map(o=>xs(o,!0)).filter(Boolean))]}var Ki=[[/\b(pip3?|uv\s+pip|pipx)\s+install\b|\bpython3?\s+-m\s+pip\s+install\b/,"installs Python packages"],[/--break-system-packages/,"changes system Python packages"],[/\b(npm|pnpm|yarn|bun)\s+(i|install|add)\b.*\s-g\b|\b(npm|pnpm)\s+(i|install)\s+(-g|--global)\b/,"installs a global package"],[/\b(apt|apt-get|dnf|yum|pacman|brew|snap|choco|winget)\s+(install|remove|upgrade|-S)\b/,"installs or removes system packages"],[/\b(curl|wget)\b[^|;&]*(\s-o\s|\s-O\b|>\s)/,"downloads a file"],[/\bgit\s+push\b/,"pushes to a remote"],[/\bgit\s+(reset\s+--hard|clean\s+-[a-z]*f|checkout\s+--\s|branch\s+-D)\b/,"discards git work"],[/(^|[\s;&|(])rm\s+(-[a-zA-Z]*[rR]|--recursive)/,"deletes recursively"],[/\bchmod\s+-R\b|\bchown\s+-R\b/,"changes permissions recursively"],[/\b(docker|podman)\s+(rm|rmi|system\s+prune|volume\s+rm)\b/,"deletes containers or images"],[/\b(kubectl|terraform|pulumi)\s+(delete|destroy|apply)\b/,"changes infrastructure"]];function vs(e){for(let[t,n]of Ki)if(t.test(e))return n;return null}var Gi=8,Ss=6e4,Ji=1200,Yi=`[Summary of the earlier conversation, written to save context]
84
+ `,Xi=e=>e.role==="user"&&e.content.startsWith("[view_image]");function Vi(e){let t=Math.max(1,e.length-Gi);for(;t>1&&e[t].role==="tool";)t--;return t}function Zi(e){let n=e.map(o=>{let s=(o.content??"").slice(0,Ji);return o.role==="assistant"?`ASSISTANT: ${s}${o.tool_calls?.length?` [calls: ${o.tool_calls.map(r=>`${r.name} ${r.arguments.slice(0,200)}`).join("; ")}]`:""}`:o.role==="tool"?`TOOL RESULT: ${o.content===en?"(cleared)":s}`:`${o.role.toUpperCase()}: ${s}`}).join(`
85
+ `);return n.length>Ss&&(n=`\u2026
86
+ `+n.slice(-Ss)),n}async function Ts(e,t,n,o){let s=Vi(n);if(s<=2)return null;let r=n.map((g,k)=>g.role==="user"&&!Xi(g)?k:-1).filter(g=>g>=0).pop()??-1,i=r>0&&r<s?n[r]:null,c=n.slice(1,s).filter(g=>g!==i);if(!c.length)return null;let u;try{u=await e.chat({model:t,tools:[],signal:o,messages:[{role:"system",content:"You summarize an AI coding agent's work so it can continue with less context."},{role:"user",content:`Summarize this conversation so far for the agent itself. Keep: the user's goals and constraints, decisions made, files created or changed (paths), commands that worked and their key results/numbers, errors and how they were fixed, and what was in progress. Use short bullet points, at most ~400 words. No preamble.
87
+
88
+ ${Zi(c)}`}]})}catch{return null}let d=(u.content??"").trim();if(!d)return null;let p=[{role:"user",content:Yi+d}];return i&&p.push(i),n.splice(1,s-1,...p),u.usage}import{execFile as Qi}from"child_process";import ea from"fs/promises";import ta from"path";var na=5e3;function sn(e,t){return new Promise(n=>{Qi(e,t,{timeout:na,env:Se(process.env),maxBuffer:2e5},(o,s,r)=>{if(o?.code==="ENOENT")return n(null);n({code:o?typeof o.code=="number"?o.code:1:0,out:`${s}${r}`.trim()})})})}async function Es(e){let t=ta.extname(e).toLowerCase();try{if(t===".json"){let s=await ea.readFile(e,"utf8");if(/(^|\/)(tsconfig|jsconfig)[^/]*\.json$|\.vscode\//.test(e))return null;try{return JSON.parse(s),null}catch(r){return`invalid JSON: ${r.message}`}}let n=null;if(t===".js"||t===".mjs"||t===".cjs"?n=await sn(process.execPath.endsWith("node")?process.execPath:"node",["--check",e]):t===".py"?n=await sn("python3",["-c","import ast,sys; ast.parse(open(sys.argv[1], encoding='utf-8').read(), sys.argv[1])",e]):t===".php"?n=await sn("php",["-l",e]):(t===".sh"||t===".bash")&&(n=await sn("bash",["-n",e])),!n||n.code===0)return null;let o=n.out.split(`
89
+ `).filter(s=>s.trim());return(t===".py"?o.slice(-6):o.slice(0,8)).join(`
90
+ `).slice(0,1200)||"syntax check failed"}catch{return null}}import{execFile as oa}from"child_process";import sa from"crypto";import ra from"fs";import ia from"os";import ke from"path";var aa=9e4,la=15,Zn=e=>/\.(ts|tsx|mts|cts)$/i.test(e)&&!/\.d\.ts$/i.test(e);function Rs(e,t,n){let o=e;for(;;){let s=ke.join(o,n);if(ra.existsSync(s))return s;if(o===t||ke.dirname(o)===o||!o.startsWith(t))return null;o=ke.dirname(o)}}async function Ms(e,t,n){let o=t.filter(Zn);if(!o.length)return null;let s=new Map;for(let i of o){let c=Rs(ke.dirname(i),e,"tsconfig.json");c&&s.set(c,[...s.get(c)??[],i])}if(!s.size)return null;let r=[];for(let[i,c]of s){let u=Rs(ke.dirname(i),e,ke.join("node_modules","typescript","bin","tsc"));if(!u)continue;let d=ke.join(ia.tmpdir(),`scope-tsc-${sa.createHash("sha1").update(i).digest("hex").slice(0,12)}.tsbuildinfo`),p=await new Promise(x=>{let W=oa(process.execPath,[u,"--noEmit","-p",i,"--pretty","false","--incremental","--tsBuildInfoFile",d],{cwd:ke.dirname(i),timeout:aa,env:Se(process.env),maxBuffer:5e6},(ne,j,de)=>x({text:`${j}${de}`,timedOut:!!ne?.killed}));n?.addEventListener("abort",()=>W.kill("SIGKILL"),{once:!0})});if(n?.aborted)return null;let g=p.text.split(`
91
+ `).filter(x=>/\): error TS\d+:/.test(x)),k=new Set(c.map(x=>ke.resolve(x))),b=g.filter(x=>k.has(ke.resolve(ke.dirname(i),x.slice(0,x.indexOf("("))))),_=new Set(g.filter(x=>!b.includes(x)).map(x=>x.slice(0,x.indexOf("("))));r.push({tsconfig:ke.relative(e,i)||"tsconfig.json",errors:b.slice(0,la),otherFiles:_.size,timedOut:p.timedOut})}return r.length?r:null}function As(e){if(!e)return null;let t=e.flatMap(o=>o.errors),n=e.some(o=>o.timedOut);return!t.length&&!n?null:t.length?`
92
+
93
+ \u26A0 TypeScript errors in files you changed \u2014 fix them before moving on:
94
+ ${t.join(`
95
+ `)}`:`
65
96
 
66
- [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 Ir(e,t,n){return e==="run_shell"?`run shell command: ${t.command}${t.cwd?` (in ${t.cwd})`:""}`:(e==="write_file"||e==="edit_file")&&vo(n,t.path)?`${e} OUTSIDE project root: ${t.path}`:null}var Yo=(e,t=D.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,Ho=!!process.env.FORGE_TIMING,zo=new Set(["read_file","list_dir","grep","glob","read_multiple_files"]);function Or(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(!zo.has(o.name)||t.opts.mcp?.has(o.name))return!1;let s=Bt(o.name,o.arguments);return s.ok&&zo.has(s.name)})}async function nt(e){let{client:t,model:n,messages:o,onEvent:s}=e,r={opts:e,specs:e.plan?Cn().filter(h=>Ko.has(h.name)):[...Cn(),...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??D.maxSteps),D.hardMaxSteps),c=e.maxRunTokens??D.maxRunTokens,d="",u=!1;if(e.plan){let h=o[o.length-1];h?.role==="user"&&!h.content.endsWith(qo)&&(h.content+=qo)}let g=(h,y)=>({finalText:d,usage:r.usage,steps:h,hitStepLimit:y==="max_steps",stopReason:y,toolErrors:r.toolErrors,changedFiles:[...r.changed],cachedReads:r.cachedReads});for(let h=1;h<=a;h++){if(e.signal?.aborted)return g(h-1,"interrupted");if(c>0&&r.usage.promptTokens+r.usage.completionTokens>=c)return g(h-1,"token_budget");let y=zt(o),x=et(y);if(!u&&x>=D.warnContextTokens&&(u=!0,s?.({type:"context_warning",tokens:x})),e.signal?.aborted)return g(h-1,"interrupted");let L=!1,W=e.stream?Z=>{L=!0,s?.({type:"token",text:Z})}:void 0,X=e.stream?Z=>s?.({type:"reasoning",text:Z}):void 0,ie=Date.now(),N=await t.chat({model:n,messages:y,tools:r.specs,onToken:W,onReasoning:X});if(Ho&&console.error(`[forge-timing] step ${h}: model ${Date.now()-ie}ms, ~${x} prompt tokens, ${N.toolCalls.length} tool call(s)`),e.signal?.aborted)return g(h,"interrupted");if(Vo(r,N.usage),o.push({role:"assistant",content:N.content,tool_calls:N.toolCalls.length?N.toolCalls:void 0}),N.content&&(d=N.content,s?.({type:"assistant",text:N.content,streamed:L})),!N.toolCalls.length)return g(h,"done");let de=Date.now();if(Or(N.toolCalls,r)){let Z=N.toolCalls.map(()=>[]),ut=await Promise.all(N.toolCalls.map((Rt,ne)=>Jo(Rt,r,oe=>Z[ne].push(oe))));if(e.signal?.aborted)return g(h,"interrupted");N.toolCalls.forEach((Rt,ne)=>{for(let oe of Z[ne])s?.(oe);o.push({role:"tool",tool_call_id:Rt.id,content:Ht(ut[ne])})})}else for(let Z of N.toolCalls){if(e.signal?.aborted)return g(h,"interrupted");let ut=await Jo(Z,r);o.push({role:"tool",tool_call_id:Z.id,content:Ht(ut)})}Ho&&console.error(`[forge-timing] step ${h}: tools ${N.toolCalls.map(Z=>Z.name).join(",")} ${Date.now()-de}ms`)}return g(a,"max_steps")}var Vo=(e,t)=>{e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.cacheReadTokens=(e.usage.cacheReadTokens??0)+(t.cacheReadTokens??0)};async function Lr(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.
97
+ (TypeScript check timed out; run the project's typecheck yourself before finishing.)`}var Qn="explore";var Cs={name:Qn,description:"Hand a research question to a read-only helper agent with its own context (it can read, grep, glob, list and look at images, nothing else). Use it for broad searches across many files ('where is X handled?', 'how does Y work?') so they don't fill your context; only its short report comes back. Give a self-contained task and say what the report must contain. Not for a single known file: read that yourself.",parameters:{type:"object",properties:{task:{type:"string",description:"the question, with any paths or names you already know"}},required:["task"]}},ca=`
98
+
99
+ [You are a read-only research helper for another agent. Search and read only what the task needs, then reply with a concise report (at most ~250 words): the answer, with file paths and line numbers. Do not paste whole files.]`;function Ps(e,t){return[{role:"system",content:e},{role:"user",content:t+ca}]}import Os from"fs/promises";import fa from"path";import{execFile as ua}from"child_process";import rn from"fs/promises";import Is from"os";import Te from"path";var da={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function ma(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 pa(e){if(process.platform!=="darwin")return Promise.resolve(null);let t=Te.join(Is.tmpdir(),`forge-shrink-${process.pid}-${Date.now()}.jpg`);return new Promise(n=>{ua("sips",["-Z","1600","-s","format","jpeg","-s","formatOptions","80",e,"--out",t],async o=>{if(o)return n(null);try{n(await rn.readFile(t))}catch{n(null)}finally{rn.rm(t,{force:!0}).catch(()=>{})}})})}async function to(e,t=pa){let n=Te.extname(e).toLowerCase();if(!(n in da))throw new Error(`${Te.basename(e)}: not a supported image type (png, jpg, gif, webp)`);let o=await rn.readFile(e),s=ma(o);if(!s)throw new Error(`${Te.basename(e)}: file content is not a valid ${n.slice(1)} image`);if(o.length>pe.maxBytes/2&&s!=="image/gif"){let r=await t(e);r&&r.length<o.length&&(o=r,s="image/jpeg")}if(o.length>pe.maxBytes)throw new Error(`${Te.basename(e)}: image is ${(o.length/1048576).toFixed(1)} MB (max ${pe.maxBytes/1048576} MB)`);return{mediaType:s,data:o.toString("base64"),name:Te.basename(e)}}var eo="(?:png|jpe?g|gif|webp)",ga=new RegExp(`(^|\\s)(@?)(?:"([^"\\n]+\\.${eo})"|'([^'\\n]+\\.${eo})'|((?:\\\\ |[^\\s"'])+\\.${eo}))(?=\\s|$|[.,;:!?)]$)`,"gi");async function js(e,t,n=Is.homedir()){let o=[],s=[],r=new Map,i=[...t.matchAll(ga)],c="",u=0;for(let d of i){let p=(d[3]??d[4]??d[5]??"").replace(/\\ /g," "),g=p.startsWith("~/")?Te.join(n,p.slice(2)):Te.resolve(e,p),k=(d.index??0)+d[1].length,b=(d.index??0)+d[0].length,_=r.get(g);if(_===void 0){try{await rn.access(g)}catch{continue}if(o.length>=pe.maxPerMessage){s.push(`only ${pe.maxPerMessage} images per message; skipped ${Te.basename(g)}`);continue}try{o.push(await to(g)),_=o.length,r.set(g,_)}catch(x){s.push(x instanceof Error?x.message:String(x));continue}}c+=t.slice(u,k)+`[Image #${_}: ${Te.basename(g)}]`,u=b}return{text:c+t.slice(u),images:o,errors:s}}var no="view_image",Ns={name:no,description:"Look at an image file in the project (png, jpg, gif, webp): it is shown to you right after this call. Use it to check what you rendered (a video frame, a screenshot, a chart) instead of measuring pixels in scripts. Keep images small (scale video frames to at most ~720px on the long side) and view one contact sheet instead of many frames.",parameters:{type:"object",properties:{path:{type:"string",description:"image path, relative to the project root"}},required:["path"]}};async function Ls(e,t){if(e.remote)throw new Error("view_image is not available in SSH workspaces");let n;try{n=JSON.parse(t||"{}").path}catch{throw new Error('arguments must be JSON like {"path": "frame.png"}')}if(typeof n!="string"||!n.trim())throw new Error("path is required");let{abs:o,inside:s}=ce(e.root,n);if(!s&&!e.allowAll)throw new Error(`path "${n}" is outside the project root`);if(!e.allowAll){let r=await Os.realpath(o).catch(()=>{throw new Error(`${n}: file not found`)});if(!ce(await Os.realpath(e.root),r).inside)throw new Error(`path "${n}" resolves outside the project root (symlink)`)}return to(o)}var Fs=e=>`Showing ${e.name??"image"} (${Math.round(e.data.length*3/4/1024)} KB) in the next message.`;function Ds(e){let t=e.slice(-pe.maxPerMessage);return{role:"user",content:`[view_image] ${t.map(n=>fa.basename(n.name??"image")).join(", ")}`,images:t}}var zs=new Set(["read_file","list_dir","grep","glob","read_multiple_files","think","todo_write","explore"]),Us=`
100
+
101
+ [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 ya(e,t,n){return e==="run_shell"?`run shell command: ${t.command}${t.background?" (in the background)":""}${t.cwd?` (in ${t.cwd})`:""}`:e==="web_fetch"?`fetch ${t.url}`:(e==="write_file"||e==="edit_file")&&Vo(n,t.path)?`${e} OUTSIDE project root: ${t.path}`:null}var Ks=(e,t=F.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,Bs=!!process.env.FORGE_TIMING,Ws=new Set(["read_file","list_dir","grep","glob","read_multiple_files"]);function ba(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(!Ws.has(o.name)||t.opts.mcp?.has(o.name))return!1;let s=Vt(o.name,o.arguments);return s.ok&&Ws.has(s.name)})}async function et(e){let{client:t,model:n,messages:o,onEvent:s}=e,r={opts:e,specs:[...e.plan||e.readOnly?zn().filter(g=>zs.has(g.name)&&!(e.readOnly&&g.name==="todo_write")):[...zn(),...e.mcp?.specs()??[]],...e.vision?[Ns]:[],...e.isHelper?[]:[Cs]],usage:{promptTokens:0,completionTokens:0,cacheReadTokens:0},alwaysAllow:new Set,toolErrors:0,changed:new Set,reads:new Map,cachedReads:0,trim:Yn(),lastCompactStep:-10};!e.ctx.remote&&!r.specs.some(g=>g.name===Mt)&&(await At(e.ctx.root).catch(()=>[])).length&&r.specs.push(rs);let i=e.maxSteps===0?1/0:Math.min(Math.max(1,e.maxSteps??F.maxSteps),F.hardMaxSteps),c=e.maxRunTokens??F.maxRunTokens,u="",d=!1;if(e.plan){let g=o[o.length-1];g?.role==="user"&&!g.content.endsWith(Us)&&(g.content+=Us)}let p=(g,k)=>({finalText:u,usage:r.usage,steps:g,hitStepLimit:k==="max_steps",stopReason:k,toolErrors:r.toolErrors,changedFiles:[...r.changed],cachedReads:r.cachedReads});for(let g=1;g<=i;g++){if(e.signal?.aborted)return p(g-1,"interrupted");if(c>0&&r.usage.promptTokens+r.usage.completionTokens>=c)return p(g-1,"token_budget");let k=Pt(o,void 0,r.trim);if(r.trim.overflow&&g-r.lastCompactStep>3){r.lastCompactStep=g;let G=We(k),fe=await Ts(t,n,o,e.signal);if(e.signal?.aborted)return p(g-1,"interrupted");fe&&(ln(r,fe),r.trim=Yn(),k=Pt(o,void 0,r.trim),s?.({type:"compacted",tokensBefore:G,tokensAfter:We(k)}))}let b=We(k);if(!d&&b>=F.warnContextTokens&&(d=!0,s?.({type:"context_warning",tokens:b})),e.signal?.aborted)return p(g-1,"interrupted");let _=!1,x=e.stream?G=>{_=!0,s?.({type:"token",text:G})}:void 0,W=e.stream?G=>s?.({type:"reasoning",text:G}):void 0,ne=Date.now(),j;try{j=await t.chat({model:n,messages:k,tools:r.specs,onToken:x,onReasoning:W,signal:e.signal})}catch(G){if(e.signal?.aborted)return p(g-1,"interrupted");throw G}if(Bs&&console.error(`[forge-timing] step ${g}: model ${Date.now()-ne}ms, ~${b} prompt tokens, ${j.toolCalls.length} tool call(s)`),e.signal?.aborted)return p(g,"interrupted");if(ln(r,j.usage),s?.({type:"usage",promptTokens:r.usage.promptTokens,completionTokens:r.usage.completionTokens,cacheReadTokens:r.usage.cacheReadTokens??0}),o.push({role:"assistant",content:j.content,tool_calls:j.toolCalls.length?j.toolCalls:void 0}),j.content&&(u=j.content,s?.({type:"assistant",text:j.content,streamed:_})),!j.toolCalls.length)return p(g,"done");let de=Date.now();if(ba(j.toolCalls,r)){let G=j.toolCalls.map(()=>[]),fe=await Promise.all(j.toolCalls.map((N,Y)=>Hs(N,r,q=>G[Y].push(q))));if(e.signal?.aborted)return p(g,"interrupted");j.toolCalls.forEach((N,Y)=>{for(let q of G[Y])s?.(q);o.push({role:"tool",tool_call_id:N.id,content:Ct(fe[Y])})})}else{let G=[],fe=[];for(let N of j.toolCalls){if(e.signal?.aborted)return p(g,"interrupted");if(N.name===Qn&&!e.isHelper){let L=an(N.arguments);s?.({type:"tool_start",name:N.name,args:L});let se,re=!0,Ie=typeof L?.task=="string"?L.task.trim():"";if(!Ie)re=!1,r.toolErrors++,se="ERROR: task is required";else{let je=await et({client:e.client,model:e.model,ctx:e.ctx,signal:e.signal,vision:e.vision,stream:!1,messages:Ps(String(o[0]?.content??""),Ie),readOnly:!0,isHelper:!0,maxSteps:25,maxRunTokens:4e5,onEvent:Oe=>{Oe.type!=="usage"&&(Oe.type==="tool_start"||Oe.type==="tool_result")&&s?.({...Oe,name:`explore:${Oe.name}`})}});if(ln(r,je.usage),s?.({type:"usage",promptTokens:r.usage.promptTokens,completionTokens:r.usage.completionTokens,cacheReadTokens:r.usage.cacheReadTokens??0}),je.stopReason==="interrupted")return p(g,"interrupted");se=(je.finalText||"(the helper found nothing to report)").trim()+(je.stopReason==="done"?"":`
102
+ [helper stopped early: ${je.stopReason}]`)}s?.({type:"tool_result",name:N.name,ok:re,output:se.slice(0,400)}),o.push({role:"tool",tool_call_id:N.id,content:Ct(se)});continue}if(N.name===Mt&&r.specs.some(L=>L.name===Mt)){s?.({type:"tool_start",name:N.name,args:an(N.arguments)});let L,se=!0;try{L=await is(e.ctx.root,N.arguments)}catch(re){se=!1,r.toolErrors++,L=`ERROR: ${re?.message??re}`}s?.({type:"tool_result",name:N.name,ok:se,output:se?L.split(`
103
+ `)[0]:L}),o.push({role:"tool",tool_call_id:N.id,content:L});continue}if(e.vision&&N.name===no){s?.({type:"tool_start",name:N.name,args:an(N.arguments)});let L,se=!0;try{let re=await Ls(e.ctx,N.arguments);G.push(re),L=Fs(re)}catch(re){se=!1,r.toolErrors++,L=`ERROR: ${re?.message??re}`}s?.({type:"tool_result",name:N.name,ok:se,output:L}),o.push({role:"tool",tool_call_id:N.id,content:L});continue}let Y=await Hs(N,r),q={role:"tool",tool_call_id:N.id,content:Ct(Y)};if(o.push(q),(N.name==="write_file"||N.name==="edit_file")&&!/^(ERROR|DENIED|BLOCKED)/.test(Y)){let L=an(N.arguments)?.path;typeof L=="string"&&Zn(L)&&fe.push({path:L,msg:q})}}if(fe.length&&!e.ctx.remote){let N=await Ms(e.ctx.root,[...new Set(fe.map(q=>ce(e.ctx.root,q.path).abs))],e.signal);if(e.signal?.aborted)return p(g,"interrupted");let Y=As(N);if(N&&s?.({type:"diagnostics",errors:N.reduce((q,L)=>q+L.errors.length,0),files:new Set(fe.map(q=>q.path)).size}),Y){let q=fe[fe.length-1].msg;q.content+=Y}}G.length&&o.push(Ds(G))}Bs&&console.error(`[forge-timing] step ${g}: tools ${j.toolCalls.map(G=>G.name).join(",")} ${Date.now()-de}ms`)}return p(i,"max_steps")}var an=e=>{try{return JSON.parse(e||"{}")}catch{return e}},ln=(e,t)=>{e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.cacheReadTokens=(e.usage.cacheReadTokens??0)+(t.cacheReadTokens??0)};async function ka(e,t,n){let{client:o,model:s,messages:r}=n.opts,i=r.map(d=>d.role).lastIndexOf("assistant"),c=r.slice(0,i),u=`Your previous tool call was invalid and was not executed.
67
104
  Tool: ${e.name}
68
105
  Arguments: ${e.arguments.slice(0,2e3)}
69
106
  Problem: ${t}
70
- Re-issue exactly that action as ONE corrected tool call with valid JSON arguments.`;try{let u=await o.chat({model:s,messages:zt([...c,{role:"user",content:d}]),tools:n.specs});Vo(n,u.usage);let g=u.toolCalls[0];return g?Bt(g.name,g.arguments):{ok:!1,error:t}}catch{return{ok:!1,error:t}}}async function Fr(e,t){let{abs:n,inside:o}=(e.remote?Ue:_e)(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 jr.stat(n);return s.isFile()?{abs:n,sig:`${s.mtimeMs}:${s.size}`}:null}catch{return null}}function Dr(e,t){return zt(e.opts.messages).some(n=>n.role==="tool"&&n.tool_call_id===t.callId&&n.content===t.content)}var Go=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 Xo(e,t,n,o=s=>n.opts.onEvent?.(s)){let s=await Nn(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 Yt(e,t,n,o,s,r=a=>s.opts.onEvent?.(a)){let a=await Nn(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 Ur(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 Xo(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 Yt(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 Yt(e.name,s,!1,c,t),`ERROR: ${c}`}}async function Jo(e,t,n=o=>t.opts.onEvent?.(o)){if(t.opts.plan&&!Ko.has(e.name))return n({type:"tool_result",name:e.name,ok:!1,output:Go(e.name)}),Go(e.name);if(t.opts.mcp?.has(e.name))return Ur(e,t);let o=Bt(e.name,e.arguments);if(o.ok&&o.repaired&&n({type:"repair",name:o.name,via:"normalize"}),!o.ok){let g=await Lr(e,o.error,t);g.ok&&n({type:"repair",name:g.name,via:"model"}),o=g.ok?g:o}if(!o.ok)return t.toolErrors++,n({type:"tool_result",name:e.name,ok:!1,output:o.error}),`ERROR: ${o.error}`;let{name:s,args:r}=o;n({type:"tool_start",name:s,args:r});let a=await Xo(s,r,t,n);if(a)return a;let c={...t.opts.ctx},d=null;if(s==="read_file"){d=await Fr(c,r.path);let g=d&&t.reads.get(d.abs);if(g&&d&&g.sig===d.sig&&Dr(t,g)){t.cachedReads++;let h=`(unchanged: "${r.path}" has not changed since you read it earlier in this conversation; use that earlier result.)`;return n({type:"tool_result",name:s,ok:!0,output:h}),h}}let u=Ir(s,r,c);if(u&&!t.opts.yolo&&!t.alwaysAllow.has(s)){let g=t.opts.approve?await t.opts.approve({name:s,args:r,reason:u}):!1;if(!g)return n({type:"denied",name:s}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";g==="always"&&t.alwaysAllow.add(s)}u&&(s==="write_file"||s==="edit_file")&&(c.allowOutside=!0);try{let g=await Ze(s,r,c);return s==="write_file"||s==="edit_file"?(t.changed.add(r.path),t.reads.delete((c.remote?Ue:_e)(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:Ht(g)}),n({type:"tool_result",name:s,ok:!0,output:g}),await Yt(s,r,!0,g,t,n),g}catch(g){let h=g instanceof Error?g.message:String(g);return t.toolErrors++,n({type:"tool_result",name:s,ok:!1,output:h}),await Yt(s,r,!1,h,t,n),`ERROR: ${h}`}}var le=class extends Error{constructor(n,o,s){super(o);this.status=n;this.body=s}status;body;get code(){return this.body?.error?.code}},Br="The selected model is temporarily unavailable. Please try again shortly, or switch models with /model.";function Zo(e,t){return[401,402,403,429].includes(e)?t:e>=500?Br:t}var Pe=class extends Error{constructor(n,o){super(`cannot reach server (${o})`);this.url=n;this.reason=o}url;reason},Wr=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","ETIMEDOUT","EAI_AGAIN","ECONNRESET","ENETUNREACH"]),qr=3,Hr=new Set([429,500,502,503,504]),zr=1e4;function Gr(e,t=1e3){let n=e?Number(e):NaN;return Math.min(zr,Number.isFinite(n)&&n>=0?n*1e3:t)}var Vt=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:Yr(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 y=h?.cause?.code;if(Wr.has(y)&&a<=qr){let x=1e3*2**(a-1);this.cfg.onRetry?.({status:0,attempt:a,delayMs:x}),await r(x);continue}throw new Pe(n,y??h?.name??h?.message??"network error")}if(c.ok)return t.onToken&&c.body?await Kr(c.body,t.onToken,n,t.onReasoning):Jr(await c.json());let d=await c.text();if(Hr.has(c.status)&&a===1){let h=Gr(c.headers.get("retry-after"));this.cfg.onRetry?.({status:c.status,attempt:a,delayMs:h}),await r(h);continue}let u,g=d;try{u=JSON.parse(d),g=u.error?.message??u.error??d}catch{}throw new le(c.status,Zo(c.status,typeof g=="string"?g:JSON.stringify(g)),u)}}};function Jr(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:Qo(e.usage)}}}function Qo(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 Kr(e,t,n="stream",o){let s=e.getReader(),r=new TextDecoder,a="",c="",d,u=new Map,g=!1,h=y=>{if(!y.startsWith("data:"))return;let x=y.slice(5).trim();if(x==="[DONE]"){g=!0;return}if(!x)return;let L;try{L=JSON.parse(x)}catch{return}if(L.error)throw new le(502,Zo(502,L.error.message??"stream error"),L);L.usage&&(d=L.usage);let W=L.choices?.[0]?.delta;if(!W)return;let X=W.reasoning_content??W.reasoning;typeof X=="string"&&X&&o?.(X),typeof W.content=="string"&&W.content&&(c+=W.content,t(W.content));for(let ie of W.tool_calls??[]){let N=ie.index??0,de=u.get(N)??{id:"",name:"",arguments:""};ie.id&&(de.id=ie.id),ie.function?.name&&(de.name+=ie.function.name),typeof ie.function?.arguments=="string"&&(de.arguments+=ie.function.arguments),u.set(N,de)}};try{for(;;){let{done:y,value:x}=await s.read();if(y)break;a+=r.decode(x,{stream:!0});let L;for(;(L=a.indexOf(`
71
- `))>=0;)h(a.slice(0,L).replace(/\r$/,"")),a=a.slice(L+1);if(g){(async()=>{try{for(;!(await s.read()).done;);}catch{}})();break}}a.trim()&&h(a.trim())}catch(y){throw y instanceof le?y:new Pe(n,y?.cause?.code??y?.name??y?.message??"stream interrupted")}return{content:c||null,toolCalls:[...u.entries()].sort((y,x)=>y[0]-x[0]).map(([y,x])=>({id:x.id||`call_${y}`,name:x.name,arguments:x.arguments||"{}"})),usage:{promptTokens:d?.prompt_tokens??0,completionTokens:d?.completion_tokens??0,cacheReadTokens:Qo(d)}}}function Yr(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(-he.keepInRequest).reverse()){let r=e[s].images.reduce((a,c)=>a+c.data.length,0);if(n.size>0&&o+r>he.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}
72
- [${s.images.length} earlier image(s) omitted]`}:s)}function Vr(e){let t=e[e.length-1],n={id:"mock-1",object:"chat.completion",model:"mock-model"},o={prompt_tokens:50,completion_tokens:20,total_tokens:70,prompt_tokens_details:{cached_tokens:e.length>2?40:0}},s=h=>({...n,usage:o,choices:[{index:0,finish_reason:"stop",message:{role:"assistant",content:h}}]});if(t?.role==="tool")return s(String(t.content).startsWith("ERROR")?`That failed: ${t.content}`:"Done.");let r=String([...e].reverse().find(h=>h.role==="user")?.content??""),a=r.match(/create (?:a |an )?([\w./-]+\.\w+)/i)?.[1];if(!a)return s("Mock model: try `create hello.ts that logs hi`.");let c=String(e.find(h=>h.role==="system")?.content??""),d=/single quotes?/i.test(c)?"'":'"',u=/no semicolons|semicolon-free|without semicolons/i.test(c)?"":";",g=r.match(/logs?\s+["']?([^"'\n]+?)["']?\s*(?:\n|$)/i)?.[1]??"hi";return{...n,usage:o,choices:[{index:0,finish_reason:"tool_calls",message:{role:"assistant",content:null,tool_calls:[{id:"call_mock",type:"function",function:{name:"write_file",arguments:JSON.stringify({path:a,content:`console.log(${g.includes(d)?JSON.stringify(g):d+g+d})${u}
73
- `})}}]}}]}}var qe=class{async chat(t){let n=Vr(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 jn from"fs/promises";import es from"path";async function bt(e,t){let n=t.replace(/\s+/g," ").trim().replace(/^[-*]\s*/,"").slice(0,300);if(!n)throw new Error("empty learning");let o=es.join(e,_.dirName,"memory.md");await jn.mkdir(es.dirname(o),{recursive:!0});let s="";try{s=await jn.readFile(o,"utf8")}catch{}let r=s===""?`# Project memory
107
+ Re-issue exactly that action as ONE corrected tool call with valid JSON arguments.`;try{let d=await o.chat({model:s,messages:Pt([...c,{role:"user",content:u}]),tools:n.specs});ln(n,d.usage);let p=d.toolCalls[0];return p?Vt(p.name,p.arguments):{ok:!1,error:t}}catch{return{ok:!1,error:t}}}async function xa(e,t){let{abs:n,inside:o}=(e.remote?Fe:ce)(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 _a.stat(n);return s.isFile()?{abs:n,sig:`${s.mtimeMs}:${s.size}`}:null}catch{return null}}function $a(e,t){return Pt(e.opts.messages,void 0,e.trim).some(n=>n.role==="tool"&&n.tool_call_id===t.callId&&n.content===t.content)}var qs=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 Gs(e,t,n,o=s=>n.opts.onEvent?.(s)){let s=await Vn(n.opts.hooks,"PreToolUse",n.opts.ctx.root,{tool:e,args:t});for(let i of s.warnings)o({type:"hook_warning",name:e,message:i});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 cn(e,t,n,o,s,r=i=>s.opts.onEvent?.(i)){let i=await Vn(s.opts.hooks,"PostToolUse",s.opts.ctx.root,{tool:e,args:t,ok:n,output:o});for(let c of i.warnings)r({type:"hook_warning",name:e,message:c})}async function va(e,t){let{onEvent:n,mcp:o}=t.opts,s={};try{s=e.arguments.trim()?JSON.parse(e.arguments):{}}catch{t.toolErrors++;let i="arguments are not valid JSON";return n?.({type:"tool_result",name:e.name,ok:!1,output:i}),`ERROR: ${i}`}n?.({type:"tool_start",name:e.name,args:s});let r=await Gs(e.name,s,t);if(r)return r;if(!t.opts.yolo&&!t.alwaysAllow.has(e.name)){let i=t.opts.approve?await t.opts.approve({name:e.name,args:s,reason:`call MCP tool ${e.name}`}):!1;if(!i)return n?.({type:"denied",name:e.name}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";i==="always"&&t.alwaysAllow.add(e.name)}try{let i=await o.call(e.name,s);return n?.({type:"tool_result",name:e.name,ok:!0,output:i}),await cn(e.name,s,!0,i,t),i}catch(i){let c=i instanceof Error?i.message:String(i);return t.toolErrors++,n?.({type:"tool_result",name:e.name,ok:!1,output:c}),await cn(e.name,s,!1,c,t),`ERROR: ${c}`}}async function Hs(e,t,n=o=>t.opts.onEvent?.(o)){if((t.opts.plan||t.opts.readOnly)&&!zs.has(e.name))return n({type:"tool_result",name:e.name,ok:!1,output:qs(e.name)}),qs(e.name);if(t.opts.mcp?.has(e.name))return va(e,t);let o=Vt(e.name,e.arguments);if(o.ok&&o.repaired&&n({type:"repair",name:o.name,via:"normalize"}),!o.ok){let _=await ka(e,o.error,t);_.ok&&n({type:"repair",name:_.name,via:"model"}),o=_.ok?_: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 i=await Gs(s,r,t,n);if(i)return i;let c={...t.opts.ctx,signal:t.opts.signal},u=null;if(s==="read_file"){u=await xa(c,r.path);let _=u&&t.reads.get(u.abs);if(_&&u&&_.sig===u.sig&&$a(t,_)){t.cachedReads++;let x=`(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:x}),x}}let d=ya(s,r,c),p=s==="run_shell"?{keys:$s(String(r.command??"")),risky:vs(String(r.command??""))}:null,g=s==="web_fetch"?(()=>{try{return new URL(String(r.url)).host}catch{return""}})():"",k=p?p.keys.length>0&&p.keys.every(_=>t.alwaysAllow.has(`run_shell:${_}`)):g?t.alwaysAllow.has(`web_fetch:${g}`):t.alwaysAllow.has(s);if(!!d&&(p?.risky?!!t.opts.approve||!t.opts.yolo:!t.opts.yolo&&!k)){let _=p?p.risky||!p.keys.length?null:p.keys.join(", "):g||s,x=p?.risky?`${d} \u26A0 ${p.risky}`:d,W=t.opts.approve?await t.opts.approve({name:s,args:r,reason:x,always:_}):!1;if(!W)return n({type:"denied",name:s}),"DENIED: the user declined this action. Do not retry it; ask the user how to proceed.";if(W==="always"&&_)if(p)for(let ne of p.keys)t.alwaysAllow.add(`run_shell:${ne}`);else g?t.alwaysAllow.add(`web_fetch:${g}`):t.alwaysAllow.add(s)}d&&(s==="write_file"||s==="edit_file")&&(c.allowOutside=!0);try{let _=await dt(s,r,c);if(s==="write_file"||s==="edit_file"){if(!c.remote){let x=await Es((c.remote?Fe:ce)(c.root,r.path).abs);x&&(_+=`
108
+
109
+ \u26A0 Syntax check failed for ${r.path} \u2014 fix it:
110
+ ${x}`)}t.changed.add(r.path),t.reads.delete((c.remote?Fe:ce)(c.root,r.path).abs)}else s==="read_file"&&u&&t.reads.set(u.abs,{sig:u.sig,callId:e.id,content:Ct(_)});return n({type:"tool_result",name:s,ok:!0,output:_}),await cn(s,r,!0,_,t,n),_}catch(_){let x=_ instanceof Error?_.message:String(_);return t.toolErrors++,n({type:"tool_result",name:s,ok:!1,output:x}),await cn(s,r,!1,x,t,n),`ERROR: ${x}`}}var we=class extends Error{constructor(n,o,s){super(o);this.status=n;this.body=s}status;body;get code(){return this.body?.error?.code}},Sa="The selected model is temporarily unavailable. Please try again shortly, or switch models with /model.";function Js(e,t){return[401,402,403,429].includes(e)?t:e>=500?Sa:t}var qe=class extends Error{constructor(n,o){super(`cannot reach server (${o})`);this.url=n;this.reason=o}url;reason},Ta=new Set(["UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET","ETIMEDOUT","EAI_AGAIN","ECONNRESET","ENETUNREACH"]),Ea=3,Ra=new Set([429,500,502,503,504]),Ma=1e4;function Aa(e,t=1e3){let n=e?Number(e):NaN;return Math.min(Ma,Number.isFinite(n)&&n>=0?n*1e3:t)}var un=class extends Error{constructor(){super("stopped"),this.name="AbortedError"}},dn=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:Ia(t.messages),tools:t.tools.map(i=>({type:"function",function:i})),...t.onToken?{stream:!0,stream_options:{include_usage:!0}}:{}}),s=this.cfg.fetch??fetch,r=this.cfg.sleep??(i=>new Promise(c=>setTimeout(c,i)));for(let i=1;;i++){let c;try{c=await s(n,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.cfg.apiKey}`},body:o,signal:t.signal?AbortSignal.any([t.signal,AbortSignal.timeout(this.cfg.timeoutMs??18e4)]):AbortSignal.timeout(this.cfg.timeoutMs??18e4)})}catch(g){if(t.signal?.aborted)throw new un;let k=g?.cause?.code;if(Ta.has(k)&&i<=Ea){let b=1e3*2**(i-1);this.cfg.onRetry?.({status:0,attempt:i,delayMs:b}),await r(b);continue}throw new qe(n,k??g?.name??g?.message??"network error")}if(c.ok)try{return t.onToken&&c.body?await Pa(c.body,t.onToken,n,t.onReasoning):Ca(await c.json())}catch(g){throw t.signal?.aborted?new un:g}let u=await c.text();if(Ra.has(c.status)&&i===1){let g=Aa(c.headers.get("retry-after"));this.cfg.onRetry?.({status:c.status,attempt:i,delayMs:g}),await r(g);continue}let d,p=u;try{d=JSON.parse(u),p=d.error?.message??d.error??u}catch{}throw new we(c.status,Js(c.status,typeof p=="string"?p:JSON.stringify(p)),d)}}};function Ca(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:Ys(e.usage)}}}function Ys(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 Pa(e,t,n="stream",o){let s=e.getReader(),r=new TextDecoder,i="",c="",u,d=new Map,p=!1,g=k=>{if(!k.startsWith("data:"))return;let b=k.slice(5).trim();if(b==="[DONE]"){p=!0;return}if(!b)return;let _;try{_=JSON.parse(b)}catch{return}if(_.error)throw new we(502,Js(502,_.error.message??"stream error"),_);_.usage&&(u=_.usage);let x=_.choices?.[0]?.delta;if(!x)return;let W=x.reasoning_content??x.reasoning;typeof W=="string"&&W&&o?.(W),typeof x.content=="string"&&x.content&&(c+=x.content,t(x.content));for(let ne of x.tool_calls??[]){let j=ne.index??0,de=d.get(j)??{id:"",name:"",arguments:""};ne.id&&(de.id=ne.id),ne.function?.name&&(de.name+=ne.function.name),typeof ne.function?.arguments=="string"&&(de.arguments+=ne.function.arguments),d.set(j,de)}};try{for(;;){let{done:k,value:b}=await s.read();if(k)break;i+=r.decode(b,{stream:!0});let _;for(;(_=i.indexOf(`
111
+ `))>=0;)g(i.slice(0,_).replace(/\r$/,"")),i=i.slice(_+1);if(p){(async()=>{try{for(;!(await s.read()).done;);}catch{}})();break}}i.trim()&&g(i.trim())}catch(k){throw k instanceof we?k:new qe(n,k?.cause?.code??k?.name??k?.message??"stream interrupted")}return{content:c||null,toolCalls:[...d.entries()].sort((k,b)=>k[0]-b[0]).map(([k,b])=>({id:b.id||`call_${k}`,name:b.name,arguments:b.arguments||"{}"})),usage:{promptTokens:u?.prompt_tokens??0,completionTokens:u?.completion_tokens??0,cacheReadTokens:Ys(u)}}}function Ia(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(-pe.keepInRequest).reverse()){let r=e[s].images.reduce((i,c)=>i+c.data.length,0);if(n.size>0&&o+r>pe.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(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.arguments}}))}:s.role==="user"&&s.images?.length?n.has(r)?{role:"user",content:[{type:"text",text:s.content},...s.images.map(i=>({type:"image_url",image_url:{url:`data:${i.mediaType};base64,${i.data}`}}))]}:{role:"user",content:`${s.content}
112
+ [${s.images.length} earlier image(s) omitted]`}:s)}function ja(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=g=>({...n,usage:o,choices:[{index:0,finish_reason:"stop",message:{role:"assistant",content:g}}]});if(t?.role==="tool")return s(String(t.content).startsWith("ERROR")?`That failed: ${t.content}`:"Done.");let r=String([...e].reverse().find(g=>g.role==="user")?.content??""),i=r.match(/create (?:a |an )?([\w./-]+\.\w+)/i)?.[1];if(!i)return s("Mock model: try `create hello.ts that logs hi`.");let c=String(e.find(g=>g.role==="system")?.content??""),u=/single quotes?/i.test(c)?"'":'"',d=/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:i,content:`console.log(${p.includes(u)?JSON.stringify(p):u+p+u})${d}
113
+ `})}}]}}]}}var tt=class{async chat(t){let n=ja(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 oo from"fs/promises";import Xs from"path";async function jt(e,t){let n=t.replace(/\s+/g," ").trim().replace(/^[-*]\s*/,"").slice(0,300);if(!n)throw new Error("empty learning");let o=Xs.join(e,w.dirName,"memory.md");await oo.mkdir(Xs.dirname(o),{recursive:!0});let s="";try{s=await oo.readFile(o,"utf8")}catch{}let r=s===""?`# Project memory
74
114
 
75
115
  `:s.endsWith(`
76
116
  `)?"":`
77
- `;return await jn.appendFile(o,`${r}- ${n}
78
- `),o}import ot from"fs/promises";import Xt from"path";var ts=300,st=e=>Xt.join(e,_.dirName,"skills.md"),xt=e=>Xt.join(e,_.dirName,"memory.md");function In(e){return e.replace(/<!--[\s\S]*?-->/g,"").split(/\r?\n/).map(t=>t.match(/^\s*[-*]\s+(.+?)\s*$/)?.[1]).filter(t=>!!t)}function Xr(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>ts)throw new Error(`skill is too long (${t.length} > ${ts} chars); keep it to one short rule`);return t}var Ae=e=>e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();async function On(e){try{return await ot.readFile(e,"utf8")}catch{return""}}async function He(e){return In(await On(st(e)))}async function Ne(e){return In(await On(xt(e)))}var ns=`# Project skills
117
+ `;return await oo.appendFile(o,`${r}- ${n}
118
+ `),o}import ft from"fs/promises";import mn from"path";var Vs=300,ht=e=>mn.join(e,w.dirName,"skills.md"),Ot=e=>mn.join(e,w.dirName,"memory.md");function so(e){return e.replace(/<!--[\s\S]*?-->/g,"").split(/\r?\n/).map(t=>t.match(/^\s*[-*]\s+(.+?)\s*$/)?.[1]).filter(t=>!!t)}function Oa(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>Vs)throw new Error(`skill is too long (${t.length} > ${Vs} chars); keep it to one short rule`);return t}var He=e=>e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim();async function ro(e){try{return await ft.readFile(e,"utf8")}catch{return""}}async function nt(e){return so(await ro(ht(e)))}async function ze(e){return so(await ro(Ot(e)))}var Zs=`# Project skills
79
119
 
80
- `;async function rt(e,t){let n=Xr(t),o=st(e),s=await On(o);if(In(s).some(a=>Ae(a)===Ae(n)))return{added:!1,skill:n,file:o};await ot.mkdir(Xt.dirname(o),{recursive:!0});let r=s===""?ns:s.endsWith(`
120
+ `;async function wt(e,t){let n=Oa(t),o=ht(e),s=await ro(o);if(so(s).some(i=>He(i)===He(n)))return{added:!1,skill:n,file:o};await ft.mkdir(mn.dirname(o),{recursive:!0});let r=s===""?Zs:s.endsWith(`
81
121
  `)?"":`
82
- `;return await ot.appendFile(o,`${r}- ${n}
83
- `),{added:!0,skill:n,file:o}}async function Ln(e){let t=[],n=[[st(e),`${ns}<!-- One rule per bullet, e.g.
122
+ `;return await ft.appendFile(o,`${r}- ${n}
123
+ `),{added:!0,skill:n,file:o}}async function io(e){let t=[],n=[[ht(e),`${Zs}<!-- One rule per bullet, e.g.
84
124
  - Use pnpm, not npm
85
125
  -->
86
- `],[xt(e),`# Project memory
126
+ `],[Ot(e),`# Project memory
87
127
 
88
128
  <!-- Facts worth remembering, one per bullet. -->
89
- `]];for(let[o,s]of n)try{await ot.access(o)}catch{await ot.mkdir(Xt.dirname(o),{recursive:!0}),await ot.writeFile(o,s),t.push(o)}return t}var Zr=[/^\s*(no|nope|wrong|stop|wait|actually)\b[\s,.!:-]/i,/\b(don'?t|do not|never|stop (using|adding|doing|writing))\b/i,/\binstead\b/i,/\b(use|using|prefer)\b[^.!]*\b(not|over)\b/i,/\b(should|must|need to) (use|be|not|have)\b/i,/\bprefer\b/i,/\brather than\b/i,/\bthat'?s (wrong|not (what|right|how))\b/i,/\bplease (use|don'?t|do not|always|never|keep|avoid)\b/i,/\b(always|avoid)\b/i],Qr=/\b(again|i (told|said|already)|as i (said|mentioned)|every time|always|never|from now on|once more)\b/i,ei=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 os(e){return new Set(e.toLowerCase().replace(/[^a-z0-9+#.\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!ei.has(t)))}function ss(e,t){let n=os(e),o=os(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 ti(e){let t=e.trim();return!t||t.length>400||t.startsWith("/")||t.endsWith("?")?!1:Zr.some(n=>n.test(t))}function ni(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 oi=.4,Zt=class{seen=[];known;constructor(t=[]){this.known=[...t]}observe(t){if(!ti(t))return null;let n=ni(t);if(!n)return null;let o=this.seen.some(r=>ss(r,t)>=oi);this.seen.push(t);let s=Qr.test(t);return!o&&!s||this.known.some(r=>Ae(r)===Ae(n)||ss(r,n)>=.6)?null:(this.known.push(n),{rule:n,reason:o?"repeated":"explicit"})}};async function rs(e){let{cheap:t,strong:n,verify:o,maxToolErrors:s=3,...r}=e,a=await nt({...r,client:t.client,model:t.model}),c;if(a.stopReason!=="done")c=a.stopReason==="max_steps"?"the cheap model hit the step limit":"the cheap model used the run's token budget";else if(a.toolErrors>=s)c=`${a.toolErrors} tool calls failed`;else if(o){let h=await o();h.ok||(c=`verification failed${h.detail?`: ${h.detail.slice(0,200)}`:""}`)}if(!c)return{...a,escalated:!1,finalModel:t.model,cheapUsage:a.usage};r.onEvent?.({type:"escalate",from:t.model,to:n.model,reason:c}),r.messages.push({role:"user",content:`The previous attempt did not succeed (${c}). Review what was done, fix any problems, and finish the task.`});let d=a.usage.promptTokens+a.usage.completionTokens,u=await nt({...r,client:n.client,model:n.model,maxRunTokens:(r.maxRunTokens??D.maxRunTokens)<=0?0:Math.max(5e4,(r.maxRunTokens??D.maxRunTokens)-d)}),g={promptTokens:a.usage.promptTokens+u.usage.promptTokens,completionTokens:a.usage.completionTokens+u.usage.completionTokens,cacheReadTokens:(a.usage.cacheReadTokens??0)+(u.usage.cacheReadTokens??0)};return{...u,usage:g,steps:a.steps+u.steps,toolErrors:a.toolErrors+u.toolErrors,changedFiles:[...new Set([...a.changedFiles,...u.changedFiles])],cachedReads:a.cachedReads+u.cachedReads,escalated:!0,reason:c,finalModel:n.model,cheapUsage:a.usage,strongUsage:u.usage}}import{spawn as si}from"child_process";import it from"fs/promises";import{createHash as ri}from"crypto";import ze from"path";var ii="2025-03-26",ai=6e4,is=2e4,as=1e5,en=e=>ze.join(e,_.dirName,"mcp.json");async function Qt(e){try{let t=JSON.parse(await it.readFile(e,"utf8"));return{servers:t&&typeof t.servers=="object"&&t.servers?t.servers:{}}}catch{return{servers:{}}}}var Fn=e=>ze.join(e,_.dirName,"trusted-mcp.json"),cs=e=>ri("sha256").update(JSON.stringify(e.servers)).digest("hex");async function ds(e){try{return JSON.parse(await it.readFile(Fn(e),"utf8"))}catch{return{}}}async function tn(e,t){let n=await ds(t);n[ze.resolve(e)]=cs(await Qt(en(e))),await it.mkdir(ze.dirname(Fn(t)),{recursive:!0}),await it.writeFile(Fn(t),JSON.stringify(n,null,2),{mode:384})}async function kt(e,t){let n=await Qt(ze.join(t,_.dirName,"mcp.json")),o=await Qt(en(e)),s=Object.keys(o.servers).length===0||(await ds(t))[ze.resolve(e)]===cs(o);return{servers:{...n.servers,...s?o.servers:{}},untrusted:s?[]:Object.keys(o.servers)}}async function Bn(e,t){let n=en(e);return await it.mkdir(ze.dirname(n),{recursive:!0}),await it.writeFile(n,JSON.stringify(t,null,2)+`
90
- `),n}var nn=e=>Qt(en(e)),Dn=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=si(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(`
129
+ `]];for(let[o,s]of n)try{await ft.access(o)}catch{await ft.mkdir(mn.dirname(o),{recursive:!0}),await ft.writeFile(o,s),t.push(o)}return t}var Na=[/^\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],La=/\b(again|i (told|said|already)|as i (said|mentioned)|every time|always|never|from now on|once more)\b/i,Fa=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 Qs(e){return new Set(e.toLowerCase().replace(/[^a-z0-9+#.\s-]/g," ").split(/\s+/).filter(t=>t.length>1&&!Fa.has(t)))}function er(e,t){let n=Qs(e),o=Qs(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 Da(e){let t=e.trim();return!t||t.length>400||t.startsWith("/")||t.endsWith("?")?!1:Na.some(n=>n.test(t))}function Ua(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 Ba=.4,pn=class{seen=[];known;constructor(t=[]){this.known=[...t]}observe(t){if(!Da(t))return null;let n=Ua(t);if(!n)return null;let o=this.seen.some(r=>er(r,t)>=Ba);this.seen.push(t);let s=La.test(t);return!o&&!s||this.known.some(r=>He(r)===He(n)||er(r,n)>=.6)?null:(this.known.push(n),{rule:n,reason:o?"repeated":"explicit"})}};async function tr(e){let{cheap:t,strong:n,verify:o,maxToolErrors:s=3,...r}=e,i=await et({...r,client:t.client,model:t.model}),c;if(i.stopReason!=="done")c=i.stopReason==="max_steps"?"the cheap model hit the step limit":"the cheap model used the run's token budget";else if(i.toolErrors>=s)c=`${i.toolErrors} tool calls failed`;else if(o){let g=await o();g.ok||(c=`verification failed${g.detail?`: ${g.detail.slice(0,200)}`:""}`)}if(!c)return{...i,escalated:!1,finalModel:t.model,cheapUsage:i.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 u=i.usage.promptTokens+i.usage.completionTokens,d=await et({...r,client:n.client,model:n.model,maxRunTokens:(r.maxRunTokens??F.maxRunTokens)<=0?0:Math.max(5e4,(r.maxRunTokens??F.maxRunTokens)-u)}),p={promptTokens:i.usage.promptTokens+d.usage.promptTokens,completionTokens:i.usage.completionTokens+d.usage.completionTokens,cacheReadTokens:(i.usage.cacheReadTokens??0)+(d.usage.cacheReadTokens??0)};return{...d,usage:p,steps:i.steps+d.steps,toolErrors:i.toolErrors+d.toolErrors,changedFiles:[...new Set([...i.changedFiles,...d.changedFiles])],cachedReads:i.cachedReads+d.cachedReads,escalated:!0,reason:c,finalModel:n.model,cheapUsage:i.usage,strongUsage:d.usage}}import{spawn as Wa}from"child_process";import _t from"fs/promises";import{createHash as qa}from"crypto";import ot from"path";var Ha="2025-03-26",za=6e4,nr=2e4,or=1e5,fn=e=>ot.join(e,w.dirName,"mcp.json");async function gn(e){try{let t=JSON.parse(await _t.readFile(e,"utf8"));return{servers:t&&typeof t.servers=="object"&&t.servers?t.servers:{}}}catch{return{servers:{}}}}var ao=e=>ot.join(e,w.dirName,"trusted-mcp.json"),rr=e=>qa("sha256").update(JSON.stringify(e.servers)).digest("hex");async function ir(e){try{return JSON.parse(await _t.readFile(ao(e),"utf8"))}catch{return{}}}async function hn(e,t){let n=await ir(t);n[ot.resolve(e)]=rr(await gn(fn(e))),await _t.mkdir(ot.dirname(ao(t)),{recursive:!0}),await _t.writeFile(ao(t),JSON.stringify(n,null,2),{mode:384})}async function Nt(e,t){let n=await gn(ot.join(t,w.dirName,"mcp.json")),o=await gn(fn(e)),s=Object.keys(o.servers).length===0||(await ir(t))[ot.resolve(e)]===rr(o);return{servers:{...n.servers,...s?o.servers:{}},untrusted:s?[]:Object.keys(o.servers)}}async function uo(e,t){let n=fn(e);return await _t.mkdir(ot.dirname(n),{recursive:!0}),await _t.writeFile(n,JSON.stringify(t,null,2)+`
130
+ `),n}var wn=e=>gn(fn(e)),lo=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=Wa(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(`
91
131
  `).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(`
92
- `))>=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})+`
132
+ `))>=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,i)=>{let c=setTimeout(()=>{this.pending.delete(s),i(new Error(`${t} timed out after ${o/1e3}s`))},o);this.pending.set(s,{resolve:u=>{clearTimeout(c),r(u)},reject:u=>{clearTimeout(c),i(u)}}),this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",id:s,method:t,params:n})+`
93
133
  `)})}async notify(t,n){this.dead||this.child.stdin.write(JSON.stringify({jsonrpc:"2.0",method:t,params:n})+`
94
- `)}close(){try{this.child.kill()}catch{}}},Un=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(`
95
- `))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(){}},ls=e=>e.replace(/[^a-zA-Z0-9_-]+/g,"_"),li=(e,t)=>`mcp__${ls(e)}__${ls(t)}`.slice(0,64),at=class e{clients=new Map;byName=new Map;errors=new Map;static async fromConfig(t,n){let o=new e;return await Promise.all(Object.entries(t.servers).map(([s,r])=>o.connect(s,r,n))),o}async connect(t,n,o){let s;try{if(n.url)s=new Un(n);else if(n.command)s=new Dn(n,o);else throw new Error('needs "command" or "url"');await s.request("initialize",{protocolVersion:ii,capabilities:{},clientInfo:{name:_.bin,version:"0.1.0"}},is),await s.notify("notifications/initialized");let r;do{let a=await s.request("tools/list",r?{cursor:r}:{},is);for(let c of a.tools??[]){let d=li(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??{}},ai),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(`
96
- `),a=r.length>as?r.slice(0,as)+`
97
- \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 ci}from"child_process";import on from"fs/promises";import us from"os";import we from"path";var di={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp"};function ui(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 mi(e){if(process.platform!=="darwin")return Promise.resolve(null);let t=we.join(us.tmpdir(),`forge-shrink-${process.pid}-${Date.now()}.jpg`);return new Promise(n=>{ci("sips",["-Z","1600","-s","format","jpeg","-s","formatOptions","80",e,"--out",t],async o=>{if(o)return n(null);try{n(await on.readFile(t))}catch{n(null)}finally{on.rm(t,{force:!0}).catch(()=>{})}})})}async function pi(e,t=mi){let n=we.extname(e).toLowerCase();if(!(n in di))throw new Error(`${we.basename(e)}: not a supported image type (png, jpg, gif, webp)`);let o=await on.readFile(e),s=ui(o);if(!s)throw new Error(`${we.basename(e)}: file content is not a valid ${n.slice(1)} image`);if(o.length>he.maxBytes/2&&s!=="image/gif"){let r=await t(e);r&&r.length<o.length&&(o=r,s="image/jpeg")}if(o.length>he.maxBytes)throw new Error(`${we.basename(e)}: image is ${(o.length/1048576).toFixed(1)} MB (max ${he.maxBytes/1048576} MB)`);return{mediaType:s,data:o.toString("base64"),name:we.basename(e)}}var Wn="(?:png|jpe?g|gif|webp)",gi=new RegExp(`(^|\\s)(@?)(?:"([^"\\n]+\\.${Wn})"|'([^'\\n]+\\.${Wn})'|((?:\\\\ |[^\\s"'])+\\.${Wn}))(?=\\s|$|[.,;:!?)]$)`,"gi");async function ms(e,t,n=us.homedir()){let o=[],s=[],r=new Map,a=[...t.matchAll(gi)],c="",d=0;for(let u of a){let g=(u[3]??u[4]??u[5]??"").replace(/\\ /g," "),h=g.startsWith("~/")?we.join(n,g.slice(2)):we.resolve(e,g),y=(u.index??0)+u[1].length,x=(u.index??0)+u[0].length,L=r.get(h);if(L===void 0){try{await on.access(h)}catch{continue}if(o.length>=he.maxPerMessage){s.push(`only ${he.maxPerMessage} images per message; skipped ${we.basename(h)}`);continue}try{o.push(await pi(h)),L=o.length,r.set(h,L)}catch(W){s.push(W instanceof Error?W.message:String(W));continue}}c+=t.slice(d,y)+`[Image #${L}: ${we.basename(h)}]`,d=x}return{text:c+t.slice(d),images:o,errors:s}}import sn from"fs/promises";import fi from"os";import ps from"path";var gs=()=>ps.join(fi.homedir(),_.dirName),qn=()=>ps.join(gs(),"config.json");async function ce(){let e={};try{e=JSON.parse(await sn.readFile(qn(),"utf8"))}catch{}return{apiUrl:_.defaultApiUrl,token:process.env.SCOPE_API_KEY??process.env.FORGE_API_KEY??e.token,defaultModel:e.defaultModel}}async function Ge(e){let t={};try{t=JSON.parse(await sn.readFile(qn(),"utf8"))}catch{}let n={...t,...e};delete n.apiUrl;for(let o of Object.keys(n))n[o]===void 0&&delete n[o];await sn.mkdir(gs(),{recursive:!0}),await sn.writeFile(qn(),JSON.stringify(n,null,2),{mode:384})}async function ee(e,t={}){let n=await ce(),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 le(r.status,d,a)}return a}import _i from"fs/promises";import fs from"path";import{spawn as bs}from"child_process";import{StringDecoder as wi}from"string_decoder";import{createRequire as hi}from"module";var ve=hi(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 ln(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 yi=`
134
+ `)}close(){try{this.child.kill()}catch{}}},co=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 i=await r.text(),c;if((r.headers.get("content-type")??"").includes("text/event-stream")){for(let u of i.split(`
135
+ `))if(u.startsWith("data:"))try{let d=JSON.parse(u.slice(5));if(d.id===s){c=d;break}}catch{}}else c=JSON.parse(i);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(){}},sr=e=>e.replace(/[^a-zA-Z0-9_-]+/g,"_"),Ka=(e,t)=>`mcp__${sr(e)}__${sr(t)}`.slice(0,64),yt=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 co(n);else if(n.command)s=new lo(n,o);else throw new Error('needs "command" or "url"');await s.request("initialize",{protocolVersion:Ha,capabilities:{},clientInfo:{name:w.bin,version:"0.1.0"}},nr),await s.notify("notifications/initialized");let r;do{let i=await s.request("tools/list",r?{cursor:r}:{},nr);for(let c of i.tools??[]){let u=Ka(t,c.name);this.byName.set(u,{server:t,name:c.name,fullName:u,description:c.description??"",inputSchema:c.inputSchema??{type:"object",properties:{}}})}r=i.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??{}},za),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(`
136
+ `),i=r.length>or?r.slice(0,or)+`
137
+ \u2026[truncated]`:r;if(s?.isError)throw new Error(i||"tool reported an error");return i||"(no output)"}close(){for(let t of this.clients.values())t.close();this.clients.clear()}};import _n from"fs/promises";import Ga from"os";import ar from"path";var lr=()=>ar.join(Ga.homedir(),w.dirName),mo=()=>ar.join(lr(),"config.json");async function _e(){let e={};try{e=JSON.parse(await _n.readFile(mo(),"utf8"))}catch{}return{apiUrl:w.defaultApiUrl,token:process.env.SCOPE_API_KEY??process.env.FORGE_API_KEY??e.token,defaultModel:e.defaultModel}}async function st(e){let t={};try{t=JSON.parse(await _n.readFile(mo(),"utf8"))}catch{}let n={...t,...e};delete n.apiUrl;for(let o of Object.keys(n))n[o]===void 0&&delete n[o];await _n.mkdir(lr(),{recursive:!0}),await _n.writeFile(mo(),JSON.stringify(n,null,2),{mode:384})}async function ae(e,t={}){let n=await _e(),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 qe("server",c?.cause?.code??c?.name??"network error")}let i=await r.json().catch(()=>({}));if(!r.ok){let c=i?.error?.message??`request failed (${r.status})`,u=typeof c=="string"?c.replace(/https?:\/\/[^\s"'<>]+/gi,"server"):"request failed";throw new we(r.status,u,i)}return i}import Ya from"fs/promises";import cr from"path";import{spawn as gr}from"child_process";import{StringDecoder as Xa}from"string_decoder";import{createRequire as Ja}from"module";var Pe=Ja(import.meta.url)("../package.json").version;var a={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 fo(e){return!e||e<=0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:String(Math.round(e))}function fr(e){return`${fo(e)} tokens`}function hr(e,t,n=0){return`\u2191 ${fo(e)} in \xB7 \u2193 ${fo(t)} out`}var Va=`
98
138
  \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
99
139
  \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
100
140
  \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
101
141
  \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
102
142
  \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
103
143
  \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
104
- `.trim(),hs=[[255,214,120],[255,190,90],[255,165,70],[255,140,62],[245,115,55],[225,95,48]];function bi(){return yi.split(`
105
- `).map((e,t)=>{let[n,o,s]=hs[Math.min(t,hs.length-1)];return`\x1B[38;2;${n};${o};${s}m${e}${i.reset}`}).join(`
106
- `)}function Jn(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?bi():`${i.userPointer}${i.bold}${_.name}${i.reset}`),console.log(`
107
- ${i.bold}${_.name}${i.reset} ${i.dim}v${ve}${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(`
108
- ${i.dim} / commands \xB7 @ files \xB7 ! shell \xB7 esc interrupts \xB7 ? shortcuts${i.reset}
109
- `)}var xi=["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 rn(){let e=l("cli.ui.status_words",xi.join("|")).split("|").map(t=>t.trim()).filter(Boolean);return e[Math.floor(Math.random()*e.length)]??"Working\u2026"}var Hn=["\xB7","\u2727","\u2726","\u2736","\u2737","\u2736","\u2726","\u2727","\xB7"],_s=[12,5,4,4,4,4,4,5,16],ws=[5,4,4,4,4,4,5];function ki(e){let t=e%88,n=0;for(let s=0;s<_s.length;s++)if(n+=_s[s],t<n)return Hn[s];let o=t-58;n=0;for(let s=0;s<ws.length;s++)if(n+=ws[s],o<n)return Hn[7-s];return Hn[0]}var ys=["#E5733A","#FF9A52","#FFB347","#FFD08A","#FFF1DC","#FFD08A","#FFB347","#FF9A52","#E5733A"],$i="#9A5A3A";function vi(e){let t=parseInt(e.replace("#",""),16);return`\x1B[38;2;${t>>16&255};${t>>8&255};${t&255}m`}function Si(e,t,n,o){let s=ki(4*t),r=t%(e.length+10),a="";for(let u=0;u<e.length;u++){let g=u-(r-5),h=g>=0&&g<ys.length?ys[g]:$i;a+=vi(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 Ti=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Je=e=>Array.from(Ti.segment(e),t=>t.segment);function ye(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 Ri(e,t){let n=Je(e),o=0;for(;o<n.length&&ye(n.slice(o).join(""))>t;)o++;return n.slice(o).join("")}function cn(e,t){let n=Je(e.slice(0,t));return n.pop(),n.join("").length}function Kn(e,t){let n=Je(e.slice(t));return t+(n[0]?.length??0)}var an=class{constructor(t,n){this.onInterrupt=t;this.input=n}onInterrupt;input;frame=0;startTime=Date.now();status=rn();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=rn()),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 wi("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,cn(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=[Si(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(ye(d)<=u)return d;let g="";for(let h of Je(d)){if(ye(g+h)>u-1)break;g+=h}return g+"\u2026"};o.queue.forEach((d,u)=>{let g=u===this.selected,h=r(`${u+1}. ${d}`,s-4);n.push(g?`${i.accent}${i.bold}\u276F ${h}${i.reset}`:`${i.gray}\u23F3 ${h}${i.reset}`)});let a=Ri(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(`
110
- `)}`),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))}},Gn=[{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")}}],sc=Gn.map(e=>e.command);function Ke(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?Gn.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):[...Gn]}function xs(){console.log(l("cli.ui.0_command_code_1_2",`
111
- {0}{4}{1} {2}v{5}{3}`,i.bold,i.reset,i.dim,i.reset,_.name,ve)),console.log(l("cli.ui.0_ai_agent_that_pairs",`{0}{2}{1}
112
- `,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]
113
- `),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",`
114
- {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",`
144
+ `.trim(),ur=[[255,214,120],[255,190,90],[255,165,70],[255,140,62],[245,115,55],[225,95,48]];function Za(){return Va.split(`
145
+ `).map((e,t)=>{let[n,o,s]=ur[Math.min(t,ur.length-1)];return`\x1B[38;2;${n};${o};${s}m${e}${a.reset}`}).join(`
146
+ `)}function wo(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?Za():`${a.userPointer}${a.bold}${w.name}${a.reset}`),console.log(`
147
+ ${a.bold}${w.name}${a.reset} ${a.dim}v${Pe}${a.reset} ${a.gray}\xB7 ${w.tagline}${a.reset}`);let i=(c,u)=>console.log(` ${a.gray}${c.padEnd(8)}${a.reset}${u}`);i("model",`${a.accent}${e}${a.reset}`),i("taste",`${t} ${t===1?"rule":"rules"} loaded`),i("folder",r),console.log(`
148
+ ${a.dim} / commands \xB7 @ files \xB7 ! shell \xB7 esc interrupts \xB7 ? shortcuts${a.reset}
149
+ `)}var Qa=["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 yn(){let e=l("cli.ui.status_words",Qa.join("|")).split("|").map(t=>t.trim()).filter(Boolean);return e[Math.floor(Math.random()*e.length)]??"Working\u2026"}var po=["\xB7","\u2727","\u2726","\u2736","\u2737","\u2736","\u2726","\u2727","\xB7"],dr=[12,5,4,4,4,4,4,5,16],mr=[5,4,4,4,4,4,5];function el(e){let t=e%88,n=0;for(let s=0;s<dr.length;s++)if(n+=dr[s],t<n)return po[s];let o=t-58;n=0;for(let s=0;s<mr.length;s++)if(n+=mr[s],o<n)return po[7-s];return po[0]}var pr=["#E5733A","#FF9A52","#FFB347","#FFD08A","#FFF1DC","#FFD08A","#FFB347","#FF9A52","#E5733A"],tl="#9A5A3A";function nl(e){let t=parseInt(e.replace("#",""),16);return`\x1B[38;2;${t>>16&255};${t>>8&255};${t&255}m`}function ol(e,t,n,o){let s=el(4*t),r=t%(e.length+10),i="";for(let d=0;d<e.length;d++){let p=d-(r-5),g=p>=0&&p<pr.length?pr[p]:tl;i+=nl(g)+e[d]}let c=`${a.statusPillBg} ${a.statusPillFg}${a.bold}${s} ${i}${a.statusPillBg} ${a.reset}`,u=` ${a.bold}${a.gray}esc${a.reset} ${a.dim}${a.gray}to interrupt${a.reset} ${a.dim}${a.gray}\u2022${a.reset} ${a.dim}${a.gray}${n}s${a.reset} ${a.dim}${a.gray}\u2022${a.reset} ${a.gray}\u2193${a.reset} ${a.dim}${a.gray}${o}${a.reset}`;return c+u}var sl=new Intl.Segmenter(void 0,{granularity:"grapheme"}),rt=e=>Array.from(sl.segment(e),t=>t.segment);function Ee(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 rl(e,t){let n=rt(e),o=0;for(;o<n.length&&Ee(n.slice(o).join(""))>t;)o++;return n.slice(o).join("")}function kn(e,t){let n=rt(e.slice(0,t));return n.pop(),n.join("").length}function _o(e,t){let n=rt(e.slice(t));return t+(n[0]?.length??0)}var bn=class{constructor(t,n){this.onInterrupt=t;this.input=n}onInterrupt;input;frame=0;startTime=Date.now();status=yn();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=yn()),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 Xa("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,kn(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 i=n.draft.trim();i&&o.push(i),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=[ol(this.status,this.frame,t,this.tokens)],o=this.input;if(!o)return n;let s=Math.max(process.stdout.columns||80,20),r=(u,d)=>{if(Ee(u)<=d)return u;let p="";for(let g of rt(u)){if(Ee(p+g)>d-1)break;p+=g}return p+"\u2026"};o.queue.forEach((u,d)=>{let p=d===this.selected,g=r(`${d+1}. ${u}`,s-4);n.push(p?`${a.accent}${a.bold}\u276F ${g}${a.reset}`:`${a.gray}\u23F3 ${g}${a.reset}`)});let i=rl(o.draft,s-5),c=this.selected<0;return n.push(o.draft||!c?`${a.userPointer}\u276F${a.reset} ${i}${c?"\x1B[7m \x1B[0m":""}`:`${a.userPointer}\u276F${a.reset} \x1B[7m \x1B[0m${a.dim}Type to queue the next task\u2026${a.reset}`),n.push(`${a.dim}${"\u2500".repeat(s)}${a.reset}`),n.push(o.queue.length?`${a.dim}esc interrupt \xB7 enter queue \xB7 \u2191/\u2193 select queued \xB7 backspace/del remove${a.reset}`:`${a.dim}esc interrupt \xB7 enter queues a task to run next${a.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(`
150
+ `)}`),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))}},ho=[{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 "+w.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 "+w.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 "+w.name)}},{command:"/logout",get description(){return l("cli.ui.log_out_of_command_code","Log out of "+w.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 "+w.name+" memory")}},{command:"/model",get description(){return l("cli.ui.switch_between_command_code_models","Switch between "+w.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 "+w.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 "+w.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 "+w.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 "+w.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")}}],Ud=ho.map(e=>e.command);function it(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 bt(e){let t=e.trim().toLowerCase();return t?ho.map(n=>{let o=n.command.toLowerCase(),s=(n.displayCommand??n.command).toLowerCase(),r=n.description.toLowerCase(),i=0;return o===`/${t}`?i+=200:o.startsWith(`/${t}`)?i+=100:o.includes(t)&&(i+=50),s!==o&&s.includes(t)&&(i+=60),r.includes(t)&&(i+=25),{item:n,score:i}}).filter(n=>n.score>0).sort((n,o)=>o.score-n.score).map(n=>n.item):[...ho]}function wr(){console.log(l("cli.ui.0_command_code_1_2",`
151
+ {0}{4}{1} {2}v{5}{3}`,a.bold,a.reset,a.dim,a.reset,w.name,Pe)),console.log(l("cli.ui.0_ai_agent_that_pairs",`{0}{2}{1}
152
+ `,a.gray,a.reset,w.tagline)),console.log(l("cli.ui.0_usage_1","{0}Usage:{1}",a.bold,a.reset)),console.log(` ${a.cyan}${w.bin}${a.reset} [options] [prompt]
153
+ `),console.log(l("cli.ui.0_slash_commands_1","{0}Slash Commands:{1}",a.bold,a.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 ${w.dirName}/skills.md and memory.md`},{cmd:"/exit, /quit",desc:"Exit session"}];for(let o of t)console.log(` ${a.cyan}${o.cmd.padEnd(24)}${a.reset} ${a.gray}${o.desc}${a.reset}`);console.log(l("cli.ui.0_keyboard_shortcuts_modes_1",`
154
+ {0}Keyboard Shortcuts & Modes:{1}`,a.bold,a.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(` ${a.accent}${o.key.padEnd(24)}${a.reset} ${a.gray}${o.desc}${a.reset}`);console.log(l("cli.ui.0_1_2_tip_type",`
115
155
  {0}\u276F{1} {2}Tip: Type {3}@{4} followed by a path or {5}/{6} for commands and press Tab to complete.{7}
116
- `,i.cyan,i.reset,i.gray,i.cyan,i.reset,i.cyan,i.reset,i.reset))}function Yn(){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 Vn(){console.log("");for(let e of Yn())console.log(e);console.log("")}async function ks(e){let n=process.platform==="darwin"?"pbcopy":"wl-copy";return new Promise(o=>{try{let s=bs(n,[],{stdio:["pipe","ignore","ignore"]});s.stdin.write(e),s.stdin.end(),s.on("close",r=>{if(r===0)return o(!0);zn(e).then(o)}),s.on("error",()=>{zn(e).then(o)})}catch{zn(e).then(o)}})}function zn(e){return new Promise(t=>{try{let n=bs("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 $s(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 _i.readdir(r,{withFileTypes:!0});for(let c of a){if(n.length>=t)break;if(o.has(c.name))continue;let d=fs.join(r,c.name),u=fs.relative(e,d);c.isDirectory()?(n.push(u+"/"),await s(d)):n.push(u)}}catch{}}return await s(e),n}var je=[];async function Xn(){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 vs=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})
117
- \u2022 Please check your internet connection and try again.`}if(e instanceof le){let o=e.body?.error??{},s=vs(e.message);switch(e.status){case 401:return s.includes("login")?s:`Not authorized: ${s}.
118
- Run \`/login\` or \`${_.bin} login\` to authenticate.`;case 402:return`${s}
119
- See \`${_.bin} usage\`. Upgrade in the dashboard (/app/billing) or wait for the reset.`;case 403:return`${s}
120
- Run \`${_.bin} models\` to see what your plan includes.`;case 404:return`${s}
121
- 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}
122
- It was retried once. Try again shortly.`;default:return`${s} (HTTP ${e.status})`}}let n=vs(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.
123
- \u2022 Try again after 00:00 UTC.`:n.includes("Insufficient Balance")?"The service is temporarily unavailable. Please try again shortly.":n}function Mi(e){if(process.env.FORGE_NO_BROWSER)return;let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Ei(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}async function dn(){let e=await ee("/v1/auth/device/code",{method:"POST",auth:!1});console.log(l("cli.commands.open_0_and_confirm_code",`
156
+ `,a.cyan,a.reset,a.gray,a.cyan,a.reset,a.cyan,a.reset,a.reset))}function yo(){return[`${a.bold}Available Shortcuts:${a.reset}`,` ${a.accent}!${a.reset} for bash mode ${a.cyan}double tap esc${a.reset} to clear input`,` ${a.accent}/${a.reset} for commands ${a.cyan}\\ + \u21B5 or ctrl + j${a.reset} for newline`,` ${a.accent}@${a.reset} for file paths ${a.cyan}ctrl + v${a.reset} to paste image`,` ${a.accent}Tab${a.reset} for autocomplete ${a.cyan}\u2191 / \u2193${a.reset} to browse history`,` ${a.accent}Esc${a.reset} to interrupt agent ${a.cyan}ctrl + c${a.reset} cancel \xB7 ${a.cyan}ctrl + d${a.reset} exit`]}function bo(){console.log("");for(let e of yo())console.log(e);console.log("")}async function _r(e){let n=process.platform==="darwin"?"pbcopy":"wl-copy";return new Promise(o=>{try{let s=gr(n,[],{stdio:["pipe","ignore","ignore"]});s.stdin.write(e),s.stdin.end(),s.on("close",r=>{if(r===0)return o(!0);go(e).then(o)}),s.on("error",()=>{go(e).then(o)})}catch{go(e).then(o)}})}function go(e){return new Promise(t=>{try{let n=gr("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 yr(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 i=await Ya.readdir(r,{withFileTypes:!0});for(let c of i){if(n.length>=t)break;if(o.has(c.name))continue;let u=cr.join(r,c.name),d=cr.relative(e,u);c.isDirectory()?(n.push(d+"/"),await s(u)):n.push(d)}}catch{}}return await s(e),n}var Ke=[];async function ko(){let{execFile:e}=await import("child_process"),t=await import("fs/promises"),o=`${(await import("os")).tmpdir()}/forge-paste-${Date.now()}.png`,s=(r,i)=>new Promise(c=>e(r,i,{encoding:"buffer",maxBuffer:32*1024*1024},(u,d)=>c(u?null:d)));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"],u=>c(!u))))return await t.rm(o,{force:!0}),null}else{let i=await s("wl-paste",["--type","image/png"])??await s("xclip",["-selection","clipboard","-t","image/png","-o"]);if(!i||i.length<8)return null;await t.writeFile(o,i)}let r=await t.readFile(o).then(i=>i.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 br=e=>e.replace(/https?:\/\/[^\s"'<>]+/gi,"server").trim();function Ge(e,t){if(e instanceof qe){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})
157
+ \u2022 Please check your internet connection and try again.`}if(e instanceof we){let o=e.body?.error??{},s=br(e.message);switch(e.status){case 401:return s.includes("login")?s:`Not authorized: ${s}.
158
+ Run \`/login\` or \`${w.bin} login\` to authenticate.`;case 402:return`${s}
159
+ See \`${w.bin} usage\`. Upgrade in the dashboard (/app/billing) or wait for the reset.`;case 403:return`${s}
160
+ Run \`${w.bin} models\` to see what your plan includes.`;case 404:return`${s}
161
+ Run \`${w.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}
162
+ It was retried once. Try again shortly.`;default:return`${s} (HTTP ${e.status})`}}let n=br(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.
163
+ \u2022 Try again after 00:00 UTC.`:n.includes("Insufficient Balance")?"The service is temporarily unavailable. Please try again shortly.":n}function al(e){if(process.env.FORGE_NO_BROWSER)return;let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{il(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}async function xn(){let e=await ae("/v1/auth/device/code",{method:"POST",auth:!1});console.log(l("cli.commands.open_0_and_confirm_code",`
124
164
  Open {0}
125
165
  and confirm code: {1}
126
- `,e.verificationUrl,e.userCode)),Mi(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 ee("/v1/auth/device/token",{method:"POST",auth:!1,body:JSON.stringify({deviceCode:e.deviceCode})}).catch(o=>{throw o});if(n.status==="approved"){await Ge({token:n.apiKey});let o=await ee("/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 un(){await Ge({token:void 0}),console.log(l("cli.commands.logged_out","Logged out."))}async function mn(e){let t=await ce();if(e){await Ge({defaultModel:e}),console.log(l("cli.commands.default_model_set_to_0","Default model set to: {0}",e));return}let n=await ee("/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(`
166
+ `,e.verificationUrl,e.userCode)),al(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 ae("/v1/auth/device/token",{method:"POST",auth:!1,body:JSON.stringify({deviceCode:e.deviceCode})}).catch(o=>{throw o});if(n.status==="approved"){await st({token:n.apiKey});let o=await ae("/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 $n(){await st({token:void 0}),console.log(l("cli.commands.logged_out","Logged out."))}async function vn(e){let t=await _e();if(e){await st({defaultModel:e}),console.log(l("cli.commands.default_model_set_to_0","Default model set to: {0}",e));return}let n=await ae("/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(`
127
167
  Server default: ${n.default}`),n.data.some(s=>s.vision)&&console.log(l("cli.commands.images_can_read_images_attach",`
128
- [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 pn(){let e=await ee("/v1/usage"),t=c=>c.toLocaleString(),n=(e.promptTokens??0)+(e.completionTokens??0),o=ln(n),s=!!e.monthlyOff,r=e.estimatedRequests??0,a=e.virtualCreditsUsd??0;console.log(l("cli.commands.plan_usage",`Plan: {0}
168
+ [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 Sn(){let e=await ae("/v1/usage"),t=c=>c.toLocaleString(),n=(e.promptTokens??0)+(e.completionTokens??0),o=fr(n),s=!!e.monthlyOff,r=e.estimatedRequests??0,i=e.virtualCreditsUsd??0;console.log(l("cli.commands.plan_usage",`Plan: {0}
129
169
  Requests: {1} of {2} used
130
170
  Dollars: {3} of {4} used
131
- 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 gn(){let e=await Ln(process.cwd());for(let t of[st(process.cwd()),xt(process.cwd())])console.log(`${e.includes(t)?"created":"exists "} ${$t.relative(process.cwd(),t)}`);console.log(l("cli.commands.add_a_rule_0_skills",`
132
- Add a rule: {0} skills add "Use pnpm, not npm"`,_.bin))}async function Ts(){let e=process.cwd(),[t,n]=[await He(e),await Ne(e)];t.length?(console.log(l("cli.commands.skills_0_applied_to_every","Skills ({0}) \u2014 applied to every run:",$t.relative(e,st(e)))),t.forEach((o,s)=>console.log(` ${s+1}. ${o}`))):console.log(l("cli.commands.no_skills_yet_add_one",'No skills yet. Add one: {0} skills add "Prefer pnpm"',_.bin)),console.log(l("cli.commands.memory_notes_0_1",`
133
- Memory notes: {0} ({1})`,n.length,$t.relative(e,xt(e))))}async function Rs(e){let t=await rt(process.cwd(),e.join(" "));console.log(t.added?`Added skill: ${t.skill}
134
- It will be used on the next run.`:`Already a skill: ${t.skill}`)}var Ci=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);async function Es(e,t){let n=process.cwd(),[o,s]=[await He(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 ee("/v1/taste",{method:"POST",body:JSON.stringify({name:Ci(e??$t.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 Ms(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 ee(`/v1/taste/${e}`);await Ln(t);let o=0,s=0;for(let a of n.skills)(await rt(t,a)).added&&(o++,console.log(l("cli.commands.skill_0"," + skill: {0}",a)));let r=new Set((await Ne(t)).map(Ae));for(let a of n.memory)r.has(Ae(a))||(await bt(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 Cs(e){let t=await ee(`/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 Ps(){let e=process.cwd(),t=await kt(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
135
- `,t.untrusted.join(", "),_.dirName,_.bin));let o=await at.fromConfig(t,e);try{for(let s of n){let r=o.errors.get(s),a=o.tools.filter(c=>c.server===s);console.log(r?`\u2717 ${s} ${r}`:`\u2713 ${s} ${a.length} tool(s)`);for(let c of a)console.log(` ${c.fullName} ${c.description.split(`
136
- `)[0].slice(0,80)}`)}}finally{o.close()}}async function As(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 nn(process.cwd());n.servers[e]=/^https?:\/\//.test(t[0])?{url:t[0]}:{command:t[0],args:t.slice(1)};let o=await Bn(process.cwd(),n);await tn(process.cwd(),Oe.homedir()),console.log(l("cli.commands.saved_0_to_1_check",'Saved "{0}" to {1}. Check it: {2} mcp list',e,$t.relative(process.cwd(),o),_.bin))}async function Ns(e){let t=await nn(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 Bn(process.cwd(),t),await tn(process.cwd(),Oe.homedir()),console.log(l("cli.commands.removed_0",'Removed "{0}".',e))}async function js(){let e=await nn(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 tn(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 Is=(e,t=" ")=>{for(let n of["PreToolUse","PostToolUse"])for(let o of e[n])console.log(`${t}${n} [${o.matcher??"*"}]: ${o.command}`)};async function Os(){let e=await yt(process.cwd(),Oe.homedir());if(!We(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(We(e)&&(console.log(l("cli.commands.effective_hooks","Effective hooks:")),Is(e)),e.untrusted.length){console.log(l("cli.commands.not_run_untrusted_project_hooks",`
137
- 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 Ls(){let e=await Kt(process.cwd());if(!We(e))return console.log(l("cli.commands.no_project_hooks_in_0","No project hooks in {0}/hooks.json.",_.dirName));Is(e),await Wo(process.cwd(),Oe.homedir()),console.log(l("cli.commands.trusted_0_hook_s_they","Trusted {0} hook(s). They run until the file changes.",We(e)))}async function fn(){let e=await ce(),t=process.cwd(),n=u=>console.log(` \x1B[32m\u2713\x1B[0m ${u}`),o=(u,g)=>console.log(` \x1B[31m\u2717\x1B[0m ${u}${g?`
138
- \u2192 ${g}`:""}`);console.log(l("cli.commands.0_doctor",`
171
+ Tokens: {5}`,e.plan,t(e.requests),s||!r?"no cap":t(r),`$${(e.usedUsd??0).toFixed(2)}`,s||!i?"no cap":`$${i.toFixed(2)}`,o))}async function Tn(){let e=await io(process.cwd());for(let t of[ht(process.cwd()),Ot(process.cwd())])console.log(`${e.includes(t)?"created":"exists "} ${Lt.relative(process.cwd(),t)}`);console.log(l("cli.commands.add_a_rule_0_skills",`
172
+ Add a rule: {0} skills add "Use pnpm, not npm"`,w.bin))}async function xr(){let e=process.cwd(),[t,n]=[await nt(e),await ze(e)];t.length?(console.log(l("cli.commands.skills_0_applied_to_every","Skills ({0}) \u2014 applied to every run:",Lt.relative(e,ht(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"',w.bin)),console.log(l("cli.commands.memory_notes_0_1",`
173
+ Memory notes: {0} ({1})`,n.length,Lt.relative(e,Ot(e))))}async function $r(e){let t=await wt(process.cwd(),e.join(" "));console.log(t.added?`Added skill: ${t.skill}
174
+ It will be used on the next run.`:`Already a skill: ${t.skill}`)}var ll=e=>e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48);async function vr(e,t){let n=process.cwd(),[o,s]=[await nt(n),await ze(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.',w.dirName,w.bin));let r=await ae("/v1/taste",{method:"POST",body:JSON.stringify({name:ll(e??Lt.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}",w.bin,r.slug))}async function Sr(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",w.bin));let n=await ae(`/v1/taste/${e}`);await io(t);let o=0,s=0;for(let i of n.skills)(await wt(t,i)).added&&(o++,console.log(l("cli.commands.skill_0"," + skill: {0}",i)));let r=new Set((await ze(t)).map(He));for(let i of n.memory)r.has(He(i))||(await jt(t,i),s++,console.log(l("cli.commands.memory_0"," + memory: {0}",i)));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 Tr(e){let t=await ae(`/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 Er(){let e=process.cwd(),t=await Nt(e,Je.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 .",w.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
175
+ `,t.untrusted.join(", "),w.dirName,w.bin));let o=await yt.fromConfig(t,e);try{for(let s of n){let r=o.errors.get(s),i=o.tools.filter(c=>c.server===s);console.log(r?`\u2717 ${s} ${r}`:`\u2713 ${s} ${i.length} tool(s)`);for(let c of i)console.log(` ${c.fullName} ${c.description.split(`
176
+ `)[0].slice(0,80)}`)}}finally{o.close()}}async function Rr(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 wn(process.cwd());n.servers[e]=/^https?:\/\//.test(t[0])?{url:t[0]}:{command:t[0],args:t.slice(1)};let o=await uo(process.cwd(),n);await hn(process.cwd(),Je.homedir()),console.log(l("cli.commands.saved_0_to_1_check",'Saved "{0}" to {1}. Check it: {2} mcp list',e,Lt.relative(process.cwd(),o),w.bin))}async function Mr(e){let t=await wn(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,w.dirName));delete t.servers[e],await uo(process.cwd(),t),await hn(process.cwd(),Je.homedir()),console.log(l("cli.commands.removed_0",'Removed "{0}".',e))}async function Ar(){let e=await wn(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.",w.dirName));for(let[n,o]of Object.entries(e.servers))console.log(` ${n}: ${o.url??[o.command,...o.args??[]].join(" ")}`);await hn(process.cwd(),Je.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 Cr=(e,t=" ")=>{for(let n of["PreToolUse","PostToolUse"])for(let o of e[n])console.log(`${t}${n} [${o.matcher??"*"}]: ${o.command}`)};async function Pr(){let e=await It(process.cwd(),Je.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).",w.dirName,w.dirName));if(Qe(e)&&(console.log(l("cli.commands.effective_hooks","Effective hooks:")),Cr(e)),e.untrusted.length){console.log(l("cli.commands.not_run_untrusted_project_hooks",`
177
+ Not run (untrusted project hooks in {0}/hooks.json); review, then run: {1} hooks trust`,w.dirName,w.bin));for(let t of e.untrusted)console.log(` [${t.matcher??"*"}]: ${t.command}`)}}async function Ir(){let e=await on(process.cwd());if(!Qe(e))return console.log(l("cli.commands.no_project_hooks_in_0","No project hooks in {0}/hooks.json.",w.dirName));Cr(e),await ks(process.cwd(),Je.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 En(){let e=await _e(),t=process.cwd(),n=d=>console.log(` \x1B[32m\u2713\x1B[0m ${d}`),o=(d,p)=>console.log(` \x1B[31m\u2717\x1B[0m ${d}${p?`
178
+ \u2192 ${p}`:""}`);console.log(l("cli.commands.0_doctor",`
139
179
  {0} doctor
140
- `,_.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=>Ss("git",["--version"],(g,h)=>u(g?null:String(h).trim())));if(r?n(r):o("git not found","install git (the Changes/review features need it)"),(r?await new Promise(u=>Ss("git",["rev-parse","--is-inside-work-tree"],{cwd:t},g=>u(!g))):!1)?n("inside a git repository"):console.log(l("cli.commands.not_inside_a_git_repository"," - not inside a git repository (optional)")),e.token)try{let u=await ee("/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 kt(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 yt(t,Oe.homedir());console.log(l("cli.commands.0_hook_s_active_1"," - {0} hook(s) active{1}",We(d),d.untrusted.length?`, ${d.untrusted.length} untrusted (run \`${_.bin} hooks trust\`)`:"")),console.log("")}import Tt from"fs/promises";import eo from"os";import{execFile as Fi}from"child_process";import dt from"readline/promises";import{StringDecoder as Di}from"string_decoder";import Le from"path";import Fs from"crypto";import vt from"fs/promises";import ct from"os";import hn from"path";var Pi=/^[A-Za-z0-9_-]{6,64}$/,Ai=e=>Fs.createHash("sha256").update(hn.resolve(e)).digest("hex").slice(0,16),Ds=(e,t=ct.homedir())=>hn.join(t,_.dirName,"sessions",Ai(e)),_n=(e,t,n=ct.homedir())=>{if(!Pi.test(t))throw new Error(l("cli.sessions.invalid_session_id","invalid session id"));return hn.join(Ds(e,n),`${t}.json`)},wn=()=>Fs.randomUUID().replace(/-/g,"").slice(0,12);function St(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 Us(e,t,n=ct.homedir()){let o=_n(e,t.id,n);await vt.mkdir(hn.dirname(o),{recursive:!0});let s=`${o}.${process.pid}.tmp`;return await vt.writeFile(s,JSON.stringify(t),{mode:384}),await vt.rename(s,o),o}async function Bs(e,t,n=ct.homedir()){try{return JSON.parse(await vt.readFile(_n(e,t,n),"utf8"))}catch(o){if(o?.code==="ENOENT"||o instanceof SyntaxError)return null;throw o}}async function Zn(e,t=ct.homedir()){let n;try{n=await vt.readdir(Ds(e,t))}catch{return[]}let o=[];for(let s of n){if(!s.endsWith(".json"))continue;let r=await Bs(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 Qn(e,t,n=ct.homedir()){let o=await Zn(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?Bs(e,s.id,n):null}var yn=e=>e.flatMap((t,n)=>t.role==="user"?[n]:[]),bn=(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 Ni from"fs";import ji from"os";import Ws from"path";function Ii(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 Oi=new Set(["FORGE_API_KEY","FORGE_API_URL"]),Li=new Set(["FORGE_API_URL"]);function qs(e=process.cwd()){let t=Ws.join(ji.homedir(),_.dirName,".env");for(let n of[Ws.join(e,".env"),t]){let o;try{o=Ni.readFileSync(n,"utf8")}catch{continue}for(let[s,r]of Object.entries(Ii(o)))Li.has(s)&&n!==t||Oi.has(s)&&process.env[s]===void 0&&(process.env[s]=r)}}var v=e=>`\x1B[2m${e}\x1B[0m`,Hs=(e,t=200)=>(e.length>t?e.slice(0,t)+"\u2026":e).replace(/\n/g,"\u23CE ");function Ui(e){e.type==="token"?process.stdout.write(e.text):e.type==="assistant"?console.log(`
141
- ${i.assistantPrefix}\u25C6${i.reset} ${e.text}
142
- `):e.type==="tool_start"?console.log(`${i.userPointer}\u2692${i.reset} ${i.bold}${e.name.replace(/_/g," ")}${i.reset} ${v(Hs(JSON.stringify(e.args),120))}`):e.type==="tool_result"?console.log(v(` ${e.ok?"\u2713":"\u2717"} ${Hs(e.output,160)}`)):e.type==="repair"?console.log(v(` \u21BA repaired ${e.name} call (${e.via})`)):e.type==="denied"?console.log(v(" \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 Bi=e=>console.error(v(` \u21BB ${e.status?`server returned ${e.status}`:"connection problem"}; retrying in ${(e.delayMs/1e3).toFixed(1)}s\u2026`));async function to(e){qs();let t=await ce(),n=e.model==="mock-model"||e.model==="mock";if(!!t.token){let s=e.model??t.defaultModel??"default";try{Sn(await ee("/v1/models"))}catch{}if(!e.model)try{let r=await ee("/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(v(`model "${s}" is not available on this server; switching to "${d}".`)),s=d,await Ge({defaultModel:d})}}catch{}return{client:new Vt({baseUrl:`${t.apiUrl.replace(/\/$/,"")}/v1`,apiKey:t.token,onRetry:Bi}),model:s,label:"gateway",apiUrl:t.apiUrl}}if(n)return{client:new qe,model:"mock-model",label:"local mock"};if(!t.token){if(e.prompt)throw new le(401,"Not logged in \u2014 run `forge login` to authenticate.",{});return{client:{chat:async()=>{throw new le(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 no(e,t,n){let o=e.escalateTo??process.env.FORGE_ESCALATION_MODEL;if(o)return o;if(t!=="gateway")return null;let r=(await ee("/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 zs(e,t,n){return async o=>{if(!process.stdin.isTTY)return console.error(v(` (not a terminal) refusing: ${o.reason} \u2014 rerun with --yolo to auto-approve`)),!1;t?.();let s=e??dt.createInterface({input:process.stdin,output:process.stdout}),r=(await s.question(`
143
- ? Allow ${o.reason}
144
- [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 Gs(e,t){if(!process.stdin.isTTY)return;let n=t??dt.createInterface({input:process.stdin,output:process.stdout});try{if(!(await n.question(`
145
- 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 bt(e,o);console.log(l("cli.run.saved_to_0","Saved to {0}",Le.relative(e,s)))}finally{t||n.close()}}async function Wi(e,t,n){if(!n||!process.stdin.isTTY)return!1;let o=e??dt.createInterface({input:process.stdin,output:process.stdout});try{let s=n.reason==="repeated"?"You've corrected this more than once":"That sounds like a standing rule",r=(await o.question(`
180
+ `,w.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(d=>kr("git",["--version"],(p,g)=>d(p?null:String(g).trim())));if(r?n(r):o("git not found","install git (the Changes/review features need it)"),(r?await new Promise(d=>kr("git",["rev-parse","--is-inside-work-tree"],{cwd:t},p=>d(!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 d=await ae("/v1/me");n(`logged in as ${d.email??"user"}`)}catch(d){o(`connection error: ${Ge(d)}`,`run \`${w.bin} login\` again`)}else o("not logged in",`run \`${w.bin} login\` (or set FORGE_API_KEY)`);let c=await Nt(t,Je.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 \`${w.bin} mcp trust\`)`:""));let u=await It(t,Je.homedir());console.log(l("cli.commands.0_hook_s_active_1"," - {0} hook(s) active{1}",Qe(u),u.untrusted.length?`, ${u.untrusted.length} untrusted (run \`${w.bin} hooks trust\`)`:"")),console.log("")}import Ut from"fs/promises";import vo from"os";import{execFile as hl}from"child_process";import xt from"readline/promises";import{StringDecoder as wl}from"string_decoder";import Ye from"path";import jr from"crypto";import Ft from"fs/promises";import kt from"os";import Rn from"path";var cl=/^[A-Za-z0-9_-]{6,64}$/,ul=e=>jr.createHash("sha256").update(Rn.resolve(e)).digest("hex").slice(0,16),Or=(e,t=kt.homedir())=>Rn.join(t,w.dirName,"sessions",ul(e)),Mn=(e,t,n=kt.homedir())=>{if(!cl.test(t))throw new Error(l("cli.sessions.invalid_session_id","invalid session id"));return Rn.join(Or(e,n),`${t}.json`)},An=()=>jr.randomUUID().replace(/-/g,"").slice(0,12);function Dt(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 Nr(e,t,n=kt.homedir()){let o=Mn(e,t.id,n);await Ft.mkdir(Rn.dirname(o),{recursive:!0});let s=`${o}.${process.pid}.tmp`;return await Ft.writeFile(s,JSON.stringify(t),{mode:384}),await Ft.rename(s,o),o}async function Lr(e,t,n=kt.homedir()){try{return JSON.parse(await Ft.readFile(Mn(e,t,n),"utf8"))}catch(o){if(o?.code==="ENOENT"||o instanceof SyntaxError)return null;throw o}}async function xo(e,t=kt.homedir()){let n;try{n=await Ft.readdir(Or(e,t))}catch{return[]}let o=[];for(let s of n){if(!s.endsWith(".json"))continue;let r=await Lr(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(i=>i.role==="user").length})}return o.sort((s,r)=>r.updatedAt-s.updatedAt)}async function $o(e,t,n=kt.homedir()){let o=await xo(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?Lr(e,s.id,n):null}var Cn=e=>e.flatMap((t,n)=>t.role==="user"?[n]:[]),Pn=(e,t=Date.now())=>{let n=Math.max(0,Math.round((t-e)/1e3));return n<60?`${n}s ago`:n<3600?`${Math.round(n/60)}m ago`:n<86400?`${Math.round(n/3600)}h ago`:`${Math.round(n/86400)}d ago`};import dl from"fs";import ml from"os";import Fr from"path";function pl(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 gl=new Set(["FORGE_API_KEY","FORGE_API_URL"]),fl=new Set(["FORGE_API_URL"]);function Dr(e=process.cwd()){let t=Fr.join(ml.homedir(),w.dirName,".env");for(let n of[Fr.join(e,".env"),t]){let o;try{o=dl.readFileSync(n,"utf8")}catch{continue}for(let[s,r]of Object.entries(pl(o)))fl.has(s)&&n!==t||gl.has(s)&&process.env[s]===void 0&&(process.env[s]=r)}}var S=e=>`\x1B[2m${e}\x1B[0m`,Ur=(e,t=200)=>(e.length>t?e.slice(0,t)+"\u2026":e).replace(/\n/g,"\u23CE ");function _l(e){if(e.type==="token")process.stdout.write(e.text);else if(e.type==="assistant")console.log(`
181
+ ${a.assistantPrefix}\u25C6${a.reset} ${e.text}
182
+ `);else if(e.type==="diagnostics")console.log(S(e.errors?` \u26A0 TypeScript: ${e.errors} error(s) in changed files (sent to the agent)`:` \u2713 TypeScript: no errors in ${e.files} changed file(s)`));else if(e.type==="compacted")console.log(S(` \u21BB context summarized (~${e.tokensBefore.toLocaleString()} \u2192 ~${e.tokensAfter.toLocaleString()} tokens)`));else if(e.type==="tool_start"&&e.name==="todo_write"){let t=e.args?.todos??[];console.log(`${a.userPointer}\u2630${a.reset} ${a.bold}tasks${a.reset} ${S(`${t.filter(n=>n.status==="completed").length}/${t.length}`)}`);for(let n of t)console.log(n.status==="completed"?S(` \u2713 ${n.content}`):n.status==="in_progress"?` \u25D0 ${a.bold}${n.content}${a.reset}`:S(` \u25CB ${n.content}`))}else e.type==="tool_start"?console.log(`${a.userPointer}\u2692${a.reset} ${a.bold}${e.name.replace(/_/g," ")}${a.reset} ${S(Ur(JSON.stringify(e.args),120))}`):e.type==="tool_result"?console.log(S(` ${e.ok?"\u2713":"\u2717"} ${Ur(e.output,160)}`)):e.type==="repair"?console.log(S(` \u21BA repaired ${e.name} call (${e.via})`)):e.type==="denied"?console.log(S(" \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 yl=e=>console.error(S(` \u21BB ${e.status?`server returned ${e.status}`:"connection problem"}; retrying in ${(e.delayMs/1e3).toFixed(1)}s\u2026`));async function So(e){Dr();let t=await _e(),n=e.model==="mock-model"||e.model==="mock";if(!!t.token){let s=e.model??t.defaultModel??"default";try{Fn(await ae("/v1/models"))}catch{}if(!e.model)try{let r=await ae("/v1/models"),i=r.data.map(u=>u.id),c=typeof r.default=="string"&&i.includes(r.default)?r.default:null;if(!t.defaultModel&&c&&(s=c),i.length>0&&!i.includes(s)){let u=c||i[0];console.error(S(`model "${s}" is not available on this server; switching to "${u}".`)),s=u,await st({defaultModel:u})}}catch{}return{client:new dn({baseUrl:`${t.apiUrl.replace(/\/$/,"")}/v1`,apiKey:t.token,onRetry:yl}),model:s,label:"gateway",apiUrl:t.apiUrl}}if(n)return{client:new tt,model:"mock-model",label:"local mock"};if(!t.token){if(e.prompt)throw new we(401,"Not logged in \u2014 run `forge login` to authenticate.",{});return{client:{chat:async()=>{throw new we(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.",w.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 ae("/v1/models")).data.filter(i=>i.provider!=="mock"&&i.id!==n);return r.sort((i,c)=>c.multiplier-i.multiplier),r[0]?.id??null}function Br(e,t,n,o=!1){return async s=>{if(!process.stdin.isTTY)return o?!0:(console.error(S(` (not a terminal) refusing: ${s.reason} \u2014 rerun with --yolo to auto-approve`)),!1);t?.();let r=e??xt.createInterface({input:process.stdin,output:process.stdout}),i=s.always===null?"":` / [a]lways for ${s.always??s.name} this run`,c=(await r.question(`
183
+ ? Allow ${s.reason}
184
+ [y]es / [n]o${i}: `)).trim().toLowerCase();return e||r.close(),n?.(),i&&(c==="a"||c==="always")?"always":c==="y"||c==="yes"}}async function Wr(e,t){if(!process.stdin.isTTY)return;let n=t??xt.createInterface({input:process.stdin,output:process.stdout});try{if(!(await n.question(`
185
+ 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 jt(e,o);console.log(l("cli.run.saved_to_0","Saved to {0}",Ye.relative(e,s)))}finally{t||n.close()}}async function bl(e,t,n){if(!n||!process.stdin.isTTY)return!1;let o=e??xt.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(`
146
186
  ${s}. Save as a project skill?
147
187
  \u201C${n.rule}\u201D
148
- [y]es / [n]o / [e]dit: `)).trim().toLowerCase(),a=n.rule;if(r.startsWith("e"))a=(await o.question("Skill text: ")).trim();else if(!r.startsWith("y"))return!1;if(!a)return!1;try{let c=await rt(t,a);return console.log(c.added?`Saved to ${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 oo(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 to(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 Ao(t,eo.homedir())+`
188
+ [y]es / [n]o / [e]dit: `)).trim().toLowerCase(),i=n.rule;if(r.startsWith("e"))i=(await o.question("Skill text: ")).trim();else if(!r.startsWith("y"))return!1;if(!i)return!1;try{let c=await wt(t,i);return console.log(c.added?`Saved to ${Ye.relative(t,c.file)} \u2014 applies from your next message.`:"Already saved."),c.added}catch(c){return console.error(l("cli.run.could_not_save_0","could not save: {0}",c instanceof Error?c.message:c)),!1}}finally{e||o.close()}}async function Eo(e){if(e.effort&&!["low","high"].includes(e.effort))throw new Error(l("cli.run.effort_must_be_low_or",'--effort must be "low" or "high", not "{0}"',e.effort));let t=process.cwd();await Jo(t);let{client:n,model:o,label:s,apiUrl:r}=await So(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 i=e.outputFormat==="json"||e.outputFormat==="stream-json",c=i?console.error:console.log,u=async()=>await ds(t,vo.homedir())+`
149
189
 
150
- ${No}`+(e.appendSystemPrompt?`
190
+ ${ms}`+(e.appendSystemPrompt?`
151
191
 
152
- ${e.appendSystemPrompt}`:""),u=[{role:"system",content:await d()}],g={root:t,allowAll:e.allowAll},h=e.maxSteps??0,y=e.maxTokens??0,x=null;(e.cascade||e.effort==="high"&&!e.model)&&(x=await no(e,s,o),(!x||x===o)&&(console.error(v(`no stronger model available${s==="gateway"?" on your plan":" (pass --escalate-to <id>)"}; using ${o}.`)),x=null));let L=e.effort==="high"&&!e.model&&x?x:o,W=await kt(t,eo.homedir());W.untrusted.length&&console.error(v(`mcp: ${W.untrusted.length} project server(s) in ${_.dirName}/mcp.json not started (untrusted). Review the file, then run \`${_.bin} mcp trust\`.`));let X=await at.fromConfig(W,t);process.on("exit",()=>X.close());for(let[S,p]of X.errors)console.error(v(`mcp: server "${S}" unavailable: ${p}`));X.tools.length&&c(v(`mcp: ${X.tools.length} tool(s) from ${X.serverCount} server(s) (each call asks for approval)`));let ie=await yt(t,eo.homedir());ie.untrusted.length&&console.error(v(`hooks: ${ie.untrusted.length} project hook(s) in ${_.dirName}/hooks.json not run (untrusted). Review the file, then run \`${_.bin} hooks trust\`.`));let N=!!e.plan,de=await He(t),Z=(await Ne(t)).length,ut=new Zt(de),Rt=zs(null),ne=0,oe=wn(),Fe,Et=Date.now(),Mt=L,mt=async()=>{u.length<=1||await Us(t,{id:oe,title:Fe??St(u.slice(1)),model:Mt,createdAt:Et,updatedAt:Date.now(),messages:u.slice(1)}).catch(()=>{})},ro=async S=>{let p=dt.createInterface({input:process.stdin,output:process.stdout});try{return(await p.question(S)).trim()}finally{p.close()}},io=S=>{u.length=1,u.push(...S.messages),oe=S.id,Fe=S.title,Et=S.createdAt,ne=S.messages.filter(p=>p.role==="user").length},ao=async()=>{let S=(await Zn(t)).filter(J=>J.id!==oe).slice(0,15);if(!S.length)return console.log(v(`
192
+ ${e.appendSystemPrompt}`:""),d=[{role:"system",content:await u()}],p={root:t,allowAll:e.allowAll},g=e.maxSteps??0,k=e.maxTokens??0,b=null;(e.cascade||e.effort==="high"&&!e.model)&&(b=await To(e,s,o),(!b||b===o)&&(console.error(S(`no stronger model available${s==="gateway"?" on your plan":" (pass --escalate-to <id>)"}; using ${o}.`)),b=null));let _=e.effort==="high"&&!e.model&&b?b:o,x=await Nt(t,vo.homedir());x.untrusted.length&&console.error(S(`mcp: ${x.untrusted.length} project server(s) in ${w.dirName}/mcp.json not started (untrusted). Review the file, then run \`${w.bin} mcp trust\`.`));let W=await yt.fromConfig(x,t);process.on("exit",()=>W.close());for(let[M,f]of W.errors)console.error(S(`mcp: server "${M}" unavailable: ${f}`));W.tools.length&&c(S(`mcp: ${W.tools.length} tool(s) from ${W.serverCount} server(s) (each call asks for approval)`));let ne=await It(t,vo.homedir());ne.untrusted.length&&console.error(S(`hooks: ${ne.untrusted.length} project hook(s) in ${w.dirName}/hooks.json not run (untrusted). Review the file, then run \`${w.bin} hooks trust\`.`));let j=!!e.plan,de=await nt(t),G=(await ze(t)).length,fe=new pn(de),N=Br(null,void 0,void 0,!!e.yolo),Y=0,q=An(),L,se=Date.now(),re=_,Ie=async()=>{d.length<=1||await Nr(t,{id:q,title:L??Dt(d.slice(1)),model:re,createdAt:se,updatedAt:Date.now(),messages:d.slice(1)}).catch(()=>{})},je=async M=>{let f=xt.createInterface({input:process.stdin,output:process.stdout});try{return(await f.question(M)).trim()}finally{f.close()}},Oe=M=>{d.length=1,d.push(...M.messages),q=M.id,L=M.title,se=M.createdAt,Y=M.messages.filter(f=>f.role==="user").length},Mo=async()=>{let M=(await xo(t)).filter(Q=>Q.id!==q).slice(0,15);if(!M.length)return console.log(S(`
153
193
  No previous sessions for this project.
154
194
  `)),null;console.log(l("cli.run.0_sessions_for_this_project",`
155
- {0}Sessions for this project:{1}`,i.bold,i.reset)),S.forEach((J,K)=>console.log(` ${String(K+1).padStart(2)}. ${J.title} ${v(`${J.turns} turn(s) \xB7 ${J.model} \xB7 ${bn(J.updatedAt)} \xB7 ${J.id}`)}`));let p=Number.parseInt(await ro(`
156
- Resume which? (number, Enter to cancel): `),10);return p>=1&&p<=S.length?S[p-1].id:null};if(e.continue||e.resume){let S=e.resume===!0&&process.stdin.isTTY?await ao()??void 0:e.resume===!0?void 0:e.resume,p=e.resume===!0&&!S?null:await Qn(t,S);p?(io(p),console.error(v(`resumed "${p.title}" (${p.messages.filter(J=>J.role==="user").length} turn(s), ${bn(p.updatedAt)})`))):console.error(v(e.continue||e.resume!==!0?"no matching previous session; starting fresh.":"starting fresh."))}let be=null,lo=async()=>{if(be)return be;if(be=new Map,s==="gateway")try{for(let S of(await ee("/v1/models")).data)be.set(S.id,!!S.vision)}catch{}return be},co=async S=>(await lo()).get(S)??!1,xe=[],uo=0,Qs=15e3,kn=async()=>{if(xe.length>0&&Date.now()-uo<Qs)return xe;try{if((await ce()).token){let K=await ee("/v1/models");if(Array.isArray(K.data)&&K.data.length>0)return xe=K.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":""}`})),uo=Date.now(),be=null,xe}}catch{}let S=[],p=[{id:"mock-model",provider:"mock",description:"offline test mock"}];for(let J of p)S.some(K=>K.id===J.id)||S.push(J);return xe=S,xe},Ct={queue:[],draft:""},Pt=async(S,p=L,J=N)=>{let K=je.splice(0),m=await ms(t,K.length?`${S} ${K.map(T=>`"${T}"`).join(" ")}`:S);for(let T of m.errors)console.error(`\x1B[33m\u26A0 ${T}\x1B[0m`);let w=m.images,k="";if(w.length)if(await co(p))c(v(`\u{1F4CE} ${w.map((T,C)=>`#${C+1} ${T.name} (${Math.round(T.data.length*.75/1024)} KB)`).join(", ")}`));else{let T=[...await lo()].filter(([,C])=>C).map(([C])=>C).slice(0,5);console.error(l("cli.run.0_can_t_read_images","\x1B[33m\u26A0 {0} can't read images, so {1} image(s) were not sent.{2}\x1B[0m",p,w.length,T.length?` Try: /model ${T[0]} (vision models: ${T.join(", ")})`:" Switch to a vision-capable model with /model <id>.")),k=`
157
- (${w.length} image(s) were attached, but this model cannot view images.)`,w=[]}let B=await Io(t,m.text+k),z=!u.some(T=>T.role==="user");u.push({role:"user",content:z?await jo(t,B):B,...w.length?{images:w}:{}});let U=new AbortController,f=new an(()=>{U.abort()},Ct),b=T=>{if(a){e.outputFormat==="stream-json"&&console.log(JSON.stringify(T));return}if(T.type!=="token"){if(f.clear(),T.type==="tool_start"){let C=T.name==="run_shell"?"Running command":T.name==="read_file"||T.name==="list_dir"?"Reading files":T.name==="edit_file"||T.name==="write_file"?"Editing file":T.name.replace(/_/g," ");f.setStatus(`${C}\u2026`)}else T.type==="tool_result"&&f.setStatus(rn());Ui(T),f.draw()}},se=zs(null,()=>f.suspend(),()=>f.resume());try{!e.prompt&&process.stdout.isTTY&&f.start();let T={messages:u,ctx:g,yolo:e.yolo,approve:se,onEvent:b,maxSteps:h,maxRunTokens:y,signal:U.signal,mcp:X,hooks:ie,plan:J,stream:!0},C=e.verify?async()=>{let P=await Ze("run_shell",{command:e.verify},g).catch(Nt=>`exit code: 1
158
- ${Nt.message}`);return{ok:/^exit code: 0\b/.test(P),detail:P.split(`
159
- `).slice(1).join(" ").trim()}}:void 0,A=p==="mock-model"&&s!=="gateway"?new qe:n,R=e.cascade&&x&&e.effort!=="high"?await rs({...T,cheap:{client:A,model:p},strong:{client:n,model:x},verify:C}):await nt({...T,client:A,model:p});f.stop();let ae=f.getElapsedSec();if(R.stopReason==="interrupted")return console.log(l("cli.run.0_1_esc_2_3",`
195
+ {0}Sessions for this project:{1}`,a.bold,a.reset)),M.forEach((Q,ee)=>console.log(` ${String(ee+1).padStart(2)}. ${Q.title} ${S(`${Q.turns} turn(s) \xB7 ${Q.model} \xB7 ${Pn(Q.updatedAt)} \xB7 ${Q.id}`)}`));let f=Number.parseInt(await je(`
196
+ Resume which? (number, Enter to cancel): `),10);return f>=1&&f<=M.length?M[f-1].id:null};if(e.continue||e.resume){let M=e.resume===!0&&process.stdin.isTTY?await Mo()??void 0:e.resume===!0?void 0:e.resume,f=e.resume===!0&&!M?null:await $o(t,M);f?(Oe(f),console.error(S(`resumed "${f.title}" (${f.messages.filter(Q=>Q.role==="user").length} turn(s), ${Pn(f.updatedAt)})`))):console.error(S(e.continue||e.resume!==!0?"no matching previous session; starting fresh.":"starting fresh."))}let Re=null,Ao=async()=>{if(Re)return Re;if(Re=new Map,s==="gateway")try{for(let M of(await ae("/v1/models")).data)Re.set(M.id,!!M.vision)}catch{}return Re},jn=async M=>(await Ao()).get(M)??!1,Me=[],Co=0,Yr=15e3,On=async()=>{if(Me.length>0&&Date.now()-Co<Yr)return Me;try{if((await _e()).token){let ee=await ae("/v1/models");if(Array.isArray(ee.data)&&ee.data.length>0)return Me=ee.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(),Re=null,Me}}catch{}let M=[],f=[{id:"mock-model",provider:"mock",description:"offline test mock"}];for(let Q of f)M.some(ee=>ee.id===Q.id)||M.push(Q);return Me=M,Me},Bt={queue:[],draft:""},Wt=async(M,f=_,Q=j)=>{let ee=Ke.splice(0),m=await js(t,ee.length?`${M} ${ee.map(A=>`"${A}"`).join(" ")}`:M);for(let A of m.errors)console.error(`\x1B[33m\u26A0 ${A}\x1B[0m`);let y=m.images,v="";if(y.length)if(await jn(f))c(S(`\u{1F4CE} ${y.map((A,I)=>`#${I+1} ${A.name} (${Math.round(A.data.length*.75/1024)} KB)`).join(", ")}`));else{let A=[...await Ao()].filter(([,I])=>I).map(([I])=>I).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",f,y.length,A.length?` Try: /model ${A[0]} (vision models: ${A.join(", ")})`:" Switch to a vision-capable model with /model <id>.")),v=`
197
+ (${y.length} image(s) were attached, but this model cannot view images.)`,y=[]}let K=await gs(t,m.text+v),V=!d.some(A=>A.role==="user");d.push({role:"user",content:V?await ps(t,K):K,...y.length?{images:y}:{}});let z=new AbortController,h=new bn(()=>{z.abort()},Bt),$=A=>{if(i){e.outputFormat==="stream-json"&&console.log(JSON.stringify(A));return}if(A.type!=="token"){if(h.clear(),A.type==="tool_start"){let I=A.name==="run_shell"?"Running command":A.name==="read_file"||A.name==="list_dir"?"Reading files":A.name==="edit_file"||A.name==="write_file"?"Editing file":A.name.replace(/_/g," ");h.setStatus(`${I}\u2026`)}else A.type==="tool_result"&&h.setStatus(yn());_l(A),h.draw()}},me=Br(null,()=>h.suspend(),()=>h.resume(),!!e.yolo);try{!e.prompt&&process.stdout.isTTY&&h.start();let A={messages:d,ctx:p,yolo:e.yolo,approve:me,onEvent:$,maxSteps:g,maxRunTokens:k,signal:z.signal,mcp:W,hooks:ne,plan:Q,stream:!0},I=e.verify?async()=>{let ye=await dt("run_shell",{command:e.verify},p).catch(D=>`exit code: 1
198
+ ${D.message}`);return{ok:/^exit code: 0\b/.test(ye),detail:ye.split(`
199
+ `).slice(1).join(" ").trim()}}:void 0,O=f==="mock-model"&&s!=="gateway"?new tt:n,R=e.cascade&&b&&e.effort!=="high"?await tr({...A,cheap:{client:O,model:f},strong:{client:n,model:b},verify:I}):await et({...A,client:O,model:f,vision:await jn(f)});h.stop();let he=h.getElapsedSec();if(R.stopReason==="interrupted")return console.log(l("cli.run.0_1_esc_2_3",`
160
200
  {0}{1}esc{2} {3}Interrupted by user{4}
161
- `,i.bold,i.gray,i.reset,i.dim,i.reset)),!1;if(a){let P=R.stopReason==="done"&&R.toolErrors===0;return console.log(JSON.stringify({type:"result",ok:P,stopReason:R.stopReason,result:R.finalText,model:p,sessionId:oe,usage:R.usage,changedFiles:R.changedFiles})),P||(process.exitCode=1),P}let me=R.changedFiles.length?` \xB7 changed: ${R.changedFiles.join(", ")}`:"",pt=R.cachedReads?` \xB7 ${R.cachedReads} repeat read(s) skipped`:"",ke="finalModel"in R&&R.escalated?`${p} \u2192 ${R.finalModel}`:p,vn=(R.usage?.promptTokens??0)+(R.usage?.completionTokens??0),gt=ln(vn),ft=`${v(`[${ke}]`)} ${i.tokenBlue}${gt}${i.reset}${v(`${me}${pt}`)}`;console.log(l("cli.run.0_worked_for_1_s",`
201
+ `,a.bold,a.gray,a.reset,a.dim,a.reset)),!1;if(i){let ye=R.stopReason==="done"&&R.toolErrors===0;return console.log(JSON.stringify({type:"result",ok:ye,stopReason:R.stopReason,result:R.finalText,model:f,sessionId:q,usage:R.usage,changedFiles:R.changedFiles})),ye||(process.exitCode=1),ye}let xe=R.changedFiles.length?` \xB7 changed: ${R.changedFiles.join(", ")}`:"",$t=R.cachedReads?` \xB7 ${R.cachedReads} repeat read(s) skipped`:"",Ae="finalModel"in R&&R.escalated?`${f} \u2192 ${R.finalModel}`:f,Ln=hr(R.usage?.promptTokens??0,R.usage?.completionTokens??0,R.usage?.cacheReadTokens??0),vt=`${S(`[${Ae}]`)} ${a.tokenBlue}${Ln}${a.reset}${S(`${xe}${$t}`)}`;console.log(l("cli.run.0_worked_for_1_s",`
162
202
  {0}\u2713 Done in {1}s{2}
163
- {3}`,i.workedPrefix,ae,i.reset,ft));let Se=Yo(R,y);return Se&&console.log(`\x1B[33m${Se}\x1B[0m`),R.stopReason==="done"&&R.toolErrors===0}catch(T){return f.stop(),U.signal.aborted?(console.log(l("cli.run.0_1_esc_2_3_2",`
203
+ {3}`,a.workedPrefix,he,a.reset,vt));let at=Ks(R,k);return at&&console.log(`\x1B[33m${at}\x1B[0m`),R.stopReason==="done"&&R.toolErrors===0}catch(A){return h.stop(),z.signal.aborted?(console.log(l("cli.run.0_1_esc_2_3_2",`
164
204
  {0}{1}esc{2} {3}Interrupted by user{4}
165
- `,i.bold,i.gray,i.reset,i.dim,i.reset)),!1):(a?console.log(JSON.stringify({type:"result",ok:!1,error:Ie(T,r),sessionId:oe})):console.error(l("cli.run.error_0",`
205
+ `,a.bold,a.gray,a.reset,a.dim,a.reset)),!1):(i?console.log(JSON.stringify({type:"result",ok:!1,error:Ge(A,r),sessionId:q})):console.error(l("cli.run.error_0",`
166
206
  error: {0}
167
- `,Ie(T,r))),process.exitCode=1,!1)}finally{f.stop(),Mt=p,await mt()}};(de.length||Z)&&c(v(`using ${de.length} skill(s) and ${Z} memory note(s) from ${_.dirName}/`));async function er(S,p){if(!!!(process.stdin.isTTY&&process.stdout.isTTY)){let K=dt.createInterface({input:process.stdin,output:process.stdout});try{return(await K.question("\u203A ")).trim()}finally{K.close()}}return new Promise(K=>{let m="\x1B[2m",w="\x1B[0m",k="\x1B[38;2;255;179;71m",B=()=>Math.max(process.stdout.columns||80,20),z=()=>"\u2500".repeat(B()),U=()=>`? for shortcuts \xB7 ${k}taste on${w}${je.length?` \xB7 ${k}\u{1F4CE} ${je.length} image(s) attached${w}`:""}`,f=Ct.draft;Ct.draft="";let b=f.length,se=p.length,T="",C=!1,A=0,R=0,ae=2,me=!1,pt=0;process.stdout.write(`\x1B[38;2;255;122;61m\u276F\x1B[0m ${m}Ask ${_.name} anything\u2026${w}
168
- `),process.stdout.write(`${m}${z()}${w}
169
- `),process.stdout.write(`${U()}`),process.stdout.write("\x1B[2A\x1B[3G"),f&&setImmediate(()=>P());let ke=process.stdin,vn=ke.isRaw;ke.setRawMode(!0),ke.resume();let gt=()=>{ke.removeListener("data",mo),process.stdout.removeListener("resize",Nt),ke.setRawMode&&ke.setRawMode(vn)},ft=Te=>{gt();for(let ue=0;ue<ae;ue++)process.stdout.write(`
170
- \x1B[2K`);ae>0&&process.stdout.write(`\x1B[${ae}A`),process.stdout.write("\x1B[2K\r");let $=Te.trim();$&&!$.startsWith("/")&&$!=="?"&&process.stdout.write(`
171
- ${i.userMsgBg} ${i.userPointer}${i.bold}\u276F${i.reset}${i.userMsgBg} ${i.userFg}${$} ${i.reset}
172
-
173
- `),K($)},Se=Te=>{let $=xe.length>0?xe:[{id:"mock-model",provider:"mock",description:"offline test mock"}],ue=Te.trim().toLowerCase();return $.filter(H=>ue?H.id.toLowerCase().includes(ue):!0).map(H=>{let F=H.id===I,q=F?`\u2713 ${H.id}`:H.id,V=`${F?"(active) ":""}${H.description||"model"}`;return{command:`/model ${H.id}`,displayCommand:q,description:V}})},P=()=>{let Te=B(),$=Math.max(10,Te-8),ue=f,j=ye(f.slice(0,b));if(!f)ue=`${m}Ask ${_.name} anything\u2026${w}`,j=0;else if(ye(f)>$){let Q=Je(f),Ye=Je(f.slice(0,b)).length,Re=0;for(;Re<Ye&&ye(Q.slice(Re,Ye).join(""))>=$;)Re++;let pe="";for(let fe=Re;fe<Q.length&&ye(pe+Q[fe])<=$;fe++)pe+=Q[fe];ue=pe,j=ye(Q.slice(Re,Ye).join(""))}let H=Ke(f),F=H.showMenu&&!C,q=F?lt(H.query):[],V=(f.startsWith("/model ")||f.startsWith("/model:"))&&!C,De=V?f.replace(/^\/model[:\s]*/,"").trim().toLowerCase():"",jt=V?Se(De):[],$e=F&&q.length>0||V&&jt.length>0,te=V?jt:q;te.length>0&&(A>=te.length&&(A=Math.max(0,te.length-1)),A<0&&(A=0),A<R&&(R=A),A>=R+8&&(R=Math.max(0,A-8+1)));let Y=[];if($e&&te.length>0){Y.push(`\x1B[38;2;90;66;50m${z()}\x1B[0m`);let Q=te.slice(R,R+8),Ye=Math.min(38,Math.max(...Q.map(pe=>ye(pe.displayCommand??pe.command)),18)),Re=Math.max(10,Te-Ye-4);for(let pe=0;pe<Q.length;pe++){let fe=Q[pe],or=R+pe===A,po=(fe.displayCommand??fe.command).padEnd(Ye),go=fe.description.length>Re?fe.description.slice(0,Re-1)+"\u2026":fe.description;or?Y.push(`${i.accent}${i.bold}${po}${i.reset} ${i.accent}${go}${i.reset}`):Y.push(`${i.bannerText}${po}${i.reset} ${i.gray}${go}${i.reset}`)}}else if(me||f.trim()==="?"){Y.push("");for(let Q of Yn())Y.push(Q);Y.push(""),Y.push(`${m}${z()}${w}`),Y.push(`${U()}`)}else Y.push(`${m}${z()}${w}`),Y.push(`${U()}`);process.stdout.write(`\x1B[1G\x1B[2K\x1B[38;2;255;122;61m\u276F\x1B[0m ${ue}`);for(let Q of Y)process.stdout.write(`
174
- \x1B[2K${Q}`);let ht=Math.max(0,ae-Y.length);for(let Q=0;Q<ht;Q++)process.stdout.write(`
175
- \x1B[2K`);let It=Y.length+ht;It>0&&process.stdout.write(`\x1B[${It}A`),process.stdout.write(`\x1B[${3+j}G`),ae=Y.length},Nt=()=>{P()};process.stdout.on("resize",Nt);let nr=new Di("utf8"),mo=Te=>{let $=nr.write(Te);if(!$)return;if($==="\r"||$===`
176
- `||$.endsWith("\r")||$.endsWith(`
177
- `)){if(f.endsWith("\\")){f=f.slice(0,-1)+`
178
- `,b=f.length,me=!1,P();return}me=!1;let j=$.replace(/[\r\n]+$/,"");if(j&&(f=f.slice(0,b)+j+f.slice(b),b+=j.length,C=!1,A=0),(f.startsWith("/model ")||f.startsWith("/model:"))&&!C){let q=Se(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(q.length>0){let V=q[A]??q[0];ft(V.command);return}}let F=Ke(f);if(F.showMenu&&!C){let q=lt(F.query);if(q.length>0){let V=q[A]??q[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)){ft(V.command);return}else{f=V.command+" ",b=f.length,C=!1,A=0,R=0,P();return}}}ft(f);return}if($===" "){if((f.startsWith("/model ")||f.startsWith("/model:"))&&!C){let F=Se(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(F.length>0){f=(F[A]??F[0]).command,b=f.length,C=!0,P();return}}let H=Ke(f);if(H.showMenu&&!C){let F=lt(H.query);if(F.length>0){f=(F[A]??F[0]).command+" ",b=f.length,C=!1,A=0,R=0,P();return}}else{let F=f.slice(0,b),q=F.match(/@([a-zA-Z0-9_\-\.\/]*)$/);if(q){let V=q[1],De=F.lastIndexOf("@");$s(t).then(jt=>{let $e=jt.filter(te=>te.startsWith(V));if($e.length===1){let te=$e[0]+($e[0].endsWith("/")?"":" ");f=f.slice(0,De+1)+te+f.slice(b),b=De+1+te.length,P()}else if($e.length>1){let te=V;for(let Y=V.length+1;Y<=$e[0].length;Y++){let ht=$e[0].slice(0,Y);if($e.every(It=>It.startsWith(ht)))te=ht;else break}te.length>V.length&&(f=f.slice(0,De+1)+te+f.slice(b),b=De+1+te.length,P())}}).catch(()=>{});return}}return}if($===""){if(f.length>0){f="",b=0,C=!1,A=0,R=0,P();return}gt();for(let j=0;j<ae;j++)process.stdout.write(`
179
- \x1B[2K`);ae>0&&process.stdout.write(`\x1B[${ae}A`),process.stdout.write(`\x1B[2K\r
180
- `),process.exit(0);return}if($===""&&!f){gt();for(let j=0;j<ae;j++)process.stdout.write(`
181
- \x1B[2K`);ae>0&&process.stdout.write(`\x1B[${ae}A`),process.stdout.write(`\x1B[2K\r
182
- `),process.exit(0);return}if($==="\x7F"||$==="\b"){if(b>0){let j=cn(f,b);f=f.slice(0,j)+f.slice(b),b=j,C=!1,A=0,R=0,P()}return}if($==="\x1B"){if(me){me=!1,P();return}let j=(f.startsWith("/model ")||f.startsWith("/model:"))&&!C,H=Ke(f);if((j||H.showMenu)&&!C){C=!0,P();return}let F=Date.now();if(F-pt<400&&f.length>0){f="",b=0,me=!1,P(),pt=0;return}pt=F;return}if($.startsWith("\x1B")){if($==="\x1B[D")b>0&&(b=cn(f,b),P());else if($==="\x1B[C")b<f.length&&(b=Kn(f,b),P());else if($==="\x1B[A"){let j=Ke(f),H=j.showMenu&&!C;if(((f.startsWith("/model ")||f.startsWith("/model:"))&&!C?Se(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):H?lt(j.query):[]).length>0){A=Math.max(0,A-1),A<R&&(R=A),P();return}p.length>0&&se>0&&(se===p.length&&(T=f),se--,f=p[se],b=f.length,C=!0,P())}else if($==="\x1B[B"){let j=Ke(f),H=j.showMenu&&!C,q=(f.startsWith("/model ")||f.startsWith("/model:"))&&!C?Se(f.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):H?lt(j.query):[];if(q.length>0){A=Math.min(q.length-1,A+1),A>=R+8&&(R=Math.max(0,A-8+1)),P();return}se<p.length&&(se++,f=se===p.length?T:p[se],b=f.length,C=!0,P())}else $==="\x1B[H"||$==="\x1B[1~"||$===""?(b=0,P()):$==="\x1B[F"||$==="\x1B[4~"||$===""?(b=f.length,P()):$==="\x1B[3~"&&b<f.length&&(f=f.slice(0,b)+f.slice(Kn(f,b)),P());return}if($===""){b=0,P();return}if($===""){b=f.length,P();return}if($===""){Xn().then(j=>{j&&je.push(j),P()});return}if($.charCodeAt(0)<32&&$!==" ")return;if($==="?"&&!f){me=!me,P();return}me=!1;let ue=$.replace(/\r?\n/g," ");f=f.slice(0,b)+ue+f.slice(b),b+=ue.length,C=!1,A=0,R=0,P()};ke.on("data",mo)})}if(e.prompt){await Pt(e.prompt,L)&&await Gs(t,null);return}let $n=de.length+Z,I=L,At=[];await kn().catch(()=>{});let tr=s==="not logged in"?`${I} (not logged in)`:I;for(Jn(tr,$n,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}
183
- `);;){let S=Ct.queue.shift();S&&!S.startsWith("/")&&console.log(`
184
- ${i.userMsgBg} ${i.userPointer}${i.bold}\u276F${i.reset}${i.userMsgBg} ${i.userFg}${S} ${i.reset}
185
- `),S||await Promise.race([kn().catch(()=>{}),new Promise(m=>setTimeout(m,1500))]);let p=S??await er($n,At);if(!p)continue;if(At[At.length-1]!==p&&At.push(p),p==="/exit"||p==="/quit")break;if(p==="/clear"||p==="/new"){u.length=0,u.push({role:"system",content:await d()}),ne=0,oe=wn(),Fe=void 0,Et=Date.now(),console.clear(),Jn(I,$n,t),console.log(l("cli.run.0_new_session_started_1",`{0}\u2713 New session started.{1}
186
- `,i.assistantPrefix,i.reset));continue}if(p==="?"||p==="/shortcuts"||p==="/hotkeys"){Vn();continue}if(p==="/help"){xs();continue}if(p==="/taste"){let m=await He(t),w=await Ne(t);console.log(l("cli.run.0_taste_learning_status_1",`
187
- {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
188
- `,w.length));continue}if(p.startsWith("/skills")){let m=p.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();if(w){let k=await rt(t,w);console.log(`
189
- ${k.added?`\u2713 Added skill: "${k.skill}"`:"Skill already exists."}
190
- `)}}else{let w=await He(t);console.log(l("cli.run.0_project_skills_forge_skills",`
191
- {0}Project Skills (.forge/skills.md):{1}`,i.bold,i.reset)),w.length?w.forEach((k,B)=>console.log(` ${B+1}. ${k}`)):console.log(l("cli.run.0_no_skills_yet_add",' {0}(No skills yet. Add one with: /skills add "Prefer pnpm"){1}',i.dim,i.reset)),console.log("")}continue}if(p.startsWith("/memory")){let m=p.slice(7).trim();if(m.startsWith("add ")){let w=m.slice(4).trim();w&&(await bt(t,w),console.log(l("cli.run.saved_to_forge_memory_md",`
207
+ `,Ge(A,r))),process.exitCode=1,!1)}finally{h.stop(),re=f,await Ie()}};(de.length||G)&&c(S(`using ${de.length} skill(s) and ${G} memory note(s) from ${w.dirName}/`));async function Xr(M,f){if(!!!(process.stdin.isTTY&&process.stdout.isTTY)){let ee=xt.createInterface({input:process.stdin,output:process.stdout});try{return(await ee.question("\u203A ")).trim()}finally{ee.close()}}return new Promise(ee=>{let m="\x1B[2m",y="\x1B[0m",v="\x1B[38;2;255;179;71m",K=()=>Math.max(process.stdout.columns||80,20),V=()=>"\u2500".repeat(K()),z=()=>`? for shortcuts \xB7 ${v}taste on${y}${Ke.length?` \xB7 ${v}\u{1F4CE} ${Ke.length} image(s) attached${y}`:""}`,h=Bt.draft;Bt.draft="";let $=h.length,me=f.length,A="",I=!1,O=0,R=0,he=2,xe=!1,$t=0;process.stdout.write(`\x1B[38;2;255;122;61m\u276F\x1B[0m ${m}Ask ${w.name} anything\u2026${y}
208
+ `),process.stdout.write(`${m}${V()}${y}
209
+ `),process.stdout.write(`${z()}`),process.stdout.write("\x1B[2A\x1B[3G"),h&&setImmediate(()=>D());let Ae=process.stdin,Ln=Ae.isRaw;Ae.setRawMode(!0),Ae.resume();let vt=()=>{Ae.removeListener("data",Io),process.stdout.removeListener("resize",Po),Ae.setRawMode&&Ae.setRawMode(Ln)},at=Ne=>{vt();for(let be=0;be<he;be++)process.stdout.write(`
210
+ \x1B[2K`);he>0&&process.stdout.write(`\x1B[${he}A`),process.stdout.write("\x1B[2K\r");let T=Ne.trim();T&&!T.startsWith("/")&&T!=="?"&&process.stdout.write(`
211
+ ${a.userMsgBg} ${a.userPointer}${a.bold}\u276F${a.reset}${a.userMsgBg} ${a.userFg}${T} ${a.reset}
212
+
213
+ `),ee(T)},ye=Ne=>{let T=Me.length>0?Me:[{id:"mock-model",provider:"mock",description:"offline test mock"}],be=Ne.trim().toLowerCase();return T.filter(X=>be?X.id.toLowerCase().includes(be):!0).map(X=>{let H=X.id===B,J=H?`\u2713 ${X.id}`:X.id,oe=`${H?"(active) ":""}${X.description||"model"}`;return{command:`/model ${X.id}`,displayCommand:J,description:oe}})},D=()=>{let Ne=K(),T=Math.max(10,Ne-8),be=h,U=Ee(h.slice(0,$));if(!h)be=`${m}Ask ${w.name} anything\u2026${y}`,U=0;else if(Ee(h)>T){let ie=rt(h),lt=rt(h.slice(0,$)).length,Le=0;for(;Le<lt&&Ee(ie.slice(Le,lt).join(""))>=T;)Le++;let $e="";for(let ve=Le;ve<ie.length&&Ee($e+ie[ve])<=T;ve++)$e+=ie[ve];be=$e,U=Ee(ie.slice(Le,lt).join(""))}let X=it(h),H=X.showMenu&&!I,J=H?bt(X.query):[],oe=(h.startsWith("/model ")||h.startsWith("/model:"))&&!I,Xe=oe?h.replace(/^\/model[:\s]*/,"").trim().toLowerCase():"",Ht=oe?ye(Xe):[],Ce=H&&J.length>0||oe&&Ht.length>0,le=oe?Ht:J;le.length>0&&(O>=le.length&&(O=Math.max(0,le.length-1)),O<0&&(O=0),O<R&&(R=O),O>=R+8&&(R=Math.max(0,O-8+1)));let te=[];if(Ce&&le.length>0){te.push(`\x1B[38;2;90;66;50m${V()}\x1B[0m`);let ie=le.slice(R,R+8),lt=Math.min(38,Math.max(...ie.map($e=>Ee($e.displayCommand??$e.command)),18)),Le=Math.max(10,Ne-lt-4);for(let $e=0;$e<ie.length;$e++){let ve=ie[$e],Qr=R+$e===O,jo=(ve.displayCommand??ve.command).padEnd(lt),Oo=ve.description.length>Le?ve.description.slice(0,Le-1)+"\u2026":ve.description;Qr?te.push(`${a.accent}${a.bold}${jo}${a.reset} ${a.accent}${Oo}${a.reset}`):te.push(`${a.bannerText}${jo}${a.reset} ${a.gray}${Oo}${a.reset}`)}}else if(xe||h.trim()==="?"){te.push("");for(let ie of yo())te.push(ie);te.push(""),te.push(`${m}${V()}${y}`),te.push(`${z()}`)}else te.push(`${m}${V()}${y}`),te.push(`${z()}`);process.stdout.write(`\x1B[1G\x1B[2K\x1B[38;2;255;122;61m\u276F\x1B[0m ${be}`);for(let ie of te)process.stdout.write(`
214
+ \x1B[2K${ie}`);let St=Math.max(0,he-te.length);for(let ie=0;ie<St;ie++)process.stdout.write(`
215
+ \x1B[2K`);let zt=te.length+St;zt>0&&process.stdout.write(`\x1B[${zt}A`),process.stdout.write(`\x1B[${3+U}G`),he=te.length},Po=()=>{D()};process.stdout.on("resize",Po);let Zr=new wl("utf8"),Io=Ne=>{let T=Zr.write(Ne);if(!T)return;if(T==="\r"||T===`
216
+ `||T.endsWith("\r")||T.endsWith(`
217
+ `)){if(h.endsWith("\\")){h=h.slice(0,-1)+`
218
+ `,$=h.length,xe=!1,D();return}xe=!1;let U=T.replace(/[\r\n]+$/,"");if(U&&(h=h.slice(0,$)+U+h.slice($),$+=U.length,I=!1,O=0),(h.startsWith("/model ")||h.startsWith("/model:"))&&!I){let J=ye(h.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(J.length>0){let oe=J[O]??J[0];at(oe.command);return}}let H=it(h);if(H.showMenu&&!I){let J=bt(H.query);if(J.length>0){let oe=J[O]??J[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(oe.command)){at(oe.command);return}else{h=oe.command+" ",$=h.length,I=!1,O=0,R=0,D();return}}}at(h);return}if(T===" "){if((h.startsWith("/model ")||h.startsWith("/model:"))&&!I){let H=ye(h.replace(/^\/model[:\s]*/,"").trim().toLowerCase());if(H.length>0){h=(H[O]??H[0]).command,$=h.length,I=!0,D();return}}let X=it(h);if(X.showMenu&&!I){let H=bt(X.query);if(H.length>0){h=(H[O]??H[0]).command+" ",$=h.length,I=!1,O=0,R=0,D();return}}else{let H=h.slice(0,$),J=H.match(/@([a-zA-Z0-9_\-\.\/]*)$/);if(J){let oe=J[1],Xe=H.lastIndexOf("@");yr(t).then(Ht=>{let Ce=Ht.filter(le=>le.startsWith(oe));if(Ce.length===1){let le=Ce[0]+(Ce[0].endsWith("/")?"":" ");h=h.slice(0,Xe+1)+le+h.slice($),$=Xe+1+le.length,D()}else if(Ce.length>1){let le=oe;for(let te=oe.length+1;te<=Ce[0].length;te++){let St=Ce[0].slice(0,te);if(Ce.every(zt=>zt.startsWith(St)))le=St;else break}le.length>oe.length&&(h=h.slice(0,Xe+1)+le+h.slice($),$=Xe+1+le.length,D())}}).catch(()=>{});return}}return}if(T===""){if(h.length>0){h="",$=0,I=!1,O=0,R=0,D();return}vt();for(let U=0;U<he;U++)process.stdout.write(`
219
+ \x1B[2K`);he>0&&process.stdout.write(`\x1B[${he}A`),process.stdout.write(`\x1B[2K\r
220
+ `),process.exit(0);return}if(T===""&&!h){vt();for(let U=0;U<he;U++)process.stdout.write(`
221
+ \x1B[2K`);he>0&&process.stdout.write(`\x1B[${he}A`),process.stdout.write(`\x1B[2K\r
222
+ `),process.exit(0);return}if(T==="\x7F"||T==="\b"){if($>0){let U=kn(h,$);h=h.slice(0,U)+h.slice($),$=U,I=!1,O=0,R=0,D()}return}if(T==="\x1B"){if(xe){xe=!1,D();return}let U=(h.startsWith("/model ")||h.startsWith("/model:"))&&!I,X=it(h);if((U||X.showMenu)&&!I){I=!0,D();return}let H=Date.now();if(H-$t<400&&h.length>0){h="",$=0,xe=!1,D(),$t=0;return}$t=H;return}if(T.startsWith("\x1B")){if(T==="\x1B[D")$>0&&($=kn(h,$),D());else if(T==="\x1B[C")$<h.length&&($=_o(h,$),D());else if(T==="\x1B[A"){let U=it(h),X=U.showMenu&&!I;if(((h.startsWith("/model ")||h.startsWith("/model:"))&&!I?ye(h.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):X?bt(U.query):[]).length>0){O=Math.max(0,O-1),O<R&&(R=O),D();return}f.length>0&&me>0&&(me===f.length&&(A=h),me--,h=f[me],$=h.length,I=!0,D())}else if(T==="\x1B[B"){let U=it(h),X=U.showMenu&&!I,J=(h.startsWith("/model ")||h.startsWith("/model:"))&&!I?ye(h.replace(/^\/model[:\s]*/,"").trim().toLowerCase()):X?bt(U.query):[];if(J.length>0){O=Math.min(J.length-1,O+1),O>=R+8&&(R=Math.max(0,O-8+1)),D();return}me<f.length&&(me++,h=me===f.length?A:f[me],$=h.length,I=!0,D())}else T==="\x1B[H"||T==="\x1B[1~"||T===""?($=0,D()):T==="\x1B[F"||T==="\x1B[4~"||T===""?($=h.length,D()):T==="\x1B[3~"&&$<h.length&&(h=h.slice(0,$)+h.slice(_o(h,$)),D());return}if(T===""){$=0,D();return}if(T===""){$=h.length,D();return}if(T===""){ko().then(U=>{U&&Ke.push(U),D()});return}if(T.charCodeAt(0)<32&&T!==" ")return;if(T==="?"&&!h){xe=!xe,D();return}xe=!1;let be=T.replace(/\r?\n/g," ");h=h.slice(0,$)+be+h.slice($),$+=be.length,I=!1,O=0,R=0,D()};Ae.on("data",Io)})}if(e.prompt){await Wt(e.prompt,_)&&await Wr(t,null);return}let Nn=de.length+G,B=_,qt=[];await On().catch(()=>{});let Vr=s==="not logged in"?`${B} (not logged in)`:B;for(wo(Vr,Nn,t),s==="not logged in"&&console.log(`${a.dim} You are not logged in. Type ${a.bold}/login${a.reset}${a.dim} to authenticate.${a.reset}
223
+ `);;){let M=Bt.queue.shift();M&&!M.startsWith("/")&&console.log(`
224
+ ${a.userMsgBg} ${a.userPointer}${a.bold}\u276F${a.reset}${a.userMsgBg} ${a.userFg}${M} ${a.reset}
225
+ `),M||await Promise.race([On().catch(()=>{}),new Promise(m=>setTimeout(m,1500))]);let f=M??await Xr(Nn,qt);if(!f)continue;if(qt[qt.length-1]!==f&&qt.push(f),f==="/exit"||f==="/quit")break;if(f==="/clear"||f==="/new"){d.length=0,d.push({role:"system",content:await u()}),Y=0,q=An(),L=void 0,se=Date.now(),console.clear(),wo(B,Nn,t),console.log(l("cli.run.0_new_session_started_1",`{0}\u2713 New session started.{1}
226
+ `,a.assistantPrefix,a.reset));continue}if(f==="?"||f==="/shortcuts"||f==="/hotkeys"){bo();continue}if(f==="/help"){wr();continue}if(f==="/taste"){let m=await nt(t),y=await ze(t);console.log(l("cli.run.0_taste_learning_status_1",`
227
+ {0}Taste Learning Status:{1}`,a.bold,a.reset)),console.log(l("cli.run.status_0_on_1"," \u2022 Status: {0}ON{1}",a.cyan,a.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
228
+ `,y.length));continue}if(f.startsWith("/skills")){let m=f.slice(7).trim();if(m.startsWith("add ")){let y=m.slice(4).trim();if(y){let v=await wt(t,y);console.log(`
229
+ ${v.added?`\u2713 Added skill: "${v.skill}"`:"Skill already exists."}
230
+ `)}}else{let y=await nt(t);console.log(l("cli.run.0_project_skills_forge_skills",`
231
+ {0}Project Skills (.forge/skills.md):{1}`,a.bold,a.reset)),y.length?y.forEach((v,K)=>console.log(` ${K+1}. ${v}`)):console.log(l("cli.run.0_no_skills_yet_add",' {0}(No skills yet. Add one with: /skills add "Prefer pnpm"){1}',a.dim,a.reset)),console.log("")}continue}if(f.startsWith("/memory")){let m=f.slice(7).trim();if(m.startsWith("add ")){let y=m.slice(4).trim();y&&(await jt(t,y),console.log(l("cli.run.saved_to_forge_memory_md",`
192
232
  \u2713 Saved to .forge/memory.md: "{0}"
193
- `,w)))}else{let w=await Ne(t);console.log(l("cli.run.0_project_memory_forge_memory",`
194
- {0}Project Memory (.forge/memory.md):{1}`,i.bold,i.reset)),w.length?w.forEach((k,B)=>console.log(` ${B+1}. ${k}`)):console.log(l("cli.run.0_no_memory_notes_yet",' {0}(No memory notes yet. Add one with: /memory add "..."){1}',i.dim,i.reset)),console.log("")}continue}if(p==="/models"){console.log(""),await mn(),console.log("");continue}if(p==="/paste"||p.startsWith("/image")){let m=p.startsWith("/image")?p.slice(6).trim():"";if(m){je.push(Le.resolve(t,m.replace(/^["']|["']$/g,""))),console.log(l("cli.run.queued_0_it_goes_with",`
233
+ `,y)))}else{let y=await ze(t);console.log(l("cli.run.0_project_memory_forge_memory",`
234
+ {0}Project Memory (.forge/memory.md):{1}`,a.bold,a.reset)),y.length?y.forEach((v,K)=>console.log(` ${K+1}. ${v}`)):console.log(l("cli.run.0_no_memory_notes_yet",' {0}(No memory notes yet. Add one with: /memory add "..."){1}',a.dim,a.reset)),console.log("")}continue}if(f==="/models"){console.log(""),await vn(),console.log("");continue}if(f==="/paste"||f.startsWith("/image")){let m=f.startsWith("/image")?f.slice(6).trim():"";if(m){Ke.push(Ye.resolve(t,m.replace(/^["']|["']$/g,""))),console.log(l("cli.run.queued_0_it_goes_with",`
195
235
  \u{1F4CE} queued {0}; it goes with your next message.
196
- `,m));continue}let w=await Xn();w?(je.push(w),console.log(l("cli.run.clipboard_image_attached_0_queued",`
236
+ `,m));continue}let y=await ko();y?(Ke.push(y),console.log(l("cli.run.clipboard_image_attached_0_queued",`
197
237
  \u{1F4CE} clipboard image attached ({0} queued); it goes with your next message.
198
- `,je.length))):console.log(v(`
238
+ `,Ke.length))):console.log(S(`
199
239
  No image on the clipboard (copy or screenshot one first, e.g. Cmd+Ctrl+Shift+4 on macOS).
200
- `));continue}if(p.startsWith("/model")){let m=p.split(/\s+/);m[1]?(I=m[1],await Ge({defaultModel:I}).catch(()=>{}),console.log(l("cli.run.switched_active_model_to_0",`
240
+ `));continue}if(f.startsWith("/model")){let m=f.split(/\s+/);m[1]?(B=m[1],await st({defaultModel:B}).catch(()=>{}),console.log(l("cli.run.switched_active_model_to_0",`
201
241
  \u2713 Switched active model to: {0}{1}{2}{3}
202
- `,i.bold,I,i.reset,await co(I)?v(" [reads images]"):v(" [text only]")))):(console.log(`
203
- Active model: ${i.bold}${I}${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.
204
- `,i.cyan,i.reset,i.cyan,i.reset)));continue}if(p==="/context"){let m=et(u);if(console.log(l("cli.run.0_context_window_usage_1",`
205
- {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}",ne)),console.log(l("cli.run.estimated_tokens_0_tokens"," \u2022 Estimated tokens: ~{0} tokens",m.toLocaleString())),y>0){let w=Math.round(m/y*100);console.log(l("cli.run.budget_limit_0_tokens_1",` \u2022 Budget limit: {0} tokens ({1}% used)
206
- `,y.toLocaleString(),w))}else console.log(` \u2022 Budget limit: Unlimited
207
- `);continue}if(p==="/copy"){let m=[...u].reverse().find(w=>w.role==="assistant"&&typeof w.content=="string");if(!m||!m.content)console.log(l("cli.run.0_no_assistant_response_to",`
242
+ `,a.bold,B,a.reset,await jn(B)?S(" [reads images]"):S(" [text only]")))):(console.log(`
243
+ Active model: ${a.bold}${B}${a.reset} via ${a.cyan}${s}${a.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.
244
+ `,a.cyan,a.reset,a.cyan,a.reset)));continue}if(f==="/context"){let m=We(d);if(console.log(l("cli.run.0_context_window_usage_1",`
245
+ {0}Context Window Usage:{1}`,a.bold,a.reset)),console.log(l("cli.run.messages_in_session_0"," \u2022 Messages in session: {0}",d.length)),console.log(l("cli.run.turns_completed_0"," \u2022 Turns completed: {0}",Y)),console.log(l("cli.run.estimated_tokens_0_tokens"," \u2022 Estimated tokens: ~{0} tokens",m.toLocaleString())),k>0){let y=Math.round(m/k*100);console.log(l("cli.run.budget_limit_0_tokens_1",` \u2022 Budget limit: {0} tokens ({1}% used)
246
+ `,k.toLocaleString(),y))}else console.log(` \u2022 Budget limit: Unlimited
247
+ `);continue}if(f==="/copy"){let m=[...d].reverse().find(y=>y.role==="assistant"&&typeof y.content=="string");if(!m||!m.content)console.log(l("cli.run.0_no_assistant_response_to",`
208
248
  {0}No assistant response to copy yet.{1}
209
- `,i.dim,i.reset));else{let w=m.content;if(await ks(w))console.log(l("cli.run.0_copied_last_response_to",`
249
+ `,a.dim,a.reset));else{let y=m.content;if(await _r(y))console.log(l("cli.run.0_copied_last_response_to",`
210
250
  {0}\u2713 Copied last response to clipboard.{1}
211
- `,i.assistantPrefix,i.reset));else{let B=Le.join(t,_.dirName,"last_response.txt");await Tt.mkdir(Le.dirname(B),{recursive:!0}),await Tt.writeFile(B,w,"utf8"),console.log(l("cli.run.0_saved_last_response_to",`
251
+ `,a.assistantPrefix,a.reset));else{let K=Ye.join(t,w.dirName,"last_response.txt");await Ut.mkdir(Ye.dirname(K),{recursive:!0}),await Ut.writeFile(K,y,"utf8"),console.log(l("cli.run.0_saved_last_response_to",`
212
252
  {0}\u2713 Saved last response to {1}{2}
213
- `,i.assistantPrefix,Le.relative(t,B),i.reset))}}continue}if(p.startsWith("/export")){let m=p.includes("jsonl"),w=m?"jsonl":"md",k=`forge-session-${new Date().toISOString().replace(/[:.]/g,"-")}.${w}`,B=Le.join(t,k);if(m){let z=u.map(U=>JSON.stringify(U)).join(`
214
- `);await Tt.writeFile(B,z,"utf8")}else{let z=`# Session Transcript
253
+ `,a.assistantPrefix,Ye.relative(t,K),a.reset))}}continue}if(f.startsWith("/export")){let m=f.includes("jsonl"),y=m?"jsonl":"md",v=`forge-session-${new Date().toISOString().replace(/[:.]/g,"-")}.${y}`,K=Ye.join(t,v);if(m){let V=d.map(z=>JSON.stringify(z)).join(`
254
+ `);await Ut.writeFile(K,V,"utf8")}else{let V=`# Session Transcript
215
255
 
216
- - **Model**: ${I}
256
+ - **Model**: ${B}
217
257
  - **Date**: ${new Date().toLocaleString()}
218
258
  - **Workspace**: ${t}
219
259
 
220
260
  ---
221
261
 
222
- `;for(let U of u)U.role==="user"?z+=`### \u276F User
262
+ `;for(let z of d)z.role==="user"?V+=`### \u276F User
223
263
 
224
- ${U.content}
264
+ ${z.content}
225
265
 
226
- `:U.role==="assistant"&&U.content&&(z+=`### Assistant
266
+ `:z.role==="assistant"&&z.content&&(V+=`### Assistant
227
267
 
228
- ${U.content}
268
+ ${z.content}
229
269
 
230
- `);await Tt.writeFile(B,z,"utf8")}console.log(l("cli.run.0_exported_session_to_1",`
270
+ `);await Ut.writeFile(K,V,"utf8")}console.log(l("cli.run.0_exported_session_to_1",`
231
271
  {0}\u2713 Exported session to {1}{2}
232
- `,i.assistantPrefix,k,i.reset));continue}if(p==="/usage"){console.log(""),await pn().catch(m=>console.log(v(`could not load usage: ${m.message}`))),console.log("");continue}if(p.startsWith("/effort")){let m=p.split(/\s+/);m[1]&&["low","high"].includes(m[1])?(e.effort=m[1],console.log(l("cli.run.effort_set_to_0_1",`
272
+ `,a.assistantPrefix,v,a.reset));continue}if(f==="/usage"){console.log(""),await Sn().catch(m=>console.log(S(`could not load usage: ${m.message}`))),console.log("");continue}if(f.startsWith("/effort")){let m=f.split(/\s+/);m[1]&&["low","high"].includes(m[1])?(e.effort=m[1],console.log(l("cli.run.effort_set_to_0_1",`
233
273
  \u2713 Effort set to: {0}{1}{2}
234
- `,i.bold,e.effort,i.reset))):(e.effort=e.effort==="high"?"low":"high",console.log(l("cli.run.effort_toggled_to_0_1",`
274
+ `,a.bold,e.effort,a.reset))):(e.effort=e.effort==="high"?"low":"high",console.log(l("cli.run.effort_toggled_to_0_1",`
235
275
  \u2713 Effort toggled to: {0}{1}{2}
236
- `,i.bold,e.effort,i.reset)));continue}if(p==="/status"){console.log(l("cli.run.0_session_status_1",`
237
- {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,I,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}",ne)),console.log(l("cli.run.taste_0_skill_s_1",` \u2022 Taste: {0} skill(s), {1} memory note(s)
238
- `,de.length,Z));continue}if(p==="/init"){console.log(""),await gn(),console.log("");continue}if(p.startsWith("/theme")){let w=p.slice(6).trim().toLowerCase()==="light"?"light":"dark";console.log(l("cli.run.color_theme_0_1_2",`
276
+ `,a.bold,e.effort,a.reset)));continue}if(f==="/status"){console.log(l("cli.run.0_session_status_1",`
277
+ {0}Session Status:{1}`,a.bold,a.reset)),console.log(l("cli.run.model_0_1_2_3"," \u2022 Model: {0}{1}{2} ({3})",a.cyan,B,a.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}",Y)),console.log(l("cli.run.taste_0_skill_s_1",` \u2022 Taste: {0} skill(s), {1} memory note(s)
278
+ `,de.length,G));continue}if(f==="/init"){console.log(""),await Tn(),console.log("");continue}if(f.startsWith("/theme")){let y=f.slice(6).trim().toLowerCase()==="light"?"light":"dark";console.log(l("cli.run.color_theme_0_1_2",`
239
279
  \u2713 Color theme: {0}{1}{2}
240
- `,i.bold,w,i.reset));continue}if(p.startsWith("/language")){let m=p.slice(9).trim().toLowerCase(),w=m.includes("bn")||m.includes("\u09AC\u09BE\u0982\u09B2\u09BE")?"\u09AC\u09BE\u0982\u09B2\u09BE (Bengali)":m.includes("zh")?"\u7B80\u4F53\u4E2D\u6587 (Chinese)":"English";console.log(l("cli.run.interface_language_set_to_0",`
280
+ `,a.bold,y,a.reset));continue}if(f.startsWith("/language")){let m=f.slice(9).trim().toLowerCase(),y=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",`
241
281
  \u2713 Interface language set to: {0}{1}{2}
242
- `,i.bold,w,i.reset));continue}if(p.startsWith("/add-dir")){let m=p.slice(8).trim();if(!m)console.log(l("cli.run.0_workspace_directories_1",`
243
- {0}Workspace Directories:{1}`,i.bold,i.reset)),console.log(l("cli.run.root_0",` \u2022 Root: {0}
244
- `,t));else{let w=Le.resolve(t,m);try{(await Tt.stat(w)).isDirectory()?console.log(l("cli.run.added_directory_scope_0_1",`
282
+ `,a.bold,y,a.reset));continue}if(f.startsWith("/add-dir")){let m=f.slice(8).trim();if(!m)console.log(l("cli.run.0_workspace_directories_1",`
283
+ {0}Workspace Directories:{1}`,a.bold,a.reset)),console.log(l("cli.run.root_0",` \u2022 Root: {0}
284
+ `,t));else{let y=Ye.resolve(t,m);try{(await Ut.stat(y)).isDirectory()?console.log(l("cli.run.added_directory_scope_0_1",`
245
285
  \u2713 Added directory scope: {0}{1}{2}
246
- `,i.bold,w,i.reset)):console.log(l("cli.run.0_path_is_not_a",`
286
+ `,a.bold,y,a.reset)):console.log(l("cli.run.0_path_is_not_a",`
247
287
  {0}Path is not a directory: {1}{2}
248
- `,i.dim,w,i.reset))}catch(k){console.log(l("cli.run.0_could_not_access_directory",`
288
+ `,a.dim,y,a.reset))}catch(v){console.log(l("cli.run.0_could_not_access_directory",`
249
289
  {0}Could not access directory: {1}{2}
250
- `,i.dim,k.message,i.reset))}}continue}if(p.startsWith("/worktree")){let m=p.slice(9).trim();console.log(v(`$ git worktree ${m||"list"}`));let w=await Ze("run_shell",{command:`git worktree ${m||"list"}`},g).catch(k=>k.message);console.log(w);continue}if(p==="/agents"){console.log(l("cli.run.0_active_agent_configuration_1",`
251
- {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,I,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
252
- `));continue}if(p.startsWith("/goal")){let m=p.slice(5).trim();m==="clear"?console.log(l("cli.run.session_goal_cleared",`
290
+ `,a.dim,v.message,a.reset))}}continue}if(f.startsWith("/worktree")){let m=f.slice(9).trim();console.log(S(`$ git worktree ${m||"list"}`));let y=await dt("run_shell",{command:`git worktree ${m||"list"}`},p).catch(v=>v.message);console.log(y);continue}if(f==="/agents"){console.log(l("cli.run.0_active_agent_configuration_1",`
291
+ {0}Active Agent Configuration:{1}`,a.bold,a.reset)),console.log(l("cli.run.model_0_1_2_3_2"," \u2022 Model: {0}{1}{2} ({3})",a.cyan,B,a.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
292
+ `));continue}if(f.startsWith("/goal")){let m=f.slice(5).trim();m==="clear"?console.log(l("cli.run.session_goal_cleared",`
253
293
  \u2713 Session goal cleared.
254
294
  `)):!m||m==="status"?console.log(l("cli.run.0_session_goal_1_2",`
255
295
  {0}Session Goal:{1} {2}(No explicit goal active. Set with: /goal <objective>){3}
256
- `,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",`
296
+ `,a.bold,a.reset,a.dim,a.reset)):(d.push({role:"system",content:`CURRENT GOAL: ${m}`}),console.log(l("cli.run.set_active_session_goal_0",`
257
297
  \u2713 Set active session goal: "{0}"
258
- `,m)));continue}if(p==="/plan"){N=!N,console.log(l("cli.run.plan_mode_0_1_2",`
298
+ `,m)));continue}if(f==="/plan"){j=!j,console.log(l("cli.run.plan_mode_0_1_2",`
259
299
  \u2713 Plan mode {0}{1}{2}{3}.
260
- `,i.bold,N?"ON":"OFF",i.reset,N?" (read-only: the agent will explore and propose a plan, no edits or commands)":""));continue}if(p.startsWith("/mode")){let m=p.replace(/^\/mode:?/,"").trim();m==="accept-edits"?(e.yolo=!0,N=!1,console.log(l("cli.run.switched_to_0_accept_edits",`
300
+ `,a.bold,j?"ON":"OFF",a.reset,j?" (read-only: the agent will explore and propose a plan, no edits or commands)":""));continue}if(f.startsWith("/mode")){let m=f.replace(/^\/mode:?/,"").trim();m==="accept-edits"?(e.yolo=!0,j=!1,console.log(l("cli.run.switched_to_0_accept_edits",`
261
301
  \u2713 Switched to {0}accept-edits{1} mode (edits accepted automatically).
262
- `,i.bold,i.reset))):m==="plan"?(N=!0,console.log(l("cli.run.switched_to_0_plan_1",`
302
+ `,a.bold,a.reset))):m==="plan"?(j=!0,console.log(l("cli.run.switched_to_0_plan_1",`
263
303
  \u2713 Switched to {0}plan{1} mode (read-only reasoning).
264
- `,i.bold,i.reset))):(e.yolo=!1,N=!1,console.log(l("cli.run.switched_to_0_default_1",`
304
+ `,a.bold,a.reset))):(e.yolo=!1,j=!1,console.log(l("cli.run.switched_to_0_default_1",`
265
305
  \u2713 Switched to {0}default{1} mode (prompt before major edits).
266
- `,i.bold,i.reset)));continue}if(p.startsWith("/btw")){let m=p.slice(4).trim();if(!m)console.log(l("cli.run.usage_btw_question_ask_a",`
306
+ `,a.bold,a.reset)));continue}if(f.startsWith("/btw")){let m=f.slice(4).trim();if(!m)console.log(l("cli.run.usage_btw_question_ask_a",`
267
307
  Usage: /btw <question> (ask a quick side question that does not enter history)
268
- `));else{let w=[...u,{role:"user",content:m}];console.log(l("cli.run.0_btw_side_question_1",`
269
- {0}[btw side question]{1}`,i.gray,i.reset)),await nt({messages:w,ctx:g,yolo:!0,maxSteps:1,maxRunTokens:2e3,client:I==="mock-model"&&s!=="gateway"?new qe:n,model:I,onEvent:k=>{k.type==="assistant"&&console.log(`
270
- ${i.assistantPrefix}\u25C6${i.reset} ${k.text}
271
- `)}}).catch(k=>console.log(l("cli.run.error_0_2","error: {0}",k.message)))}continue}if(p==="/hotkeys"||p==="/shortcuts"){Vn();continue}if(p==="/changelog"){console.log(l("cli.run.0_command_code_v1_87",`
272
- {0}{2} v{3} changelog:{1}`,i.bold,i.reset,_.name,ve)),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
273
- `));continue}if(p==="/todos"){console.log(l("cli.run.0_session_todos_1",`
274
- {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}
275
- `,i.dim,i.reset));continue}if(p.startsWith("/feedback")||p.startsWith("/issue")){console.log(l("cli.run.share_feedback_or_report_an",`
308
+ `));else{let y=[...d,{role:"user",content:m}];console.log(l("cli.run.0_btw_side_question_1",`
309
+ {0}[btw side question]{1}`,a.gray,a.reset)),await et({messages:y,ctx:p,yolo:!0,maxSteps:1,maxRunTokens:2e3,client:B==="mock-model"&&s!=="gateway"?new tt:n,model:B,onEvent:v=>{v.type==="assistant"&&console.log(`
310
+ ${a.assistantPrefix}\u25C6${a.reset} ${v.text}
311
+ `)}}).catch(v=>console.log(l("cli.run.error_0_2","error: {0}",v.message)))}continue}if(f==="/hotkeys"||f==="/shortcuts"){bo();continue}if(f==="/changelog"){console.log(l("cli.run.0_command_code_v1_87",`
312
+ {0}{2} v{3} changelog:{1}`,a.bold,a.reset,w.name,Pe)),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
313
+ `));continue}if(f==="/todos"){console.log(l("cli.run.0_session_todos_1",`
314
+ {0}Session Todos:{1}`,a.bold,a.reset)),console.log(l("cli.run.0_no_pending_todos_in",` {0}(No pending todos in this session){1}
315
+ `,a.dim,a.reset));continue}if(f.startsWith("/feedback")||f.startsWith("/issue")){console.log(l("cli.run.share_feedback_or_report_an",`
276
316
  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}
277
- `,i.cyan,i.reset));continue}if(p==="/compact"||p.startsWith("/compact ")){let m=yn(u);if(m.length<2){console.log(l("cli.run.0_nothing_to_compact_yet",`
317
+ `,a.cyan,a.reset));continue}if(f==="/compact"||f.startsWith("/compact ")){let m=Cn(d);if(m.length<2){console.log(l("cli.run.0_nothing_to_compact_yet",`
278
318
  {0}Nothing to compact yet ({1} turn).{2}
279
- `,i.dim,m.length,i.reset));continue}let w=m[m.length-1],k=(f,b=1500)=>(f??"").length>b?(f??"").slice(0,b)+"\u2026":f??"",B=u.slice(1,w).map(f=>f.role==="tool"?`[tool result] ${k(f.content,400)}`:f.role==="assistant"?`assistant: ${k(f.content)}${f.tool_calls?.length?` [tools: ${f.tool_calls.map(b=>b.name).join(", ")}]`:""}`:`${f.role}: ${k(f.content)}`).join(`
280
- `).slice(-6e4),z=p.slice(8).trim(),U=et(u);console.log(v("compacting conversation\u2026"));try{let b=(await(I==="mock-model"&&s!=="gateway"?new qe:n).chat({model:I,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:`${z?`Focus especially on: ${z}
319
+ `,a.dim,m.length,a.reset));continue}let y=m[m.length-1],v=(h,$=1500)=>(h??"").length>$?(h??"").slice(0,$)+"\u2026":h??"",K=d.slice(1,y).map(h=>h.role==="tool"?`[tool result] ${v(h.content,400)}`:h.role==="assistant"?`assistant: ${v(h.content)}${h.tool_calls?.length?` [tools: ${h.tool_calls.map($=>$.name).join(", ")}]`:""}`:`${h.role}: ${v(h.content)}`).join(`
320
+ `).slice(-6e4),V=f.slice(8).trim(),z=We(d);console.log(S("compacting conversation\u2026"));try{let $=(await(B==="mock-model"&&s!=="gateway"?new tt:n).chat({model:B,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:`${V?`Focus especially on: ${V}
281
321
 
282
322
  `:""}Conversation to summarize:
283
323
 
284
- ${B}`}]})).content?.trim();if(!b)throw new Error(l("cli.run.the_model_returned_an_empty","the model returned an empty summary"));let se=u.slice(w);u.length=1,u.push({role:"user",content:`[Summary of the earlier conversation]
285
- ${b}`},{role:"assistant",content:"Understood. I have the context from that summary and will continue from here."},...se),await mt(),console.log(l("cli.run.0_conversation_compacted_1_tokens",`
324
+ ${K}`}]})).content?.trim();if(!$)throw new Error(l("cli.run.the_model_returned_an_empty","the model returned an empty summary"));let me=d.slice(y);d.length=1,d.push({role:"user",content:`[Summary of the earlier conversation]
325
+ ${$}`},{role:"assistant",content:"Understood. I have the context from that summary and will continue from here."},...me),await Ie(),console.log(l("cli.run.0_conversation_compacted_1_tokens",`
286
326
  {0}\u2713 Conversation compacted{1}
287
327
  \u2022 Tokens: ~{2} \u2192 ~{3}
288
- `,i.assistantPrefix,i.reset,U.toLocaleString(),et(u).toLocaleString()))}catch(f){console.log(l("cli.run.0_could_not_compact_1",`
328
+ `,a.assistantPrefix,a.reset,z.toLocaleString(),We(d).toLocaleString()))}catch(h){console.log(l("cli.run.0_could_not_compact_1",`
289
329
  {0}Could not compact: {1}{2}
290
- `,i.dim,Ie(f,r),i.reset))}continue}if(p==="/resume"||p==="/sessions"||p.startsWith("/resume ")){let m=p.startsWith("/resume ")?p.slice(8).trim():await ao(),w=m?await Qn(t,m):null;if(!w){m&&console.log(v(`
330
+ `,a.dim,Ge(h,r),a.reset))}continue}if(f==="/resume"||f==="/sessions"||f.startsWith("/resume ")){let m=f.startsWith("/resume ")?f.slice(8).trim():await Mo(),y=m?await $o(t,m):null;if(!y){m&&console.log(S(`
291
331
  No session matches "${m}".
292
- `));continue}io(w),console.log(l("cli.run.0_resumed_1_2_3",`
332
+ `));continue}Oe(y),console.log(l("cli.run.0_resumed_1_2_3",`
293
333
  {0}\u2713 Resumed "{1}"{2} {3}
294
- `,i.assistantPrefix,w.title,i.reset,v(`(${ne} turn(s), ${bn(w.updatedAt)})`)));continue}if(p==="/fork"||p==="/clone"){if(u.length<=1){console.log(v(`
334
+ `,a.assistantPrefix,y.title,a.reset,S(`(${Y} turn(s), ${Pn(y.updatedAt)})`)));continue}if(f==="/fork"||f==="/clone"){if(d.length<=1){console.log(S(`
295
335
  Nothing to fork yet.
296
- `));continue}Fe=`${Fe??St(u.slice(1))} (fork)`,oe=wn(),Et=Date.now(),await mt(),console.log(l("cli.run.0_forked_into_a_new",`
336
+ `));continue}L=`${L??Dt(d.slice(1))} (fork)`,q=An(),se=Date.now(),await Ie(),console.log(l("cli.run.0_forked_into_a_new",`
297
337
  {0}\u2713 Forked into a new session{1} {2}
298
- `,i.assistantPrefix,i.reset,v(oe)));continue}if(p.startsWith("/rename")){let m=p.slice(7).trim();if(!m){console.log(v(`
299
- Usage: /rename <new title> (current: ${Fe??St(u.slice(1))})
300
- `));continue}Fe=m.slice(0,120),await mt(),console.log(l("cli.run.0_session_renamed_1",`
338
+ `,a.assistantPrefix,a.reset,S(q)));continue}if(f.startsWith("/rename")){let m=f.slice(7).trim();if(!m){console.log(S(`
339
+ Usage: /rename <new title> (current: ${L??Dt(d.slice(1))})
340
+ `));continue}L=m.slice(0,120),await Ie(),console.log(l("cli.run.0_session_renamed_1",`
301
341
  {0}\u2713 Session renamed{1}
302
- `,i.assistantPrefix,i.reset));continue}if(p==="/session-file"){console.log(l("cli.run.session_0_file_1_2",`
342
+ `,a.assistantPrefix,a.reset));continue}if(f==="/session-file"){console.log(l("cli.run.session_0_file_1_2",`
303
343
  \u2022 Session: {0}
304
344
  \u2022 File: {1}{2}
305
- `,oe,_n(t,oe),u.length<=1?v(" (saved after your first message)"):""));continue}if(p==="/rewind"){let m=yn(u);if(!m.length){console.log(v(`
345
+ `,q,Mn(t,q),d.length<=1?S(" (saved after your first message)"):""));continue}if(f==="/rewind"){let m=Cn(d);if(!m.length){console.log(S(`
306
346
  Nothing to rewind.
307
- `));continue}let w=m.slice(-10);console.log(l("cli.run.0_rewind_to_before_which",`
308
- {0}Rewind to before which message?{1}`,i.bold,i.reset)),w.forEach((B,z)=>console.log(` ${String(z+1).padStart(2)}. ${St([u[B]])}`));let k=Number.parseInt(await ro(`
309
- Number (Enter to cancel): `),10);if(!(k>=1&&k<=w.length))continue;u.length=w[k-1],ne=yn(u).length,await mt(),console.log(l("cli.run.0_conversation_rewound_1_2",`
347
+ `));continue}let y=m.slice(-10);console.log(l("cli.run.0_rewind_to_before_which",`
348
+ {0}Rewind to before which message?{1}`,a.bold,a.reset)),y.forEach((K,V)=>console.log(` ${String(V+1).padStart(2)}. ${Dt([d[K]])}`));let v=Number.parseInt(await je(`
349
+ Number (Enter to cancel): `),10);if(!(v>=1&&v<=y.length))continue;d.length=y[v-1],Y=Cn(d).length,await Ie(),console.log(l("cli.run.0_conversation_rewound_1_2",`
310
350
  {0}\u2713 Conversation rewound.{1} {2}
311
- `,i.assistantPrefix,i.reset,v("File edits were not undone \u2014 use git (e.g. `git restore`) for that.")));continue}if(p.startsWith("/review")){let m=p.slice(7).trim(),w=(U,f)=>new Promise((b,se)=>Fi(U,f,{cwd:t,maxBuffer:16*1024*1024},(T,C,A)=>T?se(new Error(String(A||T.message).trim())):b(String(C)))),k="";try{/^\d+$/.test(m)?k=await w("gh",["pr","diff",m]):k=await w("git",["diff","HEAD"]).catch(()=>w("git",["diff"]))}catch(U){console.log(l("cli.run.0_could_not_get_the",`
351
+ `,a.assistantPrefix,a.reset,S("File edits were not undone \u2014 use git (e.g. `git restore`) for that.")));continue}if(f.startsWith("/review")){let m=f.slice(7).trim(),y=(z,h)=>new Promise(($,me)=>hl(z,h,{cwd:t,maxBuffer:16*1024*1024},(A,I,O)=>A?me(new Error(String(O||A.message).trim())):$(String(I)))),v="";try{/^\d+$/.test(m)?v=await y("gh",["pr","diff",m]):v=await y("git",["diff","HEAD"]).catch(()=>y("git",["diff"]))}catch(z){console.log(l("cli.run.0_could_not_get_the",`
312
352
  {0}Could not get the diff: {1}{2}
313
- `,i.dim,U instanceof Error?U.message:U,i.reset));continue}if(!k.trim()){console.log(v(`
353
+ `,a.dim,z instanceof Error?z.message:z,a.reset));continue}if(!v.trim()){console.log(S(`
314
354
  No changes to review.
315
- `));continue}let B=k.length>6e4,z=`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.
355
+ `));continue}let K=v.length>6e4,V=`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.
316
356
 
317
357
  <diff>
318
- ${B?k.slice(0,6e4)+`
319
- \u2026 (diff truncated)`:k}
320
- </diff>`;await Pt(z,I,!0),console.log("");continue}if(p==="/mcp"){console.log(l("cli.run.0_mcp_servers_1",`
321
- {0}MCP servers:{1}`,i.bold,i.reset));let m=new Map;for(let w of X.tools)m.set(w.server,[...m.get(w.server)??[],w.name]);for(let[w,k]of m)console.log(` \u2022 ${i.cyan}${w}${i.reset} ${v(`${k.length} tool(s): ${k.slice(0,6).join(", ")}${k.length>6?", \u2026":""}`)}`);for(let[w,k]of X.errors)console.log(l("cli.run.0_unavailable_1"," \u2022 {0} \x1B[31munavailable\x1B[0m {1}",w,v(k)));W.untrusted.length&&console.log(` \u2022 ${W.untrusted.join(", ")} ${v(`untrusted \u2014 run \`${_.bin} mcp trust\``)}`),!X.serverCount&&!X.errors.size&&!W.untrusted.length&&console.log(v(` none. Add one: ${_.bin} mcp add <name> <command\u2026|url>`)),console.log("");continue}if(p==="/login"){try{await dn();let m=await to(e);n=m.client,s=m.label,r=m.apiUrl,I=e.model??(await ce()).defaultModel??m.model,Mt=I,(e.cascade||e.effort==="high"&&!e.model)&&(x=await no(e,s,I)),be=null,xe=[],await kn().catch(()=>{}),console.log(`
322
- ${i.assistantPrefix}\u2713 Active session updated: ${i.bold}${s}${i.reset} (${i.cyan}${I}${i.reset}). You can now continue chatting.
358
+ ${K?v.slice(0,6e4)+`
359
+ \u2026 (diff truncated)`:v}
360
+ </diff>`;await Wt(V,B,!0),console.log("");continue}if(f==="/mcp"){console.log(l("cli.run.0_mcp_servers_1",`
361
+ {0}MCP servers:{1}`,a.bold,a.reset));let m=new Map;for(let y of W.tools)m.set(y.server,[...m.get(y.server)??[],y.name]);for(let[y,v]of m)console.log(` \u2022 ${a.cyan}${y}${a.reset} ${S(`${v.length} tool(s): ${v.slice(0,6).join(", ")}${v.length>6?", \u2026":""}`)}`);for(let[y,v]of W.errors)console.log(l("cli.run.0_unavailable_1"," \u2022 {0} \x1B[31munavailable\x1B[0m {1}",y,S(v)));x.untrusted.length&&console.log(` \u2022 ${x.untrusted.join(", ")} ${S(`untrusted \u2014 run \`${w.bin} mcp trust\``)}`),!W.serverCount&&!W.errors.size&&!x.untrusted.length&&console.log(S(` none. Add one: ${w.bin} mcp add <name> <command\u2026|url>`)),console.log("");continue}if(f==="/login"){try{await xn();let m=await So(e);n=m.client,s=m.label,r=m.apiUrl,B=e.model??(await _e()).defaultModel??m.model,re=B,(e.cascade||e.effort==="high"&&!e.model)&&(b=await To(e,s,B)),Re=null,Me=[],await On().catch(()=>{}),console.log(`
362
+ ${a.assistantPrefix}\u2713 Active session updated: ${a.bold}${s}${a.reset} (${a.cyan}${B}${a.reset}). You can now continue chatting.
323
363
  `)}catch(m){console.error(`
324
364
  \x1B[31merror: Login failed:\x1B[0m ${m?.message??m}
325
- `)}continue}if(p==="/logout"){try{await un(),s="not logged in",n={chat:async()=>{throw new le(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},x=null,be=null,console.log(v(`Token removed. Run /login to authenticate.
365
+ `)}continue}if(f==="/logout"){try{await $n(),s="not logged in",n={chat:async()=>{throw new we(401,"Not logged in \u2014 run `/login` or `forge login` to authenticate.",{})}},b=null,Re=null,console.log(S(`Token removed. Run /login to authenticate.
326
366
  `))}catch(m){console.error(`
327
367
  \x1B[31merror: Logout failed:\x1B[0m ${m?.message??m}
328
- `)}continue}if(p==="/reload"){try{let m=await to(e);n=m.client,s=m.label,r=m.apiUrl,I=e.model??(await ce()).defaultModel??m.model,Mt=I,(e.cascade||e.effort==="high"&&!e.model)&&(x=await no(e,s,I)),be=null,console.log(`
329
- ${i.assistantPrefix}\u2713 Reloaded configuration: ${i.bold}${s}${i.reset} (${i.cyan}${I}${i.reset}).
330
- `)}catch(m){console.error(v(`
368
+ `)}continue}if(f==="/reload"){try{let m=await So(e);n=m.client,s=m.label,r=m.apiUrl,B=e.model??(await _e()).defaultModel??m.model,re=B,(e.cascade||e.effort==="high"&&!e.model)&&(b=await To(e,s,B)),Re=null,console.log(`
369
+ ${a.assistantPrefix}\u2713 Reloaded configuration: ${a.bold}${s}${a.reset} (${a.cyan}${B}${a.reset}).
370
+ `)}catch(m){console.error(S(`
331
371
  Failed to reload configuration: ${m?.message??m}
332
- `))}continue}if(p==="/doctor"){await fn();continue}if(p==="/config"){let m=await ce();console.log(`
333
- ${i.bold}Config:${i.reset}
372
+ `))}continue}if(f==="/doctor"){await En();continue}if(f==="/config"){let m=await _e();console.log(`
373
+ ${a.bold}Config:${a.reset}
334
374
  \u2022 Token: ${m.token?m.token.slice(0,6)+"\u2026"+m.token.slice(-4):"(not logged in)"}
335
375
  \u2022 Default model: ${m.defaultModel??"(none)"}
336
- \u2022 Backend: ${s} Model: ${I}
337
- `);continue}if(p.startsWith("!")){let m=p.slice(1).trim();if(m){console.log(v(`$ ${m}`));let w=await Ze("run_shell",{command:m},g).catch(k=>k.message);console.log(w)}continue}let J=N,K=await Pt(p,I);if(K&&ne++,console.log(""),J&&K&&process.stdin.isTTY){let m=dt.createInterface({input:process.stdin,output:process.stdout}),w=(await m.question("? Execute this plan? [y/n]: ")).trim().toLowerCase();m.close(),(w==="y"||w==="yes")&&(N=!1,await Pt("Proceed with the plan above.",I,!1)&&ne++,console.log(""))}await Wi(null,t,ut.observe(p))&&(u[0]={role:"system",content:await d()})}ne>0&&await Gs(t,null)}typeof Js.setDefaultResultOrder=="function"&&Js.setDefaultResultOrder("ipv4first");typeof Ks.setDefaultAutoSelectFamily=="function"&&Ks.setDefaultAutoSelectFamily(!1);var re=new qi(_.bin).description(`${_.name} \u2014 CLI coding agent`).version(ve,"-v, --version","output the current version").option("-V","output the current version",()=>{console.log(ve),process.exit(0)});re.command("version").description("output the current version").action(()=>{console.log(ve)});function Ys(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 Hi("--allow-all","dev only: disable project-root restrictions").hideHelp())}var G=e=>async(...t)=>{try{await e(...t)}catch(n){console.error(l("cli.index.error_0","error: {0}",Ie(n,(await ce()).apiUrl))),process.exit(1)}},Vs=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 zi(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 Gi(e){if(process.stdin.isTTY)return e;let t=(await zi()).trim();return t?{...e,prompt:e.prompt?`${e.prompt}
376
+ \u2022 Backend: ${s} Model: ${B}
377
+ `);continue}if(f.startsWith("!")){let m=f.slice(1).trim();if(m){console.log(S(`$ ${m}`));let y=await dt("run_shell",{command:m},p).catch(v=>v.message);console.log(y)}continue}let Q=j,ee=await Wt(f,B);if(ee&&Y++,console.log(""),Q&&ee&&process.stdin.isTTY){let m=xt.createInterface({input:process.stdin,output:process.stdout}),y=(await m.question("? Execute this plan? [y/n]: ")).trim().toLowerCase();m.close(),(y==="y"||y==="yes")&&(j=!1,await Wt("Proceed with the plan above.",B,!1)&&Y++,console.log(""))}await bl(null,t,fe.observe(f))&&(d[0]={role:"system",content:await u()})}Y>0&&await Wr(t,null)}typeof qr.setDefaultResultOrder=="function"&&qr.setDefaultResultOrder("ipv4first");typeof Hr.setDefaultAutoSelectFamily=="function"&&Hr.setDefaultAutoSelectFamily(!1);var ge=new kl(w.bin).description(`${w.name} \u2014 CLI coding agent`).version(Pe,"-v, --version","output the current version").option("-V","output the current version",()=>{console.log(Pe),process.exit(0)});ge.command("version").description("output the current version").action(()=>{console.log(Pe)});function zr(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 xl("--allow-all","dev only: disable project-root restrictions").hideHelp())}var Z=e=>async(...t)=>{try{await e(...t)}catch(n){console.error(l("cli.index.error_0","error: {0}",Ge(n,(await _e()).apiUrl))),process.exit(1)}},Kr=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 $l(e=1500){return new Promise(t=>{let n="",o=!1,s=process.stdin,r=()=>{clearTimeout(c),s.off("data",i),s.off("end",r),s.off("error",r),s.pause(),t(n)},i=u=>{o=!0,n+=u},c=setTimeout(()=>{o||r()},e);s.setEncoding("utf8"),s.on("data",i),s.on("end",r),s.on("error",r)})}async function vl(e){if(process.stdin.isTTY)return e;let t=(await $l()).trim();return t?{...e,prompt:e.prompt?`${e.prompt}
338
378
 
339
379
  <stdin>
340
380
  ${t}
341
- </stdin>`:t}:e}Ys(re).action(G(async e=>oo(await Gi(Vs(e)))));Ys(re.command("chat").description("interactive session in the current directory")).action(G(async e=>oo(Vs(e))));re.command("doctor").description("check your environment (node, git, login, MCP, hooks)").action(G(fn));re.command("login").description("log in via browser").action(G(dn));re.command("logout").description("remove the stored token").action(G(un));re.command("models").description("list available models or set default").argument("[model]","model id to set as default").action(G(async e=>mn(e)));re.command("usage").description("show remaining requests and dollars").action(G(pn));re.command("init").description(`create ${_.dirName}/skills.md and memory.md`).action(G(gn));var Xs=re.command("skills").description(`project skills (${_.dirName}/skills.md) applied to every run`);Xs.command("list").description("show current skills").action(G(Ts));Xs.command("add").description('add a rule, e.g. skills add "Prefer pnpm"').argument("<text...>").action(G(async e=>Rs(e)));var so=re.command("taste").description("share skills and memory with your team");so.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(G(async(e,t)=>Es(e,t)));so.command("pull").description("merge a package into this project").argument("<package>","namespace/name").action(G(async e=>Ms(e)));so.command("list").description("browse public packages").argument("[query]").action(G(async e=>Cs(e)));var xn=re.command("mcp").description("MCP servers whose tools the agent can use");xn.command("list").description("connect and list tools").action(G(Ps));xn.command("add").description("add a stdio command or HTTP URL").argument("<name>").argument("<command...>").action(G(async(e,t)=>As(e,t)));xn.command("remove").description("remove a server").argument("<name>").action(G(async e=>Ns(e)));xn.command("trust").description("approve this project's MCP servers after reviewing them").action(G(js));var Zs=re.command("hooks").description(`PreToolUse/PostToolUse hook commands (${_.dirName}/hooks.json)`);Zs.command("list").description("show effective hooks").action(G(Os));Zs.command("trust").description("approve this project's hooks after reviewing them").action(G(Ls));re.parseAsync();
381
+ </stdin>`:t}:e}zr(ge).action(Z(async e=>Eo(await vl(Kr(e)))));zr(ge.command("chat").description("interactive session in the current directory")).action(Z(async e=>Eo(Kr(e))));ge.command("doctor").description("check your environment (node, git, login, MCP, hooks)").action(Z(En));ge.command("login").description("log in via browser").action(Z(xn));ge.command("logout").description("remove the stored token").action(Z($n));ge.command("models").description("list available models or set default").argument("[model]","model id to set as default").action(Z(async e=>vn(e)));ge.command("usage").description("show remaining requests and dollars").action(Z(Sn));ge.command("init").description(`create ${w.dirName}/skills.md and memory.md`).action(Z(Tn));var Gr=ge.command("skills").description(`project skills (${w.dirName}/skills.md) applied to every run`);Gr.command("list").description("show current skills").action(Z(xr));Gr.command("add").description('add a rule, e.g. skills add "Prefer pnpm"').argument("<text...>").action(Z(async e=>$r(e)));var Ro=ge.command("taste").description("share skills and memory with your team");Ro.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(Z(async(e,t)=>vr(e,t)));Ro.command("pull").description("merge a package into this project").argument("<package>","namespace/name").action(Z(async e=>Sr(e)));Ro.command("list").description("browse public packages").argument("[query]").action(Z(async e=>Tr(e)));var In=ge.command("mcp").description("MCP servers whose tools the agent can use");In.command("list").description("connect and list tools").action(Z(Er));In.command("add").description("add a stdio command or HTTP URL").argument("<name>").argument("<command...>").action(Z(async(e,t)=>Rr(e,t)));In.command("remove").description("remove a server").argument("<name>").action(Z(async e=>Mr(e)));In.command("trust").description("approve this project's MCP servers after reviewing them").action(Z(Ar));var Jr=ge.command("hooks").description(`PreToolUse/PostToolUse hook commands (${w.dirName}/hooks.json)`);Jr.command("list").description("show effective hooks").action(Z(Pr));Jr.command("trust").description("approve this project's hooks after reviewing them").action(Z(Ir));ge.parseAsync();