@netlify/agent-runner-cli 1.49.5-alpha → 1.50.0-alpha
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 +43 -44
- package/dist/bin.js +43 -44
- package/dist/index.js +42 -43
- package/package.json +6 -6
- package/patches/@google+gemini-cli+0.1.17.patch +0 -87
package/dist/index.js
CHANGED
|
@@ -1,82 +1,79 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),r=[],o=-1,n=0;for(;n<t.length;){let
|
|
3
|
-
`)),o=
|
|
1
|
+
import{createRequire as Zr}from"module";import{createTracerProvider as Yt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ve}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Bt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Ht}from"@netlify/otel";import{propagation as Je,context as Xe,W3CTraceContextPropagator as Kt}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Wt}from"@opentelemetry/exporter-trace-otlp-grpc";function E(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Ae=E("tracing"),ze=async(e,t,r)=>(await Yt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ve(new Ne),new Ve(new Wt({url:r.exporterUrl}))],instrumentations:[new Bt({skipHeaders:!0})]}),r.traceparent?(Je.setGlobalPropagator(new Kt),Je.extract(Xe.active(),{traceparent:r.traceparent,isRemote:!0})):Xe.active());function b(e,t,r){return Ae.log(`\u23F3 TRACE: ${t} starting...`),Ht(e,t,r)}var Ne=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[l,i]of Object.entries(o))l.includes("duration")&&typeof i=="number"?n.push(`${l}=${i.toFixed(2)}ms`):n.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ae.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ae.log(` \u274C Error: ${t.status.message}`)}};var qt=["error","failed","exception","fatal","panic","abort","crash"];function Ze(e){let t=e.split(`
|
|
2
|
+
`),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(qt.some(m=>l.includes(m))){let m=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),u=[];for(let f=m;f<=c;f++)u.push(t[f]);r.push(u.join(`
|
|
3
|
+
`)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
4
4
|
${a}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return s.length>e.length*.8?e:s}import we from"process";import{getTracer as Sr}from"@netlify/otel";import se from"process";var pe=se.env.NETLIFY_API_URL,fe=se.env.NETLIFY_API_TOKEN,M=T("api"),ge=()=>se.env.NETLIFY_LOCAL_MODE==="true",ie=async(e,t={})=>{if(!pe||!fe)throw new Error("No API URL or token");let r=new URL(e,pe),o={...t,headers:{...t.headers,Authorization:`Bearer ${fe}`}};se.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),s=n.ok&&n.status<=299;if(se.env.AGENT_RUNNERS_DEBUG==="true")M.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{M.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");M.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||M.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw a;return a},Xe=e=>{M.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(pe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(fe=e.constants.NETLIFY_API_TOKEN)},ze=()=>({apiUrl:pe,token:fe}),ae=async(e,t)=>ge()?(M.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ie(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>ge()?(M.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 Ze=async(e,t)=>ge()?(M.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ie(`/api/v1/agent_runners/${e}/sessions/${t}`),Qe=(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}}),et=async(e,t)=>ge()?(M.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"}),Ne=async(e,t)=>{M.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 X=T("ai_gateway"),be=null;var tt=async()=>{if(be)return be;X.log("Fetching available AI gateway providers");let e=await fetch(`${ze().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,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Ht=async(e,t)=>{let o=(await tt()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rt=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await Qe(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let y=o-Date.now()-6e4;y>0&&(n=setTimeout(()=>{u()},y))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Ht}};import Y from"process";import me from"path";import Ce from"fs";import{fileURLToPath as Xt}from"url";import{execa as zt,execaCommand as En}from"execa";import{Transform as Kt}from"stream";var qt=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_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","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"]),Wt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Vt(){return Object.entries(process.env).filter(([e,t])=>!(!t||qt.has(e)||Wt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function j(e){if(typeof e!="string")return e;let t=Vt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Jt(o),"g");r=r.replace(n,"******")}),r}function Jt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Kt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=j(n);o(null,s)}};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,s){let a=typeof o=="string"?j(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?j(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var le=null,ot=e=>(le&&le.destroy(),le=new K({totalAllowedTime:e}),le),st=()=>le;var K=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.`)}),s=null,a=null;o!==void 0&&(a=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};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 Zt=Xt(import.meta.url),Qt=me.dirname(Zt),he=T("shell"),Pe=new Set,er={preferLocal:!0},it=(e,t,r)=>{let[o,n]=tr(t,r),s={...er,...n},a=zt(e,o,s);return rr(a,s),or(a),a};var tr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},rr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Y.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new z).pipe(Y.stdout),e.stdout?.pipe(new z).pipe(Y.stdout),e.stderr?.pipe(new z).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),he.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return he.error("Error killing process:",r),!1}},nr=e=>at(e,"SIGKILL"),or=e=>{Pe.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{he.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(he.log(`Force killing process ${e.pid} after timeout`),nr(e))},5e3)});e.on("exit",()=>{Pe.delete(e),r()}),e.on("error",()=>{Pe.delete(e),r()})}};function Z(e,t){if(Y.env.NODE_PATH){let n=me.join(Y.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=me.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=me.join(Qt,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var lt="netlify-agent-runner-context.md",Oe="task-history",$e="netlify-context",L=".netlify",Q="results.md",De="assets";var sr=T("utils"),ir=e=>new Promise(t=>{setTimeout(t,e)}),ut=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(l=>{n.push(l)});r=!0;let i,y=new Promise(l=>{i=l});return s=(async()=>{await Promise.resolve();let l=await e(...u);for(i(l);;){if(await ir(t),!o)return r=!1,s=null,l;let c=o,m=n;o=null,n=[],l=await e(...c),m.forEach(E=>{E(l)})}})(),y};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ye=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):sr.error("Could not parse JSON",o))}},dt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let y=Math.min(i-s.length,e.length);return`${s}${e.slice(0,y)}`}return e.slice(0,i)};import{Buffer as pt}from"buffer";import ar from"path";var ft=async({config:e,netlify:t})=>{let r=await ur(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await cr(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let l=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,c,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let h=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==h&&(m=pt.from(h).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:c,ignored:s};return i!==l&&(E.diffBinary=pt.from(l).toString("base64")),m&&(E.resultDiffBinary=m),E},lr=["?? mise.toml","?? deno.lock","?? .npmrc",/\?\? .+?\.log/],ur=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
-
`).filter(
|
|
9
|
-
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`,await ue.writeFile(R,p,"utf-8"),O.log("Updated Codex config with web_search enabled"))}catch(g){throw O.warn("Failed to setup Codex config and credentials",{error:g.message}),new Error(`Codex setup failed: ${g.message}`)}let N=[Z(W.cwd(),"codex"),"exec","--yolo","--json","--config","web_search=true",...i?["--model",i]:[],a].filter(Boolean);O.log(`Running ${h} ${N.join(" ")}`);let v=t.utils.run(h,N,{all:!0,env:W.env});v.stdin?.end(),v.stdout?.on("data",g=>{O.log("[STDOUT]",g.toString())}),v.stderr?.on("data",g=>{O.log("[STDERR]",g.toString())}),v.all?.on("data",g=>{O.log("[ALL]",g.toString())});let S=hr.createInterface({input:v.all});return S.on("error",g=>{O.error("Readline interface error",{error:g.message,stack:g.stack})}),S.on("line",g=>{O.log("Received line from Codex:",g);let p=null;try{p=JSON.parse(g)}catch{O.log("Could not parse line",g);return}let f=[],_=!1;if(p?.duration_ms&&(E=p.duration_ms,_=!0),p?.type==="local_shell_call")c[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let d=_r(c[p.call_id],p);d&&(d.id=m,m+=1,l.push(d),y.push(d),f.push(d),_=!0)}else p?.type==="message"&&p.role==="assistant"?I=p.content.map(d=>d.text).join(`
|
|
18
|
-
`):p?.type==="message"&&p.role==="system"&&(w=p.content.map(d=>d.text).join(`
|
|
19
|
-
`));_&&(r?.({steps:y,duration:E}),o?.({steps:f,duration:E}))}),await v.catch(g=>{let p=yr({catchError:g,runCmd:v,error:w,result:I,runnerName:"Codex"});w=p.error,I=p.result}),S.close(),!I&&!w&&v.exitCode===0&&(w="Codex process completed successfully but produced no output",O.error("Codex process exited with code 0 but no result or error was captured")),{steps:l,duration:E,result:await ee({initialResult:I,agentName:wt,hasError:!!w}),error:te({error:w,agentName:wt}),isRetryableError:re(w)}}var It=async()=>{let e=_e.join(Tt.homedir(),".codex");await ue.rm(e,{recursive:!0,force:!0})},Er=new Set(["bash","-lc"]),_r=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Er.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import we from"process";import{getTracer as $r}from"@netlify/otel";import ie from"process";var fe=ie.env.NETLIFY_API_URL,ge=ie.env.NETLIFY_API_TOKEN,M=E("api"),me=()=>ie.env.NETLIFY_LOCAL_MODE==="true",ae=async(e,t={})=>{if(!fe||!ge)throw new Error("No API URL or token");let r=new URL(e,fe),o={...t,headers:{...t.headers,Authorization:`Bearer ${ge}`}};ie.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),s=n.ok&&n.status<=299;if(ie.env.AGENT_RUNNERS_DEBUG==="true")M.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{M.log(` ${i}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");M.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||M.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw a;return a},Qe=e=>{M.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(fe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ge=e.constants.NETLIFY_API_TOKEN)},et=()=>({apiUrl:fe,token:ge}),le=async(e,t)=>me()?(M.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>me()?(M.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var tt=async(e,t)=>me()?(M.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`),rt=(e,t,r)=>ae(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),nt=async(e,t)=>me()?(M.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"}}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),be=async(e,t)=>{M.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 z=E("ai_gateway"),Ce=null;var ot=async()=>{if(Ce)return Ce;z.log("Fetching available AI gateway providers");let e=await fetch(`${et().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 Ce=t,z.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await ot()).providers[e];if(!o)return z.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return z.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},st=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),z.log("Requesting AI gateway information");let i=await rt(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,z.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),ot()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import Y from"process";import he from"path";import Pe from"fs";import{fileURLToPath as er}from"url";import{execa as tr,execaCommand as An}from"execa";import{Transform as Jt}from"stream";var Xt=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_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","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"]),zt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Xt.has(e)||zt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function j(e){if(typeof e!="string")return e;let t=Zt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Qt(o),"g");r=r.replace(n,"******")}),r}function Qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z=class extends Jt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=j(n);o(null,s)}};function it(){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,s){let a=typeof o=="string"?j(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?j(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var ue=null,at=e=>(ue&&ue.destroy(),ue=new W({totalAllowedTime:e}),ue),lt=()=>ue;var W=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.`)}),s=null,a=null;o!==void 0&&(a=new Promise((l,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};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 rr=er(import.meta.url),nr=he.dirname(rr),ye=E("shell"),Oe=new Set,or={preferLocal:!0},F=(e,t,r)=>{let[o,n]=sr(t,r),s={...or,...n},a=tr(e,o,s);return ir(a,s),lr(a),a};var sr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},ir=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Y.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Z).pipe(Y.stdout),e.stdout?.pipe(new Z).pipe(Y.stdout),e.stderr?.pipe(new Z).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},ut=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),ye.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ye.error("Error killing process:",r),!1}},ar=e=>ut(e,"SIGKILL"),lr=e=>{Oe.add(e);let t=lt();if(t){let r=t.onTimesUp(()=>{ye.log(`Global timer expired, killing process ${e.pid}`),ut(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ye.log(`Force killing process ${e.pid} after timeout`),ar(e))},5e3)});e.on("exit",()=>{Oe.delete(e),r()}),e.on("error",()=>{Oe.delete(e),r()})}};function Q(e,t){if(Y.env.NODE_PATH){let n=he.join(Y.env.NODE_PATH,".bin",t);if(Pe.existsSync(n))return n}let r=he.join(e,"node_modules",".bin",t);if(Pe.existsSync(r))return r;let o=he.join(nr,"..","node_modules",".bin",t);if(Pe.existsSync(o))return o}var ct="netlify-agent-runner-context.md",Fe="task-history",$e="netlify-context",L=".netlify",ee="results.md",De="assets";var ur=E("utils"),cr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(c=>{n.push(c)});r=!0;let i,m=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await cr(t),!o)return r=!1,s=null,c;let u=o,f=n;o=null,n=[],c=await e(...u),f.forEach(h=>{h(c)})}})(),m};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},Ee=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...l){n=l,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,i=s;o=null,n=null,s=null,e.apply(i,l)}},a},dt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ur.error("Could not parse JSON",o))}},ft=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let m=Math.min(i-s.length,e.length);return`${s}${e.slice(0,m)}`}return e.slice(0,i)};import{Buffer as gt}from"buffer";import pr from"path";var mt=E("repo"),ht=async({config:e})=>{mt.info("Getting runner diffs");let t=await fr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=gr(o);await mr(n),mt.info("Changes after processing"),await ke();let s=await Ue(o);await Le(s);let a={stdio:["ignore","pipe","pipe"]},i=(await F("git",["diff","--staged"],a)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let c=(await F("git",["diff","--staged","--binary"],a)).stdout,u,f;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),u=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==g&&(f=gt.from(g).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==c&&(h.diffBinary=gt.from(c).toString("base64")),f&&(h.resultDiffBinary=f),h},Le=async(e=[])=>{await F("git",["add",".",...e])},ke=async()=>(await F("git",["status","-s"])).stdout,yt=/.. (.+)?\.log$/,dr=[yt],fr=async()=>{let e=await ke();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`).filter(o=>dr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Et=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},_t=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},Ue=async e=>{e||=await ke();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
9
|
+
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${pr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(yt)?.[1];n&&r.push(`:!${n}.log`)}),r},wt=async()=>{await F("git",["reset","--hard","HEAD"])},gr=e=>{let t=e.split(`
|
|
10
|
+
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),m=s.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:i,change:m},r},{});return Object.values(t)},mr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(F("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import yr from"fs/promises";import Er from"os";import xt from"path";import q from"process";import _r from"readline";import Me from"path";import hr from"fs/promises";var Ge=E("agent-output-utils");async function te({initialResult:e,agentName:t,hasError:r}){let o="",n=Me.join(process.cwd(),L,ee);try{let s=await hr.readFile(n,"utf-8");s&&(o=s,Ge.log(`Pulled result from ${Me.relative(process.cwd(),n)}`))}catch{Ge.log(`No results file found at ${Me.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function re({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.`),n&&Ge.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ne(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"))}var k=E("runner_claude"),Tt="Claude Code",_e="claude-sonnet-4-5-20250929",It=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,wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(k.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?(k.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}):(k.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function je({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:m}=a,{model:c}=a,u="";if(o){let{token:y,url:d}=o;if(!y||!d)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let p=m?.claude?.[l];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);c=p}}else if(c){if(!await o.isModelAvailableForProvider("anthropic",c))throw new Error(`Model '${c}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",_e)?(c=_e,k.log(`Using default model: ${_e}`)):k.log(`Default model ${_e} is not available, proceeding without model specification`);q.env.ANTHROPIC_API_KEY=y,q.env.ANTHROPIC_BASE_URL=d}else if(!q.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],h=[],w={},T=0,g=0,R,x,N=[Q(q.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],I=`${q.env.NVM_BIN}/node`;k.log(`Running ${I} ${N.join(" ")}`);let _=t.utils.run(I,N,{all:!0,env:q.env});_.stdin?.end();let v=Ee(()=>{r?.({steps:f,duration:g})},250),S=(y,d)=>{let p={...y,id:T};T+=1,h.push(p),f.push(p),d||v.flush(),v(),d&&v.flush()},A=_r.createInterface({input:_.all});return A.on("error",y=>{k.error("Readline interface error",{error:y.message,stack:y.stack})}),A.on("line",y=>{let d=null;try{d=JSON.parse(y)}catch{k.log("Could not parse line",y)}d?.session_id&&d.session_id!==u&&(u=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&S({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?S({message:``}):k.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let O=p.input?.description&&`\`${p.input.description}\``;S({title:[It(p.name),O].filter(Boolean).join(" ")})}else p.id&&(w[p.id]=p);v.flush();break}case"tool_result":{let O=p.tool_use_id?w[p.tool_use_id]:void 0,X;if(O){let B=O.input?.file_path&&xt.relative(q.cwd(),O.input.file_path),P=B&&`\`${B}\``;X=[It(O.name||""),P].filter(Boolean).join(" ")}let de=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(O?.name||""),K;if(typeof p.content=="string")K=p.content;else if(Array.isArray(p.content)){let B=[];p.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?B.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?B.push(``):k.log(`Unsupported image type ${P.source.type}`,P.source):k.log(`Unsupported block type ${P?.type}`)}),K=B.join(`
|
|
11
|
+
|
|
12
|
+
`)}de&&K&&(K=`\`\`\`
|
|
13
|
+
${K.trim()}
|
|
14
|
+
\`\`\``),S({title:X,message:K},!0);break}case"thinking":{p.thinking&&S({title:"Thinking",message:p.thinking},!0);break}default:k.log(`Message content type is not supported ${p.type}`,p)}}):d?.type==="result"&&(g=d.duration_ms||0,d.is_error?x=d.result:R=d.result,[h,f].forEach(p=>{p[p.length-1]?.message===R&&p.pop()}))}),await _.catch(y=>{({error:x,result:R}=wr({catchError:y,runCmd:_,error:x,result:R,runnerName:"Claude"}))}),A.close(),v.flush(),{steps:h,duration:g,result:await te({initialResult:R,agentName:Tt,hasError:!!x}),error:re({error:x,agentName:Tt}),isRetryableError:ne(x),agentSessionId:u}}var Rt=async()=>{let e=xt.join(Er.homedir(),".claude");await yr.rm(e,{recursive:!0,force:!0})};import Tr from"fs/promises";import Ir from"os";import xr from"path";import oe from"process";import Rr from"readline";var V=E("runner_codex"),vt="Codex CLI",vr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(V.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?(V.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}):(V.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ye({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:I,url:_}=n;if(!I||!_)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let v=l?.codex?.[s];if(v){if(!await n.isModelAvailableForProvider("openai",v))throw new Error(`Model override '${v}' is not available for openai provider`);i=v}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);oe.env.OPENAI_API_KEY=I,oe.env.OPENAI_BASE_URL=_}else if(!oe.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],c=[],u={},f=0,h=0,w,T,g=[Q(oe.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),R=`${oe.env.NVM_BIN}/node`;V.log(`Running ${R} ${g.join(" ")}`);let x=t.utils.run(R,g,{all:!0,env:{...oe.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),N=Rr.createInterface({input:x.all});return N.on("error",I=>{V.error("Readline interface error",{error:I.message,stack:I.stack})}),N.on("line",I=>{let _=null;try{_=JSON.parse(I)}catch{V.log("Could not parse line",I);return}let v=[],S=!1;if(_?.duration_ms&&(h=_.duration_ms,S=!0),_?.type==="local_shell_call")u[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let A=Ar(u[_.call_id],_);A&&(A.id=f,f+=1,c.push(A),m.push(A),v.push(A),S=!0)}else _?.type==="message"&&_.role==="assistant"?w=_.content.map(A=>A.text).join(`
|
|
15
|
+
`):_?.type==="message"&&_.role==="system"&&(T=_.content.map(A=>A.text).join(`
|
|
16
|
+
`));S&&(r?.({steps:m,duration:h}),o?.({steps:v,duration:h}))}),await x.catch(I=>{let _=vr({catchError:I,runCmd:x,error:T,result:w,runnerName:"Codex"});T=_.error,w=_.result}),N.close(),{steps:c,duration:h,result:await te({initialResult:w,agentName:vt,hasError:!!T}),error:re({error:T,agentName:vt}),isRetryableError:ne(T)}}var St=async()=>{let e=xr.join(Ir.homedir(),".codex");await Tr.rm(e,{recursive:!0,force:!0})},Sr=new Set(["bash","-lc"]),Ar=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Sr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
20
17
|
${n.trim()}
|
|
21
|
-
\`\`\``)}catch(s){
|
|
22
|
-
${d.trim()}
|
|
23
|
-
\`\`\``),
|
|
18
|
+
\`\`\``)}catch(s){V.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Nr from"fs/promises";import br from"os";import Nt from"path";import J from"process";import Cr from"readline";var se=E("runner_gemini"),At="Gemini CLI",Pr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(se.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?(se.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}):(se.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Or={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"};async function Be({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:y,url:d}=n;if(!y||!d)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let p=l?.gemini?.[s];if(p){if(!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model override '${p}' is not available for gemini provider`);i=p}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);J.env.GEMINI_API_KEY=y,J.env.GOOGLE_GEMINI_BASE_URL=d}else if(!J.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],u=[],f={},h=0,w=0,T,g,R=[Q(J.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","--output-format","stream-json","-p",a],x=`${J.env.NVM_BIN}/node`;se.log(`Running ${x} ${R.join(" ")}`);let N=t.utils.run(x,R,{all:!0,env:J.env});N.stdin?.end();let I=Ee(()=>{r?.({steps:m,duration:w}),o?.({steps:c,duration:w}),c=[]},250),_=(y,d)=>{y.id=h,h+=1,u.push(y),m.push(y),c.push(y),d||I.flush(),I(),d&&I.flush()},v=Cr.createInterface({input:N.all});v.on("error",y=>{se.error("Readline interface error",{error:y.message,stack:y.stack})});let S="",A=()=>{S&&_({message:S.trim()}),S=""};return v.on("line",y=>{let d=null;try{if(y.startsWith("[API Error")){let p=y.match(/\[api error: (.+?)]$/i)?.[1];d={type:"error",value:dt(p,!1)?.error?.message||p||"Gemini encountered error"}}else d=JSON.parse(y)}catch{return}if(d)switch(["message","result"].includes(d.type)||A(),d.type){case"message":{d.role!=="user"&&d.content&&(S+=d.content);break}case"tool_use":{let p=Or[d.tool_name]??d.tool_name,O=d.parameters?.file_path,X=O&&Nt.relative(J.cwd(),O),de=d.parameters?.command,B={title:[p,X&&`\`${X}\``,de&&`\`${de}\``].filter(Boolean).join(" ")};f[d.tool_id]=B,I.flush();break}case"tool_result":{let p=f[d.tool_id];p&&(d.output&&(p.message=`\`\`\`
|
|
19
|
+
${d.output.trim()}
|
|
20
|
+
\`\`\``),_(p,!0));break}case"result":{w=d.stats?.duration_ms,d.status==="error"?g=d.error?.message:T=S.trim();break}case"error":{g=d.error;break}case"finished":break;default:{se.warn("Unhandled message type:",d.type);break}}}),await N.catch(y=>{({error:g,result:T}=Pr({catchError:y,runCmd:N,error:g,result:T,runnerName:"Gemini"}))}),v.close(),I.flush(),{steps:u,duration:w,result:await te({initialResult:T,agentName:At,hasError:!!g}),error:re({error:g,agentName:At}),isRetryableError:ne(g)}}var bt=async()=>{let e=Nt.join(br.homedir(),".gemini");await Nr.rm(e,{recursive:!0,force:!0})};var Fr={codex:{runner:Ye,clean:St},claude:{runner:je,clean:Rt},gemini:{runner:Be,clean:bt}},Ct=Fr;var Dr=E("init_stage"),Pt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b($r(),"init-stage",async n=>{let s=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.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Ct[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=Lr({apiToken:r});Qe(l);let i=e.useGateway?await st({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=pt(({steps:h=[],duration:w})=>{let T=h.map(g=>({...g,title:g.title?j(g.title):void 0,message:g.message?j(g.message):void 0}));return h.length=0,G(e.id,e.sessionId,{steps:T,duration:w})},t);Dr.info("Adding build files to stage");let c=await Ue();await Le(c);let u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await Et(),await le(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await _t(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-s;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:i,context:l,persistSteps:m,runner:a,sha:u}}),Lr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:we.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||we.env.NETLIFY_API_TOKEN,SITE_ID:we.env.SITE_ID,FUNCTIONS_DIST:we.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:F}});import{getTracer as He}from"@netlify/otel";import kr from"crypto";import H from"fs/promises";import D from"path";import U from"process";var $=E("context"),Ur=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:U.env.NETLIFY_TEAM_ID,userId:U.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:U.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Mr=10,Gr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),L,o),s=0;for(;await jr(n);){if(s>=Mr)throw new Error("Failed to generate context file");o=`${t}-${kr.randomUUID().slice(0,5)}${r}`,n=D.join(U.cwd(),L,o),s+=1}return o},jr=async e=>{try{return await H.access(e),!0}catch{return!1}},Yr=async()=>{try{$.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return $.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(o=>o&&typeof o=="object"&&o.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?($.warn("Catchall consumer missing or invalid contextScopes"),null):r:($.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?$.warn("Netlify features context request timed out"):$.warn("Failed to fetch Netlify features context:",e.message),null}},Br=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await H.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?$.warn(`Download timeout for ${e}`):$.warn(`Failed to download context file ${e}:`,r.message),!1}},Te=null,Hr=async()=>{if(Te)return Te;let e=await Yr();if(!e)return[];let t=D.join(U.cwd(),L,$e);await H.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return $.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=D.join(t,a),i=D.join(L,$e,a);return $.log(`Downloading ${s.scope} context...`),await Br(s.endpoint,l)?($.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Te=(await Promise.all(r)).filter(n=>n!==null),Te},Ot=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Ur(t),s=await Gr(ct),a=D.join(U.cwd(),L);await H.mkdir(a,{recursive:!0});let l=D.join(L,s),i=D.join(U.cwd(),l),m=D.join(U.cwd(),L,ee);try{await H.unlink(m),$.log(`Deleted old results file: ${m}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
24
21
|
Your task is to analyze and fix the build errors.
|
|
25
22
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
26
23
|
Don't try to run build by yourself. Just fix the errors.
|
|
27
24
|
|
|
28
25
|
<build_error_context>
|
|
29
26
|
${o}
|
|
30
|
-
</build_error_context>`:"",
|
|
27
|
+
</build_error_context>`:"",u="";r.siteContext&&r.siteContext.length!==0&&(u=`
|
|
31
28
|
<project_rules>
|
|
32
|
-
${r.siteContext.filter(
|
|
29
|
+
${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
|
|
33
30
|
|
|
34
31
|
`)}
|
|
35
32
|
</project_rules>
|
|
36
|
-
`);let
|
|
33
|
+
`);let f="";if(r.sessionHistoryContext?.length){let g=D.join(U.cwd(),L,Fe);await H.mkdir(g,{recursive:!0});let R=await Promise.all(r.sessionHistoryContext.map(async(x,N)=>{let I=N+1,_=`attempt-${I}.md`,v=D.join(g,_),S=D.join(L,Fe,_),A=`# Task History - Attempt ${I}
|
|
37
34
|
|
|
38
35
|
## Request - what the user asked for
|
|
39
|
-
${
|
|
36
|
+
${x.request}
|
|
40
37
|
|
|
41
38
|
---
|
|
42
39
|
|
|
43
40
|
## Response - what the agent replied with after its work
|
|
44
41
|
|
|
45
|
-
${
|
|
46
|
-
`;return await H.writeFile(
|
|
42
|
+
${x.response}
|
|
43
|
+
`;return await H.writeFile(v,A,"utf-8"),$.log(`Created history file: ${S}`),S}));f+=`
|
|
47
44
|
<session_history_context>
|
|
48
45
|
History of prior work on this task.
|
|
49
46
|
You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
|
|
50
47
|
|
|
51
|
-
${
|
|
48
|
+
${R.slice(-5).map(x=>`- ${x}`).join(`
|
|
52
49
|
`)}
|
|
53
50
|
|
|
54
51
|
</session_history_context>
|
|
55
|
-
`}let
|
|
52
|
+
`}let h=await Hr(),w="";h.length>0&&(w=`
|
|
56
53
|
<netlify_features_context>
|
|
57
54
|
If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
58
55
|
DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
|
|
59
56
|
|
|
60
|
-
${
|
|
57
|
+
${h.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
61
58
|
`)}
|
|
62
59
|
|
|
63
60
|
Refer to these files when working with specific Netlify features.
|
|
64
61
|
</netlify_features_context>
|
|
65
|
-
`);let
|
|
62
|
+
`);let T=`
|
|
66
63
|
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
67
64
|
|
|
68
65
|
<request>
|
|
69
66
|
<user_request>
|
|
70
67
|
${r.prompt}
|
|
71
68
|
</user_request>
|
|
72
|
-
${
|
|
69
|
+
${c}
|
|
73
70
|
</request>
|
|
74
71
|
|
|
75
72
|
<requirements>
|
|
76
73
|
<responses>
|
|
77
74
|
- Do not speak in first person. You may speak as "the agent".
|
|
78
|
-
- When work is complete, write a changes summary in ${a}/${
|
|
79
|
-
- If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${a}/${
|
|
75
|
+
- When work is complete, write a changes summary in ${a}/${ee} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
|
|
76
|
+
- If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${a}/${ee} file.
|
|
80
77
|
- Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
|
|
81
78
|
- NEVER look into the \`.git\` folder
|
|
82
79
|
- NEVER print potentially sensitive values (like secrets) in the planning output or results
|
|
@@ -85,7 +82,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
85
82
|
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${De} folder
|
|
86
83
|
- move assets from ${a}/${De} folder to the project assets folder if they are referenced in a code or applied changes
|
|
87
84
|
</attachements>
|
|
88
|
-
${
|
|
85
|
+
${u}
|
|
89
86
|
</requirements>
|
|
90
87
|
|
|
91
88
|
<extra_context>
|
|
@@ -102,34 +99,36 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
102
99
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
103
100
|
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
104
101
|
</environment>
|
|
105
|
-
${
|
|
102
|
+
${w}
|
|
106
103
|
<docs>
|
|
107
104
|
- Netlify Docs: https://docs.netlify.com
|
|
108
105
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
109
106
|
</docs>
|
|
110
107
|
</extra_context>
|
|
111
108
|
|
|
112
|
-
${
|
|
113
|
-
`;return await H.writeFile(i,
|
|
109
|
+
${f}
|
|
110
|
+
`;return await H.writeFile(i,T,"utf-8"),$.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
|
|
114
111
|
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
115
112
|
|
|
116
113
|
<request>
|
|
117
114
|
<user_request>
|
|
118
115
|
${r.prompt}
|
|
119
116
|
</user_request>
|
|
120
|
-
${
|
|
117
|
+
${c}
|
|
121
118
|
</request>
|
|
122
119
|
|
|
123
120
|
Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
124
|
-
`),
|
|
125
|
-
${
|
|
126
|
-
${
|
|
127
|
-
`.trim(),
|
|
121
|
+
`),T};var Kr=E("prompt"),Ft=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Ot({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Kr.log("Contextful Prompt:",n),{prompt:n}};var Ie=E("inference_stage"),$t=5,xe=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:l,attempt:i,contextPrefix:m,priorAgentSessionId:c}=e;Ie.log(`Running inference stage, attempt ${i} of ${$t}`);let u=await b(He(),"inference-stage",async f=>{f?.setAttributes({"inference.attempt":i||1}),it();let{prompt:h}=await b(He(),"compose-prompt",async()=>await Ft({cliPath:t,config:r,buildErrorContext:Wr(n),netlify:o})),w=`
|
|
122
|
+
${m||""}
|
|
123
|
+
${h}
|
|
124
|
+
`.trim(),T={...r,prompt:w},g=await b(He(),`run-${r.runner}`,async()=>await s({aiGateway:l,config:T,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:c}));return g.result&&(g.result=j(g.result)),g.error&&(g.error=j(g.error)),await a.flush(),g});if(u.error){if(Ie.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:i||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!i||i<$t))return Ie.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await xe({...e,attempt:(i||1)+1,priorAgentSessionId:u.agentSessionId,contextPrefix:u.agentSessionId?"":"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw Ie.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},Wr=e=>!e||e.length===0?"":`
|
|
128
125
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
129
126
|
|
|
130
127
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
131
128
|
|
|
132
129
|
${e.pop()}
|
|
133
|
-
`;import
|
|
134
|
-
Preview deploy created successfully:`,{deployId:
|
|
130
|
+
`;import Jr from"process";import{getTracer as Ke}from"@netlify/otel";import{getTracer as qr}from"@netlify/otel";var ce=E("deploy"),Dt=async e=>await b(qr(),"create-preview-deploy",async t=>Vr(e,t)),Vr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},l)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ce.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ce.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let m=s||"netlify";ce.log(`Running: ${m} ${i.join(" ")}`),l?.setAttributes({cmd:m,args:i});let c=await e.utils.run(m,i,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(c.stdout.trim());l?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),ce.log(`
|
|
131
|
+
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let f={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(f.sourceZipFilename=u.source_zip_filename),f}catch(i){throw ce.error("Failed to create preview deploy via CLI:",i),l?.setAttributes({success:!1,error:i.message}),i}};var pe=E("deploy_stage"),We=async e=>await b(Ke(),"run-deploy-stage",async()=>Xr(e)),Xr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ke(),"get-runner-diffs",async()=>await ht({config:t,netlify:r}));if(pe.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:m}=s,c=!0;pe.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let u=null;if(o!==void 0&&c)try{let f;try{let h=await b(Ke(),"get-runner-session",async()=>await tt(t.id,t.sessionId));h?.title&&(f=h.title)}catch(h){pe.warn("Failed to fetch session title, using fallback message:",h.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),u=await Dt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:ft(t.id,Jr.env.SITE_NAME),filter:n})}catch(f){return pe.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:m,deployError:f instanceof Error?f.message:String(f)}}return pe.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:u,diffBinary:i,resultDiffBinary:m}};import{getTracer as ve}from"@netlify/otel";async function Lt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var Re=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
|
|
132
|
+
`);for(let a of s)if(a.startsWith("diff --git")){if(o&&n.length>0){let i=this.containsNetlifyForm(n,o);i&&r.push(i)}let l=a.split(" ");o=l[l.length-1].replace(/^b\//,""),n=[]}else a.startsWith("+")&&!a.startsWith("+++")&&n.push(a.slice(1));if(o&&n.length>0){let a=this.containsNetlifyForm(n,o);a&&r.push(a)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let o=t.join(`
|
|
133
|
+
`),n=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,m=Math.max(0,i-20),c=Math.min(o.length,i+l[0].length+20),u=o.slice(m,c).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${u}`}}}return null}};var C=E("cleanup_stage"),kt=async e=>await b(ve(),"cleanup-stage",async()=>zr(e)),qe=1024*1024*10,zr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result:r||"Done",duration:o};l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename);let m=t||s||n||a;if(m){let c=new Re,u=t||s||"",f=c.scanDiffForForms(u);f.detected?(C.log("Detected Netlify form(s) in diff:"),f.matches.forEach(({file:h,snippet:w})=>{C.log(` - ${h}: ${w}`)}),i.has_netlify_form=!0):C.log("Did not detect Netlify form(s) in diff"),C.log("Did not detect Netlify form(s) in diff")}if(m)try{C.log("Getting pre-signed URLs for diff upload");let c=await nt(e.id,e.sessionId),u=[];(t||s)&&u.push(be(c.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=c.result.s3_key,C.log("Successfully uploaded result_diff to S3")})),(n||a)&&u.push(be(c.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=c.cumulative.s3_key,C.log("Successfully uploaded cumulative_diff to S3")})),C.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||a)&&(C.log("Updating agent runner with cumulative diff S3 key"),await b(ve(),"update-runner",async()=>{await le(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){C.error("S3 upload failed, falling back to inline diffs:",c);let u=Buffer.byteLength(t||s||""),f=Buffer.byteLength(a||n||"");if(u>qe||f>qe){let h=`Diffs exceed maximum inline size of ${qe} bytes.`;throw C.error(h),new Error(h)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,C.log("Updating agent runner with inline diffs (fallback)"),await b(ve(),"update-runner",async()=>{await le(e.id,{result_diff:n,result_diff_binary:a})}))}else C.log("No diffs to upload");return C.log("Updated agent runner with result"),await Lt(async()=>await b(ve(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(c,u)=>{C.error(`Error updating agent runner session (attempt ${c}):`,u),C.log("Retrying...")}}),C.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ut,shutdownTracers as Qr,withActiveSpan as Mt}from"@netlify/otel";var en=Zr(import.meta.url),Gt=en("../package.json"),jt=E("pipeline_index"),Se=3,Ds=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=at(W.timeUnits.hours(4)),m=await ze(Gt.version,e.id,a);try{await Mt(Ut(),"run-pipeline",{},m,async()=>{let c,{aiGateway:u,context:f,persistSteps:h,runner:w,sha:T}=await i("init",()=>Pt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Gt.version}),W.timeUnits.minutes(10));l=w.clean,e.sha=T;let{runnerResult:g}=await i("inference",()=>xe({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:u}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let R=await i("deploy",()=>We({cliPath:r,config:e,context:f,result:g.result,filter:s})),x=g,N=[];if(R.hasChanges&&R.deployError){N.push(Ze(R.deployError));let y=1;for(;y<=Se&&!R.previewInfo;)jt.log(`Deploy attempt had errors. Retrying. ${y}/${Se}`),await Mt(Ut(),"deploy-stage",async d=>{d?.setAttributes({"stage.attempt":y});let{runnerResult:p}=await i(`inference-retry-${y}`,()=>xe({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:u,buildErrors:N,priorAgentSessionId:g.agentSessionId}));x={...p,steps:[...x.steps||[],...p.steps||[]],duration:(x.duration||0)+(p.duration||0)},R=await i(`deploy-retry-${y}`,()=>We({cliPath:r,config:e,context:f,result:p.result,filter:s})),R.deployError&&N.push(R.deployError),y++});y>Se&&!R.previewInfo&&(c=new Error(`Deploy validation failed after ${Se} attempts`))}let{diff:I,resultDiff:_,previewInfo:v,diffBinary:S,resultDiffBinary:A}=R;if(await i("cleanup",()=>kt({config:e,diff:I,result:x.result,duration:x.duration,resultDiff:_,diffBinary:S,resultDiffBinary:A,previewInfo:v}),W.timeUnits.minutes(10)),c)throw c;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await wt())})}catch(c){jt.error("Got error while running pipeline",c),await l?.();let u=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:u||"Encountered error when running agent",state:"error"}),c}finally{await Qr()}};export{Ds as runPipeline};
|
|
135
134
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netlify/agent-runner-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.50.0-alpha",
|
|
5
5
|
"description": "CLI tool for running Netlify agents",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -72,13 +72,13 @@
|
|
|
72
72
|
"vitest": "^1.5.0"
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
|
-
"@anthropic-ai/claude-code": "2.0.
|
|
76
|
-
"@google/gemini-cli": "0.
|
|
77
|
-
"@netlify/otel": "^
|
|
78
|
-
"@openai/codex": "0.55.0",
|
|
75
|
+
"@anthropic-ai/claude-code": "2.0.42",
|
|
76
|
+
"@google/gemini-cli": "0.16.0",
|
|
77
|
+
"@netlify/otel": "^5.0.0",
|
|
79
78
|
"@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",
|
|
80
79
|
"execa": "^8.0.0",
|
|
81
80
|
"get-port": "^5.1.1",
|
|
82
|
-
"minimist": "^1.2.8"
|
|
81
|
+
"minimist": "^1.2.8",
|
|
82
|
+
"my-codex-no-sandbox": "^0.1.2505290819"
|
|
83
83
|
}
|
|
84
84
|
}
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
diff --git a/node_modules/@google/gemini-cli/dist/src/nonInteractiveCli.js b/node_modules/@google/gemini-cli/dist/src/nonInteractiveCli.js
|
|
2
|
-
index 874ec89..6eb9a7d 100644
|
|
3
|
-
--- a/node_modules/@google/gemini-cli/dist/src/nonInteractiveCli.js
|
|
4
|
-
+++ b/node_modules/@google/gemini-cli/dist/src/nonInteractiveCli.js
|
|
5
|
-
@@ -5,9 +5,22 @@
|
|
6
|
-
*/
|
|
7
|
-
import { executeToolCall, shutdownTelemetry, isTelemetrySdkInitialized, GeminiEventType, ToolErrorType, } from '@google/gemini-cli-core';
|
|
8
|
-
import { parseAndFormatApiError } from './ui/utils/errorParsing.js';
|
|
9
|
-
+function writeAsync(data) {
|
|
10
|
-
+ return new Promise((resolve, reject) => {
|
|
11
|
-
+ const canWrite = process.stdout.write(data, (err) => {
|
|
12
|
-
+ if (err) reject(err);
|
|
13
|
-
+ else resolve();
|
|
14
|
-
+ });
|
|
15
|
-
+ if (!canWrite) {
|
|
16
|
-
+ process.stdout.once('drain', resolve);
|
|
17
|
-
+ }
|
|
18
|
-
+ });
|
|
19
|
-
+}
|
|
20
|
-
export async function runNonInteractive(config, input, prompt_id) {
|
|
21
|
-
await config.initialize();
|
|
22
|
-
// Handle EPIPE errors when the output is piped to a command that closes early.
|
|
23
|
-
+ const startTime = Date.now();
|
|
24
|
-
+ let lastContent = '';
|
|
25
|
-
process.stdout.on('error', (err) => {
|
|
26
|
-
if (err.code === 'EPIPE') {
|
|
27
|
-
// Exit gracefully if the pipe is closed.
|
|
28
|
-
@@ -29,15 +42,27 @@ export async function runNonInteractive(config, input, prompt_id) {
|
|
29
|
-
}
|
|
30
|
-
const functionCalls = [];
|
|
31
|
-
const responseStream = geminiClient.sendMessageStream(currentMessages[0]?.parts || [], abortController.signal, prompt_id);
|
|
32
|
-
+ let contentBuffer = '';
|
|
33
|
-
+ const flushContentBuffer = async () => {
|
|
34
|
-
+ if (contentBuffer) {
|
|
35
|
-
+ await writeAsync(JSON.stringify({ type: 'content', value: contentBuffer }) + '\n');
|
|
36
|
-
+ lastContent = contentBuffer;
|
|
37
|
-
+ contentBuffer = '';
|
|
38
|
-
+ }
|
|
39
|
-
+ }
|
|
40
|
-
for await (const event of responseStream) {
|
|
41
|
-
if (abortController.signal.aborted) {
|
|
42
|
-
console.error('Operation cancelled.');
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
if (event.type === GeminiEventType.Content) {
|
|
46
|
-
- process.stdout.write(event.value);
|
|
47
|
-
+ contentBuffer += event.value;
|
|
48
|
-
+ } else {
|
|
49
|
-
+ await flushContentBuffer();
|
|
50
|
-
+ await writeAsync(JSON.stringify(event) + '\n');
|
|
51
|
-
}
|
|
52
|
-
- else if (event.type === GeminiEventType.ToolCallRequest) {
|
|
53
|
-
+
|
|
54
|
-
+ if (event.type === GeminiEventType.ToolCallRequest) {
|
|
55
|
-
const toolCallRequest = event.value;
|
|
56
|
-
const fc = {
|
|
57
|
-
name: toolCallRequest.name,
|
|
58
|
-
@@ -47,6 +72,7 @@ export async function runNonInteractive(config, input, prompt_id) {
|
|
59
|
-
functionCalls.push(fc);
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
+ await flushContentBuffer();
|
|
63
|
-
if (functionCalls.length > 0) {
|
|
64
|
-
const toolResponseParts = [];
|
|
65
|
-
for (const fc of functionCalls) {
|
|
66
|
-
@@ -59,6 +85,9 @@ export async function runNonInteractive(config, input, prompt_id) {
|
|
67
|
-
prompt_id,
|
|
68
|
-
};
|
|
69
|
-
const toolResponse = await executeToolCall(config, requestInfo, toolRegistry, abortController.signal);
|
|
70
|
-
+
|
|
71
|
-
+ await writeAsync(JSON.stringify({type: 'tool_result', value: toolResponse}) + '\n');
|
|
72
|
-
+
|
|
73
|
-
if (toolResponse.error) {
|
|
74
|
-
console.error(`Error executing tool ${fc.name}: ${toolResponse.resultDisplay || toolResponse.error.message}`);
|
|
75
|
-
if (toolResponse.errorType === ToolErrorType.UNHANDLED_EXCEPTION)
|
|
76
|
-
@@ -81,7 +110,10 @@ export async function runNonInteractive(config, input, prompt_id) {
|
|
77
|
-
currentMessages = [{ role: 'user', parts: toolResponseParts }];
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
- process.stdout.write('\n'); // Ensure a final newline
|
|
81
|
-
+ const endTime = Date.now();
|
|
82
|
-
+ const duration = endTime - startTime;
|
|
83
|
-
+ const result = { type: 'result', duration_ms: duration, value: lastContent };
|
|
84
|
-
+ await writeAsync(JSON.stringify(result) + '\n');
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
}
|