goatchain-cli 0.0.2-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +368 -0
- package/dist/args-B4NUWmzz.js +2 -0
- package/dist/chunk-B_5Rb6Gi.js +1 -0
- package/dist/cli.mjs +4 -0
- package/dist/index.js +145 -0
- package/dist/openai-BOGzt3st.js +1 -0
- package/dist/openai-Ba5c3VJv.js +16 -0
- package/dist/repl-RiteZLua.js +76 -0
- package/dist/src-BD_MMztG.js +284 -0
- package/dist/src-Dpj3VSps.js +1 -0
- package/dist/theme-4Sto2Osm.js +1 -0
- package/dist/theme-DvHvtqNs.js +1 -0
- package/dist/ui-B9ajujL6.js +1 -0
- package/dist/ui-D4n45LUU.js +2 -0
- package/package.json +43 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import{n as e,r as t,t as n}from"./chunk-B_5Rb6Gi.js";import{t as r}from"./openai-Ba5c3VJv.js";import{createRequire as i}from"node:module";import{randomUUID as a}from"node:crypto";import{copyFile as o,mkdir as s,mkdtemp as c,readFile as l,readdir as u,rm as d,stat as f,writeFile as p}from"node:fs/promises";import m from"node:path";import h from"node:process";import{chmodSync as g,existsSync as _,mkdirSync as v,readFileSync as y,readdirSync as b,rmSync as x,statSync as S,unlinkSync as C,writeFileSync as w}from"node:fs";import{homedir as T}from"node:os";import{spawn as E}from"node:child_process";import{Buffer as D}from"node:buffer";import O from"picomatch";function k(e,t){let n=t?.phase;n||=e.shouldContinue?e.pendingToolCalls.length>0?`tool_execution`:`llm_call`:`completed`;let r=t?.status;return r||=n===`completed`?`Completed: ${e.stopReason??`unknown`}`:n===`tool_execution`?`Executing tools: ${e.pendingToolCalls.map(e=>e.toolCall.function.name).join(`, `)}`:n===`approval_pending`?`Waiting for user approval`:`Iteration ${e.iteration}: Calling LLM`,{schemaVersion:1,sessionId:e.sessionId,agentId:e.agentId,agentName:t?.agentName,iteration:e.iteration,phase:n,status:r,modelConfig:t?.modelConfig,requestParams:t?.requestParams,messages:[...e.messages],pendingToolCalls:e.pendingToolCalls.map(e=>({toolCall:{...e.toolCall},result:e.result,isError:e.isError})),currentResponse:e.currentResponse,currentThinking:e.currentThinking,shouldContinue:e.shouldContinue,stopReason:e.stopReason,lastModelStopReason:e.lastModelStopReason,usage:{...e.usage},metadata:{...e.metadata},savedAt:Date.now()}}function A(e){let t=e.schemaVersion??1;if(t!==1)throw Error(`Unsupported checkpoint schemaVersion: ${t}. Please migrate checkpoints or upgrade GoatChain.`);return{sessionId:e.sessionId,agentId:e.agentId,iteration:e.iteration,messages:[...e.messages],pendingToolCalls:e.pendingToolCalls.map(e=>({toolCall:{...e.toolCall},result:e.result,isError:e.isError})),currentResponse:e.currentResponse,currentThinking:e.currentThinking,shouldContinue:e.shouldContinue,stopReason:e.stopReason,lastModelStopReason:e.lastModelStopReason,usage:{...e.usage},metadata:{...e.metadata}}}let j;function M(){if(j!==void 0)return j;try{let e=i(import.meta.url)(`tiktoken`);return j=e,e}catch{return j=null,null}}function N(e,t){if(!e)return 0;let n=M();if(!n)return Math.ceil(e.length/4);let r=null;try{return r=t?n.encoding_for_model(t):n.encoding_for_model(`gpt-4o`),r.encode(e).length}catch(t){console.error(`Error encoding text:`,t);try{return r=n.get_encoding(`cl100k_base`),r.encode(e).length}catch{return Math.ceil(e.length/4)}}finally{r?.free()}}function P(e,t){return typeof e==`string`?N(e,t):Array.isArray(e)?e.reduce((e,n)=>typeof n==`object`&&n&&`text`in n?e+N(String(n.text),t):e,0):0}function F(e,t){try{return N(JSON.stringify(e),t)}catch{return ee(e,t)}}function ee(e,t){let n=4;if(n+=P(e.content,t),e.role===`assistant`&&e.tool_calls)for(let r of e.tool_calls){n+=N(r.function.name,t);let e=typeof r.function.arguments==`string`?r.function.arguments:JSON.stringify(r.function.arguments);n+=N(e,t),n+=10}return e.role===`tool`&&e.name&&(n+=N(e.name,t)),e.role===`assistant`&&e.reasoning_content&&(n+=N(e.reasoning_content,t)),n}function I(e,t){if(!e||e.length===0)return 0;try{return N(JSON.stringify(e),t)}catch{return e.reduce((e,n)=>e+F(n,t),3)}}const L={CHECKPOINT:`checkpoint`,COMPRESSION:`compression`,SESSION:`session`,COMPRESSION_SNAPSHOT:`compression-snapshot`};function te(e,t,n=`[Previous conversation context]`){let r=[...e],i=r.findIndex(e=>e.role===`system`);if(i===-1)return r;let a=r[i],o=a.content,s={type:`text`,text:`${n}\n\n${t}`},c;return c=typeof o==`string`?[{type:`text`,text:o},s]:Array.isArray(o)?[...o,s]:[o,s],r[i]={...a,content:c},r}function ne(e,t=`[Previous conversation context]`){let n=e.find(e=>e.role===`system`);if(!n)return!1;let r=n.content;return typeof r==`string`?r.includes(t):Array.isArray(r)?r.some(e=>e.type===`text`&&e.text?.includes(t)):!1}function re(e,t){let n=[...e],r=-1;for(let e=n.length-1;e>=0;e--)if(n[e].role===`user`){r=e;break}if(r===-1){let e={role:`user`,content:t};return[...n,e]}let i=n[r],a=i.content,o,s={type:`text`,text:t};return o=typeof a==`string`?[{type:`text`,text:a},s]:Array.isArray(a)?[...a,s]:[a,s],n[r]={...i,content:o},n}const ie=`
|
|
2
|
+
You are a helpful AI assistant tasked with summarizing conversations.
|
|
3
|
+
|
|
4
|
+
Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
5
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
6
|
+
|
|
7
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
8
|
+
|
|
9
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
10
|
+
- The user's explicit requests and intents
|
|
11
|
+
- Your approach to addressing the user's requests
|
|
12
|
+
- Key decisions, technical concepts and code patterns
|
|
13
|
+
- Specific details like:
|
|
14
|
+
- file names
|
|
15
|
+
- full code snippets
|
|
16
|
+
- function signatures
|
|
17
|
+
- file edits
|
|
18
|
+
- Errors that you ran into and how you fixed them
|
|
19
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
20
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
21
|
+
|
|
22
|
+
Your summary should include the following sections:
|
|
23
|
+
|
|
24
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
25
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
26
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
27
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
28
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
29
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
30
|
+
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
31
|
+
7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
32
|
+
8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
|
|
33
|
+
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
|
|
34
|
+
|
|
35
|
+
Here's an example of how your output should be structured:
|
|
36
|
+
|
|
37
|
+
<example>
|
|
38
|
+
<analysis>
|
|
39
|
+
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
|
40
|
+
</analysis>
|
|
41
|
+
|
|
42
|
+
<summary>
|
|
43
|
+
1. Primary Request and Intent:
|
|
44
|
+
[Detailed description]
|
|
45
|
+
|
|
46
|
+
2. Key Technical Concepts:
|
|
47
|
+
- [Concept 1]
|
|
48
|
+
- [Concept 2]
|
|
49
|
+
- [...]
|
|
50
|
+
|
|
51
|
+
3. Files and Code Sections:
|
|
52
|
+
- [File Name 1]
|
|
53
|
+
- [Summary of why this file is important]
|
|
54
|
+
- [Summary of the changes made to this file, if any]
|
|
55
|
+
- [Important Code Snippet]
|
|
56
|
+
- [File Name 2]
|
|
57
|
+
- [Important Code Snippet]
|
|
58
|
+
- [...]
|
|
59
|
+
|
|
60
|
+
4. Errors and fixes:
|
|
61
|
+
- [Detailed description of error 1]:
|
|
62
|
+
- [How you fixed the error]
|
|
63
|
+
- [User feedback on the error if any]
|
|
64
|
+
- [...]
|
|
65
|
+
|
|
66
|
+
5. Problem Solving:
|
|
67
|
+
[Description of solved problems and ongoing troubleshooting]
|
|
68
|
+
|
|
69
|
+
6. All user messages:
|
|
70
|
+
- [Detailed non tool use user message]
|
|
71
|
+
- [...]
|
|
72
|
+
|
|
73
|
+
7. Pending Tasks:
|
|
74
|
+
- [Task 1]
|
|
75
|
+
- [Task 2]
|
|
76
|
+
- [...]
|
|
77
|
+
|
|
78
|
+
8. Current Work:
|
|
79
|
+
[Precise description of current work]
|
|
80
|
+
|
|
81
|
+
9. Optional Next Step:
|
|
82
|
+
[Optional Next step to take]
|
|
83
|
+
|
|
84
|
+
</summary>
|
|
85
|
+
</example>
|
|
86
|
+
|
|
87
|
+
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
|
|
88
|
+
|
|
89
|
+
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
|
|
90
|
+
<example>
|
|
91
|
+
## Compact Instructions
|
|
92
|
+
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
|
|
93
|
+
</example>
|
|
94
|
+
|
|
95
|
+
<example>
|
|
96
|
+
# Summary instructions
|
|
97
|
+
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
|
|
98
|
+
</example>
|
|
99
|
+
|
|
100
|
+
Existing summary (may be empty):
|
|
101
|
+
{{existingSummary}}
|
|
102
|
+
|
|
103
|
+
Messages to summarize:
|
|
104
|
+
{{toolOutputs}}
|
|
105
|
+
`;function ae(e){let{maxTokens:t,protectedTurns:n=2,enableSummary:r=!1,model:i,getModel:a,summaryPrompt:o=ie,stateStore:s,getStateStore:c,persistClearedContent:l=!1,name:u,onCompressionStart:d,onCompressionEnd:f}=e;if(r&&!i&&!a)throw Error(`ContextCompressionMiddleware: "model" or "getModel" required when enableSummary is true`);let p=Math.floor(t*.8),m=u??`context-compression`,h=async(e,t)=>{let u=s??c?.(),m;u&&(m=await u.load(e.sessionId,L.COMPRESSION));let h=e.messages;if(m?.summary&&(ne(h)||(h=te(h,m.summary))),I(h)>p){let s=r?i??a?.():void 0,{compressedMessages:c,stats:g,summary:_}=await oe(h,{protectedTurns:n,targetTokens:p,enableSummary:r,summaryPrompt:o},s,m?.summary,d,f),v={...e,messages:c,metadata:{...e.metadata,lastCompression:g}};if(u){let t=Date.now(),n={lastStats:g,history:[...m?.history??[],g],summary:_,updatedAt:t};if(await u.save(e.sessionId,L.COMPRESSION,n),l){let n={messages:c.map(e=>({role:e.role,content:e.content,tool_call_id:e.tool_call_id,name:e.name,tool_calls:`tool_calls`in e?e.tool_calls:void 0})),stats:g,timestamp:t},r=`${L.COMPRESSION_SNAPSHOT}-${t}`;await u.save(e.sessionId,r,n)}}return t(v)}return h===e.messages?t(e):t({...e,messages:h})};return h.__middlewareName=m,h}async function oe(e,t,n,r,i,a){let{protectedTurns:o,enableSummary:s,summaryPrompt:c}=t,l=I(e),{protectedToolIds:u,unprotectedToolMessages:d}=le(e,ce(e),se(e,o)),f={tokensBefore:l,tokensAfter:0,clearedToolOutputs:d.length,summaryGenerated:!1,timestamp:Date.now()};i?.(f);let p=[],m=e.map(e=>{if(e.role===`tool`){let t=e;if(!u.has(t.tool_call_id)){let e=typeof t.content==`string`?t.content:JSON.stringify(t.content);return p.push({name:t.name,content:e}),{...t,content:`[Old tool result content cleared]`}}}return e}),h=r;if(s&&n&&p.length>0){let e=(await pe(p,n,c,r)).trim();e.length>0&&(h=e,m=te(m,h))}let g=ue(m),_=I(g);if(s&&h&&_>t.targetTokens){let e=P(h),n=_-t.targetTokens;if(e>n){let t=Math.max(100,e-n-100)*4,r=h.slice(0,t-43)+`
|
|
106
|
+
|
|
107
|
+
[... summary truncated due to length ...]`,i=m.findIndex(e=>e.role===`system`);if(i>=0){let e=m[i],t=`[Previous conversation context]`;if(typeof e.content==`string`){let n=e.content.indexOf(`---\n${t}`);n>=0&&(e.content=e.content.slice(0,n).trimEnd())}else Array.isArray(e.content)&&(e.content=e.content.filter(e=>!(e.type===`text`&&e.text?.includes(t))));m=te(m,r),h=r}}}g=ue(m);let v=I(g);t.targetTokens;let y={tokensBefore:l,tokensAfter:v,clearedToolOutputs:p.length,summaryGenerated:s&&p.length>0,timestamp:Date.now()};return a?.(y),{compressedMessages:g,stats:y,summary:h,clearedContents:p}}function se(e,t){let n=e=>e.role===`user`?(typeof e.content==`string`?e.content:``).startsWith(`[Context from cleared tool outputs]`):!1;if(t<=0)return e.length;let r=0,i=[];for(let a=e.length-1;a>=0;a--){let o=e[a];if(o.role===`user`&&!n(o)&&(r++,i.unshift(a),r>=t))return a}return Math.max(0,e.length-6)}function ce(e){let t=e=>e.role===`user`?(typeof e.content==`string`?e.content:``).startsWith(`[Context from cleared tool outputs]`):!1,n=-1;for(let r=0;r<e.length;r++)if(e[r].role===`user`&&!t(e[r])){n=r;break}if(n===-1)return 0;let r=-1;for(let t=n+1;t<e.length;t++)if(e[t].role===`assistant`){r=t;break}if(r===-1)return n+1;for(let n=r+1;n<e.length;n++)if(e[n].role===`user`&&!t(e[n]))return n;let i=0;for(let t=r+1;t<e.length;t++)if(e[t].role===`tool`&&(i++,i>=1))return t+1;return e.length}function le(e,t,n){let r=new Set,i=[],a=[],o=[],s=[];for(let n=0;n<t;n++){let t=e[n];t.role===`tool`&&(r.add(t.tool_call_id),a.push(n))}for(let t=n;t<e.length;t++){let n=e[t];n.role===`tool`&&(r.add(n.tool_call_id),o.push(t))}for(let a=t;a<n;a++){let t=e[a];if(t.role===`tool`){let e=t;s.push(a),r.has(e.tool_call_id)||i.push(e)}}return{protectedToolIds:r,unprotectedToolMessages:i}}function ue(e){let t=[],n=e=>e.role===`user`?(typeof e.content==`string`?e.content:``).startsWith(`[Context from cleared tool outputs]`):!1;for(let r of e){if(r.role!==`user`){t.push(r);continue}if(n(r)){t.push(r);continue}let e=t[t.length-1];if(e&&e.role===`user`){if(n(e)){t.push(r);continue}if(e.name===r.name){t[t.length-1]={...e,content:de(e.content,r.content)};continue}}t.push(r)}return t}function de(e,t){return[...fe(e),...fe(t)]}function fe(e){if(typeof e==`string`)return e.trim().length>0?[{type:`text`,text:e}]:[];if(Array.isArray(e)){let t=[],n=e;for(let e of n){if(typeof e==`string`){let n=e.trim();n.length>0&&t.push({type:`text`,text:n});continue}if(e&&typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`){let e=n.text;if(typeof e==`string`&&e.trim().length===0)continue}t.push(n);continue}if(e!=null){let n=String(e);n.trim().length>0&&t.push({type:`text`,text:n})}}return t}if(e&&typeof e==`object`&&`type`in e){let t=e;if(t.type===`text`){let e=t.text;if(typeof e==`string`&&e.trim().length===0)return[]}return[t]}let t=String(e);return t.trim().length>0?[{type:`text`,text:t}]:[]}async function pe(e,t,n,r){let i=[{role:`system`,content:`You are a helpful assistant that creates concise summaries.`},{role:`user`,content:me(n,e.map(({name:e,content:t})=>`## ${e??`unknown_tool`}\n${t.length>5e3?`${t.slice(0,5e3)}...[truncated for summary]`:t}`).join(`
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
`),r)}],a=``;for await(let e of t.stream({messages:i,maxOutputTokens:1e3}))if(e.type===`delta`&&e.chunk.kind===`text`)a+=e.chunk.text;else if(e.type===`response_end`)break;return a}function me(e,t,n){let r=e.includes(`{{toolOutputs}}`),i=e.includes(`{{existingSummary}}`),a=n??``;return r||i?e.split(`{{toolOutputs}}`).join(t).split(`{{existingSummary}}`).join(a):`${e}\n\n${a.length>0?`Existing summary:\n${a}\n\nTool outputs to summarize:\n${t}`:`Tool outputs to summarize:\n${t}`}`}async function he(e){let{sessionId:t,fullMessages:n,model:r,stateStore:i,summaryPrompt:a=ie}=e,o=[];for(let e of n)if(e.role===`tool`){let t=e,n=typeof t.content==`string`?t.content:JSON.stringify(t.content);o.push({name:t.name,content:n})}let s=o;if(o.length===0){let e=[];for(let t of n)if(t.role===`user`||t.role===`assistant`){let n;n=typeof t.content==`string`?t.content:Array.isArray(t.content)?t.content.map(e=>e.type===`text`?e.text:e.type===`image`?`[Image]`:`[Other content]`).join(`
|
|
112
|
+
`):JSON.stringify(t.content),e.push({name:t.role===`user`?`user_message`:`assistant_message`,content:`${t.role===`user`?`User`:`Assistant`}: ${n}`})}if(e.length===0)return{summary:``,messageCount:n.length,toolOutputCount:0};s=e}let c=(await pe(s,r,a,void 0)).trim();if(c.length===0)return{summary:``,messageCount:n.length,toolOutputCount:o.length};let l=await i.load(t,L.COMPRESSION),u=Date.now(),d={lastStats:l?.lastStats,history:l?.history??[],summary:c,updatedAt:u};return await i.save(t,L.COMPRESSION,d),{summary:c,messageCount:n.length,toolOutputCount:o.length}}var ge=class{setModelOverride(e){this.configOverride||={},this.configOverride.model=e,this.updatedAt=Date.now()}clearModelOverride(){this.configOverride&&(delete this.configOverride.model,this.updatedAt=Date.now())}setSystemPromptOverride(e){this.configOverride||={},this.configOverride.systemPromptOverride=e,this.updatedAt=Date.now()}clearSystemPromptOverride(){this.configOverride&&(delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now())}disableTools(e){this.configOverride||={},this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...e],this.updatedAt=Date.now()}enableAllTools(){this.configOverride&&(delete this.configOverride.disabledTools,this.updatedAt=Date.now())}setStatus(e,t){this.status=e,this.errorMessage=t,this.updatedAt=Date.now()}markActive(){this.lastActiveAt=Date.now(),this.updatedAt=Date.now()}addMessage(e){this.messages.push(e),this.markActive()}getLastMessagePreview(e=100){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1],n=typeof t.content==`string`?t.content:JSON.stringify(t.content);return n.length>e?`${n.substring(0,e)}...`:n}addUsage(e){this.usage.promptTokens+=e.promptTokens,this.usage.completionTokens+=e.completionTokens,this.usage.totalTokens+=e.totalTokens,this.updatedAt=Date.now()}recordResponse(e){let t=(this.avgResponseTime??0)*this.responseCount;this.responseCount++,this.avgResponseTime=(t+e)/this.responseCount,this.updatedAt=Date.now()}incrementToolCallCount(){this.toolCallCount++,this.updatedAt=Date.now()}toSnapshot(){let e={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},t={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},n={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:e,configOverride:this.configOverride?{...this.configOverride}:void 0,context:t,stats:n}}restoreFromSnapshot(e){this.status=e.state.status,this.updatedAt=e.state.updatedAt,this.lastActiveAt=e.state.lastActiveAt,this.title=e.state.title,this.errorMessage=e.state.errorMessage,this.configOverride=e.configOverride?{...e.configOverride}:void 0,this.messages=[...e.context.messages],this.toolCallCount=e.context.toolCallCount,this.usage={...e.stats.usage},this.responseCount=e.stats.responseCount,this.avgResponseTime=e.stats.avgResponseTime}},_e=class{},R=class extends Error{constructor(e=`Agent execution aborted`){super(e),this.name=`AgentAbortError`}},ve=class extends Error{iterations;constructor(e,t){super(t??`Agent exceeded maximum iterations (${e})`),this.name=`AgentMaxIterationsError`,this.iterations=e}},z=class extends Error{constructor(e=`Agent execution paused`){super(e),this.name=`AgentPauseError`}};function B(e,t){if(!e?.aborted)return;let n=e?.reason;throw n instanceof Error?n:new R(typeof n==`string`?n:t?`${t} aborted`:`Agent execution aborted`)}var ye=class{},be=class{hooks;constructor(e){this.hooks=e??{}}async executePreToolUse(e){let t=this.hooks.preToolUse;if(!t||t.length===0)return{allow:!0};let n=e.toolCall;for(let r of t){let t=await r({...e,toolCall:n});if(!t.allow)return{allow:!1,modifiedToolCall:t.modifiedToolCall};t.modifiedToolCall&&(n=t.modifiedToolCall)}return n===e.toolCall?{allow:!0}:{allow:!0,modifiedToolCall:n}}async executePostToolUse(e,t){let n=this.hooks.postToolUse;if(!(!n||n.length===0))for(let r of n)await r(e,t)}async executePostToolUseFailure(e,t){let n=this.hooks.postToolUseFailure;if(!(!n||n.length===0))for(let r of n)await r(e,t)}};function xe(e){return(t,n)=>{let r=-1,i=async(t,a)=>{if(t<=r)throw Error(`next() called multiple times`);if(r=t,t===e.length)return n?await n(a):a;let o=e[t];return o(a,e=>i(t+1,e))};return i(0,t)}}function Se(e,t,n){let r=[{role:`system`,content:n},...e.messages??[],{role:`user`,content:e.input}];return{sessionId:e.sessionId??``,agentId:t,messages:r,iteration:0,pendingToolCalls:[],currentResponse:``,shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}var V=class extends Error{code;retryable;status;constructor(e,t){super(e),this.name=`ModelError`,this.code=t.code,this.retryable=t.retryable??!1,this.status=t.status}},Ce=class{state=new Map;get(e){return this.state.get(this.keyOf(e))||{failures:0,nextRetryAt:0}}markSuccess(e){this.state.set(this.keyOf(e),{failures:0,nextRetryAt:0})}markFailure(e,t){let n=this.get(e).failures+1,r=Math.min(t.maxDelayMs,t.baseDelayMs*2**Math.min(8,n-1));this.state.set(this.keyOf(e),{failures:n,nextRetryAt:t.now+r,lastError:{code:t.code,message:t.message}})}isAvailable(e,t){return this.get(e).nextRetryAt<=t}keyOf(e){return`${e.provider}:${e.modelId}`}},we=class extends Ce{},Te=class{constructor(e,t){this.health=e,this.fallbackOrder=t}select(e){let{now:t}=e,n=this.fallbackOrder.filter(e=>this.health.isAvailable(e,t));return n.length?n:this.fallbackOrder}},Ee=class{static isRetryableStatus(e){return e===408||e===409||e===429||e>=500&&e<=599}static async sleep(e,t){return e<=0?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{a(),n()},e);function a(){clearTimeout(i),t&&t.removeEventListener(`abort`,o)}function o(){a(),r(Error(`Aborted`))}if(t){if(t.aborted)return o();t.addEventListener(`abort`,o)}})}};function De(e=`req`){let t=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${t}`}var Oe=class e{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor(e={}){this.maxAttempts=e.maxAttempts??3,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.strategy=e.strategy??`exponential`,this.jitter=e.jitter??`equal`,this.multiplier=e.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay(e){let t;switch(this.strategy){case`exponential`:t=this.baseDelayMs*this.multiplier**(e-1);break;case`linear`:t=this.baseDelayMs*e;break;case`fixed`:t=this.baseDelayMs;break}return t=Math.min(t,this.maxDelayMs),t=this.applyJitter(t),this._previousDelay=t,Math.floor(t)}applyJitter(e){switch(this.jitter){case`full`:return Math.random()*e;case`equal`:return e/2+Math.random()*e/2;case`decorrelated`:return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case`none`:default:return e}}canRetry(e){return e<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new e;static aggressive=new e({maxAttempts:5,baseDelayMs:1e3,maxDelayMs:6e4});static gentle=new e({maxAttempts:3,baseDelayMs:2e3,maxDelayMs:3e4,jitter:`full`})};function ke(e){let t=e.adapters??(e.adapter?[e.adapter]:void 0);if(!t||t.length===0)throw new V("Missing adapter(s). Provide `adapter` for the simple case, or `adapters` for multi-provider routing.",{code:`missing_adapter`,retryable:!1});if(e.adapter&&e.adapters)throw new V("Provide either `adapter` or `adapters`, not both.",{code:`invalid_options`,retryable:!1});let n=new Map(t.map(e=>[e.provider,e])),r=e.health??new we,i=e.fallback?.onPartialOutput??`stop`,a=e.fallback?.onPartialToolCalls??`stop`,o=e.routing?.fallbackOrder??(()=>{let e=[];for(let n of t)n.defaultModelId&&e.push({provider:n.provider,modelId:n.defaultModelId});if(e.length===0)throw new V(`No routing configuration and no adapter with defaultModelId provided. Either provide options.routing.fallbackOrder or set defaultModelId on your adapters.`,{code:`missing_routing`,retryable:!1});return e})(),s=new Te(r,o),c=new Oe({maxAttempts:e.retry?.maxAttemptsPerModel??3,baseDelayMs:e.retry?.baseDelayMs??500,maxDelayMs:e.retry?.maxDelayMs??3e4,strategy:e.retry?.strategy??`exponential`,jitter:e.retry?.jitter??`equal`}),l=e.timeoutMs??6e4;function u(e){let t=n.get(e.provider);if(!t)throw new V(`No adapter for provider: ${e.provider}`,{code:`adapter_missing`,retryable:!1});return t}async function*d(t){let n=Date.now(),o=t.requestId||De(`req`),{model:d,...f}=t,p=t.model?[t.model]:s.select({now:n}),m;for(let n of p){let s=u(n),d=t.timeoutMs??l,p=!1,h=!1,g=0,_=new AbortController,v=t.signal,y=setTimeout(()=>_.abort(),d),b=()=>_.abort();v&&(v.aborted?_.abort():v.addEventListener(`abort`,b));let x={...f,requestId:o,model:n,stream:t.stream??!0,signal:_.signal,timeoutMs:d};try{for(let t=1;t<=c.maxAttempts;t++){g=t;try{for await(let e of s.stream({request:x}))e.type===`delta`&&(p=!0,e.chunk.kind===`tool_call_delta`&&(h=!0)),yield e;r.markSuccess(n);return}catch(r){m=r;let i=Ae(r),a=i.retryable;if(p||!a||!c.canRetry(t))throw i;let o=c.getDelay(t);e.retry?.onRetry?.({attempt:t,maxAttempts:c.maxAttempts,delayMs:o,error:{code:i.code,message:i.message,retryable:i.retryable},model:n,request:x}),await Ee.sleep(o,_.signal)}}}catch(e){let t=Ae(e);r.markFailure(n,{now:Date.now(),baseDelayMs:c.baseDelayMs,maxDelayMs:c.maxDelayMs,code:t.code,message:t.message});let s=!(h&&a===`stop`||p&&i===`stop`);if(yield{type:`error`,requestId:o,terminal:!s,model:n,attempt:g||1,source:`client`,error:{code:t.code,message:t.message,retryable:t.retryable}},!s)throw t;m=t;continue}finally{clearTimeout(y),v&&v.removeEventListener(`abort`,b)}}throw Ae(m||new V(`All models failed`,{code:`all_models_failed`}))}async function f(e){let t=``,n=``,r=`error`,i,a,o=e.requestId||``,s=!1;for await(let c of d({...e,stream:!0}))c.type===`response_start`?(s=!0,o=c.requestId,a=c.model,t=``):c.type===`delta`&&c.chunk.kind===`text`?t+=c.chunk.text:c.type===`response_end`?(n=t,r=c.stopReason,i=c.usage):c.type===`error`&&(r=`error`);if(!a)throw new V(`Missing response_start from adapter`,{code:`protocol_error`,retryable:!1});return{requestId:o,model:a,text:s?n:t,stopReason:r,usage:i}}return{get modelId(){return o[0]?.modelId??`unknown`},get modelRef(){return o[0]},get modelRefs(){return[...o]},setModelId(e){let t=o[0];if(!t)throw new V(`No primary model to update`,{code:`no_primary_model`,retryable:!1});o[0]={provider:t.provider,modelId:e}},stream:d,run:f}}function Ae(e){if(e instanceof V)return e;if(e&&typeof e==`object`){let t=typeof e.status==`number`?e.status:void 0,n=typeof e.code==`string`?e.code:t?`http_${t}`:`unknown_error`;return new V(typeof e.message==`string`?e.message:`Unknown error`,{code:n,retryable:t?Ee.isRetryableStatus(t):!1,status:t})}return new V(String(e||`Unknown error`),{code:`unknown_error`,retryable:!1})}function je(e){function t(e,t){if(typeof e!=`string`)return``;let n=e.trim();return n?/^data:/i.test(n)||/^https?:\/\//i.test(n)?n:typeof t==`string`&&t.trim()?`data:${t.trim()};base64,${n}`:n:``}if(typeof e==`string`)return e.trim().length===0?``:e;if(e==null)return``;if(typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`&&n.text)return n.text;if(n.type===`image`){let e=t(n.data??n.source?.data,n.mimeType??n.source?.media_type??n.source?.mimeType);return e?[{type:`image_url`,image_url:{url:e}}]:``}}if(Array.isArray(e)){let n=[];for(let r of e)if(typeof r==`string`)n.push({type:`text`,text:r});else if(r&&typeof r==`object`&&`type`in r){let e=r;if(e.type===`text`&&e.text)n.push({type:`text`,text:e.text});else if(e.type===`image`){let r=t(e.data??e.source?.data,e.mimeType??e.source?.media_type??e.source?.mimeType);r&&n.push({type:`image_url`,image_url:{url:r}})}}return n.length>0?n:``}return String(e)}function Me(e){return{...e,content:je(e.content)}}function Ne(e,t){return typeof t==`string`&&/deepseek/i.test(t)?!0:/^deepseek-/i.test(e)}function Pe(e={}){let t=e.baseUrl;function n(){if(typeof e.apiKey==`function`){let t=e.apiKey();if(typeof t==`string`){let e=t.trim();if(!e)throw new V(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return e}if(t!=null)throw new V(`Invalid apiKey provider`,{code:`invalid_api_key`,retryable:!1})}if(typeof e.apiKey==`string`){let t=e.apiKey.trim();if(!t)throw new V(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return t}let t=typeof process<`u`?process.env?.OPENAI_API_KEY:void 0;if(typeof t!=`string`||!t.trim())throw new V(`Missing OPENAI_API_KEY`,{code:`missing_api_key`,retryable:!1});return t.trim()}function i(){let i=n();return typeof t==`string`&&/\/chat\/completions\/?$/.test(t)?new r({apiKey:i,organization:e.organization,project:e.project,baseURL:`https://api.openai.com/v1`,fetch:(e,n)=>fetch(t,n)}):new r({apiKey:i,organization:e.organization,project:e.project,baseURL:t||void 0})}function a(e){return{provider:`openai`,modelId:e.model.modelId}}function o(e){if(e instanceof V)return e;let t=typeof e?.status==`number`?e.status:void 0;return new V(typeof e?.message==`string`?e.message:`OpenAI error`,{code:typeof e?.code==`string`?e.code:t?`openai_http_${t}`:`openai_error`,retryable:t?Ee.isRetryableStatus(t):!1,status:t})}async function*s(n){let{request:r}=n,s=r.requestId||De(`req`),c=i(),l=r.model.modelId,u=e.compat?.requireReasoningContentForToolCalls,d=typeof u==`boolean`?u:Ne(l,t),f=r.stream!==!1,p=[];if(r.messages&&Array.isArray(r.messages))for(let e of r.messages){let t=Me(e);if(!d&&t&&typeof t==`object`)`reasoning_content`in t&&delete t.reasoning_content;else if(d&&t?.role===`assistant`&&Array.isArray(t?.tool_calls)&&t.tool_calls.length>0){let e=t.reasoning_content;(typeof e!=`string`||e.length===0)&&(t.reasoning_content=`.`)}p.push(t)}else typeof r.instructions==`string`&&r.instructions.length>0&&p.push({role:`system`,content:r.instructions}),p.push({role:`user`,content:r.input});let m=(()=>{let e=r.reasoning?.effort;if(typeof e==`string`&&(e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`))return e})(),h={model:l,messages:p,stream:f,stream_options:f?{include_usage:!0}:void 0,metadata:r.metadata??void 0,reasoning_effort:m,max_completion_tokens:r.maxOutputTokens??void 0,stop:r.stop??void 0,temperature:r.temperature??void 0,top_p:r.topP??void 0,presence_penalty:r.presencePenalty??void 0,frequency_penalty:r.frequencyPenalty??void 0,seed:r.seed??void 0};r.tools&&Array.isArray(r.tools)&&r.tools.length>0&&(h.tools=r.tools);try{if(yield{type:`response_start`,requestId:s,model:a(r)},!f){let e=await c.chat.completions.create({...h,stream:!1},{signal:r.signal,timeout:r.timeoutMs}),t=Array.isArray(e?.choices)?e.choices[0]:void 0,n=t?.message,i=typeof n?.reasoning_content==`string`?n.reasoning_content:``;i.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:i}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:i}});let a=typeof n?.content==`string`?n.content:``;a.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:a}});let o=Array.isArray(n?.tool_calls)?n.tool_calls:[];for(let e=0;e<o.length;e++){let t=o[e],n=typeof t?.id==`string`?t.id:`call_${e}`,r=typeof t?.function?.name==`string`?t.function.name:void 0,i=typeof t?.function?.arguments==`string`?t.function.arguments:void 0;(i||r)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:i}})}yield{type:`response_end`,requestId:s,stopReason:Fe(t?.finish_reason),usage:e?.usage};return}let e=await c.chat.completions.create({...h,stream:!0},{signal:r.signal,timeout:r.timeoutMs}),t=null,n,i=new Map,o=!1,l=``;for await(let r of e){r?.usage!=null&&(n=r.usage);let e=Array.isArray(r?.choices)?r.choices:[];for(let n of e){n?.finish_reason!=null&&(t=n.finish_reason);let e=n?.delta,r=e?.reasoning_content;typeof r==`string`&&r.length>0&&(o||(o=!0,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}}),l+=r,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:r}});let a=e?.content;typeof a==`string`&&a.length>0&&(o&&(o=!1,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:a}});let c=Array.isArray(e?.tool_calls)?e.tool_calls:[];for(let e of c){let t=typeof e?.index==`number`?e.index:0,n=i.get(t)||(typeof e?.id==`string`?e.id:`call_${t}`);i.set(t,n);let r=typeof e?.function?.name==`string`?e.function.name:void 0,a=typeof e?.function?.arguments==`string`?e.function.arguments:void 0;(r||a)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:a}})}}}o&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`response_end`,requestId:s,stopReason:Fe(t),usage:n}}catch(e){throw e?.name===`AbortError`?new V(`Aborted`,{code:`aborted`,retryable:!1}):o(e)}}return{provider:`openai`,defaultModelId:e.defaultModelId,stream:s}}function Fe(e){return e===`tool_calls`||e===`function_call`?`tool_call`:e===`length`?`length`:e===`content_filter`?`error`:`final`}function Ie(e){if(e){if(e instanceof V)return{code:e.code,message:e.message,status:e.status,retryable:e.retryable};if(e instanceof Error){let t=e,n=typeof t.code==`string`?t.code:void 0,r=typeof t.status==`number`?t.status:void 0,i=typeof t.retryable==`boolean`?t.retryable:void 0;return{code:n,message:e.message,status:r,retryable:i}}return{message:String(e)}}}function Le(e){let t=e?.function?.arguments;if(typeof t==`string`)try{return JSON.parse(t),e}catch(n){let r=n instanceof Error?n.message:String(n);return{...e,function:{...e.function,arguments:JSON.stringify({_raw:t,_parseError:r})}}}return t&&typeof t==`object`?{...e,function:{...e.function,arguments:JSON.stringify(t)}}:{...e,function:{...e.function,arguments:JSON.stringify(t??null)}}}function Re(e){let t=!1,n=e.map(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return e;let n=e.tool_calls;if(!Array.isArray(n)||n.length===0)return e;let r=!1,i=n.map(e=>{let t=Le(e);return t!==e&&(r=!0),t});return r?(t=!0,{...e,tool_calls:i}):e});return t?n:e}var H=class e extends ge{id;agentId;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;_autoSave;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_hasCheckpoint;_checkpointRestored=!1;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;_emitSessionCreatedEvent;_sessionCreatedEventEmitted=!1;getDisabledToolNames(){let e=this.configOverride?.disabledTools;return!e||e.length===0?new Set:new Set(e)}isToolDisabled(e){return this.getDisabledToolNames().has(e)}collectBlockedTools(e){let t=new Set;for(let n of this._middlewares)if(typeof n.__getBlockedTools==`function`){let r=n.__getBlockedTools(e);(Array.isArray(r)?r:Array.from(r)).forEach(e=>t.add(e))}return t}isToolBlocked(e,t){let n=e.metadata?.blockedTools;return n?n instanceof Set?n.has(t):Array.isArray(n)?n.includes(t):!1:!1}getToolsForModel(e){let t=this._tools?.toOpenAIFormat();if(!t||t.length===0)return;let n=this.getDisabledToolNames(),r=n.size===0?t:t.filter(e=>!n.has(e.function.name)),i=e.metadata?.blockedTools;return i&&i.size>0&&(r=r.filter(e=>!i.has(e.function.name))),r.length>0?r:void 0}getEffectiveSystemPrompt(){let e=this.configOverride?.systemPromptOverride;return typeof e==`string`?e:this._systemPrompt}constructor(e,t,n,r){if(super(),this._stateStore=e,this.id=t,n)this.createdAt=n.createdAt,this.restoreFromSnapshot(n);else{let e=Date.now();this.createdAt=e,this.status=`active`,this.updatedAt=e,this.lastActiveAt=e,this.messages=[],this.toolCallCount=0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._modelClient=r?.modelClient,this._tools=r?.tools,this._middlewares=r?.middlewares??[],this._systemPrompt=r?.systemPrompt,this._agentName=r?.agentName,this._onUsage=r?.onUsage,this._hasCheckpoint=r?.hasCheckpoint??!1,this._hooks=r?.hooks,this._modelOverride=r?.model,this._maxIterations=r?.maxIterations,this._requestParams=r?.requestParams,this._emitSessionCreatedEvent=r?.emitSessionCreatedEvent===!0}get hasCheckpoint(){return this._hasCheckpoint}send(e,t){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error(`Cannot send while receiving messages`);if(this._pendingInput)throw Error(`Pending input already exists; call receive() to consume it before sending another message`);this._pendingInput={input:e,options:t}}async*receive(e){if(this._isReceiving)throw Error(`Cannot receive concurrently`);if(!this._hasCheckpoint&&!this._pendingInput)throw Error(`Nothing to receive; call send() first (or resume from a session that has a checkpoint)`);this._isReceiving=!0;try{if(this._emitSessionCreatedEvent&&!this._sessionCreatedEventEmitted&&(this._sessionCreatedEventEmitted=!0,yield{type:`session_created`,agentId:this.agentId,sessionId:this.id}),!this._hasCheckpoint&&this._pendingInput&&this._stateStore)try{let e=await this._stateStore.loadCheckpoint(this.id);e&&Array.isArray(e.pendingToolCalls)&&e.pendingToolCalls.length>0&&(this._hasCheckpoint=!0,this._checkpointRestored=!1)}catch{}if(this._hasCheckpoint&&!this._checkpointRestored&&this._pendingInput){let{input:t,options:n}=this._pendingInput;this._pendingInput=null;let r=await this._stateStore.loadCheckpoint(this.id);if(!r)throw Error(`Checkpoint not found for sessionId: ${this.id}`);let i=A(r);i.sessionId!==this.id&&(i.sessionId=this.id),i.metadata={...i.metadata,_pendingUserInput:t};let a=this._requestParams??r.requestParams,o=n??e;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:o?.signal,model:this.getRuntimeModelOverride(),toolContext:o?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,Date.now()),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(this._hasCheckpoint&&!this._checkpointRestored){let t=e??this._pendingInput?.options;if(yield*this._stream(void 0,t),!this._pendingInput)return}if(this._pendingInput){let{input:e,options:t}=this._pendingInput;this._pendingInput=null,yield*this._stream(e,t)}}finally{this._isReceiving=!1}}async*receiveWithApprovals(e,t){let n=t?.toolContext,r={...n??{},approval:{...n?.approval??{},decisions:{...n?.approval?.decisions??{},...e}}};yield*this.receive({...t,toolContext:r})}async*_stream(e,t){this._ensureRuntimeConfigured(e!==void 0);let n=Date.now(),r=this.getRuntimeModelOverride(),i;if(this._hasCheckpoint&&!this._checkpointRestored){let e=await this._stateStore.loadCheckpoint(this.id);if(!e)throw Error(`Checkpoint not found for sessionId: ${this.id}`);i=A(e),i.sessionId!==this.id&&(i.sessionId=this.id);let a=this._requestParams??e.requestParams;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,n),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(e===void 0)throw Error(`Input is required to stream`);if(!this.title&&this.messages.length===0){let t=this.extractTextFromContent(e);t&&(this.title=this.createTitle(t))}let a=this.messages.filter(e=>e.role!==`system`);i=Se({sessionId:this.id,input:e,messages:a},this.agentId,this.getEffectiveSystemPrompt()??``),yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:this._requestParams}),await this._finalizeRun(i,n)}resolveModelRef(e){if(e.provider)return{provider:e.provider,modelId:e.modelId};let t=(this._modelClient?.modelRefs??[]).find(t=>t.modelId===e.modelId);if(t)return t;let n=this._modelClient?.modelRef?.provider;if(n)return{provider:n,modelId:e.modelId}}getRuntimeModelOverride(){if(this.configOverride?.model){let e=this.resolveModelRef(this.configOverride.model);if(e)return e}return this._modelOverride}_ensureRuntimeConfigured(e){if(!this._modelClient)throw Error(`Session is not configured with a model client`);if(e&&this.getEffectiveSystemPrompt()===void 0)throw Error(`Session is not configured with a system prompt`)}extractTextFromContent(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text).join(` `):e&&typeof e==`object`&&e.type===`text`&&e.text||``}createTitle(e,t=50){let n=e.trim();return n.length<=t?n:`${n.substring(0,t).trim()}...`}_recordUsage(e){this._onUsage&&this._onUsage(e)}async executeModelStream(e,t,n,r,i){if(!this._modelClient)throw Error(`Session is not configured with a model client`);let a=[],o=e.sessionId,s=new Map,c=!1,l=!1,u=e=>{let t=s.get(e);if(t)return t;let n={argsText:``,started:!1};return s.set(e,n),n},d=(e,t)=>{let n=u(e);t&&!n.toolName&&(n.toolName=t),n.started||(n.started=!0,a.push({type:`tool_call_start`,callId:e,toolName:n.toolName,sessionId:o}))},f=(e,t,n)=>{let r=u(e);t&&!r.toolName&&(r.toolName=t),typeof n==`string`&&n.length>0&&(r.argsText+=n),d(e,r.toolName),a.push({type:`tool_call_delta`,callId:e,toolName:r.toolName,argsTextDelta:n,sessionId:o})},p=()=>{c||(c=!0,a.push({type:`text_start`,sessionId:o}))},m=()=>{!c||l||(l=!0,a.push({type:`text_end`,content:e.currentResponse,sessionId:o}))},h=()=>{for(let[t,n]of s){if(!n.toolName)continue;let r={id:t,type:`function`,function:{name:n.toolName,arguments:n.argsText}};this._tools&&e.pendingToolCalls.push({toolCall:r}),a.push({type:`tool_call_end`,toolCall:r,sessionId:o})}s.clear()},g=(()=>{if(!i)return;let e={...i};return typeof e.maxOutputTokens!=`number`&&typeof i.maxTokens==`number`&&(e.maxOutputTokens=i.maxTokens),delete e.maxTokens,e})(),_=r?{model:r,messages:Re(e.messages),tools:n,signal:t,...g??{}}:{messages:Re(e.messages),tools:n,signal:t,...g??{}};try{for await(let n of this._modelClient.stream(_))if(B(t,`Session streaming`),n.type===`delta`)if(n.chunk.kind===`text`)p(),e.currentResponse+=n.chunk.text,a.push({type:`text_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.chunk.kind===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.chunk.text,a.push({type:`thinking_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_end`){let t=typeof n.chunk.text==`string`?n.chunk.text:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else n.chunk.kind===`tool_call_delta`&&f(n.chunk.callId,n.chunk.toolId,n.chunk.argsTextDelta);else if(n.type===`response_end`){m(),h(),e.lastModelStopReason=n.stopReason;let t=n.usage;if(t&&typeof t==`object`){let n=t;if(n.prompt_tokens||n.completion_tokens||n.total_tokens){let t={promptTokens:n.prompt_tokens??0,completionTokens:n.completion_tokens??0,totalTokens:n.total_tokens??0};e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.totalTokens+=t.totalTokens,this._recordUsage(t)}}}else if(n.type===`error`&&n.terminal!==!1){let t=n.error?.code??`model_error`;e.error=new V(n.error?.message??`Model error`,{code:t,retryable:n.error?.retryable}),e.shouldContinue=!1,e.stopReason=`error`}}catch(n){if(n instanceof R)throw n;if(t?.aborted)throw new R(typeof t?.reason==`string`?t.reason:`Agent execution aborted`);e.error=n instanceof Error?n:Error(String(n)),e.shouldContinue=!1,e.stopReason=`error`}finally{m(),s.size>0&&h()}return a}async executeToolCall(e,t,n,r){B(n,`Tool execution: ${e.toolCall.function.name}`);let i=r?new be(r):void 0,a=e.toolCall.id,o=e.toolCall,s=o,c=e=>({sessionId:t.sessionId,agentId:t.agentId,toolCall:e,toolContext:t});if(i){let n=await i.executePreToolUse(c(s));if(!n.allow)return e.result=`Tool execution blocked by PreToolUse hook`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};n.modifiedToolCall&&(s={...n.modifiedToolCall,id:a,type:o.type})}let l=this._tools?.get(s.function.name);if(!l)return e.result=`Tool not found: ${s.function.name}`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};try{let n=typeof s.function.arguments==`string`?JSON.parse(s.function.arguments):s.function.arguments;return e.result=await l.execute(n,t),e.isError=!1,i&&await i.executePostToolUse(c(s),e.result),{type:`tool_result`,tool_call_id:a,result:e.result,sessionId:t.sessionId}}catch(n){let r=n instanceof Error?n:Error(String(n));return e.result=r.message,e.isError=!0,i&&await i.executePostToolUseFailure(c(s),r),{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId}}}createToolExecutionContext(e,t){return{sessionId:e.sessionId,agentId:e.agentId,signal:t,usage:e.usage}}mergeStateResults(e,t){e.currentResponse=t.currentResponse,e.currentThinking=t.currentThinking,e.pendingToolCalls=t.pendingToolCalls,e.usage=t.usage,e.metadata=t.metadata}addToolResultToHistory(e,t){let n=t.result,r,i=t.isError;if(typeof n==`string`)r=n;else if(n&&typeof n==`object`&&`content`in n){let e=n;r=JSON.stringify(e.content),e.isError===!0&&(i=!0)}else r=JSON.stringify(n);e.messages.push({role:`tool`,tool_call_id:t.toolCall.id,content:r,...i?{isError:!0}:{}})}addAssistantMessageWithToolCalls(e){let t=typeof e.currentThinking==`string`?e.currentThinking:void 0;e.messages.push({role:`assistant`,content:e.currentResponse||``,tool_calls:e.pendingToolCalls.map(e=>Le(e.toolCall)),...t&&t.length>0?{reasoning_content:t}:{}})}addFinalAssistantMessage(e){e.currentResponse&&e.messages.push({role:`assistant`,content:e.currentResponse})}async*_streamWithState(e,t){let n=t.maxIterations??30,r=t.signal,i=xe(this._middlewares),a=this.createToolExecutionContext(e,r),o=this._stateStore,s=o?.savePoint??`before`,c=o?.deleteOnComplete??!0,l=t.model?{modelId:t.model.modelId,provider:t.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0;for(;e.shouldContinue;){if(B(r,`Session iteration ${e.iteration}`),e.iteration>=n){e.shouldContinue=!1,e.stopReason=`max_iterations`,yield{type:`done`,finalResponse:e.currentResponse,stopReason:`max_iterations`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(yield{type:`iteration_start`,iteration:e.iteration,sessionId:e.sessionId},e.pendingToolCalls.length>0){try{yield*this.handleToolCalls(e,a,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:o,checkpointModelConfig:l,requestParams:t.requestParams})}catch(e){if(e instanceof z)return;throw e}if(e.metadata?._pendingUserInput){let t=e.metadata._pendingUserInput;delete e.metadata._pendingUserInput,e.messages.push({role:`user`,content:t})}continue}if(e.currentResponse=``,e.currentThinking=void 0,e.pendingToolCalls=[],e.lastModelStopReason=void 0,o&&(s===`before`||s===`both`)){let n=k(e,{agentName:this._agentName,modelConfig:l,requestParams:t.requestParams});await o.saveCheckpoint(n)}let u=[],d=await i(e,async e=>{B(r,`Session model call`);let n=this.collectBlockedTools(e);e.metadata.blockedTools=n;let i=this.getToolsForModel(e);return u=await this.executeModelStream(e,r,i,t.model,t.requestParams),e});if(this.mergeStateResults(e,d),o&&(s===`after`||s===`both`)){let n=k(e,{agentName:this._agentName,modelConfig:l,requestParams:t.requestParams});await o.saveCheckpoint(n)}for(let e of u)yield e;if(B(r,`Session iteration ${e.iteration}`),e.stopReason===`error`){yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:e.pendingToolCalls.length,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`error`,modelStopReason:e.lastModelStopReason,error:Ie(e.error),usage:{...e.usage},sessionId:e.sessionId};break}if(e.pendingToolCalls.length>0)try{yield*this.handleToolCalls(e,a,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:o,checkpointModelConfig:l,requestParams:t.requestParams})}catch(e){if(e instanceof z)return;throw e}else yield*this.handleFinalResponse(e);if(!e.shouldContinue){o&&c&&await o.deleteCheckpoint(e.sessionId);break}}}static APPROVAL_REQUIRED_LEVELS=new Set([`high`,`critical`]);requiresApproval(t){return e.APPROVAL_REQUIRED_LEVELS.has(t)}async*handleToolCalls(e,t,n){let r=e.pendingToolCalls.length,i=n?.signal,a=n?.toolContextInput,o=a?.approval,s=o?.strategy??`high_risk`,c=o?.autoApprove!==!0,l=o?.decisions??{},u=e=>c?s===`all`?!0:this.requiresApproval(e):!1,d=t=>e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)}),f=t=>{d(t)||this.addAssistantMessageWithToolCalls(e)},p=t=>e.messages.some(e=>e&&typeof e==`object`&&e.role===`tool`&&e.tool_call_id===t),m=new Set,h=e=>{try{return typeof e.function.arguments==`string`?JSON.parse(e.function.arguments):e.function.arguments}catch(t){let n=t instanceof Error?t.message:String(t);return{_raw:e.function.arguments,_parseError:n}}},g=t=>{let n=[];for(let r=t;r<e.pendingToolCalls.length;r++){let t=e.pendingToolCalls[r];if(p(t.toolCall.id)||m.has(t.toolCall.id)||l[t.toolCall.id])continue;let i=this._tools?.get(t.toolCall.function.name),a=i?.riskLevel??`safe`;i&&this.isToolDisabled(t.toolCall.function.name)||i&&this.isToolBlocked(e,t.toolCall.function.name)||!i||!u(a)||(m.add(t.toolCall.id),n.push({type:`tool_approval_requested`,tool_call_id:t.toolCall.id,toolName:t.toolCall.function.name,riskLevel:a,args:h(t.toolCall),sessionId:e.sessionId}))}return n};for(let r=0;r<e.pendingToolCalls.length;r++){let o=e.pendingToolCalls[r];if(p(o.toolCall.id)){e.pendingToolCalls.splice(r,1),r--;continue}let s=o.toolCall.function.name,c=this._tools?.get(s),d=c?.riskLevel??`safe`;if(c&&this.isToolBlocked(e,s)){let t=`Tool "${s}" is blocked by middleware`;o.result=`Tool execution skipped: ${t}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:s,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}if(c&&this.isToolDisabled(s)){let t=`Tool "${s}" is disabled for this session`;o.result=`Tool execution skipped: ${t}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:s,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}if(c&&u(d)){let t=l[o.toolCall.id];if(!t){e.stopReason=`approval_required`;for(let e of g(r))yield e;let t=k(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for approval: ${s}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(t),yield{type:`requires_action`,kind:`tool_approval`,checkpoint:n?.stateStore?void 0:t,checkpointRef:n?.stateStore?{sessionId:t.sessionId,agentId:t.agentId}:void 0,sessionId:e.sessionId},this.messages=e.messages.filter(e=>e.role!==`system`),await this.save(),yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new z}if(!t.approved){let n=t.reason??`User denied approval`;o.result=`Tool execution skipped: ${n}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:o.toolCall.function.name,reason:n,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}}f(o.toolCall.id);let m=await this.executeToolCall(o,t,i,n?.hooks),h=m.type===`tool_result`&&(m.isError||m.result&&typeof m.result==`object`&&m.result.isError===!0);if(c&&c.name===`AskUserQuestion`&&h){let s=a?.askUser?.answers?.[o.toolCall.id];if(s){let a={...typeof o.toolCall.function.arguments==`string`?JSON.parse(o.toolCall.function.arguments):o.toolCall.function.arguments,answers:s};o.toolCall.function.arguments=JSON.stringify(a),yield await this.executeToolCall(o,t,i,n?.hooks),this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}else{yield m,e.stopReason=`approval_required`;let t=(typeof o.toolCall.function.arguments==`string`?JSON.parse(o.toolCall.function.arguments):o.toolCall.function.arguments)?.questions||[],r=k(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for user answers: ${c.name}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(r),this.messages=e.messages.filter(e=>e.role!==`system`),await this.save(),yield{type:`requires_action`,kind:`ask_user`,toolCallId:o.toolCall.id,questions:t,checkpoint:n?.stateStore?void 0:r,checkpointRef:n?.stateStore?{sessionId:r.sessionId,agentId:r.agentId}:void 0,sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new z}}yield m,this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--}e.pendingToolCalls=[],e.iteration++,yield{type:`iteration_end`,iteration:e.iteration-1,willContinue:!0,toolCallCount:r,usage:{...e.usage},sessionId:e.sessionId}}async*handleFinalResponse(e){e.shouldContinue=!1,e.stopReason=`final_response`,this.addFinalAssistantMessage(e),yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:0,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`final_response`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId}}async _finalizeRun(e,t){this.messages=e.messages.filter(e=>e.role!==`system`),e.usage.totalTokens>0&&this.addUsage(e.usage);let n=Date.now()-t;this.recordResponse(n),await this.save()}async save(){let e=this.toSnapshot();await this._stateStore.save(this.id,L.SESSION,e)}async load(){let e=await this._stateStore.load(this.id,L.SESSION);return e?(this.restoreFromSnapshot(e),!0):!1}setStatus(e,t){super.setStatus(e,t),this._autoSave&&this.save().catch(()=>{})}markActive(){super.markActive(),this._autoSave&&this.save().catch(()=>{})}addMessage(e){super.addMessage(e),this._autoSave&&this.save().catch(()=>{})}addUsage(e){super.addUsage(e),this._autoSave&&this.save().catch(()=>{})}recordResponse(e){super.recordResponse(e),this._autoSave&&this.save().catch(()=>{})}incrementToolCallCount(){super.incrementToolCallCount(),this._autoSave&&this.save().catch(()=>{})}setModelOverride(e){super.setModelOverride(e),this._modelOverride=this.resolveModelRef(e)??this._modelOverride,this._autoSave&&this.save().catch(()=>{})}clearModelOverride(){super.clearModelOverride(),this._modelOverride=void 0,this._autoSave&&this.save().catch(()=>{})}setSystemPromptOverride(e){super.setSystemPromptOverride(e),this._autoSave&&this.save().catch(()=>{})}clearSystemPromptOverride(){super.clearSystemPromptOverride(),this._autoSave&&this.save().catch(()=>{})}disableTools(e){super.disableTools(e),this._autoSave&&this.save().catch(()=>{})}enableAllTools(){super.enableAllTools(),this._autoSave&&this.save().catch(()=>{})}setAutoSave(e){this._autoSave=e}},ze=class extends _e{_stateStore;constructor(e){super(),this._stateStore=e}async create(e){let t=e??a(),n=Date.now(),r={id:t,createdAt:n,state:{status:`active`,updatedAt:n,lastActiveAt:n},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0}},i=new H(this._stateStore,t,r);return await i.save(),i}async get(e){let t=await this._stateStore.load(e,L.SESSION);if(t)return new H(this._stateStore,e,t)}async list(){let e=await this._stateStore.listSessions(),t=[];for(let n of e){let e=await this._stateStore.load(n,L.SESSION);if(e){let r=new H(this._stateStore,n,e);t.push(r)}}return t}async destroy(e){await this._stateStore.deleteSession(e)}},Be=class{savePoint;deleteOnComplete;constructor(e){this.savePoint=e?.savePoint??`before`,this.deleteOnComplete=e?.deleteOnComplete??!0}assertValidStorageSegment(e,t){if(!t)throw Error(`${e} must be a non-empty string`);if(t===`.`||t===`..`)throw Error(`${e} must not be "." or ".."`);if(t.includes(`/`)||t.includes(`\\`))throw Error(`${e} must not contain path separators`);if(t.includes(`\0`))throw Error(`${e} must not contain NUL bytes`)}async save(e,t,n){let r=this.buildPath(e,t),i=JSON.stringify(n,null,2);await this._write(r,i)}async load(e,t){let n=this.buildPath(e,t),r=await this._read(n);if(r!==void 0)try{return JSON.parse(r)}catch{return}}async delete(e,t){let n=this.buildPath(e,t);await this._delete(n)}async deleteSession(e){let t=this.buildPrefix(e),n=await this._list(t);await Promise.all(n.map(e=>this._delete(e)))}async listKeys(e){let t=this.buildPrefix(e);return(await this._list(t)).map(t=>this.extractKey(e,t))}async exists(e,t){let n=this.buildPath(e,t);return this._exists(n)}async saveCheckpoint(e){let t={_meta:{description:`GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY`,savedAt:new Date().toISOString(),agentId:e.agentId,agentName:e.agentName,sessionId:e.sessionId,iteration:e.iteration,phase:e.phase,status:e.status,messageCount:e.messages.length,toolCallsPending:e.pendingToolCalls?.length??0},checkpoint:e};await this.save(e.sessionId,L.CHECKPOINT,t)}async loadCheckpoint(e){return(await this.load(e,L.CHECKPOINT))?.checkpoint}async deleteCheckpoint(e){await this.delete(e,L.CHECKPOINT)}async listCheckpoints(){let e=await this.listSessions(),t=[];for(let n of e){let e=await this.loadCheckpoint(n);e&&t.push(e)}return t}async listSessions(){let e=await this._list(``),t=new Set;for(let n of e){let e=this.extractSessionId(n);e&&t.add(e)}return Array.from(t)}buildPath(e,t){return this.assertValidStorageSegment(`sessionId`,e),this.assertValidStorageSegment(`key`,t),`${e}/${t}`}buildPrefix(e){return this.assertValidStorageSegment(`sessionId`,e),`${e}/`}extractKey(e,t){let n=this.buildPrefix(e);return t.startsWith(n)?t.slice(n.length):t}extractSessionId(e){let t=e.split(`/`);return t.length>0?t[0]:void 0}},Ve=class extends Be{baseDir;constructor(e){super(e),this.baseDir=m.resolve(e.dir),this.ensureDir(this.baseDir)}async _write(e,t){let n=this.toFilePath(e);this.ensureDir(m.dirname(n)),w(n,t,`utf-8`)}async _read(e){let t=this.toFilePath(e);try{return _(t)?y(t,`utf-8`):void 0}catch{return}}async _delete(e){let t=this.toFilePath(e);_(t)&&x(t);let n=m.dirname(t);if(_(n))try{b(n).length===0&&x(n,{recursive:!0})}catch{}}async _exists(e){return _(this.toFilePath(e))}async _list(e){let t=[];if(!_(this.baseDir))return t;let n=b(this.baseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let r of n){if(e&&!r.startsWith(e.split(`/`)[0]))continue;let n=m.join(this.baseDir,r),i=this.listJsonFiles(n);for(let n of i){let i=`${r}/${m.basename(n,`.json`)}`;(!e||i.startsWith(e))&&t.push(i)}}return t}toFilePath(e){return m.join(this.baseDir,`${e}.json`)}ensureDir(e){_(e)||v(e,{recursive:!0})}listJsonFiles(e){return _(e)?b(e).filter(e=>e.endsWith(`.json`)).map(t=>m.join(e,t)):[]}getBaseDir(){return this.baseDir}clear(){_(this.baseDir)&&(x(this.baseDir,{recursive:!0}),v(this.baseDir,{recursive:!0}))}},He=class extends Be{store=new Map;constructor(e){super(e)}async _write(e,t){this.store.set(e,t)}async _read(e){return this.store.get(e)}async _delete(e){this.store.delete(e)}async _exists(e){return this.store.has(e)}async _list(e){let t=[];for(let n of this.store.keys())(e===``||n.startsWith(e))&&t.push(n);return t}clear(){this.store.clear()}stats(){let e=new Set;for(let t of this.store.keys()){let n=this.extractSessionId(t);n&&e.add(n)}return{entryCount:this.store.size,sessionCount:e.size}}},Ue=class{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];_middlewareCounter=0;_middlewareTools=new Map;constructor(e){this.id=e.id??crypto.randomUUID(),this.name=e.name,this.systemPrompt=e.systemPrompt,this.createdAt=Date.now(),this._model=e.model,this._tools=e.tools,this._stateStore=e.stateStore??new He({savePoint:`before`}),this._sessionManager=new ze(this._stateStore)}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get modelRefs(){let e=this._model.modelRefs;if(Array.isArray(e))return e;let t=this._model.modelRef;return t?[t]:[]}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession(e){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let t=await this._sessionManager.create(e?.sessionId);if(!this._stateStore)throw Error(`StateStore is required to create sessions`);let n=t.toSnapshot();return new H(this._stateStore,t.id,n,{...e,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map(e=>e.fn),hasCheckpoint:!1,emitSessionCreatedEvent:!0})}async resumeSession(e,t){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let n=await this._sessionManager.get(e);if(!n)throw Error(`Session not found: ${e}`);let r=!!await this._stateStore?.loadCheckpoint(e);if(!this._stateStore)throw Error(`StateStore is required to resume sessions`);let i=n.toSnapshot();return new H(this._stateStore,n.id,i,{...t,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map(e=>e.fn),hasCheckpoint:r,emitSessionCreatedEvent:!1})}use(e,t){let n=t??e.__middlewareName??`middleware_${this._middlewareCounter++}`;if(this._middlewares.some(e=>e.name===n))throw Error(`Middleware with name "${n}" already exists`);let r={name:n,fn:e};return this._middlewares.push(r),e.__createTools&&typeof e.__createTools==`function`&&this._registerMiddlewareTools(n,e.__createTools),()=>{this.removeMiddleware(n)}}removeMiddleware(e){let t=-1,n;return typeof e==`string`?(t=this._middlewares.findIndex(t=>t.name===e),n=e):(t=this._middlewares.findIndex(t=>t.fn===e),t>-1&&(n=this._middlewares[t].name)),t>-1&&n?(this._unregisterMiddlewareTools(n),this._middlewares.splice(t,1),!0):!1}clearMiddlewares(){for(let e of this._middlewareTools.keys())this._unregisterMiddlewareTools(e);this._middlewares=[]}get middlewares(){return[...this._middlewares]}get middlewareNames(){return this._middlewares.map(e=>e.name)}setModel(e){(e=>!!(e&&typeof e==`object`&&typeof e.provider==`string`&&typeof e.modelId==`string`&&typeof e.stream!=`function`))(e)?this._modelOverride=e:(this._model=e,this._modelOverride=void 0)}_getNamespacedToolName(e,t){return`${e}:${t}`}_registerMiddlewareTools(e,t){if(!this._tools)return;let n=t(),r=[];for(let t of n){let n=this._getNamespacedToolName(e,t.name),i=Object.create(Object.getPrototypeOf(t));Object.assign(i,t),Object.defineProperty(i,`name`,{value:n,writable:!1,configurable:!0});try{this._tools.register(i),r.push(n)}catch(e){console.warn(`Failed to register tool ${n}:`,e)}}r.length>0&&this._middlewareTools.set(e,r)}_unregisterMiddlewareTools(e){if(!this._tools)return;let t=this._middlewareTools.get(e);if(t){for(let e of t)this._tools.unregister(e);this._middlewareTools.delete(e)}}};function We(e){return{content:[{type:`text`,text:e}]}}function U(e){return{content:[{type:`text`,text:e}],isError:!0}}function Ge(e,t){return{content:[{type:`image`,data:e,mimeType:t}]}}var W=class{riskLevel=`safe`},Ke=class extends W{name=`AskUserQuestion`;riskLevel=`safe`;description=`Use this tool when you need to ask the user questions during execution. This allows you to:
|
|
113
|
+
1. Gather user preferences or requirements
|
|
114
|
+
2. Clarify ambiguous instructions
|
|
115
|
+
3. Get decisions on implementation choices as you work
|
|
116
|
+
4. Offer choices to the user about what direction to take
|
|
117
|
+
|
|
118
|
+
Usage notes:
|
|
119
|
+
- Users will always be able to select "Other" to provide custom text input
|
|
120
|
+
- Use multiSelect: true to allow multiple answers to be selected for a question
|
|
121
|
+
- If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`;parameters={type:`object`,properties:{questions:{type:`array`,items:{type:`object`,properties:{question:{type:`string`,description:`The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"`},header:{type:`string`,maxLength:12,description:`Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".`},options:{type:`array`,items:{type:`object`,properties:{label:{type:`string`,description:`The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice.`},description:{type:`string`,description:`Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.`}},required:[`label`,`description`]},minItems:2,maxItems:4,description:`The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no 'Other' option, that will be provided automatically.`},multiSelect:{type:`boolean`,description:`Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive.`}},required:[`question`,`header`,`options`,`multiSelect`]},minItems:1,maxItems:4,description:`Questions to ask the user (1-4 questions)`},answers:{type:`object`,additionalProperties:{type:[`string`,`array`]},description:`User answers collected by the permission component`}},required:[`questions`]};async execute(e){let{questions:t,answers:n}=this.validateArgs(e);if(!n||Object.keys(n).length===0)return{content:[{type:`text`,text:`No answers provided. This tool requires user interaction to collect responses.`}],isError:!0};let r=[];for(let e=0;e<t.length;e++){let i=t[e],a=n[String(e)];if(a){let e=Array.isArray(a)?a.join(`, `):a;r.push(`${i.header}: ${e}`)}}let i=r.length>0?`User responses: ${r.join(`; `)}`:`No answers received`;return{content:[{type:`text`,text:i}],structuredContent:{success:!0,answers:n,message:i}}}validateArgs(e){let t=e.questions;if(!Array.isArray(t))throw TypeError(`questions is required and must be an array`);if(t.length<1||t.length>4)throw Error(`questions must contain 1-4 items`);let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(typeof r!=`object`||!r)throw TypeError(`questions[${e}] must be an object`);let{question:i,header:a,options:o,multiSelect:s}=r;if(typeof i!=`string`||!i.trim())throw Error(`questions[${e}].question is required and must be a non-empty string`);if(typeof a!=`string`||!a.trim())throw Error(`questions[${e}].header is required and must be a non-empty string`);if(a.length>12)throw Error(`questions[${e}].header must be at most 12 characters`);if(!Array.isArray(o))throw TypeError(`questions[${e}].options must be an array`);if(o.length<2||o.length>4)throw Error(`questions[${e}].options must contain 2-4 items`);if(typeof s!=`boolean`)throw TypeError(`questions[${e}].multiSelect is required and must be a boolean`);let c=[];for(let t=0;t<o.length;t++){let n=o[t];if(typeof n!=`object`||!n)throw TypeError(`questions[${e}].options[${t}] must be an object`);let{label:r,description:i}=n;if(typeof r!=`string`||!r.trim())throw Error(`questions[${e}].options[${t}].label is required and must be a non-empty string`);if(typeof i!=`string`||!i.trim())throw Error(`questions[${e}].options[${t}].description is required and must be a non-empty string`);c.push({label:r.trim(),description:i.trim()})}n.push({question:i.trim(),header:a.trim(),options:c,multiSelect:!!s})}let r;if(e.answers&&typeof e.answers==`object`&&e.answers!==null){r={};for(let[t,n]of Object.entries(e.answers))typeof n==`string`?r[t]=n:Array.isArray(n)?r[t]=n.map(e=>String(e)):r[t]=String(n)}return{questions:n,answers:r}}};const qe=`0.40.0`,G=[`bash`,`c`,`cpp`,`csharp`,`css`,`elixir`,`go`,`haskell`,`html`,`java`,`javascript`,`json`,`kotlin`,`lua`,`nix`,`php`,`python`,`ruby`,`rust`,`scala`,`solidity`,`swift`,`typescript`,`tsx`,`yaml`],K=1*1024*1024,Je={"darwin-arm64":{arch:`aarch64`,os:`apple-darwin`},"darwin-x64":{arch:`x86_64`,os:`apple-darwin`},"linux-arm64":{arch:`aarch64`,os:`unknown-linux-gnu`},"linux-x64":{arch:`x86_64`,os:`unknown-linux-gnu`},"win32-x64":{arch:`x86_64`,os:`pc-windows-msvc`},"win32-arm64":{arch:`aarch64`,os:`pc-windows-msvc`},"win32-ia32":{arch:`i686`,os:`pc-windows-msvc`}};function q(e){try{return S(e).size>1e4}catch{return!1}}function Ye(){return{"darwin-arm64":`@ast-grep/cli-darwin-arm64`,"darwin-x64":`@ast-grep/cli-darwin-x64`,"linux-arm64":`@ast-grep/cli-linux-arm64-gnu`,"linux-x64":`@ast-grep/cli-linux-x64-gnu`,"win32-x64":`@ast-grep/cli-win32-x64-msvc`,"win32-arm64":`@ast-grep/cli-win32-arm64-msvc`,"win32-ia32":`@ast-grep/cli-win32-ia32-msvc`}[`${h.platform}-${h.arch}`]??null}function Xe(){try{return i(import.meta.url)(`@ast-grep/cli/package.json`).version}catch{return qe}}function Ze(){if(h.platform===`win32`){let e=h.env.LOCALAPPDATA||h.env.APPDATA||m.join(T(),`AppData`,`Local`);return m.join(e,`goat-chain`,`bin`)}let e=h.env.XDG_CACHE_HOME||m.join(T(),`.cache`);return m.join(e,`goat-chain`,`bin`)}function Qe(){return h.platform===`win32`?`ast-grep.exe`:`ast-grep`}function $e(){return h.platform===`win32`?`sg.exe`:`sg`}function et(){let e=[Qe(),$e()];return Array.from(new Set(e))}function tt(){let e=Ze();for(let t of et()){let n=m.join(e,t);if(_(n)&&q(n))return n}return null}async function nt(e,t){let n=h.platform===`win32`,{exitCode:r,stderr:i}=await ut(n?`powershell`:`unzip`,n?[`-command`,`Expand-Archive -Path '${e}' -DestinationPath '${t}' -Force`]:[`-o`,e,`-d`,t]);if(r!==0){let e=n?`Ensure PowerShell is available on your system.`:`Please install 'unzip' (e.g., apt install unzip, brew install unzip).`;throw Error(`zip extraction failed (exit ${r}): ${i}\n\n${e}`)}}async function rt(e=qe){let t=`${h.platform}-${h.arch}`,n=Je[t];if(!n)return console.error(`[goat-chain] Unsupported platform for ast-grep: ${t}`),null;let r=Ze(),i=Qe(),a=m.join(r,i);if(_(a))return a;let{arch:o,os:s}=n,c=`app-${o}-${s}.zip`,l=`https://github.com/ast-grep/ast-grep/releases/download/${e}/${c}`;console.log(`[goat-chain] Downloading ast-grep binary...`);try{_(r)||v(r,{recursive:!0});let e=await fetch(l,{redirect:`follow`});if(!e.ok)throw Error(`HTTP ${e.status}: ${e.statusText}`);let t=m.join(r,c),n=await e.arrayBuffer();return await p(t,Buffer.from(n)),await nt(t,r),_(t)&&C(t),h.platform!==`win32`&&_(a)&&g(a,493),console.log(`[goat-chain] ast-grep binary ready.`),a}catch(e){return console.error(`[goat-chain] Failed to download ast-grep: ${e instanceof Error?e.message:e}`),null}}async function it(){return tt()||rt(Xe())}function at(){let e=Qe(),t=tt();if(t&&q(t))return t;try{let t=i(import.meta.url).resolve(`@ast-grep/cli/package.json`),n=m.dirname(t),r=m.join(n,e);if(_(r)&&q(r))return r}catch{}let n=Ye();if(n)try{let e=i(import.meta.url).resolve(`${n}/package.json`),t=m.dirname(e),r=h.platform===`win32`?`ast-grep.exe`:`ast-grep`,a=m.join(t,r);if(_(a)&&q(a))return a}catch{}if(h.platform===`darwin`){for(let e of[`/opt/homebrew/bin/ast-grep`,`/usr/local/bin/ast-grep`,`/opt/homebrew/bin/sg`,`/usr/local/bin/sg`])if(_(e)&&q(e))return e}return null}let J=null,ot=null;function st(){if(J!==null)return J;let e=at();return e?(J=e,e):`sg`}function ct(e){J=e}async function lt(){return J!==null&&_(J)?J:ot||(ot=(async()=>{let e=at();if(e&&_(e))return J=e,ct(e),e;let t=await it();return t?(J=t,ct(t),t):null})(),ot)}function ut(e,t){return new Promise((n,r)=>{let i=E(e,t,{stdio:[`ignore`,`pipe`,`pipe`]}),a=``,o=``;i.stdout?.on(`data`,e=>{a+=e.toString()}),i.stderr?.on(`data`,e=>{o+=e.toString()}),i.on(`error`,e=>{r(e)}),i.on(`close`,e=>{n({exitCode:e,stdout:a,stderr:o})})})}function dt(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=!1,c=[],l=0,u=[],d=0;console.log(`[goat-chain] Spawning process:`,e,t,r??h.cwd());let f=E(e,t,{cwd:r,stdio:[`ignore`,`pipe`,`pipe`]}),p=setTimeout(()=>{o=!0,f.kill()},n);f.stdout?.on(`data`,e=>{if(l>=K){s=!0;return}let t=K-l;e.length>t?(c.push(e.subarray(0,t)),l+=t,s=!0):(c.push(e),l+=e.length)}),f.stderr?.on(`data`,e=>{if(d>=K)return;let t=K-d;e.length>t?(u.push(e.subarray(0,t)),d+=t):(u.push(e),d+=e.length)}),f.on(`error`,e=>{clearTimeout(p),a(e)}),f.on(`close`,e=>{clearTimeout(p),i({stdout:Buffer.concat(c).toString(),stderr:Buffer.concat(u).toString(),exitCode:e,timedOut:o,outputTruncated:s})})})}function ft(e){return e.code===`ENOENT`||e.message?.includes(`ENOENT`)||e.message?.includes(`not found`)}function pt(e,t){try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{if(!t)return[]}try{let t=e.lastIndexOf(`}`);if(t>0){let n=e.lastIndexOf(`},`,t);if(n>0){let t=`${e.substring(0,n+1)}]`,r=JSON.parse(t);return Array.isArray(r)?r:[]}}}catch{return null}return null}async function mt(e){console.log(`[goat-chain] Running ast-grep command...`,e);let t=e.jsonOutput!==!1,n=[`run`,`-p`,e.pattern,`--lang`,e.lang];if(t&&n.push(`--json=compact`),e.rewrite&&(n.push(`-r`,e.rewrite),e.updateAll&&n.push(`--update-all`)),e.context&&e.context>0&&n.push(`-C`,String(e.context)),e.globs)for(let t of e.globs)n.push(`--globs`,t);let r=e.paths&&e.paths.length>0?e.paths:[`.`];n.push(...r);let i=3e5,a=!!e.binaryPath,o=e.binaryPath??st();if(!a&&!_(o)&&o!==`sg`){let e=await lt();e&&(o=e)}let s;try{s=await dt(o,n,i,e.cwd)}catch(t){let n=t;if(!a&&ft(n)){let t=await it();return t?(J=t,ct(t),mt(e)):{matches:[],totalMatches:0,truncated:!1,error:`ast-grep CLI binary not found.
|
|
122
|
+
|
|
123
|
+
Auto-download failed. Manual install options:
|
|
124
|
+
bun add -D @ast-grep/cli
|
|
125
|
+
cargo install ast-grep --locked
|
|
126
|
+
brew install ast-grep`}}return{matches:[],totalMatches:0,truncated:!1,error:`Failed to spawn ast-grep: ${n.message}`}}if(s.timedOut)return{matches:[],totalMatches:0,truncated:!0,truncatedReason:`timeout`,error:`Search timeout after ${i}ms`,exitCode:s.exitCode,stderr:s.stderr};if(!t){let e=s.stdout.trim(),t=s.stderr.trim();if(s.exitCode!==0){let n=t||e||`ast-grep exited with code ${s.exitCode}`;return{matches:[],totalMatches:0,truncated:s.outputTruncated,truncatedReason:s.outputTruncated?`max_output_bytes`:void 0,error:n,exitCode:s.exitCode,stderr:s.stderr}}return{matches:[],totalMatches:0,truncated:s.outputTruncated,truncatedReason:s.outputTruncated?`max_output_bytes`:void 0,exitCode:s.exitCode,stderr:s.stderr}}if(s.exitCode!==0&&s.stdout.trim()===``)return s.stderr.includes(`No files found`)?{matches:[],totalMatches:0,truncated:!1,exitCode:s.exitCode,stderr:s.stderr}:s.stderr.trim()?{matches:[],totalMatches:0,truncated:!1,error:s.stderr.trim(),exitCode:s.exitCode,stderr:s.stderr}:{matches:[],totalMatches:0,truncated:!1,exitCode:s.exitCode,stderr:s.stderr};if(!s.stdout.trim())return{matches:[],totalMatches:0,truncated:!1,exitCode:s.exitCode,stderr:s.stderr};let c=s.outputTruncated||Buffer.byteLength(s.stdout)>=K,l=pt(s.stdout,c);if(l===null)return{matches:[],totalMatches:0,truncated:!0,truncatedReason:`max_output_bytes`,error:`Output too large and could not be parsed`,exitCode:s.exitCode,stderr:s.stderr};let u=l.length,d=u>500;return{matches:d?l.slice(0,500):l,totalMatches:u,truncated:c||d,truncatedReason:c?`max_output_bytes`:d?`max_matches`:void 0,exitCode:s.exitCode,stderr:s.stderr}}function ht(e,t){if(!e||!t)return e;let n=m.relative(t,e);return n&&!n.startsWith(`..`)&&!m.isAbsolute(n)?n:e}function gt(e){return e.truncatedReason===`max_matches`?`showing first ${e.matches.length} of ${e.totalMatches}`:e.truncatedReason===`max_output_bytes`?`output exceeded 1MB limit`:e.truncatedReason===`timeout`?`search timed out`:`output truncated`}function _t(e){let t=(e.lines??e.text??``).trim();return t?` ${t}`:``}function vt(e,t){if(e.error)return`Error: ${e.error}`;if(e.matches.length===0)return`No matches found`;let n=[];e.truncated&&n.push(`Results truncated (${gt(e)})\n`),n.push(`Found ${e.matches.length} match(es)${e.truncated?` (truncated from ${e.totalMatches})`:``}:\n`);for(let r of e.matches){let e=(r.range?.start?.line??0)+1,i=(r.range?.start?.column??0)+1,a=`${ht(r.file,t)}:${e}:${i}`;n.push(a);let o=_t(r);o&&n.push(o),n.push(``)}return n.join(`
|
|
127
|
+
`)}function yt(e,t,n){if(e.error)return`Error: ${e.error}`;if(e.matches.length===0)return`No matches found to replace`;let r=t?`[DRY RUN] `:``,i=[];e.truncated&&i.push(`Results truncated (${gt(e)})\n`),i.push(`${r}${e.matches.length} replacement(s):\n`);for(let t of e.matches){let e=(t.range?.start?.line??0)+1,r=(t.range?.start?.column??0)+1,a=`${ht(t.file,n)}:${e}:${r}`;i.push(a);let o=t.text?.trim();o&&i.push(` ${o}`),i.push(``)}return t&&i.push(`Use dryRun=false to apply changes`),i.join(`
|
|
128
|
+
`)}function bt(e,t){let n=e.trim();return t===`python`&&(n.startsWith(`class `)&&n.endsWith(`:`)||(n.startsWith(`def `)||n.startsWith(`async def `))&&n.endsWith(`:`))?`Hint: Remove trailing colon. Try: "${n.slice(0,-1)}"`:[`javascript`,`typescript`,`tsx`].includes(t)&&/^(?:export\s+)?(?:async\s+)?function\s+\$[A-Z_]+\s*$/i.test(n)?`Hint: Function patterns need params and body. Try "function $NAME($$$) { $$$ }"`:null}var xt=class extends W{name=`ast_grep_replace`;riskLevel=`high`;description=`Replace code patterns across filesystem with AST-aware rewriting. Dry-run by default.
|
|
129
|
+
|
|
130
|
+
Usage notes:
|
|
131
|
+
- Use meta-variables in rewrite to preserve matched content
|
|
132
|
+
- Example: pattern='console.log($MSG)' rewrite='logger.info($MSG)'
|
|
133
|
+
- Set dryRun=false to apply changes`;parameters={type:`object`,properties:{pattern:{type:`string`,description:`AST pattern to match.`},rewrite:{type:`string`,description:`Replacement pattern (can use $VAR from pattern).`},lang:{type:`string`,enum:[...G],description:`Target language (ast-grep language identifier).`},paths:{type:`array`,items:{type:`string`},description:`Paths to search (default: ["."]).`},globs:{type:`array`,items:{type:`string`},description:`Include/exclude globs (prefix ! to exclude).`},dryRun:{type:`boolean`,description:`Preview changes without applying (default: true).`}},required:[`pattern`,`rewrite`,`lang`]};cwd;astGrepPath;constructor(e){super(),this.cwd=e?.cwd??h.cwd(),this.astGrepPath=e?.astGrepPath}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let t=this.validateArgs(e),n=t.dryRun!==!1,r=await mt({pattern:t.pattern,rewrite:t.rewrite,lang:t.lang,paths:t.paths,globs:t.globs,updateAll:!1,cwd:this.cwd,binaryPath:this.astGrepPath});if(!n&&!r.error&&r.matches.length>0){let e=await mt({pattern:t.pattern,rewrite:t.rewrite,lang:t.lang,paths:t.paths,globs:t.globs,updateAll:!0,jsonOutput:!1,cwd:this.cwd,binaryPath:this.astGrepPath});if(e.error||e.exitCode!==null&&e.exitCode!==0){let t=`Error: ${e.error||e.stderr?.trim()||`ast-grep replace failed${e.exitCode===null?``:` (exit ${e.exitCode})`}`}`,n={exitCode:e.exitCode??r.exitCode??null,output:t,matches:r.matches,matchCount:r.totalMatches,stderr:e.stderr?.trim()||r.stderr?.trim()||void 0,truncated:r.truncated,truncatedReason:r.truncatedReason,timedOut:r.truncatedReason===`timeout`};return{content:[{type:`text`,text:t}],structuredContent:n,isError:!0}}let i=yt(r,n,this.cwd),a={exitCode:e.exitCode??r.exitCode??null,output:i,matches:r.matches,matchCount:r.totalMatches,stderr:e.stderr?.trim()||r.stderr?.trim()||void 0,truncated:r.truncated,truncatedReason:r.truncatedReason,timedOut:r.truncatedReason===`timeout`};return{content:[{type:`text`,text:i}],structuredContent:a,isError:!1}}let i=yt(r,n,this.cwd),a={exitCode:r.exitCode??null,output:i,matches:r.matches,matchCount:r.totalMatches,stderr:r.stderr?.trim()||void 0,truncated:r.truncated,truncatedReason:r.truncatedReason,timedOut:r.truncatedReason===`timeout`};return{content:[{type:`text`,text:i}],structuredContent:a,isError:!!r.error}}validateArgs(e){let t=e.pattern,n=e.rewrite,r=e.lang;if(typeof t!=`string`||!t.trim())throw Error(`pattern is required and must be a non-empty string`);if(typeof n!=`string`||!n.trim())throw Error(`rewrite is required and must be a non-empty string`);if(typeof r!=`string`||!r.trim())throw Error(`lang is required and must be a non-empty string`);if(!G.includes(r))throw Error(`lang must be one of: ${G.join(`, `)}`);let i={pattern:t.trim(),rewrite:n.trim(),lang:r.trim()};if(e.paths!==void 0&&e.paths!==null){if(!Array.isArray(e.paths)||e.paths.some(e=>typeof e!=`string`))throw TypeError(`paths must be an array of strings`);i.paths=e.paths.map(e=>e.trim()).filter(Boolean)}if(e.globs!==void 0&&e.globs!==null){if(!Array.isArray(e.globs)||e.globs.some(e=>typeof e!=`string`))throw TypeError(`globs must be an array of strings`);i.globs=e.globs.map(e=>e.trim()).filter(Boolean)}return e.dryRun!==void 0&&e.dryRun!==null&&(i.dryRun=!!e.dryRun),i}};const St=5e3;var Ct=class extends W{name=`ast_grep_search`;description=`Search code patterns across filesystem using AST-aware matching. Supports 25 languages.
|
|
134
|
+
|
|
135
|
+
Usage notes:
|
|
136
|
+
- Use meta-variables: $VAR (single node), $$$ (multiple nodes)
|
|
137
|
+
- Patterns must be complete AST nodes (valid code)
|
|
138
|
+
- For functions, include params and body: 'export async function $NAME($$$) { $$$ }' not 'export async function $NAME'
|
|
139
|
+
- Examples: 'console.log($MSG)', 'def $FUNC($$$):', 'async function $NAME($$$)'`;parameters={type:`object`,properties:{pattern:{type:`string`,description:`AST pattern with meta-variables ($VAR, $$$). Must be complete AST node.`},lang:{type:`string`,enum:[...G],description:`Target language (ast-grep language identifier).`},paths:{type:`array`,items:{type:`string`},description:`Paths to search (default: ["."]).`},globs:{type:`array`,items:{type:`string`},description:`Include/exclude globs (prefix ! to exclude).`},context:{type:`number`,description:`Context lines around match.`}},required:[`pattern`,`lang`]};cwd;astGrepPath;constructor(e){super(),this.cwd=e?.cwd??h.cwd(),this.astGrepPath=e?.astGrepPath}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let t=this.validateArgs(e),n=await mt({pattern:t.pattern,lang:t.lang,paths:t.paths,globs:t.globs,context:t.context,cwd:this.cwd,binaryPath:this.astGrepPath}),r=vt(n,this.cwd);if(n.matches.length===0&&!n.error){let e=bt(t.pattern,t.lang);e&&(r+=`\n\n${e}`)}let i=n.truncated,a=n.truncatedReason;r.length>St&&(r=r.slice(0,St)+`
|
|
140
|
+
|
|
141
|
+
... [output truncated due to length limit]`,i=!0,a||=`max_output_bytes`);let o={exitCode:n.exitCode??null,output:r,matches:n.matches,matchCount:n.totalMatches,stderr:n.stderr?.trim()||void 0,truncated:i,truncatedReason:a,timedOut:n.truncatedReason===`timeout`};return{content:[{type:`text`,text:r}],structuredContent:o,isError:!!n.error}}validateArgs(e){let t=e.pattern,n=e.lang;if(typeof t!=`string`||!t.trim())throw Error(`pattern is required and must be a non-empty string`);if(typeof n!=`string`||!n.trim())throw Error(`lang is required and must be a non-empty string`);if(!G.includes(n))throw Error(`lang must be one of: ${G.join(`, `)}`);let r={pattern:t.trim(),lang:n.trim()};if(e.paths!==void 0&&e.paths!==null){if(!Array.isArray(e.paths)||e.paths.some(e=>typeof e!=`string`))throw TypeError(`paths must be an array of strings`);r.paths=e.paths.map(e=>e.trim()).filter(Boolean)}if(e.globs!==void 0&&e.globs!==null){if(!Array.isArray(e.globs)||e.globs.some(e=>typeof e!=`string`))throw TypeError(`globs must be an array of strings`);r.globs=e.globs.map(e=>e.trim()).filter(Boolean)}if(e.context!==void 0&&e.context!==null){if(typeof e.context!=`number`||!Number.isFinite(e.context)||e.context<0)throw TypeError(`context must be a non-negative number`);r.context=Math.floor(e.context)}return r}};const wt=3e4,Tt=12e4;var Et=class extends W{name=`Bash`;riskLevel=`critical`;description=`Executes a given bash command in a persistent shell session with optional timeout.
|
|
142
|
+
|
|
143
|
+
Usage notes:
|
|
144
|
+
- The command argument is required.
|
|
145
|
+
- You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes).
|
|
146
|
+
- If not specified, commands will timeout after 120000ms (2 minutes).
|
|
147
|
+
- If the output exceeds 30000 characters, it will be truncated.
|
|
148
|
+
- You can use the run_in_background parameter to run the command in the background.`;parameters={type:`object`,properties:{command:{type:`string`,description:`The command to execute`},timeout:{type:`number`,description:`Optional timeout in milliseconds (max 600000)`},description:{type:`string`,description:`Clear, concise description of what this command does in 5-10 words`},run_in_background:{type:`boolean`,description:`Set to true to run this command in the background`}},required:[`command`]};cwd;shell;constructor(e){super(),this.cwd=e?.cwd??h.cwd(),this.shell=e?.shell??(h.platform===`win32`?`cmd.exe`:`/bin/bash`)}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let{command:t,timeout:n=Tt,run_in_background:r}=this.validateArgs(e),i=r?await this.executeBackground(t):await this.executeSync(t,n),a=[];return i.stdout&&a.push(i.stdout),i.stderr&&a.push(`[stderr]:\n${i.stderr}`),i.timedOut&&a.push(`[Command timed out after ${n}ms]`),i.background&&a.push(`[Running in background with PID ${i.pid}]`),{content:[{type:`text`,text:a.join(`
|
|
149
|
+
`)||`[No output]`}],structuredContent:i,isError:i.exitCode!==0&&i.exitCode!==null&&!i.background}}validateArgs(e){let t=e.command;if(typeof t!=`string`||!t.trim())throw Error(`Command is required and must be a non-empty string`);let n=Tt;if(e.timeout!==void 0){if(typeof e.timeout!=`number`)throw TypeError(`Timeout must be a number`);n=Math.min(Math.max(0,e.timeout),6e5)}return{command:t.trim(),timeout:n,description:typeof e.description==`string`?e.description:void 0,run_in_background:e.run_in_background===!0}}executeSync(e,t){return new Promise(n=>{let r=``,i=``,a=!1,o=!1,s=h.platform===`win32`?[`/c`,e]:[`-c`,e],c=E(this.shell,s,{cwd:this.cwd,env:h.env,stdio:[`ignore`,`pipe`,`pipe`]}),l=setTimeout(()=>{a=!0,c.kill(`SIGTERM`),setTimeout(()=>{c.killed||c.kill(`SIGKILL`)},5e3)},t);c.stdout?.on(`data`,e=>{let t=e.toString();r.length+t.length>wt?(r+=t.slice(0,wt-r.length),o=!0):r+=t}),c.stderr?.on(`data`,e=>{let t=e.toString();i.length+t.length>wt?(i+=t.slice(0,wt-i.length),o=!0):i+=t}),c.on(`close`,e=>{clearTimeout(l),n({exitCode:e,stdout:o?`${r}\n... [output truncated]`:r,stderr:i,truncated:o,timedOut:a,background:!1})}),c.on(`error`,e=>{clearTimeout(l),n({exitCode:1,stdout:``,stderr:`Failed to execute command: ${e.message}`,truncated:!1,timedOut:!1,background:!1})})})}executeBackground(e){return new Promise(t=>{let n=h.platform===`win32`?[`/c`,e]:[`-c`,e],r=E(this.shell,n,{cwd:this.cwd,env:h.env,stdio:`ignore`,detached:!0});r.unref(),t({exitCode:null,stdout:`Command started in background with PID ${r.pid}`,stderr:``,truncated:!1,timedOut:!1,background:!0,pid:r.pid})})}},Dt=class extends W{name=`Edit`;riskLevel=`high`;description=`Performs exact string replacements in files.
|
|
150
|
+
|
|
151
|
+
Usage notes:
|
|
152
|
+
- When editing, preserve the exact indentation (tabs/spaces) from the original file
|
|
153
|
+
- The edit will FAIL if old_string is not unique in the file unless replace_all is true
|
|
154
|
+
- Use replace_all for replacing/renaming strings across the entire file
|
|
155
|
+
- old_string and new_string must be different
|
|
156
|
+
- ALWAYS prefer editing existing files over creating new ones`;parameters={type:`object`,properties:{file_path:{type:`string`,description:`The absolute path to the file to modify`},old_string:{type:`string`,description:`The text to replace`},new_string:{type:`string`,description:`The text to replace it with (must be different from old_string)`},replace_all:{type:`boolean`,description:`Replace all occurrences of old_string (default false)`}},required:[`file_path`,`old_string`,`new_string`]};cwd;constructor(e){super(),this.cwd=e?.cwd??h.cwd()}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let{file_path:t,old_string:n,new_string:r,replace_all:i}=this.validateArgs(e),a=m.isAbsolute(t)?t:m.resolve(this.cwd,t);try{if((await f(a)).isDirectory())return U(`Path is a directory, not a file: ${a}`)}catch(e){if(e.code===`ENOENT`)return U(`File not found: ${a}`);throw e}let o=await l(a,`utf-8`),s=this.countOccurrences(o,n);if(s===0)return U(`old_string not found in file: ${a}\n\nSearched for:\n${this.truncateForError(n)}`);if(s>1&&!i)return U(`old_string is not unique in the file (found ${s} occurrences). Either provide more context to make it unique, or set replace_all: true to replace all occurrences.`);let c,u;if(i)c=o.split(n).join(r),u=s;else{let e=o.indexOf(n);c=o.slice(0,e)+r+o.slice(e+n.length),u=1}await p(a,c,`utf-8`);let d={success:!0,replacements:u,filePath:a,message:`Successfully replaced ${u} occurrence${u>1?`s`:``} in ${m.basename(a)}`};return{content:[{type:`text`,text:d.message}],structuredContent:d}}validateArgs(e){let t=e.file_path,n=e.old_string,r=e.new_string;if(typeof t!=`string`||!t.trim())throw Error(`file_path is required and must be a non-empty string`);if(typeof n!=`string`)throw TypeError(`old_string is required and must be a string`);if(n===``)throw Error(`old_string cannot be empty`);if(typeof r!=`string`)throw TypeError(`new_string is required and must be a string`);if(n===r)throw Error(`new_string must be different from old_string`);return{file_path:t.trim(),old_string:n,new_string:r,replace_all:e.replace_all===!0}}countOccurrences(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}truncateForError(e,t=200){return e.length<=t?e:`${e.slice(0,t)}... [truncated, ${e.length} chars total]`}},Ot=class extends W{name=`ExitPlanMode`;riskLevel=`safe`;description=`Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
|
|
157
|
+
|
|
158
|
+
## How This Tool Works
|
|
159
|
+
- You should have already written your plan to the plan file specified in the plan mode system message
|
|
160
|
+
- This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
|
|
161
|
+
- This tool simply signals that you're done planning and ready for the user to review and approve
|
|
162
|
+
- The user will see the contents of your plan file when they review it
|
|
163
|
+
|
|
164
|
+
## When to Use This Tool
|
|
165
|
+
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
|
|
166
|
+
|
|
167
|
+
## Handling Ambiguity in Plans
|
|
168
|
+
Before using this tool, ensure your plan is clear and unambiguous. If there are multiple valid approaches or unclear requirements:
|
|
169
|
+
1. Use the AskUserQuestion tool to clarify with the user
|
|
170
|
+
2. Ask about specific implementation choices (e.g., architectural patterns, which library to use)
|
|
171
|
+
3. Clarify any assumptions that could affect the implementation
|
|
172
|
+
4. Edit your plan file to incorporate user feedback
|
|
173
|
+
5. Only proceed with ExitPlanMode after resolving ambiguities and updating the plan file
|
|
174
|
+
|
|
175
|
+
## Examples
|
|
176
|
+
|
|
177
|
+
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
|
|
178
|
+
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
|
|
179
|
+
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
|
|
180
|
+
`;parameters={type:`object`,properties:{},additionalProperties:!0};async execute(e){let t=`Exited plan mode. Your plan has been submitted for user review and approval. The user will review your plan file and decide whether to approve, reject, or request modifications.`;return{content:[{type:`text`,text:t}],structuredContent:{success:!0,message:t}}}};const kt=1e3;function At(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`*`)e[n+1]===`*`?e[n+2]===`/`?(t+=`(?:.*\\/)?`,n+=3):(t+=`.*`,n+=2):(t+=`[^/]*`,n++);else if(r===`?`)t+=`[^/]`,n++;else if(r===`{`){let r=e.indexOf(`}`,n);if(r!==-1){let i=e.slice(n+1,r).split(`,`);t+=`(?:${i.map(e=>jt(e)).join(`|`)})`,n=r+1}else t+=`\\{`,n++}else if(r===`[`){let r=e.indexOf(`]`,n);r===-1?(t+=`\\[`,n++):(t+=e.slice(n,r+1),n=r+1)}else r===`.`?(t+=`\\.`,n++):r===`/`?(t+=`\\/`,n++):`()[]{}^$+|\\`.includes(r)?(t+=`\\${r}`,n++):(t+=r,n++)}return RegExp(`^${t}$`)}function jt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var Mt=class extends W{name=`Glob`;description=`Fast file pattern matching tool that works with any codebase size.
|
|
181
|
+
|
|
182
|
+
Usage notes:
|
|
183
|
+
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
184
|
+
- Returns matching file paths sorted by modification time (newest first)
|
|
185
|
+
- Use this tool when you need to find files by name patterns
|
|
186
|
+
- You can call multiple tools in a single response for parallel searches
|
|
187
|
+
|
|
188
|
+
Supported patterns:
|
|
189
|
+
- \`*\` matches any sequence of characters except path separator
|
|
190
|
+
- \`**\` matches any sequence of characters including path separator
|
|
191
|
+
- \`?\` matches any single character
|
|
192
|
+
- \`{a,b}\` matches either a or b
|
|
193
|
+
- \`[abc]\` matches any character in brackets`;parameters={type:`object`,properties:{pattern:{type:`string`,description:`The glob pattern to match files against`},path:{type:`string`,description:`The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior.`}},required:[`pattern`]};cwd;constructor(e){super(),this.cwd=e?.cwd??h.cwd()}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let{pattern:t,path:n}=this.validateArgs(e),r=n?m.isAbsolute(n)?n:m.resolve(this.cwd,n):this.cwd;try{if(!(await f(r)).isDirectory())return U(`Path is not a directory: ${r}`)}catch(e){if(e.code===`ENOENT`)return U(`Directory not found: ${r}`);throw e}let i=t;!t.startsWith(`**/`)&&!t.startsWith(`/`)&&!t.startsWith(`./`)&&(i=`**/${t}`);let a=At(i),o=[];await this.walkDirectory(r,``,a,o,0),o.sort((e,t)=>t.mtime-e.mtime);let s=o.length>kt,c=o.slice(0,kt).map(e=>e.path),l={files:c,totalMatches:o.length,truncated:s};return{content:[{type:`text`,text:c.length>0?`Found ${o.length} file${o.length===1?``:`s`}${s?` (showing first ${kt})`:``}:\n${c.join(`
|
|
194
|
+
`)}`:`No files found matching pattern: ${t}`}],structuredContent:l}}validateArgs(e){let t=e.pattern;if(typeof t!=`string`||!t.trim())throw Error(`Pattern is required and must be a non-empty string`);let n;if(e.path!==void 0&&e.path!==null&&e.path!==`undefined`&&e.path!==`null`){if(typeof e.path!=`string`)throw TypeError(`Path must be a string`);n=e.path.trim()||void 0}return{pattern:t.trim(),path:n}}async walkDirectory(e,t,n,r,i){if(i>20)return;let a=t?m.join(e,t):e,o;try{o=await u(a,{withFileTypes:!0})}catch{return}for(let s of o){if(s.name.startsWith(`.`)||s.name===`node_modules`)continue;let o=t?`${t}/${s.name}`:s.name;if(s.isDirectory())await this.walkDirectory(e,o,n,r,i+1);else if(s.isFile()&&n.test(o))try{let e=await f(m.join(a,s.name));r.push({path:o,mtime:e.mtimeMs})}catch{}}}},Nt=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.splitWhen=e.flatten=void 0;function t(e){return e.reduce((e,t)=>[].concat(e,t),[])}e.flatten=t;function n(e,t){let n=[[]],r=0;for(let i of e)t(i)?(r++,n[r]=[]):n[r].push(i);return n}e.splitWhen=n})),Pt=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isEnoentCodeError=void 0;function t(e){return e.code===`ENOENT`}e.isEnoentCodeError=t})),Ft=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDirentFromStats=void 0;var t=class{constructor(e,t){this.name=e,this.isBlockDevice=t.isBlockDevice.bind(t),this.isCharacterDevice=t.isCharacterDevice.bind(t),this.isDirectory=t.isDirectory.bind(t),this.isFIFO=t.isFIFO.bind(t),this.isFile=t.isFile.bind(t),this.isSocket=t.isSocket.bind(t),this.isSymbolicLink=t.isSymbolicLink.bind(t)}};function n(e,n){return new t(e,n)}e.createDirentFromStats=n})),It=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.convertPosixPathToPattern=t.convertWindowsPathToPattern=t.convertPathToPattern=t.escapePosixPath=t.escapeWindowsPath=t.escape=t.removeLeadingDotSegment=t.makeAbsolute=t.unixify=void 0;let n=e(`os`),r=e(`path`),i=n.platform()===`win32`,a=/(\\?)([()*?[\]{|}]|^!|[!+@](?=\()|\\(?![!()*+?@[\]{|}]))/g,o=/(\\?)([()[\]{}]|^!|[!+@](?=\())/g,s=/^\\\\([.?])/,c=/\\(?![!()+@[\]{}])/g;function l(e){return e.replace(/\\/g,`/`)}t.unixify=l;function u(e,t){return r.resolve(e,t)}t.makeAbsolute=u;function d(e){if(e.charAt(0)===`.`){let t=e.charAt(1);if(t===`/`||t===`\\`)return e.slice(2)}return e}t.removeLeadingDotSegment=d,t.escape=i?f:p;function f(e){return e.replace(o,`\\$2`)}t.escapeWindowsPath=f;function p(e){return e.replace(a,`\\$2`)}t.escapePosixPath=p,t.convertPathToPattern=i?m:h;function m(e){return f(e).replace(s,`//$1`).replace(c,`/`)}t.convertWindowsPathToPattern=m;function h(e){return p(e)}t.convertPosixPathToPattern=h})),Lt=n(((e,t)=>{
|
|
195
|
+
/*!
|
|
196
|
+
* is-extglob <https://github.com/jonschlinkert/is-extglob>
|
|
197
|
+
*
|
|
198
|
+
* Copyright (c) 2014-2016, Jon Schlinkert.
|
|
199
|
+
* Licensed under the MIT License.
|
|
200
|
+
*/
|
|
201
|
+
t.exports=function(e){if(typeof e!=`string`||e===``)return!1;for(var t;t=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(t[2])return!0;e=e.slice(t.index+t[0].length)}return!1}})),Rt=n(((e,t)=>{
|
|
202
|
+
/*!
|
|
203
|
+
* is-glob <https://github.com/jonschlinkert/is-glob>
|
|
204
|
+
*
|
|
205
|
+
* Copyright (c) 2014-2017, Jon Schlinkert.
|
|
206
|
+
* Released under the MIT License.
|
|
207
|
+
*/
|
|
208
|
+
var n=Lt(),r={"{":`}`,"(":`)`,"[":`]`},i=function(e){if(e[0]===`!`)return!0;for(var t=0,n=-2,i=-2,a=-2,o=-2,s=-2;t<e.length;){if(e[t]===`*`||e[t+1]===`?`&&/[\].+)]/.test(e[t])||i!==-1&&e[t]===`[`&&e[t+1]!==`]`&&(i<t&&(i=e.indexOf(`]`,t)),i>t&&(s===-1||s>i||(s=e.indexOf(`\\`,t),s===-1||s>i)))||a!==-1&&e[t]===`{`&&e[t+1]!==`}`&&(a=e.indexOf(`}`,t),a>t&&(s=e.indexOf(`\\`,t),s===-1||s>a))||o!==-1&&e[t]===`(`&&e[t+1]===`?`&&/[:!=]/.test(e[t+2])&&e[t+3]!==`)`&&(o=e.indexOf(`)`,t),o>t&&(s=e.indexOf(`\\`,t),s===-1||s>o))||n!==-1&&e[t]===`(`&&e[t+1]!==`|`&&(n<t&&(n=e.indexOf(`|`,t)),n!==-1&&e[n+1]!==`)`&&(o=e.indexOf(`)`,n),o>n&&(s=e.indexOf(`\\`,n),s===-1||s>o))))return!0;if(e[t]===`\\`){var c=e[t+1];t+=2;var l=r[c];if(l){var u=e.indexOf(l,t);u!==-1&&(t=u+1)}if(e[t]===`!`)return!0}else t++}return!1},a=function(e){if(e[0]===`!`)return!0;for(var t=0;t<e.length;){if(/[*?{}()[\]]/.test(e[t]))return!0;if(e[t]===`\\`){var n=e[t+1];t+=2;var i=r[n];if(i){var a=e.indexOf(i,t);a!==-1&&(t=a+1)}if(e[t]===`!`)return!0}else t++}return!1};t.exports=function(e,t){if(typeof e!=`string`||e===``)return!1;if(n(e))return!0;var r=i;return t&&t.strict===!1&&(r=a),r(e)}})),zt=n(((t,n)=>{var r=Rt(),i=e(`path`).posix.dirname,a=e(`os`).platform()===`win32`,o=`/`,s=/\\/g,c=/[\{\[].*[\}\]]$/,l=/(^|[^\\])([\{\[]|\([^\)]+$)/,u=/\\([\!\*\?\|\[\]\(\)\{\}])/g;n.exports=function(e,t){Object.assign({flipBackslashes:!0},t).flipBackslashes&&a&&e.indexOf(o)<0&&(e=e.replace(s,o)),c.test(e)&&(e+=o),e+=`a`;do e=i(e);while(r(e)||l.test(e));return e.replace(u,`$1`)}})),Bt=n((e=>{e.isInteger=e=>typeof e==`number`?Number.isInteger(e):typeof e==`string`&&e.trim()!==``?Number.isInteger(Number(e)):!1,e.find=(e,t)=>e.nodes.find(e=>e.type===t),e.exceedsLimit=(t,n,r=1,i)=>i===!1||!e.isInteger(t)||!e.isInteger(n)?!1:(Number(n)-Number(t))/Number(r)>=i,e.escapeNode=(e,t=0,n)=>{let r=e.nodes[t];r&&(n&&r.type===n||r.type===`open`||r.type===`close`)&&r.escaped!==!0&&(r.value=`\\`+r.value,r.escaped=!0)},e.encloseBrace=e=>e.type===`brace`?e.commas>>0+e.ranges>>0?!1:(e.invalid=!0,!0):!1,e.isInvalidBrace=e=>e.type===`brace`?e.invalid===!0||e.dollar?!0:!(e.commas>>0+e.ranges>>0)||e.open!==!0||e.close!==!0?(e.invalid=!0,!0):!1:!1,e.isOpenOrClose=e=>e.type===`open`||e.type===`close`?!0:e.open===!0||e.close===!0,e.reduce=e=>e.reduce((e,t)=>(t.type===`text`&&e.push(t.value),t.type===`range`&&(t.type=`text`),e),[]),e.flatten=(...e)=>{let t=[],n=e=>{for(let r=0;r<e.length;r++){let i=e[r];if(Array.isArray(i)){n(i);continue}i!==void 0&&t.push(i)}return t};return n(e),t}})),Vt=n(((e,t)=>{let n=Bt();t.exports=(e,t={})=>{let r=(e,i={})=>{let a=t.escapeInvalid&&n.isInvalidBrace(i),o=e.invalid===!0&&t.escapeInvalid===!0,s=``;if(e.value)return(a||o)&&n.isOpenOrClose(e)?`\\`+e.value:e.value;if(e.value)return e.value;if(e.nodes)for(let t of e.nodes)s+=r(t);return s};return r(e)}})),Ht=n(((e,t)=>{t.exports=function(e){return typeof e==`number`?e-e===0:typeof e==`string`&&e.trim()!==``?Number.isFinite?Number.isFinite(+e):isFinite(+e):!1}})),Ut=n(((e,t)=>{let n=Ht(),r=(e,t,a)=>{if(n(e)===!1)throw TypeError(`toRegexRange: expected the first argument to be a number`);if(t===void 0||e===t)return String(e);if(n(t)===!1)throw TypeError(`toRegexRange: expected the second argument to be a number.`);let o={relaxZeros:!0,...a};typeof o.strictZeros==`boolean`&&(o.relaxZeros=o.strictZeros===!1);let c=String(o.relaxZeros),l=String(o.shorthand),u=String(o.capture),d=String(o.wrap),f=e+`:`+t+`=`+c+l+u+d;if(r.cache.hasOwnProperty(f))return r.cache[f].result;let p=Math.min(e,t),m=Math.max(e,t);if(Math.abs(p-m)===1){let n=e+`|`+t;return o.capture?`(${n})`:o.wrap===!1?n:`(?:${n})`}let h=g(e)||g(t),_={min:e,max:t,a:p,b:m},v=[],y=[];return h&&(_.isPadded=h,_.maxLen=String(_.max).length),p<0&&(y=s(m<0?Math.abs(m):1,Math.abs(p),_,o),p=_.a=0),m>=0&&(v=s(p,m,_,o)),_.negatives=y,_.positives=v,_.result=i(y,v,o),o.capture===!0?_.result=`(${_.result})`:o.wrap!==!1&&v.length+y.length>1&&(_.result=`(?:${_.result})`),r.cache[f]=_,_.result};function i(e,t,n){let r=c(e,t,`-`,!1,n)||[],i=c(t,e,``,!1,n)||[],a=c(e,t,`-?`,!0,n)||[];return r.concat(a).concat(i).join(`|`)}function a(e,t){let n=1,r=1,i=f(e,n),a=new Set([t]);for(;e<=i&&i<=t;)a.add(i),n+=1,i=f(e,n);for(i=p(t+1,r)-1;e<i&&i<=t;)a.add(i),r+=1,i=p(t+1,r)-1;return a=[...a],a.sort(u),a}function o(e,t,n){if(e===t)return{pattern:e,count:[],digits:0};let r=l(e,t),i=r.length,a=``,o=0;for(let e=0;e<i;e++){let[t,i]=r[e];t===i?a+=t:t!==`0`||i!==`9`?a+=h(t,i,n):o++}return o&&(a+=n.shorthand===!0?`\\d`:`[0-9]`),{pattern:a,count:[o],digits:i}}function s(e,t,n,r){let i=a(e,t),s=[],c=e,l;for(let e=0;e<i.length;e++){let t=i[e],a=o(String(c),String(t),r),u=``;if(!n.isPadded&&l&&l.pattern===a.pattern){l.count.length>1&&l.count.pop(),l.count.push(a.count[0]),l.string=l.pattern+m(l.count),c=t+1;continue}n.isPadded&&(u=_(t,n,r)),a.string=u+a.pattern+m(a.count),s.push(a),c=t+1,l=a}return s}function c(e,t,n,r,i){let a=[];for(let i of e){let{string:e}=i;!r&&!d(t,`string`,e)&&a.push(n+e),r&&d(t,`string`,e)&&a.push(n+e)}return a}function l(e,t){let n=[];for(let r=0;r<e.length;r++)n.push([e[r],t[r]]);return n}function u(e,t){return e>t?1:t>e?-1:0}function d(e,t,n){return e.some(e=>e[t]===n)}function f(e,t){return Number(String(e).slice(0,-t)+`9`.repeat(t))}function p(e,t){return e-e%10**t}function m(e){let[t=0,n=``]=e;return n||t>1?`{${t+(n?`,`+n:``)}}`:``}function h(e,t,n){return`[${e}${t-e===1?``:`-`}${t}]`}function g(e){return/^-?(0+)\d/.test(e)}function _(e,t,n){if(!t.isPadded)return e;let r=Math.abs(t.maxLen-String(e).length),i=n.relaxZeros!==!1;switch(r){case 0:return``;case 1:return i?`0?`:`0`;case 2:return i?`0{0,2}`:`00`;default:return i?`0{0,${r}}`:`0{${r}}`}}r.cache={},r.clearCache=()=>r.cache={},t.exports=r})),Wt=n(((t,n)=>{let r=e(`util`),i=Ut(),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>t=>e===!0?Number(t):String(t),s=e=>typeof e==`number`||typeof e==`string`&&e!==``,c=e=>Number.isInteger(+e),l=e=>{let t=`${e}`,n=-1;if(t[0]===`-`&&(t=t.slice(1)),t===`0`)return!1;for(;t[++n]===`0`;);return n>0},u=(e,t,n)=>typeof e==`string`||typeof t==`string`?!0:n.stringify===!0,d=(e,t,n)=>{if(t>0){let n=e[0]===`-`?`-`:``;n&&(e=e.slice(1)),e=n+e.padStart(n?t-1:t,`0`)}return n===!1?String(e):e},f=(e,t)=>{let n=e[0]===`-`?`-`:``;for(n&&(e=e.slice(1),t--);e.length<t;)e=`0`+e;return n?`-`+e:e},p=(e,t,n)=>{e.negatives.sort((e,t)=>e<t?-1:e>t?1:0),e.positives.sort((e,t)=>e<t?-1:e>t?1:0);let r=t.capture?``:`?:`,i=``,a=``,o;return e.positives.length&&(i=e.positives.map(e=>f(String(e),n)).join(`|`)),e.negatives.length&&(a=`-(${r}${e.negatives.map(e=>f(String(e),n)).join(`|`)})`),o=i&&a?`${i}|${a}`:i||a,t.wrap?`(${r}${o})`:o},m=(e,t,n,r)=>{if(n)return i(e,t,{wrap:!1,...r});let a=String.fromCharCode(e);return e===t?a:`[${a}-${String.fromCharCode(t)}]`},h=(e,t,n)=>{if(Array.isArray(e)){let t=n.wrap===!0,r=n.capture?``:`?:`;return t?`(${r}${e.join(`|`)})`:e.join(`|`)}return i(e,t,n)},g=(...e)=>RangeError(`Invalid range arguments: `+r.inspect(...e)),_=(e,t,n)=>{if(n.strictRanges===!0)throw g([e,t]);return[]},v=(e,t)=>{if(t.strictRanges===!0)throw TypeError(`Expected step "${e}" to be a number`);return[]},y=(e,t,n=1,r={})=>{let i=Number(e),a=Number(t);if(!Number.isInteger(i)||!Number.isInteger(a)){if(r.strictRanges===!0)throw g([e,t]);return[]}i===0&&(i=0),a===0&&(a=0);let s=i>a,c=String(e),_=String(t),v=String(n);n=Math.max(Math.abs(n),1);let y=l(c)||l(_)||l(v),b=y?Math.max(c.length,_.length,v.length):0,x=y===!1&&u(e,t,r)===!1,S=r.transform||o(x);if(r.toRegex&&n===1)return m(f(e,b),f(t,b),!0,r);let C={negatives:[],positives:[]},w=e=>C[e<0?`negatives`:`positives`].push(Math.abs(e)),T=[],E=0;for(;s?i>=a:i<=a;)r.toRegex===!0&&n>1?w(i):T.push(d(S(i,E),b,x)),i=s?i-n:i+n,E++;return r.toRegex===!0?n>1?p(C,r,b):h(T,null,{wrap:!1,...r}):T},b=(e,t,n=1,r={})=>{if(!c(e)&&e.length>1||!c(t)&&t.length>1)return _(e,t,r);let i=r.transform||(e=>String.fromCharCode(e)),a=`${e}`.charCodeAt(0),o=`${t}`.charCodeAt(0),s=a>o,l=Math.min(a,o),u=Math.max(a,o);if(r.toRegex&&n===1)return m(l,u,!1,r);let d=[],f=0;for(;s?a>=o:a<=o;)d.push(i(a,f)),a=s?a-n:a+n,f++;return r.toRegex===!0?h(d,null,{wrap:!1,options:r}):d},x=(e,t,n,r={})=>{if(t==null&&s(e))return[e];if(!s(e)||!s(t))return _(e,t,r);if(typeof n==`function`)return x(e,t,1,{transform:n});if(a(n))return x(e,t,0,n);let i={...r};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,c(n)?c(e)&&c(t)?y(e,t,n,i):b(e,t,Math.max(Math.abs(n),1),i):n!=null&&!a(n)?v(n,i):x(e,t,1,n)};n.exports=x})),Gt=n(((e,t)=>{let n=Wt(),r=Bt();t.exports=(e,t={})=>{let i=(e,a={})=>{let o=r.isInvalidBrace(a),s=e.invalid===!0&&t.escapeInvalid===!0,c=o===!0||s===!0,l=t.escapeInvalid===!0?`\\`:``,u=``;if(e.isOpen===!0)return l+e.value;if(e.isClose===!0)return console.log(`node.isClose`,l,e.value),l+e.value;if(e.type===`open`)return c?l+e.value:`(`;if(e.type===`close`)return c?l+e.value:`)`;if(e.type===`comma`)return e.prev.type===`comma`?``:c?e.value:`|`;if(e.value)return e.value;if(e.nodes&&e.ranges>0){let i=r.reduce(e.nodes),a=n(...i,{...t,wrap:!1,toRegex:!0,strictZeros:!0});if(a.length!==0)return i.length>1&&a.length>1?`(${a})`:a}if(e.nodes)for(let t of e.nodes)u+=i(t,e);return u};return i(e)}})),Kt=n(((e,t)=>{let n=Wt(),r=Vt(),i=Bt(),a=(e=``,t=``,n=!1)=>{let r=[];if(e=[].concat(e),t=[].concat(t),!t.length)return e;if(!e.length)return n?i.flatten(t).map(e=>`{${e}}`):t;for(let i of e)if(Array.isArray(i))for(let e of i)r.push(a(e,t,n));else for(let e of t)n===!0&&typeof e==`string`&&(e=`{${e}}`),r.push(Array.isArray(e)?a(i,e,n):i+e);return i.flatten(r)};t.exports=(e,t={})=>{let o=t.rangeLimit===void 0?1e3:t.rangeLimit,s=(e,c={})=>{e.queue=[];let l=c,u=c.queue;for(;l.type!==`brace`&&l.type!==`root`&&l.parent;)l=l.parent,u=l.queue;if(e.invalid||e.dollar){u.push(a(u.pop(),r(e,t)));return}if(e.type===`brace`&&e.invalid!==!0&&e.nodes.length===2){u.push(a(u.pop(),[`{}`]));return}if(e.nodes&&e.ranges>0){let s=i.reduce(e.nodes);if(i.exceedsLimit(...s,t.step,o))throw RangeError(`expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.`);let c=n(...s,t);c.length===0&&(c=r(e,t)),u.push(a(u.pop(),c)),e.nodes=[];return}let d=i.encloseBrace(e),f=e.queue,p=e;for(;p.type!==`brace`&&p.type!==`root`&&p.parent;)p=p.parent,f=p.queue;for(let t=0;t<e.nodes.length;t++){let n=e.nodes[t];if(n.type===`comma`&&e.type===`brace`){t===1&&f.push(``),f.push(``);continue}if(n.type===`close`){u.push(a(u.pop(),f,d));continue}if(n.value&&n.type!==`open`){f.push(a(f.pop(),n.value));continue}n.nodes&&s(n,e)}return f};return i.flatten(s(e))}})),qt=n(((e,t)=>{t.exports={MAX_LENGTH:1e4,CHAR_0:`0`,CHAR_9:`9`,CHAR_UPPERCASE_A:`A`,CHAR_LOWERCASE_A:`a`,CHAR_UPPERCASE_Z:`Z`,CHAR_LOWERCASE_Z:`z`,CHAR_LEFT_PARENTHESES:`(`,CHAR_RIGHT_PARENTHESES:`)`,CHAR_ASTERISK:`*`,CHAR_AMPERSAND:`&`,CHAR_AT:`@`,CHAR_BACKSLASH:`\\`,CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:`\r`,CHAR_CIRCUMFLEX_ACCENT:`^`,CHAR_COLON:`:`,CHAR_COMMA:`,`,CHAR_DOLLAR:`$`,CHAR_DOT:`.`,CHAR_DOUBLE_QUOTE:`"`,CHAR_EQUAL:`=`,CHAR_EXCLAMATION_MARK:`!`,CHAR_FORM_FEED:`\f`,CHAR_FORWARD_SLASH:`/`,CHAR_HASH:`#`,CHAR_HYPHEN_MINUS:`-`,CHAR_LEFT_ANGLE_BRACKET:`<`,CHAR_LEFT_CURLY_BRACE:`{`,CHAR_LEFT_SQUARE_BRACKET:`[`,CHAR_LINE_FEED:`
|
|
209
|
+
`,CHAR_NO_BREAK_SPACE:`\xA0`,CHAR_PERCENT:`%`,CHAR_PLUS:`+`,CHAR_QUESTION_MARK:`?`,CHAR_RIGHT_ANGLE_BRACKET:`>`,CHAR_RIGHT_CURLY_BRACE:`}`,CHAR_RIGHT_SQUARE_BRACKET:`]`,CHAR_SEMICOLON:`;`,CHAR_SINGLE_QUOTE:`'`,CHAR_SPACE:` `,CHAR_TAB:` `,CHAR_UNDERSCORE:`_`,CHAR_VERTICAL_LINE:`|`,CHAR_ZERO_WIDTH_NOBREAK_SPACE:``}})),Jt=n(((e,t)=>{let n=Vt(),{MAX_LENGTH:r,CHAR_BACKSLASH:i,CHAR_BACKTICK:a,CHAR_COMMA:o,CHAR_DOT:s,CHAR_LEFT_PARENTHESES:c,CHAR_RIGHT_PARENTHESES:l,CHAR_LEFT_CURLY_BRACE:u,CHAR_RIGHT_CURLY_BRACE:d,CHAR_LEFT_SQUARE_BRACKET:f,CHAR_RIGHT_SQUARE_BRACKET:p,CHAR_DOUBLE_QUOTE:m,CHAR_SINGLE_QUOTE:h,CHAR_NO_BREAK_SPACE:g,CHAR_ZERO_WIDTH_NOBREAK_SPACE:_}=qt();t.exports=(e,t={})=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);let v=t||{},y=typeof v.maxLength==`number`?Math.min(r,v.maxLength):r;if(e.length>y)throw SyntaxError(`Input length (${e.length}), exceeds max characters (${y})`);let b={type:`root`,input:e,nodes:[]},x=[b],S=b,C=b,w=0,T=e.length,E=0,D=0,O,k=()=>e[E++],A=e=>{if(e.type===`text`&&C.type===`dot`&&(C.type=`text`),C&&C.type===`text`&&e.type===`text`){C.value+=e.value;return}return S.nodes.push(e),e.parent=S,e.prev=C,C=e,e};for(A({type:`bos`});E<T;)if(S=x[x.length-1],O=k(),!(O===_||O===g)){if(O===i){A({type:`text`,value:(t.keepEscaping?O:``)+k()});continue}if(O===p){A({type:`text`,value:`\\`+O});continue}if(O===f){w++;let e;for(;E<T&&(e=k());){if(O+=e,e===f){w++;continue}if(e===i){O+=k();continue}if(e===p&&(w--,w===0))break}A({type:`text`,value:O});continue}if(O===c){S=A({type:`paren`,nodes:[]}),x.push(S),A({type:`text`,value:O});continue}if(O===l){if(S.type!==`paren`){A({type:`text`,value:O});continue}S=x.pop(),A({type:`text`,value:O}),S=x[x.length-1];continue}if(O===m||O===h||O===a){let e=O,n;for(t.keepQuotes!==!0&&(O=``);E<T&&(n=k());){if(n===i){O+=n+k();continue}if(n===e){t.keepQuotes===!0&&(O+=n);break}O+=n}A({type:`text`,value:O});continue}if(O===u){D++,S=A({type:`brace`,open:!0,close:!1,dollar:C.value&&C.value.slice(-1)===`$`||S.dollar===!0,depth:D,commas:0,ranges:0,nodes:[]}),x.push(S),A({type:`open`,value:O});continue}if(O===d){if(S.type!==`brace`){A({type:`text`,value:O});continue}S=x.pop(),S.close=!0,A({type:`close`,value:O}),D--,S=x[x.length-1];continue}if(O===o&&D>0){S.ranges>0&&(S.ranges=0,S.nodes=[S.nodes.shift(),{type:`text`,value:n(S)}]),A({type:`comma`,value:O}),S.commas++;continue}if(O===s&&D>0&&S.commas===0){let e=S.nodes;if(D===0||e.length===0){A({type:`text`,value:O});continue}if(C.type===`dot`){if(S.range=[],C.value+=O,C.type=`range`,S.nodes.length!==3&&S.nodes.length!==5){S.invalid=!0,S.ranges=0,C.type=`text`;continue}S.ranges++,S.args=[];continue}if(C.type===`range`){e.pop();let t=e[e.length-1];t.value+=C.value+O,C=t,S.ranges--;continue}A({type:`dot`,value:O});continue}A({type:`text`,value:O})}do if(S=x.pop(),S.type!==`root`){S.nodes.forEach(e=>{e.nodes||(e.type===`open`&&(e.isOpen=!0),e.type===`close`&&(e.isClose=!0),e.nodes||(e.type=`text`),e.invalid=!0)});let e=x[x.length-1],t=e.nodes.indexOf(S);e.nodes.splice(t,1,...S.nodes)}while(x.length>0);return A({type:`eos`}),b}})),Yt=n(((e,t)=>{let n=Vt(),r=Gt(),i=Kt(),a=Jt(),o=(e,t={})=>{let n=[];if(Array.isArray(e))for(let r of e){let e=o.create(r,t);Array.isArray(e)?n.push(...e):n.push(e)}else n=[].concat(o.create(e,t));return t&&t.expand===!0&&t.nodupes===!0&&(n=[...new Set(n)]),n};o.parse=(e,t={})=>a(e,t),o.stringify=(e,t={})=>n(typeof e==`string`?o.parse(e,t):e,t),o.compile=(e,t={})=>(typeof e==`string`&&(e=o.parse(e,t)),r(e,t)),o.expand=(e,t={})=>{typeof e==`string`&&(e=o.parse(e,t));let n=i(e,t);return t.noempty===!0&&(n=n.filter(Boolean)),t.nodupes===!0&&(n=[...new Set(n)]),n},o.create=(e,t={})=>e===``||e.length<3?[e]:t.expand===!0?o.expand(e,t):o.compile(e,t),t.exports=o})),Xt=n(((t,n)=>{let r=e(`util`),i=Yt(),a=e(`picomatch`),o=e(`picomatch/lib/utils`),s=e=>e===``||e===`./`,c=e=>{let t=e.indexOf(`{`);return t>-1&&e.indexOf(`}`,t)>-1},l=(e,t,n)=>{t=[].concat(t),e=[].concat(e);let r=new Set,i=new Set,o=new Set,s=0,c=e=>{o.add(e.output),n&&n.onResult&&n.onResult(e)};for(let o=0;o<t.length;o++){let l=a(String(t[o]),{...n,onResult:c},!0),u=l.state.negated||l.state.negatedExtglob;u&&s++;for(let t of e){let e=l(t,!0);(u?!e.isMatch:e.isMatch)&&(u?r.add(e.output):(r.delete(e.output),i.add(e.output)))}}let l=(s===t.length?[...o]:[...i]).filter(e=>!r.has(e));if(n&&l.length===0){if(n.failglob===!0)throw Error(`No matches found for "${t.join(`, `)}"`);if(n.nonull===!0||n.nullglob===!0)return n.unescape?t.map(e=>e.replace(/\\/g,``)):t}return l};l.match=l,l.matcher=(e,t)=>a(e,t),l.isMatch=(e,t,n)=>a(t,n)(e),l.any=l.isMatch,l.not=(e,t,n={})=>{t=[].concat(t).map(String);let r=new Set,i=[],a=e=>{n.onResult&&n.onResult(e),i.push(e.output)},o=new Set(l(e,t,{...n,onResult:a}));for(let e of i)o.has(e)||r.add(e);return[...r]},l.contains=(e,t,n)=>{if(typeof e!=`string`)throw TypeError(`Expected a string: "${r.inspect(e)}"`);if(Array.isArray(t))return t.some(t=>l.contains(e,t,n));if(typeof t==`string`){if(s(e)||s(t))return!1;if(e.includes(t)||e.startsWith(`./`)&&e.slice(2).includes(t))return!0}return l.isMatch(e,t,{...n,contains:!0})},l.matchKeys=(e,t,n)=>{if(!o.isObject(e))throw TypeError(`Expected the first argument to be an object`);let r=l(Object.keys(e),t,n),i={};for(let t of r)i[t]=e[t];return i},l.some=(e,t,n)=>{let r=[].concat(e);for(let e of[].concat(t)){let t=a(String(e),n);if(r.some(e=>t(e)))return!0}return!1},l.every=(e,t,n)=>{let r=[].concat(e);for(let e of[].concat(t)){let t=a(String(e),n);if(!r.every(e=>t(e)))return!1}return!0},l.all=(e,t,n)=>{if(typeof e!=`string`)throw TypeError(`Expected a string: "${r.inspect(e)}"`);return[].concat(t).every(t=>a(t,n)(e))},l.capture=(e,t,n)=>{let r=o.isWindows(n),i=a.makeRe(String(e),{...n,capture:!0}).exec(r?o.toPosixSlashes(t):t);if(i)return i.slice(1).map(e=>e===void 0?``:e)},l.makeRe=(...e)=>a.makeRe(...e),l.scan=(...e)=>a.scan(...e),l.parse=(e,t)=>{let n=[];for(let r of[].concat(e||[]))for(let e of i(String(r),t))n.push(a.parse(e,t));return n},l.braces=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);return t&&t.nobrace===!0||!c(e)?[e]:i(e,t)},l.braceExpand=(e,t)=>{if(typeof e!=`string`)throw TypeError(`Expected a string`);return l.braces(e,{...t,expand:!0})},l.hasBraces=c,n.exports=l})),Zt=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.isAbsolute=t.partitionAbsoluteAndRelative=t.removeDuplicateSlashes=t.matchAny=t.convertPatternsToRe=t.makeRe=t.getPatternParts=t.expandBraceExpansion=t.expandPatternsWithBraceExpansion=t.isAffectDepthOfReadingPattern=t.endsWithSlashGlobStar=t.hasGlobStar=t.getBaseDirectory=t.isPatternRelatedToParentDirectory=t.getPatternsOutsideCurrentDirectory=t.getPatternsInsideCurrentDirectory=t.getPositivePatterns=t.getNegativePatterns=t.isPositivePattern=t.isNegativePattern=t.convertToNegativePattern=t.convertToPositivePattern=t.isDynamicPattern=t.isStaticPattern=void 0;let n=e(`path`),r=zt(),i=Xt(),a=/[*?]|^!/,o=/\[[^[]*]/,s=/(?:^|[^!*+?@])\([^(]*\|[^|]*\)/,c=/[!*+?@]\([^(]*\)/,l=/,|\.\./,u=/(?!^)\/{2,}/g;function d(e,t={}){return!f(e,t)}t.isStaticPattern=d;function f(e,t={}){return e===``?!1:!!(t.caseSensitiveMatch===!1||e.includes(`\\`)||a.test(e)||o.test(e)||s.test(e)||t.extglob!==!1&&c.test(e)||t.braceExpansion!==!1&&p(e))}t.isDynamicPattern=f;function p(e){let t=e.indexOf(`{`);if(t===-1)return!1;let n=e.indexOf(`}`,t+1);if(n===-1)return!1;let r=e.slice(t,n);return l.test(r)}function m(e){return g(e)?e.slice(1):e}t.convertToPositivePattern=m;function h(e){return`!`+e}t.convertToNegativePattern=h;function g(e){return e.startsWith(`!`)&&e[1]!==`(`}t.isNegativePattern=g;function _(e){return!g(e)}t.isPositivePattern=_;function v(e){return e.filter(g)}t.getNegativePatterns=v;function y(e){return e.filter(_)}t.getPositivePatterns=y;function b(e){return e.filter(e=>!S(e))}t.getPatternsInsideCurrentDirectory=b;function x(e){return e.filter(S)}t.getPatternsOutsideCurrentDirectory=x;function S(e){return e.startsWith(`..`)||e.startsWith(`./..`)}t.isPatternRelatedToParentDirectory=S;function C(e){return r(e,{flipBackslashes:!1})}t.getBaseDirectory=C;function w(e){return e.includes(`**`)}t.hasGlobStar=w;function T(e){return e.endsWith(`/**`)}t.endsWithSlashGlobStar=T;function E(e){let t=n.basename(e);return T(e)||d(t)}t.isAffectDepthOfReadingPattern=E;function D(e){return e.reduce((e,t)=>e.concat(O(t)),[])}t.expandPatternsWithBraceExpansion=D;function O(e){let t=i.braces(e,{expand:!0,nodupes:!0,keepEscaping:!0});return t.sort((e,t)=>e.length-t.length),t.filter(e=>e!==``)}t.expandBraceExpansion=O;function k(e,t){let{parts:n}=i.scan(e,Object.assign(Object.assign({},t),{parts:!0}));return n.length===0&&(n=[e]),n[0].startsWith(`/`)&&(n[0]=n[0].slice(1),n.unshift(``)),n}t.getPatternParts=k;function A(e,t){return i.makeRe(e,t)}t.makeRe=A;function j(e,t){return e.map(e=>A(e,t))}t.convertPatternsToRe=j;function M(e,t){return t.some(t=>t.test(e))}t.matchAny=M;function N(e){return e.replace(u,`/`)}t.removeDuplicateSlashes=N;function P(e){let t=[],n=[];for(let r of e)F(r)?t.push(r):n.push(r);return[t,n]}t.partitionAbsoluteAndRelative=P;function F(e){return n.isAbsolute(e)}t.isAbsolute=F})),Qt=n(((t,n)=>{let r=e(`stream`).PassThrough,i=Array.prototype.slice;n.exports=a;function a(){let e=[],t=i.call(arguments),n=!1,a=t[t.length-1];a&&!Array.isArray(a)&&a.pipe==null?t.pop():a={};let s=a.end!==!1,c=a.pipeError===!0;a.objectMode??=!0,a.highWaterMark??=64*1024;let l=r(a);function u(){for(let t=0,n=arguments.length;t<n;t++)e.push(o(arguments[t],a));return d(),this}function d(){if(n)return;n=!0;let t=e.shift();if(!t){process.nextTick(f);return}Array.isArray(t)||(t=[t]);let r=t.length+1;function i(){--r>0||(n=!1,d())}function a(e){function t(){e.removeListener(`merge2UnpipeEnd`,t),e.removeListener(`end`,t),c&&e.removeListener(`error`,n),i()}function n(e){l.emit(`error`,e)}if(e._readableState.endEmitted)return i();e.on(`merge2UnpipeEnd`,t),e.on(`end`,t),c&&e.on(`error`,n),e.pipe(l,{end:!1}),e.resume()}for(let e=0;e<t.length;e++)a(t[e]);i()}function f(){n=!1,l.emit(`queueDrain`),s&&l.end()}return l.setMaxListeners(0),l.add=u,l.on(`unpipe`,function(e){e.emit(`merge2UnpipeEnd`)}),t.length&&u.apply(null,t),l}function o(e,t){if(Array.isArray(e))for(let n=0,r=e.length;n<r;n++)e[n]=o(e[n],t);else{if(!e._readableState&&e.pipe&&(e=e.pipe(r(t))),!e._readableState||!e.pause||!e.pipe)throw Error(`Only readable stream can be merged.`);e.pause()}return e}})),$t=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.merge=void 0;let t=Qt();function n(e){let n=t(e);return e.forEach(e=>{e.once(`error`,e=>n.emit(`error`,e))}),n.once(`close`,()=>r(e)),n.once(`end`,()=>r(e)),n}e.merge=n;function r(e){e.forEach(e=>e.emit(`close`))}})),en=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.isEmpty=e.isString=void 0;function t(e){return typeof e==`string`}e.isString=t;function n(e){return e===``}e.isEmpty=n})),Y=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.string=e.stream=e.pattern=e.path=e.fs=e.errno=e.array=void 0,e.array=Nt(),e.errno=Pt(),e.fs=Ft(),e.path=It(),e.pattern=Zt(),e.stream=$t(),e.string=en()})),tn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.convertPatternGroupToTask=e.convertPatternGroupsToTasks=e.groupPatternsByBaseDirectory=e.getNegativePatternsAsPositive=e.getPositivePatterns=e.convertPatternsToTasks=e.generate=void 0;let t=Y();function n(e,n){let s=r(e,n),c=r(n.ignore,n),l=a(s),u=o(s,c),d=l.filter(e=>t.pattern.isStaticPattern(e,n)),f=l.filter(e=>t.pattern.isDynamicPattern(e,n)),p=i(d,u,!1),m=i(f,u,!0);return p.concat(m)}e.generate=n;function r(e,n){let r=e;return n.braceExpansion&&(r=t.pattern.expandPatternsWithBraceExpansion(r)),n.baseNameMatch&&(r=r.map(e=>e.includes(`/`)?e:`**/${e}`)),r.map(e=>t.pattern.removeDuplicateSlashes(e))}function i(e,n,r){let i=[],a=t.pattern.getPatternsOutsideCurrentDirectory(e),o=t.pattern.getPatternsInsideCurrentDirectory(e),u=s(a),d=s(o);return i.push(...c(u,n,r)),`.`in d?i.push(l(`.`,o,n,r)):i.push(...c(d,n,r)),i}e.convertPatternsToTasks=i;function a(e){return t.pattern.getPositivePatterns(e)}e.getPositivePatterns=a;function o(e,n){return t.pattern.getNegativePatterns(e).concat(n).map(t.pattern.convertToPositivePattern)}e.getNegativePatternsAsPositive=o;function s(e){return e.reduce((e,n)=>{let r=t.pattern.getBaseDirectory(n);return r in e?e[r].push(n):e[r]=[n],e},{})}e.groupPatternsByBaseDirectory=s;function c(e,t,n){return Object.keys(e).map(r=>l(r,e[r],t,n))}e.convertPatternGroupsToTasks=c;function l(e,n,r,i){return{dynamic:i,positive:n,negative:r,base:e,patterns:[].concat(n,r.map(t.pattern.convertToNegativePattern))}}e.convertPatternGroupToTask=l})),nn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.read=void 0;function t(e,t,i){t.fs.lstat(e,(a,o)=>{if(a!==null){n(i,a);return}if(!o.isSymbolicLink()||!t.followSymbolicLink){r(i,o);return}t.fs.stat(e,(e,a)=>{if(e!==null){if(t.throwErrorOnBrokenSymbolicLink){n(i,e);return}r(i,o);return}t.markSymbolicLink&&(a.isSymbolicLink=()=>!0),r(i,a)})})}e.read=t;function n(e,t){e(t)}function r(e,t){e(null,t)}})),rn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.read=void 0;function t(e,t){let n=t.fs.lstatSync(e);if(!n.isSymbolicLink()||!t.followSymbolicLink)return n;try{let n=t.fs.statSync(e);return t.markSymbolicLink&&(n.isSymbolicLink=()=>!0),n}catch(e){if(!t.throwErrorOnBrokenSymbolicLink)return n;throw e}}e.read=t})),an=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createFileSystemAdapter=t.FILE_SYSTEM_ADAPTER=void 0;let n=e(`fs`);t.FILE_SYSTEM_ADAPTER={lstat:n.lstat,stat:n.stat,lstatSync:n.lstatSync,statSync:n.statSync};function r(e){return e===void 0?t.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},t.FILE_SYSTEM_ADAPTER),e)}t.createFileSystemAdapter=r})),on=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=an();e.default=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=t.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue(e,t){return e??t}}})),X=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.statSync=e.stat=e.Settings=void 0;let t=nn(),n=rn(),r=on();e.Settings=r.default;function i(e,n,r){if(typeof n==`function`){t.read(e,o(),n);return}t.read(e,o(n),r)}e.stat=i;function a(e,t){let r=o(t);return n.read(e,r)}e.statSync=a;function o(e={}){return e instanceof r.default?e:new r.default(e)}})),sn=n(((e,t)=>{
|
|
210
|
+
/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
211
|
+
let n;t.exports=typeof queueMicrotask==`function`?queueMicrotask.bind(typeof window<`u`?window:global):e=>(n||=Promise.resolve()).then(e).catch(e=>setTimeout(()=>{throw e},0))})),cn=n(((e,t)=>{
|
|
212
|
+
/*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
213
|
+
t.exports=r;let n=sn();function r(e,t){let r,i,a,o=!0;Array.isArray(e)?(r=[],i=e.length):(a=Object.keys(e),r={},i=a.length);function s(e){function i(){t&&t(e,r),t=null}o?n(i):i()}function c(e,t,n){r[e]=n,(--i===0||t)&&s(t)}i?a?a.forEach(function(t){e[t](function(e,n){c(t,e,n)})}):e.forEach(function(e,t){e(function(e,n){c(t,e,n)})}):s(null),o=!1}})),ln=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;let t=process.versions.node.split(`.`);if(t[0]===void 0||t[1]===void 0)throw Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);let n=Number.parseInt(t[0],10),r=Number.parseInt(t[1],10);e.IS_SUPPORT_READDIR_WITH_FILE_TYPES=n>10||n===10&&r>=10})),un=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.createDirentFromStats=void 0;var t=class{constructor(e,t){this.name=e,this.isBlockDevice=t.isBlockDevice.bind(t),this.isCharacterDevice=t.isCharacterDevice.bind(t),this.isDirectory=t.isDirectory.bind(t),this.isFIFO=t.isFIFO.bind(t),this.isFile=t.isFile.bind(t),this.isSocket=t.isSocket.bind(t),this.isSymbolicLink=t.isSymbolicLink.bind(t)}};function n(e,n){return new t(e,n)}e.createDirentFromStats=n})),dn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.fs=void 0,e.fs=un()})),fn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.joinPathSegments=void 0;function t(e,t,n){return e.endsWith(n)?e+t:e+n+t}e.joinPathSegments=t})),pn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.readdir=e.readdirWithFileTypes=e.read=void 0;let t=X(),n=cn(),r=ln(),i=dn(),a=fn();function o(e,t,n){if(!t.stats&&r.IS_SUPPORT_READDIR_WITH_FILE_TYPES){s(e,t,n);return}l(e,t,n)}e.read=o;function s(e,t,r){t.fs.readdir(e,{withFileTypes:!0},(i,o)=>{if(i!==null){u(r,i);return}let s=o.map(n=>({dirent:n,name:n.name,path:a.joinPathSegments(e,n.name,t.pathSegmentSeparator)}));if(!t.followSymbolicLinks){d(r,s);return}n(s.map(e=>c(e,t)),(e,t)=>{if(e!==null){u(r,e);return}d(r,t)})})}e.readdirWithFileTypes=s;function c(e,t){return n=>{if(!e.dirent.isSymbolicLink()){n(null,e);return}t.fs.stat(e.path,(r,a)=>{if(r!==null){if(t.throwErrorOnBrokenSymbolicLink){n(r);return}n(null,e);return}e.dirent=i.fs.createDirentFromStats(e.name,a),n(null,e)})}}function l(e,r,o){r.fs.readdir(e,(s,c)=>{if(s!==null){u(o,s);return}n(c.map(n=>{let o=a.joinPathSegments(e,n,r.pathSegmentSeparator);return e=>{t.stat(o,r.fsStatSettings,(t,a)=>{if(t!==null){e(t);return}let s={name:n,path:o,dirent:i.fs.createDirentFromStats(n,a)};r.stats&&(s.stats=a),e(null,s)})}}),(e,t)=>{if(e!==null){u(o,e);return}d(o,t)})})}e.readdir=l;function u(e,t){e(t)}function d(e,t){e(null,t)}})),mn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.readdir=e.readdirWithFileTypes=e.read=void 0;let t=X(),n=ln(),r=dn(),i=fn();function a(e,t){return!t.stats&&n.IS_SUPPORT_READDIR_WITH_FILE_TYPES?o(e,t):s(e,t)}e.read=a;function o(e,t){return t.fs.readdirSync(e,{withFileTypes:!0}).map(n=>{let a={dirent:n,name:n.name,path:i.joinPathSegments(e,n.name,t.pathSegmentSeparator)};if(a.dirent.isSymbolicLink()&&t.followSymbolicLinks)try{let e=t.fs.statSync(a.path);a.dirent=r.fs.createDirentFromStats(a.name,e)}catch(e){if(t.throwErrorOnBrokenSymbolicLink)throw e}return a})}e.readdirWithFileTypes=o;function s(e,n){return n.fs.readdirSync(e).map(a=>{let o=i.joinPathSegments(e,a,n.pathSegmentSeparator),s=t.statSync(o,n.fsStatSettings),c={name:a,path:o,dirent:r.fs.createDirentFromStats(a,s)};return n.stats&&(c.stats=s),c})}e.readdir=s})),hn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createFileSystemAdapter=t.FILE_SYSTEM_ADAPTER=void 0;let n=e(`fs`);t.FILE_SYSTEM_ADAPTER={lstat:n.lstat,stat:n.stat,lstatSync:n.lstatSync,statSync:n.statSync,readdir:n.readdir,readdirSync:n.readdirSync};function r(e){return e===void 0?t.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},t.FILE_SYSTEM_ADAPTER),e)}t.createFileSystemAdapter=r})),gn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`path`),r=X(),i=hn();t.default=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=i.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,n.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new r.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,t){return e??t}}})),_n=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Settings=e.scandirSync=e.scandir=void 0;let t=pn(),n=mn(),r=gn();e.Settings=r.default;function i(e,n,r){if(typeof n==`function`){t.read(e,o(),n);return}t.read(e,o(n),r)}e.scandir=i;function a(e,t){let r=o(t);return n.read(e,r)}e.scandirSync=a;function o(e={}){return e instanceof r.default?e:new r.default(e)}})),vn=n(((e,t)=>{function n(e){var t=new e,n=t;function r(){var r=t;return r.next?t=r.next:(t=new e,n=t),r.next=null,r}function i(e){n.next=e,n=e}return{get:r,release:i}}t.exports=n})),yn=n(((e,t)=>{var n=vn();function r(e,t,r){if(typeof e==`function`&&(r=t,t=e,e=null),!(r>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);var o=n(a),s=null,c=null,l=0,u=null,d={push:v,drain:i,saturated:i,pause:p,paused:!1,get concurrency(){return r},set concurrency(e){if(!(e>=1))throw Error(`fastqueue concurrency must be equal to or greater than 1`);if(r=e,!d.paused)for(;s&&l<r;)l++,b()},running:f,resume:g,idle:_,length:m,getQueue:h,unshift:y,empty:i,kill:x,killAndDrain:S,error:C};return d;function f(){return l}function p(){d.paused=!0}function m(){for(var e=s,t=0;e;)e=e.next,t++;return t}function h(){for(var e=s,t=[];e;)t.push(e.value),e=e.next;return t}function g(){if(d.paused){if(d.paused=!1,s===null){l++,b();return}for(;s&&l<r;)l++,b()}}function _(){return l===0&&d.length()===0}function v(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?c?(c.next=f,c=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function y(n,a){var f=o.get();f.context=e,f.release=b,f.value=n,f.callback=a||i,f.errorHandler=u,l>=r||d.paused?s?(f.next=s,s=f):(s=f,c=f,d.saturated()):(l++,t.call(e,f.value,f.worked))}function b(n){n&&o.release(n);var i=s;i&&l<=r?d.paused?l--:(c===s&&(c=null),s=i.next,i.next=null,t.call(e,i.value,i.worked),c===null&&d.empty()):--l===0&&d.drain()}function x(){s=null,c=null,d.drain=i}function S(){s=null,c=null,d.drain(),d.drain=i}function C(e){u=e}}function i(){}function a(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var e=this;this.worked=function(t,n){var r=e.callback,a=e.errorHandler,o=e.value;e.value=null,e.callback=i,e.errorHandler&&a(t,o),r.call(e.context,t,n),e.release(e)}}function o(e,t,n){typeof e==`function`&&(n=t,t=e,e=null);function a(e,n){t.call(this,e).then(function(e){n(null,e)},n)}var o=r(e,a,n),s=o.push,c=o.unshift;return o.push=l,o.unshift=u,o.drained=d,o;function l(e){var t=new Promise(function(t,n){s(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function u(e){var t=new Promise(function(t,n){c(e,function(e,r){if(e){n(e);return}t(r)})});return t.catch(i),t}function d(){return new Promise(function(e){process.nextTick(function(){if(o.idle())e();else{var t=o.drain;o.drain=function(){typeof t==`function`&&t(),e(),o.drain=t}}})})}}t.exports=r,t.exports.promise=o})),bn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.joinPathSegments=e.replacePathSegmentSeparator=e.isAppliedFilter=e.isFatalError=void 0;function t(e,t){return e.errorFilter===null?!0:!e.errorFilter(t)}e.isFatalError=t;function n(e,t){return e===null||e(t)}e.isAppliedFilter=n;function r(e,t){return e.split(/[/\\]/).join(t)}e.replacePathSegmentSeparator=r;function i(e,t,n){return e===``?t:e.endsWith(n)?e+t:e+n+t}e.joinPathSegments=i})),xn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=bn();e.default=class{constructor(e,n){this._root=e,this._settings=n,this._root=t.replacePathSegmentSeparator(e,n.pathSegmentSeparator)}}})),Sn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`events`),r=_n(),i=yn(),a=bn(),o=xn();t.default=class extends o.default{constructor(e,t){super(e,t),this._settings=t,this._scandir=r.scandir,this._emitter=new n.EventEmitter,this._queue=i(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit(`end`)}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw Error(`The reader is already destroyed`);this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on(`entry`,e)}onError(e){this._emitter.once(`error`,e)}onEnd(e){this._emitter.once(`end`,e)}_pushToQueue(e,t){let n={directory:e,base:t};this._queue.push(n,e=>{e!==null&&this._handleError(e)})}_worker(e,t){this._scandir(e.directory,this._settings.fsScandirSettings,(n,r)=>{if(n!==null){t(n,void 0);return}for(let t of r)this._handleEntry(t,e.base);t(null,void 0)})}_handleError(e){this._isDestroyed||!a.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit(`error`,e))}_handleEntry(e,t){if(this._isDestroyed||this._isFatalError)return;let n=e.path;t!==void 0&&(e.path=a.joinPathSegments(t,e.name,this._settings.pathSegmentSeparator)),a.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&a.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(n,t===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit(`entry`,e)}}})),Cn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Sn();e.default=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new t.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(t=>{n(e,t)}),this._reader.onEntry(e=>{this._storage.push(e)}),this._reader.onEnd(()=>{r(e,this._storage)}),this._reader.read()}};function n(e,t){e(t)}function r(e,t){e(null,t)}})),wn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`stream`),r=Sn();t.default=class{constructor(e,t){this._root=e,this._settings=t,this._reader=new r.default(this._root,this._settings),this._stream=new n.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit(`error`,e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}}})),Tn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=_n(),n=bn(),r=xn();e.default=class extends r.default{constructor(){super(...arguments),this._scandir=t.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,t){this._queue.add({directory:e,base:t})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,t){try{let n=this._scandir(e,this._settings.fsScandirSettings);for(let e of n)this._handleEntry(e,t)}catch(e){this._handleError(e)}}_handleError(e){if(n.isFatalError(this._settings,e))throw e}_handleEntry(e,t){let r=e.path;t!==void 0&&(e.path=n.joinPathSegments(t,e.name,this._settings.pathSegmentSeparator)),n.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&n.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(r,t===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}}})),En=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Tn();e.default=class{constructor(e,n){this._root=e,this._settings=n,this._reader=new t.default(this._root,this._settings)}read(){return this._reader.read()}}})),Dn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`path`),r=_n();t.default=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,1/0),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,n.sep),this.fsScandirSettings=new r.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,t){return e??t}}})),On=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.Settings=e.walkStream=e.walkSync=e.walk=void 0;let t=Cn(),n=wn(),r=En(),i=Dn();e.Settings=i.default;function a(e,n,r){if(typeof n==`function`){new t.default(e,c()).read(n);return}new t.default(e,c(n)).read(r)}e.walk=a;function o(e,t){let n=c(t);return new r.default(e,n).read()}e.walkSync=o;function s(e,t){let r=c(t);return new n.default(e,r).read()}e.walkStream=s;function c(e={}){return e instanceof i.default?e:new i.default(e)}})),kn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`path`),r=X(),i=Y();t.default=class{constructor(e){this._settings=e,this._fsStatSettings=new r.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return n.resolve(this._settings.cwd,e)}_makeEntry(e,t){let n={name:t,path:t,dirent:i.fs.createDirentFromStats(t,e)};return this._settings.stats&&(n.stats=e),n}_isFatalError(e){return!i.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}}})),An=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`stream`),r=X(),i=On(),a=kn();t.default=class extends a.default{constructor(){super(...arguments),this._walkStream=i.walkStream,this._stat=r.stat}dynamic(e,t){return this._walkStream(e,t)}static(e,t){let r=e.map(this._getFullEntryPath,this),i=new n.PassThrough({objectMode:!0});i._write=(n,a,o)=>this._getEntry(r[n],e[n],t).then(e=>{e!==null&&t.entryFilter(e)&&i.push(e),n===r.length-1&&i.end(),o()}).catch(o);for(let e=0;e<r.length;e++)i.write(e);return i}_getEntry(e,t,n){return this._getStat(e).then(e=>this._makeEntry(e,t)).catch(e=>{if(n.errorFilter(e))return null;throw e})}_getStat(e){return new Promise((t,n)=>{this._stat(e,this._fsStatSettings,(e,r)=>e===null?t(r):n(e))})}}})),jn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=On(),n=kn(),r=An();e.default=class extends n.default{constructor(){super(...arguments),this._walkAsync=t.walk,this._readerStream=new r.default(this._settings)}dynamic(e,t){return new Promise((n,r)=>{this._walkAsync(e,t,(e,t)=>{e===null?n(t):r(e)})})}async static(e,t){let n=[],r=this._readerStream.static(e,t);return new Promise((e,t)=>{r.once(`error`,t),r.on(`data`,e=>n.push(e)),r.once(`end`,()=>e(n))})}}})),Mn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default=class{constructor(e,t,n){this._patterns=e,this._settings=t,this._micromatchOptions=n,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let t=this._getPatternSegments(e),n=this._splitSegmentsIntoSections(t);this._storage.push({complete:n.length<=1,pattern:e,segments:t,sections:n})}}_getPatternSegments(e){return t.pattern.getPatternParts(e,this._micromatchOptions).map(e=>t.pattern.isDynamicPattern(e,this._settings)?{dynamic:!0,pattern:e,patternRe:t.pattern.makeRe(e,this._micromatchOptions)}:{dynamic:!1,pattern:e})}_splitSegmentsIntoSections(e){return t.array.splitWhen(e,e=>e.dynamic&&t.pattern.hasGlobStar(e.pattern))}}})),Nn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Mn();e.default=class extends t.default{match(e){let t=e.split(`/`),n=t.length,r=this._storage.filter(e=>!e.complete||e.segments.length>n);for(let e of r){let r=e.sections[0];if(!e.complete&&n>r.length||t.every((t,n)=>{let r=e.segments[n];return!!(r.dynamic&&r.patternRe.test(t)||!r.dynamic&&r.pattern===t)}))return!0}return!1}}})),Pn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y(),n=Nn();e.default=class{constructor(e,t){this._settings=e,this._micromatchOptions=t}getFilter(e,t,n){let r=this._getMatcher(t),i=this._getNegativePatternsRe(n);return t=>this._filter(e,t,r,i)}_getMatcher(e){return new n.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let n=e.filter(t.pattern.isAffectDepthOfReadingPattern);return t.pattern.convertPatternsToRe(n,this._micromatchOptions)}_filter(e,n,r,i){if(this._isSkippedByDeep(e,n.path)||this._isSkippedSymbolicLink(n))return!1;let a=t.path.removeLeadingDotSegment(n.path);return this._isSkippedByPositivePatterns(a,r)?!1:this._isSkippedByNegativePatterns(a,i)}_isSkippedByDeep(e,t){return this._settings.deep===1/0?!1:this._getEntryLevel(e,t)>=this._settings.deep}_getEntryLevel(e,t){let n=t.split(`/`).length;return e===``?n:n-e.split(`/`).length}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,t){return!this._settings.baseNameMatch&&!t.match(e)}_isSkippedByNegativePatterns(e,n){return!t.pattern.matchAny(e,n)}}})),Fn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default=class{constructor(e,t){this._settings=e,this._micromatchOptions=t,this.index=new Map}getFilter(e,n){let[r,i]=t.pattern.partitionAbsoluteAndRelative(n),a={positive:{all:t.pattern.convertPatternsToRe(e,this._micromatchOptions)},negative:{absolute:t.pattern.convertPatternsToRe(r,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0})),relative:t.pattern.convertPatternsToRe(i,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}))}};return e=>this._filter(e,a)}_filter(e,n){let r=t.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(r)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e))return!1;let i=this._isMatchToPatternsSet(r,n,e.dirent.isDirectory());return this._settings.unique&&i&&this._createIndexRecord(r),i}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isMatchToPatternsSet(e,t,n){return!(!this._isMatchToPatterns(e,t.positive.all,n)||this._isMatchToPatterns(e,t.negative.relative,n)||this._isMatchToAbsoluteNegative(e,t.negative.absolute,n))}_isMatchToAbsoluteNegative(e,n,r){if(n.length===0)return!1;let i=t.path.makeAbsolute(this._settings.cwd,e);return this._isMatchToPatterns(i,n,r)}_isMatchToPatterns(e,n,r){if(n.length===0)return!1;let i=t.pattern.matchAny(e,n);return!i&&r?t.pattern.matchAny(e+`/`,n):i}}})),In=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return t.errno.isEnoentCodeError(e)||this._settings.suppressErrors}}})),Ln=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Y();e.default=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let n=e.path;return this._settings.absolute&&(n=t.path.makeAbsolute(this._settings.cwd,n),n=t.path.unixify(n)),this._settings.markDirectories&&e.dirent.isDirectory()&&(n+=`/`),this._settings.objectMode?Object.assign(Object.assign({},e),{path:n}):n}}})),Rn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`path`),r=Pn(),i=Fn(),a=In(),o=Ln();t.default=class{constructor(e){this._settings=e,this.errorFilter=new a.default(this._settings),this.entryFilter=new i.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new r.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new o.default(this._settings)}_getRootDirectory(e){return n.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let t=e.base===`.`?``:e.base;return{basePath:t,pathSegmentSeparator:`/`,concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(t,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}}})),zn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=jn(),n=Rn();e.default=class extends n.default{constructor(){super(...arguments),this._reader=new t.default(this._settings)}async read(e){let t=this._getRootDirectory(e),n=this._getReaderOptions(e);return(await this.api(t,e,n)).map(e=>n.transform(e))}api(e,t,n){return t.dynamic?this._reader.dynamic(e,n):this._reader.static(t.patterns,n)}}})),Bn=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0});let n=e(`stream`),r=An(),i=Rn();t.default=class extends i.default{constructor(){super(...arguments),this._reader=new r.default(this._settings)}read(e){let t=this._getRootDirectory(e),r=this._getReaderOptions(e),i=this.api(t,e,r),a=new n.Readable({objectMode:!0,read:()=>{}});return i.once(`error`,e=>a.emit(`error`,e)).on(`data`,e=>a.emit(`data`,r.transform(e))).once(`end`,()=>a.emit(`end`)),a.once(`close`,()=>i.destroy()),a}api(e,t,n){return t.dynamic?this._reader.dynamic(e,n):this._reader.static(t.patterns,n)}}})),Vn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=X(),n=On(),r=kn();e.default=class extends r.default{constructor(){super(...arguments),this._walkSync=n.walkSync,this._statSync=t.statSync}dynamic(e,t){return this._walkSync(e,t)}static(e,t){let n=[];for(let r of e){let e=this._getFullEntryPath(r),i=this._getEntry(e,r,t);i===null||!t.entryFilter(i)||n.push(i)}return n}_getEntry(e,t,n){try{let n=this._getStat(e);return this._makeEntry(n,t)}catch(e){if(n.errorFilter(e))return null;throw e}}_getStat(e){return this._statSync(e,this._fsStatSettings)}}})),Hn=n((e=>{Object.defineProperty(e,`__esModule`,{value:!0});let t=Vn(),n=Rn();e.default=class extends n.default{constructor(){super(...arguments),this._reader=new t.default(this._settings)}read(e){let t=this._getRootDirectory(e),n=this._getReaderOptions(e);return this.api(t,e,n).map(n.transform)}api(e,t,n){return t.dynamic?this._reader.dynamic(e,n):this._reader.static(t.patterns,n)}}})),Un=n((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;let n=e(`fs`),r=e(`os`),i=Math.max(r.cpus().length,1);t.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:n.lstat,lstatSync:n.lstatSync,stat:n.stat,statSync:n.statSync,readdir:n.readdir,readdirSync:n.readdirSync},t.default=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,i),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,t){return e===void 0?t:e}_getFileSystemMethods(e={}){return Object.assign(Object.assign({},t.DEFAULT_FILE_SYSTEM_ADAPTER),e)}}})),Wn=t(n(((e,t)=>{let n=tn(),r=zn(),i=Bn(),a=Hn(),o=Un(),s=Y();async function c(e,t){u(e);let n=l(e,r.default,t),i=await Promise.all(n);return s.array.flatten(i)}(function(e){e.glob=e,e.globSync=t,e.globStream=r,e.async=e;function t(e,t){u(e);let n=l(e,a.default,t);return s.array.flatten(n)}e.sync=t;function r(e,t){u(e);let n=l(e,i.default,t);return s.stream.merge(n)}e.stream=r;function c(e,t){u(e);let r=[].concat(e),i=new o.default(t);return n.generate(r,i)}e.generateTasks=c;function d(e,t){u(e);let n=new o.default(t);return s.pattern.isDynamicPattern(e,n)}e.isDynamicPattern=d;function f(e){return u(e),s.path.escape(e)}e.escapePath=f;function p(e){return u(e),s.path.convertPathToPattern(e)}e.convertPathToPattern=p,(function(e){function t(e){return u(e),s.path.escapePosixPath(e)}e.escapePath=t;function n(e){return u(e),s.path.convertPosixPathToPattern(e)}e.convertPathToPattern=n})(e.posix||={}),(function(e){function t(e){return u(e),s.path.escapeWindowsPath(e)}e.escapePath=t;function n(e){return u(e),s.path.convertWindowsPathToPattern(e)}e.convertPathToPattern=n})(e.win32||={})})(c||={});function l(e,t,r){let i=[].concat(e),a=new o.default(r),s=n.generate(i,a),c=new t(a);return s.map(c.read,c)}function u(e){if(![].concat(e).every(e=>s.string.isString(e)&&!s.string.isEmpty(e)))throw TypeError(`Patterns must be a string (non empty) or an array of strings`)}t.exports=c}))(),1);const Z=5e3,Gn=6e4,Kn=`latest`,qn={"darwin-arm64":{arch:`aarch64`,os:`apple-darwin`},"darwin-x64":{arch:`x86_64`,os:`apple-darwin`},"linux-arm64":{arch:`aarch64`,os:`unknown-linux-musl`},"linux-x64":{arch:`x86_64`,os:`unknown-linux-musl`},"win32-x64":{arch:`x86_64`,os:`pc-windows-msvc`},"win32-arm64":{arch:`aarch64`,os:`pc-windows-msvc`}};function Jn(e){try{return S(e).size>1e4}catch{return!1}}function Yn(){return h.platform===`win32`?`rg.exe`:`rg`}function Xn(){let e=m.join(Ze(),Yn());return _(e)&&Jn(e)?e:null}function Zn(e){return e.code===`ENOENT`||e.message?.includes(`ENOENT`)||e.message?.includes(`not found`)}function Qn(e,t){return new Promise((n,r)=>{let i=E(e,t,{stdio:[`ignore`,`pipe`,`pipe`]}),a=``,o=``;i.stdout?.on(`data`,e=>{a+=e.toString()}),i.stderr?.on(`data`,e=>{o+=e.toString()}),i.on(`error`,e=>{r(e)}),i.on(`close`,e=>{n({exitCode:e,stdout:a,stderr:o})})})}async function $n(e,t){let{exitCode:n,stderr:r}=await Qn(`powershell`,[`-command`,`Expand-Archive -Path '${e}' -DestinationPath '${t}' -Force`]);if(n!==0)throw Error(`zip extraction failed (exit ${n}): ${r}\n\nEnsure PowerShell is available on your system.`)}async function er(e,t){let{exitCode:n,stderr:r}=await Qn(`tar`,[`-xzf`,e,`-C`,t]);if(n!==0)throw Error(`tar extraction failed (exit ${n}): ${r}\n\nPlease install 'tar' (e.g., apt install tar, brew install gnu-tar).`)}async function tr(e,t){let n=await u(e,{withFileTypes:!0});for(let r of n){let n=m.join(e,r.name);if(r.isFile()&&r.name===t)return n;if(r.isDirectory()){let e=await tr(n,t);if(e)return e}}return null}let Q=null,nr=null,$=null;async function rr(e){if(e!==`latest`)return e;if($)return $;try{let e=new AbortController,t=setTimeout(()=>e.abort(),3e4);try{let t=await fetch(`https://api.github.com/repos/BurntSushi/ripgrep/releases/latest`,{redirect:`follow`,signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let n=(await t.json())?.tag_name;if(!n)throw Error(`Missing tag_name in GitHub response.`);return $=n.startsWith(`v`)?n.slice(1):n,$}finally{clearTimeout(t)}}catch(e){return console.error(`[goat-chain] Failed to resolve latest ripgrep version: ${e instanceof Error?e.message:e}`),null}}async function ir(e=Kn){let t=`${h.platform}-${h.arch}`,n=qn[t];if(!n)return console.error(`[goat-chain] Unsupported platform for ripgrep: ${t}`),null;let r=Ze(),i=Yn(),a=m.join(r,i);if(_(a)&&Jn(a))return a;let s=await rr(e);if(!s)return null;let{arch:l,os:u}=n,f=h.platform===`win32`?`zip`:`tar.gz`,y=`ripgrep-${s}-${l}-${u}.${f}`,b=`https://github.com/BurntSushi/ripgrep/releases/download/${s}/${y}`;console.log(`[goat-chain] Downloading ripgrep binary...`);let x=null,S=m.join(r,y);try{_(r)||v(r,{recursive:!0});let e=new AbortController,t=setTimeout(()=>e.abort(),12e4);try{let t=await fetch(b,{redirect:`follow`,signal:e.signal});if(!t.ok)throw Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.arrayBuffer();await p(S,D.from(n))}finally{clearTimeout(t)}x=await c(m.join(r,`ripgrep-`)),f===`zip`?await $n(S,x):await er(S,x);let n=await tr(x,i);if(!n)throw Error(`ripgrep binary not found in extracted archive.`);if(await o(n,a),h.platform!==`win32`&&_(a)&&g(a,493),!Jn(a))throw Error(`Downloaded ripgrep binary failed validation.`);return console.log(`[goat-chain] ripgrep binary ready.`),a}catch(e){return console.error(`[goat-chain] Failed to download ripgrep: ${e instanceof Error?e.message:e}`),null}finally{await d(S,{force:!0}).catch(()=>{}),x&&await d(x,{recursive:!0,force:!0}).catch(()=>{})}}async function ar(e=Kn){return Xn()||ir(e)}async function or(){return Q!==null&&_(Q)?Q:nr||(nr=(async()=>{let e=Xn();if(e)return Q=e,e;let t=await ar();return t?(Q=t,t):null})(),nr)}var sr=class extends W{name=`Grep`;description=`A powerful search tool built on ripgrep.
|
|
214
|
+
|
|
215
|
+
Usage notes:
|
|
216
|
+
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
217
|
+
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
|
|
218
|
+
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
|
|
219
|
+
- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
|
|
220
|
+
- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true
|
|
221
|
+
- If ripgrep is not available, this tool falls back to a JS-based search (slower). You can opt into downloading a ripgrep binary via the GrepTool constructor option \`allowDownload: true\`.`;parameters={type:`object`,properties:{pattern:{type:`string`,description:`The regular expression pattern to search for in file contents`},path:{type:`string`,description:`File or directory to search in. Defaults to current working directory.`},glob:{type:`string`,description:`Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")`},output_mode:{type:`string`,enum:[`content`,`files_with_matches`,`count`],description:`Output mode: "content" shows matching lines, "files_with_matches" shows file paths (default), "count" shows match counts.`},"-B":{type:`number`,description:`Number of lines to show before each match. Requires output_mode: "content".`},"-A":{type:`number`,description:`Number of lines to show after each match. Requires output_mode: "content".`},"-C":{type:`number`,description:`Number of lines to show before and after each match. Requires output_mode: "content".`},"-n":{type:`boolean`,description:`Show line numbers in output. Requires output_mode: "content". Defaults to true.`},"-i":{type:`boolean`,description:`Case insensitive search`},type:{type:`string`,description:`File type to search (e.g., js, py, rust, go, java). More efficient than glob for standard file types.`},head_limit:{type:`number`,description:`Limit output to first N lines/entries. Defaults to 0 (unlimited).`},offset:{type:`number`,description:`Skip first N lines/entries before applying head_limit. Defaults to 0.`},multiline:{type:`boolean`,description:`Enable multiline mode where . matches newlines and patterns can span lines. Default: false.`}},required:[`pattern`]};cwd;rgPath;allowDownload;constructor(e){super(),this.cwd=e?.cwd??h.cwd(),this.rgPath=e?.rgPath??`rg`,this.allowDownload=e?.allowDownload===!0}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let t=this.validateArgs(e),n=this.buildRgArgs(t),r=await this.runRipgrep(n,t),i=r.output||`[No matches found]`;return r.timedOut&&(i+=`
|
|
222
|
+
[Search timed out]`),r.matchCount!==void 0&&(i=`Found ${r.matchCount} match${r.matchCount===1?``:`es`}\n${i}`),{content:[{type:`text`,text:i}],structuredContent:r,isError:r.exitCode!==null&&r.exitCode!==0&&r.exitCode!==1}}validateArgs(e){let t=e.pattern;if(typeof t!=`string`||!t.trim())throw Error(`Pattern is required and must be a non-empty string`);let n={pattern:t.trim()};if(e.path!==void 0&&e.path!==null&&e.path!==``){if(typeof e.path!=`string`)throw TypeError(`Path must be a string`);n.path=e.path.trim()}if(e.glob!==void 0&&e.glob!==null&&e.glob!==``){if(typeof e.glob!=`string`)throw TypeError(`Glob must be a string`);n.glob=e.glob.trim()}if(e.type!==void 0&&e.type!==null&&e.type!==``){if(typeof e.type!=`string`)throw TypeError(`Type must be a string`);n.type=e.type.trim()}if(e.output_mode!==void 0){let t=[`content`,`files_with_matches`,`count`];if(!t.includes(e.output_mode))throw Error(`Invalid output_mode. Must be one of: ${t.join(`, `)}`);n.output_mode=e.output_mode}for(let t of[`-B`,`-A`,`-C`,`head_limit`,`offset`])if(e[t]!==void 0&&e[t]!==null){if(typeof e[t]!=`number`)throw TypeError(`${t} must be a number`);n[t]=Math.max(0,Math.floor(e[t]))}for(let t of[`-n`,`-i`,`multiline`])e[t]!==void 0&&e[t]!==null&&(n[t]=!!e[t]);return n}buildRgArgs(e){let t=[],n=e.output_mode??`files_with_matches`;return n===`files_with_matches`?t.push(`-l`):n===`count`&&t.push(`-c`),n===`content`&&(e[`-n`]!==!1&&t.push(`-n`),e[`-B`]!==void 0&&e[`-B`]>0&&t.push(`-B`,String(e[`-B`])),e[`-A`]!==void 0&&e[`-A`]>0&&t.push(`-A`,String(e[`-A`])),e[`-C`]!==void 0&&e[`-C`]>0&&t.push(`-C`,String(e[`-C`]))),e[`-i`]&&t.push(`-i`),e.multiline&&t.push(`-U`,`--multiline-dotall`),e.type&&t.push(`--type`,e.type),e.glob&&t.push(`--glob`,e.glob),t.push(`--color`,`never`),t.push(`--no-heading`),t.push(`--regexp`,e.pattern),e.path&&t.push(`--`,e.path),t}runRipgrep(e,t,n=!1){return new Promise(r=>{let i=``,a=!1,o=!1,s=!1,c=null,l=!1;if(this.rgPath===`rg`){let e=Xn();e&&(this.rgPath=e)}let u=E(this.rgPath,e,{cwd:this.cwd,env:h.env,stdio:[`ignore`,`pipe`,`pipe`]}),d=e=>{s||(s=!0,r(e))},f=setTimeout(()=>{a=!0,u.kill(`SIGTERM`),setTimeout(()=>{u.killed||u.kill(`SIGKILL`)},5e3)},Gn);u.stdout?.on(`data`,e=>{let t=e.toString();i.length+t.length>Z?(i+=t.slice(0,Z-i.length),o=!0,clearTimeout(f),u.kill(`SIGTERM`)):i+=t}),u.stderr?.on(`data`,e=>{let t=e.toString();t.includes(`error:`)&&(i+=`\n[stderr]: ${t}`)}),u.on(`close`,e=>{if(s)return;if(clearTimeout(f),c||e!==null&&e<0){l||this.runJsSearch(t).then(d);return}let n=i;if(t.offset||t.head_limit){let e=i.split(`
|
|
223
|
+
`).filter(e=>e.trim()),r=t.offset??0,a=t.head_limit??e.length;n=e.slice(r,r+a).join(`
|
|
224
|
+
`)}let r;t.output_mode===`count`&&(r=n.split(`
|
|
225
|
+
`).filter(e=>e.trim()).reduce((e,t)=>{let n=t.match(/:(\d+)$/);return e+(n?Number.parseInt(n[1],10):0)},0)),d({exitCode:e,output:o?`${n}\n... [output truncated]`:n,truncated:o,timedOut:a,matchCount:r})}),u.on(`error`,r=>{if(s)return;c=r,l=!0,clearTimeout(f);let i=r;if(this.allowDownload&&!n&&Zn(i)){(async()=>{try{let n=await or();if(n){this.rgPath=n,d(await this.runRipgrep(e,t,!0));return}}catch{}d(await this.runJsSearch(t))})();return}this.runJsSearch(t).then(d)})})}async runJsSearch(e){let t=!1,n=!1,r=setTimeout(()=>{t=!0},Gn),i=e.output_mode??`files_with_matches`,a=e[`-B`]??0,o=e[`-A`]??0,s=e[`-C`]??0;s>0&&(a=Math.max(a,s),o=Math.max(o,s));let c=!!e[`-i`],u=!!e.multiline,d=`${c?`i`:``}${u?`sm`:``}`,p=null,h=null;try{u?h=new RegExp(e.pattern,`${d}g`):p=new RegExp(e.pattern,d)}catch(e){return clearTimeout(r),{exitCode:2,engine:`js`,output:`Invalid regex pattern: ${e.message}`,truncated:!1,timedOut:!1}}let g=e.path??`.`,_=m.isAbsolute(g)?g:m.resolve(this.cwd,g),v=m.isAbsolute(g),y;try{y=await f(_)}catch{return clearTimeout(r),{exitCode:2,engine:`js`,output:`Search path not found: ${g}`,truncated:!1,timedOut:!1}}let b=[],x=Wn.default.default??Wn.default;if(typeof x!=`function`)return clearTimeout(r),this.runSystemGrep(e);let S=_;if(y.isFile())b=[_],S=m.dirname(_);else if(y.isDirectory()){S=_;try{b=await x(`**/*`,{cwd:S,absolute:!0,onlyFiles:!0,dot:!0})}catch{return clearTimeout(r),this.runSystemGrep(e)}}else return clearTimeout(r),{exitCode:2,engine:`js`,output:`Search path not found: ${g}`,truncated:!1,timedOut:!1};b.sort();let C=[],w=!1,T=0,E=e=>{let t=e.length+1;return T+t>Z?(n=!0,!1):(C.push(e),T+=t,!0)},D={js:[`.js`,`.cjs`,`.mjs`],jsx:[`.jsx`],ts:[`.ts`,`.tsx`,`.d.ts`],tsx:[`.tsx`],json:[`.json`],md:[`.md`,`.markdown`],py:[`.py`],go:[`.go`],rs:[`.rs`],java:[`.java`],c:[`.c`,`.h`],cpp:[`.cc`,`.cpp`,`.cxx`,`.hpp`,`.hh`,`.hxx`,`.h`]},k=t=>{if(!e.type)return!0;let n=e.type.toLowerCase(),r=D[n]??[n.startsWith(`.`)?n:`.${n}`],i=t.toLowerCase();return r.some(e=>i.endsWith(e))},A=e=>v?e:m.relative(this.cwd,e)||m.basename(e),j=e.glob,M=O.isMatch,N=i===`content`?e[`-n`]!==!1:!1;for(let e of b){if(t)break;if(T>=Z){n=!0;break}if(!k(e)||j&&M&&!M(m.basename(e),j))continue;let r=``;try{r=await l(e,`utf-8`)}catch{continue}if(!r||r.includes(`\0`))continue;let s=A(e);if(!u){let e=r.split(/\r?\n/),t=new Set;for(let n=0;n<e.length;n++)p.test(e[n])&&t.add(n+1);if(t.size===0)continue;w=!0;let n=t.size;if(i===`files_with_matches`){if(!E(s))break;continue}if(i===`count`){if(!E(`${s}:${n}`))break;continue}let c=new Set(t);if(a>0||o>0){let n=e.length;for(let e of t){let t=Math.max(1,e-a),r=Math.min(n,e+o);for(let e=t;e<=r;e++)c.add(e)}}let l=!1;for(let t of Array.from(c).sort((e,t)=>e-t)){let n=e[t-1]??``;if(!E(N?`${s}:${t}:${n}`:`${s}:${n}`)){l=!0;break}}if(l)break;continue}let c=r.split(/\r?\n/),d=[0];for(let e=0;e<r.length;e++)r[e]===`
|
|
226
|
+
`&&d.push(e+1);let f=e=>{let t=0,n=d.length-1;for(;t<=n;){let r=Math.floor((t+n)/2);d[r]<=e?t=r+1:n=r-1}return Math.max(n+1,1)};h.lastIndex=0;let g=new Set;for(let e of r.matchAll(h)){let t=e.index??0,n=e[0]?.length??0,r=Math.max(t,t+n-1),i=f(t),a=f(r);for(let e=i;e<=a;e++)g.add(e)}if(g.size===0)continue;w=!0;let _=g.size;if(i===`files_with_matches`){if(!E(s))break;continue}if(i===`count`){if(!E(`${s}:${_}`))break;continue}let v=new Set(g);if(a>0||o>0){let e=c.length;for(let t of g){let n=Math.max(1,t-a),r=Math.min(e,t+o);for(let e=n;e<=r;e++)v.add(e)}}let y=!1;for(let e of Array.from(v).sort((e,t)=>e-t)){let t=c[e-1]??``;if(!E(N?`${s}:${e}:${t}`:`${s}:${t}`)){y=!0;break}}if(y)break}clearTimeout(r);let P=C;if(e.offset||e.head_limit){let t=C.filter(e=>e.trim()),n=e.offset??0,r=e.head_limit??t.length;P=t.slice(n,n+r)}let F=P.join(`
|
|
227
|
+
`);F.length>Z&&(F=F.slice(0,Z),n=!0);let ee;return i===`count`&&(ee=F.split(`
|
|
228
|
+
`).filter(e=>e.trim()).reduce((e,t)=>{let n=t.split(`:`).pop(),r=n?Number.parseInt(n,10):NaN;return e+(Number.isFinite(r)?r:0)},0)),{exitCode:w?0:1,engine:`js`,output:n?`${F}\n... [output truncated]`:F,truncated:n,timedOut:t,matchCount:ee}}runSystemGrep(e){return new Promise(t=>{let n=``,r=!1,i=!1,a=[];a.push(`-R`,`-E`,`-I`);let o=e.output_mode??`files_with_matches`;o===`files_with_matches`?a.push(`-l`):o===`count`?a.push(`-c`):a.push(`-n`),o===`content`&&(e[`-B`]!==void 0&&e[`-B`]>0&&a.push(`-B`,String(e[`-B`])),e[`-A`]!==void 0&&e[`-A`]>0&&a.push(`-A`,String(e[`-A`])),e[`-C`]!==void 0&&e[`-C`]>0&&a.push(`-C`,String(e[`-C`]))),e[`-i`]&&a.push(`-i`),a.push(e.pattern),e.path?a.push(e.path):a.push(`.`);let s=E(`grep`,a,{cwd:this.cwd,env:h.env,stdio:[`ignore`,`pipe`,`pipe`]}),c=setTimeout(()=>{r=!0,s.kill(`SIGTERM`),setTimeout(()=>{s.killed||s.kill(`SIGKILL`)},5e3)},Gn);s.stdout?.on(`data`,e=>{let t=e.toString();n.length+t.length>Z?(n+=t.slice(0,Z-n.length),i=!0,clearTimeout(c),s.kill(`SIGTERM`)):n+=t}),s.stderr?.on(`data`,e=>{let t=e.toString();t.trim()&&(n+=`\n[stderr]: ${t}`)}),s.on(`close`,a=>{clearTimeout(c);let s=n;if(e.offset||e.head_limit){let t=n.split(`
|
|
229
|
+
`).filter(e=>e.trim()),r=e.offset??0,i=e.head_limit??t.length;s=t.slice(r,r+i).join(`
|
|
230
|
+
`)}let l;o===`count`&&(l=s.split(`
|
|
231
|
+
`).filter(e=>e.trim()).reduce((e,t)=>{let n=t.split(`:`).pop(),r=n?Number.parseInt(n,10):NaN;return e+(Number.isFinite(r)?r:0)},0)),t({exitCode:a,engine:`grep`,output:i?`${s}\n... [output truncated]`:s,truncated:i,timedOut:r,matchCount:l})}),s.on(`error`,e=>{clearTimeout(c),t({exitCode:1,engine:`grep`,output:`Failed to execute grep: ${e.message}.`,truncated:!1,timedOut:!1})})})}};const cr=2e3,lr=2e3,ur=new Set(`.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.svg,.pdf,.zip,.tar,.gz,.rar,.7z,.exe,.dll,.so,.dylib,.mp3,.mp4,.avi,.mov,.wav,.woff,.woff2,.ttf,.eot`.split(`,`)),dr={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".svg":`image/svg+xml`,".pdf":`application/pdf`,".json":`application/json`,".js":`text/javascript`,".ts":`text/typescript`,".html":`text/html`,".css":`text/css`,".md":`text/markdown`,".txt":`text/plain`};var fr=class extends W{name=`Read`;_cwd;_allowedDirectory;constructor(e){super(),this._cwd=e?.cwd??h.cwd(),this._allowedDirectory=e?.allowedDirectory}get description(){let e=`Reads a file from the local filesystem. You can access any file directly by using this tool.
|
|
232
|
+
|
|
233
|
+
Usage notes:
|
|
234
|
+
- The file_path parameter must be an absolute path, not a relative path
|
|
235
|
+
- By default, it reads up to ${cr} lines starting from the beginning
|
|
236
|
+
- You can optionally specify a line offset and limit for large files
|
|
237
|
+
- Any lines longer than ${lr} characters will be truncated
|
|
238
|
+
- Results are returned with line numbers (like cat -n format)
|
|
239
|
+
- Can read images (PNG, JPG, etc.), PDFs, and Jupyter notebooks
|
|
240
|
+
- You can call multiple tools in parallel to read multiple files at once`;return this._allowedDirectory?`${e}
|
|
241
|
+
- IMPORTANT: Files can ONLY be read from within: ${this._allowedDirectory}
|
|
242
|
+
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`:e}get parameters(){return{type:`object`,properties:{file_path:{type:`string`,description:this._allowedDirectory?`The absolute path to the file to read (must be within ${this._allowedDirectory})`:`The absolute path to the file to read`},offset:{type:`number`,description:`The line number to start reading from (1-based). Only provide if the file is too large to read at once.`},limit:{type:`number`,description:`The number of lines to read. Only provide if the file is too large to read at once.`}},required:[`file_path`]}}setCwd(e){this._cwd=e}getCwd(){return this._cwd}setAllowedDirectory(e){this._allowedDirectory=e}getAllowedDirectory(){return this._allowedDirectory}async execute(e){let{file_path:t,offset:n,limit:r}=this.validateArgs(e),i=m.isAbsolute(t)?t:m.resolve(this._cwd,t);if(this._allowedDirectory){let e=m.resolve(this._allowedDirectory),n=m.resolve(i);if(!n.startsWith(e+m.sep)&&n!==e)return U(`Access denied: ${t}\nFiles can only be read from within: ${this._allowedDirectory}\nPlease use a path like: ${this._allowedDirectory}/<filename>`)}let a;try{a=await f(i)}catch(e){if(e.code===`ENOENT`)return U(`File not found: ${i}`);throw e}if(a.isDirectory())return U(`Path is a directory, not a file: ${i}. Use ls command via Bash tool to read directories.`);let o=m.extname(i).toLowerCase(),s=ur.has(o),c=dr[o],u;if(s){if(u=await this.handleBinaryFile(i,a.size,c),c?.startsWith(`image/`))return{content:[{type:`image`,data:(await l(i)).toString(`base64`),mimeType:c}],structuredContent:u}}else u=o===`.ipynb`?await this.handleJupyterNotebook(i,a.size,n,r):await this.handleTextFile(i,a.size,n,r);return{content:[{type:`text`,text:u.content}],structuredContent:u}}validateArgs(e){let t=e.file_path;if(typeof t!=`string`||!t.trim())throw Error(`file_path is required and must be a non-empty string`);let n={file_path:t.trim()};if(e.offset!==void 0&&e.offset!==null){if(typeof e.offset!=`number`)throw TypeError(`offset must be a number`);n.offset=Math.max(1,Math.floor(e.offset))}if(e.limit!==void 0&&e.limit!==null){if(typeof e.limit!=`number`)throw TypeError(`limit must be a number`);n.limit=Math.max(1,Math.floor(e.limit))}return n}async handleBinaryFile(e,t,n){let r=(await l(e)).toString(`base64`);return{content:`[Binary file: ${m.basename(e)}]\nSize: ${this.formatSize(t)}\nMIME type: ${n??`unknown`}\nBase64 encoded content:\n${r}`,totalLines:1,linesReturned:1,startLine:1,truncated:!1,fileSize:t,isBinary:!0,mimeType:n}}async handleJupyterNotebook(e,t,n,r){let i=await l(e,`utf-8`),a;try{a=JSON.parse(i)}catch{throw Error(`Invalid Jupyter notebook format: ${e}`)}let o=a.cells||[],s=[];for(let e=0;e<o.length;e++){let t=o[e],n=e+1,r=t.cell_type||`unknown`;s.push(`--- Cell ${n} (${r}) ---`);let i=Array.isArray(t.source)?t.source.join(``):t.source||``;if(s.push(...i.split(`
|
|
243
|
+
`)),t.outputs&&t.outputs.length>0){s.push(`--- Output ---`);for(let e of t.outputs)if(e.text){let t=Array.isArray(e.text)?e.text.join(``):e.text;s.push(...t.split(`
|
|
244
|
+
`))}else if(e.data&&e.data[`text/plain`]){let t=Array.isArray(e.data[`text/plain`])?e.data[`text/plain`].join(``):e.data[`text/plain`];s.push(...t.split(`
|
|
245
|
+
`))}}s.push(``)}return this.formatOutput(s,t,n,r)}async handleTextFile(e,t,n,r){let i=await l(e,`utf-8`);if(i.length===0)return{content:`[File is empty]`,totalLines:0,linesReturned:0,startLine:1,truncated:!1,fileSize:t,isBinary:!1};let a=i.split(`
|
|
246
|
+
`);return this.formatOutput(a,t,n,r)}formatOutput(e,t,n,r){let i=e.length,a=n??1,o=r??cr,s=a-1,c=Math.min(s+o,i),l=e.slice(s,c),u=!1;return{content:l.map((e,t)=>{let n=a+t,r=String(n).padStart(6,` `),i=e;return e.length>lr&&(i=`${e.slice(0,lr)}... [truncated]`,u=!0),`${r}|${i}`}).join(`
|
|
247
|
+
`),totalLines:i,linesReturned:l.length,startLine:a,truncated:u,fileSize:t,isBinary:!1}}formatSize(e){let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n.toFixed(r===0?0:2)} ${t[r]}`}},pr=class extends W{name=`TodoWrite`;riskLevel=`low`;description=`Use this tool to create and manage a structured task list for your current coding session.
|
|
248
|
+
|
|
249
|
+
When to use:
|
|
250
|
+
- Complex multi-step tasks (3+ steps)
|
|
251
|
+
- Non-trivial tasks requiring careful planning
|
|
252
|
+
- User explicitly requests todo list
|
|
253
|
+
- User provides multiple tasks
|
|
254
|
+
- After receiving new instructions
|
|
255
|
+
|
|
256
|
+
When NOT to use:
|
|
257
|
+
- Single, straightforward task
|
|
258
|
+
- Trivial tasks (< 3 steps)
|
|
259
|
+
- Purely conversational/informational requests
|
|
260
|
+
|
|
261
|
+
Task States:
|
|
262
|
+
- pending: Task not yet started
|
|
263
|
+
- in_progress: Currently working on (limit to ONE at a time)
|
|
264
|
+
- completed: Task finished successfully
|
|
265
|
+
|
|
266
|
+
Task descriptions have two forms:
|
|
267
|
+
- content: Imperative form (e.g., "Run tests")
|
|
268
|
+
- activeForm: Present continuous form (e.g., "Running tests")`;parameters={type:`object`,properties:{todos:{type:`array`,items:{type:`object`,properties:{content:{type:`string`,minLength:1,description:`The task description in imperative form (e.g., "Run tests")`},status:{type:`string`,enum:[`pending`,`in_progress`,`completed`],description:`Current status of the task`},activeForm:{type:`string`,minLength:1,description:`The task description in present continuous form (e.g., "Running tests")`}},required:[`content`,`status`,`activeForm`]},description:`The updated todo list`}},required:[`todos`]};todos=[];onChangeCallback;onChange(e){this.onChangeCallback=e}getTodos(){return[...this.todos]}clear(){this.todos=[],this.onChangeCallback?.(this.todos)}async execute(e){let{todos:t}=this.validateArgs(e);this.todos=t,this.onChangeCallback?.(this.todos);let n=t.filter(e=>e.status===`pending`).length,r=t.filter(e=>e.status===`in_progress`).length,i=t.filter(e=>e.status===`completed`).length,a=[];i>0&&a.push(`${i} completed`),r>0&&a.push(`${r} in progress`),n>0&&a.push(`${n} pending`);let o=a.length>0?`Todo list updated: ${a.join(`, `)}`:`Todo list is empty`,s={success:!0,todos:this.todos,pendingCount:n,inProgressCount:r,completedCount:i,message:o};return{content:[{type:`text`,text:o}],structuredContent:s}}validateArgs(e){let t=e.todos;if(!Array.isArray(t))throw TypeError(`todos is required and must be an array`);let n=[],r=[`pending`,`in_progress`,`completed`];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i!=`object`||!i)throw TypeError(`todos[${e}] must be an object`);let{content:a,status:o,activeForm:s}=i;if(typeof a!=`string`||!a.trim())throw Error(`todos[${e}].content is required and must be a non-empty string`);if(typeof o!=`string`||!r.includes(o))throw Error(`todos[${e}].status must be one of: ${r.join(`, `)}`);if(typeof s!=`string`||!s.trim())throw Error(`todos[${e}].activeForm is required and must be a non-empty string`);n.push({content:a.trim(),status:o,activeForm:s.trim()})}let i=n.filter(e=>e.status===`in_progress`);return i.length>1&&console.warn(`Warning: ${i.length} tasks are in_progress. Ideally only one task should be in_progress at a time.`),{todos:n}}},mr=class extends W{name=`WebSearch`;riskLevel=`medium`;description=`Allows the agent to search the web and use the results to inform responses.
|
|
269
|
+
|
|
270
|
+
Usage notes:
|
|
271
|
+
- Provides up-to-date information for current events and recent data
|
|
272
|
+
- Returns search results with titles, links, and snippets
|
|
273
|
+
- Use this tool for accessing information beyond the knowledge cutoff
|
|
274
|
+
- After answering, include a "Sources:" section with relevant URLs as markdown hyperlinks`;parameters={type:`object`,properties:{query:{type:`string`,minLength:2,description:`The search query to use`}},required:[`query`]};apiKey;apiEndpoint;numResults;constructor(e){super(),this.apiKey=e?.apiKey??h.env.SERPER_API_KEY??``,this.apiEndpoint=e?.apiEndpoint??`https://google.serper.dev/search?format=json`,this.numResults=e?.numResults??10}setApiKey(e){this.apiKey=e}async execute(e){let{query:t}=this.validateArgs(e);if(!this.apiKey)return U(`Serper API key is not configured. Set SERPER_API_KEY environment variable or pass apiKey in constructor.`);try{let e=await fetch(this.apiEndpoint,{method:`POST`,headers:{"X-API-KEY":this.apiKey,"Content-Type":`application/json`},body:JSON.stringify({q:t,num:this.numResults})});if(!e.ok){let t=await e.text();return U(`Serper API error (${e.status}): ${t}`)}let n=((await e.json()).organic??[]).map((e,t)=>({title:e.title,link:e.link,snippet:e.snippet,position:e.position??t+1})),r=this.formatMarkdown(t,n),i={success:!0,query:t,results:n,totalResults:n.length,markdown:r};return{content:[{type:`text`,text:r}],structuredContent:i}}catch(e){return U(`Failed to execute search: ${e instanceof Error?e.message:String(e)}`)}}validateArgs(e){let t=e.query;if(typeof t!=`string`||t.trim().length<2)throw Error(`query is required and must be at least 2 characters`);return{query:t.trim()}}formatMarkdown(e,t){if(t.length===0)return`No results found for: "${e}"`;let n=[`## Search Results for: "${e}"`,``];for(let e of t)n.push(`### ${e.position}. [${e.title}](${e.link})`),n.push(``),n.push(e.snippet),n.push(``);n.push(`---`),n.push(``),n.push(`**Sources:**`);for(let e of t)n.push(`- [${e.title}](${e.link})`);return n.join(`
|
|
275
|
+
`)}},hr=class extends W{name=`Write`;riskLevel=`high`;_cwd;_allowedDirectory;constructor(e){super(),this._cwd=e?.cwd??h.cwd(),this._allowedDirectory=e?.allowedDirectory}get description(){let e=`Writes a file to the local filesystem.
|
|
276
|
+
|
|
277
|
+
Usage notes:
|
|
278
|
+
- This tool will overwrite the existing file if there is one at the provided path
|
|
279
|
+
- Parent directories will be created automatically if they don't exist
|
|
280
|
+
- ALWAYS prefer editing existing files over writing new ones
|
|
281
|
+
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested`;return this._allowedDirectory?`${e}
|
|
282
|
+
- IMPORTANT: Files can ONLY be written within: ${this._allowedDirectory}
|
|
283
|
+
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`:e}get parameters(){return{type:`object`,properties:{file_path:{type:`string`,description:this._allowedDirectory?`The absolute path to the file to write (must be within ${this._allowedDirectory})`:`The absolute path to the file to write (must be absolute, not relative)`},content:{type:`string`,description:`The content to write to the file`}},required:[`file_path`,`content`]}}setCwd(e){this._cwd=e}getCwd(){return this._cwd}setAllowedDirectory(e){this._allowedDirectory=e}getAllowedDirectory(){return this._allowedDirectory}async execute(e){let{file_path:t,content:n}=this.validateArgs(e),r=m.isAbsolute(t)?t:m.resolve(this._cwd,t);if(this._allowedDirectory){let e=m.resolve(this._allowedDirectory),n=m.resolve(r);if(!n.startsWith(e+m.sep)&&n!==e)return U(`Access denied: ${t}\nFiles can only be written within: ${this._allowedDirectory}\nPlease use a path like: ${this._allowedDirectory}/<filename>`)}let i=!1;try{if((await f(r)).isDirectory())return U(`Path is a directory, not a file: ${r}`);i=!0}catch(e){if(e.code!==`ENOENT`)throw e}await s(m.dirname(r),{recursive:!0}),await p(r,n,`utf-8`);let a=Buffer.byteLength(n,`utf-8`),o={success:!0,filePath:r,bytesWritten:a,overwritten:i,message:i?`Successfully overwrote ${m.basename(r)} (${this.formatSize(a)})`:`Successfully created ${m.basename(r)} (${this.formatSize(a)})`};return{content:[{type:`text`,text:o.message}],structuredContent:o}}validateArgs(e){let t=e.file_path,n=e.content;if(typeof t!=`string`||!t.trim())throw Error(`file_path is required and must be a non-empty string`);if(typeof n!=`string`)throw TypeError(`content is required and must be a string`);return{file_path:t.trim(),content:n}}formatSize(e){let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n.toFixed(r===0?0:2)} ${t[r]}`}};const gr=[`Bash`,`Edit`,`Write`,`AstGrepReplace`],_r=[`<system-reminder>`,`# Plan Mode Active`,``,`You are in READ-ONLY planning mode. You MUST NOT make any file edits or system changes.`,`Do not use Write, Edit, or any bash commands that modify files. Only read, search, and analyze.`,`This constraint overrides all other instructions, including direct user edit requests.`,``,`## Your Responsibility`,``,`Research the codebase and construct a well-formed plan to accomplish the user's goal.`,`Ask clarifying questions when facing ambiguities or technical tradeoffs.`,``,`## Using Tools`,``,`- Use AskUserQuestion when you need to clarify requirements or choose between valid approaches`,`- Use TodoWrite to create an execution plan with 3-8 steps (all status: pending)`,`- Use read-only tools (Read, Grep, Glob, AstGrepSearch) to explore the codebase`,``,`## Plan Creation`,``,`After exploration, create an execution plan using TodoWrite. Do NOT implement yet.`,`Present your plan and wait for user approval before any execution.`,`</system-reminder>`].join(`
|
|
284
|
+
`);function vr(e){let t=e?.instruction??_r,n=e?.insertEveryIteration??!0,r=e?.name??`plan-mode`,i=async(e,i)=>{let a={...e.metadata,planMode:!0,planModeMiddleware:r};if(!(n||e.iteration===0))return i({...e,metadata:a});let o=re(e.messages,t);return i({...e,metadata:a,messages:o})};return i.__middlewareName=r,i.__createTools=()=>[new Ot],i.__getBlockedTools=e=>e.metadata?.planMode?[...gr]:[],i}var yr=class{tools=new Map;register(e){if(this.tools.has(e.name))throw Error(`Tool "${e.name}" already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}list(){return Array.from(this.tools.values())}has(e){return this.tools.has(e)}get size(){return this.tools.size}toOpenAIFormat(){return this.list().map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}};export{be as A,L as B,Pe as C,V as D,we as E,_e as F,k as H,ge as I,he as L,R as M,ve as N,Se as O,B as P,ae as R,H as S,Oe as T,A as V,We as _,pr as a,Ve as b,Mt as c,Ct as d,xt as f,Ge as g,U as h,mr as i,ye as j,xe as k,Dt as l,W as m,vr as n,fr as o,Ke as p,hr as r,sr as s,yr as t,Et as u,Ue as v,ke as w,Be as x,He as y,re as z};
|