@lark-apaas/openclaw-extension-miaoda-coding 1.0.14 → 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- import{createRequire as e}from"node:module";import{execFile as t,spawn as n}from"node:child_process";import{randomUUID as r}from"node:crypto";import i,{readFileSync as a}from"node:fs";import o,{dirname as s,join as c,resolve as l}from"node:path";import{appendFile as u,mkdir as d,readFile as f,readdir as p,rm as m,writeFile as h}from"node:fs/promises";import*as g from"fs";import{readdir as _,readdirSync as v,realpath as y,realpathSync as b,stat as x,statSync as S}from"fs";import{basename as C,dirname as w,isAbsolute as T,normalize as E,posix as D,relative as O,resolve as k,sep as A}from"path";import{fileURLToPath as j}from"url";import{createRequire as M}from"module";import{fileURLToPath as N}from"node:url";var ee=Object.create,P=Object.defineProperty,F=Object.getOwnPropertyDescriptor,I=Object.getOwnPropertyNames,L=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),B=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=I(t),a=0,o=i.length,s;a<o;a++)s=i[a],!R.call(e,s)&&s!==n&&P(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=F(t,s))||r.enumerable});return e},V=(e,t,n)=>(n=e==null?{}:ee(L(e)),B(t||!e||!e.__esModule?P(n,`default`,{value:e,enumerable:!0}):n,e)),H=e(import.meta.url);function U(){return l(process.env.OPENCLAW_STATE_DIR||process.cwd())}function W(e){return c(e,`.agent`)}function G(e,t){return c(e,`app`,t)}function K(e,t){return c(e,t)}function q(e){let t=typeof e.workspaceDir==`string`&&e.workspaceDir!==``,n=typeof e.agentDir==`string`&&e.agentDir!==``;if(!t||!n)throw Error(`resolveToolPaths: workspaceDir and agentDir are required in tool factory context`);return{workspaceDir:e.workspaceDir,agentDir:e.agentDir,agentId:e.agentId,sessionKey:e.sessionKey}}var J=M(import.meta.url);function Y(e){let t=E(e);return t.length>1&&t[t.length-1]===A&&(t=t.substring(0,t.length-1)),t}const X=/[\\/]/g;function Z(e,t){return e.replace(X,t)}const te=/^[a-z]:[\\/]$/i;function ne(e){return e===`/`||te.test(e)}function re(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,a=process.platform===`win32`&&e.includes(`/`)||e.startsWith(`.`);return n&&(e=k(e)),(r||a)&&(e=Y(e)),e===`.`?``:Z(e[e.length-1]===i?e:e+i,i)}function ie(e,t){return t+e}function ae(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:Z(O(e,r),t.pathSeparator)+t.pathSeparator+n}}function oe(e){return e}function se(e,t,n){return t+e+n}function ce(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?ae(e,t):r?ie:oe}function le(e){return function(t,n){n.push(t.substring(e.length)||`.`)}}function ue(e){return function(t,n,r){let i=t.substring(e.length)||`.`;r.every(e=>e(i,!0))&&n.push(i)}}const de=(e,t)=>{t.push(e||`.`)},fe=(e,t,n)=>{let r=e||`.`;n.every(e=>e(r,!0))&&t.push(r)},pe=()=>{};function me(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?ue(e):le(e):r&&r.length?fe:de:pe}const he=(e,t,n,r)=>{r.every(t=>t(e,!1))&&n.files++},ge=(e,t,n,r)=>{r.every(t=>t(e,!1))&&t.push(e)},_e=(e,t,n,r)=>{n.files++},ve=(e,t)=>{t.push(e)},ye=()=>{};function be(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?ye:n&&n.length?r?he:ge:r?_e:ve}const xe=e=>e,Se=()=>[``].slice(0,0);function Ce(e){return e.group?Se:xe}const we=(e,t,n)=>{e.push({directory:t,files:n,dir:t})},Te=()=>{};function Ee(e){return e.group?we:Te}const De=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:a}}=t;r.enqueue(),i.realpath(e,(o,s)=>{if(o)return r.dequeue(a?null:o,t);i.stat(s,(i,o)=>{if(i)return r.dequeue(a?null:i,t);if(o.isDirectory()&&Ae(e,s,t))return r.dequeue(null,t);n(o,s),r.dequeue(null,t)})})},Oe=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:a}}=t;r.enqueue();try{let r=i.realpathSync(e),a=i.statSync(r);if(a.isDirectory()&&Ae(e,r,t))return;n(a,r)}catch(e){if(!a)throw e}};function ke(e,t){return!e.resolveSymlinks||e.excludeSymlinks?null:t?Oe:De}function Ae(e,t,n){if(n.options.useRealPaths)return je(t,n);let r=w(e),i=1;for(;r!==n.root&&i<2;){let e=n.symlinks.get(r);e&&(e===t||e.startsWith(t)||t.startsWith(e))?i++:r=w(r)}return n.symlinks.set(e,t),i>1}function je(e,t){return t.visited.includes(e+t.options.pathSeparator)}const Me=e=>e.counts,Ne=e=>e.groups,Pe=e=>e.paths,Fe=e=>e.paths.slice(0,e.options.maxFiles),Ie=(e,t,n)=>(Be(t,n,e.counts,e.options.suppressErrors),null),Le=(e,t,n)=>(Be(t,n,e.paths,e.options.suppressErrors),null),Re=(e,t,n)=>(Be(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),ze=(e,t,n)=>(Be(t,n,e.groups,e.options.suppressErrors),null);function Be(e,t,n,r){t(e&&!r?e:null,n)}function Ve(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?Me:Ie:r?t?Ne:ze:i?t?Fe:Re:t?Pe:Le}const He={withFileTypes:!0},Ue=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:a}=e;e.visited.push(t),e.counts.directories++,a.readdir(t||`.`,He,(t,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:t,e)})},We=(e,t,n,r,i)=>{let{fs:a}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=a.readdirSync(t||`.`,He)}catch(t){if(!e.options.suppressErrors)throw t}i(o,n,r)};function Ge(e){return e?We:Ue}var Ke=class{count=0;constructor(e){this.onQueueEmpty=e}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0))}},qe=class{_files=0;_directories=0;set files(e){this._files=e}get files(){return this._files}set directories(e){this._directories=e}get directories(){return this._directories}get dirs(){return this._directories}},Je=class{aborted=!1;abort(){this.aborted=!0}},Ye=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=Ve(t,this.isSynchronous),this.root=re(e,t),this.state={root:ne(this.root)?this.root:this.root.slice(0,-1),paths:[``].slice(0,0),groups:[],counts:new qe,options:t,queue:new Ke((e,t)=>this.callbackInvoker(t,e,n)),symlinks:new Map,visited:[``].slice(0,0),controller:new Je,fs:t.fs||g},this.joinPath=ce(this.root,t),this.pushDirectory=me(this.root,t),this.pushFile=be(t),this.getArray=Ce(t),this.groupFiles=Ee(t),this.resolveSymlink=ke(t,this.isSynchronous),this.walkDirectory=Ge(this.isSynchronous)}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,n)=>{let{paths:r,options:{filters:i,resolveSymlinks:a,excludeSymlinks:o,exclude:s,maxFiles:c,signal:l,useRealPaths:u,pathSeparator:d},controller:f}=this.state;if(f.aborted||l&&l.aborted||c&&r.length>c)return;let p=this.getArray(this.state.paths);for(let c=0;c<e.length;++c){let l=e[c];if(l.isFile()||l.isSymbolicLink()&&!a&&!o){let e=this.joinPath(l.name,t);this.pushFile(e,p,this.state.counts,i)}else if(l.isDirectory()){let e=se(l.name,t,this.state.options.pathSeparator);if(s&&s(l.name,e))continue;this.pushDirectory(e,r,i),this.walkDirectory(this.state,e,e,n-1,this.walk)}else if(this.resolveSymlink&&l.isSymbolicLink()){let e=ie(l.name,t);this.resolveSymlink(e,this.state,(t,r)=>{if(t.isDirectory()){if(r=re(r,this.state.options),s&&s(l.name,u?r:e+d))return;this.walkDirectory(this.state,r,u?r:e+d,n-1,this.walk)}else{r=u?r:e;let t=C(r),n=re(w(r),this.state.options);r=this.joinPath(t,n),this.pushFile(r,p,this.state.counts,i)}})}}this.groupFiles(this.state.groups,t,p)}};function Xe(e,t){return new Promise((n,r)=>{Ze(e,t,(e,t)=>{if(e)return r(e);n(t)})})}function Ze(e,t,n){new Ye(e,t,n).start()}function Qe(e,t){return new Ye(e,t).start()}var $e=class{constructor(e,t){this.root=e,this.options=t}withPromise(){return Xe(this.root,this.options)}withCallback(e){Ze(this.root,this.options,e)}sync(){return Qe(this.root,this.options)}};let et=null;try{J.resolve(`picomatch`),et=J(`picomatch`)}catch{}var tt=class{globCache={};options={maxDepth:1/0,suppressErrors:!0,pathSeparator:A,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction}group(){return this.options.group=!0,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=!0,this}withRelativePaths(){return this.options.relativePaths=!0,this}withDirs(){return this.options.includeDirs=!0,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=!0,this.options.includeBasePath=!0,this}withErrors(){return this.options.suppressErrors=!1,this}withSymlinks({resolvePaths:e=!0}={}){return this.options.resolveSymlinks=!0,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=!0,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=!0,this.options.includeDirs=!0,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=!0,this}crawl(e){return new $e(e||`.`,this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new $e(e||`.`,this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:!0})}globWithOptions(e,...t){let n=this.globFunction||et;if(!n)throw Error(`Please specify a glob function to use glob matching.`);var r=this.globCache[e.join(`\0`)];return r||(r=n(e,...t),this.globCache[e.join(`\0`)]=r),this.options.filters.push(e=>r(e)),this}},nt=z(((e,t)=>{let n=`[^\\\\/]`,r=`[^/]`,i=`(?:\\/|$)`,a=`(?:^|\\/)`,o=`\\.{1,2}${i}`,s={DOT_LITERAL:`\\.`,PLUS_LITERAL:`\\+`,QMARK_LITERAL:`\\?`,SLASH_LITERAL:`\\/`,ONE_CHAR:`(?=.)`,QMARK:r,END_ANCHOR:i,DOTS_SLASH:o,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!${a}${o})`,NO_DOT_SLASH:`(?!\\.{0,1}${i})`,NO_DOTS_SLASH:`(?!${o})`,QMARK_NO_DOT:`[^.\\/]`,STAR:`${r}*?`,START_ANCHOR:a,SEP:`/`},c={...s,SLASH_LITERAL:`[\\\\/]`,QMARK:n,STAR:`${n}*?`,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:`\\`};t.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:{__proto__:null,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`},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(e){return{"!":{type:`negate`,open:`(?:(?!(?:`,close:`))${e.STAR})`},"?":{type:`qmark`,open:`(?:`,close:`)?`},"+":{type:`plus`,open:`(?:`,close:`)+`},"*":{type:`star`,open:`(?:`,close:`)*`},"@":{type:`at`,open:`(?:`,close:`)`}}},globChars(e){return e===!0?c:s}}})),rt=z((e=>{let{REGEX_BACKSLASH:t,REGEX_REMOVE_BACKSLASH:n,REGEX_SPECIAL_CHARS:r,REGEX_SPECIAL_CHARS_GLOBAL:i}=nt();e.isObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),e.hasRegexChars=e=>r.test(e),e.isRegexChar=t=>t.length===1&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(i,`\\$1`),e.toPosixSlashes=e=>e.replace(t,`/`),e.isWindows=()=>{if(typeof navigator<`u`&&navigator.platform){let e=navigator.platform.toLowerCase();return e===`win32`||e===`windows`}return typeof process<`u`&&process.platform?process.platform===`win32`:!1},e.removeBackslashes=e=>e.replace(n,e=>e===`\\`?``:e),e.escapeLast=(t,n,r)=>{let i=t.lastIndexOf(n,r);return i===-1?t:t[i-1]===`\\`?e.escapeLast(t,n,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let n=e;return n.startsWith(`./`)&&(n=n.slice(2),t.prefix=`./`),n},e.wrapOutput=(e,t={},n={})=>{let r=`${n.contains?``:`^`}(?:${e})${n.contains?``:`$`}`;return t.negated===!0&&(r=`(?:^(?!${r}).*$)`),r},e.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:`/`),r=n[n.length-1];return r===``?n[n.length-2]:r}})),it=z(((e,t)=>{let n=rt(),{CHAR_ASTERISK:r,CHAR_AT:i,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_EXCLAMATION_MARK:c,CHAR_FORWARD_SLASH:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_LEFT_PARENTHESES:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_PLUS:p,CHAR_QUESTION_MARK:m,CHAR_RIGHT_CURLY_BRACE:h,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=nt(),v=e=>e===l||e===a,y=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)};t.exports=(e,t)=>{let b=t||{},x=e.length-1,S=b.parts===!0||b.scanToEnd===!0,C=[],w=[],T=[],E=e,D=-1,O=0,k=0,A=!1,j=!1,M=!1,N=!1,ee=!1,P=!1,F=!1,I=!1,L=!1,R=!1,z=0,B,V,H={value:``,depth:0,isGlob:!1},U=()=>D>=x,W=()=>E.charCodeAt(D+1),G=()=>(B=V,E.charCodeAt(++D));for(;D<x;){V=G();let e;if(V===a){F=H.backslashes=!0,V=G(),V===u&&(P=!0);continue}if(P===!0||V===u){for(z++;U()!==!0&&(V=G());){if(V===a){F=H.backslashes=!0,G();continue}if(V===u){z++;continue}if(P!==!0&&V===s&&(V=G())===s){if(A=H.isBrace=!0,M=H.isGlob=!0,R=!0,S===!0)continue;break}if(P!==!0&&V===o){if(A=H.isBrace=!0,M=H.isGlob=!0,R=!0,S===!0)continue;break}if(V===h&&(z--,z===0)){P=!1,A=H.isBrace=!0,R=!0;break}}if(S===!0)continue;break}if(V===l){if(C.push(D),w.push(H),H={value:``,depth:0,isGlob:!1},R===!0)continue;if(B===s&&D===O+1){O+=2;continue}k=D+1;continue}if(b.noext!==!0&&(V===p||V===i||V===r||V===m||V===c)&&W()===d){if(M=H.isGlob=!0,N=H.isExtglob=!0,R=!0,V===c&&D===O&&(L=!0),S===!0){for(;U()!==!0&&(V=G());){if(V===a){F=H.backslashes=!0,V=G();continue}if(V===g){M=H.isGlob=!0,R=!0;break}}continue}break}if(V===r){if(B===r&&(ee=H.isGlobstar=!0),M=H.isGlob=!0,R=!0,S===!0)continue;break}if(V===m){if(M=H.isGlob=!0,R=!0,S===!0)continue;break}if(V===f){for(;U()!==!0&&(e=G());){if(e===a){F=H.backslashes=!0,G();continue}if(e===_){j=H.isBracket=!0,M=H.isGlob=!0,R=!0;break}}if(S===!0)continue;break}if(b.nonegate!==!0&&V===c&&D===O){I=H.negated=!0,O++;continue}if(b.noparen!==!0&&V===d){if(M=H.isGlob=!0,S===!0){for(;U()!==!0&&(V=G());){if(V===d){F=H.backslashes=!0,V=G();continue}if(V===g){R=!0;break}}continue}break}if(M===!0){if(R=!0,S===!0)continue;break}}b.noext===!0&&(N=!1,M=!1);let K=E,q=``,J=``;O>0&&(q=E.slice(0,O),E=E.slice(O),k-=O),K&&M===!0&&k>0?(K=E.slice(0,k),J=E.slice(k)):M===!0?(K=``,J=E):K=E,K&&K!==``&&K!==`/`&&K!==E&&v(K.charCodeAt(K.length-1))&&(K=K.slice(0,-1)),b.unescape===!0&&(J&&=n.removeBackslashes(J),K&&F===!0&&(K=n.removeBackslashes(K)));let Y={prefix:q,input:e,start:O,base:K,glob:J,isBrace:A,isBracket:j,isGlob:M,isExtglob:N,isGlobstar:ee,negated:I,negatedExtglob:L};if(b.tokens===!0&&(Y.maxDepth=0,v(V)||w.push(H),Y.tokens=w),b.parts===!0||b.tokens===!0){let t;for(let n=0;n<C.length;n++){let r=t?t+1:O,i=C[n],a=e.slice(r,i);b.tokens&&(n===0&&O!==0?(w[n].isPrefix=!0,w[n].value=q):w[n].value=a,y(w[n]),Y.maxDepth+=w[n].depth),(n!==0||a!==``)&&T.push(a),t=i}if(t&&t+1<e.length){let n=e.slice(t+1);T.push(n),b.tokens&&(w[w.length-1].value=n,y(w[w.length-1]),Y.maxDepth+=w[w.length-1].depth)}Y.slashes=C,Y.parts=T}return Y}})),at=z(((e,t)=>{let n=nt(),r=rt(),{MAX_LENGTH:i,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:s,REPLACEMENTS:c}=n,l=(e,t)=>{if(typeof t.expandRange==`function`)return t.expandRange(...e,t);e.sort();let n=`[${e.join(`-`)}]`;try{new RegExp(n)}catch{return e.map(e=>r.escapeRegex(e)).join(`..`)}return n},u=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,d=e=>{let t=[],n=0,r=0,i=0,a=``,o=!1;for(let s of e){if(o===!0){a+=s,o=!1;continue}if(s===`\\`){a+=s,o=!0;continue}if(s===`"`){i=i===1?0:1,a+=s;continue}if(i===0){if(s===`[`)n++;else if(s===`]`&&n>0)n--;else if(n===0){if(s===`(`)r++;else if(s===`)`&&r>0)r--;else if(s===`|`&&r===0){t.push(a),a=``;continue}}}a+=s}return t.push(a),t},f=e=>{let t=!1;for(let n of e){if(t===!0){t=!1;continue}if(n===`\\`){t=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},p=e=>{let t=e.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=!0);if(f(t))return t.replace(/\\(.)/g,`$1`)},m=e=>{let t=e.map(p).filter(Boolean);for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let r=t[e],i=t[n],a=r[0];if(!(!a||r!==a.repeat(r.length)||i!==a.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},h=(e,t=!0)=>{if(e[0]!==`+`&&e[0]!==`*`||e[1]!==`(`)return;let n=0,r=0,i=0,a=!1;for(let o=1;o<e.length;o++){let s=e[o];if(a===!0){a=!1;continue}if(s===`\\`){a=!0;continue}if(s===`"`){i=i===1?0:1;continue}if(i!==1){if(s===`[`){n++;continue}if(s===`]`&&n>0){n--;continue}if(!(n>0)){if(s===`(`){r++;continue}if(s===`)`&&(r--,r===0))return t===!0&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},g=e=>{let t=0,n=[];for(;t<e.length;){let r=h(e.slice(t),!1);if(!r||r.type!==`*`)return;let i=d(r.body).map(e=>e.trim());if(i.length!==1)return;let a=p(i[0]);if(!a||a.length!==1)return;n.push(a),t+=r.end+1}if(!(n.length<1))return`${n.length===1?r.escapeRegex(n[0]):`[${n.map(e=>r.escapeRegex(e)).join(``)}]`}*`},_=e=>{let t=0,n=e.trim(),r=h(n);for(;r;)t++,n=r.body.trim(),r=h(n);return t},v=(e,t)=>{if(t.maxExtglobRecursion===!1)return{risky:!1};let r=typeof t.maxExtglobRecursion==`number`?t.maxExtglobRecursion:n.DEFAULT_MAX_EXTGLOB_RECURSION,i=d(e).map(e=>e.trim());if(i.length>1&&(i.some(e=>e===``)||i.some(e=>/^[*?]+$/.test(e))||m(i)))return{risky:!0};for(let e of i){let t=g(e);if(t)return{risky:!0,safeOutput:t};if(_(e)>r)return{risky:!0}}return{risky:!1}},y=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);e=c[e]||e;let d={...t},f=typeof d.maxLength==`number`?Math.min(i,d.maxLength):i,p=e.length;if(p>f)throw SyntaxError(`Input length: ${p}, exceeds maximum allowed length: ${f}`);let m={type:`bos`,value:``,output:d.prepend||``},h=[m],g=d.capture?``:`?:`,_=n.globChars(d.windows),b=n.extglobChars(_),{DOT_LITERAL:x,PLUS_LITERAL:S,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:T,NO_DOT:E,NO_DOT_SLASH:D,NO_DOTS_SLASH:O,QMARK:k,QMARK_NO_DOT:A,STAR:j,START_ANCHOR:M}=_,N=e=>`(${g}(?:(?!${M}${e.dot?T:x}).)*?)`,ee=d.dot?``:E,P=d.dot?k:A,F=d.bash===!0?N(d):j;d.capture&&(F=`(${F})`),typeof d.noext==`boolean`&&(d.noextglob=d.noext);let I={input:e,index:-1,start:0,dot:d.dot===!0,consumed:``,output:``,prefix:``,backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:h};e=r.removePrefix(e,I),p=e.length;let L=[],R=[],z=[],B=m,V,H=()=>I.index===p-1,U=I.peek=(t=1)=>e[I.index+t],W=I.advance=()=>e[++I.index]||``,G=()=>e.slice(I.index+1),K=(e=``,t=0)=>{I.consumed+=e,I.index+=t},q=e=>{I.output+=e.output==null?e.value:e.output,K(e.value)},J=()=>{let e=1;for(;U()===`!`&&(U(2)!==`(`||U(3)===`?`);)W(),I.start++,e++;return e%2==0?!1:(I.negated=!0,I.start++,!0)},Y=e=>{I[e]++,z.push(e)},X=e=>{I[e]--,z.pop()},Z=e=>{if(B.type===`globstar`){let t=I.braces>0&&(e.type===`comma`||e.type===`brace`),n=e.extglob===!0||L.length&&(e.type===`pipe`||e.type===`paren`);e.type!==`slash`&&e.type!==`paren`&&!t&&!n&&(I.output=I.output.slice(0,-B.output.length),B.type=`star`,B.value=`*`,B.output=F,I.output+=B.output)}if(L.length&&e.type!==`paren`&&(L[L.length-1].inner+=e.value),(e.value||e.output)&&q(e),B&&B.type===`text`&&e.type===`text`){B.output=(B.output||B.value)+e.value,B.value+=e.value;return}e.prev=B,h.push(e),B=e},te=(e,t)=>{let n={...b[t],conditions:1,inner:``};n.prev=B,n.parens=I.parens,n.output=I.output,n.startIndex=I.index,n.tokensIndex=h.length;let r=(d.capture?`(`:``)+n.open;Y(`parens`),Z({type:e,value:t,output:I.output?``:w}),Z({type:`paren`,extglob:!0,value:W(),output:r}),L.push(n)},ne=n=>{let i=e.slice(n.startIndex,I.index+1),a=v(e.slice(n.startIndex+2,I.index),d);if((n.type===`plus`||n.type===`star`)&&a.risky){let e=a.safeOutput?(n.output?``:w)+(d.capture?`(${a.safeOutput})`:a.safeOutput):void 0,t=h[n.tokensIndex];t.type=`text`,t.value=i,t.output=e||r.escapeRegex(i);for(let e=n.tokensIndex+1;e<h.length;e++)h[e].value=``,h[e].output=``,delete h[e].suffix;I.output=n.output+t.output,I.backtrack=!0,Z({type:`paren`,extglob:!0,value:V,output:``}),X(`parens`);return}let o=n.close+(d.capture?`)`:``),s;if(n.type===`negate`){let e=F;n.inner&&n.inner.length>1&&n.inner.includes(`/`)&&(e=N(d)),(e!==F||H()||/^\)+$/.test(G()))&&(o=n.close=`)$))${e}`),n.inner.includes(`*`)&&(s=G())&&/^\.[^\\/.]+$/.test(s)&&(o=n.close=`)${y(s,{...t,fastpaths:!1}).output})${e})`),n.prev.type===`bos`&&(I.negatedExtglob=!0)}Z({type:`paren`,extglob:!0,value:V,output:o}),X(`parens`)};if(d.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(s,(e,t,r,i,a,o)=>i===`\\`?(n=!0,e):i===`?`?t?t+i+(a?k.repeat(a.length):``):o===0?P+(a?k.repeat(a.length):``):k.repeat(r.length):i===`.`?x.repeat(r.length):i===`*`?t?t+i+(a?F:``):F:t?e:`\\${e}`);return n===!0&&(i=d.unescape===!0?i.replace(/\\/g,``):i.replace(/\\+/g,e=>e.length%2==0?`\\\\`:e?`\\`:``)),i===e&&d.contains===!0?(I.output=e,I):(I.output=r.wrapOutput(i,I,t),I)}for(;!H();){if(V=W(),V===`\0`)continue;if(V===`\\`){let e=U();if(e===`/`&&d.bash!==!0||e===`.`||e===`;`)continue;if(!e){V+=`\\`,Z({type:`text`,value:V});continue}let t=/^\\+/.exec(G()),n=0;if(t&&t[0].length>2&&(n=t[0].length,I.index+=n,n%2!=0&&(V+=`\\`)),d.unescape===!0?V=W():V+=W(),I.brackets===0){Z({type:`text`,value:V});continue}}if(I.brackets>0&&(V!==`]`||B.value===`[`||B.value===`[^`)){if(d.posix!==!1&&V===`:`){let e=B.value.slice(1);if(e.includes(`[`)&&(B.posix=!0,e.includes(`:`))){let e=B.value.lastIndexOf(`[`),t=B.value.slice(0,e),n=a[B.value.slice(e+2)];if(n){B.value=t+n,I.backtrack=!0,W(),!m.output&&h.indexOf(B)===1&&(m.output=w);continue}}}(V===`[`&&U()!==`:`||V===`-`&&U()===`]`)&&(V=`\\${V}`),V===`]`&&(B.value===`[`||B.value===`[^`)&&(V=`\\${V}`),d.posix===!0&&V===`!`&&B.value===`[`&&(V=`^`),B.value+=V,q({value:V});continue}if(I.quotes===1&&V!==`"`){V=r.escapeRegex(V),B.value+=V,q({value:V});continue}if(V===`"`){I.quotes=I.quotes===1?0:1,d.keepQuotes===!0&&Z({type:`text`,value:V});continue}if(V===`(`){Y(`parens`),Z({type:`paren`,value:V});continue}if(V===`)`){if(I.parens===0&&d.strictBrackets===!0)throw SyntaxError(u(`opening`,`(`));let e=L[L.length-1];if(e&&I.parens===e.parens+1){ne(L.pop());continue}Z({type:`paren`,value:V,output:I.parens?`)`:`\\)`}),X(`parens`);continue}if(V===`[`){if(d.nobracket===!0||!G().includes(`]`)){if(d.nobracket!==!0&&d.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));V=`\\${V}`}else Y(`brackets`);Z({type:`bracket`,value:V});continue}if(V===`]`){if(d.nobracket===!0||B&&B.type===`bracket`&&B.value.length===1){Z({type:`text`,value:V,output:`\\${V}`});continue}if(I.brackets===0){if(d.strictBrackets===!0)throw SyntaxError(u(`opening`,`[`));Z({type:`text`,value:V,output:`\\${V}`});continue}X(`brackets`);let e=B.value.slice(1);if(B.posix!==!0&&e[0]===`^`&&!e.includes(`/`)&&(V=`/${V}`),B.value+=V,q({value:V}),d.literalBrackets===!1||r.hasRegexChars(e))continue;let t=r.escapeRegex(B.value);if(I.output=I.output.slice(0,-B.value.length),d.literalBrackets===!0){I.output+=t,B.value=t;continue}B.value=`(${g}${t}|${B.value})`,I.output+=B.value;continue}if(V===`{`&&d.nobrace!==!0){Y(`braces`);let e={type:`brace`,value:V,output:`(`,outputIndex:I.output.length,tokensIndex:I.tokens.length};R.push(e),Z(e);continue}if(V===`}`){let e=R[R.length-1];if(d.nobrace===!0||!e){Z({type:`text`,value:V,output:V});continue}let t=`)`;if(e.dots===!0){let e=h.slice(),n=[];for(let t=e.length-1;t>=0&&(h.pop(),e[t].type!==`brace`);t--)e[t].type!==`dots`&&n.unshift(e[t].value);t=l(n,d),I.backtrack=!0}if(e.comma!==!0&&e.dots!==!0){let n=I.output.slice(0,e.outputIndex),r=I.tokens.slice(e.tokensIndex);e.value=e.output=`\\{`,V=t=`\\}`,I.output=n;for(let e of r)I.output+=e.output||e.value}Z({type:`brace`,value:V,output:t}),X(`braces`),R.pop();continue}if(V===`|`){L.length>0&&L[L.length-1].conditions++,Z({type:`text`,value:V});continue}if(V===`,`){let e=V,t=R[R.length-1];t&&z[z.length-1]===`braces`&&(t.comma=!0,e=`|`),Z({type:`comma`,value:V,output:e});continue}if(V===`/`){if(B.type===`dot`&&I.index===I.start+1){I.start=I.index+1,I.consumed=``,I.output=``,h.pop(),B=m;continue}Z({type:`slash`,value:V,output:C});continue}if(V===`.`){if(I.braces>0&&B.type===`dot`){B.value===`.`&&(B.output=x);let e=R[R.length-1];B.type=`dots`,B.output+=V,B.value+=V,e.dots=!0;continue}if(I.braces+I.parens===0&&B.type!==`bos`&&B.type!==`slash`){Z({type:`text`,value:V,output:x});continue}Z({type:`dot`,value:V,output:x});continue}if(V===`?`){if(!(B&&B.value===`(`)&&d.noextglob!==!0&&U()===`(`&&U(2)!==`?`){te(`qmark`,V);continue}if(B&&B.type===`paren`){let e=U(),t=V;(B.value===`(`&&!/[!=<:]/.test(e)||e===`<`&&!/<([!=]|\w+>)/.test(G()))&&(t=`\\${V}`),Z({type:`text`,value:V,output:t});continue}if(d.dot!==!0&&(B.type===`slash`||B.type===`bos`)){Z({type:`qmark`,value:V,output:A});continue}Z({type:`qmark`,value:V,output:k});continue}if(V===`!`){if(d.noextglob!==!0&&U()===`(`&&(U(2)!==`?`||!/[!=<:]/.test(U(3)))){te(`negate`,V);continue}if(d.nonegate!==!0&&I.index===0){J();continue}}if(V===`+`){if(d.noextglob!==!0&&U()===`(`&&U(2)!==`?`){te(`plus`,V);continue}if(B&&B.value===`(`||d.regex===!1){Z({type:`plus`,value:V,output:S});continue}if(B&&(B.type===`bracket`||B.type===`paren`||B.type===`brace`)||I.parens>0){Z({type:`plus`,value:V});continue}Z({type:`plus`,value:S});continue}if(V===`@`){if(d.noextglob!==!0&&U()===`(`&&U(2)!==`?`){Z({type:`at`,extglob:!0,value:V,output:``});continue}Z({type:`text`,value:V});continue}if(V!==`*`){(V===`$`||V===`^`)&&(V=`\\${V}`);let e=o.exec(G());e&&(V+=e[0],I.index+=e[0].length),Z({type:`text`,value:V});continue}if(B&&(B.type===`globstar`||B.star===!0)){B.type=`star`,B.star=!0,B.value+=V,B.output=F,I.backtrack=!0,I.globstar=!0,K(V);continue}let t=G();if(d.noextglob!==!0&&/^\([^?]/.test(t)){te(`star`,V);continue}if(B.type===`star`){if(d.noglobstar===!0){K(V);continue}let n=B.prev,r=n.prev,i=n.type===`slash`||n.type===`bos`,a=r&&(r.type===`star`||r.type===`globstar`);if(d.bash===!0&&(!i||t[0]&&t[0]!==`/`)){Z({type:`star`,value:V,output:``});continue}let o=I.braces>0&&(n.type===`comma`||n.type===`brace`),s=L.length&&(n.type===`pipe`||n.type===`paren`);if(!i&&n.type!==`paren`&&!o&&!s){Z({type:`star`,value:V,output:``});continue}for(;t.slice(0,3)===`/**`;){let n=e[I.index+4];if(n&&n!==`/`)break;t=t.slice(3),K(`/**`,3)}if(n.type===`bos`&&H()){B.type=`globstar`,B.value+=V,B.output=N(d),I.output=B.output,I.globstar=!0,K(V);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&!a&&H()){I.output=I.output.slice(0,-(n.output+B.output).length),n.output=`(?:${n.output}`,B.type=`globstar`,B.output=N(d)+(d.strictSlashes?`)`:`|$)`),B.value+=V,I.globstar=!0,I.output+=n.output+B.output,K(V);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&t[0]===`/`){let e=t[1]===void 0?``:`|$`;I.output=I.output.slice(0,-(n.output+B.output).length),n.output=`(?:${n.output}`,B.type=`globstar`,B.output=`${N(d)}${C}|${C}${e})`,B.value+=V,I.output+=n.output+B.output,I.globstar=!0,K(V+W()),Z({type:`slash`,value:`/`,output:``});continue}if(n.type===`bos`&&t[0]===`/`){B.type=`globstar`,B.value+=V,B.output=`(?:^|${C}|${N(d)}${C})`,I.output=B.output,I.globstar=!0,K(V+W()),Z({type:`slash`,value:`/`,output:``});continue}I.output=I.output.slice(0,-B.output.length),B.type=`globstar`,B.output=N(d),B.value+=V,I.output+=B.output,I.globstar=!0,K(V);continue}let n={type:`star`,value:V,output:F};if(d.bash===!0){n.output=`.*?`,(B.type===`bos`||B.type===`slash`)&&(n.output=ee+n.output),Z(n);continue}if(B&&(B.type===`bracket`||B.type===`paren`)&&d.regex===!0){n.output=V,Z(n);continue}(I.index===I.start||B.type===`slash`||B.type===`dot`)&&(B.type===`dot`?(I.output+=D,B.output+=D):d.dot===!0?(I.output+=O,B.output+=O):(I.output+=ee,B.output+=ee),U()!==`*`&&(I.output+=w,B.output+=w)),Z(n)}for(;I.brackets>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));I.output=r.escapeLast(I.output,`[`),X(`brackets`)}for(;I.parens>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`)`));I.output=r.escapeLast(I.output,`(`),X(`parens`)}for(;I.braces>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`}`));I.output=r.escapeLast(I.output,`{`),X(`braces`)}if(d.strictSlashes!==!0&&(B.type===`star`||B.type===`bracket`)&&Z({type:`maybe_slash`,value:``,output:`${C}?`}),I.backtrack===!0){I.output=``;for(let e of I.tokens)I.output+=e.output==null?e.value:e.output,e.suffix&&(I.output+=e.suffix)}return I};y.fastpaths=(e,t)=>{let a={...t},o=typeof a.maxLength==`number`?Math.min(i,a.maxLength):i,s=e.length;if(s>o)throw SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`);e=c[e]||e;let{DOT_LITERAL:l,SLASH_LITERAL:u,ONE_CHAR:d,DOTS_SLASH:f,NO_DOT:p,NO_DOTS:m,NO_DOTS_SLASH:h,STAR:g,START_ANCHOR:_}=n.globChars(a.windows),v=a.dot?m:p,y=a.dot?h:p,b=a.capture?``:`?:`,x={negated:!1,prefix:``},S=a.bash===!0?`.*?`:g;a.capture&&(S=`(${S})`);let C=e=>e.noglobstar===!0?S:`(${b}(?:(?!${_}${e.dot?f:l}).)*?)`,w=e=>{switch(e){case`*`:return`${v}${d}${S}`;case`.*`:return`${l}${d}${S}`;case`*.*`:return`${v}${S}${l}${d}${S}`;case`*/*`:return`${v}${S}${u}${d}${y}${S}`;case`**`:return v+C(a);case`**/*`:return`(?:${v}${C(a)}${u})?${y}${d}${S}`;case`**/*.*`:return`(?:${v}${C(a)}${u})?${y}${S}${l}${d}${S}`;case`**/.*`:return`(?:${v}${C(a)}${u})?${l}${d}${S}`;default:{let t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;let n=w(t[1]);return n?n+l+t[2]:void 0}}},T=w(r.removePrefix(e,x));return T&&a.strictSlashes!==!0&&(T+=`${u}?`),T},t.exports=y})),ot=z(((e,t)=>{let n=it(),r=at(),i=rt(),a=nt(),o=e=>e&&typeof e==`object`&&!Array.isArray(e),s=(e,t,n=!1)=>{if(Array.isArray(e)){let r=e.map(e=>s(e,t,n));return e=>{for(let t of r){let n=t(e);if(n)return n}return!1}}let r=o(e)&&e.tokens&&e.input;if(e===``||typeof e!=`string`&&!r)throw TypeError(`Expected pattern to be a non-empty string`);let i=t||{},a=i.windows,c=r?s.compileRe(e,t):s.makeRe(e,t,!1,!0),l=c.state;delete c.state;let u=()=>!1;if(i.ignore){let e={...t,ignore:null,onMatch:null,onResult:null};u=s(i.ignore,e,n)}let d=(n,r=!1)=>{let{isMatch:o,match:d,output:f}=s.test(n,c,t,{glob:e,posix:a}),p={glob:e,state:l,regex:c,posix:a,input:n,output:f,match:d,isMatch:o};return typeof i.onResult==`function`&&i.onResult(p),o===!1?(p.isMatch=!1,r?p:!1):u(n)?(typeof i.onIgnore==`function`&&i.onIgnore(p),p.isMatch=!1,r?p:!1):(typeof i.onMatch==`function`&&i.onMatch(p),r?p:!0)};return n&&(d.state=l),d};s.test=(e,t,n,{glob:r,posix:a}={})=>{if(typeof e!=`string`)throw TypeError(`Expected input to be a string`);if(e===``)return{isMatch:!1,output:``};let o=n||{},c=o.format||(a?i.toPosixSlashes:null),l=e===r,u=l&&c?c(e):e;return l===!1&&(u=c?c(e):e,l=u===r),(l===!1||o.capture===!0)&&(l=o.matchBase===!0||o.basename===!0?s.matchBase(e,t,n,a):t.exec(u)),{isMatch:!!l,match:l,output:u}},s.matchBase=(e,t,n)=>(t instanceof RegExp?t:s.makeRe(t,n)).test(i.basename(e)),s.isMatch=(e,t,n)=>s(t,n)(e),s.parse=(e,t)=>Array.isArray(e)?e.map(e=>s.parse(e,t)):r(e,{...t,fastpaths:!1}),s.scan=(e,t)=>n(e,t),s.compileRe=(e,t,n=!1,r=!1)=>{if(n===!0)return e.output;let i=t||{},a=i.contains?``:`^`,o=i.contains?``:`$`,c=`${a}(?:${e.output})${o}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let l=s.toRegex(c,t);return r===!0&&(l.state=e),l},s.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||typeof e!=`string`)throw TypeError(`Expected a non-empty string`);let a={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]===`.`||e[0]===`*`)&&(a.output=r.fastpaths(e,t)),a.output||(a=r(e,t)),s.compileRe(a,t,n,i)},s.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?`i`:``))}catch(e){if(t&&t.debug===!0)throw e;return/$^/}},s.constants=a,t.exports=s})),st=V(z(((e,t)=>{let n=ot(),r=rt();function i(e,t,i=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:r.isWindows()}),n(e,t,i)}Object.assign(i,n),t.exports=i}))(),1);const ct=Array.isArray,lt=/\\/g,ut=process.platform===`win32`,dt=/^(\/?\.\.)+$/;function ft(e,t={}){let n=e.length,r=Array(n),i=Array(n),a,o;for(a=0;a<n;a++){let n=vt(e[a]);r[a]=n;let s=n.length,c=Array(s);for(o=0;o<s;o++)c[o]=(0,st.default)(n[o],t);i[a]=c}return e=>{let s=e.split(`/`);if(s[0]===`..`&&dt.test(e))return!0;for(a=0;a<n;a++){let e=r[a],n=i[a],c=s.length,l=Math.min(c,e.length);for(o=0;o<l;){let r=e[o];if(r.includes(`/`))return!0;if(!n[o](s[o]))break;if(!t.noglobstar&&r===`**`)return!0;o++}if(o===c)return!0}return!1}}const pt=/^[A-Z]:\/$/i,mt=ut?e=>pt.test(e):e=>e===`/`;function ht(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let t=e.length+ +!mt(e);return(e,n)=>e.slice(t,n?-1:void 0)||`.`}let r=t.slice(e.length+1);return r?(e,t)=>{if(e===`.`)return r;let n=`${r}/${e}`;return t?n.slice(0,-1):n}:(e,t)=>t&&e!==`.`?e.slice(0,-1):e}return n?t=>D.relative(e,t)||`.`:n=>D.relative(e,`${t}/${n}`)||`.`}function gt(e,t){if(t.startsWith(`${e}/`)){let n=t.slice(e.length+1);return e=>`${n}/${e}`}return n=>{let r=D.relative(e,`${t}/${n}`);return n[n.length-1]===`/`&&r!==``?`${r}/`:r||`.`}}const _t={parts:!0};function vt(e){let t=st.default.scan(e,_t);return t.parts?.length?t.parts:[e]}const yt=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,bt=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,xt=ut?e=>e.replace(bt,`\\$&`):e=>e.replace(yt,`\\$&`);function St(e,t){if(t?.caseSensitiveMatch===!1)return!0;let n=st.default.scan(e);return n.isGlob||n.negated}function Ct(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString(`es`)}]`,...e)}function wt(e){return typeof e==`string`?[e]:e??[]}const Tt=/^(\/?\.\.)+/,Et=/\\(?=[()[\]{}!*+?@|])/g;function Dt(e,t,n,r){let i=t.cwd,a=e;e[e.length-1]===`/`&&(a=e.slice(0,-1)),a[a.length-1]!==`*`&&t.expandDirectories&&(a+=`/**`);let o=xt(i);a=T(a.replace(Et,``))?D.relative(o,a):D.normalize(a);let s=Tt.exec(a)?.[0],c=vt(a);if(s){let e=(s.length+1)/3,t=0,r=o.split(`/`);for(;t<e&&c[t+e]===r[r.length+t-e];)a=a.slice(0,(e-t-1)*3)+a.slice((e-t)*3+c[t+e].length+1)||`.`,t++;let l=D.join(i,s.slice(t*3));l[0]!==`.`&&n.root.length>l.length&&(n.root=l,n.depthOffset=-e+t)}if(!r&&n.depthOffset>=0){n.commonPath??=c;let e=[],t=Math.min(n.commonPath.length,c.length);for(let r=0;r<t;r++){let t=c[r];if(t===`**`&&!c[r+1]){e.pop();break}if(r===c.length-1||t!==n.commonPath[r]||St(t))break;e.push(t)}n.depthOffset=e.length,n.commonPath=e,n.root=e.length>0?D.join(i,...e):i}return a}function Ot(e,t,n){let r=[],i=[];for(let t of e.ignore)t&&(t[0]!==`!`||t[1]===`(`)&&i.push(Dt(t,e,n,!0));for(let a of t)a&&(a[0]!==`!`||a[1]===`(`?r.push(Dt(a,e,n,!1)):(a[1]!==`!`||a[2]===`(`)&&i.push(Dt(a.slice(1),e,n,!0)));return{match:r,ignore:i}}function kt(e,t){let n=e.cwd,r={root:n,depthOffset:0},i=Ot(e,t,r);e.debug&&Ct(`internal processing patterns:`,i);let{absolute:a,caseSensitiveMatch:o,debug:s,dot:c,followSymbolicLinks:l,onlyDirectories:u}=e,d=r.root.replace(lt,``),f={dot:c,nobrace:e.braceExpansion===!1,nocase:!o,noextglob:e.extglob===!1,noglobstar:e.globstar===!1,posix:!0},p=(0,st.default)(i.match,f),m=(0,st.default)(i.ignore,f),h=ft(i.match,f),g=ht(n,d,a),_=a?g:ht(n,d,!0),v=(e,t)=>{let n=_(t,!0);return n!==`.`&&!h(n)||m(n)},y;e.deep!==void 0&&(y=Math.round(e.deep-r.depthOffset));let b=new tt({filters:[s?(e,t)=>{let n=g(e,t),r=p(n)&&!m(n);return r&&Ct(`matched ${n}`),r}:(e,t)=>{let n=g(e,t);return p(n)&&!m(n)}],exclude:s?(e,t)=>{let n=v(e,t);return Ct(`${n?`skipped`:`crawling`} ${t}`),n}:v,fs:e.fs,pathSeparator:`/`,relativePaths:!a,resolvePaths:a,includeBasePath:a,resolveSymlinks:l,excludeSymlinks:!l,excludeFiles:u,includeDirs:u||!e.onlyFiles,maxDepth:y,signal:e.signal}).crawl(d);return e.debug&&Ct(`internal properties:`,{...r,root:d}),[b,n!==d&&!a&&gt(n,d)]}function At(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}const jt={caseSensitiveMatch:!0,cwd:process.cwd(),debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:!0,followSymbolicLinks:!0,onlyFiles:!0};function Mt(e){let t={...jt,...e};return t.cwd=(t.cwd instanceof URL?j(t.cwd):k(t.cwd)).replace(lt,`/`),t.ignore=wt(t.ignore),t.fs&&={readdir:t.fs.readdir||_,readdirSync:t.fs.readdirSync||v,realpath:t.fs.realpath||y,realpathSync:t.fs.realpathSync||b,stat:t.fs.stat||x,statSync:t.fs.statSync||S},t.debug&&Ct(`globbing with options:`,t),t}function Nt(e,t={}){if(e&&t?.patterns)throw Error(`Cannot pass patterns as both an argument and an option`);let n=ct(e)||typeof e==`string`,r=wt((n?e:e.patterns)??`**/*`),i=Mt(n?t:e);return r.length>0?kt(i,r):[]}async function Pt(e,t){let[n,r]=Nt(e,t);return n?At(await n.withPromise(),r):[]}var Ft=z(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{DEFAULT_CLOCK_TOLERANCE_SEC:()=>f,DEFAULT_JWT_EXPIRE_TIME_MS:()=>d,FileTokenProvider:()=>C,HttpClient:()=>F,HttpError:()=>N,generateJWTToken:()=>m,parseJWTTokenWithVerify:()=>h,registerPlatformPlugin:()=>O,resolvePlatformBaseURL:()=>D}),t.exports=c(l);var u=H(`crypto`),d=1800*1e3,f=60,p={alg:`HS256`,typ:`JWT`};function m(e,t){let n=Math.floor(Date.now()/1e3),r={...e,iss:e.access_key,iat:n,nbf:n,exp:n+Math.floor(t.expireTimeMs/1e3),jti:(0,u.randomUUID)()},i=_(JSON.stringify(p)),a=_(JSON.stringify(r));return`${i}.${a}.${g(`${i}.${a}`,t.secretKey)}`}function h(e,t,n){let r=e.split(`.`);if(r.length!==3)throw Error(`invalid JWT token format`);let[i,a,o]=r;if(JSON.parse(v(i)).alg!==`HS256`)throw Error(`unsupported JWT alg`);let s=g(`${i}.${a}`,t.secretKey),c=Buffer.from(s),l=Buffer.from(o);if(c.length!==l.length||!(0,u.timingSafeEqual)(c,l))throw Error(`JWT signature verification failed`);let d=JSON.parse(v(a));if(!n?.skipExpiration){let e=n?.clockTolerance??f,t=Math.floor(Date.now()/1e3);if(d.exp!==void 0&&d.exp+e<t)throw Error(`JWT token expired at ${new Date(d.exp*1e3).toISOString()}`);if(d.nbf!==void 0&&d.nbf-e>t)throw Error(`JWT token not yet valid, will be valid at ${new Date(d.nbf*1e3).toISOString()}`);if(d.iat!==void 0&&d.iat-e>t)throw Error(`JWT token issued in the future at ${new Date(d.iat*1e3).toISOString()}`)}return d}function g(e,t){return(0,u.createHmac)(`sha256`,t).update(e).digest(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function _(e){return Buffer.from(e).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function v(e){let t=(4-(e.length%4||4))%4,n=`${e}${`=`.repeat(t)}`.replace(/-/g,`+`).replace(/_/g,`/`);return Buffer.from(n,`base64`).toString(`utf8`)}var y=class{cache=new Map;config;constructor(e){this.config={refreshBeforeMs:300*1e3,...e}}getToken(e){let t=this.getCacheKey(e),n=this.cache.get(t),r=Date.now();if(n&&n.expiresAtMs-r>this.config.refreshBeforeMs)return n.token;let i=m(e,this.config),a=r+this.config.expireTimeMs;return this.cache.set(t,{token:i,expiresAtMs:a}),i}clearCache(){this.cache.clear()}clearCacheFor(e){let t=this.getCacheKey(e);this.cache.delete(t)}getCacheKey(e){return[e.access_key,e.tenant_id?.toString()||``,e.user_id||``,e.app_id||``,e.app_env||``,e.sandbox_id||``].join(`:`)}getCacheStats(){let e=Date.now(),t=0,n=0;for(let r of this.cache.values())r.expiresAtMs>e?t++:n++;return{total:this.cache.size,valid:t,expired:n}}},b=H(`fs`),x=300*1e3,S=[`/home/gem/workspace/.force/openclaw/miaoda-provider-key`],C=class{cache=new Map;paths;refreshBeforeMs;constructor(e){this.paths=e?.paths??S,this.refreshBeforeMs=e?.refreshBeforeMs??x}getToken(){let e=Date.now();for(let t of this.paths){let n=this.cache.get(t);if(n&&n.expiresAtMs-e>this.refreshBeforeMs)return{token:n.token,accessKey:n.accessKey};let r=this.readAndParse(t);if(r&&(this.cache.set(t,r),r.expiresAtMs>e))return{token:r.token,accessKey:r.accessKey};if(n&&n.expiresAtMs>e)return{token:n.token,accessKey:n.accessKey}}return null}clearCache(){this.cache.clear()}readAndParse(e){try{let t=(0,b.readFileSync)(e,`utf-8`).trim();if(!t)return null;let n=this.decodePayload(t);return n?.exp?{token:t,accessKey:n.access_key??``,expiresAtMs:n.exp*1e3}:null}catch{return null}}decodePayload(e){try{let t=e.split(`.`);if(t.length!==3)return null;let n=(4-(t[1].length%4||4))%4,r=`${t[1]}${`=`.repeat(n)}`.replace(/-/g,`+`).replace(/_/g,`/`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}catch{return null}}},w=`FORCE_AUTHN_INNERAPI_DOMAIN`,T=`FORCE_AUTHN_ACCESS_KEY`,E=`FORCE_AUTHN_ACCESS_SECRET`;function D(e){if(!e?.enabled)return e?.baseURL;if(e.baseURL)return e.baseURL;let t=e.domainEnv||w,n=process.env[t];if(!n)throw Error(`\u5E73\u53F0\u6A21\u5F0F\u9700\u8981\u57FA\u7840\u57DF\u540D\uFF0C\u8BF7\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF ${t}`);return n}function O(e,t){if(!t.enabled)return;k(`platform.defaultClaims`,t.defaultClaims);let n;t.tokenProvider?.type===`file`&&(n=new C({paths:t.tokenProvider.paths,refreshBeforeMs:t.refreshBeforeMs}));let r=t.accessKeyEnv||T,i=t.secretKeyEnv||E,a=t.accessKey??(process.env[r]||``),o=new y({accessKey:a,secretKey:t.secretKey??(process.env[i]||``),expireTimeMs:t.expireTimeMs??d,refreshBeforeMs:t.refreshBeforeMs});return e.request.use(e=>{if(n){let t=n.getToken();if(t){let n={...e.headers,Authorization:`Bearer ${t.token}`,"x-api-key":t.accessKey};return{...e,headers:n}}}k(`request.platformAuth.customClaims`,e.platformAuth?.customClaims);let r={...t.defaultClaims||{},...e.platformAuth?.customClaims||{},access_key:a},i=o.getToken(r),s={...e.headers,Authorization:`Bearer ${i}`,"x-api-key":a};return{...e,headers:s}}),o}function k(e,t){if(t&&Object.prototype.hasOwnProperty.call(t,`access_key`))throw Error(`${e} \u4E0D\u5141\u8BB8\u8BBE\u7F6E access_key`)}var A=class{interceptors=[];use(e,t){return this.interceptors.push({onFulfilled:e,onRejected:t}),this.interceptors.length-1}eject(e){this.interceptors[e]&&(this.interceptors[e]=null)}clear(){this.interceptors=[]}forEach(e){this.interceptors.forEach(t=>{t!==null&&e(t)})}};function j(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function M(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e))return e.reduce((e,[t,n])=>(e[t]=n,e),{});let t={};return Object.entries(e).forEach(([e,n])=>{t[e]=Array.isArray(n)?n.join(`,`):n}),t}var N=class e extends Error{isHttpError=!0;response;config;constructor(t,n,r){super(r||`Request failed with status ${t?.status||`unknown`}`),this.name=`HttpError`,this.response=t,this.config=ee(n),Object.setPrototypeOf(this,e.prototype)}};function ee(e){let{headers:t,...n}=e;return{...n,headers:P(t)}}function P(e){if(!e)return;let t=M(e),n={},r=[`authorization`,`x-api-key`,`cookie`,`x-secret`];for(let[e,i]of Object.entries(t)){let t=e.toLowerCase();r.includes(t)?n[e]=`[REDACTED]`:n[e]=i}return n}var F=class{defaultConfig;securityConfig;interceptors={request:new A,response:new A};constructor(e){let{platform:t,security:n,...r}=e||{};this.defaultConfig={timeout:5e3,...r};let i=n?.strictMode??!1;this.securityConfig={allowedProtocols:i?[`http:`,`https:`]:null,maxResponseSize:i?50*1024*1024:0,strictMode:i,...n},t?.enabled&&(this.defaultConfig.baseURL||(this.defaultConfig.baseURL=D(t)),O(this.interceptors,t))}async get(e,t){return this.request({...t,url:e,method:`GET`})}async post(e,t,n){let r={...n?.headers},i=t;return j(t)&&(i=JSON.stringify(t),Object.keys(r).some(e=>e.toLowerCase()===`content-type`)||(r[`Content-Type`]=`application/json`)),this.request({...n,url:e,method:`POST`,body:i,headers:r})}async put(e,t,n){let r={...n?.headers},i=t;return j(t)&&(i=JSON.stringify(t),Object.keys(r).some(e=>e.toLowerCase()===`content-type`)||(r[`Content-Type`]=`application/json`)),this.request({...n,url:e,method:`PUT`,body:i,headers:r})}async delete(e,t){return this.request({...t,url:e,method:`DELETE`})}async patch(e,t,n){let r={...n?.headers},i=t;return j(t)&&(i=JSON.stringify(t),Object.keys(r).some(e=>e.toLowerCase()===`content-type`)||(r[`Content-Type`]=`application/json`)),this.request({...n,url:e,method:`PATCH`,body:i,headers:r})}async request(e){let t=M(this.defaultConfig.headers),n=M(e.headers),r={};for(let e in t)r[e.toLowerCase()]={key:e,value:t[e]};for(let e in n)r[e.toLowerCase()]={key:e,value:n[e]};let i={};for(let e in r){let{key:t,value:n}=r[e];i[t]=n}let a={...this.defaultConfig,...e,headers:i};try{a=await this.runRequestInterceptors(a)}catch(e){return Promise.reject(e)}a.headers=M(a.headers);let o=this.buildUrl(a.url,a.params),s=a.timeout||this.defaultConfig.timeout||5e3,c=new AbortController,l=setTimeout(()=>c.abort(),s),u=a.signal;u&&(u.aborted?(clearTimeout(l),c.abort()):u.addEventListener(`abort`,()=>c.abort(),{once:!0}));let{platformAuth:d,params:f,timeout:p,baseURL:m,url:h,...g}=a;try{let e=await fetch(o,{...g,signal:c.signal});if(clearTimeout(l),this.securityConfig.maxResponseSize>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(e>this.securityConfig.maxResponseSize)throw Error(`Response size ${e} bytes exceeds limit of ${this.securityConfig.maxResponseSize} bytes`)}}if(!e.ok){let t=new N(e,a);return this.runResponseInterceptors(Promise.reject(t))}return this.runResponseInterceptors(Promise.resolve(e))}catch(e){clearTimeout(l);let t=e instanceof N?e:new N(void 0,a,e.name===`AbortError`?`Request aborted`:e.message);return this.runResponseInterceptors(Promise.reject(t))}}runRequestInterceptors(e){let t=Promise.resolve(e),n=[];this.interceptors.request.forEach(e=>{n.push(e)});for(let e of n)t=t.then(e.onFulfilled,e.onRejected);return t}async runResponseInterceptors(e){let t=e,n=[];this.interceptors.response.forEach(e=>{n.push(e)});for(let e of n)t=t.then(e.onFulfilled,e.onRejected);return t}buildUrl(e,t){let n=this.defaultConfig.baseURL,r;r=!n||/^https?:\/\//i.test(e)?e:n.replace(/\/+$/,``)+`/`+e.replace(/^\/+/,``);let i=new URL(r),{allowedProtocols:a}=this.securityConfig;if(a&&!a.includes(i.protocol))throw Error(`Protocol ${i.protocol} is not allowed. Allowed: ${a.join(`, `)}`);if(t)for(let[e,n]of Object.entries(t))n!=null&&i.searchParams.set(e,String(n));return i.href}}}))();let It;function Lt(){if(It)return It;try{let e=l(s(N(import.meta.url)),`..`,`package.json`);It=JSON.parse(a(e,`utf-8`))}catch(e){console.warn(`[miaoda-coding] failed to read package.json: ${e instanceof Error?e.message:e}`),It={}}return It}function Rt(){let e=process.env.FORCE_AUTHN_INNERAPI_DOMAIN;if(!e)throw Error(`studio-client: 缺少环境变量,需要: FORCE_AUTHN_INNERAPI_DOMAIN`);return{apiUrl:e}}const zt=new Set([`k_st_ec_400002683`]);var Bt=class extends Error{userFacing=!0;constructor(e,t,n){super(e),this.statusCode=t,this.logId=n,this.name=`UserFacingError`}};function Vt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`)}function Ht(...e){for(let t of e)if(typeof t==`string`&&t)return t}async function*Ut(e){let t=new TextDecoder,n=``,r;for await(let i of e){n+=t.decode(i,{stream:!0});let e=n.split(`
1
+ import{createRequire as e}from"node:module";import{execFile as t,spawn as n}from"node:child_process";import{randomUUID as r}from"node:crypto";import i,{readFileSync as a}from"node:fs";import o,{dirname as s,join as c,resolve as l}from"node:path";import{appendFile as u,mkdir as d,readFile as f,readdir as p,rm as m,writeFile as h}from"node:fs/promises";import*as g from"fs";import{readdir as _,readdirSync as v,realpath as y,realpathSync as b,stat as x,statSync as S}from"fs";import{basename as C,dirname as w,isAbsolute as T,normalize as E,posix as D,relative as O,resolve as k,sep as A}from"path";import{fileURLToPath as j}from"url";import{createRequire as M}from"module";import{fileURLToPath as N}from"node:url";var P=Object.create,F=Object.defineProperty,I=Object.getOwnPropertyDescriptor,L=Object.getOwnPropertyNames,R=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty,B=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),V=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=L(t),a=0,o=i.length,s;a<o;a++)s=i[a],!z.call(e,s)&&s!==n&&F(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=I(t,s))||r.enumerable});return e},H=(e,t,n)=>(n=e==null?{}:P(R(e)),V(t||!e||!e.__esModule?F(n,`default`,{value:e,enumerable:!0}):n,e)),U=e(import.meta.url);function W(){return l(process.env.OPENCLAW_STATE_DIR||process.cwd())}function G(e){return c(e,`.agent`)}function K(e,t){return c(e,`app`,t)}function q(e,t){return c(e,t)}function J(e){let t=typeof e.workspaceDir==`string`&&e.workspaceDir!==``,n=typeof e.agentDir==`string`&&e.agentDir!==``;if(!t||!n)throw Error(`resolveToolPaths: workspaceDir and agentDir are required in tool factory context`);return{workspaceDir:e.workspaceDir,agentDir:e.agentDir,agentId:e.agentId,sessionKey:e.sessionKey}}var ee=M(import.meta.url);function Y(e){let t=E(e);return t.length>1&&t[t.length-1]===A&&(t=t.substring(0,t.length-1)),t}const X=/[\\/]/g;function Z(e,t){return e.replace(X,t)}const te=/^[a-z]:[\\/]$/i;function ne(e){return e===`/`||te.test(e)}function re(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,a=process.platform===`win32`&&e.includes(`/`)||e.startsWith(`.`);return n&&(e=k(e)),(r||a)&&(e=Y(e)),e===`.`?``:Z(e[e.length-1]===i?e:e+i,i)}function ie(e,t){return t+e}function ae(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:Z(O(e,r),t.pathSeparator)+t.pathSeparator+n}}function oe(e){return e}function se(e,t,n){return t+e+n}function ce(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?ae(e,t):r?ie:oe}function le(e){return function(t,n){n.push(t.substring(e.length)||`.`)}}function ue(e){return function(t,n,r){let i=t.substring(e.length)||`.`;r.every(e=>e(i,!0))&&n.push(i)}}const de=(e,t)=>{t.push(e||`.`)},fe=(e,t,n)=>{let r=e||`.`;n.every(e=>e(r,!0))&&t.push(r)},pe=()=>{};function me(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?ue(e):le(e):r&&r.length?fe:de:pe}const he=(e,t,n,r)=>{r.every(t=>t(e,!1))&&n.files++},ge=(e,t,n,r)=>{r.every(t=>t(e,!1))&&t.push(e)},_e=(e,t,n,r)=>{n.files++},ve=(e,t)=>{t.push(e)},ye=()=>{};function be(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?ye:n&&n.length?r?he:ge:r?_e:ve}const xe=e=>e,Se=()=>[``].slice(0,0);function Ce(e){return e.group?Se:xe}const we=(e,t,n)=>{e.push({directory:t,files:n,dir:t})},Te=()=>{};function Ee(e){return e.group?we:Te}const De=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:a}}=t;r.enqueue(),i.realpath(e,(o,s)=>{if(o)return r.dequeue(a?null:o,t);i.stat(s,(i,o)=>{if(i)return r.dequeue(a?null:i,t);if(o.isDirectory()&&Ae(e,s,t))return r.dequeue(null,t);n(o,s),r.dequeue(null,t)})})},Oe=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:a}}=t;r.enqueue();try{let r=i.realpathSync(e),a=i.statSync(r);if(a.isDirectory()&&Ae(e,r,t))return;n(a,r)}catch(e){if(!a)throw e}};function ke(e,t){return!e.resolveSymlinks||e.excludeSymlinks?null:t?Oe:De}function Ae(e,t,n){if(n.options.useRealPaths)return je(t,n);let r=w(e),i=1;for(;r!==n.root&&i<2;){let e=n.symlinks.get(r);e&&(e===t||e.startsWith(t)||t.startsWith(e))?i++:r=w(r)}return n.symlinks.set(e,t),i>1}function je(e,t){return t.visited.includes(e+t.options.pathSeparator)}const Me=e=>e.counts,Ne=e=>e.groups,Pe=e=>e.paths,Fe=e=>e.paths.slice(0,e.options.maxFiles),Ie=(e,t,n)=>(Be(t,n,e.counts,e.options.suppressErrors),null),Le=(e,t,n)=>(Be(t,n,e.paths,e.options.suppressErrors),null),Re=(e,t,n)=>(Be(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),ze=(e,t,n)=>(Be(t,n,e.groups,e.options.suppressErrors),null);function Be(e,t,n,r){t(e&&!r?e:null,n)}function Ve(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?Me:Ie:r?t?Ne:ze:i?t?Fe:Re:t?Pe:Le}const He={withFileTypes:!0},Ue=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:a}=e;e.visited.push(t),e.counts.directories++,a.readdir(t||`.`,He,(t,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:t,e)})},We=(e,t,n,r,i)=>{let{fs:a}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=a.readdirSync(t||`.`,He)}catch(t){if(!e.options.suppressErrors)throw t}i(o,n,r)};function Ge(e){return e?We:Ue}var Ke=class{count=0;constructor(e){this.onQueueEmpty=e}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0))}},qe=class{_files=0;_directories=0;set files(e){this._files=e}get files(){return this._files}set directories(e){this._directories=e}get directories(){return this._directories}get dirs(){return this._directories}},Je=class{aborted=!1;abort(){this.aborted=!0}},Ye=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=Ve(t,this.isSynchronous),this.root=re(e,t),this.state={root:ne(this.root)?this.root:this.root.slice(0,-1),paths:[``].slice(0,0),groups:[],counts:new qe,options:t,queue:new Ke((e,t)=>this.callbackInvoker(t,e,n)),symlinks:new Map,visited:[``].slice(0,0),controller:new Je,fs:t.fs||g},this.joinPath=ce(this.root,t),this.pushDirectory=me(this.root,t),this.pushFile=be(t),this.getArray=Ce(t),this.groupFiles=Ee(t),this.resolveSymlink=ke(t,this.isSynchronous),this.walkDirectory=Ge(this.isSynchronous)}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,n)=>{let{paths:r,options:{filters:i,resolveSymlinks:a,excludeSymlinks:o,exclude:s,maxFiles:c,signal:l,useRealPaths:u,pathSeparator:d},controller:f}=this.state;if(f.aborted||l&&l.aborted||c&&r.length>c)return;let p=this.getArray(this.state.paths);for(let c=0;c<e.length;++c){let l=e[c];if(l.isFile()||l.isSymbolicLink()&&!a&&!o){let e=this.joinPath(l.name,t);this.pushFile(e,p,this.state.counts,i)}else if(l.isDirectory()){let e=se(l.name,t,this.state.options.pathSeparator);if(s&&s(l.name,e))continue;this.pushDirectory(e,r,i),this.walkDirectory(this.state,e,e,n-1,this.walk)}else if(this.resolveSymlink&&l.isSymbolicLink()){let e=ie(l.name,t);this.resolveSymlink(e,this.state,(t,r)=>{if(t.isDirectory()){if(r=re(r,this.state.options),s&&s(l.name,u?r:e+d))return;this.walkDirectory(this.state,r,u?r:e+d,n-1,this.walk)}else{r=u?r:e;let t=C(r),n=re(w(r),this.state.options);r=this.joinPath(t,n),this.pushFile(r,p,this.state.counts,i)}})}}this.groupFiles(this.state.groups,t,p)}};function Xe(e,t){return new Promise((n,r)=>{Ze(e,t,(e,t)=>{if(e)return r(e);n(t)})})}function Ze(e,t,n){new Ye(e,t,n).start()}function Qe(e,t){return new Ye(e,t).start()}var $e=class{constructor(e,t){this.root=e,this.options=t}withPromise(){return Xe(this.root,this.options)}withCallback(e){Ze(this.root,this.options,e)}sync(){return Qe(this.root,this.options)}};let et=null;try{ee.resolve(`picomatch`),et=ee(`picomatch`)}catch{}var tt=class{globCache={};options={maxDepth:1/0,suppressErrors:!0,pathSeparator:A,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction}group(){return this.options.group=!0,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=!0,this}withRelativePaths(){return this.options.relativePaths=!0,this}withDirs(){return this.options.includeDirs=!0,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=!0,this.options.includeBasePath=!0,this}withErrors(){return this.options.suppressErrors=!1,this}withSymlinks({resolvePaths:e=!0}={}){return this.options.resolveSymlinks=!0,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=!0,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=!0,this.options.includeDirs=!0,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=!0,this}crawl(e){return new $e(e||`.`,this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new $e(e||`.`,this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:!0})}globWithOptions(e,...t){let n=this.globFunction||et;if(!n)throw Error(`Please specify a glob function to use glob matching.`);var r=this.globCache[e.join(`\0`)];return r||(r=n(e,...t),this.globCache[e.join(`\0`)]=r),this.options.filters.push(e=>r(e)),this}},nt=B(((e,t)=>{let n=`[^\\\\/]`,r=`[^/]`,i=`(?:\\/|$)`,a=`(?:^|\\/)`,o=`\\.{1,2}${i}`,s={DOT_LITERAL:`\\.`,PLUS_LITERAL:`\\+`,QMARK_LITERAL:`\\?`,SLASH_LITERAL:`\\/`,ONE_CHAR:`(?=.)`,QMARK:r,END_ANCHOR:i,DOTS_SLASH:o,NO_DOT:`(?!\\.)`,NO_DOTS:`(?!${a}${o})`,NO_DOT_SLASH:`(?!\\.{0,1}${i})`,NO_DOTS_SLASH:`(?!${o})`,QMARK_NO_DOT:`[^.\\/]`,STAR:`${r}*?`,START_ANCHOR:a,SEP:`/`},c={...s,SLASH_LITERAL:`[\\\\/]`,QMARK:n,STAR:`${n}*?`,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:`\\`};t.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:{__proto__:null,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`},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(e){return{"!":{type:`negate`,open:`(?:(?!(?:`,close:`))${e.STAR})`},"?":{type:`qmark`,open:`(?:`,close:`)?`},"+":{type:`plus`,open:`(?:`,close:`)+`},"*":{type:`star`,open:`(?:`,close:`)*`},"@":{type:`at`,open:`(?:`,close:`)`}}},globChars(e){return e===!0?c:s}}})),rt=B((e=>{let{REGEX_BACKSLASH:t,REGEX_REMOVE_BACKSLASH:n,REGEX_SPECIAL_CHARS:r,REGEX_SPECIAL_CHARS_GLOBAL:i}=nt();e.isObject=e=>typeof e==`object`&&!!e&&!Array.isArray(e),e.hasRegexChars=e=>r.test(e),e.isRegexChar=t=>t.length===1&&e.hasRegexChars(t),e.escapeRegex=e=>e.replace(i,`\\$1`),e.toPosixSlashes=e=>e.replace(t,`/`),e.isWindows=()=>{if(typeof navigator<`u`&&navigator.platform){let e=navigator.platform.toLowerCase();return e===`win32`||e===`windows`}return typeof process<`u`&&process.platform?process.platform===`win32`:!1},e.removeBackslashes=e=>e.replace(n,e=>e===`\\`?``:e),e.escapeLast=(t,n,r)=>{let i=t.lastIndexOf(n,r);return i===-1?t:t[i-1]===`\\`?e.escapeLast(t,n,i-1):`${t.slice(0,i)}\\${t.slice(i)}`},e.removePrefix=(e,t={})=>{let n=e;return n.startsWith(`./`)&&(n=n.slice(2),t.prefix=`./`),n},e.wrapOutput=(e,t={},n={})=>{let r=`${n.contains?``:`^`}(?:${e})${n.contains?``:`$`}`;return t.negated===!0&&(r=`(?:^(?!${r}).*$)`),r},e.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:`/`),r=n[n.length-1];return r===``?n[n.length-2]:r}})),it=B(((e,t)=>{let n=rt(),{CHAR_ASTERISK:r,CHAR_AT:i,CHAR_BACKWARD_SLASH:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_EXCLAMATION_MARK:c,CHAR_FORWARD_SLASH:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_LEFT_PARENTHESES:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_PLUS:p,CHAR_QUESTION_MARK:m,CHAR_RIGHT_CURLY_BRACE:h,CHAR_RIGHT_PARENTHESES:g,CHAR_RIGHT_SQUARE_BRACKET:_}=nt(),v=e=>e===l||e===a,y=e=>{e.isPrefix!==!0&&(e.depth=e.isGlobstar?1/0:1)};t.exports=(e,t)=>{let b=t||{},x=e.length-1,S=b.parts===!0||b.scanToEnd===!0,C=[],w=[],T=[],E=e,D=-1,O=0,k=0,A=!1,j=!1,M=!1,N=!1,P=!1,F=!1,I=!1,L=!1,R=!1,z=!1,B=0,V,H,U={value:``,depth:0,isGlob:!1},W=()=>D>=x,G=()=>E.charCodeAt(D+1),K=()=>(V=H,E.charCodeAt(++D));for(;D<x;){H=K();let e;if(H===a){I=U.backslashes=!0,H=K(),H===u&&(F=!0);continue}if(F===!0||H===u){for(B++;W()!==!0&&(H=K());){if(H===a){I=U.backslashes=!0,K();continue}if(H===u){B++;continue}if(F!==!0&&H===s&&(H=K())===s){if(A=U.isBrace=!0,M=U.isGlob=!0,z=!0,S===!0)continue;break}if(F!==!0&&H===o){if(A=U.isBrace=!0,M=U.isGlob=!0,z=!0,S===!0)continue;break}if(H===h&&(B--,B===0)){F=!1,A=U.isBrace=!0,z=!0;break}}if(S===!0)continue;break}if(H===l){if(C.push(D),w.push(U),U={value:``,depth:0,isGlob:!1},z===!0)continue;if(V===s&&D===O+1){O+=2;continue}k=D+1;continue}if(b.noext!==!0&&(H===p||H===i||H===r||H===m||H===c)&&G()===d){if(M=U.isGlob=!0,N=U.isExtglob=!0,z=!0,H===c&&D===O&&(R=!0),S===!0){for(;W()!==!0&&(H=K());){if(H===a){I=U.backslashes=!0,H=K();continue}if(H===g){M=U.isGlob=!0,z=!0;break}}continue}break}if(H===r){if(V===r&&(P=U.isGlobstar=!0),M=U.isGlob=!0,z=!0,S===!0)continue;break}if(H===m){if(M=U.isGlob=!0,z=!0,S===!0)continue;break}if(H===f){for(;W()!==!0&&(e=K());){if(e===a){I=U.backslashes=!0,K();continue}if(e===_){j=U.isBracket=!0,M=U.isGlob=!0,z=!0;break}}if(S===!0)continue;break}if(b.nonegate!==!0&&H===c&&D===O){L=U.negated=!0,O++;continue}if(b.noparen!==!0&&H===d){if(M=U.isGlob=!0,S===!0){for(;W()!==!0&&(H=K());){if(H===d){I=U.backslashes=!0,H=K();continue}if(H===g){z=!0;break}}continue}break}if(M===!0){if(z=!0,S===!0)continue;break}}b.noext===!0&&(N=!1,M=!1);let q=E,J=``,ee=``;O>0&&(J=E.slice(0,O),E=E.slice(O),k-=O),q&&M===!0&&k>0?(q=E.slice(0,k),ee=E.slice(k)):M===!0?(q=``,ee=E):q=E,q&&q!==``&&q!==`/`&&q!==E&&v(q.charCodeAt(q.length-1))&&(q=q.slice(0,-1)),b.unescape===!0&&(ee&&=n.removeBackslashes(ee),q&&I===!0&&(q=n.removeBackslashes(q)));let Y={prefix:J,input:e,start:O,base:q,glob:ee,isBrace:A,isBracket:j,isGlob:M,isExtglob:N,isGlobstar:P,negated:L,negatedExtglob:R};if(b.tokens===!0&&(Y.maxDepth=0,v(H)||w.push(U),Y.tokens=w),b.parts===!0||b.tokens===!0){let t;for(let n=0;n<C.length;n++){let r=t?t+1:O,i=C[n],a=e.slice(r,i);b.tokens&&(n===0&&O!==0?(w[n].isPrefix=!0,w[n].value=J):w[n].value=a,y(w[n]),Y.maxDepth+=w[n].depth),(n!==0||a!==``)&&T.push(a),t=i}if(t&&t+1<e.length){let n=e.slice(t+1);T.push(n),b.tokens&&(w[w.length-1].value=n,y(w[w.length-1]),Y.maxDepth+=w[w.length-1].depth)}Y.slashes=C,Y.parts=T}return Y}})),at=B(((e,t)=>{let n=nt(),r=rt(),{MAX_LENGTH:i,POSIX_REGEX_SOURCE:a,REGEX_NON_SPECIAL_CHARS:o,REGEX_SPECIAL_CHARS_BACKREF:s,REPLACEMENTS:c}=n,l=(e,t)=>{if(typeof t.expandRange==`function`)return t.expandRange(...e,t);e.sort();let n=`[${e.join(`-`)}]`;try{new RegExp(n)}catch{return e.map(e=>r.escapeRegex(e)).join(`..`)}return n},u=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,d=e=>{let t=[],n=0,r=0,i=0,a=``,o=!1;for(let s of e){if(o===!0){a+=s,o=!1;continue}if(s===`\\`){a+=s,o=!0;continue}if(s===`"`){i=i===1?0:1,a+=s;continue}if(i===0){if(s===`[`)n++;else if(s===`]`&&n>0)n--;else if(n===0){if(s===`(`)r++;else if(s===`)`&&r>0)r--;else if(s===`|`&&r===0){t.push(a),a=``;continue}}}a+=s}return t.push(a),t},f=e=>{let t=!1;for(let n of e){if(t===!0){t=!1;continue}if(n===`\\`){t=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},p=e=>{let t=e.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=!0);if(f(t))return t.replace(/\\(.)/g,`$1`)},m=e=>{let t=e.map(p).filter(Boolean);for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let r=t[e],i=t[n],a=r[0];if(!(!a||r!==a.repeat(r.length)||i!==a.repeat(i.length))&&(r===i||r.startsWith(i)||i.startsWith(r)))return!0}return!1},h=(e,t=!0)=>{if(e[0]!==`+`&&e[0]!==`*`||e[1]!==`(`)return;let n=0,r=0,i=0,a=!1;for(let o=1;o<e.length;o++){let s=e[o];if(a===!0){a=!1;continue}if(s===`\\`){a=!0;continue}if(s===`"`){i=i===1?0:1;continue}if(i!==1){if(s===`[`){n++;continue}if(s===`]`&&n>0){n--;continue}if(!(n>0)){if(s===`(`){r++;continue}if(s===`)`&&(r--,r===0))return t===!0&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},g=e=>{let t=0,n=[];for(;t<e.length;){let r=h(e.slice(t),!1);if(!r||r.type!==`*`)return;let i=d(r.body).map(e=>e.trim());if(i.length!==1)return;let a=p(i[0]);if(!a||a.length!==1)return;n.push(a),t+=r.end+1}if(!(n.length<1))return`${n.length===1?r.escapeRegex(n[0]):`[${n.map(e=>r.escapeRegex(e)).join(``)}]`}*`},_=e=>{let t=0,n=e.trim(),r=h(n);for(;r;)t++,n=r.body.trim(),r=h(n);return t},v=(e,t)=>{if(t.maxExtglobRecursion===!1)return{risky:!1};let r=typeof t.maxExtglobRecursion==`number`?t.maxExtglobRecursion:n.DEFAULT_MAX_EXTGLOB_RECURSION,i=d(e).map(e=>e.trim());if(i.length>1&&(i.some(e=>e===``)||i.some(e=>/^[*?]+$/.test(e))||m(i)))return{risky:!0};for(let e of i){let t=g(e);if(t)return{risky:!0,safeOutput:t};if(_(e)>r)return{risky:!0}}return{risky:!1}},y=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);e=c[e]||e;let d={...t},f=typeof d.maxLength==`number`?Math.min(i,d.maxLength):i,p=e.length;if(p>f)throw SyntaxError(`Input length: ${p}, exceeds maximum allowed length: ${f}`);let m={type:`bos`,value:``,output:d.prepend||``},h=[m],g=d.capture?``:`?:`,_=n.globChars(d.windows),b=n.extglobChars(_),{DOT_LITERAL:x,PLUS_LITERAL:S,SLASH_LITERAL:C,ONE_CHAR:w,DOTS_SLASH:T,NO_DOT:E,NO_DOT_SLASH:D,NO_DOTS_SLASH:O,QMARK:k,QMARK_NO_DOT:A,STAR:j,START_ANCHOR:M}=_,N=e=>`(${g}(?:(?!${M}${e.dot?T:x}).)*?)`,P=d.dot?``:E,F=d.dot?k:A,I=d.bash===!0?N(d):j;d.capture&&(I=`(${I})`),typeof d.noext==`boolean`&&(d.noextglob=d.noext);let L={input:e,index:-1,start:0,dot:d.dot===!0,consumed:``,output:``,prefix:``,backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:h};e=r.removePrefix(e,L),p=e.length;let R=[],z=[],B=[],V=m,H,U=()=>L.index===p-1,W=L.peek=(t=1)=>e[L.index+t],G=L.advance=()=>e[++L.index]||``,K=()=>e.slice(L.index+1),q=(e=``,t=0)=>{L.consumed+=e,L.index+=t},J=e=>{L.output+=e.output==null?e.value:e.output,q(e.value)},ee=()=>{let e=1;for(;W()===`!`&&(W(2)!==`(`||W(3)===`?`);)G(),L.start++,e++;return e%2==0?!1:(L.negated=!0,L.start++,!0)},Y=e=>{L[e]++,B.push(e)},X=e=>{L[e]--,B.pop()},Z=e=>{if(V.type===`globstar`){let t=L.braces>0&&(e.type===`comma`||e.type===`brace`),n=e.extglob===!0||R.length&&(e.type===`pipe`||e.type===`paren`);e.type!==`slash`&&e.type!==`paren`&&!t&&!n&&(L.output=L.output.slice(0,-V.output.length),V.type=`star`,V.value=`*`,V.output=I,L.output+=V.output)}if(R.length&&e.type!==`paren`&&(R[R.length-1].inner+=e.value),(e.value||e.output)&&J(e),V&&V.type===`text`&&e.type===`text`){V.output=(V.output||V.value)+e.value,V.value+=e.value;return}e.prev=V,h.push(e),V=e},te=(e,t)=>{let n={...b[t],conditions:1,inner:``};n.prev=V,n.parens=L.parens,n.output=L.output,n.startIndex=L.index,n.tokensIndex=h.length;let r=(d.capture?`(`:``)+n.open;Y(`parens`),Z({type:e,value:t,output:L.output?``:w}),Z({type:`paren`,extglob:!0,value:G(),output:r}),R.push(n)},ne=n=>{let i=e.slice(n.startIndex,L.index+1),a=v(e.slice(n.startIndex+2,L.index),d);if((n.type===`plus`||n.type===`star`)&&a.risky){let e=a.safeOutput?(n.output?``:w)+(d.capture?`(${a.safeOutput})`:a.safeOutput):void 0,t=h[n.tokensIndex];t.type=`text`,t.value=i,t.output=e||r.escapeRegex(i);for(let e=n.tokensIndex+1;e<h.length;e++)h[e].value=``,h[e].output=``,delete h[e].suffix;L.output=n.output+t.output,L.backtrack=!0,Z({type:`paren`,extglob:!0,value:H,output:``}),X(`parens`);return}let o=n.close+(d.capture?`)`:``),s;if(n.type===`negate`){let e=I;n.inner&&n.inner.length>1&&n.inner.includes(`/`)&&(e=N(d)),(e!==I||U()||/^\)+$/.test(K()))&&(o=n.close=`)$))${e}`),n.inner.includes(`*`)&&(s=K())&&/^\.[^\\/.]+$/.test(s)&&(o=n.close=`)${y(s,{...t,fastpaths:!1}).output})${e})`),n.prev.type===`bos`&&(L.negatedExtglob=!0)}Z({type:`paren`,extglob:!0,value:H,output:o}),X(`parens`)};if(d.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(e)){let n=!1,i=e.replace(s,(e,t,r,i,a,o)=>i===`\\`?(n=!0,e):i===`?`?t?t+i+(a?k.repeat(a.length):``):o===0?F+(a?k.repeat(a.length):``):k.repeat(r.length):i===`.`?x.repeat(r.length):i===`*`?t?t+i+(a?I:``):I:t?e:`\\${e}`);return n===!0&&(i=d.unescape===!0?i.replace(/\\/g,``):i.replace(/\\+/g,e=>e.length%2==0?`\\\\`:e?`\\`:``)),i===e&&d.contains===!0?(L.output=e,L):(L.output=r.wrapOutput(i,L,t),L)}for(;!U();){if(H=G(),H===`\0`)continue;if(H===`\\`){let e=W();if(e===`/`&&d.bash!==!0||e===`.`||e===`;`)continue;if(!e){H+=`\\`,Z({type:`text`,value:H});continue}let t=/^\\+/.exec(K()),n=0;if(t&&t[0].length>2&&(n=t[0].length,L.index+=n,n%2!=0&&(H+=`\\`)),d.unescape===!0?H=G():H+=G(),L.brackets===0){Z({type:`text`,value:H});continue}}if(L.brackets>0&&(H!==`]`||V.value===`[`||V.value===`[^`)){if(d.posix!==!1&&H===`:`){let e=V.value.slice(1);if(e.includes(`[`)&&(V.posix=!0,e.includes(`:`))){let e=V.value.lastIndexOf(`[`),t=V.value.slice(0,e),n=a[V.value.slice(e+2)];if(n){V.value=t+n,L.backtrack=!0,G(),!m.output&&h.indexOf(V)===1&&(m.output=w);continue}}}(H===`[`&&W()!==`:`||H===`-`&&W()===`]`)&&(H=`\\${H}`),H===`]`&&(V.value===`[`||V.value===`[^`)&&(H=`\\${H}`),d.posix===!0&&H===`!`&&V.value===`[`&&(H=`^`),V.value+=H,J({value:H});continue}if(L.quotes===1&&H!==`"`){H=r.escapeRegex(H),V.value+=H,J({value:H});continue}if(H===`"`){L.quotes=L.quotes===1?0:1,d.keepQuotes===!0&&Z({type:`text`,value:H});continue}if(H===`(`){Y(`parens`),Z({type:`paren`,value:H});continue}if(H===`)`){if(L.parens===0&&d.strictBrackets===!0)throw SyntaxError(u(`opening`,`(`));let e=R[R.length-1];if(e&&L.parens===e.parens+1){ne(R.pop());continue}Z({type:`paren`,value:H,output:L.parens?`)`:`\\)`}),X(`parens`);continue}if(H===`[`){if(d.nobracket===!0||!K().includes(`]`)){if(d.nobracket!==!0&&d.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));H=`\\${H}`}else Y(`brackets`);Z({type:`bracket`,value:H});continue}if(H===`]`){if(d.nobracket===!0||V&&V.type===`bracket`&&V.value.length===1){Z({type:`text`,value:H,output:`\\${H}`});continue}if(L.brackets===0){if(d.strictBrackets===!0)throw SyntaxError(u(`opening`,`[`));Z({type:`text`,value:H,output:`\\${H}`});continue}X(`brackets`);let e=V.value.slice(1);if(V.posix!==!0&&e[0]===`^`&&!e.includes(`/`)&&(H=`/${H}`),V.value+=H,J({value:H}),d.literalBrackets===!1||r.hasRegexChars(e))continue;let t=r.escapeRegex(V.value);if(L.output=L.output.slice(0,-V.value.length),d.literalBrackets===!0){L.output+=t,V.value=t;continue}V.value=`(${g}${t}|${V.value})`,L.output+=V.value;continue}if(H===`{`&&d.nobrace!==!0){Y(`braces`);let e={type:`brace`,value:H,output:`(`,outputIndex:L.output.length,tokensIndex:L.tokens.length};z.push(e),Z(e);continue}if(H===`}`){let e=z[z.length-1];if(d.nobrace===!0||!e){Z({type:`text`,value:H,output:H});continue}let t=`)`;if(e.dots===!0){let e=h.slice(),n=[];for(let t=e.length-1;t>=0&&(h.pop(),e[t].type!==`brace`);t--)e[t].type!==`dots`&&n.unshift(e[t].value);t=l(n,d),L.backtrack=!0}if(e.comma!==!0&&e.dots!==!0){let n=L.output.slice(0,e.outputIndex),r=L.tokens.slice(e.tokensIndex);e.value=e.output=`\\{`,H=t=`\\}`,L.output=n;for(let e of r)L.output+=e.output||e.value}Z({type:`brace`,value:H,output:t}),X(`braces`),z.pop();continue}if(H===`|`){R.length>0&&R[R.length-1].conditions++,Z({type:`text`,value:H});continue}if(H===`,`){let e=H,t=z[z.length-1];t&&B[B.length-1]===`braces`&&(t.comma=!0,e=`|`),Z({type:`comma`,value:H,output:e});continue}if(H===`/`){if(V.type===`dot`&&L.index===L.start+1){L.start=L.index+1,L.consumed=``,L.output=``,h.pop(),V=m;continue}Z({type:`slash`,value:H,output:C});continue}if(H===`.`){if(L.braces>0&&V.type===`dot`){V.value===`.`&&(V.output=x);let e=z[z.length-1];V.type=`dots`,V.output+=H,V.value+=H,e.dots=!0;continue}if(L.braces+L.parens===0&&V.type!==`bos`&&V.type!==`slash`){Z({type:`text`,value:H,output:x});continue}Z({type:`dot`,value:H,output:x});continue}if(H===`?`){if(!(V&&V.value===`(`)&&d.noextglob!==!0&&W()===`(`&&W(2)!==`?`){te(`qmark`,H);continue}if(V&&V.type===`paren`){let e=W(),t=H;(V.value===`(`&&!/[!=<:]/.test(e)||e===`<`&&!/<([!=]|\w+>)/.test(K()))&&(t=`\\${H}`),Z({type:`text`,value:H,output:t});continue}if(d.dot!==!0&&(V.type===`slash`||V.type===`bos`)){Z({type:`qmark`,value:H,output:A});continue}Z({type:`qmark`,value:H,output:k});continue}if(H===`!`){if(d.noextglob!==!0&&W()===`(`&&(W(2)!==`?`||!/[!=<:]/.test(W(3)))){te(`negate`,H);continue}if(d.nonegate!==!0&&L.index===0){ee();continue}}if(H===`+`){if(d.noextglob!==!0&&W()===`(`&&W(2)!==`?`){te(`plus`,H);continue}if(V&&V.value===`(`||d.regex===!1){Z({type:`plus`,value:H,output:S});continue}if(V&&(V.type===`bracket`||V.type===`paren`||V.type===`brace`)||L.parens>0){Z({type:`plus`,value:H});continue}Z({type:`plus`,value:S});continue}if(H===`@`){if(d.noextglob!==!0&&W()===`(`&&W(2)!==`?`){Z({type:`at`,extglob:!0,value:H,output:``});continue}Z({type:`text`,value:H});continue}if(H!==`*`){(H===`$`||H===`^`)&&(H=`\\${H}`);let e=o.exec(K());e&&(H+=e[0],L.index+=e[0].length),Z({type:`text`,value:H});continue}if(V&&(V.type===`globstar`||V.star===!0)){V.type=`star`,V.star=!0,V.value+=H,V.output=I,L.backtrack=!0,L.globstar=!0,q(H);continue}let t=K();if(d.noextglob!==!0&&/^\([^?]/.test(t)){te(`star`,H);continue}if(V.type===`star`){if(d.noglobstar===!0){q(H);continue}let n=V.prev,r=n.prev,i=n.type===`slash`||n.type===`bos`,a=r&&(r.type===`star`||r.type===`globstar`);if(d.bash===!0&&(!i||t[0]&&t[0]!==`/`)){Z({type:`star`,value:H,output:``});continue}let o=L.braces>0&&(n.type===`comma`||n.type===`brace`),s=R.length&&(n.type===`pipe`||n.type===`paren`);if(!i&&n.type!==`paren`&&!o&&!s){Z({type:`star`,value:H,output:``});continue}for(;t.slice(0,3)===`/**`;){let n=e[L.index+4];if(n&&n!==`/`)break;t=t.slice(3),q(`/**`,3)}if(n.type===`bos`&&U()){V.type=`globstar`,V.value+=H,V.output=N(d),L.output=V.output,L.globstar=!0,q(H);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&!a&&U()){L.output=L.output.slice(0,-(n.output+V.output).length),n.output=`(?:${n.output}`,V.type=`globstar`,V.output=N(d)+(d.strictSlashes?`)`:`|$)`),V.value+=H,L.globstar=!0,L.output+=n.output+V.output,q(H);continue}if(n.type===`slash`&&n.prev.type!==`bos`&&t[0]===`/`){let e=t[1]===void 0?``:`|$`;L.output=L.output.slice(0,-(n.output+V.output).length),n.output=`(?:${n.output}`,V.type=`globstar`,V.output=`${N(d)}${C}|${C}${e})`,V.value+=H,L.output+=n.output+V.output,L.globstar=!0,q(H+G()),Z({type:`slash`,value:`/`,output:``});continue}if(n.type===`bos`&&t[0]===`/`){V.type=`globstar`,V.value+=H,V.output=`(?:^|${C}|${N(d)}${C})`,L.output=V.output,L.globstar=!0,q(H+G()),Z({type:`slash`,value:`/`,output:``});continue}L.output=L.output.slice(0,-V.output.length),V.type=`globstar`,V.output=N(d),V.value+=H,L.output+=V.output,L.globstar=!0,q(H);continue}let n={type:`star`,value:H,output:I};if(d.bash===!0){n.output=`.*?`,(V.type===`bos`||V.type===`slash`)&&(n.output=P+n.output),Z(n);continue}if(V&&(V.type===`bracket`||V.type===`paren`)&&d.regex===!0){n.output=H,Z(n);continue}(L.index===L.start||V.type===`slash`||V.type===`dot`)&&(V.type===`dot`?(L.output+=D,V.output+=D):d.dot===!0?(L.output+=O,V.output+=O):(L.output+=P,V.output+=P),W()!==`*`&&(L.output+=w,V.output+=w)),Z(n)}for(;L.brackets>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`]`));L.output=r.escapeLast(L.output,`[`),X(`brackets`)}for(;L.parens>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`)`));L.output=r.escapeLast(L.output,`(`),X(`parens`)}for(;L.braces>0;){if(d.strictBrackets===!0)throw SyntaxError(u(`closing`,`}`));L.output=r.escapeLast(L.output,`{`),X(`braces`)}if(d.strictSlashes!==!0&&(V.type===`star`||V.type===`bracket`)&&Z({type:`maybe_slash`,value:``,output:`${C}?`}),L.backtrack===!0){L.output=``;for(let e of L.tokens)L.output+=e.output==null?e.value:e.output,e.suffix&&(L.output+=e.suffix)}return L};y.fastpaths=(e,t)=>{let a={...t},o=typeof a.maxLength==`number`?Math.min(i,a.maxLength):i,s=e.length;if(s>o)throw SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${o}`);e=c[e]||e;let{DOT_LITERAL:l,SLASH_LITERAL:u,ONE_CHAR:d,DOTS_SLASH:f,NO_DOT:p,NO_DOTS:m,NO_DOTS_SLASH:h,STAR:g,START_ANCHOR:_}=n.globChars(a.windows),v=a.dot?m:p,y=a.dot?h:p,b=a.capture?``:`?:`,x={negated:!1,prefix:``},S=a.bash===!0?`.*?`:g;a.capture&&(S=`(${S})`);let C=e=>e.noglobstar===!0?S:`(${b}(?:(?!${_}${e.dot?f:l}).)*?)`,w=e=>{switch(e){case`*`:return`${v}${d}${S}`;case`.*`:return`${l}${d}${S}`;case`*.*`:return`${v}${S}${l}${d}${S}`;case`*/*`:return`${v}${S}${u}${d}${y}${S}`;case`**`:return v+C(a);case`**/*`:return`(?:${v}${C(a)}${u})?${y}${d}${S}`;case`**/*.*`:return`(?:${v}${C(a)}${u})?${y}${S}${l}${d}${S}`;case`**/.*`:return`(?:${v}${C(a)}${u})?${l}${d}${S}`;default:{let t=/^(.*?)\.(\w+)$/.exec(e);if(!t)return;let n=w(t[1]);return n?n+l+t[2]:void 0}}},T=w(r.removePrefix(e,x));return T&&a.strictSlashes!==!0&&(T+=`${u}?`),T},t.exports=y})),ot=B(((e,t)=>{let n=it(),r=at(),i=rt(),a=nt(),o=e=>e&&typeof e==`object`&&!Array.isArray(e),s=(e,t,n=!1)=>{if(Array.isArray(e)){let r=e.map(e=>s(e,t,n));return e=>{for(let t of r){let n=t(e);if(n)return n}return!1}}let r=o(e)&&e.tokens&&e.input;if(e===``||typeof e!=`string`&&!r)throw TypeError(`Expected pattern to be a non-empty string`);let i=t||{},a=i.windows,c=r?s.compileRe(e,t):s.makeRe(e,t,!1,!0),l=c.state;delete c.state;let u=()=>!1;if(i.ignore){let e={...t,ignore:null,onMatch:null,onResult:null};u=s(i.ignore,e,n)}let d=(n,r=!1)=>{let{isMatch:o,match:d,output:f}=s.test(n,c,t,{glob:e,posix:a}),p={glob:e,state:l,regex:c,posix:a,input:n,output:f,match:d,isMatch:o};return typeof i.onResult==`function`&&i.onResult(p),o===!1?(p.isMatch=!1,r?p:!1):u(n)?(typeof i.onIgnore==`function`&&i.onIgnore(p),p.isMatch=!1,r?p:!1):(typeof i.onMatch==`function`&&i.onMatch(p),r?p:!0)};return n&&(d.state=l),d};s.test=(e,t,n,{glob:r,posix:a}={})=>{if(typeof e!=`string`)throw TypeError(`Expected input to be a string`);if(e===``)return{isMatch:!1,output:``};let o=n||{},c=o.format||(a?i.toPosixSlashes:null),l=e===r,u=l&&c?c(e):e;return l===!1&&(u=c?c(e):e,l=u===r),(l===!1||o.capture===!0)&&(l=o.matchBase===!0||o.basename===!0?s.matchBase(e,t,n,a):t.exec(u)),{isMatch:!!l,match:l,output:u}},s.matchBase=(e,t,n)=>(t instanceof RegExp?t:s.makeRe(t,n)).test(i.basename(e)),s.isMatch=(e,t,n)=>s(t,n)(e),s.parse=(e,t)=>Array.isArray(e)?e.map(e=>s.parse(e,t)):r(e,{...t,fastpaths:!1}),s.scan=(e,t)=>n(e,t),s.compileRe=(e,t,n=!1,r=!1)=>{if(n===!0)return e.output;let i=t||{},a=i.contains?``:`^`,o=i.contains?``:`$`,c=`${a}(?:${e.output})${o}`;e&&e.negated===!0&&(c=`^(?!${c}).*$`);let l=s.toRegex(c,t);return r===!0&&(l.state=e),l},s.makeRe=(e,t={},n=!1,i=!1)=>{if(!e||typeof e!=`string`)throw TypeError(`Expected a non-empty string`);let a={negated:!1,fastpaths:!0};return t.fastpaths!==!1&&(e[0]===`.`||e[0]===`*`)&&(a.output=r.fastpaths(e,t)),a.output||(a=r(e,t)),s.compileRe(a,t,n,i)},s.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?`i`:``))}catch(e){if(t&&t.debug===!0)throw e;return/$^/}},s.constants=a,t.exports=s})),st=H(B(((e,t)=>{let n=ot(),r=rt();function i(e,t,i=!1){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:r.isWindows()}),n(e,t,i)}Object.assign(i,n),t.exports=i}))(),1);const ct=Array.isArray,lt=/\\/g,ut=process.platform===`win32`,dt=/^(\/?\.\.)+$/;function ft(e,t={}){let n=e.length,r=Array(n),i=Array(n),a,o;for(a=0;a<n;a++){let n=vt(e[a]);r[a]=n;let s=n.length,c=Array(s);for(o=0;o<s;o++)c[o]=(0,st.default)(n[o],t);i[a]=c}return e=>{let s=e.split(`/`);if(s[0]===`..`&&dt.test(e))return!0;for(a=0;a<n;a++){let e=r[a],n=i[a],c=s.length,l=Math.min(c,e.length);for(o=0;o<l;){let r=e[o];if(r.includes(`/`))return!0;if(!n[o](s[o]))break;if(!t.noglobstar&&r===`**`)return!0;o++}if(o===c)return!0}return!1}}const pt=/^[A-Z]:\/$/i,mt=ut?e=>pt.test(e):e=>e===`/`;function ht(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let t=e.length+ +!mt(e);return(e,n)=>e.slice(t,n?-1:void 0)||`.`}let r=t.slice(e.length+1);return r?(e,t)=>{if(e===`.`)return r;let n=`${r}/${e}`;return t?n.slice(0,-1):n}:(e,t)=>t&&e!==`.`?e.slice(0,-1):e}return n?t=>D.relative(e,t)||`.`:n=>D.relative(e,`${t}/${n}`)||`.`}function gt(e,t){if(t.startsWith(`${e}/`)){let n=t.slice(e.length+1);return e=>`${n}/${e}`}return n=>{let r=D.relative(e,`${t}/${n}`);return n[n.length-1]===`/`&&r!==``?`${r}/`:r||`.`}}const _t={parts:!0};function vt(e){let t=st.default.scan(e,_t);return t.parts?.length?t.parts:[e]}const yt=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,bt=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,xt=ut?e=>e.replace(bt,`\\$&`):e=>e.replace(yt,`\\$&`);function St(e,t){if(t?.caseSensitiveMatch===!1)return!0;let n=st.default.scan(e);return n.isGlob||n.negated}function Ct(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString(`es`)}]`,...e)}function wt(e){return typeof e==`string`?[e]:e??[]}const Tt=/^(\/?\.\.)+/,Et=/\\(?=[()[\]{}!*+?@|])/g;function Dt(e,t,n,r){let i=t.cwd,a=e;e[e.length-1]===`/`&&(a=e.slice(0,-1)),a[a.length-1]!==`*`&&t.expandDirectories&&(a+=`/**`);let o=xt(i);a=T(a.replace(Et,``))?D.relative(o,a):D.normalize(a);let s=Tt.exec(a)?.[0],c=vt(a);if(s){let e=(s.length+1)/3,t=0,r=o.split(`/`);for(;t<e&&c[t+e]===r[r.length+t-e];)a=a.slice(0,(e-t-1)*3)+a.slice((e-t)*3+c[t+e].length+1)||`.`,t++;let l=D.join(i,s.slice(t*3));l[0]!==`.`&&n.root.length>l.length&&(n.root=l,n.depthOffset=-e+t)}if(!r&&n.depthOffset>=0){n.commonPath??=c;let e=[],t=Math.min(n.commonPath.length,c.length);for(let r=0;r<t;r++){let t=c[r];if(t===`**`&&!c[r+1]){e.pop();break}if(r===c.length-1||t!==n.commonPath[r]||St(t))break;e.push(t)}n.depthOffset=e.length,n.commonPath=e,n.root=e.length>0?D.join(i,...e):i}return a}function Ot(e,t,n){let r=[],i=[];for(let t of e.ignore)t&&(t[0]!==`!`||t[1]===`(`)&&i.push(Dt(t,e,n,!0));for(let a of t)a&&(a[0]!==`!`||a[1]===`(`?r.push(Dt(a,e,n,!1)):(a[1]!==`!`||a[2]===`(`)&&i.push(Dt(a.slice(1),e,n,!0)));return{match:r,ignore:i}}function kt(e,t){let n=e.cwd,r={root:n,depthOffset:0},i=Ot(e,t,r);e.debug&&Ct(`internal processing patterns:`,i);let{absolute:a,caseSensitiveMatch:o,debug:s,dot:c,followSymbolicLinks:l,onlyDirectories:u}=e,d=r.root.replace(lt,``),f={dot:c,nobrace:e.braceExpansion===!1,nocase:!o,noextglob:e.extglob===!1,noglobstar:e.globstar===!1,posix:!0},p=(0,st.default)(i.match,f),m=(0,st.default)(i.ignore,f),h=ft(i.match,f),g=ht(n,d,a),_=a?g:ht(n,d,!0),v=(e,t)=>{let n=_(t,!0);return n!==`.`&&!h(n)||m(n)},y;e.deep!==void 0&&(y=Math.round(e.deep-r.depthOffset));let b=new tt({filters:[s?(e,t)=>{let n=g(e,t),r=p(n)&&!m(n);return r&&Ct(`matched ${n}`),r}:(e,t)=>{let n=g(e,t);return p(n)&&!m(n)}],exclude:s?(e,t)=>{let n=v(e,t);return Ct(`${n?`skipped`:`crawling`} ${t}`),n}:v,fs:e.fs,pathSeparator:`/`,relativePaths:!a,resolvePaths:a,includeBasePath:a,resolveSymlinks:l,excludeSymlinks:!l,excludeFiles:u,includeDirs:u||!e.onlyFiles,maxDepth:y,signal:e.signal}).crawl(d);return e.debug&&Ct(`internal properties:`,{...r,root:d}),[b,n!==d&&!a&&gt(n,d)]}function At(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}const jt={caseSensitiveMatch:!0,cwd:process.cwd(),debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:!0,followSymbolicLinks:!0,onlyFiles:!0};function Mt(e){let t={...jt,...e};return t.cwd=(t.cwd instanceof URL?j(t.cwd):k(t.cwd)).replace(lt,`/`),t.ignore=wt(t.ignore),t.fs&&={readdir:t.fs.readdir||_,readdirSync:t.fs.readdirSync||v,realpath:t.fs.realpath||y,realpathSync:t.fs.realpathSync||b,stat:t.fs.stat||x,statSync:t.fs.statSync||S},t.debug&&Ct(`globbing with options:`,t),t}function Nt(e,t={}){if(e&&t?.patterns)throw Error(`Cannot pass patterns as both an argument and an option`);let n=ct(e)||typeof e==`string`,r=wt((n?e:e.patterns)??`**/*`),i=Mt(n?t:e);return r.length>0?kt(i,r):[]}async function Pt(e,t){let[n,r]=Nt(e,t);return n?At(await n.withPromise(),r):[]}var Ft=B(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{DEFAULT_CLOCK_TOLERANCE_SEC:()=>f,DEFAULT_JWT_EXPIRE_TIME_MS:()=>d,FileTokenProvider:()=>C,HttpClient:()=>I,HttpError:()=>N,generateJWTToken:()=>m,parseJWTTokenWithVerify:()=>h,registerPlatformPlugin:()=>O,resolvePlatformBaseURL:()=>D}),t.exports=c(l);var u=U(`crypto`),d=1800*1e3,f=60,p={alg:`HS256`,typ:`JWT`};function m(e,t){let n=Math.floor(Date.now()/1e3),r={...e,iss:e.access_key,iat:n,nbf:n,exp:n+Math.floor(t.expireTimeMs/1e3),jti:(0,u.randomUUID)()},i=_(JSON.stringify(p)),a=_(JSON.stringify(r));return`${i}.${a}.${g(`${i}.${a}`,t.secretKey)}`}function h(e,t,n){let r=e.split(`.`);if(r.length!==3)throw Error(`invalid JWT token format`);let[i,a,o]=r;if(JSON.parse(v(i)).alg!==`HS256`)throw Error(`unsupported JWT alg`);let s=g(`${i}.${a}`,t.secretKey),c=Buffer.from(s),l=Buffer.from(o);if(c.length!==l.length||!(0,u.timingSafeEqual)(c,l))throw Error(`JWT signature verification failed`);let d=JSON.parse(v(a));if(!n?.skipExpiration){let e=n?.clockTolerance??f,t=Math.floor(Date.now()/1e3);if(d.exp!==void 0&&d.exp+e<t)throw Error(`JWT token expired at ${new Date(d.exp*1e3).toISOString()}`);if(d.nbf!==void 0&&d.nbf-e>t)throw Error(`JWT token not yet valid, will be valid at ${new Date(d.nbf*1e3).toISOString()}`);if(d.iat!==void 0&&d.iat-e>t)throw Error(`JWT token issued in the future at ${new Date(d.iat*1e3).toISOString()}`)}return d}function g(e,t){return(0,u.createHmac)(`sha256`,t).update(e).digest(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function _(e){return Buffer.from(e).toString(`base64`).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}function v(e){let t=(4-(e.length%4||4))%4,n=`${e}${`=`.repeat(t)}`.replace(/-/g,`+`).replace(/_/g,`/`);return Buffer.from(n,`base64`).toString(`utf8`)}var y=class{cache=new Map;config;constructor(e){this.config={refreshBeforeMs:300*1e3,...e}}getToken(e){let t=this.getCacheKey(e),n=this.cache.get(t),r=Date.now();if(n&&n.expiresAtMs-r>this.config.refreshBeforeMs)return n.token;let i=m(e,this.config),a=r+this.config.expireTimeMs;return this.cache.set(t,{token:i,expiresAtMs:a}),i}clearCache(){this.cache.clear()}clearCacheFor(e){let t=this.getCacheKey(e);this.cache.delete(t)}getCacheKey(e){return[e.access_key,e.tenant_id?.toString()||``,e.user_id||``,e.app_id||``,e.app_env||``,e.sandbox_id||``].join(`:`)}getCacheStats(){let e=Date.now(),t=0,n=0;for(let r of this.cache.values())r.expiresAtMs>e?t++:n++;return{total:this.cache.size,valid:t,expired:n}}},b=U(`fs`),x=300*1e3,S=[`/home/gem/workspace/.force/openclaw/miaoda-provider-key`],C=class{cache=new Map;paths;refreshBeforeMs;constructor(e){this.paths=e?.paths??S,this.refreshBeforeMs=e?.refreshBeforeMs??x}getToken(){let e=Date.now();for(let t of this.paths){let n=this.cache.get(t);if(n&&n.expiresAtMs-e>this.refreshBeforeMs)return{token:n.token,accessKey:n.accessKey};let r=this.readAndParse(t);if(r&&(this.cache.set(t,r),r.expiresAtMs>e))return{token:r.token,accessKey:r.accessKey};if(n&&n.expiresAtMs>e)return{token:n.token,accessKey:n.accessKey}}return null}clearCache(){this.cache.clear()}readAndParse(e){try{let t=(0,b.readFileSync)(e,`utf-8`).trim();if(!t)return null;let n=this.decodePayload(t);return n?.exp?{token:t,accessKey:n.access_key??``,expiresAtMs:n.exp*1e3}:null}catch{return null}}decodePayload(e){try{let t=e.split(`.`);if(t.length!==3)return null;let n=(4-(t[1].length%4||4))%4,r=`${t[1]}${`=`.repeat(n)}`.replace(/-/g,`+`).replace(/_/g,`/`);return JSON.parse(Buffer.from(r,`base64`).toString(`utf8`))}catch{return null}}},w=`FORCE_AUTHN_INNERAPI_DOMAIN`,T=`FORCE_AUTHN_ACCESS_KEY`,E=`FORCE_AUTHN_ACCESS_SECRET`;function D(e){if(!e?.enabled)return e?.baseURL;if(e.baseURL)return e.baseURL;let t=e.domainEnv||w,n=process.env[t];if(!n)throw Error(`\u5E73\u53F0\u6A21\u5F0F\u9700\u8981\u57FA\u7840\u57DF\u540D\uFF0C\u8BF7\u8BBE\u7F6E\u73AF\u5883\u53D8\u91CF ${t}`);return n}function O(e,t){if(!t.enabled)return;k(`platform.defaultClaims`,t.defaultClaims);let n;t.tokenProvider?.type===`file`&&(n=new C({paths:t.tokenProvider.paths,refreshBeforeMs:t.refreshBeforeMs}));let r=t.accessKeyEnv||T,i=t.secretKeyEnv||E,a=t.accessKey??(process.env[r]||``),o=new y({accessKey:a,secretKey:t.secretKey??(process.env[i]||``),expireTimeMs:t.expireTimeMs??d,refreshBeforeMs:t.refreshBeforeMs});return e.request.use(e=>{if(n){let t=n.getToken();if(t){let n={...e.headers,Authorization:`Bearer ${t.token}`,"x-api-key":t.accessKey};return{...e,headers:n}}}k(`request.platformAuth.customClaims`,e.platformAuth?.customClaims);let r={...t.defaultClaims||{},...e.platformAuth?.customClaims||{},access_key:a},i=o.getToken(r),s={...e.headers,Authorization:`Bearer ${i}`,"x-api-key":a};return{...e,headers:s}}),o}function k(e,t){if(t&&Object.prototype.hasOwnProperty.call(t,`access_key`))throw Error(`${e} \u4E0D\u5141\u8BB8\u8BBE\u7F6E access_key`)}var A=class{interceptors=[];use(e,t){return this.interceptors.push({onFulfilled:e,onRejected:t}),this.interceptors.length-1}eject(e){this.interceptors[e]&&(this.interceptors[e]=null)}clear(){this.interceptors=[]}forEach(e){this.interceptors.forEach(t=>{t!==null&&e(t)})}};function j(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function M(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e))return e.reduce((e,[t,n])=>(e[t]=n,e),{});let t={};return Object.entries(e).forEach(([e,n])=>{t[e]=Array.isArray(n)?n.join(`,`):n}),t}var N=class e extends Error{isHttpError=!0;response;config;constructor(t,n,r){super(r||`Request failed with status ${t?.status||`unknown`}`),this.name=`HttpError`,this.response=t,this.config=P(n),Object.setPrototypeOf(this,e.prototype)}};function P(e){let{headers:t,...n}=e;return{...n,headers:F(t)}}function F(e){if(!e)return;let t=M(e),n={},r=[`authorization`,`x-api-key`,`cookie`,`x-secret`];for(let[e,i]of Object.entries(t)){let t=e.toLowerCase();r.includes(t)?n[e]=`[REDACTED]`:n[e]=i}return n}var I=class{defaultConfig;securityConfig;interceptors={request:new A,response:new A};constructor(e){let{platform:t,security:n,...r}=e||{};this.defaultConfig={timeout:5e3,...r};let i=n?.strictMode??!1;this.securityConfig={allowedProtocols:i?[`http:`,`https:`]:null,maxResponseSize:i?50*1024*1024:0,strictMode:i,...n},t?.enabled&&(this.defaultConfig.baseURL||(this.defaultConfig.baseURL=D(t)),O(this.interceptors,t))}async get(e,t){return this.request({...t,url:e,method:`GET`})}async post(e,t,n){let r={...n?.headers},i=t;return j(t)&&(i=JSON.stringify(t),Object.keys(r).some(e=>e.toLowerCase()===`content-type`)||(r[`Content-Type`]=`application/json`)),this.request({...n,url:e,method:`POST`,body:i,headers:r})}async put(e,t,n){let r={...n?.headers},i=t;return j(t)&&(i=JSON.stringify(t),Object.keys(r).some(e=>e.toLowerCase()===`content-type`)||(r[`Content-Type`]=`application/json`)),this.request({...n,url:e,method:`PUT`,body:i,headers:r})}async delete(e,t){return this.request({...t,url:e,method:`DELETE`})}async patch(e,t,n){let r={...n?.headers},i=t;return j(t)&&(i=JSON.stringify(t),Object.keys(r).some(e=>e.toLowerCase()===`content-type`)||(r[`Content-Type`]=`application/json`)),this.request({...n,url:e,method:`PATCH`,body:i,headers:r})}async request(e){let t=M(this.defaultConfig.headers),n=M(e.headers),r={};for(let e in t)r[e.toLowerCase()]={key:e,value:t[e]};for(let e in n)r[e.toLowerCase()]={key:e,value:n[e]};let i={};for(let e in r){let{key:t,value:n}=r[e];i[t]=n}let a={...this.defaultConfig,...e,headers:i};try{a=await this.runRequestInterceptors(a)}catch(e){return Promise.reject(e)}a.headers=M(a.headers);let o=this.buildUrl(a.url,a.params),s=a.timeout||this.defaultConfig.timeout||5e3,c=new AbortController,l=setTimeout(()=>c.abort(),s),u=a.signal;u&&(u.aborted?(clearTimeout(l),c.abort()):u.addEventListener(`abort`,()=>c.abort(),{once:!0}));let{platformAuth:d,params:f,timeout:p,baseURL:m,url:h,...g}=a;try{let e=await fetch(o,{...g,signal:c.signal});if(clearTimeout(l),this.securityConfig.maxResponseSize>0){let t=e.headers.get(`content-length`);if(t){let e=parseInt(t,10);if(e>this.securityConfig.maxResponseSize)throw Error(`Response size ${e} bytes exceeds limit of ${this.securityConfig.maxResponseSize} bytes`)}}if(!e.ok){let t=new N(e,a);return this.runResponseInterceptors(Promise.reject(t))}return this.runResponseInterceptors(Promise.resolve(e))}catch(e){clearTimeout(l);let t=e instanceof N?e:new N(void 0,a,e.name===`AbortError`?`Request aborted`:e.message);return this.runResponseInterceptors(Promise.reject(t))}}runRequestInterceptors(e){let t=Promise.resolve(e),n=[];this.interceptors.request.forEach(e=>{n.push(e)});for(let e of n)t=t.then(e.onFulfilled,e.onRejected);return t}async runResponseInterceptors(e){let t=e,n=[];this.interceptors.response.forEach(e=>{n.push(e)});for(let e of n)t=t.then(e.onFulfilled,e.onRejected);return t}buildUrl(e,t){let n=this.defaultConfig.baseURL,r;r=!n||/^https?:\/\//i.test(e)?e:n.replace(/\/+$/,``)+`/`+e.replace(/^\/+/,``);let i=new URL(r),{allowedProtocols:a}=this.securityConfig;if(a&&!a.includes(i.protocol))throw Error(`Protocol ${i.protocol} is not allowed. Allowed: ${a.join(`, `)}`);if(t)for(let[e,n]of Object.entries(t))n!=null&&i.searchParams.set(e,String(n));return i.href}}}))();const It=new Set([`forced_quota_failed`,`k_st_ec_400002680`,`k_st_ec_400002681`,`k_st_ec_400002682`,`k_st_ec_400002683`,`k_st_ec_400002684`,`k_st_ec_400002685`,`k_st_ec_400002686`,`k_st_ec_400002687`,`k_st_ec_400002688`,`k_st_ec_400002690`,`k_st_ec_400002698`]),Lt=new Set([`k_st_ec_400002680`,`k_st_ec_400002681`,`k_st_ec_400002682`,`k_st_ec_400002683`,`k_st_ec_400002684`,`k_st_ec_400002685`,`k_st_ec_400002686`,`k_st_ec_400002687`,`k_st_ec_400002688`,`k_st_ec_400002689`,`k_st_ec_400002690`,`k_st_ec_400002698`]);function Rt(e){return!!e&&It.has(e)}function zt(e){return!!e&&Lt.has(e)}let Bt;function Vt(){if(Bt)return Bt;try{let e=l(s(N(import.meta.url)),`..`,`package.json`);Bt=JSON.parse(a(e,`utf-8`))}catch(e){console.warn(`[miaoda-coding] failed to read package.json: ${e instanceof Error?e.message:e}`),Bt={}}return Bt}function Ht(){let e=process.env.FORCE_AUTHN_INNERAPI_DOMAIN;if(!e)throw Error(`studio-client: 缺少环境变量,需要: FORCE_AUTHN_INNERAPI_DOMAIN`);return{apiUrl:e}}var Ut=class extends Error{userFacing=!0;constructor(e,t,n){super(e),this.statusCode=t,this.logId=n,this.name=`UserFacingError`}};function Wt(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`)}function Gt(...e){for(let t of e)if(typeof t==`string`&&t)return t}async function*Kt(e){let t=new TextDecoder,n=``,r;for await(let i of e){n+=t.decode(i,{stream:!0});let e=n.split(`
2
2
 
3
3
  `);n=e.pop();for(let t of e){let e=t.split(`
4
- `),n=e.find(e=>e.startsWith(`id:`));n&&(r=n.slice(3).trim());let i=e.find(e=>e.startsWith(`data:`));if(!i)continue;let a=i.slice(5).trim();if(a){if(a===`[DONE]`){yield{data:null,id:r,done:!0};return}try{yield{data:JSON.parse(a),id:r,done:!1}}catch{}}}}}var Wt=class{#e;#t;constructor(){this.#t=Rt();let e=Lt().headers;this.#e=new Ft.HttpClient({baseURL:this.#t.apiUrl,timeout:9e5,...process.env.FORCE_FRAMEWORK_ENVIRONMENT!==`online`&&Vt(e)?{headers:e}:{},platform:{enabled:!0,tokenProvider:{type:`file`}}})}async createSubApp(e={}){let t=`${this.#t.apiUrl}/api/v1/studio/innerapi/openclaw/sub_app/create`,n={};e.message&&(n.message=e.message),e.agentId&&(n.agentId=e.agentId);let r;try{r=await this.#e.post(t,n,{headers:{"Content-Type":`application/json`}})}catch(e){if(e instanceof Ft.HttpError&&e.response){let t=e.response.headers.get(`x-tt-logid`)??``;throw Error(`createSubApp 请求失败 (logID: ${t}): ${e.response.status}`)}throw e}let i=r.headers?.get?.(`x-tt-logid`)??``,a=await r.json();if(a.BaseResp?.StatusCode!==0&&a.BaseResp?.StatusMessage)throw Error(`createSubApp 业务错误 (logID: ${i}): ${a.BaseResp.StatusMessage}`);if(a.error_msg&&a.status_code!==`0`)throw zt.has(a.status_code)?new Bt(a.error_msg,a.status_code,i):Error(`createSubApp 服务错误 (logID: ${i}): ${a.error_msg}`);let o=Ht(a.appID,a.appId,a.app_id,a.data?.appID,a.data?.appId,a.data?.app_id),s=Ht(a.conversationID,a.conversationId,a.conversation_id,a.data?.conversationID,a.data?.conversationId,a.data?.conversation_id);if(!o){let e=Object.keys(a).join(`,`)||`(none)`,t=a.data&&typeof a.data==`object`&&Object.keys(a.data).join(`,`)||`(none)`;throw Error(`createSubApp 返回异常 (logID: ${i}): 缺少 appID,topLevelKeys=${e} dataKeys=${t}`)}return{appID:o,conversationID:s,logId:i}}async*streamChat(e){let t=`${this.#t.apiUrl}/api/v1/studio/innerapi/openclaw/sub_app/${e.appID}/stream_chat`,n={appID:e.appID,message:e.message};e.workDir&&(n.workDir=e.workDir),e.channelAppId&&(n.channelAppId=e.channelAppId);let r={"Content-Type":`application/json`,Accept:`text/event-stream`};e.lastEventID&&(r[`Last-Event-ID`]=e.lastEventID);let i;try{i=await this.#e.post(t,n,{headers:r})}catch(e){if(e instanceof Ft.HttpError&&e.response){let t=e.response.headers.get(`x-tt-logid`)??``,n=Error(`streamChat 请求失败 (logID: ${t}): ${e.response.status}`);throw n.logId=t,n}let t=e.cause?` cause: ${e.cause.message||e.cause}`:``,n=e.code?` code: ${e.code}`:``;throw Error(`streamChat 网络错误: ${e.message}${n}${t}`)}yield{__meta:!0,logId:i.headers?.get?.(`x-tt-logid`)??``},yield*Ut(i.body)}};const Gt=`.spark`,Kt=`meta.json`;function qt(e){return c(e,Gt,Kt)}async function Jt(e){try{return JSON.parse(await f(qt(e),`utf8`))}catch{return null}}async function Yt(e){if(!e)return null;try{return JSON.parse(await f(c(l(e),Gt,Kt),`utf8`))}catch{return null}}async function Xt(e,t,n){await d(c(e,Gt),{recursive:!0});let r=await Jt(e),i={...r??{},...t};if(i.features||=[],!r){let e=await Yt(n?.rootDir);if(e)for(let[t,n]of Object.entries(e))t in i||(i[t]=n)}await h(qt(e),JSON.stringify(i,null,2),`utf8`)}function Zt(e){let t=e;return t?.data?.message??t?.Data?.Message??null}async function Qt(e){let t=e.maxReconnect??2,n=e.maxTotalReconnect??10,r=e.reconnectDelayMs??1500,i,a=0,o=0,s=0,c,l;for(;;){let u=!1,d=!1,f=!1,p=i;try{for await(let t of e.createStream(p)){if(e.signal?.aborted)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,success:!1,error:`cancelled`};let n=t;if(n?.__meta){l=n.logId||l;continue}let r=n;if(r.id&&(i=r.id),r.id&&p&&r.id===p)continue;if(r.done)break;s++,a>0&&(a=0);let d=Zt(r.data);if(d?.type===`metadata`&&d?.status!==`in_progress`&&(u=!0),d?.role===`assistant`&&d?.type===`message`&&d?.status===`completed`&&typeof d?.content==`string`&&d.content&&(c=d.content),e.onEvent&&e.onEvent(r,{lastEventId:i,reconnectCount:o})===!1){f=!0;break}}}catch(e){if(!u){let t=e instanceof Error?e.message:String(e);if(/\b4[0-9]{2}\b/.test(t)||t.includes(`业务错误`))return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,success:!1,error:t};d=!0}}if(f)break;if(s===0&&!u&&!d)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,success:!1,error:`stream returned no events`};if(u)break;if(d||i){if(a++,o++,a<=t&&o<=n&&i){if(e.onReconnect?.(o,i),await new Promise(t=>{let n=setTimeout(t,r);e.signal&&e.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),e.signal?.aborted)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,success:!1,error:`cancelled`};continue}let u=`stream disconnected, reconnect exhausted`;return e.onFailed?.(u),{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,success:!1,error:u}}break}return e.onComplete?.({totalEvents:s,reconnectCount:o,lastEventId:i}),{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,success:!0}}let $t=``,en=0;function tn(e){try{let t=nn(e);if(!t)return null;let n=t.replace(/\s*\(.*\)$/,``).replace(/\s*:.*$/,``),r=Date.now();return n===$t&&r-en<3e4?null:($t=n,en=r,t)}catch{return null}}function nn(e){let t=e.role,n=e.tool_calls,r=e.content;if(e.finish_reason,t===`assistant`&&n?.length)for(let e of n){let t=e?.function?.name??e?.name,n={};try{let t=e?.function?.arguments??e?.arguments;n=typeof t==`string`?JSON.parse(t):t??{}}catch{}if(t===`bash`){let e=String(n.command??``);if(e.includes(`init`))return`初始化项目`;if(e.includes(`db sql`))return`数据库操作`;if(e.includes(`deploy`))return`部署中`}}return t===`tool`&&typeof r==`string`&&(r.startsWith(`执行 run_shell_command 工具失败`)||r.startsWith(`command exitcode:`))?`失败: ${r.slice(0,200)+(r.length>200?`...`:``)}`:null}const rn=`.spark`,an=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1,timeZoneName:`longOffset`});async function on(e){return(await Pt(`**/SKILL.md`,{cwd:e,followSymbolicLinks:!0}).catch(()=>[])).length>0}async function sn(e){try{return JSON.parse(await f(c(e,`.spark`,`meta.json`),`utf8`))}catch{return null}}async function cn(e,t){if(!await on(c(e,`.agent`,`skills`)))return`.agent/skills 下未找到 SKILL.md,项目 Agent 技能未配置`;let n=await sn(e)??(t?await sn(t):null);return n?!n.stack||!n.version?`.spark/meta.json 缺少 stack 或 version 字段`:null:`缺少 .spark/meta.json,项目未初始化`}function ln(e){return c(e,rn,`progress.txt`)}function un(){let e=Object.fromEntries(an.formatToParts(new Date).filter(e=>e.type!==`literal`).map(e=>[e.type,e.value])),t=e.timeZoneName===`GMT`?`+00:00`:e.timeZoneName.replace(/^GMT/,``);return`${e.year}-${e.month}-${e.day}T${e.hour}:${e.minute}:${e.second}${t}`}function dn(e){let t=[],n=``,r=``,i=``,a=e.includes(`## 已完成`)||e.includes(`## 当前任务`),o=!1,s=!a;for(let c of e.split(`
5
- `)){let e=c.trim();if(a){if(e===`## 已完成`){o=!0,s=!1;continue}if(e.startsWith(`## 当前任务`)){s=!0,o=!1;continue}if(e===``)continue}if(o&&e)t.push(e);else if(s&&e){let t=e.match(/^\[([^\]]+)\]\s*(.*)/);if(t){let e=t[2];i=t[1],r=e,!a&&e.startsWith(`需求: `)&&(n=e.slice(4))}else n||=e}}return{history:t,taskDesc:n,lastStatus:r,lastTimestamp:i}}async function fn(e,t){await d(c(e,rn),{recursive:!0});let n=ln(e),r=[];try{let e=await f(n,`utf8`);if(e.trim()){let t=dn(e);if(r.push(...t.history),t.taskDesc){let e=t.lastTimestamp||un(),n;n=t.lastStatus.startsWith(`失败:`)?t.lastStatus:t.lastStatus===`处理完成`?`成功`:t.lastStatus||`未知状态`,r.push(`[${e}] ${t.taskDesc} — ${n}`)}}}catch{}await h(n,`## 已完成\n\n${r.length?r.join(`
4
+ `),n=e.find(e=>e.startsWith(`id:`));n&&(r=n.slice(3).trim());let i=e.find(e=>e.startsWith(`data:`));if(!i)continue;let a=i.slice(5).trim();if(a){if(a===`[DONE]`){yield{data:null,id:r,done:!0};return}try{yield{data:JSON.parse(a),id:r,done:!1}}catch{}}}}}var qt=class{#e;#t;constructor(){this.#t=Ht();let e=Vt().headers;this.#e=new Ft.HttpClient({baseURL:this.#t.apiUrl,timeout:9e5,...process.env.FORCE_FRAMEWORK_ENVIRONMENT!==`online`&&Wt(e)?{headers:e}:{},platform:{enabled:!0,tokenProvider:{type:`file`}}})}async createSubApp(e={}){let t=`${this.#t.apiUrl}/api/v1/studio/innerapi/openclaw/sub_app/create`,n={};e.message&&(n.message=e.message),e.agentId&&(n.agentId=e.agentId);let r;try{r=await this.#e.post(t,n,{headers:{"Content-Type":`application/json`}})}catch(e){if(e instanceof Ft.HttpError&&e.response){let t=e.response.headers.get(`x-tt-logid`)??``;throw Error(`createSubApp 请求失败 (logID: ${t}): ${e.response.status}`)}throw e}let i=r.headers?.get?.(`x-tt-logid`)??``,a=await r.json();if(a.BaseResp?.StatusCode!==0&&a.BaseResp?.StatusMessage)throw Error(`createSubApp 业务错误 (logID: ${i}): ${a.BaseResp.StatusMessage}`);if(a.error_msg&&a.status_code!==`0`)throw zt(a.status_code)?new Ut(a.error_msg,a.status_code,i):Error(`createSubApp 服务错误 (logID: ${i}): ${a.error_msg}`);let o=Gt(a.appID,a.appId,a.app_id,a.data?.appID,a.data?.appId,a.data?.app_id),s=Gt(a.conversationID,a.conversationId,a.conversation_id,a.data?.conversationID,a.data?.conversationId,a.data?.conversation_id);if(!o){let e=Object.keys(a).join(`,`)||`(none)`,t=a.data&&typeof a.data==`object`&&Object.keys(a.data).join(`,`)||`(none)`;throw Error(`createSubApp 返回异常 (logID: ${i}): 缺少 appID,topLevelKeys=${e} dataKeys=${t}`)}return{appID:o,conversationID:s,logId:i}}async*streamChat(e){let t=`${this.#t.apiUrl}/api/v1/studio/innerapi/openclaw/sub_app/${e.appID}/stream_chat`,n={appID:e.appID,message:e.message};e.workDir&&(n.workDir=e.workDir),e.channelAppId&&(n.channelAppId=e.channelAppId);let r={"Content-Type":`application/json`,Accept:`text/event-stream`};e.lastEventID&&(r[`Last-Event-ID`]=e.lastEventID);let i;try{i=await this.#e.post(t,n,{headers:r})}catch(e){if(e instanceof Ft.HttpError&&e.response){let t=e.response.headers.get(`x-tt-logid`)??``,n=Error(`streamChat 请求失败 (logID: ${t}): ${e.response.status}`);throw n.logId=t,n}let t=e.cause?` cause: ${e.cause.message||e.cause}`:``,n=e.code?` code: ${e.code}`:``;throw Error(`streamChat 网络错误: ${e.message}${n}${t}`)}yield{__meta:!0,logId:i.headers?.get?.(`x-tt-logid`)??``},yield*Kt(i.body)}};const Jt=`.spark`,Yt=`meta.json`;function Xt(e){return c(e,Jt,Yt)}async function Zt(e){try{return JSON.parse(await f(Xt(e),`utf8`))}catch{return null}}async function Qt(e){if(!e)return null;try{return JSON.parse(await f(c(l(e),Jt,Yt),`utf8`))}catch{return null}}async function $t(e,t,n){await d(c(e,Jt),{recursive:!0});let r=await Zt(e),i={...r??{},...t};if(i.features||=[],!r){let e=await Qt(n?.rootDir);if(e)for(let[t,n]of Object.entries(e))t in i||(i[t]=n)}await h(Xt(e),JSON.stringify(i,null,2),`utf8`)}function en(e){let t=e;return t?.data?.message??t?.Data?.Message??null}function tn(e){return(typeof e?.finishReason==`string`&&e.finishReason?e.finishReason:void 0)||(typeof e?.metadata?.finishReason==`string`&&e.metadata.finishReason?e.metadata.finishReason:void 0)}function nn(e){let t=[e?.metadata?.error?.message,e?.metadata?.error?.Message,e?.error?.message,e?.error?.Message];for(let e of t)if(typeof e==`string`&&e.trim())return e.trim()}function rn(e){let t=[e?.metadata?.error?.code,e?.metadata?.error?.Code,e?.error?.code,e?.error?.Code];for(let e of t)if(typeof e==`string`&&e.trim())return e.trim()}function an(e){return e===`credit_limit`}function on(e){let t=e;if(en(t))return;let n=t?.BaseResp??t?.baseResp,r=typeof t?.StatusMessage==`string`?t.StatusMessage:void 0,i=typeof t?.StatusCode==`number`?t.StatusCode:typeof t?.status_code==`number`?t.status_code:void 0,a=typeof n?.KStatusMessage==`string`&&n.KStatusMessage?n.KStatusMessage:typeof n?.StatusMessage==`string`&&n.StatusMessage?n.StatusMessage:void 0,o=typeof n?.KStatusCode==`string`&&n.KStatusCode?n.KStatusCode:void 0;if(r===`error`||typeof i==`number`&&i!==0||o||a&&a!==`success`)return{message:a??r??`stream service failed`,code:o}}async function sn(e){let t=e.maxReconnect??2,n=e.maxTotalReconnect??10,r=e.reconnectDelayMs??1500,i,a=0,o=0,s=0,c,l,u,d,f,p;for(;;){let m=!1,h=!1,g=!1,_=i;try{for await(let t of e.createStream(_)){if(e.signal?.aborted)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:`stream_interrupted`,finishReasonRaw:f,errorCodeRaw:p,success:!1,error:`cancelled`};let n=t;if(n?.__meta){l=n.logId||l;continue}let r=n;r.id&&(i=r.id);let h=en(r.data),v=on(r.data),y=!!(r.id&&_&&r.id===_);v&&(p=v.code??p,u=Rt(v.code)?`quota_exceeded`:`service_failed`,d=v.message);let b=tn(h);b&&(f=b);let x=h?.type===`metadata`&&h?.status!==`in_progress`;x&&(m=!0,b===`user_stop`&&u!==`service_failed`&&u!==`quota_exceeded`&&(u=`user_stopped`,d=`user stopped`));let S=h?.status===`failed`;if(S){let e=rn(h);p=e??p,u=Rt(e)||an(b)?`quota_exceeded`:`service_failed`,d=nn(h)??(b?`stream failed: ${b}`:`stream failed`)}if(y){if(x||S||v)break;continue}if(r.done)break;if(s++,a>0&&(a=0),h?.role===`assistant`&&h?.type===`message`&&h?.status===`completed`&&typeof h?.content==`string`&&h.content&&(c=h.content),e.onEvent&&e.onEvent(r,{lastEventId:i,reconnectCount:o})===!1){g=!0;break}}}catch(e){if(!m){let t=e instanceof Error?e.message:String(e);if(/\b4[0-9]{2}\b/.test(t)||t.includes(`业务错误`))return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:`service_failed`,finishReasonRaw:f,errorCodeRaw:p,success:!1,error:t};h=!0}}if(g)break;if(u===`service_failed`||u===`quota_exceeded`)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:u,finishReasonRaw:f,errorCodeRaw:p,success:!1,error:d??`stream failed`};if(u===`user_stopped`)break;if(s===0&&!m&&!h)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:`stream_interrupted`,finishReasonRaw:f,errorCodeRaw:p,success:!1,error:`stream returned no events`};if(m){u??=`completed`;break}if(h||i){if(a++,o++,a<=t&&o<=n&&i){if(e.onReconnect?.(o,i),await new Promise(t=>{let n=setTimeout(t,r);e.signal&&e.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()},{once:!0})}),e.signal?.aborted)return{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:`stream_interrupted`,finishReasonRaw:f,errorCodeRaw:p,success:!1,error:`cancelled`};continue}let u=`stream disconnected, reconnect exhausted`;return e.onFailed?.(u),{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:`stream_interrupted`,finishReasonRaw:f,errorCodeRaw:p,success:!1,error:u}}break}return u===`completed`&&e.onComplete?.({totalEvents:s,reconnectCount:o,lastEventId:i}),{totalEvents:s,reconnectCount:o,lastEventId:i,finalText:c,logId:l,terminalReason:u,finishReasonRaw:f,errorCodeRaw:p,success:!u||u===`completed`,error:u===`user_stopped`?d:void 0}}let cn=``,ln=0;function un(e){try{let t=dn(e);if(!t)return null;let n=t.replace(/\s*\(.*\)$/,``).replace(/\s*:.*$/,``),r=Date.now();return n===cn&&r-ln<3e4?null:(cn=n,ln=r,t)}catch{return null}}function dn(e){let t=e.role,n=e.tool_calls,r=e.content;if(e.finish_reason,t===`assistant`&&n?.length)for(let e of n){let t=e?.function?.name??e?.name,n={};try{let t=e?.function?.arguments??e?.arguments;n=typeof t==`string`?JSON.parse(t):t??{}}catch{}if(t===`bash`){let e=String(n.command??``);if(e.includes(`init`))return`初始化项目`;if(e.includes(`db sql`))return`数据库操作`;if(e.includes(`deploy`))return`部署中`}}return t===`tool`&&typeof r==`string`&&(r.startsWith(`执行 run_shell_command 工具失败`)||r.startsWith(`command exitcode:`))?`失败: ${r.slice(0,200)+(r.length>200?`...`:``)}`:null}const fn=`.spark`,pn=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1,timeZoneName:`longOffset`});async function mn(e){return(await Pt(`**/SKILL.md`,{cwd:e,followSymbolicLinks:!0}).catch(()=>[])).length>0}async function hn(e){try{return JSON.parse(await f(c(e,`.spark`,`meta.json`),`utf8`))}catch{return null}}async function gn(e,t){if(!await mn(c(e,`.agent`,`skills`)))return`.agent/skills 下未找到 SKILL.md,项目 Agent 技能未配置`;let n=await hn(e)??(t?await hn(t):null);return n?!n.stack||!n.version?`.spark/meta.json 缺少 stack 或 version 字段`:null:`缺少 .spark/meta.json,项目未初始化`}function _n(e){return c(e,fn,`progress.txt`)}function vn(){let e=Object.fromEntries(pn.formatToParts(new Date).filter(e=>e.type!==`literal`).map(e=>[e.type,e.value])),t=e.timeZoneName===`GMT`?`+00:00`:e.timeZoneName.replace(/^GMT/,``);return`${e.year}-${e.month}-${e.day}T${e.hour}:${e.minute}:${e.second}${t}`}function yn(e){let t=[],n=``,r=``,i=``,a=e.includes(`## 已完成`)||e.includes(`## 当前任务`),o=!1,s=!a;for(let c of e.split(`
5
+ `)){let e=c.trim();if(a){if(e===`## 已完成`){o=!0,s=!1;continue}if(e.startsWith(`## 当前任务`)){s=!0,o=!1;continue}if(e===``)continue}if(o&&e)t.push(e);else if(s&&e){let t=e.match(/^\[([^\]]+)\]\s*(.*)/);if(t){let e=t[2];i=t[1],r=e,!a&&e.startsWith(`需求: `)&&(n=e.slice(4))}else n||=e}}return{history:t,taskDesc:n,lastStatus:r,lastTimestamp:i}}async function bn(e,t){await d(c(e,fn),{recursive:!0});let n=_n(e),r=[];try{let e=await f(n,`utf8`);if(e.trim()){let t=yn(e);if(r.push(...t.history),t.taskDesc){let e=t.lastTimestamp||vn(),n;n=t.lastStatus.startsWith(`失败:`)?t.lastStatus:t.lastStatus===`处理完成`?`成功`:t.lastStatus||`未知状态`,r.push(`[${e}] ${t.taskDesc} — ${n}`)}}}catch{}await h(n,`## 已完成\n\n${r.length?r.join(`
6
6
  `)+`
7
- `:``}\n## 当前任务\n\n${t}\n`,`utf8`)}async function Q(e,t){await u(ln(e),`[${un()}] ${t}\n`,`utf8`)}async function*pn(e){let{cwd:t,rootDir:n,task:r,agentId:i,signal:a}=e;try{let o=await cn(t,n);if(o){yield{type:`failed`,phase:`pre-create`,userFacing:!1,error:o};return}let s=new Wt,c=e.requestText??r;await fn(t,c.slice(0,200)+(c.length>200?`...`:``)),e.traceId&&await Q(t,`trace_id: ${e.traceId}`),await Q(t,`已接收需求`),yield{type:`progress`,message:`已接收需求`};let l=await Jt(t),u=!l?.appId,d=un();if(u){let e;try{e=await s.createSubApp({message:r,agentId:i})}catch(e){let n=e instanceof Error?e.message:String(e),r=e instanceof Bt,i=e?.logId;try{await Q(t,`失败: ${n}`)}catch{}yield{type:`failed`,error:n,phase:`create`,userFacing:r,logId:i};return}let{appID:a,conversationID:o,logId:c}=e;l={appId:a,conversationId:o,createdAt:d,updatedAt:d},await Xt(t,l,{rootDir:n}),await Q(t,`应用已创建(appId: ${a})`),yield{type:`app_created`,appId:a,conversationId:o,logId:c}}await Q(t,`正在处理`),yield{type:`progress`,message:`正在处理`};let f=!1,p=Date.now(),m=setInterval(()=>{Q(t,`正在开发中(已 ${Math.floor((Date.now()-p)/6e4)} 分钟)`).catch(()=>{})},6e4),h;try{h=await Qt({createStream:n=>s.streamChat({appID:l.appId,message:r,workDir:t,channelAppId:e.channelAppId,...n?{lastEventID:n}:{}}),onEvent:e=>{if(a?.aborted)return!1;let n=Zt(e.data),r=n?.delta?.type;!f&&n?.role===`assistant`&&(n?.status===`in_progress`||r===`text`)&&(f=!0,Q(t,`正在输出结果`).catch(()=>{}));try{if(n?.status===`completed`){let e=tn(n);e&&Q(t,e).catch(()=>{})}}catch{}},onReconnect:(t,n)=>{e.onReconnect?.(t,n)},onFailed:n=>{e.onStreamFailed?.(n),Q(t,`失败: ${n}`).catch(()=>{})},signal:a})}finally{clearInterval(m)}if(!h.success){let e=h.error?.includes(`disconnected`)||h.error?.includes(`no events`);yield{type:`failed`,error:h.error||`stream failed`,logId:h.logId,phase:`stream`,retryable:e};return}let{finalText:g,logId:_}=h;if(f&&(yield{type:`progress`,message:`正在输出结果`,logId:_||void 0}),a?.aborted){await Q(t,`失败: cancelled`),yield{type:`failed`,error:`cancelled`};return}let v=un();await Xt(t,{...l,updatedAt:v,finalText:g},{rootDir:n}),g&&await Q(t,`Agent 回复: ${g.slice(0,200)+(g.length>200?`...`:``)}`),await Q(t,`处理完成`),yield{type:`completed`,appId:l.appId,logId:_||void 0,finalText:g}}catch(e){let n=e instanceof Error?e.message:String(e);try{await Q(t,`失败: ${n}`)}catch{}yield{type:`failed`,error:n,logId:e?.logId}}}const mn=[`research`,`design`,`feedback`];function hn(e){return e.replace(/[^a-zA-Z0-9\u4e00-\u9fff-]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`reference`}async function gn(e){let t;try{t=await p(e)}catch{return 1}let n=0;for(let e of t){let t=e.match(/^(\d{3})-/);if(t){let e=parseInt(t[1],10);e>n&&(n=e)}}return n+1}async function _n(e){try{let t=await f(c(e,`reference`,`manifest.json`),`utf8`);return JSON.parse(t)}catch{return{updatedAt:new Date().toISOString(),files:[]}}}async function vn(e,t){await d(c(e,`reference`),{recursive:!0}),await h(c(e,`reference`,`manifest.json`),JSON.stringify(t,null,2),`utf8`)}async function yn(e){let{appCwd:t,category:n,content:r,filename:i,mode:a=`append`}=e,o=c(t,`reference`,n);if(a===`replace`)try{await m(o,{recursive:!0,force:!0})}catch{}await d(o,{recursive:!0});let s=await gn(o),l=`${n}/${`${String(s).padStart(3,`0`)}-${hn(i??`reference`)}.md`}`,u=`reference/${l}`;await h(c(t,u),r,`utf8`);let f=await _n(t);return a===`replace`&&(f.files=f.files.filter(e=>e.category!==n)),f.files.push({path:l,category:n,writtenAt:new Date().toISOString()}),f.updatedAt=new Date().toISOString(),await vn(t,f),{relativePath:u,category:n,seq:s}}async function bn(e){let t=c(e,`reference`),n;try{n=await p(t)}catch{return{totalFiles:0,categories:{}}}let r={},i=0;for(let e of n){if(!mn.includes(e))continue;let n;try{n=(await p(c(t,e))).filter(e=>e.endsWith(`.md`)).sort()}catch{continue}n.length>0&&(r[e]={count:n.length,files:n},i+=n.length)}return{totalFiles:i,categories:r}}async function xn(e){return(await bn(e)).totalFiles>0}function Sn(e){let t=e?.log,n=e?.timeoutMs??5e3,r=null,i=null,a=null;return{onSessionStart(e){t?.info?.(`db-schema: session_start sessionId=${e??`unknown`}, clearing cache`),r=null,i=null,a=e??null},async getSchemaSummary(e){return e&&a!==null&&e!==a?(t?.warn?.(`db-schema: session changed without session_start: ${a} -> ${e}, resetting cache`),r=null,i=null,a=e):e&&a===null&&(a=e),r===null?i||(i=(async()=>{t?.info?.(`db-schema: fetching (timeout=${n}ms)`);try{let{stdout:e}=await Cn(wn(),n),i=Tn(e);if(i.length===0)return t?.info?.(`db-schema: empty, skip injection for this session`),r=``,null;let a=En(i);return r=a,t?.info?.(`db-schema: cached ${i.length} table(s), ${a.length} chars`),a}catch(e){let n=e instanceof Error?e.message:String(e);return t?.warn?.(`db-schema: fetch failed (will not retry this session): ${n}`),r=``,null}finally{i=null}})(),i):r===``?null:r}}}function Cn(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`timeout after ${t}ms`)),t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}function wn(){return new Promise((e,n)=>{t(`npx`,[`-y`,`@lark-apaas/miaoda-data-cli`,`db`,`schema`,`--json`],{timeout:3e4,maxBuffer:10*1024*1024},(t,r,i)=>{if(t)return n(Error(`execFile failed: ${t.message} | stderr: ${i?.slice(0,500)??``} | stdout: ${r?.slice(0,500)??``}`));e({stdout:r,stderr:i})})})}function Tn(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n:n&&typeof n==`object`&&n.tableName?[n]:[]}function En(e){return`【当前数据库表结构】\n${e.map(e=>{let t=e.fields.map(e=>`${e.fieldName}(${e.type})`).join(`, `),n=e.comment?` (${e.comment})`:``;return`- ${e.tableName}${n}: ${t}`}).join(`
8
- `)}`}function Dn(){return`dev`}var On=V(z((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=10,n=1e3,r=function(e){return JSON.stringify({ev_type:`batch`,list:e})};function i(e){var i=e.transport,a=e.endpoint,o=e.size,s=o===void 0?t:o,c=e.wait,l=c===void 0?n:c,u=[],d=0,f,p,m={getSize:function(){return s},getWait:function(){return l},setSize:function(e){s=e},setWait:function(e){l=e},getEndpoint:function(){return a},setEndpoint:function(e){a=e},send:function(e){u.push(e),u.length>=s&&h.call(this),clearTimeout(d),d=setTimeout(h.bind(this),l)},flush:function(){clearTimeout(d),h.call(this)},getBatchData:function(){return u.length?r(u):``},clear:function(){clearTimeout(d),u=[]},fail:function(e){f=e},success:function(e){p=e}};function h(){if(u.length){var e=this.getBatchData();i.post({url:a,data:e,fail:function(t){f&&f(t,e)},success:function(){p&&p(e)}}),u=[]}}return m}
7
+ `:``}\n## 当前任务\n\n${t}\n`,`utf8`)}async function Q(e,t){await u(_n(e),`[${vn()}] ${t}\n`,`utf8`)}async function*xn(e){let{cwd:t,rootDir:n,task:r,agentId:i,signal:a}=e;try{let o=await gn(t,n);if(o){yield{type:`failed`,phase:`pre-create`,userFacing:!1,error:o};return}let s=new qt,c=e.requestText??r;await bn(t,c.slice(0,200)+(c.length>200?`...`:``)),e.traceId&&await Q(t,`trace_id: ${e.traceId}`),await Q(t,`已接收需求`),yield{type:`progress`,message:`已接收需求`};let l=await Zt(t),u=!l?.appId,d=vn();if(u){let e;try{e=await s.createSubApp({message:r,agentId:i})}catch(e){let n=e instanceof Error?e.message:String(e),r=e instanceof Ut,i=e?.logId;try{await Q(t,`失败: ${n}`)}catch{}yield{type:`failed`,error:n,phase:`create`,userFacing:r,logId:i};return}let{appID:a,conversationID:o,logId:c}=e;l={appId:a,conversationId:o,createdAt:d,updatedAt:d},await $t(t,l,{rootDir:n}),await Q(t,`应用已创建(appId: ${a})`),yield{type:`app_created`,appId:a,conversationId:o,logId:c}}await Q(t,`正在处理`),yield{type:`progress`,message:`正在处理`};let f=!1,p=Date.now(),m=setInterval(()=>{Q(t,`正在开发中(已 ${Math.floor((Date.now()-p)/6e4)} 分钟)`).catch(()=>{})},6e4),h;try{h=await sn({createStream:n=>s.streamChat({appID:l.appId,message:r,workDir:t,channelAppId:e.channelAppId,...n?{lastEventID:n}:{}}),onEvent:e=>{if(a?.aborted)return!1;let n=en(e.data),r=n?.delta?.type;!f&&n?.role===`assistant`&&(n?.status===`in_progress`||r===`text`)&&(f=!0,Q(t,`正在输出结果`).catch(()=>{}));try{if(n?.status===`completed`){let e=un(n);e&&Q(t,e).catch(()=>{})}}catch{}},onReconnect:(t,n)=>{e.onReconnect?.(t,n)},onFailed:t=>{e.onStreamFailed?.(t)},signal:a})}finally{clearInterval(m)}if(!h.success){let e=h.terminalReason??`stream_interrupted`,n=e===`stream_interrupted`;await Q(t,`失败: ${h.error??e}`),yield{type:`failed`,error:h.error||`stream failed`,appId:l.appId,logId:h.logId,lastEventId:h.lastEventId,phase:`stream`,retryable:n,terminalReason:e,sseEventCount:h.totalEvents,reconnectCount:h.reconnectCount,finishReasonRaw:h.finishReasonRaw,errorCodeRaw:h.errorCodeRaw};return}let{finalText:g,logId:_,totalEvents:v,reconnectCount:y,finishReasonRaw:b}=h;if(f&&(yield{type:`progress`,message:`正在输出结果`,logId:_||void 0}),a?.aborted){await Q(t,`失败: cancelled`),yield{type:`failed`,error:`cancelled`,appId:l.appId,phase:`stream`,lastEventId:h.lastEventId,retryable:!0,terminalReason:`stream_interrupted`,sseEventCount:v,reconnectCount:y,finishReasonRaw:b,errorCodeRaw:h.errorCodeRaw};return}let x=vn();await $t(t,{...l,updatedAt:x,finalText:g},{rootDir:n}),g&&await Q(t,`Agent 回复: ${g.slice(0,200)+(g.length>200?`...`:``)}`),await Q(t,`处理完成`),yield{type:`completed`,appId:l.appId,logId:_||void 0,lastEventId:h.lastEventId,finalText:g,terminalReason:`completed`,sseEventCount:v,reconnectCount:y,finishReasonRaw:b}}catch(e){let n=e instanceof Error?e.message:String(e);try{await Q(t,`失败: ${n}`)}catch{}yield{type:`failed`,error:n,logId:e?.logId}}}const Sn=[`research`,`design`,`feedback`];function Cn(e){return e.replace(/[^a-zA-Z0-9\u4e00-\u9fff-]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,60)||`reference`}async function wn(e){let t;try{t=await p(e)}catch{return 1}let n=0;for(let e of t){let t=e.match(/^(\d{3})-/);if(t){let e=parseInt(t[1],10);e>n&&(n=e)}}return n+1}async function Tn(e){try{let t=await f(c(e,`reference`,`manifest.json`),`utf8`);return JSON.parse(t)}catch{return{updatedAt:new Date().toISOString(),files:[]}}}async function En(e,t){await d(c(e,`reference`),{recursive:!0}),await h(c(e,`reference`,`manifest.json`),JSON.stringify(t,null,2),`utf8`)}async function Dn(e){let{appCwd:t,category:n,content:r,filename:i,mode:a=`append`}=e,o=c(t,`reference`,n);if(a===`replace`)try{await m(o,{recursive:!0,force:!0})}catch{}await d(o,{recursive:!0});let s=await wn(o),l=`${n}/${`${String(s).padStart(3,`0`)}-${Cn(i??`reference`)}.md`}`,u=`reference/${l}`;await h(c(t,u),r,`utf8`);let f=await Tn(t);return a===`replace`&&(f.files=f.files.filter(e=>e.category!==n)),f.files.push({path:l,category:n,writtenAt:new Date().toISOString()}),f.updatedAt=new Date().toISOString(),await En(t,f),{relativePath:u,category:n,seq:s}}async function On(e){let t=c(e,`reference`),n;try{n=await p(t)}catch{return{totalFiles:0,categories:{}}}let r={},i=0;for(let e of n){if(!Sn.includes(e))continue;let n;try{n=(await p(c(t,e))).filter(e=>e.endsWith(`.md`)).sort()}catch{continue}n.length>0&&(r[e]={count:n.length,files:n},i+=n.length)}return{totalFiles:i,categories:r}}async function kn(e){return(await On(e)).totalFiles>0}function An(e){let t=e?.log,n=e?.timeoutMs??5e3,r=null,i=null,a=null;return{onSessionStart(e){t?.info?.(`db-schema: session_start sessionId=${e??`unknown`}, clearing cache`),r=null,i=null,a=e??null},async getSchemaSummary(e){return e&&a!==null&&e!==a?(t?.warn?.(`db-schema: session changed without session_start: ${a} -> ${e}, resetting cache`),r=null,i=null,a=e):e&&a===null&&(a=e),r===null?i||(i=(async()=>{t?.info?.(`db-schema: fetching (timeout=${n}ms)`);try{let{stdout:e}=await jn(Mn(),n),i=Nn(e);if(i.length===0)return t?.info?.(`db-schema: empty, skip injection for this session`),r=``,null;let a=Pn(i);return r=a,t?.info?.(`db-schema: cached ${i.length} table(s), ${a.length} chars`),a}catch(e){let n=e instanceof Error?e.message:String(e);return t?.warn?.(`db-schema: fetch failed (will not retry this session): ${n}`),r=``,null}finally{i=null}})(),i):r===``?null:r}}}function jn(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(Error(`timeout after ${t}ms`)),t);e.then(e=>{clearTimeout(i),n(e)},e=>{clearTimeout(i),r(e)})})}function Mn(){return new Promise((e,n)=>{t(`npx`,[`-y`,`@lark-apaas/miaoda-data-cli`,`db`,`schema`,`--json`],{timeout:3e4,maxBuffer:10*1024*1024},(t,r,i)=>{if(t)return n(Error(`execFile failed: ${t.message} | stderr: ${i?.slice(0,500)??``} | stdout: ${r?.slice(0,500)??``}`));e({stdout:r,stderr:i})})})}function Nn(e){let t=e.trim();if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n:n&&typeof n==`object`&&n.tableName?[n]:[]}function Pn(e){return`【当前数据库表结构】\n${e.map(e=>{let t=e.fields.map(e=>`${e.fieldName}(${e.type})`).join(`, `),n=e.comment?` (${e.comment})`:``;return`- ${e.tableName}${n}: ${t}`}).join(`
8
+ `)}`}function Fn(){return`dev`}var In=H(B((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=10,n=1e3,r=function(e){return JSON.stringify({ev_type:`batch`,list:e})};function i(e){var i=e.transport,a=e.endpoint,o=e.size,s=o===void 0?t:o,c=e.wait,l=c===void 0?n:c,u=[],d=0,f,p,m={getSize:function(){return s},getWait:function(){return l},setSize:function(e){s=e},setWait:function(e){l=e},getEndpoint:function(){return a},setEndpoint:function(e){a=e},send:function(e){u.push(e),u.length>=s&&h.call(this),clearTimeout(d),d=setTimeout(h.bind(this),l)},flush:function(){clearTimeout(d),h.call(this)},getBatchData:function(){return u.length?r(u):``},clear:function(){clearTimeout(d),u=[]},fail:function(e){f=e},success:function(e){p=e}};function h(){if(u.length){var e=this.getBatchData();i.post({url:a,data:e,fail:function(t){f&&f(t,e)},success:function(){p&&p(e)}}),u=[]}}return m}
9
9
  /*! *****************************************************************************
10
10
  Copyright (c) Microsoft Corporation.
11
11
 
@@ -20,7 +20,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
20
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
21
  PERFORMANCE OF THIS SOFTWARE.
22
22
  ***************************************************************************** */
23
- var a=function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},a.apply(this,arguments)};function o(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function s(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function c(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var l=function(){return{}};function u(e){return e}function d(e){return typeof e==`object`&&!!e}var f=Object.prototype;function p(e){return f.toString.call(e)===`[object Array]`}function m(e){return typeof e==`boolean`}function h(e){return typeof e==`number`}function g(e){return typeof e==`string`}function _(e,t){if(!p(e)||e.length===0)return!1;for(var n=0;n<e.length;){if(e[n]===t)return!0;n++}return!1}var v=function(e,t){if(!p(e))return e;var n=e.indexOf(t);if(n>=0){var r=e.slice();return r.splice(n,1),r}return e},y=function(e,t,n){for(var r,i,a=s(t.split(`.`)),o=a[0],c=a.slice(1);e&&c.length>0;)e=e[o],r=c,i=s(r),o=i[0],c=i.slice(1);if(e)return n(e,o)};function b(e){try{return g(e)?e:JSON.stringify(e)}catch(e){return`[FAILED_TO_STRINGIFY]:`+String(e)}}function x(){var e={},t={},n={set:function(r,i){return e[r]=i,t[r]=b(i),n},merge:function(r){return e=a(a({},e),r),Object.keys(r).forEach(function(e){t[e]=b(r[e])}),n},delete:function(r){return delete e[r],delete t[r],n},clear:function(){return e={},t={},n},get:function(e){return t[e]},toString:function(){return a({},t)}};return n}var S=function(){return``.padStart?function(e,t){return t===void 0&&(t=8),e.padStart(t,` `)}:function(e){return e}}(),C=0,w=function(){var e=[...arguments];console.error.apply(console,c([`[SDK]`,Date.now(),S(``+ C++)],s(e),!1))},T=0,E=function(){var e=[...arguments];console.warn.apply(console,c([`[SDK]`,Date.now(),S(``+ T++)],s(e),!1))},D=function(e){return Math.random()<Number(e)},O=function(e,t){return e<Number(t)},k=function(e){return function(t){for(var n=t,r=0;r<e.length&&n;r++)try{n=e[r](n)}catch(e){w(e)}return n}};function A(){for(var e=Array(16),t=0,n=0;n<16;n++)n&3||(t=Math.random()*4294967296),e[n]=t>>>((n&3)<<3)&255;return e}function j(e){for(var t=[],n=0;n<256;++n)t[n]=(n+256).toString(16).substr(1);var r=0,i=t;return[i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]]].join(``)}function M(){var e=A();return e[6]=e[6]&15|64,e[8]=e[8]&63|128,j(e)}function N(){var e=!1,t={},n=function(e){e.length&&e.forEach(function(e){try{e()}catch{}}),e.length=0},r=function(e){t[e]&&t[e].forEach(function(e){n(e[1])}),t[e]=void 0};return{set:function(r,i,a){t[r]?t[r].push([i,a]):t[r]=[[i,a]],e&&n(a)},has:function(e){return!!t[e]},remove:r,removeByEvType:function(e){Object.keys(t).forEach(function(r){t[r]&&t[r].forEach(function(t){t[0]===e&&n(t[1])})})},clear:function(){e=!0,Object.keys(t).forEach(function(e){r(e)})}}}var ee=500,P=50;function F(e,t,n){if(t.push(n),!(t.length<ee)){var r=t.splice(0,P);e.savePreStartDataToDb&&e.savePreStartDataToDb(r)}}function I(e){var t=e.getPreStartQueue();t.forEach(function(t){return e.build(t)}),t.length=0}var L=[`init`,`start`,`config`,`beforeDestroy`,`provide`,`beforeReport`,`report`,`beforeBuild`,`build`,`beforeSend`,`send`,`beforeConfig`];function R(e){var t=e.builder,n=e.createSender,r=e.createDefaultConfig,i=e.createConfigManager,a=e.userConfigNormalizer,o=e.initConfigNormalizer,l=e.validateInitConfig,u,f,p={};L.forEach(function(e){return p[e]=[]});var m=!1,h=!1,g=!1,y=[],b=[],x=N(),S={getBuilder:function(){return t},getSender:function(){return u},getPreStartQueue:function(){return y},init:function(e){if(m){E(`already inited`);return}if(e&&d(e)&&l(e)){var t=r(e);if(!t)throw Error(`defaultConfig missing`);var a=o(e);if(f=i(t),f.setConfig(a),f.onChange(function(){C(`config`)}),u=n(f.getConfig()),!u)throw Error(`sender missing`);m=!0,C(`init`,!0)}else throw Error(`invalid InitConfig, init failed`)},set:function(e){m&&e&&d(e)&&(C(`beforeConfig`,!1,e),f?.setConfig(e))},config:function(e){if(m)return e&&d(e)&&(C(`beforeConfig`,!1,e),f?.setConfig(a(e))),f?.getConfig()},provide:function(e,t){if(_(b,e)){E(`cannot provide `+e+`, reserved`);return}S[e]=t,C(`provide`,!1,e)},start:function(){m&&(h||f?.onReady(function(){h=!0,C(`start`,!0),I(S)}))},report:function(e){if(e){var t=k(p.beforeReport)(e);if(t){var n=k(p.report)(t);n&&(h?this.build(n):F(S,y,n))}}},build:function(e){if(h){var n=k(p.beforeBuild)(e);if(n){var r=t.build(n);if(r){var i=k(p.build)(r);i&&this.send(i)}}}},send:function(e){if(h){var t=k(p.beforeSend)(e);t&&(u.send(t),C(`send`,!1,t))}},destroy:function(){x.clear(),g=!0,y.length=0,C(`beforeDestroy`,!0)},on:function(e,t){if(e===`init`&&m||e===`start`&&h||e===`beforeDestroy`&&g)try{t()}catch{}else p[e]&&p[e].push(t)},off:function(e,t){p[e]&&(p[e]=v(p[e],t))},destroyAgent:x};return b=Object.keys(S),S;function C(e,t){t===void 0&&(t=!1);var n=[...arguments].slice(2);p[e].forEach(function(e){try{e.apply(void 0,c([],s(n),!1))}catch{}}),t&&(p[e].length=0)}}var z=function(e){var t=x();e.provide(`context`,t),e.on(`report`,function(e){return e.extra||={},e.extra.context=t.toString(),e})};function B(e,t){e.on(`init`,function(){var n=[],r=function(r){r.forEach(function(r){var i=r.name;_(n,i)||(n.push(i),r.setup(e),t&&t(i,r.setup),e.destroyAgent.set(i,i,[function(){n=v(n,i),r.tearDown&&r.tearDown()}]))})};e.provide(`applyIntegrations`,r);var i=e.config();i&&i.integrations&&r(i.integrations)})}var V=function(e){try{typeof window==`object`&&d(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch{}},H=function(){return Date.now()};function U(){if(typeof window==`object`&&d(window))return window}var W=function(e){if(e)return e.__SLARDAR_REGISTRY__||={Slardar:{plugins:[],errors:[],subject:{}}},e.__SLARDAR_REGISTRY__.Slardar},G=function(){var e=[...arguments],t=W(U());t&&(t.errors||=[],t.errors.push(e))},K=function(e){var t;if(!(typeof window!=`object`||!window.__perfsee__)){var n={};return(t=Error.captureStackTrace)==null||t.call(Error,n,e),n.stack}},q=`custom`,J=`event`,Y=`log`,X=function(e){if(!(!e||!d(e))&&!(!e.name||!g(e.name))){var t={name:e.name,type:J};if(`metrics`in e&&d(e.metrics)){var n=e.metrics,r={};for(var i in n)h(n[i])&&(r[i]=n[i]);t.metrics=r}if(`categories`in e&&d(e.categories)){var a=e.categories,o={};for(var i in a)o[i]=b(a[i]);t.categories=o}return`attached_log`in e&&g(e.attached_log)&&(t.attached_log=e.attached_log),t}},Z=function(e){if(!(!e||!d(e))&&!(!e.content||!g(e.content))){var t=e.content,n={content:b(t),type:Y,level:`info`};if(`level`in e&&(n.level=e.level),`extra`in e&&d(e.extra)){var r=e.extra,i={},a={};for(var o in r)h(r[o])?i[o]=r[o]:a[o]=b(r[o]);n.metrics=i,n.categories=a}return`attached_log`in e&&g(e.attached_log)&&(n.attached_log=e.attached_log),n}},te=function(e){var t=function(n){var r=X(n);if(r){var i=K(t);i&&(r.stacks=i),e.report({ev_type:q,payload:r,extra:{timestamp:H()}})}};e.provide(`sendEvent`,t),e.provide(`sendLog`,function(t){var n=Z(t);n&&e.report({ev_type:q,payload:n,extra:{timestamp:H()}})})},ne=function(e,t){var n=e.common||{};return n.sample_rate=t,e.common=n,e},re=function(e,t,n,r,i){return e?(function(e){return function(){return e}})(i(r,t)):function(){return n(t)}},ie=function(e,t){return e.map(function(e){switch(t){case`number`:return Number(e);case`boolean`:return e===`1`;default:return String(e)}})},ae=function(e,t,n){switch(n){case`eq`:return _(t,e);case`neq`:return!_(t,e);case`gt`:return e>t[0];case`gte`:return e>=t[0];case`lt`:return e<t[0];case`lte`:return e<=t[0];case`regex`:return!!e.match(new RegExp(t.join(`|`)));case`not_regex`:return!e.match(new RegExp(t.join(`|`)));default:return!1}},oe=function(e,t,n,r){var i=y(e,t,function(e,t){return e[t]});return i===void 0?!1:ae(i,ie(r,m(i)?`bool`:h(i)?`number`:`string`),n)},se=function(e,t){try{return t.type===`rule`?oe(e,t.field,t.op,t.values):t.type===`and`?t.children.every(function(t){return se(e,t)}):t.children.some(function(t){return se(e,t)})}catch(e){return G(e),!1}},ce=function(e,t,n,r,i,a){var o={};return Object.keys(e).forEach(function(s){var c=e[s],l=c.enable,u=c.sample_rate,d=c.conditional_sample_rules;l?(o[s]={enable:l,sample_rate:u,effectiveSampleRate:u*n,hit:re(t,u,r,i,a)},d&&(o[s].conditional_hit_rules=d.map(function(e){var o=e.sample_rate,s=e.filter;return{sample_rate:o,hit:re(t,o,r,i,a),effectiveSampleRate:o*n,filter:s}}))):o[s]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}}),o},le=function(e,t,n,r,i){if(!t)return u;var a=t.sample_rate,o=t.include_users,s=t.sample_granularity,c=t.rules,l=t.r,d=l===void 0?Math.random():l;if(_(o,e))return function(e){return ne(e,1)};var f=s===`session`,p=re(f,a,n,d,r),m=ce(c,f,a,n,d,r);return function(e){if(!p())return f&&i[0](),!1;if(!(e.ev_type in m))return ne(e,a);if(!m[e.ev_type].enable)return f&&i[1](e.ev_type),!1;if(e.common?.sample_rate)return e;var t=m[e.ev_type],n=t.conditional_hit_rules;if(n){for(var r=0;r<n.length;r++)if(se(e,n[r].filter))return n[r].hit()?ne(e,n[r].effectiveSampleRate):!1}return t.hit()?ne(e,t.effectiveSampleRate):(!(n&&n.length)&&f&&i[1](e.ev_type),!1)}},ue=function(e){e.on(`start`,function(){var t=e.config(),n=t.userId,r=t.sample,i=le(n,r,D,O,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on(`build`,i)})},de={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:a(a({},e.extra||{}),e.overrides||{})}}},fe=`mon.zijieapi.com`,pe=fe,me=`2.1.8`,he=`SDK_BASE`,ge=`/monitor_web/settings/browser-settings`,_e=`/monitor_browser/collect/batch/`,ve={sample_rate:1,include_users:[],sample_granularity:`session`,rules:{}},ye=20,be=`session`;function xe(e){var t,n,r=[`userId`,`deviceId`,`sessionId`,`env`];try{for(var i=o(r),a=i.next();!a.done;a=i.next()){var s=a.value;e[s]||delete e[s]}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return e}function Se(e){return xe(a({},e))}function Ce(e){return d(e)&&`bid`in e&&`transport`in e}function we(e){return xe(a({},e))}function Te(e){if(!e)return{};var t=e.sample,n=e.timestamp,r=e.quota_rate,i=r===void 0?1:r;if(!t)return{};var a=t.sample_rate,o=t.sample_granularity,s=o===void 0?be:o,c=t.include_users,l=t.rules,u=l===void 0?[]:l;return{sample:{include_users:c,sample_rate:a*i,sample_granularity:s,rules:u.reduce(function(e,t){var n=t.name;return e[n]={enable:t.enable,sample_rate:t.sample_rate,conditional_sample_rules:t.conditional_sample_rules},e},{})},serverTimestamp:n}}var Ee=function(e,t){return t===void 0&&(t=_e),(e&&e.indexOf(`//`)>=0?``:`https://`)+e+t},De=function(e,t){return t===void 0&&(t=ge),(e&&e.indexOf(`//`)>=0?``:`https://`)+e+t},Oe=function(){return M()},ke=function(){return M()},Ae=function(e){return e+`_`+Date.now()},je=function(){return M()},Me=function(e){var t=e,n,r={},i,o,s=l,c=l;return{getConfig:function(){return t},setConfig:function(e){return r=a(a({},r),e||{}),u(),n||(n=e,t.useLocalConfig||!t.bid?(o={},s()):Ne(t.transport,t.domain,t.bid,function(e){i=e,d()})),t},onChange:function(e){c=e},onReady:function(e){s=e,o&&s()}};function u(){var n=a(a(a({},e),o||{}),r);n.sample=Pe(Pe(e.sample,o?.sample),r.sample),t=n,c()}function d(){o=Te(i),u(),s()}};function Ne(e,t,n,r){if(!e.get)return r({});e.get({withCredentials:!0,url:De(t)+`?bid=`+n+`&store=1`,success:function(e){r(e.data||{})},fail:function(){r({sample:{sample_rate:.001}})}})}function Pe(e,t){if(!e||!t)return e||t;var n=a(a({},e),t);return n.include_users=c(c([],s(e.include_users||[]),!1),s(t.include_users||[]),!1),n.rules=c(c([],s(Object.keys(e.rules||{})),!1),s(Object.keys(t.rules||{})),!1).reduce(function(n,r){return r in n||(r in(e.rules||{})&&r in(t.rules||{})?(n[r]=a(a({},e.rules[r]),t.rules[r]),n[r].conditional_sample_rules=c(c([],s(e.rules[r].conditional_sample_rules||[]),!1),s(t.rules[r].conditional_sample_rules||[]),!1)):n[r]=e.rules?.[r]||t.rules?.[r]),n},{}),n}var Fe=function(e,t){var n=t||{},r=n.version,i=n.name,o={url:``,protocol:``,domain:``,path:``,query:``,timestamp:Date.now(),sdk_version:r||me,sdk_name:i||he};return a(a({},e),{extra:a(a({},o),e.extra||{})})},Ie=function(e){e.on(`report`,function(t){return Fe(t,e.config())})},Le=function(e,t){var n={};return n.bid=t.bid,n.pid=t.pid,n.view_id=t.viewId,n.user_id=t.userId,n.device_id=t.deviceId,n.session_id=t.sessionId,n.release=t.release,n.env=t.env,a(a({},e),{extra:a(a({},n),e.extra||{})})},Re=function(e){e.on(`beforeBuild`,function(t){return Le(t,e.config())})};function ze(e){return i(e)}var Be=function(e){return{bid:``,pid:``,viewId:Ae(`_`),userId:Oe(),deviceId:ke(),sessionId:je(),domain:fe,release:``,env:`production`,sample:ve,plugins:{},transport:{get:l,post:l},useLocalConfig:!1}},Ve=function(e){var t=e===void 0?{}:e,n=t.createSender,r=n===void 0?function(e){return ze({size:ye,endpoint:Ee(e.domain),transport:e.transport})}:n,i=t.builder,a=i===void 0?de:i,o=t.createDefaultConfig,s=R({validateInitConfig:Ce,initConfigNormalizer:Se,userConfigNormalizer:we,createSender:r,builder:a,createDefaultConfig:o===void 0?Be:o,createConfigManager:Me});return z(s),Re(s),Ie(s),B(s),V(s),s},He=function(e){e===void 0&&(e={});var t=Ve(e);return ue(t),te(t),t},Ue=He();e.BATCH_REPORT_PATH=_e,e.CustomPlugin=te,e.DEFAULT_SAMPLE_CONFIG=ve,e.DEFAULT_SAMPLE_GRANULARITY=be,e.DEFAULT_SENDER_SIZE=ye,e.InjectConfigPlugin=Re,e.InjectEnvPlugin=Ie,e.REPORT_DOMAIN=fe,e.SDK_NAME=he,e.SDK_VERSION=me,e.SETTINGS_DOMAIN=pe,e.SETTINGS_PATH=ge,e.addConfigToReportEvent=Le,e.addEnvToSendEvent=Fe,e.builder=de,e.createBaseClient=He,e.createConfigManager=Me,e.createMinimalClient=Ve,e.default=Ue,e.getDefaultConfig=Be,e.getDefaultDeviceId=ke,e.getDefaultSessionId=je,e.getDefaultUserId=Oe,e.getReportUrl=Ee,e.getServerConfig=Ne,e.getSettingsUrl=De,e.getViewId=Ae,e.mergeSampleConfig=Pe,e.normalizeInitConfig=Se,e.normalizeStrictFields=xe,e.normalizeUserConfig=we,e.parseServerConfig=Te,e.validateInitConfig=Ce}))(),1);function kn(e){return!e||typeof e!=`object`||!(`default`in e)?e:e.default}function An(e){let t=kn(e);return kn(t)??t??e??{}}const jn=An(On.default);let Mn=!1;function Nn(){if(!Mn)try{let e=Lt();jn.init({bid:`apaas_miaoda`,release:String(e.version??`unknown`),env:Dn(),transport:{get:({url:e,success:t,fail:n})=>fetch(e).then(e=>e.json()).then(e=>t?.(e)).catch(e=>n?.(e)),post:({url:e,data:t})=>{let n=typeof t==`string`?t:JSON.stringify(t);return fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:n}).catch(()=>{})}}}),jn.start(),Mn=!0}catch{}}function Pn(e){if(e!==void 0)return String(e)}function Fn(e){let t={source:`node-plugin`},n=e.traceId,r=e.projectId,i=Pn(e.isNew),a=e.appId,o=e.agentId,s=e.sessionKey;return n&&(t.trace_id=n),r&&(t.project_id=r),i&&(t.is_new=i),a&&(t.app_id=a),o&&(t.agent_id=o),e.domain&&(t.domain=e.domain),s&&(t.session_key=s),t}function In(e,t){let n={...e};for(let[e,r]of Object.entries(t??{}))r!=null&&(n[e]=typeof r==`boolean`?String(r):r);return n}function Ln(e){try{let t={},n=Fn(e),r=e.durationMs,i=e.sseEventCount,a=e.reconnectCount,o=e.createDurationMs;typeof r==`number`&&(t.duration_ms=r),typeof i==`number`&&(t.sse_event_count=i),typeof a==`number`&&(t.reconnect_count=a),typeof o==`number`&&(t.create_duration_ms=o);let s={...n,status:e.status,is_new:n.is_new??`false`},c=e.errorType;e.phase&&(s.phase=e.phase),c&&(s.error_type=c.slice(0,100)),jn.sendEvent?.({name:`miaoda_coding_task`,metrics:t,categories:s})}catch{}}function Rn(e){try{let t={},n=Fn(e);typeof e.durationMs==`number`&&(t.duration_ms=e.durationMs);let r={...n,request_name:e.requestName,status:e.status};e.logId&&(r.log_id=e.logId),e.phase&&(r.phase=e.phase),e.errorType&&(r.error_type=e.errorType.slice(0,100)),jn.sendEvent?.({name:`miaoda_coding_request`,metrics:t,categories:r})}catch{}}function zn(e){try{if(!e.projectId)return;let t=In(Fn(e),{event:e.event,phase:e.phase}),n=e.logIds;n?.length&&(t.log_ids=n.join(`,`)),jn.sendLog?.({content:e.error,level:`error`,extra:t})}catch{}}function $(e){try{let t=In(Fn(e),{event:e.event,phase:e.phase,status:e.status,...e.extra});jn.sendLog?.({content:e.message,level:e.level??`info`,extra:t})}catch{}}const Bn=/^[a-z0-9][a-z0-9-]{0,63}$/,Vn=new Set([`.`,`..`,`con`,`nul`,`prn`,`aux`]);function Hn(e){let t=e?.config?.plugins?.entries?.[`openclaw-extension-miaoda-coding`]?.config??{};return{verbose:t?.verbose===!0,hooks:{allowPromptInjection:t?.hooks?.allowPromptInjection!==!1}}}function Un(e,t){if(!e)return;let r=o.dirname(process.execPath),i=n(`openclaw`,[`message`,`send`,`--channel`,`feishu`,`--target`,e,`--message`,t],{stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,PATH:`${r}:${process.env.PATH||``}`}});i.stderr.on(`data`,()=>{}),i.on(`close`,()=>{}),i.unref()}function Wn(e){return String(e??``).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,``).replace(/\s+/g,` `).trim()}function Gn(e){let t=String(e??``).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,``).trim();if(!t)throw Error(`task 不能为空`);if(t.length>4e3)throw Error(`task 不能超过 4000 个字符`);return t}function Kn(e){let t=Wn(e);if(!qn(t))throw Error(`project_id 不合法: "${t}"`);return t}function qn(e){return Bn.test(e)&&!Vn.has(e)}function Jn(e){if(e==null||e===``)return;let t=Wn(e);if(t!==`none`){if(!/^(user|chat|thread):\S+$/.test(t))throw Error(`target 不合法`);return t}}function Yn(e,t){let n=G(e,t);if(i.existsSync(n))return n;let r=K(e,t);return i.existsSync(r)?r:n}function Xn(e){let t=new Map,n=o.join(e,`app`);try{for(let e of i.readdirSync(n,{withFileTypes:!0}))!e.isDirectory()||!qn(e.name)||t.set(e.name,o.join(n,e.name))}catch{}try{for(let n of i.readdirSync(e,{withFileTypes:!0}))!n.isDirectory()||n.name===`app`||!qn(n.name)||t.has(n.name)||t.set(n.name,o.join(e,n.name))}catch{}return[...t.entries()].map(([e,t])=>({projectId:e,appCwd:t}))}function Zn(e){try{return i.readFileSync(e,`utf8`).split(`
24
- `).map(e=>e.trim()).filter(Boolean)}catch{return[]}}function Qn(e){return e.replace(/^\[[^\]]+\]\s*/,``)}function $n(e){return e.replace(/应用已创建(appId:\s*[^)]+)/g,`应用已创建`)}function er(e){return e.slice(-3).map(Qn).map($n).join(` | `)||`暂无进度记录`}function tr(e){let t=er(e);return t.includes(`失败:`)?`failed`:t.includes(`处理完成`)?`completed`:t===`暂无进度记录`?`pending`:`running`}function nr(e){try{let t=JSON.parse(i.readFileSync(o.join(e,`.spark`,`meta.json`),`utf8`));return typeof t?.appId==`string`&&t.appId.trim().length>0}catch{return!1}}var rr={id:`openclaw-extension-miaoda-coding`,name:`妙搭`,description:`妙搭制品创建与修改`,register(e){let t=`[miaoda-coding]`,n={info:n=>e.logger.info?.(`${t} ${n}`),warn:n=>e.logger.warn?.(`${t} ${n}`),error:n=>e.logger.error?.(`${t} ${n}`)},a={verbose:!1,hooks:{allowPromptInjection:!0}},s=Sn({log:n});n.info(`plugin registered`),Nn(),e.on(`session_start`,(e,t)=>{try{s.onSessionStart(e?.sessionId)}catch(e){n.warn(`session_start reset failed: ${String(e)}`)}});let c=new Set([`miaoda_coding`]),l=new Set([`miaoda_check_progress`]);e.on(`before_tool_call`,(e,t)=>{let r=e.toolName,i=t?.sessionKey??``,a=i.toLowerCase().split(`:`).includes(`subagent`);if(c.has(r)&&!a)return n.warn(`blocked ${r} from non-subagent session: ${i}`),{block:!0,blockReason:`${r} 只能由 subagent 调用。请通过 sessions_spawn(runtime="subagent", mode="run") 派活,不要直接调用此工具。读 miaoda-coding skill 了解完整流程。`};if(l.has(r)&&a)return n.warn(`blocked ${r} from subagent session: ${i}`),{block:!0,blockReason:`${r} 不能由 subagent 调用。subagent 不应直接操作参考资料或查询进度。`}}),e.on(`before_prompt_build`,async(e,t)=>{if(!Hn(t).hooks.allowPromptInjection)return;let r={prependSystemContext:[`【硬规则 — 妙搭】`,`当用户要求创建或修改应用、网页、页面时,必须通过 sessions_spawn(runtime="subagent", mode="run") 交给妙搭。`,`读 miaoda-coding skill 后严格按指示操作。只传 runtime、mode、task 三个参数,不要传 streamTo/sandbox 等。`,`如果需求在支持范围内并且已经派活给 subagent,最终回复可以是正常交付文案:一条简短总结,外加预览链接;不要把”不适用场景”的主站引导规则误用到正常交付场景。`,`绝对不要自己写代码或用 exec 生成文件。如果 sessions_spawn 调用本身返回错误,去掉多余参数后重试。如果 subagent 执行失败需要重试,generation_request 填"继续"(不要重复发完整需求),详见 skill 中的重试流程。`,`如果对话中有需要传递给 code agent 的上下文(研究结果、用户偏好等),先调 miaoda_write_reference 写入 reference 目录,再 spawn。用户反悔或需要替换之前的上下文时,使用 miaoda_write_reference 的 mode=replace。妙搭只做制品生成,不做研究。`,`不要用 sessions_history 读取子 agent 的 session,查进度用 miaoda_check_progress tool(仅限建应用场景,数据库操作等不要用)。`,`subagent 完成后只发一条消息,严禁发多条。不要调 message tool。如果 result hint 说预览链接已自动发送,则只发纯文字总结,不要再带任何链接;否则附上预览链接,格式用加粗 Markdown 链接 **[url](url)**,不要发裸 URL。`].join(` `)};try{let e=await s.getSchemaSummary(t?.sessionId);e&&(r.appendSystemContext=e)}catch(e){n.error(`db schema injection threw unexpected error: ${String(e)}`)}return r}),e.registerTool(e=>{let t=q(e);return{name:`list_projects`,label:`列出妙搭项目`,description:`列出已创建的妙搭项目,返回 project_id、appId、updatedAt、finalText、status 和进度摘要。修改已有项目时必须先调此工具。`,parameters:{type:`object`,properties:{}},async execute(){let e=[];try{e=Xn(t.workspaceDir).map(({projectId:e,appCwd:t})=>{let n=o.join(t,`.spark`,`meta.json`),r=o.join(t,`.spark`,`progress.txt`),a=null;try{a=JSON.parse(i.readFileSync(n,`utf8`))}catch{}let s=Zn(r);return{project_id:e,appId:a?.appId??null,updatedAt:a?.updatedAt??null,finalText:a?.finalText??null,status:tr(s),progressSummary:er(s)}})}catch{}return{content:[{type:`text`,text:JSON.stringify({projects:e},null,2)}]}}}}),e.registerTool(e=>{let t=q(e);return{name:`miaoda_check_progress`,label:`查看妙搭应用生成进度`,description:`查看通过 miaoda_coding 创建的应用的生成进度。仅用于 sessions_spawn 派活建应用后查看进度,不适用于数据库操作等其他场景。`,parameters:{type:`object`,properties:{project_id:{type:`string`,description:`项目目录名(从 list_projects 获取)`}},required:[`project_id`]},async execute(e,n){try{let e=Kn(n.project_id),r=Yn(t.workspaceDir,e),a=o.join(r,`.spark`,`progress.txt`),s=i.readFileSync(a,`utf8`).trim().split(`
25
- `).filter(Boolean),c=null;try{c=JSON.parse(i.readFileSync(o.join(r,`.spark`,`meta.json`),`utf8`))}catch{}let l=!!c?.finalText,u=s.slice(-20).map($n).join(`
26
- `);return{content:[{type:`text`,text:JSON.stringify({status:`ok`,project_id:e,lines:s.length,progress:u,delivery_ready:l,finalTextAvailable:l,note:`miaoda_check_progress 只用于查看进度,不能根据 appId 或进度文本推导预览链接;最终链接只以 subagent completion result 中的 output/finalText 为准。`})}]}}catch{return{content:[{type:`text`,text:JSON.stringify({status:`no_progress`,project_id:n.project_id,message:`暂无进度记录`,delivery_ready:!1,finalTextAvailable:!1,note:`miaoda_check_progress 只用于查看进度,不能根据 appId 或进度文本推导预览链接;最终链接只以 subagent completion result 中的 output/finalText 为准。`})}]}}}}}),e.registerTool(e=>{let t=q(e);return{name:`miaoda_write_reference`,label:`写入妙搭参考资料`,description:`将参考资料写入妙搭项目的 reference 目录,供 code agent 在生成时自行查阅。按 category 分类写入。mode=append(默认)追加,mode=replace 替换该 category 全部内容(用于反悔/调整场景)。`,parameters:{type:`object`,properties:{project_id:{type:`string`,description:`项目目录名`},category:{type:`string`,enum:[`research`,`design`,`feedback`],description:`资料类别:research(调研结果)、design(设计要求)、feedback(用户反馈)`},content:{type:`string`,description:`参考资料内容(Markdown 格式,摘要+关键原文引用)`},filename:{type:`string`,description:`可选文件名(不含扩展名)`},mode:{type:`string`,enum:[`append`,`replace`],description:`写入模式:append(追加,默认)、replace(替换该 category 全部内容)`}},required:[`project_id`,`category`,`content`]},async execute(e,n){try{let e=Kn(n.project_id);if(!mn.includes(n.category))throw Error(`category 不合法,必须是 ${mn.join(`、`)} 之一`);let r=n.content?.trim();if(!r)throw Error(`content 不能为空`);if(r.length>5e4)throw Error(`content 不能超过 50000 个字符`);let i=n.mode===`replace`?`replace`:`append`,a=Yn(t.workspaceDir,e),o=await yn({appCwd:a,category:n.category,content:r,filename:n.filename,mode:i}),s=await bn(a);return{content:[{type:`text`,text:JSON.stringify({status:`ok`,...o,summary:s},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({status:`error`,error:e instanceof Error?e.message:String(e)})}]}}}}});let u=900*1e3;e.registerTool(e=>{let t=q(e),s=e.config?.channels?.feishu,c=e.agentAccountId,l=(c?s?.accounts?.[c]:void 0)?.appId??s?.appId;return n.info(`channelAppId resolved: ${l??`(none)`} (accountId=${c??`(none)`})`),{name:`miaoda_coding`,label:`妙搭`,description:`创建或修改妙搭应用/网页。只接受生成指令,不接受搜索/调研等任务。如有参考资料,应事先通过 miaoda_write_reference 写入 reference 目录。修改已有项目时必须先调 list_projects 获取 project_id。返回结构化 JSON(status/appId/finalText/output/meta)。`,parameters:{type:`object`,properties:{generation_request:{type:`string`,description:`生成指令(如'做一个学习网站,包含章节、题库、测验')`},project_id:{type:`string`,description:`本地项目目录名,仅允许小写字母、数字和短横线`},target:{type:`string`,description:`飞书消息推送目标:单聊用 user:ou_xxx,群聊用 chat:oc_xxx,非飞书渠道传 none`}},required:[`generation_request`,`project_id`,`target`]},async execute(s,c){let d=r();try{let r=Date.now(),s=Gn(c.generation_request),f=Kn(c.project_id),p=Jn(c.target),m=process.env.FORCE_AUTHN_INNERAPI_DOMAIN,h=Yn(t.workspaceDir,f);i.mkdirSync(h,{recursive:!0});let g=!nr(h),_={traceId:d,projectId:f,isNew:g,agentId:t.agentId,domain:m,sessionKey:e?.sessionKey};n.info(`miaoda_coding called (project=${f}, isNew=${g}, traceId=${d})`),$({..._,event:`start`,message:`miaoda_coding started for ${f}`,extra:{target:p??`none`}}),g&&$({..._,event:`create_start`,message:`createSubApp started for ${f}`});let v=await xn(h)?`工作目录下有 reference/ 目录,包含参考资料,请先查阅再开始工作。\n\n${s}`:s,y=o.join(h,`.agent`);if(!i.existsSync(y)){let e=W(U());if(i.existsSync(e))try{i.symlinkSync(e,y)}catch{}}let b=[],x,S=!1,C=!1,w=null,T=g?Date.now():void 0,E=g?void 0:Date.now(),D=new AbortController,O=setTimeout(()=>D.abort(),u);try{for await(let e of pn({cwd:h,rootDir:U(),task:v,requestText:s,traceId:d,agentId:t.agentId,channelAppId:l,signal:D.signal,onReconnect:(e,t)=>{n.warn(`stream reconnect (project=${f}, attempt=${e}, lastEventId=${t??`none`}, traceId=${d})`),$({..._,event:`stream_reconnect`,message:`stream reconnect for ${f}`,level:`warn`,extra:{attempt:e,last_event_id:t??`none`}})},onStreamFailed:e=>{n.error(`stream failed (project=${f}, traceId=${d}): ${e}`),$({..._,event:`stream_failed`,message:String(e),level:`error`})}})){if(`logId`in e&&e.logId&&b.push(e.logId),a.verbose&&p)switch(e.type){case`app_created`:Un(p,`应用已创建(appId: ${e.appId})`);break;case`failed`:Un(p,`处理失败: ${e.error}`);break}if(e.type===`completed`&&(w={appId:e.appId,finalText:e.finalText},Rn({..._,requestName:`stream_chat`,status:`ok`,appId:e.appId,logId:e.logId,phase:`stream`,durationMs:E?Date.now()-E:void 0}),$({..._,event:`stream_completed`,message:`streamChat completed for ${f}`,appId:e.appId,extra:{log_id:e.logId??`none`}})),e.type===`app_created`&&(Rn({..._,requestName:`create_sub_app`,status:`ok`,appId:e.appId,logId:e.logId,phase:`create`,durationMs:T?Date.now()-T:void 0}),E=Date.now(),$({..._,event:`create_succeeded`,message:`createSubApp completed for ${f}`,appId:e.appId,extra:{log_id:e.logId,conversation_id:e.conversationId??`none`}})),e.type===`failed`){if(x=e.error,S=e.retryable??!1,e.phase===`pre-create`){n.error(`pre-create validation failed (project=${f}): ${e.error}`),clearTimeout(O),Ln({..._,status:`error`,phase:`pre-create`,appId:null,durationMs:Date.now()-r}),$({..._,event:`pre_create_validation_failed`,message:e.error,level:`error`,phase:`pre-create`});let t={status:`error`,project_id:f,appId:null,error:e.error,meta:null,hint:`这是运行环境配置问题,不是用户操作失误。直接将 error 字段内容告知用户,并说明需要联系管理员修复配置;不要建议换 project_id,不要重试`};return{content:[{type:`text`,text:JSON.stringify(t)}]}}if(e.phase===`create`){n.error(`createSubApp failed (project=${f}, traceId=${d}): ${e.error}`);let t=!!p;if(p){let t=e.userFacing?e.error:`createSubApp 失败: ${e.error}`;n.info(`delivering create error via feishu (project=${f}, target=${p}, traceId=${d})`),Un(p,t)}else n.warn(`create failed but no target for feishu delivery (project=${f}, traceId=${d})`);let i=e.userFacing?{status:`error`,project_id:f,appId:null,meta:null,logIds:b.length?b:void 0,hint:t?`创建失败,详情已通过飞书发送给用户,不要重复发送错误内容`:`创建失败,将 error 字段的内容原样发送给用户,不要改写、不要删减、不要重试`,error:t?void 0:e.error}:{status:`error`,project_id:f,appId:null,error:e.error,meta:null,logIds:b.length?b:void 0,hint:t?`createSubApp 失败,错误已通过飞书发送。根据 error 内容用通俗语言告诉用户具体原因,不要重试`:`createSubApp 失败,根据 error 内容用通俗语言告诉用户具体原因,不要重试`};return Ln({..._,status:`error`,phase:`create`,appId:null,durationMs:Date.now()-r}),Rn({..._,requestName:`create_sub_app`,status:`error`,appId:null,logId:e.logId,phase:`create`,durationMs:T?Date.now()-T:void 0,errorType:e.userFacing?`user_facing`:`request_failed`}),$({..._,event:`create_failed`,message:e.error,level:`error`,phase:`create`,extra:{delivered:t,log_id:e.logId??`none`,user_facing:e.userFacing??!1}}),t&&$({..._,event:`delivery_sent`,message:`create failure delivered via feishu`,level:`info`,extra:{target:p,delivery_type:`create_error`}}),{content:[{type:`text`,text:JSON.stringify(i)}]}}e.phase===`stream`&&Rn({..._,requestName:`stream_chat`,status:`error`,appId:w?.appId??null,logId:e.logId,phase:`stream`,durationMs:E?Date.now()-E:void 0,errorType:e.retryable?`retryable_disconnect`:`stream_failed`})}}}catch(e){if(!D.signal.aborted)throw e}finally{clearTimeout(O)}C=D.signal.aborted;let k=null;try{k=JSON.parse(i.readFileSync(o.join(h,`.spark`,`meta.json`),`utf8`))}catch{}let A={status:C?`timeout`:x?`error`:`ok`,project_id:f,appId:w?.appId??k?.appId??null,finalText:w?.finalText??k?.finalText,output:w?.finalText??k?.finalText,logIds:b.length?b:void 0,meta:k};if(n.info(`miaoda_coding done (project=${f}, status=${A.status}, logIds=${b.join(`,`)}, traceId=${d})`),Ln({..._,status:A.status,projectId:f,appId:A.appId,durationMs:Date.now()-r}),$({..._,event:`task_done`,message:`miaoda_coding completed for ${f}`,status:A.status,appId:A.appId,extra:{last_log_id:b.at(-1)??`none`,log_id_count:b.length}}),C?(A.error=`执行超时(${u/1e3}秒)`,A.retryable=!0,A.hint=`执行超时,任务可能仍在后台运行。建议先调用 miaoda_check_progress 查看进度,再决定是否重试`):x&&(A.error=x,S&&(A.retryable=!0,A.hint=`网络连接中断,任务可能已部分完成。建议先调用 miaoda_check_progress 查看当前状态,再决定下一步`)),p&&A.status===`ok`){let e=k?.appUrl;if(n.info(`delivery check (project=${f}, target=${p}, appUrl=${e??`missing`}, traceId=${d})`),typeof e==`string`&&e.trim()){let t=e.includes(`?`)?`&`:`?`,r=`${e.trim()}${t}mode=sidebar-semi`;Un(p,`**[${r}](${r})**`),n.info(`delivery sent (project=${f}, url=${r}, traceId=${d})`),$({..._,event:`delivery_sent`,message:`preview link delivered via feishu`,level:`info`,appId:A.appId,extra:{target:p,preview_url:r,delivery_type:`preview_link`}}),A.hint=`预览链接已自动发送给用户,announce 时不要再带预览链接`}else n.warn(`delivery skipped: no appUrl in meta.json (project=${f}, traceId=${d})`),$({..._,event:`delivery_skipped`,message:`preview link delivery skipped because appUrl is missing`,level:`warn`,appId:A.appId,extra:{target:p,reason:`missing_app_url`}})}return{content:[{type:`text`,text:JSON.stringify(A,null,2)}]}}catch(e){return zn({error:e instanceof Error?e.message:String(e),event:`top_level_error`,traceId:d,projectId:c.project_id,agentId:t.agentId,domain:process.env.FORCE_AUTHN_INNERAPI_DOMAIN}),{content:[{type:`text`,text:JSON.stringify({status:`error`,error:e instanceof Error?e.message:String(e)})}]}}}}}),e.registerService({id:`miaoda-coding-config`,async start(e){a=Hn(e)},async stop(){}})}};export{rr as default};
23
+ var a=function(){return a=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},a.apply(this,arguments)};function o(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function s(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function c(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}var l=function(){return{}};function u(e){return e}function d(e){return typeof e==`object`&&!!e}var f=Object.prototype;function p(e){return f.toString.call(e)===`[object Array]`}function m(e){return typeof e==`boolean`}function h(e){return typeof e==`number`}function g(e){return typeof e==`string`}function _(e,t){if(!p(e)||e.length===0)return!1;for(var n=0;n<e.length;){if(e[n]===t)return!0;n++}return!1}var v=function(e,t){if(!p(e))return e;var n=e.indexOf(t);if(n>=0){var r=e.slice();return r.splice(n,1),r}return e},y=function(e,t,n){for(var r,i,a=s(t.split(`.`)),o=a[0],c=a.slice(1);e&&c.length>0;)e=e[o],r=c,i=s(r),o=i[0],c=i.slice(1);if(e)return n(e,o)};function b(e){try{return g(e)?e:JSON.stringify(e)}catch(e){return`[FAILED_TO_STRINGIFY]:`+String(e)}}function x(){var e={},t={},n={set:function(r,i){return e[r]=i,t[r]=b(i),n},merge:function(r){return e=a(a({},e),r),Object.keys(r).forEach(function(e){t[e]=b(r[e])}),n},delete:function(r){return delete e[r],delete t[r],n},clear:function(){return e={},t={},n},get:function(e){return t[e]},toString:function(){return a({},t)}};return n}var S=function(){return``.padStart?function(e,t){return t===void 0&&(t=8),e.padStart(t,` `)}:function(e){return e}}(),C=0,w=function(){var e=[...arguments];console.error.apply(console,c([`[SDK]`,Date.now(),S(``+ C++)],s(e),!1))},T=0,E=function(){var e=[...arguments];console.warn.apply(console,c([`[SDK]`,Date.now(),S(``+ T++)],s(e),!1))},D=function(e){return Math.random()<Number(e)},O=function(e,t){return e<Number(t)},k=function(e){return function(t){for(var n=t,r=0;r<e.length&&n;r++)try{n=e[r](n)}catch(e){w(e)}return n}};function A(){for(var e=Array(16),t=0,n=0;n<16;n++)n&3||(t=Math.random()*4294967296),e[n]=t>>>((n&3)<<3)&255;return e}function j(e){for(var t=[],n=0;n<256;++n)t[n]=(n+256).toString(16).substr(1);var r=0,i=t;return[i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],`-`,i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]],i[e[r++]]].join(``)}function M(){var e=A();return e[6]=e[6]&15|64,e[8]=e[8]&63|128,j(e)}function N(){var e=!1,t={},n=function(e){e.length&&e.forEach(function(e){try{e()}catch{}}),e.length=0},r=function(e){t[e]&&t[e].forEach(function(e){n(e[1])}),t[e]=void 0};return{set:function(r,i,a){t[r]?t[r].push([i,a]):t[r]=[[i,a]],e&&n(a)},has:function(e){return!!t[e]},remove:r,removeByEvType:function(e){Object.keys(t).forEach(function(r){t[r]&&t[r].forEach(function(t){t[0]===e&&n(t[1])})})},clear:function(){e=!0,Object.keys(t).forEach(function(e){r(e)})}}}var P=500,F=50;function I(e,t,n){if(t.push(n),!(t.length<P)){var r=t.splice(0,F);e.savePreStartDataToDb&&e.savePreStartDataToDb(r)}}function L(e){var t=e.getPreStartQueue();t.forEach(function(t){return e.build(t)}),t.length=0}var R=[`init`,`start`,`config`,`beforeDestroy`,`provide`,`beforeReport`,`report`,`beforeBuild`,`build`,`beforeSend`,`send`,`beforeConfig`];function z(e){var t=e.builder,n=e.createSender,r=e.createDefaultConfig,i=e.createConfigManager,a=e.userConfigNormalizer,o=e.initConfigNormalizer,l=e.validateInitConfig,u,f,p={};R.forEach(function(e){return p[e]=[]});var m=!1,h=!1,g=!1,y=[],b=[],x=N(),S={getBuilder:function(){return t},getSender:function(){return u},getPreStartQueue:function(){return y},init:function(e){if(m){E(`already inited`);return}if(e&&d(e)&&l(e)){var t=r(e);if(!t)throw Error(`defaultConfig missing`);var a=o(e);if(f=i(t),f.setConfig(a),f.onChange(function(){C(`config`)}),u=n(f.getConfig()),!u)throw Error(`sender missing`);m=!0,C(`init`,!0)}else throw Error(`invalid InitConfig, init failed`)},set:function(e){m&&e&&d(e)&&(C(`beforeConfig`,!1,e),f?.setConfig(e))},config:function(e){if(m)return e&&d(e)&&(C(`beforeConfig`,!1,e),f?.setConfig(a(e))),f?.getConfig()},provide:function(e,t){if(_(b,e)){E(`cannot provide `+e+`, reserved`);return}S[e]=t,C(`provide`,!1,e)},start:function(){m&&(h||f?.onReady(function(){h=!0,C(`start`,!0),L(S)}))},report:function(e){if(e){var t=k(p.beforeReport)(e);if(t){var n=k(p.report)(t);n&&(h?this.build(n):I(S,y,n))}}},build:function(e){if(h){var n=k(p.beforeBuild)(e);if(n){var r=t.build(n);if(r){var i=k(p.build)(r);i&&this.send(i)}}}},send:function(e){if(h){var t=k(p.beforeSend)(e);t&&(u.send(t),C(`send`,!1,t))}},destroy:function(){x.clear(),g=!0,y.length=0,C(`beforeDestroy`,!0)},on:function(e,t){if(e===`init`&&m||e===`start`&&h||e===`beforeDestroy`&&g)try{t()}catch{}else p[e]&&p[e].push(t)},off:function(e,t){p[e]&&(p[e]=v(p[e],t))},destroyAgent:x};return b=Object.keys(S),S;function C(e,t){t===void 0&&(t=!1);var n=[...arguments].slice(2);p[e].forEach(function(e){try{e.apply(void 0,c([],s(n),!1))}catch{}}),t&&(p[e].length=0)}}var B=function(e){var t=x();e.provide(`context`,t),e.on(`report`,function(e){return e.extra||={},e.extra.context=t.toString(),e})};function V(e,t){e.on(`init`,function(){var n=[],r=function(r){r.forEach(function(r){var i=r.name;_(n,i)||(n.push(i),r.setup(e),t&&t(i,r.setup),e.destroyAgent.set(i,i,[function(){n=v(n,i),r.tearDown&&r.tearDown()}]))})};e.provide(`applyIntegrations`,r);var i=e.config();i&&i.integrations&&r(i.integrations)})}var H=function(e){try{typeof window==`object`&&d(window)&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__&&window.__SLARDAR_DEVTOOLS_GLOBAL_HOOK__.push(e)}catch{}},U=function(){return Date.now()};function W(){if(typeof window==`object`&&d(window))return window}var G=function(e){if(e)return e.__SLARDAR_REGISTRY__||={Slardar:{plugins:[],errors:[],subject:{}}},e.__SLARDAR_REGISTRY__.Slardar},K=function(){var e=[...arguments],t=G(W());t&&(t.errors||=[],t.errors.push(e))},q=function(e){var t;if(!(typeof window!=`object`||!window.__perfsee__)){var n={};return(t=Error.captureStackTrace)==null||t.call(Error,n,e),n.stack}},J=`custom`,ee=`event`,Y=`log`,X=function(e){if(!(!e||!d(e))&&!(!e.name||!g(e.name))){var t={name:e.name,type:ee};if(`metrics`in e&&d(e.metrics)){var n=e.metrics,r={};for(var i in n)h(n[i])&&(r[i]=n[i]);t.metrics=r}if(`categories`in e&&d(e.categories)){var a=e.categories,o={};for(var i in a)o[i]=b(a[i]);t.categories=o}return`attached_log`in e&&g(e.attached_log)&&(t.attached_log=e.attached_log),t}},Z=function(e){if(!(!e||!d(e))&&!(!e.content||!g(e.content))){var t=e.content,n={content:b(t),type:Y,level:`info`};if(`level`in e&&(n.level=e.level),`extra`in e&&d(e.extra)){var r=e.extra,i={},a={};for(var o in r)h(r[o])?i[o]=r[o]:a[o]=b(r[o]);n.metrics=i,n.categories=a}return`attached_log`in e&&g(e.attached_log)&&(n.attached_log=e.attached_log),n}},te=function(e){var t=function(n){var r=X(n);if(r){var i=q(t);i&&(r.stacks=i),e.report({ev_type:J,payload:r,extra:{timestamp:U()}})}};e.provide(`sendEvent`,t),e.provide(`sendLog`,function(t){var n=Z(t);n&&e.report({ev_type:J,payload:n,extra:{timestamp:U()}})})},ne=function(e,t){var n=e.common||{};return n.sample_rate=t,e.common=n,e},re=function(e,t,n,r,i){return e?(function(e){return function(){return e}})(i(r,t)):function(){return n(t)}},ie=function(e,t){return e.map(function(e){switch(t){case`number`:return Number(e);case`boolean`:return e===`1`;default:return String(e)}})},ae=function(e,t,n){switch(n){case`eq`:return _(t,e);case`neq`:return!_(t,e);case`gt`:return e>t[0];case`gte`:return e>=t[0];case`lt`:return e<t[0];case`lte`:return e<=t[0];case`regex`:return!!e.match(new RegExp(t.join(`|`)));case`not_regex`:return!e.match(new RegExp(t.join(`|`)));default:return!1}},oe=function(e,t,n,r){var i=y(e,t,function(e,t){return e[t]});return i===void 0?!1:ae(i,ie(r,m(i)?`bool`:h(i)?`number`:`string`),n)},se=function(e,t){try{return t.type===`rule`?oe(e,t.field,t.op,t.values):t.type===`and`?t.children.every(function(t){return se(e,t)}):t.children.some(function(t){return se(e,t)})}catch(e){return K(e),!1}},ce=function(e,t,n,r,i,a){var o={};return Object.keys(e).forEach(function(s){var c=e[s],l=c.enable,u=c.sample_rate,d=c.conditional_sample_rules;l?(o[s]={enable:l,sample_rate:u,effectiveSampleRate:u*n,hit:re(t,u,r,i,a)},d&&(o[s].conditional_hit_rules=d.map(function(e){var o=e.sample_rate,s=e.filter;return{sample_rate:o,hit:re(t,o,r,i,a),effectiveSampleRate:o*n,filter:s}}))):o[s]={enable:l,hit:function(){return!1},sample_rate:0,effectiveSampleRate:0}}),o},le=function(e,t,n,r,i){if(!t)return u;var a=t.sample_rate,o=t.include_users,s=t.sample_granularity,c=t.rules,l=t.r,d=l===void 0?Math.random():l;if(_(o,e))return function(e){return ne(e,1)};var f=s===`session`,p=re(f,a,n,d,r),m=ce(c,f,a,n,d,r);return function(e){if(!p())return f&&i[0](),!1;if(!(e.ev_type in m))return ne(e,a);if(!m[e.ev_type].enable)return f&&i[1](e.ev_type),!1;if(e.common?.sample_rate)return e;var t=m[e.ev_type],n=t.conditional_hit_rules;if(n){for(var r=0;r<n.length;r++)if(se(e,n[r].filter))return n[r].hit()?ne(e,n[r].effectiveSampleRate):!1}return t.hit()?ne(e,t.effectiveSampleRate):(!(n&&n.length)&&f&&i[1](e.ev_type),!1)}},ue=function(e){e.on(`start`,function(){var t=e.config(),n=t.userId,r=t.sample,i=le(n,r,D,O,[function(){e.destroy()},function(t){e.destroyAgent.removeByEvType(t)}]);e.on(`build`,i)})},de={build:function(e){return{ev_type:e.ev_type,payload:e.payload,common:a(a({},e.extra||{}),e.overrides||{})}}},fe=`mon.zijieapi.com`,pe=fe,me=`2.1.8`,he=`SDK_BASE`,ge=`/monitor_web/settings/browser-settings`,_e=`/monitor_browser/collect/batch/`,ve={sample_rate:1,include_users:[],sample_granularity:`session`,rules:{}},ye=20,be=`session`;function xe(e){var t,n,r=[`userId`,`deviceId`,`sessionId`,`env`];try{for(var i=o(r),a=i.next();!a.done;a=i.next()){var s=a.value;e[s]||delete e[s]}}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return e}function Se(e){return xe(a({},e))}function Ce(e){return d(e)&&`bid`in e&&`transport`in e}function we(e){return xe(a({},e))}function Te(e){if(!e)return{};var t=e.sample,n=e.timestamp,r=e.quota_rate,i=r===void 0?1:r;if(!t)return{};var a=t.sample_rate,o=t.sample_granularity,s=o===void 0?be:o,c=t.include_users,l=t.rules,u=l===void 0?[]:l;return{sample:{include_users:c,sample_rate:a*i,sample_granularity:s,rules:u.reduce(function(e,t){var n=t.name;return e[n]={enable:t.enable,sample_rate:t.sample_rate,conditional_sample_rules:t.conditional_sample_rules},e},{})},serverTimestamp:n}}var Ee=function(e,t){return t===void 0&&(t=_e),(e&&e.indexOf(`//`)>=0?``:`https://`)+e+t},De=function(e,t){return t===void 0&&(t=ge),(e&&e.indexOf(`//`)>=0?``:`https://`)+e+t},Oe=function(){return M()},ke=function(){return M()},Ae=function(e){return e+`_`+Date.now()},je=function(){return M()},Me=function(e){var t=e,n,r={},i,o,s=l,c=l;return{getConfig:function(){return t},setConfig:function(e){return r=a(a({},r),e||{}),u(),n||(n=e,t.useLocalConfig||!t.bid?(o={},s()):Ne(t.transport,t.domain,t.bid,function(e){i=e,d()})),t},onChange:function(e){c=e},onReady:function(e){s=e,o&&s()}};function u(){var n=a(a(a({},e),o||{}),r);n.sample=Pe(Pe(e.sample,o?.sample),r.sample),t=n,c()}function d(){o=Te(i),u(),s()}};function Ne(e,t,n,r){if(!e.get)return r({});e.get({withCredentials:!0,url:De(t)+`?bid=`+n+`&store=1`,success:function(e){r(e.data||{})},fail:function(){r({sample:{sample_rate:.001}})}})}function Pe(e,t){if(!e||!t)return e||t;var n=a(a({},e),t);return n.include_users=c(c([],s(e.include_users||[]),!1),s(t.include_users||[]),!1),n.rules=c(c([],s(Object.keys(e.rules||{})),!1),s(Object.keys(t.rules||{})),!1).reduce(function(n,r){return r in n||(r in(e.rules||{})&&r in(t.rules||{})?(n[r]=a(a({},e.rules[r]),t.rules[r]),n[r].conditional_sample_rules=c(c([],s(e.rules[r].conditional_sample_rules||[]),!1),s(t.rules[r].conditional_sample_rules||[]),!1)):n[r]=e.rules?.[r]||t.rules?.[r]),n},{}),n}var Fe=function(e,t){var n=t||{},r=n.version,i=n.name,o={url:``,protocol:``,domain:``,path:``,query:``,timestamp:Date.now(),sdk_version:r||me,sdk_name:i||he};return a(a({},e),{extra:a(a({},o),e.extra||{})})},Ie=function(e){e.on(`report`,function(t){return Fe(t,e.config())})},Le=function(e,t){var n={};return n.bid=t.bid,n.pid=t.pid,n.view_id=t.viewId,n.user_id=t.userId,n.device_id=t.deviceId,n.session_id=t.sessionId,n.release=t.release,n.env=t.env,a(a({},e),{extra:a(a({},n),e.extra||{})})},Re=function(e){e.on(`beforeBuild`,function(t){return Le(t,e.config())})};function ze(e){return i(e)}var Be=function(e){return{bid:``,pid:``,viewId:Ae(`_`),userId:Oe(),deviceId:ke(),sessionId:je(),domain:fe,release:``,env:`production`,sample:ve,plugins:{},transport:{get:l,post:l},useLocalConfig:!1}},Ve=function(e){var t=e===void 0?{}:e,n=t.createSender,r=n===void 0?function(e){return ze({size:ye,endpoint:Ee(e.domain),transport:e.transport})}:n,i=t.builder,a=i===void 0?de:i,o=t.createDefaultConfig,s=z({validateInitConfig:Ce,initConfigNormalizer:Se,userConfigNormalizer:we,createSender:r,builder:a,createDefaultConfig:o===void 0?Be:o,createConfigManager:Me});return B(s),Re(s),Ie(s),V(s),H(s),s},He=function(e){e===void 0&&(e={});var t=Ve(e);return ue(t),te(t),t},Ue=He();e.BATCH_REPORT_PATH=_e,e.CustomPlugin=te,e.DEFAULT_SAMPLE_CONFIG=ve,e.DEFAULT_SAMPLE_GRANULARITY=be,e.DEFAULT_SENDER_SIZE=ye,e.InjectConfigPlugin=Re,e.InjectEnvPlugin=Ie,e.REPORT_DOMAIN=fe,e.SDK_NAME=he,e.SDK_VERSION=me,e.SETTINGS_DOMAIN=pe,e.SETTINGS_PATH=ge,e.addConfigToReportEvent=Le,e.addEnvToSendEvent=Fe,e.builder=de,e.createBaseClient=He,e.createConfigManager=Me,e.createMinimalClient=Ve,e.default=Ue,e.getDefaultConfig=Be,e.getDefaultDeviceId=ke,e.getDefaultSessionId=je,e.getDefaultUserId=Oe,e.getReportUrl=Ee,e.getServerConfig=Ne,e.getSettingsUrl=De,e.getViewId=Ae,e.mergeSampleConfig=Pe,e.normalizeInitConfig=Se,e.normalizeStrictFields=xe,e.normalizeUserConfig=we,e.parseServerConfig=Te,e.validateInitConfig=Ce}))(),1);function Ln(e){return!e||typeof e!=`object`||!(`default`in e)?e:e.default}function Rn(e){let t=Ln(e);return Ln(t)??t??e??{}}const zn=Rn(In.default);let Bn=!1;function Vn(){if(!Bn)try{let e=Vt();zn.init({bid:`apaas_miaoda`,release:String(e.version??`unknown`),env:Fn(),transport:{get:({url:e,success:t,fail:n})=>fetch(e).then(e=>e.json()).then(e=>t?.(e)).catch(e=>n?.(e)),post:({url:e,data:t})=>{let n=typeof t==`string`?t:JSON.stringify(t);return fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:n}).catch(()=>{})}}}),zn.start(),Bn=!0}catch{}}function Hn(e){if(e!==void 0)return String(e)}function Un(e){let t={source:`node-plugin`},n=e.traceId,r=e.projectId,i=Hn(e.isNew),a=e.appId,o=e.agentId,s=e.sessionKey;return n&&(t.trace_id=n),r&&(t.project_id=r),i&&(t.is_new=i),a&&(t.app_id=a),o&&(t.agent_id=o),e.domain&&(t.domain=e.domain),s&&(t.session_key=s),e.refer&&(t.refer=e.refer),t}function Wn(e,t){let n={...e};for(let[e,r]of Object.entries(t??{}))r!=null&&(n[e]=typeof r==`boolean`?String(r):r);return n}function Gn(e){switch(e){case`user_stopped`:return`user_stopped`;case`quota_exceeded`:return`quota_exceeded`;case`service_failed`:return`service_failed`;case`stream_interrupted`:return`stream_interrupted`;default:return}}function Kn(e){return e===`user_stopped`||e===`quota_exceeded`}function qn(e){try{let t={},n=Un(e),r=e.durationMs,i=e.sseEventCount,a=e.reconnectCount,o=e.createDurationMs;typeof r==`number`&&(t.duration_ms=r),typeof i==`number`&&(t.sse_event_count=i),typeof a==`number`&&(t.reconnect_count=a),typeof o==`number`&&(t.create_duration_ms=o);let s={...n,status:e.status,is_new:n.is_new??`false`},c=e.errorType;e.phase&&(s.phase=e.phase),c&&(s.error_type=c.slice(0,100)),e.terminalReason&&(s.terminal_reason=e.terminalReason.slice(0,100)),e.errorCode&&(s.error_code=e.errorCode.slice(0,100)),zn.sendEvent?.({name:`miaoda_coding_task`,metrics:t,categories:s})}catch{}}function Jn(e){try{let t={},n=Un(e);typeof e.durationMs==`number`&&(t.duration_ms=e.durationMs),typeof e.sseEventCount==`number`&&(t.sse_event_count=e.sseEventCount),typeof e.reconnectCount==`number`&&(t.reconnect_count=e.reconnectCount);let r={...n,request_name:e.requestName,status:e.status};e.logId&&(r.log_id=e.logId),e.phase&&(r.phase=e.phase),e.errorType&&(r.error_type=e.errorType.slice(0,100)),e.terminalReason&&(r.terminal_reason=e.terminalReason.slice(0,100)),e.errorCode&&(r.error_code=e.errorCode.slice(0,100)),zn.sendEvent?.({name:`miaoda_coding_request`,metrics:t,categories:r})}catch{}}function Yn(e){try{if(!e.projectId)return;let t=Wn(Un(e),{event:e.event,phase:e.phase}),n=e.logIds;n?.length&&(t.log_ids=n.join(`,`)),zn.sendLog?.({content:e.error,level:`error`,extra:t})}catch{}}function $(e){try{let t=Wn(Un(e),{event:e.event,phase:e.phase,status:e.status,...e.extra});zn.sendLog?.({content:e.message,level:e.level??`info`,extra:t})}catch{}}const Xn=/^[a-z0-9][a-z0-9-]{0,63}$/,Zn=new Set([`.`,`..`,`con`,`nul`,`prn`,`aux`]);function Qn(e){let t=e?.config?.plugins?.entries?.[`openclaw-extension-miaoda-coding`]?.config??{};return{verbose:t?.verbose===!0,hooks:{allowPromptInjection:t?.hooks?.allowPromptInjection!==!1}}}function $n(e,t){i.mkdirSync(o.dirname(e),{recursive:!0});let n=`${e}.tmp.${process.pid}.${Date.now()}`;try{i.writeFileSync(n,JSON.stringify(t,null,2)),i.renameSync(n,e)}catch(e){try{i.unlinkSync(n)}catch{}throw e}}function er(e){try{$n(e,{});return}catch(t){try{i.unlinkSync(e);return}catch(e){if(e?.code===`ENOENT`)return;throw t}}}function tr(e,t){if(!e)return;let r=o.dirname(process.execPath),i=n(`openclaw`,[`message`,`send`,`--channel`,`feishu`,`--target`,e,`--message`,t],{stdio:[`ignore`,`ignore`,`pipe`],env:{...process.env,PATH:`${r}:${process.env.PATH||``}`}});i.stderr.on(`data`,()=>{}),i.on(`close`,()=>{}),i.unref()}function nr(e){return String(e??``).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,``).replace(/\s+/g,` `).trim()}function rr(e){let t=String(e??``).replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,``).trim();if(!t)throw Error(`task 不能为空`);if(t.length>4e3)throw Error(`task 不能超过 4000 个字符`);return t}function ir(e){let t=nr(e);if(!ar(t))throw Error(`project_id 不合法: "${t}"`);return t}function ar(e){return Xn.test(e)&&!Zn.has(e)}function or(e){if(e==null||e===``)return;let t=nr(e);if(t!==`none`){if(!/^(user|chat|thread):\S+$/.test(t))throw Error(`target 不合法`);return t}}function sr(e,t){let n=K(e,t);if(i.existsSync(n))return n;let r=q(e,t);return i.existsSync(r)?r:n}function cr(e){let t=new Map,n=o.join(e,`app`);try{for(let e of i.readdirSync(n,{withFileTypes:!0}))!e.isDirectory()||!ar(e.name)||t.set(e.name,o.join(n,e.name))}catch{}try{for(let n of i.readdirSync(e,{withFileTypes:!0}))!n.isDirectory()||n.name===`app`||!ar(n.name)||t.has(n.name)||t.set(n.name,o.join(e,n.name))}catch{}return[...t.entries()].map(([e,t])=>({projectId:e,appCwd:t}))}function lr(e){try{return i.readFileSync(e,`utf8`).split(`
24
+ `).map(e=>e.trim()).filter(Boolean)}catch{return[]}}function ur(e){return e.replace(/^\[[^\]]+\]\s*/,``)}function dr(e){return e.replace(/应用已创建(appId:\s*[^)]+)/g,`应用已创建`)}function fr(e){return e.slice(-3).map(ur).map(dr).join(` | `)||`暂无进度记录`}function pr(e){let t=fr(e);return t.includes(`失败:`)?`failed`:t.includes(`处理完成`)?`completed`:t===`暂无进度记录`?`pending`:`running`}function mr(e){try{let t=JSON.parse(i.readFileSync(o.join(e,`.spark`,`meta.json`),`utf8`));return typeof t?.appId==`string`&&t.appId.trim().length>0}catch{return!1}}var hr={id:`openclaw-extension-miaoda-coding`,name:`妙搭`,description:`妙搭制品创建与修改`,register(e){let t=`[miaoda-coding]`,n={info:n=>e.logger.info?.(`${t} ${n}`),warn:n=>e.logger.warn?.(`${t} ${n}`),error:n=>e.logger.error?.(`${t} ${n}`)},a={verbose:!1,hooks:{allowPromptInjection:!0}},s=An({log:n});n.info(`plugin registered`),Vn(),e.on(`session_start`,(e,t)=>{try{s.onSessionStart(e?.sessionId)}catch(e){n.warn(`session_start reset failed: ${String(e)}`)}});let c=new Set([`miaoda_coding`]),l=new Set([`miaoda_check_progress`]);e.on(`before_tool_call`,(e,t)=>{let r=e.toolName,i=t?.sessionKey??``,a=i.toLowerCase().split(`:`).includes(`subagent`);if(c.has(r)&&!a)return n.warn(`blocked ${r} from non-subagent session: ${i}`),{block:!0,blockReason:`${r} 只能由 subagent 调用。请通过 sessions_spawn(runtime="subagent", mode="run") 派活,不要直接调用此工具。读 miaoda-coding skill 了解完整流程。`};if(l.has(r)&&a)return n.warn(`blocked ${r} from subagent session: ${i}`),{block:!0,blockReason:`${r} 不能由 subagent 调用。subagent 不应直接操作参考资料或查询进度。`}}),e.on(`before_prompt_build`,async(e,t)=>{if(!Qn(t).hooks.allowPromptInjection)return;let r={prependSystemContext:[`【硬规则 — 妙搭】`,`当用户要求创建或修改应用、网页、页面时,必须通过 sessions_spawn(runtime="subagent", mode="run") 交给妙搭。`,`读 miaoda-coding skill 后严格按指示操作。只传 runtime、mode、task 三个参数,不要传 streamTo/sandbox 等。`,`如果需求在支持范围内并且已经派活给 subagent,最终回复只发一条简短总结;是否附上预览链接严格按 miaoda-coding skill 第 6 条(读 .spark/delivery.json 和 .spark/meta.json)判断,不要自行决定;不要把"不适用场景"的主站引导规则误用到正常交付场景。`,`绝对不要自己写代码或用 exec 生成文件。如果 sessions_spawn 调用本身返回错误,去掉多余参数后重试。如果 subagent 执行失败需要重试,generation_request 填"继续"(不要重复发完整需求),详见 skill 中的重试流程。`,`如果对话中有需要传递给 code agent 的上下文(研究结果、用户偏好等),先调 miaoda_write_reference 写入 reference 目录,再 spawn。用户反悔或需要替换之前的上下文时,使用 miaoda_write_reference 的 mode=replace。妙搭只做制品生成,不做研究。`,`不要用 sessions_history 读取子 agent 的 session,查进度用 miaoda_check_progress tool(仅限建应用场景,数据库操作等不要用)。`,`subagent 完成后只发一条总结消息,严禁发多条。是否带预览链接严格按 miaoda-coding skill 6 条的 delivery.json/meta.json 判断流程,不要自己决定。不要调 message tool。`].join(` `)};try{let e=await s.getSchemaSummary(t?.sessionId);e&&(r.appendSystemContext=e)}catch(e){n.error(`db schema injection threw unexpected error: ${String(e)}`)}return r}),e.registerTool(e=>{let t=J(e);return{name:`list_projects`,label:`列出妙搭项目`,description:`列出已创建的妙搭项目,返回 project_id、appId、updatedAt、finalText、status 和进度摘要。修改已有项目时必须先调此工具。`,parameters:{type:`object`,properties:{}},async execute(){let e=[];try{e=cr(t.workspaceDir).map(({projectId:e,appCwd:t})=>{let n=o.join(t,`.spark`,`meta.json`),r=o.join(t,`.spark`,`progress.txt`),a=null;try{a=JSON.parse(i.readFileSync(n,`utf8`))}catch{}let s=lr(r);return{project_id:e,appId:a?.appId??null,updatedAt:a?.updatedAt??null,finalText:a?.finalText??null,status:pr(s),progressSummary:fr(s)}})}catch{}return{content:[{type:`text`,text:JSON.stringify({projects:e},null,2)}]}}}}),e.registerTool(e=>{let t=J(e);return{name:`miaoda_check_progress`,label:`查看妙搭应用生成进度`,description:`查看通过 miaoda_coding 创建的应用的生成进度。仅用于 sessions_spawn 派活建应用后查看进度,不适用于数据库操作等其他场景。`,parameters:{type:`object`,properties:{project_id:{type:`string`,description:`项目目录名(从 list_projects 获取)`}},required:[`project_id`]},async execute(e,n){try{let e=ir(n.project_id),r=sr(t.workspaceDir,e),a=o.join(r,`.spark`,`progress.txt`),s=i.readFileSync(a,`utf8`).trim().split(`
25
+ `).filter(Boolean),c=null;try{c=JSON.parse(i.readFileSync(o.join(r,`.spark`,`meta.json`),`utf8`))}catch{}let l=!!c?.finalText,u=s.slice(-20).map(dr).join(`
26
+ `);return{content:[{type:`text`,text:JSON.stringify({status:`ok`,project_id:e,lines:s.length,progress:u,delivery_ready:l,finalTextAvailable:l,note:`miaoda_check_progress 只用于查看进度,不能根据 appId 或进度文本推导预览链接;最终链接只以 subagent completion result 中的 output/finalText 为准。`})}]}}catch{return{content:[{type:`text`,text:JSON.stringify({status:`no_progress`,project_id:n.project_id,message:`暂无进度记录`,delivery_ready:!1,finalTextAvailable:!1,note:`miaoda_check_progress 只用于查看进度,不能根据 appId 或进度文本推导预览链接;最终链接只以 subagent completion result 中的 output/finalText 为准。`})}]}}}}}),e.registerTool(e=>{let t=J(e);return{name:`miaoda_write_reference`,label:`写入妙搭参考资料`,description:`将参考资料写入妙搭项目的 reference 目录,供 code agent 在生成时自行查阅。按 category 分类写入。mode=append(默认)追加,mode=replace 替换该 category 全部内容(用于反悔/调整场景)。`,parameters:{type:`object`,properties:{project_id:{type:`string`,description:`项目目录名`},category:{type:`string`,enum:[`research`,`design`,`feedback`],description:`资料类别:research(调研结果)、design(设计要求)、feedback(用户反馈)`},content:{type:`string`,description:`参考资料内容(Markdown 格式,摘要+关键原文引用)`},filename:{type:`string`,description:`可选文件名(不含扩展名)`},mode:{type:`string`,enum:[`append`,`replace`],description:`写入模式:append(追加,默认)、replace(替换该 category 全部内容)`}},required:[`project_id`,`category`,`content`]},async execute(e,n){try{let e=ir(n.project_id);if(!Sn.includes(n.category))throw Error(`category 不合法,必须是 ${Sn.join(`、`)} 之一`);let r=n.content?.trim();if(!r)throw Error(`content 不能为空`);if(r.length>5e4)throw Error(`content 不能超过 50000 个字符`);let i=n.mode===`replace`?`replace`:`append`,a=sr(t.workspaceDir,e),o=await Dn({appCwd:a,category:n.category,content:r,filename:n.filename,mode:i}),s=await On(a);return{content:[{type:`text`,text:JSON.stringify({status:`ok`,...o,summary:s},null,2)}]}}catch(e){return{content:[{type:`text`,text:JSON.stringify({status:`error`,error:e instanceof Error?e.message:String(e)})}]}}}}});let u=3600*1e3;e.registerTool(e=>{let t=J(e),s=e.config?.channels?.feishu,c=e.agentAccountId,l=(c?s?.accounts?.[c]:void 0)?.appId??s?.appId;return n.info(`channelAppId resolved: ${l??`(none)`} (accountId=${c??`(none)`})`),{name:`miaoda_coding`,label:`妙搭`,description:`创建或修改妙搭应用/网页。只接受生成指令,不接受搜索/调研等任务。如有参考资料,应事先通过 miaoda_write_reference 写入 reference 目录。修改已有项目时必须先调 list_projects 获取 project_id。返回结构化 JSON(status/appId/finalText/output/meta)。`,parameters:{type:`object`,properties:{generation_request:{type:`string`,description:`生成指令(如'做一个学习网站,包含章节、题库、测验')`},project_id:{type:`string`,description:`本地项目目录名,仅允许小写字母、数字和短横线`},target:{type:`string`,description:`飞书消息推送目标:单聊用 user:ou_xxx,群聊用 chat:oc_xxx,非飞书渠道传 none`}},required:[`generation_request`,`project_id`,`target`]},async execute(s,c){let d=r();try{let r=Date.now(),s=rr(c.generation_request),f=ir(c.project_id),p=or(c.target),m=process.env.FORCE_AUTHN_INNERAPI_DOMAIN,h=sr(t.workspaceDir,f);i.mkdirSync(h,{recursive:!0});let g=!mr(h),_={traceId:d,projectId:f,isNew:g,agentId:t.agentId,domain:m,sessionKey:e?.sessionKey};n.info(`miaoda_coding called (project=${f}, isNew=${g}, traceId=${d})`),$({..._,event:`start`,message:`miaoda_coding started for ${f}`,extra:{target:p??`none`}});let v=o.join(h,`.spark`,`delivery.json`);try{er(v)}catch(e){throw n.error(`failed to reset delivery marker (project=${f}, traceId=${d}): ${String(e)}`),$({..._,event:`miaoda_coding_delivery_marker_reset_failed`,message:`aborting run — unable to establish clean delivery.json state`,level:`error`,extra:{error:String(e)}}),Error(`无法初始化投递状态文件: ${String(e)}`)}g&&$({..._,event:`create_start`,message:`createSubApp started for ${f}`});let y=await kn(h)?`工作目录下有 reference/ 目录,包含参考资料,请先查阅再开始工作。\n\n${s}`:s,b=o.join(h,`.agent`);if(!i.existsSync(b)){let e=G(W());if(i.existsSync(e))try{i.symlinkSync(e,b)}catch{}}let x=[],S,C=!1,w,T,E,D,O,k,A=!1,j=null,M=g?Date.now():void 0,N=g?void 0:Date.now(),P=new AbortController,F=setTimeout(()=>P.abort(),u);try{for await(let e of xn({cwd:h,rootDir:W(),task:y,requestText:s,traceId:d,agentId:t.agentId,channelAppId:l,signal:P.signal,onReconnect:(e,t)=>{n.warn(`stream reconnect (project=${f}, attempt=${e}, lastEventId=${t??`none`}, traceId=${d})`),$({..._,event:`stream_reconnect`,message:`stream reconnect for ${f}`,level:`warn`,extra:{attempt:e,last_event_id:t??`none`}})},onStreamFailed:e=>{n.error(`stream failed (project=${f}, traceId=${d}): ${e}`),$({..._,event:`stream_failed`,message:String(e),level:`error`})}})){if(`logId`in e&&e.logId&&x.push(e.logId),a.verbose&&p)switch(e.type){case`app_created`:tr(p,`应用已创建(appId: ${e.appId})`);break;case`failed`:tr(p,`处理失败: ${e.error}`);break}if(e.type===`completed`){let t=e.terminalReason??`completed`;j={appId:e.appId,finalText:e.finalText},w=t,T=e.sseEventCount,E=e.reconnectCount,D=e.finishReasonRaw,O=e.errorCodeRaw,k=e.lastEventId,Jn({..._,requestName:`stream_chat`,status:`ok`,appId:e.appId,logId:e.logId,phase:`stream`,durationMs:N?Date.now()-N:void 0,terminalReason:t,sseEventCount:e.sseEventCount,reconnectCount:e.reconnectCount}),$({..._,event:`stream_completed`,message:`streamChat completed for ${f}`,appId:e.appId,extra:{log_id:e.logId??`none`}}),$({..._,event:`stream_terminal`,message:`stream terminal: ${t}`,appId:e.appId,extra:{terminal_reason:t,finish_reason_raw:e.finishReasonRaw??`none`,last_event_id:e.lastEventId??`none`,reconnect_count:e.reconnectCount??0,sse_event_count:e.sseEventCount??0,log_id:e.logId??`none`}})}if(e.type===`app_created`&&(Jn({..._,requestName:`create_sub_app`,status:`ok`,appId:e.appId,logId:e.logId,phase:`create`,durationMs:M?Date.now()-M:void 0}),N=Date.now(),$({..._,event:`create_succeeded`,message:`createSubApp completed for ${f}`,appId:e.appId,extra:{log_id:e.logId,conversation_id:e.conversationId??`none`}})),e.type===`failed`){let t=e.terminalReason??(e.retryable?`stream_interrupted`:`service_failed`);if(S=e.error,C=e.retryable??!1,w=t,T=e.sseEventCount??T,E=e.reconnectCount??E,D=e.finishReasonRaw??D,O=e.errorCodeRaw??O,k=e.lastEventId??k,e.phase===`pre-create`){n.error(`pre-create validation failed (project=${f}): ${e.error}`),clearTimeout(F),qn({..._,status:`error`,phase:`pre-create`,appId:null,durationMs:Date.now()-r}),$({..._,event:`pre_create_validation_failed`,message:e.error,level:`error`,phase:`pre-create`});let t={status:`error`,project_id:f,appId:null,error:e.error,meta:null,hint:`这是运行环境配置问题,不是用户操作失误。直接将 error 字段内容告知用户,并说明需要联系管理员修复配置;不要建议换 project_id,不要重试`};return{content:[{type:`text`,text:JSON.stringify(t)}]}}if(e.phase===`create`){n.error(`createSubApp failed (project=${f}, traceId=${d}): ${e.error}`);let t=!!p;if(p){let t=e.userFacing?e.error:`createSubApp 失败: ${e.error}`;n.info(`delivering create error via feishu (project=${f}, target=${p}, traceId=${d})`),tr(p,t)}else n.warn(`create failed but no target for feishu delivery (project=${f}, traceId=${d})`);let i=e.userFacing?{status:`error`,project_id:f,appId:null,meta:null,logIds:x.length?x:void 0,hint:t?`创建失败,详情已通过飞书发送给用户,不要重复发送错误内容`:`创建失败,将 error 字段的内容原样发送给用户,不要改写、不要删减、不要重试`,error:t?void 0:e.error}:{status:`error`,project_id:f,appId:null,error:e.error,meta:null,logIds:x.length?x:void 0,hint:t?`createSubApp 失败,错误已通过飞书发送。根据 error 内容用通俗语言告诉用户具体原因,不要重试`:`createSubApp 失败,根据 error 内容用通俗语言告诉用户具体原因,不要重试`};return qn({..._,status:`error`,phase:`create`,appId:null,durationMs:Date.now()-r}),Jn({..._,requestName:`create_sub_app`,status:`error`,appId:null,logId:e.logId,phase:`create`,durationMs:M?Date.now()-M:void 0,errorType:e.userFacing?`user_facing`:`request_failed`}),$({..._,event:`create_failed`,message:e.error,level:`error`,phase:`create`,extra:{delivered:t,log_id:e.logId??`none`,user_facing:e.userFacing??!1}}),t&&$({..._,event:`delivery_sent`,message:`create failure delivered via feishu`,level:`info`,extra:{target:p,delivery_type:`create_error`}}),{content:[{type:`text`,text:JSON.stringify(i)}]}}e.phase===`stream`&&(Jn({..._,requestName:`stream_chat`,status:`error`,appId:e.appId??j?.appId??null,logId:e.logId,phase:`stream`,durationMs:N?Date.now()-N:void 0,errorType:Gn(t)??(e.retryable?`stream_interrupted`:`service_failed`),terminalReason:t,errorCode:e.errorCodeRaw,sseEventCount:e.sseEventCount,reconnectCount:e.reconnectCount}),$({..._,event:`stream_terminal`,message:`stream terminal: ${t}`,level:Kn(t)?`info`:`error`,appId:e.appId??j?.appId??null,extra:{terminal_reason:t,finish_reason_raw:e.finishReasonRaw??`none`,error_code_raw:e.errorCodeRaw??`none`,last_event_id:e.lastEventId??`none`,reconnect_count:e.reconnectCount??0,sse_event_count:e.sseEventCount??0,log_id:e.logId??`none`}}))}}}catch(e){if(!P.signal.aborted)throw e}finally{clearTimeout(F)}A=P.signal.aborted;let I=null;try{I=JSON.parse(i.readFileSync(o.join(h,`.spark`,`meta.json`),`utf8`))}catch{}let L={status:A?`timeout`:S?`error`:`ok`,project_id:f,appId:j?.appId??I?.appId??null,finalText:j?.finalText??I?.finalText,output:j?.finalText??I?.finalText,logIds:x.length?x:void 0,meta:I};if(n.info(`miaoda_coding done (project=${f}, status=${L.status}, logIds=${x.join(`,`)}, traceId=${d})`),qn({..._,status:L.status,projectId:f,appId:L.appId,durationMs:Date.now()-r,phase:L.status===`ok`||w?`stream`:void 0,errorType:Gn(w),terminalReason:w,errorCode:O,sseEventCount:T,reconnectCount:E}),$({..._,event:`task_done`,message:`miaoda_coding completed for ${f}`,status:L.status,appId:L.appId,extra:{last_log_id:x.at(-1)??`none`,log_id_count:x.length,terminal_reason:w??`none`,finish_reason_raw:D??`none`,error_code_raw:O??`none`,last_event_id:k??`none`}}),A?(L.error=`执行超时(${u/1e3}秒)`,L.retryable=!0,L.hint=`执行超时,任务可能仍在后台运行。建议先调用 miaoda_check_progress 查看进度,再决定是否重试`):S&&(L.error=S,C&&(L.retryable=!0,L.hint=`网络连接中断,任务可能已部分完成。建议先调用 miaoda_check_progress 查看当前状态,再决定下一步`)),L.status===`ok`&&!p&&(n.warn(`delivery skipped: target is missing (project=${f}, traceId=${d})`),$({..._,event:`delivery_skipped`,message:`preview link delivery skipped because target is missing (subagent passed none/empty)`,level:`warn`,appId:L.appId,extra:{reason:`missing_target`}})),p&&L.status===`ok`){let e=I?.appUrl;if(n.info(`delivery check (project=${f}, target=${p}, appUrl=${e??`missing`}, traceId=${d})`),typeof e==`string`&&e.trim()){let t=e.includes(`?`)?`&`:`?`,r=`${e.trim()}${t}mode=sidebar-semi`;tr(p,`**[${r}](${r})**`),n.info(`delivery sent (project=${f}, url=${r}, traceId=${d})`),$({..._,event:`delivery_sent`,message:`preview link delivered via feishu`,level:`info`,appId:L.appId,extra:{target:p,preview_url:r,delivery_type:`preview_link`}});try{$n(v,{deliveredAt:Date.now(),deliveredUrl:r,deliveredForTrace:d}),$({..._,event:`miaoda_coding_delivery_marker_written`,message:`delivery.json recorded successful feishu preview-link delivery`,level:`info`,appId:L.appId,extra:{preview_url:r}})}catch(e){n.warn(`failed to write delivery marker (project=${f}, traceId=${d}): ${String(e)}`),$({..._,event:`miaoda_coding_delivery_marker_write_failed`,message:`failed to write delivery.json after successful feishu delivery`,level:`warn`,appId:L.appId,extra:{error:String(e),preview_url:r}})}L.hint=`预览链接已自动发送给用户,announce 时不要再带预览链接`}else n.warn(`delivery skipped: no appUrl in meta.json (project=${f}, traceId=${d})`),$({..._,event:`delivery_skipped`,message:`preview link delivery skipped because appUrl is missing`,level:`warn`,appId:L.appId,extra:{target:p,reason:`missing_app_url`}})}return{content:[{type:`text`,text:JSON.stringify(L,null,2)}]}}catch(e){return Yn({error:e instanceof Error?e.message:String(e),event:`top_level_error`,traceId:d,projectId:c.project_id,agentId:t.agentId,domain:process.env.FORCE_AUTHN_INNERAPI_DOMAIN}),{content:[{type:`text`,text:JSON.stringify({status:`error`,error:e instanceof Error?e.message:String(e)})}]}}}}}),e.registerService({id:`miaoda-coding-config`,async start(e){a=Qn(e)},async stop(){}})}};export{hr as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/openclaw-extension-miaoda-coding",
3
- "version": "1.0.14",
3
+ "version": "1.0.16",
4
4
  "description": "妙搭 Coding Agent — 通过 AI 创建和修改妙搭应用",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -26,7 +26,7 @@
26
26
  ]
