@netlify/agent-runner-cli 1.131.0-fafo.2 → 1.131.0-fafo.3

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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import ln from"process";import kl from"minimist";import zi from"fs";import K from"process";var cn="netlify-agent-runner-context.md",pr="task-history",re=".netlify",Me="results.md",Ce="assets",un="features",mr="other",gr="personal";var fr="enterprise",Ue="free",dn=[gr,"pro",fr,Ue],kt=["normal","redeploy","create","ask","dtn-prod-iteration","rebase","conflict_resolution"],pn="The base code 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.",mn=`The working tree has conflict markers (<<<<<<<, =======, >>>>>>>) where this branch's edits and the latest changes from the main project disagree. Resolve every marker by deciding the right combination of changes, remove all marker lines, and leave the working tree consistent (no leftover markers, no broken references, no syntax errors introduced by the resolution).
2
+ import ln from"process";import Pl from"minimist";import zi from"fs";import K from"process";var cn="netlify-agent-runner-context.md",pr="task-history",re=".netlify",Me="results.md",Ce="assets",un="features",mr="other",gr="personal";var fr="enterprise",Ue="free",dn=[gr,"pro",fr,Ue],kt=["normal","redeploy","create","ask","dtn-prod-iteration","rebase","conflict_resolution"],pn="The base code 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.",mn=`The working tree has conflict markers (<<<<<<<, =======, >>>>>>>) where this branch's edits and the latest changes from the main project disagree. Resolve every marker by deciding the right combination of changes, remove all marker lines, and leave the working tree consistent (no leftover markers, no broken references, no syntax errors introduced by the resolution).
3
3
 
4
4
  The summary you write to results.md must follow this output format:
5
5
 
@@ -20,7 +20,7 @@ The technical section that follows can keep file paths, property names, values,
20
20
  </security>`,w={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};import Ni from"process";var ki="NETLIFY_FF_",V=()=>{let e={};for(let[t,r]of Object.entries(Ni.env))t.startsWith(ki)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",idleTimeoutEnabled:e.NETLIFY_FF_AGENT_RUNNER_IDLE_TIMEOUT==="true"||e.NETLIFY_FF_AGENT_RUNNER_IDLE_TIMEOUT==="1",fetchAssetsEnabled:e.NETLIFY_FF_AGENT_RUNNER_FETCH_ASSETS==="true"||e.NETLIFY_FF_AGENT_RUNNER_FETCH_ASSETS==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};import Pi from"process";function E(e){let t=Pi.env.LOG!=="0";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 fn=E("utils"),Oi=e=>new Promise(t=>{setTimeout(t,e)}),hn=e=>{if(!e)return e;try{let t=new URL(e);return t.username&&(t.username="***"),t.password&&(t.password="***"),t.toString()}catch{return"[REDACTED]"}},Pt=(e,t=3e3)=>{let r=!1,n=null,s=[],i=null,o=(...a)=>{if(r)return n=a,new Promise(d=>{s.push(d)});r=!0;let c,l=new Promise(d=>{c=d});return i=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await Oi(t),!n)return r=!1,i=null,d;let m=n,p=s;n=null,s=[],d=await e(...m),p.forEach(f=>{f(d)})}})(),l};return o.flush=async()=>{if((r||n)&&i)return await i,o.flush()},o},je=(e,t,r=!1)=>{let n=null,s=null,i=null,o=function(...a){s=a,i=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(i,s),s=null,i=null)},t),c&&(e.apply(i,s),s=null,i=null)};return o.cancel=()=>{clearTimeout(n),n=null,s=null,i=null},o.flush=()=>{if(n){clearTimeout(n);let a=s,c=i;n=null,s=null,i=null,e.apply(c,a)}},o},ut=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):fn.error("Could not parse JSON",n))}},Di=e=>e.charAt(0).toUpperCase()+e.slice(1),Se=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():Di(t)).join(" ");function ke(e,t){t&&e.log(`Skill invoked: ${t}`)}var yn=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_n=(e,t,r=!1)=>{if(r)return;let n=60,s=55,i=".netlify.app",o="agent-",a=6;if(!t)return`${o}${e.slice(0,a)}`;let c=`--${t}${i}`;if(c.length>s)return"";let l=n-c.length;if(l<=0)return"";if(l>=o.length+a){let d=Math.min(l-o.length,e.length);return`${o}${e.slice(0,d)}`}return e.slice(0,l)},$i=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!dn.some(t=>t in e),wn=()=>{let e={},t=V().modelVersionOverrides;return Object.entries(t).forEach(([r,n])=>{if(n)try{let s=JSON.parse(n);$i(s)&&(e[r]=s)}catch(s){let o=s instanceof SyntaxError?"Invalid JSON":s.message;fn.error(`Could not parse ${r} model version override from feature flag: ${o}`)}}),e},hr=e=>{let t=e.match(/<<-?\s*['"]?(\w+)['"]?/);if(!t)return{command:e};let r=e.indexOf(t[0]),n=e.slice(r+t[0].length).trim();return{command:e.slice(0,r).trim(),heredocContent:n||void 0}},Fi=1e4,yr=(e,t=Fi)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{AsyncLocalStorage as Li}from"async_hooks";import Mi from"dgram";import Ge from"process";var Ui="buildbot.agent_runner.",ji=8125,Gi=e=>{let t=Object.keys(e);return t.length===0?"":"|#"+t.map(r=>`${r}:${e[r]}`).join(",")},dt=(e,t,r,n={})=>`${Ui}${e}:${t}|${r}${Gi(n)}`,Bi={service:"buildbot"},vn={},_r=new Li,wr=e=>{vn={...e}},Ot=(e,t)=>{let r=_r.getStore()??{};return _r.run({...r,...e},t)},pt=e=>({...vn,..._r.getStore()??{},...e,...Bi}),Yi=(e,t)=>{let r=!1,n=Mi.createSocket("udp4");return n.unref(),n.once("error",s=>{if(!r){let i=s.code??s.message;Ge.stderr.write(`[metrics] UDP error: ${i}
21
21
  `),r=!0}}),s=>{r||n.send(s,t,e,i=>{if(i&&!r){let o=i.code??i.message;Ge.stderr.write(`[metrics] UDP send to ${e}:${t} failed: ${o}
22
22
  `),r=!0}})}},En=()=>{},bn=()=>({enabled:!!Ge.env.HOST_NODE_IP}),qi=()=>{let e=Ge.env.HOST_NODE_IP;if(!e)return En;let t=Ge.env.DD_AGENT_PORT,r=t===void 0?ji:Number(t);return!Number.isInteger(r)||r<=0||r>65535?(Ge.stderr.write(`[metrics] DD_AGENT_PORT="${t}" is not a valid port; metrics disabled
