goatchain 0.0.2 → 0.0.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 +173 -236
- package/README.zh.md +430 -0
- package/dist/acp-adapter/ACPAgent.d.ts +63 -0
- package/dist/acp-adapter/ProtocolConverter.d.ts +48 -0
- package/dist/acp-adapter/SessionRouter.d.ts +50 -0
- package/dist/acp-adapter/index.d.ts +12 -0
- package/dist/acp-adapter/types.d.ts +95 -0
- package/dist/acp-server.d.ts +21 -0
- package/dist/agent/agent.d.ts +196 -0
- package/dist/agent/errors.d.ts +29 -0
- package/dist/agent/hooks/index.d.ts +2 -0
- package/dist/agent/hooks/manager.d.ts +8 -0
- package/dist/agent/hooks/types.d.ts +19 -0
- package/dist/agent/index.d.ts +14 -0
- package/dist/agent/middleware.d.ts +162 -0
- package/dist/agent/tokenCounter.d.ts +55 -0
- package/dist/agent/types.d.ts +247 -0
- package/dist/index.d.ts +21 -3328
- package/dist/index.js +424 -140
- package/dist/middleware/checkpointMiddleware.d.ts +29 -0
- package/dist/middleware/commitModeMiddleware.d.ts +93 -0
- package/dist/middleware/contextCompressionMiddleware.d.ts +131 -0
- package/dist/middleware/gitUtils.d.ts +119 -0
- package/dist/middleware/parallelSubagentMiddleware.d.ts +83 -0
- package/dist/middleware/planModeMiddleware.d.ts +80 -0
- package/dist/middleware/utils.d.ts +58 -0
- package/dist/model/adapter.d.ts +14 -0
- package/dist/model/createModel.d.ts +168 -0
- package/dist/model/errors.d.ts +14 -0
- package/dist/model/health.d.ts +35 -0
- package/dist/model/index.d.ts +7 -0
- package/dist/model/openai/createOpenAIAdapter.d.ts +23 -0
- package/dist/model/router.d.ts +17 -0
- package/dist/model/types.d.ts +190 -0
- package/dist/model/utils/http.d.ts +15 -0
- package/dist/model/utils/id.d.ts +1 -0
- package/dist/model/utils/retry.d.ts +142 -0
- package/dist/session/base.d.ts +1 -0
- package/dist/session/executors/ParallelTaskExecutor.d.ts +16 -0
- package/dist/session/executors/ToolExecutor.d.ts +37 -0
- package/dist/session/handlers/ApprovalHandler.d.ts +6 -0
- package/dist/session/handlers/CheckpointManager.d.ts +10 -0
- package/dist/session/index.d.ts +4 -0
- package/dist/session/manager.d.ts +35 -0
- package/dist/session/session.d.ts +159 -0
- package/dist/session/stateStoreSessionManager.d.ts +36 -0
- package/dist/session/utils/AsyncQueue.d.ts +7 -0
- package/dist/session/utils/AutoSaveManager.d.ts +6 -0
- package/dist/state/FileStateStore.d.ts +72 -0
- package/dist/state/InMemoryStateStore.d.ts +46 -0
- package/dist/state/index.d.ts +6 -0
- package/dist/state/stateStore.d.ts +181 -0
- package/dist/state/types.d.ts +85 -0
- package/dist/subagent/file-search-specialist.d.ts +16 -0
- package/dist/subagent/index.d.ts +7 -0
- package/dist/tool/FilteredToolRegistry.d.ts +82 -0
- package/dist/tool/base.d.ts +57 -0
- package/dist/tool/builtin/askUser.d.ts +90 -0
- package/dist/tool/builtin/astGrepCli.d.ts +37 -0
- package/dist/tool/builtin/astGrepFormat.d.ts +4 -0
- package/dist/tool/builtin/astGrepReplace.d.ts +71 -0
- package/dist/tool/builtin/astGrepSearch.d.ts +101 -0
- package/dist/tool/builtin/bash.d.ts +96 -0
- package/dist/tool/builtin/edit.d.ts +82 -0
- package/dist/tool/builtin/enterPlanMode.d.ts +58 -0
- package/dist/tool/builtin/exitPlanMode.d.ts +48 -0
- package/dist/tool/builtin/glob.d.ts +70 -0
- package/dist/tool/builtin/grep.d.ts +122 -0
- package/dist/tool/builtin/index.d.ts +30 -0
- package/dist/tool/builtin/read.d.ts +127 -0
- package/dist/tool/builtin/skill.d.ts +111 -0
- package/dist/tool/builtin/task.d.ts +132 -0
- package/dist/tool/builtin/todoPlan.d.ts +52 -0
- package/dist/tool/builtin/todoWrite.d.ts +94 -0
- package/dist/tool/builtin/webFetch.d.ts +62 -0
- package/dist/tool/builtin/webSearch.d.ts +89 -0
- package/dist/tool/builtin/write.d.ts +103 -0
- package/dist/tool/index.d.ts +6 -0
- package/dist/tool/registry.d.ts +55 -0
- package/dist/tool/types.d.ts +107 -0
- package/dist/types/common.d.ts +53 -0
- package/dist/types/event.d.ts +217 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/message.d.ts +44 -0
- package/dist/types/snapshot.d.ts +329 -0
- package/package.json +35 -28
package/dist/index.js
CHANGED
|
@@ -1,118 +1,262 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
<summary>
|
|
44
|
-
1. Primary Request and Intent:
|
|
45
|
-
[Detailed description]
|
|
46
|
-
|
|
47
|
-
2. Key Technical Concepts:
|
|
48
|
-
- [Concept 1]
|
|
49
|
-
- [Concept 2]
|
|
50
|
-
- [...]
|
|
51
|
-
|
|
52
|
-
3. Files and Code Sections:
|
|
53
|
-
- [File Name 1]
|
|
54
|
-
- [Summary of why this file is important]
|
|
55
|
-
- [Summary of the changes made to this file, if any]
|
|
56
|
-
- [Important Code Snippet]
|
|
57
|
-
- [File Name 2]
|
|
58
|
-
- [Important Code Snippet]
|
|
59
|
-
- [...]
|
|
60
|
-
|
|
61
|
-
4. Errors and fixes:
|
|
62
|
-
- [Detailed description of error 1]:
|
|
63
|
-
- [How you fixed the error]
|
|
64
|
-
- [User feedback on the error if any]
|
|
65
|
-
- [...]
|
|
66
|
-
|
|
67
|
-
5. Problem Solving:
|
|
68
|
-
[Description of solved problems and ongoing troubleshooting]
|
|
69
|
-
|
|
70
|
-
6. All user messages:
|
|
71
|
-
- [Detailed non tool use user message]
|
|
72
|
-
- [...]
|
|
73
|
-
|
|
74
|
-
7. Pending Tasks:
|
|
75
|
-
- [Task 1]
|
|
76
|
-
- [Task 2]
|
|
77
|
-
- [...]
|
|
78
|
-
|
|
79
|
-
8. Current Work:
|
|
80
|
-
[Precise description of current work]
|
|
81
|
-
|
|
82
|
-
9. Optional Next Step:
|
|
83
|
-
[Optional Next step to take]
|
|
84
|
-
|
|
85
|
-
</summary>
|
|
86
|
-
</example>
|
|
87
|
-
|
|
88
|
-
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
|
|
89
|
-
|
|
90
|
-
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
|
|
91
|
-
<example>
|
|
92
|
-
## Compact Instructions
|
|
93
|
-
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
|
|
94
|
-
</example>
|
|
95
|
-
|
|
96
|
-
<example>
|
|
97
|
-
# Summary instructions
|
|
98
|
-
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
|
|
99
|
-
</example>
|
|
100
|
-
|
|
101
|
-
Existing summary (may be empty):
|
|
1
|
+
// @bun
|
|
2
|
+
var CJ=Object.create;var{getPrototypeOf:xJ,defineProperty:R7,getOwnPropertyNames:RJ}=Object;var yJ=Object.prototype.hasOwnProperty;var y7=($,Z,Y)=>{Y=$!=null?CJ(xJ($)):{};let W=Z||!$||!$.__esModule?R7(Y,"default",{value:$,enumerable:!0}):Y;for(let J of RJ($))if(!yJ.call(W,J))R7(W,J,{get:()=>$[J],enumerable:!0});return W};var d=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var V1=import.meta.require;var P5=d((f5)=>{Object.defineProperty(f5,"__esModule",{value:!0});f5.splitWhen=f5.flatten=void 0;function EK($){return $.reduce((Z,Y)=>[].concat(Z,Y),[])}f5.flatten=EK;function _K($,Z){let Y=[[]],W=0;for(let J of $)if(Z(J))W++,Y[W]=[];else Y[W].push(J);return Y}f5.splitWhen=_K});var C5=d((S5)=>{Object.defineProperty(S5,"__esModule",{value:!0});S5.isEnoentCodeError=void 0;function DK($){return $.code==="ENOENT"}S5.isEnoentCodeError=DK});var k5=d((R5)=>{Object.defineProperty(R5,"__esModule",{value:!0});R5.createDirentFromStats=void 0;class x5{constructor($,Z){this.name=$,this.isBlockDevice=Z.isBlockDevice.bind(Z),this.isCharacterDevice=Z.isCharacterDevice.bind(Z),this.isDirectory=Z.isDirectory.bind(Z),this.isFIFO=Z.isFIFO.bind(Z),this.isFile=Z.isFile.bind(Z),this.isSocket=Z.isSocket.bind(Z),this.isSymbolicLink=Z.isSymbolicLink.bind(Z)}}function jK($,Z){return new x5($,Z)}R5.createDirentFromStats=jK});var m5=d((h5)=>{Object.defineProperty(h5,"__esModule",{value:!0});h5.convertPosixPathToPattern=h5.convertWindowsPathToPattern=h5.convertPathToPattern=h5.escapePosixPath=h5.escapeWindowsPath=h5.escape=h5.removeLeadingDotSegment=h5.makeAbsolute=h5.unixify=void 0;var fK=V1("os"),TK=V1("path"),I5=fK.platform()==="win32",PK=2,SK=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,AK=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,CK=/^\\\\([.?])/,xK=/\\(?![!()+@[\]{}])/g;function RK($){return $.replace(/\\/g,"/")}h5.unixify=RK;function yK($,Z){return TK.resolve($,Z)}h5.makeAbsolute=yK;function kK($){if($.charAt(0)==="."){let Z=$.charAt(1);if(Z==="/"||Z==="\\")return $.slice(PK)}return $}h5.removeLeadingDotSegment=kK;h5.escape=I5?PY:SY;function PY($){return $.replace(AK,"\\$2")}h5.escapeWindowsPath=PY;function SY($){return $.replace(SK,"\\$2")}h5.escapePosixPath=SY;h5.convertPathToPattern=I5?b5:v5;function b5($){return PY($).replace(CK,"//$1").replace(xK,"/")}h5.convertWindowsPathToPattern=b5;function v5($){return SY($)}h5.convertPosixPathToPattern=v5});var u5=d((aj,d5)=>{/*!
|
|
3
|
+
* is-extglob <https://github.com/jonschlinkert/is-extglob>
|
|
4
|
+
*
|
|
5
|
+
* Copyright (c) 2014-2016, Jon Schlinkert.
|
|
6
|
+
* Licensed under the MIT License.
|
|
7
|
+
*/d5.exports=function(Z){if(typeof Z!=="string"||Z==="")return!1;var Y;while(Y=/(\\).|([@?!+*]\(.*\))/g.exec(Z)){if(Y[2])return!0;Z=Z.slice(Y.index+Y[0].length)}return!1}});var p5=d((oj,l5)=>{/*!
|
|
8
|
+
* is-glob <https://github.com/jonschlinkert/is-glob>
|
|
9
|
+
*
|
|
10
|
+
* Copyright (c) 2014-2017, Jon Schlinkert.
|
|
11
|
+
* Released under the MIT License.
|
|
12
|
+
*/var cK=u5(),c5={"{":"}","(":")","[":"]"},lK=function($){if($[0]==="!")return!0;var Z=0,Y=-2,W=-2,J=-2,Q=-2,X=-2;while(Z<$.length){if($[Z]==="*")return!0;if($[Z+1]==="?"&&/[\].+)]/.test($[Z]))return!0;if(W!==-1&&$[Z]==="["&&$[Z+1]!=="]"){if(W<Z)W=$.indexOf("]",Z);if(W>Z){if(X===-1||X>W)return!0;if(X=$.indexOf("\\",Z),X===-1||X>W)return!0}}if(J!==-1&&$[Z]==="{"&&$[Z+1]!=="}"){if(J=$.indexOf("}",Z),J>Z){if(X=$.indexOf("\\",Z),X===-1||X>J)return!0}}if(Q!==-1&&$[Z]==="("&&$[Z+1]==="?"&&/[:!=]/.test($[Z+2])&&$[Z+3]!==")"){if(Q=$.indexOf(")",Z),Q>Z){if(X=$.indexOf("\\",Z),X===-1||X>Q)return!0}}if(Y!==-1&&$[Z]==="("&&$[Z+1]!=="|"){if(Y<Z)Y=$.indexOf("|",Z);if(Y!==-1&&$[Y+1]!==")"){if(Q=$.indexOf(")",Y),Q>Y){if(X=$.indexOf("\\",Y),X===-1||X>Q)return!0}}}if($[Z]==="\\"){var K=$[Z+1];Z+=2;var V=c5[K];if(V){var B=$.indexOf(V,Z);if(B!==-1)Z=B+1}if($[Z]==="!")return!0}else Z++}return!1},pK=function($){if($[0]==="!")return!0;var Z=0;while(Z<$.length){if(/[*?{}()[\]]/.test($[Z]))return!0;if($[Z]==="\\"){var Y=$[Z+1];Z+=2;var W=c5[Y];if(W){var J=$.indexOf(W,Z);if(J!==-1)Z=J+1}if($[Z]==="!")return!0}else Z++}return!1};l5.exports=function(Z,Y){if(typeof Z!=="string"||Z==="")return!1;if(cK(Z))return!0;var W=lK;if(Y&&Y.strict===!1)W=pK;return W(Z)}});var n5=d((sj,i5)=>{var iK=p5(),nK=V1("path").posix.dirname,rK=V1("os").platform()==="win32",AY="/",aK=/\\/g,oK=/[\{\[].*[\}\]]$/,sK=/(^|[^\\])([\{\[]|\([^\)]+$)/,tK=/\\([\!\*\?\|\[\]\(\)\{\}])/g;i5.exports=function(Z,Y){var W=Object.assign({flipBackslashes:!0},Y);if(W.flipBackslashes&&rK&&Z.indexOf(AY)<0)Z=Z.replace(aK,AY);if(oK.test(Z))Z+=AY;Z+="a";do Z=nK(Z);while(iK(Z)||sK.test(Z));return Z.replace(tK,"$1")}});var n8=d((eK)=>{eK.isInteger=($)=>{if(typeof $==="number")return Number.isInteger($);if(typeof $==="string"&&$.trim()!=="")return Number.isInteger(Number($));return!1};eK.find=($,Z)=>$.nodes.find((Y)=>Y.type===Z);eK.exceedsLimit=($,Z,Y=1,W)=>{if(W===!1)return!1;if(!eK.isInteger($)||!eK.isInteger(Z))return!1;return(Number(Z)-Number($))/Number(Y)>=W};eK.escapeNode=($,Z=0,Y)=>{let W=$.nodes[Z];if(!W)return;if(Y&&W.type===Y||W.type==="open"||W.type==="close"){if(W.escaped!==!0)W.value="\\"+W.value,W.escaped=!0}};eK.encloseBrace=($)=>{if($.type!=="brace")return!1;if($.commas>>0+$.ranges>>0===0)return $.invalid=!0,!0;return!1};eK.isInvalidBrace=($)=>{if($.type!=="brace")return!1;if($.invalid===!0||$.dollar)return!0;if($.commas>>0+$.ranges>>0===0)return $.invalid=!0,!0;if($.open!==!0||$.close!==!0)return $.invalid=!0,!0;return!1};eK.isOpenOrClose=($)=>{if($.type==="open"||$.type==="close")return!0;return $.open===!0||$.close===!0};eK.reduce=($)=>$.reduce((Z,Y)=>{if(Y.type==="text")Z.push(Y.value);if(Y.type==="range")Y.type="text";return Z},[]);eK.flatten=(...$)=>{let Z=[],Y=(W)=>{for(let J=0;J<W.length;J++){let Q=W[J];if(Array.isArray(Q)){Y(Q);continue}if(Q!==void 0)Z.push(Q)}return Z};return Y($),Z}});var r8=d((ej,a5)=>{var r5=n8();a5.exports=($,Z={})=>{let Y=(W,J={})=>{let Q=Z.escapeInvalid&&r5.isInvalidBrace(J),X=W.invalid===!0&&Z.escapeInvalid===!0,K="";if(W.value){if((Q||X)&&r5.isOpenOrClose(W))return"\\"+W.value;return W.value}if(W.value)return W.value;if(W.nodes)for(let V of W.nodes)K+=Y(V);return K};return Y($)}});var s5=d(($f,o5)=>{/*!
|
|
13
|
+
* is-number <https://github.com/jonschlinkert/is-number>
|
|
14
|
+
*
|
|
15
|
+
* Copyright (c) 2014-present, Jon Schlinkert.
|
|
16
|
+
* Released under the MIT License.
|
|
17
|
+
*/o5.exports=function($){if(typeof $==="number")return $-$===0;if(typeof $==="string"&&$.trim()!=="")return Number.isFinite?Number.isFinite(+$):isFinite(+$);return!1}});var XW=d((Zf,QW)=>{/*!
|
|
18
|
+
* to-regex-range <https://github.com/micromatch/to-regex-range>
|
|
19
|
+
*
|
|
20
|
+
* Copyright (c) 2015-present, Jon Schlinkert.
|
|
21
|
+
* Released under the MIT License.
|
|
22
|
+
*/var t5=s5(),a0=($,Z,Y)=>{if(t5($)===!1)throw TypeError("toRegexRange: expected the first argument to be a number");if(Z===void 0||$===Z)return String($);if(t5(Z)===!1)throw TypeError("toRegexRange: expected the second argument to be a number.");let W={relaxZeros:!0,...Y};if(typeof W.strictZeros==="boolean")W.relaxZeros=W.strictZeros===!1;let J=String(W.relaxZeros),Q=String(W.shorthand),X=String(W.capture),K=String(W.wrap),V=$+":"+Z+"="+J+Q+X+K;if(a0.cache.hasOwnProperty(V))return a0.cache[V].result;let B=Math.min($,Z),G=Math.max($,Z);if(Math.abs(B-G)===1){let w=$+"|"+Z;if(W.capture)return`(${w})`;if(W.wrap===!1)return w;return`(?:${w})`}let F=JW($)||JW(Z),z={min:$,max:Z,a:B,b:G},N=[],q=[];if(F)z.isPadded=F,z.maxLen=String(z.max).length;if(B<0){let w=G<0?Math.abs(G):1;q=e5(w,Math.abs(B),z,W),B=z.a=0}if(G>=0)N=e5(B,G,z,W);if(z.negatives=q,z.positives=N,z.result=VV(q,N,W),W.capture===!0)z.result=`(${z.result})`;else if(W.wrap!==!1&&N.length+q.length>1)z.result=`(?:${z.result})`;return a0.cache[V]=z,z.result};function VV($,Z,Y){let W=xY($,Z,"-",!1,Y)||[],J=xY(Z,$,"",!1,Y)||[],Q=xY($,Z,"-?",!0,Y)||[];return W.concat(Q).concat(J).join("|")}function zV($,Z){let Y=1,W=1,J=ZW($,Y),Q=new Set([Z]);while($<=J&&J<=Z)Q.add(J),Y+=1,J=ZW($,Y);J=YW(Z+1,W)-1;while($<J&&J<=Z)Q.add(J),W+=1,J=YW(Z+1,W)-1;return Q=[...Q],Q.sort(FV),Q}function GV($,Z,Y){if($===Z)return{pattern:$,count:[],digits:0};let W=BV($,Z),J=W.length,Q="",X=0;for(let K=0;K<J;K++){let[V,B]=W[K];if(V===B)Q+=V;else if(V!=="0"||B!=="9")Q+=qV(V,B,Y);else X++}if(X)Q+=Y.shorthand===!0?"\\d":"[0-9]";return{pattern:Q,count:[X],digits:J}}function e5($,Z,Y,W){let J=zV($,Z),Q=[],X=$,K;for(let V=0;V<J.length;V++){let B=J[V],G=GV(String(X),String(B),W),F="";if(!Y.isPadded&&K&&K.pattern===G.pattern){if(K.count.length>1)K.count.pop();K.count.push(G.count[0]),K.string=K.pattern+WW(K.count),X=B+1;continue}if(Y.isPadded)F=UV(B,Y,W);G.string=F+G.pattern+WW(G.count),Q.push(G),X=B+1,K=G}return Q}function xY($,Z,Y,W,J){let Q=[];for(let X of $){let{string:K}=X;if(!W&&!$W(Z,"string",K))Q.push(Y+K);if(W&&$W(Z,"string",K))Q.push(Y+K)}return Q}function BV($,Z){let Y=[];for(let W=0;W<$.length;W++)Y.push([$[W],Z[W]]);return Y}function FV($,Z){return $>Z?1:Z>$?-1:0}function $W($,Z,Y){return $.some((W)=>W[Z]===Y)}function ZW($,Z){return Number(String($).slice(0,-Z)+"9".repeat(Z))}function YW($,Z){return $-$%Math.pow(10,Z)}function WW($){let[Z=0,Y=""]=$;if(Y||Z>1)return`{${Z+(Y?","+Y:"")}}`;return""}function qV($,Z,Y){return`[${$}${Z-$===1?"":"-"}${Z}]`}function JW($){return/^-?(0+)\d/.test($)}function UV($,Z,Y){if(!Z.isPadded)return $;let W=Math.abs(Z.maxLen-String($).length),J=Y.relaxZeros!==!1;switch(W){case 0:return"";case 1:return J?"0?":"0";case 2:return J?"0{0,2}":"00";default:return J?`0{0,${W}}`:`0{${W}}`}}a0.cache={};a0.clearCache=()=>a0.cache={};QW.exports=a0});var kY=d((Yf,qW)=>{/*!
|
|
23
|
+
* fill-range <https://github.com/jonschlinkert/fill-range>
|
|
24
|
+
*
|
|
25
|
+
* Copyright (c) 2014-present, Jon Schlinkert.
|
|
26
|
+
* Licensed under the MIT License.
|
|
27
|
+
*/var HV=V1("util"),VW=XW(),KW=($)=>$!==null&&typeof $==="object"&&!Array.isArray($),NV=($)=>{return(Z)=>$===!0?Number(Z):String(Z)},RY=($)=>{return typeof $==="number"||typeof $==="string"&&$!==""},cZ=($)=>Number.isInteger(+$),yY=($)=>{let Z=`${$}`,Y=-1;if(Z[0]==="-")Z=Z.slice(1);if(Z==="0")return!1;while(Z[++Y]==="0");return Y>0},MV=($,Z,Y)=>{if(typeof $==="string"||typeof Z==="string")return!0;return Y.stringify===!0},wV=($,Z,Y)=>{if(Z>0){let W=$[0]==="-"?"-":"";if(W)$=$.slice(1);$=W+$.padStart(W?Z-1:Z,"0")}if(Y===!1)return String($);return $},o8=($,Z)=>{let Y=$[0]==="-"?"-":"";if(Y)$=$.slice(1),Z--;while($.length<Z)$="0"+$;return Y?"-"+$:$},LV=($,Z,Y)=>{$.negatives.sort((K,V)=>K<V?-1:K>V?1:0),$.positives.sort((K,V)=>K<V?-1:K>V?1:0);let W=Z.capture?"":"?:",J="",Q="",X;if($.positives.length)J=$.positives.map((K)=>o8(String(K),Y)).join("|");if($.negatives.length)Q=`-(${W}${$.negatives.map((K)=>o8(String(K),Y)).join("|")})`;if(J&&Q)X=`${J}|${Q}`;else X=J||Q;if(Z.wrap)return`(${W}${X})`;return X},zW=($,Z,Y,W)=>{if(Y)return VW($,Z,{wrap:!1,...W});let J=String.fromCharCode($);if($===Z)return J;let Q=String.fromCharCode(Z);return`[${J}-${Q}]`},GW=($,Z,Y)=>{if(Array.isArray($)){let W=Y.wrap===!0,J=Y.capture?"":"?:";return W?`(${J}${$.join("|")})`:$.join("|")}return VW($,Z,Y)},BW=(...$)=>{return RangeError("Invalid range arguments: "+HV.inspect(...$))},FW=($,Z,Y)=>{if(Y.strictRanges===!0)throw BW([$,Z]);return[]},EV=($,Z)=>{if(Z.strictRanges===!0)throw TypeError(`Expected step "${$}" to be a number`);return[]},_V=($,Z,Y=1,W={})=>{let J=Number($),Q=Number(Z);if(!Number.isInteger(J)||!Number.isInteger(Q)){if(W.strictRanges===!0)throw BW([$,Z]);return[]}if(J===0)J=0;if(Q===0)Q=0;let X=J>Q,K=String($),V=String(Z),B=String(Y);Y=Math.max(Math.abs(Y),1);let G=yY(K)||yY(V)||yY(B),F=G?Math.max(K.length,V.length,B.length):0,z=G===!1&&MV($,Z,W)===!1,N=W.transform||NV(z);if(W.toRegex&&Y===1)return zW(o8($,F),o8(Z,F),!0,W);let q={negatives:[],positives:[]},w=(H)=>q[H<0?"negatives":"positives"].push(Math.abs(H)),A=[],O=0;while(X?J>=Q:J<=Q){if(W.toRegex===!0&&Y>1)w(J);else A.push(wV(N(J,O),F,z));J=X?J-Y:J+Y,O++}if(W.toRegex===!0)return Y>1?LV(q,W,F):GW(A,null,{wrap:!1,...W});return A},OV=($,Z,Y=1,W={})=>{if(!cZ($)&&$.length>1||!cZ(Z)&&Z.length>1)return FW($,Z,W);let J=W.transform||((z)=>String.fromCharCode(z)),Q=`${$}`.charCodeAt(0),X=`${Z}`.charCodeAt(0),K=Q>X,V=Math.min(Q,X),B=Math.max(Q,X);if(W.toRegex&&Y===1)return zW(V,B,!1,W);let G=[],F=0;while(K?Q>=X:Q<=X)G.push(J(Q,F)),Q=K?Q-Y:Q+Y,F++;if(W.toRegex===!0)return GW(G,null,{wrap:!1,options:W});return G},a8=($,Z,Y,W={})=>{if(Z==null&&RY($))return[$];if(!RY($)||!RY(Z))return FW($,Z,W);if(typeof Y==="function")return a8($,Z,1,{transform:Y});if(KW(Y))return a8($,Z,0,Y);let J={...W};if(J.capture===!0)J.wrap=!0;if(Y=Y||J.step||1,!cZ(Y)){if(Y!=null&&!KW(Y))return EV(Y,J);return a8($,Z,1,Y)}if(cZ($)&&cZ(Z))return _V($,Z,Y,J);return OV($,Z,Math.max(Math.abs(Y),1),J)};qW.exports=a8});var NW=d((Wf,HW)=>{var DV=kY(),UW=n8(),jV=($,Z={})=>{let Y=(W,J={})=>{let Q=UW.isInvalidBrace(J),X=W.invalid===!0&&Z.escapeInvalid===!0,K=Q===!0||X===!0,V=Z.escapeInvalid===!0?"\\":"",B="";if(W.isOpen===!0)return V+W.value;if(W.isClose===!0)return console.log("node.isClose",V,W.value),V+W.value;if(W.type==="open")return K?V+W.value:"(";if(W.type==="close")return K?V+W.value:")";if(W.type==="comma")return W.prev.type==="comma"?"":K?W.value:"|";if(W.value)return W.value;if(W.nodes&&W.ranges>0){let G=UW.reduce(W.nodes),F=DV(...G,{...Z,wrap:!1,toRegex:!0,strictZeros:!0});if(F.length!==0)return G.length>1&&F.length>1?`(${F})`:F}if(W.nodes)for(let G of W.nodes)B+=Y(G,W);return B};return Y($)};HW.exports=jV});var LW=d((Jf,wW)=>{var fV=kY(),MW=r8(),S$=n8(),o0=($="",Z="",Y=!1)=>{let W=[];if($=[].concat($),Z=[].concat(Z),!Z.length)return $;if(!$.length)return Y?S$.flatten(Z).map((J)=>`{${J}}`):Z;for(let J of $)if(Array.isArray(J))for(let Q of J)W.push(o0(Q,Z,Y));else for(let Q of Z){if(Y===!0&&typeof Q==="string")Q=`{${Q}}`;W.push(Array.isArray(Q)?o0(J,Q,Y):J+Q)}return S$.flatten(W)},TV=($,Z={})=>{let Y=Z.rangeLimit===void 0?1000:Z.rangeLimit,W=(J,Q={})=>{J.queue=[];let X=Q,K=Q.queue;while(X.type!=="brace"&&X.type!=="root"&&X.parent)X=X.parent,K=X.queue;if(J.invalid||J.dollar){K.push(o0(K.pop(),MW(J,Z)));return}if(J.type==="brace"&&J.invalid!==!0&&J.nodes.length===2){K.push(o0(K.pop(),["{}"]));return}if(J.nodes&&J.ranges>0){let F=S$.reduce(J.nodes);if(S$.exceedsLimit(...F,Z.step,Y))throw RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let z=fV(...F,Z);if(z.length===0)z=MW(J,Z);K.push(o0(K.pop(),z)),J.nodes=[];return}let V=S$.encloseBrace(J),B=J.queue,G=J;while(G.type!=="brace"&&G.type!=="root"&&G.parent)G=G.parent,B=G.queue;for(let F=0;F<J.nodes.length;F++){let z=J.nodes[F];if(z.type==="comma"&&J.type==="brace"){if(F===1)B.push("");B.push("");continue}if(z.type==="close"){K.push(o0(K.pop(),B,V));continue}if(z.value&&z.type!=="open"){B.push(o0(B.pop(),z.value));continue}if(z.nodes)W(z,J)}return B};return S$.flatten(W($))};wW.exports=TV});var _W=d((Qf,EW)=>{EW.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
|
|
28
|
+
`,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:"\t",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var TW=d((Xf,fW)=>{var PV=r8(),{MAX_LENGTH:OW,CHAR_BACKSLASH:IY,CHAR_BACKTICK:SV,CHAR_COMMA:AV,CHAR_DOT:CV,CHAR_LEFT_PARENTHESES:xV,CHAR_RIGHT_PARENTHESES:RV,CHAR_LEFT_CURLY_BRACE:yV,CHAR_RIGHT_CURLY_BRACE:kV,CHAR_LEFT_SQUARE_BRACKET:DW,CHAR_RIGHT_SQUARE_BRACKET:jW,CHAR_DOUBLE_QUOTE:IV,CHAR_SINGLE_QUOTE:bV,CHAR_NO_BREAK_SPACE:vV,CHAR_ZERO_WIDTH_NOBREAK_SPACE:hV}=_W(),gV=($,Z={})=>{if(typeof $!=="string")throw TypeError("Expected a string");let Y=Z||{},W=typeof Y.maxLength==="number"?Math.min(OW,Y.maxLength):OW;if($.length>W)throw SyntaxError(`Input length (${$.length}), exceeds max characters (${W})`);let J={type:"root",input:$,nodes:[]},Q=[J],X=J,K=J,V=0,B=$.length,G=0,F=0,z,N=()=>$[G++],q=(w)=>{if(w.type==="text"&&K.type==="dot")K.type="text";if(K&&K.type==="text"&&w.type==="text"){K.value+=w.value;return}return X.nodes.push(w),w.parent=X,w.prev=K,K=w,w};q({type:"bos"});while(G<B){if(X=Q[Q.length-1],z=N(),z===hV||z===vV)continue;if(z===IY){q({type:"text",value:(Z.keepEscaping?z:"")+N()});continue}if(z===jW){q({type:"text",value:"\\"+z});continue}if(z===DW){V++;let w;while(G<B&&(w=N())){if(z+=w,w===DW){V++;continue}if(w===IY){z+=N();continue}if(w===jW){if(V--,V===0)break}}q({type:"text",value:z});continue}if(z===xV){X=q({type:"paren",nodes:[]}),Q.push(X),q({type:"text",value:z});continue}if(z===RV){if(X.type!=="paren"){q({type:"text",value:z});continue}X=Q.pop(),q({type:"text",value:z}),X=Q[Q.length-1];continue}if(z===IV||z===bV||z===SV){let w=z,A;if(Z.keepQuotes!==!0)z="";while(G<B&&(A=N())){if(A===IY){z+=A+N();continue}if(A===w){if(Z.keepQuotes===!0)z+=A;break}z+=A}q({type:"text",value:z});continue}if(z===yV){F++;let A={type:"brace",open:!0,close:!1,dollar:K.value&&K.value.slice(-1)==="$"||X.dollar===!0,depth:F,commas:0,ranges:0,nodes:[]};X=q(A),Q.push(X),q({type:"open",value:z});continue}if(z===kV){if(X.type!=="brace"){q({type:"text",value:z});continue}let w="close";X=Q.pop(),X.close=!0,q({type:w,value:z}),F--,X=Q[Q.length-1];continue}if(z===AV&&F>0){if(X.ranges>0){X.ranges=0;let w=X.nodes.shift();X.nodes=[w,{type:"text",value:PV(X)}]}q({type:"comma",value:z}),X.commas++;continue}if(z===CV&&F>0&&X.commas===0){let w=X.nodes;if(F===0||w.length===0){q({type:"text",value:z});continue}if(K.type==="dot"){if(X.range=[],K.value+=z,K.type="range",X.nodes.length!==3&&X.nodes.length!==5){X.invalid=!0,X.ranges=0,K.type="text";continue}X.ranges++,X.args=[];continue}if(K.type==="range"){w.pop();let A=w[w.length-1];A.value+=K.value+z,K=A,X.ranges--;continue}q({type:"dot",value:z});continue}q({type:"text",value:z})}do if(X=Q.pop(),X.type!=="root"){X.nodes.forEach((O)=>{if(!O.nodes){if(O.type==="open")O.isOpen=!0;if(O.type==="close")O.isClose=!0;if(!O.nodes)O.type="text";O.invalid=!0}});let w=Q[Q.length-1],A=w.nodes.indexOf(X);w.nodes.splice(A,1,...X.nodes)}while(Q.length>0);return q({type:"eos"}),J};fW.exports=gV});var AW=d((Kf,SW)=>{var PW=r8(),mV=NW(),dV=LW(),uV=TW(),k1=($,Z={})=>{let Y=[];if(Array.isArray($))for(let W of $){let J=k1.create(W,Z);if(Array.isArray(J))Y.push(...J);else Y.push(J)}else Y=[].concat(k1.create($,Z));if(Z&&Z.expand===!0&&Z.nodupes===!0)Y=[...new Set(Y)];return Y};k1.parse=($,Z={})=>uV($,Z);k1.stringify=($,Z={})=>{if(typeof $==="string")return PW(k1.parse($,Z),Z);return PW($,Z)};k1.compile=($,Z={})=>{if(typeof $==="string")$=k1.parse($,Z);return mV($,Z)};k1.expand=($,Z={})=>{if(typeof $==="string")$=k1.parse($,Z);let Y=dV($,Z);if(Z.noempty===!0)Y=Y.filter(Boolean);if(Z.nodupes===!0)Y=[...new Set(Y)];return Y};k1.create=($,Z={})=>{if($===""||$.length<3)return[$];return Z.expand!==!0?k1.compile($,Z):k1.expand($,Z)};SW.exports=k1});var lZ=d((Vf,xW)=>{var cV=V1("path"),CW={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)"},lV={...CW,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)"},pV={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};xW.exports={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:pV,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:cV.sep,extglobChars($){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${$.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars($){return $===!0?lV:CW}}});var pZ=d((tV)=>{var iV=V1("path"),nV=process.platform==="win32",{REGEX_BACKSLASH:rV,REGEX_REMOVE_BACKSLASH:aV,REGEX_SPECIAL_CHARS:oV,REGEX_SPECIAL_CHARS_GLOBAL:sV}=lZ();tV.isObject=($)=>$!==null&&typeof $==="object"&&!Array.isArray($);tV.hasRegexChars=($)=>oV.test($);tV.isRegexChar=($)=>$.length===1&&tV.hasRegexChars($);tV.escapeRegex=($)=>$.replace(sV,"\\$1");tV.toPosixSlashes=($)=>$.replace(rV,"/");tV.removeBackslashes=($)=>{return $.replace(aV,(Z)=>{return Z==="\\"?"":Z})};tV.supportsLookbehinds=()=>{let $=process.version.slice(1).split(".").map(Number);if($.length===3&&$[0]>=9||$[0]===8&&$[1]>=10)return!0;return!1};tV.isWindows=($)=>{if($&&typeof $.windows==="boolean")return $.windows;return nV===!0||iV.sep==="\\"};tV.escapeLast=($,Z,Y)=>{let W=$.lastIndexOf(Z,Y);if(W===-1)return $;if($[W-1]==="\\")return tV.escapeLast($,Z,W-1);return`${$.slice(0,W)}\\${$.slice(W)}`};tV.removePrefix=($,Z={})=>{let Y=$;if(Y.startsWith("./"))Y=Y.slice(2),Z.prefix="./";return Y};tV.wrapOutput=($,Z={},Y={})=>{let W=Y.contains?"":"^",J=Y.contains?"":"$",Q=`${W}(?:${$})${J}`;if(Z.negated===!0)Q=`(?:^(?!${Q}).*$)`;return Q}});var dW=d((Gf,mW)=>{var kW=pZ(),{CHAR_ASTERISK:bY,CHAR_AT:Vz,CHAR_BACKWARD_SLASH:iZ,CHAR_COMMA:zz,CHAR_DOT:vY,CHAR_EXCLAMATION_MARK:hY,CHAR_FORWARD_SLASH:gW,CHAR_LEFT_CURLY_BRACE:gY,CHAR_LEFT_PARENTHESES:mY,CHAR_LEFT_SQUARE_BRACKET:Gz,CHAR_PLUS:Bz,CHAR_QUESTION_MARK:IW,CHAR_RIGHT_CURLY_BRACE:Fz,CHAR_RIGHT_PARENTHESES:bW,CHAR_RIGHT_SQUARE_BRACKET:qz}=lZ(),vW=($)=>{return $===gW||$===iZ},hW=($)=>{if($.isPrefix!==!0)$.depth=$.isGlobstar?1/0:1},Uz=($,Z)=>{let Y=Z||{},W=$.length-1,J=Y.parts===!0||Y.scanToEnd===!0,Q=[],X=[],K=[],V=$,B=-1,G=0,F=0,z=!1,N=!1,q=!1,w=!1,A=!1,O=!1,H=!1,j=!1,S=!1,b=!1,y=0,k,D,I={value:"",depth:0,isGlob:!1},M=()=>B>=W,L=()=>V.charCodeAt(B+1),u=()=>{return k=D,V.charCodeAt(++B)};while(B<W){D=u();let g;if(D===iZ){if(H=I.backslashes=!0,D=u(),D===gY)O=!0;continue}if(O===!0||D===gY){y++;while(M()!==!0&&(D=u())){if(D===iZ){H=I.backslashes=!0,u();continue}if(D===gY){y++;continue}if(O!==!0&&D===vY&&(D=u())===vY){if(z=I.isBrace=!0,q=I.isGlob=!0,b=!0,J===!0)continue;break}if(O!==!0&&D===zz){if(z=I.isBrace=!0,q=I.isGlob=!0,b=!0,J===!0)continue;break}if(D===Fz){if(y--,y===0){O=!1,z=I.isBrace=!0,b=!0;break}}}if(J===!0)continue;break}if(D===gW){if(Q.push(B),X.push(I),I={value:"",depth:0,isGlob:!1},b===!0)continue;if(k===vY&&B===G+1){G+=2;continue}F=B+1;continue}if(Y.noext!==!0){if((D===Bz||D===Vz||D===bY||D===IW||D===hY)===!0&&L()===mY){if(q=I.isGlob=!0,w=I.isExtglob=!0,b=!0,D===hY&&B===G)S=!0;if(J===!0){while(M()!==!0&&(D=u())){if(D===iZ){H=I.backslashes=!0,D=u();continue}if(D===bW){q=I.isGlob=!0,b=!0;break}}continue}break}}if(D===bY){if(k===bY)A=I.isGlobstar=!0;if(q=I.isGlob=!0,b=!0,J===!0)continue;break}if(D===IW){if(q=I.isGlob=!0,b=!0,J===!0)continue;break}if(D===Gz){while(M()!==!0&&(g=u())){if(g===iZ){H=I.backslashes=!0,u();continue}if(g===qz){N=I.isBracket=!0,q=I.isGlob=!0,b=!0;break}}if(J===!0)continue;break}if(Y.nonegate!==!0&&D===hY&&B===G){j=I.negated=!0,G++;continue}if(Y.noparen!==!0&&D===mY){if(q=I.isGlob=!0,J===!0){while(M()!==!0&&(D=u())){if(D===mY){H=I.backslashes=!0,D=u();continue}if(D===bW){b=!0;break}}continue}break}if(q===!0){if(b=!0,J===!0)continue;break}}if(Y.noext===!0)w=!1,q=!1;let l=V,f="",U="";if(G>0)f=V.slice(0,G),V=V.slice(G),F-=G;if(l&&q===!0&&F>0)l=V.slice(0,F),U=V.slice(F);else if(q===!0)l="",U=V;else l=V;if(l&&l!==""&&l!=="/"&&l!==V){if(vW(l.charCodeAt(l.length-1)))l=l.slice(0,-1)}if(Y.unescape===!0){if(U)U=kW.removeBackslashes(U);if(l&&H===!0)l=kW.removeBackslashes(l)}let _={prefix:f,input:$,start:G,base:l,glob:U,isBrace:z,isBracket:N,isGlob:q,isExtglob:w,isGlobstar:A,negated:j,negatedExtglob:S};if(Y.tokens===!0){if(_.maxDepth=0,!vW(D))X.push(I);_.tokens=X}if(Y.parts===!0||Y.tokens===!0){let g;for(let m=0;m<Q.length;m++){let r=g?g+1:G,$1=Q[m],Y1=$.slice(r,$1);if(Y.tokens){if(m===0&&G!==0)X[m].isPrefix=!0,X[m].value=f;else X[m].value=Y1;hW(X[m]),_.maxDepth+=X[m].depth}if(m!==0||Y1!=="")K.push(Y1);g=$1}if(g&&g+1<$.length){let m=$.slice(g+1);if(K.push(m),Y.tokens)X[X.length-1].value=m,hW(X[X.length-1]),_.maxDepth+=X[X.length-1].depth}_.slashes=Q,_.parts=K}return _};mW.exports=Uz});var lW=d((Bf,cW)=>{var s8=lZ(),I1=pZ(),{MAX_LENGTH:t8,POSIX_REGEX_SOURCE:Hz,REGEX_NON_SPECIAL_CHARS:Nz,REGEX_SPECIAL_CHARS_BACKREF:Mz,REPLACEMENTS:uW}=s8,wz=($,Z)=>{if(typeof Z.expandRange==="function")return Z.expandRange(...$,Z);$.sort();let Y=`[${$.join("-")}]`;try{new RegExp(Y)}catch(W){return $.map((J)=>I1.escapeRegex(J)).join("..")}return Y},A$=($,Z)=>{return`Missing ${$}: "${Z}" - use "\\\\${Z}" to match literal characters`},dY=($,Z)=>{if(typeof $!=="string")throw TypeError("Expected a string");$=uW[$]||$;let Y={...Z},W=typeof Y.maxLength==="number"?Math.min(t8,Y.maxLength):t8,J=$.length;if(J>W)throw SyntaxError(`Input length: ${J}, exceeds maximum allowed length: ${W}`);let Q={type:"bos",value:"",output:Y.prepend||""},X=[Q],K=Y.capture?"":"?:",V=I1.isWindows(Z),B=s8.globChars(V),G=s8.extglobChars(B),{DOT_LITERAL:F,PLUS_LITERAL:z,SLASH_LITERAL:N,ONE_CHAR:q,DOTS_SLASH:w,NO_DOT:A,NO_DOT_SLASH:O,NO_DOTS_SLASH:H,QMARK:j,QMARK_NO_DOT:S,STAR:b,START_ANCHOR:y}=B,k=(R)=>{return`(${K}(?:(?!${y}${R.dot?w:F}).)*?)`},D=Y.dot?"":A,I=Y.dot?j:S,M=Y.bash===!0?k(Y):b;if(Y.capture)M=`(${M})`;if(typeof Y.noext==="boolean")Y.noextglob=Y.noext;let L={input:$,index:-1,start:0,dot:Y.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:X};$=I1.removePrefix($,L),J=$.length;let u=[],l=[],f=[],U=Q,_,g=()=>L.index===J-1,m=L.peek=(R=1)=>$[L.index+R],r=L.advance=()=>$[++L.index]||"",$1=()=>$.slice(L.index+1),Y1=(R="",C=0)=>{L.consumed+=R,L.index+=C},s1=(R)=>{L.output+=R.output!=null?R.output:R.value,Y1(R.value)},b1=()=>{let R=1;while(m()==="!"&&(m(2)!=="("||m(3)==="?"))r(),L.start++,R++;if(R%2===0)return!1;return L.negated=!0,L.start++,!0},D1=(R)=>{L[R]++,f.push(R)},a=(R)=>{L[R]--,f.pop()},s=(R)=>{if(U.type==="globstar"){let C=L.braces>0&&(R.type==="comma"||R.type==="brace"),P=R.extglob===!0||u.length&&(R.type==="pipe"||R.type==="paren");if(R.type!=="slash"&&R.type!=="paren"&&!C&&!P)L.output=L.output.slice(0,-U.output.length),U.type="star",U.value="*",U.output=M,L.output+=U.output}if(u.length&&R.type!=="paren")u[u.length-1].inner+=R.value;if(R.value||R.output)s1(R);if(U&&U.type==="text"&&R.type==="text"){U.value+=R.value,U.output=(U.output||"")+R.value;return}R.prev=U,X.push(R),U=R},W1=(R,C)=>{let P={...G[C],conditions:1,inner:""};P.prev=U,P.parens=L.parens,P.output=L.output;let c=(Y.capture?"(":"")+P.open;D1("parens"),s({type:R,value:C,output:L.output?"":q}),s({type:"paren",extglob:!0,value:r(),output:c}),u.push(P)},v=(R)=>{let C=R.close+(Y.capture?")":""),P;if(R.type==="negate"){let c=M;if(R.inner&&R.inner.length>1&&R.inner.includes("/"))c=k(Y);if(c!==M||g()||/^\)+$/.test($1()))C=R.close=`)$))${c}`;if(R.inner.includes("*")&&(P=$1())&&/^\.[^\\/.]+$/.test(P)){let n=dY(P,{...Z,fastpaths:!1}).output;C=R.close=`)${n})${c})`}if(R.prev.type==="bos")L.negatedExtglob=!0}s({type:"paren",extglob:!0,value:_,output:C}),a("parens")};if(Y.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test($)){let R=!1,C=$.replace(Mz,(P,c,n,t,J1,v1)=>{if(t==="\\")return R=!0,P;if(t==="?"){if(c)return c+t+(J1?j.repeat(J1.length):"");if(v1===0)return I+(J1?j.repeat(J1.length):"");return j.repeat(n.length)}if(t===".")return F.repeat(n.length);if(t==="*"){if(c)return c+t+(J1?M:"");return M}return c?P:`\\${P}`});if(R===!0)if(Y.unescape===!0)C=C.replace(/\\/g,"");else C=C.replace(/\\+/g,(P)=>{return P.length%2===0?"\\\\":P?"\\":""});if(C===$&&Y.contains===!0)return L.output=$,L;return L.output=I1.wrapOutput(C,L,Z),L}while(!g()){if(_=r(),_==="\x00")continue;if(_==="\\"){let P=m();if(P==="/"&&Y.bash!==!0)continue;if(P==="."||P===";")continue;if(!P){_+="\\",s({type:"text",value:_});continue}let c=/^\\+/.exec($1()),n=0;if(c&&c[0].length>2){if(n=c[0].length,L.index+=n,n%2!==0)_+="\\"}if(Y.unescape===!0)_=r();else _+=r();if(L.brackets===0){s({type:"text",value:_});continue}}if(L.brackets>0&&(_!=="]"||U.value==="["||U.value==="[^")){if(Y.posix!==!1&&_===":"){let P=U.value.slice(1);if(P.includes("[")){if(U.posix=!0,P.includes(":")){let c=U.value.lastIndexOf("["),n=U.value.slice(0,c),t=U.value.slice(c+2),J1=Hz[t];if(J1){if(U.value=n+J1,L.backtrack=!0,r(),!Q.output&&X.indexOf(U)===1)Q.output=q;continue}}}}if(_==="["&&m()!==":"||_==="-"&&m()==="]")_=`\\${_}`;if(_==="]"&&(U.value==="["||U.value==="[^"))_=`\\${_}`;if(Y.posix===!0&&_==="!"&&U.value==="[")_="^";U.value+=_,s1({value:_});continue}if(L.quotes===1&&_!=='"'){_=I1.escapeRegex(_),U.value+=_,s1({value:_});continue}if(_==='"'){if(L.quotes=L.quotes===1?0:1,Y.keepQuotes===!0)s({type:"text",value:_});continue}if(_==="("){D1("parens"),s({type:"paren",value:_});continue}if(_===")"){if(L.parens===0&&Y.strictBrackets===!0)throw SyntaxError(A$("opening","("));let P=u[u.length-1];if(P&&L.parens===P.parens+1){v(u.pop());continue}s({type:"paren",value:_,output:L.parens?")":"\\)"}),a("parens");continue}if(_==="["){if(Y.nobracket===!0||!$1().includes("]")){if(Y.nobracket!==!0&&Y.strictBrackets===!0)throw SyntaxError(A$("closing","]"));_=`\\${_}`}else D1("brackets");s({type:"bracket",value:_});continue}if(_==="]"){if(Y.nobracket===!0||U&&U.type==="bracket"&&U.value.length===1){s({type:"text",value:_,output:`\\${_}`});continue}if(L.brackets===0){if(Y.strictBrackets===!0)throw SyntaxError(A$("opening","["));s({type:"text",value:_,output:`\\${_}`});continue}a("brackets");let P=U.value.slice(1);if(U.posix!==!0&&P[0]==="^"&&!P.includes("/"))_=`/${_}`;if(U.value+=_,s1({value:_}),Y.literalBrackets===!1||I1.hasRegexChars(P))continue;let c=I1.escapeRegex(U.value);if(L.output=L.output.slice(0,-U.value.length),Y.literalBrackets===!0){L.output+=c,U.value=c;continue}U.value=`(${K}${c}|${U.value})`,L.output+=U.value;continue}if(_==="{"&&Y.nobrace!==!0){D1("braces");let P={type:"brace",value:_,output:"(",outputIndex:L.output.length,tokensIndex:L.tokens.length};l.push(P),s(P);continue}if(_==="}"){let P=l[l.length-1];if(Y.nobrace===!0||!P){s({type:"text",value:_,output:_});continue}let c=")";if(P.dots===!0){let n=X.slice(),t=[];for(let J1=n.length-1;J1>=0;J1--){if(X.pop(),n[J1].type==="brace")break;if(n[J1].type!=="dots")t.unshift(n[J1].value)}c=wz(t,Y),L.backtrack=!0}if(P.comma!==!0&&P.dots!==!0){let n=L.output.slice(0,P.outputIndex),t=L.tokens.slice(P.tokensIndex);P.value=P.output="\\{",_=c="\\}",L.output=n;for(let J1 of t)L.output+=J1.output||J1.value}s({type:"brace",value:_,output:c}),a("braces"),l.pop();continue}if(_==="|"){if(u.length>0)u[u.length-1].conditions++;s({type:"text",value:_});continue}if(_===","){let P=_,c=l[l.length-1];if(c&&f[f.length-1]==="braces")c.comma=!0,P="|";s({type:"comma",value:_,output:P});continue}if(_==="/"){if(U.type==="dot"&&L.index===L.start+1){L.start=L.index+1,L.consumed="",L.output="",X.pop(),U=Q;continue}s({type:"slash",value:_,output:N});continue}if(_==="."){if(L.braces>0&&U.type==="dot"){if(U.value===".")U.output=F;let P=l[l.length-1];U.type="dots",U.output+=_,U.value+=_,P.dots=!0;continue}if(L.braces+L.parens===0&&U.type!=="bos"&&U.type!=="slash"){s({type:"text",value:_,output:F});continue}s({type:"dot",value:_,output:F});continue}if(_==="?"){if(!(U&&U.value==="(")&&Y.noextglob!==!0&&m()==="("&&m(2)!=="?"){W1("qmark",_);continue}if(U&&U.type==="paren"){let c=m(),n=_;if(c==="<"&&!I1.supportsLookbehinds())throw Error("Node.js v10 or higher is required for regex lookbehinds");if(U.value==="("&&!/[!=<:]/.test(c)||c==="<"&&!/<([!=]|\w+>)/.test($1()))n=`\\${_}`;s({type:"text",value:_,output:n});continue}if(Y.dot!==!0&&(U.type==="slash"||U.type==="bos")){s({type:"qmark",value:_,output:S});continue}s({type:"qmark",value:_,output:j});continue}if(_==="!"){if(Y.noextglob!==!0&&m()==="("){if(m(2)!=="?"||!/[!=<:]/.test(m(3))){W1("negate",_);continue}}if(Y.nonegate!==!0&&L.index===0){b1();continue}}if(_==="+"){if(Y.noextglob!==!0&&m()==="("&&m(2)!=="?"){W1("plus",_);continue}if(U&&U.value==="("||Y.regex===!1){s({type:"plus",value:_,output:z});continue}if(U&&(U.type==="bracket"||U.type==="paren"||U.type==="brace")||L.parens>0){s({type:"plus",value:_});continue}s({type:"plus",value:z});continue}if(_==="@"){if(Y.noextglob!==!0&&m()==="("&&m(2)!=="?"){s({type:"at",extglob:!0,value:_,output:""});continue}s({type:"text",value:_});continue}if(_!=="*"){if(_==="$"||_==="^")_=`\\${_}`;let P=Nz.exec($1());if(P)_+=P[0],L.index+=P[0].length;s({type:"text",value:_});continue}if(U&&(U.type==="globstar"||U.star===!0)){U.type="star",U.star=!0,U.value+=_,U.output=M,L.backtrack=!0,L.globstar=!0,Y1(_);continue}let R=$1();if(Y.noextglob!==!0&&/^\([^?]/.test(R)){W1("star",_);continue}if(U.type==="star"){if(Y.noglobstar===!0){Y1(_);continue}let P=U.prev,c=P.prev,n=P.type==="slash"||P.type==="bos",t=c&&(c.type==="star"||c.type==="globstar");if(Y.bash===!0&&(!n||R[0]&&R[0]!=="/")){s({type:"star",value:_,output:""});continue}let J1=L.braces>0&&(P.type==="comma"||P.type==="brace"),v1=u.length&&(P.type==="pipe"||P.type==="paren");if(!n&&P.type!=="paren"&&!J1&&!v1){s({type:"star",value:_,output:""});continue}while(R.slice(0,3)==="/**"){let $8=$[L.index+4];if($8&&$8!=="/")break;R=R.slice(3),Y1("/**",3)}if(P.type==="bos"&&g()){U.type="globstar",U.value+=_,U.output=k(Y),L.output=U.output,L.globstar=!0,Y1(_);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&!t&&g()){L.output=L.output.slice(0,-(P.output+U.output).length),P.output=`(?:${P.output}`,U.type="globstar",U.output=k(Y)+(Y.strictSlashes?")":"|$)"),U.value+=_,L.globstar=!0,L.output+=P.output+U.output,Y1(_);continue}if(P.type==="slash"&&P.prev.type!=="bos"&&R[0]==="/"){let $8=R[1]!==void 0?"|$":"";L.output=L.output.slice(0,-(P.output+U.output).length),P.output=`(?:${P.output}`,U.type="globstar",U.output=`${k(Y)}${N}|${N}${$8})`,U.value+=_,L.output+=P.output+U.output,L.globstar=!0,Y1(_+r()),s({type:"slash",value:"/",output:""});continue}if(P.type==="bos"&&R[0]==="/"){U.type="globstar",U.value+=_,U.output=`(?:^|${N}|${k(Y)}${N})`,L.output=U.output,L.globstar=!0,Y1(_+r()),s({type:"slash",value:"/",output:""});continue}L.output=L.output.slice(0,-U.output.length),U.type="globstar",U.output=k(Y),U.value+=_,L.output+=U.output,L.globstar=!0,Y1(_);continue}let C={type:"star",value:_,output:M};if(Y.bash===!0){if(C.output=".*?",U.type==="bos"||U.type==="slash")C.output=D+C.output;s(C);continue}if(U&&(U.type==="bracket"||U.type==="paren")&&Y.regex===!0){C.output=_,s(C);continue}if(L.index===L.start||U.type==="slash"||U.type==="dot"){if(U.type==="dot")L.output+=O,U.output+=O;else if(Y.dot===!0)L.output+=H,U.output+=H;else L.output+=D,U.output+=D;if(m()!=="*")L.output+=q,U.output+=q}s(C)}while(L.brackets>0){if(Y.strictBrackets===!0)throw SyntaxError(A$("closing","]"));L.output=I1.escapeLast(L.output,"["),a("brackets")}while(L.parens>0){if(Y.strictBrackets===!0)throw SyntaxError(A$("closing",")"));L.output=I1.escapeLast(L.output,"("),a("parens")}while(L.braces>0){if(Y.strictBrackets===!0)throw SyntaxError(A$("closing","}"));L.output=I1.escapeLast(L.output,"{"),a("braces")}if(Y.strictSlashes!==!0&&(U.type==="star"||U.type==="bracket"))s({type:"maybe_slash",value:"",output:`${N}?`});if(L.backtrack===!0){L.output="";for(let R of L.tokens)if(L.output+=R.output!=null?R.output:R.value,R.suffix)L.output+=R.suffix}return L};dY.fastpaths=($,Z)=>{let Y={...Z},W=typeof Y.maxLength==="number"?Math.min(t8,Y.maxLength):t8,J=$.length;if(J>W)throw SyntaxError(`Input length: ${J}, exceeds maximum allowed length: ${W}`);$=uW[$]||$;let Q=I1.isWindows(Z),{DOT_LITERAL:X,SLASH_LITERAL:K,ONE_CHAR:V,DOTS_SLASH:B,NO_DOT:G,NO_DOTS:F,NO_DOTS_SLASH:z,STAR:N,START_ANCHOR:q}=s8.globChars(Q),w=Y.dot?F:G,A=Y.dot?z:G,O=Y.capture?"":"?:",H={negated:!1,prefix:""},j=Y.bash===!0?".*?":N;if(Y.capture)j=`(${j})`;let S=(D)=>{if(D.noglobstar===!0)return j;return`(${O}(?:(?!${q}${D.dot?B:X}).)*?)`},b=(D)=>{switch(D){case"*":return`${w}${V}${j}`;case".*":return`${X}${V}${j}`;case"*.*":return`${w}${j}${X}${V}${j}`;case"*/*":return`${w}${j}${K}${V}${A}${j}`;case"**":return w+S(Y);case"**/*":return`(?:${w}${S(Y)}${K})?${A}${V}${j}`;case"**/*.*":return`(?:${w}${S(Y)}${K})?${A}${j}${X}${V}${j}`;case"**/.*":return`(?:${w}${S(Y)}${K})?${X}${V}${j}`;default:{let I=/^(.*?)\.(\w+)$/.exec(D);if(!I)return;let M=b(I[1]);if(!M)return;return M+X+I[2]}}},y=I1.removePrefix($,H),k=b(y);if(k&&Y.strictSlashes!==!0)k+=`${K}?`;return k};cW.exports=dY});var iW=d((Ff,pW)=>{var Lz=V1("path"),Ez=dW(),uY=lW(),cY=pZ(),_z=lZ(),Oz=($)=>$&&typeof $==="object"&&!Array.isArray($),G1=($,Z,Y=!1)=>{if(Array.isArray($)){let G=$.map((z)=>G1(z,Z,Y));return(z)=>{for(let N of G){let q=N(z);if(q)return q}return!1}}let W=Oz($)&&$.tokens&&$.input;if($===""||typeof $!=="string"&&!W)throw TypeError("Expected pattern to be a non-empty string");let J=Z||{},Q=cY.isWindows(Z),X=W?G1.compileRe($,Z):G1.makeRe($,Z,!1,!0),K=X.state;delete X.state;let V=()=>!1;if(J.ignore){let G={...Z,ignore:null,onMatch:null,onResult:null};V=G1(J.ignore,G,Y)}let B=(G,F=!1)=>{let{isMatch:z,match:N,output:q}=G1.test(G,X,Z,{glob:$,posix:Q}),w={glob:$,state:K,regex:X,posix:Q,input:G,output:q,match:N,isMatch:z};if(typeof J.onResult==="function")J.onResult(w);if(z===!1)return w.isMatch=!1,F?w:!1;if(V(G)){if(typeof J.onIgnore==="function")J.onIgnore(w);return w.isMatch=!1,F?w:!1}if(typeof J.onMatch==="function")J.onMatch(w);return F?w:!0};if(Y)B.state=K;return B};G1.test=($,Z,Y,{glob:W,posix:J}={})=>{if(typeof $!=="string")throw TypeError("Expected input to be a string");if($==="")return{isMatch:!1,output:""};let Q=Y||{},X=Q.format||(J?cY.toPosixSlashes:null),K=$===W,V=K&&X?X($):$;if(K===!1)V=X?X($):$,K=V===W;if(K===!1||Q.capture===!0)if(Q.matchBase===!0||Q.basename===!0)K=G1.matchBase($,Z,Y,J);else K=Z.exec(V);return{isMatch:Boolean(K),match:K,output:V}};G1.matchBase=($,Z,Y,W=cY.isWindows(Y))=>{return(Z instanceof RegExp?Z:G1.makeRe(Z,Y)).test(Lz.basename($))};G1.isMatch=($,Z,Y)=>G1(Z,Y)($);G1.parse=($,Z)=>{if(Array.isArray($))return $.map((Y)=>G1.parse(Y,Z));return uY($,{...Z,fastpaths:!1})};G1.scan=($,Z)=>Ez($,Z);G1.compileRe=($,Z,Y=!1,W=!1)=>{if(Y===!0)return $.output;let J=Z||{},Q=J.contains?"":"^",X=J.contains?"":"$",K=`${Q}(?:${$.output})${X}`;if($&&$.negated===!0)K=`^(?!${K}).*$`;let V=G1.toRegex(K,Z);if(W===!0)V.state=$;return V};G1.makeRe=($,Z={},Y=!1,W=!1)=>{if(!$||typeof $!=="string")throw TypeError("Expected a non-empty string");let J={negated:!1,fastpaths:!0};if(Z.fastpaths!==!1&&($[0]==="."||$[0]==="*"))J.output=uY.fastpaths($,Z);if(!J.output)J=uY($,Z);return G1.compileRe(J,Z,Y,W)};G1.toRegex=($,Z)=>{try{let Y=Z||{};return new RegExp($,Y.flags||(Y.nocase?"i":""))}catch(Y){if(Z&&Z.debug===!0)throw Y;return/$^/}};G1.constants=_z;pW.exports=G1});var tW=d((qf,sW)=>{var rW=V1("util"),aW=AW(),a1=iW(),lY=pZ(),nW=($)=>$===""||$==="./",oW=($)=>{let Z=$.indexOf("{");return Z>-1&&$.indexOf("}",Z)>-1},K1=($,Z,Y)=>{Z=[].concat(Z),$=[].concat($);let W=new Set,J=new Set,Q=new Set,X=0,K=(G)=>{if(Q.add(G.output),Y&&Y.onResult)Y.onResult(G)};for(let G=0;G<Z.length;G++){let F=a1(String(Z[G]),{...Y,onResult:K},!0),z=F.state.negated||F.state.negatedExtglob;if(z)X++;for(let N of $){let q=F(N,!0);if(!(z?!q.isMatch:q.isMatch))continue;if(z)W.add(q.output);else W.delete(q.output),J.add(q.output)}}let B=(X===Z.length?[...Q]:[...J]).filter((G)=>!W.has(G));if(Y&&B.length===0){if(Y.failglob===!0)throw Error(`No matches found for "${Z.join(", ")}"`);if(Y.nonull===!0||Y.nullglob===!0)return Y.unescape?Z.map((G)=>G.replace(/\\/g,"")):Z}return B};K1.match=K1;K1.matcher=($,Z)=>a1($,Z);K1.isMatch=($,Z,Y)=>a1(Z,Y)($);K1.any=K1.isMatch;K1.not=($,Z,Y={})=>{Z=[].concat(Z).map(String);let W=new Set,J=[],X=new Set(K1($,Z,{...Y,onResult:(K)=>{if(Y.onResult)Y.onResult(K);J.push(K.output)}}));for(let K of J)if(!X.has(K))W.add(K);return[...W]};K1.contains=($,Z,Y)=>{if(typeof $!=="string")throw TypeError(`Expected a string: "${rW.inspect($)}"`);if(Array.isArray(Z))return Z.some((W)=>K1.contains($,W,Y));if(typeof Z==="string"){if(nW($)||nW(Z))return!1;if($.includes(Z)||$.startsWith("./")&&$.slice(2).includes(Z))return!0}return K1.isMatch($,Z,{...Y,contains:!0})};K1.matchKeys=($,Z,Y)=>{if(!lY.isObject($))throw TypeError("Expected the first argument to be an object");let W=K1(Object.keys($),Z,Y),J={};for(let Q of W)J[Q]=$[Q];return J};K1.some=($,Z,Y)=>{let W=[].concat($);for(let J of[].concat(Z)){let Q=a1(String(J),Y);if(W.some((X)=>Q(X)))return!0}return!1};K1.every=($,Z,Y)=>{let W=[].concat($);for(let J of[].concat(Z)){let Q=a1(String(J),Y);if(!W.every((X)=>Q(X)))return!1}return!0};K1.all=($,Z,Y)=>{if(typeof $!=="string")throw TypeError(`Expected a string: "${rW.inspect($)}"`);return[].concat(Z).every((W)=>a1(W,Y)($))};K1.capture=($,Z,Y)=>{let W=lY.isWindows(Y),Q=a1.makeRe(String($),{...Y,capture:!0}).exec(W?lY.toPosixSlashes(Z):Z);if(Q)return Q.slice(1).map((X)=>X===void 0?"":X)};K1.makeRe=(...$)=>a1.makeRe(...$);K1.scan=(...$)=>a1.scan(...$);K1.parse=($,Z)=>{let Y=[];for(let W of[].concat($||[]))for(let J of aW(String(W),Z))Y.push(a1.parse(J,Z));return Y};K1.braces=($,Z)=>{if(typeof $!=="string")throw TypeError("Expected a string");if(Z&&Z.nobrace===!0||!oW($))return[$];return aW($,Z)};K1.braceExpand=($,Z)=>{if(typeof $!=="string")throw TypeError("Expected a string");return K1.braces($,{...Z,expand:!0})};K1.hasBraces=oW;sW.exports=K1});var G4=d((V4)=>{Object.defineProperty(V4,"__esModule",{value:!0});V4.isAbsolute=V4.partitionAbsoluteAndRelative=V4.removeDuplicateSlashes=V4.matchAny=V4.convertPatternsToRe=V4.makeRe=V4.getPatternParts=V4.expandBraceExpansion=V4.expandPatternsWithBraceExpansion=V4.isAffectDepthOfReadingPattern=V4.endsWithSlashGlobStar=V4.hasGlobStar=V4.getBaseDirectory=V4.isPatternRelatedToParentDirectory=V4.getPatternsOutsideCurrentDirectory=V4.getPatternsInsideCurrentDirectory=V4.getPositivePatterns=V4.getNegativePatterns=V4.isPositivePattern=V4.isNegativePattern=V4.convertToNegativePattern=V4.convertToPositivePattern=V4.isDynamicPattern=V4.isStaticPattern=void 0;var eW=V1("path"),Dz=n5(),pY=tW(),$4="**",jz="\\",fz=/[*?]|^!/,Tz=/\[[^[]*]/,Pz=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,Sz=/[!*+?@]\([^(]*\)/,Az=/,|\.\./,Cz=/(?!^)\/{2,}/g;function Z4($,Z={}){return!Y4($,Z)}V4.isStaticPattern=Z4;function Y4($,Z={}){if($==="")return!1;if(Z.caseSensitiveMatch===!1||$.includes(jz))return!0;if(fz.test($)||Tz.test($)||Pz.test($))return!0;if(Z.extglob!==!1&&Sz.test($))return!0;if(Z.braceExpansion!==!1&&xz($))return!0;return!1}V4.isDynamicPattern=Y4;function xz($){let Z=$.indexOf("{");if(Z===-1)return!1;let Y=$.indexOf("}",Z+1);if(Y===-1)return!1;let W=$.slice(Z,Y);return Az.test(W)}function Rz($){return e8($)?$.slice(1):$}V4.convertToPositivePattern=Rz;function yz($){return"!"+$}V4.convertToNegativePattern=yz;function e8($){return $.startsWith("!")&&$[1]!=="("}V4.isNegativePattern=e8;function W4($){return!e8($)}V4.isPositivePattern=W4;function kz($){return $.filter(e8)}V4.getNegativePatterns=kz;function Iz($){return $.filter(W4)}V4.getPositivePatterns=Iz;function bz($){return $.filter((Z)=>!iY(Z))}V4.getPatternsInsideCurrentDirectory=bz;function vz($){return $.filter(iY)}V4.getPatternsOutsideCurrentDirectory=vz;function iY($){return $.startsWith("..")||$.startsWith("./..")}V4.isPatternRelatedToParentDirectory=iY;function hz($){return Dz($,{flipBackslashes:!1})}V4.getBaseDirectory=hz;function gz($){return $.includes($4)}V4.hasGlobStar=gz;function J4($){return $.endsWith("/"+$4)}V4.endsWithSlashGlobStar=J4;function mz($){let Z=eW.basename($);return J4($)||Z4(Z)}V4.isAffectDepthOfReadingPattern=mz;function dz($){return $.reduce((Z,Y)=>{return Z.concat(Q4(Y))},[])}V4.expandPatternsWithBraceExpansion=dz;function Q4($){let Z=pY.braces($,{expand:!0,nodupes:!0,keepEscaping:!0});return Z.sort((Y,W)=>Y.length-W.length),Z.filter((Y)=>Y!=="")}V4.expandBraceExpansion=Q4;function uz($,Z){let{parts:Y}=pY.scan($,Object.assign(Object.assign({},Z),{parts:!0}));if(Y.length===0)Y=[$];if(Y[0].startsWith("/"))Y[0]=Y[0].slice(1),Y.unshift("");return Y}V4.getPatternParts=uz;function X4($,Z){return pY.makeRe($,Z)}V4.makeRe=X4;function cz($,Z){return $.map((Y)=>X4(Y,Z))}V4.convertPatternsToRe=cz;function lz($,Z){return Z.some((Y)=>Y.test($))}V4.matchAny=lz;function pz($){return $.replace(Cz,"/")}V4.removeDuplicateSlashes=pz;function iz($){let Z=[],Y=[];for(let W of $)if(K4(W))Z.push(W);else Y.push(W);return[Z,Y]}V4.partitionAbsoluteAndRelative=iz;function K4($){return eW.isAbsolute($)}V4.isAbsolute=K4});var U4=d((Hf,q4)=>{var NG=V1("stream"),B4=NG.PassThrough,MG=Array.prototype.slice;q4.exports=wG;function wG(){let $=[],Z=MG.call(arguments),Y=!1,W=Z[Z.length-1];if(W&&!Array.isArray(W)&&W.pipe==null)Z.pop();else W={};let J=W.end!==!1,Q=W.pipeError===!0;if(W.objectMode==null)W.objectMode=!0;if(W.highWaterMark==null)W.highWaterMark=65536;let X=B4(W);function K(){for(let G=0,F=arguments.length;G<F;G++)$.push(F4(arguments[G],W));return V(),this}function V(){if(Y)return;Y=!0;let G=$.shift();if(!G){process.nextTick(B);return}if(!Array.isArray(G))G=[G];let F=G.length+1;function z(){if(--F>0)return;Y=!1,V()}function N(q){function w(){if(q.removeListener("merge2UnpipeEnd",w),q.removeListener("end",w),Q)q.removeListener("error",A);z()}function A(O){X.emit("error",O)}if(q._readableState.endEmitted)return z();if(q.on("merge2UnpipeEnd",w),q.on("end",w),Q)q.on("error",A);q.pipe(X,{end:!1}),q.resume()}for(let q=0;q<G.length;q++)N(G[q]);z()}function B(){if(Y=!1,X.emit("queueDrain"),J)X.end()}if(X.setMaxListeners(0),X.add=K,X.on("unpipe",function(G){G.emit("merge2UnpipeEnd")}),Z.length)K.apply(null,Z);return X}function F4($,Z){if(!Array.isArray($)){if(!$._readableState&&$.pipe)$=$.pipe(B4(Z));if(!$._readableState||!$.pause||!$.pipe)throw Error("Only readable stream can be merged.");$.pause()}else for(let Y=0,W=$.length;Y<W;Y++)$[Y]=F4($[Y],Z);return $}});var w4=d((N4)=>{Object.defineProperty(N4,"__esModule",{value:!0});N4.merge=void 0;var LG=U4();function EG($){let Z=LG($);return $.forEach((Y)=>{Y.once("error",(W)=>Z.emit("error",W))}),Z.once("close",()=>H4($)),Z.once("end",()=>H4($)),Z}N4.merge=EG;function H4($){$.forEach((Z)=>Z.emit("close"))}});var _4=d((L4)=>{Object.defineProperty(L4,"__esModule",{value:!0});L4.isEmpty=L4.isString=void 0;function _G($){return typeof $==="string"}L4.isString=_G;function OG($){return $===""}L4.isEmpty=OG});var K0=d((O4)=>{Object.defineProperty(O4,"__esModule",{value:!0});O4.string=O4.stream=O4.pattern=O4.path=O4.fs=O4.errno=O4.array=void 0;var jG=P5();O4.array=jG;var fG=C5();O4.errno=fG;var TG=k5();O4.fs=TG;var PG=m5();O4.path=PG;var SG=G4();O4.pattern=SG;var AG=w4();O4.stream=AG;var CG=_4();O4.string=CG});var A4=d((P4)=>{Object.defineProperty(P4,"__esModule",{value:!0});P4.convertPatternGroupToTask=P4.convertPatternGroupsToTasks=P4.groupPatternsByBaseDirectory=P4.getNegativePatternsAsPositive=P4.getPositivePatterns=P4.convertPatternsToTasks=P4.generate=void 0;var d1=K0();function vG($,Z){let Y=j4($,Z),W=j4(Z.ignore,Z),J=f4(Y),Q=T4(Y,W),X=J.filter((G)=>d1.pattern.isStaticPattern(G,Z)),K=J.filter((G)=>d1.pattern.isDynamicPattern(G,Z)),V=nY(X,Q,!1),B=nY(K,Q,!0);return V.concat(B)}P4.generate=vG;function j4($,Z){let Y=$;if(Z.braceExpansion)Y=d1.pattern.expandPatternsWithBraceExpansion(Y);if(Z.baseNameMatch)Y=Y.map((W)=>W.includes("/")?W:`**/${W}`);return Y.map((W)=>d1.pattern.removeDuplicateSlashes(W))}function nY($,Z,Y){let W=[],J=d1.pattern.getPatternsOutsideCurrentDirectory($),Q=d1.pattern.getPatternsInsideCurrentDirectory($),X=rY(J),K=rY(Q);if(W.push(...aY(X,Z,Y)),"."in K)W.push(oY(".",Q,Z,Y));else W.push(...aY(K,Z,Y));return W}P4.convertPatternsToTasks=nY;function f4($){return d1.pattern.getPositivePatterns($)}P4.getPositivePatterns=f4;function T4($,Z){return d1.pattern.getNegativePatterns($).concat(Z).map(d1.pattern.convertToPositivePattern)}P4.getNegativePatternsAsPositive=T4;function rY($){let Z={};return $.reduce((Y,W)=>{let J=d1.pattern.getBaseDirectory(W);if(J in Y)Y[J].push(W);else Y[J]=[W];return Y},Z)}P4.groupPatternsByBaseDirectory=rY;function aY($,Z,Y){return Object.keys($).map((W)=>{return oY(W,$[W],Z,Y)})}P4.convertPatternGroupsToTasks=aY;function oY($,Z,Y,W){return{dynamic:W,positive:Z,negative:Y,base:$,patterns:[].concat(Z,Y.map(d1.pattern.convertToNegativePattern))}}P4.convertPatternGroupToTask=oY});var y4=d((x4)=>{Object.defineProperty(x4,"__esModule",{value:!0});x4.read=void 0;function lG($,Z,Y){Z.fs.lstat($,(W,J)=>{if(W!==null){C4(Y,W);return}if(!J.isSymbolicLink()||!Z.followSymbolicLink){sY(Y,J);return}Z.fs.stat($,(Q,X)=>{if(Q!==null){if(Z.throwErrorOnBrokenSymbolicLink){C4(Y,Q);return}sY(Y,J);return}if(Z.markSymbolicLink)X.isSymbolicLink=()=>!0;sY(Y,X)})})}x4.read=lG;function C4($,Z){$(Z)}function sY($,Z){$(null,Z)}});var b4=d((k4)=>{Object.defineProperty(k4,"__esModule",{value:!0});k4.read=void 0;function pG($,Z){let Y=Z.fs.lstatSync($);if(!Y.isSymbolicLink()||!Z.followSymbolicLink)return Y;try{let W=Z.fs.statSync($);if(Z.markSymbolicLink)W.isSymbolicLink=()=>!0;return W}catch(W){if(!Z.throwErrorOnBrokenSymbolicLink)return Y;throw W}}k4.read=pG});var g4=d((v4)=>{Object.defineProperty(v4,"__esModule",{value:!0});v4.createFileSystemAdapter=v4.FILE_SYSTEM_ADAPTER=void 0;var $6=V1("fs");v4.FILE_SYSTEM_ADAPTER={lstat:$6.lstat,stat:$6.stat,lstatSync:$6.lstatSync,statSync:$6.statSync};function iG($){if($===void 0)return v4.FILE_SYSTEM_ADAPTER;return Object.assign(Object.assign({},v4.FILE_SYSTEM_ADAPTER),$)}v4.createFileSystemAdapter=iG});var u4=d((d4)=>{Object.defineProperty(d4,"__esModule",{value:!0});var nG=g4();class m4{constructor($={}){this._options=$,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=nG.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue($,Z){return $!==null&&$!==void 0?$:Z}}d4.default=m4});var s0=d((l4)=>{Object.defineProperty(l4,"__esModule",{value:!0});l4.statSync=l4.stat=l4.Settings=void 0;var c4=y4(),aG=b4(),eY=u4();l4.Settings=eY.default;function oG($,Z,Y){if(typeof Z==="function"){c4.read($,$7(),Z);return}c4.read($,$7(Z),Y)}l4.stat=oG;function sG($,Z){let Y=$7(Z);return aG.read($,Y)}l4.statSync=sG;function $7($={}){if($ instanceof eY.default)return $;return new eY.default($)}});var r4=d((ff,n4)=>{/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var i4;n4.exports=typeof queueMicrotask==="function"?queueMicrotask.bind(typeof window<"u"?window:global):($)=>(i4||(i4=Promise.resolve())).then($).catch((Z)=>setTimeout(()=>{throw Z},0))});var o4=d((Tf,a4)=>{/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */a4.exports=ZB;var $B=r4();function ZB($,Z){let Y,W,J,Q=!0;if(Array.isArray($))Y=[],W=$.length;else J=Object.keys($),Y={},W=J.length;function X(V){function B(){if(Z)Z(V,Y);Z=null}if(Q)$B(B);else B()}function K(V,B,G){if(Y[V]=G,--W===0||B)X(B)}if(!W)X(null);else if(J)J.forEach(function(V){$[V](function(B,G){K(V,B,G)})});else $.forEach(function(V,B){V(function(G,F){K(B,G,F)})});Q=!1}});var Z7=d((e4)=>{Object.defineProperty(e4,"__esModule",{value:!0});e4.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var Z6=process.versions.node.split(".");if(Z6[0]===void 0||Z6[1]===void 0)throw Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var s4=Number.parseInt(Z6[0],10),YB=Number.parseInt(Z6[1],10),t4=10,WB=10,JB=s4>t4,QB=s4===t4&&YB>=WB;e4.IS_SUPPORT_READDIR_WITH_FILE_TYPES=JB||QB});var J3=d((Y3)=>{Object.defineProperty(Y3,"__esModule",{value:!0});Y3.createDirentFromStats=void 0;class Z3{constructor($,Z){this.name=$,this.isBlockDevice=Z.isBlockDevice.bind(Z),this.isCharacterDevice=Z.isCharacterDevice.bind(Z),this.isDirectory=Z.isDirectory.bind(Z),this.isFIFO=Z.isFIFO.bind(Z),this.isFile=Z.isFile.bind(Z),this.isSocket=Z.isSocket.bind(Z),this.isSymbolicLink=Z.isSymbolicLink.bind(Z)}}function XB($,Z){return new Z3($,Z)}Y3.createDirentFromStats=XB});var Y7=d((Q3)=>{Object.defineProperty(Q3,"__esModule",{value:!0});Q3.fs=void 0;var KB=J3();Q3.fs=KB});var W7=d((K3)=>{Object.defineProperty(K3,"__esModule",{value:!0});K3.joinPathSegments=void 0;function VB($,Z,Y){if($.endsWith(Y))return $+Z;return $+Y+Z}K3.joinPathSegments=VB});var N3=d((U3)=>{Object.defineProperty(U3,"__esModule",{value:!0});U3.readdir=U3.readdirWithFileTypes=U3.read=void 0;var zB=s0(),z3=o4(),GB=Z7(),G3=Y7(),B3=W7();function BB($,Z,Y){if(!Z.stats&&GB.IS_SUPPORT_READDIR_WITH_FILE_TYPES){F3($,Z,Y);return}q3($,Z,Y)}U3.read=BB;function F3($,Z,Y){Z.fs.readdir($,{withFileTypes:!0},(W,J)=>{if(W!==null){Y6(Y,W);return}let Q=J.map((K)=>({dirent:K,name:K.name,path:B3.joinPathSegments($,K.name,Z.pathSegmentSeparator)}));if(!Z.followSymbolicLinks){J7(Y,Q);return}let X=Q.map((K)=>FB(K,Z));z3(X,(K,V)=>{if(K!==null){Y6(Y,K);return}J7(Y,V)})})}U3.readdirWithFileTypes=F3;function FB($,Z){return(Y)=>{if(!$.dirent.isSymbolicLink()){Y(null,$);return}Z.fs.stat($.path,(W,J)=>{if(W!==null){if(Z.throwErrorOnBrokenSymbolicLink){Y(W);return}Y(null,$);return}$.dirent=G3.fs.createDirentFromStats($.name,J),Y(null,$)})}}function q3($,Z,Y){Z.fs.readdir($,(W,J)=>{if(W!==null){Y6(Y,W);return}let Q=J.map((X)=>{let K=B3.joinPathSegments($,X,Z.pathSegmentSeparator);return(V)=>{zB.stat(K,Z.fsStatSettings,(B,G)=>{if(B!==null){V(B);return}let F={name:X,path:K,dirent:G3.fs.createDirentFromStats(X,G)};if(Z.stats)F.stats=G;V(null,F)})}});z3(Q,(X,K)=>{if(X!==null){Y6(Y,X);return}J7(Y,K)})})}U3.readdir=q3;function Y6($,Z){$(Z)}function J7($,Z){$(null,Z)}});var D3=d((_3)=>{Object.defineProperty(_3,"__esModule",{value:!0});_3.readdir=_3.readdirWithFileTypes=_3.read=void 0;var HB=s0(),NB=Z7(),M3=Y7(),w3=W7();function MB($,Z){if(!Z.stats&&NB.IS_SUPPORT_READDIR_WITH_FILE_TYPES)return L3($,Z);return E3($,Z)}_3.read=MB;function L3($,Z){return Z.fs.readdirSync($,{withFileTypes:!0}).map((W)=>{let J={dirent:W,name:W.name,path:w3.joinPathSegments($,W.name,Z.pathSegmentSeparator)};if(J.dirent.isSymbolicLink()&&Z.followSymbolicLinks)try{let Q=Z.fs.statSync(J.path);J.dirent=M3.fs.createDirentFromStats(J.name,Q)}catch(Q){if(Z.throwErrorOnBrokenSymbolicLink)throw Q}return J})}_3.readdirWithFileTypes=L3;function E3($,Z){return Z.fs.readdirSync($).map((W)=>{let J=w3.joinPathSegments($,W,Z.pathSegmentSeparator),Q=HB.statSync(J,Z.fsStatSettings),X={name:W,path:J,dirent:M3.fs.createDirentFromStats(W,Q)};if(Z.stats)X.stats=Q;return X})}_3.readdir=E3});var T3=d((j3)=>{Object.defineProperty(j3,"__esModule",{value:!0});j3.createFileSystemAdapter=j3.FILE_SYSTEM_ADAPTER=void 0;var C$=V1("fs");j3.FILE_SYSTEM_ADAPTER={lstat:C$.lstat,stat:C$.stat,lstatSync:C$.lstatSync,statSync:C$.statSync,readdir:C$.readdir,readdirSync:C$.readdirSync};function EB($){if($===void 0)return j3.FILE_SYSTEM_ADAPTER;return Object.assign(Object.assign({},j3.FILE_SYSTEM_ADAPTER),$)}j3.createFileSystemAdapter=EB});var A3=d((S3)=>{Object.defineProperty(S3,"__esModule",{value:!0});var _B=V1("path"),OB=s0(),DB=T3();class P3{constructor($={}){this._options=$,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=DB.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,_B.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new OB.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue($,Z){return $!==null&&$!==void 0?$:Z}}S3.default=P3});var W6=d((x3)=>{Object.defineProperty(x3,"__esModule",{value:!0});x3.Settings=x3.scandirSync=x3.scandir=void 0;var C3=N3(),fB=D3(),X7=A3();x3.Settings=X7.default;function TB($,Z,Y){if(typeof Z==="function"){C3.read($,K7(),Z);return}C3.read($,K7(Z),Y)}x3.scandir=TB;function PB($,Z){let Y=K7(Z);return fB.read($,Y)}x3.scandirSync=PB;function K7($={}){if($ instanceof X7.default)return $;return new X7.default($)}});var k3=d((bf,y3)=>{function CB($){var Z=new $,Y=Z;function W(){var Q=Z;if(Q.next)Z=Q.next;else Z=new $,Y=Z;return Q.next=null,Q}function J(Q){Y.next=Q,Y=Q}return{get:W,release:J}}y3.exports=CB});var b3=d((vf,V7)=>{var xB=k3();function I3($,Z,Y){if(typeof $==="function")Y=Z,Z=$,$=null;if(!(Y>=1))throw Error("fastqueue concurrency must be equal to or greater than 1");var W=xB(RB),J=null,Q=null,X=0,K=null,V={push:w,drain:f1,saturated:f1,pause:G,paused:!1,get concurrency(){return Y},set concurrency(y){if(!(y>=1))throw Error("fastqueue concurrency must be equal to or greater than 1");if(Y=y,V.paused)return;for(;J&&X<Y;)X++,O()},running:B,resume:N,idle:q,length:F,getQueue:z,unshift:A,empty:f1,kill:H,killAndDrain:j,error:b,abort:S};return V;function B(){return X}function G(){V.paused=!0}function F(){var y=J,k=0;while(y)y=y.next,k++;return k}function z(){var y=J,k=[];while(y)k.push(y.value),y=y.next;return k}function N(){if(!V.paused)return;if(V.paused=!1,J===null){X++,O();return}for(;J&&X<Y;)X++,O()}function q(){return X===0&&V.length()===0}function w(y,k){var D=W.get();if(D.context=$,D.release=O,D.value=y,D.callback=k||f1,D.errorHandler=K,X>=Y||V.paused)if(Q)Q.next=D,Q=D;else J=D,Q=D,V.saturated();else X++,Z.call($,D.value,D.worked)}function A(y,k){var D=W.get();if(D.context=$,D.release=O,D.value=y,D.callback=k||f1,D.errorHandler=K,X>=Y||V.paused)if(J)D.next=J,J=D;else J=D,Q=D,V.saturated();else X++,Z.call($,D.value,D.worked)}function O(y){if(y)W.release(y);var k=J;if(k&&X<=Y)if(!V.paused){if(Q===J)Q=null;if(J=k.next,k.next=null,Z.call($,k.value,k.worked),Q===null)V.empty()}else X--;else if(--X===0)V.drain()}function H(){J=null,Q=null,V.drain=f1}function j(){J=null,Q=null,V.drain(),V.drain=f1}function S(){var y=J;J=null,Q=null;while(y){var{next:k,callback:D,errorHandler:I,value:M,context:L}=y;if(y.value=null,y.callback=f1,y.errorHandler=null,I)I(Error("abort"),M);D.call(L,Error("abort")),y.release(y),y=k}V.drain=f1}function b(y){K=y}}function f1(){}function RB(){this.value=null,this.callback=f1,this.next=null,this.release=f1,this.context=null,this.errorHandler=null;var $=this;this.worked=function(Y,W){var{callback:J,errorHandler:Q,value:X}=$;if($.value=null,$.callback=f1,$.errorHandler)Q(Y,X);J.call($.context,Y,W),$.release($)}}function yB($,Z,Y){if(typeof $==="function")Y=Z,Z=$,$=null;function W(G,F){Z.call(this,G).then(function(z){F(null,z)},F)}var J=I3($,W,Y),Q=J.push,X=J.unshift;return J.push=K,J.unshift=V,J.drained=B,J;function K(G){var F=new Promise(function(z,N){Q(G,function(q,w){if(q){N(q);return}z(w)})});return F.catch(f1),F}function V(G){var F=new Promise(function(z,N){X(G,function(q,w){if(q){N(q);return}z(w)})});return F.catch(f1),F}function B(){var G=new Promise(function(F){process.nextTick(function(){if(J.idle())F();else{var z=J.drain;J.drain=function(){if(typeof z==="function")z();F(),J.drain=z}}})});return G}}V7.exports=I3;V7.exports.promise=yB});var J6=d((v3)=>{Object.defineProperty(v3,"__esModule",{value:!0});v3.joinPathSegments=v3.replacePathSegmentSeparator=v3.isAppliedFilter=v3.isFatalError=void 0;function kB($,Z){if($.errorFilter===null)return!0;return!$.errorFilter(Z)}v3.isFatalError=kB;function IB($,Z){return $===null||$(Z)}v3.isAppliedFilter=IB;function bB($,Z){return $.split(/[/\\]/).join(Z)}v3.replacePathSegmentSeparator=bB;function vB($,Z,Y){if($==="")return Z;if($.endsWith(Y))return $+Z;return $+Y+Z}v3.joinPathSegments=vB});var z7=d((m3)=>{Object.defineProperty(m3,"__esModule",{value:!0});var dB=J6();class g3{constructor($,Z){this._root=$,this._settings=Z,this._root=dB.replacePathSegmentSeparator($,Z.pathSegmentSeparator)}}m3.default=g3});var G7=d((u3)=>{Object.defineProperty(u3,"__esModule",{value:!0});var cB=V1("events"),lB=W6(),pB=b3(),Q6=J6(),iB=z7();class d3 extends iB.default{constructor($,Z){super($,Z);this._settings=Z,this._scandir=lB.scandir,this._emitter=new cB.EventEmitter,this._queue=pB(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{if(!this._isFatalError)this._emitter.emit("end")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw Error("The reader is already destroyed");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry($){this._emitter.on("entry",$)}onError($){this._emitter.once("error",$)}onEnd($){this._emitter.once("end",$)}_pushToQueue($,Z){let Y={directory:$,base:Z};this._queue.push(Y,(W)=>{if(W!==null)this._handleError(W)})}_worker($,Z){this._scandir($.directory,this._settings.fsScandirSettings,(Y,W)=>{if(Y!==null){Z(Y,void 0);return}for(let J of W)this._handleEntry(J,$.base);Z(null,void 0)})}_handleError($){if(this._isDestroyed||!Q6.isFatalError(this._settings,$))return;this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit("error",$)}_handleEntry($,Z){if(this._isDestroyed||this._isFatalError)return;let Y=$.path;if(Z!==void 0)$.path=Q6.joinPathSegments(Z,$.name,this._settings.pathSegmentSeparator);if(Q6.isAppliedFilter(this._settings.entryFilter,$))this._emitEntry($);if($.dirent.isDirectory()&&Q6.isAppliedFilter(this._settings.deepFilter,$))this._pushToQueue(Y,Z===void 0?void 0:$.path)}_emitEntry($){this._emitter.emit("entry",$)}}u3.default=d3});var p3=d((l3)=>{Object.defineProperty(l3,"__esModule",{value:!0});var rB=G7();class c3{constructor($,Z){this._root=$,this._settings=Z,this._reader=new rB.default(this._root,this._settings),this._storage=[]}read($){this._reader.onError((Z)=>{aB($,Z)}),this._reader.onEntry((Z)=>{this._storage.push(Z)}),this._reader.onEnd(()=>{oB($,this._storage)}),this._reader.read()}}l3.default=c3;function aB($,Z){$(Z)}function oB($,Z){$(null,Z)}});var r3=d((n3)=>{Object.defineProperty(n3,"__esModule",{value:!0});var tB=V1("stream"),eB=G7();class i3{constructor($,Z){this._root=$,this._settings=Z,this._reader=new eB.default(this._root,this._settings),this._stream=new tB.Readable({objectMode:!0,read:()=>{},destroy:()=>{if(!this._reader.isDestroyed)this._reader.destroy()}})}read(){return this._reader.onError(($)=>{this._stream.emit("error",$)}),this._reader.onEntry(($)=>{this._stream.push($)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}}n3.default=i3});var s3=d((o3)=>{Object.defineProperty(o3,"__esModule",{value:!0});var ZF=W6(),X6=J6(),YF=z7();class a3 extends YF.default{constructor(){super(...arguments);this._scandir=ZF.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue($,Z){this._queue.add({directory:$,base:Z})}_handleQueue(){for(let $ of this._queue.values())this._handleDirectory($.directory,$.base)}_handleDirectory($,Z){try{let Y=this._scandir($,this._settings.fsScandirSettings);for(let W of Y)this._handleEntry(W,Z)}catch(Y){this._handleError(Y)}}_handleError($){if(!X6.isFatalError(this._settings,$))return;throw $}_handleEntry($,Z){let Y=$.path;if(Z!==void 0)$.path=X6.joinPathSegments(Z,$.name,this._settings.pathSegmentSeparator);if(X6.isAppliedFilter(this._settings.entryFilter,$))this._pushToStorage($);if($.dirent.isDirectory()&&X6.isAppliedFilter(this._settings.deepFilter,$))this._pushToQueue(Y,Z===void 0?void 0:$.path)}_pushToStorage($){this._storage.push($)}}o3.default=a3});var $2=d((e3)=>{Object.defineProperty(e3,"__esModule",{value:!0});var JF=s3();class t3{constructor($,Z){this._root=$,this._settings=Z,this._reader=new JF.default(this._root,this._settings)}read(){return this._reader.read()}}e3.default=t3});var W2=d((Y2)=>{Object.defineProperty(Y2,"__esModule",{value:!0});var XF=V1("path"),KF=W6();class Z2{constructor($={}){this._options=$,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,XF.sep),this.fsScandirSettings=new KF.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue($,Z){return $!==null&&$!==void 0?$:Z}}Y2.default=Z2});var V6=d((Q2)=>{Object.defineProperty(Q2,"__esModule",{value:!0});Q2.Settings=Q2.walkStream=Q2.walkSync=Q2.walk=void 0;var J2=p3(),zF=r3(),GF=$2(),B7=W2();Q2.Settings=B7.default;function BF($,Z,Y){if(typeof Z==="function"){new J2.default($,K6()).read(Z);return}new J2.default($,K6(Z)).read(Y)}Q2.walk=BF;function FF($,Z){let Y=K6(Z);return new GF.default($,Y).read()}Q2.walkSync=FF;function qF($,Z){let Y=K6(Z);return new zF.default($,Y).read()}Q2.walkStream=qF;function K6($={}){if($ instanceof B7.default)return $;return new B7.default($)}});var z6=d((z2)=>{Object.defineProperty(z2,"__esModule",{value:!0});var MF=V1("path"),wF=s0(),K2=K0();class V2{constructor($){this._settings=$,this._fsStatSettings=new wF.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath($){return MF.resolve(this._settings.cwd,$)}_makeEntry($,Z){let Y={name:Z,path:Z,dirent:K2.fs.createDirentFromStats(Z,$)};if(this._settings.stats)Y.stats=$;return Y}_isFatalError($){return!K2.errno.isEnoentCodeError($)&&!this._settings.suppressErrors}}z2.default=V2});var F7=d((B2)=>{Object.defineProperty(B2,"__esModule",{value:!0});var EF=V1("stream"),_F=s0(),OF=V6(),DF=z6();class G2 extends DF.default{constructor(){super(...arguments);this._walkStream=OF.walkStream,this._stat=_F.stat}dynamic($,Z){return this._walkStream($,Z)}static($,Z){let Y=$.map(this._getFullEntryPath,this),W=new EF.PassThrough({objectMode:!0});W._write=(J,Q,X)=>{return this._getEntry(Y[J],$[J],Z).then((K)=>{if(K!==null&&Z.entryFilter(K))W.push(K);if(J===Y.length-1)W.end();X()}).catch(X)};for(let J=0;J<Y.length;J++)W.write(J);return W}_getEntry($,Z,Y){return this._getStat($).then((W)=>this._makeEntry(W,Z)).catch((W)=>{if(Y.errorFilter(W))return null;throw W})}_getStat($){return new Promise((Z,Y)=>{this._stat($,this._fsStatSettings,(W,J)=>{return W===null?Z(J):Y(W)})})}}B2.default=G2});var U2=d((q2)=>{Object.defineProperty(q2,"__esModule",{value:!0});var fF=V6(),TF=z6(),PF=F7();class F2 extends TF.default{constructor(){super(...arguments);this._walkAsync=fF.walk,this._readerStream=new PF.default(this._settings)}dynamic($,Z){return new Promise((Y,W)=>{this._walkAsync($,Z,(J,Q)=>{if(J===null)Y(Q);else W(J)})})}async static($,Z){let Y=[],W=this._readerStream.static($,Z);return new Promise((J,Q)=>{W.once("error",Q),W.on("data",(X)=>Y.push(X)),W.once("end",()=>J(Y))})}}q2.default=F2});var M2=d((N2)=>{Object.defineProperty(N2,"__esModule",{value:!0});var nZ=K0();class H2{constructor($,Z,Y){this._patterns=$,this._settings=Z,this._micromatchOptions=Y,this._storage=[],this._fillStorage()}_fillStorage(){for(let $ of this._patterns){let Z=this._getPatternSegments($),Y=this._splitSegmentsIntoSections(Z);this._storage.push({complete:Y.length<=1,pattern:$,segments:Z,sections:Y})}}_getPatternSegments($){return nZ.pattern.getPatternParts($,this._micromatchOptions).map((Y)=>{if(!nZ.pattern.isDynamicPattern(Y,this._settings))return{dynamic:!1,pattern:Y};return{dynamic:!0,pattern:Y,patternRe:nZ.pattern.makeRe(Y,this._micromatchOptions)}})}_splitSegmentsIntoSections($){return nZ.array.splitWhen($,(Z)=>Z.dynamic&&nZ.pattern.hasGlobStar(Z.pattern))}}N2.default=H2});var E2=d((L2)=>{Object.defineProperty(L2,"__esModule",{value:!0});var CF=M2();class w2 extends CF.default{match($){let Z=$.split("/"),Y=Z.length,W=this._storage.filter((J)=>!J.complete||J.segments.length>Y);for(let J of W){let Q=J.sections[0];if(!J.complete&&Y>Q.length)return!0;if(Z.every((K,V)=>{let B=J.segments[V];if(B.dynamic&&B.patternRe.test(K))return!0;if(!B.dynamic&&B.pattern===K)return!0;return!1}))return!0}return!1}}L2.default=w2});var D2=d((O2)=>{Object.defineProperty(O2,"__esModule",{value:!0});var G6=K0(),RF=E2();class _2{constructor($,Z){this._settings=$,this._micromatchOptions=Z}getFilter($,Z,Y){let W=this._getMatcher(Z),J=this._getNegativePatternsRe(Y);return(Q)=>this._filter($,Q,W,J)}_getMatcher($){return new RF.default($,this._settings,this._micromatchOptions)}_getNegativePatternsRe($){let Z=$.filter(G6.pattern.isAffectDepthOfReadingPattern);return G6.pattern.convertPatternsToRe(Z,this._micromatchOptions)}_filter($,Z,Y,W){if(this._isSkippedByDeep($,Z.path))return!1;if(this._isSkippedSymbolicLink(Z))return!1;let J=G6.path.removeLeadingDotSegment(Z.path);if(this._isSkippedByPositivePatterns(J,Y))return!1;return this._isSkippedByNegativePatterns(J,W)}_isSkippedByDeep($,Z){if(this._settings.deep===1/0)return!1;return this._getEntryLevel($,Z)>=this._settings.deep}_getEntryLevel($,Z){let Y=Z.split("/").length;if($==="")return Y;let W=$.split("/").length;return Y-W}_isSkippedSymbolicLink($){return!this._settings.followSymbolicLinks&&$.dirent.isSymbolicLink()}_isSkippedByPositivePatterns($,Z){return!this._settings.baseNameMatch&&!Z.match($)}_isSkippedByNegativePatterns($,Z){return!G6.pattern.matchAny($,Z)}}O2.default=_2});var T2=d((f2)=>{Object.defineProperty(f2,"__esModule",{value:!0});var O0=K0();class j2{constructor($,Z){this._settings=$,this._micromatchOptions=Z,this.index=new Map}getFilter($,Z){let[Y,W]=O0.pattern.partitionAbsoluteAndRelative(Z),J={positive:{all:O0.pattern.convertPatternsToRe($,this._micromatchOptions)},negative:{absolute:O0.pattern.convertPatternsToRe(Y,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:O0.pattern.convertPatternsToRe(W,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return(Q)=>this._filter(Q,J)}_filter($,Z){let Y=O0.path.removeLeadingDotSegment($.path);if(this._settings.unique&&this._isDuplicateEntry(Y))return!1;if(this._onlyFileFilter($)||this._onlyDirectoryFilter($))return!1;let W=this._isMatchToPatternsSet(Y,Z,$.dirent.isDirectory());if(this._settings.unique&&W)this._createIndexRecord(Y);return W}_isDuplicateEntry($){return this.index.has($)}_createIndexRecord($){this.index.set($,void 0)}_onlyFileFilter($){return this._settings.onlyFiles&&!$.dirent.isFile()}_onlyDirectoryFilter($){return this._settings.onlyDirectories&&!$.dirent.isDirectory()}_isMatchToPatternsSet($,Z,Y){if(!this._isMatchToPatterns($,Z.positive.all,Y))return!1;if(this._isMatchToPatterns($,Z.negative.relative,Y))return!1;if(this._isMatchToAbsoluteNegative($,Z.negative.absolute,Y))return!1;return!0}_isMatchToAbsoluteNegative($,Z,Y){if(Z.length===0)return!1;let W=O0.path.makeAbsolute(this._settings.cwd,$);return this._isMatchToPatterns(W,Z,Y)}_isMatchToPatterns($,Z,Y){if(Z.length===0)return!1;let W=O0.pattern.matchAny($,Z);if(!W&&Y)return O0.pattern.matchAny($+"/",Z);return W}}f2.default=j2});var A2=d((S2)=>{Object.defineProperty(S2,"__esModule",{value:!0});var IF=K0();class P2{constructor($){this._settings=$}getFilter(){return($)=>this._isNonFatalError($)}_isNonFatalError($){return IF.errno.isEnoentCodeError($)||this._settings.suppressErrors}}S2.default=P2});var y2=d((R2)=>{Object.defineProperty(R2,"__esModule",{value:!0});var C2=K0();class x2{constructor($){this._settings=$}getTransformer(){return($)=>this._transform($)}_transform($){let Z=$.path;if(this._settings.absolute)Z=C2.path.makeAbsolute(this._settings.cwd,Z),Z=C2.path.unixify(Z);if(this._settings.markDirectories&&$.dirent.isDirectory())Z+="/";if(!this._settings.objectMode)return Z;return Object.assign(Object.assign({},$),{path:Z})}}R2.default=x2});var B6=d((I2)=>{Object.defineProperty(I2,"__esModule",{value:!0});var hF=V1("path"),gF=D2(),mF=T2(),dF=A2(),uF=y2();class k2{constructor($){this._settings=$,this.errorFilter=new dF.default(this._settings),this.entryFilter=new mF.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new gF.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new uF.default(this._settings)}_getRootDirectory($){return hF.resolve(this._settings.cwd,$.base)}_getReaderOptions($){let Z=$.base==="."?"":$.base;return{basePath:Z,pathSegmentSeparator:"/",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(Z,$.positive,$.negative),entryFilter:this.entryFilter.getFilter($.positive,$.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}}I2.default=k2});var h2=d((v2)=>{Object.defineProperty(v2,"__esModule",{value:!0});var lF=U2(),pF=B6();class b2 extends pF.default{constructor(){super(...arguments);this._reader=new lF.default(this._settings)}async read($){let Z=this._getRootDirectory($),Y=this._getReaderOptions($);return(await this.api(Z,$,Y)).map((J)=>Y.transform(J))}api($,Z,Y){if(Z.dynamic)return this._reader.dynamic($,Y);return this._reader.static(Z.patterns,Y)}}v2.default=b2});var d2=d((m2)=>{Object.defineProperty(m2,"__esModule",{value:!0});var nF=V1("stream"),rF=F7(),aF=B6();class g2 extends aF.default{constructor(){super(...arguments);this._reader=new rF.default(this._settings)}read($){let Z=this._getRootDirectory($),Y=this._getReaderOptions($),W=this.api(Z,$,Y),J=new nF.Readable({objectMode:!0,read:()=>{}});return W.once("error",(Q)=>J.emit("error",Q)).on("data",(Q)=>J.emit("data",Y.transform(Q))).once("end",()=>J.emit("end")),J.once("close",()=>W.destroy()),J}api($,Z,Y){if(Z.dynamic)return this._reader.dynamic($,Y);return this._reader.static(Z.patterns,Y)}}m2.default=g2});var l2=d((c2)=>{Object.defineProperty(c2,"__esModule",{value:!0});var sF=s0(),tF=V6(),eF=z6();class u2 extends eF.default{constructor(){super(...arguments);this._walkSync=tF.walkSync,this._statSync=sF.statSync}dynamic($,Z){return this._walkSync($,Z)}static($,Z){let Y=[];for(let W of $){let J=this._getFullEntryPath(W),Q=this._getEntry(J,W,Z);if(Q===null||!Z.entryFilter(Q))continue;Y.push(Q)}return Y}_getEntry($,Z,Y){try{let W=this._getStat($);return this._makeEntry(W,Z)}catch(W){if(Y.errorFilter(W))return null;throw W}}_getStat($){return this._statSync($,this._fsStatSettings)}}c2.default=u2});var n2=d((i2)=>{Object.defineProperty(i2,"__esModule",{value:!0});var Zq=l2(),Yq=B6();class p2 extends Yq.default{constructor(){super(...arguments);this._reader=new Zq.default(this._settings)}read($){let Z=this._getRootDirectory($),Y=this._getReaderOptions($);return this.api(Z,$,Y).map(Y.transform)}api($,Z,Y){if(Z.dynamic)return this._reader.dynamic($,Y);return this._reader.static(Z.patterns,Y)}}i2.default=p2});var o2=d((a2)=>{Object.defineProperty(a2,"__esModule",{value:!0});a2.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var x$=V1("fs"),Jq=V1("os"),Qq=Math.max(Jq.cpus().length,1);a2.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:x$.lstat,lstatSync:x$.lstatSync,stat:x$.stat,statSync:x$.statSync,readdir:x$.readdir,readdirSync:x$.readdirSync};class r2{constructor($={}){if(this._options=$,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,Qq),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories)this.onlyFiles=!1;if(this.stats)this.objectMode=!0;this.ignore=[].concat(this.ignore)}_getValue($,Z){return $===void 0?Z:$}_getFileSystemMethods($={}){return Object.assign(Object.assign({},a2.DEFAULT_FILE_SYSTEM_ADAPTER),$)}}a2.default=r2});var e2=d((zT,t2)=>{var s2=A4(),Kq=h2(),Vq=d2(),zq=n2(),U7=o2(),h1=K0();async function H7($,Z){u1($);let Y=N7($,Kq.default,Z),W=await Promise.all(Y);return h1.array.flatten(W)}(function($){$.glob=$,$.globSync=Z,$.globStream=Y,$.async=$;function Z(B,G){u1(B);let F=N7(B,zq.default,G);return h1.array.flatten(F)}$.sync=Z;function Y(B,G){u1(B);let F=N7(B,Vq.default,G);return h1.stream.merge(F)}$.stream=Y;function W(B,G){u1(B);let F=[].concat(B),z=new U7.default(G);return s2.generate(F,z)}$.generateTasks=W;function J(B,G){u1(B);let F=new U7.default(G);return h1.pattern.isDynamicPattern(B,F)}$.isDynamicPattern=J;function Q(B){return u1(B),h1.path.escape(B)}$.escapePath=Q;function X(B){return u1(B),h1.path.convertPathToPattern(B)}$.convertPathToPattern=X;let K;(function(B){function G(z){return u1(z),h1.path.escapePosixPath(z)}B.escapePath=G;function F(z){return u1(z),h1.path.convertPosixPathToPattern(z)}B.convertPathToPattern=F})(K=$.posix||($.posix={}));let V;(function(B){function G(z){return u1(z),h1.path.escapeWindowsPath(z)}B.escapePath=G;function F(z){return u1(z),h1.path.convertWindowsPathToPattern(z)}B.convertPathToPattern=F})(V=$.win32||($.win32={}))})(H7||(H7={}));function N7($,Z,Y){let W=[].concat($),J=new U7.default(Y),Q=s2.generate(W,J),X=new Z(J);return Q.map(X.read,X)}function u1($){if(![].concat($).every((W)=>h1.string.isString(W)&&!h1.string.isEmpty(W)))throw TypeError("Patterns must be a string (non empty) or an array of strings")}t2.exports=H7});var rZ=d((GT,ZJ)=>{var $J={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:"(?=.)",QMARK:"[^/]",END_ANCHOR:"(?:\\/|$)",DOTS_SLASH:"\\.{1,2}(?:\\/|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|\\/)\\.{1,2}(?:\\/|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:\\/|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:\\/|$))",QMARK_NO_DOT:"[^.\\/]",STAR:"[^/]*?",START_ANCHOR:"(?:^|\\/)",SEP:"/"},Gq={...$J,SLASH_LITERAL:"[\\\\/]",QMARK:"[^\\\\/]",STAR:"[^\\\\/]*?",DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},Bq={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};ZJ.exports={MAX_LENGTH:65536,POSIX_REGEX_SOURCE:Bq,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars($){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${$.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars($){return $===!0?Gq:$J}}});var aZ=d((Nq)=>{var{REGEX_BACKSLASH:Fq,REGEX_REMOVE_BACKSLASH:qq,REGEX_SPECIAL_CHARS:Uq,REGEX_SPECIAL_CHARS_GLOBAL:Hq}=rZ();Nq.isObject=($)=>$!==null&&typeof $==="object"&&!Array.isArray($);Nq.hasRegexChars=($)=>Uq.test($);Nq.isRegexChar=($)=>$.length===1&&Nq.hasRegexChars($);Nq.escapeRegex=($)=>$.replace(Hq,"\\$1");Nq.toPosixSlashes=($)=>$.replace(Fq,"/");Nq.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let $=navigator.platform.toLowerCase();return $==="win32"||$==="windows"}if(typeof process<"u"&&process.platform)return process.platform==="win32";return!1};Nq.removeBackslashes=($)=>{return $.replace(qq,(Z)=>{return Z==="\\"?"":Z})};Nq.escapeLast=($,Z,Y)=>{let W=$.lastIndexOf(Z,Y);if(W===-1)return $;if($[W-1]==="\\")return Nq.escapeLast($,Z,W-1);return`${$.slice(0,W)}\\${$.slice(W)}`};Nq.removePrefix=($,Z={})=>{let Y=$;if(Y.startsWith("./"))Y=Y.slice(2),Z.prefix="./";return Y};Nq.wrapOutput=($,Z={},Y={})=>{let W=Y.contains?"":"^",J=Y.contains?"":"$",Q=`${W}(?:${$})${J}`;if(Z.negated===!0)Q=`(?:^(?!${Q}).*$)`;return Q};Nq.basename=($,{windows:Z}={})=>{let Y=$.split(Z?/[\\/]/:"/"),W=Y[Y.length-1];if(W==="")return Y[Y.length-2];return W}});var BJ=d((FT,GJ)=>{var JJ=aZ(),{CHAR_ASTERISK:M7,CHAR_AT:Tq,CHAR_BACKWARD_SLASH:oZ,CHAR_COMMA:Pq,CHAR_DOT:w7,CHAR_EXCLAMATION_MARK:L7,CHAR_FORWARD_SLASH:zJ,CHAR_LEFT_CURLY_BRACE:E7,CHAR_LEFT_PARENTHESES:_7,CHAR_LEFT_SQUARE_BRACKET:Sq,CHAR_PLUS:Aq,CHAR_QUESTION_MARK:QJ,CHAR_RIGHT_CURLY_BRACE:Cq,CHAR_RIGHT_PARENTHESES:XJ,CHAR_RIGHT_SQUARE_BRACKET:xq}=rZ(),KJ=($)=>{return $===zJ||$===oZ},VJ=($)=>{if($.isPrefix!==!0)$.depth=$.isGlobstar?1/0:1},Rq=($,Z)=>{let Y=Z||{},W=$.length-1,J=Y.parts===!0||Y.scanToEnd===!0,Q=[],X=[],K=[],V=$,B=-1,G=0,F=0,z=!1,N=!1,q=!1,w=!1,A=!1,O=!1,H=!1,j=!1,S=!1,b=!1,y=0,k,D,I={value:"",depth:0,isGlob:!1},M=()=>B>=W,L=()=>V.charCodeAt(B+1),u=()=>{return k=D,V.charCodeAt(++B)};while(B<W){D=u();let g;if(D===oZ){if(H=I.backslashes=!0,D=u(),D===E7)O=!0;continue}if(O===!0||D===E7){y++;while(M()!==!0&&(D=u())){if(D===oZ){H=I.backslashes=!0,u();continue}if(D===E7){y++;continue}if(O!==!0&&D===w7&&(D=u())===w7){if(z=I.isBrace=!0,q=I.isGlob=!0,b=!0,J===!0)continue;break}if(O!==!0&&D===Pq){if(z=I.isBrace=!0,q=I.isGlob=!0,b=!0,J===!0)continue;break}if(D===Cq){if(y--,y===0){O=!1,z=I.isBrace=!0,b=!0;break}}}if(J===!0)continue;break}if(D===zJ){if(Q.push(B),X.push(I),I={value:"",depth:0,isGlob:!1},b===!0)continue;if(k===w7&&B===G+1){G+=2;continue}F=B+1;continue}if(Y.noext!==!0){if((D===Aq||D===Tq||D===M7||D===QJ||D===L7)===!0&&L()===_7){if(q=I.isGlob=!0,w=I.isExtglob=!0,b=!0,D===L7&&B===G)S=!0;if(J===!0){while(M()!==!0&&(D=u())){if(D===oZ){H=I.backslashes=!0,D=u();continue}if(D===XJ){q=I.isGlob=!0,b=!0;break}}continue}break}}if(D===M7){if(k===M7)A=I.isGlobstar=!0;if(q=I.isGlob=!0,b=!0,J===!0)continue;break}if(D===QJ){if(q=I.isGlob=!0,b=!0,J===!0)continue;break}if(D===Sq){while(M()!==!0&&(g=u())){if(g===oZ){H=I.backslashes=!0,u();continue}if(g===xq){N=I.isBracket=!0,q=I.isGlob=!0,b=!0;break}}if(J===!0)continue;break}if(Y.nonegate!==!0&&D===L7&&B===G){j=I.negated=!0,G++;continue}if(Y.noparen!==!0&&D===_7){if(q=I.isGlob=!0,J===!0){while(M()!==!0&&(D=u())){if(D===_7){H=I.backslashes=!0,D=u();continue}if(D===XJ){b=!0;break}}continue}break}if(q===!0){if(b=!0,J===!0)continue;break}}if(Y.noext===!0)w=!1,q=!1;let l=V,f="",U="";if(G>0)f=V.slice(0,G),V=V.slice(G),F-=G;if(l&&q===!0&&F>0)l=V.slice(0,F),U=V.slice(F);else if(q===!0)l="",U=V;else l=V;if(l&&l!==""&&l!=="/"&&l!==V){if(KJ(l.charCodeAt(l.length-1)))l=l.slice(0,-1)}if(Y.unescape===!0){if(U)U=JJ.removeBackslashes(U);if(l&&H===!0)l=JJ.removeBackslashes(l)}let _={prefix:f,input:$,start:G,base:l,glob:U,isBrace:z,isBracket:N,isGlob:q,isExtglob:w,isGlobstar:A,negated:j,negatedExtglob:S};if(Y.tokens===!0){if(_.maxDepth=0,!KJ(D))X.push(I);_.tokens=X}if(Y.parts===!0||Y.tokens===!0){let g;for(let m=0;m<Q.length;m++){let r=g?g+1:G,$1=Q[m],Y1=$.slice(r,$1);if(Y.tokens){if(m===0&&G!==0)X[m].isPrefix=!0,X[m].value=f;else X[m].value=Y1;VJ(X[m]),_.maxDepth+=X[m].depth}if(m!==0||Y1!=="")K.push(Y1);g=$1}if(g&&g+1<$.length){let m=$.slice(g+1);if(K.push(m),Y.tokens)X[X.length-1].value=m,VJ(X[X.length-1]),_.maxDepth+=X[X.length-1].depth}_.slashes=Q,_.parts=K}return _};GJ.exports=Rq});var UJ=d((qT,qJ)=>{var F6=rZ(),o1=aZ(),{MAX_LENGTH:q6,POSIX_REGEX_SOURCE:yq,REGEX_NON_SPECIAL_CHARS:kq,REGEX_SPECIAL_CHARS_BACKREF:Iq,REPLACEMENTS:FJ}=F6,bq=($,Z)=>{if(typeof Z.expandRange==="function")return Z.expandRange(...$,Z);$.sort();let Y=`[${$.join("-")}]`;try{new RegExp(Y)}catch(W){return $.map((J)=>o1.escapeRegex(J)).join("..")}return Y},R$=($,Z)=>{return`Missing ${$}: "${Z}" - use "\\\\${Z}" to match literal characters`},O7=($,Z)=>{if(typeof $!=="string")throw TypeError("Expected a string");$=FJ[$]||$;let Y={...Z},W=typeof Y.maxLength==="number"?Math.min(q6,Y.maxLength):q6,J=$.length;if(J>W)throw SyntaxError(`Input length: ${J}, exceeds maximum allowed length: ${W}`);let Q={type:"bos",value:"",output:Y.prepend||""},X=[Q],K=Y.capture?"":"?:",V=F6.globChars(Y.windows),B=F6.extglobChars(V),{DOT_LITERAL:G,PLUS_LITERAL:F,SLASH_LITERAL:z,ONE_CHAR:N,DOTS_SLASH:q,NO_DOT:w,NO_DOT_SLASH:A,NO_DOTS_SLASH:O,QMARK:H,QMARK_NO_DOT:j,STAR:S,START_ANCHOR:b}=V,y=(v)=>{return`(${K}(?:(?!${b}${v.dot?q:G}).)*?)`},k=Y.dot?"":w,D=Y.dot?H:j,I=Y.bash===!0?y(Y):S;if(Y.capture)I=`(${I})`;if(typeof Y.noext==="boolean")Y.noextglob=Y.noext;let M={input:$,index:-1,start:0,dot:Y.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:X};$=o1.removePrefix($,M),J=$.length;let L=[],u=[],l=[],f=Q,U,_=()=>M.index===J-1,g=M.peek=(v=1)=>$[M.index+v],m=M.advance=()=>$[++M.index]||"",r=()=>$.slice(M.index+1),$1=(v="",R=0)=>{M.consumed+=v,M.index+=R},Y1=(v)=>{M.output+=v.output!=null?v.output:v.value,$1(v.value)},s1=()=>{let v=1;while(g()==="!"&&(g(2)!=="("||g(3)==="?"))m(),M.start++,v++;if(v%2===0)return!1;return M.negated=!0,M.start++,!0},b1=(v)=>{M[v]++,l.push(v)},D1=(v)=>{M[v]--,l.pop()},a=(v)=>{if(f.type==="globstar"){let R=M.braces>0&&(v.type==="comma"||v.type==="brace"),C=v.extglob===!0||L.length&&(v.type==="pipe"||v.type==="paren");if(v.type!=="slash"&&v.type!=="paren"&&!R&&!C)M.output=M.output.slice(0,-f.output.length),f.type="star",f.value="*",f.output=I,M.output+=f.output}if(L.length&&v.type!=="paren")L[L.length-1].inner+=v.value;if(v.value||v.output)Y1(v);if(f&&f.type==="text"&&v.type==="text"){f.output=(f.output||f.value)+v.value,f.value+=v.value;return}v.prev=f,X.push(v),f=v},s=(v,R)=>{let C={...B[R],conditions:1,inner:""};C.prev=f,C.parens=M.parens,C.output=M.output;let P=(Y.capture?"(":"")+C.open;b1("parens"),a({type:v,value:R,output:M.output?"":N}),a({type:"paren",extglob:!0,value:m(),output:P}),L.push(C)},W1=(v)=>{let R=v.close+(Y.capture?")":""),C;if(v.type==="negate"){let P=I;if(v.inner&&v.inner.length>1&&v.inner.includes("/"))P=y(Y);if(P!==I||_()||/^\)+$/.test(r()))R=v.close=`)$))${P}`;if(v.inner.includes("*")&&(C=r())&&/^\.[^\\/.]+$/.test(C)){let c=O7(C,{...Z,fastpaths:!1}).output;R=v.close=`)${c})${P})`}if(v.prev.type==="bos")M.negatedExtglob=!0}a({type:"paren",extglob:!0,value:U,output:R}),D1("parens")};if(Y.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test($)){let v=!1,R=$.replace(Iq,(C,P,c,n,t,J1)=>{if(n==="\\")return v=!0,C;if(n==="?"){if(P)return P+n+(t?H.repeat(t.length):"");if(J1===0)return D+(t?H.repeat(t.length):"");return H.repeat(c.length)}if(n===".")return G.repeat(c.length);if(n==="*"){if(P)return P+n+(t?I:"");return I}return P?C:`\\${C}`});if(v===!0)if(Y.unescape===!0)R=R.replace(/\\/g,"");else R=R.replace(/\\+/g,(C)=>{return C.length%2===0?"\\\\":C?"\\":""});if(R===$&&Y.contains===!0)return M.output=$,M;return M.output=o1.wrapOutput(R,M,Z),M}while(!_()){if(U=m(),U==="\x00")continue;if(U==="\\"){let C=g();if(C==="/"&&Y.bash!==!0)continue;if(C==="."||C===";")continue;if(!C){U+="\\",a({type:"text",value:U});continue}let P=/^\\+/.exec(r()),c=0;if(P&&P[0].length>2){if(c=P[0].length,M.index+=c,c%2!==0)U+="\\"}if(Y.unescape===!0)U=m();else U+=m();if(M.brackets===0){a({type:"text",value:U});continue}}if(M.brackets>0&&(U!=="]"||f.value==="["||f.value==="[^")){if(Y.posix!==!1&&U===":"){let C=f.value.slice(1);if(C.includes("[")){if(f.posix=!0,C.includes(":")){let P=f.value.lastIndexOf("["),c=f.value.slice(0,P),n=f.value.slice(P+2),t=yq[n];if(t){if(f.value=c+t,M.backtrack=!0,m(),!Q.output&&X.indexOf(f)===1)Q.output=N;continue}}}}if(U==="["&&g()!==":"||U==="-"&&g()==="]")U=`\\${U}`;if(U==="]"&&(f.value==="["||f.value==="[^"))U=`\\${U}`;if(Y.posix===!0&&U==="!"&&f.value==="[")U="^";f.value+=U,Y1({value:U});continue}if(M.quotes===1&&U!=='"'){U=o1.escapeRegex(U),f.value+=U,Y1({value:U});continue}if(U==='"'){if(M.quotes=M.quotes===1?0:1,Y.keepQuotes===!0)a({type:"text",value:U});continue}if(U==="("){b1("parens"),a({type:"paren",value:U});continue}if(U===")"){if(M.parens===0&&Y.strictBrackets===!0)throw SyntaxError(R$("opening","("));let C=L[L.length-1];if(C&&M.parens===C.parens+1){W1(L.pop());continue}a({type:"paren",value:U,output:M.parens?")":"\\)"}),D1("parens");continue}if(U==="["){if(Y.nobracket===!0||!r().includes("]")){if(Y.nobracket!==!0&&Y.strictBrackets===!0)throw SyntaxError(R$("closing","]"));U=`\\${U}`}else b1("brackets");a({type:"bracket",value:U});continue}if(U==="]"){if(Y.nobracket===!0||f&&f.type==="bracket"&&f.value.length===1){a({type:"text",value:U,output:`\\${U}`});continue}if(M.brackets===0){if(Y.strictBrackets===!0)throw SyntaxError(R$("opening","["));a({type:"text",value:U,output:`\\${U}`});continue}D1("brackets");let C=f.value.slice(1);if(f.posix!==!0&&C[0]==="^"&&!C.includes("/"))U=`/${U}`;if(f.value+=U,Y1({value:U}),Y.literalBrackets===!1||o1.hasRegexChars(C))continue;let P=o1.escapeRegex(f.value);if(M.output=M.output.slice(0,-f.value.length),Y.literalBrackets===!0){M.output+=P,f.value=P;continue}f.value=`(${K}${P}|${f.value})`,M.output+=f.value;continue}if(U==="{"&&Y.nobrace!==!0){b1("braces");let C={type:"brace",value:U,output:"(",outputIndex:M.output.length,tokensIndex:M.tokens.length};u.push(C),a(C);continue}if(U==="}"){let C=u[u.length-1];if(Y.nobrace===!0||!C){a({type:"text",value:U,output:U});continue}let P=")";if(C.dots===!0){let c=X.slice(),n=[];for(let t=c.length-1;t>=0;t--){if(X.pop(),c[t].type==="brace")break;if(c[t].type!=="dots")n.unshift(c[t].value)}P=bq(n,Y),M.backtrack=!0}if(C.comma!==!0&&C.dots!==!0){let c=M.output.slice(0,C.outputIndex),n=M.tokens.slice(C.tokensIndex);C.value=C.output="\\{",U=P="\\}",M.output=c;for(let t of n)M.output+=t.output||t.value}a({type:"brace",value:U,output:P}),D1("braces"),u.pop();continue}if(U==="|"){if(L.length>0)L[L.length-1].conditions++;a({type:"text",value:U});continue}if(U===","){let C=U,P=u[u.length-1];if(P&&l[l.length-1]==="braces")P.comma=!0,C="|";a({type:"comma",value:U,output:C});continue}if(U==="/"){if(f.type==="dot"&&M.index===M.start+1){M.start=M.index+1,M.consumed="",M.output="",X.pop(),f=Q;continue}a({type:"slash",value:U,output:z});continue}if(U==="."){if(M.braces>0&&f.type==="dot"){if(f.value===".")f.output=G;let C=u[u.length-1];f.type="dots",f.output+=U,f.value+=U,C.dots=!0;continue}if(M.braces+M.parens===0&&f.type!=="bos"&&f.type!=="slash"){a({type:"text",value:U,output:G});continue}a({type:"dot",value:U,output:G});continue}if(U==="?"){if(!(f&&f.value==="(")&&Y.noextglob!==!0&&g()==="("&&g(2)!=="?"){s("qmark",U);continue}if(f&&f.type==="paren"){let P=g(),c=U;if(f.value==="("&&!/[!=<:]/.test(P)||P==="<"&&!/<([!=]|\w+>)/.test(r()))c=`\\${U}`;a({type:"text",value:U,output:c});continue}if(Y.dot!==!0&&(f.type==="slash"||f.type==="bos")){a({type:"qmark",value:U,output:j});continue}a({type:"qmark",value:U,output:H});continue}if(U==="!"){if(Y.noextglob!==!0&&g()==="("){if(g(2)!=="?"||!/[!=<:]/.test(g(3))){s("negate",U);continue}}if(Y.nonegate!==!0&&M.index===0){s1();continue}}if(U==="+"){if(Y.noextglob!==!0&&g()==="("&&g(2)!=="?"){s("plus",U);continue}if(f&&f.value==="("||Y.regex===!1){a({type:"plus",value:U,output:F});continue}if(f&&(f.type==="bracket"||f.type==="paren"||f.type==="brace")||M.parens>0){a({type:"plus",value:U});continue}a({type:"plus",value:F});continue}if(U==="@"){if(Y.noextglob!==!0&&g()==="("&&g(2)!=="?"){a({type:"at",extglob:!0,value:U,output:""});continue}a({type:"text",value:U});continue}if(U!=="*"){if(U==="$"||U==="^")U=`\\${U}`;let C=kq.exec(r());if(C)U+=C[0],M.index+=C[0].length;a({type:"text",value:U});continue}if(f&&(f.type==="globstar"||f.star===!0)){f.type="star",f.star=!0,f.value+=U,f.output=I,M.backtrack=!0,M.globstar=!0,$1(U);continue}let v=r();if(Y.noextglob!==!0&&/^\([^?]/.test(v)){s("star",U);continue}if(f.type==="star"){if(Y.noglobstar===!0){$1(U);continue}let C=f.prev,P=C.prev,c=C.type==="slash"||C.type==="bos",n=P&&(P.type==="star"||P.type==="globstar");if(Y.bash===!0&&(!c||v[0]&&v[0]!=="/")){a({type:"star",value:U,output:""});continue}let t=M.braces>0&&(C.type==="comma"||C.type==="brace"),J1=L.length&&(C.type==="pipe"||C.type==="paren");if(!c&&C.type!=="paren"&&!t&&!J1){a({type:"star",value:U,output:""});continue}while(v.slice(0,3)==="/**"){let v1=$[M.index+4];if(v1&&v1!=="/")break;v=v.slice(3),$1("/**",3)}if(C.type==="bos"&&_()){f.type="globstar",f.value+=U,f.output=y(Y),M.output=f.output,M.globstar=!0,$1(U);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!n&&_()){M.output=M.output.slice(0,-(C.output+f.output).length),C.output=`(?:${C.output}`,f.type="globstar",f.output=y(Y)+(Y.strictSlashes?")":"|$)"),f.value+=U,M.globstar=!0,M.output+=C.output+f.output,$1(U);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&v[0]==="/"){let v1=v[1]!==void 0?"|$":"";M.output=M.output.slice(0,-(C.output+f.output).length),C.output=`(?:${C.output}`,f.type="globstar",f.output=`${y(Y)}${z}|${z}${v1})`,f.value+=U,M.output+=C.output+f.output,M.globstar=!0,$1(U+m()),a({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&v[0]==="/"){f.type="globstar",f.value+=U,f.output=`(?:^|${z}|${y(Y)}${z})`,M.output=f.output,M.globstar=!0,$1(U+m()),a({type:"slash",value:"/",output:""});continue}M.output=M.output.slice(0,-f.output.length),f.type="globstar",f.output=y(Y),f.value+=U,M.output+=f.output,M.globstar=!0,$1(U);continue}let R={type:"star",value:U,output:I};if(Y.bash===!0){if(R.output=".*?",f.type==="bos"||f.type==="slash")R.output=k+R.output;a(R);continue}if(f&&(f.type==="bracket"||f.type==="paren")&&Y.regex===!0){R.output=U,a(R);continue}if(M.index===M.start||f.type==="slash"||f.type==="dot"){if(f.type==="dot")M.output+=A,f.output+=A;else if(Y.dot===!0)M.output+=O,f.output+=O;else M.output+=k,f.output+=k;if(g()!=="*")M.output+=N,f.output+=N}a(R)}while(M.brackets>0){if(Y.strictBrackets===!0)throw SyntaxError(R$("closing","]"));M.output=o1.escapeLast(M.output,"["),D1("brackets")}while(M.parens>0){if(Y.strictBrackets===!0)throw SyntaxError(R$("closing",")"));M.output=o1.escapeLast(M.output,"("),D1("parens")}while(M.braces>0){if(Y.strictBrackets===!0)throw SyntaxError(R$("closing","}"));M.output=o1.escapeLast(M.output,"{"),D1("braces")}if(Y.strictSlashes!==!0&&(f.type==="star"||f.type==="bracket"))a({type:"maybe_slash",value:"",output:`${z}?`});if(M.backtrack===!0){M.output="";for(let v of M.tokens)if(M.output+=v.output!=null?v.output:v.value,v.suffix)M.output+=v.suffix}return M};O7.fastpaths=($,Z)=>{let Y={...Z},W=typeof Y.maxLength==="number"?Math.min(q6,Y.maxLength):q6,J=$.length;if(J>W)throw SyntaxError(`Input length: ${J}, exceeds maximum allowed length: ${W}`);$=FJ[$]||$;let{DOT_LITERAL:Q,SLASH_LITERAL:X,ONE_CHAR:K,DOTS_SLASH:V,NO_DOT:B,NO_DOTS:G,NO_DOTS_SLASH:F,STAR:z,START_ANCHOR:N}=F6.globChars(Y.windows),q=Y.dot?G:B,w=Y.dot?F:B,A=Y.capture?"":"?:",O={negated:!1,prefix:""},H=Y.bash===!0?".*?":z;if(Y.capture)H=`(${H})`;let j=(k)=>{if(k.noglobstar===!0)return H;return`(${A}(?:(?!${N}${k.dot?V:Q}).)*?)`},S=(k)=>{switch(k){case"*":return`${q}${K}${H}`;case".*":return`${Q}${K}${H}`;case"*.*":return`${q}${H}${Q}${K}${H}`;case"*/*":return`${q}${H}${X}${K}${w}${H}`;case"**":return q+j(Y);case"**/*":return`(?:${q}${j(Y)}${X})?${w}${K}${H}`;case"**/*.*":return`(?:${q}${j(Y)}${X})?${w}${H}${Q}${K}${H}`;case"**/.*":return`(?:${q}${j(Y)}${X})?${Q}${K}${H}`;default:{let D=/^(.*?)\.(\w+)$/.exec(k);if(!D)return;let I=S(D[1]);if(!I)return;return I+Q+D[2]}}},b=o1.removePrefix($,O),y=S(b);if(y&&Y.strictSlashes!==!0)y+=`${X}?`;return y};qJ.exports=O7});var MJ=d((UT,NJ)=>{var vq=BJ(),D7=UJ(),HJ=aZ(),hq=rZ(),gq=($)=>$&&typeof $==="object"&&!Array.isArray($),B1=($,Z,Y=!1)=>{if(Array.isArray($)){let G=$.map((z)=>B1(z,Z,Y));return(z)=>{for(let N of G){let q=N(z);if(q)return q}return!1}}let W=gq($)&&$.tokens&&$.input;if($===""||typeof $!=="string"&&!W)throw TypeError("Expected pattern to be a non-empty string");let J=Z||{},Q=J.windows,X=W?B1.compileRe($,Z):B1.makeRe($,Z,!1,!0),K=X.state;delete X.state;let V=()=>!1;if(J.ignore){let G={...Z,ignore:null,onMatch:null,onResult:null};V=B1(J.ignore,G,Y)}let B=(G,F=!1)=>{let{isMatch:z,match:N,output:q}=B1.test(G,X,Z,{glob:$,posix:Q}),w={glob:$,state:K,regex:X,posix:Q,input:G,output:q,match:N,isMatch:z};if(typeof J.onResult==="function")J.onResult(w);if(z===!1)return w.isMatch=!1,F?w:!1;if(V(G)){if(typeof J.onIgnore==="function")J.onIgnore(w);return w.isMatch=!1,F?w:!1}if(typeof J.onMatch==="function")J.onMatch(w);return F?w:!0};if(Y)B.state=K;return B};B1.test=($,Z,Y,{glob:W,posix:J}={})=>{if(typeof $!=="string")throw TypeError("Expected input to be a string");if($==="")return{isMatch:!1,output:""};let Q=Y||{},X=Q.format||(J?HJ.toPosixSlashes:null),K=$===W,V=K&&X?X($):$;if(K===!1)V=X?X($):$,K=V===W;if(K===!1||Q.capture===!0)if(Q.matchBase===!0||Q.basename===!0)K=B1.matchBase($,Z,Y,J);else K=Z.exec(V);return{isMatch:Boolean(K),match:K,output:V}};B1.matchBase=($,Z,Y)=>{return(Z instanceof RegExp?Z:B1.makeRe(Z,Y)).test(HJ.basename($))};B1.isMatch=($,Z,Y)=>B1(Z,Y)($);B1.parse=($,Z)=>{if(Array.isArray($))return $.map((Y)=>B1.parse(Y,Z));return D7($,{...Z,fastpaths:!1})};B1.scan=($,Z)=>vq($,Z);B1.compileRe=($,Z,Y=!1,W=!1)=>{if(Y===!0)return $.output;let J=Z||{},Q=J.contains?"":"^",X=J.contains?"":"$",K=`${Q}(?:${$.output})${X}`;if($&&$.negated===!0)K=`^(?!${K}).*$`;let V=B1.toRegex(K,Z);if(W===!0)V.state=$;return V};B1.makeRe=($,Z={},Y=!1,W=!1)=>{if(!$||typeof $!=="string")throw TypeError("Expected a non-empty string");let J={negated:!1,fastpaths:!0};if(Z.fastpaths!==!1&&($[0]==="."||$[0]==="*"))J.output=D7.fastpaths($,Z);if(!J.output)J=D7($,Z);return B1.compileRe(J,Z,Y,W)};B1.toRegex=($,Z)=>{try{let Y=Z||{};return new RegExp($,Y.flags||(Y.nocase?"i":""))}catch(Y){if(Z&&Z.debug===!0)throw Y;return/$^/}};B1.constants=hq;NJ.exports=B1});var _J=d((HT,EJ)=>{var wJ=MJ(),mq=aZ();function LJ($,Z,Y=!1){if(Z&&(Z.windows===null||Z.windows===void 0))Z={...Z,windows:mq.isWindows()};return wJ($,Z,Y)}Object.assign(LJ,wJ);EJ.exports=LJ});function j1($,Z){let Y=Z?.phase;if(!Y)if(!$.shouldContinue)Y="completed";else if($.pendingToolCalls.length>0)Y="tool_execution";else Y="llm_call";let W=Z?.status;if(!W)if(Y==="completed")W=`Completed: ${$.stopReason??"unknown"}`;else if(Y==="tool_execution")W=`Executing tools: ${$.pendingToolCalls.map((Q)=>Q.toolCall.function.name).join(", ")}`;else if(Y==="approval_pending")W="Waiting for user approval";else W=`Iteration ${$.iteration}: Calling LLM`;return{schemaVersion:1,sessionId:$.sessionId,agentName:Z?.agentName,iteration:$.iteration,phase:Y,status:W,modelConfig:Z?.modelConfig,requestParams:Z?.requestParams,messages:[...$.messages],pendingToolCalls:$.pendingToolCalls.map((J)=>({toolCall:{...J.toolCall},result:J.result,isError:J.isError})),currentResponse:$.currentResponse,currentThinking:$.currentThinking,shouldContinue:$.shouldContinue,stopReason:$.stopReason,lastModelStopReason:$.lastModelStopReason,usage:{...$.usage},metadata:{...$.metadata},savedAt:Date.now()}}function k$($){let Z=$.schemaVersion??1;if(Z!==1)throw Error(`Unsupported checkpoint schemaVersion: ${Z}. Please migrate checkpoints or upgrade GoatChain.`);return{sessionId:$.sessionId,iteration:$.iteration,messages:[...$.messages],pendingToolCalls:$.pendingToolCalls.map((Y)=>({toolCall:{...Y.toolCall},result:Y.result,isError:Y.isError})),currentResponse:$.currentResponse,currentThinking:$.currentThinking,shouldContinue:$.shouldContinue,stopReason:$.stopReason,lastModelStopReason:$.lastModelStopReason,usage:{...$.usage},metadata:{...$.metadata}}}import{createRequire as kJ}from"module";var Z8;function IJ(){if(Z8!==void 0)return Z8;try{let Z=kJ(import.meta.url)("tiktoken");return Z8=Z,Z}catch{return Z8=null,null}}var bJ="gpt-4o";function t1($,Z){if(!$)return 0;let Y=IJ();if(!Y)return Math.ceil($.length/4);let W=null;try{return W=Z?Y.encoding_for_model(Z):Y.encoding_for_model(bJ),W.encode($).length}catch(J){console.error("Error encoding text:",J);try{return W=Y.get_encoding("cl100k_base"),W.encode($).length}catch{return Math.ceil($.length/4)}}finally{W?.free()}}function k7($,Z){if(typeof $==="string")return t1($,Z);if(Array.isArray($))return $.reduce((Y,W)=>{if(typeof W==="object"&&W!==null&&"text"in W)return Y+t1(String(W.text),Z);return Y},0);return 0}function I7($,Z){try{let Y=JSON.stringify($);return t1(Y,Z)}catch{return vJ($,Z)}}function vJ($,Z){let W=4;if(W+=k7($.content,Z),$.role==="assistant"&&$.tool_calls)for(let J of $.tool_calls){W+=t1(J.function.name,Z);let Q=typeof J.function.arguments==="string"?J.function.arguments:JSON.stringify(J.function.arguments);W+=t1(Q,Z),W+=10}if($.role==="tool"&&$.name)W+=t1($.name,Z);if($.role==="assistant"&&$.reasoning_content)W+=t1($.reasoning_content,Z);return W}function e0($,Z){if(!$||$.length===0)return 0;try{let Y=JSON.stringify($);return t1(Y,Z)}catch{return $.reduce((W,J)=>W+I7(J,Z),3)}}var L1={CHECKPOINT:"checkpoint",COMPRESSION:"compression",SESSION:"session",COMPRESSION_SNAPSHOT:"compression-snapshot"};function j6($,Z,Y="[Previous conversation context]"){let W=[...$],J=W.findIndex((z)=>z.role==="system");if(J===-1)return W;let Q=W[J],X=Q.content;if(!Z||Z.trim().length===0)return W;let V={type:"text",text:`${Y}
|
|
29
|
+
|
|
30
|
+
${Z}`},G=[...hJ(X,Y),V],F={...Q,content:G};return W[J]=F,W}function hJ($,Z){let Y=(W)=>{let J=W.indexOf(Z);if(J>=0)return W.slice(0,J).trimEnd();return W};if(typeof $==="string"){let W=Y($);return W.trim().length>0?[{type:"text",text:W}]:[]}if(Array.isArray($)){let W=[];for(let J of $){if(typeof J==="string"){let Q=Y(J);if(Q.trim().length>0)W.push({type:"text",text:Q});continue}if(J&&typeof J==="object"&&"type"in J){let Q=J;if(Q.type==="text"){let X=typeof Q.text==="string"?Q.text:"",K=Y(X);if(K.trim().length>0)W.push({...Q,text:K});continue}W.push(Q)}}return W}if($&&typeof $==="object"&&"type"in $){let W=$;if(W.type==="text"){let J=typeof W.text==="string"?W.text:"",Q=Y(J);return Q.trim().length>0?[{...W,text:Q}]:[]}return[W]}return[]}function f6($,Z){let Y=[...$],W=-1;for(let B=Y.length-1;B>=0;B--)if(Y[B].role==="user"){W=B;break}if(W===-1){let B={role:"user",content:Z};return[...Y,B]}let J=Y[W],Q=J.content,X,K={type:"text",text:Z};if(typeof Q==="string")X=[{type:"text",text:Q},K];else if(Array.isArray(Q))X=[...Q,K];else X=[Q,K];let V={...J,content:X};return Y[W]=V,Y}var b7="[Old tool result content cleared]",gJ=`
|
|
31
|
+
Summarize the conversation context for future continuation.
|
|
32
|
+
|
|
33
|
+
Rules:
|
|
34
|
+
- Be concise and factual
|
|
35
|
+
- Use bullet points (6-12 bullets)
|
|
36
|
+
- Include: user goals, key decisions, files/paths touched, unresolved issues, next steps
|
|
37
|
+
- Keep under 1200 characters
|
|
38
|
+
- If existing summary provided, merge old + new into one consolidated summary
|
|
39
|
+
- Remove redundancy and repeated facts
|
|
40
|
+
|
|
41
|
+
Existing summary (if any):
|
|
102
42
|
{{existingSummary}}
|
|
103
43
|
|
|
104
|
-
|
|
105
|
-
{{
|
|
106
|
-
`;function
|
|
44
|
+
Content to summarize:
|
|
45
|
+
{{content}}
|
|
46
|
+
`;function v7($){let{maxTokens:Z,protectedTurns:Y=2,model:W,stateStore:J}=$,Q=Math.floor(Z*0.5),X=Math.floor(Z*0.8),K=async(V,B)=>{let G=await J.load(V.sessionId,L1.COMPRESSION),F=V.messages;if(G?.summary)F=j6(F,G.summary);let z=e0(F),N=0,q=0,w=G?.summary,A=!1;if(z>X){let y=cJ(F),k=lJ(F,Y),D=await dJ(F,W,G?.summary,y,k);if(D.summaryApplied)F=D.compressedMessages,w=D.newSummary,q=D.removedCount,A=!0}if((A?e0(F):z)>Q){let y=mJ(F);F=y.compressedMessages,N=y.clearedCount}let H=A||N>0,j=H?e0(F):z,S=H?Date.now():0;if(A){let y={tokensBefore:z,tokensAfter:j,clearedToolOutputs:N,removedMessages:q,summaryGenerated:!0,timestamp:S},k={lastStats:y,history:[...G?.history??[],y],summary:w,updatedAt:S};await J.save(V.sessionId,L1.COMPRESSION,k)}let b={...V,messages:F,metadata:H?{...V.metadata,lastCompression:{tokensBefore:z,tokensAfter:j,clearedToolOutputs:N,removedMessages:q,summaryGenerated:A,timestamp:S}}:V.metadata};return B(b)};return K.__middlewareName="context-compression",K}function mJ($){let Z=0,Y=pJ($);return{compressedMessages:$.map((J,Q)=>{if(J.role==="tool"&&!iJ(Q,Y.start,Y.end)){let X=J;if(typeof X.content==="string"&&X.content===b7)return J;return Z++,{...X,content:b7}}return J}),clearedCount:Z}}async function dJ($,Z,Y,W,J){let Q=$.slice(W,J);if(Q.length===0)return{compressedMessages:$,newSummary:Y??"",removedCount:0,summaryApplied:!1};let X=h7(Q),K=await g7(X,Z,Y);if(!K)return{compressedMessages:$,newSummary:Y??"",removedCount:0,summaryApplied:!1};let V=[...$.slice(0,W),...$.slice(J)];return{compressedMessages:j6(V,K),newSummary:K,removedCount:Q.length,summaryApplied:!0}}function h7($){let Z=[];for(let Y of $)if(Y.role==="user"){let W=typeof Y.content==="string"?Y.content:JSON.stringify(Y.content);Z.push(`## User
|
|
47
|
+
${W}`)}else if(Y.role==="assistant"){let W=typeof Y.content==="string"?Y.content:JSON.stringify(Y.content);Z.push(`## Assistant
|
|
48
|
+
${W}`)}else if(Y.role==="tool"){let W=Y,J=typeof W.content==="string"?W.content:JSON.stringify(W.content),Q=J.length>5000?`${J.slice(0,5000)}...[truncated]`:J;Z.push(`## Tool: ${W.name||"unknown"}
|
|
49
|
+
${Q}`)}return Z.join(`
|
|
107
50
|
|
|
108
|
-
|
|
51
|
+
---
|
|
109
52
|
|
|
110
|
-
|
|
53
|
+
`)}async function g7($,Z,Y,W){let J=uJ(W??gJ,Y,$),Q=[{role:"system",content:"You are a helpful assistant that creates concise rolling summaries."},{role:"user",content:J}],X="";for await(let K of Z.stream({messages:Q,maxOutputTokens:500}))if(K.type==="delta"&&K.chunk.kind==="text")X+=K.chunk.text;else if(K.type==="response_end")break;return X.trim()}function uJ($,Z,Y){let W=$.includes("{{existingSummary}}"),J=$.includes("{{content}}"),Q=$;if(W)Q=Q.replace("{{existingSummary}}",Z??"(none)");if(J)Q=Q.replace("{{content}}",Y);if(W&&J)return Q;let X=[];if(!W)X.push(`Existing summary (if any):
|
|
54
|
+
${Z??"(none)"}`);if(!J)X.push(`Content to summarize:
|
|
55
|
+
${Y}`);return`${Q.trim()}
|
|
111
56
|
|
|
112
|
-
|
|
57
|
+
${X.join(`
|
|
58
|
+
|
|
59
|
+
`)}
|
|
60
|
+
`}async function m7($){let{sessionId:Z,fullMessages:Y,model:W,stateStore:J,summaryPrompt:Q}=$,X=Y.length,K=Y.filter((A)=>A.role==="tool").length,V=Y.filter((A)=>A.role!=="system");if(V.length===0)return{summary:"",messageCount:X,toolOutputCount:K};let B=await J.load(Z,L1.COMPRESSION),G=h7(V),F=await g7(G,W,B?.summary,Q);if(!F)return{summary:"",messageCount:X,toolOutputCount:K};let z=Date.now(),N=e0(Y),q={tokensBefore:N,tokensAfter:N,clearedToolOutputs:0,removedMessages:V.length,summaryGenerated:!0,timestamp:z},w={lastStats:q,history:[...B?.history??[],q],summary:F,updatedAt:z};return await J.save(Z,L1.COMPRESSION,w),{summary:F,messageCount:X,toolOutputCount:K}}function cJ($){let Z=-1;for(let W=0;W<$.length;W++)if($[W].role==="user"){Z=W;break}if(Z===-1)return 0;let Y=-1;for(let W=Z+1;W<$.length;W++)if($[W].role==="assistant"){Y=W;break}if(Y===-1)return Z+1;for(let W=Y+1;W<$.length;W++)if($[W].role==="user")return W;return $.length}function lJ($,Z){if(Z<=0)return $.length;let Y=0,W=[];for(let Q=$.length-1;Q>=0;Q--)if($[Q].role==="user"){if(Y++,W.unshift(Q),Y>=Z)return Q}let J=6;return Math.max(0,$.length-J)}function pJ($){let Z=-1;for(let J=$.length-1;J>=0;J--)if($[J].role==="assistant"){Z=J;break}if(Z===-1)return{start:$.length,end:$.length};let Y=-1;for(let J=Z;J>=0;J--)if($[J].role==="user"){Y=J;break}if(Y===-1)return{start:$.length,end:$.length};let W=$.length;for(let J=Y+1;J<$.length;J++)if($[J].role==="user"){W=J;break}return{start:Y,end:W}}function iJ($,Z,Y){return $>=Z&&$<Y}import{EventEmitter as LX}from"events";class T0 extends Error{constructor($="Agent execution aborted"){super($);this.name="AgentAbortError"}}class T6 extends Error{iterations;constructor($,Z){super(Z??`Agent exceeded maximum iterations (${$})`);this.name="AgentMaxIterationsError",this.iterations=$}}class V0 extends Error{constructor($="Agent execution paused"){super($);this.name="AgentPauseError"}}function e1($,Z){if(!$?.aborted)return;let Y=$?.reason;if(Y instanceof Error)throw Y;throw new T0(typeof Y==="string"?Y:Z?`${Z} aborted`:"Agent execution aborted")}function Y8($){return(Z,Y)=>{let W=-1,J=async(Q,X)=>{if(Q<=W)throw Error("next() called multiple times");if(W=Q,Q===$.length)return Y?await Y(X):X;let K=$[Q];return K(X,(V)=>J(Q+1,V))};return J(0,Z)}}function W8($,Z){let Y=[{role:"system",content:Z},...$.messages??[],{role:"user",content:$.input}];return{sessionId:$.sessionId??"",messages:Y,iteration:0,pendingToolCalls:[],currentResponse:"",shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}class Q1 extends Error{code;retryable;status;constructor($,Z){super($);this.name="ModelError",this.code=Z.code,this.retryable=Z.retryable??!1,this.status=Z.status}}class d7{state=new Map;get($){return this.state.get(this.keyOf($))||{failures:0,nextRetryAt:0}}markSuccess($){this.state.set(this.keyOf($),{failures:0,nextRetryAt:0})}markFailure($,Z){let W=this.get($).failures+1,J=Math.min(Z.maxDelayMs,Z.baseDelayMs*2**Math.min(8,W-1));this.state.set(this.keyOf($),{failures:W,nextRetryAt:Z.now+J,lastError:{code:Z.code,message:Z.message}})}isAvailable($,Z){return this.get($).nextRetryAt<=Z}keyOf($){return`${$.provider}:${$.modelId}`}}class I$ extends d7{}class P6{health;fallbackOrder;constructor($,Z){this.health=$;this.fallbackOrder=Z}select($){let{now:Z}=$,Y=this.fallbackOrder.filter((W)=>this.health.isAvailable(W,Z));return Y.length?Y:this.fallbackOrder}}class $${static isRetryableStatus($){return $===408||$===409||$===429||$>=500&&$<=599}static async sleep($,Z){if($<=0)return Promise.resolve();return new Promise((Y,W)=>{let J=setTimeout(()=>{Q(),Y()},$);function Q(){if(clearTimeout(J),Z)Z.removeEventListener("abort",X)}function X(){Q(),W(Error("Aborted"))}if(Z){if(Z.aborted)return X();Z.addEventListener("abort",X)}})}}function J8($="req"){let Z=Math.random().toString(16).slice(2),Y=Date.now().toString(16);return`${$}_${Y}_${Z}`}class P0{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor($={}){this.maxAttempts=$.maxAttempts??3,this.baseDelayMs=$.baseDelayMs??500,this.maxDelayMs=$.maxDelayMs??30000,this.strategy=$.strategy??"exponential",this.jitter=$.jitter??"equal",this.multiplier=$.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay($){let Z;switch(this.strategy){case"exponential":Z=this.baseDelayMs*this.multiplier**($-1);break;case"linear":Z=this.baseDelayMs*$;break;case"fixed":Z=this.baseDelayMs;break}return Z=Math.min(Z,this.maxDelayMs),Z=this.applyJitter(Z),this._previousDelay=Z,Math.floor(Z)}applyJitter($){switch(this.jitter){case"full":return Math.random()*$;case"equal":return $/2+Math.random()*$/2;case"decorrelated":return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case"none":default:return $}}canRetry($){return $<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new P0;static aggressive=new P0({maxAttempts:5,baseDelayMs:1000,maxDelayMs:60000});static gentle=new P0({maxAttempts:3,baseDelayMs:2000,maxDelayMs:30000,jitter:"full"})}function nJ($){let Z=$.adapters??($.adapter?[$.adapter]:void 0);if(!Z||Z.length===0)throw new Q1("Missing adapter(s). Provide `adapter` for the simple case, or `adapters` for multi-provider routing.",{code:"missing_adapter",retryable:!1});if($.adapter&&$.adapters)throw new Q1("Provide either `adapter` or `adapters`, not both.",{code:"invalid_options",retryable:!1});let Y=new Map(Z.map((N)=>[N.provider,N])),W=$.health??new I$,J=$.fallback?.onPartialOutput??"stop",Q=$.fallback?.onPartialToolCalls??"stop",X=$.routing?.fallbackOrder??(()=>{let N=[];for(let q of Z)if(q.defaultModelId)N.push({provider:q.provider,modelId:q.defaultModelId});if(N.length===0)throw new Q1("No routing configuration and no adapter with defaultModelId provided. Either provide options.routing.fallbackOrder or set defaultModelId on your adapters.",{code:"missing_routing",retryable:!1});return N})(),K=new P6(W,X),V=new P0({maxAttempts:$.retry?.maxAttemptsPerModel??3,baseDelayMs:$.retry?.baseDelayMs??500,maxDelayMs:$.retry?.maxDelayMs??30000,strategy:$.retry?.strategy??"exponential",jitter:$.retry?.jitter??"equal"}),B=$.timeoutMs??60000;function G(N){let q=Y.get(N.provider);if(!q)throw new Q1(`No adapter for provider: ${N.provider}`,{code:"adapter_missing",retryable:!1});return q}async function*F(N){let q=Date.now(),w=N.requestId||J8("req"),{model:A,...O}=N,H=N.model?[N.model]:K.select({now:q}),j;for(let S of H){let b=G(S),y=N.timeoutMs??B,k=!1,D=!1,I=0,M=new AbortController,L=N.signal,u=setTimeout(()=>M.abort(),y),l=()=>M.abort();if(L)if(L.aborted)M.abort();else L.addEventListener("abort",l);let f={...O,requestId:w,model:S,stream:N.stream??!0,signal:M.signal,timeoutMs:y};try{for(let U=1;U<=V.maxAttempts;U++){I=U;try{for await(let _ of b.stream({request:f})){if(_.type==="delta"){if(k=!0,_.chunk.kind==="tool_call_delta")D=!0}yield _}W.markSuccess(S);return}catch(_){j=_;let g=S6(_),m=g.retryable;if(k||!m||!V.canRetry(U))throw g;let r=V.getDelay(U);$.retry?.onRetry?.({attempt:U,maxAttempts:V.maxAttempts,delayMs:r,error:{code:g.code,message:g.message,retryable:g.retryable},model:S,request:f}),await $$.sleep(r,M.signal)}}}catch(U){let _=S6(U);W.markFailure(S,{now:Date.now(),baseDelayMs:V.baseDelayMs,maxDelayMs:V.maxDelayMs,code:_.code,message:_.message});let r=!(D&&Q==="stop"||k&&J==="stop");if(yield{type:"error",requestId:w,terminal:!r,model:S,attempt:I||1,source:"client",error:{code:_.code,message:_.message,retryable:_.retryable}},!r)throw _;j=_;continue}finally{if(clearTimeout(u),L)L.removeEventListener("abort",l)}}throw S6(j||new Q1("All models failed",{code:"all_models_failed"}))}async function z(N){let q="",w="",A="error",O,H,j=N.requestId||"",S=!1;for await(let b of F({...N,stream:!0}))if(b.type==="response_start")S=!0,j=b.requestId,H=b.model,q="";else if(b.type==="delta"&&b.chunk.kind==="text")q+=b.chunk.text;else if(b.type==="response_end")w=q,A=b.stopReason,O=b.usage;else if(b.type==="error")A="error";if(!H)throw new Q1("Missing response_start from adapter",{code:"protocol_error",retryable:!1});return{requestId:j,model:H,text:S?w:q,stopReason:A,usage:O}}return{get modelId(){return X[0]?.modelId??"unknown"},get modelRef(){return X[0]},get modelRefs(){return[...X]},setModelId(N){let q=X[0];if(!q)throw new Q1("No primary model to update",{code:"no_primary_model",retryable:!1});X[0]={provider:q.provider,modelId:N}},stream:F,run:z}}function S6($){if($ instanceof Q1)return $;if($&&typeof $==="object"){let Z=typeof $.status==="number"?$.status:void 0,Y=typeof $.code==="string"?$.code:Z?`http_${Z}`:"unknown_error",W=typeof $.message==="string"?$.message:"Unknown error",J=Z?$$.isRetryableStatus(Z):!1;return new Q1(W,{code:Y,retryable:J,status:Z})}return new Q1(String($||"Unknown error"),{code:"unknown_error",retryable:!1})}function i($,Z,Y,W,J){if(W==="m")throw TypeError("Private method is not writable");if(W==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return W==="a"?J.call($,Y):J?J.value=Y:Z.set($,Y),Y}function E($,Z,Y,W){if(Y==="a"&&!W)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!W:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?W:Y==="a"?W.call($):W?W.value:Z.get($)}var A6=function(){let{crypto:$}=globalThis;if($?.randomUUID)return A6=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),Y=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(W)=>(+W^Y()&15>>+W/4).toString(16))};function b$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var v$=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class p extends Error{}class F1 extends p{constructor($,Z,Y,W){super(`${F1.makeMessage($,Z,Y)}`);this.status=$,this.headers=W,this.requestID=W?.get("x-request-id"),this.error=Z;let J=Z;this.code=J?.code,this.param=J?.param,this.type=J?.type}static makeMessage($,Z,Y){let W=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Y;if($&&W)return`${$} ${W}`;if($)return`${$} status code (no body)`;if(W)return W;return"(no status code or body)"}static generate($,Z,Y,W){if(!$||!W)return new S0({message:Y,cause:v$(Z)});let J=Z?.error;if($===400)return new h$($,J,Y,W);if($===401)return new g$($,J,Y,W);if($===403)return new m$($,J,Y,W);if($===404)return new d$($,J,Y,W);if($===409)return new u$($,J,Y,W);if($===422)return new c$($,J,Y,W);if($===429)return new l$($,J,Y,W);if($>=500)return new p$($,J,Y,W);return new F1($,J,Y,W)}}class H1 extends F1{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class S0 extends F1{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class A0 extends S0{constructor({message:$}={}){super({message:$??"Request timed out."})}}class h$ extends F1{}class g$ extends F1{}class m$ extends F1{}class d$ extends F1{}class u$ extends F1{}class c$ extends F1{}class l$ extends F1{}class p$ extends F1{}class i$ extends p{constructor(){super("Could not parse response content as the length limit was reached")}}class n$ extends p{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class $0 extends Error{constructor($){super($)}}var aJ=/^[a-z][a-z0-9+.-]*:/i,u7=($)=>{return aJ.test($)},_1=($)=>(_1=Array.isArray,_1($)),C6=_1;function x6($){if(typeof $!=="object")return{};return $??{}}function c7($){if(!$)return!0;for(let Z in $)return!1;return!0}function l7($,Z){return Object.prototype.hasOwnProperty.call($,Z)}function r$($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var p7=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new p(`${$} must be an integer`);if(Z<0)throw new p(`${$} must be a positive integer`);return Z};var i7=($)=>{try{return JSON.parse($)}catch(Z){return}};var c1=($)=>new Promise((Z)=>setTimeout(Z,$));var z0="6.16.0";var o7=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function oJ(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var sJ=()=>{let $=oJ();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z0,"X-Stainless-OS":r7(Deno.build.os),"X-Stainless-Arch":n7(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z0,"X-Stainless-OS":r7(globalThis.process.platform??"unknown"),"X-Stainless-Arch":n7(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=tJ();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Z.browser}`,"X-Stainless-Runtime-Version":Z.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function tJ(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:Y}of $){let W=Y.exec(navigator.userAgent);if(W){let J=W[1]||0,Q=W[2]||0,X=W[3]||0;return{browser:Z,version:`${J}.${Q}.${X}`}}}return null}var n7=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},r7=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},a7,s7=()=>{return a7??(a7=sJ())};function t7(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function R6(...$){let Z=globalThis.ReadableStream;if(typeof Z>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Z(...$)}function Q8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return R6({start(){},async pull(Y){let{done:W,value:J}=await Z.next();if(W)Y.close();else Y.enqueue(J)},async cancel(){await Z.return?.()}})}function y6($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let Y=await Z.read();if(Y?.done)Z.releaseLock();return Y}catch(Y){throw Z.releaseLock(),Y}},async return(){let Y=Z.cancel();return Z.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function e7($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var $9=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};var X8="RFC3986",k6=($)=>String($),K8={RFC1738:($)=>String($).replace(/%20/g,"+"),RFC3986:k6},I6="RFC1738";var V8=($,Z)=>(V8=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),V8($,Z)),l1=(()=>{let $=[];for(let Z=0;Z<256;++Z)$.push("%"+((Z<16?"0":"")+Z.toString(16)).toUpperCase());return $})();var b6=1024,Z9=($,Z,Y,W,J)=>{if($.length===0)return $;let Q=$;if(typeof $==="symbol")Q=Symbol.prototype.toString.call($);else if(typeof $!=="string")Q=String($);if(Y==="iso-8859-1")return escape(Q).replace(/%u[0-9a-f]{4}/gi,function(K){return"%26%23"+parseInt(K.slice(2),16)+"%3B"});let X="";for(let K=0;K<Q.length;K+=b6){let V=Q.length>=b6?Q.slice(K,K+b6):Q,B=[];for(let G=0;G<V.length;++G){let F=V.charCodeAt(G);if(F===45||F===46||F===95||F===126||F>=48&&F<=57||F>=65&&F<=90||F>=97&&F<=122||J===I6&&(F===40||F===41)){B[B.length]=V.charAt(G);continue}if(F<128){B[B.length]=l1[F];continue}if(F<2048){B[B.length]=l1[192|F>>6]+l1[128|F&63];continue}if(F<55296||F>=57344){B[B.length]=l1[224|F>>12]+l1[128|F>>6&63]+l1[128|F&63];continue}G+=1,F=65536+((F&1023)<<10|V.charCodeAt(G)&1023),B[B.length]=l1[240|F>>18]+l1[128|F>>12&63]+l1[128|F>>6&63]+l1[128|F&63]}X+=B.join("")}return X};function Y9($){if(!$||typeof $!=="object")return!1;return!!($.constructor&&$.constructor.isBuffer&&$.constructor.isBuffer($))}function v6($,Z){if(_1($)){let Y=[];for(let W=0;W<$.length;W+=1)Y.push(Z($[W]));return Y}return Z($)}var J9={brackets($){return String($)+"[]"},comma:"comma",indices($,Z){return String($)+"["+Z+"]"},repeat($){return String($)}},Q9=function($,Z){Array.prototype.push.apply($,_1(Z)?Z:[Z])},W9,N1={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Z9,encodeValuesOnly:!1,format:X8,formatter:k6,indices:!1,serializeDate($){return(W9??(W9=Function.prototype.call.bind(Date.prototype.toISOString)))($)},skipNulls:!1,strictNullHandling:!1};function ZQ($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"||typeof $==="symbol"||typeof $==="bigint"}var h6={};function X9($,Z,Y,W,J,Q,X,K,V,B,G,F,z,N,q,w,A,O){let H=$,j=O,S=0,b=!1;while((j=j.get(h6))!==void 0&&!b){let M=j.get($);if(S+=1,typeof M<"u")if(M===S)throw RangeError("Cyclic object value");else b=!0;if(typeof j.get(h6)>"u")S=0}if(typeof B==="function")H=B(Z,H);else if(H instanceof Date)H=z?.(H);else if(Y==="comma"&&_1(H))H=v6(H,function(M){if(M instanceof Date)return z?.(M);return M});if(H===null){if(Q)return V&&!w?V(Z,N1.encoder,A,"key",N):Z;H=""}if(ZQ(H)||Y9(H)){if(V){let M=w?Z:V(Z,N1.encoder,A,"key",N);return[q?.(M)+"="+q?.(V(H,N1.encoder,A,"value",N))]}return[q?.(Z)+"="+q?.(String(H))]}let y=[];if(typeof H>"u")return y;let k;if(Y==="comma"&&_1(H)){if(w&&V)H=v6(H,V);k=[{value:H.length>0?H.join(",")||null:void 0}]}else if(_1(B))k=B;else{let M=Object.keys(H);k=G?M.sort(G):M}let D=K?String(Z).replace(/\./g,"%2E"):String(Z),I=W&&_1(H)&&H.length===1?D+"[]":D;if(J&&_1(H)&&H.length===0)return I+"[]";for(let M=0;M<k.length;++M){let L=k[M],u=typeof L==="object"&&typeof L.value<"u"?L.value:H[L];if(X&&u===null)continue;let l=F&&K?L.replace(/\./g,"%2E"):L,f=_1(H)?typeof Y==="function"?Y(I,l):I:I+(F?"."+l:"["+l+"]");O.set($,S);let U=new WeakMap;U.set(h6,O),Q9(y,X9(u,f,Y,W,J,Q,X,K,Y==="comma"&&w&&_1(H)?null:V,B,G,F,z,N,q,w,A,U))}return y}function YQ($=N1){if(typeof $.allowEmptyArrays<"u"&&typeof $.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof $.encodeDotInKeys<"u"&&typeof $.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if($.encoder!==null&&typeof $.encoder<"u"&&typeof $.encoder!=="function")throw TypeError("Encoder has to be a function.");let Z=$.charset||N1.charset;if(typeof $.charset<"u"&&$.charset!=="utf-8"&&$.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let Y=X8;if(typeof $.format<"u"){if(!V8(K8,$.format))throw TypeError("Unknown format option provided.");Y=$.format}let W=K8[Y],J=N1.filter;if(typeof $.filter==="function"||_1($.filter))J=$.filter;let Q;if($.arrayFormat&&$.arrayFormat in J9)Q=$.arrayFormat;else if("indices"in $)Q=$.indices?"indices":"repeat";else Q=N1.arrayFormat;if("commaRoundTrip"in $&&typeof $.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let X=typeof $.allowDots>"u"?!!$.encodeDotInKeys===!0?!0:N1.allowDots:!!$.allowDots;return{addQueryPrefix:typeof $.addQueryPrefix==="boolean"?$.addQueryPrefix:N1.addQueryPrefix,allowDots:X,allowEmptyArrays:typeof $.allowEmptyArrays==="boolean"?!!$.allowEmptyArrays:N1.allowEmptyArrays,arrayFormat:Q,charset:Z,charsetSentinel:typeof $.charsetSentinel==="boolean"?$.charsetSentinel:N1.charsetSentinel,commaRoundTrip:!!$.commaRoundTrip,delimiter:typeof $.delimiter>"u"?N1.delimiter:$.delimiter,encode:typeof $.encode==="boolean"?$.encode:N1.encode,encodeDotInKeys:typeof $.encodeDotInKeys==="boolean"?$.encodeDotInKeys:N1.encodeDotInKeys,encoder:typeof $.encoder==="function"?$.encoder:N1.encoder,encodeValuesOnly:typeof $.encodeValuesOnly==="boolean"?$.encodeValuesOnly:N1.encodeValuesOnly,filter:J,format:Y,formatter:W,serializeDate:typeof $.serializeDate==="function"?$.serializeDate:N1.serializeDate,skipNulls:typeof $.skipNulls==="boolean"?$.skipNulls:N1.skipNulls,sort:typeof $.sort==="function"?$.sort:null,strictNullHandling:typeof $.strictNullHandling==="boolean"?$.strictNullHandling:N1.strictNullHandling}}function g6($,Z={}){let Y=$,W=YQ(Z),J,Q;if(typeof W.filter==="function")Q=W.filter,Y=Q("",Y);else if(_1(W.filter))Q=W.filter,J=Q;let X=[];if(typeof Y!=="object"||Y===null)return"";let K=J9[W.arrayFormat],V=K==="comma"&&W.commaRoundTrip;if(!J)J=Object.keys(Y);if(W.sort)J.sort(W.sort);let B=new WeakMap;for(let z=0;z<J.length;++z){let N=J[z];if(W.skipNulls&&Y[N]===null)continue;Q9(X,X9(Y[N],N,K,V,W.allowEmptyArrays,W.strictNullHandling,W.skipNulls,W.encodeDotInKeys,W.encode?W.encoder:null,W.filter,W.sort,W.allowDots,W.serializeDate,W.format,W.formatter,W.encodeValuesOnly,W.charset,B))}let G=X.join(W.delimiter),F=W.addQueryPrefix===!0?"?":"";if(W.charsetSentinel)if(W.charset==="iso-8859-1")F+="utf8=%26%2310003%3B&";else F+="utf8=%E2%9C%93&";return G.length>0?F+G:""}function z9($){let Z=0;for(let J of $)Z+=J.length;let Y=new Uint8Array(Z),W=0;for(let J of $)Y.set(J,W),W+=J.length;return Y}var K9;function Z$($){let Z;return(K9??(Z=new globalThis.TextEncoder,K9=Z.encode.bind(Z)))($)}var V9;function m6($){let Z;return(V9??(Z=new globalThis.TextDecoder,V9=Z.decode.bind(Z)))($)}var P1,S1;class Y${constructor(){P1.set(this,void 0),S1.set(this,void 0),i(this,P1,new Uint8Array,"f"),i(this,S1,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?Z$($):$;i(this,P1,z9([E(this,P1,"f"),Z]),"f");let Y=[],W;while((W=JQ(E(this,P1,"f"),E(this,S1,"f")))!=null){if(W.carriage&&E(this,S1,"f")==null){i(this,S1,W.index,"f");continue}if(E(this,S1,"f")!=null&&(W.index!==E(this,S1,"f")+1||W.carriage)){Y.push(m6(E(this,P1,"f").subarray(0,E(this,S1,"f")-1))),i(this,P1,E(this,P1,"f").subarray(E(this,S1,"f")),"f"),i(this,S1,null,"f");continue}let J=E(this,S1,"f")!==null?W.preceding-1:W.preceding,Q=m6(E(this,P1,"f").subarray(0,J));Y.push(Q),i(this,P1,E(this,P1,"f").subarray(W.index),"f"),i(this,S1,null,"f")}return Y}flush(){if(!E(this,P1,"f").length)return[];return this.decode(`
|
|
61
|
+
`)}}P1=new WeakMap,S1=new WeakMap;Y$.NEWLINE_CHARS=new Set([`
|
|
62
|
+
`,"\r"]);Y$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function JQ($,Z){for(let J=Z??0;J<$.length;J++){if($[J]===10)return{preceding:J,index:J+1,carriage:!1};if($[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function G9($){for(let W=0;W<$.length-1;W++){if($[W]===10&&$[W+1]===10)return W+2;if($[W]===13&&$[W+1]===13)return W+2;if($[W]===13&&$[W+1]===10&&W+3<$.length&&$[W+2]===13&&$[W+3]===10)return W+4}return-1}var G8={off:0,error:200,warn:300,info:400,debug:500},d6=($,Z,Y)=>{if(!$)return;if(l7(G8,$))return $;z1(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(G8))}`);return};function a$(){}function z8($,Z,Y){if(!Z||G8[$]>G8[Y])return a$;else return Z[$].bind(Z)}var QQ={error:a$,warn:a$,info:a$,debug:a$},B9=new WeakMap;function z1($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return QQ;let W=B9.get(Z);if(W&&W[0]===Y)return W[1];let J={error:z8("error",Z,Y),warn:z8("warn",Z,Y),info:z8("info",Z,Y),debug:z8("debug",Z,Y)};return B9.set(Z,[Y,J]),J}var Z0=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,Y])=>[Z,Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":Y]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var o$;class A1{constructor($,Z,Y){this.iterator=$,o$.set(this,void 0),this.controller=Z,i(this,o$,Y,"f")}static fromSSEResponse($,Z,Y){let W=!1,J=Y?z1(Y):console;async function*Q(){if(W)throw new p("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let X=!1;try{for await(let K of XQ($,Z)){if(X)continue;if(K.data.startsWith("[DONE]")){X=!0;continue}if(K.event===null||!K.event.startsWith("thread.")){let V;try{V=JSON.parse(K.data)}catch(B){throw J.error("Could not parse message into JSON:",K.data),J.error("From chunk:",K.raw),B}if(V&&V.error)throw new F1(void 0,V.error,void 0,$.headers);yield V}else{let V;try{V=JSON.parse(K.data)}catch(B){throw console.error("Could not parse message into JSON:",K.data),console.error("From chunk:",K.raw),B}if(K.event=="error")throw new F1(void 0,V.error,V.message,void 0);yield{event:K.event,data:V}}}X=!0}catch(K){if(b$(K))return;throw K}finally{if(!X)Z.abort()}}return new A1(Q,Z,Y)}static fromReadableStream($,Z,Y){let W=!1;async function*J(){let X=new Y$,K=y6($);for await(let V of K)for(let B of X.decode(V))yield B;for(let V of X.flush())yield V}async function*Q(){if(W)throw new p("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");W=!0;let X=!1;try{for await(let K of J()){if(X)continue;if(K)yield JSON.parse(K)}X=!0}catch(K){if(b$(K))return;throw K}finally{if(!X)Z.abort()}}return new A1(Q,Z,Y)}[(o$=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),W=(J)=>{return{next:()=>{if(J.length===0){let Q=Y.next();$.push(Q),Z.push(Q)}return J.shift()}}};return[new A1(()=>W($),this.controller,E(this,o$,"f")),new A1(()=>W(Z),this.controller,E(this,o$,"f"))]}toReadableStream(){let $=this,Z;return R6({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:W,done:J}=await Z.next();if(J)return Y.close();let Q=Z$(JSON.stringify(W)+`
|
|
63
|
+
`);Y.enqueue(Q)}catch(W){Y.error(W)}},async cancel(){await Z.return?.()}})}}async function*XQ($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new p("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new p("Attempted to iterate over a response with no body")}let Y=new F9,W=new Y$,J=y6($.body);for await(let Q of KQ(J))for(let X of W.decode(Q)){let K=Y.decode(X);if(K)yield K}for(let Q of W.flush()){let X=Y.decode(Q);if(X)yield X}}async function*KQ($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let W=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?Z$(Y):Y,J=new Uint8Array(Z.length+W.length);J.set(Z),J.set(W,Z.length),Z=J;let Q;while((Q=G9(Z))!==-1)yield Z.slice(0,Q),Z=Z.slice(Q)}if(Z.length>0)yield Z}class F9{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
|
|
64
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,W]=VQ($,":");if(W.startsWith(" "))W=W.substring(1);if(Z==="event")this.event=W;else if(Z==="data")this.data.push(W);return null}}function VQ($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function B8($,Z){let{response:Y,requestLogID:W,retryOfRequestLogID:J,startTime:Q}=Z,X=await(async()=>{if(Z.options.stream){if(z1($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller,$);return A1.fromSSEResponse(Y,Z.controller,$)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let V=Y.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){let F=await Y.json();return u6(F,Y)}return await Y.text()})();return z1($).debug(`[${W}] response parsed`,Z0({retryOfRequestLogID:J,url:Y.url,status:Y.status,body:X,durationMs:Date.now()-Q})),X}function u6($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("x-request-id"),enumerable:!1})}var s$;class C0 extends Promise{constructor($,Z,Y=B8){super((W)=>{W(null)});this.responsePromise=Z,this.parseResponse=Y,s$.set(this,void 0),i(this,s$,$,"f")}_thenUnwrap($){return new C0(E(this,s$,"f"),this.responsePromise,async(Z,Y)=>u6($(await this.parseResponse(Z,Y),Y),Y.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(E(this,s$,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}s$=new WeakMap;var F8;class q8{constructor($,Z,Y,W){F8.set(this,void 0),i(this,F8,$,"f"),this.options=W,this.response=Z,this.body=Y}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new p("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await E(this,F8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(F8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class U8 extends C0{constructor($,Z,Y){super($,Z,async(W,J)=>new Y(W,J.response,await B8(W,J),J.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class Y0 extends q8{constructor($,Z,Y,W){super($,Z,Y,W);this.data=Y.data||[],this.object=Y.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class e extends q8{constructor($,Z,Y,W){super($,Z,Y,W);this.data=Y.data||[],this.has_more=Y.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.getPaginatedItems(),Z=$[$.length-1]?.id;if(!Z)return null;return{...this.options,query:{...x6(this.options.query),after:Z}}}}class G0 extends q8{constructor($,Z,Y,W){super($,Z,Y,W);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.last_id=Y.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.last_id;if(!$)return null;return{...this.options,query:{...x6(this.options.query),after:$}}}}var p6=()=>{if(typeof File>"u"){let{process:$}=globalThis,Z=typeof $?.versions?.node==="string"&&parseInt($.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(Z?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function W$($,Z,Y){return p6(),new File($,Z??"unknown_file",Y)}function t$($){return(typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"").split(/[\\/]/).pop()||void 0}var H8=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",i6=async($,Z)=>{if(!c6($.body))return $;return{...$,body:await U9($.body,Z)}},C1=async($,Z)=>{return{...$,body:await U9($.body,Z)}},q9=new WeakMap;function GQ($){let Z=typeof $==="function"?$:$.fetch,Y=q9.get(Z);if(Y)return Y;let W=(async()=>{try{let J="Response"in Z?Z.Response:(await Z("data:,")).constructor,Q=new FormData;if(Q.toString()===await new J(Q).text())return!1;return!0}catch{return!0}})();return q9.set(Z,W),W}var U9=async($,Z)=>{if(!await GQ(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Y=new FormData;return await Promise.all(Object.entries($||{}).map(([W,J])=>l6(Y,W,J))),Y},H9=($)=>$ instanceof Blob&&("name"in $),BQ=($)=>typeof $==="object"&&$!==null&&($ instanceof Response||H8($)||H9($)),c6=($)=>{if(BQ($))return!0;if(Array.isArray($))return $.some(c6);if($&&typeof $==="object"){for(let Z in $)if(c6($[Z]))return!0}return!1},l6=async($,Z,Y)=>{if(Y===void 0)return;if(Y==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")$.append(Z,String(Y));else if(Y instanceof Response)$.append(Z,W$([await Y.blob()],t$(Y)));else if(H8(Y))$.append(Z,W$([await new Response(Q8(Y)).blob()],t$(Y)));else if(H9(Y))$.append(Z,Y,t$(Y));else if(Array.isArray(Y))await Promise.all(Y.map((W)=>l6($,Z+"[]",W)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([W,J])=>l6($,`${Z}[${W}]`,J)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var N9=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",FQ=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&N9($),qQ=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function N8($,Z,Y){if(p6(),$=await $,FQ($)){if($ instanceof File)return $;return W$([await $.arrayBuffer()],$.name)}if(qQ($)){let J=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),W$(await n6(J),Z,Y)}let W=await n6($);if(Z||(Z=t$($)),!Y?.type){let J=W.find((Q)=>typeof Q==="object"&&("type"in Q)&&Q.type);if(typeof J==="string")Y={...Y,type:J}}return W$(W,Z,Y)}async function n6($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(N9($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(H8($))for await(let Y of $)Z.push(...await n6(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${UQ($)}`)}return Z}function UQ($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class x{constructor($){this._client=$}}function w9($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var M9=Object.freeze(Object.create(null)),NQ=($=w9)=>function(Y,...W){if(Y.length===1)return Y[0];let J=!1,Q=[],X=Y.reduce((G,F,z)=>{if(/[?#]/.test(F))J=!0;let N=W[z],q=(J?encodeURIComponent:$)(""+N);if(z!==W.length&&(N==null||typeof N==="object"&&N.toString===Object.getPrototypeOf(Object.getPrototypeOf(N.hasOwnProperty??M9)??M9)?.toString))q=N+"",Q.push({start:G.length+F.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(N).slice(8,-1)} is not a valid path parameter`});return G+F+(z===W.length?"":q)},""),K=X.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,B;while((B=V.exec(K))!==null)Q.push({start:B.index,length:B[0].length,error:`Value "${B[0]}" can't be safely passed as a path parameter`});if(Q.sort((G,F)=>G.start-F.start),Q.length>0){let G=0,F=Q.reduce((z,N)=>{let q=" ".repeat(N.start-G),w="^".repeat(N.length);return G=N.start+N.length,z+q+w},"");throw new p(`Path parameters result in path with invalid segments:
|
|
65
|
+
${Q.map((z)=>z.error).join(`
|
|
66
|
+
`)}
|
|
67
|
+
${X}
|
|
68
|
+
${F}`)}return X},T=NQ(w9);class J$ extends x{list($,Z={},Y){return this._client.getAPIList(T`/chat/completions/${$}/messages`,e,{query:Z,...Y})}}function e$($){return $!==void 0&&"function"in $&&$.function!==void 0}function $Z($){return $?.$brand==="auto-parseable-response-format"}function x0($){return $?.$brand==="auto-parseable-tool"}function L9($,Z){if(!Z||!r6(Z))return{...$,choices:$.choices.map((Y)=>{return _9(Y.message.tool_calls),{...Y,message:{...Y.message,parsed:null,...Y.message.tool_calls?{tool_calls:Y.message.tool_calls}:void 0}}})};return ZZ($,Z)}function ZZ($,Z){let Y=$.choices.map((W)=>{if(W.finish_reason==="length")throw new i$;if(W.finish_reason==="content_filter")throw new n$;return _9(W.message.tool_calls),{...W,message:{...W.message,...W.message.tool_calls?{tool_calls:W.message.tool_calls?.map((J)=>EQ(Z,J))??void 0}:void 0,parsed:W.message.content&&!W.message.refusal?LQ(Z,W.message.content):null}}});return{...$,choices:Y}}function LQ($,Z){if($.response_format?.type!=="json_schema")return null;if($.response_format?.type==="json_schema"){if("$parseRaw"in $.response_format)return $.response_format.$parseRaw(Z);return JSON.parse(Z)}return null}function EQ($,Z){let Y=$.tools?.find((W)=>e$(W)&&W.function?.name===Z.function.name);return{...Z,function:{...Z.function,parsed_arguments:x0(Y)?Y.$parseRaw(Z.function.arguments):Y?.function.strict?JSON.parse(Z.function.arguments):null}}}function E9($,Z){if(!$||!("tools"in $)||!$.tools)return!1;let Y=$.tools?.find((W)=>e$(W)&&W.function?.name===Z.function.name);return e$(Y)&&(x0(Y)||Y?.function.strict||!1)}function r6($){if($Z($.response_format))return!0;return $.tools?.some((Z)=>x0(Z)||Z.type==="function"&&Z.function.strict===!0)??!1}function _9($){for(let Z of $||[])if(Z.type!=="function")throw new p(`Currently only \`function\` tool calls are supported; Received \`${Z.type}\``)}function O9($){for(let Z of $??[]){if(Z.type!=="function")throw new p(`Currently only \`function\` tool types support auto-parsing; Received \`${Z.type}\``);if(Z.function.strict!==!0)throw new p(`The \`${Z.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Q$=($)=>{return $?.role==="assistant"},a6=($)=>{return $?.role==="tool"};var o6,M8,w8,YZ,WZ,L8,JZ,W0,QZ,E8,_8,X$,D9;class R0{constructor(){o6.add(this),this.controller=new AbortController,M8.set(this,void 0),w8.set(this,()=>{}),YZ.set(this,()=>{}),WZ.set(this,void 0),L8.set(this,()=>{}),JZ.set(this,()=>{}),W0.set(this,{}),QZ.set(this,!1),E8.set(this,!1),_8.set(this,!1),X$.set(this,!1),i(this,M8,new Promise(($,Z)=>{i(this,w8,$,"f"),i(this,YZ,Z,"f")}),"f"),i(this,WZ,new Promise(($,Z)=>{i(this,L8,$,"f"),i(this,JZ,Z,"f")}),"f"),E(this,M8,"f").catch(()=>{}),E(this,WZ,"f").catch(()=>{})}_run($){setTimeout(()=>{$().then(()=>{this._emitFinal(),this._emit("end")},E(this,o6,"m",D9).bind(this))},0)}_connected(){if(this.ended)return;E(this,w8,"f").call(this),this._emit("connect")}get ended(){return E(this,QZ,"f")}get errored(){return E(this,E8,"f")}get aborted(){return E(this,_8,"f")}abort(){this.controller.abort()}on($,Z){return(E(this,W0,"f")[$]||(E(this,W0,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=E(this,W0,"f")[$];if(!Y)return this;let W=Y.findIndex((J)=>J.listener===Z);if(W>=0)Y.splice(W,1);return this}once($,Z){return(E(this,W0,"f")[$]||(E(this,W0,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(i(this,X$,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){i(this,X$,!0,"f"),await E(this,WZ,"f")}_emit($,...Z){if(E(this,QZ,"f"))return;if($==="end")i(this,QZ,!0,"f"),E(this,L8,"f").call(this);let Y=E(this,W0,"f")[$];if(Y)E(this,W0,"f")[$]=Y.filter((W)=>!W.once),Y.forEach(({listener:W})=>W(...Z));if($==="abort"){let W=Z[0];if(!E(this,X$,"f")&&!Y?.length)Promise.reject(W);E(this,YZ,"f").call(this,W),E(this,JZ,"f").call(this,W),this._emit("end");return}if($==="error"){let W=Z[0];if(!E(this,X$,"f")&&!Y?.length)Promise.reject(W);E(this,YZ,"f").call(this,W),E(this,JZ,"f").call(this,W),this._emit("end")}}_emitFinal(){}}M8=new WeakMap,w8=new WeakMap,YZ=new WeakMap,WZ=new WeakMap,L8=new WeakMap,JZ=new WeakMap,W0=new WeakMap,QZ=new WeakMap,E8=new WeakMap,_8=new WeakMap,X$=new WeakMap,o6=new WeakSet,D9=function(Z){if(i(this,E8,!0,"f"),Z instanceof Error&&Z.name==="AbortError")Z=new H1;if(Z instanceof H1)return i(this,_8,!0,"f"),this._emit("abort",Z);if(Z instanceof p)return this._emit("error",Z);if(Z instanceof Error){let Y=new p(Z.message);return Y.cause=Z,this._emit("error",Y)}return this._emit("error",new p(String(Z)))};function j9($){return typeof $.parse==="function"}var O1,s6,O8,t6,e6,$Y,f9,T9,_Q=10;class XZ extends R0{constructor(){super(...arguments);O1.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion($){this._chatCompletions.push($),this._emit("chatCompletion",$);let Z=$.choices[0]?.message;if(Z)this._addMessage(Z);return $}_addMessage($,Z=!0){if(!("content"in $))$.content=null;if(this.messages.push($),Z){if(this._emit("message",$),a6($)&&$.content)this._emit("functionToolCallResult",$.content);else if(Q$($)&&$.tool_calls){for(let Y of $.tool_calls)if(Y.type==="function")this._emit("functionToolCall",Y.function)}}}async finalChatCompletion(){await this.done();let $=this._chatCompletions[this._chatCompletions.length-1];if(!$)throw new p("stream ended without producing a ChatCompletion");return $}async finalContent(){return await this.done(),E(this,O1,"m",s6).call(this)}async finalMessage(){return await this.done(),E(this,O1,"m",O8).call(this)}async finalFunctionToolCall(){return await this.done(),E(this,O1,"m",t6).call(this)}async finalFunctionToolCallResult(){return await this.done(),E(this,O1,"m",e6).call(this)}async totalUsage(){return await this.done(),E(this,O1,"m",$Y).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let $=this._chatCompletions[this._chatCompletions.length-1];if($)this._emit("finalChatCompletion",$);let Z=E(this,O1,"m",O8).call(this);if(Z)this._emit("finalMessage",Z);let Y=E(this,O1,"m",s6).call(this);if(Y)this._emit("finalContent",Y);let W=E(this,O1,"m",t6).call(this);if(W)this._emit("finalFunctionToolCall",W);let J=E(this,O1,"m",e6).call(this);if(J!=null)this._emit("finalFunctionToolCallResult",J);if(this._chatCompletions.some((Q)=>Q.usage))this._emit("totalUsage",E(this,O1,"m",$Y).call(this))}async _createChatCompletion($,Z,Y){let W=Y?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}E(this,O1,"m",f9).call(this,Z);let J=await $.chat.completions.create({...Z,stream:!1},{...Y,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ZZ(J,Z))}async _runChatCompletion($,Z,Y){for(let W of Z.messages)this._addMessage(W,!1);return await this._createChatCompletion($,Z,Y)}async _runTools($,Z,Y){let{tool_choice:J="auto",stream:Q,...X}=Z,K=typeof J!=="string"&&J.type==="function"&&J?.function?.name,{maxChatCompletions:V=_Q}=Y||{},B=Z.tools.map((z)=>{if(x0(z)){if(!z.$callback)throw new p("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:z.$callback,name:z.function.name,description:z.function.description||"",parameters:z.function.parameters,parse:z.$parseRaw,strict:!0}}}return z}),G={};for(let z of B)if(z.type==="function")G[z.function.name||z.function.function.name]=z.function;let F="tools"in Z?B.map((z)=>z.type==="function"?{type:"function",function:{name:z.function.name||z.function.function.name,parameters:z.function.parameters,description:z.function.description,strict:z.function.strict}}:z):void 0;for(let z of Z.messages)this._addMessage(z,!1);for(let z=0;z<V;++z){let q=(await this._createChatCompletion($,{...X,tool_choice:J,tools:F,messages:[...this.messages]},Y)).choices[0]?.message;if(!q)throw new p("missing message in ChatCompletion response");if(!q.tool_calls?.length)return;for(let w of q.tool_calls){if(w.type!=="function")continue;let A=w.id,{name:O,arguments:H}=w.function,j=G[O];if(!j){let k=`Invalid tool_call: ${JSON.stringify(O)}. Available options are: ${Object.keys(G).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:A,content:k});continue}else if(K&&K!==O){let k=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(K)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:A,content:k});continue}let S;try{S=j9(j)?await j.parse(H):H}catch(k){let D=k instanceof Error?k.message:String(k);this._addMessage({role:"tool",tool_call_id:A,content:D});continue}let b=await j.function(S,this),y=E(this,O1,"m",T9).call(this,b);if(this._addMessage({role:"tool",tool_call_id:A,content:y}),K)return}}return}}O1=new WeakSet,s6=function(){return E(this,O1,"m",O8).call(this).content??null},O8=function(){let Z=this.messages.length;while(Z-- >0){let Y=this.messages[Z];if(Q$(Y))return{...Y,content:Y.content??null,refusal:Y.refusal??null}}throw new p("stream ended without producing a ChatCompletionMessage with role=assistant")},t6=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let Y=this.messages[Z];if(Q$(Y)&&Y?.tool_calls?.length)return Y.tool_calls.filter((W)=>W.type==="function").at(-1)?.function}return},e6=function(){for(let Z=this.messages.length-1;Z>=0;Z--){let Y=this.messages[Z];if(a6(Y)&&Y.content!=null&&typeof Y.content==="string"&&this.messages.some((W)=>W.role==="assistant"&&W.tool_calls?.some((J)=>J.type==="function"&&J.id===Y.tool_call_id)))return Y.content}return},$Y=function(){let Z={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:Y}of this._chatCompletions)if(Y)Z.completion_tokens+=Y.completion_tokens,Z.prompt_tokens+=Y.prompt_tokens,Z.total_tokens+=Y.total_tokens;return Z},f9=function(Z){if(Z.n!=null&&Z.n>1)throw new p("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},T9=function(Z){return typeof Z==="string"?Z:Z===void 0?"undefined":JSON.stringify(Z)};class KZ extends XZ{static runTools($,Z,Y){let W=new KZ,J={...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,Z,J)),W}_addMessage($,Z=!0){if(super._addMessage($,Z),Q$($)&&$.content)this._emit("content",$.content)}}var w1={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class P9 extends Error{}class S9 extends Error{}function OQ($,Z=w1.ALL){if(typeof $!=="string")throw TypeError(`expecting str, got ${typeof $}`);if(!$.trim())throw Error(`${$} is empty`);return DQ($.trim(),Z)}var DQ=($,Z)=>{let Y=$.length,W=0,J=(z)=>{throw new P9(`${z} at position ${W}`)},Q=(z)=>{throw new S9(`${z} at position ${W}`)},X=()=>{if(F(),W>=Y)J("Unexpected end of input");if($[W]==='"')return K();if($[W]==="{")return V();if($[W]==="[")return B();if($.substring(W,W+4)==="null"||w1.NULL&Z&&Y-W<4&&"null".startsWith($.substring(W)))return W+=4,null;if($.substring(W,W+4)==="true"||w1.BOOL&Z&&Y-W<4&&"true".startsWith($.substring(W)))return W+=4,!0;if($.substring(W,W+5)==="false"||w1.BOOL&Z&&Y-W<5&&"false".startsWith($.substring(W)))return W+=5,!1;if($.substring(W,W+8)==="Infinity"||w1.INFINITY&Z&&Y-W<8&&"Infinity".startsWith($.substring(W)))return W+=8,1/0;if($.substring(W,W+9)==="-Infinity"||w1.MINUS_INFINITY&Z&&1<Y-W&&Y-W<9&&"-Infinity".startsWith($.substring(W)))return W+=9,-1/0;if($.substring(W,W+3)==="NaN"||w1.NAN&Z&&Y-W<3&&"NaN".startsWith($.substring(W)))return W+=3,NaN;return G()},K=()=>{let z=W,N=!1;W++;while(W<Y&&($[W]!=='"'||N&&$[W-1]==="\\"))N=$[W]==="\\"?!N:!1,W++;if($.charAt(W)=='"')try{return JSON.parse($.substring(z,++W-Number(N)))}catch(q){Q(String(q))}else if(w1.STR&Z)try{return JSON.parse($.substring(z,W-Number(N))+'"')}catch(q){return JSON.parse($.substring(z,$.lastIndexOf("\\"))+'"')}J("Unterminated string literal")},V=()=>{W++,F();let z={};try{while($[W]!=="}"){if(F(),W>=Y&&w1.OBJ&Z)return z;let N=K();F(),W++;try{let q=X();Object.defineProperty(z,N,{value:q,writable:!0,enumerable:!0,configurable:!0})}catch(q){if(w1.OBJ&Z)return z;else throw q}if(F(),$[W]===",")W++}}catch(N){if(w1.OBJ&Z)return z;else J("Expected '}' at end of object")}return W++,z},B=()=>{W++;let z=[];try{while($[W]!=="]")if(z.push(X()),F(),$[W]===",")W++}catch(N){if(w1.ARR&Z)return z;J("Expected ']' at end of array")}return W++,z},G=()=>{if(W===0){if($==="-"&&w1.NUM&Z)J("Not sure what '-' is");try{return JSON.parse($)}catch(N){if(w1.NUM&Z)try{if($[$.length-1]===".")return JSON.parse($.substring(0,$.lastIndexOf(".")));return JSON.parse($.substring(0,$.lastIndexOf("e")))}catch(q){}Q(String(N))}}let z=W;if($[W]==="-")W++;while($[W]&&!",]}".includes($[W]))W++;if(W==Y&&!(w1.NUM&Z))J("Unterminated number literal");try{return JSON.parse($.substring(z,W))}catch(N){if($.substring(z,W)==="-"&&w1.NUM&Z)J("Not sure what '-' is");try{return JSON.parse($.substring(z,$.lastIndexOf("e")))}catch(q){Q(String(q))}}},F=()=>{while(W<Y&&`
|
|
69
|
+
\r `.includes($[W]))W++};return X()},ZY=($)=>OQ($,w1.ALL^w1.NUM);var M1,J0,K$,B0,YY,D8,WY,JY,QY,j8,XY,A9;class F0 extends XZ{constructor($){super();M1.add(this),J0.set(this,void 0),K$.set(this,void 0),B0.set(this,void 0),i(this,J0,$,"f"),i(this,K$,[],"f")}get currentChatCompletionSnapshot(){return E(this,B0,"f")}static fromReadableStream($){let Z=new F0(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createChatCompletion($,Z,Y){let W=new F0(Z);return W._run(()=>W._runChatCompletion($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createChatCompletion($,Z,Y){super._createChatCompletion;let W=Y?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}E(this,M1,"m",YY).call(this);let J=await $.chat.completions.create({...Z,stream:!0},{...Y,signal:this.controller.signal});this._connected();for await(let Q of J)E(this,M1,"m",WY).call(this,Q);if(J.controller.signal?.aborted)throw new H1;return this._addChatCompletion(E(this,M1,"m",j8).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}E(this,M1,"m",YY).call(this),this._connected();let W=A1.fromReadableStream($,this.controller),J;for await(let Q of W){if(J&&J!==Q.id)this._addChatCompletion(E(this,M1,"m",j8).call(this));E(this,M1,"m",WY).call(this,Q),J=Q.id}if(W.controller.signal?.aborted)throw new H1;return this._addChatCompletion(E(this,M1,"m",j8).call(this))}[(J0=new WeakMap,K$=new WeakMap,B0=new WeakMap,M1=new WeakSet,YY=function(){if(this.ended)return;i(this,B0,void 0,"f")},D8=function(Z){let Y=E(this,K$,"f")[Z.index];if(Y)return Y;return Y={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},E(this,K$,"f")[Z.index]=Y,Y},WY=function(Z){if(this.ended)return;let Y=E(this,M1,"m",A9).call(this,Z);this._emit("chunk",Z,Y);for(let W of Z.choices){let J=Y.choices[W.index];if(W.delta.content!=null&&J.message?.role==="assistant"&&J.message?.content)this._emit("content",W.delta.content,J.message.content),this._emit("content.delta",{delta:W.delta.content,snapshot:J.message.content,parsed:J.message.parsed});if(W.delta.refusal!=null&&J.message?.role==="assistant"&&J.message?.refusal)this._emit("refusal.delta",{delta:W.delta.refusal,snapshot:J.message.refusal});if(W.logprobs?.content!=null&&J.message?.role==="assistant")this._emit("logprobs.content.delta",{content:W.logprobs?.content,snapshot:J.logprobs?.content??[]});if(W.logprobs?.refusal!=null&&J.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:W.logprobs?.refusal,snapshot:J.logprobs?.refusal??[]});let Q=E(this,M1,"m",D8).call(this,J);if(J.finish_reason){if(E(this,M1,"m",QY).call(this,J),Q.current_tool_call_index!=null)E(this,M1,"m",JY).call(this,J,Q.current_tool_call_index)}for(let X of W.delta.tool_calls??[]){if(Q.current_tool_call_index!==X.index){if(E(this,M1,"m",QY).call(this,J),Q.current_tool_call_index!=null)E(this,M1,"m",JY).call(this,J,Q.current_tool_call_index)}Q.current_tool_call_index=X.index}for(let X of W.delta.tool_calls??[]){let K=J.message.tool_calls?.[X.index];if(!K?.type)continue;if(K?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:K.function?.name,index:X.index,arguments:K.function.arguments,parsed_arguments:K.function.parsed_arguments,arguments_delta:X.function?.arguments??""});else x9(K?.type)}}},JY=function(Z,Y){if(E(this,M1,"m",D8).call(this,Z).done_tool_calls.has(Y))return;let J=Z.message.tool_calls?.[Y];if(!J)throw Error("no tool call snapshot");if(!J.type)throw Error("tool call snapshot missing `type`");if(J.type==="function"){let Q=E(this,J0,"f")?.tools?.find((X)=>e$(X)&&X.function.name===J.function.name);this._emit("tool_calls.function.arguments.done",{name:J.function.name,index:Y,arguments:J.function.arguments,parsed_arguments:x0(Q)?Q.$parseRaw(J.function.arguments):Q?.function.strict?JSON.parse(J.function.arguments):null})}else x9(J.type)},QY=function(Z){let Y=E(this,M1,"m",D8).call(this,Z);if(Z.message.content&&!Y.content_done){Y.content_done=!0;let W=E(this,M1,"m",XY).call(this);this._emit("content.done",{content:Z.message.content,parsed:W?W.$parseRaw(Z.message.content):null})}if(Z.message.refusal&&!Y.refusal_done)Y.refusal_done=!0,this._emit("refusal.done",{refusal:Z.message.refusal});if(Z.logprobs?.content&&!Y.logprobs_content_done)Y.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:Z.logprobs.content});if(Z.logprobs?.refusal&&!Y.logprobs_refusal_done)Y.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:Z.logprobs.refusal})},j8=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");let Z=E(this,B0,"f");if(!Z)throw new p("request ended without sending any chunks");return i(this,B0,void 0,"f"),i(this,K$,[],"f"),jQ(Z,E(this,J0,"f"))},XY=function(){let Z=E(this,J0,"f")?.response_format;if($Z(Z))return Z;return null},A9=function(Z){var Y,W,J,Q;let X=E(this,B0,"f"),{choices:K,...V}=Z;if(!X)X=i(this,B0,{...V,choices:[]},"f");else Object.assign(X,V);for(let{delta:B,finish_reason:G,index:F,logprobs:z=null,...N}of Z.choices){let q=X.choices[F];if(!q)q=X.choices[F]={finish_reason:G,index:F,message:{},logprobs:z,...N};if(z)if(!q.logprobs)q.logprobs=Object.assign({},z);else{let{content:b,refusal:y,...k}=z;if(C9(k),Object.assign(q.logprobs,k),b)(Y=q.logprobs).content??(Y.content=[]),q.logprobs.content.push(...b);if(y)(W=q.logprobs).refusal??(W.refusal=[]),q.logprobs.refusal.push(...y)}if(G){if(q.finish_reason=G,E(this,J0,"f")&&r6(E(this,J0,"f"))){if(G==="length")throw new i$;if(G==="content_filter")throw new n$}}if(Object.assign(q,N),!B)continue;let{content:w,refusal:A,function_call:O,role:H,tool_calls:j,...S}=B;if(C9(S),Object.assign(q.message,S),A)q.message.refusal=(q.message.refusal||"")+A;if(H)q.message.role=H;if(O)if(!q.message.function_call)q.message.function_call=O;else{if(O.name)q.message.function_call.name=O.name;if(O.arguments)(J=q.message.function_call).arguments??(J.arguments=""),q.message.function_call.arguments+=O.arguments}if(w){if(q.message.content=(q.message.content||"")+w,!q.message.refusal&&E(this,M1,"m",XY).call(this))q.message.parsed=ZY(q.message.content)}if(j){if(!q.message.tool_calls)q.message.tool_calls=[];for(let{index:b,id:y,type:k,function:D,...I}of j){let M=(Q=q.message.tool_calls)[b]??(Q[b]={});if(Object.assign(M,I),y)M.id=y;if(k)M.type=k;if(D)M.function??(M.function={name:D.name??"",arguments:""});if(D?.name)M.function.name=D.name;if(D?.arguments){if(M.function.arguments+=D.arguments,E9(E(this,J0,"f"),M))M.function.parsed_arguments=ZY(M.function.arguments)}}}}return X},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("chunk",(W)=>{let J=Z.shift();if(J)J.resolve(W);else $.push(W)}),this.on("end",()=>{Y=!0;for(let W of Z)W.resolve(void 0);Z.length=0}),this.on("abort",(W)=>{Y=!0;for(let J of Z)J.reject(W);Z.length=0}),this.on("error",(W)=>{Y=!0;for(let J of Z)J.reject(W);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,Q)=>Z.push({resolve:J,reject:Q})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new A1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function jQ($,Z){let{id:Y,choices:W,created:J,model:Q,system_fingerprint:X,...K}=$,V={...K,id:Y,choices:W.map(({message:B,finish_reason:G,index:F,logprobs:z,...N})=>{if(!G)throw new p(`missing finish_reason for choice ${F}`);let{content:q=null,function_call:w,tool_calls:A,...O}=B,H=B.role;if(!H)throw new p(`missing role for choice ${F}`);if(w){let{arguments:j,name:S}=w;if(j==null)throw new p(`missing function_call.arguments for choice ${F}`);if(!S)throw new p(`missing function_call.name for choice ${F}`);return{...N,message:{content:q,function_call:{arguments:j,name:S},role:H,refusal:B.refusal??null},finish_reason:G,index:F,logprobs:z}}if(A)return{...N,index:F,finish_reason:G,logprobs:z,message:{...O,role:H,content:q,refusal:B.refusal??null,tool_calls:A.map((j,S)=>{let{function:b,type:y,id:k,...D}=j,{arguments:I,name:M,...L}=b||{};if(k==null)throw new p(`missing choices[${F}].tool_calls[${S}].id
|
|
70
|
+
${f8($)}`);if(y==null)throw new p(`missing choices[${F}].tool_calls[${S}].type
|
|
71
|
+
${f8($)}`);if(M==null)throw new p(`missing choices[${F}].tool_calls[${S}].function.name
|
|
72
|
+
${f8($)}`);if(I==null)throw new p(`missing choices[${F}].tool_calls[${S}].function.arguments
|
|
73
|
+
${f8($)}`);return{...D,id:k,type:y,function:{...L,name:M,arguments:I}}})}};return{...N,message:{...O,content:q,role:H,refusal:B.refusal??null},finish_reason:G,index:F,logprobs:z}}),created:J,model:Q,object:"chat.completion",...X?{system_fingerprint:X}:{}};return L9(V,Z)}function f8($){return JSON.stringify($)}function C9($){return}function x9($){}class V$ extends F0{static fromReadableStream($){let Z=new V$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static runTools($,Z,Y){let W=new V$(Z),J={...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"runTools"}};return W._run(()=>W._runTools($,Z,J)),W}}class q0 extends x{constructor(){super(...arguments);this.messages=new J$(this._client)}create($,Z){return this._client.post("/chat/completions",{body:$,...Z,stream:$.stream??!1})}retrieve($,Z){return this._client.get(T`/chat/completions/${$}`,Z)}update($,Z,Y){return this._client.post(T`/chat/completions/${$}`,{body:Z,...Y})}list($={},Z){return this._client.getAPIList("/chat/completions",e,{query:$,...Z})}delete($,Z){return this._client.delete(T`/chat/completions/${$}`,Z)}parse($,Z){return O9($.tools),this._client.chat.completions.create($,{...Z,headers:{...Z?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((Y)=>ZZ(Y,$))}runTools($,Z){if($.stream)return V$.runTools(this._client,$,Z);return KZ.runTools(this._client,$,Z)}stream($,Z){return F0.createChatCompletion(this._client,$,Z)}}q0.Messages=J$;class y0 extends x{constructor(){super(...arguments);this.completions=new q0(this._client)}}y0.Completions=q0;var R9=Symbol("brand.privateNullableHeaders");function*TQ($){if(!$)return;if(R9 in $){let{values:W,nulls:J}=$;yield*W.entries();for(let Q of J)yield[Q,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(C6($))Y=$;else Z=!0,Y=Object.entries($??{});for(let W of Y){let J=W[0];if(typeof J!=="string")throw TypeError("expected header name to be a string");let Q=C6(W[1])?W[1]:[W[1]],X=!1;for(let K of Q){if(K===void 0)continue;if(Z&&!X)X=!0,yield[J,null];yield[J,K]}}}var h=($)=>{let Z=new Headers,Y=new Set;for(let W of $){let J=new Set;for(let[Q,X]of TQ(W)){let K=Q.toLowerCase();if(!J.has(K))Z.delete(Q),J.add(K);if(X===null)Z.delete(Q),Y.add(K);else Z.append(Q,X),Y.delete(K)}}return{[R9]:!0,values:Z,nulls:Y}};class VZ extends x{create($,Z){return this._client.post("/audio/speech",{body:$,...Z,headers:h([{Accept:"application/octet-stream"},Z?.headers]),__binaryResponse:!0})}}class zZ extends x{create($,Z){return this._client.post("/audio/transcriptions",C1({body:$,...Z,stream:$.stream??!1,__metadata:{model:$.model}},this._client))}}class GZ extends x{create($,Z){return this._client.post("/audio/translations",C1({body:$,...Z,__metadata:{model:$.model}},this._client))}}class Q0 extends x{constructor(){super(...arguments);this.transcriptions=new zZ(this._client),this.translations=new GZ(this._client),this.speech=new VZ(this._client)}}Q0.Transcriptions=zZ;Q0.Translations=GZ;Q0.Speech=VZ;class z$ extends x{create($,Z){return this._client.post("/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(T`/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/batches",e,{query:$,...Z})}cancel($,Z){return this._client.post(T`/batches/${$}/cancel`,Z)}}class BZ extends x{create($,Z){return this._client.post("/assistants",{body:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,Z){return this._client.get(T`/assistants/${$}`,{...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,Z,Y){return this._client.post(T`/assistants/${$}`,{body:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}list($={},Z){return this._client.getAPIList("/assistants",e,{query:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,Z){return this._client.delete(T`/assistants/${$}`,{...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class FZ extends x{create($,Z){return this._client.post("/realtime/sessions",{body:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class qZ extends x{create($,Z){return this._client.post("/realtime/transcription_sessions",{body:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}}class k0 extends x{constructor(){super(...arguments);this.sessions=new FZ(this._client),this.transcriptionSessions=new qZ(this._client)}}k0.Sessions=FZ;k0.TranscriptionSessions=qZ;class UZ extends x{create($,Z){return this._client.post("/chatkit/sessions",{body:$,...Z,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers])})}cancel($,Z){return this._client.post(T`/chatkit/sessions/${$}/cancel`,{...Z,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers])})}}class HZ extends x{retrieve($,Z){return this._client.get(T`/chatkit/threads/${$}`,{...Z,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers])})}list($={},Z){return this._client.getAPIList("/chatkit/threads",G0,{query:$,...Z,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers])})}delete($,Z){return this._client.delete(T`/chatkit/threads/${$}`,{...Z,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},Z?.headers])})}listItems($,Z={},Y){return this._client.getAPIList(T`/chatkit/threads/${$}/items`,G0,{query:Z,...Y,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},Y?.headers])})}}class I0 extends x{constructor(){super(...arguments);this.sessions=new UZ(this._client),this.threads=new HZ(this._client)}}I0.Sessions=UZ;I0.Threads=HZ;class NZ extends x{create($,Z,Y){return this._client.post(T`/threads/${$}/messages`,{body:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}retrieve($,Z,Y){let{thread_id:W}=Z;return this._client.get(T`/threads/${W}/messages/${$}`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}update($,Z,Y){let{thread_id:W,...J}=Z;return this._client.post(T`/threads/${W}/messages/${$}`,{body:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}list($,Z={},Y){return this._client.getAPIList(T`/threads/${$}/messages`,e,{query:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}delete($,Z,Y){let{thread_id:W}=Z;return this._client.delete(T`/threads/${W}/messages/${$}`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}class MZ extends x{retrieve($,Z,Y){let{thread_id:W,run_id:J,...Q}=Z;return this._client.get(T`/threads/${W}/runs/${J}/steps/${$}`,{query:Q,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}list($,Z,Y){let{thread_id:W,...J}=Z;return this._client.getAPIList(T`/threads/${W}/runs/${$}/steps`,e,{query:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}var y9=($)=>{if(typeof Buffer<"u"){let Z=Buffer.from($,"base64");return Array.from(new Float32Array(Z.buffer,Z.byteOffset,Z.length/Float32Array.BYTES_PER_ELEMENT))}else{let Z=atob($),Y=Z.length,W=new Uint8Array(Y);for(let J=0;J<Y;J++)W[J]=Z.charCodeAt(J);return Array.from(new Float32Array(W.buffer))}};var U0=($)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[$]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.($)?.trim();return};var E1,v0,KY,p1,T8,g1,h0,G$,b0,A8,x1,P8,S8,EZ,wZ,LZ,k9,I9,b9,v9,h9,g9,m9;class H0 extends R0{constructor(){super(...arguments);E1.add(this),KY.set(this,[]),p1.set(this,{}),T8.set(this,{}),g1.set(this,void 0),h0.set(this,void 0),G$.set(this,void 0),b0.set(this,void 0),A8.set(this,void 0),x1.set(this,void 0),P8.set(this,void 0),S8.set(this,void 0),EZ.set(this,void 0)}[(KY=new WeakMap,p1=new WeakMap,T8=new WeakMap,g1=new WeakMap,h0=new WeakMap,G$=new WeakMap,b0=new WeakMap,A8=new WeakMap,x1=new WeakMap,P8=new WeakMap,S8=new WeakMap,EZ=new WeakMap,E1=new WeakSet,Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("event",(W)=>{let J=Z.shift();if(J)J.resolve(W);else $.push(W)}),this.on("end",()=>{Y=!0;for(let W of Z)W.resolve(void 0);Z.length=0}),this.on("abort",(W)=>{Y=!0;for(let J of Z)J.reject(W);Z.length=0}),this.on("error",(W)=>{Y=!0;for(let J of Z)J.reject(W);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,Q)=>Z.push({resolve:J,reject:Q})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream($){let Z=new v0;return Z._run(()=>Z._fromReadableStream($)),Z}async _fromReadableStream($,Z){let Y=Z?.signal;if(Y){if(Y.aborted)this.controller.abort();Y.addEventListener("abort",()=>this.controller.abort())}this._connected();let W=A1.fromReadableStream($,this.controller);for await(let J of W)E(this,E1,"m",wZ).call(this,J);if(W.controller.signal?.aborted)throw new H1;return this._addRun(E(this,E1,"m",LZ).call(this))}toReadableStream(){return new A1(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream($,Z,Y,W){let J=new v0;return J._run(()=>J._runToolAssistantStream($,Z,Y,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream($,Z,Y,W){let J=W?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let Q={...Y,stream:!0},X=await $.submitToolOutputs(Z,Q,{...W,signal:this.controller.signal});this._connected();for await(let K of X)E(this,E1,"m",wZ).call(this,K);if(X.controller.signal?.aborted)throw new H1;return this._addRun(E(this,E1,"m",LZ).call(this))}static createThreadAssistantStream($,Z,Y){let W=new v0;return W._run(()=>W._threadAssistantStream($,Z,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),W}static createAssistantStream($,Z,Y,W){let J=new v0;return J._run(()=>J._runAssistantStream($,Z,Y,{...W,headers:{...W?.headers,"X-Stainless-Helper-Method":"stream"}})),J}currentEvent(){return E(this,P8,"f")}currentRun(){return E(this,S8,"f")}currentMessageSnapshot(){return E(this,g1,"f")}currentRunStepSnapshot(){return E(this,EZ,"f")}async finalRunSteps(){return await this.done(),Object.values(E(this,p1,"f"))}async finalMessages(){return await this.done(),Object.values(E(this,T8,"f"))}async finalRun(){if(await this.done(),!E(this,h0,"f"))throw Error("Final run was not received.");return E(this,h0,"f")}async _createThreadAssistantStream($,Z,Y){let W=Y?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}let J={...Z,stream:!0},Q=await $.createAndRun(J,{...Y,signal:this.controller.signal});this._connected();for await(let X of Q)E(this,E1,"m",wZ).call(this,X);if(Q.controller.signal?.aborted)throw new H1;return this._addRun(E(this,E1,"m",LZ).call(this))}async _createAssistantStream($,Z,Y,W){let J=W?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let Q={...Y,stream:!0},X=await $.create(Z,Q,{...W,signal:this.controller.signal});this._connected();for await(let K of X)E(this,E1,"m",wZ).call(this,K);if(X.controller.signal?.aborted)throw new H1;return this._addRun(E(this,E1,"m",LZ).call(this))}static accumulateDelta($,Z){for(let[Y,W]of Object.entries(Z)){if(!$.hasOwnProperty(Y)){$[Y]=W;continue}let J=$[Y];if(J===null||J===void 0){$[Y]=W;continue}if(Y==="index"||Y==="type"){$[Y]=W;continue}if(typeof J==="string"&&typeof W==="string")J+=W;else if(typeof J==="number"&&typeof W==="number")J+=W;else if(r$(J)&&r$(W))J=this.accumulateDelta(J,W);else if(Array.isArray(J)&&Array.isArray(W)){if(J.every((Q)=>typeof Q==="string"||typeof Q==="number")){J.push(...W);continue}for(let Q of W){if(!r$(Q))throw Error(`Expected array delta entry to be an object but got: ${Q}`);let X=Q.index;if(X==null)throw console.error(Q),Error("Expected array delta entry to have an `index` property");if(typeof X!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${X}`);let K=J[X];if(K==null)J.push(Q);else J[X]=this.accumulateDelta(K,Q)}continue}else throw Error(`Unhandled record type: ${Y}, deltaValue: ${W}, accValue: ${J}`);$[Y]=J}return $}_addRun($){return $}async _threadAssistantStream($,Z,Y){return await this._createThreadAssistantStream(Z,$,Y)}async _runAssistantStream($,Z,Y,W){return await this._createAssistantStream(Z,$,Y,W)}async _runToolAssistantStream($,Z,Y,W){return await this._createToolAssistantStream(Z,$,Y,W)}}v0=H0,wZ=function(Z){if(this.ended)return;switch(i(this,P8,Z,"f"),E(this,E1,"m",b9).call(this,Z),Z.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":E(this,E1,"m",m9).call(this,Z);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":E(this,E1,"m",I9).call(this,Z);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":E(this,E1,"m",k9).call(this,Z);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:gQ(Z)}},LZ=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");if(!E(this,h0,"f"))throw Error("Final run has not been received");return E(this,h0,"f")},k9=function(Z){let[Y,W]=E(this,E1,"m",h9).call(this,Z,E(this,g1,"f"));i(this,g1,Y,"f"),E(this,T8,"f")[Y.id]=Y;for(let J of W){let Q=Y.content[J.index];if(Q?.type=="text")this._emit("textCreated",Q.text)}switch(Z.event){case"thread.message.created":this._emit("messageCreated",Z.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",Z.data.delta,Y),Z.data.delta.content)for(let J of Z.data.delta.content){if(J.type=="text"&&J.text){let Q=J.text,X=Y.content[J.index];if(X&&X.type=="text")this._emit("textDelta",Q,X.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(J.index!=E(this,G$,"f")){if(E(this,b0,"f"))switch(E(this,b0,"f").type){case"text":this._emit("textDone",E(this,b0,"f").text,E(this,g1,"f"));break;case"image_file":this._emit("imageFileDone",E(this,b0,"f").image_file,E(this,g1,"f"));break}i(this,G$,J.index,"f")}i(this,b0,Y.content[J.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(E(this,G$,"f")!==void 0){let J=Z.data.content[E(this,G$,"f")];if(J)switch(J.type){case"image_file":this._emit("imageFileDone",J.image_file,E(this,g1,"f"));break;case"text":this._emit("textDone",J.text,E(this,g1,"f"));break}}if(E(this,g1,"f"))this._emit("messageDone",Z.data);i(this,g1,void 0,"f")}},I9=function(Z){let Y=E(this,E1,"m",v9).call(this,Z);switch(i(this,EZ,Y,"f"),Z.event){case"thread.run.step.created":this._emit("runStepCreated",Z.data);break;case"thread.run.step.delta":let W=Z.data.delta;if(W.step_details&&W.step_details.type=="tool_calls"&&W.step_details.tool_calls&&Y.step_details.type=="tool_calls")for(let Q of W.step_details.tool_calls)if(Q.index==E(this,A8,"f"))this._emit("toolCallDelta",Q,Y.step_details.tool_calls[Q.index]);else{if(E(this,x1,"f"))this._emit("toolCallDone",E(this,x1,"f"));if(i(this,A8,Q.index,"f"),i(this,x1,Y.step_details.tool_calls[Q.index],"f"),E(this,x1,"f"))this._emit("toolCallCreated",E(this,x1,"f"))}this._emit("runStepDelta",Z.data.delta,Y);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(i(this,EZ,void 0,"f"),Z.data.step_details.type=="tool_calls"){if(E(this,x1,"f"))this._emit("toolCallDone",E(this,x1,"f")),i(this,x1,void 0,"f")}this._emit("runStepDone",Z.data,Y);break;case"thread.run.step.in_progress":break}},b9=function(Z){E(this,KY,"f").push(Z),this._emit("event",Z)},v9=function(Z){switch(Z.event){case"thread.run.step.created":return E(this,p1,"f")[Z.data.id]=Z.data,Z.data;case"thread.run.step.delta":let Y=E(this,p1,"f")[Z.data.id];if(!Y)throw Error("Received a RunStepDelta before creation of a snapshot");let W=Z.data;if(W.delta){let J=v0.accumulateDelta(Y,W.delta);E(this,p1,"f")[Z.data.id]=J}return E(this,p1,"f")[Z.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":E(this,p1,"f")[Z.data.id]=Z.data;break}if(E(this,p1,"f")[Z.data.id])return E(this,p1,"f")[Z.data.id];throw Error("No snapshot available")},h9=function(Z,Y){let W=[];switch(Z.event){case"thread.message.created":return[Z.data,W];case"thread.message.delta":if(!Y)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let J=Z.data;if(J.delta.content)for(let Q of J.delta.content)if(Q.index in Y.content){let X=Y.content[Q.index];Y.content[Q.index]=E(this,E1,"m",g9).call(this,Q,X)}else Y.content[Q.index]=Q,W.push(Q);return[Y,W];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(Y)return[Y,W];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},g9=function(Z,Y){return v0.accumulateDelta(Y,Z)},m9=function(Z){switch(i(this,S8,Z.data,"f"),Z.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":if(i(this,h0,Z.data,"f"),E(this,x1,"f"))this._emit("toolCallDone",E(this,x1,"f")),i(this,x1,void 0,"f");break;case"thread.run.cancelling":break}};function gQ($){}class B$ extends x{constructor(){super(...arguments);this.steps=new MZ(this._client)}create($,Z,Y){let{include:W,...J}=Z;return this._client.post(T`/threads/${$}/runs`,{query:{include:W},body:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),stream:Z.stream??!1})}retrieve($,Z,Y){let{thread_id:W}=Z;return this._client.get(T`/threads/${W}/runs/${$}`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}update($,Z,Y){let{thread_id:W,...J}=Z;return this._client.post(T`/threads/${W}/runs/${$}`,{body:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}list($,Z={},Y){return this._client.getAPIList(T`/threads/${$}/runs`,e,{query:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}cancel($,Z,Y){let{thread_id:W}=Z;return this._client.post(T`/threads/${W}/runs/${$}/cancel`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}async createAndPoll($,Z,Y){let W=await this.create($,Z,Y);return await this.poll(W.id,{thread_id:$},Y)}createAndStream($,Z,Y){return H0.createAssistantStream($,this._client.beta.threads.runs,Z,Y)}async poll($,Z,Y){let W=h([Y?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Y?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:J,response:Q}=await this.retrieve($,Z,{...Y,headers:{...Y?.headers,...W}}).withResponse();switch(J.status){case"queued":case"in_progress":case"cancelling":let X=5000;if(Y?.pollIntervalMs)X=Y.pollIntervalMs;else{let K=Q.headers.get("openai-poll-after-ms");if(K){let V=parseInt(K);if(!isNaN(V))X=V}}await c1(X);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return J}}}stream($,Z,Y){return H0.createAssistantStream($,this._client.beta.threads.runs,Z,Y)}submitToolOutputs($,Z,Y){let{thread_id:W,...J}=Z;return this._client.post(T`/threads/${W}/runs/${$}/submit_tool_outputs`,{body:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers]),stream:Z.stream??!1})}async submitToolOutputsAndPoll($,Z,Y){let W=await this.submitToolOutputs($,Z,Y);return await this.poll(W.id,Z,Y)}submitToolOutputsStream($,Z,Y){return H0.createToolAssistantStream($,this._client.beta.threads.runs,Z,Y)}}B$.Steps=MZ;class g0 extends x{constructor(){super(...arguments);this.runs=new B$(this._client),this.messages=new NZ(this._client)}create($={},Z){return this._client.post("/threads",{body:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,Z){return this._client.get(T`/threads/${$}`,{...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,Z,Y){return this._client.post(T`/threads/${$}`,{body:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}delete($,Z){return this._client.delete(T`/threads/${$}`,{...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}createAndRun($,Z){return this._client.post("/threads/runs",{body:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers]),stream:$.stream??!1})}async createAndRunPoll($,Z){let Y=await this.createAndRun($,Z);return await this.runs.poll(Y.id,{thread_id:Y.thread_id},Z)}createAndRunStream($,Z){return H0.createThreadAssistantStream($,this._client.beta.threads,Z)}}g0.Runs=B$;g0.Messages=NZ;class i1 extends x{constructor(){super(...arguments);this.realtime=new k0(this._client),this.chatkit=new I0(this._client),this.assistants=new BZ(this._client),this.threads=new g0(this._client)}}i1.Realtime=k0;i1.ChatKit=I0;i1.Assistants=BZ;i1.Threads=g0;class F$ extends x{create($,Z){return this._client.post("/completions",{body:$,...Z,stream:$.stream??!1})}}class _Z extends x{retrieve($,Z,Y){let{container_id:W}=Z;return this._client.get(T`/containers/${W}/files/${$}/content`,{...Y,headers:h([{Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}}class q$ extends x{constructor(){super(...arguments);this.content=new _Z(this._client)}create($,Z,Y){return this._client.post(T`/containers/${$}/files`,C1({body:Z,...Y},this._client))}retrieve($,Z,Y){let{container_id:W}=Z;return this._client.get(T`/containers/${W}/files/${$}`,Y)}list($,Z={},Y){return this._client.getAPIList(T`/containers/${$}/files`,e,{query:Z,...Y})}delete($,Z,Y){let{container_id:W}=Z;return this._client.delete(T`/containers/${W}/files/${$}`,{...Y,headers:h([{Accept:"*/*"},Y?.headers])})}}q$.Content=_Z;class m0 extends x{constructor(){super(...arguments);this.files=new q$(this._client)}create($,Z){return this._client.post("/containers",{body:$,...Z})}retrieve($,Z){return this._client.get(T`/containers/${$}`,Z)}list($={},Z){return this._client.getAPIList("/containers",e,{query:$,...Z})}delete($,Z){return this._client.delete(T`/containers/${$}`,{...Z,headers:h([{Accept:"*/*"},Z?.headers])})}}m0.Files=q$;class OZ extends x{create($,Z,Y){let{include:W,...J}=Z;return this._client.post(T`/conversations/${$}/items`,{query:{include:W},body:J,...Y})}retrieve($,Z,Y){let{conversation_id:W,...J}=Z;return this._client.get(T`/conversations/${W}/items/${$}`,{query:J,...Y})}list($,Z={},Y){return this._client.getAPIList(T`/conversations/${$}/items`,G0,{query:Z,...Y})}delete($,Z,Y){let{conversation_id:W}=Z;return this._client.delete(T`/conversations/${W}/items/${$}`,Y)}}class d0 extends x{constructor(){super(...arguments);this.items=new OZ(this._client)}create($={},Z){return this._client.post("/conversations",{body:$,...Z})}retrieve($,Z){return this._client.get(T`/conversations/${$}`,Z)}update($,Z,Y){return this._client.post(T`/conversations/${$}`,{body:Z,...Y})}delete($,Z){return this._client.delete(T`/conversations/${$}`,Z)}}d0.Items=OZ;class U$ extends x{create($,Z){let Y=!!$.encoding_format,W=Y?$.encoding_format:"base64";if(Y)z1(this._client).debug("embeddings/user defined encoding_format:",$.encoding_format);let J=this._client.post("/embeddings",{body:{...$,encoding_format:W},...Z});if(Y)return J;return z1(this._client).debug("embeddings/decoding base64 embeddings from base64"),J._thenUnwrap((Q)=>{if(Q&&Q.data)Q.data.forEach((X)=>{let K=X.embedding;X.embedding=y9(K)});return Q})}}class DZ extends x{retrieve($,Z,Y){let{eval_id:W,run_id:J}=Z;return this._client.get(T`/evals/${W}/runs/${J}/output_items/${$}`,Y)}list($,Z,Y){let{eval_id:W,...J}=Z;return this._client.getAPIList(T`/evals/${W}/runs/${$}/output_items`,e,{query:J,...Y})}}class H$ extends x{constructor(){super(...arguments);this.outputItems=new DZ(this._client)}create($,Z,Y){return this._client.post(T`/evals/${$}/runs`,{body:Z,...Y})}retrieve($,Z,Y){let{eval_id:W}=Z;return this._client.get(T`/evals/${W}/runs/${$}`,Y)}list($,Z={},Y){return this._client.getAPIList(T`/evals/${$}/runs`,e,{query:Z,...Y})}delete($,Z,Y){let{eval_id:W}=Z;return this._client.delete(T`/evals/${W}/runs/${$}`,Y)}cancel($,Z,Y){let{eval_id:W}=Z;return this._client.post(T`/evals/${W}/runs/${$}`,Y)}}H$.OutputItems=DZ;class u0 extends x{constructor(){super(...arguments);this.runs=new H$(this._client)}create($,Z){return this._client.post("/evals",{body:$,...Z})}retrieve($,Z){return this._client.get(T`/evals/${$}`,Z)}update($,Z,Y){return this._client.post(T`/evals/${$}`,{body:Z,...Y})}list($={},Z){return this._client.getAPIList("/evals",e,{query:$,...Z})}delete($,Z){return this._client.delete(T`/evals/${$}`,Z)}}u0.Runs=H$;class N$ extends x{create($,Z){return this._client.post("/files",C1({body:$,...Z},this._client))}retrieve($,Z){return this._client.get(T`/files/${$}`,Z)}list($={},Z){return this._client.getAPIList("/files",e,{query:$,...Z})}delete($,Z){return this._client.delete(T`/files/${$}`,Z)}content($,Z){return this._client.get(T`/files/${$}/content`,{...Z,headers:h([{Accept:"application/binary"},Z?.headers]),__binaryResponse:!0})}async waitForProcessing($,{pollInterval:Z=5000,maxWait:Y=1800000}={}){let W=new Set(["processed","error","deleted"]),J=Date.now(),Q=await this.retrieve($);while(!Q.status||!W.has(Q.status))if(await c1(Z),Q=await this.retrieve($),Date.now()-J>Y)throw new A0({message:`Giving up on waiting for file ${$} to finish processing after ${Y} milliseconds.`});return Q}}class jZ extends x{}class fZ extends x{run($,Z){return this._client.post("/fine_tuning/alpha/graders/run",{body:$,...Z})}validate($,Z){return this._client.post("/fine_tuning/alpha/graders/validate",{body:$,...Z})}}class M$ extends x{constructor(){super(...arguments);this.graders=new fZ(this._client)}}M$.Graders=fZ;class TZ extends x{create($,Z,Y){return this._client.getAPIList(T`/fine_tuning/checkpoints/${$}/permissions`,Y0,{body:Z,method:"post",...Y})}retrieve($,Z={},Y){return this._client.get(T`/fine_tuning/checkpoints/${$}/permissions`,{query:Z,...Y})}delete($,Z,Y){let{fine_tuned_model_checkpoint:W}=Z;return this._client.delete(T`/fine_tuning/checkpoints/${W}/permissions/${$}`,Y)}}class w$ extends x{constructor(){super(...arguments);this.permissions=new TZ(this._client)}}w$.Permissions=TZ;class PZ extends x{list($,Z={},Y){return this._client.getAPIList(T`/fine_tuning/jobs/${$}/checkpoints`,e,{query:Z,...Y})}}class L$ extends x{constructor(){super(...arguments);this.checkpoints=new PZ(this._client)}create($,Z){return this._client.post("/fine_tuning/jobs",{body:$,...Z})}retrieve($,Z){return this._client.get(T`/fine_tuning/jobs/${$}`,Z)}list($={},Z){return this._client.getAPIList("/fine_tuning/jobs",e,{query:$,...Z})}cancel($,Z){return this._client.post(T`/fine_tuning/jobs/${$}/cancel`,Z)}listEvents($,Z={},Y){return this._client.getAPIList(T`/fine_tuning/jobs/${$}/events`,e,{query:Z,...Y})}pause($,Z){return this._client.post(T`/fine_tuning/jobs/${$}/pause`,Z)}resume($,Z){return this._client.post(T`/fine_tuning/jobs/${$}/resume`,Z)}}L$.Checkpoints=PZ;class n1 extends x{constructor(){super(...arguments);this.methods=new jZ(this._client),this.jobs=new L$(this._client),this.checkpoints=new w$(this._client),this.alpha=new M$(this._client)}}n1.Methods=jZ;n1.Jobs=L$;n1.Checkpoints=w$;n1.Alpha=M$;class SZ extends x{}class c0 extends x{constructor(){super(...arguments);this.graderModels=new SZ(this._client)}}c0.GraderModels=SZ;class E$ extends x{createVariation($,Z){return this._client.post("/images/variations",C1({body:$,...Z},this._client))}edit($,Z){return this._client.post("/images/edits",C1({body:$,...Z,stream:$.stream??!1},this._client))}generate($,Z){return this._client.post("/images/generations",{body:$,...Z,stream:$.stream??!1})}}class _$ extends x{retrieve($,Z){return this._client.get(T`/models/${$}`,Z)}list($){return this._client.getAPIList("/models",Y0,$)}delete($,Z){return this._client.delete(T`/models/${$}`,Z)}}class O$ extends x{create($,Z){return this._client.post("/moderations",{body:$,...Z})}}class AZ extends x{accept($,Z,Y){return this._client.post(T`/realtime/calls/${$}/accept`,{body:Z,...Y,headers:h([{Accept:"*/*"},Y?.headers])})}hangup($,Z){return this._client.post(T`/realtime/calls/${$}/hangup`,{...Z,headers:h([{Accept:"*/*"},Z?.headers])})}refer($,Z,Y){return this._client.post(T`/realtime/calls/${$}/refer`,{body:Z,...Y,headers:h([{Accept:"*/*"},Y?.headers])})}reject($,Z={},Y){return this._client.post(T`/realtime/calls/${$}/reject`,{body:Z,...Y,headers:h([{Accept:"*/*"},Y?.headers])})}}class CZ extends x{create($,Z){return this._client.post("/realtime/client_secrets",{body:$,...Z})}}class N0 extends x{constructor(){super(...arguments);this.clientSecrets=new CZ(this._client),this.calls=new AZ(this._client)}}N0.ClientSecrets=CZ;N0.Calls=AZ;function d9($,Z){if(!Z||!JX(Z))return{...$,output_parsed:null,output:$.output.map((Y)=>{if(Y.type==="function_call")return{...Y,parsed_arguments:null};if(Y.type==="message")return{...Y,content:Y.content.map((W)=>({...W,parsed:null}))};else return Y})};return VY($,Z)}function VY($,Z){let Y=$.output.map((J)=>{if(J.type==="function_call")return{...J,parsed_arguments:KX(Z,J)};if(J.type==="message"){let Q=J.content.map((X)=>{if(X.type==="output_text")return{...X,parsed:WX(Z,X.text)};return X});return{...J,content:Q}}return J}),W=Object.assign({},$,{output:Y});if(!Object.getOwnPropertyDescriptor($,"output_text"))C8(W);return Object.defineProperty(W,"output_parsed",{enumerable:!0,get(){for(let J of W.output){if(J.type!=="message")continue;for(let Q of J.content)if(Q.type==="output_text"&&Q.parsed!==null)return Q.parsed}return null}}),W}function WX($,Z){if($.text?.format?.type!=="json_schema")return null;if("$parseRaw"in $.text?.format)return($.text?.format).$parseRaw(Z);return JSON.parse(Z)}function JX($){if($Z($.text?.format))return!0;return!1}function QX($){return $?.$brand==="auto-parseable-tool"}function XX($,Z){return $.find((Y)=>Y.type==="function"&&Y.name===Z)}function KX($,Z){let Y=XX($.tools??[],Z.name);return{...Z,...Z,parsed_arguments:QX(Y)?Y.$parseRaw(Z.arguments):Y?.strict?JSON.parse(Z.arguments):null}}function C8($){let Z=[];for(let Y of $.output){if(Y.type!=="message")continue;for(let W of Y.content)if(W.type==="output_text")Z.push(W.text)}$.output_text=Z.join("")}var D$,x8,M0,R8,u9,c9,l9,p9;class y8 extends R0{constructor($){super();D$.add(this),x8.set(this,void 0),M0.set(this,void 0),R8.set(this,void 0),i(this,x8,$,"f")}static createResponse($,Z,Y){let W=new y8(Z);return W._run(()=>W._createOrRetrieveResponse($,Z,{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),W}async _createOrRetrieveResponse($,Z,Y){let W=Y?.signal;if(W){if(W.aborted)this.controller.abort();W.addEventListener("abort",()=>this.controller.abort())}E(this,D$,"m",u9).call(this);let J,Q=null;if("response_id"in Z)J=await $.responses.retrieve(Z.response_id,{stream:!0},{...Y,signal:this.controller.signal,stream:!0}),Q=Z.starting_after??null;else J=await $.responses.create({...Z,stream:!0},{...Y,signal:this.controller.signal});this._connected();for await(let X of J)E(this,D$,"m",c9).call(this,X,Q);if(J.controller.signal?.aborted)throw new H1;return E(this,D$,"m",l9).call(this)}[(x8=new WeakMap,M0=new WeakMap,R8=new WeakMap,D$=new WeakSet,u9=function(){if(this.ended)return;i(this,M0,void 0,"f")},c9=function(Z,Y){if(this.ended)return;let W=(Q,X)=>{if(Y==null||X.sequence_number>Y)this._emit(Q,X)},J=E(this,D$,"m",p9).call(this,Z);switch(W("event",Z),Z.type){case"response.output_text.delta":{let Q=J.output[Z.output_index];if(!Q)throw new p(`missing output at index ${Z.output_index}`);if(Q.type==="message"){let X=Q.content[Z.content_index];if(!X)throw new p(`missing content at index ${Z.content_index}`);if(X.type!=="output_text")throw new p(`expected content to be 'output_text', got ${X.type}`);W("response.output_text.delta",{...Z,snapshot:X.text})}break}case"response.function_call_arguments.delta":{let Q=J.output[Z.output_index];if(!Q)throw new p(`missing output at index ${Z.output_index}`);if(Q.type==="function_call")W("response.function_call_arguments.delta",{...Z,snapshot:Q.arguments});break}default:W(Z.type,Z);break}},l9=function(){if(this.ended)throw new p("stream has ended, this shouldn't happen");let Z=E(this,M0,"f");if(!Z)throw new p("request ended without sending any events");i(this,M0,void 0,"f");let Y=VX(Z,E(this,x8,"f"));return i(this,R8,Y,"f"),Y},p9=function(Z){let Y=E(this,M0,"f");if(!Y){if(Z.type!=="response.created")throw new p(`When snapshot hasn't been set yet, expected 'response.created' event, got ${Z.type}`);return Y=i(this,M0,Z.response,"f"),Y}switch(Z.type){case"response.output_item.added":{Y.output.push(Z.item);break}case"response.content_part.added":{let W=Y.output[Z.output_index];if(!W)throw new p(`missing output at index ${Z.output_index}`);let J=W.type,Q=Z.part;if(J==="message"&&Q.type!=="reasoning_text")W.content.push(Q);else if(J==="reasoning"&&Q.type==="reasoning_text"){if(!W.content)W.content=[];W.content.push(Q)}break}case"response.output_text.delta":{let W=Y.output[Z.output_index];if(!W)throw new p(`missing output at index ${Z.output_index}`);if(W.type==="message"){let J=W.content[Z.content_index];if(!J)throw new p(`missing content at index ${Z.content_index}`);if(J.type!=="output_text")throw new p(`expected content to be 'output_text', got ${J.type}`);J.text+=Z.delta}break}case"response.function_call_arguments.delta":{let W=Y.output[Z.output_index];if(!W)throw new p(`missing output at index ${Z.output_index}`);if(W.type==="function_call")W.arguments+=Z.delta;break}case"response.reasoning_text.delta":{let W=Y.output[Z.output_index];if(!W)throw new p(`missing output at index ${Z.output_index}`);if(W.type==="reasoning"){let J=W.content?.[Z.content_index];if(!J)throw new p(`missing content at index ${Z.content_index}`);if(J.type!=="reasoning_text")throw new p(`expected content to be 'reasoning_text', got ${J.type}`);J.text+=Z.delta}break}case"response.completed":{i(this,M0,Z.response,"f");break}}return Y},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("event",(W)=>{let J=Z.shift();if(J)J.resolve(W);else $.push(W)}),this.on("end",()=>{Y=!0;for(let W of Z)W.resolve(void 0);Z.length=0}),this.on("abort",(W)=>{Y=!0;for(let J of Z)J.reject(W);Z.length=0}),this.on("error",(W)=>{Y=!0;for(let J of Z)J.reject(W);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,Q)=>Z.push({resolve:J,reject:Q})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}async finalResponse(){await this.done();let $=E(this,R8,"f");if(!$)throw new p("stream ended without producing a ChatCompletion");return $}}function VX($,Z){return d9($,Z)}class xZ extends x{list($,Z={},Y){return this._client.getAPIList(T`/responses/${$}/input_items`,e,{query:Z,...Y})}}class RZ extends x{count($={},Z){return this._client.post("/responses/input_tokens",{body:$,...Z})}}class w0 extends x{constructor(){super(...arguments);this.inputItems=new xZ(this._client),this.inputTokens=new RZ(this._client)}create($,Z){return this._client.post("/responses",{body:$,...Z,stream:$.stream??!1})._thenUnwrap((Y)=>{if("object"in Y&&Y.object==="response")C8(Y);return Y})}retrieve($,Z={},Y){return this._client.get(T`/responses/${$}`,{query:Z,...Y,stream:Z?.stream??!1})._thenUnwrap((W)=>{if("object"in W&&W.object==="response")C8(W);return W})}delete($,Z){return this._client.delete(T`/responses/${$}`,{...Z,headers:h([{Accept:"*/*"},Z?.headers])})}parse($,Z){return this._client.responses.create($,Z)._thenUnwrap((Y)=>VY(Y,$))}stream($,Z){return y8.createResponse(this._client,$,Z)}cancel($,Z){return this._client.post(T`/responses/${$}/cancel`,Z)}compact($,Z){return this._client.post("/responses/compact",{body:$,...Z})}}w0.InputItems=xZ;w0.InputTokens=RZ;class yZ extends x{create($,Z,Y){return this._client.post(T`/uploads/${$}/parts`,C1({body:Z,...Y},this._client))}}class l0 extends x{constructor(){super(...arguments);this.parts=new yZ(this._client)}create($,Z){return this._client.post("/uploads",{body:$,...Z})}cancel($,Z){return this._client.post(T`/uploads/${$}/cancel`,Z)}complete($,Z,Y){return this._client.post(T`/uploads/${$}/complete`,{body:Z,...Y})}}l0.Parts=yZ;var i9=async($)=>{let Z=await Promise.allSettled($),Y=Z.filter((J)=>J.status==="rejected");if(Y.length){for(let J of Y)console.error(J.reason);throw Error(`${Y.length} promise(s) failed - see the above errors`)}let W=[];for(let J of Z)if(J.status==="fulfilled")W.push(J.value);return W};class kZ extends x{create($,Z,Y){return this._client.post(T`/vector_stores/${$}/file_batches`,{body:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}retrieve($,Z,Y){let{vector_store_id:W}=Z;return this._client.get(T`/vector_stores/${W}/file_batches/${$}`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}cancel($,Z,Y){let{vector_store_id:W}=Z;return this._client.post(T`/vector_stores/${W}/file_batches/${$}/cancel`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}async createAndPoll($,Z,Y){let W=await this.create($,Z);return await this.poll($,W.id,Y)}listFiles($,Z,Y){let{vector_store_id:W,...J}=Z;return this._client.getAPIList(T`/vector_stores/${W}/file_batches/${$}/files`,e,{query:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}async poll($,Z,Y){let W=h([Y?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Y?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:J,response:Q}=await this.retrieve(Z,{vector_store_id:$},{...Y,headers:W}).withResponse();switch(J.status){case"in_progress":let X=5000;if(Y?.pollIntervalMs)X=Y.pollIntervalMs;else{let K=Q.headers.get("openai-poll-after-ms");if(K){let V=parseInt(K);if(!isNaN(V))X=V}}await c1(X);break;case"failed":case"cancelled":case"completed":return J}}}async uploadAndPoll($,{files:Z,fileIds:Y=[]},W){if(Z==null||Z.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let J=W?.maxConcurrency??5,Q=Math.min(J,Z.length),X=this._client,K=Z.values(),V=[...Y];async function B(F){for(let z of F){let N=await X.files.create({file:z,purpose:"assistants"},W);V.push(N.id)}}let G=Array(Q).fill(K).map(B);return await i9(G),await this.createAndPoll($,{file_ids:V})}}class IZ extends x{create($,Z,Y){return this._client.post(T`/vector_stores/${$}/files`,{body:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}retrieve($,Z,Y){let{vector_store_id:W}=Z;return this._client.get(T`/vector_stores/${W}/files/${$}`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}update($,Z,Y){let{vector_store_id:W,...J}=Z;return this._client.post(T`/vector_stores/${W}/files/${$}`,{body:J,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}list($,Z={},Y){return this._client.getAPIList(T`/vector_stores/${$}/files`,e,{query:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}delete($,Z,Y){let{vector_store_id:W}=Z;return this._client.delete(T`/vector_stores/${W}/files/${$}`,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}async createAndPoll($,Z,Y){let W=await this.create($,Z,Y);return await this.poll($,W.id,Y)}async poll($,Z,Y){let W=h([Y?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":Y?.pollIntervalMs?.toString()??void 0}]);while(!0){let J=await this.retrieve(Z,{vector_store_id:$},{...Y,headers:W}).withResponse(),Q=J.data;switch(Q.status){case"in_progress":let X=5000;if(Y?.pollIntervalMs)X=Y.pollIntervalMs;else{let K=J.response.headers.get("openai-poll-after-ms");if(K){let V=parseInt(K);if(!isNaN(V))X=V}}await c1(X);break;case"failed":case"completed":return Q}}}async upload($,Z,Y){let W=await this._client.files.create({file:Z,purpose:"assistants"},Y);return this.create($,{file_id:W.id},Y)}async uploadAndPoll($,Z,Y){let W=await this.upload($,Z,Y);return await this.poll($,W.id,Y)}content($,Z,Y){let{vector_store_id:W}=Z;return this._client.getAPIList(T`/vector_stores/${W}/files/${$}/content`,Y0,{...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}class L0 extends x{constructor(){super(...arguments);this.files=new IZ(this._client),this.fileBatches=new kZ(this._client)}create($,Z){return this._client.post("/vector_stores",{body:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}retrieve($,Z){return this._client.get(T`/vector_stores/${$}`,{...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}update($,Z,Y){return this._client.post(T`/vector_stores/${$}`,{body:Z,...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}list($={},Z){return this._client.getAPIList("/vector_stores",e,{query:$,...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}delete($,Z){return this._client.delete(T`/vector_stores/${$}`,{...Z,headers:h([{"OpenAI-Beta":"assistants=v2"},Z?.headers])})}search($,Z,Y){return this._client.getAPIList(T`/vector_stores/${$}/search`,Y0,{body:Z,method:"post",...Y,headers:h([{"OpenAI-Beta":"assistants=v2"},Y?.headers])})}}L0.Files=IZ;L0.FileBatches=kZ;class j$ extends x{create($,Z){return this._client.post("/videos",i6({body:$,...Z},this._client))}retrieve($,Z){return this._client.get(T`/videos/${$}`,Z)}list($={},Z){return this._client.getAPIList("/videos",G0,{query:$,...Z})}delete($,Z){return this._client.delete(T`/videos/${$}`,Z)}downloadContent($,Z={},Y){return this._client.get(T`/videos/${$}/content`,{query:Z,...Y,headers:h([{Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}remix($,Z,Y){return this._client.post(T`/videos/${$}/remix`,i6({body:Z,...Y},this._client))}}var f$,n9,k8;class T$ extends x{constructor(){super(...arguments);f$.add(this)}async unwrap($,Z,Y=this._client.webhookSecret,W=300){return await this.verifySignature($,Z,Y,W),JSON.parse($)}async verifySignature($,Z,Y=this._client.webhookSecret,W=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");E(this,f$,"m",n9).call(this,Y);let J=h([Z]).values,Q=E(this,f$,"m",k8).call(this,J,"webhook-signature"),X=E(this,f$,"m",k8).call(this,J,"webhook-timestamp"),K=E(this,f$,"m",k8).call(this,J,"webhook-id"),V=parseInt(X,10);if(isNaN(V))throw new $0("Invalid webhook timestamp format");let B=Math.floor(Date.now()/1000);if(B-V>W)throw new $0("Webhook timestamp is too old");if(V>B+W)throw new $0("Webhook timestamp is too new");let G=Q.split(" ").map((q)=>q.startsWith("v1,")?q.substring(3):q),F=Y.startsWith("whsec_")?Buffer.from(Y.replace("whsec_",""),"base64"):Buffer.from(Y,"utf-8"),z=K?`${K}.${X}.${$}`:`${X}.${$}`,N=await crypto.subtle.importKey("raw",F,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let q of G)try{let w=Buffer.from(q,"base64");if(await crypto.subtle.verify("HMAC",N,w,new TextEncoder().encode(z)))return}catch{continue}throw new $0("The given webhook signature does not match the expected signature")}}f$=new WeakSet,n9=function(Z){if(typeof Z!=="string"||Z.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},k8=function(Z,Y){if(!Z)throw Error("Headers are required");let W=Z.get(Y);if(W===null||W===void 0)throw Error(`Missing required header: ${Y}`);return W};var zY,GY,I8,r9;class o{constructor({baseURL:$=U0("OPENAI_BASE_URL"),apiKey:Z=U0("OPENAI_API_KEY"),organization:Y=U0("OPENAI_ORG_ID")??null,project:W=U0("OPENAI_PROJECT_ID")??null,webhookSecret:J=U0("OPENAI_WEBHOOK_SECRET")??null,...Q}={}){if(zY.add(this),I8.set(this,void 0),this.completions=new F$(this),this.chat=new y0(this),this.embeddings=new U$(this),this.files=new N$(this),this.images=new E$(this),this.audio=new Q0(this),this.moderations=new O$(this),this.models=new _$(this),this.fineTuning=new n1(this),this.graders=new c0(this),this.vectorStores=new L0(this),this.webhooks=new T$(this),this.beta=new i1(this),this.batches=new z$(this),this.uploads=new l0(this),this.responses=new w0(this),this.realtime=new N0(this),this.conversations=new d0(this),this.evals=new u0(this),this.containers=new m0(this),this.videos=new j$(this),Z===void 0)throw new p("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let X={apiKey:Z,organization:Y,project:W,webhookSecret:J,...Q,baseURL:$||"https://api.openai.com/v1"};if(!X.dangerouslyAllowBrowser&&o7())throw new p(`It looks like you're running in a browser-like environment.
|
|
74
|
+
|
|
75
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
76
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
77
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
78
|
+
|
|
79
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
80
|
+
|
|
81
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
82
|
+
`);this.baseURL=X.baseURL,this.timeout=X.timeout??GY.DEFAULT_TIMEOUT,this.logger=X.logger??console;let K="warn";this.logLevel=K,this.logLevel=d6(X.logLevel,"ClientOptions.logLevel",this)??d6(U0("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??K,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??t7(),i(this,I8,$9,"f"),this._options=X,this.apiKey=typeof Z==="string"?Z:"Missing Key",this.organization=Y,this.project=W,this.webhookSecret=J}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){return}async authHeaders($){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery($){return g6($,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${z0}`}defaultIdempotencyKey(){return`stainless-node-retry-${A6()}`}makeStatusError($,Z,Y,W){return F1.generate($,Z,Y,W)}async _callApiKey(){let $=this._options.apiKey;if(typeof $!=="function")return!1;let Z;try{Z=await $()}catch(Y){if(Y instanceof p)throw Y;throw new p(`Failed to get token from 'apiKey' function: ${Y.message}`,{cause:Y})}if(typeof Z!=="string"||!Z)throw new p(`Expected 'apiKey' function argument to return a string but it returned ${Z}`);return this.apiKey=Z,!0}buildURL($,Z,Y){let W=!E(this,zY,"m",r9).call(this)&&Y||this.baseURL,J=u7($)?new URL($):new URL(W+(W.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),Q=this.defaultQuery();if(!c7(Q))Z={...Q,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))J.search=this.stringifyQuery(Z);return J.toString()}async prepareOptions($){await this._callApiKey()}async prepareRequest($,{url:Z,options:Y}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Y){return this.request(Promise.resolve(Y).then((W)=>{return{method:$,path:Z,...W}}))}request($,Z=null){return new C0(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let W=await $,J=W.maxRetries??this.maxRetries;if(Z==null)Z=J;await this.prepareOptions(W);let{req:Q,url:X,timeout:K}=await this.buildRequest(W,{retryCount:J-Z});await this.prepareRequest(Q,{url:X,options:W});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),B=Y===void 0?"":`, retryOf: ${Y}`,G=Date.now();if(z1(this).debug(`[${V}] sending request`,Z0({retryOfRequestLogID:Y,method:W.method,url:X,options:W,headers:Q.headers})),W.signal?.aborted)throw new H1;let F=new AbortController,z=await this.fetchWithTimeout(X,Q,K,F).catch(v$),N=Date.now();if(z instanceof globalThis.Error){let A=`retrying, ${Z} attempts remaining`;if(W.signal?.aborted)throw new H1;let O=b$(z)||/timed? ?out/i.test(String(z)+("cause"in z?String(z.cause):""));if(Z)return z1(this).info(`[${V}] connection ${O?"timed out":"failed"} - ${A}`),z1(this).debug(`[${V}] connection ${O?"timed out":"failed"} (${A})`,Z0({retryOfRequestLogID:Y,url:X,durationMs:N-G,message:z.message})),this.retryRequest(W,Z,Y??V);if(z1(this).info(`[${V}] connection ${O?"timed out":"failed"} - error; no more retries left`),z1(this).debug(`[${V}] connection ${O?"timed out":"failed"} (error; no more retries left)`,Z0({retryOfRequestLogID:Y,url:X,durationMs:N-G,message:z.message})),O)throw new A0;throw new S0({cause:z})}let q=[...z.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,O])=>", "+A+": "+JSON.stringify(O)).join(""),w=`[${V}${B}${q}] ${Q.method} ${X} ${z.ok?"succeeded":"failed"} with status ${z.status} in ${N-G}ms`;if(!z.ok){let A=await this.shouldRetry(z);if(Z&&A){let y=`retrying, ${Z} attempts remaining`;return await e7(z.body),z1(this).info(`${w} - ${y}`),z1(this).debug(`[${V}] response error (${y})`,Z0({retryOfRequestLogID:Y,url:z.url,status:z.status,headers:z.headers,durationMs:N-G})),this.retryRequest(W,Z,Y??V,z.headers)}let O=A?"error; no more retries left":"error; not retryable";z1(this).info(`${w} - ${O}`);let H=await z.text().catch((y)=>v$(y).message),j=i7(H),S=j?void 0:H;throw z1(this).debug(`[${V}] response error (${O})`,Z0({retryOfRequestLogID:Y,url:z.url,status:z.status,headers:z.headers,message:S,durationMs:Date.now()-G})),this.makeStatusError(z.status,j,S,z.headers)}return z1(this).info(w),z1(this).debug(`[${V}] response start`,Z0({retryOfRequestLogID:Y,url:z.url,status:z.status,headers:z.headers,durationMs:N-G})),{response:z,options:W,controller:F,requestLogID:V,retryOfRequestLogID:Y,startTime:G}}getAPIList($,Z,Y){return this.requestAPIList(Z,{method:"get",path:$,...Y})}requestAPIList($,Z){let Y=this.makeRequest(Z,null,void 0);return new U8(this,Y,$)}async fetchWithTimeout($,Z,Y,W){let{signal:J,method:Q,...X}=Z||{};if(J)J.addEventListener("abort",()=>W.abort());let K=setTimeout(()=>W.abort(),Y),V=globalThis.ReadableStream&&X.body instanceof globalThis.ReadableStream||typeof X.body==="object"&&X.body!==null&&Symbol.asyncIterator in X.body,B={signal:W.signal,...V?{duplex:"half"}:{},method:"GET",...X};if(Q)B.method=Q.toUpperCase();try{return await this.fetch.call(void 0,$,B)}finally{clearTimeout(K)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,W){let J,Q=W?.get("retry-after-ms");if(Q){let K=parseFloat(Q);if(!Number.isNaN(K))J=K}let X=W?.get("retry-after");if(X&&!J){let K=parseFloat(X);if(!Number.isNaN(K))J=K*1000;else J=Date.parse(X)-Date.now()}if(!(J&&0<=J&&J<60000)){let K=$.maxRetries??this.maxRetries;J=this.calculateDefaultRetryTimeoutMillis(Z,K)}return await c1(J),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let J=Z-$,Q=Math.min(0.5*Math.pow(2,J),8),X=1-Math.random()*0.25;return Q*X*1000}async buildRequest($,{retryCount:Z=0}={}){let Y={...$},{method:W,path:J,query:Q,defaultBaseURL:X}=Y,K=this.buildURL(J,Q,X);if("timeout"in Y)p7("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:V,body:B}=this.buildBody({options:Y}),G=await this.buildHeaders({options:$,method:W,bodyHeaders:V,retryCount:Z});return{req:{method:W,headers:G,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&B instanceof globalThis.ReadableStream&&{duplex:"half"},...B&&{body:B},...this.fetchOptions??{},...Y.fetchOptions??{}},url:K,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:W}){let J={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let Q=h([J,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(W),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...s7(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders($),this._options.defaultHeaders,Y,$.headers]);return this.validateHeaders(Q),Q.values}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Y=h([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Y.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:Q8($)};else return E(this,I8,"f").call(this,{body:$,headers:Y})}}GY=o,I8=new WeakMap,zY=new WeakSet,r9=function(){return this.baseURL!=="https://api.openai.com/v1"};o.OpenAI=GY;o.DEFAULT_TIMEOUT=600000;o.OpenAIError=p;o.APIError=F1;o.APIConnectionError=S0;o.APIConnectionTimeoutError=A0;o.APIUserAbortError=H1;o.NotFoundError=d$;o.ConflictError=u$;o.RateLimitError=l$;o.BadRequestError=h$;o.AuthenticationError=g$;o.InternalServerError=p$;o.PermissionDeniedError=m$;o.UnprocessableEntityError=c$;o.InvalidWebhookSignatureError=$0;o.toFile=N8;o.Completions=F$;o.Chat=y0;o.Embeddings=U$;o.Files=N$;o.Images=E$;o.Audio=Q0;o.Moderations=O$;o.Models=_$;o.FineTuning=n1;o.Graders=c0;o.VectorStores=L0;o.Webhooks=T$;o.Beta=i1;o.Batches=z$;o.Uploads=l0;o.Responses=w0;o.Realtime=N0;o.Conversations=d0;o.Evals=u0;o.Containers=m0;o.Videos=j$;function HX($){function Z(Y,W){if(typeof Y!=="string")return"";let J=Y.trim();if(!J)return"";if(/^data:/i.test(J)||/^https?:\/\//i.test(J))return J;if(typeof W==="string"&&W.trim())return`data:${W.trim()};base64,${J}`;return J}if(typeof $==="string")return $.trim().length===0?"":$;if($===null||$===void 0)return"";if(typeof $==="object"&&"type"in $){let Y=$;if(Y.type==="text"&&Y.text)return Y.text;if(Y.type==="image"){let W=Z(Y.data??Y.source?.data,Y.mimeType??Y.source?.media_type??Y.source?.mimeType);if(!W)return"";return[{type:"image_url",image_url:{url:W}}]}}if(Array.isArray($)){let Y=[];for(let W of $)if(typeof W==="string")Y.push({type:"text",text:W});else if(W&&typeof W==="object"&&"type"in W){let J=W;if(J.type==="text"&&J.text)Y.push({type:"text",text:J.text});else if(J.type==="image"){let Q=Z(J.data??J.source?.data,J.mimeType??J.source?.media_type??J.source?.mimeType);if(Q)Y.push({type:"image_url",image_url:{url:Q}})}}return Y.length>0?Y:""}return String($)}function NX($){return{...$,content:HX($.content)}}function MX($,Z){if(typeof Z==="string"&&/deepseek/i.test(Z))return!0;return/^deepseek-/i.test($)}function wX($={}){let Z=$.baseUrl;function Y(){if(typeof $.apiKey==="function"){let V=$.apiKey();if(typeof V==="string"){let B=V.trim();if(!B)throw new Q1("Missing apiKey",{code:"missing_api_key",retryable:!1});return B}if(V!=null)throw new Q1("Invalid apiKey provider",{code:"invalid_api_key",retryable:!1})}if(typeof $.apiKey==="string"){let V=$.apiKey.trim();if(!V)throw new Q1("Missing apiKey",{code:"missing_api_key",retryable:!1});return V}let K=typeof process<"u"?process.env?.OPENAI_API_KEY:void 0;if(typeof K!=="string"||!K.trim())throw new Q1("Missing OPENAI_API_KEY",{code:"missing_api_key",retryable:!1});return K.trim()}function W(){let K=Y();if(typeof Z==="string"&&/\/chat\/completions\/?$/.test(Z))return new o({apiKey:K,organization:$.organization,project:$.project,baseURL:"https://api.openai.com/v1",fetch:(B,G)=>{return fetch(Z,G)}});return new o({apiKey:K,organization:$.organization,project:$.project,baseURL:Z||void 0})}function J(K){return{provider:"openai",modelId:K.model.modelId}}function Q(K){if(K instanceof Q1)return K;let V=typeof K?.status==="number"?K.status:void 0,B=typeof K?.message==="string"?K.message:"OpenAI error",G=typeof K?.code==="string"?K.code:V?`openai_http_${V}`:"openai_error",F=V?$$.isRetryableStatus(V):!1;return new Q1(B,{code:G,retryable:F,status:V})}async function*X(K){let{request:V}=K,B=V.requestId||J8("req"),G=W(),F=V.model.modelId,z=$.compat?.interleavedThinking,N=typeof z==="boolean"?z:MX(F,Z),q=V.stream!==!1,w=[];if(V.messages&&Array.isArray(V.messages))for(let H of V.messages){let j=NX(H);if(!N&&j&&typeof j==="object"){if("reasoning_content"in j)delete j.reasoning_content}else if(N&&j?.role==="assistant"&&Array.isArray(j?.tool_calls)&&j.tool_calls.length>0){let S=j.reasoning_content;if(typeof S!=="string"||S.length===0)j.reasoning_content="."}w.push(j)}else{if(typeof V.instructions==="string"&&V.instructions.length>0)w.push({role:"system",content:V.instructions});w.push({role:"user",content:V.input})}let A=(()=>{let H=V.reasoning?.effort;if(typeof H!=="string")return;if(H==="none"||H==="minimal"||H==="low"||H==="medium"||H==="high"||H==="xhigh")return H;return})(),O={model:F,messages:w,stream:q,stream_options:q?{include_usage:!0}:void 0,metadata:V.metadata??void 0,reasoning_effort:A,max_completion_tokens:V.maxOutputTokens??void 0,stop:V.stop??void 0,temperature:V.temperature??void 0,top_p:V.topP??1};if(V.tools&&Array.isArray(V.tools)&&V.tools.length>0)O.tools=V.tools;try{let H=J(V);if(yield{type:"response_start",requestId:B,model:H},!q){let I=await G.chat.completions.create({...O,stream:!1},{signal:V.signal,timeout:V.timeoutMs}),M=Array.isArray(I?.choices)?I.choices[0]:void 0,L=M?.message,u=typeof L?.reasoning_content==="string"?L.reasoning_content:"";if(u.length>0)yield{type:"delta",requestId:B,chunk:{kind:"thinking_start"}},yield{type:"delta",requestId:B,chunk:{kind:"thinking_delta",text:u}},yield{type:"delta",requestId:B,chunk:{kind:"thinking_end",text:u}};let l=typeof L?.content==="string"?L.content:"";if(l.length>0)yield{type:"delta",requestId:B,chunk:{kind:"text",text:l}};let f=Array.isArray(L?.tool_calls)?L.tool_calls:[];for(let _=0;_<f.length;_++){let g=f[_],m=typeof g?.id==="string"?g.id:`call_${_}`,r=typeof g?.function?.name==="string"?g.function.name:void 0,$1=typeof g?.function?.arguments==="string"?g.function.arguments:void 0;if($1||r)yield{type:"delta",requestId:B,chunk:{kind:"tool_call_delta",callId:m,toolId:r,argsTextDelta:$1}}}let U=a9(M?.finish_reason);yield{type:"response_end",requestId:B,stopReason:U,usage:I?.usage};return}let j=await G.chat.completions.create({...O,stream:!0},{signal:V.signal,timeout:V.timeoutMs}),S=null,b,y=new Map,k=!1,D="";for await(let I of j){if(I?.usage!=null)b=I.usage;let M=Array.isArray(I?.choices)?I.choices:[];for(let L of M){if(L?.finish_reason!=null)S=L.finish_reason;let u=L?.delta,l=u?.reasoning_content;if(typeof l==="string"&&l.length>0){if(!k)k=!0,yield{type:"delta",requestId:B,chunk:{kind:"thinking_start"}};D+=l,yield{type:"delta",requestId:B,chunk:{kind:"thinking_delta",text:l}}}let f=u?.content;if(typeof f==="string"&&f.length>0){if(k)k=!1,yield{type:"delta",requestId:B,chunk:{kind:"thinking_end",text:D||void 0}};yield{type:"delta",requestId:B,chunk:{kind:"text",text:f}}}let U=Array.isArray(u?.tool_calls)?u.tool_calls:[];for(let _ of U){let g=typeof _?.index==="number"?_.index:0,r=y.get(g)||(typeof _?.id==="string"?_.id:`call_${g}`);y.set(g,r);let $1=typeof _?.function?.name==="string"?_.function.name:void 0,Y1=typeof _?.function?.arguments==="string"?_.function.arguments:void 0;if($1||Y1)yield{type:"delta",requestId:B,chunk:{kind:"tool_call_delta",callId:r,toolId:$1,argsTextDelta:Y1}}}}}if(k)yield{type:"delta",requestId:B,chunk:{kind:"thinking_end",text:D||void 0}};yield{type:"response_end",requestId:B,stopReason:a9(S),usage:b}}catch(H){if(H?.name==="AbortError")throw new Q1("Aborted",{code:"aborted",retryable:!1});throw Q(H)}}return{provider:"openai",defaultModelId:$.defaultModelId,stream:X}}function a9($){if($==="tool_calls"||$==="function_call")return"tool_call";if($==="length")return"length";if($==="content_filter")return"error";if($==="stop"||$==null)return"final";return"final"}class b8{queue=[];waiters=[];enqueue($){let Z=this.waiters.shift();if(Z){Z($);return}this.queue.push($)}isEmpty(){return this.queue.length===0}async dequeueOrWait($){if(this.queue.length>0)return this.queue.shift();return new Promise((Z)=>{let Y=setTimeout(()=>{let W=this.waiters.indexOf(Z);if(W>=0)this.waiters.splice(W,1);Z(void 0)},$);this.waiters.push((W)=>{clearTimeout(Y),Z(W)})})}}class BY{tools;options;eventQueue=new b8;constructor($,Z){this.tools=$;this.options=Z}async*executeTasksInParallel($,Z,Y){this.eventQueue=new b8;let W=!1,J=$.map(async(K)=>{let V=K.toolCall.function.name,B=this.tools?.get(V);if(!B)return{tc:K,result:`Tool "${V}" not found`,isError:!0};try{let G=typeof K.toolCall.function.arguments==="string"?JSON.parse(K.toolCall.function.arguments):K.toolCall.function.arguments,F=`${Z.sessionId}:subagent:${crypto.randomUUID()}`,z={...Y,sessionId:F,emitEvent:(q)=>{this.eventQueue.enqueue({...q,sessionId:Z.sessionId})}},N=await B.execute(G,z);return{tc:K,result:N,isError:!1}}catch(G){return{tc:K,result:`Task execution failed: ${G instanceof Error?G.message:String(G)}`,isError:!0}}}),Q=Promise.allSettled(J).then((K)=>{return W=!0,K});while(!W||!this.eventQueue.isEmpty()){let K=await this.eventQueue.dequeueOrWait(5);if(K)yield K}let X=await Q;for(let[K,V]of X.entries()){let B=$[K];if(V.status==="fulfilled"){let{result:G,isError:F}=V.value;B.result=G,B.isError=F}else B.result=`Task execution rejected: ${V.reason}`,B.isError=!0;if(!this.options.hasAssistantToolCallMessage(Z,B.toolCall.id))this.options.addAssistantMessageWithToolCalls(Z);yield{type:"tool_result",tool_call_id:B.toolCall.id,result:B.result,isError:B.isError,sessionId:Z.sessionId},this.options.addToolResultToHistory(Z,B)}}}class p0{hooks;constructor($){this.hooks=$??{}}async executePreToolUse($){let Z=this.hooks.preToolUse;if(!Z)return{allow:!0};return await Z($)}async executePostToolUse($,Z){let Y=this.hooks.postToolUse;if(!Y)return;await Y($,Z)}async executePostToolUseFailure($,Z){let Y=this.hooks.postToolUseFailure;if(!Y)return;await Y($,Z)}}class FY{options;toolEventQueue=[];constructor($){this.options=$}createToolExecutionContext($,Z){return{sessionId:$.sessionId,signal:Z,usage:$.usage,emitEvent:(Y)=>{this.toolEventQueue.push({...Y,sessionId:$.sessionId})}}}async executeToolCall($,Z,Y,W,J){e1(Y,`Tool execution: ${$.toolCall.function.name}`);let Q=W?new p0(W):void 0,X=$.toolCall.id,K=$.toolCall,V=K,B=(z)=>({sessionId:Z.sessionId,toolCall:z,toolContext:Z});if(J){if(!J.allow)return $.result="Tool execution blocked by PreToolUse hook",$.isError=!0,{type:"tool_result",tool_call_id:X,result:$.result,isError:!0,sessionId:Z.sessionId};if(J.modifiedToolCall)V={...J.modifiedToolCall,id:X,type:K.type}}else if(Q){let z=await Q.executePreToolUse(B(V));if(!z.allow)return $.result="Tool execution blocked by PreToolUse hook",$.isError=!0,{type:"tool_result",tool_call_id:X,result:$.result,isError:!0,sessionId:Z.sessionId};if(z.modifiedToolCall)V={...z.modifiedToolCall,id:X,type:K.type}}let G=this.options.tools?.get(V.function.name);if(!G)return $.result=`Tool not found: ${V.function.name}`,$.isError=!0,{type:"tool_result",tool_call_id:X,result:$.result,isError:!0,sessionId:Z.sessionId};let F;try{F=typeof V.function.arguments==="string"?V.function.arguments.trim()===""?{}:JSON.parse(V.function.arguments):V.function.arguments??{}}catch{F={}}try{if($.result=await G.execute(F,Z),$.isError=!1,Q)await Q.executePostToolUse(B(V),$.result);return{type:"tool_result",tool_call_id:X,result:$.result,sessionId:Z.sessionId}}catch(z){let N=z instanceof Error?z:Error(String(z));if($.result=N.message,$.isError=!0,Q)await Q.executePostToolUseFailure(B(V),N);return{type:"tool_result",tool_call_id:X,result:$.result,isError:!0,sessionId:Z.sessionId}}}async*handleToolCalls($,Z,Y){let W=$.pendingToolCalls.length,J=Y?.signal,Q=Y?.toolContextInput,X=Q?.approval,K=X?.decisions??{},V=(O)=>{return this.options.approvalHandler.shouldRequireApproval(X,O)},B=(O)=>{return $.messages.some((H)=>{if(!H||typeof H!=="object"||H.role!=="assistant")return!1;let j=H.tool_calls;return Array.isArray(j)&&j.some((S)=>S?.id===O)})},G=(O)=>{if(!B(O))this.options.addAssistantMessageWithToolCalls($)},F=(O)=>{return $.messages.some((H)=>H&&typeof H==="object"&&H.role==="tool"&&H.tool_call_id===O)},z=new Set,N=(O)=>{try{return typeof O.function.arguments==="string"?JSON.parse(O.function.arguments):O.function.arguments}catch(H){let j=H instanceof Error?H.message:String(H);return{_raw:O.function.arguments,_parseError:j}}},q=(O)=>{let H=[];for(let j=O;j<$.pendingToolCalls.length;j++){let S=$.pendingToolCalls[j];if(F(S.toolCall.id))continue;if(z.has(S.toolCall.id))continue;if(K[S.toolCall.id])continue;let b=this.options.tools?.get(S.toolCall.function.name),y=b?.riskLevel??"safe";if(b&&this.options.isToolDisabled(S.toolCall.function.name))continue;if(b&&this.options.isToolBlocked($,S.toolCall.function.name))continue;if(!b||!V(y))continue;z.add(S.toolCall.id),H.push({type:"tool_approval_requested",tool_call_id:S.toolCall.id,toolName:S.toolCall.function.name,riskLevel:y,args:N(S.toolCall),sessionId:$.sessionId})}return H};if($.metadata?.parallelMode===!0){let O=$.pendingToolCalls.filter((H)=>{let j=H.toolCall.function.name;return j==="Task"||j.endsWith("_Task")});if(O.length>1)yield*this.options.parallelTaskExecutor.executeTasksInParallel(O,$,Z),$.pendingToolCalls=$.pendingToolCalls.filter((H)=>!O.includes(H))}let A=this.options.checkpointManager.hasStore();for(let O=0;O<$.pendingToolCalls.length;O++){let H=$.pendingToolCalls[O];if(F(H.toolCall.id)){$.pendingToolCalls.splice(O,1),O--;continue}let j=H.toolCall.function.name,S=this.options.tools?.get(j),b=S?.riskLevel??"safe",y;if(Y?.hooks?.preToolUse){let M=new p0(Y.hooks),L=(u)=>({sessionId:$.sessionId,toolCall:u,toolContext:Z});if(y=await M.executePreToolUse(L(H.toolCall)),!y.allow){H.result="Tool execution blocked by PreToolUse hook",H.isError=!0,G(H.toolCall.id),yield{type:"tool_result",tool_call_id:H.toolCall.id,result:H.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,H),$.pendingToolCalls.splice(O,1),O--;let u=j1($,{agentName:this.options.agentName,phase:"tool_execution",status:`Tool blocked by preToolUse hook: ${j}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});await this.options.checkpointManager.saveCheckpoint(u);continue}}if(S&&this.options.isToolBlocked($,j)){let M=`Tool "${j}" is blocked by middleware`;H.result=`Tool execution skipped: ${M}`,H.isError=!0,G(H.toolCall.id),yield{type:"tool_skipped",tool_call_id:H.toolCall.id,toolName:j,reason:M,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:H.toolCall.id,result:H.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,H),$.pendingToolCalls.splice(O,1),O--;let L=j1($,{agentName:this.options.agentName,phase:"tool_execution",status:`Tool blocked: ${j}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});await this.options.checkpointManager.saveCheckpoint(L);continue}if(S&&this.options.isToolDisabled(j)){let M=`Tool "${j}" is disabled for this session`;H.result=`Tool execution skipped: ${M}`,H.isError=!0,G(H.toolCall.id),yield{type:"tool_skipped",tool_call_id:H.toolCall.id,toolName:j,reason:M,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:H.toolCall.id,result:H.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,H),$.pendingToolCalls.splice(O,1),O--;let L=j1($,{agentName:this.options.agentName,phase:"tool_execution",status:`Tool disabled: ${j}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});await this.options.checkpointManager.saveCheckpoint(L);continue}if(S&&V(b)){let M=K[H.toolCall.id];if(!M){$.stopReason="approval_required";for(let u of q(O))yield u;let L=j1($,{agentName:this.options.agentName,phase:"approval_pending",status:`Waiting for approval: ${j}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});throw await this.options.checkpointManager.saveCheckpoint(L),yield{type:"requires_action",kind:"tool_approval",checkpoint:A?void 0:L,checkpointRef:A?{sessionId:L.sessionId}:void 0,sessionId:$.sessionId},await this.options.persistSessionState($),yield{type:"done",finalResponse:$.currentResponse,stopReason:"approval_required",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId},new V0}if(!M.approved){let L=M.reason??"User denied approval";H.result=`Tool execution skipped: ${L}`,H.isError=!0,G(H.toolCall.id),yield{type:"tool_skipped",tool_call_id:H.toolCall.id,toolName:H.toolCall.function.name,reason:L,sessionId:$.sessionId},yield{type:"tool_result",tool_call_id:H.toolCall.id,result:H.result,isError:!0,sessionId:$.sessionId},this.options.addToolResultToHistory($,H),$.pendingToolCalls.splice(O,1),O--;let u=j1($,{agentName:this.options.agentName,phase:"tool_execution",status:`Tool approval rejected: ${j}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});await this.options.checkpointManager.saveCheckpoint(u);continue}}G(H.toolCall.id),this.toolEventQueue=[];let k=await this.executeToolCall(H,Z,J,Y?.hooks,y);for(let M of this.toolEventQueue)yield M;this.toolEventQueue=[];let D=k.type==="tool_result"&&(k.isError||k.result&&typeof k.result==="object"&&k.result.isError===!0);if(S&&S.name==="AskUserQuestion"&&D){let M=Q?.askUser?.answers?.[H.toolCall.id];if(!M){yield k,$.stopReason="approval_required";let u=(typeof H.toolCall.function.arguments==="string"?JSON.parse(H.toolCall.function.arguments):H.toolCall.function.arguments)?.questions||[],l=j1($,{agentName:this.options.agentName,phase:"approval_pending",status:`Waiting for user answers: ${S.name}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});throw await this.options.checkpointManager.saveCheckpoint(l),await this.options.persistSessionState($),yield{type:"requires_action",kind:"ask_user",toolCallId:H.toolCall.id,questions:u,checkpoint:A?void 0:l,checkpointRef:A?{sessionId:l.sessionId}:void 0,sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"approval_required",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId},new V0}else{let u={...typeof H.toolCall.function.arguments==="string"?JSON.parse(H.toolCall.function.arguments):H.toolCall.function.arguments,answers:M};H.toolCall.function.arguments=JSON.stringify(u),this.toolEventQueue=[];let l=await this.executeToolCall(H,Z,J,Y?.hooks,y);for(let U of this.toolEventQueue)yield U;this.toolEventQueue=[],yield l,this.options.addToolResultToHistory($,H),$.pendingToolCalls.splice(O,1),O--;let f=j1($,{agentName:this.options.agentName,phase:"tool_execution",status:H.isError?`AskUser error: ${S.name}`:`AskUser completed: ${S.name}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});await this.options.checkpointManager.saveCheckpoint(f);continue}}yield k,this.options.addToolResultToHistory($,H),$.pendingToolCalls.splice(O,1),O--;let I=j1($,{agentName:this.options.agentName,phase:"tool_execution",status:H.isError?`Tool error: ${j}`:`Tool completed: ${j}`,modelConfig:Y?.checkpointModelConfig,requestParams:Y?.requestParams});await this.options.checkpointManager.saveCheckpoint(I)}$.pendingToolCalls=[],$.iteration++,yield{type:"iteration_end",iteration:$.iteration-1,willContinue:!0,toolCallCount:W,usage:{...$.usage},sessionId:$.sessionId}}}class v8{static APPROVAL_REQUIRED_LEVELS=new Set(["high","critical"]);requiresApproval($){return v8.APPROVAL_REQUIRED_LEVELS.has($)}shouldRequireApproval($,Z){if($?.autoApprove===!0)return!1;if(($?.strategy??"high_risk")==="all")return!0;return this.requiresApproval(Z)}}class qY{stateStore;constructor($){this.stateStore=$}hasStore(){return Boolean(this.stateStore)}async saveCheckpoint($){if(!this.stateStore)return;await this.stateStore.saveCheckpoint($)}async loadCheckpoint($){return this.stateStore?.loadCheckpoint($)}async clearCheckpoint($){if(!this.stateStore)return;await this.stateStore.deleteCheckpoint($)}}class UY{saveHandler;onError;constructor($,Z){this.saveHandler=$;this.onError=Z}async trigger(){try{await this.saveHandler()}catch($){let Z=$ instanceof Error?$:Error(String($));console.warn("[Session] Auto-save failed:",Z.message),this.onError?.(Z)}}}var EX=100;function _X($){if(!$)return;if($ instanceof Q1)return{code:$.code,message:$.message,status:$.status,retryable:$.retryable};if($ instanceof Error){let Z=$,Y=typeof Z.code==="string"?Z.code:void 0,W=typeof Z.status==="number"?Z.status:void 0,J=typeof Z.retryable==="boolean"?Z.retryable:void 0;return{code:Y,message:$.message,status:W,retryable:J}}return{message:String($)}}function s9($){let Z=$?.function?.arguments;if(typeof Z==="string")try{return JSON.parse(Z),$}catch(Y){let W=Y instanceof Error?Y.message:String(Y);return{...$,function:{...$.function,arguments:JSON.stringify({_raw:Z,_parseError:W})}}}if(Z&&typeof Z==="object")return{...$,function:{...$.function,arguments:JSON.stringify(Z)}};return{...$,function:{...$.function,arguments:JSON.stringify(Z??null)}}}function o9($){let Z=!1,Y=$.map((W)=>{if(!W||typeof W!=="object"||W.role!=="assistant")return W;let J=W.tool_calls;if(!Array.isArray(J)||J.length===0)return W;let Q=!1,X=J.map((K)=>{let V=s9(K);if(V!==K)Q=!0;return V});if(!Q)return W;return Z=!0,{...W,tool_calls:X}});return Z?Y:$}class R1 extends LX{id;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;_checkpointManager;_approvalHandler;_parallelTaskExecutor;_toolExecutor;_autoSave;_autoSaveManager;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_hasCheckpoint;_checkpointRestored=!1;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;_emitSessionCreatedEvent;_sessionCreatedEventEmitted=!1;getDisabledToolNames(){let $=this.configOverride?.disabledTools;if(!$||$.length===0)return new Set;return new Set($)}isToolDisabled($){return this.getDisabledToolNames().has($)}collectBlockedTools($){let Z=new Set;for(let Y of this._middlewares)if(typeof Y.__getBlockedTools==="function"){let W=Y.__getBlockedTools($);(Array.isArray(W)?W:Array.from(W)).forEach((Q)=>Z.add(Q))}return Z}isToolBlocked($,Z){let Y=$.metadata?.blockedTools;if(!Y)return!1;if(Y instanceof Set)return Y.has(Z);if(Array.isArray(Y))return Y.includes(Z);return!1}getToolsForModel($){let Z=this._tools?.toOpenAIFormat();if(!Z||Z.length===0)return;let Y=this.getDisabledToolNames(),W=Y.size===0?Z:Z.filter((Q)=>!Y.has(Q.function.name)),J=$.metadata?.blockedTools;if(J&&J.size>0)W=W.filter((Q)=>!J.has(Q.function.name));return W.length>0?W:void 0}getEffectiveSystemPrompt(){let $=this.configOverride?.systemPromptOverride;if(typeof $==="string")return $;return this._systemPrompt}constructor($,Z,Y,W){super();if(this._stateStore=$,this._checkpointManager=new qY($),this._approvalHandler=new v8,this.id=Z,Y)this.createdAt=Y.createdAt,this.restoreFromSnapshot(Y);else{let J=Date.now();this.createdAt=J,this.status="active",this.updatedAt=J,this.lastActiveAt=J,this.messages=[],this.toolCallCount=0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._autoSaveManager=new UY(()=>this.save(),(J)=>{this.emit("auto-save-failed",{error:J})}),this._modelClient=W?.modelClient,this._tools=W?.tools,this._middlewares=W?.middlewares??[],this._systemPrompt=W?.systemPrompt,this._agentName=W?.agentName,this._onUsage=W?.onUsage,this._hasCheckpoint=W?.hasCheckpoint??!1,this._hooks=W?.hooks,this._modelOverride=W?.model,this._maxIterations=W?.maxIterations,this._requestParams=W?.requestParams,this._emitSessionCreatedEvent=W?.emitSessionCreatedEvent===!0,this._parallelTaskExecutor=new BY(this._tools,{hasAssistantToolCallMessage:(J,Q)=>this.hasAssistantToolCallMessage(J,Q),addAssistantMessageWithToolCalls:(J)=>this.addAssistantMessageWithToolCalls(J),addToolResultToHistory:(J,Q)=>this.addToolResultToHistory(J,Q)}),this._toolExecutor=new FY({tools:this._tools,agentName:this._agentName,approvalHandler:this._approvalHandler,checkpointManager:this._checkpointManager,parallelTaskExecutor:this._parallelTaskExecutor,isToolDisabled:(J)=>this.isToolDisabled(J),isToolBlocked:(J,Q)=>this.isToolBlocked(J,Q),addAssistantMessageWithToolCalls:(J)=>this.addAssistantMessageWithToolCalls(J),addToolResultToHistory:(J,Q)=>this.addToolResultToHistory(J,Q),persistSessionState:(J)=>this.persistSessionState(J)})}get hasCheckpoint(){return this._hasCheckpoint}send($,Z){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error("Cannot send while receiving messages");if(this._pendingInput)throw Error("Pending input already exists; call receive() to consume it before sending another message");this._pendingInput={input:$,options:Z}}async*receive($){if(this._isReceiving)throw Error("Cannot receive concurrently");if(!this._hasCheckpoint&&!this._pendingInput)throw Error("Nothing to receive; call send() first (or resume from a session that has a checkpoint)");this._isReceiving=!0;try{if(this._emitSessionCreatedEvent&&!this._sessionCreatedEventEmitted)this._sessionCreatedEventEmitted=!0,yield{type:"session_created",sessionId:this.id};if(!this._hasCheckpoint&&this._pendingInput&&this._stateStore)try{let Z=await this._checkpointManager.loadCheckpoint(this.id);if(Z&&Array.isArray(Z.pendingToolCalls)&&Z.pendingToolCalls.length>0)this._hasCheckpoint=!0,this._checkpointRestored=!1}catch{}if(this._hasCheckpoint&&!this._checkpointRestored&&this._pendingInput){let{input:Z,options:Y}=this._pendingInput;this._pendingInput=null;let W=await this._checkpointManager.loadCheckpoint(this.id);if(!W)throw Error(`Checkpoint not found for sessionId: ${this.id}`);let J=k$(W);if(J.sessionId!==this.id)J.sessionId=this.id;J.metadata={...J.metadata,_pendingUserInput:Z};let Q=this._requestParams??W.requestParams,X=Y??$;yield*this._streamWithState(J,{maxIterations:this._maxIterations,signal:X?.signal,model:this.getRuntimeModelOverride(),toolContext:X?.toolContext,hooks:this._hooks,requestParams:Q}),await this._finalizeRun(J,Date.now()),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(this._hasCheckpoint&&!this._checkpointRestored){let Z=$??this._pendingInput?.options;if(yield*this._stream(void 0,Z),!this._pendingInput)return}if(this._pendingInput){let{input:Z,options:Y}=this._pendingInput;this._pendingInput=null,yield*this._stream(Z,Y)}}finally{this._isReceiving=!1}}async*receiveWithApprovals($,Z){if(!this._hasCheckpoint&&this._stateStore)try{let J=await this._checkpointManager.loadCheckpoint(this.id);if(J&&Array.isArray(J.pendingToolCalls)&&J.pendingToolCalls.length>0)this._hasCheckpoint=!0,this._checkpointRestored=!1}catch{}let Y=Z?.toolContext,W={...Y??{},approval:{...Y?.approval??{},decisions:{...Y?.approval?.decisions??{},...$}}};yield*this.receive({...Z,toolContext:W})}async*_stream($,Z){this._ensureRuntimeConfigured($!==void 0);let Y=Date.now(),W=this.getRuntimeModelOverride(),J;if(this._hasCheckpoint&&!this._checkpointRestored){let X=await this._checkpointManager.loadCheckpoint(this.id);if(!X)throw Error(`Checkpoint not found for sessionId: ${this.id}`);if(J=k$(X),J.sessionId!==this.id)J.sessionId=this.id;let K=this._requestParams??X.requestParams;yield*this._streamWithState(J,{maxIterations:this._maxIterations,signal:Z?.signal,model:W,toolContext:Z?.toolContext,hooks:this._hooks,requestParams:K}),await this._finalizeRun(J,Y),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if($===void 0)throw Error("Input is required to stream");if(!this.title&&this.messages.length===0){let X=this.extractTextFromContent($);if(X)this.title=this.createTitle(X)}let Q=this.messages.filter((X)=>X.role!=="system");J=W8({sessionId:this.id,input:$,messages:Q},this.getEffectiveSystemPrompt()??""),yield*this._streamWithState(J,{maxIterations:this._maxIterations,signal:Z?.signal,model:W,toolContext:Z?.toolContext,hooks:this._hooks,requestParams:this._requestParams}),await this._finalizeRun(J,Y)}resolveModelRef($){if($.provider)return{provider:$.provider,modelId:$.modelId};let Y=(this._modelClient?.modelRefs??[]).find((J)=>J.modelId===$.modelId);if(Y)return Y;let W=this._modelClient?.modelRef?.provider;if(W)return{provider:W,modelId:$.modelId};return}getRuntimeModelOverride(){if(this.configOverride?.model){let $=this.resolveModelRef(this.configOverride.model);if($)return $}return this._modelOverride}_ensureRuntimeConfigured($){if(!this._modelClient)throw Error("Session is not configured with a model client");if($&&this.getEffectiveSystemPrompt()===void 0)throw Error("Session is not configured with a system prompt")}extractTextFromContent($){if(typeof $==="string")return $;if(Array.isArray($))return $.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(" ");if($&&typeof $==="object"&&$.type==="text")return $.text||"";return""}createTitle($,Z=50){let Y=$.trim();if(Y.length<=Z)return Y;return`${Y.substring(0,Z).trim()}...`}_recordUsage($){if(this._onUsage)this._onUsage($)}async executeModelStream($,Z,Y,W,J){if(!this._modelClient)throw Error("Session is not configured with a model client");let Q=[],X=$.sessionId,K=new Map,V=!1,B=!1,G=(H)=>{let j=K.get(H);if(j)return j;let S={argsText:"",started:!1};return K.set(H,S),S},F=(H,j)=>{let S=G(H);if(j&&!S.toolName)S.toolName=j;if(!S.started)S.started=!0,Q.push({type:"tool_call_start",callId:H,toolName:S.toolName,sessionId:X})},z=(H,j,S)=>{let b=G(H);if(j&&!b.toolName)b.toolName=j;if(typeof S==="string"&&S.length>0)b.argsText+=S;F(H,b.toolName),Q.push({type:"tool_call_delta",callId:H,toolName:b.toolName,argsTextDelta:S,sessionId:X})},N=()=>{if(V)return;V=!0,Q.push({type:"text_start",sessionId:X})},q=()=>{if(!V||B)return;B=!0,Q.push({type:"text_end",content:$.currentResponse,sessionId:X})},w=()=>{for(let[H,j]of K){if(!j.toolName)continue;let S={id:H,type:"function",function:{name:j.toolName,arguments:j.argsText}};if(this._tools)$.pendingToolCalls.push({toolCall:S});Q.push({type:"tool_call_end",toolCall:S,sessionId:X})}K.clear()},A=(()=>{if(!J)return;let H={...J};if(typeof H.maxOutputTokens!=="number"&&typeof J.maxTokens==="number")H.maxOutputTokens=J.maxTokens;return delete H.maxTokens,H})(),O=W?{model:W,messages:o9($.messages),tools:Y,signal:Z,...A??{}}:{messages:o9($.messages),tools:Y,signal:Z,...A??{}};try{for await(let H of this._modelClient.stream(O))if(e1(Z,"Session streaming"),H.type==="delta"){if(H.chunk.kind==="text")N(),$.currentResponse+=H.chunk.text,Q.push({type:"text_delta",delta:H.chunk.text,sessionId:X});else if(H.chunk.kind==="thinking_start")Q.push({type:"thinking_start",sessionId:X});else if(H.chunk.kind==="thinking_delta")$.currentThinking=($.currentThinking??"")+H.chunk.text,Q.push({type:"thinking_delta",delta:H.chunk.text,sessionId:X});else if(H.chunk.kind==="thinking_end"){let j=typeof H.chunk.text==="string"?H.chunk.text:"";if(j&&typeof $.currentThinking!=="string")$.currentThinking=j;let S=typeof $.currentThinking==="string"?$.currentThinking:j;Q.push({type:"thinking_end",sessionId:X,...S?{content:S}:{}})}else if(H.chunk.kind==="tool_call_delta")z(H.chunk.callId,H.chunk.toolId,H.chunk.argsTextDelta)}else if(H.type==="response_end"){q(),w(),$.lastModelStopReason=H.stopReason;let j=H.usage;if(j&&typeof j==="object"){let S=j;if(S.prompt_tokens||S.completion_tokens||S.total_tokens){let b={promptTokens:S.prompt_tokens??0,completionTokens:S.completion_tokens??0,totalTokens:S.total_tokens??0};$.usage.promptTokens+=b.promptTokens,$.usage.completionTokens+=b.completionTokens,$.usage.totalTokens+=b.totalTokens,this._recordUsage(b)}}}else if(H.type==="error"){if(H.terminal!==!1){let j=H.error?.code??"model_error",S=H.error?.message??"Model error",b=new Q1(S,{code:j,retryable:H.error?.retryable});$.error=b,$.shouldContinue=!1,$.stopReason="error"}}}catch(H){if(H instanceof T0)throw H;if(Z?.aborted)throw new T0(typeof Z?.reason==="string"?Z.reason:"Agent execution aborted");$.error=H instanceof Error?H:Error(String(H)),$.shouldContinue=!1,$.stopReason="error"}finally{if(q(),K.size>0)w()}return Q}mergeStateResults($,Z){$.currentResponse=Z.currentResponse,$.currentThinking=Z.currentThinking,$.pendingToolCalls=Z.pendingToolCalls,$.usage=Z.usage,$.metadata=Z.metadata,$.shouldContinue=Z.shouldContinue,$.stopReason=Z.stopReason,$.messages=Z.messages}addToolResultToHistory($,Z){let Y=Z.result,W,J=Z.isError;if(typeof Y==="string")W=Y;else if(Y&&typeof Y==="object"&&"content"in Y){let Q=Y;if(W=JSON.stringify(Q.content),Q.isError===!0)J=!0}else W=JSON.stringify(Y);$.messages.push({role:"tool",tool_call_id:Z.toolCall.id,content:W,...J?{isError:!0}:{}})}addAssistantMessageWithToolCalls($){let Z=typeof $.currentThinking==="string"?$.currentThinking:void 0;$.messages.push({role:"assistant",content:$.currentResponse||"",tool_calls:$.pendingToolCalls.map((Y)=>s9(Y.toolCall)),...Z&&Z.length>0?{reasoning_content:Z}:{}})}addFinalAssistantMessage($){if($.currentResponse)$.messages.push({role:"assistant",content:$.currentResponse})}async persistSessionState($){this.messages=$.messages.filter((Z)=>Z.role!=="system"),await this.save()}async*_streamWithState($,Z){let Y=Z.maxIterations??EX,W=Z.signal,J=Y8(this._middlewares),Q=this._toolExecutor.createToolExecutionContext($,W),X=this._stateStore,K=X?.savePoint??"before",V=X?.deleteOnComplete??!0,B=Z.model?{modelId:Z.model.modelId,provider:Z.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0;while($.shouldContinue){if(e1(W,`Session iteration ${$.iteration}`),$.iteration>=Y){$.shouldContinue=!1,$.stopReason="max_iterations",yield{type:"done",finalResponse:$.currentResponse,stopReason:"max_iterations",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId};break}if(yield{type:"iteration_start",iteration:$.iteration,sessionId:$.sessionId},$.pendingToolCalls.length>0){try{yield*this._toolExecutor.handleToolCalls($,Q,{signal:W,toolContextInput:Z.toolContext,hooks:Z.hooks,checkpointModelConfig:B,requestParams:Z.requestParams})}catch(z){if(z instanceof V0){this._hasCheckpoint=!0,this._checkpointRestored=!1;return}throw z}if($.metadata?._pendingUserInput){let z=$.metadata._pendingUserInput;delete $.metadata._pendingUserInput,$.messages.push({role:"user",content:z})}continue}if($.currentResponse="",$.currentThinking=void 0,$.pendingToolCalls=[],$.lastModelStopReason=void 0,X&&(K==="before"||K==="both")){let z=j1($,{agentName:this._agentName,modelConfig:B,requestParams:Z.requestParams});await X.saveCheckpoint(z)}let G=[],F=await J($,async(z)=>{e1(W,"Session model call");let N=this.collectBlockedTools(z);z.metadata.blockedTools=N;let q=this.getToolsForModel(z);return G=await this.executeModelStream(z,W,q,Z.model,Z.requestParams),z});if(this.mergeStateResults($,F),X&&(K==="after"||K==="both")){let z=j1($,{agentName:this._agentName,modelConfig:B,requestParams:Z.requestParams});await X.saveCheckpoint(z)}for(let z of G)yield z;if(e1(W,`Session iteration ${$.iteration}`),$.stopReason==="error"){yield{type:"iteration_end",iteration:$.iteration,willContinue:!1,toolCallCount:$.pendingToolCalls.length,usage:{...$.usage},sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"error",modelStopReason:$.lastModelStopReason,error:_X($.error),usage:{...$.usage},sessionId:$.sessionId};break}if($.pendingToolCalls.length>0)try{yield*this._toolExecutor.handleToolCalls($,Q,{signal:W,toolContextInput:Z.toolContext,hooks:Z.hooks,checkpointModelConfig:B,requestParams:Z.requestParams})}catch(z){if(z instanceof V0){this._hasCheckpoint=!0,this._checkpointRestored=!1;return}throw z}else yield*this.handleFinalResponse($);if(!$.shouldContinue){if(X&&V)await X.deleteCheckpoint($.sessionId);break}}}hasAssistantToolCallMessage($,Z){return $.messages.some((Y)=>{if(!Y||typeof Y!=="object"||Y.role!=="assistant")return!1;let W=Y.tool_calls;return Array.isArray(W)&&W.some((J)=>J?.id===Z)})}async*handleFinalResponse($){$.shouldContinue=!1,$.stopReason="final_response",this.addFinalAssistantMessage($),yield{type:"iteration_end",iteration:$.iteration,willContinue:!1,toolCallCount:0,usage:{...$.usage},sessionId:$.sessionId},yield{type:"done",finalResponse:$.currentResponse,stopReason:"final_response",modelStopReason:$.lastModelStopReason,usage:{...$.usage},sessionId:$.sessionId}}async _finalizeRun($,Z){if(this.messages=$.messages.filter((W)=>W.role!=="system"),$.usage.totalTokens>0)this.addUsage($.usage);let Y=Date.now()-Z;this.recordResponse(Y),await this.save()}getLastMessagePreview($=100){if(this.messages.length===0)return;let Z=this.messages[this.messages.length-1],Y=typeof Z.content==="string"?Z.content:JSON.stringify(Z.content);return Y.length>$?`${Y.substring(0,$)}...`:Y}toSnapshot(){let $={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},Z={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},Y={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:$,configOverride:this.configOverride?{...this.configOverride}:void 0,context:Z,stats:Y}}restoreFromSnapshot($){this.status=$.state.status,this.updatedAt=$.state.updatedAt,this.lastActiveAt=$.state.lastActiveAt,this.title=$.state.title,this.errorMessage=$.state.errorMessage,this.configOverride=$.configOverride?{...$.configOverride}:void 0,this.messages=[...$.context.messages],this.toolCallCount=$.context.toolCallCount,this.usage={...$.stats.usage},this.responseCount=$.stats.responseCount,this.avgResponseTime=$.stats.avgResponseTime}async save(){let $=this.toSnapshot();await this._stateStore.save(this.id,L1.SESSION,$)}async load(){let $=await this._stateStore.load(this.id,L1.SESSION);if($)return this.restoreFromSnapshot($),!0;return!1}triggerAutoSave(){this._autoSaveManager.trigger()}setStatus($,Z){if(this.status=$,this.errorMessage=Z,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}markActive(){if(this.lastActiveAt=Date.now(),this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}addMessage($){if(this.messages.push($),this.markActive(),this._autoSave)this.triggerAutoSave()}addUsage($){if(this.usage.promptTokens+=$.promptTokens,this.usage.completionTokens+=$.completionTokens,this.usage.totalTokens+=$.totalTokens,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}recordResponse($){let Z=(this.avgResponseTime??0)*this.responseCount;if(this.responseCount++,this.avgResponseTime=(Z+$)/this.responseCount,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}incrementToolCallCount(){if(this.toolCallCount++,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}setModelOverride($){if(!this.configOverride)this.configOverride={};if(this.configOverride.model=$,this.updatedAt=Date.now(),this._modelOverride=this.resolveModelRef($)??this._modelOverride,this._autoSave)this.triggerAutoSave()}clearModelOverride(){if(this.configOverride)delete this.configOverride.model,this.updatedAt=Date.now();if(this._modelOverride=void 0,this._autoSave)this.triggerAutoSave()}setSystemPromptOverride($){if(!this.configOverride)this.configOverride={};if(this.configOverride.systemPromptOverride=$,this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}clearSystemPromptOverride(){if(this.configOverride)delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now();if(this._autoSave)this.triggerAutoSave()}disableTools($){if(!this.configOverride)this.configOverride={};if(this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...$],this.updatedAt=Date.now(),this._autoSave)this.triggerAutoSave()}enableAllTools(){if(this.configOverride)delete this.configOverride.disabledTools,this.updatedAt=Date.now();if(this._autoSave)this.triggerAutoSave()}setMiddlewares($){this._middlewares=$}setAutoSave($){this._autoSave=$}}class bZ{}import{randomUUID as OX}from"crypto";class h8 extends bZ{_stateStore;constructor($){super();this._stateStore=$}async create($){let Z=$??OX(),Y=Date.now(),W={id:Z,createdAt:Y,state:{status:"active",updatedAt:Y,lastActiveAt:Y},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0}},J=new R1(this._stateStore,Z,W);return await J.save(),J}async get($){let Z=await this._stateStore.load($,L1.SESSION);if(!Z)return;return new R1(this._stateStore,$,Z)}async list(){let $=await this._stateStore.listSessions(),Z=[];for(let Y of $){let W=await this._stateStore.load(Y,L1.SESSION);if(W){let J=new R1(this._stateStore,Y,W);Z.push(J)}}return Z}async destroy($){await this._stateStore.deleteSession($)}}import{existsSync as E0,mkdirSync as t9,readdirSync as HY,readFileSync as DX,rmSync as NY,writeFileSync as jX}from"fs";import n0 from"path";class i0{savePoint;deleteOnComplete;constructor($){this.savePoint=$?.savePoint??"before",this.deleteOnComplete=$?.deleteOnComplete??!0}assertValidStorageSegment($,Z){if(!Z)throw Error(`${$} must be a non-empty string`);if(Z==="."||Z==="..")throw Error(`${$} must not be "." or ".."`);if(Z.includes("/")||Z.includes("\\"))throw Error(`${$} must not contain path separators`);if(Z.includes("\x00"))throw Error(`${$} must not contain NUL bytes`)}async save($,Z,Y){let W=this.buildPath($,Z),J=JSON.stringify(Y,null,2);await this._write(W,J)}async load($,Z){let Y=this.buildPath($,Z),W=await this._read(Y);if(W===void 0)return;try{return JSON.parse(W)}catch{return}}async delete($,Z){let Y=this.buildPath($,Z);await this._delete(Y)}async deleteSession($){let Z=this.buildPrefix($),Y=await this._list(Z);await Promise.all(Y.map((W)=>this._delete(W)))}async listKeys($){let Z=this.buildPrefix($);return(await this._list(Z)).map((W)=>this.extractKey($,W))}async exists($,Z){let Y=this.buildPath($,Z);return this._exists(Y)}async saveCheckpoint($){let Z={_meta:{description:"GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY",savedAt:new Date().toISOString(),agentName:$.agentName,sessionId:$.sessionId,iteration:$.iteration,phase:$.phase,status:$.status,messageCount:$.messages.length,toolCallsPending:$.pendingToolCalls?.length??0},checkpoint:$};await this.save($.sessionId,L1.CHECKPOINT,Z)}async loadCheckpoint($){return(await this.load($,L1.CHECKPOINT))?.checkpoint}async deleteCheckpoint($){await this.delete($,L1.CHECKPOINT)}async listCheckpoints(){let $=await this.listSessions(),Z=[];for(let Y of $){let W=await this.loadCheckpoint(Y);if(W)Z.push(W)}return Z}async listSessions(){let $=await this._list(""),Z=new Set;for(let Y of $){let W=this.extractSessionId(Y);if(W)Z.add(W)}return Array.from(Z)}buildPath($,Z){return this.assertValidStorageSegment("sessionId",$),this.assertValidStorageSegment("key",Z),`${$}/${Z}`}buildPrefix($){return this.assertValidStorageSegment("sessionId",$),`${$}/`}extractKey($,Z){let Y=this.buildPrefix($);return Z.startsWith(Y)?Z.slice(Y.length):Z}extractSessionId($){let Z=$.split("/");return Z.length>0?Z[0]:void 0}}class MY extends i0{baseDir;constructor($){super($);this.baseDir=n0.resolve($.dir),this.ensureDir(this.baseDir)}async _write($,Z){let Y=this.toFilePath($);this.ensureDir(n0.dirname(Y)),jX(Y,Z,"utf-8")}async _read($){let Z=this.toFilePath($);try{if(!E0(Z))return;return DX(Z,"utf-8")}catch{return}}async _delete($){let Z=this.toFilePath($);if(E0(Z))NY(Z);let Y=n0.dirname(Z);if(E0(Y))try{if(HY(Y).length===0)NY(Y,{recursive:!0})}catch{}}async _exists($){let Z=this.toFilePath($);return E0(Z)}async _list($){let Z=[];if(!E0(this.baseDir))return Z;let Y=HY(this.baseDir,{withFileTypes:!0}).filter((W)=>W.isDirectory()).map((W)=>W.name);for(let W of Y){if($&&!W.startsWith($.split("/")[0]))continue;let J=n0.join(this.baseDir,W),Q=this.listJsonFiles(J);for(let X of Q){let K=n0.basename(X,".json"),V=`${W}/${K}`;if(!$||V.startsWith($))Z.push(V)}}return Z}toFilePath($){return n0.join(this.baseDir,`${$}.json`)}ensureDir($){if(!E0($))t9($,{recursive:!0})}listJsonFiles($){if(!E0($))return[];return HY($).filter((Z)=>Z.endsWith(".json")).map((Z)=>n0.join($,Z))}getBaseDir(){return this.baseDir}clear(){if(E0(this.baseDir))NY(this.baseDir,{recursive:!0}),t9(this.baseDir,{recursive:!0})}}class vZ extends i0{store=new Map;constructor($){super($)}async _write($,Z){this.store.set($,Z)}async _read($){return this.store.get($)}async _delete($){this.store.delete($)}async _exists($){return this.store.has($)}async _list($){let Z=[];for(let Y of this.store.keys())if($===""||Y.startsWith($))Z.push(Y);return Z}clear(){this.store.clear()}stats(){let $=new Set;for(let Z of this.store.keys()){let Y=this.extractSessionId(Z);if(Y)$.add(Y)}return{entryCount:this.store.size,sessionCount:$.size}}}class hZ{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];_middlewareCounter=0;_middlewareTools=new Map;constructor($){this.id=$.id??crypto.randomUUID(),this.name=$.name,this.systemPrompt=$.systemPrompt,this.createdAt=Date.now(),this._model=$.model,this._tools=$.tools,this._stateStore=$.stateStore??new vZ({savePoint:"before"}),this._sessionManager=new h8(this._stateStore);let Z=$.middleware??[];for(let Y of Z)this.use(Y)}get model(){return this._model}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get modelRefs(){let $=this._model.modelRefs;if(Array.isArray($))return $;let Z=this._model.modelRef;return Z?[Z]:[]}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession($){if(!this._sessionManager)throw Error("SessionManager is not configured");let Z=await this._sessionManager.create($?.sessionId);if(!this._stateStore)throw Error("StateStore is required to create sessions");let Y=Z.toSnapshot();return new R1(this._stateStore,Z.id,Y,{...$,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map((W)=>W.fn),hasCheckpoint:!1,emitSessionCreatedEvent:!0})}async resumeSession($,Z){if(!this._sessionManager)throw Error("SessionManager is not configured");let Y=await this._sessionManager.get($);if(!Y)throw Error(`Session not found: ${$}`);let W=Boolean(await this._stateStore?.loadCheckpoint($));if(!this._stateStore)throw Error("StateStore is required to resume sessions");console.warn(`[Agent] Resuming session ${$} with checkpoint: ${W}`);let J=Y.toSnapshot();return new R1(this._stateStore,Y.id,J,{...Z,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map((Q)=>Q.fn),hasCheckpoint:W,emitSessionCreatedEvent:!1})}use($,Z){let Y=Z??$.__middlewareName??`middleware_${this._middlewareCounter++}`;if(this._middlewares.some((J)=>J.name===Y))throw Error(`Middleware with name "${Y}" already exists`);let W={name:Y,fn:$};if(this._middlewares.push(W),$.__createTools&&typeof $.__createTools==="function")this._registerMiddlewareTools(Y,$.__createTools);return()=>{this.removeMiddleware(Y)}}removeMiddleware($){let Z=-1,Y;if(typeof $==="string")Z=this._middlewares.findIndex((W)=>W.name===$),Y=$;else if(Z=this._middlewares.findIndex((W)=>W.fn===$),Z>-1)Y=this._middlewares[Z].name;if(Z>-1&&Y)return this._unregisterMiddlewareTools(Y),this._middlewares.splice(Z,1),!0;return!1}clearMiddlewares(){for(let $ of this._middlewareTools.keys())this._unregisterMiddlewareTools($);this._middlewares=[]}get middlewares(){return[...this._middlewares]}get middlewareNames(){return this._middlewares.map(($)=>$.name)}setModel($){if(((Y)=>{return Boolean(Y&&typeof Y==="object"&&typeof Y.provider==="string"&&typeof Y.modelId==="string"&&typeof Y.stream!=="function")})($))this._modelOverride=$;else this._model=$,this._modelOverride=void 0}_getNamespacedToolName($,Z){return`${$}_${Z}`}_registerMiddlewareTools($,Z){if(!this._tools)return;let Y=Z(),W=[];for(let J of Y){let Q=this._getNamespacedToolName($,J.name),X=Object.create(Object.getPrototypeOf(J));Object.assign(X,J),Object.defineProperty(X,"name",{value:Q,writable:!1,configurable:!0});try{this._tools.register(X),W.push(Q)}catch(K){console.warn(`Failed to register tool ${Q}:`,K)}}if(W.length>0)this._middlewareTools.set($,W)}_unregisterMiddlewareTools($){if(!this._tools)return;let Z=this._middlewareTools.get($);if(!Z)return;for(let Y of Z)this._tools.unregister(Y);this._middlewareTools.delete($)}}import{execSync as q1}from"child_process";import{unlinkSync as fX,writeFileSync as TX}from"fs";import{tmpdir as PX}from"os";import{join as SX}from"path";function AX($){try{return q1("git rev-parse --git-dir",{cwd:$,stdio:"pipe"}),!0}catch{return!1}}function e9($){try{return q1("git add --all",{cwd:$,encoding:"utf-8"}),q1("git diff --staged --name-only",{cwd:$,encoding:"utf-8"}).trim().split(`
|
|
83
|
+
`).filter(Boolean)}catch(Z){throw Error(`Failed to stage files: ${Z instanceof Error?Z.message:String(Z)}`)}}function $5($){try{return q1("git diff --staged",{cwd:$,encoding:"utf-8"})}catch(Z){throw Error(`Failed to get diff: ${Z instanceof Error?Z.message:String(Z)}`)}}function wY($){try{return q1("git diff --staged --name-only",{cwd:$,encoding:"utf-8"}).trim().length>0}catch{return!1}}function Z5($){try{let Z=q1("git diff --staged --name-status",{cwd:$,encoding:"utf-8"});if(!Z.trim())return[];return Z.trim().split(`
|
|
84
|
+
`).filter(Boolean).map((Y)=>{let W=Y.split("\t"),J=W[0].charAt(0);if(J==="R"||J==="C")return{file:W[2],status:J,oldFile:W[1]};return{file:W[1],status:J}})}catch{return[]}}function LY($){try{if(q1("git diff --name-only",{cwd:$,encoding:"utf-8"}).trim().length>0)return!0;return q1("git ls-files --others --exclude-standard",{cwd:$,encoding:"utf-8"}).trim().length>0}catch{return!1}}function Y5($,Z){try{let Y=SX(PX(),`goatchain-commit-${Date.now()}.txt`);TX(Y,$,"utf-8");try{return q1(`git commit -F "${Y}"`,{cwd:Z,stdio:"pipe"}),q1("git rev-parse HEAD",{cwd:Z,encoding:"utf-8"}).trim()}finally{try{fX(Y)}catch{}}}catch(Y){throw Error(`Failed to create commit: ${Y instanceof Error?Y.message:String(Y)}`)}}function CX($){try{let Z=q1("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8"}).trim();return Z==="HEAD"?null:Z}catch{return null}}function xX($,Z="origin"){try{return q1("git remote",{cwd:$,encoding:"utf-8"}).split(`
|
|
85
|
+
`).map((W)=>W.trim()).includes(Z)}catch{return!1}}function RX($){try{return q1("git rev-parse --abbrev-ref --symbolic-full-name @{u}",{cwd:$,encoding:"utf-8"}).trim()||null}catch{return null}}function W5($,Z="origin"){try{return q1(`git fetch ${Z}`,{cwd:$,stdio:"pipe"}),!0}catch{return!1}}function yX($){try{let Z=q1("git rev-list --left-right --count @{u}...HEAD",{cwd:$,encoding:"utf-8"}).trim(),[Y,W]=Z.split(/\s+/).map((J)=>Number.parseInt(J,10));return{ahead:W||0,behind:Y||0,hasUpstream:!0}}catch{return{ahead:0,behind:0,hasUpstream:!1}}}function kX($){try{let Z=q1("git status --porcelain",{cwd:$,encoding:"utf-8"});return/^(?:UU|AA|DD|AU|UA|DU|UD)\s/m.test(Z)}catch{return!1}}function IX($){try{let Z=q1("git status --porcelain",{cwd:$,encoding:"utf-8"}),Y=[],W=Z.split(`
|
|
86
|
+
`);for(let J of W){let Q=J.match(/^(?:UU|AA|DD|AU|UA|DU|UD)\s+(\S.*)$/);if(Q)Y.push(Q[1].trim())}return Y}catch{return[]}}function bX($){try{try{return q1("git rev-parse --verify MERGE_HEAD",{cwd:$,stdio:"pipe"}),{inMerge:!0,type:"merge"}}catch{}try{return q1("test -d .git/rebase-merge -o -d .git/rebase-apply",{cwd:$,stdio:"pipe"}),{inMerge:!0,type:"rebase"}}catch{}try{return q1("git rev-parse --verify CHERRY_PICK_HEAD",{cwd:$,stdio:"pipe"}),{inMerge:!0,type:"cherry-pick"}}catch{}return{inMerge:!1,type:null}}catch{return{inMerge:!1,type:null}}}function EY($){let Z={canCommit:!0,isGitRepo:!1,hasChanges:!1,hasConflicts:!1,conflictFiles:[],inMergeState:!1,mergeStateType:null,hasRemote:!1,hasUpstream:!1,ahead:0,behind:0,isDiverged:!1,currentBranch:null,warnings:[],errors:[]};if(Z.isGitRepo=AX($),!Z.isGitRepo)return Z.canCommit=!1,Z.errors.push("Not a git repository"),Z;if(Z.currentBranch=CX($),!Z.currentBranch)Z.warnings.push("Detached HEAD state - no branch checked out");let Y=bX($);if(Z.inMergeState=Y.inMerge,Z.mergeStateType=Y.type,Z.inMergeState)Z.warnings.push(`Currently in ${Z.mergeStateType} state`);if(Z.hasConflicts=kX($),Z.hasConflicts)Z.conflictFiles=IX($),Z.canCommit=!1,Z.errors.push(`Unresolved conflicts in ${Z.conflictFiles.length} file(s): ${Z.conflictFiles.join(", ")}`);if(Z.hasChanges=LY($)||wY($),!Z.hasChanges&&!Z.inMergeState)Z.canCommit=!1,Z.errors.push("No changes to commit");if(Z.hasRemote=xX($),Z.hasRemote){let W=RX($);if(Z.hasUpstream=!!W,Z.hasUpstream){let J=yX($);if(Z.ahead=J.ahead,Z.behind=J.behind,Z.isDiverged=Z.ahead>0&&Z.behind>0,Z.behind>0)Z.warnings.push(`Local branch is ${Z.behind} commit(s) behind remote`);if(Z.isDiverged)Z.warnings.push(`Branch has diverged: ${Z.ahead} ahead, ${Z.behind} behind`)}else Z.warnings.push("No upstream branch configured")}return Z}var vX="You are a commit message generator. You print plain text without code blocks and don't talk.";function hX($,Z,Y){if(Y)return Y.replace("[DIFF_CONTENT]",$).replace("[LANGUAGE]",Z);return`Analyze the following staged diffs and craft a conventional commit message in ${Z}.
|
|
87
|
+
|
|
88
|
+
Staged Diffs:
|
|
89
|
+
\`\`\`diff
|
|
90
|
+
${$}
|
|
91
|
+
\`\`\`
|
|
92
|
+
|
|
93
|
+
Requirements:
|
|
94
|
+
- Title: Under 50 characters with appropriate type (feat/fix/docs/style/refactor/test/chore)
|
|
95
|
+
- Body: List changes in categories (Added/Changed/Fixed/Removed/etc.) with lines under 70 chars
|
|
96
|
+
- Format exactly as:
|
|
97
|
+
|
|
98
|
+
<type>[optional scope]: <title>
|
|
99
|
+
|
|
100
|
+
Added (if applicable):
|
|
101
|
+
- [New features/modules]
|
|
102
|
+
|
|
103
|
+
Changed (if applicable):
|
|
104
|
+
- [Modifications to existing functionality]
|
|
105
|
+
|
|
106
|
+
Fixed (if applicable):
|
|
107
|
+
- [Bug fixes]
|
|
108
|
+
|
|
109
|
+
Security (if applicable):
|
|
110
|
+
- [Security improvements]`}function _Y($){let Z=[];if($.errors.length>0)Z.push("\u274C \u9519\u8BEF (Errors):"),$.errors.forEach((Y)=>Z.push(` \u2022 ${Y}`));if($.warnings.length>0)Z.push("\u26A0\uFE0F \u8B66\u544A (Warnings):"),$.warnings.forEach((Y)=>Z.push(` \u2022 ${Y}`));if($.conflictFiles.length>0)Z.push(""),Z.push("\uD83D\uDD00 \u51B2\u7A81\u6587\u4EF6 (Conflict files):"),$.conflictFiles.forEach((Y)=>Z.push(` \u2022 ${Y}`));if($.inMergeState)Z.push(""),Z.push(`\uD83D\uDCCC \u5F53\u524D\u72B6\u6001: \u6B63\u5728\u8FDB\u884C ${$.mergeStateType}`);if($.hasUpstream&&($.ahead>0||$.behind>0)){if(Z.push(""),Z.push("\uD83D\uDCCA \u5206\u652F\u72B6\u6001:"),$.ahead>0)Z.push(` \u2022 \u9886\u5148\u8FDC\u7A0B ${$.ahead} \u4E2A\u63D0\u4EA4`);if($.behind>0)Z.push(` \u2022 \u843D\u540E\u8FDC\u7A0B ${$.behind} \u4E2A\u63D0\u4EA4`)}return Z.join(`
|
|
111
|
+
`)}function J5($){switch($){case"A":return"\u65B0\u589E (new file)";case"M":return"\u4FEE\u6539 (modified)";case"D":return"\u5220\u9664 (deleted)";case"R":return"\u91CD\u547D\u540D (renamed)";case"C":return"\u590D\u5236 (copied)";case"T":return"\u7C7B\u578B\u53D8\u66F4 (typechange)";case"U":return"\u672A\u5408\u5E76 (unmerged)";default:return $}}function gX($){if($.length===0)return"";let Z=["\uD83D\uDCCB Changes to be committed (\u5F85\u63D0\u4EA4\u7684\u66F4\u6539):",""],Y={};for(let J of $){let Q=J.status;if(!Y[Q])Y[Q]=[];Y[Q].push(J)}let W=["A","M","D","R","C","T","U"];for(let J of W){let Q=Y[J];if(!Q||Q.length===0)continue;Z.push(` ${J5(J)}:`);for(let X of Q)if(X.oldFile)Z.push(` \u2022 ${X.oldFile} \u2192 ${X.file}`);else Z.push(` \u2022 ${X.file}`);Z.push("")}for(let[J,Q]of Object.entries(Y)){if(W.includes(J))continue;Z.push(` ${J5(J)}:`);for(let X of Q)Z.push(` \u2022 ${X.file}`);Z.push("")}return Z.push(` \u5171 ${$.length} \u4E2A\u6587\u4EF6 (Total: ${$.length} files)`),Z.join(`
|
|
112
|
+
`)}function mX($){let Z=$.name??"commit-mode",Y=$.model,W=$.defaultLanguage??"English",J=$.defaultAutoStage??!0,Q=$.fetchBeforeCommit??!1,X=$.allowBehindRemote??!1,K=$.cwd??process.cwd(),V=$.customPrompt,B=async(G,F)=>{if(G.metadata?.commitProcessed)return F(G);try{let z=EY(K);if(!z.isGitRepo){let M={role:"assistant",content:`\u2717 \u9519\u8BEF\uFF1A\u5F53\u524D\u76EE\u5F55\u4E0D\u662F git \u4ED3\u5E93\u3002
|
|
113
|
+
|
|
114
|
+
Error: Not in a git repository. Please run this from within a git repository.`};return{...G,messages:[...G.messages,M],currentResponse:M.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,preCommitCheck:z}}}let N={fetched:!1,message:""};if(Q&&z.hasRemote)if(W5(K)){N={fetched:!0,message:"\u5DF2\u4ECE\u8FDC\u7A0B\u83B7\u53D6\u6700\u65B0\u66F4\u65B0"};let L=EY(K);Object.assign(z,{ahead:L.ahead,behind:L.behind,isDiverged:L.isDiverged})}else N={fetched:!1,message:"\u65E0\u6CD5\u4ECE\u8FDC\u7A0B\u83B7\u53D6\u66F4\u65B0\uFF08\u7F51\u7EDC\u95EE\u9898\u6216\u65E0\u6743\u9650\uFF09"};if(z.hasConflicts){let M={role:"assistant",content:`\u2717 \u5B58\u5728\u672A\u89E3\u51B3\u7684\u51B2\u7A81\uFF0C\u65E0\u6CD5\u63D0\u4EA4\u3002
|
|
115
|
+
|
|
116
|
+
\u274C Cannot commit: Unresolved conflicts detected.
|
|
117
|
+
|
|
118
|
+
${_Y(z)}
|
|
119
|
+
|
|
120
|
+
\u8BF7\u5148\u89E3\u51B3\u4EE5\u4E0A\u51B2\u7A81\u6587\u4EF6\uFF0C\u7136\u540E\u518D\u6B21\u5C1D\u8BD5\u63D0\u4EA4\u3002
|
|
121
|
+
Please resolve the conflicts above before committing.`};return{...G,messages:[...G.messages,M],currentResponse:M.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,preCommitCheck:z,hasConflicts:!0}}}if(z.inMergeState&&!z.hasChanges){let M={role:"assistant",content:`\u2717 \u5F53\u524D\u6B63\u5728\u8FDB\u884C ${z.mergeStateType}\uFF0C\u4F46\u6CA1\u6709\u6682\u5B58\u7684\u66F4\u6539\u3002
|
|
122
|
+
|
|
123
|
+
\u274C Currently in ${z.mergeStateType} state but no staged changes.
|
|
124
|
+
|
|
125
|
+
${_Y(z)}
|
|
126
|
+
|
|
127
|
+
\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u7684 ${z.mergeStateType} \u64CD\u4F5C\u3002
|
|
128
|
+
Please complete or abort the current ${z.mergeStateType} operation.`};return{...G,messages:[...G.messages,M],currentResponse:M.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,preCommitCheck:z}}}if(!X&&z.behind>0){let M={role:"assistant",content:`\u26A0\uFE0F \u672C\u5730\u5206\u652F\u843D\u540E\u4E8E\u8FDC\u7A0B ${z.behind} \u4E2A\u63D0\u4EA4\u3002
|
|
129
|
+
|
|
130
|
+
\u26A0\uFE0F Local branch is ${z.behind} commit(s) behind remote.
|
|
131
|
+
|
|
132
|
+
${_Y(z)}
|
|
133
|
+
|
|
134
|
+
\u5EFA\u8BAE\u5148\u6267\u884C git pull \u62C9\u53D6\u6700\u65B0\u66F4\u6539\uFF0C\u89E3\u51B3\u53EF\u80FD\u7684\u51B2\u7A81\u540E\u518D\u63D0\u4EA4\u3002
|
|
135
|
+
Recommend running 'git pull' first to get latest changes and resolve any conflicts before committing.
|
|
136
|
+
|
|
137
|
+
\u5982\u9700\u5F3A\u5236\u63D0\u4EA4\uFF0C\u8BF7\u4F7F\u7528 allowBehindRemote: true \u9009\u9879\u3002`};return{...G,messages:[...G.messages,M],currentResponse:M.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,preCommitCheck:z,isBehindRemote:!0}}}if(J){if(LY(K))e9(K);else if(!wY(K)&&!z.inMergeState){let M={role:"assistant",content:`\u2717 \u6CA1\u6709\u9700\u8981\u63D0\u4EA4\u7684\u66F4\u6539\u3002
|
|
138
|
+
|
|
139
|
+
No changes to commit. Working directory is clean.`};return{...G,messages:[...G.messages,M],currentResponse:M.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,preCommitCheck:z}}}}let q=Z5(K),w=$5(K);if(!w||w.trim().length===0){let M={role:"assistant",content:`\u2717 \u6CA1\u6709\u6682\u5B58\u7684\u66F4\u6539\u3002
|
|
140
|
+
|
|
141
|
+
No staged changes to commit. Please stage files first or enable auto_stage.`};return{...G,messages:[...G.messages,M],currentResponse:M.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,preCommitCheck:z}}}if(!Y.run)throw Error("Model does not support run() method");let A=hX(w,W,V),O=[{role:"system",content:vX},{role:"user",content:A}],j=(await Y.run({messages:O})).text.trim();if(!j)throw Error("LLM returned empty commit message");let S=Y5(j,K),b=gX(q),y=N.fetched?`
|
|
142
|
+
|
|
143
|
+
\uD83D\uDCE1 ${N.message}`:"",k=z.warnings.length>0?`
|
|
144
|
+
|
|
145
|
+
\u26A0\uFE0F \u6CE8\u610F\u4E8B\u9879:
|
|
146
|
+
${z.warnings.map((M)=>` \u2022 ${M}`).join(`
|
|
147
|
+
`)}`:"",D=z.currentBranch?`
|
|
148
|
+
\u5206\u652F: ${z.currentBranch}`:"",I={role:"assistant",content:`\u2713 \u6210\u529F\u521B\u5EFA commit
|
|
149
|
+
|
|
150
|
+
Commit Hash: ${S}${D}${y}${k}
|
|
151
|
+
|
|
152
|
+
${b}
|
|
153
|
+
|
|
154
|
+
Commit Message:
|
|
155
|
+
${j}`};return{...G,messages:[...G.messages,I],currentResponse:I.content,shouldContinue:!1,stopReason:"final_response",metadata:{...G.metadata,commitProcessed:!0,commitHash:S,commitMessage:j,preCommitCheck:z}}}catch(z){let N={role:"assistant",content:`\u2717 \u521B\u5EFA commit \u5931\u8D25
|
|
156
|
+
|
|
157
|
+
Error: ${z instanceof Error?z.message:String(z)}`};return{...G,messages:[...G.messages,N],currentResponse:N.content,shouldContinue:!1,stopReason:"error",metadata:{...G.metadata,commitProcessed:!0}}}};return B.__middlewareName=Z,B}function Q5($){return{content:[{type:"text",text:$}]}}function X1($){return{content:[{type:"text",text:$}],isError:!0}}function X5($,Z){return{content:[{type:"image",data:$,mimeType:Z}]}}class Z1{riskLevel="safe"}class g8 extends Z1{name="AskUserQuestion";riskLevel="safe";description=`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
158
|
+
1. Gather user preferences or requirements
|
|
159
|
+
2. Clarify ambiguous instructions
|
|
160
|
+
3. Get decisions on implementation choices as you work
|
|
161
|
+
4. Offer choices to the user about what direction to take
|
|
162
|
+
|
|
163
|
+
Usage notes:
|
|
164
|
+
- Users will always be able to select "Other" to provide custom text input
|
|
165
|
+
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
166
|
+
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`;parameters={type:"object",properties:{questions:{type:"array",items:{type:"object",properties:{question:{type:"string",description:'The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'},header:{type:"string",maxLength:12,description:'Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'},options:{type:"array",items:{type:"object",properties:{label:{type:"string",description:"The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."},description:{type:"string",description:"Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications."}},required:["label","description"]},minItems:2,maxItems:4,description:"The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically."},multiSelect:{type:"boolean",description:"Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."}},required:["question","header","options","multiSelect"]},minItems:1,maxItems:4,description:"Questions to ask the user (1-4 questions)"},answers:{type:"object",additionalProperties:{type:["string","array"]},description:"User answers collected by the permission component"}},required:["questions"]};async execute($){let{questions:Z,answers:Y}=this.validateArgs($);if(!Y||Object.keys(Y).length===0)throw Error("AskUserTool.execute() was called without answers. This indicates a bug: Session should have intercepted this tool call and emitted a requires_action event. The tool should only be executed after the user provides answers via toolContext.");let W=this.formatAnswersMessage(Z,Y);return{content:[{type:"text",text:W}],structuredContent:{success:!0,answers:Y,message:W}}}validateArgs($){let Z=$.questions;if(!Array.isArray(Z))throw TypeError("questions is required and must be an array");if(Z.length<1||Z.length>4)throw Error("questions must contain 1-4 items");let Y=[];for(let J=0;J<Z.length;J++){let Q=Z[J];if(typeof Q!=="object"||Q===null)throw TypeError(`questions[${J}] must be an object`);let{question:X,header:K,options:V,multiSelect:B}=Q;if(typeof X!=="string"||!X.trim())throw Error(`questions[${J}].question is required and must be a non-empty string`);if(typeof K!=="string"||!K.trim())throw Error(`questions[${J}].header is required and must be a non-empty string`);if(K.length>12)throw Error(`questions[${J}].header must be at most 12 characters`);if(!Array.isArray(V))throw TypeError(`questions[${J}].options must be an array`);if(V.length<2||V.length>4)throw Error(`questions[${J}].options must contain 2-4 items`);if(typeof B!=="boolean")throw TypeError(`questions[${J}].multiSelect is required and must be a boolean`);let G=[];for(let F=0;F<V.length;F++){let z=V[F];if(typeof z!=="object"||z===null)throw TypeError(`questions[${J}].options[${F}] must be an object`);let{label:N,description:q}=z;if(typeof N!=="string"||!N.trim())throw Error(`questions[${J}].options[${F}].label is required and must be a non-empty string`);if(typeof q!=="string"||!q.trim())throw Error(`questions[${J}].options[${F}].description is required and must be a non-empty string`);G.push({label:N.trim(),description:q.trim()})}Y.push({question:X.trim(),header:K.trim(),options:G,multiSelect:Boolean(B)})}let W;if($.answers&&typeof $.answers==="object"&&$.answers!==null){W={};for(let[J,Q]of Object.entries($.answers))if(typeof Q==="string")W[J]=Q;else if(Array.isArray(Q))W[J]=Q.map((X)=>String(X));else W[J]=String(Q)}return{questions:Y,answers:W}}formatAnswersMessage($,Z){let Y=[];for(let W=0;W<$.length;W++){let J=$[W],Q=Z[String(W)];if(Q===void 0)continue;Y.push(`Question ${W+1} (${J.header}): ${J.question}`);let X=this.formatAnswerText(Q);if(X.inline!==void 0)Y.push(`Answer: ${X.inline}`);else if(X.lines){Y.push("Answer:");for(let K of X.lines)Y.push(` ${K}`)}Y.push("")}if(Y.length===0)return"No answers received";if(Y[Y.length-1]==="")Y.pop();return`User responses:
|
|
167
|
+
|
|
168
|
+
${Y.join(`
|
|
169
|
+
`)}`}formatAnswerText($){if(Array.isArray($)){if($.length===0)return{inline:"(no response)"};if($.length===1){let Y=String($[0]);if(Y.includes(`
|
|
170
|
+
`))return{lines:Y.split(`
|
|
171
|
+
`)};return{inline:Y}}return{lines:this.formatArrayAnswer($.map((Y)=>String(Y)))}}let Z=String($);if(Z.includes(`
|
|
172
|
+
`))return{lines:Z.split(`
|
|
173
|
+
`)};return{inline:Z}}formatArrayAnswer($){let Z=[];for(let Y of $){let W=Y.split(`
|
|
174
|
+
`);Z.push(`- ${W[0]??""}`);for(let J=1;J<W.length;J++)Z.push(` ${W[J]}`)}return Z}}import VK from"process";import{spawn as G5}from"child_process";import{chmodSync as dX,existsSync as m1,mkdirSync as uX,statSync as cX,unlinkSync as lX}from"fs";import{writeFile as pX}from"fs/promises";import{createRequire as OY}from"module";import{homedir as K5}from"os";import y1 from"path";import U1 from"process";var iX="ast-grep/ast-grep",B5="0.40.0",_0=["bash","c","cpp","csharp","css","elixir","go","haskell","html","java","javascript","json","kotlin","lua","nix","php","python","ruby","rust","scala","solidity","swift","typescript","tsx","yaml"],nX=300000,gZ=1048576,V5=500,rX={"darwin-arm64":{arch:"aarch64",os:"apple-darwin"},"darwin-x64":{arch:"x86_64",os:"apple-darwin"},"linux-arm64":{arch:"aarch64",os:"unknown-linux-gnu"},"linux-x64":{arch:"x86_64",os:"unknown-linux-gnu"},"win32-x64":{arch:"x86_64",os:"pc-windows-msvc"},"win32-arm64":{arch:"aarch64",os:"pc-windows-msvc"},"win32-ia32":{arch:"i686",os:"pc-windows-msvc"}};function mZ($){try{return cX($).size>1e4}catch{return!1}}function aX(){return{"darwin-arm64":"@ast-grep/cli-darwin-arm64","darwin-x64":"@ast-grep/cli-darwin-x64","linux-arm64":"@ast-grep/cli-linux-arm64-gnu","linux-x64":"@ast-grep/cli-linux-x64-gnu","win32-x64":"@ast-grep/cli-win32-x64-msvc","win32-arm64":"@ast-grep/cli-win32-arm64-msvc","win32-ia32":"@ast-grep/cli-win32-ia32-msvc"}[`${U1.platform}-${U1.arch}`]??null}function oX(){try{return OY(import.meta.url)("@ast-grep/cli/package.json").version}catch{return B5}}function dZ(){if(U1.platform==="win32"){let W=U1.env.LOCALAPPDATA||U1.env.APPDATA||y1.join(K5(),"AppData","Local");return y1.join(W,"goat-chain","bin")}let Z=U1.env.XDG_CACHE_HOME||y1.join(K5(),".cache");return y1.join(Z,"goat-chain","bin")}function DY(){return U1.platform==="win32"?"ast-grep.exe":"ast-grep"}function sX(){return U1.platform==="win32"?"sg.exe":"sg"}function tX(){let $=[DY(),sX()];return Array.from(new Set($))}function F5(){let $=dZ();for(let Z of tX()){let Y=y1.join($,Z);if(m1(Y)&&mZ(Y))return Y}return null}async function eX($,Z){let Y=U1.platform==="win32",W=Y?"powershell":"unzip",J=Y?["-command",`Expand-Archive -Path '${$}' -DestinationPath '${Z}' -Force`]:["-o",$,"-d",Z],{exitCode:Q,stderr:X}=await WK(W,J);if(Q!==0)throw Error(`zip extraction failed (exit ${Q}): ${X}
|
|
175
|
+
|
|
176
|
+
${Y?"Ensure PowerShell is available on your system.":"Please install 'unzip' (e.g., apt install unzip, brew install unzip)."}`)}async function $K($=B5){let Z=`${U1.platform}-${U1.arch}`,Y=rX[Z];if(!Y)return console.error(`[goat-chain] Unsupported platform for ast-grep: ${Z}`),null;let W=dZ(),J=DY(),Q=y1.join(W,J);if(m1(Q))return Q;let{arch:X,os:K}=Y,V=`app-${X}-${K}.zip`,B=`https://github.com/${iX}/releases/download/${$}/${V}`;console.log("[goat-chain] Downloading ast-grep binary...");try{if(!m1(W))uX(W,{recursive:!0});let G=await fetch(B,{redirect:"follow"});if(!G.ok)throw Error(`HTTP ${G.status}: ${G.statusText}`);let F=y1.join(W,V),z=await G.arrayBuffer();if(await pX(F,Buffer.from(z)),await eX(F,W),m1(F))lX(F);if(U1.platform!=="win32"&&m1(Q))dX(Q,493);return console.log("[goat-chain] ast-grep binary ready."),Q}catch(G){return console.error(`[goat-chain] Failed to download ast-grep: ${G instanceof Error?G.message:G}`),null}}async function q5(){let $=oX(),Z=await $K($);if(Z)X0=Z,H5(Z);return Z}async function z5(){let $=F5();if($)return $;if(r1)return r1;return r1=(async()=>{try{return await q5()}finally{r1=null}})(),r1}function U5(){let $=DY(),Z=F5();if(Z&&mZ(Z))return Z;try{let J=OY(import.meta.url).resolve("@ast-grep/cli/package.json"),Q=y1.dirname(J),X=y1.join(Q,$);if(m1(X)&&mZ(X))return X}catch{}let Y=aX();if(Y)try{let J=OY(import.meta.url).resolve(`${Y}/package.json`),Q=y1.dirname(J),X=U1.platform==="win32"?"ast-grep.exe":"ast-grep",K=y1.join(Q,X);if(m1(K)&&mZ(K))return K}catch{}if(U1.platform==="darwin"){let W=["/opt/homebrew/bin/ast-grep","/usr/local/bin/ast-grep","/opt/homebrew/bin/sg","/usr/local/bin/sg"];for(let J of W)if(m1(J)&&mZ(J))return J}return null}var X0=null,r1=null;function ZK(){if(X0!==null)return X0;let $=U5();if($)return X0=$,$;return"sg"}function H5($){X0=$}async function YK(){if(X0!==null&&m1(X0))return X0;if(r1)return r1;return r1=(async()=>{try{let $=U5();if($&&m1($))return X0=$,H5($),$;return await q5()}finally{r1=null}})(),r1}function WK($,Z){return new Promise((Y,W)=>{let J=G5($,Z,{stdio:["ignore","pipe","pipe"]}),Q="",X="";J.stdout?.on("data",(K)=>{Q+=K.toString()}),J.stderr?.on("data",(K)=>{X+=K.toString()}),J.on("error",(K)=>{W(K)}),J.on("close",(K)=>{Y({exitCode:K,stdout:Q,stderr:X})})})}function JK($,Z,Y,W){return new Promise((J,Q)=>{let X=!1,K=!1,V=[],B=0,G=[],F=0;console.log("[goat-chain] Spawning process:",$,Z,W??U1.cwd());let z=G5($,Z,{cwd:W,stdio:["ignore","pipe","pipe"]}),N=setTimeout(()=>{X=!0,z.kill()},Y);z.stdout?.on("data",(q)=>{if(B>=gZ){K=!0;return}let w=gZ-B;if(q.length>w)V.push(q.subarray(0,w)),B+=w,K=!0;else V.push(q),B+=q.length}),z.stderr?.on("data",(q)=>{if(F>=gZ)return;let w=gZ-F;if(q.length>w)G.push(q.subarray(0,w)),F+=w;else G.push(q),F+=q.length}),z.on("error",(q)=>{clearTimeout(N),Q(q)}),z.on("close",(q)=>{clearTimeout(N),J({stdout:Buffer.concat(V).toString(),stderr:Buffer.concat(G).toString(),exitCode:q,timedOut:X,outputTruncated:K})})})}function QK($){return $.code==="ENOENT"||$.message?.includes("ENOENT")||$.message?.includes("not found")||$.message?.includes("cannot execute")||$.message?.includes("Exec format error")||$.code==="EACCES"}function XK($,Z){try{let Y=JSON.parse($);return Array.isArray(Y)?Y:[]}catch{if(!Z)return[]}try{let Y=$.lastIndexOf("}");if(Y>0){let W=$.lastIndexOf("},",Y);if(W>0){let J=`${$.substring(0,W+1)}]`,Q=JSON.parse(J);return Array.isArray(Q)?Q:[]}}}catch{return null}return null}async function r0($){console.log("[goat-chain] Running ast-grep command...",$);let Z=$.jsonOutput!==!1,Y=["run","-p",$.pattern,"--lang",$.lang];if(Z)Y.push("--json=compact");if($.rewrite){if(Y.push("-r",$.rewrite),$.updateAll)Y.push("--update-all")}if($.context&&$.context>0)Y.push("-C",String($.context));if($.globs)for(let N of $.globs)Y.push("--globs",N);let W=$.paths&&$.paths.length>0?$.paths:["."];Y.push(...W);let J=nX,Q=Boolean($.binaryPath),X=$.binaryPath??ZK();if(!Q&&!m1(X)&&X!=="sg"){let N=await YK();if(N)X=N}let K;try{K=await JK(X,Y,J,$.cwd)}catch(N){let q=N;if(!Q&&QK(q)){if(await z5())return r0($);return{matches:[],totalMatches:0,truncated:!1,error:`ast-grep CLI binary not found or invalid.
|
|
177
|
+
|
|
178
|
+
Auto-download failed. Manual install options:
|
|
179
|
+
pnpm install --force # Re-run postinstall scripts
|
|
180
|
+
bun add -D @ast-grep/cli
|
|
181
|
+
cargo install ast-grep --locked
|
|
182
|
+
brew install ast-grep
|
|
183
|
+
|
|
184
|
+
See docs/TROUBLESHOOTING.md for more information.`}}return{matches:[],totalMatches:0,truncated:!1,error:`Failed to spawn ast-grep: ${q.message}`}}if(K.timedOut)return{matches:[],totalMatches:0,truncated:!0,truncatedReason:"timeout",error:`Search timeout after ${J}ms`,exitCode:K.exitCode,stderr:K.stderr};if(!Z){let N=K.stdout.trim(),q=K.stderr.trim();if(K.exitCode!==0){let w=q||N||`ast-grep exited with code ${K.exitCode}`;return{matches:[],totalMatches:0,truncated:K.outputTruncated,truncatedReason:K.outputTruncated?"max_output_bytes":void 0,error:w,exitCode:K.exitCode,stderr:K.stderr}}return{matches:[],totalMatches:0,truncated:K.outputTruncated,truncatedReason:K.outputTruncated?"max_output_bytes":void 0,exitCode:K.exitCode,stderr:K.stderr}}if(K.exitCode!==0&&K.stdout.trim()===""){if(K.stderr.includes("No files found"))return{matches:[],totalMatches:0,truncated:!1,exitCode:K.exitCode,stderr:K.stderr};let N=K.stderr.toLowerCase();if(!Q&&(N.includes("command not found")||N.includes("cannot execute")||N.includes("exec format error")||N.includes("permission denied"))){if(await z5())return r0($)}if(K.stderr.trim())return{matches:[],totalMatches:0,truncated:!1,error:K.stderr.trim(),exitCode:K.exitCode,stderr:K.stderr};return{matches:[],totalMatches:0,truncated:!1,exitCode:K.exitCode,stderr:K.stderr}}if(!K.stdout.trim())return{matches:[],totalMatches:0,truncated:!1,exitCode:K.exitCode,stderr:K.stderr};let V=K.outputTruncated||Buffer.byteLength(K.stdout)>=gZ,B=XK(K.stdout,V);if(B===null)return{matches:[],totalMatches:0,truncated:!0,truncatedReason:"max_output_bytes",error:"Output too large and could not be parsed",exitCode:K.exitCode,stderr:K.stderr};let G=B.length,F=G>V5;return{matches:F?B.slice(0,V5):B,totalMatches:G,truncated:V||F,truncatedReason:V?"max_output_bytes":F?"max_matches":void 0,exitCode:K.exitCode,stderr:K.stderr}}import N5 from"path";function M5($,Z){if(!$||!Z)return $;let Y=N5.relative(Z,$);if(Y&&!Y.startsWith("..")&&!N5.isAbsolute(Y))return Y;return $}function w5($){if($.truncatedReason==="max_matches")return`showing first ${$.matches.length} of ${$.totalMatches}`;if($.truncatedReason==="max_output_bytes")return"output exceeded 1MB limit";if($.truncatedReason==="timeout")return"search timed out";return"output truncated"}function KK($){let Z=($.lines??$.text??"").trim();return Z?` ${Z}`:""}function L5($,Z){if($.error)return`Error: ${$.error}`;if($.matches.length===0)return"No matches found";let Y=[];if($.truncated)Y.push(`Results truncated (${w5($)})
|
|
185
|
+
`);Y.push(`Found ${$.matches.length} match(es)${$.truncated?` (truncated from ${$.totalMatches})`:""}:
|
|
186
|
+
`);for(let W of $.matches){let J=(W.range?.start?.line??0)+1,Q=(W.range?.start?.column??0)+1,X=`${M5(W.file,Z)}:${J}:${Q}`;Y.push(X);let K=KK(W);if(K)Y.push(K);Y.push("")}return Y.join(`
|
|
187
|
+
`)}function jY($,Z,Y){if($.error)return`Error: ${$.error}`;if($.matches.length===0)return"No matches found to replace";let W=Z?"[DRY RUN] ":"",J=[];if($.truncated)J.push(`Results truncated (${w5($)})
|
|
188
|
+
`);J.push(`${W}${$.matches.length} replacement(s):
|
|
189
|
+
`);for(let Q of $.matches){let X=(Q.range?.start?.line??0)+1,K=(Q.range?.start?.column??0)+1,V=`${M5(Q.file,Y)}:${X}:${K}`;J.push(V);let B=Q.text?.trim();if(B)J.push(` ${B}`);J.push("")}if(Z)J.push("Use dryRun=false to apply changes");return J.join(`
|
|
190
|
+
`)}function E5($,Z){let Y=$.trim();if(Z==="python"){if(Y.startsWith("class ")&&Y.endsWith(":"))return`Hint: Remove trailing colon. Try: "${Y.slice(0,-1)}"`;if((Y.startsWith("def ")||Y.startsWith("async def "))&&Y.endsWith(":"))return`Hint: Remove trailing colon. Try: "${Y.slice(0,-1)}"`}if(["javascript","typescript","tsx"].includes(Z)){if(/^(?:export\s+)?(?:async\s+)?function\s+\$[A-Z_]+\s*$/i.test(Y))return'Hint: Function patterns need params and body. Try "function $NAME($$$) { $$$ }"'}return null}class m8 extends Z1{name="ast_grep_replace";riskLevel="high";description=`Replace code patterns across filesystem with AST-aware rewriting. Dry-run by default.
|
|
191
|
+
|
|
192
|
+
Usage notes:
|
|
193
|
+
- Use meta-variables in rewrite to preserve matched content
|
|
194
|
+
- Example: pattern='console.log($MSG)' rewrite='logger.info($MSG)'
|
|
195
|
+
- Set dryRun=false to apply changes`;parameters={type:"object",properties:{pattern:{type:"string",description:"AST pattern to match."},rewrite:{type:"string",description:"Replacement pattern (can use $VAR from pattern)."},lang:{type:"string",enum:[..._0],description:"Target language (ast-grep language identifier)."},paths:{type:"array",items:{type:"string"},description:'Paths to search (default: ["."]).'},globs:{type:"array",items:{type:"string"},description:"Include/exclude globs (prefix ! to exclude)."},dryRun:{type:"boolean",description:"Preview changes without applying (default: true)."}},required:["pattern","rewrite","lang"]};cwd;astGrepPath;constructor($){super();this.cwd=$?.cwd??VK.cwd(),this.astGrepPath=$?.astGrepPath}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($){let Z=this.validateArgs($),Y=Z.dryRun!==!1,W=await r0({pattern:Z.pattern,rewrite:Z.rewrite,lang:Z.lang,paths:Z.paths,globs:Z.globs,updateAll:!1,cwd:this.cwd,binaryPath:this.astGrepPath});if(!Y&&!W.error&&W.matches.length>0){let X=await r0({pattern:Z.pattern,rewrite:Z.rewrite,lang:Z.lang,paths:Z.paths,globs:Z.globs,updateAll:!0,jsonOutput:!1,cwd:this.cwd,binaryPath:this.astGrepPath});if(Boolean(X.error)||X.exitCode!==null&&X.exitCode!==0){let F=`Error: ${X.error||X.stderr?.trim()||`ast-grep replace failed${X.exitCode!==null?` (exit ${X.exitCode})`:""}`}`,z={exitCode:X.exitCode??W.exitCode??null,output:F,matches:W.matches,matchCount:W.totalMatches,stderr:X.stderr?.trim()||W.stderr?.trim()||void 0,truncated:W.truncated,truncatedReason:W.truncatedReason,timedOut:W.truncatedReason==="timeout"};return{content:[{type:"text",text:F}],structuredContent:z,isError:!0}}let V=jY(W,Y,this.cwd),B={exitCode:X.exitCode??W.exitCode??null,output:V,matches:W.matches,matchCount:W.totalMatches,stderr:X.stderr?.trim()||W.stderr?.trim()||void 0,truncated:W.truncated,truncatedReason:W.truncatedReason,timedOut:W.truncatedReason==="timeout"};return{content:[{type:"text",text:V}],structuredContent:B,isError:!1}}let J=jY(W,Y,this.cwd),Q={exitCode:W.exitCode??null,output:J,matches:W.matches,matchCount:W.totalMatches,stderr:W.stderr?.trim()||void 0,truncated:W.truncated,truncatedReason:W.truncatedReason,timedOut:W.truncatedReason==="timeout"};return{content:[{type:"text",text:J}],structuredContent:Q,isError:Boolean(W.error)}}validateArgs($){let{pattern:Z,rewrite:Y,lang:W}=$;if(typeof Z!=="string"||!Z.trim())throw Error("pattern is required and must be a non-empty string");if(typeof Y!=="string"||!Y.trim())throw Error("rewrite is required and must be a non-empty string");if(typeof W!=="string"||!W.trim())throw Error("lang is required and must be a non-empty string");if(!_0.includes(W))throw Error(`lang must be one of: ${_0.join(", ")}`);let J={pattern:Z.trim(),rewrite:Y.trim(),lang:W.trim()};if($.paths!==void 0&&$.paths!==null){if(!Array.isArray($.paths)||$.paths.some((Q)=>typeof Q!=="string"))throw TypeError("paths must be an array of strings");J.paths=$.paths.map((Q)=>Q.trim()).filter(Boolean)}if($.globs!==void 0&&$.globs!==null){if(!Array.isArray($.globs)||$.globs.some((Q)=>typeof Q!=="string"))throw TypeError("globs must be an array of strings");J.globs=$.globs.map((Q)=>Q.trim()).filter(Boolean)}if($.dryRun!==void 0&&$.dryRun!==null)J.dryRun=Boolean($.dryRun);return J}}import zK from"process";var _5=5000;class d8 extends Z1{name="ast_grep_search";description=`Search code patterns across filesystem using AST-aware matching. Supports 25 languages.
|
|
196
|
+
|
|
197
|
+
Usage notes:
|
|
198
|
+
- Use meta-variables: $VAR (single node), $$$ (multiple nodes)
|
|
199
|
+
- Patterns must be complete AST nodes (valid code)
|
|
200
|
+
- For functions, include params and body: 'export async function $NAME($$$) { $$$ }' not 'export async function $NAME'
|
|
201
|
+
- Examples: 'console.log($MSG)', 'def $FUNC($$$):', 'async function $NAME($$$)'`;parameters={type:"object",properties:{pattern:{type:"string",description:"AST pattern with meta-variables ($VAR, $$$). Must be complete AST node."},lang:{type:"string",enum:[..._0],description:"Target language (ast-grep language identifier)."},paths:{type:"array",items:{type:"string"},description:'Paths to search (default: ["."]).'},globs:{type:"array",items:{type:"string"},description:"Include/exclude globs (prefix ! to exclude)."},context:{type:"number",description:"Context lines around match."}},required:["pattern","lang"]};cwd;astGrepPath;constructor($){super();this.cwd=$?.cwd??zK.cwd(),this.astGrepPath=$?.astGrepPath}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($){let Z=this.validateArgs($),Y=await r0({pattern:Z.pattern,lang:Z.lang,paths:Z.paths,globs:Z.globs,context:Z.context,cwd:this.cwd,binaryPath:this.astGrepPath}),W=L5(Y,this.cwd);if(Y.matches.length===0&&!Y.error){let K=E5(Z.pattern,Z.lang);if(K)W+=`
|
|
202
|
+
|
|
203
|
+
${K}`}let{truncated:J,truncatedReason:Q}=Y;if(W.length>_5){if(W=W.slice(0,_5)+`
|
|
204
|
+
|
|
205
|
+
... [output truncated due to length limit]`,J=!0,!Q)Q="max_output_bytes"}let X={exitCode:Y.exitCode??null,output:W,matches:Y.matches,matchCount:Y.totalMatches,stderr:Y.stderr?.trim()||void 0,truncated:J,truncatedReason:Q,timedOut:Y.truncatedReason==="timeout"};return{content:[{type:"text",text:W}],structuredContent:X,isError:Boolean(Y.error)}}validateArgs($){let{pattern:Z,lang:Y}=$;if(typeof Z!=="string"||!Z.trim())throw Error("pattern is required and must be a non-empty string");if(typeof Y!=="string"||!Y.trim())throw Error("lang is required and must be a non-empty string");if(!_0.includes(Y))throw Error(`lang must be one of: ${_0.join(", ")}`);let W={pattern:Z.trim(),lang:Y.trim()};if($.paths!==void 0&&$.paths!==null){if(!Array.isArray($.paths)||$.paths.some((J)=>typeof J!=="string"))throw TypeError("paths must be an array of strings");W.paths=$.paths.map((J)=>J.trim()).filter(Boolean)}if($.globs!==void 0&&$.globs!==null){if(!Array.isArray($.globs)||$.globs.some((J)=>typeof J!=="string"))throw TypeError("globs must be an array of strings");W.globs=$.globs.map((J)=>J.trim()).filter(Boolean)}if($.context!==void 0&&$.context!==null){if(typeof $.context!=="number"||!Number.isFinite($.context)||$.context<0)throw TypeError("context must be a non-negative number");W.context=Math.floor($.context)}return W}}import{spawn as O5}from"child_process";import P$ from"process";var u8=30000,D5=120000,GK=600000;class c8 extends Z1{name="Bash";riskLevel="critical";description=`Executes a given bash command in a persistent shell session with optional timeout.
|
|
206
|
+
|
|
207
|
+
Usage notes:
|
|
208
|
+
- The command argument is required.
|
|
209
|
+
- Use 'run_in_background: true' for long-running processes such as:
|
|
210
|
+
* Development servers: npm run dev, yarn dev, pnpm dev, npm start
|
|
211
|
+
* Server processes: node server.js, python -m http.server
|
|
212
|
+
* Watch modes: npm run watch, yarn watch
|
|
213
|
+
* Database/service daemons: redis-server, mongod
|
|
214
|
+
* Any command that runs indefinitely until manually stopped
|
|
215
|
+
- If not specified, commands will timeout after 120000ms (2 minutes).
|
|
216
|
+
- Standard timeout is suitable for short-lived commands like builds, tests, and file operations.
|
|
217
|
+
- If the output exceeds 30000 characters, it will be truncated.
|
|
218
|
+
|
|
219
|
+
Examples:
|
|
220
|
+
- Background: { command: "npm run dev", run_in_background: true, description: "Start dev server" }
|
|
221
|
+
- Foreground: { command: "npm test", timeout: 60000, description: "Run tests" }
|
|
222
|
+
- Foreground: { command: "npm run build", description: "Build project" }`;parameters={type:"object",properties:{command:{type:"string",description:"The command to execute"},timeout:{type:"number",description:"Optional timeout in milliseconds (max 600000)"},description:{type:"string",description:"Clear, concise description of what this command does in 5-10 words"},run_in_background:{type:"boolean",description:"Set to true to run this command in the background. REQUIRED for long-running processes like dev servers (npm run dev, npm start), watch modes, or any command that runs indefinitely. The command will start immediately and return its PID without waiting for completion."}},required:["command"]};cwd;shell;constructor($){super();this.cwd=$?.cwd??P$.cwd(),this.shell=$?.shell??(P$.platform==="win32"?"cmd.exe":"/bin/bash")}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($){let{command:Z,timeout:Y=D5,run_in_background:W}=this.validateArgs($),J=this.shouldRunInBackground(Z),Q;if(J&&!W)Q=`\u26A0\uFE0F WARNING: This command appears to be a long-running process (dev server, watch mode, or daemon). It will timeout after ${Y}ms. Consider using 'run_in_background: true' to run it properly in the background.`;let X=W?await this.executeBackground(Z):await this.executeSync(Z,Y);if(Q)X.warning=Q;let K=[];if(X.warning)K.push(X.warning),K.push("");if(X.stdout)K.push(X.stdout);if(X.stderr)K.push(`[stderr]:
|
|
223
|
+
${X.stderr}`);if(X.timedOut){if(K.push(`[Command timed out after ${Y}ms]`),J)K.push("[Hint: This looks like a long-running process. Retry with 'run_in_background: true']")}if(X.background)K.push(`[Running in background with PID ${X.pid}]`);return{content:[{type:"text",text:K.join(`
|
|
224
|
+
`)||"[No output]"}],structuredContent:X,isError:X.exitCode!==0&&X.exitCode!==null&&!X.background}}shouldRunInBackground($){let Z=$.toLowerCase().trim();return[/^(npm|yarn|pnpm|bun)\s+(run\s+)?(dev|start|serve)/,/^(npm|yarn|pnpm|bun)\s+run\s+watch/,/^node\s+.*server/,/^(python|python3)\s+-m\s+(http\.server|SimpleHTTPServer)/,/^(ruby)\s+-run\s+-e\s+httpd/,/^(vite|webpack-dev-server|parcel|rollup)\s+/,/^(redis-server|mongod|postgres|mysql)/,/^(next|nuxt)\s+dev/].some((W)=>W.test(Z))}validateArgs($){let Z=$.command;if(typeof Z!=="string"||!Z.trim())throw Error("Command is required and must be a non-empty string");let Y=D5;if($.timeout!==void 0){if(typeof $.timeout!=="number")throw TypeError("Timeout must be a number");Y=Math.min(Math.max(0,$.timeout),GK)}return{command:Z.trim(),timeout:Y,description:typeof $.description==="string"?$.description:void 0,run_in_background:$.run_in_background===!0}}executeSync($,Z){return new Promise((Y)=>{let W="",J="",Q=!1,X=!1,K=P$.platform==="win32"?["/c",$]:["-c",$],V=O5(this.shell,K,{cwd:this.cwd,env:P$.env,stdio:["ignore","pipe","pipe"]}),B=setTimeout(()=>{Q=!0,V.kill("SIGTERM"),setTimeout(()=>{if(!V.killed)V.kill("SIGKILL")},5000)},Z);V.stdout?.on("data",(G)=>{let F=G.toString();if(W.length+F.length>u8)W+=F.slice(0,u8-W.length),X=!0;else W+=F}),V.stderr?.on("data",(G)=>{let F=G.toString();if(J.length+F.length>u8)J+=F.slice(0,u8-J.length),X=!0;else J+=F}),V.on("close",(G)=>{clearTimeout(B),Y({exitCode:G,stdout:X?`${W}
|
|
225
|
+
... [output truncated]`:W,stderr:J,truncated:X,timedOut:Q,background:!1})}),V.on("error",(G)=>{clearTimeout(B),Y({exitCode:1,stdout:"",stderr:`Failed to execute command: ${G.message}`,truncated:!1,timedOut:!1,background:!1})})})}executeBackground($){return new Promise((Z)=>{let Y=P$.platform==="win32"?["/c",$]:["-c",$],W=O5(this.shell,Y,{cwd:this.cwd,env:P$.env,stdio:"ignore",detached:!0});W.unref(),Z({exitCode:null,stdout:`Command started in background with PID ${W.pid}`,stderr:"",truncated:!1,timedOut:!1,background:!0,pid:W.pid})})}}import{readFile as BK,stat as FK,writeFile as qK}from"fs/promises";import fY from"path";import UK from"process";class l8 extends Z1{name="Edit";riskLevel="high";description=`Performs exact string replacements in files.
|
|
113
226
|
|
|
114
|
-
|
|
115
|
-
`):JSON.stringify(t.content),e.push({name:t.role===`user`?`user_message`:`assistant_message`,content:`${t.role===`user`?`User`:`Assistant`}: ${n}`})}if(e.length===0)return{summary:``,messageCount:n.length,toolOutputCount:0};s=e}let c=(await k(s,r,a,void 0)).trim();if(c.length===0)return{summary:``,messageCount:n.length,toolOutputCount:o.length};let l=await i.load(t,T.COMPRESSION),u=Date.now(),d={lastStats:l?.lastStats,history:l?.history??[],summary:c,updatedAt:u};return await i.save(t,T.COMPRESSION,d),{summary:c,messageCount:n.length,toolOutputCount:o.length}}var A=class{setModelOverride(e){this.configOverride||={},this.configOverride.model=e,this.updatedAt=Date.now()}clearModelOverride(){this.configOverride&&(delete this.configOverride.model,this.updatedAt=Date.now())}setSystemPromptOverride(e){this.configOverride||={},this.configOverride.systemPromptOverride=e,this.updatedAt=Date.now()}clearSystemPromptOverride(){this.configOverride&&(delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now())}disableTools(e){this.configOverride||={},this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...e],this.updatedAt=Date.now()}enableAllTools(){this.configOverride&&(delete this.configOverride.disabledTools,this.updatedAt=Date.now())}setStatus(e,t){this.status=e,this.errorMessage=t,this.updatedAt=Date.now()}markActive(){this.lastActiveAt=Date.now(),this.updatedAt=Date.now()}addMessage(e){this.messages.push(e),this.markActive()}getLastMessagePreview(e=100){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1],n=typeof t.content==`string`?t.content:JSON.stringify(t.content);return n.length>e?`${n.substring(0,e)}...`:n}addUsage(e){this.usage.promptTokens+=e.promptTokens,this.usage.completionTokens+=e.completionTokens,this.usage.totalTokens+=e.totalTokens,this.updatedAt=Date.now()}recordResponse(e){let t=(this.avgResponseTime??0)*this.responseCount;this.responseCount++,this.avgResponseTime=(t+e)/this.responseCount,this.updatedAt=Date.now()}incrementToolCallCount(){this.toolCallCount++,this.updatedAt=Date.now()}toSnapshot(){let e={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},t={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},n={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:e,configOverride:this.configOverride?{...this.configOverride}:void 0,context:t,stats:n}}restoreFromSnapshot(e){this.status=e.state.status,this.updatedAt=e.state.updatedAt,this.lastActiveAt=e.state.lastActiveAt,this.title=e.state.title,this.errorMessage=e.state.errorMessage,this.configOverride=e.configOverride?{...e.configOverride}:void 0,this.messages=[...e.context.messages],this.toolCallCount=e.context.toolCallCount,this.usage={...e.stats.usage},this.responseCount=e.stats.responseCount,this.avgResponseTime=e.stats.avgResponseTime}},le=class{},j=class extends Error{constructor(e=`Agent execution aborted`){super(e),this.name=`AgentAbortError`}},ue=class extends Error{iterations;constructor(e,t){super(t??`Agent exceeded maximum iterations (${e})`),this.name=`AgentMaxIterationsError`,this.iterations=e}},M=class extends Error{constructor(e=`Agent execution paused`){super(e),this.name=`AgentPauseError`}};function N(e,t){if(!e?.aborted)return;let n=e?.reason;throw n instanceof Error?n:new j(typeof n==`string`?n:t?`${t} aborted`:`Agent execution aborted`)}var de=class{},P=class{hooks;constructor(e){this.hooks=e??{}}async executePreToolUse(e){let t=this.hooks.preToolUse;if(!t||t.length===0)return{allow:!0};let n=e.toolCall;for(let r of t){let t=await r({...e,toolCall:n});if(!t.allow)return{allow:!1,modifiedToolCall:t.modifiedToolCall};t.modifiedToolCall&&(n=t.modifiedToolCall)}return n===e.toolCall?{allow:!0}:{allow:!0,modifiedToolCall:n}}async executePostToolUse(e,t){let n=this.hooks.postToolUse;if(!(!n||n.length===0))for(let r of n)await r(e,t)}async executePostToolUseFailure(e,t){let n=this.hooks.postToolUseFailure;if(!(!n||n.length===0))for(let r of n)await r(e,t)}};function F(e){return(t,n)=>{let r=-1,i=async(t,a)=>{if(t<=r)throw Error(`next() called multiple times`);if(r=t,t===e.length)return n?await n(a):a;let o=e[t];return o(a,e=>i(t+1,e))};return i(0,t)}}function I(e,t,n){let r=[{role:`system`,content:n},...e.messages??[],{role:`user`,content:e.input}];return{sessionId:e.sessionId??``,agentId:t,messages:r,iteration:0,pendingToolCalls:[],currentResponse:``,shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}var L=class e extends A{id;agentId;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;_autoSave;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_hasCheckpoint;_checkpointRestored=!1;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;constructor(e,t,n,r){if(super(),this._stateStore=e,this.id=t,n)this.createdAt=n.createdAt,this.restoreFromSnapshot(n);else{let e=Date.now();this.createdAt=e,this.status=`active`,this.updatedAt=e,this.lastActiveAt=e,this.messages=[],this.toolCallCount=0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._modelClient=r?.modelClient,this._tools=r?.tools,this._middlewares=r?.middlewares??[],this._systemPrompt=r?.systemPrompt,this._agentName=r?.agentName,this._onUsage=r?.onUsage,this._hasCheckpoint=r?.hasCheckpoint??!1,this._hooks=r?.hooks,this._modelOverride=r?.model,this._maxIterations=r?.maxIterations,this._requestParams=r?.requestParams}get hasCheckpoint(){return this._hasCheckpoint}send(e,t){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error(`Cannot send while receiving messages`);this._pendingInput={input:e,options:t}}async*receive(){if(this._isReceiving)throw Error(`Cannot receive concurrently`);this._isReceiving=!0;try{if(this._hasCheckpoint&&!this._checkpointRestored&&(yield*this._stream(void 0,this._pendingInput?.options),!this._pendingInput))return;if(this._pendingInput){let{input:e,options:t}=this._pendingInput;this._pendingInput=null,yield*this._stream(e,t)}}finally{this._isReceiving=!1}}resolveModelRef(e){if(e.provider)return{provider:e.provider,modelId:e.modelId};let t=(this._modelClient?.modelRefs??[]).find(t=>t.modelId===e.modelId);if(t)return t;let n=this._modelClient?.modelRef?.provider;if(n)return{provider:n,modelId:e.modelId}}getRuntimeModelOverride(){if(this.configOverride?.model){let e=this.resolveModelRef(this.configOverride.model);if(e)return e}return this._modelOverride}async*_stream(e,t){this._ensureRuntimeConfigured(e!==void 0);let n=Date.now(),r=this.getRuntimeModelOverride(),i;if(this._hasCheckpoint&&!this._checkpointRestored){let e=await this._stateStore.loadCheckpoint(this.id);if(!e)throw Error(`Checkpoint not found for sessionId: ${this.id}`);i=v(e),i.sessionId!==this.id&&(i.sessionId=this.id);let a=this._requestParams??e.requestParams;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,n),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(e===void 0)throw Error(`Input is required to stream`);let a=this.messages.filter(e=>e.role!==`system`);i=I({sessionId:this.id,input:e,messages:a},this.agentId,this._systemPrompt??``),yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:this._requestParams}),await this._finalizeRun(i,n)}_ensureRuntimeConfigured(e){if(!this._modelClient)throw Error(`Session is not configured with a model client`);if(e&&!this._systemPrompt)throw Error(`Session is not configured with a system prompt`)}_recordUsage(e){this._onUsage&&this._onUsage(e)}async executeModelStream(e,t,n,r,i){if(!this._modelClient)throw Error(`Session is not configured with a model client`);let a=[],o=e.sessionId,s=new Map,c=!1,l=!1,u=e=>{let t=s.get(e);if(t)return t;let n={argsText:``,started:!1};return s.set(e,n),n},d=(e,t)=>{let n=u(e);t&&!n.toolName&&(n.toolName=t),n.started||(n.started=!0,a.push({type:`tool_call_start`,callId:e,toolName:n.toolName,sessionId:o}))},f=(e,t,n)=>{let r=u(e);t&&!r.toolName&&(r.toolName=t),typeof n==`string`&&n.length>0&&(r.argsText+=n),d(e,r.toolName),a.push({type:`tool_call_delta`,callId:e,toolName:r.toolName,argsTextDelta:n,sessionId:o})},p=()=>{c||(c=!0,a.push({type:`text_start`,sessionId:o}))},m=()=>{!c||l||(l=!0,a.push({type:`text_end`,content:e.currentResponse,sessionId:o}))},h=()=>{for(let[t,n]of s){if(!n.toolName)continue;let r={id:t,type:`function`,function:{name:n.toolName,arguments:n.argsText}};this._tools&&e.pendingToolCalls.push({toolCall:r}),a.push({type:`tool_call_end`,toolCall:r,sessionId:o})}s.clear()},g=(()=>{if(!i)return;let e={...i};return typeof e.maxOutputTokens!=`number`&&typeof i.maxTokens==`number`&&(e.maxOutputTokens=i.maxTokens),delete e.maxTokens,e})(),_=r?{model:r,messages:e.messages,tools:n,...g??{}}:{messages:e.messages,tools:n,...g??{}};try{for await(let n of this._modelClient.stream(_))if(N(t,`Session streaming`),n.type===`delta`)if(n.chunk.kind===`text`)p(),e.currentResponse+=n.chunk.text,a.push({type:`text_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.chunk.kind===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.chunk.text,a.push({type:`thinking_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_end`){let t=typeof n.chunk.text==`string`?n.chunk.text:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else n.chunk.kind===`tool_call_delta`&&f(n.chunk.callId,n.chunk.toolId,n.chunk.argsTextDelta);else if(n.type===`response_end`){m(),h(),e.lastModelStopReason=n.stopReason;let t=n.usage;if(t&&typeof t==`object`){let n=t;if(n.prompt_tokens||n.completion_tokens||n.total_tokens){let t={promptTokens:n.prompt_tokens??0,completionTokens:n.completion_tokens??0,totalTokens:n.total_tokens??0};e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.totalTokens+=t.totalTokens,this._recordUsage(t)}}}else if(n.type===`error`){let t=n.error?.code??`model_error`,r=n.error?.message??`Model error`,i=Error(`${t}: ${r}`);i.code=t,e.error=i,e.shouldContinue=!1,e.stopReason=`error`}else if(n.type===`text_delta`)p(),e.currentResponse+=n.delta,a.push({type:`text_delta`,delta:n.delta,sessionId:o});else if(n.type===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.type===`thinking_end`){let t=typeof n.content==`string`?n.content:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else if(n.type===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.content,a.push({type:`thinking_delta`,delta:n.content,sessionId:o});else if(n.type===`tool_call`&&this._tools){let t=n.toolCall;a.push({type:`tool_call_start`,callId:t.id,toolName:t.function.name,sessionId:o}),e.pendingToolCalls.push({toolCall:t}),a.push({type:`tool_call_end`,toolCall:t,sessionId:o})}else n.type===`usage`&&(e.usage.promptTokens+=n.usage.promptTokens,e.usage.completionTokens+=n.usage.completionTokens,e.usage.totalTokens+=n.usage.totalTokens,this._recordUsage(n.usage))}catch(t){if(t instanceof j)throw t;e.error=t instanceof Error?t:Error(String(t)),e.shouldContinue=!1,e.stopReason=`error`}finally{m(),s.size>0&&h()}return a}async executeToolCall(e,t,n,r){N(n,`Tool execution: ${e.toolCall.function.name}`);let i=r?new P(r):void 0,a=e.toolCall.id,o=e.toolCall,s=o,c=e=>({sessionId:t.sessionId,agentId:t.agentId,toolCall:e,toolContext:t});if(i){let n=await i.executePreToolUse(c(s));if(!n.allow)return e.result=`Tool execution blocked by PreToolUse hook`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};n.modifiedToolCall&&(s={...n.modifiedToolCall,id:a,type:o.type})}let l=this._tools?.get(s.function.name);if(!l)return e.result=`Tool not found: ${s.function.name}`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};try{let n=typeof s.function.arguments==`string`?JSON.parse(s.function.arguments):s.function.arguments;return e.result=await l.execute(n,t),e.isError=!1,i&&await i.executePostToolUse(c(s),e.result),{type:`tool_result`,tool_call_id:a,result:e.result,sessionId:t.sessionId}}catch(n){let r=n instanceof Error?n:Error(String(n));return e.result=r.message,e.isError=!0,i&&await i.executePostToolUseFailure(c(s),r),{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId}}}createToolExecutionContext(e,t){return{sessionId:e.sessionId,agentId:e.agentId,signal:t,usage:e.usage}}mergeStateResults(e,t){e.currentResponse=t.currentResponse,e.currentThinking=t.currentThinking,e.pendingToolCalls=t.pendingToolCalls,e.usage=t.usage}addToolResultToHistory(e,t){let n=t.result,r,i=t.isError;if(typeof n==`string`)r=n;else if(n&&typeof n==`object`&&`content`in n){let e=n;r=JSON.stringify(e.content),e.isError===!0&&(i=!0)}else r=JSON.stringify(n);e.messages.push({role:`tool`,tool_call_id:t.toolCall.id,content:r,...i?{isError:!0}:{}})}addAssistantMessageWithToolCalls(e){let t=typeof e.currentThinking==`string`?e.currentThinking:void 0;e.messages.push({role:`assistant`,content:e.currentResponse||``,tool_calls:e.pendingToolCalls.map(e=>e.toolCall),...t&&t.length>0?{reasoning_content:t}:{}})}addFinalAssistantMessage(e){e.currentResponse&&e.messages.push({role:`assistant`,content:e.currentResponse})}async*_streamWithState(e,t){let n=t.maxIterations??10,r=t.signal,i=this._tools?.toOpenAIFormat(),a=F(this._middlewares),o=this.createToolExecutionContext(e,r),s=this._stateStore,c=s?.savePoint??`before`,l=s?.deleteOnComplete??!0,u=t.model?{modelId:t.model.modelId,provider:t.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0;for(;e.shouldContinue;){if(N(r,`Session iteration ${e.iteration}`),e.iteration>=n){e.shouldContinue=!1,e.stopReason=`max_iterations`,yield{type:`done`,finalResponse:e.currentResponse,stopReason:`max_iterations`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(yield{type:`iteration_start`,iteration:e.iteration,sessionId:e.sessionId},e.pendingToolCalls.length>0){try{yield*this.handleToolCalls(e,o,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:s,checkpointModelConfig:u,requestParams:t.requestParams})}catch(e){if(e instanceof M)return;throw e}continue}if(e.currentResponse=``,e.currentThinking=void 0,e.pendingToolCalls=[],e.lastModelStopReason=void 0,s&&(c===`before`||c===`both`)){let n=_(e,{agentName:this._agentName,modelConfig:u,requestParams:t.requestParams});await s.saveCheckpoint(n)}let d=[],f=await a(e,async e=>(N(r,`Session model call`),d=await this.executeModelStream(e,r,i,t.model,t.requestParams),e));if(this.mergeStateResults(e,f),s&&(c===`after`||c===`both`)){let n=_(e,{agentName:this._agentName,modelConfig:u,requestParams:t.requestParams});await s.saveCheckpoint(n)}for(let e of d)yield e;if(N(r,`Session iteration ${e.iteration}`),e.stopReason===`error`){yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:e.pendingToolCalls.length,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`error`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(e.pendingToolCalls.length>0)try{yield*this.handleToolCalls(e,o,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:s,checkpointModelConfig:u,requestParams:t.requestParams})}catch(e){if(e instanceof M)return;throw e}else yield*this.handleFinalResponse(e);if(!e.shouldContinue){s&&l&&await s.deleteCheckpoint(e.sessionId);break}}}static APPROVAL_REQUIRED_LEVELS=new Set([`high`,`critical`]);requiresApproval(t){return e.APPROVAL_REQUIRED_LEVELS.has(t)}async*handleToolCalls(e,t,n){let r=e.pendingToolCalls.length,i=n?.signal,a=n?.toolContextInput?.approval,o=a?.strategy??`high_risk`,s=a?.autoApprove!==!0&&(a?.strategy!=null||a?.decisions!=null),c=a?.decisions??{},l=e=>s?o===`all`?!0:this.requiresApproval(e):!1,u=t=>e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)}),d=t=>{u(t)||this.addAssistantMessageWithToolCalls(e)},f=t=>e.messages.some(e=>e&&typeof e==`object`&&e.role===`tool`&&e.tool_call_id===t),p=new Set,m=e=>{try{return typeof e.function.arguments==`string`?JSON.parse(e.function.arguments):e.function.arguments}catch{return{_raw:e.function.arguments}}},h=t=>{let n=[];for(let r=t;r<e.pendingToolCalls.length;r++){let t=e.pendingToolCalls[r];if(f(t.toolCall.id)||p.has(t.toolCall.id)||c[t.toolCall.id])continue;let i=this._tools?.get(t.toolCall.function.name),a=i?.riskLevel??`safe`;!i||!l(a)||(p.add(t.toolCall.id),n.push({type:`tool_approval_requested`,tool_call_id:t.toolCall.id,toolName:t.toolCall.function.name,riskLevel:a,args:m(t.toolCall),sessionId:e.sessionId}))}return n};for(let r=0;r<e.pendingToolCalls.length;r++){let a=e.pendingToolCalls[r];if(f(a.toolCall.id)){e.pendingToolCalls.splice(r,1),r--;continue}let o=this._tools?.get(a.toolCall.function.name),s=o?.riskLevel??`safe`;if(o&&l(s)){let t=a.toolCall.function.name,i=c[a.toolCall.id];if(!i){e.stopReason=`approval_required`;for(let e of h(r))yield e;let i=_(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for approval: ${t}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(i),yield{type:`requires_action`,kind:`tool_approval`,checkpoint:n?.stateStore?void 0:i,checkpointRef:n?.stateStore?{sessionId:i.sessionId,agentId:i.agentId}:void 0,sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new M}if(!i.approved){let t=i.reason??`User denied approval`;a.result=`Tool execution skipped: ${t}`,a.isError=!0,d(a.toolCall.id),yield{type:`tool_skipped`,tool_call_id:a.toolCall.id,toolName:a.toolCall.function.name,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:a.toolCall.id,result:a.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,a),e.pendingToolCalls.splice(r,1),r--;continue}}d(a.toolCall.id),yield await this.executeToolCall(a,t,i,n?.hooks),this.addToolResultToHistory(e,a),e.pendingToolCalls.splice(r,1),r--}e.pendingToolCalls=[],e.iteration++,yield{type:`iteration_end`,iteration:e.iteration-1,willContinue:!0,toolCallCount:r,usage:{...e.usage},sessionId:e.sessionId}}async*handleFinalResponse(e){e.shouldContinue=!1,e.stopReason=`final_response`,this.addFinalAssistantMessage(e),yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:0,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`final_response`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId}}async _finalizeRun(e,t){this.messages=e.messages.filter(e=>e.role!==`system`),e.usage.totalTokens>0&&this.addUsage(e.usage);let n=Date.now()-t;this.recordResponse(n),await this.save()}async save(){let e=this.toSnapshot();await this._stateStore.save(this.id,T.SESSION,e)}async load(){let e=await this._stateStore.load(this.id,T.SESSION);return e?(this.restoreFromSnapshot(e),!0):!1}setStatus(e,t){super.setStatus(e,t),this._autoSave&&this.save().catch(()=>{})}markActive(){super.markActive(),this._autoSave&&this.save().catch(()=>{})}addMessage(e){super.addMessage(e),this._autoSave&&this.save().catch(()=>{})}addUsage(e){super.addUsage(e),this._autoSave&&this.save().catch(()=>{})}recordResponse(e){super.recordResponse(e),this._autoSave&&this.save().catch(()=>{})}incrementToolCallCount(){super.incrementToolCallCount(),this._autoSave&&this.save().catch(()=>{})}setModelOverride(e){super.setModelOverride(e),this._modelOverride=this.resolveModelRef(e)??this._modelOverride,this._autoSave&&this.save().catch(()=>{})}clearModelOverride(){super.clearModelOverride(),this._modelOverride=void 0,this._autoSave&&this.save().catch(()=>{})}setSystemPromptOverride(e){super.setSystemPromptOverride(e),this._autoSave&&this.save().catch(()=>{})}clearSystemPromptOverride(){super.clearSystemPromptOverride(),this._autoSave&&this.save().catch(()=>{})}disableTools(e){super.disableTools(e),this._autoSave&&this.save().catch(()=>{})}enableAllTools(){super.enableAllTools(),this._autoSave&&this.save().catch(()=>{})}setAutoSave(e){this._autoSave=e}},fe=class extends le{_stateStore;constructor(e){super(),this._stateStore=e}async create(){let e=t(),n=Date.now(),r={id:e,createdAt:n,state:{status:`active`,updatedAt:n,lastActiveAt:n},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0}},i=new L(this._stateStore,e,r);return await i.save(),i}async get(e){let t=await this._stateStore.load(e,T.SESSION);if(t)return new L(this._stateStore,e,t)}async list(){let e=await this._stateStore.listSessions(),t=[];for(let n of e){let e=await this._stateStore.load(n,T.SESSION);if(e){let r=new L(this._stateStore,n,e);t.push(r)}}return t}async destroy(e){await this._stateStore.deleteSession(e)}},R=class{savePoint;deleteOnComplete;constructor(e){this.savePoint=e?.savePoint??`before`,this.deleteOnComplete=e?.deleteOnComplete??!0}async save(e,t,n){let r=this.buildPath(e,t),i=JSON.stringify(n,null,2);await this._write(r,i)}async load(e,t){let n=this.buildPath(e,t),r=await this._read(n);if(r!==void 0)try{return JSON.parse(r)}catch{return}}async delete(e,t){let n=this.buildPath(e,t);await this._delete(n)}async deleteSession(e){let t=this.buildPrefix(e),n=await this._list(t);await Promise.all(n.map(e=>this._delete(e)))}async listKeys(e){let t=this.buildPrefix(e);return(await this._list(t)).map(t=>this.extractKey(e,t))}async exists(e,t){let n=this.buildPath(e,t);return this._exists(n)}async saveCheckpoint(e){let t={_meta:{description:`GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY`,savedAt:new Date().toISOString(),agentId:e.agentId,agentName:e.agentName,sessionId:e.sessionId,iteration:e.iteration,phase:e.phase,status:e.status,messageCount:e.messages.length,toolCallsPending:e.pendingToolCalls?.length??0},checkpoint:e};await this.save(e.sessionId,T.CHECKPOINT,t)}async loadCheckpoint(e){return(await this.load(e,T.CHECKPOINT))?.checkpoint}async deleteCheckpoint(e){await this.delete(e,T.CHECKPOINT)}async listCheckpoints(){let e=await this.listSessions(),t=[];for(let n of e){let e=await this.loadCheckpoint(n);e&&t.push(e)}return t}async listSessions(){let e=await this._list(``),t=new Set;for(let n of e){let e=this.extractSessionId(n);e&&t.add(e)}return Array.from(t)}buildPath(e,t){return`${e}/${t}`}buildPrefix(e){return`${e}/`}extractKey(e,t){let n=this.buildPrefix(e);return t.startsWith(n)?t.slice(n.length):t}extractSessionId(e){let t=e.split(`/`);return t.length>0?t[0]:void 0}},z=class extends R{baseDir;constructor(e){super(e),this.baseDir=c.resolve(e.dir),this.ensureDir(this.baseDir)}async _write(e,t){let n=this.toFilePath(e);this.ensureDir(c.dirname(n)),s(n,t,`utf-8`)}async _read(e){let t=this.toFilePath(e);try{return n(t)?i(t,`utf-8`):void 0}catch{return}}async _delete(e){let t=this.toFilePath(e);n(t)&&o(t);let r=c.dirname(t);if(n(r))try{a(r).length===0&&o(r,{recursive:!0})}catch{}}async _exists(e){return n(this.toFilePath(e))}async _list(e){let t=[];if(!n(this.baseDir))return t;let r=a(this.baseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let n of r){if(e&&!n.startsWith(e.split(`/`)[0]))continue;let r=c.join(this.baseDir,n),i=this.listJsonFiles(r);for(let r of i){let i=`${n}/${c.basename(r,`.json`)}`;(!e||i.startsWith(e))&&t.push(i)}}return t}toFilePath(e){return c.join(this.baseDir,`${e}.json`)}ensureDir(e){n(e)||r(e,{recursive:!0})}listJsonFiles(e){return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>c.join(e,t)):[]}getBaseDir(){return this.baseDir}clear(){n(this.baseDir)&&(o(this.baseDir,{recursive:!0}),r(this.baseDir,{recursive:!0}))}},B=class extends R{store=new Map;constructor(e){super(e)}async _write(e,t){this.store.set(e,t)}async _read(e){return this.store.get(e)}async _delete(e){this.store.delete(e)}async _exists(e){return this.store.has(e)}async _list(e){let t=[];for(let n of this.store.keys())(e===``||n.startsWith(e))&&t.push(n);return t}clear(){this.store.clear()}stats(){let e=new Set;for(let t of this.store.keys()){let n=this.extractSessionId(t);n&&e.add(n)}return{entryCount:this.store.size,sessionCount:e.size}}},pe=class{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];constructor(e){this.id=e.id??crypto.randomUUID(),this.name=e.name,this.systemPrompt=e.systemPrompt,this.createdAt=Date.now(),this._model=e.model,this._tools=e.tools,this._stateStore=e.stateStore??new B,this._sessionManager=new fe(this._stateStore)}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get modelRefs(){let e=this._model.modelRefs;if(Array.isArray(e))return e;let t=this._model.modelRef;return t?[t]:[]}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession(e){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let t=await this._sessionManager.create();if(!this._stateStore)throw Error(`StateStore is required to create sessions`);let n=t.toSnapshot();return new L(this._stateStore,t.id,n,{...e,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares,hasCheckpoint:!1})}async resumeSession(e,t){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let n=await this._sessionManager.get(e);if(!n)throw Error(`Session not found: ${e}`);let r=!!await this._stateStore?.loadCheckpoint(e);if(!this._stateStore)throw Error(`StateStore is required to resume sessions`);let i=n.toSnapshot();return new L(this._stateStore,n.id,i,{...t,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares,hasCheckpoint:r})}use(e){return this._middlewares.push(e),this}setModel(e){(e=>!!(e&&typeof e==`object`&&typeof e.provider==`string`&&typeof e.modelId==`string`&&typeof e.stream!=`function`))(e)?this._modelOverride=e:(this._model=e,this._modelOverride=void 0)}},me=class{},V=class extends Error{code;retryable;status;constructor(e,t){super(e),this.name=`ModelError`,this.code=t.code,this.retryable=t.retryable??!1,this.status=t.status}},he=class{state=new Map;get(e){return this.state.get(this.keyOf(e))||{failures:0,nextRetryAt:0}}markSuccess(e){this.state.set(this.keyOf(e),{failures:0,nextRetryAt:0})}markFailure(e,t){let n=this.get(e).failures+1,r=Math.min(t.maxDelayMs,t.baseDelayMs*2**Math.min(8,n-1));this.state.set(this.keyOf(e),{failures:n,nextRetryAt:t.now+r,lastError:{code:t.code,message:t.message}})}isAvailable(e,t){return this.get(e).nextRetryAt<=t}keyOf(e){return`${e.provider}:${e.modelId}`}},H=class extends he{},ge=class{constructor(e,t){this.health=e,this.fallbackOrder=t}select(e){let{now:t}=e,n=this.fallbackOrder.filter(e=>this.health.isAvailable(e,t));return n.length?n:this.fallbackOrder}},U=class{static isRetryableStatus(e){return e===408||e===409||e===429||e>=500&&e<=599}static async sleep(e,t){return e<=0?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{a(),n()},e);function a(){clearTimeout(i),t&&t.removeEventListener(`abort`,o)}function o(){a(),r(Error(`Aborted`))}if(t){if(t.aborted)return o();t.addEventListener(`abort`,o)}})}};function W(e=`req`){let t=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${t}`}var G=class e{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor(e={}){this.maxAttempts=e.maxAttempts??3,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.strategy=e.strategy??`exponential`,this.jitter=e.jitter??`equal`,this.multiplier=e.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay(e){let t;switch(this.strategy){case`exponential`:t=this.baseDelayMs*this.multiplier**(e-1);break;case`linear`:t=this.baseDelayMs*e;break;case`fixed`:t=this.baseDelayMs;break}return t=Math.min(t,this.maxDelayMs),t=this.applyJitter(t),this._previousDelay=t,Math.floor(t)}applyJitter(e){switch(this.jitter){case`full`:return Math.random()*e;case`equal`:return e/2+Math.random()*e/2;case`decorrelated`:return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case`none`:default:return e}}canRetry(e){return e<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new e;static aggressive=new e({maxAttempts:5,baseDelayMs:1e3,maxDelayMs:6e4});static gentle=new e({maxAttempts:3,baseDelayMs:2e3,maxDelayMs:3e4,jitter:`full`})};function _e(e){let t=new Map(e.adapters.map(e=>[e.provider,e])),n=e.health??new H,r=e.routing?.fallbackOrder??(()=>{let t=[];for(let n of e.adapters)n.defaultModelId&&t.push({provider:n.provider,modelId:n.defaultModelId});if(t.length===0)throw new V(`No routing configuration and no adapter with defaultModelId provided. Either provide options.routing.fallbackOrder or set defaultModelId on your adapters.`,{code:`missing_routing`,retryable:!1});return t})(),i=new ge(n,r),a=new G({maxAttempts:e.retry?.maxAttemptsPerModel??3,baseDelayMs:e.retry?.baseDelayMs??500,maxDelayMs:e.retry?.maxDelayMs??3e4,strategy:e.retry?.strategy??`exponential`,jitter:e.retry?.jitter??`equal`}),o=e.timeoutMs??6e4;function s(e){let n=t.get(e.provider);if(!n)throw new V(`No adapter for provider: ${e.provider}`,{code:`adapter_missing`,retryable:!1});return n}async function*c(t){let r=Date.now(),c=t.requestId||W(`req`),{model:l,...u}=t,d=t.model?[t.model]:i.select({now:r}),f;for(let r of d){let i=s(r),l=t.timeoutMs??o,d=new AbortController,p=t.signal,m=setTimeout(()=>d.abort(),l),h=()=>d.abort();p&&(p.aborted?d.abort():p.addEventListener(`abort`,h));let g={...u,requestId:c,model:r,stream:t.stream??!0,signal:d.signal,timeoutMs:l};try{for(let t=1;t<=a.maxAttempts;t++)try{for await(let e of i.stream({request:g}))yield e;n.markSuccess(r);return}catch(n){f=n;let i=K(n);if(!i.retryable||!a.canRetry(t))throw i;let o=a.getDelay(t);e.retry?.onRetry?.({attempt:t,maxAttempts:a.maxAttempts,delayMs:o,error:{code:i.code,message:i.message,retryable:i.retryable},model:r,request:g}),await U.sleep(o,d.signal)}}catch(e){let t=K(e);n.markFailure(r,{now:Date.now(),baseDelayMs:a.baseDelayMs,maxDelayMs:a.maxDelayMs,code:t.code,message:t.message}),yield{type:`error`,requestId:c,error:{code:t.code,message:t.message,retryable:t.retryable}},f=t;continue}finally{clearTimeout(m),p&&p.removeEventListener(`abort`,h)}}throw K(f||new V(`All models failed`,{code:`all_models_failed`}))}async function l(e){let t=``,n=`error`,r,i,a=e.requestId||``;for await(let o of c({...e,stream:!0}))o.type===`response_start`?(a=o.requestId,i=o.model):o.type===`delta`&&o.chunk.kind===`text`?t+=o.chunk.text:o.type===`text_delta`?t+=o.delta:o.type===`response_end`?(n=o.stopReason,r=o.usage):o.type===`error`&&(n=`error`);if(!i)throw new V(`Missing response_start from adapter`,{code:`protocol_error`,retryable:!1});return{requestId:a,model:i,text:t,stopReason:n,usage:r}}return{get modelId(){return r[0]?.modelId??`unknown`},get modelRef(){return r[0]},get modelRefs(){return[...r]},setModelId(e){let t=r[0];if(!t)throw new V(`No primary model to update`,{code:`no_primary_model`,retryable:!1});r[0]={provider:t.provider,modelId:e}},invoke:async(e,t)=>{let n=await l({messages:e,tools:t?.tools});return{message:{role:`assistant`,content:n.text},usage:n.usage}},stream:((e,t)=>c(Array.isArray(e)?{messages:e,tools:t?.tools}:e)),run:l}}function K(e){if(e instanceof V)return e;if(e&&typeof e==`object`){let t=typeof e.status==`number`?e.status:void 0,n=typeof e.code==`string`?e.code:t?`http_${t}`:`unknown_error`;return new V(typeof e.message==`string`?e.message:`Unknown error`,{code:n,retryable:t?U.isRetryableStatus(t):!1,status:t})}return new V(String(e||`Unknown error`),{code:`unknown_error`,retryable:!1})}function ve(e){function t(e,t){if(typeof e!=`string`)return``;let n=e.trim();return n?/^data:/i.test(n)||/^https?:\/\//i.test(n)?n:typeof t==`string`&&t.trim()?`data:${t.trim()};base64,${n}`:n:``}if(typeof e==`string`)return e.trim().length===0?``:e;if(e==null)return``;if(typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`&&n.text)return n.text;if(n.type===`image`){let e=t(n.data??n.source?.data,n.mimeType??n.source?.media_type??n.source?.mimeType);return e?[{type:`image_url`,image_url:{url:e}}]:``}}if(Array.isArray(e)){let n=[];for(let r of e)if(typeof r==`string`)n.push({type:`text`,text:r});else if(r&&typeof r==`object`&&`type`in r){let e=r;if(e.type===`text`&&e.text)n.push({type:`text`,text:e.text});else if(e.type===`image`){let r=t(e.data??e.source?.data,e.mimeType??e.source?.media_type??e.source?.mimeType);r&&n.push({type:`image_url`,image_url:{url:r}})}}return n.length>0?n:``}return String(e)}function ye(e){return{...e,content:ve(e.content)}}function be(e,t){return typeof t==`string`&&/deepseek/i.test(t)?!0:/^deepseek-/i.test(e)}function xe(e={}){let t=e.baseUrl;function n(){if(typeof e.apiKey==`string`){if(!e.apiKey.trim())throw new V(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return e.apiKey}let t=typeof process<`u`?process.env?.OPENAI_API_KEY:void 0;if(!t)throw new V(`Missing OPENAI_API_KEY`,{code:`missing_api_key`,retryable:!1});return t}function r(){let r=n();return typeof t==`string`&&/\/chat\/completions\/?$/.test(t)?new l({apiKey:r,organization:e.organization,project:e.project,baseURL:`https://api.openai.com/v1`,fetch:(e,n)=>fetch(t,n)}):new l({apiKey:r,organization:e.organization,project:e.project,baseURL:t||void 0})}function i(e){return{provider:`openai`,modelId:e.model.modelId}}function a(e){if(e instanceof V)return e;let t=typeof e?.status==`number`?e.status:void 0;return new V(typeof e?.message==`string`?e.message:`OpenAI error`,{code:typeof e?.code==`string`?e.code:t?`openai_http_${t}`:`openai_error`,retryable:t?U.isRetryableStatus(t):!1,status:t})}async function*o(n){let{request:o}=n,s=o.requestId||W(`req`),c=r(),l=o.model.modelId,u=e.compat?.requireReasoningContentForToolCalls,d=typeof u==`boolean`?u:be(l,t),f=o.stream!==!1,p=[];if(o.messages&&Array.isArray(o.messages))for(let e of o.messages){let t=ye(e);if(!d&&t&&typeof t==`object`)`reasoning_content`in t&&delete t.reasoning_content;else if(d&&t?.role===`assistant`&&Array.isArray(t?.tool_calls)&&t.tool_calls.length>0){let e=t.reasoning_content;(typeof e!=`string`||e.length===0)&&(t.reasoning_content=``)}p.push(t)}else typeof o.instructions==`string`&&o.instructions.length>0&&p.push({role:`system`,content:o.instructions}),p.push({role:`user`,content:o.input});let m=(()=>{let e=o.reasoning?.effort;if(typeof e==`string`&&(e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`))return e})(),h={model:l,messages:p,stream:f,stream_options:f?{include_usage:!0}:void 0,metadata:o.metadata??void 0,reasoning_effort:m,max_completion_tokens:o.maxOutputTokens??void 0,stop:o.stop??void 0,temperature:o.temperature??void 0,top_p:o.topP??void 0,presence_penalty:o.presencePenalty??void 0,frequency_penalty:o.frequencyPenalty??void 0,seed:o.seed??void 0};o.tools&&Array.isArray(o.tools)&&o.tools.length>0&&(h.tools=o.tools);try{if(yield{type:`response_start`,requestId:s,model:i(o)},!f){let e=await c.chat.completions.create({...h,stream:!1},{signal:o.signal,timeout:o.timeoutMs}),t=Array.isArray(e?.choices)?e.choices[0]:void 0,n=t?.message,r=typeof n?.reasoning_content==`string`?n.reasoning_content:``;r.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:r}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:r}});let i=typeof n?.content==`string`?n.content:``;i.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:i}});let a=Array.isArray(n?.tool_calls)?n.tool_calls:[];for(let e=0;e<a.length;e++){let t=a[e],n=typeof t?.id==`string`?t.id:`call_${e}`,r=typeof t?.function?.name==`string`?t.function.name:void 0,i=typeof t?.function?.arguments==`string`?t.function.arguments:void 0;(i||r)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:i}})}yield{type:`response_end`,requestId:s,stopReason:q(t?.finish_reason),usage:e?.usage};return}let e=await c.chat.completions.create({...h,stream:!0},{signal:o.signal,timeout:o.timeoutMs}),t=null,n,r=new Map,a=!1,l=``;for await(let i of e){i?.usage!=null&&(n=i.usage);let e=Array.isArray(i?.choices)?i.choices:[];for(let n of e){n?.finish_reason!=null&&(t=n.finish_reason);let e=n?.delta,i=e?.reasoning_content;typeof i==`string`&&i.length>0&&(a||(a=!0,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}}),l+=i,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:i}});let o=e?.content;typeof o==`string`&&o.length>0&&(a&&(a=!1,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:o}});let c=Array.isArray(e?.tool_calls)?e.tool_calls:[];for(let e of c){let t=typeof e?.index==`number`?e.index:0,n=r.get(t)||(typeof e?.id==`string`?e.id:`call_${t}`);r.set(t,n);let i=typeof e?.function?.name==`string`?e.function.name:void 0,a=typeof e?.function?.arguments==`string`?e.function.arguments:void 0;(i||a)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:i,argsTextDelta:a}})}}}a&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`response_end`,requestId:s,stopReason:q(t),usage:n}}catch(e){throw e?.name===`AbortError`?new V(`Aborted`,{code:`aborted`,retryable:!1}):a(e)}}return{provider:`openai`,defaultModelId:e.defaultModelId,stream:o}}function q(e){return e===`tool_calls`||e===`function_call`?`tool_call`:e===`length`?`length`:e===`content_filter`?`error`:`final`}function Se(e){return{content:[{type:`text`,text:e}]}}function J(e){return{content:[{type:`text`,text:e}],isError:!0}}function Ce(e,t){return{content:[{type:`image`,data:e,mimeType:t}]}}var Y=class{riskLevel=`safe`};const X=1e3;function we(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`*`)e[n+1]===`*`?e[n+2]===`/`?(t+=`(?:.*\\/)?`,n+=3):(t+=`.*`,n+=2):(t+=`[^/]*`,n++);else if(r===`?`)t+=`[^/]`,n++;else if(r===`{`){let r=e.indexOf(`}`,n);if(r!==-1){let i=e.slice(n+1,r).split(`,`);t+=`(?:${i.map(e=>Te(e)).join(`|`)})`,n=r+1}else t+=`\\{`,n++}else if(r===`[`){let r=e.indexOf(`]`,n);r===-1?(t+=`\\[`,n++):(t+=e.slice(n,r+1),n=r+1)}else r===`.`?(t+=`\\.`,n++):r===`/`?(t+=`\\/`,n++):`()[]{}^$+|\\`.includes(r)?(t+=`\\${r}`,n++):(t+=r,n++)}return RegExp(`^${t}$`)}function Te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var Ee=class extends Y{name=`Glob`;description=`Fast file pattern matching tool that works with any codebase size.
|
|
227
|
+
Usage notes:
|
|
228
|
+
- When editing, preserve the exact indentation (tabs/spaces) from the original file
|
|
229
|
+
- The edit will FAIL if old_string is not unique in the file unless replace_all is true
|
|
230
|
+
- Use replace_all for replacing/renaming strings across the entire file
|
|
231
|
+
- old_string and new_string must be different
|
|
232
|
+
- ALWAYS prefer editing existing files over creating new ones`;parameters={type:"object",properties:{file_path:{type:"string",description:"The absolute path to the file to modify"},old_string:{type:"string",description:"The text to replace"},new_string:{type:"string",description:"The text to replace it with (must be different from old_string)"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)"}},required:["file_path","old_string","new_string"]};cwd;constructor($){super();this.cwd=$?.cwd??UK.cwd()}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($){let{file_path:Z,old_string:Y,new_string:W,replace_all:J}=this.validateArgs($),Q=fY.isAbsolute(Z)?Z:fY.resolve(this.cwd,Z);try{if((await FK(Q)).isDirectory())return X1(`Path is a directory, not a file: ${Q}`)}catch(F){if(F.code==="ENOENT")return X1(`File not found: ${Q}`);throw F}let X=await BK(Q,"utf-8"),K=this.countOccurrences(X,Y);if(K===0)return X1(`old_string not found in file: ${Q}
|
|
233
|
+
|
|
234
|
+
Searched for:
|
|
235
|
+
${this.truncateForError(Y)}`);if(K>1&&!J)return X1(`old_string is not unique in the file (found ${K} occurrences). Either provide more context to make it unique, or set replace_all: true to replace all occurrences.`);let V,B;if(J)V=X.split(Y).join(W),B=K;else{let F=X.indexOf(Y);V=X.slice(0,F)+W+X.slice(F+Y.length),B=1}await qK(Q,V,"utf-8");let G={success:!0,replacements:B,filePath:Q,message:`Successfully replaced ${B} occurrence${B>1?"s":""} in ${fY.basename(Q)}`};return{content:[{type:"text",text:G.message}],structuredContent:G}}validateArgs($){let{file_path:Z,old_string:Y,new_string:W}=$;if(typeof Z!=="string"||!Z.trim())throw Error("file_path is required and must be a non-empty string");if(typeof Y!=="string")throw TypeError("old_string is required and must be a string");if(Y==="")throw Error("old_string cannot be empty");if(typeof W!=="string")throw TypeError("new_string is required and must be a string");if(Y===W)throw Error("new_string must be different from old_string");return{file_path:Z.trim(),old_string:Y,new_string:W,replace_all:$.replace_all===!0}}countOccurrences($,Z){let Y=0,W=$.indexOf(Z);while(W!==-1)Y++,W=$.indexOf(Z,W+Z.length);return Y}truncateForError($,Z=200){if($.length<=Z)return $;return`${$.slice(0,Z)}... [truncated, ${$.length} chars total]`}}class uZ extends Z1{name="ExitPlanMode";riskLevel="safe";description=`Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
|
|
236
|
+
|
|
237
|
+
## How This Tool Works
|
|
238
|
+
- You should have already written your plan to the plan file specified in the plan mode system message
|
|
239
|
+
- This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
|
|
240
|
+
- This tool simply signals that you're done planning and ready for the user to review and approve
|
|
241
|
+
- The user will see the contents of your plan file when they review it
|
|
242
|
+
|
|
243
|
+
## When to Use This Tool
|
|
244
|
+
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
|
|
245
|
+
|
|
246
|
+
## Handling Ambiguity in Plans
|
|
247
|
+
Before using this tool, ensure your plan is clear and unambiguous. If there are multiple valid approaches or unclear requirements:
|
|
248
|
+
1. Use the AskUserQuestion tool to clarify with the user
|
|
249
|
+
2. Ask about specific implementation choices (e.g., architectural patterns, which library to use)
|
|
250
|
+
3. Clarify any assumptions that could affect the implementation
|
|
251
|
+
4. Edit your plan file to incorporate user feedback
|
|
252
|
+
5. Only proceed with ExitPlanMode after resolving ambiguities and updating the plan file
|
|
253
|
+
|
|
254
|
+
## Examples
|
|
255
|
+
|
|
256
|
+
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
|
|
257
|
+
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
|
|
258
|
+
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
|
|
259
|
+
`;parameters={type:"object",properties:{},additionalProperties:!0};async execute($){return{content:[{type:"text",text:"Exited plan mode. Your plan has been submitted for user review and approval. The user will review your plan file and decide whether to approve, reject, or request modifications."}],structuredContent:{success:!0,message:"Exited plan mode. Your plan has been submitted for user review and approval. The user will review your plan file and decide whether to approve, reject, or request modifications."}}}}import{readdir as HK,stat as j5}from"fs/promises";import p8 from"path";import NK from"process";var TY=1000,MK=20;function wK($){let Z="",Y=0;while(Y<$.length){let W=$[Y];if(W==="*")if($[Y+1]==="*")if($[Y+2]==="/")Z+="(?:.*\\/)?",Y+=3;else Z+=".*",Y+=2;else Z+="[^/]*",Y++;else if(W==="?")Z+="[^/]",Y++;else if(W==="{"){let J=$.indexOf("}",Y);if(J!==-1){let Q=$.slice(Y+1,J).split(",");Z+=`(?:${Q.map((X)=>LK(X)).join("|")})`,Y=J+1}else Z+="\\{",Y++}else if(W==="["){let J=$.indexOf("]",Y);if(J!==-1)Z+=$.slice(Y,J+1),Y=J+1;else Z+="\\[",Y++}else if(W===".")Z+="\\.",Y++;else if(W==="/")Z+="\\/",Y++;else if("()[]{}^$+|\\".includes(W))Z+=`\\${W}`,Y++;else Z+=W,Y++}return new RegExp(`^${Z}$`)}function LK($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}class i8 extends Z1{name="Glob";description=`Fast file pattern matching tool that works with any codebase size.
|
|
116
260
|
|
|
117
261
|
Usage notes:
|
|
118
262
|
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
@@ -125,57 +269,197 @@ Supported patterns:
|
|
|
125
269
|
- \`**\` matches any sequence of characters including path separator
|
|
126
270
|
- \`?\` matches any single character
|
|
127
271
|
- \`{a,b}\` matches either a or b
|
|
128
|
-
- \`[abc]\` matches any character in brackets`;parameters={type
|
|
129
|
-
|
|
272
|
+
- \`[abc]\` matches any character in brackets`;parameters={type:"object",properties:{pattern:{type:"string",description:"The glob pattern to match files against"},path:{type:"string",description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior.'}},required:["pattern"]};cwd;constructor($){super();this.cwd=$?.cwd??NK.cwd()}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($){let{pattern:Z,path:Y}=this.validateArgs($),W=Y?p8.isAbsolute(Y)?Y:p8.resolve(this.cwd,Y):this.cwd;try{if(!(await j5(W)).isDirectory())return X1(`Path is not a directory: ${W}`)}catch(F){if(F.code==="ENOENT")return X1(`Directory not found: ${W}`);throw F}let J=Z;if(!Z.startsWith("**/")&&!Z.startsWith("/")&&!Z.startsWith("./"))J=`**/${Z}`;let Q=wK(J),X=[];await this.walkDirectory(W,"",Q,X,0),X.sort((F,z)=>z.mtime-F.mtime);let K=X.length>TY,V=X.slice(0,TY).map((F)=>F.path),B={files:V,totalMatches:X.length,truncated:K};return{content:[{type:"text",text:V.length>0?`Found ${X.length} file${X.length!==1?"s":""}${K?` (showing first ${TY})`:""}:
|
|
273
|
+
${V.join(`
|
|
274
|
+
`)}`:`No files found matching pattern: ${Z}`}],structuredContent:B}}validateArgs($){let Z=$.pattern;if(typeof Z!=="string"||!Z.trim())throw Error("Pattern is required and must be a non-empty string");let Y;if($.path!==void 0&&$.path!==null&&$.path!=="undefined"&&$.path!=="null"){if(typeof $.path!=="string")throw TypeError("Path must be a string");Y=$.path.trim()||void 0}return{pattern:Z.trim(),path:Y}}async walkDirectory($,Z,Y,W,J){if(J>MK)return;let Q=Z?p8.join($,Z):$,X;try{X=await HK(Q,{withFileTypes:!0})}catch{return}for(let K of X){if(K.name.startsWith(".")||K.name==="node_modules")continue;let V=Z?`${Z}/${K.name}`:K.name;if(K.isDirectory())await this.walkDirectory($,V,Y,W,J+1);else if(K.isFile()){if(Y.test(V))try{let B=p8.join(Q,K.name),G=await j5(B);W.push({path:V,mtime:G.mtimeMs})}catch{}}}}}var T7=y7(e2(),1),DJ=y7(_J(),1);import{Buffer as dq}from"buffer";import{spawn as f7}from"child_process";import{chmodSync as uq,existsSync as tZ,mkdirSync as cq,statSync as lq}from"fs";import{copyFile as pq,mkdtemp as iq,readdir as nq,readFile as rq,rm as OJ,stat as aq,writeFile as oq}from"fs/promises";import T1 from"path";import j0 from"process";var D0=5000,j7=60000,sq="BurntSushi/ripgrep",jJ="latest",tq={"darwin-arm64":{arch:"aarch64",os:"apple-darwin"},"darwin-x64":{arch:"x86_64",os:"apple-darwin"},"linux-arm64":{arch:"aarch64",os:"unknown-linux-musl"},"linux-x64":{arch:"x86_64",os:"unknown-linux-musl"},"win32-x64":{arch:"x86_64",os:"pc-windows-msvc"},"win32-arm64":{arch:"aarch64",os:"pc-windows-msvc"}};function P7($){try{return lq($).size>1e4}catch{return!1}}function fJ(){return j0.platform==="win32"?"rg.exe":"rg"}function S7(){let $=T1.join(dZ(),fJ());return tZ($)&&P7($)?$:null}function eq($){return $.code==="ENOENT"||$.message?.includes("ENOENT")||$.message?.includes("not found")}function TJ($,Z){return new Promise((Y,W)=>{let J=f7($,Z,{stdio:["ignore","pipe","pipe"]}),Q="",X="";J.stdout?.on("data",(K)=>{Q+=K.toString()}),J.stderr?.on("data",(K)=>{X+=K.toString()}),J.on("error",(K)=>{W(K)}),J.on("close",(K)=>{Y({exitCode:K,stdout:Q,stderr:X})})})}async function $U($,Z){let W=["-command",`Expand-Archive -Path '${$}' -DestinationPath '${Z}' -Force`],{exitCode:J,stderr:Q}=await TJ("powershell",W);if(J!==0)throw Error(`zip extraction failed (exit ${J}): ${Q}
|
|
275
|
+
|
|
276
|
+
Ensure PowerShell is available on your system.`)}async function ZU($,Z){let{exitCode:Y,stderr:W}=await TJ("tar",["-xzf",$,"-C",Z]);if(Y!==0)throw Error(`tar extraction failed (exit ${Y}): ${W}
|
|
277
|
+
|
|
278
|
+
Please install 'tar' (e.g., apt install tar, brew install gnu-tar).`)}async function PJ($,Z){let Y=await nq($,{withFileTypes:!0});for(let W of Y){let J=T1.join($,W.name);if(W.isFile()&&W.name===Z)return J;if(W.isDirectory()){let Q=await PJ(J,Z);if(Q)return Q}}return null}var sZ=null,U6=null,H6=null;async function YU($){if($!=="latest")return $;if(H6)return H6;try{let Z=new AbortController,Y=setTimeout(()=>Z.abort(),30000);try{let W=await fetch("https://api.github.com/repos/BurntSushi/ripgrep/releases/latest",{redirect:"follow",signal:Z.signal});if(!W.ok)throw Error(`HTTP ${W.status}: ${W.statusText}`);let Q=(await W.json())?.tag_name;if(!Q)throw Error("Missing tag_name in GitHub response.");return H6=Q.startsWith("v")?Q.slice(1):Q,H6}finally{clearTimeout(Y)}}catch(Z){return console.error(`[goat-chain] Failed to resolve latest ripgrep version: ${Z instanceof Error?Z.message:Z}`),null}}async function WU($=jJ){let Z=`${j0.platform}-${j0.arch}`,Y=tq[Z];if(!Y)return console.error(`[goat-chain] Unsupported platform for ripgrep: ${Z}`),null;let W=dZ(),J=fJ(),Q=T1.join(W,J);if(tZ(Q)&&P7(Q))return Q;let X=await YU($);if(!X)return null;let{arch:K,os:V}=Y,B=j0.platform==="win32"?"zip":"tar.gz",G=`ripgrep-${X}-${K}-${V}.${B}`,F=`https://github.com/${sq}/releases/download/${X}/${G}`;console.log("[goat-chain] Downloading ripgrep binary...");let z=null,N=T1.join(W,G);try{if(!tZ(W))cq(W,{recursive:!0});let q=new AbortController,w=setTimeout(()=>q.abort(),120000);try{let O=await fetch(F,{redirect:"follow",signal:q.signal});if(!O.ok)throw Error(`HTTP ${O.status}: ${O.statusText}`);let H=await O.arrayBuffer();await oq(N,dq.from(H))}finally{clearTimeout(w)}if(z=await iq(T1.join(W,"ripgrep-")),B==="zip")await $U(N,z);else await ZU(N,z);let A=await PJ(z,J);if(!A)throw Error("ripgrep binary not found in extracted archive.");if(await pq(A,Q),j0.platform!=="win32"&&tZ(Q))uq(Q,493);if(!P7(Q))throw Error("Downloaded ripgrep binary failed validation.");return console.log("[goat-chain] ripgrep binary ready."),Q}catch(q){return console.error(`[goat-chain] Failed to download ripgrep: ${q instanceof Error?q.message:q}`),null}finally{if(await OJ(N,{force:!0}).catch(()=>{}),z)await OJ(z,{recursive:!0,force:!0}).catch(()=>{})}}async function JU($=jJ){let Z=S7();if(Z)return Z;return WU($)}async function QU(){if(sZ!==null&&tZ(sZ))return sZ;if(U6)return U6;return U6=(async()=>{let $=S7();if($)return sZ=$,$;let Z=await JU();if(Z)return sZ=Z,Z;return null})(),U6}class N6 extends Z1{name="Grep";description=`A powerful search tool built on ripgrep.
|
|
130
279
|
|
|
131
280
|
Usage notes:
|
|
132
281
|
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
133
282
|
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
|
|
134
283
|
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
|
|
135
284
|
- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
|
|
136
|
-
- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
`)}let
|
|
140
|
-
|
|
141
|
-
`).filter(
|
|
142
|
-
`)}let
|
|
143
|
-
`).filter(
|
|
285
|
+
- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true
|
|
286
|
+
- If ripgrep is not available, this tool falls back to a JS-based search (slower). You can opt into downloading a ripgrep binary via the GrepTool constructor option \`allowDownload: true\`.`;parameters={type:"object",properties:{pattern:{type:"string",description:"The regular expression pattern to search for in file contents"},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:'Output mode: "content" shows matching lines, "files_with_matches" shows file paths (default), "count" shows match counts.'},"-B":{type:"number",description:'Number of lines to show before each match. Requires output_mode: "content".'},"-A":{type:"number",description:'Number of lines to show after each match. Requires output_mode: "content".'},"-C":{type:"number",description:'Number of lines to show before and after each match. Requires output_mode: "content".'},"-n":{type:"boolean",description:'Show line numbers in output. Requires output_mode: "content". Defaults to true.'},"-i":{type:"boolean",description:"Case insensitive search"},type:{type:"string",description:"File type to search (e.g., js, py, rust, go, java). More efficient than glob for standard file types."},head_limit:{type:"number",description:"Limit output to first N lines/entries. Defaults to 0 (unlimited)."},offset:{type:"number",description:"Skip first N lines/entries before applying head_limit. Defaults to 0."},multiline:{type:"boolean",description:"Enable multiline mode where . matches newlines and patterns can span lines. Default: false."}},required:["pattern"]};cwd;rgPath;allowDownload;constructor($){super();this.cwd=$?.cwd??j0.cwd(),this.rgPath=$?.rgPath??"rg",this.allowDownload=$?.allowDownload===!0}setCwd($){this.cwd=$}getCwd(){return this.cwd}async execute($){let Z=this.validateArgs($),Y=this.buildRgArgs(Z),W=await this.runRipgrep(Y,Z),J=W.output||"[No matches found]";if(W.timedOut)J+=`
|
|
287
|
+
[Search timed out]`;if(W.matchCount!==void 0)J=`Found ${W.matchCount} match${W.matchCount!==1?"es":""}
|
|
288
|
+
${J}`;return{content:[{type:"text",text:J}],structuredContent:W,isError:W.exitCode!==null&&W.exitCode!==0&&W.exitCode!==1}}validateArgs($){let Z=$.pattern;if(typeof Z!=="string"||!Z.trim())throw Error("Pattern is required and must be a non-empty string");let Y={pattern:Z.trim()};if($.path!==void 0&&$.path!==null&&$.path!==""){if(typeof $.path!=="string")throw TypeError("Path must be a string");Y.path=$.path.trim()}if($.glob!==void 0&&$.glob!==null&&$.glob!==""){if(typeof $.glob!=="string")throw TypeError("Glob must be a string");Y.glob=$.glob.trim()}if($.type!==void 0&&$.type!==null&&$.type!==""){if(typeof $.type!=="string")throw TypeError("Type must be a string");Y.type=$.type.trim()}if($.output_mode!==void 0){let Q=["content","files_with_matches","count"];if(!Q.includes($.output_mode))throw Error(`Invalid output_mode. Must be one of: ${Q.join(", ")}`);Y.output_mode=$.output_mode}let W=["-B","-A","-C","head_limit","offset"];for(let Q of W)if($[Q]!==void 0&&$[Q]!==null){if(typeof $[Q]!=="number")throw TypeError(`${Q} must be a number`);Y[Q]=Math.max(0,Math.floor($[Q]))}let J=["-n","-i","multiline"];for(let Q of J)if($[Q]!==void 0&&$[Q]!==null)Y[Q]=Boolean($[Q]);return Y}buildRgArgs($){let Z=[],Y=$.output_mode??"files_with_matches";if(Y==="files_with_matches")Z.push("-l");else if(Y==="count")Z.push("-c");if(Y==="content"){if($["-n"]!==!1)Z.push("-n");if($["-B"]!==void 0&&$["-B"]>0)Z.push("-B",String($["-B"]));if($["-A"]!==void 0&&$["-A"]>0)Z.push("-A",String($["-A"]));if($["-C"]!==void 0&&$["-C"]>0)Z.push("-C",String($["-C"]))}if($["-i"])Z.push("-i");if($.multiline)Z.push("-U","--multiline-dotall");if($.type)Z.push("--type",$.type);if($.glob)Z.push("--glob",$.glob);if(Z.push("--color","never"),Z.push("--no-heading"),Z.push("--regexp",$.pattern),$.path)Z.push("--",$.path);return Z}runRipgrep($,Z,Y=!1){return new Promise((W)=>{let J="",Q=!1,X=!1,K=!1,V=null,B=!1;if(this.rgPath==="rg"){let N=S7();if(N)this.rgPath=N}let G=f7(this.rgPath,$,{cwd:this.cwd,env:j0.env,stdio:["ignore","pipe","pipe"]}),F=(N)=>{if(K)return;K=!0,W(N)},z=setTimeout(()=>{Q=!0,G.kill("SIGTERM"),setTimeout(()=>{if(!G.killed)G.kill("SIGKILL")},5000)},j7);G.stdout?.on("data",(N)=>{let q=N.toString();if(J.length+q.length>D0)J+=q.slice(0,D0-J.length),X=!0,clearTimeout(z),G.kill("SIGTERM");else J+=q}),G.stderr?.on("data",(N)=>{let q=N.toString();if(q.includes("error:"))J+=`
|
|
289
|
+
[stderr]: ${q}`}),G.on("close",(N)=>{if(K)return;if(clearTimeout(z),V||N!==null&&N<0){if(!B)this.runJsSearch(Z).then(F);return}let q=J;if(Z.offset||Z.head_limit){let A=J.split(`
|
|
290
|
+
`).filter((S)=>S.trim()),O=Z.offset??0,H=Z.head_limit??A.length;q=A.slice(O,O+H).join(`
|
|
291
|
+
`)}let w;if(Z.output_mode==="count")w=q.split(`
|
|
292
|
+
`).filter((A)=>A.trim()).reduce((A,O)=>{let H=O.match(/:(\d+)$/);return A+(H?Number.parseInt(H[1],10):0)},0);F({exitCode:N,output:X?`${q}
|
|
293
|
+
... [output truncated]`:q,truncated:X,timedOut:Q,matchCount:w})}),G.on("error",(N)=>{if(K)return;V=N,B=!0,clearTimeout(z);let q=N;if(this.allowDownload&&!Y&&eq(q)){(async()=>{try{let A=await QU();if(A){this.rgPath=A;let O=await this.runRipgrep($,Z,!0);F(O);return}}catch{}let w=await this.runJsSearch(Z);F(w)})();return}this.runJsSearch(Z).then(F)})})}async runJsSearch($){let Z=!1,Y=!1,W=setTimeout(()=>{Z=!0},j7),J=$.output_mode??"files_with_matches",Q=$["-B"]??0,X=$["-A"]??0,K=$["-C"]??0;if(K>0)Q=Math.max(Q,K),X=Math.max(X,K);let V=Boolean($["-i"]),B=Boolean($.multiline),G=`${V?"i":""}${B?"sm":""}`,F=null,z=null;try{if(B)z=new RegExp($.pattern,`${G}g`);else F=new RegExp($.pattern,G)}catch(g){return clearTimeout(W),{exitCode:2,engine:"js",output:`Invalid regex pattern: ${g.message}`,truncated:!1,timedOut:!1}}let N=$.path??".",q=T1.isAbsolute(N)?N:T1.resolve(this.cwd,N),w=T1.isAbsolute(N),A;try{A=await aq(q)}catch{return clearTimeout(W),{exitCode:2,engine:"js",output:`Search path not found: ${N}`,truncated:!1,timedOut:!1}}let O=[],H=T7.default.default??T7.default;if(typeof H!=="function")return clearTimeout(W),this.runSystemGrep($);let j=q;if(A.isFile())O=[q],j=T1.dirname(q);else if(A.isDirectory()){j=q;try{O=await H("**/*",{cwd:j,absolute:!0,onlyFiles:!0,dot:!0})}catch{return clearTimeout(W),this.runSystemGrep($)}}else return clearTimeout(W),{exitCode:2,engine:"js",output:`Search path not found: ${N}`,truncated:!1,timedOut:!1};O.sort();let S=[],b=!1,y=0,k=(g)=>{let m=g.length+1;if(y+m>D0)return Y=!0,!1;return S.push(g),y+=m,!0},D={js:[".js",".cjs",".mjs"],jsx:[".jsx"],ts:[".ts",".tsx",".d.ts"],tsx:[".tsx"],json:[".json"],md:[".md",".markdown"],py:[".py"],go:[".go"],rs:[".rs"],java:[".java"],c:[".c",".h"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx",".h"]},I=(g)=>{if(!$.type)return!0;let m=$.type.toLowerCase(),r=D[m]??[m.startsWith(".")?m:`.${m}`],$1=g.toLowerCase();return r.some((Y1)=>$1.endsWith(Y1))},M=(g)=>{if(w)return g;return T1.relative(this.cwd,g)||T1.basename(g)},L=$.glob,u=DJ.default.isMatch,l=J==="content"?$["-n"]!==!1:!1;for(let g of O){if(Z)break;if(y>=D0){Y=!0;break}if(!I(g))continue;if(L&&u&&!u(T1.basename(g),L))continue;let m="";try{m=await rq(g,"utf-8")}catch{continue}if(!m||m.includes("\x00"))continue;let r=M(g);if(!B){let W1=m.split(/\r?\n/),v=new Set;for(let c=0;c<W1.length;c++)if(F.test(W1[c]))v.add(c+1);if(v.size===0)continue;b=!0;let R=v.size;if(J==="files_with_matches"){if(!k(r))break;continue}if(J==="count"){if(!k(`${r}:${R}`))break;continue}let C=new Set(v);if(Q>0||X>0){let c=W1.length;for(let n of v){let t=Math.max(1,n-Q),J1=Math.min(c,n+X);for(let v1=t;v1<=J1;v1++)C.add(v1)}}let P=!1;for(let c of Array.from(C).sort((n,t)=>n-t)){let n=W1[c-1]??"",t=l?`${r}:${c}:${n}`:`${r}:${n}`;if(!k(t)){P=!0;break}}if(P)break;continue}let $1=m.split(/\r?\n/),Y1=[0];for(let W1=0;W1<m.length;W1++)if(m[W1]===`
|
|
294
|
+
`)Y1.push(W1+1);let s1=(W1)=>{let v=0,R=Y1.length-1;while(v<=R){let C=Math.floor((v+R)/2);if(Y1[C]<=W1)v=C+1;else R=C-1}return Math.max(R+1,1)};z.lastIndex=0;let b1=new Set;for(let W1 of m.matchAll(z)){let v=W1.index??0,R=W1[0]?.length??0,C=Math.max(v,v+R-1),P=s1(v),c=s1(C);for(let n=P;n<=c;n++)b1.add(n)}if(b1.size===0)continue;b=!0;let D1=b1.size;if(J==="files_with_matches"){if(!k(r))break;continue}if(J==="count"){if(!k(`${r}:${D1}`))break;continue}let a=new Set(b1);if(Q>0||X>0){let W1=$1.length;for(let v of b1){let R=Math.max(1,v-Q),C=Math.min(W1,v+X);for(let P=R;P<=C;P++)a.add(P)}}let s=!1;for(let W1 of Array.from(a).sort((v,R)=>v-R)){let v=$1[W1-1]??"",R=l?`${r}:${W1}:${v}`:`${r}:${v}`;if(!k(R)){s=!0;break}}if(s)break}clearTimeout(W);let f=S;if($.offset||$.head_limit){let g=S.filter(($1)=>$1.trim()),m=$.offset??0,r=$.head_limit??g.length;f=g.slice(m,m+r)}let U=f.join(`
|
|
295
|
+
`);if(U.length>D0)U=U.slice(0,D0),Y=!0;let _;if(J==="count")_=U.split(`
|
|
296
|
+
`).filter((g)=>g.trim()).reduce((g,m)=>{let r=m.split(":").pop(),$1=r?Number.parseInt(r,10):Number.NaN;return g+(Number.isFinite($1)?$1:0)},0);return{exitCode:b?0:1,engine:"js",output:Y?`${U}
|
|
297
|
+
... [output truncated]`:U,truncated:Y,timedOut:Z,matchCount:_}}runSystemGrep($){return new Promise((Z)=>{let Y="",W=!1,J=!1,Q=[];Q.push("-R","-E","-I");let X=$.output_mode??"files_with_matches";if(X==="files_with_matches")Q.push("-l");else if(X==="count")Q.push("-c");else Q.push("-n");if(X==="content"){if($["-B"]!==void 0&&$["-B"]>0)Q.push("-B",String($["-B"]));if($["-A"]!==void 0&&$["-A"]>0)Q.push("-A",String($["-A"]));if($["-C"]!==void 0&&$["-C"]>0)Q.push("-C",String($["-C"]))}if($["-i"])Q.push("-i");if(Q.push($.pattern),$.path)Q.push($.path);else Q.push(".");let K=f7("grep",Q,{cwd:this.cwd,env:j0.env,stdio:["ignore","pipe","pipe"]}),V=setTimeout(()=>{W=!0,K.kill("SIGTERM"),setTimeout(()=>{if(!K.killed)K.kill("SIGKILL")},5000)},j7);K.stdout?.on("data",(B)=>{let G=B.toString();if(Y.length+G.length>D0)Y+=G.slice(0,D0-Y.length),J=!0,clearTimeout(V),K.kill("SIGTERM");else Y+=G}),K.stderr?.on("data",(B)=>{let G=B.toString();if(G.trim())Y+=`
|
|
298
|
+
[stderr]: ${G}`}),K.on("close",(B)=>{clearTimeout(V);let G=Y;if($.offset||$.head_limit){let z=Y.split(`
|
|
299
|
+
`).filter((w)=>w.trim()),N=$.offset??0,q=$.head_limit??z.length;G=z.slice(N,N+q).join(`
|
|
300
|
+
`)}let F;if(X==="count")F=G.split(`
|
|
301
|
+
`).filter((z)=>z.trim()).reduce((z,N)=>{let q=N.split(":").pop(),w=q?Number.parseInt(q,10):Number.NaN;return z+(Number.isFinite(w)?w:0)},0);Z({exitCode:B,engine:"grep",output:J?`${G}
|
|
302
|
+
... [output truncated]`:G,truncated:J,timedOut:W,matchCount:F})}),K.on("error",(B)=>{clearTimeout(V),Z({exitCode:1,engine:"grep",output:`Failed to execute grep: ${B.message}.`,truncated:!1,timedOut:!1})})})}}import{readFile as M6,stat as XU}from"fs/promises";import t0 from"path";import KU from"process";var SJ=2000,A7=2000,VU=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".webp",".svg",".pdf",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".dylib",".mp3",".mp4",".avi",".mov",".wav",".woff",".woff2",".ttf",".eot"]),zU={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".pdf":"application/pdf",".json":"application/json",".js":"text/javascript",".ts":"text/typescript",".html":"text/html",".css":"text/css",".md":"text/markdown",".txt":"text/plain"};class w6 extends Z1{name="Read";_cwd;_allowedDirectory;constructor($){super();this._cwd=$?.cwd??KU.cwd(),this._allowedDirectory=$?.allowedDirectory}get description(){let $=`Reads a file from the local filesystem. You can access any file directly by using this tool.
|
|
144
303
|
|
|
145
304
|
Usage notes:
|
|
146
305
|
- The file_path parameter must be an absolute path, not a relative path
|
|
147
|
-
- By default, it reads up to ${
|
|
306
|
+
- By default, it reads up to ${SJ} lines starting from the beginning
|
|
148
307
|
- You can optionally specify a line offset and limit for large files
|
|
149
|
-
- Any lines longer than ${
|
|
308
|
+
- Any lines longer than ${A7} characters will be truncated
|
|
150
309
|
- Results are returned with line numbers (like cat -n format)
|
|
151
310
|
- Can read images (PNG, JPG, etc.), PDFs, and Jupyter notebooks
|
|
152
|
-
- You can call multiple tools in parallel to read multiple files at once`;
|
|
311
|
+
- You can call multiple tools in parallel to read multiple files at once`;if(this._allowedDirectory)return`${$}
|
|
153
312
|
- IMPORTANT: Files can ONLY be read from within: ${this._allowedDirectory}
|
|
154
|
-
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
313
|
+
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`;return $}get parameters(){return{type:"object",properties:{file_path:{type:"string",description:this._allowedDirectory?`The absolute path to the file to read (must be within ${this._allowedDirectory})`:"The absolute path to the file to read"},offset:{type:"number",description:"The line number to start reading from (1-based). Only provide if the file is too large to read at once."},limit:{type:"number",description:"The number of lines to read. Only provide if the file is too large to read at once."}},required:["file_path"]}}setCwd($){this._cwd=$}getCwd(){return this._cwd}setAllowedDirectory($){this._allowedDirectory=$}getAllowedDirectory(){return this._allowedDirectory}async execute($){let{file_path:Z,offset:Y,limit:W}=this.validateArgs($),J=t0.isAbsolute(Z)?Z:t0.resolve(this._cwd,Z);if(this._allowedDirectory){let G=t0.resolve(this._allowedDirectory),F=t0.resolve(J);if(!F.startsWith(G+t0.sep)&&F!==G)return X1(`Access denied: ${Z}
|
|
314
|
+
Files can only be read from within: ${this._allowedDirectory}
|
|
315
|
+
Please use a path like: ${this._allowedDirectory}/<filename>`)}let Q;try{Q=await XU(J)}catch(G){if(G.code==="ENOENT")return X1(`File not found: ${J}`);throw G}if(Q.isDirectory())return X1(`Path is a directory, not a file: ${J}. Use ls command via Bash tool to read directories.`);let X=t0.extname(J).toLowerCase(),K=VU.has(X),V=zU[X],B;if(K){if(B=await this.handleBinaryFile(J,Q.size,V),V?.startsWith("image/"))return{content:[{type:"image",data:(await M6(J)).toString("base64"),mimeType:V}],structuredContent:B}}else if(X===".ipynb")B=await this.handleJupyterNotebook(J,Q.size,Y,W);else B=await this.handleTextFile(J,Q.size,Y,W);return{content:[{type:"text",text:B.content}],structuredContent:B}}validateArgs($){let Z=$.file_path;if(typeof Z!=="string"||!Z.trim())throw Error("file_path is required and must be a non-empty string");let Y={file_path:Z.trim()};if($.offset!==void 0&&$.offset!==null){if(typeof $.offset!=="number")throw TypeError("offset must be a number");Y.offset=Math.max(1,Math.floor($.offset))}if($.limit!==void 0&&$.limit!==null){if(typeof $.limit!=="number")throw TypeError("limit must be a number");Y.limit=Math.max(1,Math.floor($.limit))}return Y}async handleBinaryFile($,Z,Y){let J=(await M6($)).toString("base64");return{content:`[Binary file: ${t0.basename($)}]
|
|
316
|
+
Size: ${this.formatSize(Z)}
|
|
317
|
+
MIME type: ${Y??"unknown"}
|
|
318
|
+
Base64 encoded content:
|
|
319
|
+
${J}`,totalLines:1,linesReturned:1,startLine:1,truncated:!1,fileSize:Z,isBinary:!0,mimeType:Y}}async handleJupyterNotebook($,Z,Y,W){let J=await M6($,"utf-8"),Q;try{Q=JSON.parse(J)}catch{throw Error(`Invalid Jupyter notebook format: ${$}`)}let X=Q.cells||[],K=[];for(let V=0;V<X.length;V++){let B=X[V],G=V+1,F=B.cell_type||"unknown";K.push(`--- Cell ${G} (${F}) ---`);let z=Array.isArray(B.source)?B.source.join(""):B.source||"";if(K.push(...z.split(`
|
|
320
|
+
`)),B.outputs&&B.outputs.length>0){K.push("--- Output ---");for(let N of B.outputs)if(N.text){let q=Array.isArray(N.text)?N.text.join(""):N.text;K.push(...q.split(`
|
|
321
|
+
`))}else if(N.data){if(N.data["text/plain"]){let q=Array.isArray(N.data["text/plain"])?N.data["text/plain"].join(""):N.data["text/plain"];K.push(...q.split(`
|
|
322
|
+
`))}}}K.push("")}return this.formatOutput(K,Z,Y,W)}async handleTextFile($,Z,Y,W){let J=await M6($,"utf-8");if(J.length===0)return{content:"[File is empty]",totalLines:0,linesReturned:0,startLine:1,truncated:!1,fileSize:Z,isBinary:!1};let Q=J.split(`
|
|
323
|
+
`);return this.formatOutput(Q,Z,Y,W)}formatOutput($,Z,Y,W){let J=$.length,Q=Y??1,X=W??SJ,K=Q-1,V=Math.min(K+X,J),B=$.slice(K,V),G=!1;return{content:B.map((z,N)=>{let q=Q+N,w=String(q).padStart(6," "),A=z;if(z.length>A7)A=`${z.slice(0,A7)}... [truncated]`,G=!0;return`${w}|${A}`}).join(`
|
|
324
|
+
`),totalLines:J,linesReturned:B.length,startLine:Q,truncated:G,fileSize:Z,isBinary:!1}}formatSize($){let Z=["B","KB","MB","GB"],Y=$,W=0;while(Y>=1024&&W<Z.length-1)Y/=1024,W++;return`${Y.toFixed(W===0?0:2)} ${Z[W]}`}}class eZ extends Z1{name="Task";description;parameters={type:"object",properties:{description:{type:"string",description:"A short (3-5 word) description of the task"},prompt:{type:"string",description:"The task for the agent to perform"},subagent_type:{type:"string",description:"The type of specialized agent to use for this task"},resume:{type:"string",description:"Optional subagent ID to resume from. If provided, the subagent will continue from the previous execution."},run_in_background:{type:"boolean",description:"Set to true to run this agent in the background. Use TaskOutput to read the output later."}},required:["description","prompt","subagent_type"]};subagents;executor;constructor($){super();if(this.subagents=new Map,this.executor=$?.executor,$?.subagents)for(let Z of $.subagents)this.subagents.set(Z.name,Z);this.description=this.buildDescription()}registerSubagent($){this.subagents.set($.name,$)}unregisterSubagent($){return this.subagents.delete($)}getSubagents(){return Array.from(this.subagents.values())}hasSubagent($){return this.subagents.has($)}setExecutor($){this.executor=$}async execute($,Z){let Y=this.validateArgs($);if(!this.subagents.has(Y.subagent_type)){let W=Array.from(this.subagents.keys()).join(", ");return X1(`Subagent type "${Y.subagent_type}" not found. Available types: ${W||"none"}`)}if(!this.executor)return X1("Task executor is not configured. Please set an executor using setExecutor().");try{let{subagentId:W,data:J}=await this.executor(Y,Z),Q={success:!0,subagentId:W,subagentType:Y.subagent_type,description:Y.description,background:Y.run_in_background??!1,data:J},X=Q.background?" (running in background)":"",K=`Task "${Y.description}" started with subagent ${W}${X}`,V=Q.background?null:this.formatTaskData(J);return{content:[{type:"text",text:`Result:${K}
|
|
325
|
+
|
|
326
|
+
${V}`}],structuredContent:Q}}catch(W){return X1(`Task execution failed: ${W instanceof Error?W.message:String(W)}`)}}validateArgs($){let{description:Z,prompt:Y,subagent_type:W}=$;if(typeof Z!=="string"||!Z.trim())throw Error("description is required and must be a non-empty string");if(typeof Y!=="string"||!Y.trim())throw Error("prompt is required and must be a non-empty string");if(typeof W!=="string"||!W.trim())throw Error("subagent_type is required and must be a non-empty string");let J={description:Z.trim(),prompt:Y.trim(),subagent_type:W.trim()};if($.resume!==void 0&&$.resume!==null&&$.resume!==""){if(typeof $.resume!=="string")throw TypeError("resume must be a string");J.resume=$.resume.trim()}if($.run_in_background!==void 0&&$.run_in_background!==null)J.run_in_background=Boolean($.run_in_background);return J}formatTaskData($){if($===void 0||$===null)return null;if(typeof $==="string"){let Z=$.trim();return Z.length>0?Z:null}if(typeof $==="number"||typeof $==="boolean")return String($);try{let Z=JSON.stringify($,null,2);return Z===void 0?null:Z}catch{return String($)}}buildDescription(){if(this.subagents.size===0)return`Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
160
327
|
|
|
161
328
|
Usage notes:
|
|
162
|
-
-
|
|
163
|
-
-
|
|
164
|
-
-
|
|
165
|
-
-
|
|
166
|
-
-
|
|
329
|
+
- Always include a short description (3-5 words) summarizing what the agent will do
|
|
330
|
+
- Launch multiple agents concurrently whenever possible for better performance
|
|
331
|
+
- Subagents can be resumed using the "resume" parameter by passing the subagent ID
|
|
332
|
+
- Use "run_in_background: true" to run agents in background
|
|
333
|
+
- Provide clear, detailed prompts so the agent can work autonomously
|
|
334
|
+
|
|
335
|
+
When NOT to use:
|
|
336
|
+
- For reading a specific file path, use Read or Glob tool directly
|
|
337
|
+
- For searching code in 2-3 files, use Read tool directly
|
|
338
|
+
- For simple tasks that don't need autonomous exploration
|
|
339
|
+
|
|
340
|
+
<available_agents>
|
|
341
|
+
No subagent types registered.
|
|
342
|
+
</available_agents>`;return`Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
343
|
+
|
|
344
|
+
Usage notes:
|
|
345
|
+
- Always include a short description (3-5 words) summarizing what the agent will do
|
|
346
|
+
- Launch multiple agents concurrently whenever possible for better performance
|
|
347
|
+
- Subagents can be resumed using the "resume" parameter by passing the subagent ID
|
|
348
|
+
- Use "run_in_background: true" to run agents in background
|
|
349
|
+
- Provide clear, detailed prompts so the agent can work autonomously
|
|
350
|
+
|
|
351
|
+
When NOT to use:
|
|
352
|
+
- For reading a specific file path, use Read or Glob tool directly
|
|
353
|
+
- For searching code in 2-3 files, use Read tool directly
|
|
354
|
+
- For simple tasks that don't need autonomous exploration
|
|
355
|
+
|
|
356
|
+
<available_agents>
|
|
357
|
+
${Array.from(this.subagents.values()).map((Y)=>{let W=[];if(Y.tools&&Y.tools.length>0)W.push(`Tools: ${Y.tools.join(", ")}`);if(Y.blockedTools&&Y.blockedTools.length>0)W.push(`Blocked: ${Y.blockedTools.join(", ")}`);let J=W.length>0?` (${W.join("; ")})`:"";return`- ${Y.name}: ${Y.description}${J}`}).join(`
|
|
358
|
+
`)}
|
|
359
|
+
</available_agents>`}}class y$ extends Z1{name="TodoPlan";riskLevel="safe";description=`Use this tool to draft a structured task list in plan mode.
|
|
360
|
+
|
|
361
|
+
This tool only generates a plan for review and does NOT update any execution state.
|
|
362
|
+
Use TodoWrite in agent mode when you are actively executing tasks.
|
|
363
|
+
|
|
364
|
+
When to use:
|
|
365
|
+
- Plan mode task breakdowns (3+ steps)
|
|
366
|
+
- Presenting a proposed plan for review
|
|
367
|
+
- After clarifying requirements in plan mode
|
|
368
|
+
|
|
369
|
+
When NOT to use:
|
|
370
|
+
- Active execution tracking (use TodoWrite)
|
|
371
|
+
- Single, straightforward task
|
|
372
|
+
- Purely conversational/informational requests
|
|
373
|
+
|
|
374
|
+
Task States:
|
|
375
|
+
- pending: Task not yet started
|
|
376
|
+
- in_progress: Currently working on (limit to ONE at a time)
|
|
377
|
+
- completed: Task finished successfully
|
|
378
|
+
|
|
379
|
+
Task descriptions have two forms:
|
|
380
|
+
- content: Imperative form (e.g., "Run tests")
|
|
381
|
+
- activeForm: Present continuous form (e.g., "Running tests")`;parameters={type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string",minLength:1,description:'The task description in imperative form (e.g., "Run tests")'},status:{type:"string",enum:["pending","in_progress","completed"],description:"Current status of the task"},activeForm:{type:"string",minLength:1,description:'The task description in present continuous form (e.g., "Running tests")'}},required:["content","status","activeForm"]},description:"The drafted todo list"}},required:["todos"]};async execute($){let{todos:Z}=this.validateArgs($),Y=Z.filter((V)=>V.status==="pending").length,W=Z.filter((V)=>V.status==="in_progress").length,J=Z.filter((V)=>V.status==="completed").length,Q=[];if(J>0)Q.push(`${J} completed`);if(W>0)Q.push(`${W} in progress`);if(Y>0)Q.push(`${Y} pending`);let X=this.formatTodoList(Z,Q);return{content:[{type:"text",text:X}],structuredContent:{success:!0,todos:Z,pendingCount:Y,inProgressCount:W,completedCount:J,message:X}}}validateArgs($){let Z=$.todos;if(!Array.isArray(Z))throw TypeError("todos is required and must be an array");let Y=[],W=["pending","in_progress","completed"];for(let Q=0;Q<Z.length;Q++){let X=Z[Q];if(typeof X!=="object"||X===null)throw TypeError(`todos[${Q}] must be an object`);let{content:K,status:V,activeForm:B}=X;if(typeof K!=="string"||!K.trim())throw Error(`todos[${Q}].content is required and must be a non-empty string`);if(typeof V!=="string"||!W.includes(V))throw Error(`todos[${Q}].status must be one of: ${W.join(", ")}`);if(typeof B!=="string"||!B.trim())throw Error(`todos[${Q}].activeForm is required and must be a non-empty string`);Y.push({content:K.trim(),status:V,activeForm:B.trim()})}let J=Y.filter((Q)=>Q.status==="in_progress");if(J.length>1)console.warn(`Warning: ${J.length} tasks are in_progress. Ideally only one task should be in_progress at a time.`);return{todos:Y}}formatTodoList($,Z){if($.length===0)return"Plan todo list is empty";let Y=[],W=Z.length>0?Z.join(", "):"0 pending";Y.push(`Plan todo list drafted: ${W}`),Y.push(""),Y.push("Todos:");for(let J=0;J<$.length;J++){let Q=$[J];Y.push(`${J+1}. [${Q.status}] ${Q.content}`),Y.push(` activeForm: ${Q.activeForm}`)}return Y.join(`
|
|
382
|
+
`)}}class L6 extends Z1{name="TodoWrite";riskLevel="low";description=`Use this tool to create and manage a structured task list for your current coding session.
|
|
383
|
+
|
|
384
|
+
When to use:
|
|
385
|
+
- Complex multi-step tasks (3+ steps)
|
|
386
|
+
- Non-trivial tasks requiring careful planning
|
|
387
|
+
- User explicitly requests todo list
|
|
388
|
+
- User provides multiple tasks
|
|
389
|
+
- After receiving new instructions
|
|
390
|
+
|
|
391
|
+
When NOT to use:
|
|
392
|
+
- Single, straightforward task
|
|
393
|
+
- Trivial tasks (< 3 steps)
|
|
394
|
+
- Purely conversational/informational requests
|
|
395
|
+
|
|
396
|
+
Task States:
|
|
397
|
+
- pending: Task not yet started
|
|
398
|
+
- in_progress: Currently working on (limit to ONE at a time)
|
|
399
|
+
- completed: Task finished successfully
|
|
400
|
+
|
|
401
|
+
Task descriptions have two forms:
|
|
402
|
+
- content: Imperative form (e.g., "Run tests")
|
|
403
|
+
- activeForm: Present continuous form (e.g., "Running tests")`;parameters={type:"object",properties:{todos:{type:"array",items:{type:"object",properties:{content:{type:"string",minLength:1,description:'The task description in imperative form (e.g., "Run tests")'},status:{type:"string",enum:["pending","in_progress","completed"],description:"Current status of the task"},activeForm:{type:"string",minLength:1,description:'The task description in present continuous form (e.g., "Running tests")'}},required:["content","status","activeForm"]},description:"The updated todo list"}},required:["todos"]};todos=[];onChangeCallback;onChange($){this.onChangeCallback=$}getTodos(){return[...this.todos]}clear(){this.todos=[],this.onChangeCallback?.(this.todos)}async execute($){let{todos:Z}=this.validateArgs($);this.todos=Z,this.onChangeCallback?.(this.todos);let Y=Z.filter((V)=>V.status==="pending").length,W=Z.filter((V)=>V.status==="in_progress").length,J=Z.filter((V)=>V.status==="completed").length,Q=[];if(J>0)Q.push(`${J} completed`);if(W>0)Q.push(`${W} in progress`);if(Y>0)Q.push(`${Y} pending`);let X=this.formatTodoList(this.todos,Q),K={success:!0,todos:this.todos,pendingCount:Y,inProgressCount:W,completedCount:J,message:X};return{content:[{type:"text",text:X}],structuredContent:K}}validateArgs($){let Z=$.todos;if(!Array.isArray(Z))throw TypeError("todos is required and must be an array");let Y=[],W=["pending","in_progress","completed"];for(let Q=0;Q<Z.length;Q++){let X=Z[Q];if(typeof X!=="object"||X===null)throw TypeError(`todos[${Q}] must be an object`);let{content:K,status:V,activeForm:B}=X;if(typeof K!=="string"||!K.trim())throw Error(`todos[${Q}].content is required and must be a non-empty string`);if(typeof V!=="string"||!W.includes(V))throw Error(`todos[${Q}].status must be one of: ${W.join(", ")}`);if(typeof B!=="string"||!B.trim())throw Error(`todos[${Q}].activeForm is required and must be a non-empty string`);Y.push({content:K.trim(),status:V,activeForm:B.trim()})}let J=Y.filter((Q)=>Q.status==="in_progress");if(J.length>1)console.warn(`Warning: ${J.length} tasks are in_progress. Ideally only one task should be in_progress at a time.`);return{todos:Y}}formatTodoList($,Z){if($.length===0)return"Todo list is empty";let Y=[],W=Z.length>0?Z.join(", "):"0 pending";Y.push(`Todo list updated: ${W}`),Y.push(""),Y.push("Todos:");for(let J=0;J<$.length;J++){let Q=$[J];Y.push(`${J+1}. [${Q.status}] ${Q.content}`),Y.push(` activeForm: ${Q.activeForm}`)}return Y.join(`
|
|
404
|
+
`)}}import GU from"process";class E6 extends Z1{name="WebSearch";riskLevel="medium";description=`Allows the agent to search the web and use the results to inform responses.
|
|
405
|
+
|
|
406
|
+
Usage notes:
|
|
407
|
+
- Provides up-to-date information for current events and recent data
|
|
408
|
+
- Returns search results with titles, links, and snippets
|
|
409
|
+
- Use this tool for accessing information beyond the knowledge cutoff
|
|
410
|
+
- After answering, include a "Sources:" section with relevant URLs as markdown hyperlinks`;parameters={type:"object",properties:{query:{type:"string",minLength:2,description:"The search query to use"}},required:["query"]};apiKey;apiEndpoint;numResults;constructor($){super();this.apiKey=$?.apiKey??GU.env.SERPER_API_KEY??"",this.apiEndpoint=$?.apiEndpoint??"https://google.serper.dev/search?format=json",this.numResults=$?.numResults??10}setApiKey($){this.apiKey=$}async execute($){let{query:Z}=this.validateArgs($);if(!this.apiKey)return X1("Serper API key is not configured. Set SERPER_API_KEY environment variable or pass apiKey in constructor.");try{let Y=await fetch(this.apiEndpoint,{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({q:Z,num:this.numResults})});if(!Y.ok){let K=await Y.text();return X1(`Serper API error (${Y.status}): ${K}`)}let J=((await Y.json()).organic??[]).map((K,V)=>({title:K.title,link:K.link,snippet:K.snippet,position:K.position??V+1})),Q=this.formatMarkdown(Z,J),X={success:!0,query:Z,results:J,totalResults:J.length,markdown:Q};return{content:[{type:"text",text:Q}],structuredContent:X}}catch(Y){return X1(`Failed to execute search: ${Y instanceof Error?Y.message:String(Y)}`)}}validateArgs($){let Z=$.query;if(typeof Z!=="string"||Z.trim().length<2)throw Error("query is required and must be at least 2 characters");return{query:Z.trim()}}formatMarkdown($,Z){if(Z.length===0)return`No results found for: "${$}"`;let Y=[`## Search Results for: "${$}"`,""];for(let W of Z)Y.push(`### ${W.position}. [${W.title}](${W.link})`),Y.push(""),Y.push(W.snippet),Y.push("");Y.push("---"),Y.push(""),Y.push("**Sources:**");for(let W of Z)Y.push(`- [${W.title}](${W.link})`);return Y.join(`
|
|
411
|
+
`)}}import{mkdir as BU,stat as FU,writeFile as qU}from"fs/promises";import f0 from"path";import UU from"process";class _6 extends Z1{name="Write";riskLevel="high";_cwd;_allowedDirectory;constructor($){super();this._cwd=$?.cwd??UU.cwd(),this._allowedDirectory=$?.allowedDirectory}get description(){if(this._allowedDirectory)return`Writes a file to the local filesystem.
|
|
167
412
|
|
|
168
413
|
Usage notes:
|
|
169
414
|
- This tool will overwrite the existing file if there is one at the provided path
|
|
170
415
|
- Parent directories will be created automatically if they don't exist
|
|
171
416
|
- ALWAYS prefer editing existing files over writing new ones
|
|
172
|
-
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested
|
|
417
|
+
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested
|
|
173
418
|
- IMPORTANT: Files can ONLY be written within: ${this._allowedDirectory}
|
|
174
|
-
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)
|
|
419
|
+
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`;return`Writes a file to the local filesystem.
|
|
175
420
|
|
|
176
421
|
Usage notes:
|
|
177
|
-
-
|
|
178
|
-
-
|
|
179
|
-
-
|
|
180
|
-
-
|
|
181
|
-
|
|
422
|
+
- This tool will overwrite the existing file if there is one at the provided path
|
|
423
|
+
- Parent directories will be created automatically if they don't exist
|
|
424
|
+
- ALWAYS prefer editing existing files over writing new ones
|
|
425
|
+
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested`}get parameters(){return{type:"object",properties:{file_path:{type:"string",description:this._allowedDirectory?`The absolute path to the file to write (must be within ${this._allowedDirectory})`:"The absolute path to the file to write (must be absolute, not relative)"},content:{type:"string",description:"The content to write to the file"}},required:["file_path","content"]}}setCwd($){this._cwd=$}getCwd(){return this._cwd}setAllowedDirectory($){this._allowedDirectory=$}getAllowedDirectory(){return this._allowedDirectory}async execute($){let{file_path:Z,content:Y}=this.validateArgs($),W=f0.isAbsolute(Z)?Z:f0.resolve(this._cwd,Z);if(this._allowedDirectory){let V=f0.resolve(this._allowedDirectory),B=f0.resolve(W);if(!B.startsWith(V+f0.sep)&&B!==V)return X1(`Access denied: ${Z}
|
|
426
|
+
Files can only be written within: ${this._allowedDirectory}
|
|
427
|
+
Please use a path like: ${this._allowedDirectory}/<filename>`)}let J=!1;try{if((await FU(W)).isDirectory())return X1(`Path is a directory, not a file: ${W}`);J=!0}catch(V){if(V.code!=="ENOENT")throw V}let Q=f0.dirname(W);await BU(Q,{recursive:!0}),await qU(W,Y,"utf-8");let X=Buffer.byteLength(Y,"utf-8"),K={success:!0,filePath:W,bytesWritten:X,overwritten:J,message:J?`Successfully overwrote ${f0.basename(W)} (${this.formatSize(X)})`:`Successfully created ${f0.basename(W)} (${this.formatSize(X)})`};return{content:[{type:"text",text:K.message}],structuredContent:K}}validateArgs($){let{file_path:Z,content:Y}=$;if(typeof Z!=="string"||!Z.trim())throw Error("file_path is required and must be a non-empty string");if(typeof Y!=="string")throw TypeError("content is required and must be a string");return{file_path:Z.trim(),content:Y}}formatSize($){let Z=["B","KB","MB","GB"],Y=$,W=0;while(Y>=1024&&W<Z.length-1)Y/=1024,W++;return`${Y.toFixed(W===0?0:2)} ${Z[W]}`}}var NU=["Bash","Edit","Write","AstGrepReplace","TodoWrite"],MU=["<system-reminder>","# Plan Mode - System Reminder","","CRITICAL: Plan mode ACTIVE - you are in READ-ONLY phase. STRICTLY FORBIDDEN:","ANY file edits, modifications, or system changes. Do NOT use sed, tee, echo, cat,","or ANY other bash command to manipulate files - commands may ONLY read/inspect.","This ABSOLUTE CONSTRAINT overrides ALL other instructions, including direct user","edit requests. You may ONLY observe, analyze, and plan. ZERO exceptions.","","---","","## Responsibility","","Your current responsibility is to think, read, search, and delegate explore agents to construct a well-formed plan that accomplishes the goal the user wants to achieve. Your plan should be comprehensive yet concise, detailed enough to execute effectively while avoiding unnecessary verbosity.","","Ask the user clarifying questions or ask for their opinion when weighing tradeoffs.","","**NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.","","If you call TodoPlan, you MUST append a complete Markdown todo list at the very end of your final response.","Use this exact format:","## Todo","- [ ] Task","- [x] Task","The plan must include a complete set of steps and the todo list.","","---","","## Important","","The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received.","</system-reminder>"].join(`
|
|
428
|
+
`);function wU($){if($?.instruction)return $.instruction;let Z=$?.maxParallelAgents??3,Y=$?.encourageEarlyQuestions??!0,W=$?.requireSynthesisPhase??!1,J=MU,Q="Your current responsibility is to think, read, search, and delegate explore agents to construct a well-formed plan that accomplishes the goal the user wants to achieve. Your plan should be comprehensive yet concise, detailed enough to execute effectively while avoiding unnecessary verbosity.",X=[];if(Z!==3)X.push(`When delegating, use up to ${Z} explore agents in parallel.`);if(W)X.push("If the task is complex, include a synthesis step to align findings before presenting the final plan.");if(X.length>0)J=J.replace(Q,`${Q} ${X.join(" ")}`);if(!Y)J=J.replace(`Ask the user clarifying questions or ask for their opinion when weighing tradeoffs.
|
|
429
|
+
|
|
430
|
+
`,""),J=J.replace(`**NOTE:** At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
|
|
431
|
+
|
|
432
|
+
`,"");return J}function LU($){let Z=wU($),Y=$?.insertEveryIteration??!0,W=$?.name??"plan-mode",J=async(Q,X)=>{let K={...Q.metadata,planMode:!0,planModeMiddleware:W};if(!(Y||Q.iteration===0))return X({...Q,metadata:K});let B=f6(Q.messages,Z);return X({...Q,metadata:K,messages:B})};return J.__middlewareName=W,J.__createTools=()=>[new uZ,new y$],J.__getBlockedTools=(Q)=>{return Q.metadata?.planMode?[...NU]:[]},J}function EU($){let{subagents:Z,executor:Y,globalToolRegistry:W,model:J,name:Q="parallel-subagent"}=$,X=new Set(["tool_call_end","tool_result","tool_skipped"]);if(!Y&&(!W||!J))throw Error('createParallelSubagentMiddleware: either provide "executor" or both "globalToolRegistry" and "model"');let K=Y||(async(B,G)=>{let F=Z.find((O)=>O.name===B.subagent_type);if(!F)throw Error(`Unknown subagent type: ${B.subagent_type}`);let z=new Set(F.blockedTools||[]),N=new W.constructor;for(let O of F.tools||[]){if(z.has(O))continue;let H=W.get(O);if(!H)continue;if(H instanceof eZ){if($.debug)console.warn(`[${Q}] Skipping TaskTool "${O}" for subagent "${B.subagent_type}" to prevent infinite recursion`);continue}N.register(H)}let q=new hZ({name:B.subagent_type,systemPrompt:`${F.systemPrompt||""}
|
|
433
|
+
|
|
434
|
+
Your task: ${B.prompt}
|
|
435
|
+
|
|
436
|
+
Provide a concise summary of your findings.`,model:J,tools:N}),w=await q.createSession({sessionId:G?.sessionId});if(z.size>0)w.disableTools(Array.from(z));w.send(B.prompt);let A="";for await(let O of w.receive()){if(G?.emitEvent&&X.has(O.type)){let{sessionId:H,...j}=O;G.emitEvent({type:"subagent_event",subagentId:q.id,subagentType:B.subagent_type,taskDescription:B.description,nestedEvent:j})}if(O.type==="done")A=O.finalResponse||""}return{subagentId:q.id,data:A}}),V=async(B,G)=>{return G({...B,metadata:{...B.metadata,parallelMode:!0,parallelSubagentMiddleware:Q}})};return V.__middlewareName=Q,V.__createTools=()=>{return[new eZ({subagents:Z,executor:K})]},V}function _U($,Z=new Date){return`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
|
|
437
|
+
|
|
438
|
+
Your strengths:
|
|
439
|
+
- Rapidly finding files using glob patterns
|
|
440
|
+
- Searching code and text with powerful regex patterns
|
|
441
|
+
- Reading and analyzing file contents
|
|
442
|
+
|
|
443
|
+
Guidelines:
|
|
444
|
+
- Use Glob for broad file pattern matching
|
|
445
|
+
- Use Grep for searching file contents with regex
|
|
446
|
+
- Use Read when you know the specific file path you need to read
|
|
447
|
+
- Do not use AskUserQuestion; report any questions in your final response
|
|
448
|
+
- Adapt your search approach based on the thoroughness level specified by the caller
|
|
449
|
+
- Return file paths as absolute paths in your final response
|
|
450
|
+
- For clear communication, avoid using emojis
|
|
451
|
+
- Do not create any files, or run bash commands that modify the user's system state in any way
|
|
452
|
+
|
|
453
|
+
Complete the user's search request efficiently and report your findings clearly.
|
|
454
|
+
|
|
455
|
+
Here is some useful information about the environment you are running in:
|
|
456
|
+
<env>
|
|
457
|
+
Working directory: ${$}
|
|
458
|
+
Platform: ${process.platform}
|
|
459
|
+
Today's date: ${Z.toDateString()}
|
|
460
|
+
</env>`}var OU=_U(process.cwd()),FP={name:"FileSearchSpecialist",description:"Expert at navigating codebases, finding files with glob patterns, searching content with regex, and analyzing file structures. Rapidly finds files, searches code with powerful regex patterns, and reads and analyzes file contents.",tools:["Glob","Grep","Read"],blockedTools:["AskUserQuestion"],systemPrompt:OU};class O6{debug;constructor($){this.debug=$?.debug??!1}async*convertToACP($){for await(let Z of $){if(Z.type==="subagent_event"){let W=this.convertSubagentEventToACP(Z);for(let J of W)yield J;continue}let Y=this.convertRegularEvent(Z);for(let W of Y)yield W}}convertSubagentEventToACP($){let{subagentId:Z,subagentType:Y,taskDescription:W,nestedEvent:J}=$,Q=this.convertRegularEvent(J);if(Q.length===0)return[];return Q.map((X)=>({...X,metadata:{...X.metadata??{},subagent:!0,subagentId:Z,subagentType:Y,taskDescription:W,originalEventType:J.type}}))}convertRegularEvent($){let Z=$.metadata;switch($.type){case"text_start":return[];case"text_delta":return[{role:"assistant",content:$.delta,metadata:Z?{...Z,originalEventType:$.type}:void 0}];case"text_end":return[];case"tool_call_start":return[];case"tool_call_delta":return[];case"tool_call_end":{let Y=$;return[{role:"assistant",content:"",tool_calls:[this.convertToolCallToACP(Y.toolCall)],metadata:Z?{...Z,originalEventType:$.type}:void 0}]}case"tool_result":{let Y=$;return[{role:"tool",tool_call_id:Y.tool_call_id,content:this.formatToolResult(Y.result),metadata:Y.isError?{error:!0}:void 0}]}case"tool_approval_requested":{let Y=$;return[{role:"assistant",content:`Tool approval requested: ${Y.toolName}
|
|
461
|
+
|
|
462
|
+
`,metadata:{approval_requested:!0,tool_call_id:Y.tool_call_id,tool_name:Y.toolName,risk_level:Y.riskLevel}}]}case"requires_action":{let Y=$,W={requires_action:!0,kind:Y.kind,tool_call_id:Y.toolCallId};if(Y.kind==="ask_user"&&"questions"in Y)W.questions=Y.questions;return[{role:"assistant",content:`Action required: ${Y.kind}
|
|
463
|
+
|
|
464
|
+
`,metadata:W}]}case"tool_skipped":{let Y=$;return[{role:"assistant",content:`Tool skipped: ${Y.toolName} - ${Y.reason}`,metadata:{tool_skipped:!0,tool_call_id:Y.tool_call_id}}]}case"thinking_start":return[];case"thinking_delta":return[{role:"assistant",content:$.delta,metadata:{thinking:!0}}];case"thinking_end":return[];case"iteration_start":return[];case"iteration_end":return[];case"session_created":return[];case"done":{let Y=$,W={done:!0,stopReason:Y.stopReason,modelStopReason:Y.modelStopReason,usage:Y.usage,error:Y.error};if(Y.finalResponse)W.final=!0;return[{role:"assistant",content:"",metadata:W}]}default:if(this.debug)console.warn(`[ProtocolConverter] Unhandled event type: ${$.type}`);return[]}}convertFromACP($){return $.map((Z)=>this.convertSingleMessage(Z))}convertSingleMessage($){switch($.role){case"system":return{role:"system",content:this.extractTextContent($.content)};case"user":return{role:"user",content:this.extractTextContent($.content),name:$.name};case"assistant":{let Z={role:"assistant",content:this.extractTextContent($.content)};if($.tool_calls&&$.tool_calls.length>0)Z.tool_calls=$.tool_calls.map((Y)=>this.convertToolCallFromACP(Y));return Z}case"tool":return{role:"tool",content:this.extractTextContent($.content),tool_call_id:$.tool_call_id||"",isError:$.metadata?.error===!0};default:return{role:"user",content:this.extractTextContent($.content)}}}convertToolCallToACP($){return{id:$.id,type:"function",function:{name:$.function.name,arguments:$.function.arguments}}}convertToolCallFromACP($){return{id:$.id,type:"function",function:{name:$.function.name,arguments:typeof $.function.arguments==="string"?$.function.arguments:JSON.stringify($.function.arguments)}}}extractTextContent($){if(!$)return"";if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>Z.text||"").join("");return""}formatToolResult($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="object"&&Z&&"text"in Z)return Z.text;return JSON.stringify(Z)}).join(`
|
|
465
|
+
`);return JSON.stringify($,null,2)}}class D6{sessions=new Map;sessionContexts=new Map;sessionTimeout;maxConcurrentSessions;maxIterations;cleanupTimer;constructor($){this.sessionTimeout=$?.sessionTimeout??1800000,this.maxConcurrentSessions=$?.maxConcurrentSessions??10,this.maxIterations=$?.maxIterations,this.cleanupTimer=setInterval(()=>{this.cleanupExpiredSessions()},300000)}async getOrCreateSession($,Z){if(this.sessions.get($))this.sessions.delete($),this.sessionContexts.delete($);if(this.sessions.size>=this.maxConcurrentSessions)this.removeOldestSession();let W=Z.sessionManager;if(W){console.warn(`[SessionRouter] Checking if session ${$} exists in state store resumeSession`);try{if(await W.get($)){let X=await Z.resumeSession($,{maxIterations:this.maxIterations});return console.warn(`[SessionRouter] Session ${$} resumed messages: ${JSON.stringify(X.messages)}`),this.sessions.set($,X),this.sessionContexts.set($,{sessionId:$,createdAt:Date.now(),lastAccessedAt:Date.now()}),X}}catch{}}let J=await Z.createSession({sessionId:$,maxIterations:this.maxIterations});return this.sessions.set($,J),this.sessionContexts.set($,{sessionId:$,createdAt:Date.now(),lastAccessedAt:Date.now()}),J}getSession($){let Z=this.sessions.get($);if(Z){let Y=this.sessionContexts.get($);if(Y)Y.lastAccessedAt=Date.now()}return Z}removeSession($){let Z=this.sessions.delete($);return this.sessionContexts.delete($),Z}getActiveSessions(){return Array.from(this.sessions.keys())}getSessionCount(){return this.sessions.size}cleanupExpiredSessions(){let $=Date.now(),Z=[];for(let[Y,W]of this.sessionContexts.entries())if($-W.lastAccessedAt>this.sessionTimeout)Z.push(Y);for(let Y of Z)this.removeSession(Y);if(Z.length>0)console.warn(`[SessionRouter] Cleaned up ${Z.length} expired sessions`)}removeOldestSession(){let $,Z=1/0;for(let[Y,W]of this.sessionContexts.entries())if(W.createdAt<Z)Z=W.createdAt,$=Y;if($)this.removeSession($),console.warn(`[SessionRouter] Removed oldest session: ${$}`)}destroy(){if(this.cleanupTimer)clearInterval(this.cleanupTimer),this.cleanupTimer=void 0;this.sessions.clear(),this.sessionContexts.clear()}}class AJ{agent;router;converter;debug;constructor($,Z){if(this.agent=$,this.debug=Z?.debug??!1,this.router=new D6({sessionTimeout:Z?.sessionTimeout,maxConcurrentSessions:Z?.maxConcurrentSessions,maxIterations:Z?.maxIterations}),this.converter=new O6({debug:this.debug}),this.debug)console.warn("[ACPAgent] Initialized with agent:",$.name),console.warn("[ACPAgent] Middlewares:",$.middlewareNames)}async*receiveMessage($,Z){let Y=Z?.session_id??this.generateSessionId();if(this.debug)console.warn(`[ACPAgent] Receiving ${$.length} messages for session: ${Y}`);try{let W=await this.router.getOrCreateSession(Y,this.agent),J=this.converter.convertFromACP($);if(this.debug)console.warn(`[ACPAgent] Converted to ${J.length} GoatChain messages`);let Q={},X=[];for(let z of $)if(z.role==="tool"&&z.tool_call_id){X.push(this.converter.convertFromACP([z])[0]);try{let N=typeof z.content==="string"?JSON.parse(z.content):z.content;if(N.answers)Q[z.tool_call_id]=N.answers}catch{}}let K=Object.keys(Q).length>0,V=W.hasCheckpoint;if(this.debug)console.warn(`[ACPAgent] Has tool results: ${K}, Has checkpoint: ${V}`);let B=J.filter((z)=>z.role==="user");if(B.length>0){let z=B[B.length-1],N=K?{askUser:{answers:Q}}:void 0;if(this.debug)console.warn(`[ACPAgent] Sending user message ${z.content} ${N?" with toolContext":""} `);W.send(z.content,N?{toolContext:N}:void 0)}else if(V&&!K){if(this.debug)console.warn("[ACPAgent] Resuming from checkpoint without new input")}let G=0,F=!1;for await(let z of this.converter.convertToACP(W.receive())){if(G++,this.debug)console.warn(`[ACPAgent] Event #${G}:`,z.role,z.metadata?.done?"(done)":"");if(yield z,z.metadata?.done)F=!0}if(F&&this.debug)console.warn(`[ACPAgent] Session ${Y} completed with ${G} events`)}catch(W){console.error("[ACPAgent] Error processing messages:",W),yield{role:"assistant",content:`Error: ${W instanceof Error?W.message:String(W)}`,metadata:{error:!0,done:!0}}}}async*receiveWithApprovals($,Z){let Y=Z?.session_id??this.generateSessionId();if(this.debug)console.warn(`[ACPAgent] Resuming with approvals for session: ${Y}`);try{let W=await this.router.getOrCreateSession(Y,this.agent),J=0,Q=!1;for await(let X of this.converter.convertToACP(W.receiveWithApprovals($))){if(J++,this.debug)console.warn(`[ACPAgent] Event #${J}:`,X.role,X.metadata?.done?"(done)":"");if(yield X,X.metadata?.done)Q=!0}if(Q&&this.debug)console.warn(`[ACPAgent] Session ${Y} completed with ${J} events`)}catch(W){console.error("[ACPAgent] Error processing approvals:",W),yield{role:"assistant",content:`Error: ${W instanceof Error?W.message:String(W)}`,metadata:{error:!0,done:!0}}}}getSessionInfo(){return{activeSessions:this.router.getActiveSessions(),sessionCount:this.router.getSessionCount()}}getSession($){return this.router.getSession($)}closeSession($){return this.router.removeSession($)}getAgent(){return this.agent}destroy(){if(this.router.destroy(),this.debug)console.warn("[ACPAgent] Destroyed")}generateSessionId(){return`acp-session-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}class C7{parentRegistry;allowedTools;constructor($,Z){this.parentRegistry=$,this.allowedTools=new Set(Z)}get($){if(!this.allowedTools.has($))return;return this.parentRegistry.get($)}list(){return Array.from(this.allowedTools).map(($)=>this.parentRegistry.get($)).filter(($)=>$!==void 0)}has($){return this.allowedTools.has($)&&this.parentRegistry.has($)}get size(){return this.list().length}toOpenAIFormat(){return this.list().map(($)=>({type:"function",function:{name:$.name,description:$.description,parameters:$.parameters}}))}register($){throw Error("FilteredToolRegistry is read-only. Use the parent ToolRegistry to register tools.")}unregister($){throw Error("FilteredToolRegistry is read-only. Use the parent ToolRegistry to unregister tools.")}}class x7{tools=new Map;register($){if(this.tools.has($.name))throw Error(`Tool "${$.name}" already registered`);this.tools.set($.name,$)}unregister($){return this.tools.delete($)}get($){return this.tools.get($)}list(){return Array.from(this.tools.values())}has($){return this.tools.has($)}get size(){return this.tools.size}toOpenAIFormat(){return this.list().map(($)=>({type:"function",function:{name:$.name,description:$.description,parameters:$.parameters}}))}}export{j1 as toLoopCheckpoint,Q5 as textContent,f6 as injectSystemReminderToLastUserMessage,X5 as imageContent,k$ as fromLoopCheckpoint,OU as fileSearchSpecialistPrompt,FP as fileSearchSpecialist,X1 as errorContent,e1 as ensureNotAborted,LU as createPlanModeMiddleware,EU as createParallelSubagentMiddleware,wX as createOpenAIAdapter,nJ as createModel,W8 as createInitialLoopState,v7 as createContextCompressionMiddleware,mX as createCommitModeMiddleware,m7 as compressSessionManually,Y8 as compose,_U as buildFileSearchSpecialistPrompt,_6 as WriteTool,E6 as WebSearchTool,x7 as ToolRegistry,L6 as TodoWriteTool,y$ as TodoPlanTool,i0 as StateStore,L1 as StateKeys,D6 as SessionRouter,R1 as Session,P0 as RetryPolicy,w6 as ReadTool,O6 as ProtocolConverter,Q1 as ModelError,vZ as InMemoryStateStore,I$ as InMemoryModelHealth,p0 as HookManager,N6 as GrepTool,i8 as GlobTool,C7 as FilteredToolRegistry,MY as FileStateStore,l8 as EditTool,c8 as BashTool,Z1 as BaseTool,bZ as BaseSessionManager,R1 as BaseSession,d8 as AstGrepSearchTool,m8 as AstGrepReplaceTool,g8 as AskUserTool,T6 as AgentMaxIterationsError,T0 as AgentAbortError,hZ as Agent,AJ as ACPAgent};
|