@netlify/agent-runner-cli 1.200.2-bug.3 → 1.200.2-bug.4
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/README.md +11 -0
- package/dist/bin-local.js +4 -4
- package/dist/bin.js +4 -4
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -30,3 +30,14 @@ exist nowhere in Humio — buildbot computes them for the metric only. This repo
|
|
|
30
30
|
`buildbot.agent_runner.*`.
|
|
31
31
|
|
|
32
32
|
See [Observability](https://app.notion.com/p/3e61da88359a81bcb2d8c9f58dbb32ef) for the rest and what each field means.
|
|
33
|
+
|
|
34
|
+
### If `$aro()` is slow
|
|
35
|
+
|
|
36
|
+
Fall back to `$bbot()` without `kvParse()`. `$aro()` parses every agent run line in the window before your filter
|
|
37
|
+
applies, so a long window can time out. Narrow `$bbot()` with `dev_server_id` or a quoted string and read the fields
|
|
38
|
+
from `msg`. A quoted string can also match transcript text:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
$bbot() | dev_server_id=<dev_server_id>
|
|
42
|
+
$bbot() | "agent_runner_id=<id>"
|
|
43
|
+
```
|
package/dist/bin-local.js
CHANGED
|
@@ -385,8 +385,8 @@ For example, you can use the \`pathToFileURL()\` method of the \`url\` core modu
|
|
|
385
385
|
`,LF:`
|
|
386
386
|
`,concatBytes:EY},Lct=(t,e)=>{let r=new Uint8Array(t.length+e.length);return r.set(t,0),r.set(e,t.length),r},Uct={windowsNewline:new Uint8Array([13,10]),unixNewline:new Uint8Array([10]),LF:10,concatBytes:Lct};import{Buffer as Fct}from"buffer";var fwe=(t,e)=>t?void 0:zct.bind(void 0,e),zct=function*(t,e){if(typeof e!="string"&&!zr(e)&&!Fct.isBuffer(e))throw new TypeError(`The \`${t}\` option's transform must use "objectMode: true" to receive as input: ${typeof e}.`);yield e},pwe=(t,e)=>t?jct.bind(void 0,e):qct.bind(void 0,e),jct=function*(t,e){hwe(t,e),yield e},qct=function*(t,e){if(hwe(t,e),typeof e!="string"&&!zr(e))throw new TypeError(`The \`${t}\` option's function must yield a string or an Uint8Array, not ${typeof e}.`);yield e},hwe=(t,e)=>{if(e==null)throw new TypeError(`The \`${t}\` option's function must not call \`yield ${e}\`.
|
|
387
387
|
Instead, \`yield\` should either be called with a value, or not be called at all. For example:
|
|
388
|
-
if (condition) { yield value; }`)};import{Buffer as Bct}from"buffer";import{StringDecoder as Vct}from"string_decoder";var qD=(t,e,r)=>{if(r)return;if(t)return{transform:Gct.bind(void 0,new TextEncoder)};let n=new Vct(e);return{transform:Hct.bind(void 0,n),final:Wct.bind(void 0,n)}},Gct=function*(t,e){Bct.isBuffer(e)?yield ou(e):typeof e=="string"?yield t.encode(e):yield e},Hct=function*(t,e){yield zr(e)?t.write(e):e},Wct=function*(t){let e=t.end();e!==""&&(yield e)};import{callbackify as mwe}from"util";var wY=mwe(async(t,e,r,n)=>{e.currentIterable=t(...r);try{for await(let i of e.currentIterable)n.push(i)}finally{delete e.currentIterable}}),BD=async function*(t,e,r){if(r===e.length){yield t;return}let{transform:n=Yct}=e[r];for await(let i of n(t))yield*BD(i,e,r+1)},gwe=async function*(t){for(let[e,{final:r}]of Object.entries(t))yield*Kct(r,Number(e),t)},Kct=async function*(t,e,r){if(t!==void 0)for await(let n of t())yield*BD(n,r,e+1)},_we=mwe(async({currentIterable:t},e)=>{if(t!==void 0){await(e?t.throw(e):t.return());return}if(e)throw e}),Yct=function*(t){yield t};var TY=(t,e,r,n)=>{try{for(let i of t(...e))r.push(i);n()}catch(i){n(i)}},ywe=(t,e)=>[...e.flatMap(r=>[...wp(r,t,0)]),...UT(t)],wp=function*(t,e,r){if(r===e.length){yield t;return}let{transform:n=Qct}=e[r];for(let i of n(t))yield*wp(i,e,r+1)},UT=function*(t){for(let[e,{final:r}]of Object.entries(t))yield*Zct(r,Number(e),t)},Zct=function*(t,e,r){if(t!==void 0)for(let n of t())yield*wp(n,r,e+1)},Qct=function*(t){yield t};var AY=({value:t,value:{transform:e,final:r,writableObjectMode:n,readableObjectMode:i},optionName:s},{encoding:o})=>{let a={},c=vwe(t,o,s),u=bp(e),l=bp(r),d=u?wY.bind(void 0,BD,a):TY.bind(void 0,wp),f=u||l?wY.bind(void 0,gwe,a):TY.bind(void 0,UT),p=u||l?_we.bind(void 0,a):void 0;return{stream:new Jct({writableObjectMode:n,writableHighWaterMark:Swe(n),readableObjectMode:i,readableHighWaterMark:Swe(i),transform(m,_,S){d([m,c,0],this,S)},flush(m){f([c],this,m)},destroy:p})}},VD=(t,e,r,n)=>{let i=e.filter(({type:o})=>o==="generator"),s=n?i.reverse():i;for(let{value:o,optionName:a}of s){let c=vwe(o,r,a);t=ywe(c,t)}return t},vwe=({transform:t,final:e,binary:r,writableObjectMode:n,readableObjectMode:i,preserveNewlines:s},o,a)=>{let c={};return[{transform:fwe(n,a)},qD(r,o,n),jD(r,s,n,c),{transform:t,final:e},{transform:pwe(i,a)},dwe({binary:r,preserveNewlines:s,readableObjectMode:i,state:c})].filter(Boolean)};var Ewe=(t,e)=>{for(let r of Xct(t))eut(t,r,e)},Xct=t=>new Set(Object.entries(t).filter(([,{direction:e}])=>e==="input").map(([e])=>Number(e))),eut=(t,e,r)=>{let{stdioItems:n}=t[e],i=n.filter(({contents:a})=>a!==void 0);if(i.length===0)return;if(e!==0){let[{type:a,optionName:c}]=i;throw new TypeError(`Only the \`stdin\` option, not \`${c}\`, can be ${Bl[a]} with synchronous methods.`)}let o=i.map(({contents:a})=>a).map(a=>tut(a,n));r.input=OT(o)},tut=(t,e)=>{let r=VD(t,e,"utf8",!0);return rut(r),OT(r)},rut=t=>{let e=t.find(r=>typeof r!="string"&&!zr(r));if(e!==void 0)throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${e}.`)};import{writeFileSync as out,appendFileSync as aut}from"fs";var GD=({stdioItems:t,encoding:e,verboseInfo:r,fdNumber:n})=>n!=="all"&&R_(r,n)&&!es.has(e)&&nut(n)&&(t.some(({type:i,value:s})=>i==="native"&&iut.has(s))||t.every(({type:i})=>$s.has(i))),nut=t=>t===1||t===2,iut=new Set(["pipe","overlapped"]),bwe=async(t,e,r,n)=>{for await(let i of t)sut(e)||Twe(i,r,n)},wwe=(t,e,r)=>{for(let n of t)Twe(n,e,r)},sut=t=>t._readableState.pipes.length>0,Twe=(t,e,r)=>{let n=sD(t);Ga({type:"output",verboseMessage:n,fdNumber:e,verboseInfo:r})};var Awe=({fileDescriptors:t,syncResult:{output:e},options:r,isMaxBuffer:n,verboseInfo:i})=>{if(e===null)return{output:Array.from({length:3})};let s={},o=new Set([]);return{output:e.map((c,u)=>cut({result:c,fileDescriptors:t,fdNumber:u,state:s,outputFiles:o,isMaxBuffer:n,verboseInfo:i},r)),...s}},cut=({result:t,fileDescriptors:e,fdNumber:r,state:n,outputFiles:i,isMaxBuffer:s,verboseInfo:o},{buffer:a,encoding:c,lines:u,stripFinalNewline:l,maxBuffer:d})=>{if(t===null)return;let f=Rbe(t,s,d),p=ou(f),{stdioItems:h,objectMode:m}=e[r],_=uut([p],h,c,n),{serializedResult:S,finalResult:b=S}=lut({chunks:_,objectMode:m,encoding:c,lines:u,stripFinalNewline:l,fdNumber:r});dut({serializedResult:S,fdNumber:r,state:n,verboseInfo:o,encoding:c,stdioItems:h,objectMode:m});let R=a[r]?b:void 0;try{return n.error===void 0&&fut(S,h,i),R}catch(y){return n.error=y,R}},uut=(t,e,r,n)=>{try{return VD(t,e,r,!1)}catch(i){return n.error=i,t}},lut=({chunks:t,objectMode:e,encoding:r,lines:n,stripFinalNewline:i,fdNumber:s})=>{if(e)return{serializedResult:t};if(r==="buffer")return{serializedResult:OT(t)};let o=zSe(t,r);return n[s]?{serializedResult:o,finalResult:bY(o,!i[s],e)}:{serializedResult:o}},dut=({serializedResult:t,fdNumber:e,state:r,verboseInfo:n,encoding:i,stdioItems:s,objectMode:o})=>{if(!GD({stdioItems:s,encoding:i,verboseInfo:n,fdNumber:e}))return;let a=bY(t,!1,o);try{wwe(a,e,n)}catch(c){r.error??=c}},fut=(t,e,r)=>{for(let{path:n,append:i}of e.filter(({type:s})=>FD.has(s))){let s=typeof n=="string"?n:n.toString();i||r.has(s)?aut(n,t):(r.add(s),out(n,t))}};var Rwe=([,t,e],r)=>{if(r.all)return t===void 0?e:e===void 0?t:Array.isArray(t)?Array.isArray(e)?[...t,...e]:[...t,uu(e,r,"all")]:Array.isArray(e)?[uu(t,r,"all"),...e]:zr(t)&&zr(e)?CK([t,e]):`${t}${e}`};import{once as RY}from"events";var xwe=async(t,e)=>{let[r,n]=await put(t);return e.isForcefullyTerminated??=!1,[r,n]},put=async t=>{let[e,r]=await Promise.allSettled([RY(t,"spawn"),RY(t,"exit")]);return e.status==="rejected"?[]:r.status==="rejected"?Owe(t):r.value},Owe=async t=>{try{return await RY(t,"exit")}catch{return Owe(t)}},Iwe=async t=>{let[e,r]=await t;if(!hut(e,r)&&xY(e,r))throw new Ho;return[e,r]},hut=(t,e)=>t===void 0&&e===void 0,xY=(t,e)=>t!==0||e!==null;var Pwe=({error:t,status:e,signal:r,output:n},{maxBuffer:i})=>{let s=mut(t,e,r),o=s?.code==="ETIMEDOUT",a=Abe(s,n,i);return{resultError:s,exitCode:e,signal:r,timedOut:o,isMaxBuffer:a}},mut=(t,e,r)=>t!==void 0?t:xY(e,r)?new Ho:void 0;var Cwe=(t,e,r)=>{let{file:n,commandArguments:i,command:s,escapedCommand:o,startTime:a,verboseInfo:c,options:u,fileDescriptors:l}=_ut(t,e,r),d=vut({file:n,commandArguments:i,options:u,command:s,escapedCommand:o,verboseInfo:c,fileDescriptors:l,startTime:a});return $_(d,c,u)},_ut=(t,e,r)=>{let{command:n,escapedCommand:i,startTime:s,verboseInfo:o}=aD(t,e,r),a=yut(r),{file:c,commandArguments:u,options:l}=xD(t,e,a);Sut(l);let d=awe(l,o);return{file:c,commandArguments:u,command:n,escapedCommand:i,startTime:s,verboseInfo:o,options:l,fileDescriptors:d}},yut=t=>t.node&&!t.ipc?{...t,ipc:!1}:t,Sut=({ipc:t,ipcInput:e,detached:r,cancelSignal:n})=>{e&&HD("ipcInput"),t&&HD("ipc: true"),r&&HD("detached: true"),n&&HD("cancelSignal")},HD=t=>{throw new TypeError(`The "${t}" option cannot be used with synchronous methods.`)},vut=({file:t,commandArguments:e,options:r,command:n,escapedCommand:i,verboseInfo:s,fileDescriptors:o,startTime:a})=>{let c=Eut({file:t,commandArguments:e,options:r,command:n,escapedCommand:i,fileDescriptors:o,startTime:a});if(c.failed)return c;let{resultError:u,exitCode:l,signal:d,timedOut:f,isMaxBuffer:p}=Pwe(c,r),{output:h,error:m=u}=Awe({fileDescriptors:o,syncResult:c,options:r,isMaxBuffer:p,verboseInfo:s}),_=h.map((b,R)=>uu(b,r,R)),S=uu(Rwe(h,r),r,"all");return wut({error:m,exitCode:l,signal:d,timedOut:f,isMaxBuffer:p,stdio:_,all:S,options:r,command:n,escapedCommand:i,startTime:a})},Eut=({file:t,commandArguments:e,options:r,command:n,escapedCommand:i,fileDescriptors:s,startTime:o})=>{try{Ewe(s,r);let a=but(r);return gut(...OD(t,e,a))}catch(a){return M_({error:a,command:n,escapedCommand:i,fileDescriptors:s,options:r,startTime:o,isSync:!0})}},but=({encoding:t,maxBuffer:e,...r})=>({...r,encoding:"buffer",maxBuffer:MD(e)}),wut=({error:t,exitCode:e,signal:r,timedOut:n,isMaxBuffer:i,stdio:s,all:o,options:a,command:c,escapedCommand:u,startTime:l})=>t===void 0?$D({command:c,escapedCommand:u,stdio:s,all:o,ipcOutput:[],options:a,startTime:l}):LT({error:t,command:c,escapedCommand:u,timedOut:n,isCanceled:!1,isGracefullyCanceled:!1,isMaxBuffer:i,isForcefullyTerminated:!1,exitCode:e,signal:r,stdio:s,all:o,ipcOutput:[],options:a,startTime:l,isSync:!0});import{setMaxListeners as ldt}from"events";import{spawn as ddt}from"child_process";import $we from"process";import{once as OY,on as Tut}from"events";var kwe=({anyProcess:t,channel:e,isSubprocess:r,ipc:n},{reference:i=!0,filter:s}={})=>(I_({methodName:"getOneMessage",isSubprocess:r,ipc:n,isConnected:ED(t)}),Aut({anyProcess:t,channel:e,isSubprocess:r,filter:s,reference:i})),Aut=async({anyProcess:t,channel:e,isSubprocess:r,filter:n,reference:i})=>{_D(e,i);let s=ql(t,e,r),o=new AbortController;try{return await Promise.race([Rut(s,n,o),xut(s,r,o),Out(s,r,o)])}catch(a){throw P_(t),a}finally{o.abort(),yD(e,i)}},Rut=async(t,e,{signal:r})=>{if(e===void 0){let[n]=await OY(t,"message",{signal:r});return n}for await(let[n]of Tut(t,"message",{signal:r}))if(e(n))return n},xut=async(t,e,{signal:r})=>{await OY(t,"disconnect",{signal:r}),yEe(e)},Out=async(t,e,{signal:r})=>{let[n]=await OY(t,"strict:error",{signal:r});throw hD(n,e)};import{once as Dwe,on as Iut}from"events";var Mwe=({anyProcess:t,channel:e,isSubprocess:r,ipc:n},{reference:i=!0}={})=>IY({anyProcess:t,channel:e,isSubprocess:r,ipc:n,shouldAwait:!r,reference:i}),IY=({anyProcess:t,channel:e,isSubprocess:r,ipc:n,shouldAwait:i,reference:s})=>{I_({methodName:"getEachMessage",isSubprocess:r,ipc:n,isConnected:ED(t)}),_D(e,s);let o=ql(t,e,r),a=new AbortController,c={};return Put(t,o,a),Cut({ipcEmitter:o,isSubprocess:r,controller:a,state:c}),kut({anyProcess:t,channel:e,ipcEmitter:o,isSubprocess:r,shouldAwait:i,controller:a,state:c,reference:s})},Put=async(t,e,r)=>{try{await Dwe(e,"disconnect",{signal:r.signal}),r.abort()}catch{}},Cut=async({ipcEmitter:t,isSubprocess:e,controller:r,state:n})=>{try{let[i]=await Dwe(t,"strict:error",{signal:r.signal});n.error=hD(i,e),r.abort()}catch{}},kut=async function*({anyProcess:t,channel:e,ipcEmitter:r,isSubprocess:n,shouldAwait:i,controller:s,state:o,reference:a}){try{for await(let[c]of Iut(r,"message",{signal:s.signal}))Nwe(o),yield c}catch{Nwe(o)}finally{s.abort(),yD(e,a),n||P_(t),i&&await t}},Nwe=({error:t})=>{if(t)throw t};var Lwe=(t,{ipc:e})=>{Object.assign(t,Fwe(t,!1,e))},Uwe=()=>{let t=$we,e=!0,r=$we.channel!==void 0;return{...Fwe(t,e,r),getCancelSignal:GEe.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r})}},Fwe=(t,e,r)=>({sendMessage:AD.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r}),getOneMessage:kwe.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r}),getEachMessage:Mwe.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r})});import{ChildProcess as Nut}from"child_process";import{PassThrough as Dut,Readable as Mut,Writable as $ut,Duplex as Lut}from"stream";var zwe=({error:t,command:e,escapedCommand:r,fileDescriptors:n,options:i,startTime:s,verboseInfo:o})=>{SY(n);let a=new Nut;Uut(a,n),Object.assign(a,{readable:Fut,writable:zut,duplex:jut});let c=M_({error:t,command:e,escapedCommand:r,fileDescriptors:n,options:i,startTime:s,isSync:!1}),u=qut(c,o,i);return{subprocess:a,promise:u}},Uut=(t,e)=>{let r=FT(),n=FT(),i=FT(),s=Array.from({length:e.length-3},FT),o=FT(),a=[r,n,i,...s];Object.assign(t,{stdin:r,stdout:n,stderr:i,all:o,stdio:a})},FT=()=>{let t=new Dut;return t.end(),t},Fut=()=>new Mut({read(){}}),zut=()=>new $ut({write(){}}),jut=()=>new Lut({read(){},write(){}}),qut=async(t,e,r)=>$_(t,e,r);import{createReadStream as jwe,createWriteStream as qwe}from"fs";import{Buffer as But}from"buffer";import{Readable as zT,Writable as Vut,Duplex as Gut}from"stream";var Vwe=(t,e)=>zD(Hut,t,e,!1),jT=({type:t,optionName:e})=>{throw new TypeError(`The \`${e}\` option cannot be ${Bl[t]}.`)},Bwe={fileNumber:jT,generator:AY,asyncGenerator:AY,nodeStream:({value:t})=>({stream:t}),webTransform({value:{transform:t,writableObjectMode:e,readableObjectMode:r}}){let n=e||r;return{stream:Gut.fromWeb(t,{objectMode:n})}},duplex:({value:{transform:t}})=>({stream:t}),native(){}},Hut={input:{...Bwe,fileUrl:({value:t})=>({stream:jwe(t)}),filePath:({value:{file:t}})=>({stream:jwe(t)}),webStream:({value:t})=>({stream:zT.fromWeb(t)}),iterable:({value:t})=>({stream:zT.from(t)}),asyncIterable:({value:t})=>({stream:zT.from(t)}),string:({value:t})=>({stream:zT.from(t)}),uint8Array:({value:t})=>({stream:zT.from(But.from(t))})},output:{...Bwe,fileUrl:({value:t})=>({stream:qwe(t)}),filePath:({value:{file:t,append:e}})=>({stream:qwe(t,e?{flags:"a"}:{})}),webStream:({value:t})=>({stream:Vut.fromWeb(t)}),iterable:jT,asyncIterable:jT,string:jT,uint8Array:jT}};import{on as Wut,once as Gwe}from"events";import{PassThrough as Kut,getDefaultHighWaterMark as Yut}from"stream";import{finished as Kwe}from"stream/promises";function Tp(t){if(!Array.isArray(t))throw new TypeError(`Expected an array, got \`${typeof t}\`.`);for(let i of t)CY(i);let e=t.some(({readableObjectMode:i})=>i),r=Zut(t,e),n=new PY({objectMode:e,writableHighWaterMark:r,readableHighWaterMark:r});for(let i of t)n.add(i);return n}var Zut=(t,e)=>{if(t.length===0)return Yut(e);let r=t.filter(({readableObjectMode:n})=>n===e).map(({readableHighWaterMark:n})=>n);return Math.max(...r)},PY=class extends Kut{#e=new Set([]);#r=new Set([]);#t=new Set([]);#n;#s=Symbol("unpipe");#i=new WeakMap;add(e){if(CY(e),this.#e.has(e))return;this.#e.add(e),this.#n??=Qut(this,this.#e,this.#s);let r=elt({passThroughStream:this,stream:e,streams:this.#e,ended:this.#r,aborted:this.#t,onFinished:this.#n,unpipeEvent:this.#s});this.#i.set(e,r),e.pipe(this,{end:!1})}async remove(e){if(CY(e),!this.#e.has(e))return!1;let r=this.#i.get(e);return r===void 0?!1:(this.#i.delete(e),e.unpipe(this),await r,!0)}},Qut=async(t,e,r)=>{WD(t,Hwe);let n=new AbortController;try{await Promise.race([Jut(t,n),Xut(t,e,r,n)])}finally{n.abort(),WD(t,-Hwe)}},Jut=async(t,{signal:e})=>{try{await Kwe(t,{signal:e,cleanup:!0})}catch(r){throw Ywe(t,r),r}},Xut=async(t,e,r,{signal:n})=>{for await(let[i]of Wut(t,"unpipe",{signal:n}))e.has(i)&&i.emit(r)},CY=t=>{if(typeof t?.pipe!="function")throw new TypeError(`Expected a readable stream, got: \`${typeof t}\`.`)},elt=async({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,onFinished:s,unpipeEvent:o})=>{WD(t,Wwe);let a=new AbortController;try{await Promise.race([tlt(s,e,a),rlt({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:a}),nlt({stream:e,streams:r,ended:n,aborted:i,unpipeEvent:o,controller:a})])}finally{a.abort(),WD(t,-Wwe)}r.size>0&&r.size===n.size+i.size&&(n.size===0&&i.size>0?kY(t):ilt(t))},tlt=async(t,e,{signal:r})=>{try{await t,r.aborted||kY(e)}catch(n){r.aborted||Ywe(e,n)}},rlt=async({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:{signal:s}})=>{try{await Kwe(e,{signal:s,cleanup:!0,readable:!0,writable:!1}),r.has(e)&&n.add(e)}catch(o){if(s.aborted||!r.has(e))return;Zwe(o)?i.add(e):Qwe(t,o)}},nlt=async({stream:t,streams:e,ended:r,aborted:n,unpipeEvent:i,controller:{signal:s}})=>{if(await Gwe(t,i,{signal:s}),!t.readable)return Gwe(s,"abort",{signal:s});e.delete(t),r.delete(t),n.delete(t)},ilt=t=>{t.writable&&t.end()},Ywe=(t,e)=>{Zwe(e)?kY(t):Qwe(t,e)},Zwe=t=>t?.code==="ERR_STREAM_PREMATURE_CLOSE",kY=t=>{(t.readable||t.writable)&&t.destroy()},Qwe=(t,e)=>{t.destroyed||(t.once("error",slt),t.destroy(e))},slt=()=>{},WD=(t,e)=>{let r=t.getMaxListeners();r!==0&&r!==Number.POSITIVE_INFINITY&&t.setMaxListeners(r+e)},Hwe=2,Wwe=1;import{finished as Jwe}from"stream/promises";var U_=(t,e)=>{t.pipe(e),olt(t,e),alt(t,e)},olt=async(t,e)=>{if(!(Go(t)||Go(e))){try{await Jwe(t,{cleanup:!0,readable:!0,writable:!1})}catch{}NY(e)}},NY=t=>{t.writable&&t.end()},alt=async(t,e)=>{if(!(Go(t)||Go(e))){try{await Jwe(e,{cleanup:!0,readable:!1,writable:!0})}catch{}DY(t)}},DY=t=>{t.readable&&t.destroy()};var Xwe=(t,e,r)=>{let n=new Map;for(let[i,{stdioItems:s,direction:o}]of Object.entries(e)){for(let{stream:a}of s.filter(({type:c})=>$s.has(c)))clt(t,a,o,i);for(let{stream:a}of s.filter(({type:c})=>!$s.has(c)))llt({subprocess:t,stream:a,direction:o,fdNumber:i,pipeGroups:n,controller:r})}for(let[i,s]of n.entries()){let o=s.length===1?s[0]:Tp(s);U_(o,i)}},clt=(t,e,r,n)=>{r==="output"?U_(t.stdio[n],e):U_(e,t.stdio[n]);let i=ult[n];i!==void 0&&(t[i]=e),t.stdio[n]=e},ult=["stdin","stdout","stderr"],llt=({subprocess:t,stream:e,direction:r,fdNumber:n,pipeGroups:i,controller:s})=>{if(e===void 0)return;dlt(e,s);let[o,a]=r==="output"?[e,t.stdio[n]]:[t.stdio[n],e],c=i.get(o)??[];i.set(o,[...c,a])},dlt=(t,{signal:e})=>{Go(t)&&vp(t,flt,e)},flt=2;import{addAbortListener as mlt}from"events";var Ap=[];Ap.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Ap.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Ap.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var KD=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",MY=Symbol.for("signal-exit emitter"),$Y=globalThis,plt=Object.defineProperty.bind(Object),LY=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if($Y[MY])return $Y[MY];plt($Y,MY,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let s of this.listeners[e])i=s(r,n)===!0||i;return e==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},YD=class{},hlt=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),UY=class extends YD{onExit(){return()=>{}}load(){}unload(){}},FY=class extends YD{#e=zY.platform==="win32"?"SIGINT":"SIGHUP";#r=new LY;#t;#n;#s;#i={};#o=!1;constructor(e){super(),this.#t=e,this.#i={};for(let r of Ap)this.#i[r]=()=>{let n=this.#t.listeners(r),{count:i}=this.#r,s=e;if(typeof s.__signal_exit_emitter__=="object"&&typeof s.__signal_exit_emitter__.count=="number"&&(i+=s.__signal_exit_emitter__.count),n.length===i){this.unload();let o=this.#r.emit("exit",null,r),a=r==="SIGHUP"?this.#e:r;o||e.kill(e.pid,a)}};this.#s=e.reallyExit,this.#n=e.emit}onExit(e,r){if(!KD(this.#t))return()=>{};this.#o===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#r.on(n,e),()=>{this.#r.removeListener(n,e),this.#r.listeners.exit.length===0&&this.#r.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#r.count+=1;for(let e of Ap)try{let r=this.#i[e];r&&this.#t.on(e,r)}catch{}this.#t.emit=(e,...r)=>this.#c(e,...r),this.#t.reallyExit=e=>this.#a(e)}}unload(){this.#o&&(this.#o=!1,Ap.forEach(e=>{let r=this.#i[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#t.removeListener(e,r)}catch{}}),this.#t.emit=this.#n,this.#t.reallyExit=this.#s,this.#r.count-=1)}#a(e){return KD(this.#t)?(this.#t.exitCode=e||0,this.#r.emit("exit",this.#t.exitCode,null),this.#s.call(this.#t,this.#t.exitCode)):0}#c(e,...r){let n=this.#n;if(e==="exit"&&KD(this.#t)){typeof r[0]=="number"&&(this.#t.exitCode=r[0]);let i=n.call(this.#t,e,...r);return this.#r.emit("exit",this.#t.exitCode,null),i}else return n.call(this.#t,e,...r)}},zY=globalThis.process,{onExit:eTe,load:Bir,unload:Vir}=hlt(KD(zY)?new FY(zY):new UY);var tTe=(t,{cleanup:e,detached:r},{signal:n})=>{if(!e||r)return;let i=eTe(()=>{t.kill()});mlt(n,()=>{i()})};var nTe=({source:t,sourcePromise:e,boundOptions:r,createNested:n},...i)=>{let s=oD(),{destination:o,destinationStream:a,destinationError:c,from:u,unpipeSignal:l}=glt(r,n,i),{sourceStream:d,sourceError:f}=ylt(t,u),{options:p,fileDescriptors:h}=Wa.get(t);return{sourcePromise:e,sourceStream:d,sourceOptions:p,sourceError:f,destination:o,destinationStream:a,destinationError:c,unpipeSignal:l,fileDescriptors:h,startTime:s}},glt=(t,e,r)=>{try{let{destination:n,pipeOptions:{from:i,to:s,unpipeSignal:o}={}}=_lt(t,e,...r),a=gD(n,s);return{destination:n,destinationStream:a,from:i,unpipeSignal:o}}catch(n){return{destinationError:n}}},_lt=(t,e,r,...n)=>{if(Array.isArray(r))return{destination:e(rTe,t)(r,...n),pipeOptions:t};if(typeof r=="string"||r instanceof URL||IK(r)){if(Object.keys(t).length>0)throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');let[i,s,o]=ZN(r,...n);return{destination:e(rTe)(i,s,o),pipeOptions:o}}if(Wa.has(r)){if(Object.keys(t).length>0)throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");return{destination:r,pipeOptions:n[0]}}throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${r}`)},rTe=({options:t})=>({options:{...t,stdin:"pipe",piped:!0}}),ylt=(t,e)=>{try{return{sourceStream:C_(t,e)}}catch(r){return{sourceError:r}}};var sTe=({sourceStream:t,sourceError:e,destinationStream:r,destinationError:n,fileDescriptors:i,sourceOptions:s,startTime:o})=>{let a=Slt({sourceStream:t,sourceError:e,destinationStream:r,destinationError:n});if(a!==void 0)throw jY({error:a,fileDescriptors:i,sourceOptions:s,startTime:o})},Slt=({sourceStream:t,sourceError:e,destinationStream:r,destinationError:n})=>{if(e!==void 0&&n!==void 0)return n;if(n!==void 0)return DY(t),n;if(e!==void 0)return NY(r),e},jY=({error:t,fileDescriptors:e,sourceOptions:r,startTime:n})=>M_({error:t,command:iTe,escapedCommand:iTe,fileDescriptors:e,options:r,startTime:n,isSync:!1}),iTe="source.pipe(destination)";var oTe=async t=>{let[{status:e,reason:r,value:n=r},{status:i,reason:s,value:o=s}]=await t;if(o.pipedFrom.includes(n)||o.pipedFrom.push(n),i==="rejected")throw o;if(e==="rejected")throw n;return o};import{finished as vlt}from"stream/promises";var aTe=(t,e,r)=>{let n=ZD.has(e)?blt(t,e):Elt(t,e);return vp(t,Tlt,r.signal),vp(e,Alt,r.signal),wlt(e),n},Elt=(t,e)=>{let r=Tp([t]);return U_(r,e),ZD.set(e,r),r},blt=(t,e)=>{let r=ZD.get(e);return r.add(t),r},wlt=async t=>{try{await vlt(t,{cleanup:!0,readable:!1,writable:!0})}catch{}ZD.delete(t)},ZD=new WeakMap,Tlt=2,Alt=1;import{aborted as Rlt}from"util";var cTe=(t,e)=>t===void 0?[]:[xlt(t,e)],xlt=async(t,{sourceStream:e,mergedStream:r,fileDescriptors:n,sourceOptions:i,startTime:s})=>{await Rlt(t,e),await r.remove(e);let o=new Error("Pipe canceled by `unpipeSignal` option.");throw jY({error:o,fileDescriptors:n,sourceOptions:i,startTime:s})};var QD=(t,...e)=>{if(Sr(e[0]))return QD.bind(void 0,{...t,boundOptions:{...t.boundOptions,...e[0]}});let{destination:r,...n}=nTe(t,...e),i=Olt({...n,destination:r});return i.pipe=QD.bind(void 0,{...t,source:r,sourcePromise:i,boundOptions:{}}),i},Olt=async({sourcePromise:t,sourceStream:e,sourceOptions:r,sourceError:n,destination:i,destinationStream:s,destinationError:o,unpipeSignal:a,fileDescriptors:c,startTime:u})=>{let l=Ilt(t,i);sTe({sourceStream:e,sourceError:n,destinationStream:s,destinationError:o,fileDescriptors:c,sourceOptions:r,startTime:u});let d=new AbortController;try{let f=aTe(e,s,d);return await Promise.race([oTe(l),...cTe(a,{sourceStream:e,mergedStream:f,sourceOptions:r,fileDescriptors:c,startTime:u})])}finally{d.abort()}},Ilt=(t,e)=>Promise.allSettled([t,e]);import{setImmediate as $lt}from"timers/promises";import{on as Plt}from"events";import{getDefaultHighWaterMark as Clt}from"stream";var JD=({subprocessStdout:t,subprocess:e,binary:r,shouldEncode:n,encoding:i,preserveNewlines:s})=>{let o=new AbortController;return klt(e,o),lTe({stream:t,controller:o,binary:r,shouldEncode:!t.readableObjectMode&&n,encoding:i,shouldSplit:!t.readableObjectMode,preserveNewlines:s})},klt=async(t,e)=>{try{await t}catch{}finally{e.abort()}},qY=({stream:t,onStreamEnd:e,lines:r,encoding:n,stripFinalNewline:i,allMixed:s})=>{let o=new AbortController;Nlt(e,o,t);let a=t.readableObjectMode&&!s;return lTe({stream:t,controller:o,binary:n==="buffer",shouldEncode:!a,encoding:n,shouldSplit:!a&&r,preserveNewlines:!i})},Nlt=async(t,e,r)=>{try{await t}catch{r.destroy()}finally{e.abort()}},lTe=({stream:t,controller:e,binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o})=>{let a=Plt(t,"data",{signal:e.signal,highWaterMark:uTe,highWatermark:uTe});return Dlt({onStdoutChunk:a,controller:e,binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o})},BY=Clt(!0),uTe=BY,Dlt=async function*({onStdoutChunk:t,controller:e,binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o}){let a=Mlt({binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o});try{for await(let[c]of t)yield*wp(c,a,0)}catch(c){if(!e.signal.aborted)throw c}finally{yield*UT(a)}},Mlt=({binary:t,shouldEncode:e,encoding:r,shouldSplit:n,preserveNewlines:i})=>[qD(t,r,!e),jD(t,i,!n,{})].filter(Boolean);var dTe=async({stream:t,onStreamEnd:e,fdNumber:r,encoding:n,buffer:i,maxBuffer:s,lines:o,allMixed:a,stripFinalNewline:c,verboseInfo:u,streamInfo:l})=>{let d=Llt({stream:t,onStreamEnd:e,fdNumber:r,encoding:n,allMixed:a,verboseInfo:u,streamInfo:l});if(!i){await Promise.all([Ult(t),d]);return}let f=vY(c,r),p=qY({stream:t,onStreamEnd:e,lines:o,encoding:n,stripFinalNewline:f,allMixed:a}),[h]=await Promise.all([Flt({stream:t,iterable:p,fdNumber:r,encoding:n,maxBuffer:s,lines:o}),d]);return h},Llt=async({stream:t,onStreamEnd:e,fdNumber:r,encoding:n,allMixed:i,verboseInfo:s,streamInfo:{fileDescriptors:o}})=>{if(!GD({stdioItems:o[r]?.stdioItems,encoding:n,verboseInfo:s,fdNumber:r}))return;let a=qY({stream:t,onStreamEnd:e,lines:!0,encoding:n,stripFinalNewline:!0,allMixed:i});await bwe(a,t,r,s)},Ult=async t=>{await $lt(),t.readableFlowing===null&&t.resume()},Flt=async({stream:t,stream:{readableObjectMode:e},iterable:r,fdNumber:n,encoding:i,maxBuffer:s,lines:o})=>{try{return e||o?await kD(r,{maxBuffer:s}):i==="buffer"?new Uint8Array(await ND(r,{maxBuffer:s})):await D_(r,{maxBuffer:s})}catch(a){return fTe(bbe({error:a,stream:t,readableObjectMode:e,lines:o,encoding:i,fdNumber:n}))}},VY=async t=>{try{return await t}catch(e){return fTe(e)}},fTe=({bufferedData:t})=>USe(t)?new Uint8Array(t):t;import{finished as zlt}from"stream/promises";var qT=async(t,e,r,{isSameDirection:n,stopOnExit:i=!1}={})=>{let s=jlt(t,r),o=new AbortController;try{await Promise.race([...i?[r.exitPromise]:[],zlt(t,{cleanup:!0,signal:o.signal})])}catch(a){s.stdinCleanedUp||Vlt(a,e,r,n)}finally{o.abort()}},jlt=(t,{originalStreams:[e],subprocess:r})=>{let n={stdinCleanedUp:!1};return t===e&&qlt(t,r,n),n},qlt=(t,e,r)=>{let{_destroy:n}=t;t._destroy=(...i)=>{Blt(e,r),n.call(t,...i)}},Blt=({exitCode:t,signalCode:e},r)=>{(t!==null||e!==null)&&(r.stdinCleanedUp=!0)},Vlt=(t,e,r,n)=>{if(!Glt(t,e,r,n))throw t},Glt=(t,e,r,n=!0)=>r.propagating?pTe(t)||XD(t):(r.propagating=!0,GY(r,e)===n?pTe(t):XD(t)),GY=({fileDescriptors:t},e)=>e!=="all"&&t[e].direction==="input",XD=t=>t?.code==="ERR_STREAM_PREMATURE_CLOSE",pTe=t=>t?.code==="EPIPE";var hTe=({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:s,verboseInfo:o,streamInfo:a})=>t.stdio.map((c,u)=>HY({stream:c,fdNumber:u,encoding:e,buffer:r[u],maxBuffer:n[u],lines:i[u],allMixed:!1,stripFinalNewline:s,verboseInfo:o,streamInfo:a})),HY=async({stream:t,fdNumber:e,encoding:r,buffer:n,maxBuffer:i,lines:s,allMixed:o,stripFinalNewline:a,verboseInfo:c,streamInfo:u})=>{if(!t)return;let l=qT(t,e,u);if(GY(u,e)){await l;return}let[d]=await Promise.all([dTe({stream:t,onStreamEnd:l,fdNumber:e,encoding:r,buffer:n,maxBuffer:i,lines:s,allMixed:o,stripFinalNewline:a,verboseInfo:c,streamInfo:u}),l]);return d};var mTe=({stdout:t,stderr:e},{all:r})=>r&&(t||e)?Tp([t,e].filter(Boolean)):void 0,gTe=({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:s,verboseInfo:o,streamInfo:a})=>HY({...Hlt(t,r),fdNumber:"all",encoding:e,maxBuffer:n[1]+n[2],lines:i[1]||i[2],allMixed:Wlt(t),stripFinalNewline:s,verboseInfo:o,streamInfo:a}),Hlt=({stdout:t,stderr:e,all:r},[,n,i])=>{let s=n||i;return s?n?i?{stream:r,buffer:s}:{stream:t,buffer:s}:{stream:e,buffer:s}:{stream:r,buffer:s}},Wlt=({all:t,stdout:e,stderr:r})=>t&&e&&r&&e.readableObjectMode!==r.readableObjectMode;import{once as Klt}from"events";var _Te=t=>R_(t,"ipc"),yTe=(t,e)=>{let r=sD(t);Ga({type:"ipc",verboseMessage:r,fdNumber:"ipc",verboseInfo:e})};var STe=async({subprocess:t,buffer:e,maxBuffer:r,ipc:n,ipcOutput:i,verboseInfo:s})=>{if(!n)return i;let o=_Te(s),a=au(e,"ipc"),c=au(r,"ipc");for await(let u of IY({anyProcess:t,channel:t.channel,isSubprocess:!1,ipc:n,shouldAwait:!1,reference:!0}))a&&(wbe(t,i,c),i.push(u)),o&&yTe(u,s);return i},vTe=async(t,e)=>(await Promise.allSettled([t]),e);var ETe=async({subprocess:t,options:{encoding:e,buffer:r,maxBuffer:n,lines:i,timeoutDuration:s,cancelSignal:o,gracefulCancel:a,forceKillAfterDelay:c,stripFinalNewline:u,ipc:l,ipcInput:d},context:f,verboseInfo:p,fileDescriptors:h,originalStreams:m,onInternalError:_,controller:S})=>{let b=xwe(t,f),R={originalStreams:m,fileDescriptors:h,subprocess:t,exitPromise:b,propagating:!1},y=hTe({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:u,verboseInfo:p,streamInfo:R}),v=gTe({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:u,verboseInfo:p,streamInfo:R}),T=[],O=STe({subprocess:t,buffer:r,maxBuffer:n,ipc:l,ipcOutput:T,verboseInfo:p}),C=Ylt(m,t,R),I=Zlt(h,R);try{return await Promise.race([Promise.all([{},Iwe(b),Promise.all(y),v,O,tbe(t,d),...C,...I]),_,Qlt(t,S),...ZEe(t,s,f,S),..._Ee({subprocess:t,cancelSignal:o,gracefulCancel:a,context:f,controller:S}),...KEe({subprocess:t,cancelSignal:o,gracefulCancel:a,forceKillAfterDelay:c,context:f,controller:S})])}catch(k){return f.terminationReason??="other",Promise.all([{error:k},b,Promise.all(y.map(w=>VY(w))),VY(v),vTe(O,T),Promise.allSettled(C),Promise.allSettled(I)])}},Ylt=(t,e,r)=>t.map((n,i)=>n===e.stdio[i]?void 0:qT(n,i,r)),Zlt=(t,e)=>t.flatMap(({stdioItems:r},n)=>r.filter(({value:i,stream:s=i})=>Ko(s,{checkOpen:!1})&&!Go(s)).map(({type:i,value:s,stream:o=s})=>qT(o,n,e,{isSameDirection:$s.has(i),stopOnExit:i==="native"}))),Qlt=async(t,{signal:e})=>{let[r]=await Klt(t,"error",{signal:e});throw r};var bTe=()=>({readableDestroy:new WeakMap,writableFinal:new WeakMap,writableDestroy:new WeakMap}),BT=(t,e,r)=>{let n=t[r];n.has(e)||n.set(e,[]);let i=n.get(e),s=Ha();return i.push(s),{resolve:s.resolve.bind(s),promises:i}},F_=async({resolve:t,promises:e},r)=>{t();let[n]=await Promise.race([Promise.allSettled([!0,r]),Promise.all([!1,...e])]);return!n};import{Readable as Jlt}from"stream";import{callbackify as Xlt}from"util";import{finished as wTe}from"stream/promises";var WY=async t=>{if(t!==void 0)try{await KY(t)}catch{}},TTe=async t=>{if(t!==void 0)try{await YY(t)}catch{}},KY=async t=>{await wTe(t,{cleanup:!0,readable:!1,writable:!0})},YY=async t=>{await wTe(t,{cleanup:!0,readable:!0,writable:!1})},eM=async(t,e)=>{if(await t,e)throw e},tM=(t,e,r)=>{r&&!XD(r)?t.destroy(r):e&&t.destroy()};var ATe=({subprocess:t,concurrentStreams:e,encoding:r},{from:n,binary:i=!0,preserveNewlines:s=!0}={})=>{let o=i||es.has(r),{subprocessStdout:a,waitReadableDestroy:c}=ZY(t,n,e),{readableEncoding:u,readableObjectMode:l,readableHighWaterMark:d}=QY(a,o),{read:f,onStdoutDataDone:p}=JY({subprocessStdout:a,subprocess:t,binary:o,encoding:r,preserveNewlines:s}),h=new Jlt({read:f,destroy:Xlt(e9.bind(void 0,{subprocessStdout:a,subprocess:t,waitReadableDestroy:c})),highWaterMark:d,objectMode:l,encoding:u});return XY({subprocessStdout:a,onStdoutDataDone:p,readable:h,subprocess:t}),h},ZY=(t,e,r)=>{let n=C_(t,e),i=BT(r,n,"readableDestroy");return{subprocessStdout:n,waitReadableDestroy:i}},QY=({readableEncoding:t,readableObjectMode:e,readableHighWaterMark:r},n)=>n?{readableEncoding:t,readableObjectMode:e,readableHighWaterMark:r}:{readableEncoding:t,readableObjectMode:!0,readableHighWaterMark:BY},JY=({subprocessStdout:t,subprocess:e,binary:r,encoding:n,preserveNewlines:i})=>{let s=Ha(),o=JD({subprocessStdout:t,subprocess:e,binary:r,shouldEncode:!r,encoding:n,preserveNewlines:i});return{read(){edt(this,o,s)},onStdoutDataDone:s}},edt=async(t,e,r)=>{try{let{value:n,done:i}=await e.next();i?r.resolve():t.push(n)}catch{}},XY=async({subprocessStdout:t,onStdoutDataDone:e,readable:r,subprocess:n,subprocessStdin:i})=>{try{await YY(t),await n,await WY(i),await e,r.readable&&r.push(null)}catch(s){await WY(i),RTe(r,s)}},e9=async({subprocessStdout:t,subprocess:e,waitReadableDestroy:r},n)=>{await F_(r,e)&&(RTe(t,n),await eM(e,n))},RTe=(t,e)=>{tM(t,t.readable,e)};import{Writable as tdt}from"stream";import{callbackify as xTe}from"util";var OTe=({subprocess:t,concurrentStreams:e},{to:r}={})=>{let{subprocessStdin:n,waitWritableFinal:i,waitWritableDestroy:s}=t9(t,r,e),o=new tdt({...r9(n,t,i),destroy:xTe(i9.bind(void 0,{subprocessStdin:n,subprocess:t,waitWritableFinal:i,waitWritableDestroy:s})),highWaterMark:n.writableHighWaterMark,objectMode:n.writableObjectMode});return n9(n,o),o},t9=(t,e,r)=>{let n=gD(t,e),i=BT(r,n,"writableFinal"),s=BT(r,n,"writableDestroy");return{subprocessStdin:n,waitWritableFinal:i,waitWritableDestroy:s}},r9=(t,e,r)=>({write:rdt.bind(void 0,t),final:xTe(ndt.bind(void 0,t,e,r))}),rdt=(t,e,r,n)=>{t.write(e,r)?n():t.once("drain",n)},ndt=async(t,e,r)=>{await F_(r,e)&&(t.writable&&t.end(),await e)},n9=async(t,e,r)=>{try{await KY(t),e.writable&&e.end()}catch(n){await TTe(r),ITe(e,n)}},i9=async({subprocessStdin:t,subprocess:e,waitWritableFinal:r,waitWritableDestroy:n},i)=>{await F_(r,e),await F_(n,e)&&(ITe(t,i),await eM(e,i))},ITe=(t,e)=>{tM(t,t.writable,e)};import{Duplex as idt}from"stream";import{callbackify as sdt}from"util";var PTe=({subprocess:t,concurrentStreams:e,encoding:r},{from:n,to:i,binary:s=!0,preserveNewlines:o=!0}={})=>{let a=s||es.has(r),{subprocessStdout:c,waitReadableDestroy:u}=ZY(t,n,e),{subprocessStdin:l,waitWritableFinal:d,waitWritableDestroy:f}=t9(t,i,e),{readableEncoding:p,readableObjectMode:h,readableHighWaterMark:m}=QY(c,a),{read:_,onStdoutDataDone:S}=JY({subprocessStdout:c,subprocess:t,binary:a,encoding:r,preserveNewlines:o}),b=new idt({read:_,...r9(l,t,d),destroy:sdt(odt.bind(void 0,{subprocessStdout:c,subprocessStdin:l,subprocess:t,waitReadableDestroy:u,waitWritableFinal:d,waitWritableDestroy:f})),readableHighWaterMark:m,writableHighWaterMark:l.writableHighWaterMark,readableObjectMode:h,writableObjectMode:l.writableObjectMode,encoding:p});return XY({subprocessStdout:c,onStdoutDataDone:S,readable:b,subprocess:t,subprocessStdin:l}),n9(l,b,c),b},odt=async({subprocessStdout:t,subprocessStdin:e,subprocess:r,waitReadableDestroy:n,waitWritableFinal:i,waitWritableDestroy:s},o)=>{await Promise.all([e9({subprocessStdout:t,subprocess:r,waitReadableDestroy:n},o),i9({subprocessStdin:e,subprocess:r,waitWritableFinal:i,waitWritableDestroy:s},o)])};var s9=(t,e,{from:r,binary:n=!1,preserveNewlines:i=!1}={})=>{let s=n||es.has(e),o=C_(t,r),a=JD({subprocessStdout:o,subprocess:t,binary:s,shouldEncode:!0,encoding:e,preserveNewlines:i});return adt(a,o,t)},adt=async function*(t,e,r){try{yield*t}finally{e.readable&&e.destroy(),await r}};var CTe=(t,{encoding:e})=>{let r=bTe();t.readable=ATe.bind(void 0,{subprocess:t,concurrentStreams:r,encoding:e}),t.writable=OTe.bind(void 0,{subprocess:t,concurrentStreams:r}),t.duplex=PTe.bind(void 0,{subprocess:t,concurrentStreams:r,encoding:e}),t.iterable=s9.bind(void 0,t,e),t[Symbol.asyncIterator]=s9.bind(void 0,t,e,{})};var kTe=(t,e)=>{for(let[r,n]of udt){let i=n.value.bind(e);Reflect.defineProperty(t,r,{...n,value:i})}},cdt=(async()=>{})().constructor.prototype,udt=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(cdt,t)]);var NTe=(t,e,r,n)=>{let{file:i,commandArguments:s,command:o,escapedCommand:a,startTime:c,verboseInfo:u,options:l,fileDescriptors:d}=fdt(t,e,r),{subprocess:f,promise:p}=hdt({file:i,commandArguments:s,options:l,startTime:c,verboseInfo:u,command:o,escapedCommand:a,fileDescriptors:d});return f.pipe=QD.bind(void 0,{source:f,sourcePromise:p,boundOptions:{},createNested:n}),kTe(f,p),Wa.set(f,{options:l,fileDescriptors:d}),f},fdt=(t,e,r)=>{let{command:n,escapedCommand:i,startTime:s,verboseInfo:o}=aD(t,e,r),{file:a,commandArguments:c,options:u}=xD(t,e,r),l=pdt(u),d=Vwe(l,o);return{file:a,commandArguments:c,command:n,escapedCommand:i,startTime:s,verboseInfo:o,options:l,fileDescriptors:d}},pdt=({timeout:t,signal:e,...r})=>{if(e!==void 0)throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');return{...r,timeoutDuration:t}},hdt=({file:t,commandArguments:e,options:r,startTime:n,verboseInfo:i,command:s,escapedCommand:o,fileDescriptors:a})=>{let c;try{c=ddt(...OD(t,e,r))}catch(h){return zwe({error:h,command:s,escapedCommand:o,fileDescriptors:a,options:r,startTime:n,verboseInfo:i})}let u=new AbortController;ldt(Number.POSITIVE_INFINITY,u.signal);let l=[...c.stdio];Xwe(c,a,u),tTe(c,r,u);let d={},f=Ha();c.kill=mEe.bind(void 0,{kill:c.kill.bind(c),options:r,onInternalError:f,context:d,controller:u}),c.all=mTe(c,r),CTe(c,r),Lwe(c,r);let p=mdt({subprocess:c,options:r,startTime:n,verboseInfo:i,fileDescriptors:a,originalStreams:l,command:s,escapedCommand:o,context:d,onInternalError:f,controller:u});return{subprocess:c,promise:p}},mdt=async({subprocess:t,options:e,startTime:r,verboseInfo:n,fileDescriptors:i,originalStreams:s,command:o,escapedCommand:a,context:c,onInternalError:u,controller:l})=>{let[d,[f,p],h,m,_]=await ETe({subprocess:t,options:e,context:c,verboseInfo:n,fileDescriptors:i,originalStreams:s,onInternalError:u,controller:l});l.abort(),u.resolve();let S=h.map((y,v)=>uu(y,e,v)),b=uu(m,e,"all"),R=gdt({errorInfo:d,exitCode:f,signal:p,stdio:S,all:b,ipcOutput:_,context:c,options:e,command:o,escapedCommand:a,startTime:r});return $_(R,n,e)},gdt=({errorInfo:t,exitCode:e,signal:r,stdio:n,all:i,ipcOutput:s,context:o,options:a,command:c,escapedCommand:u,startTime:l})=>"error"in t?LT({error:t.error,command:c,escapedCommand:u,timedOut:o.terminationReason==="timeout",isCanceled:o.terminationReason==="cancel"||o.terminationReason==="gracefulCancel",isGracefullyCanceled:o.terminationReason==="gracefulCancel",isMaxBuffer:t.error instanceof Ka,isForcefullyTerminated:o.isForcefullyTerminated,exitCode:e,signal:r,stdio:n,all:i,ipcOutput:s,options:a,startTime:l,isSync:!1}):$D({command:c,escapedCommand:u,stdio:n,all:i,ipcOutput:s,options:a,startTime:l});var rM=(t,e)=>{let r=Object.fromEntries(Object.entries(e).map(([n,i])=>[n,_dt(n,t[n],i)]));return{...t,...r}},_dt=(t,e,r)=>ydt.has(t)&&Sr(e)&&Sr(r)?{...e,...r}:r,ydt=new Set(["env",...MK]);var Vl=(t,e,r,n)=>{let i=(o,a,c)=>Vl(o,a,r,c),s=(...o)=>Sdt({mapArguments:t,deepOptions:r,boundOptions:e,setBoundExeca:n,createNested:i},...o);return n!==void 0&&n(s,i,e),s},Sdt=({mapArguments:t,deepOptions:e={},boundOptions:r={},setBoundExeca:n,createNested:i},s,...o)=>{if(Sr(s))return i(t,rM(r,s),n);let{file:a,commandArguments:c,options:u,isSync:l}=vdt({mapArguments:t,firstArgument:s,nextArguments:o,deepOptions:e,boundOptions:r});return l?Cwe(a,c,u):NTe(a,c,u,i)},vdt=({mapArguments:t,firstArgument:e,nextArguments:r,deepOptions:n,boundOptions:i})=>{let s=VSe(e)?GSe(e,r):[e,...r],[o,a,c]=ZN(...s),u=rM(rM(n,i),c),{file:l=o,commandArguments:d=a,options:f=u,isSync:p=!1}=t({file:o,commandArguments:a,options:u});return{file:l,commandArguments:d,options:f,isSync:p}};var DTe=({file:t,commandArguments:e})=>$Te(t,e),MTe=({file:t,commandArguments:e})=>({...$Te(t,e),isSync:!0}),$Te=(t,e)=>{if(e.length>0)throw new TypeError(`The command and its arguments must be passed as a single string: ${t} ${e}.`);let[r,...n]=Edt(t);return{file:r,commandArguments:n}},Edt=t=>{if(typeof t!="string")throw new TypeError(`The command must be a string: ${String(t)}.`);let e=t.trim();if(e==="")return[];let r=[];for(let n of e.split(bdt)){let i=r.at(-1);i&&i.endsWith("\\")?r[r.length-1]=`${i.slice(0,-1)} ${n}`:r.push(n)}return r},bdt=/ +/g;var LTe=(t,e,r)=>{t.sync=e(wdt,r),t.s=t.sync},UTe=({options:t})=>FTe(t),wdt=({options:t})=>({...FTe(t),isSync:!0}),FTe=t=>({options:{...Tdt(t),...t}}),Tdt=({input:t,inputFile:e,stdio:r})=>t===void 0&&e===void 0&&r===void 0?{stdin:"inherit"}:{},zTe={preferLocal:!0};var jTe=Vl(()=>({})),Mar=Vl(()=>({isSync:!0})),qTe=Vl(DTe),$ar=Vl(MTe),Lar=Vl(JEe),Uar=Vl(UTe,{},zTe,LTe),{sendMessage:Far,getOneMessage:zar,getEachMessage:jar,getCancelSignal:qar}=Uwe();var BTe=!1,VTe,Adt=t=>{VTe??=t},GTe=t=>{BTe=!0,Adt(t)},Mn=()=>BTe,lu=()=>VTe,HTe=t=>{switch(t){case"SIGTERM":case"SIGINT":return t;case void 0:return"interrupted";default:return}};var VT=null,WTe=t=>(VT&&VT.destroy(),VT=new Ls({totalAllowedTime:t}),VT),KTe=()=>VT;var Ls=class{constructor({totalAllowedTime:e}){this.withStageTimer=async(e,r,n,{interruptible:i=!0}={})=>{if(this.isTimeExpired())throw new Error(`${e} stage did not complete in the allowed time. Time has already expired.`);if(i&&Mn())throw new Error(`Aborting ${e} stage \u2014 shutting down`);let s=this.onTimesUp(()=>{throw new Error(`${e} stage did not complete in the allowed time.`)}),o=null,a=null;n!==void 0&&(a=new Promise((l,d)=>{o=setTimeout(()=>{d(new Error(`${e} stage exceeded its maximum duration of ${n}ms`))},n)}));let c=Date.now(),u="success";try{return await UC({stage:e},async()=>a?await Promise.race([r(),a]):await r())}catch(l){throw u="failure",l}finally{K.timing("stage.duration",Date.now()-c,{stage:e,outcome:u}),s(),o&&clearTimeout(o)}};this.startTime=Date.now(),this.totalAllowedTime=e,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let e=this.getElapsedTime(),r=this.totalAllowedTime-e;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 e=this.subscribers.length-1;e>=0;e--)try{this.subscribers[e]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(e){if(this.subscribers.push(e),this.hasTimedOut)try{e()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(e);r>-1&&this.subscribers.splice(r,1)}}off(e){let r=this.subscribers.indexOf(e);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:e=>e*1e3,minutes:e=>e*60*1e3,hours:e=>e*60*60*1e3}}};var YTe={name:"@netlify/agent-runner-cli",type:"module",version:"1.200.2-bug.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:{prebuild:"rm -rf dist",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:smoke":"node scripts/smoke-dist.js","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:opencode":"vitest run test/integration/opencode.test.ts","test:integration:muse":"vitest run test/integration/muse.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","check:types":"tsc --noEmit",postinstall:"node scripts/postinstall.js"},engines:{node:">=22"},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":"^10.0.1","@netlify/axis":"^1.21.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:"^10.5.0","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.295","@anthropic-ai/sdk":"^0.128.0","@google/gemini-cli":"0.42.0","@modelcontextprotocol/sdk":"^1.29.0","@netlify/cache-utils":"^6.0.5","@netlify/database-proxy":"^0.2.2","@netlify/otel":"^6.0.6","@netlify/ts-cli":"^1.2.0","@openai/codex":"0.162.0","@opentelemetry/api":"^1.9.0","@opentelemetry/exporter-trace-otlp-grpc":"0.218.0",execa:"^9.6.1",fastify:"5.12.5",minimist:"^1.2.8",openai:"7.31.0",zod:"^4.4.3"}};var Idt=xdt(import.meta.url),Pdt=du.dirname(Idt),Cdt=Odt(import.meta.url),z_=re("shell"),o9=new Set,ZTe={preferLocal:!0},_t=(t,e,r)=>{let[n,i]=kdt(e,r),s={...ZTe,...i},o=jTe(t,n,s);JTe(o,s),tAe(o);let a=r?.idleTimeout;return a&&a>0&&eAe(o,a),o},QTe=(t,e)=>{let r={...ZTe,...e},n=qTe(t,r);return JTe(n,r),tAe(n),e?.idleTimeout&&e.idleTimeout>0&&eAe(n,e.idleTimeout),n},kdt=function(t,e){return Array.isArray(t)?[t,e]:typeof t=="object"&&t!==null?[[],t]:[[],void 0]},JTe=(t,e)=>{if(e.stdio!==void 0||e.stdout!==void 0||e.stderr!==void 0||Za.env.NETLIFY_LOCAL_QUIET==="true")return;if(Za.env.NETLIFY_MASK_LOGS!=="false"){t.stdout?.pipe(new Nb).pipe(Za.stdout),t.stderr?.pipe(new Nb).pipe(Za.stderr);return}t.stdout?.pipe(Za.stdout),t.stderr?.pipe(Za.stderr)},a9=(t,e="SIGTERM")=>{try{return t.pid&&!t.killed?(Za.kill(-t.pid,e),z_.log(`Killed process ${t.pid} with signal ${e}`),!0):!1}catch(r){return z_.error("Error killing process:",r),!1}},XTe=t=>a9(t,"SIGKILL"),eAe=(t,e)=>{let r=null,n=()=>{z_.log(`Process ${t.pid} killed due to idle timeout (no output for ${e}ms)`),a9(t,"SIGTERM"),setTimeout(()=>{t.pid&&!t.killed&&(z_.log(`Force killing idle process ${t.pid}`),XTe(t))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,e)};i(),t.stdout?.on("data",i),t.stderr?.on("data",i);let s=()=>{r&&(clearTimeout(r),r=null)};t.on("exit",s),t.on("error",s)},tAe=t=>{o9.add(t);let e=KTe();if(e){let r=e.onTimesUp(()=>{z_.log(`Global timer expired, killing process ${t.pid}`),a9(t,"SIGTERM"),setTimeout(()=>{t.pid&&!t.killed&&(z_.log(`Force killing process ${t.pid} after timeout`),XTe(t))},5e3)});t.on("exit",()=>{o9.delete(t),r()}),t.on("error",()=>{o9.delete(t),r()})}};function iM(t,e){return!!Yo(t,e)}function Yo(t,e){if(!Za.env.NETLIFY_LOCAL_MODE)try{let i=Cdt.resolve(YTe.name),s=du.dirname(i);for(;s!==du.dirname(s);){let o=du.dirname(s);if(du.basename(o)==="node_modules"){let a=du.join(o,".bin",e);if(nM.existsSync(a))return a;break}s=o}}catch(i){console.error("Could not resolve package.json",i)}if(Za.env.NODE_PATH){let i=du.join(Za.env.NODE_PATH,".bin",e);if(nM.existsSync(i))return i}let r=du.join(t,"node_modules",".bin",e);if(nM.existsSync(r))return r;let n=du.join(Pdt,"..","node_modules",".bin",e);if(nM.existsSync(n))return n}var rAe=re("repo"),aAe="runner-diffs-",c9=t=>`${aAe}${t}-`,cAe=async t=>{let e=sM.tmpdir(),r;try{r=await Qo.readdir(e)}catch{return}await Promise.all(r.filter(n=>n.startsWith(aAe)&&!n.startsWith(c9(t))).map(n=>Qo.rm(Zo.join(e,n),{recursive:!0,force:!0}).catch(()=>{})))},nAe=async t=>{let e=Ndt("sha256");for await(let r of Ddt(t))e.update(r);return e.digest("hex")},iAe=async(t,e)=>t.size===e.size&&await nAe(t.path)===await nAe(e.path),uAe=/.. (.+)?\.log$/,Mdt=[uAe],$dt=1,sAe=t=>{let e=t.split(`
|
|
389
|
-
`).reduce((r,n)=>{if(!n)return r;let[i,s,,...o]=n,a=o.join(""),c=i.trim(),u=s.trim();return r[a]?r[a].change=u:r[a]={filePath:a,stage:c,change:u},r},{});return Object.values(e)},Ldt=t=>t instanceof Error&&String(t.stderr??"").includes("No such remote"),Udt=t=>{let e=t instanceof Error?t.message:String(t),r=String(t?.stderr??"").trim();return Ei(r?`${e}: ${r}`:e)},Fdt={stdin:"pipe",stdout:"pipe",stderr:"pipe",stripFinalNewline:!1},oAe=500,GT=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n));this.step=r;this.cause=n}},$n=class{constructor(e=process.cwd()){this.cwd=e}getRoot(){return this.root??=this.run(["rev-parse","--show-toplevel"],{stdout:"pipe"}).then(({stdout:e})=>String(e).trim()),this.root}async restorePausedWork(e){let r="restore";try{let n=await this.restorePausedFiles(e);return r="stage",await this.stageBuildSetup(),await this.unstageFiles(n.changedFiles,{cwd:await this.getRoot()}),{rewrittenFileCount:n.rewrittenFileCount}}catch(n){throw new GT(r,n)}}run(e,r={}){return _t("git",e,{cwd:this.cwd,...r,env:{...r.env,NETLIFY_INTERNAL_GIT:"1"}})}async
|
|
388
|
+
if (condition) { yield value; }`)};import{Buffer as Bct}from"buffer";import{StringDecoder as Vct}from"string_decoder";var qD=(t,e,r)=>{if(r)return;if(t)return{transform:Gct.bind(void 0,new TextEncoder)};let n=new Vct(e);return{transform:Hct.bind(void 0,n),final:Wct.bind(void 0,n)}},Gct=function*(t,e){Bct.isBuffer(e)?yield ou(e):typeof e=="string"?yield t.encode(e):yield e},Hct=function*(t,e){yield zr(e)?t.write(e):e},Wct=function*(t){let e=t.end();e!==""&&(yield e)};import{callbackify as mwe}from"util";var wY=mwe(async(t,e,r,n)=>{e.currentIterable=t(...r);try{for await(let i of e.currentIterable)n.push(i)}finally{delete e.currentIterable}}),BD=async function*(t,e,r){if(r===e.length){yield t;return}let{transform:n=Yct}=e[r];for await(let i of n(t))yield*BD(i,e,r+1)},gwe=async function*(t){for(let[e,{final:r}]of Object.entries(t))yield*Kct(r,Number(e),t)},Kct=async function*(t,e,r){if(t!==void 0)for await(let n of t())yield*BD(n,r,e+1)},_we=mwe(async({currentIterable:t},e)=>{if(t!==void 0){await(e?t.throw(e):t.return());return}if(e)throw e}),Yct=function*(t){yield t};var TY=(t,e,r,n)=>{try{for(let i of t(...e))r.push(i);n()}catch(i){n(i)}},ywe=(t,e)=>[...e.flatMap(r=>[...wp(r,t,0)]),...UT(t)],wp=function*(t,e,r){if(r===e.length){yield t;return}let{transform:n=Qct}=e[r];for(let i of n(t))yield*wp(i,e,r+1)},UT=function*(t){for(let[e,{final:r}]of Object.entries(t))yield*Zct(r,Number(e),t)},Zct=function*(t,e,r){if(t!==void 0)for(let n of t())yield*wp(n,r,e+1)},Qct=function*(t){yield t};var AY=({value:t,value:{transform:e,final:r,writableObjectMode:n,readableObjectMode:i},optionName:s},{encoding:o})=>{let a={},c=vwe(t,o,s),u=bp(e),l=bp(r),d=u?wY.bind(void 0,BD,a):TY.bind(void 0,wp),f=u||l?wY.bind(void 0,gwe,a):TY.bind(void 0,UT),p=u||l?_we.bind(void 0,a):void 0;return{stream:new Jct({writableObjectMode:n,writableHighWaterMark:Swe(n),readableObjectMode:i,readableHighWaterMark:Swe(i),transform(m,_,S){d([m,c,0],this,S)},flush(m){f([c],this,m)},destroy:p})}},VD=(t,e,r,n)=>{let i=e.filter(({type:o})=>o==="generator"),s=n?i.reverse():i;for(let{value:o,optionName:a}of s){let c=vwe(o,r,a);t=ywe(c,t)}return t},vwe=({transform:t,final:e,binary:r,writableObjectMode:n,readableObjectMode:i,preserveNewlines:s},o,a)=>{let c={};return[{transform:fwe(n,a)},qD(r,o,n),jD(r,s,n,c),{transform:t,final:e},{transform:pwe(i,a)},dwe({binary:r,preserveNewlines:s,readableObjectMode:i,state:c})].filter(Boolean)};var Ewe=(t,e)=>{for(let r of Xct(t))eut(t,r,e)},Xct=t=>new Set(Object.entries(t).filter(([,{direction:e}])=>e==="input").map(([e])=>Number(e))),eut=(t,e,r)=>{let{stdioItems:n}=t[e],i=n.filter(({contents:a})=>a!==void 0);if(i.length===0)return;if(e!==0){let[{type:a,optionName:c}]=i;throw new TypeError(`Only the \`stdin\` option, not \`${c}\`, can be ${Bl[a]} with synchronous methods.`)}let o=i.map(({contents:a})=>a).map(a=>tut(a,n));r.input=OT(o)},tut=(t,e)=>{let r=VD(t,e,"utf8",!0);return rut(r),OT(r)},rut=t=>{let e=t.find(r=>typeof r!="string"&&!zr(r));if(e!==void 0)throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${e}.`)};import{writeFileSync as out,appendFileSync as aut}from"fs";var GD=({stdioItems:t,encoding:e,verboseInfo:r,fdNumber:n})=>n!=="all"&&R_(r,n)&&!es.has(e)&&nut(n)&&(t.some(({type:i,value:s})=>i==="native"&&iut.has(s))||t.every(({type:i})=>$s.has(i))),nut=t=>t===1||t===2,iut=new Set(["pipe","overlapped"]),bwe=async(t,e,r,n)=>{for await(let i of t)sut(e)||Twe(i,r,n)},wwe=(t,e,r)=>{for(let n of t)Twe(n,e,r)},sut=t=>t._readableState.pipes.length>0,Twe=(t,e,r)=>{let n=sD(t);Ga({type:"output",verboseMessage:n,fdNumber:e,verboseInfo:r})};var Awe=({fileDescriptors:t,syncResult:{output:e},options:r,isMaxBuffer:n,verboseInfo:i})=>{if(e===null)return{output:Array.from({length:3})};let s={},o=new Set([]);return{output:e.map((c,u)=>cut({result:c,fileDescriptors:t,fdNumber:u,state:s,outputFiles:o,isMaxBuffer:n,verboseInfo:i},r)),...s}},cut=({result:t,fileDescriptors:e,fdNumber:r,state:n,outputFiles:i,isMaxBuffer:s,verboseInfo:o},{buffer:a,encoding:c,lines:u,stripFinalNewline:l,maxBuffer:d})=>{if(t===null)return;let f=Rbe(t,s,d),p=ou(f),{stdioItems:h,objectMode:m}=e[r],_=uut([p],h,c,n),{serializedResult:S,finalResult:b=S}=lut({chunks:_,objectMode:m,encoding:c,lines:u,stripFinalNewline:l,fdNumber:r});dut({serializedResult:S,fdNumber:r,state:n,verboseInfo:o,encoding:c,stdioItems:h,objectMode:m});let R=a[r]?b:void 0;try{return n.error===void 0&&fut(S,h,i),R}catch(y){return n.error=y,R}},uut=(t,e,r,n)=>{try{return VD(t,e,r,!1)}catch(i){return n.error=i,t}},lut=({chunks:t,objectMode:e,encoding:r,lines:n,stripFinalNewline:i,fdNumber:s})=>{if(e)return{serializedResult:t};if(r==="buffer")return{serializedResult:OT(t)};let o=zSe(t,r);return n[s]?{serializedResult:o,finalResult:bY(o,!i[s],e)}:{serializedResult:o}},dut=({serializedResult:t,fdNumber:e,state:r,verboseInfo:n,encoding:i,stdioItems:s,objectMode:o})=>{if(!GD({stdioItems:s,encoding:i,verboseInfo:n,fdNumber:e}))return;let a=bY(t,!1,o);try{wwe(a,e,n)}catch(c){r.error??=c}},fut=(t,e,r)=>{for(let{path:n,append:i}of e.filter(({type:s})=>FD.has(s))){let s=typeof n=="string"?n:n.toString();i||r.has(s)?aut(n,t):(r.add(s),out(n,t))}};var Rwe=([,t,e],r)=>{if(r.all)return t===void 0?e:e===void 0?t:Array.isArray(t)?Array.isArray(e)?[...t,...e]:[...t,uu(e,r,"all")]:Array.isArray(e)?[uu(t,r,"all"),...e]:zr(t)&&zr(e)?CK([t,e]):`${t}${e}`};import{once as RY}from"events";var xwe=async(t,e)=>{let[r,n]=await put(t);return e.isForcefullyTerminated??=!1,[r,n]},put=async t=>{let[e,r]=await Promise.allSettled([RY(t,"spawn"),RY(t,"exit")]);return e.status==="rejected"?[]:r.status==="rejected"?Owe(t):r.value},Owe=async t=>{try{return await RY(t,"exit")}catch{return Owe(t)}},Iwe=async t=>{let[e,r]=await t;if(!hut(e,r)&&xY(e,r))throw new Ho;return[e,r]},hut=(t,e)=>t===void 0&&e===void 0,xY=(t,e)=>t!==0||e!==null;var Pwe=({error:t,status:e,signal:r,output:n},{maxBuffer:i})=>{let s=mut(t,e,r),o=s?.code==="ETIMEDOUT",a=Abe(s,n,i);return{resultError:s,exitCode:e,signal:r,timedOut:o,isMaxBuffer:a}},mut=(t,e,r)=>t!==void 0?t:xY(e,r)?new Ho:void 0;var Cwe=(t,e,r)=>{let{file:n,commandArguments:i,command:s,escapedCommand:o,startTime:a,verboseInfo:c,options:u,fileDescriptors:l}=_ut(t,e,r),d=vut({file:n,commandArguments:i,options:u,command:s,escapedCommand:o,verboseInfo:c,fileDescriptors:l,startTime:a});return $_(d,c,u)},_ut=(t,e,r)=>{let{command:n,escapedCommand:i,startTime:s,verboseInfo:o}=aD(t,e,r),a=yut(r),{file:c,commandArguments:u,options:l}=xD(t,e,a);Sut(l);let d=awe(l,o);return{file:c,commandArguments:u,command:n,escapedCommand:i,startTime:s,verboseInfo:o,options:l,fileDescriptors:d}},yut=t=>t.node&&!t.ipc?{...t,ipc:!1}:t,Sut=({ipc:t,ipcInput:e,detached:r,cancelSignal:n})=>{e&&HD("ipcInput"),t&&HD("ipc: true"),r&&HD("detached: true"),n&&HD("cancelSignal")},HD=t=>{throw new TypeError(`The "${t}" option cannot be used with synchronous methods.`)},vut=({file:t,commandArguments:e,options:r,command:n,escapedCommand:i,verboseInfo:s,fileDescriptors:o,startTime:a})=>{let c=Eut({file:t,commandArguments:e,options:r,command:n,escapedCommand:i,fileDescriptors:o,startTime:a});if(c.failed)return c;let{resultError:u,exitCode:l,signal:d,timedOut:f,isMaxBuffer:p}=Pwe(c,r),{output:h,error:m=u}=Awe({fileDescriptors:o,syncResult:c,options:r,isMaxBuffer:p,verboseInfo:s}),_=h.map((b,R)=>uu(b,r,R)),S=uu(Rwe(h,r),r,"all");return wut({error:m,exitCode:l,signal:d,timedOut:f,isMaxBuffer:p,stdio:_,all:S,options:r,command:n,escapedCommand:i,startTime:a})},Eut=({file:t,commandArguments:e,options:r,command:n,escapedCommand:i,fileDescriptors:s,startTime:o})=>{try{Ewe(s,r);let a=but(r);return gut(...OD(t,e,a))}catch(a){return M_({error:a,command:n,escapedCommand:i,fileDescriptors:s,options:r,startTime:o,isSync:!0})}},but=({encoding:t,maxBuffer:e,...r})=>({...r,encoding:"buffer",maxBuffer:MD(e)}),wut=({error:t,exitCode:e,signal:r,timedOut:n,isMaxBuffer:i,stdio:s,all:o,options:a,command:c,escapedCommand:u,startTime:l})=>t===void 0?$D({command:c,escapedCommand:u,stdio:s,all:o,ipcOutput:[],options:a,startTime:l}):LT({error:t,command:c,escapedCommand:u,timedOut:n,isCanceled:!1,isGracefullyCanceled:!1,isMaxBuffer:i,isForcefullyTerminated:!1,exitCode:e,signal:r,stdio:s,all:o,ipcOutput:[],options:a,startTime:l,isSync:!0});import{setMaxListeners as ldt}from"events";import{spawn as ddt}from"child_process";import $we from"process";import{once as OY,on as Tut}from"events";var kwe=({anyProcess:t,channel:e,isSubprocess:r,ipc:n},{reference:i=!0,filter:s}={})=>(I_({methodName:"getOneMessage",isSubprocess:r,ipc:n,isConnected:ED(t)}),Aut({anyProcess:t,channel:e,isSubprocess:r,filter:s,reference:i})),Aut=async({anyProcess:t,channel:e,isSubprocess:r,filter:n,reference:i})=>{_D(e,i);let s=ql(t,e,r),o=new AbortController;try{return await Promise.race([Rut(s,n,o),xut(s,r,o),Out(s,r,o)])}catch(a){throw P_(t),a}finally{o.abort(),yD(e,i)}},Rut=async(t,e,{signal:r})=>{if(e===void 0){let[n]=await OY(t,"message",{signal:r});return n}for await(let[n]of Tut(t,"message",{signal:r}))if(e(n))return n},xut=async(t,e,{signal:r})=>{await OY(t,"disconnect",{signal:r}),yEe(e)},Out=async(t,e,{signal:r})=>{let[n]=await OY(t,"strict:error",{signal:r});throw hD(n,e)};import{once as Dwe,on as Iut}from"events";var Mwe=({anyProcess:t,channel:e,isSubprocess:r,ipc:n},{reference:i=!0}={})=>IY({anyProcess:t,channel:e,isSubprocess:r,ipc:n,shouldAwait:!r,reference:i}),IY=({anyProcess:t,channel:e,isSubprocess:r,ipc:n,shouldAwait:i,reference:s})=>{I_({methodName:"getEachMessage",isSubprocess:r,ipc:n,isConnected:ED(t)}),_D(e,s);let o=ql(t,e,r),a=new AbortController,c={};return Put(t,o,a),Cut({ipcEmitter:o,isSubprocess:r,controller:a,state:c}),kut({anyProcess:t,channel:e,ipcEmitter:o,isSubprocess:r,shouldAwait:i,controller:a,state:c,reference:s})},Put=async(t,e,r)=>{try{await Dwe(e,"disconnect",{signal:r.signal}),r.abort()}catch{}},Cut=async({ipcEmitter:t,isSubprocess:e,controller:r,state:n})=>{try{let[i]=await Dwe(t,"strict:error",{signal:r.signal});n.error=hD(i,e),r.abort()}catch{}},kut=async function*({anyProcess:t,channel:e,ipcEmitter:r,isSubprocess:n,shouldAwait:i,controller:s,state:o,reference:a}){try{for await(let[c]of Iut(r,"message",{signal:s.signal}))Nwe(o),yield c}catch{Nwe(o)}finally{s.abort(),yD(e,a),n||P_(t),i&&await t}},Nwe=({error:t})=>{if(t)throw t};var Lwe=(t,{ipc:e})=>{Object.assign(t,Fwe(t,!1,e))},Uwe=()=>{let t=$we,e=!0,r=$we.channel!==void 0;return{...Fwe(t,e,r),getCancelSignal:GEe.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r})}},Fwe=(t,e,r)=>({sendMessage:AD.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r}),getOneMessage:kwe.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r}),getEachMessage:Mwe.bind(void 0,{anyProcess:t,channel:t.channel,isSubprocess:e,ipc:r})});import{ChildProcess as Nut}from"child_process";import{PassThrough as Dut,Readable as Mut,Writable as $ut,Duplex as Lut}from"stream";var zwe=({error:t,command:e,escapedCommand:r,fileDescriptors:n,options:i,startTime:s,verboseInfo:o})=>{SY(n);let a=new Nut;Uut(a,n),Object.assign(a,{readable:Fut,writable:zut,duplex:jut});let c=M_({error:t,command:e,escapedCommand:r,fileDescriptors:n,options:i,startTime:s,isSync:!1}),u=qut(c,o,i);return{subprocess:a,promise:u}},Uut=(t,e)=>{let r=FT(),n=FT(),i=FT(),s=Array.from({length:e.length-3},FT),o=FT(),a=[r,n,i,...s];Object.assign(t,{stdin:r,stdout:n,stderr:i,all:o,stdio:a})},FT=()=>{let t=new Dut;return t.end(),t},Fut=()=>new Mut({read(){}}),zut=()=>new $ut({write(){}}),jut=()=>new Lut({read(){},write(){}}),qut=async(t,e,r)=>$_(t,e,r);import{createReadStream as jwe,createWriteStream as qwe}from"fs";import{Buffer as But}from"buffer";import{Readable as zT,Writable as Vut,Duplex as Gut}from"stream";var Vwe=(t,e)=>zD(Hut,t,e,!1),jT=({type:t,optionName:e})=>{throw new TypeError(`The \`${e}\` option cannot be ${Bl[t]}.`)},Bwe={fileNumber:jT,generator:AY,asyncGenerator:AY,nodeStream:({value:t})=>({stream:t}),webTransform({value:{transform:t,writableObjectMode:e,readableObjectMode:r}}){let n=e||r;return{stream:Gut.fromWeb(t,{objectMode:n})}},duplex:({value:{transform:t}})=>({stream:t}),native(){}},Hut={input:{...Bwe,fileUrl:({value:t})=>({stream:jwe(t)}),filePath:({value:{file:t}})=>({stream:jwe(t)}),webStream:({value:t})=>({stream:zT.fromWeb(t)}),iterable:({value:t})=>({stream:zT.from(t)}),asyncIterable:({value:t})=>({stream:zT.from(t)}),string:({value:t})=>({stream:zT.from(t)}),uint8Array:({value:t})=>({stream:zT.from(But.from(t))})},output:{...Bwe,fileUrl:({value:t})=>({stream:qwe(t)}),filePath:({value:{file:t,append:e}})=>({stream:qwe(t,e?{flags:"a"}:{})}),webStream:({value:t})=>({stream:Vut.fromWeb(t)}),iterable:jT,asyncIterable:jT,string:jT,uint8Array:jT}};import{on as Wut,once as Gwe}from"events";import{PassThrough as Kut,getDefaultHighWaterMark as Yut}from"stream";import{finished as Kwe}from"stream/promises";function Tp(t){if(!Array.isArray(t))throw new TypeError(`Expected an array, got \`${typeof t}\`.`);for(let i of t)CY(i);let e=t.some(({readableObjectMode:i})=>i),r=Zut(t,e),n=new PY({objectMode:e,writableHighWaterMark:r,readableHighWaterMark:r});for(let i of t)n.add(i);return n}var Zut=(t,e)=>{if(t.length===0)return Yut(e);let r=t.filter(({readableObjectMode:n})=>n===e).map(({readableHighWaterMark:n})=>n);return Math.max(...r)},PY=class extends Kut{#e=new Set([]);#r=new Set([]);#t=new Set([]);#n;#s=Symbol("unpipe");#i=new WeakMap;add(e){if(CY(e),this.#e.has(e))return;this.#e.add(e),this.#n??=Qut(this,this.#e,this.#s);let r=elt({passThroughStream:this,stream:e,streams:this.#e,ended:this.#r,aborted:this.#t,onFinished:this.#n,unpipeEvent:this.#s});this.#i.set(e,r),e.pipe(this,{end:!1})}async remove(e){if(CY(e),!this.#e.has(e))return!1;let r=this.#i.get(e);return r===void 0?!1:(this.#i.delete(e),e.unpipe(this),await r,!0)}},Qut=async(t,e,r)=>{WD(t,Hwe);let n=new AbortController;try{await Promise.race([Jut(t,n),Xut(t,e,r,n)])}finally{n.abort(),WD(t,-Hwe)}},Jut=async(t,{signal:e})=>{try{await Kwe(t,{signal:e,cleanup:!0})}catch(r){throw Ywe(t,r),r}},Xut=async(t,e,r,{signal:n})=>{for await(let[i]of Wut(t,"unpipe",{signal:n}))e.has(i)&&i.emit(r)},CY=t=>{if(typeof t?.pipe!="function")throw new TypeError(`Expected a readable stream, got: \`${typeof t}\`.`)},elt=async({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,onFinished:s,unpipeEvent:o})=>{WD(t,Wwe);let a=new AbortController;try{await Promise.race([tlt(s,e,a),rlt({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:a}),nlt({stream:e,streams:r,ended:n,aborted:i,unpipeEvent:o,controller:a})])}finally{a.abort(),WD(t,-Wwe)}r.size>0&&r.size===n.size+i.size&&(n.size===0&&i.size>0?kY(t):ilt(t))},tlt=async(t,e,{signal:r})=>{try{await t,r.aborted||kY(e)}catch(n){r.aborted||Ywe(e,n)}},rlt=async({passThroughStream:t,stream:e,streams:r,ended:n,aborted:i,controller:{signal:s}})=>{try{await Kwe(e,{signal:s,cleanup:!0,readable:!0,writable:!1}),r.has(e)&&n.add(e)}catch(o){if(s.aborted||!r.has(e))return;Zwe(o)?i.add(e):Qwe(t,o)}},nlt=async({stream:t,streams:e,ended:r,aborted:n,unpipeEvent:i,controller:{signal:s}})=>{if(await Gwe(t,i,{signal:s}),!t.readable)return Gwe(s,"abort",{signal:s});e.delete(t),r.delete(t),n.delete(t)},ilt=t=>{t.writable&&t.end()},Ywe=(t,e)=>{Zwe(e)?kY(t):Qwe(t,e)},Zwe=t=>t?.code==="ERR_STREAM_PREMATURE_CLOSE",kY=t=>{(t.readable||t.writable)&&t.destroy()},Qwe=(t,e)=>{t.destroyed||(t.once("error",slt),t.destroy(e))},slt=()=>{},WD=(t,e)=>{let r=t.getMaxListeners();r!==0&&r!==Number.POSITIVE_INFINITY&&t.setMaxListeners(r+e)},Hwe=2,Wwe=1;import{finished as Jwe}from"stream/promises";var U_=(t,e)=>{t.pipe(e),olt(t,e),alt(t,e)},olt=async(t,e)=>{if(!(Go(t)||Go(e))){try{await Jwe(t,{cleanup:!0,readable:!0,writable:!1})}catch{}NY(e)}},NY=t=>{t.writable&&t.end()},alt=async(t,e)=>{if(!(Go(t)||Go(e))){try{await Jwe(e,{cleanup:!0,readable:!1,writable:!0})}catch{}DY(t)}},DY=t=>{t.readable&&t.destroy()};var Xwe=(t,e,r)=>{let n=new Map;for(let[i,{stdioItems:s,direction:o}]of Object.entries(e)){for(let{stream:a}of s.filter(({type:c})=>$s.has(c)))clt(t,a,o,i);for(let{stream:a}of s.filter(({type:c})=>!$s.has(c)))llt({subprocess:t,stream:a,direction:o,fdNumber:i,pipeGroups:n,controller:r})}for(let[i,s]of n.entries()){let o=s.length===1?s[0]:Tp(s);U_(o,i)}},clt=(t,e,r,n)=>{r==="output"?U_(t.stdio[n],e):U_(e,t.stdio[n]);let i=ult[n];i!==void 0&&(t[i]=e),t.stdio[n]=e},ult=["stdin","stdout","stderr"],llt=({subprocess:t,stream:e,direction:r,fdNumber:n,pipeGroups:i,controller:s})=>{if(e===void 0)return;dlt(e,s);let[o,a]=r==="output"?[e,t.stdio[n]]:[t.stdio[n],e],c=i.get(o)??[];i.set(o,[...c,a])},dlt=(t,{signal:e})=>{Go(t)&&vp(t,flt,e)},flt=2;import{addAbortListener as mlt}from"events";var Ap=[];Ap.push("SIGHUP","SIGINT","SIGTERM");process.platform!=="win32"&&Ap.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&Ap.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var KD=t=>!!t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function",MY=Symbol.for("signal-exit emitter"),$Y=globalThis,plt=Object.defineProperty.bind(Object),LY=class{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if($Y[MY])return $Y[MY];plt($Y,MY,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,r){this.listeners[e].push(r)}removeListener(e,r){let n=this.listeners[e],i=n.indexOf(r);i!==-1&&(i===0&&n.length===1?n.length=0:n.splice(i,1))}emit(e,r,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let s of this.listeners[e])i=s(r,n)===!0||i;return e==="exit"&&(i=this.emit("afterExit",r,n)||i),i}},YD=class{},hlt=t=>({onExit(e,r){return t.onExit(e,r)},load(){return t.load()},unload(){return t.unload()}}),UY=class extends YD{onExit(){return()=>{}}load(){}unload(){}},FY=class extends YD{#e=zY.platform==="win32"?"SIGINT":"SIGHUP";#r=new LY;#t;#n;#s;#i={};#o=!1;constructor(e){super(),this.#t=e,this.#i={};for(let r of Ap)this.#i[r]=()=>{let n=this.#t.listeners(r),{count:i}=this.#r,s=e;if(typeof s.__signal_exit_emitter__=="object"&&typeof s.__signal_exit_emitter__.count=="number"&&(i+=s.__signal_exit_emitter__.count),n.length===i){this.unload();let o=this.#r.emit("exit",null,r),a=r==="SIGHUP"?this.#e:r;o||e.kill(e.pid,a)}};this.#s=e.reallyExit,this.#n=e.emit}onExit(e,r){if(!KD(this.#t))return()=>{};this.#o===!1&&this.load();let n=r?.alwaysLast?"afterExit":"exit";return this.#r.on(n,e),()=>{this.#r.removeListener(n,e),this.#r.listeners.exit.length===0&&this.#r.listeners.afterExit.length===0&&this.unload()}}load(){if(!this.#o){this.#o=!0,this.#r.count+=1;for(let e of Ap)try{let r=this.#i[e];r&&this.#t.on(e,r)}catch{}this.#t.emit=(e,...r)=>this.#c(e,...r),this.#t.reallyExit=e=>this.#a(e)}}unload(){this.#o&&(this.#o=!1,Ap.forEach(e=>{let r=this.#i[e];if(!r)throw new Error("Listener not defined for signal: "+e);try{this.#t.removeListener(e,r)}catch{}}),this.#t.emit=this.#n,this.#t.reallyExit=this.#s,this.#r.count-=1)}#a(e){return KD(this.#t)?(this.#t.exitCode=e||0,this.#r.emit("exit",this.#t.exitCode,null),this.#s.call(this.#t,this.#t.exitCode)):0}#c(e,...r){let n=this.#n;if(e==="exit"&&KD(this.#t)){typeof r[0]=="number"&&(this.#t.exitCode=r[0]);let i=n.call(this.#t,e,...r);return this.#r.emit("exit",this.#t.exitCode,null),i}else return n.call(this.#t,e,...r)}},zY=globalThis.process,{onExit:eTe,load:Bir,unload:Vir}=hlt(KD(zY)?new FY(zY):new UY);var tTe=(t,{cleanup:e,detached:r},{signal:n})=>{if(!e||r)return;let i=eTe(()=>{t.kill()});mlt(n,()=>{i()})};var nTe=({source:t,sourcePromise:e,boundOptions:r,createNested:n},...i)=>{let s=oD(),{destination:o,destinationStream:a,destinationError:c,from:u,unpipeSignal:l}=glt(r,n,i),{sourceStream:d,sourceError:f}=ylt(t,u),{options:p,fileDescriptors:h}=Wa.get(t);return{sourcePromise:e,sourceStream:d,sourceOptions:p,sourceError:f,destination:o,destinationStream:a,destinationError:c,unpipeSignal:l,fileDescriptors:h,startTime:s}},glt=(t,e,r)=>{try{let{destination:n,pipeOptions:{from:i,to:s,unpipeSignal:o}={}}=_lt(t,e,...r),a=gD(n,s);return{destination:n,destinationStream:a,from:i,unpipeSignal:o}}catch(n){return{destinationError:n}}},_lt=(t,e,r,...n)=>{if(Array.isArray(r))return{destination:e(rTe,t)(r,...n),pipeOptions:t};if(typeof r=="string"||r instanceof URL||IK(r)){if(Object.keys(t).length>0)throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');let[i,s,o]=ZN(r,...n);return{destination:e(rTe)(i,s,o),pipeOptions:o}}if(Wa.has(r)){if(Object.keys(t).length>0)throw new TypeError("Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).");return{destination:r,pipeOptions:n[0]}}throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${r}`)},rTe=({options:t})=>({options:{...t,stdin:"pipe",piped:!0}}),ylt=(t,e)=>{try{return{sourceStream:C_(t,e)}}catch(r){return{sourceError:r}}};var sTe=({sourceStream:t,sourceError:e,destinationStream:r,destinationError:n,fileDescriptors:i,sourceOptions:s,startTime:o})=>{let a=Slt({sourceStream:t,sourceError:e,destinationStream:r,destinationError:n});if(a!==void 0)throw jY({error:a,fileDescriptors:i,sourceOptions:s,startTime:o})},Slt=({sourceStream:t,sourceError:e,destinationStream:r,destinationError:n})=>{if(e!==void 0&&n!==void 0)return n;if(n!==void 0)return DY(t),n;if(e!==void 0)return NY(r),e},jY=({error:t,fileDescriptors:e,sourceOptions:r,startTime:n})=>M_({error:t,command:iTe,escapedCommand:iTe,fileDescriptors:e,options:r,startTime:n,isSync:!1}),iTe="source.pipe(destination)";var oTe=async t=>{let[{status:e,reason:r,value:n=r},{status:i,reason:s,value:o=s}]=await t;if(o.pipedFrom.includes(n)||o.pipedFrom.push(n),i==="rejected")throw o;if(e==="rejected")throw n;return o};import{finished as vlt}from"stream/promises";var aTe=(t,e,r)=>{let n=ZD.has(e)?blt(t,e):Elt(t,e);return vp(t,Tlt,r.signal),vp(e,Alt,r.signal),wlt(e),n},Elt=(t,e)=>{let r=Tp([t]);return U_(r,e),ZD.set(e,r),r},blt=(t,e)=>{let r=ZD.get(e);return r.add(t),r},wlt=async t=>{try{await vlt(t,{cleanup:!0,readable:!1,writable:!0})}catch{}ZD.delete(t)},ZD=new WeakMap,Tlt=2,Alt=1;import{aborted as Rlt}from"util";var cTe=(t,e)=>t===void 0?[]:[xlt(t,e)],xlt=async(t,{sourceStream:e,mergedStream:r,fileDescriptors:n,sourceOptions:i,startTime:s})=>{await Rlt(t,e),await r.remove(e);let o=new Error("Pipe canceled by `unpipeSignal` option.");throw jY({error:o,fileDescriptors:n,sourceOptions:i,startTime:s})};var QD=(t,...e)=>{if(Sr(e[0]))return QD.bind(void 0,{...t,boundOptions:{...t.boundOptions,...e[0]}});let{destination:r,...n}=nTe(t,...e),i=Olt({...n,destination:r});return i.pipe=QD.bind(void 0,{...t,source:r,sourcePromise:i,boundOptions:{}}),i},Olt=async({sourcePromise:t,sourceStream:e,sourceOptions:r,sourceError:n,destination:i,destinationStream:s,destinationError:o,unpipeSignal:a,fileDescriptors:c,startTime:u})=>{let l=Ilt(t,i);sTe({sourceStream:e,sourceError:n,destinationStream:s,destinationError:o,fileDescriptors:c,sourceOptions:r,startTime:u});let d=new AbortController;try{let f=aTe(e,s,d);return await Promise.race([oTe(l),...cTe(a,{sourceStream:e,mergedStream:f,sourceOptions:r,fileDescriptors:c,startTime:u})])}finally{d.abort()}},Ilt=(t,e)=>Promise.allSettled([t,e]);import{setImmediate as $lt}from"timers/promises";import{on as Plt}from"events";import{getDefaultHighWaterMark as Clt}from"stream";var JD=({subprocessStdout:t,subprocess:e,binary:r,shouldEncode:n,encoding:i,preserveNewlines:s})=>{let o=new AbortController;return klt(e,o),lTe({stream:t,controller:o,binary:r,shouldEncode:!t.readableObjectMode&&n,encoding:i,shouldSplit:!t.readableObjectMode,preserveNewlines:s})},klt=async(t,e)=>{try{await t}catch{}finally{e.abort()}},qY=({stream:t,onStreamEnd:e,lines:r,encoding:n,stripFinalNewline:i,allMixed:s})=>{let o=new AbortController;Nlt(e,o,t);let a=t.readableObjectMode&&!s;return lTe({stream:t,controller:o,binary:n==="buffer",shouldEncode:!a,encoding:n,shouldSplit:!a&&r,preserveNewlines:!i})},Nlt=async(t,e,r)=>{try{await t}catch{r.destroy()}finally{e.abort()}},lTe=({stream:t,controller:e,binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o})=>{let a=Plt(t,"data",{signal:e.signal,highWaterMark:uTe,highWatermark:uTe});return Dlt({onStdoutChunk:a,controller:e,binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o})},BY=Clt(!0),uTe=BY,Dlt=async function*({onStdoutChunk:t,controller:e,binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o}){let a=Mlt({binary:r,shouldEncode:n,encoding:i,shouldSplit:s,preserveNewlines:o});try{for await(let[c]of t)yield*wp(c,a,0)}catch(c){if(!e.signal.aborted)throw c}finally{yield*UT(a)}},Mlt=({binary:t,shouldEncode:e,encoding:r,shouldSplit:n,preserveNewlines:i})=>[qD(t,r,!e),jD(t,i,!n,{})].filter(Boolean);var dTe=async({stream:t,onStreamEnd:e,fdNumber:r,encoding:n,buffer:i,maxBuffer:s,lines:o,allMixed:a,stripFinalNewline:c,verboseInfo:u,streamInfo:l})=>{let d=Llt({stream:t,onStreamEnd:e,fdNumber:r,encoding:n,allMixed:a,verboseInfo:u,streamInfo:l});if(!i){await Promise.all([Ult(t),d]);return}let f=vY(c,r),p=qY({stream:t,onStreamEnd:e,lines:o,encoding:n,stripFinalNewline:f,allMixed:a}),[h]=await Promise.all([Flt({stream:t,iterable:p,fdNumber:r,encoding:n,maxBuffer:s,lines:o}),d]);return h},Llt=async({stream:t,onStreamEnd:e,fdNumber:r,encoding:n,allMixed:i,verboseInfo:s,streamInfo:{fileDescriptors:o}})=>{if(!GD({stdioItems:o[r]?.stdioItems,encoding:n,verboseInfo:s,fdNumber:r}))return;let a=qY({stream:t,onStreamEnd:e,lines:!0,encoding:n,stripFinalNewline:!0,allMixed:i});await bwe(a,t,r,s)},Ult=async t=>{await $lt(),t.readableFlowing===null&&t.resume()},Flt=async({stream:t,stream:{readableObjectMode:e},iterable:r,fdNumber:n,encoding:i,maxBuffer:s,lines:o})=>{try{return e||o?await kD(r,{maxBuffer:s}):i==="buffer"?new Uint8Array(await ND(r,{maxBuffer:s})):await D_(r,{maxBuffer:s})}catch(a){return fTe(bbe({error:a,stream:t,readableObjectMode:e,lines:o,encoding:i,fdNumber:n}))}},VY=async t=>{try{return await t}catch(e){return fTe(e)}},fTe=({bufferedData:t})=>USe(t)?new Uint8Array(t):t;import{finished as zlt}from"stream/promises";var qT=async(t,e,r,{isSameDirection:n,stopOnExit:i=!1}={})=>{let s=jlt(t,r),o=new AbortController;try{await Promise.race([...i?[r.exitPromise]:[],zlt(t,{cleanup:!0,signal:o.signal})])}catch(a){s.stdinCleanedUp||Vlt(a,e,r,n)}finally{o.abort()}},jlt=(t,{originalStreams:[e],subprocess:r})=>{let n={stdinCleanedUp:!1};return t===e&&qlt(t,r,n),n},qlt=(t,e,r)=>{let{_destroy:n}=t;t._destroy=(...i)=>{Blt(e,r),n.call(t,...i)}},Blt=({exitCode:t,signalCode:e},r)=>{(t!==null||e!==null)&&(r.stdinCleanedUp=!0)},Vlt=(t,e,r,n)=>{if(!Glt(t,e,r,n))throw t},Glt=(t,e,r,n=!0)=>r.propagating?pTe(t)||XD(t):(r.propagating=!0,GY(r,e)===n?pTe(t):XD(t)),GY=({fileDescriptors:t},e)=>e!=="all"&&t[e].direction==="input",XD=t=>t?.code==="ERR_STREAM_PREMATURE_CLOSE",pTe=t=>t?.code==="EPIPE";var hTe=({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:s,verboseInfo:o,streamInfo:a})=>t.stdio.map((c,u)=>HY({stream:c,fdNumber:u,encoding:e,buffer:r[u],maxBuffer:n[u],lines:i[u],allMixed:!1,stripFinalNewline:s,verboseInfo:o,streamInfo:a})),HY=async({stream:t,fdNumber:e,encoding:r,buffer:n,maxBuffer:i,lines:s,allMixed:o,stripFinalNewline:a,verboseInfo:c,streamInfo:u})=>{if(!t)return;let l=qT(t,e,u);if(GY(u,e)){await l;return}let[d]=await Promise.all([dTe({stream:t,onStreamEnd:l,fdNumber:e,encoding:r,buffer:n,maxBuffer:i,lines:s,allMixed:o,stripFinalNewline:a,verboseInfo:c,streamInfo:u}),l]);return d};var mTe=({stdout:t,stderr:e},{all:r})=>r&&(t||e)?Tp([t,e].filter(Boolean)):void 0,gTe=({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:s,verboseInfo:o,streamInfo:a})=>HY({...Hlt(t,r),fdNumber:"all",encoding:e,maxBuffer:n[1]+n[2],lines:i[1]||i[2],allMixed:Wlt(t),stripFinalNewline:s,verboseInfo:o,streamInfo:a}),Hlt=({stdout:t,stderr:e,all:r},[,n,i])=>{let s=n||i;return s?n?i?{stream:r,buffer:s}:{stream:t,buffer:s}:{stream:e,buffer:s}:{stream:r,buffer:s}},Wlt=({all:t,stdout:e,stderr:r})=>t&&e&&r&&e.readableObjectMode!==r.readableObjectMode;import{once as Klt}from"events";var _Te=t=>R_(t,"ipc"),yTe=(t,e)=>{let r=sD(t);Ga({type:"ipc",verboseMessage:r,fdNumber:"ipc",verboseInfo:e})};var STe=async({subprocess:t,buffer:e,maxBuffer:r,ipc:n,ipcOutput:i,verboseInfo:s})=>{if(!n)return i;let o=_Te(s),a=au(e,"ipc"),c=au(r,"ipc");for await(let u of IY({anyProcess:t,channel:t.channel,isSubprocess:!1,ipc:n,shouldAwait:!1,reference:!0}))a&&(wbe(t,i,c),i.push(u)),o&&yTe(u,s);return i},vTe=async(t,e)=>(await Promise.allSettled([t]),e);var ETe=async({subprocess:t,options:{encoding:e,buffer:r,maxBuffer:n,lines:i,timeoutDuration:s,cancelSignal:o,gracefulCancel:a,forceKillAfterDelay:c,stripFinalNewline:u,ipc:l,ipcInput:d},context:f,verboseInfo:p,fileDescriptors:h,originalStreams:m,onInternalError:_,controller:S})=>{let b=xwe(t,f),R={originalStreams:m,fileDescriptors:h,subprocess:t,exitPromise:b,propagating:!1},y=hTe({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:u,verboseInfo:p,streamInfo:R}),v=gTe({subprocess:t,encoding:e,buffer:r,maxBuffer:n,lines:i,stripFinalNewline:u,verboseInfo:p,streamInfo:R}),T=[],O=STe({subprocess:t,buffer:r,maxBuffer:n,ipc:l,ipcOutput:T,verboseInfo:p}),C=Ylt(m,t,R),I=Zlt(h,R);try{return await Promise.race([Promise.all([{},Iwe(b),Promise.all(y),v,O,tbe(t,d),...C,...I]),_,Qlt(t,S),...ZEe(t,s,f,S),..._Ee({subprocess:t,cancelSignal:o,gracefulCancel:a,context:f,controller:S}),...KEe({subprocess:t,cancelSignal:o,gracefulCancel:a,forceKillAfterDelay:c,context:f,controller:S})])}catch(k){return f.terminationReason??="other",Promise.all([{error:k},b,Promise.all(y.map(w=>VY(w))),VY(v),vTe(O,T),Promise.allSettled(C),Promise.allSettled(I)])}},Ylt=(t,e,r)=>t.map((n,i)=>n===e.stdio[i]?void 0:qT(n,i,r)),Zlt=(t,e)=>t.flatMap(({stdioItems:r},n)=>r.filter(({value:i,stream:s=i})=>Ko(s,{checkOpen:!1})&&!Go(s)).map(({type:i,value:s,stream:o=s})=>qT(o,n,e,{isSameDirection:$s.has(i),stopOnExit:i==="native"}))),Qlt=async(t,{signal:e})=>{let[r]=await Klt(t,"error",{signal:e});throw r};var bTe=()=>({readableDestroy:new WeakMap,writableFinal:new WeakMap,writableDestroy:new WeakMap}),BT=(t,e,r)=>{let n=t[r];n.has(e)||n.set(e,[]);let i=n.get(e),s=Ha();return i.push(s),{resolve:s.resolve.bind(s),promises:i}},F_=async({resolve:t,promises:e},r)=>{t();let[n]=await Promise.race([Promise.allSettled([!0,r]),Promise.all([!1,...e])]);return!n};import{Readable as Jlt}from"stream";import{callbackify as Xlt}from"util";import{finished as wTe}from"stream/promises";var WY=async t=>{if(t!==void 0)try{await KY(t)}catch{}},TTe=async t=>{if(t!==void 0)try{await YY(t)}catch{}},KY=async t=>{await wTe(t,{cleanup:!0,readable:!1,writable:!0})},YY=async t=>{await wTe(t,{cleanup:!0,readable:!0,writable:!1})},eM=async(t,e)=>{if(await t,e)throw e},tM=(t,e,r)=>{r&&!XD(r)?t.destroy(r):e&&t.destroy()};var ATe=({subprocess:t,concurrentStreams:e,encoding:r},{from:n,binary:i=!0,preserveNewlines:s=!0}={})=>{let o=i||es.has(r),{subprocessStdout:a,waitReadableDestroy:c}=ZY(t,n,e),{readableEncoding:u,readableObjectMode:l,readableHighWaterMark:d}=QY(a,o),{read:f,onStdoutDataDone:p}=JY({subprocessStdout:a,subprocess:t,binary:o,encoding:r,preserveNewlines:s}),h=new Jlt({read:f,destroy:Xlt(e9.bind(void 0,{subprocessStdout:a,subprocess:t,waitReadableDestroy:c})),highWaterMark:d,objectMode:l,encoding:u});return XY({subprocessStdout:a,onStdoutDataDone:p,readable:h,subprocess:t}),h},ZY=(t,e,r)=>{let n=C_(t,e),i=BT(r,n,"readableDestroy");return{subprocessStdout:n,waitReadableDestroy:i}},QY=({readableEncoding:t,readableObjectMode:e,readableHighWaterMark:r},n)=>n?{readableEncoding:t,readableObjectMode:e,readableHighWaterMark:r}:{readableEncoding:t,readableObjectMode:!0,readableHighWaterMark:BY},JY=({subprocessStdout:t,subprocess:e,binary:r,encoding:n,preserveNewlines:i})=>{let s=Ha(),o=JD({subprocessStdout:t,subprocess:e,binary:r,shouldEncode:!r,encoding:n,preserveNewlines:i});return{read(){edt(this,o,s)},onStdoutDataDone:s}},edt=async(t,e,r)=>{try{let{value:n,done:i}=await e.next();i?r.resolve():t.push(n)}catch{}},XY=async({subprocessStdout:t,onStdoutDataDone:e,readable:r,subprocess:n,subprocessStdin:i})=>{try{await YY(t),await n,await WY(i),await e,r.readable&&r.push(null)}catch(s){await WY(i),RTe(r,s)}},e9=async({subprocessStdout:t,subprocess:e,waitReadableDestroy:r},n)=>{await F_(r,e)&&(RTe(t,n),await eM(e,n))},RTe=(t,e)=>{tM(t,t.readable,e)};import{Writable as tdt}from"stream";import{callbackify as xTe}from"util";var OTe=({subprocess:t,concurrentStreams:e},{to:r}={})=>{let{subprocessStdin:n,waitWritableFinal:i,waitWritableDestroy:s}=t9(t,r,e),o=new tdt({...r9(n,t,i),destroy:xTe(i9.bind(void 0,{subprocessStdin:n,subprocess:t,waitWritableFinal:i,waitWritableDestroy:s})),highWaterMark:n.writableHighWaterMark,objectMode:n.writableObjectMode});return n9(n,o),o},t9=(t,e,r)=>{let n=gD(t,e),i=BT(r,n,"writableFinal"),s=BT(r,n,"writableDestroy");return{subprocessStdin:n,waitWritableFinal:i,waitWritableDestroy:s}},r9=(t,e,r)=>({write:rdt.bind(void 0,t),final:xTe(ndt.bind(void 0,t,e,r))}),rdt=(t,e,r,n)=>{t.write(e,r)?n():t.once("drain",n)},ndt=async(t,e,r)=>{await F_(r,e)&&(t.writable&&t.end(),await e)},n9=async(t,e,r)=>{try{await KY(t),e.writable&&e.end()}catch(n){await TTe(r),ITe(e,n)}},i9=async({subprocessStdin:t,subprocess:e,waitWritableFinal:r,waitWritableDestroy:n},i)=>{await F_(r,e),await F_(n,e)&&(ITe(t,i),await eM(e,i))},ITe=(t,e)=>{tM(t,t.writable,e)};import{Duplex as idt}from"stream";import{callbackify as sdt}from"util";var PTe=({subprocess:t,concurrentStreams:e,encoding:r},{from:n,to:i,binary:s=!0,preserveNewlines:o=!0}={})=>{let a=s||es.has(r),{subprocessStdout:c,waitReadableDestroy:u}=ZY(t,n,e),{subprocessStdin:l,waitWritableFinal:d,waitWritableDestroy:f}=t9(t,i,e),{readableEncoding:p,readableObjectMode:h,readableHighWaterMark:m}=QY(c,a),{read:_,onStdoutDataDone:S}=JY({subprocessStdout:c,subprocess:t,binary:a,encoding:r,preserveNewlines:o}),b=new idt({read:_,...r9(l,t,d),destroy:sdt(odt.bind(void 0,{subprocessStdout:c,subprocessStdin:l,subprocess:t,waitReadableDestroy:u,waitWritableFinal:d,waitWritableDestroy:f})),readableHighWaterMark:m,writableHighWaterMark:l.writableHighWaterMark,readableObjectMode:h,writableObjectMode:l.writableObjectMode,encoding:p});return XY({subprocessStdout:c,onStdoutDataDone:S,readable:b,subprocess:t,subprocessStdin:l}),n9(l,b,c),b},odt=async({subprocessStdout:t,subprocessStdin:e,subprocess:r,waitReadableDestroy:n,waitWritableFinal:i,waitWritableDestroy:s},o)=>{await Promise.all([e9({subprocessStdout:t,subprocess:r,waitReadableDestroy:n},o),i9({subprocessStdin:e,subprocess:r,waitWritableFinal:i,waitWritableDestroy:s},o)])};var s9=(t,e,{from:r,binary:n=!1,preserveNewlines:i=!1}={})=>{let s=n||es.has(e),o=C_(t,r),a=JD({subprocessStdout:o,subprocess:t,binary:s,shouldEncode:!0,encoding:e,preserveNewlines:i});return adt(a,o,t)},adt=async function*(t,e,r){try{yield*t}finally{e.readable&&e.destroy(),await r}};var CTe=(t,{encoding:e})=>{let r=bTe();t.readable=ATe.bind(void 0,{subprocess:t,concurrentStreams:r,encoding:e}),t.writable=OTe.bind(void 0,{subprocess:t,concurrentStreams:r}),t.duplex=PTe.bind(void 0,{subprocess:t,concurrentStreams:r,encoding:e}),t.iterable=s9.bind(void 0,t,e),t[Symbol.asyncIterator]=s9.bind(void 0,t,e,{})};var kTe=(t,e)=>{for(let[r,n]of udt){let i=n.value.bind(e);Reflect.defineProperty(t,r,{...n,value:i})}},cdt=(async()=>{})().constructor.prototype,udt=["then","catch","finally"].map(t=>[t,Reflect.getOwnPropertyDescriptor(cdt,t)]);var NTe=(t,e,r,n)=>{let{file:i,commandArguments:s,command:o,escapedCommand:a,startTime:c,verboseInfo:u,options:l,fileDescriptors:d}=fdt(t,e,r),{subprocess:f,promise:p}=hdt({file:i,commandArguments:s,options:l,startTime:c,verboseInfo:u,command:o,escapedCommand:a,fileDescriptors:d});return f.pipe=QD.bind(void 0,{source:f,sourcePromise:p,boundOptions:{},createNested:n}),kTe(f,p),Wa.set(f,{options:l,fileDescriptors:d}),f},fdt=(t,e,r)=>{let{command:n,escapedCommand:i,startTime:s,verboseInfo:o}=aD(t,e,r),{file:a,commandArguments:c,options:u}=xD(t,e,r),l=pdt(u),d=Vwe(l,o);return{file:a,commandArguments:c,command:n,escapedCommand:i,startTime:s,verboseInfo:o,options:l,fileDescriptors:d}},pdt=({timeout:t,signal:e,...r})=>{if(e!==void 0)throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');return{...r,timeoutDuration:t}},hdt=({file:t,commandArguments:e,options:r,startTime:n,verboseInfo:i,command:s,escapedCommand:o,fileDescriptors:a})=>{let c;try{c=ddt(...OD(t,e,r))}catch(h){return zwe({error:h,command:s,escapedCommand:o,fileDescriptors:a,options:r,startTime:n,verboseInfo:i})}let u=new AbortController;ldt(Number.POSITIVE_INFINITY,u.signal);let l=[...c.stdio];Xwe(c,a,u),tTe(c,r,u);let d={},f=Ha();c.kill=mEe.bind(void 0,{kill:c.kill.bind(c),options:r,onInternalError:f,context:d,controller:u}),c.all=mTe(c,r),CTe(c,r),Lwe(c,r);let p=mdt({subprocess:c,options:r,startTime:n,verboseInfo:i,fileDescriptors:a,originalStreams:l,command:s,escapedCommand:o,context:d,onInternalError:f,controller:u});return{subprocess:c,promise:p}},mdt=async({subprocess:t,options:e,startTime:r,verboseInfo:n,fileDescriptors:i,originalStreams:s,command:o,escapedCommand:a,context:c,onInternalError:u,controller:l})=>{let[d,[f,p],h,m,_]=await ETe({subprocess:t,options:e,context:c,verboseInfo:n,fileDescriptors:i,originalStreams:s,onInternalError:u,controller:l});l.abort(),u.resolve();let S=h.map((y,v)=>uu(y,e,v)),b=uu(m,e,"all"),R=gdt({errorInfo:d,exitCode:f,signal:p,stdio:S,all:b,ipcOutput:_,context:c,options:e,command:o,escapedCommand:a,startTime:r});return $_(R,n,e)},gdt=({errorInfo:t,exitCode:e,signal:r,stdio:n,all:i,ipcOutput:s,context:o,options:a,command:c,escapedCommand:u,startTime:l})=>"error"in t?LT({error:t.error,command:c,escapedCommand:u,timedOut:o.terminationReason==="timeout",isCanceled:o.terminationReason==="cancel"||o.terminationReason==="gracefulCancel",isGracefullyCanceled:o.terminationReason==="gracefulCancel",isMaxBuffer:t.error instanceof Ka,isForcefullyTerminated:o.isForcefullyTerminated,exitCode:e,signal:r,stdio:n,all:i,ipcOutput:s,options:a,startTime:l,isSync:!1}):$D({command:c,escapedCommand:u,stdio:n,all:i,ipcOutput:s,options:a,startTime:l});var rM=(t,e)=>{let r=Object.fromEntries(Object.entries(e).map(([n,i])=>[n,_dt(n,t[n],i)]));return{...t,...r}},_dt=(t,e,r)=>ydt.has(t)&&Sr(e)&&Sr(r)?{...e,...r}:r,ydt=new Set(["env",...MK]);var Vl=(t,e,r,n)=>{let i=(o,a,c)=>Vl(o,a,r,c),s=(...o)=>Sdt({mapArguments:t,deepOptions:r,boundOptions:e,setBoundExeca:n,createNested:i},...o);return n!==void 0&&n(s,i,e),s},Sdt=({mapArguments:t,deepOptions:e={},boundOptions:r={},setBoundExeca:n,createNested:i},s,...o)=>{if(Sr(s))return i(t,rM(r,s),n);let{file:a,commandArguments:c,options:u,isSync:l}=vdt({mapArguments:t,firstArgument:s,nextArguments:o,deepOptions:e,boundOptions:r});return l?Cwe(a,c,u):NTe(a,c,u,i)},vdt=({mapArguments:t,firstArgument:e,nextArguments:r,deepOptions:n,boundOptions:i})=>{let s=VSe(e)?GSe(e,r):[e,...r],[o,a,c]=ZN(...s),u=rM(rM(n,i),c),{file:l=o,commandArguments:d=a,options:f=u,isSync:p=!1}=t({file:o,commandArguments:a,options:u});return{file:l,commandArguments:d,options:f,isSync:p}};var DTe=({file:t,commandArguments:e})=>$Te(t,e),MTe=({file:t,commandArguments:e})=>({...$Te(t,e),isSync:!0}),$Te=(t,e)=>{if(e.length>0)throw new TypeError(`The command and its arguments must be passed as a single string: ${t} ${e}.`);let[r,...n]=Edt(t);return{file:r,commandArguments:n}},Edt=t=>{if(typeof t!="string")throw new TypeError(`The command must be a string: ${String(t)}.`);let e=t.trim();if(e==="")return[];let r=[];for(let n of e.split(bdt)){let i=r.at(-1);i&&i.endsWith("\\")?r[r.length-1]=`${i.slice(0,-1)} ${n}`:r.push(n)}return r},bdt=/ +/g;var LTe=(t,e,r)=>{t.sync=e(wdt,r),t.s=t.sync},UTe=({options:t})=>FTe(t),wdt=({options:t})=>({...FTe(t),isSync:!0}),FTe=t=>({options:{...Tdt(t),...t}}),Tdt=({input:t,inputFile:e,stdio:r})=>t===void 0&&e===void 0&&r===void 0?{stdin:"inherit"}:{},zTe={preferLocal:!0};var jTe=Vl(()=>({})),Mar=Vl(()=>({isSync:!0})),qTe=Vl(DTe),$ar=Vl(MTe),Lar=Vl(JEe),Uar=Vl(UTe,{},zTe,LTe),{sendMessage:Far,getOneMessage:zar,getEachMessage:jar,getCancelSignal:qar}=Uwe();var BTe=!1,VTe,Adt=t=>{VTe??=t},GTe=t=>{BTe=!0,Adt(t)},Mn=()=>BTe,lu=()=>VTe,HTe=t=>{switch(t){case"SIGTERM":case"SIGINT":return t;case void 0:return"interrupted";default:return}};var VT=null,WTe=t=>(VT&&VT.destroy(),VT=new Ls({totalAllowedTime:t}),VT),KTe=()=>VT;var Ls=class{constructor({totalAllowedTime:e}){this.withStageTimer=async(e,r,n,{interruptible:i=!0}={})=>{if(this.isTimeExpired())throw new Error(`${e} stage did not complete in the allowed time. Time has already expired.`);if(i&&Mn())throw new Error(`Aborting ${e} stage \u2014 shutting down`);let s=this.onTimesUp(()=>{throw new Error(`${e} stage did not complete in the allowed time.`)}),o=null,a=null;n!==void 0&&(a=new Promise((l,d)=>{o=setTimeout(()=>{d(new Error(`${e} stage exceeded its maximum duration of ${n}ms`))},n)}));let c=Date.now(),u="success";try{return await UC({stage:e},async()=>a?await Promise.race([r(),a]):await r())}catch(l){throw u="failure",l}finally{K.timing("stage.duration",Date.now()-c,{stage:e,outcome:u}),s(),o&&clearTimeout(o)}};this.startTime=Date.now(),this.totalAllowedTime=e,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let e=this.getElapsedTime(),r=this.totalAllowedTime-e;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 e=this.subscribers.length-1;e>=0;e--)try{this.subscribers[e]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(e){if(this.subscribers.push(e),this.hasTimedOut)try{e()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(e);r>-1&&this.subscribers.splice(r,1)}}off(e){let r=this.subscribers.indexOf(e);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:e=>e*1e3,minutes:e=>e*60*1e3,hours:e=>e*60*60*1e3}}};var YTe={name:"@netlify/agent-runner-cli",type:"module",version:"1.200.2-bug.4",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:{prebuild:"rm -rf dist",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:smoke":"node scripts/smoke-dist.js","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:opencode":"vitest run test/integration/opencode.test.ts","test:integration:muse":"vitest run test/integration/muse.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","check:types":"tsc --noEmit",postinstall:"node scripts/postinstall.js"},engines:{node:">=22"},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":"^10.0.1","@netlify/axis":"^1.21.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:"^10.5.0","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.295","@anthropic-ai/sdk":"^0.128.0","@google/gemini-cli":"0.42.0","@modelcontextprotocol/sdk":"^1.29.0","@netlify/cache-utils":"^6.0.5","@netlify/database-proxy":"^0.2.2","@netlify/otel":"^6.0.6","@netlify/ts-cli":"^1.2.0","@openai/codex":"0.162.0","@opentelemetry/api":"^1.9.0","@opentelemetry/exporter-trace-otlp-grpc":"0.218.0",execa:"^9.6.1",fastify:"5.12.5",minimist:"^1.2.8",openai:"7.31.0",zod:"^4.4.3"}};var Idt=xdt(import.meta.url),Pdt=du.dirname(Idt),Cdt=Odt(import.meta.url),z_=re("shell"),o9=new Set,ZTe={preferLocal:!0},_t=(t,e,r)=>{let[n,i]=kdt(e,r),s={...ZTe,...i},o=jTe(t,n,s);JTe(o,s),tAe(o);let a=r?.idleTimeout;return a&&a>0&&eAe(o,a),o},QTe=(t,e)=>{let r={...ZTe,...e},n=qTe(t,r);return JTe(n,r),tAe(n),e?.idleTimeout&&e.idleTimeout>0&&eAe(n,e.idleTimeout),n},kdt=function(t,e){return Array.isArray(t)?[t,e]:typeof t=="object"&&t!==null?[[],t]:[[],void 0]},JTe=(t,e)=>{if(e.stdio!==void 0||e.stdout!==void 0||e.stderr!==void 0||Za.env.NETLIFY_LOCAL_QUIET==="true")return;if(Za.env.NETLIFY_MASK_LOGS!=="false"){t.stdout?.pipe(new Nb).pipe(Za.stdout),t.stderr?.pipe(new Nb).pipe(Za.stderr);return}t.stdout?.pipe(Za.stdout),t.stderr?.pipe(Za.stderr)},a9=(t,e="SIGTERM")=>{try{return t.pid&&!t.killed?(Za.kill(-t.pid,e),z_.log(`Killed process ${t.pid} with signal ${e}`),!0):!1}catch(r){return z_.error("Error killing process:",r),!1}},XTe=t=>a9(t,"SIGKILL"),eAe=(t,e)=>{let r=null,n=()=>{z_.log(`Process ${t.pid} killed due to idle timeout (no output for ${e}ms)`),a9(t,"SIGTERM"),setTimeout(()=>{t.pid&&!t.killed&&(z_.log(`Force killing idle process ${t.pid}`),XTe(t))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,e)};i(),t.stdout?.on("data",i),t.stderr?.on("data",i);let s=()=>{r&&(clearTimeout(r),r=null)};t.on("exit",s),t.on("error",s)},tAe=t=>{o9.add(t);let e=KTe();if(e){let r=e.onTimesUp(()=>{z_.log(`Global timer expired, killing process ${t.pid}`),a9(t,"SIGTERM"),setTimeout(()=>{t.pid&&!t.killed&&(z_.log(`Force killing process ${t.pid} after timeout`),XTe(t))},5e3)});t.on("exit",()=>{o9.delete(t),r()}),t.on("error",()=>{o9.delete(t),r()})}};function iM(t,e){return!!Yo(t,e)}function Yo(t,e){if(!Za.env.NETLIFY_LOCAL_MODE)try{let i=Cdt.resolve(YTe.name),s=du.dirname(i);for(;s!==du.dirname(s);){let o=du.dirname(s);if(du.basename(o)==="node_modules"){let a=du.join(o,".bin",e);if(nM.existsSync(a))return a;break}s=o}}catch(i){console.error("Could not resolve package.json",i)}if(Za.env.NODE_PATH){let i=du.join(Za.env.NODE_PATH,".bin",e);if(nM.existsSync(i))return i}let r=du.join(t,"node_modules",".bin",e);if(nM.existsSync(r))return r;let n=du.join(Pdt,"..","node_modules",".bin",e);if(nM.existsSync(n))return n}var rAe=re("repo"),aAe="runner-diffs-",c9=t=>`${aAe}${t}-`,cAe=async t=>{let e=sM.tmpdir(),r;try{r=await Qo.readdir(e)}catch{return}await Promise.all(r.filter(n=>n.startsWith(aAe)&&!n.startsWith(c9(t))).map(n=>Qo.rm(Zo.join(e,n),{recursive:!0,force:!0}).catch(()=>{})))},nAe=async t=>{let e=Ndt("sha256");for await(let r of Ddt(t))e.update(r);return e.digest("hex")},iAe=async(t,e)=>t.size===e.size&&await nAe(t.path)===await nAe(e.path),uAe=/.. (.+)?\.log$/,Mdt=[uAe],$dt=1,sAe=t=>{let e=t.split(`
|
|
389
|
+
`).reduce((r,n)=>{if(!n)return r;let[i,s,,...o]=n,a=o.join(""),c=i.trim(),u=s.trim();return r[a]?r[a].change=u:r[a]={filePath:a,stage:c,change:u},r},{});return Object.values(e)},Ldt=t=>t instanceof Error&&String(t.stderr??"").includes("No such remote"),Udt=t=>{let e=t instanceof Error?t.message:String(t),r=String(t?.stderr??"").trim();return Ei(r?`${e}: ${r}`:e)},Fdt={stdin:"pipe",stdout:"pipe",stderr:"pipe",stripFinalNewline:!1},oAe=500,GT=class extends Error{constructor(r,n){super(n instanceof Error?n.message:String(n));this.step=r;this.cause=n}},$n=class{constructor(e=process.cwd()){this.cwd=e}getRoot(){return this.root??=this.run(["rev-parse","--show-toplevel"],{stdout:"pipe"}).then(({stdout:e})=>String(e).trim()),this.root}async restorePausedWork(e){let r="restore";try{let n=await this.restorePausedFiles(e);return r="stage",await this.stageBuildSetup(),await this.unstageFiles(n.changedFiles,{cwd:await this.getRoot()}),{rewrittenFileCount:n.rewrittenFileCount}}catch(n){throw new GT(r,n)}}run(e,r={}){return _t("git",e,{cwd:this.cwd,...r,env:{...r.env,NETLIFY_INTERNAL_GIT:"1"}})}async commitAndCreateDiffs({config:e,isRetry:r}){rAe.info("Getting runner diffs");let n=await this.hasAgentChanges(),{hasChanges:i}=n,{status:s}=n;if(!i)return{hasChanges:!1};if(!r){let u=sAe(s);await this.discardSetupOnlyChanges(u)}rAe.info("Changes after processing"),await this.getStatus();let o=await this.getIgnoredPathspecs(s);if(await this.stageFiles(o),i=await this.hasStagedChanges(),!i)return{hasChanges:!1,ignored:o};await this.run(["commit","-m","Agent runner [skip ci]"]);let a=await Qo.mkdtemp(Zo.join(sM.tmpdir(),c9(e.sessionId))),c=await this.writeDiffFiles({config:e,diffDir:a,target:{commit:"HEAD"},ignored:o});return await this.rollbackIfLocal(),c.hasChanges&&K.distribution("diff.size",(c.diffBinary??c.diff).size,{phase:"final"}),c}async getStatus(){let e=await this.run(["-c","status.relativePaths=true","status","-s"]);return String(e.stdout??"")}async hasAgentChanges(){let e=await this.getStatus();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
390
390
|
`).filter(i=>Mdt.some(o=>o instanceof RegExp?o.test(i):i===o)?!1:i[1]?.trim()!=="")).length!==0,status:e}}async getCurrentCommitSha(){let{stdout:e}=await this.run(["rev-parse","HEAD"]);return String(e??"").trim()}async reset(){await this.run(["reset","--hard","HEAD"])}async discardSetupOnlyChanges(e){let r=e.filter(n=>n.stage&&!n.change).map(n=>n.filePath);r.length!==0&&await this.run(["restore","--staged","--worktree","--pathspec-from-file=-"],{input:r.join(`
|
|
391
391
|
`)})}async stageBuildSetup(){let e=await this.getIgnoredPathspecs();await this.stageFiles(e)}async getIgnoredPathspecs(e){e||=await this.getStatus();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(`
|
|
392
392
|
`).forEach(i=>{r.forEach(o=>{let a=i===`?? ${o}`,c=i.startsWith(`?? ${o}/`)||i.startsWith(`?? ${o}${Zo.sep}`);(a||c)&&n.push(`:!${o}`)});let s=i.match(uAe)?.[1];s&&n.push(`:!${s}.log`)}),n}async stageFiles(e=[],r){await this.run(["add",".",...e],{env:r})}async unstageFiles(e,r={}){e.length!==0&&await this.run(["reset","--pathspec-from-file=-","--pathspec-file-nul","HEAD"],{...r,input:e.map(n=>`:(literal)${n}`).join("\0")})}async writeDiffFiles({config:e,diffDir:r,target:n,ignored:i}){let s="commit"in n?n.commit:"--cached",o="indexPath"in n?{GIT_INDEX_FILE:n.indexPath}:void 0,a=async({from:p,fileName:h,binary:m})=>{let _=Zo.join(r,h),S=m?["diff","--no-relative",p,s,"--binary"]:["diff","--no-relative",p,s];await this.run([...S,`--output=${_}`],{stdio:["ignore","ignore","pipe"],env:o});let{size:b}=await Qo.stat(_);return{path:_,size:b}},c=await a({from:e.runSha,fileName:"session.patch"});if(c.size===0)return{hasChanges:!1,ignored:i};let u=await a({from:e.runSha,fileName:"session-binary.patch",binary:!0}),l,d;if(e.sha){l=await a({from:e.sha,fileName:"cumulative.patch"});let p=await a({from:e.sha,fileName:"cumulative-binary.patch",binary:!0});await iAe(l,p)||(d=p)}let f={hasChanges:!0,diff:c,resultDiff:l,ignored:i};return await iAe(c,u)||(f.diffBinary=u),d&&(f.resultDiffBinary=d),f}async hasStagedChanges(){try{return await this.run(["diff","--staged","--quiet"]),!1}catch{return!0}}async rollbackIfLocal(){process.env.NETLIFY_LOCAL_MODE&&await this.run(["reset","--soft","HEAD~1"])}async hasCommits(){try{return await this.run(["rev-parse","--verify","--quiet","HEAD"]),!0}catch(e){if(e.exitCode===$dt)return!1;throw e}}async hasNoCommittedFiles(){if(!await this.hasCommits())return!0;let{stdout:e}=await this.run(["ls-tree","--name-only","HEAD"]);return String(e??"").trim().length===0}async getFirstCommitSha(){let{stdout:e}=await this.run(["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()}async removeUntrackedFiles(){let e=await this.run(["clean","-fd","-e",".netlify"],{stdio:["ignore","pipe","pipe"]});return String(e.stdout??"").split(`
|
|
@@ -703,13 +703,13 @@ Below are all of the logs with potential issues that we extracted. Some of them
|
|
|
703
703
|
|
|
704
704
|
${t.pop()}
|
|
705
705
|
`;var QR=re("deploy"),LIt=t=>t===""||/[\s"\\]/u.test(t)?JSON.stringify(t):t,o$e=async t=>await zt(ht(),"create-preview-deploy",async e=>UIt(t,e)),UIt=async({hasRepo:t,message:e="Agent Preview",deploySubdomain:r,cliPath:n,filter:i,prodDeploy:s,agentRunnerId:o,agentRunnerSessionId:a},c)=>{try{let u=["deploy","--message",e,"--json","--verbose",s?"--prod":"--draft"];QR.log("Deploy: Uploading source zip"),u.push("--upload-source-zip"),r&&!s&&u.push("--alias",r),i&&u.push("--filter",i),u.push("--context",s?"production":"deploy-preview");let l=n||"netlify";QR.log(`Running: ${l} ${u.map(LIt).join(" ")}`),c?.setAttributes({cmd:l,args:u});let d={};o&&(d.NETLIFY_AGENT_RUNNER_ID=o),a&&(d.NETLIFY_AGENT_RUNNER_SESSION_ID=a);let f=await _t(l,u,{stdio:["ignore","pipe","pipe"],env:{...process.env,NETLIFY_DEPLOY_SOURCE:"agent_runner",...d}});f.stderr&&QR.log(String(f.stderr));let p=JSON.parse(String(f.stdout??"").trim());c?.setAttributes({success:!0,deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id}),QR.log(`
|
|
706
|
-
Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let h={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(h.sourceZipFilename=p.source_zip_filename),h}catch(u){throw QR.error("Failed to create preview deploy via CLI:",u),c?.setAttributes({success:!1,error:u.message}),u}};import a$e from"fs";import mJ from"path";var c$e=(t=process.cwd())=>{let e=mJ.join(t,tn,Sde);return{hasNetlifyForm:a$e.existsSync(mJ.join(e,"netlify-forms")),hasNetlifyIdentity:a$e.existsSync(mJ.join(e,"netlify-identity"))}};var oa=re("deploy_stage"),JR=async t=>await zt(ht(),"run-deploy-stage",async()=>FIt(t)),FIt=async({cliPath:t,config:e,result:r,filter:n,isRetry:i,deploySubdomain:s})=>{if(e.mode==="ask")return{hasChanges:!1,previewInfo:null,isProdDeploy:!1,hasNetlifyForm:!1,hasNetlifyIdentity:!1};let o=new $n,a=await zt(ht(),"get-runner-diffs",async()=>await o.
|
|
706
|
+
Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let h={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(h.sourceZipFilename=p.source_zip_filename),h}catch(u){throw QR.error("Failed to create preview deploy via CLI:",u),c?.setAttributes({success:!1,error:u.message}),u}};import a$e from"fs";import mJ from"path";var c$e=(t=process.cwd())=>{let e=mJ.join(t,tn,Sde);return{hasNetlifyForm:a$e.existsSync(mJ.join(e,"netlify-forms")),hasNetlifyIdentity:a$e.existsSync(mJ.join(e,"netlify-identity"))}};var oa=re("deploy_stage"),JR=async t=>await zt(ht(),"run-deploy-stage",async()=>FIt(t)),FIt=async({cliPath:t,config:e,result:r,filter:n,isRetry:i,deploySubdomain:s})=>{if(e.mode==="ask")return{hasChanges:!1,previewInfo:null,isProdDeploy:!1,hasNetlifyForm:!1,hasNetlifyIdentity:!1};let o=new $n,a=await zt(ht(),"get-runner-diffs",async()=>await o.commitAndCreateDiffs({config:e,isRetry:i}));if(oa.info("Resolved git",{hasChanges:a.hasChanges,ignored:a.ignored??[]}),!a.hasChanges&&e.mode!=="redeploy"&&!e.pendingUndeployedChanges)return{hasChanges:!1,previewInfo:null,isProdDeploy:!1,hasNetlifyForm:!1,hasNetlifyIdentity:!1};let c=a.hasChanges?a.diff:void 0,u=a.hasChanges?a.resultDiff:void 0,l=a.hasChanges?a.diffBinary:void 0,d=a.hasChanges?a.resultDiffBinary:void 0,f=a.hasChanges||e.mode==="redeploy",{hasNetlifyForm:p,hasNetlifyIdentity:h}=c$e();if(p||h){let R={};p&&(oa.log("Detected Netlify Forms enablement \u2014 enabling early"),R.has_netlify_form=!0),h&&(oa.log("Detected Netlify Identity enablement \u2014 enabling early"),R.has_netlify_identity=!0);try{await $r(e.id,e.sessionId,R)}catch(y){oa.warn("Failed to send early feature enablement (continuing):",y)}}let m=r!==void 0&&(f||e.mode==="redeploy"||!!e.pendingUndeployedChanges);oa.log("Deploy condition check:",{resultUndefined:r===void 0,resultType:typeof r,hasChanges:f,isRedeploy:e.mode==="redeploy",pendingUndeployedChanges:!!e.pendingUndeployedChanges,wouldCreateDeploy:m});let _=oM(e.mode),S=null,b;if(m)try{let R;try{let y=await zt(ht(),"get-runner-session",async()=>await qf(e.id,e.sessionId));y?.title&&(R=y.title)}catch(y){oa.warn("Failed to fetch session title, using fallback message:",y.message)}if(await $r(e.id,e.sessionId,{steps:[{title:_?"Deploying project":"Deploying preview",category:W.Deployment}]}),S=await o$e({cliPath:t,hasRepo:e.hasRepo,message:R,deploySubdomain:s,filter:n,prodDeploy:_,agentRunnerId:e.id,agentRunnerSessionId:e.sessionId}),_)try{let y=await o.pushToOrigin({targetBranch:e.pushBranch});y.pushed?oa.log(`Pushed workspace commits to origin (${y.branch})`):oa.log(`Skipped origin push (${y.reason})`)}catch(y){b=y instanceof Error?y.message:String(y),oa.warn("Failed to push workspace commits to origin (continuing):",y)}}catch(R){if(Mn())throw R;return oa.warn("Failed to create preview deploy (continuing with agent run):",R),{diff:c,resultDiff:u,hasChanges:f,previewInfo:null,diffBinary:l,resultDiffBinary:d,deployError:R instanceof Error?R.message:String(R),isProdDeploy:_,hasNetlifyForm:p,hasNetlifyIdentity:h}}return oa.log("Git status",{hasDiff:!!c,hasChanges:f}),{diff:c,resultDiff:u,hasChanges:f,previewInfo:S,diffBinary:l,resultDiffBinary:d,gitPushError:b,isProdDeploy:_,hasNetlifyForm:p,hasNetlifyIdentity:h}};var zIt=re("redeploy"),u$e="Redeploy completed",l$e=async({cliPath:t,config:e,filter:r,deploySubdomain:n,isProdDeploy:i,withStageTimer:s})=>{let o=await s("deploy",()=>JR({cliPath:t,config:e,result:u$e,filter:r,isRetry:!1,deploySubdomain:n}));o.deployError&&(zIt.warn(`Redeploy deploy failed: ${o.deployError}`),K.inc("deploy.failed",1,{attempt:1})),FC({previewDeployed:!!o.previewInfo,hadFailedAttempts:!!o.deployError});let{diff:a,resultDiff:c,previewInfo:u,diffBinary:l,resultDiffBinary:d,hasNetlifyForm:f,hasNetlifyIdentity:p}=o;return{diff:a,result:u$e,duration:0,resultDiff:c,diffBinary:l,resultDiffBinary:d,previewInfo:u,isProdDeploy:i,hasNetlifyForm:f,hasNetlifyIdentity:p}};import l1e from"process";import jIt from"fs";import qIt from"path";import BIt from"process";var gJ=re("db_migrations"),VIt=new Set(["drizzle.config.ts","drizzle.config.js","drizzle.config.mjs"]),f$e=async t=>await UC({stage:"db-migrations"},()=>zt(ht(),"db-migrations",async e=>{let r=t.cwd||BIt.cwd();if(!(await d$e("@netlify/database",r)||await d$e("@netlify/db",r)))return e?.setAttributes({skipped:!0,reason:"@netlify/database is not installed"}),K.inc("db_migrations.run",1,{outcome:"skipped",reason:"no_module"}),{skipped:!0,reason:"no_module"};let i=[...VIt].find(s=>jIt.existsSync(qIt.join(r,s)));if(!i)return e?.setAttributes({skipped:!0,reason:"no drizzle config found"}),K.inc("db_migrations.run",1,{outcome:"skipped",reason:"no_config"}),{skipped:!0,reason:"no_config"};e?.setAttributes({configFile:i}),gJ.log(`Found ${i}, running drizzle-kit generate to ensure migrations are up to date`);try{let s=await _t("npx",["drizzle-kit","generate"],{cwd:r,stdio:["ignore","pipe","pipe"]});return s.stdout&&gJ.log(String(s.stdout)),e?.setAttributes({success:!0}),K.inc("db_migrations.run",1,{outcome:"success"}),{skipped:!1}}catch(s){let o=GIt(s);return gJ.warn("drizzle-kit generate failed:",o),e?.setAttributes({success:!1,error:o}),K.inc("db_migrations.run",1,{outcome:"failure"}),{skipped:!1,error:o}}})),d$e=async(t,e)=>{try{return await QTe(`node -e "require.resolve('${t}')"`,{cwd:e,stdio:"ignore"}),!0}catch{return!1}},GIt=t=>{if(t&&typeof t=="object"){let e=[];if("stderr"in t&&t.stderr&&e.push(String(t.stderr)),"stdout"in t&&t.stdout&&e.push(String(t.stdout)),e.length>0)return e.join(`
|
|
707
707
|
`)}return t instanceof Error?t.message:String(t)};var E1=re("migration_state"),_J=async({cliPath:t,cwd:e})=>{let r;try{let n=await _t(t,["db","status","--json"],{cwd:e,stdio:["ignore","pipe","pipe"]});r=n.stdout?String(n.stdout):""}catch(n){let i=n;throw E1.warn("`netlify db status --json` failed",{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr}),n}E1.log("`netlify db status --json` output",{stdout:r});try{return JSON.parse(r)}catch(n){throw E1.warn("Failed to parse `netlify db status --json` output",{stdout:r,error:String(n)}),n}},HIt=()=>["## 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(`
|
|
708
708
|
`),WIt=t=>{if(t.applied.length===0&&t.pending.length===0)return null;let e=["## CRITICAL: Current Netlify Database state",""];if(t.applied.length>0){e.push("The following migrations are **already applied** to your preview database branch. They are immutable:","");for(let r of t.applied)e.push(`- ${r.name}`);e.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 e.push("No migrations are applied to your preview database branch yet.");if(t.pending.length>0){e.push(""),e.push("The following migration files exist on disk but have NOT yet been applied:","");for(let r of t.pending)e.push(`- ${r.name}`);e.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 e.join(`
|
|
709
709
|
`)},yJ=async({cliPath:t,cwd:e,isFreshDatabase:r})=>{if(r)return HIt();try{return WIt(await _J({cliPath:t,cwd:e}))}catch(n){return E1.warn("Skipping migration context injection \u2014 failed to build state block",{error:n}),null}},p$e=t=>{let e=[];return t.missingOnDisk.length>0&&e.push("The following migration file(s) are applied to the preview database branch but are no longer on disk","under their original name:",...t.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. **Renaming or renumbering an applied migration is a","deletion**: the platform matches migrations by version, so moving one to a new version prefix removes the","original as far as the branch is concerned, and the new file reads as an unapplied migration whose version","almost certainly sorts too early. 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."),t.outOfOrder.length>0&&(e.length>0&&e.push(""),e.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:",...t.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.")),e.length===0?null:(e.push("","Note on refusals: if you reached this state after the platform refused a migration, that refusal names only","the database that refused it. It is not evidence that the migration is unapplied anywhere \u2014 every branch,","and production, keeps its own record of what it has applied. The applied list above is the only authority on","this branch, and it overrides any procedure written in AGENTS.md, PLAN.md, or other project notes."),e.join(`
|
|
710
710
|
`))},h$e=t=>t.missingOnDisk.length>0||t.outOfOrder.length>0;var m$e=re("db_migrations_verify"),KIt=t=>{let e=t.missingOnDisk.length>0,r=t.outOfOrder.length>0;return e&&r?"both":e?"missing_on_disk":r?"out_of_order":"none"},g$e=async t=>await zt(ht(),"db-migrations-verify-stage",async e=>{let r;try{r=await _J({cliPath:t.cliPath,cwd:t.cwd})}catch(i){return m$e.warn("Skipping migration verification \u2014 failed to read status",{error:i}),e?.setAttributes({"verify.skipped":!0,"verify.skip_reason":"status_error"}),K.inc("db_migrations.verify",1,{drift:"unknown"}),{}}if(!h$e(r))return e?.setAttributes({"verify.drift":!1}),K.inc("db_migrations.verify",1,{drift:"none"}),{};let n=p$e(r);return K.inc("db_migrations.verify",1,{drift:KIt(r)}),e?.setAttributes({"verify.drift":!0,"verify.missing_on_disk_count":r.missingOnDisk.length,"verify.out_of_order_count":r.outOfOrder.length}),m$e.log("Detected post-inference migration drift",{missingOnDisk:r.missingOnDisk.map(i=>i.name),outOfOrder:r.outOfOrder.map(i=>i.name)}),{error:n??void 0}});import wX from"process";import _kt from"net";var ls=Hr(SX(),1),C$r=ls.default.Client,k$r=ls.default.Pool,N$r=ls.default.Connection,D$r=ls.default.types,M$r=ls.default.Query,$$r=ls.default.DatabaseError,L$r=ls.default.escapeIdentifier,U$r=ls.default.escapeLiteral,F$r=ls.default.Result,z$r=ls.default.TypeOverrides,j$r=ls.default.defaults,o1e=ls.default;var ykt=1e3,Skt=6e4,bX=class extends Error{willRetry;constructor(t,e){super(t),this.name="ProvisionHeldError",this.willRetry=e}},a1e=t=>t instanceof bX;function vkt(t,e={}){let r=e.baseMs??ykt,n=e.maxMs??Skt,i=e.isPermanent??(()=>!1),s,o,a=0,c=!1,u=0,l=d=>{let f=d instanceof Error?d.message:String(d);if(u+=1,c=i(d),c)o=new bX(`Database provisioning failed and will not be retried: ${f}`,!1);else{let p=Math.min(r*2**(u-1),n);a=Date.now()+p;let h=String(p/1e3);o=new bX(`Database provisioning failed, retrying in ${h}s: ${f}`,!0)}throw d};return async()=>{if(o&&(c||Date.now()<a))throw o;return s??=t().then(d=>(u=0,o=void 0,d),l).finally(()=>{s=void 0}),await s}}var Ekt=80877103,bkt=196608,wkt=Buffer.from([78]);function Tkt(){let t=Buffer.alloc(9);t.writeUInt8(82,0),t.writeInt32BE(8,1),t.writeInt32BE(0,5);let e=Buffer.alloc(6);return e.writeUInt8(90,0),e.writeInt32BE(5,1),e.writeUInt8(73,5),Buffer.concat([t,e])}function F1(t){let e=Buffer.from("SERROR\0","utf8"),r=Buffer.concat([Buffer.from("M","utf8"),Buffer.from(t+"\0","utf8")]),n=Buffer.from("CXX000\0","utf8"),i=Buffer.from([0]),s=e.length+r.length+n.length+i.length,o=Buffer.alloc(5);return o.writeUInt8(69,0),o.writeInt32BE(s+4,1),Buffer.concat([o,e,n,r,i])}async function Akt(t){let{clientSocket:e,provision:r,logger:n,cleanup:i}=t,s;try{s=await r()}catch(f){let p=f instanceof Error?f.message:"Provisioning failed";throw a1e(f)||n("Provisioning error:",p),e.end(F1(p)),i(),f}let o=xkt(s),a=new o1e.Client({host:o.host,port:o.port,user:o.user,password:o.password,database:o.database,ssl:o.ssl,options:o.options});a.on("error",()=>{});try{await a.connect()}catch(f){let p=f instanceof Error?f.message:"Remote connection failed";throw n("Remote connection error:",p),e.end(F1(p)),i(),f}let c=a.connection,u=c.stream;c.removeAllListeners(),u.removeAllListeners();let l=u,d=f=>p=>{p.code!=="ECONNRESET"&&n(`${f} socket error:`,p.message),i()};return l.on("error",d("Remote")),l.on("close",i),e.on("error",d("Client")),e.on("close",i),e.write(Tkt()),e.on("data",f=>{l.destroyed||l.write(f)}),l.on("data",f=>{e.destroyed||e.write(f)}),e.resume(),l}function Rkt(t,e){let{provision:r,logger:n,onCleanup:i}=e,s,o="ssl",a=!1;function c(){a||(a=!0,t.destroy(),s?.destroy(),i())}t.on("error",u=>{u.code!=="ECONNRESET"&&n("Client socket error:",u.message),c()}),t.on("data",u=>{if(o==="ssl"){if(u.length>=8&&u.readInt32BE(4)===Ekt){t.write(wkt),o="startup";return}o="startup"}if(o==="startup"){if(u.length<8){t.end(F1("Invalid startup message")),c();return}if(u.readInt32BE(4)!==bkt){t.end(F1("Unsupported protocol version")),c();return}t.pause(),t.removeAllListeners("data"),Akt({clientSocket:t,provision:r,logger:n,cleanup:c}).then(d=>{s=d},d=>{a1e(d)||n("Startup error:",d),c()})}})}function xkt(t){let e=new URL(t);return{host:e.hostname,port:Number(e.port)||5432,user:decodeURIComponent(e.username),password:decodeURIComponent(e.password),database:e.pathname.slice(1)||"postgres",ssl:e.searchParams.get("sslmode")==="require"?!0:void 0,options:e.searchParams.get("options")??void 0}}var c1e=class{server;sockets=new Set;host;port;logger;provision;constructor(t){this.host=t.host??"127.0.0.1",this.port=t.port??0,this.logger=t.logger??(()=>{}),this.provision=vkt(t.provision,t.retry)}async start(){return new Promise((t,e)=>{let r=_kt.createServer(n=>{this.sockets.add(n),n.on("close",()=>{this.sockets.delete(n)}),Rkt(n,{provision:this.provision,logger:this.logger,onCleanup:()=>{this.sockets.delete(n)}})});r.on("error",n=>{e(n)}),r.listen(this.port,this.host,()=>{this.server=r;let n=r.address(),i=`postgres://${this.host}:${String(n.port)}`;this.logger("Proxy listening on",i),t(i)})})}async stop(){for(let t of this.sockets)t.destroy();return this.sockets.clear(),new Promise(t=>{if(!this.server){t();return}this.server.close(()=>{this.server=void 0,t()})})}};var z1=re("db_setup"),u1e=async({siteId:t,isProd:e,alias:r,connectionString:n})=>await zt(ht(),"db-setup-stage",async i=>{i?.setAttributes({"db_setup.site_id":t,"db_setup.is_prod":e,...r&&{"db_setup.alias":r}});let s;if(e?s="production":r&&(s=r),wX.env.NETLIFY_DB_BRANCH=s,n)return i?.setAttributes({"db_setup.source":"config","db_setup.has_proxy":!1}),z1.log("Using database connection string provided by the API"),wX.env.NETLIFY_DB_URL=n,{connectionString:n,wasProvisioned:()=>!1};let o=!1,a=new c1e({logger:(...u)=>z1.log("db-proxy:",...u),provision:async()=>(z1.log("Provisioning database for site via API"),await Xde(t),o=!0,await Pkt(t,e,r)),retry:{isPermanent:Ikt}}),c=await a.start();return i?.setAttributes({"db_setup.source":"proxy","db_setup.has_proxy":!0}),z1.log("Local DB proxy started",{connectionString:c}),wX.env.NETLIFY_DB_URL=c,{connectionString:c,proxy:a,wasProvisioned:()=>o}}),Okt=new Set([400,401,403,422]),Ikt=t=>Rs(t)||t instanceof Error&&"statusCode"in t&&Okt.has(t.statusCode),Pkt=async(t,e,r)=>e||!r?(await Qde(t)).connection_string:(await efe(t,r),(await Jde(t,r)).connection_string);var d1e=({config:t,cliPath:e,cwd:r,withStageTimer:n})=>{let i,s,o=null,a=t.mode==="ask",c=async()=>t.siteId?s?.()?!0:t.site?.has_database:!1;return{prepare:async({deploySubdomain:u,isProdDeploy:l})=>{if(a)return o=lAe(t,u),o?(K.inc("ask_mode.db_read_granted",1),TSe({cliPath:e,branch:o.branch})):void 0;l1e.env.EXPERIMENTAL_NETLIFY_DB_ENABLED="1";let d=t.siteId;if(l1e.env.NETLIFY_LOCAL_MODE||!d)return;let f=await n("db-setup",()=>u1e({siteId:d,isProd:l,alias:u,connectionString:t.dbConnectionString}),Ls.timeUnits.minutes(10));return i=f.proxy,s=f.wasProvisioned,r?await yJ({cliPath:e,cwd:r,isFreshDatabase:!!f.proxy})??void 0:void 0},currentContext:async()=>{if(!(a||!r)&&await c()!==!1)return await yJ({cliPath:e,cwd:r,isFreshDatabase:!1})??void 0},generateMigrations:async()=>a?{skipped:!0,reason:"no_module"}:await f$e({cwd:r}),verifyMigrations:async()=>a||!r?{}:await n("db-migrations-verify",()=>g$e({cliPath:e,cwd:r})),hasDatabase:c,stop:async()=>{await i?.stop()},revokeAskAccess:()=>{o&&l9()}}};import Ckt from"process";var f1e=re("teardown"),p1e=({config:t,cwd:e,database:r,stopUsageTracking:n})=>{let i,s=t.mode==="ask",o=new $n(e);return{setRunnerCleanup:a=>{i=a},run:async a=>{let c=async(l,d)=>{try{await d()}catch(f){f1e.warn(`Teardown step failed: ${l}`,{state:a,error:f?.message||f}),K.inc("teardown.step_failed",1,{step:l,state:a})}},u=a==="completed"&&!Ckt.env.NETLIFY_LOCAL_MODE;await c("usage-tracker",n),(a==="errored"||a==="cancelled"||u)&&await c("runner-cleanup",()=>i?.()),await c("db-proxy",()=>r.stop()),u&&await c("reset-repo",()=>o.reset()),s&&u&&await c("remove-untracked-files",async()=>{let l=await o.removeUntrackedFiles();l.length>0&&(f1e.warn(`Removed ${l.length} leftover untracked change(s) after ask run`,{removed:l}),K.inc("ask_mode.leaked_untracked_files",l.length))})}}};var kkt=({isHotFollowUp:t,enqueuedAt:e})=>t?e===void 0?[]:[["request",e]]:[["spawn",Number(process.env.NETLIFY_AGENT_RUNNER_SPAWN_AT_MS)],["enqueue",Number(process.env.NETLIFY_AGENT_RUNNER_ENQUEUED_AT_MS)]],TX=(t,e,r,n)=>{for(let[i,s]of kkt(r))Number.isFinite(s)&&s>0&&s<=n&&t.timing(e,n-s,{from:i})},h1e=(t,e=Date.now(),r=K)=>TX(r,"startup.duration",t,e),m1e=(t,e=Date.now(),r=K)=>TX(r,"startup.time_to_prompt",t,e),g1e=(t,e=Date.now(),r=K)=>TX(r,"startup.time_to_first_output",t,e);var _1e=(t,e=Date.now(),r=K)=>{let n={outcome:t.outcome,native_resume:t.nativeResume,is_answer_resume:t.isAnswerResume};r.timing("session.duration",e-t.startedAt,{hot_follow_up:t.isHotFollowUp,...n}),t.creditsCost!=null&&r.distribution("session.credits_cost",t.creditsCost,{...n,...t.model?{model:t.model}:{},...t.effort?{effort:t.effort}:{}})};var y1e=re("run"),Nkt="unspecified",S1e=(t,e=Date.now(),r=y1e)=>{r.info(Ca({event:"run.finished",agent_runner_id:t.agentRunnerId,session_id:t.sessionId,dev_server_id:t.devServerId,agent:t.agent,mode:t.mode,orchestrator_version:t.version,model:t.model,effort:t.effort,outcome:t.outcome,finalization_outcome:t.finalizationOutcome,stop_reason:t.stopReason,elapsed_ms:e-t.startedAt,credits:t.creditsCost,native_resume:t.nativeResume,is_answer_resume:t.isAnswerResume,hot_follow_up:t.isHotFollowUp}))},v1e=(t,e=y1e)=>{e.info(Ca({event:"run.started",agent_runner_id:t.agentRunnerId,session_id:t.sessionId,dev_server_id:t.devServerId,agent:t.agent,mode:t.mode,orchestrator_version:t.version,model:t.model,effort:t.effort??Nkt,is_answer_resume:t.isAnswerResume,hot_follow_up:t.isHotFollowUp}))};function E1e(t){return["One or more AI functions use the legacy **v1** syntax (`exports.handler` / `module.exports.handler`):","",t.map(r=>`- ${r}`).join(`
|
|
711
711
|
`),"",'Netlify AI Gateway credentials (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY` and the matching `*_BASE_URL` variables) are injected ONLY into the modern v2/v3 function runtime. A v1 function builds and deploys successfully but throws "missing API key" at runtime \u2014 this will NOT appear as a build error.',"","Rewrite each listed function using **v2** syntax \u2014 `export default async (req: Request) => Response` \u2014 or **v3** object export (`satisfies NetlifyFunction`), preserving its existing behavior and route. Do not set your own API keys; rely on the injected gateway credentials. See the `netlify-ai-gateway` skill for examples."].join(`
|
|
712
|
-
`)}var Hh=re("usage_tracker"),Dkt=4e3,Mkt=5e3,$kt=2e4,Lkt=(t,e,r)=>t===!0||r!=null&&e!=null&&e>=r,Ukt=(t,e,r)=>e!=null&&e>0&&r!=null&&t!=null&&e-t<=r,b1e=(t,e,r,{creditReserve:n,onCreditReserveReached:i}={})=>{let s=!1,o=!1,a=!1,c=!1,u,l,d,f=r,p,h=i!=null&&n!=null,m=()=>{p&&(clearInterval(p),p=void 0)},_=O=>{m(),p=setInterval(()=>{b()},O),p.unref?.()},S=async()=>{try{let O=await GC(t,e);Hh.log("Usage update response",{usage:O?.usage});let C=O?.usage?.total_credits_cost;C!=null&&(u=C);let I=O?.enforced_credits_cap;if(I!=null&&I!==f){let w=f==null;f=I,Hh.log("Took the session credit limit from a usage poll",{sessionCreditLimit:f,totalCreditsCost:C,isFirstLimit:w}),w&&K.inc("session.credit_cap_late_arrival",1)}let k=Lkt(O?.credit_limit_exceeded,C,f);if(k&&(Hh.log("Credit limit exceeded",{totalCreditsCost:C,sessionCreditLimit:f}),a||(l=Date.now(),d=C??u??0,_($kt)),a=!0),h&&!c&&!k&&Ukt(C,f,n)){c=!0,Hh.log("Credit reserve reached",{totalCreditsCost:C,sessionCreditLimit:f,creditReserve:n});try{i()}catch(w){Hh.warn("onCreditReserveReached callback threw",{error:w?.message||w})}}}catch(O){Hh.warn("Failed to update usage",{error:O?.message||O})}},b=KN(S,Dkt);return{onAgentOutput:()=>{if(a)throw new As("AI credit usage exceeded enforced limit.",503,"Credit limit reached. Check credit limits to continue using Agent Runners.");o||(s=!0,p||_(Mkt))},stop:async()=>{o||(o=!0,m(),s&&(b.cancel(),Hh.log("Sending final usage update"),await S(),l!==void 0&&(K.timing("credit_limit.overage_duration",Date.now()-l),K.distribution("credit_limit.overage_credits",Math.max(0,(u??d??0)-(d??0))))))},getCreditsCost:()=>u,getSessionCreditLimit:()=>f}};var w1e=re("session_credit_limit"),Fkt=async t=>{if(t.sessionCreditLimit!=null)return{limit:t.sessionCreditLimit,source:"env"};try{let e=(await GC(t.id,t.sessionId))?.enforced_credits_cap;if(e!=null)return w1e.log("Resolved the session credit limit from the usage endpoint",{limit:e}),{limit:e,source:"usage"}}catch(e){w1e.warn("Usage call for the session credit limit failed",{error:e?.message||e})}return{source:"none"}},T1e=async(t,e=!1)=>{let{limit:r,source:n}=await Fkt(t);t.sessionCreditLimit=r,K.inc("session.credit_cap_source",1,{source:n,hot_follow_up:e})};var Qd=re("credit_wrapup"),A1e="low",zkt=t=>{if(t.mode==="ask")return T2;if(t.mode==="normal")return A2;let e=YT(t);return ZT(t,e)?b2:w2},R1e=t=>typeof t=="number"?t:void 0,AX=t=>{let e=He(),r=e.creditWrapUpReserveByModeAgentAndModel[t.mode]?.[t.runner];return R1e(t.model?r?.models?.[t.model]:void 0)??R1e(r?.agent)??e.creditWrapUpReserve},x1e=(t,e)=>{if(e<=0)return!1;let r=He();return t.mode==="create"?r.creditWrapUpEnabled:t.mode==="ask"||t.mode==="normal"?r.creditWrapUpNormalEnabled:!1},RX=(t,e)=>{if(t==="fix"){Qd.log("Credit reserve reached outside of the main inference turn \u2014 letting the fix finish without a wrap-up"),K.inc("session.credit_wrapup_skipped_fix_turn",1,{credit_reserve:e});return}if(t==="no_session"){Qd.warn("Credit reserve reached but no session id yet \u2014 skipping wrap-up interrupt"),K.inc("session.credit_wrapup_skipped_no_session",1,{credit_reserve:e});return}Qd.log("Credit reserve reached with no turn to interrupt \u2014 the agent had already finished")},O1e=(t,e,r)=>{if(e==null)return;let n=Math.max(0,e-t.creditsSpentBeforeWrapUp);Qd.log("Credit wrap-up cost",{credits:n,creditsCostAtSessionEnd:e,effort:A1e,inferenceAfterWrapUp:r,...t}),K.distribution("session.credit_wrapup_cost",n,{outcome:t.outcome,effort:A1e,credit_reserve:t.creditReserve,inference_after_wrap_up:r,...t.model?{model:t.model}:{}})},xX=async({runnerResult:t,interruptedSessionId:e,creditsSpentBeforeWrapUp:r,cliPath:n,config:i,context:s,runner:o,aiGateway:a,cwd:c,persistSteps:u,usageTracker:l,withStageTimer:d,answerFold:f})=>{let p=AX(i),h=new AbortController,m=!1,_=!1,S,b=Object.assign(async v=>{try{l.onAgentOutput()}catch(T){Rs(T)&&!m&&(m=!0,Qd.log("Wrap-up turn spent the credit reserve \u2014 stopping wrap-up",{creditsSpentBeforeWrapUp:r}),K.inc("session.credit_wrapup_aborted",1,{credit_reserve:p}),h.abort())}return u(v)},{flush:u.flush.bind(u)});Qd.log("Running credit wrap-up inference turn",{creditsSpentBeforeWrapUp:r,creditReserve:p});try{await u({steps:[{category:W.WrapUp,message:`You are reaching your usage limit. ${i.mode==="ask"?"Wrapping up and gathering the info found so far.":"Wrapping up and leaving your work in a usable state."}`}],duration:0})}catch{}let R;try{let{runnerResult:v}=await d("inference-credit-wrapup",()=>Wd({cliPath:n,config:i,context:s,runner:o,persistSteps:b,aiGateway:a,cwd:c,contextPrefix:zkt(i),priorAgentSessionId:e,resumeForCreditWrapUp:!0,answerFold:f,forceLowEffortForCreditWrapUp:!0,abortSignal:h.signal}));S=v.resolvedModel,m&&Qd.log("Wrap-up turn was aborted due to budget limit"),R={...HT(t,v),resolvedModel:t.resolvedModel,effort:t.effort,resolvedProviderEffort:t.resolvedProviderEffort}}catch(v){Qd.warn("Credit wrap-up turn failed \u2014 proceeding with pre-wrap-up result",{error:v?.message||v}),K.inc("session.credit_wrapup_failed",1,{credit_reserve:p}),_=!0,R=t}let y=S??t.resolvedModel;return{runnerResult:R,costReport:{creditsSpentBeforeWrapUp:r,creditReserve:p,outcome:_?"failed":m?"aborted":"completed",...y?{model:y}:{}}}};var I1e=t=>{let e,r=!1;return{getActiveTurn:()=>e?"main":r?"fix":"none",getMainTurnAbortSignal:()=>t?e?.signal:void 0,startMainTurn:()=>{e=new AbortController},finishMainTurn:()=>{e=void 0},runFixTurn:async n=>{r=!0;try{return await n()}finally{r=!1}},abortMainTurn:()=>e?.abort()}};var P1e=4e3,jkt=3e4,Jd=re("in_progress_work_preservation"),C1e=async(t,e)=>{if(!e)return null;v1(e);let r=Ld(t.runner),n=null;try{await Promise.race([Promise.all([y1({runnerId:t.id,sessionId:t.sessionId,archive:r,nativeSessionId:e}).then(i=>{n=i}),yv({config:t,nativeSessionArchive:r,nativeSessionId:e}).catch(i=>{Jd.warn("Failed to seed the native session cache before teardown",{error:i?.message||i})})]),new Promise(i=>{setTimeout(i,P1e).unref()})])}catch(i){Jd.warn("Failed to preserve native session before teardown",{error:i?.message||i})}return n},ux=async({config:t,session:e,nativeSessionId:r,stoppedSession:n,erroredSession:i,creditInterrupted:s=!1})=>{let o=i?.reason??n?.stopReason??(e?"credit_limit":"user_cancelled"),a=(e||i)&&!Mn()?jkt:P1e,c=!1,u=!0,l=new Set,d=(y,v)=>{K.inc("session.preservation",1,{reason:o,step:y,outcome:v}),Jd.info("Session preservation",{sessionId:t.sessionId,reason:o,step:y,outcome:v})},f=async(y,v)=>{l.add(y),d(y,"started");try{await v(),u&&d(y,"succeeded")}catch(T){c=!0,u&&d(y,"failed"),Jd.warn("Failed to preserve session artifacts",{reason:o,step:y,error:T})}finally{l.delete(y)}};d("all","started");let p=null,h={},m=[],_=Ld(t.runner);if(r&&_){let y={config:t,nativeSessionArchive:_,nativeSessionId:r};m.push(Promise.allSettled([f("conversation",async()=>{let v=await ZR(y);if(!v)throw new Error("Native session upload returned no archive key");u&&(p=v)}),...!n&&!i&&He().warmNativeResumeEnabled&&t.cache?.dir?[f("cache",async()=>{if(!await yv(y))throw new Error("Native session cache was not saved")})]:[]]))}if(t.mode!=="ask"&&(!i||t.runSha)&&m.push(f("diff",()=>new $n().commitAgentWork({config:t}).then(y=>y.hasChanges?YR({config:t,diff:y.diff,diffBinary:y.diffBinary,resultDiff:y.resultDiff,resultDiffBinary:y.resultDiffBinary}):{}).then(y=>{u&&(h=y)}))),m.length>0){let y=!1,v;if(await Promise.race([Promise.all(m).then(()=>{y=!0}),new Promise(T=>{v=setTimeout(T,a),v.unref()})]),clearTimeout(v),!y){c=!0;for(let T of l)d(T,"failed");Jd.warn("Session preservation exceeded its budget",{reason:o,budgetMs:a}),e&&K.inc("credit_preservation.timed_out",1)}}u=!1,d("session-update","started");let S=Mn(),b=s?{state:"interrupted",interrupt_reason:"credit_limit"}:{result:i?.result??n?.result??e?.error.userMessage??"Cancelled by user",state:i?"error":"cancelled"},R=!1;try{await w_(()=>$r(t.id,t.sessionId,{...b,...e?{credit_limit_exceeded:!0}:{},...r?{native_session_id:r}:{},...p?{native_session_s3_key:p}:{},...h,...e?{metadata:{final_agent_config:e.finalAgentConfig,...e.creditWrapUp?{credit_wrap_up:!0}:{}}}:{}}),{maxRetries:S?2:3,baseDelay:S?100:1e3,onRetry:(y,v)=>{Jd.error(`Error updating agent runner session (attempt ${y}):`,v),Jd.log("Retrying...")}}),R=!0,d("session-update","succeeded")}catch(y){c=!0,d("session-update","failed"),Jd.warn("Could not update session (site may have been deleted)",{error:y})}return d("all",c?"failed":"succeeded"),{sessionUpdated:R}};import qkt from"process";var OX=re("shutdown"),k1e=!1,Bkt,Vkt=async t=>{if(k1e)return;if(k1e=!0,OX.info("Shutting down...",{signal:t}),K.inc("shutdown.started",1,{signal:t,reason:lu()??t,active_session:dJ()}),GTe(t),K.distribution("session.hot_followups",UMe()),!dJ()){let r=Date.now(),n=FMe(),i=zMe();n!==void 0&&K.timing("session.last_linger",r-n),i!==void 0&&K.timing("session.total_linger",r-i)}let e=Bkt?.close().catch(r=>{OX.error("Error closing server during graceful shutdown",r)});await qMe(),await e,await DC(),await Pde(),OX.info("Shutdown complete"),qkt.exit(0)};var N1e=t=>{Vkt(t)};var Cv=re("session_finalization"),M1e=({config:t,teardown:e,withStageTimer:r,cwd:n})=>{let i=!1;return async s=>{switch(s.outcome){case"completed":{Fu(s.artifacts.nativeSessionId),i=!0,await IX({config:t,artifacts:s.artifacts,withStageTimer:r}),await Gkt({cwd:n,pipelineSpan:s.pipelineSpan}),await e.run("completed");return}case"redeployed":{Fu(s.artifacts.nativeSessionId),i=!0,await IX({config:t,artifacts:s.artifacts,withStageTimer:r}),await e.run("completed");return}case"deploy_failed":throw Fu(s.artifacts.nativeSessionId),i=!0,await IX({config:t,artifacts:s.artifacts,withStageTimer:r}),s.error;case"awaiting_input":{let{nativeSessionId:o,pendingInteraction:a}=s;Fu(o),i=!0;let c=await Hkt({config:t,session:s,cwd:n,withStageTimer:r});YMe(a,t.sessionId,c),await e.run("awaiting_input");return}case"credit_interrupted":{let{nativeSessionId:o}=s;Fu(o),i=!0,await $1e({config:t,nativeSessionId:o,interruptReason:"credit_reserve",cwd:n,withStageTimer:r}),Cv.log("Credit reserve reached; session set to interrupted",{sessionId:t.sessionId}),await e.run("credit_interrupted");return}case"credit_limit":{let o=s.error.agentSessionId??s.nativeSessionId;Fu(o);let a=He().creditInterruptEnabled;if(a&&!Mn()&&await Wkt({config:t,session:s,nativeSessionId:o,cwd:n,withStageTimer:r})){await e.run("credit_interrupted");return}let c=a&&Mn()&&lu()==="credit_limit",u=await ux({config:t,session:s,nativeSessionId:o,...c?{creditInterrupted:!0}:{}});if(c&&u.sessionUpdated){await e.run("credit_interrupted");return}await e.run("cancelled"),N1e("credit_limit_cancelled");return}case"api_resource_not_found":{await e.run("errored");try{await $r(t.id,t.sessionId,{result:s.error.userMessage,state:"error",metadata:{final_agent_config:s.finalAgentConfig,...s.creditWrapUp?{credit_wrap_up:!0}:{}}})}catch{Cv.warn("Could not update session (site may have been deleted)")}return}case"user_cancelled":{let o=s.error?.agentSessionId??s.nativeSessionId;Fu(o),await ux({config:t,nativeSessionId:o}),await e.run("cancelled");return}case"auto_shutdown":case"dev_server_stopped":{let o=s.error?.agentSessionId??s.nativeSessionId;Fu(o),await ux({config:t,nativeSessionId:o,stoppedSession:{stopReason:s.outcome,result:D1e(s.error)}}),await e.run("cancelled");return}case"interrupted":case"error":{let{error:o}=s,a=D1e(o),c=o?.agentSessionId??s.nativeSessionId,u=s.outcome==="error"?"error":HTe(lu()),l=!1;if(!i&&u!==void 0){i=!0,Fu(c);try{l=(await ux({config:t,nativeSessionId:c,erroredSession:{reason:u,result:a}})).sessionUpdated}catch(p){Cv.warn("Failed to preserve errored session artifacts",{error:p})}}let d=!i&&s.outcome!=="error"&&!!c,f=d?await C1e(t,c):null;if(await e.run("errored"),l)return;try{await $r(t.id,t.sessionId,{result:a,state:"error",...d?{native_session_id:c}:{},...f?{native_session_s3_key:f}:{}})}catch(p){Cv.error("Failed to update session with error state, retrying with minimal payload:",p);try{await $r(t.id,t.sessionId,{result:"Encountered error when running agent",state:"error"})}catch(h){Cv.error("Failed to mark session as errored:",h)}}return}}}},D1e=t=>{let e=t instanceof Error?t.shortMessage||t.message:"";return e?MAe(hM(e)):"Encountered error when running agent"},Gkt=async({cwd:t,pipelineSpan:e})=>{try{let r=await $C(t??process.cwd());r.aiTotal>0&&e?.setAttributes({"agent.fn_ai_total":r.aiTotal,"agent.fn_ai_v1":r.v1,"agent.fn_ai_v2":r.v2,"agent.fn_ai_v3":r.v3,"agent.fn_ai_unknown":r.unknown})}catch{}},Hkt=async({config:t,session:e,cwd:r,withStageTimer:n})=>n("cleanup",async()=>{let{nativeSessionId:i,pendingInteraction:s}=e,{diffFields:o,nativeSessionS3Key:a}=await L1e({config:t,nativeSessionId:i,cwd:r}),c;try{c=await KMe(t,s,{nativeSessionId:i,nativeSessionS3Key:a??void 0,diffFields:o})}catch(u){throw K.inc("inference.pause_persist_failed",1),o&&K.inc("pending_diff.save",1,{outcome:"failed",step:"persist"}),u}return o&&K.inc("pending_diff.save",1,{outcome:o.diff_produced?"saved":"no_changes"}),c},Ls.timeUnits.minutes(10),{interruptible:!1}),Wkt=async({config:t,session:e,nativeSessionId:r,cwd:n,withStageTimer:i})=>{try{return await $1e({config:t,nativeSessionId:r,interruptReason:"credit_limit",creditLimit:e,cwd:n,withStageTimer:i}),!0}catch(s){return Cv.warn("Failed to interrupt the session at the credit limit, cancelling it instead",{error:s}),!1}},$1e=async({config:t,nativeSessionId:e,interruptReason:r,creditLimit:n,cwd:i,withStageTimer:s})=>s("cleanup",async()=>{let{diffFields:o,nativeSessionS3Key:a}=await L1e({config:t,nativeSessionId:e,cwd:i});try{await $r(t.id,t.sessionId,{state:"interrupted",interrupt_reason:r,...o,...e?{native_session_id:e}:{},...a?{native_session_s3_key:a}:{},...n?{credit_limit_exceeded:!0,metadata:{final_agent_config:n.finalAgentConfig,...n.creditWrapUp?{credit_wrap_up:!0}:{}}}:{}})}catch(c){throw o&&K.inc("pending_diff.save",1,{outcome:"failed",step:"persist"}),c}o&&K.inc("pending_diff.save",1,{outcome:o.diff_produced?"saved":"no_changes"})},Ls.timeUnits.minutes(10),{interruptible:!1}),L1e=async({config:t,nativeSessionId:e,cwd:r})=>{let n=await kMe({config:t,cwd:r}),i=Ld(t.runner),s=await ZR({config:t,nativeSessionArchive:i,nativeSessionId:e});return await yv({config:t,nativeSessionArchive:i,nativeSessionId:e}),{diffFields:n,nativeSessionS3Key:s}},IX=async({config:t,artifacts:e,withStageTimer:r})=>{await r("cleanup",()=>IMe({config:t,...e,nativeSessionArchive:Ld(t.runner)}),Ls.timeUnits.minutes(10),{interruptible:!1})},Fu=t=>{t&&v1(t)};var Ykt=Kkt(import.meta.url),Xd=Ykt("../package.json"),Vr=re("pipeline_index"),kv=3,PX=2,Zkt=["codex","gemini"],pJ=t=>{let{config:e}=t;return pde({agent_runner_id:e.id,session_id:e.sessionId,agent:e.runner,mode:e.mode,orchestrator_version:Xd.version,model:e.model,effort:e.effort},()=>Qkt(t))},Qkt=async({config:t,apiToken:e,cliPath:r="netlify",cwd:n,filter:i,isHotFollowUp:s=!1,enqueuedAt:o,tracing:a={}})=>{let c,u,l=B=>{u=B},d=Date.now(),f="success",p=!1,h,m,_=!1,S,b=!1,{withStageTimer:R}=WTe(Ls.timeUnits.hours(4)),y=d1e({config:t,cliPath:r,cwd:n,withStageTimer:R}),v=p1e({config:t,cwd:n,database:y,stopUsageTracking:()=>c?.stop()}),T,O=M1e({config:t,teardown:v,withStageTimer:R,cwd:n}),C=B=>(T??=B.outcome,O(B)),I=await wde(Xd.version,t.id,a);Vr.log(`Agent runner orchestrator v${Xd.version}`,{featureFlags:He().raw,metrics:kde()});let k={agent:t.runner,mode:t.mode,is_follow_up:t.sessionHistoryContext.length>0,version:Xd.version,fast_init:t.fastInit,credit_wrapup:!1,budget_eligible:!1,budget_constrained:!1,ask_first:!1};$b({...k});let w=!!t.answeredInteraction;v1e({agentRunnerId:t.id,sessionId:t.sessionId,devServerId:process.env.NETLIFY_DEV_SERVER_ID,agent:t.runner,mode:t.mode,version:Xd.version,model:t.model,effort:t.effort,isAnswerResume:w,isHotFollowUp:s}),h1e({isHotFollowUp:s,enqueuedAt:o}),cAe(t.sessionId);try{await fE(ht(),"run-pipeline",{},I,async B=>{await fJ(lJ(),t.runner),B?.setAttributes({"gen_ai.capability.name":t.mode,"session.id":t.sessionId,...process.env.NETLIFY_DEV_SERVER_ID?{"dev_server.id":process.env.NETLIFY_DEV_SERVER_ID}:{}});let{aiGateway:$,context:E,persistSteps:P,runner:M,sha:X}=await R("init",()=>NMe({config:t,apiToken:e,cliPath:r,cwd:n,filter:i,runnerVersion:Xd.version,isHotFollowUp:s}),Ls.timeUnits.minutes(10)),Q=M.runner;He().idleTimeoutEnabled||v.setRunnerCleanup(M.clean),await T1e(t,s),Object.assign(k,UAe(t)),$b({...k});let te=AX(t),xe=x1e(t,te),Ae=I1e(xe),ye,Te=!1,be=0,_e,fe=t.resumeAction==="wrap_up";c=b1e(t.id,t.sessionId,t.sessionCreditLimit,{...xe&&!fe?{creditReserve:te,onCreditReserveReached:()=>{if(!Te){if(Ae.getActiveTurn()!=="main"){Te=!0,RX(Ae.getActiveTurn(),te);return}if(!_e){RX("no_session",te);return}Te=!0,be=c?.getCreditsCost()??0,Vr.log("Credit reserve reached \u2014 interrupting agent to wrap up",{creditsSpentBeforeWrapUp:be,creditReserve:te}),k.credit_wrapup=!0,$b({...k}),K.inc("session.credit_wrapup_triggered",1,{credit_reserve:te}),Ae.abortMainTurn()}}}:{}});let le=oM(t.mode),Ce;t.deployAlias&&t.deployAlias.length>0?Ce=t.deployAlias:(t.deployAlias!==void 0&&!le&&Vr.warn("Received empty deploy alias for a non-prod deploy, falling back to local computation"),Ce=$Se(t.id,process.env.SITE_NAME,le));let J=!1,me=!1,j=Object.assign(async Ne=>{J||(J=!0,m1e({isHotFollowUp:s,enqueuedAt:o}));try{c?.onAgentOutput()}catch(Et){return Rs(Et)?ye??=Et:Vr.warn("Unexpected error in onAgentOutput",{error:Et?.message||Et}),P(Ne)}return!me&&Ne.steps?.some(Et=>Et.category!==W.Environment&&Et.category!==W.SubagentPrompt)&&(me=!0,g1e({isHotFollowUp:s,enqueuedAt:o})),P(Ne)},{flush:P.flush.bind(P)});if(t.sha=X,t.mode==="redeploy"){let Ne=await l$e({cliPath:r,config:t,filter:i,deploySubdomain:Ce,isProdDeploy:le,withStageTimer:R});await c?.stop(),await C({outcome:"redeployed",artifacts:Ne});return}let U=XMe(),z=t.mode==="ask",H;t.mode==="create"&&!t.resumeAction&&(H=(await R("create",()=>jAe({config:t,cwd:n}))).additionalContext),H=await ASe(H,t);let Z=await y.prepare({deploySubdomain:Ce,isProdDeploy:le});Z&&(H=[Z,H].filter(Boolean).join(`
|
|
712
|
+
`)}var Hh=re("usage_tracker"),Dkt=4e3,Mkt=5e3,$kt=2e4,Lkt=(t,e,r)=>t===!0||r!=null&&e!=null&&e>=r,Ukt=(t,e,r)=>e!=null&&e>0&&r!=null&&t!=null&&e-t<=r,b1e=(t,e,r,{creditReserve:n,onCreditReserveReached:i}={})=>{let s=!1,o=!1,a=!1,c=!1,u,l,d,f=r,p,h=i!=null&&n!=null,m=()=>{p&&(clearInterval(p),p=void 0)},_=O=>{m(),p=setInterval(()=>{b()},O),p.unref?.()},S=async()=>{try{let O=await GC(t,e);Hh.log("Usage update response",{usage:O?.usage});let C=O?.usage?.total_credits_cost;C!=null&&(u=C);let I=O?.enforced_credits_cap;if(I!=null&&I!==f){let w=f==null;f=I,Hh.log("Took the session credit limit from a usage poll",{sessionCreditLimit:f,totalCreditsCost:C,isFirstLimit:w}),w&&K.inc("session.credit_cap_late_arrival",1)}let k=Lkt(O?.credit_limit_exceeded,C,f);if(k&&(Hh.log("Credit limit exceeded",{totalCreditsCost:C,sessionCreditLimit:f}),a||(l=Date.now(),d=C??u??0,_($kt)),a=!0),h&&!c&&!k&&Ukt(C,f,n)){c=!0,Hh.log("Credit reserve reached",{totalCreditsCost:C,sessionCreditLimit:f,creditReserve:n});try{i()}catch(w){Hh.warn("onCreditReserveReached callback threw",{error:w?.message||w})}}}catch(O){Hh.warn("Failed to update usage",{error:O?.message||O})}},b=KN(S,Dkt);return{onAgentOutput:()=>{if(a)throw new As("AI credit usage exceeded enforced limit.",503,"Credit limit reached. Check credit limits to continue using Agent Runners.");o||(s=!0,p||_(Mkt))},stop:async()=>{o||(o=!0,m(),s&&(b.cancel(),Hh.log("Sending final usage update"),await S(),l!==void 0&&(K.timing("credit_limit.overage_duration",Date.now()-l),K.distribution("credit_limit.overage_credits",Math.max(0,(u??d??0)-(d??0))))))},getCreditsCost:()=>u,getSessionCreditLimit:()=>f}};var w1e=re("session_credit_limit"),Fkt=async t=>{if(t.sessionCreditLimit!=null)return{limit:t.sessionCreditLimit,source:"env"};try{let e=(await GC(t.id,t.sessionId))?.enforced_credits_cap;if(e!=null)return w1e.log("Resolved the session credit limit from the usage endpoint",{limit:e}),{limit:e,source:"usage"}}catch(e){w1e.warn("Usage call for the session credit limit failed",{error:e?.message||e})}return{source:"none"}},T1e=async(t,e=!1)=>{let{limit:r,source:n}=await Fkt(t);t.sessionCreditLimit=r,K.inc("session.credit_cap_source",1,{source:n,hot_follow_up:e})};var Qd=re("credit_wrapup"),A1e="low",zkt=t=>{if(t.mode==="ask")return T2;if(t.mode==="normal")return A2;let e=YT(t);return ZT(t,e)?b2:w2},R1e=t=>typeof t=="number"?t:void 0,AX=t=>{let e=He(),r=e.creditWrapUpReserveByModeAgentAndModel[t.mode]?.[t.runner];return R1e(t.model?r?.models?.[t.model]:void 0)??R1e(r?.agent)??e.creditWrapUpReserve},x1e=(t,e)=>{if(e<=0)return!1;let r=He();return t.mode==="create"?r.creditWrapUpEnabled:t.mode==="ask"||t.mode==="normal"?r.creditWrapUpNormalEnabled:!1},RX=(t,e)=>{if(t==="fix"){Qd.log("Credit reserve reached outside of the main inference turn \u2014 letting the fix finish without a wrap-up"),K.inc("session.credit_wrapup_skipped_fix_turn",1,{credit_reserve:e});return}if(t==="no_session"){Qd.warn("Credit reserve reached but no session id yet \u2014 skipping wrap-up interrupt"),K.inc("session.credit_wrapup_skipped_no_session",1,{credit_reserve:e});return}Qd.log("Credit reserve reached with no turn to interrupt \u2014 the agent had already finished")},O1e=(t,e,r)=>{if(e==null)return;let n=Math.max(0,e-t.creditsSpentBeforeWrapUp);Qd.log("Credit wrap-up cost",{credits:n,creditsCostAtSessionEnd:e,effort:A1e,inferenceAfterWrapUp:r,...t}),K.distribution("session.credit_wrapup_cost",n,{outcome:t.outcome,effort:A1e,credit_reserve:t.creditReserve,inference_after_wrap_up:r,...t.model?{model:t.model}:{}})},xX=async({runnerResult:t,interruptedSessionId:e,creditsSpentBeforeWrapUp:r,cliPath:n,config:i,context:s,runner:o,aiGateway:a,cwd:c,persistSteps:u,usageTracker:l,withStageTimer:d,answerFold:f})=>{let p=AX(i),h=new AbortController,m=!1,_=!1,S,b=Object.assign(async v=>{try{l.onAgentOutput()}catch(T){Rs(T)&&!m&&(m=!0,Qd.log("Wrap-up turn spent the credit reserve \u2014 stopping wrap-up",{creditsSpentBeforeWrapUp:r}),K.inc("session.credit_wrapup_aborted",1,{credit_reserve:p}),h.abort())}return u(v)},{flush:u.flush.bind(u)});Qd.log("Running credit wrap-up inference turn",{creditsSpentBeforeWrapUp:r,creditReserve:p});try{await u({steps:[{category:W.WrapUp,message:`You are reaching your usage limit. ${i.mode==="ask"?"Wrapping up and gathering the info found so far.":"Wrapping up and leaving your work in a usable state."}`}],duration:0})}catch{}let R;try{let{runnerResult:v}=await d("inference-credit-wrapup",()=>Wd({cliPath:n,config:i,context:s,runner:o,persistSteps:b,aiGateway:a,cwd:c,contextPrefix:zkt(i),priorAgentSessionId:e,resumeForCreditWrapUp:!0,answerFold:f,forceLowEffortForCreditWrapUp:!0,abortSignal:h.signal}));S=v.resolvedModel,m&&Qd.log("Wrap-up turn was aborted due to budget limit"),R={...HT(t,v),resolvedModel:t.resolvedModel,effort:t.effort,resolvedProviderEffort:t.resolvedProviderEffort}}catch(v){Qd.warn("Credit wrap-up turn failed \u2014 proceeding with pre-wrap-up result",{error:v?.message||v}),K.inc("session.credit_wrapup_failed",1,{credit_reserve:p}),_=!0,R=t}let y=S??t.resolvedModel;return{runnerResult:R,costReport:{creditsSpentBeforeWrapUp:r,creditReserve:p,outcome:_?"failed":m?"aborted":"completed",...y?{model:y}:{}}}};var I1e=t=>{let e,r=!1;return{getActiveTurn:()=>e?"main":r?"fix":"none",getMainTurnAbortSignal:()=>t?e?.signal:void 0,startMainTurn:()=>{e=new AbortController},finishMainTurn:()=>{e=void 0},runFixTurn:async n=>{r=!0;try{return await n()}finally{r=!1}},abortMainTurn:()=>e?.abort()}};var P1e=4e3,jkt=3e4,Jd=re("in_progress_work_preservation"),C1e=async(t,e)=>{if(!e)return null;v1(e);let r=Ld(t.runner),n=null;try{await Promise.race([Promise.all([y1({runnerId:t.id,sessionId:t.sessionId,archive:r,nativeSessionId:e}).then(i=>{n=i}),yv({config:t,nativeSessionArchive:r,nativeSessionId:e}).catch(i=>{Jd.warn("Failed to seed the native session cache before teardown",{error:i?.message||i})})]),new Promise(i=>{setTimeout(i,P1e).unref()})])}catch(i){Jd.warn("Failed to preserve native session before teardown",{error:i?.message||i})}return n},ux=async({config:t,session:e,nativeSessionId:r,stoppedSession:n,erroredSession:i,creditInterrupted:s=!1})=>{let o=i?.reason??n?.stopReason??(e?"credit_limit":"user_cancelled"),a=(e||i)&&!Mn()?jkt:P1e,c=!1,u=!0,l=new Set,d=(y,v)=>{K.inc("session.preservation",1,{reason:o,step:y,outcome:v}),Jd.info("Session preservation",{sessionId:t.sessionId,reason:o,step:y,outcome:v})},f=async(y,v)=>{l.add(y),d(y,"started");try{await v(),u&&d(y,"succeeded")}catch(T){c=!0,u&&d(y,"failed"),Jd.warn("Failed to preserve session artifacts",{reason:o,step:y,error:T})}finally{l.delete(y)}};d("all","started");let p=null,h={},m=[],_=Ld(t.runner);if(r&&_){let y={config:t,nativeSessionArchive:_,nativeSessionId:r};m.push(Promise.allSettled([f("conversation",async()=>{let v=await ZR(y);if(!v)throw new Error("Native session upload returned no archive key");u&&(p=v)}),...!n&&!i&&He().warmNativeResumeEnabled&&t.cache?.dir?[f("cache",async()=>{if(!await yv(y))throw new Error("Native session cache was not saved")})]:[]]))}if(t.mode!=="ask"&&(!i||t.runSha)&&m.push(f("diff",()=>new $n().commitAndCreateDiffs({config:t}).then(y=>y.hasChanges?YR({config:t,diff:y.diff,diffBinary:y.diffBinary,resultDiff:y.resultDiff,resultDiffBinary:y.resultDiffBinary}):{}).then(y=>{u&&(h=y)}))),m.length>0){let y=!1,v;if(await Promise.race([Promise.all(m).then(()=>{y=!0}),new Promise(T=>{v=setTimeout(T,a),v.unref()})]),clearTimeout(v),!y){c=!0;for(let T of l)d(T,"failed");Jd.warn("Session preservation exceeded its budget",{reason:o,budgetMs:a}),e&&K.inc("credit_preservation.timed_out",1)}}u=!1,d("session-update","started");let S=Mn(),b=s?{state:"interrupted",interrupt_reason:"credit_limit"}:{result:i?.result??n?.result??e?.error.userMessage??"Cancelled by user",state:i?"error":"cancelled"},R=!1;try{await w_(()=>$r(t.id,t.sessionId,{...b,...e?{credit_limit_exceeded:!0}:{},...r?{native_session_id:r}:{},...p?{native_session_s3_key:p}:{},...h,...e?{metadata:{final_agent_config:e.finalAgentConfig,...e.creditWrapUp?{credit_wrap_up:!0}:{}}}:{}}),{maxRetries:S?2:3,baseDelay:S?100:1e3,onRetry:(y,v)=>{Jd.error(`Error updating agent runner session (attempt ${y}):`,v),Jd.log("Retrying...")}}),R=!0,d("session-update","succeeded")}catch(y){c=!0,d("session-update","failed"),Jd.warn("Could not update session (site may have been deleted)",{error:y})}return d("all",c?"failed":"succeeded"),{sessionUpdated:R}};import qkt from"process";var OX=re("shutdown"),k1e=!1,Bkt,Vkt=async t=>{if(k1e)return;if(k1e=!0,OX.info("Shutting down...",{signal:t}),K.inc("shutdown.started",1,{signal:t,reason:lu()??t,active_session:dJ()}),GTe(t),K.distribution("session.hot_followups",UMe()),!dJ()){let r=Date.now(),n=FMe(),i=zMe();n!==void 0&&K.timing("session.last_linger",r-n),i!==void 0&&K.timing("session.total_linger",r-i)}let e=Bkt?.close().catch(r=>{OX.error("Error closing server during graceful shutdown",r)});await qMe(),await e,await DC(),await Pde(),OX.info("Shutdown complete"),qkt.exit(0)};var N1e=t=>{Vkt(t)};var Cv=re("session_finalization"),M1e=({config:t,teardown:e,withStageTimer:r,cwd:n})=>{let i=!1;return async s=>{switch(s.outcome){case"completed":{Fu(s.artifacts.nativeSessionId),i=!0,await IX({config:t,artifacts:s.artifacts,withStageTimer:r}),await Gkt({cwd:n,pipelineSpan:s.pipelineSpan}),await e.run("completed");return}case"redeployed":{Fu(s.artifacts.nativeSessionId),i=!0,await IX({config:t,artifacts:s.artifacts,withStageTimer:r}),await e.run("completed");return}case"deploy_failed":throw Fu(s.artifacts.nativeSessionId),i=!0,await IX({config:t,artifacts:s.artifacts,withStageTimer:r}),s.error;case"awaiting_input":{let{nativeSessionId:o,pendingInteraction:a}=s;Fu(o),i=!0;let c=await Hkt({config:t,session:s,cwd:n,withStageTimer:r});YMe(a,t.sessionId,c),await e.run("awaiting_input");return}case"credit_interrupted":{let{nativeSessionId:o}=s;Fu(o),i=!0,await $1e({config:t,nativeSessionId:o,interruptReason:"credit_reserve",cwd:n,withStageTimer:r}),Cv.log("Credit reserve reached; session set to interrupted",{sessionId:t.sessionId}),await e.run("credit_interrupted");return}case"credit_limit":{let o=s.error.agentSessionId??s.nativeSessionId;Fu(o);let a=He().creditInterruptEnabled;if(a&&!Mn()&&await Wkt({config:t,session:s,nativeSessionId:o,cwd:n,withStageTimer:r})){await e.run("credit_interrupted");return}let c=a&&Mn()&&lu()==="credit_limit",u=await ux({config:t,session:s,nativeSessionId:o,...c?{creditInterrupted:!0}:{}});if(c&&u.sessionUpdated){await e.run("credit_interrupted");return}await e.run("cancelled"),N1e("credit_limit_cancelled");return}case"api_resource_not_found":{await e.run("errored");try{await $r(t.id,t.sessionId,{result:s.error.userMessage,state:"error",metadata:{final_agent_config:s.finalAgentConfig,...s.creditWrapUp?{credit_wrap_up:!0}:{}}})}catch{Cv.warn("Could not update session (site may have been deleted)")}return}case"user_cancelled":{let o=s.error?.agentSessionId??s.nativeSessionId;Fu(o),await ux({config:t,nativeSessionId:o}),await e.run("cancelled");return}case"auto_shutdown":case"dev_server_stopped":{let o=s.error?.agentSessionId??s.nativeSessionId;Fu(o),await ux({config:t,nativeSessionId:o,stoppedSession:{stopReason:s.outcome,result:D1e(s.error)}}),await e.run("cancelled");return}case"interrupted":case"error":{let{error:o}=s,a=D1e(o),c=o?.agentSessionId??s.nativeSessionId,u=s.outcome==="error"?"error":HTe(lu()),l=!1;if(!i&&u!==void 0){i=!0,Fu(c);try{l=(await ux({config:t,nativeSessionId:c,erroredSession:{reason:u,result:a}})).sessionUpdated}catch(p){Cv.warn("Failed to preserve errored session artifacts",{error:p})}}let d=!i&&s.outcome!=="error"&&!!c,f=d?await C1e(t,c):null;if(await e.run("errored"),l)return;try{await $r(t.id,t.sessionId,{result:a,state:"error",...d?{native_session_id:c}:{},...f?{native_session_s3_key:f}:{}})}catch(p){Cv.error("Failed to update session with error state, retrying with minimal payload:",p);try{await $r(t.id,t.sessionId,{result:"Encountered error when running agent",state:"error"})}catch(h){Cv.error("Failed to mark session as errored:",h)}}return}}}},D1e=t=>{let e=t instanceof Error?t.shortMessage||t.message:"";return e?MAe(hM(e)):"Encountered error when running agent"},Gkt=async({cwd:t,pipelineSpan:e})=>{try{let r=await $C(t??process.cwd());r.aiTotal>0&&e?.setAttributes({"agent.fn_ai_total":r.aiTotal,"agent.fn_ai_v1":r.v1,"agent.fn_ai_v2":r.v2,"agent.fn_ai_v3":r.v3,"agent.fn_ai_unknown":r.unknown})}catch{}},Hkt=async({config:t,session:e,cwd:r,withStageTimer:n})=>n("cleanup",async()=>{let{nativeSessionId:i,pendingInteraction:s}=e,{diffFields:o,nativeSessionS3Key:a}=await L1e({config:t,nativeSessionId:i,cwd:r}),c;try{c=await KMe(t,s,{nativeSessionId:i,nativeSessionS3Key:a??void 0,diffFields:o})}catch(u){throw K.inc("inference.pause_persist_failed",1),o&&K.inc("pending_diff.save",1,{outcome:"failed",step:"persist"}),u}return o&&K.inc("pending_diff.save",1,{outcome:o.diff_produced?"saved":"no_changes"}),c},Ls.timeUnits.minutes(10),{interruptible:!1}),Wkt=async({config:t,session:e,nativeSessionId:r,cwd:n,withStageTimer:i})=>{try{return await $1e({config:t,nativeSessionId:r,interruptReason:"credit_limit",creditLimit:e,cwd:n,withStageTimer:i}),!0}catch(s){return Cv.warn("Failed to interrupt the session at the credit limit, cancelling it instead",{error:s}),!1}},$1e=async({config:t,nativeSessionId:e,interruptReason:r,creditLimit:n,cwd:i,withStageTimer:s})=>s("cleanup",async()=>{let{diffFields:o,nativeSessionS3Key:a}=await L1e({config:t,nativeSessionId:e,cwd:i});try{await $r(t.id,t.sessionId,{state:"interrupted",interrupt_reason:r,...o,...e?{native_session_id:e}:{},...a?{native_session_s3_key:a}:{},...n?{credit_limit_exceeded:!0,metadata:{final_agent_config:n.finalAgentConfig,...n.creditWrapUp?{credit_wrap_up:!0}:{}}}:{}})}catch(c){throw o&&K.inc("pending_diff.save",1,{outcome:"failed",step:"persist"}),c}o&&K.inc("pending_diff.save",1,{outcome:o.diff_produced?"saved":"no_changes"})},Ls.timeUnits.minutes(10),{interruptible:!1}),L1e=async({config:t,nativeSessionId:e,cwd:r})=>{let n=await kMe({config:t,cwd:r}),i=Ld(t.runner),s=await ZR({config:t,nativeSessionArchive:i,nativeSessionId:e});return await yv({config:t,nativeSessionArchive:i,nativeSessionId:e}),{diffFields:n,nativeSessionS3Key:s}},IX=async({config:t,artifacts:e,withStageTimer:r})=>{await r("cleanup",()=>IMe({config:t,...e,nativeSessionArchive:Ld(t.runner)}),Ls.timeUnits.minutes(10),{interruptible:!1})},Fu=t=>{t&&v1(t)};var Ykt=Kkt(import.meta.url),Xd=Ykt("../package.json"),Vr=re("pipeline_index"),kv=3,PX=2,Zkt=["codex","gemini"],pJ=t=>{let{config:e}=t;return pde({agent_runner_id:e.id,session_id:e.sessionId,agent:e.runner,mode:e.mode,orchestrator_version:Xd.version,model:e.model,effort:e.effort},()=>Qkt(t))},Qkt=async({config:t,apiToken:e,cliPath:r="netlify",cwd:n,filter:i,isHotFollowUp:s=!1,enqueuedAt:o,tracing:a={}})=>{let c,u,l=B=>{u=B},d=Date.now(),f="success",p=!1,h,m,_=!1,S,b=!1,{withStageTimer:R}=WTe(Ls.timeUnits.hours(4)),y=d1e({config:t,cliPath:r,cwd:n,withStageTimer:R}),v=p1e({config:t,cwd:n,database:y,stopUsageTracking:()=>c?.stop()}),T,O=M1e({config:t,teardown:v,withStageTimer:R,cwd:n}),C=B=>(T??=B.outcome,O(B)),I=await wde(Xd.version,t.id,a);Vr.log(`Agent runner orchestrator v${Xd.version}`,{featureFlags:He().raw,metrics:kde()});let k={agent:t.runner,mode:t.mode,is_follow_up:t.sessionHistoryContext.length>0,version:Xd.version,fast_init:t.fastInit,credit_wrapup:!1,budget_eligible:!1,budget_constrained:!1,ask_first:!1};$b({...k});let w=!!t.answeredInteraction;v1e({agentRunnerId:t.id,sessionId:t.sessionId,devServerId:process.env.NETLIFY_DEV_SERVER_ID,agent:t.runner,mode:t.mode,version:Xd.version,model:t.model,effort:t.effort,isAnswerResume:w,isHotFollowUp:s}),h1e({isHotFollowUp:s,enqueuedAt:o}),cAe(t.sessionId);try{await fE(ht(),"run-pipeline",{},I,async B=>{await fJ(lJ(),t.runner),B?.setAttributes({"gen_ai.capability.name":t.mode,"session.id":t.sessionId,...process.env.NETLIFY_DEV_SERVER_ID?{"dev_server.id":process.env.NETLIFY_DEV_SERVER_ID}:{}});let{aiGateway:$,context:E,persistSteps:P,runner:M,sha:X}=await R("init",()=>NMe({config:t,apiToken:e,cliPath:r,cwd:n,filter:i,runnerVersion:Xd.version,isHotFollowUp:s}),Ls.timeUnits.minutes(10)),Q=M.runner;He().idleTimeoutEnabled||v.setRunnerCleanup(M.clean),await T1e(t,s),Object.assign(k,UAe(t)),$b({...k});let te=AX(t),xe=x1e(t,te),Ae=I1e(xe),ye,Te=!1,be=0,_e,fe=t.resumeAction==="wrap_up";c=b1e(t.id,t.sessionId,t.sessionCreditLimit,{...xe&&!fe?{creditReserve:te,onCreditReserveReached:()=>{if(!Te){if(Ae.getActiveTurn()!=="main"){Te=!0,RX(Ae.getActiveTurn(),te);return}if(!_e){RX("no_session",te);return}Te=!0,be=c?.getCreditsCost()??0,Vr.log("Credit reserve reached \u2014 interrupting agent to wrap up",{creditsSpentBeforeWrapUp:be,creditReserve:te}),k.credit_wrapup=!0,$b({...k}),K.inc("session.credit_wrapup_triggered",1,{credit_reserve:te}),Ae.abortMainTurn()}}}:{}});let le=oM(t.mode),Ce;t.deployAlias&&t.deployAlias.length>0?Ce=t.deployAlias:(t.deployAlias!==void 0&&!le&&Vr.warn("Received empty deploy alias for a non-prod deploy, falling back to local computation"),Ce=$Se(t.id,process.env.SITE_NAME,le));let J=!1,me=!1,j=Object.assign(async Ne=>{J||(J=!0,m1e({isHotFollowUp:s,enqueuedAt:o}));try{c?.onAgentOutput()}catch(Et){return Rs(Et)?ye??=Et:Vr.warn("Unexpected error in onAgentOutput",{error:Et?.message||Et}),P(Ne)}return!me&&Ne.steps?.some(Et=>Et.category!==W.Environment&&Et.category!==W.SubagentPrompt)&&(me=!0,g1e({isHotFollowUp:s,enqueuedAt:o})),P(Ne)},{flush:P.flush.bind(P)});if(t.sha=X,t.mode==="redeploy"){let Ne=await l$e({cliPath:r,config:t,filter:i,deploySubdomain:Ce,isProdDeploy:le,withStageTimer:R});await c?.stop(),await C({outcome:"redeployed",artifacts:Ne});return}let U=XMe(),z=t.mode==="ask",H;t.mode==="create"&&!t.resumeAction&&(H=(await R("create",()=>jAe({config:t,cwd:n}))).additionalContext),H=await ASe(H,t);let Z=await y.prepare({deploySubdomain:Ce,isProdDeploy:le});Z&&(H=[Z,H].filter(Boolean).join(`
|
|
713
713
|
|
|
714
714
|
`));let ae=async()=>{let Ne=await i$e(t,n);_=!0;let Et=await xX({runnerResult:{steps:[],duration:0},interruptedSessionId:Ne,creditsSpentBeforeWrapUp:c.getCreditsCost()??0,cliPath:r,config:t,context:E,runner:Q,aiGateway:$,cwd:n,persistSteps:P,usageTracker:c,withStageTimer:R,answerFold:U});return S=Et.costReport,{runnerResult:Et.runnerResult,nativeResume:!!Ne}};Ae.startMainTurn();let ee=await R("inference",async()=>{if(fe)return ae();try{return await Wd({cliPath:r,config:t,context:E,runner:Q,persistSteps:j,aiGateway:$,additionalContext:H,cwd:n,answerFold:U,abortSignal:Ae.getMainTurnAbortSignal(),onSessionId:Ne=>{_e=Ne,u=Ne}})}catch(Ne){if(!(Ne instanceof gg)||t.mode!=="rebase"&&t.mode!=="conflict_resolution")throw Ne;for(let Et of Zkt){if(ye&&Rs(ye))throw ye;if(Et===t.runner)continue;let aa=JS[Et];if(aa){Vr.log(`Primary runner ${t.runner} failed in ${t.mode} mode, falling back to ${Et}`),$b({...k,agent:Et}),_e=void 0,u=void 0,await fJ(lJ(),Et);try{let ji=await Wd({cliPath:r,config:{...t,runner:Et},context:E,runner:aa.runner,persistSteps:j,aiGateway:$,additionalContext:H,cwd:n,answerFold:U,abortSignal:Ae.getMainTurnAbortSignal(),onSessionId:ds=>{_e=ds,u=ds}});return t.runner=Et,Q=aa.runner,He().idleTimeoutEnabled||v.setRunnerCleanup(aa.clean),ji}catch(ji){if(Rs(ji))throw ji;Vr.error(`Fallback runner ${Et} also failed`,{error:String(ji)})}}}throw Ne}}).finally(Ae.finishMainTurn),ue=ee.runnerResult;u=ue.agentSessionId??u,p=ee.nativeResume??!1,h=ue.resolvedModel,m=ue.effort;let $e=async(Ne,Et)=>{let aa=await y.currentContext(),{runnerResult:ji}=await Ae.runFixTurn(()=>R(Ne,()=>Wd({cliPath:r,config:t,context:E,runner:Q,persistSteps:j,aiGateway:$,buildErrors:Et,additionalContext:aa,priorAgentSessionId:u,onSessionId:l,answerFold:U}))).catch(ds=>{throw u=ds?.agentSessionId??u,ds});if(u=ji.agentSessionId??u,ye)throw Object.assign(ye,{agentSessionId:u}),ye;ue=HT(ue,ji)},ot=ue.agentSessionId,Ie=xe&&Te&&ue.aborted&&!ye;if(Ie&&He().creditInterruptEnabled&&ot){await C({outcome:"credit_interrupted",nativeSessionId:ot}),f="credit_interrupted";return}if(Ie&&ot&&c){_=!0;let Ne=await xX({runnerResult:ue,interruptedSessionId:ot,creditsSpentBeforeWrapUp:be,cliPath:r,config:t,context:E,runner:Q,aiGateway:$,cwd:n,persistSteps:P,usageTracker:c,withStageTimer:R,answerFold:U});ue=Ne.runnerResult,u=ue.agentSessionId??u,S=Ne.costReport}if(t.mode==="create"&&await zAe(n??process.cwd()),ye)throw Object.assign(ye,{agentSessionId:ue.agentSessionId}),ye;if(ue.pendingInteraction){await C({outcome:"awaiting_input",pendingInteraction:ue.pendingInteraction,nativeSessionId:ue.agentSessionId}),f="awaiting_input";return}let Ke=await y.generateMigrations();if(Ke.error){Vr.log("Migration generation failed, running inference to fix the issue"),await $e("inference-migration-fix",[`Running \`drizzle-kit generate\` to generate database migrations failed with the following error:
|
|
715
715
|
|