23
- `),En):Yi(e,r)},Hi=(e=qi())=>({inc(t,r=1,n={}){e(dt(t,r,"c",pt(n)))},gauge(t,r,n={}){e(dt(t,r,"g",pt(n)))},histogram(t,r,n={}){e(dt(t,r,"h",pt(n)))},timing(t,r,n={}){e(dt(t,r,"ms",pt(n)))},distribution(t,r,n={}){e(dt(t,r,"d",pt(n)))}}),S=Hi(),Be=(e,t={})=>{let r=e.input_tokens??0,n=e.output_tokens??0,s=e.cache_creation_input_tokens??0,i=e.cache_read_input_tokens??0;S.distribution("inference.tokens",r,{...t,kind:"input"}),S.distribution("inference.tokens",n,{...t,kind:"output"});let o=e.total_tokens??r+n+s+i;S.distribution("inference.tokens.total",o,t)};var Vi="claude",Ki=e=>typeof e.request=="string"&&typeof e.response=="string",Ji=e=>typeof e.site_context=="string",Xi=e=>(e??[]).filter(Ki),Zi=e=>(e??[]).filter(Ji),Qi={rebase:pn,conflict_resolution:mn},eo=(e,t)=>Qi[e]??t,Ye=E("config"),Sn=({sessionId:e,prompt:t,mode:r,sha:n,context:s,enforcedAICreditsRemaining:i,agent:o,model:a,previousSession:c,assetMap:l})=>{let d=K.env.NETLIFY_AGENT_RUNNER_ID,m=K.env.NETLIFY_TEAM_ID,p=K.env.SITE_ID;if(!d)throw new Error("ID of agent runner is not provided");if(!m)throw new Error("Account ID is not provided");if(!kt.includes(r))throw new Error(`Mode ${r} is not supported`);let f=eo(r,t);if(r!=="redeploy"&&!f)throw new Error("Prompt is not provided");let h=o||K.env.NETLIFY_AGENT_RUNNER_AGENT||Vi,x=a||K.env.NETLIFY_AGENT_RUNNER_MODEL||void 0,_=Xi(s),g=Zi(s),b=K.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",A=K.env.NETLIFY_AGENT_RUNNER_FAST_INIT==="1",F=!V().byokEnabled,D=ro(),P=wn(),G=K.env.NETLIFY_AGENT_RUNNER_DEPLOY_ALIAS,$=K.env.NETLIFY_AGENT_RUNNER_DB_CONNECTION_STRING||void 0,N={id:d,sessionId:e,runner:h,model:x,sessionHistoryContext:_,siteContext:g,hasRepo:b,fastInit:A,useGateway:F,sha:n,runSha:"",accountType:D,modelVersionOverrides:P,enforcedAICreditsRemaining:i,siteId:p,accountId:m,deployAlias:G,dbConnectionString:$,previousSession:c,assetMap:l},I=r==="redeploy"?{...N,mode:r}:{...N,mode:r,prompt:f};return Ye.log({fullConfig:{...I,dbConnectionString:hn($)}}),I},Tn=()=>{let e=K.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e)throw new Error("ID of agent runner session is not provided");let t=ut(K.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Ye);return Sn({sessionId:e,prompt:K.env.NETLIFY_AGENT_RUNNER_PROMPT,mode:K.env.NETLIFY_AGENT_RUNNER_MODE||"normal",sha:K.env.NETLIFY_AGENT_RUNNER_SHA,context:t,enforcedAICreditsRemaining:no(),assetMap:to()})},to=()=>{let e=K.env.NETLIFY_AGENT_RUNNER_ASSET_MAP_PATH;if(!e)return;let t;try{t=zi.readFileSync(e,"utf8")}catch(n){Ye.warn("Failed to read asset map file",{assetMapPath:e,error:n?.message||n}),S.inc("assets.map_read_failed",1);return}let r=ut(t,!0,Ye);if(!r||typeof r!="object"||Array.isArray(r)){Ye.warn("Asset map file did not parse to an object",{assetMapPath:e}),S.inc("assets.map_read_failed",1);return}return r},xn=e=>Sn(e),ro=()=>{let e=K.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?gr:e.includes("pro")?"pro":e.startsWith("enterprise")?fr:e.endsWith("free")?Ue:mr:mr},no=()=>{let e=K.env.ACC_ENFORCED_AI_CREDITS_REMAINING;if(e==null)return;let t=parseInt(e,10);if(Number.isNaN(t)){Ye.warn("Invalid ACC_ENFORCED_AI_CREDITS_REMAINING value, ignoring",{raw:e});return}return t};var he=class extends Error{constructor(r,n,s,i=!1){super(r);this.statusCode=n;this.userMessage=s;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},qe=e=>e instanceof he,Pe=class extends Error{constructor(t){super(t),this.name="ProviderError"}},In=e=>e instanceof Pe;import xl from"fastify";import ht from"fs/promises";import Vn from"os";import yt from"path";import De from"process";import Ho from"readline";import Wo from"@anthropic-ai/sdk";import Er from"path";import so from"fs/promises";var vr=E("agent-output-utils");async function He({initialResult:e,agentName:t,hasError:r}){let n="",s=Er.join(process.cwd(),re,Me);try{let i=await so.readFile(s,"utf-8");i&&(n=i,vr.log(`Pulled result from ${Er.relative(process.cwd(),s)}`))}catch{vr.log(`No results file found at ${Er.relative(process.cwd(),s)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}var io=[/^API Error:\s*\d{3}/i,/^\d{3}\s*status code/i,/^API request failed:\s*\d{3}/i,/^API Error: The socket connection was closed/i,/^overloaded_error/i];function Dt(e){let t=e.trim();return io.some(r=>r.test(t))?"Encountered a temporary issue \u2014 the agent will attempt to continue.":e}function We({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",s="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?s="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.":n?.includes("error when talking to gemini api")?s="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(s=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(s=`The ${t} API request's have timed out. Please try again or use a different available agent.`),(n?.includes("network error")||n?.includes("socket connection was closed"))&&(s=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n?.includes("503")&&!n?.includes("usage exceeded")&&(s=`The ${t} API is currently experiencing high load. Retrying automatically...`),(n?.includes("529")||n?.includes("overloaded_error"))&&(s=`The ${t} API is currently overloaded. Retrying automatically...`),n?.includes("at capacity")&&(s=`The ${t} model is currently at capacity. Retrying automatically...`),(n?.includes("there's an issue with the selected model")||n?.includes("is not available for")&&n?.includes("provider"))&&(s=`The ${t} model is temporarily unavailable. Please try again later or use a different available agent.`),s&&vr.log(`Providing updated error messsage: ${s}, replacing original error: ${r}`),s||r||void 0}function ze(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("socket connection was closed")||r?.includes("request timed out")||r?.includes("network error")?!0:r?.includes("usage exceeded")?!1:!!(r?.includes("503")||r?.includes("529")||r?.includes("overloaded_error")||r?.includes("at capacity"))}function Ve(e){if(!e)return!1;let t=e.replace(/\s+/g," ").trim().toLowerCase();return!!(t.includes("there's an issue with the selected model")||t.includes("is not available for")&&t.includes("provider"))}import Ee from"process";import we from"path";import Ft from"fs";import{fileURLToPath as go}from"url";import{createRequire as fo}from"module";import{execa as ho,execaCommand as yo}from"execa";import{Transform as oo}from"stream";var ao=["NETLIFY_AI_GATEWAY_KEY"];function lo(){let e=(process.env.NETLIFY_SENSITIVE_ENV_KEYS||"").split(",").map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...ao])]}function co(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function uo(){let t=lo().map(r=>process.env[r]).filter(r=>!(!r||co(r)));return[...new Set(t)].sort((r,n)=>n.length-r.length)}function de(e){if(typeof e!="string")return e;let t=uo();if(t.length===0)return e;let r=e;return t.forEach(n=>{let s=new RegExp(po(n),"g");r=r.replace(s,"******")}),r}function po(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var mt=class extends oo{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let s=t.toString(),i=de(s);n(null,i)}},$t=Symbol("maskedWrite");function An(){if(process.env.NETLIFY_MASK_LOGS!=="false"){if(!process.stdout.write[$t]){let t=process.stdout.write.bind(process.stdout),r=function(n,s,i){let o=typeof n=="string"?de(n):n;return typeof s=="function"?t(o,s):t(o,s,i)};r[$t]=!0,process.stdout.write=r}if(!process.stderr.write[$t]){let t=process.stderr.write.bind(process.stderr),r=function(n,s,i){let o=typeof n=="string"?de(n):n;return typeof s=="function"?t(o,s):t(o,s,i)};r[$t]=!0,process.stderr.write=r}}}var gt=null,Rn=e=>(gt&&gt.destroy(),gt=new _e({totalAllowedTime:e}),gt),Cn=()=>gt;var _e=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let s=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,o=null;n!==void 0&&(o=new Promise((l,d)=>{i=setTimeout(()=>{d(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));let a=Date.now(),c="success";try{return await Ot({stage:t},async()=>o?await Promise.race([r(),o]):await r())}catch(l){throw c="failure",l}finally{S.timing("stage.duration",Date.now()-a,{stage:t,outcome:c}),s(),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 Nn={name:"@netlify/agent-runner-cli",type:"module",version:"1.131.0-fafo.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":'eslint --cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',"format:fix:lint":'eslint --fix --cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',"format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":'prettier --check --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"',"format:fix:prettier":'prettier --write --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"',"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 vitest run --coverage --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","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",postinstall:"node scripts/postinstall.js"},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/axis":"^1.14.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/coverage-v8":"^4.1.5","@vitest/eslint-plugin":"^1.6.6","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0",jiti:"^2.7.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.154","@anthropic-ai/sdk":"0.91.1","@google/gemini-cli":"0.42.0","@netlify/database-proxy":"^0.1.5","@netlify/otel":"^6.0.3","@netlify/ts-cli":"^1.2.0","@openai/codex":"0.128.0","@opentelemetry/api":"^1.9.0","@opentelemetry/exporter-trace-otlp-grpc":"0.218.0",execa:"^9.6.1",fastify:"5.8.5",minimist:"^1.2.8",openai:"6.34.0"}};var _o=go(import.meta.url),wo=we.dirname(_o),Eo=fo(import.meta.url),Ke=E("shell"),br=new Set,kn={preferLocal:!0},j=(e,t,r)=>{let[n,s]=vo(t,r),i={...kn,...s},o=ho(e,n,i);On(o,i),Fn(o);let a=r?.idleTimeout;return a&&a>0&&$n(o,a),o},Pn=(e,t)=>{let r={...kn,...t},n=yo(e,r);return On(n,r),Fn(n),t?.idleTimeout&&t.idleTimeout>0&&$n(n,t.idleTimeout),n},vo=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},On=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Ee.env.NETLIFY_MASK_LOGS!=="false"){e.stdout?.pipe(new mt).pipe(Ee.stdout),e.stderr?.pipe(new mt).pipe(Ee.stderr);return}e.stdout?.pipe(Ee.stdout),e.stderr?.pipe(Ee.stderr)},Sr=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Ee.kill(-e.pid,t),Ke.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Ke.error("Error killing process:",r),!1}},Dn=e=>Sr(e,"SIGKILL"),$n=(e,t)=>{let r=null,n=()=>{Ke.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Sr(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ke.log(`Force killing idle process ${e.pid}`),Dn(e))},5e3)},s=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};s(),e.stdout?.on("data",s),e.stderr?.on("data",s);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Fn=e=>{br.add(e);let t=Cn();if(t){let r=t.onTimesUp(()=>{Ke.log(`Global timer expired, killing process ${e.pid}`),Sr(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ke.log(`Force killing process ${e.pid} after timeout`),Dn(e))},5e3)});e.on("exit",()=>{br.delete(e),r()}),e.on("error",()=>{br.delete(e),r()})}};function Te(e,t){if(!Ee.env.NETLIFY_LOCAL_MODE)try{let s=Eo.resolve(Nn.name),i=we.dirname(s);for(;i!==we.dirname(i);){let o=we.dirname(i);if(we.basename(o)==="node_modules"){let a=we.join(o,".bin",t);if(Ft.existsSync(a))return a;break}i=o}}catch(s){console.error("Could not resolve package.json",s)}if(Ee.env.NODE_PATH){let s=we.join(Ee.env.NODE_PATH,".bin",t);if(Ft.existsSync(s))return s}let r=we.join(e,"node_modules",".bin",t);if(Ft.existsSync(r))return r;let n=we.join(wo,"..","node_modules",".bin",t);if(Ft.existsSync(n))return n}import Mt from"process";import{fileURLToPath as ko}from"url";import{createRequire as Po}from"module";import Ut from"path";import{getTracer as Oo}from"@netlify/otel";import{createTracerProvider as bo}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ln}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as So}from"@netlify/otel/instrumentation-fetch";import{getTracer as To,withActiveSpan as xo}from"@netlify/otel";import{propagation as Mn,context as Un,W3CTraceContextPropagator as Io}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Ao}from"@opentelemetry/exporter-trace-otlp-grpc";var Tr=E("tracing"),jn=8e3,Gn=async(e,t,r)=>{let n=[new Ln(new xr),new Ln(new Ao({url:r.exporterUrl}))];return await bo({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:n,instrumentations:[new So({skipHeaders:!0})]}),r.traceparent?(Mn.setGlobalPropagator(new Io),Mn.extract(Un.active(),{traceparent:r.traceparent,isRemote:!0})):Un.active()};function L(e,t,r){return Tr.log(`\u23F3 TRACE: ${t} starting...`),xo(e,t,r)}var xr=class{export(t,r){for(let n of t)this.logSpan(n);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,n=t.attributes,s=[];for(let[a,c]of Object.entries(n))a.includes("duration")&&typeof c=="number"?s.push(`${a}=${c.toFixed(2)}ms`):s.push(`${a}=${c}`);let i=t.status?.code===2?"\u274C":"\u2705",o=s.length>0?` [${s.join(", ")}]`:"";Tr.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${o}`),t.status?.code===2&&t.status.message&&Tr.log(` \u274C Error: ${t.status.message}`)}};function Ir(){return process.env.AGENT_RUNNER_CAPTURE_LLM_CONTENT!=="false"}function Bn(e){return e.includes("claude")?"anthropic":e.includes("codex")?"openai":e.includes("gemini")?"google":e}function Lt(e,t,r){let n={role:e,parts:[{type:"text",content:de(t)}]};return r&&(n.finish_reason=r),JSON.stringify([n])}function Yn(e,t,r,n){if(!e.length)return;let s=To();if(!s)return;let i=Ir(),o=Math.max(1,(n-r)/e.length);e.forEach((a,c)=>{let l=Math.min(n,r+c*o),d=Math.min(n,l+o),m=a.title||a.type||`step-${a.id??c}`,p=a.type==="tool_use"||a.type==="tool_result",f=a.message?a.message.length>jn?`${a.message.slice(0,jn)}\u2026`:a.message:void 0;s.startSpan(m,{startTime:l,attributes:{"gen_ai.capability.name":t,"gen_ai.step.name":m,"gen_ai.operation.name":p?"execute_tool":"chat",...p?{"gen_ai.tool.name":m}:{},"spark.step.id":a.id??-1,...a.type?{"spark.step.type":a.type}:{},...a.category?{"spark.step.category":a.category}:{},...a.groupId?{"spark.step.group_id":a.groupId}:{},...a.parentGroupId?{"spark.step.parent_group_id":a.parentGroupId}:{},...i&&f?p?{"gen_ai.tool.call.result":de(f)}:{"gen_ai.output.messages":Lt("assistant",f)}:{}}}).end(d)})}import{readdir as Ro,rm as Co}from"fs/promises";import{join as No}from"path";async function qn(e,t=[]){let n=(await Ro(e)).filter(s=>!t.includes(s));await Promise.all(n.map(s=>Co(No(e,s),{recursive:!0,force:!0})))}var Do=Ut.dirname(ko(import.meta.url)),Hn=Po(import.meta.url),$o=Ut.resolve(Do,"scripts/scaffold.js"),Fo="scripts/scaffold.js",Lo=/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/g,Ar=e=>{if(e.length>=2){let t=e[0],r=e[e.length-1];if(t==='"'&&r==='"'||t==="'"&&r==="'")return e.slice(1,-1)}return e},Mo=e=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e),Uo=e=>{let t=Ar(e);return t==="node"||t.endsWith("/node")},Oe=e=>{if(typeof e!="string")return!1;let t=e.match(Lo)||[];if(t.length<2)return!1;let r=0;for(;r<t.length&&Mo(Ar(t[r]));)r+=1;if(r>=t.length||!Uo(t[r]))return!1;let n=t[r+1];return n?Ar(n).includes(Fo):!1},ft=E("create_stage"),jo="After completing the user's request:\n- Add a README.md to the project root describing what the project is, the key technologies used, and how to run it locally.\n- Add an AGENTS.md to the project root describing the project architecture, key directories, coding conventions, and any non-obvious decisions. This file is read by AI agents in future sessions to understand the project.\n\nDo not run local validation or dev-server commands to check your work \u2014 specifically `tsc`, `npx tsc`, `vite build`, `vite dev`, or any equivalent build/start/test command. The build pipeline installs and validates the project automatically after your edits. Verify your changes by reading the files you edited.\n\nCommands that generate or modify project files are fine to run when the task requires them \u2014 for example `drizzle-kit generate` to write a database migration after a schema change, or other code-generation utilities documented in the skills.",Go="./.netlify-cache",Bo=({cwd:e=Mt.cwd()}={})=>{let t=Mt.env.NVM_BIN?`${Mt.env.NVM_BIN}/node`:"node",r;try{let n=Hn.resolve("@netlify/ts-cli/package.json"),s=Ut.dirname(n),i=Hn("@netlify/ts-cli/package.json");r=Ut.join(s,i.bin)}catch{r=Te(e,"ts-cli")}return{nodeCmd:t,tsCliPath:r}},Yo=e=>{let t=[];try{if(!e)throw new Error("empty response");t=JSON.parse(e)}catch(r){return ft.error("Failed to parse template list from ts-cli",{raw:e,error:r.message}),S.inc("context.degraded",1,{component:"templates"}),[]}return t.filter(r=>r.type==="example").map(r=>{let{type:n,...s}=r;return s})},qo=({templates:e,nodeCmd:t,scaffoldScriptPath:r})=>{let n=JSON.stringify(e.map(({id:i,name:o,description:a})=>({id:i,name:o,description:a})),null,2);return["You are creating a new Netlify project to fulfill the user's request. The project directory is currently empty.",e.length>0?`## Available Templates
23
+ `),En):Yi(e,r)},Hi=(e=qi())=>({inc(t,r=1,n={}){e(dt(t,r,"c",pt(n)))},gauge(t,r,n={}){e(dt(t,r,"g",pt(n)))},histogram(t,r,n={}){e(dt(t,r,"h",pt(n)))},timing(t,r,n={}){e(dt(t,r,"ms",pt(n)))},distribution(t,r,n={}){e(dt(t,r,"d",pt(n)))}}),S=Hi(),Be=(e,t={})=>{let r=e.input_tokens??0,n=e.output_tokens??0,s=e.cache_creation_input_tokens??0,i=e.cache_read_input_tokens??0;S.distribution("inference.tokens",r,{...t,kind:"input"}),S.distribution("inference.tokens",n,{...t,kind:"output"});let o=e.total_tokens??r+n+s+i;S.distribution("inference.tokens.total",o,t)};var Vi="claude",Ki=e=>typeof e.request=="string"&&typeof e.response=="string",Ji=e=>typeof e.site_context=="string",Xi=e=>(e??[]).filter(Ki),Zi=e=>(e??[]).filter(Ji),Qi={rebase:pn,conflict_resolution:mn},eo=(e,t)=>Qi[e]??t,Ye=E("config"),Sn=({sessionId:e,prompt:t,mode:r,sha:n,context:s,enforcedAICreditsRemaining:i,agent:o,model:a,previousSession:c,assetMap:l})=>{let d=K.env.NETLIFY_AGENT_RUNNER_ID,m=K.env.NETLIFY_TEAM_ID,p=K.env.SITE_ID;if(!d)throw new Error("ID of agent runner is not provided");if(!m)throw new Error("Account ID is not provided");if(!kt.includes(r))throw new Error(`Mode ${r} is not supported`);let f=eo(r,t);if(r!=="redeploy"&&!f)throw new Error("Prompt is not provided");let h=o||K.env.NETLIFY_AGENT_RUNNER_AGENT||Vi,x=a||K.env.NETLIFY_AGENT_RUNNER_MODEL||void 0,_=Xi(s),g=Zi(s),b=K.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",A=K.env.NETLIFY_AGENT_RUNNER_FAST_INIT==="1",F=!V().byokEnabled,D=ro(),P=wn(),G=K.env.NETLIFY_AGENT_RUNNER_DEPLOY_ALIAS,$=K.env.NETLIFY_AGENT_RUNNER_DB_CONNECTION_STRING||void 0,N={id:d,sessionId:e,runner:h,model:x,sessionHistoryContext:_,siteContext:g,hasRepo:b,fastInit:A,useGateway:F,sha:n,runSha:"",accountType:D,modelVersionOverrides:P,enforcedAICreditsRemaining:i,siteId:p,accountId:m,deployAlias:G,dbConnectionString:$,previousSession:c,assetMap:l},I=r==="redeploy"?{...N,mode:r}:{...N,mode:r,prompt:f};return Ye.log({fullConfig:{...I,dbConnectionString:hn($)}}),I},Tn=()=>{let e=K.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e)throw new Error("ID of agent runner session is not provided");let t=ut(K.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Ye);return Sn({sessionId:e,prompt:K.env.NETLIFY_AGENT_RUNNER_PROMPT,mode:K.env.NETLIFY_AGENT_RUNNER_MODE||"normal",sha:K.env.NETLIFY_AGENT_RUNNER_SHA,context:t,enforcedAICreditsRemaining:no(),assetMap:to()})},to=()=>{let e=K.env.NETLIFY_AGENT_RUNNER_ASSET_MAP_PATH;if(!e)return;let t;try{t=zi.readFileSync(e,"utf8")}catch(n){Ye.warn("Failed to read asset map file",{assetMapPath:e,error:n?.message||n}),S.inc("assets.map_read_failed",1);return}let r=ut(t,!0,Ye);if(!r||typeof r!="object"||Array.isArray(r)){Ye.warn("Asset map file did not parse to an object",{assetMapPath:e}),S.inc("assets.map_read_failed",1);return}return r},xn=e=>Sn(e),ro=()=>{let e=K.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?gr:e.includes("pro")?"pro":e.startsWith("enterprise")?fr:e.endsWith("free")?Ue:mr:mr},no=()=>{let e=K.env.ACC_ENFORCED_AI_CREDITS_REMAINING;if(e==null)return;let t=parseInt(e,10);if(Number.isNaN(t)){Ye.warn("Invalid ACC_ENFORCED_AI_CREDITS_REMAINING value, ignoring",{raw:e});return}return t};var he=class extends Error{constructor(r,n,s,i=!1){super(r);this.statusCode=n;this.userMessage=s;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},qe=e=>e instanceof he,Pe=class extends Error{constructor(t){super(t),this.name="ProviderError"}},In=e=>e instanceof Pe;import Il from"fastify";import ht from"fs/promises";import Vn from"os";import yt from"path";import De from"process";import Ho from"readline";import Wo from"@anthropic-ai/sdk";import Er from"path";import so from"fs/promises";var vr=E("agent-output-utils");async function He({initialResult:e,agentName:t,hasError:r}){let n="",s=Er.join(process.cwd(),re,Me);try{let i=await so.readFile(s,"utf-8");i&&(n=i,vr.log(`Pulled result from ${Er.relative(process.cwd(),s)}`))}catch{vr.log(`No results file found at ${Er.relative(process.cwd(),s)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}var io=[/^API Error:\s*\d{3}/i,/^\d{3}\s*status code/i,/^API request failed:\s*\d{3}/i,/^API Error: The socket connection was closed/i,/^overloaded_error/i];function Dt(e){let t=e.trim();return io.some(r=>r.test(t))?"Encountered a temporary issue \u2014 the agent will attempt to continue.":e}function We({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",s="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?s="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.":n?.includes("error when talking to gemini api")?s="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(s=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(s=`The ${t} API request's have timed out. Please try again or use a different available agent.`),(n?.includes("network error")||n?.includes("socket connection was closed"))&&(s=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n?.includes("503")&&!n?.includes("usage exceeded")&&(s=`The ${t} API is currently experiencing high load. Retrying automatically...`),(n?.includes("529")||n?.includes("overloaded_error"))&&(s=`The ${t} API is currently overloaded. Retrying automatically...`),n?.includes("at capacity")&&(s=`The ${t} model is currently at capacity. Retrying automatically...`),(n?.includes("there's an issue with the selected model")||n?.includes("is not available for")&&n?.includes("provider"))&&(s=`The ${t} model is temporarily unavailable. Please try again later or use a different available agent.`),s&&vr.log(`Providing updated error messsage: ${s}, replacing original error: ${r}`),s||r||void 0}function ze(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("socket connection was closed")||r?.includes("request timed out")||r?.includes("network error")?!0:r?.includes("usage exceeded")?!1:!!(r?.includes("503")||r?.includes("529")||r?.includes("overloaded_error")||r?.includes("at capacity"))}function Ve(e){if(!e)return!1;let t=e.replace(/\s+/g," ").trim().toLowerCase();return!!(t.includes("there's an issue with the selected model")||t.includes("is not available for")&&t.includes("provider"))}import Ee from"process";import we from"path";import Ft from"fs";import{fileURLToPath as go}from"url";import{createRequire as fo}from"module";import{execa as ho,execaCommand as yo}from"execa";import{Transform as oo}from"stream";var ao=["NETLIFY_AI_GATEWAY_KEY"];function lo(){let e=(process.env.NETLIFY_SENSITIVE_ENV_KEYS||"").split(",").map(t=>t.trim()).filter(Boolean);return[...new Set([...e,...ao])]}function co(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function uo(){let t=lo().map(r=>process.env[r]).filter(r=>!(!r||co(r)));return[...new Set(t)].sort((r,n)=>n.length-r.length)}function de(e){if(typeof e!="string")return e;let t=uo();if(t.length===0)return e;let r=e;return t.forEach(n=>{let s=new RegExp(po(n),"g");r=r.replace(s,"******")}),r}function po(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var mt=class extends oo{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let s=t.toString(),i=de(s);n(null,i)}},$t=Symbol("maskedWrite");function An(){if(process.env.NETLIFY_MASK_LOGS!=="false"){if(!process.stdout.write[$t]){let t=process.stdout.write.bind(process.stdout),r=function(n,s,i){let o=typeof n=="string"?de(n):n;return typeof s=="function"?t(o,s):t(o,s,i)};r[$t]=!0,process.stdout.write=r}if(!process.stderr.write[$t]){let t=process.stderr.write.bind(process.stderr),r=function(n,s,i){let o=typeof n=="string"?de(n):n;return typeof s=="function"?t(o,s):t(o,s,i)};r[$t]=!0,process.stderr.write=r}}}var gt=null,Rn=e=>(gt&&gt.destroy(),gt=new _e({totalAllowedTime:e}),gt),Cn=()=>gt;var _e=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let s=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,o=null;n!==void 0&&(o=new Promise((l,d)=>{i=setTimeout(()=>{d(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));let a=Date.now(),c="success";try{return await Ot({stage:t},async()=>o?await Promise.race([r(),o]):await r())}catch(l){throw c="failure",l}finally{S.timing("stage.duration",Date.now()-a,{stage:t,outcome:c}),s(),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 Nn={name:"@netlify/agent-runner-cli",type:"module",version:"1.131.0-fafo.3",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":'eslint --cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',"format:fix:lint":'eslint --fix --cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',"format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":'prettier --check --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"',"format:fix:prettier":'prettier --write --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"',"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 vitest run --coverage --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","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",postinstall:"node scripts/postinstall.js"},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/axis":"^1.14.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/coverage-v8":"^4.1.5","@vitest/eslint-plugin":"^1.6.6","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0",jiti:"^2.7.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.154","@anthropic-ai/sdk":"0.91.1","@google/gemini-cli":"0.42.0","@netlify/database-proxy":"^0.1.5","@netlify/otel":"^6.0.3","@netlify/ts-cli":"^1.2.0","@openai/codex":"0.128.0","@opentelemetry/api":"^1.9.0","@opentelemetry/exporter-trace-otlp-grpc":"0.218.0",execa:"^9.6.1",fastify:"5.8.5",minimist:"^1.2.8",openai:"6.34.0"}};var _o=go(import.meta.url),wo=we.dirname(_o),Eo=fo(import.meta.url),Ke=E("shell"),br=new Set,kn={preferLocal:!0},j=(e,t,r)=>{let[n,s]=vo(t,r),i={...kn,...s},o=ho(e,n,i);On(o,i),Fn(o);let a=r?.idleTimeout;return a&&a>0&&$n(o,a),o},Pn=(e,t)=>{let r={...kn,...t},n=yo(e,r);return On(n,r),Fn(n),t?.idleTimeout&&t.idleTimeout>0&&$n(n,t.idleTimeout),n},vo=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},On=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Ee.env.NETLIFY_MASK_LOGS!=="false"){e.stdout?.pipe(new mt).pipe(Ee.stdout),e.stderr?.pipe(new mt).pipe(Ee.stderr);return}e.stdout?.pipe(Ee.stdout),e.stderr?.pipe(Ee.stderr)},Sr=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Ee.kill(-e.pid,t),Ke.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Ke.error("Error killing process:",r),!1}},Dn=e=>Sr(e,"SIGKILL"),$n=(e,t)=>{let r=null,n=()=>{Ke.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Sr(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ke.log(`Force killing idle process ${e.pid}`),Dn(e))},5e3)},s=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};s(),e.stdout?.on("data",s),e.stderr?.on("data",s);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Fn=e=>{br.add(e);let t=Cn();if(t){let r=t.onTimesUp(()=>{Ke.log(`Global timer expired, killing process ${e.pid}`),Sr(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ke.log(`Force killing process ${e.pid} after timeout`),Dn(e))},5e3)});e.on("exit",()=>{br.delete(e),r()}),e.on("error",()=>{br.delete(e),r()})}};function Te(e,t){if(!Ee.env.NETLIFY_LOCAL_MODE)try{let s=Eo.resolve(Nn.name),i=we.dirname(s);for(;i!==we.dirname(i);){let o=we.dirname(i);if(we.basename(o)==="node_modules"){let a=we.join(o,".bin",t);if(Ft.existsSync(a))return a;break}i=o}}catch(s){console.error("Could not resolve package.json",s)}if(Ee.env.NODE_PATH){let s=we.join(Ee.env.NODE_PATH,".bin",t);if(Ft.existsSync(s))return s}let r=we.join(e,"node_modules",".bin",t);if(Ft.existsSync(r))return r;let n=we.join(wo,"..","node_modules",".bin",t);if(Ft.existsSync(n))return n}import Mt from"process";import{fileURLToPath as ko}from"url";import{createRequire as Po}from"module";import Ut from"path";import{getTracer as Oo}from"@netlify/otel";import{createTracerProvider as bo}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ln}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as So}from"@netlify/otel/instrumentation-fetch";import{getTracer as To,withActiveSpan as xo}from"@netlify/otel";import{propagation as Mn,context as Un,W3CTraceContextPropagator as Io}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Ao}from"@opentelemetry/exporter-trace-otlp-grpc";var Tr=E("tracing"),jn=8e3,Gn=async(e,t,r)=>{let n=[new Ln(new xr),new Ln(new Ao({url:r.exporterUrl}))];return await bo({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:n,instrumentations:[new So({skipHeaders:!0})]}),r.traceparent?(Mn.setGlobalPropagator(new Io),Mn.extract(Un.active(),{traceparent:r.traceparent,isRemote:!0})):Un.active()};function L(e,t,r){return Tr.log(`\u23F3 TRACE: ${t} starting...`),xo(e,t,r)}var xr=class{export(t,r){for(let n of t)this.logSpan(n);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,n=t.attributes,s=[];for(let[a,c]of Object.entries(n))a.includes("duration")&&typeof c=="number"?s.push(`${a}=${c.toFixed(2)}ms`):s.push(`${a}=${c}`);let i=t.status?.code===2?"\u274C":"\u2705",o=s.length>0?` [${s.join(", ")}]`:"";Tr.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${o}`),t.status?.code===2&&t.status.message&&Tr.log(` \u274C Error: ${t.status.message}`)}};function Ir(){return process.env.AGENT_RUNNER_CAPTURE_LLM_CONTENT!=="false"}function Bn(e){return e.includes("claude")?"anthropic":e.includes("codex")?"openai":e.includes("gemini")?"google":e}function Lt(e,t,r){let n={role:e,parts:[{type:"text",content:de(t)}]};return r&&(n.finish_reason=r),JSON.stringify([n])}function Yn(e,t,r,n){if(!e.length)return;let s=To();if(!s)return;let i=Ir(),o=Math.max(1,(n-r)/e.length);e.forEach((a,c)=>{let l=Math.min(n,r+c*o),d=Math.min(n,l+o),m=a.title||a.type||`step-${a.id??c}`,p=a.type==="tool_use"||a.type==="tool_result",f=a.message?a.message.length>jn?`${a.message.slice(0,jn)}\u2026`:a.message:void 0;s.startSpan(m,{startTime:l,attributes:{"gen_ai.capability.name":t,"gen_ai.step.name":m,"gen_ai.operation.name":p?"execute_tool":"chat",...p?{"gen_ai.tool.name":m}:{},"spark.step.id":a.id??-1,...a.type?{"spark.step.type":a.type}:{},...a.category?{"spark.step.category":a.category}:{},...a.groupId?{"spark.step.group_id":a.groupId}:{},...a.parentGroupId?{"spark.step.parent_group_id":a.parentGroupId}:{},...i&&f?p?{"gen_ai.tool.call.result":de(f)}:{"gen_ai.output.messages":Lt("assistant",f)}:{}}}).end(d)})}import{readdir as Ro,rm as Co}from"fs/promises";import{join as No}from"path";async function qn(e,t=[]){let n=(await Ro(e)).filter(s=>!t.includes(s));await Promise.all(n.map(s=>Co(No(e,s),{recursive:!0,force:!0})))}var Do=Ut.dirname(ko(import.meta.url)),Hn=Po(import.meta.url),$o=Ut.resolve(Do,"scripts/scaffold.js"),Fo="scripts/scaffold.js",Lo=/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/g,Ar=e=>{if(e.length>=2){let t=e[0],r=e[e.length-1];if(t==='"'&&r==='"'||t==="'"&&r==="'")return e.slice(1,-1)}return e},Mo=e=>/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(e),Uo=e=>{let t=Ar(e);return t==="node"||t.endsWith("/node")},Oe=e=>{if(typeof e!="string")return!1;let t=e.match(Lo)||[];if(t.length<2)return!1;let r=0;for(;r<t.length&&Mo(Ar(t[r]));)r+=1;if(r>=t.length||!Uo(t[r]))return!1;let n=t[r+1];return n?Ar(n).includes(Fo):!1},ft=E("create_stage"),jo="After completing the user's request:\n- Add a README.md to the project root describing what the project is, the key technologies used, and how to run it locally.\n- Add an AGENTS.md to the project root describing the project architecture, key directories, coding conventions, and any non-obvious decisions. This file is read by AI agents in future sessions to understand the project.\n\nDo not run local validation or dev-server commands to check your work \u2014 specifically `tsc`, `npx tsc`, `vite build`, `vite dev`, or any equivalent build/start/test command. The build pipeline installs and validates the project automatically after your edits. Verify your changes by reading the files you edited.\n\nCommands that generate or modify project files are fine to run when the task requires them \u2014 for example `drizzle-kit generate` to write a database migration after a schema change, or other code-generation utilities documented in the skills.",Go="./.netlify-cache",Bo=({cwd:e=Mt.cwd()}={})=>{let t=Mt.env.NVM_BIN?`${Mt.env.NVM_BIN}/node`:"node",r;try{let n=Hn.resolve("@netlify/ts-cli/package.json"),s=Ut.dirname(n),i=Hn("@netlify/ts-cli/package.json");r=Ut.join(s,i.bin)}catch{r=Te(e,"ts-cli")}return{nodeCmd:t,tsCliPath:r}},Yo=e=>{let t=[];try{if(!e)throw new Error("empty response");t=JSON.parse(e)}catch(r){return ft.error("Failed to parse template list from ts-cli",{raw:e,error:r.message}),S.inc("context.degraded",1,{component:"templates"}),[]}return t.filter(r=>r.type==="example").map(r=>{let{type:n,...s}=r;return s})},qo=({templates:e,nodeCmd:t,scaffoldScriptPath:r})=>{let n=JSON.stringify(e.map(({id:i,name:o,description:a})=>({id:i,name:o,description:a})),null,2);return["You are creating a new Netlify project to fulfill the user's request. The project directory is currently empty.",e.length>0?`## Available Templates
24
24
 
25
25
  Start with one of the following templates by using the Bash command below, unless there's a strong reason to start from scratch based on the users prompt.
26
26
 
@@ -70,17 +70,17 @@ ${o.trim()}
70
70
  `),"utf8"),n},aa=async(e,t=Yt.join(na.homedir(),".gemini"))=>{let r=Yt.join(t,"tmp"),n=e.slice(0,8),s;try{s=await wt.readdir(r)}catch{return}for(let i of s){let o=Yt.join(r,i,"chats"),a;try{a=await wt.readdir(o)}catch{continue}for(let c of a){if(!c.endsWith(".jsonl")||!c.includes(n))continue;let l=Yt.join(o,c);try{let d=(await wt.readFile(l,"utf8")).split(`
71
71
  `,1)[0];if(JSON.parse(d).sessionId===e)return l}catch{continue}}}},qt=async e=>{try{let t=await aa(e);return t?(await oa(t),!0):(as.log(`No gemini session file for ${e}; not resumable, using fresh session`),!1)}catch(t){return as.warn(`Could not sanitize gemini session ${e} for resume; using fresh session`,{error:sa(t)}),!1}};var ae=E("runner_gemini"),kr="Gemini CLI",Qe="gemini-3.5-flash",ca=({catchError:e,runCmd:t,error:r,result:n,runnerName:s})=>(ae.log(`${s} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(ae.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(ae.log("Setting result to undefined because no valid result was captured"),{error:r||`${s} failed`,result:void 0})),ls={list_directory:{name:"List directory",category:w.Explore},read_file:{name:"Read file",category:w.FileRead},write_file:{name:"Edit file",category:w.FileWrite},glob:{name:"Find files",category:w.Explore},search_file_content:{name:"Search files",category:w.Explore},replace:{name:"Edit file",category:w.FileWrite},run_shell_command:{name:"Run command",category:w.RunCommand},web_fetch:{name:"Fetch web",category:w.Web},web_search:{name:"Search web",category:w.Web},read_many_files:{name:"Read files",category:w.FileRead},save_memory:{name:"Memorize",category:w.Memorize},activate_skill:{name:"Use Skill",category:w.Skill},grep_search:{name:"Search files",category:w.Explore}},ua=async()=>{let e=et.join(Ht.homedir(),".gemini"),t=et.join(e,"settings.json");try{await Et.mkdir(e,{recursive:!0});let r={};try{let n=await Et.readFile(t,"utf-8");r=JSON.parse(n)}catch{ae.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,r.context||(r.context={}),r.context.fileName=["GEMINI.md","AGENTS.md"],await Et.writeFile(t,JSON.stringify(r,null,2),"utf-8"),ae.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){ae.error("Failed to ensure Gemini CLI settings",{error:r.message}),S.inc("context.degraded",1,{component:"agent_config"})}},da=e=>{e?.category===w.Skill&&e.type&&ke(ae,Se(e.type))};async function Pr({config:e,netlify:t,persistSteps:r=void 0,sendSteps:n=void 0,aiGateway:s,continueSession:i=!1,priorAgentSessionId:o=void 0,cwd:a=Ze.cwd()}){let{accountType:c,prompt:l,modelVersionOverrides:d}=e,{model:m}=e;if(await ua(),s){let{token:y,url:u}=s;if(!y||!u)throw new Error("No token or url provided from AI Gateway");if(d?.gemini){let v=d?.gemini?.[c];if(v){if(!await s.isModelAvailableForProvider("gemini",v))throw new Error(`Model override '${v}' is not available for gemini provider`);m=v}}if(!m)!!Qe&&await s.isModelAvailableForProvider("gemini",Qe)?(m=Qe,ae.log(`Using default model: ${Qe}`)):Qe&&ae.log(`Default model ${Qe} is not available, proceeding without model specification`);else if(m&&!d?.gemini?.[c]&&!await s.isModelAvailableForProvider("gemini",m))throw new Error(`Model '${m}' is not available for gemini provider`);Ze.env.GEMINI_API_KEY=y,Ze.env.GOOGLE_GEMINI_BASE_URL=u}else if(!Ze.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],f=[],h=[],x={},_=0,g=0,b,A,F,D,P=!!(i&&o),G=!1;P&&(G=await qt(o)),P&&!G&&(ae.log(`Gemini resume requested for session ${o} but it was not resumable; starting a fresh session`),S.inc("inference.native_resume",1,{outcome:"sanitize_failed"}));let $=[Te(a,"gemini"),...m?["--model",m]:[],"--yolo","--skip-trust","--output-format","stream-json",...G?["-r",o]:[],"-p",""],N=`${Ze.env.NVM_BIN}/node`;ae.log(`Running ${N} ${$.join(" ")}`);let I=t.utils.run(N,$,{all:!0,env:Ze.env,cwd:a,idleTimeout:Ne});I.stdin?.end(l);let M=je(()=>{r?.({steps:p,duration:g}),n?.({steps:f,duration:g}),f=[]},250),B=(y,u)=>{y.id=_,_+=1,h.push(y),p.push(y),f.push(y),u||M.flush(),M(),u&&M.flush()};B({title:`Using ${kr} with ${m||"default"}`,category:w.Environment},!0);let O=la.createInterface({input:I.all});O.on("error",y=>{ae.error("Readline interface error",{error:y.message,stack:y.stack})});let R="",T=()=>{R&&B({message:R.trim(),category:w.AgentMessage}),R=""};return O.on("line",y=>{let u=null;try{if(y.startsWith("[API Error")){let v=y.match(/\[api error: (.+?)]$/i)?.[1];u={type:"error",value:ut(v,!1)?.error?.message||v||"Gemini encountered error"}}else u=JSON.parse(y)}catch{return}if(u)switch(u.type==="init"&&typeof u.session_id=="string"&&(D=u.session_id),["message","result"].includes(u.type)||T(),u.type){case"message":{u.role!=="user"&&u.content&&(R+=u.content);break}case"tool_use":{let v=ls[u.tool_name]?.name??u.tool_name,J=u.parameters?.file_path,q=J&&et.relative(a,J),ee=u.parameters?.command,z=u.tool_name==="activate_skill"&&u.parameters?.name,ue=u.tool_name==="run_shell_command"&&Oe(ee),Y=[v,q&&`\`${q}\``,ee&&`\`${ee}\``].filter(Boolean).join(" ");if(z)Y=`Use ${Se(z)}`;else if(ue)Y="Generating the site";else if(u.tool_name==="grep_search"){let{dir_path:ge,pattern:Fe}=u.parameters||{};ge&&Fe?Y=`Search in \`${ge}\` for \`${Fe}\``:ge?Y=`Search in \`${ge}\``:Fe&&(Y=`Search for \`${Fe}\``)}let H={title:Y,category:ue?w.SiteGeneration:ls[u.tool_name]?.category,...z&&{type:z}};x[u.tool_id]=H,M.flush();break}case"tool_result":{let v=x[u.tool_id];v&&(u.output&&(v.message=`\`\`\`
72
72
  ${u.output.trim()}
73
- \`\`\``),B(v,!0),da(v));break}case"result":{g=u.stats?.duration_ms,u.stats&&(Be(u.stats),F=u.stats),u.status==="error"?A=u.error?.message:b=R.trim();break}case"error":{A=u.error;break}case"finished":break;case"init":break;default:{ae.warn("Unhandled message type:",u.type);break}}}),await I.catch(y=>{({error:A,result:b}=ca({catchError:y,runCmd:I,error:A,result:b,runnerName:"Gemini"}))}),O.close(),M.flush(),{steps:h,duration:g,result:await He({initialResult:b,agentName:kr,hasError:!!A}),error:We({error:A,agentName:kr}),isRetryableError:ze(A),isProviderUnavailableError:Ve(A),resolvedModel:m,usage:F,agentSessionId:D}}var cs=async()=>{let e=et.join(Ht.homedir(),".gemini");await Et.rm(e,{recursive:!0,force:!0});let t=et.join(Ht.homedir(),".agents","skills");await Et.rm(t,{recursive:!0,force:!0})},us={baseDir:et.join(Ht.homedir(),".gemini"),include:["tmp"]};var Or={codex:{runner:Nr,clean:ns,nativeSessionArchive:ss},claude:{runner:Rr,clean:Zn,nativeSessionArchive:Qn},gemini:{runner:Pr,clean:cs,nativeSessionArchive:us}},Dr=Object.keys(Or),$r=e=>Or[e]?.nativeSessionArchive,tt=Or;import{readFileSync as wl}from"fs";import El from"path";import{createRequire as vl}from"module";var pa=["error","failed","exception","fatal","panic","abort","crash"];function ds(e){let t=e.split(`
73
+ \`\`\``),B(v,!0),da(v));break}case"result":{g=u.stats?.duration_ms,u.stats&&(Be(u.stats),F=u.stats),u.status==="error"?A=u.error?.message:b=R.trim();break}case"error":{A=u.error;break}case"finished":break;case"init":break;default:{ae.warn("Unhandled message type:",u.type);break}}}),await I.catch(y=>{({error:A,result:b}=ca({catchError:y,runCmd:I,error:A,result:b,runnerName:"Gemini"}))}),O.close(),M.flush(),{steps:h,duration:g,result:await He({initialResult:b,agentName:kr,hasError:!!A}),error:We({error:A,agentName:kr}),isRetryableError:ze(A),isProviderUnavailableError:Ve(A),resolvedModel:m,usage:F,agentSessionId:D}}var cs=async()=>{let e=et.join(Ht.homedir(),".gemini");await Et.rm(e,{recursive:!0,force:!0});let t=et.join(Ht.homedir(),".agents","skills");await Et.rm(t,{recursive:!0,force:!0})},us={baseDir:et.join(Ht.homedir(),".gemini"),include:["tmp"]};var Or={codex:{runner:Nr,clean:ns,nativeSessionArchive:ss},claude:{runner:Rr,clean:Zn,nativeSessionArchive:Qn},gemini:{runner:Pr,clean:cs,nativeSessionArchive:us}},Dr=Object.keys(Or),$r=e=>Or[e]?.nativeSessionArchive,tt=Or;import{readFileSync as El}from"fs";import vl from"path";import{createRequire as bl}from"module";var pa=["error","failed","exception","fatal","panic","abort","crash"];function ds(e){let t=e.split(`
74
74
  `),r=[],n=-1,s=0;for(;s<t.length;){let a=t[s].slice(0,500).toLowerCase();if(pa.some(l=>a.includes(l))){let l=Math.max(0,s-10,n+1),d=Math.min(t.length-1,s+20),m=[];for(let p=l;p<=d;p++)m.push(t[p]);r.push(m.join(`
75
75
  `)),n=d,s=d+1}else s++}if(r.length===0)return e;let i=r.map((o,a)=>`<extracted_error_chunk order="${a+1}">
76
76
  ${o}
77
77
  </extracted_error_chunk>`).join(`
78
78
 
79
- `);return i.length>e.length*.8?e:i}import{execSync as Ra}from"child_process";import Xt from"fs/promises";import Ca from"path";import me from"process";import{getTracer as Na}from"@netlify/otel";import vt from"process";var Wt=vt.env.NETLIFY_API_URL,zt=vt.env.NETLIFY_API_TOKEN,X=E("api"),Ie=()=>vt.env.NETLIFY_LOCAL_MODE==="true",ie=async(e,t={})=>{if(!Wt||!zt)throw new Error("No API URL or token");let r=new URL(e,Wt),n={...t,headers:{...t.headers,Authorization:`Bearer ${zt}`}};vt.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let s=await fetch(r,n),i=s.ok&&s.status<=299;if(vt.env.AGENT_RUNNERS_DEBUG==="true")X.log(`Response headers for ${r}:`),s.headers.forEach((a,c)=>{X.log(` ${c}: ${a}`)});else{let a=s.headers.get("x-request-id")||s.headers.get("x-nf-request-id");X.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||(X.error(`Got status ${s.status} for request ${r}`),S.inc("api.request_failed",1,{status:s.status})),t.raw){if(!i)throw new Error(`API request failed: ${s.status} ${s.statusText}`);return s}let o=await(s.headers.get("content-type")?.includes("application/json")?s.json():s.text());if(!i){let a=typeof o=="string"?o:JSON.stringify(o);throw s.status===404?new he(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):s.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new he(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${s.status} - ${a}`)}return o},ps=e=>{X.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Wt=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(zt=e.constants.NETLIFY_API_TOKEN)},ms=()=>({apiUrl:Wt,token:zt}),bt=async(e,t)=>Ie()?(X.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ie(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),pe=async(e,t,r)=>Ie()?(X.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 gs=async e=>Ie()?(X.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):ie(`/api/v1/sites/${e}`),fs=async(e,t)=>Ie()?(X.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ie(`/api/v1/agent_runners/${e}/sessions/${t}`),hs=(e,t,r)=>ie(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),ys=(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},gracefulOn503:!0}),_s=async(e,t)=>Ie()?(X.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"}),ws=async(e,t)=>Ie()?(X.log("Mock API: getNativeSessionUploadUrl called",{runnerId:e,sessionId:t}),{upload_url:"https://s3.mock.com/mock-upload-url-native-session",s3_key:"mock-s3-key-native-session"}):ie(`/api/v1/agent_runners/${e}/sessions/${t}/native_session/upload`,{method:"POST"}),Es=async(e,t)=>Ie()?(X.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):ie(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),Fr="netlifydb_readonly",vs=async e=>(await ie(`/api/v1/sites/${e}/database?role=${Fr}`,{raw:!0})).json(),bs=async e=>{if(Ie())return X.log("Mock API: siteHasDatabase called",{siteId:e}),!1;try{return await ie(`/api/v1/sites/${e}/database?role=${Fr}`,{raw:!0}),!0}catch(t){if(t?.message?.includes("404"))return!1;X.warn("siteHasDatabase check inconclusive",{siteId:e,error:t?.message});return}},Ss=async(e,t)=>(await ie(`/api/v1/sites/${e}/database/branch/${encodeURIComponent(t)}?role=${Fr}`,{raw:!0})).json(),Ts=async e=>ie(`/api/v1/sites/${e}/database`,{method:"POST",json:{}}),xs=async(e,t)=>ie(`/api/v1/sites/${e}/database/branch`,{method:"POST",json:{branch_id:t}}),St=async(e,t,{maxRetries:r=3,baseDelayMs:n=500,contentType:s="text/plain"}={})=>{X.log(`Uploading to S3: ${e.substring(0,50)}...`);for(let i=1;i<=r;i++)try{let o=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":s}});if(!o.ok)throw new Error(`S3 upload failed with status ${o.status}`);return o}catch(o){if(i===r)throw o;let a=n*2**(i-1);X.warn(`S3 upload attempt ${i}/${r} failed: ${o.message}. Retrying in ${a}ms...`),await new Promise(c=>setTimeout(c,a))}};var rt=E("ai_gateway"),Lr=null;var Vt=async()=>{if(Lr)return Lr;rt.log("Fetching available AI gateway providers");let e=await fetch(`${ms().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 Lr=t,rt.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},ma=async(e,t)=>{let n=(await Vt()).providers[e];if(!n)return rt.log(`Provider '${e}' not found`),!1;let s=n.models.includes(t);return rt.log(`Model validation for ${e}/${t}`,{isAvailable:s}),s},Is=async({config:e})=>{let t,r,n,s,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(n),rt.log("Requesting AI gateway information");let l=await(i?hs(e.accountId,e.id,e.sessionId):ys(e.siteId,e.id,e.sessionId));if({token:t,url:s}=l,r=l.expires_at?l.expires_at*1e3:void 0,process.env.NETLIFY_AI_GATEWAY_KEY=t,process.env.NETLIFY_AI_GATEWAY_BASE_URL=s,rt.log("Got AI gateway information",{token:!!t,expiresAt:r,url:s}),r){let d=r-Date.now()-6e4;d>0&&(n=setTimeout(()=>{a()},d))}};return await Promise.all([a(),Vt()]),{get url(){return s},get token(){return t},isModelAvailableForProvider:ma}};import ga from"crypto";import Jt from"fs/promises";import Tt from"path";import fa from"process";var Mr=E("asset_fetch"),Kt=100*1024*1024,As=e=>ga.createHash("sha1").update(e).digest("hex").slice(0,8),ha=e=>typeof e=="string"&&e.length>0&&e!=="."&&e!==".."&&e===Tt.basename(e),ya=async e=>{try{return await Jt.stat(e),!0}catch{return!1}},_a=e=>decodeURIComponent(new URL(e).pathname),wa=(e,t)=>{let r=Tt.basename(e)||"attachment";if(!t.has(r))return t.add(r),r;let n=Tt.extname(r),s=r.slice(0,r.length-n.length),i=`${s}-${As(e)}${n}`;for(let o=1;t.has(i);o+=1)i=`${s}-${As(e)}-${o}${n}`;return t.add(i),i},Ea=async(e,t)=>{let r=await fetch(e);if(!r.ok)throw new Error(`Asset download failed: ${r.status} ${r.statusText}`);let n=r.headers.get("content-length");if(n&&Number(n)>Kt)throw new Error(`Asset too large: ${n} bytes (max ${Kt})`);let s=Buffer.from(await r.arrayBuffer());if(s.byteLength>Kt)throw new Error(`Asset too large: ${s.byteLength} bytes (max ${Kt})`);let i=`${t}.part`;await Jt.writeFile(i,s),await Jt.rename(i,t)},va=async(e,t,r)=>{if(!ha(e)){Mr.warn(`Skipping attachments for unsafe session id: ${e}`);return}if(!Array.isArray(t)||t.length===0)return;let n=Tt.join(r,re,Ce,e);await Jt.mkdir(n,{recursive:!0});let s=new Set,i=t.filter(a=>typeof a=="string"&&a.length>0).map(a=>({url:a,filename:wa(_a(a),s)}));if(i.length===0)return;let o=0;await Promise.all(i.map(async({url:a,filename:c})=>{let l=Tt.join(n,c);await ya(l)||(await Ea(a,l),o+=1)})),Mr.info(`Session ${e}: fetched ${o} attachment(s), ${i.length-o} already present`)},Rs=async({assetMap:e,cwd:t=fa.cwd()})=>{let r=Object.entries(e??{});if(r.length===0)return;let n=r.reduce((s,[,i])=>s+(i?.length??0),0);Mr.info(`Reconciling ${n} attachment(s) across ${r.length} session(s)`),await Promise.all(r.map(([s,i])=>va(s,i,t)))};import{Buffer as Cs}from"buffer";import ba from"path";var Ns=E("repo"),Ps=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{Ns.info("Getting runner diffs");let n=await Ta(r),{hasChanges:s}=n,{status:i}=n;if(!s)return{hasChanges:!1};if(!t){let x=Ia(i);await Aa(x,r)}Ns.info("Changes after processing"),await jr(r);let o=await Br(i,r);if(await Ur(o,r),s=await xa(r),!s)return{hasChanges:!1,ignored:o};process.env.NETLIFY_INTERNAL_GIT="1";try{await j("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},c=await j("git",["diff",e.runSha,"HEAD"],a),l=String(c.stdout??"");if(s=!!l,!s)return await ks(r),{hasChanges:!1,ignored:o};let d=await j("git",["diff",e.runSha,"HEAD","--binary"],a),m=String(d.stdout??""),p,f;if(e.sha){let x=await j("git",["diff",e.sha,"HEAD"],a);p=String(x.stdout??"");let _=await j("git",["diff",e.sha,"HEAD","--binary"],a),g=String(_.stdout??"");p!==g&&(f=Cs.from(g).toString("base64"))}await ks(r);let h={hasChanges:!0,diff:l,resultDiff:p,ignored:o};return l!==m&&(h.diffBinary=Cs.from(m).toString("base64")),f&&(h.resultDiffBinary=f),h},ks=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await j("git",["reset","--soft","HEAD~1"],{cwd:e})},Ur=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await j("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},jr=async(e=process.cwd())=>{let t=await j("git",["status","-s"],{cwd:e});return String(t.stdout??"")},Os=/.. (.+)?\.log$/,Sa=[Os],Ta=async(e=process.cwd())=>{let t=await jr(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
80
- `).filter(s=>Sa.some(o=>o instanceof RegExp?o.test(s):s===o)?!1:s[1]?.trim()!=="")).length!==0,status:t}},xa=async(e=process.cwd())=>{try{return await j("git",["diff","--staged","--quiet"],{cwd:e}),!1}catch{return!0}},Gr=async(e=process.cwd())=>{let{stdout:t}=await j("git",["rev-parse","HEAD"],{cwd:e});return String(t??"").trim()},Ds=async(e=process.cwd())=>{let{stdout:t}=await j("git",["rev-list","--max-parents=0","HEAD"],{cwd:e});return String(t??"").trim()},Br=async(e,t=process.cwd())=>{e||=await jr(t);let r=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build","CLAUDE.local.md"],n=[];return e.split(`
81
- `).forEach(s=>{r.forEach(o=>{let a=s===`?? ${o}`,c=s.startsWith(`?? ${o}/`)||s.startsWith(`?? ${o}${ba.sep}`);(a||c)&&n.push(`:!${o}`)});let i=s.match(Os)?.[1];i&&n.push(`:!${i}.log`)}),n},Yr=async(e=process.cwd())=>{await j("git",["reset","--hard","HEAD"],{cwd:e})},Ia=e=>{let t=e.split(`
82
- `).reduce((r,n)=>{if(!n)return r;let[s,i,,...o]=n,a=o.join(""),c=s.trim(),l=i.trim();return r[a]?r[a].change=l:r[a]={filePath:a,stage:c,change:l},r},{});return Object.values(t)},Aa=async(e,t=process.cwd())=>{let r=e.filter(n=>n.stage&&!n.change).map(n=>n.filePath);r.length!==0&&await j("git",["restore","--staged","--worktree","--pathspec-from-file=-"],{cwd:t,input:r.join(`
83
- `)})};var Ae=E("init_stage"),ka=async(e,t)=>{if(!(!V().fetchAssetsEnabled||!e.assetMap))try{await Rs({assetMap:e.assetMap,cwd:t})}catch(r){throw Ae.error("Failed to fetch session assets",{error:r?.message||r}),S.inc("assets.fetch_failed",1),r}},$s=async({config:e,apiThrottle:t,apiToken:r,cwd:n,runnerVersion:s})=>await L(Na(),"init-stage",async i=>{let o=performance.now(),c=(e.assetMap?.[e.sessionId]??[]).filter(b=>typeof b=="string"&&b.length>0).length;S.inc("assets.session",1,{has_assets:c>0}),c>0&&S.distribution("assets.session.count",c),i?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":s||"unknown","init.assetCount":c});let l=tt[e.runner];if(!l)throw i?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let d=Oa({apiToken:r,config:e});if(ps(d),e.siteId)try{e.site=await gs(e.siteId)}catch(b){Ae.error("Failed to get the site information",{error:b})}let m=e.useGateway?await Is({config:e}):void 0;i?.setAttributes({"init.aiGateway.created":!!m}),await pe(e.id,e.sessionId,{steps:[{title:"Environment ready",category:w.Environment,type:"ready"}]});let p=5*1024,f=1e4,h=Pt(async({steps:b=[],duration:A})=>{let F=b.map(D=>{let P=D.title?yr(de(D.title),p):void 0,G=D.category===w.AgentMessage||D.category===w.UserMessage,$=D.message?de(D.message):void 0,N=$&&!G?yr($,f):$,I=D.category===w.UserMessage,M=N&&!I?Dt(N):N;return M!==N&&Ae.info("Sanitized internal error from step message",{original:N}),{...D,title:P,message:M}});b.length=0;try{return await pe(e.id,e.sessionId,{steps:F,duration:A})}catch(D){Ae.error("persistSteps failed",{error:D?.message||D})}},t);Ae.info("Adding build files to stage");let x=await Br();await Ur(x),me.env.NETLIFY_LOCAL_MODE||await Pa();let _;e.hasRepo?e.sha?(_=e.sha,i?.setAttributes({"init.sha.source":"provided"})):(_=await Gr(),await bt(e.id,{sha:_}),i?.setAttributes({"init.sha.source":"current_commit"})):(_=await Ds(),i?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"})),e.runSha=await Gr(),await ka(e,n);let g=performance.now()-o;return i?.setAttributes({"init.sha":_||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:m,context:d,persistSteps:h,runner:l,sha:_}}),Pa=async()=>{let e="/tmp/netlify-git-wrapper",t=Ca.join(e,"git");try{await Xt.access(t,Xt.constants.X_OK),me.env.PATH?.split(":").includes(e)||(me.env.PATH=`${e}:${me.env.PATH}`),Ae.info("Git wrapper already installed; skipping");return}catch{}let r="/usr/bin/git";try{let s=(me.env.PATH||"").split(":").filter(i=>i!==e).join(":");r=Ra("which git",{env:{...me.env,PATH:s}}).toString().trim()||r}catch{}let n=`#!/bin/bash
79
+ `);return i.length>e.length*.8?e:i}import{execSync as Ca}from"child_process";import Xt from"fs/promises";import Na from"path";import me from"process";import{getTracer as ka}from"@netlify/otel";import vt from"process";var Wt=vt.env.NETLIFY_API_URL,zt=vt.env.NETLIFY_API_TOKEN,X=E("api"),Ie=()=>vt.env.NETLIFY_LOCAL_MODE==="true",ie=async(e,t={})=>{if(!Wt||!zt)throw new Error("No API URL or token");let r=new URL(e,Wt),n={...t,headers:{...t.headers,Authorization:`Bearer ${zt}`}};vt.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let s=await fetch(r,n),i=s.ok&&s.status<=299;if(vt.env.AGENT_RUNNERS_DEBUG==="true")X.log(`Response headers for ${r}:`),s.headers.forEach((a,c)=>{X.log(` ${c}: ${a}`)});else{let a=s.headers.get("x-request-id")||s.headers.get("x-nf-request-id");X.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||(X.error(`Got status ${s.status} for request ${r}`),S.inc("api.request_failed",1,{status:s.status})),t.raw){if(!i)throw new Error(`API request failed: ${s.status} ${s.statusText}`);return s}let o=await(s.headers.get("content-type")?.includes("application/json")?s.json():s.text());if(!i){let a=typeof o=="string"?o:JSON.stringify(o);throw s.status===404?new he(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):s.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new he(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${s.status} - ${a}`)}return o},ps=e=>{X.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Wt=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(zt=e.constants.NETLIFY_API_TOKEN)},ms=()=>({apiUrl:Wt,token:zt}),bt=async(e,t)=>Ie()?(X.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ie(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),pe=async(e,t,r)=>Ie()?(X.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 gs=async e=>Ie()?(X.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):ie(`/api/v1/sites/${e}`),fs=async(e,t)=>Ie()?(X.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ie(`/api/v1/agent_runners/${e}/sessions/${t}`),hs=(e,t,r)=>ie(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),ys=(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},gracefulOn503:!0}),_s=async(e,t)=>Ie()?(X.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"}),ws=async(e,t)=>Ie()?(X.log("Mock API: getNativeSessionUploadUrl called",{runnerId:e,sessionId:t}),{upload_url:"https://s3.mock.com/mock-upload-url-native-session",s3_key:"mock-s3-key-native-session"}):ie(`/api/v1/agent_runners/${e}/sessions/${t}/native_session/upload`,{method:"POST"}),Es=async(e,t)=>Ie()?(X.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):ie(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),Fr="netlifydb_readonly",vs=async e=>(await ie(`/api/v1/sites/${e}/database?role=${Fr}`,{raw:!0})).json(),bs=async e=>{if(Ie())return X.log("Mock API: siteHasDatabase called",{siteId:e}),!1;try{return await ie(`/api/v1/sites/${e}/database?role=${Fr}`,{raw:!0}),!0}catch(t){if(t?.message?.includes("404"))return!1;X.warn("siteHasDatabase check inconclusive",{siteId:e,error:t?.message});return}},Ss=async(e,t)=>(await ie(`/api/v1/sites/${e}/database/branch/${encodeURIComponent(t)}?role=${Fr}`,{raw:!0})).json(),Ts=async e=>ie(`/api/v1/sites/${e}/database`,{method:"POST",json:{}}),xs=async(e,t)=>ie(`/api/v1/sites/${e}/database/branch`,{method:"POST",json:{branch_id:t}}),St=async(e,t,{maxRetries:r=3,baseDelayMs:n=500,contentType:s="text/plain"}={})=>{X.log(`Uploading to S3: ${e.substring(0,50)}...`);for(let i=1;i<=r;i++)try{let o=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":s}});if(!o.ok)throw new Error(`S3 upload failed with status ${o.status}`);return o}catch(o){if(i===r)throw o;let a=n*2**(i-1);X.warn(`S3 upload attempt ${i}/${r} failed: ${o.message}. Retrying in ${a}ms...`),await new Promise(c=>setTimeout(c,a))}};var rt=E("ai_gateway"),Lr=null;var Vt=async()=>{if(Lr)return Lr;rt.log("Fetching available AI gateway providers");let e=await fetch(`${ms().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 Lr=t,rt.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},ma=async(e,t)=>{let n=(await Vt()).providers[e];if(!n)return rt.log(`Provider '${e}' not found`),!1;let s=n.models.includes(t);return rt.log(`Model validation for ${e}/${t}`,{isAvailable:s}),s},Is=async({config:e})=>{let t,r,n,s,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(n),rt.log("Requesting AI gateway information");let l=await(i?hs(e.accountId,e.id,e.sessionId):ys(e.siteId,e.id,e.sessionId));if({token:t,url:s}=l,r=l.expires_at?l.expires_at*1e3:void 0,process.env.NETLIFY_AI_GATEWAY_KEY=t,process.env.NETLIFY_AI_GATEWAY_BASE_URL=s,rt.log("Got AI gateway information",{token:!!t,expiresAt:r,url:s}),r){let d=r-Date.now()-6e4;d>0&&(n=setTimeout(()=>{a()},d))}};return await Promise.all([a(),Vt()]),{get url(){return s},get token(){return t},isModelAvailableForProvider:ma}};import ga from"crypto";import Jt from"fs/promises";import Tt from"path";import fa from"process";var Mr=E("asset_fetch"),Kt=100*1024*1024,ha=6e4,As=e=>ga.createHash("sha1").update(e).digest("hex").slice(0,8),ya=e=>typeof e=="string"&&e.length>0&&e!=="."&&e!==".."&&e===Tt.basename(e),_a=async e=>{try{return await Jt.stat(e),!0}catch{return!1}},wa=e=>decodeURIComponent(new URL(e).pathname),Ea=(e,t)=>{let r=Tt.basename(e)||"attachment";if(!t.has(r))return t.add(r),r;let n=Tt.extname(r),s=r.slice(0,r.length-n.length),i=`${s}-${As(e)}${n}`;for(let o=1;t.has(i);o+=1)i=`${s}-${As(e)}-${o}${n}`;return t.add(i),i},va=async(e,t)=>{let r=await fetch(e,{signal:AbortSignal.timeout(ha)});if(!r.ok)throw new Error(`Asset download failed: ${r.status} ${r.statusText}`);let n=r.headers.get("content-length");if(n&&Number(n)>Kt)throw new Error(`Asset too large: ${n} bytes (max ${Kt})`);let s=Buffer.from(await r.arrayBuffer());if(s.byteLength>Kt)throw new Error(`Asset too large: ${s.byteLength} bytes (max ${Kt})`);let i=`${t}.part`;await Jt.writeFile(i,s),await Jt.rename(i,t)},ba=async(e,t,r)=>{if(!ya(e)){Mr.warn(`Skipping attachments for unsafe session id: ${e}`);return}if(!Array.isArray(t)||t.length===0)return;let n=Tt.join(r,re,Ce,e);await Jt.mkdir(n,{recursive:!0});let s=new Set,i=t.filter(a=>typeof a=="string"&&a.length>0).map(a=>({url:a,filename:Ea(wa(a),s)}));if(i.length===0)return;let o=0;await Promise.all(i.map(async({url:a,filename:c})=>{let l=Tt.join(n,c);await _a(l)||(await va(a,l),o+=1)})),Mr.info(`Session ${e}: fetched ${o} attachment(s), ${i.length-o} already present`)},Rs=async({assetMap:e,cwd:t=fa.cwd()})=>{let r=Object.entries(e??{});if(r.length===0)return;let n=r.reduce((s,[,i])=>s+(i?.length??0),0);Mr.info(`Reconciling ${n} attachment(s) across ${r.length} session(s)`),await Promise.all(r.map(([s,i])=>ba(s,i,t)))};import{Buffer as Cs}from"buffer";import Sa from"path";var Ns=E("repo"),Ps=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{Ns.info("Getting runner diffs");let n=await xa(r),{hasChanges:s}=n,{status:i}=n;if(!s)return{hasChanges:!1};if(!t){let x=Aa(i);await Ra(x,r)}Ns.info("Changes after processing"),await jr(r);let o=await Br(i,r);if(await Ur(o,r),s=await Ia(r),!s)return{hasChanges:!1,ignored:o};process.env.NETLIFY_INTERNAL_GIT="1";try{await j("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},c=await j("git",["diff",e.runSha,"HEAD"],a),l=String(c.stdout??"");if(s=!!l,!s)return await ks(r),{hasChanges:!1,ignored:o};let d=await j("git",["diff",e.runSha,"HEAD","--binary"],a),m=String(d.stdout??""),p,f;if(e.sha){let x=await j("git",["diff",e.sha,"HEAD"],a);p=String(x.stdout??"");let _=await j("git",["diff",e.sha,"HEAD","--binary"],a),g=String(_.stdout??"");p!==g&&(f=Cs.from(g).toString("base64"))}await ks(r);let h={hasChanges:!0,diff:l,resultDiff:p,ignored:o};return l!==m&&(h.diffBinary=Cs.from(m).toString("base64")),f&&(h.resultDiffBinary=f),h},ks=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await j("git",["reset","--soft","HEAD~1"],{cwd:e})},Ur=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await j("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},jr=async(e=process.cwd())=>{let t=await j("git",["status","-s"],{cwd:e});return String(t.stdout??"")},Os=/.. (.+)?\.log$/,Ta=[Os],xa=async(e=process.cwd())=>{let t=await jr(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
80
+ `).filter(s=>Ta.some(o=>o instanceof RegExp?o.test(s):s===o)?!1:s[1]?.trim()!=="")).length!==0,status:t}},Ia=async(e=process.cwd())=>{try{return await j("git",["diff","--staged","--quiet"],{cwd:e}),!1}catch{return!0}},Gr=async(e=process.cwd())=>{let{stdout:t}=await j("git",["rev-parse","HEAD"],{cwd:e});return String(t??"").trim()},Ds=async(e=process.cwd())=>{let{stdout:t}=await j("git",["rev-list","--max-parents=0","HEAD"],{cwd:e});return String(t??"").trim()},Br=async(e,t=process.cwd())=>{e||=await jr(t);let r=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build","CLAUDE.local.md"],n=[];return e.split(`
81
+ `).forEach(s=>{r.forEach(o=>{let a=s===`?? ${o}`,c=s.startsWith(`?? ${o}/`)||s.startsWith(`?? ${o}${Sa.sep}`);(a||c)&&n.push(`:!${o}`)});let i=s.match(Os)?.[1];i&&n.push(`:!${i}.log`)}),n},Yr=async(e=process.cwd())=>{await j("git",["reset","--hard","HEAD"],{cwd:e})},Aa=e=>{let t=e.split(`
82
+ `).reduce((r,n)=>{if(!n)return r;let[s,i,,...o]=n,a=o.join(""),c=s.trim(),l=i.trim();return r[a]?r[a].change=l:r[a]={filePath:a,stage:c,change:l},r},{});return Object.values(t)},Ra=async(e,t=process.cwd())=>{let r=e.filter(n=>n.stage&&!n.change).map(n=>n.filePath);r.length!==0&&await j("git",["restore","--staged","--worktree","--pathspec-from-file=-"],{cwd:t,input:r.join(`
83
+ `)})};var Ae=E("init_stage"),Pa=async(e,t)=>{if(!(!V().fetchAssetsEnabled||!e.assetMap))try{await Rs({assetMap:e.assetMap,cwd:t})}catch(r){throw Ae.error("Failed to fetch session assets",{error:r?.message||r}),S.inc("assets.fetch_failed",1),r}},$s=async({config:e,apiThrottle:t,apiToken:r,cwd:n,runnerVersion:s})=>await L(ka(),"init-stage",async i=>{let o=performance.now(),c=(e.assetMap?.[e.sessionId]??[]).filter(b=>typeof b=="string"&&b.length>0).length;S.inc("assets.session",1,{has_assets:c>0}),c>0&&S.distribution("assets.session.count",c),i?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":s||"unknown","init.assetCount":c});let l=tt[e.runner];if(!l)throw i?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let d=Da({apiToken:r,config:e});if(ps(d),e.siteId)try{e.site=await gs(e.siteId)}catch(b){Ae.error("Failed to get the site information",{error:b})}let m=e.useGateway?await Is({config:e}):void 0;i?.setAttributes({"init.aiGateway.created":!!m}),await pe(e.id,e.sessionId,{steps:[{title:"Environment ready",category:w.Environment,type:"ready"}]});let p=5*1024,f=1e4,h=Pt(async({steps:b=[],duration:A})=>{let F=b.map(D=>{let P=D.title?yr(de(D.title),p):void 0,G=D.category===w.AgentMessage||D.category===w.UserMessage,$=D.message?de(D.message):void 0,N=$&&!G?yr($,f):$,I=D.category===w.UserMessage,M=N&&!I?Dt(N):N;return M!==N&&Ae.info("Sanitized internal error from step message",{original:N}),{...D,title:P,message:M}});b.length=0;try{return await pe(e.id,e.sessionId,{steps:F,duration:A})}catch(D){Ae.error("persistSteps failed",{error:D?.message||D})}},t);Ae.info("Adding build files to stage");let x=await Br();await Ur(x),me.env.NETLIFY_LOCAL_MODE||await Oa();let _;e.hasRepo?e.sha?(_=e.sha,i?.setAttributes({"init.sha.source":"provided"})):(_=await Gr(),await bt(e.id,{sha:_}),i?.setAttributes({"init.sha.source":"current_commit"})):(_=await Ds(),i?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"})),e.runSha=await Gr(),await Pa(e,n);let g=performance.now()-o;return i?.setAttributes({"init.sha":_||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:m,context:d,persistSteps:h,runner:l,sha:_}}),Oa=async()=>{let e="/tmp/netlify-git-wrapper",t=Na.join(e,"git");try{await Xt.access(t,Xt.constants.X_OK),me.env.PATH?.split(":").includes(e)||(me.env.PATH=`${e}:${me.env.PATH}`),Ae.info("Git wrapper already installed; skipping");return}catch{}let r="/usr/bin/git";try{let s=(me.env.PATH||"").split(":").filter(i=>i!==e).join(":");r=Ca("which git",{env:{...me.env,PATH:s}}).toString().trim()||r}catch{}let n=`#!/bin/bash
84
84
  # Git wrapper that blocks add and commit commands
85
85
  # The deployment system handles staging and commits automatically
86
86
 
@@ -110,7 +110,7 @@ case "$1" in
110
110
  exec ${r} "$@"
111
111
  ;;
112
112
  esac
113
- `;try{await Xt.mkdir(e,{recursive:!0}),await Xt.writeFile(t,n,{mode:493}),me.env.PATH=`${e}:${me.env.PATH}`,me.env.NETLIFY_INTERNAL_GIT="0",Ae.info("Installed git wrapper to block add/commit commands")}catch(s){Ae.warn("Failed to install git wrapper",{error:s?.message||s}),S.inc("context.degraded",1,{component:"git_wrapper"})}},Oa=({apiToken:e,config:t})=>({constants:{NETLIFY_API_HOST:me.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||me.env.NETLIFY_API_TOKEN,SITE_ID:t.siteId,FUNCTIONS_DIST:me.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:j}});import{getTracer as Vr}from"@netlify/otel";import Da from"crypto";import Z from"fs/promises";import qr from"os";import U from"path";import ye from"process";import{fileURLToPath as $a}from"url";import{trace as Fa}from"@opentelemetry/api";var le=E("context"),La=$a(import.meta.url),Ma=U.dirname(La),Ls={claude:U.join(qr.homedir(),".claude","skills"),gemini:U.join(qr.homedir(),".agents","skills"),codex:U.join(qr.homedir(),".agents","skills")},Fs=U.join(Ma,"skills"),Wr=e=>e.replace(/<\/user_request/gi,"&lt;/user_request"),zr=e=>typeof e=="string"&&/^[A-Za-z0-9_-]+$/.test(e)?e:null,Ua=({userRequest:e,buildErrorContextText:t="",projectContext:r="",sessionHistoryContextText:n="",additionalContext:s="",netlifyInfo:i={},cliPath:o="netlify",skillsDir:a="",netlifyFolder:c=re,resultsFilename:l=Me,assetsFolder:d=Ce,sessionId:m,nodeVersion:p=ye.version||"unknown"})=>{let f=zr(m),h=s?`<additional_rules>
113
+ `;try{await Xt.mkdir(e,{recursive:!0}),await Xt.writeFile(t,n,{mode:493}),me.env.PATH=`${e}:${me.env.PATH}`,me.env.NETLIFY_INTERNAL_GIT="0",Ae.info("Installed git wrapper to block add/commit commands")}catch(s){Ae.warn("Failed to install git wrapper",{error:s?.message||s}),S.inc("context.degraded",1,{component:"git_wrapper"})}},Da=({apiToken:e,config:t})=>({constants:{NETLIFY_API_HOST:me.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||me.env.NETLIFY_API_TOKEN,SITE_ID:t.siteId,FUNCTIONS_DIST:me.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:j}});import{getTracer as Vr}from"@netlify/otel";import $a from"crypto";import Z from"fs/promises";import qr from"os";import U from"path";import ye from"process";import{fileURLToPath as Fa}from"url";import{trace as La}from"@opentelemetry/api";var le=E("context"),Ma=Fa(import.meta.url),Ua=U.dirname(Ma),Ls={claude:U.join(qr.homedir(),".claude","skills"),gemini:U.join(qr.homedir(),".agents","skills"),codex:U.join(qr.homedir(),".agents","skills")},Fs=U.join(Ua,"skills"),Wr=e=>e.replace(/<\/user_request/gi,"&lt;/user_request"),zr=e=>typeof e=="string"&&/^[A-Za-z0-9_-]+$/.test(e)?e:null,ja=({userRequest:e,buildErrorContextText:t="",projectContext:r="",sessionHistoryContextText:n="",additionalContext:s="",netlifyInfo:i={},cliPath:o="netlify",skillsDir:a="",netlifyFolder:c=re,resultsFilename:l=Me,assetsFolder:d=Ce,sessionId:m,nodeVersion:p=ye.version||"unknown"})=>{let f=zr(m),h=s?`<additional_rules>
114
114
  ${s}
115
115
  </additional_rules>`:"";return`
116
116
  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.
@@ -170,12 +170,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
170
170
  </extra_context>
171
171
 
172
172
  ${n}
173
- `},Hr=null;var Zt="SKILL.md",ja=()=>{let e=V().skillVariations;return le.log(`Active skill variations: ${e.length?e.join(", "):"none"}`),e},Ms=e=>{let t=e.match(/^(.+)@([^.]+)(.*)$/);return t?{baseName:`${t[1]}${t[3]}`,variation:t[2]}:{baseName:e,variation:null}},Ga=async(e,t=[])=>{try{let r=await Z.readdir(e);for(let n of r){let{baseName:s,variation:i}=Ms(n);if(i&&s===Zt&&t.includes(i))return{filename:n,variation:i}}}catch{}return{filename:Zt,variation:null}},Ba=async(e,{targetDir:t}={})=>{let r=t||Ls[e];if(!r)return le.warn(`Unknown runner: ${e}, skipping skills setup`),[];if(Hr)return Hr;let n=[],s=ja();try{await Z.mkdir(r,{recursive:!0});let i=await Z.readdir(Fs);for(let o of i){let a=U.join(Fs,o);if(!(await Z.stat(a)).isDirectory())continue;let{baseName:l,variation:d}=Ms(o);if(d&&!s.includes(d))continue;let m=U.join(r,l);try{await Z.cp(a,m,{recursive:!0});let p=await Ga(a,s);p.variation&&(await Z.copyFile(U.join(a,p.filename),U.join(m,Zt)),await Z.unlink(U.join(m,p.filename)),le.log(`Using skill variation for ${l}: ${p.filename}`)),n.push(l),d&&le.log(`Installed skill variation: ${l} (variation: ${d})`)}catch(p){le.warn(`Failed to copy skill ${l}:`,p.message),S.inc("context.degraded",1,{component:"skills"})}}}catch(i){le.warn("Failed to setup agent skills:",i.message),S.inc("context.degraded",1,{component:"skills"})}if(n.includes("netlify-ai-gateway"))try{let i=await Vt(),o=U.join(r,"netlify-ai-gateway",Zt),a=await Z.readFile(o,"utf-8");if(a.includes("<!-- AVAILABLE_MODELS -->")){let c=Object.entries(i.providers).map(([l,d])=>`### ${l}
173
+ `},Hr=null;var Zt="SKILL.md",Ga=()=>{let e=V().skillVariations;return le.log(`Active skill variations: ${e.length?e.join(", "):"none"}`),e},Ms=e=>{let t=e.match(/^(.+)@([^.]+)(.*)$/);return t?{baseName:`${t[1]}${t[3]}`,variation:t[2]}:{baseName:e,variation:null}},Ba=async(e,t=[])=>{try{let r=await Z.readdir(e);for(let n of r){let{baseName:s,variation:i}=Ms(n);if(i&&s===Zt&&t.includes(i))return{filename:n,variation:i}}}catch{}return{filename:Zt,variation:null}},Ya=async(e,{targetDir:t}={})=>{let r=t||Ls[e];if(!r)return le.warn(`Unknown runner: ${e}, skipping skills setup`),[];if(Hr)return Hr;let n=[],s=Ga();try{await Z.mkdir(r,{recursive:!0});let i=await Z.readdir(Fs);for(let o of i){let a=U.join(Fs,o);if(!(await Z.stat(a)).isDirectory())continue;let{baseName:l,variation:d}=Ms(o);if(d&&!s.includes(d))continue;let m=U.join(r,l);try{await Z.cp(a,m,{recursive:!0});let p=await Ba(a,s);p.variation&&(await Z.copyFile(U.join(a,p.filename),U.join(m,Zt)),await Z.unlink(U.join(m,p.filename)),le.log(`Using skill variation for ${l}: ${p.filename}`)),n.push(l),d&&le.log(`Installed skill variation: ${l} (variation: ${d})`)}catch(p){le.warn(`Failed to copy skill ${l}:`,p.message),S.inc("context.degraded",1,{component:"skills"})}}}catch(i){le.warn("Failed to setup agent skills:",i.message),S.inc("context.degraded",1,{component:"skills"})}if(n.includes("netlify-ai-gateway"))try{let i=await Vt(),o=U.join(r,"netlify-ai-gateway",Zt),a=await Z.readFile(o,"utf-8");if(a.includes("<!-- AVAILABLE_MODELS -->")){let c=Object.entries(i.providers).map(([l,d])=>`### ${l}
174
174
 
175
175
  ${d.models.map(m=>`- \`${m}\``).join(`
176
176
  `)}`).join(`
177
177
 
178
- `);a=a.replace("<!-- AVAILABLE_MODELS -->",c),await Z.writeFile(o,a,"utf-8"),le.log("Injected dynamic model list into AI Gateway skill",{modelList:c})}}catch(i){le.warn("Failed to inject dynamic model list into AI Gateway skill:",i.message),S.inc("context.degraded",1,{component:"model_list"})}return n.length>0&&(le.log(`Installed ${n.length} skills for ${e}: ${n.join(", ")}`,{runner:e,skills:n,targetDir:r}),Fa.getActiveSpan()?.setAttributes({"agent.skills_loaded":n,"agent.skills_loaded_count":n.length})),Hr=n,n},Ya=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:ye.env.NETLIFY_TEAM_ID,userId:ye.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:ye.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},qa=10,Ha=async e=>{let{name:t,ext:r}=U.parse(e),n=e,s=U.join(ye.cwd(),re,n),i=0;for(;await Us(s);){if(i>=qa)throw new Error("Failed to generate context file");n=`${t}-${Da.randomUUID().slice(0,5)}${r}`,s=U.join(ye.cwd(),re,n),i+=1}return n},Us=async e=>{try{return await Z.access(e),!0}catch{return!1}},js=async({cliPath:e,netlify:t,config:r,buildErrorContext:n,additionalContext:s,resumePrompt:i})=>{let o=Ya(t),a=await Ha(cn),c=U.join(ye.cwd(),re);await Z.mkdir(c,{recursive:!0});let l=U.join(re,a),d=U.join(ye.cwd(),l),m=U.join(ye.cwd(),re,Me);try{await Z.unlink(m),le.log(`Deleted old results file: ${m}`)}catch{}let p=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
178
+ `);a=a.replace("<!-- AVAILABLE_MODELS -->",c),await Z.writeFile(o,a,"utf-8"),le.log("Injected dynamic model list into AI Gateway skill",{modelList:c})}}catch(i){le.warn("Failed to inject dynamic model list into AI Gateway skill:",i.message),S.inc("context.degraded",1,{component:"model_list"})}return n.length>0&&(le.log(`Installed ${n.length} skills for ${e}: ${n.join(", ")}`,{runner:e,skills:n,targetDir:r}),La.getActiveSpan()?.setAttributes({"agent.skills_loaded":n,"agent.skills_loaded_count":n.length})),Hr=n,n},qa=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:ye.env.NETLIFY_TEAM_ID,userId:ye.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:ye.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Ha=10,Wa=async e=>{let{name:t,ext:r}=U.parse(e),n=e,s=U.join(ye.cwd(),re,n),i=0;for(;await Us(s);){if(i>=Ha)throw new Error("Failed to generate context file");n=`${t}-${$a.randomUUID().slice(0,5)}${r}`,s=U.join(ye.cwd(),re,n),i+=1}return n},Us=async e=>{try{return await Z.access(e),!0}catch{return!1}},js=async({cliPath:e,netlify:t,config:r,buildErrorContext:n,additionalContext:s,resumePrompt:i})=>{let o=qa(t),a=await Wa(cn),c=U.join(ye.cwd(),re);await Z.mkdir(c,{recursive:!0});let l=U.join(re,a),d=U.join(ye.cwd(),l),m=U.join(ye.cwd(),re,Me);try{await Z.unlink(m),le.log(`Deleted old results file: ${m}`)}catch{}let p=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
179
179
  Your task is to analyze and fix the build errors.
180
180
  Don't apply techniques of reverting changes. Apply fixes related to errors.
181
181
  Don't try to run build by yourself. Just fix the errors.
@@ -221,7 +221,7 @@ ${M}`;return await Z.writeFile(G,B,"utf-8"),le.log(`Created history file: ${$}`)
221
221
  `)}
