@netlify/agent-runner-cli 1.67.0-alpha.1 → 1.67.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin-local.js +2 -2
- package/dist/bin.js +2 -2
- package/dist/index.js +2 -2
- package/package.json +2 -2
package/dist/bin-local.js
CHANGED
|
@@ -5,7 +5,7 @@ import $ from"process";import vr from"path";import Sr from"fs";import io from"mi
|
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import{execSync as Rn}from"child_process";import lr from"fs/promises";import vn from"path";import ee from"process";import{getTracer as Sn}from"@netlify/otel";import Te from"process";var se=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},Tt=e=>e instanceof se;var be=Te.env.NETLIFY_API_URL,Ne=Te.env.NETLIFY_API_TOKEN,H=y("api"),Pe=()=>Te.env.NETLIFY_LOCAL_MODE==="true",Ie=async(e,t={})=>{if(!be||!Ne)throw new Error("No API URL or token");let r=new URL(e,be),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};Te.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Te.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{H.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new se(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new se(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${a}`)}return s},It=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(be=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},xt=()=>({apiUrl:be,token:Ne}),xe=async(e,t)=>Pe()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Ie(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),M=async(e,t,r)=>Pe()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Ie(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Rt=async(e,t)=>Pe()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Ie(`/api/v1/agent_runners/${e}/sessions/${t}`),vt=(e,t,r)=>Ie(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),St=async(e,t)=>Pe()?(H.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):Ie(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ke=async(e,t)=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ae=y("ai_gateway"),We=null;var At=async()=>{if(We)return We;ae.log("Fetching available AI gateway providers");let e=await fetch(`${xt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return We=t,ae.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},$r=async(e,t)=>{let o=(await At()).providers[e];if(!o)return ae.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ae.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},bt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(n),ae.log("Requesting AI gateway information");let c=await vt(s,t.id,t.sessionId);if({token:r,url:i}=c,o=c.expires_at?c.expires_at*1e3:void 0,ae.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let u=o-Date.now()-6e4;u>0&&(n=setTimeout(()=>{a()},u))}};return await Promise.all([a(),At()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:$r}};import W from"process";import z from"path";import Ce from"fs";import{fileURLToPath as jr}from"url";import{createRequire as Yr}from"module";import{execa as Br,execaCommand as Uo}from"execa";import{Transform as Fr}from"stream";var Lr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Dr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Mr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Lr.has(e)||Dr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function X(e){if(typeof e!="string")return e;let t=Mr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Ur(o),"g");r=r.replace(n,"******")}),r}function Ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var le=class extends Fr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=X(n);o(null,i)}};function Nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?X(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?X(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Re=null,Pt=e=>(Re&&Re.destroy(),Re=new Q({totalAllowedTime:e}),Re),Ct=()=>Re;var Q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var kt="netlify-agent-runner-context.md",Je="task-history",K=".netlify",ne="results.md",Ve="assets";var oe=1800*1e3;var Ot={name:"@netlify/agent-runner-cli",type:"module",version:"1.67.0-alpha.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json" "!src/skills/**/*.md"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.37","@anthropic-ai/sdk":"0.72.1","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",kaddidlehopper:"^0.1.2",minimist:"^1.2.8",openai:"6.17.0"}};var qr=jr(import.meta.url),Hr=z.dirname(qr),Kr=Yr(import.meta.url),ce=y("shell"),Xe=new Set,Wr={preferLocal:!0},A=(e,t,r)=>{let[o,n]=Jr(t,r),i={...Wr,...n},s=Br(e,o,i);Vr(s,i),zr(s);let a=r?.idleTimeout;return a&&a>0&&Xr(s,a),s};var Jr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Vr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(W.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new le).pipe(W.stdout),e.stdout?.pipe(new le).pipe(W.stdout),e.stderr?.pipe(new le).pipe(W.stderr);return}e.stdout?.pipe(W.stdout),e.stderr?.pipe(W.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(W.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},$t=e=>ze(e,"SIGKILL"),Xr=(e,t)=>{let r=null,o=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),$t(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},zr=e=>{Xe.add(e);let t=Ct();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),$t(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function ke(e,t){return!!Z(e,t)}function Z(e,t){if(!W.env.NETLIFY_LOCAL_MODE)try{let n=Kr.resolve(Ot.name),i=z.dirname(n);for(;i!==z.dirname(i);){let s=z.dirname(i);if(z.basename(s)==="node_modules"){let a=z.join(s,".bin",t);if(Ce.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(W.env.NODE_PATH){let n=z.join(W.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=z.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=z.join(Hr,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var Zr=y("utils"),Qr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(p=>{n.push(p)});r=!0;let c,u=new Promise(p=>{c=p});return i=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await Qr(t),!o)return r=!1,i=null,p;let d=o,m=n;o=null,n=[],p=await e(...d),m.forEach(g=>{g(p)})}})(),u};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ue=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},Lt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Zr.error("Could not parse JSON",o))}},Dt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let u=Math.min(c-i.length,e.length);return`${i}${e.slice(0,u)}`}return e.slice(0,c)};var en=50*1024,Ze=(e,t=en)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Mt}from"buffer";import tn from"path";var Ut=y("repo"),Gt=async({config:e,isRetry:t})=>{Ut.info("Getting runner diffs");let r=await nn(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let h=on(n);await sn(h)}Ut.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},a=await A("git",["diff","--staged"],s),c=String(a.stdout??"");if(o=!!c,!o)return{hasChanges:!1,ignored:i};let u=await A("git",["diff","--staged","--binary"],s),p=String(u.stdout??""),d,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await A("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let h=await A("git",["diff",e.sha,"HEAD"],s);d=String(h.stdout??"");let T=await A("git",["diff",e.sha,"HEAD","--binary"],s),w=String(T.stdout??"");d!==w&&(m=Mt.from(w).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:d,ignored:i};return c!==p&&(g.diffBinary=Mt.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},Qe=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await A("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},et=async()=>{let e=await A("git",["status","-s"]);return String(e.stdout??"")},jt=/.. (.+)?\.log$/,rn=[jt],nn=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`);return i.length>e.length*.8?e:i}import{execSync as Rn}from"child_process";import lr from"fs/promises";import vn from"path";import ee from"process";import{getTracer as Sn}from"@netlify/otel";import Te from"process";var se=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},Tt=e=>e instanceof se;var be=Te.env.NETLIFY_API_URL,Ne=Te.env.NETLIFY_API_TOKEN,H=y("api"),Pe=()=>Te.env.NETLIFY_LOCAL_MODE==="true",Ie=async(e,t={})=>{if(!be||!Ne)throw new Error("No API URL or token");let r=new URL(e,be),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};Te.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Te.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{H.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new se(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new se(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${a}`)}return s},It=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(be=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},xt=()=>({apiUrl:be,token:Ne}),xe=async(e,t)=>Pe()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Ie(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),M=async(e,t,r)=>Pe()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Ie(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Rt=async(e,t)=>Pe()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Ie(`/api/v1/agent_runners/${e}/sessions/${t}`),vt=(e,t,r)=>Ie(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),St=async(e,t)=>Pe()?(H.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):Ie(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ke=async(e,t)=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ae=y("ai_gateway"),We=null;var At=async()=>{if(We)return We;ae.log("Fetching available AI gateway providers");let e=await fetch(`${xt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return We=t,ae.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},$r=async(e,t)=>{let o=(await At()).providers[e];if(!o)return ae.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ae.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},bt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(n),ae.log("Requesting AI gateway information");let c=await vt(s,t.id,t.sessionId);if({token:r,url:i}=c,o=c.expires_at?c.expires_at*1e3:void 0,ae.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let u=o-Date.now()-6e4;u>0&&(n=setTimeout(()=>{a()},u))}};return await Promise.all([a(),At()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:$r}};import W from"process";import z from"path";import Ce from"fs";import{fileURLToPath as jr}from"url";import{createRequire as Yr}from"module";import{execa as Br,execaCommand as Uo}from"execa";import{Transform as Fr}from"stream";var Lr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Dr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Mr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Lr.has(e)||Dr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function X(e){if(typeof e!="string")return e;let t=Mr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Ur(o),"g");r=r.replace(n,"******")}),r}function Ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var le=class extends Fr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=X(n);o(null,i)}};function Nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?X(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?X(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Re=null,Pt=e=>(Re&&Re.destroy(),Re=new Q({totalAllowedTime:e}),Re),Ct=()=>Re;var Q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var kt="netlify-agent-runner-context.md",Je="task-history",K=".netlify",ne="results.md",Ve="assets";var oe=1800*1e3;var Ot={name:"@netlify/agent-runner-cli",type:"module",version:"1.67.0-alpha.2",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json" "!src/skills/**/*.md"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.37","@anthropic-ai/sdk":"0.72.1","@google/gemini-cli":"0.27.3","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",kaddidlehopper:"^0.1.2",minimist:"^1.2.8",openai:"6.17.0"}};var qr=jr(import.meta.url),Hr=z.dirname(qr),Kr=Yr(import.meta.url),ce=y("shell"),Xe=new Set,Wr={preferLocal:!0},A=(e,t,r)=>{let[o,n]=Jr(t,r),i={...Wr,...n},s=Br(e,o,i);Vr(s,i),zr(s);let a=r?.idleTimeout;return a&&a>0&&Xr(s,a),s};var Jr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Vr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(W.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new le).pipe(W.stdout),e.stdout?.pipe(new le).pipe(W.stdout),e.stderr?.pipe(new le).pipe(W.stderr);return}e.stdout?.pipe(W.stdout),e.stderr?.pipe(W.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(W.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},$t=e=>ze(e,"SIGKILL"),Xr=(e,t)=>{let r=null,o=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),$t(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},zr=e=>{Xe.add(e);let t=Ct();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),$t(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function ke(e,t){return!!Z(e,t)}function Z(e,t){if(!W.env.NETLIFY_LOCAL_MODE)try{let n=Kr.resolve(Ot.name),i=z.dirname(n);for(;i!==z.dirname(i);){let s=z.dirname(i);if(z.basename(s)==="node_modules"){let a=z.join(s,".bin",t);if(Ce.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(W.env.NODE_PATH){let n=z.join(W.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=z.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=z.join(Hr,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var Zr=y("utils"),Qr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(p=>{n.push(p)});r=!0;let c,u=new Promise(p=>{c=p});return i=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await Qr(t),!o)return r=!1,i=null,p;let d=o,m=n;o=null,n=[],p=await e(...d),m.forEach(g=>{g(p)})}})(),u};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ue=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},Lt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Zr.error("Could not parse JSON",o))}},Dt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let u=Math.min(c-i.length,e.length);return`${i}${e.slice(0,u)}`}return e.slice(0,c)};var en=50*1024,Ze=(e,t=en)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Mt}from"buffer";import tn from"path";var Ut=y("repo"),Gt=async({config:e,isRetry:t})=>{Ut.info("Getting runner diffs");let r=await nn(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let h=on(n);await sn(h)}Ut.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},a=await A("git",["diff","--staged"],s),c=String(a.stdout??"");if(o=!!c,!o)return{hasChanges:!1,ignored:i};let u=await A("git",["diff","--staged","--binary"],s),p=String(u.stdout??""),d,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await A("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let h=await A("git",["diff",e.sha,"HEAD"],s);d=String(h.stdout??"");let T=await A("git",["diff",e.sha,"HEAD","--binary"],s),w=String(T.stdout??"");d!==w&&(m=Mt.from(w).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:d,ignored:i};return c!==p&&(g.diffBinary=Mt.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},Qe=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await A("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},et=async()=>{let e=await A("git",["status","-s"]);return String(e.stdout??"")},jt=/.. (.+)?\.log$/,rn=[jt],nn=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(o=>rn.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Yt=async()=>{let{stdout:e}=await A("git",["rev-parse","HEAD"]);return String(e??"").trim()},Bt=async()=>{let{stdout:e}=await A("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},tt=async e=>{e||=await et();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
10
10
|
`).forEach(o=>{t.forEach(i=>{let s=o===`?? ${i}`,a=o.startsWith(`?? ${i}/`)||o.startsWith(`?? ${i}${tn.sep}`);(s||a)&&r.push(`:!${i}`)});let n=o.match(jt)?.[1];n&&r.push(`:!${n}.log`)}),r},rt=async()=>{await A("git",["reset","--hard","HEAD"])},on=e=>{let t=e.split(`
|
|
11
11
|
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,a=s.join(""),c=n.trim(),u=i.trim();return r[a]?r[a].change=u:r[a]={filePath:a,stage:c,change:u},r},{});return Object.values(t)},sn=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(A("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import ln from"fs/promises";import cn from"os";import Wt from"path";import ge from"process";import un from"readline";import dn from"@anthropic-ai/sdk";import nt from"path";import an from"fs/promises";var ot=y("agent-output-utils");async function de({initialResult:e,agentName:t,hasError:r}){let o="",n=nt.join(process.cwd(),K,ne);try{let i=await an.readFile(n,"utf-8");i&&(o=i,ot.log(`Pulled result from ${nt.relative(process.cwd(),n)}`))}catch{ot.log(`No results file found at ${nt.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function pe({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o?.includes("503")&&(n=`The ${t} API is currently experiencing high load. Retrying automatically...`),n&&ot.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function me(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error")||r?.includes("503"))}var qt=e=>!!e;var U=y("runner_claude"),Ht="Claude Code",fe="claude-opus-4-6",Kt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,pn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(U.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(U.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(U.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Jt({aiGateway:e,config:t,model:r}){let o=r;if(e)if(t.modelVersionOverrides?.claude){let n=t.modelVersionOverrides?.claude?.[t.accountType];if(n){if(!await e.isModelAvailableForProvider("anthropic",n))throw new Error(`Model override '${n}' is not available for anthropic provider`);o=n}}else if(r){if(!await e.isModelAvailableForProvider("anthropic",r))throw new Error(`Model '${r}' is not available for anthropic provider`)}else!!fe&&await e.isModelAvailableForProvider("anthropic",fe)?(U.log(`Using default model: ${fe}`),o=fe):fe&&U.log(`Default model ${fe} is not available, proceeding without model specification`);return o}function Vt({aiGateway:e}){if(e){let{token:t,url:r}=e;if(!t||!r)throw new Error("No token or url provided from AI Gateway");ge.env.ANTHROPIC_API_KEY=t,ge.env.ANTHROPIC_BASE_URL=r}else if(!ge.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided")}async function it({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=ge.cwd()}){let a=e,{prompt:c}=a,{model:u}=e,p="";Vt({aiGateway:o});let d=await Jt({config:e,aiGateway:o,model:u}),m=[],g=[],h={},T=0,w=0,E,R,F=[Z(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...d?["--model",d]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",c],D=`${ge.env.NVM_BIN}/node`;U.log(`Running ${D} ${F.join(" ")}`);let N=t.utils.run(D,F,{all:!0,env:ge.env,cwd:s,idleTimeout:oe});N.stdin?.end();let O=ue(()=>{r?.({steps:m,duration:w})},250),I=(v,f)=>{let l={...v,id:T};T+=1,g.push(l),m.push(l),f||O.flush(),O(),f&&O.flush()},P=un.createInterface({input:N.all});return P.on("error",v=>{U.error("Readline interface error",{error:v.message,stack:v.stack})}),P.on("line",v=>{let f=null;try{f=JSON.parse(v)}catch{U.log("Could not parse line",v)}f?.session_id&&f.session_id!==p&&(p=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&I({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?I({message:``}):U.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let _=l.input?.description&&`\`${l.input.description}\``;I({title:[Kt(l.name),_].filter(Boolean).join(" ")})}else l.id&&(h[l.id]=l);O.flush();break}case"tool_result":{let _=l.tool_use_id?h[l.tool_use_id]:void 0,te;if(_){let re=_.input?.file_path&&Wt.relative(s,_.input.file_path),k=re&&`\`${re}\``;te=[Kt(_.name||""),k].filter(Boolean).join(" ")}let we=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(_?.name||""),V;if(typeof l.content=="string")V=l.content;else if(Array.isArray(l.content)){let re=[];l.content.forEach(k=>{k?.type==="text"&&typeof k.text=="string"?re.push(k.text):k?.type==="image"&&typeof k.source=="object"&&k.source?k.source.type==="base64"&&k.source.media_type?re.push(``):U.log(`Unsupported image type ${k.source.type}`,k.source):U.log(`Unsupported block type ${k?.type}`)}),V=re.join(`
|
|
@@ -24,7 +24,7 @@ ${o}
|
|
|
24
24
|
|
|
25
25
|
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:o}},En=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!hn.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
26
26
|
${n.trim()}
|
|
27
|
-
\`\`\``)}catch(i){G.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}},nr=async({aiGateway:e,config:t,model:r,prompt:o,systemPrompt:n="",outputFormat:i,maxTokens:s=4096})=>{if(tr({aiGateway:e}),!await er({config:t,aiGateway:e,model:r}))throw new Error("Model is required");let u=await new fn().responses.parse({model:r,max_output_tokens:s,input:[n&&{role:"system",content:n},{role:"user",content:o}].filter(Boolean),...i&&{text:{format:{...i,name:"output"}}}});return{response:u,text:u.output_text}};import $e from"fs/promises";import ir from"os";import Fe from"path";import ye from"process";import _n from"readline";var B=y("runner_gemini"),or="Gemini CLI",Ee="",wn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(B.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(B.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(B.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Tn={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},In=async()=>{let e=Fe.join(ir.homedir(),".gemini"),t=Fe.join(e,"settings.json");try{await $e.mkdir(e,{recursive:!0});let r={};try{let o=await $e.readFile(t,"utf-8");r=JSON.parse(o)}catch{B.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await $e.writeFile(t,JSON.stringify(r,null,2),"utf-8"),B.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){B.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function at({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ye.cwd()}){let{accountType:s,prompt:a,modelVersionOverrides:c}=e,{model:u}=e;if(await In(),n){let{token:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let _=c?.gemini?.[s];if(_){if(!await n.isModelAvailableForProvider("gemini",_))throw new Error(`Model override '${_}' is not available for gemini provider`);u=_}}if(!u)!!Ee&&await n.isModelAvailableForProvider("gemini",Ee)?(u=Ee,B.log(`Using default model: ${Ee}`)):Ee&&B.log(`Default model ${Ee} is not available, proceeding without model specification`);else if(u&&!c?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",u))throw new Error(`Model '${u}' is not available for gemini provider`);ye.env.GEMINI_API_KEY=f,ye.env.GOOGLE_GEMINI_BASE_URL=l}else if(!ye.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],d=[],m=[],g={},h=0,T=0,w,E,R=[Z(i,"gemini"),...u?["--model",u]:[],"--yolo","--output-format","stream-json","-p",a],F=`${ye.env.NVM_BIN}/node`;B.log(`Running ${F} ${R.join(" ")}`);let D=t.utils.run(F,R,{all:!0,env:ye.env,cwd:i,idleTimeout:oe});D.stdin?.end();let N=ue(()=>{r?.({steps:p,duration:T}),o?.({steps:d,duration:T}),d=[]},250),O=(f,l)=>{f.id=h,h+=1,m.push(f),p.push(f),d.push(f),l||N.flush(),N(),l&&N.flush()},I=_n.createInterface({input:D.all});I.on("error",f=>{B.error("Readline interface error",{error:f.message,stack:f.stack})});let P="",v=()=>{P&&O({message:P.trim()}),P=""};return I.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let _=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:Lt(_,!1)?.error?.message||_||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(["message","result"].includes(l.type)||v(),l.type){case"message":{l.role!=="user"&&l.content&&(P+=l.content);break}case"tool_use":{let _=Tn[l.tool_name]??l.tool_name,te=l.parameters?.file_path,we=te&&Fe.relative(i,te),V=l.parameters?.command,k={title:[_,we&&`\`${we}\``,V&&`\`${V}\``].filter(Boolean).join(" ")};g[l.tool_id]=k,N.flush();break}case"tool_result":{let _=g[l.tool_id];_&&(l.output&&(_.message=`\`\`\`
|
|
27
|
+
\`\`\``)}catch(i){G.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}},nr=async({aiGateway:e,config:t,model:r,prompt:o,systemPrompt:n="",outputFormat:i,maxTokens:s=4096})=>{if(tr({aiGateway:e}),!await er({config:t,aiGateway:e,model:r}))throw new Error("Model is required");let u=await new fn().responses.parse({model:r,max_output_tokens:s,input:[n&&{role:"system",content:n},{role:"user",content:o}].filter(Boolean),...i&&{text:{format:{...i,name:"output"}}}});return{response:u,text:u.output_text}};import $e from"fs/promises";import ir from"os";import Fe from"path";import ye from"process";import _n from"readline";var B=y("runner_gemini"),or="Gemini CLI",Ee="",wn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(B.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(B.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(B.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Tn={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},In=async()=>{let e=Fe.join(ir.homedir(),".gemini"),t=Fe.join(e,"settings.json");try{await $e.mkdir(e,{recursive:!0});let r={};try{let o=await $e.readFile(t,"utf-8");r=JSON.parse(o)}catch{B.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),r.skills||(r.skills={}),r.skills.enabled=!0,await $e.writeFile(t,JSON.stringify(r,null,2),"utf-8"),B.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){B.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function at({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ye.cwd()}){let{accountType:s,prompt:a,modelVersionOverrides:c}=e,{model:u}=e;if(await In(),n){let{token:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let _=c?.gemini?.[s];if(_){if(!await n.isModelAvailableForProvider("gemini",_))throw new Error(`Model override '${_}' is not available for gemini provider`);u=_}}if(!u)!!Ee&&await n.isModelAvailableForProvider("gemini",Ee)?(u=Ee,B.log(`Using default model: ${Ee}`)):Ee&&B.log(`Default model ${Ee} is not available, proceeding without model specification`);else if(u&&!c?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",u))throw new Error(`Model '${u}' is not available for gemini provider`);ye.env.GEMINI_API_KEY=f,ye.env.GOOGLE_GEMINI_BASE_URL=l}else if(!ye.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],d=[],m=[],g={},h=0,T=0,w,E,R=[Z(i,"gemini"),...u?["--model",u]:[],"--yolo","--output-format","stream-json","-p",a],F=`${ye.env.NVM_BIN}/node`;B.log(`Running ${F} ${R.join(" ")}`);let D=t.utils.run(F,R,{all:!0,env:ye.env,cwd:i,idleTimeout:oe});D.stdin?.end();let N=ue(()=>{r?.({steps:p,duration:T}),o?.({steps:d,duration:T}),d=[]},250),O=(f,l)=>{f.id=h,h+=1,m.push(f),p.push(f),d.push(f),l||N.flush(),N(),l&&N.flush()},I=_n.createInterface({input:D.all});I.on("error",f=>{B.error("Readline interface error",{error:f.message,stack:f.stack})});let P="",v=()=>{P&&O({message:P.trim()}),P=""};return I.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let _=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:Lt(_,!1)?.error?.message||_||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(["message","result"].includes(l.type)||v(),l.type){case"message":{l.role!=="user"&&l.content&&(P+=l.content);break}case"tool_use":{let _=Tn[l.tool_name]??l.tool_name,te=l.parameters?.file_path,we=te&&Fe.relative(i,te),V=l.parameters?.command,k={title:[_,we&&`\`${we}\``,V&&`\`${V}\``].filter(Boolean).join(" ")};g[l.tool_id]=k,N.flush();break}case"tool_result":{let _=g[l.tool_id];_&&(l.output&&(_.message=`\`\`\`
|
|
28
28
|
${l.output.trim()}
|
|
29
29
|
\`\`\``),O(_,!0));break}case"result":{T=l.stats?.duration_ms,l.status==="error"?E=l.error?.message:w=P.trim();break}case"error":{E=l.error;break}case"finished":break;default:{B.warn("Unhandled message type:",l.type);break}}}),await D.catch(f=>{({error:E,result:w}=wn({catchError:f,runCmd:D,error:E,result:w,runnerName:"Gemini"}))}),I.close(),N.flush(),{steps:m,duration:T,result:await de({initialResult:w,agentName:or,hasError:!!E}),error:pe({error:E,agentName:or}),isRetryableError:me(E)}}var sr=async()=>{let e=Fe.join(ir.homedir(),".gemini");await $e.rm(e,{recursive:!0,force:!0})};var xn={codex:{runner:st,clean:rr},claude:{runner:it,clean:Xt},gemini:{runner:at,clean:sr}},ar=xn;var Le=y("init_stage"),cr=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await S(Sn(),"init-stage",async n=>{let i=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":o||"unknown"});let s=ar[e.runner];if(!s)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=bn({apiToken:r});It(a);let c=e.useGateway?await bt({netlify:a,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!c});let u=5*1024,p=Ft(async({steps:h=[],duration:T})=>{let w=h.map(E=>{let R=E.title?Ze(X(E.title),u):void 0,F=E.message?Ze(X(E.message)):void 0;return{...E,title:R,message:F}});h.length=0;try{return await M(e.id,e.sessionId,{steps:w,duration:T})}catch(E){Le.error("persistSteps failed",{error:E?.message||E})}},t);Le.info("Adding build files to stage");let d=await tt();await Qe(d),ee.env.NETLIFY_LOCAL_MODE||await An();let m;e.hasRepo?e.sha?(m=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(m=await Yt(),await xe(e.id,{sha:m}),n?.setAttributes({"init.sha.source":"current_commit"})):(m=await Bt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let g=performance.now()-i;return n?.setAttributes({"init.sha":m||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:c,context:a,persistSteps:p,runner:s,sha:m}}),An=async()=>{let e="/usr/bin/git";try{e=Rn("which git").toString().trim()||e}catch{}let t="/tmp/netlify-git-wrapper",r=vn.join(t,"git"),o=`#!/bin/bash
|
|
30
30
|
# Git wrapper that blocks add and commit commands
|
package/dist/bin.js
CHANGED
|
@@ -5,7 +5,7 @@ import yt from"process";import _o from"minimist";import{createRequire as lo}from
|
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import{execSync as Cn}from"child_process";import fr from"fs/promises";import Pn from"path";import Z from"process";import{getTracer as On}from"@netlify/otel";import we from"process";var oe=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},It=e=>e instanceof oe;var Ae=we.env.NETLIFY_API_URL,Ne=we.env.NETLIFY_API_TOKEN,B=y("api"),be=()=>we.env.NETLIFY_LOCAL_MODE==="true",Te=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};we.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(we.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{B.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||B.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new oe(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new oe(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${a}`)}return s},Rt=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},vt=()=>({apiUrl:Ae,token:Ne}),xe=async(e,t)=>be()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Te(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),L=async(e,t,r)=>be()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var St=async(e,t)=>be()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`),At=(e,t,r)=>Te(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),Nt=async(e,t)=>be()?(B.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):Te(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=async(e,t)=>{B.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ie=y("ai_gateway"),We=null;var bt=async()=>{if(We)return We;ie.log("Fetching available AI gateway providers");let e=await fetch(`${vt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return We=t,ie.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Gr=async(e,t)=>{let o=(await bt()).providers[e];if(!o)return ie.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ie.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},Ct=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(n),ie.log("Requesting AI gateway information");let c=await At(s,t.id,t.sessionId);if({token:r,url:i}=c,o=c.expires_at?c.expires_at*1e3:void 0,ie.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let u=o-Date.now()-6e4;u>0&&(n=setTimeout(()=>{a()},u))}};return await Promise.all([a(),bt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Gr}};import q from"process";import J from"path";import Ce from"fs";import{fileURLToPath as Kr}from"url";import{createRequire as Vr}from"module";import{execa as Jr,execaCommand as zo}from"execa";import{Transform as jr}from"stream";var Yr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Br=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Hr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Yr.has(e)||Br.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function V(e){if(typeof e!="string")return e;let t=Hr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(qr(o),"g");r=r.replace(n,"******")}),r}function qr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var se=class extends jr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=V(n);o(null,i)}};function Pt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?V(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?V(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Ie=null,Ot=e=>(Ie&&Ie.destroy(),Ie=new X({totalAllowedTime:e}),Ie),kt=()=>Ie;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Ft="netlify-agent-runner-context.md",Ke="task-history",H=".netlify",te="results.md",Ve="assets",Je="other",Xe="personal";var ze="enterprise",Ze="free",$t=[Xe,"pro",ze,Ze],Lt=["normal","redeploy","create","ask","dtn-prod-iteration","rebase"],Dt="The production deploy has changed since you started working. Please reapply the changes to the current codebase, resolving any conflicts that arise. Use the attached diff file if present, otherwise review the previous session context to reproduce the changes.",re=1800*1e3;var Mt={name:"@netlify/agent-runner-cli",type:"module",version:"1.67.0-alpha.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json" "!src/skills/**/*.md"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.37","@anthropic-ai/sdk":"0.72.1","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",kaddidlehopper:"^0.1.2",minimist:"^1.2.8",openai:"6.17.0"}};var Xr=Kr(import.meta.url),zr=J.dirname(Xr),Zr=Vr(import.meta.url),ae=y("shell"),Qe=new Set,Qr={preferLocal:!0},O=(e,t,r)=>{let[o,n]=en(t,r),i={...Qr,...n},s=Jr(e,o,i);tn(s,i),nn(s);let a=r?.idleTimeout;return a&&a>0&&rn(s,a),s};var en=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},tn=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new se).pipe(q.stdout),e.stdout?.pipe(new se).pipe(q.stdout),e.stderr?.pipe(new se).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),ae.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ae.error("Error killing process:",r),!1}},Ut=e=>et(e,"SIGKILL"),rn=(e,t)=>{let r=null,o=()=>{ae.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing idle process ${e.pid}`),Ut(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},nn=e=>{Qe.add(e);let t=kt();if(t){let r=t.onTimesUp(()=>{ae.log(`Global timer expired, killing process ${e.pid}`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing process ${e.pid} after timeout`),Ut(e))},5e3)});e.on("exit",()=>{Qe.delete(e),r()}),e.on("error",()=>{Qe.delete(e),r()})}};function z(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let n=Zr.resolve(Mt.name),i=J.dirname(n);for(;i!==J.dirname(i);){let s=J.dirname(i);if(J.basename(s)==="node_modules"){let a=J.join(s,".bin",t);if(Ce.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(q.env.NODE_PATH){let n=J.join(q.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=J.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=J.join(zr,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var Gt=y("utils"),on=e=>new Promise(t=>{setTimeout(t,e)}),jt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(d=>{n.push(d)});r=!0;let c,u=new Promise(d=>{c=d});return i=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await on(t),!o)return r=!1,i=null,d;let p=o,m=n;o=null,n=[],d=await e(...p),m.forEach(g=>{g(d)})}})(),u};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},le=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},Pe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Gt.error("Could not parse JSON",o))}},Yt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let u=Math.min(c-i.length,e.length);return`${i}${e.slice(0,u)}`}return e.slice(0,c)},sn=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!$t.some(t=>t in e),Bt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let i=JSON.parse(o);sn(i)&&(e[r]=i)}catch(i){let a=i instanceof SyntaxError?"Invalid JSON":i.message;Gt.error(`Could not parse ${r} model version override from ${n}: ${a}`)}}}),e},an=50*1024,tt=(e,t=an)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Ht}from"buffer";import ln from"path";var qt=y("repo"),Wt=async({config:e,isRetry:t})=>{qt.info("Getting runner diffs");let r=await un(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let h=pn(n);await dn(h)}qt.info("Changes after processing"),await nt();let i=await ot(n);await rt(i);let s={stdio:["ignore","pipe","pipe"]},a=await O("git",["diff","--staged"],s),c=String(a.stdout??"");if(o=!!c,!o)return{hasChanges:!1,ignored:i};let u=await O("git",["diff","--staged","--binary"],s),d=String(u.stdout??""),p,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await O("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let h=await O("git",["diff",e.sha,"HEAD"],s);p=String(h.stdout??"");let T=await O("git",["diff",e.sha,"HEAD","--binary"],s),E=String(T.stdout??"");p!==E&&(m=Ht.from(E).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:p,ignored:i};return c!==d&&(g.diffBinary=Ht.from(d).toString("base64")),m&&(g.resultDiffBinary=m),g},rt=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await O("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},nt=async()=>{let e=await O("git",["status","-s"]);return String(e.stdout??"")},Kt=/.. (.+)?\.log$/,cn=[Kt],un=async()=>{let e=await nt();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`);return i.length>e.length*.8?e:i}import{execSync as Cn}from"child_process";import fr from"fs/promises";import Pn from"path";import Z from"process";import{getTracer as On}from"@netlify/otel";import we from"process";var oe=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},It=e=>e instanceof oe;var Ae=we.env.NETLIFY_API_URL,Ne=we.env.NETLIFY_API_TOKEN,B=y("api"),be=()=>we.env.NETLIFY_LOCAL_MODE==="true",Te=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};we.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(we.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{B.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||B.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new oe(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new oe(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${a}`)}return s},Rt=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},vt=()=>({apiUrl:Ae,token:Ne}),xe=async(e,t)=>be()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Te(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),L=async(e,t,r)=>be()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var St=async(e,t)=>be()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`),At=(e,t,r)=>Te(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),Nt=async(e,t)=>be()?(B.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):Te(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=async(e,t)=>{B.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ie=y("ai_gateway"),We=null;var bt=async()=>{if(We)return We;ie.log("Fetching available AI gateway providers");let e=await fetch(`${vt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return We=t,ie.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Gr=async(e,t)=>{let o=(await bt()).providers[e];if(!o)return ie.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ie.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},Ct=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(n),ie.log("Requesting AI gateway information");let c=await At(s,t.id,t.sessionId);if({token:r,url:i}=c,o=c.expires_at?c.expires_at*1e3:void 0,ie.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let u=o-Date.now()-6e4;u>0&&(n=setTimeout(()=>{a()},u))}};return await Promise.all([a(),bt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Gr}};import q from"process";import J from"path";import Ce from"fs";import{fileURLToPath as Kr}from"url";import{createRequire as Vr}from"module";import{execa as Jr,execaCommand as zo}from"execa";import{Transform as jr}from"stream";var Yr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Br=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Hr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Yr.has(e)||Br.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function V(e){if(typeof e!="string")return e;let t=Hr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(qr(o),"g");r=r.replace(n,"******")}),r}function qr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var se=class extends jr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=V(n);o(null,i)}};function Pt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?V(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?V(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Ie=null,Ot=e=>(Ie&&Ie.destroy(),Ie=new X({totalAllowedTime:e}),Ie),kt=()=>Ie;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Ft="netlify-agent-runner-context.md",Ke="task-history",H=".netlify",te="results.md",Ve="assets",Je="other",Xe="personal";var ze="enterprise",Ze="free",$t=[Xe,"pro",ze,Ze],Lt=["normal","redeploy","create","ask","dtn-prod-iteration","rebase"],Dt="The production deploy has changed since you started working. Please reapply the changes to the current codebase, resolving any conflicts that arise. Use the attached diff file if present, otherwise review the previous session context to reproduce the changes.",re=1800*1e3;var Mt={name:"@netlify/agent-runner-cli",type:"module",version:"1.67.0-alpha.2",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json" "!src/skills/**/*.md"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.37","@anthropic-ai/sdk":"0.72.1","@google/gemini-cli":"0.27.3","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",kaddidlehopper:"^0.1.2",minimist:"^1.2.8",openai:"6.17.0"}};var Xr=Kr(import.meta.url),zr=J.dirname(Xr),Zr=Vr(import.meta.url),ae=y("shell"),Qe=new Set,Qr={preferLocal:!0},O=(e,t,r)=>{let[o,n]=en(t,r),i={...Qr,...n},s=Jr(e,o,i);tn(s,i),nn(s);let a=r?.idleTimeout;return a&&a>0&&rn(s,a),s};var en=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},tn=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new se).pipe(q.stdout),e.stdout?.pipe(new se).pipe(q.stdout),e.stderr?.pipe(new se).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),ae.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ae.error("Error killing process:",r),!1}},Ut=e=>et(e,"SIGKILL"),rn=(e,t)=>{let r=null,o=()=>{ae.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing idle process ${e.pid}`),Ut(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},nn=e=>{Qe.add(e);let t=kt();if(t){let r=t.onTimesUp(()=>{ae.log(`Global timer expired, killing process ${e.pid}`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing process ${e.pid} after timeout`),Ut(e))},5e3)});e.on("exit",()=>{Qe.delete(e),r()}),e.on("error",()=>{Qe.delete(e),r()})}};function z(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let n=Zr.resolve(Mt.name),i=J.dirname(n);for(;i!==J.dirname(i);){let s=J.dirname(i);if(J.basename(s)==="node_modules"){let a=J.join(s,".bin",t);if(Ce.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(q.env.NODE_PATH){let n=J.join(q.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=J.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=J.join(zr,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var Gt=y("utils"),on=e=>new Promise(t=>{setTimeout(t,e)}),jt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(d=>{n.push(d)});r=!0;let c,u=new Promise(d=>{c=d});return i=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await on(t),!o)return r=!1,i=null,d;let p=o,m=n;o=null,n=[],d=await e(...p),m.forEach(g=>{g(d)})}})(),u};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},le=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},Pe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Gt.error("Could not parse JSON",o))}},Yt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let u=Math.min(c-i.length,e.length);return`${i}${e.slice(0,u)}`}return e.slice(0,c)},sn=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!$t.some(t=>t in e),Bt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let i=JSON.parse(o);sn(i)&&(e[r]=i)}catch(i){let a=i instanceof SyntaxError?"Invalid JSON":i.message;Gt.error(`Could not parse ${r} model version override from ${n}: ${a}`)}}}),e},an=50*1024,tt=(e,t=an)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Ht}from"buffer";import ln from"path";var qt=y("repo"),Wt=async({config:e,isRetry:t})=>{qt.info("Getting runner diffs");let r=await un(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let h=pn(n);await dn(h)}qt.info("Changes after processing"),await nt();let i=await ot(n);await rt(i);let s={stdio:["ignore","pipe","pipe"]},a=await O("git",["diff","--staged"],s),c=String(a.stdout??"");if(o=!!c,!o)return{hasChanges:!1,ignored:i};let u=await O("git",["diff","--staged","--binary"],s),d=String(u.stdout??""),p,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await O("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let h=await O("git",["diff",e.sha,"HEAD"],s);p=String(h.stdout??"");let T=await O("git",["diff",e.sha,"HEAD","--binary"],s),E=String(T.stdout??"");p!==E&&(m=Ht.from(E).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:p,ignored:i};return c!==d&&(g.diffBinary=Ht.from(d).toString("base64")),m&&(g.resultDiffBinary=m),g},rt=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await O("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},nt=async()=>{let e=await O("git",["status","-s"]);return String(e.stdout??"")},Kt=/.. (.+)?\.log$/,cn=[Kt],un=async()=>{let e=await nt();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(o=>cn.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Vt=async()=>{let{stdout:e}=await O("git",["rev-parse","HEAD"]);return String(e??"").trim()},Jt=async()=>{let{stdout:e}=await O("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},ot=async e=>{e||=await nt();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
10
10
|
`).forEach(o=>{t.forEach(i=>{let s=o===`?? ${i}`,a=o.startsWith(`?? ${i}/`)||o.startsWith(`?? ${i}${ln.sep}`);(s||a)&&r.push(`:!${i}`)});let n=o.match(Kt)?.[1];n&&r.push(`:!${n}.log`)}),r},it=async()=>{await O("git",["reset","--hard","HEAD"])},pn=e=>{let t=e.split(`
|
|
11
11
|
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,a=s.join(""),c=n.trim(),u=i.trim();return r[a]?r[a].change=u:r[a]={filePath:a,stage:c,change:u},r},{});return Object.values(t)},dn=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(O("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import fn from"fs/promises";import gn from"os";import Qt from"path";import me from"process";import hn from"readline";import yn from"@anthropic-ai/sdk";import st from"path";import mn from"fs/promises";var at=y("agent-output-utils");async function ce({initialResult:e,agentName:t,hasError:r}){let o="",n=st.join(process.cwd(),H,te);try{let i=await mn.readFile(n,"utf-8");i&&(o=i,at.log(`Pulled result from ${st.relative(process.cwd(),n)}`))}catch{at.log(`No results file found at ${st.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ue({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o?.includes("503")&&(n=`The ${t} API is currently experiencing high load. Retrying automatically...`),n&&at.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function pe(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error")||r?.includes("503"))}var Xt=e=>!!e;var D=y("runner_claude"),zt="Claude Code",de="claude-opus-4-6",Zt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,En=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(D.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(D.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(D.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function er({aiGateway:e,config:t,model:r}){let o=r;if(e)if(t.modelVersionOverrides?.claude){let n=t.modelVersionOverrides?.claude?.[t.accountType];if(n){if(!await e.isModelAvailableForProvider("anthropic",n))throw new Error(`Model override '${n}' is not available for anthropic provider`);o=n}}else if(r){if(!await e.isModelAvailableForProvider("anthropic",r))throw new Error(`Model '${r}' is not available for anthropic provider`)}else!!de&&await e.isModelAvailableForProvider("anthropic",de)?(D.log(`Using default model: ${de}`),o=de):de&&D.log(`Default model ${de} is not available, proceeding without model specification`);return o}function tr({aiGateway:e}){if(e){let{token:t,url:r}=e;if(!t||!r)throw new Error("No token or url provided from AI Gateway");me.env.ANTHROPIC_API_KEY=t,me.env.ANTHROPIC_BASE_URL=r}else if(!me.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided")}async function lt({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=me.cwd()}){let a=e,{prompt:c}=a,{model:u}=e,d="";tr({aiGateway:o});let p=await er({config:e,aiGateway:o,model:u}),m=[],g=[],h={},T=0,E=0,_,R,F=[z(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...p?["--model",p]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",c],$=`${me.env.NVM_BIN}/node`;D.log(`Running ${$} ${F.join(" ")}`);let N=t.utils.run($,F,{all:!0,env:me.env,cwd:s,idleTimeout:re});N.stdin?.end();let k=le(()=>{r?.({steps:m,duration:E})},250),x=(v,f)=>{let l={...v,id:T};T+=1,g.push(l),m.push(l),f||k.flush(),k(),f&&k.flush()},b=hn.createInterface({input:N.all});return b.on("error",v=>{D.error("Readline interface error",{error:v.message,stack:v.stack})}),b.on("line",v=>{let f=null;try{f=JSON.parse(v)}catch{D.log("Could not parse line",v)}f?.session_id&&f.session_id!==d&&(d=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&x({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?x({message:``}):D.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let w=l.input?.description&&`\`${l.input.description}\``;x({title:[Zt(l.name),w].filter(Boolean).join(" ")})}else l.id&&(h[l.id]=l);k.flush();break}case"tool_result":{let w=l.tool_use_id?h[l.tool_use_id]:void 0,Q;if(w){let ee=w.input?.file_path&&Qt.relative(s,w.input.file_path),P=ee&&`\`${ee}\``;Q=[Zt(w.name||""),P].filter(Boolean).join(" ")}let _e=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(w?.name||""),K;if(typeof l.content=="string")K=l.content;else if(Array.isArray(l.content)){let ee=[];l.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?ee.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?ee.push(``):D.log(`Unsupported image type ${P.source.type}`,P.source):D.log(`Unsupported block type ${P?.type}`)}),K=ee.join(`
|
|
@@ -24,7 +24,7 @@ ${o}
|
|
|
24
24
|
|
|
25
25
|
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:o}},Rn=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!xn.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
26
26
|
${n.trim()}
|
|
27
|
-
\`\`\``)}catch(i){M.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}},cr=async({aiGateway:e,config:t,model:r,prompt:o,systemPrompt:n="",outputFormat:i,maxTokens:s=4096})=>{if(ar({aiGateway:e}),!await sr({config:t,aiGateway:e,model:r}))throw new Error("Model is required");let u=await new wn().responses.parse({model:r,max_output_tokens:s,input:[n&&{role:"system",content:n},{role:"user",content:o}].filter(Boolean),...i&&{text:{format:{...i,name:"output"}}}});return{response:u,text:u.output_text}};import ke from"fs/promises";import pr from"os";import Fe from"path";import ge from"process";import vn from"readline";var G=y("runner_gemini"),ur="Gemini CLI",he="",Sn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(G.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(G.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(G.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),An={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},Nn=async()=>{let e=Fe.join(pr.homedir(),".gemini"),t=Fe.join(e,"settings.json");try{await ke.mkdir(e,{recursive:!0});let r={};try{let o=await ke.readFile(t,"utf-8");r=JSON.parse(o)}catch{G.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await ke.writeFile(t,JSON.stringify(r,null,2),"utf-8"),G.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){G.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function ut({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ge.cwd()}){let{accountType:s,prompt:a,modelVersionOverrides:c}=e,{model:u}=e;if(await Nn(),n){let{token:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let w=c?.gemini?.[s];if(w){if(!await n.isModelAvailableForProvider("gemini",w))throw new Error(`Model override '${w}' is not available for gemini provider`);u=w}}if(!u)!!he&&await n.isModelAvailableForProvider("gemini",he)?(u=he,G.log(`Using default model: ${he}`)):he&&G.log(`Default model ${he} is not available, proceeding without model specification`);else if(u&&!c?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",u))throw new Error(`Model '${u}' is not available for gemini provider`);ge.env.GEMINI_API_KEY=f,ge.env.GOOGLE_GEMINI_BASE_URL=l}else if(!ge.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],p=[],m=[],g={},h=0,T=0,E,_,R=[z(i,"gemini"),...u?["--model",u]:[],"--yolo","--output-format","stream-json","-p",a],F=`${ge.env.NVM_BIN}/node`;G.log(`Running ${F} ${R.join(" ")}`);let $=t.utils.run(F,R,{all:!0,env:ge.env,cwd:i,idleTimeout:re});$.stdin?.end();let N=le(()=>{r?.({steps:d,duration:T}),o?.({steps:p,duration:T}),p=[]},250),k=(f,l)=>{f.id=h,h+=1,m.push(f),d.push(f),p.push(f),l||N.flush(),N(),l&&N.flush()},x=vn.createInterface({input:$.all});x.on("error",f=>{G.error("Readline interface error",{error:f.message,stack:f.stack})});let b="",v=()=>{b&&k({message:b.trim()}),b=""};return x.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let w=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:Pe(w,!1)?.error?.message||w||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(["message","result"].includes(l.type)||v(),l.type){case"message":{l.role!=="user"&&l.content&&(b+=l.content);break}case"tool_use":{let w=An[l.tool_name]??l.tool_name,Q=l.parameters?.file_path,_e=Q&&Fe.relative(i,Q),K=l.parameters?.command,P={title:[w,_e&&`\`${_e}\``,K&&`\`${K}\``].filter(Boolean).join(" ")};g[l.tool_id]=P,N.flush();break}case"tool_result":{let w=g[l.tool_id];w&&(l.output&&(w.message=`\`\`\`
|
|
27
|
+
\`\`\``)}catch(i){M.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}},cr=async({aiGateway:e,config:t,model:r,prompt:o,systemPrompt:n="",outputFormat:i,maxTokens:s=4096})=>{if(ar({aiGateway:e}),!await sr({config:t,aiGateway:e,model:r}))throw new Error("Model is required");let u=await new wn().responses.parse({model:r,max_output_tokens:s,input:[n&&{role:"system",content:n},{role:"user",content:o}].filter(Boolean),...i&&{text:{format:{...i,name:"output"}}}});return{response:u,text:u.output_text}};import ke from"fs/promises";import pr from"os";import Fe from"path";import ge from"process";import vn from"readline";var G=y("runner_gemini"),ur="Gemini CLI",he="",Sn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(G.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(G.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(G.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),An={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},Nn=async()=>{let e=Fe.join(pr.homedir(),".gemini"),t=Fe.join(e,"settings.json");try{await ke.mkdir(e,{recursive:!0});let r={};try{let o=await ke.readFile(t,"utf-8");r=JSON.parse(o)}catch{G.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),r.skills||(r.skills={}),r.skills.enabled=!0,await ke.writeFile(t,JSON.stringify(r,null,2),"utf-8"),G.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){G.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function ut({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ge.cwd()}){let{accountType:s,prompt:a,modelVersionOverrides:c}=e,{model:u}=e;if(await Nn(),n){let{token:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let w=c?.gemini?.[s];if(w){if(!await n.isModelAvailableForProvider("gemini",w))throw new Error(`Model override '${w}' is not available for gemini provider`);u=w}}if(!u)!!he&&await n.isModelAvailableForProvider("gemini",he)?(u=he,G.log(`Using default model: ${he}`)):he&&G.log(`Default model ${he} is not available, proceeding without model specification`);else if(u&&!c?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",u))throw new Error(`Model '${u}' is not available for gemini provider`);ge.env.GEMINI_API_KEY=f,ge.env.GOOGLE_GEMINI_BASE_URL=l}else if(!ge.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],p=[],m=[],g={},h=0,T=0,E,_,R=[z(i,"gemini"),...u?["--model",u]:[],"--yolo","--output-format","stream-json","-p",a],F=`${ge.env.NVM_BIN}/node`;G.log(`Running ${F} ${R.join(" ")}`);let $=t.utils.run(F,R,{all:!0,env:ge.env,cwd:i,idleTimeout:re});$.stdin?.end();let N=le(()=>{r?.({steps:d,duration:T}),o?.({steps:p,duration:T}),p=[]},250),k=(f,l)=>{f.id=h,h+=1,m.push(f),d.push(f),p.push(f),l||N.flush(),N(),l&&N.flush()},x=vn.createInterface({input:$.all});x.on("error",f=>{G.error("Readline interface error",{error:f.message,stack:f.stack})});let b="",v=()=>{b&&k({message:b.trim()}),b=""};return x.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let w=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:Pe(w,!1)?.error?.message||w||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(["message","result"].includes(l.type)||v(),l.type){case"message":{l.role!=="user"&&l.content&&(b+=l.content);break}case"tool_use":{let w=An[l.tool_name]??l.tool_name,Q=l.parameters?.file_path,_e=Q&&Fe.relative(i,Q),K=l.parameters?.command,P={title:[w,_e&&`\`${_e}\``,K&&`\`${K}\``].filter(Boolean).join(" ")};g[l.tool_id]=P,N.flush();break}case"tool_result":{let w=g[l.tool_id];w&&(l.output&&(w.message=`\`\`\`
|
|
28
28
|
${l.output.trim()}
|
|
29
29
|
\`\`\``),k(w,!0));break}case"result":{T=l.stats?.duration_ms,l.status==="error"?_=l.error?.message:E=b.trim();break}case"error":{_=l.error;break}case"finished":break;default:{G.warn("Unhandled message type:",l.type);break}}}),await $.catch(f=>{({error:_,result:E}=Sn({catchError:f,runCmd:$,error:_,result:E,runnerName:"Gemini"}))}),x.close(),N.flush(),{steps:m,duration:T,result:await ce({initialResult:E,agentName:ur,hasError:!!_}),error:ue({error:_,agentName:ur}),isRetryableError:pe(_)}}var dr=async()=>{let e=Fe.join(pr.homedir(),".gemini");await ke.rm(e,{recursive:!0,force:!0})};var bn={codex:{runner:ct,clean:lr},claude:{runner:lt,clean:rr},gemini:{runner:ut,clean:dr}},mr=bn;var $e=y("init_stage"),gr=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await S(On(),"init-stage",async n=>{let i=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":o||"unknown"});let s=mr[e.runner];if(!s)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=Fn({apiToken:r});Rt(a);let c=e.useGateway?await Ct({netlify:a,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!c});let u=5*1024,d=jt(async({steps:h=[],duration:T})=>{let E=h.map(_=>{let R=_.title?tt(V(_.title),u):void 0,F=_.message?tt(V(_.message)):void 0;return{..._,title:R,message:F}});h.length=0;try{return await L(e.id,e.sessionId,{steps:E,duration:T})}catch(_){$e.error("persistSteps failed",{error:_?.message||_})}},t);$e.info("Adding build files to stage");let p=await ot();await rt(p),Z.env.NETLIFY_LOCAL_MODE||await kn();let m;e.hasRepo?e.sha?(m=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(m=await Vt(),await xe(e.id,{sha:m}),n?.setAttributes({"init.sha.source":"current_commit"})):(m=await Jt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let g=performance.now()-i;return n?.setAttributes({"init.sha":m||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:c,context:a,persistSteps:d,runner:s,sha:m}}),kn=async()=>{let e="/usr/bin/git";try{e=Cn("which git").toString().trim()||e}catch{}let t="/tmp/netlify-git-wrapper",r=Pn.join(t,"git"),o=`#!/bin/bash
|
|
30
30
|
# Git wrapper that blocks add and commit commands
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import{createRequire as Wn}from"module";import{createTracerProvider as _r}from"@
|
|
|
4
4
|
${s}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return i.length>e.length*.8?e:i}import{execSync as fn}from"child_process";import rr from"fs/promises";import gn from"path";import z from"process";import{getTracer as hn}from"@netlify/otel";import _e from"process";var ne=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},gt=e=>e instanceof ne;var ve=_e.env.NETLIFY_API_URL,Se=_e.env.NETLIFY_API_TOKEN,Y=E("api"),Ae=()=>_e.env.NETLIFY_LOCAL_MODE==="true",Ee=async(e,t={})=>{if(!ve||!Se)throw new Error("No API URL or token");let r=new URL(e,ve),o={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};_e.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(_e.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{Y.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ne(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new ne(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${a}`)}return s},ht=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ve=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:ve,token:Se}),we=async(e,t)=>Ae()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Ee(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),D=async(e,t,r)=>Ae()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var _t=async(e,t)=>Ae()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}`),Et=(e,t,r)=>Ee(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),wt=async(e,t)=>Ae()?(Y.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var oe=E("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;oe.log("Fetching available AI gateway providers");let e=await fetch(`${yt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return Be=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Rr=async(e,t)=>{let o=(await Tt()).providers[e];if(!o)return oe.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},It=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(n),oe.log("Requesting AI gateway information");let c=await Et(s,t.id,t.sessionId);if({token:r,url:i}=c,o=c.expires_at?c.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let u=o-Date.now()-6e4;u>0&&(n=setTimeout(()=>{a()},u))}};return await Promise.all([a(),Tt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Rr}};import q from"process";import J from"path";import be from"fs";import{fileURLToPath as Cr}from"url";import{createRequire as kr}from"module";import{execa as Or,execaCommand as Ao}from"execa";import{Transform as vr}from"stream";var Sr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Ar=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function br(){return Object.entries(process.env).filter(([e,t])=>!(!t||Sr.has(e)||Ar.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=br();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Nr(o),"g");r=r.replace(n,"******")}),r}function Nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends vr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=K(n);o(null,i)}};function xt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?K(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?K(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Te=null,Rt=e=>(Te&&Te.destroy(),Te=new V({totalAllowedTime:e}),Te),vt=()=>Te;var V=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var St="netlify-agent-runner-context.md",qe="task-history",B=".netlify",ee="results.md",He="assets";var te=1800*1e3;var At={name:"@netlify/agent-runner-cli",type:"module",version:"1.67.0-alpha.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json" "!src/skills/**/*.md"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.37","@anthropic-ai/sdk":"0.72.1","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",kaddidlehopper:"^0.1.2",minimist:"^1.2.8",openai:"6.17.0"}};var $r=Cr(import.meta.url),Fr=J.dirname($r),Dr=kr(import.meta.url),se=E("shell"),We=new Set,Lr={preferLocal:!0},k=(e,t,r)=>{let[o,n]=Mr(t,r),i={...Lr,...n},s=Or(e,o,i);Ur(s,i),jr(s);let a=r?.idleTimeout;return a&&a>0&&Gr(s,a),s};var Mr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Ur=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(q.stdout),e.stdout?.pipe(new ie).pipe(q.stdout),e.stderr?.pipe(new ie).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},Ke=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),se.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return se.error("Error killing process:",r),!1}},bt=e=>Ke(e,"SIGKILL"),Gr=(e,t)=>{let r=null,o=()=>{se.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Ke(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing idle process ${e.pid}`),bt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},jr=e=>{We.add(e);let t=vt();if(t){let r=t.onTimesUp(()=>{se.log(`Global timer expired, killing process ${e.pid}`),Ke(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing process ${e.pid} after timeout`),bt(e))},5e3)});e.on("exit",()=>{We.delete(e),r()}),e.on("error",()=>{We.delete(e),r()})}};function X(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let n=Dr.resolve(At.name),i=J.dirname(n);for(;i!==J.dirname(i);){let s=J.dirname(i);if(J.basename(s)==="node_modules"){let a=J.join(s,".bin",t);if(be.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(q.env.NODE_PATH){let n=J.join(q.env.NODE_PATH,".bin",t);if(be.existsSync(n))return n}let r=J.join(e,"node_modules",".bin",t);if(be.existsSync(r))return r;let o=J.join(Fr,"..","node_modules",".bin",t);if(be.existsSync(o))return o}var Yr=E("utils"),Br=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(d=>{n.push(d)});r=!0;let c,u=new Promise(d=>{c=d});return i=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await Br(t),!o)return r=!1,i=null,d;let p=o,m=n;o=null,n=[],d=await e(...p),m.forEach(g=>{g(d)})}})(),u};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ae=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},Pt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Yr.error("Could not parse JSON",o))}},Ct=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let u=Math.min(c-i.length,e.length);return`${i}${e.slice(0,u)}`}return e.slice(0,c)};var qr=50*1024,Je=(e,t=qr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as kt}from"buffer";import Hr from"path";var Ot=E("repo"),$t=async({config:e,isRetry:t})=>{Ot.info("Getting runner diffs");let r=await Kr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let h=Jr(n);await Vr(h)}Ot.info("Changes after processing"),await Xe();let i=await ze(n);await Ve(i);let s={stdio:["ignore","pipe","pipe"]},a=await k("git",["diff","--staged"],s),c=String(a.stdout??"");if(o=!!c,!o)return{hasChanges:!1,ignored:i};let u=await k("git",["diff","--staged","--binary"],s),d=String(u.stdout??""),p,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await k("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let h=await k("git",["diff",e.sha,"HEAD"],s);p=String(h.stdout??"");let T=await k("git",["diff",e.sha,"HEAD","--binary"],s),w=String(T.stdout??"");p!==w&&(m=kt.from(w).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:p,ignored:i};return c!==d&&(g.diffBinary=kt.from(d).toString("base64")),m&&(g.resultDiffBinary=m),g},Ve=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await k("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},Xe=async()=>{let e=await k("git",["status","-s"]);return String(e.stdout??"")},Ft=/.. (.+)?\.log$/,Wr=[Ft],Kr=async()=>{let e=await Xe();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
7
|
+
`);return i.length>e.length*.8?e:i}import{execSync as fn}from"child_process";import rr from"fs/promises";import gn from"path";import z from"process";import{getTracer as hn}from"@netlify/otel";import _e from"process";var ne=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},gt=e=>e instanceof ne;var ve=_e.env.NETLIFY_API_URL,Se=_e.env.NETLIFY_API_TOKEN,Y=E("api"),Ae=()=>_e.env.NETLIFY_LOCAL_MODE==="true",Ee=async(e,t={})=>{if(!ve||!Se)throw new Error("No API URL or token");let r=new URL(e,ve),o={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};_e.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(_e.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{Y.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ne(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new ne(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${a}`)}return s},ht=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ve=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:ve,token:Se}),we=async(e,t)=>Ae()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Ee(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),D=async(e,t,r)=>Ae()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var _t=async(e,t)=>Ae()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}`),Et=(e,t,r)=>Ee(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),wt=async(e,t)=>Ae()?(Y.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var oe=E("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;oe.log("Fetching available AI gateway providers");let e=await fetch(`${yt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return Be=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Rr=async(e,t)=>{let o=(await Tt()).providers[e];if(!o)return oe.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},It=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(n),oe.log("Requesting AI gateway information");let c=await Et(s,t.id,t.sessionId);if({token:r,url:i}=c,o=c.expires_at?c.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let u=o-Date.now()-6e4;u>0&&(n=setTimeout(()=>{a()},u))}};return await Promise.all([a(),Tt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Rr}};import q from"process";import J from"path";import be from"fs";import{fileURLToPath as Cr}from"url";import{createRequire as kr}from"module";import{execa as Or,execaCommand as Ao}from"execa";import{Transform as vr}from"stream";var Sr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Ar=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function br(){return Object.entries(process.env).filter(([e,t])=>!(!t||Sr.has(e)||Ar.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=br();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Nr(o),"g");r=r.replace(n,"******")}),r}function Nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends vr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=K(n);o(null,i)}};function xt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?K(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?K(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Te=null,Rt=e=>(Te&&Te.destroy(),Te=new V({totalAllowedTime:e}),Te),vt=()=>Te;var V=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var St="netlify-agent-runner-context.md",qe="task-history",B=".netlify",ee="results.md",He="assets";var te=1800*1e3;var At={name:"@netlify/agent-runner-cli",type:"module",version:"1.67.0-alpha.2",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json" "!src/skills/**/*.md"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.37","@anthropic-ai/sdk":"0.72.1","@google/gemini-cli":"0.27.3","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",kaddidlehopper:"^0.1.2",minimist:"^1.2.8",openai:"6.17.0"}};var $r=Cr(import.meta.url),Fr=J.dirname($r),Dr=kr(import.meta.url),se=E("shell"),We=new Set,Lr={preferLocal:!0},k=(e,t,r)=>{let[o,n]=Mr(t,r),i={...Lr,...n},s=Or(e,o,i);Ur(s,i),jr(s);let a=r?.idleTimeout;return a&&a>0&&Gr(s,a),s};var Mr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Ur=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(q.stdout),e.stdout?.pipe(new ie).pipe(q.stdout),e.stderr?.pipe(new ie).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},Ke=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),se.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return se.error("Error killing process:",r),!1}},bt=e=>Ke(e,"SIGKILL"),Gr=(e,t)=>{let r=null,o=()=>{se.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Ke(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing idle process ${e.pid}`),bt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},jr=e=>{We.add(e);let t=vt();if(t){let r=t.onTimesUp(()=>{se.log(`Global timer expired, killing process ${e.pid}`),Ke(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing process ${e.pid} after timeout`),bt(e))},5e3)});e.on("exit",()=>{We.delete(e),r()}),e.on("error",()=>{We.delete(e),r()})}};function X(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let n=Dr.resolve(At.name),i=J.dirname(n);for(;i!==J.dirname(i);){let s=J.dirname(i);if(J.basename(s)==="node_modules"){let a=J.join(s,".bin",t);if(be.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(q.env.NODE_PATH){let n=J.join(q.env.NODE_PATH,".bin",t);if(be.existsSync(n))return n}let r=J.join(e,"node_modules",".bin",t);if(be.existsSync(r))return r;let o=J.join(Fr,"..","node_modules",".bin",t);if(be.existsSync(o))return o}var Yr=E("utils"),Br=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(d=>{n.push(d)});r=!0;let c,u=new Promise(d=>{c=d});return i=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await Br(t),!o)return r=!1,i=null,d;let p=o,m=n;o=null,n=[],d=await e(...p),m.forEach(g=>{g(d)})}})(),u};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ae=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},Pt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Yr.error("Could not parse JSON",o))}},Ct=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let u=Math.min(c-i.length,e.length);return`${i}${e.slice(0,u)}`}return e.slice(0,c)};var qr=50*1024,Je=(e,t=qr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as kt}from"buffer";import Hr from"path";var Ot=E("repo"),$t=async({config:e,isRetry:t})=>{Ot.info("Getting runner diffs");let r=await Kr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let h=Jr(n);await Vr(h)}Ot.info("Changes after processing"),await Xe();let i=await ze(n);await Ve(i);let s={stdio:["ignore","pipe","pipe"]},a=await k("git",["diff","--staged"],s),c=String(a.stdout??"");if(o=!!c,!o)return{hasChanges:!1,ignored:i};let u=await k("git",["diff","--staged","--binary"],s),d=String(u.stdout??""),p,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await k("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let h=await k("git",["diff",e.sha,"HEAD"],s);p=String(h.stdout??"");let T=await k("git",["diff",e.sha,"HEAD","--binary"],s),w=String(T.stdout??"");p!==w&&(m=kt.from(w).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:p,ignored:i};return c!==d&&(g.diffBinary=kt.from(d).toString("base64")),m&&(g.resultDiffBinary=m),g},Ve=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await k("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},Xe=async()=>{let e=await k("git",["status","-s"]);return String(e.stdout??"")},Ft=/.. (.+)?\.log$/,Wr=[Ft],Kr=async()=>{let e=await Xe();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
8
|
`).filter(o=>Wr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Dt=async()=>{let{stdout:e}=await k("git",["rev-parse","HEAD"]);return String(e??"").trim()},Lt=async()=>{let{stdout:e}=await k("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},ze=async e=>{e||=await Xe();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
9
9
|
`).forEach(o=>{t.forEach(i=>{let s=o===`?? ${i}`,a=o.startsWith(`?? ${i}/`)||o.startsWith(`?? ${i}${Hr.sep}`);(s||a)&&r.push(`:!${i}`)});let n=o.match(Ft)?.[1];n&&r.push(`:!${n}.log`)}),r},Ze=async()=>{await k("git",["reset","--hard","HEAD"])},Jr=e=>{let t=e.split(`
|
|
10
10
|
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,a=s.join(""),c=n.trim(),u=i.trim();return r[a]?r[a].change=u:r[a]={filePath:a,stage:c,change:u},r},{});return Object.values(t)},Vr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(k("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import zr from"fs/promises";import Zr from"os";import jt from"path";import de from"process";import Qr from"readline";import en from"@anthropic-ai/sdk";import Qe from"path";import Xr from"fs/promises";var et=E("agent-output-utils");async function le({initialResult:e,agentName:t,hasError:r}){let o="",n=Qe.join(process.cwd(),B,ee);try{let i=await Xr.readFile(n,"utf-8");i&&(o=i,et.log(`Pulled result from ${Qe.relative(process.cwd(),n)}`))}catch{et.log(`No results file found at ${Qe.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ce({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o?.includes("503")&&(n=`The ${t} API is currently experiencing high load. Retrying automatically...`),n&&et.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ue(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error")||r?.includes("503"))}var Mt=e=>!!e;var L=E("runner_claude"),Ut="Claude Code",pe="claude-opus-4-6",Gt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,tn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(L.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Yt({aiGateway:e,config:t,model:r}){let o=r;if(e)if(t.modelVersionOverrides?.claude){let n=t.modelVersionOverrides?.claude?.[t.accountType];if(n){if(!await e.isModelAvailableForProvider("anthropic",n))throw new Error(`Model override '${n}' is not available for anthropic provider`);o=n}}else if(r){if(!await e.isModelAvailableForProvider("anthropic",r))throw new Error(`Model '${r}' is not available for anthropic provider`)}else!!pe&&await e.isModelAvailableForProvider("anthropic",pe)?(L.log(`Using default model: ${pe}`),o=pe):pe&&L.log(`Default model ${pe} is not available, proceeding without model specification`);return o}function Bt({aiGateway:e}){if(e){let{token:t,url:r}=e;if(!t||!r)throw new Error("No token or url provided from AI Gateway");de.env.ANTHROPIC_API_KEY=t,de.env.ANTHROPIC_BASE_URL=r}else if(!de.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided")}async function tt({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=de.cwd()}){let a=e,{prompt:c}=a,{model:u}=e,d="";Bt({aiGateway:o});let p=await Yt({config:e,aiGateway:o,model:u}),m=[],g=[],h={},T=0,w=0,y,R,$=[X(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...p?["--model",p]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",c],F=`${de.env.NVM_BIN}/node`;L.log(`Running ${F} ${$.join(" ")}`);let b=t.utils.run(F,$,{all:!0,env:de.env,cwd:s,idleTimeout:te});b.stdin?.end();let O=ae(()=>{r?.({steps:m,duration:w})},250),I=(v,f)=>{let l={...v,id:T};T+=1,g.push(l),m.push(l),f||O.flush(),O(),f&&O.flush()},N=Qr.createInterface({input:b.all});return N.on("error",v=>{L.error("Readline interface error",{error:v.message,stack:v.stack})}),N.on("line",v=>{let f=null;try{f=JSON.parse(v)}catch{L.log("Could not parse line",v)}f?.session_id&&f.session_id!==d&&(d=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&I({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?I({message:``}):L.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let _=l.input?.description&&`\`${l.input.description}\``;I({title:[Gt(l.name),_].filter(Boolean).join(" ")})}else l.id&&(h[l.id]=l);O.flush();break}case"tool_result":{let _=l.tool_use_id?h[l.tool_use_id]:void 0,Z;if(_){let Q=_.input?.file_path&&jt.relative(s,_.input.file_path),C=Q&&`\`${Q}\``;Z=[Gt(_.name||""),C].filter(Boolean).join(" ")}let ye=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(_?.name||""),W;if(typeof l.content=="string")W=l.content;else if(Array.isArray(l.content)){let Q=[];l.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?Q.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?Q.push(``):L.log(`Unsupported image type ${C.source.type}`,C.source):L.log(`Unsupported block type ${C?.type}`)}),W=Q.join(`
|
|
@@ -23,7 +23,7 @@ ${o}
|
|
|
23
23
|
|
|
24
24
|
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:o}},ln=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!sn.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
25
25
|
${n.trim()}
|
|
26
|
-
\`\`\``)}catch(i){M.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}},zt=async({aiGateway:e,config:t,model:r,prompt:o,systemPrompt:n="",outputFormat:i,maxTokens:s=4096})=>{if(Vt({aiGateway:e}),!await Jt({config:t,aiGateway:e,model:r}))throw new Error("Model is required");let u=await new nn().responses.parse({model:r,max_output_tokens:s,input:[n&&{role:"system",content:n},{role:"user",content:o}].filter(Boolean),...i&&{text:{format:{...i,name:"output"}}}});return{response:u,text:u.output_text}};import Pe from"fs/promises";import Qt from"os";import Ce from"path";import fe from"process";import cn from"readline";var G=E("runner_gemini"),Zt="Gemini CLI",ge="",un=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(G.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(G.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(G.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),pn={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},dn=async()=>{let e=Ce.join(Qt.homedir(),".gemini"),t=Ce.join(e,"settings.json");try{await Pe.mkdir(e,{recursive:!0});let r={};try{let o=await Pe.readFile(t,"utf-8");r=JSON.parse(o)}catch{G.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await Pe.writeFile(t,JSON.stringify(r,null,2),"utf-8"),G.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){G.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function nt({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=fe.cwd()}){let{accountType:s,prompt:a,modelVersionOverrides:c}=e,{model:u}=e;if(await dn(),n){let{token:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let _=c?.gemini?.[s];if(_){if(!await n.isModelAvailableForProvider("gemini",_))throw new Error(`Model override '${_}' is not available for gemini provider`);u=_}}if(!u)!!ge&&await n.isModelAvailableForProvider("gemini",ge)?(u=ge,G.log(`Using default model: ${ge}`)):ge&&G.log(`Default model ${ge} is not available, proceeding without model specification`);else if(u&&!c?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",u))throw new Error(`Model '${u}' is not available for gemini provider`);fe.env.GEMINI_API_KEY=f,fe.env.GOOGLE_GEMINI_BASE_URL=l}else if(!fe.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],p=[],m=[],g={},h=0,T=0,w,y,R=[X(i,"gemini"),...u?["--model",u]:[],"--yolo","--output-format","stream-json","-p",a],$=`${fe.env.NVM_BIN}/node`;G.log(`Running ${$} ${R.join(" ")}`);let F=t.utils.run($,R,{all:!0,env:fe.env,cwd:i,idleTimeout:te});F.stdin?.end();let b=ae(()=>{r?.({steps:d,duration:T}),o?.({steps:p,duration:T}),p=[]},250),O=(f,l)=>{f.id=h,h+=1,m.push(f),d.push(f),p.push(f),l||b.flush(),b(),l&&b.flush()},I=cn.createInterface({input:F.all});I.on("error",f=>{G.error("Readline interface error",{error:f.message,stack:f.stack})});let N="",v=()=>{N&&O({message:N.trim()}),N=""};return I.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let _=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:Pt(_,!1)?.error?.message||_||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(["message","result"].includes(l.type)||v(),l.type){case"message":{l.role!=="user"&&l.content&&(N+=l.content);break}case"tool_use":{let _=pn[l.tool_name]??l.tool_name,Z=l.parameters?.file_path,ye=Z&&Ce.relative(i,Z),W=l.parameters?.command,C={title:[_,ye&&`\`${ye}\``,W&&`\`${W}\``].filter(Boolean).join(" ")};g[l.tool_id]=C,b.flush();break}case"tool_result":{let _=g[l.tool_id];_&&(l.output&&(_.message=`\`\`\`
|
|
26
|
+
\`\`\``)}catch(i){M.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}},zt=async({aiGateway:e,config:t,model:r,prompt:o,systemPrompt:n="",outputFormat:i,maxTokens:s=4096})=>{if(Vt({aiGateway:e}),!await Jt({config:t,aiGateway:e,model:r}))throw new Error("Model is required");let u=await new nn().responses.parse({model:r,max_output_tokens:s,input:[n&&{role:"system",content:n},{role:"user",content:o}].filter(Boolean),...i&&{text:{format:{...i,name:"output"}}}});return{response:u,text:u.output_text}};import Pe from"fs/promises";import Qt from"os";import Ce from"path";import fe from"process";import cn from"readline";var G=E("runner_gemini"),Zt="Gemini CLI",ge="",un=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(G.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(G.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(G.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),pn={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},dn=async()=>{let e=Ce.join(Qt.homedir(),".gemini"),t=Ce.join(e,"settings.json");try{await Pe.mkdir(e,{recursive:!0});let r={};try{let o=await Pe.readFile(t,"utf-8");r=JSON.parse(o)}catch{G.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),r.skills||(r.skills={}),r.skills.enabled=!0,await Pe.writeFile(t,JSON.stringify(r,null,2),"utf-8"),G.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){G.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function nt({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=fe.cwd()}){let{accountType:s,prompt:a,modelVersionOverrides:c}=e,{model:u}=e;if(await dn(),n){let{token:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let _=c?.gemini?.[s];if(_){if(!await n.isModelAvailableForProvider("gemini",_))throw new Error(`Model override '${_}' is not available for gemini provider`);u=_}}if(!u)!!ge&&await n.isModelAvailableForProvider("gemini",ge)?(u=ge,G.log(`Using default model: ${ge}`)):ge&&G.log(`Default model ${ge} is not available, proceeding without model specification`);else if(u&&!c?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",u))throw new Error(`Model '${u}' is not available for gemini provider`);fe.env.GEMINI_API_KEY=f,fe.env.GOOGLE_GEMINI_BASE_URL=l}else if(!fe.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],p=[],m=[],g={},h=0,T=0,w,y,R=[X(i,"gemini"),...u?["--model",u]:[],"--yolo","--output-format","stream-json","-p",a],$=`${fe.env.NVM_BIN}/node`;G.log(`Running ${$} ${R.join(" ")}`);let F=t.utils.run($,R,{all:!0,env:fe.env,cwd:i,idleTimeout:te});F.stdin?.end();let b=ae(()=>{r?.({steps:d,duration:T}),o?.({steps:p,duration:T}),p=[]},250),O=(f,l)=>{f.id=h,h+=1,m.push(f),d.push(f),p.push(f),l||b.flush(),b(),l&&b.flush()},I=cn.createInterface({input:F.all});I.on("error",f=>{G.error("Readline interface error",{error:f.message,stack:f.stack})});let N="",v=()=>{N&&O({message:N.trim()}),N=""};return I.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let _=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:Pt(_,!1)?.error?.message||_||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(["message","result"].includes(l.type)||v(),l.type){case"message":{l.role!=="user"&&l.content&&(N+=l.content);break}case"tool_use":{let _=pn[l.tool_name]??l.tool_name,Z=l.parameters?.file_path,ye=Z&&Ce.relative(i,Z),W=l.parameters?.command,C={title:[_,ye&&`\`${ye}\``,W&&`\`${W}\``].filter(Boolean).join(" ")};g[l.tool_id]=C,b.flush();break}case"tool_result":{let _=g[l.tool_id];_&&(l.output&&(_.message=`\`\`\`
|
|
27
27
|
${l.output.trim()}
|
|
28
28
|
\`\`\``),O(_,!0));break}case"result":{T=l.stats?.duration_ms,l.status==="error"?y=l.error?.message:w=N.trim();break}case"error":{y=l.error;break}case"finished":break;default:{G.warn("Unhandled message type:",l.type);break}}}),await F.catch(f=>{({error:y,result:w}=un({catchError:f,runCmd:F,error:y,result:w,runnerName:"Gemini"}))}),I.close(),b.flush(),{steps:m,duration:T,result:await le({initialResult:w,agentName:Zt,hasError:!!y}),error:ce({error:y,agentName:Zt}),isRetryableError:ue(y)}}var er=async()=>{let e=Ce.join(Qt.homedir(),".gemini");await Pe.rm(e,{recursive:!0,force:!0})};var mn={codex:{runner:rt,clean:Xt},claude:{runner:tt,clean:qt},gemini:{runner:nt,clean:er}},tr=mn;var ke=E("init_stage"),nr=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await S(hn(),"init-stage",async n=>{let i=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":o||"unknown"});let s=tr[e.runner];if(!s)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=_n({apiToken:r});ht(a);let c=e.useGateway?await It({netlify:a,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!c});let u=5*1024,d=Nt(async({steps:h=[],duration:T})=>{let w=h.map(y=>{let R=y.title?Je(K(y.title),u):void 0,$=y.message?Je(K(y.message)):void 0;return{...y,title:R,message:$}});h.length=0;try{return await D(e.id,e.sessionId,{steps:w,duration:T})}catch(y){ke.error("persistSteps failed",{error:y?.message||y})}},t);ke.info("Adding build files to stage");let p=await ze();await Ve(p),z.env.NETLIFY_LOCAL_MODE||await yn();let m;e.hasRepo?e.sha?(m=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(m=await Dt(),await we(e.id,{sha:m}),n?.setAttributes({"init.sha.source":"current_commit"})):(m=await Lt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let g=performance.now()-i;return n?.setAttributes({"init.sha":m||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:c,context:a,persistSteps:d,runner:s,sha:m}}),yn=async()=>{let e="/usr/bin/git";try{e=fn("which git").toString().trim()||e}catch{}let t="/tmp/netlify-git-wrapper",r=gn.join(t,"git"),o=`#!/bin/bash
|
|
29
29
|
# Git wrapper that blocks add and commit commands
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netlify/agent-runner-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.67.0-alpha.
|
|
4
|
+
"version": "1.67.0-alpha.2",
|
|
5
5
|
"description": "CLI tool for running Netlify agents",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"dependencies": {
|
|
80
80
|
"@anthropic-ai/claude-code": "2.1.37",
|
|
81
81
|
"@anthropic-ai/sdk": "0.72.1",
|
|
82
|
-
"@google/gemini-cli": "0.
|
|
82
|
+
"@google/gemini-cli": "0.27.3",
|
|
83
83
|
"@netlify/otel": "^5.1.1",
|
|
84
84
|
"@openai/codex": "0.93.0",
|
|
85
85
|
"@opentelemetry/exporter-trace-otlp-grpc": "^0.208.0",
|