27
27
  },
28
28
  "devDependencies": {
29
- "@lark-apaas/http-client": "^0.1.3",
29
+ "@lark-apaas/http-client": "^0.1.5",
30
30
  "@slardar/base": "^2.1.8",
31
31
  "@vitest/coverage-v8": "^4.0.18",
32
32
  "openclaw": "^2026.3.2",
@@ -207,9 +207,12 @@ tool 返回的 JSON 里如果有 `hint` 字段,严格按 hint 指示行事。
207
207
  3. 调 sessions_spawn
208
208
  4. 回复用户"交给妙搭了,稍等"
209
209
  5. **不要** 调 sessions_history、subagents、或任何 poll 操作
210
- 6. subagent announce 回来后,**只发一条总结消息**:简短总结做了什么,并附上预览链接
211
- - 预览链接获取方式:优先读 `workspace/app/<project_id>/.spark/meta.json`;如果不存在,再回退读 `workspace/<project_id>/.spark/meta.json`。从其中的 `appUrl` 字段拼上 `?mode=sidebar-semi`(如已有 query 参数则用 `&mode=sidebar-semi`)
212
- - 如果 `meta.json` 中没有 `appUrl`,说明可能未部署成功,参考「查看执行详情」章节了解情况
210
+ 6. subagent announce 回来后,按 plugin 写的投递标记判断该不该带链接(路径默认 `workspace/app/<project_id>/.spark/`,如不存在再回退 `workspace/<project_id>/.spark/`):
211
+ - `.spark/delivery.json`(每次 run 开头 plugin 会 atomic 覆写成空对象,投递成功后再覆写成含 `deliveredAt` 的对象;所以它永远只反映**本次 run** 的状态)
212
+ - **`delivery.json` 里有 `deliveredAt` 字段**(plugin 本次 run 已自动投递预览链接)→ 只发一条简短纯文字总结,**不要带预览链接**(plugin 已经发过一条,主 agent 再带就是两条)
213
+ - **`delivery.json` 存在但没有 `deliveredAt` 字段 / 文件不存在 / 读不了**:读 `.spark/meta.json`
214
+ - **有 `appUrl`**(plugin 本次 run 没投递,常见于 subagent 把 target 填成 "none")→ 主 agent **自己补发链接**:把 `appUrl` 拼上 `?mode=sidebar-semi`(如已有 query 参数则用 `&mode=sidebar-semi`),用加粗 Markdown 链接 `**[url](url)**` 放在简短总结里一起发,只发一条
215
+ - **没有 `appUrl`**(部署未成功)→ 按下方「处理失败和异常」第 4 条处理
213
216
  - **严禁发多条消息**
214
217
  - 不要提系统、子任务、announce、subagent 等内部细节
215
218
  7. `miaoda_check_progress` 用于两种场景:(a) 用户主动问进度时,(b) 任务失败且结果中有 `hint` 建议查进度时
@@ -227,7 +230,7 @@ subagent 返回的结果 JSON 中可能包含 `status: "error"` 或 `status: "ti
227
230
  - **重试时**:走**修改已有项目**流程,`generation_request` 填 `"继续"`。feida-ai 的 conversation 中已有完整上下文(需求 + 之前的代码 + 失败日志),发"继续"即可让 Agent 接着上次的进度工作。**禁止**用创建模板重复发送完整的原始需求——这会导致 Agent 看到重复的需求消息,浪费 token 并造成混乱
228
231
  2. **`hint` 包含"createSubApp 失败"**:createSubApp 是创建应用的前置步骤,失败原因可能是用户额度不足、权限不够、或服务异常等。根据 `error` 字段的具体内容用通俗语言告诉用户(如"额度用完了"、"没有权限"、"服务暂时不可用"),**不要重试,不要调 miaoda_check_progress**
229
232
  3. **`retryable: false` 或无 `retryable` 字段**:直接告诉用户失败了,附上错误信息,问用户怎么处理
230
- 4. **结果里没有预览链接**(`hint` 提到"未检测到预览链接"):调 `miaoda_check_progress` 查看最新状态,可能链接还没生成
233
+ 4. **subagent 总结里提到部署失败 / 没生成预览链接**:如实告诉用户"应用生成/部署失败",根据错误信息用通俗语言说明原因,问用户要不要重试。**不要自己拼预览链接**,也**不要调 `miaoda_check_progress`**(这个 tool 不返回 appUrl,查了也拿不到链接)
231
234
 
232
235
  **禁止行为**:
233
236
  - 不要在用户不知情的情况下自动重试——先告诉用户情况,等用户确认