222
222
 
223
223
  </session_history_context>
224
- `}let x=r.skillsTargetDir||Ls[r.runner];r.runner&&await Ba(r.runner,{targetDir:r.skillsTargetDir});let _=Ua({userRequest:r.prompt,buildErrorContextText:p,projectContext:f,sessionHistoryContextText:h,additionalContext:s,netlifyInfo:o,cliPath:e,skillsDir:x,netlifyFolder:c,resultsFilename:Me,assetsFolder:Ce,sessionId:r.sessionId});return await Z.writeFile(d,_,"utf-8"),le.log(`Generated agent context document at: ${d}`),_.length>5e5&&(_=`
224
+ `}let x=r.skillsTargetDir||Ls[r.runner];r.runner&&await Ya(r.runner,{targetDir:r.skillsTargetDir});let _=ja({userRequest:r.prompt,buildErrorContextText:p,projectContext:f,sessionHistoryContextText:h,additionalContext:s,netlifyInfo:o,cliPath:e,skillsDir:x,netlifyFolder:c,resultsFilename:Me,assetsFolder:Ce,sessionId:r.sessionId});return await Z.writeFile(d,_,"utf-8"),le.log(`Generated agent context document at: ${d}`),_.length>5e5&&(_=`
225
225
  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.
226
226
 
227
227
  <request>
@@ -232,17 +232,17 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
232
232
  </request>
233
233
 
234
234
  Use the following file for the complete context of the ask, the environment, and what's available. ${d} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
235
- `),_};var Wa=E("prompt"),Gs=async({cliPath:e,config:t,netlify:r,buildErrorContext:n,additionalContext:s,resumePrompt:i})=>{let o=await js({cliPath:e,config:t,netlify:r,buildErrorContext:n,additionalContext:s,resumePrompt:i});return process.env.AGENT_RUNNER_DEBUG&&Wa.log("Contextful Prompt:",o),{prompt:o}};var Qt=E("inference_stage"),Bs=5,$e=async e=>{let{additionalContext:t,cliPath:r,config:n,context:s,buildErrors:i,runner:o,persistSteps:a,aiGateway:c,attempt:l,contextPrefix:d,priorAgentSessionId:m,cwd:p}=e;Qt.log(`Running inference stage, attempt ${l} of ${Bs}`);let f=!1,h=await L(Vr(),"inference-stage",async x=>{x?.setAttributes({"inference.attempt":l||1}),An();let _=!!(l&&l>1),g=await za(n,_);f=g.viable,g.outcome!=="not_requested"&&S.inc("inference.native_resume",1,{outcome:g.outcome});let{prompt:b}=await L(Vr(),"compose-prompt",async()=>await Gs({cliPath:r,config:n,buildErrorContext:Va(i),netlify:s,additionalContext:t,resumePrompt:g.viable})),A=`
235
+ `),_};var za=E("prompt"),Gs=async({cliPath:e,config:t,netlify:r,buildErrorContext:n,additionalContext:s,resumePrompt:i})=>{let o=await js({cliPath:e,config:t,netlify:r,buildErrorContext:n,additionalContext:s,resumePrompt:i});return process.env.AGENT_RUNNER_DEBUG&&za.log("Contextful Prompt:",o),{prompt:o}};var Qt=E("inference_stage"),Bs=5,$e=async e=>{let{additionalContext:t,cliPath:r,config:n,context:s,buildErrors:i,runner:o,persistSteps:a,aiGateway:c,attempt:l,contextPrefix:d,priorAgentSessionId:m,cwd:p}=e;Qt.log(`Running inference stage, attempt ${l} of ${Bs}`);let f=!1,h=await L(Vr(),"inference-stage",async x=>{x?.setAttributes({"inference.attempt":l||1}),An();let _=!!(l&&l>1),g=await Va(n,_);f=g.viable,g.outcome!=="not_requested"&&S.inc("inference.native_resume",1,{outcome:g.outcome});let{prompt:b}=await L(Vr(),"compose-prompt",async()=>await Gs({cliPath:r,config:n,buildErrorContext:Ka(i),netlify:s,additionalContext:t,resumePrompt:g.viable})),A=`
236
236
  ${d||""}
237
237
  ${b}
238
- `.trim(),F={...n,prompt:A},D=m??(g.viable?g.sessionId:void 0),P=await L(Vr(),`run-${n.runner}`,async G=>{let $=Ir();G?.setAttributes({"gen_ai.operation.name":"chat","gen_ai.capability.name":n.mode,"gen_ai.provider.name":Bn(n.runner),"gen_ai.system":n.runner,...$?{"gen_ai.input.messages":Lt("user",A)}:{}});let N=Date.now(),I=await o({aiGateway:c,config:F,netlify:s,persistSteps:a,continueSession:_||g.viable,priorAgentSessionId:D,cwd:p}),M=Date.now(),B=I.resolvedModel||n.model||"unknown",W=I.error?"error":"stop";return G?.setAttributes({...$?{"gen_ai.output.messages":Lt("assistant",I.result??I.error??"",W)}:{},"gen_ai.response.finish_reasons":[W],"gen_ai.request.model":B,"gen_ai.response.model":B,...I.effort?{"gen_ai.request.effort":I.effort}:{},...I.usage?.input_tokens!=null?{"gen_ai.usage.input_tokens":I.usage.input_tokens}:{},...I.usage?.output_tokens!=null?{"gen_ai.usage.output_tokens":I.usage.output_tokens}:{},...I.usage?.cache_creation_input_tokens!=null?{"gen_ai.usage.cache_creation.input_tokens":I.usage.cache_creation_input_tokens}:{},...I.usage?.cache_read_input_tokens!=null?{"gen_ai.usage.cache_read.input_tokens":I.usage.cache_read_input_tokens}:{}}),Yn(I.steps??[],n.mode,N,M),I});return P.result&&(P.result=de(P.result)),P.error&&(P.error=de(P.error)),await a.flush(),P});if(h.error){if(Qt.error("Runner failed",{stepsCount:h.steps.length,duration:h.duration,error:h.error,isRetryableError:h.isRetryableError,attempt:l||1,agentSessionId:h.agentSessionId}),S.inc("inference.failed",1,{attempt:l||1,is_retryable:!!h.isRetryableError,is_provider_unavailable:!!h.isProviderUnavailableError}),h.isRetryableError&&(!l||l<Bs))return Qt.log("Retrying inference stage"),await new Promise(_=>setTimeout(_,5e3)),{runnerResult:(await $e({...e,attempt:(l||1)+1,priorAgentSessionId:h.agentSessionId,contextPrefix:h.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,nativeResume:f};throw Qt.log("Do not retry inference stage"),h.error.toLowerCase().includes("usage exceeded")?new he(h.error,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):h.isRetryableError||h.isProviderUnavailableError?new Pe(h.error):new Error(h.error)}return{runnerResult:h,nativeResume:f}},za=async(e,t)=>{let r=e.previousSession,n=!t&&r?.agent===e.runner&&!!r?.nativeSessionId;if(t||!Ys(e))return{viable:!1,outcome:n?"not_eligible":"not_requested"};let s=r?.nativeSessionId;return e.runner==="gemini"&&s&&!await qt(s)?{viable:!1,outcome:"sanitize_failed"}:{viable:!0,sessionId:s,outcome:"resumed"}},Va=e=>!e||e.length===0?"":`
238
+ `.trim(),F={...n,prompt:A},D=m??(g.viable?g.sessionId:void 0),P=await L(Vr(),`run-${n.runner}`,async G=>{let $=Ir();G?.setAttributes({"gen_ai.operation.name":"chat","gen_ai.capability.name":n.mode,"gen_ai.provider.name":Bn(n.runner),"gen_ai.system":n.runner,...$?{"gen_ai.input.messages":Lt("user",A)}:{}});let N=Date.now(),I=await o({aiGateway:c,config:F,netlify:s,persistSteps:a,continueSession:_||g.viable,priorAgentSessionId:D,cwd:p}),M=Date.now(),B=I.resolvedModel||n.model||"unknown",W=I.error?"error":"stop";return G?.setAttributes({...$?{"gen_ai.output.messages":Lt("assistant",I.result??I.error??"",W)}:{},"gen_ai.response.finish_reasons":[W],"gen_ai.request.model":B,"gen_ai.response.model":B,...I.effort?{"gen_ai.request.effort":I.effort}:{},...I.usage?.input_tokens!=null?{"gen_ai.usage.input_tokens":I.usage.input_tokens}:{},...I.usage?.output_tokens!=null?{"gen_ai.usage.output_tokens":I.usage.output_tokens}:{},...I.usage?.cache_creation_input_tokens!=null?{"gen_ai.usage.cache_creation.input_tokens":I.usage.cache_creation_input_tokens}:{},...I.usage?.cache_read_input_tokens!=null?{"gen_ai.usage.cache_read.input_tokens":I.usage.cache_read_input_tokens}:{}}),Yn(I.steps??[],n.mode,N,M),I});return P.result&&(P.result=de(P.result)),P.error&&(P.error=de(P.error)),await a.flush(),P});if(h.error){if(Qt.error("Runner failed",{stepsCount:h.steps.length,duration:h.duration,error:h.error,isRetryableError:h.isRetryableError,attempt:l||1,agentSessionId:h.agentSessionId}),S.inc("inference.failed",1,{attempt:l||1,is_retryable:!!h.isRetryableError,is_provider_unavailable:!!h.isProviderUnavailableError}),h.isRetryableError&&(!l||l<Bs))return Qt.log("Retrying inference stage"),await new Promise(_=>setTimeout(_,5e3)),{runnerResult:(await $e({...e,attempt:(l||1)+1,priorAgentSessionId:h.agentSessionId,contextPrefix:h.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,nativeResume:f};throw Qt.log("Do not retry inference stage"),h.error.toLowerCase().includes("usage exceeded")?new he(h.error,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):h.isRetryableError||h.isProviderUnavailableError?new Pe(h.error):new Error(h.error)}return{runnerResult:h,nativeResume:f}},Va=async(e,t)=>{let r=e.previousSession,n=!t&&r?.agent===e.runner&&!!r?.nativeSessionId;if(t||!Ys(e))return{viable:!1,outcome:n?"not_eligible":"not_requested"};let s=r?.nativeSessionId;return e.runner==="gemini"&&s&&!await qt(s)?{viable:!1,outcome:"sanitize_failed"}:{viable:!0,sessionId:s,outcome:"resumed"}},Ka=e=>!e||e.length===0?"":`
239
239
  Deploy failed failed. Here are the errors to review on the latest build:
240
240
 
241
241
  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.
242
242
 
243
243
  ${e.pop()}
244
- `;import{getTracer as Jr}from"@netlify/otel";import{getTracer as Ka}from"@netlify/otel";var nt=E("deploy"),Ja=e=>e===""||/[\s"\\]/u.test(e)?JSON.stringify(e):e,qs=async e=>await L(Ka(),"create-preview-deploy",async t=>Xa(e,t)),Xa=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:s,cliPath:i,filter:o,prodDeploy:a},c)=>{try{let l=["deploy","--message",n,"--json","--verbose",a?"--prod":"--draft"];nt.log("Deploy: Uploading source zip"),l.push("--upload-source-zip"),s&&!a&&l.push("--alias",s),o&&l.push("--filter",o),r?(nt.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context",a?"production":"deploy-preview");let d=i||"netlify";nt.log(`Running: ${d} ${l.map(Ja).join(" ")}`),c?.setAttributes({cmd:d,args:l});let m=await e.utils.run(d,l,{stdio:["ignore","pipe","pipe"],env:{...process.env,NETLIFY_DEPLOY_SOURCE:"agent_runner"}});m.stderr&&nt.log(String(m.stderr));let p=JSON.parse(String(m.stdout??"").trim());c?.setAttributes({success:!0,deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id}),nt.log(`
245
- Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let f={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(f.sourceZipFilename=p.source_zip_filename),f}catch(l){throw nt.error("Failed to create preview deploy via CLI:",l),c?.setAttributes({success:!1,error:l.message}),l}};var er=e=>["dtn-prod-iteration","create"].includes(e);import Hs from"fs";import Kr from"path";var Ws=(e=process.cwd())=>{let t=Kr.join(e,re,un);return{hasNetlifyForm:Hs.existsSync(Kr.join(t,"netlify-forms")),hasNetlifyIdentity:Hs.existsSync(Kr.join(t,"netlify-identity"))}};var Re=E("deploy_stage"),tr=async e=>await L(Jr(),"run-deploy-stage",async()=>Za(e)),Za=async({cliPath:e,config:t,context:r,result:n,filter:s,isRetry:i,deploySubdomain:o})=>{let a=await L(Jr(),"get-runner-diffs",async()=>await Ps({config:t,isRetry:i}));if(Re.info("Resolved git",{hasChanges:a.hasChanges,ignored:a.ignored??[]}),!a.hasChanges&&t.mode!=="redeploy")return{diff:"",hasChanges:!1,previewInfo:null,isProdDeploy:!1,hasNetlifyForm:!1,hasNetlifyIdentity:!1};let c=a.hasChanges?a.diff:"",l=a.hasChanges?a.resultDiff:void 0,d=a.hasChanges?a.diffBinary:void 0,m=a.hasChanges?a.resultDiffBinary:void 0,p=a.hasChanges||t.mode==="redeploy",{hasNetlifyForm:f,hasNetlifyIdentity:h}=Ws();if(f||h){let g={};f&&(Re.log("Detected Netlify Forms enablement \u2014 enabling early"),g.has_netlify_form=!0),h&&(Re.log("Detected Netlify Identity enablement \u2014 enabling early"),g.has_netlify_identity=!0);try{await pe(t.id,t.sessionId,g)}catch(b){Re.warn("Failed to send early feature enablement (continuing):",b)}}Re.log("Deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:p,isRedeploy:t.mode==="redeploy",wouldCreateDeploy:n!==void 0&&(p||t.mode==="redeploy")});let x=er(t.mode),_=null;if(n!==void 0&&(p||t.mode==="redeploy"))try{let g;try{let b=await L(Jr(),"get-runner-session",async()=>await fs(t.id,t.sessionId));b?.title&&(g=b.title)}catch(b){Re.warn("Failed to fetch session title, using fallback message:",b.message)}await pe(t.id,t.sessionId,{steps:[{title:x?"Deploying project":"Deploying preview",category:w.Deployment}]}),_=await qs({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:o,filter:s,prodDeploy:x})}catch(g){return Re.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:c,resultDiff:l,hasChanges:p,previewInfo:null,diffBinary:d,resultDiffBinary:m,deployError:g instanceof Error?g.message:String(g),isProdDeploy:x,hasNetlifyForm:f,hasNetlifyIdentity:h}}return Re.log("Git status",{hasDiff:!!c,hasChanges:p}),{diff:c,resultDiff:l,hasChanges:p,previewInfo:_,diffBinary:d,resultDiffBinary:m,isProdDeploy:x,hasNetlifyForm:f,hasNetlifyIdentity:h}};import{getTracer as xt}from"@netlify/otel";async function zs(e,t){let{maxRetries:r,baseDelay:n,onRetry:s}=t,i;for(let o=1;o<=r;o++)try{return await e()}catch(a){if(i=a,o===r)throw i;s&&s(o,i),await new Promise(c=>setTimeout(c,n*o))}throw i}import rr from"fs/promises";import Qa from"os";import Vs from"path";var st=E("native_session"),el=async(e,t)=>(await Promise.all(t.map(async n=>{try{return await rr.stat(Vs.join(e,n)),n}catch{return null}}))).filter(n=>n!==null),Ks=async({runnerId:e,sessionId:t,archive:r})=>{if(!r)return st.log("No native session archive descriptor for this runner, skipping"),!1;let{baseDir:n,include:s}=r,i=!1;try{i=(await rr.stat(n)).isDirectory()}catch{}if(!i)return st.log(`Native session base dir ${n} not found, skipping`),!1;let o=await el(n,s);if(o.length===0)return st.log(`No native session history found under ${n}, skipping`),!1;let a=Vs.join(Qa.tmpdir(),`native-session-${t}.zip`);try{await j("zip",["-r","-q","-X",a,...o],{cwd:n});let c=await rr.readFile(a);st.log(`Zipped native session (${c.length} bytes) from ${o.join(", ")}`);let{upload_url:l}=await ws(e,t);return await St(l,c,{contentType:"application/zip"}),st.log("Successfully uploaded native session to S3"),!0}catch(c){return st.error("Failed to archive/upload native session, continuing without it:",c),!1}finally{await rr.rm(a,{force:!0}).catch(()=>{})}};var ce=E("cleanup_stage"),Zr=async e=>await L(xt(),"cleanup-stage",async()=>tl(e)),Xr=1024*1024*10,tl=async({config:e,diff:t,result:r,duration:n,resultDiff:s,diffBinary:i,resultDiffBinary:o,previewInfo:a,isProdDeploy:c,hasNetlifyForm:l,hasNetlifyIdentity:d,nativeSessionArchive:m,nativeSessionId:p})=>{let f={result:r||"Done",duration:n};a&&a.deployId&&(f.deploy_id=a.deployId),a&&a.sourceZipFilename&&(f.result_zip_file_name=a.sourceZipFilename),c&&(f.is_published=!0),p&&(f.native_session_id=p);let h=t||i||s||o;if(h&&(f.diff_produced=!0),l&&(f.has_netlify_form=!0),d&&(f.has_netlify_identity=!0),h)try{ce.log("Getting pre-signed URLs for diff upload");let x=await _s(e.id,e.sessionId),_=[];(t||i)&&_.push(St(x.result.upload_url,i||t).then(()=>{f.result_diff_s3_key=x.result.s3_key,ce.log("Successfully uploaded result_diff to S3")})),(s||o)&&_.push(St(x.cumulative.upload_url,o||s).then(()=>{f.cumulative_diff_s3_key=x.cumulative.s3_key,ce.log("Successfully uploaded cumulative_diff to S3")})),ce.log(`Uploading ${_.length} diff(s) to S3 in parallel`),await Promise.all(_),(s||o)&&(ce.log("Updating agent runner with cumulative diff S3 key"),await L(xt(),"update-runner",async()=>{await bt(e.id,{result_diff_s3_key:x.cumulative.s3_key})}))}catch(x){ce.error("S3 upload failed, falling back to inline diffs:",x);let _=Buffer.byteLength(t||i||""),g=Buffer.byteLength(o||s||"");if(_>Xr||g>Xr){let b=`Diffs exceed maximum inline size of ${Xr} bytes.`;throw ce.error(b),new Error(b)}f.result_diff=t,f.result_diff_binary=i,(s||o)&&(f.cumulative_diff=s,f.cumulative_diff_binary=o,ce.log("Updating agent runner with inline diffs (fallback)"),await L(xt(),"update-runner",async()=>{await bt(e.id,{result_diff:s,result_diff_binary:o})}))}else ce.log("No diffs to upload");return await L(xt(),"upload-native-session",()=>Ks({runnerId:e.id,sessionId:e.sessionId,archive:m})),ce.log("Updated agent runner with result"),await zs(async()=>await L(xt(),"update-runner-session",()=>pe(e.id,e.sessionId,f)),{maxRetries:3,baseDelay:1e3,onRetry:(x,_)=>{ce.error(`Error updating agent runner session (attempt ${x}):`,_),ce.log("Retrying...")}}),ce.log("Finished updating agent runner with result"),{sessionUpdate:f}};import ve from"fs";import be from"path";import rl from"process";import{getTracer as nl}from"@netlify/otel";var oe=E("db_migrations"),sl=new Set(["drizzle.config.ts","drizzle.config.js","drizzle.config.mjs"]),il="netlify/database/migrations",Js=/^[a-z0-9_]{1,50}$/,it=50,Qs=(e,t)=>{if(!t)return be.join(e,il);let r=be.isAbsolute(t)?t:be.resolve(e,t),n=be.relative(e,r);if(n!==""&&(n.startsWith("..")||be.isAbsolute(n))){oe.warn(`Refusing to use migrations directory outside cwd: ${r} (cwd: ${e})`);return}return r},ol=e=>`Your task: return a short snake_case slug that summarises a SQL database migration.
244
+ `;import{getTracer as Jr}from"@netlify/otel";import{getTracer as Ja}from"@netlify/otel";var nt=E("deploy"),Xa=e=>e===""||/[\s"\\]/u.test(e)?JSON.stringify(e):e,qs=async e=>await L(Ja(),"create-preview-deploy",async t=>Za(e,t)),Za=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:s,cliPath:i,filter:o,prodDeploy:a},c)=>{try{let l=["deploy","--message",n,"--json","--verbose",a?"--prod":"--draft"];nt.log("Deploy: Uploading source zip"),l.push("--upload-source-zip"),s&&!a&&l.push("--alias",s),o&&l.push("--filter",o),r?(nt.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context",a?"production":"deploy-preview");let d=i||"netlify";nt.log(`Running: ${d} ${l.map(Xa).join(" ")}`),c?.setAttributes({cmd:d,args:l});let m=await e.utils.run(d,l,{stdio:["ignore","pipe","pipe"],env:{...process.env,NETLIFY_DEPLOY_SOURCE:"agent_runner"}});m.stderr&&nt.log(String(m.stderr));let p=JSON.parse(String(m.stdout??"").trim());c?.setAttributes({success:!0,deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id}),nt.log(`
245
+ Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let f={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(f.sourceZipFilename=p.source_zip_filename),f}catch(l){throw nt.error("Failed to create preview deploy via CLI:",l),c?.setAttributes({success:!1,error:l.message}),l}};var er=e=>["dtn-prod-iteration","create"].includes(e);import Hs from"fs";import Kr from"path";var Ws=(e=process.cwd())=>{let t=Kr.join(e,re,un);return{hasNetlifyForm:Hs.existsSync(Kr.join(t,"netlify-forms")),hasNetlifyIdentity:Hs.existsSync(Kr.join(t,"netlify-identity"))}};var Re=E("deploy_stage"),tr=async e=>await L(Jr(),"run-deploy-stage",async()=>Qa(e)),Qa=async({cliPath:e,config:t,context:r,result:n,filter:s,isRetry:i,deploySubdomain:o})=>{let a=await L(Jr(),"get-runner-diffs",async()=>await Ps({config:t,isRetry:i}));if(Re.info("Resolved git",{hasChanges:a.hasChanges,ignored:a.ignored??[]}),!a.hasChanges&&t.mode!=="redeploy")return{diff:"",hasChanges:!1,previewInfo:null,isProdDeploy:!1,hasNetlifyForm:!1,hasNetlifyIdentity:!1};let c=a.hasChanges?a.diff:"",l=a.hasChanges?a.resultDiff:void 0,d=a.hasChanges?a.diffBinary:void 0,m=a.hasChanges?a.resultDiffBinary:void 0,p=a.hasChanges||t.mode==="redeploy",{hasNetlifyForm:f,hasNetlifyIdentity:h}=Ws();if(f||h){let g={};f&&(Re.log("Detected Netlify Forms enablement \u2014 enabling early"),g.has_netlify_form=!0),h&&(Re.log("Detected Netlify Identity enablement \u2014 enabling early"),g.has_netlify_identity=!0);try{await pe(t.id,t.sessionId,g)}catch(b){Re.warn("Failed to send early feature enablement (continuing):",b)}}Re.log("Deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:p,isRedeploy:t.mode==="redeploy",wouldCreateDeploy:n!==void 0&&(p||t.mode==="redeploy")});let x=er(t.mode),_=null;if(n!==void 0&&(p||t.mode==="redeploy"))try{let g;try{let b=await L(Jr(),"get-runner-session",async()=>await fs(t.id,t.sessionId));b?.title&&(g=b.title)}catch(b){Re.warn("Failed to fetch session title, using fallback message:",b.message)}await pe(t.id,t.sessionId,{steps:[{title:x?"Deploying project":"Deploying preview",category:w.Deployment}]}),_=await qs({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:o,filter:s,prodDeploy:x})}catch(g){return Re.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:c,resultDiff:l,hasChanges:p,previewInfo:null,diffBinary:d,resultDiffBinary:m,deployError:g instanceof Error?g.message:String(g),isProdDeploy:x,hasNetlifyForm:f,hasNetlifyIdentity:h}}return Re.log("Git status",{hasDiff:!!c,hasChanges:p}),{diff:c,resultDiff:l,hasChanges:p,previewInfo:_,diffBinary:d,resultDiffBinary:m,isProdDeploy:x,hasNetlifyForm:f,hasNetlifyIdentity:h}};import{getTracer as xt}from"@netlify/otel";async function zs(e,t){let{maxRetries:r,baseDelay:n,onRetry:s}=t,i;for(let o=1;o<=r;o++)try{return await e()}catch(a){if(i=a,o===r)throw i;s&&s(o,i),await new Promise(c=>setTimeout(c,n*o))}throw i}import rr from"fs/promises";import el from"os";import Vs from"path";var st=E("native_session"),tl=async(e,t)=>(await Promise.all(t.map(async n=>{try{return await rr.stat(Vs.join(e,n)),n}catch{return null}}))).filter(n=>n!==null),Ks=async({runnerId:e,sessionId:t,archive:r})=>{if(!r)return st.log("No native session archive descriptor for this runner, skipping"),!1;let{baseDir:n,include:s}=r,i=!1;try{i=(await rr.stat(n)).isDirectory()}catch{}if(!i)return st.log(`Native session base dir ${n} not found, skipping`),!1;let o=await tl(n,s);if(o.length===0)return st.log(`No native session history found under ${n}, skipping`),!1;let a=Vs.join(el.tmpdir(),`native-session-${t}.zip`);try{await j("zip",["-r","-q","-X",a,...o],{cwd:n});let c=await rr.readFile(a);st.log(`Zipped native session (${c.length} bytes) from ${o.join(", ")}`);let{upload_url:l}=await ws(e,t);return await St(l,c,{contentType:"application/zip"}),st.log("Successfully uploaded native session to S3"),!0}catch(c){return st.error("Failed to archive/upload native session, continuing without it:",c),!1}finally{await rr.rm(a,{force:!0}).catch(()=>{})}};var ce=E("cleanup_stage"),Zr=async e=>await L(xt(),"cleanup-stage",async()=>rl(e)),Xr=1024*1024*10,rl=async({config:e,diff:t,result:r,duration:n,resultDiff:s,diffBinary:i,resultDiffBinary:o,previewInfo:a,isProdDeploy:c,hasNetlifyForm:l,hasNetlifyIdentity:d,nativeSessionArchive:m,nativeSessionId:p})=>{let f={result:r||"Done",duration:n};a&&a.deployId&&(f.deploy_id=a.deployId),a&&a.sourceZipFilename&&(f.result_zip_file_name=a.sourceZipFilename),c&&(f.is_published=!0),p&&(f.native_session_id=p);let h=t||i||s||o;if(h&&(f.diff_produced=!0),l&&(f.has_netlify_form=!0),d&&(f.has_netlify_identity=!0),h)try{ce.log("Getting pre-signed URLs for diff upload");let x=await _s(e.id,e.sessionId),_=[];(t||i)&&_.push(St(x.result.upload_url,i||t).then(()=>{f.result_diff_s3_key=x.result.s3_key,ce.log("Successfully uploaded result_diff to S3")})),(s||o)&&_.push(St(x.cumulative.upload_url,o||s).then(()=>{f.cumulative_diff_s3_key=x.cumulative.s3_key,ce.log("Successfully uploaded cumulative_diff to S3")})),ce.log(`Uploading ${_.length} diff(s) to S3 in parallel`),await Promise.all(_),(s||o)&&(ce.log("Updating agent runner with cumulative diff S3 key"),await L(xt(),"update-runner",async()=>{await bt(e.id,{result_diff_s3_key:x.cumulative.s3_key})}))}catch(x){ce.error("S3 upload failed, falling back to inline diffs:",x);let _=Buffer.byteLength(t||i||""),g=Buffer.byteLength(o||s||"");if(_>Xr||g>Xr){let b=`Diffs exceed maximum inline size of ${Xr} bytes.`;throw ce.error(b),new Error(b)}f.result_diff=t,f.result_diff_binary=i,(s||o)&&(f.cumulative_diff=s,f.cumulative_diff_binary=o,ce.log("Updating agent runner with inline diffs (fallback)"),await L(xt(),"update-runner",async()=>{await bt(e.id,{result_diff:s,result_diff_binary:o})}))}else ce.log("No diffs to upload");return await L(xt(),"upload-native-session",()=>Ks({runnerId:e.id,sessionId:e.sessionId,archive:m})),ce.log("Updated agent runner with result"),await zs(async()=>await L(xt(),"update-runner-session",()=>pe(e.id,e.sessionId,f)),{maxRetries:3,baseDelay:1e3,onRetry:(x,_)=>{ce.error(`Error updating agent runner session (attempt ${x}):`,_),ce.log("Retrying...")}}),ce.log("Finished updating agent runner with result"),{sessionUpdate:f}};import ve from"fs";import be from"path";import nl from"process";import{getTracer as sl}from"@netlify/otel";var oe=E("db_migrations"),il=new Set(["drizzle.config.ts","drizzle.config.js","drizzle.config.mjs"]),ol="netlify/database/migrations",Js=/^[a-z0-9_]{1,50}$/,it=50,Qs=(e,t)=>{if(!t)return be.join(e,ol);let r=be.isAbsolute(t)?t:be.resolve(e,t),n=be.relative(e,r);if(n!==""&&(n.startsWith("..")||be.isAbsolute(n))){oe.warn(`Refusing to use migrations directory outside cwd: ${r} (cwd: ${e})`);return}return r},al=e=>`Your task: return a short snake_case slug that summarises a SQL database migration.
246
246
 
247
247
  Rules:
248
248
  - Lowercase letters, digits, and underscores only. Match the regex ^[a-z0-9_]{1,${it}}$.
@@ -265,17 +265,17 @@ SQL:
265
265
  ${e}
266
266
  \`\`\`
267
267
 
268
- Output a single slug. No sentences, no markdown, no quotes, no newlines. Your entire response must match ^[a-z0-9_]{1,${it}}$.`,al=e=>{let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");if(!t)return;if(t.length<=it)return t;let r=t.slice(0,it),n=r.lastIndexOf("_");return n>=Math.floor(it*2/3)?r.slice(0,n):r},ei=async(e,t)=>{let r=Qs(e,t);if(r)try{let n=await ve.promises.readdir(r);return new Set(n)}catch(n){if(n.code==="ENOENT")return new Set;oe.warn(`Failed to snapshot migrations directory ${r} \u2014 rename disabled for this run`,{code:n.code,error:n.message});return}},ll="claude-haiku-4-5",cl="gpt-5.4-nano",Xs=async(e,t)=>{let r={...t,maxTokens:80},{response:n,text:s}=e==="claude"?await es({...r,model:ll}):await os({...r,model:cl});return n?.usage&&Be(n.usage,{agent:e}),s},ul=async({sql:e,aiGateway:t,config:r})=>{let n=r.runner==="codex"?"codex":"claude",s=n==="claude"?"codex":"claude",i={aiGateway:t,config:r,prompt:ol(e)},o;try{o=await Xs(n,i)}catch(l){oe.warn(`${n} request failed for migration slug; trying ${s}`,{error:l.message});try{o=await Xs(s,i)}catch(d){oe.warn(`${s} request also failed for migration slug`,{error:d.message});return}}let a=o.trim();if(Js.test(a))return a;let c=al(a);if(c&&Js.test(c))return oe.warn(`Provider returned a non-conforming migration slug "${a}" \u2014 using normalized fallback "${c}"`),c;oe.warn(`Provider returned invalid migration slug: ${a}`)},dl=async({cwd:e,migrationsPath:t,snapshot:r,applied:n,config:s,aiGateway:i})=>{let o=Qs(e,t);if(!o)return;let a;try{a=await ve.promises.readdir(o)}catch{return}let c=a.filter(m=>!r.has(m)),l=[];for(let m of c){if(n?.has(m))continue;let p=be.join(o,m),f;try{f=await ve.promises.stat(p)}catch{continue}if(!f.isDirectory())continue;let h=be.join(p,"migration.sql");if(!ve.existsSync(h))continue;let x=m.match(/^(\d{14})_(.+)$/);if(!x)continue;let[,_,g]=x;l.push({name:m,prefix:_,currentSuffix:g,entryPath:p,sqlPath:h})}l.length>0&&oe.log(`Considering ${l.length} migration(s) for rename`,{migrations:l.map(m=>m.name)});for(let{name:m,prefix:p,currentSuffix:f,entryPath:h,sqlPath:x}of l){let _;try{_=await ve.promises.readFile(x,"utf8")}catch(F){oe.warn(`Failed to read ${x} \u2014 skipping rename for ${m}`,{code:F.code,error:F.message}),S.inc("db_migrations.rename",1,{outcome:"sql_read_failed"});continue}let g=await ul({sql:_,config:s,aiGateway:i});if(!g){S.inc("db_migrations.rename",1,{outcome:"no_slug"});continue}if(g===f){S.inc("db_migrations.rename",1,{outcome:"slug_unchanged"});continue}let b=`${p}_${g}`,A=be.join(o,b);if(ve.existsSync(A)){oe.warn(`Cannot rename migration ${m} \u2192 ${b}: target already exists`),S.inc("db_migrations.rename",1,{outcome:"target_exists"});continue}try{await ve.promises.rename(h,A),oe.log(`Renamed migration ${m} \u2192 ${b}`),S.inc("db_migrations.rename",1,{outcome:"renamed"})}catch(F){oe.warn(`Failed to rename migration ${m} \u2192 ${b}`,{error:F.message}),S.inc("db_migrations.rename",1,{outcome:"rename_failed"})}}let d=await ve.promises.readdir(o).catch(()=>[]);r.clear();for(let m of d)r.add(m)},nr=async e=>await Ot({stage:"db-migrations"},()=>L(nl(),"db-migrations",async t=>{let r=e.cwd||rl.cwd();if(!(await Zs("@netlify/database",r)||await Zs("@netlify/db",r)))return t?.setAttributes({skipped:!0,reason:"@netlify/database is not installed"}),S.inc("db_migrations.run",1,{outcome:"skipped",reason:"no_module"}),{skipped:!0};let s=[...sl].find(i=>ve.existsSync(be.join(r,i)));if(!s)return t?.setAttributes({skipped:!0,reason:"no drizzle config found"}),S.inc("db_migrations.run",1,{outcome:"skipped",reason:"no_config"}),{skipped:!0};t?.setAttributes({configFile:s}),oe.log(`Found ${s}, running drizzle-kit generate to ensure migrations are up to date`);try{let i=await j("npx",["drizzle-kit","generate"],{cwd:r,stdio:["ignore","pipe","pipe"]});return i.stdout&&oe.log(String(i.stdout)),t?.setAttributes({success:!0}),S.inc("db_migrations.run",1,{outcome:"success"}),e.snapshot&&await dl({cwd:r,migrationsPath:e.migrationsPath,snapshot:e.snapshot,applied:e.applied,config:e.config,aiGateway:e.aiGateway}),{skipped:!1}}catch(i){let o=pl(i);return oe.warn("drizzle-kit generate failed:",o),t?.setAttributes({success:!1,error:o}),S.inc("db_migrations.run",1,{outcome:"failure"}),{skipped:!1,error:o}}})),Zs=async(e,t)=>{try{return await Pn(`node -e "require.resolve('${e}')"`,{cwd:t,stdio:"ignore"}),!0}catch{return!1}},pl=e=>{if(e&&typeof e=="object"){let t=[];if("stderr"in e&&e.stderr&&t.push(String(e.stderr)),"stdout"in e&&e.stdout&&t.push(String(e.stdout)),t.length>0)return t.join(`
269
- `)}return e instanceof Error?e.message:String(e)};import{getTracer as ml}from"@netlify/otel";var Qr=E("migration_state"),sr=async({cliPath:e,cwd:t})=>{let r="";try{let n=await j(e,["db","status","--json"],{cwd:t,stdio:["ignore","pipe","pipe"]});r=n.stdout?String(n.stdout):""}catch(n){let s=n;throw Qr.warn("`netlify db status --json` failed",{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr}),n}Qr.log("`netlify db status --json` output",{stdout:r});try{return JSON.parse(r)}catch(n){throw Qr.warn("Failed to parse `netlify db status --json` output",{stdout:r,error:String(n)}),n}},ti=()=>["## Netlify Database","","A Netlify Database (managed Postgres) is available for this site.","It will be provisioned automatically on first connection.","No migrations have been applied yet \u2014 this is a fresh database.","","Use `@netlify/database` with Drizzle ORM for persistent data storage.","Define your schema in `db/schema.ts` and migrations will be generated automatically at deploy time.","Read the `netlify-database` skill for setup instructions."].join(`
268
+ Output a single slug. No sentences, no markdown, no quotes, no newlines. Your entire response must match ^[a-z0-9_]{1,${it}}$.`,ll=e=>{let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");if(!t)return;if(t.length<=it)return t;let r=t.slice(0,it),n=r.lastIndexOf("_");return n>=Math.floor(it*2/3)?r.slice(0,n):r},ei=async(e,t)=>{let r=Qs(e,t);if(r)try{let n=await ve.promises.readdir(r);return new Set(n)}catch(n){if(n.code==="ENOENT")return new Set;oe.warn(`Failed to snapshot migrations directory ${r} \u2014 rename disabled for this run`,{code:n.code,error:n.message});return}},cl="claude-haiku-4-5",ul="gpt-5.4-nano",Xs=async(e,t)=>{let r={...t,maxTokens:80},{response:n,text:s}=e==="claude"?await es({...r,model:cl}):await os({...r,model:ul});return n?.usage&&Be(n.usage,{agent:e}),s},dl=async({sql:e,aiGateway:t,config:r})=>{let n=r.runner==="codex"?"codex":"claude",s=n==="claude"?"codex":"claude",i={aiGateway:t,config:r,prompt:al(e)},o;try{o=await Xs(n,i)}catch(l){oe.warn(`${n} request failed for migration slug; trying ${s}`,{error:l.message});try{o=await Xs(s,i)}catch(d){oe.warn(`${s} request also failed for migration slug`,{error:d.message});return}}let a=o.trim();if(Js.test(a))return a;let c=ll(a);if(c&&Js.test(c))return oe.warn(`Provider returned a non-conforming migration slug "${a}" \u2014 using normalized fallback "${c}"`),c;oe.warn(`Provider returned invalid migration slug: ${a}`)},pl=async({cwd:e,migrationsPath:t,snapshot:r,applied:n,config:s,aiGateway:i})=>{let o=Qs(e,t);if(!o)return;let a;try{a=await ve.promises.readdir(o)}catch{return}let c=a.filter(m=>!r.has(m)),l=[];for(let m of c){if(n?.has(m))continue;let p=be.join(o,m),f;try{f=await ve.promises.stat(p)}catch{continue}if(!f.isDirectory())continue;let h=be.join(p,"migration.sql");if(!ve.existsSync(h))continue;let x=m.match(/^(\d{14})_(.+)$/);if(!x)continue;let[,_,g]=x;l.push({name:m,prefix:_,currentSuffix:g,entryPath:p,sqlPath:h})}l.length>0&&oe.log(`Considering ${l.length} migration(s) for rename`,{migrations:l.map(m=>m.name)});for(let{name:m,prefix:p,currentSuffix:f,entryPath:h,sqlPath:x}of l){let _;try{_=await ve.promises.readFile(x,"utf8")}catch(F){oe.warn(`Failed to read ${x} \u2014 skipping rename for ${m}`,{code:F.code,error:F.message}),S.inc("db_migrations.rename",1,{outcome:"sql_read_failed"});continue}let g=await dl({sql:_,config:s,aiGateway:i});if(!g){S.inc("db_migrations.rename",1,{outcome:"no_slug"});continue}if(g===f){S.inc("db_migrations.rename",1,{outcome:"slug_unchanged"});continue}let b=`${p}_${g}`,A=be.join(o,b);if(ve.existsSync(A)){oe.warn(`Cannot rename migration ${m} \u2192 ${b}: target already exists`),S.inc("db_migrations.rename",1,{outcome:"target_exists"});continue}try{await ve.promises.rename(h,A),oe.log(`Renamed migration ${m} \u2192 ${b}`),S.inc("db_migrations.rename",1,{outcome:"renamed"})}catch(F){oe.warn(`Failed to rename migration ${m} \u2192 ${b}`,{error:F.message}),S.inc("db_migrations.rename",1,{outcome:"rename_failed"})}}let d=await ve.promises.readdir(o).catch(()=>[]);r.clear();for(let m of d)r.add(m)},nr=async e=>await Ot({stage:"db-migrations"},()=>L(sl(),"db-migrations",async t=>{let r=e.cwd||nl.cwd();if(!(await Zs("@netlify/database",r)||await Zs("@netlify/db",r)))return t?.setAttributes({skipped:!0,reason:"@netlify/database is not installed"}),S.inc("db_migrations.run",1,{outcome:"skipped",reason:"no_module"}),{skipped:!0};let s=[...il].find(i=>ve.existsSync(be.join(r,i)));if(!s)return t?.setAttributes({skipped:!0,reason:"no drizzle config found"}),S.inc("db_migrations.run",1,{outcome:"skipped",reason:"no_config"}),{skipped:!0};t?.setAttributes({configFile:s}),oe.log(`Found ${s}, running drizzle-kit generate to ensure migrations are up to date`);try{let i=await j("npx",["drizzle-kit","generate"],{cwd:r,stdio:["ignore","pipe","pipe"]});return i.stdout&&oe.log(String(i.stdout)),t?.setAttributes({success:!0}),S.inc("db_migrations.run",1,{outcome:"success"}),e.snapshot&&await pl({cwd:r,migrationsPath:e.migrationsPath,snapshot:e.snapshot,applied:e.applied,config:e.config,aiGateway:e.aiGateway}),{skipped:!1}}catch(i){let o=ml(i);return oe.warn("drizzle-kit generate failed:",o),t?.setAttributes({success:!1,error:o}),S.inc("db_migrations.run",1,{outcome:"failure"}),{skipped:!1,error:o}}})),Zs=async(e,t)=>{try{return await Pn(`node -e "require.resolve('${e}')"`,{cwd:t,stdio:"ignore"}),!0}catch{return!1}},ml=e=>{if(e&&typeof e=="object"){let t=[];if("stderr"in e&&e.stderr&&t.push(String(e.stderr)),"stdout"in e&&e.stdout&&t.push(String(e.stdout)),t.length>0)return t.join(`
269
+ `)}return e instanceof Error?e.message:String(e)};import{getTracer as gl}from"@netlify/otel";var Qr=E("migration_state"),sr=async({cliPath:e,cwd:t})=>{let r="";try{let n=await j(e,["db","status","--json"],{cwd:t,stdio:["ignore","pipe","pipe"]});r=n.stdout?String(n.stdout):""}catch(n){let s=n;throw Qr.warn("`netlify db status --json` failed",{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr}),n}Qr.log("`netlify db status --json` output",{stdout:r});try{return JSON.parse(r)}catch(n){throw Qr.warn("Failed to parse `netlify db status --json` output",{stdout:r,error:String(n)}),n}},ti=()=>["## Netlify Database","","A Netlify Database (managed Postgres) is available for this site.","It will be provisioned automatically on first connection.","No migrations have been applied yet \u2014 this is a fresh database.","","Use `@netlify/database` with Drizzle ORM for persistent data storage.","Define your schema in `db/schema.ts` and migrations will be generated automatically at deploy time.","Read the `netlify-database` skill for setup instructions."].join(`
270
270
  `),ri=e=>{if(e.applied.length===0&&e.pending.length===0)return null;let t=["## CRITICAL: Current Netlify Database state",""];if(e.applied.length>0){t.push("The following migrations are **already applied** to your preview database branch. They are immutable:","");for(let r of e.applied)t.push(`- ${r.name}`);t.push("","**Never delete, rename, or edit an applied migration file.** Doing so will break the deploy \u2014 the","platform requires every migration applied to the branch to exist on disk with its original content. If","you think an applied migration is wrong, roll forward with a NEW migration that corrects whatever it","did. That's always safe; deletion isn't.")}else t.push("No migrations are applied to your preview database branch yet.");if(e.pending.length>0){t.push(""),t.push("The following migration files exist on disk but have NOT yet been applied:","");for(let r of e.pending)t.push(`- ${r.name}`);t.push("","Pending files can be modified or deleted freely \u2014 use `netlify db migrations reset` to remove them","cleanly, then regenerate via `npx drizzle-kit generate` if you want a replacement.")}return t.join(`
271
271
  `)},ni=e=>{let t=[];return e.missingOnDisk.length>0&&t.push("You deleted the following migration file(s) that are already applied to the preview database branch:",...e.missingOnDisk.map(r=>`- ${r.name}`),"","Applied migrations cannot be removed \u2014 the deploy will fail because the platform requires every applied","migration to exist on disk with its original content. Please revise your work:","","1. Restore the deleted file(s) by running `netlify db migrations pull --force`, which overwrites the"," local migrations directory with the authoritative state of the branch. Note this also wipes any"," unapplied migration files you generated this session \u2014 regenerate them via `npx drizzle-kit generate`"," afterwards if you still need them (your `db/schema.ts` edits aren't affected by the pull).","2. If the underlying problem is that an applied migration is wrong, add a NEW migration on top that"," corrects whatever it did (drop a column, rename a table, etc.). Do not touch the original."),e.outOfOrder.length>0&&(t.length>0&&t.push(""),t.push("The following pending migration file(s) have a version prefix that sorts BEFORE migrations already","applied to the branch, so the platform will reject them on deploy:",...e.outOfOrder.map(r=>`- ${r.name} (version ${r.version} \u2264 applied max ${r.maxApplied})`),"","Delete these out-of-order files (use `netlify db migrations reset` \u2014 it only removes unapplied files),","then run `npx drizzle-kit generate` to produce a replacement whose version sorts after the applied","migrations.")),t.length===0?null:t.join(`
272
- `)},si=e=>e.missingOnDisk.length>0||e.outOfOrder.length>0;var ii=E("db_migrations_verify"),oi=async e=>await L(ml(),"db-migrations-verify-stage",async t=>{let r;try{r=await sr({cliPath:e.cliPath,cwd:e.cwd})}catch(s){return ii.warn("Skipping migration verification \u2014 failed to read status",{error:s}),t?.setAttributes({"verify.skipped":!0,"verify.skip_reason":"status_error"}),{}}if(!si(r))return t?.setAttributes({"verify.drift":!1}),{};let n=ni(r);return t?.setAttributes({"verify.drift":!0,"verify.missing_on_disk_count":r.missingOnDisk.length,"verify.out_of_order_count":r.outOfOrder.length}),ii.log("Detected post-inference migration drift",{missingOnDisk:r.missingOnDisk.map(s=>s.name),outOfOrder:r.outOfOrder.map(s=>s.name)}),{error:n??void 0}});import en from"process";import{getTracer as gl}from"@netlify/otel";import{NetlifyDBProxy as fl}from"@netlify/database-proxy";var ir=E("db_setup"),ai=async({siteId:e,isProd:t,alias:r,connectionString:n})=>await L(gl(),"db-setup-stage",async s=>{s?.setAttributes({"db_setup.site_id":e,"db_setup.is_prod":t,...r&&{"db_setup.alias":r}});let i;if(t?i="production":r&&(i=r),en.env.NETLIFY_DB_BRANCH=i,n)return s?.setAttributes({"db_setup.source":"config","db_setup.has_proxy":!1}),ir.log("Using database connection string provided by the API"),en.env.NETLIFY_DB_URL=n,{connectionString:n,wasProvisioned:()=>!1};let o=!1,a=new fl({logger:(...l)=>ir.log("db-proxy:",...l),provision:async()=>(o=!0,ir.log("Provisioning database for site via API"),await Ts(e),await hl(e,t,r))}),c=await a.start();return s?.setAttributes({"db_setup.source":"proxy","db_setup.has_proxy":!0}),ir.log("Local DB proxy started",{connectionString:c}),en.env.NETLIFY_DB_URL=c,{connectionString:c,proxy:a,wasProvisioned:()=>o}}),hl=async(e,t,r)=>t||!r?(await vs(e)).connection_string:(await xs(e,r),(await Ss(e,r)).connection_string);import{getTracer as or,shutdownTracers as bl,withActiveSpan as ar}from"@netlify/otel";var yl=({isHotFollowUp:e,enqueuedAt:t})=>e?t===void 0?[]:[["request",t]]:[["spawn",Number(process.env.NETLIFY_AGENT_RUNNER_SPAWN_AT_MS)],["enqueue",Number(process.env.NETLIFY_AGENT_RUNNER_ENQUEUED_AT_MS)]],li=(e,t,r,n)=>{for(let[s,i]of yl(r))Number.isFinite(i)&&i>0&&i<=n&&e.timing(t,n-i,{from:s})},ci=(e,t=Date.now(),r=S)=>li(r,"startup.duration",e,t),ui=(e,t=Date.now(),r=S)=>li(r,"startup.time_to_first_output",e,t);var It=E("usage_tracker"),_l=4e3,di=(e,t,r)=>{let n=!1,s=!1,i=!1,o,c=Pt(async()=>{try{let p=await Es(e,t);It.log("Usage update response",{usage:p?.usage});let f=p?.usage?.total_credits_cost;f!=null&&(o=f,r!=null&&f>=r&&(It.log("Credit limit exceeded",{totalCreditsCost:f,enforcedCreditsRemaining:r}),i=!0)),p?.credit_limit_exceeded&&(It.log("Credit limit exceeded (flagged by API)"),i=!0)}catch(p){It.warn("Failed to update usage",{error:p?.message||p})}},_l);return{onAgentOutput:()=>{if(i)throw new he("AI credit usage exceeded enforced limit.",503,"Credit limit reached. Check credit limits to continue using Agent Runners.",!0);s||(n=!0,c())},stop:async()=>{s||(s=!0,n&&(It.log("Sending final usage update"),c(),await c.flush()))},getCreditsCost:()=>o}};var Sl=vl(import.meta.url),At=Sl("../package.json"),Q=E("pipeline_index"),ot=3,Tl=["codex","gemini"],pi=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,filter:s,isHotFollowUp:i=!1,enqueuedAt:o,tracing:a={}})=>{let c,l,d,m=Date.now(),p="success",f=!1,{withStageTimer:h}=Rn(_e.timeUnits.hours(4)),x=await Gn(At.version,e.id,a);Q.log(`Agent runner orchestrator v${At.version}`,{featureFlags:V().raw,metrics:bn()}),wr({agent:e.runner,mode:e.mode,is_follow_up:e.sessionHistoryContext.length>0,version:At.version,fast_init:e.fastInit}),ci({isHotFollowUp:i,enqueuedAt:o});try{await ar(or(),"run-pipeline",{},x,async _=>{await rn(tn(),e.runner),_?.setAttributes({"gen_ai.capability.name":e.mode,"session.id":e.sessionId});let{aiGateway:g,context:b,persistSteps:A,runner:F,sha:D}=await h("init",()=>$s({config:e,apiToken:t,cliPath:r,cwd:n,filter:s,runnerVersion:At.version}),_e.timeUnits.minutes(10)),P=F.runner;V().idleTimeoutEnabled||(c=F.clean),l=di(e.id,e.sessionId,e.enforcedAICreditsRemaining);let G=er(e.mode),$;e.deployAlias&&e.deployAlias.length>0?$=e.deployAlias:(e.deployAlias!==void 0&&!G&&Q.warn("Received empty deploy alias for a non-prod deploy, falling back to local computation"),$=_n(e.id,process.env.SITE_NAME,G));let N,I=!1,M=Object.assign(async C=>{try{l?.onAgentOutput()}catch(k){qe(k)?N??=k:Q.warn("Unexpected error in onAgentOutput",{error:k?.message||k});return}return!I&&C.steps?.some(k=>k.category!==w.Environment&&k.category!==w.UserMessage)&&(I=!0,ui({isHotFollowUp:i,enqueuedAt:o})),A(C)},{flush:A.flush.bind(A)});if(e.sha=D,e.mode==="redeploy"){let C=await h("deploy",()=>tr({cliPath:r,config:e,context:b,result:"Redeploy completed",filter:s,isRetry:!1,deploySubdomain:$}));C.deployError&&(Q.warn(`Redeploy deploy failed: ${C.deployError}`),S.inc("deploy.failed",1,{attempt:1}));let{diff:k,resultDiff:fe,previewInfo:te,diffBinary:Le,resultDiffBinary:Ai,hasNetlifyForm:Ri,hasNetlifyIdentity:Ci}=C;await l?.stop(),await h("cleanup",()=>Zr({config:e,diff:k,result:"Redeploy completed",duration:0,resultDiff:fe,diffBinary:Le,resultDiffBinary:Ai,previewInfo:te,isProdDeploy:G,hasNetlifyForm:Ri,hasNetlifyIdentity:Ci,nativeSessionArchive:$r(e.runner)}),_e.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await c?.(),await d?.stop(),await Yr());return}let B;e.mode==="create"&&(B=(await h("create",()=>Wn({config:e,cwd:n}))).additionalContext),process.env.EXPERIMENTAL_NETLIFY_DB_ENABLED="1";let W,O;if(!process.env.NETLIFY_LOCAL_MODE&&e.siteId){let C=await h("db-setup",()=>ai({siteId:e.siteId,isProd:G,alias:$,connectionString:e.dbConnectionString}),_e.timeUnits.minutes(10));if(d=C.proxy,n)if(C.proxy)B=[ti(),B].filter(Boolean).join(`
272
+ `)},si=e=>e.missingOnDisk.length>0||e.outOfOrder.length>0;var ii=E("db_migrations_verify"),oi=async e=>await L(gl(),"db-migrations-verify-stage",async t=>{let r;try{r=await sr({cliPath:e.cliPath,cwd:e.cwd})}catch(s){return ii.warn("Skipping migration verification \u2014 failed to read status",{error:s}),t?.setAttributes({"verify.skipped":!0,"verify.skip_reason":"status_error"}),{}}if(!si(r))return t?.setAttributes({"verify.drift":!1}),{};let n=ni(r);return t?.setAttributes({"verify.drift":!0,"verify.missing_on_disk_count":r.missingOnDisk.length,"verify.out_of_order_count":r.outOfOrder.length}),ii.log("Detected post-inference migration drift",{missingOnDisk:r.missingOnDisk.map(s=>s.name),outOfOrder:r.outOfOrder.map(s=>s.name)}),{error:n??void 0}});import en from"process";import{getTracer as fl}from"@netlify/otel";import{NetlifyDBProxy as hl}from"@netlify/database-proxy";var ir=E("db_setup"),ai=async({siteId:e,isProd:t,alias:r,connectionString:n})=>await L(fl(),"db-setup-stage",async s=>{s?.setAttributes({"db_setup.site_id":e,"db_setup.is_prod":t,...r&&{"db_setup.alias":r}});let i;if(t?i="production":r&&(i=r),en.env.NETLIFY_DB_BRANCH=i,n)return s?.setAttributes({"db_setup.source":"config","db_setup.has_proxy":!1}),ir.log("Using database connection string provided by the API"),en.env.NETLIFY_DB_URL=n,{connectionString:n,wasProvisioned:()=>!1};let o=!1,a=new hl({logger:(...l)=>ir.log("db-proxy:",...l),provision:async()=>(o=!0,ir.log("Provisioning database for site via API"),await Ts(e),await yl(e,t,r))}),c=await a.start();return s?.setAttributes({"db_setup.source":"proxy","db_setup.has_proxy":!0}),ir.log("Local DB proxy started",{connectionString:c}),en.env.NETLIFY_DB_URL=c,{connectionString:c,proxy:a,wasProvisioned:()=>o}}),yl=async(e,t,r)=>t||!r?(await vs(e)).connection_string:(await xs(e,r),(await Ss(e,r)).connection_string);import{getTracer as or,shutdownTracers as Sl,withActiveSpan as ar}from"@netlify/otel";var _l=({isHotFollowUp:e,enqueuedAt:t})=>e?t===void 0?[]:[["request",t]]:[["spawn",Number(process.env.NETLIFY_AGENT_RUNNER_SPAWN_AT_MS)],["enqueue",Number(process.env.NETLIFY_AGENT_RUNNER_ENQUEUED_AT_MS)]],li=(e,t,r,n)=>{for(let[s,i]of _l(r))Number.isFinite(i)&&i>0&&i<=n&&e.timing(t,n-i,{from:s})},ci=(e,t=Date.now(),r=S)=>li(r,"startup.duration",e,t),ui=(e,t=Date.now(),r=S)=>li(r,"startup.time_to_first_output",e,t);var It=E("usage_tracker"),wl=4e3,di=(e,t,r)=>{let n=!1,s=!1,i=!1,o,c=Pt(async()=>{try{let p=await Es(e,t);It.log("Usage update response",{usage:p?.usage});let f=p?.usage?.total_credits_cost;f!=null&&(o=f,r!=null&&f>=r&&(It.log("Credit limit exceeded",{totalCreditsCost:f,enforcedCreditsRemaining:r}),i=!0)),p?.credit_limit_exceeded&&(It.log("Credit limit exceeded (flagged by API)"),i=!0)}catch(p){It.warn("Failed to update usage",{error:p?.message||p})}},wl);return{onAgentOutput:()=>{if(i)throw new he("AI credit usage exceeded enforced limit.",503,"Credit limit reached. Check credit limits to continue using Agent Runners.",!0);s||(n=!0,c())},stop:async()=>{s||(s=!0,n&&(It.log("Sending final usage update"),c(),await c.flush()))},getCreditsCost:()=>o}};var Tl=bl(import.meta.url),At=Tl("../package.json"),Q=E("pipeline_index"),ot=3,xl=["codex","gemini"],pi=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,filter:s,isHotFollowUp:i=!1,enqueuedAt:o,tracing:a={}})=>{let c,l,d,m=Date.now(),p="success",f=!1,{withStageTimer:h}=Rn(_e.timeUnits.hours(4)),x=await Gn(At.version,e.id,a);Q.log(`Agent runner orchestrator v${At.version}`,{featureFlags:V().raw,metrics:bn()}),wr({agent:e.runner,mode:e.mode,is_follow_up:e.sessionHistoryContext.length>0,version:At.version,fast_init:e.fastInit}),ci({isHotFollowUp:i,enqueuedAt:o});try{await ar(or(),"run-pipeline",{},x,async _=>{await rn(tn(),e.runner),_?.setAttributes({"gen_ai.capability.name":e.mode,"session.id":e.sessionId});let{aiGateway:g,context:b,persistSteps:A,runner:F,sha:D}=await h("init",()=>$s({config:e,apiToken:t,cliPath:r,cwd:n,filter:s,runnerVersion:At.version}),_e.timeUnits.minutes(10)),P=F.runner;V().idleTimeoutEnabled||(c=F.clean),l=di(e.id,e.sessionId,e.enforcedAICreditsRemaining);let G=er(e.mode),$;e.deployAlias&&e.deployAlias.length>0?$=e.deployAlias:(e.deployAlias!==void 0&&!G&&Q.warn("Received empty deploy alias for a non-prod deploy, falling back to local computation"),$=_n(e.id,process.env.SITE_NAME,G));let N,I=!1,M=Object.assign(async C=>{try{l?.onAgentOutput()}catch(k){qe(k)?N??=k:Q.warn("Unexpected error in onAgentOutput",{error:k?.message||k});return}return!I&&C.steps?.some(k=>k.category!==w.Environment&&k.category!==w.UserMessage)&&(I=!0,ui({isHotFollowUp:i,enqueuedAt:o})),A(C)},{flush:A.flush.bind(A)});if(e.sha=D,e.mode==="redeploy"){let C=await h("deploy",()=>tr({cliPath:r,config:e,context:b,result:"Redeploy completed",filter:s,isRetry:!1,deploySubdomain:$}));C.deployError&&(Q.warn(`Redeploy deploy failed: ${C.deployError}`),S.inc("deploy.failed",1,{attempt:1}));let{diff:k,resultDiff:fe,previewInfo:te,diffBinary:Le,resultDiffBinary:Ai,hasNetlifyForm:Ri,hasNetlifyIdentity:Ci}=C;await l?.stop(),await h("cleanup",()=>Zr({config:e,diff:k,result:"Redeploy completed",duration:0,resultDiff:fe,diffBinary:Le,resultDiffBinary:Ai,previewInfo:te,isProdDeploy:G,hasNetlifyForm:Ri,hasNetlifyIdentity:Ci,nativeSessionArchive:$r(e.runner)}),_e.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await c?.(),await d?.stop(),await Yr());return}let B;e.mode==="create"&&(B=(await h("create",()=>Wn({config:e,cwd:n}))).additionalContext),process.env.EXPERIMENTAL_NETLIFY_DB_ENABLED="1";let W,O;if(!process.env.NETLIFY_LOCAL_MODE&&e.siteId){let C=await h("db-setup",()=>ai({siteId:e.siteId,isProd:G,alias:$,connectionString:e.dbConnectionString}),_e.timeUnits.minutes(10));if(d=C.proxy,n)if(C.proxy)B=[ti(),B].filter(Boolean).join(`
273
273
 
274
274
  `);else try{let k=await sr({cliPath:r,cwd:n});W=new Set(k.applied.map(te=>te.name)),O=k.migrationsPath;let fe=ri(k);fe&&(B=[fe,B].filter(Boolean).join(`
275
275
 
276
- `))}catch(k){Q.warn("Skipping migration context injection \u2014 failed to build state block",{error:k})}}let R=await ei(n??process.cwd(),O),T=await h("inference",async()=>{try{return await $e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,additionalContext:B,cwd:n})}catch(C){if(!(C instanceof Pe)||e.mode!=="rebase"&&e.mode!=="conflict_resolution")throw C;for(let k of Tl){if(N&&qe(N))throw N;if(k===e.runner)continue;let fe=tt[k];if(fe){Q.log(`Primary runner ${e.runner} failed in ${e.mode} mode, falling back to ${k}`),wr({agent:k,mode:e.mode,version:At.version}),await rn(tn(),k);try{let te=await $e({cliPath:r,config:{...e,runner:k},context:b,runner:fe.runner,persistSteps:M,aiGateway:g,additionalContext:B,cwd:n});return e.runner=k,P=fe.runner,V().idleTimeoutEnabled||(c=fe.clean),te}catch(te){if(qe(te))throw te;Q.error(`Fallback runner ${k} also failed`,{error:String(te)})}}}throw C}}),y=T.runnerResult;if(f=T.nativeResume??!1,e.mode==="create")try{let C=JSON.parse(wl(El.join(n??process.cwd(),".netlify","scaffold-result.json"),"utf8"));await ar(or(),"create-scaffold-telemetry",k=>{k?.setAttributes({"create.template":C.template,"create.packageManager":C.packageManager})})}catch{await ar(or(),"create-scaffold-telemetry",C=>{C?.setAttributes({"create.template":"none","create.packageManager":"none"})})}if(N)throw N;let u=await nr({cwd:n,migrationsPath:O,snapshot:R,applied:W,config:e,aiGateway:g});if(u.error){Q.log("Migration generation failed, running inference to fix the issue");let{runnerResult:C}=await h("inference-migration-fix",()=>$e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,buildErrors:[`Running \`drizzle-kit generate\` to generate database migrations failed with the following error:
276
+ `))}catch(k){Q.warn("Skipping migration context injection \u2014 failed to build state block",{error:k})}}let R=await ei(n??process.cwd(),O),T=await h("inference",async()=>{try{return await $e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,additionalContext:B,cwd:n})}catch(C){if(!(C instanceof Pe)||e.mode!=="rebase"&&e.mode!=="conflict_resolution")throw C;for(let k of xl){if(N&&qe(N))throw N;if(k===e.runner)continue;let fe=tt[k];if(fe){Q.log(`Primary runner ${e.runner} failed in ${e.mode} mode, falling back to ${k}`),wr({agent:k,mode:e.mode,version:At.version}),await rn(tn(),k);try{let te=await $e({cliPath:r,config:{...e,runner:k},context:b,runner:fe.runner,persistSteps:M,aiGateway:g,additionalContext:B,cwd:n});return e.runner=k,P=fe.runner,V().idleTimeoutEnabled||(c=fe.clean),te}catch(te){if(qe(te))throw te;Q.error(`Fallback runner ${k} also failed`,{error:String(te)})}}}throw C}}),y=T.runnerResult;if(f=T.nativeResume??!1,e.mode==="create")try{let C=JSON.parse(El(vl.join(n??process.cwd(),".netlify","scaffold-result.json"),"utf8"));await ar(or(),"create-scaffold-telemetry",k=>{k?.setAttributes({"create.template":C.template,"create.packageManager":C.packageManager})})}catch{await ar(or(),"create-scaffold-telemetry",C=>{C?.setAttributes({"create.template":"none","create.packageManager":"none"})})}if(N)throw N;let u=await nr({cwd:n,migrationsPath:O,snapshot:R,applied:W,config:e,aiGateway:g});if(u.error){Q.log("Migration generation failed, running inference to fix the issue");let{runnerResult:C}=await h("inference-migration-fix",()=>$e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,buildErrors:[`Running \`drizzle-kit generate\` to generate database migrations failed with the following error:
277
277
 
278
278
  ${u.error}
279
279
 
280
- Please fix the issue and do NOT run \`drizzle-kit generate\` yourself \u2014 it will be run automatically after you're done.`],priorAgentSessionId:y.agentSessionId}));y={...C,steps:[...y.steps||[],...C.steps||[]],duration:(y.duration||0)+(C.duration||0)},await nr({cwd:n,migrationsPath:O,snapshot:R,applied:W,config:e,aiGateway:g})}if(n&&!u.skipped){let C=await h("db-migrations-verify",()=>oi({cliPath:r,cwd:n}));if(C.error){Q.log("Migration drift detected, running inference to fix");let{runnerResult:k}=await h("inference-migration-drift-fix",()=>$e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,buildErrors:[C.error],priorAgentSessionId:y.agentSessionId}));y={...k,steps:[...y.steps||[],...k.steps||[]],duration:(y.duration||0)+(k.duration||0)}}}let v=await h("deploy",()=>tr({cliPath:r,config:e,context:b,result:y.result,filter:s,isRetry:!1,deploySubdomain:$})),J=v.hasChanges?v:void 0,q=y;v.deployError&&S.inc("deploy.failed",1,{attempt:1});let ee=[],z;if(v.hasChanges&&v.deployError){ee.push(ds(v.deployError));let C=1,k=!1;for(;C<=ot&&!v.previewInfo&&!k;)Q.log(`Deploy attempt had errors. Retrying. ${C}/${ot}`),await ar(or(),"deploy-stage",async fe=>{fe?.setAttributes({"stage.attempt":C});let te;try{te=(await h(`inference-retry-${C}`,()=>$e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,buildErrors:ee,priorAgentSessionId:y.agentSessionId}))).runnerResult}catch(Le){if(qe(Le))throw Le;Q.warn(`Inference retry ${C} failed, stopping deploy retries:`,Le),k=!0;return}if(N)throw N;q={...te,steps:[...q.steps||[],...te.steps||[]],duration:(q.duration||0)+(te.duration||0)},await nr({cwd:n,migrationsPath:O,snapshot:R,applied:W,config:e,aiGateway:g}),v=await h(`deploy-retry-${C}`,()=>tr({cliPath:r,config:e,context:b,result:te.result,filter:s,isRetry:!0,deploySubdomain:$})),v.hasChanges&&(J=v),v.deployError&&(S.inc("deploy.failed",1,{attempt:C+1}),ee.push(v.deployError)),C++});C>ot&&!v.previewInfo&&(S.inc("deploy.retries_exhausted",1),e.mode==="create"?(console.warn(`Deploy still failing after ${ot} retries, failing the create run`),z=new Error(`Deploy failed after ${ot} retries`)):console.warn(`Deploy still failing after ${ot} retries, completing run without a preview`))}let ue=v.previewInfo||v.hasChanges?v:J??v,{diff:Y,resultDiff:H,previewInfo:ge,diffBinary:Fe,resultDiffBinary:Ti,hasNetlifyForm:xi,hasNetlifyIdentity:Ii}=ue;await l?.stop();let ur=q.agentSessionId??y.agentSessionId;if(ur&&mi(ur),await h("cleanup",()=>Zr({config:e,diff:Y,result:q.result,duration:q.duration,resultDiff:H,diffBinary:Fe,resultDiffBinary:Ti,previewInfo:ge,isProdDeploy:G,hasNetlifyForm:xi,hasNetlifyIdentity:Ii,nativeSessionArchive:$r(e.runner),nativeSessionId:ur}),_e.timeUnits.minutes(10)),z)throw z;process.env.NETLIFY_LOCAL_MODE||(await c?.(),await d?.stop(),await Yr());let ct=e.siteId?await bs(e.siteId):!1;typeof ct=="boolean"&&_?.setAttributes({"actual.has_db":ct}),Q.info("agent_storage_outcome",{sessionId:e.sessionId,runnerId:e.id,siteId:e.siteId,accountId:e.accountId,runner:e.runner,has_db:ct??"unknown"});let dr=_?.spanContext();dr&&await pe(e.id,e.sessionId,{metadata:{storage_outcome:{...typeof ct=="boolean"?{has_db:ct}:{},trace_id:dr.traceId,span_id:dr.spanId}}}).catch(C=>Q.warn("Failed to persist storage_outcome",{error:C?.message}))})}catch(_){if(qe(_)){p="gracefulError",Q.info("Agent run terminated gracefully",{statusCode:_.statusCode,reason:_.message}),await l?.stop(),await c?.(),await d?.stop();try{await pe(e.id,e.sessionId,{result:_.userMessage,state:_.isCreditLimitExceeded?"cancelled":"error",..._.isCreditLimitExceeded&&{credit_limit_exceeded:!0}})}catch{Q.info("Could not update session (site may have been deleted)")}return}p="error",Q.error("Got error while running pipeline",_),await l?.stop(),await c?.(),await d?.stop();let g=_ instanceof Error&&_.message,b=g?Dt(g):"Encountered error when running agent";throw await pe(e.id,e.sessionId,{result:b,state:"error"}),_}finally{S.timing("session.duration",Date.now()-m,{hot_follow_up:i,outcome:p,native_resume:f});let _=l?.getCreditsCost();_!=null&&S.distribution("session.credits_cost",_,{outcome:p,native_resume:f}),await bl()}};var at=null,nn={},fi,sn,Rt=class extends Error{constructor(){super("A session is already running"),this.name="SessionAlreadyRunningError"}},hi=e=>{nn=e},lr=e=>{if(at)throw new Rt;let t={...nn,...e,tracing:{...nn.tracing,...e.tracing}};return at=pi(t).finally(()=>{at=null,fi=t.config.runner}),at},tn=()=>fi,gi=E("session_manager"),rn=async(e,t)=>{if(!V().idleTimeoutEnabled||!e||e===t)return;let r=tt[e];if(r)try{await r.clean(),gi.info(`Wiped previous agent state (${e}) on switch to ${t}`)}catch(n){gi.warn(`Failed to clean previous agent ${e} on switch`,{error:n?.message||n})}finally{sn=void 0}},mi=e=>{sn=e};var Ys=e=>{if(!V().idleTimeoutEnabled)return!1;let t=e.previousSession;return!t||t.agent!==e.runner||!t.nativeSessionId?!1:t.nativeSessionId===sn},yi=async()=>{if(at)try{await at}catch{}};var on=E("server"),_i=8888,wi=!1,Ei=()=>{wi=!0};var Il={type:"object",required:["prompt","sessionId","sha","mode","context"],properties:{prompt:{type:"string"},sessionId:{type:"string"},sha:{type:"string"},mode:{type:"string",enum:kt},context:{type:"array",items:{type:"object"}},enforcedAICreditsRemaining:{type:"integer"},agent:{type:"string",enum:Dr},model:{type:"string"},enqueuedAt:{type:"integer"},assetMap:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},previousSession:{type:"object",required:["nativeSessionId","agent"],properties:{nativeSessionId:{type:"string"},agent:{type:"string",enum:Dr}}}}},Al=async(e,t)=>{wi&&t.code(503).send({error:"shutdown",message:"Server is shutting down"})},Rl=async()=>({ok:!0}),Cl=async(e,t)=>{try{let r=xn(e.body),n=typeof e.headers.traceparent=="string"?{traceparent:e.headers.traceparent}:void 0;return lr({config:r,tracing:n,isHotFollowUp:!0,enqueuedAt:e.body.enqueuedAt}).catch(s=>{on.error("Background session failed",s)}),{ok:!0,sessionId:e.body.sessionId}}catch(r){return r instanceof Rt?t.code(409).send({error:"session_already_running",message:r.message}):(on.error("Error handling POST /sessions",r),t.code(500).send({error:"internal_server_error",message:"Internal server error"}))}},Nl=()=>{let e=xl({logger:!1});return e.addHook("onRequest",Al),e.get("/health",Rl),e.post("/sessions",{schema:{body:Il}},Cl),e},vi=async()=>{let e=Nl();return await e.listen({port:_i,host:"0.0.0.0"}),on.info(`HTTP server listening on port ${_i}`),e};import Ct from"process";var cr=E("shutdown"),bi=!1,Si=e=>{let t=async r=>{if(!bi){bi=!0,cr.info(`Received ${r}, draining`),Ei();try{await e.close(),await yi()}catch(n){cr.error("Error during graceful shutdown",n)}cr.info("Shutdown complete"),Ct.exit(0)}};Ct.on("SIGINT",()=>{t("SIGINT")}),Ct.on("SIGTERM",()=>{t("SIGTERM")}),Ct.on("unhandledRejection",r=>{cr.error("Unhandled promise rejection \u2014 exiting",r),Ct.exit(1)})};var Pl=2,an=E("bin_cmd"),lt=kl(ln.argv.slice(2),{string:["auth","cwd","cli-path","filter","trace-exporter-url","traceparent"]}),Nt=null;try{let e=Tn(),t={apiToken:lt.auth,cwd:lt.cwd,cliPath:lt["cli-path"],filter:lt.filter,tracing:{exporterUrl:lt["trace-exporter-url"]}};hi(t);let r=lr({config:e,...t,tracing:{...t.tracing,traceparent:lt.traceparent}});V().idleTimeoutEnabled&&(Nt=await vi(),Si(Nt)),await r,an.info("Finished agent"),Nt||ln.exit(0)}catch(e){if(an.error("Error running agent pipeline:",e),Nt)try{await Nt.close()}catch(t){an.error("Error closing server during failure exit",t)}ln.exit(In(e)?Pl:1)}
280
+ Please fix the issue and do NOT run \`drizzle-kit generate\` yourself \u2014 it will be run automatically after you're done.`],priorAgentSessionId:y.agentSessionId}));y={...C,steps:[...y.steps||[],...C.steps||[]],duration:(y.duration||0)+(C.duration||0)},await nr({cwd:n,migrationsPath:O,snapshot:R,applied:W,config:e,aiGateway:g})}if(n&&!u.skipped){let C=await h("db-migrations-verify",()=>oi({cliPath:r,cwd:n}));if(C.error){Q.log("Migration drift detected, running inference to fix");let{runnerResult:k}=await h("inference-migration-drift-fix",()=>$e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,buildErrors:[C.error],priorAgentSessionId:y.agentSessionId}));y={...k,steps:[...y.steps||[],...k.steps||[]],duration:(y.duration||0)+(k.duration||0)}}}let v=await h("deploy",()=>tr({cliPath:r,config:e,context:b,result:y.result,filter:s,isRetry:!1,deploySubdomain:$})),J=v.hasChanges?v:void 0,q=y;v.deployError&&S.inc("deploy.failed",1,{attempt:1});let ee=[],z;if(v.hasChanges&&v.deployError){ee.push(ds(v.deployError));let C=1,k=!1;for(;C<=ot&&!v.previewInfo&&!k;)Q.log(`Deploy attempt had errors. Retrying. ${C}/${ot}`),await ar(or(),"deploy-stage",async fe=>{fe?.setAttributes({"stage.attempt":C});let te;try{te=(await h(`inference-retry-${C}`,()=>$e({cliPath:r,config:e,context:b,runner:P,persistSteps:M,aiGateway:g,buildErrors:ee,priorAgentSessionId:y.agentSessionId}))).runnerResult}catch(Le){if(qe(Le))throw Le;Q.warn(`Inference retry ${C} failed, stopping deploy retries:`,Le),k=!0;return}if(N)throw N;q={...te,steps:[...q.steps||[],...te.steps||[]],duration:(q.duration||0)+(te.duration||0)},await nr({cwd:n,migrationsPath:O,snapshot:R,applied:W,config:e,aiGateway:g}),v=await h(`deploy-retry-${C}`,()=>tr({cliPath:r,config:e,context:b,result:te.result,filter:s,isRetry:!0,deploySubdomain:$})),v.hasChanges&&(J=v),v.deployError&&(S.inc("deploy.failed",1,{attempt:C+1}),ee.push(v.deployError)),C++});C>ot&&!v.previewInfo&&(S.inc("deploy.retries_exhausted",1),e.mode==="create"?(console.warn(`Deploy still failing after ${ot} retries, failing the create run`),z=new Error(`Deploy failed after ${ot} retries`)):console.warn(`Deploy still failing after ${ot} retries, completing run without a preview`))}let ue=v.previewInfo||v.hasChanges?v:J??v,{diff:Y,resultDiff:H,previewInfo:ge,diffBinary:Fe,resultDiffBinary:Ti,hasNetlifyForm:xi,hasNetlifyIdentity:Ii}=ue;await l?.stop();let ur=q.agentSessionId??y.agentSessionId;if(ur&&mi(ur),await h("cleanup",()=>Zr({config:e,diff:Y,result:q.result,duration:q.duration,resultDiff:H,diffBinary:Fe,resultDiffBinary:Ti,previewInfo:ge,isProdDeploy:G,hasNetlifyForm:xi,hasNetlifyIdentity:Ii,nativeSessionArchive:$r(e.runner),nativeSessionId:ur}),_e.timeUnits.minutes(10)),z)throw z;process.env.NETLIFY_LOCAL_MODE||(await c?.(),await d?.stop(),await Yr());let ct=e.siteId?await bs(e.siteId):!1;typeof ct=="boolean"&&_?.setAttributes({"actual.has_db":ct}),Q.info("agent_storage_outcome",{sessionId:e.sessionId,runnerId:e.id,siteId:e.siteId,accountId:e.accountId,runner:e.runner,has_db:ct??"unknown"});let dr=_?.spanContext();dr&&await pe(e.id,e.sessionId,{metadata:{storage_outcome:{...typeof ct=="boolean"?{has_db:ct}:{},trace_id:dr.traceId,span_id:dr.spanId}}}).catch(C=>Q.warn("Failed to persist storage_outcome",{error:C?.message}))})}catch(_){if(qe(_)){p="gracefulError",Q.info("Agent run terminated gracefully",{statusCode:_.statusCode,reason:_.message}),await l?.stop(),await c?.(),await d?.stop();try{await pe(e.id,e.sessionId,{result:_.userMessage,state:_.isCreditLimitExceeded?"cancelled":"error",..._.isCreditLimitExceeded&&{credit_limit_exceeded:!0}})}catch{Q.info("Could not update session (site may have been deleted)")}return}p="error",Q.error("Got error while running pipeline",_),await l?.stop(),await c?.(),await d?.stop();let g=_ instanceof Error&&_.message,b=g?Dt(g):"Encountered error when running agent";throw await pe(e.id,e.sessionId,{result:b,state:"error"}),_}finally{S.timing("session.duration",Date.now()-m,{hot_follow_up:i,outcome:p,native_resume:f});let _=l?.getCreditsCost();_!=null&&S.distribution("session.credits_cost",_,{outcome:p,native_resume:f}),await Sl()}};var at=null,nn={},fi,sn,Rt=class extends Error{constructor(){super("A session is already running"),this.name="SessionAlreadyRunningError"}},hi=e=>{nn=e},lr=e=>{if(at)throw new Rt;let t={...nn,...e,tracing:{...nn.tracing,...e.tracing}};return at=pi(t).finally(()=>{at=null,fi=t.config.runner}),at},tn=()=>fi,gi=E("session_manager"),rn=async(e,t)=>{if(!V().idleTimeoutEnabled||!e||e===t)return;let r=tt[e];if(r)try{await r.clean(),gi.info(`Wiped previous agent state (${e}) on switch to ${t}`)}catch(n){gi.warn(`Failed to clean previous agent ${e} on switch`,{error:n?.message||n})}finally{sn=void 0}},mi=e=>{sn=e};var Ys=e=>{if(!V().idleTimeoutEnabled)return!1;let t=e.previousSession;return!t||t.agent!==e.runner||!t.nativeSessionId?!1:t.nativeSessionId===sn},yi=async()=>{if(at)try{await at}catch{}};var on=E("server"),_i=8888,wi=!1,Ei=()=>{wi=!0};var Al={type:"object",required:["prompt","sessionId","sha","mode","context"],properties:{prompt:{type:"string"},sessionId:{type:"string"},sha:{type:"string"},mode:{type:"string",enum:kt},context:{type:"array",items:{type:"object"}},enforcedAICreditsRemaining:{type:"integer"},agent:{type:"string",enum:Dr},model:{type:"string"},enqueuedAt:{type:"integer"},assetMap:{type:"object",additionalProperties:{type:"array",items:{type:"string"}}},previousSession:{type:"object",required:["nativeSessionId","agent"],properties:{nativeSessionId:{type:"string"},agent:{type:"string",enum:Dr}}}}},Rl=async(e,t)=>{wi&&t.code(503).send({error:"shutdown",message:"Server is shutting down"})},Cl=async()=>({ok:!0}),Nl=async(e,t)=>{try{let r=xn(e.body),n=typeof e.headers.traceparent=="string"?{traceparent:e.headers.traceparent}:void 0;return lr({config:r,tracing:n,isHotFollowUp:!0,enqueuedAt:e.body.enqueuedAt}).catch(s=>{on.error("Background session failed",s)}),{ok:!0,sessionId:e.body.sessionId}}catch(r){return r instanceof Rt?t.code(409).send({error:"session_already_running",message:r.message}):(on.error("Error handling POST /sessions",r),t.code(500).send({error:"internal_server_error",message:"Internal server error"}))}},kl=()=>{let e=Il({logger:!1});return e.addHook("onRequest",Rl),e.get("/health",Cl),e.post("/sessions",{schema:{body:Al}},Nl),e},vi=async()=>{let e=kl();return await e.listen({port:_i,host:"0.0.0.0"}),on.info(`HTTP server listening on port ${_i}`),e};import Ct from"process";var cr=E("shutdown"),bi=!1,Si=e=>{let t=async r=>{if(!bi){bi=!0,cr.info(`Received ${r}, draining`),Ei();try{await e.close(),await yi()}catch(n){cr.error("Error during graceful shutdown",n)}cr.info("Shutdown complete"),Ct.exit(0)}};Ct.on("SIGINT",()=>{t("SIGINT")}),Ct.on("SIGTERM",()=>{t("SIGTERM")}),Ct.on("unhandledRejection",r=>{cr.error("Unhandled promise rejection \u2014 exiting",r),Ct.exit(1)})};var Ol=2,an=E("bin_cmd"),lt=Pl(ln.argv.slice(2),{string:["auth","cwd","cli-path","filter","trace-exporter-url","traceparent"]}),Nt=null;try{let e=Tn(),t={apiToken:lt.auth,cwd:lt.cwd,cliPath:lt["cli-path"],filter:lt.filter,tracing:{exporterUrl:lt["trace-exporter-url"]}};hi(t);let r=lr({config:e,...t,tracing:{...t.tracing,traceparent:lt.traceparent}});V().idleTimeoutEnabled&&(Nt=await vi(),Si(Nt)),await r,an.info("Finished agent"),Nt||ln.exit(0)}catch(e){if(an.error("Error running agent pipeline:",e),Nt)try{await Nt.close()}catch(t){an.error("Error closing server during failure exit",t)}ln.exit(In(e)?Ol:1)}
281
281
  //# sourceMappingURL=bin.js.map